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
8f4936a6a0a60798ce58f97f0be69feff46565ff
C++
Aaryankamboj/Data-Structures-and-algorithms
/imheritance_question.cpp
UTF-8
1,778
4.03125
4
[]
no_license
#include <iostream> #include <cmath> #include <math.h> using namespace std; class SimpleCalculator { protected: int num1, num2; char choice; public: void set_numbers(int a, int b, char sym) { num1 = a; num2 = b; choice = sym; } void selection(int, int, char); }; void SimpleCalculator::selection(int a, int b, char choice) { switch (choice) { case '+': cout << a + b; break; case '-': cout << a - b; break; case '*': cout << a * b; break; case '/': cout << a / b; break; } } class ComplexCalculator { protected: int cnum1, cnum2, num; char C_choice; public: void set_cnums(int a, int b, char sym) { cnum1 = a; cnum2 = b; C_choice = sym; } void C_selection(int, int, char); }; void ComplexCalculator::C_selection(int cnum1, int cnum2, char C_choice) { switch (C_choice) { case 's': cout << "Choose the number whose sin theta you want to calculate : "; cin >> num; if (num == cnum1) { cnum1 = cnum1 * (3.14 / 2*3.14); cout << sin(cnum1) << endl; } else { acos(cnum2); cout << sin(cnum2) << endl; } break; case 'c': cout << "Choose the number whose cos theta you want to calculate : "; cin >> num; if (num == cnum1) cout << cos(cnum1) << endl; else cout << cos(cnum2) << endl; break; } } class hybrid : public SimpleCalculator, public ComplexCalculator { cout << "Hello World"; }; int main() { hybrid h1; // h1.selection(10,20,'+'); h1.C_selection(10, 90, 'c'); }
true
55bee3e7f8621b32fae0f61fbbb5d4b047ce94ee
C++
mayonaiys/run_Qt
/src/main.cpp
UTF-8
1,127
2.65625
3
[ "MIT" ]
permissive
#include <QApplication> #include "Window.h" int main(int argc, char **argv) { QApplication game(argc,argv); //Création du programme //Ajout d'une police personnalisée pour le jeu QFontDatabase::addApplicationFont("../fonts/Joystick-5KjV.ttf"); //Ajout de la police QFont font = QFont("Joystick",50); //Création de la police QApplication::setFont(font); //Attribution de la police au programme //Ajout d'un splash au démarrage QSplashScreen* splash = new QSplashScreen(); //Création du splash splash->setWindowFlags(Qt::FramelessWindowHint); //Suppression des contours de la fenêtre QPixmap pixmap("../img/splash/splash.png"); splash->setPixmap(pixmap); //Ajout d'un background au splash splash->resize(580,361); //Modification de la taille du splash splash->show(); //Affichage du splash //Création fenêtre principale Window window; QTimer::singleShot(2000,splash,SLOT(close())); //Au bout de 2 secondes le splash se ferme QTimer::singleShot(2000,&window,SLOT(show())); //Au bout de 2 secondes le programme s'ouvre return QApplication::exec(); }
true
d032fbc0759753d06c6661c9edfa703761e89bba
C++
satyamdash/c-_codes
/Lecture-16_Recursion/Reverse_String.cpp
UTF-8
250
2.796875
3
[]
no_license
#include<iostream> using namespace std; void Reverse(string str) { if(str.size()==0) { return; } string ros=str.substr(1); Reverse(ros); cout<<str[0]; } int main() { string str; getline(cin,str); Reverse(str); }
true
d5e838c924c29850ef77198e9012c197d648520d
C++
whutaihejin/repo
/primer/chapter16/flexible_array_member.cc
UTF-8
952
3.34375
3
[]
no_license
#include <iostream> struct Flex { Flex(): count(0), average(0) {} int count; double average; double scores[]; // friend std::ostream& operator<<(std::ostream&, const Flex&); }; struct F { int count; double average; }; int main() { std::cout << "Flex size:" << sizeof(Flex) << std::endl; std::cout << "F size:" << sizeof(F) << std::endl; struct Flex* f; int n = 5; f = reinterpret_cast<struct Flex*>(malloc(sizeof(Flex) + n * sizeof(double))); f->count = n; double total = 0; for (int i = 0; i < n; ++i) { f->scores[i] = 20.0 - i; total += f->scores[i]; } f->average = total / n; std::cout << (*f) << std::endl; return 0; } std::ostream& operator<<(std::ostream& os, const Flex& flex) { os << "scores: "; for (int i = 0; i < flex.count; ++i) { os << flex.scores[i] << " "; } os << "\naverage: " << flex.average; return os; }
true
d7192b3e85ad937cdd1dc1fd0f6754d24efe6e2f
C++
ExpandiumSAS/nx
/sources/include/nx/nx/data.hpp
UTF-8
1,747
2.78125
3
[ "MIT" ]
permissive
#ifndef __NX_DATA_H__ #define __NX_DATA_H__ #include <sstream> #include <vector> #include <memory> #include <nx/config.h> #include <nx/file.hpp> #include <nx/socket_base.hpp> namespace nx { enum class data_item { stream, file }; using data_items = std::vector<data_item>; class NX_API data { public: std::size_t size() const; void clear(); template <typename Socket> void operator()(Socket& s) const { auto sit = streams_.begin(); auto fit = files_.begin(); for (auto& i : items_) { switch (i) { case data_item::stream: s << (*sit)->str(); ++sit; break; case data_item::file: s << *fit; ++fit; break; } } } template <typename T> data& operator<<(T&& v) { auto& s = make_stream(); auto old_size = stream_size(); s << std::forward<T>(v); size_ += stream_size() - old_size; return *this; } data& operator<<(const file& f); data& operator<<(const data& other); private: using stream_type = std::ostringstream; using stream_ptr = std::unique_ptr<stream_type>; using streams = std::vector<stream_ptr>; using files = std::vector<file>; stream_type& make_stream(); std::size_t stream_size(); void make_file(const file& f); std::size_t size_{ 0 }; data_items items_; streams streams_; files files_; }; template < typename Socket, typename = std::enable_if_t< std::is_base_of<socket_base, Socket>::value > > Socket& operator<<(Socket& s, const data& d) { d(s); return s; } } // namespace nx #endif // __NX_DATA_H__
true
9e1102be4aaa61b101f4c2f49d42b5bf9484e9c3
C++
dubshfjh/LeetCode
/123.cpp
UTF-8
1,641
3.828125
4
[]
no_license
动态规划:使用两个数组forward[]和back[]。1. forward[i]:{0..i}这段区间的最优利润,即[i-a]处低价买 & [i-a+b]处高价卖,从0正向遍历到i可以求解。PS:a,b>=0 2. back[i]:{n-1...i}这段区间的逆向最差利润,即[n-a]处高价买 & [n-a-b]处低价卖,它就是[n-a-b]处低价买 & [n-a]处高价卖这种实际情况的逆向说法,从n-1反向遍历到i可以求解。 3. 最后求解forward[i]-back[i]可以得到以每个i为两次交易分界点的最大利润。 class Solution { public: int maxProfit(vector<int>& prices) { int size = prices.size(); if(size<=1){ return 0; } vector<int> forward(size,0); vector<int> back(size,0); int curMin = prices[0]; for(int i=1;i<size;i++){ curMin = min(curMin,prices[i]);//更新加上i之后左侧元素的最小值 forward[i] = max(forward[i-1],prices[i]-curMin);//如果prices[i]-curMin > forward[i-1],说明在curMin处买进 & 在i处卖出货物利润更高,更新i左侧的最大利润 } int curMax = prices[size-1]; int res=0; for(int i=size-2;i>=0;i--){ curMax = max(curMax,prices[i]);//更新加上i之后右侧元素的最大值 back[i] = min(back[i+1],prices[i]-curMax);//如果prices[i]-curMax < back[i+1],说明在i处买入 & 在curMax处卖出货物利润更高,数组寸的是逆向数值[i]-curMax res = max(res,forward[i]-back[i]);//计算以i为交易分界点的最大利润,尝试更新最终利润结果 } return res; } };
true
1d8e751f460fcaa7ba70314a74212ea664a46998
C++
shivam17u113/Data-structure-and-algo-revesio-
/Design & Analysis Of Algorithm/7 Hamiltoniain Cycles.cpp
UTF-8
4,267
3.328125
3
[]
no_license
/* SIDDESH SUNIL VYAVAHARE A3 17U373 331067 TY IT */ /* REFERENCES ABDUL BARI YOUTUBE CHANNEL HAMILTONIAN CYCLES */ #include<iostream> #include<math.h> #include<vector> #include<cstring> using namespace std; #define br cout<<"========================================\n"; #define fbr cout<<"\n========================================\n"; class H_Cycles { private: int v,e; //no of vertices and edges int **a; // pointer approach for storing and accessing 2d matrix for graph int *x; //store hamiltonian cycle in x array public: void accept(); void display(); void Hamiltonian(int ); void nextVertex(int ); void displayX(); H_Cycles() { cout<<"Enter vertices \n"; cin>>v; a=new int*[v]; //ALLOCATE MEMORY FOR GRAPH x=new int[v]; for(int i=0;i<v;i++) //INITIALIZE WITH VERTEX 0 x[i]=0; for(int i=0;i<v;i++) //allocate memory a[i]=new int[v]; for(int i=0;i<v;i++) //assign weight of graph to infinite if i!=j for(int j=0;j<v;j++) *(*(a+i)+j)=0; } }; void H_Cycles::accept() //accept the edges { cout<<"Enter no of Edges: "; cin>>e; int r,c; cout<<"Enter Source Destinaion \n"; for(int i=1;i<=e;i++) { cin>>r>>c; *(*(a+r)+c)=1; *(*(a+c)+r)=1; } } void H_Cycles::display() //display graph { cout<<"The Matrix is \n"; for(int i=0;i<v;i++) { for(int j=0;j<v;j++) cout<<*(*(a+i)+j)<<"\t"; cout<<endl; } } void H_Cycles:: displayX() //DISPLAY THE HAMILTON CYCLE { for(int i=0;i<v;i++) cout<<x[i]+1<<" "; cout<<x[0]+1<<endl; } void H_Cycles::Hamiltonian(int k) // recursive funtion { do { if(k==v && a[x[v-1]][x[0]]!=0) //display when cycle is complete { displayX(); //display the cycle stored in x and break recusrive call return ; } else nextVertex(k); //update the x array if(x[k]==0) //if after repeating all vertex 0 occurs skip this itreartion return; if(k==v) //after processing nextval if k==v display X array displayX(); else if(k+1<=v) Hamiltonian(k+1); // else go to next new pos in x array }while(1); } void H_Cycles::nextVertex(int k) { do { x[k]=(x[k]+1)%(v); //assign all the vertices mod v if(x[k]==0) //if first vertex then break rec calls return; if(a[x[k-1]][x[k]]!=0) // if edge is present then { int j=0; for( j=0;j<=k-1;j++) //find for dublicate vertex if present break if(x[j]==x[k]) break; if(j==k) //if dublicate vertex is present then if(k<v || (k==v)&& a[x[v-1]][x[0]]!=0) // if dublicate vertex is last vertex return; //and it edge to base vertex print it; } }while(1); } int main() { H_Cycles H; int ch; do { cout<<"Enter choice \n1.Accept Graph\n2.Display Graph\n3.Generate All Cycles \n4.Exit\n"; // do while for choices cin>>ch; br; //break line defined in #define switch(ch) { case 1: H.accept(); br; //break line defined in #define break; case 2: H.display(); fbr; //break line defined in #define break; case 3: cout<<"All Hamiltonian Cycles are :\n"; H.Hamiltonian(1); br; //break line defined in #define break; } } while(ch!=4); return 0; } /* OUTPUT Enter vertices 5 Enter choice 1.Accept Graph 2.Display Graph 3.Generate All Cycles 4.Exit 1 ======================================== Enter no of Edges: 8 Enter Source Destinaion 0 1 0 4 0 2 1 4 1 3 1 2 2 3 3 4 ======================================== Enter choice 1.Accept Graph 2.Display Graph 3.Generate All Cycles 4.Exit 2 ======================================== The Matrix is 0 1 1 0 1 1 0 1 1 1 1 1 0 1 0 0 1 1 0 1 1 1 0 1 0 ======================================== Enter choice 1.Accept Graph 2.Display Graph 3.Generate All Cycles 4.Exit 3 ======================================== All Hamiltonian Cycles are : 1 2 3 4 5 1 1 2 5 4 3 1 1 3 2 4 5 1 1 3 4 2 5 1 1 3 4 5 2 1 1 5 2 4 3 1 1 5 4 2 3 1 1 5 4 3 2 1 ======================================== Enter choice 1.Accept Graph 2.Display Graph 3.Generate All Cycles 4.Exit 4 ======================================== */
true
dc43fdfd8aa3622ab0fb58606891ef6ef4b9b19b
C++
atoxiam/IntroToCPP
/MonthOfYear/Main.cpp
UTF-8
832
3.390625
3
[]
no_license
#include <iostream> int main() { int varA = 0, varC = 0; printf("This program will tell you how many days are in a month when you input the number that corresponds with that month \n"); printf("Please enter the number of the month you seeketh: "); scanf_s("%d", &varA); getchar(); switch (varA) { case 1: varC = 31; break; case 2: varC = 28; break; case 3: varC = 31; break; case 4: varC = 30; break; case 5: varC = 31; break; case 6: varC = 30; break; case 7: varC = 31; break; case 8: varC = 30; break; case 9: varC = 31; break; case 10: varC = 30; break; case 11: varC = 31; break; case 12: varC = 30; break; default: printf("The number you entered has made an error\t"); break; } printf(" The amount of days in that month is %d", varC); getchar(); }
true
460feb19fa224938c390a5966248abbfaf315f54
C++
anushkaGurjar99/Data-Structure-and-Algorithms
/LEETCODE/DFS/Q841. Keys and Rooms.cpp
UTF-8
962
3.234375
3
[]
no_license
/* * Author : Anushka Gurjar * Date : October 2020 * flags : -std=c++17 */ #include<bits/stdc++.h> using namespace std; // Problem Statement: https://leetcode.com/problems/keys-and-rooms/ class Solution{ public: bool canVisitAllRooms(vector<vector<int>>& rooms){ int size = rooms.size(); vector<bool> v(size, 0); dfs(rooms, v, 0); for(auto itr: v){ if(!itr) return false; } return true; } void dfs(vector<vector<int>>& rooms, vector<bool>& v, int curr){ if(v[curr]) return; v[curr] = true; for(auto itr: rooms[curr]){ if(!v[itr]) dfs(rooms, v, itr); v[itr] = true; } } }; /* take an array of which shows particular room is visited or not. visit all possible rooms using DFS. at last check all rooms are visited or not. */
true
1400c79df66bfb4e4e30fb1a97d51b56ae4e93f3
C++
Alonvita/AP1_EX2
/CheckAdditionCreation.cpp
UTF-8
6,078
2.953125
3
[]
no_license
// // Created by alon on 29/11/18. // #include "CheckAdditionCreation.h" void Test1() { auto* myImplementation = new MyImplementation(); // ---- PLANE 1 ---- // MODEL int p1Model = 747; // CREW map<Jobs, int> p1crewNeeded; p1crewNeeded.insert(make_pair(NAVIGATOR, 1)); p1crewNeeded.insert(make_pair(PILOT, 2)); p1crewNeeded.insert(make_pair(FLY_ATTENDANT, 1)); p1crewNeeded.insert(make_pair(MANAGER, 1)); map<Classes, int> seats; seats.insert(make_pair(FIRST_CLASS, 2)); seats.insert(make_pair(SECOND_CLASS, 3)); Plane* p1 = myImplementation->addPlane(p1Model, p1crewNeeded, seats); cout << "TEST1 DEBUG: Plane1 Added: " << p1->getID() << endl; Plane* p2 = myImplementation->addPlane(p1Model, p1crewNeeded, seats); cout << "TEST1 DEBUG: Plane2 Added: " << p2->getID() << endl; // ---- END PLANE 1 ---- // ---- CUSTOMER 1 ---- string fullName = "Alon Vita"; int priority = 1; Customer* c1 = myImplementation->addCustomer(fullName, priority); cout << "TEST1 DEBUG: Customer1 Added: " << c1->getID() << endl; // ---- END CUSTOMER 1 ---- // ---- CUSTOMER 2 ---- fullName = "Evya Shtern"; priority = 2; Customer* c2 = myImplementation->addCustomer(fullName, priority); cout << "TEST1 DEBUG: Customer2 Added: " << c2->getID() << endl; // ---- END CUSTOMER 2 ---- // ---- CUSTOMER 3 ---- fullName = "Ofek Israel"; priority = 3; Customer* c3 = myImplementation->addCustomer(fullName, priority); cout << "TEST1 DEBUG: Customer3 Added: " << c3->getID() << endl; // ---- END CUSTOMER 3 ---- // ---- CUSTOMER 4 ---- fullName = "David Vita"; priority = 4; Customer* c4 = myImplementation->addCustomer(fullName, priority); cout << "TEST1 DEBUG: Customer4 Added: " << c4->getID() <<endl; // ---- END CUSTOMER 4 ---- // ---- EMPLOYEE 0 ---- int seniority = 1; int bYear = 1993; string employerID = "EID1234"; Jobs job = MANAGER; Employee* emp0 = myImplementation->addEmployee(seniority, bYear, employerID, job); // ---- EMPLOYEE 0 ---- // ---- EMPLOYEE 1 ---- seniority = 2; bYear = 1990; employerID = "EID0"; job = FLY_ATTENDANT; Employee* emp1 = myImplementation->addEmployee(seniority, bYear, employerID, job); cout << "TEST1 DEBUG: Employee1 Added: " << emp1->getID() << endl; // ---- EMPLOYEE 1 ---- // ---- EMPLOYEE 2 ---- seniority = 93; bYear = 1880; employerID = "EID0"; job = PILOT; Employee* emp2 = myImplementation->addEmployee(seniority, bYear, employerID, job); cout << "TEST1 DEBUG: Employee2 Added: " << emp2->getID() << endl; // ---- EMPLOYEE 2 ---- // ---- EMPLOYEE 3 ---- seniority = 82; bYear = 1900; job = PILOT; employerID = "EID0"; Employee* emp3 = myImplementation->addEmployee(seniority, bYear, employerID, job); cout << "TEST1 DEBUG: Employee3 Added: " << emp3->getID() << endl; // ---- EMPLOYEE 3 ---- // ---- EMPLOYEE 4 ---- seniority = 50; bYear = 1940; job = NAVIGATOR; employerID = "EID2"; Employee* emp4 = myImplementation->addEmployee(seniority, bYear, employerID, job); cout << "TEST1 DEBUG: Employee4 Added: " << emp4->getID() << endl; // ---- EMPLOYEE 4 ---- // ---- TEST DATES ---- Date d = Date("1993-10-10"); Date d1 = Date("1993-10-10"); Date d2 = Date("1991-10-10"); Date d3 = Date("1993-11-10"); Date d4 = Date("1993-10-11"); if(d == d1) cout << "TEST1 DEBUG: DATE TEST 1 PASSED" << endl; if(d > d2) cout << "TEST1 DEBUG: DATE TEST 2 PASSED" << endl; if(d < d3) cout << "TEST1 DEBUG: DATE TEST 3 PASSED" << endl; if(d < d4) cout << "TEST1 DEBUG: DATE TEST 4 PASSED" << endl; // ---- END TEST DATES ---- Flight* f1 = myImplementation->addFlight(747, d, "israel", "metula"); cout << "TEST1 DEBUG: Flight Added: " << f1->getID() << endl; // ---- EMPLOYEE 5 ---- seniority = 50; bYear = 1940; job = NAVIGATOR; employerID = "EID2"; Employee* emp5 = myImplementation->addEmployee(seniority, bYear, employerID, job); cout << "TEST1 DEBUG: Employee4 Added: " << emp5->getID() << endl; // ---- EMPLOYEE 5 ---- // ---- EMPLOYEE 6 ---- seniority = 50; bYear = 1940; job = PILOT; employerID = "EID2"; Employee* emp6 = myImplementation->addEmployee(seniority, bYear, employerID, job); cout << "TEST1 DEBUG: Employee4 Added: " << emp6->getID() << endl; // ---- EMPLOYEE 6 ---- // ---- EMPLOYEE 7 ---- seniority = 50; bYear = 1940; job = PILOT; employerID = "EID2"; Employee* emp7 = myImplementation->addEmployee(seniority, bYear, employerID, job); cout << "TEST1 DEBUG: Employee4 Added: " << emp7->getID() << endl; // ---- EMPLOYEE 7 ---- // ---- EMPLOYEE 8 ---- seniority = 50; bYear = 1940; job = FLY_ATTENDANT; employerID = "EID2"; Employee* emp8 = myImplementation->addEmployee(seniority, bYear, employerID, job); cout << "TEST1 DEBUG: Employee4 Added: " << emp8->getID() << endl; // ---- EMPLOYEE 8 ---- // ---- EMPLOYEE 9 ---- seniority = 2; bYear = 1990; employerID = "EID0"; job = MANAGER; Employee* emp9 = myImplementation->addEmployee(seniority, bYear, employerID, job); cout << "TEST1 DEBUG: Employee1 Added: " << emp9->getID() << endl; // ---- EMPLOYEE 9 ---- Flight* f2 = myImplementation->addFlight(747, d, "israel", "metula"); cout << "TEST1 DEBUG: Flight Added: " << f2->getID() << endl; myImplementation->addResevation("CID0", "FID0", FIRST_CLASS, 20); myImplementation->addResevation("CID0", "FID0", FIRST_CLASS, 20); myImplementation->addResevation("CID0", "FID0", SECOND_CLASS, 15); myImplementation->addResevation("CID0", "FID0", SECOND_CLASS, 15); myImplementation->addResevation("CID1", "FID1", FIRST_CLASS, 22); myImplementation->addResevation("CID2", "FID1", SECOND_CLASS, 13); // EXIT TO PARSE INTO FILES myImplementation->exit(); }
true
e37a192ae909ef0b5b6ac6c39d611cd04a9f3315
C++
mohsin0176/HandNotes-onCPlusCPlus
/structunionenum/15.cpp
UTF-8
454
2.703125
3
[]
no_license
#include<iostream> #include<bits/stdc++.h> #include<math.h> #include<cstdlib.h> #include<limits.h> #include<iomanip.h> #include<fstream.h> #include<process.h> #define PI 3.1416 using namespace std; enum days_of_week{sun,mon,tues,wednesday,thu,fri,sat}; int main() { days_of_week day1,day2; day1=mon; day2=thu; int dff=day2-day1; cout<<diff; if (day1<day2) { cout<<"Day1 comes before Day2"<<endl; } return 0; }
true
4f3e81ab6f2940bf5277746dd245ee0112bbed3e
C++
Pisces000221/curly-octo-waddle
/712-d2e/1.cpp
UTF-8
1,014
3.328125
3
[]
no_license
#include <cstdio> #include <cstdlib> #include <cstring> #include <string> class RepeatNumberCompare { public: static const int MAXLEN = 602; std::string compare(int x1, int k1, int x2, int k2) { char x1_str[15], x2_str[15]; int s[MAXLEN] = { 0 }, t[MAXLEN] = { 0 }; sprintf(x1_str, "%d", x1); sprintf(x2_str, "%d", x2); int x1_len = strlen(x1_str), x2_len = strlen(x2_str); for (int i = 0; i < x1_len * k1; ++i) s[i] = x1_str[x1_len - 1 - i % x1_len]; for (int i = 0; i < x2_len * k2; ++i) t[i] = x2_str[x2_len - 1 - i % x2_len]; //for (int i = 0; i < x1_len * k1; ++i) putchar(s[i]); putchar('\n'); //for (int i = 0; i < x2_len * k2; ++i) putchar(t[i]); putchar('\n'); for (int i = MAXLEN - 1; i >= 0; --i) if (s[i] != t[i]) return (s[i] < t[i] ? "Less" : "Greater"); return "Equal"; } }; int main() { RepeatNumberCompare worker; puts(worker.compare(1234, 3, 70, 4).c_str()); puts(worker.compare(1010, 3, 101010, 2).c_str()); return 0; }
true
412911027c496add07091aca8c5db6e85214648b
C++
chenmenis/stuff
/permuteStrings.cpp
UTF-8
1,341
3.09375
3
[]
no_license
#include <iostream> #include <algorithm> #include <cstdio> #include <vector> #include <unordered_map> #include <stack> #include <climits> #include <cstring> #include <string> #include <sstream> #include <cmath> using namespace std; void permuteUtility(vector<char> &chars, vector<int> &counts,vector<char> &results,int level){ if(level==results.size()){ for(auto x:results) cout << x << ","; cout << "done" << endl; } for(int nonZero=0;nonZero < counts.size();nonZero++){ if(counts[nonZero]==0) continue; results[level] = chars[nonZero]; counts[nonZero]--; permuteUtility(chars,counts,results,level+1); counts[nonZero]++; } } void permuteString(string s){ unordered_map<char,int> map; vector<char> chars; vector<int> counts; for(char x:s){ if(map.find(x)!=map.end()){ map[x]++; } else { map[x] = 1; } } cout << " asdf s" << endl; int index =0; for ( auto it = map.begin(); it != map.end(); ++it ) { chars.push_back((char)it->first); counts.push_back( (int)it->second); } vector<char> results(s.length()); permuteUtility(chars,counts,results,0); } int main() { permuteString("aabcd"); return 0; }
true
0d7d3b0c837af285baf33d411483cd5d5a614815
C++
HenkeZeke/HuaweiRouter
/DebugServer/Network/network.cpp
UTF-8
5,070
2.828125
3
[]
no_license
#include "network.h" Network::Network(): releaseTheKraken(0), freePort(8000) {} Network::Network(std::vector<std::pair<int,int>> &adjList, int port, int nodesAmount): freePort(port), adjList(adjList) { createNodes(nodesAmount); } Network::Network(std::vector<Node> &nodes, std::vector<std::pair<int,int>> &adjList, int port = 8000): nodes(nodes), adjList(adjList), freePort(port) {} void Network::createNodes(int nodesAmount) { using namespace std; nodes = {}; for (int i = 0; i < nodesAmount; ++i) { nodes.push_back(Node(i)); } } void Network::setLeftToSendRight( Channel& left, Channel& right) { using namespace std; thread initRecieverThread(&Channel::initReciever, &left); thread initSenderThread(&Channel::initSender, &right); initRecieverThread.join(); initSenderThread.join(); } void Network::connectTwoChannels( Channel& left, Channel& right) { using namespace std; setLeftToSendRight(left, right); setLeftToSendRight(right, left); } void Network::connectNetwork() { using namespace std; int channelId = 0; auxillaryList = {}; for (pair<int,int>& edge : adjList) { Node& first = nodes[edge.first]; Node& second = nodes[edge.second]; first.addChannel( channelId, freePort, freePort + 5, nullptr, nullptr); second.addChannel( channelId + 1, freePort + 5, freePort, nullptr, nullptr); freePort += 10; channelId += 2; connectTwoChannels(first.getLastChannel(), second.getLastChannel()); auxillaryList.push_back({first.getChannelsAmount() - 1, second.getChannelsAmount() - 1}); } } void Network::startLeftToSendRight( Channel& left, Channel& right) { using namespace std; std::thread startSendingThread (&Channel::startSending, left); std::thread startRecievingThread (&Channel::startRecieving, right); startSendingThread.detach(); startRecievingThread.detach(); } void Network::startTwoChannels( Channel& left, Channel& right) { startLeftToSendRight(left, right); startLeftToSendRight(right, left); } void Network::startLeftToSendRightDebug(Channel& left, Channel& right, char c) { using namespace std; std::thread startSendingThread (&Channel::startSendingDebug, left, c); std::thread startRecievingThread (&Channel::startRecievingDebug, right); startSendingThread.detach(); startRecievingThread.detach(); } void Network::startLeftToSendRightInfo(Channel &left, Channel &right, std::string *infoPtr){ std::thread startSendingThread (&Channel::startSendingInformation, left, infoPtr); std::thread startRecievingThread (&Channel::startRecievingInformation, right, infoPtr->size()); startSendingThread.detach(); startRecievingThread.detach(); } void Network::startTwoChannelsDebug(Channel& left, Channel& right, char c) { startLeftToSendRightDebug(left, right, c); startLeftToSendRightDebug(right, left, c + 1); } void Network::startTwoChannelsInfo(Channel &left, Channel &right, std::string *infoPtr) { startLeftToSendRightInfo(left, right, infoPtr); startLeftToSendRightInfo(right, left, infoPtr); } void Network::startDebugNetwork() { releaseTheKraken = 0; char a = 'a'; for (int i = 0; i < adjList.size(); ++i) { Node& first = nodes[adjList[i].first]; Node& second = nodes[adjList[i].second]; Channel& channelOfFirst = first[auxillaryList[i].first]; Channel& channelOfSecond = second[auxillaryList[i].second]; startTwoChannelsDebug(channelOfFirst, channelOfSecond, a); a += 2; } releaseTheKraken = 1; } void Network::startInfoNetwork(std::string *infoPtr) { releaseTheKraken = 0; for (int i = 0; i < adjList.size(); ++i) { Node& first = nodes[adjList[i].first]; Node& second = nodes[adjList[i].second]; Channel& channelOfFirst = first[auxillaryList[i].first]; Channel& channelOfSecond = second[auxillaryList[i].second]; startTwoChannelsInfo(channelOfFirst, channelOfSecond, infoPtr); } releaseTheKraken = 1; } void Network::startInfoOrientedNetwork(std::string *infoPtr) { releaseTheKraken = 0; for (int i = 0; i < adjList.size(); ++i) { Node& first = nodes[adjList[i].first]; Node& second = nodes[adjList[i].second]; Channel& channelOfFirst = first[auxillaryList[i].first]; Channel& channelOfSecond = second[auxillaryList[i].second]; startLeftToSendRightInfo(channelOfFirst, channelOfSecond, infoPtr); } releaseTheKraken = 1; }
true
a11c42cdfce64a5195dfc8da10086ccceefd1283
C++
tokjun/TrackingServerSimulator
/TestClientSimulator.cxx
UTF-8
2,523
2.53125
3
[]
no_license
/*========================================================================= Program: Tracking Server Simulator (Test Client) Language: C++ Copyright (c) Brigham and Women's Hospital. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include <iostream> #include <math.h> #include <cstdlib> #include "igtlClientSocket.h" #include "TestClientProtocolNormal.h" #include "OpenIGTLinkSockUtil.h" int main(int argc, char* argv[]) { //------------------------------------------------------------ // Parse Arguments if (argc != 4) // check number of arguments { // If not correct, print usage std::cerr << "Usage: " << argv[0] << " <hostname> <port> <string>" << std::endl; std::cerr << " <hostname> : IP or host name" << std::endl; std::cerr << " <port> : Port # (18944 in Slicer default)" << std::endl; std::cerr << " <test> : Test Protocol# (1-10)" << std::endl; exit(0); } char* hostname = argv[1]; int port = atoi(argv[2]); int test = atoi(argv[3]); if (test <= 0 || test > 10) { std::cerr << "Invalid test" << std::endl; exit(0); } //------------------------------------------------------------ // Establish Connection igtl::ClientSocket::Pointer socket; socket = igtl::ClientSocket::New(); int r = socket->ConnectToServer(hostname, port); if (r != 0) { std::cerr << "Cannot connect to the server." << std::endl; exit(0); } //------------------------------------------------------------ // Call Test TestClientProtocolBase* testProtocol = NULL; switch (test) { case 1: { testProtocol = (TestClientProtocolNormal*) new TestClientProtocolNormal(); break; } default: break; } if (testProtocol) { OpenIGTLinkSockUtil * sockUtil = new OpenIGTLinkSockUtil(); sockUtil->SetSocket(socket); // Set timeout values (ms) testProtocol->SetTimeoutShort(1000); testProtocol->SetTimeoutMedium(5000); testProtocol->SetTimeoutMedium(10000); testProtocol->SetSockUtil(sockUtil); testProtocol->Exec(); } //------------------------------------------------------------ // Close connection socket->CloseSocket(); }
true
71a5f0e1bc1bf166456abd75322cc29d3583c988
C++
mirabl/j
/construct-rectangle.cpp
UTF-8
234
2.9375
3
[]
no_license
class Solution { public: vector<int> constructRectangle(int area) { for (int W = sqrt(area); W >= 0; W--) { if (area % W == 0) { return vector<int>{area / W, W}; } } } };
true
693aaa0f3ffc8d03235ad61a88de92340e83542c
C++
Palette25/Computer-Vision
/Final/Final-Project/PartI/src/Partition.cpp
UTF-8
12,357
2.625
3
[]
no_license
#include "Partition.h" Partition::Partition(CImg<unsigned char>& input, int seq){ this->seq = seq; this->grayImg = ImageSegmenter::toGrayScale(input); CImg<unsigned char> grayScale = this->grayImg; // Single Threshold Detect this->grayImg = threshold(grayScale, 15, 0.08); CImg<unsigned char> dilationed = this->grayImg; cimg_forXY(dilationed, x, y){ if(dilationed(x, y) == 0) dilationed(x, y) = 255; else dilationed(x, y) = 0; } this->grayImg = dilationed; this->grayImg = EdgeDetection(this->grayImg, 6); HoughTransformer hough(0, 0, dilationed, 0, false); cimg_forXY(dilationed, x, y){ if(dilationed(x, y) == 0) dilationed(x, y) = 255; else dilationed(x, y) = 0; if(this->grayImg(x, y) == 0) this->grayImg(x, y) = 255; else this->grayImg(x, y) = 0; } // Randon rotate double theta = hough.theta; theta = (theta - 90.0); // Perform Partition double ror = theta / 180.0 * cimg::PI; this->grayImg = reotate_biliinar(this->grayImg, ror); findDividingLine(3, 4); divideColumn(4); } CImg<unsigned char> Partition::threshold(CImg<unsigned char>& input, int size, float thres){ CImg<unsigned char> result(input.width(), input.height(), 1, 1, 255); CImg<int> integral(input.width(), input.height(), 1, 1, 0); cimg_forY(result, y){ int sum = 0; cimg_forX(result, x){ sum += input(x, y); if(y == 0){ integral(x, y) = sum; }else{ integral(x, y) = integral(x, y - 1) + sum; } } } // Self-Suitting Threshold cimg_forY(input, y) { int y1 = (y - size > 0) ?y - size : 0; int y2 = (y + size < input.height()) ? (y + size) : (input.height() - 1); cimg_forX(input, x) { int x1 = (x - size > 0) ? x - size : 0; int x2 = (x + size < input.width()) ? (x + size) : (input.width() - 1); int count = (x2 - x1) * (y2 - y1); int sum = integral(x2, y2) - integral(x1, y2) - integral(x2, y1) + integral(x1, y1); if (input(x, y) * count < sum * (1.0 - thres)) { result(x, y) = 0; } } } CImg<bool> isVisited(input.width(), input.height(), 1, 1, false); cimg_forXY(isVisited, x, y){ if(x > BOUNDER && x < (isVisited.width() - BOUNDER) && y > BOUNDER && y < (isVisited.height() - BOUNDER)) continue; if(isVisited(x, y) || result(x, y) != 0) continue; HoughPos currentPos(x, y); stack<HoughPos> posStack; posStack.push(currentPos); isVisited(x, y) = true; // DFS Searching while (!posStack.empty()){ HoughPos currentPos = posStack.top(); posStack.pop(); if (isVisited(currentPos.x,currentPos.y)) continue; isVisited(currentPos.x,currentPos.y) = true; // Eight Neighbor searching for (int i = currentPos.x - 1; i < currentPos.x + 2; i++){ for (int j = currentPos.y - 1; j < currentPos.y + 2; j++){ if (i >= 0 && i < isVisited.width() && j >= 0 && j < isVisited.height()){ if (i == currentPos.x && j == currentPos.y) continue; if (result(i, j) == 0){ HoughPos nextPos(i, j); posStack.push(nextPos); } } } } } } cimg_forXY(result, x, y){ if(isVisited(x, y)){ result(x, y) = 255; } } return result; } // Divide Image accroding to columns void Partition::divideColumn(int thres){ for(int i = 1; i < linePos.size(); i++) { int barHeight = linePos[i] - linePos[i - 1]; CImg<unsigned char> barItemImg = CImg<unsigned char>(grayImg.width(), barHeight, 1, 1, 0); cimg_forXY(barItemImg, x, y) { barItemImg(x, y, 0) = grayImg(x, linePos[i - 1] + 1 + y, 0); } vector<square> squareTmp; vector<int> dividePosXset = getColumnLine(barItemImg, thres); if(dividePosXset.empty()) continue; int everyCol = 0; for(int j = 1; j < dividePosXset.size(); j++){ // Reduce noise points square squ(HoughPos(dividePosXset[j - 1], linePos[i - 1]), HoughPos(dividePosXset[j - 1], linePos[i]), HoughPos(dividePosXset[j], linePos[i - 1]), HoughPos(dividePosXset[j], linePos[i])); int count = 0; for(int y = squ.lt.y; y<= squ.lb.y; y++){ bool flag = false; for(int x = squ.lt.x; x <= squ.rt.x; x++){ if(grayImg(x, y) == 0){ flag = true; break; } } if(flag) count++; } if(count > 6){ everyCol++; squareTmp.push_back(squ); } } if(everyCol > 4){ this->squareVec.push_back(squareTmp); // Draw lines unsigned char lineColor[1] = {0}; for (int j = 0; j < dividePosXset.size(); j++) { dividedImg.draw_line(dividePosXset[j], linePos[i - 1], dividePosXset[j], linePos[i], lineColor); } } } } void Partition::findDividingLine(int singleThreshold, int threshold){ CImg<int> histogram(grayImg.width(), grayImg.height(), 1, 1, 255); dividedImg = grayImg; // Scanning for histogram cimg_forY(grayImg, y){ int blackPixel = 0; cimg_forX(grayImg, x) { if (grayImg(x, y) == 0) blackPixel++; } blackPixel = blackPixel > singleThreshold ? blackPixel : 0; blackPixels.push_back(blackPixel); } // Loop for line finding cimg_forY(grayImg, y){ if(blackPixels[y] != 0){ int pointer = y + 1; int counter = 0; while(pointer < grayImg.height() && blackPixels[pointer] != 0){ pointer++; counter += blackPixels[pointer]; } counter /= (pointer - y); pointer--; // Delete noise if(pointer < grayImg.height() - 1 && blackPixels[pointer] != 0 && counter < threshold){ int distance = pointer - y + 1; if(distance < threshold){ for(int i = y; i <= pointer; i++){ blackPixels[i] = 0; } } } } } for(int y = 0; y < blackPixels.size(); y++) { if(y == 0) continue; if (blackPixels[y] == 0 && blackPixels[y - 1] != 0) linePos.push_back(y); else if (blackPixels[y] != 0 && blackPixels[y - 1] == 0) linePos.push_back(y - 1); } unsigned char lineColor[1] = {0}; vector<int> tmpVec = linePos; linePos.clear(); // Delete empty lines for(int index = 0; index < tmpVec.size() - 1; index++){ int counter = 0; for(int i = tmpVec[index]; i <= tmpVec[index + 1]; i++){ if(blackPixels[i] != 0) counter++; } if((double)counter / (double)(tmpVec[index + 1] - tmpVec[index]) < 0.3) { int median = (tmpVec[index + 1] + tmpVec[index]) / 2; linePos.push_back(median); index++; } else{ linePos.push_back(tmpVec[index]); } } linePos.push_back(tmpVec[tmpVec.size() - 1]); tmpVec = linePos; linePos.clear(); int distance = tmpVec[tmpVec.size() - 1] - tmpVec[0]; distance /= tmpVec.size(); // Close Distance line combined for(int index = 0; index < tmpVec.size() - 1; index++){ if(tmpVec[index + 1] - tmpVec[index] < (distance / 3)) { int median = (tmpVec[index + 1] + tmpVec[index]) / 2; linePos.push_back(median); index++; } else{ linePos.push_back(tmpVec[index]); } } linePos.push_back(tmpVec[tmpVec.size() - 1]); if(linePos[0] > 2){ linePos[0] -= 2; } if(linePos[linePos.size() - 1] + 2 < grayImg.height()){ linePos[linePos.size() - 1] += 2; } for(int i = 0; i < linePos.size(); i++){ dividedImg.draw_line(0, linePos[i], grayImg.width() - 1, linePos[i], lineColor); } } // Get every column lines vector<int> Partition::getColumnLine(CImg<unsigned char>& input, int thres){ vector<int> countVec; cimg_forX(input, x){ int blackPixel = 0; cimg_forY(input, y) { if (input(x, y) == 0) blackPixel++; } bool flag = (blackPixel > thres) ? true : false; if(x - 1 >= 0 && countVec[x - 1] != 0){ flag = true; } if(!flag) { blackPixel = 0; } countVec.push_back(blackPixel); } int counter = 0; for(int i = 0; i < countVec.size(); i++){ if(countVec[i] != 0) counter++; } // Delete empty rows if(counter == 0){ vector<int> InflectionPosXs; InflectionPosXs.clear(); return InflectionPosXs; } // Get Inflection Points vector<int> InflectionPosXs = getColumnInflectionPoints(countVec); unsigned char lineColor[1] = {0}; for(int i = 0; i < InflectionPosXs.size(); i++){ input.draw_line(InflectionPosXs[i], 0, InflectionPosXs[i], input.width() - 1, lineColor); } return InflectionPosXs; } vector<int> Partition::getColumnInflectionPoints(vector<int>& vec){ vector<int> resultInflectionPosXs, tempInflectionPosXs; // Look up inflection points for(int i = 0; i < vec.size(); i++){ // White to Black inflection if (i > 0 && vec[i] != 0 && vec[i - 1] == 0) tempInflectionPosXs.push_back(i - 1); // Black to White inflection else if (i > 0 && vec[i] == 0 && vec[i - 1] != 0) tempInflectionPosXs.push_back(i); } // Combine vectora vector<int> tmpVec = tempInflectionPosXs; tempInflectionPosXs.clear(); if(tmpVec[0] > 5) tmpVec[0] -= 5; if(tmpVec[tmpVec.size() - 1] + 5 < grayImg.width()) tmpVec[tmpVec.size() - 1] += 5; tempInflectionPosXs.push_back(tmpVec[0]); for(int index = 1; index < tmpVec.size() - 1; index++){ int counter = 0; for(int i = tmpVec[index]; i <= tmpVec[index + 1]; i++){ if(vec[i] != 0) counter++; } if(counter == 0) { int median = (tmpVec[index + 1] + tmpVec[index]) / 2; tempInflectionPosXs.push_back(median); index++; } else{ tempInflectionPosXs.push_back(tmpVec[index]); } } tempInflectionPosXs.push_back(tmpVec[tmpVec.size() - 1 ]); if(seq < 10){ int max = 0; for(int i = 1; i < tempInflectionPosXs.size(); i++){ if(tempInflectionPosXs[i] - tempInflectionPosXs[i - 1] > max) max = tempInflectionPosXs[i] - tempInflectionPosXs[i - 1]; } float distance = 0.0; for(int i = 1; i < tempInflectionPosXs.size(); i++){ distance += tempInflectionPosXs[i] - tempInflectionPosXs[i - 1]; } distance -= (float)max; distance /= (float)(tempInflectionPosXs.size() - 1); for(auto iter = tempInflectionPosXs.begin(); iter != tempInflectionPosXs.end(); iter++){ if(iter != tempInflectionPosXs.begin() && (float)(*iter - *(iter - 1)) >= 2.077 * distance){ int median = *iter - *(iter - 1); median /= 2; median += *(iter - 1); tempInflectionPosXs.insert(iter, median); iter = tempInflectionPosXs.begin(); } } } return tempInflectionPosXs; } // Getter methods vector<vector<square> > Partition::getSquare(){ return this->squareVec; } CImg<unsigned char> Partition::getGrayImg(){ return this->grayImg; } CImg<unsigned char> Partition::getDividedImg(){ return this->dividedImg; }
true
86d0954b693dc70a371800c25c38d81f46b2613b
C++
alielbashir/learncpp
/casting.cpp
UTF-8
199
2.78125
3
[]
no_license
#include <iostream> #include <string> using namespace std; int main() { // CASTING // changing data from 1 type to another cout << (int)3.14 << endl; cout << (double)3/2 << endl; }
true
0f1d283bca04591d749637a3a98e20ea52fe59a6
C++
zackkk/leetcode
/Max Points on a Line.cpp
UTF-8
1,006
3.21875
3
[]
no_license
/** * Definition for a point. * struct Point { * int x; * int y; * Point() : x(0), y(0) {} * Point(int a, int b) : x(a), y(b) {} * }; */ class Solution { public: // y = kx + b int maxPoints(vector<Point> &points) { int max_num = 0; for(Point p : points){ int itself = 0; int vertical = 0; map<double, int> m; for(Point q : points){ if(q.x == p.x && q.y == p.y) { itself++; continue; } if(q.x == p.x) { vertical++; continue; } double k = (double)(q.y - p.y) / (q.x - p.x); m[k]++; } max_num = max(max_num, itself + vertical); int max_tmp = 0; for(auto it = m.begin(); it != m.end(); ++it) max_tmp = max(max_tmp, it->second); max_num = max(max_num, itself + max_tmp); } return max_num; } };
true
af1a2a4ea8e4b03ad377c7ab4c07eb2943838728
C++
michaelkotor/laba05
/include/Iterator.h
UTF-8
897
3.234375
3
[]
no_license
// // Created by Michael Kotor on 11/2/20. // #ifndef LABA05_ITERATOR_H #define LABA05_ITERATOR_H #include "Node.h" #include "Queue.h" template <typename T> class Iterator { private: Node<T>* value; public: Iterator(Queue<T> queue) { this->value = queue.getTop(); } void operator++() { if(hasNext()) { this->value->next; } } void operator--() { if(hasPrevios()) { this->value->previos; } } void next() { if(hasNext()) { this->value->next; } } void previos() { if(hasPrevios()) { this->value->previos; } } bool hasNext() { return this->value->next != nullptr; } bool hasPrevios() { return this->value->previos != nullptr; } T* get() { return this->value; } }; #endif //LABA05_ITERATOR_H
true
ae561ad6978d20b6775bec4451b863f93660d2f4
C++
yqs112358/YQ-CPP-Library
/CheckPath.h
UTF-8
326
2.765625
3
[ "Apache-2.0" ]
permissive
#ifndef YQ_CHECK_PATH_H #define YQ_CHECK_PATH_H #include <string> using std::string; string CheckPath(string path) { try { string::size_type pos=0; string chars("?*:<>|\""); while((pos=path.find_first_of(chars,pos)) != string::npos) path.erase(pos,1); return path; } catch(...) { return ""; } } #endif
true
f0ec31bd5b7e0b45e1e187fee30b9d1369482022
C++
spoosanthiram/Thanuva
/Core/Include/Matrix4x4.h
UTF-8
3,538
3.046875
3
[]
no_license
/* * Core: Common Code used by other modules of Thanuva * * Copyright 2016, Saravanan Poosanthiram * All rights reserved. */ #ifndef CORE_MATRIX4X4_H #define CORE_MATRIX4X4_H #include <array> #include "Point3d.h" namespace Core { class HPoint; class HVector; class Quaternion; /** * Column based matrix */ class Matrix4x4 { public: static const int kNRows = 4; static const int kNColumns = 4; public: static Matrix4x4 zero() { Matrix4x4 z; z.makeZero(); return z; } static Matrix4x4 identity() { Matrix4x4 eye; eye.makeIdentity(); return eye; } static Matrix4x4 frustum(double left, double right, double bottom, double top, double near, double far); static Matrix4x4 perspective(double fovy, double aspect, double near, double far); static Matrix4x4 ortho(double left, double right, double bottom, double top, double near, double far); public: Matrix4x4() : m_elements() {} Matrix4x4(double val0, double val1, double val2, double val3 , double val4, double val5, double val6, double val7 , double val8, double val9, double val10, double val11 , double val12, double val13, double val14, double val15); Matrix4x4(const std::array<double, kNRows * kNColumns>& values) : m_elements(values) {} Matrix4x4(const Matrix4x4& rhs) : m_elements(rhs.m_elements) {} Matrix4x4(Matrix4x4&& rhs) : m_elements(rhs.m_elements) {} Matrix4x4& operator=(const Matrix4x4& rhs) { if (this != &rhs) m_elements = rhs.m_elements; return *this; } Matrix4x4& operator=(Matrix4x4&& rhs) { if (this != &rhs) m_elements = rhs.m_elements; return *this; } double operator()(std::size_t irow, std::size_t icolumn) const { return m_elements[(icolumn * kNRows) + irow]; } const double* data() const { return m_elements.data(); } void data(float* values) const; std::string str() const; void setValue(int irow, int icolumn, double value) { m_elements[(icolumn * kNRows) + irow] = value; } void setColumn(int icolumn, double val0, double val1, double val2, double val3); void setColumn(int icolumn, const double* values); void setColumn(int icolumn, const HPoint& hp); void setColumn(int icolumn, const HVector& hv); void set(const std::string& str); void makeZero() { m_elements.fill(0.0); } void makeIdentity(); void transpose(); void invert(); void scale(double x, double y, double z); void translate(double x, double y, double z); void translate(const Core::Point3d& p) { this->translate(p.x(), p.y(), p.z()); } void rotateAlongX(double angle); void rotateAlongY(double angle); void rotateAlongZ(double angle); void rotate(const Quaternion& q); Matrix4x4& operator*=(const Matrix4x4& rhs) { *this = *this * rhs; return *this; } bool operator==(const Matrix4x4& rhs) const; bool operator!=(const Matrix4x4& rhs) const { return !(*this == rhs); } Matrix4x4 operator*(const Matrix4x4& rhs) const; HPoint operator*(const HPoint& rhs) const; HPoint multiplyInfinite(const HPoint& rhs) const; protected: std::array<double, kNRows * kNColumns> m_elements; }; } // namespace Core #endif // CORE_MATRIX4X4_H
true
c7a665b74c8cc2e150f9e31176afeeed0a28c170
C++
terataichi/2-
/Project2/ModePuyo/FallMode.h
SHIFT_JIS
2,044
2.515625
3
[]
no_license
#pragma once #include "../Stage.h" struct FallMode { void operator()(Stage& stage) { bool nextFlg = true; for (auto puyo : stage.puyoVec_) { // ܂Ă`FbN puyo->SetOldDirFlg(); nextFlg &= stage.CheckMove(puyo); } std::for_each(stage.puyoVec_.rbegin(), stage.puyoVec_.rend(), [&](SharePuyo& uniPuyo) { if (uniPuyo->id() != PuyoID::Ojama) { // Ղ񂳂 if (uniPuyo->GetDirFlg().bit.down && !uniPuyo->GetOldDirFlg().bit.down) { Vector2 grid{ 0,0 }; grid = uniPuyo->GetGrid(stage.blockSize_); auto max = (STAGE_Y - 1) - grid.y; if (max > 3) { max = 3; } for (int j = 0; j < max; j++) { if (stage.data_[grid.y + j][grid.x]->id() != PuyoID::Ojama) { stage.data_[grid.y + j][grid.x]->SetPuyon(); stage.data_[grid.y + j][grid.x]->SetCnt((max - j)); if (j >= max) { break; } } else { break; } } } } }); bool puyon = true; // ՂɍsĂǂ int count = 0; // S񂵂Ă邩 bool fall = true; std::for_each(stage.puyoVec_.rbegin(), stage.puyoVec_.rend(), [&](SharePuyo& uniPuyo) { if (uniPuyo->id() == PuyoID::Ojama) { fall &= uniPuyo->seiretu(); } }); std::for_each(stage.ojamaList_.rbegin(), stage.ojamaList_.rend(), [&](SharePuyo& ojama) { if (!ojama->CheckFall()) { ojama->UpDate(count); count++; } }); // 鏈 std::for_each(stage.puyoVec_.rbegin(), stage.puyoVec_.rend(), [&](SharePuyo& uniPuyo) { if (fall) { uniPuyo->SetDrop(); } // false܂Ă邩AɂȂ if (!uniPuyo->UpDate(0)) { Vector2 grid = uniPuyo->GetGrid(stage.blockSize_); stage.data_[grid.y][grid.x].reset(); puyon = false; } }); if (puyon) { stage.stgMode_ = StgMode::Puyon; } } };
true
2c261675c84c693d44a98e1ffb3b7eaae28b91a4
C++
MultivacX/leetcode2020
/algorithms/hard/1510. Stone Game IV.h
UTF-8
800
3.203125
3
[ "MIT" ]
permissive
// 1510. Stone Game IV // https://leetcode.com/problems/stone-game-iv/ // Runtime: 44 ms, faster than 78.31% of C++ online submissions for Stone Game IV. // Memory Usage: 21.9 MB, less than 5.18% of C++ online submissions for Stone Game IV. class Solution { public: bool winnerSquareGame(int n) { static vector<int> memo(100001, 0); if (memo[n] != 0) return memo[n] > 0; int k = sqrt(n); if (n == k * k || n == k * k + 2) { memo[n] = 1; return true; } // k * k < n for (int i = 1; i <= k; ++i) { if (!winnerSquareGame(n - i * i)) { memo[n] = 1; return true; } } memo[n] = -1; return false; } };
true
d38e2edb2f2aff040fc43f1c0f9d53b1419bcda1
C++
tyler-eto/alarum
/baseSpace.cpp
UTF-8
4,241
3.296875
3
[]
no_license
/********************************************************************* ** Program name: baseSpace.cpp ** Author: Tyler Eto ** Date: 6/7/18 ** Description: implementation file for BaseSpace class *********************************************************************/ #include "baseSpace.hpp" #include "helpers.hpp" using std::cout; using std::endl; // constructor BaseSpace::BaseSpace() { itemContainer.fill(nullptr); type = ""; // name = ""; } // destructor BaseSpace::~BaseSpace() { for (int i=0; i<(int)itemContainer.size(); ++i) { if (itemContainer[i] != nullptr) { delete itemContainer[i]; itemContainer[i] = nullptr; } } } // getters std::string BaseSpace::getType() { return type; } // std::string BaseSpace::getName() { return name; } // void BaseSpace::setName(std::string n) { this->name = n; } /********************************************************************* getItemByIndex: retrieve item name by index. used for investigation *********************************************************************/ std::string BaseSpace::getItemNameByIndex(int index) { if (itemContainer[index] != nullptr) { return itemContainer[index]->getName(); } return ""; } /********************************************************************* hasItems : quick check if space has items in itemContainer *********************************************************************/ bool BaseSpace::hasItems() { for (int i=0; i<(int)itemContainer.size(); ++i) { if (itemContainer[i] != nullptr) { return true; } } return false; } /********************************************************************* showItems : prints the items available in the room's itemContainer *********************************************************************/ void BaseSpace::showItems() { for (int i=0; i<(int)itemContainer.size(); ++i) { if (itemContainer[i] != nullptr) { cout << i+1 << ") " << itemContainer[i]->getName() << " : " << itemContainer[i]->getDescription() << endl; } } } /********************************************************************* selectItem : takes in index of item wanted by player and returns the item at the index *********************************************************************/ Item* BaseSpace::selectItem(int index) { Item *tmp = itemContainer[index]; // delete spot in itemContainer? // delete itemContainer[index]; itemContainer[index] = nullptr; return tmp; } /********************************************************************* describeSpace : grabs first dialogue from top of stack and prints it *********************************************************************/ std::string BaseSpace::describe() { // set variable to dialogue std::string tmp = dialogue.top(); // pop dialogue dialogue.pop(); // add it back if stack is now empty if (dialogue.empty()) { dialogue.push(tmp); } return tmp; } /********************************************************************* storyText : just does some formatting around story text *********************************************************************/ std::string BaseSpace::storyText(std::string text) { // choose a color return text; } /********************************************************************* push_dialogue : for game setup, push dialogue *********************************************************************/ void BaseSpace::pushDialogue(std::string s) { dialogue.push(s); } /********************************************************************* pushItem : for game setup, push item *********************************************************************/ bool BaseSpace::pushItem(Item *item) { bool wasAdded = false; for (int i=0; i<(int)itemContainer.size(); ++i) { if (itemContainer[i] == nullptr && !wasAdded) { itemContainer[i] = item; wasAdded = true; } } return wasAdded; } /********************************************************************* pushItemWithIndex : for setting items back if player doesn't want them *********************************************************************/ bool BaseSpace::pushItemWithIndex(Item *item, int index) { if (itemContainer[index] == nullptr) { // push item itemContainer[index] = item; return true; } return false; }
true
735a59de2f5b413807b5f6b1ad7ed62031791ea6
C++
liuhe3647/serialize
/thirdParty/json/GenericReader.cpp
UTF-8
15,636
2.515625
3
[]
no_license
#include "GenericReader.h" #include <assert.h> namespace custom { resetStruct::resetStruct(uint8_t** pStruct, uint8_t* pTarget) :_pStruct(pStruct), _pTarget(pTarget) { } void resetStruct::reset() { *_pStruct = _pTarget; } /*------------------------------------------------------------------------------*/ jsonConverter::jsonConverter(convert_t func, size_t value, size_t has, obtainConvert_t obtain, clear_t _clearArray) :_szKey(NULL), _keyLength(0), _func(func), _value(value), _has(has), _obtain(obtain), _clearArray(_clearArray), _last(NULL), _lastStruct(NULL, NULL) { } void jsonConverter::operator()(uint8_t* pStruct, const char* cValue, uint32_t length) const { (*_func)((pStruct + _value), cValue, length, (bool*)(_has ? pStruct + _has : NULL)); if (_last) { jsonConverter* temp = const_cast<jsonConverter*>(this); _lastStruct.reset(); *temp = *_last; } } void* jsonConverter::getConvert(uint8_t* pStruct, void* owner) const { if (_obtain) return (*_obtain)(pStruct + _value, _szKey, _keyLength, owner); return NULL; } void jsonConverter::clear(uint8_t* pStruct) const { if (_clearArray) (*_clearArray)(pStruct + _value); } void jsonConverter::setKey(const char* szKey, uint32_t length) const { _szKey = szKey; _keyLength = length; } void jsonConverter::setLast(const jsonConverter* last, const resetStruct& lastStruct) const { _last = const_cast<jsonConverter*>(last); _lastStruct = lastStruct; } /*------------------------------------------------------------------------------*/ jsonConverterMgr::jsonConverterMgr(const void* pStruct, bool isMap) :_owner(NULL), _pStruct((uint8_t*)pStruct), _isMap(isMap) { } jsonConverterMgr::jsonConverterMgr(const jsonConverterMgr& that) : _owner(that._owner), _pStruct(NULL), _isMap(that._isMap), _map(that._map) { } const uint8_t* jsonConverterMgr::getStruct() const { return _pStruct; } bool jsonConverterMgr::isMap() const { return _isMap; } void jsonConverterMgr::clear() { _map.clear(); } void jsonConverterMgr::insert(const std::pair<std::string, jsonConverter>& item) { _map.insert(item); } jsonConverterMgr::const_iterator jsonConverterMgr::end() const { return _map.end(); } jsonConverterMgr::const_iterator jsonConverterMgr::find(const char* sz, uint32_t length) const { return _map.find(std::string(sz, length)); } void jsonConverterMgr::setStruct(void* value, void* owner) { if (value && owner) { _owner = (Handler*)owner; _owner->_stackStruct.push_back(_owner->_struct); _owner->_struct = (uint8_t*)value; } } /*------------------------------------------------------------------------------*/ StringStream::StringStream(Ch* src, uint32_t length) : _src(src), _length(length) { } StringStream::Ch StringStream::Peek() const { if (isEnd()) return '\0'; return *_src; } StringStream::Ch StringStream::Take() { --_length; return *_src++; } StringStream::Ch* StringStream::Strart() const { return _src; } bool StringStream::isEnd() const { return (_length == 0); } /*------------------------------------------------------------------------------*/ Handler::Handler(jsonConverterMgr* mgr, void* pStruct) :_converter(NULL), _mgr(mgr), _struct((uint8_t*)pStruct) { assert(_mgr); _mgr->setStruct(pStruct, this); } bool Handler::Key(const char* sz, uint32_t length) { assert(_mgr); if (_mgr->isMap()) { const jsonConverter* tempConverter = _converter; uint8_t* tempStruct = _struct; _converter->setKey(sz, length); jsonConverterMgr* mgr = (jsonConverterMgr*)_converter->getConvert(_struct, this); _converter = &mgr->find(sz, length)->second; _converter->setLast(tempConverter, resetStruct(&_struct, tempStruct)); } else { jsonConverterMgr::const_iterator it = _mgr->find(sz, length); if (it != _mgr->end()) { _converter = &it->second; } else { _converter = NULL; } } return true; } bool Handler::Value(const char* sz, uint32_t length) { if (_converter) { (*_converter)(_struct, sz, length); } return true; } bool Handler::StartObject() { if (_converter) { _stackFunction.push_back(_converter); assert(_mgr); _stackMgr.push_back(_mgr); _mgr = (jsonConverterMgr*)_converter->getConvert(_struct, this); } return true; } bool Handler::EndObject(uint32_t memberCount) { if (!_stackMgr.empty()) { assert(_mgr); bool bIsMap = _mgr->isMap(); _mgr = _stackMgr.back(); _stackMgr.erase(_stackMgr.begin() + _stackMgr.size() - 1); _converter = _stackFunction.back(); _stackFunction.erase(_stackFunction.begin() + _stackFunction.size() - 1); if (!bIsMap || memberCount) { _struct = _stackStruct.back(); _stackStruct.erase(_stackStruct.begin() + _stackStruct.size() - 1); } } return true; } bool Handler::StartArray() { return true; } bool Handler::EndArray(uint32_t elementCount) { if (!elementCount) { _converter->clear(_struct); } return true; } void Handler::convert(bool& value, const char* sz, uint32_t length) { if (length == 4 && strncmp(sz, "true", 4) == 0) { value = true; } else if (length == 5 && strncmp(sz, "false", 5) == 0) { value = false; } else { assert(false); } } void Handler::convert(int32_t& value, const char* sz, uint32_t length) { if (!length) return; value = 0; bool bMinus = false; if (sz[0] == '-') { bMinus = true; } for (uint32_t idx = bMinus; idx < length; ++idx) { value *= 10; value += sz[idx] - '0'; } if (bMinus) value = 0 - value; } void Handler::convert(uint32_t& value, const char* sz, uint32_t length) { if (!length) return; value = 0; for (uint32_t idx = 0; idx < length; ++idx) { value *= 10; value += sz[idx] - '0'; } } void Handler::convert(int64_t& value, const char* sz, uint32_t length) { if (!length) return; value = 0; bool bMinus = false; if (sz[0] == '-') { bMinus = true; } for (uint32_t idx = bMinus; idx < length; ++idx) { value *= 10; value += sz[idx] - '0'; } if (bMinus) value = 0 - value; } void Handler::convert(uint64_t& value, const char* sz, uint32_t length) { if (!length) return; value = 0; for (uint32_t idx = 0; idx < length; ++idx) { value *= 10; value += sz[idx] - '0'; } } static inline double decimal(uint8_t n, uint32_t num) { double db = n * 1.0f; while (num--) db = db / 10; return db; } void Handler::convert(float& value, const char* sz, uint32_t length) { if (!length) return; value = 0; bool bMinus = false; if (sz[0] == '-') { bMinus = true; } for (uint32_t idx = bMinus, bFlag = false, num = 0; idx < length; ++idx) { const char& c = sz[idx]; if (c == '.') { bFlag = true; continue; } uint8_t n = c - '0'; if (!bFlag) { value *= 10; value += n; } else { ++num; value += decimal(n, num); } } if (bMinus) value = 0 - value; } void Handler::convert(double& value, const char* sz, uint32_t length) { if (!length) return; value = 0; for (uint32_t idx = 0, bFlag = false, num = 0; idx < length; ++idx) { const char& c = sz[idx]; if (c == '.') { bFlag = true; continue; } uint8_t n = c - '0'; if (!bFlag) { value *= 10; value += n; } else { ++num; value += decimal(n, num); } } } /*------------------------------------------------------------------------------*/ static bool Consume(StringStream& is, const char expect) { if (is.Peek() == expect) { is.Take(); return true; } else return false; } static void SkipWhitespace(StringStream& is) { for (;;) { const char c = is.Peek(); if (c == ' ' || c == '\n' || c == '\r' || c == '\t') { is.Take(); } else { break; } } } CustomGenericReader::CustomGenericReader() :_result(true) { } bool CustomGenericReader::Parse(StringStream& is, Handler& handler) { if (is.Peek() != '\0') { ParseValue(is, handler); } return _result; } const char* CustomGenericReader::getError()const { return _strError.c_str(); } void CustomGenericReader::setError(const char* sz) { _result = false; _strError.append(sz); } void CustomGenericReader::ParseValue(StringStream& is, Handler& handler) { switch (is.Peek()) { case 'n': ParseNull(is, handler); break; case 't': ParseTrue(is, handler); break; case 'f': ParseFalse(is, handler); break; case '"': ParseString(is, handler); break; case '{': ParseObject(is, handler); break; case '[': ParseArray(is, handler); break; default: ParseNumber(is, handler); break; } if (!_result) return; } void CustomGenericReader::ParseKey(StringStream& is, Handler& handler) { assert(is.Peek() == '\"'); is.Take(); // Skip '\"' const char* szStart = is.Strart(); for (; is.Peek() != '\0'; is.Take()) { if (is.Peek() == '\"') { handler.Key(szStart, is.Strart() - szStart); is.Take(); // Skip '\"' return; } } setError("KeyInvalid"); } void CustomGenericReader::ParseNull(StringStream& is, Handler& handler) { assert(is.Peek() == 'n'); is.Take(); if (Consume(is, 'u') && Consume(is, 'l') && Consume(is, 'l')) { handler.Value("", 0); } else { setError("ValueInvalid"); } } void CustomGenericReader::ParseTrue(StringStream& is, Handler& handler) { assert(is.Peek() == 't'); const char* szStart = is.Strart(); is.Take(); if (Consume(is, 'r') && Consume(is, 'u') && Consume(is, 'e')) { handler.Value(szStart, is.Strart() - szStart); } else { setError("ValueInvalid"); } } void CustomGenericReader::ParseFalse(StringStream& is, Handler& handler) { assert(is.Peek() == 'f'); const char* szStart = is.Strart(); is.Take(); if (Consume(is, 'a') && Consume(is, 'l') && Consume(is, 's') && Consume(is, 'e')) { handler.Value(szStart, is.Strart() - szStart); } else { setError("ValueInvalid"); } } void CustomGenericReader::ParseString(StringStream& is, Handler& handler) { assert(is.Peek() == '\"'); is.Take(); // Skip '\"' const char* szStart = is.Strart(); for (; is.Peek() != '\0'; is.Take()) { if (is.Peek() == '\"') { handler.Value(szStart, is.Strart() - szStart); is.Take(); // Skip '\"' return; } } setError("ValueInvalid"); } void CustomGenericReader::ParseArray(StringStream& is, Handler& handler) { assert(is.Peek() == '['); is.Take(); // Skip '[' if (!handler.StartArray()) { setError("ParseErrorTermination"); return; } SkipWhitespace(is); if (Consume(is, ']')) { if (!handler.EndArray(0)) { setError("ParseErrorTermination"); } return; } for (uint32_t elementCount = 0;;) { ParseValue(is, handler); ++elementCount; SkipWhitespace(is); if (Consume(is, ',')) { SkipWhitespace(is); } else if (Consume(is, ']')) { if ((!handler.EndArray(elementCount))) { setError("ParseErrorTermination"); } return; } else { setError("ParseErrorArrayMissCommaOrSquareBracket"); return; } } setError("ValueArrayInvalid"); } void CustomGenericReader::ParseNumber(StringStream& is, Handler& handler) { const char* szStart = is.Strart(); for (; is.Peek() != '\0'; is.Take()) { if (is.Peek() == '-' || is.Peek() == '.' || (is.Peek() >= '0' && is.Peek() <= '9')) { continue; } else { handler.Value(szStart, is.Strart() - szStart); return; } } setError("ValueInvalid"); } void CustomGenericReader::ParseObject(StringStream& is, Handler& handler) { assert(is.Peek() == '{'); const char* szStart = is.Strart(); is.Take(); // Skip '{' if (!handler.StartObject()) { setError("ParseErrorTermination"); return; } SkipWhitespace(is); if (is.Peek() == '}') { is.Take(); if (!handler.EndObject(0)) { setError("ParseErrorTermination"); } return; } for (uint32_t memberCount = 0; !is.isEnd();) { if (is.Peek() != '"') { setError("ObjectMissName"); return; } ParseKey(is, handler); SkipWhitespace(is); if (!Consume(is, ':')) { setError("ObjectMissColon"); return; } SkipWhitespace(is); ParseValue(is, handler); ++memberCount; SkipWhitespace(is); switch (is.Peek()) { case ',': is.Take(); SkipWhitespace(is); break; case '}': is.Take(); if (!handler.EndObject(memberCount)) { setError("ParseErrorTermination"); } return; default: setError("ObjectMissCommaOrCurlyBracket"); break; // This useless break is only for making warning and coverage happy } } } }
true
ea8097382ae2c238871bac479ea22c9045bd8518
C++
ycwu0609/OOP_practice
/LAB4/Lab4.cpp
UTF-8
3,345
3.53125
4
[]
no_license
#include <iostream> using namespace std; class PolySeq { public: PolySeq operator -(PolySeq p); PolySeq operator *(PolySeq p); void print(); int set_num(int a){num_of_terms=a;} int get_num_of_terms(){return num_of_terms;} void set_coe(int* s); int* get_coe(){return coe;} void set_exp(int* s); int* get_exp(){return exp;} int GetValue(int x); private: int coe[100]; int exp[100]; int num_of_terms; }; ostream& operator<<(ostream& out,PolySeq p) { int a=p.get_num_of_terms(); out<<p.get_coe()[0]<<" "; out<<"X^"<<a-1; for(int i=1;i<a;i++) { if(p.get_coe()[i]==0) { continue; } out<<" +"; out<<p.get_coe()[i]<<" "; out<<"X^"<<a-1-i; } out<<endl; return out; } int main() { int a,c1[100],e1[100]; int b,c2[100],e2[100]; int x; PolySeq Poly1; PolySeq Poly2; PolySeq Poly3; PolySeq Poly4; PolySeq Poly5; cout<<"Enter Num of Terms of Poly1:"<<endl; cin>>a; Poly1.set_num(a); //set num cout<<"Enter Coefficients of Poly1:"<<endl; for(int i=0;i<a;i++) { cin>>c1[i]; } Poly1.set_coe(c1); //set coe cout<<"Enter Exponentials of x in Poly1<from high to low>:"<<endl; for(int i=0;i<a;i++) { cin>>e1[i]; } Poly1.set_exp(e1); //set exp cout<<"Enter Num of Terms of Poly2:"<<endl; cin>>b; Poly2.set_num(b); //set num cout<<"Enter Coefficients of Poly2:"<<endl; for(int i=0;i<b;i++) { cin>>c2[i]; } Poly2.set_coe(c2); //set coe cout<<"Enter Exponentials of x in Poly2<from high to low>:"<<endl; for(int i=0;i<b;i++) { cin>>e2[i]; } Poly2.set_exp(e2); //set exp cout<<"Enter the value of x:"<<endl; cin>>x; cout<<"P1-P2: "; Poly3=Poly1-Poly2; cout<<Poly3; cout<<"P2-P1: "; Poly4=Poly2-Poly1; cout<<Poly4; cout<<"P1*P2: "; Poly5=Poly1*Poly2; cout<<Poly5; cout<<"P1<x1>: "; cout<<Poly1.GetValue(x)<<endl; cout<<"P2<x1>: "; cout<<Poly2.GetValue(x)<<endl; cout<<"<P1-P2><x1>: "; cout<<Poly3.GetValue(x)<<endl; cout<<"<P2-P1><x1>: "; cout<<Poly4.GetValue(x)<<endl; cout<<"<P1*P2><x1>: "; cout<<Poly5.GetValue(x)<<endl; return 0; } void PolySeq::set_coe(int* s) { for(int i=0;i<num_of_terms;i++) { coe[i]=s[i]; } } void PolySeq::set_exp(int* s) { for(int i=0;i<num_of_terms;i++) { exp[i]=s[i]; } } PolySeq PolySeq::operator -(PolySeq p) { int a; a=num_of_terms; PolySeq result; int i=a-1; int j=p.get_num_of_terms()-1; int b=p.get_num_of_terms()-a; while(i>=0&&j>=0) { result.coe[i]=coe[i]-p.coe[j]; i--; j--; } if(b>0) { result.coe[j]=0-p.coe[j]; result.set_num(b+a); } for(i;i>=0;i--) { result.coe[i]=coe[i]; result.set_num(a); } return result; } PolySeq PolySeq::operator *(PolySeq p) { int a,b,i,j; a=num_of_terms; b=p.get_num_of_terms(); PolySeq result; for(i=0;i<100;i++) { result.coe[i]=0; } for(i=0;i<a;i++) {for(j=0;j<b;j++) { result.coe[i+j]+=coe[i]*p.coe[j]; } } result.set_num(i+j-1); return result; } int PolySeq::GetValue(int x) { int a=num_of_terms,sum[100]={0},result=0,i,j; for(i=0;i<a;i++) { sum[i]+=coe[i]; for(j=a-1;j>i;j--) { sum[i]*=x; } result+=sum[i]; } return result; }
true
b78e75c0ccfa1db04acb69efae633c2388efe8cc
C++
suchyba/ZadanieZAlgorytmow4
/ASD4/main.cpp
WINDOWS-1250
6,333
2.921875
3
[]
no_license
#include <iostream> #include <string> #include <sstream> #include <vector> #include <fstream> #include "BCD.h" #include "main.h" #include "BCDstruct.h" #include "Wypisywanie.h" #include "Menu.h" #include <conio.h> using namespace std; int main() { fstream plikIn, plikOut; wezelBST* ang = NULL, * pol = NULL; bool koniec = false; while (!koniec) { switch (mainMenu()) { case 0: // ustawianie stanow poczatkowych { switch (menuStart()) { case 0: // wypelnianie pliku angielskimu slowkami { plikIn.open("In0402.txt"); plikOut.open("Out0402.txt"); while (!plikIn.eof()) { string ciag; plikIn >> ciag; if (!ang) { ang = new wezelBST; ang->key = ciag; } else { wezelBST* w = new wezelBST(); w->key = ciag; dodaj(ang, w); } } porzadekKLP_Plik(ang, &plikOut); cout << "\nTeraz uzupelnij plik Out0402.txt o polskie tluamczenia." << endl; cout << "Nacisnij dowolny klawisz by kontynuowac..." << endl; _getch(); plikIn.close(); plikOut.close(); break; } case 1: // wczytywanie obu slownikow { plikIn.open("Out0402.txt"); while (!plikIn.eof()) { string angielskie, polskie; plikIn >> angielskie >> polskie; wezelBST* wang = new wezelBST(); wezelBST* wpol = new wezelBST(); wang->key = angielskie; wpol->key = polskie; wang->tlumaczenie = wpol; wpol->tlumaczenie = wang; if (!ang) { ang = wang; } else { dodaj(ang, wang); } if (!pol) { pol = wpol; } else { dodaj(pol, wpol); } } cout << "\nWczytano!" << endl; cout << "Nacisnij dowolny klawisz by kontynuowac..." << endl; _getch(); plikIn.close(); break; } case -1: { break; } } break; } case 1: //wyswietlanie w porzadku KLP { switch (menuWypisywanie()) { case 0: { system("cls"); cout << "\t\tSlownik angielsko-polski w porzadku KLP" << endl; cout << "\t#######################################################" << endl; porzadekKLP_tlumaczenia(ang); break; } case 1: { system("cls"); cout << "\t\tSlownik polsko-angielski w porzadku KLP" << endl; cout << "\t#######################################################" << endl; porzadekKLP_tlumaczenia(pol); break; } case -1: { break; } } cout << "\nNacisnij dowolny klawisz by kontynuowac..." << endl; _getch(); break; } case 2: // wyszukiwanie w sowniku { string szukane; switch (menuZnajdzSlowo(&szukane)) { case -1: { break; } case 0: { // polskie wezelBST* slowo = szukaj(pol, szukane); if (slowo) { cout << "\nZnaleziono slowo: " << szukane << endl; cout << "Jego tlumaczenie to: " << slowo->tlumaczenie->key << endl; } else { cout << "Nie ma takiego slowa w slowniku" << endl; } break; } case 1: { // angielskie wezelBST* slowo = szukaj(ang, szukane); if (slowo) { cout << "\nZnaleziono slowo: " << szukane << endl; cout << "Jego tlumaczenie to: " << slowo->tlumaczenie->key << endl; } else { cout << "Nie ma takiego slowa w slowniku" << endl; } break; } } cout << "\nNacisnij dowolny klawisz by kontynuowac..." << endl; _getch(); break; } case 3: // Dodawanie slowa do slownika { string angielskie, polskie; cout << "\t\tDodawanie slowa do slownika" << endl; cout << "\t############################################" << endl; cout << "Podaj angielskie slowo: "; cin >> angielskie; cout << "Podaj polskie slowo: "; cin >> polskie; wezelBST* wang = new wezelBST(); wezelBST* wpol = new wezelBST(); wang->key = angielskie; wpol->key = polskie; wang->tlumaczenie = wpol; wpol->tlumaczenie = wang; if (!ang) { ang = wang; } else { dodaj(ang, wang); } if (!pol) { pol = wpol; } else { dodaj(pol, wpol); } break; } case 4: // Usuwanie slowa ze slownika { string angielskie; int jezyk = menuUsun(&angielskie); switch (jezyk) { case 1: // angielskie { wezelBST* znalezione = szukaj(ang, angielskie); if (!znalezione) { cout << "Podane slowo nie istnieje!!!" << endl; } else { wezelBST* znalezioneTlum = znalezione->tlumaczenie; int tmpAng = usun(ang, angielskie); if (tmpAng == -1) cout << "Podane slowo nie istnieje!!!" << endl; else if (tmpAng == -2) { wezelBST* cpy = ang; ang = usunKorzen(cpy); } int tmpPol = usun(pol, znalezioneTlum->key); if (tmpPol == -1) cout << "Podane slowo nie istnieje!!!" << endl; else if (tmpPol == -2) { wezelBST* cpy = pol; pol = usunKorzen(cpy); } } break; } case 0: // polskie { wezelBST* znalezione = szukaj(pol, angielskie); if (!znalezione) { cout << "Podane slowo nie istnieje!!!" << endl; } else { wezelBST* znalezioneTlum = znalezione->tlumaczenie; int tmpPol = usun(pol, angielskie); if (tmpPol == -1) cout << "Podane slowo nie istnieje!!!" << endl; else if (tmpPol == -2) { wezelBST* cpy = pol; pol = usunKorzen(cpy); } int tmpAng = usun(ang, znalezioneTlum->key); if (tmpAng == -1) cout << "Podane slowo nie istnieje!!!" << endl; else if (tmpAng == -2) { wezelBST* cpy = ang; ang = usunKorzen(cpy); } } break; } } cout << "\nNacisnij dowolny klawisz by kontynuowac..." << endl; _getch(); break; } case -1: { koniec = true; break; } } } return 0; }
true
9596849fcd5f59717f9659d180c9f6bd8a322736
C++
mertsaner/Algorithms
/HackerRank/search/bilboards.cpp
UTF-8
809
2.734375
3
[]
no_license
#include <iostream> #include <vector> #include <deque> using namespace std; int main() { int N,K; cin >> N >> K; long long sum=0; vector<long long> c(N+1), dp(N+1); deque<long long> dpQ; for(int i=0;i<N;i++) cin >> c[i], sum+=c[i]; if(K==N) { cout << sum << endl; return 0; } for(int i=0;i<K+1;i++) { dp[i] = c[i]; while(!dpQ.empty() && dp[i]<=dp[dpQ.back()]) dpQ.pop_back(); dpQ.push_back(i); } for(int i=K+1;i<N;i++) { dp[i] = c[i] + dp[dpQ.front()]; while(!dpQ.empty() && dp[i]<=dp[dpQ.back()]) dpQ.pop_back(); while(!dpQ.empty() && dpQ.front() < i-K) dpQ.pop_front(); dpQ.push_back(i); } cout << sum-dp[dpQ.front()] << endl; return 0; }
true
fe5f981b95ed222d25e4ceffb534046035cf40d1
C++
tomzhang/blackhole
/src/blackhole/repository/config/base.hpp
UTF-8
825
2.75
3
[ "MIT" ]
permissive
#pragma once #include <string> #include <boost/variant.hpp> #include "blackhole/dynamic.hpp" namespace blackhole { namespace repository { namespace config { class base_t { std::string type_; dynamic_t::object_t config_; public: base_t(std::string type) : type_(std::move(type)) {} const std::string& type() const { return type_; } const dynamic_t::object_t& config() const { return config_; } void config(dynamic_t::object_t value) { config_ = std::move(value); } dynamic_t& operator[](const std::string& key) { return config_[key]; } const dynamic_t& operator[](const std::string& key) const { return config_.at(key); } }; } // namespace config } // namespace repository } // namespace blackhole
true
ba2f73c0f186127e6c97bac3e53958f050343dad
C++
flight7788/3d-printing-with-moveo-1
/Cura/CuraEngine/src/infill/SubDivCube.h
UTF-8
5,338
2.78125
3
[ "GPL-3.0-only", "AGPL-3.0-only" ]
permissive
//Copyright (c) 2018 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef INFILL_SUBDIVCUBE_H #define INFILL_SUBDIVCUBE_H #include "../settings/types/Ratio.h" #include "../utils/IntPoint.h" #include "../utils/Point3.h" namespace cura { struct LayerIndex; class Polygons; class SliceMeshStorage; class SubDivCube { public: /*! * Constructor for SubDivCube. Recursively calls itself eight times to flesh out the octree. * \param mesh contains infill layer data and settings * \param my_center the center of the cube * \param depth the recursion depth of the cube (0 is most recursed) */ SubDivCube(SliceMeshStorage& mesh, Point3& center, size_t depth); ~SubDivCube(); //!< destructor (also destroys children) /*! * Precompute the octree of subdivided cubes * \param mesh contains infill layer data and settings */ static void precomputeOctree(SliceMeshStorage& mesh); /*! * Generates the lines of subdivision of the specific cube at the specific layer. It recursively calls itself, so it ends up drawing all the subdivision lines of sub-cubes too. * \param z the specified layer height * \param result (output) The resulting lines */ void generateSubdivisionLines(const coord_t z, Polygons& result); private: /*! * Generates the lines of subdivision of the specific cube at the specific layer. It recursively calls itself, so it ends up drawing all the subdivision lines of sub-cubes too. * \param z the specified layer height * \param result (output) The resulting lines * \param directional_line_groups Array of 3 times a polylines. Used to keep track of line segments that are all pointing the same direction for line segment combining */ void generateSubdivisionLines(const coord_t z, Polygons& result, Polygons (&directional_line_groups)[3]); struct CubeProperties { coord_t side_length; //!< side length of cubes coord_t height; //!< height of cubes based. This is the distance from one point of a cube to its 3d opposite. coord_t square_height; //!< square cut across lengths. This is the diagonal distance across a face of the cube. coord_t max_draw_z_diff; //!< maximum draw z differences. This is the maximum difference in z at which lines need to be drawn. coord_t max_line_offset; //!< maximum line offsets. This is the maximum distance at which subdivision lines should be drawn from the 2d cube center. }; /*! * Rotates a point 120 degrees about the origin. * \param target the point to rotate. */ static void rotatePoint120(Point& target); /*! * Rotates a point to align it with the orientation of the infill. * \param target the point to rotate. */ static void rotatePointInitial(Point& target); /*! * Determines if a described theoretical cube should be subdivided based on if a sphere that encloses the cube touches the infill mesh. * \param mesh contains infill layer data and settings * \param center the center of the described cube * \param radius the radius of the enclosing sphere * \return the described cube should be subdivided */ static bool isValidSubdivision(SliceMeshStorage& mesh, Point3& center, coord_t radius); /*! * Finds the distance to the infill border at the specified layer from the specified point. * \param mesh contains infill layer data and settings * \param layer_nr the number of the specified layer * \param location the location of the specified point * \param[out] distance2 the squared distance to the infill border * \return Code 0: outside, 1: inside, 2: boundary does not exist at specified layer */ static coord_t distanceFromPointToMesh(SliceMeshStorage& mesh, const LayerIndex layer_nr, Point& location, coord_t* distance2); /*! * Adds the defined line to the specified polygons. It assumes that the specified polygons are all parallel lines. Combines line segments with touching ends closer than epsilon. * \param[out] group the polygons to add the line to * \param from the first endpoint of the line * \param to the second endpoint of the line */ void addLineAndCombine(Polygons& group, Point from, Point to); size_t depth; //!< the recursion depth of the cube (0 is most recursed) Point3 center; //!< center location of the cube in absolute coordinates SubDivCube* children[8] = {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}; //!< pointers to this cube's eight octree children static std::vector<CubeProperties> cube_properties_per_recursion_step; //!< precomputed array of basic properties of cubes based on recursion depth. static Ratio radius_multiplier; //!< multiplier for the bounding radius when determining if a cube should be subdivided static Point3Matrix rotation_matrix; //!< The rotation matrix to get from axis aligned cubes to cubes standing on a corner point aligned with the infill_angle static PointMatrix infill_rotation_matrix; //!< Horizontal rotation applied to infill static coord_t radius_addition; //!< addition to the bounding radius when determining if a cube should be subdivided }; } #endif //INFILL_SUBDIVCUBE_H
true
e9be5469e35aa52f871b69341a4c9fd86dbf326e
C++
EdsonYamamoto/URI-Online-Judge-Beginner
/1015.cpp
UTF-8
1,189
3.3125
3
[]
no_license
/* URI Online Judge | 1015 Distância Entre Dois Pontos Adaptado por Neilor Tonin, URI Brasil Timelimit: 1 Leia os quatro valores correspondentes aos eixos x e y de dois pontos quaisquer no plano, p1(x1,y1) e p2(x2,y2) e calcule a distância entre eles, mostrando 4 casas decimais após a vírgula, segundo a fórmula: Distancia = Entrada O arquivo de entrada contém duas linhas de dados. A primeira linha contém dois valores de ponto flutuante: x1 y1 e a segunda linha contém dois valores de ponto flutuante x2 y2. Saída Calcule e imprima o valor da distância segundo a fórmula fornecida, com 4 casas após o ponto decimal. Exemplo de Entrada Exemplo de Saída 1.0 7.0 5.0 9.0 4.4721 -2.5 0.4 12.1 7.3 16.1484 2.5 -0.4 -12.2 7.0 16.4575 */ #include <iostream> #include <stdio.h> /* printf */ #include <math.h> /* pow */ /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char** argv) { double x1, y1, x2, y2, Distancia; scanf("%lf",&x1); scanf("%lf",&y1); scanf("%lf",&x2); scanf("%lf",&y2); Distancia = sqrt(pow(x2-x1,2)+pow(y2-y1,2)); printf("%.4lf\n",Distancia ); return 0; }
true
32baec8e3fe70b8fcb41011996aff5a8db705c5d
C++
pandakkkk/DataStructures-Algorithms
/Graphs/Traversal on Graphs/Breadth First Search/1557. Minimum Number of Vertices to Reach All Nodes.cpp
UTF-8
701
3.34375
3
[]
no_license
// 1557. Minimum Number of Vertices to Reach All Nodes //? Graphs | Mother Vertex | OutDegree #include <bits/stdc++.h> using namespace std; /* * A node that does not have any incoming edge can only be reached by itself. * Any other node with incoming edges can be reached from some other node. * We only have to count the number of nodes with zero incoming edges. */ class Solution { public: vector<int> findSmallestSetOfVertices(int n, vector<vector<int>> &edges) { vector<int> outdegree(n, 0), result; for (vector<int> &edge : edges) outdegree[edge[1]]++; for (int i = 0; i < n; i++) if (outdegree[i] == 0) result.push_back(i); return result; } };
true
ee3e9aa2fe22fd814d67430a40619fbb6794f28e
C++
wenqicao/algorithm-sec2
/8_15.cpp
UTF-8
1,546
3.375
3
[]
no_license
#include <iostream> #include <memory> using namespace std; template<class T> struct ListNode{ T data; shared_ptr<ListNode<T>> next; }; shared_ptr<ListNode<int>> reverse_list(shared_ptr<ListNode<int>> head){ shared_ptr<ListNode<int>> cur = head, pre = nullptr; while(cur){ shared_ptr<ListNode<int>> temp = cur->next; cur->next = pre; pre = cur; cur = temp; } return pre; } bool is_parlidrom(shared_ptr<ListNode<int>> head){ shared_ptr<ListNode<int>> fast = head, slow = head; while(fast){ fast=fast->next; if(fast){ fast=fast->next; slow=slow->next; } } shared_ptr<ListNode<int>> reverse_head = reverse_list(slow); while(reverse_head&&head){ if(reverse_head->data != head->data){ return false; } reverse_head=reverse_head->next; head=head->next; } return true; } int main(){ shared_ptr<ListNode<int>> n1 = make_shared<ListNode<int>>(ListNode<int>{1,nullptr}); shared_ptr<ListNode<int>> n2 = make_shared<ListNode<int>>(ListNode<int>{2,nullptr}); shared_ptr<ListNode<int>> n3 = make_shared<ListNode<int>>(ListNode<int>{3,nullptr}); shared_ptr<ListNode<int>> n4 = make_shared<ListNode<int>>(ListNode<int>{4,nullptr}); shared_ptr<ListNode<int>> n5 = make_shared<ListNode<int>>(ListNode<int>{3,nullptr}); shared_ptr<ListNode<int>> n6 = make_shared<ListNode<int>>(ListNode<int>{2,nullptr}); shared_ptr<ListNode<int>> n7 = make_shared<ListNode<int>>(ListNode<int>{1,nullptr}); n1->next = n2; n2->next = n3; n3->next = n4; n4->next = n5; n5->next = n6; n6->next = n7; cout<<is_parlidrom(n1); }
true
1090efaca28add0c434b30dbe71fffe90e42f764
C++
tanmay017/Data-Structure-and-Algorithms-Learning
/14. Trees/const_bin_tree_ino_pre0.cpp
UTF-8
1,085
3.53125
4
[]
no_license
#include <bits/stdc++.h> //This code is for problem construct binary tree from Inorder and Postorder using namespace std; struct Node { int key; Node *left; Node *right; Node(int k) { key = k; left = right = NULL; } }; Node *cTree(int in[], int pre[], int is, int ie) { if (is > ie) return NULL; static int preIndex = 0; //can be also used global variable Node *root = new Node(pre[preIndex++]); int inIndex; for (int i = is; i <= ie; i++) { if (root->key == in[i]) { inIndex = i; break; } } root->left = cTree(in, pre, is, inIndex - 1); root->right = cTree(in, pre, inIndex + 1, ie); return root; } void inorder(Node *root) { if (root != NULL) { inorder(root->left); cout << root->key << " "; inorder(root->right); } } int main() { int in[] = {20, 10, 40, 30, 50}; int pre[] = {10, 20, 30, 40, 50}; int n = sizeof(in) / sizeof(in[0]); Node *root = cTree(in, pre, 0, n - 1); inorder(root); }
true
74ca5809056e5cc39222833c9ee219aa524591ae
C++
Mtaylorr/PIE-Olympie
/PathFinding/headers/astar.h
UTF-8
474
2.578125
3
[]
no_license
#pragma once #include <vector> #include "grid.h" #include "node.h" class AStar { private: static constexpr float SQRT_2 = 1.41421356237f; public: Grid& grid; private: int widthNodes, heightNodes; Node** nodes; std::vector<Node*> priority; public: std::vector<Node*> explored; public: AStar(Grid& grid); ~AStar(); std::vector<std::pair<int, int>> findPath(int xstart, int ystart, int xend, int yend); private: void resetNodes(); void deleteNodes(); };
true
7d251ede37a9074e2603ed8df97abb537a80cbb7
C++
BramLachat/GPGPU
/RT_TT_CGAL/Mesh.cpp
UTF-8
2,309
3.0625
3
[]
no_license
#include <vector> #include <string> #include <iostream> #include <iterator> #include <map> #include <fstream> #include <chrono> #include <algorithm> #include "omp.h" #include "Mesh.h" Mesh::Mesh(std::string n, unsigned int size) { name = n; triangles.reserve(size); vertices.reserve(size); } std::string Mesh::getName() { return name; } int Mesh::getNumberOfTriangles() { return triangles.size(); } int Mesh::getNumberOfVertices() { return vertices.size(); } void Mesh::addTriangle(const Triangle& t) { triangles.push_back(t); } void Mesh::addVertex(const Point& v) { vertices.push_back(v); } int Mesh::findDuplicate(const Point& v) { std::map<std::string, int>::iterator itr = VertexIndices.find(std::to_string(v[0]) + std::to_string(v[1]) + std::to_string(v[2])); if (itr != VertexIndices.end()) { return itr->second; } else { return -1; } } int Mesh::getLastVertex() { return (vertices.size() - 1); } Point* Mesh::getVertexAtIndex(int index) { return &(vertices.at(index)); } void Mesh::resize() { vertices.shrink_to_fit(); } void Mesh::addVertexIndex(const std::string& s, int index) { VertexIndices.insert(std::pair<std::string, int>(s, index)); } std::list<Point> Mesh::getPointList() { std::list<Point> result(vertices.begin(), vertices.end()); return result; } std::list<Triangle> Mesh::getTriangleList() { std::list<Triangle> result(triangles.begin(), triangles.end()); return result; } /*int3* Mesh::getInt3ArrayTriangles() { int3* triangleArray; cudaError_t status = cudaHostAlloc((void**)&triangleArray, triangles.size() * sizeof(int3), cudaHostAllocDefault); if (status != cudaSuccess) printf("Error allocating pinned host memory\n"); //int3* triangleArray = new int3[triangles.size()]; for (int i = 0; i < triangles.size(); i++) { triangleArray[i] = triangles[i].getIndexOfVerticesInMesh(); } return triangleArray; } float3* Mesh::getFloat3ArrayVertices() { float3* vertexArray; cudaError_t status = cudaHostAlloc((void**)&vertexArray, vertices.size() * sizeof(float3), cudaHostAllocDefault); if (status != cudaSuccess) printf("Error allocating pinned host memory\n"); //float3* vertexArray = new float3[vertices.size()]; for (int i = 0; i < vertices.size(); i++) { vertexArray[i] = vertices[i].getCoordinatesFloat3(); } return vertexArray; }*/
true
678a29c0a35f51614e6391d539687868ac0bbb36
C++
avoropay/action_video
/RunWith2Speed/RunWith2Speed.ino
UTF-8
1,943
2.578125
3
[]
no_license
#include <AccelStepper.h> // For arduino speed up #define FASTADC 1 // defines for setting and clearing register bits #ifndef cbi #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit)) #endif #ifndef sbi #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit)) #endif // For arduino speed up end // Define some steppers and the pins the will use AccelStepper stepper1(1, 4, 5); // stepP, dirP AccelStepper stepper2(1, 6, 7); float round_speed1 = 0.0; float correction1 = 3.0; float round_speed2 = 0.0; float correction2 = 3.0; #define speedPinRead1 A0 #define speedPinRead2 A2 void setup() { // For arduino speed up #if FASTADC // set prescale to 16 sbi(ADCSRA,ADPS2) ; cbi(ADCSRA,ADPS1) ; cbi(ADCSRA,ADPS0) ; #endif // For arduino speed up end pinMode(speedPinRead1, INPUT); pinMode(speedPinRead2, INPUT); stepper1.setMaxSpeed(1000.0); stepper2.setMaxSpeed(1000.0); stepper1.setSpeed(0.0); stepper2.setSpeed(0.0); } void loop() { float djoistik1 = analogRead(speedPinRead1); if(djoistik1 > 522.0){ round_speed1 = (djoistik1 - 512.0) * correction1; stepper1.setSpeed(round_speed1); stepper1.setDirection(false); }else if(djoistik1 < 500){ round_speed1 = (512.0 - djoistik1) * correction1; stepper1.setSpeed(round_speed1); stepper1.setDirection(true); }else{ round_speed1 = 0.0; stepper1.setSpeed(round_speed1); } float djoistik2 = analogRead(speedPinRead2); if(djoistik2 > 530.0){ round_speed2 = (djoistik2 - 512.0) * correction2; stepper2.setSpeed(round_speed2); stepper2.setDirection(false); }else if(djoistik2 < 500){ round_speed2 = (512.0 - djoistik2) * correction2; stepper2.setSpeed(round_speed2); stepper2.setDirection(true); }else{ round_speed2 = 0.0; stepper2.setSpeed(round_speed2); } stepper1.runSpeed(); stepper2.runSpeed(); }
true
13918c9acea733bf6357b09b164a8d29c6666063
C++
benjaminhuanghuang/ben-leetcode
/1455_Check_If_a_Word_Occurs_As_a_Prefix_of_Any_Word_in_a_Sentence/solution.cpp
UTF-8
950
3.46875
3
[]
no_license
/* 1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence Level: Easy https://leetcode.com/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence */ #include <vector> #include <string> #include <sstream> // stringstream, getline #include "common/ListNode.h" #include "common/TreeNode.h" using namespace std; /* Solution: C++没有自带的切割字符串的方法,可以用stringstream实现分割,O(N)的复杂度. */ class Solution { public: vector<string> splitSentence(const string &text) { string tmp; vector<string> words; stringstream ss(text); while (getline(ss, tmp, ' ')) { words.push_back(tmp); } return words; } int isPrefixOfWord(string sentence, string searchWord) { auto words = splitSentence(sentence); for (int i = 0; i < words.size(); ++i) { if (words[i].find(searchWord) == 0) return i + 1; } return -1; } };
true
5bb33b2f86ad78f38797d75310d1f71b0ab2f298
C++
snewell/bureaucracy
/include/bureaucracy/timer.hpp
UTF-8
7,429
3.3125
3
[ "BSD-2-Clause" ]
permissive
#ifndef BUREAUCRACY_TIMER_HPP #define BUREAUCRACY_TIMER_HPP 1 #include <condition_variable> #include <functional> #include <mutex> #include <thread> #include <unordered_map> #include <vector> namespace bureaucracy { /** \brief A class that triggers Events at certain times. * * A Timer manages a list of Events that should be fired at specific * times. Timer will invoke an Event as close to the requested time as * possible but makes no guarantees regarding the level of precision or * delta. * * \warning The precision of Timer is dependent on the implementation of * the chrono library. This should be sufficient for most uses * but projects that require precise timing should use a * different timer implementation. */ class Timer { public: /// \brief An Item added to a Timer. class Item { friend class Timer; public: /// \brief An Identifier for an Item. using Id = std::uint64_t; /// \brief Current status of an Item. enum class Status { queued, ///< the Item is queued firing, ///< the Item is firing or about to be fired complete ///< the Item has been fired or cancelled }; /// \brief Result of a call to cancel. enum class CancelStatus { cancelled, ///< the Item was cancelled failed ///< the cancel operation failed }; /** \brief Construct an Item. * * \internal * * \param [in] timer * the Timer associated with this Item * * \param [in] id * the Id of this Item */ Item(Timer * timer, Id id); private: Timer * const my_timer; Id const my_id; }; /** \brief A function a Timer can invoke. * * \warning An Event should ideally be a very minimal function that * cannot block to avoid delaying firing of other Events. If * an Event requires complex work consider using the Event to * feed work into a Worker. */ using Event = std::function<void()>; /// \brief A point in time when an Event can be invoked. using Time = std::chrono::time_point<std::chrono::steady_clock>; /// \brief Construct a Timer Timer(); /** \brief Add an Event that fires at a specific time. * * Add \p event to the Timer and invoke it as close to \p due as * possible. * * \param [in] event * an Event to fire when it's \p due * * \param [in] due * an exact (not relative) time to invoke \p event * * \note If \p due is in the past \p event will be fired the next time * the Timer executes Events. */ Item add(Event event, Time due); /** \brief Add an Event that fires at a specific time. * * Add \p event to the Timer and invoke it as close to \p due as * possible. This is a helper function if \p due is not a Time. * * \param [in] event * an Event to fire when it's \p due * * \param [in] due * An exact (not relative) time to invoke \p event. This will be * converted to a Time. * * \note If \p due is in the past \p event will be fired the next time * the Timer executes Events. */ template <typename CLOCK> Item add(Event event, std::chrono::time_point<CLOCK> due); /** \brief Add an Event that fires after a delay. * * Add \p event that fires in \p delay. This function is equivalent * to using the the Time version of add where \p due is `now() + due`. * * \param [in] event * an Event to fire after \p delay time * * \param [in] delay * a duration to wait * * \note If \p delay is negative \p event will be fired the next time * the Timer executes Events. */ template <typename... ARGS> Item add(Event event, std::chrono::duration<ARGS...> delay); /** \brief Stop accepting Events and terminate the Timer thread * * \note Any scheduled Events will _not_ be called. * * \warning Calling stop from multiple threads is undefined behavior. * * \warning Calling stop from an Event invoked by that Timer is * undefined behavior. */ void stop(); /** \brief Determine if this Timer is accepting new Events. * * \retval true this Timer is accepting new Events * \retval false this Timer is not accepting new Events */ bool isAccepting() const noexcept; /** \brief Determine if this Timer's thread is running. * * \retval true this Timer's thread is running * \retval false this Timer's thread is not running */ bool isRunning() const noexcept; /** \brief Cancel an Item if possible. * * This can fail if: * * this Item is current firing * * this Item is queued to fire (i.e., its delay has expired and * has already been flagged for processing) * * \retval CancelStatus::cancelled * This Item was cancelled successfully. * * \retval CancelStatus::failed * This Item was not cancelled. */ Item::CancelStatus cancel(Timer::Item item); /// \cond false ~Timer() noexcept; Timer(Timer const &) = delete; Timer(Timer &&) noexcept = delete; Timer & operator=(Timer const &) = delete; Timer & operator=(Timer &&) = delete; /// \endcond private: std::thread my_timerThread; mutable std::mutex my_mutex; std::condition_variable my_wakeup; std::unordered_map<Item::Id, Event> my_events; struct FutureEvent { Item::Id event; Time due; }; using FutureEvents = std::vector<FutureEvent>; FutureEvents my_futureEvents; struct PendingEvent { Item::Id event; Time due; Event fn; }; std::vector<PendingEvent> my_pendingEvents; FutureEvents::iterator my_nextFuture; Item::Id my_nextId; bool my_isAccepting; bool my_isRunning; bool my_isFiring; }; template <typename CLOCK> inline Timer::Item Timer::add(Event event, std::chrono::time_point<CLOCK> due) { auto const delay = due - CLOCK::now(); return add(std::move(event), delay); } template <typename... ARGS> inline Timer::Item Timer::add(Event event, std::chrono::duration<ARGS...> delay) { return add(std::move(event), std::chrono::steady_clock::now() + delay); } } // namespace bureaucracy #endif
true
9f52e358c27554ea5f88359aeaa8b3f605ec8246
C++
Oh-kyung-tak/Algorithm
/Baekjoon/baekjoon_15786.cpp
UTF-8
416
3.078125
3
[]
no_license
#include<iostream> #include<set> #include<algorithm> #include<string> using namespace std; int n, m; string word; int main() { scanf("%d %d", &n, &m); cin >> word; while (m--) { int count = 0; string pass; cin >> pass; for (int i = 0; i < pass.size(); i++) { if (word[count] == pass[i]) count++; } if (count == n) cout << "true" << endl; else cout << "false" << endl; } }
true
b4ff7500d14e3e0fb7f9dc709ebe3a5a30e343a7
C++
FashionDB/lockfree
/C++11/rbq.hpp
UTF-8
6,032
2.90625
3
[]
no_license
#include <atomic> #ifndef __LOCKFREE_RBQ_MPMC_H__ #define __LOCKFREE_RBQ_MPMC_H__ #ifdef _WIN32 #include <Windows.h> #ifdef __cplusplus extern "C" { #endif static inline void usleep(__int64 usec) { HANDLE timer; LARGE_INTEGER ft; ft.QuadPart = -(10 * usec); timer = CreateWaitableTimer(NULL, TRUE, NULL); SetWaitableTimer(timer, &ft, 0, NULL, NULL, 0); WaitForSingleObject(timer, INFINITE); CloseHandle(timer); } static inline int sched_yield() { SwitchToThread(); return (0); } #ifdef __cplusplus }; #endif #else #include <sched.h> #include <unistd.h> #endif // _WIN32 constexpr uint32_t STATUS_EMPT = 0; constexpr uint32_t STATUS_FILL = 1; constexpr uint32_t STATUS_READ = 2; constexpr uint32_t STATUS_FULL = 3; template <typename T> class rbqueue { struct alignas(64) rbnode { std::atomic<uint32_t> status; T object; rbnode() { status.store(STATUS_EMPT); }; }; protected: alignas(64) std::atomic<uint64_t> head; alignas(64) std::atomic<uint64_t> tail; size_t size; rbnode * data; rbqueue() { ; }; public: rbqueue(int order) { size = (1ULL << order); data = new rbnode[size]; head.store(0); tail.store(0); }; virtual ~rbqueue() { delete[] data; }; inline bool isfull() { uint64_t _tail = tail.load(std::memory_order_relaxed); uint64_t _head = head.load(std::memory_order_relaxed); return (_tail >= (_head + size)); }; inline bool isempty() { uint64_t _tail = tail.load(std::memory_order_relaxed); uint64_t _head = head.load(std::memory_order_relaxed); return (_head >= _tail); }; inline size_t getsize() { return size; }; inline bool push(const T & object) { uint64_t currReadIndexA, currWriteIndex, nextWriteIndex; // do { // check if queue full currWriteIndex = tail.load(std::memory_order_relaxed); currReadIndexA = head.load(std::memory_order_relaxed); if (currWriteIndex >= (currReadIndexA + size)) { return false; } // now perfrom the FAA operation on the write index. // the Space @ currWriteIndex will be reserved for us. nextWriteIndex = tail.fetch_add(1); currWriteIndex = nextWriteIndex & (size - 1); } // while (1); // We know now that space @ currWriteIndex is reserved for us. // In case of slow reader, we use CAS to ensure a correct data swap rbnode * pnode = data + currWriteIndex; uint32_t S0 = STATUS_EMPT; while (!pnode->status.compare_exchange_weak(S0, STATUS_FILL)) { S0 = STATUS_EMPT; usleep((currWriteIndex & 1) + 1); } /* fill - exclusive */ pnode->object = object; /* done - update status */ pnode->status.store(STATUS_FULL, std::memory_order_release); return true; }; /* pop @ mutiple consumers */ inline bool pop(T & object) { uint64_t currWritIndex, currReadIndex, nextReadIndex; // do { // check if queue empty currReadIndex = head.load(std::memory_order_relaxed); currWritIndex = tail.load(std::memory_order_relaxed); if (currReadIndex >= currWritIndex) { return false; } // now perfrom the FAA operation on the read index. // the Space @ currReadIndex will be reserved for us. nextReadIndex = head.fetch_add(1); currReadIndex = nextReadIndex & (size - 1); } // while(1); // We know now that space @ currReadIndex is reserved for us. // In case of slow writer, we use CAS to ensure a correct data swap rbnode * pnode = data + currReadIndex; uint32_t S0 = STATUS_FULL; while (!pnode->status.compare_exchange_weak(S0, STATUS_READ)) { S0 = STATUS_FULL; usleep((currReadIndex & 1) + 1); } /* read - exclusive */ object = pnode->object; /* done - update status */ pnode->status.store(STATUS_EMPT, std::memory_order_release); /* return - data */ return true; }; /* pop @ mutiple consumers */ inline T pop() { uint64_t currWritIndex, currReadIndex, nextReadIndex; // do { // check if queue empty currReadIndex = head.load(std::memory_order_relaxed); currWritIndex = tail.load(std::memory_order_relaxed); if (currReadIndex >= currWritIndex) { return (T(0)); } // now perfrom the FAA operation on the read index. // the Space @ currReadIndex will be reserved for us. nextReadIndex = head.fetch_add(1); currReadIndex = nextReadIndex & (size - 1); } // while(1); // We know now that space @ currReadIndex is reserved for us. // In case of slow writer, we use CAS to ensure a correct data swap rbnode* pnode = data + currReadIndex; uint32_t S0 = STATUS_FULL; while (!pnode->status.compare_exchange_weak(S0, STATUS_READ)) { S0 = STATUS_FULL; usleep((currReadIndex & 1) + 1); } /* read - exclusive */ T object(pnode->object); /* done - update status */ pnode->status.store(STATUS_EMPT, std::memory_order_release); /* return - data */ return object; }; /* push @ single producer single consumer */ inline bool pushspsc(const T & object) { uint64_t currWriteIndex = tail.load(std::memory_order_relaxed); uint64_t currReadIndexA = head.load(std::memory_order_relaxed); if (currWriteIndex >= (currReadIndexA + size)) { return false; } data[currWriteIndex & (size - 1)].object = object; tail.store(currWriteIndex + 1, std::memory_order_relaxed); return true; } /* pop @ single producer single consumer */ inline bool popspsc(T & object) { uint64_t currReadIndex = head.load(std::memory_order_relaxed); uint64_t currWritIndex = tail.load(std::memory_order_relaxed); if (currReadIndex >= currWritIndex) { return false; }; object = data[currReadIndex & (size - 1)].object; head.store(currReadIndex + 1, std::memory_order_relaxed); return (true); }; /* pop @ single producer single consumer */ inline T popspsc() { uint64_t currReadIndex = head.load(std::memory_order_relaxed); uint64_t currWritIndex = tail.load(std::memory_order_relaxed); if (currReadIndex >= currWritIndex) { return false; }; T object(data[currReadIndex & (size - 1)].object); head.store(currReadIndex + 1, std::memory_order_relaxed); return (object); }; }; #endif
true
54b6f793df336a4311c77696455f6b77d1c22934
C++
RobertCFletcher/Zoo_Tycoon
/tiger.hpp
UTF-8
603
2.609375
3
[]
no_license
/***************************************************************************************************************** **Name: Robert Fletcher **Course: CS162 **Date: 02/04/2018 **Description: Project 2 - Header file for the tiger class. *******************************************************************************************************************/ #include "animal.hpp" #ifndef TIGER_HPP #define TIGER_HPP class tiger : public animal { private: int numberOfBabies; int cost; int payoff; int feedingCostMultiplier; protected: public: tiger(); int getFeedingCost(); }; #endif
true
49fe801c142c4457107e1ac578fcb24faad57458
C++
ngminteck/DigipenGAM200GAM250
/GAM200AndGAM250/ChestNutEngine/Matrix4x4.cpp
UTF-8
10,786
3.140625
3
[]
no_license
#include "Matrix4x4.h" #include <iomanip> Matrix4x4::Matrix4x4() { identity(); } Matrix4x4::Matrix4x4(const float src[16]) { set(src); } Matrix4x4::Matrix4x4(float m00, float m01, float m02, float m03, float m04, float m05, float m06, float m07, float m08, float m09, float m10, float m11, float m12, float m13, float m14, float m15) { set(m00, m01, m02, m03, m04, m05, m06, m07, m08, m09, m10, m11, m12, m13, m14, m15); } void Matrix4x4::set(const float src[16]) { m[0] = src[0]; m[1] = src[1]; m[2] = src[2]; m[3] = src[3]; m[4] = src[4]; m[5] = src[5]; m[6] = src[6]; m[7] = src[7]; m[8] = src[8]; m[9] = src[9]; m[10] = src[10]; m[11] = src[11]; m[12] = src[12]; m[13] = src[13]; m[14] = src[14]; m[15] = src[15]; } void Matrix4x4::set(float m00, float m01, float m02, float m03, float m04, float m05, float m06, float m07, float m08, float m09, float m10, float m11, float m12, float m13, float m14, float m15) { m[0] = m00; m[1] = m01; m[2] = m02; m[3] = m03; m[4] = m04; m[5] = m05; m[6] = m06; m[7] = m07; m[8] = m08; m[9] = m09; m[10] = m10; m[11] = m11; m[12] = m12; m[13] = m13; m[14] = m14; m[15] = m15; } const float* Matrix4x4::get() const { return m; } Matrix4x4& Matrix4x4::identity() { m[0] = m[5] = m[10] = m[15] = 1.0f; m[1] = m[2] = m[3] = m[4] = m[6] = m[7] = m[8] = m[9] = m[11] = m[12] = m[13] = m[14] = 0.0f; return *this; } Matrix4x4& Matrix4x4::translate(float x, float y, float z) { m[0] += m[3] * x; m[4] += m[7] * x; m[8] += m[11] * x; m[12] += m[15] * x; m[1] += m[3] * y; m[5] += m[7] * y; m[9] += m[11] * y; m[13] += m[15] * y; m[2] += m[3] * z; m[6] += m[7] * z; m[10] += m[11] * z; m[14] += m[15] * z; return *this; } Matrix4x4& Matrix4x4::translate(const Vector3D& v) { return translate(v.x, v.y, v.z); } Matrix4x4& Matrix4x4::rotate(float angle, float x, float y, float z) { float c = cosf(angle * DEG2RAD); // cosine float s = sinf(angle * DEG2RAD); // sine float c1 = 1.0f - c; // 1 - c float m0 = m[0], m4 = m[4], m8 = m[8], m12 = m[12], m1 = m[1], m5 = m[5], m9 = m[9], m13 = m[13], m2 = m[2], m6 = m[6], m10 = m[10], m14 = m[14]; // build rotation matrix float r0 = x * x * c1 + c; float r1 = x * y * c1 + z * s; float r2 = x * z * c1 - y * s; float r4 = x * y * c1 - z * s; float r5 = y * y * c1 + c; float r6 = y * z * c1 + x * s; float r8 = x * z * c1 + y * s; float r9 = y * z * c1 - x * s; float r10 = z * z * c1 + c; // multiply rotation matrix m[0] = r0 * m0 + r4 * m1 + r8 * m2; m[1] = r1 * m0 + r5 * m1 + r9 * m2; m[2] = r2 * m0 + r6 * m1 + r10 * m2; m[4] = r0 * m4 + r4 * m5 + r8 * m6; m[5] = r1 * m4 + r5 * m5 + r9 * m6; m[6] = r2 * m4 + r6 * m5 + r10 * m6; m[8] = r0 * m8 + r4 * m9 + r8 * m10; m[9] = r1 * m8 + r5 * m9 + r9 * m10; m[10] = r2 * m8 + r6 * m9 + r10 * m10; m[12] = r0 * m12 + r4 * m13 + r8 * m14; m[13] = r1 * m12 + r5 * m13 + r9 * m14; m[14] = r2 * m12 + r6 * m13 + r10 * m14; return *this; } Matrix4x4& Matrix4x4::rotate(float angle, const Vector3D& axis) { return rotate(angle, axis.x, axis.y, axis.z); } Matrix4x4& Matrix4x4::rotateX(float angle) { float c = cosf(angle * DEG2RAD); float s = sinf(angle * DEG2RAD); float m1 = m[1], m2 = m[2], m5 = m[5], m6 = m[6], m9 = m[9], m10 = m[10], m13 = m[13], m14 = m[14]; m[1] = m1 * c + m2 * -s; m[2] = m1 * s + m2 * c; m[5] = m5 * c + m6 * -s; m[6] = m5 * s + m6 * c; m[9] = m9 * c + m10 * -s; m[10] = m9 * s + m10 * c; m[13] = m13 * c + m14 * -s; m[14] = m13 * s + m14 * c; return *this; } Matrix4x4& Matrix4x4::rotateY(float angle) { float c = cosf(angle * DEG2RAD); float s = sinf(angle * DEG2RAD); float m0 = m[0], m2 = m[2], m4 = m[4], m6 = m[6], m8 = m[8], m10 = m[10], m12 = m[12], m14 = m[14]; m[0] = m0 * c + m2 * s; m[2] = m0 * -s + m2 * c; m[4] = m4 * c + m6 * s; m[6] = m4 * -s + m6 * c; m[8] = m8 * c + m10 * s; m[10] = m8 * -s + m10 * c; m[12] = m12 * c + m14 * s; m[14] = m12 * -s + m14 * c; return *this; } Matrix4x4& Matrix4x4::rotateZ(float angle) { float c = cosf(angle * DEG2RAD); float s = sinf(angle * DEG2RAD); float m0 = m[0], m1 = m[1], m4 = m[4], m5 = m[5], m8 = m[8], m9 = m[9], m12 = m[12], m13 = m[13]; m[0] = m0 * c + m1 * -s; m[1] = m0 * s + m1 * c; m[4] = m4 * c + m5 * -s; m[5] = m4 * s + m5 * c; m[8] = m8 * c + m9 * -s; m[9] = m8 * s + m9 * c; m[12] = m12 * c + m13 * -s; m[13] = m12 * s + m13 * c; return *this; } Matrix4x4& Matrix4x4::scale(float s) { return scale(s, s, s); } Matrix4x4& Matrix4x4::scale(float sx, float sy, float sz) { m[0] *= sx; m[4] *= sx; m[8] *= sx; m[12] *= sx; m[1] *= sy; m[5] *= sy; m[9] *= sy; m[13] *= sy; m[2] *= sz; m[6] *= sz; m[10] *= sz; m[14] *= sz; return *this; } Matrix4x4 Matrix4x4::operator+(const Matrix4x4& rhs) const { return Matrix4x4(m[0] + rhs[0], m[1] + rhs[1], m[2] + rhs[2], m[3] + rhs[3], m[4] + rhs[4], m[5] + rhs[5], m[6] + rhs[6], m[7] + rhs[7], m[8] + rhs[8], m[9] + rhs[9], m[10] + rhs[10], m[11] + rhs[11], m[12] + rhs[12], m[13] + rhs[13], m[14] + rhs[14], m[15] + rhs[15]); } Matrix4x4 Matrix4x4::operator-(const Matrix4x4& rhs) const { return Matrix4x4(m[0] - rhs[0], m[1] - rhs[1], m[2] - rhs[2], m[3] - rhs[3], m[4] - rhs[4], m[5] - rhs[5], m[6] - rhs[6], m[7] - rhs[7], m[8] - rhs[8], m[9] - rhs[9], m[10] - rhs[10], m[11] - rhs[11], m[12] - rhs[12], m[13] - rhs[13], m[14] - rhs[14], m[15] - rhs[15]); } Matrix4x4& Matrix4x4::operator+=(const Matrix4x4& rhs) { m[0] += rhs[0]; m[1] += rhs[1]; m[2] += rhs[2]; m[3] += rhs[3]; m[4] += rhs[4]; m[5] += rhs[5]; m[6] += rhs[6]; m[7] += rhs[7]; m[8] += rhs[8]; m[9] += rhs[9]; m[10] += rhs[10]; m[11] += rhs[11]; m[12] += rhs[12]; m[13] += rhs[13]; m[14] += rhs[14]; m[15] += rhs[15]; return *this; } Matrix4x4& Matrix4x4::operator-=(const Matrix4x4& rhs) { m[0] -= rhs[0]; m[1] -= rhs[1]; m[2] -= rhs[2]; m[3] -= rhs[3]; m[4] -= rhs[4]; m[5] -= rhs[5]; m[6] -= rhs[6]; m[7] -= rhs[7]; m[8] -= rhs[8]; m[9] -= rhs[9]; m[10] -= rhs[10]; m[11] -= rhs[11]; m[12] -= rhs[12]; m[13] -= rhs[13]; m[14] -= rhs[14]; m[15] -= rhs[15]; return *this; } Vector4D Matrix4x4::operator*(const Vector4D& rhs) const { return Vector4D(m[0] * rhs.x + m[4] * rhs.y + m[8] * rhs.z + m[12] * rhs.w, m[1] * rhs.x + m[5] * rhs.y + m[9] * rhs.z + m[13] * rhs.w, m[2] * rhs.x + m[6] * rhs.y + m[10] * rhs.z + m[14] * rhs.w, m[3] * rhs.x + m[7] * rhs.y + m[11] * rhs.z + m[15] * rhs.w); } Vector3D Matrix4x4::operator*(const Vector3D& rhs) const { return Vector3D(m[0] * rhs.x + m[1] * rhs.y + m[2] * rhs.z /*+ m[12]*/, m[4] * rhs.x + m[5] * rhs.y + m[6] * rhs.z /*+m[7]*/, m[8] * rhs.x + m[9] * rhs.y + m[10] * rhs.z /*+ m[14]*/); } Matrix4x4 Matrix4x4::operator*(const Matrix4x4& rhs) const { return Matrix4x4(m[0] * rhs[0] + m[4] * rhs[1] + m[8] * rhs[2] + m[12] * rhs[3], m[1] * rhs[0] + m[5] * rhs[1] + m[9] * rhs[2] + m[13] * rhs[3], m[2] * rhs[0] + m[6] * rhs[1] + m[10] * rhs[2] + m[14] * rhs[3], m[3] * rhs[0] + m[7] * rhs[1] + m[11] * rhs[2] + m[15] * rhs[3], m[0] * rhs[4] + m[4] * rhs[5] + m[8] * rhs[6] + m[12] * rhs[7], m[1] * rhs[4] + m[5] * rhs[5] + m[9] * rhs[6] + m[13] * rhs[7], m[2] * rhs[4] + m[6] * rhs[5] + m[10] * rhs[6] + m[14] * rhs[7], m[3] * rhs[4] + m[7] * rhs[5] + m[11] * rhs[6] + m[15] * rhs[7], m[0] * rhs[8] + m[4] * rhs[9] + m[8] * rhs[10] + m[12] * rhs[11], m[1] * rhs[8] + m[5] * rhs[9] + m[9] * rhs[10] + m[13] * rhs[11], m[2] * rhs[8] + m[6] * rhs[9] + m[10] * rhs[10] + m[14] * rhs[11], m[3] * rhs[8] + m[7] * rhs[9] + m[11] * rhs[10] + m[15] * rhs[11], m[0] * rhs[12] + m[4] * rhs[13] + m[8] * rhs[14] + m[12] * rhs[15], m[1] * rhs[12] + m[5] * rhs[13] + m[9] * rhs[14] + m[13] * rhs[15], m[2] * rhs[12] + m[6] * rhs[13] + m[10] * rhs[14] + m[14] * rhs[15], m[3] * rhs[12] + m[7] * rhs[13] + m[11] * rhs[14] + m[15] * rhs[15]); } Matrix4x4& Matrix4x4::operator*=(const Matrix4x4& rhs) { *this = *this * rhs; return *this; } bool Matrix4x4::operator==(const Matrix4x4& n) const { return (m[0] == n[0]) && (m[1] == n[1]) && (m[2] == n[2]) && (m[3] == n[3]) && (m[4] == n[4]) && (m[5] == n[5]) && (m[6] == n[6]) && (m[7] == n[7]) && (m[8] == n[8]) && (m[9] == n[9]) && (m[10] == n[10]) && (m[11] == n[11]) && (m[12] == n[12]) && (m[13] == n[13]) && (m[14] == n[14]) && (m[15] == n[15]); } bool Matrix4x4::operator!=(const Matrix4x4& n) const { return (m[0] != n[0]) || (m[1] != n[1]) || (m[2] != n[2]) || (m[3] != n[3]) || (m[4] != n[4]) || (m[5] != n[5]) || (m[6] != n[6]) || (m[7] != n[7]) || (m[8] != n[8]) || (m[9] != n[9]) || (m[10] != n[10]) || (m[11] != n[11]) || (m[12] != n[12]) || (m[13] != n[13]) || (m[14] != n[14]) || (m[15] != n[15]); } float Matrix4x4::operator[](int index) const { return m[index]; } float& Matrix4x4::operator[](int index) { return m[index]; } Matrix4x4 operator-(const Matrix4x4& rhs) { return Matrix4x4(-rhs[0], -rhs[1], -rhs[2], -rhs[3], -rhs[4], -rhs[5], -rhs[6], -rhs[7], -rhs[8], -rhs[9], -rhs[10], -rhs[11], -rhs[12], -rhs[13], -rhs[14], -rhs[15]); } Matrix4x4 operator*(float s, const Matrix4x4& rhs) { return Matrix4x4(s*rhs[0], s*rhs[1], s*rhs[2], s*rhs[3], s*rhs[4], s*rhs[5], s*rhs[6], s*rhs[7], s*rhs[8], s*rhs[9], s*rhs[10], s*rhs[11], s*rhs[12], s*rhs[13], s*rhs[14], s*rhs[15]); } Vector3D operator*(const Vector3D& v, const Matrix4x4& m) { return Vector3D(v.x*m[0] + v.y*m[1] + v.z*m[2], v.x*m[4] + v.y*m[5] + v.z*m[6], v.x*m[8] + v.y*m[9] + v.z*m[10]); } Vector4D operator*(const Vector4D& v, const Matrix4x4& m) { return Vector4D(v.x*m[0] + v.y*m[1] + v.z*m[2] + v.w*m[3], v.x*m[4] + v.y*m[5] + v.z*m[6] + v.w*m[7], v.x*m[8] + v.y*m[9] + v.z*m[10] + v.w*m[11], v.x*m[12] + v.y*m[13] + v.z*m[14] + v.w*m[15]); } std::ostream& operator<<(std::ostream& os, const Matrix4x4& m) { os << std::fixed << std::setprecision(5); os << "[" << std::setw(10) << m[0] << " " << std::setw(10) << m[4] << " " << std::setw(10) << m[8] << " " << std::setw(10) << m[12] << "]\n" << "[" << std::setw(10) << m[1] << " " << std::setw(10) << m[5] << " " << std::setw(10) << m[9] << " " << std::setw(10) << m[13] << "]\n" << "[" << std::setw(10) << m[2] << " " << std::setw(10) << m[6] << " " << std::setw(10) << m[10] << " " << std::setw(10) << m[14] << "]\n" << "[" << std::setw(10) << m[3] << " " << std::setw(10) << m[7] << " " << std::setw(10) << m[11] << " " << std::setw(10) << m[15] << "]\n"; os << std::resetiosflags(std::ios_base::fixed | std::ios_base::floatfield); return os; }
true
aaecff4086302287b3d7e7084b69a69ffa97657b
C++
yumkong/cpp_prac
/leet/0820/leet_530.cpp
UTF-8
1,317
3.828125
4
[]
no_license
// minimum absolute different in BST // given a binary search tree with non-negative values, find the minimum absolute difference of any two nodes // NOTE: there at least two nodes in this BST #include <iostream> #include <climits> // INT_MAX, INT_MIN #include <vector> using namespace std; //Definition for a binary tree node. struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: int getMinimumDifference(TreeNode* root) { //do a preorder traverse vector<int> arr; helper(root, arr); int res = INT_MAX; //cout << "0 :" << arr[0] << endl; for(int i = 1; i < arr.size(); ++i) { //cout << i << ": " << arr[i] << endl; res = min(res, arr[i] - arr[i-1]); } return res; } void helper(TreeNode* root, vector<int>& arr) { if(!root) return; if(root->left) helper(root->left, arr); arr.push_back(root->val); if(root->right) helper(root->right, arr); } }; int main() { Solution solu; TreeNode *root = new TreeNode(1); root->right = new TreeNode(3); root->right->left = new TreeNode(2); cout << solu.getMinimumDifference(root) << endl; return 0; }
true
7aba46e4fa145d39903ed1837bf78f44e0232707
C++
maksym-pasichnyk/NativeParticleSystem
/NativePlugin/Src/Runtime/Allocator/LinearAllocator.h
UTF-8
4,277
2.640625
3
[]
no_license
#ifndef LINEAR_ALLOCATOR_H_ #define LINEAR_ALLOCATOR_H_ #include <cstddef> #include <list> #include "Configuration/UnityConfigure.h" #if UNITY_LINUX || UNITY_PS4 #include <stdint.h> // uintptr_t #endif #include "Runtime/Allocator/MemoryMacros.h" struct LinearAllocatorBase { static const int kMinimalAlign = 4; struct Block { char* m_Begin; char* m_Current; size_t m_Size; MemLabelId m_Label; void initialize (size_t size, MemLabelId label) { m_Label = label; m_Current = m_Begin = (char*)UNITY_MALLOC(label,size); m_Size = size; } void reset () { m_Current = m_Begin; } void purge () { UNITY_FREE(m_Label, m_Begin); } size_t used () const { return m_Current - m_Begin; } void* current () const { return m_Current; } size_t available () const { return m_Size - used (); } size_t padding (size_t alignment) const { size_t pad = (((uintptr_t)m_Current - 1) | (alignment - 1)) + 1 - (uintptr_t)m_Current; return pad; } void* bump (size_t size) { char* p = m_Current; m_Current += size; return p; } void roll_back (size_t size) { m_Current -= size; } bool belongs (const void* p) { //if (p >= m_Begin && p <= m_Begin + m_Size) // return true; //return false; //return p >= m_Begin && p <= m_Begin + m_Size; return (uintptr_t)p - (uintptr_t)m_Begin <= (uintptr_t)m_Size; } void set (void* p) { m_Current = (char*)p; } }; typedef std::list<Block, STL_ALLOCATOR(kMemPoolAlloc, Block) > block_container; LinearAllocatorBase (size_t blockSize, MemLabelId label) : m_Blocks(), m_BlockSize (blockSize), m_AllocLabel (label) { } void add_block (size_t size) { m_Blocks.push_back (Block()); size_t blockSize = size > m_BlockSize ? size : m_BlockSize; m_Blocks.back ().initialize (blockSize, m_AllocLabel); } void purge (bool releaseAllBlocks = false) { if (m_Blocks.empty ()) return; block_container::iterator begin = m_Blocks.begin (); if (!releaseAllBlocks) begin++; for (block_container::iterator it = begin, end = m_Blocks.end (); it != end; ++it) it->purge (); m_Blocks.erase (begin, m_Blocks.end ()); if (!releaseAllBlocks) m_Blocks.back ().reset (); } bool belongs (const void* p) { for (block_container::iterator it = m_Blocks.begin (), end = m_Blocks.end (); it != end; ++it) { if (it->belongs (p)) return true; } return false; } void* current () const { return m_Blocks.empty () ? 0 : m_Blocks.back ().current (); } void rewind (void* mark) { for (block_container::iterator it = m_Blocks.end (); it != m_Blocks.begin (); --it) { block_container::iterator tit = it; --tit; if (tit->belongs (mark)) { tit->set (mark); for (block_container::iterator temp = it; temp != m_Blocks.end (); ++temp) temp->purge (); m_Blocks.erase (it, m_Blocks.end ()); break; } } } protected: block_container m_Blocks; size_t m_BlockSize; MemLabelId m_AllocLabel; }; struct ForwardLinearAllocator : public LinearAllocatorBase { ForwardLinearAllocator (size_t blockSize, MemLabelId label) : LinearAllocatorBase (blockSize, label) { } ~ForwardLinearAllocator () { purge (true); } size_t GetAllocatedBytes() const { size_t s = 0; for (block_container::const_iterator it = m_Blocks.begin (); it != m_Blocks.end(); ++it) s += it->used(); return s; } void* allocate (size_t size, size_t alignment = 4) { // Assert (size == AlignUIntPtr (size, kMinimalAlign)); if (m_Blocks.empty ()) add_block (size); Block* block = &m_Blocks.back (); size_t padding = block->padding (alignment); if (size + padding > block->available ()) { add_block (size); block = &m_Blocks.back (); } uintptr_t p = (uintptr_t)block->bump (size + padding); return (void*)(p + padding); } void deallocate (void* dealloc) { } void deallocate_no_thread_check (void* dealloc) { } void purge (bool releaseAllBlocks = false) { LinearAllocatorBase::purge (releaseAllBlocks); } void rewind (void* mark) { LinearAllocatorBase::rewind (mark); } using LinearAllocatorBase::current; using LinearAllocatorBase::belongs; }; #endif
true
44e5a904fbc96fb4f38aee163e021a6dbbb8348c
C++
adegroat/csci441_a6
/ParticleSystem.cpp
UTF-8
4,583
2.6875
3
[]
no_license
#include "ParticleSystem.h" ParticleSystem::ParticleSystem(float startX, float startY, float startZ, float maxAngle, float minVel, float maxVel, float minLife, float maxLife, float spawnRate) { this->startX = startX; this->startY = startY; this->startZ = startZ; this->maxAngle = maxAngle; this->minVel = minVel; this->maxVel = maxVel; this->minLife = minLife; this->maxLife = maxLife; this->spawnRate = spawnRate; this->prevSpawn = 0.0f; } void ParticleSystem::setup() { shader.init("shaders/particle.v.glsl", "shaders/particle.f.glsl", "shaders/particle.g.glsl"); textureHandle = CSCI441::TextureUtils::loadAndRegisterTexture("textures/flare_0.png"); glGenVertexArrays(1, &vao); glBindVertexArray(vao); for(int i = 0; i < 100; i++) { particles.push_back(randomParticle()); } ParticleStruct particleData[particles.size()]; for(unsigned int i = 0; i < particles.size(); i++) { particleData[i].x = particles[i].position.x; particleData[i].y = particles[i].position.y; particleData[i].z = particles[i].position.z; particleData[i].vx = particles[i].velocity.x; particleData[i].vy = particles[i].velocity.y; particleData[i].vz = particles[i].velocity.z; particleData[i].remainingLife = 0.0f; } glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(particleData), particleData, GL_STATIC_DRAW); int positionAttribLocation = glGetAttribLocation(shader.getProgram(), "position"); glEnableVertexAttribArray(positionAttribLocation); glVertexAttribPointer(positionAttribLocation, 3, GL_FLOAT, GL_FALSE, sizeof(ParticleStruct), (void*)0); int velocityAttribLocation = glGetAttribLocation(shader.getProgram(), "velocity"); glEnableVertexAttribArray(velocityAttribLocation); glVertexAttribPointer(velocityAttribLocation, 3, GL_FLOAT, GL_FALSE, sizeof(ParticleStruct), (void*)(3 * sizeof(float))); int remainingLifeAttribLocation = glGetAttribLocation(shader.getProgram(), "remainingLife"); glEnableVertexAttribArray(remainingLifeAttribLocation); glVertexAttribPointer(remainingLifeAttribLocation, 1, GL_FLOAT, GL_FALSE, sizeof(ParticleStruct), (void*)(6 * sizeof(float))); } Particle ParticleSystem::randomParticle() { float dirX = sin((-maxAngle + getRand(2.0f*maxAngle)) * (M_PI / 180.0f)); float dirZ = sin((-maxAngle + getRand(2.0f*maxAngle)) * (M_PI / 180.0f)); float speed = getRand(maxVel); if(speed < minVel) speed = minVel; float lifeTime = minLife + getRand(maxLife); return Particle(glm::vec3(startX, startY, startZ), glm::vec3(dirX * speed, 0.4f, dirZ * speed), lifeTime); } void ParticleSystem::draw() { shader.useProgram(); glBindTexture(GL_TEXTURE_2D, textureHandle); glBindVertexArray(vao); glDrawArrays(GL_POINTS, 0, particles.size()); } void ParticleSystem::update(glm::mat4 modelViewMtx, glm::mat4 projMtx, glm::vec3 camPos, glm::vec3 lookAtPoint) { glBindVertexArray(vao); shader.updateMVP(modelViewMtx, projMtx); std::vector<Particle>::iterator start = particles.begin(); for(unsigned int i = 0; i < particles.size(); i++) { if(particles[i].isDone()) { particles.erase(start + i); } } if(glfwGetTime() - prevSpawn > 1.0f/spawnRate) { particles.push_back(randomParticle()); prevSpawn = glfwGetTime(); } // TODO: Sort particles based on distance from camera float distances[particles.size()]; int index[particles.size()]; glm::vec3 viewVector = glm::normalize(lookAtPoint - camPos); for(unsigned int i = 0; i < particles.size(); i++) { glm::vec4 pointVec(particles[i].position, 1.0f); pointVec = glm::mat4(1.0f) * pointVec; glm::vec3 ep = glm::vec3(pointVec) - camPos; distances[i] = glm::dot(viewVector, ep); index[i] = i; } for(int i = 0; i < particles.size() - 1; i++) { for(int j = 0; j < particles.size() - 1; j++) { if(distances[index[j + 1]] > distances[index[j]]) { int temp = index[j]; index[j] = index[j + 1]; index[j + 1] = temp; } } } ParticleStruct particleData[particles.size()]; for(unsigned int i = 0; i < particles.size(); i++) { particles[i].update(); particleData[i].x = particles[index[i]].position.x; particleData[i].y = particles[index[i]].position.y; particleData[i].z = particles[index[i]].position.z; particleData[i].vx = particles[index[i]].velocity.x; particleData[i].vy = particles[index[i]].velocity.y; particleData[i].vz = particles[index[i]].velocity.z; particleData[i].remainingLife = particles[i].getRemainingLife(); } glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(particleData), (void*)particleData); }
true
d3e2601da05a720481ead44b9f41cd38dc3eb5bf
C++
juhuahuang/leetcode
/BinartTreeLevelOrderTraversal_102.cpp
UTF-8
843
3
3
[]
no_license
#include "BinartTreeLevelOrderTraversal_102.h" void BinaryTreeLevelOrderTraversal_102::execute() { this->result = LevelOrder(this->root); } BinaryTreeLevelOrderTraversal_102::BinaryTreeLevelOrderTraversal_102(vector<int> num) { } vector<vector<int>> BinaryTreeLevelOrderTraversal_102::LevelOrder(TreeNode * root) { vector<vector<int>> result; vector<TreeNode*> nextLevel; vector<TreeNode*> currentLevel; if (root != NULL) { nextLevel.push_back(root); } while (!nextLevel.empty()) { vector<int> currentLevelVal; currentLevel = nextLevel; nextLevel.clear(); for (TreeNode* n : currentLevel) { currentLevelVal.push_back(n->val); if (n->left != NULL) { nextLevel.push_back(n->left); } if (n->right != NULL) { nextLevel.push_back(n->right); } } result.push_back(currentLevelVal); } return result; }
true
6c30d48c9833471159283da46c5b1b3adadc1697
C++
dmitryikh/rcfg
/test/ClassParserTest.cpp
UTF-8
3,755
2.828125
3
[ "MIT" ]
permissive
#include <gtest/gtest.h> #include <nlohmann/json.hpp> #include <rcfg/rcfg.h> #include "TestEventSink.h" using json = nlohmann::json; struct Config { std::string s1; int i2; bool b3; }; auto getParser() { rcfg::ClassParser<Config> p; p.member(&Config::s1, "s1", rcfg::Default{std::string("aba")}, rcfg::Updatable, rcfg::NotEmpty); p.member(&Config::i2, "i2", rcfg::Bounds{0, 10}); p.member(&Config::b3, "b3", rcfg::Default{true}); return p; } TEST(ClassParser, Parse) { const auto p = getParser(); { SCOPED_TRACE("Correct Parse"); Config c{}; ASSERT_EQ(c.s1, ""); ASSERT_EQ(c.i2, 0); ASSERT_EQ(c.b3, false); json j; j["s1"] = "lalaland"; j["i2"] = 10; j["b3"] = true; TestEventSink sink; p.parse(sink, c, j, false); ASSERT_EQ(sink.errorCount, 0); ASSERT_EQ(sink.setCount, 3); ASSERT_EQ(c.s1, "lalaland"); ASSERT_EQ(c.i2, 10); ASSERT_EQ(c.b3, true); } { SCOPED_TRACE("Default s1"); Config c{}; json j; j["i2"] = 1; j["b3"] = true; TestEventSink sink; p.parse(sink, c, j, false); ASSERT_EQ(sink.errorCount, 0); ASSERT_EQ(sink.setCount, 3); ASSERT_EQ(c.s1, "aba"); ASSERT_EQ(c.i2, 1); ASSERT_EQ(c.b3, true); } { SCOPED_TRACE("Default b3"); Config c{}; json j; j["s1"] = "a"; j["i2"] = 0; TestEventSink sink; p.parse(sink, c, j, false); ASSERT_EQ(sink.errorCount, 0); ASSERT_EQ(sink.setCount, 3); ASSERT_EQ(c.s1, "a"); ASSERT_EQ(c.i2, 0); ASSERT_EQ(c.b3, true); } { SCOPED_TRACE("Empty node"); Config c{}; ASSERT_EQ(c.s1, ""); ASSERT_EQ(c.i2, 0); ASSERT_EQ(c.b3, false); json j; TestEventSink sink; p.parse(sink, c, j, false); // i2 don't have defaults ASSERT_EQ(sink.errorCount, 1); // s1 & b3 have defaults ASSERT_EQ(sink.setCount, 2); ASSERT_EQ(c.s1, "aba"); ASSERT_EQ(c.i2, 0); ASSERT_EQ(c.b3, true); } } struct EmbConf { int i1; }; struct Conf { EmbConf e; std::string s1; }; auto getConfParser() { rcfg::ClassParser<EmbConf> p1; p1.member(&EmbConf::i1, "i1"); rcfg::ClassParser<Conf> p2; p2.member(&Conf::e, "", p1); p2.member(&Conf::s1, "s1"); return p2; } TEST(ClassParser, FlatMemberParser) { const auto p = getConfParser(); { SCOPED_TRACE("Correct Parse"); Conf c{}; json j; j["s1"] = "lalaland"; j["i1"] = 10; TestEventSink sink; p.parse(sink, c, j, false); ASSERT_EQ(sink.errorCount, 0); ASSERT_EQ(sink.setCount, 2); ASSERT_EQ(c.e.i1, 10); ASSERT_EQ(c.s1, "lalaland"); } } namespace { struct Config2 { std::vector<std::string> v1; }; auto getConfig2Parser() { rcfg::ClassParser<Config2> p1; p1.member(&Config2::v1, ""); return p1; } } TEST(ClassParser, VectorMemberParser) { const auto p = getConfig2Parser(); { SCOPED_TRACE("Correct Parse"); Config2 c{}; json j = {"aaa", "bbb", "ccc"}; TestEventSink sink; p.parse(sink, c, j, false); ASSERT_EQ(sink.errorCount, 0); ASSERT_EQ(sink.setCount, 3); const auto expected = std::vector<std::string>{"aaa", "bbb", "ccc"}; ASSERT_EQ(c.v1, expected); } } struct Config3 { std::map<std::string, std::string> m1; std::unordered_map<std::string, int> m2; }; auto getConfig3Parser() { rcfg::ClassParser<Config3> p1; p1.member(&Config3::m1, "m1"); p1.member(&Config3::m2, "m2"); return p1; } TEST(ClassParser, MapMemberParser) { const auto p = getConfig3Parser(); { SCOPED_TRACE("Correct Parse"); Config3 c{}; json j; j["m1"]["a"] = "A"; j["m1"]["b"] = "B"; j["m2"]["c"] = 3; TestEventSink sink; p.parse(sink, c, j, false); ASSERT_EQ(sink.errorCount, 0); ASSERT_EQ(sink.setCount, 3); ASSERT_EQ(c.m1.size(), 2); ASSERT_EQ(c.m1.at("a"), "A"); ASSERT_EQ(c.m1.at("b"), "B"); ASSERT_EQ(c.m2.size(), 1); ASSERT_EQ(c.m2.at("c"), 3); } }
true
dbcec52de2168f776a7de58d8f0bd492cf7fcf27
C++
DanielParra159/EngineAndGame
/Engine/src/Include/Common/Graphics/SpriteAnimatorComponent.h
UTF-8
3,579
2.53125
3
[ "CC0-1.0" ]
permissive
#ifndef _ENGINE_GRAPHICS_SPRITEANIMATORCOMPONENT_H_ #define _ENGINE_GRAPHICS_SPRITEANIMATORCOMPONENT_H_ #include "Defs.h" #include "Types.h" #include "Logic/IComponent.h" #include "Graphics/SpriteAnimator.h" namespace logic{ class IGameObject; } namespace graphics { /** */ class SpriteAnimatorComponent : public logic::IComponent { friend class RenderManager; REGISTER_COMPONENT_HEAD(SpriteAnimatorComponent) protected: SpriteAnimator* mSpriteAnimator; Vector3D<float32> mRotationOffset; protected: SpriteAnimatorComponent() : logic::IComponent(), mSpriteAnimator(NULL){} virtual ~SpriteAnimatorComponent() {} virtual void Release(); virtual void PrepareToRender(); virtual void Update(); virtual void SetCallbacks(logic::IGameObject* aGameObject, UpdateFunction& aUpdateFunction, FixedUpdateFunction& aFixedUpdateFunction, RenderFunction& aRenderFunction); void SetSpriteAnimator(SpriteAnimator* aSpriteAnimator); public: void SetRotationOffset(const Vector3D<float32>& aRotationOffset) { mRotationOffset = aRotationOffset; } void SetSpeedScale(float32 aSpeedScale) { mSpriteAnimator->SetSpeedScale(aSpeedScale); } float32 GetSpeedScale() const { return mSpriteAnimator->GetSpeedScale(); }; void PlayState(uint32 aId, uint32 aFrame = 0) { mSpriteAnimator->PlayState(aId, aFrame); } void AddState(uint32 aId, uint32 aFrameStart, uint32 aNumFrames, float32 aAnimDuration, BOOL aLoop) { mSpriteAnimator->AddState(aId, aFrameStart, aNumFrames, aAnimDuration, aLoop); } void AddTransition(uint32 aFromState, uint32 aToState, eConditionType aType, float32 aFloatValue, const std::string& aParameter) { mSpriteAnimator->AddTransition(aFromState, aToState, aType, aFloatValue, aParameter); } void AddTransition(uint32 aFromState, uint32 aToState, eConditionType aType, int32 aIntValue, const std::string& aParameter) { mSpriteAnimator->AddTransition(aFromState, aToState, aType, aIntValue, aParameter); } void AddTransition(uint32 aFromState, uint32 aToState, eConditionType aType, const std::string& aParameter) { mSpriteAnimator->AddTransition(aFromState, aToState, aType, aParameter); } void SetFloatParameter(const std::string& aName, float32 aFloatValue) { mSpriteAnimator->SetFloatParameter(aName, aFloatValue); } void SetIntParameter(const std::string& aName, int32 aIntValue) { mSpriteAnimator->SetIntParameter(aName, aIntValue); } void SetBoolParameter(const std::string& aName, BOOL aBoolValue) { mSpriteAnimator->SetBoolParameter(aName, aBoolValue); } void SetTriggerParameter(const std::string& aName) { mSpriteAnimator->SetTriggerParameter(aName); } void SetFlipXY(BOOL aFlipX, BOOL aFlipY) { mSpriteAnimator->SetFlipX(aFlipX); mSpriteAnimator->SetFlipY(aFlipY); } void SetFlipX(BOOL aFlipX) { mSpriteAnimator->SetFlipX(aFlipX); } BOOL GetFlipX() const { return mSpriteAnimator->GetFlipX(); } void SetFlipY(BOOL aFlipY) { mSpriteAnimator->SetFlipY(aFlipY); } BOOL GetFlipY() const { return mSpriteAnimator->GetFlipY(); } Material* GetMaterial() { return mSpriteAnimator->GetMaterial(); } void SetMaterial(Material *aMaterial) { mSpriteAnimator->SetMaterial(aMaterial); } }; // SpriteAnimatorComponent } // namespace graphics #endif // _ENGINE_GRAPHICS_SPRITEANIMATORCOMPONENT_H_
true
9e487f965b11101169852c242d70c5586d657213
C++
sntwr/UVa-Solved-Problems
/solved/UVa484/484.cpp
UTF-8
441
2.765625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main () { map<int, int> ct; vector<int> rank; int num; while (scanf ("%d", &num) == 1) { map<int, int>::iterator it; if ((it = ct.find (num)) != ct.end ()) { it->second++; } else { ct[num] = 1; rank.push_back (num); } } vector<int>::iterator iter; for (iter = rank.begin (); iter != rank.end (); iter++) { printf ("%d %d\n", *iter, ct[*iter]); } return 0; }
true
90d23726b43d30fa307b727c7de464db3ed84bfe
C++
serishan/LeetCode
/Solutions/C++/Problem 004.cpp
UTF-8
1,393
4.375
4
[]
no_license
/* Question 4: Median of Two Sorted Arrays There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). You may assume nums1 and nums2 cannot be both empty. [Example 1] nums1 = [1, 3] nums2 = [2] The median is 2.0 [Example 2] nums1 = [1, 2] nums2 = [3, 4] The median is (2 + 3)/2 = 2.5 */ class Solution { public: /* [Function] findMedianSortedArrays [Parameters] nums1 - vector of int holding the first list of numbers nums2 - vector of int holding the second list of numbers [Return] Median value of two vectors */ double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { double median = 0.0; //First merge two vectors and sort vector<int> destination; merge(nums1.begin(), nums1.end(), nums2.begin(), nums2.end(), back_inserter(destination)); //Check the size of the merged vector //If it has odd elements if (destination.size() % 2 == 1) { int index = (destination.size() / 2); median = destination[index]; } //Otherwise has even elements else { int index1 = (destination.size() / 2) - 1; int index2 = (destination.size() / 2); double center = (destination[index1] + destination[index2]) / 2.0; median = center; } return median; } };
true
695cd4f439baf9aa85e6b18f1151f59796ea17af
C++
KoWunnaKo/qmlib
/include/qmlib/finance/rates/composite_rate.hpp
UTF-8
4,185
2.578125
3
[]
no_license
#ifndef __COMPOSITE_RATE_QM_HPP__ #define __COMPOSITE_RATE_QM_HPP__ #include <qmlib/corelib/static/all.hpp> #include <qmlib/corelib/tools.hpp> #include <qmlib/corelib/templates/observer.hpp> /** \file * \brief Composite rate base class template * \ingroup rates * */ QM_NAMESPACE2(finance) template<class C> struct composite_rate_element {}; class basecomposite: public lazy { public: void rebuild() {this->build(); this->refresh();} /// \brief build the composite rate virtual void build() {} /// \brief refresh the composite rate /// /// This function does not require to rebuild the compositerate but only /// to refresh its values virtual void refresh() {} const itersolver& solver() const { return m_solve;} protected: itersolver m_solve; }; /** \brief Class template for a general composite rate * \ingroup rates * * Class template for handling composite rates * * @param C element type */ template<class C> class composite_rate : public basecomposite { public: typedef C element_type; typedef QM_SMART_PTR(element_type) ELEMENT; typedef composite_rate_element<element_type> element_wrap; typedef typename element_wrap::key_type key_type; typedef dataserie<key_type,false,ELEMENT> element_serie; typedef typename element_serie::iterator iterator; typedef typename element_serie::const_iterator const_iterator; /// \brief Add a rate to the composite rate list template<class T> void add(const QM_SMART_PTR(T)& element) {this->addelement(smart_cast<C,T>(element));} /// \brief number of rates used in the composite rate unsigned size() const { return m_used_insts.size();} iterator begin() { return m_used_insts.begin();} iterator end() { return m_used_insts.end();} const_iterator begin() const { return m_used_insts.begin();} const_iterator end() const { return m_used_insts.end();} ELEMENT get(unsigned i) const { return m_used_insts.get_slow(i).value().elem;} const qdate& referenceDate() const { return m_date;} template<class L> L instlist(bool idl) const { L l; if(idl) for(const_iterator it=m_idle_insts.begin();it!=m_idle_insts.end();++it) l.append(it->value()); else for(const_iterator it=this->begin();it!=this->end();++it) l.append(it->value()); return l; } void updatelazy() {this->refresh_update();} protected: element_serie m_idle_insts; element_serie m_used_insts; qdate m_date; composite_rate(){} composite_rate(const qdate& dte):m_date(dte){} void refresh_update(); virtual bool addtoinstruments(const key_type& key, const ELEMENT& el) = 0; /// \brief clean the used instruments /// /// This function loop over the instrument used for building the composite rate /// and eliminate the one which are not valid bool clean(); /// \brief Add an element to the composite rate void addelement(const ELEMENT& el) { if(!el) return; try { key_type k = element_wrap::keyval(el,m_date); if(element_wrap::valid(el)) { if(this->addtoinstruments(k,el)) this->rebuild(); } else m_idle_insts.addkeyval(k,el); this->registerWith(el); } catch(...){} } }; template<class C> inline bool composite_rate<C>::clean() { ELEMENT el; key_type k; bool changed = false; for(iterator it=this->begin();it!=this->end();++it) { el = it->value(); if(!element_wrap::valid(el)) { changed = true; k = element_wrap::keyval(el,m_date); m_idle_insts.addkeyval(k,el); it = m_used_insts.erase(it); if(it == this->end()) break; } } return changed; } template<class C> inline void composite_rate<C>::refresh_update() { ELEMENT el; key_type k; bool ch = this->clean(); for(iterator it=m_idle_insts.begin();it!=m_idle_insts.end();++it) { el = it->value(); k = element_wrap::keyval(el,m_date); if(!element_wrap::valid(el)) continue; if(this->addtoinstruments(k,el)) { ch = true; it = m_idle_insts.erase(it); if(it == m_idle_insts.end()) break; } } if(ch) this->rebuild(); else this->refresh(); } QM_NAMESPACE_END2 #endif // __COMPOSITE_RATE_QM_HPP__
true
60c65a91a2ab2f69a6039188ba301ed9c94817ce
C++
froseb/lgo
/blatt1/src/LinearProgram.cpp
UTF-8
2,314
3.671875
4
[]
no_license
#include "LinearProgram.h" #include <iostream> #include <string> #include <fstream> #include <vector> // Constructs a linear program object by the content of an input file LinearProgram::LinearProgram(std::string input_file) { std::ifstream file(input_file); if (!file.good()) { throw std::runtime_error("Could not open file"); } file >> rows; file >> cols; double tmp; for (unsigned int i=0; i<cols; i++) { file >> tmp; objectiveFunction.push_back(tmp); } for (unsigned int i=0; i<rows; i++) { file >> tmp; constraints.push_back(tmp); } for (unsigned int i=0; i<rows; i++) { matrix.push_back(std::vector<double>()); for (unsigned int j=0; j<cols; j++) { file >> tmp; matrix[i].push_back(tmp); } } } // Gets the amount of rows unsigned int LinearProgram::getRowCount() { return rows; } // Gets the amount of cols unsigned int LinearProgram::getColCount() { return cols; } // Gets the value of the matrix in the `row`th row and `col`th column double LinearProgram::getMatValue(unsigned int row, unsigned int col) { if (row >= getRowCount() || col >= getColCount()) { throw std::invalid_argument("Index out of bounds"); } return matrix[row][col]; } // Gets the `index`th coefficient of the objective function double LinearProgram::getObjectiveValue(unsigned int index) { if (index >= cols) { throw std::invalid_argument("Index out of bounds"); } return objectiveFunction[index]; } // Gets the `index`th constraint double LinearProgram::getConstraint(unsigned int index) { if (index >= rows) { throw std::invalid_argument("Index out of bounds"); } return constraints[index]; } // Adds a new side condition to the LP void LinearProgram::addRow(std::vector<double>& rowVals, double constraint) { if (rowVals.size() != cols) { throw std::invalid_argument("Size of new row does not equal the width of the matrix"); } matrix.push_back(rowVals); constraints.push_back(constraint); rows++; } std::vector<double>& LinearProgram::getRow(unsigned int index) { if (index >= rows) { throw std::invalid_argument("Index out of bounds"); } return matrix[index]; }
true
850d4be8082289b459ffc3d24b90db68c591034b
C++
NCCA/Sponza
/src/Mtl.cpp
UTF-8
14,855
2.609375
3
[]
no_license
#include "Mtl.h" #include <fstream> #include <ngl/NGLStream.h> #include <ngl/Texture.h> #include <ngl/ShaderLib.h> #include <list> #include <ngl/pystring.h> namespace ps = pystring; bool Mtl::load(const std::string &_fname) { std::fstream fileIn; fileIn.open(_fname.c_str(), std::ios::in); if (!fileIn.is_open()) { std::cout << "File : " << _fname << " Not found Exiting " << std::endl; return false; } // this is the line we wish to parse std::string lineBuffer; // say which separators should be used in this // case Spaces, Tabs and return \ new line std::vector<std::string> tokens; // loop through the file while (!fileIn.eof()) { // grab a line from the input getline(fileIn, lineBuffer, '\n'); // make sure it's not an empty line if (lineBuffer.size() > 1) { // now tokenize the line ps::split(lineBuffer, tokens); // and get the first token // now see if it's a valid one and call the correct function if (tokens[0] == "newmtl") { // add to our map it is possible that a badly formed file would not have an mtl // def first however this is so unlikely I can't be arsed to handle that case. // If it does crash it could be due to this code. // std::cout<<"found "<<m_currentName<<"\n"; m_currentName = tokens[1]; m_current = new mtlItem; // These are the OpenGL texture ID's so set to zero first (for no texture) m_current->map_KaId = 0; m_current->map_KdId = 0; m_current->map_dId = 0; m_current->map_bumpId = 0; m_current->bumpId = 0; m_materials[m_currentName] = m_current; } else if (tokens[0] == "Ns") { m_current->Ns = std::stof(tokens[1]); } else if (tokens[0] == "Ni") { m_current->Ni = std::stof(tokens[1]); } else if (tokens[0] == "d") { m_current->d = std::stof(tokens[1]); } else if (tokens[0] == "Tr") { m_current->Tr = std::stof(tokens[1]); } else if (tokens[0] == "Tf") { m_current->Tf.m_x = std::stof(tokens[1]); m_current->Tf.m_y = std::stof(tokens[2]); m_current->Tf.m_z = std::stof(tokens[3]); } else if (tokens[0] == "illum") { m_current->illum = std::stoi(tokens[1]); } else if (tokens[0] == "Ka") { m_current->Ka.m_x = std::stof(tokens[1]); m_current->Ka.m_y = std::stof(tokens[2]); m_current->Ka.m_z = std::stof(tokens[3]); } else if (tokens[0] == "Kd") { m_current->Kd.m_x = std::stof(tokens[1]); m_current->Kd.m_y = std::stof(tokens[2]); m_current->Kd.m_z = std::stof(tokens[3]); } else if (tokens[0] == "Ks") { m_current->Ks.m_x = std::stof(tokens[1]); m_current->Ks.m_y = std::stof(tokens[2]); m_current->Ks.m_z = std::stof(tokens[3]); } else if (tokens[0] == "Ke") { m_current->Ke.m_x = std::stof(tokens[1]); m_current->Ke.m_y = std::stof(tokens[2]); m_current->Ke.m_z = std::stof(tokens[3]); } else if (tokens[0] == "map_Ka") { m_current->map_Ka = convertToPath(tokens[1]); } else if (tokens[0] == "map_Kd") { m_current->map_Kd = convertToPath(tokens[1]); } else if (tokens[0] == "map_d") { m_current->map_d = convertToPath(tokens[1]); } else if (tokens[0] == "map_bump") { m_current->map_bump = convertToPath(tokens[1]); } else if (tokens[0] == "bump") { m_current->bump = convertToPath(tokens[1]); } else if (tokens[0] == "map_Ks") { m_current->map_Ks = convertToPath(tokens[1]); } } // end zero line } // end while // as the trigger for putting the meshes back is the newmtl we will always have a hanging one // this adds it to the list m_materials[m_currentName] = m_current; loadTextures(); return true; } Mtl::Mtl(const std::string &_fname, bool _loadTextures) { m_loadTextures = _loadTextures; load(_fname); if (m_loadTextures == true) { loadTextures(); } } Mtl::~Mtl() { clear(); } void Mtl::loadTextures() { m_textureID.clear(); std::cout << "loading textures this may take some time\n"; // first loop and store all the texture names in the container std::list<std::string> names; auto end = m_materials.end(); auto i = m_materials.begin(); for (; i != end; ++i) { if (i->second->map_Ka.size() != 0) names.push_back(i->second->map_Ka); if (i->second->map_Kd.size() != 0) names.push_back(i->second->map_Kd); if (i->second->map_d.size() != 0) names.push_back(i->second->map_d); if (i->second->map_bump.size() != 0) names.push_back(i->second->map_bump); if (i->second->map_bump.size() != 0) names.push_back(i->second->bump); } std::cout << "we have this many textures " << names.size() << "\n"; // now remove duplicates names.unique(); std::cout << "we have " << names.size() << " unique textures to load\n"; // now we load the textures and get the GL id // now we associate the ID with the mtlItem for (auto name : names) { std::cout << "loading texture " << name << "\n"; ngl::Texture t(name); std::cout << t.getWidth() << " x " << t.getHeight() << '\n'; GLuint textureID = t.setTextureGL(); m_textureID.push_back(textureID); std::cout << "processing " << name << " ID" << textureID << "\n"; i = m_materials.begin(); for (; i != end; ++i) { if (i->second->map_Ka == name) i->second->map_KaId = textureID; if (i->second->map_Kd == name) i->second->map_KdId = textureID; if (i->second->map_d == name) i->second->map_dId = textureID; if (i->second->map_bump == name) i->second->map_bumpId = textureID; if (i->second->bump == name) i->second->bumpId = textureID; } } std::cout << "done \n"; } void Mtl::clear() { auto end = m_materials.end(); auto i = m_materials.begin(); for (; i != end; ++i) { delete i->second; } if (m_loadTextures == true) { for (auto i : m_textureID) glDeleteTextures(1, &i); } } std::string Mtl::convertToPath(std::string _p) const { ps::strip(_p, " \t\n\r"); #ifdef WIN32 _p = ps::replace(_p, "\\", "\\\\"); #else _p = ps::replace(_p, "\\", "/"); #endif return _p; } void Mtl::debugPrint() const { auto end = m_materials.end(); auto i = m_materials.begin(); std::cout << m_materials.size() << "\n"; for (; i != end; ++i) { std::cerr << "-------------------------------------------------\n"; std::cout << "Material Name " << i->first << "\n"; std::cerr << "-------------------------------------------------\n"; std::cout << "Ns " << i->second->Ns << "\n"; std::cout << "Ni " << i->second->Ni << "\n"; std::cout << "d " << i->second->d << "\n"; std::cout << "Tr " << i->second->Tr << "\n"; std::cout << "illum " << i->second->illum << "\n"; std::cout << "Tf " << i->second->Tf << "\n"; std::cout << "Ka " << i->second->Ka << "\n"; std::cout << "Kd " << i->second->Kd << "\n"; std::cout << "Ks " << i->second->Ks << "\n"; std::cout << "Ke " << i->second->Ke << "\n"; std::cout << "map_Ka " << i->second->map_Ka << "\n"; std::cout << "map_Kd " << i->second->map_Kd << "\n"; std::cout << "map_d " << i->second->map_d << "\n"; std::cout << "map_bump " << i->second->map_bump << "\n"; std::cout << "bump " << i->second->bump << "\n"; std::cout << "map_Ka Texture ID" << i->second->map_KaId << "\n"; std::cout << "map_Kd Texture ID " << i->second->map_KdId << "\n"; std::cout << "map_d Texture ID " << i->second->map_dId << "\n"; std::cout << "map_bump Texture ID " << i->second->map_bumpId << "\n"; std::cout << "bump Texture ID " << i->second->bumpId << "\n"; std::cerr << "-------------------------------------------------\n"; } } mtlItem *Mtl::find(const std::string &_n) const { auto material = m_materials.find(_n); // make sure we have a valid material if (material != m_materials.end()) { return material->second; } else { std::cerr << "Warning could not find material " << _n << "\n"; return 0; } } bool Mtl::saveBinary(const std::string &_fname) const { std::ofstream fileOut; fileOut.open(_fname.c_str(), std::ios::out | std::ios::binary); if (!fileOut.is_open()) { std::cout << "File : " << _fname << " could not be written for output" << std::endl; return false; } // write our own id into the file so we can check we have the correct type // when loading const std::string header("ngl::mtlbin"); fileOut.write(header.c_str(), header.length()); unsigned int size = m_materials.size(); fileOut.write(reinterpret_cast<char *>(&size), sizeof(size)); auto start = m_materials.begin(); auto end = m_materials.end(); for (; start != end; ++start) { // std::cout<<"writing out "<<start->first<<"\n"; // first write the length of the string size = start->first.length(); fileOut.write(reinterpret_cast<char *>(&size), sizeof(size)); // now the string fileOut.write(reinterpret_cast<const char *>(start->first.c_str()), size); // now we do the different data elements of the mtlItem. fileOut.write(reinterpret_cast<char *>(&start->second->Ns), sizeof(float)); fileOut.write(reinterpret_cast<char *>(&start->second->Ni), sizeof(float)); fileOut.write(reinterpret_cast<char *>(&start->second->d), sizeof(float)); fileOut.write(reinterpret_cast<char *>(&start->second->Tr), sizeof(float)); fileOut.write(reinterpret_cast<char *>(&start->second->illum), sizeof(int)); fileOut.write(reinterpret_cast<char *>(&start->second->Tf), sizeof(ngl::Vec3)); fileOut.write(reinterpret_cast<char *>(&start->second->Ka), sizeof(ngl::Vec3)); fileOut.write(reinterpret_cast<char *>(&start->second->Kd), sizeof(ngl::Vec3)); fileOut.write(reinterpret_cast<char *>(&start->second->Ks), sizeof(ngl::Vec3)); fileOut.write(reinterpret_cast<char *>(&start->second->Ke), sizeof(ngl::Vec3)); // first write the length of the string size = start->second->map_Ka.length(); fileOut.write(reinterpret_cast<char *>(&size), sizeof(size)); // now the string fileOut.write(reinterpret_cast<const char *>(start->second->map_Ka.c_str()), size); // first write the length of the string size = start->second->map_Kd.length(); fileOut.write(reinterpret_cast<char *>(&size), sizeof(size)); // now the string fileOut.write(reinterpret_cast<const char *>(start->second->map_Kd.c_str()), size); // first write the length of the string size = start->second->map_d.length(); fileOut.write(reinterpret_cast<char *>(&size), sizeof(size)); // now the string fileOut.write(reinterpret_cast<const char *>(start->second->map_d.c_str()), size); // first write the length of the string size = start->second->map_bump.length(); fileOut.write(reinterpret_cast<char *>(&size), sizeof(size)); // now the string fileOut.write(reinterpret_cast<const char *>(start->second->map_bump.c_str()), size); // first write the length of the string size = start->second->bump.length(); fileOut.write(reinterpret_cast<char *>(&size), sizeof(size)); // now the string fileOut.write(reinterpret_cast<const char *>(start->second->bump.c_str()), size); } fileOut.close(); return true; } bool Mtl::loadBinary(const std::string &_fname) { std::ifstream fileIn; fileIn.open(_fname.c_str(), std::ios::in | std::ios::binary); if (!fileIn.is_open()) { std::cout << "File : " << _fname << " could not be opened for reading" << std::endl; return false; } // clear out what we already have. clear(); unsigned int mapsize; char header[12]; fileIn.read(header, 11 * sizeof(char)); header[11] = 0; // for strcmp we need \n // basically I used the magick string ngl::bin (I presume unique in files!) and // we test against it. if (strcmp(header, "ngl::mtlbin")) { // best close the file and exit fileIn.close(); std::cout << "this is not an ngl::mtlbin file " << std::endl; return false; } fileIn.read(reinterpret_cast<char *>(&mapsize), sizeof(mapsize)); unsigned int size; std::string materialName; std::string s; for (unsigned int i = 0; i < mapsize; ++i) { mtlItem *item = new mtlItem; fileIn.read(reinterpret_cast<char *>(&size), sizeof(size)); // now the string we first need to allocate space then copy in materialName.resize(size); fileIn.read(reinterpret_cast<char *>(&materialName[0]), size); // now we do the different data elements of the mtlItem. fileIn.read(reinterpret_cast<char *>(&item->Ns), sizeof(float)); fileIn.read(reinterpret_cast<char *>(&item->Ni), sizeof(float)); fileIn.read(reinterpret_cast<char *>(&item->d), sizeof(float)); fileIn.read(reinterpret_cast<char *>(&item->Tr), sizeof(float)); fileIn.read(reinterpret_cast<char *>(&item->illum), sizeof(int)); fileIn.read(reinterpret_cast<char *>(&item->Tf), sizeof(ngl::Vec3)); fileIn.read(reinterpret_cast<char *>(&item->Ka), sizeof(ngl::Vec3)); fileIn.read(reinterpret_cast<char *>(&item->Kd), sizeof(ngl::Vec3)); fileIn.read(reinterpret_cast<char *>(&item->Ks), sizeof(ngl::Vec3)); fileIn.read(reinterpret_cast<char *>(&item->Ke), sizeof(ngl::Vec3)); // more strings fileIn.read(reinterpret_cast<char *>(&size), sizeof(size)); // now the string we first need to allocate space then copy in s.resize(size); fileIn.read(reinterpret_cast<char *>(&s[0]), size); item->map_Ka = s; fileIn.read(reinterpret_cast<char *>(&size), sizeof(size)); // now the string we first need to allocate space then copy in s.resize(size); fileIn.read(reinterpret_cast<char *>(&s[0]), size); item->map_Kd = s; fileIn.read(reinterpret_cast<char *>(&size), sizeof(size)); // now the string we first need to allocate space then copy in s.resize(size); fileIn.read(reinterpret_cast<char *>(&s[0]), size); item->map_d = s; fileIn.read(reinterpret_cast<char *>(&size), sizeof(size)); // now the string we first need to allocate space then copy in s.resize(size); fileIn.read(reinterpret_cast<char *>(&s[0]), size); item->map_bump = s; fileIn.read(reinterpret_cast<char *>(&size), sizeof(size)); // now the string we first need to allocate space then copy in s.resize(size); fileIn.read(reinterpret_cast<char *>(&s[0]), size); item->bump = s; m_materials[materialName] = item; } m_loadTextures = true; loadTextures(); return true; }
true
b8c51f811638b771d4a12921cf95186f8087996b
C++
TASUIT-Inc/CGT-Year-3-Labyrintian
/CodeMeat/src/CodeMeat_Core/Objects/LoaderParams.cpp
UTF-8
8,225
2.75
3
[]
no_license
#include "LoaderParams.h" void LoaderParams::CreateCube() { DrawMode = GL_TRIANGLES; float px = 0.1f; float nx = -0.1f; float py = 0.1f; float ny = -0.1f; float pz = 0.1f; float nz = -0.1f; Vertex p1, p2, p3, p4, p5, p6, p7, p8; //face layout /*Front Face: p1 --- p2 Left Face: p6 --- p1 Back Face: p5 --- p6 Right Face: p2 --- p5 Top Face: p6 --- p5 Bottom Face: p3 --- p4 | | | | | | | | | | | | | | | | | | | | | | | | p3 --- p4 p8 --- p3 p7 --- p8 p4 --- p7 p1 --- p2 p8 --- p7 Connections: p1 -> p2, p8, p5 p2 -> p3, p5, p1 p3 -> p2, p8, p4 p4 -> p3, p5, p8 p5 -> p6, p4, p1 p6 -> p1, p7, p5 p7 -> p6, p4, p8 p8 -> p1, p7, p4*/ p1.m_Pos = glm::vec3(nx, py, pz); p2.m_Pos = glm::vec3(px, py, pz); p3.m_Pos = glm::vec3(nx, ny, pz); p4.m_Pos = glm::vec3(px, ny, pz); p5.m_Pos = glm::vec3(px, py, nz); p6.m_Pos = glm::vec3(nx, py, nz); p7.m_Pos = glm::vec3(px, ny, nz); p8.m_Pos = glm::vec3(nx, ny, nz); p1.m_Norm = p1.m_Pos; p2.m_Norm = p2.m_Pos; p3.m_Norm = p3.m_Pos; p4.m_Norm = p4.m_Pos; p5.m_Norm = p5.m_Pos; p6.m_Norm = p6.m_Pos; p7.m_Norm = p7.m_Pos; p8.m_Norm = p8.m_Pos; p1.m_TexCoords = glm::vec2(0.0f, 1.0f); p2.m_TexCoords = glm::vec2(1.0f, 1.0f); p3.m_TexCoords = glm::vec2(0.0f, 0.0f); p4.m_TexCoords = glm::vec2(1.0f, 0.0f); p5.m_TexCoords = glm::vec2(0.0f, 1.0f); p6.m_TexCoords = glm::vec2(1.0f, 1.0f); p7.m_TexCoords = glm::vec2(0.0f, 0.0f); p8.m_TexCoords = glm::vec2(1.0f, 0.0f); PushVertexOrder(p1, p2, p3); //Front Face PushVertexOrder(p4, p3, p2); PushVertexOrder(p6, p1, p8); //Left Face PushVertexOrder(p3, p8, p1); PushVertexOrder(p5, p6, p7); //Back Face PushVertexOrder(p8, p7, p6); PushVertexOrder(p2, p5, p4); //Right Face PushVertexOrder(p7, p4, p5); PushVertexOrder(p6, p5, p1); //Top Face PushVertexOrder(p2, p1, p5); PushVertexOrder(p3, p4, p8); //Bottom Face PushVertexOrder(p7, p8, p4); InitBufferData(); } void LoaderParams::CreatePyramid() { DrawMode = GL_TRIANGLES; float px = 0.1f; float nx = -0.1f; float py = 0.1f; float ny = -0.1f; float pz = 0.1f; float nz = -0.1f; float ze = 0.0f; Vertex p1, p2, p3, p4, p5; //face layout /*Front Face: p1 Left Face: p1 Back Face: p1 Right Face: p1 Bottom Face: p3 --- p2 / \ / \ / \ / \ | | / \ / \ / \ / \ | | p3 - - - p2 p4 - - - p3 p5 - - - p4 p2 - - - p5 p4 --- p5 Connections: p1 -> p2, p3, p4 p2 -> p3, p1, p4 p3 -> p1, p2, p4 p4 -> p1, p5, p3 p5 -> p1, p2, p4*/ p1.m_Pos = glm::vec3(ze, py, ze); p2.m_Pos = glm::vec3(px, ze, pz); p3.m_Pos = glm::vec3(nx, ze, pz); p4.m_Pos = glm::vec3(nx, ze, nz); p5.m_Pos = glm::vec3(px, ze, nz); p1.m_Norm = p1.m_Pos; p2.m_Norm = p2.m_Pos; p3.m_Norm = p3.m_Pos; p4.m_Norm = p4.m_Pos; p5.m_Norm = p5.m_Pos; p1.m_TexCoords = glm::vec2(0.5f, 0.5f); p2.m_TexCoords = glm::vec2(1.0f, 1.0f); p3.m_TexCoords = glm::vec2(0.0f, 1.0f); p4.m_TexCoords = glm::vec2(0.0f, 0.0f); p5.m_TexCoords = glm::vec2(1.0f, 0.0f); PushVertexOrder(p1, p2, p3); //Front Face PushVertexOrder(p1, p3, p4); //Left Face PushVertexOrder(p1, p4, p5); //Back Face PushVertexOrder(p1, p5, p2); //Right Face PushVertexOrder(p3, p2, p4); //Top Face PushVertexOrder(p5, p4, p2); InitBufferData(); } void LoaderParams::CreatePlane() { DrawMode = GL_TRIANGLES; float px = 1.0f; float nx = -1.0f; float py = 1.0f; float ny = -1.0f; float pz = 1.0f; float nz = -1.0f; float ze = 0.0f; Vertex p1, p2, p3, p4; p1.m_Pos = glm::vec3(nx, py, ze); p2.m_Pos = glm::vec3(px, py, ze); p3.m_Pos = glm::vec3(nx, ny, ze); p4.m_Pos = glm::vec3(px, ny, ze); p1.m_Norm = p1.m_Pos; p2.m_Norm = p2.m_Pos; p3.m_Norm = p3.m_Pos; p4.m_Norm = p4.m_Pos; p1.m_TexCoords = glm::vec2(0.0f, 1.0f); p2.m_TexCoords = glm::vec2(1.0f, 1.0f); p3.m_TexCoords = glm::vec2(0.0f, 0.0f); p4.m_TexCoords = glm::vec2(1.0f, 0.0f); PushVertexOrder(p1, p2, p3); //Front Face PushVertexOrder(p4, p3, p2); InitBufferData(); } void LoaderParams::CreateSphere(glm::vec2 Segments) { const float PI = acos(-1); // Note of Interest// /*Use this if you want a spiral Sphere int i, j, k, vi1, vi2; int index = 0; // index for vertex for (i = 0; i < m_Segments.y; ++i) { vi1 = i * (m_Segments.x + 1); // index of tmpVertices vi2 = (i + 1) * (m_Segments.x + 1); for (j = 0; j < m_Segments.x; ++j, ++vi1, ++vi2) { // get 4 vertices per sector // v1--v3 // | | // v2--v4 v1 = tmpVertices[vi1]; v2 = tmpVertices[vi2]; v3 = tmpVertices[vi1 + 1]; v4 = tmpVertices[vi2 + 1]; // if 1st stack and last stack, store only 1 triangle per sector // otherwise, store 2 triangles (quad) per sector if (i == 0) // a triangle for first stack ========================== { // put a triangle AddVertex(v1.x, v1.y, v1.z); AddVertex(v2.x, v2.y, v2.z); AddVertex(v4.x, v4.y, v4.z); //put tex coords of triangle AddTexCoord(v1.s, v1.t); AddTexCoord(v2.s, v2.t); AddTexCoord(v4.s, v4.t); // put normal n = ComputeFaceNormals(v1.x, v1.y, v1.z, v2.x, v2.y, v2.z, v4.x, v4.y, v4.z); for (k = 0; k < 3; ++k) // same normals for 3 vertices { Addnormal(n[0], n[1], n[2]); } index += 3; // for next } else if (i == (m_Segments.y - 1)) // a triangle for last stack ========= { // put a triangle AddVertex(v1.x, v1.y, v1.z); AddVertex(v2.x, v2.y, v2.z); AddVertex(v3.x, v3.y, v3.z); // put tex coords of triangle AddTexCoord(v1.s, v1.t); AddTexCoord(v2.s, v2.t); AddTexCoord(v3.s, v3.t); // put normal n = ComputeFaceNormals(v1.x, v1.y, v1.z, v2.x, v2.y, v2.z, v3.x, v3.y, v3.z); for (k = 0; k < 3; ++k) // same normals for 3 vertices { Addnormal(n[0], n[1], n[2]); } index += 3; // for next } else // 2 triangles for others ==================================== { // put Triangle vertices: v1-v2-v3-v4 AddVertex(v1.x, v1.y, v1.z); AddVertex(v2.x, v2.y, v2.z); AddVertex(v3.x, v3.y, v3.z); AddVertex(v4.x, v4.y, v4.z); // put tex coords of Triangle AddTexCoord(v1.s, v1.t); AddTexCoord(v2.s, v2.t); AddTexCoord(v3.s, v3.t); AddTexCoord(v4.s, v4.t); n = ComputeFaceNormals(v1.x, v1.y, v1.z, v2.x, v2.y, v2.z, v3.x, v3.y, v3.z); for (k = 0; k < 4; ++k) // same normals for 3 vertices { Addnormal(n[0], n[1], n[2]); } index += 4; // for next } } } */ // generate interleaved vertex array as well isSphere = true; } void LoaderParams::PushVertexOrder(Vertex V1, Vertex V2, Vertex V3) { m_InterLeavedVertices.push_back(V1); m_InterLeavedVertices.push_back(V2); m_InterLeavedVertices.push_back(V3); } void LoaderParams::Draw(unsigned int texture =0) { glBindVertexArray(m_VAO); if (texture != 0) { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture); } glDrawArrays(GL_TRIANGLES, 0, m_InterLeavedVertices.size()); } void LoaderParams::InitBufferData() { glGenVertexArrays(1, &m_VAO); glGenBuffers(1, &m_VBO); glBindVertexArray(m_VAO); glBindBuffer(GL_ARRAY_BUFFER, m_VBO); glBufferData(GL_ARRAY_BUFFER, m_InterLeavedVertices.size() * sizeof(Vertex), m_InterLeavedVertices.data(), GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, m_Norm)); glEnableVertexAttribArray(1); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, m_TexCoords)); glEnableVertexAttribArray(2); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, m_Tangent)); glEnableVertexAttribArray(3); glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, m_Bitangent)); glEnableVertexAttribArray(4); glBindVertexArray(0); }
true
a3dc599d4bfcdc72eb2d01df3198f0da73ba0624
C++
dimritium/Code
/ProEuler/19.cpp
UTF-8
656
2.640625
3
[]
no_license
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int ro,col,coln,n,x,t; cin>>t; while(t--) { cin>>n; int a[n][n]; for(ro=0;ro<n;ro++) for(col=0;col<=ro;col++) cin>>a[ro][col]; cout<<givRes(a); } return 0; } int givRes(int n) { long long int sum=0; for(ro=0;ro<n;ro++) { for(col=0;col<=ro;col++) { sum+=a[ro][col]; } cout<<sum<<"\n"; }
true
5e8567be4ea3b2ba8cc0419ce4da30679a428fbd
C++
snoplus/oxsx
/examples/plot/ROOTOut.cpp
UTF-8
1,135
3.359375
3
[]
no_license
/* Demonstrates how to render 1 or 2 D histograms/BinnedPdfs to ROOT histograms */ #include <BinnedED.h> #include <DistTools.h> #include <Histogram.h> #include <TH1D.h> #include <TH2D.h> int main(){ // 1D example // Make a dummy histogram AxisCollection axes; axes.AddAxis(BinAxis("name", 0, 10, 100)); Histogram histo(axes); for(int i = 0; i < 100; i++) histo.Fill(i, i * i ); // second argument is a weight // Use it to make a dummy BinnedPdf BinnedED pdf("1Dhisto", histo); // Convert to root objects // the second argument toggles whether // probability = height (false) or area (true) TH1D th1fromHisto = DistTools::ToTH1D(histo, false); TH1D th1fromPdf = DistTools::ToTH1D(histo, false); // 2D example // set up axes.AddAxis(BinAxis("name2", 1, 2, 10)); Histogram histo2D(axes); for(size_t i = 0; i < histo2D.GetNBins(); i++) histo2D.AddBinContent(i, i * i); BinnedED pdf2D("2Dhisto", histo2D); // convert TH2D th2dfromHisto = DistTools::ToTH2D(histo2D, false); return 0; }
true
ba4c40e33ebb1821cef19c7502d28c4a725fb048
C++
sameerad2001/myGeekForGeeksPracticeQuestions
/Stack/Medium/Remove K Digits/main3.cpp
UTF-8
820
3.28125
3
[]
no_license
#include <iostream> #include <stack> #include <algorithm> using namespace std; // https://www.youtube.com/watch?v=3QJzHqNAEXs string removeKdigits(string s, int k) { int n = s.size(); stack<int> st; if (k == 0) { return s; } for (int i = 0; i < n; i++) { int number = s[i] - '0'; while (!st.empty() && st.top() > number && k > 0) { st.pop(); k--; } if (st.empty() && number == 0) continue; st.push(number); } while (!st.empty() && k--) { st.pop(); } string res = ""; while (!st.empty()) { res += st.top() + '0'; st.pop(); } if (res.empty()) res += '0'; reverse(res.begin(), res.end()); return res; } int main() {}
true
c4e5d90439424212d8117637d66ce80667f57ebc
C++
ShinDongHwans/BaekJoon
/여러_개씩_묶어_큰값_골라_배열_만들기.cpp
UTF-8
452
2.828125
3
[]
no_license
#include <stdio.h> int min(int x, int y){ if(x>y) return x; else return y; } int main(){ int n, g; int m[100]={}; int minor; int range; scanf("%d %d", &n, &g); for(int i=0;i<n;i++){ scanf("%d", &m[i]); } if(n%g!=0) range = n/g+1; else range = n/g; for(int i=0;i<range;i++){ minor=-1000; for(int j=i*g;j<i*g+g&&j<n;j++){ minor=min(minor,m[j]); } m[i]=minor; } for(int i=0;i<range;i++){ printf("%d ", m[i]); } }
true
d151c0afc52f3ac086c9256b6b29f2fbbbb71884
C++
joyfish/Coco2d-xRes
/cocos2d设计模式/二段构建.cpp
UTF-8
6,449
3.484375
3
[]
no_license
二段构建 所谓二段构建,就是指创建对象时不是直接通过构建函数来分配内存并完成初始化操作。取而代之的是,构造函数只 负责分配内存,而初始化的工作则由一些名为initXXX的成员方法来完成。然后再定义一些静态类方法把这两个阶段组 合起来,完成最终对象的构建。因为在《Cocoa设计模式》一书中,把此惯用法称之为“Two Stage Creation”,即“二段 构建”。因为此模式在cocos2d里面被广泛使用,所以把该模式也引入过来了。 1.应用场景: 二段构建在cocos2d-x里面随处可见,自从2.0版本以后,所有的二段构建方法的签名都改成create了。这样做的好处是 一方面统一接口,方便记忆,另一方面是以前的类似Cocoa的命名规范不适用c++,容易引起歧义。下面以CCSprite为类, 来具体阐述二段构建的过程,请看下列代码: //此方法现在已经不推荐使用了,将来可能会删除 CCSprite* CCSprite::spriteWithFile(const char *pszFileName) { return CCSprite::create(pszFileName); } CCSprite* CCSprite::create(const char *pszFileName) { CCSprite *pobSprite = new CCSprite(); //1.第一阶段,分配内存 if (pobSprite && pobSprite->initWithFile(pszFileName)) //2.第二阶段,初始化 { pobSprite->autorelease(); //!!!额外做了内存管理的工作。 return pobSprite; } CC_SAFE_DELETE(pobSprite); return NULL; } 如上面代码中的注释所示,创建一个sprite明显被分为两个步骤:1.使用new来创建内存;2.使用initXXX方法来完成初始化。 因为CCSprite的构造函数也有初始化的功能,所以,我们再来看看CCSprite的构建函数实现: CCSprite::CCSprite(void) : m_pobTexture(NULL) , m_bShouldBeHidden(false) { } 很明显,这个构建函数所做的初始化工作非常有限,仅仅是在初始化列表里面初始化了m_pobTexture和m_bShouldBeHidden两 个变量。实际的初始化工作大部分都放在initXXX系列方法中,大家可以动手去查看源代码。 2.分析为什么要使用此模式? 这种二段构建对于C++程序员来说,其实有点别扭。因为c++的构造函数在设计之初就是用来分配内存+初始化对象的。如果再 搞个二段构建,实则是多此一举。但是,在objective-c里面是没有构造函数这一说的,所以,在Cocoa的编程世界里,二段 构建被广泛采用。而cocos2d-x当初是从cocos2d-iphone移植过来了,为了保持最大限度的代码一致性,所以保留了这种二段 构建方式。这样可以方便移植cocos2d-iphone的游戏,同时也方便cocos2d-iphone的程序员快速上手cocos2d-x。 不过在后来,由于c++天生不具备oc那种可以指定每一个参数的名称的能力,所以,cocos2d-x的设计者决定使用c++的函数重 载来解决这个问题。这也是后来为什么2.0版本以后,都使用create函数的重载版本了。 虽然接口签名改掉了,但是本质并没有变化,还是使用的二段构建。二段构建并没有什么不好,只是更加突出了对象需要初 始化。在某种程度上也可以说是一种设计强化。因为忘记初始化是一切莫名其妙的bug的罪魁祸首。同时,二段构建出来的对 象都是autorelease的对象,而autorelease对象是使用引用计数来管理内存的。客户端程序员在使用此接口创建对象的时候, 无需关心具体实现细节,只要知道使用create方法可以创建并初始化一个自动释放内存的对象即可。 在一点,在《Effective Java》一书中,也有提到。为每一个类提供一个静态工厂方法来代替构造函数,它有以下三个优点: 1.与构造函数不同,静态方法有名字,而构造函数只能通过参数重载。 2.它每次被调用的时候,不一定都创建一个新的对象。比如Boolean.valueOf(boolean)。 3.它还可以返回原类型的子类型对象。 因此,使用二段构建的原因有二: 1.兼容性、历史遗留原因。(这也再次印证了一句话,一切系统都是遗留系统,呵呵) 2.二段构建有其自身独有的优势。 3.使用此模式的优缺点是什么? 优点: 1.显示分开内存分配和初始化阶段,让初始化地位突出。因为程序员一般不会忘记分配内存,但却常常忽略初始化的作用。 2.见上面分析《Effective Java》的第1条:“为每一个类提供一个静态工厂方法来代替构造函数” 3.除了完成对象构建,还可以管理对象内存。 缺点: 1.不如直接使用构造函数来得直白、明了,违反直觉,但这个是相对的。 4.此模式的定义及一般实现 定义: 将一个对象的构建分为两个步骤来进行:1.分配内存 2.初始化 它的一般实现如下: class Test { public: //静态工厂方法 static Test* create() { Test *pTest = new Test; if (pTest && pTest->init()) { //这里还可以做其它操作,比如cocos2d-x里面管理内存 return pTest; } return NULL; } // Test() { //分配成员变量的内存,但不初始化 } bool init(){ //这里初始化对象成员 return true; } private: //这里定义数据成员 }; 5.在游戏开发中如何运用此模式 这个也非常简单,就是今后在使用cocos2d-x的时候,如果你继承CCSprite实现自定义的精灵,你也需要按照“二段构建” 的方式,为你的类提供一个静态工厂方法,同时编写相应的初始化方法。当然,命名规范最好和cocos2d-x统一,即静态 工厂方法为create,而初始化方法为initXXXX。 6.此模式经常与哪些模式配合使用 由于此模式在GoF的设计模式中并未出现,所以暂时不讨论与其它模式的关系。 最后看看cocos2d-x创始人王哲对于为什么要设计成二段构建的看法: “其实我们设计二段构造时首先考虑其优势而非兼容cocos2d-iphone. 初始化时会遇到图片资源不存在等异常,而C++ 构造函数无返回值,只能用try-catch来处理异常,启用try-catch会使编译后二进制文件大不少,故需要init返回bool 值。Symbian, Bada SDK,objc的alloc + init也都是二阶段构造”。
true
562590605821f2d4a42cbe74d88864c49fd4be38
C++
rocky946/data-structure-course
/chapter09/seq_list.cpp
UTF-8
328
2.65625
3
[]
no_license
// 顺序表基本运算算法 #include <stdio.h> #include "seq_list.h" void CreateList(RecType R[], KeyType keys[], int n) { for (int i = 0; i < n; ++i) { R[i].key = keys[i]; } } void DispList(RecType R[], int n) { for (int i = 0; i < n; ++i) { printf("%d ", R[i].key); } printf("\n"); }
true
382c8627933f6c0ad9376d869943a45b82c258c4
C++
LuizaPizzi/VItA
/structures/tree/SproutingVolumetricCostEstimator.cpp
UTF-8
3,237
2.640625
3
[ "Apache-2.0" ]
permissive
/* SPDX-License-Identifier: Apache-2.0 */ /* Copyright 2020 Gonzalo Maso Talou */ /* * SproutingVolumetricCostEstimator.cpp * * Created on: Apr 11, 2018 * Author: Gonzalo D. Maso Talou */ #include "SproutingVolumetricCostEstimator.h" #include "../vascularElements/SingleVessel.h" SproutingVolumetricCostEstimator::SproutingVolumetricCostEstimator(double volumeFactor, double proteolyticFactor, double diffusionFactor): AbstractCostEstimator(){ previousVolume = 0.0; this->proteolyticFactor = proteolyticFactor; this->diffusionFactor = diffusionFactor; this->volumeFactor = volumeFactor; distToParent = 1.0; parentRadius = 1.0; } SproutingVolumetricCostEstimator::~SproutingVolumetricCostEstimator(){ } void SproutingVolumetricCostEstimator::previousState(AbstractObjectCCOTree* tree, AbstractVascularElement* parent, point iNew, point iTest, double dLim){ previousVolume = ((SingleVessel *) tree->getRoot())->treeVolume; point a = ((SingleVessel *)parent)->xProx; point b = ((SingleVessel *)parent)->xDist; // Parent-to-iNew distance // Parent vessel slope point m = b - a; // Parameter for closer projection double t = (m ^ (iNew - a)) / (m^m); // Confine t into [0,1] interval if (t < 0){ t = 0; } else if( t > 1.0){ t = 1.0; } // Closest segment between iNew and parent vessel point proj = (iNew - a) - m * t; distToParent = sqrt(proj ^ proj); parentRadius = ((SingleVessel *)parent)->radius; } double SproutingVolumetricCostEstimator::computeCost(AbstractObjectCCOTree* tree){ double volCost = volumeFactor * (computeTreeCost(tree->getRoot()) - previousVolume); double proteolysisCost = proteolyticFactor * parentRadius; // 500.0 double stimulusCost = diffusionFactor * (distToParent * distToParent); cout << "Volumetric cost = " << volCost << ", Protease degradation cost = " << proteolysisCost << ", VEGF/FGF difussion cost = " << stimulusCost << endl; return volCost + proteolysisCost + stimulusCost ; } double SproutingVolumetricCostEstimator::computeTreeCost(AbstractVascularElement* root) { double currentCost = ((SingleVessel *)root)->getVolume(); vector<AbstractVascularElement *> children = root->getChildren(); for (std::vector<AbstractVascularElement *>::iterator it = children.begin(); it != children.end(); ++it) { currentCost += computeTreeCost(*it); } return currentCost; } AbstractCostEstimator* SproutingVolumetricCostEstimator::clone(){ return (new SproutingVolumetricCostEstimator(volumeFactor, proteolyticFactor, diffusionFactor)); } double SproutingVolumetricCostEstimator::getVolumeFactor() { return this->volumeFactor; } double SproutingVolumetricCostEstimator::getProteolyticFactor() { return this->proteolyticFactor; } double SproutingVolumetricCostEstimator::getDiffusionFactor() { return this->diffusionFactor; } void SproutingVolumetricCostEstimator::logCostEstimator(FILE *fp) { double v_fac, p_fac, d_fac; v_fac = this->getVolumeFactor(); p_fac = this->getProteolyticFactor(); d_fac = this->getDiffusionFactor(); fprintf(fp, "This domain uses SproutingVolumetricCostEstimator.\n"); fprintf(fp, "Volume factor = %f.\n", v_fac); fprintf(fp, "Proteolytic factor = %f.\n", p_fac); fprintf(fp, "Diffusion factor = %f.\n", d_fac); }
true
b166dc7f48720d0535307dbca979a223d3e13bc2
C++
tanjot/Code-Practice
/hashTable_RansomNote.cpp
UTF-8
3,558
3.15625
3
[]
no_license
//******PROBLEM STATEMENT - Hash Tables : Ransom Note******/ //A kidnapper wrote a ransom note but is worried it will be traced back to him. He found a magazine and wants to know if he can cut out whole words from it and use them to create an untraceable replica of his ransom note. The words in his note are case-sensitive and he must use whole words available in the magazine, meaning he cannot use substrings or concatenation to create the words he needs. // //Given the words in the magazine and the words in the ransom note, print Yes if he can replicate his ransom note exactly using whole words from the magazine; otherwise, print No. // //Input Format // //The first line contains two space-separated integers describing the respective values of (the number of words in the magazine) and (the number of words in the ransom note). //The second line contains space-separated strings denoting the words present in the magazine. //The third line contains space-separated strings denoting the words present in the ransom note. // //Constraints // //. //Each word consists of English alphabetic letters (i.e., to and to ). //The words in the note and magazine are case-sensitive. //Output Format // //Print Yes if he can use the magazine to create an untraceable replica of his ransom note; otherwise, print No. // //Sample Input 0 // //6 4 //give me one grand today night //give one grand today //Sample Output 0 // //Yes //Sample Input 1 // //6 5 //two times three is not four //two times two is four //Sample Output 1 // //No //******CODE******/ #include <map> #include <set> #include <list> #include <cmath> #include <ctime> #include <deque> #include <queue> #include <stack> #include <string> #include <bitset> #include <cstdio> #include <limits> #include <vector> #include <climits> #include <cstring> #include <cstdlib> #include <fstream> #include <numeric> #include <sstream> #include <iostream> #include <algorithm> #include <unordered_map> using namespace std; bool create_ransom_note(unordered_map<string, int> magazine, vector<string> ransom) { unordered_map<string, int>::iterator mapIt; for(vector<string>::const_iterator it=ransom.begin(); it != ransom.end(); ++it) { mapIt = magazine.find(*it); if( mapIt == magazine.end())// && mapIt->second <= 0 ) { return false; } else { mapIt->second--; if(mapIt->second == 0) { magazine.erase(*it); } } } return true; } bool ransom_note(vector<string> magazine, vector<string> ransom) { bool ret_val = false; unordered_map<string, int> mag; unordered_map<string, int>::iterator mapIt; //Insert magazine words into map "mag" for(vector<string>::const_iterator it=magazine.begin(); it != magazine.end(); ++it) { mapIt = mag.find(*it); if( mapIt == mag.end() ) { mag.insert(std::make_pair(*it, 1)); } else { mapIt->second++; } } ret_val = create_ransom_note(mag, ransom); return ret_val; } int main(){ int m; int n; cin >> m >> n; vector<string> magazine(m); for(int magazine_i = 0;magazine_i < m;magazine_i++){ cin >> magazine[magazine_i]; } vector<string> ransom(n); for(int ransom_i = 0;ransom_i < n;ransom_i++){ cin >> ransom[ransom_i]; } if(ransom_note(magazine, ransom)) cout << "Yes\n"; else cout << "No\n"; return 0; }
true
8c2269e8eb1fe369cf7c03b8f835cb269a5e496a
C++
ADFLin/GameProject
/Engine/Math/Vector2.h
UTF-8
1,480
3.125
3
[]
no_license
#ifndef Vector2_h__ #define Vector2_h__ #include "Math/Base.h" #include "TVector2.h" namespace Math { class Vector2 : public TVector2< float > { public: Vector2() = default; constexpr Vector2(Vector2 const& rhs) = default; template< class T > constexpr Vector2(TVector2< T > const& rhs) :TVector2<float>(rhs) {} constexpr Vector2(float x, float y) :TVector2<float>(x, y) {} float normalize() { float len = Math::Sqrt(length2()); if( len < FLOAT_DIV_ZERO_EPSILON ) return 0.0; *this *= (1 / len); return len; } float length() const { return Math::Sqrt(length2()); } bool isNormalized() const { return Math::Abs(1 - length2()) < 1e-5; } static inline Vector2 Cross(float value, Vector2 const& v) { return Vector2(-value * v.y, value * v.x); } }; FORCEINLINE Vector2 GetNormal(Vector2 const& v) { Vector2 result = v; result.normalize(); return result; } FORCEINLINE float Distance(Vector2 const& a, Vector2 const& b) { return Vector2(a - b).length(); } // ( a x b ) x c = (a.c)b - (b.c) a FORCEINLINE Vector2 TripleProduct(Vector2 const& a, Vector2 const& b, Vector2 const& c) { return a.dot(c) * b - b.dot(c) * a; } FORCEINLINE Vector2 Perp(Vector2 const& v) { return Vector2(-v.y, v.x); } FORCEINLINE Vector2 Clamp(Vector2 const& v, Vector2 const& min, Vector2 const& max) { return Vector2( Clamp(v.x, min.x, max.x), Clamp(v.y, min.y, max.y)); } } #endif // Vector2_h__
true
8072b68b291ff23cc757c88cb16695bbbdc83006
C++
zeta1999/TrilateralMap
/Mesh.cpp
UTF-8
6,020
3.03125
3
[]
no_license
#pragma once #include "Mesh.h" #include <cmath> void Mesh::loadOff(char* name) { FILE* fPtr = fopen(name, "r"); char str[334]; fscanf(fPtr, "%s", str); int nVerts, nTris, n, i = 0; float x, y, z; fscanf(fPtr, "%d %d %d\n", &nVerts, &nTris, &n); while (i++ < nVerts) { fscanf(fPtr, "%f %f %f", &x, &y, &z); addVertex(x, y, z); } while (fscanf(fPtr, "%d", &i) != EOF) { fscanf(fPtr, "%f %f %f", &x, &y, &z); addTriangle((int)x, (int)y, (int)z); } fclose(fPtr); } void Mesh::loadMesh(std::vector<double> *vs, std::vector<int> *ts){ for (int i = 0; i < vs->size(); i+=3) addVertex(vs->at(i), vs->at(i + 1), vs->at(i + 2)); for (int i = 0; i < ts->size(); i += 3) addTriangle(ts->at(i), ts->at(i + 1), ts->at(i + 2)); } void Mesh::loadOff(char* name, std::vector<double> *vs, std::vector<int> *ts) { FILE* fPtr = fopen(name, "r"); char str[334]; fscanf(fPtr, "%s", str); int nVerts, nTris, n, i = 0; float x, y, z; fscanf(fPtr, "%d %d %d\n", &nVerts, &nTris, &n); while (i++ < nVerts) { fscanf(fPtr, "%f %f %f", &x, &y, &z); addVertex(x, y, z); vs->push_back(x); vs->push_back(y); vs->push_back(z); } while (fscanf(fPtr, "%d", &i) != EOF) { fscanf(fPtr, "%f %f %f", &x, &y, &z); addTriangle((int)x, (int)y, (int)z); ts->push_back((int)x); ts->push_back((int)y); ts->push_back((int)z); } fclose(fPtr); } void Mesh::loadArray(vector<array<double, 3>> vs, vector<array<int, 3>> tris) { for (int i = 0; i < vs.size(); i++) addVertex(vs[i][0], vs[i][1], vs[i][2]); for (int i = 0; i < tris.size(); i++) addTriangle(tris[i][0], tris[i][1], tris[i][2]); } void Mesh::loadOff(char* name, SbVec3f tr) { FILE* fPtr = fopen(name, "r"); char str[334]; fscanf(fPtr, "%s", str); int nVerts, nTris, n, i = 0; float x, y, z; fscanf(fPtr, "%d %d %d\n", &nVerts, &nTris, &n); while (i++ < nVerts) { fscanf(fPtr, "%f %f %f", &x, &y, &z); addVertex(x+tr[0], y+tr[1], z+tr[2]); } while (fscanf(fPtr, "%d", &i) != EOF) { fscanf(fPtr, "%f %f %f", &x, &y, &z); addTriangle((int)x, (int)y, (int)z); } fclose(fPtr); } void Mesh::loadObj(char* path){ std::ifstream file(path); std::string line; while (std::getline(file, line)) { std::stringstream linestream(line); std::string data; float x, y, z; // If you have truly tab delimited data use getline() with third parameter. // If your data is just white space separated data // then the operator >> will do (it reads a space separated word into a string). std::getline(linestream, data, ' '); // read up-to the first tab (discard tab). // Read the integers using the operator >> linestream >> x >> y >> z; char h = data.at(0); if (h == 'v'){ //cout << "Yes" << endl; //cout << h << " " << x << " " << y << " " << z << endl; addVertex(x, y, z); } else if (h == 'f'){ //cout << h << " " << x << " " << y << " " << z << endl; addTriangle((int)x, (int)y, (int)z); } } /*FILE * file = fopen(path, "r"); float x, y, z; char lineHeader[512]; int i = 0; while (fscanf(file, "%s", lineHeader) != EOF){ if (strcmp(lineHeader, "v") == 0){ fscanf(file, "%f %f %f\n", &x, &y, &z); } else if (strcmp(lineHeader, "f") == 0){ fscanf(file, "%f %f %f\n", &x, &y, &z); addTriangle((int)x, (int)y, (int)z); } i++; } fclose(file);*/ } void Mesh::createCube(float sideLen) { //coordinates float flbc[3] = { 0, 0, 0 }, deltaX = 0, deltaY = 0, deltaZ = 0; for (int v = 0; v < 8; v++) { switch (v) { case 1: deltaX = sideLen; break; case 2: deltaZ = -sideLen; break; case 3: deltaX = 0; break; case 4: deltaZ = 0; deltaY = sideLen; break; case 5: deltaX = sideLen; break; case 6: deltaZ = -sideLen; break; default: deltaX = 0;; break; } addVertex(flbc[0] + deltaX, flbc[1] + deltaY, flbc[2] + deltaZ); } addTriangle(0, 2, 1); addTriangle(0, 3, 2); addTriangle(1, 2, 5); addTriangle(2, 6, 5); addTriangle(2, 3, 6); addTriangle(3, 7, 6); addTriangle(3, 4, 7); addTriangle(3, 0, 4); addTriangle(4, 5, 6); addTriangle(4, 6, 7); addTriangle(0, 1, 5); addTriangle(0, 5, 4); } void Mesh::addTriangle(int v1, int v2, int v3) { int idx = tris.size(); tris.push_back(new Triangle(idx, v1, v2, v3)); //set up structure verts[v1]->triList.push_back(idx); verts[v2]->triList.push_back(idx); verts[v3]->triList.push_back(idx); if (!makeVertsNeighbor(v1, v2)) addEdge(v1, v2); if (!makeVertsNeighbor(v1, v3)) addEdge(v1, v3); if (!makeVertsNeighbor(v2, v3)) addEdge(v2, v3); } bool Mesh::makeVertsNeighbor(int v1i, int v2i) { //returns true if v1i already neighbor w/ v2i; false o/w for (int i = 0; i < verts[v1i]->vertList.size(); i++) if (verts[v1i]->vertList[i] == v2i) return true; verts[v1i]->vertList.push_back(v2i); verts[v2i]->vertList.push_back(v1i); return false; } void Mesh::addVertex(float x, float y, float z) { int idx = verts.size(); float* c = new float[3]; c[0] = x; c[1] = y; c[2] = z; verts.push_back(new Vertex(idx, c)); } void Mesh::addEdge(int v1, int v2) { int idx = edges.size(); // Compute the length of edge (Euclidean Distance) //float length = sqrt(pow(verts[v1]->coords[0] - verts[v2]->coords[0], 2) + pow(verts[v1]->coords[1] - verts[v2]->coords[1], 2) + pow(verts[v1]->coords[2] - verts[v2]->coords[2], 2)); edges.push_back(new Edge(idx, v1, v2/*, length*/)); verts[v1]->edgeList.push_back(idx); verts[v2]->edgeList.push_back(idx); } float Mesh::computeDistanceBetweenTwoVertex(Mesh* mesh, int idFirst, int idSecond){ return sqrt(pow(mesh->verts[idFirst]->coords[0] - mesh->verts[idSecond]->coords[0], 2) + pow(mesh->verts[idFirst]->coords[1] - mesh->verts[idSecond]->coords[1], 2) + pow(mesh->verts[idFirst]->coords[2] - mesh->verts[idSecond]->coords[2], 2)); } /////////////////****************************************************//////////////////////////////////*********************************/////////////////////////////////////////***********************
true
d8728a7c9f24a39598ac41620124d41000296e26
C++
Yixi-sha/datastructure_new
/dataStructureLib/src/dynamicarray.cpp
UTF-8
3,295
3.296875
3
[]
no_license
#ifndef DYNAMICARRAY_CPP #define DYNAMICARRAY_CPP #include "../inc/dynamicarray.h" namespace yixi { template <typename T> void DynamicArray<T>::memCopy(T* dis, T* src, int N) { for(int i = 0; i < N ; i++) { dis[i] = src[i]; } } template <typename T> void DynamicArray<T>::update(T* newMem, int newSize) { T* origin = this->i_mem; this->i_mem = newMem; i_size = newSize; if(origin != nullptr) delete[] origin; } template <typename T> DynamicArray<T>::DynamicArray(int size ) : i_size(size) { if(0 != size) { this->i_mem = (new T[size]); if(this->i_mem == nullptr) { i_size = 0; THROW_EXCEPTION(NoEnoughMemoryException, "No Enough Memory to create DynamicArray"); } } else { this->i_mem = nullptr; } } template <typename T> DynamicArray<T>::DynamicArray(const DynamicArray<T>& obj) : i_size(obj.size()) { if(0 != obj.size()) { T* temp = (new char[obj.size()]); if(temp != nullptr) { memCopy(temp, obj.i_mem, obj.size()); this->i_mem = temp; } else { i_size = 0; THROW_EXCEPTION(NoEnoughMemoryException, "No Enough Memory to create DynamicArray"); } } else { this->i_mem = nullptr; } } template <typename T> DynamicArray<T>& DynamicArray<T>::operator =(const DynamicArray<T>& obj) { if(this != &obj) { if(0 != obj.size()) { T *temp =(new T[obj.size()]); if(temp != nullptr) { memCopy(temp, obj.i_mem, obj.size()); update(temp, obj.size()); } else { THROW_EXCEPTION(NoEnoughMemoryException, "No Enough Memory to copy DynamicArray"); } } else { this->i_size = 0; if(this->i_mem != nullptr) { T* temp = this->i_mem; this->i_mem = nullptr; delete[] temp; } } } return *this; } template <typename T> int DynamicArray<T>::size() const { return i_size; } template <typename T> bool DynamicArray<T>::reSize(int size) { bool ret = true; if(size != i_size) { if(0 != size) { T* temp = (new T[size]); if(temp != nullptr) { int tempSize = i_size < size ? i_size : size; memCopy(temp, this->i_mem, tempSize); update(temp, size); } else { ret = false; THROW_EXCEPTION(NoEnoughMemoryException, "No Enough Memory to resize DynamicArray"); } } else { this->i_size = 0; if(this->i_mem != nullptr) { T* temp = this->i_mem; this->i_mem = nullptr; delete[] temp; } } } return ret; } template <typename T> DynamicArray<T>::~DynamicArray() { if(this->i_mem != nullptr) { T* temp = this->i_mem; this->i_mem = nullptr; delete[] temp; } } } #endif // DYNAMICARRAY_CPP
true
27379f5f0e2faa751fcd4fe7b1a3a7ee9e795f0e
C++
humorbei/ThicknessGauge
/ThicknessGaugeNullSaver/ThicknessGaugeNullSaver.cpp
UTF-8
948
2.71875
3
[ "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
// ThicknessGaugeNullSaver.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <string> #include <opencv2/core/mat.hpp> #include <opencv2/videoio.hpp> #include <opencv2/videoio/videoio_c.h> #include <opencv2/imgcodecs.hpp> void save_null() { std::string filename; std::cout << "Enter filename to capture null file as.>"; std::cin >> filename; if (filename.empty()) { std::cout << "You must give a filename.\n"; return; } // quick and dirty hack to save null image quickly std::cout << "Enter delay in seconds before capture to " << filename << "\n>"; int t; std::cin >> t; cv::Mat nullImage; cv::VideoCapture cap; cap.open(CV_CAP_PVAPI); cap >> nullImage; cv::imwrite(filename, nullImage); cap.release(); } // simple application to generate null image files. int main() { save_null(); return 0; }
true
90841dd3e00615a2d0118cad04f11eb6a3731560
C++
xiays146/ComputerRoomManagementSystem_V0
/admin.cpp
GB18030
3,507
3.21875
3
[]
no_license
#include "admin.h" #include "mianFunction.h" Admin::Admin() {} Admin::Admin(string name, string password) { name = name; password = password; initVector(); } //˵ void Admin::openMenu() { cout << "\t+----------------+\n"; cout << "\t| 1.˺ |\n"; cout << "\t| 2.鿴˺ |\n"; cout << "\t| 3.鿴 |\n"; cout << "\t| 4.ԤԼ |\n"; cout << "\t| 0.ע½ |\n"; cout << "\t+----------------+\n"; } // void Admin::addPerson() { cout << "ӵͣ" << endl; cout << "1.ѧ˻" << endl; cout << "2.ʦ˻" << endl; //ûѡ int select; cin >> select; //û string name; string pwd; string id; string file; if (select == 1) { cout << "ѧţ\n"; cin >> id; while (checkRepeat(id, select)) {//idظ cout << "ѧظ..." << endl; cin >> id; } file = STUDENT_FILE; } else if (select == 2) { cout << "ְţ\n"; cin >> id; while (checkRepeat(id, select)) {//idظ cout << "ְظ..." << endl; cin >> id; } file = TEACHER_FILE; } cout << "\n"; cin >> name; cout << "룺\n"; cin >> pwd; //洢 ofstream ofs; ofs.open(file, ios::out | ios::app); ofs << id << " " << name << " " << pwd << endl; ofs.close(); printMessage("ӳɹ"); //ӳɹ󣬵ʼӵ initVector(); } void Admin::showPerson() { cout << "ѡ鿴ݣ" << endl; cout << "1.ѧ˻Ϣ" << endl; cout << "2.нʦ˻Ϣ" << endl; int select = 0; cin >> select; if (select == 1) { //show student cout << "ѧ˺Ϣ£" << endl; for (auto it = vStudent.begin(); it != vStudent.end(); it++) cout << "ѧID" << it->getID() << " ˻" << it->name << " ˻룺" << it->password << endl; } else { //show teacher cout << "ʦ˺Ϣ£" << endl; for (auto it = vTeacher.begin(); it != vTeacher.end(); it++) cout << "ְID" << it->getID() << " ˻" << it->name << " ˻룺" << it->password << endl; } } void Admin::showComputer() {} void Admin::clearFile() {} void Admin::initVector() { ifstream ifs; vStudent.clear(); ifs.open(STUDENT_FILE, ios::in); if (!ifs.is_open()) { printMessage("ļʧܣ"); return; } //Student stu; string id, name, pwd; while (ifs >> id && ifs >> name && ifs >> pwd) { Student stu = Student(id, name, pwd); vStudent.push_back(stu); } cout << "ǰѧΪ" << vStudent.size() << endl; ifs.close(); vTeacher.clear(); ifs.open(TEACHER_FILE, ios::in); if (!ifs.is_open()) { printMessage("ļʧܣ"); return; } //string id, name, pwd; while (ifs >> id && ifs >> name && ifs >> pwd) { Teacher teacher = Teacher(id, name, pwd); vTeacher.push_back(teacher); } cout << "ǰʦΪ" << vTeacher.size() << endl; ifs.close(); } bool Admin::checkRepeat(string id, int type) { if (type == 1) {//ѧid for (auto it = vStudent.begin(); it != vStudent.end(); it++) { if (it->getID() == id) return true; } } else {//ʦid for (auto it = vTeacher.begin(); it != vTeacher.end(); it++) { if (it->getID() == id) return true; } } return false; }
true
659db987c5c126849f0277dfe405d783d9317f52
C++
olejniczakmarcin/Implementacja-List
/ListaDwukierunkowa/main.cpp
UTF-8
578
2.890625
3
[]
no_license
#include <iostream> #include "BidirectionalList.h" int main() { BidirectionalList* head = new BidirectionalList(2); head->AddToTheEnd(3); head->AddToTheEnd(2); head->AddToTheEnd(1); head = head->AddToTheBegining(11); head->PrintNext(); head->PrintPrev(); std::cout<<"rozmiar listy "<< head->Size() << "\n"; head = head->RemoveFirst(); //head=head.removefirst(); head->PrintNext(); head->RemoveElement(4); head->PrintNext(); //head.removeelement(2); //head.printnext(); //head=head.removeelement(1); //head.printnext(); head->RemoveElement(6); delete head; }
true
46e96889927a1732a181108c47024561940a44b8
C++
code0monkey1/Competitive
/unique_pairs.cpp
UTF-8
766
2.65625
3
[]
no_license
/*input abacaba */ #include<bits/stdc++.h> using namespace std; //defines #define all(c) c.begin(), c.end() #define fastio ios_base::sync_with_stdio(false);cin.tie(NULL); #define ll long long #define vii vector< vi > #define vi vector<int> #define re(i,a,b) for(int i=int(a);i<int(b);i++) #define pb push_back #define all(c) c.begin(), c.end() #define present(container, element) (container.find(element) != container.end()) //for map,set..etc #define cpresent(container, element) (find(all(container),element) != container.end()) //for vectors #define mp make_pair /* FILE IO freopen("in.txt","r",stdin); freopen("out.txt","w",stdout); */ int main(){ float f=1.0/6.0 ; cout<<to_string(f); return 0; }
true
604b7a1ab06299cd8039a98b0992c57dc1730dae
C++
rvolosenkov/TP-Patterns
/Game.h
UTF-8
5,378
2.765625
3
[]
no_license
#ifndef GAME_GAME_H #define GAME_GAME_H class CUnit { public: virtual void set_strength(unsigned int strength) = 0; virtual void set_health(unsigned int health) = 0; virtual void set_intelligence(unsigned int intelligence) = 0; virtual void set_charisma(unsigned int charisma) = 0; virtual void set_weapon(unsigned int weapon) = 0; virtual int get_strength() const = 0; virtual int get_health() const = 0; virtual int get_intelligence() const = 0; virtual int get_charisma() const = 0; virtual int get_weapon() const = 0; virtual void show_parametres() const = 0; }; class CWarrior : public CUnit { public: CWarrior() : m_strength(0), m_health(0), m_intelligence(0), m_charisma(0), m_weapon(0) {} void set_strength(unsigned int strength) override; void set_health(unsigned int health) override; void set_intelligence(unsigned int intelligence) override; void set_charisma(unsigned int charisma) override; void set_weapon(unsigned int weapon) override; int get_strength() const override; int get_health() const override; int get_intelligence() const override; int get_charisma() const override; int get_weapon() const override; void show_parametres() const override; private: unsigned int m_strength; unsigned int m_health; unsigned int m_intelligence; unsigned int m_charisma; unsigned int m_weapon; }; bool operator==(const CWarrior& first_warrior, const CWarrior& second_warrior); class CAgent : public CUnit { public: CAgent() : m_strength(0), m_health(0), m_intelligence(0), m_charisma(0), m_weapon(0) {} void set_strength(unsigned int strength) override; void set_health(unsigned int health) override; void set_intelligence(unsigned int intelligence) override; void set_charisma(unsigned int charisma) override; void set_weapon(unsigned int weapon) override; int get_strength() const override; int get_health() const override; int get_intelligence() const override; int get_charisma() const override; int get_weapon() const override; void show_parametres() const override; private: unsigned int m_strength; unsigned int m_health; unsigned int m_intelligence; unsigned int m_charisma; unsigned int m_weapon; }; bool operator==(const CAgent& first_agent, const CAgent& second_agent); class CDragon : public CUnit { public: CDragon() : m_strength(0), m_health(0), m_intelligence(0), m_charisma(0), m_weapon(0) {} void set_strength(unsigned int strength) override; void set_health(unsigned int health) override; void set_intelligence(unsigned int intelligence) override; void set_charisma(unsigned int charisma) override; void set_weapon(unsigned int weapon) override; int get_strength() const override; int get_health() const override; int get_intelligence() const override; int get_charisma() const override; int get_weapon() const override; void show_parametres() const override; private: unsigned int m_strength; unsigned int m_health; unsigned int m_intelligence; unsigned int m_charisma; unsigned int m_weapon; }; bool operator==(const CDragon& first_dragon, const CDragon& second_dragon); class CWizard : public CUnit { public: CWizard() : m_strength(0), m_health(0), m_intelligence(0), m_charisma(0), m_weapon(0) {} void set_strength(unsigned int strength) override; void set_health(unsigned int health) override; void set_intelligence(unsigned int intelligence) override; void set_charisma(unsigned int charisma) override; void set_weapon(unsigned int weapon) override; int get_strength() const override; int get_health() const override; int get_intelligence() const override; int get_charisma() const override; int get_weapon() const override; void show_parametres() const override; private: unsigned int m_strength; unsigned int m_health; unsigned int m_intelligence; unsigned int m_charisma; unsigned int m_weapon; }; bool operator==(const CWizard& first_wizard, const CWizard& second_wizard); template <class T> class CSingleton { public: CSingleton() = delete; ~CSingleton() = delete; CSingleton(const CSingleton&) = delete; CSingleton& operator=(const CSingleton&) = delete; static T* get_instance(); private: static T* m_instance; }; class CArmyFactory { public: virtual CWarrior* create_warrior() = 0; virtual CAgent* create_agent() = 0; virtual CDragon* create_dragon() = 0; virtual CWizard* create_wizard() = 0; }; class CHumanArmyFactory : public CArmyFactory { public: CWarrior* create_warrior() override; CAgent* create_agent() override; CDragon* create_dragon() override; CWizard* create_wizard() override; }; class CAlienArmyFactory : public CArmyFactory { public: CWarrior* create_warrior() override; CAgent* create_agent() override; CDragon* create_dragon() override; CWizard* create_wizard() override; }; class Army { public: Army() = default; void add_unit(CUnit* curr_unit); void show_army(); private: std::vector<CUnit*> my_army; }; #endif //GAME_GAME_H
true
fcf9fed1736fed8a1e70ddb901ca8f47e2cbb447
C++
ForyMurguia/2048
/2048/GameState.h
UTF-8
1,427
3.25
3
[]
no_license
#pragma once #include <stdint.h> #include <stdlib.h> #include <iostream> #include <string> using namespace std; const uint8_t BOARD_SIZE = 4; enum InputDirection { UP, RIGHT, LEFT, DOWN, NONE, UNDO, }; const string inputNames[6] = { "UP", "RIGHT", "LEFT", "DOWN", "UNDO", "NONE" }; const int64_t tilePoints[4][4] = { {1 << 12, 1 << 13, 1 << 14, 1 << 15}, {1 << 11, 1 << 10, 1 << 9, 1 << 8}, {1 << 4, 1 << 5, 1 << 6, 1 << 7}, {1 << 3, 1 << 2, 1 << 1, 1} }; class GameState { public: GameState(); ~GameState(); void startNewGame(); string getTileString(); string getStateString(); void print(); bool move(InputDirection); int64_t getNumSteps(); int64_t getPoints(); void addRandomTile(); void copy(GameState &other); uint8_t getTile(int r, int c); int getNumFreeTiles(); int64_t getFitness(); void addTile(uint8_t position, uint8_t value); int8_t randomTile(); int8_t randomTileValue(); private: uint8_t myBoard[BOARD_SIZE][BOARD_SIZE]; uint8_t myNumFreeTiles; uint64_t myPoints; uint64_t myNumSteps; bool mergeTiles(InputDirection direction); bool shiftTiles(InputDirection direction); void initialize(); int getStepRowR(InputDirection direction); int getStepRowC(InputDirection direction); int getStepColumnR(InputDirection direction); int getStepColumnC(InputDirection direction); int getStartR(InputDirection direction); int getStartC(InputDirection direction); };
true
664af144d6ec086a1e65a56dfb33e06ef0547c44
C++
netogallo/rainbow
/src/FileSystem/FileSystem.h
UTF-8
2,391
2.703125
3
[ "MIT" ]
permissive
// Copyright (c) 2010-16 Bifrost Entertainment AS and Tommy Nguyen // Distributed under the MIT License. // (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT) #ifndef FILESYSTEM_FILESYSTEM_H_ #define FILESYSTEM_FILESYSTEM_H_ #include <system_error> #include "FileSystem/Path.h" namespace rainbow { namespace filesystem { /// <summary>Creates an absolute path.</summary> auto absolute(const char* path) -> Path; /// <summary>Creates new directories.</summary> bool create_directories(const char* path, std::error_code& error); inline bool create_directories(const Path& path, std::error_code& error) { return create_directories(path.c_str(), error); } /// <summary>Returns current working directory.</summary> auto current_path(const char* path = nullptr) -> const char*; /// <summary>Returns path of executable.</summary> auto executable_path(const char* argv0 = nullptr) -> const char*; /// <summary> /// Returns whether <paramref name="path"/> refers to a directory. /// </summary> bool is_directory(const char* path, std::error_code& error); inline bool is_directory(const Path& path, std::error_code& error) { return is_directory(path.c_str(), error); } /// <summary> /// Returns whether <paramref name="path"/> refers to a regular file. /// </summary> bool is_regular_file(const char* path, std::error_code& error); inline bool is_regular_file(const Path& path, std::error_code& error) { return is_regular_file(path.c_str(), error); } /// <summary> /// Creates a path relative to the current working directory. /// </summary> auto relative(const char* path) -> Path; /// <summary>Removes a file or empty directory.</summary> bool remove(const char* path, std::error_code& error); inline bool remove(const Path& path, std::error_code& error) { return remove(path.c_str(), error); } /// <summary>Creates a path relative to the user's data directory.</summary> auto user(const char* path) -> Path; /// <summary>Returns user data directory.</summary> auto user_data_path() -> const char*; #ifdef RAINBOW_TEST /// <summary>Sets current working directory.</summary> void set_current_path(const char* path); #endif }} // namespace rainbow::filesystem #endif
true
51fefdd4515a528eb9f1eadf4137fc80ae836fa5
C++
Synodiporos/TestC
/Test/src/Model/Task.h
UTF-8
633
2.5625
3
[]
no_license
/* * Task.h * * Created on: 27 �α� 2018 * Author: Synodiporos */ #ifndef MODEL_TASK_H_ #define MODEL_TASK_H_ class Task { public: Task(const char* name, unsigned short duration); Task(const char* name, unsigned short duration, bool editable); virtual ~Task(); void setName(const char* name); const char* getName(); void setDuration(unsigned int duration); unsigned int getDuration(); bool isEditable(); void setEditable(bool editable); private: const char* name; //Duration in seconds unsigned int duration = 0; bool editable = true; }; #endif /* MODEL_TASK_H_ */
true
e216e6912d3c41eb9bb996fcbf69bf346a617376
C++
Miautawn/VU_OP_Uzduotis2_2
/Extensions/student_functions.cpp
UTF-8
5,575
2.96875
3
[]
no_license
#include "student_functions.hpp" //funkcija, kuri palygina du studentus pagal pavardę ar vardą bool student_compare_names(Student l_student, Student r_student) { return (l_student.get_last_name() == r_student.get_last_name()) ? l_student.get_name() < r_student.get_name() : l_student.get_last_name() < r_student.get_last_name(); } template <class Container> void sort_students(Container &students, string sort_argument) { if(sort_argument == "GRADES") { std::sort(students.begin(), students.end()); } else if(sort_argument == "NAMES") { std::sort(students.begin(), students.end(), student_compare_names); } } template <> void sort_students(list<Student> &students, string sort_argument) { students.sort(); } void student_benchmark_generate_file(int n, string file_name) { vector<Student> generated_students; Student bench_student; std::ostringstream buffer; buffer<<"VARDAS PAVARDĖ"<<endl; for(int i = 0; i<n; i++) { //duomenų generavimas bench_student.clear_grades(); bench_student.set_name("Vardas" + std::to_string(i+1)); bench_student.set_last_name("Pavarde" + std::to_string(i+1)); int grade_num = -1; bench_student.generate_grades(grade_num, false); //studento buferizavimas buffer<<left<<setw(15) <<bench_student.get_name()<<" "<<setw(30) <<bench_student.get_last_name(); for(int j = 0; j<bench_student.get_grade(); j++) buffer<<left<<setw(5)<<bench_student.get_grade(j)<<setw(5); buffer<<bench_student.get_exam_score()<<endl; } //išvedimas mūsų benchmark failo ofstream output(file_name); output << buffer.str(); output.close(); } template <class Container> void student_benchmark(Container bench_students, string container_code, string split_mode) { int stages[5] = {1000, 10000, 100000, 1000000, 10000000}; double full_time; Timer m_timer; string local_file; for(int stage_index = 0; stage_index < 5; stage_index++) { // bench_students.reserve(stages[stage_index]); cout<<"\n***************************"; cout<<"\nPradedamas tikrinimas su "<<stages[stage_index]<<" studentų..."<<endl; local_file = "bench_temp" + std::to_string(stages[stage_index]) + ".txt"; m_timer.reset(); full_time = 0; //failo kūrimas if(!files_exists(local_file)) { student_benchmark_generate_file(stages[stage_index], local_file); cout<<stages[stage_index]<<" studentų generavimas ir failo kūrimas užtruko: " <<m_timer.split_time(full_time)<<endl; } //failo nuskaitymas read_students_from_file(bench_students, "bench_temp" + std::to_string(stages[stage_index]) + ".txt", false); cout<<stages[stage_index]<<" studentų nuskaitymas užtruko: " <<m_timer.split_time(full_time)<<endl; //studentų rūšiavimas į dvi grupes: /////////////////////////////////// //1) surušiavimas didėjimo tvarka sort_students(bench_students); cout<<stages[stage_index]<<" studentų surūšiavimas didėjimo tvarka užtruko: " <<m_timer.split_time(full_time)<<endl; //2) pirmo >= 5 radimas typename Container::iterator first_good_student = std::lower_bound(bench_students.begin(), bench_students.end(), 5, [](const Student &l_student, const int value) { return l_student.get_final_score_mean() < value; }); //3) kietaku ir varguoliu į skirtingus konteinerius paskirstymas Container temp_kietuoliai; Container temp_varguoliai; Container *kietuoliai = &temp_kietuoliai; Container *varguoliai = &temp_varguoliai; if(split_mode == "COPY") { temp_kietuoliai = {first_good_student, bench_students.end()}; temp_varguoliai = {bench_students.begin(), first_good_student}; } else { temp_kietuoliai = {first_good_student, bench_students.end()}; bench_students.erase(first_good_student, bench_students.end()); varguoliai = &bench_students; } cout<<stages[stage_index]<<" Įrašų 'kietakų' ir 'varguolių' rūšiavimas užtruko: " <<m_timer.split_time(full_time)<<endl; /////////////////////////////////// //studentų rūšiavimas į dvi grupes: //kietakų išvedimas į failą local_file = "Benchmark/bench_kietuoliai" + std::to_string(stages[stage_index]) + ".txt"; output_to_file(*kietuoliai, "GRADES", false, local_file); cout<<stages[stage_index]<<" Įrašų 'kietuolių' išvedimas į failą užtruko: " <<m_timer.split_time(full_time)<<endl; //nabagėlių išvedimas į failą local_file = "Benchmark/bench_varguoliai" + std::to_string(stages[stage_index]) + ".txt"; output_to_file(*varguoliai, "GRADES", false, local_file); cout<<stages[stage_index]<<" Įrašų 'varguolių' išvedimas į failą užtruko: " <<m_timer.split_time(full_time)<<endl; //galutinio laiko išrašymas cout<<stages[stage_index]<<" VISAS TESTAS UŽTRUKO: "<<full_time<<endl; if(stage_index != 4) { if(!yes_or_no("Ar norite testi?")) break; else bench_students.clear(); } } } template void sort_students(vector<Student> &students, string sort_argument); template void sort_students(deque<Student> &students, string sort_argument); template void student_benchmark(vector<Student> bench_students, string container_code, string split_mode); template void student_benchmark(list<Student> bench_students, string container_code, string split_mode); template void student_benchmark(deque<Student> bench_students, string container_code, string split_mode);
true
93c01c43ec01ece3e1be4066f3aa55ed84df5912
C++
souvikxyz/Algorithms
/binary-tree-problems/kth-largest-element.cpp
UTF-8
1,183
4
4
[]
no_license
#include <bits/stdc++.h> using namespace std; class Node { public: int data; Node *left, *right; Node(int data); }; Node ::Node(int data) { this->data = data; } void kth_largest_element(Node *root, int k, int &count) { if (root != NULL && count < k) { kth_largest_element(root->right, k, count); count++; if (count == k) { cout << root->data << endl; return; } kth_largest_element(root->left, k, count); } } Node *insert(Node *node, int key) { if (node == NULL) return new Node(key); if (key < node->data) node->left = insert(node->left, key); else if (key > node->data) node->right = insert(node->right, key); return node; } int main() { /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ Node *root = NULL; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); int c = 0; kth_largest_element(root, 4, c); return 0; }
true
19c2adb194c3e5aadcb19f08052c7517ce575022
C++
Makaronodentro/imperial
/cpp/revision/practice_tests/piglatin.cpp
UTF-8
2,372
3.046875
3
[]
no_license
#include "piglatin.h" int findFirstVowel(const char* str){ int c = 0; if(tolower(str[0]) == 'y'){ str++; c++; } while(str[0] && !isVowel(str[0])){ str++; c++; } if(str[0] == 'y'){ str++; if(!str[0]){ c++; } } return c; } bool isVowel(char c){ c = tolower(c); if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'y'){ return true; } return false; } void translateWord(const char* str, char* out){ strcpy(out, str); // if digit, leave as is if(isdigit(str[0])) return; int fv = findFirstVowel(str); // if findFirstVowel == 0, add way at the end of the word if(fv == 0) strcat(out, "way"); else { shiftElements(out, fv); strcat(out, "ay"); } } void shiftElements(char* in, int n){ int l = strlen(in); char t[l]; for(int i = 0; i < l; i++){ t[i] = in[(i+n)%l]; } strcpy(in, t); } void translateStream(istream& in, ostream& out){ char line[256]; char word[64] = ""; char tran[64] = ""; memset(word,0,sizeof(word)); memset(word,0,sizeof(word)); char c[2]; c[1] = '\0'; in.get(c[0]); while(in.getline(line, 256)){ while(get_word(const char *input_line, int word_number, char *output_word)) translateWord(word, tran); out<<tran; out<<c[0]; memset(word,0,sizeof(word)); memset(word,0,sizeof(word)); } else{ out<<c[0]; } in.get(c[0]); } } bool get_word(const char *input_line, int word_number, char *output_word) { char *output_start = output_word; int words = 0; if (word_number < 1) { *output_word = '\0'; return false; } do { while (*input_line && !isalnum(*input_line)) input_line++; if (*input_line == '\0') break; output_word = output_start; while (*input_line && (isalnum(*input_line) || *input_line=='\'')) { *output_word = toupper(*input_line); output_word++; input_line++; } *output_word = '\0'; if (++words == word_number) return true; } while (*input_line); *output_start = '\0'; return false; }
true
d3265f3330f69614742cb4be560a6dcc76a8b75c
C++
amrufathy/Interpreter
/src/Hash.cpp
UTF-8
2,522
3.578125
4
[]
no_license
#include "Hash.h" hash::hash() /**Constructor*/ { for(int i=0; i<tablesize; i++) { hashtable[i]=new VAR; hashtable[i]->name="empty"; hashtable[i]->value=0; hashtable[i]->next=NULL; } } /**must be changed*/ int hash::Hash(string key) { int hash=0; int index; for (int i = 0; i <key.length(); i++) { hash=hash+(int)key[i]; } index=hash%tablesize; return index; } /// Add a name and value to the table bool hash::add(const char* name, double value) { int index =Hash(name); bool sucess; if(hashtable[index]->name=="empty") { hashtable[index]->name=name; hashtable[index]->value=value; sucess=true; } else { VAR *ptr = hashtable[index]; VAR *n=new VAR; n->name=name; n->value=value; n->next=NULL; while(ptr->next!=NULL) { ptr=ptr->next; } ptr->next = n; sucess=true; } return sucess; } bool hash::getIndex(const char* name) { int index=Hash(name); bool foundname=false; VAR *ptr=hashtable[index]; while(ptr) { if(ptr->name==name) { foundname=true; } ptr=ptr->next; } if(foundname==true) { return index; } else { return -1; } } bool hash::getValue(const char* name, double* value) { int index=Hash(name); bool foundname=false; VAR *ptr=hashtable[index]; while(ptr) { if(ptr->name==name) { foundname=true; *value=ptr->value; } ptr=ptr->next; } return foundname; } int hash::countitems(int index) { int c=0; if(hashtable[index]->name=="empty") { return c; } else { c++; VAR *ptr=hashtable[index]; while(ptr->next!=NULL) { printf("%d\n",c); c++; ptr=ptr->next; } } return c; } void hash::printitem(int index) { VAR *ptr=hashtable[index]; if(ptr->name=="empty") { cout<<"index= "<<index<<" is empty \n"; } else { cout<<"index"<<index<<"contains these items\n"; while(ptr->next!=NULL) { cout<<"--------------------------------\n"; cout<<ptr->name<<endl; cout<<ptr->value<<endl; cout<<"--------------------------------\n"; ptr=ptr->next; } } }
true
c7162b19548cc3d9f63360535e169cc3b2c23dc0
C++
PeymanJahangirlou/DSS_NCP_TAKE_HOME_EXERCISE_V5
/Mproject/GLApp/GLApp/JsonParser.h
UTF-8
2,365
2.703125
3
[]
no_license
/* * Disney DSS-NCP Take Home Exercise v5 * * @author Peyman Jahangirlou * @brief Json Parser class: * - load json from web then read movies from home url (default mode) * - load json from web then read movies from erf url (default mode) * - then populates MovieContainer map. */ #ifndef JsonParser_h #define JsonParser_h #include <string> #include <iostream> #include <unordered_set> #include <unordered_map> #include <memory> #include <json\json.h> #define CURL_STATICLIB #include <curl\curl.h> #pragma comment(lib,"Normaliz.lib") #pragma comment(lib,"Ws2_32.lib") #pragma comment(lib,"Wldap32.lib") #pragma comment(lib,"Crypt32.lib") #pragma comment(lib,"advapi32.lib") #include "Movie.h" using std::unordered_map; using std::unordered_set; using std::string; /* * Simple Json parser class which reads from json file */ class JsonParser { public: typedef unordered_map<string, unordered_set<std::shared_ptr<Movie>>> MovieContainer; /* @brief default construct, sets default json url to M_urlLink */ JsonParser(); /** @brief read json file from url by refId **/ bool readByRefId(const string& refId); /** @brief read json file from home url **/ bool readDefault(); /** @brief read default json file and appends refId to refIdSet **/ void getRefIds(unordered_set<string>& refIdSet); /** @brief read each movie from json file then appends to movieSet **/ void getMovieSet(MovieContainer & movieMap); Json::Value root() { return M_root; } private: enum class Mode {default, refId}; string M_urlLink; Json::Value M_root; Mode M_mode{ Mode::default }; const string M_homeUrl{ "https://cd-static.bamgrid.com/dp-117731241344/home.json" }; const string M_refUrl{ "https://cd-static.bamgrid.com/dp-117731241344/sets/" }; /** @brief curl call back function **/ static size_t M_curlWriteToString(void* buffer, size_t size, size_t nmemb, void* userp); /* * @brief read json file from url then M_root has everything. * @return true upon successful read, otherwise false. */ bool M_read(); /** @brief helper function -> iterates throug MovieItems and append each to MovieMap **/ void M_populateMovieSet(const string & contentClassStr, const Json::Value & movieItems, MovieContainer& movieMap); }; #endif
true
5b6e8880d4d775aeccd43c69a2a6222ec3bfa0f2
C++
jpborsi/learn-cpp-codejam
/2017/1-B/1B-B.cpp
UTF-8
2,857
3
3
[]
no_license
//2017 Round 1B, Problem B #include <iostream> #include <string> #include <map> #include <set> using namespace std; string illegalStrings[] = {"RR","OO","YY","GG","BB","VV", "RO","OR","RV","VR","OY","YO","OG","GO","OV","VO","YG","GY", "BG","GB","BV","VB","GV","VG"}; set<string> illegal(illegalStrings,illegalStrings+24); bool check(string s){ if (s.length() <= 1){ return true; } for(int i = 0; i < s.length()-1; i++){ if(illegal.find(s.substr(i,2)) != illegal.end()){ return false; } } string connect = ""; connect += s[0]; connect += s[s.length()-1]; if(illegal.find(connect) != illegal.end()){ return false; } return true; } string getArrangement(int N, int R, int O, int Y, int G, int B, int V){ if(R < G || Y < V || B < O){ return "IMPOSSIBLE"; } if(R > N/2 || B > N/2 || Y > N/2){ return "IMPOSSIBLE"; } int placedR = 0; int placedY = 0; int placedB = 0; string s = ""; for(int i = 0; i < O; i++){ s += "BO"; placedB++; } if(O > 0 && s.length() < N){ s+= "B"; placedB++; } for(int i = 0; i < V; i++){ s+= "YV"; placedY++; } if(V > 0 && s.length() < N){ s+= "Y"; placedY++; } for(int i = 0; i < G; i++){ s+= "RG"; placedR++; } if(G > 0 && s.length() < N){ s+= "R"; placedR++; } if(s.length()==N && check(s)){ return s; } if(s.length()==0){ if(R > B && R > Y){ s = "R"; placedR++; }else if(B > Y){ s = "B"; placedB++; }else{ s = "Y"; placedY++; } } map<char,int> leftToPlace; leftToPlace['B'] = B - placedB; leftToPlace['R'] = R - placedR; leftToPlace['Y'] = Y - placedY; while(s.length() < N){ //cout << s << endl; char firstChar = s[0]; char lastChar = s[s.length()-1]; //cout << firstChar << lastChar << endl; //cout << leftToPlace[firstChar] << leftToPlace[lastChar] << endl; if(lastChar=='B'){ if(leftToPlace['Y']>leftToPlace['R'] || (leftToPlace['Y']==leftToPlace['R']&&firstChar=='Y')){ s += 'Y'; leftToPlace['Y'] = leftToPlace['Y']-1; }else{ s += 'R'; leftToPlace['R'] = leftToPlace['R']-1; } }else if(lastChar=='Y'){ if(leftToPlace['B']>leftToPlace['R']|| (leftToPlace['B']==leftToPlace['R']&&firstChar=='B')){ s += 'B'; leftToPlace['B'] = leftToPlace['B']-1; }else{ s += 'R'; leftToPlace['R'] = leftToPlace['R']-1; } }else{ if(leftToPlace['B']>leftToPlace['Y']|| (leftToPlace['B']==leftToPlace['Y']&&firstChar=='B')){ s += 'B'; leftToPlace['B'] = leftToPlace['B']-1; }else{ s += 'Y'; leftToPlace['Y'] = leftToPlace['Y']-1; } } } if(check(s)){ return s; }else{ //cout << "ERROR" << endl; return "IMPOSSIBLE"; } } int main(){ int T; int N, R, O, Y, G, B, V; cin >> T; for(int i = 1; i <= T; i++){ cin >> N >> R >> O >> Y >> G >> B >> V; cout << "Case #" << i << ": " << getArrangement(N, R, O, Y, G, B, V) << endl; } }
true
45778d400b16d31a82ee2612520165f3954a52cf
C++
DevwratJoshi/VolBot-Velocity-Verlet-sim
/src/test.cpp
UTF-8
13,744
2.734375
3
[]
no_license
/* * volbot_classes.cpp * The force on the robot will edit the velocity, which will edit the position * The functions will be run for all the particles, and the new values will edit the new frame * of the simulation * Created on: Oct 29, 2018 * Author: dev */ #include "volbot_classes.h" #include<iostream> #include<cmath> using namespace std; using namespace VolBot2D; using namespace cv; float modulus(float a) { if(a < 0) { a = -a; } return a; } int render(Mat image, VolBot* Balls, Container Box, Simulator S) { int i = 0; static char wndname[] = "VolBot"; Scalar robot_colour (0, 0, 220); Scalar container_colour (220, 0, 0); Point center, pt1, pt2, pt3, pt4; // The center of a particular ball and four corners of the container //* The first corner of the rectangle is considered to be the top left corner. The next point is on position forward in the //* counter clockwise direction for(i = 0; i < NUMBER_OF_BALLS; i++) { center.x = Balls[i].position[0] * S.size_ratio; center.y = Balls[i].position[1]* S.size_ratio; circle(image, center, (int)Balls[i].give_radius()* S.size_ratio, robot_colour, -1, LINE_AA); } pt1.x = (int)Box.min[0]* S.size_ratio; pt1.y = (int)Box.max[1]* S.size_ratio; pt2.x = (int)Box.min[0]* S.size_ratio; pt2.y = (int)Box.min[1]* S.size_ratio; pt3.x = (int)Box.max[0]* S.size_ratio; pt3.y = (int)Box.min[1]* S.size_ratio; pt4.x = (int)Box.max[0]* S.size_ratio; pt4.y = (int)Box.max[1]* S.size_ratio; line( image, pt1, pt2, container_colour, 2, LINE_AA ); line( image, pt2, pt3, container_colour, 2, LINE_AA ); line( image, pt3, pt4, container_colour, 2, LINE_AA ); flip(image, image, 0); imshow(wndname, image); waitKey(RENDER_DELAY); return 0; } float dot_product(int length, float* a, float* b) { float product = 0.; for(int i = 0; i < length; i++) { product += (*a)*(*b); a++; b++; } return product; } /* * The next function will calculate relative velocity after collision using coeff of restitution float relative_velocity(float e, float vel_1, float vel_2) { return (modulus((vel_2-vel_1))*e); // Return a positive scalar. The direction will be figured out later } */ VolBot::VolBot() { mass = 1; radius = RADIUS; temp_velocity[0] = 0.; temp_velocity[1] = 0.; force[0] = 0.; force[1] = 0.; temp_force[0] = 0.; temp_force[1] = GRAVITATIONAL_ACC; } Container::Container() { min[0] = BOX_MIN_X; min[1] = BOX_MIN_Y; max[0] = BOX_MAX_X; max[1] = BOX_MAX_Y; mass = HUGE_VALF; velocity[0] = 0.; velocity[1] = 0.; } Simulator::Simulator(float act_height, float act_width, float pix_height, float pix_width) // act_height and act_width in meters { size_ratio = (float)pix_height/act_height; } float* VolBot::set_position(float* new_position) { float* current_pos = new_position; position[0] = *current_pos; //cout << "New position x is = " << position[0] << endl; current_pos++; position[1]= *current_pos; //cout << "New position y is = " << position[1] << endl; return position; } float* VolBot::set_velocity(float* new_velocity) { float* curr_velocity = new_velocity; velocity[0] = *curr_velocity; //cout << "New velocity x is = " << velocity[0] << endl; curr_velocity++; velocity[1] = *curr_velocity; //cout << "New velocity y is = " << velocity[1] << endl; return velocity; } float* VolBot::set_force(float* new_force) // This is planned to be just gravity for now. { // The velocity will be calculated using conservation // momentum laws. float* current_force = force; current_force[0] = new_force[0]; current_force[1] = new_force[1]; return current_force; } float* VolBot::give_position(void) { return position; } float* VolBot::give_velocity(void) { return velocity; } float VolBot::give_radius(void) { return radius; } // And now for the container functions float* Container::set_position(float* new_min, float* new_max) { min[0] = new_min[0]; min[1] = new_min[1]; max[0] = new_max[0]; max[1] = new_max[1]; return new_min; // Picked a random value to return. } float* Container::set_velocity(float* new_velocity) { velocity[0] = new_velocity[0]; velocity[1] = new_velocity[1]; return velocity; } float* Container::give_velocity(void) { return velocity; } float* Container::give_min(void) { return min; } float* Container::give_max(void) { return max; } bool Simulator::BotvsBot(VolBot* Focus, VolBot* Other, float* collision_direction) // Focus is the robot currently being considered, { // and Other is the other one float* Focus_pos = Focus->give_position(); // argument 3 is the vector in the direction of float* Other_pos = Other->give_position(); //velocity added to Focus float* Focus_velo = Focus->give_velocity(); float* Other_velo = Other->give_velocity(); float* point_1 = collision_direction; float* point_2 = ++collision_direction; float r = Focus->give_radius() + Other->give_radius(); float rel_velo; // Magnitude of the relative velocity after collision float distance = sqrt((double)(Focus->position[0]-Other->position[0]) * (Focus->position[0]-Other->position[0])) + ((Focus->position[1]-Other->position[1]) * (Focus->position[1]-Other->position[1])); collision_direction = point_1; // Restore collision_direction to its original position if (r >= distance) // There has been a collision { // The collision vector will be in the correct direction for Focus cout << "sum of radii = " << r << endl; cout << "distance = " << distance << endl; *point_1 = Other_pos[0] - Focus_pos[0]; *point_2 = Other_pos[1] - Focus_pos[1]; r = sqrt((double)((*point_1 * (*point_1)) + (*point_2) * (*point_2))); collision_direction[0] = *point_1/r; collision_direction[1] = *point_2/r; /* Collision detection holds the unit vector in the direction of the collision. * (in the direction from Focus to Other) * Now to resolve the velocities. */ //rel_velo = relative_velocity((float)COEFFICIENT_E, dot_product((int)DIM, Focus.give_velocity(), collision_direction), dot_product((int)DIM, Other.give_velocity(), collision_direction)); if(FORCE_DISTANCE) { float radius_difference = Focus->give_radius() + Other->give_radius(); Focus->position[0] -= ((radius_difference - distance)/2) * collision_direction[0]; Focus->position[1] -= ((radius_difference - distance)/2) * collision_direction[1]; Other->position[0] += ((radius_difference - distance)/2) * collision_direction[0]; Other->position[1] += ((radius_difference - distance)/2) * collision_direction[1]; } for(int i = 0; i < DIM; i++) { float v1, v2; //v = dot_product((int)DIM, Focus->velocity, collision_direction) - dot_product((int)DIM, Other->velocity, collision_direction); v1 = dot_product((int)DIM, Focus->velocity, collision_direction); v2 = dot_product((int)DIM, Other->velocity, collision_direction); Focus->temp_velocity[i] -= collision_direction[i] * (v1 - v2 * COEFFICIENT_E); Other->temp_velocity[i] += collision_direction[i] * (-v2 + v1 * COEFFICIENT_E); } /* * We now have the relative velocity after collision * The individual velocities after collision in the direction of the collision vector will be * calculated using conservation of linear momentum */ return true; // Return TRUE for a collision } return false; } char Simulator::BotvsWall(VolBot* Bot, Container Wall) // Focus is the robot currently being considered, { // and Other is the other one float* Bot_pos = Bot->give_position(); float* Wall_min = Wall.give_min(); float* Wall_max = Wall.give_max(); float collision_direction[2]; // Direction of collision away from the center of the robot float v; // Velocity after collision // Use r for the distance to the wall float r = Bot->position[0] - Wall_min[0]; // The distance to the wall if(r < (Bot->give_radius()) && Bot->position[1] <= Wall_max[1]) // The ball collided with the left side { collision_direction[0] = -1.0; collision_direction[1] = 0.; v = dot_product((int)DIM, Bot->velocity, collision_direction); Bot->temp_velocity[0] -= v * (1 + COEFFICIENT_E) * collision_direction[0]; Bot->force[1] = GRAVITATIONAL_ACC; // normal force //return 'l'; // Returns l for left wall when the ball touches the left wall } r = Wall_max[0] - Bot_pos[0]; if(r < (Bot->give_radius())&& Bot->position[1] <= Wall_max[1]) // The ball collided with the left side { collision_direction[0] = 1.0; collision_direction[1] = 0.; v = dot_product((int)DIM, Bot->velocity, collision_direction); Bot->temp_velocity[0] -= v * (1 + COEFFICIENT_E) * collision_direction[0]; Bot->force[1] = GRAVITATIONAL_ACC; //return 'r'; // Returns r for right wall when the ball touches the right wall } r = Bot_pos[1] - Wall_min[1]; // The y coordinate of the bottom line if(r < Bot->give_radius() && Bot->position[1] <= Wall_max[1]) { collision_direction[0] = 0.; collision_direction[1] = -1.0; v = dot_product((int)DIM, Bot->velocity, collision_direction); Bot->temp_velocity[1] -= v * (1 + COEFFICIENT_E) * collision_direction[1]; Bot->force[1] = 0.; // normal force return 'b'; // Returns b for bottom if the robot touches the bottom } // Return TRUE for a collision Bot->force[1] = GRAVITATIONAL_ACC; return 'n'; // Nothing for no collision } int Simulator::run_simulation(VolBot* Balls, Container Box, Simulator S ) { float temp_pos[DIM]; float temp_velo[DIM]; float pos[2]; float vel[2] = {0., 0.}; pos[0] = 4; pos[1] = 4; for(int row = 0; row < 3; row++) { static int i = 0; for(int column = 0; column < 3; column++) { pos[0] += 5*column; Balls[i].set_position(pos); pos[0] -= 5*column; Balls[i].set_velocity(vel); i++; } pos[1] += 6; if(row%2 == 0) pos[0] = 3; else pos[0] = 4; } //waitKey(0); //cout << "Current x position for 0 = " << *Balls[0].set_position(pos_1) << endl; //cout << "Current x position for 1 = " << *Balls[1].set_position(pos_2) << endl; int count = 0; while(1) { Mat image = Mat::zeros(PIX_HEIGHT, PIX_WIDTH, CV_8UC3); //count ++; //cout << "instant = " << count++ << endl; int i = 0; for(i = 0; i < NUMBER_OF_BALLS; i++) // Check for collisions and edit temporary velocity vector { for(int j = i+1; j < NUMBER_OF_BALLS; j++) { float collision_direction[2]; // The vector normal to the collision. if(S.BotvsBot(&Balls[i], &Balls[j], collision_direction)) { cout << "Collision between robots " << i << " and " << j << "!" << endl; cout << count << endl ; }// If there is a collision detected, edit temp velos // for both of them //else //cout << "Robots didn't collide this time" << endl; } /* * Now to check for collision between the Robot i and the container */ //cout << " Checking for collision of i with wall = " << i << endl; char a = S.BotvsWall(&Balls[i], Box); // Collision between robot and wall switch (a) { case 'r': cout << "The robot " << i << " collided with the right wall!" << endl; break; case 'l': cout << "The robot " << i << " collided with the left wall!" << endl; break; case 'b': cout << ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>The robot " << i << " collided with the floor!" << endl; break; case 'n': cout << "No collision with the wall container for robot " << i << endl; break; default: break; } /* * Next to change the position and velocity of each ball we're done with */ for(int m = 0; m < DIM; m++) { temp_velo[m] = (Balls[i].velocity[m] + Balls[i].temp_velocity[m]); if(m == 1) // the y direction temp_velo[m] += Balls[i].force[1] * (1.0/FPS); Balls[i].temp_velocity[m] = 0.; // reset temp_velocity of the object to 0 } Balls[i].set_velocity(temp_velo); // Ball velocity now set for next frame float* current_pos = Balls[i].give_position(); for(int m = 0; m < DIM; m++) { temp_pos[m] = Balls[i].position[m] + Balls[i].velocity[m] * (1.0/FPS); } Balls[i].set_position(temp_pos); //cout << "x coordinate of the ball " << i << " = " << Balls[i].position[0] << endl; //cout << "y coordinate of the ball " << i << " = " << Balls[i].position[1] << endl; if(i == DIM-1) cout << endl; } render(image, Balls, Box, S); } return 0; } /* int Simulator::render(Mat image, VolBot* Balls, Container Box, Simulator S) { int i = 0; Scalar robot_colour (0, 0, 220); Scalar container_colour (220, 0, 0); Point center, pt1, pt2, pt3, pt4; // The center of a particular ball and four corners of the container //* The first corner of the rectangle is considered to be the top left corner. The next point is on position forward in the //* counter clockwise direction for(i = 0; i < NUMBER_OF_BALLS; i++) { center.x = Balls[i].position[0] * S.size_ratio; center.y = Balls[i].position[1]* S.size_ratio; circle(image, center, (int)Balls[i].give_radius()* S.size_ratio, robot_colour, -1, LINE_AA); } pt1.x = (int)Box.min[0]* S.size_ratio; pt1.y = (int)Box.max[1]* S.size_ratio; pt2.x = (int)Box.min[0]* S.size_ratio; pt2.y = (int)Box.min[1]* S.size_ratio; pt3.x = (int)Box.max[0]* S.size_ratio; pt3.y = (int)Box.min[1]* S.size_ratio; pt4.x = (int)Box.max[0]* S.size_ratio; pt4.y = (int)Box.max[1]* S.size_ratio; line( image, pt1, pt2, container_colour, 2, LINE_AA ); line( image, pt2, pt3, container_colour, 2, LINE_AA ); line( image, pt3, pt4, container_colour, 2, LINE_AA ); //waitKey(0); return 0; } */
true
8427e553224412553464432214f76660aa37854d
C++
DeepF02/Apnikaksha-C-DSA-Playlist
/code66.cpp
UTF-8
408
3.078125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int decimalToOctal(int n){ int ans=0; int x=1; while(x<n){ x*=8; } //x/=2; while(x>0){ int lastdigit = n/x; n -= lastdigit*x; x/=8; ans = ans*10 + lastdigit; } return ans; } int32_t main(){ int n; cout<<"Enter any decimal no. : "; cin>>n; cout<<decimalToOctal(n)<<endl; }
true
96edb289986adc550fe7178449cd7e37a22198c0
C++
blizmax/PSRayTracing
/src/Common.h
UTF-8
964
2.890625
3
[ "Apache-2.0", "CC0-1.0" ]
permissive
#pragma once // A collection of things (most likely defines or datatypes) that should be common across the project #include <limits> // adding `noexcept` to your functions usually results in a perf. boost. It's here as a toggable flag // to show the effects of it happening (or not) #ifdef USE_NOEXCEPT #define NOEXCEPT noexcept #else #define NOEXCEPT #endif #ifdef USE_SINGLE_PRECISION_REAL // Use floats (singles) for the maths using rreal = float; #else // Use doubles for the maths using rreal = double; #endif constexpr auto Infinity = std::numeric_limits<rreal>::infinity(); constexpr auto Pi = static_cast<rreal>(3.1415926535897932385); constexpr rreal HalfPi = Pi / static_cast<rreal>(2); constexpr rreal TwoPi = static_cast<rreal>(2) * Pi; constexpr rreal ThreeHalvesPi = static_cast<rreal>(3.0 / 2.0) * Pi; constexpr rreal InvTwoPi = static_cast<rreal>(1) / TwoPi; constexpr rreal TwoOverPi = static_cast<rreal>(2) / Pi;
true
69de181779a89d2a1b8e33b7e42ccfc49b2c63d0
C++
graynet-dev/aHomeBus
/ahb_io_din.h
UTF-8
4,611
2.8125
3
[]
no_license
/** aHomeBus io module - digital inputs @copyright 2019 Ivan Raspopov Based on aSysBus - 2015-2017 Florian Knodt, www.adlerweb.info Based on iSysBus - 2010 Patrick Amrhein, www.isysbus.org This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef AHB_IO_DIN__H #define AHB_IO_DIN__H #include <Arduino.h> #include <inttypes.h> #include <ahb.h> #define AHB_IO_DIN_DIRECT 0 //pushed = on, released = off - e.g. switch, temporary action, etc #define AHB_IO_DIN_BTOGGLE 1 //toggle every time button is pushed - e.g. push-button as light swtich, etc #define AHB_IO_DIN_STOGGLE 2 //toggle every time button is pushed or released - e.g. multiple switches for switching lights /** * Direct input struct * Contains pin numbers and configuration for outputs */ typedef struct { /** * Affected pin */ byte pin = 0xFF; /** * Target address * Unicast: 0x0001 - 0x07FF * Milticast/Broadcast: 0x0001 - 0xFFFF * 0x0 -> everything */ unsigned int target = 0; /** * Is pin inverted? */ boolean invert = false; /** * Use Pull-Up? */ boolean pullup = false; /** * Input mode */ byte mode = AHB_IO_DIN_DIRECT; /** * Last received state */ byte last = LOW; } ahbIoDIn; /** * Digital input module * @see AHB_IO */ class AHB_IO_DIN : public AHB_IO { private: /** * Number of configured inputs */ byte _items; /** * Array of configured inputs */ ahbIoDIn *_config; public: /** * Initialize * @param read configuration objects using id X, 1-15 * @return bool true if successful */ AHB_IO_DIN(byte cfgId); /** * Read configuration block starting at provided address * @param read configuration object from address X * @return bool true if successful */ bool cfgRead(unsigned int address); /** * Write current configuration * @param ahbIoDIn configuration struct reference * @return bool true if successful */ bool cfgWrite(ahbIoDIn &cfg); /** * Reset current configuration and free memory * @return bool true if successful */ bool cfgReset(void); /** * Reserve memory for configuration * @param objects number of configuration objects * @return bool true if successful */ bool cfgReserve(byte objects); /** * Process incoming packet * @param pkg Packet struct * @return bool true if successful */ bool process(ahbPacket &pkg); /** * Main loop call, e.G. for polling stuff * @return bool true if successful */ bool loop(void); /** * Attach an input to a set of metadata * * If the supplied pins state changes an IO-message will be send * * @param target target address between 0x0001 and 0xFFFF * @param pin Pin number to monitor * @param mode AHB_IN_DIRECT = Direct output, _TOGGLE = Toggle output when HIGH * @param invert input * @param pullup use internal pull-up resistor * @return true if successfully added */ bool attach(unsigned int target, byte pin, byte mode, bool invert, bool pullup); }; #endif /* AHB_IO_DIN__H */
true
28e1fba43f84a801565f1d2523854aab724770b0
C++
fathonyfath/quez-cpp
/quez/bullet.h
UTF-8
891
2.875
3
[ "MIT" ]
permissive
#pragma once #include "game_object.h" class Bullet : public GameObject { public: Bullet(SpriteRenderer* renderer, Texture2D* sprite, glm::vec3 size, float speed) : GameObject(renderer, sprite, size), speed(speed) { collider.p = colliderPos; collider.r = 9.0f; }; void update(GameEngine* engine) { float currentBulletXSpeed = std::sin(glm::radians(rotation)) * engine->getDeltaReadOnly() * speed; float currentBulletYSpeed = std::cos(glm::radians(rotation)) * engine->getDeltaReadOnly() * speed; glm::vec2 newPos = glm::vec2(position.x - currentBulletXSpeed, position.y + currentBulletYSpeed); position = glm::vec3(newPos.x, newPos.y, 0.0f); collider.p.x = position.x; collider.p.y = position.y; } float directionX; float directionY; float speed; c2Circle collider; c2v colliderPos; };
true
97d76c2ad177664d76b7acc521abf15906272e1e
C++
feelfreelinux/td
/td/telegram/files/ResourceState.h
UTF-8
2,488
2.609375
3
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference", "JSON" ]
permissive
// // Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2018 // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #pragma once #include "td/utils/common.h" #include "td/utils/format.h" #include "td/utils/logging.h" #include "td/utils/StringBuilder.h" namespace td { class ResourceState { public: void start_use(int64 x) { using_ += x; CHECK(used_ + using_ <= limit_); } void stop_use(int64 x) { CHECK(x <= using_); using_ -= x; used_ += x; } void update_limit(int64 extra) { limit_ += extra; } bool update_estimated_limit(int64 extra) { auto new_estimated_limit = used_ + extra; if (new_estimated_limit == estimated_limit_) { return false; } estimated_limit_ = new_estimated_limit; return true; } void set_unit_size(size_t new_unit_size) { unit_size_ = new_unit_size; } int64 active_limit() const { return limit_ - used_; } int64 get_using() const { return using_; } int64 unused() const { return limit_ - using_ - used_; } int64 estimated_extra() const { auto new_unused = max(limit_, estimated_limit_) - using_ - used_; new_unused = static_cast<int64>((new_unused + unit_size() - 1) / unit_size() * unit_size()); return new_unused + using_ + used_ - limit_; } size_t unit_size() const { return unit_size_; } ResourceState &operator+=(const ResourceState &other) { using_ += other.active_limit(); used_ += other.used_; return *this; } ResourceState &operator-=(const ResourceState &other) { using_ -= other.active_limit(); used_ -= other.used_; return *this; } void update_master(const ResourceState &other) { estimated_limit_ = other.estimated_limit_; used_ = other.used_; using_ = other.using_; unit_size_ = other.unit_size_; } void update_slave(const ResourceState &other) { limit_ = other.limit_; } friend StringBuilder &operator<<(StringBuilder &sb, const ResourceState &state) { return sb << tag("estimated_limit", state.estimated_limit_) << tag("used", state.used_) << tag("using", state.using_) << tag("limit", state.limit_); } private: int64 estimated_limit_ = 0; // me int64 limit_ = 0; // master int64 used_ = 0; // me int64 using_ = 0; // me size_t unit_size_ = 1; // me }; } // namespace td
true
65164fc41fced925ace3c68ac5c8708eb9031f1d
C++
Budziaszek/Macau-multiplayer-card-game
/src/graphics/CardsImages.cpp
UTF-8
3,439
2.796875
3
[]
no_license
// // Created by Magdalena on 18.09.2020. // #include "CardsImages.h" bool CardsImages::load(const std::string &tileset, sf::Vector2u tileSize) { if (!texture.loadFromFile(tileset)) return false; vertex = new sf::VertexArray[52]; size = tileSize; for (unsigned int tileNumber = 0; tileNumber < 52; tileNumber++) { vertex[tileNumber].setPrimitiveType(sf::Quads); vertex[tileNumber].resize(4); sf::Vertex *quad = &(vertex[tileNumber][0]); unsigned int n = tileNumber % (texture.getSize().x / tileSize.x); unsigned int m = tileNumber / (texture.getSize().x / tileSize.x); quad[0].texCoords = sf::Vector2f(n * tileSize.x, m * tileSize.y); quad[1].texCoords = sf::Vector2f((n + 1) * tileSize.x, m * tileSize.y); quad[2].texCoords = sf::Vector2f((n + 1) * tileSize.x, (m + 1) * tileSize.y); quad[3].texCoords = sf::Vector2f(n * tileSize.x, (m + 1) * tileSize.y); quad[0].position = sf::Vector2f(0, 0); quad[1].position = sf::Vector2f(tileSize.x, 0); quad[2].position = sf::Vector2f(tileSize.x, tileSize.y); quad[3].position = sf::Vector2f(0, tileSize.y); } cardBack = sf::RectangleShape(sf::Vector2f(71, 96)); cardBack.setFillColor(sf::Color(153, 0, 0, 255)); cardBack.setOutlineThickness(-1); cardBack.setOutlineColor(sf::Color::Black); return true; } void CardsImages::setNumber(unsigned int cardNumber) { number = cardNumber; } void CardsImages::setPosition(sf::Vector2i point) { sf::Vertex *quad = &(vertex[number][0]); quad[0].position = sf::Vector2f(point.x, point.y); quad[1].position = sf::Vector2f(point.x + size.x, point.y); quad[2].position = sf::Vector2f(point.x + size.x, point.y + size.y); quad[3].position = sf::Vector2f(point.x, point.y + size.y); } void CardsImages::draw(sf::RenderTarget &target, sf::RenderStates states) const { states.transform *= getTransform(); states.texture = &texture; target.draw(vertex[number], states); } sf::Vector2u CardsImages::getSize() { return size; } sf::RectangleShape *CardsImages::getCardBack() { return &cardBack; } void CardsImages::initializePositions(int windowWidth, int windowHeight) { float m = 170; xPosition = new float[4]{ (float) windowWidth / 2.0f - (float) getSize().x / 2, (float) windowWidth / 2.0f - m, (float) windowWidth / 2.0f - (float) getSize().x / 2, (float) windowWidth / 2.0f + m + (float) getSize().x }; yPosition = new float[4]{ (float) windowHeight / 2.0f + m, (float) windowHeight / 2.0f - (float) getSize().x / 2, (float) windowHeight / 2.0f - m - (float) getSize().y, (float) windowHeight / 2.0f - (float) getSize().x / 2 }; rotation = new float[4]{0, 90, 0, 90}; xStep = new float[4]{1, 0, 1, 0}; yStep = new float[4]{0, 1, 0, 1}; } float CardsImages::getYPosition(int player) { return yPosition[player]; } float CardsImages::getRotation(int player) { return rotation[player]; } float CardsImages::getXPosition(int player) { return xPosition[player]; } void CardsImages::setCard(Card card) { setNumber((card.getColor() - 1) * 13 + card.getFigure() - 1); } float CardsImages::getXStep(int player) { return xStep[player]; } float CardsImages::getYStep(int player) { return yStep[player]; }
true
0e7a64aec3c281ea90e83371c14c26a8a31c6db4
C++
ria317/cpp_workspace
/210615_study/inorder_tree.cpp
UTF-8
2,913
3.59375
4
[]
no_license
#include <iostream> #include <stack> #include <queue> using namespace std; typedef struct Node { int value; Node *left; Node *right; Node(int val) { value = val; left = nullptr; right = nullptr; } } Node; char canvas[100+10] = {0}; void print_tree(Node* root) { //// 트리의 level 갯수 // 1. tree 너비를 찾는다. Node* tmp = root; queue<pair<Node,int>> q; vector<int> value_arr; vector<int> depth_arr; q.push(make_pair(*tmp, 0)); while(!q.empty()) { Node idx = q.front().first; int depth = q.front().second; if( idx.left != nullptr ) { q.push(make_pair(*idx.left, depth+1)); } if( idx.right != nullptr) { q.push(make_pair(*idx.right, depth+1)); } value_arr.push_back(idx.value); depth_arr.push_back(depth); q.pop(); } for(int i=0; i<value_arr.size(); i++) { cout << "depth : " << depth_arr[i] << ", value : " << value_arr[i] << endl; } cout << endl; } void print2DUtil(Node *root, int space) { // Base case if (root == NULL) return; // Increase distance between levels space += 10; // Process right child first print2DUtil(root->right, space); // Print current node after space // count cout<<endl; for (int i = 10; i < space; i++) cout<<" "; cout<<root->value<<"\n"; // Process left child print2DUtil(root->left, space); } Node *insert(Node *root, int value) { Node* idx = root; if( idx == nullptr) { idx = new Node(value); return idx; } else { while(idx != nullptr ) { if( idx->value < value ) { if( idx->right == nullptr) { idx->right = new Node(value); break; }else { idx = idx->right; } } else if( idx->value > value ) { if( idx->left == nullptr) { idx->left = new Node(value); break; } else { idx = idx->left; } } else { return idx; } } } return root; } void travel_tree_inorder(Node *node) { stack<Node> sp; Node *p = nullptr; p = node; while(!sp.empty() || p != nullptr) { if( p == nullptr) { Node tmp = sp.top(); cout << tmp.value << endl; p = tmp.right; sp.pop(); } else { sp.push(*p); p = p->left; } } } int main() { int pre_order[7] = {4,2,1,3,6,5,7}; Node *root = nullptr; for(int i=0; i<7; i++) { root = insert(root, pre_order[i]); } travel_tree_inorder(root); //print_tree(root); print2DUtil(root, 0); }
true
d239c8cc64d999564195c78491769cd37048c6f5
C++
SvyatVasik/OOP_LAB_02
/Lab_02/Lab_02.task_02/Source.cpp
WINDOWS-1251
2,150
3.828125
4
[]
no_license
#include<iostream> using namespace std; class Time { private: int *hour; int *minute; int *second; public: Time(); Time(int h, int m, int s); Time(const Time &one); ~Time(); void SetHour(int svhour); void SetMinute(int svminute); void SetSecond(int svsecond); int GetHour(); int GetMinute(); int GetSecond(); }; Time::Time() { this->hour = new int(0); this->minute = new int(0); this->second = new int(0); } Time::Time(int h, int m, int s) { this->hour = new int(h); this->minute = new int(m); this->second = new int(s); } Time::Time(const Time &sv) { hour = new int(*sv.hour); minute = new int(*sv.minute); second = new int(*sv.second); } Time::~Time() { delete hour; delete minute; delete second; } void Time::SetHour(int svhour) { if (svhour < 0 || svhour > 23) { throw " "; } *hour = svhour; } void Time::SetMinute(int svminute) { if (svminute < 0 || svminute > 59) { throw " "; } *minute = svminute; } void Time::SetSecond(int svsecond) { if (svsecond < 0 || svsecond > 59) { throw " "; } *second = svsecond; } int Time::GetHour() { return *hour; } int Time::GetMinute() { return *minute; } int Time::GetSecond() { return *second; } int main(void) { Time *sv = new Time; int hour = 0, minute = 0, second = 0; cout << "Please,Enter the time:" << endl; cout << "Hour: "; cin >> hour; sv->SetHour(hour); cout << "Minute: "; cin >> minute; sv->SetMinute(minute); cout << "Second: "; cin >> second; sv->SetSecond(second); cout << endl << "Time:" << endl; cout << "*******************************" << endl; cout<<"* " << sv->GetHour() << " hours " << sv->GetMinute() << " minutes " << sv->GetSecond() << " seconds" << endl; cout<<"* " << sv->GetHour() << ":" << sv->GetMinute() << ":" << sv->GetSecond() << endl; cout << "*******************************" << endl; system("pause"); return 0; }
true
e018c709ec81517165723b038bdb1a3a5704cec3
C++
yenjorda/BruinNav
/BruinNav/MyMap.h
UTF-8
3,888
3.578125
4
[]
no_license
// MyMap.h // Skeleton for the MyMap class template. You must implement the first six // member functions. #ifndef MYMAP_H #define MYMAP_H #include <string> #include <queue> #include "support.h" template<typename KeyType, typename ValueType> class MyMap { public: MyMap(); ~MyMap(); void clear(); int size() const; void associate(const KeyType& key, const ValueType& value); // for a map that can't be modified, return a pointer to const ValueType const ValueType* find(const KeyType& key) const; // for a modifiable map, return a pointer to modifiable ValueType ValueType* find(const KeyType& key) { return const_cast<ValueType*>(const_cast<const MyMap*>(this)->find(key)); } // C++11 syntax for preventing copying and assignment MyMap(const MyMap&) = delete; MyMap& operator=(const MyMap&) = delete; private: struct Node { KeyType key; ValueType value; Node* left; Node* right; }; Node* m_root; int m_size; }; template<typename KeyType, typename ValueType> MyMap<typename KeyType, typename ValueType>::MyMap() { m_root = nullptr; m_size = 0; } template<typename KeyType, typename ValueType> MyMap<typename KeyType, typename ValueType>::~MyMap() { clear(); } template<typename KeyType, typename ValueType> void MyMap<typename KeyType, typename ValueType>::clear() { if (m_root == nullptr) { return; } queue<Node*> q; q.push(m_root); while (!q.empty()) { Node* traverse = q.front(); q.pop(); if (traverse->left != nullptr) { q.push(traverse->left); } if (traverse->right != nullptr) { q.push(traverse->right); } delete traverse; } m_root = nullptr; } template<typename KeyType, typename ValueType> int MyMap<typename KeyType, typename ValueType>::size() const { return m_size; } template<typename KeyType, typename ValueType> void MyMap<typename KeyType, typename ValueType>::associate(const KeyType& key, const ValueType& value) { ValueType* finder = find(key); //create a value type that is equal to the returned value for find if (finder== nullptr) { Node* traverse = m_root; for (;;) { if (traverse == nullptr) break; if (traverse->key > key) { if (traverse->left != nullptr) { traverse = traverse->left; } //if key is less than node's key, go left else break; } if (traverse->key < key) { if (traverse->right != nullptr) { traverse = traverse->right; } //if key is greater then node's key, go right else break; } } //add in all the info Node* add = new Node; add->left = nullptr; add->right = nullptr; add->value = value; add->key = key; m_size++; if (traverse == nullptr) { m_root = add; } //if is is empty then set head to first node else { if (traverse->key > key) { traverse->left = add; } else traverse->right = add; } } else { *finder= value; //if it's not nullptr, then that means there already exists a key, so change key's value to parameter's value } } template<typename KeyType, typename ValueType> const ValueType* MyMap<typename KeyType, typename ValueType>::find(const KeyType& key) const { if (m_root == nullptr) return nullptr; Node* traverse = m_root; for (;;) { if (traverse->key == key) { break; } //if keys match, then break else if (traverse->key > key) { if (traverse->left != nullptr) { traverse = traverse->left; } //if not nullptr, then set traverse to left to continue traversing else { break; } //if nullptr then break } else if (traverse->key < key) { if (traverse->right != nullptr) { traverse = traverse->right; } //if not nullptr, then set traverse to right to continue traversing else { break; } //if nullptr, then breal } } if (traverse->key == key) { ValueType* result = &traverse->value; return result; } //if the key is found, return the value else return nullptr; } #endif
true
a936568dd7e165439cac0d64e4380fcf393cc67c
C++
HoangNguyen174/ModelExporterLoader
/SoulStoneEngine/SimpleMaterial.cpp
UTF-8
1,457
2.59375
3
[]
no_license
#include "SimpleMaterial.hpp" #include "./Render/GLRender.hpp" SimpleMaterial::SimpleMaterial(const std::string& name, OpenGLShaderProgram* shaderProgram) { m_materialName = name; m_shaderProgram = shaderProgram; } void SimpleMaterial::SetUniformValues() { glUniform1i( m_shaderProgram->m_diffuseTextureUniformLoc, 0 ); glUniform1i( m_shaderProgram->m_specularTextureUniformLoc, 1 ); glUniform1i( m_shaderProgram->m_normalTextureUniformLoc, 2 ); glUniform3f( m_shaderProgram->m_lightWorldPosLoc, m_lightWorldPosition.x, m_lightWorldPosition.y, m_lightWorldPosition.z); glUniform3f( m_shaderProgram->m_cameraWorldPositionUniformLoc, m_cameraWorldPosition.x,m_cameraWorldPosition.y,m_cameraWorldPosition.z); glUniformMatrix4fv( m_shaderProgram->m_worldToScreenMatrixLoc, 1, GL_FALSE, m_worldToScreenMatrix ); } void SimpleMaterial::BindTexture() { if( m_diffuseTexture != nullptr) { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_diffuseTexture->m_openglTextureID); } if( m_normalTexture != nullptr ) { glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, m_normalTexture->m_openglTextureID ); } if( m_specularTexture != nullptr ) { glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, m_specularTexture->m_openglTextureID); } } void SimpleMaterial::ActivateMaterial() { m_shaderProgram->UseShaderProgram(); } void SimpleMaterial::DisableMaterial() { m_shaderProgram->DisableShaderProgram(); }
true
c2523147cb9b3d371ce3bbecabd036894843fe5d
C++
yana87gt/procon
/atcoder/diverta2019/c.cpp
UTF-8
779
2.609375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; #define rep(i,n) for(int i=0;i<int(n);++i) int main(void){ int n; cin >> n; int cnt = 0, x = 0, y = 0, z = 0; rep(i,n){ string s; cin >> s; int m = s.size(); rep(j,m-1){ if (s[j] == 'A' && s[j+1] == 'B'){ cnt++; } } if (s[0] == 'B' && s.back() == 'A') { y++; } else if (s.back() == 'A') { x++; } else if (s[0] == 'B') { z++; } } if (y >= 1) { cnt += y-1; if (x) { x--; cnt ++; } if (z) { z--; cnt ++; } } cnt += min(x,z); cout << cnt << endl; return 0; }
true
7857937ae9a7a376df6995e52cc72269ee575ab3
C++
haoping07/Leetcode-notes
/C++/83-Remove_Duplicates_from_Sorted_List.cpp
UTF-8
1,594
4.1875
4
[]
no_license
/* 83. Remove Duplicates from Sorted List (Easy) Notes: 1. fast-slow pointer - O(n) Use Two pointers to scan the list, if the two pointers' value are the same, move fast pointer backward, else, slow pointer's next points to fast pointer node, slow pointer points to fast pointer's node. 2. One poiner - O(n) In the previous method, we skip the duplicate nodes, this causes memory leak. The better solution should be using a pointer to scan the list, if the next node value is same as the current one, delete the duplicate and point the current one's next to the next next one. */ // One pointer class Solution { public: ListNode* deleteDuplicates(ListNode* head) { ListNode* node = head; while (node && node->next) { if (node->val == node->next->val) { ListNode* temp = node->next; node->next = node->next->next; delete temp; } else node = node->next; } return head; } }; /* // Fast-slow pointer (Not recommended) class Solution { public: ListNode* deleteDuplicates(ListNode* head) { if (!head) return head; ListNode* slow = head, * fast = head; while (fast) { if (slow->val != fast->val) { slow->next = fast; slow = fast; fast = fast->next; } else fast = fast->next; } slow->next = fast; return head; } }; */
true
04191a5dc676bdcaf362485272abce4a5c74e176
C++
theonenottaken/E-commerce-with-Cpp
/Server/UDP.cpp
UTF-8
2,078
3.109375
3
[]
no_license
/******************************************************************************************* * Student Name: Caleb Shere Benjmin Wexler * Exercise Name: Targil 5 * File Description: UDP.cpp *******************************************************************************************/ #include "UDP.hpp" #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <iostream> #include <stdio.h> #include <string.h> #include <cstring> /******************************************************************************* * Constructor. ******************************************************************************/ UDP::UDP() { // TODO Auto-generated constructor stub } /******************************************************************************* * Destructor. ******************************************************************************/ UDP::~UDP() { // TODO Auto-generated destructor stub } /******************************************************************************* * This function sends the given string to the client using the function * sendto(). ******************************************************************************/ void UDP :: sendData(const std::string& data) { char* toSend = new char[data.length() + 1]; std::strcpy(toSend, data.c_str()); int length = strlen(toSend); int sent_bytes = sendto(sock, toSend, length, 0, (struct sockaddr *) &from, sizeof(from)); if (sent_bytes < 0) { perror("error writing to socket"); } delete toSend; } /******************************************************************************* * This function receives a string from the client. It returns the string it * receives. ******************************************************************************/ std::string UDP :: receiveData() { unsigned int from_len = sizeof(struct sockaddr_in); char buffer[4096]; memset(&buffer, 0, sizeof(buffer)); int bytes = recvfrom(sock, buffer, sizeof(buffer), 0, (struct sockaddr *) &from, &from_len); if (bytes < 0) { perror("error reading from socket"); } return buffer; }
true
0735abb4a988fdd736d5c7eca34851e2fe4c4c83
C++
Robotik-MOLQ/Robocup-Program
/robocupGreenlight_21_6/fahren.cpp
UTF-8
1,620
2.5625
3
[]
no_license
#include <Arduino.h> #include "fahren.h" #include "meinePins.h" #include <SPI.h> byte PEData; void schreibePEData(byte data) { digitalWrite(LICHT_CS, LOW); SPI.transfer(data); digitalWrite(LICHT_CS, HIGH); } byte Taster=0; int leseTaster() { digitalWrite(LICHT_CS, LOW); delayMicroseconds(10); digitalWrite(LICHT_CS, HIGH); delayMicroseconds(10); Taster = SPI.transfer(0); return Taster; } void setLED(int led) { PEData &= 0xF0; PEData |= (led & 0x0F); schreibePEData(PEData); } void OnFwd(byte mot, int v) { // prüfe auf erlaubten Wertebereich if (v < -255) v = -255; else if (v > 255) v = 255; byte richtung = 0; if (v >= 0) { // vorwärts fahren if (mot & OUT_A) { analogWrite(PWMA, v); PEData = PEData & ~32; PEData = PEData | 16; schreibePEData(PEData); } if (mot & OUT_B) { analogWrite(PWMB, v); PEData = PEData & ~128; PEData = PEData | 64; schreibePEData(PEData); } } else { v = -v; if (mot & OUT_A) { analogWrite(PWMA, v); PEData = PEData | 32; PEData = PEData & ~16; schreibePEData(PEData); } if (mot & OUT_B) { analogWrite(PWMB, v); PEData = PEData | 128; PEData = PEData & ~64; schreibePEData(PEData); } } } void OnRev(byte mot, int v) { OnFwd(mot, -v); } void Off(byte mot) { byte richtung = 0; if (mot & OUT_A) { analogWrite(PWMA, 0); PEData = PEData & ~48; schreibePEData(PEData); } if (mot & OUT_B) { analogWrite(PWMB, 0); PEData = PEData & ~192; schreibePEData(PEData); } }
true
6e7c545db27df6b93e04f7e11670a1a3ae48c02f
C++
zhanll/LearnOpenGL
/LearnOpenGL/src/Mesh.h
UTF-8
685
2.65625
3
[]
no_license
#pragma once #include <glm/glm.hpp> #include <string> #include <vector> #include <memory> #include "Texture.h" class Shader; struct Vertex { glm::vec3 Position; glm::vec3 Normal; glm::vec2 TexCoords; glm::vec3 Tangent; glm::vec3 Bitangent; }; class Mesh { public: // mesh data std::vector<Vertex> vertices; std::vector<unsigned int> indices; std::vector<std::shared_ptr<Texture>> textures; Mesh(std::vector<Vertex> vertices, std::vector<unsigned int> indices, std::vector<std::shared_ptr<Texture>> textures); void Draw(Shader& shader); void Draw(); unsigned int GetVAO() const; private: // render data unsigned int VAO, VBO, EBO; void setupMesh(); };
true
54c28a4d7fba37a1f5ca34356f83dcd1e4ade2b3
C++
divadsn/Codeforces
/358a.cpp
UTF-8
730
3.140625
3
[ "Apache-2.0" ]
permissive
#include <iostream> using namespace std; int main() { int n; cin >> n; long *L = new long[n - 1]; long *R = new long[n - 1]; long lp, cp; cin >> lp; for (int i = 0; i < n - 1; i++) { cin >> cp; if (cp < lp) { L[i] = cp; R[i] = lp; } else { L[i] = lp; R[i] = cp; } lp = cp; } bool intersect = false; for (long k = 0; k < n - 1; k++) { if (intersect) break; for (long s = 0; s < n - 1; s++){ if(s == k) continue; if (intersect) break; if (L[k] < L[s] && L[s] < R[k] && R[k] < R[s]) { intersect = true; break; } } } if (intersect) cout << "yes" << endl; else cout << "no" << endl; }
true
5dc5109a808231e81026d4e24a5284d9867db98b
C++
ricardojamaia/FarmerFour
/lib/Controller/src/Controller.h
UTF-8
2,373
2.65625
3
[ "MIT" ]
permissive
// // Created by Ricardo Maia on 09/06/2020. // #ifndef FARMFOUR_CONTROLLER_H #define FARMFOUR_CONTROLLER_H #define CTRL_MAX_NUM_VALVES 3 #define CTRL_VALVE_OUT_PINS {24, 26, 28} #define CTRL_PUMP_OUT_PIN 22 #define FF_CTRL_EEPROM_ADDR_CRC 0x00 #define FF_CTRL__EEPROM_ADDR_CONFIG 0x10 #include <TimeLib.h> #include <TimeAlarms.h> // TODO: mValve on and isValveOn does not seem to be used other than for testing. Read pin value to check if the valve is on. class Controller { public: static Controller &getInstance() { static Controller instance; return instance; } void setHour(int valveId, int hour) { mValveConfigArray[valveId].hour = hour; } void setMinute(int valveId, int minute){ mValveConfigArray[valveId].minute = minute; } void setRepeat(int valveId, int repeatEveryHours){ mValveConfigArray[valveId].repeatEveryHours = repeatEveryHours; } void setDuration(int valveId, int durationMinutes){ mValveConfigArray[valveId].durationMinutes = durationMinutes; } void enable(int valveId); void disable(int valveId); void turnOnValve(int valveId); void turnOffValve(int valveId); int getHour(int valveId){ return mValveConfigArray[valveId].hour; } int getMinute(int valveId){ return mValveConfigArray[valveId].minute; } int getRepeat(int valveId){ return mValveConfigArray[valveId].repeatEveryHours; } int getDuration(int valveId){ return mValveConfigArray[valveId].durationMinutes; } bool isActive(int valveId){ return mValveConfigArray[valveId].active; } bool isValveOn(int valveId){ return mValveOn[valveId]; } void setup(); void save(); void load(); static void _alarmHandler(){ Controller::getInstance().alarmHandler(); } private: typedef struct { bool active; int hour; int minute; int repeatEveryHours; int durationMinutes; } ValveConfigT; Controller(){}; Controller(Controller const &); // Don't Implement. void operator=(Controller const &); // Don't implement ValveConfigT mValveConfigArray[CTRL_MAX_NUM_VALVES]; AlarmId onAlarmId[CTRL_MAX_NUM_VALVES]; AlarmId offAlarmId[CTRL_MAX_NUM_VALVES]; int mValvePins[CTRL_MAX_NUM_VALVES] = CTRL_VALVE_OUT_PINS; bool mValveOn[CTRL_MAX_NUM_VALVES]; void alarmHandler(); }; #endif //FARMFOUR_CONTROLLER_H
true
9e94acce308d1ba8d071a50c29625edcc2c6a21c
C++
nowacoder/cpp-nowcoder
/HJ030_Proc_Comb_Str.cpp
UTF-8
1,465
3.265625
3
[]
no_license
#include <string> #include <iostream> #include <algorithm> using namespace std; char convert(char c) { if ((c>=48 and c<=57) or (c>=65 and c<=70) or (c>=97 and c<=102)) { if (c=='0' or c=='6' or c=='9') return c; else if (c=='f' or c=='F') return 'F'; else if (c=='1') return '8'; else if (c=='2') return '4'; else if (c=='3') return 'C'; else if (c=='4') return '2'; else if (c=='5') return 'A'; else if (c=='7') return 'E'; else if (c=='8') return '1'; else if (c=='A' or c=='a') return '5'; else if (c=='B' or c=='b') return 'D'; else if (c=='C' or c=='c') return '3'; else if (c=='D' or c=='d') return 'B'; else if (c=='E' or c=='e') return '7'; } else return c; } int main() { string str1, str2; while (cin >> str1 >> str2) { string str = str1 + str2; if (str.length()>=3) { str1 = ""; for (int i=0; i<str.length(); i+=2) str1 += str[i]; sort(str1.begin(), str1.end()); for (int i=0; i<str.length(); i+=2) str[i] = str1[i/2]; str2 = ""; for (int i=1; i<str.length(); i+=2) str2 += str[i]; sort(str2.begin(), str2.end()); for (int i=1; i<str.length(); i+=2) str[i] = str2[(i-1)/2]; for (int i=0; i<str.length(); i++) str[i] = convert(str[i]); } cout << str << endl; } return 0; }
true