blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 117 | path stringlengths 3 268 | src_encoding stringclasses 34
values | length_bytes int64 6 4.23M | score float64 2.52 5.19 | int_score int64 3 5 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | text stringlengths 13 4.23M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
f70fcec15bdb57ff00aba5d73904da1c95202991 | C++ | Wornairz/UniCT | /Prog2/esercizi/logaritmo_decimale.cpp | UTF-8 | 475 | 3.484375 | 3 | [] | no_license | #include <math.h>
#include <iostream>
using namespace std;
double logaritmo(double base, double argomento)
{
double esponente = 1, logaritmo = 0;
while(argomento > 1)
{
if(argomento >= base)
{
logaritmo += esponente;
argomento /= base;
}
else
{
esponente /= 2;
base = sqrt(base);
}
}
return logaritmo;
}
int main()
{
cout << logaritmo(3, 57) << endl;
}
| true |
bfb091884cbde63b019f99c9be6522c3af81de26 | C++ | csevier/LunaEXR | /Luna/luna_ray_tracer/src/Ray.cpp | UTF-8 | 431 | 2.640625 | 3 | [] | no_license | #include "Ray.hpp"
namespace luna
{
Ray::Ray(const Vector3d& origin, const Vector3d& direction): mOrigin(origin), mDirection(direction)
{
}
const Vector3d& Ray::Origin() const
{
return mOrigin;
}
const Vector3d& Ray::Direction() const
{
return mDirection;
}
Vector3d Ray::PointAtParameter(float param) const
{
return mOrigin + (mDirection * param);
}
}
| true |
aa8156a58d786f0de8b25a76a98aec8ab4b7ff30 | C++ | man-of-steele21/Final | /Problem1.cpp | UTF-8 | 1,200 | 2.6875 | 3 | [] | no_license | #include <iostream>
#include <math.h>
#include <iomanip>
#include <unistd.h>
#include <stdlib.h>
#include <gsl/gsl_rng.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#define _USE_MATH_DEFINES
using namespace std;
int main(int argc, char **argv)
{
if (argc != 2)
{
cout << "Invalid number of arguments entered" << endl;
exit(1);
}
int count = 0;
float x, y, z, dev, err, res;
gsl_rng * myrng;
int trials = atoi(argv[1]);
const gsl_rng_type * rngtype;
gsl_rng_env_setup();
rngtype = gsl_rng_default;
myrng = gsl_rng_alloc (rngtype);
gsl_rng_set(myrng, (getpid() * 1000)); // seeding with PID*1000 for better accuracy
for (int i = 0; i < trials; i++)
{
x = gsl_rng_uniform (myrng);
y = gsl_rng_uniform (myrng);
z = sqrt(pow(x, 2) + pow(y, 2));
if (z < 1)
count++;
}
gsl_rng_free (myrng);
res = 4*(float)count/(float)trials;
dev = fabs(res-M_PI);
err = dev/M_PI*100;
cout << "Result: " << fixed << setprecision(5) << res << endl;
cout << "Deviation: " << fixed << setprecision(5) << dev << endl;
cout << "Percent error: " << fixed << setprecision(5) << err << endl;
return 0;
}
| true |
1a698c18339b1ed314ebb6148174a86cfff8155f | C++ | nishantvishwamitra/leetcode | /lcp.cpp | UTF-8 | 641 | 3.234375 | 3 | [] | no_license | // Better solution under ExploringRecursion
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.size() == 0) {
return "";
}
std::string lcp = strs[0];
std::string temp = "";
for(int i = 1 ; i < strs.size() ; ++i) {
std::string::iterator it = strs[i].begin();
std::string::iterator lcpIt = lcp.begin();
while(it != strs[i].end() || lcpIt != lcp.end()) {
if(*it == *lcpIt) {
temp = temp + *it;
} else {
lcp = temp;
break;
}
++it;
++lcpIt;
}
temp = "";
}
return lcp;
}
};
| true |
3d861a3fbac511d81df3042717189e05266a24ef | C++ | byhj/OJ-PAT | /src/Basic/1021. 个位数统计 (15).cpp | UTF-8 | 309 | 2.984375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string str;
while (cin >> str)
{
vector<int> vi(10);
for (const auto &c : str)
++vi[c - '0'];
for (int i = 0; i != vi.size(); ++i)
if (vi[i] != 0)
cout << i << ":" << vi[i] << endl;
}
return 0;
} | true |
23614a5f143195fa68d4c80829442eb029e71b95 | C++ | aceiro/atm_2019 | /CI-APP/Src/FormSelect.cpp | UTF-8 | 4,677 | 3.265625 | 3 | [] | no_license | // Declaração das Bibliotecas internas do C++
#include <iostream>
#include <string>
#include <iomanip> // Biblioteca interna do C++ para trabalhar com alinhamento (width, right, etc)
// Declaração das Bibliotecas internas do Projeto (declação das Classes)
#include "../Include/Form.hpp"
// Uso refinado do Escopo STD
using std::cout;
using std::cin;
using std::getline;
using std::endl;
using std::string;
using std::setw; // setw() é uma função para alinhar a largura
using std::left; // Alinhar a esquerda
void Form::formSelect() {
string idCI;
int escape = 0;
if (!Data.empty()) {
// Imprimindo todas os Registros de CI
displayRecordsReport();
do {
// Escolhendo qual será o registro a ser retornado, para ver recuperar todos os dados
cout << endl << "CONSULTAR ID. (escolha entre os registros acima): ";
getline(cin, idCI);
// Váriavel de Controle de exibições do Loop
escape++;
// Controle do Loop
if (escape == NUMBER_OF_ATTMPTS) {
recordNotFoundMenssage();
abortingProcessMessage();
break;
}
} while (!formSelect(idCI));
displaySelectCI(idCI);
successfulMessage();
}
else
emptyMessage();
}
// Método para verificar se um registro está presente na estrutura de dados
bool Form::formSelect(string idCI) {
for (unsigned index = 0; index < Data.size(); index++) {
// Condição para ser que o registro exista
if ((Data[index].getIdCI()) == idCI)
return true;
}
return false;
}
// Método para imprimir (Formulário de impressão) a CI que tem a referência do ID utilizado
void Form::displaySelectCI(string idCI) {
for (unsigned index = 0; index < Data.size(); index++) {
if ((Data[index].getIdCI()) == idCI) {
cout << endl << endl;
cout << "ID.: ";
cout << setw(49) << left << Data[index].getIdCI();
cout << "DATA: ";
cout << setw(15) << left << Data[index].getDateCI();
cout << endl << endl;
cout << "DE: ";
cout << setw(50) << left << Data[index].getSenderCI();
cout << "PARA: ";
cout << setw(50) << left << Data[index].getRecipientCI();
cout << endl << endl;
cout << "ASSUNTO: ";
cout << setw(100) << left << Data[index].getSubjectCI();
cout << endl << endl;
cout << "MENSAGEM: ";
cout << setw(500) << left << Data[index].getMessageCI();
cout << endl << endl;
}
}
}
// Método para imprimir (Uso no método UPDATE) a CI que tem a referência do ID utilizado
void Form::displaySelectCI(string idCI, string toUpdate) {
for (unsigned index = 0; index < Data.size(); index++) {
if ((Data[index].getIdCI()) == idCI) {
cout << endl << endl;
cout << "ID.: ";
cout << setw(49) << left << Data[index].getIdCI();
cout << "DATA: ";
cout << setw(15) << left << Data[index].getDateCI();
cout << endl << endl;
cout << "[ A ] - DE: ";
cout << setw(50) << left << Data[index].getSenderCI();
cout << endl << endl;
cout << "[ B ] - PARA: ";
cout << setw(50) << left << Data[index].getRecipientCI();
cout << endl << endl;
cout << "[ C ] - ASSUNTO: ";
cout << setw(100) << left << Data[index].getSubjectCI();
cout << endl << endl;
cout << "[ D ] - MENSAGEM: ";
cout << setw(500) << left << Data[index].getMessageCI();
cout << endl << endl;
}
}
}
// Método para mensagem padrão de registro não encontrado, quando a estrutura de dados está vazia
void Form::emptyMessage() {
cout << endl << endl << "\t\tNenhum registro foi encontrado!!!" << endl << endl;
}
// Método para Imprimir uma especie de relatórios de registros.
void Form::displayRecordsReport() {
// Cabeçalho da tabela (campos identificação, data, mensagem)
cout << endl;
cout << setw(30) << left << "ID.";
cout << setw(15) << left << "DATA";
cout << setw(100) << left << "ASSUNTO";
cout << endl;
// Loop para carregar todas as mensagens armazenada no Vector (em memória)
for (unsigned index = 0; index < Data.size(); index++) {
cout << setw(30) << left << Data[index].getIdCI();
cout << setw(15) << left << Data[index].getDateCI();
cout << setw(100) << left << Data[index].getSubjectCI();
cout << endl;
}
}
// Método para mensagem padrão para cancelar o processo
void Form::abortingProcessMessage() {
cout << endl << endl << "\t\tAbortando Processo..." << endl << endl;
}
// Método para mensagem padrão de quando registro procurado não foi encontrado.
void Form::recordNotFoundMenssage() {
cout << endl << endl << "\t\tRegistro não encontrado..." << endl << endl;
} | true |
d3eb929b5d519a0828814ce6b259e47495dfe2e2 | C++ | Po-Jen/Fluent-Extractor | /src/FileFrameScanner.cpp | UTF-8 | 3,495 | 2.609375 | 3 | [
"MIT"
] | permissive | //
// Created by binroot on 12/14/15.
//
#include "FileFrameScanner.h"
#include <boost/filesystem.hpp>
#include <sstream>
#include <fstream>
using namespace std;
using cv::imread;
FileFrameScanner::FileFrameScanner(std::string filepath) {
m_filepath = filepath;
m_rgb_file_prefix = "aligned_rgb_";
m_xyz_file_prefix = "raw_point_";
m_skeleton_file_prefix = "skeleton_";
m_file_num_length = 5;
}
std::string zero_pad(long num, int length) {
std::string num_str = std::to_string(num);
int zeros_to_prepend = length - num_str.length();
num_str.insert(0, zeros_to_prepend, '0');
return num_str;
}
string FileFrameScanner::rgb_filename(int idx) {
return m_rgb_file_prefix + zero_pad(idx, m_file_num_length) + ".png";
}
void FileFrameScanner::xyz_filename(int idx, string& x_file, string& y_file, string& z_file) {
x_file = m_xyz_file_prefix + zero_pad(idx, m_file_num_length) + "_X.png";
y_file = m_xyz_file_prefix + zero_pad(idx, m_file_num_length) + "_Y.png";
z_file = m_xyz_file_prefix + zero_pad(idx, m_file_num_length) + "_Z.png";
}
string FileFrameScanner::skeleton_filename(int idx) {
return m_skeleton_file_prefix + zero_pad(idx, m_file_num_length) + ".txt";
}
bool FileFrameScanner::get(int idx, cv::Mat& img_bgr, cv::Mat& img_x, cv::Mat& img_y, cv::Mat& img_z, PointT& left_hand, PointT& right_hand) {
string img_file = rgb_filename(idx);
string x_file, y_file, z_file;
xyz_filename(idx, x_file, y_file, z_file);
string skeleton_file = skeleton_filename(idx);
img_bgr = imread(m_filepath + img_file);
img_x = imread(m_filepath + x_file, CV_LOAD_IMAGE_UNCHANGED);
img_y = imread(m_filepath + y_file, CV_LOAD_IMAGE_UNCHANGED);
img_z = imread(m_filepath + z_file, CV_LOAD_IMAGE_UNCHANGED);
read_skeleton(m_filepath + skeleton_file);
left_hand = m_left_hand;
right_hand = m_right_hand;
if (img_bgr.size().area() == 0) {
cout << "ERR: " << img_file << " is not found in " << m_filepath << endl;
return false;
} else if (img_x.size().area() == 0) {
cout << "ERR: " << x_file << " is malformed" << endl;
exit(1);
} else if (img_y.size().area() == 0) {
cout << "ERR: " << y_file << " is malformed" << endl;
exit(1);
} else if (img_z.size().area() == 0) {
cout << "ERR: " << z_file << " is malformed" << endl;
exit(1);
}
return true;
}
void FileFrameScanner::read_skeleton(string filename) {
if (boost::filesystem::is_regular_file(m_filepath + filename)) {
std::ifstream infile(filename);
std::string line;
int line_idx = 0;
while (getline(infile, line)) {
if (line_idx == 7) {
// left hand
std::istringstream iss(line);
double l, p3x, p3y, p3z, t, p2x, p2y;
iss >> l >> p3x >> p3y >> p3z >> t >> p2x >> p2y;
m_left_hand.x = p3x;
m_left_hand.y = p3y;
m_left_hand.z = p3z;
} else if (line_idx == 11) {
// right hand
std::istringstream iss(line);
double l, p3x, p3y, p3z, t, p2x, p2y;
iss >> l >> p3x >> p3y >> p3z >> t >> p2x >> p2y;
m_right_hand.x = p3x;
m_right_hand.y = p3y;
m_right_hand.z = p3z;
} else if (line_idx > 11) {
break;
}
line_idx++;
}
}
} | true |
e6a66674b4a79f8f97794fed289c672f1e1dd4d2 | C++ | wangxianghust/Cpp-Primer | /13/50.cpp | UTF-8 | 407 | 2.953125 | 3 | [] | no_license | #include "E49_String.h"
#include <iostream>
#include <vector>
using std::vector;
using std::cin;
using std::cout;
using std::endl;
String baz(){
String ret("world");
return ret;
}
void print(const String& s){
for(auto i : s){
cout << i << "";
}
cout << endl << "---";
}
int main(){
const char* s = "hello, world";
String st(s);
String stt;
stt = st;
String sttt;
// baz();
stt = baz();
} | true |
51135f056dc5fb3593fc04c9367e0242c18de77a | C++ | oliffur/learning | /Algorithms/Traversals.h | UTF-8 | 5,179 | 4.0625 | 4 | [] | no_license | /* traverses a binary tree in three different orders using two different
* techniques
*
*/
#include <iostream>
#include <stack>
#include <iterator>
#include "TreeNode.h"
using namespace std;
// preorder traverse the tree recursively
void preorderRecursive(TreeNode* root){
// first print out the value of the root
// this implies the root of the tree will be printed first
cout << root->value << endl;
// if the left child exists, recurse left
if (root->left) preorderTraversalRecursive(root->left);
// if the right child exists, recurse right
// this means that the rightmost node will be printed last
if (root->right) preorderTraversalRecursive(root->right);
}
// inorder traverse the tree recursively
void inorderRecursive(TreeNode* root){
// if left child exists, recurse left
// this means that the leftmost node will be printed first
if (root->left) recursiveIn(root->left);
// print out the value of the root
cout << root->value << endl;
// if the right child exists, recurse right
// this implies the rightmost node will be printed last
if (root->right) recursiveIn(root->right);
}
// postorder traverse the tree recursively
void postorderRecursive(TreeNode* root){
// if the left child exists, recurse left
// this implies the left-most node is printed first
if (root->left) recursivePost(root->left);
// if the right child exists, recurse right
if (root->right) recursivePost(root->right);
// print out the value at the root
// this implies that the root of the tree is printed last
cout << root->value << endl;
}
// preorder traverses the tree iteratively
void preorderIterative(TreeNode* root){
// create a stack on which to push addresses of nodes that we have not yet
// processed; generally, this stack will consist of some left child being
// on the top, followed by its parent's right child, followed by its
// parent's parent's right child, etc., which matches the hierarchy of
// printing in a preorder manner
stack<TreeNode*> TreeStack;
// address of the current node
TreeNode* current;
TreeStack.push(root);
// while TreeStack is not empty...
while (!TreeStack.empty()){
// pop the top item on the stock and print its value
current = TreeStack.top();
TreeStack.pop();
cout << current->value << endl;
// if right child of top item exists, push it onto the stack; then do
// the same for the left child
if (current->right) TreeStack.push(current->right);
if (current->left) TreeStack.push(current->left);
}
}
// inorder traverses the tree iteratively
void inorderIterative(TreeNode* root){
// set up stack and set 'current' to root
// current will be the node currently under examination; the stack will
// hold its parents
stack<TreeNode*> TreeStack;
TreeNode* current = root;
while (!TreeStack.empty() || current){
// if 'current' exists, push current node and continue left
if (current){
TreeStack.push(current);
current = current->left;
}
// otherwise, process the current node and go right
else{
current = TreeStack.top();
TreeStack.pop();
cout << current->value << endl;
current = current->right;
}
}
}
// postorder traverses the tree iteratively
void iterativePost(TreeNode* root){
// create stack and set current to root
stack<TreeNode*> TreeStack;
TreeNode* current = root;
do{
// move all the way to the left, pushing the right node and the current
// node of nodes we pass along the way
//
// we are not processing the nodes in the order that they will be printed;
// this is because we pushed the nodes onto the stack in such a way that
// when we get to a node, we can distinguish whether it is a parent node
// or a right node; then when we process we will flip them to print them
// in the correct order
while (current){
if (current->right) TreeStack.push(current->right);
TreeStack.push(current);
current = current->left;
}
// pop from TreeStack and set as current
current = TreeStack.top();
TreeStack.pop();
// here: if current node has a right child equal to the node at the top
// of the stack, then it must be that, in the sequence of visiting the
// subtrees in a postorder fashion, we have just finished some left
// branch and we are now looking at the remaining two (parent and right).
// In this situation, we want to process the right child first, so we flip
// the nodes to process them
if (current->right && TreeStack.top() == current->right){
TreeStack.pop();
TreeStack.push(current);
current = current->right;
}
// if the current node has a right child but it is not equal to the top,
// then it must be that we have just finished a right branch and we are
// back at the parent;
// therefore we must print this out
//
// if the current node does not have a right child, then we must process
// this node
else{
cout << current->value << endl;
current = nullptr;
}
}while(!TreeStack.empty());
}
| true |
f9efc3d1ed723851a39a8f90b04a3d0d05759fbd | C++ | StrongerL/algorithm_cpp | /pta/1007_MaximumSubsequenceSum_20200113.cpp | UTF-8 | 1,169 | 3.140625 | 3 | [] | no_license | /*
来源
https://pintia.cn/problem-sets/994805342720868352/problems/994805514284679168
题目
1007 Maximum Subsequence Sum (25分)
思路
双指针即可,代码很快写出来了,但是被0和负数这种情况困了快一个小时。。。
*/
#include <iostream>
using namespace std;
int nums[10010];
int K, cur_i, cur_j, cur_sum, max_i, max_j, max_sum;
bool exist_zero;
int main() {
cin >> K;
for (int i = 0; i < K; i++) {
cin >> nums[i];
if (nums[i] == 0) {
exist_zero = true;
}
}
while (cur_i < K && cur_j < K) {
cur_sum += nums[cur_j];
if (cur_sum > max_sum) {
max_i = cur_i;
max_j = cur_j;
max_sum = cur_sum;
}
if (cur_sum < 0) {
cur_sum = 0;
cur_i = cur_j + 1;
}
cur_j++;
}
if (max_sum == 0) {
if (exist_zero) { // 全0|0和负数
cout << 0 << " " << 0 << " " << 0;
} else { // 全负数
cout << 0 << " " << nums[0] << " " << nums[K - 1];
}
} else {
cout << max_sum << " " << nums[max_i] << " " << nums[max_j];
}
}
| true |
e34f8835f2c9e6eeecd5ceb904a21bfd08f147f2 | C++ | mayanksharma27/DS_and_algo_codes | /dp/house-robber.cpp | UTF-8 | 471 | 2.9375 | 3 | [] | no_license | //https://leetcode.com/problems/house-robber/
class Solution {
public:
int rob(vector<int>& nums) {
if(nums.size() == 0 ) return 0;
int incl_old,incl=nums[0],excl=0;
for(auto it = nums.begin()+1;it!=nums.end();++it){
incl_old =incl;
incl = *it+ excl;
excl = ( incl_old > excl ? incl_old : excl);
// cout << incl << " "<<excl<<endl;
}
return incl > excl ? incl : excl;
}
};
| true |
a326c2036b134aea89a9bb642346b49547c6d19f | C++ | huangbin5/PAT_Advanced | /109-10/1096.cpp | UTF-8 | 1,041 | 3 | 3 | [] | no_license | #include <algorithm>
#include <cmath>
#include <iostream>
using namespace std;
// #define DEBUG
bool isPrime(int n) {
if (n <= 1)
return false;
int sqt = sqrt(n);
for (int i = 2; i <= sqt; ++i) {
if (n % i == 0)
return false;
}
return true;
}
int main() {
#ifdef DEBUG
freopen("d:\\input.txt", "r", stdin);
freopen("d:\\output.txt", "w", stdout);
#endif
int n;
scanf("%d", &n);
if (isPrime(n)) {
printf("1\n%d", n);
return 0;
}
int sqt = sqrt(n) + 1, len = 0, start;
for (int i = 2; i <= sqt; ++i) {
int tmp = n;
for (int j = i; j <= sqt; ++j) {
if (tmp % j)
break;
tmp /= j;
if (j - i + 1 > len) {
len = j - i + 1;
start = i;
}
}
}
printf("%d\n", len);
for (int i = 0; i < len; ++i) {
if (i == 0)
printf("%d", start);
else
printf("*%d", start + i);
}
return 0;
} | true |
f24ad9f8ec9b83a8d49cf258a3d6ab53b3750ccd | C++ | open-space-collective/open-space-toolkit-physics | /include/OpenSpaceToolkit/Physics/Time/Instant.hpp | UTF-8 | 14,865 | 2.59375 | 3 | [
"Apache-2.0",
"MPL-2.0",
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | /// Apache License 2.0
#ifndef __OpenSpaceToolkit_Physics_Time_Instant__
#define __OpenSpaceToolkit_Physics_Time_Instant__
#include <OpenSpaceToolkit/Core/Types/Integer.hpp>
#include <OpenSpaceToolkit/Core/Types/Real.hpp>
#include <OpenSpaceToolkit/Core/Types/String.hpp>
#include <OpenSpaceToolkit/Physics/Time/DateTime.hpp>
#include <OpenSpaceToolkit/Physics/Time/Duration.hpp>
#include <OpenSpaceToolkit/Physics/Time/Scale.hpp>
#include <OpenSpaceToolkit/Physics/Units/Time.hpp>
namespace ostk
{
namespace physics
{
namespace time
{
using ostk::core::types::Int64;
using ostk::core::types::Uint64;
using ostk::core::types::Real;
using ostk::core::types::String;
using ostk::physics::time::Scale;
using ostk::physics::time::Duration;
#define DEFAULT_TIME_SCALE Scale::UTC
#define DEFAULT_DATE_TIME_FORMAT DateTime::Format::Standard
/// @brief Point in time
///
/// @ref https://en.wikipedia.org/wiki/Instant
/// @ref https://www.boost.org/doc/libs/1_67_0/doc/html/date_time/details.html#date_time.calculations
/// @ref http://rhodesmill.org/skyfield/time.html
/// @ref http://www.madore.org/~david/computers/unix-leap-seconds.html
/// @ref http://help.agi.com/AGIComponentsJava/html/TimeAndTimeStandards.htm
class Instant
{
public:
/// @brief Default constructor (deleted)
Instant() = delete;
/// @brief Equal to operator
///
/// @code
/// Instant::DateTime(DateTime(2018, 1, 2, 0, 0, 0), Scale::TT) ==
/// Instant::DateTime(DateTime(2018, 1, 2, 0, 0, 0), Scale::TT) ; // True
/// @endcode
///
/// @param [in] anInstant An instant
/// @return True if instants are equal
bool operator==(const Instant& anInstant) const;
/// @brief Not equal to operator
///
/// @code
/// Instant::DateTime(DateTime(2018, 1, 2, 0, 0, 0), Scale::TT) !=
/// Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 0), Scale::TT) ; // True
/// @endcode
///
/// @param [in] anInstant An instant
/// @return True if instants are not equal
bool operator!=(const Instant& anInstant) const;
/// @brief Less than operator
///
/// @code
/// Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 0), Scale::TT) <
/// Instant::DateTime(DateTime(2018, 1, 2, 0, 0, 0), Scale::TT) ; // True
/// @endcode
///
/// @param [in] anInstant An instant
/// @return True if lhs duration is less than rhs duration
bool operator<(const Instant& anInstant) const;
/// @brief Less than or equal to operator
///
/// @code
/// Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 0), Scale::TT) <=
/// Instant::DateTime(DateTime(2018, 1, 2, 0, 0, 0), Scale::TT) ; // True
/// @endcode
///
/// @param [in] anInstant An instant
/// @return True if lhs duration is less than or equal to rhs duration
bool operator<=(const Instant& anInstant) const;
/// @brief Greater than operator
///
/// @code
/// Instant::DateTime(DateTime(2018, 1, 2, 0, 0, 0), Scale::TT) >
/// Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 0), Scale::TT) ; // True
/// @endcode
///
/// @param [in] anInstant An instant
/// @return True if lhs duration is greater than rhs duration
bool operator>(const Instant& anInstant) const;
/// @brief Greater than operator
///
/// @code
/// Instant::DateTime(DateTime(2018, 1, 2, 0, 0, 0), Scale::TT) >=
/// Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 0), Scale::TT) ; // True
/// @endcode
///
/// @param [in] anInstant An instant
/// @return True if lhs duration is greater than or equal to rhs duration
bool operator>=(const Instant& anInstant) const;
/// @brief Addition operator
///
/// @code
/// Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 0), Scale::TT) + Duration::Days(1.0) ; //
/// 2018-01-02 00:00:00
/// @endcode
///
/// @param [in] aDuration A duration
/// @return Instant
Instant operator+(const Duration& aDuration) const;
/// @brief Subtraction operator
///
/// @code
/// Instant::DateTime(DateTime(2018, 1, 2, 0, 0, 0), Scale::TT) - Duration::Days(1.0) ; //
/// 2018-01-01 00:00:00
/// @endcode
///
/// @param [in] aDuration A duration
/// @return Instant
Instant operator-(const Duration& aDuration) const;
/// @brief Subtraction operator
///
/// @code
/// Instant::DateTime(DateTime(2018, 1, 2, 0, 0, 0), Scale::TT) -
/// Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 0), Scale::TT) ; // 1.0 [day]
/// @endcode
///
/// @param [in] anInstant An instant
/// @return Duration
Duration operator-(const Instant& anInstant) const;
/// @brief Addition assignement operator
///
/// @code
/// Instant instant = Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 0), Scale::TT) ;
/// instant += Duration::Days(1.0) ; // 2018-01-02 00:00:00 [TT]
/// @endcode
///
/// @param [in] aDuration A duration
/// @return Reference to instant
Instant& operator+=(const Duration& aDuration);
/// @brief Subtraction assignement operator
///
/// @code
/// Instant instant = Instant::DateTime(DateTime(2018, 1, 2, 0, 0, 0), Scale::TT) ;
/// instant -= Duration::Days(1.0) ; // 2018-01-01 00:00:00 [TT]
/// @endcode
///
/// @param [in] aDuration A duration
/// @return Reference to instant
Instant& operator-=(const Duration& aDuration);
/// @brief Output stream operator
///
/// @code
/// std::cout << Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 0), Scale::UTC) ;
/// @endcode
///
/// @param [in] anOutputStream An output stream
/// @param [in] anInstant An instant
/// @return A reference to output stream
friend std::ostream& operator<<(std::ostream& anOutputStream, const Instant& anInstant);
/// @brief Check if instant is defined
///
/// @code
/// Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 0), Scale::UTC).isDefined() ; // True
/// @endcode
///
/// @return True if instant is defined
bool isDefined() const;
/// @brief Check if instant is post-epoch (J2000)
///
/// @code
/// Instant::DateTime(DateTime(2018, 1, 1, 0, 0, 0), Scale::UTC).isPostEpoch() ; // True
/// @endcode
///
/// @return True if instant is post-epoch
bool isPostEpoch() const;
/// @brief Check if instant is near another instant
///
/// @code
/// Instant::J2000().isNear(Instant::J2000(), Duration::Zero()) ; // True
/// @endcode
///
/// @param [in] anInstant An instant
/// @param [in] aTolerance A tolerance
/// @return True if instant is near another instant
bool isNear(const Instant& anInstant, const Duration& aTolerance) const;
/// @brief Get date-time expressed in given time scale
///
/// @code
/// Instant::J2000().getDateTime(Scale::TT) ; // 2000-01-01 12:00:00
/// @endcode
///
/// @param [in] aTimeScale A time scale
/// @return Date-time
time::DateTime getDateTime(const Scale& aTimeScale) const;
/// @brief Get Julian Date expressed in given time scale
///
/// @code
/// Instant::J2000().getJulianDate(Scale::TT) ; // 2451545.0
/// @endcode
///
/// @param [in] aTimeScale A time scale
/// @return Julian Date
Real getJulianDate(const Scale& aTimeScale) const;
/// @brief Get Modified Julian Date expressed in given time scale
///
/// @code
/// Instant::J2000().getModifiedJulianDate(Scale::TT) ; // 51544.0
/// @endcode
///
/// @param [in] aTimeScale A time scale
/// @return Modified Julian Date
Real getModifiedJulianDate(const Scale& aTimeScale) const;
/// @brief Get Leap Second count
///
/// The Leap Second count is the number of seconds between TAI and UTC scales.
///
/// @code
/// Instant::J2000().getLeapSecondCount() ;
/// @endcode
///
/// @return Leap Second
Int64 getLeapSecondCount() const;
/// @brief Get string representation of instant
///
/// @code
/// Instant::J2000().toString(Scale::TT) ; // 2000-01-01 12:00:00 [TT]
/// @endcode
///
/// @param [in] aTimeScale A time scale
/// @return Serialized instant
String toString(
const Scale& aTimeScale = DEFAULT_TIME_SCALE, const DateTime::Format& aDateTimeFormat = DEFAULT_DATE_TIME_FORMAT
) const;
/// @brief Constructs an undefined instant
///
/// @code
/// Instant instant = Instant::Undefined() ;
/// instant.isDefined() ; // False
/// @endcode
///
/// @return Undefined instant
static Instant Undefined();
/// @brief Constructs an instant at current time
///
/// @code
/// Instant instant = Instant::Now() ;
/// @endcode
///
/// @return Instant at current time
static Instant Now();
/// @brief Constructs instant at J2000 epoch
///
/// The currently-used standard epoch "J2000" is defined by international agreement to be
/// equivalent to:
/// - The Gregorian date January 1, 2000 at 12:00 TT (Terrestrial Time).
/// - The Julian date 2451545.0 TT (Terrestrial Time).
/// - January 1, 2000, 11:59:27.816 TAI (International Atomic Time).
/// - January 1, 2000, 11:58:55.816 UTC (Coordinated Universal Time).
///
/// @ref https://en.wikipedia.org/wiki/Epoch_(astronomy)#Julian_years_and_J2000
///
/// @return Instant at J2000 epoch
static Instant J2000();
/// @brief Constructs instant from date-time
///
/// @code
/// Instant instant = Instant::DateTime(DateTime(2000, 1, 1, 12, 0, 0), Scale::TT) ; //
/// 2000-01-01 12:00:00 [TT]
/// @endcode
///
/// @input [in] aDateTime A date-time
/// @input [in] aTimeScale A time scale
/// @return Instant
static Instant DateTime(const time::DateTime& aDateTime, const Scale& aTimeScale);
/// @brief Constructs instant from Julian Date
///
/// @code
/// Instant instant = Instant::JulianDate(2451545.0, Scale::TT) ; // 2000-01-01 12:00:00 [TT]
/// @endcode
///
/// @ref https://en.wikipedia.org/wiki/Julian_day
///
/// @input [in] aJulianDate A Julian Date
/// @input [in] aTimeScale A time scale
/// @return Instant
static Instant JulianDate(const Real& aJulianDate, const Scale& aTimeScale);
/// @brief Constructs instant from Modified Julian Date
///
/// @code
/// Instant instant = Instant::ModifiedJulianDate(51544.0, Scale::TT) ; // 2000-01-01 12:00:00
/// [TT]
/// @endcode
///
/// @ref https://en.wikipedia.org/wiki/Julian_day
///
/// @input [in] aJulianDate A Modified Julian Date
/// @input [in] aTimeScale A time scale
/// @return Instant
static Instant ModifiedJulianDate(const Real& aModifiedJulianDate, const Scale& aTimeScale);
private:
class Count
{
public:
Uint64 countFromEpoch_;
bool postEpoch_;
Count(Uint64 aNanosecondCountFromEpoch, bool isPostEpoch);
bool operator==(const Count& aCount) const;
bool operator!=(const Count& aCount) const;
bool operator<(const Count& aCount) const;
bool operator<=(const Count& aCount) const;
bool operator>(const Count& aCount) const;
bool operator>=(const Count& aCount) const;
Count operator+(const Count& aCount) const;
Count operator+(Int64 aNanosecondDisplacement) const;
Count operator-(Int64 aNanosecondDisplacement) const;
String toString() const;
};
Instant::Count count_;
Scale scale_;
Instant(const Instant::Count& aCount, const Scale& aTimeScale);
Instant inScale(const Scale& aTimeScale) const;
static Instant::Count ConvertCountScale(
const Instant::Count& aCount, const Scale& anInputTimeScale, const Scale& anOutputTimeScale
);
static Instant::Count UTC_TAI(const Instant::Count& aCount_TAI);
static Instant::Count TAI_UTC(const Instant::Count& aCount_UTC);
static Instant::Count TAI_TT(const Instant::Count& aCount_TT);
static Instant::Count TT_TAI(const Instant::Count& aCount_TAI);
static Instant::Count UT1_UTC(const Instant::Count& aCount_UTC);
static Instant::Count UTC_UT1(const Instant::Count& aCount_UT1);
static Instant::Count GPST_TAI(const Instant::Count& aCount_TAI);
static Instant::Count TAI_GPST(const Instant::Count& aCount_GPST);
static Int64 dAT_UTC(const Instant::Count& aCount_UTC);
static Int64 dAT_TAI(const Instant::Count& aCount_TAI);
static Int64 DUT1_UTC(const Instant::Count& aCount_UTC);
static Int64 DUT1_UT1(const Instant::Count& aCount_UT1);
};
} // namespace time
} // namespace physics
} // namespace ostk
#endif
| true |
e4fecd16810ef76f09cd353199a8cdd43b1236aa | C++ | xzrunner/shadergraph | /include/shadergraph/block/Blend.h | UTF-8 | 7,753 | 2.71875 | 3 | [
"MIT"
] | permissive | #pragma once
#include "shadergraph/Block.h"
#include <SM_Vector.h>
namespace shadergraph
{
namespace block
{
class Blend : public Block
{
public:
enum class Mode
{
Burn,
Darken,
Difference,
Dodge,
Divide,
Exclusion,
HardLight,
HardMix,
Lighten,
LinearBurn,
LinearDodge,
LinearLight,
LinearLightAddSub,
Multiply,
Negation,
Overlay,
PinLight,
Screen,
SoftLight,
Subtract,
VividLight,
Overwrite
};
public:
Blend()
{
SetupPorts({
{ VarType::Float3, "base" },
{ VarType::Float3, "blend" },
{ VarType::Float, "opacity" },
}, {
{ VarType::Float3, "_out" },
});
}
virtual std::string GetHeader(const Evaluator& eval) const
{
return R"(
// https://docs.unity3d.com/Packages/com.unity.shadergraph@9.0/manual/Blend-Node.html
// Burn
vec3 blend_burn(vec3 base, vec3 blend, float opacity)
{
vec3 ret = 1.0 - (1.0 - blend)/base;
return mix(base, ret, opacity);
}
// Darken
vec3 blend_darken(vec3 base, vec3 blend, float opacity)
{
vec3 ret = min(blend, base);
return mix(base, ret, opacity);
}
// Difference
vec3 blend_difference(vec3 base, vec3 blend, float opacity)
{
vec3 ret = abs(blend - base);
return mix(base, ret, opacity);
}
// Dodge
vec3 blend_dodge(vec3 base, vec3 blend, float opacity)
{
vec3 ret = base / (1.0 - blend);
return mix(base, ret, opacity);
}
// Divide
vec3 blend_divide(vec3 base, vec3 blend, float opacity)
{
vec3 ret = base / (blend + 0.000000000001);
return mix(base, ret, opacity);
}
// Exclusion
vec3 blend_exclusion(vec3 base, vec3 blend, float opacity)
{
vec3 ret = blend + base - (2.0 * blend * base);
return mix(base, ret, opacity);
}
// HardLight
vec3 blend_hard_light(vec3 base, vec3 blend, float opacity)
{
vec3 result1 = 1.0 - 2.0 * (1.0 - base) * (1.0 - blend);
vec3 result2 = 2.0 * base * blend;
vec3 zeroOrOne = step(blend, vec3(0.5));
vec3 ret = result2 * zeroOrOne + (1 - zeroOrOne) * result1;
return mix(base, ret, opacity);
}
// HardMix
vec3 blend_hard_mix(vec3 base, vec3 blend, float opacity)
{
vec3 ret = step(1 - base, blend);
return mix(base, ret, opacity);
}
// Lighten
vec3 blend_lighten(vec3 base, vec3 blend, float opacity)
{
vec3 ret = max(blend, base);
return mix(base, ret, opacity);
}
// LinearBurn
vec3 blend_linear_burn(vec3 base, vec3 blend, float opacity)
{
vec3 ret = base + blend - 1.0;
return mix(base, ret, opacity);
}
// LinearDodge
vec3 blend_linear_dodge(vec3 base, vec3 blend, float opacity)
{
vec3 ret = base + blend;
return mix(base, ret, opacity);
}
// LinearLight
vec3 blend_linear_light(vec3 base, vec3 blend, float opacity)
{
vec3 ret;
ret.x = blend.x < 0.5 ? max(base.x + (2 * blend.x) - 1, 0) : min(base.x + 2 * (blend.x - 0.5), 1);
ret.y = blend.y < 0.5 ? max(base.y + (2 * blend.y) - 1, 0) : min(base.y + 2 * (blend.y - 0.5), 1);
ret.z = blend.z < 0.5 ? max(base.z + (2 * blend.z) - 1, 0) : min(base.z + 2 * (blend.z - 0.5), 1);
return mix(base, ret, opacity);
}
// LinearLightAddSub
vec3 blend_linear_light_add_sub(vec3 base, vec3 blend, float opacity)
{
vec3 ret = blend + 2.0 * base - 1.0;
return mix(base, ret, opacity);
}
// Multiply
vec3 blend_multiply(vec3 base, vec3 blend, float opacity)
{
vec3 ret = base * blend;
return mix(base, ret, opacity);
}
// Negation
vec3 blend_negation(vec3 base, vec3 blend, float opacity)
{
vec3 ret = 1.0 - abs(1.0 - blend - base);
return mix(base, ret, opacity);
}
// Overlay
vec3 blend_overlay(vec3 base, vec3 blend, float opacity)
{
vec3 result1 = 1.0 - 2.0 * (1.0 - base) * (1.0 - blend);
vec3 result2 = 2.0 * base * blend;
vec3 zeroOrOne = step(base, vec3(0.5));
vec3 ret = result2 * zeroOrOne + (1 - zeroOrOne) * result1;
return mix(base, ret, opacity);
}
// PinLight
vec3 blend_pin_light(vec3 base, vec3 blend, float opacity)
{
vec3 check = step (0.5, blend);
vec3 result1 = check * max(2.0 * (base - 0.5), blend);
vec3 ret = result1 + (1.0 - check) * min(2.0 * base, blend);
return mix(base, ret, opacity);
}
// Screen
vec3 blend_screen(vec3 base, vec3 blend, float opacity)
{
vec3 ret = 1.0 - (1.0 - blend) * (1.0 - base);
return mix(base, ret, opacity);
}
// SoftLight
vec3 blend_soft_light(vec3 base, vec3 blend, float opacity)
{
vec3 result1 = 2.0 * base * blend + base * base * (1.0 - 2.0 * blend);
vec3 result2 = sqrt(base) * (2.0 * blend - 1.0) + 2.0 * base * (1.0 - blend);
vec3 zeroOrOne = step(0.5, blend);
vec3 ret = result2 * zeroOrOne + (1 - zeroOrOne) * result1;
return mix(base, ret, opacity);
}
// Subtract
vec3 blend_subtract(vec3 base, vec3 blend, float opacity)
{
vec3 ret = base - blend;
return mix(base, ret, opacity);
}
// VividLight
vec3 blend_vivid_light(vec3 base, vec3 blend, float opacity)
{
vec3 result1 = 1.0 - (1.0 - blend) / (2.0 * base);
vec3 result2 = blend / (2.0 * (1.0 - base));
vec3 zeroOrOne = step(0.5, base);
vec3 ret = result2 * zeroOrOne + (1 - zeroOrOne) * result1;
return mix(base, ret, opacity);
}
// Overwrite
vec3 blend_overwrite(vec3 base, vec3 blend, float opacity)
{
return mix(base, blend, opacity);
}
)";
}
virtual std::string GetBody(const Evaluator& eval) const override
{
std::string func;
switch (m_mode)
{
case Mode::Burn:
func = "blend_burn";
break;
case Mode::Darken:
func = "blend_darken";
break;
case Mode::Difference:
func = "blend_difference";
break;
case Mode::Dodge:
func = "blend_dodge";
break;
case Mode::Divide:
func = "blend_divide";
break;
case Mode::Exclusion:
func = "blend_exclusion";
break;
case Mode::HardLight:
func = "blend_hard_light";
break;
case Mode::HardMix:
func = "blend_hard_mix";
break;
case Mode::Lighten:
func = "blend_lighten";
break;
case Mode::LinearBurn:
func = "blend_linear_burn";
break;
case Mode::LinearDodge:
func = "blend_linear_dodge";
break;
case Mode::LinearLight:
func = "blend_linear_light";
break;
case Mode::LinearLightAddSub:
func = "blend_linear_light_add_sub";
break;
case Mode::Multiply:
func = "blend_multiply";
break;
case Mode::Negation:
func = "blend_negation";
break;
case Mode::Overlay:
func = "blend_overlay";
break;
case Mode::PinLight:
func = "blend_pin_light";
break;
case Mode::Screen:
func = "blend_screen";
break;
case Mode::SoftLight:
func = "blend_soft_light";
break;
case Mode::Subtract:
func = "blend_subtract";
break;
case Mode::VividLight:
func = "blend_vivid_light";
break;
case Mode::Overwrite:
func = "blend_overwrite";
break;
default:
assert(0);
}
return "vec3 #_out# = " + func + "(#base#, #blend#, #opacity#);";
}
RTTR_ENABLE(Block)
#define PARM_FILEPATH "shadergraph/block/blend.parm.h"
#include <dag/node_parms_gen.h>
#undef PARM_FILEPATH
}; // Blend
}
} | true |
90813136e97cbbcab1c00fd1a0cf2dbf62c0fec5 | C++ | Areklis909/SteganoImages | /lib/ImageHandler/ImageHandler.cpp | UTF-8 | 2,483 | 2.609375 | 3 | [] | no_license | #ifndef IMAGE_HANDLER_CPP
#define IMAGE_HANDLER_CPP
#include <ImageHandler/ImageHandler.hpp>
#include <ConstData/ConstData.hpp>
#include <MessageTooBigException/MessageTooBigException.hpp>
namespace NsImageHandler {
ImageHandler::ImageHandler(const std::string & imagePath, const std::string & pathToWrite) :
image(cv::imread(imagePath)),
pathToWrite(pathToWrite),
redChannel(2),
greenChannel(1),
blueChannel(0),
steganoMarker("SteganoImages")
{
checkImageProperties(imagePath);
}
ImageHandler::ImageHandler(const std::string & imagePath) : image(cv::imread(imagePath)),
pathToWrite(""),
redChannel(2),
greenChannel(1),
blueChannel(0),
steganoMarker("SteganoImages")
{
checkImageProperties(imagePath);
}
void ImageHandler::checkImageProperties(const std::string & imagePath) {
if(image.empty() || image.depth() != CV_8U) {
throw std::runtime_error("Failed to open requested image: " + imagePath);
}
numOfPixels = channels() * rows() * cols();
}
ImageHandler::~ImageHandler() {
if(pathToWrite.empty() == false) {
cv::imwrite(pathToWrite, image);
}
}
int ImageHandler::channels() const {
return image.channels();
}
int ImageHandler::depth() const {
return image.depth();
}
int ImageHandler::rows() const {
return image.rows;
}
int ImageHandler::cols() const {
return image.cols;
}
const std::string & ImageHandler::getSteganoMarker() const {
return steganoMarker;
}
size_t ImageHandler::getSteganoMarkerSizeInBits() const {
using namespace NsConstData;
return steganoMarker.size() * bitsInByte;
}
cv::Mat & ImageHandler::getChannel(const int channelNumber) {
if(splitChannels.empty() == true) {
cv::split(image, splitChannels);
}
return splitChannels.at(channelNumber);
}
cv::Mat & ImageHandler::getRedChannel() {
return getChannel(redChannel);
}
cv::Mat & ImageHandler::getGreenChannel() {
return getChannel(greenChannel);
}
cv::Mat & ImageHandler::getBlueChannel() {
return getChannel(blueChannel);
}
int ImageHandler::getNumOfPixels() const {
return numOfPixels;
}
void ImageHandler::verifyMessageSize(const size_t messageSize, const size_t markerSize) {
using namespace NsConstData;
using namespace NsMessageTooBigException;
const size_t maxSize = (cols() * rows()) - msgSizeMarkerSizeInBits - markerSize;
if(messageSize > maxSize) {
throw MessageTooBigException();
}
}
}
#endif
| true |
7869176c3c03fb3625ff903790b3eae575a7f929 | C++ | malcolmyeh/CC3K | /werewolf.cc | UTF-8 | 1,599 | 3.203125 | 3 | [] | no_license | #include "werewolf.h"
Werewolf::Werewolf(Posn position, int chamberID)
{
this->Atk = 30;
this->Def = 5;
this->HP = 120;
this->gold = 1;
this->race = "Werewolf";
this->symbol = 'W';
this->hasCompass = false;
this->chamberID = chamberID;
this->position = position;
this->stunned = false;
}
Werewolf::~Werewolf() {}
std::string Werewolf::dealDamage(Character *opponent)
{
double amount;
std::string combatMsg;
std::string attacker = this->race;
int attack = this->Atk;
int defense = opponent->getDef();
if (this->stunned)
{
this->stunned = false;
combatMsg = attacker + " is stunned. ";
return combatMsg;
}
if (rand() % 2 == 0)
{
combatMsg = attacker + "'s attack missed. ";
return combatMsg;
}
if (this->HP <= 30)
{
combatMsg = attacker + "'s unstoppable rage increases its damage by 3. ";
this->Atk += 3;
}
else if (this-> HP <= 60)
{
combatMsg = attacker + "'s blinding rage increases its damage by 2. ";
this->Atk += 2;
}
else if (this-> HP <= 90)
{
combatMsg = attacker + "'s rage increases its damage by 1. ";
this->Atk += 1;
}
amount = ceil((100.0 / (100.0 + defense)) * attack);
opponent->takeDamage((int)amount);
combatMsg += attacker + " deals " + std::to_string((int)amount) + " damage to you (HP: " + std::to_string(opponent->getHP()) + "). ";
if (opponent->getHP() == 0)
{
combatMsg += "You have been slain.";
}
return combatMsg;
}
| true |
dfe027ac8261f156c1ec854c3bcf721541e63263 | C++ | osamu-k/CppStudy | /ExpressionCpp001/visitor.h | UTF-8 | 612 | 2.640625 | 3 | [] | no_license | #ifndef VISITOR_H
#define VISITOR_H
class NodeInteger;
class NodeVariable;
class NodeAdd;
class NodeSub;
class NodeMul;
class NodeDiv;
class NodeAssign;
class Visitor
{
public:
virtual void visitInteger( NodeInteger *ni ) = 0;
virtual void visitVariable( NodeVariable *nv ) = 0;
virtual void visitAdd( NodeAdd *na ) = 0;
virtual void visitSub( NodeSub *ns ) = 0;
virtual void visitMul(NodeMul *nm ) = 0;
virtual void visitDiv( NodeDiv *nv ) = 0;
virtual void visitAssign( NodeAssign *na ) = 0;
protected:
Visitor()
{}
virtual ~Visitor()
{}
};
#endif // VISITOR_H
| true |
43b82df961a4a748a3ca4e1bf0db3ea5e43c2345 | C++ | slux83/libslx | /test/cppunit/sunboundedblockingqueue_test.h | UTF-8 | 5,863 | 3.015625 | 3 | [
"Apache-2.0"
] | permissive | /******************************************************************************
[FILE_HEADER_BEGIN]
[FILE_HEADER_END]
******************************************************************************/
#ifndef SBLOCKINGQUEUE_TEST_H
#define SBLOCKINGQUEUE_TEST_H
#include <unistd.h>
#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
#include "../../src/concurrent/sunboundedblockingqueue.h"
#include "../../src/concurrent/sthread.h"
//Used to count dequeues in test testNConsumerNProducer()
SMutex m1;
int dequeues;
/*!
\brief Test Unit for SUnboundedBlockingQueue object
*/
class SUnboundedBlockingQueueTest : public CppUnit::TestFixture
{
CPPUNIT_TEST_SUITE(SUnboundedBlockingQueueTest);
CPPUNIT_TEST(testOneConsumerOneProducer);
CPPUNIT_TEST(testOneConsumerNProducer);
CPPUNIT_TEST(testNConsumerNProducer);
CPPUNIT_TEST_SUITE_END();
private:
//The object to test
static SUnboundedBlockingQueue<int> *queue;
//Internal test thread class -------------------------------------- [BEGIN]
class TestThread : public SThread
{
public:
int startNum;
bool isProducer; //I'm damn lazy :p
TestThread(int n, const std::string &name, bool producer) : SThread(name)
{
startNum = n;
isProducer = producer;
}
protected:
virtual void run()
{
SThread::run();
//Enqueue/Dequeue into the queue 10 elements
if (isProducer)
{
for (int i=0; i<10; ++i)
{
queue->enqueue(startNum + i);
#if 0
std::cout << name << ": Enqueueing " << (startNum + i) << std::endl;
fflush(stdout);
#endif
}
}
else
{
while (true)
{
int dequeuedVal = queue->dequeue();
m1.lock();
++dequeues;
CPPUNIT_ASSERT_EQUAL(true, (dequeuedVal >= 0 && dequeuedVal <= 29));
#if 0
std::cout << name << ": Dequeueing " << (dequeuedVal)
<< " dequeues: " << dequeues << std::endl;
fflush(stdout);
#endif
if (dequeues == 29) //Okay, all datas are dequeued
{
m1.unlock();
break;
}
m1.unlock();
}
}
}
};
//Internal test thread class ---------------------------------------- [END]
public:
void setUp()
{
queue = new SUnboundedBlockingQueue<int>();
dequeues = 0;
}
void tearDown()
{
//delete queue;
//NOTE: we can't destroy here the queue. This is just a test :)
fflush(stdout);
}
void testOneConsumerOneProducer()
{
delete queue;
queue = new SUnboundedBlockingQueue<int>();
//This thread will be insert into the queue values from 0...9
TestThread *producer = new TestThread(0, "Thread-producer", true);
//Start the thread
producer->start();
//Now this thread (the consumer) will consume ten values
for (int i=0; i<10; ++i)
{
//The queue shall mantains the same insertion order during the dequeueing
CPPUNIT_ASSERT_EQUAL(i, queue->dequeue());
}
producer->join();
CPPUNIT_ASSERT_EQUAL(true, queue->isEmpty());
delete producer;
producer = NULL;
}
void testOneConsumerNProducer()
{
//Ensure that the queue is empty
CPPUNIT_ASSERT_EQUAL(true, queue->isEmpty());
//We create 3 producer therads. Each of these will insert into the queue 10 elements.
TestThread *producer1 = new TestThread(0, "Thread-producer-1", true);
TestThread *producer2 = new TestThread(10, "Thread-producer-2", true);
TestThread *producer3 = new TestThread(20, "Thread-producer-3", true);
//Start the first thread
producer1->start();
//Now this thread (the consumer) will consume 30 values
for (int i=0; i<30; ++i)
{
//We cannot know with value is dequeued, but we can test
//that its range is between 0 and 29 :)
int dequeuedVal = queue->dequeue();
#if 0
std::cout << "Main: Dequeueing " << dequeuedVal << std::endl;
fflush(stdout);
#endif
CPPUNIT_ASSERT_EQUAL(true, (dequeuedVal >= 0 && dequeuedVal <= 29));
//After the first 6 values consumed, we let start the other two threads :p
if (i == 5)
{
producer2->start();
producer3->start();
}
}
producer1->join();
producer2->join();
producer3->join();
CPPUNIT_ASSERT_EQUAL(true, queue->isEmpty());
delete producer1;
producer1 = NULL;
delete producer2;
producer2 = NULL;
delete producer3;
producer3 = NULL;
}
void testNConsumerNProducer()
{
//Ensure that the queue is empty
CPPUNIT_ASSERT_EQUAL(true, queue->isEmpty());
//We create 3 producer therads. Each of these will insert into the queue 10 elements.
TestThread *producer1 = new TestThread(0, "Thread-producer-1", true);
TestThread *producer2 = new TestThread(10, "Thread-producer-2", true);
TestThread *producer3 = new TestThread(20, "Thread-producer-3", true);
//And... we create 3 consumer threads. Each of these will read a maximum of 10 elements.
//This is only a test case, not the reality
TestThread *consumer1 = new TestThread(0, "Thread-consumer-1", false);
TestThread *consumer2 = new TestThread(0, "Thread-consumer-2", false);
TestThread *consumer3 = new TestThread(0, "Thread-consumer-3", false);
//Let's the three consumers wait for data...
consumer1->start();
consumer2->start();
consumer3->start();
//Now, let's rock!
producer1->start();
producer2->start();
producer3->start();
producer1->join();
producer2->join();
producer3->join();
//We wait 1 sec that should be enough for consumers.
sleep(1);
CPPUNIT_ASSERT_EQUAL(true, queue->isEmpty());
CPPUNIT_ASSERT_EQUAL(30, dequeues);
#if 0
std::cout << "Dequeues: " << dequeues << std::endl;
#endif
//For definition consumer threads have an infinite internal loop that wait data forever
delete producer1;
producer1 = NULL;
delete producer2;
producer2 = NULL;
delete producer3;
producer3 = NULL;
delete consumer1;
consumer1 = NULL;
delete consumer2;
consumer2 = NULL;
delete consumer3;
consumer3 = NULL;
}
};
#endif // SBLOCKINGQUEUE_TEST_H
| true |
41e7cc92438fc020fe17382097736c522f81293f | C++ | S4ltF1sh/SPOJ | /P141SUMB.cpp | UTF-8 | 519 | 2.953125 | 3 | [] | no_license | //P141SUMB - ROUND 1B - Hoán vị
#include <iostream>
#include <vector>
#include <string>
#include <cmath>
#include <algorithm>
using namespace std;
vector<int> DanhDau(5005, 0);
int main()
{
ios_base::sync_with_stdio();
cin.tie();
int n, tmp, Count = 0;
cin >> n;
for (int i = 1; i <= n; i++)
{
cin >> tmp;
DanhDau.at(tmp) = 1;
}
for (int i = 1; i <= n; i++)
{
if (DanhDau.at(i) == 0)
Count++;
}
cout << Count;
} | true |
8c2f0a5bfb9ceb7c3f8ca2d3a2629276d1714f49 | C++ | x-y-z/fast-neural-net | /src/activate_function.h | UTF-8 | 2,707 | 2.96875 | 3 | [
"Apache-2.0"
] | permissive | /*
* =====================================================================================
*
* Filename: activate_function.h
*
* Description:
*
* Version: 1.0
* Created: 02/04/2015 11:12:57 AM
* Revision: none
* Compiler: gcc
*
* Author: YOUR NAME (),
* Organization:
*
* =====================================================================================
*/
#ifndef __ACTIVATE_FUNCTION_H__
#define __ACTIVATE_FUNCTION_H__
#include <cassert>
#include <vector>
#include <cmath>
#include <algorithm>
using std::vector;
using std::max;
using std::min;
namespace ACT_FUNC
{
struct binary_linear
{
template<typename VALUE, typename WEIGHT>
static VALUE activate(const vector<VALUE> &input, const vector<WEIGHT> &weight)
{
assert(input.size() == weight.size());
VALUE output = 0;
for (unsigned int idx = 0; idx < input.size(); ++idx)
{
output += input.at(idx) * weight.at(idx);
}
return output;
}
template<typename VALUE, typename WEIGHT>
static WEIGHT derivative(VALUE output)
{
return 1.0;
}
template<typename VALUE, typename WEIGHT>
static VALUE threshold(VALUE output, VALUE threshold)
{
return (output > threshold) & 1;
}
};
struct linear
{
template<typename VALUE, typename WEIGHT>
static VALUE activate(const vector<VALUE> &input, const vector<WEIGHT> &weight)
{
assert(input.size() == weight.size());
VALUE output = 0;
for (unsigned int idx = 0; idx < input.size(); ++idx)
{
output += input.at(idx) * weight.at(idx);
}
return output;
}
template<typename VALUE, typename WEIGHT>
static WEIGHT derivative(VALUE output)
{
return 1.0;
}
template<typename VALUE, typename WEIGHT>
static VALUE threshold(VALUE output, VALUE)
{
return output;
}
};
struct sigmoid
{
template<typename VALUE, typename WEIGHT>
static VALUE activate(const vector<VALUE> &input, const vector<WEIGHT> &weight)
{
assert(input.size() == weight.size());
VALUE output = 0;
for (unsigned int idx = 0; idx < input.size(); ++idx)
{
output += input.at(idx) * weight.at(idx);
}
return 1./ (1.+ exp(-max(min(output,(VALUE)500),(VALUE)-500)));
}
template<typename VALUE, typename WEIGHT>
static WEIGHT derivative(VALUE output)
{
return output * (1 - output);
}
template<typename VALUE, typename WEIGHT>
static VALUE threshold(VALUE output, VALUE)
{
return output;
}
};
};
#endif
| true |
cf29c34e172410d20b8730d33bee3532c077f715 | C++ | aivaraskriksciunas/Home-Defence | /src/characters/Bullet.h | UTF-8 | 663 | 2.78125 | 3 | [] | no_license | #pragma once
#include <cmath>
#include "Ghost.h"
#define BULLET_SIZE 8
class Bullet {
public:
Bullet( int posx, int posy, int direction );
void move();
int checkCollisionWithGhost( std::vector<Ghost*>* ghostList );
int getDamage();
int getX();
int getY();
bool isDead();
private:
float posx, posy;
int direction;
const int bulletSpeed = 8;
const int damage = 100;
//bullet lifespan in seconds since launch
const int lifespan = 3;
//each bullet can last a certain amount of time only.
//this timer is to check how much time has passed
sf::Clock timeSinceLaunch;
};
| true |
b6128817339e6edb66d87762c88c94eff4c02101 | C++ | iAmmarTahir/XML-Checker | /XML/XML.h | UTF-8 | 723 | 3.265625 | 3 | [] | no_license | #ifndef XML_H
#define XML_H
#include <iostream>
#include "Stack.h"
using namespace std;
class XML
{
private:
int lineNumber;
string tag;
public:
XML();
XML(const int& _lineNumber,const string& _tag);
~XML();
friend ostream& operator<<(ostream& cout, const XML &rhs);
bool operator==(const string &rhs);
};
XML::XML()
{
lineNumber = 0;
tag = "";
}
XML::~XML()
{}
XML::XML(const int& _lineNumber, const string& _tag)
{
lineNumber = _lineNumber;
tag = _tag;
}
ostream& operator<<(ostream& cout, const XML &rhs)
{
cout << "<" << rhs.tag.c_str() << ">" << " on line number: " << rhs.lineNumber << '.' << endl;
return cout;
}
bool XML::operator==(const string& rhs)
{
return tag.compare(rhs) == 0;
}
#endif | true |
a0296f54e44f4a126ecd1ed64149eb572901849a | C++ | ArashSameni/AP_IUT | /Exercises/10/1.Todo List/Task.cpp | UTF-8 | 1,158 | 2.71875 | 3 | [] | no_license | #include "Task.h"
#include "file.h"
#include <QDebug>
const QString Task::FILENAME = "tasks.json";
int Task::tasksCount = 0;
QJsonObject Task::getTaskAsJson(int id)
{
return getObject(FILENAME, QString::number(id));
}
Task Task::getTask(QJsonObject &obj)
{
Task task(obj["fUsername"].toString(),
obj["title"].toString());
task.id = obj["id"].toInt();
task.isFinished = obj["isFinished"].toBool();
return task;
}
Task Task::getTask(int id)
{
QJsonObject obj = getTaskAsJson(id);
return getTask(obj);
}
Task::Task(QString fUsername, QString title)
{
this->fUsername = fUsername;
this->title = title;
}
void Task::check()
{
isFinished = true;
}
void Task::unCheck()
{
isFinished = false;
}
void Task::save()
{
if(!id)
id = ++tasksCount;
QJsonObject obj;
obj["id"] = id;
obj["fUsername"] = fUsername;
obj["title"] = title;
obj["isFinished"] = isFinished;
saveObject(FILENAME, QString::number(id), obj);
}
void Task::remove(int id)
{
removeObject(FILENAME, QString::number(id));
}
void Task::remove()
{
removeObject(FILENAME, QString::number(id));
}
| true |
e32d22e19cd61fdc3de9492cc22e65c33d49d645 | C++ | kardinal95/multisort_urfu | /multisort_ui/arrays.cpp | UTF-8 | 766 | 4 | 4 | [] | no_license | #include <iostream>
#include <time.h>
#include "arrays.h"
using namespace std;
/*
Fills array with random integers
Input: arr - pointer to array, size - size of array
*/
void fill_random(int * arr, int size)
{
//Generate new seed
srand((unsigned)time(NULL));
// Fill the array
for (int i = 0; i<size; i++)
{
arr[i] = rand();
}
}
/*
Prints the content of array
Input: arr - pointer to array, size - size of array
*/
void print_array(int * arr, int size)
{
printf_s("Contents of array:\n");
// Check if the size > 0
if (size < 1)
{
printf_s("none.\n");
}
else
{
// Print all but the last
for (int i = 0; i<size-1; i++)
{
printf_s("%d, ", arr[i]);
}
// Pretty print the last with '.' on the end
printf_s("%d.\n", arr[size-1]);
}
} | true |
7e75d2ed4f069487cb65845b90d46835bfbd48e7 | C++ | mohmahkho/competitive-programming | /src/data-structure/sparse_table.cc | UTF-8 | 1,349 | 2.625 | 3 | [] | no_license | template<typename T, bool idempotent, typename F = function<T(const T&, const T&)>>
struct SparseTable {
int n;
F f;
vector<int> lg2;
vector<vector<T>> t;
SparseTable(const vector<T>& a, F f_)
: n(a.size()), f(f_) {
lg2.assign(n + 1, 0);
for(int i = 2; i <= n; ++i) {
lg2[i] = lg2[i >> 1] + 1;
}
t.assign(n, vector<T>(lg2[n] + 1));
for(int i = 0; i < n; ++i) {
t[i][0] = a[i];
}
for(int j = 1; j <= lg2[n]; ++j) {
for(int i = 0; i + (1 << j) - 1 < n; ++i) {
t[i][j] = f(t[i][j - 1], t[i + (1 << (j - 1))][j - 1]);
}
}
}
void push_back(T x) {
++n;
lg2.push_back(0);
if(n >= 2) lg2[n] = lg2[n >> 1] + 1;
t.push_back({x});
for(int j = 1; j <= lg2[n]; ++j) {
int i = n - (1 << j);
if(t[i].size() <= j) t[i].push_back(T());
t[i][j] = f(t[i][j - 1], t[i + (1 << (j - 1))][j - 1]);
}
} // O(lgn)
template<bool trigger = idempotent>
enable_if_t<trigger, T> query(int l, int r) {
int j = lg2[r - l + 1];
return f(t[l][j], t[r - (1 << j) + 1][j]);
} // O(1)
template<bool trigger = idempotent>
enable_if_t<!trigger, T> query(int l, int r) {
if(l == r) return t[l][0];
int j = lg2[r - l + 1];
if(l + (1 << j) - 1 == r) return t[l][j];
return f(t[l][j], query(l + (1 << j), r));
} // O(lgn)
};
| true |
1502d64da8c2d0a8f623273b1d4a9eca417721c4 | C++ | pjared/Pioneer-Simulator | /Path.h | UTF-8 | 27,674 | 3.15625 | 3 | [] | no_license | #ifndef PATH_H
#define PATH_H
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
class Path {
private:
string currentLoc = "Navoo";
string nextLoc = "Mount Pisgah";
int famNum = 6; // make this a random number between 3 and 6, family number will deplete food faster
int numFood = 3;
int helpedMan = 0; //0 = didn't get event, 1 = didn't help, 2 = Did help
int wheelHelp = 0; //0 = didn't get event, 1 = didn't help, 2 = Did help
int gotWolf = false; //0 = didn't get event, 1 = didn't help, 2 = Did help
bool hasWolf = false;
bool wardedFox = false;
public:
int getRand() {
srand(time(NULL));
int randNum = rand();
return randNum;
}
void start() {
cout << "\n ----------------------------------------------START OF GAME : NAUVOO------------------------------------ " << endl;
currentLoc = "Navoo";
cout << "The Missouri Executive Order 44 has just been issued by Governer Boggs and you have just moved to Nauvoo with your family. You have been ";
cout << "told by Brigham to lead a handcart company West to Salt Lake valley to be one of the first groups to go see the new promised land. ";
cout << "Although reluctant to leave after just relocating, you have faith to do as commanded." << endl;
cout << "\nYou start your journey in " << currentLoc << " with " << famNum << " family members." << endl;
//the first trek can be an outline of how the game will work
//coding an outline for how events will work
cout << "As you play the game, your last location will be marked so you will have a checkpoint in case you lose. You lose when your hunger ";
cout << "hits 0. As you go from location to location, there is a random chance for events for happen, and some locations have garunteed events to happen. ";
cout << "Your choices will influence you gameplay. While some this is left to chance, your choices can result in losing family members or substantial ";
cout << "amounts of food. After reaching a new location, you will be given a small menu to go hunting, play a pioneer game, sing, or sleep. Keep in mind ";
cout << "that you can only choose one thing to do when given the menu." << endl;
cout << "Have you read the basics of the game? Answer \"yes\" if so (without the quotation marks)" << endl;
string userInput;
do {
cout << "ENTER ANSWER: ";
cin >> userInput;
} while (userInput != "yes");
cout << "Great! Your handcart company starts it's journey towards Mount Pisgah" << endl;
system("pause");
mountPisgah();
}
void mountPisgah() {
currentLoc = "Mount Pisgah";
//nextLoc = "Winter Quarters";
cout << "\n ----------------------------------------------MOUNT PISGAH------------------------------------ " << endl;
cout << "\nYou have made it to " << currentLoc << "." << endl;
cout << "Now the menu that pops up at every location stop will happen." << endl;
system("pause");
campStop();
system("pause");
cout << "You come to a fork in the road. The sign that points to the left says \"Winter Quarters\" ";
cout << "And the sign the points to the right says \"Confluence Point\"." << endl;
string userInput;
bool goodOutput;
do {
cout << "Would you like to go:\n -Left\n -Right" << endl;
cout << "Remember to type answers in all lowercase" << endl;
cout << "ENTER ANSWER: ";
cin >> userInput;
if (userInput == "left") {
goodOutput = true;
winterQuarters();
}
else if (userInput == "right") {
goodOutput = true;
confluencePoint();
}
else {
cout << "Not a direction, try again." << endl;
cout << "Remember to type in lowercase only." << endl;
system("pause");
goodOutput = false;
}
} while (goodOutput == false);
}
void winterQuarters() {
currentLoc = "Winter Quarters";
//nextLoc = "Confluence Point";
cout << "\n ----------------------------------------------WINTER QUARTERS------------------------------------ " << endl;
cout << "\nYou have made it to " << currentLoc << "." << endl;
//Garunteed event
kidWander();
system("pause");
fortLaurence();
}
void confluencePoint() {
currentLoc = "Confluence Point";
cout << "\n ----------------------------------------------CONFLUENCE POINT------------------------------------ " << endl;
cout << "\nYou have made it to " << currentLoc << "." << endl;
system("pause");
campStop();
system("pause");
//Garunteed event
childBirth();
system("pause");
fortLaurence();
}
void fortLaurence() {
currentLoc = "Fort Laurence";
cout << "\n ----------------------------------------------FORT LAURENCE------------------------------------ " << endl;
cout << "\nYou have made it to " << currentLoc << "." << endl;
system("pause");
campStop();
system("pause");
// Garunteed random event:
chooseEvent();
int chosenPath = splitPath();
system("pause");
if (chosenPath == 1) { //left - Indians
indepRock();
}
if (chosenPath == 2) { // right - Wolf
southPass();
}
}
void indepRock() {
currentLoc = "Independance Rock";
cout << "\n ----------------------------------------------INDEPENDANCE ROCK-------------------------------- " << endl;
cout << "\nYou have made it to " << currentLoc << "." << endl;
system("pause");
campStop();
system("pause");
//Chance to get indian villiage or Indian attack
system("pause");
echoCanyon();
}
void southPass() {
currentLoc = "South Pass";
nextLoc = "Echo Canyon";
cout << "\n ----------------------------------------------SOUTH PASS------------------------------------ " << endl;
cout << "\nYou have made it to " << currentLoc << "." << endl;
system("pause");
campStop();
system("pause");
//If they don't have the pet wolf, then there will be an attack
system("pause");
echoCanyon();
}
void echoCanyon() {
currentLoc = "Echo Canyon";
nextLoc = "Salt Lake Valley";
cout << "\n ----------------------------------------------ECHO CANYON------------------------------------ " << endl;
cout << "\nYou have made it to " << currentLoc << "." << "You know that the next stop will be " << nextLoc << "!" << endl;
system("pause");
campStop();
system("pause");
// random event:
chooseEvent();
system("pause");
end();
}
void end() {
cout << "\n ----------------------------------------------SALT LAKE VALLEY------------------------------- " << endl;
cout << "\nYou have made it to salt Lake Valley! Great job" << endl;
printStats();
cout << "\n ------------------------------------------------END OF GAME--------------------------------------------- " << endl;
system("pause");
}
void printStats() {
cout << "You ended with " << famNum << " family members and " << numFood << " food left." << endl;
//WHEEL wheelHelp
if (wheelHelp == 1) {
cout << "You decided to have the company go ahead of you instead of getting help. One man army. You also had a fox invade your camp, " << endl;
if (wardedFox == true) {
cout << "but your pet wolf warded him off." << endl;
}
else {
cout << "and lost food." << endl;
}
}
if (wheelHelp == 2) {
cout << "When in need of help and your wheel broke, you had your company stop and help you. Hooray for teamwork." << endl;
}
//0 = didn't get event, 1 = didn't get help, 2 = Did get help
//MAN
if (helpedMan == 1) {
cout << "When a man was in need, you instead walked past him. Good job you saint." << endl;
}
if (helpedMan == 2) {
cout << "When a man was in need, you stopped and save his life. Good job you saint." << endl;
}
//0 = didn't get event, 1 = didn't help, 2 = Did help
//WOLF
if (gotWolf == true) {
cout << "When going back to get your son, you added a baby wolf to your family." << endl;
if (hasWolf == true) {
cout << "You kept him all the way to Salt Lake." << endl;
}
else {
cout << "The baby was returned to it's family and you avoided being attacked by wolves." << endl;
}
}
//gotWolf
}
// Finish song
void sing() {
int randNum = (getRand() % 2);
if (randNum == 0) {
cout << "Country Roads. Take me home." << endl;
cout << "Almost heaven, West Virginia" << endl;
cout << "Blue Ridge Mountains, Shenandoah River" << endl;
cout << "Life is old there, older than the trees" << endl;
cout << "Younger than the mountains, growing like a breeze" << endl;
cout << "Country roads, take me home" << endl;
cout << "To the place I belong" << endl;
cout << "West Virginia, mountain mama" << endl;
cout << "Take me home, country roads" << endl;
}
else {
cout << "Pioneer children sang as they walked and walked and walked and walked. " << endl;
cout << " Pioneer children sang as they walked and walked and walked and walked. " << endl;
cout << "They washed at streams and worked and played. " << endl;
cout << " Sundays they camped and read and prayed. " << endl;
cout << "Week after week, they sang as they walked and walked and walked and walked and walked. " << endl;
}
}
//Add randomizer when done
void hunt() {
if (hasWolf == true) {
int randNum = (getRand() % 2);
//can get a food between 2 & 3
if (randNum == 0) {
cout << "Your pet wolf leads you to group of rabbits. +2 Food" << endl;
numFood += 2;
}
else {
cout << "Your pet wolf leads you to deer drinking water by a river. +3 Food" << endl;
numFood += 2;
}
}
else {
int randNum = (getRand() % 3);
// can get between 1-3
if (randNum == 0) {
cout << "You check your traps to a rabbit. +1 Food" << endl;
numFood += 1;
}
else if (randNum == 1) {
cout << "You check your traps to a fox. +2 Food" << endl;
numFood += 2;
}
else {
cout << "Along the way to check your traps, you see a deer. You aim your musket and take it down. +3 Food" << endl;
numFood += 3;
}
}
}
//Need to do randomizer to randNum
void cornHole() {
int userPower;
int numAces = 0;
int randNum = ((getRand() % 3) + 5);
bool goodInput = false;
cout << "\n ----------------------------------------------MINIGAME: CORNHOLE--------------------------- " << endl;
cout << "You get 3 shots. If the power level you choose matches the random number generated you make it." << endl;
do {
cout << "Choose a power level from 5-7" << endl;
cin >> userPower;
if (userPower >= 5 && userPower <= 7) {
goodInput = true;
}
else {
goodInput = false;
cout << "Not an input. Try again." << endl;
}
} while (goodInput == false);
if(userPower == randNum) {
cout << "Perfect shot!" << endl;
numAces += 1;
}
else {
cout << "Miss!" << endl;
}
do {
cout << "Choose a power level from 5-7" << endl;
cin >> userPower;
if (userPower >= 5 && userPower <= 7) {
goodInput = true;
}
else {
goodInput = false;
cout << "Not an input. Try again." << endl;
}
} while (goodInput == false);
if (userPower == randNum) {
cout << "Perfect shot!" << endl;
numAces += 1;
}
else {
cout << "Miss!" << endl;
}
do {
cout << "Choose a power level from 5-7" << endl;
cin >> userPower;
if (userPower >= 5 && userPower <= 7) {
goodInput = true;
}
else {
goodInput = false;
cout << "Not an input. Try again." << endl;
}
} while (goodInput == false);
if (userPower == randNum) {
cout << "Perfect shot!" << endl;
numAces += 1;
}
else {
cout << "Miss!" << endl;
}
cout << "\nYou made " << numAces << "/3 shots." << endl;
cout << "\n ----------------------------------------------END OF MINIGAME------------------------------ " << endl;
system("pause");
}
void hungerCheck() {
if (numFood == 0) {
cout << "\n -----------------------------------------OUT OF FOOD: GAME OVER------------------------ " << endl;
cout << "You ran out of food, you have lost the game. The page will now exit. Please hit play again if you'd like to do another game" << endl;
system("pause");
exit(0);
}
}
//Done
void campStop() {
hungerCheck();
cout << "Your company all gets in a large circle to form camp and rest." << endl;
cout << "You are at " << numFood << " food left." << endl;
string userInput;
bool goodOutput;
do {
cout << "Would you like to:\n -Hunt\n -Play a game(answer: play)\n -sing\n -sleep" << endl;
cout << "Please remember that you only get to do one option" << endl;
cout << "Remember to type answers in all lowercase" << endl;
cout << "ENTER ANSWER: ";
cin >> userInput;
if (userInput == "hunt") {
goodOutput = true;
hunt();
}
else if (userInput == "play") {
goodOutput = true;
cornHole();
}
else if (userInput == "sing") {
goodOutput = true;
sing();
}
else if (userInput == "sleep") {
goodOutput = true;
}
else {
cout << "\nNot an option, try again.\n" << endl;
//cout << "Remember to type in lowercase only." << endl;
goodOutput = false;
//system("pause");
}
} while (goodOutput == false);
cout << "You get your family together for a nice meal. -1 Food" << endl;
numFood -= 1;
cout << "You now have " << numFood << " food left." << endl;
}
/*GARUNTEED EVENTS*/
//Done
void childBirth() {
famNum += 1;
cout << "While along the trail, your pregnant wife goes into labor. You now have " << famNum << " family memebers" << endl;
};
//Done
void kidWander() {
cout << "While walking along the path, your spouse tells you that one of your boys have gone missing. You assume they ";
cout << "have wandered off the path while walking, and are now no longer with the group." << endl;
bool inputCheck;
string userInput;
do {
cout << "Would you like to : \n -Hope he makes his way back(answer: hope)\n -Go looking for him(answer: look)" << endl;
cout << "Remember to type answers in all lowercase" << endl;
cout << "ENTER ANSWER: ";
cin >> userInput;
if (userInput == "hope") {
cout << "\nHmmm. Not sure why you chose that one." << endl;
cout << "While you hoped that the boy would have gotten picked up by another family in the handcart company, ";
cout << "you don't see him at the campfire that night. What a good parent you are." << endl;
famNum -= 1;
cout << "You now have " << famNum << " family memebers" << endl;
inputCheck = true;
}
else if (userInput == "look") {
cout << "\nYou head back while your family continues to trek along. You take some food in case the journey is long. ";
cout << "You find your son petting a small wolf that has also wandered from it's pack. You feed the wolf food you brought. ";
cout << "You now have added a pet to the family and will make hunting easier. ";
cout << "The wolf might also need to be returned to it's family. This might be useful later on." << endl;
hasWolf = true;
gotWolf = true;
inputCheck = true;
}
else {
cout << "Remember to type in lowercase only." << endl;
cout << "Not an option, try again." << endl;
system("pause");
inputCheck = false;
}
} while (inputCheck == false);
}
//Need to add randomizer in left path
int splitPath() {
cout << "While along the trail, theres a fork in the road. It's not marked on you map of where your supposed to go.";
cout << "On the left you see a tree with a small carving, likely the territory marking of Native Americans. The carving is unknown ";
cout << "to be of a hostile or friendly tribe." << endl;
cout << "On your right up ahead further on the path you see a deer carcass on the trail, torn apart likely by wolves." << endl;
bool inputCheck;
string userInput;
do {
cout << "Which path would you like to go?\n -Left\n -Right" << endl;
cout << "Remember to type answers in all lowercase" << endl;
cout << "ENTER ANSWER: ";
cin >> userInput;
if (userInput == "left") {
int randNum = (getRand() % 2);
cout << "\nYour company takes the left. Many people seemed worried after noticing the carving themselves.\n" << endl;
if (randNum == 0) {
indianAttack();
}
else {
indianTrade();
}
inputCheck = true;
return 1;
}
else if (userInput == "right") {
cout << "\nYour company walks around the dead deer. In the distance, you see a single wolf on the top of a cliff" << endl;
wolfAttack();
inputCheck = true;
return 2;
}
else {
cout << "Not a direction, try again." << endl;
inputCheck = false;
//system("pause");
}
} while (inputCheck == false);
//cout << "Well that wasn't suppose to happen" << endl;
return 0;
}
void wolfAttack() {
cout << "\nWhile your handcart company has gathered to rest, you hear howls off in the distance getting closer and closer ";
cout << "Eyes glow around your camp." << endl;
if (hasWolf == true) {
cout << "The baby wolf begins to howl and the sourrounding wolves quiet down. The baby wolf licks your face before walking";
cout << " out into the dark to join its family. The other wolves ignore you." << endl;
hasWolf = false;
}
else {
bool inputCheck;
string userInput;
do {
cout << "What would you like to do?\n -Fight\n -Warn the wolves off with fire(answer: warn)\n" << endl;
cout << "Remember to type answers in all lowercase" << endl;
cout << "ENTER ANSWER: ";
cin >> userInput;
if (userInput == "fight") {
cout << "The company fires their muskets where they see eyes. You hear a cry after firing your musket at eyes.";
cout << "The wolves howl one last time and leave." << endl;
numFood += 2;
cout << "You now have " << numFood << " food from the killed wolf." << endl;
inputCheck = true;
}
else if (userInput == "warn") {
cout << "You craft a makeshift torch along with the others and wave them at the wolves as they get closer." << endl;
cout << "They are warded off for now, but come back during the night and kill one of your oxen while the company is asleep." << endl;
numFood -= 1;
cout << "You now have " << numFood << " food." << endl;
inputCheck = true;
}
else {
cout << "Not an option, try again." << endl;
inputCheck = false;
system("pause");
}
} while (inputCheck == false);
}
}
// Add randomizer in prayer
void indianAttack() {
cout << "\nWhile your handcart company has gathered to rest, you hear multiple screeches accompanying the ";
cout << "stomping of hooves on the ground around you. You realize that indians are circling around you." << endl;
bool inputCheck;
string userInput;
do {
cout << "What would you like to do?\n -Fight\n -Hope they go away(answer: hope)\n -Pray" << endl;
cout << "Remember to type answers in all lowercase" << endl;
cout << "ENTER ANSWER: ";
cin >> userInput;
if (userInput == "fight") {
string userInput2;
do {
cout << "Would you like to: \n -Fire a warning shot(answer: warn)\n -Prepare the men for close quarter combat(answer: prepare)" << endl;
cin >> userInput2;
if (userInput2 == "warn") {
cout << "The natives are scared of the loud pop and the flash of light. They leave." << endl;
inputCheck = true;
}
else if (userInput2 == "prepare") {
cout << "The natives get closer and closer and a fight ensues. They leave soon after but you discover ";
cout << "that your eldest son has been fatally wounded." << endl;
famNum -= 1;
cout << "You now have " << famNum << "family members. You bury your eldest son at your next camp stop." << endl;
inputCheck = true;
}
else {
cout << "Not an option, try again." << endl;
inputCheck = false;
system("pause");
}
} while (inputCheck == false);
inputCheck = true;
}
else if (userInput == "hope") {
//steal all of your food
cout << "The indians sorround you and steal all of your food." << endl;
numFood = 1;
cout << "You now have " << numFood << "food left." << endl;
inputCheck = true;
}
else if (userInput == "pray") {
int randNum = (getRand() % 2);
if (randNum == 1) {
cout << "The noise dies down and the Indians leave without continuing their attack. Only you know why they stopped." << endl;
}
else {
cout << "The indians sorround you and steal all of your food." << endl;
numFood = 1;
cout << "You now have " << numFood << "food left." << endl;
}
inputCheck = true;
}
else {
cout << "Not an option, try again." << endl;
inputCheck = false;
system("pause");
}
} while (inputCheck == false);
}
//Done
void indianTrade() {
cout << "You see an Indian village up ahead. A native approaches you and speaks to a language you cannot understand. ";
cout << "You can't tell wether the man is friendly or hostile due to a blank expression on his face" << endl;
bool inputCheck;
string userInput;
do {
cout << "What would you like to do?\n -Wave to him(answer: wave)\n -Ignore the man(answer: ignore)\n" << endl;
cout << "Remember to type answers in all lowercase" << endl;
cout << "ENTER ANSWER: ";
cin >> userInput;
if (userInput == "ignore") {
cout << "You smile while passing the strange man. He gets your message and walks back to his village" << endl;
inputCheck = true;
}
else if (userInput == "wave") {
cout << "The man offers you some meat and points to the animal pelts you have drying on top of your cart. +2 Food" << endl;
numFood += 2;
cout << "You now have " << numFood << " food." << endl;
inputCheck = true;
}
else {
cout << "Not an option, try again." << endl;
inputCheck = false;
system("pause");
}
} while (inputCheck == false);
}
/*EVENTS*/
//Need to finish these, along with add a trade function for wandering man and indian village -
// All of these should only be able to happen once
//randomizer in choosing
void chooseEvent() {
bool relief = false;
bool wheel = false;
bool tradesman = false;
bool hurtMan = false;
int randNum = (getRand() % 4);
if (randNum == 0 && relief == false) {
reliefCart();
relief = true;
}
else if (randNum == 1 && wheel == false) {
wheelBreak();
wheel = true;
}
else if (randNum == 2 && tradesman == false) {
wanderingTradesman();
tradesman = true;
}
else if (randNum == 3 && hurtMan == false) {
manToHelp();
hurtMan = true;
}
}
//Done
void reliefCart() {
numFood += 5;
cout << "In the distance you see a small group of handcarts, the cart leading the group has a red cross on the side of the cart. ";
cout << "They are here with food."<< endl;
cout << "You have been given +5 food. Your food is now at " << numFood << "." << endl;
//Somehow max out hunger, but still can lose it to an indian/wolf attack
}
//Done
void wheelBreak() {
cout << "Your cart goes over a bump and you hear a crack. You ignore it at first, but while going over a pothole your ";
cout << "wheel breaks and your cart now stuck. You get other members to help carry the cart to the side of the road." << endl;
bool inputCheck;
string userInput;
do {
cout << "How would you like to approach him?\n -Tell the company to contine without you(answer: continue)";
cout << "\n -Have the company stop to help you(answer: stop)" << endl;
cout << "Remember to type answers in all lowercase" << endl;
cout << "ENTER ANSWER: ";
cin >> userInput;
if (userInput == "stop") {
wheelHelp = 2;
cout << "The company stops with you and the men gather to help fix the wheel. It is done in less than an hour" << endl;
inputCheck = true;
}
else if (userInput == "continue") {
wheelHelp = 1;
cout << "The company leaves and you fix the wheel, but have to camp for the night without them. ";
cout << "A fox comes in to steal some food."<< endl;
if (hasWolf == true) {
wardedFox = true;
cout << "Your pet wolf wakes up and wards off the fox. You don't lose any food." << endl;
}
else {
if (numFood <= 2) {
numFood -= 1;
cout << "-1 Food. You now have " << numFood << "food." << endl;
}
else {
numFood -= 2;
cout << "-2 Food. You now have " << numFood << "food." << endl;
}
}
inputCheck = true;
}
else {
cout << "Not an option, try again." << endl;
inputCheck = false;
system("pause");
}
} while (inputCheck == false);
}
//Done
void manToHelp() {
helpedMan = 1; //0 = didn't get event, 1 = didn't help, 2 = Did help
cout << "Along the path you see a man lying face down on the path. At first he seems dead, but he is stil breathing" << endl;
bool inputCheck;
string userInput;
do {
cout << "Would you like to:\n Help the man(answer: help - cost: -1 food)\n -Not my problem, someone else will help(answer: ignore)" << endl;
cout << "Remember to type answers in all lowercase" << endl;
cout << "ENTER ANSWER: ";
cin >> userInput;
if (userInput == "help") {
helpedMan = 2;
cout << "Help the man up, bandage him " << endl;
numFood -= 1;
cout << "You now have " << numFood << " food." << endl;
inputCheck = true;
}
else if (userInput == "ignore") {
cout << "The company wonders why you didn't stop to help the man but follow your example and leave him there. ";
cout << "The man lies there longer until he passes away. Hope you feel good about yourself now"<< endl;
inputCheck = true;
}
else {
cout << "Not an option, try again." << endl;
inputCheck = false;
system("pause");
}
} while (inputCheck == false);
}
//Done
void wanderingTradesman() {
cout << "While traveling a long the trail, a man that looks like a game hunter approaches your company" << endl;
bool inputCheck;
string userInput;
do {
cout << "How would you like to approach him?\n -Greet\n -Ignore\n -Ward off(answer: ward)" << endl;
cout << "Remember to type answers in all lowercase" << endl;
cout << "ENTER ANSWER: ";
cin >> userInput;
if (userInput == "greet") {
cout << "The man stops to talk to you asking to trade. You give him some supplies in exchange for meat" << endl;
numFood += 2;
cout << "You now have " << numFood << " food." << endl;
inputCheck = true;
}
else if (userInput == "ignore") {
cout << "The man waves to you as you pass him" << endl;
inputCheck = true;
}
else if (userInput == "ward") {
cout << "You tell the man to keep his distance. He sighs and walks away, ";
cout << "it sure would have been nice to trade with him" << endl;
inputCheck = true;
}
else {
cout << "Not an option, try again." << endl;
inputCheck = false;
system("pause");
}
} while (inputCheck == false);
}
};
#endif
| true |
401aab5ab880125c494e796988f31f1b0d74e36d | C++ | dolremi/data_structure | /Linked_list/Kth/main.cpp | UTF-8 | 1,355 | 3.921875 | 4 | [] | no_license | #include "LinkedList.h"
#include <iostream>
using namespace std;
// The problem is find the kth to last element of a singly linked list
// There are three versions of solutions to this problem:
// 1. If the linked list size is known, jsut iterate though the list to find the (size-k)th element in the list
// 2. A recursive version to find the kth of the last element
// 3. A iterative version utilized the "runne" technqiue
int main(int argc, char *argv[]){
LinkedList myList;
int val,size, k, select;
cout << "please insert the size of linked list" << endl;
cin >> size;
for(int i = 0;i < size ; i++){
cin >> val;
myList.append(val);
}
cout << "Now the list is " << endl;
myList.display();
cout << endl;
cout << "which one you want to see?" << endl;
cin >> k;
cout << "which version? 1. iteration 2. recursive" << endl;
cin >> select;
if(select == 1){
ListNode *chosen = myList.kthlastIter(k);
if(chosen)
cout << "Now the value of node is " << chosen->val << endl;
else
cout << "k is out of the range" << endl;
}else{
int m = 0;
ListNode *chosen = myList.kthlastRecur(myList.currentHead(),m, k);
if(chosen)
cout << "Now the value of node is " << chosen->val << endl;
else
cout << "k is out of the range" << endl;
}
return 0;
}
| true |
5b120fc87edbd832542306843610ce497ad3480a | C++ | BasicAlgorithm/SpaceSoccer | /SpaceSoccer/Classes/2do backups/Bombs.cpp | UTF-8 | 456 | 2.515625 | 3 | [] | no_license | #include "Bombs.h"
Bombs * Bombs::create()
{
Bombs* ret = new (std::nothrow) Bombs;
ret->initWithFile("bomba.png");
//ret->setTag(TAG_DOG);
ret->scheduleUpdate();
if (ret) {
ret->autorelease();
return ret;
}
else
{
CC_SAFE_DELETE(ret);
return nullptr;
}
}
Bombs::Bombs()
{
_duration = 0.0f;
_remove = false;
}
Bombs::~Bombs()
{
}
void Bombs::update(float dt)
{
_duration += dt;
}
void Bombs::marktoremove()
{
_remove = true;
}
| true |
f9a6b6f83f733b6656289fbec0ba9b7e510fa7d2 | C++ | Jonnipolar/Red-Thunder-s-Pizza-Palace | /Red Thunder's Pizza Palace/src/Models/PizzaSize.cpp | WINDOWS-1250 | 469 | 3.15625 | 3 | [] | no_license | #include "PizzaSize.h"
PizzaSize::PizzaSize() {
this->_size = "Str";
this->price = 1500;
}
PizzaSize::PizzaSize(string _size, int price){
this->_size = _size;
this->price = price;
}
string PizzaSize::get_size() {
return this->_size;
}
int PizzaSize::get_price() {
return this->price;
}
ostream& operator << (ostream& out, const PizzaSize& psize) {
out << psize._size << ":" << psize.price << endl;
return out;
}
| true |
b81ebc3bc4ef06243cf15e627c84688c0e33ed39 | C++ | TiAmoPlus/PAT-BaseLevel | /1013. 数素数 (20)/源.cpp | GB18030 | 648 | 3.015625 | 3 | [] | no_license | #include<stdio.h>
#include<math.h>
bool sushu(int n) {//жһǷ
for (int t = 2; t <= sqrt(n); t++) {
if (n%t == 0) {
return false;
}
}
return true;
}
int main() {
bool temp;
int M, N,num = 0, n = 1,huanghang=0;
scanf("%d%d", &M, &N);
while (true)
{
n++;
temp = sushu(n);
if (temp == true) {
num++;
if (num >= M&&num <= N) {
huanghang++;
if (huanghang%10==1) {
printf("%d", n);
}
else {
if (huanghang % 10 == 0) {
printf(" %d\n", n);
}
else
{
printf(" %d", n);
}
}
}
else if (num > N) {
break;
}
}
}
return 0;
} | true |
374c3dcca7770de6379959ca59533358b7f84d7f | C++ | Ibrahim5aad/OpenGL-WorldWithMouseAndKeyboardControls | /vertex.h | UTF-8 | 361 | 2.84375 | 3 | [] | no_license | #pragma once
#include<gl\glm\glm.hpp>
using namespace std;
using namespace glm;
struct vertex
{
glm::vec3 position;
glm::vec3 normal;
glm::vec2 texture;
public:
vertex() = default;
vertex(vec3 _position) :position{ _position }, normal(0, 0, 0){
}
vertex(vec3 pos, vec3 norm, vec2 text) {
position = pos;
normal = norm;
texture = text;
}
}; | true |
61acacc0b0c2362fdd594d66e75411380134a430 | C++ | monpeco/TDD-with-Catch2 | /unit-convertion/decimal_to_hex.cpp | UTF-8 | 3,609 | 3.46875 | 3 | [] | no_license | #define CATCH_CONFIG_MAIN
#include <iostream>
#include <cmath>
#include <sstream>
#include "catch.hpp"
std::string decimal_to_hex( std::string &_decimal);
std::string decimal_to_hex_digit( std::string &_decimal);
TEST_CASE("Test base case", "Given a string that represents a series of decimal numbers, returns its hexadecimal represtation"){
std::string str("");
std::string rstr = str;
REQUIRE( decimal_to_hex(rstr) == "");
}
TEST_CASE("Test decimal_to_hex case of 0", "Given a string that represents a series of decimal numbers, returns its hexadecimal represtation"){
std::string str("0");
std::string rstr = str;
REQUIRE( decimal_to_hex(rstr) == "0");
}
TEST_CASE("Test decimal_to_hex case of 2", "Given a string that represents a series of decimal numbers, returns its hexadecimal represtation"){
std::string str("2");
std::string rstr = str;
REQUIRE( decimal_to_hex(rstr) == "2");
}
TEST_CASE("Test decimal_to_hex case of 15", "Given a string that represents a series of decimal numbers, returns its hexadecimal represtation"){
std::string str("15");
std::string rstr = str;
REQUIRE( decimal_to_hex(rstr) == "f");
}
TEST_CASE("Test decimal_to_hex case of 14 4", "Given a string that represents a series of decimal numbers, returns its hexadecimal represtation"){
std::string str("14 4");
std::string rstr = str;
REQUIRE( decimal_to_hex(rstr) == "e 4");
}
TEST_CASE("Test decimal_to_hex case of 1 0 9 15", "Given a string that represents a series of decimal numbers, returns its hexadecimal represtation"){
std::string str("1 0 9 15");
std::string rstr = str;
REQUIRE( decimal_to_hex(rstr) == "1 0 9 f");
}
/* string -> string
* Given a string that represents a series of decimal numbers, returns its hexadecimal represtation
*/
std::string decimal_to_hex( std::string &_decimal){
std::string word_decimal = "";
std::string delimiter = " ";
std::string result;
for(std::string::size_type n = 0; n < _decimal.size(); n++){
if(_decimal.size() == 1){
result += decimal_to_hex_digit(_decimal);
}else{
if(_decimal[n] == ' ' || n == (_decimal.size() - 1) ){
result += decimal_to_hex_digit(word_decimal);
word_decimal="";
if(n<_decimal.size())
result += " ";
}else{
word_decimal += std::string(1,_decimal[n]);
}
}
}
//std::string token = s.substr(0, s.find(delimiter));
return result;
}
TEST_CASE("Test decimal_to_hex_digit case of 0", "Given a string that represents a single decimal digit, returns its hexadecimal represtation"){
std::string str("0");
std::string rstr = str;
REQUIRE( decimal_to_hex_digit(rstr) == "0");
}
TEST_CASE("Test decimal_to_hex_digit case of 7", "Given a string that represents a single decimal digit, returns its hexadecimal represtation"){
std::string str("7");
std::string rstr = str;
REQUIRE( decimal_to_hex_digit(rstr) == "7");
}
TEST_CASE("Test decimal_to_hex_digit case of 15", "Given a string that represents a single decimal digit, returns its hexadecimal represtation"){
std::string str("15");
std::string rstr = str;
REQUIRE( decimal_to_hex_digit(rstr) == "f");
}
/* string -> string
* Given a string that represents a single decimal digit, returns its hexadecimal represtation
*/
std::string decimal_to_hex_digit( std::string &_decimal){
const std::string hexdigits = "0123456789abcdef";
std::string::size_type n = 0;
char digit = 0;
std::stringstream(_decimal) >> n;
if(n < hexdigits.size())
digit = hexdigits[n];
std::string s(1, digit);
return s;
}
| true |
5e01d17472093d4bc0b4782ab995093f7e45c04c | C++ | estradjm/Code-Portfolio | /Control_Systems/AddressSign/AddressSignControl.ino | UTF-8 | 3,982 | 2.84375 | 3 | [
"Apache-2.0"
] | permissive | //Written by Ruben Marc Speybrouck - Modified by Jenniffer Estrada
// This code controls the address sign in the front door to
// automatically turn on at dusk and off at dawn. Since the
// sign uses 12V at 1000 mA, the Arduino cannot power it directly,
// therefore, the Arduino uses a solid state relay to control the
// sign.
// TODO: Need to get an adequate mosfet to control 12V, a small project box,
// small perf board, and a power supply for the Arduino.
// N Channel MOSFET: https://www.sparkfun.com/products/10213
// Short tutorial for the N Channel MOSFET: http://bildr.org/2012/03/rfp30n06le-arduino/
// constants won't change. Used here to
// set pin numbers:
const int ledPin = 13; // the number of the LED pin
// Variables will change:
int ledState = LOW; // ledState used to set the LED
unsigned long timeNow = 0;
unsigned long timeLast = 0;
//Time start Settings:
int startingHour = 18;
// set your starting hour here, not below at int hour. This ensures accurate daily correction of time
int seconds = 0;
int minutes = 29;
int hours = startingHour;
int days = 0;
//Accuracy settings
int dailyErrorFast = 0; // set the average number of milliseconds your microcontroller's time is fast on a daily basis
int dailyErrorBehind = 0; // set the average number of milliseconds your microcontroller's time is behind on a daily basis
int correctedToday = 1; // do not change this variable, one means that the time has already been corrected today for the error in your boards crystal. This is true for the first day because you just set the time when you uploaded the sketch.
void setup() {
// set up serial connection
Serial.begin(9600);
// set the digital pin as output:
pinMode(ledPin, OUTPUT);
}
void loop() { // put your main code here, to run repeatedly:
timeNow = millis()/1000; // the number of milliseconds that have passed since boot
seconds = timeNow - timeLast;
//the number of seconds that have passed since the last time 60 seconds was reached.
if (seconds == 60) {
timeLast = timeNow;
minutes = minutes + 1; }
//if one minute has passed, start counting milliseconds from zero again and add one minute to the clock.
if (minutes == 60){
minutes = 0;
hours = hours + 1; }
// if one hour has passed, start counting minutes from zero and add one hour to the clock
if (hours == 24){
hours = 0;
days = days + 1;
}
//if 24 hours have passed, add one day
if (hours ==(24 - startingHour) && correctedToday == 0){
delay(dailyErrorFast*1000);
seconds = seconds + dailyErrorBehind;
correctedToday = 1; }
//every time 24 hours have passed since the initial starting time and it has not been reset this day before, add milliseconds or delay the program with some milliseconds.
//Change these varialbes according to the error of your board.
// The only way to find out how far off your boards internal clock is, is by uploading this sketch at exactly the same time as the real time, letting it run for a few days
// and then determining how many seconds slow/fast your boards internal clock is on a daily average. (24 hours).
if (hours == 24 - startingHour + 2) {
correctedToday = 0; }
//let the sketch know that a new day has started for what concerns correction, if this line was not here the arduiono // would continue to correct for an entire hour that is 24 - startingHour.
//Serial.print("The time is: ");
//Serial.print(days);
//Serial.print(":");
//Serial.print(hours);
//Serial.print(":");
//Serial.print(minutes);
//Serial.print(":");
//Serial.println(seconds);
// Control the Address Sign with a Digital Output Pin
// Start at 9pm at night and end at 4am in the morning (out of daylight savings)
if (hours >= 21 || hours <= 4){
// if the LED sign is off, then turn it on
if (ledState == LOW)
ledState = HIGH;
else
ledState = HIGH;
// set the LED with the ledState of the variable:
digitalWrite(ledPin, ledState);
}
else {
digitalWrite(ledPin, LOW);
}
}
| true |
b2c7e53bb01624982fffa04ceca2c4a14ab7bfd9 | C++ | gmoryes/Coroutine | /coro.cpp | UTF-8 | 1,769 | 3.1875 | 3 | [] | no_license | #include <iostream>
#include <csetjmp>
#include <cstdio>
#include <algorithm>
using std::cout;
using std::endl;
struct Context {
Context(): low(nullptr), high(nullptr), stack(nullptr) {}
char *low;
char *high;
char* stack;
int size;
std::jmp_buf env;
};
Context a_ctx, b_ctx, run_ctx;
void store(Context &ctx) {
volatile char high;
ctx.high = (char*)&high;
if (ctx.stack != nullptr)
delete[] ctx.stack;
int size = std::abs(ctx.high - ctx.low);
ctx.stack = new char[size];
char *cur = ctx.low;
int i = 0;
while (cur != ctx.high) {
ctx.stack[i] = *cur;
cur--;
i++;
}
ctx.size = i;
}
char* cur_static;
void change_coro(Context &next) {
cur_static = next.low;
for (int i = 0; i < next.size; i++) {
*cur_static = next.stack[i];
cur_static--;
}
longjmp(next.env, 1);
}
void b() {
cout << "B(1)" << endl;
if (setjmp(b_ctx.env) > 0) {
cout << "B(2)" << endl;
change_coro(a_ctx);
} else {
store(b_ctx);
change_coro(a_ctx);
}
}
void a() {
cout << "A(1)" << endl;
if (setjmp(a_ctx.env) > 0) {
cout << "A(2)" << endl;
if (setjmp(a_ctx.env) > 0) {
change_coro(run_ctx);
} else {
store(a_ctx);
change_coro(b_ctx);
}
} else {
store(a_ctx);
b();
}
}
void run() {
volatile char stack_start_here;
a_ctx.low = (char*)&stack_start_here;
b_ctx.low = (char*)&stack_start_here;
run_ctx.low = (char*)&stack_start_here;
if (setjmp(run_ctx.env) > 0) {
cout << "Done" << endl;
} else {
store(run_ctx);
a();
}
}
int main() {
run();
return 0;
}
| true |
75b8afbc4c3d34818cb0989309f3c9fe9f706253 | C++ | lucaslgr/estrutura-de-dados-cplusplus | /Revisão P1/testesPonteiros.cpp | UTF-8 | 1,114 | 3.5 | 4 | [
"MIT"
] | permissive | #include <iostream>
#define VAL 98
using namespace std;
int main()
{
//TESTE 1
cout << "\n\nTESTE 1" << endl;
int i = 3, j = 5;
int *p = &i, *q = &j;
int resultado = 3*-*p/(*q)+7;
cout << "A saida 9/5 eh:" << 9/5 << endl;
cout << "A saida de 3*-*p/(*q)+7 eh: " << resultado << endl;
//FIM TESTE 1
//TESTE 2
cout << "\n\nTESTE 2" << endl;
//int *p1 = VAL;
//cout << &VAL << endl;
//cout << *p1;
//FIM TESTE 2
//TESTE 3
cout << "\n\nTESTE 3" << endl;
int vet[] = {1, 2, 3, 4, 5, 6};
cout << "vet[3]: " << vet[3] << endl;
cout << "*(vet + 3): " << *(vet + 3) << endl;
//FIM TESTE 3
//TESTE 4
// cout << "\n\nTESTE 4" << endl;
// int vet1[8] = {1,2,3,4,5,6,7,8};
// cout << vet1++ << endl;
//FIM TESTE 4
//TESTE 4
// cout << "\n\nTESTE 4" << endl;
//Qual é a diferença entre as duas?
char s[] = "Brasil";
//char *s1 = "Brasil"; //NÃO FUNCIONA
// cout << "Tamanho em bytes de s1: " << sizeof(s1) << endl;
// cout << "Tamanho em bytes de s2: " << sizeof(s2) << endl;
return 0;
} | true |
a6962daa19c8471a6527b2b3e4db058a258aeccf | C++ | kailasspawar/DS-ALGO-PROGRAMS | /Strings/ReverseWordsInAString.cpp | UTF-8 | 646 | 3.53125 | 4 | [] | no_license | #include<iostream>
#include<algorithm>
using namespace std;
void rev(char *begin,char *end)
{
char temp;
while(begin < end)
{
temp = *begin;
*begin++ = *end;
*end-- = temp;
}
}
void reverseWords(char *s)
{
char *word_begin = s;
char *temp = s;
cout<<*temp<<endl;
while(*temp)
{
temp++;
if(*temp == '\0')
{
rev(word_begin,temp-1);
}
else if(*temp == ' ')
{
rev(word_begin,temp-1);
word_begin = temp+1;
}
}
rev(s,temp-1);
}
int main()
{
char s[] = "i love programming very much";
char *temp = s;
reverseWords(s);
cout<<s<<endl;
return 0;
}
| true |
7ca18805a6ab6173e7fbab418e749c53ee156c18 | C++ | alenops/opal | /data structure/上机/双向起泡排序/双向起泡排序.cpp | GB18030 | 805 | 3.375 | 3 | [] | no_license | //˫ij
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
//˳ṹͶ
typedef int datatype;
typedef struct{
int key;
datatype data;
}sequenlist;
void create(sequenlist[],int);
void print(sequenlist[],int);
void dbubblesort(sequenlist[],int);
void main()
{
const int n=10;
sequenlist r[n+1];
create(r,n);
printf("ǰݣ");
print(r,n);
dbubblesort(r,n);
printf("ݣ");
print(r,n);
}
//˳
void create(sequenlist r[],int n)
{
srand(time(0));
for(int i=1;i<=n;i++)
r[i].key=rand()%90;
}
//˳
void print(sequenlist r[],int n)
{
for(int i=1;i<=n;i++)
printf("%5d",r[i].key);
printf("\n");
}
//˫㷨
| true |
43aecd4a74993f562732db4c01f296a505ec1dc3 | C++ | andygandara/CFL-Parser | /parser.cc | UTF-8 | 8,798 | 3.3125 | 3 | [] | no_license | //
// Andres Gandara
// parser.cc
//
// Created by Andy Gandara on 3/30/18.
// Copyright © 2018 Andy Gandara. All rights reserved.
//
#include <iostream>
#include <cstdlib>
#include "parser.h"
using namespace std;
// Recursively checks that the variable exists in the scope
bool Parser::variable_exists(Scope* scope,string str) {
if (scope->variables.find(str) == scope->variables.end()) // variable string not found
{
if (scope->parent != NULL) // is nested scope
return variable_exists(scope->parent, str); // checks parent recursively for variable
else
return false; // not found in any parents, so returns false
}
else // variable found
return true;
}
void Parser::syntax_error()
{
cout << "Syntax Error\n";
exit(1);
}
Token Parser::expect(TokenType expected_type)
{
Token t = lexer.GetToken();
if (t.token_type != expected_type)
syntax_error();
return t;
}
// Peeks token by getting and ungetting token
Token Parser::peek()
{
Token t = lexer.GetToken();
lexer.UngetToken(t);
return t;
}
// Peek second token
Token Parser::doublePeek()
{
Token t1 = lexer.GetToken();
Token t2 = lexer.GetToken();
lexer.UngetToken(t2);
lexer.UngetToken(t1);
return t2;
}
// Parsing
void Parser::parse_program()
{
// program -> scope
// TODO
Token t = peek();
if (t.token_type == LBRACE)
parse_scope();
else syntax_error();
}
void Parser::parse_scope()
{
// scope -> LBRACE scope_list RBRACE
// TODO
Scope* update_scope = new Scope;
update_scope->parent = currentScope;
currentScope = update_scope;
allScopes.push_back(update_scope);
expect(LBRACE);
parse_scope_list();
expect(RBRACE);
currentScope = currentScope->parent;
}
void Parser::parse_scope_list()
{
// scope_list -> scope | var_decl | stmt | scope scope_list | var_decl scope_list | stmt scope_list
// TODO
Token t = peek();
Token temp = lexer.GetToken();
Token t1 = peek();
lexer.UngetToken(temp);
// scope
if (t.token_type == LBRACE)
parse_scope();
// stmt
else if (t.token_type == WHILE || (t.token_type == ID && t1.token_type == EQUAL))
parse_stmt();
// var_decl
else if (t.token_type == ID && t1.token_type != EQUAL)
parse_var_decl();
else
syntax_error();
// scope scope_list || var_decl scope_list || stmt scope_list
Token t3 = peek();
if (t3.token_type == LBRACE || t3.token_type == ID || t3.token_type == WHILE)
parse_scope_list();
}
void Parser::parse_var_decl()
{
// var_decl -> id_list COLON type_name SEMICOLON
// TODO
parse_id_list();
expect(COLON);
parse_type_name();
expect(SEMICOLON);
}
void Parser::parse_id_list()
{
// id_list -> ID | ID COMMA id_list
// TODO
Token t = peek();
Token temp = lexer.GetToken();//doublePeek();
Token t1 = peek();
lexer.UngetToken(temp);
if (currentScope->variables.find(t.lexeme) != currentScope->variables.end()) // ID found in scope -- double declaration
{
while (peek().token_type == ID || peek().token_type == COMMA){
lexer.GetToken();
}
expect(COLON);
lexer.GetToken(); // move past type
expect(SEMICOLON);
cout << "ERROR CODE 1.1 " << t.lexeme << endl;
exit(0);
}
else // ID not found in current scope -- proceeds to parse ID list
{
//currentScope->variables[t.lexeme] = 1;
currentScope->variables[t.lexeme] = 0;
if (t.token_type == ID && t1.token_type != COMMA){
expect(ID);
}
else if (t.token_type == ID && t1.token_type == COMMA){
expect(ID);
expect(COMMA);
parse_id_list();
}
else syntax_error();
}
}
void Parser::parse_type_name()
{
// type_name -> REAL | INT | BOOLEAN | STRING
// TODO
Token t = peek();
if (t.token_type == REAL || t.token_type == INT || t.token_type == BOOLEAN || t.token_type == STRING)
{
lexer.GetToken();
return;
}
else syntax_error();
}
void Parser::parse_stmt_list()
{
// stmt_list -> stmt | stmt stmt_list
// TODO
Token t = peek();
if (t.token_type == WHILE || t.token_type == ID)
parse_stmt();
else syntax_error();
Token t1 = peek();
if (t1.token_type == WHILE || t1.token_type == ID)
parse_stmt_list();
}
void Parser::parse_stmt()
{
// stmt -> assign_stmt | while_stmt
// TODO
Token t = peek();
Token temp = lexer.GetToken();
Token t1 = peek();
lexer.UngetToken(temp);
if (t.token_type == ID && t1.token_type == EQUAL)
parse_assign_stmt();
else if (t.token_type == WHILE && t1.token_type == LPAREN)
parse_while_stmt();
else syntax_error();
}
void Parser::parse_assign_stmt()
{
// assign_stmt -> ID EQUAL expr SEMICOLON
// TODO
Token t = peek();
expect(ID);
expect(EQUAL);
t = peek();
if (t.token_type == ID && !variable_exists(currentScope, t.lexeme)) // Token is ID and ID not found in scope
{
lexer.GetToken();
expect(SEMICOLON);
cout << "ERROR CODE 1.2 " << t.lexeme << endl;
exit(0);
}
parse_expr();
expect(SEMICOLON);
}
void Parser::parse_while_stmt()
{
// while_stmt -> WHILE condition LBRACE stmt_list RBRACE | WHILE condition stmt
// TODO
expect(WHILE);
parse_condition();
Token t = peek();
if (t.token_type == LBRACE)
{
expect(LBRACE);
parse_stmt_list();
expect(RBRACE);
}
else if (t.token_type == ID || t.token_type == WHILE)
parse_stmt();
else syntax_error();
}
void Parser::parse_expr()
{
// expr -> arithmetic_operator expr expr | boolean_operator expr expr | relational_operator expr expr | NOT expr | primary
// TODO
Token t = peek();
if (t.token_type == PLUS || t.token_type == MINUS || t.token_type == MULT || t.token_type == DIV)
{
parse_arithmetic_operator();
parse_expr();
parse_expr();
}
else if (t.token_type == AND || t.token_type == OR || t.token_type == XOR)
{
parse_boolean_operator();
parse_expr();
parse_expr();
}
else if (t.token_type == GREATER || t.token_type == GTEQ || t.token_type == LESS || t.token_type == LTEQ || t.token_type == NOTEQUAL)
{
parse_relational_operator();
parse_expr();
parse_expr();
}
else if (t.token_type == NOT)
{
expect(NOT);
parse_expr();
}
else if (t.token_type == ID || t.token_type == NUM || t.token_type == REALNUM || t.token_type == STRING_CONSTANT || t.token_type == TRUE || t.token_type == FALSE)
parse_primary();
else syntax_error();
}
void Parser::parse_arithmetic_operator()
{
// arop -> PLUS | MINUS | MULT | DIV
// TODO
Token t = lexer.GetToken();
if (t.token_type == PLUS || t.token_type == MINUS || t.token_type == MULT || t.token_type == DIV)
return;
else syntax_error();
}
void Parser::parse_boolean_operator()
{
// boolop -> AND | OR | XOR
// TODO
Token t = lexer.GetToken();
if (t.token_type == AND || t.token_type == OR || t.token_type == XOR)
return;
else syntax_error();
}
void Parser::parse_relational_operator()
{
// relop -> GREATER | GTEQ | LESS | LTEQ | NOTEQUAL
// TODO
Token t = lexer.GetToken();
if (t.token_type == GREATER || t.token_type == GTEQ || t.token_type == LESS || t.token_type == NOTEQUAL || t.token_type == LTEQ)
return;
else syntax_error();
}
void Parser::parse_primary()
{
// primary -> ID | NUM | REALNUM | STRING_CONSTANT | bool_constant
// TODO
Token t = lexer.GetToken();
if (t.token_type == ID || t.token_type == NUM || t.token_type == REALNUM || t.token_type == STRING_CONSTANT)
return;
else if (t.token_type == TRUE || t.token_type == FALSE)
{
lexer.UngetToken(t);
parse_bool_const();
}
else syntax_error();
}
void Parser::parse_bool_const()
{
// bool_const -> TRUE | FALSE
// TODO
Token t = lexer.GetToken();
if (t.token_type == TRUE || t.token_type == FALSE)
return;
else syntax_error();
}
void Parser::parse_condition()
{
// condition -> LPAREN expr RPAREN
// TODO
expect(LPAREN);
parse_expr();
expect(RPAREN);
}
void Parser::begin_parsing()
{
// TODO
Token t = peek();
if (t.token_type == LBRACE)
parse_program();
else syntax_error();}
int main()
{
Parser parser;
parser.begin_parsing();
return 0;
}
| true |
dcd3d7310d15aa8376c6766bed517cce7f90df8b | C++ | eliray01/dsba-ads2020-hw1 | /main.cpp | UTF-8 | 1,358 | 3.03125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <ctime>
#include <random>
#include <algorithm>
#include <utility>
#include <fstream>
#include "Multiplicator.h"
using namespace std;
int main()
{
srand(time(0));
ofstream Table;
Table.open(R"(C:\Users\fahre_000\dsba-ads2020-hw1\data\output.csv)");
Table.clear();
Multiplicator M;
Number num1,num2,result;
Table << "Length" << ',' << "Grade School Multiplication" << ',' << "Divide and conquer" << ',' << "Karatsuba" << '\n';
int k = 0;
for(int i = 50; i <= 1000; i += 50){
double sum = 0,sum1 = 0,sum2 = 0;
for(int k = 0; k < 10; k++){
num1.generate_random_number(i);
num2.generate_random_number(i);
clock_t start = clock();
M.GradeSchoolMultiplication(num1,num2);
clock_t end = clock();
clock_t start1 = clock();
M.DaC(num1,num2);
clock_t end1 = clock();
clock_t start2 = clock();
M.Karatsuba(num1,num2);
clock_t end2 = clock();
sum += (double)(end - start)/CLOCKS_PER_SEC; // Grade School Multiplication
sum1 += (double)(end1 - start1)/CLOCKS_PER_SEC; // Divide and Conquer
sum2 += (double)(end2 - start2)/CLOCKS_PER_SEC; // Karatsuba
}
Table << i << ',' << (sum/10) << ',' << (sum1/10) << ',' << (sum2/10) << '\n';
}
} | true |
af7db261af867d346a7b8c6c350127c449099909 | C++ | TamNguyenMinh2494/C-C- | /DFS/DFS/DFS/DFS.cpp | UTF-8 | 1,616 | 3.1875 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
#include <conio.h>
#define MAX 20
#define initial 1
#define visited 2
void InputFromFile(int G[][MAX], int &n);
void graph_traversal();
void DFS(int vertex);
void push(int vertex);
int pop();
int isEmpty();
int stack[MAX];
int top = -1;
int vertices;
int adjacent_matrix[MAX][MAX];
int vertex_status[MAX];
void main()
{
InputFromFile(adjacent_matrix, vertices);
graph_traversal();
_getch();
}
void InputFromFile(int G[][MAX], int &n)
{
int i, j;
FILE *f = fopen("data.txt", "rt");
fscanf(f, "%d", &n);
for (i = 0; i<n; i++)
for (j = 0; j<n; j++)
fscanf(f, "%d", &G[i][j]);
fclose(f);
}
void graph_traversal()
{
int vertex;
for (vertex = 0; vertex < vertices; vertex++)
{
vertex_status[vertex] = initial;
}
printf("Enter Starting Vertex for DFS:\t");
scanf("%d", &vertex);
DFS(vertex);
printf("\n");
}
void DFS(int vertex)
{
int count;
push(vertex);
while (!isEmpty())
{
vertex = pop();
if (vertex_status[vertex] == initial)
{
printf("%3d", vertex);
vertex_status[vertex] = visited;
}
for (count = vertices - 1; count >= 0; count--)
{
if (adjacent_matrix[vertex][count] >= 1 && vertex_status[count] == initial)
{
push(count);
}
}
}
}
void push(int vertex)
{
if (top == (MAX - 1))
{
printf("Stack Overflow\n");
return;
}
top = top + 1;
stack[top] = vertex;
}
int pop()
{
int vertex;
if (top == -1)
{
printf("Stack Underflow\n");
exit(1);
}
else
{
vertex = stack[top];
top = top - 1;
return vertex;
}
}
int isEmpty()
{
if (top == -1)
{
return 1;
}
else
{
return 0;
}
} | true |
aa54fd7f09b77fd5abf3c9cbcfe369e3a53e182b | C++ | xiaoland/CaiojSolution | /question_test/1017.cpp | UTF-8 | 554 | 2.828125 | 3 | [
"Apache-2.0"
] | permissive | // TIME COUNT: 2:24 PASS: 3
#include <cstdio>
#include <sstream>
#include <string>
using namespace std;
int pd(int a) {
stringstream ss;
ss<<a;
string as;
ss>>as;
int asl = as.length();
if(asl < 4) {
if(as[0] == as[asl-1]) {
return 0;
}
}
else {
if(as[0] == as[3] && as[1] == as[2]) {
return 0;
}
}
}
int main() {
int x, y;
scanf("%d%d", &x, &y);
for(int i = x; i <= y; i++) {
if(pd(i) == 0) {
printf("%d\n", i);
}
}
} | true |
e8ca9b450ea68bde791b8f9a3d7c6c57bb5eac5e | C++ | SergeyLeus161/Course-work- | /Seller.cpp | UTF-8 | 248 | 2.96875 | 3 | [] | no_license | #include "Seller.h"
Seller::Seller() : salary(0) {}
Seller::Seller(string n) : salary(0), name(n) {}
string Seller::get_name() {
return name;
}
void Seller::add_salary(int sum) {
salary += sum;
}
int Seller::get_salary() {
return salary;
}
| true |
100da3bf8b228d749651cc66a8f65b0d395879ba | C++ | tullisar/EASy68K-Mac | /Sim68K/mac68kutils.cpp | UTF-8 | 3,547 | 2.96875 | 3 | [] | no_license | /***************************** 68000 SIMULATOR ****************************
File Name: mac68kutils.cpp
Version: 1.0 (Mac OS X)
This file contains various routines used in the Mac OS X port of EASy68K
The routines are :
memDistance
Created: 2011-03-17
Robert Bartlett-Schneider
***************************************************************************/
#include "extern.h"
BOOL trapInput = NO;
/**************************** long memDistance() ****************************
name : long memDistance(void *max, void *min, long size)
parameters : void *max : The upper bound of the memory range
void *min : The lower bound of the memory range
function : calculates the distance between pointers, with a size specified
by size, either BYTE_MASK, WORD_MASK, or LONG_MASK.
****************************************************************************/
long memDistance(void* max, void* min, long size)
{
long factor = 0;
switch (size) // Determine distance factor (typically bytes)
{
case BYTE_MASK:
factor = 1;
break;
case WORD_MASK:
factor = 2;
break;
case LONG_MASK:
factor = 4;
break;
default:
factor = 1;
break;
}
unsigned long *maxAddr = (unsigned long *)max; // Cast to unsigned long pointers (addresses)
unsigned long *minAddr = (unsigned long *)min;
unsigned long distance = (unsigned long)maxAddr - (unsigned long)minAddr; // Calculate distance
return (distance / factor);
}
/********************* NSString* binaryStringForValue() **********************
name : NSString* binaryStringForValue(unsigned short value)
parameters : unsigned short value : the number to be converted to a 16 bit
binary string representation
function : Returns a string representation of a number as a 16 bit binary
number.
****************************************************************************/
NSString* binaryStringForValue(unsigned short value)
{
int position = WORD68K; // Start at end of string
char buf[WORD68K+1];
buf[position--] = '\0';
do {
if (value & 1) buf[position--] = '1'; // Test and set bits
else buf[position--] = '0';
value >>= 1; // Shift then loop
} while (value > 0);
while (position >= 0) // Fill remaining buffer space with 0
buf[position--] = '0';
return [NSString stringWithFormat:@"%s",buf];
}
/********************* NSNumber* binaryStringToValue() **********************
name : NSNumber* binaryStringToValue(NSString* input)
parameters : NSString* input : a string containing a binary representation
of a 16 bit number.
function : Returns a string representation of a number as a 16 bit binary
number.
****************************************************************************/
NSNumber* binaryStringToValue(NSString *input)
{
char buf[17];
sprintf(buf, "%s", [input cStringUsingEncoding:NSUTF8StringEncoding]);
int value = 0;
for (int i = 0; i < strlen(buf)-1; i++) { // Test and set
if (buf[i] == '1') (value |= 1);
value <<= 1; // Shift and loop
}
return [NSNumber numberWithUnsignedShort:value];
} | true |
4f53f8d8495f5b1c1fec93960d6da815cf378baa | C++ | anna-porter/Compilers-4301-Fall-2017 | /stage2/stage2.cpp | UTF-8 | 87,960 | 2.5625 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include <iomanip>
#include <stack>
#include <cstdlib>
#include <fstream>
#include <ctime>
#include <sstream>
using namespace std;
const int MAX_SYMBOL_TABLE_SIZE = 256;
enum storeType {INTEGER, BOOLEAN, PROG_NAME};
enum allocation {YES,NO};
enum modes {VARIABLE, CONSTANT};
const string storeTypeStrings[] = {"INTEGER", "BOOLEAN", "PROG_NAME"};
const string allocationStrings[] = {"YES","NO"};
const string modesStrings[] = {"VARIABLE","CONSTANT"};
struct entry //define symbol table entry format
{
string internalName;
string externalName;
storeType dataType;
modes mode;
string value;
allocation alloc;
int units;
};
vector<entry> symbolTable;
ifstream sourceFile;
ofstream listingFile,objectFile;
string token;
char charac;
const char END_OF_FILE = '$'; //arbitrary choice
int lineNum = 0;
int boolCount = 0;
int intCount = 0;
int beginDepth = 0;
string GetTemp();
void FreeTemp();
//paragraph says it wants this in the parser function
int tempCount;//initialize to -1 to reflect the fact we have no temporaries yet
int maxTempCount;
int loopCount = 0;
string areg = "";
const string rammTab = " ";
const string rTbFv = " ";
bool hold = false;
bool FALS = false;
bool ZERO = false;
bool TRU = false;
stack<string> operators;
stack<string> operands;
//Declare functions
void CreateListingHeader();
void Parser();
void CreateListingTrailer(int numErr);
void PrintSymbolTable();
void printError(string error);
void Prog();
void ProgStmt();
void Consts();
void Vars();
void BeginEndStmt();
void ConstStmts();
void VarStmts();
string Ids();
string GenInternalName(storeType inType);
vector<string> parseNames(string names);
void Insert(string externalName,storeType inType, modes inMode, string inValue,allocation inAlloc, int inUnits, string forcedIntName = "");
storeType WhichType(string name);
string WhichValue(string name);
string NextToken();
char NextChar();
bool operator==(entry lhs, string rhs);
bool IsBool(string str);
bool IsInt(string str);
bool IsKeyWord(string str);
bool IsNonKey(string str);
void ExecStmt();
void ExecStmts();
void AssignStmt();
void ReadStmt();
void WriteStmt();
void Express();
void Term();
void Expresses();
void Terms();
void Factor();
void Factors();
void Part();
void IfStmt();
void ElsePt();
void WhileStmt();
void RepeatStmt();
void NullStmt();
bool RelOp();
bool AddLevelOp();
bool MultLevelOp();
void Code(string op,string operand1="",string operand2="");
void pushOperator(string op);
string popOperator();
void pushOperand(string operand);
string popOperand();
void EmitStartCode();
void EmitEndCode();
void EmitReadCode(string operand1);
void EmitWriteCode(string operand1);
void EmitAdditionCode(string operand1,string operand2);
void EmitSubtractionCode(string operand1, string operand2);
void EmitNegationCode(string operand);
void EmitNotCode(string operand);
void EmitLessEqualCode(string operand1, string operand2);
void EmitLessThanCode(string operand1, string operand2);
void EmitGreaterEqualCode(string operand1, string operand2);
void EmitGreaterThanCode(string operand1, string operand2);
void EmitMultiplicationCode(string operand1,string operand2);
void EmitDivisionCode(string operand1,string operand2);
void EmitModCode(string operand1, string operand2);
void EmitAndCode(string operand1,string operand2);
void EmitOrCode(string operand1,string operand2);
void EmitAssignCode(string operand1,string operand2);
void EmitNotEqualsCode(string operand1,string operand2);
void EmitEqualsCode(string operand1,string operand2);
void EmitThenCode(string operand);
void EmitElseCode(string operand);
void EmitPostIfCode(string operand);
void EmitWhileCode();
void EmitDoCode(string operand);
void EmitPostWhileCode(string operand1,string operand2);
void EmitRepeatCode();
void EmitUntilCode(string operand1, string operand2);
string getIntName(string extName);
//this program is the stage0 compiler for Pascallite. It will accept
//input from argv[1], generating a listing to argv[2], and object code to
//argv[3]
int main(int argc, char **argv)
{
sourceFile.open(argv[1]);
listingFile.open(argv[2]);
objectFile.open(argv[3]);
CreateListingHeader();
Parser();
CreateListingTrailer(0);
listingFile.close();
//PrintSymbolTable();
objectFile.close();
sourceFile.close();
return 0;
}
void CreateListingHeader()
{
lineNum++;
time_t now = time (NULL);
if(listingFile.is_open())
{
listingFile << "STAGE0: " << "Anna Porter, Jacob Hallenberger\t" << ctime(&now);
listingFile << setw(23) << left << "\nLINE NO." << "SOURCE STATEMENT\n\n" << setw(5) << right << lineNum << "|";
}
//line numbers and source statements should be aligned under the headings
}
void Parser()
{
//initialize to -1 to reflect the fact we have no temporaries yet
tempCount = -1;
maxTempCount = -1;
NextChar();
//charac must be initialized to the first character of the source file
if(NextToken() != "program")
{
printError("keyword \"program\" expected");//process err
} //a call to NextToken() has two effects
// (1) the variable, token, is assigned the value of the next token
// (2) the next token is read from the source file in order to make
// the assignment. The value returned by NextToken() is also
// the next token.
Prog();
//parser implements the grammar rules, calling first rule
}
void CreateListingTrailer(int numErr)
{
if(numErr == 0)
{
listingFile << "\n\n";
}
listingFile << "COMPILATION TERMINATED " << numErr << " ERRORS ENCOUNTERED\n";
//print "COMPILATION TERMINATED", "# ERRORS ENCOUNTERED";
}
void PrintSymbolTable()
{
entry entr;
ostringstream out;
//Print header
time_t now = time (NULL);
out << "STAGE0: " << "Anna Porter, Jacob Hallenberger\t" << ctime(&now) << "\nSymbol Table\n\n";
objectFile << out.str();
out.str("");
for(unsigned int i=0; i<symbolTable.size(); ++i)
{
entr = symbolTable[i];
out << setw(15) << left;
if(entr.externalName.length() > 15)
{
out << entr.externalName.substr(0,15);
}
else
{
out << entr.externalName;
}
out << " " << setw(4) << left << entr.internalName;
out << " " << setw(9) << right << storeTypeStrings[entr.dataType];
out << " " << setw(8) << right << modesStrings[entr.mode];
out << " " << setw(15) << right;
if(entr.dataType == BOOLEAN)
{
if(entr.value == "true")
{
out << "1";
}
else if(entr.value == "false")
{
out << "0";
}
else
{
out << "";
}
}
else
{
if(entr.value.length() > 15)
{
out << entr.value.substr(0,15);
}
else
{
out << entr.value;
}
}
out << " " << setw(3) << right << allocationStrings[entr.alloc];
out << " " << setw(1) << entr.units;
objectFile << out.str() << "\n";
out.str("");
}
}
//we made this!
void printError(string error)
{
if(listingFile.is_open())
{
listingFile << "\nError: Line " << lineNum << ": " << error << "\n\n";
CreateListingTrailer(1);
listingFile.close();
//PrintSymbolTable();
objectFile.close();
}
//sourceFile.close();
}
//i think this may be all we need to do
//I think it's finished except the last if statement
void Prog() //token should be "program"
{
if (token != "program")
{
printError("keyword \"program\" expected");//process err
}
ProgStmt();
EmitStartCode();
if (token == "const")
{
Consts();//not sure if finished (It should be done now, along with ConstStmnts, but there is an if at the end I'm iffy about)
}
if (token == "var")
{
Vars();//not sure if finished
}
if (token != "begin")
{
printError("keyword \"begin\" expected");//process err
}
BeginEndStmt();
if (charac != END_OF_FILE)//CHANGED THIS TO CHARAC FROM TOKEN
{
printError("no text may follow \"end\""); //process err
}
EmitEndCode();
}
void ProgStmt() //token should be "program"
{
string x;
if (token != "program")
{
printError("keyword \"program\" expected"); //process err
}
x = NextToken();
if (!IsNonKey(token))
{
printError("program name expected"); //process err
}
if (NextToken() != ";")
{
//cout << "XX:" << "PROGSTMT" << endl;
printError("semicolon expected"); //process err
}
NextToken();
Insert(x,PROG_NAME,CONSTANT,x,NO,0);
}
void Consts() //token should be "const"
{
if (token != "const")
{
printError("keyword \"const\" expected"); //process err
}
if (!IsNonKey(NextToken()))
{
printError("non-keyword identifier must follow \"const\""); //process err
}
ConstStmts();
}
void Vars() //token should be "var"
{
if (token != "var")
{
printError("keyword \"var\" expected"); //process err
}
if (!IsNonKey(NextToken()))
{
printError("non-keyword identifier must follow \"var\""); //process err
}
VarStmts();
}
void BeginEndStmt() //token should be "begin"
{
if (token != "begin")
{
printError("keyword \"begin\" expected"); //process err
}
++beginDepth;
//Does this need to call something here?
NextToken();
ExecStmts();
if (token != "end")
{
printError("keyword \"end\" expected"); //process err
}
--beginDepth;
NextToken();
if (token != "." && token != ";")
{
printError("semicolon or period expected"); //process err
}
if(token == "." && beginDepth>0)
{
printError("mismatched begin-end statements or missing semicolon");
}
Code("end",token);
if(token != ";"){
NextToken();
}
}
void ConstStmts() //token should be NON_KEY_ID
{
//strings for stuff
string x,y;
//If token isn't a NON_KEY_ID, then trigger error
if (!IsNonKey(token))
{
printError("non-keyword identifier expected");//process err
}
x = token;
//The next token must be equals
if (NextToken() != "=")
{
printError("\"=\" expected");//process err
}
y = NextToken();
//The next token (y) must be one of the following symbols/keywords
if (y != "+" && !IsNonKey(y) && y != "-" && y != "not" && y != "true" && y!= "false" && !IsInt(y))
{
printError("token to right of \"=\" illegal");//process err
}
//If y is a + or - then it must be followed by an integer
if (y == "+" || y == "-")
{
if(!IsInt(NextToken()))
{
printError("integer expected after sign");//process err
}
y = y + token;
}
//If y is "not", it must be followed by a BOOLEAN or Non-Key ID
if (y == "not")
{
NextToken();
if(!IsBool(token) && !IsNonKey(token))
{
printError("boolean or non keyword identifier expected after not");//process err
}
//Invert the BOOLEAN that follows y
if(token == "true" || WhichValue(token) == "true")
{
y = "false";
}
else
{
y = "true";
}
}
//The statement must be followed by a ;
if (NextToken() != ";")
{
//cout << "XX:" << "CONSTSTMTS" << endl;
printError("semicolon expected");//process err
}
//Insert the newly defined CONSTANT into the symbol table
Insert(x,WhichType(y),CONSTANT,WhichValue(y),YES,1);
//The next token must signal the beginning of the variable section, the code section
//or define another CONSTANT
x = NextToken(); //Reuse x to avoid calling NextToken() more times than needed (and because I'm too lazy to declare another variable for this)
//cout << "Token: " << token << endl;
if (x != "begin" && x != "var" && !IsNonKey(x))
{
printError("non-keyword identifier,\"begin\", or \"var\" expected");//process err
}
if (IsNonKey(x)) //THIS MIGHT NEED TO BE CHANGED TO IsNonKey(x). I'm not sure if getting the next token here will break stuff, I think it might though,according to the syntax chart
{
ConstStmts();
}
}
void VarStmts() //token should be NON_KEY_ID
{
string x,y,tkn;
//Token must be a NON_KEY_ID
if (!IsNonKey(token))
{
printError("non-keyword identifier expected");//process err
}
x = Ids();
if (token != ":")
{
printError("\":\" expected");//process err
}
tkn = NextToken();
if(tkn != "integer" && tkn != "boolean")
{
printError("illegal type follows \":\"");//process err
}
y = token;
if(NextToken() != ";")
{
//cout << "XX:" << "VARSTMTS" << endl;
printError("semicolon expected");//process err
}
Insert(x,WhichType(y),VARIABLE,"",YES,1);
tkn = NextToken();
if (tkn != "begin" && !IsNonKey(tkn))
{
printError("non-keyword identifier or \"begin\" expected");//process err
}
if (IsNonKey(token)) //I THINK THIS MIGHT BE A BUG I'm fairly sure that this if should say if(IsNonKey(token)) instead of not, but this is how the pseudocode had it, so I'm leaving it for now
{
VarStmts();
}
}
void ExecStmts()
{
ExecStmt();
//If token is not end, then it must be another exec stmt, so continue
if(token != "end" && token != "until" && token != ")")
{
ExecStmts();
}
}
//Reads in exec statements
void ExecStmt()
{
//cout << "XX:" << "ExecStmt: " << token << endl;
/*if(token == ";")
{
NextToken();
}*/
//token must be a non key ID, "read", or "write" in order to be an exec statement, it can also be end if the program has looped
if(!IsNonKey(token) && token != "read" && token != "write" && token != "end" && token != "if" && token != "while" && token != "repeat" && token != ";" && token != "begin" && token != "until")
{
printError("non-keyword identifier, \"read\", \"write\", \"if\", \"while\", \"repeat\", \";\", or \"begin\" expected");
}
if(token == "read")
{
ReadStmt();
}
else if(token == "write")
{
WriteStmt();
}
else if(token == "if")
{
IfStmt();
}
else if(token == "while")
{
WhileStmt();
}
else if(token == "repeat")
{
RepeatStmt();
}
else if(token == ";")
{
NullStmt();
}
else if(token == "begin")
{
BeginEndStmt();
}
else if(token != ";" && token != "end" && IsNonKey(token))
{
AssignStmt();
}
//MIGHT WANT TO REMOVE THIS
else if(token != "end")
{
printError("non-keyword identifier, \"read\", \"write\", \"if\", \"while\", \"repeat\", \";\", or \"begin\" expected");
}
}
//This is the fun one
void AssignStmt()
{
//cout << "XX:" << "AssignStmt: " << token << endl;
//Assignments must begin with a non key ID
if(!IsNonKey(token))
{
printError("non-keyword identifier expected");
}
pushOperand(token);
//Assignments must have ":=" after the non key ID
if(NextToken() != ":=")
{
printError("\":=\" expected");
}
pushOperator(":=");
//Next production is express
NextToken();
Express();
//Assignments must end with a semicolon
if(token != ";")
{
//cout << "XX:" << "ASSIGNSTMT" << endl;
printError("semicolon expected");
}
//Express the assignment statement
Code(popOperator(),popOperand(),popOperand());
//NextToken();
}
//Reads in data/variables
void ReadStmt()
{
//cout << "XX:" << "ReadStmt: " << token << endl;
//READ_LIST
//If the token isn't "read", you shouldn't be here
if(token != "read")
{
printError("keyword \"read\" expected");
}
//The next token must be a left parenthesis
if(NextToken() != "(")
{
printError("\"(\" expected");
}
NextToken();
string x = Ids();
//cout << "XX:" << "Read IDS: " << x << endl;
//token should be ")"
if(token != ")")
{
printError("\",\" or \")\" expected");
}
Code("read",x,"");
//End of READ_STMT must be a semicolon
if(NextToken() != ";")
{
//cout << "XX:" << "READSTMT" << endl;
printError("semicolon expected");
}
NextToken();
}
//writes out data
void WriteStmt()
{
//cout << "XX:" << "WriteStmt: " << token << endl;
//WRITE_LIST
//If the token isn't "write", you shouldn't be here
if(token != "write")
{
printError("keyword \"write\" expected");
}
//The next token must be a left parenthesis
if(NextToken() != "(")
{
printError("\"(\" expected");
}
NextToken();
string x = Ids();
//cout << "XX:" << "WriteIds: " << x << " | " << token << endl;
//token should be ")"
if(token != ")")
{
printError("\",\" or \")\" expected");
}
Code("write",x);
//NextToken();
//End of WRITE_STMT must be a semicolon
if(NextToken() != ";")
{
//cout << "XX:" << "BOB" << endl;
printError("semicolon expected");
}
//cout << "XX:" << "WriteStmtEnd " << token << endl;
NextToken();
}
void Express()
{
//NextToken();
Term();
Expresses();
}
void Expresses()
{
//cout << "XX:" << "Expresses: " << token << endl;
//NextToken();
//////cout << "XX:" << "ExpressesOut: " << token << endl;
//If token is a REL_OP then code is needed
if(RelOp())
{
//Push the operator onto the stack
pushOperator(token);
//Call Term
NextToken();
Term();
//Express code to implement the operator
Code(popOperator(),popOperand(),popOperand());
//Call Expresses again
Expresses(); //THIS MIGHT BE A BUG, THE SYNTAX CHART AND COMPILER STRUCTURE CONTRADICT EACH OTHER
}
//else token must be ")", ",", or ";"
else if(token != ")" && token != "," && token != ";" && token != "do" && token != "then")
{
printError("\")\", comma, or semicolon expected");
}
}
void Term()
{
//NextToken();
Factor();
Terms();
}
void Terms()
{
//NextToken();
//cout << "XX:" << "Terms: " << token << endl;
//If token is an ADD_LEVEL_OP, then code is needed
if(AddLevelOp())
{
//Push the operator
pushOperator(token);
//Call Factor()
NextToken();
Factor();
//Call code with the operator
Code(popOperator(),popOperand(),popOperand());
//Call Terms again
Terms();
}
//If token is not a REL_OP, or ")", or ";", then there is an error
else if(!RelOp() && token != ")" && token != ";" && token != "do" && token != "then")
{
//cout << "XX:" << "non-multi level operator, \")\" or semicolon expected - TERMS" << endl;
printError("non-multi level operator, \")\" or semicolon expected");
}
}
void Factor()
{
//NextToken();
Part();
Factors();
}
void Factors()
{
//NextToken();
//cout << "XX:" << "Factors: " << token << endl;
//If token is a MULTI_LEVEL_OP, then code is needed
if(MultLevelOp())
{
//Push the operator onto the stack
pushOperator(token);
//Call Part()
NextToken();
Part();
//Express code for the operator
Code(popOperator(),popOperand(),popOperand());
//Call Factors again
Factors();
}
//If token is not a different operator, or ")", or ";", then there is an error
else if(!RelOp() && !AddLevelOp() && token != ")" && token != ";" && token != "do" && token != "then")
{
//cout << "XX:" << "operator, \")\" or semicolon expected - FACTORS" << endl;
printError("operator, \")\", \"do\", \"then\" or semicolon expected");
}
}
void Part()
{
//NextToken();
//cout << "XX:" << "Part: " << token << endl;
if(token == "not")
{
NextToken();
//If token is true, push false
if(token == "true")
{
pushOperand("false");
NextToken();
}
//If token is false, push true
else if(token == "false")
{
pushOperand("true");
NextToken();
}
//If token is a non key identifier, emit code for not NonKeyID
else if(IsNonKey(token))
{
Code("not", token);
NextToken();
}
//If token is "(", begin another expression
else if(token == "(")
{
Express();
if(token != ")" && token != ";")
{
printError("\")\" expected");
}
}
//Else there is an error
else
{
printError("expression, non-keyword identifier, or boolean literal expected");
}
}
else if(token == "+")
{
NextToken();
//If token is "(", begin another expression
if(token == "(")
{
Express();
if(token != ")" && token != ";")
{
printError("\")\" expected");
}
}
//If token is an integer or a non keyword identifier, then push it onto the stack
else if(IsInt(token) || IsNonKey(token))
{
pushOperand(token);
NextToken();
}
//else there is an error
else
{
printError("expression, non-keyword identifier, or integer literal expected");
}
}
else if(token == "-")
{
NextToken();
//If token is "(", begin another expression
if(token == "(")
{
Express();
if(token != ")" && token != ";")
{
//cout << "XX:" << "NEGATE------------------------------" << endl;
printError("\")\" expected");
}
//Express code to negate the expression
Code("neg",popOperand());
//NextToken();
}
//If token is an integer then push it onto the stack after negation
else if(IsInt(token))
{
ostringstream neg;
neg << "-" << token;
if(find(symbolTable.begin(),symbolTable.end(),neg.str()) == symbolTable.end())
Insert(neg.str(),INTEGER,CONSTANT,neg.str(),YES,1);
pushOperand(neg.str());
NextToken();
}
//If the token is a non keyword identifier, then express code to negate it
else if(IsNonKey(token))
{
Code("neg",token);
NextToken();
}
//else there is an error
else
{
printError("expression, non-keyword identifier, or integer literal expected");
}
}
//If the token is an integer, boolean, or non keyword identifier, then push the operand onto the stack
else if(IsInt(token) || IsBool(token) || IsNonKey(token) || token == "true" || token == "false")
{
if(token == "true")
{
pushOperand("true");
}
else if(token == "false")
{
pushOperand("false");
}
else
{
pushOperand(token);
}
NextToken();
}
//If the token is "(", then it begins yet another expression
else if(token == "(")
{
NextToken();
Express();
if(token != ")")
{
printError("\")\" expected");
}
NextToken();
}
//Else an error has been encountered
else
{
printError("expression, non-keyword identifier, integer or boolean literal, \"not\", \"+\", or \"-\", expected");
}
//NextToken();
}
//STAGE 2 PRODUCTIONS
void IfStmt(){
//cout << "XX:" << "IfStmt : " << token << endl;
if(token != "if"){
printError("Keyword \"if\" expected");
}
NextToken();
Express();
//Might need to change NextToken to token
if(token != "then"){
printError("Keyword \"then\" expected");
}
Code("then",popOperand());
NextToken();
ExecStmt();
if(token == ";"){
NextToken();
}
ElsePt();
}
void ElsePt(){
//cout << "XX:" << "ElsePt : " << token << endl;
if(token == "else"){
Code("else",popOperand());
NextToken();
ExecStmt();
}
else
{
//NextToken();
}
Code("post_if",popOperand());
}
void WhileStmt(){
//cout << "XX:" << "WhileStmt : " << token << endl;
if(token != "while"){
printError("keyword \"while\" expected");
}
Code("while");
NextToken();
if(token == "(")
{
//NextToken();
}
Express();
//cout << "XX:" << "WhileStmtDo : " << token << endl;
if(token != "do"){
printError("keyword \"do\" expected");
}
Code("do",popOperand());
NextToken();
ExecStmt();
Code("post_while",popOperand(),popOperand());
}
void RepeatStmt(){
if(token != "repeat"){
printError("keyword \"repeat\" expected");
}
Code("repeat");
NextToken();
ExecStmts();
if(token != "until"){
printError("keyword \"until\" expected");
}
NextToken();
if(token == "(")
{
NextToken();
}
Express();
//cout << "XX:" << "Until : " << token << endl;
Code("until",popOperand(),popOperand());
if(token == ")"){
NextToken();
}
if(token != ";"){
printError("semicolon expected");
}
}
void NullStmt(){
if(token != ";"){
printError("semicolon expected");
}
NextToken();
}
//True if token is a REL_OP false if not
bool RelOp()
{
return (token == "=" || token == "<>" || token == "<=" || token == ">=" || token == "<" || token == ">");
}
//True if token is a ADD_LEVEL_OP false if not
bool AddLevelOp()
{
return (token == "+" || token == "-" || token == "or");
}
//True if token is a MULTI_LEVEL_OP false if not
bool MultLevelOp()
{
return (token == "*" || token == "div" || token == "mod" || token == "and");
}
//So this recursively collects every Id after a variable declaration
string Ids() //token should be NON_KEY_ID
{
string temp, tempString;
//Token must be a NON_KEY_ID
if (!IsNonKey(token))
{
printError("non-keyword identifier expected");//process err
}
tempString = token;
temp = token;
//If there are more Ids, continue
if(NextToken() == ",")
{
//The Id must be a NON_KEY_ID
if (!IsNonKey(NextToken()))
{
printError("non-keyword identifier expected");//process err
}
tempString = temp + "," + Ids();
}
return tempString;
}
string GenInternalName(storeType inType)
{
ostringstream out;
if(inType == BOOLEAN)
{
out << "B";
out << boolCount;
boolCount++;
}
else if(inType == INTEGER)
{
out << "I";
out << intCount;
intCount++;
}
else if(inType == PROG_NAME)
{
out << "P";
out << 0;
}
return out.str();
}
vector<string> parseNames(string names)
{
vector<string> outnames;
string name;
for(uint i=0; i<names.length(); ++i)
{
if(names.at(i)==',')
{
outnames.push_back(name);
name = "";
}
else
{
name += names.at(i);
}
}
//cout << name << ":";
if(name.length() >= 15)
{
name = name.substr(0,15);
}
//cout << name << "\n";
outnames.push_back(name);
return outnames;
}
//create symbol table entry for each identifier in list of external names
//Multiply inserted names are illegal
void Insert(string externalName,storeType inType, modes inMode, string inValue,
allocation inAlloc, int inUnits, string forcedIntName)
{
vector<string> nameEntries;
nameEntries = parseNames(externalName);
//(name broken from list of external names and put into name != "")
for(unsigned int i=0; i<nameEntries.size(); ++i)
{
//symbolTable[name] is defined
if(find(symbolTable.begin(),symbolTable.end(),nameEntries[i].substr(0,15)) != symbolTable.end())
{
printError("multiple name definition");//process err
}
else if(nameEntries[i] != "true" && nameEntries[i] != "false" && IsKeyWord(nameEntries[i]))
{
//cout << "XX:" << "INSERT: " << externalName << endl;
printError("illegal use of keyword");//process err
}
else if(symbolTable.size() > 255)
{
printError("symbol table overflow");
}
else //create table entry
{
entry newent;
newent.externalName = nameEntries[i].substr(0,15);
newent.dataType = inType;
newent.mode = inMode;
//Special cases for boolean
if(inValue == "true" || inValue == "yes")
{
newent.value = "1";
}
else if(inValue == "false" || inValue == "no")
{
newent.value = "0";
}
else
{
newent.value = inValue;
}
newent.alloc = inAlloc;
newent.units = inUnits;
if(forcedIntName == "ZERO" || forcedIntName == "TRUE" || forcedIntName == "FALS")
{
newent.internalName = forcedIntName;
}
else
{
//symbolTable[name]=(name,inType,inMode,inValue,inAlloc,inUnits)
if(isupper(nameEntries[i].at(0)))
{
newent.internalName = nameEntries[i];
}
//symbolTable[name]=(GenInternalName(inType),inType,inMode,inValue,inAlloc,inUnits)
else
{
newent.internalName = GenInternalName(inType);
}
}
symbolTable.push_back(newent);
}
}
}
storeType WhichType(string name) //tells which data type a name has
{
storeType type;
if (IsBool(name) || IsInt(name) || name == "boolean" || name == "integer")
{
if(name == "true" || name == "false" || name == "boolean")
{
type = BOOLEAN;
}
else
{
type = INTEGER;
}
}
else //name is an identifier and hopefully a constant
{
//vector<entry>::iterator it;
//it = find(symbolTable.begin(),symbolTable.end(),name);
if(find(symbolTable.begin(),symbolTable.end(),name) != symbolTable.end())
{
type = (*find(symbolTable.begin(),symbolTable.end(),name)).dataType; //type = (*it).dataType;
} /*symbolTable[name] is defined then data type = type of symbolTable[name]*/
else
{
//cout << "XX:" << "WHICHTYPE: " << name << endl;
printError("reference to undefined constant or variable");//process err
}
}
return type;
}
string WhichValue(string name) //tells which value a name has
{
string value;
if(IsBool(name) || IsInt(name))
{
value = name;
}
else //name is an identifier and hopefully a constant
{
/*symbolTable[name] is defined and has a value*/
if(find(symbolTable.begin(),symbolTable.end(),name) != symbolTable.end())
{
value = (*find(symbolTable.begin(),symbolTable.end(),name)).value;
/*value = value of symbolTable[name]*/
}
else
{
//cout << "XX:" << "WHICHVALUE: " << name << endl;
printError("reference to undefined constant or variable");//process err
}
}
return value;
}
//Last Edited 11/10 Anna
string NextToken() //returns the next token or end of file marker
{
token = "";
while (token == "")
{
if (charac == '{')
{ //process comment
char c = NextChar();
while (c != END_OF_FILE && c != '}')//<--THIS WAS A CURLY BRACE MATCHING A PARENTHESIS AND IDKY BUT I CHANGED IT
{
c = NextChar();
}
if (charac == END_OF_FILE)
{
printError("unexpected end of file");//process err
}
NextChar();
}
else if (charac == '}')
{
token += END_OF_FILE;
printError("'}' cannot begin token");//process error:
}
else if (iswspace(charac))
{
NextChar();
}
else if (charac == ':' || charac == ',' || charac == ';' || charac == '=' || charac == '+' || charac == '-' || charac == '.' || charac == '<' || charac == '>' || charac == '(' || charac == ')' || charac == '*')
{
token = charac;
NextChar();
if((token == ":" || token == "<" || token == ">") && (charac == '=' || charac == '>'))
{
if(charac == '=' || (token == "<" && charac == '>'))
{
token += charac;
NextChar();
}
}
}
else if (isalpha(charac) && islower(charac))
{
char x;
token = "";
do
{
token += charac;
x = NextChar();
} while (isalnum(x) || x == '_');
if (*(token.end()-1) == '_')
{
printError("'_' cannot end token");
}
}
else if (isdigit(charac))
{
token = charac;
while (isdigit(NextChar()))
token+=charac;
}
else if (charac == END_OF_FILE)
{
token = charac;
}
else
{
token = "ERROR";
printError ("illegal symbol");
}
}
return token;
}
//Last edited: 11/10 Anna
char NextChar() //returns the next character or end of file marker
{
//read in next character
if(sourceFile.is_open())
{
sourceFile.get(charac);
if (sourceFile.eof())/*end of file*/
{
charac = '$';
sourceFile.close();
//cout << "EOF" << endl;//END_OF_FILE //use a special character to designate end of file
}
else
{
//sourceFile.get(charac);
if(hold)
{
hold = false;
//cout << "A\n";
//while(charac == '\n')
//{
//sourceFile.get(charac);
if(sourceFile.fail())
{
charac = '$';
//listingFile << endl << endl;
sourceFile.close();
}
else
{
lineNum++;
if(charac != '\n')
{
listingFile << "\n" << setw(5) << right << lineNum << "|" << charac;
}
else
{
listingFile << "\n" << setw(5) << right << lineNum << "|";
hold = true;
}
}
//}
}
else if(charac == '\n' && !hold)
{
hold = true;
}
else
{
//cout << "O\n";
listingFile << charac;
}
//listingFile << charac;
}
}
//listingFile << charac; /*charac = next character*/
/*if(sourceFile.is_open() && charac == '\n')
{
cout << "B";
lineNum++;
listingFile << setw(5) << right << lineNum << "|";
}*/
return charac;
}
//Last edited: 11/10 Jacob
//Overloads == to work with the tableEntries
bool operator==(entry lhs, string rhs)
{
return lhs.externalName == rhs;
}
//Last edited: 11/9 Jacob
//Checks to see if str is a BOOLEAN, and returns true if it is
bool IsBool(string str)
{
return str == "true" || str == "false";
}
//Last edited: 11/9 Jacob
//Checks to see if str is an INTEGER, and returns true if it is
bool IsInt(string str)
{
int count = 0;
if(str.length() > 0)
{
if(!isdigit(str.at(0)))
{
if(str.at(0) != '-' && str.at(0) != '+')
{
return false;
}
count++;
}
}
//Check to see if the rest of str is made of numbers
for(unsigned int i = count; i<str.length(); ++i)
{
//Check to see if str is made entirely of numbers, if not, then return false
if(!isdigit(str.at(i)))
{
//Then the string is not a valid INTEGER
return false;
}
}
//If this point is reached, str should be a valid INTEGER with only numbers
return true;
}
//Last edited: 11/9 Jacob
//Checks to see if str is a Pascalite keyword, and returns true if it is
bool IsKeyWord(string str)
{
return (str == "program" || str == "begin" || str == "end" || str == "var" || str == "const" || str == "integer" || str == "boolean" || str == "true" || str == "false" || str == "not" || str == "mod" || str == "div" || str == "and" || str == "or" || str == "read" || str == "write" || str == "if" || str == "then" || str == "else" || str == "repeat" || str == "while" || str == "do" || str == "until" || str == "case" || str == "of" || str = "for" || str == "to" || str == "downto");
}
//Last edited: 11/9 Jacob H
//Checks to see if str is a NON_KEY_ID and returns true if it is and false if it is not
bool IsNonKey(string str)
{
//A NON_KEY_ID must not be a keyword and the first char of a NON_KEY_ID must be a lowercase letter and not an underscore
if(IsKeyWord(str) || str.length() < 1 || !islower(str.at(0)) || str.at(0) == '_')
{
return false;
}
//Then check to see if the rest of the str is alphanum
for(unsigned int i=1; i<str.length(); ++i)
{
//If the current index is an underscore
//it MUST be followed by a letter or number
if(str.at(i)=='_')
{
++i; //Increment the index
//Check to ensure that the new index isn't out of bounds
if(i >= str.length())
{
//Then the string has ended with _ and is thus invalid
return false;
}
}
//Else str has a different char next
//Then another char exists, so check the see if it is alphanum
if(!islower(str.at(i)) && !isdigit(str.at(i)))
{
//Then the string is not a valid alphanum
return false;
}
}
//If this point is reached, str should be a valid NON_KEY_ID, with only letters, numbers, and underscores
return true;
}
//Moved stack declarations to the top
void pushOperator(string op)
{
//cout << "XX:" << "PushOperator : " << op << "+++++++---" << endl;
operators.push(op);
}
string popOperator()
{
//if the operators aren't empty, then pop from the stack
if(!operators.empty())
{
string top = operators.top();
operators.pop();
//cout << "XX:" << "PopOperator : " << top << "------+" << endl;
return top;
}
else
printError("operator stack underflow");
return "ERROR";
}
void pushOperand(string op)
{
//cout << "XX:" << "PushOperand : " << op << " ++++++" << endl;
if(op!= "" && op[0] != 'L')
{
if(op != "" && op[0] != 'L' && find(symbolTable.begin(),symbolTable.end(),op) == symbolTable.end()) //has no symbol entry
{
//Special cases to handle booleans
if(op == "true")
{
Insert(op,BOOLEAN,CONSTANT,"1",YES,1);
}
else if(op == "false")
{
Insert(op,BOOLEAN,CONSTANT,"0",YES,1);
}
else
{
//Insert the literal into the table
Insert(op,WhichType(op),CONSTANT,op,YES,1);
}
}
}
//if a name is a literal and has no symbol table entry.
operands.push(op);
}
string popOperand()
{
if(!operands.empty())
{
string top = operands.top();
operands.pop();
//cout << "XX:" << "popOperand : " << top << " -------" << endl;
return top;
}
else
{
printError("operand stack underflow");
}
return "ERROR";
}
//Giant block of all the operators
void Code(string op, string operand1, string operand2)
{
//cout << "XX:" << "Code: " << op << " " << operand1 << " " << operand2 << endl;
//if op is program, then emit the starting code
if(op == "program")
{
//EmitStartCode();
}
else if(op == "end")
{
//If the end of the program, then emit the end code
if(operand1 == ".")
{
//EmitEndCode();
}
}
else if(op == "read")
{
//think this needs to read in an operand
EmitReadCode(operand1);
}
else if(op == "write")
{
//i think this also needs an operand input
EmitWriteCode(operand1);
}
else if(op == "+")
{
//Test for unary or binary operator
if(operand2 == "")
return;//EmitUniaryAddCode(operand1); Do nothing because this function does nothing
else
EmitAdditionCode(operand1,operand2);
}
else if(op == "-")
{
if(operand2 == "")
EmitNegationCode(operand1);
else
EmitSubtractionCode(operand1,operand2);
}
else if(op == "neg")
{
EmitNegationCode(operand1);
}
else if(op == "not")
{
EmitNotCode(operand1);
}
else if(op == "*")
{
EmitMultiplicationCode(operand1,operand2);
}
else if(op == "div")
{
EmitDivisionCode(operand1,operand2);
}
else if(op == "mod")
{
EmitModCode(operand1,operand2);
}
else if(op == "and")
{
EmitAndCode(operand1,operand2);
}
else if(op == "or")
{
EmitOrCode(operand1,operand2);
}
else if(op == "=")
{
EmitEqualsCode(operand1,operand2);
}
else if(op == "<>")
{
EmitNotEqualsCode(operand1,operand2);
}
else if(op == "<=")
{
EmitLessEqualCode(operand1,operand2);
}
else if(op == ">=")
{
EmitGreaterEqualCode(operand1,operand2);
}
else if(op == "<")
{
EmitLessThanCode(operand1,operand2);
}
else if(op == ">")
{
EmitGreaterThanCode(operand1,operand2);
}
else if(op == ":=")
{
EmitAssignCode(operand1,operand2);
}
else if(op == "then")
{
EmitThenCode(operand1);
}
else if(op == "else")
{
EmitElseCode(operand1);
}
else if(op == "post_if")
{
EmitPostIfCode(operand1);
}
else if(op == "while")
{
EmitWhileCode();
}
else if(op == "do")
{
EmitDoCode(operand1);
}
else if(op == "post_while")
{
EmitPostWhileCode(operand1, operand2);
}
else if(op == "repeat")
{
EmitRepeatCode();
}
else if(op == "until")
{
EmitUntilCode(operand1, operand2);
}
else
{
printError("undefined operation");
}
}
//Anna 11/28
//custom thing, gets passed external name and returns the internal name
string getIntName(string extName)
{
string intName;
//just in case this is called with an internal name, this if will check to see if its an internal and just return it.
if(extName == "")
{
return "EMPTY";
}
if(extName.size() == 2 && isupper(extName[0]) && isdigit(extName[1]))
{
return extName;
}
if(find(symbolTable.begin(),symbolTable.end(),extName) != symbolTable.end())
{
intName = (*find(symbolTable.begin(),symbolTable.end(),extName)).internalName;
}
else
{
printError("reference to an undefined constant or variable");
}
return intName;
}
//----------------------------EMIT STATEMENTS-----------------------------------
void EmitEndCode()
{
entry entr;
//Output halt
objectFile << rammTab << "HLT " << rTbFv << endl;
//Output symbols
for(unsigned int i=0; i<symbolTable.size(); ++i)
{
entr = symbolTable[i];
//If the entry should be saved
if(entr.alloc == YES)
{
//Output the internal name
objectFile << setw(4) << left << entr.internalName << right << " ";
//Determine if a BSS or DEC is needed
if(entr.mode == CONSTANT)
{
objectFile << "DEC ";
//If type is boolean, output will be different than if it is integer
if(entr.dataType == BOOLEAN)
{
//If entr is true, then value is "0001", if false "0000"
objectFile << "000" << entr.value;
}
else
{
//Check if the integer is negative or not
if(entr.value.at(0) == '-')
{
objectFile << "-" << setfill('0') << setw(3) << entr.value.substr(1) << setfill(' ');
}
else
{
objectFile << setfill('0') << setw(4) << entr.value << setfill(' ');
}
}
objectFile << rTbFv;
}
else
{
objectFile << "BSS 0001" << rTbFv;
}
//Comment with external name
objectFile << entr.externalName << endl;
}
}
//Output END
objectFile << rammTab << "END STRT" << rTbFv << endl;
}
void EmitNegationCode(string operand1)
{
string intOp1, intAreg; //internal names for operand 1 and 2 and areg, and a variable for holding temps.
intAreg = getIntName(areg);
intOp1 = getIntName(operand1);
if(WhichType(operand1) != INTEGER)
{
printError("neg operator requires integer operand");
}
if(!ZERO)
{
Insert("ZERO", INTEGER, CONSTANT, "0", YES, 1);
ZERO = true;
}
//A Register holds a temp not operand1 nor operand2 then deassign it
if (intAreg[0] == 'T' && intAreg != intOp1)
{
//emit code to store that temp into memory
objectFile << rammTab << "STA " << setw(4) << left << intAreg << right << rTbFv << "deassign AReg" <<endl;
//change the allocate entry for the temp in the symbol table to yes
(*find(symbolTable.begin(),symbolTable.end(),areg)).alloc = YES;
areg = "";
intAreg = "";
}
//A register holds a non-temp not operand1 nor operand2 then deassign it
if (intAreg[0] != 'T' && intAreg != intOp1)
{
areg = "";
intAreg = "";
}
if(operand1.at(0) == 'T')
FreeTemp();
areg = GetTemp();
objectFile << rammTab << "LDA ZERO" << rTbFv << endl;
objectFile << rammTab << "ISB " << setw(4) << left << intOp1 << right << rTbFv << "-" << operand1 << endl;
pushOperand(areg);
}
void EmitReadCode(string operand1)
{
vector<string> nameEntries;
nameEntries = parseNames(operand1);
//(name broken from list of external names and put into name != "")
for(unsigned int i=0; i<nameEntries.size(); ++i)
{
string intOp = getIntName(nameEntries[i]);
//If trying to read into a const
if((*find(symbolTable.begin(),symbolTable.end(),nameEntries[i])).mode == CONSTANT)
{
string er = "reading in of read-only location \"" + nameEntries[i] + "\"";
printError(er);
}
objectFile << rammTab << "RDI " << setw(4) << left << intOp << right << rTbFv << "read(" << nameEntries[i] << ")" << endl;
}
}
void EmitWriteCode(string operand1)
{
vector<string> nameEntries;
nameEntries = parseNames(operand1);
//(name broken from list of external names and put into name != "")
for(unsigned int i=0; i<nameEntries.size(); ++i)
{
string intOp = getIntName(nameEntries[i]);
objectFile << rammTab << "PRI " << setw(4)<< left << intOp << right << rTbFv << "write(" << nameEntries[i] << ")" << endl;
areg = nameEntries[i];
}
}
void EmitAdditionCode(string operand1,string operand2) //add operand1 to operand2
{
string intOp1, intOp2, intAreg, temporary; //internal names for operand 1 and 2 and areg, and a variable for holding temps.
intAreg = getIntName(areg);
intOp1 = getIntName(operand1);
intOp2 = getIntName(operand2);
if (WhichType(operand1) != INTEGER || WhichType(operand2) != INTEGER)
{
printError("operator + requires integer operands");
}
//A Register holds a temp not operand1 nor operand2 then deassign it
if (intAreg[0] == 'T' && (intAreg != intOp1 && intAreg != intOp2))
{
//emit code to store that temp into memory
objectFile << rammTab << "STA " << setw(4) << left << intAreg << right << rTbFv << "deassign AReg" <<endl;
//change the allocate entry for the temp in the symbol table to yes
(*find(symbolTable.begin(),symbolTable.end(),areg)).alloc = YES;
areg = "";
intAreg = "";
}
//A register holds a non-temp not operand1 nor operand2 then deassign it
if (intAreg[0] != 'T' && (intAreg != intOp1 && intAreg != intOp2))
{
areg = "";
intAreg = "";
}
//if neither operand is in A register then
if(intAreg[0] != 'T' && intAreg != intOp1 && intAreg != intOp2)
{
//emit code to load operand2 into A register
objectFile << rammTab << "LDA " << setw(4) << left << left <<intOp2 << right << right << rTbFv << endl;
intAreg = intOp2;
}
//emit code to perform register-memory addition
if(intAreg == intOp2)
{
objectFile << rammTab << "IAD " << setw(4) << left << intOp1 << right << rTbFv << operand2 << " + " << operand1 << endl;
}
else if (intAreg == intOp1)
{
objectFile << rammTab << "IAD " << setw(4) << left << intOp2 << right << rTbFv << operand2 << " + " << operand1 << endl;
}
//deassign all temporaries involved in the addition and free those names for reuse
//if operator 1 and/or 2 were a temp, free them
if(operand1[0] == 'T')
{
FreeTemp();
}
if(operand2[0] == 'T')
{
FreeTemp();
}
//A Register = next available temporary name and change type of its symbol table entry to integer
areg = GetTemp();
(*find(symbolTable.begin(),symbolTable.end(),areg)).dataType = INTEGER;
pushOperand(areg);
//push the name of the result onto operandStk
}
void EmitSubtractionCode(string operand1, string operand2)
{
string intAreg = getIntName(areg);
string intOp1 = getIntName(operand1);
string intOp2 = getIntName(operand2);
if (WhichType(operand1) != INTEGER || WhichType(operand2) != INTEGER)
{
printError("operator - requires integer operands");
}
//A Register holds a temp not operand1 nor operand2 then deassign it
if (intAreg[0] == 'T' && intAreg != intOp2)
{
//emit code to store that temp into memory
objectFile << rammTab << "STA " << setw(4) << left << intAreg << right << rTbFv << "deassign AReg" <<endl;
//change the allocate entry for the temp in the symbol table to yes
(*find(symbolTable.begin(),symbolTable.end(),areg)).alloc = YES;
areg = "";
intAreg = "";
}
//A register holds a non-temp not operand1 nor operand2 then deassign it
if (intAreg[0] != 'T' && intAreg != intOp2)
{
areg = "";
intAreg = "";
}
//operand 2 is not in the A register then load it
if(intAreg != intOp2)
{
//emit code to load operand2 into A register
objectFile << rammTab << "LDA " << setw(4) << left <<intOp2 << right << rTbFv << endl;
}
//emit code to perform register-memory subtraction
objectFile << rammTab<< "ISB " << setw(4) << left <<intOp1 << right << rTbFv << operand2 << " - " << operand1 << endl;
//deassign all temporaries involved in the addition and free those names for reuse
//if operator 1 and/or 2 were a temp, free them
if(operand1[0] == 'T')
{
FreeTemp();
}
if(operand2[0] == 'T')
{
FreeTemp();
}
//A Register = next available temporary name and change type of its symbol table entry to integer
areg = GetTemp();
(*find(symbolTable.begin(),symbolTable.end(),areg)).dataType = INTEGER;
pushOperand(areg);
//push the name of the result onto operandStk
}
void EmitDivisionCode(string operand1,string operand2) //divide operand2 by operand1
{
//cout << "XX:" << " EmitDivision: " << operand2 << "/" << operand1 << endl;
string intOp1, intOp2, intAreg; //internal names for operand 1 and 2 and areg
intAreg = getIntName(areg);
intOp1 = getIntName(operand1);
intOp2 = getIntName(operand2);
//cout << "XX:" << " EmitDivisionInternals: " << "areg:" << intAreg << " " << intOp2 << "/" << intOp1 << endl;
//if either operand is not integer
if (WhichType(operand1) != INTEGER || WhichType(operand2) != INTEGER)
{
printError("operator div requires integer operands");
}
//if A Register holds a temp not operand2
if(intAreg[0] == 'T' && intAreg != intOp2)
{
//emit code to store that temp into memory
objectFile << rammTab << "STA " << setw(4) << left << intAreg << right << rTbFv << "deassign AReg" <<endl;
//change the allocate entry for the temp in the symbol table to yes
(*find(symbolTable.begin(),symbolTable.end(),areg)).alloc = YES;
areg = "";
intAreg = "";
}
//if A register holds a non-temp not operand2 then deassign it
if(intAreg[0] != 'T' && intAreg != intOp2)
{
areg = "";
intAreg = "";
}
//if operand2 is not in A register
if (intAreg != intOp2)
{
//emit instruction to do a register-memory load of operand2 into the A register;
objectFile << rammTab << "LDA " << setw(4) << left <<intOp2 << right <<rTbFv << endl;
}
// emit code to perform a register-memory division
objectFile << rammTab << "IDV " << setw(4) << left <<intOp1 << right << rTbFv << operand2 << " div " << operand1 << endl;
//deassign all temporaries involved and free those names for reuse
//if operator 1 and/or 2 were a temp, free them
if(operand1[0] == 'T')
{
FreeTemp();
}
if(operand2[0] == 'T')
{
FreeTemp();
}
//A Register = next available temporary name and change type of its symbol table entry to integer
areg = GetTemp();
(*find(symbolTable.begin(),symbolTable.end(),areg)).dataType = INTEGER;
pushOperand(areg);
//push the name of the result onto operandStk
}
void EmitMultiplicationCode(string operand1,string operand2) //multiply operand2 by operand1
{
string intOp1, intOp2, intAreg; //internal names for operand 1 and 2 and areg
intAreg = getIntName(areg);
intOp1 = getIntName(operand1);
intOp2 = getIntName(operand2);
//if either operand is not integer
if (WhichType(operand1) != INTEGER || WhichType(operand2) != INTEGER)
{
printError("operator * requires integer operands");
}
//if A Register holds a temp not operand1 nor operand2 then
if(intAreg[0] == 'T' && (intAreg != intOp1 && intAreg != intOp2 ))
{
//emit code to store that temp into memory
objectFile << rammTab << "STA " << setw(4) << left <<areg <<right << rTbFv << "deassign AReg" <<endl;
//change the allocate entry for the temp in the symbol table to yes
(*find(symbolTable.begin(),symbolTable.end(),areg)).alloc = YES;
areg = "";
intAreg = "";
}
//if A register holds a non-temp not operand2 nor operand1 then deassign it
if(intAreg[0] != 'T' && intAreg != intOp1 && intAreg != intOp2)
{
areg = "";
intAreg = "";
}
//if neither operand is in A register then
if(intAreg != intOp1 && intAreg != intOp2)
{
//emit code to load operand2 into the A register;
objectFile << rammTab << "LDA " << setw(4) << left << intOp2 << right << rTbFv << endl;
areg = intOp2;
}
//emit code to perform a register-memory multiplication with A Register holding the result;
if(areg == intOp1)
{
//objectFile << "areg == intOp1" << endl;
objectFile << rammTab << "IMU " << setw(4) << left << intOp2 << right << rTbFv << operand2 << " * " << operand1 << endl;
}
else if (areg == intOp2)
{
//objectFile << "areg == intOp2" << endl;
objectFile << rammTab << "IMU " << setw(4) << left << intOp1 << right << rTbFv << operand2 << " * " << operand1 << endl;
}
//deassign all temporaries involved in and free those names for reuse
//if operator 1 and/or 2 were a temp, free them
if(operand1[0] == 'T')
{
FreeTemp();
}
if(operand2[0] == 'T')
{
FreeTemp();
}
//A Register = next available temporary name and change type of its symbol table entry to integer
areg = GetTemp();
(*find(symbolTable.begin(),symbolTable.end(),areg)).dataType = INTEGER;
pushOperand(areg);
//push the name of the result onto operandStk
}
void EmitModCode(string operand1, string operand2)
{
string intOp1, intOp2, intAreg; //internal names for operand 1 and 2 and areg
intAreg = getIntName(areg);
intOp1 = getIntName(operand1);
intOp2 = getIntName(operand2);
//if either operand is not integer
if (WhichType(operand1) != INTEGER || WhichType(operand2) != INTEGER)
{
printError("operator mod requires integer operands");
}
//if A Register holds a temp not operand1 nor operand2 then
if(intAreg[0] == 'T' && intAreg != intOp2)
{
//emit code to store that temp into memory
objectFile << rammTab << "STA " << setw(4) << left << intAreg << right << rTbFv << "deassign AReg" <<endl;
//change the allocate entry for it in the symbol table to yes
(*find(symbolTable.begin(),symbolTable.end(),areg)).alloc = YES;
areg = "";
intAreg = "";
}
//if A register holds a non-temp not operand2 nor operand1 then deassign it
if(intAreg[0] != 'T' && intAreg != intOp2)
{
areg = "";
intAreg = "";
}
//if operand 2 is not in the register, load it in there
if(intAreg != intOp2)
{
//emit code to load operand2 into the A register;
objectFile << rammTab << "LDA " << setw(4) << left <<intOp2 << right << rTbFv << endl;
}
//divide by op1
objectFile << rammTab << "IDV " << setw(4)<< left <<intOp1 << right << rTbFv << operand2 << " mod " << operand1 << endl;
//A Register = next available temporary name and change type of its symbol table entry to integer
areg = GetTemp();
(*find(symbolTable.begin(),symbolTable.end(),areg)).dataType = INTEGER;
(*find(symbolTable.begin(),symbolTable.end(),areg)).alloc = YES;
//push name of result onto operandStk;
pushOperand(areg);
objectFile << rammTab << "STQ " << setw(4) << left << areg << right << rTbFv << "store remainder in memory" << endl;
objectFile << rammTab << "LDA " << setw(4) << left << areg << right << rTbFv << "load remainder from memory" << endl;
//deassign all temporaries involved and free those names for reuse;
if(operand1[0] == 'T')
{
FreeTemp();
}
if(operand2[0] == 'T')
{
FreeTemp();
}
}
void EmitAndCode(string operand1,string operand2) //"and" operand1 to operand2
{
string intOp1, intOp2, intAreg; //internal names for operand 1 and 2 and areg
intAreg = getIntName(areg);
intOp1 = getIntName(operand1);
intOp2 = getIntName(operand2);
//if either operand is not boolean
if (WhichType(operand1) != BOOLEAN || WhichType(operand2) != BOOLEAN)
{
printError("operator and requires boolean operands");
}
//if A Register holds a temp not operand1 nor operand2 then
if(intAreg[0] == 'T' && (intAreg != intOp1 && intAreg != intOp2))
{
//emit code to store that temp into memory
objectFile << rammTab << "STA " << setw(4) << left <<intAreg << right << rTbFv << "deassign AReg" <<endl;
//change the allocate entry for it in the symbol table to yes
(*find(symbolTable.begin(),symbolTable.end(),areg)).alloc = YES;
areg = "";
intAreg = "";
}
//if A register holds a non-temp not operand2 nor operand1 then deassign it
if(intAreg[0] != 'T' && (intAreg != intOp1 && intAreg != intOp2))
{
areg = "";
intAreg = "";
}
//if neither operand is in A register then
if(intAreg != intOp1 && intAreg != intOp2)
{
//emit code to load operand2 into the A register;
objectFile << rammTab << "LDA " << setw(4) << left <<intOp2 << right << rTbFv << endl;
areg = intOp2;
}
//emit code to perform a register-memory multiplication with A Register holding the result;
if(areg == intOp2)
{
objectFile << rammTab << "IMU " << setw(4) << left <<intOp1 << right << rTbFv << operand2 << " and " << operand1 << endl;
}
else if (areg == intOp1)
{
objectFile << rammTab << "IMU " << setw(4) << left <<intOp2 << right << rTbFv << operand2 << " and " << operand1 << endl;
}
//deassign all temporaries involved and free those names for reuse;
if(operand1[0] == 'T')
{
FreeTemp();
}
if(operand2[0] == 'T')
{
FreeTemp();
}
//A Register is nothing useful so deassign
areg = GetTemp();
intAreg = "";
(*find(symbolTable.begin(),symbolTable.end(),areg)).dataType = BOOLEAN;
pushOperand(areg);
}
void EmitOrCode(string operand1, string operand2)
{
string intOp1, intOp2, intAreg; //internal names for operand 1 and 2 and areg
intAreg = getIntName(areg);
intOp1 = getIntName(operand1);
intOp2 = getIntName(operand2);
//if either operand is not boolean
if (WhichType(operand1) != BOOLEAN || WhichType(operand2) != BOOLEAN)
{
printError("operator or requires boolean operands");
}
//If there is a temp that is not operand1 or operand 2 in the register, store it out
if(areg != "" && areg.at(0) == 'T' && (areg != operand1 && areg != operand2))
{
//emit code to store that temp into memory
objectFile << rammTab << "STA " << setw(4) << left << intAreg << right << rTbFv << "deassign AReg" << endl;
//change the allocate entry for the temp in the symbol table to yes
(*find(symbolTable.begin(),symbolTable.end(),areg)).alloc = YES;
areg = "";
intAreg = "";
}
//If there is a non temp variable that is not an operand, then deassign areg
if(areg != "" && areg.at(0) != 'T' && areg != operand1 && areg != operand2)
{
areg = "";
intAreg = "";
}
//if neither operand is in A register then
if(intAreg != intOp1 && intAreg != intOp2)
{
//emit code to load operand2 into A register
objectFile << rammTab << "LDA " << setw(4) << left <<intOp2 << right << rTbFv << endl;
areg = intOp2;
}
//Add operand 1 and 2
if(areg == intOp2)
{
objectFile << rammTab << "IAD " << setw(4) << left <<intOp1 << right << rTbFv << operand2 << " or " << operand1 << endl;
}
else if(areg == intOp1)
{
objectFile << rammTab << "IAD " << setw(4) << left <<intOp2 << right << rTbFv << operand2 << " or " << operand1 << endl;
}
//if zero jump to the next lable +1
objectFile << rammTab << "AZJ " << "L" << setw(3) << left << loopCount << "+1 " << endl;
//If true is not in the symbol table, it must be added
if(!TRU)
{
Insert("TRUE", BOOLEAN, CONSTANT, "1", YES, 1, "TRUE");
TRU = true;
}
objectFile << "L" << setw(3) << left << loopCount << " LDA " << "TRUE" << rTbFv << endl;
loopCount++;
if(operand1.at(0) == 'T')
FreeTemp();
if(operand2.at(0) == 'T')
FreeTemp();
areg = GetTemp();
(*find(symbolTable.begin(),symbolTable.end(),areg)).dataType = BOOLEAN;
pushOperand(areg);
}
void EmitNotCode(string operand)
{
string intOp = getIntName(operand);
if(WhichType(operand) != BOOLEAN)
{
printError("operator not requires boolean operands");
}
/*if(!ZERO)
{
Insert("ZERO", INTEGER, CONSTANT, "0", YES, 1, "ZERO");
ZERO = true;
}*/
//If A doesn't contain operand, it must be loaded
if(areg != operand)
{
objectFile << rammTab << "LDA " << setw(4) << left << intOp << right << rTbFv << endl;
}
objectFile << rammTab << "AZJ " << "L" << setw(3) << left << loopCount << rTbFv << "not " << operand << endl;
//If false does not exist, then add it to the symbol table
if(!FALS)
{
Insert("FALSE", BOOLEAN, CONSTANT, "0", YES, 1, "FALS");
FALS = true;
}
//Then load false
objectFile << rammTab << "LDA " << "FALS" << rTbFv << endl;
//Unconditional jump to after the label
objectFile << rammTab << "UNJ " << "L" << setw(3) << left << loopCount << "+1 " << endl;
//Label, load true
//If true does not exist, then add it to the symbol table
if(!TRU)
{
Insert("TRUE", BOOLEAN, CONSTANT, "1", YES, 1, "TRUE");
TRU = true;
}
objectFile << "L" << setw(3) << left << loopCount << " LDA " << "TRUE" << rTbFv << endl;
if(operand.at(0) == 'T')
{
FreeTemp();
}
areg = GetTemp();
(*find(symbolTable.begin(),symbolTable.end(),areg)).dataType = BOOLEAN;
pushOperand(areg);
}
void EmitEqualsCode(string operand1,string operand2) //test whether operand2 equals operand1
{
string intOp1, intOp2, intAreg; //internal names for operand 1 and 2 and areg
intAreg = getIntName(areg);
intOp1 = getIntName(operand1);
intOp2 = getIntName(operand2);
//if types of operands are not the same
if(WhichType(operand1) != WhichType(operand2))
{
printError("incompatible types");
}
//if A Register holds a temp not operand1 nor operand2 then
if(intAreg[0] == 'T' && (intAreg != intOp1 && intAreg != intOp2))
{
//emit code to store that temp into memory
objectFile << rammTab << "STA " << setw(4) << left << intAreg << right << rTbFv << "deassign AReg" <<endl;
//change the allocate entry for it in the symbol table to yes
(*find(symbolTable.begin(),symbolTable.end(),areg)).alloc = YES;
areg = "";
intAreg = "";
}
// if A register holds a non-temp not operand2 nor operand1 then deassign it
if(intAreg[0] != 'T' && intAreg != intOp1 && intAreg != intOp2)
{
areg = "";
intAreg = "";
}
if(intAreg == intOp2)
{
//emit code to load operand2 into the A register;
//objectFile << rammTab << "LDA " << setw(4) << left <<intOp1 << right << rTbFv << endl;
objectFile << rammTab << "ISB " << setw(4) << left <<intOp1 << right << rTbFv << operand2 << " = " << operand1 << endl;
}
else if(intAreg == intOp1)
{
//objectFile << rammTab << "LDA " << setw(4) << left <<intOp2 << right << rTbFv << endl;
objectFile << rammTab << "ISB " << setw(4) << left <<intOp2 << right << rTbFv << operand2 << " = " << operand1 << endl;
}
else
{
objectFile << rammTab << "LDA " << setw(4) << left <<intOp2 << right << rTbFv << endl;
objectFile << rammTab << "ISB " << setw(4) << left <<intOp1 << right << rTbFv << operand2 << " = " << operand1 << endl;
}
//emit code to perform a register-memory subtraction with A Register holding the result;
//objectFile << rammTab << "ISB " << setw(4) << left <<intOp1 << right << rTbFv << operand2 << " = " << operand1 << endl;
//emit code to perform an AZJ to the next available Ln
objectFile << rammTab << "AZJ L" << setw(3) << left <<loopCount <<right <<rTbFv << endl;
//emit code to do a register-memory load FALS
objectFile << rammTab << "LDA FALS" << rTbFv<< endl;
//Insert FALS in symbol table with value 0 and external name false
if(!FALS)
{
Insert("FALSE", BOOLEAN, CONSTANT, "0", YES, 1, "FALS");
FALS = true;
}
//emit code to perform a UNJ to the acquired label Ln +1
objectFile << rammTab << "UNJ " << "L" << setw(3) << left <<loopCount <<right<< "+1 " << rTbFv << endl;
//emit code to label the next instruction with the acquired label Ln
//and do a register-memory load TRUE
objectFile << "L" << setw(3) << left << loopCount << " LDA " << "TRUE" << rTbFv << endl;
loopCount++;
if(!TRU)
{
Insert("TRUE", BOOLEAN, CONSTANT, "1", YES, 1, "TRUE");
TRU = true;
}
//Insert TRUE in symbol table with value 1 and external name true
//deassign all temporaries involved and free those names for reuse;
if(operand1[0] == 'T')
{
FreeTemp();
}
if(operand2[0] == 'T')
{
FreeTemp();
}
areg = GetTemp();
(*find(symbolTable.begin(),symbolTable.end(),areg)).dataType = BOOLEAN;
pushOperand(areg);
}
void EmitNotEqualsCode(string operand1,string operand2) //test whether operand2 equals operand1
{
string intOp1, intOp2, intAreg; //internal names for operand 1 and 2 and areg
intAreg = getIntName(areg);
intOp1 = getIntName(operand1);
intOp2 = getIntName(operand2);
//if types of operands are not the same
if(WhichType(operand1) != WhichType(operand2))
{
printError("incompatible types");
}
//if A Register holds a temp not operand1 nor operand2 then
if(intAreg[0] == 'T' && intAreg != intOp1 && intAreg != intOp2 )
{
//deassign it
//emit code to store that temp into memory
objectFile << rammTab << "STA " << setw(4) << left << intAreg << right << rTbFv << "deassign AReg" <<endl;
//change the allocate entry for it in the symbol table to yes
(*find(symbolTable.begin(),symbolTable.end(),areg)).alloc = YES;
areg = "";
intAreg = "";
}
// if A register holds a non-temp not operand2 nor operand1 then deassign it
if(intAreg[0] != 'T' && intAreg != intOp1 && intAreg != intOp2)
{
areg = "";
intAreg = "";
}
if(intAreg == intOp2)
{
//emit code to load operand2 into the A register;
//objectFile << rammTab << "LDA " << setw(4) << left <<intOp1 << right << rTbFv << endl;
objectFile << rammTab << "ISB " << setw(4) << left <<intOp1 << right << rTbFv << operand2 << " <> " << operand1 << endl;
}
else if(intAreg == intOp1)
{
//objectFile << rammTab << "LDA " << setw(4) << left <<intOp2 << right << rTbFv << endl;
objectFile << rammTab << "ISB " << setw(4) << left <<intOp2 << right << rTbFv << operand2 << " <> " << operand1 << endl;
}
else
{
objectFile << rammTab << "LDA " << setw(4) << left <<intOp2 << right << rTbFv << endl;
objectFile << rammTab << "ISB " << setw(4) << left <<intOp1 << right << rTbFv << operand2 << " <> " << operand1 << endl;
}
//emit code to perform an AZJ to the next available Ln
objectFile << rammTab << "AZJ L" << setw(3) << left <<loopCount <<right << "+1 " << endl;
objectFile << "L" << loopCount << " LDA TRUE " << endl;
//Insert TRUE in symbol table with value 1 and external name false
if(!TRU)
{
Insert("TRUE", BOOLEAN, CONSTANT, "1", YES, 1, "TRUE");
TRU = true;
}
loopCount++;
//deassign all temporaries involved and free those names for reuse;
if(operand1[0] == 'T')
{
FreeTemp();
}
if(operand2[0] == 'T')
{
FreeTemp();
}
//A Register is garbage so deassign
areg = GetTemp();
(*find(symbolTable.begin(),symbolTable.end(),areg)).dataType = BOOLEAN;
pushOperand(areg);
}
void EmitLessThanCode(string operand1, string operand2)
{
string intOp1, intOp2, intAreg; //internal names for operand 1 and 2 and areg
intAreg = getIntName(areg);
intOp1 = getIntName(operand1);
intOp2 = getIntName(operand2);
//if types of operands are not the same
if(WhichType(operand1) != WhichType(operand2))
{
printError("incompatible types");
}
//if A Register holds a temp not operand1 nor operand2 then
if(intAreg[0] == 'T' && (intAreg != intOp1 && intAreg != intOp2))
{
//emit code to store that temp into memory
objectFile << rammTab << "STA " << setw(4) << left << intAreg << right << rTbFv << "deassign AReg" <<endl;
//change the allocate entry for it in the symbol table to yes
(*find(symbolTable.begin(),symbolTable.end(),areg)).alloc = YES;
areg = "";
intAreg = "";
}
// if A register holds a non-temp not operand2 nor operand1 then deassign it
if(intAreg[0] != 'T' && intAreg != intOp1 && intAreg != intOp2)
{
areg = "";
intAreg = "";
}
//if neither operand is in A register then
if(intAreg != intOp2)
{
//emit code to load operand2 into the A register;
objectFile << rammTab << "LDA " << setw(4) << left <<intOp2 << right << rTbFv << endl;
}
objectFile << rammTab << "ISB " << setw(4) << left <<intOp1 << right << rTbFv << operand2 << " < " << operand1 << endl;
objectFile << rammTab << "AMJ L" << setw(3) << left <<loopCount <<right << rTbFv << endl;
//if the result isn't negative, then its false
objectFile << rammTab << "LDA FALS" << rTbFv << endl;
if(!FALS)
{
Insert("FALSE", BOOLEAN, CONSTANT, "0", YES, 1, "FALS");
FALS = true;
}
objectFile << rammTab << "UNJ " << "L" << setw(3) << left <<loopCount <<right << "+1 " << endl;
//if the result /IS/ negative then its true
objectFile << "L" << setw(3)<< left << loopCount << " LDA " << "TRUE" << rTbFv << endl;
if(!TRU)
{
Insert("TRUE", BOOLEAN, CONSTANT, "1", YES, 1, "TRUE");
TRU = true;
}
loopCount++;
//deassign all temporaries involved and free those names for reuse;
if(operand1[0] == 'T')
{
FreeTemp();
}
if(operand2[0] == 'T')
{
FreeTemp();
}
areg = GetTemp();
(*find(symbolTable.begin(),symbolTable.end(),areg)).dataType = BOOLEAN;
pushOperand(areg);
}
void EmitLessEqualCode(string operand1, string operand2)
{
string intOp1, intOp2, intAreg; //internal names for operand 1 and 2 and areg
intAreg = getIntName(areg);
intOp1 = getIntName(operand1);
intOp2 = getIntName(operand2);
//if types of operands are not the same
if(WhichType(operand1) != WhichType(operand2))
{
printError("incompatible types");
}
//if A Register holds a temp not operand1 nor operand2 then
if(intAreg[0] == 'T' && (intAreg != intOp1 && intAreg != intOp2))
{
//emit code to store that temp into memory
objectFile << rammTab << "STA " << setw(4) << left << areg << right << rTbFv << "deassign AReg" <<endl;
//change the allocate entry for it in the symbol table to yes
(*find(symbolTable.begin(),symbolTable.end(),areg)).alloc = YES;
areg = "";
intAreg = "";
}
// if A register holds a non-temp not operand2 nor operand1 then deassign it
if(intAreg[0] != 'T' && intAreg != intOp1 && intAreg != intOp2)
{
areg = "";
intAreg = "";
}
//if neither operand is in A register then
if(intAreg != intOp1 && intAreg != intOp2)
{
//emit code to load operand2 into the A register;
objectFile << rammTab << "LDA " << setw(4) << left <<intOp2 << right << rTbFv << endl;
areg = intOp2;
}
if(areg == intOp1)
{
objectFile << rammTab << "ISB " << setw(4) << left <<intOp2 << right << rTbFv << operand2 << " <= " << operand1 << endl;
}
else if(areg == intOp2)
{
objectFile << rammTab << "ISB " << setw(4) << left <<intOp1 << right << rTbFv << operand2 << " <= " << operand1 << endl;
}
objectFile << rammTab << "AMJ L" << setw(3) << left <<loopCount <<right << rTbFv << endl;
objectFile << rammTab << "AZJ L" << setw(3) << left <<loopCount <<right << rTbFv << endl;
//if the result isn't negative, then its false
objectFile << rammTab << "LDA FALS" << rTbFv << endl;
if(!FALS)
{
Insert("FALSE", BOOLEAN, CONSTANT, "0", YES, 1, "FALS");
FALS = true;
}
objectFile << rammTab << "UNJ " << "L" << setw(3) << left <<loopCount <<right << "+1 " << endl;
//if the result /IS/ negative then its true
objectFile << "L" << setw(3) << left << loopCount << " LDA " << "TRUE" << rTbFv << endl;
if(!TRU)
{
Insert("TRUE", BOOLEAN, CONSTANT, "1", YES, 1, "TRUE");
TRU = true;
}
loopCount++;
//deassign all temporaries involved and free those names for reuse;
if(operand1[0] == 'T')
{
FreeTemp();
}
if(operand2[0] == 'T')
{
FreeTemp();
}
areg = GetTemp();
(*find(symbolTable.begin(),symbolTable.end(),areg)).dataType = BOOLEAN;
pushOperand(areg);
}
void EmitGreaterEqualCode(string operand1, string operand2)
{
string intOp1, intOp2, intAreg; //internal names for operand 1 and 2 and areg
intAreg = getIntName(areg);
intOp1 = getIntName(operand1);
intOp2 = getIntName(operand2);
//if types of operands are not the same
if(WhichType(operand1) != WhichType(operand2))
{
printError("incompatible types");
}
//if A Register holds a temp not operand1 nor operand2 then
if(intAreg[0] == 'T' && (intAreg != intOp1 && intAreg != intOp2))
{
//emit code to store that temp into memory
objectFile << rammTab << "STA " << setw(4) << left << areg << right << rTbFv << "deassign AReg" <<endl;
//change the allocate entry for it in the symbol table to yes
(*find(symbolTable.begin(),symbolTable.end(),areg)).alloc = YES;
areg = "";
intAreg = "";
}
// if A register holds a non-temp not operand2 nor operand1 then deassign it
if(intAreg[0] != 'T' && intAreg != intOp1 && intAreg != intOp2)
{
areg = "";
intAreg = "";
}
//if neither operand is in A register then
if(intAreg != intOp2)
{
//emit code to load operand2 into the A register;
objectFile << rammTab << "LDA " << setw(4) << left <<intOp2 << right << rTbFv << endl;
}
objectFile << rammTab << "ISB " << setw(4) << left <<intOp1 << right << rTbFv << operand2 << " >= " << operand1 << endl;
objectFile << rammTab << "AMJ L" << setw(3) << left <<loopCount <<right << rTbFv << endl;
//if the result isn't negative, then its false
objectFile << rammTab << "LDA TRUE" << rTbFv << endl;
if(!FALS)
{
Insert("FALSE", BOOLEAN, CONSTANT, "0", YES, 1, "FALS");
FALS = true;
}
objectFile << rammTab << "UNJ " << "L" << setw(3) << left <<loopCount <<right << "+1 " << endl;
//if the result /IS/ negative then its true
objectFile << "L" << setw(3) << left << loopCount << " LDA " << "FALS" << rTbFv << endl;
if(!TRU)
{
Insert("TRUE", BOOLEAN, CONSTANT, "1", YES, 1, "TRUE");
TRU = true;
}
loopCount++;
//deassign all temporaries involved and free those names for reuse;
if(operand1[0] == 'T')
{
FreeTemp();
}
if(operand2[0] == 'T')
{
FreeTemp();
}
areg = GetTemp();
(*find(symbolTable.begin(),symbolTable.end(),areg)).dataType = BOOLEAN;
pushOperand(areg);
}
void EmitGreaterThanCode(string operand1, string operand2)
{
string intOp1, intOp2, intAreg; //internal names for operand 1 and 2 and areg
intAreg = getIntName(areg);
intOp1 = getIntName(operand1);
intOp2 = getIntName(operand2);
//if types of operands are not the same
if(WhichType(operand1) != WhichType(operand2))
{
printError("incompatible types");
}
//if A Register holds a temp not operand1 nor operand2 then
if(intAreg[0] == 'T' && (intAreg != intOp1 && intAreg != intOp2))
{
//emit code to store that temp into memory
objectFile << rammTab << "STA " << setw(4) << left << areg << right << rTbFv << "deassign AReg" <<endl;
//change the allocate entry for it in the symbol table to yes
(*find(symbolTable.begin(),symbolTable.end(),areg)).alloc = YES;
areg = "";
intAreg = "";
}
// if A register holds a non-temp not operand2 nor operand1 then deassign it
if(intAreg[0] != 'T' && intAreg != intOp1 && intAreg != intOp2)
{
areg = "";
intAreg = "";
}
if(intAreg != intOp2)
{
//emit code to load operand2 into the A register;
objectFile << rammTab << "LDA " << setw(4) << left <<intOp2 << right << rTbFv << endl;
}
objectFile << rammTab << "ISB " << setw(4) << left <<intOp1 << right << rTbFv << operand2 << " > " << operand1 << endl;
objectFile << rammTab << "AMJ L" << setw(3) << left <<loopCount <<right << rTbFv << endl;
objectFile << rammTab << "AZJ L" << setw(3) << left <<loopCount <<right << rTbFv << endl;
//if the result isn't negative, then its false
if(!TRU)
{
Insert("TRUE", BOOLEAN, CONSTANT, "1", YES, 1, "TRUE");
TRU = true;
}
objectFile << rammTab << "LDA TRUE" << rTbFv << endl;
if(!FALS)
{
Insert("FALSE", BOOLEAN, CONSTANT, "0", YES, 1, "FALS");
FALS = true;
}
objectFile << rammTab << "UNJ " << "L" << setw(3) << left << loopCount << "+1 " << endl;
//if the result /IS/ negative then its true
objectFile << "L" << setw(3) << left << loopCount << " LDA " << "FALS" << rTbFv << endl;
loopCount++;
//deassign all temporaries involved and free those names for reuse;
if(operand1[0] == 'T')
{
FreeTemp();
}
if(operand2[0] == 'T')
{
FreeTemp();
}
areg = GetTemp();
(*find(symbolTable.begin(),symbolTable.end(),areg)).dataType = BOOLEAN;
pushOperand(areg);
}
void EmitAssignCode(string operand1,string operand2) //assign the value of operand1 to operand2
{
string intOp1, intOp2, intAreg; //internal names for operand 1 and 2 and areg
intAreg = getIntName(areg);
intOp1 = getIntName(operand1);
intOp2 = getIntName(operand2);
//if types of operands are not the same
if (WhichType(operand1) != WhichType(operand2))
{
printError("incompatible types"); //process error: incompatible types
}
//if storage mode of operand2 is not VARIABLE
if((*find(symbolTable.begin(),symbolTable.end(),operand2)).mode != VARIABLE)
{
//process error: symbol on left-hand side of assignment must have a storage mode of VARIABLE
printError("symbol on left-hand side of assignment must have a storage mode of VARIABLE");
}
//if operand1 = operand2 return;
//symbol table doesn't update values so if the values this won't work
//if((*find(symbolTable.begin(),symbolTable.end(),operand2)).value == (*find(symbolTable.begin(),symbolTable.end(),operand1)).value)
if(operand1 == operand2)
{
return;
}
//if operand1 is not in A register then
if (areg != intOp1)
{
//emit code to load operand1 into the A register;
objectFile << rammTab << "LDA " << setw(4) << left <<intOp1 << right << rTbFv << endl;
}
//emit code to store the contents of that register into the memory location pointed to by operand2
objectFile << rammTab << "STA " << setw(4) << left << intOp2 << right << rTbFv << operand2 << " := " << operand1 << endl;
//deassign operand1;
//if operand1 is a temp then free its name for reuse;
if(intOp1[0] == 'T')
{
FreeTemp();
areg = "";
}
areg = operand2;
objectFile << "areg = " << operand2 << " from EmitAssign" << endl;
//free temporary
//operand2 can never be a temporary since it is to the left of ':='
}
void FreeTemp()
{
tempCount--;
if (tempCount < -1)
{
printError("compiler error, currentTempNo should be >= –1");
}
}
string GetTemp()
{
ostringstream temp;
tempCount++;
temp << "T";
temp << tempCount;
if (tempCount > maxTempCount)
{
//Insert a temp that does not take up memory and has default type of INTEGER, this should be changed by the calling function
Insert(temp.str(), INTEGER, VARIABLE, "", NO, 1);
maxTempCount++;
}
return temp.str();
}
void EmitStartCode()
{
entry ent = symbolTable[0];
//If the first entry in the symbol table isn't the program name, then look through the entire table for it
if(ent.dataType != PROG_NAME)
{
for(unsigned int i=0; i<symbolTable.size(); ++i)
{
if(symbolTable[i].dataType == PROG_NAME)
{
ent = symbolTable[i];
break;
}
}
}
objectFile << "STRT NOP" << rTbFv << rTbFv << ent.externalName << " - Anna Porter, Jacob Hallenberger" << endl;
}
void EmitThenCode(string operand) //emit code that follows 'then' and statement predicate
{
ostringstream tempLabel;
tempLabel << "L" << loopCount;
loopCount++;
if(WhichType(operand) != BOOLEAN)
{
printError("Condition must be a boolean");
}
//emit instruction to set the condition code depending on the value of operand;
string intOp = getIntName(operand);
if(areg != operand)
{
objectFile << rammTab << "LDA " << intOp << rTbFv << endl;
}
//emit instruction to branch to tempLabel if the condition code indicates operand is zero (false)
objectFile << rammTab << "AZJ " << setw(4) << left << tempLabel.str() << right << rTbFv << "if false jump to " << tempLabel.str() << endl;
//push tempLabel onto operandStk so that it can be referenced when EmitElseCode() or EmitPostIfCode() is called;
pushOperand(tempLabel.str());
//if operand is a temp then
if(operand[0] == 'T')
{
//free operand's name for reuse;
FreeTemp();
}
//deassign operands from all registers
areg = "";
}
void EmitElseCode(string operand) //emit code that follows else clause of if statement
{
ostringstream tempLabel;
tempLabel << "L" << loopCount;
loopCount++;
//emit instruction to branch unconditionally to tempLabel;
objectFile << rammTab << "UNJ " << setw(4) << left << tempLabel.str() << right << rTbFv << "jump to end if" << endl;
//emit instruction to label this point of object code with the argument operand;
objectFile << setw(6) << left << operand << setw(6) << left << "NOP" << rTbFv << " else" << endl;
//push tempLabel onto operandStk;
pushOperand(tempLabel.str());
//deassign operands from all registers
areg = "";
}
void EmitPostIfCode(string operand) //emit code that follows end of if statement
{
//emit instruction to label this point of object code with the argument operand;
objectFile << setw(6) << left << operand << setw(6) << left << "NOP" << rTbFv << " end if" << endl;
//deassign operands from all registers
areg = "";
}
void EmitWhileCode() //emit code that follows while
{
ostringstream tempLabel;
tempLabel << "L" << loopCount;
//assign next label to tempLabel;
//tempLabel += (""+loopCount);
loopCount++;
//emit instruction to label this point of object code as tempLabel;
objectFile << setw(6) << left << tempLabel.str() << setw(6) << left << "NOP" << rTbFv << " while" << endl;
//push tempLabel onto operandStk;
pushOperand(tempLabel.str());
//deassign operands from all registers
areg = "";
}
void EmitDoCode(string operand) //emit code that follows do
{
ostringstream tempLabel;
tempLabel << "L" << loopCount;
loopCount++;
if(WhichType(operand) != BOOLEAN)
{
printError("Condition must be a boolean");
}
string intOp = getIntName(operand);
//emit instruction to set the condition code depending on the value of operand;
if(areg != operand)
{
objectFile << rammTab << "LDA " << setw(4) << intOp << rTbFv << endl;
}
//emit instruction to branch to tempLabel if the condition code indicates operand is zero (false)
objectFile << rammTab << "AZJ " << setw(4) <<tempLabel.str() << rTbFv << "do" << endl;
//push tempLabel onto operandStk;
pushOperand(tempLabel.str());
//if operand is a temp then
if(operand[0] == 'T')
{
//free operand's name for reuse;
FreeTemp();
}
//deassign operands from all registers
areg = "";
}
void EmitPostWhileCode(string operand1,string operand2)
//emit code at end of while loop, operand2 is the label of the beginning of the loop,
//operand1 is the label which should follow the end of the loop
{
//emit instruction which branches unconditionally to the beginning of the loop, i.e., to the value of operand2
objectFile << rammTab << "UNJ " << setw(4) << left << operand2 << right << rTbFv << "end while" << endl;
//emit instruction which labels this point of the object code with the argument operand1;
objectFile << setw(6) << left << operand1 << setw(6) << left << "NOP " << endl;
//deassign operands from all registers
areg = "";
}
void EmitRepeatCode() //emit code that follows repeat
{
ostringstream tempLabel;
tempLabel << "L" << loopCount;
loopCount++;
//emit instruction to label this point in the object code with the value of tempLabel;
objectFile << setw(6) << left << tempLabel.str() << setw(6) << left << "NOP" << rTbFv << " repeat" << endl;
//push tempLabel onto operandStk;
pushOperand(tempLabel.str());
//deassign operands from all registers
areg = "";
}
void EmitUntilCode(string operand1, string operand2)
//emit code that follows until and the predicate of loop. operand1 is the value of the
//predicate. operand2 is the label that points to the beginning of the loop
{
if(WhichType(operand1) != BOOLEAN)
{
printError("Condition must be a boolean");
}
//emit instruction to set the condition code depending on the value of operand1;
string intOp = getIntName(operand1);
if(areg != operand1)
{
objectFile << rammTab << "LDA " << intOp << rTbFv << endl;
}
//emit instruction to branch to the value of operand2 if the condition code indicates operand1 is zero (false)
objectFile << rammTab << "AZJ " << operand2 << rTbFv << " until" << endl;
//if operand1 is a temp then
if(operand1[0] == 'T')
{
//free operand1's name for reuse;
FreeTemp();
}
//deassign operands from all registers
areg = "";
}
| true |
561e336f2d0ec212d895bbba32653abefd72dd90 | C++ | Jonatankk/codigos | /Codeforces/cf122a.cpp | UTF-8 | 515 | 3.0625 | 3 | [] | no_license | /*
* Leonardo Deliyannis Constantin
* http://codeforces.com/problemset/problem/122/A
*/
#include <stdio.h>
#include <vector>
using namespace std;
int main(){
int n;
bool ans;
vector<int> lucky = {
4, 7, 44, 47, 74, 77, 444, 447, 474, 477, 744, 747, 774, 777 };
while(scanf("%d", &n) != EOF){
ans = false;
for(int l : lucky){
if(n % l == 0){
ans = true;
break;
}
}
printf("%s\n", ans ? "YES" : "NO");
}
return 0;
}
| true |
e64e5856424bedc9ea08737f0532db8083e0ecdd | C++ | huanjihgh/Object | /object/task/TaskQueue.cpp | UTF-8 | 3,090 | 2.734375 | 3 | [] | no_license |
#include <thread>
#include <mutex>
#include <functional>
#include <queue>
#include <assert.h>
#include"../../include/task/TaskQueue.h"
namespace object {
TaskQueue::TaskQueue() : m_quit(false)
, m_mutex()
, m_condition()
, m_queue()
, m_thread(new std::thread(&TaskQueue::handle, this))
{
}
TaskQueue::~TaskQueue()
{
}
size_t TaskQueue::size() {
std::lock_guard<std::mutex> lock(m_mutex);
return this->m_queue.size();
}
void TaskQueue::quit() {
std::lock_guard<std::mutex> lock(m_mutex);
m_quit = true;
m_condition.notify_all();
}
void TaskQueue::wait()
{
assert(true == m_quit && true == m_thread->joinable());
m_thread->join();
}
void TaskQueue::post(std::function<void()> task) {
post(false, task);
}
void TaskQueue::post(bool mustExecute, std::function<void()> task) {
std::lock_guard<std::mutex> lock(m_mutex);
if (false == m_quit)
{
m_queue.push({ mustExecute, task });
m_condition.notify_all();
}
}
void TaskQueue::handle() {
while (true)
{
Task task;
{
std::unique_lock<std::mutex> lock(m_mutex);
m_condition.wait(lock, [this]() {
return (m_quit || false == m_queue.empty());
});
if (false == m_queue.empty())
{
task = m_queue.front();
m_queue.pop();
}
}
if ((false == m_quit || true == task.mustExecute) && task.executor)
{
#if !defined(_DEBUG) && !defined(DEBUG)
try
{
task.executor();
}
catch (const std::exception&)
{
}
#else
task.executor();
#endif
}
{
std::unique_lock<std::mutex> lock(m_mutex);
if (true == m_quit && true == m_queue.empty())
{
break;
}
}
}
}
ThreadPool::ThreadPool(int size) : m_quit(false), rand(0)
{
for (int i = 0; i < size; i++)
{
this->m_taskqueue_list.push_back(new TaskQueue());
}
}
ThreadPool* ThreadPool::Instance(int size) {
static ThreadPool* t = nullptr;
if (!t) {
object::Lock l;
if (!t)
t = new ThreadPool(size);
}
return t;
}
ThreadPool::~ThreadPool()
{
}
void ThreadPool::quit() {
//auto b=this->m_taskqueue_list
int i = 0;
int size = this->m_taskqueue_list.size();
i = size - 1;
for (; size >= 0; size--, i--)
{
this->m_taskqueue_list[i]->quit();
this->m_taskqueue_list[i]->wait();
delete this->m_taskqueue_list[i];
}
this->m_taskqueue_list.clear();
}
void ThreadPool::post(std::function<void()> task) {
post(false, task);
}
void ThreadPool::post(bool mustExecute, std::function<void()> task, int thread) {
if (thread == -1) {
size_t size = this->m_taskqueue_list.size();
//std::vector<tmsort> x(size);
for (size_t i = 0; i < size; i++)
{
thread = this->m_taskqueue_list[i]->size();
if (thread < 1) {
this->m_taskqueue_list[i]->post(mustExecute, task);
return;
}
/* tmsort f;
f.i = i;
f.k = thread;
x.push_back(f);*/
}
rand = rand + 1;
rand = rand % size;
this->m_taskqueue_list[rand]->post(mustExecute, task);
}
else {
this->m_taskqueue_list[thread]->post(mustExecute, task);
}
}
} | true |
260a1ffb8bb7269e666f072407a797e5d43831fe | C++ | SuperNinjaFat/smudger | /smudger/smudger.cpp | UTF-8 | 6,321 | 3.09375 | 3 | [] | no_license | // smudger.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "pch.h"
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
#include <vector>
#include <sstream>
#include <stdlib.h>
#include <time.h>
using namespace std;
const string directoryMaster = "weeks/Documents/college-directory/year-4/semester-2/software-dev-methods"; //"super/Documents/GitHub";
string readFile(string filename) {
string contents = "";
ifstream file;
file.open(filename);
if (file.is_open()) {
stringstream buffer;
buffer << file.rdbuf();
file.close();
contents = buffer.str();
}
return contents;
}
vector<string> readFileToVector(string filename) {
vector<string> contents;
string word;
ifstream file;
file.open(filename);
while (file >> word) {
contents.push_back(word);
}
return contents;
}
int countInstances(string phrase, string filename) {
// Will check how many instances of the given phrase exist within the filename
string contents = readFile(filename);
if (contents != "") {
int fileLength = contents.length();
int phraseLength = phrase.length();
int instances = 0;
// Goes through entire contents
for(int i = 0; i < fileLength - phraseLength; i++){
int j;
// Now checks to see if the phrase is in contents
for (j = 0; j < phraseLength; j++) {
if (contents[i + j] != phrase[j])
break;
}
// Checks to see if the entire phrase existed
if (j == phraseLength) {
instances++;
j = 0;
}
}
return instances;
}
else {
return -1;
}
}
string newName(string filename) {
string newFilename = filename;
return newFilename.insert(filename.size() - 4, "_smudged");
}
int wordsInFile(string contents, int fileLength) {
int words = 0;
for (int i = 0; i < fileLength; i++) {
if (contents[i] == ' ')
words++;
}
return words;
}
void replaceWords(string phrase, string filename) {
//create name for new file
string newFilename = newName(filename);
ifstream file;
file.open(filename);
if (file.is_open()) {
stringstream buffer;
buffer << file.rdbuf();
file.close();
string contents = buffer.str();
int fileLength = contents.length();
//finds how many words there are in the entire file
int words = wordsInFile(contents, fileLength);
//generate a random place to inject the word
int loc = generateRandLoc(words);
ofstream outputFile;
outputFile.open(newFilename);
if (outputFile.is_open()) {
vector<string> contents = readFileToVector(filename);
for (int i = 0; i < int(contents.size()); i++) {
if (i != loc) {
if (i == contents.size())
outputFile << contents[i].c_str();
else
outputFile << contents[i].c_str() << ' ';
}
else {
outputFile << phrase << ' ';
}
}
outputFile.close();
}
}
}
void addWords(string phrase, string filename) {
//create name for new file
string newFilename = newName(filename);
ifstream file;
file.open(filename);
if (file.is_open()) {
stringstream buffer;
buffer << file.rdbuf();
file.close();
string contents = buffer.str();
int fileLength = contents.length();
//finds how many words there are in the entire file
int words = wordsInFile(contents, fileLength);
//generate a random place to inject the word
int loc = generateRandLoc(words);
ofstream outputFile;
outputFile.open(newFilename);
if (outputFile.is_open()) {
vector<string> contents = readFileToVector(filename);
for (int i = 0; i < int(contents.size()); i++) {
if (i != loc) {
if (i == contents.size())
outputFile << contents[i].c_str();
else
outputFile << contents[i].c_str() << ' ';
}
else {
outputFile << contents[i].c_str() << ' ' << phrase << ' ';
}
}
outputFile.close();
}
}
}
int generateRandLoc(int wordAmount) {
//adapted from http://www.cplusplus.com/reference/cstdlib/rand/
/* initialize random seed: */
srand(time(NULL));
return rand() % wordAmount + 1;
}
void batOutput(string batName, string source) {
ofstream batch;
batch.open(batName);
if (batch.is_open()) {
vector<string> contents = readFileToVector(source);
batch << "cd ..\n";
for (int i = 0; i < int(contents.size()); i++) {
batch << "\nsam " << contents[i].c_str();
}
}
batch.close();
}
/*
Arguments entered should be
[0] program name
[1] -d or a -h
[2] filename
[3] -r or -a
[4] the word
*/
argument argumentHandler(int argc, char* argv[]) {
argument obj;
if (argc == 5) {
if (argv[1] == "-h") {
show_usage(argv[1]);
}
else if (argv[1] == "-d") {
if (argv[3] == "-r" || argv[3] == "-a") {
obj.filename = argv[2];
obj.command = argv[3];
obj.phrase = argv[4];
return obj;
}
}
}
return obj;
}
void show_usage(string name) {
std::cerr << "Usage: " << name << " <option(s)> SOURCES"
<< "Options:\n"
<< "\t-h,--help\t\tShow this help message\n"
<< "\t-d,--destination DESTINATION\tSpecify the destination path"
<< std::endl;
}
int argumentEnough(int argc, char* argv[]) {
if (argc < 5) {
show_usage(argv[0]);
return 1;
}
else {
return 0;
}
return 2;
}
int main(int argc, char* argv[])
{
//addWords("ploopy", "C:/Users/" + directoryMaster + "/smudger/smudger/test.txt");
//batOutput("testingBat.bat", "C:/Users/" + directoryMaster + "/smudger/smudger/test.txt");
if (argumentEnough(argc, argv) == 1)
return 1;
argument obj = argumentHandler(argc, argv);
if (obj.command == "-r") {
cout << "Replacing words\n";
replaceWords(obj.phrase, obj.filename);
} else if (obj.command == "-a") {
cout << "Adding words\n";
addWords(obj.phrase, obj.filename);
}
}
// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu
// Tips for Getting Started:
// 1. Use the Solution Explorer window to add/manage files
// 2. Use the Team Explorer window to connect to source control
// 3. Use the Output window to see build output and other messages
// 4. Use the Error List window to view errors
// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
| true |
02082b29fe8234858de435c81789f5d9408675a0 | C++ | ArinPoray/C_Projects | /Ass03_C++_final/Ass03_C++_final/Pair.h | UTF-8 | 230 | 2.9375 | 3 | [] | no_license | // Pair.h
#ifndef _PAIR_H
#define _PAIR_H
class Pair
{
double x, y;
public:
Pair() :x(0), y(0){}
Pair(double x, double y) :x(x), y(y){}
Pair operator+(Pair&);
Pair operator/(double);
void Report();
};
#endif | true |
93c67ff3445c5807fa25a043775347d51ccb20d0 | C++ | jigsaw5071/algorithms | /Greedy/JobSequencing.cpp | UTF-8 | 2,137 | 3.21875 | 3 | [] | no_license | #include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
/** =================== JOB SEQUENCING PROBLEM ==================================
=> This is another very interesting problem based on greedy paradigm.
=> This problem can be done in both ways i.e. either by decreasingly sorting by Profit or decreasingly sorting
by Deadline.
=> This problem is implemented in deadline sorted way.
=> You can find the solution to Profit sorted way at : http://www.geeksforgeeks.org/job-sequencing-problem-set-1-greedy-algorithm/
=> Both the solutions take O(n * n) time
=> There is a better algorithm for this using union-find DS . You can take a look at it in Disjoint -Set directory of this
repo.
*/
struct Job{
char name;
int deadline;
int profit;
};
int main(void){
vector<Job> jobs = { {'a', 3, 25}, {'b', 3, 20}, {'c', 2, 24},{'d', 2, 28}, {'e', 1, 22}};
sort(jobs.begin() , jobs.end() , [](Job& x , Job& y){
return ((x.deadline == y.deadline)?(x.profit > y.profit):(x.deadline > y.deadline));
});
int maxDeadLine = jobs[0].deadline;
vector<Job> ans(maxDeadLine + 1);
vector<bool> isEmpty(maxDeadLine + 1 , true);
isEmpty[maxDeadLine] = false;
ans[maxDeadLine] = jobs[0];
for(int i = 1 ; i < jobs.size() ; ++i){
int deadline = jobs[i].deadline;
if(isEmpty[deadline]){
isEmpty[deadline] = false;
ans[deadline] = jobs[i];
}
else{
while(deadline > 0){
if(isEmpty[deadline]){
ans[deadline] = jobs[i];
isEmpty[deadline] = false;
break;
}
if(jobs[i].profit > ans[deadline].profit){
int j = deadline - 1;
Job jb = ans[deadline];
ans[deadline] = jobs[i];
while(j > 0 || !isEmpty[j]){
Job temp = ans[j];
ans[j] = jb;
jb = temp;
j--;
}
if(j > 0 && isEmpty[j]){
ans[j] = jb;
isEmpty[j] = false;
}
break;
}
deadline--;
}
}
}
for(int i = 1 ; i <= maxDeadLine ; ++i){
cout << ans[i].name << " ";
}
return 0;
}
| true |
fa39a61a8a5363f8ec72e89c88695d61107e05a5 | C++ | shinron4/Algorithmmi-Coding | /almostshort.cpp | UTF-8 | 1,849 | 2.625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <queue>
#define MAX 10000000
#define MP make_pair
#define PB push_back
#define F first
#define S second
#define OUT cout <<
#define IN cin >>
#define newline cout << "\n"
#define space cout << " "
#define fastIO ios_base::sync_with_stdio(false); cin.tie(NULL);
using namespace std;
vector< vector< pair<int, int> > > G(500), GI(500);
class compare{
public:
bool operator()(pair<int, int> &p, pair<int, int> &q){
return p.S < q.S;
}
};
void dijkstra(int n, int s, int d[], vector< vector < pair<int, int> > > G){
bool c[n];
priority_queue< pair<int, int>, vector< pair<int, int> >, compare > q;
for(int i = 0; i < n; i++){
d[i] = MAX;
c[i] = false;
}
d[s] = 0;
q.push(MP(s, 0));
while(!q.empty()){
int u = q.top().F;
q.pop();
if(!c[u]){
for(int j = 0; j < G[u].size(); j++){
int v = G[u][j].F, w = G[u][j].S;
if(d[v] > d[u] + w){
d[v] = d[u] + w;
q.push(MP(v, d[v]));
}
}
c[u] = true;
}
}
}
int main(){
int n, m, s, d, dist1[500], dist2[500];
fastIO
while(true){
IN n; IN m;
if(n == 0) break;
IN s; IN d;
for(int i = 0; i < m; i++){
int u, v, w;
IN u; IN v; IN w;
G[u].PB(MP(v, w));
}
dijkstra(n, s, dist1, G);
if(dist1[d] == MAX) OUT -1;
else{
int m = dist1[d];
for(int j = 0; j < n; j++)
for(int k = 0; k < G[j].size(); k++)
GI[G[j][k].F].PB(MP(j, G[j][k].S));
dijkstra(n, d, dist2, GI);
for(int j = 0; j < n; j++) GI[j].clear();
for(int j = 0; j < n; j++){
for(int k = 0; k < G[j].size(); k++){
int u = j, v = G[j][k].F, w = G[j][k].S;
if(dist1[u] + w + dist2[v] != m) GI[u].PB(MP(v, w));
}
}
dijkstra(n, s, dist1, GI);
OUT (dist1[d] < MAX ? dist1[d] : -1);
}
for(int j = 0; j < n; j++){
GI[j].clear();
G[j].clear();
}
newline;
}
return 0;
} | true |
59453081585c6d09f25acba0e2d61b12a1ebc4d9 | C++ | On-Jin/stf | /src/Engine/Graphic/Skybox.hpp | UTF-8 | 1,215 | 2.609375 | 3 | [
"Unlicense"
] | permissive | #pragma once
#include <glad/glad.h>
#include <string>
#include <list>
#include "Engine/Shader.hpp"
# define SKYBOX_NUMBER_OF_FACES 6
class Skybox {
public:
class ConstructorException : public std::invalid_argument {
public:
ConstructorException(void) noexcept;
ConstructorException(std::string) noexcept;
virtual const char* what() const noexcept;
~ConstructorException(void) noexcept;
ConstructorException(ConstructorException const &src) noexcept;
private:
ConstructorException &operator=(ConstructorException const &rhs) noexcept;
std::string _error;
};
enum eFace { RIGHT = 0, LEFT, UP, DOWN, FRONT, BACK };
Skybox(std::string const &pathSkybox,
std::string const &pathDirectorySkyBox,
std::list< std::string > const &skyboxFile);
~Skybox() noexcept;
Skybox() noexcept = delete;
Skybox(Skybox const &shader) = delete;
Skybox &operator=(Skybox const &shader) = delete;
void render(glm::mat4 const &view, glm::mat4 const &projection);
private:
Shader shader_;
unsigned int textureSkyBox_;
unsigned int skyboxVAO_;
unsigned int skyboxVBO_;
/* 6 Faces, 6 Points (3 per traingle), 3 coordinate per point */
static float skyboxVertices_[6 * 6 * 3];
}; | true |
d0b97b2cba86769880ae2e6a1d0bdbfe70913869 | C++ | pokevii/GrizzellJoshua_CSC17A_43396 | /Hmwk/Review Homework 1/Gaddis_9thEd_Chap4_Prob10_DaysInMonth/main.cpp | UTF-8 | 1,160 | 3.703125 | 4 | [] | no_license | #include <cstdlib>
#include <iostream>
using namespace std;
/*
*
*/
int main(int argc, char** argv) {
int month, year, days;
//Ask the user for a month.
cout << "Enter a month (1-12): ";
cin >> month;
cout << endl;
//Check how many days are in the month the user specified.
//Maybe a switch case would have looked cleaner..
if(month == 1 || month == 3 || month == 5 || month == 7 || month == 9 || month == 11){
days = 31;
}
else if(month == 4 || month == 6 || month == 8 || month == 10 || month == 12) {
days = 30;
}
else if(month == 2){
days = 28;
}
else{
cout << "Invalid month.\n";
return 1;
}
//Ask user for a year.
cout << "Enter a year: ";
cin >> year;
cout << endl;
//Leap year check
if(month == 2){
if(year % 100 == 0){
if(year % 400 == 0){
days++;
}
} else {
if(year % 4 == 0)
{
days++;
}
}
}
//Print amount of days.
cout << "Days: " << days << endl;
return 0;
}
| true |
f900eb708f3c5297c89beaedb63f6e379bce07c7 | C++ | jtsalisbury/EECE4040-Projects | /HW4/Classes.cpp | UTF-8 | 4,662 | 3.625 | 4 | [] | no_license | #include "Classes.h"
Node::Node(string val) {
m_value = val;
m_next = nullptr;
}
Node::~Node() { }
string Node::getValue() {
return m_value;
}
Node* Node::getNext() {
return m_next;
}
void Node::setNext(Node* next) {
m_next = next;
}
Digraph::Digraph() { }
Digraph::~Digraph() {
Node* current;
Node* next;
// Loop through each header
for (int i = 0; i < m_headers.size(); i++) {
current = m_headers[i];
// Loop through the edges connected to the header and delete them
while (current != nullptr) {
next = current->getNext();
current->setNext(nullptr);
delete current;
current = next;
}
m_headers[i] = nullptr;
}
}
void Digraph::addVertex(string val) {
// Create a new node and add it to the header list
Node* vertex = new Node(val);
m_headers.push_back(vertex);
}
bool Digraph::hasEdge(int from, int to) {
// Out of bounds
if (from > m_headers.size() - 1 || to > m_headers.size() - 1) {
return false;
}
// Using the index of the node, get the header
Node* header = m_headers[from];
// Get the value of the to node
string targetValue = m_headers[to]->getValue();
// Loop through the edges connected to the header and see if we have a match
while (header->getNext() != nullptr) {
Node* next = header->getNext();
// A match!
if (next->getValue() == targetValue) {
return true;
}
header = next;
}
return false;
}
bool Digraph::addEdge(int from, int to) {
if (from > m_headers.size() - 1 || to > m_headers.size() - 1) {
return false;
}
// Make a new node with the info
string toValue = m_headers[to]->getValue();
Node* newNode = new Node(toValue);
// Get the last node in the linked list
Node* header = m_headers[from];
while (header->getNext() != nullptr) {
header = header->getNext();
}
// Add the node
header->setNext(newNode);
return true;
}
bool Digraph::removeEdge(int from, int to) {
// Out of bounds
if (from > m_headers.size() - 1 || to > m_headers.size() - 1) {
return false;
}
// Get the header
Node* current = m_headers[from];
Node* previous = current;
// Get the target node value
string targetValue = m_headers[to]->getValue();
// No edges
if (current->getNext() == nullptr) {
return false;
}
// Loop through the edges and look for a match
while (current->getNext() != nullptr) {
Node* next = current->getNext();
previous = current;
current = next;
// Match found
if (current->getValue() == targetValue) {
break;
}
}
// Delete the node and update references
previous->setNext(current->getNext());
current->setNext(nullptr);
delete current;
return true;
}
void Digraph::sortUtil(map<string, int> *mark, map<string, bool>* inStack, Node** head, Node* v) {
// Make the node as visited, and add it to our "stack"
(*mark)[v->getValue()] = 1;
(*inStack)[v->getValue()] = true;
Node* w;
Node* edge = v;
// Loop through all connected edges
while (edge != nullptr) {
w = edge->getNext();
// If the next edge is valid, see if we've already visited it in this cycle. If we have, this indicates a cycle.
if (w != nullptr) {
if ((*inStack)[w->getValue()]) {
m_hascycles = true;
return;
}
}
// If the next edge is valid and we haven't visited it, lets visit it!
if (w != nullptr && (*mark)[w->getValue()] == 0) {
// We have to find the header node associated with the edge
for (int i = 0; i < m_headers.size(); i++) {
if (m_headers[i]->getValue() == w->getValue()) {
// Start sorting from this header node
sortUtil(mark, inStack, head, m_headers[i]);
break;
}
}
}
edge = w;
}
// Remove v from the "stack"
(*inStack)[v->getValue()] = false;
// Add v to the sorted linked list
if (*head == nullptr) {
*head = new Node(v->getValue()); // no header node previously
} else {
Node* prev = new Node(v->getValue());
prev->setNext(*head);
*head = prev;
}
}
Node* Digraph::sort() {
// Create a few maps. One to mark which nodes have been visited overall, one to mark visited in a cycle
map<string, int> mark;
map<string, bool> inStack;
// The first node which will be returned
Node* m_head = nullptr;
// Init all visited to zero
for (int i = 0; i < m_headers.size(); i++) {
mark[m_headers[i]->getValue()] = 0;
}
// Begin looping through the header nodes and sorting from each
for (int i = 0; i < m_headers.size(); i++) {
string val = m_headers[i]->getValue();
if (mark[val] == 0) {
inStack.clear(); // make sure we clear the stack
sortUtil(&mark, &inStack, &m_head, m_headers[i]);
}
}
return m_head;
}
bool Digraph::hasCycles() {
// This will be set AFTER a sort has been ran
return m_hascycles;
} | true |
b2237c0980dd20ca118cda7acfca30cc4e722606 | C++ | moodgalal/problem-solving-with-c- | /Team/main.cpp | UTF-8 | 460 | 2.78125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int n , counter=0, p,v,t;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>p>>v>>t;
if(p==1&&v==1&&t==1)
counter++;
else if(p==1&&v==1)
counter++;
else if(v==1&&t==1)
counter++;
else if (p==1&&t==1)
counter++;
else
continue;
}
cout<<counter<<endl;
return 0;
}
| true |
7e958625538babc5bc59145b9dd360576f3c8761 | C++ | staplets/419_Project | /Project/BedroomHeader.h | UTF-8 | 3,199 | 2.890625 | 3 | [] | no_license | /***********************************************************
* Author: Shaun Stapleton
* Date Created: 5/04/16
* Last Modification Date: 5/05/16
* Filename: BedroomHeader.h
*
* Overview:
* This file is the header file for Bedroom objects and iteraction of objects.
*
******************************/
//define header
#ifndef BedroomHeader_h
#define BedroomHeader_h
#include "stdafx.h"
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
#include <stack>
#include <unordered_map>
//Bed Object
class Bed
{
private:
protected://protected member variables.
std::string description;
std::string pen;
public:
//default constructor
Bed()
{
this->description = "An elegant King bed with a golden European style bed frame.";
this->pen = "pen inscribed with the word \'Beaujolais\'";
}
//Virtual Destructor
virtual ~Bed()
{}
//member function to check dining table
void checkBed(std::unordered_map<std::string, std::string>& inv);
//Accessor Functions for accessing private variables.
std::string getDescription() const;
std::string getPen() const;
//Mutator Functions to change private variables.
void setDescription(const std::string theDescription);
void setPen(const std::string thePen);
};
//Body
class Body
{
private:
protected://protected member variables.
std::string grape;
std::string pulse;
std::string description;
std::string descriptionTwo;
std::string descriptionThree;
public:
//default constructor
Body()
{
this->grape = "Gamay Grape";
this->pulse = "\n\nSherlock checks the vitals and finds no pulse.\n\n";
this->description = "\n\nThere are no signs of strangulation or suicide.\n\nMr. Cunningham has dried blood around his nose and mouth. He is a caucasian male in his mid twenties.\n\n";
this->descriptionTwo = "He is dressed in a tan sports jacket and brown pants.\n\nIt appears as though he had come into the room and passed away shortly after. He is still wearing his shoes.\n\n";
this->descriptionThree = "Sherlock deducts that he has been poisoned, but how and why...\n\n";
}
//Virtual Destructor
virtual ~Body()
{}
//member function to get into the trunk
void checkBody(std::unordered_map<std::string, std::string>& inv);
//Accessor Functions for accessing private variables.
std::string getGrape() const;
std::string getPulse() const;
std::string getDescription() const;
std::string getDescriptionTwo() const;
std::string getDescriptionThree() const;
//Mutator Functions to change private variables.
void setGrape(const std::string theGrape);
void setPulse(const std::string thePulse);
void setDescription(const std::string theDescription);
void setDescriptionTwo(const std::string theDescriptionTwo);
void setDescriptionThree(const std::string theDescriptionThree);
};
//navigation function to handle game play while the player is in the bedroom room
int bedroomNavigate(std::unordered_map<std::string, std::string>& inventory);
#endif | true |
d36e7bc44dba5c327f86a0db6ce598f0c735f514 | C++ | Ahmedv3/Algorytmy_I_Struktury_Danych | /lista2/zad2.cpp | UTF-8 | 1,425 | 3.5625 | 4 | [] | no_license | #include <iostream>
using namespace std;
int tab[1000000];
int licznik1, licznik2, licznik3 =0;
int max(const int t[], int n){
int x = t[n];
while(n--){
licznik1++;
if(x < t[n]){
x = t[n];
}
}
// cout << "Ilosc porownan: " << licznik1 << endl;
return x;
}
int max2(const int t[], int n){
if(n == 1){
// cout << "Ilosc porownan: " << licznik2 << endl;
return t[0];
}
int max = max2(t,n-1);
licznik2++;
if(max > t[n-1]){
// cout << "Ilosc porownan: " << licznik2 << endl;
return max;
}
else {
// cout << "Ilosc porownan: " << licznik2 << endl;
return t[n-1];
}
}
int max3(const int t[], int pierwszy, int ostatni){
if(pierwszy == ostatni){
// cout << "Ilosc porownan: " << licznik3 << endl;
return t[ostatni];
}
int polowa = (pierwszy * ostatni) /2;
int max1 = max3(t, pierwszy, polowa);
int max2 = max3(t, polowa+1, ostatni);
licznik3++;
if(max1 > max2){
// cout << "Ilosc porownan: " << licznik3 << endl;
return max1;
}
else{
// cout << "Ilosc porownan: " << licznik3 << endl;
return max2;
}
}
int main(int argc, char const *argv[]) {
int n;
cout << "podaj ilosc elementow"<< endl;
cin>>n;
for(int i=0;i<n;i++){
cout << "wprowadz " << i+1 << " element: "<< endl;
cin>>tab[i];
}
cout << max(tab, n) << endl;
cout << max2(tab, n) << endl;
cout << max3(tab, tab[0], tab[n-1]) << endl;
}
| true |
0cc9bd11accede6070f6710a981f33efe8b8f3c3 | C++ | sreeves/vs-test | /Bread.h | UTF-8 | 578 | 2.96875 | 3 | [] | no_license | /*
Alexis Reeves, Section 10, lexinreeves@gmail.com
Description: Declaration of class Bread. Contains protected variables breadType and BREADPRICE.
Done without pair programming and in Visual Studio.
Late Days: none
*/
#ifndef Bread_header
#define Bread_header
#include <iostream>
#include <string>
#include <sstream>
#include "BakedGood.h"
using namespace std;
class Bread : public BakedGood {
public:
Bread(string breadType = "not specified");
string ToString() const;
double DiscountedPrice(int numGoods);
protected:
string breadType;
const double BREADPRICE = 4.50;
};
#endif | true |
6f1492c25437e96afbfe8b5a9b7462bc863bcef8 | C++ | recurze/Competitive-Programming | /ds/dsu.cpp | UTF-8 | 634 | 2.96875 | 3 | [] | no_license | class DSU {
public:
DSU(int _n): n(_n), parent(std::vector<int>(n)), size(std::vector<int>(n, 1)) {
std::iota(parent.begin(), parent.end(), 0);
}
void union_set(int a, int b) {
a = find_set(a);
b = find_set(b);
if (a != b) {
if (size[a] < size[b]) {
std::swap(a, b);
}
parent[b] = a; size[a] += size[b];
}
}
int find_set(int v) {
assert(0 <= v and v < n);
return v == parent[v] ? v : (parent[v] = find_set(parent[v]));
}
private:
int n;
std::vector<int> parent;
std::vector<int> size;
};
| true |
0481e9d8bda53b9e14eb97f84d223544f60bb8bb | C++ | skullbox305/Water-PH-Adjuster | /phSensor.h | UTF-8 | 1,577 | 2.609375 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <string>
#include <vector>
#include <mutex>
class phSensor
{
public:
phSensor(int position);
~phSensor();
float getNewPHReading();
float getPHReading();
int getBusAddress();
int getSlotPosition();
float getTempCompensation();
bool setTempCompensation(float newTemp);
int getCalibrationStatus();
bool clearCalibration();
bool lowpointCalibration(float phVal);
bool midpointCalibration(float phVal);
bool highpointCalibration(float phVal);
bool startSleepmode();
std::string getDeviceInfo();
bool getSlope(float &acidCalibration, float &baseCalibration); //fehlerhaft. manchal z.B.90% aber auch 100% m�glich
bool setNewBusAddress(int newAddr);
bool checkDeviceModell();
bool isDisconnected();
bool isOperating();
void setOperatingStatus(bool running);
private:
bool calibration(std::string cmd, float phVal);
float phValue;
int deviceID;
int busAddress;
int slotPosition;
bool running;
bool disconnected;
std::mutex phMtx;
};
extern std::vector<phSensor*> phSensors;
////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary>Initialises the ph module.</summary>
///
/// <param name="addr"> The i2c address</param>
/// <param name="slotPosition">The slot position in the water sensor array (1-16)</param>
////////////////////////////////////////////////////////////////////////////////////////////////////
static int initPhModule(int slotPosition)
{
phSensors.push_back(new phSensor(slotPosition));
return (phSensors.size() - 1);
}
| true |
2d597450e5016542fc74e1c340eca9eaab094c81 | C++ | y-shindoh/binary_heap | /binary_heap.hpp | UTF-8 | 4,948 | 3.59375 | 4 | [] | no_license | /* -*- coding: utf-8; tab-width: 4 -*- */
/**
* @file binary_heap.hpp
* @brief binary heapのテンプレート
* @author Yasutaka SHINDOH / 新堂 安孝
* @note アルゴリズムイントロダクション第1巻を参考に実装した。
*/
#ifndef __BINARY_HEAP_HPP__
#define __BINARY_HEAP_HPP__ "binary_heap.hpp"
#include <cstddef>
#include <cassert>
#include <vector>
#include <utility>
namespace ys
{
/**
* @class binary heapのテンプレート・クラス
*/
template<typename TYPE>
class BinaryHeap
{
private:
std::vector<TYPE> data_; ///< ヒープ本体
/**
* ヒープ条件の比較用関数
* @note 第1引数を親にしたい場合は0以下の整数を返却する。
* @note 第2引数を親にしたい場合は1以上の整数を返却する。
*/
int (* compare_)(const TYPE&, const TYPE&);
/**
* 指定位置の要素から親に向かってヒープ条件を成立させる
* @param[in] i ヒープのインデックス
* @note 不正な引数 @a i を用いた際の動作は不定。
* @note 最悪計算量はΘ(log n)。
*/
void
heapify_up(size_t i)
{
size_t j;
while (0 < i) {
j = (i - 1) / 2;
if (0 >= compare_(data_[j], data_[i])) break;
std::swap<TYPE>(data_[j], data_[i]);
i = j;
}
}
/**
* 指定位置の要素から子に向かってヒープ条件を成立させる
* @param[in] i ヒープのインデックス
* @note 不正な引数 @a i を用いた際の動作は不定。
* @note 最悪計算量はΘ(log n)。
*/
void
heapify_down(size_t i)
{
size_t j, k;
const size_t l = data_.size();
while (i < l) {
j = i * 2 + 1;
if (l <= j) break;
k = j + 1;
if (k < l && 0 < compare_(data_[j], data_[k])) j = k;
if (0 >= compare_(data_[i], data_[j])) break;
std::swap<TYPE>(data_[j], data_[i]);
i = j;
}
}
public:
/**
* コンストラクタ
*/
BinaryHeap()
: compare_(0)
{
;
}
/**
* ヒープの準備
* @param[in] data ヒープに入力するデータ列
* @param[in] length 引数 @a data の長さ
* @param[in] compare ヒープ条件の比較用関数
* @note 最悪計算量はΘ(n log n)。
*/
void
prepare(const TYPE* data,
size_t length,
int (* compare)(const TYPE&, const TYPE&))
{
assert(data);
assert(length);
assert(compare);
compare_ = compare;
data_.reserve(length);
for (size_t i(0); i < length; ++i) {
data_.push_back(data[i]);
heapify_up(i);
}
}
/**
* ヒープが空かどうかを確認
* @return true: ヒープは空, false: ヒープは空でない
* @note 最悪計算量はΘ(1)。
*/
bool
empty() const
{
return data_.empty();
}
/**
* ヒープ内の要素数を取得
* @return ヒープ内の要素数
* @note 最悪計算量はΘ(1)。
*/
size_t
size() const
{
return data_.size();
}
/**
* ヒープにデータを追加
* @param[in] data 追加するデータ
* @note 最悪計算量はΘ(log n)。
ただし、 @a data_ のメモリ領域が伸びた場合はΘ(n)。
*/
void
push(const TYPE& data)
{
const size_t l = data_.size();
data_.push_back(data);
heapify_up(l);
}
/**
* ヒープのルートを取得しヒープから削除
* @return ヒープのルートのデータ
* @note 1つ以上の要素を含む時に使用すること。
* @note 最悪計算量はΘ(log n)。
*/
TYPE
pop()
{
assert(!data_.empty());
TYPE value = data_[0];
TYPE tmp = data_.back();
data_.pop_back();
if (!data_.empty()) {
data_[0] = tmp;
heapify_down(0);
}
return value;
}
/**
* ヒープ内のデータを書き換え
* @param[in] i ヒープのインデックス
* @param[in] data 書き換える値
* @note 不正な引数 @a i を用いた際の動作は不定。
* @note 最悪計算量はΘ(log n)。
*/
void
update(size_t i,
const TYPE& data)
{
assert(compare_);
assert(i < data_.size());
data_[i] = data;
if (0 < i) {
size_t j = (i - 1) / 2;
if (0 < compare_(data_[j], data)) {
heapify_up(i);
return;
}
}
heapify_down(i);
}
/**
* ヒープの先頭データを直接取得
* @return ヒープの先頭データ
* @note 最悪計算量はΘ(1)。
*/
TYPE
top() const
{
assert(!data_.empty());
return data_.front();
}
/**
* ヒープ内のデータを直接取得
* @param[in] i ヒープのインデックス
* @return ヒープ内の指定した位置のデータ
* @note 不正な引数 @a i を用いた際の動作は不定。
* @note 最悪計算量はΘ(1)。
*/
TYPE
get(size_t i) const
{
assert(i < data_.size());
return data_[i];
}
};
};
#endif // __BINARY_HEAP_HPP__
| true |
45d057030c7a31ee22bc97f8d47451e3a3b34f46 | C++ | ywtseng/NTUPlacement | /src/database/cell_pin_port.hpp | UTF-8 | 532 | 2.796875 | 3 | [] | no_license | #ifndef CELL_PIN_PORT_HPP
#define CELL_PIN_PORT_HPP
#include "../util/type.hpp"
#include "rect.hpp"
class CellPinPort {
public:
CellPinPort();
CellPinPort(CellPinId cell_pin_id, LayerId layer_id, const Rect& rect);
void Print(std::ostream& os = std::cout, int indent_level = 0) const;
// Getters
CellPinId cell_pin_id() const;
LayerId layer_id() const;
const Rect& rect() const;
// Setters
void set_rect(const Rect& rect);
private:
CellPinId cell_pin_id_;
LayerId layer_id_;
Rect rect_;
};
#endif
| true |
cf9fe8d1a5daf694e0706ceae2176b18b77faf1f | C++ | rauf/ctci | /Ch 3 Stacks and Queues/Q3-2.cpp | UTF-8 | 1,465 | 3.8125 | 4 | [] | no_license | #include<iostream>
#include<cstring>
#include<stdio.h>
#define BIG_NUM 1000000
class Node {
public:
int data;
Node *link;
Node(int _data){
data = _data;
link = NULL;
}
};
class Stack{
int *arr;
int top;
int size;
Node *minList;
void addMin(int n) {
if(minList == NULL){
minList = new Node(n);
return;
}
Node *newNode = new Node(n);
newNode->link = minList;
minList = newNode;
}
void removeMin() {
Node *toDelete = minList;
minList = minList->link;
delete toDelete;
}
public:
Stack(int _size) {
size = _size;
arr = new int[size];
top = -1;
}
void push(int n) {
if(top > size) return;
if(minList == NULL || n < min()){
addMin(n);
}
arr[++top] = n;
}
int pop() {
if(top <= -1) return -1;
int n = arr[top];
top--;
if(min() == n) {
removeMin();
}
return n;
}
int min(){
return minList == NULL ? BIG_NUM : minList->data;
}
void print() {
std::cout << "\nArray: ";
for (int i = 0; i <= top; ++i)
std::cout << arr[i] << " ";
std::cout << std::endl;
}
};
int main() {
Stack *s = new Stack(10);
s->push(5);
s->push(12);
s->push(4);
s->push(6);
s->push(2);
s->push(65);
s->print();
std::cout << "Min : " << s->min();
s->pop();
s->pop(); //removing 2
s->print();
std::cout << "\nMin : " << s->min() << std::endl;
s->pop();
s->pop();
s->pop();
s->pop(); //removing all
s->print();
std::cout << "\nMin : " << s->min() << std::endl;
} | true |
db2c588e2ac5a12a303f86a47949bc1850518b39 | C++ | ca1773130n/ZMorpher | /src/ZEdge.cpp | UTF-8 | 8,094 | 2.703125 | 3 | [
"MIT"
] | permissive | #include "stdafx.h"
#include "ZVert.h"
#include "ZEdge.h"
#include "ZFace.h"
#include "ZMesh.h"
#include "D3DEx.h"
ZEdge::ZEdge( VOID )
{
marked = FALSE;
v1 = v2 = NULL;
twin = next = NULL;
index = 0;
normal.SetValAll( D3DXVECTOR3(0,0,0) );
texcoord.SetValAll( D3DXVECTOR2(0,0) );
}
ZEdge::ZEdge( ZVert* pV1, ZVert* pV2, ZFace* pF, D3DXVECTOR3 no, D3DXVECTOR2 co, ZType typecode )
{
new (this) ZEdge();
v1 = pV1;
v2 = pV2;
type = typecode;
normal.SetValAll( no );
texcoord.SetValAll( co );
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* \brief 현재 값을 보간에 사용할 min 값으로 지정
min 값은 모핑의 시작 지점의 속성을 갖는 값이다. 현재 속성으로 이 min 값을 지정하는 함수이다.
* \param VOID 없음
* \return 없음
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
VOID
ZEdge::SetMin( VOID )
{
normal.min = normal;
texcoord.min = texcoord;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* \brief 주어진 두 엣지 사이에 이 엣지가 존재하는지 여부를 반환
이 엣지와 주어진 두 엣지, 이렇게 세 엣지는 모두 시작점 v1이 같은 엣지들이다.
이때 e1, e2가 어떤 각을 이루며 V자 형태 또는 부채꼴 형태를 가질텐데, 이 엣지가 그 사이에 있는지 여부를 판단한다.
여기서는 e1과 e2가 이루는 사이각보다 이 엣지와 e1, e2 각각이 이루는 각도가 모두 작은 경우 그에 해당한다고 판단한다.
* \param e1 기준 엣지 1번 포인터
* \param e2 기준 엣지 2번 포인터
* \return TRUE면 사이에 있음, FALSE면 반대
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
BOOL
ZEdge::IsBetween( ZEdge* e1, ZEdge* e2 )
{
FLOAT angle = e1->GetAngleBetween( e2 );
return ( GetAngleBetween(e1) <= angle && GetAngleBetween(e2) <= angle );
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* \brief 이 엣지와 주어진 엣지가 서로 이루는 라디안 각을 구해 돌려준다.
이 경우도 역시 두 엣지는 v1을 공유하고 있어야 한다. V자를 이루는 두 엣지가 이루는 각도를 구해 반환한다.
* \param pE 상대 엣지 포인터
* \return 라디안 값 사이각
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
FLOAT
ZEdge::GetAngleBetween( ZEdge* pE )
{
return GetAngleBetweenVectors( D3DXVECTOR3(v2->pos - v1->pos), D3DXVECTOR3( pE->v2->pos - pE->v1->pos) );
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* \brief vertex pV를 v1으로 공유하고 이 엣지와 주어진 pEdge 사이에 있는 엣지들 중에서, 이 엣지와 반시계방향으로 가장 작은 각을 이루는 엣지를 찾아 반환한다
* \param pEdge 이 엣지와 함께 기준이 되는 엣지 포인터
* \param pV 공유하는 v1 vertex 포인터
* \return 찾은 엣지 포인터. 없으면 NULL 반환
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
ZEdge*
ZEdge::FindClosestCCWEdge( ZEdge* pEdge, ZVert* pV )
{
FLOAT angle, minangle = 1000000;
ZEdge* pMinEdge = 0;
// pV로부터 뻗어나가는 엣지들 중에서 이 엣지와 사이각이 가장 작고 이 엣지와 pEdge 사이에 놓인 것을 찾는다
ZEdge** pE = pV->edges.GetData();
for( DWORD i=0; i < pV->edges.GetSize(); i++ )
{
if( pE[i]->IsBetween(pEdge, this) == TRUE )
{
angle = GetAngleBetween( pE[i] );
if( angle < minangle )
{
minangle = angle;
pMinEdge = pE[i];
}
}
}
return pMinEdge;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* \brief 교차 판정 함수.
이 엣지와 주어진 엣지 e2가 서로 구면상에서 교차하는지 판단하고, 교차할 경우 교점을 구해 ppNewVert에 돌려준다
* \param e2 검사할 상대 엣지 포인터
* \param ppNewVert 교점 vertex 포인터. 주어진 값이 NULL이면 교차여부만 반환하고, NULL이 아니면 교차할 경우 교점이 여기 저장된다
* \return 교차 여부를 반환. TRUE면 교차, FALSE면 교차하지 않음
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
BOOL
ZEdge::CheckIntersect( ZEdge* e2, ZVert** ppNewVert )
{
ZEdge* e1 = this;
// 교차 판정할 필요가 없는 조건들. 서로 v1 또는 v2를 공유하거나 twin관계인 등은 어차피 교차하지 않으므로 제외한다.(서로 한쪽 끝이 맞닿아 있는 경우는 교차하지 않는 것으로 한다)
if( e1->v1->pos == e2->v1->pos || e1->v2->pos == e2->v1->pos || e1->v1->pos == e2->v2->pos || e1->v2->pos == e2->v2->pos ) return FALSE;
if( e1->v1 == e2->v1 ||
e1->v2 == e2->v1 ||
e1->v1 == e2->v2 ||
e1->v2 == e2->v2 ||
e1->v1->correspond == e2->v1 ||
e1->v2->correspond == e2->v1 ||
e1->v1->correspond == e2->v2 ||
e1->v2->correspond == e2->v2
) return FALSE;
D3DXVECTOR3 v0(0,0,0), v[4], vGamma;
FLOAT s[4];
D3DXPLANE plane;
v[0] = e1->v1->pos;
v[1] = e1->v2->pos;
v[2] = e2->v1->pos;
v[3] = e2->v2->pos;
//////////////////////////////////////////////////////////////////////////
// 교차 판정 알고리즘
//
// 엣지 e1의 v1, v2와 원점 O가 이루는 삼각형이 속한 평면을 구하고,
// 엣지 e2를 해당 평면에 투과시켜 교점 vGamma를 구한다.
// 그리고 s값을 구하여 모두 1보다 작은 경우 교차한다고 판단한다.
// Alexa 논문에 해당 알고리즘이 나와 있으므로 참고할것.
//////////////////////////////////////////////////////////////////////////
for( int i=0; i < 4; i += 2 )
{
D3DXPlaneFromPoints( &plane, &v0, &v[i], &v[i+1] );
if( D3DXPlaneIntersectLine( &vGamma, &plane, &v[(i+2)%4], &v[(i+3)%4] ) == NULL ) return FALSE;
s[(i+2)%4] = D3DXVec3Length( &(vGamma - v[(i+2)%4]) ) / D3DXVec3Length( &(v[(i+3)%4] - v[(i+2)%4]) );
s[(i+3)%4] = D3DXVec3Length( &(vGamma - v[(i+3)%4]) ) / D3DXVec3Length( &(v[(i+2)%4] - v[(i+3)%4]) );
}
if( s[0] < 1 && s[1] < 1 && s[2] < 1 && s[3] < 1 )
{
// 교점을 저장
if( ppNewVert != NULL )
{
D3DXVec3Normalize( &vGamma, &vGamma );
ZVert* newVert = new ZVert( ZTYPE_CUT, vGamma );
// 여기서 포지션 min, max 및 barycentric UV를 정함. 이 값들을 토대로 보간에 사용함
newVert->pos.org = e2->v1->pos.org + s[2] * ( e2->v2->pos.org - e2->v1->pos.org );
newVert->pos.max = e1->v1->pos.org + s[0] * ( e1->v2->pos.org - e1->v1->pos.org );
newVert->barycentricUV.x = s[0];
newVert->barycentricUV.y = s[2];
// 이 교점을 생성하게 된 두 엣지의 포인터와, 그 두 엣지의 네 vertex를 저장해 둔다.
// 나중에 normal 및 텍스쳐 좌표 보간을 위해 쓰일 것임
newVert->interedges[0] = e2;
newVert->interedges[1] = e1;
newVert->interverts[0] = e1->v1->correspond ? e1->v1->correspond : e1->v1;
newVert->interverts[1] = e1->v2->correspond ? e1->v2->correspond : e1->v2;
newVert->interverts[2] = e2->v1;
newVert->interverts[3] = e2->v2;
*ppNewVert = newVert;
}
return TRUE;
}
return FALSE;
}
| true |
98b1918bdec96bcef98db308e44ba4cefe3411fd | C++ | shitalbk/C-programs | /dsa/src/fiborecursive.cpp | UTF-8 | 525 | 3.75 | 4 | [] | no_license | //lab work 7 (b)- II
//fibonacci sequence by recursive function
#include<stdio.h>
#include<stdlib.h>
int Fibonacci(int);
main()
{
int n, c;
printf("Enter the number of terms\n");
scanf("%d",&n);
printf("Fibonacci series\n");
for ( c = 0 ; c < n ; c++ )
{
printf("%d\t", Fibonacci(c));
}
system("pause");
return 0;
}
int Fibonacci(int n)
{
if ( n == 0 || n==1)
return n;
else
return ( Fibonacci(n-1) + Fibonacci(n-2) );
}
| true |
b3f90d2404a318ebd759c84dc6ab4bed49ba05bd | C++ | Badhansen/UVa-Online-Judge | /11332 - Summing Digits/11332 - Summing Digits.cpp | UTF-8 | 513 | 2.96875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
long long int digit_sum (long long int number)
{
long long int sum=0;
while (number){
sum=sum+number%10;
number/=10;
}
return sum;
}
int main ()
{
long long int T, number;
while (1){
cin >> number;
if (number==0)
break;
long long int sum=0;
sum=digit_sum(number);
while (sum>9){
sum=digit_sum(sum);
}
cout << sum << endl;
}
return 0;
}
| true |
b1fecfcb2949c0dac47d7b8468e5f7b8c8917ad7 | C++ | liuluke0325/OOP345workshop | /WS04/at_home/MessagePack.h | UTF-8 | 916 | 2.84375 | 3 | [] | no_license |
/*
Name:HsuehChihLiu
id: 116131186
Date: 6/12/19
*/
#ifndef SICT_MESSAGEPACK_H
#define SICT_MESSAGEPACK_H
#include "Message.h"
#include <iostream>
namespace sict {
//manages a composition of Message objects
class MessagePack {
// The number of objects is defined at run - time by the client module.
Message* message;
size_t numOfMsg;
// Copy and Move
public:
// A default constructor that places the object in a safe empty state
MessagePack();
MessagePack(Message** message, size_t numOfMessage);
// Copy
MessagePack(const MessagePack& src);
MessagePack& operator= (const MessagePack& src);
// Move
MessagePack(MessagePack&& src);
MessagePack& operator= (MessagePack&& src);
void display(std::ostream& os) const;
size_t size() const;
~MessagePack();
};
std::ostream& operator<< (std::ostream& os, const MessagePack& messagePack);
}
#endif // !SICT_MESSAGEPACK_H
| true |
1412672b3974a1c5b8a2ae89e7b2bb088479326c | C++ | ayulockin/dataStructureInC | /sorting/merge_sort_final.cpp | UTF-8 | 773 | 3.25 | 3 | [] | no_license | #include<stdio.h>
void merge_sort(int [], int, int);
void merge(int [], int, int, int);
int main(){
int a[20] = {44,55,33,99,88,77,22,11,110,66};
int n = 10;
merge_sort(a, 0, n-1);
for(int i=0; i<n; i++){
printf("%d\t", a[i]);
}
}
void merge_sort(int a[], int l, int r){
int q;
if(l<r){
q = (l+r)/2;
merge_sort(a, l, q);
merge_sort(a, q+1, r);
merge(a, l, q, r);
}
}
void merge(int a[], int l, int q, int r){
int b[20];
int l1 = l;
int r1 = q+1;
int i = l;
while((l1<=q) && (r1<=r)){
if(a[l1]<a[r1]){
b[i] = a[l1];
l1++;
i++;
}
else{
b[i] = a[r1];
r1++;
i++;
}
}
while(l1<=q){
b[i] = a[l1];
l1++;
i++;
}
while(r1<=r){
b[i] = a[r1];
r1++;
i++;
}
for(i=l; i<=r; i++){
a[i] = b[i];
}
}
| true |
9a39d9bf32795ec664b5557000e4cef5f27c52d6 | C++ | leader1118/KHJ-Project | /3D/3D_LIB/3Dlib_Sample/xMap.cpp | UHC | 8,945 | 3 | 3 | [] | no_license | #include "xMap.h"
float xMap::Lerp(float fStart, float fEnd, float fTangent)
{
return fStart - (fStart*fTangent) + (fEnd*fTangent);
}
float xMap::GetHeightmap(int row, int col)
{
return m_VertexList[row * m_iNumRows + col].p.y;// *m_xMapDesc.fScaleHeight;
}
float xMap::GetHeight(float fPosX, float fPosZ)
{
// fPosX/fPosZ ġ شϴ ̸ʼ ã´.
// m_iNumColsm_iNumRows / ũⰪ.
float fCellX = (float)(m_iNumCellCols*m_fCellDistance / 2.0f + fPosX);
float fCellZ = (float)(m_iNumCellRows*m_fCellDistance / 2.0f - fPosZ);
// ũ 0~1 ٲپ ̸ 迭 Ѵ.
fCellX /= (float)m_fCellDistance;
fCellZ /= (float)m_fCellDistance;
// fCellX, fCellZ ۰ų ִ ( Ҽκ ߶.)
float fVertexCol = ::floorf(fCellX);
float fVertexRow = ::floorf(fCellZ);
// ̸ ʱȭ Ѵ.
if (fVertexCol < 0.0f) fVertexCol = 0.0f;
if (fVertexRow < 0.0f) fVertexRow = 0.0f;
if ((float)(m_iNumCols - 2) < fVertexCol) fVertexCol = (float)(m_iNumCols - 2);
if ((float)(m_iNumRows - 2) < fVertexRow) fVertexRow = (float)(m_iNumRows - 2);
// ÷ ϴ 4 ̰ ã´.
// A B
// *---*
// | / |
// *---*
// C D
float A = GetHeightmap((int)fVertexRow, (int)fVertexCol);
float B = GetHeightmap((int)fVertexRow, (int)fVertexCol + 1);
float C = GetHeightmap((int)fVertexRow + 1, (int)fVertexCol);
float D = GetHeightmap((int)fVertexRow + 1, (int)fVertexCol + 1);
// A ġ () Ѵ. 0 ~ 1.0f
float fDeltaX = fCellX - fVertexCol;
float fDeltaZ = fCellZ - fVertexRow;
// ۾ ս ã´.
float fHeight = 0.0f;
// ̽ Ѵ.
// fDeltaZ + fDeltaX < 1.0f
if (fDeltaZ < (1.0f - fDeltaX)) //ABC
{
float uy = B - A; // A->B
float vy = C - A; // A->C
// ̰ ̸ Ͽ ŸX ã´.
fHeight = A + Lerp(0.0f, uy, fDeltaX) + Lerp(0.0f, vy, fDeltaZ);
}
// Ʒ̽ Ѵ.
else // DCB
{
float uy = C - D; // D->C
float vy = B - D; // D->B
// ̰ ̸ Ͽ ŸZ ã´.
fHeight = D + Lerp(0.0f, uy, 1.0f - fDeltaX) + Lerp(0.0f, vy, 1.0f - fDeltaZ);
}
return fHeight;
}
bool xMap::CreateHeightMap(ID3D11Device* pDevice,
ID3D11DeviceContext* pContext,
T_STR szName)
{
HRESULT hr;
D3DX11_IMAGE_INFO imageinfo;
ID3D11Resource* pLoadTexture = nullptr;
D3DX11_IMAGE_LOAD_INFO info;
ZeroMemory(&info, sizeof(info));
info.MipLevels = 1;
info.Usage = D3D11_USAGE_STAGING;
info.CpuAccessFlags = D3D11_CPU_ACCESS_WRITE | D3D11_CPU_ACCESS_READ;
info.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
info.pSrcInfo = &imageinfo;
if (FAILED(hr = D3DX11CreateTextureFromFile(pDevice,
szName.c_str(), &info, NULL, &pLoadTexture, NULL)))
{
return false;
}
ID3D11Texture2D* pTex2D = nullptr;
if( FAILED(pLoadTexture->QueryInterface(
__uuidof(ID3D11Texture2D),
(LPVOID*)&pTex2D)))
{
return false;
}
SAFE_RELEASE(pLoadTexture);
D3D11_TEXTURE2D_DESC desc;
pTex2D->GetDesc(&desc);
m_fHeightList.resize(desc.Height*desc.Width);
D3D11_MAPPED_SUBRESOURCE map;
UINT index = D3D11CalcSubresource(0, 0, 1);
if (SUCCEEDED(pContext->Map(pTex2D,
index, D3D11_MAP_READ, 0, &map)))
{
UCHAR* pTexels = (UCHAR*)map.pData;
for (UINT iRow = 0; iRow < desc.Height; iRow++)
{
UINT rowStart = iRow * map.RowPitch;
for (UINT iCol= 0; iCol < desc.Width; iCol++)
{
UINT colStart = iCol * 4;
UCHAR uRed = pTexels[rowStart + colStart +0];
m_fHeightList[iRow*desc.Width+ iCol] = uRed;
}
}
pContext->Unmap(pTex2D, index);
}
m_iNumRows = desc.Height;
m_iNumCols = desc.Width;
SAFE_RELEASE(pTex2D);
return true;
}
HRESULT xMap::CreateVertexData()
{
m_iNumVertex = m_iNumVertices;
m_VertexList.resize(m_iNumVertices);
float fHalfCols = (m_iNumCols-1) / 2.0f;
float fHalfRows = (m_iNumRows - 1) / 2.0f;
float fOffsetU = 1.0f / (m_iNumCols - 1);
float fOffsetV = 1.0f / (m_iNumRows - 1);
for (int iRow = 0; iRow < m_iNumRows; iRow++)
{
for (int iCol = 0; iCol < m_iNumCols; iCol++)
{
int iIndex = iRow * m_iNumCols + iCol;
m_VertexList[iIndex].p.x = (iCol-fHalfCols)*m_fCellDistance;
m_VertexList[iIndex].p.y = GetHeightOfVertex(iIndex);
m_VertexList[iIndex].p.z = -((iRow - fHalfRows)*m_fCellDistance);
m_VertexList[iIndex].n = GetNormalOfVertex(iIndex);
m_VertexList[iIndex].c = GetColorOfVertex(iIndex);
m_VertexList[iIndex].t = GetTextureOfVertex(fOffsetU*iCol, fOffsetV*iRow);
}
}
return S_OK;
}
HRESULT xMap::CreateIndexData()
{
m_iNumIndex = m_iNumFace * 3;
m_IndexList.resize(m_iNumIndex);
int iIndex = 0;
for (int iRow = 0; iRow < m_iNumCellRows; iRow++)
{
for (int iCol = 0; iCol < m_iNumCellCols; iCol++)
{
// 0 1 2
// 3 4 5
int iNextRow = iRow + 1;
m_IndexList[iIndex + 0] = iRow * m_iNumCols + iCol;
m_IndexList[iIndex + 1] = m_IndexList[iIndex + 0]+1;
m_IndexList[iIndex + 2] = iNextRow * m_iNumCols + iCol;
m_IndexList[iIndex + 3] = m_IndexList[iIndex + 2];
m_IndexList[iIndex + 4] = m_IndexList[iIndex + 1];
m_IndexList[iIndex + 5] = m_IndexList[iIndex + 2]+1;
iIndex += 6;
}
}
GenVertexNormal();
return S_OK;
}
bool xMap::GenVertexNormal()
{
InitFaceNormals();
GenNormalLookupTable();
CalcPerVertexNormalsFastLookup();
return true;
}
void xMap::InitFaceNormals()
{
m_FaceNormalList.resize(m_iNumFace);
}
void xMap::CalcFaceNormals()
{
int iFaceIndex = 0;
for (int iIndex = 0; iIndex < m_IndexList.size(); iIndex += 3)
{
DWORD i0 = m_IndexList[iIndex];
DWORD i1 = m_IndexList[iIndex + 1];
DWORD i2 = m_IndexList[iIndex + 2];
m_FaceNormalList[iFaceIndex++] = ComputeFaceNormal(i0, i1, i2);
}
}
D3DXVECTOR3 xMap::ComputeFaceNormal(DWORD i0, DWORD i1, DWORD i2)
{
D3DXVECTOR3 vNormal;
D3DXVECTOR3 v0 = m_VertexList[i1].p - m_VertexList[i0].p;
D3DXVECTOR3 v1 = m_VertexList[i2].p - m_VertexList[i0].p;
D3DXVec3Cross(&vNormal, &v0, &v1);
D3DXVec3Normalize(&vNormal, &vNormal);
return vNormal;
}
void xMap::GenNormalLookupTable()
{
m_NormalLooupTabel.resize(m_iNumVertex);
for (int iFace = 0; iFace < m_iNumFace; iFace++)
{
for (int iVertex = 0; iVertex < 3; iVertex++)
{
for (int iTable = 0; iTable < 6; iTable++)
{
int iIndex = m_IndexList[iFace*3+iVertex];
if (m_NormalLooupTabel[iIndex].faceIndex[iTable] == -1)
{
m_NormalLooupTabel[iIndex].faceIndex[iTable] =
iFace;
break;
}
}
}
}
}
void xMap::CalcPerVertexNormalsFastLookup()
{
CalcFaceNormals();
for (int iVertex = 0; iVertex < m_NormalLooupTabel.size(); iVertex++)
{
D3DXVECTOR3 avgNormal(0,0,0);
int iFace = 0;
for (iFace = 0; iFace < 6; iFace++)
{
if (m_NormalLooupTabel[iVertex].faceIndex[iFace] != -1)
{
int iFaceIndex = m_NormalLooupTabel[iVertex].faceIndex[iFace];
avgNormal += m_FaceNormalList[iFaceIndex];
}
else
{
break;
}
}
D3DXVec3Normalize(&m_VertexList[iVertex].n, &avgNormal);
////
//D3DXVECTOR3 vLight(100, 100, 100);
//D3DXVec3Normalize(&vLight, &vLight);
//float fDot = D3DXVec3Dot(&m_VertexList[iVertex].n,&vLight);
//m_VertexList[iVertex].c.x = fDot;
//m_VertexList[iVertex].c.y = fDot;
//m_VertexList[iVertex].c.z = fDot;
}
}
D3DXVECTOR2 xMap::GetTextureOfVertex(float fU, float fV)
{
return D3DXVECTOR2(fU, fV);
}
D3DXVECTOR3 xMap::GetNormalOfVertex(int iIndex)
{
return D3DXVECTOR3(0.0f, 1.0f, 0.0f );
}
D3DXVECTOR4 xMap::GetColorOfVertex(int iIndex)
{
return D3DXVECTOR4(
randstep(0.0f, 1.0f),
randstep(0.0f, 1.0f),
randstep(0.0f, 1.0f), 1.0f );
}
float xMap::GetHeightOfVertex(int iIndex)
{
if (m_fHeightList.size() > 0)
{
return m_fHeightList[iIndex] * m_fScaleHeight;
}
return 0.0f;
}
bool xMap::CreateMap(xMapDesc desc)
{
m_iNumRows = desc.iNumRows;
m_iNumCols = desc.iNumCols;
m_iNumCellRows = m_iNumRows-1;
m_iNumCellCols= m_iNumCols-1;
m_iNumVertices = m_iNumRows * m_iNumCols;
m_iNumFace = m_iNumCellRows* m_iNumCellCols*2;
m_fCellDistance = desc.fDistance;
m_fScaleHeight = desc.fScaleHeight;
m_xMapDesc = desc;
return true;
}
bool xMap::Load(ID3D11Device* pDevice, xMapDesc desc)
{
m_pd3dDevice = pDevice;
if (!CreateMap(desc))
{
return false;
}
xShape::Create(m_pd3dDevice,desc.szShaderFile,desc.szTextureFile);
return true;
}
bool xMap::Init()
{
return true;
}
bool xMap::Frame()
{
return xShape::Frame();
}
bool xMap::Render(ID3D11DeviceContext* pContext)
{
xShape::Render(pContext);
return true;
}
bool xMap::Release()
{
xShape::Release();
return true;
}
xMap::xMap()
{
m_fScaleHeight = 1;
}
xMap::~xMap()
{
}
| true |
f0622135390ca0cb703356db7c5219074599aba7 | C++ | RobTillaart/Arduino | /libraries/GY521/examples/GY521_test_2/GY521_test_2.ino | UTF-8 | 1,570 | 2.65625 | 3 | [
"MIT"
] | permissive | //
// FILE: GY521_test_2.ino
// AUTHOR: Rob Tillaart
// PURPOSE: test set/get functions
// DATE: 2020-08-06
#include "GY521.h"
GY521 sensor(0x69);
void setup()
{
Serial.begin(115200);
Serial.println();
Serial.println(__FILE__);
Serial.print("GY521_LIB_VERSION: ");
Serial.println(GY521_LIB_VERSION);
Wire.begin();
delay(100);
if (sensor.wakeup() == false)
{
Serial.println("Could not connect to GY521");
}
Serial.println("ACCEL TEST");
for (uint8_t n = 0; n < 4; n++)
{
sensor.setAccelSensitivity(n);
uint8_t p = sensor.getAccelSensitivity();
if (n != p)
{
Serial.print("\tAccel err:\t");
Serial.print(n);
Serial.print("\t");
Serial.println(p);
}
}
Serial.println("GYRO TEST");
for (uint8_t n = 0; n < 4; n++)
{
sensor.setGyroSensitivity(n);
uint8_t p = sensor.getGyroSensitivity();
if (n != p)
{
Serial.print("\tGyro err:\t");
Serial.print(n);
Serial.print("\t");
Serial.println(p);
}
}
Serial.println("THROTTLE TEST");
sensor.setThrottle();
if (sensor.getThrottle() == false)
{
Serial.println("\tThrot:\ttrue");
}
sensor.setThrottle(false);
if (sensor.getThrottle() == true)
{
Serial.println("\tThrot err:\tfalse");
}
for (uint16_t n = 0; n < 1000; n++) // 0 - 1 second.
{
sensor.setThrottleTime(n);
if (sensor.getThrottleTime() != n)
{
Serial.print("\tTT err:\t");
Serial.println(n);
}
}
Serial.println("\nDone...");
}
void loop()
{
}
// -- END OF FILE --
| true |
470741f499d42f68a9325a645e8249314ce093fa | C++ | dawidpaweloszek/3S_Game_engine | /3S_game_engine/include/GameLogic/Hierarchy.h | UTF-8 | 1,689 | 2.5625 | 3 | [] | no_license | #pragma once
#ifndef HIERARCHY_H
#define HIERARCHY_H
#include "Application/Application.h"
#include "GameLogic/Proctor.h"
#include "Camera/Camera.h"
#include <vector>
#include "UIRender/UIElement.h"
namespace GameLogic
{
class Hierarchy
{
public:
/* Constructors */
Hierarchy(bool _state = true);
Hierarchy(Application::Window* _scene, Camera* _camera = NULL, bool _state = true);
/* Objects method */
void addObject(Proctor* _proctor);
void removeObject(Proctor* _proctor);
Proctor* getObjectsInRadiusOf(Proctor* _proctor, float _radius);
Proctor* getObject(std::string _name);
Proctor* getObject(unsigned int _uuid);
std::vector<Proctor*> getProctors();
std::vector<Proctor*> getInteractable();
std::vector<Proctor*> getTreasure();
std::vector<Proctor*> getCash();
std::vector<Proctor*> getEnemiesList();
/* Scene method */
float getDeltaTime();
/* Camera method */
void setCamera(Camera* _camera);
Camera* getCamera();
/* State methods */
void setState(bool _state);
bool getState();
/* Render methods */
void renderWithShader(Shader* _shader);
void drawHierarchyWindow();
/* Player methods */
int playerHealth = 3;
UIRender::UIElement* health[6];
void takeDamage();
void update(bool _onlyRender = false, bool _drawDebug = false, int collisionIncrement = 0);
void cleanup();
private:
bool collidersLoaded;
std::vector<Proctor*> proctors;
std::vector<Proctor*> interactable;
std::vector<Proctor*> treasure;
std::vector<Proctor*> cash;
Application::Window* scene;
Camera* camera;
/* Debug window variables */
bool active;
std::string activeProctorName = "none";
};
}
#endif // !HIERARCHY_H | true |
9ca19a83c80e14bceb020982806626622ffbd264 | C++ | kei1107/algorithm | /problems/Atcoder/ARC063_C.cpp | UTF-8 | 1,968 | 2.890625 | 3 | [] | no_license | #include "bits/stdc++.h"
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
const int INF = 1e9;
const ll LINF = 1e18;
/*
<url:https://arc063.contest.atcoder.jp/tasks/arc063_a>
問題文============================================================
きつねの次郎と三郎が一次元リバーシで遊んでいます。
一次元リバーシでは、盤面には白か黒の石が一列に並んだ状態となっており、列の右端か左端に新たに石を打っていきます。
通常のリバーシと同じように、たとえば白の石を打つことで黒の石を挟むと、挟まれた黒の石は白い石に変わります。
ゲームの途中で三郎に急用ができて帰ってしまうことになりました。このとき、盤面の状態は文字列 S で表されます。
石は |S| (文字列の長さ) 個並んでおり、
左から i (1≦i≦|S|) 個目の石の色は、S の i 文字目が B のとき黒、W のとき白です。
次郎は現在の盤面に対して、できるだけ少ない個数の石を新たに打つことで全ての石を同じ色にしようと考えました。
最小で何個の石を打てばよいかを求めてください。
=================================================================
解説=============================================================
左と右から順番にひっくり返して行った場合をシミュレーションすれば良い
================================================================
*/
int main(void) {
cin.tie(0); ios::sync_with_stdio(false);
string S; cin >> S;
int ans = INF;
int tmp = 0;
for(int i = 0; i < (int)S.length()-1;i++){
if(S[i] != S[i]+1) tmp++;
}
ans = min(ans,tmp);
tmp = 0;
for(int i = (int)S.length()-1; i>0;i--){
if(S[i] != S[i-1]) tmp++;
}
ans = min(ans,tmp);
cout << ans << endl;
return 0;
}
| true |
02ae7f46cc51bf3c0f3232eac67a83af22af2ed1 | C++ | ArtemGen/xray-oxygen | /code/engine.vc2008/xrCore/Buildcpp.cpp | UTF-8 | 952 | 2.625 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause"
] | permissive | #include "stdafx.h"
// computing build id
extern LPCSTR build_date;
extern u32 build_id;
static constexpr char* month_id[12] = {
"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
};
static constexpr u32 days_in_month[12] =
{
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
static constexpr u32 start_day = 26;
static constexpr u32 start_month = 12;
static constexpr u32 start_year = 2016;
// binary hash, mainly for copy-protection
void compute_build_id()
{
build_date = __DATE__;
u32 Days;
u32 MonthId = 0;
u32 Years;
string16 Month = { 0 };
sscanf(__DATE__, "%s %d %d", Month, &Days, &Years);
for (u32 i = 0; i < 12; i++)
{
if (_stricmp(month_id[i], Month))
continue;
MonthId = i;
break;
}
build_id = (Years - start_year) * 365 + Days - start_day;
for (u32 i = 0; i < MonthId; ++i)
build_id += days_in_month[i];
for (u32 i = 0; i < start_month - 1; ++i)
build_id -= days_in_month[i];
} | true |
37889d506d286edf8e90203d21cac46499603c5e | C++ | DrScKAWAMOTO/FullereneViewer | /src/Matrix3.h | UTF-8 | 2,664 | 2.828125 | 3 | [
"Apache-2.0"
] | permissive | /*
* Project: FullereneViewer
* Version: 1.0
* Copyright: (C) 2011-15 Dr.Sc.KAWAMOTO,Takuji (Ext)
*/
#ifndef __MATRIX3_H__
#define __MATRIX3_H__
class Vector3;
class Quaternion;
class Matrix3 {
// friend classes & functions
// members
private:
double p_xx, p_xy, p_xz;
double p_yx, p_yy, p_yz;
double p_zx, p_zy, p_zz;
// private tools
// constructors & the destructor
public:
Matrix3(double xx = 1.0, double xy = 0.0, double xz = 0.0,
double yx = 0.0, double yy = 1.0, double yz = 0.0,
double zx = 0.0, double zy = 0.0, double zz = 1.0);
Matrix3(double* array);
Matrix3(const Matrix3& you);
Matrix3(const Quaternion& you);
// Matrix3(Q1 * Q2) = Matrix3(Q1) * Matrix3(Q2)
// V * Matrix3(Q) = Vector3(Q.conjugation() * Quaternion(V) * Q)
void operator = (const Matrix3& you);
~Matrix3();
void randomize();
// type converters
const double* to_array44() const;
const double* to_array33() const;
// comparators
bool operator == (const Matrix3& you) const;
// math operators
friend Vector3 operator * (const Vector3& a, const Matrix3& b);
friend Vector3 operator * (const Matrix3& a, const Vector3& b);
friend Matrix3 operator * (const Matrix3& a, const Matrix3& b);
friend Matrix3 operator - (const Matrix3& a, const Matrix3& b);
friend Matrix3 operator - (const Matrix3& a);
void operator *= (const Matrix3& b);
void operator *= (double b);
double det() const;
double abs() const;
Matrix3 inv() const;
Matrix3 transpose() const;
void orthonormalize();
static void Eigenvalues_and_Eigenvectors(const Matrix3& target,
double& value1, Vector3& vector1,
double& value2, Vector3& vector2,
double& value3, Vector3& vector3);
// I/O
public:
void print(int width) const;
// class decision
// member accessing methods
public:
double xx() const { return p_xx; }
double xy() const { return p_xy; }
double xz() const { return p_xz; }
double yx() const { return p_yx; }
double yy() const { return p_yy; }
double yz() const { return p_yz; }
double zx() const { return p_zx; }
double zy() const { return p_zy; }
double zz() const { return p_zz; }
double& xx() { return p_xx; }
double& xy() { return p_xy; }
double& xz() { return p_xz; }
double& yx() { return p_yx; }
double& yy() { return p_yy; }
double& yz() { return p_yz; }
double& zx() { return p_zx; }
double& zy() { return p_zy; }
double& zz() { return p_zz; }
};
#endif /* __MATRIX3_H__ */
/* Local Variables: */
/* mode: c++ */
/* End: */
| true |
9a4e0ca834df99b6446632538f7099d20b42e0a7 | C++ | Luke1962/robot | /Prove/ArduinoMAVLink/ArduinoMAVLink.ino/ArduinoMAVLink.ino.ino | UTF-8 | 1,430 | 2.625 | 3 | [] | no_license |
// Arduino MAVLink test code.
//#include <FastSerial.h>
#include <mavlink/include/mavlink.h> // Mavlink interface
// FastSerialPort0(Serial);
void setup() {
Serial.begin(57600);
}
void loop() {
// Define the system type (see mavlink_types.h for list of possible types)
int system_type = MAV_QUADROTOR;
int autopilot_type = MAV_AUTOPILOT_GENERIC;
// Initialize the required buffers
mavlink_message_t msg;
uint8_t buf[MAVLINK_MAX_PACKET_LEN];
// Pack the message
// mavlink_message_heartbeat_pack(system id, component id, message container, system type, MAV_AUTOPILOT_GENERIC)
mavlink_msg_heartbeat_pack(100, 200, &msg, system_type, autopilot_type);
// Copy the message to send buffer
uint16_t len = mavlink_msg_to_send_buffer(buf, &msg);
// Send the message (.write sends as bytes)
Serial.write(buf, len);
comm_receive();
}
void comm_receive() {
mavlink_message_t msg;
mavlink_status_t status;
//receive data over serial
while(Serial.available() > 0) {
uint8_t c = Serial.read();
//try to get a new message
if(mavlink_parse_char(MAVLINK_COMM_0, c, &msg, &status)) {
// Handle message
switch(msg.msgid) {
case MAVLINK_MSG_ID_SET_MODE: {
// set mode
}
break;
case MAVLINK_MSG_ID_ACTION:
// EXECUTE ACTION
break;
default:
//Do nothing
break;
}
}
// And get the next one
}
}
| true |
9a9a05e78042ded33f43bc17c906077155dcd0bf | C++ | hauke96/glowing-octo-batman | /main.cpp | UTF-8 | 395 | 2.546875 | 3 | [] | no_license | #include <GameManager.h>
#include <iostream>
#include <string>
using namespace std;
// UNDERLINE : \033[4m
// BOLD : \033[1m
// NOTHING : \033[0m
// ROT : \033[31m
// DARK GREEN : \033[32m
// BROWN : \033[33m
// BLUE : \033[34m
// LIGHT GREEN: \033[36m
// GRAY : \033[37m
int main()
{
GameManager _gameManager;
_gameManager.start();
return 0;
}
| true |
ca874c39146e3f0a8ee501dd8a78ee78597f3ff4 | C++ | nohhyeonjin/BOJ | /DFSBFS/2178.cpp | UTF-8 | 924 | 2.515625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int n,m;
int maze[100][100];
int visited[100][100];
int dy[4]={0,1,0,-1};
int dx[4]={1,0,-1,0};
bool inside(int ny,int nx){
if(ny>=0&&nx>=0&&ny<n&&nx<m) return true;
return false;
}
void bfs(){
queue<pair<int,int>> q;
q.push(make_pair(0,0));
visited[0][0]=1;
while(!q.empty()){
int y=q.front().first;
int x=q.front().second;
int cnt=maze[y][x]+1;
q.pop();
for(int i=0;i<4;i++){
int ny=y+dy[i];
int nx=x+dx[i];
if(inside(ny,nx)&&maze[ny][nx]>0&&visited[ny][nx]==0){
q.push(make_pair(ny,nx));
maze[ny][nx]=cnt;
visited[ny][nx]=1;
}
}
}
}
int main(){
scanf("%d %d",&n,&m);
for(int i=0;i<n;i++){
for(int j=0;j<m;j++) scanf("%1d",&maze[i][j]);
}
bfs();
printf("%d",maze[n-1][m-1]);
} | true |
6b340cc0e028d8a0fcff1a2d792936256c3e2126 | C++ | hongwei7/LeetcodePractice | /70.爬楼梯.cpp | UTF-8 | 395 | 2.765625 | 3 | [] | no_license | /*
* @lc app=leetcode.cn id=70 lang=cpp
*
* [70] 爬楼梯
*/
// @lc code=start
class Solution {
public:
int climbStairs(int n) {
if (n == 1)
return 1;
int pre1 = 1, pre2 = 2, now = 2;
for(int i = 2; i < n; i ++){
now = pre1 + pre2;
pre1 = pre2;
pre2 = now;
}
return now;
}
};
// @lc code=end
| true |
9964a4c095c272e994c352f720d7a76d69441943 | C++ | jorgepuertoesteban/EchosOfNightmare | /EON/include/graphics/VisualBody.h | UTF-8 | 426 | 2.671875 | 3 | [] | no_license | #pragma once
#include "Vec2.h"
class VisualBody : public sf::Drawable {
public:
virtual ~VisualBody() {}
virtual void Initialize(Vec2 tam) = 0;
virtual bool GetVisible() = 0;
virtual void SetPosition(Vec2 pos) = 0;
virtual void SetRotation(float angle) = 0;
virtual void SetVisible(bool aux) = 0;
virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const = 0;
protected:
};
| true |
94cca0a95fd8bc738176966b7d2cc5f2921da604 | C++ | fredemmott/jerboa | /src/plugins/JerboaPlaylist/JerboaPlaylist_Implementation.cpp | UTF-8 | 4,611 | 2.6875 | 3 | [] | no_license | #include "JerboaPlaylist_Implementation.h"
#include <QDateTime>
#include <QDebug>
JerboaPlaylist::Implementation::Implementation(Jerboa::TagReader* tagReader, QObject* parent)
:
Jerboa::PlaylistInterface(tagReader, parent),
m_loopMode(LoopNone),
m_shuffleMode(ShuffleNone),
m_currentTrack(-1),
m_nextTrack(-1)
{
qsrand(QDateTime::currentDateTime().toTime_t());
}
Jerboa::PlaylistInterface::LoopMode JerboaPlaylist::Implementation::loopMode() const
{
return m_loopMode;
}
Jerboa::PlaylistInterface::ShuffleMode JerboaPlaylist::Implementation::shuffleMode() const
{
return m_shuffleMode;
}
void JerboaPlaylist::Implementation::setLoopMode(LoopMode mode)
{
m_loopMode = mode;
emit loopModeChanged(mode);
adjustNextTrack();
}
void JerboaPlaylist::Implementation::setShuffleMode(ShuffleMode mode)
{
m_shuffleMode = mode;
emit shuffleModeChanged(mode);
adjustNextTrack();
}
int JerboaPlaylist::Implementation::currentTrack() const
{
return m_currentTrack;
}
int JerboaPlaylist::Implementation::nextTrack() const
{
return m_nextTrack;
}
QList<Jerboa::TrackData> JerboaPlaylist::Implementation::tracks() const
{
return m_tracks;
}
int JerboaPlaylist::Implementation::appendTracks(const QList<Jerboa::TrackData>& data)
{
Q_FOREACH(const Jerboa::TrackData& track, data)
{
Q_UNUSED(track); // For non-debug builds
Q_ASSERT(track.isValid());
}
m_tracks.append(data);
const int index = m_tracks.count() - data.count();
adjustNextTrack();
emit tracksAdded(index, data);
return index;
}
void JerboaPlaylist::Implementation::insertTracks(int index, const QList<Jerboa::TrackData>& data)
{
if(index == -1)
{
appendTracks(data);
return;
}
for(int i = 0; i < data.count(); ++i)
{
const Jerboa::TrackData& track = data.at(i);
Q_ASSERT(track.isValid());
m_tracks.insert(index + i, track);
}
if(m_currentTrack >= index)
{
m_currentTrack += data.count();
}
adjustNextTrack();
emit tracksAdded(index, data);
}
void JerboaPlaylist::Implementation::removeTracks(int index, int count)
{
for(int i = 0; i < count; ++i)
{
if(m_currentTrack == index && m_currentTrack != -1)
{
m_currentTrack = -1;
}
else if(m_currentTrack > index)
{
--m_currentTrack;
}
m_tracks.removeAt(index);
}
setCurrentTrack(m_currentTrack);
emit tracksRemoved(index, count);
adjustNextTrack();
}
void JerboaPlaylist::Implementation::setCurrentTrack(int index)
{
Q_ASSERT(index < m_tracks.count());
m_currentTrack = index;
emit positionChanged(index);
adjustNextTrack();
}
int JerboaPlaylist::Implementation::startOfAlbum(int index) const
{
while(index >= 1)
{
if(m_tracks.at(index - 1).album() != m_tracks.at(index).album())
{
break;
}
--index;
}
return index;
}
void JerboaPlaylist::Implementation::adjustNextTrack()
{
if(m_tracks.isEmpty())
{
m_nextTrack = -1;
emit dataChanged();
return;
}
if(m_loopMode == LoopTrack && m_currentTrack < m_tracks.count())
{
m_nextTrack = m_currentTrack;
emit dataChanged();
return;
}
switch(m_shuffleMode)
{
case ShuffleNone:
if(m_currentTrack + 1 < m_tracks.count())
{
if(
m_currentTrack >= 0
&&
m_loopMode == LoopAlbum
&&
m_tracks.at(m_currentTrack).album() != m_tracks.at(m_currentTrack + 1).album()
)
{
m_nextTrack = startOfAlbum(m_currentTrack);
}
else
{
m_nextTrack = m_currentTrack + 1;
}
}
else if(m_loopMode == LoopPlaylist)
{
m_nextTrack = 0;
}
else if(m_loopMode == LoopAlbum)
{
m_nextTrack = startOfAlbum(m_currentTrack);
}
else
{
m_nextTrack = -1;
}
emit dataChanged();
return;
case ShuffleTracks:
// not perfect, but good enough
m_nextTrack = qrand() % m_tracks.count();
emit dataChanged();
return;
case ShuffleAlbums:
if(
m_tracks.count() > (m_currentTrack + 1)
&&
m_tracks.at(m_currentTrack).album() == m_tracks.at(m_currentTrack + 1).album()
)
{
m_nextTrack = m_currentTrack + 1;
}
else if(
m_currentTrack != -1
&&
m_loopMode == LoopAlbum
)
{
m_nextTrack = startOfAlbum(m_currentTrack);
}
else
{
// Pick a random track
int currentTrack = qrand() % m_tracks.count();
// Backtrack until we find the first track in an album
while(true)
{
Q_ASSERT(currentTrack >= 0);
if(currentTrack == 0 || m_tracks.at(currentTrack).album() != m_tracks.at(currentTrack - 1).album())
{
m_nextTrack = currentTrack;
emit dataChanged();
return;
}
--currentTrack;
}
}
emit dataChanged();
return;
}
emit dataChanged();
}
| true |
dce290357fd727c4deebf916e76546d1d41c4685 | C++ | matusnovak/doxybook2 | /example/src/Audio/AudioManager.hpp | UTF-8 | 928 | 2.953125 | 3 | [
"MIT"
] | permissive | #pragma once
#include "AudioBuffer.hpp"
namespace Engine {
namespace Audio {
/*!
* @brief An audio manager that *accepts* multiple **Audio::AudioBuffer** instances
* @details Lorem Ipsum Donor. Some [Random link with **bold** and _italics_](http://github.com)
* And the following is a \c typewritter font. And here is some list items:
* * First item
* * Second item
* * Third item **with bold text**
*
* Followed by some more text and another list:
* * First item
* * Second item
* @ingroup Audio
* @see Audio::AudioBuffer
*/
class AudioManager final {
public:
AudioManager(int numOfChannels = 128);
~AudioManager();
void enque(const AudioBuffer& buffer);
};
} // namespace Audio
} // namespace Engine | true |
220afbb2e27ae352812bf9f7c64c72d911361f87 | C++ | ailyanlu/zoj | /1069.cpp | UTF-8 | 1,142 | 2.90625 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#define MAXN 22
using namespace std;
bool isok(bool face[3][MAXN][MAXN], bool newface[3][MAXN][MAXN], int n) {
for(int i = 0; i < 3; ++i)
for(int j = 0; j < n; ++j)
for(int k = 0; k < n; ++k)
if(face[i][j][k] != newface[i][j][k])
return false;
return true;
}
int main() {
int n;
bool face[3][MAXN][MAXN], newface[3][MAXN][MAXN];
char tmp[MAXN];
int t = 1;
while(scanf("%d", &n) != EOF) {
if(n == 0)
break;
for(int i = 0; i < 3; ++i)
for(int j = 0; j < n; ++j) {
scanf("%s", tmp);
for(int k = 0; tmp[k]; ++k) {
if(tmp[k] == 'X')
face[i][j][k] = true;
else
face[i][j][k] = false;
newface[i][j][k] = false;
}
}
for(int i = 0; i < n; ++i)
for(int j = 0; j < n; ++j)
for(int k = 0; k < n; ++k) {
bool val = (face[0][i][j] && face[1][j][k] && face[2][i][k]);
newface[0][i][j] |= val;
newface[1][j][k] |= val;
newface[2][i][k] |= val;
}
if(isok(face, newface, n))
printf("Data set %d: Valid set of patterns\n", t);
else
printf("Data set %d: Impossible combination\n", t);
++t;
}
return 0;
}
| true |
5a1528e21e5908a5dcfd53144926613af0c59eca | C++ | chixulub/kattis | /dicegame/dicegame.cpp | UTF-8 | 530 | 3.328125 | 3 | [] | no_license | #include <iostream>
#include <cstdint>
using namespace std;
float expected(int a, int b)
{
int n = 1+b-a;
int sum = n*a + (n*n + n)/2;
return sum/float(n);
}
int main(int, char**)
{
float exps[4];
int a,b;
for (int i = 0; i < 4; ++i)
{
cin >> a >> b;
exps[i] = expected(a,b);
}
float gunnar = exps[0] + exps[1];
float emma = exps[2] + exps[3];
if ( gunnar > emma)
{
cout << "Gunnar" << endl;
}
else if (emma > gunnar)
{
cout << "Emma" << endl;
}
else
{
cout << "Tie" << endl;
}
return 0;
}
| true |
3489d04e81da2f471c4f960585f3d7d6c5d7c205 | C++ | Dan-sensei/Micro-Machines | /Animator.h | UTF-8 | 1,722 | 2.84375 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: Animation.h
* Author: dan
*
* Created on 10 de marzo de 2018, 16:25
*/
#ifndef ANIMATION_H
#define ANIMATION_H
#include <vector>
#include <SFML/System/Time.hpp>
#include <SFML/System/Vector2.hpp>
#include <SFML/Graphics/Sprite.hpp>
#include <list>
#include <string>
#include <iostream>
class Animator {
public:
struct Animation{
std::string animName;
std::string animTexture;
std::vector<sf::IntRect> animFrames;
sf::Time animDuration;
bool animLoop;
Animation(std::string const& n, std::string const& tex, sf::Time const& d, bool l)
:animName(n), animTexture(tex), animDuration(d), animLoop(l){}
void AddFrames(const sf::Vector2i& startFrom, const sf::Vector2i& frameSize, unsigned int nFrames){
sf::Vector2i currentFrame = startFrom;
for(unsigned int i = 0; i < nFrames; i++){
animFrames.push_back(sf::IntRect(currentFrame.x, currentFrame.y, frameSize.x, frameSize.y));
currentFrame.x += frameSize.x;
}
}
};
Animator(sf::Sprite& s);
Animator::Animation& createAnimation(std::string const& name, std::string const& textureName, sf::Time const& duration, bool loop = false);
void update(sf::Time const& dt);
private:
sf::Sprite& sprite;
sf::Time currentTime;
std::list<Animation> animations;
Animation* currentAnimation;
void switchAnimation(Animation* anim);
};
#endif /* ANIMATION_H */
| true |
999fe8ab54ee47244b214104dedff378f168e0e9 | C++ | rthaper01/competitive-programming-4-solutions | /Chapter 2/Kattis/unionfind.cpp | UTF-8 | 1,241 | 2.78125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include "stdio.h"
using namespace std;
int findSet(int i, int* v) {
if (v[i] == i) {
return i;
}
else {
v[i] = findSet(v[i], v);
return v[i];
}
}
bool isSameSet(int i, int j, int* v) {
return (findSet(i, v) == findSet(j, v));
}
void unionSet(int i, int j, int* v, int* r) {
if (isSameSet(i, j, v)) {
return;
}
int x = findSet(i, v), y = findSet(j, v);
if (r[x] > r[y]) {
swap(x, y);
}
v[x] = y;
if (r[x] == r[y]) {
r[y]++;
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
int N, Q;
scanf("%d%d\n", &N, &Q);
int p[N];
for (int i = 0; i < N; i++) {
p[i] = i;
}
int rank[N];
int a, b;
for (int i = 0; i < Q; i++) {
char ch;
scanf("%c", &ch);
if (ch == '=') {
scanf("%d%d\n", &a, &b);
unionSet(a, b, p, rank);
}
else if (ch == '?') {
scanf("%d%d\n", &a, &b);
if (isSameSet(a, b, p)) {
printf("yes\n");
}
else {
printf("no\n");
}
}
}
return 0;
} | true |
812e8a81353cf0d9827abaa4415f81ef1c46ec21 | C++ | liuxinren456852/PlaneDetection | /CommandLineOption/src/primitive.h | UTF-8 | 1,795 | 3.203125 | 3 | [] | no_license | #ifndef PRIMITIVE_H
#define PRIMITIVE_H
#include <set>
#include <Eigen/Core>
template <size_t DIMENSION>
class Primitive
{
public:
Primitive(const Eigen::Matrix<float, DIMENSION, 1> ¢er)
: mCenter(center)
{
}
virtual ~Primitive()
{
}
virtual const Eigen::Matrix<float, DIMENSION, 1>& center() const
{
return mCenter;
}
virtual void center(const Eigen::Matrix<float, DIMENSION, 1> ¢er)
{
mCenter = center;
}
const Eigen::Vector3f& color() const
{
return mColor;
}
void color(const Eigen::Vector3f &color)
{
mColor = color;
}
int label() const
{
return mLabel;
}
void label(int label)
{
mLabel = label;
}
const std::vector<size_t>& inliers() const
{
return mInliers;
}
void inliers(const std::vector<size_t> &inliers)
{
mInliers = inliers;
}
void addInlier(size_t point)
{
mInliers.push_back(point);
}
void addInliers(const std::vector<size_t> &points)
{
mInliers.insert(mInliers.end(), points.begin(), points.end());
}
virtual void leastSquares(const Eigen::Matrix<float, DIMENSION, -1> &points)
{
}
virtual float getSignedDistanceFromSurface(const Eigen::Matrix<float, DIMENSION, 1> &point) const = 0;
virtual Eigen::Matrix<float, DIMENSION, 1> normalAt(const Eigen::Matrix<float, DIMENSION, 1> &point) const = 0;
protected:
Eigen::Matrix<float, DIMENSION, 1> mCenter;
Eigen::Vector3f mColor;
std::vector<size_t> mInliers;
int mLabel;
};
template class Primitive<2>;
template class Primitive<3>;
typedef Primitive<2> Primitive2d;
typedef Primitive<3> Primitive3d;
#endif // PRIMITIVE_H
| true |
105691ac70ba03a4051a26197f274dfacbbf2d86 | C++ | aaronmjacobs/Restoration | /src/TextureMaterial.h | UTF-8 | 1,252 | 2.671875 | 3 | [] | no_license | #ifndef TEXTURE_MATERIAL_H
#define TEXTURE_MATERIAL_H
#include "PhongMaterial.h"
#include "FrameBuffer.h"
class TextureMaterial : public PhongMaterial {
protected:
GLuint textureID, altTextureID;
GLint uTexture, aTexCoord;
const std::string textureFileName;
const std::string altTextureFileName;
public:
/**
* Name of the class (used in deserialization to determine types).
*/
static const std::string CLASS_NAME;
/**
* Create the texture id and phong material
*/
TextureMaterial(const std::string &jsonFileName,
SPtr<ShaderProgram> shaderProgram,
const glm::vec3 &ambient,
const glm::vec3 &diffuse,
const glm::vec3 &specular,
const glm::vec3 &emission,
float shininess,
const std::string &textureFileName,
const std::string &altTextureFileName = "");
/**
* Delete the texture.
*/
virtual ~TextureMaterial();
/**
* Serializes the object to JSON.
*/
virtual Json::Value serialize() const;
virtual void apply(const RenderData &renderData, const Mesh &mesh);
virtual void disable();
bool hasAltTexture();
};
#endif
| true |
81690066e54f904e6c272c8742cd0846ca3b69d1 | C++ | sahilgithub908/coderspree | /AR-VR/devAyushDubey_ayushdubey_2024csit1122_2/FunctionAndArrays/SubarrayProblem.cpp | UTF-8 | 368 | 2.6875 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main(){
int n,i,j,k;
cin>>n;
int* arr = new int[n];
for(i = 0 ; i < n; i++)
cin>>arr[i];
i=0;
while(i<n){
for(k=i;k<n;k++){
for(j=i;j<=k;j++)
cout<<arr[j]<<" ";
cout<<endl;
}
i++;
}
// write your code here
} | true |
53789dffd8cf01971f19fff6ba8cfa1d50a11e71 | C++ | rhaps0dy/UPF-SWERC | /ACM-ICPC-Live-Archive/2013/Europe_Central/6591_bus.cpp | UTF-8 | 261 | 2.625 | 3 | [] | no_license | #include<iostream>
#include<algorithm>
using namespace std;
int cache[31];
int main() {
int N;
cin >> N;
cache[0] = 0;
for(int i=1; i<31; i++)
cache[i] = cache[i-1]*2 + 1;
while(N--) {
int n;
cin >> n;
cout << cache[n] << endl;
}
return 0;
}
| true |
eabab0320988c2a9ddf2c6c4a3ae96cd93374c80 | C++ | chavangorakh1999/DataStructureAndAlgorithms | /FactorialUsingRecursion.cpp | UTF-8 | 356 | 3.078125 | 3 | [] | no_license | //
// main.cpp
// FactorialUsingRecursion
//
// Created by Gorakh Chavan on 16/03/20.
// Copyright © 2020 Gorakh Chavan. All rights reserved.
//
#include <iostream>
using namespace std;
int fact(int a)
{
if(a==0)
return 1;
else
return fact(a-1)*a;
};
int main()
{
int z;
z=fact(5);
cout<<z<<endl;
return 0;
}
| true |
ec102509f7b11b1a56cc11965d11ad138fc37843 | C++ | denis-gubar/Leetcode | /Tree/1602. Find Nearest Right Node in Binary Tree.cpp | UTF-8 | 829 | 3.234375 | 3 | [] | no_license | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* calc(TreeNode* root, TreeNode* u, int level, int& uLevel)
{
if (!root)
return nullptr;
if (level == uLevel)
return root;
if (root == u)
uLevel = level;
TreeNode* result = calc(root->left, u, level + 1, uLevel);
if (result)
return result;
return calc(root->right, u, level + 1, uLevel);
}
TreeNode* findNearestRightNode(TreeNode* root, TreeNode* u) {
int uLevel = -1;
return calc(root, u, 0, uLevel);
}
}; | true |
efe200e93dd3c6b674312d379266a0f00948de48 | C++ | Arthurlpgc/PatternMatchingTool | /src/parser.h | UTF-8 | 3,548 | 3.140625 | 3 | [] | no_license | #include <getopt.h>
#include <fstream>
#include <string>
#include <vector>
#include <queue>
const char* const short_opts = "tce:p:a:h";
const option long_opts[] = {
{"help", no_argument, nullptr, 'h'},
{"count", no_argument, nullptr, 'c'},
{"edit", required_argument, nullptr, 'e'},
{"pattern", required_argument, nullptr, 'p'},
{"algorithm", required_argument, nullptr, 'a'},
};
struct Parser {
std::queue<std::string> filenames;
std::string pattern_file_path = "";
std::vector<std::string> patts;
std::string algorithm = "None";
std::ifstream* file = NULL;
std::string filename = "";
int edit_distance = 0;
std::string buffer;
bool help = false;
bool line = true;
bool dist = false;
int error = 0;
Parser(int argc, char** argv) {
int opt = 0;
while(opt != -1) {
opt = getopt_long(argc, argv, short_opts, long_opts, nullptr);
switch(opt) {
case 'c':
line = false;
break;
case 'e':
edit_distance = std::stoi(optarg);
dist = true;
break;
case 'p':
pattern_file_path = std::string(optarg);
break;
case 'a':
algorithm = std::string(optarg);
break;
case -1:
break;
default:
help = true;
return;
}
}
if (argc <= 1) {
help = true;
return;
}
int ind = optind;
if (pattern_file_path != "") {
std::string pattern;
std::ifstream* pattern_file = new std::ifstream();
pattern_file->open(pattern_file_path);
if(!pattern_file->is_open()){
error = 2;
return;
}
while(!pattern_file->eof()) {
getline(*pattern_file, pattern);
patts.push_back(pattern);
if(dist && pattern.length() <= edit_distance) {
error = 3;
return;
}
}
pattern_file->close();
} else if (ind != argc) {
std::string pattern = std::string(argv[ind++]);
patts.push_back(pattern);
if(dist && pattern.length() <= edit_distance) {
error = 3;
return;
}
} else {
error = 1;
return;
}
while(ind < argc) {
std::string file_name = std::string(argv[ind++]);
filenames.push(file_name);
}
if(filenames.size() > 1) {
filename = filenames.front();
}
}
inline bool iterator() {
if(filenames.empty()){
return false;
}
if(file != NULL) {
file->close();
delete file;
}
if(filename != "") {
filename = filenames.front() + ": ";
}
file = new std::ifstream();
file->open(filenames.front());
if(!file->is_open())file = NULL;
filenames.pop();
return true;
}
inline std::string next() {
if(file == NULL) {
return "\n";
}
getline(*file, buffer);
return buffer;
}
inline bool has_next() {
return file != NULL && !file->eof();
}
};
| true |
0e86668e2244c1204a13d9cb06a78629ab0bdf1f | C++ | Victor-Hamon/Gomoku_AI | /main.cpp | UTF-8 | 539 | 2.5625 | 3 | [] | no_license | #include<iostream>
#include<string>
#include "Commands.h"
#include "SharedFunctions.h"
Incephalon incephalon;
[[noreturn]] int play() {
std::string command;
Vector input, best;
int size = 20;
incephalon.setSize(20);
while (true) {
std::cin >> command;
toupper(command);
for (auto& current_command : commands) {
if (current_command.key == command) {
current_command.handler(input, best, size, incephalon);
}
}
}
}
int main() {
play();
}
| true |
d207fee1ff04e0e53f1e3964a98565334adb0c95 | C++ | elsys/Shaprin_Frameword3D | /src/osgf/OSGF/OSGFKeyboard.h | UTF-8 | 1,023 | 2.71875 | 3 | [
"MIT"
] | permissive | #pragma once
#include <vector>
#include <Windows.h>
#include "OSGFInputElement.h"
class OSGFKeyboard :
public OSGFInputElement
{
public:
OSGFKeyboard(Game& game)
:OSGFInputElement(game),
mCurrentState(0xFFFF,1),mPrevState(0xFFFF,1)
{
}
virtual void Update(double dTime)
{
mPrevState = mCurrentState;
}
const BYTE& operator[](USHORT index)const
{
return mCurrentState[index];
}
virtual void HandleInput(const RAWINPUT* ri)
{
RAWKEYBOARD k= ri->data.keyboard;
mCurrentState[k.VKey] = k.Flags & 0x01;
}
bool IsKeyDown(USHORT vKey)const
{
return mCurrentState[vKey]==0;
}
bool IsKeyUp(USHORT vKey)const
{
return !IsKeyDown(vKey);
}
bool IsKeyReleased(USHORT vKey)const
{
return (mCurrentState[vKey])&&!mPrevState[vKey];
}
bool IsKeyJustPressed(USHORT vKey)const
{
return (!mCurrentState[vKey])&&(mPrevState[vKey]);
}
virtual ~OSGFKeyboard(void)
{
}
private:
std::vector<BYTE> mCurrentState;
std::vector<BYTE> mPrevState;
};
| true |
be136802cba743494fa5416cae93518a07652bd5 | C++ | dannybanko/CSS343 | /Project-4/history.hpp | UTF-8 | 977 | 2.828125 | 3 | [] | no_license | //----------------------------------------------------------------------------
// History.h
// Implementation:
// -- This class is responsible for storing the history of customers
// transactions with movie type
// Assumptions:
// -- Inherits all behavior from Transaction parent class, although it has
// a unique constructor and destructor
// -- display() makes a call to Customer displayHistor() method
//----------------------------------------------------------------------------
#ifndef history_hpp
#define history_hpp
#include <fstream>
#include <iostream>
#include "transaction.hpp"
#include "customerHash.hpp"
#include "inventoryTree.hpp"
using namespace std;
class Customer;
class History : public Transaction {
public:
// constructor / destructor
History();
~History();
// processes transaction
virtual bool process(string, Movie*, Customer*);
// returns pointer to History
virtual Transaction* create();
};
#endif
| true |
395f456db4aa6add1ba8f5a7e62abfd0e7c16b20 | C++ | MohamadIsmail/Graphics-project | /FPS Game/FPSglutDesign/Player.cpp | UTF-8 | 760 | 3.125 | 3 | [] | no_license | #include"Player.h"
#include"Utils.h"
Player::Player(double x,double y,double z)
{
m_position.setX(x);
m_position.setY(y);
m_position.setZ(z);
}
Vector3d Player:: getPosition()
{
return m_position;
}
void Player:: setPosition(Vector3d tmp)
{
m_position=tmp;
}
double Player:: getFacing()
{
return m_facing;
}
void Player:: setFacing(double value)
{
m_facing=Utils::WrapAngle(value);
}
double Player:: getPitch()
{
return m_pitch;
}
void Player::setPitch(double value)
{
m_pitch = Utils::LimitAngle(value, -89, 89);
}
Vector3d Player:: Forwards()
{
double r = Utils::ToRadians(m_facing);
return Vector3d(-sin(r), 0, -cos(r));
}
Vector3d Player:: Sideways()
{
double r = Utils::ToRadians(m_facing);
return Vector3d(-cos(r), 0, sin(r));
} | true |
b8a3da583ed8f9c832a8675c4acf9ac2663eec94 | C++ | SaberQ/leetcode | /tests/SwapNodesInPairsTest.cpp | UTF-8 | 2,277 | 3.59375 | 4 | [] | no_license | #include "catch.hpp"
#include "SwapNodesInPairs.hpp"
TEST_CASE("Swap Nodes In Pairs") {
SwapNodesInPairs s;
ListNode* head = nullptr;
ListNode* result = nullptr;
SECTION("Sample test") {
ListNode* n = nullptr;
n = new ListNode(4); n->next = head; head = n;
n = new ListNode(3); n->next = head; head = n;
n = new ListNode(2); n->next = head; head = n;
n = new ListNode(1); n->next = head; head = n;
result = s.swapPairs(head);
n = result;
REQUIRE_FALSE(n == nullptr); REQUIRE(n->val == 2); n = n->next;
REQUIRE_FALSE(n == nullptr); REQUIRE(n->val == 1); n = n->next;
REQUIRE_FALSE(n == nullptr); REQUIRE(n->val == 4); n = n->next;
REQUIRE_FALSE(n == nullptr); REQUIRE(n->val == 3); n = n->next;
REQUIRE(n == nullptr);
}
SECTION("Empty list") {
REQUIRE(s.swapPairs(head) == nullptr);
}
SECTION("Odd items in list") {
ListNode* n = nullptr;
n = new ListNode(5); n->next = head; head = n;
n = new ListNode(4); n->next = head; head = n;
n = new ListNode(3); n->next = head; head = n;
n = new ListNode(2); n->next = head; head = n;
n = new ListNode(1); n->next = head; head = n;
result = s.swapPairs(head);
n = result;
REQUIRE_FALSE(n == nullptr); REQUIRE(n->val == 2); n = n->next;
REQUIRE_FALSE(n == nullptr); REQUIRE(n->val == 1); n = n->next;
REQUIRE_FALSE(n == nullptr); REQUIRE(n->val == 4); n = n->next;
REQUIRE_FALSE(n == nullptr); REQUIRE(n->val == 3); n = n->next;
REQUIRE_FALSE(n == nullptr); REQUIRE(n->val == 5); n = n->next;
REQUIRE(n == nullptr);
}
SECTION("Single item in list") {
ListNode* n = nullptr;
n = new ListNode(1); n->next = head; head = n;
result = s.swapPairs(head);
n = result;
REQUIRE_FALSE(n == nullptr); REQUIRE(n->val == 1); n = n->next;
REQUIRE(n == nullptr);
}
SECTION("Two items in list") {
ListNode* n = nullptr;
n = new ListNode(5); n->next = head; head = n;
n = new ListNode(4); n->next = head; head = n;
result = s.swapPairs(head);
n = result;
REQUIRE_FALSE(n == nullptr); REQUIRE(n->val == 5); n = n->next;
REQUIRE_FALSE(n == nullptr); REQUIRE(n->val == 4); n = n->next;
REQUIRE(n == nullptr);
}
list_free(result);
}
| true |
8c6b84c009f2bdad68c5aee57447095c70b919cb | C++ | sarankaarthik/CPCprep | /Week5/10.cpp | UTF-8 | 1,764 | 3.328125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <map>
using namespace std;
vector<int> freq(vector<int> nums,int target)
{
int low = 0;
int high = nums.size() - 1;
int index;
vector<int> a;
if(high < low)
{
a.push_back(-1);
a.push_back(-1);
return a;
}
while (low <= high)
{
int mid = (low + high) / 2;
if(nums[mid] < target)
low = mid + 1;
else if(nums[mid] > target)
high = mid - 1;
else if(nums[mid] == target)
{
index = mid;
break;
}
else
index = -1;
}
if(index == -1)
{
a.push_back(-1);
a.push_back(-1);
return a;
}
int l = index;
int r = index;
int flag;
while(nums[l] == target || nums[r] == target)
{
if(nums[l] == target && l > 0)
{
l--;
flag = 1;
}
if(nums[r] == target && r < nums.size() - 1)
{
r++;
flag = 1;
}
if(flag == 1)
flag = 0;
else
break;
}
if(l == 0 && nums[l] == target)
a.push_back(l);
else
a.push_back(l+1);
if(r == nums.size() - 1 && nums[r] == target)
a.push_back(r);
else
a.push_back(r-1);
return a;
}
int main()
{
vector<int> a{1,1,2,2,2,2,3,3,4};
int x;
cin>>x;
vector<int> b = freq(a,x);
cout<<b[1] - b[0] + 1<<" ";
}
| true |
781519962b336e03c2caa20bfa40a000286a93ea | C++ | constantinpape/z5 | /src/test/multiarray/test_xtutil.cxx | UTF-8 | 3,652 | 2.890625 | 3 | [
"MIT"
] | permissive | #include <random>
#include "gtest/gtest.h"
#include "z5/dataset.hxx"
#include "z5/multiarray/xtensor_util.hxx"
namespace z5 {
namespace multiarray {
TEST(XtUtilTest, TestCopyBufferToView) {
const int minDim = 2;
const int maxDim = 6;
for(int dim = minDim; dim <= maxDim; ++dim) {
std::cout << "Dimension: " << dim << std::endl;
// shape of the array, the view into the array
// and the view's offset
std::vector<int64_t> shape(dim);
std::vector<std::size_t> viewShape(dim);
std::vector<std::size_t> viewOffset(dim);
// we choose smaller shapes for d > 3, because 100^4 = 10^8
// is pretty big already (and 10^10 even worse...)
if(dim > 3) {
for(int d = 0; d < dim; ++d) {
shape[d] = (d < 2) ? 3 : 100;
// TODO random values for view shape and offset
viewShape[d] = (d < 2) ? 2 : 40;
viewOffset[d] = (d < 2) ? 1 : 20;
}
}
else {
shape = std::vector<int64_t>(dim, 100);
viewShape = std::vector<std::size_t>(dim, 40);
viewOffset = std::vector<std::size_t>(dim, 20);
}
// make the big array and view
xt::xarray<int> array = xt::zeros<int>(shape);
xt::xstrided_slice_vector slice;
sliceFromRoi(slice, viewOffset, viewShape);
auto view = xt::strided_view(array, slice);
// make 1D buffer
std::vector<int> buffer(view.size());
std::iota(buffer.begin(), buffer.end(), 0);
// copy the buffer into the array
copyBufferToViewND(buffer, view, array.strides());
// check the result
std::size_t i = 0;
for(auto viewIt = view.begin(); viewIt != view.end(); ++viewIt, ++i) {
ASSERT_EQ(*viewIt, buffer[i]);
}
}
}
TEST(XtUtilTest, TestCopyViewToBuffer) {
const int minDim = 2;
const int maxDim = 6;
for(int dim = minDim; dim <= maxDim; ++dim) {
std::cout << "Dimension: " << dim << std::endl;
// shape of the array, the view into the array
// and the view's offset
std::vector<int64_t> shape(dim);
std::vector<std::size_t> viewShape(dim);
std::vector<std::size_t> viewOffset(dim);
for(int d = 0; d < dim; ++d) {
// we choose smaller shapes for d > 3, because 100^4 = 10^8
// is prettyp big already (and 10^10 even worse...)
shape[d] = (d < 3) ? 100 : 3;
// TODO random values for view shape and offset
viewShape[d] = (d < 3) ? 40 : 2;
viewOffset[d] = (d < 3) ? 20 : 1;
}
// make the big array and view
xt::xarray<int> array = xt::zeros<int>(shape);
xt::xstrided_slice_vector slice;
sliceFromRoi(slice, viewOffset, viewShape);
auto view = xt::strided_view(array, slice);
std::iota(view.begin(), view.end(), 0);
// make 1D buffer
std::vector<int> buffer(view.size());
// copy the buffer into the array
copyViewToBufferND(view, buffer, array.strides());
// check the result
std::size_t i = 0;
for(auto viewIt = view.begin(); viewIt != view.end(); ++viewIt, ++i) {
ASSERT_EQ(*viewIt, buffer[i]);
}
}
}
}
}
| true |
7f5b424c8b739f2b509328fb41f596f81aca0507 | C++ | ArturRodriguesAguiar/Hash_List_BST_AVL | /Main.cpp | ISO-8859-1 | 673 | 2.734375 | 3 | [] | no_license | #include <bits/stdc++.h>
#include "BST.h"
#include "AVL.h"
#include "Array_Hash.h"
#include "Linked_List_Hash.h"
/*C++ tem funes HEAP nativas, mas a lgica de ambas as estruturas
(rvores Binrias e a Heap) foram elaboradas na sintaxe C99. Usei
o C++ s pra funes que usam buffer, que oferece mais praticidade.*/
int main(){
unsigned Tamanho, i;
ifstream Arquivo("Entrada.txt");
Arquivo >> Tamanho;
int Vetor[Tamanho];
for(i = 0; i < Tamanho; i++)
Arquivo >> Vetor[i];
Lancar_BST(Vetor, Tamanho);
Lancar_AVL(Vetor, Tamanho);
Lancar_Array_Hash(Vetor, Tamanho);
//Lancar_Linked_List_Hash(Vetor);
return 0;
}
| true |
230c709dc1f6833da350d750847fd184fce3d77e | C++ | kgolov/uni-data-structures | /Homeworks/HW-5/Task-3/task-3.cpp | UTF-8 | 3,558 | 3.78125 | 4 | [
"MIT"
] | permissive | #include <iostream>
#include <queue>
#include <string>
using std::queue;
using std::string;
struct Person {
string name;
int timeEntered;
int group;
Person(string name, int group, int entered) {
this->name = name;
this->group = group;
timeEntered = entered;
}
};
struct Node {
queue<Person> que;
int group;
Node* left;
Node* right;
Node(Person pers) {
group = pers.group;
que.push(pers);
left = nullptr;
right = nullptr;
}
~Node() {
delete left;
delete right;
}
void add(Person pers) {
if (pers.group == group) {
que.push(pers);
}
else if (pers.group < group) {
if (left == nullptr) {
left = new Node(pers);
}
else {
left->add(pers);
}
}
else {
if (right == nullptr) {
right = new Node(pers);
}
else {
right->add(pers);
}
}
}
Node* search(int group) {
if (this->group == group) {
return this;
}
else if (group < this->group && left != nullptr) {
return left->search(group);
}
else if (group > this->group&& right != nullptr) {
return right->search(group);
}
return nullptr;
}
};
int main() {
int currentTime = 0;
queue<int> groups;
int students;
std::cin >> students;
int maxGroup;
std::cin >> maxGroup;
string inputName;
int inputGroup;
std::cin >> inputName;
std::cin >> inputGroup;
Person input(inputName, inputGroup, currentTime);
Node* tree = new Node(input);
groups.push(inputGroup);
string output = "";
for (int i = 1; i < students; i++) {
currentTime++;
std::cin >> inputName;
std::cin >> inputGroup;
input = Person(inputName, inputGroup, currentTime);
Node* searched = tree->search(inputGroup);
if (!searched || searched->que.empty()) {
// Add group to queue
groups.push(inputGroup);
}
tree->add(input);
if (currentTime % 2 == 0) {
int nextGroup = groups.front();
Node* next = tree->search(nextGroup);
Person toDequeue = next->que.front();
output += toDequeue.name;
output += " ";
output += std::to_string(toDequeue.timeEntered);
output += " ";
output += std::to_string(currentTime);
output += "\n";
next->que.pop();
if (next->que.empty()) {
groups.pop();
}
}
}
while (!groups.empty()) {
currentTime++;
if (currentTime % 2 == 0) {
int nextGroup = groups.front();
Node* next = tree->search(nextGroup);
Person toDequeue = next->que.front();
output += toDequeue.name;
output += " ";
output += std::to_string(toDequeue.timeEntered);
output += " ";
output += std::to_string(currentTime);
output += "\n";
next->que.pop();
if (next->que.empty()) {
groups.pop();
}
}
}
std::cout << output;
return 0;
}
| true |