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
ede9c1020014db9063ce9c78eac3eea7b83654b6
C++
dongyangli1226/problem_solving
/algorithms/nextGreaterElement.cpp
UTF-8
1,636
4.625
5
[]
no_license
//given an array, output next greater element for each item in array // if no next greater element, print -1 for that element /* algorithm from geeksforgeeks 1) Push the first element to stack. 2) Pick rest of the elements one by one and follow following steps in loop. ….a) Mark the current element as next. ….b) If stack is not empty, then pop an element from stack and compare it with next. ….c) If next is greater than the popped element, then next is the next greater element for the popped element. ….d) Keep popping from the stack while the popped element is smaller than next. next becomes the next greater element for all such popped elements 3) After the loop in step 2 is over, pop all the elements from stack and print -1 as next element for them. O(n) */ #include <iostream> #include <vector> #include <stack> void printNextGreater(std::vector<int>& nums){ // not print the same order as nums std::stack<int> s; s.push(nums[0]); int next; for(int i=1; i<nums.size(); i++){ next = nums[i]; if(s.empty()){ s.push(next); continue; } while(!s.empty() && next > s.top()){ std::cout << s.top() << ',' << next << std::endl; s.pop(); } s.push(nums[i]); } while(!s.empty()){ std::cout << s.top() << ',' << -1 << std::endl; s.pop(); } } //if we want to print in the same order as nums: //create a map and store each next greater //in the end, iterate nums[i] ---> map[nums[i]] int main(){ std::vector<int> nums = {5,4,3,2,1}; printNextGreater(nums); return 0; }
true
8100722ad7608f4b3d360ced5f04136e5f7ffa7f
C++
aleksandrpetushkov/mapb
/mapb/elem.h
WINDOWS-1251
1,694
3.609375
4
[]
no_license
#include <cstddef> template <class T1, class T2>class elem // { public: elem(T1 const &key) // { _key = key; } void set(T1 const &key, T2 const &val) // { _key = key; _val = val; } void set(T1 const &key) // { _key = key; } T2& get_val()// { return _val; } T1 get_key() // { return _key; } elem *get_right() // { return right; } void set_val(T1 const & val) // { _val = val; } void set_right(T2 const &key) // { if(right!=nullptr) // { throw "Error: create right elem, elem exist\n"; } else // - { right = new elem<T1, T2>(key); } } elem *get_left() // { return left; } void set_left(T1 const &key)// { if(left!=nullptr)// - { throw "Error: create left elem, elem exist\n"; } else // { left = new elem<T1, T2>(key); } } protected: T1 _key; T2 _val; elem *right = nullptr; elem *left = nullptr; };
true
f23abf2ead100cb5f31fc4d2581ca028fe3a8cf2
C++
qanyue/code
/backup/Circle.cpp
UTF-8
556
3.6875
4
[]
no_license
#include <iostream> using namespace std; class circle { public : double radius {1}; circle () { radius=1.0; cout << radius << endl; } circle(double newRadius) { cout <<" I am coming"<< radius<<"##"<< newRadius<<endl; radius = newRadius; cout <<" I am coming"<< radius<<"##"<< newRadius<<endl; } double getArea() { return radius * radius * 3.14159; } }; int main(int argc, char const *argv[]) { circle circle2{5.0}; cout << "The area of the radius " << circle2.radius<< " is "<< circle2.getArea() <<endl; return 0; }
true
e7a5b01a4e645cef4b3fda2c76ad01838c5d810d
C++
tshabc/VSprojects
/operator/operator/main.cpp
GB18030
1,245
3.484375
3
[]
no_license
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <stdlib.h> #include <stdio.h> #include <string.h> using namespace std; class compe { public: compe(int a, int b); ~compe(); void outPut() { cout << "result = " << x << "+" << y << endl; } compe(const compe &c) { this->x = c.x; this->y = c.y; cout << "ÿ캯" << endl; } compe operator/(compe & ctemp) { compe temp(this->x / ctemp.x, this->y / ctemp.y); return temp; } private: friend compe add(compe &a, compe &b); friend compe operator+ (compe &a, compe &b); friend ostream & operator<<(ostream &out, compe &c); int x; int y; }; compe::compe(int a,int b) { this->x = a; this->y = b; } compe::~compe() { } compe add(compe &a,compe &b) { compe temp(a.x+b.x,a.y+b.y); return temp; } compe operator+ (compe &a, compe &b) { compe temp(a.x + b.x, a.y + b.y); return temp; } ostream & operator<<(ostream &out, compe &c) { out << "" << endl; return out; } int main01(int args,char*argus[]) { compe c1(10,20); compe c2 = compe(2,3); compe c3 = add(c1,c2); //c1 + c2; c3.outPut(); compe c4 = c1 + c2; c4.outPut(); compe c5 = c1 / c2; c5.outPut(); cout << c5 << c5<<endl; system("pause"); return 0; }
true
c8e1c74f1917c04dfded48bac091d514adcb9b2f
C++
naresh9949/Algorithms
/Rabin-Karp.cpp
UTF-8
834
3.078125
3
[]
no_license
#include<iostream> #include<cstring> #include<cmath> using namespace std; int Hash_Code(string s,int m,int n) { int valu=0; for(int i=0;i<=n;i++) { valu+=((int(s[i]))*pow(3,i)); } return valu; } bool Is_same(string Main,int s,int e,string Sub,int l) { int x,y; for(x=s,y=0;x<=e && y<l;x++,y++) { if(Main[x]!=Sub[y]) return 0; } return 1; } int Rabin_Karp(string Main,string Sub,int l1,int l2) { int MHvalu=Hash_Code(Main,0,l2-1); int SHvalu=Hash_Code(Sub,0,l2-1); for(int i=1;i<=l1-l2+1;i++) { if((MHvalu==SHvalu) && Is_same(Main,i-1,i+l2-2,Sub,l2)) return i-1; //MHvalu=(MHvalu-((int)Main[i-1]))/3; MHvalu=(MHvalu-Main[i-1])/3; //MHvalu+=(((int)Main[i+l2-1])*pow(3,l2-1)); MHvalu=MHvalu+((Main[i+l2-1])*pow(3,l2-1)); } return -1; } int main() { cout<<Rabin_Karp("aaafgsdd","sdd",8,3)<<endl; }
true
e0a5c3edfde04a5975afd826544a357bfa34b299
C++
zixuan-zhang/leetcode
/036_valid_soduku.cpp
UTF-8
6,152
3.421875
3
[]
no_license
/******************************************************************************* * @File : 036_valid_soduku.cpp * @Author: Zhang Zixuan * @Email : zixuan.zhang.victor@gmail.com * @Blog : www.noathinker.com * @Date : 2015年10月31日 星期六 19时03分47秒 ******************************************************************************/ /* * Question: * * Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. * The Sudoku board could be partially filled, where empty cells are filled * with the character '.'. * */ #include <iostream> #include <vector> using namespace std; class Solution { public: /* * Solution: * * 使用暴力的方法 * */ bool is_valid(int x, int y, int index, vector<vector<bool> >& row, vector<vector<bool> >& column, vector<vector<bool> >& sub) { return (!row[x][index] && !column[y][index] && !sub[(x/3)*3+y/3][index]); } // 这个方法判定的是这个partitially filled数独能否被solve,不符题意。不过更具 // 代表性。一开始把一题理解错了,还以为去求solvable的suduku bool is_valid_suduku(vector<vector<char> >& board, int x, int y, vector<vector<bool> >& row, vector<vector<bool> >& column, vector<vector<bool> >& sub) { //cout<<x<<" "<<y<<endl; //if (x < 0 || x >= 9 || y < 0 || y >= 9) if (x >= 9) return true; if (board[x][y] != '.') { int index = board[x][y] - '1'; //if (!row[x][index] && !column[y][index] && !sub[(x/3)*3+y/3][index]) if (is_valid(x, y, index, row, column, sub)) { row[x][index] = true; column[y][index] = true; sub[(x/3)*3+y/3][index] = true; if (8 != y) return is_valid_suduku(board, x, y+1, row, column, sub); else return is_valid_suduku(board, x+1, 0, row, column, sub); } return false; } else { //if this cell could be 1-9 bool result = false; for (int index = 0; index <= 8; ++index) { if (is_valid(x, y, index, row, column, sub)) { row[x][index] = true; column[y][index] = true; sub[(x/3)*3+y/3][index] = true; if (8 != y) result |= is_valid_suduku(board, x, y+1, row, column, sub); else result |= is_valid_suduku(board, x+1, 0, row, column, sub); //speed up! if result is true, return directly if (result) { board[x][y] = '1' + index; return true; } row[x][index] = false; column[y][index] = false; sub[(x/3)*3+y/3][index] = false; } } return result; } } bool is_valid_suduku2(vector<vector<char> >& board, int x, int y, vector<vector<bool> >& row, vector<vector<bool> >& column, vector<vector<bool> >& sub) { if (x >= 9) return true; if (board[x][y] != '.') { int index = board[x][y] - '1'; //if (!row[x][index] && !column[y][index] && !sub[(x/3)*3+y/3][index]) if (is_valid(x, y, index, row, column, sub)) { row[x][index] = true; column[y][index] = true; sub[(x/3)*3+y/3][index] = true; if (8 != y) return is_valid_suduku2(board, x, y+1, row, column, sub); else return is_valid_suduku2(board, x+1, 0, row, column, sub); } return false; } else { if (8 != y) return is_valid_suduku2(board, x, y+1, row, column, sub); else return is_valid_suduku2(board, x+1, 0, row, column, sub); } } bool isValidSuduku(vector<vector<char> >& board) { vector<vector<bool> >row(9); vector<vector<bool> >column(9); vector<vector<bool> >sub(9); for (int i = 0; i < 9; ++i) { for (int j = 0; j < 9; ++j) { row[i].push_back(false); column[i].push_back(false); sub[i].push_back(false); } } return is_valid_suduku2(board, 0, 0, row, column, sub); } }; int main() { char board_c[9][9] = { {'5', '3', '.', '.', '7', '.', '.', '.', '.'}, {'6', '.', '.', '1', '9', '5', '.', '.', '.'}, {'.', '9', '8', '.', '.', '.', '.', '6', '.'}, {'8', '.', '.', '.', '6', '.', '.', '.', '3'}, {'4', '.', '.', '8', '.', '3', '.', '.', '1'}, {'7', '.', '.', '.', '2', '.', '.', '.', '6'}, {'.', '6', '.', '.', '.', '.', '2', '8', '.'}, {'.', '.', '.', '4', '1', '9', '.', '.', '5'}, {'.', '.', '.', '.', '8', '.', '.', '7', '9'}, }; /* char board_c[9][9] = { {'4','6','3','7','2','8','9','5','1'}, {'2','5','9','4','6','1','7','3','8'}, {'7','8','1','3','5','9','6','4','2'}, {'5','3','2','1','9','7','4','8','6'}, {'9','1','4','6','8','2','5','7','3'}, {'6','7','8','5','4','3','1','2','9'}, {'8','2','6','9','7','5','3','1','4'}, {'1','4','7','2','3','6','8','9','5'}, {'3','9','5','8','1','4','2','6','7'}, }; */ vector<vector<char> >board; for (int i = 0; i < 9; ++i) { vector<char> row; for (int j = 0; j < 9; j++) row.push_back(board_c[i][j]); board.push_back(row); } Solution s; bool result = s.isValidSuduku(board); cout<<result<<endl; for (int i = 0; i < 9; ++i) { for (int j = 0; j < 9; ++j) cout<<board[i][j]<<" "; cout<<endl; } return 0; }
true
265706fb8919674f9c779524dda185adcc7e20ad
C++
Crizj/OJpractice
/leetcode/challenge/April LeetCoding Challenge 2021/Verifying an Alien Dictionary.cpp
UTF-8
913
3.515625
4
[]
no_license
#include<iostream> #include<string> #include<queue> #include<vector> using namespace std; class Solution { public: bool isAlienSorted(vector<string>& words, string order) { for(int i = 0; i+1 < words.size(); i++) { string a = words[i], b = words[i+1]; int j = 0; for(; j < a.length() && j < b.length(); j++) { if(order.find_first_of(a[j]) > order.find_first_of(b[j])) return false; else if(order.find_first_of(a[j]) < order.find_first_of(b[j])) break; } if(j == b.length() && a.length() > b.length()) return false; } return true; } }; int main() { vector<string> in = {"app","apple"}; string order = "abcdefghijklmnopqrstuvwxyz"; Solution s; if(s.isAlienSorted(in,order)) cout << "true" << endl; else cout << "false" << endl; return 0; }
true
9583edb15ae32e5bc3271368d26f30956d096ba0
C++
xumenger/xumenger.github.shit
/practice-曾经的练习程序/book/006《面向对象的程序设计--C++描述》/1/007.cpp
UTF-8
573
3.1875
3
[]
no_license
#include"TimeStamp.h" void dumpTS(const TimeStamp& ); int main(){ TimeStamp ts; time_t now = time(0); ts.set(); dumpTS(ts); ts.set(now+200000); dumpTS(ts); ts.set(now-200000); dumpTS(ts); ts.set(-999); dumpTS(ts); return 0; } void dumpTS(const TimeStamp& ts){ cout<<"\nTesting method:\n"; cout<<'\t'<<ts.get()<<'\n'; cout<<'\t'<<ts.getAsString()<<'\n'; cout<<'\t'<<ts.getYear()<<'\n'; cout<<'\t'<<ts.getMonth()<<'\n'; cout<<'\t'<<ts.getDay()<<'\n'; cout<<'\t'<<ts.getHour()<<'\n'; cout<<'\t'<<ts.getMinute()<<'\n'; cout<<'\t'<<ts.getSecond()<<'\n'; }
true
4c318815a728a3a5bc12b3c55aadd396404fff0b
C++
toiinnn/Programming-Language-I
/2th_Laboratory/src/company_manager/main.cpp
UTF-8
1,870
3.796875
4
[]
no_license
/** * @file main.cpp * @brief Main function for Company Manager. * Shows a menu to the user while he does not decide to quit. * @author Lucas Gomes Dantas (dantaslucas@ufrn.edu.br) * @since 02/09/2017 * @date 02/09/2017 */ #include "company_manager/manage_company.h" #include <iostream> /** * Main function. * Keeps a dialog with the user showing him a menu while he does not decide to quit. * The user must provide a valid number between 0 and 7, each corresponding to an option. */ int main() { std::vector<Company*> companies; int option = -1; while(option != 0) { std::cout << std::endl << "============================= MENU =============================" << std::endl; std::cout << "Welcome, manager! Here's the list of available funcionalities: " << std::endl; std::cout << "1 -> Create company" << std::endl; std::cout << "2 -> List companies" << std::endl; std::cout << "3 -> Add employee to company" << std::endl; std::cout << "4 -> List employees of a certain company" << std::endl; std::cout << "5 -> Give a raise in all employees of a certain company" << std::endl; std::cout << "6 -> List employees of a certain company by experience" << std::endl; std::cout << "7 -> Compute average number of employees per company" << std::endl; std::cout << "0 -> Leave menu" << std::endl; std::cout << std::endl << "What do you want to do?" << std::endl; std::cin >> option; while(option < 0 or option > 7) { std::cout << std::endl << "Invalid input! Read the menu and enter a valid option: " << std::endl; std::cin >> option; } manage_company(option, companies); } std::cout << std::endl << "================================================================" << std::endl; }
true
826acef1504c0d96e0a50ab721f67eb709e51b55
C++
scsampath/lab06_sampath_sachen
/CustomItem.cpp
UTF-8
1,455
3.46875
3
[]
no_license
//Created by Sachen Sampath, CS32, 5/14/2020 #include <iostream> #include <sstream> #include <iomanip> #include "CustomItem.h" using namespace std; CustomItem::CustomItem(string size) : IceCreamItem(size){ if(size == "small"){ price = 3.00; } else if(size == "medium"){ price = 5.00; } else if(size == "large"){ price = 6.50; } } CustomItem::~CustomItem(){ } void CustomItem::addTopping(std::string topping){ //check if topping exists for(size_t i = 0; i < toppings.size(); i++){ //if topping exists then increment and increase price if(topping == toppings.at(i).first){ toppings.at(i).second++; price+=.40; return; } } //topping doesnt exist so create new topping and increase price pair<string, int> newTopping(topping, 1); toppings.push_back(newTopping); price+=.40; } string CustomItem::composeItem(){ string composedItem = ""; composedItem += string("Custom Size: ") + size + "\n"; composedItem += string("Toppings:") + "\n"; for(size_t i = 0; i < toppings.size(); i++){ composedItem += string(toppings.at(i).first) + ": " + std::to_string(toppings.at(i).second) + " oz" + "\n"; } ostringstream priceStr; priceStr << fixed << setprecision(2) << price; composedItem += string("Price: $") + priceStr.str() + "\n"; return composedItem; } double CustomItem::getPrice(){ return this->price; }
true
b750920b60df5c20603f98a3a4bb01a1abfe7a18
C++
aydinsimsek/HackerRank-problem-solving
/Algorithms/Greedy/Maximum_Perimeter_Triangle.cpp
UTF-8
2,864
3.1875
3
[ "MIT" ]
permissive
#include <bits/stdc++.h> using namespace std; vector<string> split_string(string); bool nonDegenerate(int a, int b, int c) { if(a+b>c && a+c>b && b+c>a) { return true; } return false; } vector<int> maximumPerimeterTriangle(vector<int> sticks) { vector<int> result; vector<vector<int>> triangles; unsigned long int perimeter = 0; sort(sticks.begin(), sticks.end()); for(int i = 0; i < sticks.size()-2; i++) { vector<int> temp; temp.push_back(sticks[i]); temp.push_back(sticks[i+1]); temp.push_back(sticks[i+2]); triangles.push_back(temp); } for(int i = 0; i < triangles.size(); i++) { if(nonDegenerate(triangles[i][0], triangles[i][1], triangles[i][2]) == true) { unsigned long int curPerimeter = triangles[i][0]+triangles[i][1]+triangles[i][2]; if(perimeter < curPerimeter) { perimeter = curPerimeter; result.clear(); result.push_back(triangles[i][0]); result.push_back(triangles[i][1]); result.push_back(triangles[i][2]); } } } if(result.size() == 0) { result.push_back(-1); } return result; } int main() { ofstream fout(getenv("OUTPUT_PATH")); int n; cin >> n; cin.ignore(numeric_limits<streamsize>::max(), '\n'); string sticks_temp_temp; getline(cin, sticks_temp_temp); vector<string> sticks_temp = split_string(sticks_temp_temp); vector<int> sticks(n); for (int i = 0; i < n; i++) { int sticks_item = stoi(sticks_temp[i]); sticks[i] = sticks_item; } vector<int> result = maximumPerimeterTriangle(sticks); for (int i = 0; i < result.size(); i++) { fout << result[i]; if (i != result.size() - 1) { fout << " "; } } fout << "\n"; fout.close(); return 0; } vector<string> split_string(string input_string) { string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { return x == y and x == ' '; }); input_string.erase(new_end, input_string.end()); while (input_string[input_string.length() - 1] == ' ') { input_string.pop_back(); } vector<string> splits; char delimiter = ' '; size_t i = 0; size_t pos = input_string.find(delimiter); while (pos != string::npos) { splits.push_back(input_string.substr(i, pos - i)); i = pos + 1; pos = input_string.find(delimiter, i); } splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); return splits; }
true
c78e795ad073c165c48db000ae66bc50f21f65a2
C++
nilam23/DataStructures_Algorithms
/Maths/mod_Inverse_Naive.cpp
UTF-8
467
3.40625
3
[]
no_license
#include<iostream> using namespace std; int getGCD(int a, int b){ return (b ? getGCD(b, a%b) : a); } int getMMI(int a, int p){ //a = a % p; for(int x = 1; x < p; x++){ if((a * x) % p == 1) return x; } } int main(){ int a, p; cout << "Enter a: "; cin >> a; cout << "Enter p: "; cin >> p; int gcd = getGCD(a, p); if(gcd == 1) cout << "Result = " << getMMI(a, p) << endl; else cout << a << " and " << p << " are not co-primes." << endl; return 0; }
true
f4ee1dd36e7692e9afa5671118023a3e19815a4f
C++
cuicp/USACO
/Chapter3/商店购物(dfs只能过9个点版).cpp
GB18030
3,406
2.765625
3
[]
no_license
/* ID:cuichengpeng PROG:shopping LANG:C++ */ #include<iostream> #include<fstream> #include<vector> using namespace std; const int INF=10000000; const int M=5; int cost[M][M][M][M][M]; bool can(vector<vector<int> >&need,vector<vector<int> >&yh,int k); bool can(vector<vector<int> >&need,vector<vector<int> >&yh); void mul(vector<vector<int> >&need,vector<vector<int> >&yh,int k); void add(vector<vector<int> >&need,vector<vector<int> >&yh,int k); void change(vector<vector<int> >&need,vector<vector<int> >&yh);//ƷŽת int dfs(vector<vector<int> >need,vector<vector<int> >yh) { if(!can(need,yh))//ܹŻ { int sum=0; for(int i=0;i<need.size();++i) sum+=need[i][1]*need[i][2]; return sum; } int t[5]={0}; for(int i=0;i<need.size();++i)t[i]=need[i][1]; if(cost[t[0]][t[1]][t[2]][t[3]][t[4]]!=0) return cost[t[0]][t[1]][t[2]][t[3]][t[4]]; //öÿŻ int min=INF; for(int i=0;i<yh.size();++i) { if(can(need,yh,i))//õiַʽŻ { mul(need,yh,i);// int min_cost=yh[i][yh[i].size()-1]+dfs(need,yh); if(min_cost<min)min=min_cost; add(need,yh,i);//ָ } } cost[t[0]][t[1]][t[2]][t[3]][t[4]]=min; return min; } int main() { ifstream fin("shopping.txt"); ofstream fout("shopping.out"); vector<vector<int> >yh;//Żݷ vector<int>temp; vector<vector<int> >need; int i,j,s,b,n,c,k,p; fin>>s; for(i=0;i<s;++i) { fin>>n; for(j=0;j<2*n+1;++j) { fin>>c; temp.push_back(c); } yh.push_back(temp); temp.clear(); } fin>>b; for(i=0;i<b;++i) { for(j=0;j<3;++j) { fin>>c; temp.push_back(c); } need.push_back(temp); temp.clear(); } change(need,yh); /* for(int i=0;i<yh.size();++i) { for(int j=0;j<yh[i].size();++j)cout<<yh[i][j]<<' '; cout<<endl; } system("pause"); */ cout<<dfs(need,yh)<<endl; system("pause"); return 0; } bool can(vector<vector<int> >&need,vector<vector<int> >&yh,int k) { int i; for(i=0;i<yh[k].size()-1;i+=2) { if(yh[k][i+1]>need[yh[k][i]][1])break; } if(i<yh[k].size()-1)return false; return true; } bool can(vector<vector<int> >&need,vector<vector<int> >&yh) { for(int i=0;i<yh.size();++i) if(can(need,yh,i))return true; return false; } void mul(vector<vector<int> >&need,vector<vector<int> >&yh,int k) { for(int i=0;i<yh[k].size()-1;i+=2) need[yh[k][i]][1]-=yh[k][i+1]; } void add(vector<vector<int> >&need,vector<vector<int> >&yh,int k) { for(int i=0;i<yh[k].size()-1;i+=2) need[yh[k][i]][1]+=yh[k][i+1]; } void change(vector<vector<int> >&need,vector<vector<int> >&yh) { for(int i=0;i<need.size();++i) { int temp=need[i][0]; need[i][0]=i; for(int j=0;j<yh.size();++j) { for(int k=0;k<yh[j].size()-1;k+=2) { if(yh[j][k]==temp)yh[j][k]=i; } } } }
true
c1d061d64f8e9af812e7493fae5d158ce939359e
C++
Dx724/Instrument-Mini
/ESP32/InstrMini_Input/InstrMini_Input.ino
UTF-8
1,013
3.21875
3
[]
no_license
#define analogCount 2 #define digitalCount 4 #define totalCount (analogCount + digitalCount) int analogPins[analogCount] = {13, 12}; // Joystick X, Joystick Y int digitalPins[digitalCount] = {14, 33, 18, 19}; // Joystick Z, Switch and two Buttons // Note that the switch can only be in two states, so we can determine the state // by verifying the connection state from a single side. void setup() { Serial.begin(115200); // Set up pins for (int p : analogPins) { pinMode(p, INPUT); } for (int d : digitalPins) { pinMode(d, INPUT_PULLUP); } } // [joystickX, joystickY, joystickZ, switch, button1, button2] int data[totalCount] = {}; void loop() { for (int i = 0; i < analogCount; i++) { data[i] = analogRead(analogPins[i]); } for (int i = analogCount; i < totalCount; i++) { data[i] = digitalRead(digitalPins[i-analogCount]); } for (int i = 0; i < totalCount; i++) { Serial.print(data[i]); Serial.print(i == totalCount - 1 ? "\n" : " "); } delay(100); }
true
ed98d2d4fea47fba0ca0984bdf2228669519ebd0
C++
ComnHomeAce/Displaying-a-Square-of-Asterisks
/Displaying a Square of Asterisks/Displaying a Square of Asterisks.cpp
UTF-8
663
4.28125
4
[]
no_license
//This program prints a square of user-defined size #include <iostream> using namespace std; char squareOfAsterisks(int side) { //Loop for printing each line for (int i = 0; i < side; i++) { //Loop for printing the asterisks for (int j = 0; j < side; j++) { cout << "* "; //I added a space after the asterisk so it prints a true square shape } cout << "\n"; } return 0; } int main() { int side; cout << "This program prints a square of user-defined size\n\n"; cout << "Enter side length of square: "; cin >> side; cout << "\n"; cout << squareOfAsterisks(side); }
true
2f3bf3497650c7f915e1b7e6949674a882401584
C++
tarpeyd12/thread_pool
/pool/future.inl
UTF-8
836
2.984375
3
[]
no_license
#ifndef POOL_FUTURE_INL_INCLUDED #define POOL_FUTURE_INL_INCLUDED #include <utility> namespace tpl { template < typename T > future< T >::future( std::future< T >&& f ) : _future( std::move( f ) ), block_on_destruction( true ) { /* */ } template < typename T > future< T >::~future() { if( block_on_destruction && _future.valid() ) { _future.get(); } } template < typename T > auto future< T >::get() { return _future.get(); } template < typename T > void future< T >::release() { block_on_destruction = false; } template < typename T > bool future< T >::valid() const { return block_on_destruction && _future.valid(); } } #endif // POOL_FUTURE_INL_INCLUDED
true
214f142aeb61b3e11d0307bcb94e9a57a68d6531
C++
ulinka/tbcnn-attention
/github_cpp/14/98.cpp
UTF-8
5,318
2.765625
3
[]
no_license
#ifndef DPP_RADIX_SORT_HH_ #define DPP_RADIX_SORT_HH_ #include <algorithm> #include <limits> #include <stdint.h> namespace dpp { template <typename X, size_t bits> struct radix_sort_type { static unsigned int extract(const X x, size_t pos) { X::_requires_8bits_radix_width_for_custom_types(); return 0; } }; template <typename X> struct radix_sort_type<const X &, 8> { static unsigned int extract(const X x, size_t pos) { const uint8_t *d = (const uint8_t *)&x; return d[pos]; } }; #define _DPP_RADIX_SORT_INT(type) \ \ template <size_t bits> \ struct radix_sort_type<unsigned type, bits> \ { \ static const size_t _bsize = 1 << bits; \ static const size_t _passes = sizeof(type) * 8 / bits + (bits % 8 != 0); \ \ static unsigned int extract(unsigned type x, size_t pos) \ { \ return (x >> (bits * pos)) & ((1 << bits) - 1); \ } \ }; \ \ \ template <size_t bits> \ struct radix_sort_type<signed type, bits> \ { \ static const size_t _bsize = 1 << bits; \ static const size_t _passes = sizeof(type) * 8 / bits + (bits % 8 != 0); \ \ static unsigned int extract(signed type x, size_t pos) \ { \ static const signed type s = std::numeric_limits<signed type>::min(); \ return ((x - s) >> (bits * pos)) & ((1 << bits) - 1); \ } \ }; _DPP_RADIX_SORT_INT(char); _DPP_RADIX_SORT_INT(short); _DPP_RADIX_SORT_INT(int); _DPP_RADIX_SORT_INT(long); _DPP_RADIX_SORT_INT(long long); #define _DPP_RADIX_SORT_FLOAT(type) \ \ template <size_t bits> \ struct radix_sort_type<type, bits> \ { \ static const size_t _bsize = 1 << bits; \ static const size_t _passes = sizeof(type) * 8 / bits + (bits % 8 != 0); \ \ static unsigned int extract(type x, size_t pos) \ { \ switch (sizeof(type)) \ { \ case 4: { \ union { int32_t v; float f; }; \ f = x; \ return ((((v >> 31) | (1 << 31)) ^ v) >> (bits * pos)) & ((1 << bits) - 1); \ } \ case 8: { \ union { int64_t v; double f; }; \ f = x; \ return ((((v >> 63) | (1ULL << 63)) ^ v) >> (bits * pos)) & ((1 << bits) - 1); \ } \ default: \ std::abort(); \ } \ } \ } _DPP_RADIX_SORT_FLOAT(float); _DPP_RADIX_SORT_FLOAT(double); template <typename X, size_t bits> struct _radix_sort { static const size_t _bsize = 1 << bits; static const size_t _passes = sizeof(X) * 8 / bits + (bits % 8 != 0); static void sort(X *in, X *next_in, X *out, size_t len) { size_t hist[_passes][_bsize]; for (size_t j = 0; j < _passes; j++) for (size_t i = 0; i < _bsize; i++) hist[j][i] = 0; for (size_t i = 0; i < len; i++) for (size_t j = 0; j < _passes; j++) hist[j][radix_sort_type<X, bits>::extract(in[i], j)]++; for (size_t j = 0; j < _passes; j++) { uintptr_t offset[_bsize], o; o = offset[0] = 0; for (size_t i = 1; i < _bsize; i++) o = offset[i] = o + hist[j][i - 1]; for (size_t i = 0; i < len; i++) { size_t x = radix_sort_type<X, bits>::extract(in[i], j); out[offset[x]++] = in[i]; } in = next_in; std::swap(in, out); next_in = in; } } static void sort_in(X *in, size_t len) { X tmp[len]; sort(in, in, tmp, len); if (_passes % 2) for (size_t i = 0; i < len; i++) in[i] = tmp[i]; } static void sort_out(const X *in, X *out, size_t len) { if (_passes % 2) { X tmp[len]; for (size_t i = 0; i < len; i++) tmp[i] = in[i]; sort(tmp, tmp, out, len); } else if (_passes > 1) { X tmp[len]; sort((X*)in, out, tmp, len); } else { sort((X*)in, 0, out, len); } } }; template <typename iterator> void radix_sort(const iterator &begin, const iterator &end) { typedef typename iterator::value_type type; size_t len = end - begin; _radix_sort<type, 8>::sort_in(&*begin, len); } template <typename iterator, size_t bits> void radix_sort(const iterator &begin, const iterator &end) { typedef typename iterator::value_type type; size_t len = end - begin; _radix_sort<type, bits>::sort_in(&*begin, len); } template <typename X> void radix_sort(X *begin, X *end) { typedef X type; size_t len = end - begin; _radix_sort<type, 8>::sort_in(begin, len); } template <typename X, size_t bits> void radix_sort(X *begin, X *end) { typedef X type; size_t len = end - begin; _radix_sort<type, bits>::sort_in(begin, len); } template <typename X> void radix_sort(const X *begin, const X *end, X *out) { typedef X type; size_t len = end - begin; _radix_sort<type, 8>::sort_out(begin, out, len); } template <typename X, size_t bits> void radix_sort(const X *begin, const X *end, X *out) { typedef X type; size_t len = end - begin; _radix_sort<type, bits>::sort_out(begin, out, len); } } #endif
true
f6a32f9e04ddd69a0bea61073fa51abe19c3f1e1
C++
Eastonco/CS122
/PA4_Fitness/PA4/ExercisePlan.h
UTF-8
445
2.640625
3
[]
no_license
#include "Header.h" #ifndef EXERCISEPLAN #define EXERCISEPLAN class ExercisePlan { public: ExercisePlan(); ~ExercisePlan(); ExercisePlan(ExercisePlan &rhs); int getGoal(); string getName(); string getDate(); void setGoal(int newGoal); void setName(string newName); void setDate(string newDate); void editGoal(); void editName(); void editDate(); private: int mgoalSteps; string mname; string mdate; }; #endif // !EXERCISEPLAN
true
ba6965b2e92dbb0323bc72b78281291d0d941091
C++
spidersharma03/spider3d
/Engine/include/scene/sceneNodes/TextureProjectorNode.h
UTF-8
1,683
2.515625
3
[]
no_license
#ifndef _TEXTURE_PROJECTOR_NODE_H #define _TEXTURE_PROJECTOR_NODE_H #include "Node.h" #include "MeshNode.h" #include "TextureUnitState.h" #include "NodeAnimator.h" #include <map> namespace spider3d { namespace effects { class TextureProjector; } } using namespace spider3d::effects; namespace spider3d { namespace scene { class TextureProjectorNode: public Node { public: static const int PROJECTION_POLICY_CAMERA = 0; static const int PROJECTION_POLICY_PROJECTOR = 1; static const int PROJECTION_POLICY_PROJECTOR_3D = 2; TextureProjectorNode( Texture* texture, SceneManagerptr sceneManagerPtr, Nodeptr parent ); void addScope( MeshNode* meshNode ); void removeScope( MeshNode* meshNode ); void removeAllScopes(); void setProjectionPolicy(int); virtual void render(); virtual void OnRegister(); virtual void print(); TextureUnitState* getProjectorTextureUnitState(); private: class ProjectorUpdater: public NodeAnimator { public: ProjectorUpdater(TextureProjector* textureProjector); virtual void animate(sf32 time); void setProjectionPolicy(int); public: TextureProjector* textureProjector; TextureAttributes* projectorTextureAttributes; int projectionPolicy; }; Texture* texture; TextureUnitState* projectorTexUnitState; ProjectorUpdater* projectorUpdator; TextureProjector* textureProjector; map<MeshNode*, TextureUnitState*> m_oldTexUnitMap; Point3 projectorPosition; Point3 projectorTarget; Vector3 projectorUp; int projectionPolicy; }; } } #endif
true
2626ebe490cf59cb8940d14628e26415e4ea8743
C++
px1099/CS2040C-C-files
/CS2040C/Week 3/PS1_AB.cpp
UTF-8
670
2.84375
3
[]
no_license
#include <bits/stdc++.h> #define MAXSIZE 3000 using namespace std; void sortArray (unsigned long long a[], int i) { // O(N) unsigned long long temp = a[i]; while (a[i-1]>temp && i>0) { a[i] = a[i-1]; i--; } a[i] = temp; } unsigned long long median(unsigned long long a[], int n) { // O(1) if (n%2) return a[n/2]; else return (a[n/2-1]+a[n/2])/2; } int main() { // O(TC*N^2) unsigned long long a[MAXSIZE] = {0}; unsigned long long medsum; int TC, N, i, j, k; cin >> TC; for (k=0; k<TC; k++) { cin >> N; medsum = 0; for (i=0;i<N;i++) { cin >> a[i]; sortArray(a,i); medsum += median(a,i+1); } cout << medsum << endl; } return 0; }
true
ced93dc141dcf4eb1e41fcf8b036bb4178bfa9c3
C++
syruphanabi/multi-bit-adder-simulation
/Graph.cpp
UTF-8
7,759
2.890625
3
[]
no_license
#include "Graph.hpp" #include "Event.hpp" #include <iostream> using namespace std; Graph::Graph(int ID, queue<Event*> *ia, queue<Event*> *ib, queue<Event*> *ic, queue<Event*> *oc, queue<Event*> *os):graphID(ID) { //initialize and push all GNodes in to the nodes GraphMaker(); //init set(); inputA = ia; inputB = ib; inputC = ic; outputC = oc; outputS = os; } void Graph::Excute(int epi){ queue<GNode*> worklist; int val13 = -1, val14 = -1; long clock13 = -1, clock14 = -1; for (int a = 0; a < 3; a++){ for (auto node: nodes){ worklist.push(node); } } while(!worklist.empty()){ worklist.front()->simulate(*worklist.front(), epi, false); for(auto &itr : worklist.front()->getOutNeigh()){ worklist.push(itr); } if(worklist.front()->nodeID == 13 && worklist.front()->data.clock != clock13){ clock13 = worklist.front()->data.clock; if(val13 == worklist.front()->output){ SendOut(-1, 0, "NULL", 'S'); } else { val13 = worklist.front()->output; SendOut(worklist.front()->output, worklist.front()->data.clock, "REGULAR", 'S'); } } else if(worklist.front()->nodeID == 14 && worklist.front()->data.clock != clock14){ clock14 = worklist.front()->data.clock; if(val14 == worklist.front()->output){ SendOut(-1, 0, "NULL", 'C'); } else { val14 = worklist.front()->output; SendOut(worklist.front()->output, worklist.front()->data.clock, "REGULAR", 'C'); } } worklist.pop(); } for(int i = 0; i < readyOutS.size(); i++){ outputS->push(readyOutS.front()); readyOutS.pop(); } for(int i = 0; i < readyOutC.size(); i++){ outputC->push(readyOutC.front()); readyOutC.pop(); } // for (auto node: nodes){ // if(node->nodeID == 2){ // cout << "node " << node->nodeID << " is at time " << node->data.clock << " with value " << node->output << endl; // } // } } void Graph::SendOut(int out, long time, string type, char k){ Event* e = new Event(type,out); e->whichIn = 0; e->recvTime = time; if(k == 'C'){ readyOutC.push(e); } else if(k == 'S'){ readyOutS.push(e); } } void Graph::Receive() { while(!(*inputA).empty()) { Event *a = (*inputA).front(); a->whichIn = 0; nodes[0]->data.inputEvents[0].push(*a); (*inputA).pop(); } while(!(*inputB).empty()) { Event* b = (*inputB).front(); b->whichIn = 0; nodes[1]->data.inputEvents[0].push(*b); (*inputB).pop(); } while(!(*inputC).empty()) { Event* c = (*inputC).front(); c->whichIn = 0; nodes[2]->data.inputEvents[0].push(*c); (*inputC).pop(); } // for(int i = 0; i < 3; i ++){ // if (nodes[i]->data.inputEvents[0].empty()){ // cout << "channel" << i << " is empty." << endl; // }else{ // cout << "channel " << i << " recv at " << nodes[i]->data.inputEvents[0].front().recvTime << endl; // } // } } void Graph::set(){ for(int i = 0; i < 3; i++){ nodes[i]->data.numInputs = 1; nodes[i]->data.numOutputs = nodes[i]->outNeigh.size(); nodes[i]->data.inputTimes.push_back(0); queue<Event> emp; nodes[i]->input[0].exchange(0); nodes[i]->data.inputEvents.push_back(emp); } for(int i = 3; i < nodes.size(); i++){ nodes[i]->data.numInputs = nodes[i]->inNeigh.size(); nodes[i]->data.numOutputs = nodes[i]->outNeigh.size(); for(int j = 0; j < nodes[i]->data.numInputs; j++){ nodes[i]->data.inputTimes.push_back(0); queue<Event> emp; nodes[i]->data.inputEvents.push_back(emp); } } } void Graph::GraphMaker(){ GNode* a0 = new GNode(0, graphID); GNode* a1 = new GNode(1, graphID); GNode* a2 = new GNode(2, graphID); GNode* a3 = new GNode(3, graphID); GNode* a4 = new GNode(4, graphID); GNode* a5 = new GNode(5, graphID); GNode* a6 = new GNode(6, graphID); GNode* a7 = new GNode(7, graphID); GNode* a8 = new GNode(8, graphID); GNode* a9 = new GNode(9, graphID); GNode* a10 = new GNode(10, graphID); GNode* a11 = new GNode(11, graphID); GNode* a12 = new GNode(12, graphID); GNode* a13 = new GNode(13, graphID); GNode* a14 = new GNode(14, graphID); nodes.push_back(a0); nodes.push_back(a1); nodes.push_back(a2); nodes.push_back(a3); nodes.push_back(a4); nodes.push_back(a5); nodes.push_back(a6); nodes.push_back(a7); nodes.push_back(a8); nodes.push_back(a9); nodes.push_back(a10); nodes.push_back(a11); nodes.push_back(a12); nodes.push_back(a13); nodes.push_back(a14); // A(i) nodes[0]->outNeigh.push_back(nodes[3]); nodes[0]->outNeigh.push_back(nodes[9]); nodes[0]->outNeigh.push_back(nodes[10]); nodes[0]->outNeigh.push_back(nodes[11]); nodes[0]->outNeigh.push_back(nodes[12]); nodes[3]->inNeigh.push_back(nodes[0]); nodes[9]->inNeigh.push_back(nodes[0]); nodes[10]->inNeigh.push_back(nodes[0]); nodes[11]->inNeigh.push_back(nodes[0]); nodes[12]->inNeigh.push_back(nodes[0]); // B(i) nodes[1]->outNeigh.push_back(nodes[4]); nodes[1]->outNeigh.push_back(nodes[7]); nodes[1]->outNeigh.push_back(nodes[8]); nodes[1]->outNeigh.push_back(nodes[11]); nodes[1]->outNeigh.push_back(nodes[12]); nodes[4]->inNeigh.push_back(nodes[1]); nodes[7]->inNeigh.push_back(nodes[1]); nodes[8]->inNeigh.push_back(nodes[1]); nodes[11]->inNeigh.push_back(nodes[1]); nodes[12]->inNeigh.push_back(nodes[1]); // C(i) nodes[2]->outNeigh.push_back(nodes[5]); nodes[2]->outNeigh.push_back(nodes[6]); nodes[2]->outNeigh.push_back(nodes[8]); nodes[2]->outNeigh.push_back(nodes[10]); nodes[2]->outNeigh.push_back(nodes[12]); nodes[5]->inNeigh.push_back(nodes[2]); nodes[6]->inNeigh.push_back(nodes[2]); nodes[8]->inNeigh.push_back(nodes[2]); nodes[10]->inNeigh.push_back(nodes[2]); nodes[12]->inNeigh.push_back(nodes[2]); nodes[0]->type = "PORT"; nodes[1]->type = "PORT"; nodes[2]->type = "PORT"; // NOT A(i) nodes[3]->type = "NOT"; nodes[3]->outNeigh.push_back(nodes[6]); nodes[3]->outNeigh.push_back(nodes[7]); nodes[3]->outNeigh.push_back(nodes[8]); nodes[6]->inNeigh.push_back(nodes[3]); nodes[7]->inNeigh.push_back(nodes[3]); nodes[8]->inNeigh.push_back(nodes[3]); // NOT B(i) nodes[4]->type = "NOT"; nodes[4]->outNeigh.push_back(nodes[6]); nodes[4]->outNeigh.push_back(nodes[9]); nodes[4]->outNeigh.push_back(nodes[10]); nodes[6]->inNeigh.push_back(nodes[4]); nodes[9]->inNeigh.push_back(nodes[4]); nodes[10]->inNeigh.push_back(nodes[4]); // NOT C(i) nodes[5]->type = "NOT"; nodes[5]->outNeigh.push_back(nodes[7]); nodes[5]->outNeigh.push_back(nodes[9]); nodes[5]->outNeigh.push_back(nodes[11]); nodes[7]->inNeigh.push_back(nodes[5]); nodes[9]->inNeigh.push_back(nodes[5]); nodes[11]->inNeigh.push_back(nodes[5]); // 1st AND GNode nodes[6]->type = "AND"; nodes[6]->outNeigh.push_back(nodes[13]); nodes[13]->inNeigh.push_back(nodes[6]); // 2nd AND GNode nodes[7]->type = "AND"; nodes[7]->outNeigh.push_back(nodes[13]); nodes[13]->inNeigh.push_back(nodes[7]); // 3rd AND GNode nodes[8]->type = "AND"; nodes[8]->outNeigh.push_back(nodes[14]); nodes[14]->inNeigh.push_back(nodes[8]); // 4th AND GNode nodes[9]->type = "AND"; nodes[9]->outNeigh.push_back(nodes[13]); nodes[13]->inNeigh.push_back(nodes[9]); // 5th AND GNode nodes[10]->type = "AND"; nodes[10]->outNeigh.push_back(nodes[14]); nodes[14]->inNeigh.push_back(nodes[10]); // 6th AND GNode nodes[11]->type = "AND"; nodes[11]->outNeigh.push_back(nodes[14]); nodes[14]->inNeigh.push_back(nodes[11]); // 7th AND GNode nodes[12]->type = "AND"; nodes[12]->outNeigh.push_back(nodes[13]); nodes[13]->inNeigh.push_back(nodes[12]); nodes[12]->outNeigh.push_back(nodes[14]); nodes[14]->inNeigh.push_back(nodes[12]); // S(i) OR nodes[13]->type = "OR"; // C(i+1) OR nodes[14]->type = "OR"; }
true
2f3cff265315e9f48c559739b6d25ad997c13ada
C++
reckhhh/LeetCodeSolutons
/C++/79_WordSearch_Medium.cpp
UTF-8
1,836
3.71875
4
[]
no_license
/* Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. For example, Given board = [ ["ABCE"], ["SFCS"], ["ADEE"] ] word = "ABCCED", -> returns true, word = "SEE", -> returns true, word = "ABCB", -> returns false. Tags: Array, Backtracking */ class Solution { private: vector<vector<char> > *board; string *word; bool **used; public: bool isInBoard(int i, int j) { return (i < 0 || j < 0 || i >= board->size() || j >= (*board)[i].size()) ? false : true; } bool check(int i, int j, int cnt) { if(cnt == word->size()) return true; if(isInBoard(i, j)) { if(!used[i][j] && (*board)[i][j] == (*word)[cnt]) { used[i][j] = true; // used bool ret = (check(i-1, j, cnt+1) || check(i+1, j, cnt+1) || check(i, j-1, cnt+1) || check(i, j+1, cnt+1)) ? true : false; used[i][j] = false; // unused return ret; } } return false; } bool exist(vector<vector<char> > &board, string word) { int N = board.size(); if(N == 0) return false; this->board = &board; this->word = &word; used = new bool*[N]; for(int i = 0; i < N; ++i) { used[i] = new bool[board[i].size()]; for(int j = 0; j < board[i].size(); ++j) used[i][j] = false; } for(int i = 0; i < N; ++i) { for(int j = 0; j < board[i].size(); ++j) if(check(i, j, 0)) return true; } return false; } };
true
f0ee758d71464ffff03a14a2f6e5ad01da4c14fe
C++
mayankamencherla/cracking-the-coding-interview-solutions
/object-oriented-design/jukebox.cpp
UTF-8
15,624
3.625
4
[ "MIT" ]
permissive
/** * Design a jukebox using object oriented principles */ #include <iostream> #include <vector> #include <limits> #include <queue> using namespace std; class JukeBox; class Song; class CD; class CDPlayer; class Album; class Artist; class PlayList; class Artist { private: /** * Name of the artist * @param string name */ string name; public: Artist() {} Artist(string name) { this->name = name; } /** * Returns name of the artist * @return string */ string getName() { return this->name; } }; class Album { private: /** * Name of the album * @param string name */ string name; public: Album() {} Album(string name) { this->name = name; } /** * Returns name of the album * @return string */ string getName() { return this->name; } }; class Song { private: /** * Artist of the song * @param Artist artist */ Artist artist; /** * Album of the song * @param Album album */ Album album; /** * Name of the song * @param string name */ string name; /** * Duration of the song in seconds * @param int duration */ int duration; /** * Returns the artist of the song * @return Artist */ Artist getArtist() { return this->artist; } /** * Returns the album of the song * @return Album */ Album getAlbum() { return this->album; } /** * Returns the name of the song * @return string */ string getName() { return this->name; } public: Song(Artist& artist, Album& album, string name, int duration) { this->artist = artist; this->album = album; this->name = name; this->duration = duration; } /** * Returns the duration of the song in seconds * @return int */ int getDuration() { return this->duration; } /** * Prints the song in a human readable way * @return void */ void print() { printf("The name of the song is : %s.\nThe song is by the artist : %s.\nThe song is in the album : %s.\nThe song lasts for %d seconds.\n", this->getName().c_str(), this->getArtist().getName().c_str(), this->getAlbum().getName().c_str(), this->getDuration()); } }; /** * Disk of songs */ class CD { private: /** * Artist of the CD * @param Artist artist */ Artist artist; /** * Album name of the CD * @param Album album */ Album album; /** * Duration of all songs in seconds * @param int duration */ int duration; /** * vector containing list of songs in the CD * @param vector<Song> songs */ vector<Song> songs; /** * Returns the artist of the CD * @return Artist */ Artist getArtist() { return this->artist; } /** * Returns the album of the CD * @return Album */ Album getAlbum() { return this->album; } /** * Returns the duration of the CD in seconds * @return int */ int getDuration() { return this->duration; } /** * Computes the duration of the CD * @return void */ void computeDuration() { this->duration = 0; for (Song s : songs) { this->duration += s.getDuration(); } } public: CD(Artist& artist, Album& album, vector<Song>& songs) { this->artist = artist; this->album = album; this->songs = songs; this->computeDuration(); } /** * Returns all the songs in the CD * @return vector<Song> */ vector<Song> getSongs() { return this->songs; } /** * Returns the number of songs in the CD * @return int */ int numSongs() { return this->getSongs().size(); } /** * Prints the CD in a human readable way * @return void */ void print() { printf("The CD is by the artist : %s.\nThe CD has the album title : %s.\nThe CD lasts for %d seconds.\n", this->getArtist().getName().c_str(), this->getAlbum().getName().c_str(), this->getDuration()); } }; /** * Playlist of songs */ class PlayList { private: /** * Duration of all songs in seconds * @param int duration */ int duration; /** * vector containing list of songs in the PlayList * @param vector<Song> songs */ vector<Song> songs; /** * Returns the duration of the PlayList in seconds * @return int */ int getDuration() { return this->duration; } /** * Computes the duration of the CD * @return void */ void computeDuration() { this->duration = 0; for (Song s : songs) { this->duration += s.getDuration(); } } public: PlayList(vector<Song>& songs) { this->songs = songs; this->computeDuration(); } /** * Returns all the songs in the CD * @return vector<Song> */ vector<Song> getSongs() { return this->songs; } /** * Returns the number of songs in the PlayList * @return int */ int numSongs() { return this->getSongs().size(); } /** * Prints the playlist in a human readable way * @return void */ void print() { printf("The playlist has %d songs.\nThe playlist lasts for %d duration. \n", this->numSongs(), this->getDuration()); } }; /** * Plays digital playlists / songs */ class DigitalPlayer { private: /** * Queue of songs to be played * @param queue<Song> songQ */ queue<Song> songQ; public: DigitalPlayer(){} /** * Empties the queue of songs to be played * @return void */ void emptyQueue() { while (!this->empty()) songQ.pop(); } /** * Plays the selected song * @param Song& s * @return void */ void selectSong(Song& s) { this->emptyQueue(); this->enqueueSong(s); this->play(); } /** * Plays the selected playlist * @param PlayList& pl * @return void */ void selectPlaylist(PlayList& pl) { this->emptyQueue(); for (Song s : pl.getSongs()) this->enqueueSong(s); this->play(); } /** * Stops playing whatever it is playing now * @return void */ void stopPlaying() { this->emptyQueue(); } /** * Returns whether there are songs left in the queue * @return bool */ bool empty() { return this->songQ.empty(); } /** * Enqueues the next song * @param Song& s * @return void */ void enqueueSong(Song& s) { this->songQ.push(s); } /** * Dequeues the first song to be played * @return Song */ Song dequeueSong() { Song s = songQ.front(); songQ.pop(); return s; } /** * Plays the songs in the queue * @return void */ void play() { while (!this->empty()) { printf("Playing the next song in the playlist\n\n"); Song s = this->dequeueSong(); s.print(); } } }; /** * Plays songs on a CD */ class CDPlayer { private: /** * Queue of songs to be played * @param queue<Song> songQ */ queue<Song> songQ; public: CDPlayer(){} /** * Empties the queue of songs to be played * @return void */ void emptyQueue() { while (!this->empty()) songQ.pop(); } /** * Plays the selected CD * @param CD& cd * @return void */ void select(CD& cd) { this->emptyQueue(); for (Song s : cd.getSongs()) songQ.push(s); this->play(); } /** * Stops playing whatever it is playing now * @return void */ void stopPlaying() { this->emptyQueue(); } /** * Returns whether there are songs left in the queue * @return bool */ bool empty() { return songQ.empty(); } /** * Dequeues the first song to be played * @return Song */ Song dequeueSong() { Song s = songQ.front(); songQ.pop(); return s; } /** * Plays the songs in the queue * @return void */ void play() { while (!this->empty()) { printf("\nPlaying the next song in the playlist\n"); Song s = this->dequeueSong(); s.print(); } } }; class JukeBox { private: /** * The digital player attached to the JukeBox * @param DigitalPlayer dp */ DigitalPlayer dp; /** * The CD player attached to the JukeBox * @param CDPlayer cp */ CDPlayer cp; /** * Returns the disk player attached to the JukeBox * @return DigitalPlayer */ DigitalPlayer getDigitalPlayer() { return this->dp; } /** * Returns the digital player attached to the JukeBox * @return CDPlayer */ CDPlayer getCDPlayer() { return this->cp; } public: JukeBox() {} JukeBox(DigitalPlayer& dp, CDPlayer& cp) { this->dp = dp; this->cp = cp; } /** * Changes state of the jukebox * @param CD& cd * @return void */ void selectDisk(CD& cd) { this->stopPlaying(); this->getCDPlayer().select(cd); } /** * Changes state of the jukebox * @param PlayList& pl * @return void */ void selectPlaylist(PlayList& pl) { this->stopPlaying(); this->getDigitalPlayer().selectPlaylist(pl); } /** * Changes state of the jukebox * @param Song& s * @return void */ void selectSong(Song& s) { this->stopPlaying(); this->getDigitalPlayer().selectSong(s); } /** * Clears the state of the playing items * @return void */ void stopPlaying() { this->getDigitalPlayer().stopPlaying(); this->getCDPlayer().stopPlaying(); } // TODO: Enqueue functionality }; class User { private: /** * ID of the user * @param int ID */ int ID; /** * A reference to the jukeBox, that the user can interact with * @param JukeBox box */ JukeBox box; /** * Generates a unique ID for the user * @returns void */ void generateId() { this->ID = rand() % numeric_limits<int>::max(); } /** * Returns the JukeBox instance * @return JukeBox */ JukeBox getJukeBox() { return this->box; } public: User(JukeBox& J) { this->generateId(); this->box = J; } /** * User plays a song on the JukeBox * @param Song& s * @return void */ void selectSong(Song& s) { this->getJukeBox().selectSong(s); } /** * User plays a play list on the JukeBox * @param PlayList& pl * @return void */ void selectPlaylist(PlayList& pl) { this->getJukeBox().selectPlaylist(pl); } /** * User selects a CD on the JukeBox * @param CD& cd * @return void */ void selectDisk(CD& cd) { this->getJukeBox().selectDisk(cd); } // Add play and pause feature }; vector<Song> getSongs(Artist& a, Album& al) { vector<Song> res; string list = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; for (int i=0; i<10; i++) { string name; int len = 15 + rand() % 20; while (len > 0) { int x = rand() % list.size(); name += list[x]; len--; } int duration = 180 + rand() % 1000; Song s = Song(a, al, name, duration); res.push_back(s); } return res; } int main() { CDPlayer cp = CDPlayer(); DigitalPlayer dp = DigitalPlayer(); JukeBox jb = JukeBox(dp, cp); User u1 = User(jb); User u2 = User(jb); Artist a1 = Artist("Paul Harrison"); Artist a2 = Artist("Govinda Dasu"); Album alb1 = Album("Application to Simplifield"); Album alb2 = Album("Stanford Univeristy"); vector<Song> s1 = getSongs(a1, alb1); vector<Song> s2 = getSongs(a2, alb2); CD cd1 = CD(a1, alb1, s1); CD cd2 = CD(a2, alb2, s2); int num = (s1.size() + s2.size()) / 3; int ind1 = 0, ind2 = 0; vector<Song> s3; for (int i=0; i<num; i++) { if (ind2 >= s2.size() || i % 2 == 0) { Song s = s1[ind1]; s3.push_back(s); ind1++; } else { Song s = s2[ind2]; s3.push_back(s); ind2++; } } PlayList pl = PlayList(s3); u1.selectPlaylist(pl); u2.selectDisk(cd2); }
true
a855b7708edc1e2d9c762c4d989e9157a269fe0b
C++
huangzongwu/F2Native
/core/graphics/scale/Category.h
UTF-8
6,314
2.578125
3
[ "MIT" ]
permissive
#ifndef XG_GRAPHICS_SCALE_CAT_H #define XG_GRAPHICS_SCALE_CAT_H #include "graphics/scale/Scale.h" #include "utils/common.h" #include <WilkinsonExtended/WilkinsonExtended.h> #include <iterator> #include <math.h> #include <string> #include <unordered_map> using namespace std; namespace xg { namespace scale { /** * 分类度量,主要针对字符串 */ class Category : public AbstractScale { public: Category(const std::string &_field, const nlohmann::json &_values, const nlohmann::json &config = {}) : AbstractScale(_field, _values) { if(config.is_object()) { config_.merge_patch(config); } this->InitConfig(); } ScaleType GetType() const noexcept override { return ScaleType::Cat; } void Change(const nlohmann::json &cfg = {}) override { bool valuesChanged = false; if(cfg.contains("values")) { values = cfg["values"]; valuesChanged = true; } if(cfg.contains("range") && cfg["range"].is_array()) { const nlohmann::json &range = cfg["range"]; rangeMin = range[0]; rangeMax = range[1]; config_["range"] = range; } bool reCalcTicks = true; if(!cfg.contains("ticks")) { if(config_.contains("tickCount")) { this->tickCount = config_["tickCount"]; } } else { if(cfg["ticks"].is_boolean()) { reCalcTicks = cfg["ticks"]; } else if(cfg["ticks"].is_array()) { this->ticks = cfg["ticks"]; reCalcTicks = false; } } if(cfg.contains("domain") && cfg["domain"].is_array()) { const nlohmann::json &domain = cfg["domain"]; this->min = domain[0]; this->max = domain[1]; } else if(valuesChanged) { this->min = 0.; this->max = fmax(0, values.size() - 1); } if(reCalcTicks) { this->ticks = this->CalculateTicks(); } scaledCache_.clear(); } double Scale(const nlohmann::json &key) override { std::size_t keyHash = nlohmann::detail::hash(key); if(scaledCache_.find(keyHash) != scaledCache_.end()) { return scaledCache_.at(keyHash); } double percent = 0; std::size_t index = this->Transform(key); if(index + 1 > 0) { percent = CalculatePercent(static_cast<double>(index), this->min, this->max); } else { double kVal = 0.; if(key.is_number()) { kVal = key; } std::size_t divide = fmax(1, GetValuesSize() - 1); percent = kVal / (static_cast<double>(divide)); } double value = CalculateValue(percent, this->rangeMin, this->rangeMax); scaledCache_[keyHash] = value; return value; } nlohmann::json Invert(double val) override { double percent = CalculatePercent(val, this->rangeMin, this->rangeMax); double domainRange = this->max - this->min; int index = static_cast<int>(round(domainRange * percent) + this->min); if(index < this->min || index > this->max) { return nlohmann::json(); } return values[index]; } virtual std::size_t Transform(const nlohmann::json &key) const { if(values.empty()) { return -1; } std::size_t index = -1; for(size_t i = 0; i < values.size(); i++) { if(values[i] == key) { index = i; break; } } return index; } virtual inline std::size_t GetValuesSize() noexcept override { return this->max - this->min + 1; } protected: virtual nlohmann::json CalculateTicks() override { std::size_t valueSize = values.size(); if(valueSize == 0) { return {}; } if(this->tickCount > 0 && this->tickCount <= max - min + 1) { nlohmann::json rst; double Q[] = {1, 2, 5, 3, 4, 7, 6, 8, 9}; double w[] = {0.25, 0.2, 0.5, 0.05}; double outlmin, outlmax, outlstep; wilk_ext(min, max, this->tickCount, -1, Q, 6, w, &outlmin, &outlmax, &outlstep); int step = static_cast<int>(outlstep); if(step > 0) { std::size_t _max = static_cast<std::size_t>(max); for(std::size_t index = static_cast<std::size_t>(min); index <= _max; index += step) { nlohmann::json &_item = values[index]; rst.push_back(_item); } } if(rst.size() < tickCount) { rst.push_back(values[valueSize - 1]); } return std::move(rst); } return values; } // 定义域转 0~1 值域 static inline double CalculatePercent(double index, double min, double max) { return (index - min) / fmax(max - min, 1); } static inline double CalculateValue(double percent, double min, double max) { return min + percent * (max - min); } virtual void InitConfig() { nlohmann::json &range = config_["range"]; rangeMin = range[0]; rangeMax = range[1]; if(config_.contains("domain") && config_["domain"].is_array()) { nlohmann::json &domain = config_["domain"]; this->min = domain[0]; this->max = domain[1]; } else { this->min = 0.; this->max = fmax(0, values.size() - 1); } if(config_.contains("tick")) { SetTickCallbackFun(config_["tick"]); } if(config_.contains("tickCount")) { this->tickCount = config_["tickCount"]; } else { this->tickCount = GetValuesSize(); } if(config_.contains("ticks") && config_["ticks"].is_array()) { this->ticks = config_["ticks"]; }else { this->ticks = this->CalculateTicks(); } } protected: nlohmann::json config_ = { {"range", {0.0, 1.0}}, }; private: std::unordered_map<std::size_t, double> scaledCache_; }; // namespace scale } // namespace scale } // namespace xg #endif // XG_GRAPHICS_SCALE_CAT_H
true
3d91688122be66ec35036ecebab7bab35b82fd56
C++
dalek7/umbrella
/MFC/MathDisp/MathJS/MathJS/lib/PTRList.cpp
UTF-8
6,774
2.78125
3
[ "MIT" ]
permissive
#include "stdafx.h" #include "PTRList.h" #include <string.h> CPTRList::CPTRList() { pTop = pEnd = pCur = NULL;; nCurrent= -1; nMax = 0; } CPTRList::~CPTRList() { RemoveAll2(); } void CPTRList::AddTail( void *pData ) { PTR_BLK *pNew = new PTR_BLK; pNew->pData = pData; pNew->pNext = NULL; if ( pEnd ) { pNew->pPrev = pEnd; pEnd->pNext = pNew; } else pNew->pPrev = NULL; if ( pTop==NULL ) pTop = pNew; pEnd = pNew; nMax++; } void CPTRList::AddHead( void *pData ) { PTR_BLK *pNew = new PTR_BLK; pNew->pData = pData; pNew->pPrev = NULL; if ( pTop ) { pNew->pNext = pTop; pTop->pPrev = pNew; } else pNew->pNext = NULL; if ( pEnd==NULL ) pEnd= pNew; pTop = pNew; nMax++; nCurrent = -1; } void CPTRList::AddTail( char *p) { char *pNew = new char[strlen(p)+1]; strcpy( pNew,p ); CPTRList::AddTail((void*)pNew); } void CPTRList::AddHead( char *p) { char *pNew = new char[strlen(p)+1]; strcpy( pNew,p ); CPTRList::AddHead((void*)pNew); } void *CPTRList::GetHead() { return pTop; } void *CPTRList::GetTail() { return pEnd; } void CPTRList::RemoveAt2( int n ) { if ( !GetAt(n) ) return; if ( pCur==pTop ) { pCur = pTop->pNext; if ( pTop->pData ) delete pTop->pData; delete pTop; pTop = pCur; if ( pTop ) pTop->pPrev = NULL; } else if ( pCur==pEnd) { pCur = pEnd->pPrev; if ( pEnd->pData ) delete pEnd->pData; delete pEnd; pEnd = pCur; if ( pEnd ) pEnd->pNext = NULL; } else { pCur->pPrev->pNext = pCur->pNext; pCur->pNext->pPrev = pCur->pPrev; PTR_BLK *pTemp = pCur->pNext; if ( pCur->pData ) delete (pCur->pData); delete pCur; pCur = pTemp; } nCurrent = -1; nMax--; if ( nMax<0 ) nMax = 0; if ( nMax==0 ) pEnd = NULL; } void CPTRList::RemoveAt( int n ,BOOL bSelfDestroy) { if ( !GetAt(n) ) return; if ( pCur==pTop ) { pCur = pTop->pNext; if ( bSelfDestroy) if ( pTop->pData ) delete pTop->pData; delete pTop; pTop = pCur; if ( pTop ) pTop->pPrev = NULL; } else if ( pCur==pEnd) { pCur = pEnd->pPrev; if ( bSelfDestroy) if ( pEnd->pData ) delete pEnd->pData; delete pEnd; pEnd = pCur; if ( pEnd ) pEnd->pNext = NULL; } else { pCur->pPrev->pNext = pCur->pNext; pCur->pNext->pPrev = pCur->pPrev; PTR_BLK *pTemp = pCur->pNext; if ( bSelfDestroy) if ( pCur->pData ) delete (pCur->pData); delete pCur; pCur = pTemp; } nCurrent = -1; nMax--; if ( nMax<0 ) nMax = 0; if ( nMax==0 ) pEnd = NULL; } void* CPTRList::GetAt( int n) { int nCnt = 0; PTR_BLK *pBlk = pCur = pTop; if ( n>=GetCount() ) return NULL; nCurrent = n; while(pBlk!=NULL) { if ( n==nCnt ) return pBlk->pData; nCnt++; pBlk = pCur = pBlk->pNext; } nCurrent = -1; return NULL; } void* CPTRList::Search( int n ) { if ( n<0) return NULL; if ( nCurrent<0 ) return GetAt(n); if ( n>=nMax ) return NULL; if ( nCurrent-n==-1 ) { nCurrent = n; pCur = pCur->pNext; return pCur->pData; } if ( nCurrent-n==1 ) { nCurrent = n; pCur = pCur->pPrev; return pCur->pData; } if ( nCurrent-n==0 ) { nCurrent = n; return pCur->pData; } return GetAt(n); } int CPTRList::GetCount() { return nMax; } void CPTRList::RemoveAll2() { PTR_BLK *pTemp; pCur = pTop; while( pCur) { pTemp = pCur->pNext; if ( pCur->pData ) delete (pCur->pData); delete pCur; pCur = pTemp; } pCur = NULL; pTop = NULL; pEnd = NULL; nMax = 0; nCurrent= -1; } void CPTRList::RemoveAll(BOOL bSelfDestroy) { if ( bSelfDestroy==FALSE) { PTR_BLK *pTemp; pCur = pTop; while( pCur) { pTemp = pCur->pNext; delete pCur; pCur = pTemp; } pCur = NULL; pTop = NULL; pEnd = NULL; nMax = 0; nCurrent= -1; } else CPTRList::RemoveAll2(); } BOOL CPTRList::IsEmpty() { return nMax>0 ? TRUE:FALSE; } void CPTRList::InsertAfter( int n,void *pData) { if ( n<0 ) { AddTail(pData); return ; } if ( n==GetCount()-1) { AddTail(pData); return; } GetAt(n); nCurrent = -1; PTR_BLK *pNew = new PTR_BLK; pNew->pData = pData; pNew->pPrev = pCur; pNew->pNext = pCur->pNext; pCur->pNext->pPrev = pNew; pCur->pNext = pNew; nMax++; } void CPTRList::InsertAfter( void *pData ) { if ( pCur==pEnd ) { AddTail( pData ); return; } PTR_BLK *pNew = new PTR_BLK; pNew->pData = pData; pNew->pPrev = pCur; pNew->pNext = pCur->pNext; pCur->pNext->pPrev = pNew; pCur->pNext = pNew; nMax++; } void CPTRList::InsertBefore( int n,void *pData) { if ( n<0 ) { AddTail(pData); return; } if ( n==0 ) { AddHead(pData); return ; } GetAt(n); nCurrent = -1; PTR_BLK *pNew = new PTR_BLK; pNew->pData = pData; pNew->pPrev = pCur->pPrev; pNew->pNext = pCur; pCur->pPrev->pNext = pNew; pCur->pPrev = pNew; nMax++; } void CPTRList::InsertBefore( void *pData) { if ( pCur==pTop ) { AddHead(pData); return ; } PTR_BLK *pNew = new PTR_BLK; pNew->pData = pData; pNew->pPrev = pCur->pPrev; pNew->pNext = pCur; pCur->pPrev->pNext = pNew; pCur->pPrev = pNew; nMax++; } void* CPTRList::operator [](int n) { return Search(n); } int CPTRList::FindData(void *p) { void *pData; for (int i=0;i<GetCount();i++) { pData = Search(i); if ( pData==p ) return i; } return -1; } void CPTRList::Load(char *psz,int n) { FILE *fp = fopen(psz,"rb"); if ( fp==NULL) return; int cnt; fread( &cnt,sizeof(int),1,fp); for(int i=0;i<cnt;i++) { BYTE *p = new BYTE[n]; fread( p,n,1,fp); AddTail(p); } fclose(fp); } void CPTRList::Save(char *psz,int n) { FILE *fp = fopen(psz,"wb"); if ( fp==NULL) return; int cnt = GetCount(); fwrite( &cnt,sizeof(int),1,fp); for(int i=0;i<GetCount();i++) { void *p = Search(i); fwrite( p,n,1,fp); } fclose(fp); } void* CPTRList::Prev(int n) { PTR_BLK *p = pCur; for (int i=0;i<n;i++) { p = p->pPrev; if ( p==NULL) return NULL; } return p->pData; } void* CPTRList::Next(int n) { PTR_BLK *p = pCur; for (int i=0;i<n;i++) { p = p->pNext; if ( p==NULL) return NULL; } return p->pData; } CRectList::CRectList() { } CRectList::~CRectList() { RemoveAll2(); } void CRectList::Add(CRect& rect) { CRect *pNew = new CRect(rect); CPTRList::AddTail(pNew); } CRect CRectList::Search(int n) { CRect *p = (CRect*)CPTRList::Search(n); CRect ret(0,0,0,0); if ( p==NULL ) return ret; return *p; }
true
941ef4d487d01426ab6c7668d109fdc24363dc2a
C++
ThomasvanBommel/matrix-transpose
/src/Matrix.h
UTF-8
443
2.765625
3
[]
no_license
/** * @author Thomas vanBommel * @since 01-08-2021 */ #ifndef MATRIX_H_ #define MATRIX_H_ #include <iostream> using namespace std; class Matrix { public: Matrix(int, int, double=0.0, double=0.0); void transp(); double & operator () (int, int); friend ostream & operator << (ostream &, Matrix &); private: int n_, m_; double * M_; bool t_{false}; int indexOf(int, int); int rows(); int cols(); }; #endif
true
a57c37e445f576bd76a2584dec41e28648b3a719
C++
vajanko/Algorithms
/Homeworks/08. semester/Levenshtein/Levenshtein/main.cpp
UTF-8
12,031
3.265625
3
[]
no_license
#include <string> #include <sstream> #include <vector> #include <stdio.h> #include <stdlib.h> #include <iostream> #include <omp.h> #include <climits> typedef int size_type; void generate(const char* filename, size_type count, int seed) { FILE* f = fopen(filename, "wb"); if (!f) return; srand(seed); while (count--) { char ch = (char)((rand() >> 7) & 0xff); fwrite(&ch, 1, 1, f); } fclose(f); } // convert from string to given type template<typename T> T lexical_cast(const char* str) { std::istringstream buf(str); T res; buf >> res; return res; } template<typename T> T smaller(T x, T y) { return (x<y) ? x : y; } template<typename T> T smaller(T x, T y, T z) { return smaller<T>(smaller<T>(x, y), z); } #define N 1024 int generate_files(char* argv[]) { // second option - generate random strings int count = lexical_cast<size_type>(argv[2]); size_type seed = lexical_cast<size_type>(argv[3]); generate(argv[1], count, seed); return 0; } bool read_files(const char *file1, const char *file2, char *&s, size_t &s_size, char *&t, size_t &t_size) { FILE* f1 = fopen(file1, "rb"); FILE* f2 = fopen(file2, "rb"); if (!f1 || !f2) return false; fseek(f1, 0, SEEK_END); s_size = ftell(f1); s = new char[s_size]; fseek(f1, 0, SEEK_SET); fread(s, 1, s_size, f1); fclose(f1); fseek(f2, 0, SEEK_END); t_size = ftell(f2); t = new char[t_size]; fseek(f2, 0, SEEK_SET); fread(t, 1, t_size, f2); fclose(f2); return true; } size_type levenshtein_serial(const char *s, size_t s_size, const char *t, size_t t_size) { // degenerate cases if (s_size == 0) return t_size; if (t_size == 0) return s_size; // create two work vectors of integer distances size_t vec_size = t_size + 1; size_type *dst1 = new size_type[vec_size]; size_type *dst2 = new size_type[vec_size]; for (int i = 0; i <= t_size; ++i) dst2[i] = i; for (int i = 1; i <= s_size; ++i) { dst1[0] = i; // use formula to fill in the rest of the row for (int j = 1; j <= t_size; ++j) { size_type upper = dst2[j]; size_type left = dst1[j - 1]; size_type upperleft = dst2[j - 1]; char cost = (s[i - 1] == t[j - 1]) ? 0 : 1; size_type total = smaller<size_type>(upper + 1, left + 1, upperleft + cost); dst1[j] = total; } std::swap(dst1, dst2); } return dst2[t_size]; } void rotate(size_type *&ptr1, size_type *&ptr2, size_type *&ptr3) { size_type *tmp = ptr1; ptr1 = ptr2; ptr2 = ptr3; ptr3 = tmp; } size_type levenshtein_parallel(const char *s, size_t s_size, const char *t, size_t t_size) { if (s_size < t_size) { std::swap(s, t); std::swap(s_size, t_size); } size_t diag_size = t_size; size_type *diag1 = new size_type[diag_size + 1]; size_type *diag2 = new size_type[diag_size + 1]; size_type *diag3 = new size_type[diag_size + 1]; // total number of diagonals size_t total_diags = s_size + t_size + 1; // init diag2[0] = 0; diag1[0] = 1; diag1[1] = 1; // step=1 for (size_t step = 2; step <= diag_size; ++step) { #pragma omp parallel for for (size_type i = 1; i < step; ++i) { size_type i1 = i - 1; char cost = (s[step - 1 - i] == t[i1]) ? 0 : 1; size_type upper = diag1[i1]; size_type left = diag1[i]; size_type upperleft = diag2[i1]; diag3[i] = smaller<size_type>(upper + 1, left + 1, upperleft + cost); } diag3[0] = step; diag3[step] = step; rotate(diag2, diag1, diag3); } size_t full_diag_count = total_diags - diag_size; for (size_t step = diag_size + 1; step <= full_diag_count; ++step) { #pragma omp parallel for for (size_type i = 1; i <= diag_size; ++i) { size_type i1 = i - 1; char cost = (s[step - i - 1] == t[i1]) ? 0 : 1; size_type upper = diag1[i]; size_type left = diag1[i1]; size_type upperleft = diag2[i1]; diag3[i] = smaller<size_type>(upper + 1, left + 1, upperleft + cost); } diag3[0] = step; rotate(diag2, diag1, diag3); } size_t err = 0; for (size_t step = full_diag_count + 1; step < total_diags; ++step) { #pragma omp parallel for for (size_type i = 1; i <= total_diags - step; ++i) { char cost = (s[s_size - i] == t[step - full_diag_count - 1 + i]) ? 0 : 1; size_type upper = diag1[i + 1]; size_type left = diag1[i]; size_type upperleft = diag2[i + err]; diag3[i] = smaller<size_type>(upper + 1, left + 1, upperleft + cost); } diag3[0] = step; err = 1; // WARNNING: do not rotate if nothing has been done if (total_diags - step > 1) rotate(diag2, diag1, diag3); } size_type res = diag3[1]; delete diag1; delete diag2; delete diag3; return res; } size_type block_width = 8; void print_matrix(size_type ** matrix, size_t s_size, size_t t_size) { for (size_type r = 0; r <= s_size; ++r) { for (size_type c = 0; c <= t_size; ++c) std::cout << matrix[r][c] << " "; std::cout << std::endl; } } size_type **allocate_matrix(size_t s_size, size_t t_size) { size_type **matrix = new size_type*[s_size + 1]; // rows matrix[0] = new size_type[t_size + 1]; // first rows for (size_type j = 0; j <= t_size; ++j) matrix[0][j] = j; for (size_type i = 1; i <= s_size; ++i) { matrix[i] = new size_type[t_size + 1]; // alocate rows matrix[i][0] = i; // initialize first column } return matrix; } void delete_matrix(size_type ** matrix, size_t s_size, size_t t_size) { for (size_type i = 0; i <= s_size; ++i) delete[] matrix[i]; delete[]matrix; } void calculate_diagonal(size_type h_base, size_type v_base, size_type block_count, const char*s, const char *t, size_type **matrix) { size_type h_start = h_base + 1; size_type v_start = v_base + block_count; //v_base + block_count - block_index + 1; #pragma omp parallel for firstprivate (h_start, v_start) //for (size_type block_index = 1; block_index <= block_count; ++block_index) //for (size_type block_index = h_base + 1; block_index <= h_base + block_count; ++block_index) for (size_type i = 0; i < block_count; ++i) { char cost = (s[h_start - 1] == t[v_start - 1]) ? 0 : 1; size_type upper = matrix[h_start - 1][v_start]; size_type left = matrix[h_start][v_start - 1]; size_type upperleft = matrix[h_start - 1][v_start - 1]; matrix[h_start][v_start] = smaller<size_type>(upper + 1, left + 1, upperleft + cost); /*++h_start; --v_start;*/ } } size_type levenshtein_single_blocks(const char *s, size_t s_size, const char *t, size_t t_size) { if (s_size < t_size) { std::swap(s, t); std::swap(s_size, t_size); } // INITIALIZATION - allocate memory size_type **matrix = allocate_matrix(s_size, t_size); // width of matrix divided into blocks size_type max_blocks = t_size; // number of blocks on the diagonal is growing for (size_type block_count = 1; block_count < max_blocks; ++block_count) { calculate_diagonal(0, 0, block_count, s, t, matrix); } // number of blocks is constant = total_blocks size_type block_rows = s_size; size_type block_cols = t_size; size_type diag_count = block_rows + block_cols - 1; size_type max_block_diagonals = diag_count - 2 * block_cols + 2; for (size_type i = 0; i < max_block_diagonals; ++i) { calculate_diagonal(i, 0, max_blocks, s, t, matrix); } // number of blocks is falling for (size_type block_count = max_blocks - 1; block_count > 0; --block_count) { size_type h_base = block_rows - block_count; // 1, 2, 3, ... size_type v_base = max_blocks - block_count; calculate_diagonal(h_base, v_base, block_count, s, t, matrix); } size_type res = matrix[s_size][t_size]; //delete_matrix(matrix, s_size, t_size); return res; } void calculate_block_diagonal(size_type h_base, size_type v_base, size_type block_count, size_type block_size, const char*s, const char *t, size_type **matrix) { // in this step we have "block_count" block on the diagonale // we will start with the block most up and right and follow down and left #pragma omp parallel for for (size_type block_index = 1; block_index <= block_count; ++block_index) { // start (up-)right and move (down-)left -> first part is the block index, multipling by block_size // we get the actual position size_type h_start = ((h_base + block_index - 1) << block_width) ^ 1; //(h_base + block_index - 1) * block_size + 1; // just add block_size to get at the end of current block size_type h_end = h_start + block_size; // vertical start size_type v_start = ((v_base + block_count - block_index) << block_width) ^ 1; //(v_base + block_count - block_index) * block_size + 1; size_type v_end = v_start + block_size; // the same algorithm as for serial version, but only on this particular chunk of data for (size_type i = h_start; i < h_end; ++i) // block_size iterations { for (size_type j = v_start; j < v_end; ++j) // block_size iterations { // this is calculation for one block char cost = (s[i-1] == t[j-1]) ? 0 : 1; size_type upper = matrix[i-1][j]; size_type left = matrix[i][j-1]; size_type upperleft = matrix[i-1][j-1]; matrix[i][j] = smaller<size_type>(upper + 1, left + 1, upperleft + cost); } } } } size_type levenshtein_blocks(const char *s, size_t s_size, const char *t, size_t t_size) { if (s_size < t_size) { std::swap(s, t); std::swap(s_size, t_size); } // INITIALIZATION - allocate memory size_type **matrix = allocate_matrix(s_size, t_size); size_type block_size = 256; // width of matrix divided into blocks size_type max_blocks = t_size >> block_width; //t_size / block_size; // number of blocks on the diagonal is growing for (size_type block_count = 1; block_count < max_blocks; ++block_count) { calculate_block_diagonal(0, 0, block_count, block_size, s, t, matrix); } // number of blocks is constant = total_blocks size_type block_rows = s_size / block_size; size_type block_cols = t_size / block_size; size_type diag_count = block_rows + block_cols - 1; size_type max_block_diagonals = diag_count - 2 * block_cols + 2; for (size_type i = 0; i < max_block_diagonals; ++i) { calculate_block_diagonal(i, 0, max_blocks, block_size, s, t, matrix); } // number of blocks is falling for (size_type block_count = max_blocks - 1; block_count > 0; --block_count) { size_type h_base = block_rows - block_count; // 1, 2, 3, ... size_type v_base = max_blocks - block_count; calculate_block_diagonal(h_base, v_base, block_count, block_size, s, t, matrix); } size_type res = matrix[s_size][t_size]; //delete_matrix(matrix, s_size, t_size); return res; } int calculate(char *argv[]) { char *s; size_t s_size; char *t; size_t t_size; if (!read_files(argv[1], argv[2], s, s_size, t, t_size)) return -1; //size_type dist1 = levenshtein_serial(s, s_size, t, t_size); //std::cout << "serial: " << dist1 << std::endl; size_type dist2 = levenshtein_parallel(s, s_size, t, t_size); std::cout << dist2 << std::endl; //std::cout << "parallel: " << dist2 << std::endl; //size_type dist3 = levenshtein_blocks(s, s_size, t, t_size); //std::cout << dist3 << std::endl; //size_type dist4 = levenshtein_single_blocks(s, s_size, t, t_size); //std::cout << dist4 << std::endl; } void test() { /*char *s = "abcdffff"; char *t = "adbcffff"; auto dist = levenshtein_blocks(s, 8, t, 8); system("pause");*/ //long(*foo)() = &func; //long max = 1024 * 1024;// *1024; //long double sum = 0; ////long x = foo() * foo() * 1024; //for (long i = 0; i < max >> 10; ++i) //{ // for (long j = 1; j < 1024; j <<= 1) // { // sum += i + j; // } //} //std::cout << sum << std::endl; //sum = 0; //for (long i = 0; i < max; ++i) //{ // sum += i; //} //std::cout << sum << std::endl; } long func() { return 1024; } int main(int argc, char* argv[]) { int ret = 0; //double time = omp_get_wtime(); //std::cout << "BEGIN" << std::endl; //// BEGIN if (argc == 4) { ret = generate_files(argv); } else if (argc == 3) { ret = calculate(argv); } //// END //std::cout << "END" << std::endl; //time = omp_get_wtime() - time; //std::cout << "execution time: " << time << " s" << std::endl; //system("pause"); return ret; }
true
9bbc40d622252617d117d1df26cb6c7ff71b64d1
C++
jxzhsiwuxie/cppPrimer
/chap09/exercises/ex_9.14.cpp
UTF-8
1,026
4.25
4
[]
no_license
//练习 9.14:编写程序,将一个 list 中的 char * 指针(指向 C 风格字符串)元素赋值给一个 vector 中的 string。 #include <iostream> #include <list> #include <string> #include <vector> using std::cout; using std::endl; using std::list; using std::string; using std::vector; int main() { list<const char*> cStrList = {"abc", "fed", "ihj"}; cout << "原始的 list<char*> 中的内容为:" << endl; for (const auto& s : cStrList) cout << s << " "; cout << endl; vector<string> strings0(cStrList.begin(), cStrList.end()); cout << "使用初始化的方式得到的 vector<string> 中的内容为:" << endl; for (const auto& s : strings0) cout << s << " "; cout << endl; vector<string> strings1; strings1.assign(cStrList.begin(), cStrList.end()); cout << "使用 assign 的方式得到的 vector<string> 中的内容为:" << endl; for (const auto& s : strings1) cout << s << " "; cout << endl; return 0; }
true
16396e3831abb3b5ccf998fb81230bf151f31e99
C++
nevyn/OverAnimate
/OverAnimate.cpp
UTF-8
2,773
2.890625
3
[]
no_license
#include "OverAnimate.h" Animation:: Animation(TimeInterval duration, bool repeats) : beginTime(0), duration(duration), scheduled(0), enabled(1), repeats(repeats) { } void Animation:: animate( float absoluteTime ) { } #pragma mark - BoundFunctionAnimation:: BoundFunctionAnimation( AnimationFunction func, int boundArgument, TimeInterval duration, bool repeats ) : Animation(duration, repeats), function(func), boundArgument(boundArgument) { } void BoundFunctionAnimation:: animate( float absoluteTime ) { this->function(this, boundArgument, absoluteTime); } #pragma mark - AnimationSystem:: AnimationSystem() : _lowestAvailableIndex(0), _elapsedTime(0) { memset(_animations, 0, kMaxAnimationCount*sizeof(Animation*)); } float AnimationSystem:: now() { return _elapsedTime; } int AnimationSystem:: addAnimation( Animation *animation ) { if(animation->scheduled) { return -1; } if(_lowestAvailableIndex == kMaxAnimationCount-1) { // full, don't add any more return -1; } int idx = _lowestAvailableIndex; _lowestAvailableIndex++; _animations[idx] = animation; animation->scheduled = true; return idx; } void AnimationSystem:: removeAnimation( int idx ) { if(idx < 0) return; Animation *animation = _animations[idx]; if(idx >= _lowestAvailableIndex || !animation) return; animation->scheduled = false; _animations[idx] = NULL; // move the rest down for(int j = idx; j < _lowestAvailableIndex-1; j++) { _animations[j] = _animations[j+1]; } _lowestAvailableIndex--; } void AnimationSystem:: removeAnimation( Animation *toRemove ) { if(!toRemove || !toRemove->scheduled) { return; } for(int i = 0; i < _lowestAvailableIndex; i++) { Animation *animation = _animations[i]; if(animation == toRemove) { removeAnimation(i); break; } } } void AnimationSystem:: playElapsedTime( float deltaAdded ) { _elapsedTime += deltaAdded; for(int i = 0; i < _lowestAvailableIndex; i++) { Animation *animation = _animations[i]; if(!animation->enabled) { continue; } if(_elapsedTime > animation->beginTime) { float fraction = (_elapsedTime - animation->beginTime) / animation->duration; if(fraction >= 1.0) { if(animation->repeats) { animation->beginTime = now(); } else { removeAnimation(animation); i--; continue; } } animation->animate(fraction); } } }
true
a3b1dece4e4b4233da26857cb01d4b25d95cc153
C++
shivang99/Data-Structures
/Hash Table/HashTable.cpp
UTF-8
2,940
3.109375
3
[]
no_license
#include "HashTable.h" template <typename DataType, typename KeyType> HashTable<DataType, KeyType>::HashTable(int initTableSize) { tableSize = initTableSize; dataTable = new BSTree<DataType, KeyType>[tableSize]; } template <typename DataType, typename KeyType> HashTable<DataType, KeyType>::HashTable(const HashTable& other) { tableSize = other.tableSize; copyTable(other); } template <typename DataType, typename KeyType> HashTable<DataType,KeyType>& HashTable<DataType, KeyType>::operator=(const HashTable& other) { if (this != other) { clear(); tableSize = other.tableSize; dataTable = new BSTree<DataType, KeyType>[tableSize]; copyTable(other); } return *this; } template <typename DataType, typename KeyType> HashTable<DataType, KeyType>::~HashTable() { clear(); } template <typename DataType, typename KeyType> void HashTable<DataType, KeyType>::insert(const DataType& newDataItem) { int insertAt; insertAt = newDataItem.hash(newDataItem.getKey()) % tableSize; dataTable[insertAt].insert(newDataItem); } template <typename DataType, typename KeyType> bool HashTable<DataType, KeyType>::remove(const KeyType& deleteKey) { DataType temp; int delAt = temp.hash(deleteKey) % tableSize; return(dataTable[delAt].remove(deleteKey)); } template <typename DataType, typename KeyType> bool HashTable<DataType, KeyType>::retrieve(const KeyType& searchKey, DataType& returnItem) const { int foundAt; foundAt = returnItem.hash(searchKey) % tableSize; return (dataTable[foundAt].retrieve(searchKey, returnItem)); } template <typename DataType, typename KeyType> void HashTable<DataType, KeyType>::clear() { for (int x = 0; x < tableSize; x++) { dataTable[x].clear(); } } template <typename DataType, typename KeyType> bool HashTable<DataType, KeyType>::isEmpty() const { bool emp = true; for (int x = 0; x < tableSize; x++) { if (!dataTable[x].isEmpty()) { emp = false; } } return emp; } template <typename DataType, typename KeyType> double HashTable<DataType, KeyType>::standardDeviation() const { double sum = 0, average = 0, num = 0, count = 0; for (int x = 0; x < tableSize; x++) { sum += dataTable[x].getCount(); } average = sum / tableSize; sum = 0; for (int x = 0; x < tableSize; x++) { count = dataTable[x].getCount(); num = pow((count - average), 2); sum += num; } num = sum / (tableSize - 1); return (sqrt(num)); } template <typename DataType, typename KeyType> void HashTable<DataType, KeyType>::copyTable(const HashTable& source) { for (int x = 0; x < tableSize; x++) { dataTable[x] = source[x]; } } template <typename DataType, typename KeyType> void HashTable<DataType, KeyType>::showStructure() const { for (int i = 0; i < tableSize; ++i) { cout << i << ": "; dataTable[i].writeKeys(); cout << endl; } }
true
e2b08eabdd947eab5e32bc019ba6a15482ca8fd8
C++
LhdDream/kiosk_key_value
/my_simple_storage/util/bloom_filter.h
UTF-8
2,115
2.921875
3
[]
no_license
#ifndef MY_SIMPLE_STORAGE_BLOOM_FILTER_H #define MY_SIMPLE_STORAGE_BLOOM_FILTER_H #include <vector> #include "hash.h" // this file create bloom // bloom 过滤器表示如果不在这个集合之中,则说明不在,在这个集合之后,实时不一定在这个集合之中 // bloom 参考leveldb 的实现方式来进行实现 class bloom { public: explicit bloom() : m_bits_per_key(0), m_h(0) { } void Add(const std::string& key, std::string& result_) { //每次调用写入一个key m_bits_per_key = key.size() * 8; //对齐,方便内存读写以及后续位置的索引 auto bytes = (m_bits_per_key + 7) / 8; m_bits_per_key = bytes * 8; //向下取整 result_.resize(bytes, 0); m_h = APHash(key.data()); auto delta = (m_h >> 17) | (m_h << 15); for (size_t j = 0; j < 4; j++) { // 在整个bit 数组的位置 auto bitpos = m_h % (m_bits_per_key); // 在char型数组的位置 result_[bitpos / 8] |= (1 << (bitpos % 8)); // 更新获得一个新的hash 数值 m_h += delta; } } bool Key_Match(const std::string& key, std::string& result_) { if (result_.empty()) { return false; } m_h = APHash(key.data()); auto delta = (m_h >> 17) | (m_h << 15); auto array = result_.data(); m_bits_per_key = key.size() * 8; //对齐,方便内存读写以及后续位置的索引 auto bytes = (m_bits_per_key + 7) / 8; m_bits_per_key = bytes * 8; for (size_t j = 0; j < 4; j++) { // 在整个bit 数组的位置 auto bitpos = m_h % (m_bits_per_key); // 在char型数组的位置 if ((array[bitpos / 8] & (1 << (bitpos % 8))) == 0) return false; // 更新获得一个新的hash 数值 m_h += delta; } return true; } private: size_t m_bits_per_key; //每一个key拥有的bit数目 // 一般为10 uint32_t m_h; }; #endif
true
bfd4683b20b2fb140c171f41e1a187defd7129eb
C++
MF1523017/interview
/nowcoder/offer/offerCoder0321/common/common/perfect_world.h
GB18030
1,385
3.296875
3
[]
no_license
#pragma once #if 0 //ڶ #include<iostream> #include<vector> #include<string> #include<sstream> #include<algorithm> using namespace std; vector<int> split(string &s, char flag = ' ') { vector<int> res; replace(s.begin(), s.end(), flag, ' '); int n; istringstream tmp(s); while (!tmp.eof()) { tmp >> n; if (n) res.push_back(n); } return res; } //int partion(vector<int> &nums,int) int main() { string input; getline(cin, input); vector<int>nums(split(input)); sort(nums.begin(), nums.end()); for (int i = 0; i<nums.size();) { int tmp = nums[i]; cout << tmp << " "; if (tmp == nums[i]) { while (tmp == nums[i])++i; } else ++i; } cout << endl; return 0; } #endif //һ #if 0 #include<iostream> #include<stack> #include<string> using namespace std; bool func(const string &str) { stack<char> st; for (int i = 0; i<str.size(); ++i) { if ('@' == str[i] || '#' == str[i] || '$' == str[i]) st.push(str[i]); else if ('&' == str[i] || '^' == str[i] || '%' == str[i]) { if (st.empty()) return false; char ch = st.top(); if ('@' == ch&&'&' == str[i]) st.pop(); else if ('#' == ch&&'^' == str[i]) st.pop(); else if ('$' == ch&&'%' == str[i]) st.pop(); } } return st.empty(); } int main() { string input; cin >> input; cout << func(input) << endl; return 0; } #endif
true
3ac925be2ec197171bbd55eb4358dfc1bdc72ac3
C++
a995049470/Zero
/LibMerge/BitHelp.h
UTF-8
315
3.140625
3
[]
no_license
#pragma once class BitHelp { public: static int GetTargetBit(int i, int pos) { int res = (i >> (pos - 1)) & 1; return res; } static void SetTargetBit(int& i, int pos, int value) { if (value == 1) { i = i | (1 << (pos - 1)); } else if (value == 0) { i = i & ~(1 << (pos - 1)); } } };
true
57245523d6727d1b27e3c0345e78b7ddf25e7c0d
C++
artdevar/Photo-editor
/src/Converter.cpp
UTF-8
1,559
3.078125
3
[]
no_license
#include "Converter.h" #include <algorithm> #include <cmath> #include <QtGlobal> void Converter::rgbToHsv(float r, float g, float b, float * h, float * s, float * v) { static const float modifier = 1.0f / 255.0f; r *= modifier; g *= modifier; b *= modifier; const std::initializer_list<float> list{r, g, b}; const float max = std::max(list); const float min = std::min(list); const float d = max - min; *v = max; *s = (qFuzzyIsNull(max) ? 0.0f : d / max); if (qFuzzyCompare(max, min)) { *h = 0.0f; } else { static const float divider = 1.0f / 6.0f; *h = divider * (qFuzzyCompare(max, r) ? (g - b) / d : qFuzzyCompare(max, g) ? (b - r) / d + 2.0f : qFuzzyCompare(max, b) ? (r - g) / d + 4.0f : 0.0f); } } void Converter::hsvToRgb(float * r, float * g, float * b, float h, float s, float v) { qint32 i = static_cast<qint32>(std::floor(h * 6.0f)); float f = h * 6.0f - i; float p = v * (1.0f - s); float q = v * (1.0f - f * s); float t = v * (1.0f - (1.0f - f) * s); switch (i % 6) { case 0: {*r = v; *g = t; *b = p;} break; case 1: {*r = q; *g = v; *b = p;} break; case 2: {*r = p; *g = v; *b = t;} break; case 3: {*r = p; *g = q; *b = v;} break; case 4: {*r = t; *g = p; *b = v;} break; case 5: {*r = v; *g = p; *b = q;} break; } static const float modifier = 255.0f; *r *= modifier; *g *= modifier; *b *= modifier; }
true
72aa9bbdfc8d8a8090f1d6dccb9b4c655bf8057d
C++
025georgialynny/code_ex
/pa3.cpp
UTF-8
423
3.09375
3
[]
no_license
#include <iostream> #include <iomanip> #include <string> #include <sstream> using namespace std; #include "largeIntegers.h" int main() { largeIntegers num1; largeIntegers num2; cin >> num1; cin >> num2; cout << "num1: " << num1 << endl; cout << "num2: " << num2 << endl; cout << "num1 + num2 = " << num1 + num2 << endl; cout << "num1 - num2 = " << num1 - num2 << endl; return 0; }
true
481c0393cb57df3deb6d71b84d7f32d6e1b4a930
C++
john-waczak/homeworkRepo
/cs_162/labs/lab6/application.cpp
UTF-8
692
3.0625
3
[]
no_license
#include <iostream> #include <string> #include "shape.h" #include "rectangle.h" #include "circle.h" #include "square.h" using namespace std; int main(){ Shape s1 = Shape("Box", "Blue"); cout << s1.get_name() << endl; cout << s1.get_color() << endl; cout << s1.area() << endl; Rectangle r1 = Rectangle(5.0, 6.0); cout << r1.get_name() << endl; cout << r1.get_color() << endl; cout << r1.area() << endl; Circle c1 = Circle(1.00); cout << c1.get_name() << endl; cout << c1.get_color() << endl; cout << c1.area() << endl; Square sq1 = Square(5.0); cout << sq1.get_name() << endl; cout << sq1.get_color() << endl; cout << sq1.area() << endl; return 0; }
true
bb0c6d6e794fe2ced9eff4f2058944481a0164e4
C++
king1991wbs/leetcode
/uniqueBST2.cpp
UTF-8
1,261
3.75
4
[]
no_license
/* Given n, generate all structurally unique BST's (binary search trees) that store values 1...n. For example, Given n = 3, your program should return all 5 unique BST's shown below. */ #include <iostream> #include <vector> #include <cstdlib> using namespace std; // Definition for binary tree struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: vector<TreeNode *> generateTrees(int n) { if( n < 1 ) return vector<TreeNode *>(1, NULL); return genBST(1, n); } private: vector<TreeNode *> genBST(int i, int j){ vector<TreeNode *> BST; if( i > j ){ BST.push_back(NULL); return BST; } for( int k = i; k <= j; k++){ vector<TreeNode *> left = genBST(i, k - 1); vector<TreeNode *> right = genBST(k + 1, j); for( auto iter1 = left.begin(); iter1 != left.end(); iter1++ ){ for( auto iter2 = right.begin(); iter2 != right.end(); iter2++ ){ TreeNode * node = new TreeNode(k); node->left = *iter1; node->right = *iter2; BST.push_back(node); } } } return BST; } }; int main( int argc, char *argv[] ){ Solution sol; sol.generateTrees( atoi(argv[1]) ); return 0; }
true
0d2c5b0b7e5d75c0f9b0b53bdb59c7e7ca382fe0
C++
qqdkg/data-structer_learning-demo
/Helper/OfferSword.h
GB18030
465
2.78125
3
[]
no_license
#pragma once // 2021-09-06_ָoffer // 3еظ // һΪn飬ÿһֶڷΧ0n-1֮䣬Ҫҵһظ class Prob_3_UniNum { public: // ʹʵּ򵥵Ĺϣ汾 // ʱ临ӶO(1) // ռ临ӶO(n) bool findUniNum_hash(int numbers[], int n, int& duplication); // void testUniNum( ); };
true
c7b33ebd74eac348ea903695585f82b83a05d69a
C++
yqian1991/codefactory
/program/WebSearch/main.c
UTF-8
5,047
2.640625
3
[]
no_license
#include <stdio.h> #include <windows.h> #include <wininet.h> #include <assert.h> #ifdef ERROR #undef ERROR #endif #define U8 unsigned char #define U32 unsigned int #define STATUS unsigned int #define OK 0 #define ERROR (~0L) #define MAX_BLOCK_SIZE 1024 #define MAX_DOMAIN_NAME_LENGTH 64 #define MAX_THREAD_NUMBER (8) #pragma comment(lib, "wininet.lib") static STATUS download_web_page(const char* url, const char* path); static int end = 0; static int front = 1; static HANDLE h_index; /* index to read html file */ static int get_read_index() { int index; WaitForSingleObject(h_index, INFINITE); if(end == front) { ReleaseSemaphore(h_index, 1, NULL); return -1; } index = end ++; ReleaseSemaphore(h_index, 1, NULL); return index; } /* index to write html file */ static int get_write_index() { int index; WaitForSingleObject(h_index, INFINITE); index = front ++; ReleaseSemaphore(h_index, 1, NULL); return index; } /* get length of html file */ static int get_file_size(const char* path) { HANDLE hFile; int size = 0; hFile = CreateFile(path, FILE_READ_EA, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0); if (hFile != INVALID_HANDLE_VALUE) { size = GetFileSize(hFile, NULL); CloseHandle(hFile); } return size; } /* get all data from html file */ static STATUS get_file_content(const char* path, void** pp_buffer, int* size) { int length; char* buffer; HANDLE hFile; if(NULL == path) { return ERROR; } if(NULL == pp_buffer) { return ERROR; } if(NULL == size) { return ERROR; } length = get_file_size(path); if(0 == length) { return ERROR; } buffer = (char*) malloc(length +1); if(NULL == buffer) { return ERROR; } buffer[length] = '\0'; hFile = fopen(path, "r+b"); if(NULL == hFile) { free(buffer); return ERROR; } fread(buffer, 1, length, hFile); fclose(hFile); *pp_buffer = buffer; *size = length; return OK; } /* show all http name, sometimes just for debug use */ static void print_http_name(const char* buffer, int size) { while(size --) { printf("%c", *buffer ++); } printf("\n"); } static void download_linked_page(const char* url, int size) { char* data; char name[64]; print_http_name(url, size); data = (char*)malloc(size + 1); if(NULL == data) { return; } data[size] = '\0'; memmove(data, url, size); memset(name, 0, 64); sprintf(name, "E:/download/%d.html", get_write_index()); download_web_page(data, name); /* free data memroy, which contained http domain name */ free(data); } /* get http form html file, then download it by its name*/ static void get_http_and_download(const char* buffer) { const char* prev; const char* next; char letter; int count; if(NULL == buffer) { return; } next = buffer; while(1) { next = strstr(next, "http://"); if(NULL == next) { break; } count = MAX_DOMAIN_NAME_LENGTH; prev = next; next += strlen("http://"); while(1) { if(!count) { break; } count --; letter = *next; if('"' == letter || '\'' == letter || ')' == letter || '>' == letter) { break; } next ++; } if(count) { download_linked_page(prev, next - prev); } } } /* implement page download */ static STATUS download_web_page(const char* url, const char* path) { U8 buffer[MAX_BLOCK_SIZE]; U32 iNumber; FILE* hFile; HINTERNET hSession; HINTERNET hUrl; STATUS result; hSession = InternetOpen("RookIE/1.0", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); if(NULL == hSession) { return ERROR; } hUrl = InternetOpenUrl(hSession, url, NULL, 0, INTERNET_FLAG_DONT_CACHE, 0); if(NULL == hUrl) { result = ERROR; goto error1; } hFile = fopen(path, "wb"); if(NULL == hFile) { result = ERROR; goto error2; } iNumber = 1; while(iNumber > 0) { InternetReadFile(hUrl, buffer, MAX_BLOCK_SIZE -1, &iNumber); fwrite(buffer, sizeof(char), iNumber, hFile); } fclose(hFile); result = OK; error2: InternetCloseHandle(hUrl); error1: InternetCloseHandle(hSession); return result; } /* download page and its linked pages */ DWORD WINAPI download_page_entry(LPVOID param) { char* buffer; int size; char name[64]; int index; while(1) { while( -1 == (index = get_read_index())) { Sleep(100); } memset(name, 0, 64); sprintf(name, "E:/download/%d.html", index); if(OK == get_file_content(name, &buffer, &size)) { get_http_and_download(buffer); free(buffer); } } } /* entry of programme */ int main(int argc, char* argv[]) { int index; HANDLE h_download[MAX_THREAD_NUMBER]; h_index = CreateSemaphore(NULL, 1, 1, NULL); if(NULL == h_index) { assert(0); } /* 0.html is just the start page */ download_web_page("http://book.dangdang.com", "E:/download/0.html"); for(index = 0; index < MAX_THREAD_NUMBER; index ++) { h_download[index] = CreateThread(NULL, 0, download_page_entry, 0, 0, NULL); if(NULL == h_download[index]) { assert(0); } } WaitForMultipleObjects(MAX_THREAD_NUMBER, h_download, TRUE, INFINITE); CloseHandle(h_index); return 1; }
true
747524bc4700b79e53962b6eb54f6ea00a8ae1a1
C++
lxyu0405/leetcode-pratice
/valid_perfect_square/Solution.cpp
UTF-8
656
3.3125
3
[]
no_license
#include <vector> #include <iostream> using namespace std; class Solution { public: bool isPerfectSquare(int num) { if (num == 1) { return true; } long long lowerBound = 1, upperBound = num; // binary search while (lowerBound < upperBound-1) { long long mid = (lowerBound + upperBound) >> 1; long long thisSquare = mid * mid; if (thisSquare < num) { lowerBound = mid; }else if (thisSquare > num){ upperBound = mid; }else{ return true; } } return false; } };
true
99953a32a0feb3bee21f361bc528ced208879dbd
C++
rodety/OpticalManager
/rangomedida.cpp
UTF-8
5,925
2.953125
3
[]
no_license
#include "rangomedida.h" #include <QDebug> #include <QSqlQueryModel> #include <QSqlRecord> #include <QSqlError> RangoMedida::RangoMedida(int _id,double _valorIni,double _valorFin, QString _descripcion) { id=_id; valorini=_valorIni; valorfin=_valorFin; descripcion = _descripcion; } RangoMedida::RangoMedida(double _valorIni,double _valorFin, QString _descripcion) { id=0; valorini=_valorIni; valorfin=_valorFin; descripcion = _descripcion; } RangoMedida::RangoMedida() { id=0; valorini=0; valorfin=0; descripcion=""; } //Constructo con solo tener el ID RangoMedida::RangoMedida(int _id) { QSqlQuery query; query.prepare("select * from rango_medida where idrango_medida="+QString::number(_id)); query.exec(); query.next(); id=_id; valorini=query.value(1).toDouble(); valorfin=query.value(2).toDouble(); descripcion=query.value(3).toString(); } /*-------------------------------------------------------------------- FUNCION PARA DEVOLVER OBJETOS EXISTENTE ---------------------------------------------------------------------*/ /** * @brief Retorna un Qlist de las RangoMedidas existentes * @return QList RangoMedidas */ QList<RangoMedida*> RangoMedida::listar() { QSqlQuery query; query.prepare("SELECT * FROM rango_medida"); query.exec(); QList<RangoMedida*> lista_resultado; while(query.next()) { int _id=query.value(0).toInt(); double _valorini=query.value(1).toDouble(); double _valorfin=query.value(2).toDouble(); QString _descripcion=query.value(3).toString(); RangoMedida* rangomedida=new RangoMedida(_id,_valorini,_valorfin, _descripcion); lista_resultado.push_back(rangomedida); } return lista_resultado; } /** * @brief Ingresando el nombre de la RangoMedida, puede verificar si esta en la base de datos * o no, en caso de que si este llena el objeto RangoMedida con los datos de la tabla * @return Bool si es exite return true, y si no exite return false */ /*-------------------------------------------------------------------- FUNCIONES GET'S Y SET'S ---------------------------------------------------------------------*/ /** * @brief Entrega el id de la RangoMedida * @return Int id */ int RangoMedida::getId() { return id; } /** * @brief Entrega el nombre de la RangoMedida * @return QString nombre */ QString RangoMedida::getdescripcion() { return descripcion; } /** * @brief Entrega el valor incial de la RangoMedida * @return QString nombre */ double RangoMedida::getValorInicial() { return valorini; } /** * @brief Entrega el valor final de la RangoMedida * @return QString nombre */ double RangoMedida::getValorFinal() { return valorfin; } /** * @brief Permitar cambiar el dato del id * @param Int _id que representa al nuevo id */ void RangoMedida::setId(int _id) { id=_id; } /** * @brief Permite cambiar el nombre de la RangoMedida * @param QString _nombre que representa el nuevo nombre */ void RangoMedida::setdescripcion(QString _descripcion) { descripcion=_descripcion; } /** * @brief Permitar cambiar el dato del valor Incial * @param Int _id que representa al nuevo id */ void RangoMedida::setValorIncial(double _valorIni) { valorini=_valorIni; } /** * @brief Permitar cambiar el dato del valor Final * @param Int _id que representa al nuevo id */ void RangoMedida::setValorFinal(double _valorFin) { valorfin=_valorFin; } /*-------------------------------------------------------------------- FUNCIONES DEL OBJETO PERSISTENTE ---------------------------------------------------------------------*/ /** * @brief Esta funcion ejecuta el agregar una nueva RangoMedida a la base de datos * @return Bool, el cual pede ser true o false dependiendo si la operacion * se concluyo exitosamente. */ bool RangoMedida::agregar() { if(descripcion!="") { QSqlQuery query; qDebug()<<"insertando"<<QString::number(valorini); qDebug()<<"insertando"<<QString::number(valorfin); query.prepare("INSERT INTO rango_medida (val_ini,val_fin,obs)" "VALUES (?,?,?)"); query.bindValue(0,valorini); query.bindValue(1,valorfin); query.bindValue(2,descripcion); if(query.exec()==true) { //Una muy buena soluciona alo que estaba haciendo, atento para la refactorizacion query.prepare("SELECT MAX(idrango_medida) FROM rango_medida"); query.exec(); query.next(); id=query.value(0).toInt(); return true; } else return false; } else return false; } /** * @brief Esta funcion ejecuta el actualizar una RangoMedida a la base de datos * @return Bool, el cual pede ser true o false dependiendo si la operacion * se concluyo exitosamente. */ bool RangoMedida::actualizar() { if(descripcion!="") { qDebug()<<"el id a cambiar dentro de rango de medida es "<<id; QSqlQuery query; QString que="UPDATE rango_medida SET obs= '"+descripcion+"' , val_ini="+QString::number(valorini)+" , val_fin="+QString::number(valorfin)+" WHERE idrango_medida="+ QString::number(id); qDebug()<<"senetecnia sql "<<que; query.prepare(que); return query.exec(); } else return false; } /** * @brief Esta funcion ejecuta el eliminar una RangoMedida a la base de datos * @return Bool, el cual pede ser true o false dependiendo si la operacion * se concluyo exitosamente. */ bool RangoMedida::eliminar() { if(descripcion!="") { QSqlQuery query; query.prepare("DELETE FROM rango_medida WHERE idrango_medida="+ QString::number(id)); return query.exec(); } else return false; }
true
39a859a4c554197f19ff32c0c9fe356d85043e4f
C++
IsAyka1/FuncLab
/FuncBdAndLabs/child.h
UTF-8
325
2.5625
3
[]
no_license
#pragma once #include "man.h" #include <string> class Child : public Man { private: bool m_IsTwins; public: Child(const std::string& in_FirstName, const std::string& in_LastName, const std::string& in_Partonymic, std::size_t in_Year, bool in_bGender, std::size_t in_Salary, bool in_IsTwins); bool IsTwins() const; };
true
59c1bb7fa88ff3e78b0ce3536ca755da4968b958
C++
conglb/Operating-System-lab
/multiprocessing/main.cpp
UTF-8
341
2.671875
3
[]
no_license
#include <stdio.h> #include <unistd.h> using namespace std; int main() { int value1, value2; // what happend if double fork() // we have 4 processes value1 = fork(); value2 = fork(); // print pid printf("In main: value1 = %d\n value2 = %d\n pid = %d, parent_pid = %d\n", value1, value2, getpid(), getppid()); return 0; }
true
634661106d84c3520bd7c77016678aa5057900b1
C++
liuyouzhao/kenan
/app/src/main/cpp/util/webgl/Int16Array.cpp
UTF-8
1,158
2.71875
3
[]
no_license
#include "Int16Array.h" #include "defines.h" #undef LOG_TAG #define LOG_TAG "Int16Array" namespace DCanvas { Int16Array* Int16Array::create(unsigned int length) { return ArrayType<short>::create<Int16Array>(length); } Int16Array* Int16Array::create(const short* array, unsigned int length) { return ArrayType<short>::create<Int16Array>(array, length); } Int16Array* Int16Array::create(ArrayBuffer* buffer, unsigned int byteOffset, unsigned int length) { return ArrayType<short>::create<Int16Array>(buffer, byteOffset, length); } Int16Array::Int16Array(ArrayBuffer* buffer, unsigned int byteOffset, unsigned int length) : ArrayType<short>(buffer, byteOffset, length) { } void Int16Array::set(unsigned int index, double value) { if (index > m_length) { LOGE("out of size error"); return; } data()[index] = value; } Int16Array* Int16Array::subarray(int start) const { return subarray(start, length()); } Int16Array* Int16Array::subarray(int start, int end) const { Int16Array* tmp = subarrayImpl<Int16Array>(start, end); tmp->m_isSubArray = true; return tmp; } } // namespace DCanvas
true
33ef89ceb391710084fe9e0ee579a077b176137d
C++
DuyTran1234/1000ExerciseC-
/Chuong 8 - Truu tuong hoa du lieu/bai577.cpp
UTF-8
703
3.078125
3
[]
no_license
#include <iostream> using namespace std; void nhap(struct hinhCau &a); void xuat(struct hinhCau a); double dienTichXQ(struct hinhCau a); struct hinhCau { int x; int y; int z; int r; }; int main() { hinhCau dcm; nhap(dcm); cout<<"Sxq = "<<dienTichXQ(dcm)<<endl; } void nhap(struct hinhCau &a) { cout<<"Nhap hoanh do tam hinh cau: "; cin>>a.x; cout<<"Nhap tung do tam hinh cau: "; cin>>a.y; cout<<"Nhap cao do tam hinh cau: "; cin>>a.z; cout<<"Nhap ban kinh hinh cau: "; cin>>a.r; } void xuat(struct hinhCau a) { cout<<"Hinh cau tam I("<<a.x<<","<<a.y<<","<<a.z<<") co R = "<<a.r<<endl; } double dienTichXQ(struct hinhCau a) { return 4*3.14*a.r*a.r; }
true
67229505ad13f4910c4f899bceb6aadf19db27f3
C++
Updownquark/DISEnumerations
/src/main/cpp/disenum/ModelType.cpp
UTF-8
1,565
3.28125
3
[ "BSD-2-Clause" ]
permissive
#include <sstream> #include <cstddef> #include <disenum/ModelType.h> namespace DIS { hashMap<int,ModelType*> ModelType::enumerations; ModelType ModelType::MISSING_DESCRIPTION(0, "Missing Description"); ModelType::ModelType(int value, std::string description) : Enumeration(value, description) { enumerations[value] = this; }; ModelType* ModelType::findEnumeration(int aVal) { ModelType* pEnum; enumContainer::iterator enumIter = enumerations.find(aVal); if (enumIter == enumerations.end()) pEnum = NULL; else pEnum = (*enumIter).second; return pEnum; }; std::string ModelType::getDescriptionForValue(int aVal) { ModelType* pEnum = findEnumeration(aVal); if (pEnum) return pEnum->description; else { std::stringstream ss; ss << "Invalid enumeration: " << aVal; return (ss.str()); } }; ModelType ModelType::getEnumerationForValue(int aVal) throw(EnumException) { ModelType* pEnum = findEnumeration(aVal); if (pEnum) return (*pEnum); else { std::stringstream ss; ss << "No enumeration found for value " << aVal << " of enumeration ModelType"; throw EnumException("ModelType", aVal, ss.str()); } }; bool ModelType::enumerationForValueExists(int aVal) { ModelType* pEnum = findEnumeration(aVal); if (pEnum) return (true); else return (false); }; ModelType::enumContainer ModelType::getEnumerations() { return (enumerations); }; ModelType& ModelType::operator=(const int& aVal) throw(EnumException) { (*this) = getEnumerationForValue(aVal); return (*this); }; } /* namespace DIS */
true
f3dfb73f3e23d3d51fd624d4217bd9048c4ffd93
C++
JooYoung1121/CodingTest_Algorithm
/리트코드/single_number.cpp
UTF-8
290
2.6875
3
[]
no_license
class Solution { public: int singleNumber(vector<int>& nums) { map<int,int> num_cnt; for(auto num : nums){ num_cnt[num]++; } for(auto nc : num_cnt){ if(nc.second == 1) return nc.first; } return 1; } };
true
d9182185a9b5417de99aa89e0968a66267327bcc
C++
silviavn10/Trabajo-de-Informatica
/XtremETSIDI/XtremETSIDI/src/ListaPlataformas.cpp
ISO-8859-1
1,339
3.28125
3
[]
no_license
#include "ListaPlataformas.h" ListaPlataformas::ListaPlataformas(void) { numero = 0; lista = new Plataformas * [MAX_PLATAFORMAS]; // reserva memoria dinmicamente para vector lista con una dimension maxima de MAX_PLATAFORMAS } void ListaPlataformas::Dibuja() { for (int i = 0; i < numero; i++) lista[i]->Dibuja(); } void ListaPlataformas::Color(unsigned char r, unsigned char v, unsigned char a) { for (int i = 0; i < numero; i++) lista[i]->SetColor(r, v, a); } void ListaPlataformas::DestruirContenido() { for (int i = 0; i < numero; i++) delete lista[i]; numero = 0; } Plataformas * ListaPlataformas::operator [](int i) { if (i >= numero) i = numero - 1; if (i < 0) i = 0; return lista[i]; } bool ListaPlataformas::Agregar(Plataformas* p) { for (int i = 0; i < numero; i++) if (lista[i] == p) { return false; } if (numero < MAX_PLATAFORMAS) lista[numero++] = p; else return false; return true; } bool ListaPlataformas::operator += (Plataformas* p) { if (numero < MAX_PLATAFORMAS) { lista[numero++] = p; //guarda la direccion return true; } return false; } void ListaPlataformas::Colision(Mueco& h) { for (int i = 0; i < numero; i++) Interaccion::Colision(h, *lista[i]); } void ListaPlataformas::Mueve(float f) { for (int i = 0; i < numero; i++) lista[i]->Mueve(f); }
true
0b7f28eeba041db52cb84be7c11f18d360112d6e
C++
wuli2496/OJ
/学习资料/ACM推荐书目/Competitve Programming 3, Steven Halim/Code/ch3/ch3_04_Max1DRangeSum.cpp
UTF-8
762
3.140625
3
[ "Apache-2.0" ]
permissive
#include <algorithm> #include <cstdio> using namespace std; int main() { int n = 9, A[] = { 4, -5, 4, -3, 4, 4, -4, 4, -5 }; // a sample array A int running_sum = 0, ans = 0; for (int i = 0; i < n; i++) // O(n) if (running_sum + A[i] >= 0) { // the overall running sum is still +ve running_sum += A[i]; ans = max(ans, running_sum); // keep the largest RSQ overall } else // the overall running sum is -ve, we greedily restart here running_sum = 0; // because starting from 0 is better for future // iterations than starting from -ve running sum printf("Max 1D Range Sum = %d\n", ans); // should be 9 } // return 0;
true
ba691b52440f68096ff01d527c07a06c6fc696f4
C++
ericgtkb/design-patterns
/C++/FactoryMethod/GuitarFactory/guitar_factory.cc
UTF-8
861
3.125
3
[]
no_license
#include "guitar_factory.h" std::unique_ptr<Guitar> GuitarFactory::get_guitar(const std::string& type) const { std::unique_ptr<Guitar> guitar {build_guitar(type)}; guitar->assemble(); guitar->string_the_guitar(); return std::move(guitar); } std::unique_ptr<Guitar> GibsonFactory::build_guitar(const std::string &type) const { if (type == "Les Paul") { return std::make_unique<GibsonLesPaul>(); } else if (type == "SG") { return std::make_unique<GibsonSG>(); } else { return nullptr; } } std::unique_ptr<Guitar> FenderFactory::build_guitar(const std::string &type) const { if (type == "Stratocaster") { return std::make_unique<FenderStratocaster>(); } else if (type == "Telecaster") { return std::make_unique<FenderTelecaster>(); } else { return nullptr; } }
true
a4816ec15bb577358c003f204e8a3f96a89a4c94
C++
williamrosser/CS2150
/Lab4/bitCounter.cpp
UTF-8
457
3.34375
3
[]
no_license
/*Maddie Stigler *mgs4ff *9/25/14 *bitCounter.cpp */ #include <cstdlib> #include <iostream> using namespace std; int bitCount(int n) { if(n == 1) { return 1; } return (n%2) + bitCount(n/2); } int main(int argc, char *argv[]) { if(argc == 0) { cout<< "I am going to exit gracefully..." <<endl; exit(-1); } int number = atoi(argv[1]); int ones = bitCount(number); cout <<"The number of 1 bits is: "<< ones <<endl; return 0; }
true
d981e5da7eba22b7c208782a494361e797f96f64
C++
sep-inc/campus_202009_matsui
/Minigame/Sor/Scene/Shougi/SyougiGameController.h
UTF-8
2,328
2.875
3
[]
no_license
#ifndef SYOUGI_GAMECONTROLLER_H_ #define SYOUGI_GAMECONTROLLER_H_ #include "Object/Player/SyougiPlayer.h" #include "Object/SyougiBoard.h" #include "Object/SyougiPiece.h" #include "Object/SyougiCursor.h" #include "../../Utility/Vec2.h" #include "../GameControllerBase.h" class SyougiGameController :public GameControllerBase { public: SyougiGameController(); ~SyougiGameController(); /** * @brief 初期化関数 * @detail メンバ変数の初期化 */ virtual void Reset()override; /** * @brief ステップ処理関数 * @detail ステップ変更処理 */ virtual void Update()override; /**  * @brief 更新関数 * @detail 各更新処理をまとめた関数  */ virtual void ObjectUpdate()override; /** * @brief 描画情報代入関数 * @detail 盤情報を描画配列に代入 */ virtual void SetUpDrawBuffer()override; /** * @brief ルール関数 * @detail ゲームのルールを表示する */ virtual void DrawRule()override; /** * @brief 勝敗判定関数 * @detail 先手か後手のどちらが勝ったかを判定する */ virtual void GameResult()override; /** * @brief 強制終了関数 * @detail ESCが押されたときにゲームを終了する */ //virtual bool GameEnd()override; /** * @brief シーン切り替え判定関数 * @detail ESCキーを押された時の処理を行う */ virtual void ChangeState()override; /** * @brief 解放処理関数 */ virtual void Delete()override; /** * @brief インスタンス返還関数 * @detail 管理クラスのポインタ配列に返す */ static GameControllerBase* InstanceSyougi(); /** * @brief  オブジェクトポインタ関数 * @detail オブジェクトのアドレスを返す */ SyougiBoard* GetBoradPoint() { return m_board; } SyougiCursor* GetCursorPoint() { return m_cursor; } public: //!ステップの種類 enum PLAYER_TURN { FIRST_TURN, //!先手の番 SECOND_TURN //!後手の番 }m_turn; void SetNextTurn(PLAYER_TURN turn_); private: SyougiPlayer* m_player[SYOUGI_PLAYER_NUM]; //!プレイヤー SyougiBoard* m_board; //!盤 SyougiPiece* m_piece[PIECE_NUM]; //!各駒 SyougiCursor* m_cursor; //!カーソル }; #endif
true
526dbebef609eb720c016c216956a68f5a9b6846
C++
tastest/CMS2
/NtupleMacros/WZRatio/Looper.h
UTF-8
6,898
2.609375
3
[]
no_license
// -*- C++ -*- #ifndef LOOPER_H #define LOOPER_H #include "Tools/LooperBase.h" #include "Math/LorentzVector.h" typedef ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double> > LorentzVector; // List of all cuts that can be applied. The cuts are handled as a // bitfield; these labels define which bit corresponds to which cut. // The cut are tested and the corresponding bits are set for each // - event in EventSelect() // - dilepton candidate in DilepSelect() // - trilepton candidate in TrilepSelect() // - quadlepton candidate in QuadlepSelect(). enum { CUT_MORE_THAN_TWO_TRACKS, CUT_NL, //no lepton CUT_E, //exactly one isolated e CUT_M, CUT_EE, //exactly two isolated es CUT_EM, CUT_MM, CUT_ML, //more than two isolated leptons CUT_OS, CUT_ZMASS, CUT_ANTI_ZMASS, CUT_MET, CUT_ANTI_MET, CUT_MT, //transverse mass }; //---------------------------------------------------------------------- // Cut combinations for selections. These are examples that are used // for various tables in the WW analysis. // ---------------------------------------------------------------------- // Note: some quick reminders for bitwise operations. // // - To turn the enum into a cut bit, use the CUT_BIT(x) function. // For example, to set the bit for CUT_LT_PT, use CUT_BIT(CUT_LT_PT). // // - Combine bits with the bitwise OR operator (|). For example, to // turn on the bits for CUT_LT_PT and CUT_LL_PT, use // CUT_BIT(CUT_LT_PT) | CUT_BIT(CUT_LL_PT). For another example, // making a new set of cuts that is the same as an existing set with // one cut added (the hypothetical CUT_EXTRA_CUT), use the // following: // cuts_t baseline_cuts_with_extra_cut = baseline_cuts | CUT_BIT(CUT_EXTRA_CUT); // // - To turn off a bit (useful when defining a set of cuts that is the // same as another set of cuts with one cut removed), use the // following: // cuts_t baseline_cuts_without_lt_pt = baseline_cuts & ~CUT_BIT(CUT_LT_PT); //single electron cuts const static cuts_t baseline_single_electron_cuts = // (CUT_BIT(CUT_MORE_THAN_TWO_TRACKS) ) | (CUT_BIT(CUT_E) ) | // (CUT_BIT(CUT_ANTI_ZMASS) ) | (CUT_BIT(CUT_MET) ) ; // (CUT_BIT(CUT_MT) ); //single muon cuts const static cuts_t baseline_single_muon_cuts = // (CUT_BIT(CUT_MORE_THAN_TWO_TRACKS) ) | (CUT_BIT(CUT_M) ) | // (CUT_BIT(CUT_ANTI_ZMASS) ) | (CUT_BIT(CUT_MET) ) ; // (CUT_BIT(CUT_MT) ); //dielectron cuts const static cuts_t baseline_dielectron_cuts = // (CUT_BIT(CUT_MORE_THAN_TWO_TRACKS) ) | (CUT_BIT(CUT_EE) ) | // (CUT_BIT(CUT_ZMASS) ) | // (CUT_BIT(CUT_ANTI_MET) ) | (CUT_BIT(CUT_OS) ); //dimuon cuts const static cuts_t baseline_dimuon_cuts = // (CUT_BIT(CUT_MORE_THAN_TWO_TRACKS) ) | (CUT_BIT(CUT_MM) ) | // (CUT_BIT(CUT_ZMASS) ) | // (CUT_BIT(CUT_ANTI_MET) ) | (CUT_BIT(CUT_OS) ); //EM cuts const static cuts_t baseline_emu_cuts = // (CUT_BIT(CUT_MORE_THAN_TWO_TRACKS) ) | (CUT_BIT(CUT_EM) ) | // (CUT_BIT(CUT_ZMASS) ) | // (CUT_BIT(CUT_ANTI_MET) ) | (CUT_BIT(CUT_OS) ); //---------------------------------------------------------------------- // Loopers //---------------------------------------------------------------------- // Looper for an analysis. // // - switching between files, removing duplicates and other technical stuff is handled by LooperBase // - analysis-specific stuff is defined here: // * declaring histograms and booking them // * naming cuts (using the enum from above) and checking which cuts are passed // * filling histograms // * counting passing candidates class Looper : public LooperBase { public: // constructor; tell the looper what sample to loop on (see // Tools/Sample.h), what cuts candidates need to pass, and a file // name for dumping log messages Looper (Sample, cuts_t cuts, const char *logfilename = 0); virtual ~Looper () { } protected: // this is where we book our histograms virtual void BookHistos (); // filter out this event. If FilterEvent returns true, no // further processing is done on this event virtual bool FilterEvent(); // we define an analysis-specific EventSelect(), DilepSelect(), // TrilepSelect() and QuadlepSelect() that check which cuts the // event, dilepton/trilepton/quadlepton candidate passes virtual cuts_t EventSelect (); virtual cuts_t DilepSelect (int idx); virtual cuts_t TrilepSelect (int idx); virtual cuts_t QuadlepSelect (int idx); // we define an analysis-specific set of FillEventHistos(), // FillDilepHistos(), FillTrilepHistos() and FillQuadlepHistos() // that fill our histograms. // // the framework calls our FillEventHistos() function for every event virtual void FillEventHistos (); // the framework calls our FillDilepHistos() function for every // dilepton candidate; the argument is the index of the candidate // in the dilepton block virtual void FillDilepHistos (int idx); // the framework calls our FillTrilepHistos() function for every // trilepton candidate; the argument is the index of the candidate // in the trilepton block virtual void FillTrilepHistos (int idx); // the framework calls our FillQuadlepHistos() function for every // quadlepton candidate; the argument is the index of the candidate // in the quadlepton block virtual void FillQuadlepHistos (int idx); // at the end of the loop, we get a callback to do things like // printing a status message virtual void End (); // variables static const int mu_shift = 0x8000000; enum Type {NL, E, M, EE, EM, MM, ML}; float wmt_; LorentzVector lep1; LorentzVector lep2; LorentzVector boson; LorentzVector wp4_; LorentzVector genp4_; public: // these functions are called by the table-printing code virtual double CandsPassing (enum DileptonHypType i) const { return cands_passing_[i]; } virtual int CandsCount (enum DileptonHypType i) const { return cands_count_[i]; } virtual double RMS (enum DileptonHypType i) const { return sqrt(cands_passing_w2_[i]); } protected: //---------------------------------------------------------------------- // declare your histograms here: //---------------------------------------------------------------------- // a simple TH1/TH2, times four to split by hypothesis type: TH1F *helPt_[4]; TH1F *hmuPt_[4]; TH2F *hCaloEtaPt_[4]; // NMinus1Hists take care of N - 1 plots and splitting by hypothesis automatically NMinus1Hist *hmt_; NMinus1Hist *hmet_; NMinus1Hist *hnjets_; NMinus1Hist *hnjptjets_; NMinus1Hist *hdilMass_; NMinus1Hist *hLepMetMass_; NMinus1Hist *hGenLepEta_; NMinus1Hist *hGenLepPt_; protected: // count the (weighted and unweighted) number of candidates passing our cuts double cands_passing_[4]; double cands_passing_w2_[4]; unsigned int cands_count_[4]; }; #endif
true
86ddbda03a67636fe582ca7b8854aca52b763a64
C++
hoangannguyen26/simple_interpreter
/include/parser.h
UTF-8
959
2.515625
3
[]
no_license
#ifndef PARSER_H #define PARSER_H #include "lexer.h" #include "nodevisitor.h" #include "Ast/ast.h" #include "Ast/literal.h" #include <string> #include <vector> class Parser { public: explicit Parser(const LexerPtr &lexer); ASTPtr parse(); private: bool m_exitFromBlock; const LexerPtr m_lexer; TokenPtr m_currentToken; TokenPtr m_LastToken; int m_currentTabLevel; ASTPtr error(); void eat(TokenType tokenType); ASTPtr factor(); ASTPtr term(); ASTPtr expr(); ASTPtr empty(); ASTPtr variable(); LiteralPtr literal(); ASTPtr assignment_statement(); ASTPtr statement(); ASTPtr block(); ASTPtr program(); ASTPtr type_spec(); ASTPtr variable_declaration(); ASTPtr print_statement(); int getTabLevel(); ASTPtr if_statement(); ASTPtr do_statement(); ASTPtr to_int(); ASTPtr to_string(); }; using ParserPtr = std::shared_ptr<Parser>; #endif // PARSER_H
true
dddfcc4cddf57a77c59d7b50653af30a63d5b2f6
C++
Heihuang/workspace
/3288/Shell/src/message/recvmessagemq.cpp
UTF-8
2,540
2.546875
3
[]
no_license
#include "recvmessagemq.h" #include <string> #include <vector> namespace rr { BaseRecvmessageMQ::BaseRecvmessageMQ() :consumer_(NULL), mqfactory_(NULL), thread_flag_(false), thread_id_(NULL), dev_id_(""), dev_update_(NULL) { } BaseRecvmessageMQ::~BaseRecvmessageMQ() { } void BaseRecvmessageMQ::CreateConsumer() { mqfactory_->CreateConsumerProc(&consumer_); } void BaseRecvmessageMQ::DestroyConsumer() { if (consumer_ && mqfactory_) { consumer_->Close(); mqfactory_->DestroyConsumerProc(consumer_); delete mqfactory_; mqfactory_ = NULL; } } void BaseRecvmessageMQ::setDevUpdate(const DeviceStatusUpdate* devupdate) { dev_update_ = const_cast<DeviceStatusUpdate*>(devupdate); } /*************************************************************************************************/ RecvRtmessageMQ::RecvRtmessageMQ() { mqfactory_ = new DeviceStatusUpdateRequestConsumerFactory(); if (mqfactory_ == NULL) { return; } CreateConsumer(); } RecvRtmessageMQ::~RecvRtmessageMQ() { DestroyConsumer(); } void RecvRtmessageMQ::RegisterMQ() { if (consumer_) { consumer_->RegUser(this); consumer_->RegCallBack(CBMessage); } } void RecvRtmessageMQ::RecvMsg(const std::string& devid) { if (dev_id_ != devid) { printf("d1=%s, d2=%s\n", dev_id_.c_str(), devid.c_str()); return; } if (dev_update_) { dev_update_->Update(); } } void __stdcall RecvRtmessageMQ::CBMessage(std::map<std::string, std::vector<unsigned char> > msg, void* user) { RecvRtmessageMQ* self = static_cast<RecvRtmessageMQ*>(user); if (self) { std::map<std::string, std::vector<unsigned char> >::iterator it = msg.begin(); std::string devid; while (it != msg.end()) { if (it->first == "DevID") { devid.assign(it->second.begin(), it->second.end()); } it++; } self->RecvMsg(devid); } } void* RecvRtmessageMQ::RecvThread(void* param) { RecvRtmessageMQ* self = static_cast<RecvRtmessageMQ*>(param); if (self) { self->Run(); } return 0; } void RecvRtmessageMQ::Start() { unsigned int id = 0; pthread_create(&thread_id_, NULL, RecvThread, this); printf("start RecvRtmessageMQ thread id=%d\n", id); } void RecvRtmessageMQ::Stop() { pthread_join(thread_id_, NULL); } void RecvRtmessageMQ::Run() { if (consumer_) { consumer_->run(); } printf("run quit!!!\n"); } }
true
ae26a82b5635bc13e6642844c4cc69c0cecd5723
C++
l3370x/byu-cs360-webserver-lx
/handler.cc
UTF-8
11,781
2.921875
3
[]
no_license
#include "handler.h" Handler::Handler(Config c, bool sD) { cfg = c; showDebug = sD; } Handler::~Handler() {} #define MAX_MSG_SZ 1024 // Determine if the character is whitespace bool isWhitespace(char c) { switch (c) { case '\r': case '\n': case ' ': case '\0': return true; default: return false; } } // Strip off whitespace characters from the end of the line void chomp(char *line) { int len = strlen(line); while (isWhitespace(line[len])) { line[len--] = '\0'; } } // Read the line one character at a time, looking for the CR // You dont want to read too far, or you will mess up the content char * GetLine(int fds) { char tline[MAX_MSG_SZ]; char *line; int messagesize = 0; int amtread = 0; while((amtread = read(fds, tline + messagesize, 1)) < MAX_MSG_SZ) { if (amtread > 0) messagesize += amtread; else { perror("Socket Error is:"); fprintf(stderr, "Read Failed on file descriptor %d messagesize = %d\n", fds, messagesize); exit(2); } //fprintf(stderr,"%d[%c]", messagesize,message[messagesize-1]); if (tline[messagesize - 1] == '\n') break; } tline[messagesize] = '\0'; chomp(tline); line = (char *)malloc((strlen(tline) + 1) * sizeof(char)); strcpy(line, tline); //fprintf(stderr, "GetLine: [%s]\n", line); return line; } // Change to upper case and replace with underlines for CGI scripts string UpcaseAndReplaceDashWithUnderline(string s) { //std::string s char *a=new char[s.size()+1]; a[s.size()]=0; memcpy(a,s.c_str(),s.size()); int i; char *ss; ss = a; for (i = 0; ss[i] != ':'; i++) { if (ss[i] >= 'a' && ss[i] <= 'z') ss[i] = 'A' + (ss[i] - 'a'); if (ss[i] == '-') ss[i] = '_'; } return a; } // When calling CGI scripts, you will have to convert header strings // before inserting them into the environment. This routine does most // of the conversion string FormatHeader(string str, char *prefix) { string result; string value = str.substr(str.find_first_of(':',0) + 2,str.length()); string next = UpcaseAndReplaceDashWithUnderline(str); next = next.substr(0,next.find_first_of(':',0)); result = prefix + next + "=" + value; return result; } std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while(std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; return split(s, delim, elems); } // Get the header lines from a socket // envformat = true when getting a request from a web client // envformat = false when getting lines from a CGI program void GetHeaderLines(vector<string> &headerLines, HTTPRequest req, bool envformat) { // Read the headers, look for specific ones that may change our responseCode char *line; char *tline; string heads = req.pstr(); vector<string> headsV = split(heads,'\n'); vector<string>::iterator it = headsV.begin(); it = it + 1; for (; it != headsV.end() ; it++) { string theHead = FormatHeader((*it),"HTTP_"); cout << "\tYour vector of headsV contains: " << theHead << endl; } } //************************************ //Handle input // //************************************ bool Handler::handle(int client, ClientData * cd) { this->cd = cd; // read a request memset(buf_,0,1501); int nread = recv(client,buf_,1500,0); if (nread < 0) { if (errno == EINTR) // the socket call was interrupted -- try again return true; // an error occurred so stop processing perror("recv"); return false; } else if (nread == 0) { // the socket is closed return false; } string received = buf_; cd->recv(client,received); return checkBuffer(client); } //********************************************** //CHECK A CLIENT'S BUFFER AND SEE IF THERE ARE //ANY /R/N/R/N AND THEN PARSE MESSAGE IF SO // //********************************************** bool Handler::checkBuffer(int client){ //check for /r/n/r/n Client * c = cd->getClient(client); int found = 0; if(c != NULL){ found = c->buffer.find("\r\n\r\n"); } if(found != string::npos){ return parseBuffer(client,found, c); } //no /r/n/r/n was found so wait for more return true; } //********************************************** //PARSE A CLIENT'S BUFFER BECAUSE A /R/N/R/N WAS //FOUND // //********************************************** bool Handler::parseBuffer(int client,int found, Client *c){ bool head = false; string received = c->buffer.substr(0,found+4); //clear the message off the client's buffer c->buffer = c->buffer.substr(found+4); //parse request HTTPRequest req; req.parse(received); if(req.uri().substr(req.uri().length()-3,req.uri().length()).compare("ico") == 0) { if(showDebug) cout << "HIDING ICO INFO" << endl; return false; } //create response HTTPResponse resp; resp.code("200"); resp.phrase("OK"); resp.header("Date",UsefulFunctions::getDate()); resp.header("Server","l3370x"); if(showDebug){ cout<< "Buffer=\"" << received << "\"" << endl; } if(received.compare(0,3,"GET") != 0){ if(received.compare(0,4,"HEAD") != 0){ resp.code("501"); resp.phrase("Not Implemented"); return doResponse(resp,client); } else head = true; } //is a valid GET or HEAD request. //now get the file path requested string path; string host = req.header("Host"); host = host.substr(0,host.find_first_of(":")); host = "default"; path += cfg.host(host); if(cfg.host(host).length() == 0 || req.uri().length() == 0){ resp.code("400"); resp.phrase("Bad Request"); return doResponse(resp,client); } if(req.uri().compare("/") == 0){ path += "/index.html"; } else { path += req.uri(); } if(showDebug) cout << "the parsed path is :" << path << endl; //check file permissions int fdOut; fdOut = open(path.c_str(),O_RDONLY); if(fdOut < 0){ if(errno == EACCES){ resp.code("403"); resp.phrase("Forbidden"); return doResponse(resp,client); } if(errno == ENOENT){ resp.code("404"); resp.phrase("Not Found"); return doResponse(resp,client); } resp.code("500"); resp.phrase("Internal Server Error"); perror("open"); return doResponse(resp,client); } //check content length and last accessed struct stat attrib; stat(path.c_str(), &attrib); int contLength = attrib.st_size; bool isDir = false; string theDirs = ""; if(attrib.st_mode & S_IFDIR != 0) { isDir = true; if(showDebug) cout << "\n\n!!!!!!!!!!!!DIRECTORY FOUND!!!!!!!!!!!!!!!!\n" << endl; DIR *dirp; struct dirent *dp; dirp = opendir(path.c_str()); theDirs += "<html><body><h1>Index of localhost"; theDirs += req.uri(); theDirs += "</h1><hr><table><tr><td>Name</td><td>Size</td><td>Modified</td></tr>"; while ((dp = readdir(dirp)) != NULL) { string name = dp->d_name; if (name == ".." || name == ".") continue; string pathD = path; pathD += "/"; pathD += name; if(showDebug) cout << "File inside path to check is " << pathD << endl; struct stat attribD; stat(pathD.c_str(), &attribD); int contLengthD = attribD.st_size; if(attribD.st_mode & S_IFDIR != 0) { contLengthD = -1; } theDirs += "<tr>"; theDirs += "<td><a href=\"" + req.uri() + "/" + name + "\">" + name + "</a></td><td>"; if(contLengthD > 0) theDirs += UsefulFunctions::convertInt(contLengthD); theDirs += "</td><td>"; theDirs += UsefulFunctions::date((attribD.st_mtime)); theDirs += "</td></tr>"; } theDirs += "</table><hr></body></html>"; } if(head) contLength = contLength-1; string lastMod = UsefulFunctions::date((attrib.st_mtime)); //check content type string responseType; string webType = path; if(webType.length() > 0) webType = webType.substr(webType.find_last_of(".") + 1); responseType = cfg.media(webType); if(responseType.length() == 0) responseType = "text/plain"; if(isDir) responseType = "text/html"; if(showDebug){ cout << "content length is: " << contLength << endl; cout << "last modification is: " << lastMod << endl; cout << "media type is: " << responseType << endl; } string CGIpath = ""; if (webType.compare("cgi") == 0) { CGIpath = path; if(showDebug) cout << "\n\nCGI FOUND, path will be: " << CGIpath << endl; } int rangeReqStart = 0; int rangeReqEnd = 0; bool range = false; if(req.header("Range").length() > 0){ range = true; string rng = req.header("Range"); rng = rng.substr(5,string::npos); string myrangeReqStart = rng.substr(1,rng.find_first_of("-")-1); string myrangeReqEnd = rng.substr(rng.find_first_of("-")+1,string::npos); rangeReqStart = atoi(myrangeReqStart.c_str()); rangeReqEnd = atoi(myrangeReqEnd.c_str()); if(showDebug){ cout << "range Start is " << rangeReqStart << endl; cout << "range End is " << rangeReqEnd << endl; } } if(range){ return doResponse(resp,client,head,fdOut,contLength,lastMod,responseType,range,rangeReqStart,rangeReqEnd); } return doResponse(resp,client,head,fdOut,contLength,lastMod,responseType,false,0,0,isDir,theDirs, CGIpath, req); } //********************************************** //DO A RESPONSE // //********************************************** bool Handler::doResponse(HTTPResponse resp, int client,bool head, int fdOut, int len , string mod, string type, bool range, int start, int end, bool isDir, string dirs, string CGIpath, HTTPRequest req){ if(showDebug) { cout << "\ndoing doResponse!" << endl; } const char *ptr; string rStr; if(resp.code().compare("400") == 0){ resp.header("Content-Length", my400ERROR.length()); rStr = resp.str(); rStr+=my400ERROR; } else if(resp.code().compare("501") == 0){ resp.header("Content-Length", my501ERROR.length()); rStr = resp.str(); rStr+=my501ERROR; } else if(resp.code().compare("500") == 0){ resp.header("Content-Length", my500ERROR.length()); rStr = resp.str(); rStr+=my500ERROR; } else if(resp.code().compare("403") == 0){ resp.header("Content-Length", my403ERROR.length()); rStr = resp.str(); rStr+=my403ERROR; } else if(resp.code().compare("404") == 0){ resp.header("Content-Length", my404ERROR.length()); rStr = resp.str(); rStr+=my404ERROR; } else if(fdOut > 0){ int realLen = (range == true) ? end - start + 1 : len; resp.header("Content-Length",UsefulFunctions::convertInt(realLen)); resp.header("Last-Modified",mod); resp.header("Content-Type",type); rStr = resp.str(); } if(CGIpath.length() > 0) { if(showDebug) cout << "CGI SCRIPT FOUND!!!!!!!!!" << endl; rStr = "HTTP/1.0 200 OK\r\nMIME-Version:1.0\r\n"; // ******************************************** cout << "LOOK AT LINES AFTER HERE!" << endl; std::vector<string> headerVector; GetHeaderLines(headerVector, req, true); // Read in the header lines, changing the format cout << "WAS THERE ANYTHING COOL??????" << endl; // ******************************************** } if(isDir) { resp.header("Content-Length",dirs.length()); rStr = resp.str(); rStr += dirs; } if(showDebug) cout << "Sending: " << rStr << endl; ptr = rStr.c_str(); int nwritten; int nleft = rStr.length(); while (nleft) { if ((nwritten = send(client, ptr, nleft, 0)) < 0) { if (errno == EINTR) { // the socket call was interrupted -- try again continue; } else { // an error occurred, so break out perror("send"); return false; } } else if (nwritten == 0) { // the socket is closed return false; } nleft -= nwritten; ptr += nwritten; } //Send file if(fdOut > 0){ if(!head){ if(range){ off_t offset; offset = start; sendfile(client,fdOut,&offset,end-start+1); }else { sendfile(client,fdOut,NULL,len); } } close(fdOut); } return true; }
true
3862a6455ccb190e5c74be5390afc65d4e4c8d30
C++
ArighnaIITG/Placement_Materials
/Binary Search/Fixed_Point.cpp
UTF-8
749
3.8125
4
[ "Apache-2.0" ]
permissive
/* Objective: Given a sorted array of distinct integers, Find the Magic index or Fixed point in the array. Magic Index or Fixed Point: Magic index or a Fixed point in an array is an index i in the array such that A[i] = i. Example : int[] A = { -1, 0, 1, 2, 4, 10 }; Magic index or fixed point is : 4 */ /* Solution approach is simple. Use simple binary search. Take l=0 and r=n-1. Find out mid. If arr[mid]==mid return `mid`, else if arr[mid] > mid, then make r = m-1, or else l =m+1. */ int fixedpoint(vector<int>& nums) { int n = nums.size(); int l=0, r=n-1; while(l<=r){ int mid = (l+r)>>1; if(nums[mid] == mid) return mid; else if(nums[mid] > mid) r=mid-1; else l=mid+1; } return -1; }
true
411a0757e66207672cbfdaa689f3c5ad89f36ce8
C++
BetaJester/binaryizer
/include/bj/binaryizer/traits_n_concepts.hpp
UTF-8
3,406
2.640625
3
[ "MIT" ]
permissive
// Copyright (C) 2021 Glenn Duncan <betajester@betajester.com> // See README.md, LICENSE, or go to https://github.com/BetaJester/binaryizer // for details. #pragma once #include <type_traits> #include <cstddef> #include "settings.hpp" namespace bj::inline v1{ class ibinaryizer; class obinaryizer; class iobinaryizer; enum class seekdir { begin, end, current, }; // How the crap isn't this supplied? template<typename T> concept boolean = std::is_same_v<T, bool>; template<typename T> concept arithmetic = std::is_arithmetic_v<T> && !boolean<T>; template<typename T> concept binaryizable_internal = requires(const T t, obinaryizer & b) { t.binaryize(b); }; template<typename T> concept binaryizable_external = requires(const T t, obinaryizer & b) { binaryize(b, t); }; template<typename T> concept debinaryizable_internal = requires(T t, ibinaryizer & b) { t.debinaryize(b); }; template<typename T> concept debinaryizable_external = requires(T t, ibinaryizer & b) { debinaryize(b, t); }; template<typename T> concept binaryizable = binaryizable_external<T> or binaryizable_internal<T>; template<typename T> concept debinaryizable = debinaryizable_external<T> or debinaryizable_internal<T>; template<typename T> concept debinaryizer_constructable = std::is_constructible_v<T, ibinaryizer &>; template<typename T> struct is_binaryizable : std::false_type {}; template<binaryizable T> struct is_binaryizable<T> : std::true_type {}; template<typename T> constexpr bool is_binaryizable_v = is_binaryizable<T>::value; template<typename T> struct is_debinaryizable : std::false_type {}; template<debinaryizable T> struct is_debinaryizable<T> : std::true_type {}; template<typename T> constexpr bool is_debinaryizable_v = is_debinaryizable<T>::value; template<typename T> concept arithmetic_native_out = arithmetic<T> && forced_endian_out == std::endian::native; template<typename T> concept arithmetic_not_raw_out = arithmetic<T> && forced_endian_out != std::endian::native; template<typename T> concept arithmetic_native_in = arithmetic<T> && forced_endian_in == std::endian::native; template<typename T> concept arithmetic_not_raw_in = arithmetic<T> && forced_endian_in != std::endian::native; template<typename T> concept not_raw_in = arithmetic_not_raw_in<T> || debinaryizable<T>; template<typename T> concept not_raw_out = arithmetic_not_raw_out<T> || binaryizable<T>; // Explicity raw output allowed. template<typename T> struct explicitly_raw : std::false_type {}; template<typename T> constexpr bool explicitly_raw_v = explicitly_raw<T>::value; template<typename T> concept explicity_raw_in = arithmetic_native_in<T> || explicitly_raw_v<T>; template<typename T> concept explicity_raw_out = arithmetic_native_out<T> || explicitly_raw_v<T>; // For buffered. template<typename T> concept ibufferable = requires(T t, std::byte * b, std::size_t s) { t.getraw(b, s); }; template<typename T> concept obufferable = requires(T t, const std::byte * b, std::size_t s) { t.putraw(b, s); }; //template<typename T> concept bufferable = ibufferable<T> || obufferable<T>; //template<typename T> concept iobufferable = ibufferable<T> && obufferable<T>; } // namespace bj::inline v1.
true
f8a16aafeea19b64814e1ef7446febba6a66cc2a
C++
liuq901/code
/Ural/ur_1024.cpp
UTF-8
557
2.734375
3
[]
no_license
#include <cstdio> #include <cstdlib> int a[1001]; int main() { int work(int),gcd(int,int); int n; scanf("%d",&n); for (int i=1;i<=n;i++) scanf("%d",&a[i]); int ans=1; for (int i=1;i<=n;i++) { if (!a[i]) continue; int len=work(i); ans=ans/gcd(ans,len)*len; } printf("%d\n",ans); system("pause"); return(0); } int work(int x) { int ans=0; while (x) { ans++; int t=a[x]; a[x]=0; x=t; } return(ans-1); } int gcd(int a,int b) { return(b?gcd(b,a%b):a); }
true
7ff9e6b38e2a35cbf030d018dd3cca00ea324a67
C++
kartiklakhotia/addonAHIR
/appSide_testCodes/pcie/pcie_speeds.cpp
UTF-8
2,393
2.609375
3
[]
no_license
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include "timer.h" #include <riffa.h> using namespace std; fpga_t * fpga; int beginSend = 0; int beginRecv = 0; int end = 0; int numWords = 8388608*2; void * sender_fxn(void *) { unsigned int * sendbuf; GET_TIME_INIT(2); sendbuf = (unsigned int *)malloc(numWords<<2); for (int i = 0; i<numWords; i++) { sendbuf[i] = i*2 + i%10; } cout << "reached here in TX" << endl; int sent; while(!beginRecv); beginSend = 1; GET_TIME_VAL(0); sent = fpga_send(fpga, 0,sendbuf, numWords, 0, 1, 2000); GET_TIME_VAL(1); if (1) { printf("Sent %d words, expecting %d. Exiting.\n", sent, numWords); end = 1; } for (int i=0; i<10; i++) { cout << "sent word " << i << " is "<< sendbuf[i] << endl; } printf("sending bw: %f MB/s %fms\n", sent*4.0/1024/1024/((TIME_VAL_TO_MS(1) - TIME_VAL_TO_MS(0))/1000.0), (TIME_VAL_TO_MS(1) - TIME_VAL_TO_MS(0)) ); while(!end); if (sendbuf != NULL) sendbuf = NULL; } void * receiver_fxn(void *) { unsigned int * recvbuf; GET_TIME_INIT(2); recvbuf = (unsigned int *)malloc((numWords)<<2); for (int i = 0; i<numWords; i++) { recvbuf[i] = 0; } int rc; cout << "reached here in rx" << endl; beginRecv = 1; while (!beginSend){;}; // Create the receive buffer GET_TIME_VAL(0); // Wait for the filtered data to come back. rc = fpga_recv(fpga, 0, recvbuf, numWords, 2000); GET_TIME_VAL(1); if (1) { printf("Received %d words, expecting %d. Exiting.\n", rc, numWords); } for (int i=0; i<10; i++) { cout << "received word " << i << " is " << recvbuf[i] << endl; } printf("recv bw: %f MB/s %fms\n", rc*4.0/1024/1024/((TIME_VAL_TO_MS(1) - TIME_VAL_TO_MS(0))/1000.0), (TIME_VAL_TO_MS(1) - TIME_VAL_TO_MS(0)) ); if (recvbuf != NULL) recvbuf = NULL; } int main( int argc, const char** argv ) { pthread_t sender; pthread_t receiver; if (argc<2) { fprintf(stderr, "supply fpga number. Format ./tb <index>\n"); return 1; } fpga = fpga_open(atoi(argv[1])); if(fpga == NULL) { cerr << "ERROR: Could not open FPGA " << atoi(argv[1]) << "!" << endl; return -1; } fpga_reset(fpga); pthread_create(&sender, NULL, sender_fxn, NULL); pthread_create(&receiver, NULL, receiver_fxn, NULL); pthread_join(sender, NULL); pthread_join(receiver, NULL); return 0; }
true
3e9dc543fa5ebf576f3415393ae0691b182824b0
C++
chrishickey/LCR
/LCR/tests/DGraphTest.cc
UTF-8
5,511
2.796875
3
[]
no_license
//#include "../../Graph/Graph.h" #include "../Graph/DGraph.cc" using namespace std; using namespace graphns; void test(bool a, int &testID) { if( a == true ) { cout << "testID=" << to_string(testID) << " passed" << endl; } else { cout << "testID=" << to_string(testID) << " failed" << endl; } testID++; } void allTests(Graph* mg, int& t) { std::cout << mg->toString(); test(mg->getNumberOfEdges() == 18, t); test(mg->getNumberOfVertices() == 13, t); test(mg->getNumberOfLabels() == 6, t); SmallEdgeSet edgeSet; mg->getOutNeighbours(0, edgeSet); test(edgeSet[0].first == 4, t); test(edgeSet[0].second == 1, t); test(edgeSet.size() == 1, t); mg->getOutNeighbours(9, edgeSet); test(edgeSet.size() == 2, t); test(edgeSet[0].first == 0 && edgeSet[1].first == 10, t); test(edgeSet[0].second == 1 && edgeSet[1].second == 1, t); mg->getInNeighbours(12, edgeSet); test(edgeSet[0].first == 10 && edgeSet[1].first == 11, t); test(edgeSet[0].second == 2 && edgeSet[1].second == 1, t); test(edgeSet.size() == 2, t); cout << "testing adding and removing nodes, edges and labels" << endl; mg->addNode(); test(mg->getNumberOfVertices() == 14, t); mg->removeNode(4); test(mg->getNumberOfVertices() == 13, t); mg->getOutNeighbours(4, edgeSet); test(edgeSet[0].first == 6, t); test(edgeSet.size() == 1, t); mg->addEdge(11, 12, 1); mg->addEdge(11, 0, 1); mg->getOutNeighbours(11, edgeSet); test(edgeSet.size() == 2, t); mg->removeEdge(11,0); mg->getOutNeighbours(11, edgeSet); test(edgeSet.size() == 1, t); mg->changeLabel(11, 12, 2); mg->getOutNeighbours(11, edgeSet); test(edgeSet[0].second == 4, t); } int main(int argc, char *argv[]) { string s = "tests/graphs/testGraph1.edge"; DGraph* mg = new DGraph(s); int t = 1; int L = mg->getNumberOfLabels(); allTests(mg, t); cout << "- testing DGraph addNode, addEdge, hasEdge, removeEdge, changeLabel" << endl; EdgeSet* es = new EdgeSet(); mg = new DGraph(es, 100, 8); mg->addNode(); mg->addNode(); mg->addNode(); mg->addNode(); mg->addNode(); mg->addEdge(0,1,0); mg->addEdge(0,2,0); mg->addEdge(0,3,0); mg->addEdge(0,4,0); mg->removeEdge(0,1); mg->removeEdge(0,4); test(mg->hasEdge(0,3) == true, t); test(mg->hasEdge(0,2) == true, t); test(mg->hasEdge(0,4) == false, t); test(mg->hasEdge(0,1) == false, t); mg->removeEdge(0,2); mg->removeEdge(0,3); test(mg->hasEdge(0,2) == false, t); mg = new DGraph(es, 100, 8, true); mg->addEdge(0,4,0); mg->addEdge(0,4,0); cout << "testing graphns methods" << endl; LabelSet ls1 = 0; LabelSet ls2 = 1; test(isLabelSubset(ls1,ls2) == true, t); //1 test(isLabelSubset(ls2,ls1) == false, t); //2 ls1 = 3; test(isLabelSubset(ls1,ls2) == false, t); //3 test(isLabelSubset(ls2,ls1) == true, t); //4 test(isLabelEqual(ls1,ls2) == false, t); //5 ls2 = 3; test(isLabelEqual(ls1,ls2) == true, t); //6 test(getUnsignedChar(ls1,0) == 3, t); //7 ls2 = 256; test(getUnsignedChar(ls2,0) == 0, t); //8 test(getUnsignedChar(ls2,1) == 1, t); // 9 ls2 = 255; test(getUnsignedChar(ls2,0) == 255, t); // 10 ls2 = 0; setUnsignedChar(ls2,0,245); test(ls2 == 245, t); ls2 = 0; setUnsignedChar(ls2,1,1); test(ls2 == 256, t); ls2 = 255; test(getNumberOfLabelsInLabelSet(ls2) == 8, t); ls2 = 3; test(getNumberOfLabelsInLabelSet(ls2) == 2, t); ls2 = 0; test(getNumberOfLabelsInLabelSet(ls2) == 0, t); cout << "- labelSetToLabelID tests" << endl; ls1 = 1; test(labelSetToLabelID(ls1) == 0, t); ls1 = 2; test(labelSetToLabelID(ls1) == 1, t); ls1 = 4; test(labelSetToLabelID(ls1) == 2, t); ls1 = 8; test(labelSetToLabelID(ls1) == 3, t); ls1 = 1; test(labelSetToLetter(ls1) == "a", t); ls1 = 2; test(labelSetToLetter(ls1) == "b", t); ls1 = 8; test(labelSetToLetter(ls1) == "d", t); ls1 = 1; test(invertLabelSet(ls1, 8) == 254, t); test(invertLabelSet(ls1, 8) == 1, t); test(labelIDToLabelSet(0) == 1, t); test(labelIDToLabelSet(2) == 4, t); test(labelIDToLabelSet(3) == 8, t); ls1 = 1; ls2 = 0; test(joinLabelSets(ls1,ls2) == 1, t); ls2 = 3; test(joinLabelSets(ls1,ls2) == 3, t); test(intersectLabelSets(ls1,ls2) == 1, t); ls1 = 3; ls2 = 3; test(getHammingDistance(ls1,ls2) == 0, t); ls1 = 0; ls1= setJoinFlag(ls1); test(hasJoinFlag(ls1) == true, t); //cout << "ls1=" << labelSetToString(ls1) << endl; ls1 = removeJoinFlag(ls1); test(hasJoinFlag(ls1) == false, t); //cout << "ls1=" << labelSetToString(ls1) << endl; cout << "stats tests" << endl; DGraph* g1 = new DGraph("tests/graphs/testGraph10.edge"); test(g1->computerNumberOfTriangles() == 2, t); //cout << "g1->computeClusterCoefficient()=" << g1->computeClusterCoefficient() << endl; vector< vector < VertexID > > sccs; g1 = new DGraph("tests/graphs/testGraph11.edge"); g1->tarjan(sccs); test( sccs.size() == 4, t); test(g1->computeDiameter() == 7, t); //cout << "diameter=" << g1->computeDiameter() << endl; s = "tests/graphs/verysmallgraph.edge"; g1 = new DGraph(s); test(g1->getGraphSizeInBytes() == 12*(sizeof(LabelSet)+sizeof(VertexID)), t ); return 0; }
true
5c26ab3463b1678f0a5dc767e0dcd288f93d1ad9
C++
Dorjsuren1015/Bodolgo
/tsifr_nemeh.cpp
UTF-8
330
2.828125
3
[]
no_license
#include <iostream> #include <vector> using namespace std; long long calc(long long n){ if (n < 10) return n; return calc(n%10 + calc(n / 10)); } int main() { long long n; while(true){ cin >> n; if (n == 0) exit(0); cout << calc(n) << endl; } return 0; }
true
443365f00afa66a19718af2961dedc64d1d6650a
C++
rlj1202/problemsolving
/baekjoon/1983_number_box/main.cpp
UTF-8
938
2.625
3
[]
no_license
#include <iostream> #include <algorithm> using namespace std; int N; int arr[2][402]; int zeros[2]; int dp[402][402][402]; int main() { scanf("%d", &N); for (int r = 0; r < 2; r++) { int zero = 0; for (int n = 1; n <= N; n++) { int cur; scanf("%d", &cur); if (cur == 0) zero++; else arr[r][n - zero] = cur; } zeros[r] = zero; } for (int n = 1; n <= N; n++) { for (int i = max(1, n - zeros[0]); i <= min(n, N - zeros[0]); i++) { for (int j = max(1, n - zeros[1]); j <= min(n, N - zeros[1]); j++) { int prevmax = dp[n - 1][i - 1][j - 1] + arr[0][i]*arr[1][j]; if (j > 1) prevmax = max(prevmax, dp[n - 1][i][j - 1]); if (i > 1) prevmax = max(prevmax, dp[n - 1][i - 1][j]); dp[n][i][j] = prevmax; printf("%d, %d %d = %d \t\t %d %d\n", n, i, j, dp[n][i][j], dp[n - 1][i][j - 1], dp[n - 1][i - 1][j]); } } } printf("%d\n", dp[N][N - zeros[0]][N - zeros[1]]); return 0; }
true
c697e090d1aeeee972aad7032b86dd17e87c9da4
C++
xuesongzh/cpp-basis
/3.类/04构造函数初始化列表.cpp
GB18030
1,430
3.890625
4
[ "Apache-2.0" ]
permissive
#include <cstdlib> #include <iostream> #include <string> #include <vector> using namespace std; class Time { private: int Hour; int Minute; int Second; public: explicit Time(int Hour, int Minute, int Second); Time(int Hour); }; Time::Time(int TemHour, int TemMinute, int TemSecond) : Hour(TemHour), Minute(TemMinute), Second(TemSecond) //ʽֵԱ { } Time::Time(int Hour) { this->Hour = Hour; } int main(void) { Time myTime01 = Time(12, 12, 12); system("pause"); return 0; } /* *(1)캯ʼб * 1.ֱڹ캯ʵУںб棺Աʼβα(ʼֵ),Աֵ2ʼβα2 * дִʱִ{}ǰʼִУԺʹù캯Աʼбʽġ * 2.ʹù캯ʼбʽʼбʽгʼд{}еĽиֵ(ڳʼʱǸֵ)д{} * ൱ڷ˳ʼϵͳһֵ * 3.ÿԱijʼ˳ϵͳ˳йأ빹캯ʼбд˳޹ء * *(2)ΪʲôҪ캯ʼб * 1.ʼȴһֵȻٸֵ * 2.Щֻʹóʼбķʽ */
true
d7f9fa0e874b1545de7f4cfe524dfc74b6cb3d25
C++
mysterypaint/Hmm2
/src/3ds/Graphics.cpp
UTF-8
13,271
2.609375
3
[ "MIT" ]
permissive
#include "Graphics.hpp" #include "../PHL.hpp" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "../Resources.hpp" PHL_Surface db = {0}; PHL_Surface backBuffer = {0}; PHL_Surface dbAlt = {0}; PHL_Surface backBufferAlt = {0}; const int cWidth = 320; const int cHeight = 240; Screen scrnTop = { GFX_TOP, GFX_LEFT, 400, 240 }; Screen scrnBottom = { GFX_BOTTOM, GFX_LEFT, cWidth, cHeight }; Screen* activeScreen = nullptr; // Where graphics get rendered to #ifdef _3DS Screen* debugScreen = nullptr; // Bottom screen console, for debugging (or swapping screen locations) #endif PHL_Rect offset; void PHL_GraphicsInit() { gfxInitDefault(); //Initialize console on top screen. Using NULL as the second argument tells the console library to use the internal console structure as current one //gfxSet3D(false); //consoleDebugInit(debugDevice_CONSOLE); activeScreen = &scrnBottom; debugScreen = &scrnTop; PHL_ResetDrawbuffer(); //Create background image backBuffer = PHL_NewSurface(cWidth * 2, cHeight * 2); dbAlt = PHL_NewSurface(cWidth * 2, cHeight * 2); backBufferAlt = PHL_NewSurface(cWidth * 2, cHeight * 2); } void PHL_GraphicsExit() { gfxExit(); } void PHL_StartDrawing() { PHL_ResetDrawbuffer(); gfxFlushBuffers(); } void PHL_EndDrawing() { PHL_DrawOtherScreen(); gfxSwapBuffers(); gspWaitForVBlank(); } void PHL_SetDrawbuffer(PHL_Surface surf) { db = surf; offset.w = db.width; offset.h = db.height; offset.x = 0; offset.y = 0; } void PHL_ResetDrawbuffer() { db.width = activeScreen->width; db.height = activeScreen->height; db.pxdata = gfxGetFramebuffer(activeScreen->screen, activeScreen->side, NULL, NULL); offset.w = cWidth; offset.h = cHeight; offset.x = (activeScreen->width - offset.w) / 2; offset.y = (activeScreen->height - offset.h) / 2; } PHL_RGB PHL_NewRGB(uint8_t r, uint8_t g, uint8_t b) { PHL_RGB c = { r, g, b }; return c; } void PHL_SetColorKey(PHL_Surface surf, uint8_t r, uint8_t g, uint8_t b) { PHL_RGB key = { r, g, b }; surf.colorKey = key; } PHL_Surface PHL_NewSurface(uint16_t w, uint16_t h) { PHL_Surface surf; surf.width = w / 2; surf.height = h / 2; surf.pxdata = (uint8_t *) malloc(surf.width * surf.height * 3 * sizeof(uint8_t)); surf.colorKey = PHL_NewRGB(0xFF, 0x00, 0xFF); return surf; } void PHL_FreeSurface(PHL_Surface surf) { if (surf.pxdata != NULL) { free(surf.pxdata); surf.pxdata = NULL; } } PHL_Surface PHL_LoadTexture(int _img_index) { PHL_Surface surf; std::string _f_in = "romfs:/graphics/"; int fileSize = 77880; // The default filesize, in bytes (because nearly all the graphics in the game are this size) switch(_img_index) { case sprPlayer: _f_in += "test_player.bmp"; fileSize = 12342; break; case sprTile0: _f_in += "tile0.bmp"; fileSize = 1142; break; case sprProt1: _f_in += "prot1.bmp"; break; case sprTitle: _f_in += "title.bmp"; break; case sprMapG00: _f_in += "mapg00.bmp"; break; case sprMapG01: _f_in += "mapg01.bmp"; break; case sprMapG02: _f_in += "mapg02.bmp"; break; case sprMapG03: _f_in += "mapg03.bmp"; break; case sprMapG04: _f_in += "mapg04.bmp"; break; case sprMapG05: _f_in += "mapg05.bmp"; break; case sprMapG06: _f_in += "mapg06.bmp"; break; case sprMapG07: _f_in += "mapg07.bmp"; break; case sprMapG08: _f_in += "mapg08.bmp"; break; case sprMapG09: _f_in += "mapg09.bmp"; break; case sprMapG10: _f_in += "mapg10.bmp"; break; case sprMapG11: _f_in += "mapg11.bmp"; break; case sprMapG12: _f_in += "mapg12.bmp"; break; case sprMapG13: _f_in += "mapg13.bmp"; break; case sprMapG14: _f_in += "mapg14.bmp"; break; case sprMapG15: _f_in += "mapg15.bmp"; break; case sprMapG16: _f_in += "mapg16.bmp"; break; case sprMapG17: _f_in += "mapg17.bmp"; break; case sprMapG18: _f_in += "mapg18.bmp"; break; case sprMapG19: _f_in += "mapg19.bmp"; break; case sprMapG20: _f_in += "mapg20.bmp"; break; case sprMapG21: _f_in += "mapg21.bmp"; break; case sprMapG22: _f_in += "mapg22.bmp"; break; case sprMapG31: _f_in += "mapg31.bmp"; break; case sprMapG32: _f_in += "mapg32.bmp"; break; default: fileSize = 77880; } FILE * f; if ((f = fopen(_f_in.c_str(), "rb"))) { //Save bmp data uint8_t* bmpFile = (uint8_t*) malloc(fileSize * sizeof(uint8_t)); fread(bmpFile, fileSize, 1, f); fclose(f); //Create surface uint16_t w, h; memcpy(&w, &bmpFile[18], 2); memcpy(&h, &bmpFile[22], 2); surf = PHL_NewSurface(w * 2, h * 2); //Load Palette PHL_RGB palette[20][18]; int count = 0; for (int dx = 0; dx < 20; dx++) { for (int dy = 0; dy < 16; dy++) { palette[dx][dy].b = bmpFile[54 + count]; palette[dx][dy].g = bmpFile[54 + count + 1]; palette[dx][dy].r = bmpFile[54 + count + 2]; count += 4; } } //Fill pixels count = 0; for (int dx = w; dx > 0; dx--) { for (int dy = 0; dy < h; dy++) { int pix = w - dx + w * dy; int px = bmpFile[1078 + pix] / 16; int py = bmpFile[1078 + pix] % 16; //Get transparency from first palette color if (dx == w &&dy == 0) surf.colorKey = palette[0][0]; PHL_RGB c = palette[px][py]; surf.pxdata[count] = c.b; surf.pxdata[count+1] = c.g; surf.pxdata[count+2] = c.r; count += 3; } } //Cleanup free(bmpFile); } return surf; } void PHL_DrawRect(int16_t x, int16_t y, uint16_t w, uint16_t h, PHL_RGB col) { // Everything is stored in memory at 2x size; Halve it for the 3ds port if (x < 0 || y < 0 || x+w > db.width || y+h > db.height) return; //Shrink values for small 3ds screen //x /= 2; //y /= 2; x += offset.x; y += offset.y; //w /= 2; //h /= 2; s16 x2 = x + w; s16 y2 = y + h; //Keep drawing within screen if (x < offset.x) { x = offset.x; } if (y < offset.y) { y = offset.y; } if (x2 > offset.x + offset.w) { x2 = offset.x + offset.w; } if (y2 > offset.y + offset.h) { y2 = offset.y + offset.h; } w = x2 - x; h = y2 - y; u32 p = ((db.height - h - y) + (x * db.height)) * 3; for (int i = 0; i < w; i++) { for (int a = 0; a < h; a++) { db.pxdata[p] = col.b; db.pxdata[p+1] = col.g; db.pxdata[p+2] = col.r; p += 3; } p += (db.height - h) * 3; } } void PHL_DrawSurface(int16_t x, int16_t y, PHL_Surface surf) { PHL_DrawSurfacePart(x, y, 0, 0, surf.width * 2, surf.height * 2, surf); } void PHL_DrawSurfacePart(int16_t x, int16_t y, int16_t cropx, int16_t cropy, int16_t cropw, int16_t croph, PHL_Surface surf) { if (surf.pxdata != NULL) { /* // Everything is stored in memory at 2x size; Halve it for the 3ds port x = (int) x / 2; y = (int) y / 2; cropx = cropx / 2; cropy = cropy / 2; cropw /= 2; croph /= 2; */ if (x > offset.w || y > offset.h || x + cropw < 0 || y + croph < 0) { //image is outside of screen, so don't bother drawing } else { //Crop pixels that are outside of screen if (x < 0) { cropx += -(x); cropw -= -(x); x = 0; } if (y < 0) { cropy += -(y); croph -= -(y); y = 0; } //3DS exclusive optimization /* //if (roomDarkness == 1) { //if (1) { int cornerX = 0;// (herox / 2) - 80; int cornerY = 0;// (heroy / 2) + 10 - 80; if (x < cornerX) { cropx += cornerX - x; cropw -= cornerX - x; x = cornerX; } if (y < cornerY) { cropy += cornerY - y; croph -= cornerY - y; y = cornerY; } if (x + cropw > cornerX + 160) { cropw -= (x + cropw) - (cornerX + 160); } if (y + croph > cornerY + 160) { croph -= (y + croph) - (cornerY + 160); } //}*/ if (x + cropw > offset.w) cropw -= (x + cropw) - (offset.w); if (y + croph > offset.h) croph -= (y + croph) - (offset.h); // Adjust the canvas' position based on the new offsets x += offset.x; y += offset.y; // Find the first color and pixel that we're dealing with before we update the rest of the canvas uint32_t p = ((offset.h - croph - y) + (x * offset.h)) * 3; uint32_t c = ((surf.height - cropy - croph) + surf.height * cropx) * 3; // Loop through every single pixel (draw columns from left to right, top to bottom) of the final output canvas and store the correct color at each pixel for (int i = 0; i < cropw; i++) { for (int a = 0; a < croph; a++) { if (surf.colorKey.r != surf.pxdata[c + 2] || surf.colorKey.g != surf.pxdata[c + 1] || surf.colorKey.b != surf.pxdata[c]) { // Only update this pixel's color if necessary db.pxdata[p] = surf.pxdata[c]; db.pxdata[p + 1] = surf.pxdata[c + 1]; db.pxdata[p + 2] = surf.pxdata[c + 2]; } c += 3; p += 3; } // Skip drawing for all of the columns of pixels that we've cropped out (one pixel = 3 bytes of data {r,g,b}) p += (offset.h - croph) * 3; c += (surf.height - croph) * 3; } } } } void PHL_DrawBackground(PHL_Background back, PHL_Background fore) { PHL_DrawSurface(0, 0, backBuffer); } void PHL_UpdateBackground(PHL_Background back, PHL_Background fore) { PHL_SetDrawbuffer(backBuffer); /* int xx, yy; for (yy = 0; yy < 12; yy++) { for (xx = 0; xx < 16; xx++) { //Draw Background tiles PHL_DrawSurfacePart(xx * 40, yy * 40, back.tileX[xx][yy] * 40, back.tileY[xx][yy] * 40, 40, 40, images[imgTiles]); //Only draw foreground tile if not a blank tile if (fore.tileX[xx][yy] != 0 || fore.tileY[xx][yy] != 0) { PHL_DrawSurfacePart(xx * 40, yy * 40, fore.tileX[xx][yy] * 40, fore.tileY[xx][yy] * 40, 40, 40, images[imgTiles]); } } } */ PHL_ResetDrawbuffer(); } //3DS exclusive. Changes which screen to draw on void swapScreen(gfxScreen_t screen, gfx3dSide_t side) { //Clear old screen PHL_StartDrawing(); PHL_DrawRect(0, 0, 640, 480, PHL_NewRGB(0, 0, 0)); PHL_EndDrawing(); PHL_StartDrawing(); PHL_DrawRect(0, 0, 640, 480, PHL_NewRGB(0, 0, 0)); PHL_EndDrawing(); if (screen == GFX_TOP) { activeScreen = &scrnTop; debugScreen = &scrnBottom; } else { activeScreen = &scrnBottom; debugScreen = &scrnTop; } PHL_ResetDrawbuffer(); } void PHL_DrawOtherScreen() { PHL_ResetAltDrawbuffer(); //printf(":wagu: :nodding: :nodding2: :slownod: :hypernodding: :wagu2: :oj100: :revolving_hearts: "); } void PHL_ResetAltDrawbuffer() { dbAlt.width = debugScreen->width; dbAlt.height = debugScreen->height; dbAlt.pxdata = gfxGetFramebuffer(debugScreen->screen, debugScreen->side, NULL, NULL); offset.w = cWidth; offset.h = cHeight; offset.x = (debugScreen->width - offset.w) / 2; offset.y = (debugScreen->height - offset.h) / 2; }
true
24cbfa096d74fe922d4a428055193e3d74101ef3
C++
Loner0822/DataAnalysis
/CalcUnit.cpp
UTF-8
5,886
2.515625
3
[]
no_license
#include "CalcUnit.h" CalcUnit::CalcUnit() { this->Calc_Id = 0; this->Const_str = ""; this->Const_Nums.clear(); } std::vector<int> Get_Bit_From_Input(long long value, int& pos, int& len) { std::vector<int> res; res.clear(); while (value) { res.push_back(value & 1); value >>= 1; } while (pos + 1 < len) pos += 8; while (res.size() <= pos) { res.push_back(0); } return res; } double CalcUnit::Calculate_Result(double input, const int& bit_len) { double res = 0; std::vector<int> bit_vec; bool have_val; int num_len, num_val, pos, e; double const_v, x, u, r, val1, val2; switch (Calc_Id) { case 7: // 补码 pos = Const_Nums[0], num_len = Const_Nums[1]; bit_vec = Get_Bit_From_Input(long long(input + 0.5), pos, num_len); if (bit_vec[pos] == 0) { for (int i = pos - 1; i > pos - num_len; --i) { res = res * 2 + bit_vec[i]; } } else { for (int i = pos - 1; i > pos - num_len; --i) { res = res * 2 + (1 - bit_vec[i]); } res = -res - 1; } break; case 8: // 多项式计算 num_len = int(Const_Nums[1] + 0.5); for (int i = Const_Nums.size() - 1; i >= Const_Nums.size() - num_len; --i) { res = res * input + Const_Nums[i]; } break; case 9: // 缓存 res = input; break; case 10: // 提取所需位 十进制显示 pos = Const_Nums[0], num_len = Const_Nums[1]; bit_vec = Get_Bit_From_Input(long long(input + 0.5), pos, num_len); for (int i = pos; i > pos - num_len; --i) { res = res * 2 + bit_vec[i]; } break; // A[0]*input+A[1] case 11: res = Const_Nums[0] * input + Const_Nums[1]; break; case 12: // 补码 pos = bit_len - 1, num_len = bit_len; bit_vec = Get_Bit_From_Input(long long(input + 0.5), pos, num_len); if (bit_vec[pos] == 0) { for (int i = pos - 1; i > pos - num_len; --i) { res = res * 2 + bit_vec[i]; } } else { for (int i = pos - 1; i > pos - num_len; --i) { res = res * 2 + (1 - bit_vec[i]); } res = -res - 1; } break; case 13: // IEEE 浮点 32位 pos = bit_len - 1, num_len = bit_len; bit_vec = Get_Bit_From_Input(long long(input + 0.5), pos, num_len); e = 0; for (int i = pos - 1; i >= pos - 8; --i) { e = e * 2 + bit_vec[i]; } have_val = 0; for (int i = 0; i <= pos - 9; ++i) { res = (res + bit_vec[i]) / 2.0; if (bit_vec[i]) have_val = 1; } switch (e) { case 0: res = res * pow(2, -128); break; case 255: if (have_val) { res = NAN; } else { res = INFINITY; } break; default: e -= 127; res = (res + 1) * pow(2, e); break; } if (bit_vec[pos] != 0) { res = -res; } break; case 14: // 补码 无符号 pos = bit_len - 1, num_len = bit_len; bit_vec = Get_Bit_From_Input(long long(input + 0.5), pos, num_len); if (bit_vec[pos] == 0) { for (int i = pos - 1; i > pos - num_len; --i) { res = res * 2 + bit_vec[i]; } } else { res = 1.0; for (int i = pos - 1; i > pos - num_len; --i) { res = res * 2 + (1 - bit_vec[i]); } res = res + 1; } break; case 20: // 补码 非符号位/2^(15) 再平方 pos = bit_len - 1, num_len = bit_len; bit_vec = Get_Bit_From_Input(long long(input + 0.5), pos, num_len); if (bit_vec[pos] == 0) { for (int i = pos - 1; i > pos - num_len; --i) { res = res * 2 + bit_vec[i]; } res = pow(res * pow(2, -15), 2); } else { for (int i = pos - 1; i > pos - num_len; --i) { res = res * 2 + (1 - bit_vec[i]); } res = -res - 1; res = -pow((-res) * pow(2, -15), 2); } break; case 22: // 积日 积秒 res = input; break; case 23: // input*A[0]^A[1] res = input * pow(Const_Nums[0], Const_Nums[1]); break; case 24: // 不用 res = input; break; case 26: // A[0]*ln(input) + A[1] res = Const_Nums[0] * log(input) + Const_Nums[1]; break; case 28: // 多项式计算 input = input * 3.3 / 255.0; for (int i = 0; i < Const_Nums.size(); ++i) { res = res * input + Const_Nums[i]; } break; case 29: // val1:A[0]~A[1]位 val2:A[2]~A[3]位 val1/10^(val2-A[4]) pos = Const_Nums[0], num_len = Const_Nums[1]; val1 = val2 = 0.0; bit_vec = Get_Bit_From_Input(long long(input + 0.5), pos, num_len); for (int i = pos; i > pos - num_len; --i) { val1 = val1 * 2 + bit_vec[i]; } pos = Const_Nums[2], num_len = Const_Nums[3]; for (int i = pos; i > pos - num_len; --i) { val2 = val2 * 2 + bit_vec[i]; } res = val1 / pow(10, val2 - Const_Nums[4]); break; case 50: // 附录四计算 const_v = Const_Nums[Const_Nums.size() - 1]; u = (input + 1) * 5 / 4096; x = u * 10000 / (const_v - u); res = (-172843.44828) / (-4622.53337 + sqrt(21367814.75677 - (-345686.89656 * (-6.01188 - log(x))))) - 273.15; break; case 51: // 附录四计算(带参数) const_v = Const_Nums[Const_Nums.size() - 1]; u = (input + 1) * 5 / 4096; x = u * 10000 / (const_v - u); res = (-Const_Nums[2]) / (-Const_Nums[3] + sqrt(Const_Nums[4] - (-Const_Nums[5] * (-Const_Nums[6] - log(x))))) - Const_Nums[7]; break; case 52: // 不用 res = input; break; case 53: // 多种公式 switch (int(Const_Nums[0] + 0.5)) { case 1: r = ((2.55 * input) / (4096.0 - input)) * 1000; res = -0.002174 * pow(r, 2) + 2.135 * r - 288.8; break; case 3: r = ((5.1 * input) / (4096.0 - input)) * 1000; res = -0.002174 * pow(r, 2) + 2.135 * r - 288.8; break; case 4: r = ((5.1 * input) / (4096.0 - input)) * 1000; res = 515.8 * pow(r, -0.1353) - 137.9; break; case 5: r = ((10 * input) / (4096.0 - input)) * 1000; res = 703.4 * pow(r, -0.1353) - 137.9; break; case 10: u = 5.0 * input / 256; r = log(5100 * u / (5 - u)); res = 2 * 1195.569 / (sqrt(2998.869 * 2998.869 - 4 * 1195.569 * (-3.15209 - r)) - 2998.869) - 273.15; break; default: res = input; break; } break; default: res = input; break; } return res; }
true
c34ba53a51dc4f43393c2854903800d71c8dc8d1
C++
lowkeyway/Algorithm
/02_List/myList.h
UTF-8
3,597
3.5625
4
[]
no_license
#ifndef __MY_LIST_H__ #define __MY_LIST_H__ #include <iostream> #include <string> #include "listNode.h" using namespace std; template <typename T> class myList { public: myList(int size); ~myList(); bool addTail(T &data); bool outHead(T &data); bool add(int index, T &data); bool out(int index, T &data); bool isEmpty(); bool isFull(); void listPrint(); private: listNode<T>* m_pHead; listNode<T>* m_pTail; int m_iListSize; int m_iListCapacity; }; template <typename T> myList<T>::myList(int size) { m_pHead = NULL; m_pTail = NULL; m_iListCapacity = size; m_iListSize = 0; } template <typename T> myList<T>::~myList() { m_pHead = NULL; m_pTail = NULL; m_iListCapacity = 0; m_iListSize = 0; } template <typename T> bool myList<T>::addTail(T &data) { if (isFull()) { cout << "The list is full, size is " << m_iListSize << endl; return -1; } listNode<T> *pNode = new listNode<T>(&data); if (isEmpty()) { cout << "Frist input" << endl; m_pHead = pNode; m_pTail = pNode; m_iListSize++; return 0; } pNode->m_pNext = m_pHead; pNode->m_pPre = m_pTail; m_pTail->m_pNext = pNode; m_pHead->m_pPre = pNode; m_pTail = pNode; m_iListSize++; return 0; } template <typename T> bool myList<T>::outHead(T &data) { if (isEmpty()) { cout << "The list is empty now!" << endl; return -1; } listNode<T> *temp; if (1 == m_iListSize) { data = *(m_pHead->m_pData); temp = m_pHead; delete temp; m_pHead = NULL; m_pTail = NULL; } else { m_pTail->m_pNext = m_pHead->m_pNext; m_pHead->m_pNext->m_pPre = m_pHead->m_pPre; data = *(m_pHead->m_pData); temp = m_pHead; m_pHead = m_pHead->m_pNext; delete temp; } m_iListSize--; return 0; } template <typename T> bool myList<T>::add(int index, T &data) { if (index > m_iListSize || index <= 0) { cout << "Your index is out of the range!" << endl; return -1; } if (isFull()) { cout << "The list is full, size is " << m_iListSize << endl; return -1; } listNode<T> *temp = m_pHead; listNode<T> *pNode = new listNode<T>(&data); if (isEmpty()) { cout << "Frist input" << endl; m_pHead = pNode; m_pTail = pNode; m_iListSize++; return 0; } if (index == m_iListSize) { addTail(data); return 0; } for(int i = 1; i < index; i++) { temp = temp->m_pNext; } pNode->m_pNext = temp->m_pNext; pNode->m_pPre = temp; temp->m_pNext->m_pPre = pNode; temp->m_pNext = pNode; m_iListSize++; return 0; } template <typename T> bool myList<T>::out(int index, T &data) { if (index > m_iListSize || index <= 0) { cout << "Your index is out of the range!" << endl; return -1; } if (isEmpty()) { cout << "The list is empty now!" << endl; return -1; } if (index == 1) { outHead(data); return 0; } if (index == m_iListSize) { m_pTail = m_pTail->m_pPre; } listNode<T> *temp = m_pHead; for (int i = 1; i < index; i++) { temp = temp->m_pNext; } data = *(temp->m_pData); temp->m_pPre->m_pNext = temp->m_pNext; temp->m_pNext->m_pPre = temp->m_pPre; delete temp; m_iListSize--; return 0; } template <typename T> bool myList<T>::isEmpty() { return m_iListSize == 0 ? true : false; } template <typename T> bool myList<T>::isFull() { return m_iListSize == m_iListCapacity ? true : false; } template <typename T> void myList<T>::listPrint() { if (isEmpty()) { cout << "The list is empty, please input element first." << endl; return; } listNode<T> *temp = m_pHead; for (int i = 0; i < m_iListSize; i++) { cout << *(temp->m_pData) << endl; temp = temp->m_pNext; } } #endif // !__MY_LIST_H__
true
806b3fe6ecd5bdc6e6abdff1a63c51481ce6437d
C++
r0mai/tungsten
/ut/eval/builtin/TableTest.cpp
UTF-8
15,618
2.765625
3
[]
no_license
#include <boost/test/unit_test.hpp> #include "Fixture.hpp" BOOST_AUTO_TEST_SUITE( TableTest ) using namespace tungsten; BOOST_FIXTURE_TEST_CASE( test_Table_of_x , BuiltinFunctionFixture ) { boost::optional<ast::Node> result = parseAndEvaluate("Table[x]"); BOOST_REQUIRE( result ); BOOST_CHECK_EQUAL( *result,ast::Node::make<ast::Identifier>("x") ); } BOOST_FIXTURE_TEST_CASE( test_build_a_table_out_of_x_for_x_ranging_from_1_to_4 , BuiltinFunctionFixture ) { boost::optional<ast::Node> result = parseAndEvaluate("Table[x, {x, 1, 4}]"); BOOST_REQUIRE( result ); BOOST_CHECK_EQUAL( *result,ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<math::Rational>(1), ast::Node::make<math::Rational>(2), ast::Node::make<math::Rational>(3), ast::Node::make<math::Rational>(4)}) ); } BOOST_FIXTURE_TEST_CASE( test_build_a_table_out_of_x_for_x_ranging_from_1_to_minus_4 , BuiltinFunctionFixture ) { boost::optional<ast::Node> result = parseAndEvaluate("Table[x, {x, 1, -4}]"); BOOST_REQUIRE( result ); BOOST_CHECK_EQUAL( *result,ast::Node::make<ast::FunctionCall>("List", {}) ); } BOOST_FIXTURE_TEST_CASE( test_build_a_table_out_of_x_for_x_ranging_from_1_to_5_in_increments_of_2 , BuiltinFunctionFixture ) { boost::optional<ast::Node> result = parseAndEvaluate("Table[x, {x, 1, 5, 2}]"); BOOST_REQUIRE( result ); BOOST_CHECK_EQUAL( *result,ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<math::Rational>(1), ast::Node::make<math::Rational>(3), ast::Node::make<math::Rational>(5)}) ); } BOOST_FIXTURE_TEST_CASE( test_build_a_table_out_of_x_for_x_ranging_from_1_to_6_in_increments_of_2 , BuiltinFunctionFixture ) { boost::optional<ast::Node> result = parseAndEvaluate("Table[x, {x, 1, 6, 2}]"); BOOST_REQUIRE( result ); BOOST_CHECK_EQUAL( *result,ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<math::Rational>(1), ast::Node::make<math::Rational>(3), ast::Node::make<math::Rational>(5)}) ); } BOOST_FIXTURE_TEST_CASE( test_build_a_table_out_of_x_for_x_ranging_from_1_to_6_in_increments_of_minus_2 , BuiltinFunctionFixture ) { boost::optional<ast::Node> result = parseAndEvaluate("Table[x, {x, 1, 6, -2}]"); BOOST_REQUIRE( result ); BOOST_CHECK_EQUAL( *result,ast::Node::make<ast::FunctionCall>("List", {}) ); } BOOST_FIXTURE_TEST_CASE( test_build_a_table_out_of_x_for_x_ranging_from_1_to_3 , BuiltinFunctionFixture ) { boost::optional<ast::Node> result = parseAndEvaluate("Table[x, {x, 3}]"); BOOST_REQUIRE( result ); BOOST_CHECK_EQUAL( *result,ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<math::Rational>(1), ast::Node::make<math::Rational>(2), ast::Node::make<math::Rational>(3)}) ); } BOOST_FIXTURE_TEST_CASE( test_build_a_table_out_of_x_iterated_3_times , BuiltinFunctionFixture ) { boost::optional<ast::Node> result = parseAndEvaluate("Table[x, {3}]"); BOOST_REQUIRE( result ); BOOST_CHECK_EQUAL( *result,ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<ast::Identifier>("x"), ast::Node::make<ast::Identifier>("x"), ast::Node::make<ast::Identifier>("x")}) ); } BOOST_FIXTURE_TEST_CASE( test_build_a_table_out_of_x_for_x_taking_the_values_a__b_and_c , BuiltinFunctionFixture ) { boost::optional<ast::Node> result = parseAndEvaluate("Table[x, {x, {a, b, c}}]"); BOOST_REQUIRE( result ); BOOST_CHECK_EQUAL( *result,ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<ast::Identifier>("a"), ast::Node::make<ast::Identifier>("b"), ast::Node::make<ast::Identifier>("c")}) ); } BOOST_FIXTURE_TEST_CASE( test_build_a_table_out_of_x_plus_y_for_y_ranging_from_1_to_5__then_for_x_ranging_from_1_to_4 , BuiltinFunctionFixture ) { boost::optional<ast::Node> result = parseAndEvaluate("Table[x + y, {x, 1, 4}, {y, 1, 5}]"); BOOST_REQUIRE( result ); BOOST_CHECK_EQUAL( *result,ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<math::Rational>(2), ast::Node::make<math::Rational>(3), ast::Node::make<math::Rational>(4), ast::Node::make<math::Rational>(5), ast::Node::make<math::Rational>(6)}), ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<math::Rational>(3), ast::Node::make<math::Rational>(4), ast::Node::make<math::Rational>(5), ast::Node::make<math::Rational>(6), ast::Node::make<math::Rational>(7)}), ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<math::Rational>(4), ast::Node::make<math::Rational>(5), ast::Node::make<math::Rational>(6), ast::Node::make<math::Rational>(7), ast::Node::make<math::Rational>(8)}), ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<math::Rational>(5), ast::Node::make<math::Rational>(6), ast::Node::make<math::Rational>(7), ast::Node::make<math::Rational>(8), ast::Node::make<math::Rational>(9)})}) ); } BOOST_FIXTURE_TEST_CASE( test_build_a_table_out_of_the_list_a__b_for_b_ranging_from_0_to_1__then_for_a_ranging_from_0_to_2 , BuiltinFunctionFixture ) { boost::optional<ast::Node> result = parseAndEvaluate("Table[{a, b}, {a, 0, 2}, {b, 0, 1}]"); BOOST_REQUIRE( result ); BOOST_CHECK_EQUAL( *result,ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<math::Rational>(0), ast::Node::make<math::Rational>(0)}), ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<math::Rational>(0), ast::Node::make<math::Rational>(1)})}), ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<math::Rational>(1), ast::Node::make<math::Rational>(0)}), ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<math::Rational>(1), ast::Node::make<math::Rational>(1)})}), ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<math::Rational>(2), ast::Node::make<math::Rational>(0)}), ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<math::Rational>(2), ast::Node::make<math::Rational>(1)})})}) ); } BOOST_FIXTURE_TEST_CASE( test_build_a_table_out_of_x_for_x_ranging_from_2_times_2_to_2_times_2_plus_2 , BuiltinFunctionFixture ) { boost::optional<ast::Node> result = parseAndEvaluate("Table[x, {x, 2*2, 2*2 + 2}]"); BOOST_REQUIRE( result ); BOOST_CHECK_EQUAL( *result,ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<math::Rational>(4), ast::Node::make<math::Rational>(5), ast::Node::make<math::Rational>(6)}) ); } BOOST_FIXTURE_TEST_CASE( test_build_a_table_out_of_x_for_x_ranging_from_1_to_2_times_2 , BuiltinFunctionFixture ) { boost::optional<ast::Node> result = parseAndEvaluate("Table[x, {x, 2*2}]"); BOOST_REQUIRE( result ); BOOST_CHECK_EQUAL( *result,ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<math::Rational>(1), ast::Node::make<math::Rational>(2), ast::Node::make<math::Rational>(3), ast::Node::make<math::Rational>(4)}) ); } BOOST_FIXTURE_TEST_CASE( test_build_a_table_out_of_x_for_x_taking_the_values_2_times_2_and_3_times_3 , BuiltinFunctionFixture ) { boost::optional<ast::Node> result = parseAndEvaluate("Table[x, {x, {2*2, 3*3}}]"); BOOST_REQUIRE( result ); BOOST_CHECK_EQUAL( *result,ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<math::Rational>(4), ast::Node::make<math::Rational>(9)}) ); } BOOST_FIXTURE_TEST_CASE( test_build_a_table_out_of_x_iterated_1_plus_1_times , BuiltinFunctionFixture ) { boost::optional<ast::Node> result = parseAndEvaluate("Table[x, {1 + 1}]"); BOOST_REQUIRE( result ); BOOST_CHECK_EQUAL( *result,ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<ast::Identifier>("x"), ast::Node::make<ast::Identifier>("x")}) ); } BOOST_FIXTURE_TEST_CASE( test_Table_of_x_and_the_list_the_list_1_plus_1__1_plus_1 , BuiltinFunctionFixture ) { boost::optional<ast::Node> result = parseAndEvaluate("Table[x, {{1 + 1, 1 + 1}}]"); BOOST_REQUIRE( result ); BOOST_CHECK_EQUAL( *result,ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<ast::Identifier>("x"), ast::Node::make<ast::Identifier>("x")}) ); } BOOST_FIXTURE_TEST_CASE( test_build_a_table_out_of_x_for_x_ranging_from_1_over_2_to_3_4, BuiltinFunctionFixture ) { boost::optional<ast::Node> result = parseAndEvaluate("Table[x, {x, 1/2, 3.4}]"); BOOST_REQUIRE( result ); ast::Node expected = ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<math::Rational>(1,2), ast::Node::make<math::Rational>(3,2), ast::Node::make<math::Rational>(5,2)}); BOOST_CHECK_EQUAL( *result, expected ); } BOOST_FIXTURE_TEST_CASE( test_build_a_table_out_of_x_for_x_ranging_from_1_over_2_to_Pi, BuiltinFunctionFixture ) { boost::optional<ast::Node> result = parseAndEvaluate("Table[x, {x, 1/2, Pi}]"); BOOST_REQUIRE( result ); ast::Node expected = ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<math::Rational>(1,2), ast::Node::make<math::Rational>(3,2), ast::Node::make<math::Rational>(5,2)}); BOOST_CHECK_EQUAL( *result, expected ); } BOOST_FIXTURE_TEST_CASE( test_build_a_table_out_of_x_for_x_ranging_from_1_over_2_to_5_6_in_increments_of_2, BuiltinFunctionFixture ) { boost::optional<ast::Node> result = parseAndEvaluate("Table[x, {x, 1/2, 5.6, 2}]"); BOOST_REQUIRE( result ); ast::Node expected = ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<math::Rational>(1,2), ast::Node::make<math::Rational>(5,2), ast::Node::make<math::Rational>(9,2)}); BOOST_CHECK_EQUAL( *result, expected ); } BOOST_FIXTURE_TEST_CASE( test_build_a_table_out_of_x_iterated_Pi_times, BuiltinFunctionFixture ) { boost::optional<ast::Node> result = parseAndEvaluate("Table[x, {Pi}]"); BOOST_REQUIRE( result ); ast::Node expected = ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<ast::Identifier>("x"), ast::Node::make<ast::Identifier>("x"), ast::Node::make<ast::Identifier>("x")}); BOOST_CHECK_EQUAL( *result, expected ); } BOOST_FIXTURE_TEST_CASE( test_x_equals_3_semicolon_build_a_table_out_of_x_iterated_x_times, BuiltinFunctionFixture ) { boost::optional<ast::Node> result = parseAndEvaluate("x = 3; Table[x, {x}]"); BOOST_REQUIRE( result ); ast::Node expected = ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<math::Rational>(3), ast::Node::make<math::Rational>(3), ast::Node::make<math::Rational>(3)}); BOOST_CHECK_EQUAL( *result, expected ); } BOOST_FIXTURE_TEST_CASE( test_build_a_table_out_of_x_for_x_ranging_from_a_to_b_in_increments_of_the_quantity_b_minus_a_over_2, BuiltinFunctionFixture ) { boost::optional<ast::Node> result = parseAndEvaluate("Table[x, {x, a, b, (b - a)/2}]"); BOOST_REQUIRE( result ); ast::Node expected = ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<ast::Identifier>("a"), ast::Node::make<ast::FunctionCall>("Plus", {ast::Node::make<ast::Identifier>("a"), ast::Node::make<ast::FunctionCall>("Times", {ast::Node::make<math::Rational>(1,2), ast::Node::make<ast::FunctionCall>("Plus", {ast::Node::make<ast::FunctionCall>("Times", {ast::Node::make<math::Rational>(-1), ast::Node::make<ast::Identifier>("a")}), ast::Node::make<ast::Identifier>("b")})}) }), ast::Node::make<ast::Identifier>("b")}); BOOST_CHECK_EQUAL( *result, expected ); } BOOST_FIXTURE_TEST_CASE( test_build_a_table_out_of_i_for_i_ranging_from_n_to_3_times_n_in_increments_of_n, BuiltinFunctionFixture ) { boost::optional<ast::Node> result = parseAndEvaluate("Table[i, {i, n, 3*n, n}]"); BOOST_REQUIRE( result ); ast::Node expected = ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<ast::Identifier>("n"), ast::Node::make<ast::FunctionCall>("Times", {ast::Node::make<math::Rational>(2), ast::Node::make<ast::Identifier>("n")}), ast::Node::make<ast::FunctionCall>("Times", {ast::Node::make<math::Rational>(3), ast::Node::make<ast::Identifier>("n")})}); BOOST_CHECK_EQUAL( *result, expected ); } BOOST_FIXTURE_TEST_CASE( test_build_a_table_out_of_i_for_i_ranging_from_1_to_Pi, BuiltinFunctionFixture ) { boost::optional<ast::Node> result = parseAndEvaluate("Table[i, {i, 1, Pi}]"); BOOST_REQUIRE( result ); ast::Node expected = ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<math::Rational>(1), ast::Node::make<math::Rational>(2), ast::Node::make<math::Rational>(3)}); BOOST_CHECK_EQUAL( *result, expected ); } BOOST_FIXTURE_TEST_CASE( test_build_a_table_out_of_i_for_i_ranging_from_1_to_8_in_increments_of_Pi, BuiltinFunctionFixture ) { boost::optional<ast::Node> result = parseAndEvaluate("Table[i, {i, 1, 8, Pi}]"); BOOST_REQUIRE( result ); ast::Node expected = ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<math::Rational>(1), ast::Node::make<ast::FunctionCall>("Plus", {ast::Node::make<math::Rational>(1), ast::Node::make<ast::Identifier>("Pi")}), ast::Node::make<ast::FunctionCall>("Plus", {ast::Node::make<math::Rational>(1), ast::Node::make<ast::FunctionCall>("Times", {ast::Node::make<math::Rational>(2), ast::Node::make<ast::Identifier>("Pi")})})}); BOOST_CHECK_EQUAL( *result, expected ); } BOOST_FIXTURE_TEST_CASE( test_build_a_list_of_values_from_1_to_10_with_step_2, BuiltinFunctionFixture ) { boost::optional<ast::Node> result = parseAndEvaluate("Range[1, 10, 2]"); BOOST_REQUIRE( result ); ast::Node expected = ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<math::Rational>(1), ast::Node::make<math::Rational>(3), ast::Node::make<math::Rational>(5), ast::Node::make<math::Rational>(7), ast::Node::make<math::Rational>(9)}); BOOST_CHECK_EQUAL( *result, expected ); } BOOST_FIXTURE_TEST_CASE( test_build_a_list_of_values_from_1_to_4, BuiltinFunctionFixture ) { boost::optional<ast::Node> result = parseAndEvaluate("Range[4]"); BOOST_REQUIRE( result ); ast::Node expected = ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<math::Rational>(1), ast::Node::make<math::Rational>(2), ast::Node::make<math::Rational>(3), ast::Node::make<math::Rational>(4)}); BOOST_CHECK_EQUAL( *result, expected ); } BOOST_FIXTURE_TEST_CASE( test_build_a_list_of_values_from_0_to_10_with_step_Pi, BuiltinFunctionFixture ) { boost::optional<ast::Node> result = parseAndEvaluate("Range[0, 10, Pi]"); BOOST_REQUIRE( result ); ast::Node expected = ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<math::Rational>(0), ast::Node::make<ast::Identifier>("Pi"), ast::Node::make<ast::FunctionCall>("Times", {ast::Node::make<math::Rational>(2), ast::Node::make<ast::Identifier>("Pi")}), ast::Node::make<ast::FunctionCall>("Times", {ast::Node::make<math::Rational>(3), ast::Node::make<ast::Identifier>("Pi")})}); BOOST_CHECK_EQUAL( *result, expected ); } BOOST_FIXTURE_TEST_CASE( test_build_a_list_of_values_from_0_to_3, BuiltinFunctionFixture ) { boost::optional<ast::Node> result = parseAndEvaluate("Range[0, 3]"); BOOST_REQUIRE( result ); ast::Node expected = ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<math::Rational>(0), ast::Node::make<math::Rational>(1), ast::Node::make<math::Rational>(2), ast::Node::make<math::Rational>(3)}); BOOST_CHECK_EQUAL( *result, expected ); } BOOST_FIXTURE_TEST_CASE( test_build_a_list_of_values_from_1_to_the_list_3__2, BuiltinFunctionFixture ) { boost::optional<ast::Node> result = parseAndEvaluate("Range[{3, 2}]"); BOOST_REQUIRE( result ); ast::Node expected = ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<math::Rational>(1), ast::Node::make<math::Rational>(2), ast::Node::make<math::Rational>(3)}), ast::Node::make<ast::FunctionCall>("List", {ast::Node::make<math::Rational>(1), ast::Node::make<math::Rational>(2)})}); BOOST_CHECK_EQUAL( *result, expected ); } BOOST_AUTO_TEST_SUITE_END()
true
a153fd7aba25b11c964028a9d711b626ca97fc20
C++
greenfox-zerda-sparta/nmate91
/week_08/12-15/03/03/03.cpp
UTF-8
439
3.625
4
[]
no_license
#include "stdafx.h" #include <iostream> #include <string> using namespace std; unsigned int power_function(unsigned int base, unsigned int n) { if (n == 0) { return 1; } return base * power_function(base, n - 1); } int main() { // Given base and n that are both 1 or more, compute recursively (no loops) // the value of base to the n power, so powerN(3, 2) is 9 (3 squared). cout << power_function(3, 4); return 0; }
true
821ac71494c2fa2626bcfcde6e288f2725dcf697
C++
et2372584/EdgarTrujilloSanchez_CSC17C_48942
/Hmwk/FinalStack/main.cpp
UTF-8
1,533
3.484375
3
[]
no_license
#include <iostream> #include <iomanip> #include <cmath> #include "Stack.h" using namespace std; //Function Prototypes float rSin(float, Stack &); float rCos(float, Stack &); void printLine(); const int SIZE = 5; int main() { ////Recursive sin/cos Stack stack1; cout<<"\n\n"; cout<<setw(42)<<"Problem 2 - Stacks\n"; //printLine(); cout<<"\n"; cout<<"|"<<setw(8)<<"Value |"<<setw(11)<<"Sin= |"<<setw(11)<<"Cos= |" <<setw(19)<<"Times called(sin) |"<<setw(19)<<" Times called(cos) |\n"; for(float val=-1; val<=1.1; val+=0.5) { float sinV=rSin(val, stack1); float cosV=rCos(val, stack1); int sinCounter=0; int cosCounter=0; while(!stack1.isEmpty()) { char fCall=stack1.pop(); if(fCall=='S') sinCounter++; else if(fCall=='C') cosCounter++; } printLine(); cout<<"|"<<setw(7)<<val<<"|"<<setw(10)<<sinV<<"|" <<setw(10)<<cosV<<"|"<<setw(18)<<sinCounter<<"|" <<setw(18)<<cosCounter<<" |\n"; } printLine(); cout<<"\n"; return 0; } float rSin(float angle, Stack &one) { char cSin='S'; one.push(cSin); float tol=1e-2; if(angle>-tol&&angle<tol)return angle-angle*angle*angle/6; return 2*rSin(angle/2,one)*rCos(angle/2,one); } float rCos(float angle, Stack &one) { char cCos='C'; one.push(cCos); float tol=1e-2; if(angle>-tol&&angle<tol)return 1-angle*angle/2+angle*angle*angle*angle/24; float cosv=rCos(angle/2,one); float sinv=rSin(angle/2,one); return cosv*cosv-sinv*sinv; } void printLine() { for(int i=1;i<36;i++) cout<<"--"; cout<<"\n"; }
true
93cdc7574639393855266ef6cee96115c5bec17a
C++
Seventeen1Gx/CodeUp
/1067-1093 入门数学/1090 互质问题思路探索.cpp
UTF-8
360
3.203125
3
[]
no_license
#include <stdio.h> int Judge(int a, int b); int main() { int n=1; while (n<51) { printf("%3d: ", n); for ( int i=1; i<n; i++ ) { if ( Judge(n, i) ) printf("%3d ", i); } printf("\n"); n++; } return 0; } int Judge(int a, int b) { int c; while ( b!=0 ) { c = a % b; a = b; b = c; } if (a==1) return 1; return 0; }
true
1c9356cf166c61ff226b846eafcebd6ef84d81fb
C++
Anthony-arias/CMPR131-Assignment4
/Assignment4/optionTwo.h
UTF-8
19,721
3.59375
4
[]
no_license
// optionTwo.h #ifndef OPTION_TWO_LOCK #define OPTION_TWO_LOCK #include <iostream> #include <string> #include "input.h" #include "Rational.h" using namespace std; void rational_numbers(); char displayMenuOptions(char& option); void option_A(); int option_A_menuOptions(int& option); void enterNumberator(Rational& R1); void enterDenominator(Rational& R1); void displayRationalNumber(Rational R1); void normalizeRationalNumber(Rational R1); void negateRationalNumber(Rational R1); void calculateRationalNumberWithConstant(Rational R1, int option); void option_B(); int option_B_menuOptions(int& option); void enterRationalNumber(Rational& number, int option); void verifyConditionOperators(Rational R1, Rational R2); void evaluateArithmaticOperators(Rational R1, Rational R2); void evaluateExpression(Rational R1, Rational R2); // Precondition: NA // Postcondition: display menu and instruction for rational number void rational_numbers() { do { cout << "\tA rational number is a number that can be written as a fraction, a/b, where a is numerator and\n"; cout << "\tb is denominator. Rational numbers are all real numbers, and can be positive or negative. A\n"; cout << "\tnumber that is not rational is called irrational. Most of the numbers that people use in everyday\n"; cout << "\tlife are rational.These include fractions, integers and numbers with finite decimal digits.\n"; cout << "\tIn general, a number that can be written as a fraction while it is in its own form is rational.\n"; char option = ' '; switch (displayMenuOptions(option)) { case '0': return; break; case 'A': option_A(); break; case 'B': option_B(); break; default: cout << "\n\tERROR-1A: Invalid input. Must be 'A','B', or '0'\n"; pause("\n\tPress enter to continue..."); clearScreen(); break; } } while (true); } // Precondition: NA // Postcondition: ask the user to choose the option char displayMenuOptions(char& option) { cout << "\n\t2> Rational Numbers"; cout << "\n\t" + string(60, char(205)); cout << "\n\t\tA> A Rational Number"; cout << "\n\t\tB> Multiple Rational Numbers"; cout << "\n\t" + string(60, char(196)); cout << "\n\t\t0> return"; cout << "\n\t" + string(60, char(205)); option = inputChar("\n\t\tOption: "); return toupper(option); } // Rational Number -> option A: A Rational Number -> functions to implement // Precondition: NA // Postcondition: display option A menu and tasks void option_A() { Rational R1; clearScreen(); do { int option; switch (option_A_menuOptions(option)) { case 0: clearScreen(); return; break; case 1: enterNumberator(R1); pause("\n\n\tPress enter to continue..."); clearScreen(); break; case 2: enterDenominator(R1); pause("\n\n\tPress enter to continue..."); clearScreen(); break; case 3: displayRationalNumber(R1); pause("\n\n\tPress enter to continue..."); clearScreen(); break; case 4: normalizeRationalNumber(R1); pause("\n\n\tPress enter to continue..."); clearScreen(); break; case 5: negateRationalNumber(R1); pause("\n\n\tPress enter to continue..."); clearScreen(); break; case 6: calculateRationalNumberWithConstant(R1, 1); pause("\n\n\tPress enter to continue..."); clearScreen(); break; case 7: calculateRationalNumberWithConstant(R1, 2); pause("\n\n\tPress enter to continue..."); clearScreen(); break; case 8: calculateRationalNumberWithConstant(R1, 3); pause("\n\n\tPress enter to continue..."); clearScreen(); break; case 9: calculateRationalNumberWithConstant(R1, 4); pause("\n\n\tPress enter to continue..."); clearScreen(); break; default: cout << "\n\tERROR-1A: Invalid input. Must be 1, 2, 3, 4, 5, 6, 7, 8, 9, or 0\n"; break; pause("\n\tPress enter to continue..."); clearScreen(); } } while (true); } // Precondition: Rational reference object // Postcondition: enter numerator for rational number void enterNumberator(Rational& R1) { int n = inputInteger("\n\tEnter an integer for the numerator: "); R1.setNumerator(n); } // Precondition: Rational reference object // Postcondition: enter denominator for rational number void enterDenominator(Rational& R1) { int d = inputInteger("\n\tEnter an integer for the denominator: "); R1.setDenominator(d); } // Precondition: Rational object // Postcondition: display rational number void displayRationalNumber(Rational R1) { if (!R1.isDenominatorValid(R1)) cout << "\n\tRational number R1 = " << R1 << " = undefined.\n"; else cout << "\n\tRational number R1 = " << R1; } // Precondition: Rational object // Postcondition: normalize rational number void normalizeRationalNumber(Rational R1) { Rational R2(R1); int n = R2.getNumerator(); int d = R2.getDenominator(); if (!R2.isDenominatorValid(R2)) { cout << "\tR2 = " << R2 << " = undefine."; cout << "\n\n\tThe rational number has zero denominator.\n"; } else { cout << "\n\tNormalized rational number R2 (a copy of R1)\n\n"; R2.simplify(n, d); cout << "\tR2 = " << R2; } } // Precondition: Rational object // Postcondition: negate rational number void negateRationalNumber(Rational R1) { Rational R2(R1); cout << "\n\tNegated rational number R2 (a copy of R1)\n\n"; int n = R2.getNumerator(); int d = R2.getDenominator(); if (!R2.isDenominatorValid(R2)) { cout << "\tR2 = " << R2 << " = undefine."; cout << "\n\tThe rational number has zero denominator.\n"; } else { R2.simplify(n, d); cout << "\tR2 = -(" << R2 << ") = "; if (n < 0 && d < 0) { cout << "-" << abs(n) << "/" << abs(d); } else if (n < 0 || d < 0) { cout << abs(n) << "/" << abs(d); } else if (n > 0) { cout << "-" << R2; } } } // Precondition: Rational object and valid option to proceed the calculation // Postcondition: Calculate rational number with constant depending on the assigned option void calculateRationalNumberWithConstant(Rational R1, int option) { if (option == 1) { Rational R2, R3; int number = inputInteger("\n\tEnter an integer value: "); R2.setNumerator(number); R2.setDenominator(1); if (!R1.isDenominatorValid(R1)) { cout << "\n\tR2 + value "; cout << "\n\n\t(" << R1 << ")" << " + " << number << " = undefined"; cout << "\n\n\tvalue + R2"; cout << "\n\n\t" << number << " + (" << R1 << ")" << " = undefined"; } else { R3 = R2 + R1; cout << "\n\tR2 + value "; cout << "\n\n\t(" << R1 << ")" << " + " << number << " = " << R3; cout << "\n\n\tvalue + R2"; cout << "\n\n\t" << number << " + (" << R1 << ")" << " = " << R3; } } else if (option == 2) { Rational R2, R3, R4; int number = inputInteger("\n\tEnter an integer value: "); R2.setNumerator(number); R2.setDenominator(1); if (!R1.isDenominatorValid(R1)) { cout << "\n\tR2 + value "; cout << "\n\n\t(" << R1 << ")" << " - " << number << " = undefined"; cout << "\n\n\tvalue + R2"; cout << "\n\n\t" << number << " - (" << R1 << ")" << " = undefined"; } else { R3 = R1 - R2; R4 = R2 - R1; cout << "\n\tR2 - value "; cout << "\n\n\t(" << R1 << ")" << " - " << number << " = " << R3; cout << "\n\n\tvalue - R2"; cout << "\n\n\t" << number << " - (" << R1 << ")" << " = " << R4; } } else if (option == 3) { Rational R2, R3; int number = inputInteger("\n\tEnter an integer value: "); R2.setNumerator(number); R2.setDenominator(1); if (!R1.isDenominatorValid(R1)) { cout << "\n\tR2 * value "; cout << "\n\n\t(" << R1 << ")" << " * " << number << " = undefined"; cout << "\n\n\tvalue * R2"; cout << "\n\n\t" << number << " * (" << R1 << ")" << " = undefined"; } else { R3 = R2 * R1; cout << "\n\tR2 * value "; cout << "\n\n\t(" << R1 << ")" << " * " << number << " = " << R3; cout << "\n\n\tvalue * R2"; cout << "\n\n\t" << number << " * (" << R1 << ")" << " = " << R3; } } else if (option == 4) { Rational R2, R3, R4; int number = inputInteger("\n\tEnter an integer value: "); R2.setNumerator(number); R2.setDenominator(1); if (!R1.isDenominatorValid(R1)) { cout << "\n\tR2 / value "; cout << "\n\n\t(" << R1 << ")" << " / " << number << " = undefined"; cout << "\n\n\tvalue / R2"; cout << "\n\n\t" << number << " / (" << R1 << ")" << " = undefined"; } else if ((!R1.isDenominatorValid(R1)) && number == 0) { cout << "\n\tR2 / value "; cout << "\n\n\t(" << R1 << ")" << " / " << number << " = undefined"; cout << "\n\n\tvalue / R2"; cout << "\n\n\t" << number << " / (" << R1 << ")" << " = undefined"; } else if (number == 0) { R4 = R2 / R1; cout << "\n\tR2 / value "; cout << "\n\n\t(" << R1 << ")" << " / " << number << " = undefined"; cout << "\n\n\tvalue / R2"; if (R1.getNumerator() == 0) cout << "\n\n\t" << number << " / (" << R1 << ")" << " = undefined"; else cout << "\n\n\t" << number << " / (" << R1 << ")" << " = 0"; } else { R3 = R1 / R2; R4 = R2 / R1; cout << "\n\tR2 / value "; cout << "\n\n\t(" << R1 << ")" << " / " << number << " = " << R3; cout << "\n\n\tvalue / R2"; cout << "\n\n\t" << number << " / (" << R1 << ")" << " = " << R4; } } } // Precondition: valid integer reference option // Postcondition: ask user to choose one option int option_A_menuOptions(int& option) { cout << "\n\tB> A Rational Number"; cout << "\n\t" + string(60, char(205)); cout << "\n\t\t1. Enter the numerator"; cout << "\n\t\t2. Enter the denominator"; cout << "\n\t\t3. Display the rational number"; cout << "\n\t\t4. Normalize the rational number"; cout << "\n\t\t5. Negate the rational number"; cout << "\n\t\t6. Add (+) the rational number with a constant"; cout << "\n\t\t7. Subtract (-) the rational number with a constant"; cout << "\n\t\t8. Multiply (*) the rational number with a constant"; cout << "\n\t\t9. Divide (/) the rational number with a constant"; cout << "\n\t" + string(60, char(196)); cout << "\n\t\t0. return"; cout << "\n\t" + string(60, char(205)); option = inputInteger("\n\t\tOption: ", 0, 9); return toupper(option); } // Rational Number -> option B: Multiple Rational Numbers -> functions to implement // Precondition: NA // Postcondition: display option B's menu and tasks void option_B() { Rational R1, R2; clearScreen(); do { int option; switch (option_B_menuOptions(option)) { case 0: clearScreen(); return; break; case 1: enterRationalNumber(R1, 1); pause("\n\n\tPress enter to continue..."); clearScreen(); break; case 2: enterRationalNumber(R2, 2); pause("\n\n\tPress enter to continue..."); clearScreen(); break; case 3: verifyConditionOperators(R1, R2); pause("\n\n\tPress enter to continue..."); clearScreen(); break; case 4: evaluateArithmaticOperators(R1, R2); pause("\n\n\tPress enter to continue..."); clearScreen(); break; case 5: evaluateExpression(R1, R2); pause("\n\n\tPress enter to continue..."); clearScreen(); break; default: cout << "\n\tERROR-1A: Invalid input. Must be 1, 2, 3, 4, 5 or 0\n"; break; pause("\n\tPress enter to continue..."); } } while (true); } // Precondition: Rational reference object and integer valid option // Postcondition: ask the user to input numerator and denominator for two different rational numbers void enterRationalNumber(Rational& number, int option) { if (option == 1) { int n1 = inputInteger("\n\tEnter the numerator for R1: "); number.setNumerator(n1); int d1 = inputInteger("\n\tEnter the denominator for R1: "); number.setDenominator(d1); if (!number.isDenominatorValid(number)) { cout << "\n\tR1 = " << number << " = undefined\n\n"; } else { number.simplify(n1, d1); cout << "\n\tR1 = " << number; } } else if (option == 2) { int n2 = inputInteger("\n\tEnter the numerator for R2: "); number.setNumerator(n2); int d2 = inputInteger("\n\tEnter the denominator for R2: "); number.setDenominator(d2); if (!number.isDenominatorValid(number)) { cout << "\n\tR2 = " << number << " = undefined"; } else { number.simplify(n2, d2); cout << "\n\tR2 = " << number; } } } // Precondition: two Rational objects // Postcondition: verify condition operators between two rational numbers void verifyConditionOperators(Rational R1, Rational R2) { bool status1 = R1 == R2; bool status2 = R1 != R2; bool status3 = R1 >= R2; bool status4 = R1 > R2; bool status5 = R1 <= R2; bool status6 = R1 < R2; cout << "\n\t\tR1 = " << R1 << " ; R2 = " << R2; if (!R1.isDenominatorValid(R1) && !R2.isDenominatorValid(R2)) { cout << "\n\n\t\tR1 == R2 -> (undefined) == (undefined) ? " << std::boolalpha << status1; cout << "\n\t\tR1 != R2 -> (undefined) != (undefined) ? " << std::boolalpha << status2; cout << "\n\t\tR1 >= R2 -> (undefined) >= (undefined) ? " << std::boolalpha << status3; cout << "\n\t\tR1 > R2 -> (undefined) > (undefined) ? " << std::boolalpha << status4; cout << "\n\t\tR1 <= R2 -> (undefined) <= (undefined) ? " << std::boolalpha << status5; cout << "\n\t\tR1 < R2 -> (undefined) < (undefined) ? " << std::boolalpha << status6; } else if (!R1.isDenominatorValid(R1) && R2.isDenominatorValid(R2)) { cout << "\n\n\t\tR1 == R2 -> (undefined) == (" << R2 << ") ? " << std::boolalpha << status1; cout << "\n\t\tR1 != R2 -> (undefined) != (" << R2 << ") ? " << std::boolalpha << status2; cout << "\n\t\tR1 >= R2 -> (undefined) >= (" << R2 << ") ? " << std::boolalpha << status3; cout << "\n\t\tR1 > R2 -> (undefined) > (" << R2 << ") ? " << std::boolalpha << status4; cout << "\n\t\tR1 <= R2 -> (undefined) <= (" << R2 << ") ? " << std::boolalpha << status5; cout << "\n\t\tR1 < R2 -> (undefined) < (" << R2 << ") ? " << std::boolalpha << status6; } else if (R1.isDenominatorValid(R1) && !R2.isDenominatorValid(R2)) { cout << "\n\n\t\tR1 == R2 -> (" << R1 << ") == (undefined) ? " << std::boolalpha << status1; cout << "\n\t\tR1 != R2 -> (" << R1 << ") != (undefined) ? " << std::boolalpha << status2; cout << "\n\t\tR1 >= R2 -> (" << R1 << ") >= (undefined) ? " << std::boolalpha << status3; cout << "\n\t\tR1 > R2 -> (" << R1 << ") > (undefined) ? " << std::boolalpha << status4; cout << "\n\t\tR1 <= R2 -> (" << R1 << ") <= (undefined) ? " << std::boolalpha << status5; cout << "\n\t\tR1 < R2 -> (" << R1 << ") < (undefined) ? " << std::boolalpha << status6; } else { cout << "\n\n\t\tR1 == R2 -> (" << R1 << ") == (" << R2 << ") ? " << std::boolalpha << status1; cout << "\n\t\tR1 != R2 -> (" << R1 << ") != (" << R2 << ") ? " << std::boolalpha << status2; cout << "\n\t\tR1 >= R2 -> (" << R1 << ") >= (" << R2 << ") ? " << std::boolalpha << status3; cout << "\n\t\tR1 > R2 -> (" << R1 << ") > (" << R2 << ") ? " << std::boolalpha << status4; cout << "\n\t\tR1 <= R2 -> (" << R1 << ") <= (" << R2 << ") ? " << std::boolalpha << status5; cout << "\n\t\tR1 < R2 -> (" << R1 << ") < (" << R2 << ") ? " << std::boolalpha << status6; } } // Precondition: two Rational objects // Postcondition: evaluate arithmatic operators between two rational numbers void evaluateArithmaticOperators(Rational R1, Rational R2) { Rational R3 = R1 + R2; Rational R4 = R2 - R1; Rational R5 = R1 * R2; Rational R6 = R2 / R1; cout << "\n\t\tR1 = " << R1 << " ; R2 = " << R2; if (!R1.isDenominatorValid(R1) && !R2.isDenominatorValid(R2)) { cout << "\n\n\t\tAddition\t: R1 + R2 -> (undefined) + (undefined) = undefined"; cout << "\n\t\tSubtraction\t: R2 - R1 -> (undefined) - (undefined) = undefined"; cout << "\n\t\tMultiplication\t: R1 * R2 -> (undefined) * (undefined) = undefined"; cout << "\n\t\tDivision\t: R2 / R1 -> (undefined) / (undefined) = undefined"; } else if (!R1.isDenominatorValid(R1) && R2.isDenominatorValid(R2)) { cout << "\n\n\t\tAddition\t: R1 + R2 -> (undefined) + (" << R2 << ") = undefined"; cout << "\n\t\tSubtraction\t: R2 - R1 -> (" << R2 << ") - (undefined) = undefined"; cout << "\n\t\tMultiplication\t: R1 * R2 -> (undefined) * (" << R2 << ") = undefined"; cout << "\n\t\tDivision\t: R2 / R1 -> (" << R2 << ") / (undefined) = undefined"; } else if (R1.isDenominatorValid(R1) && !R2.isDenominatorValid(R2)) { cout << "\n\n\t\tAddition\t: R1 + R2 -> (" << R1 << ") + (undefined) = undefined"; cout << "\n\t\tSubtraction\t: R2 - R1 -> (undefined) - (" << R1 << ") = undefined"; cout << "\n\t\tMultiplication\t: R1 * R2 -> (" << R1 << ") * (undefined) = undefined"; cout << "\n\t\tDivision\t: R2 / R1 -> (undefined) / (" << R1 << ") = undefined"; } else { R3.simplify(R3.getNumerator(), R3.getDenominator()); R4.simplify(R4.getNumerator(), R4.getDenominator()); R5.simplify(R5.getNumerator(), R5.getDenominator()); R6.simplify(R6.getNumerator(), R6.getDenominator()); cout << "\n\n\t\tAddition\t: R1 + R2 -> (" << R1 << ") + (" << R2 << ") = " << R3; cout << "\n\t\tSubtraction\t: R2 - R1 -> (" << R2 << ") - (" << R1 << ") = " << R4; cout << "\n\t\tMultiplication\t: R1 * R2 -> (" << R1 << ") * (" << R2 << ") = " << R5; if (R1.getNumerator() == 0) cout << "\n\t\tDivision\t: R2 / R1 -> (" << R2 << ") / (" << R1 << ") = undefined"; else cout << "\n\t\tDivision\t: R2 / R1 -> (" << R2 << ") / (" << R1 << ") = " << R6; } } // Precondition: two Rational objects // Postcondition: evaluate the indicated expression and show the steps void evaluateExpression(Rational R1, Rational R2) { Rational R3; R3.setNumerator(621); R3.setDenominator(889); Rational R4 = R1 + R2; Rational temp1; temp1.setNumerator(3); temp1.setDenominator(1); Rational R5 = R4 * temp1; Rational temp2; temp2.setNumerator(7); temp2.setDenominator(1); Rational numerator = R5 / temp2; Rational temp3; temp3.setNumerator(9); temp3.setDenominator(1); Rational R6 = R1 / temp3; Rational denominator = R2 - R6; Rational R7 = numerator / denominator; bool status = R7 >= R3; R4.simplify(R4.getNumerator(), R4.getDenominator()); R5.simplify(R5.getNumerator(), R5.getDenominator()); R6.simplify(R6.getNumerator(), R6.getDenominator()); R7.simplify(R7.getNumerator(), R7.getDenominator()); numerator.simplify(numerator.getNumerator(), numerator.getDenominator()); denominator.simplify(denominator.getNumerator(), denominator.getDenominator()); cout << "\n\t\t R1 = " << R1 << endl; cout << "\t\t R2 = " << R2 << endl; cout << "\t\t R3 = " << R3 << endl; cout << "\n\t\tEvaluating expression..." << endl; cout << "\t\t\t(3 * (R1 + R2) / 7) / (R2 - R1 / 9) >= (" << R3 << ") ? " << endl; cout << "\n\t\tStep #1: (3 * (" << R4 << ") / 7) / ((" << R2 << ") - (" << R6 << ")) >= (" << R3 << ") ? " << endl; cout << "\t\tStep #2: ((" << R5 << ") / 7) / (" << denominator << ") >= (" << R3 << ") ? " << endl; cout << "\t\tStep #3: (" << numerator << ") / (" << denominator << ") >= (" << R3 << ") ? " << endl; cout << "\t\tStep #4: (" << R7 << ") >= (" << R3 << ") ? " << endl; cout << "\t\tStep #5: " << std::boolalpha << status << endl; } // Precondition: valid integer reference option // Postcondition: ask user to choose one option int option_B_menuOptions(int& option) { cout << "\n\tB> Multiple Rational Numbers"; cout << "\n\t" + string(60, char(205)); cout << "\n\t\t1. Enter rational number R1"; cout << "\n\t\t2. Enter rational number R2"; cout << "\n\t\t3. Verify condition operators (==, !=, >=, >, <= and <) of R1 and R2"; cout << "\n\t\t4. Evaluate arithmatic operators (+, - , * and /) of R1 and R2"; cout << "\n\t\t5. Evaluate (3 * (R1 + R2) / 7) / (R2 - R1 / 9) >= 621/889"; cout << "\n\t" + string(60, char(196)); cout << "\n\t\t0. return"; cout << "\n\t" + string(60, char(205)); option = inputInteger("\n\t\tOption: ", 0, 5); return toupper(option); } #endif
true
7538c089e7033f03cd834d5d75724227159bbad9
C++
plmsmile/leetcode
/094_btree_in_order/btree_inorder.cpp
UTF-8
1,003
3.765625
4
[]
no_license
/* * 二叉树中序遍历 * https://leetcode.com/problems/binary-tree-inorder-traversal/description/ * https://plmsmile.github.io/2017/12/29/leetcode-01/#中序遍历-94 * * @author PLM * @date 2018-01-07 */ #include <stack> #include <vector> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; /* * 中序遍历 */ vector<int> inorder_traversal(TreeNode* root) { vector<int> res; stack<TreeNode*> st; TreeNode* p = root; while (p || !st.empty()) { if (p) { // 根节点入栈 st.push(p); // 扫描左孩子 p = p->left; } else { // p位于栈顶,左孩子已经被遍历过或者没有左孩子,直接出栈访问 p = st.top(); res.push_back(p->val); st.pop(); // 扫描右孩子 p = p->right; } } return res; }
true
c584f8064cbf600810dd30c2c61fe6bd747aea29
C++
m1thr4nd1r/College-Works
/Operating Systems/Primo C++ (Melhor)/main.cpp
UTF-8
2,722
3.5625
4
[]
no_license
/* * main.cpp * * Created on: 05/06/2013 * Author: m1thr4nnd1r */ #include <iostream> #include <cstdlib> #include <pthread.h> #include <sstream> #include <cmath> using namespace std; struct thread_data{ unsigned int thread_id; // ID da thread unsigned int start; // Inicio do intervalo de checagem da thread unsigned int end; // Fim do intervalo de checagem da thread }; void *Prime(void *td) { struct thread_data *data; // Dados necessarios para a thread executar bool flag; // Flag para dizer se um numero é primo ou nao stringstream ss; // Variavel para converter inteiro para string string prime = ""; // Numeros primos de acordo com a thread data = (struct thread_data *) td; for (unsigned int i = data->start; i <= data->end; i++) { flag = false; for (unsigned int j = 2; j < sqrt(i); j++) if (i % j == 0) // Se i é multiplo de um numero j (j != 1 e j != i) { flag = true; // O numero é primo break; } if (!flag) // Se i nao é multiplo de nenhum numero x (x != 1 e x != i) { ss << i; // Envia i para ss prime+= ss.str() + " "; // Converte i para String ss.str(""); // Limpa a variavel } } cout << "Thread " << data->thread_id << " : " << prime << endl; pthread_exit(NULL); } int main(int argc,char **argv) { unsigned int th; // Numero de Threads unsigned int n; // Intervalo de numeros para testar (0 ate n) unsigned int start = 2; // Inicio do intervalo para cada thread n = (argv[1] != NULL) ? atoi(argv[1]) : 200; // Caso o argumento 1 tenha sido passado, entao n = argumento, caso contrario n = 200 th = (argv[2] != NULL) ? atoi(argv[2]) : 2; // Caso o argumento 2 tenha sido passado, entao th = argumento, caso contrario th = 2 cout << th << " Threads e " << n << " numeros" << endl; unsigned int range = (n - 2) / th; // Intervalo de numeros para cada thread // --- Alocaçao das threads --- pthread_t * threads = (pthread_t *) malloc(sizeof(pthread_t)*th); thread_data * td = (thread_data *) malloc(sizeof(thread_data)*th); // ---- --- --- --- --- --- --- // --- Inicializa os dados de cada uma das threads --- for (unsigned int i = 0; i < th; i++) { td[i].end = (start + range > n)? n : start + range; // td.end = Fim do intervalo de checagem da thread td[i].start = start; // td.start = Inicio do intervalo de checagem da thread td[i].thread_id = i + 1; // td.id = ID da thread start+= range + 1; } // --- --- --- --- --- --- --- --- --- --- --- --- ---- // --- Chamada de cada thread --- for (unsigned int i = 0; i < th; i++) pthread_create(&threads[i], NULL, Prime, (void *)&td[i]); // --- --- --- --- --- --- --- --- pthread_exit(NULL); // Morte da Thread main return 0; }
true
4d5147ac8d18123fc6c1d479e1eea47f3cdfd988
C++
riveridea/algorithm
/leetcode/hash-table/325.maximum-size-subarray-sum-equals-k.cpp
UTF-8
1,721
3.515625
4
[]
no_license
/* * [325] Maximum Size Subarray Sum Equals k * * https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/description/ * * algorithms * Medium (43.79%) * Total Accepted: 65.3K * Total Submissions: 149.1K * Testcase Example: '[1,-1,5,-2,3]\n3' * * Given an array nums and a target value k, find the maximum length of a * subarray that sums to k. If there isn't one, return 0 instead. * * Note: * The sum of the entire nums array is guaranteed to fit within the 32-bit * signed integer range. * * Example 1: * * * Input: nums = [1, -1, 5, -2, 3], k = 3 * Output: 4 * Explanation: The subarray [1, -1, 5, -2] sums to 3 and is the longest. * * * Example 2: * * * Input: nums = [-2, -1, 2, 1], k = 1 * Output: 2 * Explanation: The subarray [-1, 2] sums to 1 and is the longest. * * Follow Up: * Can you do it in O(n) time? * */ class Solution { public: int maxSubArrayLen(vector<int>& nums, int k) { //record a value for each i, defined as the sum //since the left //then every time find a paired j (j < i) which //has sum as k - sumofi, then update max_len //this is O(n) int n = nums.size(); if (n == 0) return 0; unordered_map<int, int> sums; int curr_sum = 0; int max_len = 0; for(int i = 0; i < n; i++) { curr_sum += nums[i]; if(curr_sum == k) { max_len = i+1; // i - 0 } else { //check if we have pair if(sums.find(curr_sum - k) != sums.end()) { max_len = max(max_len, i - sums[curr_sum-k]); // no +1,as it is excluded } } //only insert when it does not exists, the oldest i is recorded if(sums.find(curr_sum) == sums.end()) sums[curr_sum] = i; } return max_len; } };
true
f038942e0bf6e18e91902c6c05b2b058e2fa4ca6
C++
shivarao96/MineCraft-Clone
/src/world/chunk/iChunk/iChunk.h
UTF-8
251
2.734375
3
[]
no_license
#pragma once class ChunkBlock; /* * abstract class to implement set and get action on a block */ struct IChunk { virtual void setBlock(int x, int y, int z, ChunkBlock block) = 0; virtual ChunkBlock getBlock(int x, int y, int z) const = 0; };
true
d215abcda1d60871c2e8e5a7143052c8b51bac2c
C++
Spenny1068/SHA256
/main.cpp
UTF-8
223
2.828125
3
[]
no_license
#include "sha256.h" #include <iostream> int main(void) { std::string msg = ""; std::cout << "Enter string: "; std::cin >> msg; std::cout << "sha256(" << msg << "): " << sha256(msg, true) << std::endl; return 0; }
true
cbd3975ee604e67433ec47a669a80af8a45c5629
C++
thecherry94/2DPathfindingTest
/2D Pathfinding Test/Tile.cpp
UTF-8
507
2.828125
3
[]
no_license
#include "Tile.hpp" Tile::Tile(Tilemap* pMap, clan::Vec2i pos, const bool walkable, const int cost) { m_pMap = pMap; m_pos = pos; m_walkable = walkable; m_cost = cost; m_pPreviousTile = NULL; if (m_walkable) { m_backgroundColor = clan::Colorf::darkgreen; } else { m_backgroundColor = clan::Colorf::red; } } void Tile::mark_previous_tiles_recursive() { m_backgroundColor = clan::Colorf::white; if (m_pPreviousTile != NULL) { m_pPreviousTile->mark_previous_tiles_recursive(); } }
true
41c194b9d6dcaf4fa32dd225ec456d1a9dedc58f
C++
SudaisAlam/myCppPlayGround
/printaboard.cpp
UTF-8
450
3.046875
3
[]
no_license
#include<iostream> using namespace std; void printboard(int **board, int x, int y){ for(int i=x ; i<x ; i++){ for(int j=y ; j<y ; j++){ board[i][j]= 1; cout << board[i][j]; } cout<<"\n"; } } void makeboard(int x,int y){ int **board; board = new int*[x]; for(int i=0 ; i<x ; i++){ board[i] = new int[y]; } printboard(board,x,y); }
true
7f7c85c4530fdcde8a7ceddb1069bb140831b1cc
C++
luoxz-ai/glove
/src/tests/filesystem/UnbufferedFileReaderTest.cc
UTF-8
755
2.8125
3
[ "Apache-2.0" ]
permissive
#include <gtest/gtest.hpp> #include <glove/filesystem/Path.hpp> #include <glove/filesystem/io/File.hpp> #include <glove/filesystem/io/UnbufferedFileReader.hpp> namespace { const BlueDwarf::Path directoryPath("testdata/a_directory"); const BlueDwarf::Path filePath("testdata/a_directory/a_file"); const BlueDwarf::Path nonExistingPath("testdata/a_non_existing_directory"); } namespace BlueDwarf { TEST(UnbufferedFileReaderTest, CanConstructFromFile) { File file(::filePath); UnbufferedFileReader reader(file); } TEST(FileTest, CanReadBytesFromFile) { File file(::filePath); UnbufferedFileReader reader(file); char character; reader.Read(&character, sizeof(char)); EXPECT_EQ('G', character); } } /* namespace BlueDwarf */
true
ab539ae5d0b6d7fe437e0c05a4557f073eb17ad6
C++
cowarder/Algorithms
/牛客/日志排序.cpp
UTF-8
817
3.21875
3
[]
no_license
#include<iostream> #include<string> #include<vector> #include<algorithm> #include<sstream> using namespace std; class Node { public: string data; string name; string year; string time; string strcost; double cost; bool operator<(const Node& s) { if (cost != s.cost) return cost < s.cost; else if (year != s.year) return year < s.year; else return time < s.time; } }; int main() { string s; vector<Node>v; while (getline(cin, s) && s.length() != 0) { stringstream ss(s); Node n; n.data = s; ss >> n.name >> n.year >> n.time >> n.strcost; string cost=n.strcost.substr(0,n.strcost.length()-3); stringstream ss1(cost); double m; ss1 >> m; n.cost = m; v.push_back(n); } sort(v.begin(), v.end()); for (int i = 0; i < v.size(); i++) cout << v[i].data<< endl; return 0; }
true
317958fb872b19b4a66165cee114645993fc5264
C++
ninetyeightoctane/Final-PingPongGame
/main.cpp
UTF-8
7,130
3.0625
3
[]
no_license
#include <SFML/Graphics.hpp> #include <cmath> #include <ctime> int main(){ std::srand(static_cast<unsigned int>(std::time(NULL))); // Set values const float pi = 3.1415f; const int windowWidth = 900; const int windowHeight = 600; sf::Vector2f paddleSize(25, 100); float ballRad = 10.f; // Create the window sf::RenderWindow window(sf::VideoMode(windowWidth, windowHeight, 30), "Ping Pong"); window.setVerticalSyncEnabled(true); // Create the ball sf::CircleShape ball; ball.setRadius(ballRad - 3); ball.setFillColor(sf::Color::White); ball.setOrigin(ballRad / 2, ballRad / 2); // Create the right paddle sf::RectangleShape rightPaddle; rightPaddle.setSize(paddleSize - sf::Vector2f(3, 3)); rightPaddle.setFillColor(sf::Color::Red); rightPaddle.setOrigin(paddleSize / 2.f); // Create the left paddle sf::RectangleShape leftPaddle; leftPaddle.setSize(paddleSize - sf::Vector2f(3, 3)); leftPaddle.setFillColor(sf::Color::Blue); leftPaddle.setOrigin(paddleSize / 2.f); // Paddles Properties const float paddleSpeed = 400.f; const float ballSpeed = 400.f; float ballAngle = 0.f;//will adjust // Load the text font sf::Font font; if (!font.loadFromFile("/Users/ammarrangoonwala/documents/pingPongGame/pingPongGame/sansation.ttf")) return EXIT_FAILURE; // Start Menu sf::Text message; message.setFont(font); message.setCharacterSize(35); message.setPosition(150.f, 150.f); message.setFillColor(sf::Color::White); message.setString("Press the space bar to begin"); sf::Clock clock; bool isPlaying = false; while (window.isOpen()){ // Handle events sf::Event event; while (window.pollEvent(event)){ // When closed -> exit if (event.type == sf::Event::Closed){ window.close(); break; } // When space key is pressed -> play if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Space)){ if (!isPlaying){ // (re)start the game isPlaying = true; clock.restart(); // Reset the position of the paddles and ball leftPaddle.setPosition(10 + paddleSize.x / 2, windowHeight / 2); rightPaddle.setPosition(windowWidth - 10 - paddleSize.x / 2, windowHeight / 2); ball.setPosition(windowWidth / 2, windowHeight / 2); // Reset the ball do{ ballAngle = (std::rand() % 360) * 2 * pi / 360; } while (std::abs(std::cos(ballAngle)) < 0.7f); } } } if (isPlaying){ float deltaTime = clock.restart().asSeconds(); // Move Player 1 (Red) if (sf::Keyboard::isKeyPressed(sf::Keyboard::W) && (leftPaddle.getPosition().y - paddleSize.y / 2 > 5.f)){ leftPaddle.move(0.f, -paddleSpeed * deltaTime); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::S) && (leftPaddle.getPosition().y + paddleSize.y / 2 < windowHeight - 5.f)){ leftPaddle.move(0.f, paddleSpeed * deltaTime); } //Move Player 2 (Blue) if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up) && (rightPaddle.getPosition().y - paddleSize.y / 2 > 5.f)){ rightPaddle.move(0.f, -paddleSpeed * deltaTime); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down) && (rightPaddle.getPosition().y + paddleSize.y / 2 < windowHeight - 5.f)){ rightPaddle.move(0.f, paddleSpeed * deltaTime); } // Move the ball float factor = ballSpeed * deltaTime; ball.move(std::cos(ballAngle) * factor, std::sin(ballAngle) * factor); // Check for winner if (ball.getPosition().x - ballRad < 0.f){ isPlaying = false; message.setString("Red Won!\nPress the space bar to start over"); } if (ball.getPosition().x + ballRad > windowWidth){ isPlaying = false; message.setString("Blue won!\nPress the space bar to start over"); } if (ball.getPosition().y - ballRad < 0.f){ ballAngle = -ballAngle; ball.setPosition(ball.getPosition().x, ballRad + 0.1f); } if (ball.getPosition().y + ballRad > windowHeight){ ballAngle = -ballAngle; ball.setPosition(ball.getPosition().x, windowHeight - ballRad - 0.1f); } // Paddle and ball contact // Left Paddle if (ball.getPosition().x - ballRad < leftPaddle.getPosition().x + paddleSize.x / 2 && ball.getPosition().x - ballRad > leftPaddle.getPosition().x && ball.getPosition().y + ballRad >= leftPaddle.getPosition().y - paddleSize.y / 2 && ball.getPosition().y - ballRad <= leftPaddle.getPosition().y + paddleSize.y / 2) { if (ball.getPosition().y > leftPaddle.getPosition().y) ballAngle = pi - ballAngle + (std::rand() % 20) * pi / 180; else ballAngle = pi - ballAngle - (std::rand() % 20) * pi / 180; ball.setPosition(leftPaddle.getPosition().x + ballRad + paddleSize.x / 2 + 0.1f, ball.getPosition().y); } // Right Paddle if (ball.getPosition().x + ballRad > rightPaddle.getPosition().x - paddleSize.x / 2 && ball.getPosition().x + ballRad < rightPaddle.getPosition().x && ball.getPosition().y + ballRad >= rightPaddle.getPosition().y - paddleSize.y / 2 && ball.getPosition().y - ballRad <= rightPaddle.getPosition().y + paddleSize.y / 2) { if (ball.getPosition().y > rightPaddle.getPosition().y) ballAngle = pi - ballAngle + (std::rand() % 20) * pi / 180; else ballAngle = pi - ballAngle - (std::rand() % 20) * pi / 180; ball.setPosition(rightPaddle.getPosition().x - ballRad - paddleSize.x / 2 - 0.1f, ball.getPosition().y); } } // Clear the window window.clear(sf::Color::Black); if (isPlaying){ // Draw the paddles and the ball window.draw(leftPaddle); window.draw(rightPaddle); window.draw(ball); } else{ // Draw the menu window.draw(message); } // Display screen window.display(); } return EXIT_SUCCESS; }
true
f2b9e235b92cdac6812dc78b13cce7e931bc227a
C++
NightTerror1721/kpgbe
/KPGBE/KPGBE/include/cpu.h
UTF-8
449
3
3
[]
no_license
#pragma once #include "common.h" class VirtualMachine; class CPU { private: bool _stop; Ticks _ticks; public: CPU(); ~CPU(); void step(VirtualMachine& vm); void reset(); void stop(); bool isStopped() const; inline void increaseTicks(unsigned int ticks) { _ticks += static_cast<Ticks>(ticks); } inline void decreaseTicks(unsigned int ticks) { _ticks -= static_cast<Ticks>(ticks); } inline Ticks ticks() const { return _ticks; } };
true
3bddbe8c1dd0d80108dee44d2c2a22575662aaf8
C++
Ultranull/BlueWork
/BlueWork/src/resource/MeshProcessing.h
UTF-8
2,888
2.96875
3
[]
no_license
#pragma once #include <vector> #include <glm/glm.hpp> #include "Engine.h" #include "graphics/Geometry.h" class MeshProcessing{ public: static Geometry* BuildGeometry(std::vector<Engine::Vertex> vertices, unsigned int topology = GL_TRIANGLES){ Geometry* geom = new Geometry(); geom->vaObject = std::unique_ptr<VertexArray>(new VertexArray()); Buffer* vbuffer = geom->vaObject->bindBuffer<Engine::Vertex>("vertexes", GL_ARRAY_BUFFER); vbuffer->setData(vertices, GL_STATIC_DRAW); vbuffer->bindPointer(Engine::POSITION, 3, GL_FLOAT, (void*)offsetof(Engine::Vertex, Position)); vbuffer->bindPointer(Engine::TEXTURECOORD, 2, GL_FLOAT, (void*)offsetof(Engine::Vertex, TextureCoord)); vbuffer->bindPointer(Engine::NORMAL, 3, GL_FLOAT, (void*)offsetof(Engine::Vertex, Normal)); vbuffer->bindPointer(Engine::TANGENT, 3, GL_FLOAT, (void*)offsetof(Engine::Vertex, Tangent)); geom->size = vertices.size(); geom->topology = topology; return geom; } static Geometry* BuildIndexedGeometry(std::vector<Engine::Vertex> vertices, std::vector<unsigned int> indices, unsigned int topology = GL_TRIANGLES) { Geometry* geom = new Geometry(); geom->vaObject = std::unique_ptr<VertexArray>(new VertexArray());; Buffer* vbuffer = geom->vaObject->bindBuffer<Engine::Vertex>("vertexes", GL_ARRAY_BUFFER); vbuffer->setData(vertices, GL_STATIC_DRAW); vbuffer->bindPointer(Engine::POSITION, 3, GL_FLOAT, (void*)offsetof(Engine::Vertex, Position)); vbuffer->bindPointer(Engine::TEXTURECOORD, 2, GL_FLOAT, (void*)offsetof(Engine::Vertex, TextureCoord)); vbuffer->bindPointer(Engine::NORMAL, 3, GL_FLOAT, (void*)offsetof(Engine::Vertex, Normal)); Buffer* ebuffer = geom->vaObject->bindBuffer<unsigned int>("indides", GL_ELEMENT_ARRAY_BUFFER); ebuffer->setData(indices, GL_STATIC_DRAW); geom->size = indices.size(); geom->indexed = true; geom->topology = topology; return geom; } static void CalcTangents(std::vector<Engine::Vertex>& verts) { for (int i = 0; i < verts.size(); i += 3) { // Shortcuts for vertices glm::vec3& v0 = verts[i + 0].Position; glm::vec3& v1 = verts[i + 1].Position; glm::vec3& v2 = verts[i + 2].Position; // Shortcuts for UVs glm::vec2& uv0 = verts[i + 0].TextureCoord; glm::vec2& uv1 = verts[i + 1].TextureCoord; glm::vec2& uv2 = verts[i + 2].TextureCoord; // Edges of the triangle : position delta glm::vec3 deltaPos1 = v1 - v0; glm::vec3 deltaPos2 = v2 - v0; // UV delta glm::vec2 deltaUV1 = uv1 - uv0; glm::vec2 deltaUV2 = uv2 - uv0; float r = 1.0f / (deltaUV1.x * deltaUV2.y - deltaUV1.y * deltaUV2.x); glm::vec3 tangent = (deltaPos1 * deltaUV2.y - deltaPos2 * deltaUV1.y) * r; glm::vec3 bitangent = (deltaPos2 * deltaUV1.x - deltaPos1 * deltaUV2.x) * r; verts[i + 0].Tangent = tangent; verts[i + 1].Tangent = tangent; verts[i + 2].Tangent = tangent; } } };
true
768eda96ecefccbef3607309bb0782127dd74fbc
C++
chenxiaobin3000/xengine
/engine/XeTriangle.cpp
UTF-8
1,923
2.6875
3
[]
no_license
#include "stdafx.h" #include "XeTriangle.h" #include "XeMath.h" namespace XE { CTriangle::CTriangle() : m_p1(0,0), m_p2(0,0), m_p3(0,0) { } CTriangle::CTriangle(float x1, float y1, float x2, float y2, float x3, float y3) : m_p1(x1,y1), m_p2(x2,y2), m_p3(x3,y3) { } CTriangle::~CTriangle() { } // 射线法(x轴正方向) bool CTriangle::Contain(CPoint& p, bool bInSize) { int cnt = 0; // 是否交于边 if (IsFloatEqual((p.x-m_p1.x)*(m_p2.y-m_p1.y), (p.y-m_p1.y)*(m_p2.x-m_p1.x))) { return bInSize; } if (IsFloatEqual((p.x-m_p2.x)*(m_p3.y-m_p2.y), (p.y-m_p2.y)*(m_p3.x-m_p2.x))) { return bInSize; } if (IsFloatEqual((p.x-m_p3.x)*(m_p1.y-m_p3.y), (p.y-m_p3.y)*(m_p1.x-m_p3.x))) { return bInSize; } // 边1 - 平行x轴 if (!IsFloatEqual(m_p1.y, m_p2.y)) { // 上方 if (p.y <= m_p1.y || p.y <= m_p2.y) { // 下方(上闭下开) if (p.y > m_p1.y || p.y > m_p2.y) { // 右方 if (p.x <= m_p1.x || p.x <= m_p2.x) { if (p.x < (m_p1.x + (m_p2.x - m_p1.x)*(p.y - m_p1.y)/(m_p2.y - m_p1.y))) { ++cnt; } } } } } // 边2 - 平行x轴 if (!IsFloatEqual(m_p2.y, m_p3.y)) { // 上方 if (p.y <= m_p2.y || p.y <= m_p3.y) { // 下方(上闭下开) if (p.y > m_p2.y || p.y > m_p3.y) { // 右方 if (p.x <= m_p2.x || p.x <= m_p3.x) { if (p.x < (m_p2.x + (m_p3.x - m_p2.x)*(p.y - m_p2.y)/(m_p3.y - m_p2.y))) { ++cnt; } } } } } // 边3 - 平行x轴 if (!IsFloatEqual(m_p3.y, m_p1.y)) { // 上方 if (p.y <= m_p3.y || p.y <= m_p1.y) { // 下方(上闭下开) if (p.y > m_p3.y || p.y > m_p1.y) { // 右方 if (p.x <= m_p3.x || p.x <= m_p1.x) { if (p.x < (m_p3.x + (m_p1.x - m_p3.x)*(p.y - m_p3.y)/(m_p1.y - m_p3.y))) { ++cnt; } } } } } return (cnt%2==1) ? true : false; } }
true
25dd82af5a7c353923b33195e45005896cbadf3e
C++
dkostenko/CloseBox-game
/level.h
UTF-8
823
2.8125
3
[]
no_license
#ifndef LEVEL_H #define LEVEL_H #include <QtCore> class Level { public: Level(); enum Direction { UP, RIGHT, DOWN, LEFT }; enum BlocTypes {BALL, WALL, BIG_TOP, BIG_RIGHT, BIG_BOTTOM, BIG_LEFT, SMALL_TOP, SMALL_RIGHT, SMALL_BOTTOM, SMALL_LEFT }; int getBloc(int row, int col); void setBloc(int row, int col, int value); int getRows(); int getCols(); int getTime(); QString getCurrentLevelText(); QString getTimerText(); bool move(Direction direction); bool isFinished(); bool next(); private: int currentLevel; int rows; int cols; int blocs[20][3]; int inBig; int inSmall; int time; bool setCurrentMap(); bool chkDirection(int newRow, int newCol, Direction direction); }; #endif // LEVEL_H
true
7076cf6416ed5cdc86b9d17699fbaed3a2c24333
C++
ArturoRivera/Project1
/Project1/SportsTeam.h
UTF-8
307
2.515625
3
[]
no_license
#pragma once #include <string> class SportsTeam { //Private class members. private: std::string _teamName; std::string _teamCity; //Public class members. public: SportsTeam(); SportsTeam(std::string teamName, std::string teamCity); ~SportsTeam(); std::string GetSportsTeamInfo(); };
true
c411545aec71542940e3bae54ff52fce4f60e41c
C++
beemfx/Beem.Media
/games/Legacy-Engine/Source/lf_sys2/lf_mem.cpp
UTF-8
564
2.796875
3
[]
no_license
/* Memory allocation. */ #include <malloc.h> #include "lf_sys2.h" LF_ALLOC_FUNC g_pMalloc=malloc; LF_FREE_FUNC g_pFree=free; extern "C" lf_void LF_SetMemFuncs(LF_ALLOC_FUNC pAlloc, LF_FREE_FUNC pFree) { g_pMalloc=pAlloc; g_pFree=pFree; } extern "C" lf_void* LF_Malloc(lf_size_t size) { if(g_pMalloc) return g_pMalloc(size); else return LF_NULL; } extern "C" lf_void LF_Free(lf_void* p) { if(g_pFree) return g_pFree(p); } #if 0 void* operator new (lf_size_t size) { return LF_Malloc(size); } void operator delete (void* p) { LF_Free(p); } #endif
true
deec08d770dc90f983c6534f397b5572e0c77d74
C++
andreabecsek/akrscv
/src/cv_meanKRS.cpp
UTF-8
1,805
2.75
3
[]
no_license
#include <Rcpp.h> #include <akrs.h> using namespace Rcpp; // mean squared error double mse(const NumericVector a, const NumericVector b){ return mean(pow((a-b),2)); } // shuffle randomly int randWrapper(const int n){ return(floor(unif_rand())); } // create a sequence of n samples from 0 to k NumericVector sample_rcpp(int k, int n){ NumericVector seq(n); // create ordered sequence for(int i = 1; i <= k; i++){ for(int j = i; j <= n; j= j + k){ seq[j-1] = i-1; } } // randomly shuffle the sequence of indeces std::random_shuffle(seq.begin(), seq.end(), randWrapper); return seq; } //' Perform cross-validation for meanKRS function based on different lambdas. //' //' @param y numeric vector //' @param x numeric vector //' @param lambdas numeric vector //' @param k int //' @return Vector of mean squared errors for each lamdba. // [[Rcpp::export(name = "cv_meanKRS_cpp")]] NumericVector cv_meanKRS_cpp(const NumericVector y, const NumericVector x, const NumericVector lambdas, const int k){ int n = x.size(); int m = lambdas.size(); NumericVector errors(m); NumericVector folds = sample_rcpp(k, n); // iterate over lambdas for(int i=0; i < m; i++){ double error = 0; // iterate over folds for(int j = 0; j < k; j++){ // split the data into train and test set NumericVector x_test = x[(folds==j)]; NumericVector x_train = x[(folds!=j)]; NumericVector y_test = y[(folds==j)]; NumericVector y_train = y[(folds!=j)]; // fit model on training data and get NumericVector fit = akrs::meanKRS_cpp(y_train, x_train, x_test, lambdas[i]); // calculate error for fold error = error + mse(fit, y_test)/k; } errors[i] = error; } return errors; }
true
c7d342ee56590f38204f9f8409107d4f7e3757c5
C++
yotann/bcdb
/memodb/unittests/CborSaveTest.cpp
UTF-8
6,707
2.640625
3
[ "LLVM-exception", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#include "memodb/Node.h" #include "MockStore.h" #include "gtest/gtest.h" using namespace memodb; namespace { void test_save(const Node &value, const std::vector<uint8_t> &expected) { std::vector<uint8_t> out = value.saveAsCBOR(); EXPECT_EQ(expected, out); } TEST(CborSaveTest, Integer) { test_save(Node(0), {0x00}); test_save(Node(1), {0x01}); test_save(Node(10), {0x0a}); test_save(Node(23), {0x17}); test_save(Node(24), {0x18, 0x18}); test_save(Node(25), {0x18, 0x19}); test_save(Node(100), {0x18, 0x64}); test_save(Node(1000), {0x19, 0x03, 0xe8}); test_save(Node(1000000), {0x1a, 0x00, 0x0f, 0x42, 0x40}); test_save(Node(1000000000000), {0x1b, 0x00, 0x00, 0x00, 0xe8, 0xd4, 0xa5, 0x10, 0x00}); test_save(Node(static_cast<uint64_t>(18446744073709551615ull)), {0x1b, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}); test_save(Node(static_cast<int64_t>(-9223372036854775807ll)), {0x3b, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe}); test_save(Node(static_cast<int64_t>(0x8000000000000000ull)), {0x3b, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}); test_save(Node(-1), {0x20}); test_save(Node(-10), {0x29}); test_save(Node(-100), {0x38, 0x63}); test_save(Node(-1000), {0x39, 0x03, 0xe7}); } TEST(CborSaveTest, Float) { auto check = [](double value, const std::vector<uint8_t> &expected) { std::vector<uint8_t> out = Node(value).saveAsCBOR(); EXPECT_EQ(expected, out); }; check(0.0, {0xfb, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}); check(-0.0, {0xfb, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}); check(1.0, {0xfb, 0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}); check(1.1, {0xfb, 0x3f, 0xf1, 0x99, 0x99, 0x99, 0x99, 0x99, 0x9a}); check(1.5, {0xfb, 0x3f, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}); check(65504.0, {0xfb, 0x40, 0xef, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00}); check(100000.0, {0xfb, 0x40, 0xf8, 0x6a, 0x00, 0x00, 0x00, 0x00, 0x00}); check(3.4028234663852886e+38, {0xfb, 0x47, 0xef, 0xff, 0xff, 0xe0, 0x00, 0x00, 0x00}); check(1.0e+300, {0xfb, 0x7e, 0x37, 0xe4, 0x3c, 0x88, 0x00, 0x75, 0x9c}); check(1.7976931348623157e+308, {0xfb, 0x7f, 0xef, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}); check(5.960464477539063e-8, {0xfb, 0x3e, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}); check(2.2250738585072014e-308, {0xfb, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}); check(5e-324, {0xfb, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}); check(0.00006103515625, {0xfb, 0x3f, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}); check(-4.0, {0xfb, 0xc0, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}); check(-4.1, {0xfb, 0xc0, 0x10, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66}); check(INFINITY, {0xfb, 0x7f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}); check(NAN, {0xfb, 0x7f, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}); check(-INFINITY, {0xfb, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}); } TEST(CborSaveTest, Bool) { test_save(Node(false), {0xf4}); test_save(Node(true), {0xf5}); } TEST(CborSaveTest, Null) { test_save(Node{nullptr}, {0xf6}); } TEST(CborSaveTest, Bytes) { using bytes = std::vector<uint8_t>; test_save(Node(bytes{}), {0x40}); test_save(Node(bytes{0x01, 0x02, 0x03, 0x04}), {0x44, 0x01, 0x02, 0x03, 0x04}); } TEST(CborSaveTest, String) { test_save(Node(""), {0x60}); test_save(Node("a"), {0x61, 0x61}); test_save(Node("IETF"), {0x64, 0x49, 0x45, 0x54, 0x46}); test_save(Node("\"\\"), {0x62, 0x22, 0x5c}); test_save(Node("\u00fc"), {0x62, 0xc3, 0xbc}); test_save(Node("\u6c34"), {0x63, 0xe6, 0xb0, 0xb4}); test_save(Node("\u6c34"), {0x63, 0xe6, 0xb0, 0xb4}); test_save(Node("\U00010151"), {0x64, 0xf0, 0x90, 0x85, 0x91}); } TEST(CborSaveTest, List) { test_save(Node(node_list_arg), {0x80}); test_save(Node(node_list_arg, {1, 2, 3}), {0x83, 0x01, 0x02, 0x03}); test_save(Node(node_list_arg, {1, Node(node_list_arg, {2, 3}), Node(node_list_arg, {4, 5})}), {0x83, 0x01, 0x82, 0x02, 0x03, 0x82, 0x04, 0x05}); test_save( Node(node_list_arg, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25}), {0x98, 0x19, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x18, 0x18, 0x19}); } TEST(CborSaveTest, Map) { test_save(Node(node_map_arg), {0xa0}); test_save(Node(node_map_arg, {{"a", "A"}, {"b", "B"}, {"c", "C"}, {"d", "D"}, {"e", "E"}}), {0xa5, 0x61, 0x61, 0x61, 0x41, 0x61, 0x62, 0x61, 0x42, 0x61, 0x63, 0x61, 0x43, 0x61, 0x64, 0x61, 0x44, 0x61, 0x65, 0x61, 0x45}); } TEST(CborSaveTest, Mixed) { test_save(Node(node_list_arg, {"a", Node(node_map_arg, {{"b", "c"}})}), {0x82, 0x61, 0x61, 0xa1, 0x61, 0x62, 0x61, 0x63}); test_save(Node(node_map_arg, {{"a", 1}, {"b", Node(node_list_arg, {2, 3})}}), {0xa2, 0x61, 0x61, 0x01, 0x61, 0x62, 0x82, 0x02, 0x03}); } TEST(CborSaveTest, Ref) { MockStore store; test_save(Node(store, *CID::fromBytes({0x01, 0x71, 0x00, 0x01, 0xf6})), {0xd8, 0x2a, 0x46, 0x00, 0x01, 0x71, 0x00, 0x01, 0xf6}); test_save(Node(store, *CID::fromBytes( {0x01, 0x71, 0xa0, 0xe4, 0x02, 0x20, 0x03, 0x17, 0x0a, 0x2e, 0x75, 0x97, 0xb7, 0xb7, 0xe3, 0xd8, 0x4c, 0x05, 0x39, 0x1d, 0x13, 0x9a, 0x62, 0xb1, 0x57, 0xe7, 0x87, 0x86, 0xd8, 0xc0, 0x82, 0xf2, 0x9d, 0xcf, 0x4c, 0x11, 0x13, 0x14})), {0xd8, 0x2a, 0x58, 0x27, 0x00, 0x01, 0x71, 0xa0, 0xe4, 0x02, 0x20, 0x03, 0x17, 0x0a, 0x2e, 0x75, 0x97, 0xb7, 0xb7, 0xe3, 0xd8, 0x4c, 0x05, 0x39, 0x1d, 0x13, 0x9a, 0x62, 0xb1, 0x57, 0xe7, 0x87, 0x86, 0xd8, 0xc0, 0x82, 0xf2, 0x9d, 0xcf, 0x4c, 0x11, 0x13, 0x14}); } TEST(CborSaveTest, MapOrdering) { test_save(Node(node_map_arg, { {"", {}}, {"a", {}}, {"m", {}}, {"bb", {}}, {"nn", {}}, {"\xc2\x80", {}}, {"ccc", {}}, {"ooo", {}}, }), { 0xa8, 0x60, 0xf6, 0x61, 0x61, 0xf6, 0x61, 0x6d, 0xf6, 0x62, 0x62, 0x62, 0xf6, 0x62, 0x6e, 0x6e, 0xf6, 0x62, 0xc2, 0x80, 0xf6, 0x63, 0x63, 0x63, 0x63, 0xf6, 0x63, 0x6f, 0x6f, 0x6f, 0xf6, }); } } // end anonymous namespace
true
8bc2f20a824f24ffc4d05b87b597c6b7daa1729f
C++
senturkoguzhan/Student-Information-System
/lecturer.cpp
UTF-8
9,272
3.453125
3
[ "Apache-2.0" ]
permissive
/*************************************************************************************/ /* Oguzhan SENTURK */ /* */ /* osenturk@gtu.edu.tr */ /*************************************************************************************/ #include <iostream> #include <string> #include <vector> #include <ctime> #include "lecturer.h" #define MAX 16 //max lecture hour #define MIN 9 //min lecture hour using namespace std; namespace LecturerNS { void Lecturer::assignCourse(Course course1, Course lecture[], int& number_of_lectures) //function to assign course { int mismatch = 1; //mismatch is a flag to check invalid course if value 1 MISMATCH int assign_before = 0; //assign_before is a flag to check invalid course if value 1 ASSIGN BEFORE int overlap_course = 0; //if current lecture is must taken course, value 1 if (courses.size() == 3) { cout << "ERROR: LECTURER GIVES 3 LESSONS ALREADY" << endl; //ERROR MESSAGE } else { for (int k = 0; k < professions.size(); ++k) { if(professions[k] == course1.field) { mismatch = 0; break; } } if(mismatch == 1) { cout << "BLOCK: FIELD AND PROFESSION MISMATCH" << endl; //ERROR MESSAGE } else { for (int k = 0; k < courses.size(); ++k) { if(courses[k].id == course1.id) { assign_before = 1; break; } } if(assign_before == 1) { cout << "ERROR: COURSE ASSIGNED BEFORE TO LECTURER" << endl; //ERROR MESSAGE } else { int k ; for ( k= 0; k < must_take_course.size(); ++k) { if(must_take_course[k].id == course1.id) { overlap_course = 1; break; } } if( ( must_take_course.size() + courses.size() ) == 3 && overlap_course == 0) { cout << "ERROR: THERE ARE OTHER LESSONS THAT THE LECTURER HAS TO GIVE" << endl; //ERROR MESSAGE } else if(must_take_course.size() != 3 && overlap_course == 0) { cout << "DONE!" << endl; courses.push_back(course1); for(int i = 0; i < number_of_lectures; i++) { if(lecture[i].id == course1.id) //lecture has been assigned and lecture delete from array to prevent to another assign { for(int j = i; j < (number_of_lectures - 1); j++) { lecture[j] = lecture[j + 1]; } number_of_lectures --; break; } } } else { must_take_course.erase(must_take_course.begin() + k); cout << "DONE!" << endl; courses.push_back(course1); for(int i = 0; i < number_of_lectures; i++) { if(lecture[i].id == course1.id) { for(int j = i; j < (number_of_lectures - 1); j++) //lecture has been assigned and lecture delete from array to prevent to another assign { lecture[j] = lecture[j + 1]; } number_of_lectures --; break; } } } } } } if(courses.size() < 3 && (propose_courses.size() == 0) ) //lecturer hasnt propose an elevtive course yet { cout << name<<" "<< surname << " HAS NOT PROPOSED AN ELECTIVE COURSE YET, PROPOSE AN ELECTIVE COURSE" << endl; } } void Lecturer::proposeCourse(string course_data) //function to propose course { string name1, field1; int code1, credit1, total_hours1; int blockfield = 1; //blockfield is a flag to check mismatch field and profession if value 1 MISMATCH string delim = " "; //parse string by whitespace auto start = 0U; auto end = course_data.find(delim); //propse setting DeepLearning 521 3 3 AI name1 = (course_data.substr(start, end - start)); start = end + delim.length(); end = course_data.find(delim, start); code1 = stoi((course_data.substr(start, end - start))); start = end + delim.length(); end = course_data.find(delim, start); credit1 = stoi((course_data.substr(start, end - start))); start = end + delim.length(); end = course_data.find(delim, start); total_hours1 = stoi((course_data.substr(start, end - start))); start = end + delim.length(); end = course_data.find(delim, start); field1 = (course_data.substr(start, end - start)); for (int i = 0; i < professions.size(); ++i) { if(professions[i] == field1) { blockfield = 0; break; } } if (blockfield == 1) { cout << "BLOCK: FIELD AND PROFESSION MISMATCH" << endl; //Error Message } else { Course temp; //propose course are adding to vector of propose temp.name = name1; temp.code = code1; temp.credit = credit1; temp.total_hours = total_hours1; temp.field = field1; temp.isMandotary = 0; cout << "DONE!" << endl; propose_courses.push_back(temp); } } int Lecturer::assignCourse_automatic(Course course1, Course lecture[], int& number_of_lectures) //function to assign course automatic { int mismatch = 1; //mismatch is a flag to check invalid course if value 1 MISMATCH int assign_before = 0; //assign_before is a flag to check invalid course if value 1 ASSIGN BEFORE int overlap_course = 0; if (courses.size() == 3) { //cout << "ERROR: LECTURER GIVES 3 LESSONS ALREADY" << endl; } else { for (int k = 0; k < professions.size(); ++k) { if(professions[k] == course1.field) { mismatch = 0; break; } } if(mismatch == 1) { //cout << "BLOCK: FIELD AND PROFESSION MISMATCH" << endl; } else { for (int k = 0; k < courses.size(); ++k) { if(courses[k].id == course1.id) { assign_before = 1; break; } } if(assign_before == 1) { //cout << "ERROR: COURSE ASSIGNED BEFORE TO LECTURER" << endl; } else { int k ; for ( k= 0; k < must_take_course.size(); ++k) { if(must_take_course[k].id == course1.id) { overlap_course = 1; break; } } if( ( must_take_course.size() + courses.size() ) == 3 && overlap_course == 0) { //cout << "ERROR: THERE ARE OTHER LESSONS THAT THE LECTURER HAS TO GIVE" << endl; } else if(must_take_course.size() != 3 && overlap_course == 0) { //cout << "DONE!" << endl; courses.push_back(course1); for(int i = 0; i < number_of_lectures; i++) { if(lecture[i].id == course1.id) { for(int j = i; j < (number_of_lectures - 1); j++) { lecture[j] = lecture[j + 1]; } number_of_lectures --; return 1; break; } } } else { must_take_course.erase(must_take_course.begin() + k); //cout << "DONE!" << endl; courses.push_back(course1); for(int i = 0; i < number_of_lectures; i++) { if(lecture[i].id == course1.id) { for(int j = i; j < (number_of_lectures - 1); j++) { lecture[j] = lecture[j + 1]; } number_of_lectures --; return 1; break; } } } } } } return 0; } string Lecturer::getter_lecturer_name() { return name; } string Lecturer::getter_lecturer_surname() { return surname; } int Lecturer::getter_lecturer_personal_id() { return personal_id; } string Lecturer::getter_lecturer_title() { return title; } void Lecturer::setter_lecturer_name(string name1) { name = name1; } void Lecturer::setter_lecturer_surname(string surname1) { surname = surname1; } void Lecturer::setter_lecturer_personal_id(int personal_id1) { personal_id = personal_id1; } void Lecturer::setter_lecturer_title(string title1) { title = title1; } void Lecturer::setter_lecturer_professions(string professions1) { string s = professions1; string delim = ","; //parse string by comma auto start = 0U; auto end = s.find(delim); while (end != string::npos) { professions.push_back (s.substr(start, end - start)) ; start = end + delim.length(); //EX: MACH,PROG end = s.find(delim, start); //inside vector : { (MACH) , (PROG) } } professions.push_back(s.substr(start, end)) ; } Lecturer& Lecturer::operator = (const Lecturer& rightside) { if(this == &rightside) { return *this; } else { name = rightside.name; surname = rightside.surname; personal_id = rightside.personal_id; title = rightside.title; professions = rightside.professions; courses = rightside.courses; propose_courses = rightside.propose_courses; must_take_course = rightside.must_take_course ; } } Lecturer::~Lecturer() { } Lecturer::Lecturer(const Lecturer& lecturer_object) { name = lecturer_object.name; surname = lecturer_object.surname; personal_id = lecturer_object.personal_id; title = lecturer_object.title; professions = lecturer_object.professions; courses = lecturer_object.courses; propose_courses = lecturer_object.propose_courses; must_take_course = lecturer_object.must_take_course ; } Lecturer::Lecturer() { } }
true
52b2b824df0bbc04a10a5939fa6bf311bc8fb02c
C++
cpvhunter/Cpp_4th
/chapter_06/例6-3 对象数组应用举例/Point.h
GB18030
481
2.90625
3
[]
no_license
//Point.h #ifndef _POINT_H #define _POINT_H class Point{ //Ķ public: //ⲿӿ Point(); Point(int x,int y); ~Point(); void move(int newX,int newY); int getX() const {return x;} int getY() const {return y;} static void showCount(); //̬Ա private: //˽ݳԱ int x,y; }; #endif //_POINT_H
true
d372557a17510b7555af4e045de12edc7c8ced48
C++
SanchezSobrino/Campo-Estelar-2010
/src/Bar.cpp
UTF-8
1,540
2.953125
3
[ "MIT" ]
permissive
#include "Bar.h" Bar::Bar() { destination = NULL; numBars = 0; } void Bar::Draw(int val) { if(val >= 0) { rect.w = ((float)val/(float)maximo) * ancho; SDL_Rect position = rect; SDL_FillRect(destination, &position, SDL_MapRGB(destination->format, color.r, color.g, color.b)); } } void Bar::Create(int x, int y, int w, int h, int max, SDL_Surface* dest) { rect.x = x; rect.y = y; rect.w = w; rect.h = h; maximo = max; ancho = w; destination = dest; } void Bar::SetRect(Sint16 x, Sint16 y, Sint16 w, Sint16 h) { rect.x = x; rect.y = y; rect.w = w; rect.h = h; } void Bar::SetMax(int val) { maximo = val; } void Bar::SetX(int x) { rect.x = x; } void Bar::SetY(int y) { rect.y = y; } void Bar::SetW(int w) { rect.w = w; } void Bar::SetH(int h) { rect.h = h; } void Bar::SetColor(Uint8 r, Uint8 g, Uint8 b) { color = {r, g, b}; } void Bar::Increase(int val) { return; } void Bar::AddW(int w) { rect.w += w; } void Bar::AddH(int h) { rect.h += h; } void Bar::IncreaseNumBars(){ numBars++; } void Bar::SetNumBars(int val) { numBars = val; } SDL_Rect Bar::GetRect() { return rect; } int Bar::GetX() { return rect.x; } int Bar::GetY() { return rect.y; } int Bar::GetW() { return rect.w; } int Bar::GetH() { return rect.h; } int Bar::GetNumBars() { return numBars; } SDL_Color Bar::GetColor() { return color; } void Bar::SetDestination(SDL_Surface* sur) { destination = sur; }
true
4a968a1765f645aec3f099eb95d48cf50ab347ea
C++
knightzf/review
/leetcode/onlineStockSpan/q2.cpp
UTF-8
904
3.296875
3
[]
no_license
#include "header.h" class StockSpanner { private: vector<int> v; vector<int> res; public: StockSpanner() { } int next(int price) { v.push_back(price); if(v.size() == 1) { res.push_back(1); return 1; } int t = 1; int offset = 1; int idx = v.size() - 1; while(idx - offset >= 0 && v[idx - offset] <= price) { idx -= offset; offset = res[idx]; t += offset; } res.push_back(t); return res.back(); } }; int main() { //Solution s; StockSpanner s; cout<<s.next(100)<<endl; cout<<s.next(80)<<endl; cout<<s.next(60)<<endl; cout<<s.next(70)<<endl; cout<<s.next(60)<<endl; cout<<s.next(75)<<endl; cout<<s.next(85)<<endl; }
true
08fdb6e431ae4b8817154bcf1f79940f2f2193a3
C++
alaneos777/club
/project euler/202.cpp
UTF-8
1,170
2.578125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; using lli = long long int; lli sgn(lli x){ if(x > 0) return 1; if(x < 0) return -1; return 0; } tuple<lli, lli, lli> extgcd(lli a, lli b){ if(b == 0){ if(a > 0) return {a, 1, 0}; else return {-a, -1, 0}; }else{ lli q = a/b; auto[d, x, y] = extgcd(b, a - b*q); return {d, y, x - y*q}; } } vector<lli> getPrimes(lli n){ vector<lli> ans; for(lli p = 2; p*p <= n; ++p){ int a = 0; while(n % p == 0){ a++; n /= p; } if(a > 0) ans.push_back(p); } if(n > 1) ans.push_back(n); return ans; } auto getDivs(lli n){ vector<lli> ans = {1}; for(lli p : getPrimes(n)){ int sz = ans.size(); for(int i = 0; i < sz; ++i){ ans.push_back(-ans[i]*p); } } return ans; } lli S(lli N){ if(N%2 == 0) return 0; lli ans = 0; lli rhs = N%3; for(lli d : getDivs((N+3)/2)){ lli mu = sgn(d); d = abs(d); auto[gcd, x, _] = extgcd(d, 3); if(rhs % gcd > 0) continue; lli step = 3/gcd; x = x * (rhs/gcd % step) % step; if(x < 0) x += step; x = x*d; lli lcm = d*step; ans += mu * ((N+1)/2 - x + lcm) / lcm; } return ans; } int main(){ cout << S(12017639147ll) << "\n"; return 0; }
true
485e6bffd9c3b70fed32e8682f1f6338b5add0a8
C++
kopasxa/CppHomeWork
/MyThirthyHomeWork/func.6/func.6.cpp
UTF-8
509
3.09375
3
[ "MIT" ]
permissive
// Написать функцию, которая проверяет, является ли переданное ей число простым? Число называется простым, // если оно делится без остатка только на себя и на единицу. #include <iostream> using namespace std; void prosto(int number) { if (number % number == 0 && number / 1 == number) { cout << "chislo prostoe) "; } } int main() { prosto(-34); }
true
beacf82f873cddcd83160ae343e415fb8efc3ab8
C++
bklimt/StudentInfo
/StudentInfo.cpp
UTF-8
1,356
2.671875
3
[]
no_license
/* * StudentInfo.cpp * * This class is the application itself. It is derived * from CWinApp like any MFC application * */ #include "StudentInfo.h" #include "MainWindow.h" // main MDI window for the application #include "LoginDlg.h" // dialog to let users log in #include "User.h" // object that represents a user #include "Preferences.h" // the app's set of preferences #include "StorageController.h" // instantiate the applications object CStudentInfo app; // declare all global objects CStorageController storage; CPreferences preferences; CMainWindow* mainWnd; CUser user; // called when the application is run // InitInstance() is equivalent to main() BOOL CStudentInfo::InitInstance() { string exePath = __argv[0]; int filePos = exePath.find_last_of( '\\' ); if ( filePos >= 0 ) { exePath = exePath.substr( 0, filePos+1 ); } preferences.SetHomePath( exePath ); preferences.LoadPreferences(); // show the login dialog CLoginDlg login; login.DoModal(); // create the main window mainWnd = new CMainWindow(); mainWnd->Create(); mainWnd->MoveWindow( preferences.GetRect( "MainWindowRect" ), FALSE ); mainWnd->ShowWindow( preferences.GetInt( "MainWindowState" ) ); mainWnd->UpdateWindow(); // tell MFC it is the main window m_pMainWnd = mainWnd; return TRUE; // so the application will continue running }
true
75c95de5e21c3408f1fe4e8a17e9051148465ff8
C++
xuancanhit99/vs-big-repo
/OPP Tren Lop/Bai 4_2_1/CL_N1.h
UTF-8
1,143
2.9375
3
[]
no_license
#ifndef cl_n_h #define cl_n_h #include <iostream> #include <string> #include <vector> using namespace std; class Cl_N1 { string NAME; public: Cl_N1(string name); virtual void SetStr(); }; class Cl_N2 : public Cl_N1 { string NAME; public: Cl_N2(string name) : Cl_N1(name) { NAME = name; } void SetStr(); }; class Cl_N3 : public Cl_N1 { string NAME; public: Cl_N3(string name) : Cl_N1(name) { NAME = name; } void SetStr(); }; class Cl_N4 : public Cl_N1 { string NAME; public: Cl_N4(string name) : Cl_N1(name) { NAME = name; } void SetStr(); }; class Cl_N5 : public Cl_N1 { string NAME; public: Cl_N5(string name) : Cl_N1(name) { NAME = name; } void SetStr(); }; class Cl_N6 : public Cl_N2, public Cl_N3 { string NAME; public: Cl_N6(string name) : Cl_N2(name), Cl_N3(name) { NAME = name; } void SetStr(); }; class Cl_N7 : public Cl_N4, public Cl_N5 { string NAME; public: Cl_N7(string name) : Cl_N4(name), Cl_N5(name) { NAME = name; } void SetStr(); }; class Cl_N8 : Cl_N6, Cl_N7 { public: string NAME; Cl_N8(string name) : Cl_N6(name), Cl_N7(name) { NAME = name; } void SetStr(); }; #endif
true
3123328eed772e93658080d280dd8536ca3ca03b
C++
david-guerrero/MITK
/MITK/Modules/MitkExt/DataManagement/mitkSet.h
UTF-8
5,546
2.9375
3
[]
no_license
#ifndef mitkSet_H #define mitkSet_H #include <itkDataObject.h> #include <itkCommand.h> #include <mitkCommon.h> #include <vector> #include <set> #include "mitkSetObserver.h" namespace mitk { /// /// A class that acts like a weak pointer /// but for a list of itk objects /// template <class T> class Set: virtual public itk::Object { public: typedef mitk::SetObserver<T> Observer; mitkClassMacro(Set<T>, itk::Object); itkFactorylessNewMacro(Set<T>); Set() { } /// /// clears this set, copies over all elements from otherSet /// void Copy( mitk::Set<T>* otherSet ) { this->Clear(); for(unsigned int i=0; i< otherSet->GetSize(); ++i) { this->Add( otherSet->Get(i) ); } } bool Add ( const T& obj ) { if(this->Has(obj)) // this is a set! do not add twice return false; // add it now m_Objects.push_back(obj); // if index is not valid any more, just add // the element // subscribe for modified event typename itk::MemberCommand<mitk::Set<T> >::Pointer _modifiedCommand = itk::MemberCommand<mitk::Set<T> >::New(); _modifiedCommand->SetCallbackFunction(this , &Set<T>::OnObjectModified); m_ObjectModifiedTags[obj] = obj->AddObserver(itk::ModifiedEvent(), _modifiedCommand); // subscribe for delete event typename itk::MemberCommand<mitk::Set<T> >::Pointer _DeleteCommand = itk::MemberCommand<mitk::Set<T> >::New(); _DeleteCommand->SetCallbackFunction(this , &Set<T>::OnObjectModified); m_ObjectDeleteTags[obj] = obj->AddObserver(itk::DeleteEvent(), _DeleteCommand); for(typename std::set<SetObserver<T>*>::iterator it = m_SetObserver.begin(); it != m_SetObserver.end(); ++it) (*it)->OnAdded(obj); this->Modified(); return true; } bool Remove ( const T& obj ) { return this->Remove(this->IndexOf(obj)); } bool Remove ( int index ) { if( !this->IsValid(index) ) // element must exist to be removed return false; typename std::vector<T>::iterator it = m_Objects.begin(); std::advance(it, index); T& obj = *it; for(typename std::set<SetObserver<T>*>::iterator it2 = m_SetObserver.begin(); it2 != m_SetObserver.end(); ++it2) (*it2)->OnRemove(*it); // remove it now obj->RemoveObserver(m_ObjectModifiedTags[obj]); obj->RemoveObserver(m_ObjectDeleteTags[obj]); m_ObjectModifiedTags.erase(obj); m_ObjectDeleteTags.erase(obj); m_Objects.erase(it); this->Modified(); return true; } void Clear () { while(m_Objects.size() > 0) this->Remove(m_Objects.size()-1); } unsigned int GetSize() const { return m_Objects.size(); } int IndexOf(const T& obj) const { int index = -1; typename std::vector<T>::const_iterator it = m_Objects.begin(); for(unsigned int i=0; i<m_Objects.size(); ++i) { if(m_Objects.at(i) == obj) { index = i; break; } } return index; } bool Has(const T& obj) const { return this->IndexOf(obj) != -1; } bool IsEmpty() const { return m_Objects.empty(); } bool IsValid( int index ) const { if(index >= 0) { return m_Objects.size() > 0 && static_cast< unsigned int > (index) < m_Objects.size(); } return false; } T& Front() { return m_Objects.front(); } T& Back() { return m_Objects.back(); } T& Get( unsigned int index ) { return m_Objects.at(index); } const T& Front() const { return m_Objects.front(); } const T& Back() const { return m_Objects.back(); } const T& Get( unsigned int index ) const { return m_Objects.at(index); } void AddObserver( SetObserver<T>* observer ) const { m_SetObserver.insert( observer ); } void RemoveObserver( SetObserver<T>* observer ) const { m_SetObserver.erase( observer ); } void OnObjectModified(const itk::Object* caller , const itk::EventObject &event) { unsigned int i=0; for(; i<m_Objects.size(); ++i) if( static_cast<itk::Object*>(m_Objects.at(i)) == caller ) break; const itk::DeleteEvent* delEvent = dynamic_cast<const itk::DeleteEvent*>(&event); // inform listeners for(typename std::set<SetObserver<T>*>::iterator it = m_SetObserver.begin(); it != m_SetObserver.end(); ++it) delEvent ? (*it)->OnDelete( this->Get(i) ) : (*it)->OnModified( this->Get(i) ); // remove from list if object was deleted (no dangling pointers) if(delEvent) { this->Remove(i); } } Set(const Set<T>& other) { *this = other; } Set<T>& operator= (const Set<T>& other) { // do not simply copy -> because of observer objects // instead: use add method for each element of the other List for(int i=0; i<other.GetSize(); ++i) this->Add( other.Get(i) ); return *this; } virtual ~Set() { this->Clear(); } protected: /// /// Holds all objects /// std::vector<T> m_Objects; /// /// holds the list of observed itk objects (will be updated in setat()) /// mutable std::set<SetObserver<T>*> m_SetObserver; /// /// \brief Holds all tags of Modified Event Listeners. /// std::map<const T, unsigned long> m_ObjectModifiedTags; /// /// \brief Holds all tags of Modified Event Listeners. /// std::map<const T, unsigned long> m_ObjectDeleteTags; }; } // namespace mitk #endif // mitkSet_H
true
197efb41715620798e79261e6017c863cd773ed2
C++
Maximillio/Entropy
/entropymodel.h
UTF-8
2,657
2.546875
3
[]
no_license
#ifndef ENTROPYMODEL_H #define ENTROPYMODEL_H #include <entropyengine.h> #include <memory> #include <chrono> #include <ctime> #include <ratio> #include <QAbstractListModel> #include <QDebug> #include <QColor> #include <QTimer> using namespace std::chrono; class EntropyModel : public QAbstractListModel { Q_OBJECT Q_PROPERTY(float windowHeight MEMBER m_windowHeight READ windowHeight NOTIFY m_windowHeightChanged) Q_PROPERTY(float windowWidth MEMBER m_windowWidth READ windowWidth NOTIFY m_windowWidthChanged) Q_PROPERTY(int itemSpeed MEMBER m_itemSpeed READ itemSpeed WRITE setItemSpeed NOTIFY m_itemSpeedChanged) Q_PROPERTY(int itemSize MEMBER m_itemSize READ itemSize) Q_PROPERTY(bool isRunning MEMBER m_isRunning READ isRunning WRITE setIsRunning NOTIFY m_isRunningChanged) Q_PROPERTY(int itemCount READ itemCount NOTIFY itemCountChanged) public: EntropyModel(); ~EntropyModel(); int rowCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; QHash<int, QByteArray> roleNames() const override; //Getters float windowWidth() const; float windowHeight() const; int itemSpeed() const; bool isRunning() const; int itemCount() const; int itemSize() const; //Setters void setItemSpeed(int itemSpeed); void setIsRunning(bool isRunning); signals: void m_windowHeightChanged(const float& _windowHeight); void m_windowWidthChanged(const float& _windowWight); void m_itemSpeedChanged(const int& _itemSpeed); void m_isRunningChanged(const bool& _isRunning); void itemCountChanged(const int& _itemCount); public slots: bool isItem(int _x, int _y); void createItem(int _x, int _y); void destroyItem(int _x, int _y); void changeItemColor(int _x, int _y); void clearAll(); private slots: void updateData(); private: int m_frameDelay; std::unique_ptr<EntropyEngine> m_engine; std::unique_ptr<QTimer> m_frameClock; duration<double> m_timeElapsed; high_resolution_clock::time_point m_timeBefore; high_resolution_clock::time_point m_timeAfter; float m_windowHeight; float m_windowWidth; int m_itemSpeed; int m_itemSize; bool m_isRunning; }; #endif // ENTROPYMODEL_H
true