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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
adfc06a2934bd4e60e466c3c2dcbdf56ddec8396 | C++ | guptavarun619/Data-Structure | /Array/SumSubMatric2.cpp | UTF-8 | 1,885 | 3.359375 | 3 | [] | no_license | #include<iostream>
#include<climits>
using namespace std;
int main()
{
// prefix sum matrix approach
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
#endif
int row, col, tempSum = 0, maxSum = INT_MIN;
cin >> row >> col;
int a[row][col];
// Input
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
cin >> a[i][j];
}
}
// Precalculated sum array
for (int i = 0; i < col; i++)
{
int temp = 0;
for (int j = 0; j < row; j++)
{
temp += a[j][i];
a[j][i] = temp;
}
}
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
cout << a[i][j] << " ";
}
cout << endl;
}
for (int i = 0; i < row; i++)
{
int temp = 0;
for (int j = 0; j < col; j++)
{
temp += a[i][j];
a[i][j] = temp;
}
}
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
cout << a[i][j] << " ";
}
cout << endl;
}
// maxSum using pre sum array
for (int tx = 0; tx < row; tx++)
{
for (int ty = 0; ty < col; ty++)
{
for (int bx = tx; bx < row; bx++)
{ tempSum = 0;
for (int by = ty; by < col; by++)
{
tempSum = a[bx][by];
if(tx > 0)
tempSum -= a[tx - 1][by];
if(ty > 0)
tempSum -= a[bx][ty - 1];
if(tx > 0 && ty > 0)
tempSum += a[tx - 1][ty - 1];
maxSum = max(maxSum, tempSum);
}
}
}
}
cout << "Maximum sum is : " << maxSum;
return 0;
} | true |
0184cdd2a0a81d4fc2727c7f49d651579515eace | C++ | luckcul/LeetCode | /algorithms/Construct Binary Tree from Inorder and Postorder Traversal/Construct Binary Tree from Inorder and Postorder Traversal.cpp | UTF-8 | 1,076 | 3.21875 | 3 | [] | no_license | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
int in_length = inorder.size();
int post_length = postorder.size();
return sol(inorder, postorder, 0, in_length, 0, post_length);
}
TreeNode* sol(vector<int>& inorder, vector<int>& postorder, int in_s, int in_e, int post_s, int post_e) {
if(in_s >= in_e) return NULL;
int root_val = postorder[post_e-1];
TreeNode *root = new TreeNode(root_val);
int index = -1;
for(int i = in_s; i < in_e; i++) {
if(inorder[i] == root_val) {
index = i; break;
}
}
root->left = sol(inorder, postorder, in_s, index, post_s, post_s + (index-in_s));
root->right = sol(inorder, postorder, index+1, in_e, post_s + (index-in_s), post_e-1);
return root;
}
}; | true |
c3519668965a1bca0e92fd8b81e80e97ee42a23d | C++ | tinypie/algorithms | /string_connect_order.cc | UTF-8 | 1,141 | 3.703125 | 4 | [] | no_license | /*
* 字符串的连接顺序
*
* "abdbcca"
* "abc"
* 第二个在第一个中的连接顺序为
* 125, 126,145,146.
*
* 用递归方法
*/
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
void print_array(char *p, int p_len,
char *s, int s_len,
int *array, int n,
int p_start, int s_start)
{
int tn, tp, ts;
tn = n;
tp = p_start;
ts = s_start;
if (n == s_len) {
for (int i = 0; i < s_len; i++) {
cout << *(array + i);
}
cout << endl;
return;
}
for (int i = tp; i < p_len; i++) {
for (int j = ts; j < s_len; j++) {
if (*(p+i) == *(s+j)) {
array[tn] = i+1;
tp = i;
ts = j;
print_array(p, p_len, s, s_len,
array, tn+1, tp+1, ts+1);
}
}
}
}
void shun(char *p, char *s)
{
int p_len = strlen(p);
int s_len = strlen(s);
int *array = new int[s_len];
if (p == NULL || s == NULL) {
cout<<"string error"<<endl;
}
if (array == NULL) {
cout << "allocate error" << endl;
}
print_array(p, p_len, s, s_len, array, 0, 0, 0);
delete array;
}
int main()
{
char p[] = "abdbcca";
char s[] = "abc";
shun(p, s);
return 0;
}
| true |
6cd3a9d6c04809175b1aec095da80d88efecbf23 | C++ | adamMaor/myProject | /myProject/main.cpp | UTF-8 | 258 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
int add(int x, int y);
int main()
{
int pause;
string str = "Hello World";
cout << str << " " << add(5,7) << endl;
cin >> pause;
return 0;
}
int add(int x, int y)
{
return x + y;
}
| true |
14e63bd83c8aadc5a3bd8edbf5854d01a7fd0e4a | C++ | KLatitude/SNL_Complier | /SNL/Syntax_Analysis/Cpp/syn_analysis.cpp | UTF-8 | 40,871 | 2.546875 | 3 | [] | no_license | #include "../Head/syn_analysis.h"
#include<string>
#include<iostream>
using namespace std;
bool SynAnalysis::isError() {
return error_;
}
void SynAnalysis::printNode(TreeNode* root, int k) {
for (int i = 1; i <= k; i++)
cout<<"\t";
if (root->node_kind_ == ProK) {
cout<<"ProK"<<endl;
return;
}
if (root->node_kind_ == PheadK) {
cout<<"PheadK "<<root->name_[0]<<endl;
return;
}
if (root->node_kind_ == TypeK) {
cout<<"TypeK"<<endl;
return;
}
if (root->node_kind_ == VarK) {
cout<<"VarK"<<endl;
return;
}
if (root->node_kind_ == ProcDecK) {
cout<<"ProcDecK"<<endl;
return;
}
if (root->node_kind_ == StmLK) {
cout<<"StmLK"<<endl;
return;
}
if (root->node_kind_ == DecK) {
cout<<"DecK ";
if (root->attr_.proc_attr.paramt != NoVal) {
switch ((int)root->attr_.proc_attr.paramt) {
case valparamtype: cout<<"valparamtype: "; break;
case varparamtype: cout<<"varparamtype: "; break;
}
}
if (root->kind_ == IntegerK) {
cout<<"IntegerK";
for (int i = 0; i < root->idnum_; i++)
cout<<" "<<root->name_[i];
cout<<endl;
return;
}
if (root->kind_ == CharK) {
cout<<"CharK";
for (int i = 0; i < root->idnum_; i++)
cout<<" "<<root->name_[i];
cout<<endl;
return;
}
if (root->kind_ == ArrayK) {
cout<<"ArrayK ";
cout<<root->attr_.array_attr.low<<" "<<root->attr_.array_attr.up<<" ";
switch((int)root->attr_.array_attr.child_type) {
case IntegerK: cout<<"IntegerK"<<endl; break;
case CharK: cout<<"CharK"<<endl; break;
}
return;
}
if (root->kind_ == RecordK) {
cout<<"RecordK"<<endl;
return;
}
if (root->kind_ == IdK) {
cout<<"IdK "<<root->type_name_;
for (int i = 0; i < root->idnum_; i++)
cout<<" "<<root->name_[i];
cout<<endl;
return;
}
}
if (root->node_kind_ == StmtK) {
cout<<"StmtK ";
switch ((int)(root->kind_)) {
case IfK: cout<<"IfK"<<endl; break;
case WhileK: cout<<"WhileK"<<endl; break;
case AssignK: cout<<"AssignK"<<endl; break;
case ReadK: cout<<"ReadK "<<root->name_[0]<<endl; break;
case WriteK: cout<<"WriteK"<<endl; break;
case CallK: cout<<"CallK"<<endl; break;
case ReturnK: cout<<"ReturnK"<<endl; break;
}
}
if (root->node_kind_ == ExpK) {
cout<<"ExpK ";
if (root->kind_ == OpK) {
cout<<"OpK ";
switch((int)root->attr_.exp_attr.op) {
case LT: cout<<"<"<<endl; break;
case EQ: cout<<"="<<endl; break;
case ADD: cout<<"+"<<endl; break;
case MINUS: cout<<"-"<<endl; break;
case TIMES: cout<<"*"<<endl; break;
case DIV: cout<<"/"<<endl; break;
}
return;
}
if (root->kind_ == ConstK) {
cout<<"ConstK "<<root->attr_.exp_attr.val<<endl;
return;
}
if (root->kind_ == VariK) {
cout<<"VariK "<<root->name_[0]<<" ";
switch ((int)root->attr_.exp_attr.var_kind) {
case IdV: cout<<"IdV"<<endl; break;
case ArrayMembV: cout<<"ArrayMembV"<<endl; break;
case FieldMembV: cout<<"FieldMembV"<<endl; break;
}
}
}
}
void SynAnalysis::dfs(TreeNode* root, int k) {
if (root == NULL)
return;
printNode(root, k);
for (int i = 0; i < (int)root->child_.size(); i++)
dfs(root->child_[i], k + 1);
dfs(root->sibling_, k);
return;
}
void SynAnalysis::printTree() {
dfs(root, 0);
}
int SynAnalysis::getFromStr(string str) {
int sum = 0;
for (int i = 0; i < (int)str.length(); i++)
sum = sum * 10 + (int)(str[i] - '0');
return sum;
}
TreeNode* SynAnalysis::parse() {
createLL1Table();
symbol_.push(Program);
root = new TreeNode();
root->node_kind_ = ProK;
for (int i = 2; i >= 0; i--)
syn_tree_.push(&(root->child_[i]));
while (!symbol_.empty()) {
int top = symbol_.top();
symbol_.pop();
if (top == token_list_[now_]->lex_) {
now_++;
} else {
int pnum = LL1_table_[top][token_list_[now_]->lex_];
if (pnum > 0)
predict(pnum);
else {
//cout<<top<<endl;
cout<<"Error: In: "<<token_list_[now_]->line_<<endl;
if (token_list_[now_]->lex_ != ENDFILE)
cout<<"\tNo: "<<token_list_[now_]->sem_<<endl;
else
cout<<"\tNo: ENDFILE"<<endl;
cout<<"\tPossible Except:";
if (top < 42)
cout<<" "<<getLexType((LexType)top);
for (int i = 0; i < (int)LL1_table_[0].size(); i++) {
if (LL1_table_[top][i] != 0)
cout<<" "<<getLexType((LexType)i);
}
cout<<endl;
error_ = true;
}
}
}
if (token_list_[now_]->lex_ != ENDFILE)
throw exception();
return root;
}
void SynAnalysis::createLL1Table() {
LL1_table_[Program][PROGRAM] = 1;
LL1_table_[ProgramHead][PROGRAM] = 2;
LL1_table_[ProgramName][ID] = 3;
LL1_table_[DeclarePart][TYPE] = 4;
LL1_table_[DeclarePart][VAR] = 4;
LL1_table_[DeclarePart][PROCEDURE] = 4;
LL1_table_[DeclarePart][BEGIN] = 4;
LL1_table_[TypeDecpart][VAR] = 5;
LL1_table_[TypeDecpart][PROCEDURE] = 5;
LL1_table_[TypeDecpart][BEGIN] = 5;
LL1_table_[TypeDecpart][TYPE] = 6;
LL1_table_[TypeDec][TYPE] = 7;
LL1_table_[TypeDecList][ID] = 8;
LL1_table_[TypeDecMore][VAR] = 9;
LL1_table_[TypeDecMore][PROCEDURE] = 9;
LL1_table_[TypeDecMore][BEGIN] = 9;
LL1_table_[TypeDecMore][ID] = 10;
LL1_table_[TypeId][ID] = 11;
LL1_table_[TypeDef][INTEGER] = 12;
LL1_table_[TypeDef][CHAR] = 12;
LL1_table_[TypeDef][ARRAY] = 13;
LL1_table_[TypeDef][RECORD] = 13;
LL1_table_[TypeDef][ID] = 14;
LL1_table_[BaseType][INTEGER] = 15;
LL1_table_[BaseType][CHAR] = 16;
LL1_table_[StructureType][ARRAY] = 17;
LL1_table_[StructureType][RECORD] = 18;
LL1_table_[ArrayType][ARRAY] = 19;
LL1_table_[Low][INTC] = 20;
LL1_table_[Top][INTC] = 21;
LL1_table_[RecType][RECORD] = 22;
LL1_table_[FieldDecList][INTEGER] = 23;
LL1_table_[FieldDecList][CHAR] = 23;
LL1_table_[FieldDecList][ARRAY] = 24;
LL1_table_[FieldDecMore][END] = 25;
LL1_table_[FieldDecMore][INTEGER] = 26;
LL1_table_[FieldDecMore][CHAR] = 26;
LL1_table_[FieldDecMore][ARRAY] = 26;
LL1_table_[IdList][ID] = 27;
LL1_table_[IdMore][SEMI] = 28;
LL1_table_[IdMore][COMMA] = 29;
LL1_table_[VarDecpart][PROCEDURE] = 30;
LL1_table_[VarDecpart][BEGIN] = 30;
LL1_table_[VarDecpart][VAR] = 31;
LL1_table_[VarDec][VAR] = 32;
LL1_table_[VarDecList][INTEGER] = 33;
LL1_table_[VarDecList][CHAR] = 33;
LL1_table_[VarDecList][ARRAY] = 33;
LL1_table_[VarDecList][RECORD] = 33;
LL1_table_[VarDecList][ID] = 33;
LL1_table_[VarDecMore][PROCEDURE] = 34;
LL1_table_[VarDecMore][BEGIN] = 34;
LL1_table_[VarDecMore][INTEGER] = 35;
LL1_table_[VarDecMore][CHAR] = 35;
LL1_table_[VarDecMore][ARRAY] = 35;
LL1_table_[VarDecMore][RECORD] = 35;
LL1_table_[VarDecMore][ID] = 35;
LL1_table_[VarIdList][ID] = 36;
LL1_table_[VarIdMore][SEMI] = 37;
LL1_table_[VarIdMore][COMMA] = 38;
LL1_table_[ProcDecpart][BEGIN] = 39;
LL1_table_[ProcDecpart][PROCEDURE] = 40;
LL1_table_[ProcDec][PROCEDURE] = 41;
LL1_table_[ProcDecMore][BEGIN] = 42;
LL1_table_[ProcDecMore][PROCEDURE] = 43;
LL1_table_[ProcName][ID] = 44;
LL1_table_[ParamList][RPAREN] = 45;
LL1_table_[ParamList][INTEGER] = 46;
LL1_table_[ParamList][CHAR] = 46;
LL1_table_[ParamList][ARRAY] = 46;
LL1_table_[ParamList][RECORD] = 46;
LL1_table_[ParamList][ID] = 46;
LL1_table_[ParamList][VAR] = 46;
LL1_table_[ParamDecList][INTEGER] = 47;
LL1_table_[ParamDecList][CHAR] = 47;
LL1_table_[ParamDecList][ARRAY] = 47;
LL1_table_[ParamDecList][RECORD] = 47;
LL1_table_[ParamDecList][ID] = 47;
LL1_table_[ParamDecList][VAR] = 47;
LL1_table_[ParamMore][RPAREN] = 48;
LL1_table_[ParamMore][SEMI] = 49;
LL1_table_[Param][INTEGER] = 50;
LL1_table_[Param][CHAR] = 50;
LL1_table_[Param][ARRAY] = 50;
LL1_table_[Param][RECORD] = 50;
LL1_table_[Param][ID] = 50;
LL1_table_[Param][VAR] = 51;
LL1_table_[FormList][ID] = 52;
LL1_table_[FidMore][SEMI] = 53;
LL1_table_[FidMore][RPAREN] = 53;
LL1_table_[FidMore][COMMA] = 54;
LL1_table_[ProcDecPart][TYPE] = 55;
LL1_table_[ProcDecPart][VAR] = 55;
LL1_table_[ProcDecPart][PROCEDURE] = 55;
LL1_table_[ProcDecPart][BEGIN] = 55;
LL1_table_[ProcBody][BEGIN] = 56;
LL1_table_[ProgramBody][BEGIN] = 57;
LL1_table_[StmList][ID] = 58;
LL1_table_[StmList][IF] = 58;
LL1_table_[StmList][WHILE] = 58;
LL1_table_[StmList][RETURN] = 58;
LL1_table_[StmList][READ] = 58;
LL1_table_[StmList][WRITE] = 58;
LL1_table_[StmMore][ELSE] = 59;
LL1_table_[StmMore][FI] = 59;
LL1_table_[StmMore][END] = 59;
LL1_table_[StmMore][ENDWH] = 59;
LL1_table_[StmMore][SEMI] = 60;
LL1_table_[Stm][IF] = 61;
LL1_table_[Stm][WHILE] = 62;
LL1_table_[Stm][READ] = 63;
LL1_table_[Stm][WRITE] = 64;
LL1_table_[Stm][RETURN] = 65;
LL1_table_[Stm][ID] = 66;
LL1_table_[AssCall][LMIDPAREN] = 67;
LL1_table_[AssCall][DOT] = 67;
LL1_table_[AssCall][ASSIGN] = 67;
LL1_table_[AssCall][LPAREN] = 68;
LL1_table_[AssignmentRest][LMIDPAREN] = 69;
LL1_table_[AssignmentRest][DOT] = 69;
LL1_table_[AssignmentRest][ASSIGN] = 69;
LL1_table_[ConditionalStm][IF] = 70;
LL1_table_[LoopStm][WHILE] = 71;
LL1_table_[InputStm][READ] = 72;
LL1_table_[Invar][ID] = 73;
LL1_table_[OutputStm][WRITE] = 74;
LL1_table_[ReturnStm][RETURN] = 75;
LL1_table_[CallStmRest][LPAREN] = 76;
LL1_table_[ActParamList][RPAREN] = 77;
LL1_table_[ActParamList][LPAREN] = 78;
LL1_table_[ActParamList][INTC] = 78;
LL1_table_[ActParamList][ID] = 78;
LL1_table_[ActParamMore][RPAREN] = 79;
LL1_table_[ActParamMore][COMMA] = 80;
LL1_table_[RelExp][LPAREN] = 81;
LL1_table_[RelExp][INTC] = 81;
LL1_table_[RelExp][ID] = 81;
LL1_table_[OtherRelE][LT] = 82;
LL1_table_[OtherRelE][EQ] = 82;
LL1_table_[Exp][LPAREN] = 83;
LL1_table_[Exp][INTC] = 83;
LL1_table_[Exp][ID] = 83;
LL1_table_[OtherTerm][LT] = 84;
LL1_table_[OtherTerm][EQ] = 84;
LL1_table_[OtherTerm][RMIDPAREN] = 84;
LL1_table_[OtherTerm][THEN] = 84;
LL1_table_[OtherTerm][ELSE] = 84;
LL1_table_[OtherTerm][FI] = 84;
LL1_table_[OtherTerm][DO] = 84;
LL1_table_[OtherTerm][ENDWH] = 84;
LL1_table_[OtherTerm][RPAREN] = 84;
LL1_table_[OtherTerm][END] = 84;
LL1_table_[OtherTerm][SEMI] = 84;
LL1_table_[OtherTerm][COMMA] = 84;
LL1_table_[OtherTerm][ADD] = 85;
LL1_table_[OtherTerm][MINUS] = 85;
LL1_table_[Term][LPAREN] = 86;
LL1_table_[Term][INTC] = 86;
LL1_table_[Term][ID] = 86;
LL1_table_[OtherFactor][ADD] = 87;
LL1_table_[OtherFactor][MINUS] = 87;
LL1_table_[OtherFactor][LT] = 87;
LL1_table_[OtherFactor][EQ] = 87;
LL1_table_[OtherFactor][RMIDPAREN] = 87;
LL1_table_[OtherFactor][THEN] = 87;
LL1_table_[OtherFactor][ELSE] = 87;
LL1_table_[OtherFactor][FI] = 87;
LL1_table_[OtherFactor][DO] = 87;
LL1_table_[OtherFactor][ENDWH] = 87;
LL1_table_[OtherFactor][RPAREN] = 87;
LL1_table_[OtherFactor][END] = 87;
LL1_table_[OtherFactor][SEMI] = 87;
LL1_table_[OtherFactor][COMMA] = 87;
LL1_table_[OtherFactor][TIMES] = 88;
LL1_table_[OtherFactor][DIV] = 88;
LL1_table_[Factor][LPAREN] = 89;
LL1_table_[Factor][INTC] = 90;
LL1_table_[Factor][ID] = 91;
LL1_table_[Variable][ID] = 92;
LL1_table_[VariMore][ASSIGN] = 93;
LL1_table_[VariMore][TIMES] = 93;
LL1_table_[VariMore][DIV] = 93;
LL1_table_[VariMore][ADD] = 93;
LL1_table_[VariMore][MINUS] = 93;
LL1_table_[VariMore][LT] = 93;
LL1_table_[VariMore][EQ] = 93;
LL1_table_[VariMore][RMIDPAREN] = 93;
LL1_table_[VariMore][THEN] = 93;
LL1_table_[VariMore][ELSE] = 93;
LL1_table_[VariMore][FI] = 93;
LL1_table_[VariMore][DO] = 93;
LL1_table_[VariMore][ENDWH] = 93;
LL1_table_[VariMore][RPAREN] = 93;
LL1_table_[VariMore][END] = 93;
LL1_table_[VariMore][SEMI] = 93;
LL1_table_[VariMore][COMMA] = 93;
LL1_table_[VariMore][LMIDPAREN] = 94;
LL1_table_[VariMore][DOT] = 95;
LL1_table_[FieldVar][ID] = 96;
LL1_table_[FieldVarMore][ASSIGN] = 97;
LL1_table_[FieldVarMore][TIMES] = 97;
LL1_table_[FieldVarMore][DIV] = 97;
LL1_table_[FieldVarMore][ADD] = 97;
LL1_table_[FieldVarMore][MINUS] = 97;
LL1_table_[FieldVarMore][LT] = 97;
LL1_table_[FieldVarMore][EQ] = 97;
LL1_table_[FieldVarMore][RMIDPAREN] = 97;
LL1_table_[FieldVarMore][THEN] = 97;
LL1_table_[FieldVarMore][ELSE] = 97;
LL1_table_[FieldVarMore][FI] = 97;
LL1_table_[FieldVarMore][DO] = 97;
LL1_table_[FieldVarMore][ENDWH] = 97;
LL1_table_[FieldVarMore][RPAREN] = 97;
LL1_table_[FieldVarMore][END] = 97;
LL1_table_[FieldVarMore][SEMI] = 97;
LL1_table_[FieldVarMore][COMMA] = 97;
LL1_table_[FieldVarMore][LMIDPAREN] = 98;
LL1_table_[CmpOp][LT] = 99;
LL1_table_[CmpOp][EQ] = 100;
LL1_table_[AddOp][ADD] = 101;
LL1_table_[AddOp][MINUS] = 102;
LL1_table_[MultOp][TIMES] = 103;
LL1_table_[MultOp][DIV] = 104;
}
int SynAnalysis::priosity(LexType op) { //parameter is string? (unknown)
if (op == TIMES || op == DIV)
return 3;
if (op == ADD || op == MINUS)
return 2;
if (op == LT || op == EQ)
return 1;
if (op == END || op == LPAREN) //add (op == LPAREN)
return 0;
return -1;
}
void SynAnalysis::predict(int num) {
switch(num) {
case 1: process1(); break;
case 2: process2(); break;
case 3: process3(); break;
case 4: process4(); break;
case 5: process5(); break;
case 6: process6(); break;
case 7: process7(); break;
case 8: process8(); break;
case 9: process9(); break;
case 10: process10(); break;
case 11: process11(); break;
case 12: process12(); break;
case 13: process13(); break;
case 14: process14(); break;
case 15: process15(); break;
case 16: process16(); break;
case 17: process17(); break;
case 18: process18(); break;
case 19: process19(); break;
case 20: process20(); break;
case 21: process21(); break;
case 22: process22(); break;
case 23: process23(); break;
case 24: process24(); break;
case 25: process25(); break;
case 26: process26(); break;
case 27: process27(); break;
case 28: process28(); break;
case 29: process29(); break;
case 30: process30(); break;
case 31: process31(); break;
case 32: process32(); break;
case 33: process33(); break;
case 34: process34(); break;
case 35: process35(); break;
case 36: process36(); break;
case 37: process37(); break;
case 38: process38(); break;
case 39: process39(); break;
case 40: process40(); break;
case 41: process41(); break;
case 42: process42(); break;
case 43: process43(); break;
case 44: process44(); break;
case 45: process45(); break;
case 46: process46(); break;
case 47: process47(); break;
case 48: process48(); break;
case 49: process49(); break;
case 50: process50(); break;
case 51: process51(); break;
case 52: process52(); break;
case 53: process53(); break;
case 54: process54(); break;
case 55: process55(); break;
case 56: process56(); break;
case 57: process57(); break;
case 58: process58(); break;
case 59: process59(); break;
case 60: process60(); break;
case 61: process61(); break;
case 62: process62(); break;
case 63: process63(); break;
case 64: process64(); break;
case 65: process65(); break;
case 66: process66(); break;
case 67: process67(); break;
case 68: process68(); break;
case 69: process69(); break;
case 70: process70(); break;
case 71: process71(); break;
case 72: process72(); break;
case 73: process73(); break;
case 74: process74(); break;
case 75: process75(); break;
case 76: process76(); break;
case 77: process77(); break;
case 78: process78(); break;
case 79: process79(); break;
case 80: process80(); break;
case 81: process81(); break;
case 82: process82(); break;
case 83: process83(); break;
case 84: process84(); break;
case 85: process85(); break;
case 86: process86(); break;
case 87: process87(); break;
case 88: process88(); break;
case 89: process89(); break;
case 90: process90(); break;
case 91: process91(); break;
case 92: process92(); break;
case 93: process93(); break;
case 94: process94(); break;
case 95: process95(); break;
case 96: process96(); break;
case 97: process97(); break;
case 98: process98(); break;
case 99: process99(); break;
case 100: process100(); break;
case 101: process101(); break;
case 102: process102(); break;
case 103: process103(); break;
case 104: process104(); break;
default: break;
}
}
void SynAnalysis::process1() {
symbol_.push(DOT);
symbol_.push(ProgramBody);
symbol_.push(DeclarePart);
symbol_.push(ProgramHead);
return;
}
void SynAnalysis::process2() {
symbol_.push(ProgramName);
symbol_.push(PROGRAM);
currentP = new TreeNode();
currentP->node_kind_ = PheadK;
currentP->lineno_ = token_list_[now_]->line_;
TreeNode** t = syn_tree_.top();
syn_tree_.pop();
*t = currentP;
return;
}
void SynAnalysis::process3() {
symbol_.push(ID);
currentP->idnum_++;
currentP->name_.push_back(token_list_[now_]->sem_);
return;
}
void SynAnalysis::process4() {
symbol_.push(ProcDecpart);
symbol_.push(VarDecpart);
symbol_.push(TypeDecpart);
return;
}
void SynAnalysis::process5() {
return;
}
void SynAnalysis::process6() {
symbol_.push(TypeDec);
return;
}
void SynAnalysis::process7() {
symbol_.push(TypeDecList);
symbol_.push(TYPE);
currentP = new TreeNode();
currentP->node_kind_ = TypeK;
currentP->lineno_ = token_list_[now_]->line_;
TreeNode** t = syn_tree_.top();
syn_tree_.pop();
*t = currentP;
syn_tree_.push(&(currentP->sibling_));
//currentP->child_.push_back(NULL);
syn_tree_.push(&(currentP->child_[0]));
return;
}
void SynAnalysis::process8() {
symbol_.push(TypeDecMore);
symbol_.push(SEMI);
symbol_.push(TypeDef);
symbol_.push(EQ);
symbol_.push(TypeId);
currentP = new TreeNode();
currentP->node_kind_ = DecK;
currentP->lineno_ = token_list_[now_]->line_;
TreeNode** t = syn_tree_.top();
syn_tree_.pop();
*t = currentP;
syn_tree_.push(&(currentP->sibling_));
return;
}
void SynAnalysis::process9() {
syn_tree_.pop();
return;
}
void SynAnalysis::process10() {
symbol_.push(TypeDecList);
return;
}
void SynAnalysis::process11() {
symbol_.push(ID);
currentP->name_.push_back(token_list_[now_]->sem_);
currentP->idnum_++;
return;
}
void SynAnalysis::process12() {
symbol_.push(BaseType);
temp = &(currentP->kind_);
return;
}
void SynAnalysis::process13() {
symbol_.push(StructureType);
return;
}
void SynAnalysis::process14() {
symbol_.push(ID);
currentP->kind_ = IdK;
currentP->type_name_ = token_list_[now_]->sem_;
return;
}
void SynAnalysis::process15() {
symbol_.push(INTEGER);
*temp = IntegerK;
temp = NULL;
return;
}
void SynAnalysis::process16() {
symbol_.push(CHAR);
*temp = CharK;
temp = NULL;
return;
}
void SynAnalysis::process17() {
symbol_.push(ArrayType);
return;
}
void SynAnalysis::process18() {
symbol_.push(RecType);
return;
}
void SynAnalysis::process19() {
symbol_.push(BaseType);
symbol_.push(OF);
symbol_.push(RMIDPAREN);
symbol_.push(Top);
symbol_.push(UNDERANGE);
symbol_.push(Low);
symbol_.push(LMIDPAREN);
symbol_.push(ARRAY);
currentP->kind_ = ArrayK;
temp = &(currentP->attr_.array_attr.child_type);
return;
}
void SynAnalysis::process20() {
symbol_.push(INTC);
currentP->attr_.array_attr.low = getFromStr(token_list_[now_]->sem_);
return;
}
void SynAnalysis::process21() {
symbol_.push(INTC);
currentP->attr_.array_attr.up = getFromStr(token_list_[now_]->sem_);
return;
}
void SynAnalysis::process22() {
symbol_.push(END);
symbol_.push(FieldDecList);
symbol_.push(RECORD);
currentP->kind_ = RecordK;
saveP = currentP;
//currentP->child_.push_back(NULL);
syn_tree_.push(&(currentP->child_[0]));
return;
}
void SynAnalysis::process23() {
symbol_.push(FieldDecMore);
symbol_.push(SEMI);
symbol_.push(IdList);
symbol_.push(BaseType);
currentP = new TreeNode();
currentP->node_kind_ = DecK;
currentP->lineno_ = token_list_[now_]->line_;
TreeNode** t = syn_tree_.top();
syn_tree_.pop();
*t = currentP;
temp = &(currentP->kind_);
syn_tree_.push(&(currentP->sibling_));
return;
}
void SynAnalysis::process24() {
symbol_.push(FieldDecMore);
symbol_.push(SEMI);
symbol_.push(IdList);
symbol_.push(ArrayType);
currentP = new TreeNode();
currentP->node_kind_ = DecK;
currentP->lineno_ = token_list_[now_]->line_;
TreeNode** t = syn_tree_.top();
syn_tree_.pop();
*t = currentP;
syn_tree_.push(&(currentP->sibling_));
return;
}
void SynAnalysis::process25() {
syn_tree_.pop();
currentP = saveP;
return;
}
void SynAnalysis::process26() {
symbol_.push(FieldDecList);
return;
}
void SynAnalysis::process27() {
symbol_.push(IdMore);
symbol_.push(ID);
currentP->idnum_++;
currentP->name_.push_back(token_list_[now_]->sem_);
return;
}
void SynAnalysis::process28() {
return;
}
void SynAnalysis::process29() {
symbol_.push(IdList);
symbol_.push(COMMA);
return;
}
void SynAnalysis::process30() {
return;
}
void SynAnalysis::process31() {
symbol_.push(VarDec);
return;
}
void SynAnalysis::process32() {
symbol_.push(VarDecList);
symbol_.push(VAR);
currentP = new TreeNode();
currentP->node_kind_ = VarK;
currentP->lineno_ = token_list_[now_]->line_;
TreeNode** t = syn_tree_.top();
syn_tree_.pop();
*t = currentP;
syn_tree_.push(&(currentP->sibling_));
//currentP->child_.push_back(NULL);
syn_tree_.push(&(currentP->child_[0]));
return;
}
void SynAnalysis::process33() {
symbol_.push(VarDecMore);
symbol_.push(SEMI);
symbol_.push(VarIdList);
symbol_.push(TypeDef);
currentP = new TreeNode();
currentP->node_kind_ = DecK;
currentP->lineno_ = token_list_[now_]->line_;
TreeNode** t = syn_tree_.top();
syn_tree_.pop();
*t = currentP;
syn_tree_.push(&(currentP->sibling_));
return;
}
void SynAnalysis::process34() {
syn_tree_.pop();
return;
}
void SynAnalysis::process35() {
symbol_.push(VarDecList);
return;
}
void SynAnalysis::process36() {
symbol_.push(VarIdMore);
symbol_.push(ID);
currentP->idnum_++;
currentP->name_.push_back(token_list_[now_]->sem_);
return;
}
void SynAnalysis::process37() {
return;
}
void SynAnalysis::process38() {
symbol_.push(VarIdList);
symbol_.push(COMMA);
return;
}
void SynAnalysis::process39() {
//syn_tree_.pop(); //my add
return;
}
void SynAnalysis::process40() {
symbol_.push(ProcDec);
return;
}
void SynAnalysis::process41() {
symbol_.push(ProcDecMore);
symbol_.push(ProcBody);
symbol_.push(ProcDecPart);
symbol_.push(SEMI);
symbol_.push(RPAREN);
symbol_.push(ParamList);
symbol_.push(LPAREN);
symbol_.push(ProcName);
symbol_.push(PROCEDURE);
currentP = new TreeNode();
currentP->node_kind_ = ProcDecK;
currentP->lineno_ = token_list_[now_]->line_;
TreeNode** t = syn_tree_.top();
syn_tree_.pop();
*t = currentP;
syn_tree_.push(&(currentP->sibling_));
// for (int i = 0; i < 3; i++)
// currentP->child_.push_back(NULL);
for (int i = 2; i >= 0; i--)
syn_tree_.push(&(currentP->child_[i]));
return;
}
void SynAnalysis::process42() {
//syn_tree_.pop(); //my add
return;
}
void SynAnalysis::process43() {
symbol_.push(ProcDec);
return;
}
void SynAnalysis::process44() {
symbol_.push(ID);
currentP->idnum_++;
currentP->name_.push_back(token_list_[now_]->sem_);
return;
}
void SynAnalysis::process45() {
syn_tree_.pop();
return;
}
void SynAnalysis::process46() {
symbol_.push(ParamDecList);
return;
}
void SynAnalysis::process47() {
symbol_.push(ParamMore);
symbol_.push(Param);
return;
}
void SynAnalysis::process48() {
syn_tree_.pop(); //my modify
return;
}
void SynAnalysis::process49() {
symbol_.push(ParamDecList);
symbol_.push(SEMI);
return;
}
void SynAnalysis::process50() {
symbol_.push(FormList);
symbol_.push(TypeDef);
currentP = new TreeNode();
currentP->node_kind_ = DecK;
currentP->lineno_ = token_list_[now_]->line_;
currentP->attr_.proc_attr.paramt = valparamtype;
TreeNode** t = syn_tree_.top();
syn_tree_.pop();
*t = currentP;
syn_tree_.push(&(currentP->sibling_));
return;
}
void SynAnalysis::process51() {
symbol_.push(FormList);
symbol_.push(TypeDef);
symbol_.push(VAR);
currentP = new TreeNode();
currentP->node_kind_ = DecK;
currentP->lineno_ = token_list_[now_]->line_;
currentP->attr_.proc_attr.paramt = varparamtype;
TreeNode** t = syn_tree_.top();
syn_tree_.pop();
*t = currentP;
syn_tree_.push(&(currentP->sibling_));
return;
}
void SynAnalysis::process52() {
symbol_.push(FidMore);
symbol_.push(ID);
currentP->name_.push_back(token_list_[now_]->sem_);
currentP->idnum_++;
return;
}
void SynAnalysis::process53() {
return;
}
void SynAnalysis::process54() {
symbol_.push(FormList);
symbol_.push(COMMA);
return;
}
void SynAnalysis::process55() {
symbol_.push(DeclarePart);
return;
}
void SynAnalysis::process56() {
symbol_.push(ProgramBody);
return;
}
void SynAnalysis::process57() {
symbol_.push(END);
symbol_.push(StmList);
symbol_.push(BEGIN);
syn_tree_.pop();
currentP = new TreeNode();
currentP->node_kind_ = StmLK;
currentP->lineno_ = token_list_[now_]->line_;
TreeNode** t = syn_tree_.top();
syn_tree_.pop();
*t = currentP;
// currentP->child_.push_back(NULL);
syn_tree_.push(&(currentP->child_[0]));
return;
}
void SynAnalysis::process58() {
symbol_.push(StmMore);
symbol_.push(Stm);
return;
}
void SynAnalysis::process59() {
syn_tree_.pop();
return;
}
void SynAnalysis::process60() {
symbol_.push(StmList);
symbol_.push(SEMI);
return;
}
void SynAnalysis::process61() {
symbol_.push(ConditionalStm);
currentP = new TreeNode();
currentP->lineno_ = token_list_[now_]->line_;
currentP->node_kind_ = StmtK;
currentP->kind_ = IfK;
TreeNode** t = syn_tree_.top();
syn_tree_.pop();
*t = currentP;
syn_tree_.push(&(currentP->sibling_));
return;
}
void SynAnalysis::process62() {
symbol_.push(LoopStm);
currentP = new TreeNode();
currentP->lineno_ = token_list_[now_]->line_;
currentP->node_kind_ = StmtK;
currentP->kind_ = WhileK;
TreeNode** t = syn_tree_.top();
syn_tree_.pop();
*t = currentP;
syn_tree_.push(&(currentP->sibling_));
return;
}
void SynAnalysis::process63() {
symbol_.push(InputStm);
currentP = new TreeNode();
currentP->lineno_ = token_list_[now_]->line_;
currentP->node_kind_ = StmtK;
currentP->kind_ = ReadK;
TreeNode** t = syn_tree_.top();
syn_tree_.pop();
*t = currentP;
syn_tree_.push(&(currentP->sibling_));
return;
}
void SynAnalysis::process64() {
symbol_.push(OutputStm);
currentP = new TreeNode();
currentP->lineno_ = token_list_[now_]->line_;
currentP->node_kind_ = StmtK;
currentP->kind_ = WriteK;
TreeNode** t = syn_tree_.top();
syn_tree_.pop();
*t = currentP;
syn_tree_.push(&(currentP->sibling_));
return;
}
void SynAnalysis::process65() {
symbol_.push(ReturnStm);
currentP = new TreeNode();
currentP->lineno_ = token_list_[now_]->line_;
currentP->node_kind_ = StmtK;
currentP->kind_ = ReturnK;
TreeNode** t = syn_tree_.top();
syn_tree_.pop();
*t = currentP;
syn_tree_.push(&(currentP->sibling_));
return;
}
void SynAnalysis::process66() {
symbol_.push(AssCall);
symbol_.push(ID);
currentP = new TreeNode();
currentP->node_kind_ = StmtK;
currentP->lineno_ = token_list_[now_]->line_; //it probably has a mistake, example for `a \n := \n b` (not solved)
TreeNode* t = new TreeNode();
t->lineno_ = token_list_[now_]->line_;
t->node_kind_ = ExpK;
t->kind_ = VariK;
t->name_.push_back(token_list_[now_]->sem_);
t->idnum_++;
currentP->child_[0] = t;
TreeNode** t1 = syn_tree_.top();
syn_tree_.pop();
*t1 = currentP;
syn_tree_.push(&(currentP->sibling_));
return;
}
void SynAnalysis::process67() {
symbol_.push(AssignmentRest);
currentP->kind_ = AssignK;
return;
}
void SynAnalysis::process68() {
symbol_.push(CallStmRest);
currentP->child_[0]->attr_.exp_attr.var_kind = IdV;
currentP->kind_ = CallK;
return;
}
void SynAnalysis::process69() {
symbol_.push(Exp);
symbol_.push(ASSIGN);
symbol_.push(VariMore);
// currentP->child_.push_back(NULL);
syn_tree_.push(&(currentP->child_[1]));
currentP = currentP->child_[0];
//operator_.push("END"); //my modify
//my modify
TreeNode* t = new TreeNode();
t->node_kind_ = ExpK;
t->kind_ = OpK;
t->attr_.exp_attr.op = END;
operator_.push(t);
return;
}
void SynAnalysis::process70() {
symbol_.push(FI);
symbol_.push(StmList);
symbol_.push(ELSE);
symbol_.push(StmList);
symbol_.push(THEN);
symbol_.push(RelExp);
symbol_.push(IF);
// for (int i = 0; i < 3; i++)
// currentP->child_.push_back(NULL);
for (int i = 2; i >= 0; i--)
syn_tree_.push(&(currentP->child_[i]));
return;
}
void SynAnalysis::process71() {
symbol_.push(ENDWH);
symbol_.push(StmList);
symbol_.push(DO);
symbol_.push(RelExp);
symbol_.push(WHILE);
// for (int i = 0; i < 2; i++)
// currentP->child_.push_back(NULL);
for (int i = 1; i >= 0; i--)
syn_tree_.push(&(currentP->child_[i]));
return;
}
void SynAnalysis::process72() {
symbol_.push(RPAREN);
symbol_.push(Invar);
symbol_.push(LPAREN);
symbol_.push(READ);
return;
}
void SynAnalysis::process73() {
symbol_.push(ID);
currentP->idnum_++;
currentP->name_.push_back(token_list_[now_]->sem_);
return;
}
void SynAnalysis::process74() {
symbol_.push(RPAREN);
symbol_.push(Exp);
symbol_.push(LPAREN);
symbol_.push(WRITE);
// currentP->child_.push_back(NULL);
syn_tree_.push(&(currentP->child_[0]));
TreeNode* t = new TreeNode();
t->node_kind_ = ExpK;
t->kind_ = OpK;
t->attr_.exp_attr.op = END;
operator_.push(t);
return;
}
void SynAnalysis::process75() {
symbol_.push(RETURN);
return;
}
void SynAnalysis::process76() {
symbol_.push(RPAREN);
symbol_.push(ActParamList);
symbol_.push(LPAREN);
// currentP->child_.push_back(NULL);
syn_tree_.push(&(currentP->child_[1]));
return;
}
void SynAnalysis::process77() {
syn_tree_.pop();
return;
}
void SynAnalysis::process78() {
symbol_.push(ActParamMore);
symbol_.push(Exp);
TreeNode* t = new TreeNode();
t->node_kind_ = ExpK;
t->kind_ = OpK;
t->attr_.exp_attr.op = END;
operator_.push(t);
return;
}
void SynAnalysis::process79() {
return;
}
void SynAnalysis::process80() {
symbol_.push(ActParamList);
symbol_.push(COMMA);
syn_tree_.push(&(currentP->sibling_));
return;
}
void SynAnalysis::process81() {
symbol_.push(OtherRelE);
symbol_.push(Exp);
TreeNode* t = new TreeNode();
t->node_kind_ = ExpK;
t->kind_ = OpK;
t->attr_.exp_attr.op = END;
operator_.push(t);
getExpResult_ = false;
return;
}
void SynAnalysis::process82() {
symbol_.push(Exp);
symbol_.push(CmpOp);
currentP = new TreeNode();
currentP->lineno_ = token_list_[now_]->line_;
currentP->node_kind_ = ExpK;
currentP->kind_ = OpK;
currentP->attr_.exp_attr.op = token_list_[now_]->lex_;
// currentP->child_.push_back(NULL);
// currentP->child_.push_back(NULL);
//cout<<operator_.empty()<<endl;
//cout<<operator_.top()->attr_.exp_attr.op<<endl;
while (priosity(operator_.top()->attr_.exp_attr.op) >= priosity(currentP->attr_.exp_attr.op)) {
TreeNode* t = operator_.top();
operator_.pop();
TreeNode* Rnum = oprand_.top();
oprand_.pop();
TreeNode* Lnum = oprand_.top();
oprand_.pop();
t->child_[0] = Lnum;
t->child_[1] = Rnum;
oprand_.push(t);
}
operator_.push(currentP);
getExpResult_ = true;
return;
}
void SynAnalysis::process83() {
symbol_.push(OtherTerm);
symbol_.push(Term);
return;
}
void SynAnalysis::process84() {
if (token_list_[now_]->lex_ == RPAREN && expflag_ != 0) {
while (operator_.top()->attr_.exp_attr.op != LPAREN) {
TreeNode* t = operator_.top();
operator_.pop();
//cout<<token_list_[now_]->line_<<endl;
TreeNode* Rnum = oprand_.top();
oprand_.pop();
TreeNode* Lnum = oprand_.top();
oprand_.pop();
t->child_[0] = Lnum;
t->child_[1] = Rnum;
oprand_.push(t);
}
TreeNode* t1 = operator_.top();
operator_.pop();
delete t1;
expflag_--;
return;
}
if (getExpResult_ || getExpResult2_) {
while (operator_.top()->attr_.exp_attr.op != END) {
TreeNode* t = operator_.top();
operator_.pop();
TreeNode* Rnum = oprand_.top();
oprand_.pop();
TreeNode* Lnum = oprand_.top();
oprand_.pop();
t->child_[0] = Lnum;
t->child_[1] = Rnum;
oprand_.push(t);
}
TreeNode* t1 = operator_.top();
operator_.pop();
delete t1;
currentP = oprand_.top();
oprand_.pop();
TreeNode** t2 = syn_tree_.top();
syn_tree_.pop();
*t2 = currentP;
getExpResult2_ = false;
return;
}
}
void SynAnalysis::process85() {
symbol_.push(Exp);
symbol_.push(AddOp);
currentP = new TreeNode();
currentP->lineno_ = token_list_[now_]->line_;
currentP->node_kind_ = ExpK;
currentP->kind_ = OpK;
currentP->attr_.exp_attr.op = token_list_[now_]->lex_;
// currentP->child_.push_back(NULL);
// currentP->child_.push_back(NULL);
while (priosity(operator_.top()->attr_.exp_attr.op) >= priosity(currentP->attr_.exp_attr.op)) {
TreeNode* t = operator_.top();
operator_.pop();
TreeNode* Rnum = oprand_.top();
oprand_.pop();
TreeNode* Lnum = oprand_.top();
oprand_.pop();
t->child_[0] = Lnum;
t->child_[1] = Rnum;
oprand_.push(t);
}
operator_.push(currentP);
return;
}
void SynAnalysis::process86() {
symbol_.push(OtherFactor);
symbol_.push(Factor);
return;
}
void SynAnalysis::process87() {
return;
}
void SynAnalysis::process88() {
symbol_.push(Term);
symbol_.push(MultOp);
currentP = new TreeNode();
currentP->lineno_ = token_list_[now_]->line_;
currentP->node_kind_ = ExpK;
currentP->kind_ = OpK;
currentP->attr_.exp_attr.op = token_list_[now_]->lex_;
// currentP->child_.push_back(NULL);
// currentP->child_.push_back(NULL);
while (priosity(operator_.top()->attr_.exp_attr.op) >= priosity(currentP->attr_.exp_attr.op)) {
TreeNode* t = operator_.top();
operator_.pop();
TreeNode* Rnum = oprand_.top();
oprand_.pop();
TreeNode* Lnum = oprand_.top();
oprand_.pop();
t->child_[0] = Lnum;
t->child_[1] = Rnum;
oprand_.push(t);
}
operator_.push(currentP);
return;
}
void SynAnalysis::process89() {
symbol_.push(RPAREN);
symbol_.push(Exp);
symbol_.push(LPAREN);
currentP = new TreeNode();
currentP->node_kind_ = ExpK;
currentP->kind_ = OpK;
currentP->attr_.exp_attr.op = LPAREN;
operator_.push(currentP);
expflag_++;
return;
}
void SynAnalysis::process90() {
symbol_.push(INTC);
currentP = new TreeNode();
currentP->lineno_ = token_list_[now_]->line_;
currentP->node_kind_ = ExpK;
currentP->kind_ = ConstK;
currentP->attr_.exp_attr.val = getFromStr(token_list_[now_]->sem_);
oprand_.push(currentP);
return;
}
void SynAnalysis::process91() {
symbol_.push(Variable);
return;
}
void SynAnalysis::process92() {
symbol_.push(VariMore);
symbol_.push(ID);
currentP = new TreeNode();
currentP->lineno_ = token_list_[now_]->line_;
currentP->node_kind_ = ExpK;
currentP->kind_ = VariK;
currentP->name_.push_back(token_list_[now_]->sem_);
currentP->idnum_++;
oprand_.push(currentP);
return;
}
void SynAnalysis::process93() {
currentP->attr_.exp_attr.var_kind = IdV;
return;
}
void SynAnalysis::process94() {
symbol_.push(RMIDPAREN);
symbol_.push(Exp);
symbol_.push(LMIDPAREN);
currentP->attr_.exp_attr.var_kind = ArrayMembV;
// currentP->child_.push_back(NULL);
syn_tree_.push(&(currentP->child_[0]));
TreeNode* t = new TreeNode();
t->node_kind_ = ExpK;
t->kind_ = OpK;
t->attr_.exp_attr.op = END;
operator_.push(t);
getExpResult2_ = true;
return;
}
void SynAnalysis::process95() {
symbol_.push(FieldVar);
symbol_.push(DOT);
currentP->attr_.exp_attr.var_kind = FieldMembV;
// currentP->child_.push_back(NULL);
syn_tree_.push(&(currentP->child_[0]));
return;
}
void SynAnalysis::process96() {
symbol_.push(FieldVarMore);
symbol_.push(ID);
currentP = new TreeNode();
currentP->lineno_ = token_list_[now_]->line_;
currentP->node_kind_ = ExpK;
currentP->kind_ = VariK;
currentP->name_.push_back(token_list_[now_]->sem_);
currentP->idnum_++;
TreeNode** t = syn_tree_.top();
syn_tree_.pop();
*t = currentP;
return;
}
void SynAnalysis::process97() {
currentP->attr_.exp_attr.var_kind = IdV;
return;
}
void SynAnalysis::process98() {
symbol_.push(RMIDPAREN);
symbol_.push(Exp);
symbol_.push(LMIDPAREN);
currentP->attr_.exp_attr.var_kind = ArrayMembV;
// currentP->child_.push_back(NULL);
syn_tree_.push(&(currentP->child_[0]));
TreeNode* t = new TreeNode();
t->node_kind_ = ExpK;
t->kind_ = OpK;
t->attr_.exp_attr.op = END;
operator_.push(t);
getExpResult2_ = true;
return;
}
void SynAnalysis::process99() {
symbol_.push(LT);
return;
}
void SynAnalysis::process100() {
symbol_.push(EQ);
return;
}
void SynAnalysis::process101() {
symbol_.push(ADD);
return;
}
void SynAnalysis:: process102() {
symbol_.push(MINUS);
return;
}
void SynAnalysis::process103() {
symbol_.push(TIMES);
return;
}
void SynAnalysis::process104() {
symbol_.push(DIV);
return;
}
| true |
f804fe8232c4ede9c1abe9239233f66b708718c0 | C++ | Porechniy13/openGL | /lab3/zd1_5.cpp | UTF-8 | 2,100 | 2.609375 | 3 | [] | no_license | void RenderScene(void)
{
// Угол поворота вокруг ядра
static GLfloat fElect1 = 0.0f;
// Очищаем окно текущим цветом очистки
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//Обновляем матрицу наблюдения модели
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
//Транслируем всю сцену в поле зрения
//Это исходное преобразование наблюдения
glTranslatef(0.0f, 0.0f, -100.0f);
// Красное ядро и малая орбита для вращения
glPushMatrix();
glRotatef(10.0f, 0.0f, 0.0f, 1.0f);
glRotatef(fElect1, 0.0f, 1.0f, 0.0f);
glTranslatef(-10.0f, 0.0f, 0.0f);
glColor3ub(255, 0, 0);
glutSolidSphere(10.0f, 15, 15);
glPopMatrix();
// Желтые электроны
glColor3ub(255,255,0);
// Орбита первого электрона
// Записываем преобразование наблюдения
glPushMatrix();
// Поворачиваем на угол поворота
glRotatef(fElect1, 0.0f, 1.0f, 0.0f);
// Трансляция элемента от начала координат на орбиту
glTranslatef(90.0f, 0.0f, 0.0f);
// Рисуем электрон
glutSolidSphere(6.0f, 15, 15);
// Восстанавливаем преобразование наблюдения
glPopMatrix();
//Орбита второго электрона
glPushMatrix();
glRotatef(45.0f, 0.0f, 0.0f, 1.0f);
glRotatef(fElect1, 0.0f, 1.0f, 0.0f);
glTranslatef(-70.0f, 0.0f, 0.0f);
glutSolidSphere(6.0f, 15, 15);
glPopMatrix();
// Орбита третьего электрона
glPushMatrix();
glRotatef(360.0f-45.0f,0.0f, 0.0f, 1.0f);
glRotatef(fElect1, 0.0f, 1.0f, 0.0f);
glTranslatef(0.0f, 0.0f, 60.0f);
glutSolidSphere(6.0f, 15, 15);
glPopMatrix();
// Увеличиваем угол поворота
fElect1 += 10.0f;
if(fElect1 > 360.0f)
fElect1 = 0.0f;
// Показываем построенное изображение
glutSwapBuffers();
}
| true |
68e284b2d7a7d98e71dff7da908cab765491551c | C++ | royson/enigma | /Main.cpp | UTF-8 | 1,949 | 2.921875 | 3 | [] | no_license | #include <stdexcept>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
#include <cstdlib>
#include <memory>
#include "Rotor.hpp"
#include "Plugboard.hpp"
using namespace std;
int main(int argc, char **argv) {
//Check if there is an least a plugboard
if (argc <= 1) {
cerr << "Please include at least a plugboard" << endl;
exit(EXIT_FAILURE);
}
//Add the rotors
vector<tr1::shared_ptr<Rotor> > rotors;
int pbArg = argc - 1;
for (int i = 1; i < pbArg; i++) {
tr1::shared_ptr<Rotor> rotor(new Rotor(readPart(argv[i])));
rotors.push_back(rotor);
}
//Add the plugboard
tr1::shared_ptr<Plugboard> plugboard(
new Plugboard(readPart(argv[pbArg])));
//Accept input
char ch;
while (cin >> ws >> ch) {
if (ch < ALPHABET_BEGIN
|| ch >= ALPHABET_BEGIN + NUMBER_OF_ALPHABETS) {
continue;
}
//PlugBoard
ch = plugboard->map(ch);
int tmp;
//Rotors (Forward)
for (int i = 0; i < rotors.size(); i++) {
if (i == 0) {
ch = rotors[i]->map(ch, FORWARD);
} else {
tmp = mapToNumber(
(ch - rotors[i - 1]->getRotation())
+ NUMBER_OF_ALPHABETS)
% NUMBER_OF_ALPHABETS;
ch = rotors[i]->map(mapToAlphabet(tmp), FORWARD);
}
}
//Reflect
int reflectIndex = mapToNumber(ch);
reflectIndex = reflect(reflectIndex);
ch = mapToAlphabet(reflectIndex);
//Rotors (Inverse)
for (int i = rotors.size() - 1; i >= 0; i--) {
if (i == 0) {
ch = rotors[i]->map(ch, BACKWARD);
} else {
tmp = mapToNumber(
rotors[i]->map(ch, BACKWARD)
+ rotors[i - 1]->getRotation())
% NUMBER_OF_ALPHABETS;
ch = mapToAlphabet(tmp);
}
}
//PlugBoard
ch = plugboard->map(ch);
//Rotation
if (rotors.size() > 0) {
int rotateRotor = 0;
while (rotors[rotateRotor]->rotate()) {
rotateRotor = (++rotateRotor);
if (rotateRotor >= rotors.size()) {
break;
}
}
}
cout << ch;
}
return 0;
}
| true |
daff4a1a83b9c2549784f99deb1a8d8c52e80945 | C++ | cheydrick/CSInteropStructTest | /InteropStructTest.cpp | UTF-8 | 2,554 | 2.78125 | 3 | [] | no_license | // InteropStructTest.cpp : Defines the exported functions for the DLL application.
// This is the source code for InteropStructTest.dll.
#include "stdafx.h"
#include <stdio.h>
#ifdef INTEROPSTRUCTTEST_EXPORTS
#define INTEROPSTRUCTTEST_API __declspec(dllexport)
#else
#define INTEROPSTRUCTTEST_API __declspec(dllimport)
#endif
extern "C"{
INTEROPSTRUCTTEST_API int GetInteger();
INTEROPSTRUCTTEST_API void PassIntegerPointer(int *i);
INTEROPSTRUCTTEST_API void PassSimpleStructPointer(struct SimpleStruct *s);
INTEROPSTRUCTTEST_API void PassSimpleStructArray(int size, struct SimpleStruct *s);
INTEROPSTRUCTTEST_API void PassComplexStructPointer(struct ComplexStruct *s);
INTEROPSTRUCTTEST_API void PassComplexStructArray(int size, struct ComplexStruct *s);
INTEROPSTRUCTTEST_API void DebugCTypeSizes();
struct SimpleStruct
{
int firstInt;
int secondInt;
};
struct ComplexStruct
{
char firstChar;
char secondChar;
unsigned long firstLong;
short firstShort;
char thirdChar;
char fourthChar;
};
INTEROPSTRUCTTEST_API int GetInteger()
{
return 42;
}
INTEROPSTRUCTTEST_API void PassIntegerPointer(int *i)
{
*i = 27;
}
INTEROPSTRUCTTEST_API void PassSimpleStructPointer(struct SimpleStruct *s)
{
s->firstInt = 42;
s->secondInt = 27;
}
INTEROPSTRUCTTEST_API void PassSimpleStructArray(int size, struct SimpleStruct *s)
{
int i = 0;
int value = 1;
struct SimpleStruct *sptr;
sptr = s;
for (i = 0; i < size; i++)
{
sptr->firstInt = value++;
sptr->secondInt = value++;
sptr++;
}
}
INTEROPSTRUCTTEST_API void PassComplexStructPointer(struct ComplexStruct *s)
{
s->firstChar = 1;
s->secondChar = 2;
s->firstLong = 3;
s->firstShort = 4;
s->thirdChar = 5;
s->fourthChar = 6;
}
INTEROPSTRUCTTEST_API void PassComplexStructArray(int size, struct ComplexStruct *s)
{
int i = 0;
int value = 1;
struct ComplexStruct *sptr;
sptr = s;
for (i = 0; i < size; i++)
{
sptr->firstChar = value++;
sptr->secondChar = value++;
sptr->firstLong = value++;
sptr->firstShort = value++;
sptr->thirdChar = value++;
sptr->fourthChar = value++;
sptr++;
}
}
INTEROPSTRUCTTEST_API void DebugCTypeSizes()
{
printf("\nSize of C char: %i\n", sizeof(char));
printf("Size of C short: %i\n", sizeof(short));
printf("Size of C int: %i\n", sizeof(int));
printf("Size of C long: %i\n", sizeof(long));
printf("Size of C SimpleStruct: %i\n", sizeof(struct SimpleStruct));
printf("Size of C ComplexStruct: %i\n", sizeof(struct ComplexStruct));
}
}
| true |
bec6a9f6eb1b042a9ee90ac6811139616c930883 | C++ | zamfiroiu/SDD2020 | /1050_seminar01.cpp | UTF-8 | 1,423 | 3.15625 | 3 | [] | no_license | #include<stdio.h>
#include<string>
struct Virus {
char* nume;
float diametru;
int nrZileIncubatie;
};
Virus initializareVirus(const char* nume, float diametru, int nrZile) {
Virus v;
//v.nume = new char[strlen(nume) + 1];
v.nume = (char*)malloc(sizeof(char)*(strlen(nume) + 1));
strcpy(v.nume, nume);
v.diametru = diametru;
v.nrZileIncubatie = nrZile;
return v;
}
void afisareVirus(Virus *v){
printf("Virusul %s are un diametru de %5.2f microni si %d zile incubatie.\n",
(*v).nume, (*v).diametru, (*v).nrZileIncubatie);
}
void main() {
Virus virus;
virus = initializareVirus("SARS", 2, 7);
afisareVirus(&virus);
free(virus.nume);
Virus* pv;
pv = (Virus*)malloc(sizeof(Virus));
*pv=initializareVirus("Covid-19", 3, 28);
afisareVirus(pv);
free(pv->nume);
free(pv);
Virus* vv;
int nrVirusi = 5;
vv = (Virus*)malloc(nrVirusi * sizeof(Virus));
for (int i = 0; i < nrVirusi; i++) {
vv[i] = initializareVirus("AH1N1", 2.5, (i+1)*3);
}
for (int i = 0; i < nrVirusi; i++) {
afisareVirus(vv+i);
}
for (int i = 0; i < nrVirusi; i++) {
free(vv[i].nume);
}
free(vv);
Virus**vpv;
int nrPointeri = 3;
vpv = (Virus**)malloc(sizeof(Virus*)*nrPointeri);
for (int i = 0; i < nrPointeri; i++) {
vpv[i] = (Virus*)malloc(sizeof(Virus));
*(*vpv + i) = initializareVirus("gripa romaneasca", 1, 2);
//*vpv[i]
}
} | true |
6f5dad432538ee4123fe5ac6e4b03e20d04f9085 | C++ | jaidurn/BasicEngine | /BasicEngine/FileLog.h | UTF-8 | 532 | 2.546875 | 3 | [] | no_license | #pragma once
//==========================================================================================
// File Name: FileLog.h
// Author: Brian Blackmon
// Date Created: 10/16/2019
// Purpose:
// Logs messages to a file and saves the file.
//==========================================================================================
#include "ILog.h"
#include <fstream>
class FileLog : public ILog
{
public:
FileLog(string logPath);
virtual ~FileLog();
virtual void log(const string message) const;
private:
string m_logPath;
};
| true |
2278638c75ecd0aa356276812843314a4cb2df81 | C++ | Stiffstream/json_dto | /dev/sample/tutorial17/main.cpp | UTF-8 | 4,010 | 3.28125 | 3 | [
"BSD-3-Clause",
"JSON",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /*
A sample using json_dto
*/
#include <iostream>
#include <string>
#include <forward_list>
#include <list>
#include <map>
#include <unordered_map>
#include <tuple>
#include <json_dto/pub.hpp>
struct property_info_t
{
// Is this property mandatory?
bool m_mandatory;
// Priority of this property.
int m_priority;
// Default value.
std::string m_default;
// Actual value.
std::string m_value;
friend bool
operator==( const property_info_t & a, const property_info_t & b )
{
const auto tie = [](const auto & v) {
return std::tie(v.m_mandatory, v.m_priority, v.m_default, v.m_value);
};
return tie(a) == tie(b);
}
template< typename Json_Io >
void json_io( Json_Io & io )
{
io & json_dto::optional( "mandatory", m_mandatory, false )
& json_dto::mandatory( "priority", m_priority )
& json_dto::optional( "default", m_default, std::string{} )
& json_dto::mandatory( "value", m_value )
;
}
};
std::ostream &
operator<<( std::ostream & to, const property_info_t & info )
{
return (to << "(" << (info.m_mandatory ? "mandatory" : "optional")
<< ", p=" << info.m_priority << ", defaults='"
<< info.m_default << "', value='" << info.m_value << "')");
}
struct message_t
{
// Title of the message.
std::string m_title;
// Body of the message.
std::string m_body;
// List of hash-tags.
std::list< std::string > m_hash_tags;
// Map of message properties.
std::map< std::string, property_info_t > m_properties;
message_t() = default;
template< typename Json_Io >
void json_io( Json_Io & io )
{
io & json_dto::mandatory( "title", m_title )
& json_dto::mandatory( "body", m_body )
& json_dto::optional( "hash-tags", m_hash_tags,
decltype(m_hash_tags){} )
& json_dto::optional( "properties", m_properties,
decltype(m_properties){} )
;
}
};
std::ostream &
operator<<( std::ostream & to, const message_t & what )
{
to << "'" << what.m_title << "'\n";
to << "==================================\n";
to << what.m_body << "\n";
to << "----------------------------------\n";
if( !what.m_hash_tags.empty() )
{
for( const auto & v : what.m_hash_tags )
to << "#" << v << ",";
to << "\n";
}
if( !what.m_properties.empty() )
{
to << "----------------------------------\n";
for( const auto & kv : what.m_properties )
to << kv.first << " => " << kv.second << "\n";
}
to << "--- end ---\n\n";
return to;
}
const std::string json_data{
R"JSON(
[
{
"title" : "Hello!",
"body" : "Just a simple text",
"hash-tags" : ["demo"]
},
{
"title" : "Bye!",
"body" : "Just an another simple text",
"properties" : {
"importance" : { "mandatory" : true, "priority" : 1, "value" : "high" },
"access-control" : { "priority" : 0, "default" : "NONE", "value" : "simple" }
}
},
{
"title" : "Welcome!",
"body" : "This is a demo for json_dto-0.2.8",
"hash-tags" : ["demo", "json_dto", "rapidjson", "moderncpp"],
"properties" : {
"importance" : { "mandatory" : true, "priority" : 1, "value" : "high" },
"difficulty" : {
"mandatory" : false,
"priority" : 10,
"default" : "high",
"value" : "low"
}
}
}
])JSON" };
int
main( int , char *[] )
{
try
{
// Load all messages to signle-linked list.
auto messages = json_dto::from_json<
std::forward_list<message_t> >( json_data );
std::cout << "Loaded messages:\n" << std::endl;
for( const auto & m : messages )
std::cout << m;
std::cout << std::endl;
// Transform messages from one container to another.
std::unordered_map< std::string, message_t > tagged_messages;
auto it = messages.begin();
tagged_messages[ "hello" ] = *(it++);
tagged_messages[ "bye" ] = *(it++);
tagged_messages[ "welcome" ] = *it;
// Serialize the tagged messages.
std::cout << "Serialized tagged messages:\n"
<< json_dto::to_json( tagged_messages )
<< std::endl;
}
catch( const std::exception & ex )
{
std::cerr << "Error: " << ex.what() << "." << std::endl;
return 1;
}
return 0;
}
| true |
046209b49b54b6fafae80f886d1791ad426deff8 | C++ | danyaaaaaa/University | /lab9/LR9A/main.cpp | UTF-8 | 237 | 2.875 | 3 | [] | no_license | #include <iostream>
#include "vectortemplate.h"
using namespace std;
int main()
{
VECTOR<int> v1(1, 4);
VECTOR<int> v2(2, 3);
v1 == v2 ? cout << "Ravni\n" : v1 > v2 ? cout << "Bolshe\n" : cout << "Menshe\n";
return 0;
}
| true |
693cecde1e25142f9320d62814ba59772bf9db68 | C++ | Lunahri17/1k4-lunahri | /2.C++/TP2_Parte3_Codificacion.en.DevC/TP01_P3_EJ03.cpp | UTF-8 | 549 | 3.171875 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
#include<math.h>
main()
{
float x1,x2,y1,y2,a,b,d;
printf("Ingrese la coordenada X de su Primer punto: ");
scanf("%f",&x1);
printf("Ingrese la coordenada Y de su Primer punto: ");
scanf("%f",&y1);
printf("\nIngrese la coordenada X de su Segundo punto: ");
scanf("%f",&x2);
printf("Ingrese la coordenada Y de su Segundo punto: ");
scanf("%f",&y2);
a=x2-x1;
b=y2-y1;
d=sqrt(pow(a,2)+pow(b,2));
printf("\nLa distancia entre los puntos es: %.2f",d);
printf("\n\n");
system("pause");
}
| true |
e81a7e792da0f6d5c4681fce0d84c40b5cf3caa5 | C++ | SidhantPuntambekar/CSCI-1300 | /hmwk3_Puntambekar/countDigits.cpp | UTF-8 | 872 | 3.859375 | 4 | [] | no_license | //CS1300 Fall 2019
//Author: Sidhant Puntambekar
//Recitation: 304 - Reddy
//Homework 3 - Problem 4
#include <iostream>
#include <string>
using namespace std;
int countDigits(int n) //This algorithm counts the number of digits in a certain number
{
if (n < 0) //if n is less than zero, multiply it by negative 1
{
n *= -1;
}
string nString = to_string(n); //Convert input integer to string
int count = 0; //Define a count variable to count digits
for (int i = 0; i < nString.length(); i++) //Create a for loop to iterate through the string while counting digits
{
count++; //Add one to count
}
return count; //Return count
}
int main()
{
//Test case 1
//Expected output
//6
cout << countDigits(123326) << endl;
//Test case 2
//Expected output
//3
cout << countDigits(-123) << endl;
} | true |
b65670e8fe5dd1bc0c3ae1da93d79dab833913ff | C++ | sweet-iriska/--- | /Исходный код.cpp | WINDOWS-1251 | 1,244 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include <random>
#include <vector>
#include <iterator>
#include <algorithm>
#include <fstream>
#include <ctime>
using namespace std;
// 2, 1
class FunctorClass
{
public:
int operator()(int &n){
if (n % 2 == 0) {
n = 2 * n;
}
else {
n++;
}
return n;
}
};
int main()
{
setlocale(LC_ALL, "rus");
srand(time(0));
vector<int> v;
generate_n(back_inserter(v), 10, []() mutable{return rand() % 10; });
copy(begin(v), end(v), ostream_iterator<int>(cout, " "));
cout << endl;
int evenCount = 0;
int evenCount1 = 0;
for_each(v.begin(), v.end(), [&evenCount](int &n) {
if (n % 2 == 0) {
n = 2 * n;
}
else {
n++;
}
return n;
});
copy(begin(v), end(v), ostream_iterator<int>(cout, " "));
cout << endl;
for_each(v.begin(), v.end(), FunctorClass());
copy(begin(v), end(v), ostream_iterator<int>(cout, " "));
ofstream file;
file.open("1.txt", ios::out | ios::app);
if (!file)
{
cout << "Error!";
cin.sync(), cin.get();
return 1;
}
copy(begin(v), end(v), ostream_iterator<int>(file, " "));
file.close();
_getwch();
return 0;
} | true |
6cbbd4501ff4cd9d761f6d6cbfa0e0f99f39299e | C++ | YunHoseon/InhaStudy | /c++/0630/0630/GeometricObject.cpp | UTF-8 | 1,400 | 3.40625 | 3 | [] | no_license | #include "GeometricObject.h"
GeometricObject::GeometricObject()
{
}
double GeometricObject::GetArea()
{
return 0.0;
}
double GeometricObject::GetPerimeter()
{
return 0.0;
}
GeometricObject::~GeometricObject()
{
}
Triangle2::Triangle2()
{
side[0] = 1.0;
side[1] = 1.0;
side[2] = 1.0;
isTriangleFull = false;
}
Triangle2::Triangle2(double _side[], string _tColor, bool _isTriangleFull)
{
SetSide(_side);
tColor = _tColor;
isTriangleFull = _isTriangleFull;
}
void Triangle2::SetSide(double _side[])
{
for (int i = 0; i < 3; i++)
side[i] = _side[i];
}
double Triangle2::GetArea()
{
double s, a, b, c;
a = side[0];
b = side[1];
c = side[2];
s = (a + b + c) / 2;
return sqrt(s * abs((s - a)*(s - b)*(s - c)));
}
double Triangle2::GetPerimeter()
{
return side[0] + side[1] + side[2];
}
Triangle2::~Triangle2()
{
}
Rectangle2::Rectangle2()
{
SetWidth(1.0);
SetHeight(1.0);
}
Rectangle2::Rectangle2(double _width, double _height)
{
SetWidth(_width);
SetHeight(_height);
}
double Rectangle2::GetArea()
{
return width * height;
}
double Rectangle2::GetPerimeter()
{
return (width + height) * 2;
}
Rectangle2::~Rectangle2()
{
}
Circle2::Circle2()
{
SetRadius(1.0);
}
Circle2::Circle2(double radius)
{
SetRadius(radius);
}
double Circle2::GetArea()
{
return PI * pow(radius, 2);
}
double Circle2::GetPerimeter()
{
return 2*PI*radius;
}
Circle2::~Circle2()
{
} | true |
80f2e7a34520192c5ef842a966fdb140a4b672a8 | C++ | FRC-3637-Daleks/Asimov | /src/Commands/ControlSwissVelocity.h | UTF-8 | 1,067 | 2.53125 | 3 | [
"CC0-1.0"
] | permissive | /*
* ControlSwissVelocity.h
*
* Created on: Mar 3, 2016
* Author: Edward
*/
#ifndef SRC_COMMANDS_CONTROLSWISSVELOCITY_H_
#define SRC_COMMANDS_CONTROLSWISSVELOCITY_H_
#include "WPILib.h"
#include "Subsystems/Swiss.h"
#include "Utility/ValueStore.h"
namespace commands
{
using namespace dman;
/** Command for manually controlling the velocity of the swiss with a joystick
*
*/
class ControlSwissVelocity: public Command
{
public:
using Swiss_t = subsystems::Swiss *;
using Input_t = ValueStore::Value<double>;
public:
ControlSwissVelocity(Swiss_t swiss, Input_t input);
virtual ~ControlSwissVelocity() = default;
public:
/// Sets the mode of the swiss to voltage control
void Initialize() override;
/// Sets the speed of the swiss to the speed from input
void Execute() override;
/// Returns false
bool IsFinished() override;
/// Holds swiss wherever it was
void End() override;
/// Calls End
void Interrupted() override;
private:
Swiss_t swiss_;
Input_t input_;
};
}
#endif /* SRC_COMMANDS_CONTROLSWISSVELOCITY_H_ */
| true |
a009d5d97cc528dbb105a9f3b8d00e3e2ed04d65 | C++ | lechangjun/STUDY-Directx2D | /STUDY-directx2D/STUDY-directx2D-main/코드 교정/class_dx11/Rect.cpp | UTF-8 | 2,602 | 2.53125 | 3 | [] | no_license | #include "stdafx.h"
#include "Rect.h"
Rect::Rect(wstring shaderFile)
:position(0.0f, 0.0f), scale(1.0f, 1.0f), color(1, 1, 1, 1)
{
shader = new Shader(L"./_Shader2D/Effect.fx");
CreateBuffer();
Color(color);
}
Rect::Rect(wstring shaderFile, D3DXVECTOR2 position, D3DXVECTOR2 scale, D3DXCOLOR color)
: position(position), scale(scale), color(color)
{
shader = new Shader(L"./_Shader2D/Effect.fx");
CreateBuffer();
Color(color);
}
Rect::~Rect()
{
//if (shader)
//{
// delete shader;
// shader = nullptr;
//}
SAFE_DELETE(shader);
SAFE_RELEASE(vertexBuffer);
}
void Rect::CreateBuffer()
{
Vertex vertices[6]; // Rect 한개 정점 6개
vertices[0].Position = D3DXVECTOR3(-0.5f, -0.5f, 0.0f);
vertices[1].Position = D3DXVECTOR3(-0.5f, +0.5f, 0.0f);
vertices[2].Position = D3DXVECTOR3(+0.5f, -0.5f, 0.0f);
vertices[3].Position = D3DXVECTOR3(+0.5f, -0.5f, 0.0f);
vertices[4].Position = D3DXVECTOR3(-0.5f, +0.5f, 0.0f);
vertices[5].Position = D3DXVECTOR3(+0.5f, +0.5f, 0.0f);
// CreateBuffer
{
D3D11_BUFFER_DESC desc;
ZeroMemory(&desc, sizeof(D3D11_BUFFER_DESC));
desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
desc.ByteWidth = sizeof(Vertex) * 6;
desc.CPUAccessFlags = 0;
desc.Usage = D3D11_USAGE_DEFAULT;
D3D11_SUBRESOURCE_DATA data;
ZeroMemory(&data, sizeof(D3D11_SUBRESOURCE_DATA));
data.pSysMem = vertices;
HRESULT hr = Device->CreateBuffer(&desc, &data, &vertexBuffer);
assert(SUCCEEDED(hr));
}
}
void Rect::Update(D3DXMATRIX& V, D3DXMATRIX& P)
{
D3DXMATRIX W;
D3DXMATRIX S, T;
D3DXMatrixScaling(&S, scale.x, scale.y, 1.0f);
D3DXMatrixTranslation(&T, position.x, position.y, 0.0f);
W = S * T;
shader->AsMatrix("World")->SetMatrix(W);
shader->AsMatrix("View")->SetMatrix(V);
shader->AsMatrix("Projection")->SetMatrix(P);
shader->AsVector("Color")->SetFloatVector(color);
}
void Rect::Render()
{
UINT stride = sizeof(Vertex);
UINT offset = 0;
DeviceContext->IASetVertexBuffers(0, 1, &vertexBuffer, &stride, &offset);
DeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
shader->Draw(0, 0, 6);
}
void Rect::Position(float x, float y)
{
Position(D3DXVECTOR2(x, y));
}
void Rect::Position(D3DXVECTOR2 vec)
{
position = vec;
}
void Rect::Scale(float x, float y)
{
Scale(D3DXVECTOR2(x, y));
}
void Rect::Scale(D3DXVECTOR2 vec)
{
scale = vec;
}
void Rect::Color(float r, float g, float b)
{
Color(D3DXCOLOR(r, g, b, 1));
}
void Rect::Color(D3DXCOLOR vec)
{
color = vec;
} | true |
20de2ddb05174a26b9c9463bc6514f2191c9f532 | C++ | bogdanenciu/gravitySimulator | /Game/src/DrawAble.cpp | UTF-8 | 1,619 | 2.90625 | 3 | [] | no_license | #include "DrawAble.h"
DrawAble::DrawAble(std::string name, int x, int y)
{
texture = IMG_Load(name.c_str());
glGenTextures(1, &textureId);
pos.x = x;
pos.y = y;
Rotation = 0.f;
}
DrawAble::~DrawAble()
{
}
void DrawAble::draw()
{
glBindTexture(GL_TEXTURE_2D, textureId);
// Set the texture's stretching properties
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// get the number of channels in the SDL surface
nOfColors = texture->format->BytesPerPixel;
if (nOfColors == 4)
{ // alpha
if (texture->format->Rmask == 0x000000ff)
texture_format = GL_RGBA;
else
texture_format = GL_BGR_EXT;
}
else if (nOfColors == 3)
{ // no alpha
if (texture->format->Rmask == 0x000000ff)
texture_format = GL_RGB;
else
texture_format = GL_BGR_EXT;
}
else
{
// 1 channel
texture_format = GL_RED;
}
// Edit the texture object's image data using the information SDL_Surface
glTexImage2D(GL_TEXTURE_2D, 0, nOfColors, texture->w, texture->h, 0,
texture_format, GL_UNSIGNED_BYTE, texture->pixels);
glEnable(GL_TEXTURE_2D);
glRotatef(180.f, 0.0, 0.0, 1.0);
//draw Quad
glBegin(GL_QUADS);
glTexCoord2f(0, 0);
glVertex2f(pos.x - texture->w/2, pos.y- texture->h / 2);
glTexCoord2f(1, 0);
glVertex2f(pos.x + texture->w/2, pos.y - texture->h / 2);
glTexCoord2f(1, 1);
glVertex2f(pos.x + texture->w/2, pos.y + texture->h/2);
glTexCoord2f(0, 1);
glVertex2f(pos.x - texture->w / 2, pos.y + texture->h/2);
glEnd();
glRotatef(-180.f, 0.0, 0.0, 1.0);
glDisable(GL_TEXTURE_2D);
} | true |
d5b516e0b861167b49a845d228ce45338bff7c9b | C++ | Vesion/Misirlou | /leetcode/024-SwapNodesInPairs.cpp | UTF-8 | 1,456 | 3.546875 | 4 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int val) : val(val), next(NULL) {}
};
// Solution 1 : recursive
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (!head || !head->next) return head;
ListNode* new_next = swapPairs(head->next->next);
ListNode* next = head->next;
next->next = head;
head->next = new_next;
return next;
}
};
// Solution 2 : iterative
class Solution_2 {
public:
ListNode* swapPairs(ListNode* head) {
ListNode dummy(0); dummy.next = head;
ListNode* cur = &dummy;
while (cur->next && cur->next->next) {
ListNode* first = cur->next;
ListNode* second = cur->next->next;
ListNode* third = cur->next->next->next;
cur->next = second;
second->next = first;
first->next = third;
cur = first;
}
return dummy.next;
}
};
// Solution 3 : use two-level-pointer
class Solution_3 {
public:
ListNode* swapPairs(ListNode* head) {
ListNode **pp = &head, *a, *b;
while ((a = *pp) && (b = a->next)) {
a->next = b->next;
b->next = a;
*pp = b; // think about how this work
pp = &(a->next);
}
return head;
}
};
int main() {
return 0;
}
| true |
3075f0ebcd849fba4d1b88bb9d75998c7602f10a | C++ | PatriceVignola/astral-tides | /Source/ProjectLuna/Public/StreamSection.h | UTF-8 | 885 | 2.578125 | 3 | [] | no_license | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
/**
*
*/
class PROJECTLUNA_API StreamSection
{
public:
StreamSection(FVector p1, FVector p2, FVector p3, FVector p4, FVector tangent,
FVector normal, float radius);
~StreamSection();
/*
Applies the current force to the object if inside
*/
bool IsInside(FVector pos);
bool IsInside2(FVector pos);
FVector GetTangent();
FVector GetNormal();
float GetRadius();
FVector GetCentre();
FVector GetMin();
FVector GetMax();
/*void GetPoints(const FVector& p1, const FVector& p2,
const FVector& p3, const FVector& p4);*/
private:
FVector m_normal;
FVector m_tangent;
FVector m_p1, m_p2, m_p3, m_p4;
float m_area;
float m_radius;
FVector m_min;
FVector m_max;
FVector m_centre;
const float TOLERANCE = 1.001;
float GetArea(FVector pt1, FVector pt2, FVector pt3);
};
| true |
0c69c5fa489f4b9946eb6e979345c1206210e06e | C++ | danel2005/triple-of-da-centry | /mathLazy.cpp | UTF-8 | 2,460 | 3.578125 | 4 | [] | no_license | #include <iostream>
#include <math.h>
#include <iomanip>
unsigned int baranoliFunc(int n, int k)
{
int calcN = 1;
int calcK = 1;
int calcD = 1;
int result = 1;
for (int i = 1; i <= n; i++) calcN *= i;//n! זה מחשב את ה
for (int i = 1; i <= k; i++) calcK *= i;//k! זה מחשב את ה
for (int i = 1; i <= n - k; i++) calcD *= i;//(n - k)!
result = calcK * calcD;
result = calcN / result;
std::cout << "Baranoli: " << result << std::endl;
return result;
}
double realCalc(float n, float k, float pr, bool DIY, int baranoliNum)
{
double baranoli = 0.0f;
double result = 0.0f;
DIY ? baranoli = baranoliNum : baranoli = baranoliFunc(n, k);
result = baranoli * pow(pr, k) * pow(1 - pr, n - k);
return result;
}
void calc(float n, float k, float pr, bool DIY, int baranoliNum) {
double baranoli = 0;
double result = 0;
DIY ? baranoli = baranoliNum : baranoli = baranoliFunc(n, k);
std::cout << "k: " << (int)k << std::endl;
std::cout << "p^k = " << pow(pr, k) << std::endl;
std::cout << "(1 - p)^(n - k) = " << pow(1 - pr, n - k) << std::endl;
std::cout << "The result is: " << realCalc(n, k, pr, DIY, baranoliNum) << std::endl;
}
bool menu()
{
float rangeK = 0;
float rangeK2 = 0;
float n = 0;
float p = 0;
float sum = 0;
bool range = false;
char answer = ' ';
bool bronliDIY = false;
int baranoliNum = 0;
std::cout << "Enter n: ";
std::cin >> n;
std::cout << "is it a range:(y for yes)";//aviel
std::cin >> answer;
if(answer == 'y' || answer == 'Y')
{
range = true;
}
if(range)
{
std::cout << "Enter range of k: (seperate by ENTER)";
std::cin >> rangeK;
std::cin >> rangeK2;
}
else
{
std::cout << "Enter k:";
std::cin >> rangeK;
rangeK2 = rangeK;
}
std::cout << "Do you have the bronli value?(y for yes) ";
std::cin >> answer;
if(answer == 'y' || answer == 'Y')
{
bronliDIY = true;
std::cout << "Enter da baranoli: ";
std::cin >> baranoliNum;
}
if(rangeK > n || rangeK2 > n)
{
return false;
}
std::cout << "Enter p: ";
std::cin >> p;
for(int i = rangeK; i <= rangeK2; i++)
{
calc(n, i, p, bronliDIY, baranoliNum);
std::cout << std::endl;
sum += realCalc(n, i, p, bronliDIY, baranoliNum);
}
std::cout << "The sum of all the probilities is: " << std::fixed << std::setprecision(5) << sum;
return true;
}
int main()
{
if(!menu()) std::cerr << "ERROR! K CAN NEVER BE BIGGER THAN N!";
return 0;
}
//g++ -o mathLazy.exe mathLazy.cpp | true |
2ace08300624c6bb80e7f7dc1b5d842f7396b119 | C++ | abhinav-iitkgp/Data-Structures-and-Algorithms | /old Comp/stacks/basic_functions.cpp | UTF-8 | 507 | 3.234375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
void printstack(stack<int> s)
{
while(!s.empty())
{
cout<<s.top()<<" ";
s.pop();
}
cout<<endl;
}
int main()
{
stack <int> s;
s.push(10);
s.push(23);
s.push(5);
s.push(2);
s.push(4);
s.push(3);
s.push(2);
s.push(32);
printstack(s);
cout<<"s.size() "<<s.size()<<endl;
cout<<"s.empty() "<<s.empty()<<endl;
cout<<"s.top() "<<s.top()<<endl;
s.pop();
printstack(s);
cout<<endl<<s.top()<<endl;
} | true |
2e79e8da3d3d74c49a97a322bb451353336ade7f | C++ | teaspring/problems | /topics/stackqueue/header/genstack.h | UTF-8 | 836 | 3.578125 | 4 | [] | no_license | /*
* *********** <DataStructureInC++> chapter4 Stack & Queue *************
* generic stack implementation of vector
*
*/
#ifndef STACK
#define STACK
#include <vector>
using namespace std;
template<typename T, int capacity=30>
class Stack{
public:
Stack(){
pool.clear();
}
void clear(){
return pool.empty();
}
bool isEmpty() const{
return pool.empty();
}
T& topEl(){ //tail
return pool.back();
}
T pop(){ //pop from tail
T el = pool.back();
pool.pop_back();
return el;
}
void push(const T& el){ //insert at tail
pool.push_back(el);
}
private:
vector<T> pool;
};
#endif
| true |
17a741b466bcd204215e64d2a2d9f3d9b25f2f10 | C++ | wangwen135/Arduino | /LCD/LCD.ino | UTF-8 | 4,642 | 3.1875 | 3 | [] | no_license | //8位接法
//接口说明:
//1、两组电源 一组是模块的电源 一组是背光板的电源 一般均使用5V供电。本次试验背光使用3.3V供电也可以工作。
//2、VL是调节对比度的引脚,串联不大于5KΩ的电位器进行调节。本次实验使用1KΩ的电阻来设定对比度。其连接分高电位与低电位接法,本次使用低电位接法,串联1KΩ电阻后接GND。
//注意:不同液晶的对比度电阻是不同的,最好是接一个电位器进行测试,本次实验使用的1KΩ电阻在其他液晶上不一定正确。
//3、RS 是很多液晶上都有的引脚 是命令/数据选择引脚 该脚电平为高时表示将进行数据操作;为低时表示进行命令操作。
//4、RW 也是很多液晶上都有的引脚 是读写选择端 该脚电平为高是表示要对液晶进行读操作;为低时表示要进行写操作。
//5、E 同样很多液晶模块有此引脚 通常在总线上信号稳定后给一正脉冲通知把数据读走,在此脚为高电平的时候总线不允许变化。
//6、D0—D7 8 位双向并行总线,用来传送命令和数据。
//7、BLA是背光源正极,BLK是背光源负极。
//尼玛 这个是RS
int DI = 12;
int RW = 11;
int Enable = 2;
//这里是D0 - D7
int DB[] = {3, 4, 5, 6, 7, 8, 9, 10};//使用数组来定义总线需要的管脚
void LcdCommandWrite(int value) {
// 定义所有引脚
int i = 0;
for (i = DB[0]; i <= DI; i++) //总线赋值
{
digitalWrite(i, value & 01); //因为1602液晶信号识别是D7-D0(不是D0-D7),这里是用来反转信号。
value >>= 1;
}
//输出一个高脉冲
digitalWrite(Enable, LOW);
delayMicroseconds(1);
digitalWrite(Enable, HIGH);
delayMicroseconds(1);
digitalWrite(Enable, LOW);
delayMicroseconds(1);
}
void LcdDataWrite(int value) {
// 定义所有引脚
int i = 0;
digitalWrite(DI, HIGH);
digitalWrite(RW, LOW);
for (i = DB[0]; i <= DB[7]; i++) {
digitalWrite(i, value & 01);
value >>= 1;
}
//输出一个高脉冲
digitalWrite(Enable, LOW);
delayMicroseconds(1);
digitalWrite(Enable, HIGH);
delayMicroseconds(1);
digitalWrite(Enable, LOW);
delayMicroseconds(1);
}
void setup (void) {
int i = 0;
for (i = Enable; i <= DI; i++) {
pinMode(i, OUTPUT);
}
delay(100);
// 短暂的停顿后初始化LCD
// 用于LCD控制需要
//##功能设置,采用8位方式的数据传输
LcdCommandWrite(0x38); // 设置为8-bit接口,2行显示,5x7文字大小
delay(64);
// LcdCommandWrite(0x38);
// delay(50);
// LcdCommandWrite(0x38);
// delay(20);
//##设置输入模式,显示的字符不动,光标右移,AC+1
LcdCommandWrite(0x06); // 输入方式设定
// 自动增量,没有显示移位
delay(20);
LcdCommandWrite(0x0E); // 显示设置
// 开启显示屏,光标显示,无闪烁
delay(20);
LcdCommandWrite(0x01); // 屏幕清空,光标位置归零
//delay(100);
//LcdCommandWrite(0x80); // 显示设置
delay(20);
}
void loop (void) {
LcdCommandWrite(0x01); // 屏幕清空,光标位置归零
delay(10);
LcdCommandWrite(0x80 + 3);
delay(10);
// 写入欢迎信息
LcdDataWrite('S');
LcdDataWrite('B');
LcdDataWrite(' ');
LcdDataWrite('n');
LcdDataWrite('i');
LcdDataWrite('u');
LcdDataWrite(' ');
LcdDataWrite('n');
LcdDataWrite('i');
LcdDataWrite('u');
delay(10);
LcdCommandWrite(0xc0 + 1); // 定义光标位置为第二行第二个位置
delay(10);
LcdDataWrite('z');
LcdDataWrite('h');
LcdDataWrite('e');
LcdDataWrite(' ');
LcdDataWrite('s');
LcdDataWrite('h');
LcdDataWrite('i');
LcdDataWrite(' ');
LcdDataWrite('c');
LcdDataWrite('e');
LcdDataWrite(' ');
LcdDataWrite('s');
LcdDataWrite('h');
LcdDataWrite('i');
LcdDataWrite(' ');
delay(5000);
LcdCommandWrite(0x01); // 屏幕清空,光标位置归零
delay(10);
LcdDataWrite('1');
LcdDataWrite('2');
LcdDataWrite('3');
LcdDataWrite('4');
LcdDataWrite('5');
LcdDataWrite('6');
LcdDataWrite('7');
LcdDataWrite('8');
LcdDataWrite('9');
LcdDataWrite('0');
LcdDataWrite('(');
LcdDataWrite('!');
LcdDataWrite('#');
LcdDataWrite('%');
LcdDataWrite('&');
LcdDataWrite(')');
delay(1000);
LcdCommandWrite(0xc0); // 定义光标位置为第二行第二个位置
delay(10);
//显示一下温度看
LcdDataWrite('h');
LcdDataWrite('e');
LcdDataWrite(' ');
LcdDataWrite('h');
LcdDataWrite('e');
LcdDataWrite(' ');
LcdDataWrite('<');
LcdDataWrite('-');
LcdDataWrite('_');
LcdDataWrite('-');
LcdDataWrite('>');
delay(3000);
}
| true |
2ea703ae3e21fc304a18909f0ca3894cfd6ebe60 | C++ | jordantangy/cpp-messageboard-b | /Board.hpp | UTF-8 | 468 | 2.546875 | 3 | [
"MIT"
] | permissive | #pragma once
#include <iostream>
#include <vector>
using namespace std;
#include "Direction.hpp"
namespace ariel{
class Board{
std::vector<std::vector<char>> board;
public:
Board(){
board.resize(5,vector<char>(5,'_'));
}
void post(unsigned int row, unsigned int column,Direction d,const string &s);
string read(unsigned int row, unsigned int column,Direction d,unsigned int length);
void show();
};
}
| true |
bad35c5b22096733be4d45afcfa0c495b3329eb9 | C++ | xlnwel/Leetcode | /leetcode/0051.cpp | UTF-8 | 1,121 | 3.15625 | 3 | [] | no_license | #include <vector>
#include <string>
using namespace std;
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
col = vector<bool>(n, false);
diag1 = vector<bool>(2*n-1, false); // there are 2*n-1 diagonals
diag2 = vector<bool>(2*n-1, false);
vector<string> m(n, string(n, '.'));
helper(m, 0, n);
return ans;
}
private:
void helper(vector<string>& m, int row, int n) {
if (row == n) {
ans.push_back(m);
return;
}
int a = n - 1 - row;
int b = n - row + n - 1;
for (auto i = 0; i != n; ++i) {
if (col[i] || diag1[i+a] || diag2[b-i])
continue;
m[row][i] = 'Q';
flip(i, a, b);
helper(m, row+1, n);
m[row][i] = '.';
flip(i, a, b);
}
}
void flip(int i, int a, int b) {
col[i] = col[i] ^ 1;
diag1[i+a] = diag1[i+a] ^ 1;
diag2[b-i] = diag2[b-i] ^ 1;
}
vector<vector<string>> ans;
vector<bool> col;
vector<bool> diag1;
vector<bool> diag2;
}; | true |
e818c41c05c3532c2541a6cf69bf58d0b59bafdb | C++ | SamsonHunk/FPS-level-gen | /Honours/Honours.cpp | UTF-8 | 27,477 | 3.046875 | 3 | [
"MIT"
] | permissive | #include <cstdlib>
#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>
#include <iostream>
#include <writer.h>
#include "document.h"
#include "filewritestream.h"
#include "Rooms.h"
using namespace rapidjson;
//grid dimensions
int size;
//max players in the map
int maxPlayers = 8;
std::string fileName = "test";
enum TileType
{
Empty,
Floor,
Wall,
Cover,
Spawn
};
//Data for each pixel of the map
struct AreaPixel
{
TileType tile;
float heat;
Room::RoomType roomType;
};
//storage for data representation of generated level
std::vector<AreaPixel> area;
//heat map image
sf::Image heatMap;
//heat map texture
sf::Texture heatTexture;
int roomTileSize = 5; //minumum size of a room measurement
int maxHeirarchy = 6; //generation variable to control how many rooms to make
//sfml rectangles to visualise the created level
std::vector<Room> rooms;
//sfml circles to visualise the spawn points
std::vector<sf::CircleShape> spawns;
//small function to ease accessing and organising data in the vector
int index(int x, int y)
{
return x + size * y;
}
int index(sf::Vector2i xy)
{
return xy.x + size * xy.y;
}
float getDist(sf::Vector2f room0, sf::Vector2f room1)
{
return sqrt(std::pow(room0.x - room1.x, 2) + std::pow(room0.y - room1.y, 2));
}
//function encompassing the level generation
void generate();
//function to generate a heatmap for a room
void generateHeat(Room* room);
//function to insert a new room into the structure
void drawRoom(sf::Vector2f pos, sf::Vector2f size, Room::RoomType type);
//generate and parse a new level file of the currently displayed level
void outputFile();
int main()
{
bool showHeatMap = false;
//determine how big the map is going to be
std::cout << "How large is the map area? 100x100 min" << std::endl;
std::cin >> size;
std::cout << "How many players will the map support?" << std::endl;
std::cin >> maxPlayers;
srand(time(NULL));
//reserve the container in memory
area.reserve(size*size);
//generate the level
generate();
sf::Sprite heatSprite;
heatSprite.setTexture(heatTexture);
//render and show the final level
sf::RenderWindow window(sf::VideoMode(size, size), "Output");
sf::RenderWindow heatWindow(sf::VideoMode(size, size), "Heatmap");
while (window.isOpen() && heatWindow.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
window.close();
heatWindow.close();
}
if (event.type == sf::Event::KeyReleased && event.key.code == sf::Keyboard::A)
{//press the a button to make a new level
//reset the level
for (int it = 0; it < area.size(); it++)
{
area[it].tile = Empty;
area[it].heat = 0;
area[it].roomType = Room::Empty;
}
rooms.clear();
spawns.clear();
//make a new one
generate();
}
if (event.type == sf::Event::KeyReleased && event.key.code == sf::Keyboard::S)
{//press s to generate the json level file
std::cout << "Enter level file name: ";
std::cin >> fileName;
outputFile();
}
if (event.type == sf::Event::KeyReleased && event.key.code == sf::Keyboard::H)
{//press h to show the heatmap overlay
showHeatMap = !showHeatMap;
}
}
window.clear();
for (int it = rooms.size() - 1; it > -1; it--)
//for (int it = 0; it < rooms.size(); it++)
{//draw all the room graphics
window.draw(rooms[it].shape);
}
if (showHeatMap)
{
window.draw(heatSprite);
}
for (int it = 0; it < spawns.size(); it++)
{
window.draw(spawns[it]);
}
window.display();
//display the heatmap
heatWindow.clear(sf::Color::Transparent);
heatWindow.draw(heatSprite);
heatWindow.display();
}
return 0;
}
void generate()
{
std::cout << "Creating the base" << std::endl;
//figure out the center of the grid
int center = (size / 2);
int roomCount = 0;
Base base;
//generate the initial room, no other room in the map can be bigger than this room
base.generate(sf::Vector2f(center, center), size);
base.arrayIndex = 0;
int generationHeriarchy = base.heirarchy; //current position in the generation loop
//center the first room into the center of the screen
base.shape.setPosition(base.shape.getPosition().x - base.shape.getSize().x, base.shape.getPosition().y - base.shape.getSize().y);
rooms.push_back(base);
//index storage to improve efficiency moving through the vector
int roomIndex = 0;
do
{//generate the rooms in a flower pattern around the parent room until we reach the end of the heirarchy loop
NormalRoom temp;
generationHeriarchy /= 2;
//check the current room and see if it needs more rooms attatched to it
if (rooms[roomIndex].heirarchy > 1)
{
for (int it = 0; it < rooms[roomIndex].heirarchy; it++)
{
std::cout << "Attaching child room on layer " + std::to_string(generationHeriarchy) + " ";
temp.heirarchy = generationHeriarchy;
temp.parentIndex = roomIndex;
//it may be the case that it's just not possible to attach a new room
int iterations = 500;
bool intersectFlag = false;
do
{//keep trying to connect a new room to the current room but make sure that it does not intersect with another room
iterations--;
//choose a random point on the parent's shape edge to attatch the new room to, make sure it doesn't intersect with another room
sf::Vector2f point = rooms[temp.parentIndex].shape.getPosition();
sf::Vector2f roomSize = rooms[temp.parentIndex].shape.getSize();
//choose a random edge to shove the room onto and what direction to generate the shape to
//we have to offset the shape as all shapes are drawn from their top left corner
int dir = rand() % 4;
switch (dir)
{
case 0: // left edge
point.x -= roomTileSize;
point.y += rand() % (int)roomSize.y;
break;
case 1: //upper edge
point.x += rand() % (int)roomSize.x;
point.y -= roomTileSize;
break;
case 2: //right edge
point.y += rand() % (int)roomSize.y;
point.x += roomTileSize + roomSize.x;
break;
case 3: //bottom edge
point.x += rand() % (int)roomSize.x;
point.y += roomSize.y + roomTileSize;
break;
}
//generate the shape with the chosen point in mind
temp.generate(point, rooms[temp.parentIndex].sizeConstraint);
roomSize = temp.shape.getSize();
//we have to offset it again if it is above or to the left of the parent, remember the origin of the shape is the top left corner
switch (dir)
{
case 0:
temp.shape.move(sf::Vector2f(-roomSize.x, 0));
break;
case 1:
temp.shape.move(sf::Vector2f(0, -roomSize.y));
break;
}
intersectFlag = false;
//now finally check if the shape overlaps another shape
for (int it = 0; it < rooms.size(); it++)
{
if (rooms[it].shape.getGlobalBounds().intersects(temp.shape.getGlobalBounds()))
{
intersectFlag = true;
break;
}
}
//if the shape does not overlap another shape then we can finalise it as a valid room
if (!intersectFlag)
{
roomCount++;
temp.arrayIndex = roomCount;
rooms.push_back(temp);
switch (dir)
{
case 0:
std::cout << "on the left edge: ";
break;
case 1:
std::cout << "on the upper edge: ";
break;
case 2:
std::cout << "on the right edge: ";
break;
case 3:
std::cout << "on the bottom edge: ";
break;
}
}
} while (intersectFlag && iterations != 0);
if (iterations == 0)
{
std::cout << "Failed" << std::endl;
}
else
{
std::cout << "Success" << std::endl;
}
}
}
roomIndex++;
} while (generationHeriarchy != 0);
//after we create the rooms we need to connect them together with corridors
//all rooms need to be connected to the closest room of the same heirarchy and their parent room but make sure that they dont intersect with anyone
roomIndex = 0;
do
{
if (rooms[roomIndex].parentIndex != -1)
{//if the room has a parent, make a corridor connecting them together
Corridor tempCorridor;
if (tempCorridor.generate(&rooms[roomIndex], &rooms[rooms[roomIndex].parentIndex]))
{
roomCount++;
tempCorridor.arrayIndex = roomCount;
rooms.push_back(tempCorridor);
}
}
for (int it = 0; it < rooms.size(); it++)
{//connect each room on the same heirarchy level together
Corridor tempCorridor;
if (it != roomIndex && rooms[it].type != Room::CorridorType && rooms[it].heirarchy == rooms[roomIndex].heirarchy)
{
if (tempCorridor.generate(&rooms[roomIndex], &rooms[it]))
{
bool intersectFlag = false;
//check that the corridor doesn't intersect with other rooms
for (int collisionIt = 0; collisionIt < rooms.size(); collisionIt++)
{
if (collisionIt != it && collisionIt != roomIndex && rooms[collisionIt].shape.getGlobalBounds().intersects(tempCorridor.shape.getGlobalBounds()))
{
intersectFlag = true;
//if the corridor intersects with something then delete the corridor from both the target rooms
rooms[roomIndex].connections.pop_back();
rooms[it].connections.pop_back();
break;
}
}
//if there is no other intersection then we can create the corridor
if (!intersectFlag)
{
roomCount++;
tempCorridor.arrayIndex = roomCount;
rooms.push_back(tempCorridor);
}
}
}
}
roomIndex++;
if (roomIndex >= rooms.size())
{
std::cout << "Unable to make any corridors" << std::endl;
break;
}
} while (rooms[roomIndex].type != Room::CorridorType);
//at the end check all the rooms and make sure they have at least two connections
for (int it = 0; it < rooms.size(); it++)
{
if (rooms[it].type != Room::RoomType::CorridorType && rooms[it].connections.size() < 3)
{
//create a lookup vector of valid rooms we can connect a corridor to
struct RoomLookup
{
int roomIndex;
float distance;
};
std::vector<RoomLookup> validRooms;
for (int roomIt = 0; roomIt < rooms.size(); roomIt++)
{
if (rooms[roomIt].type != Room::RoomType::CorridorType && it != roomIt)
{
RoomLookup newRoom;
newRoom.distance = getDist(rooms[it].shape.getPosition(), rooms[roomIt].shape.getPosition());
newRoom.roomIndex = roomIt;
validRooms.push_back(newRoom);
}
}
//with the lookup table try and attatch a corridor to the closest possible room
bool loopFlag = true;
float minDistance = 0;
float maxDistance = 9999999;
int currentRoomIndex = 0;
int trys = 0;
while (loopFlag && trys <= validRooms.size())
{
maxDistance = 99999999999999;
//figure out the next closest room
for (int roomIt = 0; roomIt < validRooms.size(); roomIt++)
{
if (validRooms[roomIt].distance < maxDistance && validRooms[roomIt].distance > minDistance)
{
currentRoomIndex = validRooms[roomIt].roomIndex;
maxDistance = validRooms[roomIt].distance;
}
}
//now try and connect a corridor to the room
Corridor tempCorridor;
bool intersectFlag = false;
if (tempCorridor.generate(&rooms[currentRoomIndex], &rooms[it]))
{
//check that the corridor doesn't intersect with other rooms
for (int collisionIt = 0; collisionIt < rooms.size(); collisionIt++)
{
if (collisionIt != it && collisionIt != currentRoomIndex && rooms[collisionIt].shape.getGlobalBounds().intersects(tempCorridor.shape.getGlobalBounds()))
{
intersectFlag = true;
//if the corridor intersects with something then delete the corridor from both the target rooms
rooms[currentRoomIndex].connections.pop_back();
rooms[it].connections.pop_back();
break;
}
}
//if there is no other intersection then we can create the corridor
if (!intersectFlag)
{
roomCount++;
tempCorridor.arrayIndex = roomCount;
rooms.push_back(tempCorridor);
loopFlag = false;
}
}
trys++;
minDistance = maxDistance;
}
}
}
//write the rooms into the data structure and generate the walls
//initialise the structure as empty
area.clear();
AreaPixel emptyPixel;
emptyPixel.heat = 0;
emptyPixel.tile = Empty;
emptyPixel.roomType = Room::RoomType::Empty;
for (int it = 0; it < area.capacity(); it++)
{
area.push_back(emptyPixel);
}
std::cout << "Generating walls" << std::endl;
//first create bare floor of each room
for (int it = 0; it < rooms.size(); it++)
{
drawRoom(rooms[it].shape.getPosition(), rooms[it].shape.getSize(), rooms[it].type);
}
//run edge detection and colour the edges in as walls
for (int y = 0; y < size; y++)
{
for (int x = 1; x < size - 1; x++)
{
if ((area[index(x - 1, y)].tile == Empty || area[index(x + 1, y)].tile == Empty) && area[index(x, y)].tile == Floor)
{
area[index(x, y)].tile = Wall;
}
}
}
for (int x = 0; x < size; x++)
{
for (int y = 1; y < size - 1; y++)
{
if ((area[index(x, y - 1)].tile == Empty || area[index(x, y + 1)].tile == Empty) && area[index(x, y)].tile == Floor)
{
area[index(x, y)].tile = Wall;
}
}
}
//figure out a heat map of the map and place cover in areas to reduce that heat
for (int it = 0; it < rooms.size(); it++)
{
if (rooms[it].type != Room::CorridorType)
{// dont put cover in the corridors, only in the open areas
std::cout << "Generating heat for room " + std::to_string(it) << std::endl;
generateHeat(&rooms[it]);
}
}
//Now we look over the map and assign room patterns to each room to be used for spawning cover and spawn points
//determine the two rooms that are furthest away from each other, the rooms can't be corridors or the central room
int a, b;
float highestDistance = 0.f;
for (int roomA = 0; roomA < rooms.size(); roomA++)
{
if (rooms[roomA].type == Room::NormalType)
{
for (int roomB = 0; roomB < rooms.size(); roomB++)
{
if (rooms[roomB].type == Room::NormalType)
{
//for each room, check the distance between each other room, recording the highest distance we find
//get the center of each point to compare to
sf::Vector2f posA, posB, dir;
posA = rooms[roomA].shape.getPosition();
posA.x += rooms[roomA].shape.getSize().x / 2.f;
posA.y += rooms[roomA].shape.getSize().y / 2.f;
posB = rooms[roomB].shape.getPosition();
posB.x += rooms[roomB].shape.getSize().x / 2.f;
posB.y += rooms[roomA].shape.getSize().y / 2.f;
dir.x = posB.x - posA.x;
dir.y = posB.y - posA.y;
float dist = sqrt(dir.x * dir.x + dir.y * dir.y);
if (dist > highestDistance)
{
a = roomA;
b = roomB;
highestDistance = dist;
}
}
}
}
}
//now we have the two furthest rooms apart, make them the team objective rooms
rooms[a].pattern = Room::RoomPattern::Objective;
rooms[b].pattern = Room::RoomPattern::Objective;
rooms[a].shape.setFillColor(sf::Color::Red);
rooms[b].shape.setFillColor(sf::Color::Blue);
//the base should always be an arena as it is in the middle
rooms[0].pattern = Room::RoomPattern::Arena;
//now figure out what kind of room each of the other rooms are depending on the distance between them, the spawns and the middle
//each objective room needs a chokepoint connected to them
for (int it = 0; it < rooms.size(); it++)
{
if (rooms[it].pattern == Room::RoomPattern::Null && rooms[it].type != Room::RoomType::CorridorType)
{//check if the room connects to either team base
for (int conIt = 0; conIt < rooms[it].connections.size(); conIt++)
{
if (rooms[it].connections[conIt].roomIndex == a || rooms[it].connections[conIt].roomIndex == b)
{
rooms[it].pattern = Room::RoomPattern::ChokePoint;
rooms[it].shape.setFillColor(sf::Color::Magenta);
break;
}
}
}
}
//each room that is connected to the center and not a chokepoint is an arena
for (int it = 0; it < rooms.size(); it++)
{
if (rooms[it].pattern == Room::RoomPattern::Null && rooms[it].type != Room::RoomType::CorridorType)
{
for (int conIt = 0; conIt < rooms[it].connections.size(); conIt++)
{
if (rooms[it].connections[conIt].roomIndex == 0)
{
rooms[it].pattern = Room::RoomPattern::Arena;
rooms[it].shape.setFillColor(sf::Color::Yellow);
}
}
}
}
//everything else is a flank
for (int it = 0; it < rooms.size(); it++)
{
if (rooms[it].type != Room::RoomType::CorridorType && rooms[it].pattern == Room::RoomPattern::Null)
{
rooms[it].pattern = Room::RoomPattern::Flank;
}
}
int totalSpawnCount = 0;
//now create an amount of spawn points in each room depending on what kind of room it is
for (int it = 1; it < rooms.size(); it++)
{
int spawnCount = 0;
if (rooms[it].type != Room::RoomType::CorridorType)
{
std::cout << "Generating spawns for room " + std::to_string(it);
std::cout << std::endl;
switch (rooms[it].pattern)
{
case Room::RoomPattern::Objective:
spawnCount = maxPlayers / 2;
break;
case Room::RoomPattern::Arena:
spawnCount = maxPlayers / 3;
break;
case Room::RoomPattern::ChokePoint:
spawnCount = maxPlayers / 2;
break;
case Room::RoomPattern::Flank:
spawnCount = 2;
break;
default:
break;
}
//for each spawn needed to be generated
if (spawnCount > 0)
{
//create a profile of the heat in the room
struct RoomTile
{
float averageHeat = 0;
sf::Vector2i pos;
TileType type;
bool isSource = false;
};
std::vector<RoomTile> room;
std::vector<sf::CircleShape> generatedSpawns;
sf::Vector2f roomSize = rooms[it].shape.getSize();
sf::Vector2f roomPos = rooms[it].shape.getPosition();
float minRoomHeat = 99999999999999;
float maxRoomHeat = 0;
float averageRoomHeat = 0;
int numOfSources = 0;
for (int y = 0; y < roomSize.y; y += roomTileSize)
{
for (int x = 0; x < roomSize.x; x += roomTileSize)
{
RoomTile newTile;
newTile.pos.x = x + roomPos.x;
newTile.pos.y = y + roomPos.y;
newTile.type = area[index(newTile.pos)].tile;
//get the average heat of the room tile
for (int tileY = 0; tileY < roomTileSize; tileY++)
{
for (int tileX = 0; tileX < roomTileSize; tileX++)
{
newTile.averageHeat += area[index(roomPos.x + x + tileX, roomPos.y + y + tileY)].heat;
if (area[index(roomPos.x + x + tileX, roomPos.y + y + tileY)].heat >= 999999999.f)
{
newTile.isSource = true;
numOfSources++;
}
}
}
newTile.averageHeat /= roomTileSize * roomTileSize;
room.push_back(newTile);
//don't let the high heat value from a heat source muddy the room averages
if (!newTile.isSource)
{
//record entire room temperature data
if (newTile.averageHeat > maxRoomHeat)
{
maxRoomHeat = newTile.averageHeat;
}
else if (newTile.averageHeat < minRoomHeat)
{
minRoomHeat = newTile.averageHeat;
}
averageRoomHeat += newTile.averageHeat;
}
}
}
averageRoomHeat /= (room.size() - numOfSources);
//now place spawn points in the room in the places with the lowest amount of relative heat
for (int spawnIt = 0; spawnIt < spawnCount; spawnIt++)
{
//point to a random tile in the room
int pointer = rand() % room.size();
int initialPos = pointer;
float targetHeat = minRoomHeat;
bool foundTile = false;
//check that the tile we are pointing to is a valid place to put a spawn point at
do
{
//we can't put a spawn point inside a wall or in space >.>
if (room[pointer].type != TileType::Wall && room[pointer].type != TileType::Empty)
{
//check the heat of the tile
if (room[pointer].averageHeat <= targetHeat)
{
sf::CircleShape newSpawn;
newSpawn.setPosition(sf::Vector2f(room[pointer].pos.x, room[pointer].pos.y));
newSpawn.setRadius(1.f);
newSpawn.setFillColor(sf::Color::Cyan);
foundTile = true;
//check the distance between the selected spawn and each other generated spawn
for (int i = 0; i < generatedSpawns.size(); i++)
{
sf::Vector2f checkPos = generatedSpawns[i].getPosition();
if (sqrt(std::pow(checkPos.x - newSpawn.getPosition().x, 2) + std::pow(checkPos.y - newSpawn.getPosition().y, 2)) < (roomTileSize * 2))
{
foundTile = false;
break;
}
}
//check that the selected tile is not too near a corridor entrance (heat source)
if (foundTile)
{
for (int i = 0; i < room.size(); i++)
{
if (room[i].isSource)
{
sf::Vector2i checkPos = room[i].pos;
if (sqrt(std::pow(checkPos.x - newSpawn.getPosition().x, 2) + std::pow(checkPos.y - newSpawn.getPosition().y, 2)) < (roomTileSize * 1.25f))
{
foundTile = false;
break;
}
}
}
}
//if we didn't find any spawn points too close then save the spawn
if (foundTile)
{
generatedSpawns.push_back(newSpawn);
}
}
}
if (!foundTile)
{
//if we have not found a good tile on this point then move the pointer up by one
pointer++;
if (pointer >= room.size())
{
pointer = 0;
}
}
//if we made a whole loop of the room increase the heat limit
if (pointer == initialPos)
{
targetHeat += .2f;
}
} while (targetHeat < (maxRoomHeat - .2f) && !foundTile);
}
for (int i = 0; i < generatedSpawns.size(); i++)
{
spawns.push_back(generatedSpawns[i]);
}
}
}
}
std::cout << "Rendering heatmap" << std::endl;
//generate the heatmap image from the data structure
heatMap.create(size, size, sf::Color::Black);
sf::Color heatcolor = sf::Color::Red;
for (int y = 0; y < size; y++)
{
for (int x = 0; x < size; x++)
{
float heat = area[index(x, y)].heat;
if (heat >= 6969.f)
{
heatMap.setPixel(x, y, sf::Color::Magenta);
}
else
{
heatcolor.r = (int)(heat * 25.f) + heatMap.getPixel(x, y).r;
heatMap.setPixel(x, y, heatcolor);
}
}
}
heatMap.createMaskFromColor(sf::Color::Black);
//load the generated map into a texture
heatTexture.loadFromImage(heatMap);
std::cout << "Done!" << std::endl;
}
void drawRoom(sf::Vector2f pos, sf::Vector2f size, Room::RoomType type)
{
//save the room data into the final output
for (int y = 0; y < size.y; y++)
{
for (int x = 0; x < size.x; x++)
{
area[index(pos.x + x, pos.y + y)].tile = Floor;
area[index(pos.x + x, pos.y + y)].roomType = type;
}
}
}
void outputFile()
{
std::cout << "Writing file..." << std::endl;
//write the array into a json file
FILE* fp = fopen(("output/" + fileName + ".json").data(), "wb");
char writeBuffer[65536];
FileWriteStream stream(fp, writeBuffer, sizeof(writeBuffer));
Writer<FileWriteStream> writer(stream);
writer.StartObject();
writer.Key("Size");
writer.Int(size);
writer.Key("Data");
writer.StartArray();
for (int it = 0; it < area.size(); it++)
{
writer.Int(area[it].tile);
}
writer.EndArray();
writer.Key("Spawns");
writer.StartArray();
for (int it = 0; it < spawns.size(); it++)
{
writer.StartArray();
writer.Double(spawns[it].getPosition().x);
writer.Double(spawns[it].getPosition().y);
writer.EndArray();
}
writer.EndArray();
writer.EndObject();
fclose(fp);
std::cout << "Done!" << std::endl;
}
void generateHeat(Room* room)
{
struct particle
{
sf::Vector2i pos;
Room::Direction dir;
float heat;
bool isNew;
bool isSource;
};
std::vector<particle> particles;
//generate a heat map for each room defining which areas of the map are the most dangerous
for (int it = 0; it < room->connections.size(); it++) //each room connection is a heat source
{
//reset the particles
particles.clear();
Room::Connection* source = &room->connections[it];
//we only need to move the heat along the single room
int travelDistance;
if (source->dir == Room::Left || source->dir == Room::Right)
{
travelDistance = room->shape.getSize().x;
}
else
{
travelDistance = room->shape.getSize().y;
}
//generate the initial particle
particle newParticle;
newParticle.pos = sf::Vector2i(source->pos.x, source->pos.y);
newParticle.dir = source->dir;
newParticle.heat = 0.5f;
newParticle.isNew = true;
newParticle.isSource = true;
sf::Vector2i nextPos;
//lambda function for the particle generation
auto generateParticle = [&](sf::Vector2i pos, particle parentParticle)
{//rules for particle generation
if (area[index(pos)].tile != Wall)
{
newParticle.heat = parentParticle.heat;
newParticle.pos = pos;
//check there is not another particle already there in the same place
bool isUnique = true;
for (int it = 0; it < particles.size(); it++)
{
if (newParticle.pos == particles[it].pos)
{
isUnique = false;
break;
}
}
if (isUnique)
{
particles.push_back(newParticle);
}
}
};
particles.push_back(newParticle);
newParticle.isSource = false;
for (int distance = 0; distance < travelDistance; distance++)
{
int currentParticleCount = particles.size();
//for each new particle use the generation rules to figure out where to spawn the next particle
for (int particle = 0; particle < currentParticleCount; particle++)
{
if (particles[particle].isNew)
{
particles[particle].isNew = false;
//try and generate 3 new particles in a triangle pointing in the particle's direction
switch (particles[particle].dir)
{
case Room::Up:
nextPos = particles[particle].pos;
nextPos.y -= 1;
generateParticle(nextPos, particles[particle]);
nextPos.x -= 1;
generateParticle(nextPos, particles[particle]);
nextPos.x += 2;
generateParticle(nextPos, particles[particle]);
break;
case Room::Left:
nextPos = particles[particle].pos;
nextPos.x -= 1;
generateParticle(nextPos, particles[particle]);
nextPos.y -= 1;
generateParticle(nextPos, particles[particle]);
nextPos.y += 2;
generateParticle(nextPos, particles[particle]);
break;
case Room::Right:
nextPos = particles[particle].pos;
nextPos.x += 1;
generateParticle(nextPos, particles[particle]);
nextPos.y -= 1;
generateParticle(nextPos, particles[particle]);
nextPos.y += 2;
generateParticle(nextPos, particles[particle]);
break;
case Room::Down:
nextPos = particles[particle].pos;
nextPos.y += 1;
generateParticle(nextPos, particles[particle]);
nextPos.x -= 1;
generateParticle(nextPos, particles[particle]);
nextPos.x += 2;
generateParticle(nextPos, particles[particle]);
break;
default:
break;
}
}
}
}
//now record the particles to the data structure
for (int count = 0; count < particles.size(); count++)
{
if (!particles[count].isSource)
{
area[index(particles[count].pos)].heat += particles[count].heat;
}
else
{
area[index(particles[count].pos)].heat += 999999999999.f;
}
}
}
} | true |
cbf5a992c35105b5bb3ccebc6a88d09908b4dcc2 | C++ | windystrife/UnrealEngine_NVIDIAGameWorks | /Engine/Source/Runtime/Core/Public/Misc/FrameValue.h | UTF-8 | 1,698 | 2.953125 | 3 | [
"MIT",
"LicenseRef-scancode-proprietary-license"
] | permissive | // Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreGlobals.h"
/**
* This struct allows you to cache a value for a frame, and automatically invalidates
* when the frame advances.
* If the value was set this frame, IsSet() returns true and GetValue() is valid.
*/
template<typename ValueType>
struct TFrameValue
{
private:
uint64 FrameSet;
TOptional<ValueType> Value;
public:
/** Construct an OptionaType with a valid value. */
TFrameValue(const ValueType& InValue)
: FrameSet(GFrameCounter)
{
Value = InValue;
}
TFrameValue(ValueType&& InValue)
: FrameSet(GFrameCounter)
{
Value = InValue;
}
/** Construct an OptionalType with no value; i.e. unset */
TFrameValue()
: FrameSet(GFrameCounter)
{
}
/** Copy/Move construction */
TFrameValue(const TFrameValue& InValue)
: FrameSet(GFrameCounter)
{
Value = InValue;
}
TFrameValue(TFrameValue&& InValue)
: FrameSet(GFrameCounter)
{
Value = InValue;
}
TFrameValue& operator=(const TFrameValue& InValue)
{
Value = InValue;
FrameSet = GFrameCounter;
return *this;
}
TFrameValue& operator=(TFrameValue&& InValue)
{
Value = InValue;
FrameSet = GFrameCounter;
return *this;
}
TFrameValue& operator=(const ValueType& InValue)
{
Value = InValue;
FrameSet = GFrameCounter;
return *this;
}
TFrameValue& operator=(ValueType&& InValue)
{
Value = InValue;
FrameSet = GFrameCounter;
return *this;
}
public:
bool IsSet() const
{
return Value.IsSet() && FrameSet == GFrameCounter;
}
const ValueType& GetValue() const
{
checkf(FrameSet == GFrameCounter, TEXT("Cannot get value on a different frame"));
return Value.GetValue();
}
}; | true |
584330a68795999d64b9dbc5bd957d000b674471 | C++ | krupowies/Loty | /Projekt Loty/Projekt Loty/getData.cpp | UTF-8 | 1,755 | 3.109375 | 3 | [] | no_license | #include "stdafx.h"
#include "getData.h"
void addPassenger(passenger *& pHead, std::string & name, int seat)
{
if (pHead == nullptr)
{
pHead = new passenger{ name,seat, nullptr };
}
else
{
passenger *temp = pHead;
if (seat < temp->seat)
{
passenger * newTemp = new passenger{ name, seat, pHead };
pHead = newTemp;
}
else
{
while ((temp->pNext != nullptr) && !(seat < temp->seat && seat > temp->seat))
temp = temp->pNext;
if (temp->pNext == nullptr)
temp->pNext = new passenger{name, seat, nullptr};
else
{
passenger * newTemp = new passenger{ name, seat, temp->pNext };
temp->pNext = newTemp;
}
}
}
}
flight * findFlight(flight * &pHead, std::string & wantedID, std::string & wantedCity, std::string & wantedDate)
{
if (pHead == nullptr)
{
return pHead = new flight{ wantedID, wantedCity, wantedDate, nullptr, nullptr };
}
else
{
if (pHead->ID == wantedID)
return pHead;
else
return findFlight(pHead->pNext, wantedID, wantedCity, wantedDate);
}
}
bool getData(std::string & inputFileName, flight *& pHead)
{
bool file = false;
std::ifstream inputFile(inputFileName);
if (inputFile)
{
file = true;
flight * wantedFlight = nullptr;
std::ifstream inputFile(inputFileName);
while (!inputFile.eof())
{
std::string ID = "";
std::string city = "";
std::string date = "";
std::string name = "";
int seat = 0;
inputFile >> ID;
inputFile >> city;
inputFile >> date;
inputFile >> name;
inputFile >> seat;
wantedFlight = findFlight(pHead, ID, city, date);
addPassenger(wantedFlight->pPassengers, name, seat);
}
inputFile.close();
}
return file;
}
| true |
e10407a1221450243f3a9e63870ee28b1957d0f7 | C++ | curtischung/UNR-CS | /CS-202/Project 9/project9/proj9.cpp | UTF-8 | 2,596 | 3.640625 | 4 | [] | no_license | #include <iostream>
#include <cstring>
#include "NodeQueue.h"
#include "ArrayQueue.h"
using std::endl;
using std::cout;
using std::cin;
int main () {
cout << "\n"
<< "//////////////////////////////////////////\n" <<
"////////// ArrayQueue Testing ///////////\n" <<
"/////////////////////////////////////////\n"
<< endl;
size_t size;
int num;
double num2;
cout << "Please enter an array size(size): ";
cin >> size;
cout << "Please enter an integer and double(int double): ";
cin >> num >> num2;
DataType value(num, num2);
ArrayQueue a_default;
ArrayQueue a_parametized(size, value);
cout << "Parametized Constructor: " << a_parametized << endl;
ArrayQueue a_copy(a_parametized);
cout << "Copy Constructor: " << a_copy << endl;
ArrayQueue a_assignment(size, value);
a_default = a_assignment;
cout << "Assignment Operator: " << a_default << endl;
cout << "Front(): " << a_default.front() << endl;
cout << "Back(): " << a_default.back() << endl;
cout << "Size of " << a_default.size() << endl;
cout << "Empty: " << std::boolalpha << a_default.empty() << endl;
cout << "Full: " << std::boolalpha << a_default.full() << endl;
a_default.clear();
DataType value2(11, 15.98);
DataType value3(12, 27.17);
ArrayQueue pp(3, value2);
cout << pp << endl;
pp.push(value3);
cout << pp << endl;
pp.pop();
cout << pp << endl;
cout << "Size of " << pp.size() << endl;
cout << "Empty: " << pp.empty() << endl;
cout << "Full: " << pp.full() << endl;
pp.clear();
cout << "\n"
<< "//////////////////////////////////////////\n" <<
"////////// NodeQueue Testing ////////////\n" <<
"/////////////////////////////////////////\n"
<< endl;
cout << "Please enter a NEW array size(size): ";
cin >> size;
cout << "Please enter a NEW integer and double(int double): ";
cin >> num >> num2;
DataType nvalue(num, num2);
NodeQueue n_default;
NodeQueue n_parametized(size, nvalue);
cout << "Parametized Constructor: " << n_parametized << endl;
NodeQueue n_copy(n_parametized);
cout << "Copy Constructor: " << n_copy << endl;
NodeQueue n_assignment(size, nvalue);
n_default = n_assignment;
cout << "Assignment Operator: " << n_default << endl;
DataType value4(12, 21.00);
DataType value5(1, 1.19);
ArrayQueue npp(3, value4);
cout << npp << endl;
npp.push(value5);
cout << npp << endl;
npp.pop();
cout << npp << endl;
cout << "Front(): " << npp.front() << endl;
cout << "Back(): " << npp.back() << endl;
cout << "Size of " << npp.size() << endl;
cout << npp.empty() << endl;
cout << npp.full() << endl;
npp.clear();
} | true |
e989a821dc731021ba5907fd9816032e0f056765 | C++ | dxmtb/OICodeShare | /SPOJ/spoj282.cpp | UTF-8 | 1,589 | 2.765625 | 3 | [] | no_license | /*
ID: dxmtb
PROG: spoj282 Muddy Fields
TIME: 2010.8.22
STATE: Solved
MEMO: 二分图最小覆盖建模
*/
#include <cstdio>
#include <cstring>
using namespace std;
const int MAXN=50,MAXM=MAXN*MAXN;
struct Node
{
int v;
Node *next;
Node(int a,Node *b):v(a),next(b){}
};
int R,C;
char map[MAXN][MAXN+10];
int r[MAXN][MAXN],c[MAXN][MAXN];
int mr,mc;
Node *g[MAXM];
void add(int a,int b)
{
g[a]=new Node(b,g[a]);
}
void build()
{
memset(r,-1,sizeof(r));
memset(c,-1,sizeof(c));
int timer=0;
for(int i=0;i<R;i++)
{
int j;
for(j=0;j<C;j++)
if (map[i][j]=='*')
if (j==0||map[i][j-1]=='.')
r[i][j]=timer++;
else r[i][j]=timer-1;
}
mr=timer;
timer=0;
for(int i=0;i<C;i++)
{
int j;
for(j=0;j<R;j++)
if (map[j][i]=='*')
if (j==0||map[j-1][i]=='.')
c[j][i]=timer++;
else c[j][i]=timer-1;
}
mc=timer;
for(int i=0;i<R;i++)
for(int j=0;j<C;j++)
if (map[i][j]=='*')
add(r[i][j],c[i][j]);
}
int mat[MAXM],match;
bool used[MAXM];
bool find(int u)
{
for(Node *p=g[u];p;p=p->next)
{
int i=p->v;
if (!used[i])
{
used[i]=true;
if (mat[i]==-1||find(mat[i]))
{
mat[i]=u;
return true;
}
}
}
return false;
}
void hungary()
{
memset(mat,-1,sizeof(mat));
match=0;
for(int i=0;i<mr;i++)
{
memset(used,false,sizeof(used));
if (find(i))
match++;
}
}
int main()
{
int t;
scanf("%d\n",&t);
for(int i=0;i<t;i++)
{
memset(map,0,sizeof(map));
memset(g,0,sizeof(g));
scanf("%d%d\n",&R,&C);
for(int j=0;j<R;j++)
scanf("%s\n",map[j]);
build();
hungary();
printf("%d\n",match);
}
return 0;
}
| true |
8746998df7d43f92a17970a25d5cfd6292748eec | C++ | qli51/treasure | /code/sort/mergesort.cpp | UTF-8 | 1,046 | 3.234375 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
void merge(vector<int>& a,int left,int middle,int right){
int i=left;
int j=middle+1;
int *store=new int[right-left+1];
int index=0;
while(i<middle && j<right){
if(a[i]<a[j]){
store[index++]=a[i++];
}
else if(a[i]>a[j]){
store[index++]=a[j++];
}
}
while(i<middle){
store[index++]=a[i++];
}
while(j<right){
store[index++]=a[j++];
}
for(int i=0;i<right-left+1;i++){
a[left+i]=store[i];
}
}
void mergesort(vector<int>& a,int left,int right){
if(left>=right) return;
int middle=(left+right)/2;
mergesort(a,left,middle);
mergesort(a,middle+1,right);
merge(a,left,middle,right);
}
int main(){
int n;
cin>>n;
int num;
vector<int> store;
for(int i=0;i<n;i++){
cin>>num;
store.push_back(num);
}
mergesort(store,0,store.size()-1);
for(int i=0;i<store.size();i++){
cout<<store[i]<<' ';
}
}
| true |
000ce9802b929463d6ba2145be98020b71f4e3d5 | C++ | J-AugustoManzano/livro_Eixos-C-CPP | /Fontes/Cap03/CPP/C03EX06.cpp | UTF-8 | 270 | 2.953125 | 3 | [] | no_license | // C03EX06.CPP
#include <iostream>
#include <ciso646>
using namespace std;
int main()
{
int N;
cout << "Entre um valor inteiro: "; cin >> N;
cin.ignore(80, '\n');
cout << "\n";
if (not (N >= 3))
{
cout << N << endl;
}
return 0;
}
| true |
459d4117ee5dc01de0fdfbfd71b185ee1c499cbc | C++ | RawanMoukalled/ShaunGames_3 | /game1/cannon.cpp | UTF-8 | 1,402 | 3.09375 | 3 | [] | no_license | #include "cannon.h"
#include "game1scene.h"
/**
* \file cannon.cpp
* \brief Contains Cannon class definition
*/
/**
* Sets the cannonimage and initializes variables.
*/
Cannon::Cannon(QObject *parent) :
QObject(parent)
{
this->setPixmap(QPixmap("pictures/cannon.png"));
setScale(0.3);
setTransformOriginPoint(0,45);
setPos(290,210);
setZValue(0);
}
/**
* Frees allocated memory.
*/
Cannon::~Cannon() {
}
/**
* Checks the key that triggered the event.
* If the key was a left or right arrow key, the cannon rotates left or right.
* If the key was a space, a sheep is thrown.
*/
void Cannon::keyPressEvent(QKeyEvent *event) {
if (event->key() == Qt::Key_Left) {
rotateCannon(false);
}
else if (event->key() == Qt::Key_Right) {
rotateCannon(true);
}
else if (event->key() == Qt::Key_Space) {
Game1Scene *s = static_cast<Game1Scene*>(scene());
s->fireSheep();
}
}
/**
* Rotates the cannon.
*/
void Cannon::rotateCannon(bool toTheRight) {
int rot;
if (toTheRight) {
rot = rotation()+5;
if (rot >= 360) {
rot = rot - 360;
}
setRotation(rot);
}
else {
rot = rotation()-5;
if (rot < 0) {
rot = rot + 360;
}
}
setRotation(rot);
Game1Scene *s = static_cast<Game1Scene*>(scene());
s->moveCurrentSheep(toTheRight);
}
| true |
2fadb97bc9c4f9a91febc664cbbb1e84ae390eaf | C++ | hasw7569/Myhobby | /Problem_solving/5052_트라이.cpp | UTF-8 | 975 | 3.046875 | 3 | [] | no_license | #include<stdio.h>
struct Trie
{
Trie* trie[10];
bool finish;
Trie()
{
finish = 0;
for (int i = 0; i < 10; i++)
trie[i] = 0;
}
~Trie()
{
for (int i = 0; i < 10; i++)
delete trie[i];
}
bool find(const char* pos)
{
if (*pos != '\0' && finish) return true;
if (*pos == '\0' && finish) return false;
if (trie[*pos - '0'] != NULL)
return trie[*pos - '0']->find(pos + 1);
}
void insert(const char* pos)
{
if (*pos == '\0')
{
finish = 1;
return;
}
else
{
if (trie[*pos - '0'] == NULL)
trie[*pos - '0'] = new Trie();
trie[*pos - '0']->insert(pos + 1);
}
}
};
int t, n;
char input[10000][11];
int main()
{
scanf("%d", &t);
while (t--)
{
Trie res;
scanf("%d", &n);
bool flag = 0;
for (int i = 0; i < n; i++)
{
scanf(" %s", &input[i]);
res.insert(input[i]);
}
for (int i = 0; i < n; i++)
{
if (res.find(input[i])) flag = 1;
}
if (flag) printf("NO\n");
else printf("YES\n");
}
return 0;
} | true |
25e02f58e1d18550c0bb9dca0a4239817b21e683 | C++ | tonilsz/AlphaOmega | /Source/AlphaOmega/ProceduralLandscape.cpp | UTF-8 | 7,233 | 2.546875 | 3 | [] | no_license | // Fill out your copyright notice in the Description page of Project Settings.
#include "AlphaOmega.h"
#include "ProceduralLandscape.h"
/** Sets up the values to generate the landscape*/
void AProceduralLandscape::GenerateMesh() {
// Setup example height data
int32 NumberOfPoints = (widthSections + 1) * (lenghtSections + 1);
heightValues.Empty();
heightValues.AddDefaulted(widthSections + 1);
for (int k = 0; k < widthSections + 1; ++k)
heightValues[k].childs.AddDefaulted(lenghtSections + 1);
// Generate the height values
GenerateSmoothTerrain(smoothStep);
//GenerateHeights(1);
// We only need to call the desired method to build the landscape
BuildLandscape(size.X, size.Y, widthSections, lenghtSections, heightValues, smoothNormals, useUniqueTexture);
}
/** Generates the height for the mesh using randomSeed*/
void AProceduralLandscape::GenerateHeights(int smoothStep) {
FRandomStream RngStream = FRandomStream::FRandomStream(randomSeed);
int32 i, j;
// Fill height data with random values
for (i = 0; i <= widthSections;) {
for (j = 0; j <= lenghtSections;) {
heightValues[i][j] = RngStream.FRandRange(0, size.Z);
for (int k = 1; k < smoothStep; k++)
RngStream.FRandRange(0, size.Z);
j += smoothStep;
}
i += smoothStep;
}
}
/** Generates the normal vale smoothed for each vertex based on generated heights*/
void AProceduralLandscape::PrecalculateSmoothNormals() {
// Clean the values
smoothValues.Empty();
smoothValues.AddDefaulted(widthSections + 1);
for (int k = 0; k < widthSections + 1; ++k)
smoothValues[k].childs.AddDefaulted(lenghtSections + 1);
// This vales will be used several times
float widthStep = size.X / widthSections;
float lengthStep = size.Y / lenghtSections;
// Fill height data with random values
for (int32 i = 0; i <= widthSections; ++i) {
for (int32 j = 0; j <= lenghtSections; ++j) {
// We use the top vertex for the first and we rotate clockwise
// By default we use the vector direction for distance between vertex
FVector v0 = (FVector::ForwardVector * widthStep) + FVector(0.f, 0.f, heightValues[i][j]);
if (i < widthSections)
v0 = FVector(widthStep, 0, heightValues[i + 1][j]);
FVector v1 = (FVector::RightVector * lengthStep) + FVector(0.f, 0.f, heightValues[i][j]);
if (j < lenghtSections)
v1 = FVector(0, lengthStep, heightValues[i][j + 1]);
FVector v2 = (-FVector::ForwardVector * widthStep) + FVector(0.f, 0.f, heightValues[i][j]);
if (i > 0)
v2 = FVector(-widthStep, 0, heightValues[i - 1][j]);
FVector v3 = -(FVector::RightVector * lengthStep) + FVector(0.f, 0.f, heightValues[i][j]);
if (j > 0)
v3 = FVector(0, -lengthStep, heightValues[i][j - 1]);
// Calculate the new normals
FVector n0 = FVector::CrossProduct(v0, v1).GetSafeNormal();
FVector n1 = FVector::CrossProduct(v1, v2).GetSafeNormal();
FVector n2 = FVector::CrossProduct(v2, v3).GetSafeNormal();
FVector n3 = FVector::CrossProduct(v3, v0).GetSafeNormal();
smoothValues[i][j] = (n0 + n1 + n2 + n3) / 4;
}
}
}
/** With the heigth generated we need to calculate the blank positions with interpolation*/
void AProceduralLandscape::InterpolateTerrain(int smoothStep) {
// Loop all terrain interpolating values
for (int32 i = 0; i < widthSections + 1; i++) {
for (int32 j = 0; j < lenghtSections + 1; j++) {
// We need use diferent value of smooth step when we are in last positions, but we fill by default with smooth step
int32 localSmoothStep = smoothStep;
// First index to interpolate
int32 backIndex = (j / smoothStep) * smoothStep;
// If we are in last postions and length sections isn't multiple of smoothStep we need to reevaluate it
while (backIndex + localSmoothStep > lenghtSections)
--localSmoothStep;
// Second index to interpolate
int32 nextIndex = backIndex + localSmoothStep;
// Position between next and back
float interpolationPosition = (float)(j % smoothStep) / smoothStep;
if (smoothInterpolation)
interpolationPosition = FMath::SmoothStep(backIndex, nextIndex, j);
// Assing the interpolated value to the array
heightValues[i][j] = InterpolateVertex(heightValues[i][backIndex], heightValues[i][nextIndex], interpolationPosition);
// If we are in a node we need to interpolate in X direction to
if ((i % smoothStep == 0) && (j % smoothStep == 0)) {
// We need use diferent value of smooth step when we are in last positions, but we fill by default with smooth step
localSmoothStep = smoothStep;
// If we are in last postions and length sections isn't multiple of smoothStep we need to reevaluate it
while (i + localSmoothStep > widthSections)
--localSmoothStep;
// Loop in X direction
for (int k = 1; k <= localSmoothStep; k++) {
// Position between next and back, note that we allways use smoothStep here for better smoothing, if we use localSmoothStep it will go to 0 faster
interpolationPosition = (float)k / smoothStep;
if (smoothInterpolation)
interpolationPosition = FMath::SmoothStep(i, i + smoothStep, i + k);
// Assing the interpolated value to the array
heightValues[i + k][j] = InterpolateVertex(heightValues[i][j], heightValues[i + localSmoothStep][j], interpolationPosition);
}
}
}
}
}
/** Makes the interpolation between a and b using alpha and the interpolation mode desired*/
float AProceduralLandscape::InterpolateVertex(const float a, const float b, const float alpha) {
// Call the desired method to interpolate
switch (interpolationMode) {
case EInterpolationModes::IM_Circular_in:
return FMath::InterpCircularIn(a, b, alpha);
case EInterpolationModes::IM_Circular_out:
return FMath::InterpCircularOut(a, b, alpha);
case EInterpolationModes::IM_Circular_in_out:
return FMath::InterpCircularInOut(a, b, alpha);
case EInterpolationModes::IM_Ease_in:
return FMath::InterpEaseIn(a, b, alpha, exponential);
case EInterpolationModes::IM_Ease_out:
return FMath::InterpEaseOut(a, b, alpha, exponential);
case EInterpolationModes::IM_Ease_in_out:
return FMath::InterpEaseInOut(a, b, alpha, exponential);
case EInterpolationModes::IM_Expo_in:
return FMath::InterpExpoIn(a, b, alpha);
case EInterpolationModes::IM_Expo_out:
return FMath::InterpExpoOut(a, b, alpha);
case EInterpolationModes::IM_Expo_in_out:
return FMath::InterpExpoInOut(a, b, alpha);
case EInterpolationModes::IM_Sin_in:
return FMath::InterpSinIn(a, b, alpha);
case EInterpolationModes::IM_Sin_out:
return FMath::InterpSinOut(a, b, alpha);
case EInterpolationModes::IM_Sin_in_out:
return FMath::InterpSinInOut(a, b, alpha);
case EInterpolationModes::IM_Linear:
default:
return FMath::Lerp(a, b, alpha);
}
}
/** Generates the height for the mesh using randomSeed*/
void AProceduralLandscape::GenerateSmoothTerrain(int smoothStep){
// Generate the deired heights
GenerateHeights(smoothStep);
// Interpolate the values of the calculated heights
InterpolateTerrain(smoothStep);
// If required pprecalcule normals
if (smoothNormals)
PrecalculateSmoothNormals();
}
FVector AProceduralLandscape::GetSmoothFromIndex(int32 i, int32 j) {
return smoothValues[i][j];
}
| true |
80016bdde184c5738d955f92b85dde13b0e7e619 | C++ | Skywt2003/codes | /XJOI/Level2/XJOI3595 欧拉函数/eular.cpp | UTF-8 | 388 | 2.515625 | 3 | [] | no_license | #include<cstdio>
#include<cstring>
#include<iostream>
#include<cmath>
using namespace std;
int n,ans;
inline void Build_Phi(){
long long x=n;ans=n;
for (long long i=2;i<sqrt(n)&&x>1;i++) if (x%i==0){
ans=ans/i*(i-1);
while (x%i==0) x/=i;
}
if (x>1) ans=ans/x*(x-1);
}
int main(){
scanf("%d",&n);
Build_Phi();
printf("%d\n",ans);
return 0;
} | true |
23547e226ac2ea2bf915a90e3719f91bbe05c779 | C++ | zhangyanuuuuu/760p2 | /src/v2.cpp | UTF-8 | 5,284 | 2.875 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
#include <math.h>
#include <assert.h>
#include "cg_user.h"
#define DEBUG
using namespace std;
const string delimiter = " \t\n\r";
const double alpha = 1.0;
const double delta_h = 0.01;
//data structure definition
struct pin {
double px;
double py;
int netNum;
};
struct gate {
double gx;
double gy;
double width;
};
typedef vector<int> net;
//global variables
int chipWidth, chipHeight, numGates, numNets, numPins;
double Unit;
gate* Gates;
net* Nets;
pin* Pins;
//////////////////////////////////////////
// //
// parser //
// //
//////////////////////////////////////////
void
parse(char* fileName)
{
string line;
srand(time(NULL));
ifstream inFile(fileName);
if (inFile.is_open()) {
//readin the first line to get the chip width, height, and Unit
inFile >> chipWidth >> chipHeight >> Unit;
//readin the second line to get the num of gates and nets
inFile >> numGates >> numNets;
#ifdef DEBUG
cout<<"chip width is "<<chipWidth<<" and chip height is "<<chipHeight<<endl;
cout<<"unit size is "<<Unit<<endl;
cout<<"number of gates is "<<numGates<<" and num nets is "<<numNets<<endl;
#endif
Gates = new gate [numGates + 1];
for (int i = 1; i <= numGates; i++) {
Gates[i].gx = rand() % chipWidth;
Gates[i].gy = rand() % chipHeight;
}
Nets = new net [numNets + 1];
//escape the current line
getline(inFile, line);
//temp variables
int count, netConnect, netNum;
for (int i = 1; i <= numGates; i++) {
getline(inFile,line);
#ifdef DEBUG
cout << line << endl;
#endif
stringstream ss(line);
ss >> count;
#ifdef DEBUG
assert(count == i);
#endif
ss >> netConnect;
Gates[i].width = Unit*netConnect;
for (int j = 0; j < netConnect; j++) {
ss >> netNum;
Nets[netNum].push_back(i);
}
}
getline(inFile, line);
stringstream ss(line);
ss >> numPins;
#ifdef DEBUG
cout<<"Num of pins is "<<numPins<<endl;
#endif
Pins = new pin [numPins + 1];
for (int i = 1; i <= numPins; i++) {
getline(inFile, line);
stringstream ss(line);
ss >> count;
#ifdef DEBUG
assert(count == i);
#endif
ss >> Pins[i].netNum >> Pins[i].px >> Pins[i].py;
}
} else {
cout<<"Unable to open file\n";
exit(-1);
}
#ifdef DEBUG
for (int i = 1; i <= numGates; i++) {
printf("Gate %d is initialized in (%f,%f), with width %f\n", i, Gates[i].gx, Gates[i].gy, Gates[i].width);
}
for (int i = 1; i <= numPins; i++) {
printf("Pin %d is at location(%f,%f)\n", i, Pins[i].px, Pins[i].py);
}
#endif
}
//////////////////////////////////////////
// //
// calculate halfPerim //
// //
//////////////////////////////////////////
/*
double halfPerim(net* Net) {
double max_x = 0.0;
double min_x = 0.0;
double max_y = 0.0;
double min_y = 0.0;
for (int i = 0; i < Net->size(); i++) {
max_x += exp(Net[i]->gx/alpha);
min_y += exp(-Net[i]->gy/alpha);
max_y += exp(Net[i]->gx/alpha);
min_y += exp(-Net[i]->gy/alpha);
}
max_x = alpha * log(max_x);
min_x = -alpha * log(min_x);
max_y = alpha * log(max_y);
min_y = -alpha * log(min_y);
}
*/
double
myvalue(double *x, INT n)
{
double sumAllNets = 0.0;
// x if formatted as gate[1].x->position0, gate[1].y->position1, gate[2].x->p2, gate[2].y->p3...
for (int i = 1; i <= numNets; i++) {
double sum_xp = 0.0;
double sum_xn = 0.0;
double sum_yp = 0.0;
double sum_yn = 0.0;
int index_x, index_y;
for (unsigned int j = 0; j < Nets[i].size(); j++) {
index_x = 2*Nets[i][j] - 2;
index_y = 2*Nets[i][j] - 1;
sum_xp += exp(x[index_x]/alpha);
sum_xn += exp(-x[index_x]/alpha);
sum_yp += exp(x[index_y]/alpha);
sum_yn += exp(-x[index_y]/alpha);
}
sumAllNets += alpha*(log(sum_xp) + log(sum_xn) + log(sum_yp) + log(sum_yn));
}
return sumAllNets;
}
void mygrad(double *g, double *x, INT n) {
double v_new, v_old;
for (int i = 0; i < n; i++) {
v_old = myvalue(x, n);
x[i] += delta_h;
v_new = myvalue(x, n);
g[i] = (v_new - v_old) / delta_h;
x[i] -= delta_h;
}
}
//////////////////////////////////////////
// //
// main function //
// //
//////////////////////////////////////////
int
main(int argc, char *argv[])
{
if (argc < 2) {
printf("Usage: ./exe <filename>\n");
exit(-1);
}
parse(argv[1]);
//put the value of gate position to array x
//pointer to the x[i] vector
double *x = new double [numGates*2];
for (int i = 1; i <= numGates; i++) {
x[2*(i-1)] = Gates[i].gx;
x[2*(i-1)+1] = Gates[i].gy;
}
int n = numGates*2; //dimension of the x array
double cg_tol;
cg_stats Stats;
cg_parameter Parm;
int cg_return;
cg_default(&Parm);
cg_tol = 1.e-8;
//solve it
printf("FIRST CALL TO CG_DESCENT, cg_tol=%g\n", cg_tol);
cg_return = cg_descent(x, n, &Stats, &Parm, cg_tol, myvalue, mygrad, NULL, NULL);
#ifdef DEBUG
for (int i = 0; i < numGates; i++) {
printf("gate %d is at position (%f,%f)\n", i+1, x[2*i], x[2*i+1]);
}
cout<<"HPWL is "<<myvalue(x,numGates*2)<<endl;
#endif
}
| true |
ca746792683e40f14003e5e2c881e1c94b6fea51 | C++ | sejinik/Discovering_modern_cpp | /c++11/argc_argv_test.cpp | UTF-8 | 178 | 2.703125 | 3 | [] | no_license | #include <iostream>
using std::cout;
using std::endl;
int main(int argc, char* argv[]){
for(int i=0; i<argc;i++){
cout<<argv[i]<<endl;
}
return 0;
} | true |
d3c84a56978d77fcef19c5522b0a18e825ac1283 | C++ | kohn/kohn-zoj-sol | /zoj-1902.cpp | UTF-8 | 1,588 | 3.265625 | 3 | [] | no_license | #include "stdio.h"
#include "stdlib.h"
#include "string.h"
struct word
{
char string[17];
int money;
struct word *next;
};
int Hashing(char target[17])
{
int i;
int Sum_Value=0;
for(i=0;target[i]!=0;i++)
{
Sum_Value+=target[i]-'a';
}
return Sum_Value%100;
}
struct word *NewWord(char target[17],int m)
{
struct word *pWord=(struct word*)malloc(sizeof(struct word));
strcpy(pWord->string,target);
pWord->money=m;
pWord->next=NULL;
return pWord;
}
int Search(struct word *t,char target[17])
{
int value=0;
struct word *pWord=t;
while(pWord!=NULL)
{
if(strcmp(t->string,target)==0)
{
return t->money;
}
pWord=pWord->next;
}
return 0;
}
int main()
{
int m,n;
int i;
struct word *word_in_dictionary[100],*temp;
char tempword[17];
int hash,tempmoney,sum_money;
memset(word_in_dictionary,NULL,sizeof(word_in_dictionary));
scanf("%d%d",&m,&n);
for(i=0;i<m;i++)
{
scanf("%s%d",tempword,&tempmoney);
hash=Hashing(tempword);/*get hashing valus of tempword*/
temp=NewWord(tempword,tempmoney);/*make a node and insert it into hashing table*/
temp->next=word_in_dictionary[hash];
word_in_dictionary[hash]=temp;
}
for(i=0;i<n;i++)
{
sum_money=0;
scanf("%s",tempword);
while(!(tempword[0]=='.'&&tempword[1]==0))
{
hash=Hashing(tempword);
sum_money+=Search(word_in_dictionary[hash],tempword);
scanf("%s",tempword);
}
printf("%d\n",sum_money);
}
return 0;
}
| true |
063f1930114b860b59d97e2f9e0417e02572bb66 | C++ | SergiiKusii/Cracker | /src/unhesher/UnhesherNative.cpp | UTF-8 | 373 | 2.546875 | 3 | [] | no_license | #include "UnhesherNative.h"
#include "unistd.h"
std::string UnhesherNative::Crypt(const HashType, const std::string& salt, const std::string& saltPrefix, const std::string& data)
{
auto fullSalt = saltPrefix + salt;
std::string result = crypt(data.c_str(), fullSalt.c_str());
return fullSalt.size() < result.size() ? result.substr(fullSalt.size() + 1) : "";
} | true |
d8269623a4b25b489ece99d0b75c20cbd8a33411 | C++ | StutiSulg/MovieProject | /LinkedList.h | UTF-8 | 839 | 3.125 | 3 | [] | no_license | //---------------------------------------------------------------------------
// LINKEDLIST.H
// A container that represents a Linked List
//---------------------------------------------------------------------------
// Linked list Class:
// -- inserts items into linked list
// -- removes items from linked list
// -- clear items from linked list
//---------------------------------------------------------------------------
#pragma once
#include <string>
#include <iostream>
#include <fstream>
#include "Item.h"
using namespace std;
class LinkedList
{
public:
LinkedList();
~LinkedList();
bool insert(Item *obj); //change this to take all sorts of objects
bool remove(Item *target); //change this to take all sorts of objects
void clear();
private:
struct Node
{
Item *data;
Node *next;
};
Node *headPtr;
};
| true |
4b634ba9062f6caf087f96542bf195be70d7b944 | C++ | cdjames/sagitta-runner | /main.cpp | UTF-8 | 2,885 | 2.546875 | 3 | [] | no_license | /*********************************************************************
** Author: Collin James
** Date: 7/9/17
** Description: Main routines Team Sagitta's infinite runner game
*********************************************************************/
#include <unistd.h>
#include <iostream>
#include "GameManager.hpp"
#include "MenuManager.hpp"
#include "NetworkManager.hpp"
void initScreen();
void exitCurses(WINDOW * win);
int runGame(WINDOW *win, vector<double> * timing_info, IPParams * ip_info);
int main(int argc, char const *argv[])
{
/* determine input */
IPParams ip_info = {"", -1};
if(argc == 3) {
ip_info.ip = argv[1];
ip_info.port = atoi(argv[2]);
}
WINDOW *win;
/* some setup */
readFromRandFile("vals.cjr", &rand_num_list); // set up random functions
createAllBlueprints(); // set up blueprints that objects use
initScreen();
int play = 1;
vector<double> timing_info; // to store and display timing info if enabled
/* play until user chooses to quit */
while (play == 1){
#ifdef TIMING
timing_info.clear();
play = runGame(win, &timing_info, &ip_info);
#else
play = runGame(win, NULL, &ip_info);
#endif
}
exitCurses(win);
#ifdef TIMING
if(timing_info.size() == 3) {
std::cout << "avg,max,min" << std::endl;
std::cout << timing_info[0] << "," << timing_info[1] << "," << timing_info[2] << std::endl;
}
#endif
return 0;
}
int runGame(WINDOW *win, vector<double> * timing_info, IPParams * ip_info){
std::string ip;
int port;
short playerdied = -1;
NetworkManager NM = NetworkManager();
if(ip_info->port > 0 && ip_info->ip.compare("") != 0)
NM.setConnParams(*ip_info);
MenuManager MM = MenuManager(&NM);
int play = MM.mainMenu(), score = 0, seed = -1;
while (play == 1 || play == 2){
int connectSuccess = NM.setPlayer();
if (connectSuccess == -1)
return MM.errorScreen();
NM.setDifficulty(MM.getDifficulty());
/* get the seed; time now + 2 seconds */
while((seed = NM.getSeed()) == -1) {
continue; // wait
}
cj_srand(seed); // called once per game
GameManager GM = GameManager(win, &NM);
GM.updateSettings(NM.getDifficulty() / 2);
playerdied = GM.run(timing_info); // runs until user presses q
MM.updateSettings(GM);
play = MM.gameOver();
if (play == 1)
play = MM.mainMenu();
if (play == 2)
MM.findGame();
}
return play;
}
void initScreen() {
initscr(); // Start curses mode
cbreak(); /* Line buffering disabled, Pass on everything to me */
keypad(stdscr, TRUE); /* I need that nifty F1 */
// scrollok(stdscr, FALSE);
timeout(DEF_TIMEOUT); // wait x Ms for user input before going to next getch() call
noecho(); // don't print user input
curs_set(0); // make cursor invisible if possible
refresh(); // put the printw on the screen
}
void exitCurses(WINDOW * win) {
delwin(win); // delete the window
endwin(); // End curses mode
}
| true |
0952282916f2e339ae570792e8eeda29d813bc7c | C++ | snacchus/DeferredRenderer | /src/graphics/SimpleImageEffect.hpp | UTF-8 | 935 | 2.609375 | 3 | [] | no_license | #ifndef SIMPLEIMAGEEFFECT_HPP
#define SIMPLEIMAGEEFFECT_HPP
#include "ImageEffect.hpp"
class Material;
class SimpleImageEffect : public ImageEffect
{
public:
explicit SimpleImageEffect(Entity* parent);
Material* material() { return m_material; }
const Material* material() const { return m_material; }
void setMaterial(Material* mat) { m_material = mat; }
bool isOutputLinear() const { return m_outputLinear; }
void setOutputLinear(bool val) { m_outputLinear = val; }
virtual void apply(const Texture2D* input, const RenderTexture* output) final;
virtual bool isGood() const final;
COMPONENT_ALLOW_MULTIPLE;
private:
Material* m_material;
bool m_outputLinear;
virtual void apply_json_impl(const nlohmann::json& json) final;
// cppcheck-suppress unusedPrivateFunction
void extractMaterial(const nlohmann::json& json);
static json_interpreter<SimpleImageEffect> s_properties;
};
#endif // SIMPLEIMAGEEFFECT_HPP | true |
0e5c1dfcb8b4750c2340dc7468e83c6a88651218 | C++ | ToLoveToFeel/LeetCode | /Cplusplus/_0668_Kth_Smallest_Number_in_Multiplication_Table/_0668_main.cpp | UTF-8 | 914 | 3.28125 | 3 | [] | no_license | // Created by WXX on 2021/2/27 23:44
#include <iostream>
using namespace std;
/**
* 执行用时:20 ms, 在所有 C++ 提交中击败了34.86%的用户
* 内存消耗:5.6 MB, 在所有 C++ 提交中击败了98.62%的用户
*/
class Solution {
public:
// 返回小于等于mid的数据个数,将每列中小于mid的数的个数相加即可
int get(int m, int n, int mid) {
int res = 0;
for (int i = 1; i <= n; i++)
res += min(m, mid / i);
return res;
}
int findKthNumber(int m, int n, int k) {
int l = 1, r = n * m;
while (l < r) {
int mid = l + r >> 1;
if (get(m, n, mid) >= k) r = mid;
else l = mid + 1;
}
return r;
}
};
int main() {
cout << Solution().findKthNumber(3, 3, 5) << endl; // 3
cout << Solution().findKthNumber(2, 3, 6) << endl; // 6
return 0;
}
| true |
895b10cd211954c1754e22f8cbbce4d6ce3010bf | C++ | Arcade-Bytes/Rifted | /Headers/AnimationComponent.h | UTF-8 | 1,152 | 2.796875 | 3 | [] | no_license | #ifndef ANIMATIONCOMPONENT_H
#define ANIMATIONCOMPONENT_H
#include <unordered_map>
#include <rapidjson/document.h>
#include <rapidjson/writer.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/filereadstream.h>
#include "Animation.h"
#include "ResourceManager.h"
class AnimationComponent
{
private:
// Player's sprite
sf::RectangleShape& shape;
// Map of animations, how many animations will it have
// Each animation is a vector of frames, and also contains the total duration of itself
std::unordered_map<std::string, Animation*> animations;
Animation* current_animation;
public:
AnimationComponent(sf::RectangleShape& shape);
~AnimationComponent();
/**
* Loads json document and fills frames with it
**/
void loadAnimationsFromJSON(const std::string& filepath);
/**
* Interacts with the animations
**/
void addAnimation(std::string key, std::vector<Frame*> frames, bool looped = false);
void playAnimation(const std::string key, bool mirror = false);
void stopCurrentAnimation();
void resetCurrentAnimation();
void skipCurrentAnimation();
};
#endif
| true |
b850743137aa7a9099030e03347c4f380eb55864 | C++ | Tudor67/Competitive-Programming | /LeetCode/Explore/March-LeetCoding-Challenge-2021/#Day#22_VowelSpellchecker_sol1_unordered_map_O((N+Q)L)_time_O((N+Q)L)_extra_space_68ms_34MB.cpp | UTF-8 | 1,943 | 3.234375 | 3 | [
"MIT"
] | permissive | class Solution {
private:
string getLowerForm(const string& WORD){
string lowerWord = WORD;
transform(WORD.begin(), WORD.end(), lowerWord.begin(), ::tolower);
return lowerWord;
}
string getVowelForm(const string& WORD){
string vowelWord;
for(int i = 0; i < (int)WORD.length(); ++i){
char c = tolower(WORD[i]);
if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'){
vowelWord += '#';
}else{
vowelWord += c;
}
}
return vowelWord;
}
public:
vector<string> spellchecker(vector<string>& wordList, vector<string>& queries) {
unordered_set<string> wordListSet(wordList.begin(), wordList.end());
unordered_map<string, string> capitalWordMap;
unordered_map<string, string> vowelWordMap;
for(const string& WORD: wordList){
string lowerWord = getLowerForm(WORD);
if(!capitalWordMap.count(lowerWord)){
capitalWordMap[lowerWord] = WORD;
}
string vowelWord = getVowelForm(WORD);
if(!vowelWordMap.count(vowelWord)){
vowelWordMap[vowelWord] = WORD;
}
}
vector<string> answer;
for(const string& QUERY: queries){
string lowerQuery = getLowerForm(QUERY);
string vowelQuery = getVowelForm(QUERY);
if(wordListSet.count(QUERY)){
answer.push_back(QUERY);
}else if(capitalWordMap.count(lowerQuery)){
answer.push_back(capitalWordMap[lowerQuery]);
}else if(vowelWordMap.count(vowelQuery)){
answer.push_back(vowelWordMap[vowelQuery]);
}else{
answer.push_back("");
}
}
return answer;
}
}; | true |
a587f110ad6f49b7f70d3a574a9008b68e595a14 | C++ | iron-phoenix/scan_opencl | /Lab2/main.cpp | UTF-8 | 4,934 | 2.84375 | 3 | [] | no_license | #include "cl.hpp"
#include <vector>
#include <fstream>
#include <iostream>
#include <iterator>
#include <iomanip>
#include <assert.h>
#define BLOCK_SIZE 256
struct scanner {
scanner(cl::Context& context, cl::Program& program, cl::CommandQueue& queue) :
context(context),
program(program),
queue(queue)
{
scan_kernel = cl::Kernel(program, "scan_blelloch");
add_kernel = cl::Kernel(program, "blocks_sum");
}
void scan(cl::Buffer const & buffer_input, cl::Buffer const & buffer_output, size_t const data_size, size_t const block_size) {
size_t range = round_block_size(data_size, block_size);
cl::Buffer buffer_block(context, CL_MEM_READ_WRITE, sizeof(float) * range / block_size);
if (data_size <= block_size) {
cl::KernelFunctor scan_b(scan_kernel, queue, cl::NullRange, cl::NDRange(range), cl::NDRange(block_size));
cl::Event event = scan_b(buffer_input, buffer_output, cl::__local(sizeof(float) * block_size), buffer_block, data_size);
event.wait();
} else {
cl::Buffer buffer_scan(context, CL_MEM_READ_WRITE, sizeof(float) * data_size);
cl::Buffer buffer_add(context, CL_MEM_READ_WRITE, sizeof(float) * range / block_size);
cl::KernelFunctor scan_f(scan_kernel, queue, cl::NullRange, cl::NDRange(range), cl::NDRange(block_size));
cl::Event event = scan_f(buffer_input, buffer_scan, cl::__local(sizeof(float) * block_size), buffer_block, data_size);
event.wait();
scan(buffer_block, buffer_add, range / block_size, block_size);
cl::KernelFunctor add(add_kernel, queue, cl::NullRange, cl::NDRange(range), cl::NDRange(block_size));
event = add(buffer_scan, buffer_output, buffer_add);
event.wait();
}
}
private:
cl::Context context;
cl::Program program;
cl::CommandQueue queue;
cl::Kernel scan_kernel;
cl::Kernel add_kernel;
static size_t round_block_size(size_t n, size_t block_size) {
size_t result = n;
if (n % block_size != 0) result += (block_size - n % block_size);
return result;
}
};
cl::Platform get_platform() {
std::vector<cl::Platform> all_platforms;
cl::Platform::get(&all_platforms);
if (all_platforms.size() == 0){
std::cout << " No platforms found. Check OpenCL installation!" << std::endl;
exit(1);
}
cl::Platform platform = all_platforms[1];
std::cout << "Using platform: " << platform.getInfo<CL_PLATFORM_NAME>() << std::endl;
return platform;
}
cl::Device get_device(cl::Platform& platform) {
std::vector<cl::Device> all_devices;
platform.getDevices(CL_DEVICE_TYPE_ALL, &all_devices);
if (all_devices.size() == 0){
std::cout << " No devices found. Check OpenCL installation!" << std::endl;
exit(1);
}
cl::Device device = all_devices[0];
std::cout << "Using device: " << device.getInfo<CL_DEVICE_NAME>() << std::endl;
return device;
}
cl::Program get_program(cl::Device& device, cl::Context& context, std::string const & program_file_name) {
std::ifstream kernel_file(program_file_name);
std::string kernel_code(std::istreambuf_iterator<char>(kernel_file), (std::istreambuf_iterator<char>()));
cl::Program::Sources sources(1, { kernel_code.c_str(), kernel_code.length() });
cl::Program program(context, sources);
if (program.build({ device }) != CL_SUCCESS){
std::cout << " Error building: " << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(device) << std::endl;
exit(1);
}
return program;
}
void read_data(std::ifstream& in, std::vector<float>& data, size_t size) {
data.resize(size);
for (size_t i = 0; i < size; ++i)
in >> data[i];
}
void write_data(std::ofstream& out, std::vector<float> const & data) {
out << std::fixed << std::setprecision(3);
for (size_t i = 0; i < data.size(); ++i)
out << data[i] << " ";
out << std::endl;
}
void main_program(cl::Device& device, cl::Context& context, cl::Program& program) {
size_t size = 0;
size_t const block_size = BLOCK_SIZE;
std::ifstream in("input.txt");
std::ofstream out("output.txt");
in >> size;
std::vector<float> input;
std::vector<float> output(size);
read_data(in, input, size);
cl::CommandQueue queue(context, device);
cl::Buffer buffer_input(context, CL_MEM_READ_ONLY, sizeof(float) * input.size());
cl::Buffer buffer_output(context, CL_MEM_READ_ONLY, sizeof(float) * input.size());
queue.enqueueWriteBuffer(buffer_input, CL_TRUE, 0, sizeof(float) * input.size(), &input[0]);
queue.finish();
scanner s(context, program, queue);
s.scan(buffer_input, buffer_output, size, block_size);
queue.enqueueReadBuffer(buffer_output, CL_TRUE, 0, sizeof(float) * input.size(), &output[0]);
write_data(out, output);
}
int main()
{
try {
cl::Platform default_platform = get_platform();
cl::Device default_device = get_device(default_platform);
cl::Context context({ default_device });
cl::Program program = get_program(default_device, context, "scan.cl");
main_program(default_device, context, program);
}
catch (std::exception &e) {
std::cout << std::endl << e.what() << std::endl;
}
return 0;
} | true |
8c6a60065af33992d7d1ef69ac7149caa555cfaf | C++ | tangjz/acm-icpc | /lydsy/4751.cpp | UTF-8 | 1,488 | 2.6875 | 3 | [
"Apache-2.0"
] | permissive | #include <stdio.h>
const int maxt = 101, maxn = 1001, maxo = 2001, lown = 11, maxst = 11;
int t, n, m, sz, out[maxo][4];
void addLine(int x1, int y1, int x2, int y2)
{
out[sz][0] = x1;
out[sz][1] = y1;
out[sz][2] = x2;
out[sz][3] = y2;
++sz;
}
void solve1(int n, int m)
{
if(n <= m)
for(int i = 1; i <= n; ++i)
{
addLine(i, 1, i, m);
if(i < n)
addLine(i, m, i + 1, 1);
}
else
for(int i = 1; i <= m; ++i)
{
addLine(1, i, n, i);
if(i < m)
addLine(n, i, 1, i + 1);
}
}
void solve2(int n)
{
int len = n, xL = 1, yL = 1, xR = len, yR = len, dir = 0, ofst = 0;
for( ; len > 3; --len, dir ^= 1, ofst = 1)
if(dir == 0)
{
addLine(xL, yL - ofst, xL, yR);
addLine(xL, yR, xR, yR);
++xL, --yR;
}
else
{
addLine(xR, yR + ofst, xR, yL);
addLine(xR, yL, xL, yL);
--xR, ++yL;
}
if(dir == 0)
{
addLine(xL, yL - ofst, xL, yR + ofst);
addLine(xL + 1 - ofst, yR + ofst, xR + ofst, yL + 1 - ofst);
addLine(xR + ofst, yL, xL, yL);
addLine(xL, yL, xR, yR);
}
else
{
addLine(xR, yR + ofst, xR, yL - (n > 4));
addLine(xR - 1 + (n > 4), yL - (n > 4), xL - ofst, yR - 1 + ofst);
addLine(xL - ofst, yR, xR, yR);
addLine(xR, yR, xL, yL);
}
}
int main()
{
scanf("%d", &t);
while(t--)
{
scanf("%d%d", &n, &m);
sz = 0;
if(n <= 2 || n != m)
solve1(n, m);
else
solve2(n);
printf("%d\n", sz);
for(int i = 0; i < sz; ++i)
printf("%d %d %d %d\n", out[i][0], out[i][1], out[i][2], out[i][3]);
}
return 0;
}
| true |
2d21c638ce4018d402392f3a1100d609d7dfaca8 | C++ | roberteliason/COM-09480-driver | /7seg4digDriver.ino | UTF-8 | 3,492 | 3.46875 | 3 | [] | no_license | /**
* Proof of concept code that drives a
* Sparkfun 4-digit 7-segment display.
* https://www.sparkfun.com/products/9480
*
* Datasheet:
* https://www.sparkfun.com/datasheets/Components/LED/7-Segment/YSD-439AY2B-35.pdf
*
* Add 100 Ohm resistors to pins 9-12
* or risk burning out segments.
*
* The quirk with this display is that you
* cannot address the digits individually,
* they share the same 'data bus'.
* So you have to flash them one by one,
* super fast in order to fool the eye.
*/
// Dedicate the pins
const int SEG_A = 2;
const int SEG_B = 3;
const int SEG_C = 4;
const int SEG_D = 5;
const int SEG_E = 6;
const int SEG_F = 7;
const int SEG_G = 8;
const int ELM_1 = 9;
const int ELM_2 = 10;
const int ELM_3 = 11;
const int ELM_4 = 12;
// An element maps to a digit on the display
// Setting these pins high lights up the segments
// that are toggled for those elements.
int elements[4] = {
ELM_1, ELM_2, ELM_3, ELM_4
};
// Enumerate the segments in each element
// Setting these pins LOW lights the segments up.
int segments[7] = {
SEG_A, SEG_B, SEG_C, SEG_D, SEG_E, SEG_F, SEG_G
};
// A digit is the shape, or which segments
// in each elements is toggled LOW to light up
// to make the representation of a number.
// Warning: Mind****s;
int digits[10][7] = {
{ 0,0,0,0,0,0,1 }, // 0
{ 1,0,0,1,1,1,1 }, // 1
{ 0,0,1,0,0,1,0 }, // 2
{ 0,0,0,0,1,1,0 }, // 3
{ 1,0,0,1,1,0,0 }, // 4
{ 0,1,0,0,1,0,0 }, // 5
{ 0,1,0,0,0,0,0 }, // 6
{ 0,0,0,1,1,1,1 }, // 7
{ 0,0,0,0,0,0,0 }, // 8
{ 0,0,0,1,1,0,0 }, // 9
};
// The integer we want to display (0-9999)
int number = 0;
// The individual digits in above number
// This will be automatically updated in the loop
int digitsInNumber[4] = {0,0,0,0};
/**
* Loop through the pins we plan to use
* and set them accordingly
*/
void setup() {
// init Segment pins
for (int pin = SEG_A; pin <= SEG_G; pin++) {
pinMode(pin, OUTPUT);
digitalWrite(pin, HIGH);
}
// init Element pins
for (int pin = ELM_1; pin <= ELM_4; pin++) {
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW);
}
}
/**
* Turn all elements off
*/
void disableElements() {
for (int pin = ELM_1; pin <= ELM_4; pin++) {
digitalWrite(pin, LOW);
}
}
/**
* Turn all segments off
*/
void blankSegments() {
for (int seg = SEG_A; seg <= SEG_G; seg++) {
digitalWrite(seg, HIGH);
}
}
/**
* Update the segments with the set number
*/
void setSegments(int value) {
blankSegments();
for (int seg = 0; seg <= 6; seg++) {
digitalWrite(segments[seg], (digits[value][seg]==1) ? HIGH : LOW);
}
}
/**
* Update selected digit, enable
*/
void updateElement(int digit, int value) {
setSegments(value);
digitalWrite(digit, HIGH);
}
/**
* Split the number into it's digit components
* so that we can feed them one by one to the
* matching elements.
*/
void mapNumberToDigits(int * digitsInNumber, int number) {
digitsInNumber[0] = number / 1000 % 10;
digitsInNumber[1] = number / 100 % 10;
digitsInNumber[2] = number / 10 % 10;
digitsInNumber[3] = number % 10;
}
/**
* You loop me right round, baby right round
*/
void loop() {
number = millis() / 1000;
mapNumberToDigits(digitsInNumber, number);
// Loop through the elements one by one and
// flash the digit that corresponds to said
// element. Really, rally, fast. POV!
for (int dig = 0; dig <= 3; dig ++) {
disableElements();
updateElement( elements[dig], digitsInNumber[dig] );
}
}
| true |
211c6c8bde5b6f8a5c8ee9f17065e0658def14de | C++ | HoaLD20/CPP | /CPP201/Resource/Advanced C Plus Plus Programming - Working Files/Chapter 05/Chap0502.cpp | UTF-8 | 426 | 2.625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
/*cout.put('h');
cout.put('e');
cout.put('l');
cout.put('l');
cout.put('o');
cout.put(' ');
cout.put('w');
cout.put('o');
cout.put('r');
cout.put('l');
cout.put('d');
cout.put('!').put('\n');*/
cout << "hello, world!" << endl;
cout << "hello, world!" << flush;
cout << "hello, world!" << ends;
return 0;
}
| true |
29b6e797a2fe1fbe914f8e575c19681142152519 | C++ | mregorova/true_equation | /tests.cpp | UTF-8 | 1,819 | 2.84375 | 3 | [] | no_license | #include "tests.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
int equationTest(int numTest, double a, double b, double c, int numSols_main, double x1_main, double x2_main)
{
assert(isfinite(a));
assert(isfinite(b));
assert(isfinite(c));
assert(isfinite(x1_main));
assert(isfinite(x2_main));
//static int numTest = 0;
//numTest++;
double x1 = 0;
double x2 = 0;
int numSols = solve(a, b, c, &x1, &x2);
if (numSols != numSols_main)
{
printf("Test %d failed: a = %lg, b = %lg, c = %lg; Solutions: %lg %lg - Should be: %lg %lg",
numTest, a, b, c, x1, x2, x1_main, x2_main);
return 0;
}
else
{
if (!cmp_doubles(x1, x1_main) || !cmp_doubles(x2, x2_main))
{
printf("Test %d failed: a = %lg, b = %lg, c = %lg; Solutions: %lg %lg - Should be: %lg %lg",
numTest, a, b, c, x1, x2, x1_main, x2_main);
return 0;
}
else
{
printf("Test %d is succed\n", numTest);
return 1;
}
}
}
int runEquationTest()
{
int failed = 0;
if (equationTest(__LINE__, 0, 0, 0, -1, 0, 0) == 0) failed++; // number of test, a, b, c, amount of solutions, first solution, second solution
if (equationTest(__LINE__, 1, 2, -3, 2, 1, -3) == 0) failed++;
if (equationTest(__LINE__, 0, 4, 0, 1, 0, 0) == 0) failed++;
if (equationTest(__LINE__, 0, 2, -4, 1, 2, 0) == 0) failed++;
if (equationTest(__LINE__, 0, 0, 13, 0, 0, 0) == 0) failed++;
if (equationTest(__LINE__, 1, -1, 3, 0, 0, 0) == 0) failed++;
if (equationTest(__LINE__, 1, 4, 4, 1, -2, 0) == 0) failed++;
return failed;
} | true |
2a3ef0bf7035f8586cbab05eb5211ef94bc6fb97 | C++ | Ninja182/Coding | /C++/switch.cpp | UTF-8 | 460 | 3.328125 | 3 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
int main()
{
int num = 6;
switch ( num)
{
case 1 : cout << num << " : Monday\n" ; break ;
case 2 : cout << num << " : Tuesday\n" ; break ;
case 3 : cout << num << " : Wednesday\n" ; break ;
case 4 : cout << num << " : Thursday\n" ; break ;
case 5 : cout << num << " : Friday\n" ; break ;
default : cout << num << " : Weekend day\n" ;
}
return 0;
}
| true |
baa7b64c4da02d9328f209ae78c7904cea9a1699 | C++ | dzuberi/cache-coherency-project | /protocols/MESI_protocol.cpp | UTF-8 | 7,748 | 2.546875 | 3 | [] | no_license | #include "MESI_protocol.h"
#include "../sim/mreq.h"
#include "../sim/sim.h"
#include "../sim/hash_table.h"
extern Simulator *Sim;
/*************************
* Constructor/Destructor.
*************************/
MESI_protocol::MESI_protocol (Hash_table *my_table, Hash_entry *my_entry)
: Protocol (my_table, my_entry)
{
this->state = MESI_CACHE_I;
}
MESI_protocol::~MESI_protocol ()
{
}
void MESI_protocol::dump (void)
{
const char *block_states[8] = {"X","I","S","E","M","IM","ISE","SM"};
fprintf (stderr, "MESI_protocol - state: %s\n", block_states[state]);
}
void MESI_protocol::process_cache_request (Mreq *request)
{
//printf("state before:%d\n",state);
switch (state) {
case MESI_CACHE_I: do_cache_I(request); break;
case MESI_CACHE_S: do_cache_S(request); break;
case MESI_CACHE_E: do_cache_E(request); break;
case MESI_CACHE_M: do_cache_M(request); break;
default:
fatal_error ("Invalid Cache State for MESI Protocol\n");
}
//printf("state after:%d\n",state);
}
void MESI_protocol::process_snoop_request (Mreq *request)
{
//this->dump();
switch (state) {
case MESI_CACHE_I: do_snoop_I(request); break;
case MESI_CACHE_S: do_snoop_S(request); break;
case MESI_CACHE_E: do_snoop_E(request); break;
case MESI_CACHE_M: do_snoop_M(request); break;
case MESI_CACHE_IM: do_snoop_IM(request); break;
case MESI_CACHE_ISE: do_snoop_ISE(request); break;
case MESI_CACHE_SM: do_snoop_SM(request); break;
default:
fatal_error ("Invalid Cache State for MESI Protocol\n");
}
//this->dump();
}
inline void MESI_protocol::do_cache_I (Mreq *request)
{
switch(request->msg) {
case LOAD:
send_GETS(request->addr);
//state = MESI_CACHE_E;
state = MESI_CACHE_ISE;
Sim->cache_misses++;
break;
case STORE:
send_GETM(request->addr);
//state = MESI_CACHE_M;
state = MESI_CACHE_IM;
Sim->cache_misses++;
break;
default:
request->print_msg (my_table->moduleID,"ERROR");
fatal_error("Client: I state shouldn't see this message\n");
}
}
inline void MESI_protocol::do_cache_S (Mreq *request)
{
switch(request->msg) {
case LOAD:
send_DATA_to_proc(request->addr);
break;
case STORE:
send_GETM(request->addr);
state = MESI_CACHE_SM;
Sim->cache_misses++;
break;
default:
request->print_msg (my_table->moduleID,"ERROR");
fatal_error("Client: M state shouldn't see this message\n");
}
}
inline void MESI_protocol::do_cache_E (Mreq *request)
{
switch(request->msg) {
case LOAD:
send_DATA_to_proc(request->addr);
break;
case STORE:
state = MESI_CACHE_M;
Sim->silent_upgrades++;
send_DATA_to_proc(request->addr);
break;
default:
request->print_msg (my_table->moduleID,"ERROR");
fatal_error("Client: E state shouldn't see this message\n");
}
}
inline void MESI_protocol::do_cache_M (Mreq *request)
{
switch(request->msg) {
case LOAD:
case STORE:
send_DATA_to_proc(request->addr);
break;
default:
request->print_msg (my_table->moduleID,"ERROR");
fatal_error("Client: E state shouldn't see this message\n");
}
}
inline void MESI_protocol::do_snoop_I (Mreq *request)
{
switch(request->msg) {
case GETS:
break;
case GETM:
break;
case DATA:
//send_DATA_to_proc(request->addr);
//if(get_shared_line()){
// state=MESI_CACHE_S;
//}
//else state=MESI_CACHE_E;
break;
default:
request->print_msg (my_table->moduleID,"ERROR");
fatal_error("Client: I state shouldn't see this message\n");
}
}
inline void MESI_protocol::do_snoop_S (Mreq *request)
{
switch(request->msg) {
case GETS:
set_shared_line();
break;
case GETM:
set_shared_line();
state=MESI_CACHE_I;
break;
case DATA:
break;
default:
request->print_msg (my_table->moduleID,"ERROR");
fatal_error("Client: S state shouldn't see this message\n");
}
}
inline void MESI_protocol::do_snoop_E (Mreq *request)
{
switch(request->msg) {
case GETS:
//if(!get_shared_line()){
set_shared_line();
send_DATA_on_bus(request->addr,request->src_mid);
//}
//printf("%d\n",state);
state=MESI_CACHE_S;
break;
case GETM:
//if(!get_shared_line()){
send_DATA_on_bus(request->addr,request->src_mid);
//}
set_shared_line();
state=MESI_CACHE_I;
break;
case DATA:
break;
default:
request->print_msg (my_table->moduleID,"ERROR");
fatal_error("Client: E state shouldn't see this message\n");
}
}
inline void MESI_protocol::do_snoop_M (Mreq *request)
{
switch(request->msg) {
case GETS:
//if(!get_shared_line()){
set_shared_line();
send_DATA_on_bus(request->addr,request->src_mid);
//}
state=MESI_CACHE_S;
//set_shared_line();
break;
case GETM:
//if(!get_shared_line()){
set_shared_line();
send_DATA_on_bus(request->addr,request->src_mid);
//}
state=MESI_CACHE_I;
//set_shared_line();
break;
case DATA:
break;
default:
request->print_msg (my_table->moduleID,"ERROR");
fatal_error("Client: M state shouldn't see this message\n");
}
}
//intermediate state when I calls getM waiting for data
inline void MESI_protocol::do_snoop_IM (Mreq *request)
{
switch(request->msg) {
case GETS:
break;
case GETM:
break;
case DATA:
send_DATA_to_proc(request->addr);
state = MESI_CACHE_M;
break;
default:
request->print_msg (my_table->moduleID,"ERROR");
fatal_error("Client: IM state shouldn't see this message\n");
}
}
//intermediate state, when I calls getS to either choose E or S as state.
inline void MESI_protocol::do_snoop_ISE (Mreq *request)
{
switch(request->msg) {
case GETS:
//set_shared_line();
break;
case GETM:
break;
case DATA:
send_DATA_to_proc(request->addr);
if(get_shared_line()){
state = MESI_CACHE_S;
}
else state = MESI_CACHE_E;
break;
default:
request->print_msg (my_table->moduleID,"ERROR");
fatal_error("Client: ISE state shouldn't see this message\n");
}
}
//intermediate state when S calls getM waiting for data
inline void MESI_protocol::do_snoop_SM (Mreq *request)
{
switch(request->msg) {
case GETS:
set_shared_line();
break;
case GETM:
break;
case DATA:
send_DATA_to_proc(request->addr);
state = MESI_CACHE_M;
break;
default:
request->print_msg (my_table->moduleID,"ERROR");
fatal_error("Client: SM state shouldn't see this message\n");
}
}
| true |
e7a6f6ff6d13383dc482e08a2129bf8cc34dcd5c | C++ | AlecsGesser/ABC-Language-Compilers | /Syntactic Analysis/src/tabParse.hpp | UTF-8 | 3,820 | 2.546875 | 3 | [] | no_license | #ifndef tabParse_hpp
#define tabParse_hpp
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
void init_tab(vector<vector<int> >& tabParsing){
int size_H = 85, size_W = 60;
for(int i = 0 ; i < size_H ; i++){
vector<int> temp;
for(int j = 0 ; j < size_W ; j++){
temp.push_back(-1);
}
tabParsing.push_back(temp);
}
tabParsing[51][2] = 1;
tabParsing[52][2] = 3;
tabParsing[52][3] = 3;
tabParsing[52][7] = 2;
tabParsing[52][13] = 3;
tabParsing[52][15] = 3;
tabParsing[52][19] = 3;
tabParsing[52][26] = 3;
tabParsing[52][47] = 3;
tabParsing[53][2] = 13;
tabParsing[53][3] = 13;
tabParsing[53][13] = 13;
tabParsing[53][15] = 19;
tabParsing[53][19] = 13;
tabParsing[53][26] = 13;
tabParsing[54][15] = 31;
tabParsing[55][41] = 4;
tabParsing[55][43] = 5;
tabParsing[56][3] = 8;
tabParsing[56][13] = 6;
tabParsing[56][19] = 7;
tabParsing[56][26] = 9;
tabParsing[57][2] = 10;
tabParsing[57][3] = 10;
tabParsing[57][7] = 11;
tabParsing[57][13] = 10;
tabParsing[57][15] = 10;
tabParsing[57][19] = 10;
tabParsing[57][26] = 10;
tabParsing[57][47] = 10;
tabParsing[59][7] = 12;
tabParsing[60][2] = 15;
tabParsing[60][3] = 18;
tabParsing[60][13] = 14;
tabParsing[60][19] = 17;
tabParsing[60][26] = 16;
tabParsing[61][39] = 26;
tabParsing[61][46] = 27;
//tabParsing[62][3] = 24;
tabParsing[62][5] = 20;
tabParsing[62][6] = 21;
tabParsing[62][7] = 22;
tabParsing[62][8] = 23;
tabParsing[62][10] = 24;
tabParsing[62][45] = 25;
tabParsing[63][3] = 28;
tabParsing[63][13] = 28;
tabParsing[63][19] = 28;
tabParsing[63][26] = 28;
tabParsing[64][40] = 29;
tabParsing[64][45] = 30;
tabParsing[65][1] = 52;
tabParsing[65][7] = 34;
tabParsing[65][8] = 36;
tabParsing[65][10] = 35;
tabParsing[65][16] = 49;
tabParsing[65][18] = 64;
tabParsing[65][23] = 67;
tabParsing[65][24] = 69;
tabParsing[65][25] = 68;
tabParsing[65][27] = 39;
tabParsing[65][40] = 38;
tabParsing[66][1] = 33;
tabParsing[66][7] = 33;
tabParsing[66][8] = 33;
tabParsing[66][10] = 33;
tabParsing[66][16] = 33;
tabParsing[66][18] = 33;
tabParsing[66][20] = 32;
tabParsing[66][23] = 33;
tabParsing[66][24] = 33;
tabParsing[66][25] = 33;
tabParsing[66][27] = 33;
tabParsing[66][38] = 32;
tabParsing[66][40] = 33;
tabParsing[67][5] = 75;
tabParsing[67][6] = 75;
tabParsing[67][7] = 75;
tabParsing[67][8] = 75;
tabParsing[67][10] = 75;
tabParsing[67][27] = 76;
tabParsing[67][46] = 75;
tabParsing[68][40] = 40;
tabParsing[68][45] = 40;
tabParsing[68][46] = 41;
tabParsing[69][5] = 44;
tabParsing[69][6] = 46;
tabParsing[69][7] = 48;
tabParsing[69][8] = 47;
tabParsing[69][10] = 45;
tabParsing[70][43] = 43;
tabParsing[70][45] = 42;
tabParsing[71][29] = 56;
tabParsing[71][30] = 55;
tabParsing[71][31] = 53;
tabParsing[71][33] = 58;
tabParsing[71][35] = 57;
tabParsing[71][48] = 54;
tabParsing[72][21] = 50;
tabParsing[72][40] = 51;
tabParsing[73][5] = 59;
tabParsing[73][6] = 60;
tabParsing[73][7] = 63;
tabParsing[73][8] = 62;
tabParsing[73][10] = 61;
tabParsing[74][36] = 65;
tabParsing[74][49] = 66;
tabParsing[75][34] = 71;
tabParsing[75][40] = 70;
tabParsing[76][34] = 73;
tabParsing[76][40] = 73;
tabParsing[76][43] = 74;
tabParsing[79][5] = 80;
tabParsing[79][6] = 80;
tabParsing[79][7] = 80;
tabParsing[79][8] = 80;
tabParsing[79][10] = 80;
tabParsing[79][46] = 80;
tabParsing[80][37] = 77;
tabParsing[80][40] = 79;
tabParsing[80][45] = 79;
tabParsing[80][50] = 78;
tabParsing[81][5] = 84;
tabParsing[81][6] = 85;
tabParsing[81][7] = 86;
tabParsing[81][8] = 88;
tabParsing[81][10] = 87;
tabParsing[81][46] = 89;
tabParsing[82][37] = 81;
tabParsing[82][40] = 81;
tabParsing[82][42] = 83;
tabParsing[82][44] = 82;
tabParsing[82][45] = 81;
tabParsing[82][50] = 81;
}
#endif | true |
e4e4629578f03eef7ecad7c7c565003bc2fd431e | C++ | rschlenk87/AirQuest | /alvr_server/FFR.cpp | UTF-8 | 8,305 | 2.5625 | 3 | [
"MIT"
] | permissive | #include "FFR.h"
#include "Settings.h"
#include "resource.h"
#include "Utils.h"
using Microsoft::WRL::ComPtr;
using namespace d3d_render_utils;
namespace {
struct FoveationVars {
uint32_t targetEyeWidth;
uint32_t targetEyeHeight;
uint32_t optimizedEyeWidth;
uint32_t optimizedEyeHeight;
float focusPositionX;
float focusPositionY;
float foveationScaleX;
float foveationScaleY;
float boundStartX;
float boundStartY;
float distortedWidth;
float distortedHeight;
};
const float DEG_TO_RAD = (float)M_PI / 180;
#define INVERSE_DISTORTION_FN(a) atan(a);
const float INVERSE_DISTORTION_DERIVATIVE_IN_0 = 1; // d(atan(0))/dx = 1
float CalcBoundStart(float focusPos, float fovScale) {
return INVERSE_DISTORTION_FN(-focusPos * fovScale);
}
float CalcBoundEnd(float focusPos, float fovScale) {
return INVERSE_DISTORTION_FN((1.f - focusPos) * fovScale);
}
float CalcDistortedDimension(float focusPos, float fovScale) {
float boundEnd = CalcBoundEnd(focusPos, fovScale);
float boundStart = CalcBoundStart(focusPos, fovScale);
return boundEnd - boundStart;
}
float CalcOptimalDimensionForWarp(float scale, float distortedDim, float originalDim) {
float inverseDistortionDerivative = INVERSE_DISTORTION_DERIVATIVE_IN_0 * scale;
float gradientOnFocus = inverseDistortionDerivative / distortedDim;
return originalDim / gradientOnFocus;
}
float Align4Normalized(float scale, float originalDim) {
return float(int(scale * originalDim / 4.f) * 4) / originalDim;
}
float CalcOptimalDimensionForSlicing(float scale, float originalDim) {
return (1. + 3. * scale) / 4. * originalDim + 6;
}
FoveationVars CalculateFoveationVars() {
auto mode = Settings::Instance().m_foveationMode;
float targetEyeWidth = (float)Settings::Instance().m_renderWidth / 2;
float targetEyeHeight = (float)Settings::Instance().m_renderHeight;
auto leftEye = Settings::Instance().m_eyeFov[0];
// left and right side screen plane width with unit focal
float leftHalfWidth = tan(leftEye.left * DEG_TO_RAD);
float rightHalfWidth = tan(leftEye.right * DEG_TO_RAD);
// foveated center X assuming screen plane with unit width
float focusPositionX = leftHalfWidth / (leftHalfWidth + rightHalfWidth);
// align focus position to a number of pixel multiple of 4 to avoid blur and artifacts
if (mode == FOVEATION_MODE_SLICES) {
focusPositionX = Align4Normalized(focusPositionX, targetEyeWidth);
}
// NB: swapping top/bottom fov
float topHalfHeight = tan(leftEye.bottom * DEG_TO_RAD);
float bottomHalfHeight = tan(leftEye.top * DEG_TO_RAD);
float focusPositionY = topHalfHeight / (topHalfHeight + bottomHalfHeight);
focusPositionY += Settings::Instance().m_foveationVerticalOffset;
if (mode == FOVEATION_MODE_SLICES) {
focusPositionY = Align4Normalized(focusPositionY, targetEyeHeight);
}
//calculate foveation scale such as the "area" of the foveation region remains equal to (mFoveationStrengthMean)^2
// solve for {foveationScaleX, foveationScaleY}:
// /{ foveationScaleX * foveationScaleY = (mFoveationStrengthMean)^2
// \{ foveationScaleX / foveationScaleY = 1 / mFoveationShapeRatio
// then foveationScaleX := foveationScaleX / (targetEyeWidth / targetEyeHeight) to compensate for non square frame.
float foveationStrength = Settings::Instance().m_foveationStrength;
float foveationShape = Settings::Instance().m_foveationShape;
if (mode == FOVEATION_MODE_SLICES) {
foveationStrength = 1.f / (foveationStrength / 2.f + 1.f);
foveationShape = 1.f / foveationShape;
}
float scaleCoeff = foveationStrength * sqrt(foveationShape);
float foveationScaleX = scaleCoeff / foveationShape / (targetEyeWidth / targetEyeHeight);
float foveationScaleY = scaleCoeff;
if (mode == FOVEATION_MODE_SLICES) {
foveationScaleX = Align4Normalized(foveationScaleX, targetEyeWidth);
foveationScaleY = Align4Normalized(foveationScaleY, targetEyeHeight);
}
float optimizedEyeWidth = 0;
float optimizedEyeHeight = 0;
float boundStartX = 0;
float boundStartY = 0;
float distortedWidth = 0;
float distortedHeight = 0;
if (mode == FOVEATION_MODE_SLICES) {
optimizedEyeWidth = CalcOptimalDimensionForSlicing(foveationScaleX, targetEyeWidth);
optimizedEyeHeight = CalcOptimalDimensionForSlicing(foveationScaleY, targetEyeHeight);
}
else if (mode == FOVEATION_MODE_WARP) {
boundStartX = CalcBoundStart(focusPositionX, foveationScaleX);
boundStartY = CalcBoundStart(focusPositionY, foveationScaleY);
distortedWidth = CalcDistortedDimension(focusPositionX, foveationScaleX);
distortedHeight = CalcDistortedDimension(focusPositionY, foveationScaleY);
optimizedEyeWidth = CalcOptimalDimensionForWarp(foveationScaleX, distortedWidth, targetEyeWidth);
optimizedEyeHeight = CalcOptimalDimensionForWarp(foveationScaleY, distortedHeight, targetEyeHeight);
}
// round the frame dimensions to a number of pixel multiple of 32 for the encoder
auto optimizedEyeWidthAligned = (uint32_t)ceil(optimizedEyeWidth / 32.f) * 32;
auto optimizedEyeHeightAligned = (uint32_t)ceil(optimizedEyeHeight / 32.f) * 32;
//throw MakeException("%f %f %f %f %d", targetEyeHeight, focusPositionY, foveationScaleY, optimizedEyeHeight, optimizedEyeHeightAligned);
return { (uint32_t)targetEyeWidth, (uint32_t)targetEyeHeight, optimizedEyeWidthAligned, optimizedEyeHeightAligned,
focusPositionX, focusPositionY, foveationScaleX, foveationScaleY,
boundStartX, boundStartY, distortedWidth, distortedHeight };
}
}
void FFR::GetOptimizedResolution(uint32_t* width, uint32_t* height) {
auto fovVars = CalculateFoveationVars();
*width = fovVars.optimizedEyeWidth * 2;
*height = fovVars.optimizedEyeHeight;
}
FFR::FFR(ID3D11Device* device) : mDevice(device) {}
void FFR::Initialize(ID3D11Texture2D* compositionTexture) {
auto fovVars = CalculateFoveationVars();
ComPtr<ID3D11Buffer> foveatedRenderingBuffer = CreateBuffer(mDevice.Get(), fovVars);
std::vector<uint8_t> quadShaderCSO;
if (!ReadBinaryResource(quadShaderCSO, IDR_QUAD_SHADER)) {
throw MakeException(L"Failed to load resource for IDR_QUAD_SHADER.");
}
mQuadVertexShader = CreateVertexShader(mDevice.Get(), quadShaderCSO);
mOptimizedTexture = CreateTexture(mDevice.Get(), fovVars.optimizedEyeWidth * 2,
fovVars.optimizedEyeHeight, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB);
switch (Settings::Instance().m_foveationMode) {
case FOVEATION_MODE_DISABLED:
mOptimizedTexture = compositionTexture;
break;
case FOVEATION_MODE_SLICES:
{
std::vector<uint8_t> compressSlicesShaderCSO;
if (!ReadBinaryResource(compressSlicesShaderCSO, IDR_COMPRESS_SLICES_SHADER)) {
throw MakeException(L"Failed to load resource for IDR_COMPRESS_SLICES_SHADER.");
}
auto compressSlicesPipeline = RenderPipeline(mDevice.Get());
compressSlicesPipeline.Initialize({ compositionTexture }, mQuadVertexShader.Get(),
compressSlicesShaderCSO, mOptimizedTexture.Get(), foveatedRenderingBuffer.Get());
mPipelines.push_back(compressSlicesPipeline);
break;
}
case FOVEATION_MODE_WARP:
/*ComPtr<ID3D11Texture2D> horizontalBlurredTexture = CreateTexture(mDevice.Get(),
fovVars.targetEyeWidth * 2, fovVars.targetEyeHeight,
DXGI_FORMAT_R8G8B8A8_UNORM_SRGB);*/
//std::vector<uint8_t> horizontalBlurShaderCSO;
//if (!ReadBinaryResource(horizontalBlurShaderCSO, IDR_HORIZ_BLUR_SHADER)) {
// throw MakeException(L"Failed to load resource for IDR_HORIZ_BLUR_SHADER.");
//}
std::vector<uint8_t> distortionShaderCSO;
if (!ReadBinaryResource(distortionShaderCSO, IDR_DISTORTION_SHADER)) {
throw MakeException(L"Failed to load resource for IDR_DISTORTION_SHADER.");
}
/*mHorizontalBlurPipeline.Initialize({ compositionTexture }, mQuadVertexShader.Get(),
horizontalBlurShaderCSO, horizontalBlurredTexture.Get(), foveatedRenderingBuffer.Get());*/
auto distortPipeline = RenderPipeline(mDevice.Get());
distortPipeline.Initialize({ compositionTexture }, mQuadVertexShader.Get(),
distortionShaderCSO, mOptimizedTexture.Get(), foveatedRenderingBuffer.Get());
//mPipelines.push_back(horizontalBlurPipeline);
mPipelines.push_back(distortPipeline);
break;
}
}
void FFR::Render() {
for (auto &p : mPipelines) {
p.Render();
}
}
ID3D11Texture2D* FFR::GetOutputTexture() {
return mOptimizedTexture.Get();
} | true |
545e4f91df4bbe379d97c05d6348ee3e4e19bfc9 | C++ | Pennliu/uva | /699.cpp | UTF-8 | 2,260 | 2.6875 | 3 | [] | no_license | /*
* =====================================================================================
*
* Filename: 699.cpp
*
* Description:
*
* Version: 1.0
* Created: 2014年10月03日 21时28分41秒
* Revision: none
* Compiler: gcc
*
* Author: loop (),
* Organization:
*
* =====================================================================================
*/
#include <stdlib.h>
#include <iostream>
#include <cstdio>
#include <vector>
#include <string>
#include <cstring>
#include <cassert>
using namespace std;
struct node
{
int v;
struct node *l, *r;
};
node* node_new()
{
node* n = (node* )malloc(sizeof(node));
if (n)
{
n->l = n->r = NULL;
n->v = 0;
}
return n;
}
void tree_free(node* tree)
{
if (tree)
{
tree_free(tree->l);
tree_free(tree->r);
free(tree);
}
return;
}
node* tree_build()
{
int v;
scanf("%d", &v);
if (v == -1) return NULL;
node* t = node_new();
assert(t);
t->v = v;
t->l = tree_build();
t->r = tree_build();
return t;
}
static int ans[200];
static int mid;
void dfs(node* t, int mid)
{
if (t)
{
ans[mid] += t->v;
dfs(t->l, mid - 1);
dfs(t->r, mid + 1);
}
return ;
}
void solve_init()
{
mid = 100;
memset(ans, 0, sizeof(ans));
}
void solve_ans()
{
bool first = true;
for (int i = 0; i < 200; i++)
{
if (ans[i])
{
if (first)
{
first = false;
printf("%d", ans[i]);
}
else
{
printf(" %d", ans[i]);
}
}
}
printf("\n\n");
return;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("699.in", "r", stdin);
#endif
int test_case = 0;
while (1)
{
#if 0
int c = getchar();
while (!isdigit(c)) c = getchar();
if (c - '0' == -1) break;
else ungetc(stdin);
#endif
solve_init();
node* tree = tree_build();
if (!tree) break;
dfs(tree, 100);
test_case++;
printf("Case %d:\n", test_case);
solve_ans();
tree_free(tree);
}
return 0;
}
| true |
d90fef0d034c32b9b7fc70205e41e87d40e009ae | C++ | Kareem21/CS253-project-code | /Image.cc | UTF-8 | 14,925 | 3.0625 | 3 | [] | no_license | #include "Image.h"
#include "Alpha.h"
#include <fstream>
#include "PGM.h"
using namespace std;
//what is going on in this >> thing
Image* Image::create(const std::string &filename) //static factory method
{
//Check if file is alpha or PGM
bool filetype = 0; // 0 for alpha 1 for PGM
std::ifstream in(filename);
std::string line;
std::string newLine="";
while(in>>line)
{
for(auto ch: line)
{
if(isComment(ch)) break;
newLine += ch;
}
if(newLine == "Alpha"){
filetype = 0;break;}
if(newLine == "P2"){
filetype = 1;break;}
}
if(filetype == 0) //if Alpha
{
Alpha *alpha = new Alpha(filename);
return alpha;
}
if(filetype)// if P2
{
PGM *test = new PGM(filename);
return test;
}
return NULL; //if it's neither
}
Image::Image(const FileType& type)
{
initFileFormat(type);
}
Image::Image(const Image& image)
{
_image=image._image;
}
void Image::min(Image& im2) // returns ptr to current Image
{
min(Image::NW,im2); //assuming im2 is smaller
}
void Image::min(const int direction,Image& im2) //returns ptr to current Image
{
std::string thisImage;
std::string secondImage;
if(this->whatamI() == "P2")
thisImage = "P2";
else
thisImage = "Alpha";
if(im2.whatamI() == "P2")
secondImage = "P2";
else
secondImage = "Alpha";
bool smaller = 0; //this ptr is smaller image
if(im2.height() * im2.width() < this->height() * this->width())
smaller = 1; //2nd image is smaller
//All work for PGM - > PGM
if(direction == NW)
{
if(smaller == 1) //2nd image is smaller
{
for(int i = 0;i<im2.height();i++)
{
for(int j = 0;j<im2.width();j++)
{
if(im2.get(j,i) < this->get(j,i))
{
this->set(i,j,im2.get(j,i));
}
}
}
}
}
if(direction == NE)
{
if(smaller == 1) //2nd image is smaller
{
int limitHeight = im2.height();
int limitWidth = this->width() - im2.width();
for(int i = 0;i<limitHeight;i++) //height is correct
{
for(int j = limitWidth;j<this->width();j++)
{
if(im2.get(j-limitWidth,i) < this->get(j,i))
{
this->set(i,j,im2.get(j-limitWidth,i));
}
}
}
}
}
if(direction == SE)
{
if(smaller == 1) //2nd image is smaller
{
int limitHeight = this->height() - im2.height();
int limitWidth = this->width() - im2.width();
for(int i = limitHeight;i<this->height();i++) //height is correct
{
for(int j = limitWidth;j<this->width();j++)
{
if(im2.get(j-limitWidth,i-limitHeight) < this->get(j,i))
{
this->set(i,j,im2.get(j-limitWidth,i-limitHeight));
}
}
}
}
}
if(direction == SW)
{
if(smaller == 1) //2nd image is smaller
{
int limitHeight = this->height() - im2.height();
// int limitWidth = this->width() - im2->width();
for(int i = limitHeight;i<this->height();i++) //height is correct
{
for(int j = 0;j<im2.width();j++)
{
if(im2.get(j,i-limitHeight) < this->get(j,i))
{
this->set(i,j,im2.get(j,i-limitHeight));
}
}
}
}
}
}
void Image::max(Image& im2)
{
max(Image::NW,im2);
}
void Image::max(int direction, Image& im2)
{
std::string thisImage;
std::string secondImage;
if(this->whatamI() == "P2")
thisImage = "P2";
else
thisImage = "Alpha";
if(im2.whatamI() == "P2")
secondImage = "P2";
else
secondImage = "Alpha";
bool smaller = 0; //this ptr is smaller image
if(im2.height() * im2.width() < this->height() * this->width())
smaller = 1; //2nd image is smaller
//All work for PGM - > PGM
if(direction == NW)
{
if(smaller == 1) //2nd image is smaller
{
for(int i = 0;i<im2.height();i++)
{
for(int j = 0;j<im2.width();j++)
{
if(im2.get(j,i) > this->get(j,i))
{
this->set(i,j,im2.get(j,i));
}
}
}
}
}
if(direction == NE)
{
if(smaller == 1) //2nd image is smaller
{
int limitHeight = im2.height();
int limitWidth = this->width() - im2.width();
for(int i = 0;i<limitHeight;i++) //height is correct
{
for(int j = limitWidth;j>this->width();j++)
{
if(im2.get(j-limitWidth,i) < this->get(j,i))
{
this->set(i,j,im2.get(j-limitWidth,i));
}
}
}
}
}
if(direction == SE)
{
if(smaller == 1) //2nd image is smaller
{
int limitHeight = this->height() - im2.height();
int limitWidth = this->width() - im2.width();
for(int i = limitHeight;i<this->height();i++) //height is correct
{
for(int j = limitWidth;j<this->width();j++)
{
if(im2.get(j-limitWidth,i-limitHeight) > this->get(j,i))
{
this->set(i,j,im2.get(j-limitWidth,i-limitHeight));
}
}
}
}
}
if(direction == SW)
{
if(smaller == 1) //2nd image is smaller
{
int limitHeight = this->height() - im2.height();
// int limitWidth = this->width() - im2->width();
for(int i = limitHeight;i<this->height();i++) //height is correct
{
for(int j = 0;j<im2.width();j++)
{
if(im2.get(j,i-limitHeight) > this->get(j,i))
{
this->set(i,j,im2.get(j,i-limitHeight));
}
}
}
}
}
}
void Image::initFileFormat(const FileType& type)
{
_image.type=type;
_image.width=0;
_image.height=0;
_image.extra=0;
if(type==FILE_TYPE_ALPHA) _image.label="Alpha";
if(type==FILE_TYPE_PGM) _image.label="P2";
_image.data.clear();
}
void Image::initFileFormat(FileFormat& file, const FileType& type)
{
file.type=type;
file.width=0;
file.height=0;
file.extra=0;
if(type==FILE_TYPE_ALPHA) file.label="Alpha";
if(type==FILE_TYPE_PGM) file.label="P2";
file.data.clear();
}
int Image::get(const int& column, const int& row) const
{
if(row<0 || column<0) throw std::string("Invalid index for get(): ("+std::to_string(column)+","+std::to_string(row)+")");
if(row>=static_cast<int>(_image.data.size()) || column>=static_cast<int>(_image.data[row].size()))
throw std::string("Invalid index for get() ("+std::to_string( column)+","+std::to_string(row)+")");
return _image.data[row][column];
}
void Image::set(const int& row, const int& column,int value)
{
_image.data[row][column] = value;
}
void Image::rotate(const int& degrees)
{
if(degrees%90!=0) throw std::string("Invalid rotation degree"+std::to_string(degrees));
int newDegree=degrees%360;
_image=rotateFile(_image, newDegree);
}
void Image::mirror(){
size_t rows=_image.data.size();
size_t cols=rows==0? 0: _image.data[0].size();
FileFormat rotatedFile;
initFileFormat(rotatedFile, FILE_TYPE_ALPHA);
rotatedFile.extra=_image.extra;
//new rows=old columns
rotatedFile.data.resize(rows);
for(size_t i=0; i<rows;i++)
rotatedFile.data[i].resize(cols);
for(size_t i=0; i<rows;i++){
for(size_t j=0; j<cols;j++){
rotatedFile.data[i][j]= _image.data[i][cols-j-1];
}
}
_image=rotatedFile;
_image.width= cols;
_image.height= rows;
}
void Image::resize(const double& factor){
if(factor==2)
{
_image=doubleImage(_image);
}
else if(factor==0.5){
_image=average(_image);
}
else{
throw std::string("Invalid resize parameter: "+std::to_string(factor));
}
}
bool Image::isValidChar(const char& ch){
return std::isalpha(ch);
}
bool Image::isComment(const char& ch){
return ch=='#';
}
bool Image::isHeaderLine(const Line& line){
return (line=="alpha");
}
FileFormat Image::rotateFile(const FileFormat& file, const int& degree){
switch (degree){
case 0:
return rotateFile0(file);
case 90:
return rotateFile90(file);
case 180:
return rotateFile180(file);
case 270:
return rotateFile270(file);
default:
throw std::string("Invalid rotation degree: "+std::to_string(degree));
}
}
FileFormat Image::rotateFile0(const FileFormat& file){
return file;
}
FileFormat Image:: rotateFile90(const FileFormat& file)
{
size_t rows=file.data.size();
size_t cols=rows==0? 0: file.data[0].size();
FileFormat rotatedFile;
initFileFormat(rotatedFile, file.type);
rotatedFile.extra=file.extra;
//new rows=old columns
rotatedFile.data.resize(cols);
for(size_t i=0; i<cols;i++)
rotatedFile.data[i].resize(rows);
for(size_t i=0; i<rows;i++){
for(size_t j=0; j<cols;j++){
rotatedFile.data[j][i]= file.data[i][j];
}
}
//add a termination char for each line
for(size_t i=0;i<rotatedFile.data.size(); i++){
auto oldLine=rotatedFile.data[i];
auto len=oldLine.size();
for(size_t j=0;j<len;j++)
rotatedFile.data[i][j]=oldLine[len-j-1];
}
//update file size
rotatedFile.width=rows;
rotatedFile.height= cols;
return rotatedFile;
}
FileFormat Image::rotateFile180(const FileFormat& file){
size_t rows=file.data.size();
size_t cols=rows==0? 0: file.data[0].size();
FileFormat rotatedFile;
initFileFormat(rotatedFile, file.type);
rotatedFile.extra=file.extra;
//new rows=old columns
rotatedFile.data.resize(rows);
for(size_t i=0; i<rows;i++)
rotatedFile.data[i].resize(cols);
for(size_t i=0; i<rows;i++){
for(size_t j=0; j<cols;j++){
rotatedFile.data[i][j]= file.data[rows-i-1][cols-j-1];
}
}
rotatedFile.width=cols;
rotatedFile.height= rows;
return rotatedFile;
}
FileFormat Image::rotateFile270(const FileFormat& file){
size_t rows=file.data.size();
size_t cols=rows==0? 0: file.data[0].size();
FileFormat rotatedFile;
//new rows=old columns
initFileFormat(rotatedFile, file.type);
rotatedFile.data.resize(cols);
for(size_t i=0; i<cols;i++)
rotatedFile.data[i].resize(rows);
for(size_t i=0; i<rows;i++){
for(size_t j=0; j<cols;j++){
rotatedFile.data[j][i]= file.data[rows-i-1][j];
}
}
//add a termination char for each line
for(size_t i=0;i<rotatedFile.data.size(); i++){
auto oldLine=rotatedFile.data[i];
auto len=oldLine.size();
for(size_t j=0;j<len;j++)
rotatedFile.data[i][j]=oldLine[len-j-1];
}
FileFormat finalFile;
initFileFormat(finalFile, file.type);
finalFile.extra=file.extra;
finalFile.data.reserve(rotatedFile.data.size());
for(int i=rotatedFile.data.size()-1; i>=0;i--)
finalFile.data.push_back(rotatedFile.data[i]);
//update file size
finalFile.width=rows;
finalFile.height= cols;
return finalFile;
}
int Image::avrg(const FileFormat& file, const int& i, const int& j){
int sume=file.data[i][j]+file.data[i+1][j]+file.data[i][j+1]+file.data[i+1][j+1];
return static_cast<int> (sume/4.0);
}
FileFormat Image::average(const FileFormat& file){
FileFormat newFile;
initFileFormat(newFile, file.type);
newFile.extra=file.extra;
int width=file.width;
int height= file.height;
int newWidth=static_cast<int> (width/2);
int newHeight=static_cast<int> (height/2);
newFile.width=newWidth;
newFile.height=newHeight;
newFile.data.resize(newHeight);
for(int i=0;i<newHeight;i++){
newFile.data[i].resize(newWidth);
}
for (int i=0,m=0;i<height-1;i+=2, m++){
for(int j=0, n=0;j<width-1;j+=2, n++){
newFile.data[m][n]=avrg(file,i,j);
}
}
return newFile;
}
FileFormat Image::doubleImage(const FileFormat& file){
FileFormat newFile=file;
int width=file.width;
int height= file.height;
int newWidth=width*2;
int newHeight=height*2;
newFile.width=newWidth;
newFile.height=newHeight;
newFile.extra=file.extra;
//resize the new file
newFile.data.resize(newHeight);
for(int i=0;i<newHeight;i++)
newFile.data[i].resize(newWidth);
//double the image
for(int i=0;i<height;i++){
//double the collumns
for(int j=0;j<width;j++){
newFile.data[2*i][2*j]=newFile.data[2*i][2*j+1]=file.data[i][j];
newFile.data[2*i+1][2*j]=newFile.data[2*i+1][2*j+1]=file.data[i][j];
}
}
//add more rows
/*for(int i=0;i<height;i++){
newFile.data.push_back(file.data[i]);
}
//add more collumns
for(int i=0;i<newHeight;i++){
for(int j=0;j<width;j++){
newFile.data[i].push_back(newFile.data[i][j]);
}
}*/
return newFile;
}
| true |
7943a2540e962dacd8b8d8ca7b8ab33dfa4200a1 | C++ | mi2think/DoPixel | /DpLib/DpGeometry.cpp | UTF-8 | 4,620 | 2.53125 | 3 | [] | no_license | /********************************************************************
created: 2015/11/21
created: 21:11:2015 11:05
filename: D:\OneDrive\3D\DpLib\DpLib\DpGeometry.cpp
file path: D:\OneDrive\3D\DpLib\DpLib
file base: DpGeometry
file ext: cpp
author: mi2think@gmail.com
purpose: Geometry
*********************************************************************/
#include "DpGeometry.h"
#include "DpVector4.h"
namespace dopixel
{
namespace math
{
Plane::Plane()
{
}
Plane::Plane(const Vector3f& n, float d)
: n_(n)
, d_(d)
{
ASSERT(n.IsNormalized());
}
Plane::Plane(const Vector3f& p0, const Vector3f& p1, const Vector3f& p2)
{
Vector3f u = p1 - p0;
Vector3f v = p2 - p0;
n_ = CrossProduct(u, v);
n_.Normalize();
d_ = -DotProduct(n_, p0);
}
Plane::Plane(const Vector3f& n, const Vector3f& p)
: n_(n)
{
ASSERT(n_.IsNormalized());
d_ = -DotProduct(n_, p);
}
Plane::Plane(float a, float b, float c, float d)
: n_(a, b, c)
, d_(d)
{
Normalize();
}
Plane::Plane(const Plane& plane)
: n_(plane.n_)
, d_(plane.d_)
{
}
Plane& Plane::operator =(const Plane& plane)
{
if (this != &plane)
{
n_ = plane.n_;
d_ = plane.d_;
}
return *this;
}
float Plane::Distance(const Vector3f& p) const
{
return DotProduct(n_, p) + d_;
}
Vector3f Plane::NearestPoint(const Vector3f& p) const
{
// we assume q is the nearest point in plane for p
// and k is the nearest distance from p to plane. since n is unit-vector
// such: q = p + (-kn), and k = Distance(p)
return p - Distance(p) * n_;
}
void Plane::Normalize()
{
float len = n_.Length();
float f = 1.0f / len;
n_ *= f;
d_ *= f; // we also need divide d by len
}
void Plane::Transform(const Matrix44f& m)
{
// just do it! see formula in page 102
math::Vector4f v(n_.x, n_.y, n_.z, d_);
v *= m;
n_.x = v.x;
n_.y = v.y;
n_.z = v.z;
d_ = v.w;
}
//////////////////////////////////////////////////////////////////////////
Frustum::Frustum()
{
}
Frustum::Frustum(const Matrix44f& view, const Matrix44f& proj)
{
Matrix44f viewProj;
MatrixMultiply(viewProj, view, proj);
ExtractFrustum(viewProj);
}
Frustum::Frustum(const Matrix44f& viewProj)
{
ExtractFrustum(viewProj);
}
const Plane& Frustum::GetPlane(PlaneID index) const
{
ASSERT(index < PlaneMax);
return planes_[index];
}
void Frustum::ExtractFrustum(const Matrix44f& viewProj)
{
//Fast Extraction of Viewing Frustum Planes - Gribb & Hartmann
//http://www.cs.otago.ac.nz/postgrads/alexis/planeExtraction.pdf
const auto& m = viewProj.m;
// Near clipping plane
planes_[Frustum::PlaneNear] = Plane(m[0][2],
m[1][2],
m[2][2],
m[3][2]);
// Far clipping plane
planes_[Frustum::PlaneFar] = Plane(m[0][3] - m[0][2],
m[1][3] - m[1][2],
m[2][3] - m[2][2],
m[3][3] - m[3][2]);
//left clipping plane
planes_[Frustum::PlaneLeft] = Plane(m[0][3] + m[0][0],
m[1][3] + m[1][0],
m[2][3] + m[2][0],
m[3][3] + m[3][0]);
// Right clipping plane
planes_[Frustum::PlaneRight] = Plane(m[0][3] - m[0][0],
m[1][3] - m[1][0],
m[2][3] - m[2][0],
m[3][3] - m[3][0]);
// Top clipping plane
planes_[Frustum::PlaneTop] = Plane(m[0][3] - m[0][1],
m[1][3] - m[1][1],
m[2][3] - m[2][1],
m[3][3] - m[3][1]);
// Bottom clipping plane
planes_[Frustum::PlaneBottom] = Plane(m[0][3] + m[0][1],
m[1][3] + m[1][1],
m[2][3] + m[2][1],
m[3][3] + m[3][1]);
}
bool Frustum::ContainsPoint(const Vector3f& pt) const
{
for (int i = 0; i < Frustum::PlaneMax; i++)
{
if (planes_[i].Distance(pt) < 0)
return false;
}
return true;
}
//////////////////////////////////////////////////////////////////////////
bool Intersect(const Plane& plane, const Ray& ray, float& t)
{
//see formula in page 99
float dp = DotProduct(plane.n_, ray.dir_);
if (Equal(dp, 0.0f))
{
// ray is parallel to plane
// may the ray lies in the plane if DotProduct(plane.n_, ray.pt_) + plane.d_ == 0
// we treat this as not intersect yet.
return false;
}
float k = DotProduct(plane.n_, ray.pt_);
float t0 = -(k + plane.d_) / dp;
if (t0 < 0)
return false;
t = t0;
return true;
}
bool Intersect(const Plane& plane, const LineSeg& line, float& t)
{
Vector3f dir = line.v2_ - line.v1_;
dir.Normalize();
Ray ray(line.v1_, dir);
float t0;
if (Intersect(plane, ray, t0) && t0 <= 1.0f)
{
t = t0;
return true;
}
return false;
}
}
} | true |
2d09768b5ed26623c9f9bb6a6be79a7b9b223572 | C++ | catboost/catboost | /library/cpp/cache/ut/cache_ut.cpp | UTF-8 | 21,490 | 2.734375 | 3 | [
"Apache-2.0"
] | permissive | #include <library/cpp/cache/cache.h>
#include <library/cpp/cache/thread_safe_cache.h>
#include <library/cpp/testing/unittest/registar.h>
struct TStrokaWeighter {
static size_t Weight(const TString& s) {
return s.size();
}
};
Y_UNIT_TEST_SUITE(TCacheTest) {
Y_UNIT_TEST(LRUListTest) {
typedef TLRUList<int, TString> TListType;
TListType list(2);
TListType::TItem x1(1, "ttt");
list.Insert(&x1);
UNIT_ASSERT_EQUAL(list.GetOldest()->Key, 1);
TListType::TItem x2(2, "yyy");
list.Insert(&x2);
UNIT_ASSERT_EQUAL(list.GetOldest()->Key, 1);
list.Promote(list.GetOldest());
UNIT_ASSERT_EQUAL(list.GetOldest()->Key, 2);
TListType::TItem x3(3, "zzz");
list.Insert(&x3);
UNIT_ASSERT_EQUAL(list.GetOldest()->Key, 1);
}
Y_UNIT_TEST(LRUListWeightedTest) {
typedef TLRUList<int, TString, size_t (*)(const TString&)> TListType;
TListType list(7, [](auto& string) {
return string.size();
});
TListType::TItem x1(1, "ttt");
list.Insert(&x1);
while (list.RemoveIfOverflown()) {
}
UNIT_ASSERT_EQUAL(list.GetOldest()->Key, 1);
TListType::TItem x2(2, "yyy");
list.Insert(&x2);
while (list.RemoveIfOverflown()) {
}
UNIT_ASSERT_EQUAL(list.GetOldest()->Key, 1);
list.Promote(list.GetOldest());
while (list.RemoveIfOverflown()) {
}
UNIT_ASSERT_EQUAL(list.GetOldest()->Key, 2);
TListType::TItem x3(3, "zzz");
list.Insert(&x3);
while (list.RemoveIfOverflown()) {
}
UNIT_ASSERT_EQUAL(list.GetOldest()->Key, 1);
TListType::TItem x4(4, "longlong");
list.Insert(&x4);
while (list.RemoveIfOverflown()) {
}
UNIT_ASSERT_EQUAL(list.GetOldest()->Key, 4);
}
Y_UNIT_TEST(LFUListTest) {
typedef TLFUList<int, TString> TListType;
TListType list(2);
TListType::TItem x1(1, "ttt");
list.Insert(&x1);
UNIT_ASSERT_EQUAL(list.GetLeastFrequentlyUsed()->Key, 1);
TListType::TItem x2(2, "yyy");
list.Insert(&x2);
UNIT_ASSERT_EQUAL(list.GetLeastFrequentlyUsed()->Key, 1);
list.Promote(list.GetLeastFrequentlyUsed());
UNIT_ASSERT_EQUAL(list.GetLeastFrequentlyUsed()->Key, 2);
TListType::TItem x3(3, "zzz");
list.Insert(&x3);
UNIT_ASSERT_EQUAL(list.GetLeastFrequentlyUsed()->Key, 1);
}
Y_UNIT_TEST(LWListTest) {
typedef TLWList<int, TString, size_t, TStrokaWeighter> TListType;
TListType list(2);
TListType::TItem x1(1, "tt");
list.Insert(&x1);
UNIT_ASSERT_EQUAL(list.GetLightest()->Key, 1);
UNIT_ASSERT_EQUAL(list.GetSize(), 1);
TListType::TItem x2(2, "yyyy");
list.Insert(&x2);
UNIT_ASSERT_EQUAL(list.GetLightest()->Key, 1);
UNIT_ASSERT_EQUAL(list.GetSize(), 2);
TListType::TItem x3(3, "z");
list.Insert(&x3);
UNIT_ASSERT_EQUAL(list.GetLightest()->Key, 1);
UNIT_ASSERT_EQUAL(list.GetSize(), 2);
TListType::TItem x4(4, "xxxxxx");
list.Insert(&x4);
UNIT_ASSERT_EQUAL(list.GetLightest()->Key, 2);
UNIT_ASSERT_EQUAL(list.GetSize(), 2);
list.Erase(&x2);
UNIT_ASSERT_EQUAL(list.GetLightest()->Key, 4);
UNIT_ASSERT_EQUAL(list.GetSize(), 1);
}
Y_UNIT_TEST(SimpleTest) {
typedef TLRUCache<int, TString> TCache;
TCache s(2); // size 2
s.Insert(1, "abcd");
UNIT_ASSERT(s.Find(1) != s.End());
UNIT_ASSERT_EQUAL(*s.Find(1), "abcd");
s.Insert(2, "defg");
UNIT_ASSERT(s.GetOldest() == "abcd");
s.Insert(3, "hjkl");
UNIT_ASSERT(s.GetOldest() == "defg");
// key 1 will be deleted
UNIT_ASSERT(s.Find(1) == s.End());
UNIT_ASSERT(s.Find(2) != s.End());
UNIT_ASSERT(*s.Find(2) == "defg");
UNIT_ASSERT(s.Find(3) != s.End());
UNIT_ASSERT(*s.Find(3) == "hjkl");
UNIT_ASSERT(!s.Insert(3, "abcd"));
UNIT_ASSERT(*s.Find(3) == "hjkl");
s.Update(3, "abcd");
UNIT_ASSERT(*s.Find(3) == "abcd");
TCache::TIterator it = s.Find(3);
s.Erase(it);
UNIT_ASSERT(s.Find(3) == s.End());
}
Y_UNIT_TEST(LRUWithCustomSizeProviderTest) {
typedef TLRUCache<int, TString, TNoopDelete, size_t(*)(const TString&)> TCache;
TCache s(10, false, [](auto& string) { return string.size(); }); // size 10
s.Insert(1, "abcd");
UNIT_ASSERT(s.Find(1) != s.End());
UNIT_ASSERT_EQUAL(*s.Find(1), "abcd");
s.Insert(2, "defg");
UNIT_ASSERT(s.GetOldest() == "abcd");
s.Insert(3, "2c");
UNIT_ASSERT(s.GetOldest() == "abcd");
s.Insert(4, "hjkl");
UNIT_ASSERT(s.GetOldest() == "defg");
// key 1 will be deleted
UNIT_ASSERT(s.Find(1) == s.End());
UNIT_ASSERT(s.Find(2) != s.End());
UNIT_ASSERT(*s.Find(2) == "defg");
UNIT_ASSERT(s.Find(3) != s.End());
UNIT_ASSERT(*s.Find(3) == "2c");
UNIT_ASSERT(s.Find(4) != s.End());
UNIT_ASSERT(*s.Find(4) == "hjkl");
UNIT_ASSERT(!s.Insert(3, "abcd"));
UNIT_ASSERT(*s.Find(3) == "2c");
s.Update(3, "abcd");
UNIT_ASSERT(*s.Find(3) == "abcd");
TCache::TIterator it = s.Find(3);
s.Erase(it);
UNIT_ASSERT(s.Find(3) == s.End());
}
Y_UNIT_TEST(LRUSetMaxSizeTest) {
typedef TLRUCache<int, TString> TCache;
TCache s(2); // size 2
s.Insert(1, "abcd");
s.Insert(2, "efgh");
s.Insert(3, "ijkl");
UNIT_ASSERT(s.GetOldest() == "efgh");
UNIT_ASSERT(s.Find(1) == s.End());
UNIT_ASSERT(s.Find(2) != s.End());
UNIT_ASSERT(s.Find(3) != s.End());
// Increasing size should not change anything
s.SetMaxSize(3);
UNIT_ASSERT(s.GetOldest() == "efgh");
UNIT_ASSERT(s.Find(1) == s.End());
UNIT_ASSERT(s.Find(2) != s.End());
UNIT_ASSERT(s.Find(3) != s.End());
// And we should be able to add fit more entries
s.Insert(4, "mnop");
s.Insert(5, "qrst");
UNIT_ASSERT(s.GetOldest() == "ijkl");
UNIT_ASSERT(s.Find(1) == s.End());
UNIT_ASSERT(s.Find(2) == s.End());
UNIT_ASSERT(s.Find(3) != s.End());
UNIT_ASSERT(s.Find(4) != s.End());
UNIT_ASSERT(s.Find(5) != s.End());
// Decreasing size should remove oldest entries
s.SetMaxSize(2);
UNIT_ASSERT(s.GetOldest() == "mnop");
UNIT_ASSERT(s.Find(1) == s.End());
UNIT_ASSERT(s.Find(2) == s.End());
UNIT_ASSERT(s.Find(3) == s.End());
UNIT_ASSERT(s.Find(4) != s.End());
UNIT_ASSERT(s.Find(5) != s.End());
// Ano no more entries will fit
s.Insert(6, "uvwx");
UNIT_ASSERT(s.GetOldest() == "qrst");
UNIT_ASSERT(s.Find(1) == s.End());
UNIT_ASSERT(s.Find(2) == s.End());
UNIT_ASSERT(s.Find(3) == s.End());
UNIT_ASSERT(s.Find(4) == s.End());
UNIT_ASSERT(s.Find(5) != s.End());
UNIT_ASSERT(s.Find(6) != s.End());
}
Y_UNIT_TEST(LWSetMaxSizeTest) {
typedef TLWCache<int, TString, size_t, TStrokaWeighter> TCache;
TCache s(2); // size 2
s.Insert(1, "a");
s.Insert(2, "aa");
s.Insert(3, "aaa");
UNIT_ASSERT(s.GetLightest() == "aa");
UNIT_ASSERT(s.Find(1) == s.End());
UNIT_ASSERT(s.Find(2) != s.End());
UNIT_ASSERT(s.Find(3) != s.End());
// Increasing size should not change anything
s.SetMaxSize(3);
UNIT_ASSERT(s.GetLightest() == "aa");
UNIT_ASSERT(s.Find(1) == s.End());
UNIT_ASSERT(s.Find(2) != s.End());
UNIT_ASSERT(s.Find(3) != s.End());
// And we should be able to add fit more entries
s.Insert(4, "aaaa");
s.Insert(5, "aaaaa");
UNIT_ASSERT(s.GetLightest() == "aaa");
UNIT_ASSERT(s.Find(1) == s.End());
UNIT_ASSERT(s.Find(2) == s.End());
UNIT_ASSERT(s.Find(3) != s.End());
UNIT_ASSERT(s.Find(4) != s.End());
UNIT_ASSERT(s.Find(5) != s.End());
// Decreasing size should remove oldest entries
s.SetMaxSize(2);
UNIT_ASSERT(s.GetLightest() == "aaaa");
UNIT_ASSERT(s.Find(1) == s.End());
UNIT_ASSERT(s.Find(2) == s.End());
UNIT_ASSERT(s.Find(3) == s.End());
UNIT_ASSERT(s.Find(4) != s.End());
UNIT_ASSERT(s.Find(5) != s.End());
// Ano no more entries will fit
s.Insert(6, "aaaaaa");
UNIT_ASSERT(s.GetLightest() == "aaaaa");
UNIT_ASSERT(s.Find(1) == s.End());
UNIT_ASSERT(s.Find(2) == s.End());
UNIT_ASSERT(s.Find(3) == s.End());
UNIT_ASSERT(s.Find(4) == s.End());
UNIT_ASSERT(s.Find(5) != s.End());
UNIT_ASSERT(s.Find(6) != s.End());
}
Y_UNIT_TEST(LFUSetMaxSizeTest) {
typedef TLFUCache<int, TString> TCache;
TCache s(2); // size 2
s.Insert(1, "abcd");
s.Insert(2, "efgh");
s.Insert(3, "ijkl");
UNIT_ASSERT(s.Find(1) == s.End());
UNIT_ASSERT(s.Find(2) != s.End());
UNIT_ASSERT(s.Find(3) != s.End());
// Increasing size should not change anything
s.SetMaxSize(3);
UNIT_ASSERT(s.Find(1) == s.End());
UNIT_ASSERT(s.Find(2) != s.End());
UNIT_ASSERT(s.Find(3) != s.End());
// And we should be able to add fit more entries
s.Insert(4, "mnop");
s.Insert(5, "qrst");
UNIT_ASSERT(s.Find(1) == s.End());
UNIT_ASSERT(s.Find(2) == s.End());
UNIT_ASSERT(s.Find(3) != s.End());
UNIT_ASSERT(s.Find(4) != s.End());
UNIT_ASSERT(s.Find(5) != s.End());
// Decreasing size should remove oldest entries
s.SetMaxSize(2);
UNIT_ASSERT(s.Find(1) == s.End());
UNIT_ASSERT(s.Find(2) == s.End());
UNIT_ASSERT(s.Find(3) != s.End());
UNIT_ASSERT(s.Find(4) == s.End());
UNIT_ASSERT(s.Find(5) != s.End());
// Ano no more entries will fit
s.Insert(6, "uvwx");
UNIT_ASSERT(s.Find(1) == s.End());
UNIT_ASSERT(s.Find(2) == s.End());
UNIT_ASSERT(s.Find(3) != s.End());
UNIT_ASSERT(s.Find(4) == s.End());
UNIT_ASSERT(s.Find(5) == s.End());
UNIT_ASSERT(s.Find(6) != s.End());
}
Y_UNIT_TEST(MultiCacheTest) {
typedef TLRUCache<int, TString> TCache;
TCache s(3, true);
UNIT_ASSERT(s.Insert(1, "abcd"));
UNIT_ASSERT(s.Insert(1, "bcde"));
UNIT_ASSERT(s.Insert(2, "fghi"));
UNIT_ASSERT(s.Insert(2, "ghij"));
// (1, "abcd") will be deleted
UNIT_ASSERT(*s.Find(1) == "bcde");
// (1, "bcde") will be promoted
UNIT_ASSERT(*s.FindOldest() == "fghi");
}
struct TMyDelete {
static int count;
template <typename T>
static void Destroy(const T&) {
++count;
}
};
int TMyDelete::count = 0;
Y_UNIT_TEST(DeleterTest) {
typedef TLRUCache<int, TString, TMyDelete> TCache;
TCache s(2);
s.Insert(1, "123");
s.Insert(2, "456");
s.Insert(3, "789");
UNIT_ASSERT(TMyDelete::count == 1);
TCache::TIterator it = s.Find(2);
UNIT_ASSERT(it != s.End());
s.Erase(it);
UNIT_ASSERT(TMyDelete::count == 2);
}
Y_UNIT_TEST(PromoteOnFind) {
typedef TLRUCache<int, TString> TCache;
TCache s(2);
s.Insert(1, "123");
s.Insert(2, "456");
UNIT_ASSERT(s.Find(1) != s.End());
s.Insert(3, "789");
UNIT_ASSERT(s.Find(1) != s.End()); // Key 2 should have been deleted
}
class TMoveOnlyInt {
public:
ui32 Value = 0;
explicit TMoveOnlyInt(ui32 value = 0) : Value(value) {}
TMoveOnlyInt(TMoveOnlyInt&&) = default;
TMoveOnlyInt& operator=(TMoveOnlyInt&&) = default;
TMoveOnlyInt(const TMoveOnlyInt&) = delete;
TMoveOnlyInt& operator=(const TMoveOnlyInt&) = delete;
bool operator==(const TMoveOnlyInt& rhs) const {
return Value == rhs.Value;
}
explicit operator size_t() const {
return Value;
}
};
Y_UNIT_TEST(MoveOnlySimpleTest) {
typedef TLRUCache<TMoveOnlyInt, TMoveOnlyInt> TCache;
TCache s(2); // size 2
s.Insert(TMoveOnlyInt(1), TMoveOnlyInt(0x11111111));
TMoveOnlyInt lookup1(1), lookup2(2), lookup3(3);
UNIT_ASSERT(s.Find(lookup1) != s.End());
UNIT_ASSERT_EQUAL(s.Find(lookup1)->Value, 0x11111111);
s.Insert(TMoveOnlyInt(2), TMoveOnlyInt(0x22222222));
UNIT_ASSERT(s.GetOldest().Value == 0x11111111);
s.Insert(TMoveOnlyInt(3), TMoveOnlyInt(0x33333333));
UNIT_ASSERT(s.GetOldest().Value == 0x22222222);
// key 1 will be deleted
UNIT_ASSERT(s.Find(lookup1) == s.End());
UNIT_ASSERT(s.Find(lookup2) != s.End());
UNIT_ASSERT(s.Find(lookup2)->Value == 0x22222222);
UNIT_ASSERT(s.Find(lookup3) != s.End());
UNIT_ASSERT(s.Find(lookup3)->Value == 0x33333333);
UNIT_ASSERT(!s.Insert(TMoveOnlyInt(3), TMoveOnlyInt(0x11111111)));
UNIT_ASSERT(s.Find(lookup3)->Value == 0x33333333);
s.Update(TMoveOnlyInt(3), TMoveOnlyInt(0x11111111));
UNIT_ASSERT(s.Find(lookup3)->Value == 0x11111111);
TCache::TIterator it = s.Find(lookup3);
s.Erase(it);
UNIT_ASSERT(s.Find(lookup3) == s.End());
}
}
Y_UNIT_TEST_SUITE(TThreadSafeCacheTest) {
typedef TThreadSafeCache<ui32, TString, ui32> TCache;
const char* VALS[] = {"abcd", "defg", "hjkl"};
class TCallbacks: public TCache::ICallbacks {
public:
TKey GetKey(ui32 i) const override {
return i;
}
TValue* CreateObject(ui32 i) const override {
Creations++;
return new TString(VALS[i]);
}
mutable i32 Creations = 0;
};
Y_UNIT_TEST(SimpleTest) {
for (ui32 i = 0; i < Y_ARRAY_SIZE(VALS); ++i) {
const TString data = *TCache::Get<TCallbacks>(i);
UNIT_ASSERT(data == VALS[i]);
}
}
Y_UNIT_TEST(InsertUpdateTest) {
TCallbacks callbacks;
TCache cache(callbacks, 10);
cache.Insert(2, MakeAtomicShared<TString>("hj"));
TAtomicSharedPtr<TString> item = cache.Get(2);
UNIT_ASSERT(callbacks.Creations == 0);
UNIT_ASSERT(*item == "hj");
cache.Insert(2, MakeAtomicShared<TString>("hjk"));
item = cache.Get(2);
UNIT_ASSERT(callbacks.Creations == 0);
UNIT_ASSERT(*item == "hj");
cache.Update(2, MakeAtomicShared<TString>("hjk"));
item = cache.Get(2);
UNIT_ASSERT(callbacks.Creations == 0);
UNIT_ASSERT(*item == "hjk");
}
}
Y_UNIT_TEST_SUITE(TThreadSafeCacheUnsafeTest) {
typedef TThreadSafeCache<ui32, TString, ui32> TCache;
const char* VALS[] = {"abcd", "defg", "hjkl"};
const ui32 FAILED_IDX = 1;
class TCallbacks: public TCache::ICallbacks {
public:
TKey GetKey(ui32 i) const override {
return i;
}
TValue* CreateObject(ui32 i) const override {
if (i == FAILED_IDX) {
return nullptr;
}
return new TString(VALS[i]);
}
};
Y_UNIT_TEST(SimpleTest) {
TCallbacks callbacks;
TCache cache(callbacks, Y_ARRAY_SIZE(VALS));
for (ui32 i = 0; i < Y_ARRAY_SIZE(VALS); ++i) {
const TString* data = cache.GetUnsafe(i).Get();
if (i == FAILED_IDX) {
UNIT_ASSERT(data == nullptr);
} else {
UNIT_ASSERT(*data == VALS[i]);
}
}
}
}
Y_UNIT_TEST_SUITE(TThreadSafeLRUCacheTest) {
typedef TThreadSafeLRUCache<size_t, TString, size_t> TCache;
TVector<TString> Values = {"zero", "one", "two", "three", "four"};
class TCallbacks: public TCache::ICallbacks {
public:
TKey GetKey(size_t i) const override {
return i;
}
TValue* CreateObject(size_t i) const override {
UNIT_ASSERT(i < Values.size());
Creations++;
return new TString(Values[i]);
}
mutable size_t Creations = 0;
};
Y_UNIT_TEST(SimpleTest) {
for (size_t i = 0; i < Values.size(); ++i) {
const TString data = *TCache::Get<TCallbacks>(i);
UNIT_ASSERT(data == Values[i]);
}
}
Y_UNIT_TEST(InsertUpdateTest) {
TCallbacks callbacks;
TCache cache(callbacks, 10);
cache.Insert(2, MakeAtomicShared<TString>("hj"));
TAtomicSharedPtr<TString> item = cache.Get(2);
UNIT_ASSERT(callbacks.Creations == 0);
UNIT_ASSERT(*item == "hj");
cache.Insert(2, MakeAtomicShared<TString>("hjk"));
item = cache.Get(2);
UNIT_ASSERT(callbacks.Creations == 0);
UNIT_ASSERT(*item == "hj");
cache.Update(2, MakeAtomicShared<TString>("hjk"));
item = cache.Get(2);
UNIT_ASSERT(callbacks.Creations == 0);
UNIT_ASSERT(*item == "hjk");
}
Y_UNIT_TEST(LRUTest) {
TCallbacks callbacks;
TCache cache(callbacks, 3);
UNIT_ASSERT_EQUAL(cache.GetMaxSize(), 3);
for (size_t i = 0; i < Values.size(); ++i) {
TAtomicSharedPtr<TString> item = cache.Get(i);
UNIT_ASSERT(*item == Values[i]);
}
UNIT_ASSERT(callbacks.Creations == Values.size());
size_t expectedCreations = Values.size();
TAtomicSharedPtr<TString> item;
item = cache.Get(4);
UNIT_ASSERT_EQUAL(callbacks.Creations, expectedCreations);
UNIT_ASSERT(*item == "four");
item = cache.Get(2);
UNIT_ASSERT_EQUAL(callbacks.Creations, expectedCreations);
UNIT_ASSERT(*item == "two");
item = cache.Get(0);
expectedCreations++;
UNIT_ASSERT_EQUAL(callbacks.Creations, expectedCreations);
UNIT_ASSERT(*item == "zero");
UNIT_ASSERT(cache.Contains(1) == false);
UNIT_ASSERT(cache.Contains(3) == false);
UNIT_ASSERT(cache.Contains(4));
UNIT_ASSERT(cache.Contains(2));
UNIT_ASSERT(cache.Contains(0));
item = cache.Get(3);
expectedCreations++;
UNIT_ASSERT_EQUAL(callbacks.Creations, expectedCreations);
UNIT_ASSERT(*item == "three");
item = cache.Get(2);
UNIT_ASSERT_EQUAL(callbacks.Creations, expectedCreations);
UNIT_ASSERT(*item == "two");
item = cache.Get(0);
UNIT_ASSERT_EQUAL(callbacks.Creations, expectedCreations);
UNIT_ASSERT(*item == "zero");
item = cache.Get(1);
expectedCreations++;
UNIT_ASSERT_EQUAL(callbacks.Creations, expectedCreations);
UNIT_ASSERT(*item == "one");
item = cache.Get(2);
UNIT_ASSERT_EQUAL(callbacks.Creations, expectedCreations);
UNIT_ASSERT(*item == "two");
item = cache.Get(4);
expectedCreations++;
UNIT_ASSERT_EQUAL(callbacks.Creations, expectedCreations);
UNIT_ASSERT(*item == "four");
}
Y_UNIT_TEST(ChangeMaxSizeTest) {
TCallbacks callbacks;
TCache cache(callbacks, 3);
UNIT_ASSERT_EQUAL(cache.GetMaxSize(), 3);
for (size_t i = 0; i < Values.size(); ++i) {
TAtomicSharedPtr<TString> item = cache.Get(i);
UNIT_ASSERT(*item == Values[i]);
}
size_t expectedCreations = Values.size();
TAtomicSharedPtr<TString> item;
item = cache.Get(4);
UNIT_ASSERT_EQUAL(callbacks.Creations, expectedCreations);
UNIT_ASSERT(*item == "four");
item = cache.Get(3);
UNIT_ASSERT_EQUAL(callbacks.Creations, expectedCreations);
UNIT_ASSERT(*item == "three");
item = cache.Get(2);
UNIT_ASSERT_EQUAL(callbacks.Creations, expectedCreations);
UNIT_ASSERT(*item == "two");
item = cache.Get(1);
expectedCreations++;
UNIT_ASSERT_EQUAL(callbacks.Creations, expectedCreations);
UNIT_ASSERT(*item == "one");
cache.SetMaxSize(4);
item = cache.Get(0);
expectedCreations++;
UNIT_ASSERT_EQUAL(callbacks.Creations, expectedCreations);
UNIT_ASSERT(*item == "zero");
item = cache.Get(4);
expectedCreations++;
UNIT_ASSERT_EQUAL(callbacks.Creations, expectedCreations);
UNIT_ASSERT(*item == "four");
item = cache.Get(3);
expectedCreations++;
UNIT_ASSERT_EQUAL(callbacks.Creations, expectedCreations);
UNIT_ASSERT(*item == "three");
UNIT_ASSERT(cache.Contains(2) == false);
cache.SetMaxSize(2);
UNIT_ASSERT(cache.Contains(3));
UNIT_ASSERT(cache.Contains(4));
UNIT_ASSERT(cache.Contains(2) == false);
UNIT_ASSERT(cache.Contains(1) == false);
UNIT_ASSERT(cache.Contains(0) == false);
item = cache.Get(0);
expectedCreations++;
UNIT_ASSERT_EQUAL(callbacks.Creations, expectedCreations);
UNIT_ASSERT(*item == "zero");
UNIT_ASSERT(cache.Contains(4) == false);
UNIT_ASSERT(cache.Contains(3));
UNIT_ASSERT(cache.Contains(0));
}
}
| true |
0f4f330e2e4b313e906ee36c2111b10d01d86b2c | C++ | dinhtai1104/SPOJ_PTIT | /P142SUME.cpp | UTF-8 | 1,148 | 2.765625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int a[100000] ;
int k , n, s, res;
void printResult() { // hà m dùng d? in m?t c?u hình ra ngoà i
for(int i = 1 ; i <=k ; i++) {
cout<<a[i]<<" " ;
}
cout<<endl ;
}
bool check(int a[], int s)
{
int sum = 0;
for (int i = 1; i <= k; i++) sum += a[i];
if (sum == s) return 1;
return 0;
}
void backtrack(int i ) { // hà m quay lui
for(int j = a[i-1]+1 ; j<=n-k+i ; j++ ) { // xét các kh? nang c?a j
a[i] = j ; // ghi nh?n m?t giá tr? c?a j
if(i==k) { // n?u c?u hình dã d? k ph?n t?
// in m?t c?u hình ra ngoà i
if (check(a, s)) res++;
//printResult();
}
else {
backtrack(i+1) ; // quay lui
}
}
}
void toHop() { // hà m li?t kê các t? h?p
if(k>=0 && k <=n ) {
a[0] = 0 ; // kh?i t?o giá tr? a[0]
backtrack(1) ;
}
}
int main()
{
while(1)
{
//cout<<"Nhan k va n: " ;
cin>>n>>k >> s;
if (n == 0 && k == 0 && s == 0) return 0;
toHop();
cout << res << endl;;
res = 0;
}
return 0;
}
| true |
6514cd272d5066ae39a4a39fcb68b400715a222c | C++ | Bananzarama/Babel | /babelbot.cpp | UTF-8 | 2,628 | 2.84375 | 3 | [] | no_license | /** //\
* V \
* \ \_
* \,'.`-.
* |\ `. `.
* ( \ `. `-. _,.-:\
* \ \ `. `-._ __..--' ,-';/
* \ `. `-. `-..___..---' _.--' ,'/
* `. `. `-._ __..--' ,' /
* `. `-_ ``--..'' _.-' ,'
* `-_ `-.___ __,--' ,'
* `-.__ `----""" __.-'
* `--..____..--'
*/
#include <iostream>
#include <cstdlib>
#include <string>
#include <fstream>
#include <time.h>
const int ascii_start = 97;
const int ascii_end = 122;
const int pageLength = 3200;
const int bookLength = 410;
const int lineBreak = 80;
/**
int msleep(unsigned long milisec)
{
struct timespec req={0};
time_t sec=(int)(milisec/1000);
milisec=milisec-(sec*1000);
req.tv_sec=sec;
req.tv_nsec=milisec*1000000L;
while(nanosleep(&req,&req)==-1)
continue;
return 1;
}
**/
void createPage(int page) {
int count = 0, spaces = 0, periods = 0, commas = 0;
std::ofstream nfile("Page" + std::to_string(page) + ".txt");
for (int i = 0; i < pageLength; i++) {
count++;
spaces++;
periods++;
commas++;
nfile << (char)(rand()
% ((ascii_end - ascii_start) + 1) + ascii_start);
if (spaces >= (rand() % 5) + rand() % 12) {
if (commas >= 15 + rand() % 50) {
if (rand()%2 == 0) {
nfile << ",";
commas = 0;
periods = 0;
count++;
} else {
commas = 0;
}
}
if (periods >= 15 + rand() % 50) {
if (rand()%4 != 0) {
nfile << ".";
periods = 0;
commas = 0;
count++;
} else {
periods = 0;
}
}
nfile << " ";
spaces = 0;
count++;
}
if (count >= lineBreak) {
nfile << "\n";
count = 0;
}
}
}
void createBook() {
int pageCount = 0;
for (int i = 0; i < bookLength; i++) {
pageCount++;
createPage(pageCount);
}
}
void electriceito() {
std::cout << "\nDon't waste electriceito\n";
std::cin.clear();
std::cin.ignore(1000, '\n');
}
int main(int argc, char *argv[]) {
srand(time(NULL));
if (argc == 1) {
electriceito();
} else {
std::string input = argv[1];
if (input == "book") {
createBook();
}
if (input == "page") {
int pageNum = atoi(argv[2]);
createPage(pageNum);
}
if (input != "book" and input != "page") {
electriceito();
}
}
return 0;
}
| true |
1fd125a61ecc48bc15430dabac100dd31793bd31 | C++ | super-ast/analyzers | /src/super_ast/analyzer/visitor/simple_fors.cpp | UTF-8 | 5,930 | 2.8125 | 3 | [] | no_license | #include "simple_fors.hpp"
namespace super_ast {
void SimpleFors::Visit(const super_ast::Node* node) {
node->AcceptChildren(*this);
}
std::vector<Error> SimpleFors::GetErrors() {
return errors_;
}
void SimpleFors::Visit(const For* forstmt) {
// Check that init is a declaration or an assignment
bool valid_init = false;
std::string var_name;
if (const VariableDeclaration* var_decl =
dynamic_cast<const VariableDeclaration*>(&forstmt->initialization())) {
var_name = var_decl->name();
valid_init = true;
}
if (const BinaryOperator* bop =
dynamic_cast<const BinaryOperator*>(&forstmt->initialization())) {
if (const Identifier* id = dynamic_cast<const Identifier*>(&bop->left())) {
var_name = id->value();
valid_init = true;
}
}
// Check simple condition
if (!IsSimpleCondition(&(forstmt->condition()))) {
Report(forstmt->condition(), "Complex condition",
"Condition in loop contains || or && operator");
}
if (!valid_init) {
Report(forstmt->initialization(), "Invalid init",
"For init is not a simple assignment or variable declaration");
} else {
const Expression* post = &forstmt->post_iteration();
// Check the postincrement
if (const UnaryOperator* uop = dynamic_cast<const UnaryOperator*>(post)) {
if (const Identifier* id =
dynamic_cast<const Identifier*>(&uop->expression())) {
if (id->value() == var_name) {
if (ModifiedVariable::IsModified(&forstmt->body(), var_name)) {
Report(*post, "Invalid for post iteration",
"Variable in post iteration is modified in the for body");
}
} else {
Report(*post, "Invalid for post iteration",
"Init var is different from post iteration var");
}
} else {
Report(*post, "Invalid for post iteration",
"Complex post iteration in loop");
}
}
else if (const BinaryOperator* bop =
dynamic_cast<const BinaryOperator*>(&forstmt->post_iteration())) {
// Get the id that is assigned to and check if it is the same as
// the variable in the init
if (const Identifier* id =
dynamic_cast<const Identifier*>(&bop->left())) {
if (id->value() == var_name) {
// Check the type 'var = var + k'
if (bop->type() == BinaryOperator::Type::ASSIGNMENT) {
CheckAssign(&(bop->right()), var_name, &(forstmt->body()));
}
// Check the type 'var += k'
else if (bop->type() == BinaryOperator::Type::ASSIGN_ADDITION ||
bop->type() == BinaryOperator::Type::ASSIGN_SUBTRACTION) {
CheckAssignSum(&(bop->right()), var_name, &(forstmt->body()));
} else {
Report(*post, "Invalid for post iteration",
"Complex post iteration");
}
} else {
Report(*post, "Invalid for post iteration",
"Init variable is different from post iteration variable");
}
} else {
Report(*post, "Invalid for post iteration",
"Left part of assignement in post iteration is not an identifier");
}
} else {
Report(*post, "Invalid for post iteration",
"Complex post iteration in loop");
}
}
forstmt->AcceptChildren(*this);
}
bool SimpleFors::IsSimpleCondition(const Expression* expr) {
if (const BinaryOperator* bop = dynamic_cast<const BinaryOperator*>(expr)) {
return (bop->type() != BinaryOperator::Type::AND &&
bop->type() != BinaryOperator::Type::OR);
}
return false;
}
bool SimpleFors::IsValidBinaryOperator(const BinaryOperator* bop) {
return bop->type() == BinaryOperator::Type::ASSIGNMENT ||
bop->type() == BinaryOperator::Type::ASSIGN_ADDITION ||
bop->type() == BinaryOperator::Type::ASSIGN_SUBTRACTION;
}
void SimpleFors::CheckAssign(const Expression* expr, const std::string& initName,
const Block* body) {
if (const BinaryOperator* bop = dynamic_cast<const BinaryOperator*>(expr)) {
// Check if initVar is in both sides
if (const Identifier* id = dynamic_cast<const Identifier*>(&bop->left())) {
if (id->value() == initName && IsSimpleConstValue(&bop->right(), body))
return;
}
if (const Identifier* id = dynamic_cast<const Identifier*>(&bop->right())) {
if (id->value() == initName && IsSimpleConstValue(&bop->left(), body))
return;
}
}
Report(*expr, "Invalid for post iteration",
"Post iteration variable not incremented by a constant");
}
void SimpleFors::CheckAssignSum(const Expression* expr, const std::string& initName,
const Block* body) {
bool valid = true;
// Check for initVar += initVar
if (const Identifier* id = dynamic_cast<const Identifier*>(expr)) {
valid = id->value() != initName;
}
if (!IsSimpleConstValue(expr, body))
valid = false;
if (!valid)
Report(*expr, "Invalid for post iteration",
"Post iteration variable not incremented by a constant");
}
// Returns true if the value node is a literal or a variable not
// modified in the body block.
bool SimpleFors::IsSimpleConstValue(const Node* value, const Block* body) {
// Return true if it is already a literal
if (dynamic_cast<const Integer*>(value) ||
dynamic_cast<const Double*>(value) ||
dynamic_cast<const Boolean*>(value)) {
return true;
}
// Check if it is an unmodified identifier
if (const Identifier* id = dynamic_cast<const Identifier*>(value)) {
return !ModifiedVariable::IsModified(body, id->value());
}
return false;
}
void SimpleFors::Report(const Node& node, const std::string short_message,
const std::string long_message) {
int line = -1;
if (const Statement* stmt = dynamic_cast<const Statement*>(&node)) {
line = stmt->line();
}
errors_.push_back(Error(line, "", short_message, long_message));
}
};
| true |
40ecad014018d633adff80dbcf40c6cd16e53575 | C++ | thelwyn/AI-on-the-edge-device | /code/components/jomjol_image_proc/CRotateImage.h | UTF-8 | 594 | 2.546875 | 3 | [
"MIT"
] | permissive | #include "CImageBasis.h"
class CRotateImage: public CImageBasis
{
public:
CImageBasis *ImageTMP;
CRotateImage(std::string _image) : CImageBasis(_image) {ImageTMP = NULL;};
CRotateImage(uint8_t* _rgb_image, int _channels, int _width, int _height, int _bpp) : CImageBasis(_rgb_image, _channels, _width, _height, _bpp) {ImageTMP = NULL;};
CRotateImage(CImageBasis *_org, CImageBasis *_temp);
void Rotate(float _angle);
void Rotate(float _angle, int _centerx, int _centery);
void Translate(int _dx, int _dy);
void Mirror();
};
| true |
ffadc262d131093f68507d9e23b07459b4d28eb8 | C++ | nikhilpanju/CubeSolver | /Sources/scrambledialog2x2.cpp | UTF-8 | 3,351 | 2.75 | 3 | [] | no_license | #include "../Header/scrambledialog2x2.h"
#include "ui_scrambledialog2x2.h"
// Initialize the scramble variables which store the scrambled state of the cube
QString whiteFace2_scramble = "wwww", yellowFace2_scramble = "yyyy", greenFace2_scramble = "gggg",
blueFace2_scramble = "bbbb", redFace2_scramble = "rrrr", orangeFace2_scramble = "oooo";
/* This function takes a character from the "_scramble" strings and converts it into a stylesheet string
* based on the colour (r, w, y, g, b, o) which can then be applied to the buttons to display the
* scrambled state
*/
QString convertToStyleSheet2(QChar s)
{
if (s == 'w')
return "background-color: rgb(255, 255, 255);";
else if (s == 'y')
return "background-color: rgb(255, 255, 0);";
else if (s == 'g')
return "background-color: rgb(85, 255, 0);";
else if (s == 'b')
return "background-color: rgb(0, 0, 255);";
else if (s == 'r')
return "background-color: rgb(255, 0, 0);";
else if (s == 'o')
return "background-color: rgb(255, 170, 0);";
return "background-color: rgb(0, 0, 0, 50);";
}
scrambleDialog2x2::scrambleDialog2x2(QWidget *parent) :
QDialog(parent),
ui(new Ui::scrambleDialog2x2)
{
ui->setupUi(this);
/* All the buttons in this dialog are set to show the colour as specified
* in the "_scramble" variable which is derived from the convertScramble function
* from solver.cpp
*/
ui->ws0_2->setStyleSheet(convertToStyleSheet2(whiteFace2_scramble[0]));
ui->ws1_2->setStyleSheet(convertToStyleSheet2(whiteFace2_scramble[1]));
ui->ws2_2->setStyleSheet(convertToStyleSheet2(whiteFace2_scramble[2]));
ui->ws3_2->setStyleSheet(convertToStyleSheet2(whiteFace2_scramble[3]));
ui->ys0_2->setStyleSheet(convertToStyleSheet2(yellowFace2_scramble[0]));
ui->ys1_2->setStyleSheet(convertToStyleSheet2(yellowFace2_scramble[1]));
ui->ys2_2->setStyleSheet(convertToStyleSheet2(yellowFace2_scramble[2]));
ui->ys3_2->setStyleSheet(convertToStyleSheet2(yellowFace2_scramble[3]));
ui->os0_2->setStyleSheet(convertToStyleSheet2(orangeFace2_scramble[0]));
ui->os1_2->setStyleSheet(convertToStyleSheet2(orangeFace2_scramble[1]));
ui->os2_2->setStyleSheet(convertToStyleSheet2(orangeFace2_scramble[2]));
ui->os3_2->setStyleSheet(convertToStyleSheet2(orangeFace2_scramble[3]));
ui->gs0_2->setStyleSheet(convertToStyleSheet2(greenFace2_scramble[0]));
ui->gs1_2->setStyleSheet(convertToStyleSheet2(greenFace2_scramble[1]));
ui->gs2_2->setStyleSheet(convertToStyleSheet2(greenFace2_scramble[2]));
ui->gs3_2->setStyleSheet(convertToStyleSheet2(greenFace2_scramble[3]));
ui->rs0_2->setStyleSheet(convertToStyleSheet2(redFace2_scramble[0]));
ui->rs1_2->setStyleSheet(convertToStyleSheet2(redFace2_scramble[1]));
ui->rs2_2->setStyleSheet(convertToStyleSheet2(redFace2_scramble[2]));
ui->rs3_2->setStyleSheet(convertToStyleSheet2(redFace2_scramble[3]));
ui->bs0_2->setStyleSheet(convertToStyleSheet2(blueFace2_scramble[0]));
ui->bs1_2->setStyleSheet(convertToStyleSheet2(blueFace2_scramble[1]));
ui->bs2_2->setStyleSheet(convertToStyleSheet2(blueFace2_scramble[2]));
ui->bs3_2->setStyleSheet(convertToStyleSheet2(blueFace2_scramble[3]));
}
scrambleDialog2x2::~scrambleDialog2x2()
{
delete ui;
}
| true |
2562c794428de7b1f414dcf34a22fdad9f34fe86 | C++ | EdwardLam10/C- | /CSCI 235 Project 3/dictionary.cpp | UTF-8 | 1,959 | 3.484375 | 3 | [] | no_license | /***************************************************************
Title: dictionary.cpp
Author: Edward Lam
Date Created: 5/07/2017
Class: Spring 2017, CSCI 235-03, Mon & Wed 5:35pm-6:50pm
Professor: Michael Garod
Purpose: Assignment #3
Description: .cpp file for dictionary class.
***************************************************************/
#include "dictionary.h"
using namespace std;
//dictionary class constructor
dictionary::dictionary(string input) {
if(dictionary_.isEmpty()) {
load(input);
} else {
dictionary_.clear();
load(input);
}
}
//loads file and inserts evyerthing in the file into the dictionary.
void dictionary::load(string input) {
ifstream loadFile;
loadFile.open(input);
while(!loadFile.eof()) {
string word;
getline(loadFile, word);
dictionary_.insert(word);
}
}
void dictionary::suggest(string input, int num) {
if(!dictionary_.contains(input)) {
cout << input << " was not found in the dictionary." << endl;
} else {
trieNode* trav = dictionary_.getNode(input); //traverse to the node that we need to start at.
queue<trieNode*> nodeQ; //Queue needed for level order traversal
int wordsPrinted = 0;
nodeQ.push(trav);
do {
suggestHelper(nodeQ.front(), wordsPrinted);
for(char counter = 'a'; counter != '{'; counter++) {
if(nodeQ.front()->contains(counter)) {
nodeQ.push(nodeQ.front()->getNext(counter));
}
}
nodeQ.pop();
if(nodeQ.empty()) { //If all words have been printed before reaching number of requested words.
break;
}
} while(wordsPrinted < num);
}
}
//Checks if trieNode contains the end of a word. If it does,
//it will call the makeWord function from the trie class to
//retrieve the word asscociated with that node.
void dictionary::suggestHelper(trieNode* in, int &i) {
if(in->getWord()) {
cout << dictionary_.makeWord(in) << endl;
i++;
}
}
| true |
622fbd968d8dc9302165597a647551bac513d90d | C++ | denis-gubar/Leetcode | /Greedy/0402. Remove K Digits.cpp | UTF-8 | 718 | 3.078125 | 3 | [] | no_license | class Solution {
public:
string removeKdigits(string num, int k) {
string result(num);
string prefix;
auto pos = result.find('0');
while (pos != string::npos && pos <= k)
{
result = result.size() > pos + 1 ? result.substr(pos + 1) : "";
k -= pos;
pos = result.find('0');
}
for (char c = '1'; k && c <= '9'; ++c)
{
pos = result.find(c);
while (pos != string::npos && pos <= k)
{
result = result.size() > pos + 1 ? result.substr(pos + 1) : "";
k -= pos;
prefix += c;
c = '0';
pos = result.find(c);
}
}
result = prefix + result;
while (k && !result.empty())
{
result.pop_back();
--k;
}
if (result.empty())
result = "0";
return result;
}
}; | true |
cfe63001933ee9ded0367a71a79c16e6b28ff1c8 | C++ | Priyadarshanvijay/Codingblocks-2018 | /Linked_lists/detectCycleLinkList.cc | UTF-8 | 1,249 | 4.03125 | 4 | [] | no_license | #include <iostream>
using namespace std;
class Node{
public:
int data;
Node* next;//self referential classes
Node(int d){
data = d;
next = NULL;
}
};
Node* createLinkList(){
int x;
Node* head = NULL;
Node* tail = NULL;
while(true){
cin>>x;
if(x==-1) break;
Node* newNode = new Node(x);
if(head==NULL)
{
head = newNode;
tail = newNode;
}
else
{
tail->next = newNode; //we use . operator when we try to access the data member of object so the equivalent
tail = tail->next; //expression of this would be (*next).tail
}
}
return head;
}
Node* detectCycle(Node* head)
{
Node* tortoise = head;
Node* hare = head;
while(tortoise && hare && hare->next)
{
tortoise = tortoise->next;
hare = hare->next->next;
if(tortoise == hare) break;
}
if(hare && hare->next == NULL) return NULL;
return hare;
}
void removeLoop(Node* head)
{
Node* meetingPoint = detectCycle(head);
Node* start = head;
while(meetingPoint)
}
int main(){
Node* head = createLinkList();
//construct a loop
Node* tail = head;
while(tail->next) {tail = tail->next;}
tail->next = head->next->next->next;
Node* loopNode = detectCycle(head)
if (loopNode) cout << "has loop\n " ;
return 0;
} | true |
f7f9d2389b0ce6510e99e6d54ba8a056434a05fe | C++ | vashj1995/Galactic-Polar-Wars-Final | /Galactic Polar Wars/src/Floor.h | UTF-8 | 503 | 2.65625 | 3 | [] | no_license | #pragma once
#ifndef __FLOOR__
#define __FLOOR__
#include "DisplayObject.h"
#include "FloorType.h"
class Floor final : public DisplayObject {
public:
Floor();
Floor(glm::vec2 position, FloorType type);
~Floor();
// Inherited via GameObject
virtual void draw() override;
virtual void update() override;
virtual void clean() override;
void setFloorType(FloorType type);
FloorType getFloorType() const;
private:
FloorType m_floorType;
void m_checkBounds();
void m_reset();
};
#endif
| true |
9e60d6a261178551958fa37a9a6e4164ddaf13ad | C++ | Moaz-Elmaatawy/Algorithmic-toolbox | /week3_greedy_algorithms/7_maximum_salary/largest_number3.cpp | UTF-8 | 704 | 2.625 | 3 | [] | no_license | #include <algorithm>
#include <sstream>
#include <iostream>
#include <vector>
#include <string>
using namespace std ;
void largest_number(vector<string> v ,int n) {
string max0;int index=0 ;
for (int j=0;j<n;++j){
for (int i=0;i<n;++i){
if (v[i][0]>max0[0]){
max0=v[i];
index=i;
}
else if (v[i][0]==max0[0]){
if(v[i]+max0 > max0+v[i]){
index=i;
max0=v[i];
}
}
}
cout<<v[index];
max0="";
v[index]="";
}
}
int main() {
int n;
cin >> n;
vector<string> a(n);
for (int i = 0; i < a.size(); i++) {
cin >> a[i];
}
largest_number(a,n);
}
| true |
deb661c635a8d6bf9f5a8d80c343a495062fba63 | C++ | gsrbr/SrDuino | /Code/ping_pong/ping_pong.ino | UTF-8 | 6,282 | 2.75 | 3 | [
"MIT"
] | permissive | // Projeto 37 – Jogo do Ping Pong com LCD Nokia 5110
//Edited by Cogumelinho and gsrbr
// Setando os pinos do LCD Nokia 5110 no Arduino Uno
#define PIN_SCE 11
#define PIN_RESET 12
#define PIN_DC 10
#define PIN_SDIN 9
#define PIN_SCLK 8
#define PIN_BUZZER 3
#define pot 2
#define LCD_C LOW
#define LCD_D HIGH
// Inicializa o LCD com apenas 504 pixels de resolução.
#define LCD_X 84
#define LCD_Y 6
int barWidth = 14; // Comprimento das barras.
int barHeight = 4; // Largura das barras.
int ballPerimeter = 5; // Tamanho da bola.
unsigned int bar1X = 0;
unsigned int bar1Y = 0;
unsigned int bar2X = 0;
unsigned int bar2Y = LCD_Y * 8 - barHeight;
int ballX = 0;
int ballY = 0;
boolean isBallUp = false;
boolean isBallRight = true;
byte pixels[LCD_X][LCD_Y];
unsigned long lastRefreshTime;
const int refreshInterval = 150;
byte gameState = 3; // Estágios do game.
byte ballSpeed = 4; // Velocidadeda bola.
byte player1WinCount = 0;
byte player2WinCount = 0;
byte hitCount = 0;
void setup(){
pinMode(PIN_BUZZER, OUTPUT);
// Inicializa as funções abaixo.
LcdInitialise();
restartGame();
pinMode(pot, OUTPUT);
digitalWrite(pot,HIGH);
}
void loop(){
unsigned long now = millis();
if(now - lastRefreshTime > refreshInterval){
update();
refreshScreen();
lastRefreshTime = now;
}
}
// Função reinciar jogo.
void restartGame(){
ballSpeed = 1;
gameState = 1;
ballX = random(0, 60);
ballY = 20;
isBallUp = false;
isBallRight = true;
hitCount = 0;
}
// Função atualzar tela do LCD.
void refreshScreen(){
if(gameState == 1){
for(int y = 0; y < LCD_Y; y++){
for(int x = 0; x < LCD_X; x++){
byte pixel = 0x00;
int realY = y * 8;
// Inicia a bola na tela.
if(x >= ballX && x <= ballX + ballPerimeter -1 && ballY + ballPerimeter >
realY && ballY < realY + 8 ){
byte ballMask = 0x00;
for(int i = 0; i < realY + 8 - ballY; i++){
ballMask = ballMask >> 1;
if(i < ballPerimeter)
ballMask = 0x80 | ballMask;
}
pixel = pixel | ballMask;
}
// Inicia a barra na tela.
if(x >= bar1X && x <= bar1X + barWidth -1 && bar1Y + barHeight > realY &&
bar1Y < realY + 8 ){
byte barMask = 0x00;
for(int i = 0; i < realY + 8 - bar1Y; i++){
barMask = barMask >> 1;
if(i < barHeight)
barMask = 0x80 | barMask;
}
pixel = pixel | barMask;
}
if(x >= bar2X && x <= bar2X + barWidth -1 && bar2Y + barHeight > realY
&& bar2Y < realY + 8 ){
byte barMask = 0x00;
for(int i = 0; i < realY + 8 - bar2Y; i++){
barMask = barMask >> 1;
if(i < barHeight)
barMask = 0x80 | barMask;
}
pixel = pixel | barMask;
}
LcdWrite(LCD_D, pixel);
}
}
} else if(gameState == 2){
// Faz a tratativa dos estágios do jogo.
int pinOut = 8;
int freq = 150;
int duration = 1000;
tone(pinOut, freq, duration);
}
}
void update(){
if(gameState == 1){
int barMargin = LCD_X - barWidth;
// Lê os joysticks e posiciona as barras no LCD.
int joystick1 = analogRead(A0);
int joystick2 = analogRead(A1);
bar1X = joystick1 / 2 * LCD_X / 512;
bar2X = joystick2 / 2 * LCD_X / 512;
if(bar1X > barMargin) bar1X = barMargin;
if(bar2X > barMargin) bar2X = barMargin;
// Movimento da bola.
if(isBallUp)
ballY -= ballSpeed;
else
ballY += ballSpeed;
if(isBallRight)
ballX += ballSpeed;
else
ballX -= ballSpeed;
// Verifica se ouve colisões.
if(ballX < 1){
isBallRight = true;
ballX = 0;
}
else if(ballX > LCD_X - ballPerimeter - 1){
isBallRight = false;
ballX = LCD_X - ballPerimeter;
}
if(ballY < barHeight){
// Faz com que a bola ping para a barra 1.
if(ballX + ballPerimeter >= bar1X && ballX <= bar1X + barWidth){
isBallUp = false;
if(ballX + ballPerimeter/2 < bar1X + barWidth/2)
isBallRight = false;
else
isBallRight = true;
ballY = barHeight;
if(++hitCount % 10 == 0 && ballSpeed < 5)
ballSpeed++;
}else{
// Jogador 2 é o vencedor.
gameState = 2;
player2WinCount++;
}
}
if(ballY + ballPerimeter > LCD_Y * 8 - barHeight){
// Faz com que a bola ping para a barra 2.
if(ballX + ballPerimeter >= bar2X && ballX <= bar2X + barWidth){
isBallUp = true;
if(ballX + ballPerimeter/2 < bar2X + barWidth/2)
isBallRight = false;
else
isBallRight = true;
ballY = LCD_Y * 8 - barHeight - ballPerimeter;
if(++hitCount % 10 == 0 && ballSpeed < 5)
ballSpeed++;
}
else{ // Jogar 1 é o vencedor.
gameState = 2;
player1WinCount++;
}
}
}else if(gameState == 2){
for(int i =0; i < 4; i++){
LcdWrite(LCD_C, 0x0D ); // LCD no modo inverso.
delay(300);
LcdWrite(LCD_C, 0x0C );
delay(300);
}
restartGame(); // Chama da função para resetar o game.
}
}
// Inicializa o LCD.
void LcdInitialise(void){
pinMode(PIN_SCE, OUTPUT);
pinMode(PIN_RESET, OUTPUT);
pinMode(PIN_DC, OUTPUT);
pinMode(PIN_SDIN, OUTPUT);
pinMode(PIN_SCLK, OUTPUT);
delay(200);
digitalWrite(PIN_RESET, LOW);
delay(500);
digitalWrite(PIN_RESET, HIGH);
LcdWrite(LCD_C, 0x21 ); // Comandos ampliados do LCD.
LcdWrite(LCD_C, 0xB1 ); // Configura o contraste do LCD.
LcdWrite(LCD_C, 0x04 ); // Configura o tempo de coeficiente.
LcdWrite(LCD_C, 0x14 );
LcdWrite(LCD_C, 0x0C ); // LCD em modo normal.
LcdWrite(LCD_C, 0x20 );
LcdWrite(LCD_C, 0x80 );
LcdWrite(LCD_C, 0x40 );
LcdWrite(LCD_C, 0x0C );
}
void LcdWrite(byte dc, byte data){
digitalWrite(PIN_DC, dc);
digitalWrite(PIN_SCE, LOW);
shiftOut(PIN_SDIN, PIN_SCLK, MSBFIRST, data);
digitalWrite(PIN_SCE, HIGH);
}
| true |
cf3fb58e6ae0448f4e4f02979b7306df45b4d47f | C++ | geekscape/rgb_led | /rgb_led.ino | UTF-8 | 5,713 | 3.1875 | 3 | [] | no_license | /*
* File: rgb_led.ino
* Version: 0.0
* Author: Andy Gelme (@geekscape)
* License: GPLv3
*/
#include <math.h>
#include <TimerOne.h>
#include "rgb_led.h"
const byte PIN_LED_CLOCK = 7;
const byte PIN_LED_DATA = 8;
const byte LED_COUNT = 16;
rgb_t led[LED_COUNT];
const long BLEND_RATE = 100; // milliseconds
byte blendFlag = false;
long blendDoneTime = 0;
long blendNextTime = 0;
rgb_t ledDelta[LED_COUNT];
rgb_t ledTarget[LED_COUNT];
int ledOffset = 0; // Adjust starting point for using led[] array for output
rgb_t colors[] = {
RED, ORANGE, YELLOW, GREEN, BLUE, PINK, PURPLE, WHITE
};
const byte COLORS_COUNT = sizeof(colors) / sizeof(rgb_t);
void setup() {
pinMode(PIN_LED_DATA, OUTPUT);
pinMode(PIN_LED_CLOCK, OUTPUT);
ledSetAll(BLACK);
Timer1.initialize(30000);
Timer1.attachInterrupt(ledHandler);
}
void loop() {
ledSetAll(BLACK);
// Pulse a sequence of colors
// --------------------------
for (byte index = 0; index < COLORS_COUNT; index ++) {
ledPulse(colors[index], 1000);
}
// Create pattern of dark through to bright RED LEDs
// Shift (rotate) the pattern along the line of LEDs
// -------------------------------------------------
ledFadeUp(RED);
for (byte count = 0; count < 128; count ++) {
ledOffset = (ledOffset + 1) % LED_COUNT;
delay(25);
}
ledOffset = 0;
// Blend from one sequence of random LED colors to the next
// --------------------------------------------------------
for (byte count = 0; count < 16; count ++) {
for (byte index = 0; index < LED_COUNT; index ++) {
ledTarget[index] =
RGB(random(0, 2) * 255, random(0, 2) * 255, random(0, 2) * 255);
}
blend(1000);
delay(1000); // Wait for blend to complete
}
}
void ledSet(
byte index, // LED number
rgb_t rgb) { // RGB color
noInterrupts();
led[index].color[RED_INDEX] = rgb.color[RED_INDEX];
led[index].color[GREEN_INDEX] = rgb.color[GREEN_INDEX];
led[index].color[BLUE_INDEX] = rgb.color[BLUE_INDEX];
interrupts();
}
void ledSetAll(
rgb_t rgb) { // RGB color
for (byte count = 0; count < LED_COUNT; count ++) ledSet(count, rgb);
}
const float FADE_FACTOR = 10000000.0;
const float FADE_INCREMENT = (FADE_FACTOR - 1.0) / (LED_COUNT - 1);
const float FADE_SCALE = log(FADE_FACTOR);
void ledFadeUp(
rgb_t rgb) { // RGB color
float factor = FADE_FACTOR;
float previous = log(factor);
float multiplier = 0.0;
for (int count = 0; count < LED_COUNT; count ++) {
float current = log(factor);
multiplier += (previous - current);
previous = current;
factor -= FADE_INCREMENT;
float red = rgb.color[RED_INDEX] * multiplier / FADE_SCALE;
float green = rgb.color[GREEN_INDEX] * multiplier / FADE_SCALE;
float blue = rgb.color[BLUE_INDEX] * multiplier / FADE_SCALE;
ledSet(count, RGB(red, green, blue));
}
}
void ledPulse(
rgb_t rgb, // RGB color
int speed) { // Pulse time in milliseconds
int red = 0;
int green = 0;
int blue = 0;
int redDelta = (rgb.color[RED_INDEX] << 7) / 256;
int greenDelta = (rgb.color[GREEN_INDEX] << 7) / 256;
int blueDelta = (rgb.color[BLUE_INDEX] << 7) / 256;
for (int count = 0; count < 512; count ++) {
ledSetAll(RGB(red >> 7, green >> 7, blue >> 7));
red += redDelta;
green += greenDelta;
blue += blueDelta;
if (count == 255) {
redDelta = -redDelta;
greenDelta = -greenDelta;
blueDelta = -blueDelta;
}
delayMicroseconds(speed);
}
}
void blend(
long blendSpeed) { // Blend time in milliseconds
for (byte count = 0; count < LED_COUNT; count ++) {
ledDelta[count].color[RED_INDEX] =
((ledTarget[count].color[RED_INDEX] - led[count].color[RED_INDEX]) << 7) /
(blendSpeed / BLEND_RATE);
ledDelta[count].color[GREEN_INDEX] =
((ledTarget[count].color[GREEN_INDEX] - led[count].color[GREEN_INDEX]) << 7) /
(blendSpeed / BLEND_RATE);
ledDelta[count].color[BLUE_INDEX] =
((ledTarget[count].color[BLUE_INDEX] - led[count].color[BLUE_INDEX]) << 7) /
(blendSpeed / BLEND_RATE);
}
blendNextTime = millis();
blendDoneTime = blendNextTime + blendSpeed;
blendFlag = true;
}
int blender(
int value,
int delta) {
return(((value << 7) + delta) >> 7);
}
// Output led[] array to the strip of WS2801 RGB LEDs
// Every BLEND_RATE milliseconds, blend LEDs toward target colors
void ledHandler(void) {
for (byte count = 0; count < LED_COUNT; count ++) {
byte index = (ledOffset + count) % LED_COUNT;
unsigned long color = led[index].color[BLUE_INDEX];
color |= (unsigned long) led[index].color[GREEN_INDEX] << 8;
color |= (unsigned long) led[index].color[RED_INDEX] << 16;
for (byte bit = 0; bit < 24; bit ++) {
digitalWrite(PIN_LED_CLOCK, LOW);
digitalWrite(PIN_LED_DATA, (color & (1L << 23)) ? HIGH : LOW);
digitalWrite(PIN_LED_CLOCK, HIGH);
color <<= 1;
}
}
digitalWrite(PIN_LED_CLOCK, LOW); // Must stay low for 500 microseconds
if (blendFlag) {
long timeNow = millis();
if (timeNow > blendNextTime) {
blendNextTime = timeNow + BLEND_RATE;
for (byte index = 0; index < LED_COUNT; index ++) {
led[index].color[RED_INDEX] = blender(
led[index].color[RED_INDEX], ledDelta[index].color[RED_INDEX]
);
led[index].color[GREEN_INDEX] = blender(
led[index].color[GREEN_INDEX], ledDelta[index].color[GREEN_INDEX]
);
led[index].color[BLUE_INDEX] = blender(
led[index].color[BLUE_INDEX], ledDelta[index].color[BLUE_INDEX]
);
}
}
if (timeNow >= blendDoneTime) blendFlag = false;
}
}
| true |
ba19a6baa845db8be97a1b4852b7a434b4db346a | C++ | zxnrbl/micromouse | /State.cpp | UTF-8 | 4,569 | 2.53125 | 3 | [] | no_license | #include <algorithm>
#include <iostream>
#include <queue>
#include <vector>
#include "State.h"
#include "API.h"
#include "Map.h"
#include "Mouse.h"
void IState::Enter( Mouse& context ) {
}
void IState::Exit( Mouse& context ) {
}
void IState::PreUpdate( Mouse& context ) {
}
void IState::PostUpdate( Mouse& context ) {
}
Unknown::Unknown() {
}
Unknown::~Unknown() {
}
IState& Unknown::Instance() {
static Unknown instance;
return instance;
}
StateEnum Unknown::State() const {
return STATE_UNKNOWN;
}
void Unknown::Update( Mouse& context ) {
}
Idle::Idle() {
}
Idle::~Idle() {
}
IState& Idle::Instance() {
static Idle instance;
return instance;
}
StateEnum Idle::State() const {
return STATE_IDLE;
}
void Idle::Update( Mouse& context ) {
context.ChangeState( Exploring::Instance() );
}
Exploring::Exploring() {
}
Exploring::~Exploring() {
}
IState& Exploring::Instance() {
static Exploring instance;
return instance;
}
StateEnum Exploring::State() const {
return STATE_EXPLORING;
}
void Exploring::Enter( Mouse& context ) {
std::clog << "Exploring Enter" << std::endl;
std::queue< MoveEnum > empty;
std::swap( _queue, empty );
context.GetMap()->CurrentPosition().Visit( true );
context.AddGoal( Coordinate( 7, 7 ) );
context.AddGoal( Coordinate( 7, 8 ) );
context.AddGoal( Coordinate( 8, 7 ) );
context.AddGoal( Coordinate( 8, 8 ) );
API::setColor( context.GetMap()->CurrentPosition().XY().X(), context.GetMap()->CurrentPosition().XY().Y(), 'c' );
}
void Exploring::Update( Mouse& context ) {
context.CheckWalls();
context.ResetFlood();
context.CalcFlood();
context.BestStep();
if( context.AtGoal() )
context.RemoveGoal();
if( context.Goals().empty() )
context.ChangeState( Mapping::Instance() );
}
void Exploring::Exit( Mouse& context ) {
context.ClearGoals();
}
Returning::Returning() {
}
Returning::~Returning() {
}
IState& Returning::Instance() {
static Returning instance;
return instance;
}
StateEnum Returning::State() const {
return STATE_RETURNING;
}
void Returning::Enter( Mouse& context ) {
std::clog << "Returning Enter" << std::endl;
context.AddGoal( Coordinate( 0, 0 ) );
}
void Returning::Update( Mouse& context ) {
context.CheckWalls();
context.ResetFlood();
context.CalcFlood();
context.BestStep();
if( context.AtGoal() )
context.ChangeState( Speeding::Instance() );
}
void Returning::Exit( Mouse& context ) {
context.ClearGoals();
}
Mapping::Mapping() {
}
Mapping::~Mapping() {
}
IState& Mapping::Instance() {
static Mapping instance;
return instance;
}
StateEnum Mapping::State() const {
return STATE_MAPPING;
}
void Mapping::Update( Mouse& context ) {
bool complete = context.Goals().empty();
if( context.Goals().empty() ) {
for( auto row = 0; row < 16; ++row ) {
for( auto col = 0; col < 16; ++col ) {
if( !context.GetMap()->At( Coordinate( col, row ) ).Visited() ) {
complete = false;
context.AddGoal( Coordinate( col, row ) );
break;
}
}
if( !complete ) break;
}
}
else {
context.CheckWalls();
context.ResetFlood();
context.CalcFlood();
context.BestStep();
}
if( context.AtGoal() )
context.RemoveGoal();
if( complete && context.Goals().empty() )
context.ChangeState( Returning::Instance() );
}
void Mapping::Exit( Mouse& context ) {
context.ClearGoals();
}
Speeding::Speeding() {
}
Speeding::~Speeding() {
}
IState& Speeding::Instance() {
static Speeding instance;
return instance;
}
StateEnum Speeding::State() const {
return STATE_SPEEDING;
}
void Speeding::Enter( Mouse& context ) {
context.AddGoal( Coordinate( 7, 7 ) );
context.AddGoal( Coordinate( 7, 8 ) );
context.AddGoal( Coordinate( 8, 7 ) );
context.AddGoal( Coordinate( 8, 8 ) );
context.ResetFlood();
context.CalcFlood();
}
void Speeding::Update( Mouse& context ) {
context.BestStep();
if( context.AtGoal() )
context.ChangeState( Complete::Instance() );
}
void Speeding::Exit( Mouse& context ) {
context.ClearGoals();
}
Complete::Complete() {
}
Complete::~Complete() {
}
IState& Complete::Instance() {
static Complete instance;
return instance;
}
StateEnum Complete::State() const {
return STATE_COMPLETE;
}
void Complete::Update( Mouse& context ){
}
| true |
1508fa1bac1e0903fdaf455af8aee792906ac1fa | C++ | Zarakinoa/Design-Patterns | /parciales/2017/DataCompOp.h | UTF-8 | 243 | 2.625 | 3 | [] | no_license | #include <string>
using namespace std;
class DataCompOp{
private:
string comp, op;
float precioOp;
public:
DataCompOp(string , string , float);
virtual ~DataCompOp();
string getComp();
string getOp();
float getPrecioOp();
}
| true |
33eca16490d133360d3d30c64f2f165e34679362 | C++ | rdpoor/mu | /sketches/sketch_estream6.cpp | UTF-8 | 3,848 | 3.59375 | 4 | [
"MIT"
] | permissive | /*
* side-effect free streams. Uses lambda to create deferred evaluation.
* Specialized streams are static methods of the general class.
*/
#include <functional>
#include <string>
#include <vector>
#define NULL_ESTREAM nullptr
#define IS_NULL_ESTREAM(s) ((s) == NULL_ESTREAM)
#define DEFER(form, T) [=]()->EStream<T>*{return (form);}
#define FORCE(deferred_form) (deferred_form())
#define CREATE_STREAM(first, rest, T) new EStream<T>((first), DEFER(rest, T))
template <typename T>class EStream {
protected:
T first_;
std::function<EStream<T> *()> rest_;
public:
EStream(T first, std::function<EStream<T> *()> rest) :
first_(first), rest_(rest) {}
T first() {
return first_;
}
EStream<T> *rest() {
return IS_NULL_ESTREAM(rest_) ? NULL_ESTREAM : FORCE(rest_);
}
// ================================================================
// utilities
static std::vector<T> *to_vector(EStream<T> *s, int maxcount) {
std::vector<T> *v = new std::vector<T>();
EStream<T> *s0 = s;
while (!IS_NULL_ESTREAM(s0) && (maxcount > 0)) {
v->push_back(s0->first());
EStream<T> *next = s0->rest();
if (s0 != s) { // don't delete caller's stream!
delete s0;
}
s0 = next;
maxcount -= 1;
}
return v;
}
// Static methods from here on
static EStream<T> *AppendES(EStream<T> *s0, EStream<T> *s1) {
if (IS_NULL_ESTREAM(s0)) {
return s1;
} else if (IS_NULL_ESTREAM(s1)) {
return s0;
} else {
return CREATE_STREAM(s0->first(), AppendES(s0->rest(), s1), T);
}
}
template <typename MapFn>
static EStream<T> *MapES(EStream<T> *s, MapFn mapfn) {
if (IS_NULL_ESTREAM(s)) {
return NULL_ESTREAM;
} else {
return CREATE_STREAM(mapfn(s->first()), MapES(s->rest(), mapfn), T);
}
}
template <typename PredFn>
static EStream<T> *MergeES(EStream<T> *s0, EStream<T> *s1, PredFn predfn) {
if (IS_NULL_ESTREAM(s0)) {
return s1;
} else if (IS_NULL_ESTREAM(s1)) {
return s0;
} else if (predfn(s0->first(), s1->first())) {
return CREATE_STREAM(s0->first(),
MergeES(s0->rest(), s1, predfn),
T);
} else {
return CREATE_STREAM(s1->first(),
MergeES(s0, s1->rest(), predfn),
T);
}
}
static EStream<T> *TakeES(EStream<T> *s, int n) {
if ((IS_NULL_ESTREAM(s)) || (n <= 0)) {
return NULL_ESTREAM;
} else {
return CREATE_STREAM(s->first(), TakeES(s->rest(), n-1), T);
}
}
};
// ================================================================
// specialize streams
EStream<int> *IntegersES(int starting) {
return CREATE_STREAM(starting, IntegersES(starting + 1), int);
}
// ================================================================
// main
int main( void ) {
EStream<int> *take0 = EStream<int>::TakeES(IntegersES(0), 4);
std::vector<int> *v0actual = EStream<int>::to_vector(take0, 1000);
std::vector<int> v0expected = { 0, 1, 2, 3 };
printf("take0: %s\n", *v0actual == v0expected ? "match" : "mismatch");
EStream<int> *append1 =
EStream<int>::AppendES(EStream<int>::TakeES(IntegersES(0), 4),
IntegersES(100));
std::vector<int> *v1actual = EStream<int>::to_vector(append1, 7);
std::vector<int> v1expected = { 0, 1, 2, 3, 100, 101, 102 };
printf("append1: %s\n", *v1actual == v1expected ? "match" : "mismatch");
EStream<int> *s3 = EStream<int>::MapES(IntegersES(0),
[=](int v) { return v * 3; });
std::vector<int> *s3actual = EStream<int>::to_vector(s3, 7);
std::vector<int> s3expected = { 0, 3, 6, 9, 12, 15, 18 };
printf("MapES: %s\n", *s3actual == s3expected ? "match" : "mismatch");
return 0;
}
| true |
da3224a2d52e9e8778083c8559ed43b85dd22861 | C++ | rhiestan/RegardRGBD | /src/Vector.h | UTF-8 | 1,036 | 3.640625 | 4 | [
"MIT"
] | permissive | #ifndef VECTOR_H
#define VECTOR_H
/**
* This template is a simple N-dimensional vector.
*
* The data members are not initialized to 0!
*/
template <typename T, unsigned int C>
class SimpleVector
{
public:
SimpleVector() { }
SimpleVector(const SimpleVector &other)
{
for(unsigned int i = 0; i < C; i++)
{
c[i] = other.c[i];
}
}
SimpleVector(T v1, T v2)
{
c[0] = v1;
c[1] = v2;
}
SimpleVector(T v1, T v2, T v3)
{
c[0] = v1;
c[1] = v2;
c[2] = v3;
}
T &operator [](unsigned int i)
{
return c[i];
}
const T &operator [](unsigned int i) const
{
return c[i];
}
SimpleVector &operator=(const SimpleVector & other)
{
for(unsigned int i = 0; i < C; i++)
{
c[i] = other.c[i];
}
return *this;
}
// The components (still public to make access easier and faster)
T c[C];
};
typedef SimpleVector<float, 3> SVector3f;
typedef SimpleVector<double, 3> SVector3d;
typedef SimpleVector<unsigned char, 3> SVector3b;
#endif
| true |
780fc0257b0ba7055a22b41d03924b4121a9ed72 | C++ | ioleon13/LeetCode | /Unique Paths.cpp | UTF-8 | 444 | 2.953125 | 3 | [] | no_license |
class Solution {
public:
int uniquePaths(int m, int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> vec(m,0);
vec[m-1] = 1;
for(int j = n-1; j >= 0; j--)
for(int i = m-1; i >= 0; i--)
{
int downVal = i+1 < m ? vec[i+1] : 0;
vec[i] = vec[i] + downVal;
}
return vec[0];
}
}; | true |
39fa8c2c389f5989cd792ddbb8f44665c869a481 | C++ | optifat/chess_engine | /main.cpp | UTF-8 | 3,484 | 2.859375 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <chrono>
#include <iomanip>
#include "pieces/include/Input_processor.h"
#include "tree/include/Tree.h"
#include "tree/include/Evaluator.h"
int main(int argc, char* argv[]) {
bool analysisMode = true;
for(int i = 1; i < argc; i++){;
auto flag = std::string(argv[i]);
if(flag == "-p" || flag == "--playmode"){
analysisMode = false;
}
else{
std::cout << "Ignoring unknown " << flag << " flag\n";
}
}
std::cout << "Enter FEN (leave empty for starting position)\n";
std::string FEN;
getline(std::cin, FEN);
if(FEN.empty()){
FEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq";
}
//std::string FEN = "K4BB1/1Q6/5p2/8/2R2r1r/N2N2q1/kp1p1p1p/b7 w - - 0 1";
Board board(FEN);
if(analysisMode){
std::cout << "Enter desired tree depth: \n";
int treeDepth = 1;
std::cin >> treeDepth;
Tree tree(std::make_shared<Board>(board));
auto start = std::chrono::high_resolution_clock::now();
tree.generateTree(treeDepth);
auto end = std::chrono::high_resolution_clock::now();
if (MAX_POS_VAL - abs(tree.getPositionValue()) < 100) {
std::cout << "#" << ((tree.getPositionValue() > 0) ?
(MAX_POS_VAL - tree.getPositionValue()) : (-MAX_POS_VAL - tree.getPositionValue())) << std::endl;
}
else {
std::cout << tree.getPositionValue()/100 << std::endl;
}
tree.optimalSequence();
std::cout << "Total nodes generated: " << tree.totalNodesGenerated() << std::endl;
std::cout << "Total tree generation time: " << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count()
<< " microseconds" << std::endl;
std::cout << (int)(1000000*(double)tree.totalNodesGenerated() / std::chrono::duration_cast<std::chrono::microseconds>(end-start).count())
<<" nodes per sec" << std::endl;
}
else {
std::cout << "Print pawn move (e2-e4 for example), the program should return initial and final pieces on these squares \n";
std::cout << "Print stop to exit the program \n";
while(true) {
board.printInfo();
board.showBoard();
if(board.checkmate()){
std::cout << "Checkmate. ";
if(board.whiteOrder()){
std::cout << "Black wins." << std::endl;
return 0;
}
else{
std::cout << "White wins." << std::endl;
return 0;
}
}
else if(board.stalemate()){
std::cout << "Stalemate. Draw.";
return 0;
}
std::cout << board.sideToMove() << std::endl;
std::string input;
std::cin >> input;
if (input == "stop") {
break;
} else {
auto start = std::chrono::high_resolution_clock::now();
Input_processor::readMove(board, input);
auto end = std::chrono::high_resolution_clock::now();
std::cout << "Duration: " << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count()
<< " microseconds" << std::endl;
}
}
}
/*board.showBoard();
std::cout << sizeof(board) << "\n";*/
return 0;
}
| true |
d89d2a16885dbe9eb8b41406c36e7ba30fed41fe | C++ | lim-james/Wind | /Core/Events/EventsManager.h | UTF-8 | 5,449 | 2.859375 | 3 | [] | no_license | #ifndef EVENTS_MANAGER_H
#define EVENTS_MANAGER_H
#include "Event.h"
#include "../Logger/Logger.h"
#include <string>
#include <map>
#include <vector>
#include <functional>
namespace Events {
class EventsManager {
static EventsManager* instance;
std::map<std::string, std::vector<std::function<void()>>> emptyCallbacks;
std::map<std::string, std::vector<std::function<void(Event*)>>> eventCallbacks;
std::map<void*, std::map<std::string, std::function<void()>*>> emptyContextCallbacks;
std::map<void*, std::map<std::string, std::function<void(Event*)>*>> eventContextCallbacks;
struct QueuedEvent {
std::string name;
Event* event;
};
std::vector<QueuedEvent> queuedEvents;
public:
~EventsManager();
static EventsManager* GetInstance();
static void Destroy();
// subscribe empty callbacks
template<typename Context>
void Subscribe(const std::string& name, void(Context::*callback)(), Context* const context);
template<typename Context>
void Subscribe(const std::string& name, void(Context::*callback)() const, Context* const context);
// subscribe event callbacks
template<typename Context>
void Subscribe(const std::string& name, void(Context::*callback)(Event*), Context* const context);
template<typename Context>
void Subscribe(const std::string& name, void(Context::*callback)(Event*) const, Context* const context);
void UnsubscribeAll();
void Unsubscribe(const std::string& name);
template<typename Context>
void UnsubscribeContext(Context* const context);
template<typename Context>
void Unsubscribe(const std::string& name, Context* const context);
void Trigger(const std::string& name);
void Trigger(const std::string& name, Event* const event);
template<typename Context>
void TriggerContext(const std::string& name, Context* const context);
template<typename Context>
void TriggerContext(const std::string& name, Context* const context, Event* const event);
void Queue(const std::string& name);
void Queue(const std::string& name, Event* const event);
void TriggerQueued();
};
template<typename Context>
void EventsManager::Subscribe(const std::string& name, void(Context::*callback)(), Context* const context) {
auto& list = emptyCallbacks[name];
list.push_back(std::bind(callback, context));
emptyContextCallbacks[(void*)context][name] = &list.back();
}
template<typename Context>
void EventsManager::Subscribe(const std::string& name, void(Context::*callback)() const, Context* const context) {
auto& list = emptyCallbacks[name];
list.push_back(std::bind(callback, context));
emptyContextCallbacks[(void*)context][name] = &list.back();
}
template<typename Context>
void EventsManager::Subscribe(const std::string& name, void(Context::*callback)(Event*), Context* const context) {
auto& list = eventCallbacks[name];
list.push_back(std::bind(callback, context, std::placeholders::_1));
eventContextCallbacks[(void*)context][name] = &list.back();
}
template<typename Context>
void EventsManager::Subscribe(const std::string& name, void(Context::*callback)(Event*) const, Context* const context) {
auto& list = eventCallbacks[name];
list.push_back(std::bind(callback, context, std::placeholders::_1));
eventContextCallbacks[(void*)context][name] = &list.back();
}
template<typename Context>
void EventsManager::UnsubscribeContext(Context* const context) {
void* ptr = (void*)context;
auto& empty = emptyContextCallbacks[ptr];
for (auto& pair : empty) {
auto& list = emptyCallbacks[pair.first];
for (unsigned i = 0; i < list.size(); ++i) {
if (&list[i] == pair.second) {
list.erase(list.begin() + i);
break;
}
}
}
empty.clear();
auto& events = eventContextCallbacks[ptr];
for (auto& pair : events) {
auto& list = eventCallbacks[pair.first];
unsigned i = 0;
for (; i < list.size(); ++i) {
if (&list[i] == pair.second) {
list.erase(list.begin() + i);
break;
}
}
}
events.clear();
}
template<typename Context>
void EventsManager::Unsubscribe(const std::string& name, Context* const context) {
void* ptr = (void*)context;
auto& empty = emptyContextCallbacks[ptr][name];
auto& emptyList = emptyCallbacks[name];
for (unsigned i = 0; i < emptyList.size(); ++i) {
if (&emptyList[i] == empty) {
emptyList.erase(emptyList.begin() + i);
break;
}
}
emptyContextCallbacks[ptr].erase(name);
auto& events = eventContextCallbacks[ptr][name];
auto& eventsList = eventCallbacks[name];
for (unsigned i = 0; i < eventsList.size(); ++i) {
if (&eventsList[i] == events) {
eventsList.erase(eventsList.begin() + i);
break;
}
}
eventContextCallbacks[ptr].erase(name);
}
template<typename Context>
void EventsManager::TriggerContext(const std::string& name, Context* const context) {
void* ptr = (void*)context;
if (emptyContextCallbacks.find(ptr) != emptyContextCallbacks.end())
*emptyContextCallbacks[ptr][name]();
}
template<typename Context>
void EventsManager::TriggerContext(const std::string& name, Context* const context, Event* const event) {
void* ptr = (void*)context;
if (emptyContextCallbacks.find(ptr) != emptyContextCallbacks.end())
(*emptyContextCallbacks[ptr][name])();
event->name = name;
if (eventContextCallbacks.find(ptr) != eventContextCallbacks.end())
(*eventContextCallbacks[ptr][name])(event);
delete event;
}
}
#endif
| true |
010a9bd6c9582ae2149909bb4161fc2098fb2b50 | C++ | harshasbu/Algorithms | /Algorithms/AddingBitStrings.cpp | UTF-8 | 1,262 | 3.671875 | 4 | [] | no_license | /*
* AddingBitStrings.cpp
*
* Created on: Jan 16, 2015
* Author: harsha
*/
#include<iostream>
using namespace std;
string makeStringEqualLength(string Number, int length){
//cout << "length is :" << length << endl;
for(int i=0;i<length;i++)
Number = '0' + Number;
//cout << Number << endl;
return Number;
}
string add(string Num1, string Num2){
int len1 = Num1.size();
int len2 = Num2.size();
//cout << "length of string1 :" << len1 <<endl << "length of string2 :" << len2 << endl;
if(len1 != len2)
if(len1 < len2)
Num1 = makeStringEqualLength(Num1, len2-len1);
else
Num2 = makeStringEqualLength(Num2, len1-len2);
//cout << Num1.length() << " "<<Num2.length() <<endl;
int sum = 0, carry = 0,i;
string result ;
for(i=(Num1.length()-1);i>=0; i--){
int firstBit = Num1.at(i) - '0';
int secondBit = Num2.at(i) - '0';
sum = (firstBit ^ secondBit ^ carry) +'0';
result = (char)sum + result;
carry = (firstBit & secondBit) | (secondBit & carry) | (carry & firstBit);
}
if(carry)
result = '1' + result;;
return result;
}
int main(){
string Num1, Num2;
cout << "Enter the two Bit Strings :";
cin >> Num1 >> Num2;
cout << "The sum in Bits is :" << add(Num1, Num2) << endl;
return 0;
}
| true |
85b5f65e7da885c716c1add13fd7d26c7bedb660 | C++ | Hammad-Ikhlaq/Computer-Programming | /CP Lectures/Structures/Structures_And_StructureArray(Simple).cpp | UTF-8 | 2,863 | 3.828125 | 4 | [] | no_license | # include <iostream>
using namespace std;
struct Wajahat
{
int id;
int age;
int name;
};
void input_Single_Data(Wajahat *S);
void input_All_Data(Wajahat *S, int &count);
void display(Wajahat S);
void display_All(Wajahat *S, int count);
int main()
{
//This Code is Only For Understanding So Thats Why Taking Name as Integer
//In order to make it as simplpe as possible....
// Method 1....
int id = 1, name = 1, age = 1;
Wajahat S1 = { id,age,name };
cout << "Data Record Of Student Using Method 1\n\n";
display(S1);
cout << endl << endl;
// Method 2....
Wajahat S2;
S2.id = 2;
S2.age = 2;
S2.name = 2;
cout << "Data Record Of Student Using Method 2\n\n";
display(S2);
cout << endl << endl;
// Method 3....
Wajahat S3 = { 3,3,3 };
cout << "Data Record Of Student Using Method 3\n\n";
display(S3);
cout << endl << endl;
// Method 4....
cout << "Input id , age , Name Respectively\n\n";
cin >> id >> age >> name;
Wajahat S4 = { id, age, name };
cout << "Data Record Of Student Using Method 4\n\n";
display(S4);
cout << endl << endl;
// Method 5 By Using Input Function....
Wajahat S5;
input_Single_Data(&S5);
cout << "Data Record Of Student Using Method 5\n\n";
display(S5);
//Method 6 Array of Structures....
cout << "\n\nMethod 6 : Arrays Of Structure\n\n";
cout << "Method 6 Has No Relation With The Previous Ones\n";
cout << "Creating a new Array To Store Data\n\n";
cout << "Just In Order To Know How to Use Array of Structs\n\n";
int count = 0;
Wajahat array_Of_Structure[50];
input_All_Data(array_Of_Structure, count);
cout << "Displaying All Student Data Saved IN Array \n\n";
display_All(array_Of_Structure, count);
system("pause");
}
void input_Single_Data(Wajahat *S)
{
cout << "Method 5\n\n";
cout << "Enter Id \n\n";
cin >> S->id;
cout << "Enter age \n\n";
cin >> S->age;
cout << "Enter name \n\n";
cin >> S->name;
}
void input_All_Data(Wajahat *S, int &count)
{
int check;
while (true)
{
cout << "Enter 1 To Save The Data Of A Student else press Any Key" << endl;
cin >> check;
if (check == 1)
{
cout << "Enter Id \n\n";
cin >> (*(S + count)).id;
cout << "Enter age \n\n";
cin >> S[count].age;
cout << "Enter name \n\n";
cin >> S[count].name;
count++;
}
else
{
break;
}
}
}
void display(Wajahat S)
{
cout << S.id << endl;
cout << S.age << endl;
cout << S.name << endl;
}
void display_All(Wajahat *S, int count)// Student*S and Student S[] is same...
{
for (int i = 0; i < count; i++)
{
cout << "Data of Student : " << i + 1 << endl << endl;
cout << (*(S + i)).id << endl;
cout << (*(S + i)).age << endl;
cout << (*(S + i)).name << endl;
cout << "\n\n\n";
// or S[i].id is same as (*(S + i)).id
}
} | true |
10ecbce6370fc3390062fae0bfc2eba237acfe97 | C++ | jiunbae/prime | /core/solver.hpp | UTF-8 | 1,119 | 2.828125 | 3 | [
"MIT"
] | permissive | //
// Created by Jiun Bae on 2020/05/25.
//
#ifndef PRIME_SOLVER_HPP
#define PRIME_SOLVER_HPP
#include <gridarray.hpp>
#include <pool.hpp>
namespace prime {
template <typename T=uint64_t>
class Solver {
public:
Solver() = default;
explicit Solver(T size)
: size(size), sieve(std::make_shared<GridArray<T>>(size)) {}
void init() {
thread::Pool thread_pool{};
for (uint64_t i = 2; i < size; i++) {
thread_pool.push([&](uint64_t i) {
uint64_t ii = i * i;
for (uint_fast64_t j = ii; j < size; j+= i) {
sieve->operator[](j-1) |= true;
}
}, i);
}
thread_pool.join();
}
void iter(const std::function<void(T)>& f) {
for (uint64_t i = 2; i < size; i++) {
if (!sieve->operator[](i - 1)) {
f(i - 1);
}
}
}
private:
T size;
std::shared_ptr<GridArray<T>> sieve;
};
}
#endif //PRIME_SOLVER_HPP
| true |
e0e0f802145ef60ca17cc8a1167d14839fa2b6f3 | C++ | ashlei-bevington-bluefruit/snake | /src/Engine/Game.cpp | UTF-8 | 1,238 | 2.96875 | 3 | [] | no_license | #include "Game.hpp"
#include "Coord.hpp"
#include "Food.hpp"
#include "Snake.hpp"
Game::Game(GraphicsWrapper &graphics, std::vector<GameObject*> &objectsIn) : graphics(graphics) {
for (std::size_t i = 0; i < objectsIn.size(); i++)
objects.push_back(objectsIn[i]);
}
void Game::Loop() {
Update();
Render();
}
void Game::Update() {
for (std::size_t i = 0; i < objects.size(); i++) {
objects[i]->Update();
}
}
void Game::Render() {
graphics.Clear();
do {
for (std::size_t i = 0; i < objects.size(); i++) {
std::vector<Drawable> drawables = objects[i]->GetDrawables();
for (std::size_t j = 0; j < drawables.size(); j++) {
switch (drawables[j].shape) {
case Drawable::Shape::Circle:
graphics.DrawCircle(
drawables[j].properties[0],
drawables[j].properties[1],
drawables[j].properties[2]
);
break;
case Drawable::Shape::Rectangle:
graphics.DrawRectangle(
drawables[j].properties[0],
drawables[j].properties[1],
drawables[j].properties[2],
drawables[j].properties[3]
);
break;
}
}
}
} while (graphics.Render());
} | true |
fa292de392dfe5cc17478ab3429b69cdab08e328 | C++ | dszajda/cmsc240_f2020_lab7_red | /Triangle.cpp | UTF-8 | 488 | 3.140625 | 3 | [] | no_license | #ifndef __TRINAGLE_CPP__
#define __TRIANGLE_CPP__
#include <iostream>
#include "Shape.h"
#include "Triangle.h"
using namespace std;
Triangle::Triangle(string name, double base, double height) : Shape(name){
baseAmount = base;
heightAmount = height;
}
Triangle::~Triangle(){}
double Triangle::getArea(){
return (baseAmount*heightAmount)*1/2;
}
void Triangle::print(){
Shape::print();
cout << "Base: " << baseAmount << endl;
cout << "Height: " << heightAmount << endl;
}
#endif
| true |
e9029b8e888ec13eea05244d5d7ae5e776b393f1 | C++ | jdalseno/Mint2 | /src/Mojito/Efficiencies/symMultiPolyTerm.cpp | UTF-8 | 2,244 | 3.046875 | 3 | [] | no_license | #include "Mint/symMultiPolyTerm.h"
#include "Mint/Utils.h"
#include <iostream>
using namespace std;
using namespace MINT;
symMultiPolyTerm::symMultiPolyTerm(int dimension, int order)
: MINT::PolymorphVector< symPolyTerm >()
{
init(dimension, order);
}
symMultiPolyTerm::symMultiPolyTerm(const symMultiPolyTerm& other)
: MINT::PolymorphVector< symPolyTerm >(other)
{
}
bool symMultiPolyTerm::init(int dimension, int order){
return createTerms(dimension, order);
}
bool symMultiPolyTerm::createTerms(int dimension, int order){
bool dbThis=false;
std::vector<std::vector<int> > v;
createTerms(dimension, order, v);
// next: remove duplicates, where we treat e.g. 32 as 23, i.e. order
// does not matter. The symPolyTerm then implements 32 as 32, 23, etc
// so what we "contract" here is expanded again there - efficient?
// ... probably not, but it follows the logic of the setup better.
for(unsigned int i=0; i < v.size(); i++) sort((v[i]).rbegin(), (v[i]).rend());
sort(v.rbegin(), v.rend());
std::vector< std::vector<int> >::iterator
lastUnique = unique(v.begin(), v.end());
v.erase(lastUnique, v.end());
for(unsigned int j=0; j < v.size(); j++){
if(dbThis)cout << v[j] << endl;
symPolyTerm spt(v[j]);
this->push_back(spt);
}
return true;
}
bool symMultiPolyTerm::createTerms(int dimension, int order
, std::vector<std::vector<int> >& v){
if(dimension <=0) return true;
std::vector<int> p(dimension,0);
p[0]=order;
v.push_back(p);
for(int od = order-1; od > 0; od--){
std::vector<int> p(dimension,0);
p[0]=od;
std::vector<std::vector<int> > v2;
createTerms(dimension-1, order - od, v2);
for(unsigned int i=0; i < v2.size(); i++){
std::vector<int>& p2(p);
std::vector<int>& tv2(v2[i]);
for(unsigned int k=0; k < tv2.size() && k + 1 < p2.size(); k++){
p2[k+1] = tv2[k];
}
v.push_back(p2);
}
}
return true;
}
void symMultiPolyTerm::print(std::ostream& os) const{
for(unsigned int i=0; i < this->size(); i++){
if(0 != i) os << "\n\t + ";
else os << "\t";
os << (*this)[i];
}
}
std::ostream& operator<<(std::ostream& os, const symMultiPolyTerm& smpt){
smpt.print(os);
return os;
}
//
| true |
28bfa1523d3967f6e6168fe93b6748a244cc414b | C++ | W-Schlesner/WSchlesner-Portfolio | /C++/Lab 2/Client.cpp | UTF-8 | 2,242 | 3.59375 | 4 | [] | no_license | #include "Client.h"
using namespace std;
Client::Client()
{
accountBalance = 0;
firstName = "";
lastName = "";
accountBalance = 0.0;
}
Client::Client(int id, string fname, string lname, double balance)
{
accountID = id;
firstName = fname;
lastName = lname;
accountBalance = balance;
}
/*
* mutator to set account id of customer
*/
void Client::setAccountID(int value)
{
accountID = value;
}
/*
* accessor to get account id of customer
*/
int Client::getAccountID()
{
return accountID;
}
/*
* mutator to set first name of customer
*/
void Client::setFirstName(string value)
{
firstName = value;
}
/*
* accessor to get first name of customer
*/
string Client::getFirstName()
{
return firstName;
}
/*
* mutator to set account id of customer
*/
void Client::setLastName(string value)
{
lastName = value;
}
/*
* accessor to get last name of customer
*/
string Client::getLastName()
{
return lastName;
}
/*
* mutator to set account balance of customer
*/
void Client::setAccountBalance(double value)
{
accountBalance = value;
}
/*
* accessor to get account balance of customer
*/
double Client::getAccountBalance()
{
return accountBalance;
}
/*
* method to deposit amount in customer's account
*/
void Client::depositAmount(double value)
{
accountBalance += value; system("CLS");
cout << "***********************************************" << endl;
cout << "* CASH DEPOSITED **" << endl;
cout << "***********************************************" << endl;
cout << " Cash Dposited: " << value << endl;
cout << " Availabe Cash amount: " << accountBalance << endl;
}
/*
* method to withdraw amount in customer's account
*/
void Client::withdrawAmount(double value)
{
accountBalance = accountBalance - value; system("CLS");
cout << "***********************************************" << endl;
cout << "* CASH WITHDRAWN **" << endl;
cout << "***********************************************" << endl;
cout << " Cash Withdrawn: " << value << endl;
cout << " Remaining cash amount: " << accountBalance << endl;
}
| true |
3278a967b2714eb47a49d0f617c6fa637e71390f | C++ | SinPatrones/trabajofinalada | /main.cpp | UTF-8 | 7,948 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include <ctime>
#include <stdlib.h>
#include <cstdlib>
#include <vector>
#include <algorithm>
using namespace std;
/*
5 3 4 5
3 2 2 1 3 1 3 2 <- función fitnes/aptitud
101010101 11000111 110101110 110100101
5 5
101010101 110100101 cruce / mutación
1010-00101 1101-10101
101000101 110110101 <- sin mutar
| 5 | 7
| 3 2 | 4 3
|101100101| 110110001 <- mutado
------- SEGUNDA GENERACIÓN ----------
5 4 5 7
3 2 3 1 3 2 4 3 <- nuevos candidatos
101010101 110101110 110100101 110110001
101010101 110110001
7 5
3 4 4 1
101010000 110111101
5 5 7 7
3 2 3 2 4 3 3 4 <- nuevos candidatos
101010101 110100101 110110001 101010000
-------------
9
5 4
111110000
-------------
*/
unsigned long long binarioADecimal(char *individuo, int tam) {
unsigned long long decimal = 0;
int multiplicador = 1;
char caracterActual;
for (int i = tam - 1; i >= 0; i--) {
caracterActual = individuo[i];
if (caracterActual == '1') {
decimal += multiplicador;
}
multiplicador = multiplicador * 2;
}
return decimal;
}
const int TAM = 4;
char * generarIndividuo(int tam = TAM){
char * individuo = new char[tam];
for (int idx = 0; idx < tam; idx++){
int valor = rand() % 10;
if (valor > 5){
individuo[idx] = '0';
} else {
individuo[idx] = '1';
}
}
return individuo;
}
void mostrarIndividuo(char * individuo, int tam = TAM){
for(int idx = 0; idx < tam; idx++){
cout << individuo[idx];
}
}
/* 010101 01111 */
long long funcionAptitud(char * individuo, int tam = TAM){
// conversión de binario a decimal
unsigned long long numeroX = binarioADecimal(individuo, tam);
// ecuación
const long long resultado = (numeroX * numeroX) + (numeroX * 2) - 10;
return resultado;
}
bool operacionCruce(char * individuo1, char * individuo2, int tam = TAM){
// solo será una partición
int mitad = (tam / 2) + 1; // pseudo-mitad
char * primeraParte1 = new char[mitad];
// guardamos la cabeza del primero
for (int idx = 0; idx < mitad; idx++){
primeraParte1[idx] = individuo1[idx];
}
// pasamos la cabeza del segundo al primero
for (int idx = 0; idx < mitad; idx++){
individuo1[idx] = individuo2[idx];
}
// le ponemos la cabeza del individuo uno en dos
for (int idx = 0; idx < mitad; idx++){
individuo2[idx] = primeraParte1[idx];
}
return true;
}
bool operacionMutacion(char * individuo1, int tam = TAM){
int idx = rand() % tam;
if (individuo1[idx] == '1'){
individuo1[idx] = '0';
} else {
individuo1[idx] = '1';
}
return true;
}
void mostrarTodosLosCandidatos(vector<pair<char *,int>> candidatos){
for(auto & candidato: candidatos){
mostrarIndividuo(candidato.first);
cout << "->" << candidato.second << " ";
}
cout << endl;
}
void asignarCalificacion(vector<pair<char *,int>> & candidatos){
for(auto & candidato: candidatos){
candidato.second = funcionAptitud(candidato.first);
}
}
void ordenarValores(vector<pair<char *,int>> & candidatos, vector<pair<char *,int>> & positivos, vector<pair<char *,int>> & negativos, long long valorOptimo){
positivos.clear();
negativos.clear();
// agrupando en valores positivos/negativos
for (auto & candidato: candidatos){
if (valorOptimo - candidato.second > 0){
positivos.push_back(candidato);
} else {
negativos.push_back(candidato);
}
}
// Ordenando vectores de manera creciente
sort(positivos.begin(), positivos.end(), [](pair<char *,int> candidato1, pair<char *,int> candidato2){
return candidato1.second < candidato2.second;
});
sort(negativos.begin(), negativos.end(), [](pair<char *,int> candidato1, pair<char *,int> candidato2){
return candidato1.second < candidato2.second;
});
candidatos.clear();
for(auto & candidato: positivos){
candidatos.push_back(candidato);
}
for(auto & candidato: negativos){
candidatos.push_back(candidato);
}
}
int main(){
srand(time(NULL));
// el mejor candidado mide 11
const int cantidadIndividuos = 10;
// cantidad de bits 11 <-- TAM
// 6 -> 1 > 11
// 5 -> 0 >
// candidato, aptitud
vector<pair<char * , int >> candidatos;
for (int idx = 0; idx < cantidadIndividuos; idx++){
pair<char *, int> candidato(generarIndividuo(), 0);
candidatos.push_back(candidato);
}
mostrarTodosLosCandidatos(candidatos);
asignarCalificacion(candidatos);
mostrarTodosLosCandidatos(candidatos);
/* condiciones
1.- Definamos cantidad de generaciones
2.- Encontremos o aproximemos a la respuesta
3.- DETENGAMOS
4.- ERROR
*/
long long respuestaOptima = 50;
long long umbral = 5;
vector<pair<char *,int>> vectorPositivos;
vector<pair<char *,int>> vectorNegativos;
ordenarValores(candidatos, vectorPositivos, vectorNegativos, respuestaOptima);
cout << "--- CANDIDATOS ---\n";
mostrarTodosLosCandidatos(candidatos);
cout << "--- CANDIDATOS POSITIVOS ---\n";
mostrarTodosLosCandidatos(vectorPositivos);
cout << "--- CANDIDATOS NEGATIVOS ---\n";
mostrarTodosLosCandidatos(vectorNegativos);
cout << endl;
cout << "\n---> CANDIDATOS <---\n";
mostrarTodosLosCandidatos(candidatos);
cout << endl << endl;
int generacion = 1;
while(true){
// Son los dos mejores
char * candidato1 = new char[TAM];
char * candidato2 = new char[TAM];
candidato1 = candidatos[0].first;
candidato2 = candidatos[vectorPositivos.size()].first;
operacionMutacion(candidato1);
operacionMutacion(candidato2);
operacionCruce(candidato1, candidato2);
// Borrando al menos optimo de la lista más larga
if (vectorPositivos.size() > vectorNegativos.size()){
candidatos.erase(candidatos.begin() + (vectorPositivos.size() - 1));
} else {
candidatos.erase(candidatos.end() - 1);
}
cout << "------->> Mostrando candidatos menos uno\n";
mostrarTodosLosCandidatos(candidatos);
// botando a los padres antiguos
if (funcionAptitud(candidato1) > funcionAptitud(candidato2)){
pair<char*,int> nuevoCandidato(candidato1, funcionAptitud(candidato1));
candidatos.push_back(nuevoCandidato);
} else {
pair<char*,int> nuevoCandidato(candidato2, funcionAptitud(candidato2));
candidatos.push_back(nuevoCandidato);
}
//asignarCalificacion(candidatos);
ordenarValores(candidatos, vectorPositivos, vectorNegativos, respuestaOptima);
// VALOR OPTIMO --> TOTAL: 100;
// UMBRAL: -10 a 10
if ( respuestaOptima - vectorPositivos[0].second <= umbral || (respuestaOptima - vectorNegativos[0].second) >= (umbral * -1)){
cout << "-------- RESPUESTAS -----------" << endl;
cout << binarioADecimal(vectorPositivos[0].first, TAM);
cout << " - ";
cout << binarioADecimal(vectorNegativos[0].first, TAM);
cout << "\n------------------------------\n";
break;
}
cout << "GENERACION " << ++generacion << endl;
}
cout << "Mostrando Solución" << endl;
mostrarTodosLosCandidatos(candidatos);
return 0;
}
| true |
e539d285b09d97536f2c3b56d03e24331257c46b | C++ | asperaa/Data_Structure_Problems | /bst/lca.cpp | UTF-8 | 1,581 | 3.8125 | 4 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
struct node
{
int data;
struct node* left;
struct node* right;
};
struct node* newNode(int data)
{
struct node* treeNode=(struct node*)malloc(sizeof(struct node));
treeNode->data=data;
treeNode->left=NULL;
treeNode->right=NULL;
return treeNode;
}
struct node* lcaR(struct node* root,int n1,int n2)
{
if(root==NULL)
return NULL;
if(root->data>n1 && root->data>n2)
return lcaR(root->left,n1,n2);
if(root->data<n1 && root->data<n2)
return lcaR(root->right,n1,n2);
return root;
}
struct node* lcaI(struct node* root,int n1,int n2)
{
while(root!=NULL)
{
if(root->data > n1 && root->data >n2 )
root=root->left;
else if(root->data < n1 && root->data < n2)
root=root->right;
else
break;
}
return root;
}
int main()
{
// Let us construct the BST shown in the above figure
struct node *root = newNode(20);
root->left = newNode(8);
root->right = newNode(22);
root->left->left = newNode(4);
root->left->right = newNode(12);
root->left->right->left = newNode(10);
root->left->right->right = newNode(14);
int n1 = 10, n2 = 14;
struct node *t = lcaR(root, n1, n2);
printf("LCA of %d and %d is %d \n", n1, n2, t->data);
n1 = 14, n2 = 8;
t = lcaR(root, n1, n2);
printf("LCA of %d and %d is %d \n", n1, n2, t->data);
n1 = 10, n2 = 22;
t = lcaR(root, n1, n2);
printf("LCA of %d and %d is %d \n", n1, n2, t->data);
return 0;
} | true |
d7d4fb6a79e4aa37d4be47ad18002aa82896b576 | C++ | Jakelamers64/OpStratsGame2.0 | /Engine/Level.cpp | UTF-8 | 1,378 | 2.890625 | 3 | [] | no_license | #include "Level.h"
#include <algorithm>
#include <assert.h>
Level::Level(Graphics & gfx, const int levelEvel_in)
:
gfx(gfx),
levelEvel(levelEvel_in)
{
for (int y = 0; y < height; ++y)
{
for (int x = 0; x < width; ++x)
{
if (levelEvel_in == 0)
{
blocks.emplace_back(Block::Contents::Stone, Block::Displayed::TwoThreePrime,Vei2(x,y));
}
if (levelEvel_in == 1)
{
blocks.emplace_back(Block::Contents::Stone,Block::Displayed::all,Vei2(x, y));
}
}
}
/*
test code that allows you to view layer below
*/
if (levelEvel_in == 1)
{
for (int y = 1; y < height - 1; ++y)
{
for (int x = 1; x < width - 1; ++x)
{
BlockAtGridPos({ x,y }).SetContent(Block::Contents::Empty);
BlockAtGridPos({ x,y }).SetDisplayed(Block::Displayed::Nothing);
}
}
BlockAtGridPos({ 5,5 }).SetContent(Block::Contents::Stone);
BlockAtGridPos({ 5,5 }).SetDisplayed(Block::Displayed::all);
}
}
Block& Level::BlockAtGridPos(const Vei2 gridpos)
{
assert(gridpos.x >= 0);
assert(gridpos.y >= 0);
assert(gridpos.x < width);
assert(gridpos.y < height);
return blocks[gridpos.y * width + gridpos.x];
}
bool Level::IsInBounds(const Vei2 gridPos) const
{
return gridPos.x >= 0 &&
gridPos.y >= 0 &&
gridPos.x < width &&
gridPos.y < height;
}
int Level::GetWidth() const
{
return width;
}
int Level::GetHeight() const
{
return height;
}
| true |
34d547cbf27cae479b0fc95114ec6eb519cacae5 | C++ | whing123/C-Coding | /LeetCode/560.cpp | UTF-8 | 1,010 | 3.890625 | 4 | [] | no_license | /* *题目:
* 560
* Subarray Sum Equals K
prefix sum & map
*/
/*
Brief explaination:
To solve the problem, we want to know how to sum to a particular value and how many times did this value appear.
That is, how to find the value of sum[i, j], the sum from nums[i] to nums[j] , where [i, j] are indexes of the array.
And yet we know that sum[i, j] = sum[0, j] - sum[0, i - 1].
Therefore, we can iterate through the original array and accumulatively calculate the prefix sum current,
in each iteration we check whether we have encountered the value current - k in the past iterations.
*/
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
unordered_map<int, int> prefixSumCount;
prefixSumCount[0] = 1;
int res = 0;
int prefixSum = 0;
for(int num : nums){
prefixSum += num;
res += prefixSumCount[prefixSum - k];
prefixSumCount[prefixSum] += 1;
}
return res;
}
}; | true |
dc8e328f40ad97607da06343c3e06a81885fd952 | C++ | JeffTheK/rella | /test/id_test.cpp | UTF-8 | 390 | 2.546875 | 3 | [
"MIT"
] | permissive | #include "../include/doctest.h"
#include "../src/id.hpp"
TEST_CASE("get_free_id") {
reset_free_id();
CHECK(get_free_id() == 1);
CHECK(get_free_id() == 2);
}
TEST_CASE("get_type_id") {
CHECK(get_type_id<int>() != get_type_id<char>());
}
TEST_CASE("reset_free_id") {
reset_free_id();
CHECK(get_free_id() == 1);
reset_free_id();
CHECK(get_free_id() == 1);
}
| true |
3ab90219a93d4045854eefc51f91b334d943cef1 | C++ | JasonHenault/Nine | /Log.cpp | UTF-8 | 3,758 | 2.578125 | 3 | [] | no_license | #include "Nine.hpp"
#include "FastAccess.hpp"
using namespace NTOOLS;
Log::Log() {
std::cout << "Start logging." << std::endl;
}
Log::~Log() {
SaveReport();
}
void Log::RegisterInfo (const std::string &info) {
_info.push_back(info);
}
void Log::RegisterWarning (const std::string &warn, std::string file, int line) {
WarnAndError wae;
wae.mes = warn;
wae.file = file;
wae.line = line;
_warning.push_back(wae);
}
void Log::RegisterError (const std::string &error, std::string file, int line) {
std::cout << file << " (" << line << ") error : \"" << error << "\"" << std::endl;
WarnAndError wae;
wae.mes = error;
wae.file = file;
wae.line = line;
_error.push_back(wae);
}
void Log::RegisterPackage (const std::string &path, const std::string type) {
Package p;
p.path = path;
p.type = typeid(type).name();
_package.push_back(p);
}
void Log::SaveReport() {
std::cout << _error.size() << " errors, " << _warning.size() << " warnings, " << _package.size() << " packages and " << _info.size() << " informations. Saving ..." << std::endl;
std::ostringstream html;
// standart body
html << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"> \n \
<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" > \n \
<head> \n \
<title>Nine report</title> \n \
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\" /> \n \
</head> \n \
<body> \n \
<img src=\"banner.png\" alt=\"Report standart banner\" /> \n \
<br/> \n \
<img src=\"information.png\" alt=\"info\" title=\"Informations\"/> (";
html << _info.size();
html << ") \n \
<img src=\"warning.png\" alt=\"warning\" title=\"Warnings\"/> (";
html << _warning.size();
html << ") \n \
<img src=\"error.png\" alt=\"error\" title=\"Errors\"/> (";
html << _error.size();
html << ") \n \
<img src=\"package.png\" alt=\"package\" title=\"Packages\"/> (";
html << _package.size();
html << ") \n \
<br /> \n \
<textarea name=\"messages\" id=\"messages\" rows=\"25\" cols=\"100\"> \n";
////////////////
html << "Infos : \n\n";
for(int i = 0; i < _info.size(); i++) {
html << i+1;
html << ") ";
html << _info[i] + "\n";
}
html << "</textarea> \n \
</br> \n \
<textarea name=\"warning\" id=\"warning\" rows=\"25\" cols=\"100\"> \n";
html << "Warnings : \n\n";
for(int i = 0; i < _warning.size(); i++) {
html << i+1;
html << ") ";
html << _warning[i].mes + "\n";
}
html << "</textarea> \n \
</br> \n \
<textarea name=\"error\" id=\"error\" rows=\"25\" cols=\"100\"> \n";
html << "Errors :\n\n";
for(int i = 0; i < _error.size(); i++) {
html << i+1;
html << ") ";
html << _error[i].mes + "\n";
}
html << "</textarea> \n \
</br> \n \
<textarea name=\"package\" id=\"package\" rows=\"25\" cols=\"100\"> \n";
html << "Package :\n\n";
for(int i = 0; i < _package.size(); i++) {
html << i+1;
html << ") ";
html << _package[i].path + "\n";
}
html << "</textarea> \n \
</body> \n \
</html>";
std::ofstream file("Report.html", std::ios::out | std::ios::trunc);
file << html.str();
file.close();
std::cout << "Report saved in the execution directory" << std::endl;
}
| true |
b8f653804d962337e8b6b8915db88d45aa59c273 | C++ | dskleviathan/contest | /POJ3050.cpp | UTF-8 | 1,013 | 2.609375 | 3 | [] | no_license | #include<cstdio>
#include<iostream>
#include<map>
#include<math.h>
using namespace std;
int a[5][5];
int y = 0;
map<int,int> value;
map<int,int>::const_iterator itr;
void solve(int i,int j,int tmp[],int k){
if(k < 5){
tmp[k] = a[i][j];
if(i != 0) solve(i-1,j,tmp,k+1);
if(j != 4) solve(i,j+1,tmp,k+1);
if(i != 4) solve(i+1,j,tmp,k+1);
if(j != 0) solve(i,j-1,tmp,k+1);
}else{
int res;
tmp[k] = a[i][j];
res = 0;
res += tmp[0];
res += tmp[1]*10;
res += tmp[2]*100;
res += tmp[3]*1000;
res += tmp[4]*10000;
res += tmp[5]*100000;
if (value.find(res) == value.end()){
value.insert( map<int, int>::value_type(res, res));
y++;
}
}
}
int main(){
int tmp[6] = {0,0,0,0,0,0};
for(int i = 0; i < 5; i++){
for(int j = 0; j < 5; j++){
cin >> a[i][j];
}
}
for(int i = 0; i < 5; i++){
for(int j = 0; j < 5; j++){
solve(i,j,tmp,0);
}
}
cout << y << endl;
}
| true |
755d3912476ce6389c3f140b82b20061dea77371 | C++ | a2677331/My-Solutions-CS121-HW | /Lab3/Lab3(cin.ignore,setw,setfill,setprecision).cpp | UTF-8 | 2,282 | 3.40625 | 3 | [] | no_license | //********************************************************
//
// Jian Zhong
// Professor MacKay
// CS121-01
// Lab 3
// 2/17/2019
// Program Name: calculate the downpayment
// Program file:
// Input Files:
// Output Files:
// Included files:
// Purpose:
//
//********************************************************
#include <iostream>
#include <string>
#include <cmath> // needed for using pow function
#include <iomanip> // needed for using setpresicision
using namespace std;
int main()
{
string name;
double loanAmount;
double annualInterest;
double totalPayment;
double years;
double monthlyPayment;
double R;
double N;
double L;
cout << "Please enter your name: \n";
cin >> name;
cin.ignore(200, '\n'); // ⚠️除第一个string外,其他都不取。ignore next 200 chars till next line
// ⚠️用cin.ignore()默认跳过后一个值,取之后的值。
// ⚠️这里是用在输入name的后面,用来省略多余的那么之后的值,为了不影响后面的计算。
cout << "Please enter amount of the loan: \n";
cin >> loanAmount;
cout << "Please enter annual interest rate(%): \n";
cin >> annualInterest;
cout << "Please enter number of years of the loan \n";
cin >> years;
R = annualInterest * 0.01 / 12;
N = years * 12;
L = loanAmount;
monthlyPayment = L * R * pow(1 + R, N) / (pow(1 + R, N) - 1); //main fomular
totalPayment = monthlyPayment * N;
cout << setprecision(2); // keep two digits decimal
cout << fixed;
cout << "Name: " << setw(44) << name << '\n'
<< "Loan Amount: $" << setw(20) << loanAmount << '\n';
cout << setprecision(0); //let decimal disappear
cout << "Monthly Interest Rate: " << setw(20) << R * 100 << "%" << '\n';
cout << "Number of Payments: " << setw(20) << N << '\n';
cout << setprecision(2); // keep two digits decimal again
cout << fixed;
cout << "Monthly Payment: $" << setw(20) << monthlyPayment << '\n';
cout << "Total Amount Paid: $" << setw(20) << totalPayment << '\n'
<< "Interest Amount: $" << setw(20) << totalPayment - loanAmount << '\n';
return 0;
}
| true |
9b82521945b0f3e01499f5c36913b158311c131c | C++ | H-Shen/Collection_of_my_coding_practice | /Leetcode/485/485.cpp | UTF-8 | 612 | 2.640625 | 3 | [] | no_license | class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int maxConsec(0);
int curConsec(0);
int lastVal(-1);
for (size_t i = 0; i != nums.size(); ++i) {
if (nums[i] == 1 && lastVal != 1) {
curConsec = 1;
lastVal = 1;
} else if (nums[i] == 1 && lastVal == 1) {
++curConsec;
} else if (nums[i] != 1) {
lastVal = nums[i];
curConsec = 0;
}
maxConsec = max(maxConsec, curConsec);
}
return maxConsec;
}
}; | true |
d4a5a26f928640be08f2095f4be09eb9d4196b9c | C++ | Khaeshah/ACM-ICPC | /Graphs/3988.cpp | UTF-8 | 1,598 | 3.109375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
typedef vector<pair<int,pair<int,int> > > V;
V v;
int N; // numero de nodos
int mf[2010],ranking[2010];
int set(int n) { // conjunto conexo de n
if (mf[n] == n) return n;
else mf[n] = set(mf[n]);
return mf[n];
}
// coste, <origen, destino>
int kruskal() {
int a, b, sum = 0;
sort(v.begin(), v.end());
for (int i = 0; i < N; i++) {
mf[i] = i; // inicializar conjuntos conexos
ranking[i] = 0;
}
for (unsigned int i = 0; i < v.size(); i++) {
a = set(v[i].second.first);
b = set(v[i].second.second);
if (a != b) { // si conjuntos son diferentes
if(ranking[a] > ranking[b]) mf[b] = a;
else {
mf[a] = b;
ranking[b] += (ranking[a] == ranking[b]);
}
sum += v[i].first; // agregar coste de arista
}
}
return sum;
}
int main() {
int c;
cin >> c;
bool firstSpace = false;
while(c > 0) {
// Borro el vector global
while (v.size() > 0) {
v.erase(v.begin());
v.push_back(v.front());
v.erase(v.begin());
}
int m, n;
cin >> m >> n;
N = m;
map<string,int> id;
string c1,c2;
int cost;
int nodeID = 0;
// Para cada link, asigno valores [coste[origen,destino]
for(int i = 0; i < n; ++i) {
cin >> c1 >> c2 >> cost;
v.push_back(make_pair(cost,make_pair(id.count(c1) ? id[c1] : id[c1] = nodeID++,id.count(c2) ? id[c2] : id[c2] = nodeID++)));
}
int ans = kruskal();
if(firstSpace) cout << endl;
firstSpace = true;
cout << ans << endl;
--c;
}
} | true |
e932654a6d060223c57bf582d0f985f25c05d746 | C++ | Alan-Lee123/POJ | /Greedy algorithm/2325.cpp | UTF-8 | 1,114 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
#include <map>
#include <cmath>
#include <set>
#include <string>
using namespace std;
string idiv(string s, int d, int& r)
{
string ans = s;
r = 0;
for (int i = 0; i < s.size(); ++i)
{
int x = r * 10 + s[i] - '0';
ans[i] = x / d + '0';
r = x % d;
}
if (ans[0] == '0' && ans.size() > 1)
return ans.substr(1);
return ans;
}
char str[1010];
int main()
{
while (true)
{
scanf("%s", str);
if (str[0] == '-')
break;
string s = str;
if (s.size() == 1)
{
if (s == "0")
printf("10\n");
else
printf("%s\n", ("1" + s).c_str());
continue;
}
int r = 0;
int nums[10] = {0};
for (int i = 9; i > 1; --i)
{
int cnt = 0;
while (s != "0")
{
string t = idiv(s, i, r);
if (r != 0)
break;
else
{
s = t;
cnt += 1;
}
}
nums[i] = cnt;
}
if (s != "1")
{
printf("There is no such number.\n");
continue;
}
string ans = "";
for (int i = 2; i < 10; ++i)
if(nums[i] > 0)
ans += string(nums[i], i + '0');
printf("%s\n", ans.c_str());
}
return 0;
} | true |
a95b876313c7ffd7a9d62392ffcd639c5f495387 | C++ | samalvz/Basic-Raytracer | /include/Disk.h | UTF-8 | 502 | 2.671875 | 3 | [] | no_license | #ifndef DISK_H
#define DISK_H
#include "Shape.h"
namespace Raytracer148 {
class Disk : public Shape {
public:
enum type {plane, disk, ring};
Disk(Eigen::Vector3d& center, double diameter, Eigen::Vector3d color, type type) : c(center), d(diameter), color(color), type(type) {}
virtual HitRecord intersect(const Ray& ray);
private:
Eigen::Vector3d c;
Eigen::Vector3d color;
double d;
type type;
};
}
#endif | true |
4d1d4bacbea42614658669baebe8ad19a56284ea | C++ | roshihie/At_Coder | /ABC_C/ABC153_C_Fennec_vs_Monster.cpp | UTF-8 | 741 | 2.53125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
using llong = long long;
void input(int& rnFinCnt, vector<int>& rvnLifePnt)
{
int nMonstr;
cin >> nMonstr >> rnFinCnt;
rvnLifePnt.resize(nMonstr);
for (int& rnLifePnt : rvnLifePnt)
cin >> rnLifePnt;
sort(begin(rvnLifePnt), end(rvnLifePnt), greater<int>() );
}
llong calcMinAttackCnt(int nFinCnt, const vector<int>& cnrvnLifePnt)
{
llong nMinAttackCnt = 0;
for (int nx = nFinCnt; nx < cnrvnLifePnt.size(); ++nx)
nMinAttackCnt += cnrvnLifePnt[nx];
return nMinAttackCnt;
}
int main()
{
int nFinCnt;
vector<int> vnLifePnt;
input(nFinCnt, vnLifePnt);
cout << calcMinAttackCnt(nFinCnt, vnLifePnt) << endl;
return 0;
}
| true |