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
2ba3265a7e0cc378d189b6b264545aa9616a0ff5
C++
arp5/crackingthecodinginterview
/arrays_string/anagrams?.cpp
UTF-8
732
3.375
3
[]
no_license
//Write a method to decide if two strings are anagrams or not. // O(n) + O(nlogn) time complexity and O(1) space. #include <iostream> #include <map> using namespace std; bool areanagrams(string s1, string s2){ if(s1.size()==0 || s2.size()==0){ cout << "Invalid empty string " <<endl; } sort(s1.begin(),s1.end()); sort(s2.begin(), s2.end()); if(s1.size()!=s2.size())return false; for(int i=0;i<s1.size();i++){ if(s1[i]!=s2[i])return false; } return true; } /*bool areanagDS(string s1, string s2){ map<char, int>m; for(int i=0;i<s1.size();i++){ if(m.find(s1[i])!=m.end())m[s1[i]]++; else m[s1[i]]=1; } for(int j=0;j<s2.size();j++){ if(m.) } }*/ int main(){ cout << areanagrams("", "") <<endl; return 0; }
true
46fc1b46e565d5061bfbe4367a7007d227410923
C++
dudelka/udp_server
/src/file.cpp
UTF-8
1,615
3.21875
3
[]
no_license
#include "file.h" #include "utils.h" #include <algorithm> #include <exception> #include <utility> File::File(const std::string& filename, const uint16_t package_size) : filename_(filename), file_size_(0){ std::fstream file(filename); if (!file.is_open()) { throw std::runtime_error("Can't open file with filename: " + filename + "\n"); } DivideIntoChunks(file, package_size); file.close(); } void File::DivideIntoChunks(std::fstream& file, const uint16_t package_size) { uint32_t current_idx = 1; while (!file.eof()) { std::vector<unsigned char> chunk; chunk.reserve(package_size); for (uint16_t i = 0; i < package_size; ++i) { if (!file.eof()) { unsigned char c; file >> c; chunk.push_back(c); } } file_size_ += chunk.size(); chunk.shrink_to_fit(); chunks_.push_back({current_idx++, std::move(chunk)}); } } uint32_t File::CalculateChecksum() { uint32_t crc = 0; for (const auto& chunk : chunks_) { crc = crc32c(crc, chunk.data.data(), chunk.data.size()); } checksum_ = crc; return checksum_; } void File::AddChunk(File::FileChunk&& chunk) { chunks_.push_back(std::move(chunk)); } void File::Sort() { std::sort( begin(chunks_), end(chunks_), [](const FileChunk& lhs, FileChunk& rhs) { return lhs.seq_number < rhs.seq_number; } ); } std::string File::GetName() const { return filename_; } size_t File::GetFileSize() const { return file_size_; } size_t File::GetChunksCount() const { return chunks_.size(); } std::vector<File::FileChunk> File::Data() const { return chunks_; } uint32_t File::GetChecksum() const { return checksum_; }
true
6cb829f8c040de74490a6c7074d688a880a0ece2
C++
alberot11/1-DAM
/ED/exercise7to9/TextWithoutA.cpp
UTF-8
507
3.671875
4
[]
no_license
#include <iostream> using namespace std; /*Program that asks the user to enter a text iteratively until he/she types a text with no 'a' or 'A' symbols in it.*/ int main() { string text; bool isItA; do { cout << "Type any text: "; cin >> text; isItA = false; for (unsigned int i=0 ; i < text.length() ; i++) { if (text [i] == 'a') { isItA = true; } } } while (isItA == true); }
true
e0f874866962c99675aba9c523e5460b7c18ab7d
C++
jrubin11/space_race
/Cart_Point.h
UTF-8
695
2.984375
3
[]
no_license
#ifndef CART_POINT_H #define CART_POINT_H #include "Cart_Vector.h" #include <iostream> using namespace std; //cart_point class class initialization class Cart_Point { public: //public member variables double x; double y; //constructors Cart_Point(); Cart_Point(double inputx, double inputy); //friend overloaded operator friend ostream& operator<<(ostream& out, const Cart_Point& cart); }; //non-member functions including overloaded operators double cart_distance(const Cart_Point& p1, const Cart_Point& p2); Cart_Point operator+(const Cart_Point& p1, const Cart_Vector& v1); Cart_Vector operator-(const Cart_Point& p1, const Cart_Point& p2); #endif
true
ba9244694b9da93be35423a173ad72d33b46f907
C++
CetinFurkan/MENTOL_SmartWatch_Project
/Sources/SmartWatch_Firmware/DRAW_Text.ino
UTF-8
2,021
2.765625
3
[]
no_license
void drawChar(char c, int8_t x, int8_t y) { int8_t ch; word temp; temp = ((c - fontOffset) * ((fontXsize / 8) * fontYsize)) + 4; //4 is for the first property data for (int8_t j = 0; j < fontYsize; j++) { for (int zz = 0; zz < (fontXsize / 8); zz++) { ch = pgm_read_byte(&fontData[temp + zz]); for (int8_t i = 0; i < 8; i++) { if ((ch & (1 << (7 - i))) != 0) drawPixel(x + i + (zz * 8) , y + j , colorText); } } temp += (fontXsize / 8); } } void setCurrentFont(fontdatatype* font) { fontData = font; fontXsize = font[0]; fontYsize = font[1]; fontOffset = font[2]; fontNumchars = font[3]; } void drawString(char *string, int16_t x, int16_t y) { uint8_t stl = strlen( string ); for (uint8_t i = 0; i < stl; i++) drawChar(*string++, x + (i * (fontXsize)), y); } void drawString(char *string, int16_t x, int16_t y, uint16_t col) { setTextColor(col); drawString(string, x, y); } void drawNumber(long num, int x, int y, int length, char filler, uint16_t col) { setTextColor(col); drawNumber(num,x,y,length,filler); } void drawNumber(long num, int x, int y, int length, char filler) { char buf[25]; char st[27]; boolean neg = false; int c = 0, f = 0; if (num == 0) { if (length != 0) { for (c = 0; c < (length - 1); c++) st[c] = filler; st[c] = 48; st[c + 1] = 0; } else { st[0] = 48; st[1] = 0; } } else { if (num < 0) { neg = true; num = -num; } while (num > 0) { buf[c] = 48 + (num % 10); c++; num = (num - (num % 10)) / 10; } buf[c] = 0; if (neg) { st[0] = 45; } if (length > (c + neg)) { for (int i = 0; i < (length - c - neg); i++) { st[i + neg] = filler; f++; } } for (int i = 0; i < c; i++) { st[i + neg + f] = buf[c - i - 1]; } st[c + neg + f] = 0; } drawString(st, x, y); }
true
d27a082e1b5d61e7e4352e9953b3e4b0e8ad2115
C++
Yogesh-ulgebra/Laptop-in-C-
/All_c++.cpp
UTF-8
10,338
3.140625
3
[]
no_license
#include<iostream> #include<string> #include<list> #include<stack> #include<vector> using namespace std; void c(string s){ cout<<s; } void print_repeat(int count,string c){ for(int j=0;j<count;j++) cout<<c; } bool checkNumeric(char c){ return (c>='0' && c<='9'); } void getInput(string message,string * var){ c(message); getline(cin,*var); } void getInput(string message,int * var){ c(message); cin>>*var; } void getInput(string * var){ getInput("Enter a string : ",var); } void getInput(int * var){ getInput("Enter a number : ",var); } void parseArray(string str,list<int> *v){ int i,k=0; for(i=0;i<str.length();i++){ if(checkNumeric(str[i])){ k=(k*10)+(str[i]-'0'); } else{ if(k==0){ continue; } v->push_back(k); k=0; } if(i==str.length()-1){ v->push_back(k); } } } int str_len(string s){ int i=0; while(s[i]!='\0') i++; return i; } int string_size(){ string str; getInput(&str); cout<<str_len(str); return 0; } int parseInt(char c){ return ((checkNumeric(c))?(c-'0'):0); } int parseInt(string str){ int i,str_value=0; for(i=0;i<str_len(str);i++){ if(checkNumeric(str[i])){ str_value=(str_value*10)+parseInt(str[i]); } } return str_value; } void sortIint(int *arr,int length,bool ascend){ int i,j,temp; for(i=0;i<length;i++){ for(j=0;j<length;j++){ if((ascend)?(arr[i]>arr[j]):(arr[i]<arr[j])){ temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } } } } void printArray(int *arr,int length){ for(int i=0;i<length;i++){ cout<<arr[i]<<" "; } } string lettersOnly(string str){ int i,length=str_len(str); string newString=""; for(i=0;i<length;i++){ if(str[i]>='A' && str[i]<='z'){ newString+=str[i]; } } return newString; } string sortString(string str,bool ascend){ str=lettersOnly(str); int i,j,length=str_len(str); char temp; for(i=0;i<length;i++){ for(j=0;j<length;j++){ if((ascend)?(str[i]>str[j]):(str[i]<str[j])){ temp=str[i]; str[i]=str[j]; str[j]=temp; } } } return str; } int main___(){ string str; getInput(&str); bool ascending=0; cout<<sortString(str,ascending); } int main_int(){ int arr[]={4,56,2,1}; int arr_length=sizeof(arr)/sizeof(int); bool ascending=1; sortIint(arr,arr_length,ascending); printArray(arr,arr_length); } int main_i(){ string str; getInput(&str); cout<<str<<"-1 value is "<<(parseInt(str)-1); return 0; } bool palindrome(int orig){ int rev_num=0; int temp_num=orig; while(temp_num>0){ rev_num=(rev_num*10)+(temp_num%10); temp_num/=10; } return (orig==rev_num); } bool palindrome(string str){ int i,strlen=str_len(str); for(i=0;i<strlen/2;i++){ if(str[i]!=str[strlen-1-i]){ return false; } } return true; } void printResult(string str,bool success,string question){ cout<<str<<" is "<<((success)?"":"not ")<<question; } void printResult(int num,bool success,string question){ cout<<num<<" is "<<((success)?"":"not ")<<question; } bool ope_Close(string str){ int i,length=str_len(str),cou_nt=0,f=0; int open=0,close=0,err=0; vector<int>start; vector<int>closed; vector<int>diff; for(i=0;i<length;i++){ if(str[i]=='('){ open++; f++; start.push_back(i); } if(str[i]==')'){ close++; if(f==0){ err=1; continue; } f--; cou_nt++; closed.push_back(i); } } for(auto j=0;j<start.size();j++){ auto num=closed[j]-start[j]; diff.push_back(num); cout<<start[j]<<" "; cout<<closed[j]<<endl; } for(auto k=0;k<diff.size();k++){ cout<<diff[k]; } // cout<<"( - "<<open<<endl<<") - "<<close<<endl<<"closed count - "<<cou_nt<<endl; return (f==0 && err==0); } bool openClose(string str){ int i,length=str_len(str); stack<char> squre; stack<char> circle; stack<char> curly; for(i=0;i<length;i++){ switch (str[i]){ case '[': squre.push('['); break; case '(': circle.push('('); break; case '{': curly.push('{'); break; case ']': if(squre.empty()){ return false; } else squre.pop(); break; case ')': if(circle.empty()){ return false; } else circle.pop(); break; case '}': if(curly.empty()){ return false; } else curly.pop(); break; } } if(!squre.empty() || !circle.empty() || !curly.empty()) return false; return true; } string sub_str(string str,int start,int closed){ string sub_string=""; for(int i=start;i<=closed;i++){ sub_string+=str[i]; } return sub_string; } bool checkIfStrExist(string *str,int len,string str_val){ for(int i=0;i<len;i++){ if(str[i]==str_val){ return true; } } return false; } bool allClosesOpen(string str){ int i,length=str_len(str),open_count=0; list<char>circle; int fail=0,diff=0,max_position=0,min_position=0,max_diff=0,min_diff=1; vector<int>start; vector<int>closed(str.length(),-1); vector<int>open; bool initialized=false; for(i=0;i<length;i++){ switch (str[i]){ case '(': start.push_back(i); circle.push_back('('); open.push_back(open_count++); break; case ')': if(circle.empty()){ fail++; } else{ circle.pop_back(); closed[open.back()]=i; open.pop_back(); } break; } } for(auto j=0;j<start.size();j++){ if(closed[j]<0){ continue; } diff=closed[j]-start[j]; if(!initialized){ min_diff=diff; max_diff=diff; initialized=true; } if(max_diff<diff){ max_diff=diff; max_position=j; } if(min_diff>diff){ min_diff=diff; min_position=j; } } string printed[start.size()]; string printNow; int k=0; for(int l=0;l<start.size();l++){ printNow=sub_str(str,start[l],closed[l]); if(!checkIfStrExist(printed,k,printNow)){ printed[k++]=printNow; cout<<k<<" matched "<<printed[k-1]<<"\n\n"<<endl; } } cout<<"Min matched "<<sub_str(str,start[min_position],closed[min_position])<<endl; cout<<"Max matched "<<sub_str(str,start[max_position],closed[max_position])<<endl; if(!circle.empty() || fail!=0) return false; return true; } int main_parnthise(){ string str; getInput("Enter code : ",&str); printResult(str,allClosesOpen(str),"closed"); } string multiChar(char c,int len){ string str=""; for(int i=0;i<len;i++) str+=c; return str; } void crossString(string str){ char c=' '; int i,length=str_len(str),end_len,front_len,middle_len,k; k=length/2; middle_len=end_len=length; front_len=k-1; for(int i=0;i<length;i++){ if(i==k){ if(length%2==0) continue; else front_len++; } if(i<=k){ end_len--; middle_len-=2; cout<<multiChar(c,i)<<((k==i)?'\0':str[i])<<multiChar(c,middle_len)<<str[end_len]<<multiChar(c,i)<<endl; } if(i>k){ front_len--; middle_len+=2; cout<<multiChar(c,front_len)<<str[front_len]<<multiChar(c,middle_len)<<str[i]<<multiChar(c,front_len)<<endl; } } } int main(){ string str; getInput(&str); crossString(str); return 0; } int pow(int num,int x){ int result=1; for(int i=1;i<=x;i++){ result*=num; } return result; } string intToString(int num,int length){ char c; string str=""; while(length>0){ length-=1; c=num/pow(10,length); num-=(c*pow(10,length)); c+='0'; str+=c; } return str; } int intLength(int num){ int i=0; while(num>0){ num/=10; i++; } return i; } int main_inttostr(){ int num,length; getInput(&num); length=intLength(num); cout<<intToString(num,length); return 0; } int main_p(){ string str; getInput(&str); printResult(str,palindrome(str),"palindrome"); return 0; } int main__(){ int num; getInput(&num); printResult(num,palindrome(num),"palindrome"); return 0; } int main_o() { int k=0,i; string str,next_print; list <int> arr; list <int> odd; list <int> eve; getInput(&str); parseArray(str,&arr); int final_size=arr.size(); auto arr_list_pointer=arr.begin(); for(int a=0;a<final_size;a++){ if(a%2==0){ odd.push_back(*arr_list_pointer++); }else{ eve.push_back(*arr_list_pointer++); } } odd.sort(); eve.sort(); odd.reverse(); auto odd_list_pointer=odd.begin(); auto even_list_pointer=eve.begin(); for(int a=0;a<final_size;a++){ if(a%2==0){ cout<<*odd_list_pointer++; }else{ cout<<*even_list_pointer++; } cout<<((a<final_size-1)?",":""); } return 0; }
true
319c0f912913918e1e61cc5f14a804ca80b88db9
C++
dyachenkoab/Calendar
/src/data.h
UTF-8
688
2.515625
3
[]
no_license
#ifndef DATA_H #define DATA_H #include <QDate> #include <QDebug> #include <QObject> #include <QTime> struct Note { Q_GADGET Q_PROPERTY( QString name MEMBER m_name ) Q_PROPERTY( QTime time MEMBER m_time ) public: QString m_name; QTime m_time; Note() {} Note( const QString &_name, const QTime &_time ) { m_name = _name; m_time = _time; } ~Note() = default; }; Q_DECLARE_METATYPE( Note ) class Data : public QObject { Q_OBJECT QMultiHash<QDate, Note> data; void initTestData(); public: explicit Data( QObject *parent = nullptr ); public slots: QList<Note> getNotes( const QDate &date ); }; #endif // DATA_H
true
ccf0fd51947e0b1f8b2e2bb1f86846f29b7b2b8f
C++
emakryo/cmpro
/src/arc102/d.cpp
UTF-8
673
2.625
3
[]
no_license
#include<iostream> #include<iomanip> //#include<cstdio> #include<vector> #include<map> #include<queue> #include<algorithm> #include<cmath> #include<cassert> using namespace std; typedef long long ll; int L; struct edge { int s,t,w; }; int main(){ cin >> L; int r=0; while((1<<(r+1))<=L) r++; int k=1<<r; vector<edge> g; for(int i=0; i<r; i++){ g.push_back({i, i+1, 0}); g.push_back({i, i+1, 1<<i}); } for(int i=r-1; i>=0; i--){ if(k+(1<<i)-1 < L){ g.push_back({i, r, k}); k += (1<<i); } } cout << r+1 << " " << g.size() << endl; for(int i=0; i<g.size(); i++){ cout << g[i].s+1 << " " << g[i].t+1 << " " << g[i].w << endl; } return 0; }
true
b6ac2f007e52d7a742ff0840c4c69e9ff1d64ba1
C++
spcl/perf-taint
/tests/unit/dataflow/nested_function_call.cpp
UTF-8
3,295
2.59375
3
[ "BSD-3-Clause" ]
permissive
// RUN: %clangxx %cxx_flags %s -emit-llvm -o %t1.bc // RUN: %opt %opt_flags < %t1.bc 2> /dev/null > %t1.tainted.bc // RUN: %llc %llc_flags < %t1.tainted.bc > %t1.tainted.o // RUN: %clangxx %link_flags %t1.tainted.o -o %t1.exe // RUN: %execparams %t1.exe 10 10 10 > %t1.json // RUN: diff -w %s.json %t1.json // RUN: %jsonconvert %t1.json > %t2.json // RUN: diff -w %s.processed.json %t2.json // RUN: %opt %opt_flags %opt_cfsan < %t1.bc 2> /dev/null > %t2.tainted.bc // RUN: %llc %llc_flags < %t2.tainted.bc > %t2.tainted.o // RUN: %clangxx %link_flags %t2.tainted.o -o %t2.exe // RUN: %execparams %t2.exe 10 10 10 > %t3.json // RUN: diff -w %s.json %t3.json // RUN: %jsonconvert %t3.json > %t4.json // RUN: diff -w %s.processed.json %t4.json #include <cstdlib> #include "perf-taint/PerfTaint.hpp" int global = 12; int f(int x) { int tmp = 0; for(int i = 0; i < x; ++i) tmp += i; return tmp; } int g(int x) { int tmp = 0; for(int i = 0; i < x; ++i) tmp += f(x); return tmp; } // simply adds a third loop level int single_nest(int x, int y) { int tmp = 0; for(int i = x; i < global; ++i) for(int j = 0; j < y; ++j) tmp += f(i); return tmp; } // effectively create a 4d loop // g should appear as 2d loop // and f should appear as 1d loop int double_nest(int x, int y) { int tmp = 0; for(int i = x; i < global; ++i) for(int j = y; j < global; ++j) tmp += g(j); return tmp; } //// function call outside of loop //// add as a multipath int double_nest_outside(int x, int y) { int tmp = g(x); for(int i = x; i < global; ++i) for(int j = 0; j < y; ++j) tmp += i; return tmp; } // add two loops as multipath and two calls in the same function (diff func) int multipath_nest(int x, int y) { int tmp = 0; for(int i = x; i < global; ++i) { tmp += g(x); for(int j = 0; j < y; ++j) tmp += i; tmp += f(y); } return tmp; } // create two instances - one where g is called with param and one without int multipath_nest(int x, int y, int z) { int tmp = 0; for(int i = x; i < global; ++i) { tmp += g(z); for(int j = 0; j < y; ++j) tmp += i; } return tmp; } // aggregate two loops int aggregate_nest(int x, int y) { int tmp = 0; for(int i = x; i < global; ++i) { int val = i == x ? x : x + y; tmp += g(val); for(int j = 0; j < y; ++j) tmp += i; } return tmp; } int unimportant_function(int x) { return 2 * f(x); } int call_unimportant_function(int x, int y) { int tmp = 0; for(int i = x; i < global; ++i) { tmp += i; } tmp += unimportant_function(x + y); return tmp; } int main(int argc, char ** argv) { int x1 EXTRAP = atoi(argv[1]); int x2 EXTRAP = atoi(argv[2]); int x3 = atoi(argv[3]); perf_taint::register_variable(&x1, VARIABLE_NAME(x1)); perf_taint::register_variable(&x2, VARIABLE_NAME(x2)); single_nest(x1, x2); double_nest(x1, x2); double_nest_outside(x1, x2); multipath_nest(x1, x2); multipath_nest(x1, x2, x1 + x2); multipath_nest(x1, x2, x3); aggregate_nest(x1, x2); call_unimportant_function(x1, x2); return 0; }
true
27368798dab51f57b45f019e2d54ec639833e6a6
C++
Sumendra2906/DS-ALGO
/1-10/6 Array Challenges/biggest_number.cpp
UTF-8
629
3.28125
3
[]
no_license
#include <iostream> #include <string> #include <algorithm> using namespace std; bool compare(string a, string b) { //we compare ab and ab string ab = a.append(b); string ba = b.append(a); return ab > ba; } int main() { int t; cin >> t; int n; while (t > 0) { t--; cin >> n; string *ar = new string[n]; for (int i = 0; i < n; i++) { cin >> ar[i]; } sort(ar, ar + n, compare); for (int i = 0; i < n; i++) { cout << ar[i]; } cout << endl; delete[] ar; } return 0; }
true
b2ba120acc8b60a95f5093e77d963c232559cd6b
C++
LuckPsyduck/CPP-Example
/C++ Primer/C++ Primer&05/Example&5.5.cpp
GB18030
700
3.21875
3
[]
no_license
#include<iostream> #include<string> using namespace std; int main()//Ҫţȼ { int grade; cout << " input score : \n"; cin >> grade; if (grade < 0 || grade>100) { cout << "illegal\n"; return -1; } if (grade == 100) { cout << "a++" << endl; return -1; } if (grade < 60) { cout << "f\n"; return -1; } int iu = grade / 10; int it = grade % 10; string score, level, lettergrade; if (iu == 9) score = "a"; else if (iu == 8) score = "b"; else if (iu == 7) score = "c"; else score = "d"; if (it < 3) level = "-"; else if (it > 7) level = "+"; else level = " "; lettergrade = score + level; cout <<lettergrade << endl; return 0; }
true
47202ee77095b13c449dd4b55c8aa28660dd9843
C++
acc3xa/TowerOptimization
/DEMReader/Map.cpp
UTF-8
2,665
3.515625
4
[]
no_license
#include "Map.h" Map::Map() { //Size the map appropriately theMap.resize(15); for (int i = 0; i < 15; ++i) theMap[i].resize(15); } Map::~Map() { } void Map::firstInsert(string s){ //Buid the grid for first Lat/Long section vector<vector<short>>* gridptr; vector<vector<short>> grid; grid.resize(1201); for (int i = 0; i < 1201; ++i) grid[i].resize(1201); gridptr = &grid; //Open and read in file ifstream file(s.c_str(), std::ios::in | std::ios::binary); if (!file.is_open()){ cerr << "The file did not open correctly" << endl; exit(-1); } unsigned char buffer[2]; for (int i = 0; i < 1201; ++i) { for (int j = 0; j < 1201; ++j) { if (!file.read(reinterpret_cast<char*>(buffer), sizeof(buffer))) { std::cout << "Error reading file!" << std::endl; exit(-1); } grid[i][j] = (buffer[0] << 8) | buffer[1]; } } //Store this first grid in middle of map and lable the center var accordingly theMap[7][7] = gridptr; string sy = s.substr(1, 2); centerLat = atoi(sy.c_str()); string sx = s.substr(4, 3); centerLong = atoi(sx.c_str()); cout << "The center of your Map is at: " << endl; cout << centerLat << "N" << endl; cout << centerLong << "W" << endl; } void Map::insertGrid(string s){ //Buid the grid for Lat/Long section vector<vector<short>>* gridptr; vector<vector<short>> grid; grid.resize(1201); for (int i = 0; i < 1201; ++i) grid[i].resize(1201); gridptr = &grid; //Open and read in file ifstream file(s.c_str(), std::ios::in | std::ios::binary); if (!file.is_open()){ cerr << "The file did not open correctly" << endl; exit(-1); } unsigned char buffer[2]; for (int i = 0; i < 1201; ++i) { for (int j = 0; j < 1201; ++j) { if (!file.read(reinterpret_cast<char*>(buffer), sizeof(buffer))) { std::cout << "Error reading file!" << std::endl; exit(-1); } grid[i][j] = (buffer[0] << 8) | buffer[1]; } } //Read the cordinates in file name and find the position according to relation to center string sy = s.substr(1, 2); int thisy = atoi(sy.c_str()); string sx = s.substr(4, 3); int thisx = atoi(sx.c_str()); int ydifference = centerLat - thisy; int xdifference = centerLong - thisx; cout << "Differnce between Latitudes: " << ydifference << endl; cout << "Difference between Long: " << xdifference << endl; //Store this first grid in middle of map and lable the center var accordingly theMap[7+xdifference][7-ydifference] = gridptr; } int Map::getCenterLat(){ return centerLat; } int Map::getCenterLong(){ return centerLong; } vector<vector<short>>* Map::returngrid(int xdiff, int ydiff){ return theMap[7 + xdiff][7 - ydiff]; }
true
2a1ce1ac5c14f616f0a5ffcd3d1f8c3489e781f4
C++
Strawberry9583/LeetCode
/Challenge/July_LeetCoding_Challenge/Day16_pow/Day16_pow/Day16_pow.cpp
UTF-8
858
3.390625
3
[]
no_license
#include<iostream> #include<algorithm> #include<unordered_map> using namespace std; class Solution { public: double myPow(double x, int n) { long int times = std::abs(n); std::unordered_map<int, double> archive; archive[0] = 1.0; archive[1] = x; auto result = get_pow(archive, x, times); if (n < 0) { result = 1. / result; } return result; } double get_pow(std::unordered_map<int, double>& archive, double x, long int times) { if (archive.find(times) != archive.end()) { return archive[times]; } else { long int mid = times / 2; if (times & 1) { archive[times] = get_pow(archive, x, mid) * get_pow(archive, x, mid + 1); return archive[times]; } else { archive[times] = get_pow(archive, x, mid)*get_pow(archive, x, mid); return archive[times]; } } } }; int main() { cin.get(); return 0; }
true
4537d6ad9f7606e7901fe2cbd9ca978a9e84b13c
C++
specialtactics/leetcode-2020-30day
/week1/maximum-subarray-recursion.cpp
UTF-8
2,514
3.296875
3
[]
no_license
This works I believe, but it got time limit exceeded, so we need to make it smarter class Solution { public: vector<int>::iterator end; int maxSubArray(vector<int>& nums) { vector<int>::iterator it = nums.begin(); this->end = nums.end(); return recurse(*it, *it, ++it); } int recurse(int highestSum, int currentSum, vector<int>::iterator it) { // End recursion if (it == this->end) { return highestSum; } // Get current value and next iterator int currentValue = *it; int newSum = currentSum + currentValue; ++it; // Try both options int startOver = recurse(highestSum, currentValue, it); int keepAdding = recurse(highestSum, newSum, it); // Figure out which option is best, and handle all the special cases int newResult = max(max(max(max(currentSum, keepAdding), startOver), newSum), currentValue); // If we have a better result, pass it up if (newResult > highestSum) { highestSum = newResult; } return highestSum; } }; With a cool-off static const int COLD_LIMIT = 5; class Solution { public: vector<int>::iterator end; int maxSubArray(vector<int>& nums) { vector<int>::iterator it = nums.begin(); this->end = nums.end(); return recurse(*it, *it, ++it, 0); } int recurse(int highestSum, int currentSum, vector<int>::iterator it, int coldness) { // End recursion if (it == this->end || coldness == COLD_LIMIT) { return highestSum; } // Get current value and next iterator int currentValue = *it; int newSum = currentSum + currentValue; ++it; // Have a concept of whether we are getting warmer or colder to a new best result if (newSum < currentSum) { ++coldness; } // Try both options int startOver = recurse(highestSum, currentValue, it, 0); int keepAdding = recurse(highestSum, newSum, it, coldness); // Figure out which option is best, and handle all the special cases int newResult = max(max(max(max(currentSum, keepAdding), startOver), newSum), currentValue); // If we have a better result, pass it up if (newResult > highestSum) { highestSum = newResult; } return highestSum; } };
true
7ce6e7028b80bcabafe5d031c487b9dc5a0e4989
C++
skotlowski/Learning
/C++/Course/Lesson 6/main.cpp
UTF-8
317
2.875
3
[]
no_license
#include <iostream> #include <stdlib> using namespace std; int populacja=1, godziny=0; int main() { while(populacja<=1000000000) { godziny++; populacja=populacja*2; cout<<"minelo godzin: " <<godziny<<endl; cout<<"liczba bakterii: " <<populacja<<endl; } return 0; }
true
2f0467e65a9eac617d6c8c0c451ec17b557a94ee
C++
seungjae-yu/Algorithm-Solving-BOJ
/kimug2145/12787/12787.cpp14.cpp
UTF-8
1,110
2.75
3
[]
no_license
#include <iostream> #include <algorithm> #include <string> #include <cmath> using namespace std; typedef unsigned long long ll; int tc, type; #define CV 256 int main() { scanf("%d", &tc); while (tc--) { scanf("%d", &type); if (type == 1) { //ip -> ll string inp; cin >> inp; string tmp = ""; ll arr[10] = { 0, }; int idx = 0; for (int i = 0; i < inp.size(); i++) { if (inp[i] != '.') tmp += inp[i]; else { arr[idx++] = stoi(tmp), tmp = ""; } } arr[idx] = stoi(tmp); ll ans = 0; for (int i = 0; i < 8; i++) { ans += arr[i] * (ll)pow(CV, 7 - i); } cout << ans << "\n"; } if (type == 2) { //ll ->ip ll inp; cin >> inp; ll pp = 0; ll arr[10] = { 0, }; while (true) { if (inp >= pow(CV, pp)) pp++; else break; } pp--; int idx = 7; while (inp) { ll tmp = inp / pow(CV, pp); arr[idx - pp] = tmp; inp = inp - tmp * (ll)pow(CV, pp); pp--; } for (int i = 0; i < 7; i++) cout << arr[i] << "."; cout << arr[7] << "\n"; } } }
true
59690c2ca172455b1d3b8a676e6d39218d124a51
C++
Gismo359/GLEE
/src/drawing/Line.hpp
UTF-8
4,273
2.625
3
[]
no_license
// // Created by braynstorm on 2/12/18. // #ifndef GLEE_LINE_HPP #define GLEE_LINE_HPP #include "../Utils.hpp" #include <glm/glm.hpp> #include <GL/glew.h> #include <GL/gl.h> #include <vector> #include <string> #include <type_traits> #include <exception> namespace glee { using glm::vec2; using glm::vec4; GLuint createVBOLine(bool); class Line { void updateVertices() const; void updateColors() const; public: explicit Line(Line&&) noexcept; Line(const Line&) noexcept; Line& operator=(Line&&) noexcept; Line& operator=(const Line&) noexcept; template<typename Vec2_t, typename = std::enable_if_t<std::is_assignable<Vec2_t, vec2>::value>> explicit Line(Vec2_t&& start, Vec2_t&& end, bool dynamic = false) noexcept: _vbo{ createVBOLine(dynamic) }, _startVertex{ std::forward<Vec2_t>(start) }, _endVertex{ std::forward<Vec2_t>(end) } { updateVertices(); updateColors(); } template<typename Vec2_t, typename = std::enable_if_t<std::is_assignable<Vec2_t, vec2>::value>> Line& setStartVertex(Vec2_t&& vertex) noexcept { _startVertex = std::forward<Vec2_t>(vertex); updateVertices(); return *this; } template<typename Vec2_t, typename = std::enable_if_t<std::is_assignable<Vec2_t, vec2>::value>> Line& setEndVertex(Vec2_t&& vertex) noexcept { _endVertex = std::forward<Vec2_t>(vertex); updateVertices(); return *this; } template<typename Vec2_t, typename = std::enable_if_t<std::is_assignable<Vec2_t, vec2>::value>> Line& setEndPoints(Vec2_t&& start, Vec2_t&& end) noexcept { _startVertex = std::forward<Vec2_t>(start); _endVertex = std::forward<Vec2_t>(end); updateVertices(); return *this; }; Line& setColors(uint32_t startARGB, uint32_t endARGB) noexcept { _startColor = argbToVec4(startARGB); _endColor = argbToVec4(endARGB); updateColors(); return *this; } Line& setStartColor(uint32_t startARGB) noexcept { _startColor = argbToVec4(startARGB); updateColors(); return *this; } Line& setEndColor(uint32_t endARGB) noexcept { _endColor = argbToVec4(endARGB); updateColors(); return *this; } template<typename Vec4_t, typename = std::enable_if_t<std::is_assignable<vec4, Vec4_t>::value> > Line& setColors(Vec4_t&& startARGB, Vec4_t&& endARGB) noexcept { _startColor = std::forward<Vec4_t>(startARGB); _endColor = std::forward<Vec4_t>(endARGB); updateColors(); return *this; } template<typename Vec4_t, typename = std::enable_if_t<std::is_assignable<Vec4_t, vec4>::value>> Line& setStartColor(Vec4_t&& startARGB) noexcept { _startColor = std::forward<Vec4_t>(startARGB); updateColors(); return *this; } template<typename Vec4_t, typename = std::enable_if_t<std::is_assignable<Vec4_t, vec4>::value>> Line& setEndColor(Vec4_t&& endARGB) noexcept { _endColor = std::forward<Vec4_t>(endARGB); updateColors(); return *this; } const vec2& getStartVertex() const noexcept { return _startVertex; } const vec2& getEndVertex() const noexcept { return _endVertex; } const vec4& getStartColor() const noexcept { return _startColor; } const vec4& getEndColor() const noexcept { return _endColor; } const vec2& operator[](int index) const { if (index == 0) { return _startVertex; } if (index == 1) { return _endVertex; } throw std::exception{ }; } void draw() const noexcept; ~Line(); private: GLuint _vbo; vec2 _startVertex; vec2 _endVertex; vec4 _startColor{ 1.0, 1.0, 1.0, 1.0 }; vec4 _endColor{ 1.0, 1.0, 1.0, 1.0 }; }; } #endif //GLEE_LINE_HPP
true
2a507320dfd4dccc860073fd2b17aef2498643b6
C++
kid7st/Leetcode
/210-Course-Schedule-II/solution.cpp
UTF-8
829
2.78125
3
[]
no_license
class Solution { public: vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) { vector<vector<int>> edges(numCourses, vector<int>{}); vector<int> indegree(numCourses, 0); for(auto edge : prerequisites){ edges[edge.second].push_back(edge.first); ++indegree[edge.first]; } vector<int> res; queue<int> q; for(int i = 0; i < numCourses; i++) if(indegree[i] == 0) q.push(i); while(!q.empty()){ int v = q.front(); q.pop(); res.push_back(v); for(int next : edges[v]) if((--indegree[next]) == 0) q.push(next); } if(res.size() == numCourses) return res; else return vector<int>{}; } };
true
b15ac8fbb78082365bb11894a3c11a452e03e687
C++
robotroman/code_for_robot
/include/robot.h
UTF-8
7,037
2.953125
3
[]
no_license
#ifndef ROBOT_H #define ROBOT_H #include "leg.h" #include "stdafx.h" #include "servo.h" #include "camera.h" #include "point3d.h" //!\brief The class robot controls every proccess on robot. It opens the port for connection, generates and controls gaits,legs movement. //!\brief It includes commands: \sa move_legs_to_xyz \sa zero \sa gen_traj \sa walk \sa maestroGetMovingState //!\sa robot_canon_posit \sa crawling \sa fastwalk \sa legs_speed \sa walk_forwards \sa walk_sidewalk \sa kick_the_ball //!\sa robot class robot constructor //!\sa ~robot class robot deconstructor //!\class robot inherites from class stdafx \sa stdafx class robot:public stdafx { private: int gen_traj( std::vector <point3d>nodes, int side_of_robot,float factor=1); //!< using given values of nodes,sets initial positions of legs for crawling gait //!< indicator to class camera \sa \class camera leg* legs_indicator[6]; //!< indicator to class leg \sa \class leg std::vector <point3d> traj_crawling; //!< point3d(3 dimensional) vector with points of trajectory for crawl gait std::vector <point3d> forward_points; //!< the point3d (3 dimensional) vector variable, which has points in the appropriate order to walk forward std::vector <point3d> backwards_points; //!< the point3d (3 dimensional) vector variable, which has points in the appropriate order to walk backward std::vector <point3d> turn_points_left; //!< the point3d (3 dimensional) vector variable, which has points in the appropriate order to turn left std::vector <point3d> turn_points_right; //!< the point3d (3 dimensional) vector variable, which has points in the appropriate order to turn right std::vector <point3d> sidewalk_left_points; //!< the point3d (3 dimensional) vector variable, which has points in the appropriate order to walk left side std::vector <point3d> sidewalk_right_points; //!< the point3d (3 dimensional) vector variable, which has points in the appropriate order to walk right side vector <point3d> create_default_nodes(int direction,float beta); //!< contains default nodes and creates trajectories for different ways of movement double size_of_step_forwards,size_of_step_sidewalk; //!< the size of step calculated in centimeters for one leg for forwards/backwards/sidewalk gait int crawling(std::vector <point3d> nodes, std::vector <point3d> nodes2,int k,float factor_left_leg=1, float factor_right_leg=1); //!< crawl gait. The default value of sample is 18 and it could not be changed int tripod(int number, std::vector <point3d> nodes, std::vector <point3d> nodes2, int m,int k,float factor_left_leg=1, float factor_right_leg=1); //!< robot tripod gait. 3 possibilities of movement: forwards/backwards and turn public: robot(); camera* cam; //!< class robot constructor std::vector <point3d>left_side_nodes; std::vector <point3d>right_side_nodes; std::vector <point3d>create_nodes(int no,float a, float b, float c); //!< creates from given by the user points, nodes for left side and right side int move_legs_to_xyz(double x, double y, double z); //!< inverse kinematics. Moves each leg to x, y, z points given by the user int zero(); //!< turns off robot void walk( int gait , int direction ,int samples, int iteration, int speed,float beta, float factor_left_leg=1, float factor_right_leg=1); //!< moves robot with desired gait, direction, speed, samples and iteration //robot walk int maestroGetMovingState(int fd); //!< this command is used to determine if the servo has reached their target or is still changing int robot_canon_posit(); //!< moves legs to canonical position. Sets servos value 0,0,90 degrees for each leg int legs_speed(int speed); //!< sets the desired speed for legs int walk_forwards(int gait,double dis_from_ball,int speed, float beta=1,float factor_left_leg=1, float factor_right_leg=1); //!< moves robot forward/backward with desired gait,calculated distances in class camera int walk_sidewalk(int gait,int probe,double dis_from_cent,int speed,int prep_for_ball, float beta=1, float factor_left_leg=1, float factor_right_leg=1); //!< moves robot left or right with desired gait, calculated distance and value of probe in the class camera void kick_the_ball(int probe); //!< it kicks the ball after the robot tracked it and moved towards its direction void go_to_the_ball(int gait,int speed,float beta=1,float factor_left_leg=1, float factor_right_leg=1); //!< it moves robot to the ball using functions walk_forwards and walk_sidewalk, distances calculated in class camera and kicks the ball void pos_for_walk(int probe,std::vector <point3d> nodes, std::vector <point3d> nodes2,int beta); //!< sets legs to position to walk forwards or sidewalk for tripod gait void up_and_down(int probe); //!< the robot rises up in order to walk forwards or lowers down in order to turn around or go sideways //!\enum gait It allows to choose the gait //! Two types of gait: tripod(fast) and crawl(slow) //! struct gait{ int tripod=0; int crawl=1; }rgait ; //!\enum direction It allows to choose the direction of gait //! Six types of direction:forwards,backwards,turn left,turn right, walk left side, walk right side //! struct direction { int forwards=0; int backwards=1; int turn_left=2; int turn_right=3; int sidewalk_left=4; int sidewalk_right=5; } rdirection; //! virtual ~robot(); //!< class robot deconstructor }; #endif // ROBOT_H
true
03dcd42823af39309024e7f449a5ae3d9f6317ca
C++
UrsuDanAndrei/CentralNews
/utils.cpp
UTF-8
3,482
2.75
3
[]
no_license
#include "utils.h" int get_parsed_messages(int sockfd, std::vector<std::string>& msgs) { int ret_code; /* variabila utilaza pentru a marca cazul in care caracterul '\0' (finalul unui mesaj) nu a fost citit in buffer-ul anterior si trebuie citit in buffer-ul curent */ static bool trail_0 = false; char buffer[BUFF_SIZE + 5]; memset(buffer, 0, sizeof(buffer)); /* s-au primit date pe unul din socketii de client, asa ca serverul trebuie sa le receptioneze */ ret_code = recv(sockfd, buffer, BUFF_SIZE - 1, 0); DIE(ret_code < 0, "recv"); int recv_info_size = ret_code; if (ret_code == 0) { // clientul s-a deconectat return -1; } int msg_offset = 0; format* msg; /* se separa mesajele unite de TCP in buffer si daca un mesaj nu este primit in intregime se citeste de pe socket pana la completarea lui */ while (msg_offset < recv_info_size) { /* trateaza cazul in care caracterul '\0' (finalul unui mesaj) nu a fost citit in buffer-ul anterior si trebuie citit in buffer-ul curent */ if (trail_0) { memcpy(buffer, buffer + 1, sizeof(buffer) - 1); --recv_info_size; trail_0 = false; /* trateaza cazul in care '\0' este singurul caracter citit in buffer-ul curent */ if (recv_info_size == 0) { break; } } msg = (format *) (buffer + msg_offset); uint16_t len = 0; /* trateaza cazul in care separarea s-a facut exact intre cei 2 octeti care definesc dimensiunea mesajului urmator */ if (msg_offset == recv_info_size - 1) { // se plaseaza primul byte memcpy(&len, (buffer + msg_offset), 1); // se citeste de pe socket memset(buffer, 0, sizeof(buffer)); ret_code = recv(sockfd, (buffer + 1), BUFF_SIZE - 1, 0); DIE(ret_code < 0, "recv"); recv_info_size = ret_code + 1; // se plaseaza al doilea byte memcpy((((char*)(&len)) + 1), (buffer + 1), 1); // se reseteaza offset-ul si pointer-ul catre buffer msg = (format *) buffer; msg_offset = 0; } else { len = msg->len; } int read_len = strlen(msg->content); std::string str_msg(msg->content); /* daca mesajul a fost continut in intregime in buffer se continua cu identificarea si separarea urmatorului mesaj */ if (read_len == len - 3) { msgs.push_back(str_msg); msg_offset += len; continue; } /* daca mesajul nu a fost continut in intregime in buffer se realizeaza citiri de pe socket pana cand mesajul este integru */ while (read_len != len - 3) { // se citeste un nou buffer memset(buffer, 0, sizeof(buffer)); ret_code = recv(sockfd, buffer, BUFF_SIZE - 1, 0); DIE(ret_code < 0, "recv"); recv_info_size = ret_code; str_msg = str_msg + std::string(buffer); read_len += strlen(buffer); // se seteaza offset-ul in noul buffer citit msg_offset = strlen(buffer) + 1; } msgs.push_back(str_msg); } // update trail_0 if (msg_offset > recv_info_size) { trail_0 = true; } else { trail_0 = false; } return msgs.size(); }
true
9e888741953d60bd5eee8aabe69c586689c4c09c
C++
15831944/pre2006
/VisualStudioProjects/VC7/password/PasswordManage/PasswordManage/PasswordManager/PasswordManager.cpp
GB18030
5,379
2.53125
3
[]
no_license
#include "StdAfx.h" #include "PasswordManager.h" #include <fstream> CPasswordManager::CPasswordManager(void) { m_szFile = _T("password.pwd"); m_pEncrypterManager = NULL; m_Head.MajorVerson = 1; m_Head.MinorVerson = 0; #ifdef UNICODE m_Head.nUnicode = 1; #else m_Head.nUnicode = 0; #endif // #ifdef UNICODE m_Head.Extend = 0; PASSWORD_DATA data; data.szPassword = _T("ok"); data.szTitle = _T("oktitle"); data.time = time(NULL); m_Passwords[data.szTitle] = data; data.szTitle = _T("kk"); data.szPassword = _T("pass"); data.szDescription = _T("bb"); data.szKey = _T("key"); data.time = 189; m_Passwords[data.szTitle] = data; } CPasswordManager::~CPasswordManager(void) { } int CPasswordManager::SetEncrypterManager(CEncrypterManager * pMng) { if(pMng) { m_pEncrypterManager = pMng; return S_OK; }// if(pMng) return S_FALSE; } int CPasswordManager::ClearData() { try { m_Passwords.clear(); } catch(...) { return S_FALSE; }; return S_OK; } int CPasswordManager::GetFirstPassword(POSITION & pos) { pos = m_Passwords.begin(); return S_OK; } int CPasswordManager::GetNextPassword(PASSWORD_DATA & data, POSITION & pos) { if(pos != m_Passwords.end()) { data = pos->second; pos++; return S_OK; }// if(pos != m_Passwords.end()) return S_FALSE; } int CPasswordManager::InsertPassword(const tstring & szTitle, const PASSWORD_DATA & data) { std::pair < std::map < tstring, PASSWORD_DATA > ::iterator, bool > ret; ret = m_Passwords.insert(make_pair(szTitle, data)); return ret.second; } int CPasswordManager::GetPassword(const tstring & szTitle, PASSWORD_DATA & data) { std::map < tstring, PASSWORD_DATA > ::iterator it; it = m_Passwords.find(szTitle); if(m_Passwords.end() == it) { return S_FALSE; }// if(m_Passwords.end == it) data = it->second; return S_OK; } int CPasswordManager::DeletePassword(const tstring & szTitle) { try { m_Passwords.erase(szTitle); } catch (...) { return S_FALSE; } return S_OK; } int CPasswordManager::LoadFile(LPCTSTR lpszFile) { CEncrypter * pEncrypter = m_pEncrypterManager->GetEncrypter(_T("default")); if(NULL == pEncrypter) { return S_FALSE; }// if(NULL == pEncrypter) std::ifstream in(lpszFile); if(!in) { TRACE(_T("ļ,:")); return S_FALSE; } // if(!in) //ļͷ FILE_HEAD head; in.read((char * )&head, sizeof(FILE_HEAD)); //ԭڴе ClearData(); // while(!in.eof()) { PASSWORD_DATA data; char * pBuf = NULL; ReadFile(&pBuf, &in); data.szTitle = (LPCTSTR)pBuf; ReadFile(&pBuf, &in); data.szPassword = (LPCTSTR)pBuf; ReadFile(&pBuf, &in); data.szDescription = (LPCTSTR)pBuf; ReadFile(&pBuf, &in); data.szKey = (LPCTSTR)pBuf; ReadFile(&pBuf, &in); data.time = (time_t)*pBuf; m_Passwords[data.szTitle] = data; } // while(!in.eof()) in.close(); in.clear(); return S_OK; } int CPasswordManager::OutFile(LPCTSTR lpszFile) { int nRet = 0; std::ofstream out(lpszFile); if(!out) { TRACE(_T("ļ[%s]\n"), lpszFile); return S_FALSE; }// if(!out) //дļͷ out.write((char * )&m_Head, sizeof(FILE_HEAD)); //дļ std::map < tstring, PASSWORD_DATA > ::iterator it; for(it = m_Passwords.begin(); it != m_Passwords.end(); it++) { nRet = WriterFile((char * )it->second.szTitle.c_str(), sizeof(TCHAR)*(1 + it->second.szTitle.size()), &out); if(S_FALSE == nRet) { break; } // if(S_FALSE == nRet) nRet = WriterFile((char * )it->second.szPassword.c_str(), sizeof(TCHAR)* (1 + it->second.szPassword.size()), &out); if(S_FALSE == nRet) { break; }// if(S_FALSE == nRet) nRet = WriterFile((char * )it->second.szDescription.c_str(), sizeof(TCHAR)* (1 + it->second.szDescription.size()), &out); if(S_FALSE == nRet) { break; }// if(S_FALSE == nRet) nRet = WriterFile((char * )it->second.szKey.c_str(), sizeof(TCHAR)*(1 + it->second.szKey.size()), &out); if(S_FALSE == nRet) { break; }// if(S_FALSE == nRet) nRet = WriterFile((char * )&(it->second.time), sizeof(time_t), &out); if(S_FALSE == nRet) { break; } // if(S_FALSE == nRet) } // for(it = m_lstPassword.begin(); it != m_lstPassword.end(); it++) out.close(); out.clear(); return S_OK; } int CPasswordManager::WriterFile(char * pBuf, const int nLen, std::ofstream * pOut) { int length = nLen; pOut->write((char * )&length, sizeof(int)); pOut->write(pBuf, length); return S_OK; } int CPasswordManager::ReadFile(char ** pBuf, std::ifstream * pIn) { int nRet = S_OK; const int length = 256; static char * pb = NULL; static char buf[length]; int nLen = 0; pIn->read((char * )&nLen, sizeof(nLen)); if(nLen > length) { if(NULL != pb && buf != pb) { delete []pb; } else { pb = new char[nLen]; if(NULL == pb) { TRACE(_T("ڴʧ")); return S_FALSE; } // if(NULL == pb) }// if(NULL != pb && buf != pb) } else { pb = buf; }// if(nLen > length) pIn->read(pb, nLen); *pBuf = pb; return nRet; }
true
8a7fdd96af2a44bc750d731e49f08b7b9f25b735
C++
blackbox47/UVA-Problem-Solution-Using-C-or-C-Plus-Plus
/11137 - Ingenuous Cubrency.cpp
UTF-8
967
2.609375
3
[]
no_license
#include<stdio.h> #include<vector> #include<string.h> #define mx 20000 using namespace std; void coin(void); void pregenerate(void); long long arr[mx+10]; vector<long long>v; int main(void) { long long a,i,j,var,tem; coin(); pregenerate(); while(scanf("%lld", &a)==1) { printf("%lld\n", arr[a]); } return 0; } void pregenerate(void) { long long i,j,var,tem; arr[0]=1; for(i=0;i<(long long)v.size();i++) { for(j=0;j<=mx;j++) { if(arr[j]!=0) { var=j+v[i]; if(var>mx) break; arr[var]+=arr[j]; } } } // printf("%d\n", arr[a]); return ; } void coin(void) { long long i,var; for(i=1;i<25;i++) { var=i*i*i; v.push_back(var); } // for(i=0;i<(int)v.size();i++) printf("%d\n", v[i]); return ; }
true
f479b5a1c7afc3fd1f3fade92e05497b8d1926f2
C++
SeobinYun/2021_C_practice
/PuzzleBook/PuzzleBook/PuzzleBook/Operator1.cpp
UTF-8
224
2.625
3
[]
no_license
#include <stdio.h> int main(void) { int x; x = -3 + 4 * 5 - 6; printf("%d\n", x); x = 3 + 4 % 5 - 6; printf("%d\n", x); x = -3 * 4 % -6 / 5; printf("%d\n", x); x = (7 + 6) % 5 / 2; printf("%d\n", x); return 0; }
true
940783a71436be6ca96c71417c1a9e0ca0e707ad
C++
AmandineF/PMPOO
/ModelisationProjet/Algo/Algo.h
ISO-8859-1
1,703
2.921875
3
[]
no_license
#ifdef WANTDLLEXP #define DLL _declspec(dllexport) #define EXTERNC extern "C" #else #define DLL #define EXTERNC #endif #include <vector> using std::vector; class DLL Algo{ public: /*! \brief Algorithme de gnration de la carte * \param taille de la carte * \return tableau a deux dimensions d'entiers. Chaque entier correspond un type de case (Desert, Eau, Foret, Plaine ou Montagne) */ DLL static int** generationMap(int taille); /*! \brief Algorithme du placement des joueurs en dbut de jeu * \param taille de la carte * \return tableau d'entier une dimension contenant les coordonnes de dpart de chaque joueur */ DLL static int* placementJoueur(int taille); /*! \brief Algorithme de suggestion des cases o l'on peut se dplacer * \param taille de la carte * \param xActuel coordonne des abscisses correspondant la position o se trouve le personnage * \param yActuel coordonne des ordonnes correspondant la position o se trouve le personnage * \param type correspond au type du personnage selectionn (Elfe, Pirate, Nain ou Orc) * \param carteElement est un tableau d'entiers double dimension reprsentant la carte. Chaque entier correspond un type de case (Desert, Eau, Foret, Plaine ou Montagne) * \param ptMouvement correspond au nombre de points de mouvement que le personnage selectionn possde * \return un tableau de boolen deux dimensions de la taille de la carte indiquant les cases o le personnage peut se dplacer. Vrai le personnage peut se dplacer. Faux sinon. */ DLL static bool** suggestionCase(int taille, int xActuel, int yActuel, int type, int** carteElement, double ptMouvement); };
true
c818982a9a4524a950302b5d93302030844db751
C++
RuwanKarunanayake/final-staged-rhs-with-shared-memory-utilization
/bssn/cuda_gr/src/dataGeneration.cpp
UTF-8
12,065
2.96875
3
[]
no_license
/** * Created on: Sep 21, 2018 * Author: Akila, Eranga, Eminda, Ruwan **/ #include "dataGeneration.h" void data_generation_blockwise_mixed(double mean, double std, unsigned int numberOfLevels, unsigned int lower_bound, unsigned int upper_bound, bool isRandom, Block * blkList, double ** var_in_array, double ** var_out_array) { const unsigned int maxDepth=12; // Calculate block sizes std::map<int, double> block_sizes; for(int i=lower_bound; i<=upper_bound; i++){ Block blk = Block(0, 0, 0, 2*i, i, maxDepth); block_sizes[i] = 1.0*blk.blkSize*BSSN_NUM_VARS*sizeof(double)/1024/1024; } // Create distribution int seed = 100; if (isRandom) seed=time(0); std::default_random_engine generator(seed); std::normal_distribution<double> distributionN(mean, std); std::uniform_int_distribution<int> distributionU(lower_bound, upper_bound); // Generating levels and block structure int total_grid_points = 0; int p[upper_bound-lower_bound+1]; for (int i=0; i<upper_bound-lower_bound+1; i++) p[i] = 0; int level; int block_no = 0; while (block_no<numberOfLevels){ level = int(distributionN(generator)); // generate a number // distribution representation requirement if ((level>=lower_bound)&&(level<=upper_bound)) { Block & blk=blkList[block_no]; blk=Block(0, 0, 0, 2*level, level, maxDepth); blk.block_no = block_no; total_grid_points += blk.blkSize; block_no++; p[level-lower_bound]++; } } // distribution representation requirement std::cout << "---Level distribution---" << "\033[0;33m" << std::endl; double ram_requirement = 0.0; for (int i=0; i<=upper_bound-lower_bound; i++) { ram_requirement += block_sizes[i+lower_bound]*p[i]; // this is calculated in MBs std::cout << i+lower_bound << ": "; std::cout << std::setw(3) << p[i]*100/numberOfLevels << "% " << std::string(p[i]*100/numberOfLevels, '*') << std::endl; } std::cout << "\033[0m" << "Total blocks: " << block_no << " | Total grid points: " << 1.0*total_grid_points/1000000 << "x10^6" << std::endl; std::cout << "Total RAM requiremnet for input: " << ram_requirement << "MB" << std::endl; std::cout << "Total RAM requiremnet for both input/output: " << ram_requirement*2 << "MB" << std::endl; // Checking for available ram struct sysinfo myinfo; sysinfo(&myinfo); double total_MB = 1.0*myinfo.totalram/1024/1024; double available_MB = 1.0*myinfo.freeram/1024/1024; std::cout << "Total RAM: " << total_MB << "MB Available RAM: " << available_MB << "MB" << std::endl; double remaining = available_MB - ram_requirement*2; std::cout << "\nRemaining RAM if the process is going to continue: " << remaining << "MB" << std::endl; if (remaining>400){ std::cout << "Data block generating starts..." << std::endl; } else if(remaining>0){ std::cout << "Are you sure that you want to continue(Y/n):"; char sure; std::cin >> sure; if (tolower(sure)!='y') { std::cout << "Program terminated..." << std::endl; exit(0); } std::cout << "Data block generating starts..." << std::endl; }else{ std::cout << "Not enough RAM to process. Program terminated..." << std::endl; exit(0); } // Data block generation #pragma omp parallel for num_threads(20) for (int index=0; index<numberOfLevels; index++){ Block & blk=blkList[index]; const unsigned long unzip_dof=blk.blkSize; // Allocating pinned memory in RAM double * var_in_per_block; CHECK_ERROR(cudaMallocHost((void**)&var_in_per_block, unzip_dof*BSSN_NUM_VARS*sizeof(double)), "var_in_per_block"); double * var_out_per_block = new double[unzip_dof*BSSN_NUM_VARS]; CHECK_ERROR(cudaMallocHost((void**)&var_out_per_block, unzip_dof*BSSN_NUM_VARS*sizeof(double)), "var_out_per_block"); var_in_array[index] = var_in_per_block; var_out_array[index] = var_out_per_block; double coord[3]; double u[BSSN_NUM_VARS]; double x,y,z,hx,hy,hz; unsigned int size_x,size_y,size_z; x=(double)blk.x; y=(double)blk.y; z=(double)blk.z; hx=0.001; hy=0.001; hz=0.001; size_x=blk.node1D_x; size_y=blk.node1D_y; size_z=blk.node1D_z; for(unsigned int k=0; k<blk.node1D_z; k++){ for(unsigned int j=0; j<blk.node1D_y; j++){ for(unsigned int i=0; i<blk.node1D_x; i++){ coord[0]=x+i*hx; coord[1]=y+j*hy; coord[2]=z+k*hz; initial_data(u,coord); for(unsigned int var=0; var<BSSN_NUM_VARS; var++){ var_in_per_block[var*unzip_dof+k*size_y*size_x+j*size_y+i]=u[var]; } } } } } } void data_generation_blockwise_and_bssn_var_wise_mixed(double mean, double std, unsigned int numberOfLevels, unsigned int lower_bound, unsigned int upper_bound, bool isRandom, Block * blkList, double ** var_in_array, double ** var_out_array, double ** var_in, double ** var_out) { const unsigned int maxDepth=12; // Calculate block sizes std::map<int, double> block_sizes; for(int i=lower_bound; i<=upper_bound; i++){ Block blk = Block(0, 0, 0, 2*i, i, maxDepth); block_sizes[i] = 1.0*(blk.node1D_x*blk.node1D_y*blk.node1D_z)*BSSN_NUM_VARS*sizeof(double)/1024/1024; } // Create distribution int seed = 100; if (isRandom) seed=time(0); std::default_random_engine generator(seed); std::normal_distribution<double> distributionN(mean, std); std::uniform_int_distribution<int> distributionU(lower_bound, upper_bound); // Generating levels and block structure int total_grid_points = 0; int p[upper_bound-lower_bound+1]; for (int i=0; i<upper_bound-lower_bound+1; i++) p[i] = 0; int level; int block_no = 0; // RAM --- unsigned long unzipSz=0; while (block_no<numberOfLevels){ level = int(distributionN(generator)); // generate a number // distribution representation requirement if ((level>=lower_bound)&&(level<=upper_bound)) { Block & blk=blkList[block_no]; blk=Block(0, 0, 0, 2*level, level, maxDepth); blk.block_no = block_no; // RAM --- blk.offset=unzipSz; unzipSz+=blk.blkSize; total_grid_points += blk.blkSize; block_no++; p[level-lower_bound]++; } } // RAM --- const unsigned long unzip_dof_cpu=unzipSz; // distribution representation requirement std::cout << "---Level distribution---" << "\033[0;33m" << std::endl; double ram_requirement = 0.0; for (int i=0; i<=upper_bound-lower_bound; i++) { ram_requirement += block_sizes[i+lower_bound]*p[i]; // this is calculated in MBs std::cout << i+lower_bound << ": "; std::cout << std::setw(3) << p[i]*100/numberOfLevels << "% " << std::string(p[i]*100/numberOfLevels, '*') << std::endl; } std::cout << "\033[0m" << "Total blocks: " << block_no << " | Total grid points: " << 1.0*total_grid_points/1000000 << "x10^6" << std::endl; std::cout << "Total RAM requiremnet for input: " << ram_requirement << "MB" << std::endl; std::cout << "Total RAM requiremnet for both input/output: " << ram_requirement*2 << "MB" << std::endl; // RAM --- std::cout << "Total RAM requiremnet for both GPU and CPU version: " << ram_requirement*2*2 + block_sizes[upper_bound]*210/BSSN_NUM_VARS << "MB" << std::endl; // block_sizes[upper_bound]*210/BSSN_NUM_VARS this is for allocating intermediate arrays in CPU // Checking for available ram struct sysinfo myinfo; sysinfo(&myinfo); double total_MB = 1.0*myinfo.totalram/1024/1024; double available_MB = 1.0*myinfo.freeram/1024/1024; std::cout << "Total RAM: " << total_MB << "MB Available RAM: " << available_MB << "MB" << std::endl; double remaining = available_MB - ram_requirement*2*2 - block_sizes[upper_bound]*210/BSSN_NUM_VARS; std::cout << "\nRemaining RAM if the process is going to continue: " << remaining << "MB" << std::endl; if (remaining>400){ std::cout << "Data block generating starts..." << std::endl; } else if(remaining>0){ std::cout << "Are you sure that you want to continue(Y/n):"; char sure; std::cin >> sure; if (tolower(sure)!='y') { std::cout << "Program terminated..." << std::endl; exit(0); } std::cout << "Data block generating starts..." << std::endl; }else{ std::cout << "Not enough RAM to process. Program terminated..." << std::endl; exit(0); } // Data block generation #pragma omp parallel for num_threads(20) for (int index=0; index<numberOfLevels; index++){ Block & blk=blkList[index]; const unsigned long unzip_dof=(blk.node1D_x*blk.node1D_y*blk.node1D_z); // Allocating pinned memory in RAM double * var_in_per_block; CHECK_ERROR(cudaMallocHost((void**)&var_in_per_block, unzip_dof*BSSN_NUM_VARS*sizeof(double)), "var_in_per_block"); double * var_out_per_block = new double[unzip_dof*BSSN_NUM_VARS]; CHECK_ERROR(cudaMallocHost((void**)&var_out_per_block, unzip_dof*BSSN_NUM_VARS*sizeof(double)), "var_out_per_block"); var_in_array[index] = var_in_per_block; var_out_array[index] = var_out_per_block; double coord[3]; double u[BSSN_NUM_VARS]; double x,y,z,hx,hy,hz; unsigned int size_x,size_y,size_z; x=(double)blk.x; y=(double)blk.y; z=(double)blk.z; hx=0.001; hy=0.001; hz=0.001; size_x=blk.node1D_x; size_y=blk.node1D_y; size_z=blk.node1D_z; for(unsigned int k=0; k<blk.node1D_z; k++){ for(unsigned int j=0; j<blk.node1D_y; j++){ for(unsigned int i=0; i<blk.node1D_x; i++){ coord[0]=x+i*hx; coord[1]=y+j*hy; coord[2]=z+k*hz; initial_data(u,coord); for(unsigned int var=0; var<BSSN_NUM_VARS; var++){ var_in_per_block[var*unzip_dof+k*size_y*size_x+j*size_y+i]=u[var]; } } } } } // RAM --- // Data generation for CPU version for(int i=0;i<BSSN_NUM_VARS;i++){ var_in[i] = new double[unzip_dof_cpu]; var_out[i] = new double[unzip_dof_cpu]; } #pragma omp parallel for num_threads(20) for(unsigned int blk=0; blk<numberOfLevels; blk++){ double coord[3]; double u[BSSN_NUM_VARS]; Block tmpBlock=blkList[blk]; double x=(double)tmpBlock.x; double y=(double)tmpBlock.y; double z=(double)tmpBlock.z; double hx=0.001; double hy=0.001; double hz=0.001; unsigned int offset=tmpBlock.offset; unsigned int size_x=tmpBlock.node1D_x; unsigned int size_y=tmpBlock.node1D_y; unsigned int size_z=tmpBlock.node1D_z; for(unsigned int k=0;k<tmpBlock.node1D_z;k++){ for(unsigned int j=0;j<tmpBlock.node1D_y;j++){ for(unsigned int i=0;i<tmpBlock.node1D_x;i++){ coord[0]=x+i*hx; coord[1]=y+j*hy; coord[2]=z+k*hz; initial_data(u,coord); for(unsigned int var=0;var<BSSN_NUM_VARS;var++){ var_in[var][offset+k*size_y*size_x+j*size_y+i]=u[var]; var_out[var][offset+k*size_y*size_x+j*size_y+i]=0; } } } } } }
true
d9b27b3ffa0675468afa3faa5372b0a2d6919ba5
C++
rjwall/csci156
/7_11.cpp
UTF-8
655
3.8125
4
[]
no_license
#include <iostream> #include <iomanip> #include <cmath> using namespace std; const double PI = 3.14159; struct Circle { double radius; double diameter; double area; }; Circle getInfo(); int main() { Circle c; c = getInfo(); c.area = PI * pow(c.radius, 2.0); cout << "The radius and area of the circle are:\n"; cout << fixed << setprecision(2); cout << "Radius: " << c.radius << endl; cout << "Area: " << c.area << endl; return 0; } Circle getInfo() { Circle tempCircle; cout << "Enter the diameter of a circle: "; cin >> tempCircle.diameter; tempCircle.radius = tempCircle.diameter / 2.0; return tempCircle; }
true
64fc0c8104f7fdb4e9feff57417661b5299317cb
C++
resoliwan/cprimary
/l13/usedma.cpp
UTF-8
628
2.890625
3
[]
no_license
#include <iostream> #include "dma.h" using namespace std; int main() { BaseDMA b("Potabelly", 8); cout << "Displaying BaseDMA object:\n"; cout << b << endl; LacksDMA l("red", "Blimpo", 4); cout << "Displaying LacksDMA object:\n"; cout << l << endl; HasDMA h("Mercator", "Buffalo Kyes", 4); cout << "Displaying HasDMA object:\n"; cout << h << endl; LacksDMA cl(l); cout << "Result of LacksDMA copy:\n"; cout << cl << endl; HasDMA ah; ah = h; cout << "Result of HasDMA assignment:\n"; cout << ah << endl; HasDMA ch = h; cout << "Result of HasDMA copy:\n"; cout << ch << endl; return 0; }
true
fa82b7b5c655ab430464803a78a65cb0aa7bd48f
C++
xorde/xoTools
/Toolkit/helpers/CursorHelper.cpp
UTF-8
1,278
2.65625
3
[]
no_license
#include "CursorHelper.h" bool CursorHelper::m_isCustomCursorEnabled = false; QMap<QWidget*, Qt::CursorShape> CursorHelper::m_widgets = QMap<QWidget*, Qt::CursorShape>(); QMap<Qt::CursorShape, QCursor> CursorHelper::m_customCursors = QMap<Qt::CursorShape, QCursor>(); void CursorHelper::InstallCursor(Qt::CursorShape shape, QPixmap image, int x, int y) { m_customCursors.insert(shape, QCursor(image, x, y)); reassign(); } void CursorHelper::setIsCustomCursorEnabled(bool enabled) { if (m_isCustomCursorEnabled == enabled) return; m_isCustomCursorEnabled = enabled; reassign(); } bool CursorHelper::getIsCustomCursorEnabled() { return m_isCustomCursorEnabled; } void CursorHelper::setCursor(QWidget *widget, Qt::CursorShape shape) { if (!widget) return; if (m_isCustomCursorEnabled && m_customCursors.contains(shape)) { widget->setCursor(m_customCursors[shape]); } else { widget->setCursor(QCursor(shape)); } QObject::connect(widget, &QWidget::destroyed, [=]() { m_widgets.remove(widget); }); m_widgets.insert(widget, shape); } void CursorHelper::reassign() { foreach (QWidget *widget, m_widgets.keys()) { auto shape = m_widgets[widget]; setCursor(widget, shape); } }
true
44c438bc9b14399ab79da3c68955fc0c4621a44b
C++
yaoxiaoqi/Leetcode
/141 Linked List Cycle/Linked List Cycle.cpp
UTF-8
1,326
3.3125
3
[]
no_license
// // main.cpp // Leetcode // // Created by 妖小七 on 2018/11/23. // Copyright © 2018 妖小七. All rights reserved. // #include <iostream> #include <vector> #include <string> #include <algorithm> #include <cmath> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: bool hasCycle(ListNode *head) { if (head == NULL) return false; else if (head -> next == NULL) { return false; } ListNode* p = head; ListNode* q = head; do { if (p -> next != NULL) { p = p->next; } else { return false; } if (q -> next != NULL) { q = q->next; if (q->next != NULL) { q = q->next; } else { return false; } } else { return false; } } while (p != q); return true; } }; int main() { Solution s; ListNode* head = new ListNode(1); ListNode* p1 = new ListNode(2); ListNode* p2 = new ListNode(3); head->next = p1; p1->next = p2; p2->next = p1; cout << s.hasCycle(head) << endl; return 0; }
true
75fcaddee7da4689d958b3fc363748d7f2676d10
C++
mapleriver/SNLComplier
/Project/Parser.h
GB18030
7,347
2.515625
3
[]
no_license
#pragma once #include"Scanner.h" #include<list> #include<string> #include<map> #include<Token.h> struct ParseTreeNode; using Terminal = Tag; enum class Nonterminal; class Parser { private: Scanner& scanner; public: ParseTreeNode * getParseTree(); void printParseTree(ParseTreeNode * parseTree); Parser(Scanner& scan); ~Parser(); private: Token curToken; void readNextToken(); void match(Terminal expectedTer); void syntaxError(const char* errMessage); ParseTreeNode * program(); ParseTreeNode * programHead(); ParseTreeNode * declarePart(); ParseTreeNode * typeDec(); ParseTreeNode * typeDeclaration(); ParseTreeNode * typeDecList(); void typeId(ParseTreeNode * typeDecNode); void typeName(ParseTreeNode * typeDecNode); void baseType(ParseTreeNode * typeDecNode); void structureType(ParseTreeNode * typeDecNode); void arrayType(ParseTreeNode * typeDecNode); void recType(ParseTreeNode * typeDecNode); ParseTreeNode * fieldDecList(); ParseTreeNode * fieldDecMore(); void idList(ParseTreeNode * typeDecNode); void idMore(ParseTreeNode * typeDecNode); ParseTreeNode * typeDecMore(); ParseTreeNode * varDec(); ParseTreeNode * varDeclaration(); ParseTreeNode *varDecList(); ParseTreeNode * varDecMore(); void varIdList(ParseTreeNode * varDecNode); void varIdMore(ParseTreeNode * varDecNode); ParseTreeNode * procDec(); ParseTreeNode * procDeclaration(); void paramList(ParseTreeNode * procDecNode); ParseTreeNode * paramDecList(); ParseTreeNode * paramMore(); ParseTreeNode * param(); void formList(ParseTreeNode * paramDecNode); void fidMore(ParseTreeNode * paramDecNode); ParseTreeNode * procDecPart(); ParseTreeNode * procBody(); ParseTreeNode * programBody(); ParseTreeNode * stmList(); ParseTreeNode * stmMore(); ParseTreeNode * stm(); ParseTreeNode * assCall(); ParseTreeNode * callStmRest(); ParseTreeNode * actParamList(); ParseTreeNode * actParamMore(); ParseTreeNode * assignmentRest(); ParseTreeNode * conditionalStm(); ParseTreeNode * loopStm(); ParseTreeNode * inputStm(); ParseTreeNode * outputStm(); ParseTreeNode * returnStm(); ParseTreeNode * exp(); ParseTreeNode * simpleExp(); ParseTreeNode * term(); ParseTreeNode * factor(); ParseTreeNode * variable(); void variMore(ParseTreeNode * varNode); ParseTreeNode * fieldvar(); void fieldvarMore(ParseTreeNode * varNode); }; enum class Nonterminal { Program, ProgramHead, ProgramName, DeclarePart, TypeDec, TypeDeclaration, TypeDecList, TypeDecMore, TypeId, TypeName, BaseType, StructureType, ArrayType, Low, Top, RecType, FieldDecList, FieldDecMore, IdList, IdMore, VarDec, VarDeclaration, VarDecList, VarDecMore, VarIdList, VarIdMore, ProcDec, ProcDeclaration, ProcDecMore, ProcName, ParamList, ParamDecList, ParamMore, Param, FormList, FidMore, ProcDecPart, ProcBody, ProgramBody, StmList, StmMore, Stm, AssCall, AssignmentRest, ConditionalStm, StmL, LoopStm, InputStm, InVar, OutputStm, ReturnStm, CallStmRest, ActParamList, ActParamMore, RelExp, OtherRelE, Exp, OtherTerm, Term, OtherFactor, Factor, Variable, VariMore, FieldVar, FieldVarMore, CmpOp, AddOp, MultOp }; enum class ParseNodeType { PROG, PHEAD, DECPART, TYPEDEC, VARDEC, PROCDEC, STMLIST, STMT, EXP }; enum class DecType { ARRAY, CHAR, INTEGER, RECORD, ID }; enum class StmtType { IF, WHILE, ASSIGN, READ, WRITE, CALL, RETURN }; enum class ExpType { OP, CONST, VAR }; enum class VariableType { ID, ARRAYMEMB, FIELDMEMB }; enum class CheckType { VOID, INTEGER, BOOLEAN }; enum class ParamType { VALPARAM, VARPARAM }; #define MAXCHILDRENNUM 3 struct IdAttr; using SymbolTable = std::map<std::string, IdAttr>; struct ParseTreeNode { public: ParseTreeNode(){ for (int i = 0; i < MAXCHILDRENNUM; ++i) { this->children[i] = nullptr; } this->sibling = nullptr; idNum = 0; } ParseTreeNode(ParseNodeType nodeType): ParseTreeNode() { this->nodeType = nodeType; } ParseTreeNode(ParseNodeType nodeType, DecType decType) : ParseTreeNode(nodeType) { this->specificType.dec = decType; } ParseTreeNode(ParseNodeType nodeType, StmtType stmtType): ParseTreeNode(nodeType) { this->specificType.stmt = stmtType; } ParseTreeNode(ParseNodeType nodeType, ExpType expType) : ParseTreeNode(nodeType) { this->specificType.exp = expType; this->attr.exp.varType = VariableType::ID; this->attr.exp.checkType = CheckType::VOID; } ~ParseTreeNode() { for (int i = 0; i < MAXCHILDRENNUM; ++i) { delete this->children[i]; } delete this->sibling; } public: ParseTreeNode* children[MAXCHILDRENNUM]; ParseTreeNode* sibling; //int lineNo; ParseNodeType nodeType; union SpecificType { DecType dec; StmtType stmt; ExpType exp; } specificType; int idNum; std::string name[10]; SymbolTable symbolTable; union Attr{ Attr() {}; ~Attr() {}; struct{ unsigned int lowerBound; unsigned int upperBound; DecType type; }array; struct { ParamType paramType; }process; struct{ Tag op; int value; VariableType varType; CheckType checkType; }exp; std::string typeName; }attr; }; /****************************************************** **********Ҫõͼ************ ******************************************************/ /*ʶ*/ enum class IdKind {TYPE, VAR, PROC}; /*dirֱӱ(ֵ)indirʾӱ()*/ enum class AccessKind {DIR, INDIR }; /*βαĽṹ*/ struct ParamTable { SymbolTable * entry;/*ָβڷűеĵַ*/ ParamTable * next; }; /*ʶԽṹ*/ struct IdAttr { struct typeIR * idtype; /*ָʶڲʾ*/ IdKind kind; /*ʶ*/ union { struct { AccessKind access; /*жDZλֵ*/ int level; int off; bool isParam; /*жDzͨ*/ }VarAttr;/*ʶ*/ struct { int level; /*ù̵IJ*/ ParamTable * param; /**/ int mOff; /*̻¼ĴС*/ int nOff; /*spdisplayƫ*/ int procEntry; /*̵ڵַ*/ int codeEntry;/*ڱ,м*/ }ProcAttr;/*ʶ*/ }specific;/*ʶIJͬвͬ*/ }; enum class TypeKind{ intTy, charTy, arrayTy, recordTy, boolTy }; struct FieldChain { std::string id; /**/ int off; /*ڼ¼еƫ*/ typeIR * UnitType; /*гԱ*/ FieldChain * Next; }; struct typeIR { int size; /*ռռС*/ TypeKind kind; union { struct { struct typeIR * indexTy; struct typeIR * elemTy; int low; /*¼͵½*/ int up; /*¼͵Ͻ*/ }ArrayAttr; FieldChain * body; /*¼е*/ } More; };
true
1f09e2b71aa627df977dfaadd4a786869ee9186b
C++
zsuzuki/structbuilder
/cpp/sample.cpp
UTF-8
2,752
3.140625
3
[ "MIT" ]
permissive
#include "serializer.hpp" #include <cstdint> #include <iostream> #include <string> #include <vector> int main(int argc, char **argv) { try { std::cout << "Start" << std::endl; auto ser = Serializer{}; char buffer[128]; ser.initialize(buffer, sizeof(buffer)); // // number test // static constexpr int nb_num = 32; for (int i = 0; i < nb_num; i++) { ser.put<int>(i * 2); } std::cout << "put number done: " << ser.getWriteSize() << " bytes" << std::endl; for (int i = 0; i < nb_num; i++) { std::cout << " " << ser.get<int>(); } std::cout << "\nget number done: " << ser.getReadSize() << " bytes" << std::endl; // // string test // ser.reset(); std::vector<const char *> str = { "Hello, World", "Serializer is serializer", "Buffer type <char>", "serialize test program", "message of contents"}; using msg_size_t = uint8_t; for (auto s : str) { auto sz = strlen(s) + 1; ser.putBuffer<char, msg_size_t>(s, sz); } std::cout << "put string done: " << ser.getWriteSize() << " bytes" << std::endl; for (size_t i = 0; i < str.size(); i++) { auto r = ser.getBuffer<const char, msg_size_t>(); std::cout << (int)r.second << ": " << r.first << std::endl; } std::cout << "get string done: " << ser.getReadSize() << " bytes" << std::endl; ser.reset(); std::string msg1 = "String Method", msg2 = "Serializer"; std::cout << "MSG1: " << msg1 << ", MSG2: " << msg2 << ", size: " << msg1.size() << std::endl; ser.put(msg1); ser.get(msg2); std::cout << "MSG1: " << msg1 << ", MSG2: " << msg2 << ", size: " << ser.getWriteSize() << std::endl; // // bit field // NOTE: ** not aligned for test ** // struct Field { unsigned enabled : 1; unsigned index : 5; unsigned message : 10; unsigned : 14; }; ser.reset(); static constexpr msg_size_t nb_f = 5; for (int i = 0; i < nb_f; i++) { Field f{}; f.enabled = i % 3 == 0; f.index = i; f.message = 10000 - i * 144; ser.put<Field>(f); } std::cout << "put bit-field struct done: " << ser.getWriteSize() << " bytes" << std::endl; for (int i = 0; i < nb_f; i++) { auto f = ser.get<Field>(); std::cout << "F: enabled=" << f.enabled << " index=" << f.index << " message=" << f.message << std::endl; } std::cout << "get bit-field struct done: " << ser.getReadSize() << " bytes" << std::endl; } catch (std::exception &e) { std::cerr << "\n*** " << e.what() << " ***" << std::endl; } return 0; }
true
d0c3958e9bc469d539f743f84beed06e2e2d6316
C++
VARADSP/My-CPP-PROGRAMS
/celciustofarengeit.cpp
UTF-8
883
3.671875
4
[]
no_license
#include<iostream> using namespace std; #include<conio.h> #include<stdlib.h> void celtofahren(); void fahrentocel(); float celcius,fahren; int main() { int choice; do { cout << "Enter your choice for " << "\n" << "Type 1 to convert Fahrenheit to celcius " << "\n " << "2 to convert Celcius to Fahrenheit" << "\n3 to exit\n"; cin >> choice; switch(choice) { case 1 : celtofahren();break; case 2: fahrentocel();break; case 3:exit(0); } }while(choice!='3'); return 0; } void celtofahren() { cout << "Enter temp in celcius\n"; cin >> celcius; fahren=celcius*(9/5)+32; cout << "The temp is " << fahren << "\n"; } void fahrentocel() { cout << "Enter temp in fahren\n"; cin >> fahren; celcius=fahren*(5/9)-32; cout << "The temp is " << celcius << "\n"; }
true
09a45bdeba9b13bccadc8366aa39859716281ef8
C++
jaroles/Battlesnakes-V2
/Node/misc/nodemodules/Point.h
UTF-8
779
2.734375
3
[]
no_license
/* * Point.h * * Created on: Oct 25, 2012 * Author: Jure Jumalon */ #ifndef POINT_H_ #define POINT_H_ #include <stddef.h> #include <math.h> #include <memory> #include <vector> //#include "../../lib/node/src/node.h" class Point { public: Point(); virtual ~Point(); Point(float x, float y) : x_(x), y_(y) {} Point(const Point & point) : x_(point.x_), y_(point.y_) {} std::vector<std::vector<float> > rotationMatrix(float theta) const; void rotate(float theta); void translate(const Point& offset); bool inside(const Point& topLeft, const Point& bottomRight) const; std::auto_ptr<Point> clone() const; void set(float x, float y); //void get(float array[2]) const; std::vector<float> get() const; private: float x_; float y_; }; #endif /* POINT_H_ */
true
e82ae7551b1b95a0bdb67f00c647f8b8b33a21cd
C++
overflowsc/inf4715
/Sources/GameApp/MainMenu.h
UTF-8
611
2.609375
3
[]
no_license
/// /// Copyright (C) 2012 - All Rights Reserved /// All rights reserved. http://www.equals-forty-two.com /// /// @brief Declares the main menu class. /// #ifndef __MAINMENU_H__ #define __MAINMENU_H__ #include "Menu.h" // This class serves as a GUI panel to group GUI elements class MainMenu : public Menu { public: /// Default ctor MainMenu(const char* url); /// Default dtor virtual ~MainMenu(); private: /// Called when a view event occurs virtual void OnCallback(const std::string& objectName, const std::string& callbackName, const MenuArgs& args) override; }; #endif // __MAINMENU_H__
true
6dddc48c06b1109033b9d20d9084a46131e019fd
C++
MrGoumX/TowerDefense
/TowerDefense/Pirate.h
UTF-8
1,167
2.625
3
[]
no_license
#ifndef PIRATE_H #define PIRATE_H #define SECONDS_PER_TILE 1.0f #include "GeometryNode.h" #include "Renderer.h" #include "Game.h" class Pirate : public GameObject { glm::mat4 m_transformation_matrix; class GeometryNode* m_body; glm::mat4 m_body_transformation_matrix; glm::mat4 m_body_transformation_matrix_normal; class GeometryNode* m_arm; glm::mat4 m_arm_transformation_matrix; glm::mat4 m_arm_transformation_matrix_normal; class GeometryNode* m_left_foot; glm::mat4 m_left_foot_transformation_matrix; glm::mat4 m_left_foot_transformation_matrix_normal; class GeometryNode* m_right_foot; glm::mat4 m_right_foot_transformation_matrix; glm::mat4 m_right_foot_transformation_matrix_normal; glm::vec3 pos; int m_current_tile = 0; float spawn_time; int health; public: Pirate(); Pirate(float spawn_time); virtual ~Pirate(); float getTime(); static bool InitializeMeshes(); void update(Game* game) override; void draw_geometry(Renderer* renderer) override; void draw_geometry_to_shadow_map(Renderer* renderer) override; void SetPosition(glm::vec3 pos); glm::vec3 GetPosAt(float dt); glm::vec3 GetPos(); }; #endif // PIRATE_H
true
32e53c09c9a2fdae6321cae4635d5a3867ea9139
C++
snorlon/cs480Brown
/Assignment08/src/shaderloader.cpp
UTF-8
4,133
3.109375
3
[]
no_license
#include "shaderloader.h" #include "config.h" #include <iostream> using namespace std; bool shaderManager::giveLinks(config* configData) { //abort if any provided links are bogus, we NEED them if(configData == NULL) return false; simConfig = configData; //assumed success accessing links return true; } bool shaderManager::loadShaders(int argc, char **argv) { //variables std::ifstream input; int fileLength = 0; //first things first, try to load in the shader files if provided //check if we have any execution arguements if(argc > 1) { //iterate across all provided parameters for(int i = 1; i < argc; i++) { //check if this parameter is a -v for vertex shader or -f for fragment shader if(strcmp(argv[i], "-v")==0 || strcmp(argv[i], "-f")==0) { //check if we can get the next parameters if(i+1<argc) { char* tempFilename = new char[strlen(argv[i+1])+1]; strcpy(tempFilename, argv[i+1]); //store the file name //load in the vertex shader if filename is good input.clear(); input.open(tempFilename); if(input.good()) { input.seekg(0, std::ios::end); fileLength = input.tellg(); //get file size to size string input.seekg(0, std::ios::beg); if(strcmp(argv[i], "-v")==0) { vertexShader = new char[fileLength]; input.get(vertexShader, fileLength, '\0'); std::cout<<"Vertex Shader Loaded!"<<std::endl; } else { fragmentShader = new char[fileLength]; input.get(fragmentShader, fileLength, '\0'); std::cout<<"Fragment Shader Loaded!"<<std::endl; } } input.close(); } } } } //create the shaders vertex_shader = glCreateShader(GL_VERTEX_SHADER); fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); char buffer[512]; int errLength = 0; //compile the shaders GLint shader_status; // Vertex shader first glShaderSource(vertex_shader, 1, (const char **)&vertexShader, NULL); glCompileShader(vertex_shader); //check the compile status glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &shader_status); if(!shader_status) { glGetShaderInfoLog(fragment_shader, 512, &errLength, buffer); std::cerr << "[F] FAILED TO COMPILE VERTEX SHADER!" << std::endl; fprintf(stderr, "Compilation error in Vertex Shader: %s %d\n", buffer, errLength); return false; } // Now the Fragment shader glShaderSource(fragment_shader, 1, (const char **)&fragmentShader, NULL); glCompileShader(fragment_shader); //check the compile status glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &shader_status); if(!shader_status) { std::cerr << "[F] FAILED TO COMPILE FRAGMENT SHADER!" << std::endl; glGetShaderInfoLog(fragment_shader, 512, &errLength, buffer); fprintf(stderr, "Compilation error in Fragment Shader: %s\n", buffer); return false; } //Now we link the 2 shader objects into a program //This program is what is run on the GPU simConfig->program = glCreateProgram(); glAttachShader(simConfig->program, vertex_shader); glAttachShader(simConfig->program, fragment_shader); glLinkProgram(simConfig->program); //check if everything linked ok glGetProgramiv(simConfig->program, GL_LINK_STATUS, &shader_status); if(!shader_status) { std::cerr << "[F] THE SHADER PROGRAM FAILED TO LINK" << std::endl; return false; } return true; }
true
189301dd37456c83af3684b1b430ce2572354f9d
C++
icecocoa6/abc
/57/D.cpp
UTF-8
937
2.671875
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> #include <iomanip> using namespace std; long C[51][51]; int main(int argc, char *argv[]) { int N, A, B; cin >> N >> A >> B; vector<long> v(N); for (int i = 0; i < N; i++) cin >> v[i]; sort(begin(v), end(v), greater<long>()); for (int n = 0; n <= N; n++) C[n][0] = 1; for (int n = 1; n <= N; n++) for (int k = 1; k <= n; k++) C[n][k] = C[n-1][k-1] + C[n-1][k]; long sum = 0; for (int i = 0; i < A; i++) sum += v[i]; double avg = (double)sum / A; long cnt = 0; if (v[0] != v[A - 1]) { int n = 0, k = 0; for (int i = 0; i < N; i++) { if (v[i] != v[A - 1]) continue; n++; if (i < A) k++; } cnt = C[n][k]; } else { int n = 0; for (int i = 0; i < N; i++) if (v[0] == v[i]) n++; for (int k = A; k <= B && k <= n; k++) cnt += C[n][k]; } cout << fixed << setprecision(20) << avg << endl; cout << cnt << endl; return 0; }
true
f9dba3b79b8b15ea9bf7dadf75d2b853cb6d20c8
C++
suVrik/KWA
/engine/render/include/render/animation/animation_manager.h
UTF-8
1,736
2.640625
3
[]
no_license
#pragma once #include <core/containers/pair.h> #include <core/containers/shared_ptr.h> #include <core/containers/string.h> #include <core/containers/unordered_map.h> #include <core/containers/vector.h> #include <shared_mutex> namespace kw { class Animation; class Task; class TaskScheduler; struct AnimationManagerDescriptor { TaskScheduler* task_scheduler; MemoryResource* persistent_memory_resource; MemoryResource* transient_memory_resource; }; class AnimationManager { public: explicit AnimationManager(const AnimationManagerDescriptor& descriptor); ~AnimationManager(); // Enqueue animation loading if it's not yet loaded. Concurrent loads are allowed. SharedPtr<Animation> load(const char* relative_path); // O(n) where n is the total number of loaded animations. Designed for tools. const String& get_relative_path(const SharedPtr<Animation>& animation) const; // The first task creates worker tasks that load all enqueued animations at the moment. Those tasks will be finished // before the second task starts. If you are planning to load animations on this frame, you need to place your task // before the first task. If you are planning to use animations loaded on this frame, you need to place your task // after the second task. Pair<Task*, Task*> create_tasks(); private: class BeginTask; class PendingTask; TaskScheduler& m_task_scheduler; MemoryResource& m_persistent_memory_resource; MemoryResource& m_transient_memory_resource; UnorderedMap<String, SharedPtr<Animation>> m_animations; Vector<Pair<const String&, SharedPtr<Animation>>> m_pending_animations; std::shared_mutex m_animations_mutex; }; } // namespace kw
true
8f06efb30022d4825f718a6ad99232a9fc516d58
C++
ProyectoLegus/Legus
/Expresion/Expresion.h
UTF-8
1,074
2.5625
3
[]
no_license
#ifndef EXPRESION_H #define EXPRESION_H /*! \public \enum Expresiones \brief Utilizado para describir que tipo de expresion es el objeto. */ enum Expresiones { IGUALDAD, MAYOR, MAYORIGUAL, MENOR, MENORIGUAL, DISTINTO, DIVISION, DIVISIONENTERA, EXPONENCIACION, MODULO, MULTIPLICACION, OPERADORO, RESTA, SUMA, OPERADORY, LITERALBOOLEANA, LITERALCADENA, LITERALCARACTER, LITERALENTERA, LITERALFLOTANTE, NEGACION, NEGATIVO, VARIABLENORMAL, ARREGLO, FUNCION, PUERTO, SENSOR, INSTANCIADE }; /*! \enum TipoDato \brief Utilizado para describir el tipo de dato que actualmente tiene la variable. */ enum TipoDato { ENTERO, FLOTANTE, CADENA, CARACTER, BOOLEANO }; #include "Programa/Tipos/Tipo.h" #include "Programa/ExcepcionLegus.h" using namespace std; class Expresion { public: Expresion( Expresiones tipo , int numeroDeLinea); Expresiones tipo; Tipo *tipoInferido; int numeroDeLinea; virtual Tipo* validarSemantica()=0; virtual string generarCodigoJava()=0; }; #endif // EXPRESION_H
true
106af8b3593621d1c6cd183e3c33806880aeab09
C++
oscarcheng105/CS32_Coursework
/Homework3/Homework3/animal.cpp
UTF-8
1,629
3.484375
3
[]
no_license
// // animal.cpp // Homework3 // // Created by Oscar Cheng on 2020/5/4. // Copyright © 2020 Oscar Cheng. All rights reserved. // #include <string> #include <iostream> using namespace std; class Animal{ public: Animal(string str): m_name(str){}; virtual ~Animal(){}; virtual void speak() const = 0; virtual string moveAction() const = 0; string name() const {return m_name;}; private: string m_name; }; class Cat : public Animal{ public: Cat(string str):Animal(str){}; Cat(string str, int weight): Animal(str), m_weight(weight){}; virtual ~Cat() {cout<<"Destroying "<< Animal::name() <<" the cat"<<endl;}; virtual void speak() const {cout<<"Meow";}; virtual string moveAction() const {return "walk";}; private: int m_weight; }; class Pig : public Animal{ public: Pig(string str):Animal(str){}; Pig(string str, int weight): Animal(str), m_weight(weight){}; virtual ~Pig() {cout<<"Destroying "<< Animal::name() <<" the pig"<<endl;}; virtual void speak() const {if(m_weight>=160) cout<<"Grunt"; else cout<<"Oink";}; virtual string moveAction() const {return "walk";}; private: int m_weight; }; class Duck : public Animal{ public: Duck(string str):Animal(str){}; Duck(string str, int weight): Animal(str), m_weight(weight){}; virtual ~Duck() {cout<<"Destroying "<< Animal::name() <<" the duck"<<endl;}; virtual void speak() const {cout<<"Quack";}; virtual string moveAction() const {return "swim";}; private: int m_weight; };
true
1e95f1018b15645d1beb9bdeebd421ddbe979cb0
C++
digitalwizards/SparkCore-LEDMatrix-MAX7219-MAX7221
/firmware/ledmatrix-max7219-max7221.h
UTF-8
3,816
2.953125
3
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
#ifndef LEDMATRIX_h #define LEDMATRIX_h #include "Adafruit_GFX.h" class LEDMatrix : public Adafruit_GFX { public: class Bitmap { public: Bitmap(int width, int height); int getWidth(); int getHeight(); void setPixel(int x, int y, bool val); bool getPixel(int x, int y); void togglePixel(int x, int y); // allows get the whole row of pixels at once byte getByte(int id); ~Bitmap(); private: // pixels are saved as 1D byte array byte *array; int width, height; // param bytePos = which byte contains the pixel // param posInByte = index of pixel(bit) in that byte bool containsPixel(int x, int y, int *bytePos = NULL, int *posInByte = NULL); }; // = 8x8 matrix / one chip struct Matrix { // 0, 90, 180, 270 int rotation; bool mirrorX, mirrorY; // pixel [0, 0] is [firstX, firstY] for the main bitmap int firstX, firstY; // bitmap 8x8 - it's a copy of the part of the main bitmap // before transforming and flushing Bitmap *bitmap; Matrix *next; Matrix(int x = 0, int y = 0, int rotation = 0, bool mirrorX = false, bool mirrotY = false, Matrix *next = NULL); ~Matrix(); }; // a simple linked list class MatrixList { // defines the callback functions signature for method 'forEach' // it allows to transform matrixes and flush to chips typedef void (LEDMatrix::*callback)(Matrix*, int index); private: Matrix *first = NULL; int count = 0; public: void addMatrix(Matrix *matrix), forEach(callback func); int getCount(); LEDMatrix *parent; ~MatrixList(); }; // allows to send same opcode and data to all displays in spiTransfer call static const int ALL_DISPLAYS = -1; // the main bitmap - contains all pixels Bitmap *bitmap; // (pin settings is independent on HW SPI) LEDMatrix(int horizDisplays = 1, int vertDisplays = 1, int pinCLK = A0, int pinCS = A1, int pinD_OUT = A2); void // color: 0/1 or true/false drawPixel(int16_t x, int16_t y, uint16_t color), // invert the main bitmap invert(), // display: 0 is the nearest to the Spark Core shutdown(bool shutdown, int display = ALL_DISPLAYS), // intensity: 0-15 setIntensity(int intensity, int display = ALL_DISPLAYS), // rotatin: 0,90,180,270 degrees addMatrix(int x, int y, int rotation = 0, bool mirrorX = false, bool mirrorY = false), // flush the main bitmap to chips flush(); ~LEDMatrix(); private: // register address map for each MAX7219/7221 (opCodes) static const int OP_NOOP = 0, OP_DIGIT0 = 1, // == one row (byte) OP_DIGIT1 = 2, OP_DIGIT2 = 3, OP_DIGIT3 = 4, OP_DIGIT4 = 5, OP_DIGIT5 = 6, OP_DIGIT6 = 7, OP_DIGIT7 = 8, OP_DECODEMODE = 9, // no decode == 0 (useful only for 7-segment display) OP_INTENSITY = 10, // 0 - 15 (different steps for each MAX72XX) OP_SCANLIMIT = 11, // all rows == 7 (sets number of active rows / digits) OP_SHUTDOWN = 12, // turn display on == 1 OP_DISPLAYTEST = 15; // turn all LEDs on == 1 // = CLK, SS, MOSI int pinCLK, pinCS, pinD_OUT; int matrixCount; MatrixList *matrixList; void // transform 8x8 parts of the main matrix for the output // (rotating, mirroring) transform(Matrix *matrix, int index), // send transformed matrix to the output sendMatrix(Matrix *matrix, int index), // flush address with data to chips spiTransfer(byte opCode, byte data, int display = ALL_DISPLAYS); }; #endif //LEDMATRIX_h
true
10d6e1a3a4762c3839a963993f20bb74e8362c31
C++
KarolStola/DragonframeMotionController
/src/source/DragonframeMotionController.cpp
UTF-8
11,561
2.65625
3
[ "MIT" ]
permissive
#define DEBUG_LOG 0 #include "DragonframeMotionController.h" #include "DragonframeDevice.h" DragonframeMotionController::DragonframeMotionController(DragonframeDevice & dragonframeDevice) : dragonframeDevice(dragonframeDevice) , movementPositionUpdateTask(DelayedTaskTimeResolution::Milliseconds, this, & DragonframeMotionController::SendMovementPositionUpdates) { dragonframeDevice.BindAsMessageHandler(*this); movementPositionUpdateTask.Delay(movementPositionUpdateInterval); } void DragonframeMotionController::ParseInput(const String & input) { String message; for(int i = 0; i < input.length(); i++) { if (IsEndingCharacter(input[i])) { ParseMessage(message); message = ""; } else { message += input[i]; } } } void DragonframeMotionController::Update() { movementPositionUpdateTask.Update(); } char DragonframeMotionController::GetIncomingMessageDelimiter() { return incomingMessageDelimiter; } bool DragonframeMotionController::IsEndingCharacter(char character) { for(int i = 0; messageEnding[i] != '\0' ; i++) { if(character == messageEnding[i]) { return true; } } return false; } void DragonframeMotionController::SendMessage(String & message) { #if DEBUG_LOG Serial.print("RES: "); Serial.println(message); #endif dragonframeDevice.SendMessage(message); } void DragonframeMotionController::ParseMessage(String & message) { if(message.length() < 2) { return; } #if DEBUG_LOG Serial.print("MSG: "); Serial.println(message); #endif if(IsMessageHi(message)) { SendHi(); } else if (IsMessageQueryAreMotorsMoving(message)) { SendMotorMovingStatuses(); } else if(IsMessageMoveMotorTo(message)) { HandleMessageMoveMotorTo(message); } else if(IsMessageQueryMotorPosition(message)) { HandleMessageQueryMotorPosition(message); } else if(IsMessageStopMotor(message)) { HandleMessageStopMotor(message); } else if(IsMessageStopAllMotors(message)) { HandleMessageStopAllMotors(); } else if(IsMessageSetJogSpeed(message)) { HandleMessageSetJogSpeed(message); } else if(IsMessageJogMotor(message)) { HandleMessageJogMotor(message); } else if(IsMessageInchMotor(message)) { HandleMessageInchMotor(message); } else if(IsMessageZeroMotorPosition(message)) { HandleMessageZeroMotorPosition(message); } else if(IsMessageSetMotorPosition(message)) { HandleMessageSetMotorPosition(message); } } bool DragonframeMotionController::IsMessageHi(String & message) { return message.startsWith(messageHi); } bool DragonframeMotionController::IsMessageQueryAreMotorsMoving(String & message) { return message.startsWith(messageQueryAreMotorsMoving); } bool DragonframeMotionController::IsMessageMoveMotorTo(String & message) { return message.startsWith(messageMoveMotorTo); } bool DragonframeMotionController::IsMessageQueryMotorPosition(String & message) { return message.startsWith(messageQueryMotorPosition); } bool DragonframeMotionController::IsMessageStopMotor(String & message) { return message.startsWith(messageStopMotor); } bool DragonframeMotionController::IsMessageStopAllMotors(String & message) { return message.startsWith(messageStopAllMotors); } bool DragonframeMotionController::IsMessageJogMotor(String & message) { return message.startsWith(messageJogMotor); } bool DragonframeMotionController::IsMessageInchMotor(String & message) { return message.startsWith(messageInchMotor); } bool DragonframeMotionController::IsMessageSetJogSpeed(String & message) { return message.startsWith(messageSetJogSpeed); } bool DragonframeMotionController::IsMessageZeroMotorPosition(String & message) { return message.startsWith(messageZeroMotorPosition); } bool DragonframeMotionController::IsMessageSetMotorPosition(String & message) { return message.startsWith(messageSetMotorPosition); } void DragonframeMotionController::SendHi() { static String message = String(messageHi) + " " + dragonframeDevice.GetProtocolMajorVersion() + " " + dragonframeDevice.GetNumberOfAxes() + " " + dragonframeDevice.GetProtocolFullVersion() + messageEnding; SendMessage(message); } void DragonframeMotionController::SendMotorMovingStatuses() { auto reply = String(messageQueryAreMotorsMoving) + ' '; for(int i = 1; i <= dragonframeDevice.GetNumberOfAxes(); i++) { reply += dragonframeDevice.GetIsMotorMoving(i) ? '1' : '0'; } reply += messageEnding; SendMessage(reply); } void DragonframeMotionController::HandleMessageMoveMotorTo(String & message) { auto arguments = GetArguments(message); if(arguments.size() < 2) { return; } auto motor = arguments[0]; auto requestedPosition = arguments[1]; if(!IsValidMotor(motor)) { return; } auto currentPosition = dragonframeDevice.GetCurrentStep(motor); if(currentPosition == requestedPosition) { SendCurrentPosition(motor, currentPosition); } else { dragonframeDevice.MoveMotorTo(motor, requestedPosition); SendMotorMovingTo(motor, requestedPosition); } } void DragonframeMotionController::HandleMessageQueryMotorPosition(String & message) { auto arguments = GetArguments(message); if(arguments.size() < 1) { return; } auto motor = arguments[0]; if(!IsValidMotor(motor)) { return; } auto motorPosition = dragonframeDevice.GetCurrentStep(motor); SendCurrentPosition(motor, motorPosition); } void DragonframeMotionController::HandleMessageStopMotor(String & message) { auto arguments = GetArguments(message); if(arguments.size() < 1) { return; } auto motor = arguments[0]; if(!IsValidMotor(motor)) { return; } dragonframeDevice.StopMotor(motor); SendStopMotorResponse(motor); } void DragonframeMotionController::HandleMessageStopAllMotors() { dragonframeDevice.StopAllMotors(); SendStopAllMotorsResponse(); } void DragonframeMotionController::HandleMessageJogMotor(String & message) { auto arguments = GetArguments(message); if(arguments.size() < 2) { return; } auto motor = arguments[0]; auto position = arguments[1]; if(!IsValidMotor(motor)) { return; } dragonframeDevice.JogMotorTo(motor, position); SendJogMotorResponse(motor); } void DragonframeMotionController::HandleMessageInchMotor(String & message) { auto arguments = GetArguments(message); if(arguments.size() < 2) { return; } auto motor = arguments[0]; auto position = arguments[1]; if(!IsValidMotor(motor)) { return; } dragonframeDevice.InchMotorTo(motor, position); SendInchMotorResponse(motor); } void DragonframeMotionController::HandleMessageSetJogSpeed(String & message) { auto arguments = GetArguments(message); if(arguments.size() < 2) { return; } auto motor = arguments[0]; auto stepsPerSecond = arguments[1]; if(!IsValidMotor(motor)) { return; } dragonframeDevice.SetJogSpeedForMotor(motor, stepsPerSecond); SendSetJogSpeedResponse(motor, stepsPerSecond); } void DragonframeMotionController::HandleMessageZeroMotorPosition(String & message) { auto arguments = GetArguments(message); if(arguments.size() < 1) { return; } auto motor = arguments[0]; if(!IsValidMotor(motor)) { return; } dragonframeDevice.ZeroMotorPosition(motor); SendZeroMotorPositionResponse(motor); } void DragonframeMotionController::HandleMessageSetMotorPosition(String & message) { auto arguments = GetArguments(message); if(arguments.size() < 2) { return; } auto motor = arguments[0]; auto position = arguments[1]; if(!IsValidMotor(motor)) { return; } dragonframeDevice.SetMotorPosition(motor, position); SendSetMotorPositionResponse(motor, position); } void DragonframeMotionController::SendCurrentPosition(int motor, int currentPosition) { auto message = String(messageQueryMotorPosition) + " " + motor + " " + currentPosition + messageEnding; SendMessage(message); } void DragonframeMotionController::SendMotorMovingTo(int motor, int requestedPosition) { auto message = String(messageMoveMotorTo) + " " + motor + " " + requestedPosition + messageEnding; SendMessage(message); } void DragonframeMotionController::SendStopMotorResponse(int motor) { auto message = String(messageStopMotor) + " " + motor + messageEnding; SendMessage(message); } void DragonframeMotionController::SendStopAllMotorsResponse() { auto message = String(messageStopAllMotors) + messageEnding; SendMessage(message); } void DragonframeMotionController::SendJogMotorResponse(int motor) { auto message = String(messageJogMotor) + " " + motor; + messageEnding; SendMessage(message); } void DragonframeMotionController::SendInchMotorResponse(int motor) { auto message = String(messageInchMotor) + " " + motor + messageEnding; SendMessage(message); } void DragonframeMotionController::SendSetJogSpeedResponse(int motor, int stepsPerSecond) { auto message = String(messageSetJogSpeed) + " " + motor + " " + stepsPerSecond + messageEnding; SendMessage(message); } void DragonframeMotionController::SendZeroMotorPositionResponse(int motor) { auto message = String(messageZeroMotorPosition) + " " + motor + messageEnding; SendMessage(message); } void DragonframeMotionController::SendSetMotorPositionResponse(int motor, int position) { auto message = String(messageSetMotorPosition) + " " + motor + " " + position + messageEnding; SendMessage(message); } bool DragonframeMotionController::IsValidMotor(int motorIndex) { return motorIndex <= dragonframeDevice.GetNumberOfAxes(); } void DragonframeMotionController::SendMovementPositionUpdates() { for(int i = 1; i <= dragonframeDevice.GetNumberOfAxes(); i++) { if(dragonframeDevice.GetIsMotorMoving(i)) { SendCurrentPosition(i, dragonframeDevice.GetCurrentStep(i)); } } movementPositionUpdateTask.Delay(movementPositionUpdateInterval); } std::vector<int> DragonframeMotionController::GetArguments(String & message) { std::vector<int> arguments; auto currentIndex = argumentsStartIndex; while(currentIndex < message.length()) { auto currentArgument = message.substring(currentIndex).toInt(); auto argumentDigits = GetNumberOfDigitsIn(currentArgument); currentIndex += argumentDigits + 1; arguments.push_back(currentArgument); } return arguments; } int DragonframeMotionController::GetNumberOfDigitsIn(int number) { int numberOfDigits = 0; while(number > 0) { number /= 10; numberOfDigits++; } return numberOfDigits; }
true
c95b74ad60469e76610d8b09388ba0a479532187
C++
kamyu104/LeetCode-Solutions
/C++/trapping-rain-water.cpp
UTF-8
1,326
3.515625
4
[ "MIT" ]
permissive
// Time: O(n) // Space: O(1) class Solution { public: int trap(vector<int>& height) { int result = 0, left = 0, right = height.size() - 1, level = 0; while (left < right) { int lower = height[height[left] < height[right] ? left++ : right--]; level = max(level, lower); result += level - lower; } return result; } }; // Time: O(n) // Space: O(1) class Solution2 { public: int trap(vector<int>& height) { if (height.empty()) { return 0; } int i = 0, j = height.size() - 1; int left_height = height[0]; int right_height = height[height.size() - 1]; int trap = 0; while (i < j) { if (left_height < right_height) { ++i; // Fill in the gap. trap += max(0, left_height - height[i]); // Update current max height from left. left_height = max(left_height, height[i]); } else { --j; // Fill in the gap. trap += max(0, right_height - height[j]); // Update current max height from right. right_height = max(right_height, height[j]); } } return trap; } };
true
1e0924836ce8727534181b40053fa10a1a78c1ce
C++
Aeshnajain/DS-Algo
/2nd sept/test.cpp
UTF-8
315
3.03125
3
[]
no_license
#include<iostream> #include<vector> using namespace std; int XOR(int num) { long long a=1; long long b=1; long long sum=0; for(int i=0;i<num;i++) { sum+=a*a; int temp=a; a=b; b=b+temp; } return sum; } int main(int argc,char**argv) { cout<<XOR(5)<<endl; }
true
2445dc77a4ed8e2a7b0956fb98233c4683cd96f7
C++
skyser2003/Chrono-Warrior
/source/Mode/GameMode/GameMode.cpp
UTF-8
1,833
2.546875
3
[ "MIT" ]
permissive
#include "stdafx.h" #include "GameMode.h" #include "UIManager/UIManager.h" #include "Window/Window.h" #include "KeyboardInput/KeyboardInput.h" #include "MouseInput/MouseInput.h" #include "Logic/Map/Map.h" #include "Logic/FieldObject/FieldUnit/FieldUnit.h" namespace CW { GameMode::GameMode() { } GameMode::~GameMode() { } void GameMode::Initialize(const std::shared_ptr<FG::Window>& window) { Mode::Initialize(window); mMap.reset(new Map); mMap->Initialize(); currentTime = std::chrono::system_clock::now(); mSelectedUnit = nullptr; InitializeGraphics(); } void GameMode::Destroy() { Mode::Destroy(); } bool GameMode::Run() { auto now = std::chrono::system_clock::now(); auto duration = now - currentTime; currentTime = now; Update(duration); Draw(duration); return true; } void GameMode::Update(std::chrono::system_clock::duration dt) { // Keyboard input for (int keyCode : mKeyboard->GetDownKeys()) { } // Mouse input WORD x = mMouse->GetX(); WORD y = mMouse->GetY(); FG::MouseInput::BUTTON_STATE lButton = mMouse->GetLButtonState(); FG::MouseInput::BUTTON_STATE rButton = mMouse->GetRButtonState(); float wheel = mMouse->GetWheelValue(); if (lButton == FG::MouseInput::BUTTON_DOWN) { Position tilePos = GetTilePosition(x, y); auto tile = mMap->GetTile(tilePos); auto units = mMap->GetUnits(tilePos); if (tile != nullptr) { if (units.size() == 0) { mSelectedUnit = nullptr; std::shared_ptr<FieldUnit> unit(new FieldUnit); unit->SetUnitType(FieldUnit::FU_CHRONO_MAGE); unit->SetTile(tile); mMap->AddUnit(unit); } else { mSelectedUnit = units[0]; } } } // Map update mMap->ForeachTile([](Tile* tile) { }); mMap->ForeachUnit([](FieldUnit* unit) { }); } }
true
e677769812d12b59bffd6d61c42ed7f4fce504fd
C++
lopesivan/snippets
/icpc/icpc-2012-2013/uva10305.cpp
UTF-8
1,349
2.75
3
[ "MIT" ]
permissive
#include <cstdio> #include <cstring> #include <list> #define MAX (101+5) using namespace std; list<int> order; inline list<int> ::iterator find (int v, int *_v) { *_v = 0; for (list<int> ::iterator it = order.begin(); it != order.end(); ++it, ++*_v) if (*it == v) return it; return order.end(); //junk } int main() { int n, m, v, w, tmp; list<int> ::iterator it, iz; bool existe[MAX]; while( scanf("%d%d", &n, &m), n || m) { order = list<int> (); memset(existe, false, sizeof existe); for (int i = 0; i < m; ++i) { scanf("%d%d", &v, &w); if ( !(existe[v] || existe[w]) ) { order.push_back(v); order.push_back(w); existe[v] = existe[w] = true; } else if ( existe[v] && !existe[w] ) { it = find(v, &tmp); ++it; order.insert(it, w); existe[w] = true; } else if ( existe[w] && !existe[v] ) { it = find(w, &tmp); order.insert(it, v); existe[v] = true; } else { int _v, _w; it = find(v, &_v); iz = find(w, &_w); // if (iz > it) OK!! if ( _v > _w) order.splice ( iz, order, it); } } for (int i = 1; i <= n; ++i) if ( !existe[i] ) order.push_back(i); printf("%d", *(order.begin()) ); for ( it = order.begin(), ++it; it != order.end(); ++it) printf(" %d", *it); puts(""); } return 0; }
true
ca3011d333be20d4e151b33d116f836cb79471fb
C++
Arangear/The15Puzzle
/The15Puzzle/Coursework1/Solver.cpp
UTF-8
1,054
3.296875
3
[]
no_license
//Author: Daniel Cieslowski //Date created: 20.10.2019 //Last modified: 24.10.2019 #include "Solver.h" #include <algorithm> void Solver::Solve(Puzzle& puzzle) { int consecutiveCount = findConsecutiveSets(puzzle); unsigned long long int result = consecutiveCount * factorial(puzzle.ElementCount() - puzzle.Size()) * (puzzle.Size() - 1) / 2; puzzle.SetSolution(result, result, result, result); puzzle.Solve(); } const int Solver::findConsecutiveSets(const Puzzle& puzzle) { int* values = new int[puzzle.ElementCount()]; int setCount = 0; for (int i = 0; i < puzzle.ElementCount(); i++) { values[i] = puzzle(i); } std::sort(values, values + puzzle.ElementCount()); for (int i = 0; i < puzzle.ElementCount() - puzzle.Size() + 1; i++) { if (values[i] + 3 == values[i + puzzle.Size() - 1]) { setCount++; } } delete[] values; return setCount; } const unsigned long long int Solver::factorial(const int value) { unsigned long long int factorial = 1; for (int i = 1; i <= value; i++) { factorial *= i; } return factorial; }
true
1b119475062327362aeeee311a383c03c0442f22
C++
ChengfengTang/C
/shuntingYard/Node.h
UTF-8
319
2.875
3
[]
no_license
#ifndef NODE_H #define NODE_H #include<iostream> class Node { public: Node(); ~Node(); void setSymbol(char newSymbol); void setLeft(Node* newLeft); void setRight(Node* newRight); Node* getLeft(); Node* getRight(); char getSymbol(); private: char symbol; Node* left; Node* right; }; #endif
true
6b329015f9ca528c2d5d0c3776d2871305c83c57
C++
gregorgebhardt/job_stream
/job_stream/pythonType.h
UTF-8
1,312
2.84375
3
[ "MIT" ]
permissive
/** Header for the SerializedPython type so that it is integrated into decoding objects. */ #pragma once #include <boost/serialization/serialization.hpp> #include <iostream> namespace job_stream { namespace python { /** Python data stored as a pickle string */ struct SerializedPython { std::string data; SerializedPython() {} explicit SerializedPython(std::string src) : data(std::move(src)) {} SerializedPython(SerializedPython&& other) : data(std::move(other.data)) {} SerializedPython& operator=(const SerializedPython& rhs) { this->data = rhs.data; return *this; } SerializedPython& operator=(SerializedPython&& rhs) { this->data = std::move(rhs.data); return *this; } /** Implemented in _job_stream.cpp. Takes a string and turns it into a python pickled string. */ friend std::istream& operator>>(std::istream& is, SerializedPython& sp); /** Print out the repr of the stored python object. */ friend std::ostream& operator<<(std::ostream& os, const SerializedPython& sp); private: friend class boost::serialization::access; template<class Archive> void serialize(Archive& ar, const unsigned int version) { ar & this->data; } }; } //python } //job_stream
true
2a334e8edc581dcc3a9a8d06d3e6fa5d8f334385
C++
bearownage/Client-Server
/aliaslinearprobe.cpp
UTF-8
4,863
3.25
3
[]
no_license
#include <stdio.h> #include <string.h> #include <string> #include <unistd.h> #define MAPSIZE 10000 struct map_entry { char alias[128]; char key[128]; int32_t offset_entry; }; struct map_entry *map[MAPSIZE]; void alias_update_entry(ssize_t fd, map_entry *new_entry, map_entry *old_entry); void init_alias_function() { for (int32_t i = 0; i < MAPSIZE; i++) { map[i] = (map_entry *)malloc(sizeof(map_entry)); map[i]->offset_entry = -1; } } void print_alias() { for (int16_t i = 0; i < MAPSIZE; i++) { if (map[i]->offset_entry != -1) { printf("Alias: %s Key: %s\n", map[i]->alias, map[i]->key); } } } int hash_function(char alias[87]) { int32_t sum = 0; for (uint8_t i = 0; i < strlen(alias); i++) { sum += (int)alias[i]; } return sum % MAPSIZE; } /*inserts a struct into the hash table*/ void alias_insert(struct map_entry *entry) { /*preallocate the entry so it updates*/ map_entry *insert_entry = (map_entry *)malloc(sizeof(map_entry)); strcpy(insert_entry->alias, entry->alias); strcpy(insert_entry->key, entry->key); insert_entry->offset_entry = entry->offset_entry; // printf("inserting entry: Alias: %s Key: %s Offset: %d\n", // insert_entry->alias, // insert_entry->key, insert_entry->offset_entry); ssize_t count = 0; ssize_t key = hash_function(entry->alias); /*See if the first spot is a default entry that has been unused*/ if (map[key]->offset_entry == -1) { free(map[key]); map[key] = NULL; map[key] = insert_entry; } else { /*loop till we find a new entry*/ while (map[key]->offset_entry != -1) { key = (key + 1) % MAPSIZE; count++; if (count == MAPSIZE) { perror("Table is full for insert"); return; } } free(map[key]); map[key] = NULL; map[key] = insert_entry; } } /*Updates an existing alias*/ void alias_update(ssize_t fd, struct map_entry *entry) { /*preallocate the entry so it updates*/ map_entry *insert_entry = (map_entry *)malloc(sizeof(map_entry)); strcpy(insert_entry->alias, entry->alias); strcpy(insert_entry->key, entry->key); // printf("Updating entry: Alias: %s Key: %s\n", insert_entry->alias, // insert_entry->key); ssize_t count = 0; ssize_t key = hash_function(entry->alias); /*See if the first spot is a default entry that has been unused*/ if (strcmp(map[key]->alias, entry->alias) == 0) { insert_entry->offset_entry = map[key]->offset_entry; alias_update_entry(fd, insert_entry, map[key]); free(map[key]); map[key] = NULL; map[key] = insert_entry; } else { /*loop till we find a new entry*/ while (strcmp(map[key]->alias, entry->alias) != -0) { key = (key + 1) % MAPSIZE; count++; if (count == MAPSIZE) { perror("Table is full"); return; } } map[key]->offset_entry = insert_entry->offset_entry; alias_update_entry(fd, insert_entry, map[key]); free(map[key]); map[key] = NULL; map[key] = insert_entry; } } /*Searches to see if an alias exists*/ bool alias_search(struct map_entry *entry) { /*preallocate the entry so it updates*/ ssize_t count = 0; ssize_t key = hash_function(entry->alias); /*See if the first spot is a default entry that has been unused*/ if (strcmp(map[key]->alias, entry->alias) == 0) { return true; } else { /*loop till we find a new entry*/ while (strcmp(map[key]->alias, entry->alias) != -0) { key = (key + 1) % MAPSIZE; count++; if (count == MAPSIZE) { perror("Table is full"); return false; } } return true; } } /*Checks to see if any known alias matches a new key*/ bool key_search(struct map_entry *entry) { /*preallocate the entry so it updates*/ ssize_t count = 0; ssize_t key = hash_function(entry->key); /*See if the first spot is a default entry that has been unused*/ if (strcmp(map[key]->alias, entry->key) == 0) { return true; } else { /*loop till we find a new entry*/ while (strcmp(map[key]->alias, entry->key) != 0) { key = (key + 1) % MAPSIZE; count++; if (count == MAPSIZE) { perror("Table is full"); return false; } } return true; } } /*Returns the key for an alias*/ char *alias_get(struct map_entry *entry) { /*preallocate the entry so it updates*/ ssize_t count = 0; ssize_t key = hash_function(entry->alias); /*See if the first spot is a default entry that has been unused*/ if (strcmp(map[key]->alias, entry->alias) == 0) { return map[key]->key; } else { /*loop till we find a new entry*/ while (strcmp(map[key]->alias, entry->alias) != -0) { key = (key + 1) % MAPSIZE; count++; if (count == MAPSIZE) { perror("Table is full"); return NULL; } } return map[key]->key; } }
true
f6ab6b6d7d5036abf18b5b68cfb553100f9a9bc6
C++
a-rodionov/Otus.Cpp.Homework2
/ip.cpp
UTF-8
1,047
3.296875
3
[]
no_license
#include "ip.h" #include <algorithm> IP::IP(const std::vector<std::string>& ip_str) { if(4 != ip_str.size()) throw std::invalid_argument("String represantation of IP contains wrong number of elements."); std::transform(std::cbegin(ip_str), std::cend(ip_str), ip_parts.begin(), [] (const auto& ip_string) { auto ip_part = std::stoul(ip_string); if(255 < ip_part) throw std::invalid_argument("String represantation of ip element is greater than 255."); return ip_part; }); } bool operator>(const IP& lhs, const IP& rhs) { return lhs.ip_parts > rhs.ip_parts; } std::ostream& operator<<(std::ostream& out, const IP& ip) { for (auto ip_part = std::cbegin(ip.ip_parts); ip_part != std::cend(ip.ip_parts); ++ip_part) { if (ip_part != std::cbegin(ip.ip_parts)) { out << "."; } out << static_cast<unsigned int>(*ip_part); } out << std::endl; return out; }
true
49d9a44c4a126c731a5c66b8311cdf2e95bc9392
C++
willsaibott/Basic_Library
/Matrix_Operations/PixelMatrix_RGBD.h
UTF-8
7,052
3.171875
3
[]
no_license
#ifndef PIXELMATRIX_RGBD_H #define PIXELMATRIX_RGBD_H #include "PixelMatrix.h" #include "Sphere_Distance_Calculator.h" #include "Sphere_Similarities_Calculator.h" #include "Intersection_Similarities_Calculator.h" #define INTERSECTION_SIMILARITIES_ALGORITHM 2 #define SPHERE_SIMILARITIES_ALGORITHM 3 #define SPHERE_ALGORITHM 1 #define RUN_ALL_PIXEL_MATRIX 0 template <class A> class PixelMatrix_RGBD : public PixelMatrix<A>{ private: A **dist; int method; void createDistanceMatrix(); public : PixelMatrix_RGBD(A **image, imageSize newSize); PixelMatrix_RGBD(imageSize newSize); PixelMatrix_RGBD(); ~PixelMatrix_RGBD(); //getters A **getDistanceMatrix(){return dist;} A getDistance_at(uint row, uint col); //setter void setMethod(int method){this->method = method;} //others virtual void setSize(imageSize newSize); virtual void setSize(uint width, uint height); virtual void eraseMatrix(); void clean(); A ** calculateDistanceMatrix(A **pixel2, int overlap); A calculateDistance_at(A pixel2, uint row, uint col); }; template <class A> PixelMatrix_RGBD<A>::PixelMatrix_RGBD() : PixelMatrix<A>() { method = SPHERE_ALGORITHM; dist = NULL; } template <class A> PixelMatrix_RGBD<A>::PixelMatrix_RGBD(A **image, imageSize newSize) : PixelMatrix<A>(image, newSize) { method = SPHERE_ALGORITHM; dist = NULL; } template <class A> PixelMatrix_RGBD<A>::PixelMatrix_RGBD(imageSize newSize) : PixelMatrix<A>(newSize) { method = SPHERE_ALGORITHM; dist = NULL; } template <class A> PixelMatrix_RGBD<A>::~PixelMatrix_RGBD() { clean(); this->size.height = 0; this->size.width = 0; } template<class A> void PixelMatrix_RGBD<A>::clean(){ if (dist!=NULL){ for (uint i = 0; i < this->size.height; i++){ delete [] dist[i]; } delete [] dist; dist = NULL; } } template <class A> void PixelMatrix_RGBD<A>::createDistanceMatrix(){ clean(); dist = new A*[this->size.height]; for (uint i = 0; i < this->size.height; i++){ dist[i] = new A[this->size.width](); } } template <class A> void PixelMatrix_RGBD<A>::eraseMatrix(){ for (uint i = 0; i < this->size.height; i++){ for(uint j = 0; j < this->size.width; j++){ dist[i][j] = 0; } } } template <class A> void PixelMatrix_RGBD<A>::setSize(imageSize newSize){ if (this->size.height!=newSize.height || this->size.width!=newSize.width){ this->destroy(); clean(); this->size.height = newSize.height; this->size.width = newSize.width; this->createPixelMatrix(); createDistanceMatrix(); } } template <class A> void PixelMatrix_RGBD<A>::setSize(uint width, uint height){ this->destroy(); clean(); this->size.height = height; this->size.width = width; this->createPixelMatrix(); createDistanceMatrix(); } //getter template <class A> A PixelMatrix_RGBD<A>::getDistance_at(uint row, uint col){ if (row < this->size.height && col < this->size.width) return dist[row][col]; throw(OUT_OF_LIMITS); } //others template <class A> A **PixelMatrix_RGBD<A>::calculateDistanceMatrix(A** pixel2, int overlap){ A min, aux; switch (method) { case SPHERE_ALGORITHM: if (true){ Sphere_Distance_Calculator<A> sphere(this->pixel, pixel2, this->size); sphere.execute(overlap); clean(); dist = sphere.getDistanceMatrix(); } break; case RUN_ALL_PIXEL_MATRIX: //createDistanceMatrix(); for (uint x = 0; x < this->size.height; x++){ for (uint y = 0; y < this->size.width; y++){ if ((uint) pixel2[x][y] != MAX_VALUE){ point_3D<A> p1, p2; makePoint(&p1, (A)x, (A)y, pixel2[x][y]); makePoint(&p2, (A)x, (A)y, this->pixel[x][y]); min = distance2(p1, p2); for(uint i = 0; i < this->size.height; i++){ p2.x = i; for (uint j = 0; j < this->size.width; j++){ p2.y = j; p2.z = this->pixel[i][j]; if (p2.z != MAX_VALUE){ aux = distance2(p1, p2); if (aux < min) min = aux; } } } } else min = 0; dist[x][y] = min; } } break; case INTERSECTION_SIMILARITIES_ALGORITHM: if (true){ Intersection_Similarities_Calculator<A> intersection(this->pixel, pixel2, this->size); intersection.execute(overlap); clean(); dist = intersection.getDistanceMatrix(); } break; case SPHERE_SIMILARITIES_ALGORITHM: if (true){ Sphere_Similarities_Calculator<A> sphere(this->pixel, pixel2, this->size); sphere.execute(overlap); clean(); dist = sphere.getDistanceMatrix(); } break; default: break; } return dist; } template <class A> A PixelMatrix_RGBD<A>::calculateDistance_at(A pixel2, uint row, uint col){ if (row < this->size.height && col < this->size.width){ A min, aux; switch (method) { case SPHERE_ALGORITHM: if (true){ Sphere_Distance_Calculator<A> sphere(this->pixel, pixel2, this->size); min = sphere.execute_at(pixel2, row, col); } break; case RUN_ALL_PIXEL_MATRIX: createDistanceMatrix(); point_3D<A> p1, p2; makePoint(&p1, row, col, pixel2); makePoint(&p2, row, col, this->pixel[row][col]); min = distance2(p1, p2); for(uint i = 0; i < this->size.height; i++){ p2.x = i; for (uint j = 0; j < this->size.width; j++){ p2.y = j; p2.z = this->pixel[i][j]; aux = distance2(p1, p2); if (aux < min) min = aux; } } break; case INTERSECTION_SIMILARITIES_ALGORITHM: if (true){ Intersection_Similarities_Calculator<A> intersection(this->pixel, pixel2, this->size); min = intersection.execute_at(pixel2, row, col); } break; case SPHERE_SIMILARITIES_ALGORITHM: if (true){ Sphere_Similarities_Calculator<A> sphere(this->pixel, pixel2, this->size); min = sphere.execute_at(pixel2, row, col); } break; default: break; } return min; } throw(OUT_OF_LIMITS); } #endif // PIXELMATRIX_RGBD_H
true
e8aa8222eab5f6eef721302852351d966e9399fe
C++
bopopescu/CodeLingo
/Dataset/cpp/truth.cpp
UTF-8
594
3.5
4
[ "MIT" ]
permissive
// truth.cpp (c) 1997-2002 Kari Laitinen #include <iostream.h> int main() { bool true_boolean_variable = true ; bool false_boolean_variable = false ; cout << "\n In C++, expressions are evaluated so that\n" << "\n - a true expression has value " << ( 99 == 99 ) << "\n - a false expression has value " << ( 99 == 88 ) << "\n\n Boolean variables can have values" << "\n - " << true_boolean_variable << " means true " << "\n - " << false_boolean_variable << " means false\n" ; }
true
4cdbc92ba7b1e562f14a2f07a705a2e10089559c
C++
shega1992/Prata-CPP-exercises
/Chapter15/Ex15-3/exc_mean.h
UTF-8
954
3.234375
3
[]
no_license
#ifndef EXC_MEAN_H_ #define EXC_MEAN_H_ #include <iostream> #include <stdexcept> class bad_arguments : public std::logic_error { private: double v1; double v2; protected: double get_arg1() { return v1; } double get_arg2() { return v2; } public: bad_arguments(double a = 0, double b = 0) : std::logic_error("bad arguments"), v1(a), v2(b) {} virtual void mesg() = 0; }; class bad_hmean : public bad_arguments { public: bad_hmean(double a = 0, double b = 0) : bad_arguments(a,b) {} virtual void mesg(); }; inline void bad_hmean::mesg() { std::cout << "hmean(" << get_arg1() << ", " << get_arg2() << "): " << "invalid arguments: a = -b\n"; } class bad_gmean : public bad_arguments { public: bad_gmean(double a = 0, double b = 0) : bad_arguments(a, b) {} virtual void mesg(); }; void bad_gmean::mesg() { std::cout << "gmean() arguments should be >= 0\n" << "Values used: " << get_arg1() << ", " << get_arg2() << std::endl; } #endif
true
dd83e9daa86b11d1d50f8ce24037bad8e3b07cbe
C++
dacunni/FastRender
/src/RandomNumberGenerator.h
UTF-8
1,882
2.703125
3
[]
no_license
#ifndef _RANDOM_NUMBER_GENERATOR_H_ #define _RANDOM_NUMBER_GENERATOR_H_ #include <random> class Vector4; class BarycentricCoordinate; class RandomNumberGenerator { public: RandomNumberGenerator(); ~RandomNumberGenerator() = default; inline float uniform01( void ); inline float uniformRange( float min, float max ); inline float cosineQuarterWave( void ); void uniformUnitCircle( float & x, float & y ); void uniformCircle( float radius, float & x, float & y ); void uniformSurfaceUnitSphere( float & x, float & y, float & z ); void uniformSurfaceUnitSphere( Vector4 & v ); void uniformSurfaceUnitHalfSphere( const Vector4 & half_space, Vector4 & v ); void uniformConeDirection( const Vector4 & dir, float angle, Vector4 & v ); // Distribution sampling // Convention: // +z out of surface // phi measured CCW about z, with phi=0 is x+ axis // theta measured from +z axis, with theta=0 is z+ axis void cosineUnitHalfSphere( float & x, float & y, float & z ); void cosineUnitHalfSphere( Vector4 & v ); void beckmanNDF( float roughness, float & x, float & y, float & z ); void beckmanNDF( float roughness, Vector4 & v ); void uniformVolumeUnitCube( float & x, float & y, float & z ); void uniformVolumeUnitCube( Vector4 & v ); void uniformVolumeUnitSphere( float & x, float & y, float & z ); void uniformUnitTriangle2D( float & x, float & y ); void uniformTriangle3D( BarycentricCoordinate & bary ); void uniformTriangle3D( const Vector4 & v1, const Vector4 & v2, const Vector4 & v3, Vector4 & r ); private: std::random_device device; std::mt19937 engine; std::uniform_real_distribution<float> distribution; }; #include "RandomNumberGenerator.hpp" #endif
true
8be8f2620f4fdac0b00b4ff93fe0b34363262ae7
C++
nopanderer/ps
/bf/1476.cc
UTF-8
332
2.890625
3
[]
no_license
/** * 날짜 계산 * 1476 */ #include <iostream> using namespace std; int e,s,m; int E,S,M; int ans; int main(){ cin>>E>>S>>M; e=s=m=ans=1; while(true){ if(s==S && e==E && m==M) break; e++; s++; m++; if(e==16) e=1; if(s==29) s=1; if(m==20) m=1; ans++; } cout<<ans<<'\n'; return 0; }
true
1dc2c1758c3f7b65bf9e9a8a4a6eacbddf1bfb36
C++
MaiJiahne/greenhandle
/Project1/wuli.cpp
UTF-8
876
2.734375
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> #include <numeric> using namespace std; int main() { vector<double> time; vector<double> v; vector<double> result; const double length = 0.2; const double pyou = 1261.2; const double pball = 7800.0; const double D = 0.0225; const double d = 0.001015; const double g = 9.8; double temp; for (int i = 0; i < 5; i++) { cin >> temp; time.push_back(temp); } cout << "time:" << endl; for (auto& i : time) { cout << i << " "; } cout << endl; for (int i = 0; i < 5; i++) { v.push_back(0.2 / time[i]); } cout << "v:" << endl; for (auto& i : v) { cout << i << " "; } cout << endl; for (int i = 0; i < 5; i++) { result.push_back((( pball- pyou) * g * d * d) / (18 * v[i] * (1 + 2.4 * (d / D)))); } cout << "result:" << endl; for (auto& i : result) { cout << i << " "; } cout << endl; }
true
21a753db8a5f0c219586d99a27c1e1ef7a2aaa1c
C++
SunWarriorZLX/Cpp-UndergraduateCourses
/etc/main.cpp
UTF-8
6,983
2.78125
3
[]
no_license
#include<iostream> #include<string> #include<map> #include<vector> #include<stack> #include<set> #include<cstring> using namespace std; map<char,int>getnum; char Getchar[100]; //获得对应字符 vector<string>proce; int table[100][100]; //预测分析表 int num=0;int numvt=0; //numvt是终结符集合,0是‘#’,numvt表空字 string first[100]; string follow[200]; void readin() { memset(table,-1,sizeof(table)); getnum['#']=0; Getchar[0]='#'; cout<<"请输入所有的终结符:"<<endl; char x; do { cin>>x; getnum[x]=++num; Getchar[num]=x; }while(cin.peek()!='\n'); numvt=++num; getnum['@']=numvt; //kong zi Getchar[num]=('@'); cout<<"请输入所有非终结符:"<<endl; do { cin>>x; getnum[x]=++num; Getchar[num]=x; }while(cin.peek()!='\n'); cout<<"输入产生式集合(空字用‘@’表示),以‘end’结束:"<<endl; string pro; while(cin>>pro&&pro!="end") { string ss; ss+=pro[0]; for(int i=3;i<pro.size();i++) { if(pro[i]=='|') { proce.push_back(ss); ss.clear();ss+=pro[0]; } else { ss+=pro[i]; } } proce.push_back(ss); } } void jiaoji(string &a,string b) //a=a or b 取a,b交集赋值给a { set<char>se; for(int i=0;i<a.size();i++) se.insert(a[i]); for(int i=0;i<b.size();i++) se.insert(b[i]); string ans; set<char>::iterator it; for(it=se.begin();it!=se.end();it++) ans+=*it; a=ans; } string get_f(int vn,int & has_0) //dfs:vn能推出的不含空字的vt集合,并且判断vn能否推出空字 { if(vn==numvt)has_0=1; if(vn<numvt)return first[vn]; string ans; for(int i=0;i<proce.size();i++) { if(getnum[proce[i][0]]==vn) ans+=get_f(getnum[proce[i][1]],has_0); } return ans; } void getfirst() { for(int i=1;i<=numvt;i++) //终结符,first集是其本身。 { first[i]+=('0'+i); } for(int j=0;j<proce.size();j++) //扫描所有产生式 { int k=0;int has_0=0; //k扫瞄该产生式 do{ has_0=0; k++; if(k==proce[j].size()) //推到最后一个了,则附加空字 { first[getnum[proce[j][0]]]+=('0'+numvt); break; } //合并之 jiaoji(first[getnum[proce[j][0]]],get_f(getnum[proce[j][k]],has_0)); } while(has_0); //到无法推出空字为止 } } void print_first() { cout<<"first集:"<<endl; for(int i=1;i<=num;i++) { cout<<"first ["<<Getchar[i]<<"]: "; for(int j=0;j<first[i].size();j++) cout<<Getchar[first[i][j]-'0']<<" "; cout<<endl; } cout<<endl; } void getfollow() { jiaoji(follow[getnum[proce[0][0]]],"0"); //先添加‘#’; for(int j=0;j<proce.size();j++) //扫所有产生式 { for(int jj=1;jj<proce[j].size();jj++) //每个非终结符的follow集 { if(getnum[proce[j][jj]]<=numvt)continue; //vt无follow集 int k=jj; int has_0; do { has_0=0; k++; if(k==proce[j].size()) //都能推出空字,follow集=产生式左边的vn, { jiaoji(follow[getnum[proce[j][jj]]],follow[getnum[proce[j][0]]]); break; } jiaoji(follow[getnum[proce[j][jj]]],get_f(getnum[proce[j][k]],has_0)); }while(has_0); } } } void gettable() //得预测分析表 { for(int i=0;i<proce.size();i++) //扫所有产生式 { if(proce[i][1]=='@') //直接推出空字的,特判下(follow集=产生式左边的vn中元素填) { string flw=follow[getnum[proce[i][0]]]; for(int k=0;k<flw.size();k++) { table[getnum[proce[i][0]]][flw[k]-'0']=i; } } string temps=first[getnum[proce[i][1]]]; for(int j=0;j<temps.size();j++) //考察first集 { if(temps[j]!=('0'+numvt)) { table[getnum[proce[i][0]]][temps[j]-'0']=i; } else //有空字的,考察follw集 { string flw=follow[getnum[proce[i][1]]]; for(int k=0;k<flw.size();k++) { table[getnum[proce[i][0]]][flw[k]-'0']=i; } } } } } string get_proce(int i) //由对应下标获得对应产生式。 { if(i<0)return " "; //无该产生式 string ans; ans+=proce[i][0]; ans+="->"; //ans+=(proce[i][0]+"->"); 注意这样不行!思之即可。 for(int j=1;j<proce[i].size();j++) ans+=proce[i][j]; return ans; } void print_table() { cout<<"预测分析表:"<<endl; for(int i=0;i<numvt;i++) cout<<'\t'<<Getchar[i]; cout<<endl; for(int i=numvt+1;i<=num;i++) { cout<<Getchar[i]; for(int j=0;j<numvt;j++) { cout<<'\t'<<get_proce(table[i][j]); } cout<<endl; } cout<<endl; } void print_follow() { cout<<"follow集:"<<endl; for(int i=numvt+1;i<=num;i++) { cout<<"follow ["<<Getchar[i]<<"]: "; for(int j=0;j<follow[i].size();j++) cout<<Getchar[follow[i][j]-'0']<<" "; cout<<endl; } cout<<endl; } string word; bool analyze() //总控,分析字word的合法性,若合法,输出所有产生式。 { stack<char>sta; sta.push('#');sta.push(proce[0][0]); int i=0; while(!sta.empty()) { int cur=sta.top(); sta.pop(); if(cur==word[i]) //是终结符,推进 { i++; } else if(cur=='#') //成功,结束 { return 1; } else if(table[getnum[cur]][getnum[word[i]]]!=-1) //查表 { int k=table[getnum[cur]][getnum[word[i]]]; cout<<proce[k][0]<<"->"; for(int j=1;j<proce[k].size();j++) cout<<proce[k][j]; cout<<endl; for(int j=proce[k].size()-1;j>0;j--) //逆序入栈 { if(proce[k][j]!='@') sta.push(proce[k][j]); } } else //失败! { return 0; } } return 1; } int main() { readin(); getfirst(); getfollow(); getfollow(); gettable(); print_first(); print_follow(); print_table(); cout<<"请输入字:"<<endl; cin>>word; if(analyze()) cout<<"succeed!该字有效,所用产生式如上。"<<endl; else cout<<"error!"<<endl; return 0; }
true
3726c750359fb3acc89562e30223394b6e01dce6
C++
Wilingpz/sunny
/11.27练习/11.25练习/main.cpp
GB18030
3,024
3.125
3
[]
no_license
//Ŀӣhttps://www.nowcoder.com/questionTerminal/6736cc3ffd1444a4a0057dee89be789b?orderByHotValue=1&page=1&onlyReference=false //Դţ //ţţٰһα̱, μӱ3*nѡ, ÿѡֶһˮƽֵa_i. //ҪЩѡֽ, һn, ÿ3. //ţţֶˮƽֵڸöԱеڶˮƽֵ // : //һԱˮƽֱֵ3, 3, 3.ôˮƽֵ3 //һԱˮƽֱֵ3, 2, 3.ôˮƽֵ3 //һԱˮƽֱֵ1, 5, 2.ôˮƽֵ2 //Ϊñп, ţţ밲Ŷʹжˮƽֵܺ //ʾ : //ţţ6Աֵ //Ϊ : //team1 : {1, 2, 5}, team2 : {5, 5, 8}, ʱˮƽֵܺΪ7. //Ϊ : // team1 : {2, 5, 8}, team2 : {1, 5, 5}, ʱˮƽֵܺΪ10. // ûбܺΪ10ķ, 10. //Ŀ //ˮƽֵڸöԱеڶˮƽֵ //ΪжˮƽֵܺĽⷨҲ˵ÿĵڶֵǾֵܴ //ʵֵֵŵұߣСǷŵߡ //˼· //Ҫ˼·̰㷨̰㷨ʵܼÿѡֵʱѡǰܿľֲ //̰ľDZ֤ÿĵڶֵȡѡֵͿ //ÿξȡ󣬵 λ˶Σȡÿеڶ //Ȼȡ±Ϊ3n - 23n - 4 3n - 4...n + 2nλõԪۼӼɣ //൱±Ϊ[0, n - 1]n ÿߵ //ʣµ2Ϊһ飬ֵұߵ //δмֵ δֵ // 1 2 5 5 8 9 //ôȡ 8 5ӵ 13 #include<iostream> #include<algorithm> #include<vector> using namespace std; int main1() { // IOOJܻжҪ int n; while (cin >> n) { long long sum = 0; vector<int> a; a.resize(3*n); //resizeڿռͬʱгʼӰsize for (int i = 0; i < (3 * n); i++) { cin >> a[i]; } /* Ȼȡ±Ϊ3n - 23n - 4 3n - 4... n+2nλõԪۼӼɣ ൱±Ϊ[0,n-1]nÿߵ ʣµ2Ϊһ飬 ֵұߵ δмֵǰδֵ */ std::sort(a.begin(), a.end()); for (int i = n; i <= 3 * n - 2; i += 2) { sum += a[i]; } cout << sum << endl; } return 0; }
true
e92448fcd4f1207b01480c209cc0fa7407d90958
C++
SeanCST/Algorithm_Problems
/LeetCode/242_有效的字母异位词.cpp
UTF-8
480
2.9375
3
[]
no_license
class Solution { public: bool isAnagram(string s, string t) { if(s.length() != t.length()) return false; map<char, int> m; for(int i = 0; i < s.length(); i++) { m[s[i]]++; m[t[i]]--; } map<char, int>::iterator iter = m.begin(); while(iter != m.end()) { if(iter->second != 0) return false; iter++; } return true; } };
true
786f05106a1054f69bbd142a079c9f2463e8c1be
C++
Lynch88024/Daily-coding
/PAT/B1007.cpp
UTF-8
1,013
2.984375
3
[]
no_license
#include <iostream> #include <cstdio> #include <cmath> #include <cstring> #include <algorithm> using namespace std; const int maxn = 100010; int prime[maxn]; bool flag[maxn]; int prime_num = 0; bool isPrime(int n) { if(n <= 1) { return false; } int sqr = (int)sqrt(1.0*n); for(int i=2; i<=sqr; i++) { if(n%i == 0) { return false; } } return true; } void findPrime(int n) { for(int i=0; i<maxn; i++) flag[i] = true; for(int i=2; i<=n; i++) { if(flag[i] == true) { prime[prime_num++] = i; for(int j=i+i; j<=n; j+=i) { flag[j] = false; } } } //printf("%d", prime_num); } int main() { int n; scanf("%d", &n); findPrime(n); int cnt = 0; for(int i=0; i<prime_num-1; i++) { if(prime[i+1]-prime[i] == 2) { cnt++; } } printf("%d", cnt); return 0; }
true
bcb32576e0501f890263045b145a5d2ab9f32683
C++
kljadsl/cpp
/笔记/设计模式/游戏设计模式/命令模式/Command.h
UTF-8
1,321
3.140625
3
[]
no_license
#include"GameActor.h" #include"Button.h" class Command{ public: virtual ~Command(){} virtual void execute(GameActor& actor) = 0; }; class JumpCommand : public Command{ public: virtual void execute(GameActor& actor) { actor.jump(); } }; class FireCommand : public Command{ public: virtual void execute(GameActor& actor) { actor.fire(); } }; class SwapWeaponCommand : public Command{ public: virtual void execute(GameActor& actor) { actor.swapweapon(); } }; class DashCommand : public Command{ public: virtual void execute(GameActor& actor) { actor.dash(); } }; class InputHandler{ private: Command* buttonX; Command* buttonY; Command* buttonA; Command* buttonB; Button* bX; Button* bY; Button* bA; Button* bB; public: InputHandler(Command* cX, Command* cY, Command* cA, Command* cB, Button* X, Button* Y, Button* A, Button* B) : buttonX(cX), buttonY(cY), buttonA(cA), buttonB(cB), bX(X), bY(Y), bA(A), bB(B) {} Command* handleInput(){ if (isPressed(bX)) return buttonX; if (isPressed(bY)) return buttonY; if (isPressed(bA)) return buttonA; if (isPressed(bB)) return buttonB; return NULL; } };
true
c907f22b658d396f278b6a613def30be6a67988c
C++
NguyenTheAn/Algorithm
/sap_xep_mang.cpp
UTF-8
371
2.75
3
[]
no_license
#include <iostream> using namespace std; main(){ long n; cin>>n; long array[n]; for(int i=0;i<n;i++){ cin>>array[i]; } int index; for (int i=0;i<n;i++){ for (int j=i+1;j<n;j++){ if (array[i]>array[j]){ index=array[i]; array[i]=array[j]; array[j]=index; } } } for (int i=0;i<n;i++){ cout<<array[i]<<" "; } }
true
3b8036d1dd1c6280cc08bea1d8044c17c4c76235
C++
mke01/BasicC-
/Day 12/08 Static members/Source01.cpp
UTF-8
1,383
3.875
4
[]
no_license
#include <time.h> class RandomGenerator { public: static int random(int lbound, int ubound); }; int RandomGenerator::random(int lbound, int ubound) { static unsigned int seed = (unsigned int) time(nullptr); while(seed == 0) seed = (unsigned int) time(nullptr); seed *= seed; seed = seed % (ubound - lbound) + lbound; return seed; } int main() { int n = 0; n = RandomGenerator::random(0, 100); RandomGenerator rg; n = rg.random(0, 100); n = rg.random(0, 100); n = rg.random(0, 100); return 0; } /* In this program we learned 'random' implemented as static member function. Thus a class can have both static and non-static member functions. The differences between these two types of functions are as follows: Static Member function 1. Calling with object is optional. Most of the times they are called with class-name::static-member-function-name(...) syntax. 2. The 'this' pointer is missing. 3. Static member function cannot be constant function. 4. Static member function cannot be virtual function. Non-static member function 1. Calling with object is mandatory. They cannot be called with class-name::member-function-name(...) syntax. 2. The 'this' pointer is present and points to an object on which the function has been called. 3. Non-static member function can be constant function. 4. Non-static member function can be virtual function. */
true
66a8d2b86f0a2b5e236dfb58f46fbadc8f0fe94a
C++
squeakyspacebar/downsampling_assignment
/include/eye/functions.hpp
UTF-8
913
2.53125
3
[]
no_license
#ifndef EYE_FUNCTIONS_HPP #define EYE_FUNCTIONS_HPP #include <string> #include <vector> #include <eye/common.hpp> #include <eye/image.hpp> namespace eye { typedef std::pair<Image, std::vector<mode_map_t>> image_pair_t; std::vector<Image> process_image(const Image & img); void write_to_file(const Image & img, const std::string & filename); Image generate_randomized_image(const std::size_t dims); void fill_image(Image & img); std::size_t find_max_l(const Image & img); image_pair_t downsample_image(const Image & img); image_pair_t downsample_reduce(const image_pair_t & img_pair); Image create_reduced_image(const Image & img, const std::size_t dim_size); mode_pair_t find_mode(const Image & img, const std::size_t start_index); mode_pair_t reduce_modes(const Image & img, const mode_array_t & mode_array, const std::size_t start_index); } #endif
true
c6bde3cb32b6ccb68242f0e32fe6c326ee041ba8
C++
JianHangChen/LeetCode
/1792. Maximum Average Pass Ratio.cpp
UTF-8
3,015
3.203125
3
[]
no_license
// !!! sol1.1, my, O(nlogk), O(k), use array<int,3> to reduce time, faster than vector // similar to amazon oa double diff(double x, double y){ return (x + 1) / (y + 1) - x / y; } class Solution { public: double maxAverageRatio(vector<vector<int>>& classes, int extraStudents) { vector<array<double, 3> > triple; double total = 0; for(auto& c:classes){ // O(k) double x = c[0], y = c[1]; total += x / y; triple.push_back( {diff(x, y), x, y }); } priority_queue<array<double,3>> pq(triple.begin(), triple.end()); // O(k) while(extraStudents){ // nlogk auto a = pq.top(); pq.pop(); total += a[0]; double x = a[1] + 1, y = a[2] + 1; pq.push({diff(x, y), x, y }); extraStudents--; } int n = classes.size(); return total/n; } }; // sol1, my, O( (n+k)logk ), O(k) // k classes, n extrastudent // similar to amazon oa // double diff(double x, double y){ // return (x + 1) / (y + 1) - x / y; // } // class Solution { // public: // double maxAverageRatio(vector<vector<int>>& classes, int extraStudents) { // vector<pair<double, array<int, 2> >> triple; // double total = 0; // for(auto& c:classes){ // total += (double)c[0] / c[1]; // triple.push_back( {diff(c[0], c[1]), {c[0], c[1]}}); // // pq.push({diff(c[0], c[1]), {c[0], c[1]}}); // } // priority_queue<pair<double, array<int, 2>>> pq(triple.begin(), triple.end()); // while(extraStudents){ // auto a = pq.top(); pq.pop(); // total += a.first; // int x = a.second[0] + 1, y = a.second[1] + 1; // pq.push({diff(x, y), {x, y}}); // extraStudents--; // } // int n = classes.size(); // return total/n; // } // }; // sol1, my, O(klogn), O(n), tle // classes n, students k // similar to amazon oa // double diff(vector<int>& a){ // double x = a[0], y = a[1]; // return (x + 1) / (y + 1) - x / y; // } // struct CMP{ // bool operator()(vector<int>& a, vector<int>& b){ // return diff(a) < diff(b); // } // }; // class Solution { // public: // double maxAverageRatio(vector<vector<int>>& classes, int extraStudents) { // priority_queue<vector<int>, vector<vector<int>>, CMP> pq; // for(auto& c:classes){ // pq.push(c); // } // while(extraStudents){ // auto a = pq.top(); pq.pop(); // pq.push({a[0]+1, a[1]+1}); // extraStudents--; // } // double res = 0; // int n = classes.size(); // while(!pq.empty()){ // auto a = pq.top(); pq.pop(); // res += (double)a[0] / a[1]; // } // return res/n; // } // };
true
3d2804d155428f4e6787a6b38b606b0b159d5449
C++
TroyNeubauer/Calculus-Cpp
/examples/quickstart/quickstart.cpp
UTF-8
773
2.78125
3
[ "MIT" ]
permissive
#include "Calc.hpp" #include "CompileTime.hpp" #include "parser/Parser.hpp" #include <iostream> #include <string> using namespace calc; using namespace calc::compile_time; int main(int argc, const char** argv) { //Variable x("x"); //Expression e = Sin(x) + 1.5; std::string line; while (std::getline(std::cin, line)) { ParseErrorInfo info; Atom<double>* atom = Parse<double>(line, info); if (atom) { std::cout << "Result is: " << atom->Get() << std::endl; } else { std::cout << "Error: " << info.Message << " at index " << info.Position << " into " << std::string_view(info.InputBegin, info.InputEnd - info.InputBegin) << std::endl; } } }
true
4972ecc1cecd33610003a0ed74fd45b6aec04407
C++
SayaUrobuchi/uvachan
/USACO/詳解/cpp/humble.cpp
UTF-8
676
2.59375
3
[]
no_license
/* ID: dd.ener1 PROG: humble LANG: C++ */ #include <cstdio> using namespace std; long N,K,s[100]; unsigned long ham[1000000]; long dex[100]; const unsigned long OO=~0; void input(){ freopen("humble.in","r",stdin); scanf("%d%d",&N,&K); for(long i=0;i<N;++i)scanf("%d",s+i); } inline void solve(){ ham[0]=1; for(long k=1;k<=K;++k){ unsigned long min=OO; for(long i=0;i<N;++i) for(long j=dex[i];j<k;++j){ unsigned long now=s[i]*ham[j]; if(now>ham[k-1]){ if(now<min)min=now; dex[i]=j; break; } } ham[k]=min; } } void output(){ freopen("humble.out","w",stdout); printf("%d\n",ham[K]); } int main(){ input(); solve(); output(); }
true
0797fedaf5f5782058ebd75fc977ca583e4cdcd3
C++
The-Elite-Zero/8-Piece-Puzzle-Project
/PuzzleProject.cpp
UTF-8
26,768
3.5625
4
[]
no_license
// The following program will solve an 8-Piece Puzzle based on randomly // generated or pre-generated states. It will use 3 different search // algorithms: Breadth-First, Depth-First, and A* w/ Out of Place Tile // Heuristic. // // Name: // //----------------------------------------------------------------------------- #include <iostream> #include <string> #include <map> #include <queue> #include <stack> #include <vector> #include <time.h> using namespace std; // Global Variables const string goalState = "123456780"; // Solution string solutionState = "783415602"; // A Working State string initialState = "123456780"; // Variable for use within Menu() int counter = 0; // Counter for node count // Map / Map Iterator map <string, int> visited_states; map <string, int>::iterator it = visited_states.begin(); // Object "node" struct node { string currentState; // Holds currentState of this node int depth = 0; // Depth of node in tree int heuristic = 0; // How many nodes are out of place // Operator Function for Priority-Queue bool operator< (const node& other) const { return heuristic > other.heuristic; } }; // Functions void Swap0and1(node&); // Swap Function Prototypes (12) void Swap0and3(node&); void Swap1and2(node&); void Swap1and4(node&); void Swap2and5(node&); void Swap3and4(node&); void Swap4and5(node&); void Swap4and7(node&); void Swap5and8(node&); void Swap6and3(node&); void Swap6and7(node&); void Swap7and8(node&); void randomGenerator(); // Random State Generator int Check_Goal(node); // Check for Goal State void Check_Map(node&); // Map Check Function void Expand(node, vector<node>&); // Expand function void BFS(node); // Breadth-First Search Algorithm void DFS(node); // Depth-First Search Algorithm void ASS(node); // A* w/ Out of Place Algorithm void Menu(); // Menu Function void timer(long, long); // Timer Function (Run Time) void Heuristic_Calc(node&); // Calculate Heuristic void All_Searches(node); // Runs all Searches int getInvCount(int); // Inversion Count bool isSolvable(string); // Solvability Check void displayPuzzle(string PUZZLE); // Puzzle Output (Formatted Matrix) // 1-2-3 0-1-2 Logic Layouts for Matrices // 4-5-6 3-4-5 // 7-8-0 6-7-8 // Goal State [1,2,3,4,5,6,7,8,0] //----------------------------------------------------------------------------- int main() // Main Function { Menu(); // Menu called for input from User system("pause"); // Windows Only Pause // cin.ignore(); // Universal Pause // cin.get(); // cout << "Press 'Enter' to continue..." << endl; return 0; // Success } //----------------------------------------------------------------------------- void Menu() // Outputs Menu for Functionality { int option = NULL; cout << " AI Project" << endl; cout << "------------" << endl << endl; cout << "1. Generate Initial State" << endl; cout << "2. Breadth-First Search" << endl; cout << "3. Depth-First Search" << endl; cout << "4. A* Search w/ Out of Place Tiles" << endl; cout << "88. Run all Searches" << endl; cout << "\n0. Exit Program" << endl; cout << "\n\n**Note: If you do not choose to generate an initial state "; cout << "\nbefore a search, a working state will be chosen for you.**"; cout << endl << endl; cout << ">> "; cin >> option; if (cin.fail()) option = 99; // Fail safe for non-numeric inputs switch (option) { case 1: initialState = goalState; randomGenerator(); // Shuffles Goal State cout << "\nYour Initial Start State is: " << initialState << endl; cout << endl; displayPuzzle(initialState); // Output initialState Matrix cout << "\nPress 'Enter' to return to the menu" << endl; cin.ignore(); cin.get(); system("cls"); Menu(); break; case 2: if (initialState == "123456780") // Check for unchosen state { cout << "\nA state was chosen for you." << endl; randomGenerator(); cout << "Your Initial Start State is: " << initialState << endl; cout << endl << endl; displayPuzzle(initialState); // Output Matrix node initialNode; initialNode.currentState = initialState; BFS(initialNode); // Send in initialNode cout << "Press 'Enter' to return to the menu" << endl; cin.ignore(); cin.get(); system("cls"); Menu(); break; } else { cout << "\nYour Initial Start State is: " << initialState; cout << endl << endl; displayPuzzle(initialState); // Output Matrix node initialNode; initialNode.currentState = initialState; BFS(initialNode); // Send in initialNode cout << "Press 'Enter' to return to the menu" << endl; cin.ignore(); cin.get(); system("cls"); Menu(); break; } case 3: if (initialState == "123456780") // Check for unchosen state { cout << "\nA state was chosen for you." << endl; randomGenerator(); cout << "Your Initial Start State is: " << initialState; cout << endl << endl; displayPuzzle(initialState); // Output Matrix node initialNode; initialNode.currentState = initialState; DFS(initialNode); // Send in initialNode cout << "Press 'Enter' to return to the menu" << endl; cin.ignore(); cin.get(); system("cls"); Menu(); break; } else { cout << "\nYour Initial Start State is: " << initialState; cout << endl << endl; displayPuzzle(initialState); // Output Matrix node initialNode; initialNode.currentState = initialState; DFS(initialNode); // Send in initialNode cout << "Press 'Enter' to return to the menu" << endl; cin.ignore(); cin.get(); system("cls"); Menu(); break; } case 4: if (initialState == "123456780") // Check for unchosen state { cout << "\nA state was chosen for you." << endl; randomGenerator(); cout << "Your Initial Start State is: " << initialState << endl; cout << endl << endl; displayPuzzle(initialState); // Output Matrix node initialNode; initialNode.currentState = initialState; ASS(initialNode); // Send in initialNode cout << "Press 'Enter' to return to the menu" << endl; cin.ignore(); cin.get(); system("cls"); Menu(); break; } else { cout << "\nYour Initial Start State is: " << initialState; cout << endl << endl; displayPuzzle(initialState); // Output Matrix node initialNode; initialNode.currentState = initialState; ASS(initialNode); // Send in initialNode cout << "Press 'Enter' to return to the menu" << endl; cin.ignore(); cin.get(); system("cls"); Menu(); break; } case 88: if (initialState == "123456780") // Check for unchosen state { cout << "\nA state was chosen for you." << endl; randomGenerator(); cout << "Your Initial Start State is: " << initialState << endl; cout << endl << endl; displayPuzzle(initialState); // Output Matrix node initialNode; initialNode.currentState = initialState; All_Searches(initialNode); // Runs all Searches cout << "Press 'Enter' to return to the menu" << endl; cin.ignore(); cin.get(); system("cls"); Menu(); break; } else { cout << "\nYour Initial Start State is: " << initialState; cout << endl << endl; displayPuzzle(initialState); // Output Matrix node initialNode; initialNode.currentState = initialState; All_Searches(initialNode); // Runs all Searches cout << "Press 'Enter' to return to the menu" << endl; cin.ignore(); cin.get(); system("cls"); Menu(); break; } case 0: cout << "\nExiting the Program..." << endl; system("exit"); // Windows Only Pause and Exit break; default: cout << "\nInput is not valid. Please try again\n\n"; system("pause"); cout << endl; cin.clear(); cin.ignore(); cin.get(); system("cls"); // Windows Only Clear Screen Menu(); break; }//End Switch }//End void Menu() //----------------------------------------------------------------------------- void randomGenerator() // Generates Random States { // Shuffling string substrings like arrays to generate random // states to use within the search algorithms. No numbers will // repeat within the substring arrays and they will be different // every time as it is randomly seeded based on the clock. srand(time(NULL)); // Seed rand to clock time for (int i = 8; i > 0; i--) // Shuffle prevents repeats { int r = rand() % i; int temp = initialState[i]; // Swap i and r initialState[i] = initialState[r]; initialState[r] = temp; } isSolvable(initialState); // Check for Solvability }//end RandomGenerator int getInvCount(int arr[]) // Counts Inversions { int inv_count = 0; for (int i = 0; i < 9 - 1; i++) for (int j = i + 1; j < 9; j++) // Value 0 is used for empty space if (arr[j] && arr[i] && arr[i] > arr[j]) inv_count++; return inv_count; }//end getInvCount bool isSolvable(string puzzle) // Checks Solvability { int puzzleArray[3][3]; // Multidimensional array int n = 0; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) { puzzleArray[i][j] = puzzle[n]; n++; } // Count inversions in given 8 puzzle int invCount = getInvCount((int *)puzzleArray); // return true if inversion count is even. if (invCount % 2 == 0) { return true; } else randomGenerator(); // Search for a Solvable State }//end isSolvable //----------------------------------------------------------------------------- int Check_Goal(node puzzle) // Checks Node for Goal State { // Goal State = "123456780" if (puzzle.currentState == goalState) { cout << "Goal State Found after <"<< counter << "> nodes" << endl; return 0; // Goal State Found } else { return 1; // Goal State Not Found } }// end void Check_Goal //----------------------------------------------------------------------------- void Check_Map(node& puzzle) // Checks Map for Node { // map <string, int> visited_states; // Checks map for node and inserts if // node doesn't exist in map it = visited_states.begin(); it = visited_states.find(puzzle.currentState); // If iterator goes to end, add node, else clear string if (it == visited_states.end()) // If not within map { counter++; // Increment counter & add node visited_states.insert(pair<string, int>(puzzle.currentState, counter)); } else { puzzle.currentState.clear(); // Empty node of string puzzle.depth = 0; puzzle.heuristic = 0; } }// end void checkMap //----------------------------------------------------------------------------- void Expand(node puzzle, vector <node>& container) // Expands nodes { // 1-2-3 0-1-2 Logic Layouts for Matrices // 4-5-6 3-4-5 // 7-8-0 6-7-8 int position = NULL; puzzle.depth++; // Expansion Increases Depth node temp = puzzle; // Temporarily hold parent node for (int i = 0; i < 9; i++) { // Find '0' within character substring if (puzzle.currentState[i] == '0') position = i; } switch (position) // Based on '0' position, swaps called { case 0: Swap0and1(puzzle); Check_Map(puzzle); // Check Map / Insert if (!puzzle.currentState.empty()) // If node was not within map { container.push_back(puzzle); // Push node onto queue } puzzle = temp; // Reset puzzle Swap0and3(puzzle); Check_Map(puzzle); // Check Map / Insert if (!puzzle.currentState.empty()) // If node was not within map { container.push_back(puzzle); // Push node onto queue } break; case 1: Swap0and1(puzzle); Check_Map(puzzle); // Check Map / Insert if (!puzzle.currentState.empty()) // If node was not within map { container.push_back(puzzle); // Push node onto queue } puzzle = temp; // Reset puzzle Swap1and2(puzzle); Check_Map(puzzle); // Check Map / Insert if (!puzzle.currentState.empty()) // If node was not within map { container.push_back(puzzle); // Push node onto queue } puzzle = temp; // Reset puzzle Swap1and4(puzzle); Check_Map(puzzle); // Check Map / Insert if (!puzzle.currentState.empty()) // If node was not within map { container.push_back(puzzle); // Push node onto queue } break; case 2: Swap2and5(puzzle); Check_Map(puzzle); // Check Map / Insert if (!puzzle.currentState.empty()) // If node was not within map { container.push_back(puzzle); // Push node onto queue } puzzle = temp; // Reset puzzle Swap1and2(puzzle); Check_Map(puzzle); // Check Map / Insert if (!puzzle.currentState.empty()) // If node was not within map { container.push_back(puzzle); // Push node onto queue } break; case 3: Swap0and3(puzzle); Check_Map(puzzle); // Check Map / Insert if (!puzzle.currentState.empty()) // If node was not within map { container.push_back(puzzle); // Push node onto queue } puzzle = temp; // Reset puzzle Swap3and4(puzzle); Check_Map(puzzle); // Check Map / Insert if (!puzzle.currentState.empty()) // If node was not within map { container.push_back(puzzle); // Push node onto queue } puzzle = temp; // Reset puzzle Swap6and3(puzzle); Check_Map(puzzle); // Check Map / Insert if (!puzzle.currentState.empty()) // If node was not within map { container.push_back(puzzle); // Push node onto queue } break; case 4: Swap3and4(puzzle); Check_Map(puzzle); // Check Map / Insert if (!puzzle.currentState.empty()) // If node was not within map { container.push_back(puzzle); // Push node onto queue } puzzle = temp; // Reset puzzle Swap1and4(puzzle); Check_Map(puzzle); // Check Map / Insert if (!puzzle.currentState.empty()) // If node was not within map { container.push_back(puzzle); // Push node onto queue } puzzle = temp; // Reset puzzle Swap4and5(puzzle); Check_Map(puzzle); // Check Map / Insert if (!puzzle.currentState.empty()) // If node was not within map { container.push_back(puzzle); // Push node onto queue } puzzle = temp; // Reset puzzle Swap4and7(puzzle); Check_Map(puzzle); // Check Map / Insert if (!puzzle.currentState.empty()) // If node was not within map { container.push_back(puzzle); // Push node onto queue } break; case 5: Swap2and5(puzzle); Check_Map(puzzle); // Check Map / Insert if (!puzzle.currentState.empty()) // If node was not within map { container.push_back(puzzle); // Push node onto queue } puzzle = temp; // Reset puzzle Swap4and5(puzzle); Check_Map(puzzle); // Check Map / Insert if (!puzzle.currentState.empty()) // If node was not within map { container.push_back(puzzle); // Push node onto queue } puzzle = temp; // Reset puzzle Swap5and8(puzzle); Check_Map(puzzle); // Check Map / Insert if (!puzzle.currentState.empty()) // If node was not within map { container.push_back(puzzle); // Push node onto queue } break; case 6: Swap6and3(puzzle); Check_Map(puzzle); // Check Map / Insert if (!puzzle.currentState.empty()) // If node was not within map { container.push_back(puzzle); // Push node onto queue } puzzle = temp; // Reset puzzle Swap6and7(puzzle); Check_Map(puzzle); // Check Map / Insert if (!puzzle.currentState.empty()) // If node was not within map { container.push_back(puzzle); // Push node onto queue } break; case 7: Swap6and7(puzzle); Check_Map(puzzle); // Check Map / Insert if (!puzzle.currentState.empty()) // If node was not within map { container.push_back(puzzle); // Push node onto queue } puzzle = temp; // Reset puzzle Swap4and7(puzzle); Check_Map(puzzle); // Check Map / Insert if (!puzzle.currentState.empty()) // If node was not within map { container.push_back(puzzle); // Push node onto queue } puzzle = temp; // Reset puzzle Swap7and8(puzzle); Check_Map(puzzle); // Check Map / Insert if (!puzzle.currentState.empty()) // If node was not within map { container.push_back(puzzle); // Push node onto queue } break; case 8: Swap7and8(puzzle); Check_Map(puzzle); // Check Map / Insert if (!puzzle.currentState.empty()) // If node was not within map { container.push_back(puzzle); // Push node onto queue } puzzle = temp; // Reset puzzle Swap5and8(puzzle); Check_Map(puzzle); // Check Map / Insert if (!puzzle.currentState.empty()) // If node was not within map { container.push_back(puzzle); // Push node onto queue } break; }// end Swap Switch }//end void Expand //----------------------------------------------------------------------------- void BFS(node puzzle) // Breadth-First Search { cout << "Searching for Breadth-First Solution..." << endl << endl; clock_t t1, t2; // Timer Start t1 = clock(); int check = 0; // Double Check for solution counter = 0; queue <node> BFSFringe; // Containers vector <node> container; node temp; Check_Map(puzzle); // Check / Input Map BFSFringe.push(puzzle); // Push 1st Node to Queue while (!BFSFringe.empty()) // Loop for Expansions { temp = BFSFringe.front(); // Copy node at front of queue BFSFringe.pop(); // Pop node from queue if (Check_Goal(temp) == 0) // Check Goal for return { // Goal found returns 0 cout << "Goal Found at <" << temp.depth << "> Depth." << endl; cout << "Breadth-First Search Complete!" << endl; check++; goto endBFS; } else { // Goal not found returns 1 container.clear(); Expand(temp, container); // Expand for next node for (int i = 0; i < container.size(); i++) // Transfer { BFSFringe.push(container[i]); } } } if (BFSFringe.empty()) // Empty Queue { if (check == 0) // Solution never found { cout << "Queue Empty! No Solution!" << endl; } } endBFS: // Branch if goal found visited_states.clear(); // Clear Map after search ends t2 = clock(); // Timer End timer(t1, t2); // Run Time Calculator }//end BFS //----------------------------------------------------------------------------- void DFS(node puzzle) // Depth-First Search { cout << "Searching for Depth-First Solution..." << endl << endl; clock_t t1, t2; // Timer Start t1 = clock(); int check = 0; // Double Check for solution counter = 0; stack <node> DFSFringe; // Containers vector <node> container; node temp; Check_Map(puzzle); // Initial Node DFSFringe.push(puzzle); while (!DFSFringe.empty()) // Loop for Expansions { temp = DFSFringe.top(); // Copy node at top of stack DFSFringe.pop(); // Pop node from stack if (Check_Goal(temp) == 0) // Check Goal for return { // Goal found returns 0 cout << "Goal Found at <" << temp.depth << "> Depth." << endl; cout << "Depth-First Search Complete!" << endl; check++; goto endDFS; } else { // Goal not found returns 1 container.clear(); Expand(temp, container); // Expand for next node for (int i = 0; i < container.size(); i++) // Transfer { DFSFringe.push(container[i]); } } } if (DFSFringe.empty()) // Empty Queue { if (check == 0) // Solution never found { cout << "Stack Empty! No Solution!" << endl; } } endDFS: // Branch if goal found visited_states.clear(); // Clear Map after search ends t2 = clock(); // Timer End timer(t1, t2); // Run Time Calculator }//end DFS //----------------------------------------------------------------------------- void ASS(node puzzle) // A* Search w/ Heuristic { // This search algorithm will use cost based on // out of place tiles (Heuristic). cout << "Searching for A* w/ Heuristic Solution..." << endl << endl; clock_t t1, t2; // Timer Start t1 = clock(); int check = 0; // Double Check for solution counter = 0; priority_queue <node> ASSFringe; vector <node> container; // Temporary container node temp; Heuristic_Calc(puzzle); // Initial Node Check_Map(puzzle); ASSFringe.push(puzzle); while (!ASSFringe.empty()) // Loop for Expansions { temp = ASSFringe.top(); // Copy node at front of queue ASSFringe.pop(); // Pop node from queue if (Check_Goal(temp) == 0) // Check Goal for return { // Goal found returns 0 cout << "Goal Found at <" << temp.depth << "> Depth." << endl; cout << "A* Search Complete!" << endl; check++; goto endASS; } else { // Goal not found returns 1 container.clear(); Expand(temp, container); // Expand for next node for (int i = 0; i < container.size(); i++) // Transfer { container[i].heuristic = 0; Heuristic_Calc(container[i]); ASSFringe.push(container[i]); } } } if (ASSFringe.empty()) // Empty Queue { if (check == 0) // Solution never found { cout << "Priority_Queue Empty! No Solution!" << endl; } } endASS: // Branch if goal found visited_states.clear(); // Clear Map after search ends t2 = clock(); // Timer End timer(t1, t2); // Run Time Calculator } //----------------------------------------------------------------------------- void All_Searches(node puzzle) { // Run all Searches 10x and Time them all // Average them and compare the searches // Explain the differences clock_t t1, t2; // Timer Start t1 = clock(); BFS(puzzle); DFS(puzzle); ASS(puzzle); t2 = clock(); // Timer End cout << "\nRuntime for All Searches" << endl << endl; timer(t1, t2); // Run Time Calculator } //----------------------------------------------------------------------------- void Swap0and1(node& puzzle) // Swap pos 1 and 2 { // 0-1-2 Layout for Matrix // 3-4-5 // 6-7-8 int temp = 0; temp = puzzle.currentState[0]; puzzle.currentState[0] = puzzle.currentState[1]; puzzle.currentState[1] = temp; //cout << "After swapping 1 and 2" << endl << endl; //displayPuzzle(puzzle.currentState); } void Swap0and3(node& puzzle) // Swap pos 1 and 4 { // 0-1-2 Layout for Matrix // 3-4-5 // 6-7-8 int temp = 0; temp = puzzle.currentState[0]; puzzle.currentState[0] = puzzle.currentState[3]; puzzle.currentState[3] = temp; //cout << "After swapping 1 and 4" << endl << endl; //displayPuzzle(puzzle.currentState); } void Swap1and2(node& puzzle) { // 0-1-2 Layout for Matrix // 3-4-5 // 6-7-8 int temp = 0; temp = puzzle.currentState[1]; puzzle.currentState[1] = puzzle.currentState[2]; puzzle.currentState[2] = temp; //cout << "After swapping 2 and 3" << endl << endl; //displayPuzzle(puzzle.currentState); } void Swap1and4(node& puzzle) { // 0-1-2 Layout for Matrix // 3-4-5 // 6-7-8 int temp = 0; temp = puzzle.currentState[1]; puzzle.currentState[1] = puzzle.currentState[4]; puzzle.currentState[4] = temp; //cout << "After swapping 2 and 5" << endl << endl; //displayPuzzle(puzzle.currentState); } void Swap2and5(node& puzzle) { // 0-1-2 Layout for Matrix // 3-4-5 // 6-7-8 int temp = 0; temp = puzzle.currentState[2]; puzzle.currentState[2] = puzzle.currentState[5]; puzzle.currentState[5] = temp; //cout << "After swapping 3 and 6" << endl << endl; //displayPuzzle(puzzle.currentState); } void Swap3and4(node& puzzle) { // 0-1-2 Layout for Matrix // 3-4-5 // 6-7-8 int temp = 0; temp = puzzle.currentState[3]; puzzle.currentState[3] = puzzle.currentState[4]; puzzle.currentState[4] = temp; //cout << "After swapping 4 and 5" << endl << endl; //displayPuzzle(puzzle.currentState); } void Swap4and5(node& puzzle) { // 0-1-2 Layout for Matrix // 3-4-5 // 6-7-8 int temp = 0; temp = puzzle.currentState[4]; puzzle.currentState[4] = puzzle.currentState[5]; puzzle.currentState[5] = temp; //cout << "After swapping 5 and 6" << endl << endl; //displayPuzzle(puzzle.currentState); } void Swap4and7(node& puzzle) { // 0-1-2 Layout for Matrix // 3-4-5 // 6-7-8 int temp = 0; temp = puzzle.currentState[4]; puzzle.currentState[4] = puzzle.currentState[7]; puzzle.currentState[7] = temp; //cout << "After swapping 5 and 8" << endl << endl; //displayPuzzle(puzzle.currentState); } void Swap5and8(node& puzzle) { // 0-1-2 Layout for Matrix // 3-4-5 // 6-7-8 int temp = 0; temp = puzzle.currentState[5]; puzzle.currentState[5] = puzzle.currentState[8]; puzzle.currentState[8] = temp; //cout << "After swapping 6 and 9" << endl << endl; //displayPuzzle(puzzle.currentState); } void Swap6and3(node& puzzle) { // 0-1-2 Layout for Matrix // 3-4-5 // 6-7-8 int temp = 0; temp = puzzle.currentState[6]; puzzle.currentState[6] = puzzle.currentState[3]; puzzle.currentState[3] = temp; //cout << "After swapping 7 and 4" << endl << endl; //displayPuzzle(puzzle.currentState); } void Swap6and7(node& puzzle) { // 0-1-2 Layout for Matrix // 3-4-5 // 6-7-8 int temp = 0; temp = puzzle.currentState[6]; puzzle.currentState[6] = puzzle.currentState[7]; puzzle.currentState[7] = temp; //cout << "After swapping 7 and 8" << endl << endl; //displayPuzzle(puzzle.currentState); } void Swap7and8(node& puzzle) { // 0-1-2 Layout for Matrix as substring positions // 3-4-5 // 6-7-8 int temp = 0; temp = puzzle.currentState[7]; puzzle.currentState[7] = puzzle.currentState[8]; puzzle.currentState[8] = temp; //cout << "After swapping 8 and 0" << endl << endl; //displayPuzzle(puzzle.currentState); } //----------------------------------------------------------------------------- void Heuristic_Calc(node& puzzle) // Calculate Heuristic { // This function calculates the heuristic based on // Out-of-Place tiles by comparing the current node // to the Goal State and adding accordingly. for (int i = 0; i < 9; i++) { if (puzzle.currentState[i] == goalState[i]) { continue; // Compare to Goal } else { puzzle.heuristic++; // Cost Increase } } }//end void Heuristic_Calc void displayPuzzle(string puzzle) // Displays Puzzle as Matrix { // 0-1-2 Layout for Matrix as substring positions // 3-4-5 // 6-7-8 cout <<" "<<puzzle[0]<<" - "<<puzzle[1]<<" - "<<puzzle[2]<<endl; cout <<" |"<<" |"<<" |"<< endl; cout <<" "<<puzzle[3]<<" - "<<puzzle[4]<<" - "<<puzzle[5]<<endl; cout << " |" << " |" << " |" << endl; cout <<" "<<puzzle[6]<<" - "<<puzzle[7]<<" - "<<puzzle[8]<<endl<<endl; }// end void displayPuzzle() void timer(long t1, long t2) // Calculates Time { // Calculates time based on clock ticks // and converts them to seconds using // CLOCK_PER_SEC algorithm which is // basically dividing based on 1000 // ticks int hours = 0, mins = 0; float seconds = 0; float diff((float)t2 - (float)t1); hours = mins / 60; mins = seconds / 60; seconds = diff / CLOCKS_PER_SEC; cout << "Time: " << hours << ":" << mins << ":" << seconds << endl << endl; } //-----------------------------------------------------------------------------
true
53afac3a1b0c21dd065db2c90f3a2f4564c0afcd
C++
liu7920/p153
/p153/src/p153.cpp
UTF-8
236
2.90625
3
[]
no_license
#include <iostream> using namespace std; #include "Oval.h" int main() { int w, h; Oval oval; cout << "변경 witch 입력 : "; cin >> w; cout << "변경 height 입력 : "; cin >> h; oval.set(w,h); oval.show(); return 0; }
true
2046f3190972ab4c711c0504842a8481ac9a5f3c
C++
foursking1/leetcode
/lengthoflastword.cpp
UTF-8
547
3.53125
4
[]
no_license
#include <iostream> using namespace std; enum STATE { Space, Char}; int lengthOfLastWord(const char *s) { int length = 0; STATE state = Space; while( *s != '\0' ) { if( *s == ' ') { if( state == Space) { s ++ ; } else { state = Space; s ++ ; } } else { if ( state == Space) { state = Char; s ++ ; length = 1; } else { s ++ ; length ++; } } } return length; } int main() { const char *s = "a ads"; cout << lengthOfLastWord(s)<< endl; }
true
cae141f7afe549fbc0c2979659cea7e4b22f9719
C++
EasonQiu/LeetCode
/289_Game of Life.cpp
UTF-8
1,974
3.453125
3
[]
no_license
#include <iostream> #include <vector> using namespace std; // 可以用2 bits来同时存储current和next的状态 // 例如:10表示从dead到live class Solution { public: int numNeighbors(const vector<vector<int>>& board, int bi, int bj){ int sum = 0; if (bi - 1 >= 0 && bj - 1 >= 0) sum += board[bi-1][bj-1]; if (bi - 1 >= 0 && bj >= 0) sum += board[bi-1][bj]; if (bi - 1 >= 0 && bj + 1 < board[bi].size()) sum += board[bi-1][bj+1]; if (bi >= 0 && bj - 1 >= 0) sum += board[bi][bj-1]; if (bi >= 0 && bj + 1 < board[bi].size()) sum += board[bi][bj+1]; if (bi + 1 < board.size() && bj - 1 >= 0) sum += board[bi+1][bj-1]; if (bi + 1 < board.size() && bj >= 0) sum += board[bi+1][bj]; if (bi + 1 < board.size() && bj + 1 < board[bi].size()) sum += board[bi+1][bj+1]; return sum; } void gameOfLife(vector<vector<int>>& board) { vector<vector<int>> newBoard; for (int i = 0; i< board.size(); i++) newBoard.push_back(vector<int>(board[i].size())); for (int i = 0; i < board.size(); i++){ for (int j = 0; j < board[i].size(); j++){ if (board[i][j] == 0){ if (numNeighbors(board, i, j) == 3) newBoard[i][j] = 1; else newBoard[i][j] = 0; }else if (board[i][j] == 1){ if (numNeighbors(board, i, j) == 2 || numNeighbors(board, i, j) == 3) newBoard[i][j] = 1; else newBoard[i][j] = 0; } } } if (board.size() > 0) swap(board, newBoard); } }; int main() { int a[] = {1,0,0}; vector<int> oneline(a,a+3); vector<vector<int>> board; board.push_back(oneline); board.push_back(oneline); board.push_back(oneline); Solution s; s.gameOfLife(board); return 0; }
true
63376db90a8d2daa89c03e29f727a2ca92395738
C++
jamg1906/Laboratorio_2_Avanzada
/Carrera.cpp
WINDOWS-1250
3,853
2.765625
3
[]
no_license
#include "Carrera.h" #include <string> #include <iostream> #include <stdio.h> #include <thread> // std::this_thread::sleep_for #include <chrono> using namespace System::Windows::Forms; using namespace System::IO; using std::string; using namespace System::Runtime::InteropServices; bool Ganador = false; string recorrido[80]; string* Inicio = &recorrido[0]; string* Final = &recorrido[69]; string* P_Tortuga = &recorrido[0]; string* P_Liebre = &recorrido[0]; void Carrera::Reiniciar_Vector() { P_Tortuga = &recorrido[0]; P_Liebre = &recorrido[0]; Ganador = false; Inicio = &recorrido[0]; Final = &recorrido[69]; P_Tortuga = &recorrido[0]; P_Liebre = &recorrido[0]; for (int i = 0; i < 70; i++) { string* j = &recorrido[i]; *j = "-"; recorrido[0] = "[BANG! ARRANCAN!]"; recorrido[69] = "."; } for (int i = 70; i < 80; i++) { string* g = &recorrido[i]; *g = "."; } } System::String^ Carrera::Mostrar_Vector() { System::String^ carrerafinal = ""; for (int i = 0; i < 70; i++) { char* cad2 = new char[recorrido[i].length() + 1]; cad2 = +strdup(recorrido[i].c_str()); System::String^ cadena = gcnew System::String(cad2); carrerafinal += cadena + " "; //System::Windows::Forms::MessageBox::Show(cadena); } std::this_thread::sleep_for(std::chrono::milliseconds(10)); System::Windows::Forms::MessageBox::Show(carrerafinal); carrerafinal += ""; return carrerafinal; } bool Carrera::Fin() { return Ganador; } void Carrera::Movimientos() { //Carrera::Mostrar_Vector(); int r = Carrera::Generar_aleatorio(); if (r >= 1 && r <= 5) { if (*(P_Tortuga+3) == ".") { *P_Tortuga = "-"; P_Tortuga = Final; *P_Tortuga = "T"; } else { *P_Tortuga = "-"; P_Tortuga += 3; *P_Tortuga = "T"; } } //Carrera::Mostrar_Vector(); if (r >= 6 && r <= 7) { if (*(P_Tortuga-6) != "-" && *(P_Tortuga -6) != "H") { *P_Tortuga = "-"; P_Tortuga = Inicio; *P_Tortuga = "T"; } else { *P_Tortuga = "-"; P_Tortuga += -6; *P_Tortuga = "T"; } } //Carrera::Mostrar_Vector(); if (r >= 8 && r <= 10) { if (*(P_Tortuga + 1) == ".") { *P_Tortuga = "-"; P_Tortuga = Final; *P_Tortuga = "T"; } else { *P_Tortuga = "-"; P_Tortuga += 1; *P_Tortuga = "T"; } } if (r >= 3 && r <= 4) { if (*(P_Liebre + 9) == ".") { *P_Liebre = "-"; P_Liebre = Final; *P_Liebre = "H"; } else { *P_Liebre = "-"; P_Liebre += 9; *P_Liebre = "H"; } } if (r ==5) { if (*(P_Liebre - 12) != "-" && *(P_Tortuga - 12) != "T") { *P_Liebre = "-"; P_Liebre = Inicio; *P_Liebre = "H"; } else { *P_Liebre = "-"; P_Liebre += -12; *P_Liebre = "H"; } } if (r >= 6 && r <= 8) { if (*(P_Liebre + 1) == ".") { *P_Liebre = "-"; P_Liebre = Final; *P_Liebre = "H"; } else { *P_Liebre = "-"; P_Liebre += 1; *P_Liebre = "H"; } } if (r >= 9 && r <= 10) { if (*(P_Liebre - 2) != "-" && *(P_Tortuga - 2) != "T") { *P_Liebre = "-"; P_Liebre = Inicio; *P_Liebre = "H"; } else { *P_Liebre = "-"; P_Liebre += -2; *P_Liebre = "H"; } } if (P_Liebre == P_Tortuga) { if (P_Liebre == Final) { *P_Liebre = "EMPATE!"; *P_Tortuga = "EMPATE!"; Ganador = true; } else { *P_Liebre = "[OUCH!]"; *P_Tortuga = "[OUCH!]"; } } else { *P_Liebre = "H"; *P_Tortuga = "T"; } if (P_Liebre == Final && Ganador == false) { System::Windows::Forms::MessageBox::Show("La liebre gana. Ni hablar."); Ganador = true; } if (P_Tortuga == Final && Ganador == false) { System::Windows::Forms::MessageBox::Show("LA TORTUGA GANA! BRAVO!"); Ganador = true; } //Carrera::Mostrar_Vector(); } int Carrera::Generar_aleatorio() { System::Random^ random = gcnew System::Random(); int num = random->Next(1, 10); return num; }
true
241a0a2aa1daf1aaeb75d53b30d708b01cc1d771
C++
cjswoduddn/algorithm-master
/programmers/kakao/2020blind/4songsearchv2.cpp
UTF-8
576
2.890625
3
[]
no_license
#include <string> #include <regex> #include <vector> using namespace std; void convertRegex(string& str){ for(int i = 0; i < str.size(); i++) if(str[i] == '?') str[i] = '.'; } vector<int> solution(vector<string> words, vector<string> qu){ vector<int> ans; vector<vector<string>> strs(10001); for(string& str : words){ strs[str.size()].push_back(str); } for(string& str : qu){ int cnt = 0; convertRegex(str); regex re(str); for(string& st : strs[str.size()]){ if(regex_match(st, re)) cnt++; } ans.push_back(cnt); } return ans; } int main(){ }
true
b85902e35e04d97a305aece585bc3cd395c4056b
C++
Topu920/MoonAroundEarthInC-
/main.cpp
UTF-8
4,641
2.71875
3
[]
no_license
#include<windows.h> #include<GL/glu.h> #include <bits/stdc++.h> #include <stdlib.h> #include <GL/glut.h> using namespace std; //Makes the image into a texture, and returns the id of the texture GLuint LoadTextureRAW(const char *filename, int width, int height) { GLuint textureId; unsigned char *data; FILE *file; //CODE SEGMENT 1 // open texture data file = fopen(filename, "r"); if (file == NULL) return 0; // allocate buffer data = (unsigned char*) malloc(width * height * 4); //read texture data fread(data, width * height * 4, 1, file); fclose(file); for(int i = 0; i < width * height ; ++i) { int index = i*3; unsigned char B,R; B = data[index]; R = data[index+2]; //B = data[index]; data[index] = R; data[index+2] = B; } glGenTextures(1, &textureId); //Make room for our texture glBindTexture(GL_TEXTURE_2D, textureId); //Tell OpenGL which texture to edit //Map the image to the texture glTexImage2D(GL_TEXTURE_2D, //Always GL_TEXTURE_2D 0, //0 for now GL_RGB, //Format OpenGL uses for image width, height, //Width and height 0, //The border of the image GL_RGB, //GL_RGB, because pixels are stored in RGB format GL_UNSIGNED_BYTE, //GL_UNSIGNED_BYTE, because pixels are stored //as unsigned number data); //The actual pixel data delete(data); return textureId; //Returns the id of the texture } GLuint textureId1,textureID2,textureId3; //The id of the textur GLUquadric *quad; double a; double moon; void initRendering() { glEnable(GL_DEPTH_TEST); glEnable(GL_NORMALIZE); glEnable(GL_COLOR_MATERIAL); quad = gluNewQuadric(); textureId1 = LoadTextureRAW("earthmap.bmp", 1000, 500); textureID2=LoadTextureRAW("moon.bmp",1024,720); textureId3 = LoadTextureRAW("space.bmp", 1000, 500); } void handleResize(int w, int h) { glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(70.0, (float)w / (float)h, 1.0, 200.0); } void drawmoon() { glEnable(GL_TEXTURE_2D); glPushMatrix();{ glRotatef(moon,0,0,1); glTranslatef(3,3,-8); glRotatef(90,1,0,0); glRotatef(a*3,0,1,0); glScalef(1.5,1,1.5); glBindTexture(GL_TEXTURE_2D, textureID2); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); gluQuadricTexture(quad,1); gluSphere(quad,.5,20,20); }glPopMatrix(); glDisable(GL_TEXTURE_2D); } void earth() { glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, textureId1); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); const double t = glutGet(GLUT_ELAPSED_TIME) / 1000.0; a = t*90.0; glPushMatrix();{ glTranslatef(0.0f, 0.0f, -10.0f); glRotatef(176.5,1.0f,2.0f,2.0f); glRotated(a*3,0,0,1); gluQuadricTexture(quad,1); gluSphere(quad,2,20,20); }glPopMatrix(); glDisable(GL_TEXTURE_2D); } void background() { glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, textureId3); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glPushMatrix(); { glTranslatef(0.0f, 0.0f, -10.0f); glBegin(GL_QUADS); glTexCoord2f(0.0f, 0.0f); glVertex3f(-8.0f, -7.0f, 0.0f); glTexCoord2f(1.0f, 0.0f); glVertex3f(7.0f, -7.0f, 0.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f(7.0f, 7.0f, 0.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f(-8.0f, 7.0f, 0.0f); glEnd(); }glPopMatrix(); glDisable(GL_TEXTURE_2D); } void drawScene() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); background(); earth(); drawmoon(); glutSwapBuffers(); } void update(int value) { moon+=1; if(moon>360) { moon=moon-360; } glutPostRedisplay(); glutTimerFunc(25,update,0); } int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); PlaySound("dil.wav", NULL,SND_ASYNC|SND_FILENAME|SND_LOOP); glutInitWindowSize(500, 500); glutInitWindowPosition(100,100); glutCreateWindow("earth-moon"); initRendering(); glutDisplayFunc(drawScene); glutTimerFunc(25,update,0); glutReshapeFunc(handleResize); glutMainLoop(); return 0; }
true
598da7eb86bc686e3e6eb4466adc9c8c6f496735
C++
batgui/notebook
/394. Decode String.cc
UTF-8
1,423
3.109375
3
[]
no_license
class Solution { int index = 0; public: string decodeString(string s) { int digit = 1; int previousIsDigit = false; string finalstr = ""; string localstr = ""; for (; index < s.size(); index++) { if (s[index] == ']') return finalstr; if (isdigit(s[index])) { if (!previousIsDigit) digit = s[index] - '0'; else digit = digit * 10 + (s[index] - '0'); previousIsDigit = true; } else if ((s[index] == '[')) { previousIsDigit = false; index ++; string str = decodeString(s); for (int j = 0; j < digit; j++) { finalstr += str; } digit = 1; while (index < s.size() && s[index] != ']') index++; } else { previousIsDigit = false; while(isalpha(s[index]) && index < s.size()) { localstr += s[index]; index++; } index--; for (int j = 0; j < digit; j++) { finalstr += localstr; } digit = 1; localstr = ""; } } return finalstr; } };
true
394b2c4d8e5df0d94d8a24bf7abbf51306b4fcb0
C++
Sadman007/DevSkill-Programming-Course---Basic---Public-CodeBank
/DevSkill_CP/Intermediate/Batch 5/Class 9/code.cpp
UTF-8
563
2.703125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; #define MAX 1000006 #define ll long long int twoPower(int N) { return 1 << N; } bool checkBit(int N,int x) { if (N&(1<<x) == 0) return 0; return 1; } int findSingleNumber(int *arr,int n) { int xor = 0; for(int i=0;i<n;i++) xor^=arr[i]; return xor; } int main() { /** file input output add these one/two lines (depending on what you want) just after int main() freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); **/ return 0; }
true
1364193d872155e6f8b7c953354e63c7805febe8
C++
therahulgoel/competitiveProgramming
/competitiveProgramming/competitiveProgramming/Mathematical/mathematical.hpp
UTF-8
642
2.828125
3
[ "MIT" ]
permissive
// // mathematical.hpp // DS // // Created by Rahul Goel on 7/26/17. // Copyright © 2017 Rahul Goel. All rights reserved. // #ifndef mathematical_hpp #define mathematical_hpp #include <stdio.h> //1. GCD void mathematical_gcd(int a, int b); //2. LCM void mathematical_lcm(int a, int b); //3. HCF void mathematical_hcf(int a, int b); //4. Given Number is prime or not void mathematical_primeornot(int number); //5. Fibonacci Series void mathematical_fibonacciseries(int upto); //6. Factorial int mathematical_factorial(int number); //7. Sum of n Natural Numbers void mathematical_sumofnnumbers(int number); #endif /* mathematical_hpp */
true
53fcfde71f67d1e90829583eebaac3ca5d0e1f3f
C++
MonadicLabs/AT11
/include/AT11/iobuffer.h
UTF-8
2,672
3.0625
3
[ "MIT" ]
permissive
#pragma once #include <string> #include <deque> #include <vector> namespace monadic { namespace AT11 { class Interpreter; class IOBuffer { friend class Interpreter; public: IOBuffer( bool echoEnabled = true ) :_echoEnabled(echoEnabled) { } virtual ~IOBuffer() { } void setEcho( bool v ) { _echoEnabled = v; } void write_output( const std::string& str ) { _outputBuffer.push_back( str ); } size_t output_size() { return _outputBuffer.size(); } bool get_output( std::string& str ) { if( _outputBuffer.size() ) { str = _outputBuffer.front(); _outputBuffer.pop_front(); return true; } return false; } private: // void write_input( const std::string& str ) { if( _echoEnabled ) write_output( str ); _inputString += str; cerr << "_intputString=" << _inputString << endl; updateInput(); } void write_input( uint8_t* buffer, size_t buffer_size ) { std::string strBuffer = (char*)buffer; write_input( strBuffer ); } bool get_input( std::string& str ) { if( _inputBuffer.size() ) { str = _inputBuffer.front(); _inputBuffer.pop_front(); return true; } return false; } size_t input_size() { return _inputBuffer.size(); } // std::deque< std::string > _outputBuffer; std::deque< std::string > _inputBuffer; std::string _inputString; void updateInput() { std::vector< string > lines = stringToLines( _inputString ); cerr << "--------" << endl; for( std::string l : lines ) { cerr << "*** line = #" << l << "#" << endl; // Remove characters from input buffer for( int k = 0; k < l.size(); ++k ) { _inputString.erase(0); } // interpret_line( l ); _inputBuffer.push_back( l ); } } std::vector<std::string> stringToLines(std::string string) { std::vector<std::string> result; std::string temp; int markbegin = 0; int markend = 0; for (int i = 0; i < string.length(); ++i) { if (string[i] == '\r' || string[i] == '\n') { markend = i; result.push_back(string.substr(markbegin, markend - markbegin)); markbegin = (i + 1); } } return result; } bool _echoEnabled; protected: }; } }
true
c0462afe954aa461e6be666f4ca467958a28421d
C++
jorgelp2/mecanio
/Programas/leer_numero/leer_numero.ino
UTF-8
1,096
2.515625
3
[]
no_license
void setup() { Serial.begin(9600); } void loop() { if (Serial.available() > 0) { String str = Serial.readStringUntil('\n'); String fila = str.substring(0,2); String columna = str.substring(2,4); String pax = str.substring(4,6); String pay = str.substring(6,8); long tamano = sizeof(str); //long tamano = strlen(str); int data = str.toInt(); int f = fila.toInt(); int c = columna.toInt(); int x = pax.toInt(); int y = pay.toInt(); //DEBUG(data); Serial.print("numero: "); Serial.print(data); //Serial.println("A"); Serial.print("longitud : "); Serial.print(tamano); //Serial.println("A"); Serial.print("fila: "); Serial.print(f); //Serial.println("A"); Serial.print("columna: "); Serial.print(c); //Serial.println("A"); Serial.print("coordenada x: "); Serial.print(x); //Serial.println("A"); Serial.print("coordenada y: "); Serial.print(y); //Serial.println("A"); Serial.println(""); //invento Se puede comentar } }
true
49c51df351d9ea69be2cb3c427fb0311afef18b2
C++
serkanbodur/OOP_Cpp_Series
/7.Example-Polymorphic Media Players/MusicPlayer.cpp
UTF-8
1,003
2.890625
3
[ "MIT" ]
permissive
#include<iostream> #include<string> #include"MusicPlayer.h" using namespace std; void MusicPlayer::BackWard() { if (supportedFormatCount == 1) cout << "MusicPlayer : Does not support the backward operation" << endl; } void MusicPlayer::Forward() { if (supportedFormatCount == 1) cout << "MusicPlayer : Does not support the forward operation" << endl; } void MusicPlayer::EjectMedia() { if (supportedFormatCount == 2) cout << "MusicPlayer : Ejecting the media : " << Player::mediaName << endl; } void MusicPlayer::MounthMedia(const string&mediaName1) { Player::mediaName = mediaName1; cout << "MusicPlayer : " << "Trying to mount the media... " << endl; cout << "MusicPlayer : " << "Media is supported and playable" << endl; } MusicPlayer::MusicPlayer(int maxVolumeLevel1, string *supportedFormats1, int supportedFormatCount1) :Player(maxVolumeLevel1), supportedFormats(supportedFormats1), supportedFormatCount(supportedFormatCount1) { } MusicPlayer::~MusicPlayer() {}
true
c91d9bcbeaf4a5b18981cae9e242288504d38ab4
C++
RudenkoDmitriy/MyHomeWorking
/1_semestr/5/ListPoint/ListPoint/main.cpp
UTF-8
1,865
4.15625
4
[]
no_license
#include <stdio.h> #include <iostream> #include "List.h" using namespace std; //Interchange value in input positions. void swap(List *list, Position temp, Position next) { changeValue(list, temp, returnByPos(list, temp) ^ returnByPos(list, next)); changeValue(list, next, returnByPos(list, temp) ^ returnByPos(list, next)); changeValue(list, temp, returnByPos(list, temp) ^ returnByPos(list, next)); } //Insert head element to sort list. void insertHeadToSort(List* list) { for (Position temp = head(list); next(list,temp) != nullptr && returnByPos(list, temp) > returnByPos(list, next(list,temp)); temp = next(list,temp)) { swap(list, temp, next(list, temp)); } } //Function create a new empty list, sorting input data. //Operations with list: //0 - escape; //1 - add value in list; //2 - remove value; //3 - print list. //With values 2,3,113,124,43 test is positive. //Negative test with value 's','4.3'. int main() { List *list = createList(); int numberOfOperation = 1; cout << "Operations with list:" << endl; cout << "0 - escape;" << endl; cout << "1 - add value in list;"<< endl; cout << "2 - remove value;" << endl; cout << "3 - print list." << endl; while (numberOfOperation) { cout << "Enter the number of operation" << endl; cin >> numberOfOperation; switch (numberOfOperation) { case 0: { break; } case 1: { int addValue = 0; cout << "Enter the added value" << endl; cin >> addValue; insertToHead(list, addValue); insertHeadToSort(list); break; } case 2: { int removValue = 0; cout << "Enter the removed value" << endl; cin >> removValue; remove(list, returnPos(list, removValue)); break; } case 3: { print(list); break; } default: { cout << "Incorrect value" << endl; break; } } } deleteList(list); return 0; }
true
3e828c197627cf79a3917ec13854681f81756f15
C++
rongyuhuang/bpmbase
/kbarutils/tickstorage.h
UTF-8
1,903
2.78125
3
[]
no_license
#ifndef TICKTSTORAGE_H #define TICKTSTORAGE_H #include "easyctp/easyctp.h" #include <vector> // // 在这里不要计算各个周期的bar,只提供最细粒度的如1分钟的就行了 // 计算各周期的bar,应该由信号系统自己去做,每个算法的要求都不一样 // 信号系统是独立并行线程集合,不是事件驱动,这里算了也没用 // struct TickVector { TickData** data; // ticks int len; // ticks // 当日统计数据 double openPrice = 0.0; // 今日开盘价 double highPrice = 0.0; // 今日最高价 double lowPrice = 0.0; // 今日最低价 double preClosePrice = 0.0; // 昨日收盘价 double upperLimit = 0.0; // 涨停价 double lowerLimit = 0.0; // 跌停价 TickVector() : len(0) , data(0) { } TickVector(TickData** _data, int _len) : len(_len) , data(_data) { } TickData* operator[](int i) const { return data[i]; } }; class TickStorage { public: TickStorage& operator=(const TickStorage&) = delete; TickStorage(const TickStorage&) = delete; TickStorage(int cap); ~TickStorage(); TickData* appendTick(TickData* data); void getSnapshot(TickVector& result); bool getLatestTick(TickData& result); // 是否有数据 TickData* getLatestTick(); double openPrice(); double highPrice(); double lowPrice(); double preClosePrice(); double upperLimit(); double lowerLimit(); private: std::vector<TickData*> ticks_; // ticks double openPrice_ = 0; // 今日开盘价 double highPrice_ = 0; // 今日最高价 double lowPrice_ = 0; // 今日最低价 double preClosePrice_ = 0; // 昨日收盘价 double upperLimit_ = 0; // 涨停价 double lowerLimit_ = 0; // 跌停价 private: int cap_ = 86400; TickData* latestTick_ = nullptr; }; #endif // TICKTSTORAGE_H
true
1be9ec2622efc3bd40bc741d5c8024312f6d4879
C++
tlow14/1220-Projects
/Project3/vehicle.cpp
UTF-8
1,129
3.390625
3
[]
no_license
/*Author: Tom Lowry Purpose: This file includes the implementation of Vehicle class (defined in Vehicle.h) Date: 26 March 2018 Summary of Modification: None */ #include "vehicle.h" #include <cstring> //Needed for static variable to declared it for all classes ostream* Vehicle::out= &cout; //constructor initializes the variable Vehicle::Vehicle(string n) { name = new char[n.length() + 1]; strcpy(name, n.c_str()); } //Copy Constructor. Makes a deep copy of vehicle Vehicle::Vehicle(const Vehicle &v) { string s; s = v.name; name = new char[s.length() + 1]; //copies the name from v to this object's name strcpy(name, v.name); } //Destructor frees the char* name Vehicle::~Vehicle() { delete[] name; } //Assignment opertator allows for a deep copy Vehicle& Vehicle::operator=(const Vehicle &v) { //makes sure its point to something different to begin with if (this == &v) { return *this; } else { //frees the char* it has already and then makes a new name delete[] name; string s; s = v.name; name = new char[s.length() + 1]; //Copies the attribute strcpy(name, v.name); return *this; } }
true
04d1c483d820f242d9aaf5b82d1fc21b06d7c0a4
C++
NewSNode/zdb
/core/page_buffer.h
UTF-8
1,191
2.640625
3
[ "BSD-3-Clause" ]
permissive
/** * Copyright (c) 2016, Paul Asmuth <paul@asmuth.com> * All rights reserved. * * This file is part of the "libzdb" project. libzdb is free software licensed * under the 3-Clause BSD License (BSD-3-Clause). */ #pragma once #include <stdlib.h> #include <algorithm> #include <vector> namespace tsdb { class PageBuffer { public: PageBuffer(); PageBuffer(size_t value_size); PageBuffer(const PageBuffer& o) = delete; PageBuffer(PageBuffer&& o) ; PageBuffer& operator=(const PageBuffer& o); PageBuffer& operator=(PageBuffer&& o); ~PageBuffer(); void update(size_t pos, const void* value, size_t value_len); void insert(size_t pos, uint64_t time, const void* value, size_t value_len); void append(uint64_t time, const void* value, size_t value_len); void getTimestamp(size_t pos, uint64_t* timestamp) const; void getValue(size_t pos, void* value, size_t value_len) const; size_t getSize() const; void encode(std::string* out) const; bool decode(const char* data, size_t len); protected: using ValueVectorUInt64Type = std::vector<uint64_t>; size_t value_size_; std::vector<uint64_t> timestamps_; std::vector<std::string> values_; }; } // namespace tsdb
true
456cd2eda583354eb7e2e5f170276b4bd8d25eaa
C++
ravinderdevesh/SPOJ
/BUSYMAN-13841925-src.cpp
UTF-8
723
2.84375
3
[]
no_license
#include<iostream> #include<stdio.h> #include<algorithm> using namespace std; struct activity { int first,second; }; bool val(struct activity a,struct activity b) { if (a.first == b.first) return a.second>b.second; return a.first<b.first; } activity act[100001]; int main() { int t,i,count,num; cin>>t; while(t--) { cin>>num; count=0; for(i=0;i<num;i++) { scanf("%d %d",&act[i].first,&act[i].second); } sort(act,act+num,val); count=1; int lowerbound=act[num-1].first; for(i=num-2;i>=0;i--) { if(lowerbound>=act[i].second) { count++; lowerbound=act[i].first; } } printf("%d\n",count); } }
true
54e5044834094fb6caad6dd2d3c73634f5ef1fd0
C++
kverty/homeworks
/semester1/3 homework/2.cpp
UTF-8
1,583
3.96875
4
[]
no_license
#include <iostream> #include "string.h" #include <stdio.h> using namespace std; void swap(char &x, char &y) { char t = x; x = y; y = t; } void qsort(char* arr, int left, int right) { int i = left; int j = right; int m = (i + j) / 2; while (i <= j) { while (arr[i] - '0' < arr[m] - '0') i++; while (arr[j] - '0' > arr[m] - '0') j--; if (i <= j) { if (arr[i] != arr[j]) swap(arr[i], arr[j]); i++; j--; } } if (i < right) qsort(arr, i, right); if (left < j) qsort(arr, left, j); } int main() { int const size = 100; char string1[size]; char string2[size]; cout << "Enter two strings, and I will say you if you can rearrange one to another : " << endl; cout << "First : " << endl; scanf("%s", string1); cout << "and second : " << endl; scanf("%s", string2); if (strlen(string1) != strlen(string2)) { cout << "NO" << endl; return 0; } else { int length = strlen(string1); qsort(string1, 0, length - 1); qsort(string2, 0, length - 1); bool canBeRearranged = true; for (int i = 0; i < length; i++) { if (string1[i] != string2[i]) { canBeRearranged = false; break; } } if (canBeRearranged) cout << "Yes" << endl; else cout << "No" << endl; return 0; } }
true
a004b2c972fe1ce9cb06e0d1677ed5aac264e220
C++
davmrtl/IFT2008-Laboratoires-E2017
/Laboratoire3/PileTD/Pile.h
UTF-8
1,754
3.40625
3
[]
no_license
/** * \file Pile.h * \brief Classe définissant le type abstrait pile * \author Ludovic Trottier * \author Mathieu Dumoulin <mathieu.dumoulin@gmail.com> été 2013 * \author Abder * \version 0.3 * \date mai 2014 * * Représentation dans une liste chaînée */ #ifndef PILE_H #define PILE_H #include <iostream> #include <stdexcept> namespace labPileFile { /** * \class Pile * * \brief Classe générique représentant une Pile. * * La classe gère une pile générique. L'implémentation * se fait dans une liste chaînée. */ template<typename T> class Pile { public: Pile(); Pile(const Pile &); ~Pile(); void empiler(const T &); T depiler(); bool estVide() const; size_t taille() const; const T& top() const; const T & operator[](const int &) const; const Pile<T> & operator =(const Pile<T> &); template<typename U> friend std::ostream& operator <<(std::ostream &, const Pile<U> &); private: /** * \class Noeud * * \brief Classe interne représentant un noeud (une position) dans la pile. */ class Noeud { public: T m_el; /*!<L'élément de base de la pile*/ Noeud * m_suivant; /*!<Un pointeur vers le noeud suivant*/ /** * \brief Constructeur de la classe Noeud. * * \post Un noeud typique est initialisé. */ Noeud(const T& data_item, Noeud * next_ptr = 0) : m_el(data_item), m_suivant(next_ptr) { } }; /** * \typedef typedef Noeud *elem * \brief Définition d'un pointeur sur un Noeud * * Pour abréger les écritures */ typedef Noeud * elem; elem m_sommet; /*!<Pointeur vers le premier noeud, le sommet de la pile*/ int m_cardinalite; /*!<Cardinalité de la pile*/ // Méthodes privées void _detruire(); void _copier(const Pile<T> &); }; } //Fin du namespace #include "Pile.hpp" #endif
true
0ec4f9963b92f1bd229d0025926b506809ba20dc
C++
maxfish/GameDevNights
/game/game/Player.cpp
UTF-8
1,923
2.90625
3
[ "MIT" ]
permissive
// // Created by max on 05/02/17. // #include "Player.h" #include "Game.h" static const int WALK_SPEED = 2; Player::Player(Graphics &graphics, InputController *inputController, int joystick_index) { Entity(); _framesStore = new FramesStore(graphics); _framesStore->load("resources/sprites/drako", "drako.json"); // Game FPS might be different from the ones expected by the animations _speed_adjust = _framesStore->getAnimationsFPS() / (float)Game::FPS; _inputController = inputController; _joystick_index = joystick_index; _sprite = new Sprite(_framesStore); _sprite->playAnimation("stand", 0); _direction = DIR_RIGHT; } void Player::handleInput(float game_speed) { Joystick *joystick = _inputController->getJoystickFromIndex(_joystick_index); if (!joystick) { return; } bool joy_right = joystick->isButtonDown(SDL_CONTROLLER_BUTTON_DPAD_RIGHT) || joystick->getAxisValue(SDL_CONTROLLER_AXIS_LEFTX) > 0.5; bool joy_left = joystick->isButtonDown(SDL_CONTROLLER_BUTTON_DPAD_LEFT) || joystick->getAxisValue(SDL_CONTROLLER_AXIS_LEFTX) < -0.5; if (joy_left) { _direction = DIR_LEFT; } else if (joy_right) { _direction = DIR_RIGHT; } Uint16 flags = (Uint16) (Sprite::FLAG_LOOP_ANIMATION | (_direction == DIR_LEFT ? Sprite::FLAG_FLIP_X : 0)); if (joy_right) { _position_x += WALK_SPEED * game_speed; _sprite->playAnimation("walk", flags); } else if (joy_left) { _position_x -= WALK_SPEED * game_speed; _sprite->playAnimation("walk", flags); } else { _sprite->playAnimation("stand", flags); } } void Player::update(float gameSpeed) { _sprite->setPosition((int) _position_x, (int) _position_y); _sprite->update(gameSpeed * _speed_adjust); } void Player::draw(Graphics &graphics) { _sprite->draw(graphics); }
true
254854f0f8d28b8092e05ac1b02731283d23fe7f
C++
Orion116/College-Assignments
/MTH-221/lab20/lab 20/lab 20.cpp
UTF-8
2,311
3.671875
4
[]
no_license
// lab 20.cpp : Defines the entry point for the console application. // Joshua Wiley // mth22113 #include "stdafx.h" #include "rational.h" using namespace std; int _tmain(int argc, _TCHAR* argv[]) { // vector declearations rational a, b, c, S, M, SM; // user inputs fractions cout << "Enter the first fraction: "; cin >> a; cout << "Enter the second fraction: "; cin >> b; cout << "Enter the third fraction: "; cin >> c; system("cls"); // calculations S = a + b; M = b * c; SM = c + a * b; // display answers cout << "\n Answers:"; cout << "\n\ta + b =" << S << endl; cout << "\tb * c =" << M << endl; cout << "\tc + a * b =" << SM << "\n"; return 0; } /*********************** * * Helper functions * ***********************/ // Addition rational rational::operator + (rational N) { rational Sum; Sum.dem = lcd(N.dem); Sum.num = num * (Sum.dem / dem) + N.num * (Sum.dem / N.dem); Sum.reduce(); return Sum; } // multiplication rational rational::operator * (rational N) { rational M; M.num = num * N.num; M.dem = dem * N.dem; M.reduce(); return M; } // reduces the fraction to the lowest terms void rational::reduce() { long gcf; gcf = greatestcommonfactor(num, dem); num/=gcf; dem/=gcf; } // finds the greatest common factor long rational::greatestcommonfactor(long x1, long x2) { long minnum, maxnum, gcf; minnum = min(abs(x1), abs(x2)); maxnum = max(abs(x1), abs(x2)); gcf = minnum; while(maxnum % gcf !=0 || minnum % gcf !=0) gcf--; return gcf; } // finds the least common multiple long rational::lcd(long d2) { long mindem, maxdem, multiple; mindem = min(dem, d2); maxdem = max(dem, d2); multiple = 1; while(maxdem*multiple%mindem !=0) multiple++; return maxdem*multiple; } // overloaded input istream& operator >> (istream& cin, rational& f) { cin >> f.num; cin.ignore(); cin >> f.dem; // validates n / 0 errors and 0 / n while (f.num == 0 || f.dem == 0) { cout << "\nRe-enter fraction: "; cin >> f.num; cin.ignore(); cin >> f.dem; cout << "\n"; } return cin; } // custom cout display ostream& operator << (ostream& cout, rational& O) { cout << " " << O.num << " / " << O.dem; return cout; }
true
a01344f57a36f47867a9eadc78e317614330b09d
C++
yaesoubilab/AgentBasedSIRlib
/TestSIRlib/SIRSimRunner.cpp
UTF-8
10,822
2.546875
3
[]
no_license
#include "SIRSimRunner.h" SIRSimRunner::SIRSimRunner(string _fileName, int _nTrajectories, double _lambda, double _gamma, \ long _nPeople, unsigned int _ageMin, unsigned int _ageMax, \ unsigned int _ageBreak, unsigned int _tMax, unsigned int _deltaT, \ unsigned int _pLength) { fileName = _fileName; nTrajectories = _nTrajectories; lambda = _lambda; gamma = _gamma; nPeople = _nPeople; ageMin = _ageMin; ageMax = _ageMax; ageBreak = _ageBreak; tMax = _tMax; deltaT = _deltaT; pLength = _pLength; if (nTrajectories < 1) throw out_of_range("nTrajectories < 1"); } SIRSimRunner::~SIRSimRunner(void) { delete [] SIRsims; } using RunType = SIRSimRunner::RunType; template<> bool SIRSimRunner::Run<RunType::Serial>(void) { bool succ = true; RNG *masterRNG = new RNG(42); RNG **servantRNGs = new RNG *[nTrajectories]; for (int i = 0; i < nTrajectories; ++i) servantRNGs[i] = new RNG( masterRNG->mt_() ); // Allocate array of SIRSimulation pointers, then instantiate SIRSimulations SIRsims = new SIRSimulation *[nTrajectories]; for (int i = 0; i < nTrajectories; ++i) SIRsims[i] = new SIRSimulation(servantRNGs[i], lambda, gamma, nPeople, ageMin, ageMax, ageBreak, tMax, deltaT, pLength); // Run each SIRSimulation for (int i = 0; i < nTrajectories; ++i) succ &= SIRsims[i]->Run(); // Note: freeing the RNGs means that Run() cannot be called again! delete masterRNG; delete [] servantRNGs; return succ; } template<> bool SIRSimRunner::Run<RunType::Parallel>(void) { bool succ = true; // Create futures future<bool> *futures = new future<bool>[nTrajectories]; // Create master RNG and seed servant RNGs with values from master RNG. RNG *masterRNG = new RNG(time(NULL)); RNG **servantRNGs = new RNG *[nTrajectories]; for (int i = 0; i < nTrajectories; ++i) servantRNGs[i] = new RNG( masterRNG->mt_() ); // Allocate array of SIRSimulation pointers, then instantiate SIRSimulations SIRsims = new SIRSimulation *[nTrajectories]; for (int i = 0; i < nTrajectories; ++i) SIRsims[i] = new SIRSimulation(servantRNGs[i], lambda, gamma, nPeople, ageMin, ageMax, ageBreak, tMax, deltaT, pLength); // Run each SIRSimulation for (int i = 0; i < nTrajectories; ++i) futures[i] = async(launch::async | launch::deferred, \ &SIRSimulation::Run, \ SIRsims[i]); // Wait for all tasks to finish running and detect errors (barrier) for (int i = 0; i < nTrajectories; ++i) succ &= futures[i].get(); // Note: freeing the RNGs means that Run() cannot be called again! delete masterRNG; delete [] servantRNGs; delete [] futures; return succ; } std::vector<SIRTrajectoryResult> SIRSimRunner::GetTrajectoryResults(void) { std::vector<SIRTrajectoryResult> res; for (size_t i = 0; i < nTrajectories; ++i) res.push_back( getTrajectoryResult(i) ); return res; } SIRTrajectoryResult SIRSimRunner::GetTrajectoryResult(size_t i) { if (i >= nTrajectories) throw std::out_of_range("i was too small or too big"); return getTrajectoryResult(i); } std::vector<string> SIRSimRunner::Write(void) { bool succ = true; map<TimeStatType, string> columns { {TimeStatType::Sum, "Total"}, {TimeStatType::Mean, "Average"}, {TimeStatType::Min, "Minimum"}, {TimeStatType::Max, "Maximum"} }; TimeSeriesExport<int> TSExSusceptible(fileName + string("-susceptible.csv")); TimeSeriesExport<int> TSExInfected (fileName + string("-infected.csv")); TimeSeriesExport<int> TSExRecovered (fileName + string("-recovered.csv")); TimeSeriesExport<int> TSExInfections (fileName + string("-infections.csv")); TimeSeriesExport<int> TSExRecoveries (fileName + string("-recoveries.csv")); TimeStatisticsExport TSxExSusceptible(fileName + string("-susceptible-statistics.csv"), columns); TimeStatisticsExport TSxExInfected (fileName + string("-infected-statistics.csv"), columns); TimeStatisticsExport TSxExRecovered (fileName + string("-recovered-statistics.csv"), columns); TimeStatisticsExport TSxExInfections (fileName + string("-infections-statistics.csv"), columns); TimeStatisticsExport TSxExRecoveries (fileName + string("-recoveries-statistics.csv"), columns); PyramidTimeSeriesExport PTSExSusceptible(fileName + string("-susceptible-pyramid.csv")); PyramidTimeSeriesExport PTSExInfected (fileName + string("-infected-pyramid.csv")); PyramidTimeSeriesExport PTSExRecovered (fileName + string("-recovered-pyramid.csv")); PyramidTimeSeriesExport PTSExInfections (fileName + string("-infections-pyramid.csv")); PyramidTimeSeriesExport PTSExRecoveries (fileName + string("-recoveries-pyramid.csv")); PyramidDataExport<double> PDExCaseProfile(fileName + string("-cases-by-age.csv")); std::vector<string> writes { fileName + string("-susceptible.csv"), fileName + string("-infected.csv"), fileName + string("-recovered.csv"), fileName + string("-infections.csv"), fileName + string("-recoveries.csv"), fileName + string("-susceptible-statistics.csv"), fileName + string("-infected-statistics.csv"), fileName + string("-recovered-statistics.csv"), fileName + string("-infections-statistics.csv"), fileName + string("-recoveries-statistics.csv"), fileName + string("-susceptible-pyramid.csv"), fileName + string("-infected-pyramid.csv"), fileName + string("-recovered-pyramid.csv"), fileName + string("-infections-pyramid.csv"), fileName + string("-recoveries-pyramid.csv"), fileName + string("-cases-by-age.csv") }; // For each SIRSimulation, add its data to our exporters for (int i = 0; i < nTrajectories; ++i) { TimeSeries<int> *Susceptible = SIRsims[i]->GetData<TimeSeries<int>>(SIRData::Susceptible); TimeSeries<int> *Infected = SIRsims[i]->GetData<TimeSeries<int>>(SIRData::Infected); TimeSeries<int> *Recovered = SIRsims[i]->GetData<TimeSeries<int>>(SIRData::Recovered); TimeSeries<int> *Infections = SIRsims[i]->GetData<TimeSeries<int>>(SIRData::Infections); TimeSeries<int> *Recoveries = SIRsims[i]->GetData<TimeSeries<int>>(SIRData::Recoveries); TimeStatistic *SusceptibleSx = SIRsims[i]->GetData<TimeStatistic>(SIRData::Susceptible); TimeStatistic *InfectedSx = SIRsims[i]->GetData<TimeStatistic>(SIRData::Infected); TimeStatistic *RecoveredSx = SIRsims[i]->GetData<TimeStatistic>(SIRData::Recovered); TimeStatistic *InfectionsSx = SIRsims[i]->GetData<TimeStatistic>(SIRData::Infections); TimeStatistic *RecoveriesSx = SIRsims[i]->GetData<TimeStatistic>(SIRData::Recoveries); PyramidTimeSeries *SusceptiblePyr = SIRsims[i]->GetData<PyramidTimeSeries>(SIRData::Susceptible); PyramidTimeSeries *InfectedPyr = SIRsims[i]->GetData<PyramidTimeSeries>(SIRData::Infected); PyramidTimeSeries *RecoveredPyr = SIRsims[i]->GetData<PyramidTimeSeries>(SIRData::Recovered); PyramidTimeSeries *InfectionsPyr = SIRsims[i]->GetData<PyramidTimeSeries>(SIRData::Infections); PyramidTimeSeries *RecoveriesPyr = SIRsims[i]->GetData<PyramidTimeSeries>(SIRData::Recoveries); PyramidData<double> *CaseProfile = SIRsims[i]->GetData<PyramidData<double>>(SIRData::Infections); // Add succ &= TSExSusceptible.Add(Susceptible); succ &= TSExInfected.Add(Infected); succ &= TSExRecovered.Add(Recovered); succ &= TSExInfections.Add(Infections); succ &= TSExRecoveries.Add(Recoveries); succ &= TSxExSusceptible.Add(SusceptibleSx); succ &= TSxExInfected.Add(InfectedSx); succ &= TSxExRecovered.Add(RecoveredSx); succ &= TSxExInfections.Add(InfectionsSx); succ &= TSxExRecoveries.Add(RecoveriesSx); succ &= PTSExSusceptible.Add(SusceptiblePyr); succ &= PTSExInfected.Add(InfectedPyr); succ &= PTSExRecovered.Add(RecoveredPyr); succ &= PTSExInfections.Add(InfectionsPyr); succ &= PTSExRecoveries.Add(RecoveriesPyr); succ &= PDExCaseProfile.Add(CaseProfile); } // Write succ &= TSExSusceptible.Write(); succ &= TSExInfected.Write(); succ &= TSExRecovered.Write(); succ &= TSExInfections.Write(); succ &= TSExRecoveries.Write(); succ &= TSxExSusceptible.Write(); succ &= TSxExInfected.Write(); succ &= TSxExRecovered.Write(); succ &= TSxExInfections.Write(); succ &= TSxExRecoveries.Write(); succ &= PTSExSusceptible.Write(); succ &= PTSExInfected.Write(); succ &= PTSExRecovered.Write(); succ &= PTSExInfections.Write(); succ &= PTSExRecoveries.Write(); succ &= PDExCaseProfile.Write(); printf("Finished writing\n"); return succ ? writes : std::vector<std::string>{}; } SIRTrajectoryResult SIRSimRunner::getTrajectoryResult(size_t i) { struct SIRTrajectoryResult res; res.Susceptible = SIRsims[i]->GetData<PrevalenceTimeSeries<int>>(SIRData::Susceptible); res.Infected = SIRsims[i]->GetData<PrevalenceTimeSeries<int>>(SIRData::Infected); res.Recovered = SIRsims[i]->GetData<PrevalenceTimeSeries<int>>(SIRData::Recovered); res.Infections = SIRsims[i]->GetData<IncidenceTimeSeries<int>>(SIRData::Infections); res.Recoveries = SIRsims[i]->GetData<IncidenceTimeSeries<int>>(SIRData::Recoveries); res.SusceptibleSx = SIRsims[i]->GetData<TimeStatistic>(SIRData::Susceptible); res.InfectedSx = SIRsims[i]->GetData<TimeStatistic>(SIRData::Infected); res.RecoveredSx = SIRsims[i]->GetData<TimeStatistic>(SIRData::Recovered); res.InfectionsSx = SIRsims[i]->GetData<TimeStatistic>(SIRData::Infections); res.RecoveriesSx = SIRsims[i]->GetData<TimeStatistic>(SIRData::Recoveries); res.SusceptiblePyr = SIRsims[i]->GetData<PyramidTimeSeries>(SIRData::Susceptible); res.InfectedPyr = SIRsims[i]->GetData<PyramidTimeSeries>(SIRData::Infected); res.RecoveredPyr = SIRsims[i]->GetData<PyramidTimeSeries>(SIRData::Recovered); res.InfectionsPyr = SIRsims[i]->GetData<PyramidTimeSeries>(SIRData::Infections); res.RecoveriesPyr = SIRsims[i]->GetData<PyramidTimeSeries>(SIRData::Recoveries); res.CaseProfile = SIRsims[i]->GetData<PyramidData<double>>(SIRData::Infections); return res; }
true
dde394b0c4a04cea351f69ee2f9167c2b6f9664e
C++
alexandraback/datacollection
/solutions_5731331665297408_0/C++/Theogry/CODEJAM_1B_C.cpp
UTF-8
2,315
2.5625
3
[]
no_license
#include <cstdio> #include <cstdlib> #include <algorithm> #include <queue> #include <cmath> #include <iostream> #include <fstream> #include <string> #include <vector> #include <memory.h> using namespace std; #define FOR(i,s,e) for (int i=(s); i<(e); i++) #define FOE(i,s,e) for (int i=(s); i<=(e); i++) #define FOD(i,s,e) for (int i=(s); i>=(e); i--) #define CLR(a,x) memset(a, x, sizeof(a)) #define EXP(i,l) for (int i=(l); i; i=qn[i]) #define LL long long #define eps 1e-6 #define pi acos(-1.0) LL max(LL a,LL b){if (a>b){return a;} else {return b;}} LL min(LL a,LL b){if (a<b){return a;} else {return b;}} struct P{ double x, y; P(){} P(double x, double y):x(x) , y(y){} P operator+ (const P &a) const {return P(x+a.x, y+a.y);} P operator- (const P &a) const {return P(x-a.x, y-a.y);} double operator^ (const P &a) const {return x*a.x+y*a.y;} void in(){scanf("%lf%lf", &x, &y);} void out(){printf("REQUIRED %.7f %.7f\n", x, y);} double dist(P a, P b) {return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));} double sqdist(P a, P b) {return (a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y);} }; int n, m; int exist[51][51]; int code[51]; int way[51], h; int v[51]; void DFS(int u, int p){ v[u] = 1; way[++h] = code[u]; int good = -1; FOE(i, 1, n){ good = -1; FOE(j, 1, n){ if ((exist[u][j]) && (!v[j])){ if (good == -1) good = j; else if (code[good] > code[j]) good = j; } } if (good == -1) return; DFS(good, u); } } void solve(){ scanf("%d%d", &n, &m); h = 0; FOE(i, 1, n) v[i] = 0; FOE(i, 1, n) FOE(j, 1, n) exist[i][j] = 0; FOE(i, 1, n) scanf("%d", &code[i]); FOE(i, 1, m){ int a, b; scanf("%d%d", &a, &b); exist[a][b] = exist[b][a] = 1; } int small = 1; FOE(i, 2, n) if (code[i] < code[small]) small = i; DFS(small, -1); FOE(i, 1, h) printf("%d", way[i]); printf("\n"); } int main(){ freopen("C-small-attempt0 (1).in", "r", stdin); freopen("out.out", "w", stdout); int x; scanf("%d", &x); FOE(i, 1, x) { printf("Case #%d: ", i); solve(); } return 0; }
true
06595486f9991b85b879437797f7e1e00c2062a0
C++
GuMiner/agow
/Managers/ModelRenderStore.cpp
UTF-8
2,062
2.59375
3
[ "MIT" ]
permissive
#include <glm\gtc\matrix_transform.hpp> #include "Generators\PhysicsGenerator.h" #include "logging\Logger.h" #include "Physics.h" #include "ModelRenderStore.h" // TODO these should be calculated and elsewhere. const int MODELS_PER_RENDER = 65536; const int MODEL_TEXTURE_SIZE = 512; ModelRenderStore::ModelRenderStore(GLuint mvMatrixImageId, GLuint shadingColorAndSelectionImageId) : mvMatrixImageId(mvMatrixImageId), shadingColorAndSelectionImageId(shadingColorAndSelectionImageId) { } unsigned int ModelRenderStore::GetInstanceCount() { return shadingColorSelectionStore.size() / 2; } void ModelRenderStore::AddModelToStore(Model* model) { if (GetInstanceCount() == MODELS_PER_RENDER) { // TODO handle this scenario so we cannot hit it. Logger::LogError("Cannot render model, too many renders of this model type attempted!"); return; } glm::mat4 mvMatrix = glm::scale(PhysicsGenerator::GetBodyMatrix(model->body), model->scaleFactor); matrixStore.push_back(mvMatrix[0]); matrixStore.push_back(mvMatrix[1]); matrixStore.push_back(mvMatrix[2]); matrixStore.push_back(mvMatrix[3]); shadingColorSelectionStore.push_back(model->color); shadingColorSelectionStore.push_back(glm::vec4(model->selected ? 0.40f : 0.0f)); } void ModelRenderStore::InsertInModelStore(unsigned int location, Model* model) { if (location == GetInstanceCount()) { AddModelToStore(model); } else { glm::mat4 mvMatrix = glm::scale(PhysicsGenerator::GetBodyMatrix(model->body), model->scaleFactor); matrixStore[location * 4] = mvMatrix[0]; matrixStore[location * 4 + 1] = mvMatrix[1]; matrixStore[location * 4 + 2] = mvMatrix[2]; matrixStore[location * 4 + 3] = mvMatrix[3]; shadingColorSelectionStore[location * 2] = model->color; shadingColorSelectionStore[location * 2 + 1] = glm::vec4(model->selected ? 0.40f : 0.0f); } } void ModelRenderStore::Clear() { matrixStore.clear(); shadingColorSelectionStore.clear(); }
true
d3759c5d6ecea0ccf53bf1d86cc7d524cc2d4f28
C++
mananssnay/SuperAlcoholDispenser
/UnitTest/servo/servo.ino
UTF-8
421
2.671875
3
[]
no_license
#include <Servo.h> Servo myservo; int sensor = 0; void setup(){ myservo.attach(9); } void loop(){ sensor = digitalRead(sensor); for(sensor=0; sensor<=180; sensor++){ myservo.write(sensor); delay(15); } for(sensor=180; sensor>=0; sensor--){ myservo.write(sensor); delay(15); } }
true
3740060a00309dcd41a72aaf32bba526e3ea47c3
C++
j-mathes/PPP
/Chapter 13/Classes/Regular_polygon.cpp
UTF-8
475
3.171875
3
[]
no_license
#include "Regular_polygon.h" void Graph_lib::Regular_polygon::draw_lines() const { Polygon poly; for (int i=0; i<s; ++i) { poly.add(polygon_point(i * 360 / s)); } poly.draw_lines(); } Graph_lib::Point Graph_lib::Regular_polygon::polygon_point(int d) const { double radians = d * 3.14159265 / 180; Point result; result.x = static_cast<int>(center().x + radius() * cos(radians)); result.y = static_cast<int>(center().y + radius() * sin(radians)); return result; }
true
e0f9b1a310b4a5ba3d8152d047f88ca1bd3c4cff
C++
Cruyun/C-exercise
/Algorithm-Lesson/BM.cpp
UTF-8
1,868
3.203125
3
[]
no_license
// 字符串匹配 - BM 算法 // 坏字符 void PreBMBc(string &pattern, int m, int bmBc[]) { int i; for (i = 0; i < 256; ++i) { bmBc[i] = m; } for (i = 0; i < m - 1; ++i) { bmBc[pattern[i]] = m - 1 - i; } } // 好后缀 // 求pattern中以i位置字符为后缀和以最后一个字符为后缀的公共后缀串的长度 void suffix(string &pattern, int m, int suff[]) { int i, j; int k = 0; suff[m - 1] = m; j = m - 1; for (i = m - 2; i >= 0; --i) { if (i > j && suff[i + m - 1 - k] < i - j) { suff[i] = suff[i + m - 1 - k]; } else { if (i < j) { j = i; } k = i; while (j >= 0 && pattern[j] == pattern[j + m - 1 - k]) { --j; } suff[i] = k - j; } } } void PreBMGs(string &pattern, int m, int bmGs[]) { int i; int suff[256]; suffix(pattern, m, suff); for (i = 0; i < m; ++i) { bmGs[i] = m; } int j = 0; for (i = m -1; i >= 0; --i) { if (suff[i] == i + 1) { for (; j < m - 1 - i; ++j) { if (bmGs[j] == m) { bmGs[j] = m - 1 - i; } } } } for (i = 0; i <= m - 2; ++i) { bmGs[m - 1 - suff[i]] = m - 1 - i; } } void BM(string &pattern, int m, string &text, int n) { int i; int bmBc[256]; int bmGs[256]; PreBMBc(pattern, m, bmBc); PreBMGs(pattern, m, bmGs); int j = 0; while (j <= n - m) { for (i = m - 1; i >= 0 && pattern[i] == text[i + j]; --i); if (i < 0) { cout << "match: " << j << endl; j += bmGs[0]; return; } else { j += MAX(bmBc[text[i + j]] - m + 1 + i, bmGs[i]); } } cout << "NOt found"; }
true
23045e9946c1c1a832883c35f593ed1f5ceb2f97
C++
kremena1993/Yanev--Kremena--Assignments--48969
/Asisgnment 2/exmpl 9.2.cpp
UTF-8
962
3.640625
4
[]
no_license
/******************************************************************************/ /****************************** Homework 9.2 ********************************** /******************************************************************************/ #include <iostream> using namespace std; int main() { int n; float sum,avg; //create a pointer for array int *tests; cout << "How many tests do you want to enter:"; cin >> n; //dynamic array allocate tests = new int[n]; cout << "\nEnter the test's scores \n"; //for loop to add tests one by one for (int i = 0; i < n; i++){ cout << "\nScore of test " << (i + 1) << " : "; cin >> tests[i] ; } //for loop for estimating the sum for (int i = 0; i < n; i++){ sum += tests[i]; } //print out results cout<<"\nThe sum is " << sum << endl; avg = sum / n; cout <<"\nThe average is "<< avg << endl; cout << "\n" << endl; //free memory or de-allocate array delete []tests; return 0; }
true
d7dd6215d1434ca0f3429115d14ed5c69e491429
C++
fwqaq/vscode
/3_7pk小游戏(多态)/3_7pk小游戏(多态)/3_7pk小游戏(多态).cpp
GB18030
1,301
3.28125
3
[]
no_license
#include <iostream> using namespace std; #include "Moster.h" #include "Knife.h" #include "Hero.h" #include "DragonSword.h" #include "weapon.h" int main(){ // Moster* moster = new Moster; //Ӣ Hero* hero = new Hero; // Weapon* knife = new Knife; Weapon* dargon = new DragonSword; cout << "ѡ" << endl; cout << "1.ֿȭ" << endl; cout << "2.С" << endl; cout << "3." << endl; int oper = 0; cin >> oper; switch (oper){ case 1:cout << "ѡȭ" << endl; break; case 2:hero->EquipWeapon(knife); break; case 3:hero->EquipWeapon(dargon); } int round = 1;//¼ǰĻغ getchar();//뻺иس ȡһس while (true){ getchar(); system("cls"); cout << "ǰǵ" << round << endl; hero->Attack(moster); if (moster->m_Hp <= 0){ cout << moster->m_Name << "ɱ" << endl; cout << "game over" << endl; break; } moster->Attack(hero); if (hero->m_hp <= 0){ cout << hero->m_Name << "㱻" << endl; cout << "game over" << endl; break; } cout << "ӢʣѪ" << hero->m_hp << endl; cout << "ʣѪ" << moster->m_Hp << endl; ++round; } system("pause"); return EXIT_SUCCESS; }
true
b43124d3916de09b29a6285f30fb858851957d24
C++
sycLin/VFX-Project-1
/ImageAlignment.h
UTF-8
8,684
2.96875
3
[]
no_license
#include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #include <iostream> #include <cstdio> using namespace std; using namespace cv; namespace ImageAlignment { class Bitmap { public: Bitmap() { _dim1 = 0; _dim2 = 0; _real_dim2 = 0; } Bitmap(int dim1, int dim2) { if(dim1 < 0 || dim2 < 0) return; // determine the REAL second dimension // since 1 unsigned char = 8 bits int real_dim2 = dim2 / 8; if(dim2 % 8 != 0) real_dim2 += 1; // do the allocation and initialization data = (unsigned char**)malloc(dim1 * sizeof(unsigned char*)); for(int i=0; i<dim1; i++) { data[i] = (unsigned char*)malloc(real_dim2 * sizeof(unsigned char)); for(int j=0; j<real_dim2; j++) data[i][j] = 0; } _dim1 = dim1; _dim2 = dim2; _real_dim2 = real_dim2; } bool get(int d1, int d2) const { // simple checking if(d1 < 0 || d2 < 0) return false; unsigned char buf = data[d1][d2/8]; return (buf >> (d2%8)) & 1; } void set(int d1, int d2) { // simple checking if(d1 < 0 || d2 < 0) return; data[d1][d2/8] |= (1 << (d2%8)); } void reset(int d1, int d2) { // simple checking if(d1 < 0 || d2 < 0) return; data[d1][d2/8] &= ~(1 << (d2%8)); } void draw() const { for(int i=0; i<_dim1; i++) { for(int j=0; j<_dim2; j++) { std::cout << (int)get(i, j) << " "; } std::cout << std::endl; } } int dim1() const { return _dim1; } int dim2() const { return _dim2; } private: unsigned char** data; int _dim1, _dim2; // the visual dimension of the bitmap int _real_dim2; // the real second dimension }; // utility functions void ImageShrink2(const Mat oImage, Mat& nImage); void ComputeBitmaps(const Mat im, Bitmap& bm1, Bitmap& bm2); void BitmapShift(const Bitmap bm, int x0, int y0, Bitmap& bm_ret); void BitmapXOR(const Bitmap bm1, const Bitmap bm2, Bitmap& bm_ret); void BitmapAND(const Bitmap bm1, const Bitmap bm2, Bitmap& bm_ret); int BitmapTotal(const Bitmap bm); // main function void GetExpShift(const Mat im1, const Mat im2, int shift_bits, int shift_ret[2]); void ImageShift(Mat& im, int x0, int y0); // overall alignment function void AlignImages(int image_count, Mat* images); } // To downsample a grayscale image by a factor of 2 in each dimension. // oImage: original grayscale image. // nImage: the new image, will be allocated. void ImageAlignment::ImageShrink2(const Mat oImage, Mat& nImage) { int r = oImage.rows / 2; int c = oImage.cols / 2; nImage = Mat(r, c, CV_8UC1, Scalar(0)); for(int i=0; i<r; i++) { for(int j=0; j<c; j++) { nImage.at<uchar>(i, j) = oImage.at<uchar>(i*2, j*2); } } } // To compute two bitmaps for a grayscale image. // im: the grayscale image to create bitmaps. // bm1: the median-thresholding bitmap of im. (will be allocated) // bm2: the edge bitmap of im. (will be allocated) void ImageAlignment::ComputeBitmaps(const Mat im, ImageAlignment::Bitmap& bm1, ImageAlignment::Bitmap& bm2) { /* Step 1: initialize the bitmaps */ bm1 = ImageAlignment::Bitmap(im.rows, im.cols); bm2 = ImageAlignment::Bitmap(im.rows, im.cols); /* Step 2: determine median threshold */ int count[256] = {0}; int MED_THRESH = 0; // count the intensity valus for(int i=0; i<im.rows; i++) for(int j=0; j<im.cols; j++) count[im.at<uchar>(i, j)] += 1; int half_count = (im.rows * im.cols) / 2; for(int i=0; i<256; i++) { half_count -= count[i]; if(half_count < 0) { // reaching half of total pixel count MED_THRESH = i; break; } } /* Step 3: fill in bm1: thresholded bitmap */ for(int i=0; i<im.rows; i++) { for(int j=0; j<im.cols; j++) { if(im.at<uchar>(i, j) > MED_THRESH) bm1.set(i, j); } } /* Step 4: fill in bm2: edge bitmap */ for(int i=0; i<im.rows; i++) { for(int j=0; j<im.cols; j++) { if(im.at<uchar>(i, j) > MED_THRESH + 4) bm2.set(i, j); if(im.at<uchar>(i, j) < MED_THRESH - 4) bm2.set(i, j); } } } // To shift the Bitmap bm, and save result in Bitmap bm_ret. // bm: the bitmap to shift. // x0: shift length in 1st dimension. // y0: shift length in 2nd dimension. // bm_ret: resulted Bitmap after shifting. void ImageAlignment::BitmapShift(const Bitmap bm, int x0, int y0, Bitmap& bm_ret) { // initialize the bitmap to return int d1 = bm.dim1(), d2 = bm.dim2(); bm_ret = Bitmap(bm.dim1(), bm.dim2()); // shift it for(int i=0; i<d1; i++) { for(int j=0; j<d2; j++) { // if inRange and isTrue, set it int targetX = i - x0; int targetY = j - y0; if(targetX >= 0 && targetX < d1 && targetY >= 0 && targetY < d2 && bm.get(targetX, targetY)) { bm_ret.set(i, j); } } } } // To compute XOR of two Bitmaps. // bm1: the first Bitmap of doing XOR. // bm2: the second Bitmap of doing XOR. // bm_ret: the resulted Bitmap of doing XOR. void ImageAlignment::BitmapXOR(const Bitmap bm1, const Bitmap bm2, Bitmap& bm_ret) { int d1 = bm1.dim1(); int d2 = bm1.dim2(); // check dimension if(d1 != bm2.dim1() || d2 != bm2.dim2()) { cerr << "ERROR: BitmapXOR(): bm1 amd bm2 of different sizes..." << endl; return; } bm_ret = Bitmap(d1, d2); for(int i=0; i<d1; i++) { for(int j=0; j<d2; j++) { if(bm1.get(i, j) ^ bm2.get(i, j)) bm_ret.set(i, j); } } } // To compute AND of two Bitmaps. // bm1: the first Bitmap of doing AND. // bm2: the second Bitmap of doing AND. // bm_ret: the resulted Bitmap of doing AND. void ImageAlignment::BitmapAND(const Bitmap bm1, const Bitmap bm2, Bitmap& bm_ret) { int d1 = bm1.dim1(); int d2 = bm1.dim2(); // check dimension if(d1 != bm2.dim1() || d2 != bm2.dim2()) { cerr << "ERROR: BitmapAND(): bm1 amd bm2 of different sizes..." << endl; return; } bm_ret = Bitmap(d1, d2); for(int i=0; i<d1; i++) { for(int j=0; j<d2; j++) { if(bm1.get(i, j) & bm2.get(i, j)) bm_ret.set(i, j); } } } // To compute the total sum of the Bitmap bm. // bm: the Bitmap to compute the sum. int ImageAlignment::BitmapTotal(const Bitmap bm) { int ret = 0, d1 = bm.dim1(), d2 = bm.dim2(); for(int i=0; i<d1; i++) { for(int j=0; j<d2; j++) { if(bm.get(i, j)) ret += 1; } } return ret; } // Main function of Ward's MTB algorithm. // im1: the first image. // im2: the second image. // shift_bits: parameter. // shift_ret: the shift bits in 2 dimensions to return. void ImageAlignment::GetExpShift(const Mat im1, const Mat im2, int shift_bits, int shift_ret[2]) { int min_err; int cur_shift[2]; Bitmap tb1, tb2; Bitmap eb1, eb2; int i, j; if(shift_bits > 0) { Mat sml_im1, sml_im2; ImageAlignment::ImageShrink2(im1, sml_im1); ImageAlignment::ImageShrink2(im2, sml_im2); GetExpShift(sml_im1, sml_im2, shift_bits - 1, cur_shift); cur_shift[0] *= 2; cur_shift[1] *= 2; } else { cur_shift[0] = cur_shift[1] = 0; } ComputeBitmaps(im1, tb1, eb1); ComputeBitmaps(im2, tb2, eb2); min_err = im1.rows * im1.cols; for(i=-1; i<=1; i++) { for(j=-1; j<=1; j++) { int xs = cur_shift[0] + i; int ys = cur_shift[1] + j; Bitmap shifted_tb2; Bitmap shifted_eb2; Bitmap diff_b; int err; BitmapShift(tb2, xs, ys, shifted_tb2); BitmapShift(eb2, xs, ys, shifted_eb2); BitmapXOR(tb1, shifted_tb2, diff_b); BitmapAND(diff_b, eb1, diff_b); BitmapAND(diff_b, shifted_eb2, diff_b); err = BitmapTotal(diff_b); if(err < min_err) { shift_ret[0] = xs; shift_ret[1] = ys; min_err = err; } } } } // To shift a real color image (CV_8UC3). // im: the image to shift. // x0: shift amount in 1st dimension. // y0: shift amount in 2nd dimension. void ImageAlignment::ImageShift(Mat& im, int x0, int y0) { Mat tmp = im.clone(); for(int i=0; i<im.rows; i++) { for(int j=0; j<im.cols; j++) { // check if inRange int targetX = i - x0; int targetY = j - y0; if(targetX >= 0 && targetX < im.rows && targetY >= 0 && targetY < im.cols) { im.at<Vec3b>(i, j)[0] = tmp.at<Vec3b>(targetX, targetY)[0]; im.at<Vec3b>(i, j)[1] = tmp.at<Vec3b>(targetX, targetY)[1]; im.at<Vec3b>(i, j)[2] = tmp.at<Vec3b>(targetX, targetY)[2]; } } } } // To align and array of color images. // image_count: the total number of color images. // images: the array (of color images). void ImageAlignment::AlignImages(int image_count, Mat* images) { if(image_count <= 1) return; // get grayscale image of every color image Mat g_images[image_count]; for(int i=0; i<image_count; i++) cvtColor(images[i], g_images[i], CV_BGR2GRAY); // align each with its predecessor for(int i=1; i<image_count; i++) { int shift_amount[2]; GetExpShift(g_images[i-1], g_images[i], 4, shift_amount); ImageShift(images[i], shift_amount[0], shift_amount[1]); } }
true
b08d7d31723d4b2660031600b2d5f9e74cc2b4bd
C++
mattsousaa/POO_2018.2
/Pratica 7/inc/disciplina.h
UTF-8
377
2.546875
3
[]
no_license
#ifndef DISCIPLINA #define DISCIPLINA #include <iostream> #include <sstream> #include <map> #include <vector> #include <string> using namespace std; class Disciplina{ public: string nome, id; Disciplina(string nome, string id); string toString(Disciplina &disciplina); }; std::ostream& operator<<(std::ostream& os, const Disciplina& d); #endif // DISCIPLINA
true