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
413260b34349b5cd5bac5008c5af9203974fca2e
C++
mridul-mc/all_oop_cpp
/inline_function.cpp
UTF-8
187
2.796875
3
[]
no_license
#include<iostream> #include<conio.h> using namespace std; int add(int x,int y); inline int add(int x,int y) { return(x+y); } int main() { int a=10,b=20; cout<<add(a,b); }
true
b1a91357c297557c9858e24d29a7b14d4de06c12
C++
clashroyaleisgood/Courses
/進階程式設計/Project - Mini Monopoly/Map.h
UTF-8
3,705
2.65625
3
[]
no_license
#ifndef MAP_H #define MAP_H #include <iostream> #include <cstdio> #include <stdexcept> bool do_decision(); enum LandType {U,C,R,J,Ndef}; constexpr int MaxPeopleNum = 4; constexpr int MaxFineNum = 5; constexpr int MaxLandNum = 20; constexpr int MaxUpgradLV = 5; class WorldPlayer; class MapUnit { public: MapUnit() {} MapUnit(LandType type,int id,const std::string &name,int price,int fine): type_(type),id_(id),name_(name),price_(price),fine_(fine) {} virtual ~MapUnit(){} //-----return private var----- LandType type()const{ return type_; } int LandId()const { return id_; } const std::string LandName()const { return name_; } int Price()const { return price_; } int WhoOwn()const { return who_own_; } const bool* WhoIsHere()const { return who_is_here_; } int HowManyPeople()const { return how_many_people_; } //----set---- void SetOwn(const int owner) { who_own_ = owner; } void Leave(const int index); void Enter(const int index); virtual void Reset(); //----what will do in this land---- virtual void Event(WorldPlayer &p, int ind) = 0; //virtual void Event(WorldPlayer &p, int ind); virtual int Fine()const { return fine_; } virtual void Print(int collectable_sum) const =0; private: LandType type_ = Ndef; int id_ = -1; std::string name_ = "ndef"; int price_ = -1; bool who_is_here_[MaxPeopleNum] = {}; int how_many_people_ = 0; protected: int who_own_ = -1; int fine_ = -1; }; class Upgradable : public MapUnit { public: Upgradable() = default; virtual ~Upgradable(){} Upgradable(int id,const std::string &name,int price,int upgrade_cost,const int fine[]): MapUnit(U,id,name,price,-1),upgrade_cost_(upgrade_cost) { for(int i=0 ; i<MaxFineNum ; i+=1) fine_[i] = fine[i]; } virtual void Event(WorldPlayer &p, int ind); virtual void Reset(); virtual int Fine()const; virtual void Print(int collectable_sum)const; private: int LV_ = 1; int upgrade_cost_ = -1; int fine_[MaxFineNum] = {} ; }; class Collectable : public MapUnit { public: Collectable() = default; virtual ~Collectable(){} Collectable(int id,const std::string &name,int price,int fine): MapUnit(C,id,name,price,fine) {} virtual void Event(WorldPlayer &p, int ind); virtual void Print(int collectable_sum)const; }; class RandomCost : public MapUnit { public: RandomCost() = default; virtual ~RandomCost(){} RandomCost(int id,const std::string &name,int price,int fine): MapUnit(R,id,name,price,fine) {} virtual void Event(WorldPlayer &p, int ind); virtual void Print(int collectable_sum)const; }; class Jail : public MapUnit { public: Jail() = default; virtual ~Jail(){} Jail(int id,const std::string &name): MapUnit(R,id,name,-1,-1) {} virtual void Event(WorldPlayer &p, int ind); virtual void Print(int collectable_sum)const; }; class WorldMap { public: void Add(Upgradable &U); void Add(Collectable &C); void Add(RandomCost &R); void Add(Jail &J); WorldMap() {} WorldMap(const WorldMap &) = delete; WorldMap & operator = (const WorldMap &) = delete; MapUnit* Land(int ind)const { return units_[ind]; } MapUnit* operator[](int index) { return (units_[index]); } const MapUnit* operator[](int index) const { return (units_[index]); } int num_of_unit()const {return now_;} virtual ~WorldMap(); private: MapUnit* units_[MaxLandNum]= {}; int now_ = 0; }; #endif // MAP_H
true
4a72f9dbda5f67db420656b94b4c6e92469adb25
C++
DcmTruman/my_acm_training
/POJ/3259/15516338_AC_344ms_1532kB.cpp
UTF-8
1,470
2.5625
3
[]
no_license
#include<iostream> #include<algorithm> #include<string.h> #include<string> #include<queue> #include<vector> #include<map> #define clr(x,b) memset(x,(b),sizeof(x)) #define fuck cout<<"fuck:"<<__LINE__<<endl; using namespace std; const int maxn = 100200; const int maxm = 100200; int n,m,w; int ct = 0; int dis[maxn]; bool inq[maxn]; int head[maxn]; int num[maxn]; struct edge{ int to; int len; int next; }E[maxm]; struct node{ int x; int dis; bool operator < (const node b)const{ return dis<b.dis; } }; void addedge(int u,int v,int w){ E[ct].to = v; E[ct].len = w; E[ct].next = head[u]; head[u] = ct++; } bool spfa(){ queue<int>Q; int st = 1; dis[st] = 0; Q.push(st); inq[st] = true; num[st]++; while(!Q.empty()){ int t = Q.front(); Q.pop(); inq[t] = false; for(int i = head[t];i!=-1;i = E[i].next){ int d = E[i].to; // if(inq[d])continue; if(dis[d]>dis[t]+E[i].len){ //fuck dis[d] = dis[t]+E[i].len; if(!inq[d]){ inq[d] = true; Q.push(d); num[d]++; if(num[d]>n)return true; } } } } return false; } int main(){ int T; cin>>T; while(T--){ clr(head,-1); ct = 0; clr(dis,0x3f3f3f3f); clr(num,0); clr(inq,0); cin>>n>>m>>w; for(int i = 0;i<m;i++){ int u,v,l;cin>>u>>v>>l; addedge(u,v,l); addedge(v,u,l); } for(int i = 0;i<w;i++){ int u,v,l;cin>>u>>v>>l; addedge(u,v,-l); } if(spfa())cout<<"YES"<<endl; else cout<<"NO"<<endl; } //fuck }
true
9aa52278545f2bed23061ce19d48e120f8eb6362
C++
elfortitude/cpp_white_belt
/week_3/algorithms/sort_mod.cpp
UTF-8
465
2.9375
3
[]
no_license
/* * Отсортируйте массив А по модулю и выведите его в стандартный поток. */ #include <iostream> #include <vector> #include <algorithm> #include <cmath> using namespace std; int main(void) { int n; cin >> n; vector<int> A(n); for (auto& i : A) cin >> i; sort(begin(A), end(A), [](int x, int y){return(abs(x) < abs(y));}); for (const auto& i : A) cout << i << " "; cout << endl; return 0; }
true
015bcdfd9c5e4bd9f605092483c05545db5593f5
C++
MuditSrivastava/SPOJ_SOL
/LITE/13058456.cpp
UTF-8
1,435
2.78125
3
[]
no_license
#include<iostream> #include<cstdio> using namespace std; int tree[400004]; int lazy[400004]; void update(int tl,int tr,int l,int r,int node) { int mid=(tl+tr)/2; if(lazy[node]) { tree[node]=(tr-tl+1)-tree[node]; if(tl!=tr) { lazy[node*2]^=1; lazy[node*2+1]^=1; } lazy[node]=0; } if(tl>tr || l>tr || tl>r) return; if(tl>=l && r>=tr) { tree[node]=(tr-tl+1)-tree[node]; if(tl!=tr) { lazy[node*2]^=1; lazy[node*2+1]^=1; } return; } update(tl,mid,l,r,node*2); update(mid+1,tr,l,r,node*2+1); tree[node]=tree[node*2]+tree[node*2+1]; } int query(int tl,int tr,int l,int r,int node) { if(tl>tr || l>tr || tl>r) return 0; int mid=(tl+tr)/2; if(lazy[node]) { tree[node]=(tr-tl+1)-tree[node]; if(tl!=tr) { lazy[node*2]^=1; lazy[node*2+1]^=1; } lazy[node]=0; } if(tl>=l && r>=tr) { return tree[node]; } return query(tl,mid,l,r,node*2)+query(mid+1,tr,l,r,node*2+1); } int main() { int n,q; scanf("%d %d",&n,&q); int i,x,y; while(q--) { scanf("%d %d %d",&i,&x,&y); if(i==0) { update(1,n,x,y,1); } else { printf("%d\n",query(1,n,x,y,1)); } } return 0; }
true
b2cc7b8f7e17fd26c05b4f640603cb658ed51638
C++
n7kurosawa/quicksort_mm
/src/cc/quicksort_mm.hh
UTF-8
8,401
2.84375
3
[]
no_license
// Written in 2016 by n.kurosawa // // This program is under the CC0 Public Domain Dedication 1.0. // See <http://creativecommons.org/publicdomain/zero/1.0/> for details. // This program is distributed without any warranty. // ====================================================== // Quicksort/Quickselect with median of medians in C++ language. // // This routine combines the following ideas: // * quicksort and quickselect[1], of course. // * median of medians or BFPRT[2]. // * repeated step algorithms[3]. // * square root sampling[4]. // * thinning at the pivot selection[5]. // // [1] C.A.R. Hoare, Commun. ACM 4, 321 (1961). // [2] M. Blum, et al., J. Comput. Syst. Sci. 7, 448 (1973). // [3] K. Chen, A. Dumitrescu, arXiv:1409.3600 [cs.DS] (2014). // [4] C.C. McGeoch, J.D. Tygar, Random Struct. Alg. 7, 287 (1995). // [5] N. Kurosawa, arXiv:1698.04852 [cs.DS] (2016). // ====================================================== #ifndef QUICKSORT_MM_HH_INCLUDED #define QUICKSORT_MM_HH_INCLUDED #include <algorithm> #include <utility> namespace quicksort_mm { // ====================================================== // Utilities // ====================================================== // Get the median of given three elements. template<class RAIt, class Cmp> inline RAIt median3(RAIt a, RAIt b, RAIt c, Cmp cmp) { return cmp(*a, *b) ? (cmp(*b, *c) ? b : (cmp(*a, *c) ? c : a)) : (cmp(*a, *c) ? a : (cmp(*b, *c) ? c : b)); } // Get the median of given five elements. template<class RAIt, class Cmp> inline RAIt median5(RAIt a, RAIt b, RAIt c, RAIt d, RAIt e, Cmp cmp) { if (cmp(*b, *a)) std::swap(a, b); if (cmp(*d, *c)) std::swap(c, d); if (cmp(*c, *a)) { std::swap(a, c); std::swap(b, d); } if (cmp(*e, *b)) std::swap(b, e); if (cmp(*c, *b)) { return cmp(*d, *b) ? d : b; } else { return cmp(*e, *c) ? e : c; } } // Simple insertion sort template<class RAIt, class Cmp> inline void insertion_sort(RAIt first, RAIt last, Cmp cmp) { if (first == last) return; for (auto current = first+1; current != last; current++) { if (cmp(*current, *(current-1))) { auto cursor = current; auto target = *current; do { *cursor = *(cursor-1); cursor--; } while (first != cursor && cmp(target, *(cursor-1))); *cursor = target; } } } // Hoare's Partition template<class RAIt, class Cmp> RAIt partition(RAIt first, RAIt last, RAIt pivot, Cmp cmp) { if (first != pivot) std::swap(*first, *pivot); pivot = first; auto lo = first, hi = last; for (;;) { for (;;) { hi--; if (lo == hi) goto PARTITION_END; if (!cmp(*pivot, *hi)) break; } for (;;) { lo++; if (lo == hi) goto PARTITION_END; if (!cmp(*lo, *pivot)) break; } std::swap(*lo, *hi); } PARTITION_END:; std::swap(*pivot, *lo); return lo; } // approximate square root inline size_t approx_sqrt(size_t n) { int base = -1; while (0 < n) { base += 1; n /= 4; } return 1 << base; } // ====================================================== // Median of Medians // ====================================================== template<class RAIt, class Cmp> RAIt rs3_5_2_pick_pivot(RAIt first, RAIt last, Cmp cmp, size_t s=2); template<class RAIt, class Cmp> RAIt rs3_5_2_find_kth(RAIt first, RAIt last, size_t k, Cmp cmp, size_t s=2); // A variant of the repeated step algorithm (3-5). // 3-3 and 4-4 are presented in the original paper. template<class RAIt, class Cmp> RAIt rs3_5_2_pick_pivot(RAIt first, RAIt last, Cmp cmp, size_t s) { if (s < 2) s = 2; size_t nelem = last - first; // The cutoff value 15 is taken as in the paper: // M. Durand, Inf. Process. Lett. 85, 73 (2003). if (nelem < 15) return first + nelem/2; // The following cutoff values are not optimized and should be refined. if (nelem < 80) return median3(first, first+nelem/2, last-1, cmp); if (nelem < s*30 || nelem < 200) return median5(first, first+nelem/4, first+nelem/2, first+3*nelem/4, last-1, cmp); size_t nnext = nelem/(15*s); auto p = first + 0*(nelem/15); auto q = first + 7*(nelem/15); auto r = last - 7*nnext; for (size_t i = 0; i < nnext; i++) { // median of 5 (median of 3) auto x0 = median3(p+i*7+0, p+i*7+1, p+i*7+2, cmp); auto x1 = median3(p+i*7+3, p+i*7+4, p+i*7+5, cmp); auto x2 = median3(p+i*7+6, q+i, r+i*7+0, cmp); auto x3 = median3(r+i*7+1, r+i*7+2, r+i*7+3, cmp); auto x4 = median3(r+i*7+4, r+i*7+5, r+i*7+6, cmp); auto xx = median5(x0, x1, x2, x3, x4, cmp); if (xx != q+i) std::swap(*xx, *(q+i)); } // Get the median of (pseudo-) medians return rs3_5_2_find_kth(q, q+nnext, nnext/2, cmp, s); } template<class RAIt, class Cmp> RAIt rs3_5_2_find_kth(RAIt first, RAIt last, size_t k, Cmp cmp, size_t s) { size_t nelem = last - first; if (nelem < 7) { insertion_sort(first, last, cmp); return first+k; } auto pivot = rs3_5_2_pick_pivot(first, last, cmp, s); auto pivotx = partition(first, last, pivot, cmp); size_t nl = pivotx - first; // Recursive application if (nl < k) { return rs3_5_2_find_kth(pivotx + 1, last, k-nl-1, cmp); } else if (k < nl) { return rs3_5_2_find_kth(first, first+nl, k, cmp); } else { return pivotx; } } // ====================================================== // Quicksort with median of medians // // asymptotic comparison number for arrays of size N: // Random: 1.44 N ln N + o(N ln N) // Worst: 14.76 N ln N + o(N ln N) // ====================================================== template<class RandomAccessIterator, class Compare> void quicksort_body(RandomAccessIterator first, RandomAccessIterator last, Compare cmp, size_t s) { size_t nelem = last - first; if (s < 10) s = 10; // Boundary condition if (nelem < 16) { insertion_sort(first, last, cmp); return; } // Partition auto pivot = rs3_5_2_pick_pivot(first, last, cmp, s); auto pivot_position = partition(first, last, pivot, cmp); // Recursive application // The tail call optimization is assumed // 12/17 ~ 0.7059 is an approximate value of sqrt(1/2) if (last - pivot_position < pivot_position - first) { quicksort_body(pivot_position+1, last, cmp, s*12/17); quicksort_body(first, pivot_position, cmp, s*12/17); } else { quicksort_body(first, pivot_position, cmp, s*12/17); quicksort_body(pivot_position+1, last, cmp, s*12/17); } } template<class RandomAccessIterator, class Compare> void quicksort(RandomAccessIterator first, RandomAccessIterator last, Compare cmp) { size_t nelem = last-first; quicksort_body(first, last, cmp, approx_sqrt(nelem)); } template<class RandomAccessIterator> void quicksort(RandomAccessIterator first, RandomAccessIterator last) { std::less<typename std::iterator_traits<RandomAccessIterator>::value_type> cmp; quicksort(first, last, cmp); } // ====================================================== // Quickselect with median of medians // // asymptotic comparision number for arrays of size N: // Random: 2.76 N + o(N) // Worst: 26.50 N + o(N) // ====================================================== template<class RandomAccessIterator, class Compare> void quickselect(RandomAccessIterator first, RandomAccessIterator kth, RandomAccessIterator last, Compare cmp) { size_t k = kth - first; size_t nelem = last - first; if (nelem <= k) return; rs3_5_2_find_kth(first, last, k, cmp, approx_sqrt(nelem)); } template<class RandomAccessIterator> void quickselect(RandomAccessIterator first, RandomAccessIterator kth, RandomAccessIterator last) { std::less<typename std::iterator_traits<RandomAccessIterator>::value_type> cmp; quickselect(first, kth, last, cmp); } } #endif
true
dbf5bfd3472a7d8bb53fdc99dae900a2926381d4
C++
jahendrie/belted
/src/events.cpp
UTF-8
20,471
3.640625
4
[ "Zlib" ]
permissive
/******************************************************************************* * events.cpp * * This file controls all input received from the player, routing events to * their correct places or otherwise taking appropriate action. * *******************************************************************************/ #ifndef UTIL_H #include "util.h" #endif /* -------------------------------------------------------------------------------- SET LETTER -------------------------------------------------------------------------------- * Used on the 'enter high score' screen, when the player just starts typing * on the keyboard. Sets the currently highlighted initial to the letter * pressed and then switches focus to the next letter. */ void set_letter( char key ) { /* Init focus variable to zero -- it will be reset later */ int focus = 0; /* * Go through the initials, checking for focus, and sending the given key * value to whichever initial has the focus */ for( int i = 0; i < 3; ++i ) { if( initials[ i ]->has_focus() ) { initials[ i ]->set_letter( key ); initials[ i ]->update_letter_texture(); initials[ i ]->set_focus( false ); /* Switch focus to the next initial */ focus = i + 1; } } /* Correct focus if it went too high / low */ if( focus < 0 ) focus = 2; else if( focus > 2 ) focus = 0; /* Move on */ initials[ focus ]->set_focus( true ); } /* -------------------------------------------------------------------------------- SWITCH FOCUS -------------------------------------------------------------------------------- * Used on the 'enter high score' screen, when the user presses the left or * right arrow key. */ void switch_focus( int direction ) { /* Init current focus to zero */ int currentFocus = 0; /* Find the initial that has focus with a for loop */ for( int i = 0; i < 3; ++i ) { if( initials[ i ]->has_focus() ) { /* Set focus integer to match the initial with focus */ currentFocus = i; break; } } /* Adjust the focus in whichever direction the user indicated */ currentFocus += direction; /* * Here we correct the focus: Too far left and we wrap around to the max * value (2), putting the focus on the right-most initial. Too far right * and we wrap around to 0, the left-most initial. */ if( currentFocus < 0 ) currentFocus = 2; else if( currentFocus > 2 ) currentFocus = 0; /* * Go through the initials and correct their 'focus' value to true if their * position in the initials array corresponds with the current focus * variable or false if it doesn't. */ for( int i = 0; i < 3; ++i ) { if( i == currentFocus ) initials[ i ]->set_focus( true ); else initials[ i ]->set_focus( false ); } } /* -------------------------------------------------------------------------------- SWITCH LETTER -------------------------------------------------------------------------------- * Used by the 'enter high score' screen, this function adjusts the selected * initial's letter 'up' or 'down' according to which direction was indicated * by the user; -1 for up, 1 for down. -1 is given when the user presses up * on the keyboard or scrolls the mouse wheel up. +1 is given when the user * presses down on the keyboard or scrolls the mouse wheel down. */ void switch_letter( int direction ) { /* * Go through the initials array and switch the letter for whichever * initial has focus according to the direction given. */ for( int i = 0; i < 3; ++i ) { if( initials[ i ]->has_focus() ) { if( direction < 0 ) initials[ i ]->letter_up(); else if( direction > 0 ) initials[ i ]->letter_down(); } } } /* -------------------------------------------------------------------------------- MAIN EVENTS -------------------------------------------------------------------------------- * This function handles all events on the main screen - that is, the screen * where the player is actually playing the game rather than a menu or some * information screen. */ void events_main( SDL_Event &e ) { /* Send all mouse motion events straight to the player class */ if( e.type == SDL_MOUSEMOTION ) player.move_mouse(); /* Mouse button events are less complex and can be handled here */ if( e.type == SDL_MOUSEBUTTONUP ) { /* Left click: Honk horn */ if( e.button.button == SDL_BUTTON_LEFT ) player.honk(); /* Right-click: Activate power (or make an 'engine stall' sound) */ if( e.button.button == SDL_BUTTON_RIGHT ) player.init_power(); /* Middle click: Pause the game */ if( e.button.button == SDL_BUTTON_MIDDLE ) { /* Pause the game and transition to the menu screen */ gamePaused = true; start_transition( SCREEN_MENU, DIRECTION_DOWN ); /* If the music is playing, pause it */ if( Mix_PlayingMusic() == 1 ) Mix_PauseMusic(); } } /* If the player has pressed (and released) a key */ if( e.type == SDL_KEYUP ) { switch( e.key.keysym.sym ) { /* * If the player pressed ESCAPE, pause the game, transition to the * menu screen and pause the music. */ case SDLK_ESCAPE: gamePaused = true; start_transition( SCREEN_MENU, DIRECTION_DOWN ); if( Mix_PlayingMusic() == 1 ) Mix_PauseMusic(); break; /* If the player pressed Q, quit the game */ case SDLK_q: quit = true; break; /* If the player pressed S, toggle sound effects on/off */ case SDLK_s: toggle_sounds(); break; /* If the player pressed M, toggle the music on/off */ case SDLK_m: toggle_music(); break; /* SPACE honks the horn */ case SDLK_SPACE: player.honk(); break; /* SHIFT activates (or attempt to activate) the power */ case SDLK_LSHIFT: player.init_power(); break; } } } /* -------------------------------------------------------------------------------- MENU EVENTS -------------------------------------------------------------------------------- * This function handles events received from the player on the menu screen. */ void events_menu( SDL_Event &e ) { /* Just send these to the menuScreen object */ menuScreen->handle_events( e ); } /* -------------------------------------------------------------------------------- GAME OVER EVENTS -------------------------------------------------------------------------------- * This function handles events received from the player on the game over * screen. */ void events_game_over( SDL_Event &e ) { /* If the player clicked the mouse */ if( e.type == SDL_MOUSEBUTTONUP ) { /* * We check to see that a slight delay has passed before processing * events; that way, a player can't accidentally click himself off of * this screen to parts unknown before he's even realized that his * space car was destroyed. */ if( ( SDL_GetTicks() - miscTicks ) > (10 * FPS) ) { /* Left mouse button */ if( e.button.button == SDL_BUTTON_LEFT ) { /* If their score is good enough, they can register it */ if( gScores->score_qualifies( currentScore ) ) enter_high_score(); // Send to 'enter high scores' scrn /* * Otherwise, they are instead given the opportunity to gawk at * the prowess of superior space car pilots by sending them * directly to the high scores screen. */ else { /* Update all the scores */ gScores->update(); /* Transition to high scores screen */ start_transition( SCREEN_HIGH_SCORES, DIRECTION_LEFT ); } } /* * The right mouse button always means "I just want to get back to * playing, and I don't give a shit about seeing or entering any * scores". */ else if( e.button.button == SDL_BUTTON_RIGHT ) { /* Reset everything */ reset(); /* Transition back to the main screen */ start_transition( SCREEN_MAIN, DIRECTION_DOWN ); } } } /* If the player has pressed a key */ if( e.type == SDL_KEYUP ) { switch( e.key.keysym.sym ) { /* Escape is the same as RMB above; return to play immediately */ case SDLK_ESCAPE: reset(); start_transition( SCREEN_MAIN, DIRECTION_DOWN ); break; /* Q, as always, quits the game */ case SDLK_q: quit = true; break; /* Any other key will act as LMB above */ default: if( gScores->score_qualifies( currentScore ) ) enter_high_score(); else { gScores->update(); start_transition( SCREEN_HIGH_SCORES, DIRECTION_LEFT ); } break; } } } /* -------------------------------------------------------------------------------- HIGH SCORES SCREEN EVENTS -------------------------------------------------------------------------------- * This function defines the behavior of the high scores screen according to * input received from the player. */ void events_high_scores( SDL_Event &e ) { /* If the player clicked the mouse */ if( e.type == SDL_MOUSEBUTTONUP ) { /* * LMB either returns to the menu or returns to play, depending on if * the player has paused/just started the game, or has died and is just * waiting to get back to play. */ if( e.button.button == SDL_BUTTON_LEFT ) { /* If paused / just started, return to menu */ if( gamePaused || currentScore == 0 ) start_transition( SCREEN_MENU, DIRECTION_RIGHT ); /* If previously killed, reset everything and return to play */ else { reset(); start_transition( SCREEN_MAIN, DIRECTION_DOWN ); } } /* If the player clicked the right mouse button */ else if( e.button.button == SDL_BUTTON_RIGHT ) { /* If the player has paused or just started, return to menu */ if( gamePaused || currentScore == 0 ) start_transition( SCREEN_MENU, DIRECTION_RIGHT ); /* * If the player was killed and their score qualified, return to * play; this is here to prevent people from entering their score * multiple times. I'm too lazy to fix it the proper way, at least * for now. */ else if( gScores->score_qualifies( currentScore ) ) { reset(); start_transition( SCREEN_MAIN, DIRECTION_DOWN ); } /* * If their score didn't qualify, they can return to the game over * screen to be reminded of how big a loser they are */ else start_transition( SCREEN_GAME_OVER, DIRECTION_RIGHT ); } } /* If the player pressed and then released a key */ if( e.type == SDL_KEYUP ) { switch( e.key.keysym.sym ) { /* Q quits */ case SDLK_q: quit = true; break; /* Anything else returns to play or returns to menu */ default: if( gamePaused || currentScore == 0 ) start_transition( SCREEN_MENU, DIRECTION_RIGHT ); else { reset(); start_transition( SCREEN_MAIN, DIRECTION_DOWN ); } break; } } } /* -------------------------------------------------------------------------------- HIGH SCORE -------------------------------------------------------------------------------- * This function does the actual entering of the score according to both the * current score and the selected initials */ void enter_score( void ) { /* A short string to hold the character (initials) data in */ char jHancock[ 3 ]; /* Grab the initials, put them into the string */ for( int i = 0; i < 3; ++i ) { jHancock[ i ] = initials[ i ]->get_letter(); } /* Update the scores with the current score and the initials */ gScores->add_score( currentScore, jHancock ); gScores->update(); /* Go back to the high scores screen */ start_transition( SCREEN_HIGH_SCORES, DIRECTION_LEFT ); } /* -------------------------------------------------------------------------------- ENTER HIGH SCORE EVENTS -------------------------------------------------------------------------------- * Event handling for the 'enter high score' screen */ void events_enter_high_score( SDL_Event &e ) { /* If the player clicked the mouse */ if( e.type == SDL_MOUSEBUTTONUP ) { /* Right mouse button -- move backward through the initials */ if( e.button.button == SDL_BUTTON_RIGHT ) { /* If they haven't clicked anything yet, go back to game over */ if( initialsClicked == 0 ) start_transition( SCREEN_GAME_OVER, DIRECTION_DOWN ); /* Otherwise, switch the focus backward */ else { switch_focus( -1 ); --initialsClicked; // Decrement initials clicked } } /* Left mouse button -- progress forward through initials */ else if( e.button.button == SDL_BUTTON_LEFT ) { /* * If they've already selected two initials previously, this final * selected initial will enter the score */ if( initialsClicked == 2 ) enter_score(); /* Otherwise, move the focus forward through the initials array */ else { switch_focus( 1 ); ++initialsClicked; // Increment initials clicked } } } /* Mouse wheel cycles through letters */ if( e.type == SDL_MOUSEWHEEL ) { /* Move 'up' or 'down' through the alphabet with the mouse wheel */ if( e.wheel.y < 0 ) switch_letter( 1 ); else if( e.wheel.y > 0 ) switch_letter( -1 ); } /* Keyboard does various things. Just look. */ if( e.type == SDL_KEYUP ) { switch( e.key.keysym.sym ) { /* Escape returns to the game over screen */ case SDLK_ESCAPE: start_transition( SCREEN_GAME_OVER, DIRECTION_DOWN ); break; /* Left arrow key moves backward through initials */ case SDLK_LEFT: switch_focus( -1 ); break; /* Right arrow key move forward through initials */ case SDLK_RIGHT: switch_focus( 1 ); break; /* Up arrow key moves 'upward' through the alphabet */ case SDLK_UP: switch_letter( -1 ); break; /* Down arrow key moves 'downward' through the alphabet */ case SDLK_DOWN: switch_letter( 1 ); break; /* Return key confirms the initials selection */ case SDLK_RETURN: enter_score(); break; /* * By default, any other key (specifically, any other ASCII * character between the lowercase 'a' and lowercase 'z') is chosen * as the letter for the selected inital. Focus switches forward * after every keypress. */ default: if( e.key.keysym.sym >= SDLK_a && e.key.keysym.sym <= SDLK_z ) set_letter( e.key.keysym.sym ); break; } } } /* -------------------------------------------------------------------------------- HELP / CREDITS SCREEN EVENTS -------------------------------------------------------------------------------- * This function handles events on the help screen and the credits screen; they * both behave in exactly the same way, except for the direction of the * transition */ void events_help_credits( SDL_Event &e ) { // Set the direction of the transition according to which screen we're on int direction; if( currentScreen == SCREEN_HELP ) direction = DIRECTION_UP; else if( currentScreen == SCREEN_CREDITS ) direction = DIRECTION_LEFT; /* If the player clicked the mouse, just return to the menu */ if( e.type == SDL_MOUSEBUTTONUP ) start_transition( SCREEN_MENU, direction ); /* If the player pressed a button */ if( e.type == SDL_KEYUP ) { switch( e.key.keysym.sym ) { /* If the button was 'Q', quit the game */ case SDLK_q: quit = true; break; /* Otherwise, return to the menu */ default: start_transition( SCREEN_MENU, direction ); break; } } } /* -------------------------------------------------------------------------------- HANDLE EVENTS -------------------------------------------------------------------------------- * Master event handler function; this routes events to their appropriate * places according to the current screen. */ void handle_events( SDL_Event &e ) { /* Poll events here for a couple of special cases */ while( SDL_PollEvent( &e ) != 0 ) { /* If the user clicks the X button, quit the game */ if( e.type == SDL_QUIT ) quit = true; if( e.type == SDL_KEYUP ) { /* If the player hit the 'G' button, toggle mouse grabbing */ if( e.key.keysym.sym == SDLK_g ) { if( SDL_GetRelativeMouseMode() == SDL_TRUE ) SDL_SetRelativeMouseMode( SDL_FALSE ); else SDL_SetRelativeMouseMode( SDL_TRUE ); } } /* Route events to their proper functions */ if( currentScreen == SCREEN_MAIN ) events_main( e ); else if( currentScreen == SCREEN_MENU ) events_menu( e ); else if( currentScreen == SCREEN_GAME_OVER ) events_game_over( e ); else if( currentScreen == SCREEN_ENTER_HIGH_SCORE ) events_enter_high_score( e ); else if( currentScreen == SCREEN_HIGH_SCORES ) events_high_scores( e ); else if( currentScreen == SCREEN_HELP || currentScreen ==SCREEN_CREDITS) events_help_credits( e ); } /* This is outside the poll event loop to prevent keyboard delays */ player.move_keyboard(); }
true
c0fe99b5705a77b07c7bf45601006f521f7e4e5a
C++
mridulraturi7/Data-Structures
/Graph/Traversal/DFS/Iterative.cpp
UTF-8
2,200
4.1875
4
[]
no_license
/* Implementation 5. DFS Traversal of a Graph. Perform the DFS traversal of the following Graph: 0---------1 | \ | | \ | | \ | | \ | 3---------2 \ / \ / \ / \ / 4 */ #include<iostream> #include<list> #include<stack> using namespace std; class Graph { int V; list<int> *adj; public: Graph() { } Graph(int n); void addEdge(int u, int v); void dfs(int s); void printGraph(); }; Graph::Graph(int n) { this->V = n; adj = new list<int>[V]; } void Graph::addEdge(int u, int v) { adj[u].push_back(v); } void Graph::dfs(int s) { bool *visited = new bool[V]; for(int i = 0; i < V; i++) { visited[i] = false; } stack<int> st; st.push(s); visited[s] = true; list<int>::iterator it; while(st.empty() == false) { int temp = st.top(); cout<<temp<<" "; st.pop(); for(it = adj[temp].begin(); it != adj[temp].end(); it++) { if(!visited[*it]) { visited[*it] = true; st.push(*it); } } } } void Graph::printGraph() { for(int i = 0; i < V; i++) { list<int>::iterator it; cout<<"Adjacent Vertices of "<<i<<" vertex"; for(it = adj[i].begin(); it != adj[i].end(); it++) { cout<<*it<<" "; } cout<<endl; } } int main() { Graph G(5); G.addEdge(0, 1); G.addEdge(0, 2); G.addEdge(0, 3); G.addEdge(1, 0); G.addEdge(1, 2); G.addEdge(2, 0); G.addEdge(2, 1); G.addEdge(2, 3); G.addEdge(2, 4); G.addEdge(3, 0); G.addEdge(3, 2); G.addEdge(3, 4); G.addEdge(4, 2); G.addEdge(4, 3); cout<<"Graph Status (Adjacency Matrix): "<<endl; G.printGraph(); cout<<"DFS Traversal of the Graph (start vertex - 0): "; G.dfs(0); return 0; }
true
f34badfd8c5f9d890738c6a3a3ca1b378539d5ee
C++
dd-user/grapes-dd
/src/buffer.hpp
UTF-8
4,750
2.890625
3
[ "MIT" ]
permissive
/* Copyright (c) 2020 GRAPES is provided under the terms of The MIT License (MIT): Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef BUFFER_HPP #define BUFFER_HPP #include <iostream> #include <vector> /** Buffer for the data of a single graph. */ class Buffer : private std::vector<int*> { using base = std::vector<int*>; //iterator to the current buffer Buffer::iterator current; //container for output values std::vector<int> values; //iterator to the current element std::vector<int>::iterator current_value; //enable the use of values vector const bool enable_values; size_t num_current_elements; inline int* allocate() { return new int[element_size]; } public: using buffer_slot_t = std::pair<int*, bool>; //size of an internal buffer const size_t element_size; inline Buffer(size_t elem_size, bool set_values = true); inline Buffer(size_t buffersize, size_t elem_size, bool set_values=true); inline ~Buffer() { for (auto it = begin(); it != end(); ++it) delete[] *it; } inline void flush(); /** Return a pair containing a pointer to the next element available of the buffer. * and a flag setted to true if there are other elements avaiable, false otherwise. */ inline buffer_slot_t get_slot(); inline buffer_slot_t push_slot(int value); inline buffer_slot_t push_slot(); inline Buffer::base::iterator begin() { return base::begin(); } inline Buffer::base::iterator end() { return base::end(); } inline void save_value(const int v); inline int** data() { return base::data(); } inline size_t size() { return base::size(); } inline int* values_data() { return enable_values ? values.data() : nullptr; } inline unsigned num_elements() { return num_current_elements; } inline void show_content(); }; Buffer::Buffer(size_t elem_size, bool set_values) : enable_values(set_values), num_current_elements(0), element_size(elem_size) { current = begin(); } Buffer::Buffer(size_t buffersize, size_t elem_size, bool set_values) : enable_values(set_values), num_current_elements(0), element_size(elem_size) { resize(buffersize); if (enable_values) { values.resize(buffersize); current_value = values.begin(); } for (auto it = begin(); it != end(); ++it) *it = allocate(); current = begin(); } inline void Buffer::flush() { current = begin(); num_current_elements = 0; if (enable_values) current_value = values.begin(); } inline Buffer::buffer_slot_t Buffer::get_slot() { buffer_slot_t ret(*current, false); ++num_current_elements; if ((ret.second = ++current != end()) == false) current = begin(); return ret; } inline Buffer::buffer_slot_t Buffer::push_slot(int value) { buffer_slot_t ret(this->push_slot()); values.push_back(value); return ret; } inline Buffer::buffer_slot_t Buffer::push_slot() { buffer_slot_t ret(allocate(), false); base::push_back(ret.first); ++num_current_elements; return ret; } inline void Buffer::save_value(const int v) { if (enable_values) { *current_value = v; if (++current_value == values.end()) current_value = values.begin(); } } inline void Buffer::show_content() { std::cout << "Buffer has " << num_elements() << " elements\n"; for (int i = 0; i < num_current_elements; ++i) { int *p = at(i); for (int j = 0; j < element_size; ++j) { std::cout << p[j] << " "; } std::cout << " ==> " << values.at(i) << "\n"; } std::cout << std::endl; } #endif
true
ef59bcaabcc17bd4b2b2c5fd448015523d7af0ae
C++
icyleaf/omim
/base/runner.hpp
UTF-8
840
3.0625
3
[ "Apache-2.0" ]
permissive
#pragma once #include "std/function.hpp" namespace threads { typedef function<void()> RunnerFuncT; // Base Runner interface: performes given tasks. class IRunner { public: virtual ~IRunner() {} virtual void Run(RunnerFuncT const & f) const = 0; // Helper function that calls f() and catches all exception. static void CallAndCatchAll(RunnerFuncT const & f); protected: // Waits until all running threads stop. // Not for public use! Used in unit tests only, since // some runners use global thread pool and interfere with each other. virtual void Join() = 0; }; // Synchronous implementation: just immediately executes given tasks. class SimpleRunner : public IRunner { public: virtual void Run(RunnerFuncT const & f) const { IRunner::CallAndCatchAll(f); } protected: virtual void Join() { } }; }
true
50028acd1439e58308aab74ca40dbcad53369053
C++
Robotics-SLB/marnav
/src/marnav/nmea/audep.cpp
UTF-8
557
2.625
3
[ "BSD-3-Clause", "BSD-4-Clause" ]
permissive
#include "audep.hpp" #include <marnav/nmea/io.hpp> namespace marnav { namespace nmea { constexpr sentence_id audep::ID; constexpr const char * audep::TAG; audep::audep() : sentence(ID, TAG, talker_id::none) { } audep::audep(talker talk, fields::const_iterator first, fields::const_iterator last) : sentence(ID, TAG, talk) { if (std::distance(first, last) != 1) throw std::invalid_argument{"invalid number of fields in audep"}; read(*(first + 0), depth_); } void audep::append_data_to(std::string & s) const { append(s, to_string(depth_)); } } }
true
d4bc08c13aded906d49bf4c68eb2c4b735b40e67
C++
lineCode/beam
/Beam/Include/Beam/Network/MulticastSocketConnection.hpp
UTF-8
1,249
2.640625
3
[]
no_license
#ifndef BEAM_MULTICASTSOCKETCONNECTION_HPP #define BEAM_MULTICASTSOCKETCONNECTION_HPP #include <boost/noncopyable.hpp> #include "Beam/IO/Connection.hpp" #include "Beam/Network/MulticastSocket.hpp" #include "Beam/Network/Network.hpp" namespace Beam { namespace Network { /*! \class MulticastSocketConnection \brief Provides a Connection interface for a MulticastSocket. */ class MulticastSocketConnection : private boost::noncopyable { public: ~MulticastSocketConnection(); void Open(); void Close(); private: friend class MulticastSocketChannel; std::shared_ptr<MulticastSocket> m_socket; MulticastSocketConnection(const std::shared_ptr<MulticastSocket>& socket); }; inline MulticastSocketConnection::~MulticastSocketConnection() { Close(); } inline void MulticastSocketConnection::Open() { m_socket->Open(); } inline void MulticastSocketConnection::Close() { m_socket->Close(); } inline MulticastSocketConnection::MulticastSocketConnection( const std::shared_ptr<MulticastSocket>& socket) : m_socket(socket) {} } template<> struct ImplementsConcept<Network::MulticastSocketConnection, IO::Connection> : std::true_type {}; } #endif
true
6f52723d23fc4a4a892e53d4844f5ea3890564c0
C++
spiralgenetics/biograph
/modules/io/autostats.h
UTF-8
2,909
2.703125
3
[ "BSD-2-Clause" ]
permissive
#pragma once #include <boost/preprocessor/seq/for_each.hpp> #include <boost/preprocessor/tuple/elem.hpp> #include <cstdint> #include <iostream> #include <map> // Autostats provides a way to track multiple types of metrics, class autostats_base { public: virtual std::map<std::string, size_t> value_map() const = 0; void write_to_stream(std::ostream& os) const; }; class autostats_max_value { public: void add(size_t val) { m_value = std::max(val, m_value); } size_t value() const { return m_value; } private: size_t m_value = 0; }; #define DECLARE_AUTOSTATS(NAME, FIELDS) \ NAME& operator+=(const NAME& autostats_rhs) { \ BOOST_PP_SEQ_FOR_EACH(AUTOSTATS_APPLY, ADD_FIELD, FIELDS) \ return *this; \ } \ std::map<std::string, size_t> value_map() const override { \ std::map<std::string, size_t> autostats_result; \ BOOST_PP_SEQ_FOR_EACH(AUTOSTATS_APPLY, POPULATE_VALUE_MAP, FIELDS); \ return autostats_result; \ } \ friend std::ostream& operator<<(std::ostream& os, const NAME& st) __attribute__((unused)) { \ st.write_to_stream(os); \ return os; \ } \ BOOST_PP_SEQ_FOR_EACH(AUTOSTATS_APPLY, DECLARE_FIELD, FIELDS); #define AUTOSTATS_APPLY(R, OPERATION, ELEM) \ AUTOSTATS_APPLY2(OPERATION, BOOST_PP_TUPLE_ELEM(2, 0, ELEM), BOOST_PP_TUPLE_ELEM(2, 1, ELEM)) #define AUTOSTATS_APPLY2(OPERATION, COUNTER_TYPE, FIELD_NAME) \ BOOST_PP_CAT(AUTOSTATS_, BOOST_PP_CAT(BOOST_PP_CAT(OPERATION, _), COUNTER_TYPE)) \ (FIELD_NAME) #define AUTOSTATS_DECLARE_FIELD_COUNTER(FIELD_NAME) size_t FIELD_NAME = 0; #define AUTOSTATS_DECLARE_FIELD_MAX(FIELD_NAME) autostats_max_value FIELD_NAME; #define AUTOSTATS_ADD_FIELD_COUNTER(FIELD_NAME) this->FIELD_NAME += autostats_rhs.FIELD_NAME; #define AUTOSTATS_ADD_FIELD_MAX(FIELD_NAME) this->FIELD_NAME.add(autostats_rhs.FIELD_NAME.value()); #define AUTOSTATS_POPULATE_VALUE_MAP_MAX(FIELD_NAME) \ autostats_result.insert(std::make_pair(#FIELD_NAME, this->FIELD_NAME.value())); #define AUTOSTATS_POPULATE_VALUE_MAP_COUNTER(FIELD_NAME) \ autostats_result.insert(std::make_pair(#FIELD_NAME, this->FIELD_NAME));
true
33c9d19e0d4104da1bc8be273a97fb58cabc5f02
C++
zephyr-bj/algorithm
/segmentTree/0307_rangeSumQuery.cpp
UTF-8
3,439
2.984375
3
[]
no_license
class NumArray { public: vector<int>sgt; int n; void constructSGT(vector<int>&nums, int l, int h, int x){ if(l>h)return; if(l==h){ sgt[x]=nums[l];return; } int m = (l+h)>>1; constructSGT(nums, l, m, 2*x+1); constructSGT(nums, m+1, h, 2*x+2); sgt[x]=sgt[2*x+1]+sgt[2*x+2]; } int querySGT(int x, int l, int h, int i, int j){ if(i<=l&&j>=h){ return sgt[x]; }else if(i>h || j<l){ return 0; }else{ int m = (l+h)>>1; if(m<i)return querySGT(2*x+2, m+1, h, i, j); else if(m>=j)return querySGT(2*x+1, l, m, i, j); else{ int a = querySGT(2*x+1, l, m, i,m); int b = querySGT(2*x+2, m+1, h, m+1, j); return a+b; } } } void updateSGT(int x, int l, int h, int i, int val){ if(l==h&&l==i){ sgt[x]=val; return; } int m = (l+h)>>1; if(i<=m){ updateSGT(2*x+1, l, m, i, val); }else{ updateSGT(2*x+2, m+1, h, i, val); } sgt[x]=sgt[2*x+1]+sgt[2*x+2]; } NumArray(vector<int>& nums) { n = nums.size(); for(int i=0; i<2*n; i++)sgt.push_back(0); constructSGT(nums, 0, n-1, 0); } void update(int i, int val) { updateSGT(0, 0, n-1, i, val); } int sumRange(int i, int j) { return querySGT(0,0,n-1,i,j); } }; // segment tree can be used for sum/max/min or ...? // also have an alternative using map // segment tree has 2*n-1 elements in total // the original array starts from n-1, so there are n elements from n-1 to 2n-2 // non-leaf nodes from 0 to n-2, n-1 in total // root at 0 // size of array = (size of tree + 1)/2; // 2*p+1 for left subtree, covers elements from l to m; // 2*p+2 for right subtree, covers elements from m+1 to h; // (l-1)/2 is parent, (r-2)/2 is parent class NumArray { public: NumArray(vector<int>& nums) { if (nums.empty()) return; const int n = nums.size(); tree = vector<int>(2*n - 1, 0); for (int i = n - 1, j = 0; i < 2*n - 1; i++, j++) tree[i] = nums[j]; for (int i = n - 2; i >=0; i--) { tree[i] = tree[2*i + 1] + tree[2*(i+1)]; } } void update(int i, int val) { int n = (tree.size() + 1) / 2; int idx = n - 1 + i; tree[idx] = val; int parent; while (idx > 0) { if (idx % 2 == 1) { // left parent = (idx - 1) / 2; tree[parent] = tree[idx] + tree[idx + 1]; } else { parent = (idx - 2) / 2; tree[parent] = tree[idx - 1] + tree[idx]; } idx = parent; } } int sumRange(int i, int j) { int n = (tree.size() + 1) / 2; int l = n - 1 + i; int r = n - 1 + j; int sum = 0; while (l <= r) { if (l % 2 == 0) {//if not left branch sum += tree[l]; l++; } if (r % 2 == 1) {//if not right branch sum += tree[r]; r--; } l = l / 2 ; r = r / 2 - 1; } return sum; } private: vector<int> tree; };
true
792906d4c352d7c3f5ec309b325dc2ea529311cd
C++
MartinMC97/DS-AND-AA-Backup
/DSAA_Code_Cpp/List/DList.cpp
GB18030
1,097
3.46875
3
[]
no_license
/*˫ûд̫࣬ص㻹Dz*/ #pragma once #include <stdlib.h> #define ElemType int typedef struct DNode { ElemType data; DNode *Prev; DNode *Next; }*DList; int DIsEmpty(DList L) { return (L->Next == NULL); } DNode *DGotoKth(DList L, int i) //һָiڵָ { DNode* p = L; int j = 0; while (j<i) { p = p->Next; ++j; } return p; } ElemType DGetElem(DList L, int i) //صiԪ { DNode* p = DGotoKth(L, i); return p->data; } void DListInsert(DList &L, ElemType e, int i) //iλòԪ { DNode *p = DGotoKth(L, i - 1); if (p==NULL) exit(0); DNode* s = (DNode*)malloc(sizeof(DNode)); if (!s) exit(0); s->data = e; if (p->Next == NULL) //pΪձ { p->Next = s; s->Next = NULL; s->Prev = p; } else //pΪձ { s->Next = p->Next; s->Prev = p; s->Next->Prev = s; p->Next = s; } } void DListDelete(DList &L, int i) //ɾеiԪ { DNode *p = DGotoKth(L, i - 1); DNode *s = p->Next; p->Next = s->Next; s->Next->Prev = p; free(s); }
true
c95ac341c4f6b1d4ab8c4f3cc5c292d0a05e2251
C++
jaguar-paw33/CODE_AAI
/Problem Solving/8.Linked List/17.merge_two_sorted_LLs.cpp
UTF-8
1,298
3.6875
4
[]
no_license
/* Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists. Example 1: Input: l1 = [1,2,4], l2 = [1,3,4] Output: [1,1,2,3,4,4] Example 2: Input: l1 = [], l2 = [] Output: [] Example 3: Input: l1 = [], l2 = [0] Output: [0] Constraints: The number of nodes in both lists is in the range [0, 50]. -100 <= Node.val <= 100 Both l1 and l2 are sorted in non-decreasing order. */ #include<bits/stdc++.h> #include"singly_linked_list.h" using namespace std; Node * merge(Node * h1, Node * h2) { Node * h = NULL, * t = NULL; while (h1 && h2) { if (h1->data < h2->data) { if (!h) { h = h1; t = h1; } else { t->next = h1; t = h1; } h1 = h1->next; } else { if (!h) { h = h2; t = h2; } else { t->next = h2; t = h2; } h2 = h2->next; } } while (h1) { if (!h) { h = h1; t = h1; } else { t->next = h1; t = h1; } h1 = h1->next; } while (h2) { if (!h) { h = h2; t = h2; } else { t->next = h2; t = h2; } h2 = h2->next; } return h; } int main() { int n1, n2; cin >> n1 >> n2; Node * h1 = takeInput(n1); Node * h2 = takeInput(n2); Node * h = merge(h1, h2); printLL(h); delete h, h1, h2; return 0; }
true
48e3e3d32a699cab06978983e67064878a214ed5
C++
kelcamer/High-School-C-Plus-Plus
/Program2/Program2/Program2.cpp
UTF-8
3,106
3.828125
4
[]
no_license
/* Kelsey Cameron December 13, 2011 Period 1 Purpose: To calculate the area of various shapes */ #include <iostream> #include <cmath> #include <string> using namespace std; double perimetersquare(double, double); double areasquare(double, double); double circumference(double); double circlearea(double); int main(){ string userinput, shape; string intro = "This program calculates the area for a user specified geometric\nshape. YOU will be asked to enter a code representing the shape.\nDepending on your choice, the program will prompt you for\nadditional information necessary to calculate the area.\n\nYou wil be asked if you want to enter more data. Follow the\ndirections provided to either stop the program or continue.\n"; cout << intro; cout << "Do you want to enter more data?\nEnter Y for yes or N for no.\n"; cin >> userinput; while (userinput == "y" || userinput == "Y"){ cout << " -- VALID SHAPES -- \nEnter S for Square\nEnter C for Circle\nEnter R for Rectangle\n"; cin >> shape; if (shape != "s" || shape != "S" || shape != "R" || shape != "r" || shape != "C" || shape != "c"){ cout << "Please enter either a S, R, or C!!"; cin >> shape; } double length, width, area, perimeter; if (shape == "S" || shape == "s"){ cout << "PLEASE ENTER THE LENGTH OF THE SQUARE!!!\n"; cin >> length; cout << "PLEASE ENTER THE WIDTH OF THE SQUARE!!!\n"; cin >> width; perimeter = perimetersquare(length, width); area = areasquare(length, width); cout << "The perimeter of the square is " << perimeter << "." << endl; cout << "The area of the square is " << area << "." << endl; } else if (shape == "R" || shape == "r"){ cout << "PLEASE ENTER THE LENGTH OF THE RECTANGLE!!!\n"; cin >> length; cout << "PLEASE ENTER THE WIDTH OF THE RECTANGLE!!!\n"; cin >> width; perimeter = perimetersquare(length, width); area = areasquare(length, width); cout << "The perimeter of the rectangle is " << perimeter << "." << endl; cout << "The area of the rectangle is " << area << "." << endl; } else if (shape == "C" || shape == "c"){ double radius, circumference1, area; cout << "Please enter the radius!\n"; cin >> radius; circumference1 = circumference(radius); area = circlearea(radius); cout << "The circumference of the circle is " << circumference1 << "." << endl; cout << "The area of the circle is " << area << "." << endl; } cout << "Do you want to enter more data?\nEnter Y for yes or N for no.\n"; cin >> userinput; } double perimetersquare(double length, double width){ double perimeter; perimeter = 2*(length + width); return perimeter; } double areasquare(double length, double width){ double area; area = length * width; return area; } double circumference(double radius){ double circumference; circumference = 2 * 3.14 * radius; return circumference; } double circlearea(double radius){ double area; area = 3.14*pow(radius, 2); return area; }
true
c7a55e1b40a44c14aeb649baa69bb7a36b784834
C++
salvipeter/sabin-multiloop
/sabin.cc
UTF-8
6,142
2.65625
3
[]
no_license
// Based on: // // M. A. Sabin: Further transfinite developments // In: The Mathematics of Surfaces VIII (Ed. R. Cripps), pp. 161-173, 1998. #include <cmath> #include <fstream> #include <iostream> #include <set> #include "solver.hh" // Global parameters const double multiplier = 30.0; const size_t resolution = 120; const size_t u_mod = 4; const size_t v_mod = 4; const bool export_patch = true; const bool export_isolines = true; // Setup boundaries as in the paper (or at least similarly) double b1(double &u, double &v, Point3D &point, Vector3D &du, Vector3D &dv) { double t = u, d = v; v = 0; point = Point3D(0, 0, 0) * (1 - t) + Point3D(33, 0, 0) * t; du = Vector3D(1, 0, 0) * multiplier; dv = Vector3D(0, 1, 0) * multiplier; return d; } double b3(double &u, double &v, Point3D &point, Vector3D &du, Vector3D &dv) { double t = u, d = 1 - v; v = 1; point = Point3D(0, 0, 20) * (1 - t) + Point3D(33, 0, 20) * t; du = Vector3D(1, 0, 0) * multiplier; dv = Vector3D(0, -1, 0) * multiplier; return d; } double b2(double &u, double &v, Point3D &point, Vector3D &du, Vector3D &dv) { double phi = (1 - v) * M_PI, d = u; u = 0; point = Point3D(0, 0, 10) + Vector3D(0, sin(phi), cos(phi)) * 10; du = Vector3D(1, 0, 0) * multiplier; dv = Vector3D(0, -cos(phi), sin(phi)) * multiplier; return d; } double b4(double &u, double &v, Point3D &point, Vector3D &du, Vector3D &dv) { double phi = (1 - v) * M_PI, d = 1 - u; u = 1; point = Point3D(33, 0, 10) + Vector3D(0, sin(phi), cos(phi)) * 10; du = Vector3D(1, 0, 0) * multiplier; dv = Vector3D(0, -cos(phi), sin(phi)) * multiplier; return d; } double hole1(double &u, double &v, Point3D &point, Vector3D &du, Vector3D &dv) { Point2D center(0.3, 0.5), p(u, v); double radius = 0.1; auto deviation = p - center; bool inside = deviation.norm() < radius; if (deviation.norm() < 1.0e-5) deviation = Vector2D(1, 0); // does not matter, we are in the center, but avoid NaNs deviation.normalize(); auto q = center + deviation * radius; u = q[0]; v = q[1]; point = Point3D(33 * q[0], 16, 33 * q[1] - 6.5); Vector2D perp(deviation[1], -deviation[0]); auto ddev = Vector3D(0, -1.2, 0) * multiplier; auto dperp = Vector3D(perp[0], 0, perp[1]) * multiplier; du = ddev * deviation[0] + dperp * perp[0]; dv = ddev * deviation[1] + dperp * perp[1]; return inside ? -1 : (p - q).norm(); } double hole2(double &u, double &v, Point3D &point, Vector3D &du, Vector3D &dv) { Point2D center(0.7, 0.5), p(u, v); double radius = 0.1; auto deviation = p - center; bool inside = deviation.norm() < radius; if (deviation.norm() < 1.0e-5) deviation = Vector2D(1, 0); // does not matter, we are in the center, but avoid NaNs deviation.normalize(); auto q = center + deviation * radius; u = q[0]; v = q[1]; point = Point3D(33 * q[0], 16, 33 * q[1] - 6.5); Vector2D perp(deviation[1], -deviation[0]); auto ddev = Vector3D(0, -1.2, 0) * multiplier; auto dperp = Vector3D(perp[0], 0, perp[1]) * multiplier; du = ddev * deviation[0] + dperp * perp[0]; dv = ddev * deviation[1] + dperp * perp[1]; return inside ? -1 : (p - q).norm(); } // Main code int main() { std::vector<Boundary> boundaries = { b1, b2, b3, b4 }, holes = { hole1, hole2 }; std::set<size_t> hole_indices; auto is_in_hole = [&](size_t i) { return hole_indices.find(i) != hole_indices.end(); }; boundaries.insert(boundaries.end(), holes.begin(), holes.end()); std::ofstream f("/tmp/sabin.obj"); size_t index = 1; for (size_t i = 0; i <= resolution; ++i) { double u = (double)i / resolution; for (size_t j = 0; j <= resolution; ++j, ++index) { double v = (double)j / resolution; // Heuristic handling of holes bool in_hole = false; for (const auto &hole : holes) { double u1 = u, v1 = v; Point3D p; Vector3D du, dv; if (hole(u1, v1, p, du, dv) < 0) { in_hole = true; hole_indices.insert(index); Vector3D n = (du ^ dv).normalize(); f << "v " << p[0] << ' ' << p[1] << ' ' << p[2] << std::endl; f << "vn " << n[0] << ' ' << n[1] << ' ' << n[2] << std::endl; break; } } if (in_hole) continue; auto [p, n] = evalPatch(boundaries, u, v); f << "v " << p[0] << ' ' << p[1] << ' ' << p[2] << std::endl; f << "vn " << n[0] << ' ' << n[1] << ' ' << n[2] << std::endl; } } if (export_patch) { for (size_t i = 0; i < resolution; ++i) for (size_t j = 0; j < resolution; ++j) { index = i * (resolution + 1) + j + 1; if (!is_in_hole(index) || !is_in_hole(index + resolution + 2) || !is_in_hole(index + 1)) f << "f " << index << "//" << index << ' ' << index + resolution + 2 << "//" << index + resolution + 2 << ' ' << index + 1 << "//" << index + 1 << std::endl; if (!is_in_hole(index) || !is_in_hole(index + resolution + 1) || !is_in_hole(index + resolution + 2)) f << "f " << index << "//" << index << ' ' << index + resolution + 1 << "//" << index + resolution + 1 << ' ' << index + resolution + 2 << "//" << index + resolution + 2 << std::endl; } } if (export_isolines) { for (size_t k = 0; k < 2; ++k) for (size_t i = 0; i <= resolution; ++i) { bool start = true; size_t starting_index = 0; for (size_t j = 0; j <= resolution; ++j) { index = k ? j * (resolution + 1) + i + 1 : i * (resolution + 1) + j + 1; if (is_in_hole(index)) { if (!start) f << ' ' << index << std::endl; start = true; } else if (start) { starting_index = index; start = false; } else if ((k && i % v_mod == 0) || (!k && i % u_mod == 0)) { if (starting_index > 0) { f << "l " << starting_index; starting_index = 0; } f << ' ' << index; } } if (!start) f << std::endl; } } }
true
05cd24be7cc0ca80d0bda14d24f7dcfd7813d1e3
C++
irina-suslova/Lab_3
/Lab_3/main.cpp
UTF-8
44,219
3.21875
3
[]
no_license
#include <iostream> #include <time.h> #include "set.h" #include "set.cpp" #include "extrafunctions.h" #include "complex.h" #include "person.h" using namespace std; const char *MSGS_TYPE[] = {"Which type of function do you need?", "0. Quit", "1. Make integer sets", "2. Make float sets", "3. Make complex sets", "4. Make string sets", "5. Make person sets", }; const int MSGS_TYPE_SIZE = sizeof(MSGS_TYPE) / sizeof(MSGS_TYPE[0]); const char *MSGS[] = {"What do you want to do?", "0. Quit", "1. To previous step", "2. First set generate (max n elements)", "3. Second set generate (max n elements)", "4. First set max value", "5. Second set max value", "6. First set insert value", "7. Second set insert value", "8. Union", "9. Crossing", "10. Subtraction (first set - second set)", "11. Subtraction (second set - first set)", "12. Subset inclusion check (second set in first set)", "13. Subset inclusion check (first set in second set)", "14. Equality check", }; const int MSGS_SIZE = sizeof(MSGS) / sizeof(MSGS[0]); int dialog(const char *msgs[], int n) { char *error = ""; int choice; do { cout << error << endl; error = "Incorrect input. Please, enter one positive integer number.\n"; for (int i = 0; i < n; ++i) { cout << msgs[i] << endl; } cout << "Make your choice: "; choice = getchar() - '0'; char c = getchar(); while (c != '\n') { if (0 <= (int)c - '0' && (int)c - '0' <= 9) choice = choice * 10 + (c - '0'); c = getchar(); } } while (choice < 0 || choice >= n); return choice; } int main() { srand(time(NULL)); int cmd = 0; int cmd_action = 0; int mode; Set<int> *setInt1 = new Set<int>; Set<int> *setInt2 = new Set<int>; int nInt; Set<float> *setFloat1 = new Set<float>; Set<float> *setFloat2 = new Set<float>; float nFloat; Set<Complex> *setComplex1 = new Set<Complex>; Set<Complex> *setComplex2 = new Set<Complex>; Complex nComplex; Set<string> *setString1 = new Set<string>; Set<string> *setString2 = new Set<string>; string nString; Set<Person> *setPerson1 = new Set<Person>; Set<Person> *setPerson2 = new Set<Person>; Person nPerson; cout << "Hello! I've made a little program for working with sets. You are welcome :)\n"; do { cmd = dialog(MSGS_TYPE, MSGS_TYPE_SIZE); switch(cmd) { case 0: cout << "Goodbye! :)"; break; case 1: cout << "\nOption 1 - Integer sets\n"; cmd_action = 0; do { cmd_action = dialog(MSGS, MSGS_SIZE); mode = 0; nInt = 0; switch (cmd_action) { case 0: cout << "Goodbye! :)"; cmd = 0; cmd_action = 0; break; case 1: setInt1->Clear(); setInt2->Clear(); cmd_action = 0; break; case 2: cout << "\nOption 2 - First set generate (max n elements)\n"; if (setInt1->GetLength() != 0) setInt1->Clear(); cout << "Input number of elements: "; mode = readInt(nInt); if (mode != 0) { break; } if (nInt <= 0) { cout << "The number must be positive.\n"; break; } setInt1->Generate(nInt, randomInt); cout << "Generated first set:\n" << *setInt1 << endl; break; case 3: cout << "\nOption 3 - Second set generate (max n elements)\n"; if (setInt2->GetLength() != 0) setInt2->Clear(); cout << "Input number of elements: "; mode = readInt(nInt); if (mode != 0) { break; } if (nInt <= 0) { cout << "The number must be positive.\n"; break; } setInt2->Generate(nInt, randomInt); cout << "Generated second set:\n" << *setInt2 << endl; break; case 4: cout << "\nOption 4 - First set max value\n"; if (setInt1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } cout << setInt1->GetMax(); break; case 5: cout << "\nOption 5 - Second set max value\n"; if (setInt2->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << setInt2->GetMax(); break; case 6: cout << "\nOption 6 - First set insert value\n"; cout << "Input elemet: "; mode = readInt(nInt); if (mode != 0) { break; } setInt1->Insert(nInt); cout << "Success!\n" << *setInt1 << endl; break; case 7: cout << "\nOption 7 - Second set insert value\n"; cout << "Input elemet: "; mode = readInt(nInt); if (mode != 0) { break; } setInt2->Insert(nInt); cout << "Success!\n" << *setInt2 << endl; break; case 8: cout << "\nOption 8 - Union\n"; if (setInt1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } if (setInt2->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << (*setInt1 + *setInt2) << endl; break; case 9: cout << "\nOption 9 - Crossing\n"; if (setInt1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } if (setInt2->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << (*setInt1 * *setInt2) << endl; break; case 10: cout << "\nOption 10 - Subtraction (first set - second set)\n"; if (setInt1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } if (setInt2->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << (*setInt1 - *setInt2) << endl; break; case 11: cout << "\nOption 11 - Subtraction (second set - first set)\n"; if (setInt1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } if (setInt2->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << (*setInt2 - *setInt1) << endl; break; case 12: cout << "\nOption 12 - Subset inclusion check (second set in first set)\n"; if (setInt1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } if (setInt2->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << (setInt1->CheckSubset(setInt2) ? "Second set is in first set" : "Second set is not in first set") << endl; break; case 13: cout << "\nOption 13 - Subset inclusion check (first set in second set)\n"; if (setInt1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } if (setInt2->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << (setInt2->CheckSubset(setInt1) ? "First set is in second set" : "First set is not in second set") << endl; break; case 14: cout << "\nOption 14 - Equality check\n"; if (setInt1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } if (setInt2->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << ((*setInt1 == *setInt2) ? "Sets are equels" : "Sets are not equels") << endl; break; } } while(cmd_action != 0); break; case 2: cout << "\nOption 2 - Float sets\n"; cmd_action = 0; do { cmd_action = dialog(MSGS, MSGS_SIZE); switch (cmd_action) { case 0: cout << "Goodbye! :)"; cmd = 0; cmd_action = 0; break; case 1: setFloat1->Clear(); setFloat2->Clear(); cmd_action = 0; break; case 2: cout << "\nOption 2 - First set generate (max n elements)\n"; if (setFloat1->GetLength() != 0) setFloat1->Clear(); cout << "Input number of pieces: "; mode = readInt(nInt); if (mode != 0) { break; } if (nInt <= 0) { cout << "The number must be positive.\n"; break; } setFloat1->Generate(nInt, randomFloat); cout << "Generated first set:\n" << *setFloat1 << endl; break; case 3: cout << "\nOption 3 - Second set generate (max n elements)\n"; if (setFloat2->GetLength() != 0) setFloat2->Clear(); cout << "Input number of pieces: "; mode = readInt(nInt); if (mode != 0) { break; } if (nInt <= 0) { cout << "The number must be positive.\n"; break; } setFloat2->Generate(nInt, randomFloat); cout << "Generated second set:\n" << *setFloat2 << endl; break; case 4: cout << "\nOption 4 - First set max value\n"; if (setFloat1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } cout << setFloat1->GetMax(); break; case 5: cout << "\nOption 5 - Second set max value\n"; if (setFloat2->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << setFloat2->GetMax(); break; case 6: cout << "\nOption 6 - First set insert value\n"; cout << "Input elemet: "; mode = readFloat(nFloat); if (mode != 0) { break; } setFloat1->Insert(nFloat); cout << "Success!\n" << *setFloat1 << endl; break; case 7: cout << "\nOption 7 - Second set insert value\n"; cout << "Input elemet: "; mode = readFloat(nFloat); if (mode != 0) { break; } setFloat2->Insert(nFloat); cout << "Success!\n" << *setFloat2 << endl; break; case 8: cout << "\nOption 8 - Union\n"; if (setFloat1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } if (setFloat2->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << (*setFloat1 + *setFloat2) << endl; break; case 9: cout << "\nOption 9 - Crossing\n"; if (setFloat1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } if (setFloat2->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << (*setFloat1 * *setFloat2) << endl; break; case 10: cout << "\nOption 10 - Subtraction (first set - second set)\n"; if (setFloat1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } if (setFloat2->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << (*setFloat1 - *setFloat2) << endl; break; case 11: cout << "\nOption 11 - Subtraction (second set - first set)\n"; if (setFloat1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } if (setFloat2->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << (*setFloat2 - *setFloat1) << endl; break; case 12: cout << "\nOption 12 - Subset inclusion check (second set in first set)\n"; if (setFloat1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } if (setFloat2->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << (setFloat1->CheckSubset(setFloat2) ? "Second set is in first set" : "Second set is not in first set") << endl; break; case 13: cout << "\nOption 13 - Subset inclusion check (first set in second set)\n"; if (setFloat1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } if (setFloat1->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << (setFloat2->CheckSubset(setFloat1) ? "First set is in second set" : "First set is not in second set") << endl; break; case 14: cout << "\nOption 14 - Equality check\n"; if (setFloat1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } if (setFloat2->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << ((*setFloat1 == *setFloat2) ? "Sets are equels" : "Sets are not equels") << endl; break; } } while(cmd_action != 0); break; case 3: cout << "\nOption 3 - Complex sets\n"; cmd_action = 0; do { cmd_action = dialog(MSGS, MSGS_SIZE); switch (cmd_action) { case 0: cout << "Goodbye! :)"; cmd = 0; cmd_action = 0; break; case 1: setComplex1->Clear(); setComplex2->Clear(); cmd_action = 0; break; case 2: cout << "\nOption 2 - First set generate (max n elements)\n"; if (setComplex1->GetLength() != 0) setComplex1->Clear(); cout << "Input number of pieces: "; mode = readInt(nInt); if (mode != 0) { break; } if (nInt <= 0) { cout << "The number must be positive.\n"; break; } setComplex1->Generate(nInt, randomComplex); cout << "Generated first set:\n" << *setComplex1 << endl; break; case 3: cout << "\nOption 3 - Second set generate (max n elements)\n"; if (setComplex2->GetLength() != 0) setComplex2->Clear(); cout << "Input number of pieces: "; mode = readInt(nInt); if (mode != 0) { break; } if (nInt <= 0) { cout << "The number must be positive.\n"; break; } setComplex2->Generate(nInt, randomComplex); cout << "Generated second set:\n" << *setComplex2 << endl; break; case 4: cout << "\nOption 4 - First set max value\n"; if (setComplex1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } cout << setComplex1->GetMax(); break; case 5: cout << "\nOption 5 - Second set max value\n"; if (setComplex2->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << setComplex2->GetMax(); break; case 6: cout << "\nOption 6 - First set insert value\n"; cout << "Input elemet: "; mode = readComplex(nComplex); if (mode != 0) { break; } setComplex1->Insert(nComplex); cout << "Success!\n" << *setComplex1 << endl; break; case 7: cout << "\nOption 7 - Second set insert value\n"; cout << "Input elemet: "; mode = readComplex(nComplex); if (mode != 0) { break; } setComplex2->Insert(nComplex); cout << "Success!\n" << *setComplex2 << endl; break; case 8: cout << "\nOption 8 - Union\n"; if (setComplex1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } if (setComplex2->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << (*setComplex1 + *setComplex2) << endl; break; case 9: cout << "\nOption 9 - Crossing\n"; if (setComplex1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } if (setComplex2->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << (*setComplex1 * *setComplex2) << endl; break; case 10: cout << "\nOption 10 - Subtraction (first set - second set)\n"; if (setComplex1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } if (setComplex2->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << (*setComplex1 - *setComplex2) << endl; break; case 11: cout << "\nOption 11 - Subtraction (second set - first set)\n"; if (setComplex1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } if (setComplex2->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << (*setComplex2 - *setComplex1) << endl; break; case 12: cout << "\nOption 12 - Subset inclusion check (second set in first set)\n"; if (setComplex1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } if (setComplex2->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << (setComplex1->CheckSubset(setComplex2) ? "Second set is in first set" : "Second set is not in first set") << endl; break; case 13: cout << "\nOption 13 - Subset inclusion check (first set in second set)\n"; if (setComplex1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } if (setComplex2->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << (setComplex2->CheckSubset(setComplex1) ? "First set is in second set" : "First set is not in second set") << endl; break; case 14: cout << "\nOption 14 - Equality check\n"; if (setComplex1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } if (setComplex2->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << ((*setComplex1 == *setComplex2) ? "Sets are equels" : "Sets are not equels") << endl; break; } } while(cmd_action != 0); break; case 4: cout << "\nOption 4 - String sets\n"; cmd_action = 0; do { cmd_action = dialog(MSGS, MSGS_SIZE); switch (cmd_action) { case 0: cout << "Goodbye! :)"; cmd = 0; cmd_action = 0; break; case 1: setComplex1->Clear(); setComplex2->Clear(); cmd_action = 0; break; case 2: cout << "\nOption 2 - First set generate (max n elements)\n"; if (setString1->GetLength() != 0) setString1->Clear(); cout << "Input number of pieces: "; mode = readInt(nInt); if (mode != 0) { break; } if (nInt <= 0) { cout << "The number must be positive.\n"; break; } setString1->Generate(nInt, randomString); cout << "Generated first set:\n" << *setString1 << endl; break; case 3: cout << "\nOption 3 - Second set generate (max n elements)\n"; if (setString2->GetLength() != 0) setString2->Clear(); cout << "Input number of pieces: "; mode = readInt(nInt); if (mode != 0) { break; } if (nInt <= 0) { cout << "The number must be positive.\n"; break; } setString2->Generate(nInt, randomString); cout << "Generated second set:\n" << *setString2 << endl; break; case 4: cout << "\nOption 4 - First set max value\n"; if (setString1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } cout << setString1->GetMax(); break; case 5: cout << "\nOption 5 - Second set max value\n"; if (setString2->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << setString2->GetMax(); break; case 6: cout << "\nOption 6 - First set insert value\n"; cout << "Input elemet: "; mode = readString(nString); if (mode != 0) { break; } setString1->Insert(nString); cout << "Success!\n" << *setString1 << endl; break; case 7: cout << "\nOption 7 - Second set insert value\n"; cout << "Input elemet: "; mode = readString(nString); if (mode != 0) { break; } setString2->Insert(nString); cout << "Success!\n" << *setString2 << endl; break; case 8: cout << "\nOption 8 - Union\n"; if (setString1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } if (setString2->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << (*setString1 + *setString2) << endl; break; case 9: cout << "\nOption 9 - Crossing\n"; if (setString1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } if (setString2->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << (*setString1 * *setString2) << endl; break; case 10: cout << "\nOption 10 - Subtraction (first set - second set)\n"; if (setString1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } if (setString2->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << (*setString1 - *setString2) << endl; break; case 11: cout << "\nOption 11 - Subtraction (second set - first set)\n"; if (setString1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } if (setString2->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << (*setString2 - *setString1) << endl; break; case 12: cout << "\nOption 12 - Subset inclusion check (second set in first set)\n"; if (setString1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } if (setString2->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << (setString1->CheckSubset(setString2) ? "Second set is in first set" : "Second set is not in first set") << endl; break; case 13: cout << "\nOption 13 - Subset inclusion check (first set in second set)\n"; if (setString1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } if (setString2->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << (setString2->CheckSubset(setString1) ? "First set is in second set" : "First set is not in second set") << endl; break; case 14: cout << "\nOption 14 - Equality check\n"; if (setString1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } if (setString2->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << ((*setString1 == *setString2) ? "Sets are equels" : "Sets are not equels") << endl; break; } } while(cmd_action != 0); break; case 5: cout << "\nOption 5 - Person sets\n"; cmd_action = 0; do { cmd_action = dialog(MSGS, MSGS_SIZE); switch (cmd_action) { case 0: cout << "Goodbye! :)"; cmd = 0; cmd_action = 0; break; case 1: setPerson1->Clear(); setPerson2->Clear(); cmd_action = 0; break; case 2: cout << "\nOption 2 - First set generate (max n elements)\n"; if (setPerson1->GetLength() != 0) setPerson1->Clear(); cout << "Input number of pieces: "; mode = readInt(nInt); if (mode != 0) { break; } if (nInt <= 0) { cout << "The number must be positive.\n"; break; } setPerson1->Generate(nInt, randomPerson); cout << "Generated first set:\n" << *setPerson1 << endl; break; case 3: cout << "\nOption 3 - Second set generate (max n elements)\n"; if (setPerson2->GetLength() != 0) setPerson2->Clear(); cout << "Input number of pieces: "; mode = readInt(nInt); if (mode != 0) { break; } if (nInt <= 0) { cout << "The number must be positive.\n"; break; } setPerson2->Generate(nInt, randomPerson); cout << "Generated second set:\n" << *setPerson2 << endl; break; case 4: cout << "\nOption 4 - First set max value\n"; if (setPerson1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } cout << setPerson1->GetMax(); break; case 5: cout << "\nOption 5 - Second set max value\n"; if (setPerson2->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << setPerson2->GetMax(); break; case 6: cout << "\nOption 6 - First set insert value\n"; cout << "Input elemet: "; mode = readPerson(nPerson); if (mode != 0) { break; } setPerson1->Insert(nPerson); cout << "Success!\n" << *setPerson1 << endl; break; case 7: cout << "\nOption 7 - Second set insert value\n"; cout << "Input elemet: "; mode = readPerson(nPerson); if (mode != 0) { break; } setPerson2->Insert(nPerson); cout << "Success!\n" << *setPerson2 << endl; break; case 8: cout << "\nOption 8 - Union\n"; if (setPerson1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } if (setPerson2->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << (*setPerson1 + *setPerson2) << endl; break; case 9: cout << "\nOption 9 - Crossing\n"; if (setPerson1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } if (setPerson2->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << (*setPerson1 * *setPerson2) << endl; break; case 10: cout << "\nOption 10 - Subtraction (first set - second set)\n"; if (setPerson1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } if (setPerson2->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << (*setPerson1 - *setPerson2) << endl; break; case 11: cout << "\nOption 11 - Subtraction (second set - first set)\n"; if (setPerson1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } if (setPerson2->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << (*setPerson2 - *setPerson1) << endl; break; case 12: cout << "\nOption 12 - Subset inclusion check (second set in first set)\n"; if (setPerson1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } if (setPerson2->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << (setPerson1->CheckSubset(setPerson2) ? "Second set is in first set" : "Second set is not in first set") << endl; break; case 13: cout << "\nOption 13 - Subset inclusion check (first set in second set)\n"; if (setPerson1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } if (setPerson2->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << (setPerson2->CheckSubset(setPerson1) ? "First set is in second set" : "First set is not in second set") << endl; break; case 14: cout << "\nOption 14 - Equality check\n"; if (setPerson1->GetLength() == 0) { cout << "First set is empty.\n Please use generate or keyboard input.\n"; break; } if (setPerson2->GetLength() == 0) { cout << "Second set is empty.\n Please use generate or keyboard input.\n"; break; } cout << ((*setPerson1 == *setPerson2) ? "Sets are equels" : "Sets are not equels") << endl; break; } } while(cmd_action != 0); break; } } while (cmd != 0); return 0; }
true
2f6b4ef6dc7e0f2ff7cd42f3be6f9d04b764ffc8
C++
deva02ashish/Competitive-Programming
/virtual_base_claass.cpp
UTF-8
1,228
3.328125
3
[]
no_license
#include<iostream> using namespace std; /* ---------------virtual_base_inheritance---------------- student-->>test student-->>sports test-->>result sports-->>result */ class student { protected: int roll_no; public: void set_number(int a) { roll_no=a; } void print_number(void) { cout<<"your roll number is :"<<roll_no<<endl; } }; class test:virtual public student { protected: float maths ,physics; public: void set_marks(float m1,float m2) { maths=m1; physics=m2; } void print_marks(void) { cout<<"you have obtained marks"<<endl <<"math: "<<maths<<endl <<"physics: "<<physics<<endl; } }; class sports:virtual public student{ protected: float score; public: void set_score(float sc) { score=sc; } void print_score(void) { cout<<"you PT score is :"<<score<<endl; } }; class result:public test,public sports { protected: float total; public: void display(void) { total=maths+physics+score; print_number(); print_marks(); print_score(); cout<<"your total score is :"<<total<<endl; } }; int main() { result deva; deva.set_number(7); deva.set_marks(83.4,74.7); deva.set_score(7); deva.display(); return 0; }
true
b7e7e4dabeebec848a4ba5ee050634f6f12b2432
C++
sbmaruf/Algorithms-Code-Library
/Geometry/CircleSegmentTetrahedron.cpp
UTF-8
2,231
3.59375
4
[ "MIT" ]
permissive
/* This code assumes the circle center and radius to be integer. Change this when necessary. */ inline double commonArea(const Circle &a, const Circle &b) { int dsq = sqDist(a.c, b.c); double d = sqrt((double)dsq); if(sq(a.r + b.r) <= dsq) return 0; if(a.r >= b.r && sq(a.r-b.r) >= dsq) return pi * b.r * b.r; if(a.r <= b.r && sq(b.r-a.r) >= dsq) return pi * a.r * a.r; double angleA = 2.0 * acos((a.r * a.r + dsq - b.r * b.r) / (2.0 * a.r * d)); double angleB = 2.0 * acos((b.r * b.r + dsq - a.r * a.r) / (2.0 * b.r * d)); return 0.5 * (a.r * a.r * (angleA - sin(angleA)) + b.r * b.r * (angleB - sin(angleB))); } /* Segment intersection in 2D integer space. P1, p2 makes first segment, p3, p4 makes the second segment */ inline bool intersect(const Point &p1, const Point &p2, const Point &p3, const Point &p4) { i64 d1, d2, d3, d4; d1 = direction(p3, p4, p1); d2 = direction(p3, p4, p2); d3 = direction(p1, p2, p3); d4 = direction(p1, p2, p4); if(((d1 < 0 && d2 > 0) || (d1 > 0 && d2 < 0)) && ((d3 < 0 && d4 > 0) || (d3 > 0 && d4 < 0))) return true; if(!d3 && onsegment(p1, p2, p3)) return true; if(!d4 && onsegment(p1, p2, p4)) return true; if(!d1 && onsegment(p3, p4, p1)) return true; if(!d2 && onsegment(p3, p4, p2)) return true; return false; } /* Some tetrahedron formulas */ inline double volume(double u, double v, double w, double U, double V, double W) { double u1,v1,w1; u1 = v * v + w * w - U * U; v1 = w * w + u * u - V * V; w1 = u * u + v * v - W * W; return sqrt(4.0*u*u*v*v*w*w - u*u*u1*u1 - v*v*v1*v1 - w*w*w1*w1 + u1*v1*w1) / 12.0; } inline double surface(double a, double b, double c) { return sqrt((a + b + c) * (-a + b + c) * (a - b + c) * (a + b - c)) / 4.0; } inline double insphere(double WX, double WY, double WZ, double XY, double XZ, double YZ) { double sur, rad; sur = surface(WX, WY, XY) + surface(WX, XZ, WZ) + surface(WY, YZ, WZ) + surface(XY, XZ, YZ); rad = volume(WX, WY, WZ, YZ, XZ, XY) * 3.0 / sur; return rad; } //1.angle of a regular polygon if is T then total arm n = 360/(180-T) where n is integer.
true
d2764533237b424c2faa8c5eea4db6a13e64a8c6
C++
alberto-pino/ugine
/src/Emitter.h
UTF-8
1,441
2.90625
3
[]
no_license
#pragma once #include "common.h" #include "entity.h" #include "Material.h" #include "Particle.h" class Emitter : public Entity { public: Emitter(const Material& mat, bool autofade = true); void setRateRange(float min, float max) { minRateRange = min; maxRateRange = max; }; void setVelocityRange(const glm::vec3& min, const glm::vec3& max) { minVelRange = min; maxVelRange = max; }; void setSpinVelocityRange(float min, float max) { minSpinRange = min; maxSpinRange = max; }; void setScaleRange(float min, float max) { minScaleRange = min; maxScaleRange = max; }; void setLifetimeRange(float min, float max) { minLifetimeRange = min; maxLifetimeRange = max; }; void setColorRange(const glm::vec4& min, const glm::vec4& max) { minColorRange = min; maxColorRange = max; }; void emit(bool enable) { emitting = enable; }; bool isEmitting() { return emitting; }; virtual void update(float deltaTime) override; virtual void draw() override; int getNumberParticles() { return particles.size(); }; private: Material material; bool autoFade; bool emitting; float minRateRange; float maxRateRange; glm::vec3 minVelRange; glm::vec3 maxVelRange; float minSpinRange; float maxSpinRange; float minScaleRange; float maxScaleRange; float minLifetimeRange; float maxLifetimeRange; glm::vec4 minColorRange; glm::vec4 maxColorRange; std::vector<Particle> particles; float particlesToEmit = 0.0f; };
true
da26760ef5de3e74828cb7b3a25aa013bd7a51b0
C++
jsl1113/LeeJiSeon
/Coding_Test_study/C++/B5073.cpp
UTF-8
621
3.265625
3
[]
no_license
#include <iostream> #include <cmath> using namespace std; int a, b, c; bool E() { return (a == b && b == c) ? true : false; } bool I() { return (a == b || b == c || c == a) ? true : false; } int main() { ios::sync_with_stdio(); cin.tie(); while (true) { cin >> a >> b >> c; if (a == 0 && b == 0 && c == 0) break; else { int tmp = max(a, max(b, c)); if ((2 * tmp) >= (a + b + c)) cout << "Invalid" << "\n"; else { if (E()) { cout << "Equilateral" << '\n'; } else if (I()) { cout << "Isosceles" << '\n'; } else { cout << "Scalene" << "\n"; } } } } }
true
dfe9c166683f4ca4576a3d9ad57f685df7760dd8
C++
Reolsin/labs_3sem
/Lab3_dynamic/test.cpp
UTF-8
3,395
3.234375
3
[]
no_license
#include "pch.h" #include "../Library_dynamic/Stack.h" namespace Stack_dynamic { TEST(StructConstructor, Default) { Cell c; EXPECT_EQ(0, c.v); ASSERT_STREQ("", c.str); } TEST(StructConstructor, Init) { Cell c1(1); Cell c2(2, "string"); EXPECT_EQ(1, c1.v); ASSERT_STREQ("", c1.str); EXPECT_EQ(2, c2.v); ASSERT_STREQ("string", c2.str); } TEST(StructConstructor, Copy) { Cell c1(2, "string"); Cell c2 = c1; EXPECT_EQ(c1.v, c2.v); ASSERT_STREQ(c1.str, c2.str); } TEST(StructConstructor, Move) { Cell c1 = Cell(2, "string"); EXPECT_EQ(2, c1.v); ASSERT_STREQ("string", c1.str); } TEST(StructOperators, Copy) { Cell c1(2, "string"); Cell c2; c2 = c1; EXPECT_EQ(c1.v, c2.v); ASSERT_STREQ(c1.str, c2.str); } TEST(StructOperators, Move) { Cell c1; c1 = Cell(2, "string"); EXPECT_EQ(2, c1.v); ASSERT_STREQ("string", c1.str); } TEST(ClassConstructor, Default) { Stack S; EXPECT_EQ(10, S.getSZ()); EXPECT_EQ(0, S.gettop()); } TEST(ClassConstructor, Init) { Cell el; Cell c1[3]{ {1, "string1"}, {2, "string2"}, {3, "string3" } }; Stack S1(c1, 3); EXPECT_EQ(10, S1.getSZ()); EXPECT_EQ(3, S1.gettop()); S1(el); EXPECT_EQ(c1[2].v, el.v); ASSERT_STREQ(c1[2].str, el.str); S1(el); EXPECT_EQ(c1[1].v, el.v); ASSERT_STREQ(c1[1].str, el.str); S1(el); EXPECT_EQ(c1[0].v, el.v); ASSERT_STREQ(c1[0].str, el.str); Cell c2[12]; Stack S2(c2, 12); EXPECT_EQ(20, S2.getSZ()); EXPECT_EQ(12, S2.gettop()); while (S2.not_empty()) { S2(el); EXPECT_EQ(0, el.v); ASSERT_STREQ("", el.str); } } TEST(ClassConstructor, InitException) { Cell c[3]{ {1, "string1"}, {2, "string2"}, {3, "string3" } }; ASSERT_ANY_THROW(Stack S3(c, -1)); } TEST(ClassConstructor, Copy) { Cell* c = &Cell(2, "string"); Stack S1(c, 1); Stack S2 = S1; Cell el1, el2; EXPECT_EQ(S1.gettop(), S2.gettop()); EXPECT_EQ(S1.getSZ(), S2.getSZ()); S1(el1); S2(el2); EXPECT_EQ(el1.v, el2.v); ASSERT_STREQ(el1.str, el2.str); } TEST(ClassConstructor, Move) { Cell c(2, "string"); Stack S1 = Stack(&c,1); Cell el; EXPECT_EQ(S1.gettop(), 1); EXPECT_EQ(S1.getSZ(), 10); S1(el); EXPECT_EQ(el.v, 2); ASSERT_STREQ(el.str, "string"); } TEST(ClassOperators, copy) { Cell el; Cell c[12]; Stack S1(c, 12); Stack S2; S2 = S1; EXPECT_EQ(20, S2.getSZ()); EXPECT_EQ(12, S2.gettop()); while (S2.not_empty()) { S2(el); EXPECT_EQ(0, el.v); ASSERT_STREQ("", el.str); } } TEST(ClassOperators, move) { Cell el; Cell c[12]; Stack S; S = Stack(c, 12); EXPECT_EQ(20, S.getSZ()); EXPECT_EQ(12, S.gettop()); while (S.not_empty()) { S(el); EXPECT_EQ(0, el.v); ASSERT_STREQ("", el.str); } } TEST(ClassOperators, pop_push) { Stack S; Cell c(11, "str"); Cell el; S += c; S(el); EXPECT_EQ(el.v, c.v); ASSERT_STREQ(el.str, c.str); } TEST(ClassOperators, pop_pushExceptions) { Stack S; Cell el; ASSERT_ANY_THROW(S(el)); } TEST(ClassGetters, Status) { Stack S; Cell c; EXPECT_EQ(S.not_empty(), 0); EXPECT_EQ(S.is_full(), 0); S += c; EXPECT_EQ(S.not_empty(), 1); EXPECT_EQ(S.is_full(), 0); int SZ = S.getSZ(); int i = 1; while (i++ < SZ) S += c; EXPECT_EQ(S.not_empty(), 1); EXPECT_EQ(S.is_full(), 1); } } int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
true
7066917a3c0572c5178d2dcd559f46e01d6eb13e
C++
solderspot/SS_Servorator
/examples/SimpleServo/SimpleServo.ino
UTF-8
1,621
2.96875
3
[ "BSD-3-Clause" ]
permissive
// // // SimpleServo.ino // // Copyright (c) 2013-2014, Solder Spot // All rights reserved. // This sketch requires the following library: // SS_Servorator: https://github.com/solderspot/SS_Servorator // include needed librarys #include <Servo.h> #include <SS_Servorator.h> #define NUM_SERVOS 6 Servo servo[NUM_SERVOS]; SS_Servorator sr(NUM_SERVOS); // the servo handler for Servorator void update_servo( SS_Index index, SS_Angle angle, void *data) { // SS_Angle is in 1000th of a degree //Serial.println(angle/1000); servo[index].write( angle/1000); } void setup() { Serial.begin(9600); // assign PWM pins to servos servo[0].attach(3); servo[1].attach(5); servo[2].attach(6); servo[3].attach(9); servo[4].attach(10); servo[5].attach(11); // register servo handler sr.setServoHandler( update_servo, NULL); // set all servos at 45 degrees // servo 0 is fastest SS_Velocity vel = SS_FAST_RATE; for ( int i=0; i<NUM_SERVOS;i++) { sr.setServoTargetAngle(i, SS_DEGREES(45)); sr.setServoMaxVelocity( i, vel ); vel = vel / 2 ; } Serial.println("SimpleServo Ready!"); } // main loop void loop() { // make servos ping-pong between 45 and 135 degrees for ( int i=0; i<NUM_SERVOS;i++) { SS_Angle angle = sr.getServoAngle(i); if ( angle <= SS_DEGREES(45)) { sr.setServoTargetAngle(i, SS_DEGREES(135)); } else if ( angle >= SS_DEGREES(135)) { sr.setServoTargetAngle(i, SS_DEGREES(45)); } } // sr.service() needs to be called regularly so that // the servos are updated via update_servo() sr.service(); }
true
39be0bd2cba3436a434dd1defa3c4e2abebf035d
C++
TheSica/any
/any/main.cpp
UTF-8
465
2.96875
3
[]
no_license
#include <gtest/gtest.h> #include <any> #include "any.h" #include <typeinfo> #include <type_traits> #include <typeindex> struct S { S(std::string v) { tt = v; } S(S&& v) { }; std::string tt; }; int main() { testing::InitGoogleTest(); RUN_ALL_TESTS(); { any a1 = std::list<int>{ 1,2,3 }; any a2 = std::list<int>{ 4,5,6 }; a1.swap(a2); std::list<int> r = any_cast<const std::list<int>&>(a1); std::list<int> a = {1, 2, 3}; } return 0; }
true
f74b190cb539b677f0addc2e9add8a419b7c9a87
C++
Alex7Li/ProgrammingContests
/Kattis/EditingExplosion.cpp
UTF-8
2,998
2.5625
3
[]
no_license
// https://open.kattis.com/contests/nac20open/problems/editingexplosion #include <bits/stdc++.h> using namespace std; #define rep(i, a, b) for (int i = a; i < (b); ++i) #define all(x) begin(x), end(x) #define sz(x) (int)(x).size() typedef long long ll; typedef pair<int, int> pii; typedef vector<int> vi; int levD(string a, string b) { vector<vi> table(a.size() + 1, vi(b.size() + 1, a.size() + b.size())); for (int i = 0; i <= a.size(); i++) { table[i][0] = i; } for (int i = 0; i <= b.size(); i++) { table[0][i] = i; } for (int i = 1; i <= a.size(); i++) { for (int j = 1; j <= b.size(); j++) { if (a[i - 1] == b[j - 1]) { // just concat table[i][j] = table[i - 1][j - 1]; } // add or remove letter table[i][j] = min(table[i][j], table[i - 1][j] + 1); table[i][j] = min(table[i][j], table[i][j - 1] + 1); // edit letter table[i][j] = min(table[i][j], table[i - 1][j - 1] + 1); } } return table[a.size()][b.size()]; } const ll MOD = 998'244'353; ll solve(string s, int d) { map<char, int> letterCounts; for (char a : s) { letterCounts[a] = 1; } letterCounts['0'] = 26 - letterCounts.size(); map<vi, int> states; int n = s.size(); vi emptyStrState(n + 1); iota(emptyStrState.begin(), emptyStrState.end(), 0); ll equalCount = 0; if (emptyStrState[s.size()] == d) { equalCount++; } states[emptyStrState] = 1; for (int strLen = 1; strLen <= n + d; strLen++) { map<vi, int> next_states; for (auto p : states) { vi curState = p.first; int stateCount = p.second; for (auto l : letterCounts) { char letter = l.first; ll letterCount = l.second; // create next state if this is the next letter in the dp vi nextState(n + 1, d + 1); nextState[0] = strLen; for (int j = 1; j <= n; j++) { if (letter == s[j - 1]) { // just concat nextState[j] = curState[j - 1]; } // add or remove letter nextState[j] = min(nextState[j], curState[j] + 1); nextState[j] = min(nextState[j], nextState[j - 1] + 1); // edit letter nextState[j] = min(nextState[j], curState[j - 1] + 1); } // update add this state to the possible next states if (next_states.count(nextState) == 0) { next_states[nextState] = (stateCount * letterCount) % MOD; } else { next_states[nextState] = (next_states[nextState] + stateCount * letterCount) % MOD; } } } states = next_states; for (auto p : states) { vi curState = p.first; int stateCount = p.second; if (curState[curState.size() - 1] == d) { equalCount = (equalCount + stateCount) % MOD; } } } return equalCount; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); string s; cin >> s; int d; cin >> d; cout << solve(s, d) << endl; return 0; }
true
4d1e1da03aaed2caf560a7315e5bdba379d37eba
C++
Bettedaniel/Competition
/Kattis/cargame/cargame2.cpp
UTF-8
1,133
3.0625
3
[]
no_license
#include <iostream> #include <vector> #include <queue> using namespace std; int max(int a, int b) { return a > b ? a : b; } string toLowerCase(string s) { int sz = s.size(); for (int i = 0; i < sz; ++i) { s[i] = tolower(s[i]); } return s; } char match(string a, string b) { int i = 0; int SZ = b.size(); for (int k = 0; k < SZ; ++k) { if (a[i] == b[k]) { ++i; } } if (i == 3) return 1; return 0; } int main() { ios_base::sync_with_stdio(false); int a, b; cin >> a >> b; vector<string> dic(a); for (int i = 0; i < a; ++i) { cin >> dic[i]; } queue<string> tests; string s; for (int i = 0; i < b; ++i) { cin >> s; tests.push(toLowerCase(s)); } while (!tests.empty()) { s = tests.front(); tests.pop(); string ans = ""; for (int i = 0; i < a; ++i) { if (match(s, dic[i])) {ans = dic[i]; break;} } if (ans != "") { cout << ans << endl; } else { cout << "No valid word" << endl; } } }
true
03fcb29bada96963d3987addf48ed52161ebc46c
C++
xinweilau/Data-Structure-and-Algorithm
/AVL.cpp
UTF-8
12,994
3.484375
3
[]
no_license
/* Team Members: Lau Xin Wei (S10155401D) Justin Mar Mariano Justiniano (Student_ID) Group: ? Highlight Feature: - */ #include "stdafx.h" #include "AVL.h" #include <iostream> #include <sstream> #include <iomanip> using namespace std; AVL::AVL() { root = NULL; firstHitCountNode = NULL; } AVL::~AVL() { } void AVL::insert(ItemType item) { BinaryNode* newNode = new BinaryNode(); newNode->item = item; newNode->left = NULL; newNode->right = NULL; newNode->prevHitCount = NULL; newNode->nextHitCount = NULL; newNode->height = 1; root = insert(root, newNode); insertHitCount(firstHitCountNode, newNode); } BinaryNode* AVL::insert(BinaryNode* rootNode, BinaryNode* item) { /* Insert new BinaryNode into the tree */ if (rootNode == NULL) { return item; } if (item->item.getName() <= rootNode->item.getName()) { rootNode->left = insert(rootNode->left, item); } else if (item->item.getName() > rootNode->item.getName()) { rootNode->right = insert(rootNode->right, item); } /* 2. Update Height of Parent Node */ rootNode->height = 1 + max(getHeight(rootNode->left), getHeight(rootNode->right)); /* 3. Check the balance factor of the Parent Node and if depending on the balance factor and conditions, it will rotate the nodes accordingly The balance factor will determine if the tree/sub-tree is balanced */ int balance = getBalance(rootNode); // Left Left Case - Perform a Right Rotation */ if (balance > 1 && item->item.getName() < rootNode->left->item.getName()) { return rightRotate(rootNode); } // Right Right Case - Perform a Left Rotation */ if (balance < -1 && item->item.getName() > rootNode->right->item.getName()) { return leftRotate(rootNode); } // Left Right Case - Perform a Left-Right Rotation */ if (balance > 1 && item->item.getName() > rootNode->left->item.getName()) { rootNode->left = leftRotate(rootNode->left); return rightRotate(rootNode); } /* Right Left Case - Peform a Right-Left Rotation */ if (balance < -1 && item->item.getName() < rootNode->right->item.getName()) { rootNode->right = rightRotate(rootNode->right); return leftRotate(rootNode); } /* return the (unchanged) node pointer */ return rootNode; } void AVL::insertHitCount(BinaryNode* &countNode, BinaryNode* item) { // if there is nothing in the tree yet // if (countNode == NULL) { countNode = item; /* Description: Set the countNode's prevHitCount and nextHitCount to itself Type of Data Structure: circular linked list Time Complexity: Insertion of Highest and Lowest Hit Count - O(1) Average - O(n) */ countNode->prevHitCount = item; countNode->nextHitCount = item; } else { // determine if the new item is equal to or higher in comparison to the last item in the circular linked list // bool highestHitCount = (item->item.getHitCount() >= firstHitCountNode->prevHitCount->item.getHitCount()); // determine if the new item is lowest in comparison to first item in the circular linked list // bool lowestHitCount = (item->item.getHitCount() < firstHitCountNode->item.getHitCount()); // determine if the new item's hit count is smaller than the next item in the list's hit count // bool lowerHitCount = (item->item.getHitCount() <= countNode->item.getHitCount()); if (highestHitCount) { // Get the current item in the list with the highest hit count // BinaryNode* currentHighest = countNode->prevHitCount; // set the new item's next pointer to the first item in the list // item->nextHitCount = countNode; // set the new item's previous pointer to the current last item // item->prevHitCount = currentHighest; // set the first item in the list's previous pointer to the new item // countNode->prevHitCount = item; // set the current item in the list with the highest hit count's pointer to currentHighest->nextHitCount = item; } else if (lowestHitCount) { item->nextHitCount = countNode; item->prevHitCount = countNode->prevHitCount; BinaryNode* temp = countNode; temp->prevHitCount->nextHitCount = item; temp->prevHitCount = item; firstHitCountNode = item; } else if (lowerHitCount) { // set nextHitCount in item too countNode's nextHitCount // item->nextHitCount = countNode; // set prevHitCount in item to countNode // item->prevHitCount = countNode->prevHitCount; BinaryNode* temp = countNode; countNode->prevHitCount->nextHitCount = item; temp->prevHitCount = item; } else { // Traverse through the circular linked list // insertHitCount(countNode->nextHitCount, item); } } } BinaryNode* AVL::getMinValueItem(BinaryNode* node) { BinaryNode* currNode = node; while (currNode->left != NULL) { currNode = currNode->left; } return currNode; } void AVL::remove(ItemType item) { removeHitCount(firstHitCountNode, item); root = remove(root, item); } BinaryNode* AVL::remove(BinaryNode* rootNode, ItemType item) { /* 1. Delete the Node */ if (rootNode == NULL) { return rootNode; } if (item.getName() < rootNode->item.getName()) { // If the item to be deleted is smaller than the root's key, then it is from in left subtree // rootNode->left = remove(rootNode->left, item); } else if (item.getName() > rootNode->item.getName()) { // If the item to be deleted is larger than the root's key, then it is from the right subtree rootNode->right = remove(rootNode->right, item); } else { // item is same as current rootNode // // check if the item to be deleted have one or no child // if ((rootNode->left == NULL) || (rootNode->right == NULL)) { // determine if the child is a left leaf or right leaf // BinaryNode *temp = rootNode->left ? rootNode->left : rootNode->right; // if the item to be removed is the main root // if (temp == NULL) { temp = rootNode; rootNode = NULL; } else { // set the child node as the new parent // *rootNode = *temp; } // release the memory of temp variable // free(temp); } else { /* Case: This Item have 2 childrens Solution: Using inOrder traversal, find the smallest item in the right sub-tree */ BinaryNode* temp = getMinValueItem(root->right); // Copy the inorder successor's data to this node rootNode->item = temp->item; // Delete the inorder successor root->right = remove(root->right, temp->item); } } if (rootNode == NULL) { return rootNode; } // 2. Update the height of affected nodes // rootNode->height = 1 + max(getHeight(rootNode->left), getHeight(rootNode->right)); // 3. Check if the tree is unbalanced (by Balance Factor) // // and make changes accordingly based on the type of unbalance tree // int balance = getBalance(rootNode); // Left Left Case - Perform a Right Rotation // if (balance > 1 && getBalance(rootNode->left) >= 0) { return rightRotate(rootNode); } // Left Right Case - Perform a Left-Right Rotation // if (balance > 1 && getBalance(rootNode->left) < 0) { root->left = leftRotate(rootNode->left); return rightRotate(rootNode); } // Right Right Case - Perform a Left Rotation // if (balance < -1 && getBalance(rootNode->right) <= 0) { return leftRotate(rootNode); } // Right Left Case - perform a Right-Left Rotation // if (balance < -1 && getBalance(rootNode->right) > 0) { root->right = rightRotate(rootNode->right); return leftRotate(rootNode); } // If the tree remained balanced // return rootNode; } void AVL::removeHitCount(BinaryNode* &countNode, ItemType item) { if (firstHitCountNode->item.getName() == item.getName()) { // O(1) deletion - Smallest Item // countNode->nextHitCount->prevHitCount = countNode->prevHitCount; countNode->prevHitCount->nextHitCount = countNode->nextHitCount; firstHitCountNode = countNode->nextHitCount; } else if (firstHitCountNode->prevHitCount->item.getName() == item.getName()) { // O(1) deletion - Largest Item // BinaryNode* largestItem = countNode->prevHitCount; countNode->prevHitCount = largestItem->prevHitCount; largestItem->prevHitCount->nextHitCount = countNode; } else { // O(N) deletion // if (item.getName() == countNode->item.getName()) { countNode->nextHitCount->prevHitCount = countNode->prevHitCount; countNode->prevHitCount->nextHitCount = countNode->nextHitCount; } else { removeHitCount(countNode->nextHitCount, item); } } } bool AVL::isEmpty() { return (root == NULL); } void AVL::hitcountAsc() { int nodes = numOfNodes(root); int count = 1; BinaryNode* copy = firstHitCountNode; while (count <= nodes) { Item i = copy->item; stringstream stream; stream << fixed << setprecision(2) << i.getPrice(); cout << i.getName() << "\t\t" << i.getDescription() << setw(3) << "\t" << stream.str() << "\t" << i.getHitCount() << endl; copy = copy->nextHitCount; count++; } } void AVL::hitcountDesc() { BinaryNode* copy = firstHitCountNode->prevHitCount; int nodes = numOfNodes(root); int count = 1; while (count <= nodes) { Item i = copy->item; stringstream stream; stream << fixed << setprecision(2) << i.getPrice(); cout << i.getName() << "\t\t" << i.getDescription() << setw(3) << "\t" << stream.str() << "\t" << i.getHitCount() << endl; copy = copy->prevHitCount; count++; } } int AVL::numOfNodes(BinaryNode* rootNode) { int count = 0; if (rootNode == NULL) { return 0; } count = 1 + numOfNodes(rootNode->left) + numOfNodes(rootNode->right); return count; } BinaryNode* AVL::rightRotate(BinaryNode* node) { BinaryNode *leftNode = node->left; BinaryNode *leftRightNode = leftNode->right; // Perform rotation leftNode->right = node; node->left = leftRightNode; // Update heights node->height = max(getHeight(node->left), getHeight(node->right)) + 1; leftNode->height = max(getHeight(leftNode->left), getHeight(leftNode->right)) + 1; // Return new root return leftNode; } BinaryNode* AVL::leftRotate(BinaryNode* node) { BinaryNode *rightNode = node->right; BinaryNode *rightLeftNode = rightNode->left; // Perform rotation rightNode->left = node; node->right = rightLeftNode; // Update heights node->height = max(getHeight(node->left), getHeight(node->right)) + 1; rightNode->height = max(getHeight(rightNode->left), getHeight(rightNode->right)) + 1; // Return new root return rightNode; } int AVL::getHeight(BinaryNode* item) { if (item == NULL) { return 0; } else { return item->height; } } int AVL::getBalance(BinaryNode* node) { if (node == NULL) { return 0; } return (getHeight(node->left) - getHeight(node->right)); } void AVL::inOrder() { if (isEmpty()) { cout << "Tree is empty." << endl; } else { inOrder(root); } } void AVL::inOrder(BinaryNode* node) { if (node != NULL) { inOrder(node->left); Item item = node->item; stringstream stream; stream << fixed << setprecision(2) << item.getPrice(); cout << item.getName() << "\t\t" << item.getDescription() << setw(3) << "\t" << stream.str() << "\t" << item.getHitCount() << endl; inOrder(node->right); } } void AVL::preOrder() { if (isEmpty()) cout << "No item found" << endl; else preOrder(root); } void AVL::preOrder(BinaryNode* node) { if (node != NULL) { Item item = node->item; cout << item.getName() << " "; preOrder(node->left); preOrder(node->right); } } void AVL::postOrder() { if (isEmpty()) cout << "No item found" << endl; else postOrder(root); } void AVL::postOrder(BinaryNode* node) { if (node != NULL) { postOrder(node->left); postOrder(node->right); Item item = node->item; cout << item.getName() << endl; } } int AVL::max(int val1, int val2) { return (val1 > val2) ? val1 : val2; } bool AVL::saveData(string fileName) { if (isEmpty()) { cout << "Tree is Empty" << endl; } else { ofstream stream(fileName); if (stream.fail()) { cout << "Failed to open " << fileName << "." << endl; return false; } else { inOrderSave(root, stream); return true; } return false; } } void AVL::inOrderSave(BinaryNode* node, ofstream &stream) { if (node != NULL) { inOrderSave(node->left, stream); Item item = node->item; stringstream sstream; sstream << fixed << setprecision(2) << item.getPrice(); string price = sstream.str(); stream << item.getName() << ";" << item.getDescription() << ";" << price << ";" << item.getHitCount() << endl; inOrderSave(node->right, stream); } } BinaryNode* AVL::search(string Name) { BinaryNode* node = search(root, Name); return node; } BinaryNode* AVL::search(BinaryNode* node, string Name) { if (node == NULL) // item not in tree { return NULL; } else { if (node->item.getName() == Name) //item is found { return node; } else { int cmp = root->item.getName().compare(node->item.getName()); if (cmp <= 0) //search left tree { return search(node->left, Name); } else // search right tree { return search(node->right, Name); } } } }
true
631ab78ed7f777431f91465ef38e4619014c65f4
C++
peterekepeter/carbon
/Carbon/CarbonCompilerLib/Compiler.cpp
UTF-8
979
2.65625
3
[ "MIT" ]
permissive
#include "Compiler.h" #include "Lexer.h" #include "Parser.h" #include <iostream> #include <fstream> #include "Instruction.h" void Carbon::CompileStream(std::istream& stream, InstructionWriter& Output) { // easy peasy Lexer lexer(stream); Parser parser(lexer); PipeInstructions(parser, Output); } void Carbon::CompileStdin(InstructionWriter& Output) { CompileStream(std::cin, Output); } void Carbon::CompileFile(const char* Path, InstructionWriter& Output) { std::ifstream file(Path); CompileStream(file, Output); } void Carbon::CompileFile(const std::string& Path, InstructionWriter& Output) { std::ifstream file(Path); CompileStream(file, Output); } void Carbon::CompileString(const char* SourceCode, InstructionWriter& Output) { std::stringstream stream(SourceCode); CompileStream(stream, Output); } void Carbon::CompileString(const std::string& SourceCode, InstructionWriter& Output) { std::stringstream stream(SourceCode); CompileStream(stream, Output); }
true
124f9c9a58f97500ca2a4641c86fd832feee7562
C++
firesurfer/ros2_components
/src/ros2_components/CLI/CLIParser.cpp
UTF-8
3,447
2.625
3
[ "Apache-2.0" ]
permissive
/* * Copyright 2018 <Lennart Nachtigall> <firesurfer127@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "CLIParser.h" namespace ros2_components { CLIParser::CLIParser(char *argv[], int argc, std::string _programDescription):baseVerb{std::string(argv[0]), _programDescription}, helpArgument{"help", "Print this help", &helpFound} { for(int i=0; i < argc;i++) { this->arguments.push_back(std::string(argv[i])); } //0 arg is the program name baseVerb.addArgument(helpArgument); } void CLIParser::parse() { if(arguments.size() <= 0) return; std::vector<std::string> arg_copy = arguments; arg_copy.erase(arg_copy.begin()); bool error = false; this->baseVerb.parse(arguments, &error); if(helpFound || error) { if(error) { std::cout << printInColor("Bad console argument!", ConsoleColor::FG_RED) << std::endl; } printHelp(this->helpString); exit(0); } } void CLIParser::addVerb(CLIVerb& verb) { this->baseVerb.addVerb(verb); } void CLIParser::addArgument(CLIArgument &arg) { this->baseVerb.addArgument(arg); } void CLIParser::printHelp(std::string additionalInformation) { int depth = 0; std::cout << additionalInformation << std::endl; std::function<void(CLIVerb&)> func = [&](CLIVerb& verb) { //if(!verb) //return; for(int i = 0; i < depth; i++) std::cout << " "; std::cout << printInColor(verb.getName(),ConsoleColor::FG_BLUE) << std::endl; for(int i = 0; i < depth+4; i++) std::cout << " "; std::cout << verb.getDescription() << std::endl << std::endl; if(verb.getAllCliParameter().size() > 0) { for(int i = 0; i < depth+2; i++) std::cout << " "; std::cout << "Needed parameters: " << std::endl; } for(auto cliParam : verb.getAllCliParameter()) { for(int i = 0; i < depth+4; i++) std::cout << " "; std::string output = cliParam.getName() + " "; output.insert(20, cliParam.getDescription()); std::cout << output << std::endl; } for(auto cliArg : verb.getAllCliArguments()) { for(int i = 0; i < depth+4; i++) std::cout << " "; std::string output = " --" + cliArg.getName() + " "; output.insert(20, cliArg.getDescription()); std::cout << output << std::endl; } depth = depth+2; for(auto subVerbEntry : verb.getChildVerbs()) { CLIVerb& subVerb = subVerbEntry.second; func(subVerb); } depth = depth-2; }; func(this->baseVerb); } bool CLIParser::getHelpFound() const { return helpFound; } CLIVerb& CLIParser::getBaseVerb() { return baseVerb; } }
true
208ac49d9188a704fb22e57a6fc93f72c100d8b1
C++
LEE-JAE-HYUN179/Problem_Solving
/acmicpc.net/Problem_1991_트리 순회.cpp
UTF-8
1,514
3.140625
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> using namespace std; int conv(char a) { if (a >= 65 && a <= 90) return a - 65; else if (a == 46) return 26; else return -1; } char invert(int a) { if (a >= 0 && a <= 25) return a + 65; else if (a == 26) return '.'; else return 0; } int find_index(const vector<vector<int>>& tree, int code) { int index = 0; for (auto& n: tree) { if (n[0] == code) break; index++; } return index; } void inorder(const vector<vector<int>>& tree,int root ){ if(root==26) return; int index = find_index(tree, root); inorder(tree,tree[index][1]); cout << invert(root); inorder(tree,tree[index][2]); } void poseorder(const vector<vector<int>>& tree,int root ){ if(root==26) return; int index = find_index(tree, root); poseorder(tree,tree[index][1]); poseorder(tree,tree[index][2]); cout << invert(root); } void preorder(const vector<vector<int>>& tree,int root ){ if(root==26) return; int index = find_index(tree, root); cout << invert(root); preorder(tree,tree[index][1]); preorder(tree,tree[index][2]); } int main() { int num_of_node; cin>> num_of_node; vector<vector<int>> adj_list(num_of_node + 5); for(int i=0; i<num_of_node;i++){ for(int j=0;j<3;j++){ char tmp; cin >> tmp; int tmp2 = conv(tmp); adj_list[i].push_back(tmp2); } } preorder(adj_list,adj_list[0][0]); cout<<endl; inorder(adj_list,adj_list[0][0]); cout<<endl; poseorder(adj_list,adj_list[0][0]); system("pause"); return 0; }
true
08b894f6c1732c60c28aba151c9f6f61a143586c
C++
ishine/google-research
/fair_submodular_matroid/movies_mixed_utility_function.cc
UTF-8
2,355
2.53125
3
[ "CC-BY-4.0", "Apache-2.0" ]
permissive
// Copyright 2023 The Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "movies_mixed_utility_function.h" #include <memory> #include <string> #include <vector> #include "movies_data.h" MoviesMixedUtilityFunction::MoviesMixedUtilityFunction(int user, double alpha) : mf_(), mu_(user), alpha_(alpha) {} void MoviesMixedUtilityFunction::Reset() { mf_.Reset(); mu_.Reset(); } double MoviesMixedUtilityFunction::Delta(int movie) { return alpha_ * mf_.Delta(movie) + (1 - alpha_) * mu_.Delta(movie); } double MoviesMixedUtilityFunction::RemovalDelta(int movie) { return alpha_ * mf_.RemovalDelta(movie) + (1 - alpha_) * mu_.RemovalDelta(movie); } void MoviesMixedUtilityFunction::Add(int movie) { mu_.Add(movie); mf_.Add(movie); } void MoviesMixedUtilityFunction::Remove(int movie) { mu_.Remove(movie); mf_.Remove(movie); } // Not necessary, but overloaded for efficiency double MoviesMixedUtilityFunction::RemoveAndIncreaseOracleCall(int movie) { --oracle_calls_; // Since the below line will incur two oracle calls. return alpha_ * mf_.RemoveAndIncreaseOracleCall(movie) + (1 - alpha_) * mu_.RemoveAndIncreaseOracleCall(movie); } double MoviesMixedUtilityFunction::Objective( const std::vector<int>& movies) const { return alpha_ * mf_.Objective(movies) + (1 - alpha_) * mu_.Objective(movies); } const std::vector<int>& MoviesMixedUtilityFunction::GetUniverse() const { return MoviesData::GetInstance().GetMovieIds(); } std::string MoviesMixedUtilityFunction::GetName() const { return "mix of: " + std::to_string(alpha_) + " of " + mf_.GetName() + " and " + std::to_string(1 - alpha_) + " of " + mu_.GetName(); } std::unique_ptr<SubmodularFunction> MoviesMixedUtilityFunction::Clone() const { return std::make_unique<MoviesMixedUtilityFunction>(*this); }
true
1ff97acdd49947845400361789ea2c7f93f07458
C++
jzrake/Mara2
/src/CartesianMeshGeometry.cpp
UTF-8
3,632
2.671875
3
[]
no_license
#include <cassert> #include "CartesianMeshGeometry.hpp" // ============================================================================ CartesianMeshGeometry::CartesianMeshGeometry() { shape = {{128, 1, 1, 1, 1}}; lower = {{0.0, 0.0, 0.0}}; upper = {{1.0, 1.0, 1.0}}; cacheSpacing(); } CartesianMeshGeometry::CartesianMeshGeometry(Cow::Shape S) { shape = {{S[0], S[1], S[2], 1, 1}}; lower = {{0.0, 0.0, 0.0}}; upper = {{1.0, 1.0, 1.0}}; cacheSpacing(); } CartesianMeshGeometry::CartesianMeshGeometry (int ni, int nj, int nk) { shape = {{ni, nj, nk, 1, 1}}; lower = {{0.0, 0.0, 0.0}}; upper = {{1.0, 1.0, 1.0}}; cacheSpacing(); } void CartesianMeshGeometry::setCellsShape (Cow::Shape S) { shape[0] = S[0]; shape[1] = S[1]; shape[2] = S[2]; cacheSpacing(); } void CartesianMeshGeometry::setLowerUpper (Coordinate L, Coordinate U) { lower = L; upper = U; cacheSpacing(); } Cow::Shape CartesianMeshGeometry::cellsShape() const { return shape; } Cow::Index CartesianMeshGeometry::indexAtCoordinate (Coordinate x) const { return Cow::Index ({{ int((x[0] - lower[0]) / dx[0]), int((x[1] - lower[1]) / dx[1]), int((x[2] - lower[2]) / dx[2]), 0, 0 }}); } Coordinate CartesianMeshGeometry::coordinateAtIndex (double i, double j, double k) const { return Coordinate ({{ lower[0] + dx[0] * (i + 0.5), lower[1] + dx[1] * (j + 0.5), lower[2] + dx[2] * (k + 0.5)}}); } unsigned long CartesianMeshGeometry::totalCellsInMesh() const { return shape[0] * shape[1] * shape[2]; } double CartesianMeshGeometry::cellLength (int i, int j, int k, int axis) const { return dx[axis]; } double CartesianMeshGeometry::cellVolume (int i, int j, int k) const { return dV; } double CartesianMeshGeometry::meshVolume() const { return (upper[0] - lower[0]) * (upper[1] - lower[1]) * (upper[2] - lower[2]); } double CartesianMeshGeometry::faceArea (int i, int j, int k, int axis) const { return dA[axis]; } UnitVector CartesianMeshGeometry::faceNormal (int i, int j, int k, int axis) const { switch (axis) { case 0: return UnitVector::xhat; case 1: return UnitVector::yhat; case 2: return UnitVector::zhat; default: throw std::logic_error ("Axis argument not 0, 1, or 2"); } } double CartesianMeshGeometry::edgeLength (int i, int j, int k, int axis) const { return cellLength (i, j, k, axis); } UnitVector CartesianMeshGeometry::edgeVector (int i, int j, int k, int axis) const { switch (axis) { case 0: return UnitVector::xhat; case 1: return UnitVector::yhat; case 2: return UnitVector::zhat; default: throw std::logic_error ("Axis argument not 0, 1, or 2"); } } Cow::Array CartesianMeshGeometry::getPointCoordinates (int axis) const { assert (0 <= axis && axis < 3); auto coords = Cow::Array (shape[axis] + 1); for (int n = 0; n < coords.size(); ++n) { coords[n] = coordinateAtIndex (n - 0.5, n - 0.5, n - 0.5)[axis]; } return coords; } std::shared_ptr<MeshGeometry> CartesianMeshGeometry::duplicate() const { auto mg = new CartesianMeshGeometry; *mg = *this; return std::shared_ptr<MeshGeometry> (mg); } std::string CartesianMeshGeometry::getType() const { return "cartesian"; } void CartesianMeshGeometry::cacheSpacing() { for (int n = 0; n < 3; ++n) { dx[n] = (upper[n] - lower[n]) / shape[n]; } dA[0] = dx[1] * dx[2]; dA[1] = dx[2] * dx[0]; dA[2] = dx[0] * dx[1]; dV = dx[0] * dx[1] * dx[2]; }
true
3b908c14022778dc1221174b5daeaf3986b4976c
C++
pboechat/PCSS
/application/src/Mesh.h
UTF-8
3,061
2.96875
3
[]
no_license
#pragma once #include <vector> #include <GL/glew.h> #include <glm/glm.hpp> #include "GLUtils.h" struct Mesh { GLuint vao; GLuint positionBuffer; GLuint texcoordsBuffer; GLuint normalBuffer; GLuint indexBuffer; bool hasIndexBuffer; size_t numVertices; size_t numIndices; Mesh(const std::vector<glm::vec3>& vertices, const std::vector<glm::vec2>& uvs, const std::vector<glm::vec3>& normals) : hasIndexBuffer(false), numIndices(0) { glGenVertexArrays(1, &vao); numVertices = vertices.size(); glGenBuffers(1, &positionBuffer); glBindBuffer(GL_ARRAY_BUFFER, positionBuffer); glBufferData(GL_ARRAY_BUFFER, numVertices * sizeof(glm::vec3), &vertices[0], GL_STATIC_DRAW); glGenBuffers(1, &texcoordsBuffer); glBindBuffer(GL_ARRAY_BUFFER, texcoordsBuffer); glBufferData(GL_ARRAY_BUFFER, uvs.size() * sizeof(glm::vec2), &uvs[0], GL_STATIC_DRAW); glGenBuffers(1, &normalBuffer); glBindBuffer(GL_ARRAY_BUFFER, normalBuffer); glBufferData(GL_ARRAY_BUFFER, normals.size() * sizeof(glm::vec3), &normals[0], GL_STATIC_DRAW); checkOpenGLError(); } Mesh(const std::vector<glm::vec3>& vertices, const std::vector<glm::vec2>& uvs, const std::vector<glm::vec3>& normals, const std::vector<unsigned>& indices) : Mesh(vertices, uvs, normals) { hasIndexBuffer = true; numIndices = indices.size(); glGenBuffers(1, &indexBuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, numIndices * sizeof(unsigned), &indices[0], GL_STATIC_DRAW); checkOpenGLError(); } virtual ~Mesh() { glDeleteBuffers(1, &positionBuffer); glDeleteBuffers(1, &texcoordsBuffer); glDeleteBuffers(1, &normalBuffer); if (hasIndexBuffer) glDeleteBuffers(1, &indexBuffer); glDeleteVertexArrays(1, &vao); } void setup(GLuint program) { glBindVertexArray(vao); // Specify the layout of the vertex data GLint positionAttribute = glGetAttribLocation(program, "position"); if (positionAttribute != -1) { glBindBuffer(GL_ARRAY_BUFFER, positionBuffer); glEnableVertexAttribArray(positionAttribute); glVertexAttribPointer(positionAttribute, 3, GL_FLOAT, GL_FALSE, 0, 0); } GLint texcoordsAttribute = glGetAttribLocation(program, "texcoords"); if (texcoordsAttribute != -1) { glBindBuffer(GL_ARRAY_BUFFER, texcoordsBuffer); glEnableVertexAttribArray(texcoordsAttribute); glVertexAttribPointer(texcoordsAttribute, 2, GL_FLOAT, GL_FALSE, 0, 0); } GLint normalAttribute = glGetAttribLocation(program, "normal"); if (normalAttribute != -1) { glBindBuffer(GL_ARRAY_BUFFER, normalBuffer); glEnableVertexAttribArray(normalAttribute); glVertexAttribPointer(normalAttribute, 3, GL_FLOAT, GL_FALSE, 0, 0); } if (hasIndexBuffer) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer); checkOpenGLError(); } void draw() const { glBindVertexArray(vao); if (hasIndexBuffer) glDrawElements(GL_TRIANGLES, (GLsizei)numIndices, GL_UNSIGNED_INT, 0); else glDrawArrays(GL_TRIANGLES, 0, (GLsizei)numVertices); checkOpenGLError(); } };
true
21f18e875aa314bf229c1d3a901bee83bc61ad54
C++
iansmathew/OpenGL-Final-Assignment
/FirstExample/main.cpp
UTF-8
14,727
2.5625
3
[]
no_license
//*************************************************************************** // main.cpp by Ian Sebastian Mathew & Diego Camacho (C) 2018 All Rights Reserved. // // Final Assignment submission. // // Description: // - Move camera with WASD and mouse to look around //***************************************************************************** #include <iostream> #include <list> #include "vgl.h" #include "LoadShaders.h" #include "glm\glm.hpp" #include "glm\gtc\matrix_transform.hpp" #include "glm\gtc\type_ptr.hpp" #include "glm\gtx\rotate_vector.hpp" #include "SOIL.h" #include "Camera.h" #include "ShapeGenerator.h" #include "TextureLoader.h" #include "main.h" //Program pointers GLuint shaderProgram; GLuint uMVP; GLuint uModelMatrix; //Light Attributes float ambientStrength = 0.1f; float specularStrength = 0.25f; float diffuseStrength = 0.5f; glm::vec3 lightColor = glm::vec3(1.0f, 1.0f, 1.0f); glm::vec3 lightPosition = { 10.0f, 10.0f, 10.0f }; //Matrices std::list<glm::mat4> modelViewStack; glm::mat4 projectionMatrix; glm::mat4 modelMatrix; glm::mat4 viewMatrix; //Camera properties glm::vec2 mousePos; Camera camera; float radius = 3.0f; float FOV = 45.0f; float aspectRatio = 1920.f / 1080.f; bool keyStates[256]; //Objects ShapeGenerator shapeGenerator; TextureLoader textureLoader; //-- FUNCTIONS --// //----------------------------------------------------------------------------- //Main Function //----------------------------------------------------------------------------- int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE); glEnable(GL_DEPTH_TEST); glFrontFace(GL_CCW); glCullFace(GL_BACK); glutInitWindowSize(1920, 1080); glutCreateWindow("Final Assignment"); glewInit(); init(); glutDisplayFunc(display); glutTimerFunc(1000.0 / 60.0, timer, 0); glutPassiveMotionFunc(mouseMoveEvent); glutKeyboardUpFunc(keyUp); glutKeyboardFunc(keyDown); glutMainLoop(); } //----------------------------------------------------------------------------- //Initialize //----------------------------------------------------------------------------- void init() { glEnable(GL_DEPTH_TEST); ShaderInfo shaders[] = { { GL_VERTEX_SHADER, "triangles.vert" }, { GL_FRAGMENT_SHADER, "triangles.frag" }, { GL_NONE, NULL } }; shaderProgram = LoadShaders(shaders); glUseProgram(shaderProgram); initCamera(); initLights(); shapeGenerator.init(shaderProgram); /* Initialize objects here */ textureLoader.init(); } //----------------------------------------------------------------------------- //Render function //----------------------------------------------------------------------------- void display() { glClearColor(0.3f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); uploadMatrixToShader(); /* Draw objects here */ pushToStack(); drawDemoShapes(); glutSwapBuffers(); } //----------------------------------------------------------------------------- //Frame based loop function //----------------------------------------------------------------------------- void timer(int id) { controlCamera(); glutPostRedisplay(); glutTimerFunc(1000.0 / 60.0, timer, 0); } //----------------------------------------------------------------------------- //Mouse move event //----------------------------------------------------------------------------- void mouseMoveEvent(int x, int y) { mousePos.x = x; mousePos.y = y; camera.mouseUpdate(mousePos); viewMatrix = camera.getViewMatrix(); glutPostRedisplay(); } //----------------------------------------------------------------------------- //On key down //----------------------------------------------------------------------------- void keyDown(unsigned char key, int x, int y) { keyStates[key] = true; } //----------------------------------------------------------------------------- //On key up //----------------------------------------------------------------------------- void keyUp(unsigned char key, int x, int y) { keyStates[key] = false; } // -- CAMERA AND VIEW FUNCTIONS -- // #pragma region CAMERA_AND_VIEW //----------------------------------------------------------------------------- //Push the current modelViewMatrix to the stack. //----------------------------------------------------------------------------- void pushToStack() { modelViewStack.push_back(modelMatrix); } //----------------------------------------------------------------------------- //Pops the last modelViewMatrix from stack and copies it to the current matrix. //----------------------------------------------------------------------------- void popFromStack() { if (modelViewStack.empty()) throw "Stack is empty."; modelMatrix = modelViewStack.back(); modelViewStack.pop_back(); } //----------------------------------------------------------------------------- //Pushes MVP matrix to shader program. //----------------------------------------------------------------------------- void uploadMatrixToShader() { glm::mat4 modelViewProjection = glm::mat4(1.0f); modelViewProjection = projectionMatrix * viewMatrix * modelMatrix; glUniformMatrix4fv(uMVP, 1, GL_FALSE, glm::value_ptr(modelViewProjection)); glUniformMatrix4fv(uModelMatrix, 1, GL_FALSE, glm::value_ptr(modelMatrix)); } //----------------------------------------------------------------------------- //Initializes lights and uniform pointers //----------------------------------------------------------------------------- void initLights() { GLuint uAmbientStrength = glGetUniformLocation(shaderProgram, "ambientStrength"); glUniform1f(uAmbientStrength, ambientStrength); GLuint uSpecularStrength = glGetUniformLocation(shaderProgram, "specularStrength"); glUniform1f(uSpecularStrength, specularStrength); GLuint uDiffuseStrength = glGetUniformLocation(shaderProgram, "diffuseStrength"); glUniform1f(uDiffuseStrength, diffuseStrength); GLuint uLightColor = glGetUniformLocation(shaderProgram, "lightColor"); glUniform3fv(uLightColor, 1, glm::value_ptr(lightColor)); GLuint uLightPos = glGetUniformLocation(shaderProgram, "lightPos"); glUniform3fv(uLightPos, 1, glm::value_ptr(lightPosition)); GLuint uViewPos = glGetUniformLocation(shaderProgram, "viewPos"); glUniform3fv(uViewPos, 1, glm::value_ptr(camera.getCameraPosition())); } //----------------------------------------------------------------------------- //Initializes camera and sets position //----------------------------------------------------------------------------- void initCamera() { uMVP = glGetUniformLocation(shaderProgram, "uMVP"); uModelMatrix = glGetUniformLocation(shaderProgram, "model"); ///Initializing matrices modelMatrix = glm::mat4(1.0f); viewMatrix = camera.getViewMatrix(); projectionMatrix = glm::mat4(1.0f); projectionMatrix = glm::perspective(glm::radians(FOV), aspectRatio, 0.1f, 100.0f); uploadMatrixToShader(); } //----------------------------------------------------------------------------- //Move camera with keyboard //----------------------------------------------------------------------------- void controlCamera() { if (keyStates['w']) camera.moveForward(); if (keyStates['s']) camera.moveBack(); if (keyStates['a']) camera.strafeLeft(); if (keyStates['d']) camera.strafeRight(); viewMatrix = camera.getViewMatrix(); GLuint uViewPos = glGetUniformLocation(shaderProgram, "viewPos"); glUniform3fv(uViewPos, 1, glm::value_ptr(camera.getCameraPosition())); } #pragma endregion //CAMERA_AND_VIEW void drawDemoShapes() { //Floor textureLoader.loadTexture(shaderProgram, Textures::GRASS); pushToStack(); uploadMatrixToShader(); TranslateRotateScale(glm::vec3(0.0f, -5.0f, 0.0f), 0.0f, glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(1.0f)); shapeGenerator.drawPlane(); popFromStack(); //Hexagon Pillars textureLoader.loadTexture(shaderProgram, Textures::STONE); pushToStack(); TranslateRotateScale(glm::vec3(4.0f, 2.0f, 4.0f), -10.0f, glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(1.0f,2.0f,1.0f)); uploadMatrixToShader(); shapeGenerator.drawHexagon(); popFromStack(); pushToStack(); TranslateRotateScale(glm::vec3(4.0f, 2.0f, -4.0f), 10.0f, glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(1.0f, 2.0f, 1.0f)); uploadMatrixToShader(); shapeGenerator.drawHexagon(); popFromStack(); pushToStack(); TranslateRotateScale(glm::vec3(-4.0f, 2.0f, 4.0f), -10.0f, glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(1.0f, 2.0f, 1.0f)); uploadMatrixToShader(); shapeGenerator.drawHexagon(); popFromStack(); pushToStack(); TranslateRotateScale(glm::vec3(-4.0f, 2.0f, -4.0f), 10.0f, glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(1.0f, 2.0f, 1.0f)); uploadMatrixToShader(); shapeGenerator.drawHexagon(); popFromStack(); //Pillars HalfTop pushToStack(); TranslateRotateScale(glm::vec3(4.0f, 4.0f, 4.0f), -10.0f, glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(1.0f, 1.0f, 1.0f)); uploadMatrixToShader(); shapeGenerator.drawCutCone(); popFromStack(); pushToStack(); TranslateRotateScale(glm::vec3(4.0f, 4.0f, -4.0f), 10.0f, glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(1.0f, 1.0f, 1.0f)); uploadMatrixToShader(); shapeGenerator.drawCutCone(); popFromStack(); pushToStack(); TranslateRotateScale(glm::vec3(-4.0f, 4.0f, 4.0f), -10.0f, glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(1.0f, 1.0f, 1.0f)); uploadMatrixToShader(); shapeGenerator.drawCutCone(); popFromStack(); pushToStack(); TranslateRotateScale(glm::vec3(-4.0f, 4.0f, -4.0f), 10.0f, glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(1.0f, 1.0f, 1.0f)); uploadMatrixToShader(); shapeGenerator.drawCutCone(); popFromStack(); //Pillar Top textureLoader.loadTexture(shaderProgram, Textures::GOLD); pushToStack(); TranslateRotateScale(glm::vec3(4.0f, 6.0f, 4.0f), -10.0f, glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(0.8f, 1.2f, 0.8f)); uploadMatrixToShader(); shapeGenerator.drawCone(); popFromStack(); pushToStack(); TranslateRotateScale(glm::vec3(4.0f, 6.0f, -4.0f), 10.0f, glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(0.8f, 1.2f, 0.8f)); uploadMatrixToShader(); shapeGenerator.drawCone(); popFromStack(); pushToStack(); TranslateRotateScale(glm::vec3(-4.0f, 6.0f, 4.0f), -10.0f, glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(0.8f, 1.2f, 0.8f)); uploadMatrixToShader(); shapeGenerator.drawCone(); popFromStack(); pushToStack(); TranslateRotateScale(glm::vec3(-4.0f, 6.0f, -4.0f), 10.0f, glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(0.8f, 1.2f, 0.8f)); uploadMatrixToShader(); shapeGenerator.drawCone(); popFromStack(); //Castle Walls textureLoader.loadTexture(shaderProgram, Textures::STONE); pushToStack(); TranslateRotateScale(glm::vec3(-4.0f, 2.0, 0), 0.0f, glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(.2f, 2.0f, 3.15f)); uploadMatrixToShader(); shapeGenerator.drawCube(); popFromStack(); pushToStack(); TranslateRotateScale(glm::vec3(4.0f, 2.0, 0), 0.0f, glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(.2f, 2.0f, 3.15f)); uploadMatrixToShader(); shapeGenerator.drawCube(); popFromStack(); pushToStack(); TranslateRotateScale(glm::vec3(0.0f, 2.0, -4.0), 0.0f, glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(3.15f, 2.0f, .2f)); uploadMatrixToShader(); shapeGenerator.drawCube(); popFromStack(); //-->Front Wall pushToStack(); TranslateRotateScale(glm::vec3(-2.5, 2.0, 4.0), 0.0f, glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(1.05f, 2.0f, .2f)); uploadMatrixToShader(); shapeGenerator.drawCube(); popFromStack(); pushToStack(); TranslateRotateScale(glm::vec3(2.5, 2.0, 4.0), 0.0f, glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(1.05f, 2.0f, .2f)); uploadMatrixToShader(); shapeGenerator.drawCube(); popFromStack(); pushToStack(); TranslateRotateScale(glm::vec3(0, 3.0, 4.0), 0.0f, glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(1.45, 1.3, .2f)); uploadMatrixToShader(); shapeGenerator.drawCube(); popFromStack(); //Middle Stand textureLoader.loadTexture(shaderProgram, Textures::COOBLESTONE); pushToStack(); TranslateRotateScale(glm::vec3(0, 0.4f, 0), 0.0f, glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(0.5f, 0.8, 0.5f)); uploadMatrixToShader(); shapeGenerator.drawFrustum(); popFromStack(); //Diamond textureLoader.loadTexture(shaderProgram, Textures::SILVER); pushToStack(); TranslateRotateScale(glm::vec3(0, 3.0f, 0), 0.0f, glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(1.0f, 1.0f, 1.0f)); uploadMatrixToShader(); shapeGenerator.drawDiamond(); popFromStack(); //Diamond Top textureLoader.loadTexture(shaderProgram, Textures::GOLD); pushToStack(); TranslateRotateScale(glm::vec3(0, 5.0f, 0), 0.0f, glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(1.0f, 1.0f, 1.0f)); uploadMatrixToShader(); shapeGenerator.drawTorus(); popFromStack(); //Wedges textureLoader.loadTexture(shaderProgram, Textures::WOOD); pushToStack(); TranslateRotateScale(glm::vec3(2.0f, 0.5, 0), 90.0f, glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(0.5f, 0.5f, 0.5f)); uploadMatrixToShader(); shapeGenerator.drawWedge(); popFromStack(); pushToStack(); TranslateRotateScale(glm::vec3(-2.0f, 0.5, 0), -90.0f, glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(0.5f, 0.5f, 0.5f)); uploadMatrixToShader(); shapeGenerator.drawWedge(); popFromStack(); pushToStack(); TranslateRotateScale(glm::vec3(0.0f, 0.5, -2.0f), 180.0f, glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(0.5f, 0.5f, 0.5f)); uploadMatrixToShader(); shapeGenerator.drawWedge(); popFromStack(); //Half_Hexagons pushToStack(); TranslateRotateScale(glm::vec3(0.0f, 4.3f, -4.0), 180.0f, glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(1.0f, 0.8, .2f)); uploadMatrixToShader(); shapeGenerator.drawHalfHexagon(); popFromStack(); pushToStack(); TranslateRotateScale(glm::vec3(4.0, 4.3f, 0.0f), 180.0f, glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(.2f, 0.8, 1.0f)); uploadMatrixToShader(); shapeGenerator.drawHalfHexagon(); popFromStack(); pushToStack(); TranslateRotateScale(glm::vec3(-4.0, 4.3f, 0.0f), 180.0f, glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(.2f, 0.8, 1.0f)); uploadMatrixToShader(); shapeGenerator.drawHalfHexagon(); popFromStack(); pushToStack(); TranslateRotateScale(glm::vec3(0.0f, 4.6f, 4.0), 180.0f, glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(1.0f, 0.8, .2f)); uploadMatrixToShader(); shapeGenerator.drawHalfHexagon(); popFromStack(); //Triangle textureLoader.loadTexture(shaderProgram, Textures::GOLD); pushToStack(); TranslateRotateScale(glm::vec3(0.0f, 3.0f, 5.0f), 90.f, glm::vec3(1.0f, 0.0f, 0.0f), glm::vec3(1.0f, 0.5, 0.5)); uploadMatrixToShader(); shapeGenerator.drawPyramid(); popFromStack(); } void TranslateRotateScale(glm::vec3 translation, float rotationAngle, glm::vec3 rotationAxis , glm::vec3 scaleRatio){ modelMatrix = glm::translate(modelMatrix, translation); modelMatrix = glm::rotate(modelMatrix, glm::radians(rotationAngle), rotationAxis); modelMatrix = glm::scale(modelMatrix, scaleRatio); }
true
bfb285e5476a0e8be843ba6a8fa190e814d218e1
C++
amecky/diesel2D
/utils/Trails.h
UTF-8
981
2.546875
3
[]
no_license
#pragma once #include "..\world\World.h" #include "..\particles\ParticleManager.h" #include <map> namespace ds { class Trails { enum TrailEmitType { TET_DISTANCE, TET_TIME, TET_FRAMES }; struct TrailPiece { Vector2f prevPosition; int particleSystem; union { float distance; int frames; float time; }; union { float timer; int frameCounter; }; float angle; TrailEmitType emitType; }; typedef std::map<SID, TrailPiece> Pieces; public: Trails(World* world, ParticleManager* particles); ~Trails(void); void add(SID sid, float distance, int particleSystem); void add(SID sid, float angle, float distance, int particleSystem); void addFrameBased(SID sid, float angle, int frames, int particleSystem); void addTimeBased(SID sid, float angle, float ttl, int particleSystem); void tick(float dt); void remove(SID sid); private: World* _world; ParticleManager* _particles; Pieces _pieces; }; }
true
fb6d31018482ca2299253d917d01b1a9adeb3262
C++
mvdsanden/libecpp-devtools
/src/initmod/main.cc
UTF-8
1,375
2.9375
3
[]
no_license
#include "initmod.ih" #include <ecpp/string/string.hh> int InitMod::main(ArgList::iterator begin, ArgList::iterator end) { if (d_context.initialized()) throw runtime_error("we are already inside a project"); string ns = ""; string name = ""; for (ArgList::iterator i = begin; i != end; ++i) { // Parse options. if ((*i).length() > 2 && (*i).substr(0,2) == "--") { string option = (*i).substr(2,(*i).length()-2); if (option == "ns") { ++i; ns = *i; } else { usage(); throw runtime_error("unknown option"); } } else { if (d_context.initialized()) { usage(); throw runtime_error("Extra argument given"); } vector<string> id = String::split(*i,"::"); if (id.size() == 2) { ns = id[0]; name = id[1]; } else if (id.size() == 1) { name = id[0]; } else { usage(); throw runtime_error("nested namespaces are not supported"); } if (name.empty()) { usage(); throw runtime_error("no or empty project name given"); } if (ns.empty()) { usage(); throw runtime_error("no or empty project namespace given"); } // initialize the project. d_context.initNew(name,ns); } } if (!d_context.initialized()) { usage(); } cout << "Initializing this directory as project '" << ns << "::" << name << "'." << endl; return 0; }
true
66a7aea5229f526ea815ec6d75f76026cccae355
C++
SumitKumar1107/InterView
/Arrays/MissingNumber.cpp
UTF-8
684
3.5625
4
[]
no_license
Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array. Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity? Input: nums = [3,0,1] Output: 2 Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums. int missingNumber(vector<int>& nums) { int n = nums.size(); int sum = n*(n+1)/2; int ans = 0; for(int i=0;i<nums.size();i++) { ans += nums[i]; } return sum-ans; }
true
16be730f9509e5b09947859f70b1e49deb9e48d7
C++
Kev1venteur/B2_JeuxRPGCapture
/projet/include/zone.h
UTF-8
761
2.765625
3
[]
no_license
#ifndef ZONE_H #define ZONE_H #include <string> using namespace std; class Zone { public: Zone(); virtual ~Zone(); string getType(); void setType(string type); unsigned short int getXmin(); void setXmin(unsigned int value); unsigned short int getXmax(); void setXmax(unsigned int value); unsigned short int getYmin(); void setYmin(unsigned int value); unsigned short int getYmax(); void setYmax(unsigned int value); protected: private: unsigned short int xMin; unsigned short int xMax; unsigned short int yMin; unsigned short int yMax; string typeZone; }; #endif // ZONE_H
true
adfee8d145d6edede699f148308c9d3a0db93d79
C++
AndreeaRT/sem5_OOP
/crudrepo.h
UTF-8
641
2.546875
3
[]
no_license
#pragma once #include "Wagen.h" #include <vector> #include <iostream> using namespace std; template <class E> class CrudRepository { public: virtual E Finde(int id) = 0; virtual vector< E > findAll() = 0; virtual E save(E entity) = 0; virtual E del(int id) = 0; virtual E update(E entity) = 0; virtual ~CrudRepository() {}; }; class AutoInMemoryRepository: public CrudRepository<Wagen*> { public: AutoInMemoryRepository(); Wagen* Finde(int id); vector<Wagen*>autos; Wagen* Finde(int id); vector<Wagen*> findAll(); Wagen* save(Wagen* entity); Wagen* del(int id); Wagen* update(Wagen* entity); };
true
9258a924d3f51a20500f3a2cf879eac844653637
C++
kc991229/practice
/2020.7.23/2020.7.23/text.cpp
GB18030
2,592
3.65625
4
[]
no_license
/* һֳֵĴ鳤ȵһ룬ҳ֡ һΪ9{1,2,3,2,2,2,5,4,2} 2г5Σ鳤ȵһ룬20 */ #include <iostream> #include <vector> #include <algorithm> using namespace std; int MoreThanHalfNum_Solution(vector<int> numbers) { if (numbers.empty()) return 0; sort(numbers.begin(), numbers.end()); int middle = numbers[numbers.size() / 2]; int count = 0; // ִ for (int i = 0; i<numbers.size(); ++i) { if (numbers[i] == middle) ++count; } return (count>numbers.size() / 2) ? middle : 0; } /* һ򵥴¼Сģ飬ܹ¼Ĵڵļƺкš 1 ¼8¼ѭ¼˵ֵֻݼ ͬĴ¼ļ16λƺкȫƥ䣩ֻ¼һӣ 2 16ַļƣֻ¼ļЧ16ַ 3 ļܴ·¼ļƲܴ· : һлַÿа·ļƣкţԿո : еļ¼ͳƲʽļ Ŀһո磺 ʾ1 E:\V1R2\product\fpgadrive.c 1325 fpgadrive.c 1325 1 */ #include <iostream> #include <string> #include <vector> #include <sstream> #include <algorithm> string getFileName(string path){ int pos = path.rfind('\\'); return path.substr(pos + 1); } string modifyName(string name){ if (name.size() > 16){ name = name.substr(name.size() - 16); } return name; } struct ErrRecord{ string file; int lineNo; int count; ErrRecord(string file, int lineNo){ this->file = file; this->lineNo = lineNo; count = 1; } bool operator==(const ErrRecord & a){ return (file == a.file) && (lineNo == a.lineNo); } }; int main() { string file; int lineNo; vector<ErrRecord> myvec; while (cin >> file >> lineNo){ ErrRecord record(getFileName(file), lineNo); auto res = find(myvec.begin(), myvec.end(), record); if (res == myvec.end()){ myvec.push_back(record); } else{ res->count++; } } int count = 0; for (auto item : myvec){ if (count + 8 >= myvec.size()){ cout << modifyName(item.file) << " " << item.lineNo << " " << item.count << endl; } count++; } return 0; }
true
cf5b308031b3697a4ed909b6c2abf6ddb56f6ebe
C++
rhalf/SulitPisoLibraries
/ArduinoLibraries/20201231/BillCoinAcceptor/BillCoinAcceptor.cpp
UTF-8
1,481
2.875
3
[]
no_license
#include "BillCoinAcceptor.h" #include "Arduino.h" typedef void (* Callback)(); BillCoinAcceptor::BillCoinAcceptor(uint16_t pin) { _pin = pin; _multiplier = 1; if (_activeState) { pinMode(_pin, INPUT); } else { pinMode(_pin, INPUT_PULLUP); } } BillCoinAcceptor::BillCoinAcceptor(uint16_t pin, uint8_t multiplier) { _pin = pin; _multiplier = multiplier; if (_activeState) { pinMode(_pin, INPUT); } else { pinMode(_pin, INPUT_PULLUP); } } BillCoinAcceptor::BillCoinAcceptor(uint16_t pin, uint8_t multiplier, bool activeState) { _pin = pin; _multiplier = multiplier; _activeState = activeState; if (_activeState) { pinMode(_pin, INPUT); } else { pinMode(_pin, INPUT_PULLUP); } } void BillCoinAcceptor::attach(Callback callBack) { if (_activeState) { attachInterrupt(digitalPinToInterrupt(_pin), callBack, RISING); } else { attachInterrupt(digitalPinToInterrupt(_pin), callBack, FALLING); } } void BillCoinAcceptor::detach(void) { detachInterrupt(digitalPinToInterrupt(_pin)); } void BillCoinAcceptor::readPulse(void) { // invalidate signals beyond minimum interval for (_index = 0; _index < interval; _index++) { if (digitalRead(_pin) != _activeState) return; else delay(1); } pulse += 1; value = pulse * _multiplier; } void BillCoinAcceptor::clear(void) { pulse = 0;; value = 0; }
true
025ee82b26ec39d72343cf6e1c501a87786c41f0
C++
OrhanKupusoglu/find-first-id
/test/src/test_kbtree.cpp
UTF-8
7,748
2.6875
3
[ "MIT" ]
permissive
#include "gtest/gtest.h" #include <bitset> #include "../include/kcommon_tests.h" #include "../../src/include/kbtree.h" TEST(TestKBTree, BTreeDivMod) { using num_div_mod_t = std::tuple<uint32_t, uint32_t, uint32_t>; std::vector<num_div_mod_t> test_inputs = {{ 0, 0, 0}, { 1, 0, 1}, { 63, 0, 63}, { 64, 1, 0}, { 127, 1, 63}, { 128, 2, 0}, {65535, 1023, 63}, {65536, 1024, 0}}; kupid::kbtree id_factory{0}; for (const auto& num : test_inputs) { auto div_mod = id_factory.get_div_and_mod_by_64(std::get<0>(num)); std::cout.width(8); std::cout << std::right << std::get<0>(num) << " = "; std::cout.width(6); std::cout << std::right << std::get<1>(num) << " x 64 + " << std::get<2>(num) << '\n'; ASSERT_EQ(div_mod.div, std::get<1>(num)); ASSERT_EQ(div_mod.mod, std::get<2>(num)); } } TEST(TestKBTree, BTree64BitsIsFull) { std::vector<uint64_t> test_inputs = {0x0, 0x1, 0xFF, 0xFFF, 0xFFFF, 0xFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF}; kupid::kbtree id_factory{0}; for (const auto& num : test_inputs) { std::bitset<64> bits(num); std::cout << bits; if (num == 0xFFFFFFFFFFFFFFFF) { std::cout << " - full" << '\n'; ASSERT_TRUE(id_factory.is_full(num)); } else { std::cout << " - not full" << '\n'; ASSERT_FALSE(id_factory.is_full(num)); } } } TEST(TestKBTree, BTree64BitsIsOn) { using num_bit_on_t = std::tuple<uint64_t, uint64_t, bool>; std::vector<num_bit_on_t> test_inputs = {{ 0x0, 0, false}, { 0x1, 0, true}, { 0x10, 4, true}, { 0x100, 7, false}, { 0x100, 8, true}, { 0x10000000, 28, true}, { 0x100000000000, 44, true}, {0x1000000000000000, 60, true}, {0x4000000000000000, 62, true}, {0x4000000000000000, 63, false}, {0x8000000000000000, 63, true}}; kupid::kbtree id_factory{0}; for (const auto& num : test_inputs) { auto num64 = std::get<0>(num); auto index = std::get<1>(num); auto is_on = std::get<2>(num); std::bitset<64> bits(num64); std::cout << bits << " - bit[" << index << "] : " << std::boolalpha << is_on << '\n'; if (is_on) { ASSERT_TRUE(id_factory.is_bit_on(num64, index)); } else { ASSERT_FALSE(id_factory.is_bit_on(num64, index)); } } } TEST(TestKBTree, BTree64BitsSetBitOn) { kupid::kbtree id_factory{0}; for (int i = 0; i < 64; ++i) { uint64_t num = 0; id_factory.set_bit_on(num, i); std::bitset<64> bits(num); std::cout << bits << " - bit[" << i << "] : " << std::boolalpha << true << '\n'; ASSERT_TRUE(id_factory.is_bit_on(num, i)); } } TEST(TestKBTree, BTree64BitsSetBitOff) { kupid::kbtree id_factory{0}; for (int i = 0; i < 64; ++i) { uint64_t num = 0xFFFFFFFFFFFFFFFF; id_factory.set_bit_off(num, i); std::bitset<64> bits(num); std::cout << bits << " - bit[" << i << "] : " << std::boolalpha << false << '\n'; ASSERT_FALSE(id_factory.is_bit_on(num, i)); } } TEST(TestKBTree, BTree64BitsFindFirstBit1) { kupid::kbtree id_factory{0}; for (int i = 0; i < 64; ++i) { uint64_t num = 0xFFFFFFFFFFFFFFFF; id_factory.set_bit_off(num, i); std::bitset<64> bits(num); std::cout << bits << " - bit[" << i << "] : first free bit\n"; ASSERT_EQ(id_factory.find_first_free_bit(num), i); } } TEST(TestKBTree, BTree64BitsFindFirstBit2) { kupid::kbtree id_factory{0}; for (int i = 0; i < 64; ++i) { uint64_t num = 0; for (int j = 0; j < i; ++j) { id_factory.set_bit_on(num, j); } std::bitset<64> bits(num); std::cout << bits << " - bit[" << i << "] : first free bit\n"; ASSERT_EQ(id_factory.find_first_free_bit(num), i); } } TEST(TestKBTree, BTree64BitsFindFirstBit3) { kupid::kbtree id_factory{0}; kupid::krandom_int rnd_factory{64}; for (uint32_t i = 0; i < 64; ++i) { uint64_t num = 0; uint32_t index = 0; for (uint32_t j = 0; j < i; ++j) { id_factory.set_bit_on(num, j); } auto r = rnd_factory.get_random(); id_factory.set_bit_off(num, r); auto k = id_factory.find_first_free_bit(num); if (r > i) { index = i; } else { index = r; } std::bitset<64> bits(num); std::cout << bits << " - bit[" << index << "] : first free bit\n"; ASSERT_EQ(k, index); } } TEST(TestKBTree, BTreeSizeSlice) { uint32_t size = 352; std::cout << "test kupid::kbtree with size = " << size << '\n'; kupid::kbtree id_factory{size}; ASSERT_EQ(id_factory.size(), size); auto dm = id_factory.get_div_and_mod_by_64(size); auto slice = dm.mod > 0 ? dm.div + 1 : dm.div; std::cout << "slice = " << slice << '\n'; ASSERT_EQ(id_factory.slice(), slice); } TEST(TestKBTree, BTreeDataByIndex) { uint32_t size = 352; std::cout << "test kupid::kbtree with size = " << size << '\n'; kupid::kbtree id_factory{size}; ASSERT_EQ(id_factory.size(), size); for (uint32_t i = 0; i < size; ++i) { id_factory.use_id(i); } auto last_1 = id_factory.get_data(id_factory.size() - 1, false); std::bitset<64> bits(last_1); std::cout << bits << " - last data chunk : get_data(" << (id_factory.size() - 1) << ", false)\n"; auto last_2 = id_factory.get_data(id_factory.slice() - 1, true); bits = std::bitset<64>(last_2); std::cout << bits << " - last data chunk : get_data(" << (id_factory.slice() - 1) << ", true)\n"; ASSERT_EQ(last_1, last_2); } // common tests kcommon_tests<kupid::kbtree> test_kbtree{"kupid::kbtree"}; TEST(TestKBTree, SizeZero) { test_kbtree.test_size_zero(); } TEST(TestKBTree, SizeOne) { test_kbtree.test_size_one(); } TEST(TestKBTree, SizeTwo) { test_kbtree.test_size_two(); } TEST(TestKBTree, ClearUseHalf) { test_kbtree.test_clear_use_half(); } TEST(TestKBTree, SizeSmall) { test_kbtree.test_size_small(); } TEST(TestKBTree, SizeMedium) { test_kbtree.test_size_medium(); } TEST(TestKBTree, SizeLarge) { test_kbtree.test_size_large(); } #ifdef TEST_XLARGE TEST(TestKBTree, SizeXLarge) { test_kbtree.test_size_xlarge(); } #endif TEST(TestKBTree, RandomUnordered) { test_kbtree.test_random_unordered(); } TEST(TestKBTree, RandomOrdered) { test_kbtree.test_random_ordered(); }
true
e4e3978dfe7719529bc64214017c93b671ef07ba
C++
tokheim/amqpprox
/libamqpprox/amqpprox_vhoststate.cpp
UTF-8
1,693
2.671875
3
[ "Apache-2.0" ]
permissive
/* ** Copyright 2020 Bloomberg Finance L.P. ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ #include <amqpprox_vhoststate.h> #include <algorithm> #include <iostream> #include <map> namespace Bloomberg { namespace amqpprox { VhostState::VhostState() : d_vhosts() , d_mutex() { } VhostState::State::State() : d_paused(false) { } VhostState::State::State(const State& rhs) : d_paused(rhs.d_paused) { } bool VhostState::isPaused(const std::string &vhost) { std::lock_guard<std::mutex> lg(d_mutex); return d_vhosts[vhost].isPaused(); } void VhostState::setPaused(const std::string &vhost, bool paused) { std::lock_guard<std::mutex> lg(d_mutex); d_vhosts[vhost].setPaused(paused); } void VhostState::print(std::ostream &os) { std::map<std::string, State> sortedVhosts; { std::lock_guard<std::mutex> lg(d_mutex); std::copy(d_vhosts.cbegin(), d_vhosts.cend(), std::inserter(sortedVhosts, sortedVhosts.end())); } for (const auto &vhost : sortedVhosts) { auto paused = (vhost.second.isPaused() ? "PAUSED" : "UNPAUSED"); os << vhost.first << " = " << paused << "\n"; } } } }
true
47df49a04389ccc70dfd5805a6448879bf7a8722
C++
whlqz9300/leetcode
/LeetCode039_FindMinInRotatedList.cpp
UTF-8
426
3.015625
3
[]
no_license
class Solution { public: int findMin(vector<int> &num) { typedef vector<int>::iterator IterType; IterType bottom_it = num.begin(), top_it = --num.end(), mid_it; while (bottom_it < top_it){ mid_it = bottom_it + (top_it - bottom_it) / 2; if (*bottom_it > *top_it){ bottom_it = mid_it; } else top_it = mid_it; } return *bottom_it; } };
true
0e42e83f6911904ef8565ccd8f90c3dcd0b4426a
C++
shobhit-saini/IB
/Day5/Anti_diagonal.cpp
UTF-8
639
3.671875
4
[]
no_license
/* Give a N*N square matrix, return an array of its anti-diagonals. Look at the example for more details. Example: Input: 1 2 3 4 5 6 7 8 9 Return the following : [ [1], [2, 4], [3, 5, 7], [6, 8], [9] ] Input : 1 2 3 4 Return the following : [ [1], [2, 3], [4] ] */ vector<vector<int> > Solution::diagonal(vector<vector<int> > &A) { int i, j, k = 0, a; vector<vector<int>> result(2*A.size()-1); for(i = 0; i < A.size(); i++) { k = i; for(j = 0 ; j < A.size(); j++) { result[k].push_back(A[i][j]); k++; } } return result; }
true
77fb6a27dff28a1f7a07a0bfee98cba01a663a57
C++
Zhanghq8/Leetcode_notes
/57_Insert_Interval/submission1.cpp
UTF-8
988
3.125
3
[]
no_license
#include <iostream> #include <string> #include <cmath> using namespace std; class Solution { public: vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) { if (intervals.empty()) { return {newInterval}; } vector<vector<int>> result; int index = 0; while (index < intervals.size() && intervals[index][1] < newInterval[0]) { result.push_back(intervals[index]); index++; } while (index < intervals.size() && intervals[index][0] <= newInterval[1]) { newInterval[0] = min(intervals[index][0], newInterval[0]); newInterval[1] = max(intervals[index][1], newInterval[1]); index++; } result.push_back({newInterval[0], newInterval[1]}); while (index < intervals.size()) { result.push_back({intervals[index][0], intervals[index][1]}); index++; } return result; } };
true
ae0f87b8ca3da6067b65ac069ed9819f46668d7c
C++
luice/climap
/example/fib_main.cpp
UTF-8
2,950
3.34375
3
[ "MIT" ]
permissive
#include <iostream> #include <stdexcept> #include <string> #include "CLIMap.hpp" #include "integer_tests.hpp" #include "whiteboard.hpp" #include "fib_main.hpp" using std::cout; using std::endl; using std::invalid_argument; using std::out_of_range; using std::stoi; int fib_main(int, char**); int fib_f0_main(int, char**); int fib_f1_main(int, char**); int fib_set_f0_f1(int, char**, int*); int fib_out_of_range_main(int, char**); int fib_calculate_main(int, char**); int fib_invalid_noarg_main(int, char**); int fib_invalid_anyarg_main(int, char**); int fib_f0 = 0; int fib_f1 = 1; int fib_main(int argc, char **argv) { constexpr CLIMap<> climap { {"f0", fib_f0_main}, {"f1", fib_f1_main}, {is_out_of_range_integer, fib_out_of_range_main}, {is_non_negative_integer, fib_calculate_main}, {noarg, fib_invalid_noarg_main}, {anyarg, fib_invalid_anyarg_main} }; return climap.exec(argc, argv); } int fib_f0_main(int argc, char **argv) { return fib_set_f0_f1(argc, argv, &fib_f0); } int fib_f1_main(int argc, char **argv) { return fib_set_f0_f1(argc, argv, &fib_f1); } int fib_set_f0_f1(int argc, char **argv, int *f0orf1Ptr) { assert(argc>0); const char * f0orf1_cstring = argv[0]; if (argc==1) { cout << "No argument provided to fib/" << f0orf1_cstring << " command." << endl; return ARGMAP_EXIT_INVALID_ARG; } const char * arg_cstring = argv[1]; int arg_int; try { arg_int = stoi(arg_cstring); } catch (const invalid_argument&) { cout << "fib/" << f0orf1_cstring << " argument \"" << arg_cstring << "\" is not an integer." << endl; return ARGMAP_EXIT_INVALID_ARG; } catch (const out_of_range&) { cout << "fib/" << f0orf1_cstring << " argument \"" << arg_cstring << "\" out of range. Try an integer closer to zero." << endl; return ARGMAP_EXIT_INVALID_ARG; } *f0orf1Ptr = arg_int; int num_args_parsed = 1; return argmap_return_success(argc, num_args_parsed); } int fib_out_of_range_main(int argc, char **argv) { assert(argc>0); const char * arg = argv[0]; cout << "Fib argument " << arg << " out of range. Try a non-negative integer closer to zero." << endl; return ARGMAP_EXIT_INVALID_ARG; } int fib_calculate_main(int argc, char **argv) { assert(argc>0); const char * arg_cstring = argv[0]; int arg_int = stoi(arg_cstring); cout << fib(arg_int, fib_f0, fib_f1) << endl; return argmap_return_success(argc); } int fib_invalid_noarg_main(int argc, char **argv) { assert(argc>0); cout << "No argument provided to fib command." << endl; return ARGMAP_EXIT_INVALID_ARG; } int fib_invalid_anyarg_main(int argc, char **argv) { assert(argc>0); cout << "Fib argument \"" << argv[1] << "\" is invalid - not \"f0\", nor \"f1\", nor a non-negative integer." << endl; return ARGMAP_EXIT_INVALID_ARG; }
true
cbdf1fe44f7fa71b29bbf72e531ae9dfc00929cc
C++
checkmate-bitch/Random-Programs
/ProjectEuler/p33.cpp
UTF-8
884
3.296875
3
[]
no_license
#include<iostream> #include<time.h> using namespace std; float get(int x, int y) { float n, m; if(x%10 == y%10) { n= x/10; m= y/10; } else if(x%10 == y/ 10) { n= x/10; m= y%10; } else if(x/10== y%10) { n= x%10; m= y/10; } else if(x/10 == y/10) { n= x%10; m= y%10; } else return -1; return n/m; } int main() { clock_t t1, t2; t1= clock(); int den= 1, num= 1; for(int i= 10; i< 100; i++) { if(i%10!= 0) { for(int j= i+1; j< 100; j++) { float no= 0; if(j%10!= 0) { no= (float)i/(float)j; if(no== get(i, j)) { cout<<"i= "<<i<<"\tj= "<<j<<endl; num*= i; den*= j; } } } } } cout<<"fraction is "<<(float)num/den<<"\t for num= "<<num<<"\t den= "<<den<<endl; t2= clock(); float diff= ((float)t2- (float)t1)/CLOCKS_PER_SEC; cout<<"time taken is "<<diff<<" seconds\n"; return 0; }
true
cc7a9db5f4507b631bf2ba136174e28065c5c836
C++
S3FA/shrimp-cannon
/shrimpcannon/shrimpcannon.ino
UTF-8
1,177
2.5625
3
[]
no_license
#include <Button.h> #include <Tlc5940.h> #define TLC_ON 4095 #define TLC_OFF 0 #define BUTTON_PIN 14 #define NUM_EFFECTS 5 Button button = Button(BUTTON_PIN, BUTTON_PULLUP_INTERNAL, true, 100); // when an effect should start int onTimeouts[NUM_EFFECTS] = {0, 60, 120, 180, 0}; // how long an effect is on for int onLength[NUM_EFFECTS] = {60, 60, 60, 60, 200}; int offTimeouts[NUM_EFFECTS]; void setup() { for (int i = 0; i < NUM_EFFECTS; i++) { offTimeouts[i] = onTimeouts[i] + onLength[i]; } Tlc.init(); Tlc.clear(); Tlc.update(); button.pressHandler(onPress); } void loop() { button.process(); Tlc.clear(); Tlc.update(); } void onPress(Button& b){ doRoutine(millis()); } // actually do the routine void doRoutine(long startTime) { while (true) { int loopTime = millis() - startTime; for (int i = 0; i < NUM_EFFECTS; i++) { if (loopTime > onTimeouts[i] && loopTime < offTimeouts[i]) { Tlc.set(i, TLC_ON); } else { Tlc.set(i, TLC_OFF); } } Tlc.update(); // leave loop if past last routine step if (loopTime > offTimeouts[NUM_EFFECTS - 1]) { break; } } }
true
7637df970cf3eec71cdc20825bbce782ffb1e6cb
C++
shivam-72/C-basics
/C++ BASICS/mainelseif.cpp
UTF-8
276
2.828125
3
[]
no_license
#include<iostream> using namespace std; int main(){ int a; cout<<"Enter the no. : "; cin>>a; if(a<18){ cout<<" he can't vote : "; } else if(a==18){ cout<<" he can vote : "; } else cout<<"he can easily vote : " ; return 0; }
true
15737bf9e37679f85c8958c8e8d077e2a8c8afa1
C++
davafons/Chip8-Emu
/src/cpu/cpu.h
UTF-8
518
2.703125
3
[]
no_license
#pragma once #include <memory> #include "timer.h" class Memory; class Cpu { public: explicit Cpu(Memory &memory); ~Cpu(); Cpu(const Cpu &rhs); Cpu &operator=(Cpu rhs); friend void swap(Cpu &first, Cpu& second) noexcept; void cycle(); void reset(); bool mustDraw() const; bool mustSound() const; bool isPaused() const; void togglePause(); void doubleSpeed(); void halfSpeed(); private: bool paused_{false}; class ImplChip8; std::unique_ptr<ImplChip8> impl_; Timer timer_; };
true
8b0bfbd72edb703471ca8f7f0742101e685e37a6
C++
vrcordoba/Klondike
/src/controllers/CardTableController.cpp
UTF-8
1,389
2.546875
3
[]
no_license
#include "CardTableController.hpp" #include "Pile.hpp" #include "Deck.hpp" #include "CardTable.hpp" #include "Score.hpp" namespace Controllers { CardTableController::CardTableController(Models::Game& game) : Controller(game) { } CardTableController::~CardTableController() { } std::vector<FacadeCard> CardTableController::getDeck() { return getFacadePile(Controller::getDeck()); } std::vector<FacadeCard> CardTableController::getWaste() { return getFacadePile(Controller::getWaste()); } std::vector<FacadeCard> CardTableController::getTableau(std::uint8_t i) { return getFacadePile(Controller::getTableau(i)); } std::vector<FacadeCard> CardTableController::getFoundation(std::uint8_t i) { return getFacadePile(Controller::getFoundation(i)); } std::vector<FacadeCard> CardTableController::getFacadePile(const Models::Pile* pile) { std::vector<FacadeCard> facadePile; for (auto card : pile->getCards()) { FacadeCard facadeCard(card); facadePile.push_back(facadeCard); } return facadePile; } std::uint8_t CardTableController::getNumTableaus() const { return Controller::getNumTableaus(); } std::uint8_t CardTableController::getNumFoundations() const { return Controller::getNumFoundations(); } std::uint32_t CardTableController::getScore() { const Models::Score& score = Controller::getScore(); return score.getScore(); } }
true
3368abecb1393f0abb1f47eea4185cd6584e0265
C++
teamLESLEY/tobor-firmware
/include/tape.hpp
UTF-8
742
2.8125
3
[]
no_license
#ifndef TAPE_HPP #define TAPE_HPP #include <Arduino.h> class TapeSensor { const PinName LEFT_SENSOR; const PinName RIGHT_SENSOR; unsigned int onThreshold; // Common setup between constructors void setup(unsigned int threshold); public: TapeSensor(PinName leftPin, PinName rightPin, unsigned int threshold); TapeSensor(uint32_t leftPin, uint32_t rightPin, unsigned int threshold); TapeSensor(PinName leftPin, uint32_t rightPin, unsigned int threshold); TapeSensor(uint32_t leftPin, PinName rightPin, unsigned int threshold); unsigned int getLeftReading(); bool isLeftOn(); unsigned int getRightReading(); bool isRightOn(); unsigned int getThreshold(); void setThreshold(unsigned int threshold); }; #endif
true
26a475044e29bff2ca613da1ed60b952cfc07568
C++
yiZhuaMi/cPlusPlus
/LeetCode/Queue_Stack/#503/src/main.cpp
UTF-8
2,256
3.8125
4
[]
no_license
// #503 下一个更大元素 II // 给定一个循环数组(最后一个元素的下一个元素是数组的第一个元素),输出每个元素的下一个更大元素。数字 x 的下一个更大的元素是按数组遍历顺序,这个数字之后的第一个比它更大的数,这意味着你应该循环地搜索它的下一个更大的数。如果不存在,则输出 -1。 // 示例 1: // 输入: [1,2,1] // 输出: [2,-1,2] // 解释: 第一个 1 的下一个更大的数是 2; // 数字 2 找不到下一个更大的数; // 第二个 1 的下一个最大的数需要循环搜索,结果也是 2。 // 注意: 输入数组的长度不会超过 10000。 #include <iostream> #include <vector> #include <stack> using namespace std; class Solution { public: // 单调栈 vector<int> nextGreaterElements(vector<int>& nums) { int len = nums.size(); vector<int> res(len); // 栈底到栈顶非严格递增 的元素的下标 stack<int> s; // 2倍下标 相当于复制了nums 在后面 for (int i = 2 * len -1; i >= 0; i--) { // 弹出所有比这个数小/相等的,依附于大于它的(在它后面,因为反向遍历) // s非空 且 新元素大于栈顶 while (!s.empty() && nums[i % len] >= s.top()) s.pop(); // nums[i % len]对应的下一个最大值就是大于它的这个栈顶元素 res[i % len] = s.empty() ? -1 : s.top(); // 自己成为栈顶 s.push(nums[i % len]); } return res; } // 与每日温度做法相同 vector<int> nextGreaterElements(vector<int>& nums) { int len = nums.size(); // 存下标 stack<int> st; vector<int> res(len,-1); for (int i = 0; i < 2 * len; i++) { // 递减的单调栈,大于栈顶,弹出栈顶,更新栈顶对应值 while (!st.empty() && nums[i % len] > nums[st.top()]) { res[st.top()] = nums[i % len]; st.pop(); } st.push(i % len); } return res; } }; int main() { // printf("%d\n",s.divide(INT32_MIN,-1)); }
true
42230fdf708ca45bb86b81c6284709bef49c0697
C++
mrityunjayshukla411/RM-CodingTaskPhase
/Tinkercad/ArduinoCodes/PushButtonApplication/PushButtonApplication.ino
UTF-8
950
2.9375
3
[]
no_license
int buttonPin1 = 12; int buttonPin2 = 11; int ledPin = 3; int buzzPin = 2; int buttonVal1; int buttonVal2; int dt = 500; int ledBright = 0; void setup(){ pinMode(buttonPin1,INPUT); pinMode(buttonPin2,INPUT); pinMode(ledPin,OUTPUT); pinMode(buzzPin,OUTPUT); Serial.begin(9600); } void loop(){ buttonVal1 = digitalRead(buttonPin1); buttonVal2 = digitalRead(buttonPin2); Serial.print("Button 1:- "); Serial.print(buttonVal1); Serial.print(","); Serial.print("Button 2:- "); Serial.println(buttonVal2); delay(250); if(buttonVal1 == 0){ ledBright = ledBright + 5; } if(buttonVal2 == 0){ ledBright = ledBright - 5; } if (ledBright > 255) { ledBright = 255; digitalWrite(buzzPin,HIGH); delay(dt); digitalWrite(buzzPin,LOW); } if (ledBright < 0) { ledBright = 0; } Serial.print("Brightness of LED = "); Serial.println(ledBright); delay(dt); analogWrite(ledPin,ledBright); }
true
8e7963b4fda22f605eb2bb4c913ccd56747f18d5
C++
tc-imba/VE482-p2
/archive/src/query.h
UTF-8
854
2.546875
3
[]
no_license
#ifndef SRC_QUERY_H #define SRC_QUERY_H #include <string> #include <memory> #include "uexception.h" #include "db_table.h" #include "query_results.h" class Query { public: typedef std::unique_ptr<Query> Ptr; virtual QueryResult::Ptr execute() = 0; virtual std::string toString() = 0; virtual ~Query() = default; }; struct QueryCondition { std::string field; std::string op; std::string value; }; class NopQuery : public Query { public: QueryResult::Ptr execute() override { return std::make_unique<NullQueryResult>(); } std::string toString() override { return "QUERY = NOOP"; } }; class ConditionedQuery : public Query { protected: bool evalCondition(const std::vector<QueryCondition>& conditions, const Table::Object& object); }; #endif //SRC_QUERY_H
true
74285475ba395b22f6af1c57e22b4ac202b391fc
C++
JameMoriarty/Hello-World
/程序/沈阳/main.cpp
WINDOWS-1252
1,612
2.796875
3
[]
no_license
//#include <iostream> //#include <cstring> //#include <cstdio> //#include <algorithm> //using namespace std; // //int main() //{ // int T; // cin>>T; // while(T--) // { // int k,i=0; // cin>>k; // char str[100006]; // scanf("%c",&str[0]); // while(str[i]!='\n') // { // i++; // scanf("%c",&str[i]); // } // // } // return 0; //} #include <iostream> #include <cstring> #include <cstdio> #include <algorithm> using namespace std; int main() { int T; cin>>T; while(T--) { long long poi; long long sum,j=0; scanf("%lld%lld",&sum,&poi); long long num[100060],oth[100060]; for(int i=0;i<sum;i++) { scanf("%d",&num[i]); } for(int i= 0;i<sum;i++) { if(num[i]!=poi) { oth[j]=num[i]; j++; } } long long k=j; j=0; int h=0; while(h!=k-1) { if(oth[h]>oth[h+1])/// { j=1; break; } h++; } h=0; int l=0; if(j==1) { while(h!=k-1) { if(oth[h]<oth[h+1]) { l=1; break; } h++; } } if((j==1&&l==1)||k==0||k==1) printf("A is a magic array.\n"); else printf("A is not a magic array.\n"); } return 0; }
true
9813e6d2f75b41b9006ad714c32c46428b68c0bf
C++
Xuzon/PortFolio
/C++/Graphics Programming/mv_ig0/point_light_per_pixel/src/terrain.cpp
UTF-8
7,291
3.25
3
[]
no_license
#include <fstream> #include <cmath> #include <iostream> #include "terrain.h" #include "example.h" Terrain::Terrain() { m_vertexBuffer = m_indexBuffer = m_colorBuffer = 0; } void Terrain::generateVertices(const vector<float> heights, int width) { //Generate the vertices int i = 0; for (float z = float(-width / 2); z <= (width/2); ++z) { for (float x = float(-width / 2); x <= (width/2); ++x) { m_vertices.push_back(Vertex(x, heights[i++], z)); } } glGenBuffers(1, &m_vertexBuffer); //Generate a buffer for the vertices glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer); //Bind the vertex buffer glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * m_vertices.size() * 3, &m_vertices[0], GL_STATIC_DRAW); //Send the data to OpenGL } void Terrain::generateIndices(int width) { /* We loop through building the triangles that make up each grid square in the heightmap (z*w+x) *----* (z*w+x+1) | /| | / | | / | ((z+1)*w+x)*----* ((z+1)*w+x+1) */ //Generate the triangle indices for (int z = 0; z < width - 1; ++z) //Go through the rows - 1 { for (int x = 0; x < width - 1; ++x) //And the columns - 1 { m_indices.push_back((z * width) + x); //Current point m_indices.push_back(((z + 1) * width) + x); //Next row m_indices.push_back((z * width) + x + 1); //Same row, but next column m_indices.push_back(((z + 1) * width) + x); //Next row m_indices.push_back(((z + 1) * width) + x + 1); //Next row, next column m_indices.push_back((z * width) + x + 1); //Same row, but next column } } glGenBuffers(1, &m_indexBuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_indexBuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint) * m_indices.size(), &m_indices[0], GL_STATIC_DRAW); } Vertex* crossProduct(Vertex* out, Vertex* v1, Vertex* v2) { Vertex v; v.x = (v1->y * v2->z) - (v1->z * v2->y); v.y = (v1->z * v2->x) - (v1->x * v2->z); v.z = (v1->x * v2->y) - (v1->y * v2->x); out->x = v.x; out->y = v.y; out->z = v.z; return out; } Vertex* normalize(Vertex* in) { float l = sqrtf(in->x * in->x + in->y * in->y + in->z * in->z); in->x = in->x / l; in->y = in->y / l; in->z = in->z / l; return in; } void Terrain::generateNormals() { vector<Vertex> faceNormals; //Temporary array to store the face normals vector<int> shareCount; m_normals.resize(m_vertices.size()); //We want a normal for each vertex shareCount.resize(m_vertices.size()); for (unsigned int i = 0; i < shareCount.size(); ++i) { shareCount[i] = 0; } unsigned int numTriangles = m_indices.size() / 3; faceNormals.resize(numTriangles); //One normal per triangle for (unsigned int i = 0; i < numTriangles; ++i) { Vertex* v1 = &m_vertices[m_indices[i*3]]; Vertex* v2 = &m_vertices[m_indices[(i*3)+1]]; Vertex* v3 = &m_vertices[m_indices[(i*3)+2]]; Vertex vec1, vec2; vec1.x = v2->x - v1->x; vec1.y = v2->y - v1->y; vec1.z = v2->z - v1->z; vec2.x = v3->x - v1->x; vec2.y = v3->y - v1->y; vec2.z = v3->z - v1->z; Vertex* normal = &faceNormals[i]; crossProduct(normal, &vec1, &vec2); //Calculate the normal normalize(normal); for (int j = 0; j < 3; ++j) { int index = m_indices[(i*3)+j]; m_normals[index].x += normal->x; m_normals[index].y += normal->y; m_normals[index].z += normal->z; shareCount[index]++; } } for (unsigned int i = 0; i < m_vertices.size(); ++i) { m_normals[i].x = m_normals[i].x / shareCount[i]; m_normals[i].y = m_normals[i].y / shareCount[i]; m_normals[i].z = m_normals[i].z / shareCount[i]; normalize(&m_normals[i]); } glGenBuffers(1, &m_normalBuffer); glBindBuffer(GL_ARRAY_BUFFER, m_normalBuffer); //Bind the vertex buffer glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * m_normals.size() * 3, &m_normals[0], GL_STATIC_DRAW); //Send the data to OpenGL } void Terrain::generateTexCoords(int width) { for (int z = 0; z < width; ++z) { for (int x = 0; x < width; ++x) { float s = (float(x) / float(width)) * 8.0f; float t = (float(z) / float(width)) * 8.0f; m_texCoords.push_back(TexCoord(s, t)); } } glGenBuffers(1, &m_texCoordBuffer); glBindBuffer(GL_ARRAY_BUFFER, m_texCoordBuffer); //Bind the vertex buffer glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * m_texCoords.size() * 2, &m_texCoords[0], GL_STATIC_DRAW); //Send the data to OpenGL } bool Terrain::loadHeightmap(const string& rawFile, int width) { const float HEIGHT_SCALE = 10.0f; std::ifstream fileIn(rawFile.c_str(), std::ios::binary); if (!fileIn.good()) { std::cout << "File does not exist" << std::endl; return false; } //This line reads in the whole file into a string string stringBuffer(std::istreambuf_iterator<char>(fileIn), (std::istreambuf_iterator<char>())); fileIn.close(); if (stringBuffer.size() != (width * width)) { std::cout << "Image size does not match passed width" << std::endl; return false; } vector<float> heights; heights.reserve(width * width); //Reserve some space (faster) //Go through the string converting each character to a float and scale it for (int i = 0; i < (width * width); ++i) { //Convert to floating value, the unsigned char cast is importantant otherwise the values wrap at 128 float value = (float)(unsigned char)stringBuffer[i] / 256.0f; heights.push_back(value * HEIGHT_SCALE); m_colors.push_back(Color(value, value, value)); } glGenBuffers(1, &m_colorBuffer); //Generate a buffer for the colors glBindBuffer(GL_ARRAY_BUFFER, m_colorBuffer); //Bind the color buffer glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * m_colors.size() * 3, &m_colors[0], GL_STATIC_DRAW); //Send the data to OpenGL generateVertices(heights, width); generateIndices(width); generateTexCoords(width); generateNormals(); return true; } void Terrain::render() { //Bind the vertex array and set the vertex pointer to point at it glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer); //glVertexPointer(3, GL_FLOAT, 0, 0); glVertexAttribPointer((GLint)0, 3, GL_FLOAT, GL_FALSE, 0, 0); //Bind the color array // glBindBuffer(GL_ARRAY_BUFFER, m_colorBuffer); //glColorPointer(3, GL_FLOAT, 0, 0); // glVertexAttribPointer((GLint)1, 3, GL_FLOAT, GL_FALSE, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, m_texCoordBuffer); glVertexAttribPointer((GLint)1, 2, GL_FLOAT, GL_FALSE, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, m_normalBuffer); glVertexAttribPointer((GLint)2, 3, GL_FLOAT, GL_FALSE, 0, 0); //Bind the index array glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_indexBuffer); //Draw the triangles glDrawElements(GL_TRIANGLES, m_indices.size(), GL_UNSIGNED_INT, 0); }
true
75637d365a050db3c8b1773cc0057dd06f89a2a2
C++
ronitbiswas97/KongEngine
/Engine/CWindow.cpp
UTF-8
2,119
2.75
3
[]
no_license
#include <glad\glad.h> #include "CWindow.h" CWindow* CWindow::currentWindow{ nullptr }; CWindow::CWindow(int width, int height, const char * name) : frameBufferSize( static_cast<float>(width), static_cast<float>(height) ), m_name{ name } { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); m_window = glfwCreateWindow(static_cast<int>(frameBufferSize.x), static_cast<int>(frameBufferSize.y), m_name, nullptr, nullptr); glfwMakeContextCurrent(m_window); glfwSetFramebufferSizeCallback(m_window, FrameBufferSizeCallBack); glfwSetCursorPosCallback(m_window, CursorPosCallBack); currentWindow = this; } CWindow::~CWindow() { glfwDestroyWindow(m_window); glfwTerminate(); } SVector2 CWindow::GetFrameBuffer() const { return frameBufferSize; } GLFWwindow* CWindow::GetWindow() const { return m_window; } void CWindow::CursorPosition(double xPos, double yPos) { CInput::mousePosition.x = static_cast<float>(xPos); CInput::mousePosition.y = static_cast<float>(yPos); CInput::mousePosition.z = 0.0f; } void CWindow::FrameBufferSize(int width, int height) { frameBufferSize.x = static_cast<float>(width); frameBufferSize.y = static_cast<float>(height); } bool CWindow::Close() { return glfwWindowShouldClose(GetWindow()); } void CWindow::EnableTests() { glEnable(GL_DEPTH_TEST); } void CWindow::ClearBuffers() { glViewport(0, 0, static_cast<int>(CWindow::currentWindow->GetFrameBuffer().x), static_cast<int>(CWindow::currentWindow->GetFrameBuffer().y)); glClearColor(m_color.x, m_color.y, m_color.z, m_color.w); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } void CWindow::SetColor(const SVector4& color) { m_color = color; } void CWindow::FrameBufferSizeCallBack(GLFWwindow* window, int width, int height) { currentWindow->FrameBufferSize(width, height); } void CWindow::CursorPosCallBack(GLFWwindow* window, double xPos, double yPos) { currentWindow->CursorPosition(xPos, yPos); }
true
746f63c900eba5dc80a3e5440141dec52b6e8f47
C++
bhupkas/Backup
/Intern _Samsung/intern/codes/mergesort.cpp
UTF-8
768
2.78125
3
[]
no_license
/* bhupkas */ #include "iostream" #include "stdio.h" #include "vector" #include "algorithm" using namespace std; #define MAX 100000 #define FOR(i,a,b) for(i=a;i<b;i++) int B[MAX+5]; void merge(int A[],int l,int m,int r) { int k,i,j; i=l; j=m+1; k=l; while(i<=m && j<=r) { if(A[i]<A[j]) B[k++]=A[i++]; else B[k++]=A[j++]; } while(i<=m) B[k++]=A[i++]; while(j<=r) B[k++]=A[j++]; FOR(i,l,r+1) A[i]=B[i]; } void merge_sort(int A[],int l,int r) { if(l<r) { int mid=(l+r)/2; merge_sort(A,l,mid); merge_sort(A,mid+1,r); merge(A,l,mid,r); } } int main() { int n,i,j,te; cin>>n; int A[MAX+5]; FOR(i,0,n) cin>>A[i]; merge_sort(A,0,n-1); FOR(i,0,n) cout<<A[i]<<" "; cout<<endl; return 0; }
true
ef47b6d1393230a268856eb7053286f25cc4b6c7
C++
kcsoft/ArduZombieOS
/taskStatus.cpp
UTF-8
893
2.703125
3
[]
no_license
#include <Arduino.h> #include "taskStatus.h" QueueHandle_t statusQueue; void setStatusFromISR(boardStatus status) { boardStatus stat = status; xQueueSendFromISR(statusQueue, &status, 0); } void setStatus(boardStatus status) { boardStatus stat = status; xQueueSend(statusQueue, &status, 0); } void TaskStatus(void *pvParameters) { (void) pvParameters; enum boardStatus stat, status; uint8_t i; statusQueue = xQueueCreate(5, sizeof(int8_t)); pinMode(LED_BUILTIN, OUTPUT); while (true) { if (xQueueReceive(statusQueue, &stat, portTICK_PERIOD_MS) == pdPASS) { status = stat; } i = 0; while (++i <= status) { digitalWrite(LED_BUILTIN, HIGH); vTaskDelay( 60 / portTICK_PERIOD_MS ); digitalWrite(LED_BUILTIN, LOW); vTaskDelay( 200 / portTICK_PERIOD_MS ); } vTaskDelay( 500 / portTICK_PERIOD_MS ); } }
true
406ca77f14544691ee316f37e63820682d032c10
C++
CharlesThompson4748/CS-423-Project-3
/CS_423_Thompson_Charles_Project_3_Server/CS_423_Thompson_Charles_Project_3_Server/Cipher.h
UTF-8
6,745
2.734375
3
[]
no_license
/**************************************************** * File Name: cipher_sp14.h * Author: Bob Cotter * Date: 2/20/2014 * * This file provides the data arrays that provide * character substitution information needed to support * the substitution cipher used in the CS423 enhanced * IM project. * * EDIT: This file also contains functions that we written * to be used for the windows UDP client side IM service. * These functions include encrypt() which will take a * string and create and encrypted string that will be * returned. The decrypt() function which takes a string * and decrpypts it using the decr character array. The * createMessage() function which will take information * about the user, the im recipient, the message, the type * of message and the user list containing the username * and socket and address information it will then create * and message according to the type of message to be sent * to the server. * ****************************************************/ #include <iostream> #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <cstring> #include <ctime> #include <map> #include <vector> #include <fstream> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <unistd.h> using namespace std; //Encryption character array char encr[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 'b', '.', 0, 'c', '[', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'R', 'u', ',', 'q', '\t', 'Y', '\n', '\'', 'n', 's', 'v', 'e', 'H', 'o', 'N', 'M', 'r', '=', '0', ';', 'z', '/', '`', 'E', '\"', 'k', '&', '5', '>', 'i', 'p', ')', '$', '!', '2', 'O', '(', 'I', 'J', '%', 'Z', 'g', '\\', '{', 'h', '7', 'S', 'P', 'a', ' ', 'W', 'x', 'y', 'T', '+', '8', '-', 'L', '9', 'f', '#', 'F', '\r', 'B', '3', 'D', ']', 'V', '?', '*', 'G', '6', 'w', '@', '}', '|', 'C', 'l', '_', 'j', 'K', '^', '1', 't', 'Q', '<', 'U', 'd', 'm', ':', 'A', 'X', '\f', '4', '~', 0, 0, 0 }; //Decryption character array char decr[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, '$', '&', 0, '|', '^', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'Q', 'A', '8', '\\', '@', 'G', ':', '\'', 'D', '?', 'e', 'V', '\"', 'X', '\n', '5', '2', 'r', 'B', '`', '}', ';', 'g', 'M', 'W', 'Z', 'y', '3', 'u', '1', '<', 'd', 'i', 'z', '_', 'l', 'a', '7', ']', 'f', ',', 'E', 'F', 'p', 'Y', '/', '.', 'C', 'O', 't', ' ', 'N', 'U', 'v', 'c', 'R', '{', '%', 'H', '\r', 'J', 'b', 'q', 'n', '6', 'P', '\t', '\f', 'w', '+', '[', 'I', 'L', '=', 'o', '9', 'm', 'x', '(', '-', '>', '#', '0', ')', 's', '!', '*', 'h', 'S', 'T', '4', 'K', 'k', 'j', '~', 0, 0, 0 }; /* * This function takes a string a computes the * equivalent encryption from the encr character * array. * Input: String that will be encrypted * Output: String that has been encrypted */ string encrypt(string message) { string encryptedMsg; try { for (int i = 0; i < message.size(); i++) { encryptedMsg += encr[(int)message[i]]; } } catch (exception &e) { cout << "Exception thrown: " << e.what() << endl; exit(0); } return encryptedMsg; } /* * This function takes a string that has been * encrypted and decrypts the string using the * decr character array. * Input: String that will be decrypted * Output: String that has been decrypted */ string decrypt(string message, int length) { string decryptedMsg; try { for (int i = length; i < message.size(); i++) { decryptedMsg += decr[(int)message[i]]; } } catch (exception &e) { cout << "Exception thrown: " << e.what() << endl; exit(0); } return decryptedMsg; } /* * Function parses client signon message * Input: Client String message * Output: Vector with client information */ vector<string> parseMessage(string message) { vector<string> msgInfo(3); string delimiters = ";#"; size_t pos = 0; string token; int item = 0; while ((pos = message.find_first_of(delimiters)) != string::npos) { token = message.substr(0, pos); msgInfo[item] = token; message.erase(0, pos + delimiters.length()-1); item++; } cout << "Remaining Message " << message << endl; return msgInfo; } /* * This function takes the usernames and message as well as the message number * and message type and formats them for the client to recieve * Input: Strings for the usernames and message, integers for the message * number and message type * Output: String formatted for the client to recieve */ string createMessage(string userName, string message, string user_port, int messageType, map<string, pair<string, string> > users) { string msg = " "; //Signon Message if (messageType == 1) { if (users.size() > 1) { msg = "4;"; msg += users.size(); cout << "Message with count " << msg << endl; msg += "\n"; for(map<string, pair<string, string> >::const_iterator it = users.begin(); it != users.end(); it++) { msg += encrypt(it -> first); msg += ";"; msg += it -> second.first; msg += ";"; msg += it -> second.second; msg += "\n"; } msg += "#"; } else { msg = "4;0#"; } cout << "Message to send " << msg << endl; cout << "users size: " << users.size() << endl; } //Signoff Message else if (messageType == 2) { msg = "4;-1\n"; msg += encrypt(userName); msg += ";"; msg += message; msg += "#"; cout << "Message to send " << msg << endl; } //Signon Alert else if(messageType == 3) { msg = "4;new\n"; //this will need to be updated to take send to all users msg += encrypt(userName); msg += ";"; msg += message; msg += ";"; msg += user_port; msg += "#"; cout << "Message to send " << msg << endl; } //Status check else if (messageType == 4) { msg = "3;StatusCheck#"; cout << "Message to send " << msg << endl; } //Error Alert else if(messageType == 5) { msg = "Error;"; msg += encrypt(message); msg += "#"; cout << "Message to send " << msg << endl; } //Error else { cout << "Error: Message type dosn't exist" << endl; } return msg; } /* * This function searches through a map of users for a specific username * and returns true if the username is found. * Input: Map of users and string username * Output: boolean */ bool findUser(string userName, map <string, pair<int, struct sockaddr_storage> > users) { map<string, pair<int, struct sockaddr_storage> >::iterator itr; itr = users.find(userName); if(itr != users.end()) { return true; } return false; } /* * This function determines what AF_INET is being used for the input * sockaddr and return a value for the address. * Input: struct sockaddr * Output: void */ void *get_in_addr(struct sockaddr *sa) { if (sa->sa_family == AF_INET) { return &(((struct sockaddr_in*)sa)->sin_addr); } return &(((struct sockaddr_in6*)sa)->sin6_addr); }
true
4dd4a986f3b7bf395016a91cabac91b82bbc454a
C++
PhilippeCollin/s7app1
/serveur/CTlsServeur.h
UTF-8
920
2.890625
3
[]
no_license
#if !defined CTLSSERVEUR_H #define CTLSSERVEUR_H #include <iostream> #include "CServeur.h" #include "openssl/ssl.h" /** Coquille pour un serveur TLS. */ class CTlsServeur : protected CServeur { public: /** Constructeur par d�faut. */ CTlsServeur(); /** Destructeur. */ virtual ~CTlsServeur(); /** D�marre le serveur. @param addrServeur l'adresse � laquelle se connecter @param portServeur le port auquel se connecter */ int attendre(string addrServeur, unsigned int portServeur); void recevoir(); /** Arr�t du client, initiant la fermeture de la connexion. */ void arreter(); protected: /** Le contexte TLS du serveur. */ SSL_CTX* m_context; /** La connexion TLS associ�e au socket 'accept�'. */ SSL* m_connexion; }; #endif // CTLSSERVEUR_H
true
586e03024304bf57e730d016bfcb5d71522515b1
C++
saJonMR/programmiersprachen-aufgabe-1-2019
/source/Aufgabe_1.9.cpp
UTF-8
368
2.609375
3
[ "MIT" ]
permissive
#define CATCH_CONFIG_RUNNER #include <catch.hpp> #include <cmath> int checksum(int a) { int sum = 0; while (a != 0) { sum = sum + a % 10; a = a / 10; } return sum; } TEST_CASE("describe_checksum", "[checksum]") { REQUIRE(checksum (119989) == 37); } int main(int argc, char* argv[]) { return Catch::Session().run(argc, argv); }
true
61bf3e37aa5b9a6a191ead38da4f5ce656d7cb7f
C++
Ratstail91/roguish
/src/io.cpp
UTF-8
1,102
2.578125
3
[]
no_license
#include "io.hpp" //platform check #define WINDOWS _WIN32 _WIN64 #ifdef WINDOWS #include <termios.h> #include <unistd.h> #include <stdio.h> //reads from keypress, doesn't echo int getch(void) { struct termios oldattr, newattr; int ch; tcgetattr( STDIN_FILENO, &oldattr ); newattr = oldattr; newattr.c_lflag &= ~( ICANON | ECHO ); tcsetattr( STDIN_FILENO, TCSANOW, &newattr ); ch = getchar(); tcsetattr( STDIN_FILENO, TCSANOW, &oldattr ); return ch; } //reads from keypress, echoes int getche(void) { struct termios oldattr, newattr; int ch; tcgetattr( STDIN_FILENO, &oldattr ); newattr = oldattr; newattr.c_lflag &= ~( ICANON ); tcsetattr( STDIN_FILENO, TCSANOW, &newattr ); ch = getchar(); tcsetattr( STDIN_FILENO, TCSANOW, &oldattr ); return ch; } //class implementation void IO::Init() { // } void IO::Quit() { // } char IO::Input() { return getch(); } void IO::Clear() { printf("\x1b[2J"); } void IO::Print(const char c) { printf("%c", c); } void IO::Print(const char* s) { printf("%s", s); } #endif //WINDOWS
true
bbd903d6a5c4b9a26857c8e75ea1583505230e23
C++
myumoon/customtower
/customtower/nklib/include/resource/renderableTexture.h
SHIFT_JIS
4,207
2.75
3
[ "MIT" ]
permissive
/*------------------------------------------------------------------------- @F_Oobt@eNX`NX 쐬F2011/01/23 XVF2011/01/23 --------------------------------------------------------------------------*/ #ifndef __RENDERBLETEXTURE_H__ #define __RENDERBLETEXTURE_H__ #include <vector> #if defined(NK_USE_SDLGL) #include <SDL/SDL_opengl.h> #endif #include <GL/glut.h> #include <GL/glext.h> //#include <GL/glxext.h> //#include "glxext.h" //#include "wglext.h" #include "../typedef.h" #define RENDERABLE_TEXTURE RenderableTexture::GetInstance() //----------------------------------------------- // _OeNX` //----------------------------------------------- typedef struct { u32 width; //!< u32 height; //!< GLuint glTexID; //!< OpenGLeNX`ID GLuint FrameBufferID; //!< t[obt@ID GLuint RenderBufferID; //!< _[obt@ID } RenderTexInfo; typedef u32 RenderTexId; //_[eNX`ID^ /*----------------------------------*/ /* FBONX */ /*----------------------------------*/ class RenderableTexture { public: bool Init( void ); /** `”\ȃeNX`𐶐 @param outTexId : eNX`󂯎 @param width : eNX`̕ @param height : eNX`̍ */ bool CreateRenderableTexture( RenderTexId *outTexId, u32 width, u32 height ); bool CreateRenderableHalfFloatTexture( RenderTexId *outTexId, u32 width, u32 height ); /* OpenGL`̃eNX`ID擾 @param RTexId : 擾_eNX`ID @retval GL̃eNX`ID */ GLuint GetTextureID( RenderTexId RTexId ); /** `悷eNX`w @param RTexId : Zbg郌_OID */ void SetRenderTarget( RenderTexId RTexId ); /** `ΏۂGL̃obt@ɖ߂ */ void RestoreRenderTarget( void ); /** 2DeNX`ɕ`iVF[_[ƕĎg) */ void Render2D( RenderTexId RTexId ); /** GLtexԂ̃eNX`edestFBOTexԂɃRs[ */ void CopyGL2FBOTexture( RenderTexId destRTexId, GLuint GLtex ); /** eNX`̓eXN[ɕ` @param RTexId eNX`ID */ void OverWriteFrameBuffer( RenderTexId RTexId ); /** w肵_OeNX`̓eNA @param RTexId : _OID */ void ClearTexBuffer( RenderTexId RTexId ); void ClearBuffer() { glBindFramebuffer(GL_FRAMEBUFFER_EXT, 0); } // Svfj //--------------------------------------- void Destroy(); // E폜E擾 //--------------------------------------- static void Create() { if( !m_instance ) { m_instance = new RenderableTexture(); } } static void Delete() { delete m_instance; m_instance = NULL; } static RenderableTexture *GetInstance() { return m_instance; } private: RenderableTexture() { Init(); } static RenderableTexture* m_instance ; //!< VOg bool m_ready; //!< gp”\Ȃtrue std::vector<RenderTexInfo> Info; //!< eNX` PFNGLGENFRAMEBUFFERSEXTPROC glGenFramebuffers; PFNGLBINDFRAMEBUFFEREXTPROC glBindFramebuffer; PFNGLFRAMEBUFFERTEXTURE2DEXTPROC glFramebufferTexture2D; PFNGLGENRENDERBUFFERSEXTPROC glGenRenderbuffers; PFNGLBINDRENDERBUFFEREXTPROC glBindRenderbuffer; PFNGLRENDERBUFFERSTORAGEEXTPROC glRenderbufferStorage; PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC glFramebufferRenderbuffer; PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC glCheckFramebufferStatus; PFNGLGENERATEMIPMAPEXTPROC glGenerateMipmapExt; bool _CheckStatus(); }; //void CopyTexture( u32 destTex, GLuint texID ); //void OverWriteFrameBuffer( GLuint srctex ); //ʏuhŃt[obt@SʂɎweNX`` //void overWriteFrameBufferH( GLuint srctex ); //ZuhŃt[obt@SʂɎweNX`` #endif // __RENDERBLETEXTURE_H__
true
2acbaa96a910d63c2ad79d0101e0e5f9069101b0
C++
roomyroomy/algorithm
/algospot/TPATH.cpp
UTF-8
1,733
3.203125
3
[]
no_license
#include <iostream> #include <algorithm> #include <vector> using namespace std; class DisjointSet { private: vector<int> parent, rank; public: DisjointSet(int n): parent(n), rank(n, 1) { for (int idx = 0; idx < n; idx++) { parent[idx] = idx; } } int find(int n) { if (n == parent[n]) { return n; } else { parent[n] = find(parent[n]); return parent[n]; } } void merge(int u, int v) { u = find(u); v = find(v); if (u == v) return; if (rank[u] < rank[v]) parent[u] = v; else parent[v] = u; if (rank[u] == rank[v]) rank[v]++; } }; int solve(vector<pair<int, pair<int, int>>> &edges, int n) { int result = 0; sort(edges.begin(), edges.end()); result = edges[edges.size() - 1].first - edges[0].first; for(int start = 0; start < edges.size(); start++) { DisjointSet ds(n); for(int end = start; end < edges.size(); end++) { ds.merge(edges[end].second.first, edges[end].second.second); if(edges[end].first - edges[start].first > result) break; if(ds.find(0) == ds.find(n - 1)) { result = edges[end].first - edges[start].first; break; } } } return result; } int main() { std::ios::sync_with_stdio(false); int tc, n, m; cin >> tc; for(int idxCase = 0; idxCase < tc; idxCase++) { vector<pair<int, pair<int, int>>> edges; cin >> n >> m; for(int edge = 0; edge < m; edge++) { int a, b, c; cin >> a >> b >> c; edges.push_back(make_pair(c, make_pair(a, b))); } cout << solve(edges, n) << endl; } return 0; }
true
0e9fb83d4227d4667a8be763c4f3bf2d1038f346
C++
KL-Lru/Competitive-Programming
/AtCoder/abc029/c.cpp
UTF-8
651
2.578125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; #define nmax 9 int main(){ int n; cin>>n; int count=pow(3,n); int s[nmax]; for(int i=0;i<nmax;i++) s[i]=0; for(int i=0;i<count;i++){ for(int j=n-1;j>=0;j--){ switch(s[j]){ case 0:cout<<"a"<<flush;break; case 1:cout<<"b"<<flush;break; case 2:cout<<"c"<<flush;break; } } cout<<endl; s[0]++; for(int j=0;j<n;j++){ if(s[j]>2){ s[j+1]++; s[j]=0; } } } return 0; }
true
10cb8ef1e2fbfc19af91d628d6dd4d79109781cf
C++
Ra1nWarden/Online-Judges
/UVa/247.cpp
UTF-8
1,685
2.71875
3
[]
no_license
#include <cstdio> #include <map> #include <string> #include <cstring> #include <queue> #include <vector> #define MAXL 30 #define MAXN 30 using namespace std; int n, m, ni; map<string, int> names; map<int, string> rev; char a[MAXL], b[MAXL]; bool d[MAXN][MAXN]; bool visited[MAXN]; int main() { int kase = 1; while(scanf("%d %d\n", &n, &m) != EOF && (n || m)) { if(kase > 1) printf("\n"); for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { d[i][j] = i == j; } } names.clear(); rev.clear(); ni = 0; for(int i = 0; i < m; i++) { scanf("%s %s\n", a, b); string astr(a); string bstr(b); if(names.count(astr) == 0) { names[astr] = ni; rev[ni] = astr; ni++; } if(names.count(bstr) == 0) { names[bstr] = ni; rev[ni] = bstr; ni++; } d[names[astr]][names[bstr]] = true; } for(int k = 0; k < n; k++) { for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { d[i][j] = d[i][j] || (d[i][k] && d[k][j]); } } } memset(visited, false, sizeof visited); printf("Calling circles for data set %d:\n", kase++); for(int i = 0; i < n; i++) { if(!visited[i]) { vector<int> prints; prints.push_back(i); queue<int> q; q.push(i); visited[i] = true; while(!q.empty()) { int next = q.front(); q.pop(); for(int j = 0; j < n; j++) { if(!visited[j] && d[next][j] && d[j][next]) { visited[j] = true; prints.push_back(j); q.push(j); } } } for(int j = 0; j < prints.size(); j++) { if(j > 0) printf(", "); printf("%s", rev[prints[j]].c_str()); } printf("\n"); } } } return 0; }
true
5542452ae3921b3e24e3475f90eca45593fefed6
C++
Marynarz/P_Lodz_Weeia_Informatyka
/Zaliczenie/Wino/Starewino.cpp
UTF-8
1,183
2.75
3
[]
no_license
#include "Starewino.hpp" Starewino::Starewino():Wino("brak","brak",0),nazwa("brak"),rok(0) {} Starewino::Starewino(const char* marka, const char* styl,const unsigned int butelki,const char* nazwa,unsigned int rok):Wino(marka,styl,butelki),nazwa(nazwa),rok(rok) {} Starewino::Starewino(const Starewino &W):Wino(W.getMarka(),W.getStyle(),W.IleButelek()),nazwa(W.getNazwa()),rok(W.getRok()) {} Starewino::~Starewino() {} const char* Starewino::getNazwa()const { return nazwa; } unsigned int Starewino::getRok()const { return rok; } Starewino & Starewino::operator=(const Starewino &W) { this->setMarka(W.getMarka()); this->setStyle(W.getStyle()); this->setButle(W.IleButelek()); this->rok = W.getRok(); this->nazwa = W.getNazwa(); return *this; } void Starewino::Pokaz() { cout <<"Marka:\t\t"<<this->getMarka()<<endl<<"Styl:\t\t"<<this->getStyle()<<endl<<"Butelki:\t"<<this->IleButelek()<<endl<<"Nazwa:\t\t"<<nazwa<<endl<<"Rok:\t\t"<<rok<<endl; } ostream & operator<<(ostream & s, const Starewino &W) { return s<<W.getMarka()<<","<<W.getStyle()<<","<<W.IleButelek()<<','<<W.nazwa<<','<<W.rok; }
true
0aeb902a613bdc613aa9faa01d91023fae19cb54
C++
Xydrel/UdemyDataAndAlg
/Project1/Project1/QueueLinkedList.h
UTF-8
658
2.890625
3
[]
no_license
#pragma once //Includes--------------------------------------------------------------------- #include "DoublyLinkedList.h" //Types------------------------------------------------------------------------ class QueueLinkedList { public: explicit QueueLinkedList(); void Queue(IntDoublyNode::NodePtr node); IntDoublyNode::NodePtr Dequeue(); const IntDoublyNode::NodePtr First() const; const IntDoublyNode::NodePtr Rear() const; size_t Size() const; bool IsEmpty() const; bool IsFull() const; bool IsValid() const; void PrintElementValues() const; private: std::unique_ptr<IntDoublyLinkedList> _container; };
true
fa26638dca6de8d56c7650428b6582f7e959d489
C++
lucianoscarpaci/Programming-in-Cpp
/5.17.cpp
UTF-8
1,373
4
4
[]
no_license
#include<iostream> using namespace std; /* init main init the variables i. type ii. sales iii. retail */ int main(){ float retail; int type, sales; cout<<"Enter the product type (from 1 to 5): "; cin>>type; cout<<"Enter the total number of quantity sold: "; cin>>sales; switch(type){ case 1: cout<<"Retail price for product 1 is: $2.98"<<endl; retail=sales*2.98; cout<<"Total retail price is: $"<<retail<<endl; break; case 2: cout<<"Retail price for product 2 is: $4.5"<<endl; retail=sales*4.50; cout<<"Total retail price is: $"<<retail<<endl; break; case 3: cout<<"Retail price for product 3 is: $9.98"<<endl; retail=sales*9.98; cout<<"Total retail price is: $"<<retail<<endl; break; case 4: cout<<"Retail price for product 4 is: $4.49"<<endl; retail=sales*4.49; cout<<"Total retail price is: $"<<retail<<endl; break; case 5: cout<<"Retail price for product 4 is: $6.87"<<endl; retail=sales*6.87; cout<<"Total retail price is: $"<<retail<<endl; break; default: cout<<"Invalid product"; break; } return 0; }
true
7563083df652cf39a80f29811d575073e69b5e05
C++
Lanceolata/code
/algorithms/algorithms-cplusplus/leetcode/Question_0386_Lexicographical_Numbers.cc
UTF-8
459
3.1875
3
[]
no_license
#include <vector> using namespace std; class Solution { public: vector<int> lexicalOrder(int n) { vector<int> res(n); int cur = 1; for (int i = 0; i < n; i++) { res[i] = cur; if (cur * 10 <= n) { cur *= 10; } else if (cur % 10 != 9 && cur + 1 <= n) { cur++; } else { while ((cur / 10) % 10 == 9) { cur /= 10; } cur = cur / 10 + 1; } } return res; } };
true
daacd9111537ff57e009abecf6ceddb32c8eec14
C++
FallenShard/Crisp
/Crisp/Crisp/PathTracer/Samplers/Fixed.hpp
UTF-8
637
2.640625
3
[ "MIT" ]
permissive
#pragma once #include <random> #include <array> #include "Sampler.hpp" namespace crisp { class FixedSampler : public Sampler { public: FixedSampler(const VariantMap& attribs = VariantMap()); ~FixedSampler(); virtual std::unique_ptr<Sampler> clone() const override; virtual void prepare() override; virtual void generate() override; virtual void advance() override; virtual float next1D() override; virtual glm::vec2 next2D() override; private: inline float nextFloat(); std::array<float, 3> m_values; size_t m_index; }; }
true
534e842c80a566448670689e39564d13b80ec74d
C++
Vijay1997/bsdiff
/utils.cc
UTF-8
718
2.546875
3
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
// Copyright 2018 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "bsdiff/utils.h" namespace bsdiff { int64_t ParseInt64(const uint8_t* buf) { // BSPatch uses a non-standard encoding of integers. // Highest bit of that integer is used as a sign bit, 1 = negative // and 0 = positive. // Therefore, if the highest bit is set, flip it, then do 2's complement // to get the integer in standard form int64_t result = buf[7] & 0x7F; for (int i = 6; i >= 0; i--) { result <<= 8; result |= buf[i]; } if (buf[7] & 0x80) result = -result; return result; } } // namespace bsdiff
true
0dd28f17779df5ff4805abf0853240fec146058d
C++
dementrock/acm
/berkeley_programming_contest_2012/7.cpp
UTF-8
2,547
3.28125
3
[]
no_license
#include <iostream> #include <string> #include <sstream> #include <vector> #include <algorithm> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #define MAXS 10000 using namespace std; struct info { int sum, val, step; int type; // 0: left parenthesis; 1: right parenthesis; 2: other }; info calc(string s) { info stack[MAXS]; int cntstack = 0; for (int i = 0; i < s.length(); ++i) { if (s[i] == '(') { // push to stack ++cntstack; stack[cntstack].type = 0; } else if (s[i] == ')') { // pop stack int newsum = 0, newstep = 0, newval = 0; int leftpos = cntstack; while (leftpos >= 1 && stack[leftpos].type != 0) --leftpos; for (int j = leftpos + 1; j <= cntstack; ++j) { newsum += stack[j].step * newval + stack[j].sum; newstep += stack[j].step; newval += stack[j].val; } cntstack = leftpos; // override directly on the previous left parenthesis element stack[cntstack].type = 2; stack[cntstack].step = newstep; stack[cntstack].val = newval; stack[cntstack].sum = newsum; } else if ('0' <= s[i] && s[i] <= '9') { // number: perform calculation on last element of stack int n = 0; for (i; i < s.length() && '0' <= s[i] && s[i] <= '9'; ++i) { n = n * 10 + (s[i] - '0'); } if (s[i] < '0' || s[i] > '9') { --i; } stack[cntstack].sum = n * stack[cntstack].sum + n * (n - 1) / 2 * stack[cntstack].step * stack[cntstack].val; stack[cntstack].val *= n; stack[cntstack].step *= n; } else { // calc and then push to stack ++cntstack; stack[cntstack].type = 2; stack[cntstack].step = 1; if (s[i] == '+') { stack[cntstack].val = 1; } else if (s[i] == '.') { stack[cntstack].val = 0; } else if (s[i] == '-') { stack[cntstack].val = -1; } else { // shouldn't happen.. cout << "error!" << endl; } stack[cntstack].sum = stack[cntstack].val; } } info ans; ans.sum = ans.step = ans.val = 0; for (int i = 1; i <= cntstack; ++i) { ans.sum += stack[i].step * ans.val + stack[i].sum; ans.step += stack[i].step; ans.val += stack[i].val; } return ans; } double avg(string s) { info calced = calc(s); return 1.0 * calced.sum / (calced.step + 1); } int main() { string s; cout.setf(ios::fixed,ios::floatfield); cout.precision(2); while (cin >> s) { cout << "Average value of " << s << " is " << avg(s) << endl; } return 0; }
true
662975095eda369ed86225b23de702425ebf637e
C++
StudioSimGroup2/2DEngine
/Engine/src/Backend/D3D11/D3D11Renderer2D.cpp
UTF-8
6,448
2.6875
3
[]
no_license
#include "D3D11Renderer2D.h" #include <CameraManager.h> namespace Engine { D3D11Renderer2D::D3D11Renderer2D(Shader* shader, D3D11Device* dev) { mShader = shader; mDeviceContext = dev->GetDeviceContext(); InitBuffers(dev->GetDevice()); } D3D11Renderer2D::D3D11Renderer2D(Shader* shader, D3D11Device* dev, int totalWidth, int totalHeight, vec2i position) { mShader = shader; mDeviceContext = dev->GetDeviceContext(); InitBuffers(dev->GetDevice(), totalWidth, totalHeight, position.x, position.y); } D3D11Renderer2D::~D3D11Renderer2D() { if (mVertexBuffer) { mVertexBuffer->Release(); mVertexBuffer = nullptr; } if (mIndexBuffer) { mIndexBuffer->Release(); mIndexBuffer = nullptr; } if (mConstantBuffer) { mConstantBuffer->Release(); mConstantBuffer = nullptr; } mDeviceContext = nullptr; } void D3D11Renderer2D::Draw(vec2f& position, vec2f& rotation, vec2f& scale, Texture* textureToRender) { if (textureToRender == nullptr) return; auto camera = CameraManager::Get()->GetPrimaryCamera(); XMMATRIX mScale = XMMatrixScaling(scale.x, scale.y, 1.0f); XMMATRIX mRotate = XMMatrixRotationZ(XMConvertToRadians( rotation.x)); XMMATRIX mTranslate = XMMatrixTranslation(position.x, -position.y, 0.0f); XMMATRIX world = mScale * mRotate * mTranslate; ConstantBuffer cb; cb.mProjection = XMMatrixTranspose(camera->GetProjectionMatrix()); cb.mView = XMMatrixTranspose(camera->GetViewMatrix()); cb.mWorld = XMMatrixTranspose(world); cb.mFlipX = mFlipX; cb.mFlipY = mFlipY; ColourBuffer colourB; colourB.r = mColour[0]; colourB.g = mColour[1]; colourB.b = mColour[2]; colourB.a = mColour[3]; mDeviceContext->UpdateSubresource(mConstantBuffer, 0, nullptr, &cb, 0, 0); mDeviceContext->VSSetConstantBuffers(0, 1, &mConstantBuffer); mDeviceContext->PSSetConstantBuffers(0, 1, &mConstantBuffer); mDeviceContext->UpdateSubresource(mColourBuffer, 0, nullptr, &colourB, 0, 0); mDeviceContext->VSSetConstantBuffers(1, 1, &mColourBuffer); mDeviceContext->PSSetConstantBuffers(1, 1, &mColourBuffer); UINT stride = sizeof(VertexType); UINT offset = 0; mDeviceContext->IASetVertexBuffers(0, 1, &mVertexBuffer, &stride, &offset); mDeviceContext->IASetIndexBuffer(mIndexBuffer, DXGI_FORMAT_R16_UINT, 0); mShader->Load(); textureToRender->Load(); mDeviceContext->Draw(6, 0); } void D3D11Renderer2D::UpdateBuffers(int totalWidth, int totalHeight, int posX, int posY) { InitBuffers(D3D11Device::GetInstance()->GetDevice(), totalWidth, totalHeight, posX, posY); } void D3D11Renderer2D::InitBuffers(ID3D11Device* dev, int totalWidth, int totalHeight, int posX, int posY) { auto hr = S_OK; VertexType vertices[6]; float left, right, top, bottom; // Calculate the screen coordinates of the left side of the bitmap. left = 0; // 0 = X position // Calculate the screen coordinates of the right side of the bitmap. right = left + (float)32; // Calculate the screen coordinates of the top of the bitmap. top = 0; // 0 = Y position // Calculate the screen coordinates of the bottom of the bitmap. bottom = top - (float)32; if (totalWidth == -1) { // Bad triangle vertices[0].position = XMFLOAT3(left, top, 0.0f); // Top left. vertices[0].texture = XMFLOAT2(0.0f, 0.0f); vertices[1].position = XMFLOAT3(left, bottom, 0.0f); // Bottom left. vertices[1].texture = XMFLOAT2(0.0f, 1.0f); vertices[2].position = XMFLOAT3(right, bottom, 0.0f); // Bottom left. vertices[2].texture = XMFLOAT2(1.0f, 1.0f); // Second triangle. Good triangle vertices[3].position = XMFLOAT3(left, top, 0.0f); // Top left. vertices[3].texture = XMFLOAT2(0.0f, 0.0f); vertices[4].position = XMFLOAT3(right, top, 0.0f); // Top right. vertices[4].texture = XMFLOAT2(1.0f, 0.0f); vertices[5].position = XMFLOAT3(right, bottom, 0.0f); // Bottom right. vertices[5].texture = XMFLOAT2(1.0f, 1.0f); } else { // Bad triangle vertices[0].position = XMFLOAT3(left, top, 0.0f); // Top left. vertices[0].texture = XMFLOAT2(((1.0f / (totalWidth / 32.0f)) * posX/*x*/), ((1.0f / (totalHeight / 32.0f)) * posY/*y*/)); vertices[1].position = XMFLOAT3(left, bottom, 0.0f); // Bottom left. vertices[1].texture = XMFLOAT2(((1.0f / (totalWidth / 32.0f)) * posX/*x*/), ((1.0f / (totalHeight / 32.0f)) * posY/*y*/) + 1.0f / (totalHeight / 32.0f)); vertices[2].position = XMFLOAT3(right, bottom, 0.0f); // Bottom right. vertices[2].texture = XMFLOAT2(((1.0f / (totalWidth / 32.0f)) * posX/*x*/) + (1.0f/ (totalWidth / 32.0f)), ((1.0f / (totalHeight / 32.0f)) * posY/*y*/) + 1.0f / (totalHeight / 32.0f)); // Second triangle. Good triangle vertices[3].position = XMFLOAT3(left, top, 0.0f); // Top left. vertices[3].texture = XMFLOAT2(((1.0f / (totalWidth / 32.0f)) * posX/*x*/), ((1.0f / (totalHeight / 32.0f)) * posY/*y*/)); vertices[4].position = XMFLOAT3(right, top, 0.0f); // Top right. vertices[4].texture = XMFLOAT2(((1.0f / (totalWidth / 32.0f)) * posX/*x*/) + (1.0f / (totalWidth / 32.0f)), ((1.0f / (totalHeight / 32.0f)) * posY/*y*/)); vertices[5].position = XMFLOAT3(right, bottom, 0.0f); // Bottom right. vertices[5].texture = XMFLOAT2(((1.0f / (totalWidth / 32.0f)) * posX/*x*/) + (1.0f / (totalWidth / 32.0f)), ((1.0f / (totalHeight / 32.0f)) * posY/*y*/) + 1.0f / (totalHeight / 32.0f)); } D3D11_BUFFER_DESC bd = {}; bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof(VertexType) * 6; bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; bd.CPUAccessFlags = 0; D3D11_SUBRESOURCE_DATA InitData = {}; InitData.pSysMem = vertices; hr = dev->CreateBuffer(&bd, &InitData, &mVertexBuffer); // I dont think these are working corretly WORD indices[] = { 0, 1, 2, 3, 4, 5, }; bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof(WORD) * 6; bd.BindFlags = D3D11_BIND_INDEX_BUFFER; bd.CPUAccessFlags = 0; InitData.pSysMem = indices; hr = dev->CreateBuffer(&bd, &InitData, &mIndexBuffer); bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof(ConstantBuffer); bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; bd.CPUAccessFlags = 0; hr = dev->CreateBuffer(&bd, nullptr, &mConstantBuffer); bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof(ColourBuffer); bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; bd.CPUAccessFlags = 0; hr = dev->CreateBuffer(&bd, nullptr, &mColourBuffer); } }
true
ca8dd5d148c5b0d7c25b182f36b21444c5f3498f
C++
rverma870/DSA-practice
/gfg/must do interview que/DP/GetMinimumSquares.cpp
UTF-8
429
2.859375
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int MinSquares(int n) { int dp[n+1]; memset(dp,0,sizeof(dp)); dp[0]=1; dp[1]=1,dp[2]=2,dp[3]=3; for(int i=4;i<=n;i++) { dp[i]=INT_MAX; for(int j=1;j<=sqrt(i);j++) { if(i%(j*j)!=0) dp[i]=min(dp[i],dp[i%(j*j)]+i/(j*j)); else dp[i]=min(dp[i],i/(j*j)); } } return dp[n]; } int main() { int n; cin >> n; cout<<MinSquares(n); }
true
05963d274f4f7dd4a1f25a50e0388b1f20dc96e0
C++
ZelaiWang/WangZelai_CIS17a_42824
/Hmwk/Assignment 1/Truth Table/Truth Table.cpp
UTF-8
1,316
3.484375
3
[]
no_license
#include <iostream> #include <iomanip> using namespace std; //Function prototypes void decide(bool,bool); int main() { cout << setw(10) <<"X : T , Y : T"<<endl; decide(true,true); cout << endl; cout << setw(10) <<"X : F , Y : F"<<endl; decide(false,false); cout << endl; cout << setw(10) <<"X : T , Y : F"<<endl; decide(true,false); cout << endl; cout << setw(10) <<"X : F , Y : T"<<endl; decide(false,true); cout << endl; return 0; } void decide(bool x,bool y){ cout <<left; cout <<setw(10)<<"X" <<((x)?"T":"F") <<endl; cout <<setw(10)<<"Y" <<((y)?"T":"F") <<endl; cout <<setw(10)<<"!X" <<((!x)?"T":"F") <<endl; cout <<setw(10)<<"!Y" <<((!y)?"T":"F") <<endl; cout <<setw(10)<<"X&&Y" <<((x&&y)?"T":"F") <<endl; cout <<setw(10)<<"X||Y" <<((x||y)?"T":"F") <<endl; cout <<setw(10)<<"X^Y" <<((x^y)?"T":"F") <<endl; cout <<setw(10)<<"X^Y^Y" <<((x^y^y)?"T":"F") <<endl; cout <<setw(10)<<"X^Y^X" <<((x^y^x)?"T":"F") <<endl; cout <<setw(10)<<"!(X||Y)" <<((!(x||y))?"T":"F")<<endl; cout <<setw(10)<<"!X&&!Y" <<((!x&&!y)?"T":"F") <<endl; cout <<setw(10)<<"!(X&&Y)" <<((!(x&&y))?"T":"F")<<endl; cout <<setw(10)<<"!X||!Y" <<((!x||!y)?"T":"F") <<endl; }
true
e5d7e11ad88c25f26874b60d17eb80faade6125f
C++
Teveillan/templates
/KMP.cpp
UTF-8
524
2.78125
3
[]
no_license
int nxt[N]; void get_next(string s) { int i = 0, j = -1; // j记录已匹配的个数 nxt[0] = -1; while (i < s.size()) { if (j == -1 || s[i] == s[j]) { i++; j++; nxt[i] = j; } else j = nxt[j]; } } //get_next void kmp(string s1, string s2) { int i = 0, j = 0; while (i < (int)s1.size() && j < (int)s2.size()) { if (j == -1 || s1[i] == s2[j]) { i++; j++; } else { j = nxt[j]; } } }
true
0ace4667f8086b02187b12b6a67d11be52e2259d
C++
lantimilan/topcoder
/CODEFORCE/prob117C.cpp
UTF-8
2,726
2.9375
3
[]
no_license
// ========================================================= // // Filename: prob117C.cpp // // Description: // // Version: 1.0 // Created: 09/23/2011 09:35:37 AM // Revision: none // Compiler: g++ // // Author: LI YAN (lyan), lyan@cs.ucr.edu // Company: U of California Riverside // Copyright: Copyright (c) 09/23/2011, LI YAN // // ========================================================= // // tournament (graph theory) // - if a tournament has a cycle, it has a triangle // - a tournament always have a hamitonian path // - if a tournament is strongly connected, then it has a hamitonial cycle // - if a tournament is strongly connected, then for every vertex v // for every l=3 to n, there is a cycle of length l containing v // - if a tournament is 4-connected, every pair of vertices can be connected // with a hamitonian path (Thomassen 1980) // - if a tournament is acyclic, then the score sequence (outdeg) is // 0,1,2,...,n-1 #include <algorithm> #include <cstdio> #include <iostream> #include <stack> #include <string> #include <vector> using namespace std; vector<int> mark; vector<int> parent; vector<string> adj; vector<vector<int> > graph; int cycle=-1; void dfs(int k) { mark[k]=1; //int n=int(adj.size()); //for(int i=0; i<n; ++i) if (adj[k][i]=='1') for(int j=0; j<int(graph[k].size()); ++j) { int i=graph[k][j]; if (mark[i]==0) { // tree edge parent[i]=k; dfs(i); } else if (mark[i]==1) { // back edge, found cycle if (cycle<0) cycle=k; return; } else { // forward edge or cross edge, do nothing } } mark[k]=2; } int main() { int n; cin >> n; adj.resize(n); for(int i=0; i<n; ++i) { char buf[5005]; scanf("%s",buf); adj[i]=buf; } graph.resize(n); for(int i=0; i<n; ++i) for(int j=0; j<n; ++j) if (adj[i][j]=='1') graph[i].push_back(j); mark.resize(n); parent.resize(n); fill(parent.begin(), parent.end(), -1); for(int i=0; i<n; ++i) if (!mark[i] && cycle<0) dfs(i); if (cycle<0) { cout << -1 << endl; return 0; } vector<int> vec; int p; for(p=cycle; adj[cycle][p]!='1'; p=parent[p]) { vec.push_back(p); } vec.push_back(p); reverse(vec.begin(),vec.end()); // find triangle within cycle int ans[3]={-1}; for(int k=2; k<int(vec.size()); ++k) { if (adj[vec[k]][vec[0]]=='1') { ans[0]=vec[0]; ans[1]=vec[k-1]; ans[2]=vec[k]; break; } } cout << ans[0]+1 << ' ' << ans[1]+1 << ' ' << ans[2]+1 << endl; }
true
e0f86604d70ff5c88f06ef531dde46e04e8a33f2
C++
sipian/Concurrent-MST
/Boruvka_submission/src/boruvka.cpp
UTF-8
10,028
3
3
[]
no_license
#include "boruvka.h" /* * This function computes a partition of the bound of loop a thread should be dedicated to * Assume loops are of form for(int i = starting_index; i < final_index; i++) */ tuple<int, int> Boruvka::getLoopBounds(int threadID, int starting_index, int final_index) { int start, end; int cnt = (final_index - starting_index) / hardwareConcurrency; start = cnt * threadID + starting_index; if (cnt == 0) { start = threadID + starting_index; end = start + 1; if (start >= final_index) //if loop won't be executed even once start = end; } else { start = threadID * cnt + starting_index; // handling the case when cnt is not divisible by hardwareConcurrency if (threadID < hardwareConcurrency - 1) end = start + cnt; else end = final_index; } return make_tuple(start, end); } /* * Constructor for Boruvka * */ Boruvka::Boruvka(Graph &graph, int min_array_size, int no_of_threads): hardwareConcurrency(no_of_threads) { this->graph = graph; noOfVertices = graph.noOfVertices; minimumSizeOfArrayForSequentialOperation = min_array_size; noOfTheadsCreated = 0; root = vector<int> (noOfVertices); groups = map<int, vector<int> > (); outEdges = vector<vector<Edge> >(noOfVertices); inEdges = map<int, vector<Edge> >(); cheapest = vector<Edge> (noOfVertices); newGroups = map<int, vector<int> > (); newOutEdges = vector<vector<Edge> >(noOfVertices); // initially #noOfVertices components for (int i = 0; i < noOfVertices; i++) { groups[i] = vector<int>(); groups[i].push_back(i); outEdges[i] = graph.adjList[i]; // outgoing edge for a vertex inEdges[i] = vector<Edge> (); root[i] = i; // make every component parent of itself } } /* * Constructor for Boruvka * */ vector<Edge> Boruvka::run() { while (groups.size() > 1) { // preparing the data structures for the next iteration // on the new components computed previously newOutEdges = vector<vector<Edge> > (noOfVertices); newGroups = groups; keyset = getKeyset(); // cout << "start minedges\n" << endl; findMinEdges(); // parallelly find the minimum edge // cout << "start setNewGroups\n" << endl; //exit(0); setNewGroups(); // parallelly compute the connected components // cout << " ********** finsihed setNewGroups\n" << endl; if (newGroups.size() == 1) { // MST has been made break; } setNewOutEdges(); //merge the connected components // cout << "finsihed setNewOutEdges\n" << endl; } return inEdges[0]; } /* * returns a vector of the component id-s of the components present currently in group i.e. input in the current iteration */ vector<int> Boruvka::getKeyset() { vector<int> keys; for (auto it = groups.begin(); it != groups.end(); it++) { keys.insert(keys.end(), it->first); } return keys; } //returns a vector of the component id-s of the components currently in newgroup i.e. output after the current iteration vector<int> Boruvka::getNewKeyset() { vector<int> keys; for (auto it = newGroups.begin(); it != newGroups.end(); it++) { keys.insert(keys.end(), it->first); } return keys; } /* * concurrent implementation of finding minEdge on subset of vertices */ void Boruvka::findMinEdges() { std::vector<thread> th(hardwareConcurrency); for (int i = 0; i < hardwareConcurrency; i++) { th[i] = thread(&Boruvka::findMinEdgesPerThread, this, i); } noOfTheadsCreated += hardwareConcurrency; for (int i = 0; i < hardwareConcurrency; i++) { th[i].join(); } } /* * sequential function that will be called by spawning threads to find minimum element in a partition of array */ Edge Boruvka::minElementSequential(vector<Edge> &array, int start, int end) { auto begin_iterator = array.begin(); auto end_iterator = array.begin(); advance(begin_iterator, start); advance(end_iterator, end); return *min_element(begin_iterator, end_iterator, Boruvka::edgeCompare); } /* * parallel implementation of finding the minimum element */ Edge Boruvka::minElementGraph(vector<Edge> &array) { // if size is small enough no need to parallelize // Better if done sequentially if (array.size() < minimumSizeOfArrayForSequentialOperation ) { return *min_element(array.begin(), array.end(), Boruvka::edgeCompare); } else { // Parallel implementation of finding the minimum element int sz = array.size(), rl; int limit = sz / minimumSizeOfArrayForSequentialOperation; std::vector<std::future<Edge> > th(limit); // vector to hold the future of each spawned thread for (int i = 0; i < limit; i++) { if (i == limit - 1) { rl = sz; } else { rl = (i + 1) * minimumSizeOfArrayForSequentialOperation; } // calling the thread asynchronously to find minimum in an array partition th[i] = std::async(std::launch::async, &Boruvka::minElementSequential, this, ref(array), i * minimumSizeOfArrayForSequentialOperation, rl); } noOfTheadsCreated += limit; Edge result(-1, -1, INT_MAX); //dummy value to hold the final answer // loop to wait for future value of the spawned threads for (int i = 0; i < limit; i++) { Edge tmp = th[i].get(); if (tmp.w < result.w) { result = tmp; } } return result; } } void Boruvka::findMinEdgesPerThread (int threadID) { auto loopBounds = getLoopBounds(threadID, 0, keyset.size()); for (int i = get<0>(loopBounds); i < get<1>(loopBounds); i++) { int component = keyset[i]; cheapest[component] = minElementGraph(outEdges[component]); } } /* * sequential implementation of finding the connected components among the edges found in thhe first step * using union find data structure */ void Boruvka::setNewGroups() { for (int i = 0; i < keyset.size(); i++) { int group_id = keyset[i]; Edge minEdge = cheapest[group_id]; int root1 = getRootOfSubTree(minEdge.u); int root2 = getRootOfSubTree(minEdge.v); // if both trees are of the same component , no need to merge if (root1 == root2) { continue; } if (root1 < root2) { mergeNodeGroups(root1, root2); mergeNodeEdges(root1, root2, minEdge); } else { mergeNodeGroups(root2, root1); mergeNodeEdges(root2, root1, minEdge); } mergeSubTrees(root1, root2); } } /* * mering 2 groups by adding the nodes in child group to parent group */ void Boruvka::mergeNodeGroups(int root1, int root2) { newGroups[root1].insert(newGroups[root1].end(), newGroups[root2].begin(), newGroups[root2].end()); newGroups.erase(root2); } /* * mering in edges for the 2 groups merged above */ void Boruvka::mergeNodeEdges(int root1, int root2, Edge &picked) { inEdges[root1].insert(inEdges[root1].end(), inEdges[root2].begin(), inEdges[root2].end()); // adding the MST edge in inEdges inEdges[root1].push_back(picked); inEdges.erase(root2); } /* * union find data structure find */ int Boruvka::getRootOfSubTree(int i) { while (root[i] != i) { i = root[i]; } return i; } /* *union find data structure union */ void Boruvka::mergeSubTrees(int i, int j) { // performing path compression for smaller trees if (i < j) root[j] = i; else root[i] = j; } /* * parallel function to merge the components found in step 2 */ void Boruvka::setNewOutEdges() { std::vector<thread> th(hardwareConcurrency); // get the connected components of the merged groups keyset = getNewKeyset(); for (int i = 0; i < hardwareConcurrency; i++) { // spawn a thread calling setNewOutEdgesPerThread for the mereg operation th[i] = thread(&Boruvka::setNewOutEdgesPerThread, this, i); } noOfTheadsCreated += hardwareConcurrency; for (int i = 0; i < hardwareConcurrency; i++) { th[i].join(); } // save the updated edges and groups outEdges = newOutEdges; groups = newGroups; } /* * Sequential algorithm which merges the nodes edges physically */ void Boruvka::setNewOutEdgesPerThread(int threadID) { auto loopBounds = getLoopBounds(threadID, 0, keyset.size()); for (int i = get<0>(loopBounds); i < get<1>(loopBounds); i++) { int newcomponentID = keyset[i]; // getting all nodes that have been merged into 1 node std::vector<int> group_subcomponents = newGroups[newcomponentID]; newOutEdges[newcomponentID] = vector <Edge> (); for (auto it : group_subcomponents) { if (groups.find(it) == groups.end()) { // the 2 nodes have already been merged continue; } newOutEdges[newcomponentID].insert(newOutEdges[newcomponentID].end(), outEdges[it].begin(), outEdges[it].end()); outEdges[it].clear(); //edges not required as they have already been merged into a new edges } // remove the duplicated deleted edges for (auto it : inEdges[newcomponentID]) { deleteDuplicateOfEdgeInList(newOutEdges[newcomponentID], it); } // remove any cycles formed in the process deleteAllCycles(newcomponentID); } } /* * deletes all duplicates of edge 'e' in the vector 'v' */ void Boruvka::deleteDuplicateOfEdgeInList(vector<Edge> &list, Edge &e) { auto it = list.begin(); while (it != list.end()) { if ((it->u == e.u && it->v == e.v) || (it->u == e.v && it->v == e.u)) { *it = list.back(); //storing the edge e at the end list.pop_back(); continue; } it++; } } /* * iterates through all edges of component 'id' and deletes all edges that have two endpoints in the same component */ void Boruvka::deleteAllCycles(int id) { vector<Edge> *v = &newOutEdges[id]; vector<int> subs = groups[id]; auto it = v->begin(); while (it != v->end()) { int x = (*it).u; int y = (*it).v; if ( (find(subs.begin(), subs.end(), x) != subs.end()) && (find(subs.begin(), subs.end(), y) != subs.end())) { *it = v->back(); //storing the edge e at the end v->pop_back(); //deleting the last edge continue; } it++; } }
true
f988124cfa510d6bd396e45414adb6f1d83212bc
C++
rizkyaryapermana/tugas-struktur-data-1
/Unguide no 1.cpp
UTF-8
910
2.9375
3
[]
no_license
#include <iostream> using namespace std; int main() { cout << "========================" << endl; cout << " PENCARIAN ANGKA " << endl; cout << "========================\n" << endl; int n, bilangan_dicari, Data[10]; int i; bool ketemu = true; cout << "Masukkan banyak angka : "; cin >> n; for(int c=0; c<n; c++) { cout <<"Masukkan angka ke-" <<c<<" = "; cin >> Data[c]; } i=0; cout <<"\nData yang ingin dicari : "; cin >> bilangan_dicari; ketemu=0; while((i<10)&&(ketemu==0)) { if(Data[i]== bilangan_dicari) { ketemu=1; cout <<"\nAngka "<< bilangan_dicari<<" Ditemukan pada posisi ke "<<i; } else i=i+1; } if(ketemu) cout<<"\n\nData yang dicari ada"<<endl; else cout<<"\n\nData yang dicari tidak ada"<<endl; }
true
7318576dff22b3566831d98f201ee5b34fe95a58
C++
jnterry/xeno-engine
/tests/core/bits.cpp
UTF-8
7,014
2.953125
3
[]
no_license
//////////////////////////////////////////////////////////////////////////////// // Part of Xeno Engine // //////////////////////////////////////////////////////////////////////////////// /// \brief Contains unit tests for xeno engines helper types and functions for /// bit manipulation /// /// \ingroup unit_tests //////////////////////////////////////////////////////////////////////////////// #include <xen/core/bits.hpp> #include <catch.hpp> TEST_CASE("Const Bit Reference", "[core][bits]"){ // bit index : 6 5 4 3 2 1 0 const int val = 36; // 0 1 0 0 1 0 0 const xen::BitReference<int> bit0 = xen::makeBitReference(&val, 0); const xen::BitReference<int> bit1 = xen::makeBitReference(&val, 1); const xen::BitReference<int> bit2 = xen::makeBitReference(&val, 2); const xen::BitReference<int> bit3 = xen::makeBitReference(&val, 3); const xen::BitReference<int> bit4 = xen::makeBitReference(&val, 4); const xen::BitReference<int> bit5 = xen::makeBitReference(&val, 5); const xen::BitReference<int> bit6 = xen::makeBitReference(&val, 6); CHECK(bit0 == false); CHECK(bit1 == false); CHECK(bit2 == true); CHECK(bit3 == false); CHECK(bit4 == false); CHECK(bit5 == true); CHECK(bit6 == false); } TEST_CASE("Non-const Bit Reference", "[core][bits]"){ // bit index : 6 5 4 3 2 1 0 int val = 42; // 0 1 0 1 0 1 0 auto bit0 = xen::makeBitReference(&val, 0); auto bit1 = xen::makeBitReference(&val, 1); auto bit2 = xen::makeBitReference(&val, 2); auto bit3 = xen::makeBitReference(&val, 3); auto bit4 = xen::makeBitReference(&val, 4); auto bit5 = xen::makeBitReference(&val, 5); auto bit6 = xen::makeBitReference(&val, 6); REQUIRE(bit0 == false); REQUIRE(bit1 == true); REQUIRE(bit2 == false); REQUIRE(bit3 == true); REQUIRE(bit4 == false); REQUIRE(bit5 == true); REQUIRE(bit6 == false); SECTION("Set bit to 1"){ bit0 = 1; CHECK(bit0 == true); CHECK(bit1 == true); CHECK(bit2 == false); CHECK(bit3 == true); CHECK(bit4 == false); CHECK(bit5 == true); CHECK(bit6 == false); CHECK(val == 43); } SECTION("Set bit to true"){ bit4 = true; CHECK(bit0 == false); CHECK(bit1 == true); CHECK(bit2 == false); CHECK(bit3 == true); CHECK(bit4 == true); CHECK(bit5 == true); CHECK(bit6 == false); CHECK(val == 58); } SECTION("Set bit"){ bit6.set(); CHECK(bit0 == false); CHECK(bit1 == true); CHECK(bit2 == false); CHECK(bit3 == true); CHECK(bit4 == false); CHECK(bit5 == true); CHECK(bit6 == true); CHECK(val == 106); } SECTION("Set bit to 0"){ bit3 = 0; CHECK(bit0 == false); CHECK(bit1 == true); CHECK(bit2 == false); CHECK(bit3 == false); CHECK(bit4 == false); CHECK(bit5 == true); CHECK(bit6 == false); CHECK(val == 34); } SECTION("Set bit to false"){ bit1 = false; CHECK(bit0 == false); CHECK(bit1 == false); CHECK(bit2 == false); CHECK(bit3 == true); CHECK(bit4 == false); CHECK(bit5 == true); CHECK(bit6 == false); CHECK(val == 40); } SECTION("Clear bit"){ bit5.clear(); CHECK(bit0 == false); CHECK(bit1 == true); CHECK(bit2 == false); CHECK(bit3 == true); CHECK(bit4 == false); CHECK(bit5 == false); CHECK(bit6 == false); CHECK(val == 10); } SECTION("toogle"){ bit4.toogle(); CHECK(bit0 == false); CHECK(bit1 == true); CHECK(bit2 == false); CHECK(bit3 == true); CHECK(bit4 == true); CHECK(bit5 == true); CHECK(bit6 == false); CHECK(val == 58); } SECTION("Set equal to not self"){ bit4 = !bit4; CHECK(bit0 == false); CHECK(bit1 == true); CHECK(bit2 == false); CHECK(bit3 == true); CHECK(bit4 == true); CHECK(bit5 == true); CHECK(bit6 == false); CHECK(val == 58); } SECTION("Set equal to not another"){ bit4 = !bit0; CHECK(bit0 == false); CHECK(bit1 == true); CHECK(bit2 == false); CHECK(bit3 == true); CHECK(bit4 == true); CHECK(bit5 == true); CHECK(bit6 == false); CHECK(val == 58); } } TEST_CASE("BitField8", "[core][bits]"){ // 147 // bit indices : 7 6 5 4 3 2 1 0 // binary : 1 0 0 1 0 0 1 1 xen::BitField<u8, 8> field_a = 147; REQUIRE(field_a[0] == true); REQUIRE(field_a[1] == true); REQUIRE(field_a[2] == false); REQUIRE(field_a[3] == false); REQUIRE(field_a[4] == true); REQUIRE(field_a[5] == false); REQUIRE(field_a[6] == false); REQUIRE(field_a[7] == true); SECTION("Bitwise Not"){ auto result = ~field_a; CHECK(result[0] == false); CHECK(result[1] == false); CHECK(result[2] == true); CHECK(result[3] == true); CHECK(result[4] == false); CHECK(result[5] == true); CHECK(result[6] == true); CHECK(result[7] == false); } // 66 // bit indices : 7 6 5 4 3 2 1 0 // binary : 0 1 0 0 0 0 1 0 xen::BitField<u08, 8> field_b(66); REQUIRE(field_b[0] == false); REQUIRE(field_b[1] == true); REQUIRE(field_b[2] == false); REQUIRE(field_b[3] == false); REQUIRE(field_b[4] == false); REQUIRE(field_b[5] == false); REQUIRE(field_b[6] == true); REQUIRE(field_b[7] == false); // bit indices : 7 6 5 4 3 2 1 0 // field_a : 1 0 0 1 0 0 1 1 // field_b : 0 1 0 0 0 0 1 0 SECTION("Bitwise Or"){ auto result = field_a | field_b; CHECK(result[0] == true); CHECK(result[1] == true); CHECK(result[2] == false); CHECK(result[3] == false); CHECK(result[4] == true); CHECK(result[5] == false); CHECK(result[6] == true); CHECK(result[7] == true); } SECTION("Bitwise EqOr"){ field_a |= field_b; CHECK(field_a[0] == true); CHECK(field_a[1] == true); CHECK(field_a[2] == false); CHECK(field_a[3] == false); CHECK(field_a[4] == true); CHECK(field_a[5] == false); CHECK(field_a[6] == true); CHECK(field_a[7] == true); } SECTION("Bitwise And"){ auto result = field_a & field_b; CHECK(result[0] == false); CHECK(result[1] == true); CHECK(result[2] == false); CHECK(result[3] == false); CHECK(result[4] == false); CHECK(result[5] == false); CHECK(result[6] == false); CHECK(result[7] == false); } SECTION("Bitwise EqAnd"){ field_a &= field_b; CHECK(field_a[0] == false); CHECK(field_a[1] == true); CHECK(field_a[2] == false); CHECK(field_a[3] == false); CHECK(field_a[4] == false); CHECK(field_a[5] == false); CHECK(field_a[6] == false); CHECK(field_a[7] == false); } SECTION("Bitwise Xor"){ auto result = field_a ^ field_b; CHECK(result[0] == true); CHECK(result[1] == false); CHECK(result[2] == false); CHECK(result[3] == false); CHECK(result[4] == true); CHECK(result[5] == false); CHECK(result[6] == true); CHECK(result[7] == true); } SECTION("Bitwise EqXor"){ field_a ^= field_b; CHECK(field_a[0] == true); CHECK(field_a[1] == false); CHECK(field_a[2] == false); CHECK(field_a[3] == false); CHECK(field_a[4] == true); CHECK(field_a[5] == false); CHECK(field_a[6] == true); CHECK(field_a[7] == true); } }
true
e36a5f5e0775f9351f73998dd96c6c9f8a6c74a0
C++
xkyyxj/s
/algorithm/Calculator.cpp
UTF-8
63,182
3.171875
3
[]
no_license
// // Created by wangqchf on 2018/10/19. // #include "Calculator.h" //资源文件内容,暂时由main函数加载 extern std::map<std::string,std::string> res_map; price_fun Calculator::get_price_fun(PriceFlag flag) { price_fun ret_fun; switch(flag) { case PriceFlag::MAX_PRICE: ret_fun = &stock_info::get_af_max_price; break; case PriceFlag::MIN_PRICE: ret_fun = &stock_info::get_af_min_price; break; case PriceFlag::BEGIN_PRICE: ret_fun = &stock_info::get_af_begin_price; break; case PriceFlag::END_PRICE: ret_fun = &stock_info::get_af_end_price; break; default: ret_fun = &stock_info::get_af_max_price; break; } return ret_fun; } /** * 寻找期间当中最低价所在的天的信息 * 如果存在多天最低价相同,那么返回最后一天的信息 */ stock_info Calculator::find_low_point(std::list<stock_info>& info_list) { auto info_begin = info_list.begin(), info_end = info_list.end(); stock_info* ret_value = nullptr; float min_price = 0; while(info_begin != info_end) { if((*info_begin).get_min_price() < min_price) { min_price = (*info_begin).get_min_price(); ret_value = &(*info_begin); } info_begin++; } return ret_value ? *ret_value : stock_info(); } /** * 寻找期间当中最高价所在的天的信息 * 如果存在多天最高价相同,那么返回最后一天的信息 */ stock_info Calculator::find_high_point(std::list<stock_info> &info_list) { auto info_begin = info_list.begin(), info_end = info_list.end(); stock_info* ret_value = nullptr; float max_price = 0; while(info_begin != info_end) { if((*info_begin).get_max_price() < max_price) { max_price = (*info_begin).get_max_price(); ret_value = &(*info_begin); } info_begin++; } return ret_value ? *ret_value : stock_info(); } /** * 寻找期间的最大涨幅: * 期间最低价到期间最高价之间的差值 * 后续可能会添加控制选项,实现其他统计 */ void Calculator::calculate_max_min_r(std::list<stock_info>& info_list) { if(info_list.empty()) return; stock_info min_price_info, max_price_info; auto list_begin = info_list.begin(), list_end = info_list.end(); while(list_begin != list_end) { if ((*list_begin).get_min_price() < min_price) { min_price_info = (*list_begin); } if ((*list_begin).get_max_price() > max_price) { max_price_info = (*list_begin); } } } /** * 分析改段时间内连续N天上涨或者下跌的概率 */ void Calculator::prbality_analy(std::list<stock_info> &) { } /** * 这个算法目前按照后复权的价格来进行统计计算,但是打印的时候可以按照除权价格来输出 * 1. 在任意一天的收盘价买入之后,达到@param percent的涨幅,需要多少天,或者不能实现,不能实现的完成日期字段填写“xxxxxxx” * 2. 汇总统计一下,按照条件1买入,平均需要多少天达到@param percent的涨幅 * 3. 汇总一下,成功率是百分之几。 * * @param info_list 所有的基本信息 * @param percent 要求达到的百分比,正整数,如要求达到20%,那么这个参数应为20 * @param begin_date 开始日期,从这个日期往后进行统计,此参数有默认值:"0000-00-00" */ std::string Calculator::win_x_percent_days_ana(std::list<stock_info>& info_list, int percent, std::string begin_date) { //最终的结果结构体 struct percent_info { stock_info* base_info; //在base_info这一天买入 //resolve_time_info这一天达成了@param percent的百分比,如至今为止没达到,则为nullptr stock_info* resolve_time_info; //达成目标时候的上涨百分比 float percent; //达成目标花费的实际天数 long days; //判等操作,std::list的remove方法需要 bool operator==(const percent_info& param) { return base_info == param.base_info; } }; /** * 构建方式如下: * 维护一个已解决列表,和未解决列表 * 未解决列表按照价格从低到高进行排列 * 对于@param info_list所有基本信息列表进行遍历,对于每一个元素,检查是否能够解决未解决列表当中的元素: * 如果能够解决,则将其解决并移入已解决列表,然后将这个元素添加到未解决列表当中 * 如果不能解决,则将这个元素添加到未解决列表当中 */ float target_percent = static_cast<float>(percent) / 100; //构建最终百分比 auto list_begin = info_list.rbegin(), list_end = info_list.rend(); std::list<percent_info> unresolved_info; std::list<percent_info> resolved_info; while(list_begin != list_end) { stock_info* curr_info = &(*list_begin); if(curr_info->get_date_info_str().compare(begin_date) < 0) { //直到真正需要分析的开始日期为止 continue; } auto unresolved_begin = unresolved_info.begin(), unresolved_end = unresolved_info.end(); if(unresolved_begin != unresolved_end) { //看下能够解决到resolved当中,同时将当前天添加到unresolved_info当中,unresolved_info按照时间升序排列 bool resolved_finished = false; while(unresolved_begin != unresolved_end && !resolved_finished) { percent_info temp_info = (*unresolved_begin); float af_end_price = temp_info.base_info->get_af_end_price(); float cur_af_end_price = curr_info->get_af_end_price(); //看是否涨到了要求的百分比 if(cur_af_end_price > af_end_price && ((cur_af_end_price - af_end_price) / af_end_price) >= target_percent) { unresolved_begin = unresolved_info.erase(unresolved_begin); //从未解决当中移除,同时指向下一个元素 temp_info.percent = (cur_af_end_price - af_end_price) / af_end_price; //权重 //完成百分比涨幅花费的天数 temp_info.days = (curr_info->get_date_info() - temp_info.base_info->get_date_info()).days(); //记录完成这一天的信息 temp_info.resolve_time_info = curr_info; resolved_info.push_back(temp_info); //添加到已解决当中 } //遵从插入排序的方式,将当天放入到未解决列表当中 else if(cur_af_end_price > af_end_price) { unresolved_begin++; } else if(cur_af_end_price <= af_end_price) { percent_info temp_per_info{}; temp_per_info.base_info = curr_info; temp_per_info.percent = 0; temp_per_info.days = 0; temp_per_info.resolve_time_info = nullptr; unresolved_info.insert(unresolved_begin, temp_per_info); resolved_finished = true; } } if(!resolved_finished) { percent_info temp_per_info{}; temp_per_info.base_info = curr_info; temp_per_info.percent = 0; temp_per_info.days = 0; temp_per_info.resolve_time_info = nullptr; unresolved_info.push_back(temp_per_info); } } else { percent_info temp_per_info{}; temp_per_info.base_info = curr_info; temp_per_info.percent = 0; temp_per_info.days = 0; unresolved_info.push_back(temp_per_info); } list_begin++; } //统计信息 float resolved_percent = 0; long total_needed_days = 0; //总计花费了多少天达到目标百分比 //下面两个变量指明:达到目标百分比的有多少天,未达到目标百分比的有多少天 long finished_days = 0, unfinished_days = 0; unsigned long min_days = -1, max_days = 0; finished_days = resolved_info.size(); unfinished_days = unresolved_info.size(); resolved_percent = static_cast<float>(finished_days) / (finished_days + unfinished_days); //处理完成后,按照日期进行排序 auto unresolved_begin = unresolved_info.begin(), unresolved_end = unresolved_info.end(); auto resolved_begin = resolved_info.begin(); resolved_info.insert(resolved_begin, unresolved_begin, unresolved_end); resolved_info.sort([](const percent_info& first, const percent_info& second) -> bool { return first.base_info->get_date_info_str().compare(second.base_info->get_date_info_str()) <= 0; }); //排序完成后,按照排序结果构建输出字符串 //此外忽然有了一个想法:既然是构建输出字符串比较规整,可以输出为csv文件格式,有Excel进行排序操作 resolved_begin = resolved_info.begin(); auto resolved_end = resolved_info.end(); std::string output_str; //构建表头信息 //下面几个字段按照顺序分别是: //日期,编码,名称,达成获利目标日期,除权开盘价,除权收盘价,除权最高价,除权最低价,盈利百分比,盈利所需天数, output_str.append(res_map["100000CH00001"]).append(",").append(res_map["100000CH00002"]).append(","); output_str.append(res_map["100000CH00003"]).append(",").append(res_map["100000CH00017"]).append(","); output_str.append(res_map["100000CH00004"]).append(",").append(res_map["100000CH00005"]).append(","); output_str.append(res_map["100000CH00006"]).append(",").append(res_map["100000CH00007"]).append(","); output_str.append(res_map["100000CH00008"]).append(",").append(res_map["100000CH00009"]).append(","); output_str.append("\n"); while(resolved_begin != resolved_end) { percent_info per_info = (*resolved_begin); output_str.append(per_info.base_info->get_date_info_str()).append(","); output_str.append(per_info.base_info->get_stock_code()).append(","); output_str.append(per_info.base_info->get_stock_name()).append(","); output_str.append(per_info.resolve_time_info ? per_info.resolve_time_info->get_date_info_str() : "xxxxxxxx").append(","); output_str.append(std::to_string(per_info.base_info->get_begin_price())).append(","); output_str.append(std::to_string(per_info.base_info->get_end_price())).append(","); output_str.append(std::to_string(per_info.base_info->get_max_price())).append(","); output_str.append(std::to_string(per_info.base_info->get_min_price())).append(","); output_str.append(std::to_string(per_info.percent * 100)).append("%,"); output_str.append(std::to_string(per_info.days)).append(","); output_str.append("\n"); //顺便循环体当中重新统计一下总计解决天数、最少需要天数以及最大需要天数 total_needed_days += per_info.days; min_days = per_info.days > 0 && per_info.days < min_days ? per_info.days : min_days; max_days = per_info.days > 0 && per_info.days > max_days ? per_info.days : max_days; resolved_begin++; } //将统计信息写入到csv文件当中 output_str.append(res_map["100000CH00010"]/*盈利天数百分比*/).append(std::to_string(resolved_percent)).append("\n"); output_str.append(res_map["100000CH00011"]/*盈利天数*/).append(std::to_string(finished_days)).append("\n"); output_str.append(res_map["100000CH00012"]/*不能获利天数*/).append(std::to_string(unfinished_days)).append("\n"); output_str.append(res_map["100000CH00013"]/*获利所需总天数*/).append(std::to_string(total_needed_days)).append("\n"); output_str.append(res_map["100000CH00014"]/*获利所需平均天数*/).append(std::to_string(static_cast<float>(total_needed_days) / finished_days)); output_str.append("\n"); output_str.append(res_map["100000CH00015"]/*获利所需最小天数*/).append(std::to_string(min_days)).append("\n"); output_str.append(res_map["100000CH00016"]/*获利所需最长天数*/).append(std::to_string(max_days)).append("\n"); return output_str; } /** * 在当天以@param buy_price指定价格买入的话,那么截止@param days天位置,以@param sold_price价格卖出: * 1.最高收益多少 * 2.第@param days天收益如何? * 3.最高收益出现在第几天?(非交易日不算在天数当中) * 4.最少收益多少? * 5.达到@param days天的时候上涨的天数有多少?下降的天数有多少? * 得出百分比等信息。 * * @param info_list 基本信息列表 * @param days 要求获取days天后的结果,days只计算交易日,非交易日不计算到days当中 * @param begin_date 从begin_date天之后开始分析 * @param buy_price 买入价格 * @param sold_price 卖出价格 */ std::string Calculator::buy_interest_ana(std::list<stock_info> &info_list, int days, std::string begin_date, PriceFlag buy_price,PriceFlag sold_price) { struct max_buy_rst { stock_info* base_info; //base_info当天最高价买入,然后@param days那一天以收盘价卖出收益率 float days_percent; //base_info当天最高价买入,@param days天之间最高的收益率如何(收盘价计算收益率) float max_win_percent; //base_info当天最高价买入,@param days天之间最高的损失率如何(收盘价计算收益率) float max_lost_percent; //实现@param days天当中最大收益率,是在买入多少天后实现的?(非交易日不算入天数当中) int to_max_win_days; //辅助上面的非交易日不算入天数当中而添加的变量 int lower_max_win_days; //实现@param days天过程当汇总最大收益率的那天的基本信息 stock_info* mid_max_win_info; //在历经@param days这些天当中,如能获利,则为true bool mid_has_up = false; }; price_fun buy_price_fun = get_price_fun(buy_price), sold_price_fun = get_price_fun(sold_price); //统计信息 int total_days = 0; //总天数,可能有部分天不盈利也不损失 //@param days天的时候,如果获利,则此数加一 int up_days_num = 0; //@param days天的时候,如果损失,则此数加一 int down_days_num = 0; //在历经@param days这些天当中,如能获利,则此数加一,即中间历程可上涨天数 int mid_up_days_num = 0; //在历经@param days这些天当中,如果始终未获利(包含一直损失),则此数加一, int mid_down_days_num = 0; //下面三个为@param days天后那一天的数据,所有天的统计信息 float max_win_percent = 0; //最大的获利比例 float min_win_percent = 10000; //最小获利比例 float max_lose_percent = 0; //最大损失比例 //@param days天的过程当中最大收益率的平均值 float ave_max_win_percent = 0; //到达@param days天的时候,收益率的平均值是多少 float ave_target_win_percent = 0; //下面三个为@param days天之间的数据,所有天的统计信息 float mid_max_win_percent = 0; //最大的获利比例 float mid_min_win_percent = 10000; //最小获利比例 float mid_max_lose_percent = 0; //最大损失比例 auto list_begin = info_list.rbegin(), list_end = info_list.rend(); std::list<max_buy_rst> rst_list; /** * */ stock_info* temp_info = nullptr; //初始化rst_list,添加一个元素 max_buy_rst init_item{}; temp_info = &(*list_begin); init_item.base_info = temp_info; init_item.max_win_percent = -10000; rst_list.push_back(init_item); list_begin++; auto rst_begin = rst_list.begin(), windows_p = rst_list.begin(), rst_end = rst_list.end(); while(list_begin != list_end) { temp_info = &(*list_begin); windows_p = rst_begin, rst_end = rst_list.end(); /** * 滑动窗格,rst_list的头部指针始终落后@param days天, * 每次新增加一个元素到rst_list当中的时候,如果rst_list长度大于等于@param days, * 那么就会将rst_list的头部指针向前移动一个元素 */ for(int i = 0;i < days && windows_p != rst_end;i++) { /** * 计算收益比率,按照当天的收盘价来算 * 计算经历@param days的过程当中,可能的收益信息。 */ max_buy_rst& buy_rst = (*windows_p); float buy_price_val = (buy_rst.base_info->*buy_price_fun)(); float cur_sold_price_val = (temp_info->*sold_price_fun)(); float curr_win_percent = (cur_sold_price_val - buy_price_val) / buy_price_val; buy_rst.max_win_percent = buy_rst.max_win_percent > curr_win_percent ? buy_rst.max_win_percent : curr_win_percent; if(buy_rst.max_win_percent > curr_win_percent) { buy_rst.lower_max_win_days++; } else { buy_rst.to_max_win_days = buy_rst.to_max_win_days + buy_rst.lower_max_win_days + 1; buy_rst.lower_max_win_days = 0; } buy_rst.mid_max_win_info = curr_win_percent > mid_max_win_percent ? temp_info : buy_rst.mid_max_win_info; buy_rst.max_lost_percent = buy_rst.max_lost_percent > curr_win_percent ? curr_win_percent : buy_rst.max_lost_percent; mid_max_win_percent = curr_win_percent > mid_max_win_percent ? curr_win_percent : mid_max_win_percent; mid_max_lose_percent = mid_max_lose_percent < curr_win_percent ? mid_max_lose_percent : curr_win_percent; mid_min_win_percent = curr_win_percent > 0 && curr_win_percent < mid_min_win_percent ? curr_win_percent : mid_min_win_percent; buy_rst.mid_has_up = curr_win_percent > 0 || buy_rst.mid_has_up; if(i == days - 1) { /** * 计算最终达到@param days天的时候,收益率如何 * 还要有一个C++的语法陷阱:C++当中的引用是不能被重新指向新对象的, * 所以说如下的代码实际上会调用type operator=(type),编译器提供的默认的等号操作符重载 * 对于自己代码没有重写等号赋值操作的来说,就会像是默认拷贝构造函数一样,对类中的每个子对象调用 * oeprator=的等号赋值操作。 * buy_rst = (*rst_begin); */ max_buy_rst& target_buy_rst = (*rst_begin); buy_price_val = (target_buy_rst.base_info->*buy_price_fun)(); curr_win_percent = (cur_sold_price_val - buy_price_val) / buy_price_val; target_buy_rst.days_percent = curr_win_percent; max_win_percent = curr_win_percent > max_win_percent ? curr_win_percent : max_win_percent; max_lose_percent = max_lose_percent < curr_win_percent ? max_lose_percent : curr_win_percent; min_win_percent = curr_win_percent > 0 && curr_win_percent < min_win_percent ? curr_win_percent : min_win_percent; curr_win_percent > 0 ? up_days_num++ : 1; curr_win_percent < 0 ? down_days_num++ : 1; //统计最大收益率的平均值 ave_max_win_percent += buy_rst.max_win_percent; //统计到达@param days天是收益率的平均值 ave_target_win_percent += buy_rst.days_percent; rst_begin++; } windows_p++; } max_buy_rst insert_item{}; insert_item.base_info = temp_info; insert_item.max_win_percent = -10000; rst_list.push_back(insert_item); list_begin++; } //收益率平均值方面的重新计算 ave_max_win_percent /= rst_list.size(); ave_target_win_percent /= rst_list.size(); //构建输出信息,csv格式 std::string output_str; //下面几个字段按照顺序分别是: //日期,编码,名称,除权开盘价,除权收盘价,除权最高价,除权最低价,目标日盈利百分比,中间最大盈利百分比,中间最大损失百分比 //中间最大盈利所需天数,中间是否盈利 output_str.append(res_map["100000CH00001"]).append(",").append(res_map["100000CH00002"]).append(","); output_str.append(res_map["100000CH00003"]).append(",").append(res_map["100000CH00004"]).append(","); output_str.append(res_map["100000CH00005"]).append(",").append(res_map["100000CH00006"]).append(","); output_str.append(res_map["100000CH00007"]).append(",").append(res_map["100000CH00018"]).append(","); output_str.append(res_map["100000CH00019"]).append(",").append(res_map["100000CH00020"]).append(","); output_str.append(res_map["100000CH00021"]).append(",").append(res_map["100000CH00022"]).append(","); output_str.append("\n"); rst_begin = rst_list.begin(), rst_end = rst_list.end(); while(rst_begin != rst_end) { max_buy_rst& buy_rst = (*rst_begin); //统计一下相关信息,@param days的中间历程当中是否上涨过 buy_rst.mid_has_up ? mid_up_days_num++ : mid_down_days_num++; output_str.append(buy_rst.base_info->get_date_info_str()).append(","); output_str.append(buy_rst.base_info->get_stock_code()).append(","); output_str.append(buy_rst.base_info->get_stock_name()).append(","); output_str.append(std::to_string(buy_rst.base_info->get_begin_price())).append(","); output_str.append(std::to_string(buy_rst.base_info->get_end_price())).append(","); output_str.append(std::to_string(buy_rst.base_info->get_max_price())).append(","); output_str.append(std::to_string(buy_rst.base_info->get_min_price())).append(","); output_str.append(std::to_string(buy_rst.days_percent * 100)).append("%,"); output_str.append(std::to_string(buy_rst.max_win_percent * 100)).append("%,"); output_str.append(std::to_string(buy_rst.max_lost_percent * 100)).append("%,"); output_str.append(std::to_string(buy_rst.to_max_win_days)).append(","); output_str.append(buy_rst.mid_has_up ? "Y" : "N").append(","); output_str.append("\n"); rst_begin++; } //输出统计信息到字符串当中 output_str.append(res_map["100000CH00023"]/*上涨天数:*/).append(std::to_string(up_days_num)).append("\n"); output_str.append(res_map["100000CH00024"]/*下跌天数:*/).append(std::to_string(down_days_num)).append("\n"); output_str.append(res_map["100000CH00025"]/*中间历程上涨天数:*/).append(std::to_string(mid_up_days_num)).append("\n"); output_str.append(res_map["100000CH00026"]/*中间历程未上涨天数:*/).append(std::to_string(mid_down_days_num)).append("\n"); output_str.append(res_map["100000CH00028"]/*目标日最大盈利百分比*/).append(std::to_string(max_win_percent)).append("\n"); output_str.append(res_map["100000CH00027"]/*目标日最小盈利百分比*/).append(std::to_string(min_win_percent)).append("\n"); output_str.append(res_map["100000CH00029"]/*目标日最大损失百分比:*/).append(std::to_string(max_lose_percent)).append("\n"); output_str.append(res_map["100000CH00019"]/*中间最大盈利百分比*/).append(":").append(std::to_string(mid_max_win_percent)).append("\n"); output_str.append(res_map["100000CH00030"]/*中间最小盈利百分比*/).append(std::to_string(mid_min_win_percent)).append("\n"); output_str.append(res_map["100000CH00020"]/*中间最大损失百分比*/).append(":").append(std::to_string(mid_max_lose_percent)).append("\n"); output_str.append(res_map["100000CH00031"]/*平均最大盈利百分比*/).append(std::to_string(ave_max_win_percent)).append("\n"); output_str.append(res_map["100000CH00032"]/*平均目标日盈利百分比*/).append(std::to_string(ave_target_win_percent)).append("\n"); return output_str; } /** * 特定的买入模式分析收益率如何,下降@param down_days天之后买入的效果如何,其余的和buy_interest_ana类似 */ std::string Calculator::patter_buy(std::list<stock_info>& info_list, int down_days, int days, PriceFlag buy_price, PriceFlag sold_price) { struct buy_rst { stock_info* base_info = nullptr; //base_info当天最高价买入,然后@param days那一天以收盘价卖出收益率 float days_percent = 0; //base_info当天最高价买入,@param days天之间最高的收益率如何(收盘价计算收益率) float max_win_percent = 0; //base_info当天最高价买入,@param days天之间最高的损失率如何(收盘价计算收益率) float max_lost_percent = 0; //实现@param days天当中最大收益率,是在买入多少天后实现的?(非交易日不算入天数当中) int to_max_win_days = 0; //辅助上面的非交易日不算入天数当中而添加的变量 int lower_max_win_days = 0; //实现@param days天过程当汇总最大收益率的那天的基本信息 stock_info* mid_max_win_info = nullptr; //在历经@param days这些天当中,如能获利,则为true bool mid_has_up = false; //计量在base_info天买进的话,已经往后计算了多少天的收益 int cal_days_count= 0; }; //统计信息 int total_days = 0; //总天数,可能有部分天不盈利也不损失 //@param days天的时候,如果获利,则此数加一 int up_days_num = 0; //@param days天的时候,如果损失,则此数加一 int down_days_num = 0; //在历经@param days这些天当中,如能获利,则此数加一,即中间历程可上涨天数 int mid_up_days_num = 0; //在历经@param days这些天当中,如果始终未获利(包含一直损失),则此数加一, int mid_down_days_num = 0; //下面三个为@param days天后那一天的数据,所有天的统计信息 float max_win_percent = 0; //最大的获利比例 float min_win_percent = 10000; //最小获利比例 float max_lose_percent = 0; //最大损失比例 //@param days天的过程当中最大收益率的平均值 float ave_max_win_percent = 0; //到达@param days天的时候,收益率的平均值是多少 float ave_target_win_percent = 0; //下面三个为@param days天之间的数据,所有天的统计信息 float mid_max_win_percent = 0; //最大的获利比例 float mid_min_win_percent = 10000; //最小获利比例 float mid_max_lose_percent = 0; //最大损失比例 price_fun buy_fun = get_price_fun(buy_price), sold_fun = get_price_fun(sold_price); auto list_begin = info_list.rbegin(), list_end = info_list.rend(); std::list<buy_rst> rst_list; std::list<buy_rst>::iterator rst_begin = rst_list.begin(), rst_end; stock_info* temp_stock; int _down_days = 0; while(list_begin != list_end) { temp_stock = &(*list_begin); if(temp_stock->get_af_end_price() < temp_stock->get_af_begin_price()) { _down_days++; } else { _down_days = 0; } //将下面原先的==判定改为>=,就可以实现@param down_days为零的时候,任意一天买入,判定days之内的收益如何 if(_down_days >= down_days) { buy_rst insert_rst{}; insert_rst.base_info = temp_stock; rst_list.push_back(insert_rst); if(rst_list.size() == 1) { rst_begin = rst_list.begin(); continue; } } auto windows_p = rst_begin; rst_end = rst_list.end(); while(windows_p != rst_end) { buy_rst& rst_info = *windows_p; //特殊处理这种情况,避免当天是连续下降@param days的那一天,然后该天自己和自己计算收益 if(rst_info.base_info == temp_stock) { //如果此种情况达成,说明已经到了rst_list的末尾 break; } if(rst_info.cal_days_count >= days) { //永远不使rst_begin指向rst_list的末尾 auto temp_ite = rst_begin; if(++temp_ite != rst_end) { rst_begin++; } if(rst_info.cal_days_count == days) { buy_rst& target_buy_rst = (*rst_begin); float buy_price_val = (target_buy_rst.base_info->*buy_fun)(); float cur_sold_price_val = (temp_stock->*sold_fun)(); float curr_win_percent = (cur_sold_price_val - buy_price_val) / buy_price_val; target_buy_rst.days_percent = curr_win_percent; max_win_percent = curr_win_percent > max_win_percent ? curr_win_percent : max_win_percent; max_lose_percent = max_lose_percent < curr_win_percent ? max_lose_percent : curr_win_percent; min_win_percent = curr_win_percent > 0 && curr_win_percent < min_win_percent ? curr_win_percent : min_win_percent; curr_win_percent > 0 ? up_days_num++ : 1; curr_win_percent < 0 ? down_days_num++ : 1; //统计最大收益率的平均值 ave_max_win_percent += rst_info.max_win_percent; //统计到达@param days天是收益率的平均值 ave_target_win_percent += rst_info.days_percent; rst_info.cal_days_count++; } } else { float buy_price_val = (rst_info.base_info->*buy_fun)(); float cur_sold_price_val = (temp_stock->*sold_fun)(); float curr_win_percent = (cur_sold_price_val - buy_price_val) / buy_price_val; rst_info.max_win_percent = rst_info.max_win_percent > curr_win_percent ? rst_info.max_win_percent : curr_win_percent; if(rst_info.max_win_percent > curr_win_percent) { rst_info.lower_max_win_days++; } else { rst_info.to_max_win_days = rst_info.to_max_win_days + rst_info.lower_max_win_days + 1; rst_info.lower_max_win_days = 0; } rst_info.mid_max_win_info = curr_win_percent > mid_max_win_percent ? temp_stock : rst_info.mid_max_win_info; rst_info.max_lost_percent = rst_info.max_lost_percent > curr_win_percent ? curr_win_percent : rst_info.max_lost_percent; mid_max_win_percent = curr_win_percent > mid_max_win_percent ? curr_win_percent : mid_max_win_percent; mid_max_lose_percent = mid_max_lose_percent < curr_win_percent ? mid_max_lose_percent : curr_win_percent; mid_min_win_percent = curr_win_percent > 0 && curr_win_percent < mid_min_win_percent ? curr_win_percent : mid_min_win_percent; rst_info.mid_has_up = curr_win_percent > 0 || rst_info.mid_has_up; rst_info.cal_days_count++; } windows_p++; } list_begin++; } //收益率平均值方面的重新计算 ave_max_win_percent /= rst_list.size(); ave_target_win_percent /= rst_list.size(); //构建输出信息,csv格式 std::string output_str; //下面几个字段按照顺序分别是: //日期,编码,名称,除权开盘价,除权收盘价,除权最高价,除权最低价,目标日盈利百分比,中间最大盈利百分比,中间最大损失百分比 //中间最大盈利所需天数,中间是否盈利 output_str.append(res_map["100000CH00001"]).append(",").append(res_map["100000CH00002"]).append(","); output_str.append(res_map["100000CH00003"]).append(",").append(res_map["100000CH00004"]).append(","); output_str.append(res_map["100000CH00005"]).append(",").append(res_map["100000CH00006"]).append(","); output_str.append(res_map["100000CH00007"]).append(",").append(res_map["100000CH00018"]).append(","); output_str.append(res_map["100000CH00019"]).append(",").append(res_map["100000CH00020"]).append(","); output_str.append(res_map["100000CH00021"]).append(",").append(res_map["100000CH00022"]).append(","); output_str.append("\n"); rst_begin = rst_list.begin(), rst_end = rst_list.end(); while(rst_begin != rst_end) { buy_rst& rst_info = (*rst_begin); //统计一下相关信息,@param days的中间历程当中是否上涨过 rst_info.mid_has_up ? mid_up_days_num++ : mid_down_days_num++; output_str.append(rst_info.base_info->get_date_info_str()).append(","); output_str.append(rst_info.base_info->get_stock_code()).append(","); output_str.append(rst_info.base_info->get_stock_name()).append(","); output_str.append(std::to_string(rst_info.base_info->get_begin_price())).append(","); output_str.append(std::to_string(rst_info.base_info->get_end_price())).append(","); output_str.append(std::to_string(rst_info.base_info->get_max_price())).append(","); output_str.append(std::to_string(rst_info.base_info->get_min_price())).append(","); output_str.append(std::to_string(rst_info.days_percent * 100)).append("%,"); output_str.append(std::to_string(rst_info.max_win_percent * 100)).append("%,"); output_str.append(std::to_string(rst_info.max_lost_percent * 100)).append("%,"); output_str.append(std::to_string(rst_info.to_max_win_days)).append(","); output_str.append(rst_info.mid_has_up ? "Y" : "N").append(","); output_str.append("\n"); rst_begin++; } //输出统计信息到字符串当中 output_str.append(res_map["100000CH00023"]/*上涨天数:*/).append(std::to_string(up_days_num)).append("\n"); output_str.append(res_map["100000CH00024"]/*下跌天数:*/).append(std::to_string(down_days_num)).append("\n"); output_str.append(res_map["100000CH00025"]/*中间历程上涨天数:*/).append(std::to_string(mid_up_days_num)).append("\n"); output_str.append(res_map["100000CH00026"]/*中间历程未上涨天数:*/).append(std::to_string(mid_down_days_num)).append("\n"); output_str.append(res_map["100000CH00028"]/*目标日最大盈利百分比*/).append(std::to_string(max_win_percent)).append("\n"); output_str.append(res_map["100000CH00027"]/*目标日最小盈利百分比*/).append(std::to_string(min_win_percent)).append("\n"); output_str.append(res_map["100000CH00029"]/*目标日最大损失百分比:*/).append(std::to_string(max_lose_percent)).append("\n"); output_str.append(res_map["100000CH00019"]/*中间最大盈利百分比*/).append(":").append(std::to_string(mid_max_win_percent)).append("\n"); output_str.append(res_map["100000CH00030"]/*中间最小盈利百分比*/).append(std::to_string(mid_min_win_percent)).append("\n"); output_str.append(res_map["100000CH00020"]/*中间最大损失百分比*/).append(":").append(std::to_string(mid_max_lose_percent)).append("\n"); output_str.append(res_map["100000CH00031"]/*平均最大盈利百分比*/).append(std::to_string(ave_max_win_percent)).append("\n"); output_str.append(res_map["100000CH00032"]/*平均目标日盈利百分比*/).append(std::to_string(ave_target_win_percent)).append("\n"); return output_str; } /** * 特定的买入模式分析收益率如何,上升@param up_percent之后买入的效果如何,达到up_percent的后一天买入, * 其余的和buy_interest_ana类似 * * 需要关注的是这个过程当中 */ std::string Calculator::up_buy(std::list<stock_info>& info_list, int up_percent, int days, PriceFlag buy_price, PriceFlag sold_price, std::list<turn_point>& turn_list) { struct buy_rst { stock_info* base_info = nullptr; //base_info当天最高价买入,然后@param days那一天以收盘价卖出收益率 float days_percent = 0; //base_info当天最高价买入,@param days天之间最高的收益率如何(收盘价计算收益率) float max_win_percent = 0; //base_info当天最高价买入,@param days天之间最高的损失率如何(收盘价计算收益率) float max_lost_percent = 0; //实现@param days天当中最大收益率,是在买入多少天后实现的?(非交易日不算入天数当中) int to_max_win_days = 0; //辅助上面的非交易日不算入天数当中而添加的变量 int lower_max_win_days = 0; //实现@param days天过程当汇总最大收益率的那天的基本信息 stock_info* mid_max_win_info = nullptr; //在历经@param days这些天当中,如能获利,则为true bool mid_has_up = false; //计量在base_info天买进的话,已经往后计算了多少天的收益 int cal_days_count= 0; }; //统计信息 int total_days = 0; //总天数,可能有部分天不盈利也不损失 //@param days天的时候,如果获利,则此数加一 int up_days_num = 0; //@param days天的时候,如果损失,则此数加一 int down_days_num = 0; //在历经@param days这些天当中,如能获利,则此数加一,即中间历程可上涨天数 int mid_up_days_num = 0; //在历经@param days这些天当中,如果始终未获利(包含一直损失),则此数加一, int mid_down_days_num = 0; //下面三个为@param days天后那一天的数据,所有天的统计信息 float max_win_percent = 0; //最大的获利比例 float min_win_percent = 10000; //最小获利比例 float max_lose_percent = 0; //最大损失比例 //@param days天的过程当中最大收益率的平均值 float ave_max_win_percent = 0; //到达@param days天的时候,收益率的平均值是多少 float ave_target_win_percent = 0; //下面三个为@param days天之间的数据,所有天的统计信息 float mid_max_win_percent = 0; //最大的获利比例 float mid_min_win_percent = 10000; //最小获利比例 float mid_max_lose_percent = 0; //最大损失比例 float real_up_percent = static_cast<float>(up_percent) / 100; price_fun buy_fun = get_price_fun(buy_price), sold_fun = get_price_fun(sold_price); auto list_begin = info_list.rbegin(), list_end = info_list.rend(); std::list<buy_rst> rst_list; std::list<buy_rst>::iterator rst_begin = rst_list.begin(), rst_end; stock_info* temp_stock, *up_start_stock, *up_start_next_day, *pre_day_info; if(list_begin != list_end) { up_start_stock = &(*list_begin); pre_day_info = up_start_stock; list_begin++; } while(list_begin != list_end) { temp_stock = &(*list_begin); if(temp_stock->get_af_end_price() > pre_day_info->get_af_end_price()) { if((temp_stock->get_af_end_price() - up_start_stock->get_af_end_price()) / up_start_stock->get_af_end_price() >= real_up_percent) { buy_rst insert_rst{}; //为了不因为list_begin++而导致的空缺了一天 auto next_day_ite = list_begin; next_day_ite++; //如果是当前天达到了目标涨幅,那么就在下一天买入 if(next_day_ite != list_end) { temp_stock = &(*next_day_ite); insert_rst.base_info = temp_stock; rst_list.push_back(insert_rst); if(rst_list.size() == 1) { rst_begin = rst_list.begin(); continue; } } } } else { up_start_stock = temp_stock; } pre_day_info = temp_stock; //将下面原先的==判定改为>=,就可以实现@param down_days为零的时候,任意一天买入,判定days之内的收益如何 auto windows_p = rst_begin; rst_end = rst_list.end(); while(windows_p != rst_end) { buy_rst& rst_info = *windows_p; //特殊处理这种情况,避免后面的天通前面的天计算收益 if(rst_info.base_info->get_date_info() >= temp_stock->get_date_info()) { //如果此种情况达成,说明已经到了rst_list的末尾 break; } if(rst_info.cal_days_count >= days) { //永远不使rst_begin指向rst_list的末尾 auto temp_ite = rst_begin; if(++temp_ite != rst_end) { rst_begin++; } if(rst_info.cal_days_count == days) { buy_rst& target_buy_rst = (*rst_begin); float buy_price_val = (target_buy_rst.base_info->*buy_fun)(); float cur_sold_price_val = (temp_stock->*sold_fun)(); float curr_win_percent = (cur_sold_price_val - buy_price_val) / buy_price_val; target_buy_rst.days_percent = curr_win_percent; max_win_percent = curr_win_percent > max_win_percent ? curr_win_percent : max_win_percent; max_lose_percent = max_lose_percent < curr_win_percent ? max_lose_percent : curr_win_percent; min_win_percent = curr_win_percent > 0 && curr_win_percent < min_win_percent ? curr_win_percent : min_win_percent; curr_win_percent > 0 ? up_days_num++ : 1; curr_win_percent < 0 ? down_days_num++ : 1; //统计最大收益率的平均值 ave_max_win_percent += rst_info.max_win_percent; //统计到达@param days天是收益率的平均值 ave_target_win_percent += rst_info.days_percent; rst_info.cal_days_count++; } } else { float buy_price_val = (rst_info.base_info->*buy_fun)(); float cur_sold_price_val = (temp_stock->*sold_fun)(); float curr_win_percent = (cur_sold_price_val - buy_price_val) / buy_price_val; rst_info.max_win_percent = rst_info.max_win_percent > curr_win_percent ? rst_info.max_win_percent : curr_win_percent; if(rst_info.max_win_percent > curr_win_percent) { rst_info.lower_max_win_days++; } else { rst_info.to_max_win_days = rst_info.to_max_win_days + rst_info.lower_max_win_days + 1; rst_info.lower_max_win_days = 0; } rst_info.mid_max_win_info = curr_win_percent > mid_max_win_percent ? temp_stock : rst_info.mid_max_win_info; rst_info.max_lost_percent = rst_info.max_lost_percent > curr_win_percent ? curr_win_percent : rst_info.max_lost_percent; mid_max_win_percent = curr_win_percent > mid_max_win_percent ? curr_win_percent : mid_max_win_percent; mid_max_lose_percent = mid_max_lose_percent < curr_win_percent ? mid_max_lose_percent : curr_win_percent; mid_min_win_percent = curr_win_percent > 0 && curr_win_percent < mid_min_win_percent ? curr_win_percent : mid_min_win_percent; rst_info.mid_has_up = curr_win_percent > 0 || rst_info.mid_has_up; rst_info.cal_days_count++; } windows_p++; } list_begin++; } //收益率平均值方面的重新计算 ave_max_win_percent /= rst_list.size(); ave_target_win_percent /= rst_list.size(); //构建输出信息,csv格式 std::string output_str; //下面几个字段按照顺序分别是: //日期,编码,名称,除权开盘价,除权收盘价,除权最高价,除权最低价,目标日盈利百分比,中间最大盈利百分比,中间最大损失百分比 //中间最大盈利所需天数,中间是否盈利 output_str.append(res_map["100000CH00001"]).append(",").append(res_map["100000CH00002"]).append(","); output_str.append(res_map["100000CH00003"]).append(",").append(res_map["100000CH00004"]).append(","); output_str.append(res_map["100000CH00005"]).append(",").append(res_map["100000CH00006"]).append(","); output_str.append(res_map["100000CH00007"]).append(",").append(res_map["100000CH00018"]).append(","); output_str.append(res_map["100000CH00019"]).append(",").append(res_map["100000CH00020"]).append(","); output_str.append(res_map["100000CH00021"]).append(",").append(res_map["100000CH00022"]).append(","); output_str.append("\n"); rst_begin = rst_list.begin(), rst_end = rst_list.end(); while(rst_begin != rst_end) { buy_rst& rst_info = (*rst_begin); //统计一下相关信息,@param days的中间历程当中是否上涨过 rst_info.mid_has_up ? mid_up_days_num++ : mid_down_days_num++; output_str.append(rst_info.base_info->get_date_info_str()).append(","); output_str.append(rst_info.base_info->get_stock_code()).append(","); output_str.append(rst_info.base_info->get_stock_name()).append(","); output_str.append(std::to_string(rst_info.base_info->get_begin_price())).append(","); output_str.append(std::to_string(rst_info.base_info->get_end_price())).append(","); output_str.append(std::to_string(rst_info.base_info->get_max_price())).append(","); output_str.append(std::to_string(rst_info.base_info->get_min_price())).append(","); output_str.append(std::to_string(rst_info.days_percent * 100)).append("%,"); output_str.append(std::to_string(rst_info.max_win_percent * 100)).append("%,"); output_str.append(std::to_string(rst_info.max_lost_percent * 100)).append("%,"); output_str.append(std::to_string(rst_info.to_max_win_days)).append(","); output_str.append(rst_info.mid_has_up ? "Y" : "N").append(","); output_str.append("\n"); rst_begin++; } //输出统计信息到字符串当中 output_str.append(res_map["100000CH00023"]/*上涨天数:*/).append(std::to_string(up_days_num)).append("\n"); output_str.append(res_map["100000CH00024"]/*下跌天数:*/).append(std::to_string(down_days_num)).append("\n"); output_str.append(res_map["100000CH00025"]/*中间历程上涨天数:*/).append(std::to_string(mid_up_days_num)).append("\n"); output_str.append(res_map["100000CH00026"]/*中间历程未上涨天数:*/).append(std::to_string(mid_down_days_num)).append("\n"); output_str.append(res_map["100000CH00028"]/*目标日最大盈利百分比*/).append(std::to_string(max_win_percent)).append("\n"); output_str.append(res_map["100000CH00027"]/*目标日最小盈利百分比*/).append(std::to_string(min_win_percent)).append("\n"); output_str.append(res_map["100000CH00029"]/*目标日最大损失百分比:*/).append(std::to_string(max_lose_percent)).append("\n"); output_str.append(res_map["100000CH00019"]/*中间最大盈利百分比*/).append(":").append(std::to_string(mid_max_win_percent)).append("\n"); output_str.append(res_map["100000CH00030"]/*中间最小盈利百分比*/).append(std::to_string(mid_min_win_percent)).append("\n"); output_str.append(res_map["100000CH00020"]/*中间最大损失百分比*/).append(":").append(std::to_string(mid_max_lose_percent)).append("\n"); output_str.append(res_map["100000CH00031"]/*平均最大盈利百分比*/).append(std::to_string(ave_max_win_percent)).append("\n"); output_str.append(res_map["100000CH00032"]/*平均目标日盈利百分比*/).append(std::to_string(ave_target_win_percent)).append("\n"); return output_str; } /** * 斜率分析,通过斜率来获取上涨下跌以及相关信息 */ float Calculator::slope_ana(std::list<stock_info>& info_list, std::list<turn_point>& turn_point_list, PriceFlag price, int ignore_days, int unignore_percent) { //统计数据 int small_wave_count = 0; //根据哪个价格来计算斜率 price_fun cal_price = get_price_fun(price); stock_info* temp_info; auto info_begin = info_list.rbegin(), info_end = info_list.rend(); //初始化 float un_ig_percent = unignore_percent / 100; turn_point temp_turn{}; temp_turn.start_point = &(*info_begin); info_begin++; temp_turn.origin_up = ((*info_begin).*cal_price)() > (temp_turn.start_point->*cal_price)(); turn_point_list.push_back(temp_turn); info_begin++; unsigned int turn_last_days = 0; while(info_begin != info_end) { temp_info = &(*info_begin); turn_point& turn_before = turn_point_list.back(); turn_last_days++; float cur_price = (temp_info->*cal_price)(); float turn_before_price = (turn_before.start_point->*cal_price)(); float slope = (cur_price - turn_before_price) / turn_last_days; float percent = (cur_price - turn_before_price) / turn_before_price; bool is_up = cur_price > turn_before_price; if(is_up && turn_before.origin_up) { info_begin++; continue; } else if((!is_up) && (!turn_before.origin_up)) { info_begin++; continue; } else if(turn_last_days >= ignore_days || percent >= un_ig_percent){ turn_point insert_point{}; insert_point.start_point = temp_info; insert_point.origin_up = is_up; insert_point.slope = slope; insert_point.percent = percent; insert_point.wave_days = turn_last_days; turn_point_list.push_back(insert_point); turn_last_days = 0; } info_begin++; } } std::string Calculator::limit_up_ana(std::list<stock_info>& info_list, int days, PriceFlag buy_price, PriceFlag sold_price) { struct buy_rst { stock_info* base_info = nullptr; //base_info当天最高价买入,然后@param days那一天以收盘价卖出收益率 float days_percent = 0; //base_info当天最高价买入,@param days天之间最高的收益率如何(收盘价计算收益率) float max_win_percent = 0; //base_info当天最高价买入,@param days天之间最高的损失率如何(收盘价计算收益率) float max_lost_percent = 0; //实现@param days天当中最大收益率,是在买入多少天后实现的?(非交易日不算入天数当中) int to_max_win_days = 0; //辅助上面的非交易日不算入天数当中而添加的变量 int lower_max_win_days = 0; //实现@param days天过程当汇总最大收益率的那天的基本信息 stock_info* mid_max_win_info = nullptr; //在历经@param days这些天当中,如能获利,则为true bool mid_has_up = false; //计量在base_info天买进的话,已经往后计算了多少天的收益 int cal_days_count= 0; //涨停之后的那一天开盘价是否就是最低价 bool is_begin_the_max = false; }; //统计信息 int total_days = 0; //总天数,可能有部分天不盈利也不损失 //@param days天的时候,如果获利,则此数加一 int up_days_num = 0; //@param days天的时候,如果损失,则此数加一 int down_days_num = 0; //在历经@param days这些天当中,如能获利,则此数加一,即中间历程可上涨天数 int mid_up_days_num = 0; //在历经@param days这些天当中,如果始终未获利(包含一直损失),则此数加一, int mid_down_days_num = 0; //下面三个为@param days天后那一天的数据,所有天的统计信息 float max_win_percent = 0; //最大的获利比例 float min_win_percent = 10000; //最小获利比例 float max_lose_percent = 0; //最大损失比例 //@param days天的过程当中最大收益率的平均值 float ave_max_win_percent = 0; //到达@param days天的时候,收益率的平均值是多少 float ave_target_win_percent = 0; //下面三个为@param days天之间的数据,所有天的统计信息 float mid_max_win_percent = 0; //最大的获利比例 float mid_min_win_percent = 10000; //最小获利比例 float mid_max_lose_percent = 0; //最大损失比例 price_fun buy_fun = get_price_fun(buy_price), sold_fun = get_price_fun(sold_price); auto list_begin = info_list.rbegin(), list_end = info_list.rend(); std::list<buy_rst> rst_list; std::list<buy_rst>::iterator rst_begin = rst_list.begin(), rst_end; //初始化rst_list stock_info* day_before_yesterday = list_begin != list_end ? &(*list_begin) : nullptr; list_begin++; stock_info* yesterday = list_begin != list_end ? &(*list_begin) : nullptr; list_begin++; stock_info* cur_day = nullptr; stock_info* before_days, *after_days, *buy_day, *sold_day; while(list_begin != list_end) { cur_day = &(*list_begin); //如果当天是涨停的话,>1.098是为了留点冗余空间 if(yesterday->get_end_price() / day_before_yesterday->get_end_price() > 1.098) { buy_rst insert_rst{}; insert_rst.base_info = cur_day; rst_list.push_back(insert_rst); if(rst_list.size() == 1) { rst_begin = rst_list.begin(); } } auto windows_p = rst_begin; rst_end = rst_list.end(); while(windows_p != rst_end) { buy_rst& rst_info = *windows_p; //如果是当天的话,当天不会和自己计算的 if(rst_info.base_info == cur_day) { break; } if(rst_info.cal_days_count >= days) { //永远不使rst_begin指向rst_list的末尾 auto temp_ite = rst_begin; if(++temp_ite != rst_end) { rst_begin++; } if(rst_info.cal_days_count == days) { buy_rst& target_buy_rst = (*rst_begin); float buy_price_val = (target_buy_rst.base_info->*buy_fun)(); float cur_sold_price_val = (cur_day->*sold_fun)(); float curr_win_percent = (cur_sold_price_val - buy_price_val) / buy_price_val; target_buy_rst.days_percent = curr_win_percent; max_win_percent = curr_win_percent > max_win_percent ? curr_win_percent : max_win_percent; max_lose_percent = max_lose_percent < curr_win_percent ? max_lose_percent : curr_win_percent; min_win_percent = curr_win_percent > 0 && curr_win_percent < min_win_percent ? curr_win_percent : min_win_percent; curr_win_percent > 0 ? up_days_num++ : 1; curr_win_percent < 0 ? down_days_num++ : 1; //统计最大收益率的平均值 ave_max_win_percent += rst_info.max_win_percent; //统计到达@param days天是收益率的平均值 ave_target_win_percent += rst_info.days_percent; rst_info.cal_days_count++; } } else { float buy_price_val = (rst_info.base_info->*buy_fun)(); float cur_sold_price_val = (cur_day->*sold_fun)(); float curr_win_percent = (cur_sold_price_val - buy_price_val) / buy_price_val; rst_info.max_win_percent = rst_info.max_win_percent > curr_win_percent ? rst_info.max_win_percent : curr_win_percent; if(rst_info.max_win_percent > curr_win_percent) { rst_info.lower_max_win_days++; } else { rst_info.to_max_win_days = rst_info.to_max_win_days + rst_info.lower_max_win_days + 1; rst_info.lower_max_win_days = 0; } rst_info.mid_max_win_info = curr_win_percent > mid_max_win_percent ? before_days : rst_info.mid_max_win_info; rst_info.max_lost_percent = rst_info.max_lost_percent > curr_win_percent ? curr_win_percent : rst_info.max_lost_percent; mid_max_win_percent = curr_win_percent > mid_max_win_percent ? curr_win_percent : mid_max_win_percent; mid_max_lose_percent = mid_max_lose_percent < curr_win_percent ? mid_max_lose_percent : curr_win_percent; mid_min_win_percent = curr_win_percent > 0 && curr_win_percent < mid_min_win_percent ? curr_win_percent : mid_min_win_percent; rst_info.mid_has_up = curr_win_percent > 0 || rst_info.mid_has_up; //判定涨停的后一天,开盘价是否就是最低价 boost::gregorian::date::duration_type diff = cur_day->get_date_info() - rst_info.base_info->get_date_info(); rst_info.is_begin_the_max = diff.days() == 1 && (cur_day->get_begin_price() - cur_day->get_min_price()) < 0.01; rst_info.cal_days_count++; } windows_p++; } day_before_yesterday = yesterday; yesterday = cur_day; list_begin++; } //收益率平均值方面的重新计算 ave_max_win_percent /= rst_list.size(); ave_target_win_percent /= rst_list.size(); //构建输出信息,csv格式 std::string output_str; //下面几个字段按照顺序分别是: //日期,编码,名称,除权开盘价,除权收盘价,除权最高价,除权最低价,目标日盈利百分比,中间最大盈利百分比,中间最大损失百分比 //中间最大盈利所需天数,中间是否盈利,涨停后一天开盘价是否最低价 output_str.append(res_map["100000CH00001"]).append(",").append(res_map["100000CH00002"]).append(","); output_str.append(res_map["100000CH00003"]).append(",").append(res_map["100000CH00004"]).append(","); output_str.append(res_map["100000CH00005"]).append(",").append(res_map["100000CH00006"]).append(","); output_str.append(res_map["100000CH00007"]).append(",").append(res_map["100000CH00018"]).append(","); output_str.append(res_map["100000CH00019"]).append(",").append(res_map["100000CH00020"]).append(","); output_str.append(res_map["100000CH00021"]).append(",").append(res_map["100000CH00022"]).append(","); output_str.append(res_map["100000CH00033"]).append(","); output_str.append("\n"); rst_begin = rst_list.begin(), rst_end = rst_list.end(); while(rst_begin != rst_end) { buy_rst& rst_info = (*rst_begin); //统计一下相关信息,@param days的中间历程当中是否上涨过 rst_info.mid_has_up ? mid_up_days_num++ : mid_down_days_num++; output_str.append(rst_info.base_info->get_date_info_str()).append(","); output_str.append(rst_info.base_info->get_stock_code()).append(","); output_str.append(rst_info.base_info->get_stock_name()).append(","); output_str.append(std::to_string(rst_info.base_info->get_begin_price())).append(","); output_str.append(std::to_string(rst_info.base_info->get_end_price())).append(","); output_str.append(std::to_string(rst_info.base_info->get_max_price())).append(","); output_str.append(std::to_string(rst_info.base_info->get_min_price())).append(","); output_str.append(std::to_string(rst_info.days_percent * 100)).append("%,"); output_str.append(std::to_string(rst_info.max_win_percent * 100)).append("%,"); output_str.append(std::to_string(rst_info.max_lost_percent * 100)).append("%,"); output_str.append(std::to_string(rst_info.to_max_win_days)).append(","); output_str.append(rst_info.mid_has_up ? "Y" : "N").append(","); output_str.append(rst_info.is_begin_the_max ? "Y" : "N").append(","); output_str.append("\n"); rst_begin++; } //输出统计信息到字符串当中 output_str.append(res_map["100000CH00023"]/*上涨天数:*/).append(std::to_string(up_days_num)).append("\n"); output_str.append(res_map["100000CH00024"]/*下跌天数:*/).append(std::to_string(down_days_num)).append("\n"); output_str.append(res_map["100000CH00025"]/*中间历程上涨天数:*/).append(std::to_string(mid_up_days_num)).append("\n"); output_str.append(res_map["100000CH00026"]/*中间历程未上涨天数:*/).append(std::to_string(mid_down_days_num)).append("\n"); output_str.append(res_map["100000CH00028"]/*目标日最大盈利百分比*/).append(std::to_string(max_win_percent)).append("\n"); output_str.append(res_map["100000CH00027"]/*目标日最小盈利百分比*/).append(std::to_string(min_win_percent)).append("\n"); output_str.append(res_map["100000CH00029"]/*目标日最大损失百分比:*/).append(std::to_string(max_lose_percent)).append("\n"); output_str.append(res_map["100000CH00019"]/*中间最大盈利百分比*/).append(":").append(std::to_string(mid_max_win_percent)).append("\n"); output_str.append(res_map["100000CH00030"]/*中间最小盈利百分比*/).append(std::to_string(mid_min_win_percent)).append("\n"); output_str.append(res_map["100000CH00020"]/*中间最大损失百分比*/).append(":").append(std::to_string(mid_max_lose_percent)).append("\n"); output_str.append(res_map["100000CH00031"]/*平均最大盈利百分比*/).append(std::to_string(ave_max_win_percent)).append("\n"); output_str.append(res_map["100000CH00032"]/*平均目标日盈利百分比*/).append(std::to_string(ave_target_win_percent)).append("\n"); return output_str; } /** * 计算移动均线,移动均线的数据存储到stock_info当中,为此重构了一下stock_info的类 * * @param info_list 输入的所有基本信息 */ void Calculator::calculate_ma(std::list<stock_info>& info_list) { auto l_be = info_list.rbegin(), l_end = info_list.rend(); stock_info* curr = nullptr; int ma_count[60] = {0}; std::list<stock_info>::iterator ma_be_val[60] = {info_list.begin()}; float ma_all_val[60] = {0}; while(l_be != l_end) { curr = &(*l_be); if(!curr->get_ma()) { curr->set_ma(new float[60]); } for(int i = 0;i < 60;i++) { if(ma_count[i] == i + 1) { ma_all_val[i] = ma_all_val[i] - ((*ma_be_val[i]).get_af_end_price()); (ma_be_val[i])++; ma_all_val[i] += curr->get_af_end_price(); curr->get_ma()[i] / (i + 1); } else { ma_count[i] = ma_count[i] + 1; } } l_be++; } }
true
5d64b4a904ba30722116c88411a5173e383e9bcc
C++
troublefrom2001/pip
/it_apple.cpp
UTF-8
1,785
2.53125
3
[]
no_license
#include"h.h" void it_apple(SDL_Renderer *renderer, int x, int y) { it_square(renderer, x+14, y+0 ,100, 50, 0); it_square(renderer, x+14, y+2 ,100, 50, 0); it_square(renderer, x+12, y+2 ,100, 50, 0); it_square(renderer, x+12, y+4 ,100, 50, 0); it_zz(renderer, x+8, y+6 ,4, 'R'); it_zz(renderer, x+4, y+8 ,8, 'R'); it_zz(renderer, x+2, y+10 ,10, 'R'); it_zz(renderer, x+2, y+12 ,10, 'R'); it_zz(renderer, x+0, y+14 ,12, 'R'); it_zz(renderer, x+0, y+16 ,12, 'R'); it_zz(renderer, x+0, y+18 ,12, 'R'); it_zz(renderer, x+0, y+20 ,12, 'R'); it_zz(renderer, x+2, y+22 ,10, 'R'); it_zz(renderer, x+2, y+24 ,10, 'R'); it_zz(renderer, x+4, y+26 ,8, 'R'); it_square(renderer, x+6, y+28 ,250, 50, 50); it_square(renderer, x+8, y+28 ,250, 50, 50); it_square(renderer, x+14, y+28 ,250, 50, 50); it_square(renderer, x+16, y+28 ,250, 50, 50); } #include"h.h" void it_zapple(SDL_Renderer *renderer, int x, int y) { it_square(renderer, x+14, y+0 ,0, 0, 0); it_square(renderer, x+14, y+2 ,0, 0, 0); it_square(renderer, x+12, y+2 ,0, 0, 0); it_square(renderer, x+12, y+4 ,0, 0, 0); it_zz(renderer, x+8, y+6 ,4, 'B'); it_zz(renderer, x+4, y+8 ,8, 'B'); it_zz(renderer, x+2, y+10 ,10, 'B'); it_zz(renderer, x+2, y+12 ,10, 'B'); it_zz(renderer, x+0, y+14 ,12, 'B'); it_zz(renderer, x+0, y+16 ,12, 'B'); it_zz(renderer, x+0, y+18 ,12, 'B'); it_zz(renderer, x+0, y+20 ,12, 'B'); it_zz(renderer, x+2, y+22 ,10, 'B'); it_zz(renderer, x+2, y+24 ,10, 'B'); it_zz(renderer, x+4, y+26 ,8, 'B'); it_square(renderer, x+6, y+28 ,0, 0, 0); it_square(renderer, x+8, y+28 ,0, 0, 0); it_square(renderer, x+14, y+28 ,0, 0,0); it_square(renderer, x+16, y+28 ,0, 0,0); }
true
ea08702a73d5b9f7b0dbca7fe9c67230393466dc
C++
ryan-duve/d2o_analysis
/d2o_equation_79_evaluator.cc
UTF-8
22,650
2.5625
3
[]
no_license
//This program attempts to solve equation 7.9 in Ward's Thesis (Wurtz 2010) //Works by altering one parameter at a time and finding best fit, then repeats over all of them to refine the answer //Chi squared test is based on Pearson's cumulative test (asymptotically approaches chi squared) //Number of free parameters is number of cells used minus number of parameters (12) //General format of uncertainties is that they include the number of normal hits and therefore must have the unaltered run subtracted, unless they have a d in front that signifies they are an absolute error //PROBLEM: FIX THE OUTPUT FILES, they keep overwriting and so they're always empty! //Temp. solution: only call the runs one at a time //a = 1/A = x1 //b = a1 = x2 //c = a2 = x3 //d = a3 = x4 //e = a4 = x5 //f = e2 = x6 //g = e3 = x7 //h = e4 = x8 //using graphfile, input has been verified for the following histograms: a, b, c, d, e, f, h, i, j, k, l, run149 //So, 'a' represents 0, 'b' represents 1, 'c' represents 2 and so forth. #include <iostream> #include <fstream> #include <math.h> #include <stdlib.h> #include "oct_2010_hit_data.h" #include "d2o_run_loader.h" #include "d2o_background_corrector.h" #include "d2o_globals.h" #include "d2o_graph.h" using namespace std; double chi_sq(double obs[88],double theo[88],double d_theo[88]); //for use with 88 cell histograms //note: when calling this function I use the uncertainty in the observed NOT the uncertainty in the theoretical double red_chi_sq(double obs[88],double theo[88],double d_theo[88],int free_param); //for use with 88 cell histograms double N_theo(int cell,double A,double a1,double a2,double a3,double a4,double e2,double e3,double e4,double c1,double c2,double d1,double d2,int short_target); double param_error(int param_pick,double A,double a1,double a2,double a3,double a4,double e2,double e3,double e4,double c1,double c2,double d1,double d2, int short_target); void param_picker(int param_pick, int short_target); //the workhorse for this file void param_test(int param_to_test, int short_target); void equation_79_evaluator(int run,int background_cor); void equation_79_evaluator(int run,int background_cor) { //output files ofstream logfile; logfile.open ("output_files/equation_79_evaluator_log.txt"); double step = 0.0001; //step size long picks = 15; //number of times it rechecks solution logfile << "Step size: " << step << "; number of rechecks: " << picks << endl; int num_combo = 10; //number of combinations wanted for output //switches: (1 is on, 0 is off) int check = 0; int neg_correct = 0; int short_target; //automatically set short_target switch if(run < 155 && run > 0) short_target = 0; else if (run == -1) short_target = 1; else short_target = 1; // a_j = N00 for jth detector // b_j = N01 for jth detector // c_j = N02 for jth detector // d_j = N03 for jth detector // e_j = N04 for jth detector // f_j = N22 for jth detector // g_j = N23 for jth detector // h_j = N24 for jth detector // i_j = N11 for jth detector // j_j = N12 for jth detector // k_j = N11' for jth detector // l_j = N12' for jth detector //runxxx[j] = (j + 1)th detector of run xxx //Note: all simulation data (i.e. a-l) are done with arm 1 up, any runs that do not have arm 1 up must be converted //Note: simulation gain was 3.5keV/Ch so ADC cut of 500 is the same as a cut of 1750 keVee //load run into n run_loader(run); double d_n_est[88]; //let's see what runs look like without the H2O background if (background_cor == 1) { d2o_background_corrector(run); } else cout << "Background correction disabled.\n"; //fitting algorithm //randomly picks a set of parameters from their domains, compares the chi squared value and then reduces the domain near the best solution for(long ii = 1;ii <= picks;ii++) { for(int ii = 0;ii < 12;ii++) { param_picker(ii,short_target); //update log file } logfile << "Best chi squared: " << best_chi_sq << "; best reduced chi squared: " << best_red_chi_sq << endl; logfile << "A = " << best_A << "\na1 = " << best_a1 << "\na2 = " << best_a2 << "\na3 = " << best_a3 << "\na4 = " << best_a4 << "\ne2 = " << best_e2 << "\ne3 = " << best_e3 << "\ne4 = " << best_e4 << "\nc1 = " << best_c1 << "\nc2 = " << best_c2 << "\nd1 = " << best_d1 << "\nd2 = " << best_d2 << endl; } cout << "Finished determining parameters, now determining errors...\n"; double A,a1,a2,a3,a4,e2,e3,e4,c1,c2,d1,d2; A = best_A; a1 = best_a1; a2 = best_a2; a3 = best_a3; a4 = best_a4; e2 = best_e2; e3 = best_e3; e4 = best_e4; c1 = best_c1; c2 = best_c2; d1 = best_d1; d2 = best_d2; param[0] = best_A; param[1] = best_a1; param[2] = best_a2; param[3] = best_a3; param[4] = best_a4; param[5] = best_e2; param[6] = best_e3; param[7] = best_e4; param[8] = best_c1; param[9] = best_c2; param[10] = best_d1; param[11] = best_d2; //compute errors in parameters for(int ii = 0;ii < 12;ii++) { d_param[ii] = param_error(ii,A,a1,a2,a3,a4,e2,e3,e4,c1,c2,d1,d2,short_target); } logfile << "Run: " << run << endl; logfile << "Threshold = " << threshold << endl; logfile << "Best chi squared: " << best_chi_sq << "; best reduced chi squared: " << best_red_chi_sq << endl; logfile << "A = " << param[0] << " +/- " << d_param[0] << ";\n"; logfile << "a1 = " << param[1] << " +/- " << d_param[1] << ";\n"; logfile << "a2 = " << param[2] << " +/- " << d_param[2] << ";\n"; logfile << "a3 = " << param[3] << " +/- " << d_param[3] << ";\n"; logfile << "a4 = " << param[4] << " +/- " << d_param[4] << ";\n"; logfile << "e2 = " << param[5] << " +/- " << d_param[5] << ";\n"; logfile << "e3 = " << param[6] << " +/- " << d_param[6] << ";\n"; logfile << "e4 = " << param[7] << " +/- " << d_param[7] << ";\n"; logfile << "c1 = " << param[8] << " +/- " << d_param[8] << ";\n"; logfile << "c2 = " << param[9] << " +/- " << d_param[9] << ";\n"; logfile << "d1 = " << param[10] << " +/- " << d_param[10] << ";\n"; logfile << "d2 = " << param[11] << " +/- " << d_param[11] << ";\n"; cout << "Run: " << run << endl; cout << "Threshold = " << threshold << endl; cout << "Best chi squared: " << best_chi_sq << "; best reduced chi squared: " << best_red_chi_sq << endl; cout << "A = " << param[0] << " +/- " << d_param[0] << ";\n"; cout << "a1 = " << param[1] << " +/- " << d_param[1] << ";\n"; cout << "a2 = " << param[2] << " +/- " << d_param[2] << ";\n"; cout << "a3 = " << param[3] << " +/- " << d_param[3] << ";\n"; cout << "a4 = " << param[4] << " +/- " << d_param[4] << ";\n"; cout << "e2 = " << param[5] << " +/- " << d_param[5] << ";\n"; cout << "e3 = " << param[6] << " +/- " << d_param[6] << ";\n"; cout << "e4 = " << param[7] << " +/- " << d_param[7] << ";\n"; cout << "c1 = " << param[8] << " +/- " << d_param[8] << ";\n"; cout << "c2 = " << param[9] << " +/- " << d_param[9] << ";\n"; cout << "d1 = " << param[10] << " +/- " << d_param[10] << ";\n"; cout << "d2 = " << param[11] << " +/- " << d_param[11] << ";\n"; cout << "Excel input (A a1 a2 a3 ... d1 d2 d_A d_a1 ... d_d1 d_d2: \n"; for(int ii = 0;ii < 12;ii++) { cout << param[ii] << " "; } for(int ii = 0;ii < 12;ii++) { cout << d_param[ii] << " "; } cout << "\n"; //verify errors logfile << "Verify the error in the parameters: " << endl; int cells_used = 0; double n_est[88]; //calculate predicted spectrum and reduced chi squared for(int ii = 0;ii < 88;ii++) { if(n[ii] < threshold) continue; //ignore empty cells if(ii > 79) //ignore last ring { n_est[ii] = -1; continue; } else { n_est[ii] = N_theo(ii,A,a1,a2,a3,a4,e2,e3,e4,c1,c2,d1,d2,short_target); } } cells_used = 0; logfile << "chi_sq(a1) = " << chi_sq(n,n_est,d_n) << endl; cout << "chi_sq(a1) = " << chi_sq(n,n_est,d_n) << endl; for(int ii = 0;ii < 88;ii++) { if(n[ii] < threshold) continue; //ignore empty cells if(ii > 79) //ignore last ring { n_est[ii] = -1; continue; } else { n_est[ii] = N_theo(ii,A,a1 + d_param[1],a2,a3,a4,e2,e3,e4,c1,c2,d1,d2,short_target); } } logfile << "chi_sq(a1+da1) = " << chi_sq(n,n_est,d_n) << endl; cout << "chi_sq(a1+da1) = " << chi_sq(n,n_est,d_n) << endl; cells_used = 0; equation_79_graph(param[0],param[1],param[2],param[3],param[4],param[5],param[6],param[7],param[8],param[9],param[10],param[11],0); equation_79_graph_error(run,background_cor,1); //****stopped updating here**** //check solution if(check == 1) { float ave_error = 0; for(int ii = 0;ii < 80;ii++) { if(n[ii] > 0) { n_est[ii] = N_theo(ii,A,a1,a2,a3,a4,e2,e3,e4,c1,c2,d1,d2,short_target); logfile << "Estimate for hits on detector " << ii + 1 << ": " << n_est[ii] << "; actual: " << n[ii] << "; Percent error: " << abs(1.0 - double(n_est[ii])/double(n[ii]))*100.0 << "%\n"; ave_error = ave_error + abs(((1.0 - double(n_est[ii])/double(n[ii]))/88.0)); } } logfile << "Average percent error: " << ave_error*100 << "%\n"; } //for(int dummy = 0; dummy < 88; dummy++) //{ //cout << float(dummy) + .5 << " " << n[dummy] << " " << long_st_dev[dummy] << endl; //} //reset globals best_A = 0; best_a1 = 0; best_a2 = 0; best_a3 = 0; best_a4 = 0; best_e2 = 0; best_e3 = 0; best_e4 = 0; best_c1 = 0; best_c2 = 0; best_d1 = 0; best_d2 = 0; best_chi_sq = 1e50; best_red_chi_sq = 1e50; //give ridiculously high initial values //close files logfile.close(); } double chi_sq(double obs[88],double theo[88],double d_obs[88]) //for use with 88 cell histograms { //note: when calling this function I use the uncertainty in the observed NOT the uncertainty in the theoretical double chi_sq = 0; double d_theo[88]; for(int ii = 0;ii < 88;ii++) { if(obs[ii] < threshold) continue; if(theo[ii] == -1) continue; d_theo[ii] = pow(theo[ii],0.5); //uncertainty is purely statistical chi_sq = chi_sq + (obs[ii] - theo[ii])*(obs[ii] - theo[ii])/((d_theo[ii]*d_theo[ii] + d_obs[ii]*d_obs[ii])); } return chi_sq; } double red_chi_sq(double obs[88],double theo[88],double d_obs[88],int free_param) //for use with 88 cell histograms { double red_chi_sq = 0; double d_theo[88]; for(int ii = 0;ii < 88;ii++) { if(obs[ii] < threshold) continue; if(theo[ii] == -1) continue; d_theo[ii] = pow(theo[ii],0.5); //uncertainty is purely statistical red_chi_sq = red_chi_sq + (obs[ii] - theo[ii])*(obs[ii] - theo[ii])/((d_theo[ii]*d_theo[ii] + d_obs[ii]*d_obs[ii])*double(free_param)); //cerr << "double(free_param)/2.0 = " << double(free_param)/2.0 << "; free_param = " << free_param << endl; } return red_chi_sq; } double N_theo(int cell,double A,double a1,double a2,double a3,double a4,double e2,double e3,double e4,double c1,double c2,double d1,double d2,int short_target) { double N_theo; //load in simulated data if (short_target == 1) { for(int ii = 0;ii < 88;ii++) { a[ii] = a_short[ii]; b[ii] = b_short[ii]; c[ii] = c_short[ii]; d[ii] = d_short[ii]; e[ii] = e_short[ii]; f[ii] = f_short[ii]; g[ii] = g_short[ii]; h[ii] = h_short[ii]; i[ii] = i_short[ii]; j[ii] = j_short[ii]; k[ii] = k_short[ii]; l[ii] = l_short[ii]; } } else { for(int ii = 0;ii < 88;ii++) { a[ii] = a_long[ii]; b[ii] = b_long[ii]; c[ii] = c_long[ii]; d[ii] = d_long[ii]; e[ii] = e_long[ii]; f[ii] = f_long[ii]; g[ii] = g_long[ii]; h[ii] = h_long[ii]; i[ii] = i_long[ii]; j[ii] = j_long[ii]; k[ii] = k_long[ii]; l[ii] = l_long[ii]; } } N_theo = A*((1 - a1 - a2 - a3 - a4 - 3*e2 - 6*e3 - 10*e4 - c1 - 1.5*c2 - d1 - 1.5*d2)*a[cell] + a1*b[cell] + a2*c[cell] + a3*d[cell] + a4*e[cell] + 3*e2*f[cell] + 6*e3*g[cell] + 10*e4*h[cell] + c1*i[cell] + 1.5*c2*j[cell] + d1*k[cell] + 1.5*d2*l[cell]); return N_theo; } void param_picker(int param_pick,int short_target) { //cout << "Param_picker has been triggered \n"; //debug line int cells_used = 0; double chi_sq_test = 0; double red_chi_sq_test = 0; double A,a1,a2,a3,a4,e2,e3,e4,c1,c2,d1,d2; A = best_A; a1 = best_a1; a2 = best_a2; a3 = best_a3; a4 = best_a4; e2 = best_e2; e3 = best_e3; e4 = best_e4; c1 = best_c1; c2 = best_c2; d1 = best_d1; d2 = best_d2; //these pointers will change the memory of the parameter being adjusted double * param; double * max_param; double * min_param; double * best_param; double step = 0.0001; //step size long picks = 15; //number of times it rechecks solution //load in simulated data if (short_target == 1) { for(int ii = 0;ii < 88;ii++) { a[ii] = a_short[ii]; b[ii] = b_short[ii]; c[ii] = c_short[ii]; d[ii] = d_short[ii]; e[ii] = e_short[ii]; f[ii] = f_short[ii]; g[ii] = g_short[ii]; h[ii] = h_short[ii]; i[ii] = i_short[ii]; j[ii] = j_short[ii]; k[ii] = k_short[ii]; l[ii] = l_short[ii]; } } else { for(int ii = 0;ii < 88;ii++) { a[ii] = a_long[ii]; b[ii] = b_long[ii]; c[ii] = c_long[ii]; d[ii] = d_long[ii]; e[ii] = e_long[ii]; f[ii] = f_long[ii]; g[ii] = g_long[ii]; h[ii] = h_long[ii]; i[ii] = i_long[ii]; j[ii] = j_long[ii]; k[ii] = k_long[ii]; l[ii] = l_long[ii]; } } //load in parameter to alter if (param_pick == 0) { param = &A; best_param = &best_A; max_param = &max_A; min_param = &min_A; } else if (param_pick == 1) { param = &a1; best_param = &best_a1; max_param = &max_a1; min_param = &min_a1; } else if (param_pick == 2) { param = &a2; best_param = &best_a2; max_param = &max_a2; min_param = &min_a2; } else if (param_pick == 3) { param = &a3; best_param = &best_a3; max_param = &max_a3; min_param = &min_a3; } else if (param_pick == 4) { param = &a4; best_param = &best_a4; max_param = &max_a4; min_param = &min_a4; } else if (param_pick == 5) { param = &e2; best_param = &best_e2; max_param = &max_e2; min_param = &min_e2; } else if (param_pick == 6) { param = &e3; best_param = &best_e3; max_param = &max_e3; min_param = &min_e3; } else if (param_pick == 7) { param = &e4; best_param = &best_e4; max_param = &max_e4; min_param = &min_e4; } else if (param_pick == 8) { param = &c1; best_param = &best_c1; max_param = &max_c1; min_param = &min_c1; } else if (param_pick == 9) { param = &c2; best_param = &best_c2; max_param = &max_c2; min_param = &min_c2; } else if (param_pick == 10) { param = &d1; best_param = &best_d1; max_param = &max_d1; min_param = &min_d1; } else if (param_pick == 11) { param = &d2; best_param = &best_d2; max_param = &max_d2; min_param = &min_d2; } else { cout << "ERROR: param out of range\n"; return; } *param = *min_param; while(*param <= *max_param) { cells_used = 0; //calculate predicted spectrum and reduced chi squared for(int ii = 0;ii < 88;ii++) { if(n[ii] < threshold) continue; //ignore empty cells if(ii > 79) //ignore last ring { n_est[ii] = -1; continue; } else { n_est[ii] = N_theo(ii,A,a1,a2,a3,a4,e2,e3,e4,c1,c2,d1,d2,short_target); cells_used++; } } //cout << "Cells used: " << cells_used << endl; //debug line chi_sq_test = chi_sq(n,n_est,d_n); cout << ""; //****DO NOT DELETE THIS LINE: THE COMPILER NEEDS THIS LINE TO MAKE SENSE OF THE CODE*** red_chi_sq_test = red_chi_sq(n,n_est,d_n,cells_used - 12); //cout << "Chi_sq = " << chi_sq(n,n_est,d_n) << endl; //debug line //cout << "Red_chi_sq = " << red_chi_sq(n,n_est,d_n,cells_used - 12) << endl; //debug line if (chi_sq_test < best_chi_sq) { *best_param = *param; best_chi_sq = chi_sq_test; best_red_chi_sq = red_chi_sq_test; //12 parameters //cout << "Storing new parameter: " << *best_param << endl; //debug line } *param = *param + step; //cout << "param = " << *param << endl; //debug line } //cout << "Best chi squared was: " << best_chi_sq << "; best reducing chi squared was: " << best_red_chi_sq << endl; return; } //returns the uncertainty in the specified parameter double param_error(int param_pick,double A,double a1,double a2,double a3,double a4,double e2,double e3,double e4,double c1,double c2,double d1,double d2,int short_target) { //cout << "Param_picker has been triggered \n"; //debug line //these pointers will change the memory of the parameter being adjusted double * param; double * max_param; double * min_param; double * best_param; double error = 0; double step = 0.0001; //step size long picks = 15; //number of times it rechecks solution //load in simulated data if (short_target == 1) { for(int ii = 0;ii < 88;ii++) { a[ii] = a_short[ii]; b[ii] = b_short[ii]; c[ii] = c_short[ii]; d[ii] = d_short[ii]; e[ii] = e_short[ii]; f[ii] = f_short[ii]; g[ii] = g_short[ii]; h[ii] = h_short[ii]; i[ii] = i_short[ii]; j[ii] = j_short[ii]; k[ii] = k_short[ii]; l[ii] = l_short[ii]; } } else { for(int ii = 0;ii < 88;ii++) { a[ii] = a_long[ii]; b[ii] = b_long[ii]; c[ii] = c_long[ii]; d[ii] = d_long[ii]; e[ii] = e_long[ii]; f[ii] = f_long[ii]; g[ii] = g_long[ii]; h[ii] = h_long[ii]; i[ii] = i_long[ii]; j[ii] = j_long[ii]; k[ii] = k_long[ii]; l[ii] = l_long[ii]; } } //load in parameter to alter if (param_pick == 0) { param = &A; } else if (param_pick == 1) { param = &a1; } else if (param_pick == 2) { param = &a2; } else if (param_pick == 3) { param = &a3; } else if (param_pick == 4) { param = &a4; } else if (param_pick == 5) { param = &e2; } else if (param_pick == 6) { param = &e3; } else if (param_pick == 7) { param = &e4; } else if (param_pick == 8) { param = &c1; } else if (param_pick == 9) { param = &c2; } else if (param_pick == 10) { param = &d1; } else if (param_pick == 11) { param = &d2; } else { cout << "ERROR: param out of range\n"; return 0; } int cells_used; for(int ii = 0;ii < 88;ii++) { if(n[ii] < threshold) continue; //ignore empty cells if(ii > 79) //ignore last ring { n_est[ii] = -1; continue; } else { n_est[ii] = N_theo(ii,A,a1,a2,a3,a4,e2,e3,e4,c1,c2,d1,d2,short_target); //cout << "n_est[" << ii << "] = " << n_est[ii] << endl; //debug line } } double chi_sq_test = chi_sq(n,n_est,d_n); double best_chi_sq_test = chi_sq(n,n_est,d_n); while(chi_sq_test < best_chi_sq + 1 && chi_sq_test > best_chi_sq - 1) { cells_used = 0; if (chi_sq_test > 1000) //sanity check { cerr << "ERROR: sanity check failed (chi_sq > 1000), quitting param error routine.\n"; return 0; } //calculate predicted spectrum and reduced chi squared for(int ii = 0;ii < 88;ii++) { if(n[ii] < threshold) continue; //ignore empty cells if(ii > 79) //ignore last ring { n_est[ii] = -1; continue; } else { n_est[ii] = N_theo(ii,A,a1,a2,a3,a4,e2,e3,e4,c1,c2,d1,d2,short_target); //cout << "n_est[" << ii << "] = " << n_est[ii] << endl; //debug line cells_used++; } } chi_sq_test = chi_sq(n,n_est,d_n); cout << ""; //****DO NOT DELETE THIS LINE: THE COMPILER NEEDS THIS LINE TO MAKE SENSE OF THE CODE*** *param = *param + step/10.0; error = error + step/10.0; } return error; } void param_test(int param_to_test, int short_target) { double step = 0.0001; //step size long picks = 15; //number of times it rechecks solution //load in simulated data if (short_target == 1) { for(int ii = 0;ii < 88;ii++) { a[ii] = a_short[ii]; b[ii] = b_short[ii]; c[ii] = c_short[ii]; d[ii] = d_short[ii]; e[ii] = e_short[ii]; f[ii] = f_short[ii]; g[ii] = g_short[ii]; h[ii] = h_short[ii]; i[ii] = i_short[ii]; j[ii] = j_short[ii]; k[ii] = k_short[ii]; l[ii] = l_short[ii]; } } else { for(int ii = 0;ii < 88;ii++) { a[ii] = a_long[ii]; b[ii] = b_long[ii]; c[ii] = c_long[ii]; d[ii] = d_long[ii]; e[ii] = e_long[ii]; f[ii] = f_long[ii]; g[ii] = g_long[ii]; h[ii] = h_long[ii]; i[ii] = i_long[ii]; j[ii] = j_long[ii]; k[ii] = k_long[ii]; l[ii] = l_long[ii]; } cout << "Testing long target runs" << endl; } //load in parameter to test if (param_to_test == 0) { cout << "ERROR: A is not testable.\n"; return; } else if (param_to_test == 1) { for(int ii = 0;ii < 88;ii++) { n[ii] = b[ii]; d_n[ii] = pow(b[ii],0.5); } } else if (param_to_test == 2) { for(int ii = 0;ii < 88;ii++) { n[ii] = c[ii]; d_n[ii] = pow(c[ii],0.5); } } else if (param_to_test == 3) { for(int ii = 0;ii < 88;ii++) { n[ii] = d[ii]; d_n[ii] = pow(d[ii],0.5); } } else if (param_to_test == 4) { for(int ii = 0;ii < 88;ii++) { n[ii] = e[ii]; d_n[ii] = pow(e[ii],0.5); } } else if (param_to_test == 5) { for(int ii = 0;ii < 88;ii++) { n[ii] = f[ii]; d_n[ii] = pow(f[ii],0.5); } } else if (param_to_test == 6) { for(int ii = 0;ii < 88;ii++) { n[ii] = g[ii]; d_n[ii] = pow(g[ii],0.5); } } else if (param_to_test == 7) { for(int ii = 0;ii < 88;ii++) { n[ii] = h[ii]; d_n[ii] = pow(h[ii],0.5); } } else if (param_to_test == 8) { for(int ii = 0;ii < 88;ii++) { n[ii] = i[ii]; d_n[ii] = pow(i[ii],0.5); } } else if (param_to_test == 9) { for(int ii = 0;ii < 88;ii++) { n[ii] = j[ii]; d_n[ii] = pow(j[ii],0.5); } } else if (param_to_test == 10) { for(int ii = 0;ii < 88;ii++) { n[ii] = k[ii]; d_n[ii] = pow(k[ii],0.5); } } else if (param_to_test == 11) { for(int ii = 0;ii < 88;ii++) { n[ii] = l[ii]; d_n[ii] = pow(l[ii],0.5); } } else { cout << "ERROR: param out of range\n"; return; } for(long jj = 1;jj <= picks;jj++) { for(int ii = 0;ii < 12;ii++) { if(ii == param_to_test) continue; param_picker(ii,short_target); } } cout << "For parameter " << param_to_test << endl; cout << "Best chi squared: " << best_chi_sq << "; best reduced chi squared: " << best_red_chi_sq << endl; cout << "A = " << best_A << "\na1 = " << best_a1 << "\na2 " << best_a2 << "\na3 " << best_a3 << "\na4 " << best_a4 << "\ne2 " << best_e2 << "\ne3 " << best_e3 << "\ne4 " << best_e4 << "\nc1 " << best_c1 << "\nc2 " << best_c2 << "\nd1 " << best_d1 << "\nd2 " << best_d2 << endl; //reset globals best_A = 0; best_a1 = 0; best_a2 = 0; best_a3 = 0; best_a4 = 0; best_e2 = 0; best_e3 = 0; best_e4 = 0; best_c1 = 0; best_c2 = 0; best_d1 = 0; best_d2 = 0; best_chi_sq = 1e50; best_red_chi_sq = 1e50; //give ridiculously high initial values return; }
true
4637cce0f76477971bf8d6cb6481d63612fbac90
C++
fireword/fury3d
/engine/Fury/Singleton.h
UTF-8
1,231
3.421875
3
[ "MIT" ]
permissive
#ifndef _FURY_SINGLETON_H_ #define _FURY_SINGLETON_H_ #include <memory> #include <iostream> #include "Macros.h" namespace fury { template<class TargetType, class... Args> class Singleton { protected: static std::shared_ptr<TargetType> m_Instance; public: // this returns reference to current instance. // so you can call Instance().reset() to destory static instance. inline static std::shared_ptr<TargetType> &Instance() { ASSERT_MSG(m_Instance, "Singleton instance doesn't exist!"); return m_Instance; } // make sure your singleton initializes later than log singleton. inline static std::shared_ptr<TargetType> &Initialize(Args&&... args) { ASSERT_MSG(!m_Instance, "Singleton instance already exist!"); m_Instance = std::make_shared<TargetType>(std::forward<Args>(args)...); return m_Instance; } // don't do logs in singleton's destructor // because when destructing, Log's instance might be destoried already. virtual ~Singleton() { m_Instance = nullptr; } }; template<class TargetType, class... Args> std::shared_ptr<TargetType> Singleton<TargetType, Args...>::m_Instance = nullptr; } #endif // _FURY_SINGLETON_H_
true
c29d652a75a685dfe0aafa6ab38b01e1d81efb59
C++
saltandlight/SolveProblem
/20190905/circularqueue.cpp
UHC
1,435
3.96875
4
[]
no_license
//ť ϱ (Queue) // Q.create(y) // Q.push(y) // Q.pop() // Q.front() // Q.size() #include <stdio.h> const int MAX = 10; struct Queue{ // 0 1 2 3 4 5 6 7 // data 0 0 0 0 0 0 0 0 // f // r int data[MAX]; int f, r; int capacity; int numElement; void create(int y){ capacity=y; f=0; r=0; numElement=0; } void push(int y){ if(numElement >= capacity){ printf("Queue overflow\n"); }else{ data[r] = y; r=(r+1) % MAX; numElement++; } } void pop(){ if(numElement <= 0){ printf("Queue underflow\n"); } else{ data[f]=0; f=(f+1) % MAX; numElement--; } } int front(){ //ť տ ִ ȯ //, ȯ ٸ -1 ݹȯ if(numElement <= 0){ return -1; }else{ return data[f]; } } int size(){ return numElement; } }; int main() { Queue q1; q1.create(4); for(int i=0;i<10000;i++){ q1.push(i); q1.push(i+1); q1.push(i+2); q1.push(i+3); q1.pop(); q1.pop(); q1.pop(); q1.pop(); } q1.push(1); q1.push(2); printf("%d\n", q1.front()); //1 q1.pop(); printf("%d\n", q1.front()); //2 return 0; }
true
520dadfe98d248f0fdbbae6f9a2ae9663ebbda50
C++
dtbinh/gobot
/src/lifeFile.cpp
UTF-8
1,666
3.078125
3
[ "MIT" ]
permissive
#include "lifeFile.h" #include <cstdio> bool writeLifeFile(std::map<Block*, bool>& lifeMap, const char* filename) { FILE* f = fopen(filename, "wb"); if(!f) { return false; } int numberOfBlocks = lifeMap.size(); if(fwrite(&numberOfBlocks, sizeof(int), 1, f) != 1) { fclose(f); return false; } std::map<Block*, bool>::iterator itt = lifeMap.begin(); std::map<Block*, bool>::iterator end = lifeMap.end(); for( ; itt != end; ++itt) { BoardLocation location = *itt->first->locationsBegin(); if(fwrite(&location.x, sizeof(int), 1, f) != 1 || fwrite(&location.y, sizeof(int), 1, f) != 1 || fwrite(&itt->second, sizeof(bool), 1, f) != 1) { fclose(f); return false; } } fclose(f); return true; } bool readLifeFile(std::map<BoardLocation, bool>& lifeMap, const char* filename) { FILE* f = fopen(filename, "rb"); if(!f) { return false; } int numberOfBlocks = lifeMap.size(); if(fread(&numberOfBlocks, sizeof(int), 1, f) != 1) { fclose(f); return false; } for(int i = 0; i < numberOfBlocks; ++i) { BoardLocation location(0, 0); bool alive; if(fread(&location.x, sizeof(int), 1, f) != 1 || fread(&location.y, sizeof(int), 1, f) != 1 || fread(&alive, sizeof(bool), 1, f) != 1) { fclose(f); return false; } std::pair<BoardLocation, bool> mapping(location, alive); lifeMap.insert(mapping); } fclose(f); return true; }
true
971c114eef71dc1d18af25a346913263ac061107
C++
roshal/cpp
/source/trash-common/max.cpp
UTF-8
288
2.71875
3
[]
no_license
#include <iostream> #include "./max" int main() { setlocale(LC_ALL, ""); std::cout << "введите два числа" << std::endl; double a, b; std::cin >> a >> b; std::cout << "наибольшее число" << std::endl; std::cout << max(a, b) << std::endl; return 0; }
true
e96622a7cbbe67cc4e178035a93979b489a1b1fb
C++
AkiraHero/OpenRoadEd
/src/Qt/SettingsWidgets/SettingsLaneSection.h
UTF-8
1,314
2.609375
3
[]
no_license
#ifndef SETTINGSLANESECTION_H #define SETTINGSLANESECTION_H #include "../QtHeader.h" #include "../../OpenDrive/Lane.h" /** * Class that holds all the properties for the LANE_SECTION record * */ class SettingsLaneSection : public QWidget { Q_OBJECT public: /** * Initializes the properties panel and the UI elements */ SettingsLaneSection(QWidget *parent = 0); /** * Loads the data for a given record * * @param laneSection Lane section record whose properties are to be loaded * @param minS Minimum "S" property for this record * @param maxS Maximum "S" property for this record * @param first Set to true if it's the first lane section on the road */ void LoadData(LaneSection *laneSection, double minS, double maxS, bool first); private: /** * Lane section whose properties are to be displayed */ LaneSection *mLaneSection; /** * Interface widgets */ QDoubleSpinBox *mS; public slots: /** * Methods called when properties change */ void SChanged(double value); signals: /** * Signal emitted when critical road items are changed * that require that the road to be redrawn * * @param recalculateRoad Set to true if geometry records have to be recalculated (usualy true for this record) */ void RoadLaneSectionChanged(bool recalculateRoad); }; #endif
true
10a554a8b5be409cc5abf3f0907030d398d9d566
C++
mikhaputri/Review-Chapter-4
/8.cpp
UTF-8
1,069
3.453125
3
[]
no_license
// // 8.cpp // REVIEW BAGUS // // Created by Mikha Yupikha on 16/10/2016. // Copyright © 2016 Mikha Yupikha. All rights reserved. // #include <iostream> using namespace std; int main() { string colour1, colour2; cout<<"Please enter two primary colours (red, blue or yellow): "; cin>>colour1>>colour2; if (colour1=="red" && colour2=="blue") cout<<"The mix of that two colour is purple."<<endl; else if (colour1=="blue" && colour2=="red") cout<<"The mix of that two colour is purple."<<endl; else if (colour1=="red" && colour2=="yellow") cout<<"The mix of that two colour is orange."<<endl; else if ( colour1=="yellow" && colour2=="red") cout<<"The colour of that two colours is orange."<<endl; else if (colour1=="blue" && colour2=="yellow") cout<<"The mix of that two colours is green."<<endl; else if ( colour1=="yellow" && colour2=="blue") cout<<"The mix of that two colours is green." <<endl; else cout<<"That are not primary colour."<<endl; return 0; }
true
aba29368b534ac8f1113c4b32e1b5bf1c58a5253
C++
UniStuttgart-VISUS/Magic-Mouse-Pad
/mmpdcli/include/MagicMousePad/tokenise.inl
ISO-8859-1
2,288
2.796875
3
[]
no_license
// <copyright file="tokenise.cpp" company="Visualisierungsinstitut der Universitt Stuttgart"> // Copyright 2018 - 2020 Visualisierungsinstitut der Universitt Stuttgart. Alle Rechte vorbehalten. // </copyright> // <author>Christoph Mller</author> /* * MagicMousePad::Tokenise */ template<class C, class P> std::vector<std::basic_string<C>> MagicMousePad::Tokenise( const std::basic_string<C> &str, const P &isDelim, const bool omitEmpty) { typedef typename std::decay<decltype(str)>::type StringType; auto s = str.data(); std::vector<StringType> retval; do { auto begin = s; while ((*s != 0) && !isDelim(*s)) { ++s; } if (!omitEmpty || ((s - begin) > 0)) { retval.emplace_back(begin, s); } } while (*s++ != 0); return retval; } /* * MagicMousePad::Tokenise */ template<class C, class I> std::vector<std::basic_string<C>> MagicMousePad::Tokenise( const std::basic_string<C>& str, I beginDelim, I endDelim, const bool omitEmpty) { return Tokenise(str, [beginDelim, endDelim](const C c) { for (auto it = beginDelim; (it != endDelim); ++it) { if (*it == c) { return true; } } return false; }); } /* * MagicMousePad::Tokenise */ template<class C> std::vector<std::basic_string<C>> MagicMousePad::Tokenise( const std::basic_string<C>& str, const C delim, const bool omitEmpty) { return Tokenise(str, [delim](const C c) { return (c == delim); }); } /* * MagicMousePad::Tokenise */ template<class C> std::vector<std::basic_string<C>> MagicMousePad::Tokenise( const std::basic_string<C>& str, const std::basic_string<C>& delim, const bool omitEmpty) { typedef typename std::decay<decltype(str)>::type StringType; std::vector<StringType> retval; auto cur = static_cast<typename StringType::size_type>(0); while (cur != StringType::npos) { auto next = str.find(delim, cur); if (!omitEmpty || (cur != next)) { retval.emplace_back(str.substr(cur, next - cur)); } if (next != StringType::npos) { next += delim.size(); } cur = next; } return retval; }
true
46824096573dec87694ace834481f20a90f74f16
C++
wichza18/BudgetGUI
/BudgetGUI/User.cpp
UTF-8
1,696
3.3125
3
[]
no_license
#include "User.h" User::~User() { delete table; } //default constructor User::User() { table = new UserTable; table->setCurrentID(USER_CURRENT_ID, table->getTableName()); setID(USER_CURRENT_ID); Budget budget; username = "test"; password = "test"; } //full argument constructor User::User(std::string username, std::string password, Budget& budget, UserTable* t) { table = t; table->setCurrentID(USER_CURRENT_ID, table->getTableName()); setID(USER_CURRENT_ID); setUsername(username); setPassword(password); setBudget(budget); } User::User(int id, std::string username, std::string password, double totalLimit, double totalSpent, UserTable* t) { table = t; setID(id); setUsername(username); setPassword(password); Budget budget(totalLimit, totalSpent); } //getters std::string User::getUsername() const { return username; } std::string User::getPassword() const { return password; } Budget& User::getBudget() { return budget; } //setters void User::setBudget(Budget& budget) { this->budget = budget; } void User::setPassword(std::string& password) { this->password = password; } void User::setUsername(std::string& username) { this->username = username; } //helpers bool User::login(const std::string& username, const std::string& password) { bool isSuccessfulLogin = false; if (this->getUsername() == username && this->getPassword() == password) { isSuccessfulLogin = true; } return isSuccessfulLogin; } void User::setID(int id) { if (id > 0) { this->id = id; } else { throw "ID must be greater than 0"; } } int User::getID() const { return id; }
true
f21a43a2f085f723813ab7d8f9f6405c9d44456e
C++
EzzatQ/Data-Structures-HW2
/Data Structures HW2/RH.hpp
UTF-8
7,264
3.46875
3
[]
no_license
// // Linked List.hpp // Data Structures HW2 // // Created by Ezzat Qupty on 05/05/2019. // Copyright © 2019 Ezzat Qupty. All rights reserved. // #ifndef Linked_List_hpp #define Linked_List_hpp #include "Exceptions.hpp" namespace DataStructures{ ////////////////////////////////////////////////////////////////////// template<class D> class LLnode{ D* data; LLnode* prev; LLnode* next; public: LLnode(D& d): prev(nullptr), next(nullptr){ data = new D(d); } ~LLnode(){ delete data; } LLnode(LLnode& n){}; LLnode& operator=(LLnode& n); void setPrev(LLnode* p){ prev = p; } void setNext(LLnode* n){ next = n; } LLnode* getPrev(){ return prev; } LLnode* getNext(){ return next; } D* getData(){ return data; } }; ////////////////////////////////////////////////////////////////////// class roomBook{ int id; bool booked; public: roomBook(int id):id(id), booked(false){} roomBook(int id, bool booked):id(id), booked(booked){} void setId(int newId){ id = newId; } void setBooked(bool newBooked){ booked = newBooked; } int getId(){ return id; } bool getBooked(){ return booked; } }; ////////////////////////////////////////////////////////////////////// class RH{ int lectures; int hours; int rooms; int* hoursCount; int* roomsCount; LLnode<roomBook> ** freeRooms; LLnode<roomBook> *** roomsAndHours; public: RH(int hours, int rooms):hours(hours),rooms(rooms){ if(!(hours > 0 and rooms > 0)) { throw IllegalInitialization(); } lectures = 0; hoursCount = new (std::nothrow) int[hours+1]; if(!hoursCount) throw OutOfMemory(); roomsCount = new (std::nothrow) int[rooms+1]; if(!roomsCount){ delete[] hoursCount; throw OutOfMemory(); } for (int i = 0; i < hours+1; i++) { hoursCount[i] = 0; } for (int j = 0; j < rooms+1; j++) { roomsCount[j] = 0; } roomsAndHours = new LLnode<roomBook> **[hours]; for(int a = 0; a < hours;a++) roomsAndHours[a] = new LLnode<roomBook> * [rooms]; freeRooms = new LLnode<roomBook>* [hours]; roomBook first = roomBook(0); for (int i = 0; i < hours; i++) { freeRooms[i] = new LLnode<roomBook>(first); roomsAndHours[i][0] = freeRooms[i]; LLnode<roomBook>* parent = freeRooms[i]; parent->setPrev(nullptr); for (int j = 1 ; j < rooms; j++) { roomBook second = roomBook(j); LLnode<roomBook>* newNode = new LLnode<roomBook>(second); roomsAndHours[i][j] = newNode; parent->setNext(newNode); newNode->setPrev(parent); parent=newNode; } parent->setNext(nullptr); } } int getHours(){ return hours; } int getRooms(){ return rooms; } LLnode<roomBook> *** getRoomsAndHours(){return roomsAndHours;} bool isBooked(int hour, int room){ return roomsAndHours[hour][room]->getData()->getBooked(); } int getCourseAt(int hour, int room){ if(hour < 0 || hour > hours-1 || room < 0 || room > rooms-1) throw IllegalInitialization(); if(isBooked(hour, room)) return roomsAndHours[hour][room]->getData()->getId(); else return -1; } float getEfficiency(){ if(lectures>0) return (float)lectures/(float)(hoursCount[hours]*rooms); return -1; } void bookLecture(int hour, int room, int courseId){ if(hour > hours-1 || room > rooms -1) throw IllegalInitialization(); if(!roomsAndHours[hour][room]->getData()->getBooked()){ lectures++; hoursCount[hour]++; roomsCount[room]++; if(hoursCount[hour]==1) hoursCount[hours]++; if(roomsCount[room]==1) roomsCount[rooms]++; LLnode<roomBook>* current = roomsAndHours[hour][room]; LLnode<roomBook>* prevNode = current->getPrev(); LLnode<roomBook>* nextNode = current->getNext(); if(prevNode) prevNode->setNext(nextNode); else{ freeRooms[hour] = nextNode; } if(nextNode) nextNode->setPrev(prevNode); current->setPrev(nullptr); current->setNext(nullptr); current->getData()->setId(courseId); current->getData()->setBooked(true); }else throw AlreadyExists(); } void removeLecture(int hour, int room){ if(roomsAndHours[hour][room]->getData()->getBooked()){ lectures--; hoursCount[hour]--; roomsCount[room]--; if(hoursCount[hour]==0) hoursCount[hours]--; if(roomsCount[room]==0) roomsCount[rooms]--; LLnode<roomBook>* current = roomsAndHours[hour][room]; LLnode<roomBook>* head =freeRooms[hour]; current->setNext(head); if(head) head->setPrev(current); freeRooms[hour] = current; current->getData()->setId(room); current->getData()->setBooked(false); }else throw DoesNotExist(); } // returns the free rooms at the given hour void getFreeRoomsAtHour(int hour, int **rooms, int* numOfRooms){ if(hour < 0 || hour > hours-1 || !rooms || !numOfRooms) throw IllegalInitialization(); int counter = 0; LLnode<roomBook> * itr = freeRooms[hour]; while(itr && !itr->getData()->getBooked()){ counter++; itr = itr->getNext(); } if(counter == 0) throw DoesNotExist(); *numOfRooms = counter; *rooms =(int*)malloc(sizeof(int) * (*numOfRooms)); itr = freeRooms[hour]; for(int i=0; i < (*numOfRooms);i++){ (*rooms)[i] = (itr->getData()->getId()); itr = itr->getNext(); } } ~RH(){ for (int i = 0; i < hours; i++) { LLnode<roomBook>** current = roomsAndHours[i]; for (int j = 0 ; j < rooms; j++) { delete current[j]; } } delete[] freeRooms; for(int a = 0; a < hours;a++) delete[] roomsAndHours[a]; delete[] roomsAndHours; delete[] hoursCount; delete[] roomsCount; } }; } #endif /* Linked_List_hpp */
true
1125a1150be21a26ed4e75f235546b2800519cc8
C++
brittanymunyeshuli/Cpp1111_1202_Projects
/1202FinalProject/1202FinalProject/StateStats.cpp
UTF-8
1,817
3.515625
4
[]
no_license
#include "StateStats.h" #include <iostream> #include <iomanip> StateStats::StateStats() { string stateName = ""; int confirmed = 0; int recovered = 0; int dead = 0; double deathRate = 0.0; double recoveryRate = 0.0; } StateStats::StateStats(string stateNameIn, int confirmedIn, int recoveredIn, int deadIn) { stateName = stateNameIn; confirmed = confirmedIn; recovered = recoveredIn; dead = deadIn; } // State Name void StateStats::setStateName(string stateNameIn) { stateName = stateNameIn; } string StateStats::getStateName() { return stateName; } // Confirmed Cases void StateStats::setConfirmed(int confirmedIn) { confirmed = confirmedIn; } int StateStats::getConfirmed() { return confirmed; } // Recovered void StateStats::setRecovered(int recoveredIn) { recovered = recoveredIn; } int StateStats::getRecovered() { return recovered; } // Deaths void StateStats::setDeaths(int deadIn) { dead = deadIn; } int StateStats::getDead() { return dead; } // Death Rate double StateStats::calcDeathRate() { deathRate = 100 * (double(dead) / confirmed); return deathRate; } // Recovery Rate double StateStats::calcRecoveryRate() { recoveryRate = 100 * (double(recovered) / confirmed); return recoveryRate; } // Display State Stats void StateStats::displayStats() { cout << "***********************************" << endl; cout << " DATA FOR: " << getStateName() << endl; cout << " Confirmed: " << getConfirmed() << endl; cout << " Recovered: " << getRecovered() << endl; cout << " Deaths: " << getDead() << endl; cout << endl; cout << " Death Rate: " << setprecision(2) << fixed << calcDeathRate() << "%" << endl; cout << " Recovery Rate: " << setprecision(2) << fixed << calcRecoveryRate() << "%" << endl; } StateStats::~StateStats() { }
true
9401dcad716215eaa6f6c89e35980ef23f92301b
C++
quantster/ComputationalFinance
/hw3/LEcuyer.cpp
UTF-8
1,250
2.703125
3
[]
no_license
#include "LEcuyer.h" #include <iostream> using namespace std; MultipleRecursiveGenerator::MultipleRecursiveGenerator( unsigned long _m, unsigned long _a1, unsigned long _a2, unsigned long _a3, long _seed1, long _seed2, long _seed3) : m(_m), a1(_a1), a2(_a2), a3(_a3), seed1(_seed1), seed2(_seed2), seed3(_seed3) { } long MultipleRecursiveGenerator::GetOneRandomInteger() { long random = (a1 * seed3 + a2 * seed2 + a3 * seed1) % m; seed1 = seed2; seed2 = seed3; seed3 = random; return random; } RandomLEcuyer::RandomLEcuyer(unsigned long Dimensionality) : RandomRand(Dimensionality) { mrg1 = new MultipleRecursiveGenerator(2147483647, 0, 63308, -183326, 1, 2, 3); mrg2 = new MultipleRecursiveGenerator(2145483479, 86098, 0, -539608, 5, 7, 11); } RandomLEcuyer::~RandomLEcuyer() { delete mrg1; delete mrg2; } double RandomLEcuyer::GetOneUniform() { long random1 = mrg1->GetOneRandomInteger(); long random2 = mrg2->GetOneRandomInteger(); long random = (random1 - random2) % mrg1->M(); return random / double(mrg1->M()); } void RandomLEcuyer::GetUniforms(MJArray& variates) { for (unsigned long j=0; j < GetDimensionality(); j++) variates[j] = GetOneUniform(); }
true