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
4afa83094dac36ef0d5349bb99426bf90bcd0357
C++
swagatn22/GFG_mustdo
/LL/Delete keys in a Linked list.cpp
UTF-8
398
2.703125
3
[]
no_license
Node* deleteAllOccurances(Node *head,int x) { while(head->data == x){ head = head->next; } Node *temp = head; Node *prv = head; while(temp != NULL){ if(temp->data == x){ prv->next = temp->next; temp = prv->next; }else{ prv = temp; temp = temp->next; } } return head; //Your code here }
true
197f20f750d3bfe83d2c12347a3bc7bd01bd3aa6
C++
Calit2-UCI/EMMA-FINAL
/libs/vscore/header/List.h
UTF-8
2,845
3.5
4
[]
no_license
#ifndef _LIST_H #define _LIST_H #ifndef NULL #define NULL 0L #endif template<class T> class List { public: class Iterator { friend class List<T>; public: Iterator(const T &t) : _value(t) { _prev = _next = NULL; } Iterator *prev() { return _prev; } const Iterator *prev() const { return _prev; } Iterator *next() { return _next; } const Iterator *next() const { return _next; } const T &item() const { return _value; } T item() { return _value; } private: Iterator *_prev; Iterator *_next; T _value; }; List() { _head = _tail = NULL; _length = 0; } List(const List<T> &l) { _head = _tail = NULL; _length = 0; for (Iterator *i = l.first(); i != NULL; i = i->next()) append(i->item()); } ~List() { removeAll(); } void append(const T &t) { Iterator *i = new Iterator(t); i->_prev = _tail; if (_tail) { _tail->_next = i; } else { _head = i; } _tail = i; _length++; } void insert(const T &t) { Iterator *i = new Iterator(t); i->_next = _head; if (_head) { _head->_prev = i; } else { _tail = i; } _head = i; _length++; } void remove(Iterator *i) { if (i->_prev) { i->_prev->_next = i->_next; } else { _head = i->_next; } if (i->_next) { i->_next->_prev = i->_prev; } else { _tail = i->_prev; } delete i; _length--; } Iterator *find(const T &t) const { for (Iterator *i = _head; i != NULL; i = i->next()) { if (i->item() == t) return i; } return NULL; } Iterator *get(int index) const { Iterator *i; for (i = _head; i != NULL && index > 0; i = i->next()) index--; return i; } void removeAll() { Iterator *i, *j; for (i = _head; i != NULL; i = j) { j = i->next(); delete i; } } void appendList(List<T> *list) { for (Iterator *i = list->first(); i != NULL; i = i->next()) { append(i->item()); } } void insertList(List<T> *list) { for (Iterator *i = list->last(); i != NULL; i = i->prev()) { insert(i->item()); } } Iterator *first() const { return _head; } Iterator *last() const { return _tail; } int size() const { return _length; } int operator==(const List<T> &list) { Iterator *i, *j; for(i = list.first(), j = _head; i != NULL && j != NULL; i = i->next(), j = j->next()) { if (i->item() != j->item()) return 0; } return i != NULL && j != NULL; } private: Iterator *_head; Iterator *_tail; int _length; }; #endif // _LIST_H
true
58d884a8133898d7238f5d1ed3b34c20dddf61ed
C++
gazzenger/lora-node-test
/lora-arduino-testsend/lora-arduino-testsend.ino
UTF-8
3,544
2.71875
3
[]
no_license
#include <SPI.h> #include <LoRa.h> #include <SoftwareSerial.h> #include <TinyGPS.h> float lat = 28.5458,lon = 77.1703, elv = 0; // create variable for latitude and longitude object SoftwareSerial gpsSerial(A0,A1);//rx,tx TinyGPS gps; // create gps object int counter = 0; static void smartdelay(unsigned long ms); static void print_date(TinyGPS &gps); static void print_int(unsigned long val, unsigned long invalid, int len); void setup() { gpsSerial.begin(9600); Serial.begin(9600); while (!Serial); Serial.println("LoRa Receiver"); pinMode(13, OUTPUT); if (!LoRa.begin(915000000)) { Serial.println("Starting LoRa failed!"); while (1); } else { // LoRa.setTxPower(20); LoRa.setSignalBandwidth(250e3); //LoRa.setFrequency(917200000); LoRa.setSpreadingFactor(12); LoRa.setCodingRate4(5); // LoRa.setPreambleLength(8); // LoRa.enableCrc(); } } void loop() { // int packetSize = LoRa.parsePacket(); // if (packetSize) { // // received a packet // Serial.print("Received packet '"); // // // read packet // while (LoRa.available()) { // Serial.print((char)LoRa.read()); // } // // // print RSSI of packet // Serial.print("' with RSSI "); // Serial.println(LoRa.packetRssi()); // } //while (gpsSerial.available() > 0) // Serial.write(gpsSerial.read()); // Serial.print("Sending packet: "); // Serial.println(counter); // send packet // LoRa.beginPacket(); // LoRa.print("asdf"); // LoRa.print(counter); // LoRa.endPacket(); // counter++; gps.f_get_position(&lat,&lon); // get latitude and longitude elv = gps.f_altitude(); // display position Serial.print("Position: "); Serial.print("Latitude:"); Serial.print(lat,7); Serial.print(";"); Serial.print("Longitude:"); Serial.println(lon,7); Serial.println(elv,1); print_date(gps); LoRa.beginPacket(); LoRa.print(lat,5); LoRa.print(","); LoRa.print(lon,5); LoRa.print(","); LoRa.print(elv,1); // LoRa.print(counter); LoRa.endPacket(); smartdelay(5000); } static void smartdelay(unsigned long ms) { unsigned long start = millis(); do { while (gpsSerial.available()) gps.encode(gpsSerial.read()); } while (millis() - start < ms); } static void print_date(TinyGPS &gps) { int year; byte month, day, hour, minute, second, hundredths; unsigned long age; gps.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredths, &age); if (age == TinyGPS::GPS_INVALID_AGE) Serial.print("********** ******** "); else { char sz[32]; sprintf(sz, "%02d/%02d/%02d %02d:%02d:%02d ", month, day, year, hour, minute, second); Serial.print(sz); } print_int(age, TinyGPS::GPS_INVALID_AGE, 5); smartdelay(0); } static void print_int(unsigned long val, unsigned long invalid, int len) { char sz[32]; if (val == invalid) strcpy(sz, "*******"); else sprintf(sz, "%ld", val); sz[len] = 0; for (int i=strlen(sz); i<len; ++i) sz[i] = ' '; if (len > 0) sz[len-1] = ' '; Serial.print(sz); smartdelay(0); } //void loop() { // // try to parse packet // int packetSize = LoRa.parsePacket(); // if (packetSize) { // // received a packet // Serial.print("Received packet '"); // // // read packet // while (LoRa.available()) { // Serial.print((char)LoRa.read()); // } // // // print RSSI of packet // Serial.print("' with RSSI "); // Serial.println(LoRa.packetRssi()); // } //}
true
aad2e9b948589d44798f85d6cf74a03ef0209cf6
C++
kuenane/N-puzzle
/srcs/isSolvable.cpp
UTF-8
2,276
3.109375
3
[]
no_license
// ************************************************************************** // // // // ::: :::::::: // // isSolvable.cpp :+: :+: :+: // // +:+ +:+ +:+ // // By: dcojan <dcojan@student.42.fr> +#+ +:+ +#+ // // +#+#+#+#+#+ +#+ // // Created: 2015/03/26 09:36:42 by dcojan #+# #+# // // Updated: 2015/03/27 15:04:38 by dcojan ### ########.fr // // // // ************************************************************************** // #include <n-puzzle.hpp> // // C++ program to check if a given instance of 8 puzzle is solvable or not // #include <iostream> // using namespace std; // A utility function to count inversions in given array 'arr[]' static int getInvCount(const std::vector<unsigned int> &map) { int inv_count = 0; for (int i = 0; i < (int)map.size() - 1; i++) for (int j = i+1; j < (int)map.size(); j++) // Value 0 is used for empty space if (map[j] && map[i] && map[i] > map[j]) inv_count++; return inv_count; } // This function returns true if given 8 puzzle is solvable. bool isSolvable(Map &map) { map.reverseMap(); // Count inversions in given 8 puzzle int invCount = getInvCount(map.getMap()); // return true if inversion count is even. map.reverseMap(); // Works only with odd width map // For even width map : https://www.cs.bham.ac.uk/~mdr/teaching/modules04/java2/TilesSolvability.html if (map.getDim() % 2 == 1) return (invCount%2 == 1); return true; } // /* Driver progra to test above functions */ // int main(int argv, int** args) // { // int puzzle[3][3] = {{1, 8, 2}, // {0, 4, 3}, // Value 0 is used for empty space // {7, 6, 5}}; // isSolvable(puzzle)? cout << "Solvable": // cout << "Not Solvable"; // return 0; // }
true
19f5f2591f153b16e017597cb25f9a59a3cc12ca
C++
Stephenalexngo/Java-Cpp-Programs
/KattisC++/FreeFood.cpp
UTF-8
537
2.734375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { // freopen("out.txt","wt",stdout); int tester, s, t, freefooddays; bool numofdays[366]; while(cin >> tester) { freefooddays = 0; for(int z=0; z<366;z++) { numofdays[z] = false; } for(int x=0; x<tester; x++) { cin >> s; cin >> t; for(int y=s; s<t+1; s++) { if(!numofdays[s]) { numofdays[s] = true; freefooddays++; } } } cout << freefooddays << endl; } return 0; }
true
b0bdb0f951cf6f9c532303dcfb118ba54f1387b2
C++
fatmaashraframadan/Biological_Program
/Protien.cpp
UTF-8
8,458
3.375
3
[]
no_license
#include "Protien.h" #include "CodonsTable.h" Protien::Protien() { //ctor } Protien::Protien(Protien &protein2){ int counter = 0; while(protein2.seq[counter] != '\0') { counter +=1; } seq = new char[counter+1]; for(int i=0; i<counter; i++) { seq[i] = protein2.seq[i]; } seq[counter] = '\0'; type = protein2.type; } Protien::Protien(char* p){ int length = 0; while(p[length] != '\0'){ length++; } seq = new char[length+1]; noErrors = true; bool validProtein = false; for(int i=0; i<length; i++){ try{ validProtein = codonsTable.isAminoAcidValid(p[i]); if(validProtein == false){ throw 99; } seq[i] = p[i]; validProtein = false; }catch(...){ cout << "Invalid type of protein. Make sure the values are valid." << endl; noErrors = false; break; } } seq[length] = '\0'; if(noErrors == true){ tryAgainType: cout << "Type of Protein?:\n1- Hormone\n2- Enzyme\n3- TF\n4- Cellular Function" << endl; char proteinType; cin >> proteinType; switch(proteinType){ case '1': type = Hormone; break; case '2': type = Enzyme; break; case '3': type = TF; break; case '4': type = Cellular_Function; break; default: cout << "Invalid choice, try again:" << endl; goto tryAgainType; } } } Protien::~Protien() { delete[] seq; } void Protien::Print(){ cout << "Protein: "; int i=0; while(seq[i] != '\0'){ cout << seq[i]; i++; } cout << endl << "Protein Type: "; switch(type){ case 0: cout << "Hormone" << endl; break; case 1: cout << "Enzyme" << endl; break; case 2: cout << "TF" << endl; break; case 3: cout << "Cellular Function" << endl; break; } } bool Protien::isOkay(){ return noErrors; } void Protien::saveSequenceToFile(){ int length2 = 0; while(seq[length2] != '\0'){ length2++; } string fileName; cout << "Enter file name" << endl; cin >> fileName; fileName = fileName + ".txt"; ofstream createSequence(fileName.c_str()); createSequence << length2 << ' '; //assigning length for(int i=0; i<length2; i++){ createSequence << seq[i]; } createSequence << ' ' << type; } void Protien::loadSequenceFromFile(){ string fileName; cout << "Enter the name of the file you want to load sequence from: " << endl; cin >> fileName; fileName = fileName + ".txt"; ifstream loadSequence(fileName.c_str()); int length1; loadSequence >> length1; seq = new char[length1+1]; for(int i = 0 ; i <length1 ; i++) { loadSequence >> seq[i]; } seq[length1] = '\0'; int h; loadSequence >> h; switch(h) { case 0: type = Hormone; break; case 1: type = Enzyme; break; case 2: type = TF; break; case 3: type = Cellular_Function; break; } } ostream& operator << (ostream& out, Protien &protein){ protein.Print(); return out; } istream& operator >> (istream& in, Protien &protein){ CodonsTable codonsTable; int len; char s; char t; cout << "Please enter your length: "; cin >> len; cout << "Enter a number for your type \n 0 for Hormone \n 1 for Enzyme \n 2 for TF \n 3 for Cellular Function " << endl; typeTry: cin >> t; switch(t){ case '0': protein.type = Hormone; break; case '1': protein.type = Enzyme; break; case '2': protein.type = TF; break; case '3': protein.type = Cellular_Function; break; default: cout << "Please enter a number from 0 to 3. Try again: " << endl; goto typeTry; break; } protein.seq = new char [len+1]; start: cout << "Enter you sequence: "; for(int i = 0 ; i < len; i++){ cin >> s; bool valid = codonsTable.isAminoAcidValid(s); if(valid){ protein.seq[i] = s; }else{ cout << "Invalid protein. Try again." << endl; goto start; } } protein.seq[len] = '\0'; protein.noErrors = true; return in; } Protien Protien::operator +(Protien &protein2){ int length1=0, length2=0; while(seq[length1] != '\0'){ length1++; } length1++; while(protein2.seq[length2] != '\0'){ length2++; } length2++; int newLength = length2 + length1-1; char *addedSeq = new char[newLength]; for(int i=0; i<length1-1; i++){ addedSeq[i]=seq[i]; } for(int i=length1-1; i<newLength; i++){ addedSeq[i] = protein2.seq[abs(length1-1-i)]; } Protien sum1(addedSeq); return sum1; } bool Protien::operator ==(Protien &protein2){ int length1=0, length2=0; while(seq[length1] != '\0'){ length1++; } length1++; while(protein2.seq[length2] != '\0'){ length2++; } length2++; if(type == protein2.type) { if(length1 == length2) { for(int i = 0 ; i < length1 ; i++) { if(this->seq[i] != protein2.seq[i]) return false; } return true; } else return false; } else return false; } bool Protien::operator !=(Protien &protein2){ int length1=0, length2=0; while(seq[length1] != '\0'){ length1++; } length1++; while(protein2.seq[length2] != '\0'){ length2++; } length2++; if(type == protein2.type) { if(length1 == length2) { for(int i = 0 ; i < length1 ; i++) { if(this->seq[i] != protein2.seq[i]) return true; } return false; } else return true; } else return true; } void Protien::operator =(Protien &protein2){ int counter = 0; while(protein2.seq[counter] != '\0') { counter +=1; } seq = new char[counter+1]; for(int i=0; i<counter; i++) { seq[i] = protein2.seq[i]; } seq[counter] = '\0'; type = protein2.type; } DNA* Protien::GetDNAStrandsEncodingMe(DNA &bigDNA){ int currentProteinLength = 0; bool isSubSeqExist = true; while(seq[currentProteinLength] != '\0'){ currentProteinLength++; } int DNALength = bigDNA.getLength()-1, proteinLength = DNALength/3; if(DNALength%3 == 0){ vector<int> subSeqs; RNA &&newRNA = bigDNA.ConvertToRNA(); Protien &&newProtein = newRNA.ConvertToProtein(); for(int i=0; i<proteinLength; i++){ if(seq[0] == newProtein.seq[i]){ for(int j=1; j<currentProteinLength; j++){ if(seq[j] != newProtein.seq[i+j]){ isSubSeqExist = false; } } if(isSubSeqExist == true){ subSeqs.push_back(i); } isSubSeqExist = true; } } DNA* possibleStrands = new DNA[subSeqs.size()]; char* newDNASeq = new char[currentProteinLength*3 + 1]; for(int i=0; i<subSeqs.size(); i++){ for(int j=0; j<currentProteinLength*3; j++){ newDNASeq[j] = bigDNA.getElementInSeq((subSeqs[i]*3) + j); } newDNASeq[currentProteinLength*3] = '\0'; DNA &&newDNA = DNA(newDNASeq, promoter); cout << newDNA << endl; possibleStrands[i] = newDNA; } return possibleStrands; }else{ cout << "The big DNA must have a length divisible by 3" << endl; } } char Protien::getElementInSeq(int index){ return seq[index]; }
true
77f87c09a68fbbc9bbe0d52dd3ac2e03ec0a66af
C++
mizraith/mizraith_DigitalClock_forgithub
/DigitalClock_StateTypedefs.h
UTF-8
912
2.765625
3
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
/** * PART OF mizraith_DigitalClock package * * base definition of a "state" * */ #ifndef _mizraith_DigitalClockStateTypedefs_H_ #define _mizraith_DigitalClockStateTypedefs_H_ #include <Arduino.h> namespace mizraith_DigitalClock { /* Forward declaration of state structure */ struct state; /* State function prototype */ typedef void (state_func)(const struct state *); /* Indexes for gettting struct info from progmem */ const uint8_t OFFSET_CURRENTSTATE = 0; const uint8_t OFFSET_EVENTID = 1; const uint8_t OFFSET_NEXTSTATE = 2; const uint8_t OFFSET_FUNCTION = 3; /* Structure containing state function and data */ struct state { uint8_t currentstate; //0 uint8_t eventID; //1 uint8_t nextstate; //2 state_func *func_p; //3 * are uint16_t 3,4 }; } #endif
true
366b872690adc9944e1d828e28389d8df26aa109
C++
tmyksj/atcoder
/AtCoder Beginner Contest 170/C - Forbidden List/main.cpp
UTF-8
484
2.90625
3
[]
no_license
#include <iostream> #include <set> using namespace std; int main() { int x, n; cin >> x >> n; set<int> p; for (int i = 0; i < n; i++) { int pi; cin >> pi; p.insert(pi); } int res = 0; for (int i = 0; ; i++) { if (p.find(x - i) == p.end()) { res = x - i; break; } else if (p.find(x + i) == p.end()) { res = x + i; break; } } cout << res << endl; }
true
db0e5ea18abb6fd7bda4618fdd06121850aae9cc
C++
MaxCarlson/Allocators
/Allocators/Linear.h
UTF-8
2,090
3.6875
4
[]
no_license
#pragma once #include "AllocHelpers.h" namespace alloc { template<size_t bytes> // TODO: Remove from alloc:: namespace struct LStorage { inline static bool init = 1; inline static byte* MyBegin; inline static size_t MyLast; LStorage() { if (init) { MyBegin = reinterpret_cast<byte*>(operator new (bytes)); MyLast = init = 0; } } template<class T> T* allocate(size_t count) { // If we have static storage size set, make sure we don't exceed it if (count * sizeof(T) + MyLast > bytes) throw std::bad_alloc(); if (init) throw std::runtime_error("Allocator not instantiated!"); byte* begin = MyBegin + MyLast; MyLast += count * sizeof(T); return reinterpret_cast<T*>(begin); } void reset() { delete MyBegin; MyBegin = nullptr; MyLast = 0; init = true; } }; // A very basic allocator that allocates linearly // from a set @ compile time number of bytes // // Doesn't allow for freeing of memory in pieces // but rather requires all memory to be freed at once template<class Type, size_t bytes> class Linear { using value_type = Type; using pointer = Type*; using reference = Type&; using size_type = size_t; static_assert(bytes > 0, "Linear allocators memory size cannot be < 1 byte"); size_type size = bytes; LStorage<bytes> storage; friend class Linear; public: Linear() = default; pointer allocate(size_type count) { return storage.allocate<Type>(count); } void deallocate(Type* t) { throw std::runtime_error("Cannot deallocate specific memory in Linear allocator, use reset to deallocate all memory " "(and render any instatiated Linear allocator of the same bytes size useless until constructed again)"); } void reset() { storage.reset(); } template<class U> struct rebind { using other = Linear<U, bytes>; }; template<class Other> bool operator==(const Other& other) { return other.size == bytes; } template<class Other> bool operator!=(const Other& other) { return other.size != bytes; } }; }
true
f49ab5d0d2a4a0169d5f5f81d60065fe6c6a8cc1
C++
Telefragged/rndlevelsource
/rndlevelsource/Matrix.cpp
UTF-8
5,947
2.859375
3
[ "MIT" ]
permissive
#include "Matrix.h" #include <math.h> #include <limits> #include <sstream> #include "Vertex.h" #define M_PI 3.14159265358979323846 //Matrix Matrix::rotmatxPassive(double deg) //{ // double rad = deg * (M_PI / 180.0); // double sinth = sin(rad), costh = cos(rad); // double rotarr[3][3] = { // {1.0, 0.0, 0.0}, // {0.0, costh, sinth}, // {0.0, -sinth, costh}}; // return toMat(rotarr); //} // //Matrix Matrix::rotmatyPassive(double deg) //{ // double rad = deg * (M_PI / 180.0); // double sinth = sin(rad), costh = cos(rad); // double rotarr[3][3] = { // {costh, 0.0, -sinth}, // {0.0, 1.0, 0.0}, // {sinth, 0.0, costh}}; // return toMat(rotarr); //} // //Matrix Matrix::rotmatzPassive(double deg) //{ // double rad = deg * (M_PI / 180.0); // double sinth = sin(rad), costh = cos(rad); // double rotarr[3][3] = { // {costh, sinth, 0.0}, // {-sinth, costh, 0.0}, // {0.0, 0.0, 1.0}}; // return toMat(rotarr); //} Matrix& Matrix::operator=(const Matrix& rhs) { this->copyfrom(rhs); return *this; } Matrix& Matrix::operator*=(const Matrix& rhs) { //mictimer multtimer("ms operator*=()", 1000.0); Matrix prod = this->mult(rhs); copyfrom(prod); return *this; } Matrix& Matrix::operator*=(double rhs) { for (unsigned int n = 0; n < xsize_ * ysize_; n++) arr_[n] *= rhs; return *this; } inline double dotmult(const Matrix& rowmat, const Matrix& colmat, unsigned int row, unsigned int col) { double res = 0.0; for (unsigned int n = 0; n < rowmat.y(); n++) { res += (rowmat.get(row, n) * colmat.get(n, col)); } return res; } Matrix Matrix::mult(const Matrix& rhs) { if (y() != rhs.x()) return Matrix(0, 0); Matrix ret(x(), rhs.y()); for (unsigned int n = 0; n < x(); n++) { for (unsigned int m = 0; m < rhs.y(); m++) { ret.set(n, m, dotmult(*this, rhs, n, m)); } } return ret; } std::string Matrix::toStr() const { std::ostringstream os; os << "{"; for (unsigned int n = 0; n < x(); n++) { os << "{"; for (unsigned int m = 0; m < y(); m++) { if (m != 0) os << ", "; os << get(n, m); } os << "}"; if (n != x() - 1) os << ","; } os << "}"; return os.str(); } inline void rowSet(Matrix& mat, const Matrix& row, unsigned int to) { for (unsigned int n = 0; n < mat.cols(); n++) { mat[to][n] = row[0][n]; } } inline void colSet(Matrix& mat, const Matrix& col, unsigned int to) { for (unsigned int n = 0; n < mat.rows(); n++) { mat[n][to] = col[n][0]; } } inline Matrix rowGet(const Matrix& mat, unsigned int from, double mod = 0.0) { Matrix rowcpy(1, mat.cols()); for (unsigned int n = 0; n < mat.cols(); n++) rowcpy[0][n] = mat[from][n]; rowcpy *= mod; return rowcpy; } inline void rowAdd(Matrix& mat, const Matrix& row, unsigned int to) { for (unsigned int n = 0; n < mat.y(); n++) { mat[to][n] += row[0][n]; } } inline void rowSwap(Matrix& mat, unsigned int r1, unsigned int r2) { Matrix row1 = rowGet(mat, r1); rowSet(mat, rowGet(mat, r2), r1); rowSet(mat, row1, r2); } inline void rowMod(Matrix& mat, unsigned int row, double mod) { for (unsigned int col = 0; col < mat.cols(); col++) mat[row][col] *= mod; } inline unsigned int rowPivot(Matrix& mat, unsigned int currentrow) { unsigned int workingrow = currentrow; while (doubleeq(mat[currentrow][workingrow], 0.0)) { if (workingrow == mat.rows() - 1) return 0xFFFFFFFF; rowSwap(mat, currentrow, ++workingrow); } return workingrow; } inline Matrix rowGetSkip(const Matrix& mat, unsigned int from, unsigned int skip) { Matrix rowcpy(1, mat.cols() - 1); unsigned int putcnt = 0; for (unsigned int n = 0; n < mat.cols(); n++) { if (n == skip) continue; rowcpy[0][putcnt++] = mat[from][n]; } return rowcpy; } inline Matrix colGetSkip(const Matrix& mat, unsigned int from, unsigned int skip) { Matrix rowcpy(mat.rows() - 1, 1); unsigned int putcnt = 0; for (unsigned int n = 0; n < mat.rows(); n++) { if (n == skip) continue; rowcpy[putcnt++][0] = mat[n][from]; } return rowcpy; } // Probably very slow double Matrix::det() const { if (cols() != rows()) return std::numeric_limits<double>::quiet_NaN(); if (cols() == 2) return get(0, 0) * get(1, 1) - get(0, 1) * get(1, 0); double ret = 0.0; int sign = 1; for (unsigned int n = 0; n < cols(); n++) { Matrix newmat(cols() - 1, rows() - 1); double mod = get(0, n) * sign; sign *= -1; unsigned int colput = 0; for (unsigned int m = 0; m < cols(); m++) { if (m == n) continue; Matrix col = colGetSkip((*this), m, 0); colSet(newmat, col, colput++); } ret += (mod * newmat.det()); } return ret; } Matrix Matrix::gaussElim(Matrix mat) { if (mat.x() + 1 != mat.y()) return Matrix(0, 0); for (unsigned int row = 0; row < mat.rows(); row++) { unsigned int workingrow = rowPivot(mat, row); if (workingrow == 0xFFFFFFFF) { return Matrix(0, 0); } rowMod(mat, workingrow, 1.0 / mat[workingrow][workingrow]); for (unsigned int modrow = workingrow + 1; modrow < mat.rows(); modrow++) { double mod = mat[workingrow][workingrow] * mat[modrow][workingrow]; rowAdd(mat, rowGet(mat, workingrow, -mod), modrow); } } for (int row = mat.rows() - 1; row >= 0; row--) { double varval = mat[row][mat.cols() - 1]; for (int modrow = row - 1; modrow >= 0; modrow--) { mat[modrow][mat.cols() - 1] -= varval * mat[modrow][row]; mat[modrow][row] = 0.0; } } Matrix ret(mat.rows(), 1); for (unsigned int row = 0; row < mat.rows(); row++) { ret[row][0] = mat[row][mat.cols() - 1]; } return ret; } Matrix::Matrix(const Matrix& orig) : xsize_(0), ysize_(0), arr_(nullptr) { this->copyfrom(orig); } Matrix::Matrix(Matrix&& orig) : xsize_(0), ysize_(0), arr_(nullptr) { swap(*this, orig); } Matrix::Matrix(unsigned int xs, unsigned int ys, double sval) : xsize_(xs), ysize_(ys), arr_(nullptr) { if (xs == 0 || ys == 0) return; arr_ = new double[xs * ys]; for (unsigned int n = 0; n < xs; n++) { arr_[n] = sval; } } Matrix::~Matrix(void) { clear(); }
true
216f69cb059dd4b2e53b25975563caf264114154
C++
mfaisalghozi/competitive-programming-stuff
/lab/95556_Untitled7.cpp
UTF-8
211
2.75
3
[]
no_license
#include<stdio.h> int jumlah; int fibo(int n, int m){ if(n==m) jumlah++; if(n<=2) return 1; return fibo(n-1, m)+fibo(n-2, m); } int main(){ jumlah=0; fibo(10,2); printf("%d", jumlah); return 0; }
true
0f9a6884656256aae02ecbf383f16d37415eaf11
C++
hugetto/2DGame
/src/GameEngineLib/src/managers/CGameObjectManager.cpp
UTF-8
3,158
2.65625
3
[ "Apache-2.0" ]
permissive
#include "pch.h" #include <managers/CGameObjectManager.h> #include <CGameObject.h> #include <algorithm> #include <CCamera.h> namespace hugGameEngine { CGameObjectManager CGameObjectManager::sInstance; CGameObjectManager::CGameObjectManager() { } CGameObjectManager::~CGameObjectManager() { for (CGameObject* lPointer : mGameObjectList) { delete(lPointer); lPointer = 0; } mGameObjectList.clear(); } CGameObject* CGameObjectManager::CreateGameObject(const json11::Json& aJSON) { mGameObjectList.push_back(new CGameObject()); CGameObject* lGameObject = mGameObjectList.back(); lGameObject->Load(aJSON); return lGameObject; } CGameObject* CGameObjectManager::FindGameObject(const char* aGameObjectName) const { CGameObject* lRetObject = nullptr; for (CGameObject* lGameObject : mGameObjectList) { if (strcmp(lGameObject->GetName().c_str(), aGameObjectName) == 0) { lRetObject = lGameObject; break; } } return lRetObject; } std::vector< CGameObject* > CGameObjectManager::FindAllGameObjects(const char* aGameObjectName) const { std::vector< CGameObject* > lRetObject; for (CGameObject* lGameObject : mGameObjectList) { if (strcmp(lGameObject->GetName().c_str(), aGameObjectName) == 0) { lRetObject.push_back(lGameObject); } } return lRetObject; } bool CGameObjectManager::DestroyGameObject(const CGameObject* aGameObject) { std::vector< CGameObject* >::const_iterator lIt = std::begin(mGameObjectList); bool lFound = false; for (std::vector< CGameObject* >::const_iterator lIt = mGameObjectList.begin(); lIt != mGameObjectList.end(); lIt++) { if (aGameObject == (*lIt)) { lFound = true; delete (aGameObject); mGameObjectList.erase(lIt); break; } } if(!lFound) { SDL_LogDebug(SDL_LOG_CATEGORY_CUSTOM, "GameObject %s not found", aGameObject->GetName().c_str()); } return lFound; } void CGameObjectManager::Loop(Uint32 aRenderTime) const { for (std::vector< CGameObject* >::const_iterator lIt = mGameObjectList.begin(); lIt != mGameObjectList.end(); lIt++) { if ((*lIt)->ShouldCallOnEnable()) (*lIt)->OnEnable(); else if ((*lIt)->ShouldCallOnDisable()) (*lIt)->OnDisable(); (*lIt)->Loop(aRenderTime); } } std::vector< CGameObject* > CGameObjectManager::GetGameObjectInPos(const SDL_Point& aPosition) const { std::vector< CGameObject* > lRet; for (CGameObject* lGO : mGameObjectList) { if (lGO->PointInGameObject(aPosition)) { lRet.push_back(lGO); } } return lRet; } }
true
c464e5e727f3dc2407741af13810914bf802deef
C++
heimiaosd/C_Study
/c语言/循环的演示/源.cpp
UTF-8
1,143
2.921875
3
[]
no_license
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <windows.h> #include <string.h> #include <time.h> //-------------------定义数据部分----------------// //---------------函数声明部分-------------------// //计数循环 void sweetiel(); //打印字符三角形 void printCh(); int main() { printf("---------for循环---------\n"); for (int i = 0; i < 10; i++) { printf("%d\n",i); } printf("---------while循环---------\n"); int j = 0; while (j<10) { printf("%d\n", j); j++; } printf("---------do while循环---------\n"); int k = 0; do { printf("%d\n", k); k++; } while (k<10); sweetiel(); printCh(); return 0; } void sweetiel() { const int num = 22; int count = 1; //初始化 while (count<=num) { printf("计数器加一\n"); count++; } #if 0 //for死循环的写法 for (;;) { } //while死循环的写法 while (true) { } #endif // 0 } void printCh() { char ch; int row = 6; int col = 6; int index = 0; for (int i = 0; i < row; i++) { for (int j=0;j<col-i;j++) { printf("%c", 'A'+index); index++; } printf("\n"); } }
true
8d126c13986a3a4a1d8eec0ce11e7ec5c1ff31f3
C++
MeredithCL/Algorithms-Basic-Exercises
/set_intersection.cpp
UTF-8
1,200
2.953125
3
[ "MIT" ]
permissive
#include <bits/stdc++.h> using namespace std; class Solution { public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { set<int> x1; set<int> x2; int size1 = nums1.size(); int size2 = nums2.size(); vector<int> result; for (int i = 0; i < size1; ++ i) { x1.insert(nums1[i]); } for (int i = 0; i < size2; ++ i) { x2.insert(nums2[i]); } size1 = x1.size(); size2 = x2.size(); if (size1 < size2) { auto p1 = x1.begin(); auto end = x2.end(); for (int i = 0; i < size1; ++ i) { if (x2.find(*p1) != end) { result.push_back(*p1); } p1 ++; } } else { auto p2 = x2.begin(); auto end = x1.end(); for (int i = 0; i < size2; ++ i) { if (x1.find(*p2) != end) { result.push_back(*p2); } p2 ++; } } return result; } };
true
b3f04df045ebca148a2bb84dea5dbf40a1ae51ad
C++
jedh/bloodred
/Core/Include/Sprites/SpriteAnimation.h
UTF-8
641
2.859375
3
[]
no_license
#pragma once #include <string> #include <SDL.h> #include <vector> namespace BRCore { struct SpriteAnimation { public: SpriteAnimation(SDL_Texture* inTexture, std::string inName, int inNumFrames); ~SpriteAnimation(); SDL_Texture* texture; std::string name; int numFrames; int speed; bool isLooping; int currentFrame; Uint32 startTicks; int GetFrameWidth() const { return m_frameWidth; } int GetFrameHeight() const { return m_frameHeight; } const SDL_Rect& GetAnimationRect(int frame) const; private: bool m_isAnimating; int m_frameWidth; int m_frameHeight; std::vector<SDL_Rect> m_animationRects; }; }
true
c4dc51468963689627d339859a84bf7303dc68fb
C++
liwei1024/WC-
/DXF Console Exe/Game.cpp
GB18030
3,584
2.59375
3
[]
no_license
#include "pch.h" #include "Game.h" #include "utils.h" using namespace std; Game::Game() { } Game::~Game() { } // int Game::decrypt(int address) { VMProtectBeginUltra("decrypt"); int eax, esi, edx, i; eax = _Process.ReadInteger(address); esi = _Process.ReadInteger(__ַܻ); edx = eax >> 16; edx = _Process.ReadInteger(esi + edx * 4 + 36); eax = eax & 65535; eax = _Process.ReadInteger(edx + eax * 4 + 8468); edx = eax & 65535; esi = edx << 16; esi = esi | edx; i = _Process.ReadInteger(address + 4); esi = esi ^ i; VMProtectEnd(); return esi; } // void Game::encrypt(INT32 Address, INT32 Value) { VMProtectBeginUltra("encrypt"); INT32 EncryptId = 0; INT32 OffsetParam = 0; INT32 OffsetAddress = 0; INT32 Data = 0; INT32 AddressMask = 0; INT16 ax = 0; INT16 si = 0; EncryptId = _Process.ReadInteger(Address); OffsetParam = _Process.ReadInteger(_Process.ReadInteger(__ַܻ) + (EncryptId >> 16) * 4 + 36); OffsetAddress = OffsetParam + (EncryptId & 0xFFFF) * 4 + 8468; OffsetParam = _Process.ReadInteger(OffsetAddress); Data = OffsetParam & 0xFFFF; Data += Data << 16; ax = OffsetParam & 0xFFFF; AddressMask = Address & 0xF; if (AddressMask == 0x0) { si = Value >> 16; si -= ax; si += Value; } else if (AddressMask == 0x4) { si = (Value & 0xFFFF) - (Value >> 16); } else if (AddressMask == 0x8) { si = Value >> 16; si *= Value; } else if (AddressMask == 0xC) { si = Value >> 16; si += Value; si += ax; } else { return; } ax ^= si; _Process.WriteByte(OffsetAddress + 2, (BYTE)ax); _Process.WriteByte(OffsetAddress + 3, (BYTE)(ax >> 8)); _Process.WriteInteger(Address + 4, Data ^ Value); VMProtectEnd(); } // Ϸ״̬ int Game::Status() { return _Process.ReadInteger(__Ϸ״̬); } void Game::SelectRole() { } void Game::CityPlane(int MaxAreaID,int MinAreaId,int x,int y) { } void Game::SelectCopy(int CopyId,int CopyRand) { } void Game::FullScreenSkills() { } void Game::FullScreenToPickUp() { } void Game::GoToNextRoom() { } Pos Game::GetCurrentRoomPos() { Pos CurrentRoomPos; if (this->Status() == 1) { CurrentRoomPos.x = _Process.ReadOfset(__ȡֵ, { __ƫ }); CurrentRoomPos.y = _Process.ReadOfset(__ȡֵ, { __Сƫ }); } else { DWORD OffsetAddress = _Process.ReadOfset(__, { __ʱַ ,__ƫ }); CurrentRoomPos.x = _Process.ReadInteger(OffsetAddress + __ǰX); CurrentRoomPos.y = _Process.ReadInteger(OffsetAddress + __ǰY); } return CurrentRoomPos; } Pos Game::GetBossRoomPos() { Pos BossRoomPos; DWORD OffsetAddress = _Process.ReadOfset(__, { __ʱַ ,__ƫ }); BossRoomPos.x = this->decrypt(OffsetAddress + __BOSSX); BossRoomPos.y = this->decrypt(OffsetAddress + __BOSSY); return BossRoomPos; } bool Game::IsBossRoom() { Pos CurrentRoomPos; Pos BossRoomPos; CurrentRoomPos = GetCurrentRoomPos(); BossRoomPos = GetBossRoomPos(); if (CurrentRoomPos.x == BossRoomPos.x && CurrentRoomPos.y == BossRoomPos.y) { return true; } return false; } bool Game::IsOpenDoor() { if (Game::decrypt(_Process.ReadOfset(__ַ, { __ͼƫ }) + __ƫ) == 0) { return true; } else { return false; } } bool Game::GetTheCustomShop() { } void Game::ReturnCity() { } //Զ void Game::AutoUpgrade(LPVOID arg) { Game * _Game = ((Game*)arg); while (true) { } } // Զˢ void Game::AutoBrushGold(LPVOID arg) { Game * _Game = ((Game*)arg); while (true) { } }
true
b19e33a781d1dd3aa3a7dd82ead3922142fdf1fc
C++
cpaille/Assembleur
/AbstractVM/src/Parser/Parser/SyntaxAnalyzer.cpp
UTF-8
1,659
2.921875
3
[]
no_license
#include "SyntaxAnalyzer.hh" #include <AbstractVM> #include <Exception> #include <VMDef> SyntaxAnalyzer::SyntaxAnalyzer() { } SyntaxAnalyzer::~SyntaxAnalyzer() { } void SyntaxAnalyzer::addTokenType(TokenTypeInterface* type) { sort.push_back(type); } bool SyntaxAnalyzer::match(std::list<Token *>::iterator begin, std::list<Token *>::iterator end) { if (begin == end) { if (sort.size() == 1 && (*(sort.begin()))->match((*begin)->getValue())) { return true; } return false; } else { std::list<TokenTypeInterface *>::iterator iter = sort.begin(); while (begin != end) { if (iter == sort.end()) { return false; } if (!(*iter)->match((*begin)->getValue())) { return false; } begin++; iter++; } return true; } } InstructionInterface * SyntaxAnalyzer::create(std::list<Token *>::iterator begin, std::list<Token *>::iterator end) { InstructionInterface * instr = AbstractVM::getInstance()->getInstructionFactory()->createInstruction((*begin)->getValue()); instr->initialize(); if (begin != end) { begin++; instr->addParam((*begin)->getValue()); begin++; begin++; instr->addParam((*begin)->getValue()); } instr->finalize(); return instr; /**Old**/ if ((*begin)->getType() == VM_TTOKEN_INSTRUCTION) { instr->initialize(); if (begin != end) { begin++; while (begin != end) { if ((*begin)->getType() != VM_TTOKEN_OPERAND || (*begin)->getType() != VM_TTOKEN_DATA) { instr->addParam((*begin)->getValue()); } begin++; } } instr->finalize(); return instr; } throw SyntaxException(std::string("Syntax : ") + (*begin)->getType() + " / " + (*begin)->getValue()); }
true
dee3d5e277cfa7a2fe17fac52878b6c90e726682
C++
Kittnz/OculusRiftInAction
/source/Example_5_2_3_MeshDistort.cpp
UTF-8
5,907
2.75
3
[ "Apache-2.0" ]
permissive
#include "Common.h" std::map<StereoEye, Resource> SCENE_IMAGES = { { LEFT, Resource::IMAGES_TUSCANY_UNDISTORTED_LEFT_PNG}, { RIGHT, Resource::IMAGES_TUSCANY_UNDISTORTED_RIGHT_PNG } }; class DistortionHelper { protected: glm::dvec4 K; double lensOffset; double eyeAspect; double getLensOffset(StereoEye eye) { return (eye == LEFT) ? -lensOffset : lensOffset; } static glm::dvec2 screenToTexture(const glm::dvec2 & v) { return ((v + 1.0) / 2.0); } static glm::dvec2 textureToScreen(const glm::dvec2 & v) { return ((v * 2.0) - 1.0); } glm::dvec2 screenToRift(const glm::dvec2 & v, StereoEye eye) { return glm::dvec2(v.x + getLensOffset(eye), v.y / eyeAspect); } glm::dvec2 riftToScreen(const glm::dvec2 & v, StereoEye eye) { return glm::dvec2(v.x - getLensOffset(eye), v.y * eyeAspect); } double getUndistortionScaleForRadiusSquared(double rSq) { return K[0] + rSq * (K[1] + rSq * (K[2] + rSq * K[3])); } glm::dvec2 getUndistortedPosition(const glm::dvec2 & v) { return v * getUndistortionScaleForRadiusSquared(glm::length2(v)); } glm::dvec2 getTextureLookupValue(const glm::dvec2 & texCoord, StereoEye eye) { glm::dvec2 riftPos = screenToRift(textureToScreen(texCoord), eye); glm::dvec2 distorted = getUndistortedPosition(riftPos); return screenToTexture(riftToScreen(distorted, eye)); } bool closeEnough(double a, double b, double epsilon = 1e-5) { return abs(a - b) < epsilon; } double getDistortionScaleForRadius(double rTarget) { double max = rTarget * 2; double min = 0; double distortionScale; while (true) { double rSource = ((max - min) / 2.0) + min; distortionScale = getUndistortionScaleForRadiusSquared(rSource * rSource); double rResult = distortionScale * rSource; if (closeEnough(rResult, rTarget)) { break; } if (rResult < rTarget) { min = rSource; } else { max = rSource; } } return 1.0 / distortionScale; } glm::dvec2 findDistortedVertexPosition(const glm::dvec2 & source, StereoEye eye) { const glm::dvec2 rift = screenToRift(source, eye); double rTarget = glm::length(rift); double distortionScale = getDistortionScaleForRadius(rTarget); glm::dvec2 result = rift * distortionScale; glm::dvec2 resultScreen = riftToScreen(result, eye); return resultScreen; } public: DistortionHelper(const OVR::HMDInfo & ovrHmdInfo) { OVR::Util::Render::StereoConfig stereoConfig; stereoConfig.SetHMDInfo(ovrHmdInfo); const OVR::Util::Render::DistortionConfig & distortion = stereoConfig.GetDistortionConfig(); double postDistortionScale = 1.0 / stereoConfig.GetDistortionScale(); for (int i = 0; i < 4; ++i) { K[i] = distortion.K[i] * postDistortionScale; } lensOffset = distortion.XCenterOffset; eyeAspect = ovrHmdInfo.HScreenSize / 2.0f / ovrHmdInfo.VScreenSize; } gl::GeometryPtr createDistortionMesh( const glm::uvec2 & distortionMeshResolution, StereoEye eye) { std::vector<glm::vec4> vertexData; vertexData.reserve(distortionMeshResolution.x * distortionMeshResolution.y * 2); // The texture coordinates are actually from the center of the pixel, so thats what we need to use for the calculation. for (size_t y = 0; y < distortionMeshResolution.y; ++y) { for (size_t x = 0; x < distortionMeshResolution.x; ++x) { // Create a texture coordinate that goes from [0, 1] glm::dvec2 texCoord = glm::dvec2(x, y) / glm::dvec2(distortionMeshResolution - glm::uvec2(1)); // Create the vertex coordinate in the range [-1, 1] glm::dvec2 vertexPos = (texCoord * 2.0) - 1.0; // now find the distorted vertex position from the original // scene position vertexPos = findDistortedVertexPosition(vertexPos, eye); vertexData.push_back(glm::vec4(vertexPos, 0, 1)); vertexData.push_back(glm::vec4(texCoord, 0, 1)); } } std::vector<GLuint> indexData; for (size_t y = 0; y < distortionMeshResolution.y - 1; ++y) { size_t rowStart = y * distortionMeshResolution.x; size_t nextRowStart = rowStart + distortionMeshResolution.x; for (size_t x = 0; x < distortionMeshResolution.x; ++x) { indexData.push_back(nextRowStart + x); indexData.push_back(rowStart + x); } indexData.push_back(UINT_MAX); } return gl::GeometryPtr( new gl::Geometry(vertexData, indexData, indexData.size(), gl::Geometry::Flag::HAS_TEXTURE, GL_TRIANGLE_STRIP)); } }; class MeshDistortionExample : public RiftGlfwApp { protected: std::map<StereoEye, gl::Texture2dPtr> textures; std::map<StereoEye, gl::GeometryPtr> distortionGeometry; gl::ProgramPtr program; public: void initGl() { RiftGlfwApp::initGl(); glDisable(GL_BLEND); glDisable(GL_DEPTH_TEST); glEnable(GL_PRIMITIVE_RESTART); glPrimitiveRestartIndex(UINT_MAX); glClearColor(0.1f, 0.1f, 0.1f, 1.0f); program = GlUtils::getProgram( Resource::SHADERS_TEXTURED_VS, Resource::SHADERS_TEXTURED_FS); program->use(); DistortionHelper distortionHelper(ovrHmdInfo); // Load scene textures and generate distortion meshes for_each_eye([&](StereoEye eye){ GlUtils::getImageAsTexture(textures[eye], SCENE_IMAGES[eye]); distortionGeometry[eye] = distortionHelper.createDistortionMesh(glm::uvec2(64, 64), eye); }); } void draw() { glClear(GL_COLOR_BUFFER_BIT); for_each_eye([&](StereoEye eye){ renderEye(eye); }); } void renderEye(StereoEye eye) { // Enable this to see the mesh itself // glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); viewport(eye); textures[eye]->bind(); distortionGeometry[eye]->bindVertexArray(); distortionGeometry[eye]->draw(); } }; RUN_OVR_APP(MeshDistortionExample)
true
940ddfa4f4844c1b55b1a7d0197a64836cb03af4
C++
jingma-git/numeric
/chp2/lu.h
UTF-8
3,687
3.125
3
[]
no_license
#pragma once #include <eigen3/Eigen/Eigen> void lu(const Eigen::MatrixXd &A, Eigen::MatrixXd &L, Eigen::MatrixXd &U) { using namespace Eigen; int n = A.rows(); assert(A.rows() == A.cols() && "Input matrix A must be square!"); L = MatrixXd::Identity(n, n); U = A; for (int j = 0; j < n - 1; ++j) { for (int i = j + 1; i < n; ++i) { if (std::abs(U(j, j)) < EPS) { printf("pivot should not be 0!\n"); return; } double mult = U(i, j) / U(j, j); L(i, j) = mult; for (int k = 0; k <= j; ++k) { U(i, k) = 0; } for (int k = j + 1; k < n; ++k) { U(i, k) = U(i, k) - mult * U(j, k); } } } } // chp2.4 Paritial Pivot LU, select the largest pivot from the rest rows // PA = LU class PartialPivotLU { public: PartialPivotLU(const Eigen::MatrixXd &mat) : A(mat) {} const Eigen::MatrixXd &matrixL() const { return L; } const Eigen::MatrixXd &matrixU() const { return U; } const Eigen::MatrixXd &matrixP() const { return P; } void compute() // factorize { using namespace Eigen; int n = A.rows(); assert(A.rows() == A.cols() && "Input matrix A must be square!"); MatrixXd a = A; P = MatrixXd::Identity(n, n); std::cout << "a\n" << a << std::endl; for (int j = 0; j < n - 1; ++j) { for (int i = j + 1; i < n; ++i) { // select the largest element as pivot from col_j double pivot = a(j, j); int pi = j; for (int k = j + 1; k < n; ++k) { if (a(k, j) > pivot) { pivot = a(k, j); pi = k; } } if (pi != j) { P.row(j).swap(P.row(pi)); a.row(j).swap(a.row(pi)); } // eliminate pivot by subtract double mult = a(i, j) / a(j, j); a(i, j) = mult; for (int k = j + 1; k < n; ++k) { a(i, k) = a(i, k) - mult * a(j, k); } } } std::cout << "after a\n" << a << std::endl; L = MatrixXd::Identity(n, n); L.triangularView<StrictlyLower>() = a.triangularView<StrictlyLower>(); std::cout << "after L\n" << L << std::endl; U = a.triangularView<Upper>(); std::cout << "after U\n" << U << std::endl; std::cout << "after P\n" << P << std::endl; } Eigen::VectorXd solve(const Eigen::VectorXd &rhs) { int n = A.rows(); // L*c = P*rhs VectorXd b = P * rhs; for (int i = 0; i < n; ++i) { for (int j = 0; j < i; ++j) { b(i) -= L(i, j) * b(j); } b(i) = b(i) / L(i, i); } std::cout << "c\n" << b.transpose() << std::endl; for (int i = n - 1; i >= 0; --i) { for (int j = n - 1; j > i; --j) { b(i) -= U(i, j) * b(j); } b(i) = b(i) / U(i, i); } std::cout << "x\n" << b.transpose() << std::endl; return b; } private: Eigen::MatrixXd A; Eigen::MatrixXd L; Eigen::MatrixXd U; Eigen::MatrixXd P; };
true
e7b4b943cb9a47b71c84e0a9c58988c018fc0a72
C++
kszytko/object-oriented-programming
/shm/Ship.hpp
UTF-8
1,108
3.15625
3
[]
no_license
#pragma once #include <memory> #include <string> #include <vector> #include "Cargo.hpp" class Ship { public: Ship(); Ship(int id, const std::string& name, size_t speed, size_t maxCrew, size_t capacity); Ship(int id, size_t speed, size_t maxCrew); int getId() const { return _id; } std::string getName() const { return _name; } size_t getSpeed() const { return _speed; } size_t getMaxCrew() const { return _maxCrew; } size_t getCapacity() const { return _capacity; } size_t getCrew() const { return _crew; } std::vector<std::shared_ptr<Cargo>> getCargos() const { return _cargo; } std::shared_ptr<Cargo> getCargo(const size_t id) const; void setName(const std::string& name) { _name = name; } Ship& operator+=(const size_t crew); Ship& operator-=(const size_t crew); private: const int _id; std::string _name; size_t _speed; size_t _maxCrew; size_t _capacity; size_t _crew; std::vector<std::shared_ptr<Cargo>> _cargo; };
true
e3712174b3b84e3d024f4c45737bc4ee55e10d1d
C++
Dvmenasalvas/EDA
/Juez/2ndo cuatri/14.cpp
ISO-8859-1
1,190
3.171875
3
[]
no_license
// Grupo XYZ, Fulano y Mengano // Comentario general sobre la solucin, // explicando cmo se resuelve el problema #include <iostream> #include <vector> #include <fstream> #include <stdexcept> #include <algorithm> #include <string> #include "bintree_eda.h" using namespace std; // funcin que resuelve el problema // comentario sobre el coste, O(f(N)), donde N es ... int gruposRescate(bintree<int> montania, int & maximo){ if(montania.empty()) return 0; else{ int gIzq, gDer, maxIzq = 0, maxDer = 0; gIzq = gruposRescate(montania.left(), maxIzq); gDer = gruposRescate(montania.right(), maxDer); if(gIzq == 0 && gDer == 0){ if(montania.root() == 0) return 0; else { maximo = montania.root(); return 1; } } else { maximo = montania.root() + max(maxIzq, maxDer); return gIzq + gDer; } } } // Resuelve un caso de prueba, leyendo de la entrada la // configuracin, y escribiendo la respuesta void resuelveCaso() { bintree<int> montania = leerArbol(-1); int max = 0; cout << gruposRescate(montania, max) << " "; cout << max << '\n'; } int main() { int casos; cin >> casos; for(int i = 0; i < casos; i++) resuelveCaso(); return 0; }
true
a9da0da912bf77730520643ab47d65fd2db1fae4
C++
arora-ansh/CP-Repository
/algos/heaps/heaps.cpp
UTF-8
2,623
4.03125
4
[]
no_license
/* In heaps, Insertion - O(logn) Deletion - O(logn) Min/Max Element - O(1) Useful where the min/max element needs to be found out multiple times It is basically a tree like data structure where value stored in a node < value stored in each of its children Operations - • CreateHeap(H) : Create an empty heap H. • Insert(x,H) : Insert a new key with value x into the heap H. • Extract-min(H) : delete the smallest key from H. • Decrease-key(p, ∆, H) : decrease the value of the key p by amount ∆. • Merge(H1,H2) : Merge two heaps H1 and H2. Here we will implement a binary tree using an array. A complete binary tree can be implemented in such a manner. Zero index - - Index of Left Child = 2*i+1 - Index of Right Child = 2*i+2 - Index of Parent = Floor of (i-1)/2 A binary heap is one where the heap can be redrawn into a complete binary tree. Egs - H 4 14 9 17 23 21 29 91 37 25 88 33 Variables maintained - H[] - Array for the Heap Size - Size of Heap Array */ #include <iostream> using namespace std; int Heap[]; int size; int find_min(int H[]){ return H[0]; } // In this we will have to return min value and also remove it from the heap. Done in O(logn) time int extract_min(int H[]){ int x = H[0]; H[0] = H[size-1]; H[size-1] = x; size--; heapify(0,H); return x; } //Here x has to be inserted into the tree. First, insert the node into the last position and then keep switching it with its parent //until its larger than the parent. void insert(int H[], int x){ int i = size; H[size] = x; size++; while(i>0 && H[i]<H[(i-1)/2]){ int temp = H[i]; H[i] = H[(i-1)/2]; H[(i-1)/2] = temp; i = (i-1)/2; } } // We can build a heap incrementally in nlogn time. -> Trivial Solution /* Proper Method to Build binary heap - 1) Copy all elements into given array H 2) Heap Property naturally holds for all leaf nodes in the given tree (n/2) in number. 3) Heapify for the other elements. */ //Heapify function where parents are swapped if bigger void heapify(int i, int H[]){ n = size - 1; bool flag = true; while(i<=(n-1)/2 && flag){ int min = i;//Let us consider parent to be smallest initially if(H[i]>H[2*i+1]){ min = 2*i+1;//2i+1th element is made smallest in this case } if(2*i+2<=n && H[min]>H[2*i+2]){ min = 2*i+2; } if(min!=i){ int temp = H[i]; H[i] = H[min]; H[min] = temp; i = min; } else{ flag = false; } } } int main(){ return 0; }
true
a93d39be6a861e6f3fe0b93baa9da487e440fdb9
C++
kg810/KGTrading
/kglib/mmap/mmaputil.h
UTF-8
1,829
2.859375
3
[]
no_license
/* * Provide memory map functionality */ #include <vector> #include <mutex> #include <exception> #include <atomic> #include <boost/interprocess/shared_memory_object.hpp> #include <boost/interprocess/mapped_region.hpp> namespace kg { using namespace boost::interprocess; struct MetaEntry { uint16_t kgId; // unique id per symbol size_t offset; // offset of certern book std::atomic<bool> updated{false}; std::mutex _mtx; uint8_t refCount{0}; }; template<typename BOOK> class BookContainer { public: BookContainer(size_t _numOfBooks) : numOfBooks(_numOfBooks) {} ssize_t init() { // reserve space for metaHeader metaEntries.reserve(numOfBooks * sizeOfMetaEntry); metaEntries.resize(numOfBooks * sizeOfMetaEntry); sizeOfMeta = metaEntries.size(); try { shared_memory_object shm(open_or_create, "BOOKCONTAINER", read_write); shm.truncate(metaEntries.size() + sizeOfBook * numOfBooks); mapped_region region(shm, read_write); } catch( interprocess_exception& ex ) { throw std::runtime_error(ex.what()); } // initialize meta entries for(int idx = 0; idx < numOfBooks; ++idx) { metaEntries[idx].offset = idx; } std::memmove(region.get_address(), &metaEntries[0], metaEntries.size()); for(int idx = 0; idx < numOfBooks; ++idx) // initalize books { BOOK bk; std::memmove(region.get_address() + sizeOfMeta + idx * sizeOfBook, &bk, sizeOfBook); } } private: std::vector<MetaEntry> metaEntries; size_t numOfBooks; size_t sizeOfMetaEntry{sizeof(MetaEntry)}; size_t sizeOfMeta{0}; size_t sizeOfBook{sizeof(BOOK)}; }; }
true
bcee7ea6a66ce0996064f413ea6376aacb8731e3
C++
ZihengChen/CLUEAlgo
/include/CLUEAlgo.h
UTF-8
3,477
2.8125
3
[]
no_license
#ifndef CLUEAlgo_h #define CLUEAlgo_h // C/C++ headers #include <set> #include <string> #include <vector> #include <iostream> #include <fstream> #include <chrono> #include "LayerTiles.h" #include "Points.h" class CLUEAlgo{ public: // constructor CLUEAlgo(float dc, float deltao, float deltac, float rhoc, bool verbose=false ){ dc_ = dc; deltao_ = deltao; deltac_ = deltac; rhoc_ = rhoc; dm_ = std::max(deltao_, deltac_); verbose_ = verbose; } // distrcutor ~CLUEAlgo(){} // public variables float dc_, dm_, deltao_, deltac_, rhoc_; bool verbose_; Points points_; // public methods void setPoints(int n, float* x, float* y, int* layer, float* weight) { points_.clear(); points_.n = n; // input variables points_.x.assign(x, x + n); points_.y.assign(y, y + n); points_.layer.assign(layer, layer + n); points_.weight.assign(weight, weight + n); // result variables points_.rho.resize(n,0); points_.delta.resize(n,std::numeric_limits<float>::max()); points_.nearestHigher.resize(n,-1); points_.isSeed.resize(n,0); points_.followers.resize(n); points_.clusterIndex.resize(n,-1); } void clearPoints(){ points_.clear(); } void makeClusters(); void verboseResults( std::string outputFileName = "cout", int nVerbose = -1){ if (verbose_) { if (nVerbose ==-1) nVerbose=points_.n; // verbose to screen if (outputFileName.compare("cout") == 0 ) { std::cout << "index,x,y,layer,weight,rho,delta,nh,isSeed,clusterId"<< std::endl; for(int i = 0; i < nVerbose; i++) { std::cout << i << ","<<points_.x[i]<< ","<<points_.y[i]<< ","<<points_.layer[i] << ","<<points_.weight[i]; std::cout << "," << points_.rho[i]; if (points_.delta[i] <= 999) std::cout << ","<<points_.delta[i]; else std::cout << ",999"; // convert +inf to 999 in verbose std::cout << ","<<points_.nearestHigher[i]; std::cout << "," << points_.isSeed[i]; std::cout << ","<<points_.clusterIndex[i]; std::cout << std::endl; } } // verbose to file else{ std::ofstream oFile(outputFileName); oFile << "index,x,y,layer,weight,rho,delta,nh,isSeed,clusterId\n"; for(int i = 0; i < nVerbose; i++) { oFile << i << ","<<points_.x[i]<< ","<<points_.y[i]<< ","<<points_.layer[i] << ","<<points_.weight[i]; oFile << "," << points_.rho[i]; if (points_.delta[i] <= 999) oFile << ","<<points_.delta[i]; else oFile << ",999"; // convert +inf to 999 in verbose oFile << ","<<points_.nearestHigher[i]; oFile << "," << points_.isSeed[i]; oFile << ","<<points_.clusterIndex[i]; oFile << "\n"; } oFile.close(); } }// end of if verbose_ } private: // private variables // private member methods void prepareDataStructures(std::array<LayerTiles, NLAYERS> & ); void calculateLocalDensity(std::array<LayerTiles, NLAYERS> & ); void calculateDistanceToHigher(std::array<LayerTiles, NLAYERS> & ); void findAndAssignClusters(); inline float distance(int , int) const ; }; #endif
true
d78b35d4ed0e95931866a4a6254c0975b203ffdb
C++
Leumash/ProjectEuler
/43/43.cc
UTF-8
1,621
3.875
4
[]
no_license
/* The number, 1406357289, is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9 in some order, but it also has a rather interesting sub-string divisibility property. Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the following: d2d3d4=406 is divisible by 2 d3d4d5=063 is divisible by 3 d4d5d6=635 is divisible by 5 d5d6d7=357 is divisible by 7 d6d7d8=572 is divisible by 11 d7d8d9=728 is divisible by 13 d8d9d10=289 is divisible by 17 Find the sum of all 0 to 9 pandigital numbers with this property. */ #include <iostream> #include <vector> #include <algorithm> using namespace std; bool IsDivisible(int divisor, char num[], int pos) { bool toReturn; char temp = num[pos + 3]; num[pos+3] = '\0'; toReturn = (atoi(num + pos) % divisor == 0); num[pos+3] = temp; return toReturn; } bool IsInterestingSubStringDivisibilityProperty(char num[]) { int primes[] = {2,3,5,7,11,13,17}; int numPrimes = sizeof(primes) / sizeof(int); for (int i=0; i<numPrimes; ++i) { if (!IsDivisible(primes[i], num, i + 1)) { return false; } } return true; } long long GetSum() { long long sum = 0; char permutation[10]; for (int i=0; i<10; ++i) { permutation[i] = i + '0'; } do { if (IsInterestingSubStringDivisibilityProperty(permutation)) { sum += atoll(permutation); } } while (next_permutation(permutation, permutation + 10)); return sum; } int main() { cout << GetSum() << endl; return 0; }
true
6933bd055072a46d65e193138001848a9f2677e0
C++
FrancoisGDrouin/IFT-2008-TP1
/Labyrinthe.cpp
UTF-8
19,909
2.96875
3
[]
no_license
/** * \file Labyrinthe.cpp * \brief Le code des méthodes membres et privés de la classe Labyrinthe. * \author IFT-2008, Étudiant(e) * \version 0.1 * \date février 2021 * */ //Fichiers à compléter par les autres méthodes de la classe Labyrinthes demandées #include "Labyrinthe.h" namespace TP1 { //FGD D /** * \fn Labyrinthe::Labyrinthe() * \brief Constructeur par défaut de la classe Labyrinthe \n * Assigne aux attributs depart, arrivee et dernier un pointeur nul "nullptr" */ //FGD F using namespace std; // ------------------------------------------------------------------------------------------------- // Méthodes fournies // ------------------------------------------------------------------------------------------------- /** * \fn void Labyrinthe::chargeLabyrinthe(Couleur couleur, std::ifstream &entree) * \param[in] couleur, la couleur du jouer auquel le labyrinthe chargé s'applique * \param[in] entree, fichier contenant la définition du labyrinthe */ void Labyrinthe::chargeLabyrinthe(Couleur couleur, std::ifstream &entree) //1 { int nbCols, nbRangs; if (!entree.is_open()) throw logic_error("Labyrinthe::chargeLabyrinthe: Le fichier n'est pas ouvert !"); entree >> nbCols >> nbRangs; entree.ignore(); //pour consommer le \n (le caractère fin de ligne) const int MAX_LIGNE = 1000; char ligne[MAX_LIGNE]; entree.getline(ligne, MAX_LIGNE); entree.getline(ligne, MAX_LIGNE); std::ostringstream s; //Une chaîne pour écrire dedans, cette chaîne servira pour nommer les pièces du labyrinthe for (int i = 0; i < nbCols; i++) { for (int j = 0; j < nbRangs; j++) { s << i << "," << j; Piece p(s.str()); s.str(""); ajoutePieceLabyrinthe(p); } } for (int i = 0; i < nbCols; i++) { if (ligne[i * 4 + 1] == 'D' || ligne[i * 4 + 1] == 'd') { std::string nom; s << i << ",0"; nom = s.str(); s.str(""); placeDepart(nom); } if (ligne[i * 4 + 1] == 'F' || ligne[i * 4 + 1] == 'f' || ligne[i * 4 + 1] == 'A' || ligne[i * 4 + 1] == 'a') { std::string nom; s << i << ",0"; nom = s.str(); s.str(""); placeArrivee(nom); } } for (int j = 0; j < nbRangs; j++) { entree.getline(ligne, MAX_LIGNE); for (int i = (j == nbRangs - 1 && (j & 1)) ? 1 : 0; i < nbCols; i++) { if (j & 1) { if (j < nbRangs - 2 && ligne[i * 4 + 3] == ' ') { ajoutePassage(couleur, i, j, i, j + 2); } if (j < nbRangs - 1 && ligne[i * 4 + 2] == ' ') { ajoutePassage(couleur, i, j, i, j + 1); } if (j < nbRangs - 1 && ligne[i * 4 + 0] == ' ') { ajoutePassage(couleur, i - 1, j, i, j + 1); } if (j < nbRangs - 1 && (ligne[i * 4 + 1] == 'D' || ligne[i * 4 + 1] == 'd')) { std::string nom; s << i << "," << j + 1; nom = s.str(); s.str(""); placeDepart(nom); } if (j < nbRangs - 1 && (ligne[i * 4 + 1] == 'F' || ligne[i * 4 + 1] == 'f' || ligne[i * 4 + 1] == 'A' || ligne[i * 4 + 1] == 'a')) { std::string nom; s << i << "," << j + 1; nom = s.str(); s.str(""); placeArrivee(nom); } } else { if (j < nbRangs - 1 && ligne[i * 4 + 0] == ' ') { ajoutePassage(couleur, i - 1, j + 1, i, j); } if (j < nbRangs - 2 && ligne[i * 4 + 1] == ' ') { ajoutePassage(couleur, i, j, i, j + 2); } if (j < nbRangs - 1 && ligne[i * 4 + 2] == ' ') { ajoutePassage(couleur, i, j, i, j + 1); } if (j < nbRangs - 1 && (ligne[i * 4 + 3] == 'D' || ligne[i * 4 + 3] == 'd')) { std::string nom; s << i << "," << j + 1; nom = s.str(); s.str(""); placeDepart(nom); } if (j < nbRangs - 1 && (ligne[i * 4 + 3] == 'F' || ligne[i * 4 + 3] == 'f' || ligne[i * 4 + 3] == 'A' || ligne[i * 4 + 3] == 'a')) { std::string nom; s << i << "," << j + 1; nom = s.str(); s.str(""); placeArrivee(nom); } } } } } /** * \fn Labyrinthe::ajoutePassage(Couleur couleur, int i1, int j1, int i2, int j2) * \param[in] Couleur couleur Couleur de la porte à ajouter * \param[in] int i1 * \param[in] int j1 * \param[in] int i2 * \param[in] int j2 */ void Labyrinthe::ajoutePassage(Couleur couleur, int i1, int j1, int i2, int j2) //3 { NoeudListePieces *piece1, *piece2; string nomPiece1, nomPiece2; ostringstream s; s << i1 << "," << j1; nomPiece1 = s.str(); s.str(""); s << i2 << "," << j2; nomPiece2 = s.str(); s.str(""); piece1 = trouvePiece(nomPiece1); piece2 = trouvePiece(nomPiece2); Porte nouvellePorte(couleur, &(piece2->piece)); piece1->piece.ajoutePorte(nouvellePorte); } /** * \fn Labyrinthe::ajoutePieceLabyrinthe(Piece& p) * \brief ajoute une pièce au labyrinthe (si elle ne s'y trouve pas déjà) * \param[in] p La pièce à ajouter * \post la pièce appartient au labyrinthe; */ void Labyrinthe::ajoutePieceLabyrinthe(const Piece& p) { //2 Labyrinthe::NoeudListePieces* noeud = new Labyrinthe::NoeudListePieces; noeud->piece = p; if (dernier == 0) { noeud->suivant = noeud; dernier = noeud; } else if (!appartient(p)) { noeud->suivant = dernier->suivant; dernier->suivant = noeud; } } //FGD D /** * \fn Labyrinthe::Labyrinthe() * \brief Constructeur par défaut de la classe Labyrinthe \n * Assigne aux attributs depart, arrivee et dernier un pointeur nul "nullptr" */ Labyrinthe::Labyrinthe() : depart(nullptr), arrivee(nullptr), dernier(nullptr) { } /** * \fn Labyrinthe::~Labyrinthe() * \brief Destructeur de la classe Labyrinthe , s'assure de libere la memoire des instances NoeudListePieces en appelant la méthode _detruire */ Labyrinthe::~Labyrinthe() { _detruire(); } /** * \fn void Labyrinthe::placeDepart(const std::string &nom) * \brief met le pointeur depart a la position de la piece de meme nom dans le Labyrinthe. \n * Si la piece n'existe pas une exception logic_error est lance * \param[in] nom nom de la piece à placer comme étant le départ */ void Labyrinthe::placeDepart(const std::string &nom) { NoeudListePieces *courant = dernier->suivant; if (dernier->piece.getNom() == nom) { depart = &(dernier->piece); return; } while (courant != dernier) { if (courant->piece.getNom() == nom) { depart = &(courant->piece); return; } courant = courant->suivant; } throw logic_error("La pièce portant le nom spécifié n'appartient pas au Labyrinthe "); } /** * \fn void Labyrinthe::placeArrivee(const std::string &nom) * \brief met le pointeur arrivee à la position de la piece de meme nom dans le Labyrinthe * \param[in] nom nom de la piece à placer comme étant l'arrivée */ void Labyrinthe::placeArrivee(const std::string &nom) { NoeudListePieces *courant = dernier->suivant; if (dernier->piece.getNom() == nom) { arrivee = &(dernier->piece); return; } while (courant != dernier) { if (courant->piece.getNom() == nom) { arrivee = &(courant->piece); return; } courant = courant->suivant; } throw logic_error("La pièce portant le nom spécifié n'appartient pas au Labyrinthe "); } /** * \fn void Labyrinthe::_detruire() * \brief méthode de la classe Labyrinthe qui permet de détruire les instances alloueés dynamiquement */ void Labyrinthe::_detruire() { if (dernier != nullptr) { NoeudListePieces *courant = dernier->suivant; NoeudListePieces *destructeur = courant; while (courant != dernier) { courant = courant->suivant; destructeur->suivant = nullptr; delete destructeur; destructeur = courant; } dernier->suivant = nullptr; delete dernier; } dernier = nullptr; } /** * \fn const Labyrinthe &Labyrinthe::operator=(const Labyrinthe &source) * \brief Surcharge de l'opérateur d'assignation pour la classe Labyrinthe * \param[in] source une instance de type labyrinthe passé par référence constante dont on souhaite faire l'assignation */ const Labyrinthe &Labyrinthe::operator=(const Labyrinthe &source) { if (dernier != nullptr) { _detruire(); } if (source.dernier != 0) { _copier(source); } return (*this); } /** * \fn bool Labyrinthe::appartient(const Piece &p) const * \brief Méthode de la classe Labyrinthe qui vérifie si une pièce appartient au Labyrinthe * \param[in] p une instance de type piece passée par référence constante * \return un booléen qui indique si la pièce appartient au labyrinthe ou non */ bool Labyrinthe::appartient(const Piece &p) const { if (dernier == nullptr) { return false; } NoeudListePieces *courant = dernier->suivant; while (courant != dernier) { if (courant->piece.getNom() == p.getNom()) { return true; } courant = courant->suivant; } if (dernier->piece.getNom() == p.getNom()) { return true; } return false; } /** * \fn Labyrinthe::NoeudListePieces *Labyrinthe::trouvePiece(const std::string &nom) const * \brief méthode permettant de retourner l'adresse du noeud de la liste de pièces contenue dans le labyrinthe qui correspond à la pièce portant le nom fournit * \param[in] nom de la pièce */ Labyrinthe::NoeudListePieces *Labyrinthe::trouvePiece(const std::string &nom) const { if (nom == "") { throw invalid_argument("Le nom ne doit pas être vide"); } NoeudListePieces *courant = dernier->suivant; while (courant != dernier) { if (courant->piece.getNom() == nom) { return &(*courant); } courant = courant->suivant; } } /** * \fn Labyrinthe::Labyrinthe(const Labyrinthe &source) * \brief Constructeur copie de la classe Labyrinthe qui appelle la méthode _copier * \param[in] source une instance de type labyrinthe passé par référence constante */ Labyrinthe::Labyrinthe(const Labyrinthe &source) { if (source.dernier == nullptr) { dernier = nullptr; } else { _copier(source); } } /** * \fn void Labyrinthe::_copier(const Labyrinthe &source) * \brief méthode de la classe Labyrinthe permettant de faire une deep copy d'une instance de type Labyrinthe * \param[in] source une instance de type Labyrinthe passée par référence constante */ void Labyrinthe::_copier(const Labyrinthe &source) { try { dernier = source.dernier; dernier->piece = Piece(source.dernier->piece); NoeudListePieces *courant_source = source.dernier->suivant; NoeudListePieces *courant = dernier->suivant; while (courant_source != dernier) { courant->suivant = new NoeudListePieces; courant->piece = Piece(courant_source->piece); courant = courant->suivant; courant_source = courant_source->suivant; } courant->suivant = dernier; } catch (const std::exception &) { _detruire(); } } /** * \fn int Labyrinthe::solutionner(Couleur joueur) * \brief Méthode de la classe Labyrinthe qui permet de solutionner le labyrinthe pour un joueur d'une couleur donnée * \param[in] joueur une couleur * \return un int qui indique en combien d'étapes le joueur peut solutionner le labyrinthe */ int Labyrinthe::solutionner(Couleur joueur) //4 { std::queue<Piece *> file; setAttributParcourueAFalse(); depart->setParcourue(true); // 1. Enfiler la pièce de départ en lui associant une distance du départ de zéro. depart->setDistanceDuDebut(0); file.push(depart); // 2.1 Faire défiler une pièce Piece *courant = nullptr; do { courant = file.front(); file.pop(); const int distance_courante = courant->getDistanceDuDebut(); std::list<Porte> portes = courant->getPortes(); // 2.2 Enfiler toutes les pièces qui sont accessibles à partir de cette pièce à l'aide d'une porte // de la couleur du joueur, et qui n'ont pas été déjà parcourues, en leur associant la distance // du départ de la pièce défilée plus un. // 2.2.1 Déterminer si une pièce connectée à la pièce courante contient une porte pouvant s'y rendre // de la bonne couleur chercherPorteBonneCouleurVersPieceCourante(portes, joueur, file, distance_courante); permetPassageVersPieceCourante(file, courant); } while (!file.empty() && courant != arrivee); if (courant != arrivee) { return -1; } return courant->getDistanceDuDebut(); } /** * \fn void Labyrinthe::chercherPorteBonneCouleurVersPieceCourante(const std::list<Porte> &portes, Couleur joueur, std::queue<Piece *> &file, int distance_courante) * \brief méthode utilisée dans solutionner() afin de déterminer si une piece contient une porte de la couleur du joueur qui permet le passage vers la piece courante * \param[in] portes une liste de portes * \param[in] joueur la couleur du joueur pour la quelle on souhaite trouver un passage existant * \param[in] file queue contenant des pointeurs de pieces * \param[in] distance_courante distance_courante actuelle */ void Labyrinthe::chercherPorteBonneCouleurVersPieceCourante(const std::list<Porte> &portes, Couleur joueur, std::queue<Piece *> &file, int distance_courante) { for (auto &porte : portes) { if (porte.getCouleur() == joueur) { if (!porte.getDestination()->getParcourue()) { porte.getDestination()->setParcourue(true); porte.getDestination()->setDistanceDuDebut(distance_courante + 1); file.push(porte.getDestination()); } } } } /** * \fn void Labyrinthe::permetPassageVersPieceCourante(std::queue<Piece *> &file, Piece *pieceCourante) * \brief méthode utiliseé dans solutionner() afin de déterminer si une piece permet le passage vers la piece courante * \param[in] file queue contenant des pointeurs de pieces * \param[in] pieceCourante pointeur de la piece dont on cherche des passages y menant */ void Labyrinthe::permetPassageVersPieceCourante(std::queue<Piece *> &file, Piece *pieceCourante) { NoeudListePieces *courant_parcours_complet = dernier->suivant; while (courant_parcours_complet != dernier) { Piece *piece_courante_parcours_complet = &(courant_parcours_complet->piece); if (piece_courante_parcours_complet->getParcourue() == false) { for (const auto &porte : piece_courante_parcours_complet->getPortes()) { if (porte.getDestination() == pieceCourante) { piece_courante_parcours_complet->setDistanceDuDebut(pieceCourante->getDistanceDuDebut() + 1); file.push(piece_courante_parcours_complet); } } } courant_parcours_complet = courant_parcours_complet->suivant; } } /** * \fn void Labyrinthe::setAttributParcourueAFalse() * \brief Méthode mettant à false l'attribut parcourue de toutes les pieces du labyrinthes */ void Labyrinthe::setAttributParcourueAFalse() { NoeudListePieces *courantIni = dernier->suivant; while (courantIni != dernier) { courantIni->piece.setParcourue(false); courantIni->piece.setDistanceDuDebut(0); courantIni = courantIni->suivant; } dernier->piece.setParcourue(false); } /** * \fn Couleur Labyrinthe::trouveGagnant() * \brief Méthode faisant 4 appels sur solutionner() pour déterminer quel joueur de Couleur solutionne le labyrinthe en moins d'étapes en faisant appelle à la méthode chercheMeilleurScore */ Couleur Labyrinthe::trouveGagnant() { const std::map<Couleur, int> joueurs = {{Couleur::Bleu, solutionner(Couleur::Bleu)}, {Couleur::Rouge, solutionner(Couleur::Rouge)}, {Couleur::Vert, solutionner(Couleur::Vert)}, {Couleur::Jaune, solutionner(Couleur::Jaune)}}; return chercheMeilleurScore(joueurs); } /** * \fn Couleur Labyrinthe::chercheMeilleurScore(const std::map<Couleur, int> &joueurs) * \brief Méthode permettant de comparer les résultats des differents joueurs apres leur appel à la méthode solutionner * \param[in] joueurs une map <Couleur,int> */ Couleur Labyrinthe::chercheMeilleurScore(const std::map<Couleur, int> &joueurs) { std::pair<std::vector<Couleur>, int> min = {{Couleur::Aucun}, std::numeric_limits<int>::max()}; for (const auto &kv : joueurs) { if (kv.second < min.second && kv.second != -1) { min.first = std::vector<Couleur>(1, kv.first); min.second = kv.second; } else if (kv.second == min.second) { min.first.push_back(kv.first); min.second = kv.second; } } if (min.first.size() == 1) { return min.first[0]; } else { return gagnantAmbigue(min.first); } } /** * \fn Couleur Labyrinthe::gagnantAmbigue(const std::vector<Couleur> &joueurs) const * \brief méthode utilisé dans le cas d'ambiguité dans la recherche du score d'un joueur pour solutionner un labyrinthe * \param[in] joueur un vecteur de couleur des joueurs * \return une couleur du gagnant dans le cas d'ambiguité */ Couleur Labyrinthe::gagnantAmbigue(const std::vector<Couleur> &joueurs) const { if (std::find(joueurs.begin(), joueurs.end(), Couleur::Rouge) != joueurs.end()) { return Couleur::Rouge; } else if (std::find(joueurs.begin(), joueurs.end(), Couleur::Vert) != joueurs.end()) { return Couleur::Vert; } else if (std::find(joueurs.begin(), joueurs.end(), Couleur::Bleu) != joueurs.end()) { return Couleur::Bleu; } return Couleur::Jaune; } //FGD F }//fin du namespace
true
7378b84e566eec69f1b31d29771ee8c1de0ed3ce
C++
gigatexal/languagestudy
/cs162/project1/project1.cpp
UTF-8
2,935
3.421875
3
[]
no_license
#include <iostream> #include <climits> #include <cstring> #include <iomanip> using namespace std; struct Item { char name[CHAR_MAX]; unsigned int qty; double price; }; template <class T> void get(T &var); void get(char str[], const unsigned int size); void UI(); void greeting(); double total(Item items[]); double subtotal(Item item); double total(Item items[]); int main(){ UI(); return 0; } template <class T> void get(T &var){ T val; cin >> val; while (!cin){ cout << "Data entered was invalid" << endl; cin.clear(); cin.ignore(CHAR_MAX,'\n'); cin >> val; } cin.ignore(CHAR_MAX,'\n'); var = val; } void get(char str[], unsigned int size){ cin.get(str, size, '\n'); while(!cin){ cin.clear(); cin.ignore(CHAR_MAX,'\n'); cin.get(str, size, '\n'); } cin.ignore(CHAR_MAX,'\n'); } double subtotal(Item item){ return item.qty * item.price; } double total(Item items[]){ int index = 0; double totalCost; while (items[index].name && items[index].qty && items[index].price){ totalCost += subtotal(items[index]); index++; } return totalCost; } void greeting(){ cout << "Going shopping? Wouldn't it be nice to know the current" << " value of the things in your basket?" << endl; cout << "Follow the prompts and the program will keep track of your spending." << endl; return; } void UI(){ const int MAX_CART_SIZE = 1024; char quit = 'y'; Item items[MAX_CART_SIZE]; unsigned int index = 0; greeting(); while ( (quit != 'n' || quit != 'N') && index < MAX_CART_SIZE){ Item currItem; cout << "Enter in the name of the item e.g Cracker Jacks: "; get(currItem.name,CHAR_MAX); cout << "Enter in the price of " << currItem.name << " in dollars and cents e.g 12.98: "; get(currItem.price); cout << "Enter in the quantity of " << currItem.name << "(s) in whole numbers: "; get(currItem.qty); //add the item to the array of items items[index] = currItem; //display running total cout.setf(ios::fixed, ios::floatfield); cout.setf(ios::showpoint); cout.precision(2); for (int i = 0; i < MAX_CART_SIZE; i++){ if (items[i].name && items[i].qty && items[i].price){ cout << setw(20) << right << setw(6) << i << ": " << right << setw(20) << items[i].name << right << setw(10) << " " << items[i].price << right << setw(10) << " " << items[i].qty << right << setw(10) << " subtotal " << subtotal(items[i]) << endl; } else { break; } } cout << "Current total of your basket: $" << total(items) << endl; cout << "Would you like to quit? y - yes to quit, n - no to continue shopping "; get(quit); if (quit == 'y' || quit == 'Y'){ break; } index++; } return; }
true
eeef3494893db60c79137dbe2bcdce7299bd1b53
C++
bakkot/FIter
/src/FIter.h
UTF-8
6,383
3.234375
3
[]
no_license
#ifndef FITER_FITER_H #define FITER_FITER_H #include <functional> #include <iterator> namespace FIter { // Used to determine which functions a pair of iterator types have in common. template <class, class> struct least_iterator_type; template <> struct least_iterator_type<std::input_iterator_tag, std::input_iterator_tag> {typedef std::input_iterator_tag type;}; template <> struct least_iterator_type<std::input_iterator_tag, std::forward_iterator_tag> {typedef std::input_iterator_tag type;}; template <> struct least_iterator_type<std::input_iterator_tag, std::bidirectional_iterator_tag> {typedef std::input_iterator_tag type;}; template <> struct least_iterator_type<std::input_iterator_tag, std::random_access_iterator_tag> {typedef std::input_iterator_tag type;}; template <> struct least_iterator_type<std::forward_iterator_tag, std::input_iterator_tag> {typedef std::input_iterator_tag type;}; template <> struct least_iterator_type<std::forward_iterator_tag, std::forward_iterator_tag> {typedef std::forward_iterator_tag type;}; template <> struct least_iterator_type<std::forward_iterator_tag, std::bidirectional_iterator_tag> {typedef std::forward_iterator_tag type;}; template <> struct least_iterator_type<std::forward_iterator_tag, std::random_access_iterator_tag> {typedef std::forward_iterator_tag type;}; template <> struct least_iterator_type<std::bidirectional_iterator_tag, std::input_iterator_tag> {typedef std::input_iterator_tag type;}; template <> struct least_iterator_type<std::bidirectional_iterator_tag, std::forward_iterator_tag> {typedef std::forward_iterator_tag type;}; template <> struct least_iterator_type<std::bidirectional_iterator_tag, std::bidirectional_iterator_tag> {typedef std::bidirectional_iterator_tag type;}; template <> struct least_iterator_type<std::bidirectional_iterator_tag, std::random_access_iterator_tag> {typedef std::bidirectional_iterator_tag type;}; template <> struct least_iterator_type<std::random_access_iterator_tag, std::input_iterator_tag> {typedef std::input_iterator_tag type;}; template <> struct least_iterator_type<std::random_access_iterator_tag, std::forward_iterator_tag> {typedef std::forward_iterator_tag type;}; template <> struct least_iterator_type<std::random_access_iterator_tag, std::bidirectional_iterator_tag> {typedef std::bidirectional_iterator_tag type;}; template <> struct least_iterator_type<std::random_access_iterator_tag, std::random_access_iterator_tag> {typedef std::random_access_iterator_tag type;}; // Base classes from which to inherit most functionality (++, etc). Overload as needed. // By specifying the type of iterator, only those functions that type supports will be // defined. // In order to inherit from this base class, a class must supply, at least, an m_cur // member and access() and advance() methods, as well as unadvance() if the class supports // backwards iteration. If the class supports random access it must support access(n). template <class Tag, class IterT, class value_type> class Iterator_base; template <class IterT, class value_type> // input iterator class Iterator_base<std::input_iterator_tag, IterT, value_type> { private: IterT* parent; public: Iterator_base() { parent = static_cast<IterT*>(this); } IterT& operator++() { parent->advance(); return *parent; } IterT operator++(int) { auto tmp = *parent; parent->advance(); return tmp;} value_type operator*() const { return parent->access(); } value_type* operator->() const { return &(parent->access()); } bool operator==(const IterT& r) const { return (parent->m_cur == r.m_cur); } bool operator!=(const IterT& r) const { return !(parent->operator==(r)); } }; // This provides nothing additional, but inherits from input_iterator template <class IterT, class value_type> // forward iterator class Iterator_base<std::forward_iterator_tag, IterT, value_type> : public Iterator_base<std::input_iterator_tag, IterT, value_type> {}; template <class IterT, class value_type> // bidirectional iterator class Iterator_base<std::bidirectional_iterator_tag, IterT, value_type> : public Iterator_base<std::input_iterator_tag, IterT, value_type> { private: IterT* parent; public: Iterator_base() { parent = static_cast<IterT*>(this); } IterT& operator--() { parent->unadvance(); return *parent; } IterT operator--(int) { auto tmp = *parent; parent->unadvance(); return tmp; } }; template <class IterT, class value_type> // random access iterator class Iterator_base<std::random_access_iterator_tag, IterT, value_type> : public Iterator_base<std::bidirectional_iterator_tag, IterT, value_type> { private: IterT* parent; public: Iterator_base() { parent = static_cast<IterT*>(this); } //typedef typename IterT::difference_type difference_type; // strictly speaking the below 'n's should be of type difference_type, but gcc complains IterT& operator+=(int n) { parent->m_cur += n; return *parent; } IterT operator+(int n) { auto tmp = *parent; tmp+=n; return tmp; } IterT& operator-=(int n) { parent->m_cur -= n; return *parent; } IterT operator-(int n) { auto tmp = *parent; tmp-=n; return tmp; } value_type operator[](int n) { return *(*parent+n); } bool operator<(const IterT& r) { return (parent->m_cur) < r.m_cur; } bool operator<=(const IterT& r) { return (parent->m_cur) <= r.m_cur; } bool operator>(const IterT& r) { return (parent->m_cur) > r.m_cur; } bool operator>=(const IterT& r) { return (parent->m_cur) >= r.m_cur; } }; // Overloading technique from Xeo: // http://stackoverflow.com/questions/257288/is-it-possible-to-write-a-c-template-to-check-for-a-functions-existence/9154394#9154394 template <class IterT> auto _get_base(IterT parent, int) -> decltype(parent.get_base()) { return parent.get_base(); } template <class IterT> IterT _get_base(IterT parent, long) { return parent; } // Used to provide the argument and return types of a unary function at compile time. // Technique from Xeo: // http://stackoverflow.com/a/8712212/1644272 template<class FPtr> struct function_traits; template<class R, class C, class A> struct function_traits<R (C::*)(A)> { // non-const specialization typedef A arg_type; typedef R result_type; }; template<class R, class C, class A> struct function_traits<R (C::*)(A) const> { // const specialization typedef A arg_type; typedef R result_type; }; } #endif
true
0c97ad4d6187c3ce293f95e5d83d6ff4368d5797
C++
vaderaparth22/OpenGL
/OpenGL3DTextureSkyBoxCity/src/main.cpp
UTF-8
12,266
2.796875
3
[]
no_license
#include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <GL/gl.h> #include <GL/glu.h> #include "Utils.h" #include "utils/sdlglutils.h" #include <vector> #include <time.h> #include <iostream> class Player { private: float posX; float posY; float posZ; public: void draw() { glPushMatrix(); glTranslatef(this->getPosX(),this->getPosY(),this->getPosZ()); glScaled(1,2,1); glBegin(GL_QUADS); glColor3ub(255, 0, 255); //face rouge glVertex3d(1, 1, 1); glVertex3d(1, 1, -1); glVertex3d(-1, 1, -1); glVertex3d(-1, 1, 1); glColor3ub(0, 255, 0); //face verte glVertex3d(1, -1, 1); glVertex3d(1, -1, -1); glVertex3d(1, 1, -1); glVertex3d(1, 1, 1); glColor3ub(0, 0, 255); //face bleue glVertex3d(-1, -1, 1); glVertex3d(-1, -1, -1); glVertex3d(1, -1, -1); glVertex3d(1, -1, 1); glColor3ub(120, 120, 120); //face jaune glVertex3d(-1, 1, 1); glVertex3d(-1, 1, -1); glVertex3d(-1, -1, -1); glVertex3d(-1, -1, 1); glColor3ub(120, 255, 120); //face cyan glVertex3d(1, 1, -1); glVertex3d(1, -1, -1); glVertex3d(-1, -1, -1); glVertex3d(-1, 1, -1); glColor3ub(255, 0, 255); //face magenta glVertex3d(1, -1, 1); glVertex3d(1, 1, 1); glVertex3d(-1, 1, 1); glVertex3d(-1, -1, 1); glEnd(); glPopMatrix(); } float getPosX() const { return posX; } void setPosX(float posX) { Player::posX = posX; } float getPosY() const { return posY; } void setPosY(float posY) { Player::posY = posY; } float getPosZ() const { return posZ; } void setPosZ(float posZ) { Player::posZ = posZ; } }; class Ground { private: float posX; float posY; float posZ; public: void draw(GLuint textureId) { //FLOOR glPushMatrix(); glTranslatef(0.0f,-5.0f,0.0f); glScalef(20.0f,0.0f,20.0f); setPosX(0.0f); setPosY(-5.0f); setPosZ(0.0f); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, textureId); glBegin(GL_QUADS); glColor3ub(255, 255, 255); glTexCoord2f(0.0, 0.0); glVertex3d(1, -2, -1); glTexCoord2f(1.0, 0); glVertex3d(1, -2, 1); glTexCoord2f(1.0, 1.0); glVertex3d(-1, -2,1); glTexCoord2f(0.0, 1.0); glVertex3d(-1, -2, -1); glEnd(); glDisable(GL_TEXTURE_2D); glPopMatrix(); } float getPosX() const { return posX; } void setPosX(float posX) { Ground::posX = posX; } float getPosY() const { return posY; } void setPosY(float posY) { Ground::posY = posY; } float getPosZ() const { return posZ; } void setPosZ(float posZ) { Ground::posZ = posZ; } }; class Box { private: float posX; float posY; float posZ; float gravityValue; public: float getPosX() const { return posX; } void setPosX(float posX) { Box::posX = posX; } float getPosY() const { return posY; } void setPosY(float posY) { Box::posY = posY; } float getPosZ() const { return posZ; } void setPosZ(float posZ) { Box::posZ = posZ; } float getGravityValue() const { return gravityValue; } void setGravityValue(float gravityValue) { Box::gravityValue = gravityValue; } void setRandomXZ() { float randomX = rand() % 19 + -19; float randomZ = rand() % 19 + -19; setPosX(randomX); setPosZ(randomZ); } void draw() { glPushMatrix(); glTranslatef(this->getPosX(),this->getPosY(),this->getPosZ()); glBegin(GL_QUADS); glColor3ub(255, 0, 0); //face rouge glVertex3d(1, 1, 1); glVertex3d(1, 1, -1); glVertex3d(-1, 1, -1); glVertex3d(-1, 1, 1); glColor3ub(0, 255, 0); //face verte glVertex3d(1, -1, 1); glVertex3d(1, -1, -1); glVertex3d(1, 1, -1); glVertex3d(1, 1, 1); glColor3ub(0, 0, 255); //face bleue glVertex3d(-1, -1, 1); glVertex3d(-1, -1, -1); glVertex3d(1, -1, -1); glVertex3d(1, -1, 1); glColor3ub(255, 255, 0); //face jaune glVertex3d(-1, 1, 1); glVertex3d(-1, 1, -1); glVertex3d(-1, -1, -1); glVertex3d(-1, -1, 1); glColor3ub(0, 255, 255); //face cyan glVertex3d(1, 1, -1); glVertex3d(1, -1, -1); glVertex3d(-1, -1, -1); glVertex3d(-1, 1, -1); glColor3ub(255, 0, 255); //face magenta glVertex3d(1, -1, 1); glVertex3d(1, 1, 1); glVertex3d(-1, 1, 1); glVertex3d(-1, -1, 1); glEnd(); glPopMatrix(); } void setGravity() { setPosY(getPosY() - getGravityValue()); } bool isColliding(Player player, Ground ground) { SDL_Rect myRect; myRect.x = getPosX(); myRect.y = getPosY(); myRect.w = 1; myRect.h = 1; SDL_Rect playerRect; playerRect.x = player.getPosX(); playerRect.y = player.getPosY(); playerRect.w = 2; playerRect.h = 5; SDL_Rect groundRect; groundRect.w = 20; groundRect.h = 2; groundRect.x = ground.getPosZ() + groundRect.w; groundRect.y = ground.getPosY() + groundRect.h; if(SDL_HasIntersection(&myRect, &playerRect) || SDL_HasIntersection(&myRect, &groundRect)) { return true; } return false; } }; SDL_Window* win; SDL_GLContext context; bool isRunning = true; float inputX = 0; float inputY = 0; int count = 0; bool isGameOver = false; std::vector<Box> boxes; static const Uint32 MS_PER_SECOND = 1000; static const int MAX_BOX_COLLISION_COUNT = 5; void drawSkybox() { //Dessin SkyBox // glBindTexture(GL_TEXTURE_2D, idTextureSkyBox); // glBegin(GL_QUADS); // // glColor3ub(255, 255, 255); // glTexCoord2d(.75,.66); glVertex3d(75, 75, 75); // glTexCoord2d(.75,.33); glVertex3d(75, 75, -75); // glTexCoord2d(1, .33); glVertex3d(-75, 75, -75); // glTexCoord2d(1,.66); glVertex3d(-75, 75, 75); // // // glTexCoord2d(0,.66);glVertex3d(75, -75, 75); // glTexCoord2d(0,.33);glVertex3d(75, -75, -75); // glTexCoord2d(.25,.33);glVertex3d(75, 75, -75); // glTexCoord2d(.25,.66);glVertex3d(75, 75, 75); // //// glColor3ub(0, 0, 255); //face bleue // glTexCoord2d(0.25,.66);glVertex3d(-75, -75, 75); // glTexCoord2d(0.25,.33);glVertex3d(-75, -75, -75); // glTexCoord2d(0.5,.33);glVertex3d(75, -75, -75); // glTexCoord2d(0.5,.66);glVertex3d(75, -75, 75); // //// glColor3ub(255, 255, 0); //face jaune // glTexCoord2d(0.5,.66);glVertex3d(-75, 75, 75); // glTexCoord2d(0.5,.33);glVertex3d(-75, 75, -75); // glTexCoord2d(0.75,.33);glVertex3d(-75, -75, -75); // glTexCoord2d(0.75,.66);glVertex3d(-75, -75, 75); // //// glColor3ub(0, 255, 255); //face cyan // glTexCoord2d(0.25,.33);glVertex3d(75, 75, -75); // glTexCoord2d(0.25,0);glVertex3d(75, -75, -75); // glTexCoord2d(0.5,0);glVertex3d(-75, -75, -75); // glTexCoord2d(0.5,.33);glVertex3d(-75, 75, -75); // //// glColor3ub(255, 0, 255); //face magenta // glTexCoord2d(0.25,1);glVertex3d(75, -75, 75); // glTexCoord2d(0.25,.66);glVertex3d(75, 75, 75); // glTexCoord2d(0.5,.66);glVertex3d(-75, 75, 75); // glTexCoord2d(0.5,1);glVertex3d(-75, -75, 75); // // glEnd(); } void drawUpperFloor(GLuint textureId) { //FLOOR glPushMatrix(); glTranslatef(0.0f,20.0f,0.0f); glScalef(20.0f,0.0f,20.0f); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, textureId); glBegin(GL_QUADS); glColor3ub(255, 255, 255); glTexCoord2f(0.0, 0.0); glVertex3d(1, -2, -1); glTexCoord2f(1.0, 0); glVertex3d(1, -2, 1); glTexCoord2f(1.0, 1.0); glVertex3d(-1, -2,1); glTexCoord2f(0.0, 1.0); glVertex3d(-1, -2, -1); glEnd(); glDisable(GL_TEXTURE_2D); glPopMatrix(); } void spawnBox() { Box box; box.setPosY(15.0f); box.setRandomXZ(); float g = (rand()) / ( static_cast <float> (RAND_MAX/(0.5 - 0.2))); box.setGravityValue(g); boxes.push_back(box); } void drawBoxes(Player player, Ground ground) { if(!boxes.empty()) { for (int i = 0; i < boxes.size(); ++i) { boxes[i].setGravity(); boxes[i].draw(); if(boxes[i].isColliding(player, ground)) { count++; std::cout << "Boxes hit : " << count << std::endl; boxes.erase(boxes.begin() + i); } } } } int main(int argc, char** argv) { SDL_Init(SDL_INIT_VIDEO); IMG_Init(IMG_INIT_JPG|IMG_INIT_PNG); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); win = SDL_CreateWindow("OpenGl Test", SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED, 1280, 720, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN); SDL_GLContext context = SDL_GL_CreateContext(win); srand(time(NULL)); inputX = 0; inputY = 0; Uint32 timer = 0; Uint32 previousTime = SDL_GetTicks(); Uint32 currentTime = SDL_GetTicks(); Uint32 deltaTime; Uint32 randomSpawnTime = 6000; GLuint idTextureSol = loadTexture("assets/img/herbe.jpg"); GLuint idTextureSol2 = loadTexture("assets/img/sol.jpg"); GLuint idTextureSkyBox = loadTexture("assets/img/skybox.jpg"); Player player; Ground ground; glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(70, (double) 1280 / 720, 1, 1000); glEnable(GL_DEPTH_TEST); glEnable(GL_TEXTURE_2D); SDL_Event event; const Uint8* states = nullptr; while (isRunning) { currentTime = SDL_GetTicks(); deltaTime = currentTime - previousTime; if (deltaTime == 0) { deltaTime = MS_PER_SECOND; } previousTime = currentTime; glClearColor(0.f, 0.5f, 1.0f, 1.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslated(0,-3,30); gluLookAt(-50, 10, -50, 0, 0, 0, 0, 1, 0); SDL_PollEvent(&event); states = SDL_GetKeyboardState(NULL); if (event.type == SDL_QUIT) isRunning = false; if (states[SDL_SCANCODE_LEFT]) { if(player.getPosX() < 19) inputX += .5; } if (states[SDL_SCANCODE_RIGHT]) { if(player.getPosX() > -19) inputX -= .5; } if (states[SDL_SCANCODE_UP]) { if(player.getPosZ() < 19) inputY += .5; } if (states[SDL_SCANCODE_DOWN]) { if(player.getPosZ() > -19) inputY -= .5; } player.setPosX(inputX); player.setPosY(-3.0); player.setPosZ(inputY); player.draw(); //drawPyramid(); ground.draw(idTextureSol); drawUpperFloor(idTextureSol2); drawBoxes(player,ground); if(!isGameOver) { timer += deltaTime; if(timer >= 3000) { spawnBox(); //randomSpawnTime = (rand() % 5000) + 1000; timer -= 3000; } if(count >= MAX_BOX_COLLISION_COUNT) { isGameOver = true; std::cout << "GAME OVER!" << std::endl; } } SDL_Delay(3); glFlush(); SDL_GL_SwapWindow(win); } glDeleteTextures(1, &idTextureSol); glDeleteTextures(1, &idTextureSkyBox); SDL_GL_DeleteContext(context); SDL_DestroyWindow(win); IMG_Quit(); SDL_Quit(); return 0; }
true
62f94329a094c9c111be91039d8bd822767239e8
C++
lyapple2008/CPlusPlusConcurrencyInAction
/Chapter03/example01/main.cc
UTF-8
668
3.671875
4
[]
no_license
#include <list> #include <mutex> #include <algorithm> #include <thread> #include <iostream> std::list<int> some_list; // 1 std::mutex some_mutex; // 2 void add_to_list(int new_value) { std::lock_guard<std::mutex> guard(some_mutex); // 3 some_list.push_back(new_value); } bool list_contains(int value_to_find) { std::lock_guard<std::mutex> guard(some_mutex); // 4 return std::find(some_list.begin(),some_list.end(),value_to_find) != some_list.end(); } int main(int argc, char* argv[]) { std::thread t(add_to_list, 1); t.join(); if (list_contains(1)) { std::cout << "main-thread: contain" << std::endl; } return 0; }
true
6b99b2c85ddf5542ed7b71f5eb0bce1727bda0eb
C++
CSEKU160212/C_Programming_And_Data_Structure
/Data Structure/OneDimensionalArray/main.cpp
UTF-8
1,618
3.4375
3
[]
no_license
#include <bits/stdc++.h> #define n 10 #define m 5 using namespace std; int main() { // data Storing..... int A[n]; cout<<"Enter the value:"<<endl; for(int i=0; i<n; i++) { cin>>A[i]; } // print the Array for(int i=0; i<n; i++) { cout<<A[i]<<" "; } cout<<endl<<endl; // marge two array int B[m] = {1, 2, 5, 8, 55}; int X[m+n]; // new array for(int i=0; i<n; i++) X[i]= A[i]; for(int i=0; i<n; i++) X[i+n]=B[i]; cout<<"Updated Array: "; for(int i=0; i< m+n; i++) cout<<X[i]<<" "; cout<<endl<<endl; // searching data from array int val; cout<<"Enter the data to be searched: "; cin>>val; int found=0; int location=0; for(int i=0; i<n+m ; i++) if(val == X[i]) { found=1; location= i+1; break; } if(found==1) cout<<"Value Found"<<endl<<endl; else cout<<"Value Not Found"<<endl<<endl; // Maximum & minimum int max=X[0], min=X[0]; for(int i=1; i<n+m; i++) { if(max<X[i]) { max=X[i]; } if(min>X[i]) { min=X[i]; } } cout<<"Maximum Value= "<<max<<endl<<"Minimum Value= "<<min<<endl<<endl; // delete a value of n position cout<<"Enter the position to be deleted: "; int N; cin>>N; for(int i=N-1; i<n+m-1; i++) { X[i]=X[i+1]; } cout<<"After deleted the array is: "<<endl; for(int i=0; i<n+m-1; i++) cout<<X[i]<<" "; return 0; }
true
ccde4bdec4da830133db06bb24377ae66fd94f9b
C++
filipecn/helios
/helios/core/filter.h
UTF-8
6,996
2.609375
3
[ "MIT" ]
permissive
/// Copyright (c) 2021, FilipeCN. /// /// The MIT License (MIT) /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to /// deal in the Software without restriction, including without limitation the /// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or /// sell copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING /// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS /// IN THE SOFTWARE. /// ///\file core/filter.h ///\author FilipeCN (filipedecn@gmail.com) ///\date 2021-07-07 /// ///\brief #ifndef HELIOS_CORE_FILTER_H #define HELIOS_CORE_FILTER_H #include <hermes/geometry/point.h> namespace helios { // ********************************************************************************************************************* // Filter // ********************************************************************************************************************* /// Base class for implementation of various types of filter functions. class Filter { public: // ******************************************************************************************************************* // CONSTRUCTORS // ******************************************************************************************************************* HERMES_DEVICE_CALLABLE Filter(); /// The components of **radius_** define points in the axis where the function /// is zero beyond. These points go to each direction, the overall extent /// in each direction (called support) is **twice** those values. /// \param radius filter extents HERMES_DEVICE_CALLABLE explicit Filter(const hermes::vec2 &radius); /// Evaluates this filter function at **p** /// \param p sample point relative to the center of the filter /// \return real_t filter's value [[nodiscard]] HERMES_DEVICE_CALLABLE virtual real_t evaluate(const hermes::point2 &p) const = 0; // ******************************************************************************************************************* // PUBLIC FIELDS // ******************************************************************************************************************* const hermes::vec2 radius{}; //!< filter's radius_ of support const hermes::vec2 inv_radius{}; //!< reciprocal of radius_ }; // ********************************************************************************************************************* // PreComputedFilter // ********************************************************************************************************************* /// Stores a table of pre-computed weights for a given filter /// \note Generally, every image sample contributes to 16 pixels in the final image (TABLE_WIDTH = 16). template<size_t TABLE_WIDTH> class PreComputedFilter { public: PreComputedFilter() { for (int y = 0, offset = 0; y < filter_table_width; ++y) for (int x = 0; x < filter_table_width; ++x, ++offset) table[offset] = 1; } explicit PreComputedFilter(const Filter *filter) : radius{filter->radius}, inv_radius{filter->inv_radius} { // precompute filter weight table for (int y = 0, offset = 0; y < filter_table_width; ++y) for (int x = 0; x < filter_table_width; ++x, ++offset) { hermes::point2 p((x + 0.5f) * filter->radius.x / filter_table_width, (y + 0.5f) * filter->radius.y / filter_table_width); table[offset] = filter->evaluate(p); } } // ******************************************************************************************************************* // PUBLIC FIELDS // ******************************************************************************************************************* static constexpr int filter_table_width = TABLE_WIDTH; real_t table[TABLE_WIDTH * TABLE_WIDTH]{}; //!< precomputed table for filter values //!< to save computations of filter's //!< evaluate method. f = f(|x|, |y|) const hermes::vec2 radius; //!< filter's radius_ of support const hermes::vec2 inv_radius; //!< reciprocal of radius_ }; // ********************************************************************************************************************* // Box Filter // ********************************************************************************************************************* /// Equally weights all samples within a square region of the image. /// Can cause post-aliasing even when the original image's frequencies /// respect the Nyquist limit. class BoxFilter : public Filter { public: // ******************************************************************************************************************* // CONSTRUCTORS // ******************************************************************************************************************* HERMES_DEVICE_CALLABLE BoxFilter(); HERMES_DEVICE_CALLABLE explicit BoxFilter(const hermes::vec2 &radius); // ******************************************************************************************************************* // INTERFACE // ******************************************************************************************************************* [[nodiscard]] HERMES_DEVICE_CALLABLE real_t evaluate(const hermes::point2 &p) const override; }; } // namespace helios #endif // HELIOS_CORE_FILTER_H
true
57e8a1b0916fb41a8fce06c3dcc759446adde8d3
C++
EliasFloresPerez/Proyectos-C
/recurso.cpp
UTF-8
212
3.109375
3
[]
no_license
#include <iostream> using namespace std; int funcion(int x){ if(x==0){ cout<<x+1<<"+"; return 1; } cout<<x<<"+"; return x + funcion(x-1); } int main(){ cout<<endl; cout<<funcion(5); return 0; }
true
5cbc6705e3630530e5249c502b10566600b4afff
C++
mleonardallen/CarND-Unscented-Kalman-Filter-Project
/src/main.cpp
UTF-8
3,848
2.578125
3
[]
no_license
#include <iostream> #include <fstream> #include <vector> #include <stdlib.h> #include "Eigen/Dense" #include "ukf.h" #include "tools.h" #include "measurement_package.h" using namespace std; using Eigen::VectorXd; void check_arguments(int argc, char* argv[]) { string usage_instructions = "Usage instructions: "; usage_instructions += argv[0]; usage_instructions += " path/to/input.txt output.txt"; bool has_valid_args = false; // make sure the user has provided input and output files if (argc == 1) { cerr << usage_instructions << endl; } else if (argc == 2) { cerr << "Please include an output file.\n" << usage_instructions << endl; } else if (argc == 3 || argc == 4) { // 3rd parameter is for measurement type has_valid_args = true; } else if (argc > 4) { cerr << "Too many arguments.\n" << usage_instructions << endl; } if (!has_valid_args) { exit(EXIT_FAILURE); } } void check_files(ifstream& in_file, string& in_name, ofstream& out_file, string& out_name) { if (!in_file.is_open()) { cerr << "Cannot open input file: " << in_name << endl; exit(EXIT_FAILURE); } if (!out_file.is_open()) { cerr << "Cannot open output file: " << out_name << endl; exit(EXIT_FAILURE); } } int main(int argc, char* argv[]) { check_arguments(argc, argv); string in_file_name_ = argv[1]; ifstream in_file_(in_file_name_.c_str(), ifstream::in); string out_file_name_ = argv[2]; ofstream out_file_(out_file_name_.c_str(), ofstream::out); // measurement type argument int measurement_type = MeasurementPackage::BOTH; if (argc == 4) { std::istringstream iss(argv[3]); iss >> measurement_type; } check_files(in_file_, in_file_name_, out_file_, out_file_name_); /********************************************** * Set Measurements * **********************************************/ UKF ukf; MeasurementPackage *meas_package; VectorXd estimation; VectorXd measurement; VectorXd gt_values; string line; // used to compute the RMSE later vector<VectorXd> estimations; vector<VectorXd> ground_truth; while (getline(in_file_, line)) { // Create measurement package from sensor data meas_package = MeasurementPackage::create(line); measurement = meas_package->getCartesianMeasurement(); // Filter out measurement types other than passed in type. // LIDAR = 1, RADAR = 2 if (measurement_type != MeasurementPackage::BOTH and meas_package->sensor_type_ != measurement_type ) { continue; } gt_values = meas_package->getGroundTruth(); // Call the UKF-based fusion estimation = ukf.ProcessMeasurement(meas_package); // Output estimation and measurements out_file_ << estimation(0) << "\t"; // px out_file_ << estimation(1) << "\t"; // py out_file_ << estimation(2) << "\t"; // vel_abs out_file_ << estimation(3) << "\t"; // yaw_angle out_file_ << estimation(4) << "\t"; // yaw_rate out_file_ << measurement(0) << "\t"; // px out_file_ << measurement(1) << "\t"; // py // output the ground truth packages out_file_ << gt_values(0) << "\t"; // px out_file_ << gt_values(1) << "\t"; // py out_file_ << gt_values(2) << "\t"; // vx out_file_ << gt_values(3) << "\t"; // vy out_file_ << ukf.getNIS() << "\t"; // NIS out_file_ << "\n"; // Used to calculate RMSE estimations.push_back(ukf.getCartesianEstimate()); ground_truth.push_back(gt_values); } // compute the accuracy (RMSE) Tools tools; cout << "Accuracy - RMSE:" << endl << tools.CalculateRMSE(estimations, ground_truth) << endl; // close files if (out_file_.is_open()) { out_file_.close(); } if (in_file_.is_open()) { in_file_.close(); } cout << "Done!" << endl; return 0; }
true
6324a6e512df8df26b76ee83893e09430750df6f
C++
WDMdanila/sgg-os
/src/Ports/Port8Bit.cpp
UTF-8
581
2.671875
3
[]
no_license
#include "Ports/Port8Bit.h" Port8Bit::Port8Bit(uint16_t number) : Port(number) {} Port8Bit::~Port8Bit() {} void Port8Bit::write(uint8_t data) { __asm__ volatile("outb %0, %1": :"a"(data), "Nd" (number)); } uint8_t Port8Bit::read() { uint8_t result; __asm__ volatile("inb %1, %0": "=a" (result) : "Nd" (number)); return result; } Port8BitSlow::Port8BitSlow(uint16_t number) : Port8Bit(number) {} Port8BitSlow::~Port8BitSlow() {} void Port8BitSlow::write(uint8_t data) { __asm__ volatile("outb %0, %1\njmp 1f\n1: jmp 1f\n1:": :"a"(data), "Nd" (number)); }
true
88650b4c69b7d4e73591b603ee542be2ce459413
C++
forceframe/c-
/Over-grade.cpp
UTF-8
1,408
3.375
3
[]
no_license
#include <iostream> #include <string> using namespace std; template<typename T> void swap(T d[], int x, int y){ T temp = d[x]; d[x] = d[y]; d[y] = temp; } template<typename T1, typename T2> void moveMax2End(T1 d[], T2 v[], int e){ for(int i = 0; i < e-1; i++){ if(d[i] > d[i+1]){ swap(d,i,i+1); swap(v,i,i+1); } } } template <typename T1, typename T2> void bubbleSort(T1 d[], T2 v[], int N){ for(int end = N; end > 1; end--){ moveMax2End(d,v,end); } } template <typename T> int binarySearch(T data[], int N, T key){ int first = 0, last = N-1, mid; do{ mid = (first+last)/2; if(data[mid] == key) return mid; else if(data[mid] > key) last = mid-1; else first = mid+1; }while(first <= last); return -1; } int main(){ unsigned int StudentID[] = {600610787,600610780,600610749,600612161,600610717,600612147,600610727,600610744,600610767.600610781,600610726,600610720,600610777}; string grade102[] = {"F","D","D+","W","D","W","F","D+","W","F","D+","F+","D"}; int N =sizeof(StudentID)/sizeof(StudentID[0]); unsigned int key; cout << "Input Student ID to search: "; cin >> key; bubbleSort(StudentID,grade102,N); int loc = binarySearch(StudentID,N,key); if(loc == -1) cout << "Student ID " << key << "was not found"; else cout << "Student ID " << key << " got " << grade102[loc] << " in 261102"; return 0; }
true
3612d61a979c94cf9d2468751db7ef205e60cf9b
C++
LuhJunior/ody-unplugged-framework
/src/Modelo/Menu.hpp
UTF-8
544
2.625
3
[]
no_license
#ifndef MENU_H #define MENU_H #include "../Interface/Console.hpp" #include "Facede.hpp" class Menu { public: Menu () {} Menu (string nickname) { this->console = Console(); this->facede = Facede(nickname); } Menu (Facede facede) { this->console = Console(); this->facede = facede; } void getPlayerInfo(); void displayMenu(); int getOption(); void command(); void init(); bool loadPlayerMenu(string); private: Console console; Facede facede; }; #endif // MENU_H
true
8fac8c384cce3d7493c53fdc8fda9cfe0cec26b2
C++
OriaTori/PizzaOrders
/src/OrderSystem.h
UTF-8
1,006
2.953125
3
[]
no_license
#pragma once #include "Pizzeria.h" #include "Pizza.h" #include "Margherita.h" #include "Funghi.h" enum Pizzerias { VENEZIA = 0, BRAVO, GRINDTORP }; enum PaymentMethod { PAY_PAL, CREDIT_CARD, DOTPAY, CASH }; class OrderSystem { public: static OrderSystem& instance(); OrderSystem(OrderSystem const &) = delete; OrderSystem& operator=(OrderSystem const &) = delete; bool makeOrder(Pizzas pizzas, std::string deliveryAddress); void selectPizzeria(Pizzerias p); bool charge(double price); void selectPaymentMethod(PaymentMethod pm); private: ~OrderSystem() = default; OrderSystem() = default; static OrderSystem* instance_; Pizzeria* selected_; int paymentMethod_; Pizzeria venezia_{"Venezia - real Italian pizza", {new Funghi{100.0}}}; Pizzeria bravo_{"Bravo - good and cheap pizza", {new Margherita{80.0}}}; Pizzeria grindtorp_{"Grindtorp pizzeria - local pizza", {new Margherita{90.0}, new Funghi{110.0}}}; };
true
44b45bf263d753c06f7505fc3f594452e561d0f6
C++
15831944/CNCMachinSimulator
/src/parserXML/exceptionParserXML.h
UTF-8
1,128
2.65625
3
[]
no_license
#ifndef EXCEPTIONPARSERXML_H_ #define EXCEPTIONPARSERXML_H_ #include <stdexcept> #include <exception> #include <string> namespace parserXML { class ExceptionParserXML : public std::exception { private: std::string m_Msg; public: ExceptionParserXML(const std::string &msg) : m_Msg("ExceptionParserXML::" + msg) { } const char* what() const noexcept { return m_Msg.c_str(); } }; class SmartBufferException : public ExceptionParserXML { public: SmartBufferException(const std::string &msg) : ExceptionParserXML("SmartBufferException::" + msg) { } }; class LexerXMLException : public ExceptionParserXML { public: LexerXMLException(const std::string &msg) : ExceptionParserXML("LexerXMLException::" + msg) { } }; class ParserXMLException : public ExceptionParserXML { public: ParserXMLException(const std::string &msg) : ExceptionParserXML("ParserXMLException::" + msg) { } }; class TreeElementXMLException : public ExceptionParserXML { public: TreeElementXMLException(const std::string &msg) : ExceptionParserXML("TreeElementXMLException::" + msg) { } }; } #endif // EXCEPTIONPARSERXML_H_
true
82e4d820c38699f313b1d14b94fcc708252c8d2e
C++
abnermneves/alg1
/tp1/program/main.cpp
UTF-8
1,197
2.984375
3
[]
no_license
#include <iostream> #include <fstream> #include <string> #include "vertice.h" #include "grafo.h" int main(int argc, char* argv[]){ unsigned int n, m, k, a, b; char c; Vertice* v; Grafo* g = new Grafo(); //se foi executado com um parâmetro, lê do arquivo if (argc == 2){ std::string line, fname; fname = argv[1]; std::ifstream file(fname); if (file.is_open()){ file >> n >> m >> k; //lê os n vértices for (unsigned int i = 0; i < n; i++){ file >> a; v = new Vertice(i+1, a); g->addVertice(v); } //lê as m arestas for (unsigned int i = 0; i < m; i++){ file >> a >> b; g->addAresta(a, b); } //lê as k instruções for (unsigned int i = 0; i < k; i++){ file >> c; switch(c){ case 'S': file >> a >> b; g->swap(a, b); break; case 'C': file >> a; g->commander(a); break; case 'M': g->meeting(); break; } } file.close(); } } return 0; }
true
bc99814da2c581c9f4f75578950c1a2ca616cd86
C++
yssource/cli
/cli/name-processor.cxx
UTF-8
4,018
2.75
3
[ "MIT" ]
permissive
// file : cli/name-processor.cxx // author : Boris Kolpackov <boris@codesynthesis.com> // copyright : Copyright (c) 2009-2011 Code Synthesis Tools CC // license : MIT; see accompanying LICENSE file #include <set> #include <sstream> #include "context.hxx" #include "name-processor.hxx" using namespace std; namespace { typedef set<string> name_set; typedef ::context context_base; struct context: context_base { context (context_base& c): context_base (c) {} context (context& c): context_base (c) {} public: string find_name (string const& n, string const& suffix, name_set& set) { string name (escape (n + suffix)); for (size_t i (1); set.find (name) != set.end (); ++i) { ostringstream os; os << i; name = escape (n + os.str () + suffix); } set.insert (name); return name; } string find_name (string const& n, name_set& set) { return find_name (n, "", set); } }; struct primary_option: traversal::option, context { primary_option (context& c, name_set& set) : context (c), set_ (set) { } virtual void traverse (type& o) { string n (o.name ()), name; // Get rid of leading special characters, e.f., -, --, /, etc. // for (size_t i (0); i < n.size (); ++i) { if (isalpha (n[i]) || n[i] == '_') { name.assign (n.c_str (), i, n.size () - i); break; } } o.context ().set ("name", find_name (name, set_)); } private: name_set& set_; }; struct intermediate_option: traversal::option, context { intermediate_option (context& c, name_set& set) : context (c), set_ (set) { } virtual void traverse (type& o) { if (specifier && o.type ().name () != "bool") { semantics::context& oc (o.context ()); string const& base (oc.get<string> ("name")); oc.set ("specifier", find_name (base + "_specified", set_)); } } private: name_set& set_; }; struct secondary_option: traversal::option, context { secondary_option (context& c, name_set& set) : context (c), set_ (set) { } virtual void traverse (type& o) { semantics::context& oc (o.context ()); string const& base (oc.get<string> ("name")); oc.set ("member", find_name (base + "_", set_)); if (specifier && o.type ().name () != "bool") { string const& base (oc.get<string> ("specifier")); oc.set ("specifier-member", find_name (base + "_", set_)); } } private: name_set& set_; }; struct class_: traversal::class_, context { class_ (context& c) : context (c) {} virtual void traverse (type& c) { semantics::context& cc (c.context ()); cc.set ("member-name-set", name_set ()); name_set& member_set (cc.get<name_set> ("member-name-set")); member_set.insert (escape (c.name ())); // First assign primary names. // { primary_option option (*this, member_set); traversal::names names (option); class_::names (c, names); } // Then assign intermediate names. // { intermediate_option option (*this, member_set); traversal::names names (option); class_::names (c, names); } // Finally assign secondary names. // { secondary_option option (*this, member_set); traversal::names names (option); class_::names (c, names); } } }; void process_names_ (context_base& c) { context ctx (c); traversal::cli_unit unit; traversal::names unit_names; traversal::namespace_ ns; class_ cl (ctx); unit >> unit_names >> ns; unit_names >> cl; traversal::names ns_names; ns >> ns_names >> ns; ns_names >> cl; unit.dispatch (ctx.unit); } } void process_names (context_base& c) { process_names_ (c); }
true
2708e02db03fa8af52d76748e565d23c9536d283
C++
nzaouesgi/DonkeyKong-SFML
/Camera.cpp
UTF-8
571
2.765625
3
[]
no_license
#include "pch.h" #include "Camera.h" Camera::Camera(sf::View view){ this->view = view; } Camera::~Camera(){} sf::View Camera::updatePosition(sf::Vector2f mapBorders, float playerXPosition){ this->view.setCenter(playerXPosition, this->view.getCenter().y); sf::Vector2f size = this->view.getSize(); if ((playerXPosition - (size.x / 2)) <= 0) { this->view.move(-(playerXPosition - (size.x / 2)), 0); } else if (playerXPosition + (size.x / 2) >= mapBorders.x) { this->view.move(-(playerXPosition + (size.x / 2) - mapBorders.x), 0); } return this->view; }
true
36c7d82281cf0981c1adbaef66274c737034df72
C++
ChoiHeon/algorithm
/02_백준/[15988] 1, 2, 3 더하기.cpp
UTF-8
641
2.625
3
[]
no_license
// https://www.acmicpc.net/problem/9095 #include <iostream> #include <string> #include <algorithm> #include <cstring> using namespace std; int cache[11]; int solution(int n) { memset(cache, 0, sizeof(cache)); cache[0] = 1; for (int i = 1; i <= n; i++) { for (int k = 1; k <= 3; k++) { if (i < k) break; cache[i] += cache[i - k]; } } for (int j = 0; j <= n; j++) cout << cache[j] << ' '; cout << endl; return cache[n]; } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t, n; cin >> t; for (int i = 0; i < t; i++) { cin >> n; cout << solution(n) << endl; } return 0; }
true
def89d9fee2ad5a134f263ab599005f22a26a5e2
C++
ajitesh22/Coding-Problems
/climbing-stairs.cpp
UTF-8
545
3.1875
3
[]
no_license
//https://leetcode.com/problems/climbing-stairs/submissions/ class Solution { public int climbStairs(int n) { Integer oneStepBack = 2; Integer twoStepBack = 1; Integer currSteps = 0; if(n==1) return twoStepBack; if(n==2) return oneStepBack; for(int i=3;i<=n;i++){ currSteps = oneStepBack + twoStepBack; twoStepBack = oneStepBack; oneStepBack = currSteps; } return currSteps; } } /* 1 2 3 4 5*/
true
f52bdeaac399417e6a3cd9d1c8b30695ecb003f7
C++
KSXGitHub/school-practices
/algorithm-and-data-structures/1.17.hpp
UTF-8
1,082
3.5
4
[]
no_license
// Lưu ý: // * Đây là một file *.hpp, không phải *.cpp nên không thể dịch tạo file *.exe để chạy được #include <iostream> using namespace std; /* TYPES AND CLASSES */ typedef int Data; struct Node; struct Stack; struct Node { Data data; Node *next; }; struct Stack { Node *head; }; /* FUNCTION PROTOTYPES */ Node *createNode(Data, Node * = NULL); void push(Stack &, Data); bool pop(Stack &, Data &); void clear(Stack &); /* FUNCTION DEFINITIONS */ Node *createNode(Data data, Node *next) { Node *node = new Node(); *node = {data, next}; return node; } void push(Stack &stack, Data data) { stack.head = createNode(data, stack.head); } bool pop(Stack &stack, Data &data) { if (stack.head) { Node *node = stack.head; data = node->data; stack.head = node->next; delete node; return true; } return false; } void clear(Stack &stack) { Node *node = stack.head; while (node) { Node *next = node->next; delete node; node = next; } }
true
41bee90665d1feec4e1a091538c261386c31c75c
C++
fromasmtodisasm/parasol
/prslc/Lexer.cpp
UTF-8
2,287
2.765625
3
[ "BSD-2-Clause" ]
permissive
// // Created by ARJ on 9/5/15. // #include "Lexer.h" namespace prsl { using std::get; SymbolToken _symbolTokens[] = { SymbolToken(',', COMMA), SymbolToken('{', L_CURLY), SymbolToken('}', R_CURLY), SymbolToken(']', R_BRACKET), SymbolToken('(', L_PAREN), SymbolToken(')', R_PAREN), SymbolToken(':', COLON), SymbolToken('+', PLUS), SymbolToken('-', MINUS), SymbolToken('/', DIV), SymbolToken('\\', LAMBDA), SymbolToken('@', ARRAY) }; size_t _nSymbols = sizeof(_symbolTokens) / sizeof(SymbolToken); DigraphToken _digraphTokens[] = { DigraphToken('*', MULT, '.', DOT), DigraphToken('=', EQUALS, '>', GOESTO), DigraphToken('=', EQUALS, '=', EQ), DigraphToken('&', B_AND, '&', L_AND), DigraphToken('|', B_OR, '|', L_OR), DigraphToken('!', NOT, '=', NOT_EQ), DigraphToken('<', LESS, '=', LESS_EQ), DigraphToken('>', GREATER, '=', GREATER_EQ), DigraphToken('.', SWIZZLE, '.', SEQUENCE) }; size_t _nDigraphs = sizeof(_digraphTokens) / sizeof(DigraphToken); KeywordToken _keywordTokens[] = { KeywordToken("def", DEF), KeywordToken("let", LET), KeywordToken("in", IN), KeywordToken("struct", STRUCT), KeywordToken("include", INCLUDE), KeywordToken("as", AS) }; size_t _nKeywords = sizeof(_keywordTokens) / sizeof(KeywordToken); size_t StringTable::pushString(std::string const &s) { PrevMap::iterator it = previousLocations.find(s); if (it != previousLocations.end()){ return (*it).second; } size_t idx = strings.size(); previousLocations.emplace(s, idx); strings.push_back(s); return idx; } std::string const &StringTable::getString(size_t index) { return strings[index]; } std::string lookupToken(int token) { std::string retval; for (size_t i = 0; i < _nSymbols; i++){ if (token == get<1>(_symbolTokens[i])){ retval.push_back(get<0>(_symbolTokens[i])); return retval; } } for (size_t i = 0; i < _nDigraphs; i++){ if (token == get<1>(_digraphTokens[i])){ retval.push_back(get<0>(_digraphTokens[i])); return retval; } else if (token == get<3>(_digraphTokens[i])){ retval.push_back(get<0>(_digraphTokens[i])); retval.push_back(get<2>(_digraphTokens[i])); return retval; } } for (size_t i = 0; i < _nKeywords; i++){ if (token == get<1>(_keywordTokens[i])){ return get<0>(_keywordTokens[i]); } } } }
true
99c25772ce2731782fd559073235f3be70a27a57
C++
nguyenhoangvannha/01_Study_CPlusPlus
/TongHopCcode/so hoan thien.cpp
UTF-8
367
2.578125
3
[]
no_license
#include "stdio.h" #include "conio.h" #include "math.h" #include "stdlib.h" int KT_SHT(int n) { int s=0, i=1; for (i = 1; i < n;i++) if (n%i == 0) s += i; if (s <= n) return 1; else return 0; } void main() { int n; printf("\n Nhap n: "); scanf_s("%d", &n); for (int i = 1; i <= n; i++) if (KT_SHT(i) == 1) printf(" so hoan thien la %d \n", i); _getch(); }
true
cb7e3fb92316c43600f806dce9501b025a6a3211
C++
wovo/2017-berlin
/blink-templates/pin.hpp
UTF-8
280
2.625
3
[]
no_license
#include "stm32f103x6.h" GPIO_TypeDef * port_registers[] = { GPIOA, GPIOB, GPIOC, GPIOD }; template< int port, int pin > class gpio { public: static void set( bool value ){ port_registers[ port ]->BSRR = 0x01 << ( ( pin % 16 ) + ( value ? 0 : 16 ) ); } };
true
8e154f77b779cf49a41db05da1205cc1625e4fcf
C++
akavasis/ray-tracing-from-the-ground-up
/source/Light/PointLight.hpp
UTF-8
559
2.515625
3
[ "MIT" ]
permissive
#pragma once #include "Ambient.hpp" class PointLight: public Ambient{ public: PointLight(Vector3D location = Vector3D(0), float ls_ = 1.0, RGBColor color_ = 1.0, bool shadows_ = false); PointLight(PointLight& point); Vector3D get_location() const; void set_location(const Vector3D location_); void set_location(const float x, const float y, const float z); Vector3D get_direction(ShadeRec& sr); RGBColor L(ShadeRec& sr); virtual bool in_shadow(const Ray& ray, const ShadeRec& sr) const; private: Vector3D location; };
true
b0965767af449542174a39e304c065aa895afa07
C++
LeonardoPalchetti/LSN_LeonardoPalchetti
/Exercises_01/Es01/main.cpp
UTF-8
3,907
2.953125
3
[]
no_license
#include <iostream> #include "random.h" #include <fstream> #include <cmath> using namespace std; double error(double, double, int); //funzione calcolo errore int main(){ int M = 10000; //numero totale di tiri int N = 100; //numero di blocchi int L = M/N; // numero di tiri in ogni blocco double n[M]; //def n := array di numeri random [0,1] double av[M], av2[M]; //array delle misure, e del rispettivo quadrato per i blocchi double sv[M], sv2[M]; //array delle varianze delle misure, e del rispettivo quadrato per i blocchi double av_prog[M], av2_prog[M], err[M]; //medie progressive dei tiri e rispettivo errore double sv_prog[M], sv2_prog[M], serr[M]; //medie progressive della varianza dei tiri e rispettivo errore double sum, sums; fstream output; Random rnd; int seed[4]; //preparo il generatore di numeri random int p1, p2; ifstream Primes("Primes"); if (Primes.is_open()){ Primes >> p1 >> p2 ; }else cerr << "PROBLEM: Unable to open Primes" << endl; Primes.close(); ifstream input("seed.in"); string property; if (input.is_open()){ while ( !input.eof() ){ input >> property; if( property == "RANDOMSEED" ){ input >> seed[0] >> seed[1] >> seed[2] >> seed[3]; rnd.SetRandom(seed,p1,p2); } } input.close(); } else cerr << "PROBLEM: Unable to open seed.in" << endl; //fine preparazione for(int i=0; i<M; i++) //tiri random n[i] = rnd.Rannyu(); for(int i=0; i<N; i++){ //misure blocchi sum = 0; sums = 0; for (int j=0; j<L; j++){ sum += n[j+i*L]; sums += ( n[j+i*L] - 0.5)*( n[j+i*L] - 0.5); } av[i] = sum/L; av2[i] = av[i]*av[i]; sv[i] = sums/L; sv2[i] = sv[i]*sv[i]; } output.open("misure.dat", ios::out); // file dove inserire dati for(int i=0; i<N; i++){ //calcolo delle medie proggressive for(int j=0; j<i+1; j++){ av_prog[i] += av[j]; av2_prog[i] += av2[j]; sv_prog[i] += sv[j]; sv2_prog[i] += sv2[j]; } av_prog[i] /= (i+1); av2_prog[i] /= (i+1); err[i] = error( av_prog[i], av2_prog[i], i); sv_prog[i] /= (i+1); sv2_prog[i] /= (i+1); serr[i] = error( sv_prog[i], sv2_prog[i], i); output << av_prog[i] << " " << err[i] << " " << sv_prog[i] << " " << serr[i] << endl; //inserisco dati nel file } output.close(); //test del chi-quadro int M1 = 100; //sottointervalli di [0,1] int N1 = 10000; //lanci nell'intervallo [0,1] double L1 = double(M1)/double(N1); //larghezza intervalli double *t; //:= puntatore di numeri random [0,1] double n1[M1]; //:= array di numero di lanci in ogni intervallo //double av_n[M1]; //:= array delle medie del numero di lanci in ogni intervallo double a; //contatore double x[100]; //:= array dei chi-quadri fstream chi2; chi2.open("chi2.dat", ios::out); for(int b=0; b< 100; b++) { t = new double[N1]; for(int i=0; i<N1; i++) //tiri random t[i] = rnd.Rannyu(); for(int i=0; i<M1; i++) {//conteggio lanci in ogni intervallo a = 0; for(int j=0; j<N1; j++) { //tiri random if( i*L1 <= t[j] && t[j] < L1*(1+i)) a++; n1[i] = a; } } for(int i=0; i<M1; i++) x[b] += ((n1[i] - double(N1/M1))*(n1[i] - double(N1/M1)))/double(N1/M1); //calcolo del chi-quadro chi2 << x[b] << endl; delete [] t; } chi2.close(); return 0; } double error (double av, double av2, int n){ //funzione che calcola l'errore if (n==0) return 0; else return sqrt((av2 - av*av)/n); }
true
d65d37eb1afa312a6e83a24d33d925696bcd20dc
C++
Jianbo-Huang/Product-search
/pagerank.h
UTF-8
9,058
2.546875
3
[]
no_license
#ifndef __PAGE_RANK_H #define __PAGE_RANK_H #include <sstream> #include <iostream> #include <vector> #include <stdlib.h> #include <fstream> #include <map> #include <set> #include <dirent.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <math.h> #include <random> #include <algorithm> #include <stdlib.h> #include <ctype.h> #include <ctime> //#include <boost/algorithm/string/classification.hpp> // Include boost::for is_any_of //#include <boost/algorithm/string/split.hpp> // Include for boost::split using namespace std; namespace mlearn { std::string dateNow(); std::string current_time(); inline string word_join(const std::string &wd, int mxlen=20) { string nword; int len=wd.size(); if (len>mxlen) len=mxlen; for (unsigned i=0;i<wd.size();++i) { char c=wd[i]; if (c==' ' || c=='\n' ) c='-'; nword.push_back(c); } return nword; } inline void split ( std::vector<std::string> &container, const std::string &in, const std::string &del ) { int len = in.length(); int i = 0; if (container.size()>=1) { container.resize(0); } while ( i < len ) { // eat leading whitespace i = in.find_first_not_of (del, i); if (i <0) { return; // nothing left but white space } // find the end of the token int j = in.find_first_of (del, i); // push token if (j <0) { std::string ss=in.substr(i); container.push_back (ss); break; } else { std::string ss1=in.substr(i, j-i); container.push_back (ss1); } i = j + 1; } return; } inline void split(std::vector<string>&vec, const std::string &str, char sep=' ') { vec.resize(0); istringstream f(str); string s; while (getline(f, s, sep)) { if (s!=" " &&s!="\t" &&s!="\n") { vec.push_back(s); } } return; } inline int inlist(const vector<string> &list, const string &key) { for (unsigned i=0; i<list.size();i++) { if (list[i]==key) { return i; } } return -1; } inline void remove_punct(string &str) { //remove punctuation char c=str[str.size()-1]; if (c==',' || c=='.' || c==':' || c=='?' || c=='!'|| c==';') { str=str.substr(0,str.size()-1); } } inline void tlower(std::string &str) { for (unsigned i=0;i<str.size();i++) { char c=str[i]; str[i]=tolower(c); } } inline void replace_char(std::string &str) { for (unsigned i=0;i<str.size();i++) { if (str[i]=='&' || str[i]=='/'||str[i]=='-') { str[i]=' '; } } } class Item { public: string sitem; static vector<string> descwords; static double total_title_score; static double total_desc_score; static double total_type_score; vector<string> vtype; vector<string> vtitle; vector<string> vdesc; map<string,int> nfreq; double titlescore;//title score for the current query double descscore; //description score for the current query double typescore; float price; inline bool has_descwords(const vector<string> &qwords); string title() { vector<string> vtmp; split(vtmp,sitem,"\""); //cout<<"title:"<<vtmp.size()<<" "<<vtmp[1]<<" "<<vtmp[2]<<" "<<vtmp[3]<<endl; return vtmp[2]; } Item(const std::string &s1,const std::string &tit, const std::string &desc, float price0,const std::string &type="none") { sitem=s1; price=price0; str2words(vtitle,tit) ; str2words(vdesc,desc) ; if (type!="none") { str2words(vtype,type) ; } sort(vdesc.begin(),vdesc.end()); } void desc_score (const vector<std::string> &words); int findfreq(const std::string &wd); void write(ostream &os=cout); inline void str2words(vector<string> &words,const std::string &str) ; inline void str2words(set<string> &words,const std::string &str) ; Item(){;} inline bool contains(const vector<string> &qwords);//check whether title contains one or more of the words in qwords ~Item (){;} }; class Query { public: static string stop_words; static vector<string> stopwords; static void set_stopword_vector(); static inline bool is_stopword(const std::string &wd); static void remove_stopwords(const vector<string> &vec,vector<string> &newlist); string word; int findtfreq(Item &item);//find total frequency of the query words in an item description Query(const std::string &que); Query(const vector<string > &vque); vector<string> words; Query() {;} ~Query() {;} }; bool Query::is_stopword(const std::string &wd) { bool is_sword=binary_search(stopwords.begin(),stopwords.end(),wd); return is_sword; } class Catlog { public: int topm; Query *query; string score_scheme; //keymatch or tf-idf vector<Item> items; vector<int> effective_items; vector<pair<int,double>> importance;//inportance rating void get_effective_items(const Query &que); //get effective items relevant to a query map<int,int> tfreq; //term frequency map, get total frequency of all words in a search query words, for each of the effective items map<int,int> tscore; //total score of key match void gettf(Query &que); //get term frequency for the query void get_rating(Query &que); //get importance rating void readfile(const string &tfile,vector<string> &contents) ; void show_importance(ostream &os=std::cout); void show_search(ostream &os,Query &que); //show most relevant results void show_all_search(ostream &os,Query &que); Catlog(const string &tfile,int m=6) ; void setitems(vector<string> &contents); void setitems(vector<string> &contents,int istart, int iend,int ithread) ; Catlog(int m=6) { topm=m; score_scheme="keymatch"; } ~Catlog() {;} }; bool Item::has_descwords(const vector<string> &qwords) { bool hasit=false; for (unsigned i=0; i<vtitle.size();i++) { string wd=vtitle[i]; if (inlist(qwords,wd)>=0) { continue; } if (inlist(descwords,wd)>=0) { hasit=true; break; } } return hasit; } void Item::str2words(vector<string> &words,const std::string &str) { //split string to words by space vector<string> vtmp1; string del=" / - & { } # ( ) , > < ="; split(vtmp1,str,del); //boost::split(vtmp1, str, boost::is_any_of("/ - & { } # ( ) , > < = "), boost::token_compress_on); for (unsigned i=0;i<vtmp1.size();i++) { string s2=vtmp1[i]; tlower(s2); remove_punct(s2) ; bool stopwd=Query::is_stopword(s2); if (stopwd) continue ; words.push_back(s2); } return; } void Item::str2words(set<string> &words,const std::string &str) { //split string to words by space vector<string> vtmp1; string del=" / - & { } # ( ) , > < ="; split(vtmp1,str,del); for (unsigned i=0;i<vtmp1.size();i++) { string s2=vtmp1[i]; tlower(s2); remove_punct(s2) ; bool stopwd=Query::is_stopword(s2); if (stopwd) continue ; words.insert(s2); } return; } bool Item::contains(const vector<string> &qwords) { bool cnts=false; vector<int> matched(qwords.size(),0); vector<int> tmatch(qwords.size(),0); for (unsigned i=0;i<qwords.size();i++) { nfreq[qwords[i]]=0; for (unsigned k=0;k<vtitle.size();k++) { // if (inlist(vtitle,qwords[i])>=0) return true; if (vtitle[k]==qwords[i]) { cnts=true; matched[i]=1; nfreq[qwords[i]]++; } } if (vtype.size()>=1) { for (unsigned k=0;k<vtype.size();k++) { if (vtype[k]==qwords[i]) { tmatch[i]=1; } } }//if vtype }//for qwords int totmatch=0; for (unsigned s=0;s<matched.size();s++) { totmatch+=matched[s]; } int typesum=0; for (unsigned s=0;s<tmatch.size();s++) { typesum+=tmatch[s]; } titlescore=total_title_score*float(totmatch) /float(qwords.size()); typescore=total_type_score*float(typesum) /float(qwords.size()); // } if (titlescore/total_title_score>0.9) { //total match, reduce it if descriptive words are included if (has_descwords(qwords)) { titlescore*=0.85; } } return cnts; } // }//mlearn #endif
true
3fbea5d4c7cddea9ac23216911f365c78002d7d2
C++
colormotor/sandbox
/sandbox/lib/tracer.cpp
UTF-8
4,838
2.59375
3
[ "MIT" ]
permissive
/* * Tracer.cpp * * Created by Daniel Berio on 4/29/13. * http://www.enist.org * Copyright 2013. All rights reserved. * */ #include "tracer.h" namespace cm { V2 closestPoint(const V2& a, const V2& b, const V2& p) { V2 ap = p - a; V2 ab = b - a; float ab2 = ab.x*ab.x + ab.y*ab.y; float ap_ab = ap.x*ab.x + ap.y*ap.y; float t = ap_ab / ab2; if (t < 0.0f) t = 0.0f; else if (t > 1.0f) t = 1.0f; return a + ab * t; } /* m=(y2-y1)/(float)(x2-x1); float y=y1; int x; for (x=x1;x<=x2;x++,y+=m) putpixel(x,y,color); */ static int traceLine(Shape* shape, const Image& img, const V2& a, const V2& b, float scalex, float scaley, int on ) { float x0 = a.x*scalex; float y0 = a.y*scaley; float x1 = b.x*scalex; float y1 = b.y*scaley; float x = x0; float y = y0; V2 d = b-a; float len = arma::norm(d); d/=len; int w = img.width(); int h = img.height(); int step = img.step(); int chans = img.mat.channels(); int stride = step / chans; // Add an initial contour if shape is empty if(!shape->size()) shape->add(Contour()); #define THRESH 155 #define FUZZY_DIF(a,b) (abs(b-a)>THRESH) #define CLOSEST(x,y) V2(x,y) //closestPoint(a,b,V2(x,y)) float prevx = x; float prevy = y; float dist = 0.0; int v = 0; for(;;){ Contour & path = shape->last(); int iy = roundf(y); int ix = roundf(x); if(ix >= w || ix < 0 || iy >= h || iy < 0 ) v = 0; else v = img.mat.data[iy*step+(ix*chans)]; if(v) { if(on) { path.addPoint(CLOSEST(prevx,prevy)); shape->add(Contour()); } on = 0; } else // on { if(!on) { path.addPoint(CLOSEST(x,y)); } on = 1; } /* if( FUZZY_DIF(v, prevv) ) // v!=prevValue ) { if( v > THRESH ) { // point is occluded, add end point path.addPoint(CLOSEST(prevx,prevy)); shape->add(Contour()); } else { // start a new contour and add point path.addPoint(CLOSEST(prevx,prevy)); } } else { if( feq(x,x0) && feq(y,y0) && v < THRESH) // first point in line path.addPoint(CLOSEST(prevx,prevy)); } prevv = v;*/ prevx = x; prevy = y; if (dist>=len) break; x+=d.x; y+=d.y; dist+=1.0; } if(on) { shape->last().addPoint(b); // last point } return on; } /* int trace_line(Shape * shape, const Image & img, const V2 & a, const V2 & b, float scalex, float scaley, int prevValue ) { int x0 = a.x*scalex; int y0 = a.y*scaley; int x1 = b.x*scalex; int y1 = b.y*scaley; int x = x0; int y = y0; int dx = abs(x1-x0), sx = x0<x1 ? 1 : -1; int dy = abs(y1-y0), sy = y0<y1 ? 1 : -1; int err = (dx>dy ? dx : -dy)/2, e2; // Add an initial contour if shape is empty if(!shape->size()) shape->appendContour(); #define THRESH 5 #define FUZZY_DIF(a,b) (abs(b-a)>5) #define CLOSEST(x,y) closestPoint(a,b,V2(x,y)) int prevx = x; int prevy = y; for(;;){ Contour & path = shape->last(); int v = img.getIntensity(x,y)*255; if( FUZZY_DIF(v,prevValue) ) //v!=prevValue ) { if( v > THRESH ) { // point is occluded, add end point path.addPoint(CLOSEST(prevx,prevy)); shape->appendContour(); } else { // start a new contour and add point path.addPoint(CLOSEST(prevx,prevy)); } } else { if( x==x0 && y==y0 && v < THRESH) // first point in line path.addPoint(CLOSEST(prevx,prevy)); } prevValue = v; prevx = x; prevy = y; if (x==x1 && y==y1) break; e2 = err; if (e2 >-dx) { err -= dy; x += sx; } if (e2 < dy) { err += dx; y += sy; } } return prevValue; }*/ Shape trace( const Contour& path, const Image& img, float scalex, float scaley ) { Shape tmp; if(path.size() < 2) return tmp; int n = path.size()-1; if( path.closed ) n+=1; int v = 0; for( int j = 0; j < n; j++ ) { const V2 & a = path.getPoint(j); const V2 & b = path.getPoint((j+1)%path.size()); v = traceLine(&tmp, img, a, b, scalex, scaley, v); } if( v < THRESH && path.closed && tmp.size()) { Contour & last = tmp.last(); if(path.size()) last.addPoint(path.getPoint(0)); } // check that shape is valid Shape res; for( int i = 0; i < tmp.size(); i++ ) if(tmp[i].size()>1) res.add(tmp[i]); return res; } Shape trace( const Shape& s, const Image& img, float scalex, float scaley ) { Shape res; for( int i = 0; i < s.size(); i++ ) res.add(trace(s[i], img, scalex, scaley)); return res; } }
true
a47a4a479a34fb8aa25a5fce98703681e6e25cf2
C++
farzingkh/Occupancy-Grid-Mapping
/src/utility.cpp
UTF-8
1,016
3.046875
3
[ "MIT" ]
permissive
#include "../include/utility.h" #include "../include/map.h" #include <iostream> #include <math.h> #include <random> double utility::get_gaussian_random_number(double mean, double var) { // Random Generators std::random_device rd; std::mt19937 gen(rd()); // get rangom number from normal distribution std::normal_distribution<double> dist(mean, var); return dist(gen); } double utility::get_random_number() { // Random Generators std::random_device rd; std::mt19937 gen(rd()); // get random number from a uniform distribution std::uniform_real_distribution<double> dist(0.0, 1.0); return dist(gen); } double utility::get_gaussian_probability(double mean, double var, double x) { //std::cout << mean << " " << var << " " << x << std::endl; // Probability of x given normal ditribution with mean and variance double p = exp(-(pow((mean - x), 2)) / (pow(var, 2)) / 2.0) / sqrt(2.0 * M_PI * (pow(var, 2))); //std::cout << p << std::endl; return p; }
true
522f05414c226eb47790da3e717dcad5bae6403c
C++
leeseungjoo98/c-plus-plus
/static.cpp
UTF-8
510
3.53125
4
[]
no_license
//static 멤버 사용 #include <iostream> using namespace std; class Person { public : int money; void addMoney(int money) { this->money += money; } static int sharedMoney; static void addShared(int money) { sharedMoney += money; } }; int Person::sharedMoney = 10; int main() { Person::addShared(50); //60 cout << Person::sharedMoney << endl; Person han; han.money = 100; han.sharedMoney = 200; Person::sharedMoney = 300; Person::addShared(100); cout << Person::sharedMoney << endl; }
true
63193b8ec93447b03f59bbcfcbaaea54299aee59
C++
amruthr7/Navigation_System
/Navigation_System/src/CPersistentStorage.h
UTF-8
1,853
2.796875
3
[]
no_license
/*************************************************************************** *============= Copyright by Darmstadt University of Applied Sciences ======= **************************************************************************** * Filename : CPERSISTENTSTORAGE.H * Author : * Description : * * ****************************************************************************/ #ifndef CPERSISTENTSTORAGE_H #define CPERSISTENTSTORAGE_H #include <cstring> #include <ostream> #include <fstream> #include "CWpDatabase.h" #include "CPoiDatabase.h" class CPersistentStorage { public: /* @methodName : ~CPersistentStorage(){} * @description : Destructor - to delete allocated memory when the object of the class is destroyed. */ virtual ~CPersistentStorage(){} /** * Set the name of the media to be used for persistent storage. * The exact interpretation of the name depends on the implementation * of the component. * @param name the media to be used */ virtual void setMediaName(std::string name) = 0; /** * Write the data to the persistent storage. * @param waypointDb the data base with way points * @param poiDb the database with points of interest * @return true if the data could be saved successfully */ virtual bool writeData (const CWpDatabase& waypointDb, const CPoiDatabase& poiDb) = 0; /** * The mode to be used when reading the data bases. */ enum MergeMode { MERGE, REPLACE }; /* * @param waypointDb the the data base with way points * @param poiDb the database with points of interest * @param mode the merge mode * @return true if the data could be read successfully */ virtual bool readData (CWpDatabase& waypointDb, CPoiDatabase& poiDb, MergeMode mode) = 0; }; /******************** ** CLASS END *********************/ #endif /* CPERSISTENTSTORAGE_H */
true
79c0f78cab6b4444726e16b11a9c646e2085a25a
C++
ElisaNgLi/OOP345
/W2/Text.h
UTF-8
708
2.921875
3
[]
no_license
/********************************************************** * Name: Elisa Ng * Student ID: 136265170 * Seneca email: eng-li@myseneca.ca **********************************************************/ #ifndef W2_TEXT_H #define W2_TEXT_H #include <string> #include <memory> using namespace std; namespace w2 { class Text { string* m_String; size_t m_Count; public: Text(); Text(const string file); // Copy constructor Text(const Text&); // Copy assignment operator Text& operator=(const Text&); // Move constructor Text(Text&&); // Move Assignment Operator Text& operator=(Text&&); // Destructor ~Text(); // Returns the number of records of text data size_t size() const; }; } #endif
true
e284a01e28e288812e506a1667bd34ef767724e7
C++
fourseaLee/algolearn
/redblacktree/redblacktree.hpp
UTF-8
11,165
3.40625
3
[]
no_license
#ifndef RED_BLACK_TREE_H #define RED_BLAKC_TREE_H enum TreeColor { RED = 0, BLACK = 1 }; template<class N> struct NodeRbt { TreeColor color; N key; NodeRbt* right; NodeRbt* left; NodeRbt* parent; NodeRbt(TreeColor c, N k, NodeRbt* r, NodeRbt* l, NodeRbt* p): color(c),key(k),right(r),left(l),parent(p) { } }; template<class T> class TreeRbt { private: NodeRbt<T>* root_; public: TreeRbt(); ~TreeRbt(); public: void preOrder(); void inOrder(); void postOrder(); public: NodeRbt<T>* find(T key); NodeRbt<T>* search(T key); T minNode(); T maxNode(); NodeRbt<T>* getSuccessor(NodeRbt<T>* node); NodeRbt<T>* getPredecessor(NodeRbt<T>* node); public: void insert(T key); void remove(T key); void remove(T key); void destroy(); public: void print(); protected: void preOrderIter(NodeRbt<T>* node) const; void inOrderIter(NodeRbt<T>* node) const; void postOrderIter(NodeRbt<T>* node) const; NodeRbt<T>* find(NodeRbt<T>* x, T key) const; NodeRbt<T>* search(NodeRbt<T>* x, T key) const; NodeRbt<T>* minNodeIter(NodeRbt<T>* node); NodeRbt<T>* maxNodeIter(<NodeRbt<T>* node); void leftRotate(NodeRbt<T>* &root, NodeRbt<T>* x); void rightRotate(NodeRbt<T>* &root, NodeRbt<T>* y); void insert(NodeRbt<T>* &root, NodeRbt<T>* node); void insertFixUp(NodeRbt<T>* &root, NodeRbt<T>* node); void remove(NodeRbt<T>* &root, NodeRbt<T>* node); void removeFixUp(NodeRbt<T>* &root, NodeRbt<T>* node, NodeRbt<T>* parent); void destory(NodeRbt<T>* &tree); void print(NodeRbt<T>* tree, T key, int direction); }; template<class T> TreeRbt<T>::TreeRbt():root_(nullptr) { } template<class T> TreeRbt<T>::~TreeRbt() { destroy(); } template<class T> void TreeRbt::preOrder(NodeRbt<T>* tree) const { if (tree) { //function do some things; preOrder(tree->left); preOrder(tree->right); } } template<class T> void TreeRbt::preOrder() { preOrder(root_); } template<class T> void TreeRbt::inOrder(NodeRbt<T>* tree) const { if (tree) { inOrder(tree->left); //function do some things; inOrder(tree->right); } } template<class T> void TreeRbt::inOrder() { inOrder(root_); } template<class T> void TreeRbt::postOrder(NodeRbt<T>* tree) const { if (tree) { postOrder(tree->left); postOrder(tree->right); //function do some things; } } template<class T> void TreeRbt::postOrder() { postOrder(root_); } template<class T> NodeRbt<T>* TreeRbt<T>::find(NodeRbt<T>* x, T key) const { if (x == NULL || x->key == key) return x; if (key < x->key) return find(x->left, key); else return find(y->right, key); } template<class T> NodeRbt<T>* TreeRbt<T>::find(T key) { find(root_, key); } template<class T> NodeRbt<T>* TreeRbt<T>::search(NodeRbt<T>* x, T key) const { while ( x && x->key != key) { if (key < k->key) x = x->left; else x = x->right; } return x; } template<class T> NodeRbt<T>* TreeRbt<T>::search(T key) { search(root_, key); } template<class T> void TreeRbt<T>::leftRotate(NodeRbt<T>* & root, NodeRbt<T>* x) { NodeRbt<T>* y = x->right; x->right = y->left; if(y->left != nullptr) { y->left->parent = x; } y->parent = x->parent; if(x->parent == nullptr) { root = y; } else { if (x->parent->left == x) x->parent->left = y; else x->parent->right = y; } y->left = x; x->parant = y; } template<class T> void TreeRbt<T>::rightRotate(NodeRbt<T>* & root, NodeRbt<T>* y) { NodeRbt<T>* x = y->left; y->left = x->right; if (x->right != nullptr) x->right->parent = y; x->parent = y->parent; if (y->parent == nullptr) { root = x; } else { if (y == y->parent->right) y->parent->right = x; else y->parent->left = x; } x->right = y; y->parent = x; } template<class T> void TreeRbt<T>::insert(NodeRbt<T>* &root, NodeRbt<T>* node) { NodeRbt<T>* y = nullptr; NodeRbt<T>* x = root; while (x != nullptr) { y = x ; if(node->key < x->key) x = x->left; else x = x->right; } node->parent = y; if (y != nullptr) { if (node->key < y->key) y->left = node; else y->right = node; } else root = node; node->color = RED; insertFixUp(root, node); } template<class T> void TreeRbt<T>::insert(T key) { NodeRbt<T> *z = NULL; if ( ( z=new NodeRbt<T> )(key, BLACK, NULL, NULL, NULL) == NULL) return ; insert(root_, z); } template<class T> void TreeRbt<T>::insertFixUp(NodeRbt<T>* & root, NodeRbt<T>* node) { NodeRbt<T>* parent, *gparant; while ((parant = node->parent) && parent->color == RED) { gparent = parent->parent; if (parent == gparent->left) { //case one uncle is red { NodeRbt<T>* uncle = gparent ->right; if (uncle && uncle->color == RED) { uncle->color = BLACK; parent->color = BLACK; gparent->color = BLACK; node = gparent; continue; } } //case two uncle is black if(parent->right == node) { NodeRbt<T> *tmp; leftRotate(root, parent); tmp = parent; parent = node; node = tmp; } parent->color = BLACK; gparent->color = RED; rightRotate(root, gparent); } else { //case one uncle node is red { NodeRbt<T>* uncle = gparent->left; if (uncle && uncle->color == RED) { uncle->color = BLACK; parent->color = BLACK; gparent->color = RED; node = gparent; continue; } } //case two uncle node is black if (parent->left == node) { NodeRbt<T>* tmp; rightRotate(root, parent); tmp = parent; parent = node; node = tmp; } parent->color = BLACK; gparent->color = RED; leftRotate(root, gparent); } } root->color = BLACK; } template<class T> void TreeRbt<T>::remove(NodeRbt<T>* &root, NodeRbt<T>* node) { NodeRbt<T>* child, *parent; NodeColor color; if ( (node->left != nullptr) && (node->right != nullptr) ) { NodeRbt<T>* replace = node; replace = replace->right; while (replace->left != nullptr) replace = replace->left; if (node->parenet) { if (node->left == node) node->parent->left = replace; else node->parent->right = replace; } else root = replace; child = replace->right; parent = replace->parent; color = replace->color; if (parent == node) { parent = replace; } else { if (child) child->parent = parent; parent->left = child; replace->right = node->right; node->right->parent = replace; } replace->parent = node->parent; replace->color = node->color; replace->left = node->left; node->left->parent = replace; if (color == BLACK) removeFixUp(root, child, parent); delete node; return; } if (node->left) child = node->left; else child = node->right; parent = node->parent; color = node->color; if (child) child->parent = parent; if (parent) { if (parent->left == node) parent->left = child; else parent->right = child; } else root = child; if (color == BLACK) removeFixUp(root, child, parent); delete node; } template <class T> void TreeRbt<T>::remove(T key) { NodeRbt<T> *node; if ((node = search(root_, key)) != nullptr) remove(root_, node); } template <class T> void TreeRbt::removeFixUp(NodeRbt<T>* &root, NodeRbt<T>* node, NodeRbt<T>* parent) { ModeRbt<T>* other; while ((node == nullptr || node->color == BLACK) && node != root) { if (parent->left == node) { other = parent->right; if (other->color == RED) { other->color = BLACK; parent->color = RED; leftRotate(root, parent); other = parent->right; } if ((!other->left || other->left->color == BLACK) && (!other->right || other->right-> == BLACK)) { other->color = RED; node = parent; parent = node->parent; } else { if (!other->right || other->right->color == BLACK) { other->left->color = BLACK; other->color = RED; rightRotate(root, other); other = parent->right; } other->color = parent->color; parent->color = BLACK; other->right->color = BLACK; leftRotate(root, parent); node = root; break; } } else { other = parent->left; if (other->color == RED) { other->color = BLACK; parent->color = RED; rightRotate(root, parent); other = parent->left; } if ((!other->left || other->left->color == BLACK ) && (!other->right || other->right->color == BLACK)) { other->color = RED; node = parent; parent = node->parent; } else { if (!other->left || other->left->color == BLACK) { other->right->color = BLACK; other->color = RED; leftRotate(root, other); other = parent->left; } other->color = parent->color; parent->color = BLACK; other->left->color = BLACK; rightRotate(root, parent); node = root; break; } } } if (node) node->color = BLACK; } #endif
true
9c396022b9caad11e8a3a67c934b8aef98ffe10d
C++
abhishektrip/SliceBasedVolumeRendering
/Common/UI/atUserInterface.cpp
UTF-8
2,659
2.796875
3
[]
no_license
#include "atUserInterface.h" atRenderEngine::atUserInterface::atUserInterface(int width, int height) { TwDefine(" GLOBAL fontscaling=5 "); // double the size of all fonts // Initialize AntTweakBar if (!TwInit(TW_OPENGL_CORE, NULL)) { std::cout << "Ant Tweak Bar init failed" << std::endl; return; } // Tell the window size to AntTweakBar TwWindowSize(width, height); // Create a tweak bar bar = TwNewBar("TweakBar"); TwDefine(" GLOBAL help='This example shows how to integrate AntTweakBar with SDL and OpenGL.\nPress [Space] to toggle fullscreen.' "); // Message added to the help bar. TwDefine("TweakBar position= '0 0'"); TwDefine("TweakBar size= '300 1080'"); TwDefine("TweakBar resizable=true "); TwDefine("TweakBar movable=true "); // Add 'width' and 'height' to 'bar': they are read-only (RO) variables of type TW_TYPE_INT32. TwAddVarRO(bar, "Width", TW_TYPE_INT32, &width, " label='Wnd width' help='Width of the graphics window (in pixels)' "); TwAddVarRO(bar, "Height", TW_TYPE_INT32, &height, " label='Wnd height' help='Height of the graphics window (in pixels)' "); // Add 'numCurves' to 'bar': this is a modifiable variable of type TW_TYPE_INT32. Its shortcuts are [c] and [C]. TwAddVarRW(bar, "NumCubes", TW_TYPE_INT32, &numCubes, " label='Number of cubes' min=1 max=100 keyIncr=c keyDecr=C help='Defines the number of cubes in the scene.' "); // Add 'ka', 'kb and 'kc' to 'bar': they are modifiable variables of type TW_TYPE_DOUBLE TwAddVarRW(bar, "ka", TW_TYPE_DOUBLE, &ka, " label='X path coeff' keyIncr=1 keyDecr=CTRL+1 min=-10 max=10 step=0.01 "); TwAddVarRW(bar, "kb", TW_TYPE_DOUBLE, &kb, " label='Y path coeff' keyIncr=2 keyDecr=CTRL+2 min=-10 max=10 step=0.01 "); TwAddVarRW(bar, "kc", TW_TYPE_DOUBLE, &kc, " label='Z path coeff' keyIncr=3 keyDecr=CTRL+3 min=-10 max=10 step=0.01 "); // Add 'color0' and 'color1' to 'bar': they are modifable variables of type TW_TYPE_COLOR3F (3 floats color) TwAddVarRW(bar, "color0", TW_TYPE_COLOR3F, &color0, " label='Start color' help='Color of the first cube.' "); TwAddVarRW(bar, "color1", TW_TYPE_COLOR3F, &color1, " label='End color' help='Color of the last cube. Cube colors are interpolated between the Start and End colors.' "); // Add 'quit' to 'bar': this is a modifiable (RW) variable of type TW_TYPE_BOOL32 // (a boolean stored in a 32 bits integer). Its shortcut is [ESC]. TwAddVarRW(bar, "Quit", TW_TYPE_BOOL32, &quit, " label='Quit?' true='+' false='-' key='ESC' help='Quit program.' "); } atRenderEngine::atUserInterface::~atUserInterface() { TwTerminate(); } void atRenderEngine::atUserInterface::Draw() { TwDraw(); }
true
14ded235556fa4d4360b9a7f21b933721d6a7be3
C++
witold-gawlowski/octet
/octet/src/examples/example_geometry/example_geometry.h
UTF-8
4,254
2.90625
3
[]
no_license
//////////////////////////////////////////////////////////////////////////////// // // (C) Andy Thomason 2012-2014 // // Modular Framework for OpenGLES2 rendering on multiple platforms. // namespace octet { /// Scene containing a helix with octet. class example_geometry : public app { // scene for drawing helix ref<visual_scene> app_scene; // this is the vertex format used in this sample. // we have 12 bytes of float position (x, y, z) and four bytes of color (r, g, b, a) struct my_vertex { vec3p pos; uint32_t color; }; // this function converts three floats into a RGBA 8 bit color static uint32_t make_color(float r, float g, float b) { return 0xff000000 + ((int)(r*255.0f) << 0) + ((int)(g*255.0f) << 8) + ((int)(b*255.0f) << 16); } public: /// this is called when we construct the class before everything is initialised. example_geometry(int argc, char **argv) : app(argc, argv) { } /// this is called once OpenGL is initialized void app_init() { app_scene = new visual_scene(); app_scene->create_default_camera_and_lights(); // use a shader that just outputs the color_ attribute. param_shader *shader = new param_shader("shaders/default.vs", "shaders/simple_color.fs"); material *red = new material(vec4(1, 0, 0, 1), shader); // create a new mesh. mesh *helix = new mesh(); // number of steps in helix size_t num_steps = 320; // allocate vertices and indices into OpenGL buffers size_t num_vertices = num_steps * 2 + 2; size_t num_indices = num_steps * 6; helix->allocate(sizeof(my_vertex) * num_vertices, sizeof(uint32_t) * num_indices); helix->set_params(sizeof(my_vertex), num_indices, num_vertices, GL_TRIANGLES, GL_UNSIGNED_INT); // describe the structure of my_vertex to OpenGL helix->add_attribute(attribute_pos, 3, GL_FLOAT, 0); helix->add_attribute(attribute_color, 4, GL_UNSIGNED_BYTE, 12, GL_TRUE); { // these write-only locks give access to the vertices and indices. // they will be released at the next } (the end of the scope) gl_resource::wolock vl(helix->get_vertices()); my_vertex *vtx = (my_vertex *)vl.u8(); gl_resource::wolock il(helix->get_indices()); uint32_t *idx = il.u32(); // make the vertices float radius1 = 1.0f; float radius2 = 7.0f; float height = 24.0f; float num_twists = 4.0f; for (size_t i = 0; i != num_steps+1; ++i) { float r = 0.0f, g = 1.0f * i / num_steps, b = 1.0f; float y = i * (height / num_steps) - height * 0.5f; float angle = i * (num_twists * 2.0f * 3.14159265f / num_steps); vtx->pos = vec3p(cosf(angle) * radius1, y, sinf(angle) * radius1); vtx->color = make_color(r, g, b); log("%f %f %f %08x\n", r, g, b, vtx->color); vtx++; vtx->pos = vec3p(cosf(angle) * radius2, y, sinf(angle) * radius2); vtx->color = make_color(r, g, b); vtx++; } // make the triangles uint32_t vn = 0; for (size_t i = 0; i != num_steps; ++i) { // 0--2 // | \| // 1--3 idx[0] = vn + 0; idx[1] = vn + 3; idx[2] = vn + 1; idx += 3; idx[0] = vn + 0; idx[1] = vn + 2; idx[2] = vn + 3; idx += 3; vn += 2; } } // add a scene node with this new mesh. scene_node *node = new scene_node(); app_scene->add_child(node); app_scene->add_mesh_instance(new mesh_instance(node, helix, red)); } /// this is called to draw the world void draw_world(int x, int y, int w, int h) { int vx = 0, vy = 0; get_viewport_size(vx, vy); app_scene->begin_render(vx, vy); // update matrices. assume 30 fps. app_scene->update(1.0f/30); // draw the scene app_scene->render((float)vx / vy); // tumble the helix (there is only one mesh instance) scene_node *node = app_scene->get_mesh_instance(0)->get_node(); //node->rotate(1, vec3(1, 0, 0)); node->rotate(1, vec3(0, 1, 0)); } }; }
true
81cd8e140bd403111cae9925465b7fc75a0ce5da
C++
HhTtLllL/algorithm
/luogu/p1443.cpp
UTF-8
1,060
2.859375
3
[]
no_license
#include<cstdio> #include<queue> #include<cstring> using namespace std; struct node { int x; int y; int step; }; int a[405][405]; int book[405][405]; queue<node> s; int next1[8][2] = {{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1},{-2,1},{-1,2}}; int main( ) { int n,m,x,y; struct node strat; scanf( "%d%d%d%d",&n,&m,&x,&y); memset(a,-1,sizeof(a)); strat.x = x; strat.y = y; strat.step = 0; book[x][y] = 1; s.push(strat); while(!s.empty( )) { a[s.front( ).x][s.front( ).y] = s.front( ).step; for(int k = 0;k < 8;k++) { int tx = s.front( ).x + next1[k][0]; int ty = s.front( ).y + next1[k][1]; int tstep = s.front( ).step+1; if(tx < 1 || tx > n || ty < 1 || ty > m) continue; if(book[tx][ty] == 0) { book[tx][ty] = 1; strat.x = tx; strat.y = ty; strat.step = tstep; s.push(strat); } } s.pop( ); } for(int i = 1;i <= n;i++) { for(int j = 1;j <= m;j++) { if(i == x && j == y) { printf( "%-5d",0); continue; } else printf( "%-5d",a[i][j]); } printf( "\n"); } }
true
4cdc5a041c12a818e6ebe5ed58a8dec533516156
C++
developer0hye/Algo-0hye
/problems/1003/boj_1003.cpp
UTF-8
1,098
3.6875
4
[]
no_license
#include <iostream> #include <vector> using namespace std; vector<pair<int, int>> memo(41); pair<int, int> zero_one_called(int n) { if(memo[n].first != -1 && memo[n].second != -1) return memo[n]; else if(n == 0) return memo[0]; else if(n == 1) return memo[1]; pair<int, int> small_n1 = zero_one_called(n-1); pair<int, int> small_n2 = zero_one_called(n-2); memo[n].first = small_n1.first + small_n2.first; memo[n].second = small_n1.second + small_n2.second; return memo[n]; } int main() { int T; cin >> T; //first -> 0이 호출되는 횟수, second -> 1이 호출되는 횟수 memo[0].first = 1; memo[0].second = 0; memo[1].first = 0; memo[1].second = 1; for(int i = 2; i < 41; i++) { memo[i].first = -1; //해가 구해진 적 없다! memo[i].second = -1; //해가 구해진 적 없다! } for(int k = 0; k < T; k++) { int n; cin >> n; pair<int, int> answer = zero_one_called(n); cout << answer.first << " " << answer.second << "\n"; } return 0; }
true
bae2555de4af4363b8ded2ed0541750ba23cdae9
C++
goyeer/complete-cpp-developer-course
/course-source-files/section 12/ArrayStackApp/main.cpp
UTF-8
451
3.65625
4
[]
no_license
#include <iostream> #include "ArrayStack.h" using namespace std; int main() { ArrayStack stack; ArrayStack stack2; for (int i = 0; i < 17; i++) //make it get to the limit on last element { stack.push(i); } while (!stack.isEmpty()) { stack2.push(stack.pop()); } cout << "Same order as entered, using second stack:" << endl; while (!stack2.isEmpty()) { cout << stack2.pop() << endl; } return 0; }
true
025c05a1cc890cd9b277611f8160ec6cc698eb3f
C++
taqu/lime
/lframework/resource/ResourceTexture2D.h
UTF-8
1,909
2.546875
3
[]
no_license
#ifndef INC_LFRAMEWORK_RESOURCETEXTURE2D_H_ #define INC_LFRAMEWORK_RESOURCETEXTURE2D_H_ /** @file ResourceTexture2D.h @author t-sakai @date 2016/11/21 create */ #include "Resource.h" #include <lgraphics/TextureRef.h> namespace lfw { class ResourceTexture2D : public Resource { public: typedef lcore::intrusive_ptr<ResourceTexture2D> pointer; static const s32 Type = ResourceType_Texture2D; static ResourceTexture2D* load(const Char* path, s64 size, const u8* memory, const TextureParameter& param); static ResourceTexture2D* create(u32 color, const TextureParameter& param); static ResourceTexture2D* create(u32 width, u32 height, const u32* colors, const TextureParameter& param); virtual s32 getType() const { return ResourceType_Texture2D; } inline lgfx::Texture2DRef& get() ; inline lgfx::SamplerStateRef& getSampler(); inline lgfx::ShaderResourceViewRef& getShaderResourceView(); protected: ResourceTexture2D(const ResourceTexture2D&); ResourceTexture2D& operator=(const ResourceTexture2D&); ResourceTexture2D(lgfx::Texture2DRef& texture, lgfx::SamplerStateRef& sampler, lgfx::ShaderResourceViewRef& srv) :texture_(texture) ,sampler_(sampler) ,srv_(srv) { } virtual ~ResourceTexture2D() { } lgfx::Texture2DRef texture_; lgfx::SamplerStateRef sampler_; lgfx::ShaderResourceViewRef srv_; }; inline lgfx::Texture2DRef& ResourceTexture2D::get() { return texture_; } inline lgfx::SamplerStateRef& ResourceTexture2D::getSampler() { return sampler_; } inline lgfx::ShaderResourceViewRef& ResourceTexture2D::getShaderResourceView() { return srv_; } } #endif //INC_LFRAMEWORK_RESOURCETEXTURE2D_H_
true
6a28dcdb397fede3c3fc0b035f529a47d285ccd7
C++
captainmoha/data_structure_course
/3_arrays/quadraticEquationArr.cpp
UTF-8
1,078
3.8125
4
[]
no_license
#include <iostream> #include <math.h> // getting the roots of a quadratic equation using namespace std; double* quadEqn(double a, double b, double c) { double* values = new double[2]; double x1, x2; if ((b*b - 4 * a * c) >= 0) { x1 = (-b + sqrt(b*b - 4 * a * c)) / 2 * a; x2 = (-b - sqrt(b*b - 4 * a * c)) / 2 * a; values[0] = x1; values[1] = x2; return values; } else { // TODO deal with negative square roots return NULL; } } int main() { double a, b, c; cout << "Hello! , welcome to quadratic equations solver!" << endl; // get coeffecients from user cout << "Enter a: "; cin >> a; cout << endl << "Enter b: "; cin >> b; cout << endl << "Enter c: "; cin >> c; double* values; // get address of first element values = quadEqn(a, b, c); double x1, x2; // roots of equation x1 = values[0]; x2 = values[1]; cout << endl <<"The roots of the equation are : " << endl << "-----------------------------------------------------" << endl; cout << "x1 = " << x1 << endl; cout << "x2 = " << x2 << endl; return 0; }
true
fd3ffa4816c36b1d4a07fdae88206a9d33cb4fd5
C++
LarsFL/Themaopdracht_Gaming
/MarsRunner/Code/Game engine/Tile systems/Tile.hpp
UTF-8
1,218
2.921875
3
[]
no_license
#ifndef _TILE_HPP #define _TILE_HPP #include <SFML/Graphics.hpp> #include <memory> #include "TextureManager.hpp" #include "Texture.hpp" class Tile { private: std::shared_ptr<Texture> texture; int textureId; sf::Sprite sprite; sf::Vector2f position; sf::Vector2f size; TextureManager& manager; public: Tile(TextureManager& manager, int textureId, sf::Vector2f position, sf::Vector2f size, sf::IntRect textureRect) : textureId(textureId), position(position), size(size), manager(manager) { texture = manager.getTexture(textureId); sprite.setTexture(texture->texture); sprite.setPosition(position); sprite.setTextureRect(textureRect); sprite.setScale(size); }; Tile(const Tile& r) : texture(r.texture), textureId(r.textureId), sprite(r.sprite), position(r.position), size(r.size), manager(r.manager) { sprite.setTexture(texture->texture); sprite.setPosition(position); } void draw(sf::RenderWindow& window) { window.draw(sprite); } void setPosition(sf::Vector2f newPos) { position = newPos; sprite.setPosition(newPos); } sf::FloatRect getGlobalBounds() { return sprite.getGlobalBounds(); } template <class T> void callLamba(T a) { a(); } }; #endif
true
c284650a4017a2267ebc97808b10d0cf11baac5c
C++
xhochy/duckdb
/src/include/storage/column_statistics.hpp
UTF-8
1,311
2.90625
3
[ "MIT" ]
permissive
//===----------------------------------------------------------------------===// // DuckDB // // storage/column_statistics.hpp // // //===----------------------------------------------------------------------===// #pragma once #include "common/common.hpp" #include "common/types/statistics.hpp" #include "common/types/value.hpp" #include "common/types/vector.hpp" #include <mutex> namespace duckdb { //! The ColumnStatistics object holds statistics related to a physical column of //! a table class ColumnStatistics { public: ColumnStatistics() { can_have_null = false; min.is_null = true; max.is_null = true; maximum_string_length = 0; } //! Update the column statistics with a new batch of data void Update(Vector &new_vector); //! Initialize ExpressionStatistics from the ColumnStatistics void Initialize(ExpressionStatistics &target); //! True if the vector can potentially contain NULL values bool can_have_null; //! The minimum value of the column [numeric only] Value min; //! The maximum value of the column [numeric only] Value max; //! The maximum string length of a character column [VARCHAR only] index_t maximum_string_length; private: //! The lock used to update the statistics of the column std::mutex stats_lock; }; } // namespace duckdb
true
f452885c5f4f5da74f632cab7b4053de75b6050f
C++
avinash625/CodingProblems
/LeetCode/find_bottom_left_tree_value.cpp
UTF-8
857
3.265625
3
[]
no_license
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void findLeftValue(TreeNode *root, int *leftValue, int *levelValue,int level){ if(!root) return; else{ if(*levelValue < level){ *leftValue = root->val; *levelValue = level; } findLeftValue(root->left,leftValue, levelValue, level+1); findLeftValue(root->right,leftValue, levelValue, level+1); } } int findBottomLeftValue(TreeNode* root) { int leftValue , levelValue; levelValue = 0; leftValue = root->val; findLeftValue(root,&leftValue, &levelValue, 0); return leftValue; } };
true
a2e1f17a78b3a859a336c3fc759d6b14c570f50f
C++
section14/openframeworks-misc-classes
/trimesh.cpp
UTF-8
3,042
2.875
3
[]
no_license
#include "trimesh.h" trimesh::trimesh(int _rows, int _cols, float _width, float _height, int _color) { rows = _rows + 1; cols = _cols + 1; width = _width; height = _height; color = _color; //calculate height and width float rowWidth = width / rows; float colHeight = height / cols; //color var meshColor = ofColor(); //create verticies for (int rowCount = 0; rowCount<rows; rowCount++) { for (int colCount = 0; colCount<cols; colCount++) { float y = rowCount * rowWidth * -1; float x = colCount * colHeight; mesh.addVertex(ofVec3f(x,y,0)); meshColor.setHsb(color,200,200,200); mesh.addColor(meshColor); } } ///////////////////////////////// //create index vector/////////// /////////////////////////////// vector<int> indices; //location along the drawing path int indexLocation = 0; //two points per column, don't connect indexes //on the last row int rowSteps = rows - 1; int colSteps = cols * 2; //spacing switch keeps you in the correct place //for counting spaces between indexes int spacingSwitch = 0; for (int row = 0; row<rowSteps; row++) { for (int col = 0; col<colSteps; col++) { //if this is the last index location //write final location if (col == colSteps - 1) { indices.push_back(indexLocation); } else { //if spacing switch is even increment index location forward //by the number of columns, otherwise refer to next if statement if (spacingSwitch%2 == 0) { indexLocation += cols; indices.push_back(indexLocation); } else { //if row is even subtract from total columns //else add to total colums for index number spacing if (row%2 == 0) { indexLocation -= cols-1; indices.push_back(indexLocation); } else { indexLocation -= cols+1; indices.push_back(indexLocation); } } } spacingSwitch++; } } ///////////////////////////////// //add indicies to mesh ///////// /////////////////////////////// //add 0,0,0 location manually mesh.addIndex(0); for (int i=0; i<indices.size(); i++) { mesh.addIndex(indices[i]); } //add to vbo myVbo.setMesh(mesh, GL_DYNAMIC_DRAW); } void trimesh::update() { } void trimesh::draw() { myVbo.drawElements(GL_TRIANGLE_STRIP, mesh.getNumIndices()); } }
true
9024dd26c846310e1d474a2708f323cd8160b941
C++
FabianKlimpel/AdaptiveProfessor2.2.2
/include/Professor/ConfigHandler.h
UTF-8
1,895
2.984375
3
[]
no_license
#ifndef __CONFIGHANDLER__H #define __CONFIGHANDLER__H #include <iostream> #include <fstream> #include <string> using namespace std; /** * This class handles a config file provided by the user. * It handles the reading of the file and stores all necessary information in the object. */ class ConfigHandler { public: //Constructor ConfigHandler(const string configfile); //getter of member variables const bool getSummaryFlag(){return _summaryflag;} const bool getOutDotFlag(){return _outdotflag;} const bool getCovmatFlag(){return _covmat;} const double getThresholdFit(){return _thresholdfit;} const double getThresholdData(){return _thresholddata;} const double getThresholdErr(){return _thresholderr;} const double getChi2Mean(){return _chi2mean;} const double getKappa(){return _kappa;} private: //setter for the member variables void readThresholdFit(const string line); void readThresholdData(const string line); void readThresholdErr(const string line); void readChi2Mean(const string line); void readKappa(const string line); void readSummaryFlag(const string line); void readOutDotFlag(const string line); void readCovMat(const string line); /** * @_summaryflag, @_outdotflag: flags for writing additional summaries * @_covmat: flag for writing covariance matrices * @_thresholdfit: threshold of the RR constrain in the fitting * @_thresholddata: threshold of the RR constrain in the hypercube-fitting of the data * @_thresholderr: threshold of the RR constrain in getter of the fitting errors * @_chi2mean: number of modified chi2's to store in order to state a best value regarding the modified chi2 * @_kappa: shifting parameter if the RR constrain is applied */ bool _summaryflag = true, _outdotflag = false, _covmat = true; double _thresholdfit = 1e-10, _thresholddata = 1e-10, _thresholderr = 1e-10, _chi2mean = 100, _kappa = 1e-10; }; #endif
true
23f1360a2b510f9c363ee7d13ff2491c4a6ae087
C++
luas13/Leetcode_New
/src/Median-2-Sorted-Array/Median 2 Sorted Array.cpp
UTF-8
3,270
3.625
4
[]
no_license
/* Analysis: Note that the definition of the Median: (1) If the size of the sequence N is odd: N/2+1th element is median. (1) If the size of the sequence N is even: average of the N/2th and N/2+1th element is median. So in this problem, median of the two sorted arrays is the (m+n)/2+1 th element (if m+n is odd), the average of (m+n)/2 th and (m+n)/2+1 th (if m+n is even). E.g., [1,2,3],[5,6,7], the median is (3+5)/2 = 4.0. [1,2,3,4], [1,3,5,7,9], the median is 3. Our task becomes finding the Kth (K or K+1, K=(m+n)/2) number in two sorted arrays, in O(log(m+n)) time constraint (what's in your mind to see log? Yes, binary search). Similar to but slight different from binary search, we still divide K into two halves each time. Two pointers are used for each array, so that we can compare which side is smaller (?A[pa]>B[pb]). E.g., A = [1,3,5,7,9] B = [2,4,8,10,12,14,16,18]. K=(5+8) /2= 6. pa = K/2 = 3; pb = K-pa = 3; pa A[1,3,5,7,9] pb B[2,4,8,10,12,14,16,18] if (A[pa]<B[pb]), which means the elements from A[0] to A[pa] must exist in the first Kth elements. The next step now becomes finding the (K-pa) th (equals to K/2) element in the array A[pa:end] and B[]. This procedure can be viewed as "cutting" K/2 elements from the "smaller" array, and continue find the other K/2 th elements from the "bigger" array and the array after the cut. Note that smaller and bigger here is the comparison of the last elements. if (A[pa]>B[pb]), the same procedure is applied but we "cut" the B array. In this way, every time we have "cut" K/2 elements from one of the arrays, the next time is to cut (K/2) /2 elements from the new arrays, until: (1) K=1, the smaller one from A[0] and B[0] is the "Kth element". (2) One of the array meets the end. Then just return the current Kth element from the other array. */ #include <iostream> #include <vector> using namespace std; double getMedian(vector<int>& nums1, int m, vector<int>& nums2, int n, int k){ if (m > n) return getMedian(nums2, n, nums1, m, k); if (m == 0) return nums2[k-1]; if (k == 1) return min(nums1[0], nums2[0]); int p1 = min(k/2, m); int p2 = k - p1; if (nums1[p1 - 1] <= nums2[p2 - 1]){ std::vector<int> newNums1(nums1.begin()+p1, nums1.end()); return getMedian(newNums1, m-p1, nums2, n, k-p1); } else{ std::vector<int> newNums2(nums2.begin()+p2, nums2.end()); return getMedian(nums1, m, newNums2, n-p2, k-p2); } } class Solution { public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { int len1 = nums1.size(); int len2 = nums2.size(); int total = len1 + len2; if (total % 2){ return (getMedian(nums1, len1, nums2, len2, total/2 + 1)); } else{ return ((getMedian(nums1, len1, nums2, len2, total/2) + getMedian(nums1, len1, nums2, len2, (total/2 + 1)) ) / 2); } } }; int main() { //cout << "Hello world!" << endl; std::vector<int> nums1; std::vector<int> nums2; nums1.push_back(2); //nums2.push_back(2); Solution s;// = new Solution(); cout<<" The median is = "<<s.findMedianSortedArrays(nums1, nums2); return 0; }
true
172917fdc76118c385664f0a9aaf1070d39d3da3
C++
jaswantcoder/CodingNotes
/MasteringCompetitiveProgrammingQuestions/HOLI.cpp
UTF-8
975
2.5625
3
[]
no_license
//Holiday Accomodation - Page 46 //https://www.spoj.com/problems/HOLI/ #include<bits/stdc++.h> using namespace std; #define ll long long vector< pair<ll, ll> > adj[100005]; ll ret = 0; ll n; ll dfs (ll par, ll u) { ll ans = 1; for(ll i = 0; i < adj[u].size(); ++i) { ll v = adj[u][i].first; ll wt = adj[u][i].second; if(v==par) continue; ll nodes = dfs(u,v); ret += 2 * min(nodes, n-nodes) * wt; ans += nodes; } return ans; } int main() { ll t; scanf("%lld", &t); ll tc = 1; while(t--) { ret = 0; scanf("%lld", &n); for (ll i = 1; i <= n; ++i) adj[i].clear(); for (int i = 1; i <= n-1; ++i) { ll u, v, x; scanf("%lld %lld %lld", &u, &v, &x); adj[u].push_back({v, x}); adj[v].push_back({u, x}); } dfs(-1, 1); cout << "Case #" << tc++ << ": " << ret << endl; } }
true
7c9831fec6e61314c2dece5900d626107c5155d4
C++
CalebeBastos/FontClassifier
/untitled/main.cpp
UTF-8
3,650
2.609375
3
[]
no_license
//////////////////////////////////////////////////////////////////// // Constants for Backprop Font Data // //////////////////////////////////////////////////////////////////// #define FV_IN "norm.sep" #define NORMALIZE false #define FONT_DATA true #define ALPHA 0.0 // momentum factor #define ETA 0.1 // learning rate #define MAXIN 14 // number of input nodes #define MAXH 20 // number of nodes hidden layer #define MAXOUT 26 // number of nodes output layer #define N_ITERATIONS 10 // times to train the network #define NUMFV 78 // number of feature vectors total #define NUMUV 78 // number of test vectors #define LOG_MOD 10 // print results every LOG_MOD iterations #define RESULTS_OUT_NAME "bp.out" #define WEIGHTS_IN "bpw.in" #define WEIGHTS_OUT "bpw.out" #define WEIGHT_FILE_NAME "genw.txt" // for genweights #include <iostream> #include <vector> #include <fstream> #include <iomanip> #include <algorithm> //void GenerateWeights(); using namespace std; //const double MAX = double(RAND_MAX); struct myFeatures { int alphabet; int font; double feature[14]; // hardcoded 14. need to change it later sometime }; int _NUMDATA_ = 0; // total number of data sets in the input file int main() { /* vector<myFeatures> myData; myFeatures myFeature; // create an ifstream object to read in from the file ifstream fin("norm.txt"); int num1 = 0; double num2 = 0.0; int count = 0; while(fin) { count = 0; while(count < 16) // hardcoded 16. need to change it later sometime { if(count == 0) { fin >> num1; myFeature.alphabet = num1; } else if(count == 1) { fin >> num1; myFeature.font = num1; } else { fin >> num2; myFeature.feature[count-2] = num2; } count++; } myData.push_back(myFeature); _NUMDATA_++; if(fin >> num1 == NULL) break; } fin.close();*/ /****************************************************** done reading the features from the file upto here *****************************************************/ //random_shuffle(myData.begin(), myData.end()); // randomly shuffle elements of the vector myData //GenerateWeights(); cout << "Hello"; return 0; } /** * Generates random weights and writes them onto a file */ /* void GenerateWeights() { float double_off; int i; int j; float offset; ofstream outfile; float x; offset = 0.1; double_off = offset * 2.0; outfile.open(WEIGHT_FILE_NAME); srand(time(NULL)); outfile.setf(ios::fixed); for(i = 0; i < MAXH; i++) { for(j = 0; j < MAXIN + 1; j++) { x = (rand() / MAX) * double_off - offset; outfile << setprecision(6); outfile << setw(10) << x; if ((j+1) % 7 == 0) outfile << endl; } outfile << endl; } outfile << endl; for(i = 0; i < MAXOUT; i++) { for(j = 0; j < MAXH + 1; j++) { x = (rand() / MAX) * double_off - offset; outfile << setprecision(6); outfile << setw(10) << x; if ((j + 1) % 7 == 0) outfile << endl; } outfile << endl; } outfile.close(); } */
true
c6d178926f5341d09b1fa003318a0857660770a4
C++
rezarastak/CppConstitutive
/test/elastic.cc
UTF-8
1,132
2.75
3
[ "MIT" ]
permissive
#include "catch.hpp" #include "constitutive/mech/elastic.h" using namespace constitutive; TEST_CASE("Elastic params (lambda, mu)", "[mech]") { LambdaMu lambda_mu{100., 50.}; REQUIRE(lambda_mu.get_lambda() == 100.); REQUIRE(lambda_mu.get_mu() == 50.); REQUIRE(lambda_mu.get_E() == Approx(133.3).epsilon(0.01)); REQUIRE(lambda_mu.get_nu() == Approx(0.33).margin(0.01)); } TEST_CASE("Elastic params (E, nu)", "[mech]") { YoungPoisson params{120., 0.25}; REQUIRE(params.get_E() == 120.); REQUIRE(params.get_nu() == 0.25); REQUIRE(params.get_lambda() == 48.); REQUIRE(params.get_mu() == 48.); } TEST_CASE("Convert lambda, mu to E, nu", "[mech]") { LambdaMu lambda_mu(80., 60.); YoungPoisson young_poisson(lambda_mu); REQUIRE(young_poisson.get_E() == Approx(154.3).epsilon(0.01)); REQUIRE(young_poisson.get_nu() == Approx(0.29).margin(0.01)); } TEST_CASE("Convert E, nu to lambda, mu", "[mech]") { YoungPoisson young_poisson{100., 0.35}; LambdaMu lambda_mu{young_poisson}; REQUIRE(lambda_mu.get_lambda() == Approx(86.4).epsilon(0.01)); REQUIRE(lambda_mu.get_mu() == Approx(37.).epsilon(0.01)); }
true
1a8095da7a1b92f53ee57abadd37e4b289deadc3
C++
sayantikag98/Current_Data_Structures_and_Algorithms
/DSA_codes_in_cpp/Interview Prep CC/Pepcoding/online cpp foundation/1. Basics of programming/getting_started/is_a_number_prime.cpp
UTF-8
525
2.828125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; bool func(int n){ for(int i = 2; i*i<=n; i++){ if(n%i==0) return 0; } return 1; } int main(){ #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif ios::sync_with_stdio(0); cin.tie(0); int t; cin >> t; while(t--){ int n; cin>>n; bool ans = func(n); if(ans) cout<<"prime"<<"\n"; else cout<<"not prime"<<"\n"; } return 0; }
true
a7c08afbeed47558eac5bf1bc331702996971421
C++
StiffLiu/codes
/new/my_binary_search_tree.h
UTF-8
61,397
3
3
[]
no_license
#ifndef MY_BINARY_SEARCH_TREE_H #define MY_BINARY_SEARCH_TREE_H #include "my_ordered_symbol_table.h" #include <utility> #include <vector> #include <cassert> #include <iostream> #include <algorithm> #include <memory> #include <exception> namespace my_lib{ template<class K, class V, class BSTNodeTraitsParam, class C = std::less<K> > class BinarySearchTreeBase : public OrderedSymbolTable<K, V>{ public: typedef BSTNodeTraitsParam BSTNodeTraits; typedef typename BSTNodeTraits::Node Node; typedef typename BSTNodeTraits::NodePtr NodePtr; BinarySearchTreeBase(C comparator = C()) : comparator(comparator){ } BinarySearchTreeBase(BinarySearchTreeBase&& bst){ root = bst.root; comparator = bst.comparator; bst.root = NodePtr(); } BinarySearchTreeBase(const BinarySearchTreeBase& bst){ root = (bst.root == NodePtr() ? NodePtr() : BSTNodeTraits::copyNode(bst.root)); comparator = bst.comparator; } BinarySearchTreeBase& operator=(const BinarySearchTreeBase& bst){ if(this == &bst) return *this; clear(); root = (bst.root == NodePtr() ? NodePtr() : BSTNodeTraits::copyNode(bst.root)); comparator = bst.comparator; return *this; } void put(const K& k, const V& v) override { putInner(k, v); } bool remove(const K&k) override { NodePtr node = removeInner(k); BSTNodeTraits::deleteNode(node); return node != NodePtr(); } const V* get(const K& k) const override{ NodePtr node = getNode(k); if(node == NodePtr()) return nullptr; return BSTNodeTraits::value(node); } const K* min() const override{ if(root == NodePtr()) return nullptr; NodePtr leftMost = BSTNodeTraits::lmc(root); return BSTNodeTraits::key(leftMost); } const K* max() const override{ if(root == NodePtr()) return nullptr; NodePtr rightMost = BSTNodeTraits::rmc(root); return BSTNodeTraits::key(rightMost); } const K* floor(const K& k) const override{ NodePtr subtree = root; while(subtree != NodePtr()){ if(comparator(*BSTNodeTraits::key(subtree), k)){ if(BSTNodeTraits::right(subtree) == NodePtr()) break; subtree = BSTNodeTraits::right(subtree); }else if(comparator(k, *BSTNodeTraits::key(subtree))){ if(BSTNodeTraits::left(subtree) == NodePtr()){ subtree = BSTNodeTraits::parent(BSTNodeTraits::rmp(subtree)); break; } subtree = BSTNodeTraits::left(subtree); }else{ break; } } if(subtree == NodePtr()) return nullptr; return BSTNodeTraits::key(subtree); } const K* ceil(const K& k) const override{ NodePtr subtree = root; while(subtree != NodePtr()){ if(comparator(*BSTNodeTraits::key(subtree), k)){ if(BSTNodeTraits::right(subtree) == NodePtr()){ subtree = BSTNodeTraits::parent(BSTNodeTraits::lmp(subtree)); break; } subtree = BSTNodeTraits::right(subtree); }else if(comparator(k, *BSTNodeTraits::key(subtree))){ if(BSTNodeTraits::left(subtree) == NodePtr()) break; subtree = BSTNodeTraits::left(subtree); }else{ break; } } if(subtree == NodePtr()) return nullptr; return BSTNodeTraits::key(subtree); } unsigned int rank(const K& k) const override{ NodePtr subtree = root; unsigned int count = 0; while(subtree != NodePtr()){ if(comparator(*BSTNodeTraits::key(subtree), k)){ count += BSTNodeTraits::safeCount(BSTNodeTraits::left(subtree)) + 1; if(BSTNodeTraits::right(subtree) == NodePtr()){ break; } subtree = BSTNodeTraits::right(subtree); }else if(comparator(k, *BSTNodeTraits::key(subtree))){ if(BSTNodeTraits::left(subtree) == NodePtr()){ break; } subtree = BSTNodeTraits::left(subtree); }else{ count += BSTNodeTraits::safeCount(BSTNodeTraits::left(subtree)); break; } } return count; } const K* select(unsigned int index) const override{ NodePtr n = selectInner(index); if(n == NodePtr()) return nullptr; return BSTNodeTraits::key(n); } bool leftRotate(NodePtr node){ if(node == root){ if(BSTNodeTraits::leftRotate(node)){ root = BSTNodeTraits::parent(root); return true; } return false; } return BSTNodeTraits::leftRotate(node); } bool rightRotate(NodePtr node){ if(node == root){ if(BSTNodeTraits::rightRotate(node)){ root = BSTNodeTraits::parent(root); return true; } return false; } return BSTNodeTraits::rightRotate(node); } bool removeMin() override { NodePtr node = removeMinInner(); BSTNodeTraits::deleteNode(node); return node != NodePtr(); } bool removeMax() override { NodePtr node = removeMaxInner(); BSTNodeTraits::deleteNode(node); return node != NodePtr(); } bool isEmpty() const override{ return root == NodePtr(); } unsigned int size() const override{ return BSTNodeTraits::safeCount(root); } virtual int height() const{ if(root == NodePtr()) return -1; std::vector<NodePtr> parents; int height = 0; parents.push_back(root); while(!parents.empty()){ std::vector<NodePtr> childs; for(size_t i = 0;i < parents.size();++ i){ auto p = parents[i]; auto r = BSTNodeTraits::right(p), l = BSTNodeTraits::left(p); if(r != NodePtr()) childs.push_back(r); if(l != NodePtr()) childs.push_back(l); } parents.swap(childs); ++ height; } return height - 1; } unsigned int size(const K& l, const K& h) const override{ unsigned int i = rank(l), j = rank(h); if(i > j) return 0; if(getNode(h) != NodePtr()) return j - i + 1; return j - i; } void clear() override{ if(root != NodePtr()){ unsigned int count = BSTNodeTraits::count(root); std::vector<NodePtr> ps(count); ps[0] = root; for(unsigned int i = 0, j = 1;i < count;++ i){ NodePtr n = ps[i]; NodePtr l = BSTNodeTraits::left(n), r = BSTNodeTraits::right(n); if(l != NodePtr()){ ps[j] = l; ++ j; } if(r != NodePtr()){ ps[j] = r; ++ j; } BSTNodeTraits::deleteNode(n); } root = NodePtr(); } } /** * @return true if the data structure is valid. */ bool isValid() const override { assert(root == NodePtr() || BSTNodeTraits::parent(root) == NodePtr()); return root == NodePtr() || (BSTNodeTraits::parent(root) == NodePtr() && BSTNodeTraits::isValid(root)); } const C& getComparator(){ return comparator; } ~BinarySearchTreeBase(){ clear(); } private: typedef OrderedSymbolTable<K, V> Super; typedef typename Super::IteratorImpl IteratorImpl; protected: NodePtr putInner(const K& k, const V& v){ if(root == NodePtr()){ root = BSTNodeTraits::createNode(k, v, NodePtr(), NodePtr(), NodePtr(), 1); return root; } NodePtr subtree = root; NodePtr newNode = NodePtr(); //Loop invariant : // subtree is the root of the sub tree, in which k lies. while(subtree != NodePtr()){ if(comparator(*BSTNodeTraits::key(subtree), k)){ if(BSTNodeTraits::right(subtree) == NodePtr()){ newNode = BSTNodeTraits::createNode(k, v, subtree, NodePtr(), NodePtr(), 1); BSTNodeTraits::right(subtree, newNode); break; } subtree = BSTNodeTraits::right(subtree); }else if(comparator(k, *BSTNodeTraits::key(subtree))){ if(BSTNodeTraits::left(subtree) == NodePtr()){ newNode = BSTNodeTraits::createNode(k, v, subtree, NodePtr(), NodePtr(), 1); BSTNodeTraits::left(subtree, newNode); break; } subtree = BSTNodeTraits::left(subtree); }else{ BSTNodeTraits::value(subtree, v); return NodePtr(); } } while(subtree != NodePtr()){ BSTNodeTraits::count(subtree, BSTNodeTraits::count(subtree) + 1); subtree = BSTNodeTraits::parent(subtree); } return newNode; } NodePtr removeInner(const K& k){ NodePtr node = getNode(k); if(node != NodePtr()){ if(BSTNodeTraits::left(node) != NodePtr() && BSTNodeTraits::right(node) != NodePtr()){ NodePtr successor = BSTNodeTraits::right(node); while(BSTNodeTraits::left(successor) != NodePtr()) successor = BSTNodeTraits::left(successor); if(node == root) root = successor; if(BSTNodeTraits::parent(successor) != NodePtr()){ if(successor == BSTNodeTraits::left(BSTNodeTraits::parent(successor))) BSTNodeTraits::left(BSTNodeTraits::parent(successor), node); else BSTNodeTraits::right(BSTNodeTraits::parent(successor), node); } if(BSTNodeTraits::parent(node) != NodePtr()){ if(node == BSTNodeTraits::left(BSTNodeTraits::parent(node))) BSTNodeTraits::left(BSTNodeTraits::parent(node), successor); else BSTNodeTraits::right(BSTNodeTraits::parent(node), successor); } BSTNodeTraits::swap(node, successor); if(BSTNodeTraits::left(node) != NodePtr()) BSTNodeTraits::parent(BSTNodeTraits::left(node), node); if(BSTNodeTraits::right(node) != NodePtr()) BSTNodeTraits::parent(BSTNodeTraits::right(node), node); if(BSTNodeTraits::left(successor) != NodePtr()) BSTNodeTraits::parent(BSTNodeTraits::left(successor), successor); if(BSTNodeTraits::right(successor) != NodePtr()) BSTNodeTraits::parent(BSTNodeTraits::right(successor), successor); } //At least one of node's children is null NodePtr c = BSTNodeTraits::left(node); if(BSTNodeTraits::right(node) != NodePtr()) c = BSTNodeTraits::right(node); if(node != root){ NodePtr pNode = BSTNodeTraits::parent(node); (node == BSTNodeTraits::left(pNode)) ? BSTNodeTraits::left(pNode, c) : BSTNodeTraits::right(pNode, c); if(c != NodePtr()) BSTNodeTraits::parent(c, pNode); while(pNode != NodePtr()){ BSTNodeTraits::count(pNode, BSTNodeTraits::count(pNode) - 1); pNode = BSTNodeTraits::parent(pNode); } }else{ root = c; if(root != NodePtr()) BSTNodeTraits::parent(root, NodePtr()); } } return node; } NodePtr selectInner(unsigned int index) const{ if(root == NodePtr()) return NodePtr(); if(index >= BSTNodeTraits::count(root)) return NodePtr(); NodePtr n = root; unsigned int tmp = 0; if(BSTNodeTraits::left(n) != NodePtr()) tmp = BSTNodeTraits::count(BSTNodeTraits::left(n)); while(index != tmp){ if(index > tmp){ n = BSTNodeTraits::right(n); index -= (tmp + 1); }else{ n = BSTNodeTraits::left(n); } tmp = BSTNodeTraits::safeCount(BSTNodeTraits::left(n)); } return n; } NodePtr removeMinInner(){ if(root != NodePtr()){ NodePtr leftMost = root; while(BSTNodeTraits::left(leftMost) != NodePtr()){ BSTNodeTraits::count(leftMost, BSTNodeTraits::count(leftMost) - 1); leftMost = BSTNodeTraits::left(leftMost); } if(leftMost != root){ BSTNodeTraits::left(BSTNodeTraits::parent(leftMost), BSTNodeTraits::right(leftMost)); if(BSTNodeTraits::right(leftMost) != NodePtr()) BSTNodeTraits::parent(BSTNodeTraits::right(leftMost), BSTNodeTraits::parent(leftMost)); }else{ root = BSTNodeTraits::right(root); BSTNodeTraits::parent(root, NodePtr()); } return leftMost; } return NodePtr(); } NodePtr removeMaxInner(){ if(root != NodePtr()){ NodePtr rightMost = root; while(BSTNodeTraits::right(rightMost) != NodePtr()){ BSTNodeTraits::count(rightMost, BSTNodeTraits::count(rightMost) - 1); rightMost = BSTNodeTraits::right(rightMost); } if(rightMost != root){ BSTNodeTraits::right(BSTNodeTraits::parent(rightMost), BSTNodeTraits::left(rightMost)); if(BSTNodeTraits::left(rightMost) != NodePtr()) BSTNodeTraits::parent(BSTNodeTraits::left(rightMost), BSTNodeTraits::parent(rightMost)); }else{ root = BSTNodeTraits::left(root); BSTNodeTraits::parent(root, NodePtr()); } return rightMost; } return NodePtr(); } NodePtr getNode(const K& k) const{ NodePtr subtree = root; //Loop invariant : // subtree is the root of the sub tree, in which k may lies. while(subtree != NodePtr()){ if(comparator(*BSTNodeTraits::key(subtree), k)){ if(BSTNodeTraits::right(subtree) == NodePtr()) return NodePtr(); subtree = BSTNodeTraits::right(subtree); }else if(comparator(k, *BSTNodeTraits::key(subtree))){ if(BSTNodeTraits::left(subtree) == NodePtr()) return NodePtr(); subtree = BSTNodeTraits::left(subtree); }else{ return subtree; } } return NodePtr(); } struct BinarySearchTreeIterator : public IteratorImpl{ void next() override{ if(node != NodePtr()) node = BSTNodeTraits::suc(node); } bool equals(const IteratorImpl& i) const override{ const BinarySearchTreeIterator *itor = dynamic_cast<const BinarySearchTreeIterator*>(&i); if(itor != nullptr) return node == itor->node; return false; } bool operator==(const BinarySearchTreeIterator& itor){ return node == itor.node; } bool operator!=(const BinarySearchTreeIterator& itor){ return node != itor.node; } void assign(const IteratorImpl& i) override{ const BinarySearchTreeIterator *itor = dynamic_cast<const BinarySearchTreeIterator*>(&i); if(itor != nullptr) this->node = itor->node; } const K& key() const override{ return *BSTNodeTraits::key(node); } const V& value() const override{ return *BSTNodeTraits::value(node); } BinarySearchTreeIterator* copy() const override{ return new BinarySearchTreeIterator(node); } BinarySearchTreeIterator(NodePtr node) : node(node){ } private: NodePtr node; }; BinarySearchTreeIterator *implBegin() const override{ return new BinarySearchTreeIterator(root == NodePtr() ? NodePtr() : BSTNodeTraits::lmc(root)); } BinarySearchTreeIterator *implEnd() const override{ return new BinarySearchTreeIterator(NodePtr()); } protected: NodePtr root = NodePtr(); C comparator; }; template<class N, class NodeBase> struct NodeTraits{ typedef N Node; typedef Node* NodePtr; typedef const Node* ConstNodePtr; /** * @return Left most child of {@var node} */ template<class Ptr> static Ptr lmc(Ptr leftMost){ while(left(leftMost) != NodePtr()) leftMost = left(leftMost); return leftMost; } /** * @return Right most child of {@var node} */ template<class Ptr> static Ptr rmc(Ptr rightMost){ while(right(rightMost) != NodePtr()) rightMost = right(rightMost); return rightMost; } /** * @return Left most parent of {@var node} */ template<class Ptr> static Ptr lmp(Ptr leftMost){ Ptr p = parent(leftMost); while(p != NodePtr() && right(p) == leftMost){ leftMost = p; p = parent(leftMost); } return leftMost; } /** * @return Right most parent of this node */ template<class Ptr> static Ptr rmp(Ptr rightMost){ Ptr p = parent(rightMost); while(p != NodePtr() && left(p) == rightMost){ rightMost = p; p = parent(rightMost); } return rightMost; } /** * @return Successor of {@var node} */ template<class Ptr> static Ptr suc(Ptr node){ if(right(node) != NodePtr()) return lmc(right(node)); node = lmp(node); if(parent(node) != NodePtr() && node == left(parent(node))) return parent(node); return NodePtr(); } /** * @return Predecessor of this node */ template<class Ptr> static Ptr pre(Ptr node){ if(left(node) != NodePtr()) return left(node)->rmc(); node = rmp(node); if(parent(node) != NodePtr() && node == right(parent(node))) return parent(node); return NodePtr(); } /** * @return left child of {@var node} */ template<class Ptr> static Ptr left(Ptr node){ return NodeBase::left(node); } template<class Ptr> static void left(Ptr node, Ptr l){ NodeBase::left(node, l); } /** * @return right child of {@var node} */ template<class Ptr> static Ptr right(Ptr node){ return NodeBase::right(node); } template<class Ptr> static void right(Ptr node, Ptr r){ NodeBase::right(node, r); } /** * @reurn parent of {@var node} */ template<class Ptr> static Ptr parent(Ptr node){ return NodeBase::parent(node); } template<class Ptr> static void parent(Ptr node, Ptr p){ NodeBase::parent(node, p); } /** * * @return Number of nodes rooted at {@var node} */ template<class Ptr> static unsigned int count(Ptr node){ return NodeBase::count(node); } template<class Ptr> static void count(Ptr node, unsigned int c){ NodeBase::count(node, c); } template<class Ptr> static unsigned int safeCount(Ptr node){ return node == NodePtr() ? 0 : count(node); } static void swap(NodePtr node1, NodePtr node2){ NodeBase::swap(node1, node2); } static NodePtr copyNode(NodePtr node){ auto parent = new Node(*node); auto left = NodeBase::left(parent); if(left != NodePtr()){ left = copyNode(left); NodeBase::parent(left, parent); NodeBase::left(parent, left); } auto right = NodeBase::right(parent); if(right != NodePtr()){ right = copyNode(right); NodeBase::parent(right, parent); NodeBase::right(parent, right); } return parent; } /** * @return {@code true} if the data structure is valid. */ template<class Ptr> static bool isValid(const Ptr node){ if(parent(node) == node){ assert(false); return false; } unsigned int tmp = 0; if(left(node) != NodePtr()){ if(parent(left(node)) != node || !isValid(left(node))) assert(false);//return false; tmp = count(left(node)); } if(right(node) != NodePtr()){ if(parent(right(node)) != node || !isValid(right(node))) assert(false);//return false; tmp += count(right(node)); } assert(tmp + 1 == count(node)); return tmp + 1 == count(node); } template<class Ptr> static bool leftRotate(Ptr node){ NodePtr r = right(node); if(r != NodePtr()){ NodePtr p = parent(node); NodePtr b = left(r); if(p != NodePtr()){ if(node == left(p)) left(p, r); else right(p, r); } parent(r, p); parent(node, r); left(r, node); right(node, b); if(b != NodePtr()) parent(b, node); count(node, safeCount(b) + safeCount(left(node)) + 1); count(r, count(node)+ safeCount(right(r)) + 1); return true; } return false; } template<class Ptr> static bool rightRotate(Ptr node){ NodePtr l = left(node); if(l != NodePtr()){ NodePtr p = parent(node); NodePtr b = right(l); if(p != NodePtr()){ if(node == left(p)) left(p, l); else right(p, l); } parent(l, p); parent(node, l); right(l, node); left(node, b); if(b != NodePtr()) parent(b, node); count(node, safeCount(b) + safeCount(right(node)) + 1); count(l, count(node) + safeCount(left(l)) + 1); return true; } return false; } }; template<class K, class V, class BSTNode, class NodeBase> struct BSTNodeTraits : public NodeTraits<BSTNode, NodeBase>{ private: public: typedef typename NodeTraits<BSTNode, NodeBase>::Node Node; typedef typename NodeTraits<BSTNode, NodeBase>::NodePtr NodePtr; static NodePtr createNode(const K& k, const V& v){ return new Node(k, v); } static NodePtr createNode(const K& k, const V& v, NodePtr p, NodePtr l, NodePtr r){ return new Node(k, v, p, l, r); } static NodePtr createNode(const K& k, const V& v, NodePtr p, NodePtr l, NodePtr r, unsigned int count){ return new Node(k, v, p, l, r, count); } template<class Ptr> static const K* key(Ptr p){ return NodeBase::template key<Ptr, K>(p); } template<class Ptr> static const V* value(Ptr node){ return NodeBase::template value<Ptr, V>(node); } template<class Ptr> static void value(Ptr node, const V& v){ NodeBase::value(node, v); } template<class Ptr> static void deleteNode(Ptr node){ delete node; } }; template<class Node> struct BSTNodeBase{ typedef Node* NodePtr; template<class Ptr> static Ptr left(Ptr node){ return node->l; } static void left(NodePtr node, NodePtr l){ node->l = l; } template<class Ptr> static Ptr right(Ptr node){ return node->r; } static void right(NodePtr node, NodePtr r){ node->r = r; } template<class Ptr> static Ptr parent(Ptr node){ return node->p; } static void parent(NodePtr node, NodePtr p){ node->p = p; } template<class Ptr> static unsigned int count(Ptr node){ return node->c; } template<class Ptr, class K> static const K* key(Ptr p){ return &p->value.first; } template<class Ptr, class V> static const V* value(Ptr node){ return &node->value.second; } template<class Ptr, class V> static void value(Ptr node, const V& v){ node->value.second = v; } static void count(NodePtr node, unsigned int count){ node->c= count; } static void swap(NodePtr node1, NodePtr node2){ std::swap(node1->p, node2->p); std::swap(node1->l, node2->l); std::swap(node1->r, node2->r); std::swap(node1->c, node2->c); } }; template<class K, class V> struct BSTNode{ typedef BSTNode* NodePtr; typedef std::pair<K, V> Pair; NodePtr p, l, r; unsigned int c; Pair value; BSTNode(const K& k, const V& v) : BSTNode(k, v, NodePtr(), NodePtr(), NodePtr(), 1){ } BSTNode(const K& k, const V& v, NodePtr p, NodePtr l, NodePtr r, unsigned int count) :p(p), l(l), r(r), c(count), value(Pair(k, v)){ } }; template<class K, class V, class C = std::less<K> > using BinarySearchTree = BinarySearchTreeBase < K, V, BSTNodeTraits<K, V, BSTNode<K, V>, BSTNodeBase<BSTNode<K, V> > >, C > ; template<class RBNode> struct RBNodeBase : public BSTNodeBase<RBNode>{ typedef typename BSTNodeBase<RBNode>::NodePtr NodePtr; template<class Ptr> static typename RBNode::Color color(Ptr node){ return node == Ptr() ? RBNode::BLACK : node->color; } static void color(NodePtr node, typename RBNode::Color c){ assert(node != NodePtr()); node->color = c; } static void swap(NodePtr node1, NodePtr node2){ BSTNodeBase<RBNode>::swap(node1, node2); std::swap(node1->color, node2->color); } }; template<class K, class V, class RBNode, class RBNodeBase> struct RBNodeTraits : public BSTNodeTraits<K, V, RBNode, RBNodeBase>{ template<class Ptr> static typename RBNode::Color color(Ptr node){ return RBNodeBase::color(node); } template<class Ptr> static void color(Ptr node, typename RBNode::Color c){ RBNodeBase::color(node, c); } static typename RBNode::Color black(){ return RBNode::BLACK; } static typename RBNode::Color red(){ return RBNode::RED; } }; template<class K, class V> struct RBNode{ typedef RBNode* NodePtr; typedef std::pair<K, V> Pair; typedef bool Color; static const Color RED = true; static const Color BLACK = false; RBNode(const K& k, const V& v) : RBNode(k, v, NodePtr(), NodePtr(), NodePtr(), 1){ } RBNode(const K& k, const V& v, NodePtr p, NodePtr l, NodePtr r, unsigned int count) :value(k, v), p(p), l(l), r(r), c(count), color(RED){ } private: friend class RBNodeBase<RBNode<K, V> >; friend class BSTNodeBase<RBNode<K, V> >; Pair value; NodePtr p, l, r; unsigned int c; bool color = RED; }; template<class K, class V, class RBNodeTraitsParam, class C = std::less<K> > class RBTreeBase : public BinarySearchTreeBase<K, V, RBNodeTraitsParam, C>{ typedef BinarySearchTreeBase<K, V, RBNodeTraitsParam, C> Super; public: typedef typename Super::BSTNodeTraits RBNodeTraits; typedef typename Super::NodePtr NodePtr; RBTreeBase(const C& comparator = C()) : Super(comparator){ } void put(const K& k, const V& v) override { NodePtr node = Super::putInner(k, v); if(node != NodePtr()) fixInsert(node); } bool remove(const K&k) override { NodePtr node = Super::removeInner(k); if(node != NodePtr()){ assert(RBNodeTraits::left(node) == NodePtr() || RBNodeTraits::right(node) == NodePtr()); fixRemove(node); RBNodeTraits::deleteNode(node); return true; } return false; } bool removeMin() override { NodePtr node = Super::removeMinInner(); if(node != NodePtr()){ assert(RBNodeTraits::left(node) == NodePtr() || RBNodeTraits::right(node) == NodePtr()); fixRemove(node); RBNodeTraits::deleteNode(node); return true; } return false; } bool removeMax() override { NodePtr node = Super::removeMaxInner(); if(node != NodePtr()){ assert(RBNodeTraits::left(node) == NodePtr() || RBNodeTraits::right(node) == NodePtr()); fixRemove(node); RBNodeTraits::deleteNode(node); return true; } return false; } bool isValid() const override { if(!Super::isValid()) return false; if(Super::root != NodePtr()){ if(RBNodeTraits::color(Super::root) != RBNodeTraits::black()) //assert(false); return false; std::vector<NodePtr> nodes; std::vector<unsigned int> bhs; unsigned int bh = 0; bool isBhSet = false; nodes.push_back(Super::root); bhs.push_back(1); for(size_t i = 0;i < nodes.size();++ i){ NodePtr node = nodes[i]; NodePtr l = RBNodeTraits::left(node); NodePtr r = RBNodeTraits::right(node); if(RBNodeTraits::color(node) == RBNodeTraits::red() && (RBNodeTraits::color(r) != RBNodeTraits::black() || RBNodeTraits::color(l) != RBNodeTraits::black())) //assert(false); return false; if(l != NodePtr()){ bhs.push_back(RBNodeTraits::color(l) == RBNodeTraits::black() ? (bhs[i] + 1) : bhs[i]); nodes.push_back(l); }else if(!isBhSet){ bh = bhs[i]; isBhSet = true; }else if(bhs[i] != bh) //assert(false); return false; if(r != NodePtr()){ bhs.push_back(RBNodeTraits::color(r) == RBNodeTraits::black() ? (bhs[i] + 1) : bhs[i]); nodes.push_back(r); }else if(!isBhSet){ bh = bhs[i]; isBhSet = true; }else if(bhs[i] != bh) //assert(false); return false; } } return true; } protected: void fixInsert(NodePtr node){ assert(RBNodeTraits::color(node) == RBNodeTraits::red()); assert(RBNodeTraits::left(node) == NodePtr()); assert(RBNodeTraits::right(node) == NodePtr()); NodePtr p = RBNodeTraits::parent(node); while(RBNodeTraits::color(p) == RBNodeTraits::red()){ NodePtr pp = RBNodeTraits::parent(p); NodePtr uncle = NodePtr(); if(p == RBNodeTraits::left(pp)){ uncle = RBNodeTraits::right(pp); if(RBNodeTraits::color(uncle) == RBNodeTraits::red()){ RBNodeTraits::color(p, RBNodeTraits::black()); RBNodeTraits::color(uncle, RBNodeTraits::black()); RBNodeTraits::color(pp, RBNodeTraits::red()); node = pp; }else{ if(node == RBNodeTraits::right(p)){ Super::leftRotate(p); }else{ node = p; } RBNodeTraits::color(node, RBNodeTraits::black()); RBNodeTraits::color(pp, RBNodeTraits::red()); Super::rightRotate(pp); break; } }else if(p == RBNodeTraits::right(pp)){ assert(p == RBNodeTraits::right(pp)); uncle = RBNodeTraits::left(pp); if(RBNodeTraits::color(uncle) == RBNodeTraits::red()){ RBNodeTraits::color(p, RBNodeTraits::black()); RBNodeTraits::color(uncle, RBNodeTraits::black()); RBNodeTraits::color(pp, RBNodeTraits::red()); node = pp; }else{ if(node == RBNodeTraits::left(p)){ Super::rightRotate(p); }else{ node = p; } RBNodeTraits::color(node, RBNodeTraits::black()); RBNodeTraits::color(pp, RBNodeTraits::red()); Super::leftRotate(pp); break; } }else{ assert("corrupted data structure"); } p = RBNodeTraits::parent(node); } RBNodeTraits::color(Super::root, RBNodeTraits::black()); //assert(isValid()); } void fixRemove(NodePtr node){ if(node != NodePtr() && RBNodeTraits::color(node) != RBNodeTraits::red()){ NodePtr p = RBNodeTraits::parent(node); node = (RBNodeTraits::left(node) == NodePtr() ? RBNodeTraits::right(node): RBNodeTraits::left(node)); while(node != Super::root && RBNodeTraits::color(node) == RBNodeTraits::black()){ if(node == RBNodeTraits::left(p)){ NodePtr sib = RBNodeTraits::right(p); if(RBNodeTraits::color(sib) == RBNodeTraits::red()){ RBNodeTraits::color(sib, RBNodeTraits::black()); RBNodeTraits::color(p, RBNodeTraits::red()); sib = RBNodeTraits::left(sib); Super::leftRotate(p); } if(sib == NodePtr()){ assert(RBNodeTraits::color(p) == RBNodeTraits::red()); node = p; break; } if(RBNodeTraits::color(RBNodeTraits::left(sib)) == RBNodeTraits::red()){ RBNodeTraits::color(RBNodeTraits::left(sib), RBNodeTraits::color(p)); RBNodeTraits::color(p, RBNodeTraits::black()); Super::rightRotate(sib); Super::leftRotate(p); break; }else if(RBNodeTraits::color(RBNodeTraits::right(sib)) == RBNodeTraits::red()){ RBNodeTraits::color(RBNodeTraits::right(sib), RBNodeTraits::color(p)); Super::leftRotate(p); break; }else{ RBNodeTraits::color(sib, RBNodeTraits::red()); node = p; } }else{ NodePtr sib = RBNodeTraits::left(p); if(RBNodeTraits::color(sib) == RBNodeTraits::red()){ RBNodeTraits::color(sib, RBNodeTraits::black()); RBNodeTraits::color(p, RBNodeTraits::red()); sib = RBNodeTraits::right(sib); Super::rightRotate(p); } if(sib == NodePtr()){ assert(RBNodeTraits::color(p) == RBNodeTraits::red()); node = p; break; } if(RBNodeTraits::color(RBNodeTraits::right(sib)) == RBNodeTraits::red()){ RBNodeTraits::color(RBNodeTraits::right(sib), RBNodeTraits::color(p)); RBNodeTraits::color(p, RBNodeTraits::black()); Super::leftRotate(sib); Super::rightRotate(p); break; }else if(RBNodeTraits::color(RBNodeTraits::left(sib)) == RBNodeTraits::red()){ RBNodeTraits::color(RBNodeTraits::left(sib), RBNodeTraits::color(p)); Super::rightRotate(p); break; }else{ RBNodeTraits::color(sib, RBNodeTraits::red()); node = p; } } p = RBNodeTraits::parent(node); } if(node != NodePtr()) RBNodeTraits::color(node, RBNodeTraits::black()); //assert(isValid()); } } }; template<class K, class V, class C = std::less<K> > using RBTree = RBTreeBase < K, V, RBNodeTraits<K, V, RBNode<K, V>, RBNodeBase<RBNode<K, V> > >, C > ; template<class AVLNode> struct AVLNodeBase : public BSTNodeBase<AVLNode>{ typedef typename BSTNodeBase<AVLNode>::NodePtr NodePtr; template<class Ptr> static int height(Ptr node){ if(node == Ptr()) return -1; return node->h; } static void height(NodePtr node, int h){ assert(node != NodePtr()); node->h= h; } static void swap(NodePtr node1, NodePtr node2){ BSTNodeBase<AVLNode>::swap(node1, node2); std::swap(node1->h, node2->h); } }; template<class K, class V, class AVLNode, class AVLNodeBase> struct AVLNodeTraits : public BSTNodeTraits<K, V, AVLNode, AVLNodeBase>{ template<class Ptr> static int height(Ptr node){ return AVLNodeBase::height(node); } template<class Ptr> static void height(Ptr node, int h){ AVLNodeBase::height(node, h); } }; template<class K, class V> struct AVLNode{ typedef AVLNode* NodePtr; typedef std::pair<K, V> Pair; AVLNode(const K& k, const V& v) : AVLNode(k, v, NodePtr(), NodePtr(), NodePtr(), 1){ } AVLNode(const K& k, const V& v, NodePtr p, NodePtr l, NodePtr r, unsigned int count) :value(k, v), p(p), l(l), r(r), c(count), h(0){ } private: friend class AVLNodeBase<AVLNode<K, V> >; friend class BSTNodeBase<AVLNode<K, V> >; Pair value; NodePtr p, l, r; unsigned int c; int h; }; template<class K, class V, class AVLNodeTraitsParam, class C = std::less<K> > class AVLTreeBase : public BinarySearchTreeBase<K, V, AVLNodeTraitsParam, C>{ typedef BinarySearchTreeBase<K, V, AVLNodeTraitsParam, C> Super; public: typedef typename Super::BSTNodeTraits AVLNodeTraits; typedef typename Super::NodePtr NodePtr; AVLTreeBase(const C& comparator = C()) : Super(comparator){ } void put(const K& k, const V& v) override { NodePtr node = Super::putInner(k, v); if(node != NodePtr()) fixInsert(node); } bool remove(const K&k) override { NodePtr node = Super::removeInner(k); if(node != NodePtr()){ assert(AVLNodeTraits::left(node) == NodePtr() || AVLNodeTraits::right(node) == NodePtr()); fixRemove(node); AVLNodeTraits::deleteNode(node); return true; } return false; } bool removeMin() override { NodePtr node = Super::removeMinInner(); if(node != NodePtr()){ assert(AVLNodeTraits::left(node) == NodePtr() || AVLNodeTraits::right(node) == NodePtr()); fixRemove(node); AVLNodeTraits::deleteNode(node); return true; } return false; } bool removeMax() override { NodePtr node = Super::removeMaxInner(); if(node != NodePtr()){ assert(AVLNodeTraits::left(node) == NodePtr() || AVLNodeTraits::right(node) == NodePtr()); fixRemove(node); AVLNodeTraits::deleteNode(node); return true; } return false; } int height() const override { if(Super::root == NodePtr()) return -1; return AVLNodeTraits::height(Super::root); } bool isValid() const override { if(!Super::isValid()) return false; if(Super::root != NodePtr()){ std::vector<NodePtr> nodes; nodes.push_back(Super::root); for(size_t i = 0;i < nodes.size();++ i){ NodePtr node = nodes[i]; NodePtr l = AVLNodeTraits::left(node); NodePtr r = AVLNodeTraits::right(node); if(l != NodePtr()){ nodes.push_back(l); } if(r != NodePtr()){ nodes.push_back(r); } auto lH = AVLNodeTraits::height(l); auto rH = AVLNodeTraits::height(r); if(AVLNodeTraits::height(node) != std::max(lH, rH) + 1){ //std::cout << "key : " << *AVLNodeTraits::key(node) << std::endl; assert(false); return false; } if(lH > rH + 1 || rH > lH + 1){ assert(false); return false; } } } return true; } protected: void fixInsert(NodePtr node){ assert(AVLNodeTraits::left(node) == NodePtr()); assert(AVLNodeTraits::right(node) == NodePtr()); assert(AVLNodeTraits::height(node) == 0); auto p = AVLNodeTraits::parent(node); auto h = AVLNodeTraits::height(node) + 1; if(p != NodePtr() && h > AVLNodeTraits::height(p)){ AVLNodeTraits::height(p, h); node = p; p = AVLNodeTraits::parent(node); while(p != NodePtr()){ if(node == AVLNodeTraits::left(p)){ auto sib = AVLNodeTraits::right(p); auto deltaH = AVLNodeTraits::height(node) - AVLNodeTraits::height(sib); if(deltaH < -1 || deltaH > 1){ assert(deltaH == 2 || deltaH == -2); if(AVLNodeTraits::height(AVLNodeTraits::left(node)) + 1 == AVLNodeTraits::height(node)){ assert(AVLNodeTraits::height(AVLNodeTraits::right(node)) + 2 == AVLNodeTraits::height(node) || AVLNodeTraits::height(AVLNodeTraits::right(node)) + 1 == AVLNodeTraits::height(node)); Super::rightRotate(p); h = AVLNodeTraits::height(AVLNodeTraits::left(p)) + 1; if(h < AVLNodeTraits::height(p)){ AVLNodeTraits::height(p, h); break; } assert(h == AVLNodeTraits::height(p)); AVLNodeTraits::height(node, h + 1); }else{ auto r = AVLNodeTraits::right(node); h = AVLNodeTraits::height(r); assert(AVLNodeTraits::height(AVLNodeTraits::left(node)) + 2 == AVLNodeTraits::height(node)); assert(h + 1 == AVLNodeTraits::height(node)); Super::leftRotate(node); Super::rightRotate(p); AVLNodeTraits::height(r, h + 1); AVLNodeTraits::height(node, h); AVLNodeTraits::height(p, h); break; } }else{ h = AVLNodeTraits::height(node) + 1; if(h <= AVLNodeTraits::height(p)){ assert(h == AVLNodeTraits::height(p)); break; } AVLNodeTraits::height(p, h); node = p; } }else{ assert(node == AVLNodeTraits::right(p) && "corrupted data structure" != nullptr); auto sib = AVLNodeTraits::left(p); auto deltaH = AVLNodeTraits::height(node) - AVLNodeTraits::height(sib); if(deltaH < -1 || deltaH > 1){ assert(deltaH == 2 || deltaH == -2); if(AVLNodeTraits::height(AVLNodeTraits::right(node)) + 1 == AVLNodeTraits::height(node)){ assert(AVLNodeTraits::height(AVLNodeTraits::left(node)) + 2 == AVLNodeTraits::height(node) || AVLNodeTraits::height(AVLNodeTraits::left(node)) + 1 == AVLNodeTraits::height(node)); Super::leftRotate(p); h = AVLNodeTraits::height(AVLNodeTraits::right(p)) + 1; if(h < AVLNodeTraits::height(p)){ AVLNodeTraits::height(p, h); break; } AVLNodeTraits::height(node, h + 1); }else{ auto l = AVLNodeTraits::left(node); h = AVLNodeTraits::height(l); assert(AVLNodeTraits::height(AVLNodeTraits::right(node)) + 2 == AVLNodeTraits::height(node)); assert(h + 1 == AVLNodeTraits::height(node)); Super::rightRotate(node); Super::leftRotate(p); AVLNodeTraits::height(l, h + 1); AVLNodeTraits::height(node, h); AVLNodeTraits::height(p, h); break; } }else{ h = AVLNodeTraits::height(node) + 1; if(h <= AVLNodeTraits::height(p)){ assert(h == AVLNodeTraits::height(p)); break; } AVLNodeTraits::height(p, h); node = p; } } p = AVLNodeTraits::parent(node); } } //assert(isValid()); } void fixRemove(NodePtr node){ auto p = AVLNodeTraits::parent(node); if(p != NodePtr()){ { NodePtr l = AVLNodeTraits::left(p); NodePtr r = AVLNodeTraits::right(p); if(AVLNodeTraits::height(l) > AVLNodeTraits::height(r) + 1){ node = r; }else if(AVLNodeTraits::height(r) > AVLNodeTraits::height(l) + 1){ node = l; }else{ auto h = std::max(AVLNodeTraits::height(r), AVLNodeTraits::height(l)) + 1; if(h >= AVLNodeTraits::height(p)){ assert(h == AVLNodeTraits::height(p)); assert(isValid()); return; } AVLNodeTraits::height(p, h); node = p; p = AVLNodeTraits::parent(node); } } while(p != NodePtr()){ auto h = AVLNodeTraits::height(node); /*if(node != NodePtr()) std::cout << "key to adjust : " << *AVLNodeTraits::key(node) << std::endl; std::cout << "parent key : " << *AVLNodeTraits::key(p) << std::endl; if(AVLNodeTraits::parent(p) != NodePtr()){ std::cout << "parent of parent key : " << *AVLNodeTraits::key(AVLNodeTraits::parent(p)) << std::endl; }*/ if(node == AVLNodeTraits::left(p)){ auto sib = AVLNodeTraits::right(p); auto sibH = AVLNodeTraits::height(sib); auto deltaH = h - sibH; /*if(sib != NodePtr()) std::cout << "right sib key : " << *AVLNodeTraits::key(sib) << std::endl;*/ if(deltaH < -1 || deltaH > 1){ assert(deltaH == 2 || deltaH == -2); /*if(AVLNodeTraits::right(sib) != NodePtr()) std::cout << "right child of right sib key : " << *AVLNodeTraits::key(AVLNodeTraits::right(sib)) << std::endl; if(AVLNodeTraits::left(sib) != NodePtr()) std::cout << "left child of right sib key : " << *AVLNodeTraits::key(AVLNodeTraits::left(sib)) << std::endl;*/ if(AVLNodeTraits::height(AVLNodeTraits::right(sib)) + 1 == sibH){ Super::leftRotate(p); if(h + 1 == AVLNodeTraits::height(AVLNodeTraits::right(p))){ AVLNodeTraits::height(p, h + 2); AVLNodeTraits::height(sib, h + 3); break; } AVLNodeTraits::height(p, h + 1); AVLNodeTraits::height(sib, h + 2); node = sib; }else{ Super::rightRotate(sib); Super::leftRotate(p); AVLNodeTraits::height(sib, h + 1); AVLNodeTraits::height(p, h + 1); node = AVLNodeTraits::parent(p); AVLNodeTraits::height(node, h + 2); } }else{ h = std::max(h, sibH) + 1; if(h >= AVLNodeTraits::height(p)){ assert(h == AVLNodeTraits::height(p)); break; } AVLNodeTraits::height(p, h); node = p; } }else{ assert(node == AVLNodeTraits::right(p)); auto sib = AVLNodeTraits::left(p); auto sibH = AVLNodeTraits::height(sib); auto deltaH = h - sibH; /*if(sib != NodePtr()) std::cout << "left sib key : " << *AVLNodeTraits::key(sib) << std::endl;*/ if(deltaH < -1 || deltaH > 1){ assert(deltaH == 2 || deltaH == -2); /*if(AVLNodeTraits::left(sib) != NodePtr()) std::cout << "left child of left sib key : " << *AVLNodeTraits::key(AVLNodeTraits::left(sib)) << std::endl; if(AVLNodeTraits::right(sib) != NodePtr()) std::cout << "right child of left sib key : " << *AVLNodeTraits::key(AVLNodeTraits::right(sib)) << std::endl;*/ if(AVLNodeTraits::height(AVLNodeTraits::left(sib)) + 1 == sibH){ Super::rightRotate(p); if(h + 1 == AVLNodeTraits::height(AVLNodeTraits::left(p))){ AVLNodeTraits::height(p, h + 2); AVLNodeTraits::height(sib, h + 3); break; } AVLNodeTraits::height(p, h + 1); AVLNodeTraits::height(sib, h + 2); node = sib; }else{ Super::leftRotate(sib); Super::rightRotate(p); AVLNodeTraits::height(sib, h + 1); AVLNodeTraits::height(p, h + 1); node = AVLNodeTraits::parent(p); AVLNodeTraits::height(node, h + 2); } }else{ h = std::max(h, sibH) + 1; if(h >= AVLNodeTraits::height(p)){ assert(h == AVLNodeTraits::height(p)); break; } AVLNodeTraits::height(p, h); node = p; } } p = AVLNodeTraits::parent(node); } } assert(isValid()); } }; template<class K, class V, class C = std::less<K> > using AVLTree = AVLTreeBase < K, V, AVLNodeTraits<K, V, AVLNode<K, V>, AVLNodeBase<AVLNode<K, V> > >, C > ; template<class NodePtr> void output(NodePtr node, unsigned int depth, const char *ch = " "){ for(unsigned int i = 0;i < depth;++ i) std::cout << ch; auto count = node->childCount(); std::cout << node->kvpCount() << ':'; for(unsigned int i = 0;i < count;++ i) std::cout << '(' << node->key(i) << ',' << node->value(i) << ')' << ch; std::cout << std::endl; if(!node->isLeaf()) for(unsigned int i = 0;i <= count;++ i) output(node->child(i), depth + 1, ch); } template<class K, class V, class KVPArray = std::vector<std::pair<K, V> > > class BTreeNode{ public: BTreeNode(){ } BTreeNode(const BTreeNode&) = delete; BTreeNode& operator=(const BTreeNode&) = delete; size_t childCount() const { return items.size(); } size_t itemsCount() const { return items.size(); } size_t kvpCount() const { return count; } bool isLeaf() const { return nullptr == children; } template<class NodeTraits> const V* get(const K& k, NodeTraits traits) const { auto node = getNode(k, traits); return nullptr == node.first || static_cast<size_t>(-1) == node.second ? nullptr : &node.first->items[node.second].second; } const BTreeNode* child(size_t index) const { return nullptr == children || index > items.size() ? nullptr : children[index]; } const K& key(size_t index) const { return items[index].first; } const V& value(size_t index) const{ return items[index]. second; } const K* min() const { if(items.size() == 0) return nullptr; if(nullptr == children) return &key(0); return children[0]->min(); } const BTreeNode* minNode() const { if(nullptr == children) return this; return children[0]->minNode(); } const K* max() const{ if(items.size() == 0) return nullptr; if(nullptr == children) return &key(items.size() - 1); return children[items.size()]->max(); } const BTreeNode* maxNode() const { if(nullptr == children) return this; return children[items.size()]->max(); } template<class NodeTraits> static const K* floor(const BTreeNode* node, const K& k, NodeTraits traits) { auto pos = std::lower_bound(node->items.begin(), node->items.end(), k, traits); size_t index = pos - node->items.begin(); if(pos != node->items.end() && !traits(k, *pos)) return &pos->first; if(nullptr != node->children){ auto ret = floor(node->children[index], k, traits); if(nullptr != ret) return ret; } if(0 == index) return nullptr; return &node->key(index - 1); } template<class NodeTraits> static const K* ceil(const BTreeNode* node, const K& k, NodeTraits traits) { auto pos = std::lower_bound(node->items.begin(), node->items.end(), k, traits); size_t index = pos - node->items.begin(); if(pos != node->items.end() && !traits(k, *pos)) return &pos->first; if(nullptr != node->children){ auto ret = ceil(node->children[index], k, traits); if(nullptr != ret) return ret; } if(pos == node->items.end()) return nullptr; return &pos->first; } template<class NodeTraits> static unsigned int rank(const BTreeNode* node, const K& k, NodeTraits traits) { auto pos = std::lower_bound(node->items.begin(), node->items.end(), k, traits); size_t index = pos - node->items.begin(); unsigned int sum = index; if(nullptr != node->children){ for(size_t i = 0;i < index;++ i) sum += node->children[i]->count; sum += rank(node->children[index], k, traits); } return sum; } template<class NodeTraits> static const K* select(const BTreeNode* node, size_t index, NodeTraits traits) { if(index >= node->count) return nullptr; if(nullptr == node->children) return &node->key(index); for(size_t i = 0;i <= node->childCount();++ i){ size_t sz = node->child(i)->count; //std::cout << "index is " << index << " sz is " << sz << std::endl; if(index == sz) return &node->key(i); if(index < sz) return select(node->child(i), index, traits); index -= (sz + 1); } return nullptr; } ~BTreeNode(){ if(nullptr != children && count > 0){ for(size_t i = 0;i <= items.size();++ i) delete children[i]; } delete[] children; } template<class Stream> Stream& printID(Stream& stream) const { if(items.size() > 0) stream << items[0].first; return stream << "...."; } template<class NodeTraits> bool isSizeValid(NodeTraits traits) const { size_t sz = childCount(); if(sz < traits.num() - 1){ printID(std::cout) << " : size less than " << traits.num() - 1 << std::endl; return false; } if(sz >= 2 * traits.num()){ printID(std::cout) << " : size not less than " << 2 * traits.num() << std::endl; return false; } return true; } template<class NodeTraits> bool isValid(NodeTraits traits) const { for(size_t i = 1;i < items.size();++ i) if (!traits(items[i - 1], items[i])){ printID(std::cout) << " : " << i << "th key not in order" << std::endl; return false; } size_t sum = items.size(); if(nullptr != children){ for(size_t i = 0;i <= items.size();++ i){ if(!children[i]->isSizeValid(traits) || !children[i]->isValid(traits)) return false; sum += children[i]->count; } for(size_t i = 0;i < items.size();++ i){ if(!traits(*children[i]->max(), items[i])){ printID(std::cout) << " : " << i << "th key less than left child's max" << std::endl; return false; } if(!traits(items[i], *children[i + 1]->min())){ printID(std::cout) << " : " << i << "th key not less than right child's min" << std::endl; return false; } } } if(sum != count){ printID(std::cout) << "recorded k-v size is : " << count << "but actual size is : " << sum << std::endl; return false; } return true; } template<class NodeTraits> static BTreeNode* put(BTreeNode* root, const K& k, const V& v, NodeTraits traits){ // Enforce that the number of children for a BTreeNode must be at least 3 if(traits.num() <= 2) return nullptr; BTreeNode* newNode = root->put(k, v, traits); if(nullptr != newNode && newNode != root){ auto ret = new BTreeNode; ret->children = new BTreeNode*[2 * traits.num()]; ret->items.push_back(root->items.back()); root->items.pop_back(); ret->children[0] = root; ret->children[1] = newNode; ret->count = root->count + newNode->count + 1; root = ret; } return root; } template<class NodeTraits> static BTreeNode* copy(BTreeNode* node, NodeTraits traits){ if(nullptr == node) return nullptr; return new BTreeNode(*node, traits); } template<class NodeTraits> static bool remove(BTreeNode*& node, const K& k, NodeTraits traits){ if(removeInner(node, k, traits)){ node = adjustNode(node); return true; } return false; } template<class NodeTraits> static bool removeMin(BTreeNode*& node, NodeTraits traits) { if(nullptr == node && node->count == 0) return false; node->removeMin(traits); node = adjustNode(node); return true; } template<class NodeTraits> static bool removeMax(BTreeNode*& node, NodeTraits traits) { if(nullptr == node && node->count == 0) return false; node->removeMax(traits); node = adjustNode(node); return true; } private: static BTreeNode* adjustNode(BTreeNode* node){ while(node->childCount() == 0){ if(nullptr == node->children){ node = nullptr; break; } BTreeNode* toDelete = node; node = node->children[0]; //avoid child link being deleted. toDelete->count = 0; delete toDelete; } return node; } template<class NodeTraits> void removeMin(NodeTraits traits) { if(count == 0) return; if(nullptr == children) items.erase(items.begin()); else ensureNum(0, traits)->removeMin(traits); --count; } template<class NodeTraits> void removeMax(NodeTraits traits) { if(count == 0) return; if(nullptr == children) items.pop_back(); else ensureNum(items.size(), traits)->removeMax(traits); --count; } /* * Merge the {@param index}-th child and {@param index + 1}-th child * and the key at {@param index} into one node. * Assuming that both the left and right child have {@value num - 1} keys. * */ template<class NodeTraits> BTreeNode* mergeAt(size_t index, NodeTraits traits){ BTreeNode* lc = children[index]; BTreeNode* rc = children[index + 1]; assert(lc->items.size() == traits.num() - 1); assert(rc->items.size() == traits.num() - 1); // adjust children's link first for(size_t i = index + 1;i < items.size();++ i) children[i] = children[i + 1]; if(nullptr != lc->children){ assert(nullptr != rc->children); std::copy(rc->children, rc->children + rc->items.size() + 1, lc->children + lc->items.size() + 1); } //move items after link is adjusted. lc->items.push_back(items[index]); items.erase(items.begin() + index); lc->items.insert(lc->items.end(), rc->items.begin(), rc->items.end()); //adjust counts lc->count += (rc->count + 1); assert(lc->items.size() == 2 * traits.num() - 1); //avoiding child link being destructed rc->items.clear(); rc->count = 0; delete rc; return lc; } /* * Insert the {@var index}-th key to the first key of the {@param index + 1}-th child * And move the last key of {@var index}-th child to the {@param index)-th key. * */ template<class NodeTraits> BTreeNode* l2r(size_t index, NodeTraits traits){ BTreeNode* lc = children[index]; BTreeNode* rc = children[index + 1]; if(nullptr != rc->children){ assert(nullptr != lc->children); for(size_t i = rc->items.size() + 1;i > 0;-- i) rc->children[i] = rc->children[i - 1]; rc->children[0] = lc->children[lc->items.size()]; } rc->items.insert(rc->items.begin(), items[index]); items[index] = lc->items.back(); lc->items.pop_back(); if(nullptr != rc->children){ assert(nullptr != lc->children); lc->count -= (rc->children[0]->count + 1); rc->count += (rc->children[0]->count + 1); }else{ assert(nullptr == lc->children); -- lc->count; ++ rc->count; } return lc; } /* * Insert the {@var index}-th key to the first key of the {@param index + 1}-th child * And move the last key of {@var index}-th child to the {@param index)-th key. * */ template<class NodeTraits> BTreeNode* r2l(size_t index, NodeTraits traits){ BTreeNode* lc = children[index]; BTreeNode* rc = children[index + 1]; if(nullptr != lc->children){ assert(nullptr != rc->children); lc->children[lc->items.size() + 1] = rc->children[0]; for(size_t i = 0;i < rc->items.size();++ i) rc->children[i] = rc->children[i + 1]; } lc->items.push_back(items[index]); items[index] = *rc->items.begin(); rc->items.erase(rc->items.begin()); if(nullptr != lc->children){ assert(nullptr != rc->children); rc->count -= (lc->children[lc->items.size()]->count + 1); lc->count += (lc->children[lc->items.size()]->count + 1); }else{ assert(nullptr == rc->children); -- rc->count; ++ lc->count; } return lc; } template<class NodeTraits> BTreeNode* ensureNum(size_t index, NodeTraits traits){ BTreeNode* lc = children[index]; if(lc->items.size() >= traits.num()) return lc; if(index == items.size()){ --index; if(children[index]->items.size() < traits.num()) return mergeAt(index, traits); l2r(index, traits); }else{ if(children[index + 1]->items.size() < traits.num()) return mergeAt(index, traits); r2l(index, traits); } assert(lc->items.size() >= traits.num()); return lc; } template<class NodeTraits> static bool removeInner(BTreeNode* node, const K& k, NodeTraits traits){ auto pos = std::lower_bound(node->items.begin(), node->items.end(), k, traits); size_t index = pos - node->items.begin(); if(pos != node->items.end() && !traits(k, *pos)){ return node->removeAt(index, traits); } //output(node, 0); if(nullptr != node->children && removeInner(node->ensureNum(index, traits), k, traits)){ //pintID(std::cout); --node->count; return true; } return false; } template<class NodeTraits> BTreeNode(const BTreeNode& node, NodeTraits traits){ items = node.items; count = node.count; if(nullptr != node.children){ children = new BTreeNode*[traits.num() * 2]; for(size_t i = 0;i <= items.size();++ i) children[i] = new BTreeNode(*node.children[i], traits); } } template<class NodeTraits> bool removeAt(size_t index, NodeTraits traits){ if(index >= items.size()) return false; --count; if(nullptr == children){ items.erase(items.begin() + index); }else{ auto lc = children[index], rc = children[index + 1]; size_t ls = lc->items.size(), rs = rc->items.size(); if(ls < traits.num() && rs < traits.num()){ return mergeAt(index, traits)->removeAt(traits.num() - 1, traits); }else if(ls >= rs){ items[index] = lc->maxNode()->items.back(); lc->removeMax(traits); }else{ items[index] = rc->minNode()->items[0]; rc->removeMin(traits); } } return true; } BTreeNode* maxNode(){ if(nullptr == children) return this; return children[items.size()]->maxNode(); } BTreeNode* minNode(){ if(nullptr == children) return this; return children[0]->minNode(); } template<class NodeTraits> std::pair<const BTreeNode*, size_t> getNode(const K& k, NodeTraits traits) const { auto pos = std::lower_bound(items.begin(), items.end(), k, traits); size_t index = pos - items.begin(); if(pos != items.end() && !traits(k, *pos)) return {this, index}; if(nullptr == children) return {nullptr, static_cast<size_t>(-1)}; return children[index]->getNode(k, traits); } template<class NodeTraits, class Iterator> inline BTreeNode* insertItem(Iterator pos, const K& k, const V& v, NodeTraits traits){ if(items.size() >= 2 * traits.num() - 1){ BTreeNode* ret = new BTreeNode; auto& retItems = ret->items; if(static_cast<size_t>(pos - items.begin()) >= traits.num()){ retItems.insert(retItems.end(), items.begin() + traits.num(), pos); retItems.push_back({k, v}); retItems.insert(retItems.end(), pos, items.end()); items.resize(traits.num()); }else{ retItems.insert(retItems.end(), items.begin() + traits.num() - 1, items.end()); items.resize(traits.num() - 1); items.insert(pos, {k, v}); } this->count = traits.num() - 1; ret->count = traits.num(); assert(this->items.size() == traits.num()); assert(ret->items.size() == traits.num()); return ret; }else{ items.insert(pos, {k, v}); ++count; } return this; } template<class NodeTraits> BTreeNode* put(const K& k, const V& v, NodeTraits traits){ //printID(std::cout) << " put: " << k << ", " << v << std::endl; auto pos = std::lower_bound(items.begin(), items.end(), k, traits); if(pos != items.end() && !traits(k, *pos)){ //printID(std::cout) << " previous value is : " << pos->second << std::endl; pos->second = v; return nullptr; } if(nullptr != children){ //printID(std::cout) << " internal node : " << children << std::endl; size_t index = pos - items.begin(); auto child = children[index]; auto newNode = child->put(k, v, traits); // child->printID(std::cout << "child ") << std::endl; if(nullptr == newNode) return nullptr; if(newNode == child){ ++ count; return this; } // newNode->printID(std::cout << "new ") << std::endl; BTreeNode* ret = insertItem(pos, child->items.back().first, child->items.back().second, traits); child->items.pop_back(); if(this != ret){ ret->children = new BTreeNode*[2 * traits.num()]; if(index == 2 * traits.num() - 1){ ret->children[traits.num()] = newNode; }else{ ret->children[traits.num()] = children[2 * traits.num() - 1]; for(size_t i = 2 * traits.num() - 1;i > index + 1;-- i) children[i] = children[i - 1]; children[index + 1] = newNode; } std::copy(children + traits.num(), children + 2 * traits.num(), ret->children); for(size_t i = 0;i < traits.num();++ i) this->count += this->children[i]->count; for(size_t i = 0;i <= traits.num();++ i) ret->count += ret->children[i]->count; }else{ for(size_t i = items.size();i > index + 1;-- i) children[i] = children[i - 1]; children[index + 1] = newNode; } return ret; } // printID(std::cout << "leaf node ") << std::endl; return insertItem(pos, k, v, traits); } KVPArray items; BTreeNode **children = nullptr; size_t count = 0; }; template<class K, class V, class C = std::less<K> > class BTreeBase : public OrderedSymbolTable<K, V>{ typedef OrderedSymbolTable<K, V> Super; public: BTreeBase(unsigned int num, const C& comparator = C()) : traits(num, comparator){ if(num < 3) throw std::invalid_argument("degree must be greater than 2 "); } BTreeBase(const BTreeBase& tree){ traits = tree.traits; root = Node::copy(tree.root, traits); } BTreeBase& operator=(const BTreeBase&) = delete; static const int NUM = 6; typedef BTreeNode<K, V> Node; typedef Node* NodePtr; void put(const K& k, const V& v) override { if (NodePtr() == root) root = new Node; root = Node::put(root, k, v, traits); //assert(root->isValid(traits)); } const Node* getRoot() const { return root; } const V* get(const K& k) const override { return NodePtr() == root ? nullptr : root->get(k, traits); } bool remove(const K& k) override { if(NodePtr() == root) return false; return Node::remove(root, k, traits); } unsigned int size() const override { return NodePtr() == root ? 0 : root->kvpCount(); } void clear() override { delete root; root = NodePtr(); } const K* min() const override { return NodePtr() == root ? nullptr : root->min(); } const K* max() const override { return NodePtr() == root ? nullptr : root->max(); } const K* floor(const K& k) const override { return NodePtr() == root ? nullptr : Node::floor(root, k, traits); } const K* ceil(const K& k) const override { return NodePtr() == root ? nullptr : Node::ceil(root, k, traits); } unsigned int rank(const K& k) const override { return NodePtr() == root ? 0 : Node::rank(root, k, traits); } const K* select(unsigned int index) const override { return NodePtr() == root ? nullptr : Node::select(root, index, traits); } unsigned int size(const K& l, const K& h) const override { unsigned int i = rank(l), j = rank(h); return i > j ? 0 : (nullptr != get(h) ? j - i + 1 : j - i); } bool isValid() const override { return NodePtr() == root || root->isValid(traits); } bool removeMin() override { return Node::removeMin(root, traits); } bool removeMax() override { return Node::removeMax(root, traits); } ~BTreeBase(){ delete root;} protected: struct BTreeIterator : public Super::IteratorImpl{ unsigned int index; const BTreeBase* tree; BTreeIterator(unsigned int index, const BTreeBase* tree) : index(index), tree(tree){} virtual void next() override{ ++index; } virtual bool equals(const typename Super::IteratorImpl& i) const override { const BTreeIterator* itor = dynamic_cast<const BTreeIterator*>(&i); return nullptr != itor && itor->index == index && itor->tree == tree; } virtual void assign(const typename Super::IteratorImpl& i) { const BTreeIterator* itor = dynamic_cast<const BTreeIterator*>(&i); if(nullptr != itor){ index = itor->index; tree = itor->tree; } } virtual const K& key() const { return *tree->select(index); } virtual const V& value() const { return *tree->get(key()); } virtual typename Super::IteratorImpl* copy() const { return new BTreeIterator(index, tree); } }; typename Super::IteratorImpl *implBegin() const override{ return new BTreeIterator(0, this); } typename Super::IteratorImpl *implEnd() const override{ return new BTreeIterator(size(), this); } private: NodePtr root = NodePtr(); struct NodeTraits{ size_t n = 0; C comparator; NodeTraits (size_t n = NUM, const C& comparator = C()) : n(n), comparator(comparator){} size_t num(){return n;} bool operator()(const std::pair<K, V>& kvp1, const std::pair<K, V>& kvp2){ return kvp1.first < kvp2.first; } bool operator()(const K& k, const std::pair<K, V>& kvp){ return k < kvp.first; } bool operator()(const std::pair<K, V>& kvp, const K& k){ return kvp.first < k; } }traits; }; } #endif //MY_BINARY_SEARCH_TREE_H
true
91d38d1c384633c37defaf1ad84aa8ce2869e617
C++
beltransen/arduino
/serial_comm/serial_comm.ino
UTF-8
358
2.953125
3
[]
no_license
/** Comunicacion por puerto de serie **/ void setup() { // Iniciamos conexion con puerto de serie Serial.begin(19200); // Baudrate correspondiente } void loop() { // Si hay datos para leer, los guardamos y mostramos if(Serial.available()>0){ char comando = Serial.read(); Serial.print("Recibido: "); Serial.println(comando); } }
true
38d5afd5173de4cbd502c34df7c38fc4e8956785
C++
15831944/barry_dev
/src/export_lib/router/Tester/main.cpp
UTF-8
9,834
2.53125
3
[]
no_license
/*generated by gencode.py *author: bill xia *modify history: Ricky Chen 2007.4.3 */ #include "aosApi.h" #include <stdio.h> #include <iostream.h> int main(int argc,char ** argv) { char result[10240]; int ret = 0; int len = 10240; int total_case = 0; int fail_case = 0; int index=1; int count=0; int maxruntime=2; FILE *fp=NULL; while(index<argc) { if(strcmp(argv[index],"-t")==0) { maxruntime=atoi(argv[++index]); index++; continue; } if(strcmp(argv[index],"-h")==0) { cout<<"----------------------helps for usage------------------------------------------"<<endl; cout<<"1 usage: ./routertester [-t [count]]"<<endl; cout<<""<<endl; cout<<"2 the parameter [-t [count]] is optinal,it control the total run count of this application ."<<endl; cout<<" it's default value is 2 ,if it need to set it .it need a number of 2's times(eg: 2,4,6,...) "<<endl; cout<<""<<endl; cout<<"3 the result will be added to the files routerresult1 and routerresult2 in the current directory at the mean time"<<endl; cout<<" ,and this two result file's content should be the same"<<endl; cout<<""<<endl; cout<<"4 exmaple: './routertester -t 10 ' or ' ./routertester '"<<endl; cout<<""<<endl; exit(0); } } while(count<maxruntime) { printf("================================ Now run the %d time=========================================\n",count); printf("==============================================================================================\n"); if(count%2==0) { fp=fopen("routerresult1","a+"); } else { fp=fopen("routerresult2","a+"); } cout<<"============================== router add section ==================================================\n"<<endl; int index=1; int count=0; int maxruntime=2; FILE *fp=NULL; while(index<argc) { if(strcmp(argv[index],"-t")==0) { maxruntime=atoi(argv[++index]); index++; continue; } if(strcmp(argv[index],"-h")==0) { cout<<"----------------------helps for usage------------------------------------------"<<endl; cout<<"1 usage: ./routertester.exe [-t [count]]"<<endl; cout<<""<<endl; cout<<"2 exmaple: './routertester.exe -t 10 ' or ' ./routertester.exe '"<<endl; cout<<""<<endl; cout<<"3 the paramete [-t [count]] is optinal,it's default value is 2 ,it need to set a number of 2's times(eg: 2,4,6,...) "<<endl; cout<<""<<endl; cout<<"4 the result will be added to the files routerresult1 and routerresult2 in the current directory at the mean time"<<endl; cout<<""<<endl; exit(0); } } while(count<maxruntime) { printf("================================ Now run the %d time=========================================\n",count); printf("==============================================================================================\n"); if(count%2==0) { fp=fopen("routerresult1","a+"); } else { fp=fopen("routerresult2","a+"); } cout<<"============================== router add section ==================================================\n"<<endl; ret = aos_router_add_entry("route1", "192.168.0.1", "255.255.0.0", "172.22.0.1", "incard"); if (ret != 0) { printf("caseId:1 ret = %d Error\n", ret); fail_case++; } total_case++; cout<<"router add entry ret= "<<ret<<endl; fprintf(fp,"router add entry ret=%d\n", ret); cout<<"-----------------------------------------------------------------------------------------------"<<endl; ret = aos_router_add_entry("route2", "192.168.0.1", "255.255.255.254", "172.22.0.1", "outcard"); if (ret != 0) { printf("caseId:2 ret = %d Error\n", ret); fail_case++; } total_case++; cout<<"router add entry ret= "<<ret<<endl; fprintf(fp,"router add entry ret=%d\n", ret); cout<<"-----------------------------------------------------------------------------------------------"<<endl; ret = aos_router_add_entry("route3", "177.168.0.1", "255.255.255.254", "172.22.0.1", "outcard"); if (ret != 0) { printf("caseId:22 ret = %d Error\n", ret); fail_case++; } total_case++; cout<<"router add entry ret= "<<ret<<endl; fprintf(fp,"router add entry ret=%d\n", ret); cout<<"-----------------------------------------------------------------------------------------------"<<endl; ret = aos_router_set_status(1); if (ret != 0) { printf("caseId:8 ret = %d Error\n", ret); fail_case++; } total_case++; cout<<"router set status ret= "<<ret<<endl; fprintf(fp,"router set status ret=%d\n", ret); cout<<"-----------------------------------------------------------------------------------------------"<<endl; len = 10240; ret = aos_router_retrieve_config(result, &len); if (ret != 0) { printf("caseId:4 ret = %d Error\n", ret); fail_case++; } total_case++; cout<<"router show config ret= "<<ret<<"\n"<<result<<endl; fprintf(fp,"router show config ret=%d\n%s\n", ret,result); cout<<"-----------------------------------------------------------------------------------------------"<<endl; ret = aos_router_save_config(); if (ret != 0) { printf("caseId:6 ret = %d Error\n", ret); fail_case++; } total_case++; cout<<"router save config ret= "<<ret<<endl; fprintf(fp,"router save config ret=%d\n", ret); cout<<"-----------------------------------------------------------------------------------------------"<<endl; cout<<"============================== router del section ==================================================\n"<<endl; ret = aos_router_del_entry("route3"); if (ret != 0) { printf("caseId:3 ret = %d Error\n", ret); fail_case++; } total_case++; cout<<"router del entry ret= "<<ret<<endl; fprintf(fp,"router del entry ret=%d\n", ret); cout<<"-----------------------------------------------------------------------------------------------"<<endl; ret = aos_router_del_entry("route1"); if (ret != 0) { printf("caseId:3 ret = %d Error\n", ret); fail_case++; } total_case++; cout<<"router del entry ret= "<<ret<<endl; fprintf(fp,"router del entry ret=%d\n", ret); cout<<"-----------------------------------------------------------------------------------------------"<<endl; ret = aos_router_del_entry("route2"); if (ret != 0) { printf("caseId:3 ret = %d Error\n", ret); fail_case++; } total_case++; cout<<"router del entry ret= "<<ret<<endl; fprintf(fp,"router del entry ret=%d\n", ret); cout<<"-----------------------------------------------------------------------------------------------"<<endl; len = 10240; ret = aos_router_retrieve_config(result, &len); if (ret != 0) { printf("caseId:4 ret = %d Error\n", ret); fail_case++; } total_case++; cout<<"router show config ret= "<<ret<<"\n"<<result<<endl; fprintf(fp,"router show config ret=%d\n%s\n", ret,result); cout<<"-----------------------------------------------------------------------------------------------"<<endl; ret = aos_router_clear_config(); if (ret != 0) { printf("caseId:5 ret = %d Error\n", ret); fail_case++; } total_case++; cout<<"router clear config ret= "<<ret<<endl; fprintf(fp,"router clear config ret=%d\n", ret); cout<<"-----------------------------------------------------------------------------------------------"<<endl; ret = aos_router_save_config(); if (ret != 0) { printf("caseId:6 ret = %d Error\n", ret); fail_case++; } total_case++; cout<<"router save config ret= "<<ret<<endl; fprintf(fp,"router save config ret=%d\n", ret); cout<<"-----------------------------------------------------------------------------------------------"<<endl; cout<<"============================== router wrong input section ==================================================\n"<<endl; ret = aos_router_add_entry("route2", "192.168.0.1", "255.255.255.254", "172.22.0.1", "ooutcard"); if (ret == 0) { printf("caseId:2 ret = %d Error\n", ret); fail_case++; } total_case++; cout<<"router add entry ret= "<<ret<<endl; fprintf(fp,"router add entry ret=%d\n", ret); cout<<"-----------------------------------------------------------------------------------------------"<<endl; ret = aos_router_del_entry("rout2"); if (ret == 0) { printf("caseId:3 ret = %d Error\n", ret); fail_case++; } total_case++; cout<<"router del entry ret= "<<ret<<endl; fprintf(fp,"router del entry ret=%d\n", ret); cout<<"-----------------------------------------------------------------------------------------------"<<endl; len = 10240; ret = aos_router_retrieve_config(result, &len); if (ret != 0) { printf("caseId:4 ret = %d Error\n", ret); fail_case++; } total_case++; cout<<"router show config ret= "<<ret<<"\n"<<result<<endl; fprintf(fp,"router show config ret=%d\n%s\n", ret,result); cout<<"-----------------------------------------------------------------------------------------------"<<endl; //not use /* ret = aos_router_load_config(); if (ret != 0) { printf("caseId:7 ret = %d Error\n", ret); fail_case++; } total_case++; */ fclose(fp); count++; } cout<<"=============================== ROUTER APIS TEST RESULTS SUMMART====================================="<<endl; printf("the run total count is: %d\n ",count); printf("total case: %d\n fail case:%d\n", total_case, fail_case); // printf(" the differdence between the result files is: \n", system(" diff routerresult1 routerresult2")); cout<<""<<endl; cout<<"==========================================================================================================="<<endl; return 0; } }
true
58e1851a88ee7e73d533421d4f342d7ef0890762
C++
emilianbold/netbeans-releases
/cnd.completion/test/unit/data/org/netbeans/modules/cnd/completion/DotArrowSubstitutionTestCase/bug230101.cpp
UTF-8
741
3.09375
3
[]
no_license
namespace { struct MyClass { void Test() {} }; template <class T> struct my_vector { typedef T* iterator; }; template <class T> struct my_foreach_iterator { typedef typename T::iterator type; }; template <class Iterator> struct my_iterator_reference { typedef Iterator type; }; template<typename T> struct my_foreach_reference : my_iterator_reference<typename my_foreach_iterator<T>::type> { }; template <class T> typename my_foreach_reference<T>::type myDeref() { } int main() { // here dot before Test() should be replaced with arrow (*myDeref<my_vector<MyClass*> >()); return 0; } }
true
48fde4eb452acb06aeb63400e8b84184ac6bc5db
C++
emisario/code-block
/matriz.cpp
UTF-8
479
2.703125
3
[]
no_license
#include <iostream> using namespace std; int main(int argc, char *argv[]) { int i, j, matriz [4][4]; float v[4]; for (i=0;i<=4;i++) { for (j=0;j<=4;j++) { cin >> matriz[i][j]; v[i] >= matriz[i][j]; } } for (i=0; i<4;i++) { for (j=0; j<4;j++) { //cout<<"["<<matriz[i][j]<<"]"; } } for(i=0; i<4; i++) { v[i] = v[i] / 4; //cout<<"n "<<v[i]; } return 0; }
true
73c1ce10c5863a7be3190a138088a31c487511fe
C++
Python-aryan/Hacktoberfest2020
/C++/task_scheduling_problem.cpp
UTF-8
845
3.53125
4
[]
permissive
#include<iostream> #include<algorithm> using namespace std; struct Task{ char id; int deadline; int profit; }; bool comparison(Task a, Task b){ return (a.profit > b.profit); } void printTaskScheduling(Task arr[], int n){ sort(arr, arr+n, comparison); int result[n]; bool gap[n]; for (int i=0; i<n; i++){ gap[i] = false; } for (int i=0; i<n; i++){ for (int j=min(n, arr[i].deadline)-1; j>=0; j--){ if (!gap[j]){ result[j] = i; gap[j] = true; break; } } } for (int i=0; i<n; i++){ if (gap[i]){ cout << arr[result[i]].id << " "; } } } int main(){ Task arr[] = { {'a', 2, 100}, {'b', 1, 19}, {'c', 2, 27}, {'d', 1, 25}, {'e', 3, 15}}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Tasks that give most profit: \n"; printTaskScheduling(arr, n); return 0; }
true
fa3d60060f73c55054880fe1d935653a8a8482ab
C++
kpyrkosz/visualisation
/inc/graph.hpp
UTF-8
756
2.90625
3
[]
no_license
#pragma once #include <vertex.hpp> #include <edge.hpp> #include <set> #include <number_pool.hpp> namespace model { class graph { public: using vertex_collection = std::set<vertex, vertex::less>; using edge_collection = std::set<edge, edge::less>; private: vertex_collection vertices_; edge_collection edges_; number_pool vertices_index_pool_; public: const vertex& add_vertex(const std::string& label, float x, float y); void remove_vertex(const vertex& v); void add_edge(const vertex& from, const vertex& to, int weight = 0, const std::string& label = ""); void remove_edge(const edge& e); const vertex_collection& vertices() const; const edge_collection& edges() const; void clear(); }; }
true
40fc825555511c50cbf58f528786f059914b0cd0
C++
josemonsalve2/SCM
/SCMUlate/include/modules/executor.hpp
UTF-8
1,466
2.625
3
[ "Apache-2.0" ]
permissive
#ifndef __EXECUTOR_MODULE__ #define __EXECUTOR_MODULE__ #include "SCMUlate_tools.hpp" #include "control_store.hpp" #include "timers_counters.hpp" #include "memory_interface.hpp" namespace scm { /** brief: Executors * * The cu_executor performs the execution of instructions, usually in * the form of codelets. It requires an execution slot which contains * the codelet that is to be executed.*/ class cu_executor_module { private: int cu_executor_id; execution_slot * myExecutor; mem_interface_module *mem_interface_t; volatile bool* aliveSignal; TIMERS_COUNTERS_GUARD( std::string cu_timer_name; timers_counters* timer_cnt_m; ) public: cu_executor_module() = delete; cu_executor_module(int, control_store_module * const, unsigned int, bool *, l2_memory_t upperMem); TIMERS_COUNTERS_GUARD( inline void setTimerCnt(timers_counters * tmc) { this->timer_cnt_m = tmc; this->cu_timer_name = std::string("CUMEM_") + std::to_string(this->cu_executor_id); this->timer_cnt_m->addTimer(this->cu_timer_name, CUMEM_TIMER); } ) int behavior(); int codeletExecutor(); int get_executor_id(){ return this->cu_executor_id; } mem_interface_module* get_mem_interface() { return this->mem_interface_t; } ~cu_executor_module() { delete mem_interface_t; } }; } #endif
true
af95aa434ed471ba2e8b8b8617cba63a91585ee2
C++
yurisantamarina/LeetCode-Solutions
/Solutions/Distinct Subsequences.cpp
UTF-8
764
2.78125
3
[]
no_license
class Solution { public: int countDp(int i, int j, string &s, string &t, vector<vector<int> >& dp){ if(j == (int)t.size()) return 1; if(i == (int)s.size()) return 0; if(dp[i][j] != -1) return dp[i][j]; int ans = 0; if(s[i] == t[j]){ ans = countDp(i + 1, j + 1, s, t, dp) + countDp(i + 1, j, s, t, dp); }else{ ans = countDp(i + 1, j, s, t, dp); } return dp[i][j] = ans; } int numDistinct(string s, string t) { vector<vector<int> > dp; dp.resize((int)s.size()); for(int i = 0; i < (int)s.size(); i++){ dp[i].resize((int)t.size(), -1); } return countDp(0, 0, s, t, dp); } };
true
69521b13f5aecdee368223b7f22efbfa0ef5a1c0
C++
Kodiey/CS2A
/assignment_7/a7_1.cpp
UTF-8
7,261
3.5
4
[]
no_license
/* a7_1.cpp Professor Harden CS 2A */ #include <iostream> #include <iomanip> using namespace std; void getProbsPerSet(int &probsPerSet); void doOneSet(char operand, int probsPerSet, int &result); void doOneProblem(char operand, int &score, int maxNum); void generateOperands(char optr, int &firstNum, int &secondNum, int &usrAns, \ int maxNum); void calculateCorrectAnswer(char optr, int firstNum, int secondNum, \ int &correctAns); void checkAnswer(int userAnswer, int correctAnswer, int &score); void printHeader(char optr); void getMaxNum(int &maxNum); void printReport(int numCorrect1, int numCorrect2, int numCorrect3, \ int probsPerSet); const int numProblemSets = 3; const int toPercentage = 100; /* The purpose of this program is to evaluate a person's ability to do simple mathematical operations: addition (+), subtraction (-), and multiply (*). When all the questions are answered, the program will print out a summary of how the individual did on the math problems. */ // This is the main function that calls all the necessary functions to execute // the purpose of this program. To walk through the function calls, we start // by calling srand() to create a seed (pseudorandomly generate numbers). // getProbsPerSet() will ask for user to give number of problems s/he wants per // problem set. Finally, the program will generate a number of problems // specified from (getProbsPerSet) and printReport() displays the performance // of the individual. int main(){ int probsPerSet; int numCorrect1 = 0; int numCorrect2 = 0; int numCorrect3 = 0; srand(static_cast<unsigned>(time(0))); getProbsPerSet(probsPerSet); doOneSet('+', probsPerSet, numCorrect1); doOneSet('-', probsPerSet, numCorrect2); doOneSet('*', probsPerSet, numCorrect3); printReport(numCorrect1, numCorrect2, numCorrect3, probsPerSet); } // main // In this function, the number of correct of each set of problems, is passed // in by value and the number of problems per each set. Since all these values are // integers and needed to be changed to double due to percentages. // Finally it prints out the statistics of how the individual performed. void printReport(int numCorrect1, int numCorrect2, \ int numCorrect3, int probsPerSet){ double grade1, grade2, grade3; grade1 = (double) numCorrect1 / probsPerSet * toPercentage; grade2 = (double) numCorrect2 / probsPerSet * toPercentage; grade3 = (double) numCorrect3 / probsPerSet * toPercentage; int totalProblems = probsPerSet * numProblemSets; int totalCorrect = numCorrect1 + numCorrect2 + numCorrect3; double overallGrade = (double) totalCorrect / totalProblems * toPercentage; cout << setprecision(1) << fixed; cout << "Set#1: You got " << numCorrect1 << " correct out of " << probsPerSet << " for " << grade1 << "%" << endl; cout << setprecision(1) << fixed; cout << "Set#2: You got " << numCorrect2 << " correct out of " << probsPerSet << " for " << grade2 << "%" << endl; cout << setprecision(1) << fixed; cout << "Set#3: You got " << numCorrect3 << " correct out of " << probsPerSet << " for " << grade3 << "%" << endl; cout << setprecision(1) << fixed; cout << "Overall you got " << totalCorrect << " correct out of " << totalProblems << " for " << overallGrade << "%" << endl; } //printReport // Prompts user to get the maximum value for a given problem set void getMaxNum(int &maxNum){ cout << "What is the maximum number for this set? "; cin >> maxNum; cout << endl; } // getMaxNum // Prompts user to input the number problems in problem set void getProbsPerSet(int &probsPerSet){ cout << "Enter number problems per set: "; cin >> probsPerSet; cout << endl; } // Prints the Set number statement based on the operator void printHeader(char optr){ switch (optr){ case '+': cout << "Set #1" << endl; break; case '-': cout << "Set #2" << endl; break; case '*': cout << "Set #3" << endl; break; } cout << "----------" << endl; } // This prints out the questions that asks the user input the answer. // Similarly, result is passed by reference so that later on printReport() // can access this variable's value. void doOneSet(char operand, int probsPerSet, int &result){ int score; int maxNum; printHeader(operand); getMaxNum(maxNum); for (int i = 0; i < probsPerSet; i++){ doOneProblem(operand, score, maxNum); result += score; } cout << endl; } // doOneSet // doOneSet call this function to print out one statement and evaluate the // user's performance. Since score is passed by reference, it's sent back to // doOneSet to aggregate the number of times it did something correctly. void doOneProblem(char operand, int &score, int maxNum){ int firstNum; int secondNum; int userAnswer; int correctAnswer; generateOperands(operand, firstNum, secondNum, userAnswer, maxNum); calculateCorrectAnswer(operand, firstNum, secondNum, correctAnswer); checkAnswer(userAnswer, correctAnswer, score); } //doOneProblem // This generates the random number for first and second number for the problem. // It asks the user for their answer. Since the first and second number and // user answer are passed by reference, so that calculateCorrectAnswer() can // access those variables! void generateOperands(char optr, int &firstNum, int &secondNum, int &usrAns, \ int maxNum){ firstNum = rand() % (maxNum + 1) ; secondNum = rand() % (maxNum + 1); cout << firstNum << " " << optr << " "; cout << secondNum << " = "; cin >> usrAns; } // generateOperands // This calculates the correct answer for the two randomly generated numbers: // firstNum and secondNum. Once the correct answer is evaluated it will be // passed back to doOneProblem(). void calculateCorrectAnswer(char optr, int firstNum, int secondNum, \ int &correctAns){ switch (optr){ case '+': correctAns = firstNum + secondNum; break; case '-': correctAns = firstNum - secondNum; break; case '*': correctAns = firstNum * secondNum; break; } // cases for operand } // calculateCorrectAnswer // This checks if the userAnswer and correctAnswer are the same. Since // score is passed by reference, we can pass it back to save results. void checkAnswer(int userAnswer, int correctAnswer, int &score){ if (userAnswer == correctAnswer){ score = 1; cout << "correct" << endl; } else { score = 0; cout << "incorrect" << endl; } } // checkAnswer // Output: // --------------------------------------------- // Enter number problems per set: 3 // Set #1 // ---------- // What is the maximum number for this set? 100 // 65 + 27 = 79 // incorrect // 29 + 64 = 93 // correct // 22 + 50 = 72 // correct // Set #2 // ---------- // What is the maximum number for this set? 90 // 88 - 10 = 78 // correct // 39 - 69 = -30 // correct // 31 - 74 = -43 // correct // Set #3 // ---------- // What is the maximum number for this set? 20 // 6 * 14 = 84 // correct // 9 * 12 = 0 // incorrect // 1 * 6 = 0 // incorrect // Set#1: You got 2 correct out of 3 for 66.7% // Set#2: You got 3 correct out of 3 for 100.0% // Set#3: You got 1 correct out of 3 for 33.3% // Overall you got 6 correct out of 9 for 66.7%
true
a3c7d3380654639cc9e0bb846dbb5542e651c2d9
C++
talatynnikA/OS-Labs
/Новая папка (2)/какие-то процессы/Проект2/Проект2/Исходный код2.cpp.txt
WINDOWS-1251
5,292
3
3
[]
no_license
#include <iostream> #include <thread> int chpb = 0; using namespace std; #include <mutex> #include <condition_variable> // binary semaphore Pb = ( ) class binsem { public: explicit binsem(int init_count = count_max) : count_(init_count) {} // P-operation / acquire \, \ void wait() { std::unique_lock<std::mutex> lk(m_); cv_.wait(lk, [=]{ return 0 < count_; }); --count_; } // , bool try_wait() { std::lock_guard<std::mutex> lk(m_); if (0 < count_) { --count_; return true; } else { return false; } } // V-operation / release \ void signal() { std::lock_guard<std::mutex> lk(m_);// V , P. if (count_ < count_max) { ++count_; cv_.notify_one(); // , V } cout << "\nsignal\n"; } // Lockable requirements void lock() { wait(); } bool try_lock() { return try_wait(); } void unlock() { signal(); } private: static const int count_max = 1; int count_; std::mutex m_; std::condition_variable cv_; }; // binary semaphore 2(Zn = )( ) class binsem2 { public: explicit binsem2(int init_count = count_max) : count_(init_count) {} // P-operation / acquire \, \/ void wait() { std::unique_lock<std::mutex> lk(m_); cv_.wait(lk, [=]{ return 0 < count_; }); --count_; } bool try_wait() { std::lock_guard<std::mutex> lk(m_); if (0 < count_) { --count_; return true; } else { return false; } } // V-operation / release \ void signal() { std::lock_guard<std::mutex> lk(m_); if (count_ < count_max) { ++count_; cv_.notify_one(); } cout << "\nsignal\n"; } // Lockable requirements void lock() { wait(); } bool try_lock() { return try_wait(); } void unlock() { signal(); } private: static const int count_max = 1; int count_; std::mutex m_; std::condition_variable cv_; }; //-------------------------------- int proizvoditel( binsem *sem, binsem2 *sem2) { // cout << "proizvoditel begin\n"; do{ n1:{ cout << "proizvodstvo novoi portsii\n"; cout << "P(Pb)\n";// sem->wait(); sem->try_wait(); cout << "dobavlenie novoi porcii k byfery\n"; chpb = chpb + 1; cout << "chpb = "; cout << chpb << endl; } if (chpb == 0) { cout << "V(Pb)\n";// sem->signal(); cout << "V(Zn)\n";// sem2->signal(); return 0; } else{ cout << "V(Pb)\n";// sem->signal(); } } while (chpb != 10); return chpb; } int potrebitel( binsem *sem, binsem2 *sem2) { // cout << "potrebitel begin\n"; do{ n2:{ cout << "P(Pb)\n";// sem->wait(); sem->try_wait(); chpb = chpb - 1;// cout << "pip chpb = "; cout << chpb << endl;// } if (chpb == -1) { cout << "V(Pb)\n";// sem->signal(); cout << "P(Zn)\n";// sem2->wait(); sem2->try_wait(); cout << "P(Pb)\n";// sem->wait(); sem->try_wait(); return 0; } cout << "vzyatie porcii iz byfera\n"; cout << "V(Pb)\n";// sem->signal(); cout << "obrabotka vzyatoi porcii\n"; } while (chpb != 0);// . - 0 } int main(int *ptrchpb ) { binsem2 *sem2 = new binsem2(10); binsem *sem = new binsem(10); cout << "Hello World\n"; cout << " Program author: Artyom Talatynnik\nProcess interaction\n"; cout << "begin\n"; proizvoditel( sem, sem2); potrebitel(sem, sem2); system("pause"); return 0; }
true
fad9564d2fc8ef191540ebe0a4ac0f4c647e5b65
C++
esantoul/data-management
/include/poly_fun.hpp
UTF-8
2,419
3.4375
3
[ "BSD-2-Clause" ]
permissive
/** * Copyright (C) 2020 Etienne Santoul - All Rights Reserved * You may use, distribute and modify this code under the * terms of the BSD 2-Clause License * * You should have received a copy of the BSD 2-Clause License * with this file. If not, please visit: * https://github.com/esantoul/data-management */ #pragma once #include <functional> #include <memory> #include <cassert> namespace dmgmt { class PolyFunDataBase { public: virtual ~PolyFunDataBase() {} virtual void operator()(const void *) const = 0; virtual const std::type_info &type() const = 0; virtual PolyFunDataBase *clone() const = 0; protected: }; template <typename El_t> class PolyFunData : public PolyFunDataBase { public: PolyFunData(const std::function<void(const El_t &)> &fun) : mFun(fun) { } ~PolyFunData() {} void operator()(const void *data_ptr) const override { mFun(*static_cast<const El_t *>(data_ptr)); } const std::type_info &type() const override { return typeid(El_t); } PolyFunDataBase *clone() const override { return new PolyFunData{mFun}; } private: std::function<void(const El_t &)> mFun; }; /** * @brief An object that contains a polymorphic callable. * Can contain any callable with signature void(El_t) where El_t is any type. */ class PolyFun { public: template <typename El_t, typename = std::enable_if_t<!std::is_same_v<El_t, PolyFun>>> PolyFun(const std::function<void(const El_t &)> &fun) : mFunData{new PolyFunData<El_t>(fun)} { } PolyFun(const PolyFun &other) : mFunData{other.mFunData->clone()} { } template <typename El_t> void operator()(const El_t &data) const { if (typeid(El_t) == mFunData->type()) (*mFunData.get())(&data); else assert(false); } /** * @brief Formats any functor to a type handlable by PolyFun * @tparam Dat_t Type of the argument handled by the functor * @param functor a functor with void(const Dat_t&) signature * @return Functor properly converted to type std::function<void(const Dat_t&)> */ template <typename Dat_t, typename Functor_t> static std::function<void(const Dat_t &)> fmt(const Functor_t &functor) { return functor; } private: std::unique_ptr<PolyFunDataBase> mFunData; }; } // namespace dmgmt
true
a7055ef5e131ab97a98cb6170743283dd8a2127b
C++
AJOO7/ds-gui
/DataStrPro/adminnonveg.cpp
UTF-8
3,970
2.796875
3
[]
no_license
#include "adminnonveg.h" #include "ui_adminnonveg.h" #include<QString> #include <cstddef> #include<QMessageBox> #include<QFile> #include<QTextStream> class node_non { QString food; int price; int no_of_order; node_non *next; public: node_non(QString f,int p) { food=f; price=p; no_of_order=0; next=NULL; } friend class Menu_non; }; class Menu_non { node_non *head; node_non *tail; public: Menu_non() { head=NULL; tail=NULL; } void insert_dish_non(QString f,int p) { node_non *n = new node_non(f,p); if(head==NULL) { head=tail=n; return; } tail->next=n; tail=n; return; } void fill_file_non() { QFile filen("C:/Users/Alisha/Documents/DataStrPro/nonVeg.txt"); filen.open(QIODevice::WriteOnly |QIODevice::Text); QTextStream out(&filen); filen.resize(0); if(head==NULL) { out<<"END"; return; } node_non *temp=head; while(temp!=NULL) { out<<temp->food<<Qt::endl; out<<temp->price<<Qt::endl; temp=temp->next; } out<<"END"; filen.close(); return; } void delete_dish(QString f) { if(head==NULL) { QMessageBox msgBox; msgBox.setText("Nothing present to be deleted!"); msgBox.setStandardButtons( QMessageBox::Ok); msgBox.setDefaultButton(QMessageBox::Ok); msgBox.exec(); return; } if(head->food==f&&head->next==NULL){ delete head; head=NULL; return; } if(head->food==f&&head->next!=NULL){ node_non*curr=head; head=head->next; delete curr; return; } node_non*temp=head; bool found=false; while(temp->next!=NULL) { if(temp->next->food==f){ found=true; break; } temp=temp->next; } if(found==false) { QMessageBox msgBox; msgBox.setText("Dish not Found in the menu!"); msgBox.setStandardButtons( QMessageBox::Ok); msgBox.setDefaultButton(QMessageBox::Ok); msgBox.exec(); return; } node_non *t=temp->next; temp->next=t->next; delete t; return; } }; Menu_non nonVeg; adminNonVeg::adminNonVeg(QWidget *parent) : QDialog(parent), ui(new Ui::adminNonVeg) { ui->setupUi(this); QFile filen("C:/Users/Alisha/Documents/DataStrPro/nonVeg.txt"); filen.open(QFile::ReadOnly |QFile::Text); QTextStream in(&filen); QString text=in.readLine(); QString text2=in.readLine(); while(text!="END"){ nonVeg.insert_dish_non(text,text2.toInt()); text=in.readLine(); text2=in.readLine(); } filen.close(); } adminNonVeg::~adminNonVeg() { delete ui; } void adminNonVeg::on_back_clicked() { this->close(); QWidget *parent = this->parentWidget(); parent->show(); } void adminNonVeg::on_add_clicked() { QString newName=ui->foodName->text(); if(newName==NULL){ QMessageBox::information(this,"Warning","Empty username!"); return; } int newPrice=ui->foodPrice->text().toInt(); if(newPrice==NULL){ QMessageBox::information(this,"Warning","Empty price!"); return; } nonVeg.insert_dish_non(newName,newPrice); nonVeg.fill_file_non(); } void adminNonVeg::on_del_clicked() { QString name=ui->delFood->text(); nonVeg.delete_dish(name); nonVeg.fill_file_non(); }
true
198fcdc1a0f89e46a3bc6e24db2e108cc7b70e8e
C++
mirellameelo/opencv_exercises
/Atividade_1/Main.cpp
UTF-8
1,036
2.625
3
[ "MIT" ]
permissive
#include <iostream> #include <stdint.h> #include <opencv2\opencv.hpp> #include <opencv2\imgproc.hpp> using namespace cv; using namespace std; const int fps = 20; int main(int argv, char** argc) { Mat frame; Mat frame1, frame2, frame3; VideoCapture vid(0); frame = vid.read(frame); if (!vid.isOpened()) return -1; //create an empty frame (size X, size Y, Type) - number 3 = 3 channels frame1 = Mat::zeros(frame.rows, frame.cols, CV_8UC3); frame2 = Mat::zeros(frame.rows, frame.cols, CV_8UC3); frame3 = Mat::zeros(frame.rows, frame.cols, CV_8UC3); while (vid.read(frame)) { for (int r = 0; r < frame.rows; r++) { for (int c = 0; c < frame.cols; c++) { //can be done with split and merge frame1.at<Vec3b>(r, c)[0] = frame.at<Vec3b>(r, c)[0]; frame2.at<Vec3b>(r, c)[1] = frame.at<Vec3b>(r, c)[1]; frame3.at<Vec3b>(r, c)[2] = frame.at<Vec3b>(r, c)[2]; } } imshow("webcam1", frame1); imshow("webcam2", frame2); imshow("webcam3", frame3); if (waitKey(1) == 27) break; } return 0; }
true
d70ed8b5aed252961e45f164d49a2510c359759e
C++
TenFifteen/SummerCamp
/spw_lintcode/099-recoder-list/solve.cc
UTF-8
1,941
3.90625
4
[]
no_license
/** * Problem: Given a singly linked list L: L0 → L1 → … → Ln-1 → Ln * reorder it to: L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → … * Solve: split, reverse, merge * Tips: split the in the position half = (n+1)/2; merge two nodes every time * in order. */ /** * Definition of ListNode * class ListNode { * public: * int val; * ListNode *next; * ListNode(int val) { * this->val = val; * this->next = NULL; * } * } */ class Solution { public: int countList(ListNode *head) { int cnt = 0; while (head) { ++cnt; head = head->next; } return cnt; } /** * @param head: The first node of linked list. * @return: void */ void reorderList(ListNode *head) { int n = countList(head); if (n < 2) return; int half = (n+1) / 2; // split ListNode *prev = head, *it = head; while (half--) { prev = it; it = it->next; } prev->next = NULL; // reverse ListNode *h = NULL; while (it) { ListNode *now = it; it = it->next; now->next = h; h = now; } // merge ListNode *nh = new ListNode(0); prev = nh; while (head || h) { if (head) { prev->next = head; head = head->next; prev = prev->next; } if (h) { prev->next = h; h = h->next; prev = prev->next; } } prev->next = NULL; head = nh->next; delete nh; } };
true
4cbb2915b7ccecdb00646f2303f212bda2ce6d29
C++
ICCup02/Programmer
/programm/25/25/25.cpp
UTF-8
1,307
2.78125
3
[]
no_license
#include <iostream> #include <string> using namespace std; struct student { std::string name; int group; int sec[5]; }; int main() { setlocale(LC_ALL, "RUS"); const int k = 10; student stud[k] = {}; stud[0] = { "Иванов А.В." , 6, 5,5,5,5,5 }; stud[1] = { "Смирнов Г.Д.", 1, 5,5,5,1,5 };//7 stud[2] = { "Соболев К.Д.", 3, 4,4,4,4,4 }; stud[3] = { "Пупкин С.В.", 2, 5,0,5,5,5 };//5 stud[4] = { "Волосянский Н.Г.", 2, 5,2,5,5,5 };//2 stud[5] = { "Козлов А.В.", 2, 5,1,5,5,5 };//3 stud[6] = { "Климов Г.В.", 3, 5,4,4,4,5 }; stud[7] = { "Кочетов Л.М.", 4, 5,2,5,5,5 };//4 stud[8] = { "Сидоров П.Н.", 4, 5,5,3,5,5 };//6 stud[9] = { "Алексеев Р.К.", 6, 5,3,5,5,5 };//1 int x = 0; for (int o = 0, i = 0; i < 10; o++) { if (o > 4) { o = -1; i++; continue; } if (stud[i].sec[o] <= 3) { swap(stud[i], stud[x]); x++; i++; o = -1; } } int c = x; bool first = true; while (first) { first = false; for (int o = 0, i = 1, last = 0; i < x; ) { if (int(stud[i].name[o]) < int(stud[last].name[o])) { swap(stud[i], stud[last]); first = true; o = 0; } else if (stud[i].name[o] == stud[last].name[o]) { o++; continue; } else o = 0; i++, last++; } x--; } if (c > 0) { for (int i = 0; i < c; i++) { cout << stud[i].name << " " << stud[i].group << endl; } } else cout << "Not find"; }
true
a3f095210a779f0e5be81071d39612ddd707d1ec
C++
Cicciodev/esp-telegram-bot
/LED_0_1.ino
UTF-8
872
3.125
3
[]
no_license
#include<SoftwareSerial.h> // In order to debug I define a differente serial port for the esp SoftwareSerial esp(2,3); String command = ""; void setup() { Serial.begin(115200); esp.begin(115200); Serial.println("System Ready.."); pinMode(13, OUTPUT); } void loop() { if (esp.available()) { // Receiving a command from esp command = esp.readString(); // [DEBUG] say what you got // Serial.print("I received: "); // Serial.println(command); // Trimming cause of newline (or maybe simple change println with print in esp programm) command.trim(); // Handle command-action if (command == "1") { digitalWrite(13, HIGH); Serial.println("Command completed LED turned ON"); } if (command == "0") { digitalWrite(13, LOW); Serial.println("Command completed LED turned OFF"); } } }
true
7f59448b04166cdc15a1f1a625d7fcd803cb4e80
C++
ssdemajia/LeetCode
/IntegerBreak.cpp
UTF-8
973
3.625
4
[]
no_license
#include "inc.h" // 343. Integer Break class Solution { public: int integerBreak2(int n) {//使用dp来保存中间状态,即n可以由几个数组合构成 vector<int> dp(n+1, 1); for (int i = 3; i <= n; i++) { for (int j =1; j < i; j++) { dp[i] = max({dp[i], dp[j] * (i-j), j*(i-j)}); } } displayVec(dp); return dp[n]; } /* * n可以构成为 2*(n-2) 或 3*(n-3), 因为 2*2*2 < 3*3,所以先把尽可能多的3找到,即n/3-1,之所以-1,因为这样剩余的情况为 4,3,2 */ int integerBreak(int n) { if (n <= 2) return 1; if (n == 3) return 2; if (n%3 == 0) return pow(3, n/3);//n由3+3+3+3+...+3组成的情况 if (n%3 == 1) return pow(3, n/3-1)*4;//n由2+2+3+3+...+3组成 return pow(3, n/3)*2;//n由2+3+3+...+3组成 } }; int main() { Solution so; cout << so.integerBreak(5) << endl; return 0; }
true
348a5ebfde75582025088e4e4de771b961b6d22c
C++
dendibakh/Misc
/Archivator/src/FolderSnapshotLib/StoreFile.cpp
UTF-8
2,935
2.921875
3
[]
no_license
#include "StoreFile.h" #include <fstream> #include "util.h" #include <sys/stat.h> using namespace boost::filesystem; using namespace std; StoreFile::StoreFile(const path& fileName, const path& binaryName) : fileName(removeLastSlash(fileName)), binaryName(removeLastSlash(binaryName)) { try { checkExistFile(); generateBinary(); } catch(exception& e) { error.assign(e.what()); } } void StoreFile::checkExistFile() const { if (!exists(this->fileName) || !is_regular(this->fileName)) throw domain_error("No such file: " + this->fileName.string() + "."); } void StoreFile::generateBinary() const { ifstream file(fileName.string().c_str(), ifstream::binary); ofstream output(binaryName.string().c_str(), ofstream::binary | ofstream::app); try { if (!file) throw domain_error("Store file begin. Can't read the file: " + fileName.string() + "."); if (!output) throw domain_error("Store file begin. Can't create binary file: " + binaryName.string() + "."); output << FLAG_FILE; if (!output.good()) throw domain_error("Attempt to write the begin file flag. Error while writing to the file: " + binaryName.string() + "."); output << fileName.filename().string() << '\0'; if (!output.good()) throw domain_error("Attempt to write the file name. Error while writing to the file: " + binaryName.string() + "."); size = file_size(fileName); output.write((char*)&size, sizeof(uintmax_t)); if (!output.good()) throw domain_error("Attempt to write the size of the file. Error while writing to the file: " + binaryName.string() + "."); struct stat filestatus; stat( fileName.string().c_str(), &filestatus ); time_t creationTime = filestatus.st_ctime; output.write((char*)&creationTime, sizeof(time_t)); if (!output.good()) throw domain_error("Attempt to write the file creation time. Error while writing to the file: " + binaryName.string() + "."); file.seekg(0, file.beg); if (!file.good()) throw domain_error("Error while setting position to the output file: " + fileName.string() + "."); storeFileContent(file, output, size); } catch (exception& e) { error.assign(e.what()); } file.close(); output.close(); } bool StoreFile::good() const { return error.empty(); } uintmax_t StoreFile::getSizeInBytes() const { checkForError(); return size; } void StoreFile::checkForError() const { if (!error.empty()) throw domain_error(error); }
true
d1fcd7c7886a365977de8f74a935a1562761facb
C++
Kushagra788/algorithms
/merge_sorted_array.cpp
UTF-8
958
3.8125
4
[]
no_license
#include <stdio.h> #include <stdlib.h> int merge_two_sorted_arrays(int arr1[], int arr2[], int arr3[], int m, int n) { int i,j,k; i = j = k = 0; for(i=0;i < m && j < n;) { if(arr1[i] < arr2[j]) { arr3[k] = arr1[i]; k++; i++; } else { arr3[k] = arr2[j]; k++; j++; } } while(i < m) { arr3[k] = arr1[i]; k++; i++; } while(j < n) { arr3[k] = arr2[j]; k++; j++; } } int main() { int n,m; printf("\nEnter the size of Array 1 : "); scanf("%d",&m); printf("\nEnter the size of Array 2 : "); scanf("%d",&n); int arr1[m],arr2[n]; int arr3[m+n]; int i; printf("\nInput the Array 1 elements : "); for(i = 0; i < m; i++) { scanf("%d",&arr1[i]); } printf("\nInput the Array 2 elements : "); for(i = 0;i<n;i++) { scanf("%d",&arr2[i]); } merge_two_sorted_arrays(arr1,arr2,arr3,m,n); printf("\nThe Merged Sorted Array : "); for(i = 0; i < n + m; i++) { printf("%d ",arr3[i]); } printf("\n"); return 0; }
true
61e653f03f0e1b73f993e20ce1b6a05bae9c8003
C++
Yorkzhang19961122/CPP_Examples_Tsinghua
/例6-3使用数组名作为函数参数.cpp
UTF-8
1,079
4.09375
4
[]
no_license
// 例6-3使用数组名作为函数参数.cpp : //主函数中初始化一个二维数组,表示一个矩阵,并将每个元素都输出,然后调用子函数,分别计算每一行的元素之和, //将和直接存放在每行的第一个元素中,返回主函数之后输出各行元素的和 #include <iostream> using namespace std; void rowSum(int a[][4], int nRow) { //计算二维数组每行元素的和 for (int i = 0; i < nRow; i++) { for (int j = 1; j < 4; j++) a[i][0] += a[i][j]; } } int main(){ int table[3][4] = { {1,2,3,4},{2,3,4,5},{3,4,5,6} }; for (int i = 0; i < 3; i++) { //外层行循环 for (int j = 0; j < 4; j++) //内层列循环 cout << table[i][j] << " "; cout << endl; } rowSum(table, 3); //调用子函数,计算各行和,用数组名做实参其实就是将数组的首地址传给了函数rowSum for (int i = 0; i < 3; i++) //输出计算结果 cout << "Sum of row " << i << " is " << table[i][0] << endl; return 0; }
true
51b2f094291227ffb2dda446f98a3b5098d16b5c
C++
katheroine/languagium
/c++/pointers/operations_on_multidimensional_arrays.cpp
UTF-8
309
3.40625
3
[]
no_license
#include <iostream> int main() { int numbers[][3] = {{1, 2, 3}, {4, 5, 6}}; int (*pi)[3]; pi = numbers; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) { std::cout << "numbers[" << i << "][" << j << "]: " << *(*(pi + i) + j) << std::endl; } } std::cout << std::endl; }
true
2a7c495046feaf72632e1a5be254b52a7af99d5b
C++
csugulo/leetcode-solutions
/128_Longest_Consecutive_Sequence/Longest_Consecutive_Sequence.cpp
UTF-8
725
3.21875
3
[]
no_license
#include "leetcode_solutions.h" class Solution { public: int longestConsecutive(vector<int>& nums) { if(nums.size() == 0 || nums.size() == 1) return nums.size(); int res = 0; unordered_set<int> set(nums.begin(), nums.end()); for(int val : nums){ if(!set.count(val)) continue; set.erase(val); int pre(val - 1), after(val + 1); while(set.count(pre)) set.erase(pre--); while(set.count(after)) set.erase(after++); res = max(res, after - pre - 1); } return res; } }; int main(){ vector<int> nums = {100,4,200,1,3,2}; Solution s; cout << s.longestConsecutive(nums) << endl; return 0; }
true
fe0d028f7d229755889f315b2f49fa1b8a78e2ed
C++
wangchenwc/leetcode_cpp
/300_399/362_hit_counter.h
UTF-8
815
3.046875
3
[]
no_license
// // 362_hit_counter.h // cpp_code // // Created by zhongyingli on 2018/8/13. // Copyright © 2018 zhongyingli. All rights reserved. // #ifndef _62_hit_counter_h #define _62_hit_counter_h class HitCounter { public: /** Initialize your data structure here. */ HitCounter() {} /** Record a hit. @param timestamp - The current timestamp (in seconds granularity). */ void hit(int timestamp) { q.push(timestamp); } /** Return the number of hits in the past 5 minutes. @param timestamp - The current timestamp (in seconds granularity). */ int getHits(int timestamp) { while (!q.empty() && timestamp - q.front() >= 300) { q.pop(); } return q.size(); } private: queue<int> q; }; #endif /* _62_hit_counter_h */
true
61918f2c046c218c25e050707e9882ab0f07fe90
C++
shashishailaj/USACO
/Implementations/content/numerical/Polynomials/PolyInv.h
UTF-8
659
2.625
3
[ "CC0-1.0" ]
permissive
/** * Description: computes $v^{-1}$ such that * $vv^{-1}\equiv 1\pmod{x^p}$ * Time: O(N\log N) * Source: CF, http://people.csail.mit.edu/madhu/ST12/scribe/lect06.pdf * Verification: https://codeforces.com/contest/438/problem/E */ #include "FFT.h" template<class T> vector<T> inv(vector<T> v, int p) { v.rsz(p); vector<T> a = {T(1)/v[0]}; for (int i = 1; i < p; i *= 2) { if (2*i > p) v.rsz(2*i); auto l = vector<T>(begin(v),begin(v)+i); auto r = vector<T>(begin(v)+i,begin(v)+2*i); auto c = mult(a,l); c = vector<T>(begin(c)+i,end(c)); auto b = mult(a*T(-1),mult(a,r)+c); b.rsz(i); a.insert(end(a),all(b)); } a.rsz(p); return a; }
true
d37a126cd601dbac45cc03756e5ce5e4ee3ae3fb
C++
wubin28/KataDocumentEditor
/test/DocumentEditor/DocumentEditorFacade.cpp
UTF-8
1,384
3.09375
3
[]
no_license
#include "DocumentEditorFacade.h" DocumentEditorFacade::DocumentEditorFacade(string contents = "") { for (size_t i = 0; i != ROW_COUNT; ++i) { for (size_t j = 0; j != COL_COUNT; ++j) { if ((i * COL_COUNT + j) < contents.size()) { screenChars[i][j] = contents[i * COL_COUNT + j]; } else { screenChars[i][j] = ' '; } } } for (auto &row : screenColors) { for (auto &col : row) { col = "black"; } } for (auto &row : screenDrawnResult) { for (auto &col : row) { col = "*"; } } } void DocumentEditorFacade::setColor(size_t row, size_t column, size_t length, string color) { for (size_t i = 0; i != length; i++) { screenColors[row][column + i] = color; } } void DocumentEditorFacade::drawScreen() { for (size_t i = 0; i != ROW_COUNT; ++i) { for (size_t j = 0; j != COL_COUNT; ++j) { shared_ptr<Character> charObj = glyphFactory.getCharObj(screenChars[i][j]); screenDrawnResult[i][j] = charObj->draw(screenColors[i][j]); } } } string DocumentEditorFacade::getColor(size_t row, size_t column) { return screenColors[row][column]; } string DocumentEditorFacade::getScreenDrawnResult(size_t row, size_t column) { return screenDrawnResult[row][column]; }
true