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
fcdd360cd290c522f8fb161f32aa8dd1c817b296
C++
Nealoth/List
/main.cpp
UTF-8
281
2.859375
3
[]
no_license
#include <iostream> #include "List.h" using namespace custom_std; int main() { List<int> list; list.push_back(1); list.push_back(2); list.push_back(3); std::cout << list.at(1) << std::endl; std::cout << list.size() << std::endl; return 0; }
true
de219a4f321a4e7fe0cc4790e81f629f08221fa5
C++
FusixGit/hf-2011
/Protect/Rookit/Hook/HookApi/HookApi/HookApi.cpp
GB18030
1,333
2.53125
3
[]
no_license
#include <windows.h> #include "HookApi.h" CHOOKAPI HookItem ; // MessageBoxAԭ typedef int (WINAPI* PFNMessageBoxA)( HWND hWnd, LPCSTR lpText, LPCSTR lpCaption, UINT uType ) ; // ԶMessageBoxA // ʵֶԭʼMessageBoxA롢ļأȡ int WINAPI NEW_MessageBoxA( HWND hWnd, LPCSTR lpText, LPCSTR lpCaption, UINT uType ) { // HOOK HookItem.UnHook () ; // ˴Թ۲/޸ĵòȡֱӷء // // ȡԭַ PFNMessageBoxA pfnMessageBoxA = (PFNMessageBoxA)HookItem.pOldFunEntry ; // ԭ޸ int ret = pfnMessageBoxA ( hWnd, "HOOK̵Ϣ", "[]", uType ) ; // ˴Բ鿴/޸ĵԭķֵ // // HOOK HookItem.ReHook () ; return ret ; } int WINAPI WinMain ( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { // ԭʼAPI MessageBoxA ( 0, "Ϣ", "", 0 ) ; // HOOK API HookItem.Hook ( "USER32.dll", "MessageBoxA", (FARPROC)NEW_MessageBoxA ) ; // API MessageBoxA ( 0, "Ϣ", "", 0 ) ; // HOOK HookItem.UnHook () ; return 0 ; }
true
3f29f425bc60a6d3822cc9d215bf9d3086c48cf7
C++
woswos/e3-obfuscation-wars
/benchmark-server/old-versions/benchmark-server-0.6.1 - Experimenting with auto return type/benchy/src/gate/gate.h
UTF-8
4,388
2.53125
3
[]
no_license
#ifndef GATE_API_H #define GATE_API_H #include "base.h" class GateApi : public Scheme { private: public: /*******************/ /* Supported Gates */ /*******************/ void Init(){ // generate default gate bootstrapping parameters int32_t minimum_lambda = 100; TFheGateBootstrappingParameterSet* params = new_default_gate_bootstrapping_parameters(minimum_lambda); // generate a new unititialized ciphertext LweSample* uCipherText = new_gate_bootstrapping_ciphertext(params); Scheme::StoreParameter("params", params); Scheme::StoreParameter("uCipherText", uCipherText); } void GenerateKeySet(){ // cast back to data type from void TFheGateBootstrappingParameterSet* params = static_cast<TFheGateBootstrappingParameterSet*>(Scheme::GetParameter("params")); TFheGateBootstrappingSecretKeySet* keyset = new_random_gate_bootstrapping_secret_keyset(params); Scheme::StoreParameter("keyset", keyset); } auto Encrypt(int plainText) -> LweSample* { // cast back to data type from void TFheGateBootstrappingSecretKeySet* keyset = static_cast<TFheGateBootstrappingSecretKeySet*>(Scheme::GetParameter("keyset")); TFheGateBootstrappingParameterSet* params = static_cast<TFheGateBootstrappingParameterSet*>(Scheme::GetParameter("params")); // generate a new unititialized ciphertext LweSample* encryptionResult = new_gate_bootstrapping_ciphertext(params); Scheme::StoreParameter("encryptionResult", encryptionResult); // encrypts a boolean bootsSymEncrypt(encryptionResult, plainText, keyset); return encryptionResult; } template <typename T> int Decrypt(T cipherText){ TFheGateBootstrappingSecretKeySet* keyset = static_cast<TFheGateBootstrappingSecretKeySet*>(Scheme::GetParameter("keyset")); /** decrypts a boolean */ return bootsSymDecrypt(cipherText, keyset); } template <typename T> auto EvalAnd(T bitA, T bitB) -> LweSample*{ // cast back to data type from void TFheGateBootstrappingSecretKeySet* keyset = static_cast<TFheGateBootstrappingSecretKeySet*>(Scheme::GetParameter("keyset")); TFheGateBootstrappingParameterSet* params = static_cast<TFheGateBootstrappingParameterSet*>(Scheme::GetParameter("params")); LweSample* resultPtr = static_cast<LweSample*>(Scheme::GetParameter("uCipherText")); /** bootstrapped And Gate: result = a and b */ bootsAND(resultPtr, bitA, bitB, &keyset->cloud); return resultPtr; } void* EvalNand(void *bitA, void *bitB); void* EvalOr(void *bitA, void *bitB); void* EvalNor(void *bitA, void *bitB); void* EvalXor(void *bitA, void *bitB); void* EvalXnor(void *bitA, void *bitB); void* EvalMux(void *bitA, void *bitB, void *bitC); void* EvalNot(void *bitA); void* EvalBuffer(void *bitA); /*******************/ /* Gate Api Basics */ /*******************/ // Constructor GateApi(){}; // Destructor ~GateApi(){}; /**********************/ /* Benchmarking Stuff */ /**********************/ // Does the benchmarking, returns 1 if completed succesfully int benchmark(GateApi* schemePtr); int test_gate_cycle_recursive_ciphertext( std::string gate_name_s, GateApi* schemePtr, void* (GateApi::*gate_func_name)(void*, void*), int (GateApi::*test_gate_func_name)(int, int) ); int test_gate_cycle_fresh_ciphertext( std::string gate_name_s, GateApi* schemePtr, void* (GateApi::*gate_func_name)(void*, void*), int (GateApi::*test_gate_func_name)(int, int) ); int test_gate_manual_single(int bitA, int bitB); int test_gate_and(int bitA, int bitB); int test_gate_nand(int bitA, int bitB); int test_gate_or(int bitA, int bitB); int test_gate_nor(int bitA, int bitB); int test_gate_xor(int bitA, int bitB); int test_gate_xnor(int bitA, int bitB); int test_gate_mux(int bitA, int bitB, int bitC); int test_gate_not(int bitA); int test_gate_buffer(int bitA); }; #endif
true
539ac77a95f5ab1f6acf3bc158d022b4a999102b
C++
Ge-yuan-jun/coursera-peking-university
/C程序设计进阶/week6/lecture1/cursorForDimensionArray.cpp
UTF-8
589
3.21875
3
[]
no_license
/** * @Author: geyuanjun * @Date: 2016-06-20 13:55:16 * @Email: geyuanjun.sh@superjia.com * @Last modified by: geyuanjun * @Last modified time: 2016-06-20 14:00:58 */ //多维数组名做函数参数 #include<iostream> using namespace std; int maxValue(int (*p)[4]){ int max = p[0][0]; for(int i = 0; i < 3; i++){ for(int j = 0; j < 4; j++){ if(p[i][j] > max){ max = p[i][j]; } } } return max; } int main(){ int a[3][4] = {{1,3,5,7},{9,11,13,15},{2,4,6,8}}; cout << "The max value is " << maxValue(a); return 0; }
true
e0a2c62d9be418559994897871b11fb2b6259ada
C++
RashakDude/codechef_ps
/Beginner/FLOW016.cpp
UTF-8
288
3.1875
3
[]
no_license
#include <iostream> using namespace std; long gcd (long a ,long b){ if(b==0) return a; else return gcd(b,a%b); } int main(){ int num; cin >> num; while(num--){ long x,y; cin >> x >> y; cout << gcd(x,y) << " " << x*y/gcd(x,y) << endl; } }
true
28cae45013818bd1e17e81433e4cb85ad5241f6e
C++
walkccc/LeetCode
/solutions/1502. Can Make Arithmetic Progression From Sequence/1502.cpp
UTF-8
590
2.796875
3
[ "MIT" ]
permissive
class Solution { public: bool canMakeArithmeticProgression(vector<int>& arr) { const int n = arr.size(); const int max = *max_element(arr.begin(), arr.end()); const int min = *min_element(arr.begin(), arr.end()); const int range = max - min; if (range % (n - 1) != 0) return false; const int diff = range / (n - 1); if (diff == 0) return true; unordered_set<int> seen; for (const int a : arr) { if ((a - min) % diff != 0) return false; if (!seen.insert(a).second) return false; } return true; } };
true
a52841e0d7ad4acd10340f1617f164ae6697132f
C++
vikasbhalla05/Data-Structures-using-Cpp
/DeletionInLinkedList.cpp
UTF-8
487
3.59375
4
[]
no_license
// to delete the nth node // put (n-1)th temp = nth temp void deleteAtHead(node* &head){ node* todelete=head; head= head->next; delete todelete; } void deleteNode( node* &head, int val){ node* temp=head; while(temp->next->data!=val) { temp=temp->next; } node* todelete=temp->next; temp->next =temp->next->next; delete todelete; if(head==NULL){ return; } if(head->next==NULL && head->data==val){ deleteAtHead(head); return 0; } }
true
5e963970358823bc5836077286847fd1f8cd7949
C++
rulo7/3DFreeGlutSimpleAnimationObject
/Lapiz_3D.cpp
UTF-8
3,150
2.984375
3
[]
no_license
/** * * Autores: Raul Cobos y Alvar Soler * Funciones de la clase Lapiz. * */ #include "Lapiz_3D.h" #include "Lista.h" #include <cmath> #include <iostream> #include <GL/freeglut.h> #define PI 3.14159265 Lapiz_3D::Lapiz_3D() { _recorrido.ponDr(new PV3D(0.0, 0.0, 0.0)); this->_direc = 0.0; this->_ejeFijo = EJEY; } /** * Constructor del lapiz. * @param pto donde commienza el lapiz * @param theta angulo con el que empieza */ Lapiz_3D::Lapiz_3D(PV3D *pto, GLdouble direc, EJEFIJO ejeFijo) { this->_recorrido.ponDr(pto); this->_direc = direc; this->_ejeFijo = ejeFijo; } Lapiz_3D::~Lapiz_3D() { _recorrido.~Lista(); } /** * Avanza el lápiz una distancia dada * @param dist que se quiere que avance */ void Lapiz_3D::avanza(GLdouble dist) { /* Almacenamos la vieja posición para poder dibujar la línea de un punto a otro */ PV3D* vPos = this->getPosition(); PV3D* nPos; GLdouble difX,difY, difZ, rad; switch (this->_ejeFijo) { case EJEX: /* Transformamos el ángulo a radianes */ rad = getDirection() / 180.0 * PI; difY = cos((double) rad) * dist; difZ = sin((double) rad) * dist; /* Calculamos la nueva posición */ nPos = new PV3D(vPos->getX(), vPos->getY() + difY, vPos->getZ() + difZ); break; case EJEY: /* Transformamos el ángulo a radianes */ rad = getDirection() / 180.0 * PI; difZ = cos((double) rad) * dist; difX = sin((double) rad) * dist; /* Calculamos la nueva posición */ nPos = new PV3D( vPos->getX() + difX, vPos->getY(), vPos->getZ() + difZ); break; case EJEZ: /* Transformamos el ángulo a radianes */ rad = getDirection() / 180.0 * PI; difX = cos((double) rad) * dist; difY = sin((double) rad) * dist; /* Calculamos la nueva posición */ nPos = new PV3D( vPos->getX() + difX, vPos->getY() + difY, vPos->getZ()); break; } this->_recorrido.ponDr(nPos); } /** * Gira el lapiz giroXY grados en el plano * @param giroXY */ void Lapiz_3D::gira(GLdouble giro) { this->_direc += giro; } /* Setters */ /** * avanzamos el lapiz hasta la posicion indicada * y marcamos el eje que definira el plano * @param p nueva posicion del lapiz * */ void Lapiz_3D::moveTo(PV3D* p,EJEFIJO ejeFijo) { this->_recorrido.ponDr(p); this->_ejeFijo = ejeFijo; } /** * Se cambia el angulo a otro dado en el plano XY * @param a nuevo ángulo */ void Lapiz_3D::turnTo(GLdouble a) { this->_direc = a; } /* Getters */ /** * Posicion actual * @return Punto pos. actual */ PV3D* Lapiz_3D::getPosition() { return _recorrido.ultimo(); } /** * Direccion en angulos en el plano XY * @return direcc. angulo */ GLdouble Lapiz_3D::getDirection() { return this->_direc; } Lista<PV3D*> Lapiz_3D::getRecorrido() { return this->_recorrido; }
true
42da35ad558b8415832fe91bf53ff05638fd8b93
C++
wgevaert/AOC
/2021/18.cpp
UTF-8
6,425
2.859375
3
[ "WTFPL" ]
permissive
#include <iostream> #include <fstream> #include <chrono> #include <string> #include <vector>/* #include <unordered_map>*/ // Because I'm too lazy to type typedef uint64_t ull_t; typedef uint32_t u_t; typedef int64_t ll_t; unsigned verb_lvl = 0; void read_or_die(std::string pattern, std::istream& input) { for (auto a:pattern) { if (a != input.get()) { std::string parsed_pattern = ""; for (auto b:pattern) { if (b < ' ' || b > 126) parsed_pattern += "?("+std::to_string(static_cast<int>(b))+")"; else parsed_pattern += b; } std::cerr<<'\''<<parsed_pattern<<'\''<<" expected"<<std::endl; exit(1); } } } const u_t uinf=-1; // global vars, how risky. u_t expll,explr; // TODO: rewrite to just a struct with "depth" and "value" class stupidNumber { public: stupidNumber *left=NULL,*right=NULL; u_t val=uinf; stupidNumber(u_t v){val=v;left=right=NULL;} stupidNumber(stupidNumber* l, stupidNumber* r){left=l;right=r;} ~stupidNumber() {if(left!=NULL)delete left;if(right!=NULL)delete right;if(verb_lvl>6)std::cout<<"Deleting "<<val<<std::endl;} stupidNumber* getCopy() { if (val!=uinf)return new stupidNumber(val); return new stupidNumber(left->getCopy(),right->getCopy()); } bool split() { if (val != uinf && val > 9) { if (verb_lvl>6)std::cout<<"Trying to split "<<val<<std::endl; left = new stupidNumber(val/2); right = new stupidNumber((val+1)/2); val = uinf; if(verb_lvl>6)std::cout<<"splitting"<<std::endl; return true; } if (val != uinf)return false; if(left->split())return true; if(right->split())return true; return false; } bool explode(u_t d) { if (val!=uinf)return false; if(d>=4) { // Assume we're never deeper than this. if (left->val==uinf||right->val==uinf) { std::cerr<<"Oh noes!"<<std::endl;exit(1); } explr=left->val; expll=right->val; val=0; delete left;left=NULL; delete right;right=NULL; if(verb_lvl>7)std::cout<<"Exploded"<<std::endl; return true; } if (left->explode(d+1)) { right->addToLeft(); return true; } if (right->explode(d+1)) { left->addToRight(); return true; } return false; } void addToLeft() { if (expll==uinf){ if(verb_lvl>5)std::cout<<"Aborting ATL"<<std::endl; return; } if (val!=uinf){ if(verb_lvl>4)std::cout<<"Adding lvalue "<<expll<<" to "<<val<<std::endl; val+=expll; expll=uinf; } else left->addToLeft(); } void addToRight() { if (explr==uinf){ if(verb_lvl>5)std::cout<<"Aborting ATR"<<std::endl; return; } if (val!=uinf){ if(verb_lvl>4)std::cout<<"Adding rvalue "<<explr<<" to "<<val<<std::endl; val+=explr; explr=uinf; } else right->addToRight(); } ull_t getM() { if (val!=uinf)return val; return left->getM()*3+right->getM()*2; } void print() { if (val!=uinf){std::cout<<val;return;} std::cout<<'[';left->print();std::cout<<',';right->print();std::cout<<']'; } }; stupidNumber* readN(std::istream& in) { char a=in.peek(); if (a=='[') { read_or_die("[",in); stupidNumber* l=readN(in); read_or_die(",",in); stupidNumber* r=readN(in); read_or_die("]",in); auto rtr= new stupidNumber(l,r); if(verb_lvl>7)std::cout<<"Stored "<<l<<' '<<r<<" in "<<rtr<<std::endl; return rtr; } u_t val = in.get()-'0'; auto rtr= new stupidNumber(val); if(verb_lvl>7)std::cout<<"Stored "<<val<<" in "<<rtr<<std::endl; return rtr; } stupidNumber* addAndSimplify(stupidNumber* n, stupidNumber* m) { stupidNumber* rtr=new stupidNumber(n,m); while (rtr->explode(0)||rtr->split())if(verb_lvl>4){rtr->print();std::cout<<std::endl;} if(verb_lvl>2)std::cout<<"Done simplifying"<<std::endl; if(verb_lvl>2){rtr->print();std::cout<<std::endl;} return rtr; } int real_main(int argc, char** argv) { if (argc < 2) { std::cerr<<"Usage: "<<argv[0]<<" [-v {verbosity_level}] {input_file}"<<std::endl; exit(1); } verb_lvl = argc > 3 && argv[1][0] == '-' && argv[1][1] == 'v' ? std::stoul(argv[2]) : 0; std::ifstream input(argv[argc - 1]); if (!input.good()) { std::cerr<<"Input file "<<argv[argc - 1]<<" did not open correctly"<<std::endl; exit(1); } if (verb_lvl > 0) { std::cout<<"Running in verbosity mode "<<verb_lvl<<std::endl; } stupidNumber* n=readN(input),*m,*result1; std::vector<stupidNumber*>ins={n}; result1=n->getCopy(); read_or_die("\n",input); if(verb_lvl > 2){n->print();std::cout<<std::endl;} if(verb_lvl)std::cout<<"WOEI!"<<std::endl; do { if(verb_lvl)std::cout<<"WOEI!"<<std::endl; m=readN(input); ins.push_back(m); read_or_die("\n",input); if(verb_lvl > 2){m->print();std::cout<<std::endl;} if(verb_lvl)std::cout<<"WOEI!"<<std::endl; result1=addAndSimplify(result1,m->getCopy()); if(verb_lvl)std::cout<<"WOEI!"<<std::endl; } while(input.peek()!='\n'&&!input.eof()); std::cout<<result1->getM()<<std::endl; delete result1; input.close(); ull_t max=0; for (size_t i=1;i<ins.size();i++)for(size_t j=0;j<i;j++){ stupidNumber*m=addAndSimplify(ins[i]->getCopy(),ins[j]->getCopy());ull_t mag=m->getM();if(mag>max)max=mag;delete m; m=addAndSimplify(ins[j]->getCopy(),ins[i]->getCopy());mag=m->getM();if(mag>max)max=mag;delete m; } std::cout<<max<<std::endl; // do things without input return 0; } int main (int argc, char** argv) { auto start = std::chrono::high_resolution_clock::now(); int result = real_main(argc,argv); auto stop = std::chrono::high_resolution_clock::now(); std::cout<<"Duration: "<<std::chrono::duration_cast<std::chrono::microseconds>(stop - start).count()<<std::endl; return result; }
true
acf7193369b325fe53ae909d7581c1d62c777305
C++
LasseD/uva
/P10842.cpp
UTF-8
1,093
2.625
3
[]
no_license
int find(int x, int *parents) { if(parents[x] != x) parents[x] = find(parents[x], parents); return parents[x]; } bool _union(int x, int y, int *parents, int *ranks) { int xRoot = find(x, parents); int yRoot = find(y, parents); if(xRoot == yRoot) return false; // x and y are not already in same set. Merge them. if(ranks[xRoot] < ranks[yRoot]) parents[xRoot] = yRoot; else if(ranks[xRoot] > ranks[yRoot]) parents[yRoot] = xRoot; else { parents[yRoot] = xRoot; ++ranks[xRoot]; } return true; } typedef pair<int,PI> WPI; int main() { int parents[101], ranks[101]; WPI edges[10001]; int N, M, s, t, w; FORCAS { cin >> N >> M; FORI(N) { ranks[i] = 0; parents[i] = i; } FORI(M) { cin >> s >> t >> w; edges[i] = WPI(-w, PI(s,t)); } sort(edges, edges+M); int min = 1000000; FORI(M) { w = edges[i].first; PI p = edges[i].second; if(_union(p.P1, p.P2, parents, ranks)) { min = MIN(min, -w); } } cout << "Case #" << cas+1 << ": " << min << endl; } }
true
892b70cb9fe6f51531e2e91adec432fa3654823c
C++
T1duS/CompetitiveProgramming
/Olympiad/IOI/14-wall.cpp
UTF-8
1,572
2.84375
3
[]
no_license
/* Soln: Same as IOI official soln */ #include "wall.h" #include<bits/stdc++.h> using namespace std; #define REP(i,n) for(int i = 0; i < n; i ++) #define FOR(i,a,b) for(int i = a; i < b; i ++) #define pii pair<int,int> #define F first #define S second #define remax(a,b) a = max(a,b) #define remin(a,b) a = min(a,b) const int MX = 2000005; const int INF = 100000000; struct node{ int vadd,vsub; node(){ vadd = -INF; vsub = INF; } }; node seg[4*MX]; int ans[MX]; void change(int ind,int type,int val){ if(type == 1){ remax(seg[ind].vadd,val); remax(seg[ind].vsub,val); } else remin(seg[ind].vsub,val); } void push(int ind,int l,int r){ if(l == r) return; change(2*ind,1,seg[ind].vadd); change(2*ind,2,seg[ind].vsub); change(2*ind+1,1,seg[ind].vadd); change(2*ind+1,2,seg[ind].vsub); seg[ind].vadd = -INF; seg[ind].vsub = INF; } void upd(int ind, int l, int r, int x, int y, int type,int val){ push(ind,l,r); if(l > y or r < x) return; if(l >= x and r <= y){ change(ind,type,val); push(ind,l,r); return; } int m = (l+r)/2; upd(2*ind,l,m,x,y,type,val); upd(2*ind+1,m+1,r,x,y,type,val); } void calc(int ind,int l,int r){ push(ind,l,r); if(l == r){ ans[l] = min(seg[ind].vadd,seg[ind].vsub); return; } int m = (l+r)/2; calc(2*ind,l,m); calc(2*ind+1,m+1,r); } void buildWall(int n, int k, int op[], int left[], int right[], int height[], int finalHeight[]){ upd(1,0,n-1,0,n-1,1,0); upd(1,0,n-1,0,n-1,2,0); REP(i,k) upd(1,0,n-1,left[i],right[i],op[i],height[i]); calc(1,0,n-1); REP(i,n) finalHeight[i] = ans[i]; }
true
1c154f47146a08948475113db04f2324ce6f5ade
C++
calvin456/intro_derivative_pricing
/cpp_dsgn_pattern_n_derivatives_pricing/chapter6/exercise6_1/exercise6_1/main.cpp
UTF-8
5,640
2.78125
3
[ "MIT" ]
permissive
/* Excercice 6.1 For various cases compare convergence of MC sim w/ and w/o anti-thetic sampling For definition of antithetic var see notes, Numerical Methods II, Prof. Mike Giles, Oxford http://people.maths.ox.ac.uk/~gilesm/mc/ For three cases, antithetic method achieves lower se and price computed is more stable over iteration. */ #include<SimpleMC8.h> #include<ParkMiller.h> #include<iostream> #include <fstream> #include<Vanilla3.h> #include<MCStatistics.h> #include<ConvergenceTable.h> #include<AntiThetic.h> #include<DoubleDigital2.h> using namespace std; int main() { double Expiry_; double Strike; double Spot; double Vol_; double r_; unsigned long NumberOfPaths; cout << "\nEnter expiry\n"; cin >> Expiry_; cout << "\nStrike\n"; cin >> Strike; cout << "\nEnter spot\n"; cin >> Spot; cout << "\nEnter vol\n"; cin >> Vol_; cout << "\nr\n"; cin >> r_; cout << "\nNumber of paths\n"; cin >> NumberOfPaths; //construction of three different options call, put, double digital PayOffCall PayOffcall(Strike); PayOffPut PayOffput(Strike); PayOffDoubleDigital PayOffdouble_digital(Strike, Strike * 1.10); VanillaOption Optioncall(PayOffcall, Expiry_); VanillaOption Optionput(PayOffput, Expiry_); VanillaOption Option_double_digital(PayOffdouble_digital, Expiry_); ParametersConstant Vol(Vol_); ParametersConstant r(r_); StatisticsMean gatherer_mean; //exercice 6.1 StatisticsSE gatherer_se; vector<Wrapper<StatisticsMC>> stat_vec; stat_vec.resize(2); stat_vec[0] = gatherer_mean; stat_vec[1] = gatherer_se; StatsGatherer gathererOne(stat_vec); StatsGatherer gathererTwo(stat_vec); StatsGatherer gathererThree(stat_vec); StatsGatherer gathererFour(stat_vec); StatsGatherer gathererFive(stat_vec); StatsGatherer gathererSix(stat_vec); //Generate convergence tables - antithetic vs non-antithetic //call ConvergenceTable gatherer1(gathererOne); //antithetic ConvergenceTable gatherer2(gathererTwo); //non-antithetic //put ConvergenceTable gatherer3(gathererThree); //antithetic ConvergenceTable gatherer4(gathererFour); //non-antithetic //double digital ConvergenceTable gatherer5(gathererFive); //antithetic ConvergenceTable gatherer6(gathererSix); //non-antithetic RandomParkMiller generator(1); generator.ResetDimensionality(1); cout << "computation starts" << endl; double Expiry = Optioncall.GetExpiry(); double variance = Vol.IntegralSquare(0, Expiry); double rootVariance = sqrt(variance); double itoCorrection = -0.5*variance; double movedSpot = Spot*exp(r.Integral(0, Expiry) + itoCorrection); double thisSpotplus; double thisSpotminus; double discounting = exp(-r.Integral(0, Expiry)); MJArray VariateArray(1); for (unsigned long i = 0; i < NumberOfPaths; i++) { generator.GetGaussians(VariateArray); thisSpotplus = movedSpot*exp(rootVariance*VariateArray[0]); thisSpotminus = movedSpot*exp(-1.0*rootVariance*VariateArray[0]); //call double thisPayOffplus = Optioncall.OptionPayOff(thisSpotplus); double thisPayOffminus = Optioncall.OptionPayOff(thisSpotminus); double thisPayOffavg = 0.5 * (thisPayOffplus + thisPayOffminus); //antithetic variable gatherer1.DumpOneResult(thisPayOffavg*discounting); //antithetic gatherer gatherer2.DumpOneResult(thisPayOffplus*discounting); //non-antithetic gatherer //put thisPayOffplus = Optionput.OptionPayOff(thisSpotplus); thisPayOffminus = Optionput.OptionPayOff(thisSpotminus); thisPayOffavg = 0.5 * (thisPayOffplus + thisPayOffminus); //antithetic variable gatherer3.DumpOneResult(thisPayOffavg*discounting); //antithetic gatherer gatherer4.DumpOneResult(thisPayOffplus*discounting); //non-antithetic gatherer //double digital thisPayOffplus = Option_double_digital.OptionPayOff(thisSpotplus); thisPayOffminus = Option_double_digital.OptionPayOff(thisSpotminus); thisPayOffavg = 0.5 * (thisPayOffplus + thisPayOffminus); //antithetic variable gatherer5.DumpOneResult(thisPayOffavg*discounting); //antithetic gatherer gatherer6.DumpOneResult(thisPayOffplus*discounting); //non-antithetic gatherer } //call vector<vector<double> > results1 = gatherer1.GetResultsSoFar(); //antithetic vector<vector<double> > results2 = gatherer2.GetResultsSoFar(); //non-antithetic //put vector<vector<double> > results3 = gatherer3.GetResultsSoFar(); //antithetic vector<vector<double> > results4 = gatherer4.GetResultsSoFar(); //non-antithetic //double digital vector<vector<double> > results5 = gatherer5.GetResultsSoFar(); //antithetic vector<vector<double> > results6 = gatherer6.GetResultsSoFar(); //non-antithetic //---------------------------------------------- ofstream myfile; myfile.open("price.txt"); myfile << "nb paths" << "," << "vanilla anti call px" << "," << "vanilla anti call se" << "," << "vanilla call px" << "," << "vanilla call se" << "," << "vanilla put anti px" << "," << "vanilla put anti se" << "," << "vanilla put px" << "," << "vanilla put se" << "," << "double barrier anti px" << "," << "double barrier anti se" << "," << "double barrier px" << "," << "double barrier se" << "\n"; for (unsigned long i = 0; i < results1.size(); i++) { myfile << results1[i][2] << "," << results1[i][0] << "," << results1[i][1] << "," << results2[i][0] << "," << results2[i][1] << "," << results3[i][0] << "," << results3[i][1] << "," << results4[i][0] << "," << results4[i][1] << "," << results5[i][0] << "," << results5[i][1] << "," << results6[i][0] << "," << results6[i][1] << "\n"; } cout << "computation ended" << endl; myfile.close(); double tmp; cin >> tmp; return 0; }
true
54b5a46468b0039e884e2e30cd59bd026e61b877
C++
anwar-hegazy/GoGoGo
/TestCode/GoGoGo-MotorTest2/GoGoGo-MotorTest2.ino
UTF-8
1,148
2.671875
3
[]
no_license
// the setup function runs once when you press reset or power the board int in1 = 6; int in2 = 8; int stby = 0; int pwm = 5; int decoder = 2; int countLimit = 10000; int counter=0; void setup() { // initialize digital pin 13 as an output. pinMode(pwm, OUTPUT); pinMode(in2, OUTPUT); pinMode(in1, OUTPUT); pinMode(stby, OUTPUT); pinMode(decoder, INPUT); attachInterrupt(digitalPinToInterrupt(decoder), count, CHANGE); Serial.begin(9600); } void count() { ++counter; } // the loop function runs over and over again forever void loop() { leftwheel (true, 128, 100); delay(2000); leftwheel (false, 255, 10); delay(2000); } void leftwheel (boolean forward, int velocity, int steps) { analogWrite(pwm, velocity); counter = 0; while(counter<steps){ digitalWrite(stby, HIGH); if (forward == true) { digitalWrite(in1, HIGH); digitalWrite(in2, LOW); } else { digitalWrite(in1, LOW); digitalWrite(in2, HIGH); } Serial.println(counter); } Serial.print("DEBUG: Out of the loop now"); digitalWrite(in1, HIGH); digitalWrite(in2, HIGH); }
true
54281967c3f2454d634a26b5e076a8339c66ec64
C++
dean2727/KattisJourney
/lab7/lawn_mower/C.cpp
UTF-8
1,788
3.28125
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { int nx, ny; float xi, yi, left, right; float w; cin >> nx; while (nx != 0) { cin >> ny >> w; bool horizGap = false, vertGap = false; vector<float> vertPasses; while (nx--) { cin >> xi; //cout << "xi is " << xi << endl; vertPasses.push_back(xi); } sort(vertPasses.begin(), vertPasses.end()); if (vertPasses[0] - (w/2) > 0.0) vertGap = true; // if the next strip's left bound is larger than .1 away from this strips's right bound, we have gap //cout << "vertical:\n"; for (int i=0;i<vertPasses.size()-1;i++){ //cout << vertPasses[i] << endl; float nextLeft = vertPasses[i+1] - (w/2); float thisRight = vertPasses[i] + (w/2); //cout << nextLeft - thisRight << endl; if (nextLeft - thisRight > .0000001) vertGap = true; } if (vertPasses[vertPasses.size()-1] + (w/2) < 75.0) vertGap = true; vector<float> horizPasses; while (ny--){ cin >> yi; horizPasses.push_back(yi); //cout << "yi is " << yi << endl; } sort(horizPasses.begin(), horizPasses.end()); if (horizPasses[0] - (w/2) > 0.0) horizGap = true; //cout << "horizontal:\n"; // if the next strip's left bound is larger than .1 away from this strips's right bound, we have gap for (int i=0;i<horizPasses.size()-1;i++){ //cout << horizPasses[i] << endl; float nextLeft = horizPasses[i+1] - (w/2); float thisRight = horizPasses[i] + (w/2); //cout << nextLeft - thisRight << endl; if (nextLeft - thisRight > .0000001) horizGap = true; } if (horizPasses[horizPasses.size()-1] + (w/2) < 100.0) horizGap = true; if (vertGap || horizGap){ cout << "NO\n"; } else { cout << "YES\n"; } cin >> nx; } cin >> ny >> w; return 0; }
true
6b5bbd7a05a1a94b59857348cd5071bd31d8f66b
C++
pavel-lebedev96/Translator-Lexical-analysis
/Транслятор/var_table.cpp
UTF-8
1,720
3.03125
3
[]
no_license
#include "lexemes.h" #include "var_table.h" int var_table::hash(std::string l_name) { int summ = 0; for (auto i : l_name) summ += i; return summ % table.size(); } var_table::var_table(const int size) { table = std::vector<std::vector<T_lexemes>>(size); } bool var_table::add_lexeme(std::string l_name, std::pair<int, int>& l_pos) { if (find_lexeme(l_name, l_pos)) return false; table[l_pos.first].push_back(T_lexemes(l_name)); return true; } bool var_table::find_lexeme(std::string l_name, std::pair<int, int>& l_pos) { l_pos.first = hash(l_name); if (table[l_pos.first].empty()) return false; l_pos.second = 0; for (auto i : table[l_pos.first]) { if (i.name == l_name) return true; l_pos.second++; } return false; } bool var_table::get_l_attr_value(std::string l_name, std::string attr_name, int & attr_value) { std::pair<int, int> l_pos; if (!find_lexeme(l_name, l_pos)) return false; return table[l_pos.first][l_pos.second].get_attr_value(attr_name, attr_value); } bool var_table::get_l_attr_value(std::pair<int, int>& l_pos, std::string attr_name, int& attr_value) { try { return table.at(l_pos.first).at(l_pos.second).get_attr_value(attr_name, attr_value); } catch (...) { return false; } } bool var_table::set_l_attr_value(std::string l_name, std::string attr_name, int attr_value) { std::pair<int, int> l_pos; if (!find_lexeme(l_name, l_pos)) return false; return table[l_pos.first][l_pos.second].set_attr_value(attr_name, attr_value); } bool var_table::set_l_attr_value(std::pair<int, int>& l_pos, std::string attr_name, int attr_value) { try { return table.at(l_pos.first).at(l_pos.second).set_attr_value(attr_name, attr_value); } catch (...) { return false; } }
true
d454e7574ab1ff97cc6dd912bae6a01d660b3a4e
C++
edwardrowens/jimmyjump
/Core/Box2dMapper.cpp
UTF-8
656
2.59375
3
[]
no_license
#include "Box2dMapper.h" b2FixtureDef Box2dMapper::mapToFixture(const ObjectPhysicalProperties::ObjectPhysicalProperties &props) { b2FixtureDef fixtureDef; fixtureDef.density = props.density; fixtureDef.friction = props.friction; return fixtureDef; } b2BodyDef Box2dMapper::mapToBody(const ObjectPhysicalProperties::ObjectPhysicalProperties &props) { b2BodyDef bodyDef; bodyDef.type = props.bodyType; bodyDef.position.Set(props.x, props.y); return bodyDef; } b2PolygonShape Box2dMapper::mapToShape(const ObjectPhysicalProperties::ObjectPhysicalProperties &props) { b2PolygonShape box; box.SetAsBox(props.w / 2, props.h / 2); return box; }
true
34aa1afe6513e1a8fb741a618d8fe0ccbc7b97f0
C++
luchenqun/leet-code
/problems/809-expressive-words.cpp
UTF-8
2,044
3.546875
4
[]
no_license
/* * [827] Expressive Words * * https://leetcode-cn.com/problems/expressive-words/description/ * https://leetcode.com/problems/expressive-words/discuss/ * * algorithms * Medium (31.40%) * Total Accepted: 27 * Total Submissions: 86 * Testcase Example: '"heeellooo"\n["hello", "hi", "helo"]' * * 有时候人们会用额外的字母来表示额外的情感,比如 "hello" -> "heeellooo", "hi" -> * "hiii"。我们将连续的相同的字母分组,并且相邻组的字母都不相同。我们将一个拥有三个或以上字母的组定义为扩张状态(extended),如第一个例子中的 * "e" 和" o" 以及第二个例子中的 "i"。 此外,"abbcccaaaa" 将有分组 "a" , "bb" , "ccc" , "dddd";其中 * "ccc" 和 "aaaa" 处于扩张状态。 * 对于一个给定的字符串 S ,如果另一个单词能够通过将一些字母组扩张从而使其和 S * 相同,我们将这个单词定义为可扩张的(stretchy)。我们允许选择一个字母组(如包含字母 c ),然后往其中添加相同的字母 c 使其长度达到 3 * 或以上。注意,我们不能将一个只包含一个字母的字母组,如 "h",扩张到一个包含两个字母的组,如 * "hh";所有的扩张必须使该字母组变成扩张状态(至少包含三个字母)。 * 输入一组单词,输出其中可扩张的单词数量。 * 示例: * 输入: * S = "heeellooo" * words = ["hello", "hi", "helo"] * 输出:1 * 解释: * 我们能通过扩张"hello"的"e"和"o"来得到"heeellooo"。 * 我们不能通过扩张"helo"来得到"heeellooo"因为"ll"不处于扩张状态。 * 说明: * 0 <= len(S) <= 100。 * 0 <= len(words) <= 100。 * 0 <= len(words[i]) <= 100。 * S 和所有在 words 中的单词都只由小写字母组成。 */ #include <iostream> #include <string> using namespace std; class Solution { public: int expressiveWords(string S, vector<string>& words) { } }; int main() { Solution s; return 0; }
true
b5811e3302168268191d22ef3e849b2f1679d72d
C++
Zephyrwind/computational-physics
/EX1-RNG/1.3.cpp
UTF-8
2,008
3.390625
3
[]
no_license
/* Cláudio Santos nº 42208 MIEF - Modelação em Física e Engenharia Ex 1.3 - Teste do Qui-Quadrado Outubro de 2016 */ #include <math.h> #include <iostream> #include <fstream> #include <stdlib.h> using namespace std; int main() { /* Declaraçao de variaveis */ int X0=333331; // seed int c=3; // multiplicador do gerador int a=5; // desvio do gerador double Nmax=31; // maior número possível de ser gerado int n=50; // numero de numeros aleatorios gerados int range=10; // intervalo de 0-10 double pi=1.0/(double)range; // probabilidade de cada intervalo double Y[n]; // variavel para calcular numero aleatorio double X[n]; // array com os numeros aleatorios gerados int N[range]={0}; // array que conta o numero de numeros aleatorios gerados int conta=0; // contador double qui2=0; // qui-quadrado /* Gerador de n numeros aleatorios entre 0-10 usando metodo congruente com os valores do ex. 1.1 */ for(int i=0;i<n;i++){ if(i==0){ Y[0]=X0; X[0]=range*fmod(c*Y[0]+a,Nmax)/Nmax; } if(i>=1){ Y[i]=X[i-1]; X[i]=range*fmod(c*Y[i]+a,Nmax)/Nmax; } } /* Contagem do numero de numeros aleatorios em cada intervalo */ for(int j=0;j<n;j++){ for(int k=0;k<range;k++){ if(k<X[j]<k+1){ conta=conta+1; N[k]=conta; } } conta=0; } /* Implementaçao do Qui-quadrado */ for(int k=0;k<range;k++){ qui2=qui2+(N[k]-(double)n*pi)*(N[k]-(double)n*pi)/((double)n*pi); } cout << "(Metodo Congruente) Qui-Quadrado= " << qui2 << endl; /* Comparação do teste do qui quadrado usando funçao rand */ double Xr[n]; int Nr[range]={0}; double qui2r; for(int i=0;i<n;i++){ Xr[i]=range*(rand()/(double) RAND_MAX); } for(int j=0;j<n;j++){ for(int k=0;k<range;k++){ if(k<Xr[j]<k+1){ conta=conta+1; Nr[k]=conta; } } conta=0; } for(int k=0;k<range;k++){ qui2r=qui2r+(Nr[k]-(double)n*pi)*(Nr[k]-(double)n*pi)/((double)n*pi); } cout << "(Função Rand) Qui-Quadrado= " << qui2r << endl; return 0; }
true
7fc54271739f50936a79107bcb83640858b33440
C++
piyush-taneja/Codes
/c++ codes/labsheet1(1).cpp
UTF-8
1,762
3.734375
4
[]
no_license
#include<iostream> using namespace std; class complex{ double real; double imaginary; public: void enter_data(); void display_data(); void addition(complex c1,complex c2); void subtraction(complex c1,complex c2); void multipication(complex c1,complex c2); void division(complex c1,complex c2); }; void complex::enter_data() { cout<<"Enter the real part"; cin>>real; cout<<"Enter the imaginary part"; cin>>imaginary; } void complex::display_data() { if(imaginary>0) cout<<real<<"+"<<imaginary<<"i"; else cout<<real<<"-"<<imaginary<<"i"; } void complex::addition(complex c1,complex c2) { real=c1.real+c2.real; imaginary=c1.imaginary+c2.imaginary; display_data(); } void complex::subtraction(complex c1,complex c2) { real=c1.real-c2.real; imaginary=c1.imaginary-c2.imaginary; display_data(); } void complex::multipication(complex c1,complex c2) { real=c1.real*c2.real; imaginary=c1.imaginary*c2.imaginary; display_data(); }void complex::division(complex c1,complex c2) { real=c1.real/c2.real; imaginary=c1.imaginary/c2.imaginary; display_data(); } int main() { complex c1,c2,c3,c4,c5,c6; int c; while(1){ cout<<"1.Enter Data\n 2.Perform Addition \n 3.Perform Subtraction\n 4.Perform Multipication \n5.Perform Division \n6.exit"; cin>>c; switch(c) { case 1: c1.enter_data(); c2.enter_data(); break; case 2: c3.addition(c1,c2); break; case 3: c4.subtraction(c1,c2); break; case 4: c5.multipication(c1,c2); break; case 5: c6.division(c1,c2); break; case 6: break; default: cout<<"Wrong choice"; }} return 0; }
true
a669206068cd8973d85c082bad35a1d57009d09b
C++
KaranPhadnisNaik/BattleShip-Game
/Player.cpp
UTF-8
16,078
3.375
3
[]
no_license
#include "Player.h" #include <iostream> #include <cctype> #include <string> using namespace std; const int NORTH = 0; const int SOUTH = 1; const int EAST = 2; const int WEST = 3; const bool PLAYERGRID = true; const bool OPPONENTGRID = false; Player::Player() { for (int i = 0; i < 11; i++) { for (int j = 0; j < 11; j++) { PlayerGrid[i][j] = '~'; OpponentGrid[i][j] = '~'; } } char ArrayOfLetters[10] = { 'A','B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J' }; for (int i = 0; i < 10; i++) { PlayerGrid[0][i+1] = ArrayOfLetters[i]; PlayerGrid[i+1][0] = ArrayOfLetters[i]; OpponentGrid[0][i + 1] = ArrayOfLetters[i]; OpponentGrid[i + 1][0] = ArrayOfLetters[i]; } PlayerGrid[0][0] = ' '; OpponentGrid[0][0] = ' '; //printBoards(); //setStartingPieces(); } void Player::setStartingPieces() { printBoards(); insertShip(0); insertShip(1); insertShip(2); insertShip(3); insertShip(4); } string Player::AreCoordinatesSyntacticallyCorrect(string& coordinates) { bool SyntacticallycoordiantesAreOkay; while (true){ SyntacticallycoordiantesAreOkay = true; if (coordinates.size() == 2) { int i = 0; while (i < 2){ if (!isalpha(coordinates[i]) || islower(coordinates[i])) SyntacticallycoordiantesAreOkay = false; i++; } } if (coordinates.size() == 1 || SyntacticallycoordiantesAreOkay == false){ cout << "Enter synatactically valid coordinates: "; cin >> coordinates; } else break; } return coordinates; } void Player::insertShip(int INDEX) { string ArrayOfShips[5] = { "AIRCRAFT CARRIER (5 spaces)", "BATTLE SHIP (4 spaces)", "SUBMARINE (3 spaces)", "DESTROYER (3 spaces) ", "PATROL BOAT (2 spaces)" }; string coordinates; while (true){ cout << "Where do you want to place the " << ArrayOfShips[INDEX] << "?: "; cin >> coordinates; cin.ignore(1000, '\n'); //checks if the coordinates are syntactically correct, will repeat until they are // NOTE: THIS ASSUMES THAT THE PERSON ENTERS LETTER THAT ARE WITHIN THE RANGE OF THE BOARD coordinates = AreCoordinatesSyntacticallyCorrect(coordinates); /*bool SyntacticallycoordiantesAreOkay; while (true){ SyntacticallycoordiantesAreOkay = true; if (coordinates.size() == 2) { int i = 0; while (i < 2){ if (!isalpha(coordinates[i]) || islower(coordinates[i])) SyntacticallycoordiantesAreOkay = false; i++; } } if (coordinates.size() == 1 || SyntacticallycoordiantesAreOkay == false){ cout << "Enter synatactically valid coordinates: "; cin >> coordinates; } else break; } */ // direction that you want to place the ship int placementDirection; string Dir; cout << "Direction you want the ship to point ( N / S / E / W ) **Note: Will build in opposite direction**: "; while (true) { cin >> Dir; cin.ignore(1000, '\n'); if (Dir.size() == 1) { if (Dir[0] == 'N'){ placementDirection = NORTH; break; } if (Dir[0] == 'S'){ placementDirection = SOUTH; break; } if (Dir[0] == 'E'){ placementDirection = EAST; break; } if (Dir[0] == 'W'){ placementDirection = WEST; break; } } cout << "Enter proper value: "; } //concerts the letter coordinates into number coordinates int index = 0; int rowValue; int columnValue; while (index < 2) { switch (coordinates[index]){ case 'A': if (index == 0) rowValue = 1; else columnValue = 1; index++; break; case 'B': if (index == 0) rowValue = 2; else columnValue = 2; index++; break; case 'C': if (index == 0) rowValue = 3; else columnValue = 3; index++; break; case 'D': if (index == 0) rowValue = 4; else columnValue = 4; index++; break; case 'E': if (index == 0) rowValue = 5; else columnValue = 5; index++; break; case 'F': if (index == 0) rowValue = 6; else columnValue = 6; index++; break; case 'G': if (index == 0) rowValue = 7; else columnValue = 7; index++; break; case 'H': if (index == 0) rowValue = 8; else columnValue = 8; index++; break; case 'I': if (index == 0) rowValue = 9; else columnValue = 9; index++; break; case 'J': if (index == 0) rowValue = 10; else columnValue = 10; index++; break; } } // now check if the specifed ship fits within the board bool checker = false; bool willADDifTrue = true; if (INDEX == 0) // MEANS 5-SPACE SHIP { if (placementDirection == NORTH) { if (rowValue + 4 <= 10) { for (int i = 0; i < 5; i++) { if (PlayerGrid[rowValue + i][columnValue] != '~'){ cout << endl << " You will have to find other coordinates for " << ArrayOfShips[INDEX] << "." << endl; willADDifTrue = false; break; } } if (willADDifTrue){ for (int i = 0; i < 5; i++) { PlayerGrid[rowValue + i][columnValue] = '@'; checker = true; } } break; } //cout << " You will have to find other coordinates for " << ArrayOfShips[INDEX] << "." << endl; } if (placementDirection == SOUTH) { if (rowValue - 4 >= 1) { for (int i = 0; i < 5; i++) { if (PlayerGrid[rowValue - i][columnValue] != '~'){ cout << endl << " You will have to find other coordinates for " << ArrayOfShips[INDEX] << "." << endl; willADDifTrue = false; break; } } if (willADDifTrue){ for (int i = 0; i < 5; i++) { PlayerGrid[rowValue - i][columnValue] = '@'; checker = true; } } break; } //cout << " You will have to find other coordinates for " << ArrayOfShips[INDEX] << "." << endl; } if (placementDirection ==EAST) { if (columnValue - 4 >= 1) { for (int i = 0; i < 5; i++) { if (PlayerGrid[rowValue][columnValue-i] != '~'){ cout << endl << " You will have to find other coordinates for " << ArrayOfShips[INDEX] << "." << endl; break; } } for (int i = 0; i < 5; i++) { PlayerGrid[rowValue][columnValue - i] = '@'; checker = true; } break; } //cout << " You will have to find other coordinates for " << ArrayOfShips[INDEX] << "." << endl; } if (placementDirection == WEST) { if (columnValue + 4 <= 10) { for (int i = 0; i < 5; i++) { if (PlayerGrid[rowValue][columnValue + i] != '~'){ cout << endl << " You will have to find other coordinates for " << ArrayOfShips[INDEX] << "." << endl; break; } } for (int i = 0; i < 5; i++) { PlayerGrid[rowValue][columnValue + i] = '@'; checker = true; } // break; } // cout << " You will have to find other coordinates for " << ArrayOfShips[INDEX] << "." << endl; } } if (INDEX == 1) // MEANS 4-SPACE SHIP { if (placementDirection == NORTH) { if (rowValue + 3 <= 10) { for (int i = 0; i < 4; i++) { if (PlayerGrid[rowValue + i][columnValue] != '~'){ cout << endl << " You will have to find other coordinates for " << ArrayOfShips[INDEX] << "." << endl; willADDifTrue = false; break; } } if (willADDifTrue){ for (int i = 0; i < 4; i++) { PlayerGrid[rowValue + i][columnValue] = 'T'; checker = true; } } // break; } // cout << " You will have to find other coordinates for " << ArrayOfShips[INDEX] << "." << endl; } if (placementDirection == SOUTH) { if (rowValue - 3 >= 1) { for (int i = 0; i < 4; i++) { if (PlayerGrid[rowValue - i][columnValue] != '~'){ cout << endl << " You will have to find other coordinates for " << ArrayOfShips[INDEX] << "." << endl; willADDifTrue = false; break; } } if (willADDifTrue){ for (int i = 0; i < 4; i++) { PlayerGrid[rowValue - i][columnValue] = 'T'; checker = true; } } //break; } //cout << " You will have to find other coordinates for " << ArrayOfShips[INDEX] << "." << endl; } if (placementDirection == EAST) { if (columnValue - 4 >= 1) { for (int i = 0; i < 4; i++) { if (PlayerGrid[rowValue][columnValue - i] != '~'){ cout << endl << " You will have to find other coordinates for " << ArrayOfShips[INDEX] << "." << endl; willADDifTrue = false; break; } } if (willADDifTrue){ for (int i = 0; i < 4; i++) { PlayerGrid[rowValue][columnValue - i] = 'T'; checker = true; } } //break; } //cout << " You will have to find other coordinates for " << ArrayOfShips[INDEX] << "." << endl; } if (placementDirection == WEST) { if (columnValue + 3 <= 10) { for (int i = 0; i < 4; i++) { if (PlayerGrid[rowValue][columnValue + i] != '~'){ cout << endl << " You will have to find other coordinates for " << ArrayOfShips[INDEX] << "." << endl; willADDifTrue = false; break; } } if (willADDifTrue){ for (int i = 0; i < 4; i++) { PlayerGrid[rowValue][columnValue + i] = 'T'; checker = true; } } //break; } //cout << " You will have to find other coordinates for " << ArrayOfShips[INDEX] << "." << endl; } } if (INDEX == 2 || INDEX == 3 ) // MEANS 2 TYPES OF 3-SPACE SHIP { if (placementDirection == NORTH) { if (rowValue + 2 <= 10) { for (int i = 0; i < 3; i++) { if (PlayerGrid[rowValue + i][columnValue] != '~'){ cout << endl << " You will have to find other coordinates for " << ArrayOfShips[INDEX] << "." << endl; willADDifTrue = false; break; } } if (willADDifTrue){ for (int i = 0; i < 3; i++) { if (INDEX == 2) PlayerGrid[rowValue + i][columnValue] = 'U'; if (INDEX == 3) PlayerGrid[rowValue + i][columnValue] = 'Y'; checker = true; } } //break; } //cout << " You will have to find other coordinates for " << ArrayOfShips[INDEX] << "." << endl; } if (placementDirection == SOUTH) { if (rowValue - 2 >= 1) { for (int i = 0; i < 3; i++) { if (PlayerGrid[rowValue - i][columnValue] != '~'){ cout << endl << " You will have to find other coordinates for " << ArrayOfShips[INDEX] << "." << endl; willADDifTrue = false; break; } } if (willADDifTrue){ for (int i = 0; i < 3; i++) { if (INDEX == 2) PlayerGrid[rowValue - i][columnValue] = 'U'; if (INDEX == 3) PlayerGrid[rowValue - i][columnValue] = 'Y'; checker = true; } } //break; } // cout << " You will have to find other coordinates for " << ArrayOfShips[INDEX] << "." << endl; } if (placementDirection == EAST) { if (columnValue - 2 >= 1) { for (int i = 0; i < 3; i++) { if (PlayerGrid[rowValue][columnValue - i] != '~'){ cout << endl << " You will have to find other coordinates for " << ArrayOfShips[INDEX] << "." << endl; willADDifTrue = false; break; } } if (willADDifTrue) { for (int i = 0; i < 3; i++) { if (INDEX == 2) PlayerGrid[rowValue][columnValue-i] = 'U'; if (INDEX == 3) PlayerGrid[rowValue][columnValue-i] = 'Y'; checker = true; } } //break; } //cout << " You will have to find other coordinates for " << ArrayOfShips[INDEX] << "." << endl; } if (placementDirection == WEST) { if (columnValue + 2 <= 10) { for (int i = 0; i < 3; i++) { if (PlayerGrid[rowValue][columnValue + i] != '~'){ cout << endl << " You will have to find other coordinates for " << ArrayOfShips[INDEX] << "." << endl; willADDifTrue = false; break; } } if (willADDifTrue){ for (int i = 0; i < 3; i++) { if (INDEX == 2) PlayerGrid[rowValue][columnValue+i] = 'U'; if (INDEX == 3) PlayerGrid[rowValue][columnValue+i] = 'Y'; checker = true; } } //break; } //cout << endl << " You will have to find other coordinates for " << ArrayOfShips[INDEX] << "." << endl; } } if (INDEX == 4) // MEANS 2-SPACE SHIP { if (placementDirection == NORTH) { if (rowValue + 1 <= 10) { for (int i = 0; i < 2; i++) { if (PlayerGrid[rowValue + i][columnValue] != '~'){ cout << endl << " You will have to find other coordinates for " << ArrayOfShips[INDEX] << "." << endl; willADDifTrue = false; break; } } if (willADDifTrue){ for (int i = 0; i < 2; i++) { PlayerGrid[rowValue + i][columnValue] = 'P'; checker = true; } } //break; } //cout << " You will have to find other coordinates for " << ArrayOfShips[INDEX] << "." << endl; } if (placementDirection == SOUTH) { if (rowValue - 1 >= 1) { for (int i = 0; i < 2; i++) { if (PlayerGrid[rowValue - i][columnValue] != '~'){ cout << endl << " You will have to find other coordinates for " << ArrayOfShips[INDEX] << "." << endl; willADDifTrue = false; break; } } if (willADDifTrue){ for (int i = 0; i < 2; i++) { PlayerGrid[rowValue - i][columnValue] = 'P'; checker = true; } } //break; } // cout << " You will have to find other coordinates for " << ArrayOfShips[INDEX] << "." << endl; } if (placementDirection == EAST) { if (columnValue - 1 >= 1) { for (int i = 0; i < 2; i++) { if (PlayerGrid[rowValue][columnValue - i] != '~'){ cout << endl << " You will have to find other coordinates for " << ArrayOfShips[INDEX] << "." << endl; willADDifTrue = false; break; } } if (willADDifTrue) { for (int i = 0; i < 2; i++) { PlayerGrid[rowValue][columnValue - i] = 'P'; checker = true; } } //break; } //cout << " You will have to find other coordinates for " << ArrayOfShips[INDEX] << "." << endl; } if (placementDirection == WEST) { if (columnValue + 1 <= 10) { for (int i = 0; i < 2; i++) { if (PlayerGrid[rowValue][columnValue + i] != '~'){ cout << endl << " You will have to find other coordinates for " << ArrayOfShips[INDEX] << "." << endl; willADDifTrue = false; break; } } if (willADDifTrue){ for (int i = 0; i < 2; i++) { PlayerGrid[rowValue][columnValue + i] = 'P'; checker = true; } } //break; } //cout << endl << " You will have to find other coordinates for " << ArrayOfShips[INDEX] << "." << endl; } } if (checker) break; } system("cls"); printBoards(); } void Player::printBoards() { cout <<" " <<"Your Grid" << " " << "Opponent's Grid" << endl<<endl; for (int i = 0; i < 11; i++) { cout << " "; for (int j = 0; j < 11; j++) { cout << PlayerGrid[i][j] << " "; } cout << " "; for (int j = 0; j < 11; j++) { cout << OpponentGrid[i][j] << " "; } cout << endl << endl; } } bool Player::checkgrid(int row, int column) { if (PlayerGrid[row][column] == '@' || PlayerGrid[row][column] == 'T' || PlayerGrid[row][column] == 'U' || PlayerGrid[row][column] == 'Y' || PlayerGrid[row][column] == 'P') return true; else return false; } void Player::insertIntoGrid(int row, int column, char character, bool whatGridToInsert) { if (whatGridToInsert) PlayerGrid[row][column] = character; else OpponentGrid[row][column] = character; } char Player::whatLetterIsAt(int row, int column) { char character = PlayerGrid[row][column]; return character; } Player::~Player() { }
true
d3740a83f6173056b0f60d254648cdae831c4d92
C++
anderson-pids/ri-autocompletion_algorithms
/ican_implemented/src/trie.hpp
UTF-8
2,541
2.578125
3
[]
no_license
#pragma once #include "itemTable.hpp" #include "trieNode.hpp" #include <set> #include <queue> #include <vector> namespace trie { struct ActiveNode_t { TrieNode_t* node; mutable int editDistance; mutable int positionDistance; ActiveNode_t(TrieNode_t*, int); ActiveNode_t(TrieNode_t*, int, int); bool operator<(const ActiveNode_t&) const; }; struct ActiveNodeComparator_t { bool operator()(const ActiveNode_t&, const ActiveNode_t&) const; }; class Trie_t { // std::vector<unsigned int> m_characterMap; // used to map all the characters to it's defined codes TrieNode_t* m_lambdaNode; // used to indicate the first node std::vector<char> m_reverseCharacterMap; // used to map all the defined codes to it's characters (4fun) std::set<ActiveNode_t> m_activeNodeSet; // uset to save the main activeNode set std::set<std::string> m_stopWords; int m_searchLimitThreshold; // threshold used for delimit the answers amount (default : 5) int m_fuzzyLimitThreshold; // threshold used for delimit the edit distance from node (default : 1) // void encodeCharacters(const std::string&); // used to start the encoding/decoding vector of the characters contained on the file std::set<ActiveNode_t> buildNewSet(std::set<ActiveNode_t>&, char); ItemTable_t m_itemTable; public: Trie_t(); // default constructor, receiving the filename which wordmap will be readen void addStopWords(const std::string&); bool isStopWord(std::string); void printTrie(); // print the tree { see the tree on http://mshang.ca/syntree/ =) } void putWord(const std::string&, char, unsigned int); // include a string in the trie structure TrieNode_t* putNReturnWord(const std::string&); // include a string in the trie structure and return it's node // void putFile(const std::string&); void setSearchLimitThreshold(int); // set the m_searchLimitThreshold void setFuzzyLimitThreshold(int); // set the m_fuzzyLimitThreshold void buildActiveNodeSet(); // used to build the activeNode set at once // std::vector<std::string> searchExactKeyword(const std::string&); std::priority_queue<Occurrence_t, std::vector<Occurrence_t> , OccurrencePriorityComparator_t> searchSimilarKeyword(const std::string&); std::priority_queue<Occurrence_t, std::vector<Occurrence_t> , OccurrencePriorityComparator_t> searchSimilarKeyword2(const std::string&); std::string getItemOnTable(unsigned int); unsigned int insertItemOnTable(const std::string&); }; }
true
6f50022e472065c6826219ed76f4ff0fc4b15888
C++
nabeeljay/cd
/abdul_karim/TAC/parent.cpp
UTF-8
4,256
2.671875
3
[]
no_license
#include "parent.h" parent::parent() { } parent::parent(string fileName) { populate(fileName); } void parent::populate(string fileName) { char temp[32]; LOC t1; int index = 0; ifstream file(fileName); if(!file) { cerr << "Error opening the input file: " << fileName << endl; return; } while (file) { file.getline(temp, 32); t1.n = ++index; t1.lineOfCode = temp; code.push_back(t1); } /*Find leaders*/ set<int> tempLeaders; tempLeaders.insert(1); size_t locationOfGoto, locationOfAddress1, locationOfAddress2; string loc; int addr; for(int i = 0; i < code.size(); i++) { loc = code[i].lineOfCode; if((locationOfGoto = loc.find("goto")) != string::npos) { locationOfAddress1 = loc.find("(", locationOfGoto) + 1; locationOfAddress2 = loc.find(")", locationOfAddress1); addr = stoi(loc.substr(locationOfAddress1, locationOfAddress2 - locationOfAddress1)); tempLeaders.insert(addr); tempLeaders.insert(i+2); } } for(set<int>::iterator it = tempLeaders.begin(); it != tempLeaders.end(); ++it) leaders.push_back(*it); leaders.sort(); /*Create Blocks*/ unsigned int start, end; string tempString; int blockNo = 1; for(list<int>::iterator it = leaders.begin(); it != leaders.end(); blockNo++) { start = *it; it++; if(it == leaders.end()) end = code.size(); else end = *it; vector<LOC> tempTAC; for(unsigned int i = start; i < end; i++) { tempTAC.push_back(code[i-1]); } graph.push_back(block(tempTAC, blockNo)); } /*Link Blocks*/ for(int i = 0; i < graph.size(); i++) { string text = graph[i].getCode(-1); if(text.find("if") != string::npos) { if(i+1 != graph.size()) { graph[i].addToToList(i+2); graph[i+1].addToFromList(i+1); } } if(text.find("goto") != string::npos) { size_t locationOfGoto, locationOfAddress1, locationOfAddress2; locationOfGoto = text.find("goto"); locationOfAddress1 = text.find("(", locationOfGoto) + 1; locationOfAddress2 = text.find(")", locationOfAddress1); int addr = stoi(text.substr(locationOfAddress1, locationOfAddress2 - locationOfAddress1)); int j; for(j = 0; j < graph.size(); j++) if(graph[j].hasLine(addr)) break; graph[i].addToToList(j+1); graph[j].addToFromList(i+1); } else { if(i+1 != graph.size()) { graph[i].addToToList(i+2); graph[i+1].addToFromList(i+1); } } } /*Dominators*/ graph[0].setDom(1); for(unsigned int k = 1; k < graph.size(); k++) { set<unsigned int> tempFromList = graph[k].getFromList(); set<unsigned int> resultant, temp1, temp2; for(unsigned int i = 1; i < 100; i++) resultant.insert(i); for(set<unsigned int>::iterator its = tempFromList.begin(); its != tempFromList.end(); ++its) //************ { if(*its > k) continue; temp1.clear(); temp1 = resultant; temp2 = graph[*its - 1].getDom(); resultant.clear(); set_intersection(temp1.begin(), temp1.end(), temp2.begin(), temp2.end(), inserter(resultant, resultant.begin())); } resultant.insert(k+1); graph[k].setDom(resultant); } } string parent::printCode() { string text="", temp; for(int i = 0; i < code.size(); i++) { temp = to_string(code[i].n) + ":\t" + code[i].lineOfCode + "\n"; text.append(temp); } return text; } bool parent::myFunction(int i, int j) { return (i==j); } string parent::leaderList() { string text="", temp; for(list<int>::iterator it = leaders.begin(); it != leaders.end(); ++it) { temp = to_string(*it) + " "; text.append(temp); } return text; } string parent::blocks() { string text=""; for(int i = 0; i < graph.size(); i++) { text.append(graph[i].printBlock()); text.append("\n\n"); } return text; } string parent::printLoops() { string text = ""; for(int i = 0; i < graph.size(); i++) { set<unsigned int> dom, to, resultant; to = graph[i].getToList(); dom = graph[i].getDom(); resultant.clear(); set_intersection(to.begin(), to.end(), dom.begin(), dom.end(), inserter(resultant, resultant.begin())); if(resultant.size()) { text += "\nLoops from " + to_string(i+1) + ": "; for(set<unsigned int>::iterator it = resultant.begin(); it != resultant.end(); ++it) text += " " + to_string(*it); } } text += "\n"; return text; }
true
4b136184a07751cb2e2bb66076c10ae2ffaa12b2
C++
anantatapase/SPOJ
/NICEBTRE.cpp
UTF-8
799
3.03125
3
[]
no_license
#include<iostream> #include<cstdio> #include<cstring> using namespace std; int i,l; void print(char s[],int h,int *max) { if(i==l-1) return; if(h>*max)//can make max global also *max=h; if(s[i]=='l') { i++; //inserted leaf in tree (virtually) and going to next node in preorder traverasl return;//left side end going back to parent } //here s[i]==n i++; //inserted node in tree(vertually) and going to next node in preorder traversal print(s,h+1,max);//going to left side of tree //after completing left subtree print(s,h+1,max);//going to rite side return ;//rite side end going back to parent } int main() { int t; cin>>t; while(t--) { char s[10001]; int max=0; scanf("%s",s); l=strlen(s); i=0; print(s,0,&max); printf("%d\n",max); } }
true
f03e0f46ced7108dbd601a4e8bb1dbb396a68ea7
C++
tesion99/LeetCode
/cpp/74_searchMatrix.cpp
UTF-8
2,675
4.09375
4
[]
no_license
/* 编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性: 每行中的整数从左到右按升序排列。 每行的第一个整数大于前一行的最后一个整数。 示例 1: 输入: matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target = 3 输出: true 示例 2: 输入: matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target = 13 输出: false 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/search-a-2d-matrix */ // 先确定对应的行, 然后对该行进行二分查找 class Solution { public: bool searchMatrix(vector<vector<int>>& matrix, int target) { if (matrix.empty() || matrix[0].empty()) { return false; } int rows = matrix.size() - 1; int columns = matrix[0].size() - 1; for (int i = 0; i <= rows; ++i) { if (target > matrix[i][columns]) { continue; } int left = 0, right = columns; while (left <= right) { int mid = (left + right) / 2; if (matrix[i][mid] == target) { return true; } else if (matrix[i][mid] > target) { right = mid - 1; } else { left = mid + 1; } } break; } return false; } }; // 先对行进行二分查找,使用该行最大值比对target,确定target大致的行 // 在对特定行,进行二分查找 // 双重查找后,效率进一步提高 class Solution { public: bool searchMatrix(vector<vector<int>>& matrix, int target) { if (matrix.empty() || matrix[0].empty()) { return false; } int rows = matrix.size() - 1; int columns = matrix[0].size() - 1; int lr = 0, rr = rows; while (lr <= rr) { int mr = (lr + rr) / 2; if (target > matrix[mr][columns]) { lr = mr + 1; } else if (target < matrix[mr][columns]){ rr = mr - 1; } else { return true; } } if (lr > rows) { return false; } int left = 0, right = columns; while (left <= right) { int mid = (left + right) / 2; if (matrix[lr][mid] == target) { return true; } else if (matrix[lr][mid] > target) { right = mid - 1; } else { left = mid + 1; } } return false; } };
true
1c9d2a488433d3615f067e1ee86b22720af56c92
C++
ldaIas/MatrixCalculator
/test.cpp
UTF-8
3,114
3.765625
4
[]
no_license
#include <vector> #include <stdio.h> #include "matrix.h" #include <string> using namespace std; // Print a failure message void print_fail(string msg){ printf("\033[0;31m%s\033[0m\n", msg.c_str()); } // Print a success message void print_success(string msg){ printf("\033[0;32m%s\033[0m\n", msg.c_str()); } // Print the current test case void print_test(string msg){ printf("\033[0;33m%s\033[0m\n", msg.c_str()); } // Test 1: Create an empty matrix int test_empty_matrix(){ print_test("Test 1: Create empty matrix"); Matrix A; int *size_of_array = A.get_matrix_size(); if(size_of_array[0] != 0 || size_of_array[1] != 0){ string msg = "Expected: [0][0]\nActual: [" + to_string(size_of_array[0]) + "][" + to_string(size_of_array[1]) + "]"; print_fail(msg); return -1; } string msg = "Expected: [0][0]\nActual: [" + to_string(size_of_array[0]) + "][" + to_string(size_of_array[1]) + "]"; print_success(msg); printf("Matrix:\n"); A.print_matrix(); return 0; } //Test 2: Create a sized empty matrix int test_empty_sized_matrix() { print_test("Test 2: Create a sized but empty matrix"); Matrix A(3,4); int *size_of_array = A.get_matrix_size(); if(size_of_array[0] != 3 || size_of_array[1] != 4){ string msg = "Expected: [3][4]\nActual: [" + to_string(size_of_array[0]) + "][" + to_string(size_of_array[1]) + "]"; print_fail(msg); A.print_matrix(); return -1; } string msg = "Expected: [3][4]\nActual: [" + to_string(size_of_array[0]) + "][" + to_string(size_of_array[1]) + "]"; print_success(msg); printf("Matrix:\n"); A.print_matrix(); return 0; } // Test 3: Insert a row into an already created sized empty matrix in column 1 int test_val_change(){ print_test("Test 3: Insert a row into empty but sized matrix"); Matrix A(3,4); double row1 = 1; double row2 = 2; double row3 = 3; if(A.change_value(1, 1, &row1) != 0) print_fail("Value change 1 failed"); if(A.change_value(2, 1, &row2) != 0) print_fail("Value change 2 failed"); if(A.change_value(3, 1, &row3) != 0) print_fail("Value change 3 failed"); vector<vector<double*>> mat = A.get_matrix(); if(*mat.at(0).at(0) == 1 && *mat.at(1).at(0) == 2 && *mat.at(2).at(0) == 3){ print_success("Values changed succesfully"); A.print_matrix(); return 0; } else{ print_fail("Values not changed successfully"); A.print_matrix(); return -1; } } int main(){ // Test empty matrix creation if(test_empty_matrix() != 0){ print_fail("Test 1 failed\n"); } else{ print_success("Test 1 passed\n"); } // Test sized matrix creation if(test_empty_sized_matrix() != 0){ print_fail("Test 2 failed\n"); } else{ print_success("Test 2 passed\n"); } // Test vector insertion if(test_val_change() != 0){ print_fail("Test 3 failed\n"); } else{ print_success("Test 3 passed\n"); } return 0; }
true
541115f1f07a65dfd4d378dee31a6269deac314e
C++
bcaso/data_structure
/1_SqList/main.cpp
UTF-8
6,299
3.671875
4
[]
no_license
/* * 动态分配的顺序表 * */ #include <iostream> using namespace std; #define InitSize 10 //定义线性表的最大长度 typedef struct SqList{ int* data; // Clion 查看动态数组 (int(*)[10])L.data int MaxSize; int length; }DynamicList; //初始化 void Init(DynamicList& L) { L.data = (int*)malloc(InitSize * sizeof (int)); //判断是否分配成功 if (!L.data) {//如果 !L->elem 为真(为空),执行下面代码 cout << "线性表内存分配失败!退出程序。\n" << endl; exit(1);//函数异常退出,返回给操作系统1 } L.length = 0; L.MaxSize = InitSize; } // 销毁 bool DestroyList(DynamicList &L){ free(L.data); L.length = 0; L.MaxSize = 0; L.data = nullptr; // C++ 11 if(!L.data)return true; return false; } // 增长 void IncreaseList(DynamicList& L, int n){ int* p = L.data; // 存储原有数据 L.data = (int*)malloc(sizeof(int)*(L.MaxSize + n)); // L.data重新分配内存 for(int i = 0; i < L.length; i++){ // 迁移旧数据到新地址 L.data[i] = p[i]; } L.MaxSize += n; free(p); } //插入元素, 在表中第i个位置上插入x bool Insert(DynamicList& L, int i, int x) { if(i < 1 || i > L.length + 1){ cout << "位序有误" << endl; return false; } // 增加两倍的长度 if(L.length >= L.MaxSize){ IncreaseList(L, L.MaxSize); } for (int j = L.length; j >= i; --j) { L.data[j] = L.data[j-1]; } L.data[i-1] = x; L.length++; return true; } // 删除 bool DeleteElemByOrder(DynamicList& L, int i, int& element){ if(i < 1 || i > L.length + 1){ cout << "位序有误" << endl; return false; } element = L.data[i-1]; // 要删除第i个元素,第i个元素(位序)对应的下标为 i - 1 for (int j = i; j < L.length; ++j) { L.data[j-1] = L.data[j]; } L.length--; return true; } // 查找 // 查找位序为i的元素 int FindElementByOrder(DynamicList& L, int i){ return L.data[i-1]; } // 查找值为value的元素的位序 int FindElementByValue(DynamicList& L, int value){ for (int i = 0; i < L.length; ++i) { if(L.data[i] == value)return i+1; } cout << "未找到值为 " << value << "的元素" << endl; return -1; // 未找到 } //遍历操作 void PrintList(DynamicList L) { cout << "L: "; for (int i = 0; i < L.length; i++) { cout << L.data[i] << " "; } cout << endl; } // 判空 bool IsEmpty(DynamicList& L){ if(!L.length){ return true; } return false; } bool Delete_same(DynamicList& L){ if(L.length == 0) return false; int i, // 第一个不相同的元素 j; // 工作指针 // 用后面不相同的元素L.dta[j]覆盖前面的L.data[i] for (i = 0, j = 1; j < L.length; ++j) { if(L.data[i] != L.data[j]){ // 查找下一个(L.data[j])与上个元素(L.data[i])不同的元素 /* * L.data[j] 与 L.data[i] 相同 * L.data[j+1] 与 L.data[i] 相同 * L.data[j+2] 与 L.data[i] 相同 * L.data[j+n] 与 L.data[i] 不同 * 将 L.data[j+n] 前移到 L.data[i] 的下一个, 即 L.data[i+1] = L.data[j+n] * */ i++; L.data[i] = L.data[j];// 找到后,将元素L.data[j]前移 } } L.length = i + 1; return true; } int main() { DynamicList L; Init(L); // 判空 if(IsEmpty(L)) {cout << "L是空表" << endl;} else{cout << "L非空" << endl;} cout << "表L长度为 " << L.length << ", 表L大小为 " << L.MaxSize << endl; // 插入元素 cout << "-----------插入值1----------" << endl; if(Insert(L, 1, 1)){ cout << "插入成功" << endl; } PrintList(L); cout << "表L长度为 " << L.length << ", 表L大小为 " << L.MaxSize << endl; // 循环插入9个元素 cout << "----------插入9个元素--------------" << endl; for (int i = 1; i < 10; ++i) { Insert(L, i+1, i); // i是位序 } PrintList(L); //L: 1 1 2 3 4 5 6 7 8 9 // TODO ERROR 判断是否自动增长 cout << "表L长度为 " << L.length << ", 表L大小为 " << L.MaxSize << endl; // 插入第 11 个元素,11 > MaxSize, 自动增长,不会报错 cout << "--------------插入第11个元素 11, 会执行IncreaseList()使表大小自增------------" << endl; Insert(L, 11, 11); PrintList(L); //L: 1 1 2 3 4 5 6 7 8 9 cout << "表L长度为 " << L.length << ", 表L大小为 " << L.MaxSize << endl; cout << "------------------------------------------------------------------" << endl; // 查找值5的位序 cout << "值为5的位序是:" << FindElementByValue(L, 5) << endl; // 查找位序6的值 cout << "位序为6的元素的值为:" << FindElementByOrder(L, 6) << endl; // 删除位序为6的元素 int value; DeleteElemByOrder(L, 6, value); cout << "位序为6的为" << value << ", 已从表中删除." << endl; PrintList(L); cout << "---------Delete same--------" << endl; Delete_same(L); PrintList(L); // 销毁表 cout << "--------------DestroyList L-------------" << endl; DestroyList(L); cout << "表是否为空: " << IsEmpty(L) << endl; cout << "表L长度为 " << L.length << ", 表L大小为 " << L.MaxSize << endl; return 0; } /* L是空表 表L长度为 0, 表L大小为 10 -----------插入值1---------- 插入成功 L: 1 表L长度为 1, 表L大小为 10 ----------插入9个元素-------------- L: 1 1 2 3 4 5 6 7 8 9 表L长度为 10, 表L大小为 10 --------------插入第11个元素 11, 会执行IncreaseList()使表大小自增------------ L: 1 1 2 3 4 5 6 7 8 9 11 表L长度为 11, 表L大小为 20 ------------------------------------------------------------------ 值为5的位序是:6 位序为6的元素的值为:5 位序为6的为5, 已从表中删除. L: 1 1 2 3 4 6 7 8 9 11 ---------Delete same-------- L: 1 2 3 4 6 7 8 9 11 --------------DestroyList L------------- 表是否为空: 1 表L长度为 0, 表L大小为 0 * */
true
87d442a5841b10122f6f840818863ae20aad652b
C++
CoderDojoWarszawa/Arduino
/10_Servo/10c_Servo_lewo_prawo/10c_Servo_lewo_prawo.ino
UTF-8
634
2.875
3
[]
no_license
#include <Servo.h> // GND (czarny, ciemnobrązowy) - GND // +5V Zasilanie (czerwony) - +5V // Sygnał sterujący (żółty/pomarańczowy) - 9 Servo serwo; //Tworzymy instancję o nazwie serwo int pozycja = 0; //Aktualna pozycja serwa 0-180 int zmiana = 1; //Co ile ma się zmieniać pozycja serwa? void setup() { serwo.attach(9); //Serwomechanizm podłączony do pin 9 serwo.write(pozycja); //Ustawienie wychylenia na 0 stopni delay(1000); } void loop() { if (pozycja > 179) { zmiana = -1; } if (pozycja < 1) { zmiana = 1; } pozycja = pozycja + zmiana; serwo.write(pozycja); delay(50); }
true
69e07e01c8b6889b0ed3001e7120d30fca145063
C++
dradgun/firstweb
/k/chairman.cpp
UTF-8
1,684
3.171875
3
[]
no_license
#include <iostream> #include <iomanip> #include <stdlib.h> using namespace std; void randVotes(/* float votes,int chairmanAmount */); int main() { int width = 7,count; int chairmanNumber; float votesNumber,notVotes; int chairmanVotes[] = {}; const float numberOfRightStd = 500; cout << "Enter number student chairman : "; cin >> chairmanNumber; chairmanVotes[chairmanNumber]; cout << "Number of right student : " << numberOfRightStd << endl; srand((unsigned int)time(0)); votesNumber = (rand() % 500); cout << "Number of Votes : "; votesNumber = ((votesNumber * 100)/numberOfRightStd); cout << "= " << fixed << setprecision(1) << votesNumber << "%" << endl; cout << "Number of not Votes : "; notVotes = numberOfRightStd - votesNumber; notVotes = ((notVotes * 100)/numberOfRightStd); cout << "= " << fixed << setprecision(1) << notVotes << "%" << endl; cout << "Result of election chairman" << endl; cout << "---------------------------" << endl; cout << "No.\tVotes\tPercent (%)" << endl; cout << "---------------------------" << endl; cout << "---------------------------" << endl; randVotes(); return 0; } void randVotes(/* float votes,int chairmanAmount */) { int votesNumber = 420; int random1; int chairmanVotes[100] = {}; for (int i = 0; i <= 100; i++) { random1 = (rand() % votesNumber); chairmanVotes[i] = random1; votesNumber -= random1; } cout << chairmanVotes[0] << endl; cout << chairmanVotes[1] << endl; cout << chairmanVotes[2] << endl; cout << chairmanVotes[3] << endl; }
true
3361c20e84fe5893eacb57637e2a13ebcbb878fb
C++
duyanwei/leetcode
/204-CountPrimes/solution.cpp
UTF-8
1,759
3.796875
4
[]
no_license
/** * @file solution.cpp * @author duyanwei (duyanwei0702@gmail.com) * @brief * @version 0.1 * @date 2020-03-05 * * @copyright Copyright (c) 2020 * */ #include <iostream> #include <vector> class Solution { public: int countPrimes(int n) { int m = n - 1; int num = 0; while (m > 2) { int i = 2; for (; i * i < m; i++) { // loop from 2 to sqrt(n), not n / 2 !!! if (m % i == 0) { break; } } if (i * i > m) { num++; } m--; } if (m == 2) { num++; } return num; } }; /** * @brief * * @ref: https://www.cnblogs.com/grandyang/p/4462810.html * 我们从2开始遍历到根号n,先找到第一个质数2,然后将其所有的倍数全部标记出来, * 然后到下一个质数3,标记其所有倍数,一次类推,直到根号n,此时数组中未被标记的数字就是质数。 * 我们需要一个 n-1 长度的 bool 型数组来记录每个数字是否被标记,长度为 n-1 * 的原因是题目说是小于n的质数个数,并不包括n。然后来实现埃拉托斯特尼筛法,难度并不是很大, * 代码如下所示: */ class Solution2 { public: int countPrimes(int n) { int num = 0; std::vector<int> primes(n, true); for (int i = 2; i < n; i++) { if (!primes.at(i)) { continue; } num++; for (int j = 2; i * j < n; j++) { primes.at(i * j) = false; } } return num; } }; int main() { Solution2 s; std::cout << s.countPrimes(499979) << std::endl; return 0; }
true
35d2fe01fff575f1928a3ed117dd334b73a529b9
C++
marouaneaba/TP-C-graphique-GTK-MVC-..-
/TP3/src/Produit.cpp
UTF-8
400
3.28125
3
[]
no_license
#include "Produit.hpp" #include <iostream> Produit::Produit(int id,const std::string& description):_id(id),_description(description){ } int Produit::getId()const{ return _id; } const std::string& Produit::getDescription() const{ return _description; } void Produit::afficherProduit() const{ std::cout<<"Produit dont l'id N° "<<_id<<" et la description est : "<<_description<<std::endl; }
true
35dc91e1178c2cb7757dfc0c2516a6e2f343c58c
C++
vanbru80/scratch
/codecon/2016Quals/accepted/wrapit.cpp
UTF-8
930
3.203125
3
[]
no_license
#include <iostream> #include <string> #include <sstream> #include <algorithm> #include <climits> using namespace std; void wrapit(string &s, const int len) { int start = 0; int last = -1; for (int i = 0; i < s.size(); ++i) { int nchars = (i-start+1); if (s[i] == '~') { cout << s.substr(start, nchars-1) << endl; start = i+1; last = -1; continue; } if (s[i] == ' ') last = i; if (nchars > len) { if (last != -1) { cout << s.substr(start, last-start) << endl; start = last+1; last = -1; } } } cout << s.substr(start); } int main() { int len = 0; stringstream ss; string s, s1; getline(cin, s1); ss << s1; ss >> len; getline(cin, s); wrapit(s, len); return 0; }
true
75b8ebd4be86eb2a9592f1f57d9da201046d4ca0
C++
Bhavyaratra/Hackerrank-practice
/Algorithm/Implementation/Birthday_chocolate.cpp
UTF-8
661
2.640625
3
[]
no_license
#include <iostream> #include <vector> using namespace std; int main() { signed int n,A[100],d,m,sum=0,count=0; vector<int> v; cin>>n; for(int i=0;i<n;i++) { cin>>A[i]; } cin>>d>>m; for(int k = 0;k<n;k++) { for(int i = k ;i<n;i++) { for(int j=k,s=0;j<=i;j++,s++) { v.push_back(A[j]); sum=sum+A[j]; } if(v.size()==m && sum==d) { count++; sum=0; v.clear(); } else { v.clear(); sum=0; } } } cout<<count; }
true
ec3ed94eed9e6a040e57ed8ab0ab66692d5a4dfc
C++
lucashuati/maratona
/URI/1063.cpp
UTF-8
1,138
2.65625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main(){ int n; while(cin >> n,n){ vector<char> ff; queue <char> fi; stack <char> p; for(int i = 0; i < n; i++){ char c,l; cin >> c; fi.push(c); //printf("()%c()",c); } for(int i = 0; i < n; i++){ char c; cin >> c; //printf("()%c()",c); ff.push_back(c); } for(int i = 0; i < ff.size(); i++){ //printf("%c -> ",ff[i]); if(!p.empty() && p.top() == ff[i]){ p.pop(); //printf("desempilhei %c\n",ff[i]); printf("R"); }else if(!fi.empty()){ bool f = true; while(1){ if(fi.empty()){ f = false; break; } //printf("%c ",fi.front()); if(fi.front() != ff[i]){ //printf("empilhei %c\n",fi.front()); p.push(fi.front()); printf("I"); fi.pop(); }else{ // printf("empilhei %c\n",fi.front()); // printf("desempilhei %c\n",fi.front()); printf("IR"); fi.pop(); break; } } if(!f){ break; } }else{ break; } } if(p.size() != 0){ printf(" Impossible\n"); }else{ printf("\n"); } } return 0; }
true
aab5c8ff674724d7cea35db55827d08b09d90b79
C++
Tavlin/C-_lib_num_int
/main.cpp
UTF-8
4,004
2.75
3
[]
no_license
#include <math.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include "integrals.h" #include <time.h> //definition of size_of_list template <class T, const unsigned int size> const unsigned int size_of_array(T(&)[size]) { return size; } int main (int argc, char *argv[]) { printf("I am at the start of the main\n"); char* function_name_list[4] = {"Gaussian", "x*cos²(2*pi*x²)", "exp^(-x²)", "1/sqrt(x)"}; char* integral_name_list[7] = {"Left Riemann Sum", "Right Riemann Sum", "Trapezodial Rule", "Simpson's Rule", "Trapezodial Rule with semi adaptive stepsize", "Midpoint Rule with semiadatipve stepsize", "Midpoint Rule with semiadatipve stepsize and open bondary"}; double (*function_list[4])(double x, FunctionParams params) = {gaussian, strange_cos, exp_minus_x_sq, rev_sqrt}; double (* integral_list[7])(InitialData A, FunctionParams params, double(*func)(double, FunctionParams), double eps) = {left_riemann_sum, right_riemann_sum, trapezodial_integral, simpson_integral, trapezodial_integral_sas, midpoint_int, midpoint_int_to_inf}; double mus[1] = {0}; double sigmas[1] = {1}; double Ns[2] = {100,10000}; double lower_bounds[4] = {-10,-5,-2,-1}; //allways paired with upper bound double upper_bounds[4] = {0,5,2,9}; double error = 0.0000001; //initialise a list of initial data unsigned int init_data_list_lenght = (size_of_array(Ns) * size_of_array(lower_bounds)); InitialData init_data_list[init_data_list_lenght]; int num_1 = 0; for(int i = 0; i < size_of_array(Ns); i++) { for(int j = 0; j < size_of_array(lower_bounds); j++) { InitialData A; InitialData* pA; pA = &A; *pA = initialdata_init(Ns[i], lower_bounds[j], upper_bounds[j], error); init_data_list[num_1] = *pA; num_1++; } } //initialise a list of function parameters //expecting that leght of different parameterlists is equal for all parameters FunctionParams function_params_list[size_of_array(mus)]; for(int k = 0; k < size_of_array(mus); k++) { FunctionParams A; FunctionParams* pA; pA = &A; *pA = g_p_init(mus[k], sigmas[k]); function_params_list[k] = *pA; } unsigned int test_call_list_lenght = size_of_array(function_name_list) * init_data_list_lenght * size_of_array(mus); TestCall test_call_list[test_call_list_lenght]; // big loop to generate a big variety of possible test calls TestCall TC; TestCall* pTC; pTC = &TC; int num_2 = 0; for(int l = 0; l < size_of_array(function_name_list); l++) { for(int m = 0; m < init_data_list_lenght; m++) { for(int n = 0; n < size_of_array(mus); n++) { *pTC = test_call_init(function_name_list[l], init_data_list[m], function_params_list[n], function_list[l]); test_call_list[num_2] = *pTC; num_2++; } } } int check = atoi(argv[1]); if(check == 1) { for(int o = 0; o < test_call_list_lenght; o++) { for(int p = 0; p < (size_of_array(integral_list) - 1); p++) { printerplus(test_call_list[o], integral_name_list[p], integral_list[p]); } } } else if(check == 2) { printf("I am right after the check == 2\n"); for(int o = 0; o < test_call_list_lenght; o++) { for(int p = 6; p < (size_of_array(integral_list)); p++) { printerplus(test_call_list[o], integral_name_list[p], integral_list[p]); } } } else if(check == 3) { // call for the Monte Carlo Integral double integral_value = 0; for(int x = 0; x < init_data_list_lenght; x++) { printf("a = %lf\nb = %lf\nN = %lf\n", init_data_list[x].initial, init_data_list[x].final_val, init_data_list[x].stepsize); for(int y = 0; y < size_of_array(function_name_list); y++) { /*if(y == 1) { y++; }*/ integral_value = monte_carlo_integral(init_data_list[x], function_params_list[0],function_list[y], 0.01); printf("Monte Carlo Integral for %s = %lf\n\n", function_name_list[y], integral_value); } } } return 0; }
true
e6192d96a989b9a4178691d3138bc7362f4291d9
C++
CodePractice14/008_QtWidgets_Beginners_CPP
/qtwb-08-05_QStackedWidget/dialog.cpp
UTF-8
2,015
2.546875
3
[]
no_license
#include "dialog.h" #include "ui_dialog.h" Dialog::Dialog(QWidget *parent) : QDialog(parent) , ui(new Ui::Dialog) { ui->setupUi(this); init(); } Dialog::~Dialog() { delete ui; } void Dialog::on_buttonBox_accepted() { QMessageBox::information(this,"Hello",ui->txtFirst->text()); accept(); } void Dialog::on_buttonBox_rejected() { reject(); } void Dialog::next() { int index = ui->stackedWidget->currentIndex(); index++; if(index >= ui->stackedWidget->count()) index = ui->stackedWidget->count() -1; ui->stackedWidget->setCurrentIndex(index); checkButtons(); } void Dialog::back() { int index = ui->stackedWidget->currentIndex(); index--; if(index <= 0) index = 0; ui->stackedWidget->setCurrentIndex(index); checkButtons(); } void Dialog::init() { btnNext = new QPushButton("Next", this); btnBack = new QPushButton("Back", this); connect(btnNext,&QPushButton::clicked,this,&Dialog::next); connect(btnBack,&QPushButton::clicked,this,&Dialog::back); ui->buttonBox->addButton(btnBack, QDialogButtonBox::ButtonRole::ActionRole); ui->buttonBox->addButton(btnNext, QDialogButtonBox::ButtonRole::ActionRole); QWidget *widget = new QWidget(this); QLabel *lblNothing = new QLabel("Add your controls here!", this); QHBoxLayout *layout = new QHBoxLayout(this); layout->addWidget(lblNothing); widget->setLayout(layout); ui->stackedWidget->addWidget(widget); ui->stackedWidget->setCurrentIndex(0); checkButtons(); } void Dialog::checkButtons() { //First Page if(ui->stackedWidget->currentIndex() == 0) { btnBack->setEnabled(false); btnNext->setEnabled(true); return; } //Last Page if(ui->stackedWidget->currentIndex() >= ui->stackedWidget->count() -1) { btnBack->setEnabled(true); btnNext->setEnabled(false); return; } //Others btnBack->setEnabled(true); btnNext->setEnabled(true); }
true
9d6a04d38f403321a2cbe01b6a5eba96cf5cc700
C++
alexandraback/datacollection
/solutions_5640146288377856_0/C++/jibu11/A.cpp
UTF-8
448
2.6875
3
[]
no_license
#include <stdio.h> #include <string.h> int dp[20][20]; int n, c, r; int calc(int c, int n) { if(dp[c][n]) return dp[c][n]; if(c >= n * 2) return dp[c][n] = calc(c - n, n) + 1; if(c <= n + 1) return dp[c][n] = c; return dp[c][n] = calc(c - 1, n); } int main() { int k, l; scanf("%d", &k); memset(dp, 0, sizeof dp); for(l = 1; l <= k; l++) { scanf("%d%d%d", &r, &c, &n); printf("Case #%d: %d\n", l, calc(c, n)); } return 0; }
true
873c6491d8ecbe31a06bf69241ff56de678a52f9
C++
mehamasum/competitive-programming
/Data structure/BST/bst_pointer_to_pointer.cpp
UTF-8
3,803
3.3125
3
[]
no_license
#include <iostream> #include <cstdlib> using namespace std; #define FREOPEN freopen("input.txt","r",stdin); // NODE DEFINITION struct bst_node { int key; struct bst_node * left, * right ; }; typedef struct bst_node node; // FUNCTION FOR SEARCHING A KEY bool search(node** root, int num) { node *q ; q = *root ; while ( q != NULL ) { /* found */ if ( q -> key == num ) return true ; if ( q -> key > num ) q = q -> left ; else q = q -> right ; } return false; } // FUNCTIONS FOR TRAVERSING BST void in_order(node *root) { if(root==0) return; in_order(root->left); printf("%d ", root->key); in_order(root->right); } void pre_order(node *root) { if(root==0) return; printf("%d ", root->key); pre_order(root->left); pre_order(root->right); } void post_order(node *root) { if(root==0) return; post_order(root->left); post_order(root->right); printf("%d ", root->key); } //FUNCTION FOR INSERTING A NODE void insert ( node **root, int num ) { node* q= *root; if ( *root == NULL ) { *root = (node *)malloc ( sizeof ( node ) ) ; ( *root )-> left = 0 ; ( *root ) -> key = num ; ( *root ) -> right = 0 ; } else { if ( num < ( *root ) -> key ) insert ( &( ( *root ) -> left ), num ) ; else if( num > ( *root ) -> key ) insert ( &( ( *root ) -> right ), num ) ; } } bool search ( node **root, int num, node **par, node **x ) { node *q ; q = *root ; *par = NULL ; while ( q != NULL ) { /* found */ if ( q -> key == num ) { *x = q ; return true ; } *par = q ; if ( q -> key > num ) q = q -> left ; else q = q -> right ; } return false; } void delNode( node **root, int num ) { /* if tree is empty */ if ( *root == NULL ) { printf ( "\nTree is empty" ) ; return ; } node *parent, *x ; parent = x = 0 ; node *xsucc=0; if ( search ( root, num, &parent, &x) == false ) { printf ( "\nkey to be deleted, not found" ) ; return ; } /* two children */ if ( x -> left != NULL && x -> right != NULL ) { parent = x ; xsucc = x -> right ; //take the right subtree while ( xsucc -> left != NULL ) { parent = xsucc ; xsucc = xsucc -> left ; //go left } x -> key = xsucc -> key ; x = xsucc ; } /* no child */ if ( x -> left == NULL && x -> right == NULL ) { if ( parent -> right == x ) parent -> right = NULL ; else parent -> left = NULL ; free ( x ) ; return ; } /* only right child */ if ( x -> left == NULL && x -> right != NULL ) { if ( parent -> left == x ) parent -> left = x -> right ; else parent -> right = x -> right ; free ( x ) ; return ; } /* only left child */ if ( x -> left != NULL && x -> right == NULL ) { if ( parent -> left == x ) parent -> left = x -> left ; else parent -> right = x -> left ; free ( x ) ; return ; } } int main() { FREOPEN; node *root = 0; cout<<"1 to insert, 2 to delete, 3 to search\n4 for inorder, 4 for preorder, 6 for postorder traversal\n0 to exit"<<endl; while(1) { int n; cin>>n; switch(n) { case(1): int m; cin>>m; if(root==0) insert(&root, m); else insert(&root, m); break; case(2): cin>>m; delNode(&root,m); break; case(3): cin>>m; if(search(&root,m)) cout<<"Key found"<<endl; else cout<<"Key not found"<<endl; break; case(4): in_order(root); cout<<endl; break; case(5): pre_order(root); cout<<endl; break; case(6): post_order(root); cout<<endl; break; case(0): return 0; } } }
true
bb7a765135ba6a1f96ce78c42d56604dc78c7009
C++
zlubsen/Nova-platform
/src/actuators/NovaServo.cpp
UTF-8
1,485
3.109375
3
[]
no_license
#include <Arduino.h> #include "NovaServo.h" NovaServo::NovaServo(int pin) : NovaServo(pin, 0, 180) { } NovaServo::NovaServo(int pin, int min, int max) { _pin = pin; setAllowedRange(min, max); } void NovaServo::setAllowedRange(int min, int max) { _min = min; _max = max; } int NovaServo::getMinimum() { return _min; } int NovaServo::getMaximum() { return _max; } int NovaServo::getMiddle() { return ( ( _max - _min ) / 2 ) + _min; } void NovaServo::goToMinimum() { setDegree(_min); } void NovaServo::goToMaximum() { setDegree(_max); } void NovaServo::goToMiddle() { setDegree(getMiddle()); } void NovaServo::setDegree(int degree) { if(degree < _min) _servo.write(_min); else if(degree > _max) _servo.write(_max); else _servo.write(degree); } void NovaServo::setDegreeSmooth(int degree) { const int step_size = 5; // TODO make configuration item int current_degree = getDegree(); int diff = current_degree - degree; diff = abs(diff); int no_of_steps = diff / step_size; for(int steps = no_of_steps; steps > 0; steps--) { if(current_degree < degree) current_degree += step_size; else current_degree -= step_size; setDegree(current_degree); delay(75); // TODO make configuration item } goToMiddle(); } int NovaServo::getDegree() { return _servo.read(); } void NovaServo::attach() { _servo.attach(_pin); } void NovaServo::detach() { setDegreeSmooth(getMiddle()); _servo.detach(); }
true
a2b523eaa5ad7fff83ef4f16c6e114eb2faa98cc
C++
foomango/Career
/sort/insertion_sort.cc
UTF-8
1,640
3.296875
3
[]
no_license
/* * ===================================================================================== * * Filename: insertion_sort.cc * * Description: insertion sort * * Version: 1.0 * Created: 04/10/2013 10:21:56 AM * Revision: none * Compiler: g++ * * Author: WangFengwei (mn), foomango@gmail.com * Company: HUAZHONG UNIVERSITY OF SCIENCE AND TECHNOLOGY * * ===================================================================================== */ #include <iostream> #include <stdio.h> #include <stdlib.h> #include<time.h> void print_array(int array[], int len); void insertion_sort(int array[], int first, int last) { if (array == NULL || first < 0) { return; } for (int i = first + 1; i <= last; i++) { int temp = array[i]; int j = 0; for (j = i - 1; j >= first && array[j] > temp; j--) { array[j + 1] = array[j]; } array[j + 1] = temp; } } void generate_array(int array[], int len) { int seed = time(NULL); srand(seed); for (int i = 0; i < len; i++) { array[i] = random() % (10 * len); } } void print_array(int array[], int len) { for (int i = 0; i < len; i++) { if (i % 10 == 0) { printf("\n"); } printf("\t%d", array[i]); } printf("\n"); } int main(int argc, char *argv[]) { const int len = 20; int array[len]; generate_array(array, len); printf("before sort:\n"); print_array(array, len); printf("after sort:\n"); insertion_sort(array, 0, len - 1); print_array(array, len); return 0; }
true
b0b96f172a2f93f53278e25e56d607c87a7108a8
C++
eriytt/helo
/EventQueue.h
UTF-8
2,543
3.453125
3
[]
no_license
#ifndef EVENTQUEUE_H #define EVENTQUEUE_H #include "Utils.h" template <typename T> class EventQueue { public: typedef unsigned int EventID; public: class Event { public: virtual void operator()(T actual_time, T event_time, EventID id) const = 0; virtual void dispose(bool handled) const {delete this;}; virtual ~Event() {} }; class LambdaEvent : public Event { protected: std::function<void(T, T, EventID)> f; public: LambdaEvent(std::function<void(T, T, EventID)> lambda) : f(lambda) {} virtual void operator()(T actual_time, T event_time, EventID id) const {f(actual_time, event_time, id);} }; protected: struct EventQueueEntry { T time; EventID id; const Event *e; EventQueueEntry(T time, EventID id, const Event *e) : time(time), id(id), e(e) {} bool operator<(const EventQueueEntry &other) const {return time < other.time;} }; protected: HeloUtils::SortedList<EventQueueEntry> queue; EventID ectr; public: EventQueue() : ectr(0) {} void advance(T until) { T etime = 0; while (etime <= until) { if (queue.empty()) break; const EventQueueEntry &e = queue.front(); if (e.time > until) break; (*e.e)(until, e.time, e.id); etime = e.time; e.e->dispose(true); queue.pop_front(); } } void advanceNoTrigger(T until) { T etime = 0; while (etime <= until) { if (queue.empty()) break; const EventQueueEntry &e = queue.front(); if (e.time > until) break; etime = e.time; e.e->dispose(false); } } EventID postEvent(T at, const Event *e) { EventID new_id = ectr++; queue.insert(EventQueueEntry(at, new_id, e)); return new_id; } EventID postEvent(T at, std::function<void(T, T, EventID)> lambda) { EventID new_id = ectr++; queue.insert(EventQueueEntry(at, new_id, new LambdaEvent(lambda))); return new_id; } bool cancelEvent(EventID id) { bool found; queue.remove_if([id, &found](const EventQueueEntry &e) { if (e.id == id) { e.e->dispose(false); return (found = true); } return false; }); return found; } }; /* Example of deriving event */ template <typename T> class PrintEvent : public EventQueue<T>::Event { protected: std::string s; public: PrintEvent(const std::string &s) : s(s) {} virtual void operator()(T actual_time, T event_time, typename EventQueue<T>::EventID id) const {std::cout << "PrintEvent triggered: " << s << std::endl ;} }; #endif // EVENTQUEUE_H
true
317bee56e3604bec088f9cc7f835072ee9decf5c
C++
yannjor/tower-defence
/src/gui/gui.cpp
UTF-8
569
3.03125
3
[]
no_license
#include "gui.hpp" Gui::Gui() { visible_ = true; } void Gui::Show() { visible_ = true; } void Gui::Hide() { visible_ = false; } void Gui::Add(const std::string& name, GuiEntry entry) { entries_.insert({name, entry}); } GuiEntry& Gui::Get(const std::string& name) { return entries_.at(name); } bool Gui::Has(const std::string& name) { return !(entries_.find(name) == entries_.end()); } void Gui::draw(sf::RenderTarget& target, sf::RenderStates states) const { if (!visible_) return; for (auto entry : entries_) { target.draw(entry.second, states); } }
true
9584c92f8cec3defddca74d422d5775461cc1042
C++
gyjhl/01-C-HelloWorld
/01 C++书写HelloWorld/4.2.2 do__while循环语句.cpp
GB18030
670
3.46875
3
[]
no_license
#include<iostream> #include<string> #include<ctime> using namespace std; /* int main() { //, ˮɻָһ3λ, ÿλϵֵ3֮͵ //do whileе3λˮɻ //1, ȴӡеλ int num = 100; do { //2, еλҵˮɻ int a = 0; int b = 0; int c = 0; a = num % 10; //ֵĸλ b = num / 10 % 10; //ֵʮλ c = num / 100; //ֵİλ if(a*a*a+b*b*b+c*c*c==num) { cout << num << endl; num++; } } while (num < 1000); system("pause"); return 0; } */
true
f3effaa50d3ceb590d30c6b4d595ee56147222bf
C++
exatamente/EstruturaDeDados
/ControleDeEstoque/headers/LDDE.h
ISO-8859-1
1,141
3.265625
3
[]
no_license
#pragma once #include "IStructure.h" #include "No.h" class LDDE { private: No* first; No* last; int n; Stock sentinela; public: LDDE(); // Deixe para o fim (deve copiar as listas) LDDE(const LDDE&); // Este operador faz a cpia da lista em caso de atribuies LDDE& operator= (const LDDE& other) { // reset the whole ldde while (Remove(0)); n = 0; // aux variable No* current = other.first; // copies the other list element by element while (current) { Insere(current->stock); current = current->next; } return *this; } bool Insere(Stock*); /* Returns the index of the first node with value == "valor", otherwise -1 */ int Busca(std::string); Stock* Get(std::string); bool Remove(int); void Print(); const Stock& operator[] (int idx) { // check if idx fits on the ldde if (idx < 0 || idx > n) return sentinela; // aux variable No* current = first; // finds the node with the corresponding index for (int i = 0; i < idx; i++) { current = current->next; } return *(current->stock); } ~LDDE(); };
true
f010b7dfdaa8eeb75c97d8c2381ee4d64cd4075e
C++
Windowline/Google-kickstart-2021
/Round_B/Bike_Tour.cpp
UTF-8
566
2.765625
3
[]
no_license
#include <iostream> #include <vector> #include <stdio.h> #include <algorithm> using namespace std; int N; int solve(vector<int>& p) { int ans = 0; for (int i = 1; i < p.size() - 1; ++i) { if (p[i] > p[i-1] && p[i] > p[i+1]) ++ans; } return ans; } int main() { int TC; scanf("%d", &TC); for (int tc = 0; tc < TC; ++tc) { scanf("%d", &N); vector<int> in = vector<int>(N); for (int i = 0; i < N; ++i) scanf("%d", &in[i]); printf("Case #%d: %d\n", tc + 1, solve(in)); } }
true
9a0c3b05b1f465744d638cb0e1a25e50a9c86348
C++
taschetto/computerGraphics
/ElNacho/ElNacho3D/Nacho.h
UTF-8
466
2.96875
3
[ "MIT" ]
permissive
#pragma once #include "Maze.h" #include "Direction.h" class Nacho { private: Maze* maze; size_t x; size_t y; size_t oldx; size_t oldy; float radius; void SetX(size_t); void SetY(size_t); public: Nacho(Maze*); virtual ~Nacho(); size_t GetX(); size_t GetY(); size_t GetOldX(); size_t GetOldY(); bool Walk(Direction); float GetRadius() { return radius; } void SetRadius(float nradius) { radius = nradius; } };
true
09b262ad22ac6de77b09ddf327aff73e32b09ea6
C++
asegura4488/Cplusplus
/struct/struct_1/src/struct.cxx
UTF-8
435
3.28125
3
[]
no_license
/************************** ***Structure in C++, First part ---Ph. D. Alejandro Segura **************************/ #include <iostream> #include <vector> #include <typeinfo> using namespace std; int main(){ struct Personaje { //it's not possible to add initial value int edad; double telefono; }Alejandro; Alejandro.edad = 29; Alejandro.telefono = 999.99999; cout << Alejandro.edad << endl; return 0; }
true
ffbbd73da7218645b17242bda667306dcf553708
C++
erikjber/plsomlib
/cpp/plsomlib/neighbourhood/GaussianNeighbourhoodFunction.h
UTF-8
1,182
3.171875
3
[ "Unlicense" ]
permissive
/** * Created by Erik Berglund on 2018-04-11. */ #ifndef CPP_GAUSSIANNEIGHBOURHOODFUNCTION_H #define CPP_GAUSSIANNEIGHBOURHOODFUNCTION_H /** * Implementation of the NeighbourhoodFunction interface that * calculates the neighbourhood scaling according to a Gaussian function. * * The neighbourhood scaling is defined so that * S = e^(-d^2/N^2) * where S is the scaling variable returned by getScaling(...), * e is the euler number, d is the distance and N is the neighbourhood size. * */ class GaussianNeighbourhoodFunction { public: /** * Calculate the scaling according to the Gaussian neighbourhood function. * The neighbourhoodSize argument is treated as a scaling variable of the * extent of the neighbourhood. * * @param distance the distance between two nodes in output space. * @param neighbourhoodSize the size of the neighbourhood, * determines how fast the scaling variable tends to zero with increasing distance. * @return a scaling variable ranging from 1 (where distance is 0) tending to 0 for increased distance. */ double getScaling(double distance, double neighbourhoodSize); }; #endif //CPP_GAUSSIANNEIGHBOURHOODFUNCTION_H
true
49f797e1089664755fab0368b0ee497d216b7701
C++
Ian95Song/DIP-Homework
/06/Network.h
UTF-8
5,233
2.703125
3
[]
no_license
/** * Copyright 2019/2020 Andreas Ley * Written for Digital Image Processing of TU Berlin * For internal use in the course only */ #ifndef NETWORK_H #define NETWORK_H #include "Tensor.h" #include <vector> #include <memory> #include <istream> #include <random> #include <ostream> namespace dip6 { class ParametrizedLayer; class Optimizer { public: Optimizer(ParametrizedLayer *layer) : m_layer(layer) { } virtual ~Optimizer() = default; virtual void performStep(float stepsize) = 0; virtual void saveSnapshot(std::ostream &stream) {} virtual void restoreSnapshot(std::istream &stream) {} protected: ParametrizedLayer *m_layer; }; class Layer { public: virtual ~Layer() = default; virtual const char *layerName() = 0; virtual void forward(const Tensor &input) = 0; virtual void backward(const Tensor &input, const Tensor &outputGradients) = 0; inline const Tensor &getLastOutput() const { return m_output; } inline const Tensor &getLastInputGradients() const { return m_inputGradients; } virtual void updateParameters(float stepsize) { } virtual void saveSnapshot(std::ostream &stream) { } virtual void restoreSnapshot(std::istream &stream) { } protected: Tensor m_output; Tensor m_inputGradients; }; class ParametrizedLayer : public Layer { public: virtual ~ParametrizedLayer() = default; virtual void updateParameters(float stepsize) override; inline std::vector<Tensor> &getParameters() { return m_parameterTensors; } inline std::vector<Tensor> &getParameterGradients() { return m_parameterGradientTensors; } inline Optimizer *getOptimizer() { return m_optimizer.get(); } virtual void saveSnapshot(std::ostream &stream) override; virtual void restoreSnapshot(std::istream &stream) override; protected: std::vector<Tensor> m_parameterTensors; std::vector<Tensor> m_parameterGradientTensors; std::unique_ptr<Optimizer> m_optimizer; void allocateGradientTensors(); }; namespace layers { class Conv : public ParametrizedLayer { public: Conv(unsigned kernelWidth, unsigned kernelHeight, unsigned inputChannels, unsigned outputChannels); virtual const char *layerName() override { return "Conv"; } template<class Optimizer, typename... Args> Conv &setOptimizer(Args&&... args) { m_optimizer.reset(new Optimizer(this, std::forward<Args>(args)...)); return *this; } Conv &initialize(std::mt19937 &rng, float kernelScale = 1.0f, float biasScale = 1e-2f); enum { PARAM_KERNEL, PARAM_BIAS, NUM_PARAMS }; protected: void resizeOutput(const Tensor &input); void resizeInputGradients(const Tensor &input, const Tensor &outputGradients); }; class Upsample : public Layer { public: Upsample(unsigned upsampleX, unsigned upsampleY); virtual const char *layerName() override { return "Upsample"; } virtual void forward(const Tensor &input) override; virtual void backward(const Tensor &input, const Tensor &outputGradients) override; protected: unsigned m_upsampleX; unsigned m_upsampleY; }; class AvgPool : public Layer { public: AvgPool(unsigned downsampleX, unsigned downsampleY); virtual const char *layerName() override { return "AvgPool"; } virtual void forward(const Tensor &input) override; virtual void backward(const Tensor &input, const Tensor &outputGradients) override; protected: unsigned m_downsampleX; unsigned m_downsampleY; }; } class Network { public: template<class LayerType, typename... Args> LayerType &appendLayer(Args&&... args) { LayerType *p; m_layer.push_back(std::unique_ptr<Layer>(p = new LayerType(std::forward<Args>(args)...))); return *p; } const Tensor &forward(const Tensor &input); void backward(const Tensor &input, const Tensor &outputGradients); void updateParameters(float stepsize); void saveSnapshot(std::ostream &stream); void restoreSnapshot(std::istream &stream); void saveSnapshot(const std::string &filename); void restoreSnapshot(const std::string &filename); void benchmarkForward(const Tensor &input); void benchmarkBackward(const Tensor &input, const Tensor &outputGradients); protected: std::vector<std::unique_ptr<Layer>> m_layer; }; class DataProvider { public: virtual ~DataProvider() = default; virtual void reset() = 0; virtual bool fetchMinibatch(Tensor &input, Tensor &desiredOutput) = 0; protected: }; class Loss { public: virtual ~Loss() = default; virtual float computeLoss(const Tensor &computedOutput, const Tensor &desiredOutput, Tensor &computedOutputGradients) = 0; protected: }; } #endif // NETWORK_H
true
dc973690bec2b9451d77abc44bcc6471c1aeda36
C++
kaba2/pastel
/pastel/math/matrix/random_matrix/random_rotation_matrix.h
UTF-8
568
2.546875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
// Description: Uniform random rotation matrix #ifndef PASTELMATH_RANDOM_ROTATION_MATRIX_H #define PASTELMATH_RANDOM_ROTATION_MATRIX_H #include "pastel/math/matrix/matrix.h" #include "pastel/math/matrix/random_matrix/random_orthogonal_matrix.h" #include "pastel/math/matrix.h" namespace Pastel { //! Returns a uniformly distributed random rotation matrix. /*! Preconditions: n >= 0 */ template <typename Real> Matrix<Real> randomRotation(integer n) { ENSURE_OP(n, >=, 0); return randomOrthogonal<Real>(n, 1); } } #endif
true
b9ab6f502f6c0303f3ed4f6a561a4f779866a115
C++
namtrungit/BigO
/green/lecture_10/lesson_8/lesson_8.cpp
UTF-8
515
3.21875
3
[]
no_license
#include<iostream> using namespace std; struct Position { int x; int y; int value; }; int main() { int n, m, k; cin >> n >> m; cin >> k; Position array[k]; for(int i=0; i<k; i++) { Position p; cin >> p.x >> p.y >> p.value; array[i] = p; } int count = 0; for(int i=0; i<k; i++) { if(array[i].value > 0) count++; } cout << count << endl; for(int i=0; i<k; i++) { if(array[i].value > 0) { cout << array[i].x << " " << array[i].y << endl; } } return 0; }
true
0b899e4a471aaab8ae1183979168bce80309c65a
C++
bgonzalo/progcomp
/bgonzalo_prob12455.cpp
UTF-8
1,208
3.140625
3
[]
no_license
//https://github.com/morris821028/UVa/blob/master/volume124/12455%20-%20Bars.cpp #include <stdio.h> int main() { int t, w, n, i, j, p;//sea t, w, n, i, j, p tipo int scanf("%d", &t);//asignar elvalor del input a t while(t--) {//mientras t sea distinto de 0. le resta 1 a t despues de ver si se cumple la condicion scanf("%d %d", &w, &n);//le asigna los valores del input a w y n repectivamente int dp[1005] = {};//sea el arreglo dp tipo int dp[0] = 1;//asigna el valor 1 al primer elemento de dp for(i = 0; i < n; i++) {//para i desde 0 hasta n (exclusive), incrementano de uno en uno scanf("%d", &p);//asignar el valor del input a p for(j = w-p; j >= 0; j--) {//para j desde w-p hasta 0, disminuyendo de uno en uno if(dp[j] && !dp[j+p])// si el j-esimo valor de dp es distinto a 0 y el j+p-esimo valor de dp es 0 dp[j+p] = 1;//se le asigna el valor 1 al j+p-esimo valor de dp } } if(dp[w])//si el w-esimo valor de dp es distinto de 0, muestra "YES" puts("YES"); else puts("NO");//sino muestra "NO" } return 0; }
true
1a47cc271ed6c8382e34fdaffcfa696a8090f5c7
C++
RahulKushwaha/Algorithms
/LeetCode/254. Factor Combinations.cc
UTF-8
1,190
2.984375
3
[]
no_license
class Solution { public: vector<vector<int>> getFactors(int n) { vector<vector<int>> output; if(n <= 1) { return output; } vector<int> factors; getFactors(2, sqrt(n), n, 1, factors, output); return output; } void getFactors(int index, int limit, int n, int currentProduct, vector<int>& factors, vector<vector<int>>& output) { if(currentProduct > n) { return; } for(int i = index; i <= limit; i ++) { if(n %(currentProduct * i) == 0) { factors.push_back(i); int factor = n/(currentProduct*i); if(factor >= i) { factors.push_back(factor); output.push_back(factors); factors.pop_back(); } getFactors(i, limit, n, currentProduct * i, factors, output); factors.pop_back(); } } } };
true
d13b5f7bdbcb737ad43ad8dd75d8e42c9a2fae19
C++
florianne1212/CPP_piscine_42
/Day_08/ex01/span.cpp
UTF-8
3,483
2.71875
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* span.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: fcoudert <fcoudert@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/12/10 13:54:36 by fcoudert #+# #+# */ /* Updated: 2020/12/11 15:37:06 by fcoudert ### ########.fr */ /* */ /* ************************************************************************** */ #include "span.hpp" Span::Span(): _n(0) { } Span::Span(unsigned int N): _n(N) { } Span::Span(Span const & copy) { this->operator= (copy); } Span::~Span() { } Span & Span::operator=(Span const & ope) { if (this != &ope) { this->_n = ope._n; this->_vector = ope._vector; } return (*this); } void Span::addNumber(int x) { if(_vector.size() < _n) _vector.push_back(x); else throw Span::NoSpaceLeft(); } void Span::addNumber(const std::vector<int> &num) { if (num.empty()) return; if ((_vector.size() + num.size()) > _n ) throw NoSpaceLeft(); _vector.insert(_vector.end(), num.begin(), num.end()); } void Span::addNumber(int begin, int end) { if (begin > end) throw ErrorArgument(); if ((_vector.size() +(end - begin)) > _n ) throw NoSpaceLeft(); for (int i = begin; i < end; i++) this->_vector.push_back(i); } int Span::shortestSpan() { if(_vector.size() <= 1) throw Span::TooFewElements(); int mini = std::abs(_vector[0] - _vector[1]) ; int diff; std::sort(_vector.begin(), _vector.end()); for (size_t i = 1; i < _vector.size(); i++) { diff = std::abs(_vector[i - 1] - _vector[i]); if (mini > diff) mini = diff; } return(mini); } int Span::longestSpan() { if(_vector.size() <= 1) throw Span::TooFewElements(); int min = *std::min_element(_vector.begin(), _vector.end()); int max = *std::max_element(_vector.begin(), _vector.end()); return(max-min); } Span::NoSpaceLeft::NoSpaceLeft() throw () {} Span::NoSpaceLeft::~NoSpaceLeft() throw () {} Span::NoSpaceLeft::NoSpaceLeft(NoSpaceLeft const & copy) { *this = copy; } Span::NoSpaceLeft & Span::NoSpaceLeft::operator=(NoSpaceLeft const & ope) { (void) ope; return *this; } const char* Span::NoSpaceLeft::what() const throw() { return "Error : no space left !"; } Span::TooFewElements::TooFewElements() throw () {} Span::TooFewElements::~TooFewElements() throw () {} Span::TooFewElements::TooFewElements(TooFewElements const & copy) { *this = copy; }; Span::TooFewElements & Span::TooFewElements::operator=(TooFewElements const & ope) { (void) ope; return *this; } const char* Span::TooFewElements::what() const throw() { return "Error :too few elements !"; }; Span::ErrorArgument::ErrorArgument() throw () {} Span::ErrorArgument::~ErrorArgument() throw () {} Span::ErrorArgument::ErrorArgument(ErrorArgument const & copy) { *this = copy; } Span::ErrorArgument & Span::ErrorArgument::operator=(ErrorArgument const & ope) { (void) ope; return *this; } const char* Span::ErrorArgument::what() const throw() { return "Error : check the argument again !"; };
true
37cccedf6a8081e6fd9ad004072780ecfe6a5eb3
C++
NoPayneNoGame/SFML_GameEngine
/src/player.cpp
UTF-8
2,616
3.078125
3
[ "MIT" ]
permissive
#include "player.h" Player::Player() : m_window(Game::instance()->getWindow()) { m_fovAngle = 90; } Player::Player(sf::RenderWindow& window, const std::string& texture, int moveSpeed, Bullet* bullet) : m_window(Game::instance()->getWindow()) { if(!m_texture.loadFromFile(texture)) std::cerr << "Player Texture not found." << std::endl; m_sprite.setTexture(m_texture, true); m_moveSpeed = moveSpeed; m_fovAngle = 90; m_sprite.setOrigin(m_sprite.getLocalBounds().width/2, m_sprite.getLocalBounds().height/2); m_bullet = bullet; //m_window = window; } Player::~Player(){ } void Player::setTexture(const std::string& texture) { if(!m_texture.loadFromFile(texture)) std::cerr << "Player Texture not found." << std::endl; m_sprite.setTexture(m_texture, true); m_sprite.setOrigin(m_sprite.getLocalBounds().width/2, m_sprite.getLocalBounds().height/2); } void Player::setSpeed(int moveSpeed) { m_moveSpeed = moveSpeed; } void Player::update() { handleMovement(); handleRotation(); //m_bullet->setPosition(getOrigin()); m_laser.setStart(getOrigin()); m_laser.setEnd(300, 0); m_laser.setColor(sf::Color::Red); if(sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) { shootBullet(); } } void Player::updateShadow() { } void Player::handleMovement() { if(sf::Keyboard::isKeyPressed(sf::Keyboard::A)) move(-m_moveSpeed, 0); if(sf::Keyboard::isKeyPressed(sf::Keyboard::D)) move(m_moveSpeed, 0); if(sf::Keyboard::isKeyPressed(sf::Keyboard::W)) move(0, -m_moveSpeed); if(sf::Keyboard::isKeyPressed(sf::Keyboard::S)) move(0, m_moveSpeed); if(sf::Keyboard::isKeyPressed(sf::Keyboard::Q)) m_fovAngle++; if(sf::Keyboard::isKeyPressed(sf::Keyboard::E)) m_fovAngle--; } void Player::handleRotation() { sf::Vector2f mousePos(sf::Mouse::getPosition().x, sf::Mouse::getPosition().y); float angle = Smath::atan2Angle(mousePos, getPosition()); setRotation(angle); } void Player::shootBullet() { std::cout << "Bang!" << std::endl; Bullet* b = new Bullet("assets/bullet.png", 2.0f); b->getSprite().setPosition(getOrigin()); m_window.draw(b->getSprite()); } void Player::draw(sf::RenderTarget& target, sf::RenderStates states) const { states.transform *= getTransform(); states.texture = &m_texture; target.draw(m_laser, states); target.draw(m_sprite, states); //target.draw(*m_bullet, states); //for(int i = 0; i < m_bullets.size(); i++) //{ //target.draw(*m_bullets[i], states); //} }
true
dd3669e14f064c0a35cc167dc1886c277b236286
C++
eientei/Radiorandom
/src/Generic/FileSystem/Create/Create.h
UTF-8
472
2.53125
3
[]
no_license
#ifndef GENERIC_FILESYSTEM_CREATE #define GENERIC_FILESYSTEM_CREATE /// @file #include <string> #include <stdio.h> #include <Generic/Generic.h> /// Filesystem checks class class Generic::FileSystem::Create { private: std::string filepath; ///< Default path test to public: Create() {} /// Usual constructor Create(std::string filepath) : filepath(filepath) {} /// Create if such file exists void CreateFile(std::string fpath = ""); }; #endif
true
65ca37d185eb00a25f9ed4cf22e17d6406e2dfb1
C++
finch185277/leetcode
/076-100/090.cpp
UTF-8
537
2.84375
3
[]
no_license
class Solution { public: // by @yuruofeifei vector<vector<int>> subsetsWithDup(vector<int> &nums) { std::sort(nums.begin(), nums.end()); std::vector<std::vector<int>> ret = {{}}; int index = 0, size = 0; for (int i = 0; i < nums.size(); i++) { index = i >= 1 && nums.at(i) == nums.at(i - 1) ? size : 0; size = ret.size(); for (int j = index; j < size; j++) { ret.at(j).push_back(nums.at(i)); ret.push_back(ret.at(j)); ret.at(j).pop_back(); } } return ret; } };
true
8cdfaa82666c3c587244c83f9754080802c40f5f
C++
renestadler/AdventOfCode-2020
/day15.cpp
UTF-8
1,071
2.984375
3
[]
no_license
#include <regex> #include <unordered_map> #include <algorithm> #include <stack> #include <map> #include "day15.h" using namespace std; long Day15::part_one(vector<int> input) { map<int, int> elems; int lastNum = 0; for (int i = 0; i < 2020; i++) { if (i < input.size()) { if (i != 0) elems[lastNum] = i; lastNum = input[i]; } else { if (elems.count(lastNum) == 0) { elems[lastNum] = i; lastNum = 0; } else { auto elem = elems.find(lastNum); int temp = (i)-elem->second; elems[lastNum] = i; lastNum = temp; } } } return lastNum; } long Day15::part_two(vector<int> input) { unordered_map<int, int> elems; int lastNum = 0; for (int i = 0; i < input.size(); i++) { if (i != 0) elems[lastNum] = i; lastNum = input[i]; } for (int i = input.size(); i < 30000000; i++) { if (elems.find(lastNum) == elems.end()) { elems[lastNum] = i; lastNum = 0; } else { auto elem = elems.find(lastNum); int temp = (i)-elem->second; elems[lastNum] = i; lastNum = temp; } } return lastNum; }
true
d4dd972cd9e9084d7eda684dcf91c1aea9afc14c
C++
Nouser/AnimatronicEarl
/Earl_Arduino_Test.ino
UTF-8
2,484
3.171875
3
[]
no_license
#include <Servo.h> Servo leftShoulder; int lsPos = 25; Servo rightShoulder; int rsPos =0; Servo leftElbow; int lePos =0; Servo rightElbow; int rePos =0; Servo leftHand; int lhPos =0; Servo rightHand; int rhPos =0; int ledBasicRed = 9; int ledBasicGreen = 8; int ledAdvancedGreen = 10; int ledAdvancedRed = 11; boolean startingMotion; void setup() { //Set all the pins as output except the sensor. It's input. for(int i=0;i<16;i++) pinMode(i, OUTPUT); pinMode(1, INPUT); //Attach servos to pins leftShoulder.attach(7); rightShoulder.attach(6); leftElbow.attach(5); rightElbow.attach(4); leftHand.attach(3); rightHand.attach(2); //Write the appropriate positions for the shoulders and elbows leftShoulder.write(lsPos); rightShoulder.write(rsPos); leftElbow.write(lePos); rightElbow.write(rePos); //Start it up. Serial.begin(9600); Serial.print("y"); digitalWrite(ledBasicRed, HIGH); digitalWrite(ledAdvancedRed, HIGH); } void loop() {/* if( Serial.available()) { if(startingMotion==false) { char ch = Serial.read(); switch(ch) { case 'z': Serial.print("x"); break; case '1': //Move shoulder basically opposite of where it is. leftShoulder.write(lsPos+145); delay(2500); //Move it back. leftShoulder.write(lsPos); digitalWrite(7, HIGH); break; case '2': break; case '3': break; case '4': break; case '5': break; case '6': break; } } else { //Put movement for motion sesnor byte senseMotion = LOW; senseMotion = digitalRead(1); if(senseMotion==HIGH) { startingMotion = false; //Do movement for when he yells "GIMME A HAND!" Serial.print("y"); } } } */ moveArms(); } void ledTurnOnForWhat() { digitalWrite(ledBasicRed, LOW); digitalWrite(ledAdvancedRed, LOW); digitalWrite(ledBasicGreen, HIGH); digitalWrite(ledBasicGreen, HIGH); } void moveArms() { //Move the shoulders as the biggest movement. lsPos+=5; leftShoulder.write(lsPos); rsPos-=5; rightShoulder.write(rsPos); //Then move the elbows a bit less lePos+=2; leftElbow.write(lePos); rsPos-=2; rightElbow.write(rePos); }
true
d17f5227341d79cf22b7c14b48d162c073672258
C++
sebkrueger/ArduinoStairways
/examples/n01_pwm.cpp
UTF-8
3,284
3.578125
4
[]
no_license
/* n01_pwm Use a button on port 2 to trigger LED feade in on 3 Ports (9-11) in a row The circuit: LEDs attached from pin 9-11 to ground pushbutton attached from pin 2 to +5V 10K resistor attached from pin 2 to ground created 12 December 2015 by Sebastian Krüger This example code is in the public domain. */ // Constants for pin numbers const int buttonPin = 2; // the number of the pushbutton pin const int ledPins[] = {9, 10, 11}; // the LED pin with pwd const int pinCount = 3; // Count of Pin Array // Variables for button and LED state int pin = 0; // Index var int ledState = 0; // start with dark LEDs int buttonState; // the current reading from the input pin int lastButtonState = LOW; // the previous reading from the input pin // the following variables are long's because the time, measured in miliseconds, // will quickly become a bigger number than can be stored in an int. unsigned long lastDebounceTime = 0; // the last time the output pin was toggled long debounceDelay = 50; // the debounce time; increase if the output flickers void setup() { pinMode(buttonPin, INPUT); for(pin=0;pin<pinCount;pin++) { pinMode(ledPins[pin], OUTPUT); // set initial LED state digitalWrite(ledPins[pin], ledState); } // init Serial connection for debug Serial.begin(9600); } void loop() { // read the state of the switch into a local variable: int reading = digitalRead(buttonPin); // check to see if you just pressed the button // (i.e. the input went from LOW to HIGH), and you've waited // long enough since the last press to ignore any noise: // If the switch changed, due to noise or pressing: if (reading != lastButtonState) { // reset the debouncing timer lastDebounceTime = millis(); } if ((millis() - lastDebounceTime) > debounceDelay) { // whatever the reading is at, it's been there for longer // than the debounce delay, so take it as the actual current state: // if the button state has changed: if (reading != buttonState) { buttonState = reading; // only toggle the LED if the new button state is HIGH if (buttonState == HIGH) { Serial.println("Button pressed"); if (ledState > 0) { ledState = false; for(pin=pinCount;pin>0;pin--) { // LED off fadeLedOut(ledPins[pin-1]); } } else { ledState = true; for(pin=0;pin<pinCount;pin++) { // LED off fadeLedIn(ledPins[pin]); } } } } } // save the reading. Next time through the loop, // it'll be the lastButtonState: lastButtonState = reading; } // Function that fade LED in void fadeLedIn(int ledFadePin) { for (float i = 1; i <= 255; i = i * 2.3) { // set the LED with fade in to high analogWrite(ledFadePin, int(i)); delay(50); } analogWrite(ledFadePin, 255); } // Function that fade LED out void fadeLedOut(int ledFadePin) { for (float i = 255; i > 0.5; i = i / 2.3) { // set the LED with fade out to low analogWrite(ledFadePin, i); delay(50); } analogWrite(ledFadePin, 0); }
true
7951731a85e30411babfa26d7d2dba68381ea041
C++
neilforrest/protohaptic
/Rotate.cpp
UTF-8
8,955
2.640625
3
[]
no_license
// ProtoHaptic // =========== // Author: Neil Forrest, 2006 // File: Rotate.cpp // Classes: CRotate // Purpose: Represents a rotation transformation #include "stdafx.h" #include "ProtoHaptic.h" #include "Rotate.h" #include "math.h" #include <gl/gl.h> #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// #define PI 3.14159 float rad2deg(float rad) { return (float)(rad*(360.0/(2*PI))); } CRotate::CRotate(CShape *shape, HLdouble x, HLdouble y, HLdouble z, int handle_axis, int direction) { m_proxyStartPos[0]= x; m_proxyStartPos[1]= y; m_proxyStartPos[2]= z; m_shape= shape; int i; for(i= 0; i<16; i++) m_startRotation[i]= m_shape->getRotation()[i]; m_handle_axis= handle_axis; m_direction= direction; rotating= false; m_chunking= false; } int CRotate::getType() { return TRANSFORM_ROTATE; } CRotate::~CRotate() { } bool CRotate::hasAxis() { return rotating; } int CRotate:: getAxis() { return m_axis; } int CRotate::getHandleAxis() { return m_handle_axis; } static void normalise(float V[3]) { float l= (float)sqrt(V[0]*V[0] + V[1]*V[1] + V[2]*V[2]); V[0]= V[0] / l; V[1]= V[1] / l; V[2]= V[2] / l; } static void cross(float ans[3], float A[3], float B[3]) { ans[0]= A[1]*B[2]-A[2]*B[1]; ans[1]= A[2]*B[0]-A[0]*B[2]; ans[2]= A[0]*B[1]-A[1]*B[0]; } static void swap(float a[3], float b[3]) { float tmp[3]= { a[0], a[1], a[2] }; a[0]= b[0]; a[1]= b[1]; a[2]= b[2]; b[0]= tmp[0]; b[1]= tmp[1]; b[2]= tmp[2]; } void CRotate::setProxyPos(HLdouble x, HLdouble y, HLdouble z) { // float R[16]; //The rotation matrix we shall construct // // float c[3]= { m_shape->getLocationX(), // m_shape->getLocationY(), // m_shape->getLocationZ() }; //centre of object // // float p[3]= { x-c[0], // y-c[1], // z-c[2] }; //vector from object centre to proxy // // float d= sqrt(p[0]*p[0] + // p[1]*p[1] + //length of p // p[2]*p[2]); //used below // // float u[3]= { p[0] / d, // p[1] / d, // p[2] / d }; //p normalised, i.e. as unit vector // // float l= sqrt(u[0]*u[0] + u[1]*u[1]); //length of u in xy-plane // // if (l == 0.0) { /// // R[0]= u[2]; R[4]= 0.0; R[8]= 0.0; /// R[1]= 0.0; R[5]= 1.0; R[9]= 0.0; /// R[2]= 0.0; R[6]= 0.0; R[10]= u[2]; /// // } else { /// /// R[0]= (u[2]*u[0])/l; R[4]= -u[1]/l; R[8]= u[0]; /// R[1]= (u[2]*u[1])/l; R[5]= u[0]/l; R[9]= u[1]; /// R[2]= -l; R[6]= 0.0; R[10]= u[2]; // // } // // R[3] = 0.0; // R[7] = 0.0; // R[11]= 0.0; // // R[12]= 0.0; // R[13]= 0.0; // R[14]= 0.0; // R[15]= 1.0; // // // m_shape->setRotation(R); // //Second try float proxy_drag[3]= { (float)(x-m_proxyStartPos[0]), (float)(y-m_proxyStartPos[1]), (float)(z-m_proxyStartPos[2]) }; float drag_dist= (float)sqrt( proxy_drag[0]*proxy_drag[0] + proxy_drag[1]*proxy_drag[1] + proxy_drag[2]*proxy_drag[2] ); float c[3]= { m_shape->getLocationX(), m_shape->getLocationY(), m_shape->getLocationZ() }; //centre of object float p[3]= { (float)(x-c[0]), (float)(y-c[1]), (float)(z-c[2]) }; //vector from object centre to proxy float max= ((CProtoHapticApp*)AfxGetApp())->getRotationGuess(); if(drag_dist>max&&rotating==false) { rotating= true; float n[3]= { m_startRotation[0], m_startRotation[1], m_startRotation[2] }; //do projection float zy[3]= { p[0]*(n[1]*n[1]+ n[2]*n[2]) - p[1]*n[0]*n[1] - p[2]*n[0]*n[2], -p[0]*n[1]*n[0] + p[1]*(n[0]*n[0]+n[2]*n[2]) - p[2]*n[1]*n[2], -p[0]*n[0]*n[2] - p[1]*n[1]*n[2] + p[2]*(n[0]*n[0]+n[1]*n[1]) }; float n1[3]= { m_startRotation[4], m_startRotation[5], m_startRotation[6] }; //do projection float zx[3]= { p[0]*(n1[1]*n1[1]+ n1[2]*n1[2]) - p[1]*n1[0]*n1[1] - p[2]*n1[0]*n1[2], -p[0]*n1[1]*n1[0] + p[1]*(n1[0]*n1[0]+n1[2]*n1[2]) - p[2]*n1[1]*n1[2], -p[0]*n1[0]*n1[2] - p[1]*n1[1]*n1[2] + p[2]*(n1[0]*n1[0]+n1[1]*n1[1]) }; float n2[3]= { m_startRotation[8], m_startRotation[9], m_startRotation[10] }; //do projection float xy[3]= { p[0]*(n2[1]*n2[1]+ n2[2]*n2[2]) - p[1]*n2[0]*n2[1] - p[2]*n2[0]*n2[2], -p[0]*n2[1]*n2[0] + p[1]*(n2[0]*n2[0]+n2[2]*n2[2]) - p[2]*n2[1]*n2[2], -p[0]*n2[0]*n2[2] - p[1]*n2[1]*n2[2] + p[2]*(n2[0]*n2[0]+n2[1]*n2[1]) }; float zy_length= (float)sqrt( zy[0]*zy[0] + zy[1]*zy[1] + zy[2]*zy[2] ); float zx_length= (float)sqrt( zx[0]*zx[0] + zx[1]*zx[1] + zx[2]*zx[2] ); float xy_length= (float)sqrt( xy[0]*xy[0] + xy[1]*xy[1] + xy[2]*xy[2] ); if (zy_length>zx_length&&zy_length>xy_length) m_axis= ROTATE_AXIS_X; else if(zx_length>zy_length&&zx_length>xy_length) m_axis= ROTATE_AXIS_Y; else m_axis= ROTATE_AXIS_Z; } if(rotating) { float R[16]; //The rotation matrix we shall construct if(m_chunking) { p[0]= chunk(p[0]); p[1]= chunk(p[1]); p[2]= chunk(p[2]); normalise(p); } //project p to the apropriate plane as pr float pr[3]; if(m_axis==ROTATE_AXIS_X) { //we want the local zy-plane, normal to this is the local x-axis... float n[3]= { m_startRotation[0], m_startRotation[1], m_startRotation[2] }; //do projection pr[0]= p[0]*(n[1]*n[1]+ n[2]*n[2]) - p[1]*n[0]*n[1] - p[2]*n[0]*n[2]; pr[1]= -p[0]*n[1]*n[0] + p[1]*(n[0]*n[0]+n[2]*n[2]) - p[2]*n[1]*n[2]; pr[2]= -p[0]*n[0]*n[2] - p[1]*n[1]*n[2] + p[2]*(n[0]*n[0]+n[1]*n[1]); } if(m_axis==ROTATE_AXIS_Y) { //as above... float n[3]= { m_startRotation[4], m_startRotation[5], m_startRotation[6] }; pr[0]= p[0]*(n[1]*n[1]+ n[2]*n[2]) - p[1]*n[0]*n[1] - p[2]*n[0]*n[2]; pr[1]= -p[0]*n[1]*n[0] + p[1]*(n[0]*n[0]+n[2]*n[2]) - p[2]*n[1]*n[2]; pr[2]= -p[0]*n[0]*n[2] - p[1]*n[1]*n[2] + p[2]*(n[0]*n[0]+n[1]*n[1]); } if(m_axis==ROTATE_AXIS_Z) { //as above... float n[3]= { m_startRotation[8], m_startRotation[9], m_startRotation[10] }; pr[0]= p[0]*(n[1]*n[1]+ n[2]*n[2]) - p[1]*n[0]*n[1] - p[2]*n[0]*n[2]; pr[1]= -p[0]*n[1]*n[0] + p[1]*(n[0]*n[0]+n[2]*n[2]) - p[2]*n[1]*n[2]; pr[2]= -p[0]*n[0]*n[2] - p[1]*n[1]*n[2] + p[2]*(n[0]*n[0]+n[1]*n[1]); } normalise(pr); //make unit vector float X[3], Y[3], Z[3]; if(m_axis==ROTATE_AXIS_X){ Z[0]= m_direction*pr[0]; Z[1]= m_direction*pr[1]; Z[2]= m_direction*pr[2]; //the new z axis X[0]= m_startRotation[0]; X[1]= m_startRotation[1]; X[2]= m_startRotation[2]; Y[0]= -(X[1]*Z[2]-X[2]*Z[1]); Y[1]= -(X[2]*Z[0]-X[0]*Z[2]); Y[2]= -(X[0]*Z[1]-X[1]*Z[0]); normalise(Y); //make unit vector if(m_handle_axis==ROTATE_AXIS_Y) { swap(Z,Y); Z[0]= -Z[0]; Z[1]= -Z[1]; Z[2]= -Z[2]; } } if(m_axis==ROTATE_AXIS_Y){ X[0]= m_direction*pr[0]; X[1]= m_direction*pr[1]; X[2]= m_direction*pr[2]; //the new z axis Y[0]= m_startRotation[4]; Y[1]= m_startRotation[5]; Y[2]= m_startRotation[6]; Z[0]= -(Y[1]*X[2]-Y[2]*X[1]); Z[1]= -(Y[2]*X[0]-Y[0]*X[2]); Z[2]= -(Y[0]*X[1]-Y[1]*X[0]); normalise(Z); //make unit vector if(m_handle_axis==ROTATE_AXIS_Z) { swap(Z,X); X[0]= -X[0]; X[1]= -X[1]; X[2]= -X[2]; } } if(m_axis==ROTATE_AXIS_Z){ Y[0]= m_direction*pr[0]; Y[1]= m_direction*pr[1]; Y[2]= m_direction*pr[2]; //the new z axis Z[0]= m_startRotation[8]; Z[1]= m_startRotation[9]; Z[2]= m_startRotation[10]; X[0]= (Y[1]*Z[2]-Y[2]*Z[1]); X[1]= (Y[2]*Z[0]-Y[0]*Z[2]); X[2]= (Y[0]*Z[1]-Y[1]*Z[0]); normalise(X); //make unit vector if(m_handle_axis==ROTATE_AXIS_X) { swap(X,Y); Y[0]= -Y[0]; Y[1]= -Y[1]; Y[2]= -Y[2]; } } //NEW STUFF/////////////////////////////////////// R[0]= X[0]; R[4]= Y[0]; R[8]= Z[0]; R[1]= X[1]; R[5]= Y[1]; R[9]= Z[1]; R[2]= X[2]; R[6]= Y[2]; R[10]= Z[2]; R[3] = 0.0; R[7] = 0.0; R[11]= 0.0; R[12]= 0.0; R[13]= 0.0; R[14]= 0.0; R[15]= 1.0; m_shape->setRotation(R); } } void CRotate::setChunking(bool chunking) { m_chunking= chunking; } float CRotate::chunk(float f) { if(f>0.0&&f<0.5) return 0.0; if(f<0.0&&f>-0.5) return 0.0; if(f>0.0&&f>0.5) return 1.0; if(f<0.0&&f<-0.5) return -1.0; else return -1000; //To shut the compiler up! }
true
9266099a501c53746f95d5ec03126ce0a24c1907
C++
dabaopku/project_pku
/Project/C++/POJ/1606/1606.cpp
UTF-8
1,031
3.078125
3
[]
no_license
#include "iostream" #include "stdio.h" using namespace std; void solve(int a,int b,int n,int &x,int &y) { int x1,x2,y1,y2; y1=-1; while((n-b*y1)%a) y1--; x1=(n-b*y1)/a; x2=-1; while((n-a*x2)%b) x2--; y2=(n-a*x2)/b; if(x1-y1<y2-x2){ x=x1;y=y1; } else { x=x2;y=y2; } } void pour(char fill,char empty,int a,int b,int x,int y) { int na=0,nb=0; for(int i=0;i<x;i++){ cout<<"fill "<<fill<<endl; na+=a; cout<<"pour "<<fill<<" "<<empty<<endl; if(na>=(b-nb)){ na-=b-nb; nb=0; cout<<"empty "<<empty<<endl; } else{ nb+=na; na=0; } } if(fill=='A') cout<<"pour A B\n"; cout<<"success\n"; } int main() { int a,b,n; while(cin>>a>>b>>n){ int x,y; if(n==b){ cout<<"fill B\n"; cout<<"success\n"; continue; } if(n%a==0){ for(int i=0;i<n/a;i++) cout<<"fill A\npour A B\n"; cout<<"success\n"; continue; } solve(a,b,n,x,y); if(x>0) pour('A','B',a,b,x,-y); else pour('B','A',b,a,y,-x); } return 0; }
true
25e31de001875d1a70dc583bede61f5d0a2dae63
C++
minicho/TIZEN5-
/basic/src/tabTestFormFactory.cpp
UTF-8
2,901
2.53125
3
[]
no_license
#include <new> #include "tabTestFormFactory.h" #include "AppResourceId.h" #include "CalendarViewerForm.h" #include "MainForm.h" #include "ChatMain.h" #include "ChatForm.h" #include "EventListForm.h" #include "CreateEventForm.h" #include "EventDetailForm.h" #include "EditEventForm.h" #include "SetRecurrenceForm.h" using namespace Tizen::Ui::Scenes; tabTestFormFactory::tabTestFormFactory(void) { } tabTestFormFactory::~tabTestFormFactory(void) { } Tizen::Ui::Controls::Form* tabTestFormFactory::CreateFormN(const Tizen::Base::String& formId, const Tizen::Ui::Scenes::SceneId& sceneId) { SceneManager* pSceneManager = SceneManager::GetInstance(); AppAssert(pSceneManager); Tizen::Ui::Controls::Form* pNewForm = null; if (formId == FORM_CALENDAR) { CalendarViewerForm* pForm = new (std::nothrow) CalendarViewerForm(); TryReturn(pForm != null, null, "The memory is insufficient."); pForm->Initialize(); pNewForm = pForm; } else if (formId == FORM_CHATMAIN) { ChatMain* pMainFrm = new (std::nothrow) ChatMain(); pMainFrm->Initialize(); pNewForm = pMainFrm; } else if (formId == FORM_CHAT) { AppLog("FORM CHAT MENU! \n"); ChatForm* pChatForm = new (std::nothrow) ChatForm(); if (pChatForm == null) { int result; MessageBox* pMsgBox = new (std::nothrow) MessageBox(); pMsgBox->Construct(L"Error", L"Error in allocating Memory", MSGBOX_STYLE_OK); pMsgBox->ShowAndWait(result); delete pMsgBox; } pChatForm->Initialize(); AppLog("Initialize :Exit"); pSceneManager->AddSceneEventListener(sceneId, *pChatForm); pNewForm = pChatForm; } else if(formId == FORM_WEBLINK) { MainForm* pForm = new (std::nothrow) MainForm(); pForm->Initialize(); pSceneManager->AddSceneEventListener(sceneId, *pForm); pNewForm = pForm; } else if (formId == FORM_EVENT_LIST) { EventListForm* pForm = new (std::nothrow) EventListForm(); pForm->Initialize(); pSceneManager->AddSceneEventListener(sceneId, *pForm); pNewForm = pForm; } else if (formId == FORM_EVENT_CREATION) { CreateEventForm* pForm = new (std::nothrow) CreateEventForm(); pForm->Initialize(); pSceneManager->AddSceneEventListener(sceneId, *pForm); pNewForm = pForm; } else if (formId == FORM_EVENT_DETAIL) { EventDetailForm* pForm = new (std::nothrow) EventDetailForm(); pForm->Initialize(); pSceneManager->AddSceneEventListener(sceneId, *pForm); pNewForm = pForm; } else if (formId == FORM_EVENT_EDITION) { EditEventForm* pForm = new (std::nothrow) EditEventForm(); pForm->Initialize(); pSceneManager->AddSceneEventListener(sceneId, *pForm); pNewForm = pForm; } else if (formId == FORM_EVENT_RECURRENCE) { SetRecurrenceForm* pForm = new (std::nothrow) SetRecurrenceForm(); pForm->Initialize(); pSceneManager->AddSceneEventListener(sceneId, *pForm); pNewForm = pForm; } // TODO: Add your form creation code here return pNewForm; }
true
f3b1143bfe68c3a05125604bb91fe3e83d00690b
C++
th0masdw/Pacman_Engine
/Source/Engine/Scenegraph/GameScene.cpp
UTF-8
2,114
2.6875
3
[]
no_license
#include "MiniginPCH.h" #include "GameScene.h" #include "Engine/Components/ColliderComponent.h" #include "Engine/Managers/PhysicsManager.h" GameScene::GameScene(const std::string& name) : m_Name(name) { } GameScene::~GameScene() { for (GameObject* pObject : m_pObjects) { delete pObject; } } void GameScene::FlushSceneObjects() { for (auto poolIt : m_Poolables) { m_pObjects.erase(poolIt); } } void GameScene::PostInitialize() { for (GameObject* pObject : m_pObjects) { pObject->PostInitialize(); } } void GameScene::Update(const GameTime& time) { for (GameObject* pObject : m_pObjects) { if (pObject->IsActive()) pObject->Update(time); } } void GameScene::Draw() const { for (GameObject* pObject : m_pObjects) { if (pObject->IsActive()) pObject->Draw(); } } void GameScene::AddObject(GameObject* pObject) { auto it = find(m_pObjects.begin(), m_pObjects.end(), pObject); if (it == m_pObjects.end() && pObject) { auto addIt = m_pObjects.insert(pObject); pObject->SetScene(this); AddToPhysicsScene(pObject); if (pObject->IsPoolable()) m_Poolables.emplace_back(addIt); } else Debug::LogWarning("Object already present!"); } void GameScene::RemoveObject(GameObject* pObject, bool deleteObject) { auto it = find(m_pObjects.begin(), m_pObjects.end(), pObject); if (it != m_pObjects.end()) { m_pObjects.erase(it); pObject->SetScene(nullptr); RemoveFromPhysicsScene(pObject); if (deleteObject) { delete pObject; pObject = nullptr; } } } void GameScene::AddToPhysicsScene(GameObject* pObject) { auto pColliders = pObject->GetComponents<ColliderComponent>(); if (!pColliders.empty()) { for (ColliderComponent* pComp : pColliders) { PhysicsManager::GetInstance().AddCollider(pComp, m_Name); } } } void GameScene::RemoveFromPhysicsScene(GameObject* pObject) { auto pColliders = pObject->GetComponents<ColliderComponent>(); if (!pColliders.empty()) { for (ColliderComponent* pComp : pColliders) { PhysicsManager::GetInstance().RemoveCollider(pComp, m_Name); } } } std::string GameScene::GetName() const { return m_Name; }
true
7d853eebd3380ef6a4c93c6fd50078ebc557f336
C++
dmncie/QtSelfTraining
/1/PersonList.cpp
UTF-8
1,080
3.1875
3
[]
no_license
#include "PersonList.h" #include <iostream> PersonList::PersonList(): index{0} {} void PersonList::addPerson(Person person) { person.setId(index++); people.push_back(person); emit personAdded(person, people.size()); } void PersonList::updatePerson(int id, Person person) { auto it = find_if(begin(people), end(people), [id](Person& p){ return p.getId() == id; }); if (it != end(people)) { person.setId(it->getId()); *it = person; emit personModified(person, people.size()); } } void PersonList::removePerson(int id) { auto it = find_if(begin(people), end(people), [id](Person& p){ return p.getId() == id; }); if (it != end(people)) { auto person = *it; people.erase(remove_if(begin(people), end(people), [id](Person& p){ return p.getId() == id; }), end(people)); emit personRemoved(person, people.size()); } } void PersonList::printList() { for (auto& p : people) { std::cout << p << '\n'; } }
true
df9affb459502109ae8c876b0bfdd3ebb11b6d9e
C++
rae/pac
/pacman/Node.h
UTF-8
1,651
3.09375
3
[]
no_license
// // Node.hpp // pathFinder // // Created by Reid Ellis on 2017-04-14. // Copyright © 2017 Tnir Technologies. All rights reserved. // #ifndef Node_hpp #define Node_hpp #include <list> struct Node; struct Map; class SceneNode; typedef std::list<Node *> NodeList; struct Node { // position of the node int x; int y; // false if a wall or blockage bool canBePath; // // current distance from the start / finish of the path // // "g" int srcDistance; // "h" int destDistance; // the previous node on the path before this one Node *parent; // which map does this node belong to? Map * map; // the SceneNode for this map node SceneNode * sceneNode; // // methods // // trivial constructor sets x, y Node(int inX, int inY, Map *inMap); // destructor virtual ~Node(); // "f" float totalCost() { return srcDistance + destDistance; } // calculate the distance, where diagonal costs 14 (~sqrt(2) * 10), // while stright costs 10 (1 * 10) int gridDistanceTo(Node * dest); // return a list of valid nodes surrounding this one std::tuple<NodeList *, bool> neighbours(Node *finish); // search for a path to another node on "map" - returns nullptr for no path NodeList * pathToNode(Node *destination); // follow back along the parent nodes and generate a path NodeList * parentPath(); // does this node have > 2 connections? (i.e. does a ghost have to decide which // way to go when it exits this node?) bool isWaypoint(); private: // parses the list to find the cheapest one - no need to refer to 'this', so make it static static Node * findLeastCostNode(const NodeList &list); }; #endif /* Node_hpp */
true
756bcca6f80aefa8725ac26fb3988e296ba3ba7d
C++
PeterLaptik/OdtCreator
/class/src/OdtImages.cpp
UTF-8
3,429
2.515625
3
[ "BSD-3-Clause" ]
permissive
#include "../include/OdtCreator.h" #include"../include/OdtXmlNodes.h" #include <wx/filefn.h> // Inserts an image-file into the document // Inserts nothing if the file does not exist // @inPath - path to file // @width - picture width // @height - picture height void OdtCreator::InsertPicture (const wxString &inPath, int width, int height) { wxXmlNode *textNode; wxXmlNode *childNode; wxXmlNode *pictureNode; wxXmlNode *pictureChildNode; wxString sValue; wxString pictureName; wxString pictureFileName; wxString destination; if (!m_isProcessing) { m_error = ODT_ERROR_NO_DOC_IN_PROCESSING; return; } // If a temporary directory does not exist if (!wxDir::Exists(m_tmpDirPath)) return; // If the file does not exist if (!wxFile::Exists(inPath)) return; pictureName = ODT_PICTURE_PREFIX; pictureName<<m_pictureCounter; pictureFileName = ODT_PICTURE_PREFIX; pictureFileName<<m_pictureCounter; pictureFileName<<mExt; m_pictureCounter++; destination = m_tmpDirPath; destination<<m_pathSeparator<<ODT_FOLDER_PICTURES<<m_pathSeparator; if (!wxDir::Exists(destination)) wxDir::Make(destination); destination<<pictureFileName; wxCopyFile(inPath, destination); // Add text node textNode = new wxXmlNode(wxXML_ELEMENT_NODE, NODE_text, wxEmptyString, -1); textNode->AddAttribute(TAG_textStyleName, VAL_standard); // Add node childNode = new wxXmlNode(wxXML_ELEMENT_NODE, NODE_text, wxEmptyString, -1); childNode->AddAttribute(TAG_textStyleName, m_paragraphStyle); pictureNode = new wxXmlNode(wxXML_ELEMENT_NODE, NODE_drawFrame, wxEmptyString, -1); pictureNode->AddAttribute(TAG_drawName, pictureName); sValue.Clear(); sValue<<width<<mUnits; pictureNode->AddAttribute(TAG_svnWidth, sValue); pictureNode->AddAttribute(TAG_drawStyleName, mStyleImage); pictureNode->AddAttribute(TAG_drawZindex, VAL_drawZindex); sValue.Clear(); sValue<<height<<mUnits; pictureNode->AddAttribute(TAG_svnHeight, sValue); pictureNode->AddAttribute(TAG_anchorType, VAL_anchorType); pictureChildNode = new wxXmlNode(wxXML_ELEMENT_NODE, NODE_drawImage, wxEmptyString, -1); pictureChildNode->AddAttribute(TAG_xlinkActuate, VAL_xlinkActuate); pictureChildNode->AddAttribute(TAG_xlinkShow, VAL_xlinkShow); pictureChildNode->AddAttribute(TAG_xlinkType, VAL_xlinkType); sValue.Clear(); sValue<<ODT_FOLDER_PICTURES<<mSep<<pictureFileName; PictureToManifest(sValue); // Add data to manifest XML-file pictureChildNode->AddAttribute(TAG_xlinkHref, sValue); pictureChildNode->AddAttribute(TAG_loextMimeType, VAL_loextMimeTypePng); // Add nodes pictureNode->AddChild(pictureChildNode); textNode->AddChild(pictureNode); m_contentNode->AddChild(textNode); // blank line m_lastNode = NULL; // or null (check later) } // Adds a picture data to the manifest XML-file // @picName - relative path to the image void OdtCreator::PictureToManifest(wxString &picName) { wxXmlNode *nodeToManifest; nodeToManifest = new wxXmlNode(wxXML_ELEMENT_NODE, NODE_manifestFileEntry, wxEmptyString, -1); nodeToManifest->AddAttribute(TAG_manifestMediaType, VAL_loextMimeTypePng); nodeToManifest->AddAttribute(TAG_manifestFullPath, picName); m_manifestNode->AddChild(nodeToManifest); }
true
ac9d5f50cdad0c2d91c49467a189ad3594fa3857
C++
BarIfrah/Hulda-FinalProject
/src/Music.cpp
UTF-8
4,731
2.53125
3
[]
no_license
#include <Music.h> #include <Macros.h> //----------------------------------------------------------------------------- Music::Music() { loadSounds(); setSounds(); } //----------------------------------------------------------------------------- Music& Music::instance() { static Music instance; return instance; } //----------------------------------------------------------------------------- void Music::playEnemyAte() { m_sounds[(int)Sound::enemyAte].play(); } //----------------------------------------------------------------------------- void Music::playFood() { m_sounds[(int)Sound::eatFood].play(); } //----------------------------------- void Music::playToxicFood() { m_sounds[(int)Sound::eatToxic].play(); } //----------------------------------------------------------------------------- void Music::playMenu() { m_sounds[(int)Sound::menu].play(); } //----------------------------------------------------------------------------- void Music::playLevelMusic(const int & level) { switch (level) { case 1: m_sounds[(int)Sound::level1].play(); break; case 2: m_sounds[(int)Sound::level2].play(); break; case 3: m_sounds[(int)Sound::level3].play(); break; case 4: m_sounds[(int)Sound::level4].play(); break; case 5: m_sounds[(int)Sound::level5].play(); break; default: break; } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void Music::stopMenu() { m_sounds[(int)Sound::menu].stop(); } //----------------------------------------------------------------------------- void Music::stopGame() { m_sounds[(int)Sound::level1].stop(); } void Music::stopHiScoreMenu() { m_sounds[(int)Sound::hiScore].stop(); } //----------------------------------------------------------------------------- void Music::playWonGame() { m_sounds[(int)Sound::wonGame].play(); } //----------------------------------------------------------------------------- void Music::stopWonGame() { m_sounds[(int)Sound::wonGame].stop(); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void Music::playInfoMenu() { m_sounds[(int)Sound::infoMenu].play(); } //----------------------------------------------------------------------------- void Music::stopInfoMenu() { m_sounds[(int)Sound::infoMenu].stop(); } void Music::playSpecialFood() { m_sounds[(int)Sound::SpecialFood].play(); } void Music::playCredits() { m_sounds[(int)Sound::credits].play(); } void Music::stopCredits() { m_sounds[(int)Sound::credits].stop(); } void Music::stopLevelMusic(const int& level) { switch (level) { case 1: m_sounds[(int)Sound::level1].stop(); break; case 2: m_sounds[(int)Sound::level2].stop(); break; case 3: m_sounds[(int)Sound::level3].stop(); break; case 4: m_sounds[(int)Sound::level4].stop(); break; case 5: m_sounds[(int)Sound::level5].stop(); break; default: break; } } //---------------------------------------------------------------------- //----------------------------------------------------------------------------- void Music::playLostGame() { m_sounds[(int)Sound::lostGame].play(); } //----------------------------------------------------------------------------- void Music::playBack() { m_sounds[(int)Sound::back].play(); } void Music::playHiScoreMenu() { m_sounds[(int)Sound::hiScore].play(); } //----------------------------------------------------------------------------- const sf::SoundBuffer& Music::getSound(const Sound name) const { return m_soundBuff[(int)name]; } //----------------------------------------------------------------------------- void Music::loadSounds() { loadSound("MainMenu.ogg"); loadSound("EatFood.wav"); loadSound("EatToxic.wav"); loadSound("EnemyEat.wav"); loadSound("WonGame.wav"); loadSound("Life1up.wav"); loadSound("LostGame.wav"); loadSound("TimeEnd.wav"); loadSound("Back.wav"); loadSound("HiScore.wav"); loadSound("GameTheme.ogg"); loadSound("InfoMenu.ogg"); loadSound("EatSpecialFood.wav"); loadSound("Credits.wav"); loadSound("Level2Music.ogg"); loadSound("Level3Music.ogg"); loadSound("Level4Music.ogg"); loadSound("Level5Music.ogg"); } //----------------------------------------------------------------------------- void Music::loadSound(const std::string path) { sf::SoundBuffer temp; temp.loadFromFile(path); m_soundBuff.push_back(temp); } //----------------------------------------------------------------------------- void Music::setSounds() { for (int i = 0; i < AUDIOS; i++) { m_sounds.push_back(sf::Sound(getSound(Sound(i)))); m_sounds[i].setVolume(VOL); } }
true
fa20593be17c0918877063de6364da9633acc6ec
C++
snow-cube/Luogu_OJ_code
/P1328.cpp
UTF-8
667
2.78125
3
[]
no_license
#include <iostream> using namespace std; int main() { int a[200] = {0}; int b[200] = {0}; int table[5][5] = { {0, 0, 1, 1, 0}, {1, 0, 0, 1, 0}, {0, 1, 0, 0, 1}, {0, 0, 1, 0, 1}, {1, 1, 0, 0, 0} }; int N, Na, Nb; cin >> N >> Na >> Nb; for (int i = 0; i < Na; i++) { cin >> a[i]; } for (int i = 0; i < Nb; i++) { cin >> b[i]; } int i_a = 0, i_b = 0; int score_a = 0, score_b = 0; while (N--) { score_a += table[a[i_a]][b[i_b]]; score_b += table[b[i_b]][a[i_a]]; i_a < Na-1 ? i_a++ : i_a = 0; i_b < Nb-1 ? i_b++ : i_b = 0; } cout << score_a << " " << score_b << endl; return 0; }
true
0374420021a318f6ec291002d11568ba8c3c9be1
C++
Ponuyashka7316/CrazyTanks2_
/CrazyTanks2_/Tank.cpp
UTF-8
347
2.828125
3
[]
no_license
#include "stdafx.h" #include "Tank.h" void Tank::setHealth(int value) { if (value >= 0 && value < 1000) this->health = value; else this->health = 1; } int Tank::getHealth() const { return health; } void Tank::decreaseHealth() { health--; } Tank::Tank() { value = '+'; }; Tank::Tank(char ch) { value = ch; } Tank::~Tank() { };
true
3eb1f0b6c3e9ff46adf8ae195db9fc59d309a15d
C++
jyhsia5174/algo
/leetcode/1007.cpp
UTF-8
971
2.609375
3
[]
no_license
class Solution { public: int minDominoRotations(vector<int>& A, vector<int>& B) { n = A.size(); for(int i = 1; i <= 6; i++){ cnt[i] = 0; top[i] = 0; bot[i] = 0; } for(int i = 0; i < n; i++){ top[A[i]]++; bot[B[i]]++; if( A[i] == B[i] ){ cnt[A[i]] ++; } else{ cnt[A[i]] ++; cnt[B[i]] ++; } } vector<int> candidates; for(int i = 1; i <=6; i++) if( cnt[i] == n ) candidates.push_back(i); if( candidates.empty() ) return -1; int res = INT_MAX; for(auto x: candidates) res = min<int>( res, min<int>( n - top[x], n - bot[x] ) ); return res; } private: int n; int cnt[7]; int top[7]; int bot[7]; };
true
f18fc4278c73e5171f8d23db158d396958b5564d
C++
pratikmankawde/Graphics
/Fabrik IK/Elements/Joint.h
UTF-8
676
2.53125
3
[]
no_license
/* * Joint.h * * Created on: 05-Feb-2017 * Author: PprrATeekK */ # include "Vec3.h" #ifndef JOINT_H_ #define JOINT_H_ namespace elements { class Joint { private: Vec3<float> mPosition; Vec3<float> mApex; public: Joint(const Vec3<float> aPosition) { mPosition = aPosition; mApex = mPosition + 1.0f; } void setPosition(const Vec3<float> aPosition){mPosition = aPosition;} Vec3<float> getPosition() {return mPosition;} void setApex(const Vec3<float> aApex){mApex = aApex;} Vec3<float> getApex() {return mApex;} void extendLenght(); virtual ~Joint(); }; } /* namespace fabrik */ #endif /* JOINT_H_ */
true
688e1a80647be557c7b819968c3b32b8c2ba2989
C++
WhiZTiM/coliru
/Archive/09c750ef92adb379e560eeaac4d561f9/main.cpp
UTF-8
161
2.953125
3
[]
no_license
int x; constexpr int blah(int n) { return n == 0? 42 : x++; } #include <iostream> int main() { blah(0); blah(1); blah(2); std::cout << x; }
true
d0f1c006ec14b603b311a79f7ddac84800036de1
C++
dennissoftman/ScienceCraft
/shadermanager.cpp
UTF-8
4,536
2.515625
3
[]
no_license
#include "shadermanager.hpp" #include <fstream> #include <cassert> #include <glm/gtc/type_ptr.hpp> Shader::Shader() : Shader("", "", "") { } Shader::Shader(const std::string &v_path, const std::string &f_path, const std::string &g_path) { if(v_path.length() == 0 || f_path.length() == 0) { fprintf(stderr, "Empty shader names\n"); return; } bool load_geom = (g_path.length() > 0); // load shaders from files std::ifstream fin; std::string vsh_source, fsh_source, gsh_source; fin.open(v_path); assert(fin.is_open() && "Failed to load vertex shader"); std::getline(fin, vsh_source, (char)fin.eof()); fin.close(); fin.open(f_path); assert(fin.is_open() && "Failed to load fragment shader"); std::getline(fin, fsh_source, (char)fin.eof()); fin.close(); if(load_geom) { fin.open(g_path); assert(fin.is_open() && "Failed to load geometry shader"); std::getline(fin, gsh_source, (char)fin.eof()); fin.close(); } // load shaders to memory GLuint vsh, fsh, gsh; vsh = glCreateShader(GL_VERTEX_SHADER); fsh = glCreateShader(GL_FRAGMENT_SHADER); if(load_geom) gsh = glCreateShader(GL_GEOMETRY_SHADER); const GLchar *vsh_raw = vsh_source.c_str(); glShaderSource(vsh, 1, &vsh_raw, nullptr); const GLchar *fsh_raw = fsh_source.c_str(); glShaderSource(fsh, 1, &fsh_raw, nullptr); const GLchar *gsh_raw = nullptr; if(load_geom) { gsh_raw = gsh_source.c_str(); glShaderSource(gsh, 1, &gsh_raw, nullptr); } // compile shaders int ok = 0; char infoBuff[512]; glCompileShader(vsh); glGetShaderiv(vsh, GL_COMPILE_STATUS, &ok); if(!ok) { glGetShaderInfoLog(vsh, 512, nullptr, infoBuff); fprintf(stderr, "[%s] Shader compilation error:\n%s\n", v_path.c_str(), infoBuff); } glCompileShader(fsh); glGetShaderiv(fsh, GL_COMPILE_STATUS, &ok); if(!ok) { glGetShaderInfoLog(fsh, 512, nullptr, infoBuff); fprintf(stderr, "[%s] Shader compilation error:\n%s\n", f_path.c_str(), infoBuff); } if(load_geom) { glCompileShader(gsh); glGetShaderiv(gsh, GL_COMPILE_STATUS, &ok); if(!ok) { glGetShaderInfoLog(gsh, 512, nullptr, infoBuff); fprintf(stderr, "[%s] Shader compilation error:\n%s\n", g_path.c_str(), infoBuff); } } // link shaders shp = glCreateProgram(); glAttachShader(shp, vsh); glAttachShader(shp, fsh); if(load_geom) glAttachShader(shp, gsh); glLinkProgram(shp); glGetProgramiv(shp, GL_LINK_STATUS, &ok); if(!ok) { glGetProgramInfoLog(shp, 512, nullptr, infoBuff); fprintf(stderr, "Shader linking error:\n%s\n", infoBuff); } // cleanup glDeleteShader(vsh); glDeleteShader(fsh); if(load_geom) glDeleteShader(gsh); } Shader::~Shader() { glDeleteProgram(shp); } void Shader::use() { glUseProgram(shp); } void Shader::setInt(const std::string &prop, int a) { glUniform1i(glGetUniformLocation(shp, prop.c_str()), a); } void Shader::setFloat(const std::string &prop, float a) { glUniform1f(glGetUniformLocation(shp, prop.c_str()), a); } void Shader::setMat4(const std::string &prop, const glm::mat4 &mat) { glUniformMatrix4fv(glGetUniformLocation(shp, prop.c_str()), 1, GL_FALSE, glm::value_ptr(mat)); } void Shader::setVec2(const std::string &prop, const glm::vec2 &vec) { glUniform2fv(glGetUniformLocation(shp, prop.c_str()), 1, glm::value_ptr(vec)); } void Shader::setVec3(const std::string &prop, const glm::vec3 &vec) { glUniform3fv(glGetUniformLocation(shp, prop.c_str()), 1, glm::value_ptr(vec)); } void Shader::setIntArray(const std::string &prop, const int *arr, int size) { glUniform1iv(glGetUniformLocation(shp, prop.c_str()), size, arr); } ShaderManager::ShaderManager() { } Shader *ShaderManager::get(const std::string &id) const { if(m_shaders.find(id) != m_shaders.end()) return m_shaders.at(id); return nullptr; } void ShaderManager::loadShader(const std::vector<std::string> &paths, const std::string &id) { assert(m_shaders.find(id) == m_shaders.end() && "Shader duplicate"); assert((paths.size() == 2 || paths.size() == 3) && "Invalid shader quantity"); if(paths.size() == 2) m_shaders[id] = new Shader(paths[0], paths[1]); else m_shaders[id] = new Shader(paths[0], paths[1], paths[2]); }
true
5846bf228cd55412d06509b65efb24d40ec60790
C++
wlasser/oonline
/OOCommon/OOHashTable.cpp
UTF-8
3,546
2.59375
3
[]
no_license
/* This file is part of OblivionOnline Server- An open source game server for the OblivionOnline mod Copyright (C) 2008 Julian Bangert This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "OOHashTable.h" #include "Entity.h" //Masterfreek64: //in theory we would need naming functions now ... I define these as inlines directly here ... All names are defined as UINT32 s because Oblivion has them all over the place // Also I directly define the structure we will be hashing with. This is not THAT generic ;). //Should we need to reuse it I can change it quickly inline UINT32 GetName(void *obj) { return ((Entity *)obj)->RefID(); // The old SelectType method. Extremely fast here } #include "OOHashTable.h" // faster and less secure OOHashTable::OOHashTable(unsigned int size) { table = (HashEntry **)calloc(size,sizeof(HashEntry *)); tablesize = size; } OOHashTable::~OOHashTable(void) { //here we have to free all elements unsigned int i; HashEntry *entry; for(i = 0; i < tablesize;i++) { while(entry = table[i]) { table[i] = entry->next; free(entry->obj); // we need to free it somehow else as well... free(entry); } } free(table); //Auto cleanup fixes the rest } bool OOHashTable::Insert(void * object) { unsigned int hash; UINT32 id; HashEntry **prev, *newelement; id = GetName(object); hash = Hash(id,tablesize); //find a memory location for(prev = table + hash;*prev;prev = &((*prev)->next)) //We advance thorugh the list... { if(id == GetName((*prev)->obj)) { return false; // Not a unique hash .... } else if(id < GetName((*prev)->obj)) { break; // we found a location } } // We allocate the memory newelement = (HashEntry *)malloc(sizeof(HashEntry)); newelement->next = *prev; newelement->obj = object; *prev = newelement;// we insert ourselves into the chains elements++; return true; } void * OOHashTable::Find(UINT32 id) { unsigned int hash; HashEntry *entry; hash = Hash(id,tablesize); for(entry = table[hash];entry; entry = entry->next) //we go through the list { if(GetName(entry->obj) == id) { return entry->obj; } } return NULL; } bool OOHashTable::Remove(UINT32 id) { // this is not yet necessary, as we cannot detect that // I will implement it at the given time unsigned int hash; HashEntry *entry, *prev; hash = Hash(id,tablesize); entry = table[hash]; if(GetName(entry->obj) == id) // no collision , we do not need to fix it .... { free(entry->obj); free(entry); return true; } prev = entry; for(;entry; entry = entry->next) //we go through the list { if(GetName(entry->obj)==id) { if(entry->next) { prev->next = entry->next; // We fix the pointer } else { prev->next = NULL; } free(entry->obj); free(entry); return true; } prev = entry; } return false; }
true
f2a787e618d48de169aa35294c33c2365a82d8c6
C++
naddu77/ModernCppChallenge
/070_Approval_system/070_Approval_system.cpp
UTF-8
1,500
3.796875
4
[]
no_license
// 070_Approval_system.cpp : 이 파일에는 'main' 함수가 포함됩니다. 거기서 프로그램 실행이 시작되고 종료됩니다. // Note // - Chaining을 간단하게 구현 #include "pch.h" #include <iostream> #include <string> #include <string_view> struct Expense { double amount; std::string description; Expense(double const amount, std::string_view desc) : amount(amount), description(desc) { } }; class Employee { public: Employee(std::string_view name, double const appoval_limit) : name(name), appoval_limit(appoval_limit) { } Employee& operator()(Employee& other) { direct_manager = &other; return other; } void approve(Expense const& e) { if (e.amount <= appoval_limit) std::cout << name << " approved expense '" << e.description << "', cost=" << e.amount << std::endl; else if (direct_manager != nullptr) direct_manager->approve(e); else std::cout << "could not approve expense.\n"; } private: std::string const name; double const appoval_limit; Employee* direct_manager = nullptr; }; int main() { Employee john{ "john smith", 1'000 }; Employee robert{ "robert booth", 10'000 }; Employee david{ "david jones", 100'000 }; Employee cecil{ "cecil williamson", std::numeric_limits<double>::max() }; john (robert) (david) (cecil); john.approve(Expense{ 500, "magazins" }); john.approve(Expense{ 5000, "hotel accomodation" }); john.approve(Expense{ 50000, "conference costs" }); john.approve(Expense{ 200000, "new lorry" }); return 0; }
true
6b688106b27b210c85d5d0f10b1f13f159ae3a41
C++
SinisSem/MCSAS-old
/mcsas/mcsas.h
WINDOWS-1251
8,500
2.671875
3
[]
no_license
#ifndef __mcsas_h__ #define __mcsas_h__ #include <vector> using namespace std; #define REAL float namespace MCSAS { /* -------------------------------------------------------------------------------------------------------------------------------*/ // , GPU struct KernelGPUChain { unsigned int LinksNum; // unsigned int* LinksColIdx; // ( = LinksNum) unsigned int* LinksRowIdx; // ( = LinksNum) REAL* LinksVal; // ( = LinksNum) unsigned int NodesNum; // ( , ) REAL* a; // ( = (NodesNum-1)) REAL* b; // ( = NodesNum) REAL* ; // ( = (NodesNum-1)) }; /* , GPU chain_data (, sizeof(float) = 4; sizeof(uint) = 4; sizeof(void*) = 4): - # | | | --------------------------------------------------------------------------------------------------------- 1. | sizeof(uint) | links_num | 2. | sizeof(uint) | nodes_num | ( - ) 3. | sizeof(REAL) * (nodes_num-1) | vector_a | 4. | sizeof(REAL) * nodes_num | vector_b | 5. | sizeof(REAL) * (nodes_num-1) | vector_c | 6. | sizeof(uint) * links_num | link_col_idx | 7. | sizeof(uint) * links_num | link_row_idx | 8. | sizeof(REAL) * links_num | link_val | */ struct KernelGPUData { unsigned int chains_num; // (sizeof(unsigned int) = 4)//!!!!!!!!!!!!!!!!!! , - ))) unsigned int mem_size; unsigned int* chain_address; // ( ) char* chain_data; // }; /* \------------------------------------------------------------------------------------------------------------------------------*/ /*Solver-----------------------------------------------------------------------------------------------------------------------------------*/ namespace Solver { class CGPUData; /* , */ enum MCSASSResult { MCSASS_SUCCESS = 0, /*, */ MCSASS_CUDAMALLOCFAIL, /*, cudaMalloc*/ MCSASMG_UNKNOWN_ERROR = 9999 /*, */ }; } /*Solver\----------------------------------------------------------------------------------------------------------------------------------*/ /*MatrixGenerator--------------------------------------------------------------------------------------------------------------------------*/ namespace MatrixGenerator { /* , matrix_generator*/ enum MCSASMGResult { MCSASMG_SUCCESS = 0, /*, */ MCSASMG_UNSUFFICIENT_TASK, /* */ MCSASMG_UNKNOWN_ERROR = 9999 /*, */ }; /*, */ struct MCSASMGTask { vector<unsigned int> ChainNodesNumber; // unsigned int RandomNetAdmittancesNumber; // double BaseAdmittance; // double AdmittancesDispersion; // ( ) double BaseMainDiagonalAddition; // ( ) double AdditionDispersion; // ( ) double AdditionsNumber; // ( ) double EDSBase; // double EDSDispersion; // double EDSNumber; // ( ) double EDSAdmittanceBase; // double EDSAdmittanceDispersion; // bool CheckConductivity; // }; // COO ( MATLAB') struct COO_matrix { vector<double> Vals; // vector<unsigned int> Cols; // vector<unsigned int> Rows; // unsigned int GetRows(); // ( ) unsigned int GetCols(); // ( ) }; class MCSASMGUtility { public: static MCSASMGTask DefaultTask(); // static MCSASMGResult WriteMatrixMarketFile(COO_matrix, string); // matrix market file static MCSASMGResult WriteMatrixMarketFile(vector<double>, string); // matrix market file static double RandomDouble(double, double); // double static int RandomInt(int, int); // int }; struct CPUChain { vector<unsigned int> LinksColIdx; // ( = LinksNum) vector<unsigned int> LinksRowIdx; // ( = LinksNum) vector<REAL> LinksVal; // ( = LinksNum) vector<REAL> a; // ( = (NodesNum-1)) vector<REAL> b; // ( = NodesNum) vector<REAL> c; // ( = (NodesNum-1)) }; struct CPUData { vector<CPUChain> Chains; // ( = ChainNum) }; }; /*MatrixGenerator\-------------------------------------------------------------------------------------------------------------------------*/ } #endif
true
b3417abc85b370e5d06f732ae74e14c53cc91258
C++
psr2016/psr
/old/firmware/libs/controllib/pid.cpp
UTF-8
2,274
2.703125
3
[]
no_license
/* * pid.cpp */ #include "pid.h" Pid::Pid(float kp, float ki, float kd, float kff, float dt, float saturation) : m_Kp(kp), m_Ki(ki), m_Kd(kd), m_Kff(kff), m_dt(dt), m_saturation(saturation) { m_derivative_low_pass = new LowPassFilter(dt); reset(); } Pid::Pid() : m_Kp(0), m_Ki(0), m_Kd(0), m_Kff(0), m_dt(0), m_saturation(0) { m_derivative_low_pass = new LowPassFilter(0); reset(); } Pid::~Pid() { delete m_derivative_low_pass; } void Pid::init(float kp, float ki, float kd, float kff, float dt, float saturation) { m_Kp = kp; m_Ki = ki; m_Kd = kd; m_Kff = kff; m_dt = dt; m_derivative_low_pass->set_dt(dt); m_saturation = saturation; reset(); } void Pid::set_params(float kp, float ki, float kd, float kff) { m_Kp = kp; m_Ki = ki; m_Kd = kd; m_Kff = kff; reset(); } void Pid::set_derivative_low_pass(float cutoff_hz) { m_derivative_low_pass->set_cutoff_frequecy(cutoff_hz); } void Pid::reset() { m_u_i = 0; m_error_old = 0; m_old_process_var = 0; m_windup = false; } float Pid::derivative_low_pass(float val) { return m_derivative_low_pass->apply(val); } float Pid::derivative(float error, float process_var) { return (error - m_error_old); } float Pid::evaluate(float target, float process_var) { float error = target - process_var; return evaluate_using_error(error, target, process_var); } float Pid::evaluate_using_error(float error, float target, float process_var) { float u_p, u_d; u_p = m_Kp * error; if (m_Kd != 0.0) u_d = m_Kd * derivative_low_pass(derivative(error, process_var)) / m_dt; else u_d = 0.0; m_old_process_var = process_var; m_error_old = error; if (!m_windup) m_u_i += m_Ki * (((error + m_error_old) / 2.0) * m_dt); m_out = u_p + m_u_i + u_d + target * m_Kff; if (m_out >= m_saturation) { m_out = m_saturation; m_windup = true; } else if (m_out <= (-1.0 * m_saturation)) { m_out = -1.0 * m_saturation; m_windup = true; } else m_windup = false; return m_out; } float PidDerivateOutput::derivative(float error, float process_var) { return - (process_var - m_old_process_var); }
true
61668f08b77087e74d1280e8931ecfde09164fb8
C++
takjn/KurumiWatch
/KurumiWatch/Common.ino
UTF-8
1,333
2.671875
3
[ "MIT" ]
permissive
unsigned char key_read(void) { if (digitalRead(KEY_SELECT_PIN) == 0) { digitalWrite(24, LOW); while (digitalRead(KEY_SELECT_PIN) == 0); digitalWrite(24, HIGH); tick_counter = 0; return KEY_SELECT; } else if (digitalRead(KEY_PREV_PIN) == 0) { while (digitalRead(KEY_PREV_PIN) == 0); tick_counter = 0; return KEY_PREV; } else if (digitalRead(KEY_NEXT_PIN) == 0) { while (digitalRead(KEY_NEXT_PIN) == 0); tick_counter = 0; return KEY_NEXT; } return KEY_NONE; } void beep(void) { if (buzzer_volume != 0) { tone(BUZZER_PIN, 1024, BUZZER_VOLUMES[buzzer_volume]); } } void printWithCheckBoundry(int x, String str) { if (x>=0 && x < oled.displayWidth()) { oled.setCol(x); oled.print(str); } } void printValueWithCheckBoundry(int x, int val) { if (x>=0 && x < oled.displayWidth()) { oled.setCol(x); printWithZero(val); } } void printWithZero(int v) { if (v<10) { oled.print("0"); } oled.print(v); } static float getVoltage() { float ret = 0.0; digitalWrite(VOLTAGE_OUT_PIN, 1); // 2:1で抵抗分圧した回路を前提に、 RL78/G13の内部基準電圧(1.45V)でA/Dを実施。 int voltage = analogRead(VOLTAGE_CHK_PIN); ret = ((float)voltage/1023)*1.45/0.333333; digitalWrite(VOLTAGE_OUT_PIN, 0); return ret; }
true
6425f2244424ba804c570152d0210418e67bf35c
C++
samiqss/Data-Structures
/csci260/Lab4/mainTile.cpp
UTF-8
904
3.109375
3
[]
no_license
/**********************************************************/ /***** Lab 3 mainTile ****************************/ /***** CSCI 260 ****************************/ /***** Sept 25 2017 ****************************/ /**********************************************************/ #include "herringboneTile.h" #include <iostream> #include <cstdlib> // atoi() using namespace std; int main(int argc, char *argv[]) { int missrow, misscol,k; if (argc < 4) { cout << "Enter the power k, making a chessboard of dimensions 2^k x 2^k: "; cin >> k; cout << "Enter the row and column of the missing square, seperated by a space: "; cin >> missrow >> misscol; } else { k= atoi(argv[1]); missrow = atoi(argv[2]); misscol = atoi(argv[3]); } // initialize board herringboneTile b(k,missrow,misscol); b.printBoard(); }
true
b8bcd4dd3ee7a09fd602b06365c882252f59ceb1
C++
Andrew-Hany/DataStructure_algortihms
/algorithms/practise Problems/Buy_fruits.cpp
UTF-8
2,161
3.375
3
[]
no_license
/****************************************************************************** Online C++ Compiler. Code, Compile, Run and Debug C++ program online. Write your code in this editor and press "Run" button to compile and execute it. *******************************************************************************/ #include <iostream> #include <vector> using namespace std; int Partition(vector<int>&a , int start, int end) { int pivot = a[end]; int pIndex = start; for (int i = start; i < end; i++) { if (a[i] <= pivot) { swap(a[i], a[pIndex]); pIndex++; } } swap (a[pIndex], a[end]); return pIndex; } void quicksort_comparisions(vector<int>&a ,int start, int end) { if (start >= end) return ; int pivot = Partition(a, start, end); quicksort_comparisions(a, start, pivot - 1); quicksort_comparisions(a, pivot + 1, end); } void quicksort(vector<int>&a ,int n) { quicksort_comparisions(a,0, n-1); } ///-------------------------------// bool fruit(vector<int>weight,int value){ //we need to add some other possible weight to the array for(int i=weight.size()-1;i>=0;i--){ if(value>=weight[i]) { value =value-weight[i]; // cout<<weight[i]<<endl; } cout<<weight[i]<<endl; if(value==0) return true; } return false; } int main() { int array[200]={0}; int value=26; vector<int>weight={11,9,1,5}; int size=weight.size(); int sum=0; for(int i=0;i<size;i++) sum=sum+weight[i]; for(int i=0;i<size;i++)//1,2,5,10 for(int j=i+1;j<size;j++)//2,5,10 { if(array[weight[i]-weight[j]]==0){ weight.push_back(abs(weight[i]-weight[j])); array[weight[i]-weight[j]]++; } // cout<<abs(weight[i]-weight[j]); } quicksort(weight ,weight.size()); if(fruit(weight,value)&&value<= sum) cout <<"yes, we can weigh this amount for you"<<endl; else cout <<"sorry,we cant weight this amount for you"<<endl; return 0; }
true
d64dc006aaef1ef5b527ad56ce6271a3d82454bd
C++
DcmTruman/my_acm_training
/HDU/2089/18998709_AC_0ms_1208kB.cpp
UTF-8
1,446
2.96875
3
[]
no_license
#include<stdio.h> #include<string.h> using namespace std; int dp[10][10]; int digit[10]; void init() { //十位加个位dp,百位加十位dp,千位加百位dp dp[0][0]=1; for(int i=1;i<=7;i++) { for(int j=0;j<10;j++)//枚举第i位数上的数字、 { for(int k=0;k<10;k++)//枚举第i-1位上的数字、 { if(!(j==6&&k==2)&&j!=4)//满足条件 dp[i][j]+=dp[i-1][k]; } } } } int calchangdu(int n) { int cont=0; while(n) { cont++; n/=10; } return cont; } int caldigit(int n,int len) { memset(digit,0,sizeof(digit)); for(int i=1;i<=len;i++) { digit[i]=n%10; n/=10; } } int solve(int n)//计算[0,n)符合条件的个数 { int ans=0; int len=calchangdu(n); caldigit(n,len); for(int i=len;i>=1;i--)//从最高位开始枚举 { for(int j=0;j<digit[i];j++) { if(!(j==2&&digit[i+1]==6)&&j!=4) { ans+=dp[i][j]; } } if(digit[i]==4 || (digit[i]==2 && digit[i+1]==6))//第i位已经不满足条件,则i位以后都不可能满足条件,结束循环 break ; } return ans; } int main() { init(); int n,m; while(~scanf("%d%d",&n,&m)) { if(n==0&&m==0)break; printf("%d\n",solve(m+1)-solve(n)); } }
true
929be0dd820beceabdc515fc105793f1cfebe1b5
C++
raphaellmsousa/cppForProgrammers
/3_print_variables.cpp
UTF-8
198
2.875
3
[]
no_license
/* C++ for programers from Udacity */ #include <iostream> using namespace std; int main() { int integer = 384; cout << "The value of the integer is: " << integer << "\n"; return 0; }
true
761b40dba407604a1cd86bb7f13c695346247c2c
C++
David-Wong-Cascante/JuniorEngine
/Junior_Core/Src/Include/Space.h
UTF-8
1,213
2.9375
3
[ "BSD-3-Clause" ]
permissive
#pragma once /* * Author: David Wong * Email: david.wongcascante@digipen.edu * File name: Space.h * Description: The class where all levels reside * Created: 18-Dec-2018 * Last Modified: 19 Apr 2019 */ #include "GameSystem.h" namespace Junior { // Forward Declarations class Level; class Space : public GameSystem { private: // Private Variables Level* currentLevel_; Level* nextLevel_; // Moves from one level to another void MoveLevels(); public: // Constructor Space(const char* name); // Loads the assets for the space // Returns: Whether the Space managed to load the assets bool Load() override; // Initializes the space // Returns: Whether the Space managed to initialize bool Initialize() override; // Updates the component // Params: // dt: The time between frames void Update(double dt) override; // Renders the space (should debug draw be a feature in the future) void Render() override; // Shuts down the space void Shutdown() override; // Unloads the space void Unload() override; // Change the level inside the space // Params: // level: The next level we want to load void NextLevel(Level* level); // Restarts the current level void RestartLevel(); }; }
true
dc65a923261c73e86624a3e5a83f3ce3210d10c8
C++
EpicDevClub/excel-cpp
/2. Simple Aithmetics/Arithmetic Operations/Arithmetic Operations.cpp
UTF-8
704
4.28125
4
[]
no_license
//This is a program to demonstrate simple arithmetic operations #include<iostream> #include<conio.h> int main() { //declare variables int a,b; //ask user to enter two numbers std::cout << "Enter two numbers" <<std::endl; //endl is used to go to new line std::cin>>a>>b; //add two numbers int sum; sum = a+b; //subtract two numbers int diff; diff = a-b; //multiply two numbers int mul; mul = a*b; //divide two numbers float div; div = a/b; std::cout<<"Sum = "<<sum<<std::endl; std::cout<<"Difference = "<<diff<<std::endl; std::cout<<"Product = "<<mul<<std::endl; std::cout<<"Quotient = "<<div<<std::endl; return 0; }
true
beadcf76a422d44d98667ea1956632f2f2aad2db
C++
15831944/Fdo_SuperMap
/源代码/Thirdparty/UGC/inc/Algorithm/UGRectUInt.h
GB18030
2,175
2.59375
3
[ "Apache-2.0" ]
permissive
/*! \file UGRectUInt.h * \brief 4 byte unsinged int rect * \author ugc team * \attention * Copyright(c) 1996-2004 SuperMap GIS Technologies,Inc.<br> * All Rights Reserved * \version $Id: UGRectUInt.h,v 1.2 2007/09/29 06:06:07 guohui Exp $ */ /*! ˵ * 2007.09.29 guohui ͷļϸע */ #ifndef UGRECTUINT_H #define UGRECTUINT_H #include "Base/ugdefs.h" namespace UGC { class ALGORITHM_API UGRectUInt { public: UGuint left; UGuint top ; UGuint right; UGuint bottom; public: //! \brief ȱʡ캯 //! \return void //! \param //! \remarks UGRectUInt(); //! \brief //! \return void //! \param //! \remarks virtual ~UGRectUInt(); //! \brief ι캯 //! \return void //! \param l //! \param t //! \param r //! \param b //! \remarks ײ㲻ݽй(ȷleft<right,top<bottom)ϵ UGRectUInt(UGuint l, UGuint t, UGuint r, UGuint b); //! \brief 캯 //! \return void //! \param //! \remarks UGRectUInt(const UGRectUInt& srcRect); //! \brief //! \return void //! \param //! \remarks UGuint Width() const; //! \brief ߶ //! \return void //! \param //! \remarks UGuint Height() const; //! \brief = UGRectUInt& operator=(const UGRectUInt& srcRect); //! \brief == UGbool operator==(const UGRectUInt& rect) const; //! \brief != UGbool operator!=(const UGRectUInt& rect) const; //! \brief ÿ void SetRectEmpty(); //! \brief ÿ(0,0,0,0) void SetNULL(); //! \brief ϲ UGbool UnionRect(const UGRectUInt &rect1, const UGRectUInt &rect2); //! \brief Ƿ UGbool Contain(const UGRectUInt &rect) const; //! \brief Ƿཻ(߻ǵص) UGbool IsIntersect(const UGRectUInt &rect) const; //! \brief ǷΪվ //! \return TRUE if rectangle has no area UGbool IsRectEmpty() const; //! \brief ǷΪ //! \return TRUE if rectangle is (0,0,0,0) UGbool IsRectNull() const; }; } #endif
true
8019610441c6b854f7bf9c80b5444f3975e80d45
C++
jzwdsb/algorithms
/Areas_on_the_cross_section_diagram.cpp
UTF-8
795
2.78125
3
[]
no_license
// // Created by manout on 18-1-16. // #include <stack> #include <vector> #include <string> #include <algorithm> using namespace std; pair<int, vector<int>> Areas_on_the_cross_section_diagram(const string& line) { int sum = 0; vector<int> ans; stack<int> s1; stack<pair<int, int>> s2; for (int i = 0; i < line.length(); ++i) { if (line[i] == '\\') { s1.push(i); }else if (line[i] == '/' and not s1.empty()) { int j = s1.top(); s1.pop(); /** a 是当前面积*/ int a = i - j; sum += a; while( not s2.empty() and s2.top().first > j) { a += s2.top().second; s2.pop(); } s2.push(make_pair(j ,a)); } } while (not s2.empty()) { ans.push_back(s2.top().second); s2.pop(); } reverse(ans.begin(), ans.end()); return make_pair(sum, ans); }
true
492ee8926cc1a38a8274ed7a639e838d65fed9d9
C++
anilharish/LCPP
/Chapter1/test9main.cpp
UTF-8
285
3.234375
3
[]
no_license
#include<iostream> #include "test9add.h" int main() { int a,b; std::cout << "Please enter two numbers you wish to add, press enter after each number" << std::endl; std::cin >> a >> b; std::cout << "The addition of the two numbers is: " << add(a,b) << std::endl; return 0; }
true
4cee24fa160ebc934234c7fbe4f4a7f240704c66
C++
PanzerKadaver/B4-nibbler
/old/Nibbler3.0/Land.cpp
UTF-8
1,616
2.703125
3
[]
no_license
// // Land.cpp for Land in /home/alois/rendu/nibbler/nibbler // // Made by alois // Login <alois@epitech.net> // // Started on Tue Mar 18 01:11:32 2014 alois // Last update Tue Apr 1 20:16:16 2014 Nathan AUBERT // // #include <iostream> // #include "Land.hpp" Land::Land(int size) : width(size), height(size) { init(); } Land::Land(int w, int h) : width(w), height(h) { init(); } // caca void Land::initFood() { std::deque<Point> EmptyList; // read all cell for (int i = 0; i < this->width; i++) { for (int j = 0; j < this->height; j++) { if (((this->land)[i][j]).GetContent() == ' ') { EmptyList.push_back((this->land)[i][j]); } } } // get rand one Point p = Randomizer::GetItem<std::deque<Point> >(EmptyList); ((this->land)[p.GetX()][p.GetY()]).SetContent('f'); } // inversion x y // void Land::initSnake() // { // int midWidth = this->width / 2; // int midHeight = this->height / 2; // Point ptmp; // ptmp.SetX(midWidth); // ptmp.SetY(midHeight); // ptmp.SetContent('s'); // (this->land)[midWidth][midHeight - 1] = ptmp; // (this->land)[midWidth][midHeight] = ptmp; // (this->land)[midWidth][midHeight + 1] = ptmp; // } void Land::init() { Point point; for (int i = 0; i < this->width; ++i) { std::deque<Point> tmp; for (int j = 0; j < this->height; ++j) { point.SetContent((i == 0 || j == 0 || i + 1 == this->width || j + 1 == this->height) ? 'b' : ' '); point.SetX(i); point.SetY(j); tmp.push_back(point); } this->land.push_back(tmp); tmp.erase(tmp.begin(), tmp.end()); } initFood(); }
true
04d0ec2696c6e098d6f86795b041673f1a26e10c
C++
DBurrSudz/DataStructuresImplementations
/binarytreePointers.cpp
UTF-8
3,324
4.28125
4
[]
no_license
#include <iostream> #include <queue> template <typename T> class BTPointers{ private: struct Node{ T key; //Value inside a node Node* left; //Pointer to left subtree Node* right; //Pointer to the right subtree }; Node* root; /** * @brief Creates a new node in the tree. * @param key Value to be inserted into the node. * @return The newly created node. */ Node* getNode(const T key){ Node* newNode = new Node(); newNode->key = key; newNode->left = NULL; newNode->right = NULL; return newNode; } public: BTPointers(){ root = NULL; } /** * @brief Adds a node to the tree at the first available position. * @param value The value to be added to the tree. */ void addNode(const T value){ if(root == NULL){ root = getNode(value); } else{ //Looks through the tree and finds the first available position to add the node //From left to right. std::queue<Node*> q; q.push(root); while(!q.empty()){ Node* temp = q.front(); q.pop(); if(temp->left == NULL){ temp->left = getNode(value); break; } else if(temp->right == NULL){ temp->right = getNode(value); break; } else{ q.push(temp->left); q.push(temp->right); } } } return; } /** * @brief Uses a queue to print the tree with Breadth First Traversal */ void printBFS(){ if(root == NULL) return; else{ std::queue<Node*> q; q.push(root); while(!q.empty()){ Node* temp = q.front(); q.pop(); std::cout << temp->key << " "; if(temp->left != NULL) q.push(temp->left); if(temp->right != NULL) q.push(temp->right); } } } /** * @brief Prints the farthest right element in the tree. */ void printDeepestRight(){ if(root == NULL) return; else{ Node* temp = root; while(temp->right != NULL){ temp = temp->right; } std::cout << temp->key; return; } } }; int main(){ BTPointers<char> tree; tree.addNode('F'); tree.addNode('B'); tree.addNode('G'); tree.addNode('K'); tree.addNode('I'); tree.addNode('H'); tree.addNode('L'); tree.printBFS(); std::cout << std::endl; tree.printDeepestRight(); return 0; }
true
f90fd007ac8e455e9a16749066719e66fd425611
C++
20172104255/Cdate0604
/Cdate0604/Cdate0604.cpp
GB18030
1,429
3.546875
4
[]
no_license
// Cdate0604.cpp : ̨Ӧóڵ㡣 // #include "stdafx.h" #include<iostream> using namespace std; class Cdate { private: int year; int month; int day; public: void init(int y, int m, int d); void display(); void nextday(); }; void Cdate::init(int y, int m, int d) { year = y; month = m; day = d; } void Cdate::nextday() { if (year % 400 == 0 || year % 4 == 0 && year % 100 != 0) { if (month == 2) { if (day == 29) { month = month + 1; day = day + 1 - 29; } else { day += 1; } } } else { if (month == 2) { if (day == 28) { month = month + 1; day = day + 1 - 28; } else { day += 1; } } } if (month == 4 || month == 6 || month == 9 || month == 11) { if (day == 30) { month = month + 1; day = day + 1 - 30; } else { day += 1; } } else if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10) { if (day == 31) { month = month + 1; day = day + 1 - 31; } else { day += 1; } } else if (month == 12) { if (day == 31) { day = day + 1 - 31; month = month + 1 - 12; year = year + 1; } else { day += 1; } } } void Cdate::display() { cout << year << "" << month << "" << day << "" << endl; } int main() { Cdate oc; int a, b, c; cin >> a >> b >> c; oc.init(a, b, c); oc.nextday(); oc.display(); return 0; }
true
5c1e852b241fefbe0b0433598e3216a6332b61a2
C++
HonghuiLi/Playground
/C++1x/src/charpter2-TheBasics/4-Modularity/main.cpp
UTF-8
1,755
3.609375
4
[]
no_license
// main.cpp #include <iostream> #include <stdexcept> // std::out_of_range #include "Vector.h" using namespace std; void modularity() { Basic::Vector v(3); cout << v.sqrtSum(3) << "\n"; } // Exceptions report errors found at run time. void exceptionFun(Basic::Vector& v) { try { // exceptions here are handled by the handler defined below v[v.size()] = 7; // tr y to access beyond the end of v } catch (const std::out_of_range& oor) { // oops: out_of_range error // ... handle range error ... std::cerr << "Out of Range error: " << oor.what() << '\n' ; } try { Basic::Vector v1(-27); } catch (const std::length_error& oor) { // handle negative size std::cerr << "Length error: " << oor.what() << '\n' ; } catch (const std::bad_alloc& oor) { // handle memory exhaustion std::cerr << "bad alloc error: " << oor.what() << '\n' ; } } // Static Assertions: we can also perform simple checks on other properties // that are known at compile time and report failures as compiler error messages. void assertions() { static_assert(4 <= sizeof(int), "integers are too small"); // check integer size // In general, static_assert(A,S) prints S as a compiler error message if A is not true . constexpr double C = 299792.458; // km/s const double local_max = 160.0 / (60*60); // 160 km/h == 160.0/(60*60) km/s const double speed = 12.34; // double speed = 12.34; static_assert(speed < C, "can't go that fast"); // error : speed must be a constant static_assert(local_max < C, "can't go that fast"); // OK // static_assert(local_max > C, "can't go that fast"); // assert failed } int main(int argc, char const *argv[]) { /* code */ modularity(); Basic::Vector v(3); exceptionFun(v); assertions(); return 0; }
true
d10dec75a319a5e94e5ea68d7d99e12e7d435991
C++
Kreyl/KeyLock
/HackerTool/HackerTool_fw/inc/led.h
UTF-8
759
2.609375
3
[]
no_license
/* * led.h * * Created on: 03.11.2011 * Author: g.kruglov */ #ifndef LED_H_ #define LED_H_ #include "stm32f10x.h" #include "stm32f10x_gpio.h" #include "stm32f10x_tim.h" #include "delay_util.h" #define LED_BLINK_DELAY 144 class Led_t { private: uint32_t Timer; GPIO_TypeDef* IGPIO; uint16_t IPin; bool IsOn, IsInsideBlink; public: void On(void) { GPIO_SetBits(IGPIO, IPin); IsOn = true;} void Off(void) { GPIO_ResetBits(IGPIO, IPin); IsOn = false; } void Disable(void) { Off(); IsInsideBlink = false; } void Init(GPIO_TypeDef* AGPIO, uint16_t APin); void Blink(void); void Task(void); void Toggle(void) { IGPIO->ODR ^= IPin; IsOn = !IsOn; } }; extern Led_t Led1, Led2; #endif /* LED_H_ */
true
857aad6b67167102a34e309b16ff0612b0536078
C++
Struti/GrafBead
/Classes/Shader.h
UTF-8
918
2.59375
3
[]
no_license
#pragma once #include <string> #include <iostream> #include <sstream> #include <fstream> #include "GLIncludes.h" namespace ti { enum class ShaderType : unsigned int { VERTEX, FRAGMENT, TESSCONT, TESSEV, GEOMETRY }; int operator+ (ShaderType val); class Shader { public: Shader(); ~Shader(); /* Loads the shaders using the file paths given and builds a program object. Tessellation shaders are not necessary. */ void load( const std::string& vertexShaderFile, const std::string& fragmentShaderFile, const char* tessControlShader, const char* tessEvShader); void use(); static void useNone(); GLuint getUniformLocation(const std::string& uniform); GLuint getProgram(); bool isLoaded(); private: GLuint program_; GLuint shaders_[5]; static std::string loadFile(const std::string& path); static int getCompilationStatus(GLuint shader); }; }
true
08c5c6e18c73b94d5e4901163a0d4d325e72a49a
C++
bilalozcan/OOP
/smart-array/smartArray.h
ISO-8859-9
5,151
3.265625
3
[]
no_license
/*18120205035 *Bilal ZCAN *dev9 template class almas */ #pragma once #include <vector> #include <iostream> #include<string> using namespace std; template<typename T> struct Pair { T eleman; unsigned adet; }; // histogramda her bir elemandan kacar adet oldugunu gosterebilecek veri tipi */ //ndex operatrnde eleman saysndan fazla bir index istendiinde exception handling yapacak class class ExpHandNoMemory{}; //Dinamik Hafza kullanrken yer alnamadnda exception handling yapacak class class ExpHandOverMemory{}; template<class T> class AkilliDizi { template<class T> friend ostream& operator << (ostream& out,const AkilliDizi<T>& dizi); public: //bos bir akilli dizi olusturur AkilliDizi(); //tek elamanl ve eleman degeri i olan bir akilli dizi olusturur AkilliDizi(T i); //elemanSayisi elamanli bir akilli dizi olusturur ve intDizi elamanlarini akilli diziye atar AkilliDizi(const T* TDizi, unsigned int elemanSayisi); //vektoru akilli diziye donusturur AkilliDizi(const vector<T>& TVector); //Dinamik bellek yonetimi icin gerekli olan fonksiyonlari ~AkilliDizi(); AkilliDizi(const AkilliDizi<T>& copyT); AkilliDizi<T>& operator =(const AkilliDizi<T>& assigmentT); //[] operatorunun asiri yuklenmesi T& operator[](const unsigned int index); T operator[](const unsigned int index)const; //AkilliDizi'ye bir int degeri ekleyebilen + operatorunun asiri yuklenmesi AkilliDizi<T>& operator +(T i); //diziyi buyukten kucuge siralar void sirala()const; //veri icinde gecen her bir elemanin kac kez oldugunu bulur ve bunu vektor<Pair> olarak donderir void histogram(vector<Pair<T>>& hist) const; //veri icinde i degerinden kac tane olduunu sayar unsigned kacTane(T a) const; //veri icinde i degeri mevcutsa dogru degilse yanlis donderir TEMPLATE OLACAK*/ bool varMi(T a) const; private: T* veri; unsigned int kapasite; unsigned int elemanSayisi; }; class Ogrenci { //Ogrencn adn ve numarasn yazdran << operatr friend ostream& operator <<(ostream& out, Ogrenci& ogrenciOut) { out << "Adi: "; for (unsigned i = 0; i < ogrenciOut.adUzunlugu; ++i) { out << ogrenciOut.ad[i]; } out << " " << "No: "; for (unsigned i = 0; i < ogrenciOut.noUzunlugu; ++i) { out << ogrenciOut.no[i]; } out << endl; return out; } public: //Default Constructer Ogrenci() { ad = nullptr; no = nullptr; adUzunlugu = 0; noUzunlugu = 0; } //BYK L //Conversion Consturcter Ogrenci(string ad, string no) { adUzunlugu = ad.size(); noUzunlugu = no.size(); this->ad = new char[adUzunlugu]; if (this->ad == nullptr) throw ExpHandNoMemory(); this->no = new char[noUzunlugu]; if (this->no == nullptr) throw ExpHandNoMemory(); for (unsigned i = 0; i < adUzunlugu; ++i) this->ad[i] = ad[i]; for (unsigned i = 0; i < noUzunlugu; ++i) this->no[i] = no[i]; } //Destructer ~Ogrenci() { if (ad != nullptr) delete[] ad; if (no != nullptr) delete[] no; } //Copy Constructer Ogrenci(const Ogrenci& copyOgrenci) { adUzunlugu = copyOgrenci.adUzunlugu; noUzunlugu = copyOgrenci.noUzunlugu; ad = nullptr; no = nullptr; ad = new char[adUzunlugu]; if (this->ad == nullptr) throw ExpHandNoMemory(); no = new char[noUzunlugu]; if (this->no == nullptr) throw ExpHandNoMemory(); for (unsigned i = 0; i < adUzunlugu; ++i) ad[i] = copyOgrenci.ad[i]; for (unsigned i = 0; i < noUzunlugu; ++i) no[i] = copyOgrenci.no[i]; } //Assigment Operatr Ogrenci& operator=(const Ogrenci& assigmentOgrenci) { if (this == &assigmentOgrenci) return *this; if (ad != nullptr) delete[] ad; if (no != nullptr) delete[] no; adUzunlugu = assigmentOgrenci.adUzunlugu; noUzunlugu = assigmentOgrenci.noUzunlugu; ad = new char[adUzunlugu]; if (this->ad == nullptr) throw ExpHandNoMemory(); no = new char[noUzunlugu]; if (this->no == nullptr) throw ExpHandNoMemory(); for (unsigned i = 0; i < adUzunlugu; ++i) ad[i] = assigmentOgrenci.ad[i]; for (unsigned i = 0; i < noUzunlugu; ++i) no[i] = assigmentOgrenci.no[i]; return *this; } //char* tutulan renci nosunu double a evirme double cevirme() const { double carpan = noUzunlugu*10; double numara = 0; double temp; int sayilar[] = { 48, 49, 50, 51, 52, 53, 54, 55, 56, 57}; for (unsigned i = 0; i < noUzunlugu; ++i) { for (int j = 0; j < 10; ++j) if ((int)no[i] == sayilar[j]) temp = j; numara += temp * carpan; carpan /= 10; } return numara; } //renci nosuna gre karlatrma yapan < oparatr bool operator <(const Ogrenci& ogr) { if (this->cevirme() < ogr.cevirme()) return true; return false; } //renci nosuna gre karlatrma yapan > oparatr bool operator >(const Ogrenci& ogr) { if (this->cevirme() > ogr.cevirme()) return true; return false; } //renci nosuna gre karlatrma yapan == oparatr bool operator ==(const Ogrenci& ogr) { if (this->cevirme() == ogr.cevirme()) return true; return false; } private: char *ad; unsigned adUzunlugu; char *no; unsigned noUzunlugu; };
true
d0942aa6dab1e3512e285749d096a17942e597b3
C++
nickel8448/cpp
/src/leetcode/graph/reconstrust_itenary.cpp
UTF-8
2,058
3.515625
4
[]
no_license
/** * @file reconstrust_itenary.cpp * @author Rahul Wadhwani * @brief * @version 0.1 * @date 2020-06-04 * * @copyright Copyright (c) 2020 * Apporach: hierholzer's algorithm to construct a eucledian path of the itenary * Status: Completed */ #include <algorithm> #include <functional> #include <iostream> #include <queue> #include <string> #include <unordered_map> #include <vector> using std::string; using std::vector; typedef std::priority_queue<string, vector<string>, std::greater<string>> pq; typedef std::unordered_map<string, pq> mp; void dfs(string origin, vector<string> &result, mp &adj_list) { // 1. Check if this is an airport of origin if (adj_list.find(origin) != adj_list.end()) { pq &destination_list = adj_list.at(origin); while (!destination_list.empty()) { string destination = destination_list.top(); destination_list.pop(); dfs(destination, result, adj_list); } } result.push_back(origin); } vector<string> findItinerary(vector<vector<string>> &tickets) { // graph adjacency map mp adj_list; // Create the graph for (size_t i = 0; i < tickets.size(); ++i) { string airport = tickets.at(i).at(0), dest = tickets.at(i).at(1); if (adj_list.find(airport) != adj_list.end()) { adj_list.at(airport).push(dest); } else { pq new_pq; new_pq.push(dest); adj_list.insert(std::make_pair(airport, new_pq)); } } vector<string> result; dfs("JFK", result, adj_list); std::reverse(result.begin(), result.end()); return result; } int main() { vector<vector<string>> tickets = { {"MUC", "LHR"}, {"JFK", "MUC"}, {"SFO", "SJC"}, {"LHR", "SFO"}}; vector<vector<string>> tickets2 = {{"JFK", "SFO"}, {"JFK", "ATL"}, {"SFO", "ATL"}, {"ATL", "JFK"}, {"ATL", "SFO"}}; vector<vector<string>> tickets3 = { {"JFK", "KUL"}, {"JFK", "NRT"}, {"NRT", "JFK"}}; findItinerary(tickets3); return 0; }
true
be3e61017d93b22b263674ab402c022216f0106a
C++
BOTSlab/bupimo_src
/homing_algs/old_src/img/drawKeys.cpp
UTF-8
1,076
2.953125
3
[]
no_license
#include "ImgWindow.h" #include "ImgOps.h" #include "SiftExtractor.h" void drawKeys(string name, vector<Keypoint*> &keys, Img &src, ImgWindow &window) { // Create a copy of the input image and draw dots at the locations of // the keypoints. Img* drawImg = new Img(src); window.addImg(name, *drawImg); window.drawKeypoints(keys, 0, 0, 1); delete drawImg; } int main( int argc, char *argv[] ) { if (argc < 3 || ((argc+1) % 2) != 0 ) // Should be an odd number >= 3 { cout << "usage:\n\tdrawKeys IMAGE_1 IMAGE_2 KEYS_1 KEYS_2 ...\n"; cout << "argc: " << argc << endl; return 0; } ImgWindow window(""); int n = (argc - 1) / 2; for (int i=0; i<n; i++) { string imgFilename(argv[i+1]); Img img(imgFilename); string keyFilename(argv[i+1+n]); vector<Keypoint*> keys; SiftExtractor::loadKeys(keyFilename, keys); drawKeys(keyFilename, keys, img, window); SiftExtractor::clearKeys(keys); } window.interact(); return 0; }
true
d0f006d1ac91ec44013414a0dfdaba992ae90168
C++
autyinjing/Cpp-learning
/C++ Primer plus/2_begin/example/carrots.cpp
UTF-8
790
2.90625
3
[]
no_license
/* * ===================================================================================== * * Filename: carrots.cpp * * Description: * * Version: 1.0 * Created: 2014年08月20日 10时46分21秒 * Revision: none * Compiler: gcc * * Author: Aut(yinjing), linuxeryinjing@gmail.com * Company: Class 1201 of Information and Computing Science * * ===================================================================================== */ #include <iostream> int main( int argc, char *argv[] ) { using namespace std; int carrots; carrots = 25; cout << "I have "; cout << carrots; cout << " carrots."; cout << endl; carrots = carrots - 1; cout << "Crunch, crunch. Now I have " << carrots << " carrots." << endl; return 0; }
true
2b191155d20441004566d957dd7559047c37a5cd
C++
wspires/Lin-Lab
/Lin Lab/exp_eval/Expression_Evaluator.hpp
UTF-8
1,907
2.515625
3
[]
no_license
// // Expression_Evaluator.hpp // Lin Lab // // Created by Wade Spires on 1/22/12. // Copyright (c) 2012 __MyCompanyName__. All rights reserved. // #ifndef EXPRESSION_EVALUATOR_HPP #define EXPRESSION_EVALUATOR_HPP #include "All_Functions.hpp" #include "All_Operators.hpp" // c++ headers #include <string> #include <vector> namespace exp_eval { class Expression_Evaluator { public: typedef std::vector<std::string> Vec_Str; // Single operator or function result as generated by evaluate_rpn(). struct Result { enum Result_Type { Op = 0, Func = 1, Ident = 2 }; Result() { } // Operator or function name. std::string in_name; // Whether in_name is an operator, function, or identifier. Result_Type result_type; // Name of output result. std::string out_name; // Arguments to operator or function. Vec_Str args; std::string to_string() const; }; typedef std::vector<Result> Vec_Result; Expression_Evaluator(char dec_sep = '.'); Vec_Str tokenize(std::string const & expression); Vec_Str to_rpn(Vec_Str const & tokens, std::string & error); Vec_Result evaluate_rpn(Vec_Str const & tokens_rpn, std::string & error); bool is_identifier(std::string token); protected: void handle_unary_op_check(char c , char prev_c , Vec_Str & tokens , std::string & token ); bool is_part_of_ident_token(char c); bool is_not_part_of_ident_token(char c); bool is_comparison_op(char c); private: All_Operators all_operators_; All_Functions all_functions_; char dec_sep_; }; } // namespace exp_eval #endif // EXPRESSION_EVALUATOR_HPP
true
566d9ad5877cbbd34332d51aaae36c5aab47a73a
C++
katy1819/Bioinformatika
/Bioinform3/Bioinf/Main.cpp
WINDOWS-1251
584
2.84375
3
[]
no_license
#include <string> #include <iostream> using namespace std; void main() { setlocale(LC_ALL, "Russian"); string s1, s2, s3; int n, g = 0; cout << " : " << endl; getline(cin, s1); n = s1.length(); for (int i = n - 1; i > -1; i--) { s2 += s1[i]; } cout << " : " << s2 << endl; for (int j = 0; j < n; j++) { if (s2[j] == 'A') s2[j] = 'T'; else if (s2[j] == 'T') s2[j] = 'A'; else if (s2[j] == 'C') s2[j] = 'G'; else if (s2[j] == 'G') s2[j] = 'C'; } cout << ": " << s2 << endl; }
true
3783eeb7c5e9e295c5243b8c89b4ba2110dac15b
C++
mrezvani110/ktruss
/Graph.h
UTF-8
2,539
2.953125
3
[]
no_license
#ifndef GRAPH_H #define GRAPH_H #include "BipartiteTriangleGraph.h" #include "SimpleTriangleGraph.h" #include "EvaluationResults.h" class BipartiteTriangleGraph; class SimpleTriangleGraph; /* struct Key { int source; int destination; bool operator==(const Key &other) const { return ((source == other.source && destination == other.destination) || (source == other.destination && destination == other.source)); } }; namespace std::tr1 { template <> struct hash<Key> { size_t operator()(const Key& k) const { // Compute individual hash values for source // and destination and combine them using XOR // and bit shifting: return (hash<int>()(k.source) ^ (hash<int>()(k.destination) << 1)); } }; } */ class Edge { public: Edge *pre, *next; Edge *duplicate; int node_id; bool isInTriangle; #ifdef TRIANGLE_GRAPH list<pair<Edge *, Edge*> > l; int color; int weight; int index; int indexInTriGraph; Edge(): isInTriangle(false), color(0), weight(0), index(0) {} #endif }; class Node { public: int deg; // Degree of this node; number of neighbours of this node int color; Edge *first, *last; Node(): deg(0), color(0), first(NULL), last(NULL) {} }; class Graph { private: int n,m; // Number of nodes and edges int k; Node *nodes; Edge *edges; int *edgesBitStream; public: EvaluationResults evalResults; public: Graph(); ~Graph(); void read_input(char* input); void add_edge(Node &node, Edge *edge); void delete_edge(Node &node, Edge *edge); void core_decomposition(); void truss_decomposition(int _k, bool isSimpleTG); TriangleGraph *generate_triangle_graph(bool isSimpleTG); void bipartite_truss_decomposition(int _k); void simple_truss_decomposition(int _k); BipartiteTriangleGraph *generate_bipartite_triangle_graph(); SimpleTriangleGraph *generate_simple_triangle_graph(); int traverseTriangles(); int traverseTriangles(TriangleGraph *triGraph); void setEdgeBitStream(int u); void resetEdgeBitStream(int u); int getUndeletedEdgeNo(); int getEdgeInTrianglesNo(); void resetAllEdgeBitStream(); void printNode(int p); #ifdef TRIANGLE_GRAPH void print_triangle_graph(); void print_triangle_graph2(); void sort(); #endif void print(); void printSummary(); void printAdjacencyMatrix(); void printTriangle(int i, int j, int k); }; #endif /* GRAPH_H */
true