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
85340e2da5a36734c5874b6d08c6f9c9a470015b
C++
soundforascene/Art-CodeProject1.0
/src/demoParticle.cpp
UTF-8
4,852
3.046875
3
[]
no_license
#include "demoParticle.h" //------------------------------------------------------------------ demoParticle::demoParticle(){ // Im guessing this corisponds to mode 3? attractPoints = NULL; } //------------------------------------------------------------------ void demoParticle::setMode(particleMode newMode){ mode = newMode; } //------------------------------------------------------------------ void demoParticle::setAttractPoints( vector <ofPoint> * attract ){ attractPoints = attract; } //------------------------------------------------------------------ void demoParticle::reset(){ //the unique val allows us to set properties slightly differently for each particle uniqueVal = ofRandom(-10000, 10000); pos.x = ofRandomWidth(); pos.y = ofRandomHeight(); vel.x = ofRandom(-3.9, 3.9); // Changed vel.y in attempts to made a faster more 'rain' feel. from 3.9 , 3.9 to -100 , -99 vel.y = ofRandom(-100, -99); frc = ofPoint(0,0,0); scale = ofRandom(0.5, 1.0); // Below is for mode 'noise'. I have deleted the if statement meaning particles in all modes will fall down (tried) drag = ofRandom(0.95, 0.998); vel.y = fabs(vel.y) * 3.0; //make the particles all be going down } //------------------------------------------------------------------ void demoParticle::update(){ //1 - APPLY THE FORCES BASED ON WHICH MODE WE ARE IN if( mode == PARTICLE_MODE_REPEL ){ ofPoint attractPt(ofGetMouseX(), ofGetMouseY()); frc = attractPt-pos; // we get the attraction force/vector by looking at the mouse pos relative to our pos //let get the distance and only repel points close to the mouse float dist = frc.length(); frc.normalize(); //by normalizing we disregard how close the particle is to the attraction point vel *= drag; //apply drag if( dist < 150 ){ vel += -frc * 0.6; //apply force//notice the frc is negative }else{ //if the particles are not close to us, lets add a little bit of random movement using noise. this is where uniqueVal comes in handy. frc.x = ofSignedNoise(uniqueVal, pos.y * 0.01, ofGetElapsedTimef()*0.2); frc.y = ofSignedNoise(uniqueVal, pos.x * 0.01, ofGetElapsedTimef()*0.2); vel += frc * 0.04; } } else if( mode == PARTICLE_MODE_NOISE ){ ofPoint attractPt(ofGetMouseX(), ofGetMouseY()); frc = attractPt-pos; // we get the attraction force/vector by looking at the mouse pos relative to our pos //let get the distance and only repel points close to the mouse float dist = frc.length(); // This creates a float which is the distance from the mouse frc.normalize(); //by normalizing we disregard how close the particle is to the attraction point vel *= drag; // apply drag if( dist < 150 ){ vel += -frc * 0.4; //apply force// notice the frc is negative // }else{ //lets simulate falling snow //the fake wind is meant to add a shift to the particles based on where in x they are //we add pos.y as an arg so to prevent obvious vertical banding around x values - try removing the pos.y * 0.006 to see the banding float fakeWindX = ofSignedNoise(pos.x * 0.003, pos.y * 0.6, ofGetElapsedTimef() * 0.6); // frc.x controls the movement the particles made from left to right frc.x = fakeWindX + ofSignedNoise(uniqueVal, pos.y * 0.04) * 0.6; // frc.y controls the downward movement, notice how fakeWindX is only applied on the x axis // If I remove this line it looks really cool //frc.y = ofSignedNoise(uniqueVal, pos.x * 6, ofGetElapsedTimef()*0.2) * 0.09 + 0.18; vel *= drag; vel += frc * 0.4; //we do this so as to skip the bounds check for the bottom and make the particles go back to the top of the screen if( pos.y + vel.y > ofGetHeight() ){ pos.y -= ofGetHeight(); } } } //2 - UPDATE OUR POSITION pos += vel; //3 - (optional) LIMIT THE PARTICLES TO STAY ON SCREEN //we could also pass in bounds to check - or alternatively do this at the ofApp level if( pos.x > ofGetWidth() ){ pos.x = ofGetWidth(); vel.x *= -1.0; }else if( pos.x < 0 ){ pos.x = 0; vel.x *= -1.0; } if( pos.y > ofGetHeight() ){ pos.y = ofGetHeight(); vel.y *= -1.0; } else if( pos.y < 0 ){ pos.y = 0; vel.y *= -1.0; } } //------------------------------------------------------------------ void demoParticle::draw(){ if( mode == PARTICLE_MODE_NOISE ){ ofSetColor(00, 00, 00); } else if( mode == PARTICLE_MODE_REPEL ){ ofSetColor(00, 00, 00); } ofDrawCircle(pos.x, pos.y, scale * 4.0); }
true
f575bb16a484399e4106a8f2400429577776e7a9
C++
wpd550/Boost-
/Caption04/ppTool/ppTool/main.cpp
UTF-8
3,261
3.046875
3
[]
no_license
// // main.cpp // ppTool // // Created by wudong on 2019/1/11. // Copyright © 2019 wudong. All rights reserved. // #include <iostream> #include <boost/noncopyable.hpp> //不可拷贝类 #include <boost/version.hpp> #include <vector> #include <string> class do_not_copy: boost::noncopyable { public: int a =10; }; //template<class T> //struct Alloc{}; //template<class T> //using Vec = std::vector<T,Alloc<T>>; //Vec<int> V; template<class T> struct A; template <typename InputIterator> std::pair<InputIterator, size_t> max_sequence(InputIterator first, InputIterator last) { InputIterator maxfirst = last; size_t maxlen = 0; while (first != last) { InputIterator seqfirst = first; size_t len = 1; InputIterator prev = seqfirst; ++first; while (first != last && *prev + 1 == *first) { ++len; prev = first; ++first; } if (maxlen < len) { maxlen = len; maxfirst = seqfirst; } } return std::pair<InputIterator, size_t>(maxfirst, maxlen); } struct MyStruct { MyStruct(int&& a){ std::cout<<"右值引用 a = "<<++a<<std::endl; } MyStruct(int& a) { std::cout<<"左值引用 a = "<<a<<std::endl; } }; #define PP 5 void case4() { MyStruct mystruct(PP); int a=20; MyStruct mystruct1(std::forward<int>(a)); std::cout<<"a = "<<a<<std::endl; std::cout<<"PP ="<<PP<<std::endl; std::string str1 = "domon"; std::string str2 = "hp"; std::cout<<"str1 = "<<str1<<std::endl; std::string str3 = std::move(str1); std::cout<<"str1 = "<<str1<<std::endl; } template<typename T> void test1(T&& t) { std::cout<<"rValue"<<std::endl; } template<typename T> void test1(T& t) { std::cout<<"lValue"<<std::endl; } template <typename T> void test2(T&& t) { test1(t); test1(std::move(t)); test1(std::forward<T>(t)); } void case5() { test2(10); int a=10; std::cout<<"-----------------\n"; test2(a);// a 默认被转化为lValue /** lValue rValue lValue */ std::cout<<"-----------------\n"; test2(std::forward<int>(a)); //保持右值引用 /** lValue rValue rValue */ std::cout<<"-----------------\n"; test2(std::move(a)); //保持右值引用,move 函数对内置变量无效,对类使用 std::cout<<"a = "<<a<<std::endl; } //不可拷贝类 void case1() { do_not_copy A; std::cout<<A.a<<std::endl; // do_not_copy B(A); //不支持拷贝构造g函数 do_not_copy C; // C = A; // 不支持复制构造函数 } void case2() { using flags =std::ios_base::fmtflags; flags fl = std::ios_base::dec; } void case3() { std::vector<int> vec{0,1,2,3,4,5,6,7,8,9}; std::vector<int> vec1(10); std::copy(vec.begin(), vec.end(), vec1.begin()); for(auto&& i: vec1) { std::cout<<i<<std::endl; } max_sequence(vec.begin(), vec.end()); } int main(int argc, const char * argv[]) { // insert code here... std::cout << "version: "<< BOOST_VERSION<<"\n"; // case3(); // case4(); case5(); return 0; }
true
5d7e24db0ec21eade39c7c194552c075895bc2bf
C++
alexandraback/datacollection
/solutions_5738606668808192_1/C++/letsRock/c_large.cpp
UTF-8
2,010
3.03125
3
[]
no_license
#include <iostream> #include <algorithm> #include <vector> int N, J; int c = 0; unsigned long long e[11]; using namespace std; unsigned long long mod_exp (unsigned long long n, unsigned long long e, unsigned long long mod) { if(e == 0) return 1; if(e == 1) { return (n % mod); } else { if((e % 2) == 1) { unsigned long long temp = mod_exp(n, (e-1)/2, mod); return ((n * temp * temp) % mod); } else { unsigned long long temp = mod_exp(n, e/2, mod); return ((temp*temp) % mod); } } } unsigned long long modExp(unsigned long long b, unsigned long e, unsigned long long m) { unsigned long long remainder; unsigned long long x = 1; while (e != 0) { remainder = e % 2; e= e/2; if (remainder == 1) x = (x * b) % m; b= (b * b) % m; // New base equal b^2 % m } return x; } #define CHECK 500 bool isPrime(string val, unsigned long long * d, unsigned int base){ for(int k=2; k<CHECK; k++){ unsigned long long sum = 0; unsigned long long exp = 0; for(int j=val.size() -1; j>=0; j--){ if(val[j] == '1'){ if(mod_exp(base,exp,k) != modExp(base, exp,k)) cout << "ne" << endl; sum += mod_exp(base,exp,k); } exp++; } sum %= k; if(sum == 0){ *d = k; return false; } } return true; } void generate(int i,string s){ if(i == 0) generate(i + 1, s + '1'); if(i == N - 1) generate(i + 1, s + '1'); else if(i < N){ generate(i + 1, s + '0'); generate(i + 1, s + '1'); } else if( c < J ){ bool ok = true; //unsigned int val[11]; for(int j = 2; j <= 10; j++){ e[j] = 0; if(isPrime(s,&e[j],j)){ ok = false; break; } } if(ok){ cout << s; for(int j=2; j<=10; j++){ cout << " " << e[j]; } cout << endl; c++; if(c==J) exit(0); } } } int main(){ int T; cin >> T; cin >> N >> J; cout << "Case #1:" << endl; generate(0,""); }
true
26a9b037d69f46b0e940f9fb3efa7680da330b7b
C++
hychen-naza/Arduino
/Electronic_dice/Electronic_dice.ino
UTF-8
1,510
3
3
[]
no_license
int button_pin = 2; int random_value; int LED_pins[9] = {3, 4, 5, 6, 7, 8, 9, 10, 11}; void setup() { // put your setup code here, to run once: for(int i = 0; i < 9; i++){ pinMode(LED_pins[i], OUTPUT); } pinMode(button_pin, INPUT); Serial.begin(9600); } void loop() { int button_state = digitalRead(button_pin); if (button_state == HIGH){ random_value = random(1, 7); for(int i = 0; i < 9; i++){ digitalWrite(LED_pins[i], LOW); } } Serial.println(random_value); switch (random_value){ case 1: digitalWrite(LED_pins[4], HIGH); break; case 2: digitalWrite(LED_pins[0], HIGH); digitalWrite(LED_pins[8], HIGH); break; case 3: digitalWrite(LED_pins[0], HIGH); digitalWrite(LED_pins[4], HIGH); digitalWrite(LED_pins[8], HIGH); break; case 4: digitalWrite(LED_pins[0], HIGH); digitalWrite(LED_pins[2], HIGH); digitalWrite(LED_pins[6], HIGH); digitalWrite(LED_pins[8], HIGH); break; case 5: digitalWrite(LED_pins[0], HIGH); digitalWrite(LED_pins[2], HIGH); digitalWrite(LED_pins[4], HIGH); digitalWrite(LED_pins[6], HIGH); digitalWrite(LED_pins[8], HIGH); break; case 6: digitalWrite(LED_pins[0], HIGH); digitalWrite(LED_pins[2], HIGH); digitalWrite(LED_pins[3], HIGH); digitalWrite(LED_pins[5], HIGH); digitalWrite(LED_pins[6], HIGH); digitalWrite(LED_pins[8], HIGH); break; } }
true
b08ea219143c3ad042bc5e4a346f1102539e83f8
C++
mnive93/GUI-Game-C-
/database/db.cpp
UTF-8
1,408
2.75
3
[]
no_license
#include "db.h" #include<iostream> #include <mysql_connection.h> #include <driver.h> #include <cppconn/exception.h> #include<stdio.h> #include <iostream> using namespace std; using namespace sql; /** * Singleton pattern for database to have only one connection open */ MySQLDB* MySQLDB::s_instance = NULL; MySQLDB* MySQLDB:: instance() { if (!s_instance) s_instance = new MySQLDB; return s_instance; } MySQLDB ::MySQLDB() { try { cout << "connecting to mysql server...."; driver = get_driver_instance(); con = driver->connect("tcp://127.0.0.1:3306", "root", "root"); cout << "connected" << endl; con->setSchema("rps"); }catch (sql::SQLException &e) { } } void MySQLDB ::insert_data(string game_id, string player, int rock, int paper, int scissors) { try { prep_stmt = con->prepareStatement( "INSERT INTO game_details(game_id,player,rock,paper,scissors) VALUES(?,?,?,?,?)"); prep_stmt->setString(1, game_id); prep_stmt->setString(2, player); prep_stmt->setInt(3, rock); prep_stmt->setInt(4, paper); prep_stmt->setInt(5, scissors); prep_stmt->execute(); }catch (sql :: SQLException &e){ } } void MySQLDB :: close(){ try { cout << "connection \n"; con->close(); }catch (sql :: SQLException &e){ } }
true
9585a8445664e1cf60664cf9782ddd677db3738b
C++
cnclabs/codes.tpr.rec
/src/optimizer/pair_optimizer.h
UTF-8
1,322
2.546875
3
[ "MIT" ]
permissive
#ifndef PAIR_OPTIMIZER_H #define PAIR_OPTIMIZER_H #include <stdlib.h> #include <cmath> #include <iostream> #include <vector> #define SIGMOID_TABLE_SIZE 1000 #define MAX_SIGMOID 8.0 class PairOptimizer { private: void init_sigmoid(); public: // constructor PairOptimizer(); // variables std::vector<double> cached_sigmoid; // functions double fast_sigmoid(double value); // loss void feed_l2_loss(std::vector<double>& embedding, int dimension, std::vector<double>& loss); void feed_dotproduct_loss(std::vector<double>& from_embedding, std::vector<double>& to_embedding, double label, int dimension, std::vector<double>& from_loss, std::vector<double>& to_loss); void feed_loglikelihood_loss(std::vector<double>& from_embedding, std::vector<double>& to_embedding, double label, int dimension, std::vector<double>& from_loss, std::vector<double>& to_loss); }; #endif
true
8c78e6c1417af0316aecb72743c7838148812a61
C++
senior-cpp-developer/GraphProject
/src/SeriousGraphTools/Graph/Edge.h
UTF-8
954
3.109375
3
[]
no_license
#ifndef GRAPHPROJECT_EDGE_H #define GRAPHPROJECT_EDGE_H #include "Node.h" namespace SeriousGraphTools { class Edge { Node* from; Node* to; double weight; bool isBi_; public: Edge(Node* from, Node* to, double weight, bool isBi) : from(from), to(to), weight(weight), isBi_(isBi) {}; Node *getFrom() const { return from; } void setFrom(Node *from) { Edge::from = from; } Node *getTo() const { return to; } void setTo(Node *to) { Edge::to = to; } double getWeight() const { return weight; } void setWeight(double weight) { Edge::weight = weight; } bool isBi() const { return isBi_; } void setBi(bool isBi) { isBi_ = isBi; } }; } #endif //GRAPHPROJECT_EDGE_H
true
ec62350b69c92882c9c640d4b8e92ae2b0da2cf1
C++
troe88/baly
/src/Daemon.cpp
UTF-8
3,817
2.640625
3
[]
no_license
/* * Daemon.cpp * * Created on: May 3, 2015 * Author: dmitry */ #include "Daemon.h" #include "ConfigReader.h" #define EVENT struct inotify_event * std::vector<std::string> Daemon::dir; std::map<int, std::string> Daemon::_in_dir; int ftw_handler(const char *name, const struct stat *status, int type) { if (type == FTW_NS) return 0; if (type == FTW_D) Daemon::dir.push_back(name); return 0; } Daemon::Daemon() { _inotify_discriptor = 0; _is_running = true; _is_need_reup = true; } void Daemon::start() { my_print(LOG_INFO, ToString() << "Daemon is start..."); process(); } void Daemon::process() { while (_is_running) { if (_is_need_reup) { clearData(); if (init() < 0) return; _is_need_reup = false; } if (haveEvent()) { char buffer[256]; read(this->_inotify_discriptor, buffer, 256); EVENT event = (EVENT)&buffer[(size_t) 0]; dispalyEvent(event); } } close(this->_inotify_discriptor); my_print(LOG_INFO, ToString() << "Daemon is close..."); } int Daemon::init() { try { ConfigReader::read(CONFIG_PATH); } catch (const char* msg) { this->_is_running = false; my_print(LOG_ERR, ToString() << msg); return -1; } ftw(ConfigReader::_input_path.c_str(), ftw_handler, 1); if(Daemon::dir.empty()){ my_print(LOG_ERR, ToString() << "Directory list is empty"); return -1; } _inotify_discriptor = inotify_init(); if (_inotify_discriptor < 0) { my_print(LOG_ERR, ToString() << "initify init error" << strerror(errno)); this->_is_running = false; return -1; } for (std::size_t i = 0; i < Daemon::dir.size(); i++) { std::string temp = Daemon::dir.at(i); setWatcher(temp); } cout << Daemon::_in_dir.size() << endl; return 0; } void Daemon::setWatcher(const std::string &cur_dir) { int watch_dir_index = inotify_add_watch(_inotify_discriptor, cur_dir.c_str(), IN_ALL_EVENTS); if (watch_dir_index < 0) { my_print(LOG_ERR, ToString() << "add watcher to " << cur_dir << " error: " << strerror(errno)); } else { Daemon::_in_dir[watch_dir_index] = cur_dir; my_print(LOG_INFO, ToString() << "add watcher to " << cur_dir); } } void Daemon::dispalyEvent(struct inotify_event *event) { string name; string type; if (event->len) { name = event->name; } if (event->mask & IN_ISDIR) { type = "Dir"; } else { type = "File"; } std::stringstream stream; std::stringstream abs_pwd; abs_pwd << Daemon::_in_dir[event->wd] << "/" << name; stream << " name:" << abs_pwd.str() << "; type:" << type << "; event:"; switch (event->mask) { case IN_ACCESS: stream << "IN_ACCESS" << endl; return; case IN_MODIFY: stream << "IN_MODIFY" << endl; break; case IN_ATTRIB: stream << "IN_ATTRIB" << endl; break; case IN_CLOSE_WRITE: stream << "IN_CLOSE_WRITE" << endl; return; case IN_CLOSE_NOWRITE: stream << "IN_CLOSE_NOWRITE" << endl; return; case IN_CLOSE: stream << "IN_CLOSE" << endl; return; case IN_OPEN: stream << "IN_OPEN" << endl; return; break; case IN_MOVED_FROM: stream << "IN_MOVED_FROM" << endl; return; case IN_MOVED_TO: stream << "IN_MOVED_TO" << endl; return; break; case IN_MOVE: stream << "IN_MOVE" << endl; return; case IN_CREATE: stream << "IN_CREATE" << endl; break; case IN_DELETE: stream << "IN_DELETE" << endl; break; case IN_DELETE_SELF: stream << "IN_DELETE_SELF" << endl; break; case IN_MOVE_SELF: stream << "IN_MOVE_SELF" << endl; return; case IN_CREATE | IN_ISDIR: stream << "IN_CREATE | IN_ISDIR" << endl; setWatcher(abs_pwd.str()); break; case IN_DELETE | IN_ISDIR: stream << "IN_DELETE | IN_ISDIR" << endl; break; default: stream << "ENOTHER_EVENT" << endl; return; } my_print(LOG_INFO, stream.str()); } void Daemon::clearData() { Daemon::_in_dir.clear(); Daemon::dir.clear(); }
true
96f36464d26ae7719d1ee677a63d9a281120f252
C++
Jordan-Betcher/CPPAssignment2
/Assignment2/src/OrderedLinkedList.h
UTF-8
3,513
3.8125
4
[]
no_license
//============================================================================ // Name : OrderedLinkedList.h // Author : Jordan Betcher // Date : 10/23/2017 // Description : OrderedLinkedList a LinkedList that inserts based on comparative operators //============================================================================ #ifndef ORDEREDLINKEDLIST_H_ #define ORDEREDLINKEDLIST_H_ #include "LinkedList.h" template<class T> class OrderedLinkedList: public LinkedList<T> { public: OrderedLinkedList(); void insertNode(T& itemToInsert); bool hasNode(T& itemToFind); T& searchForNode(T& itemToFind); ~OrderedLinkedList(); }; //Creates an OrderedLinkedList template<class T> OrderedLinkedList<T>::OrderedLinkedList() { this->pFirstNode = NULL; this->pLastNode = NULL; this->count = 0; } //Inserts a Node into OrderedLinkedList in the proper order by comparison template<class T> void OrderedLinkedList<T>::insertNode(T& itemToInsert) { node<T> *newNode = new node<T>; newNode->data = itemToInsert; newNode->pNextNode = NULL; if (this->pFirstNode == NULL) { this->pFirstNode = newNode; this->pLastNode = newNode; } else { if (this->pFirstNode->data > itemToInsert) { node<T>* nextNode = this->pFirstNode; this->pFirstNode = newNode; this->pFirstNode->pNextNode = nextNode; } else { node<T>* pointerBefore = this->pFirstNode; node<T>* pointerToFind = pointerBefore->pNextNode; while (pointerToFind != NULL && pointerToFind->data < itemToInsert) { pointerBefore = pointerToFind; pointerToFind = pointerToFind->pNextNode; } if (pointerToFind != NULL) { pointerBefore->pNextNode = newNode; newNode->pNextNode = pointerToFind; delete pointerToFind; } else { this->pLastNode->pNextNode = newNode; this->pLastNode = newNode; } } } this->count++; } //Searches if OrderedLinkedList contains a node with the itemToFind template<class T> bool OrderedLinkedList<T>::hasNode(T& itemToFind) { if (this->pFirstNode == NULL) { } else { if (this->pFirstNode->data == itemToFind) { return true; } else { node<T>* pointerBefore = this->pFirstNode; node<T>* pointerToFind = pointerBefore->pNextNode; while (pointerToFind != NULL && pointerToFind->data != itemToFind) { pointerBefore = pointerToFind; pointerToFind = pointerToFind->pNextNode; } if (pointerToFind != NULL) { T found = pointerToFind->data; delete pointerToFind; return true; } } } return false; } //Searches for the itemToFind template<class T> inline T& OrderedLinkedList<T>::searchForNode(T& itemToFind) { if (this->pFirstNode == NULL) { } else { if (this->pFirstNode->data == itemToFind) { return this->pFirstNode->data; } else { node<T>* pointerBefore = this->pFirstNode; node<T>* pointerToFind = pointerBefore->pNextNode; while (pointerToFind != NULL && pointerToFind->data != itemToFind) { pointerBefore = pointerToFind; pointerToFind = pointerToFind->pNextNode; } if (pointerToFind != NULL) { T& found = pointerToFind->data; delete pointerToFind; return found; } } } throw exception(); } template<class T> OrderedLinkedList<T>::~OrderedLinkedList() { this->destroyList(); } #endif /* ORDEREDLINKEDLIST_H_ */
true
b586293d8bc115078db9e393fe79b7b1d11b56f5
C++
AngheloAlf/2020-1_ProgCompetitiva
/clases/08/52C/52C.cpp
UTF-8
4,559
2.875
3
[]
no_license
#include <iostream> #include <vector> #include <sstream> #include <cmath> #define MIN(x, y) ((x) < (y) ? (x) : (y)) #define TAMANO(n) std::exp2l(std::ceil(std::log2l(n+1))+1) void construir_arbol(std::vector<long long> &arbol, const std::vector<long long> &datos, size_t izquierda, size_t derecha, size_t pivote){ if(izquierda == derecha){ arbol[pivote] = datos[derecha-1]; return; } size_t mitad = (izquierda + derecha) / 2; size_t pivote_izquierdo = 2*pivote; size_t pivote_derecho = 2*pivote + 1; construir_arbol(arbol, datos, izquierda, mitad, pivote_izquierdo); construir_arbol(arbol, datos, mitad+1, derecha, pivote_derecho); arbol[pivote] = MIN(arbol[pivote_izquierdo], arbol[pivote_derecho]); } void calcular_postergado(std::vector<long long> &arbol, std::vector<long long> &lazy, size_t pivote){ if(lazy[pivote] == 0){ return; } arbol[pivote] += lazy[pivote]; size_t pivote_izquierdo = 2*pivote; size_t pivote_derecho = 2*pivote + 1; if(pivote_derecho < lazy.size()){ lazy[pivote_izquierdo] += lazy[pivote]; lazy[pivote_derecho] += lazy[pivote]; } lazy[pivote] = 0; } void sumar_al_rango(std::vector<long long> &arbol, std::vector<long long> &lazy, size_t lf, size_t rg, long long v, size_t izquierda, size_t derecha, size_t pivote){ calcular_postergado(arbol, lazy, pivote); if(rg < izquierda || derecha < lf){ return; } if(lf <= izquierda && derecha <= rg){ lazy[pivote] += v; calcular_postergado(arbol, lazy, pivote); return; } size_t mitad = (izquierda + derecha) / 2; size_t pivote_izquierdo = 2*pivote; size_t pivote_derecho = 2*pivote + 1; sumar_al_rango(arbol, lazy, lf, rg, v, izquierda, mitad, pivote_izquierdo); sumar_al_rango(arbol, lazy, lf, rg, v, mitad+1, derecha, pivote_derecho); arbol[pivote] = MIN(arbol[pivote_izquierdo], arbol[pivote_derecho]); } long long menor_en_rango(std::vector<long long> &arbol, std::vector<long long> &lazy, size_t lf, size_t rg, size_t izquierda, size_t derecha, size_t pivote){ if(rg < izquierda || derecha < lf){ return 1LL<<60; } calcular_postergado(arbol, lazy, pivote); if(lf <= izquierda && derecha <= rg){ return arbol[pivote]; } size_t mitad = (izquierda + derecha) / 2; size_t pivote_izquierdo = 2*pivote; size_t pivote_derecho = 2*pivote + 1; long long val_izq = menor_en_rango(arbol, lazy, lf, rg, izquierda, mitad, pivote_izquierdo); long long val_der = menor_en_rango(arbol, lazy, lf, rg, mitad+1, derecha, pivote_derecho); return MIN(val_izq, val_der); } int leer_numeros(size_t &lf, size_t &rg, long long &v){ std::string line; std::getline(std::cin, line); std::istringstream is(line); long long number; int i = 0; while(is >> number){ switch(i){ case 0: lf = number; break; case 1: rg = number; break; case 2: v = number; break; default: break; } ++i; } return i; } int main(){ std::ios::sync_with_stdio(false); size_t n; std::cin >> n; size_t tamano_arbol = TAMANO(n); std::vector<long long> lista_a; lista_a.resize(n, 0); std::vector<long long> arbol; arbol.resize(tamano_arbol, 0); std::vector<long long> lazy; lazy.resize(tamano_arbol, 0); for(size_t i = 0; i < n; ++i){ std::cin >> lista_a[i]; } construir_arbol(arbol, lista_a, 1, n, 1); long long m; std::cin >> m; std::cin.ignore(); size_t lf, rg; long long v; while(m--){ int i = leer_numeros(lf, rg, v); ++lf; ++rg; if(i == 2){ if(rg < lf){ long long a = menor_en_rango(arbol, lazy, lf, n, 1, n, 1); long long b = menor_en_rango(arbol, lazy, 1, rg, 1, n, 1); std::cout << MIN(a, b) << std::endl; } else{ std::cout << menor_en_rango(arbol, lazy, lf, rg, 1, n, 1) << std::endl; } } else{ if(rg < lf){ sumar_al_rango(arbol, lazy, lf, n, v, 1, n, 1); sumar_al_rango(arbol, lazy, 1, rg, v, 1, n, 1); } else{ sumar_al_rango(arbol, lazy, lf, rg, v, 1, n, 1); } } } return 0; }
true
719ea5cccea7c6d5b3874bf8d7846b8df2cc04e2
C++
devvsda/gargantua
/src/com/devsda/gargantua/asignments/2/64.cpp
UTF-8
640
3.453125
3
[ "MIT" ]
permissive
#include<iostream> using namespace std; void printPermutationRecur(char *s1, char *answer, int length, int index) { for(int i = 0; i <= length; i++) { answer[index] = s1[i]; if(index == (length)) { printf("%s\n", answer); } else printPermutationRecur(s1, answer, length, index+1); } } void printPermutation(char *s1, int length) { char *answer = (char *)malloc(sizeof(char)*(length+1)); answer[length] = '\0'; printPermutationRecur(s1, answer, length-1, 0); } main() { char *s1 = "XXY"; printPermutation(s1, 3); return 0; }
true
f9395a437041e2efd1e0b2a453ae16ddcf824a9a
C++
NOVACProject/NOVACProgram
/UserSettings.h
UTF-8
1,159
2.578125
3
[]
no_license
#pragma once #include "Common/Common.h" /** The class <b>CUserSettings</b> stores the preferences for the current user. This can be e.g. the unit to use on the flux. */ class CUserSettings { public: // ---------------------------------------------------------------- // ------------------ READING/WRITING THE SETTINGS ---------------- // ---------------------------------------------------------------- /** Writes the settings to file */ void WriteToFile(); /** Reads the settings from file */ void ReadSettings(const CString* fileName = nullptr); // ----------------------------------------------------------- // --------------------- THE SETTINGS ------------------------ // ----------------------------------------------------------- // the unit to use of the fluxes FLUX_UNIT m_fluxUnit = UNIT_TONDAY; // the unit to use of the columns COLUMN_UNIT m_columnUnit = UNIT_PPMM; // The preferred language LANGUAGES m_language = LANGUAGE_ENGLISH; private: /** The name of the user-settings file */ CString m_userSettingsFile; };
true
e483f0803260704fa1d6e2cf3d9fd6a5e20f7aee
C++
Subsystems-us/Starship
/Starship_tilt.ino
UTF-8
3,864
3.15625
3
[]
no_license
// This program calibrates the accelerometer and then // Acts as a tilt sensor to show the relative angle // in the X and Y axis directions. // Map the Arduino pins to the Starship functions #define shift_data 3 // Data for the LED shift registers #define shift_clk 4 // Clock for the LED shift registers #define lpod_latch 5 // Register latch for the left Power Pod #define rpod_latch 6 // Register latch for the right Power Pod #define disk_left_latch 7 // Latch for the left disk LEDs #define disk_right_latch 8 // Latch for the right disk LEDs #define led_red 9 // Red LED for the color sensor #define led_blue 10 // Blue LED for the color sensor #define led_green 11 // Green LED for the color sensor #define disk_speaker 12 // Speaker connection #define button_input 13 // User button #define temperature_sensor A0 // Temperature sensor input #define light_sensor A1 // Light sensor input #define color_sensor A2 // Color sensor input #define accl_X A3 // Accelerometer analog X-axis signal #define accl_Y A4 // Accelerometer analog Y-axis signal #define accl_Z A5 // Accelerometer analog Z-axis signal int maxX = 0; int maxY = 0; int maxZ = 0; int minX = 1024; int minY = 1024; int minZ = 1024; void setup() { // Start the Serial connection at 9600 baud Serial.begin(9600); // Set the pin Modes pinMode(led_red, OUTPUT); pinMode(led_blue, OUTPUT); pinMode(led_green, OUTPUT); pinMode(shift_data, OUTPUT); pinMode(shift_clk, OUTPUT); pinMode(lpod_latch , OUTPUT); pinMode(rpod_latch , OUTPUT); pinMode(disk_left_latch, OUTPUT); pinMode(disk_right_latch, OUTPUT); pinMode(disk_speaker, OUTPUT); pinMode(button_input, INPUT); // Turn off color sensor LEDs digitalWrite(led_red, LOW); // Turn off the red LED digitalWrite(led_blue, LOW); // Turn off the blue LED digitalWrite(led_green, LOW); // Turn off the green LED dispOff(); // Turn off all register LEDs Serial.begin(9600); Serial.println("Move the Starship through 360 degrees"); Serial.println("Press the button when done"); int tempAcc; while (digitalRead(button_input)) { tempAcc = analogRead(accl_X); if (tempAcc > maxX) maxX = tempAcc; if (tempAcc < minX) minX = tempAcc; tempAcc = analogRead(accl_Y); if (tempAcc > maxY) maxY = tempAcc; if (tempAcc < minY) minY = tempAcc; tempAcc = analogRead(accl_Z); if (tempAcc > maxZ) maxZ = tempAcc; if (tempAcc < minZ) minZ = tempAcc; } Serial.println("Calibration Complete."); } void loop() { int curVal = analogRead(accl_X); acclLevelX(curVal); curVal = analogRead(accl_Y); acclLevelY(curVal); delay(100); } void dispNum(char ledSet, char ledValue) { // set the desired latch low digitalWrite(ledSet, LOW); // shift out the desired number shiftOut(shift_data, shift_clk, MSBFIRST, ledValue); // set the desired latch high digitalWrite(ledSet, HIGH); } void dispOff() { // Turn all lights off dispNum(rpod_latch, 0); dispNum(lpod_latch, 0); dispNum(disk_left_latch, 0); dispNum(disk_right_latch, 0); } void acclLevelX(int curLevel) { byte vals[9] = {0, 1, 2, 4, 8, 16, 32, 64, 128}; if (curLevel > maxX) curLevel = maxX; if (curLevel < minX) curLevel = minX; int diffX = (curLevel - minX) / ((maxX - minX) / 8); dispNum(lpod_latch, vals[diffX]); dispNum(rpod_latch, vals[diffX]); } void acclLevelY(int curLevel) { byte vals[9] = {0, 1, 2, 4, 8, 16, 32, 64, 128}; if (curLevel > maxX) curLevel = maxX; if (curLevel < minX) curLevel = minX; int diffY = (curLevel - minX) / ((maxX - minX) / 16); dispNum(disk_left_latch, 0); dispNum(disk_right_latch, 0); if (diffY < 9) dispNum(disk_right_latch, vals[diffY]); else dispNum(disk_left_latch, vals[17 - diffY]); }
true
10638265897d9cc4e1a256f9c31c8188b054c285
C++
Jato30/IDJ
/src/Bullet.cpp
UTF-8
1,333
2.8125
3
[]
no_license
#include "Bullet.hpp" Bullet::Bullet(float x, float y, float angle, float speed, float maxDistance, std::string sprite, float frameTime, int frameCount, bool target) : GameObject(){ sp = Sprite(sprite); sp.SetFrameTime(frameTime); sp.SetFrameCount(frameCount); box = Rect(x, y, sp.GetWidth(), sp.GetHeight()); Bullet::speed.x = speed * std::cos(angle); Bullet::speed.y = speed * std::sin(angle); distanceLeft = maxDistance; rotation = angle; targetsPlayer = target; } void Bullet::Update(float dt){ sp.Update(dt); Vec2 bulletHead(box.GetCenter().x, box.GetCenter().y); box.x += speed.x * dt; box.y += speed.y * dt; distanceLeft -= std::sqrt(std::pow((box.GetCenter().x) - bulletHead.x, 2) + std::pow((box.GetCenter().y) - bulletHead.y, 2)); } void Bullet::Render(){ sp.Render((int) (box.x - (box.w / 2)) + Camera::pos.x, (int) (box.y - (box.h / 2)) + Camera::pos.y, rotation); } bool Bullet::IsDead(){ return distanceLeft < 0; } void Bullet::NotifyCollision(GameObject& other){ if(!other.Is("Bullet")){ if(!targetsPlayer && other.Is("Alien")){ distanceLeft = -1; } if(targetsPlayer && !other.Is("Alien")){ distanceLeft = -1; } } } bool Bullet::Is(std::string type){ return (type == "Bullet"); }
true
3530512d4dd5284978c2200c16c17cade56f7d2f
C++
bdchatham/OSU
/CS165/Final Project/Maze/main.cpp
UTF-8
12,330
3.328125
3
[]
no_license
/********** ** Program: Final Project ** Author: Aryan Aziz ** Description: Maze game with some extra features! ** Input: Various ** Output: Various **********/ /********** ** Re-Evaluation Sections ** Not sure if the items I want re-evaluated can be, but if it's possible please look into the following: ** Week 4 Assignment; Testing Section ** In the program, I lost 5 points for "Treats uppercase and lowercase characters as different values" ** Please see line 109 where I convert all values to lowercase so that they can be treated as the same. ** Week 6 Assignment; Implementation ** In the assignment, I lost 2 points for "Not playing again should probably return to the main menu." ** On line 366, I have the end of the do-while loop that takes the user back to the main menu if they want to play again **********/ #include <iostream> #include <string> #include <cctype> #include <limits> #include <vector> //######## Requirement #32 ######## #include <fstream> #include "node.h" //######## Requirement #26 ######## #include <cstdlib> //Variables bool finish = false; std::string choices[4]; int boardArrayX = 4; int boardArrayY = 3; char** boardArray; std::string name; //######## Requirement #15 ######## char nameArray[20]; char mainMenuChoice; std::vector<node> roomList; //######## Requirement #28 ######## std::vector<node> breadCrumbs; char again; namespace aziza { //######## Requirement #25 ######## void initializeMaze(node *x, bool north, bool south, bool east, bool west) { x->setNorthBool(north); //######## Requirement #24 ######## x->setSouthBool(south); x->setEastBool(east); x->setWestBool(west); } void initializeNeighbors(node *x, node *north, node *south, node *east, node *west) { x->setNorth(north); x->setSouth(south); x->setEast(east); x->setWest(west); } void generateBoard(int x, int y, node& z) { boardArray[x][y] = z.getRoomId(); } void getName(char* x) { name = std::string(x); } } class InputSource { //######## Requirement #21 ######## public: virtual char getCommand() = 0; }; class CinInputSource : public InputSource { //######## Requiement #33 ######## public: virtual char getCommand() { //######## Requiement #34 ######## char move; std::cin >> move; return move; } }; InputSource* daInputSource; struct game { //######## Requirement #20 ######## std::string name; int score; }; //Gets the possible moves and gets the move from the user char getMove(node x) { //######## Requirement #13 ######## std::string choices[4] = {"", "", "", ""}; if(x.getNorthBool() == true) { choices[0] = "North"; } if(x.getSouthBool() == true) { choices[1] = "South"; } if(x.getEastBool() == true) { choices[2] = "East"; } if(x.getWestBool() == true) { choices[3] = "West"; } std::cout << "From here, you can go: "; for(int i = 0; i < 4; i++) { std::cout << choices[i] << " "; } std::cout << std::endl; bool validChoice = false; char move; std::cout << "Please enter your move (either N, S, E, W): " << std::endl; std::cout << "Or, if you're lost, enter 'b' for the room path back to the start" << std::endl; std::cout << "Conversely, you can also enter 'l' for a general board layout (no connections are shown because this is a maze!" << std::endl; move = daInputSource->getCommand(); //Get the move move = tolower(move); //Lowercase it so that it you treat upper and lowercase the same while(validChoice == false) { while(choices[0] != "North" && move == 'n') { //If they enter n and they can't move north std::cout << "That was not a valid move, please enter a valid move: "; std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); move = daInputSource->getCommand(); } while(choices[1] != "South" && move == 's') { //If they enter s and they can't move south std::cout << "That was not a valid move, please enter a valid move: "; std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); move = daInputSource->getCommand(); } while(choices[2] != "East" && move == 'e') { //If they enter e and they can't move east std::cout << "That was not a valid move, please enter a valid move: "; std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); move = daInputSource->getCommand(); } while(choices[3] != "West" && move == 'w') { //If they enter w and they can't move west std::cout << "That was not a valid move, please enter a valid move: "; std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); move = daInputSource->getCommand(); } //If they enter anything else while(move != 'n' && move != 's' && move != 'e' && move != 'w' && move != 'b' && move != 'l') { //######## Requirement #9 ######## std::cout << "That was not a valid move, please enter a valid move: "; std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); move = daInputSource->getCommand(); } while(move == 'b') { //If they enter the breadcrumb choice std::cout << "The path back to the start is: "; for(int i = 0; i < breadCrumbs.size(); i++) { std::cout << breadCrumbs[i].getRoomId() << " "; } std::cout << std::endl; std::cout << "Please enter your move (either N, S, E, W): "; std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); move = daInputSource->getCommand(); } while(move == 'l') { //If they enter the layout std::cout << "The node layout of the board is: " << std::endl; for(int i = 0; i < 4; i++) { for(int j = 0; j < 4; j++) { std::cout << boardArray[i][j] << " "; } std::cout << std::endl; } std::cout << "Please enter your move (either N, S, E, W): "; std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); move = daInputSource->getCommand(); } validChoice = true; } return move; } node* goThere(node *x, char y) { //Actually gets the specific neighbor if(y == 'n') { return x->getNorth(); } if(y == 's') { return x->getSouth(); } if(y == 'e') { return x->getEast(); } else { return x->getWest(); } } void writeHighScore(game& x) { //######## Requirement #31 ######## std::ofstream ofs; std::string fileName = "scores.txt"; ofs.open(fileName.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::app); ofs << x.name << " " << x.score << "\r\n"; } void showHighScores(void) { std::ifstream ifs; std::string fileName = "scores.txt"; ifs.open(fileName.c_str()); std::string line; while(!ifs.eof()) { getline(ifs, line); std::cout << line << std::endl; } std::cout << std::endl; } //Main move making Function void makeMove(node *x) { //######## Requirement #10 ######## if(breadCrumbs.size() < 1) { breadCrumbs.push_back(*x); //Ads the initial value } std::cout << "================================" << std::endl; std::cout << "You're currently in room " << x->getRoomId() << std::endl; if(x->getRoomId() == 'l') { //If they reached the end std::cout << "You've reached the end!" << std::endl; std::cout << "The route you took to get here: "; game newHighScore; newHighScore.name = name; newHighScore.score = roomList.size(); for(int i = 0; i < roomList.size(); i++) { std::cout << roomList[i].getRoomId() << " "; //Show their path } std::cout << std::endl; writeHighScore(newHighScore); finish = true; } else { roomList.push_back(*x); // if(breadCrumbs[breadCrumbs.size() - 2].getRoomId() != x->getRoomId() && breadCrumbs[breadCrumbs.size() - 1].getRoomId() != x->getRoomId()) { breadCrumbs.push_back(*x); } if(breadCrumbs[breadCrumbs.size() - 2].getRoomId() == x->getRoomId()) { breadCrumbs.pop_back(); } makeMove(goThere(x, getMove(*x))); //######## Requirement #16 ######## } } //Starts/runs the actual game itself void runGame(node& a) { while(finish == false) { //######## Requiremeent #6 ######## std::cout << "What would you like to do?" << std::endl; std::cout << "1. Play Game" << std::endl; std::cout << "2. View High Scores" << std::endl; std::cin >> mainMenuChoice; //Since validChoice is defined in another function it can also be used here independently bool validChoice = false; //######## Requirement #12 ######## while(validChoice == false) { //######## Requirement #5 ######## if(mainMenuChoice == '1') { makeMove(&a); validChoice = true; } else if(mainMenuChoice == '2') { showHighScores(); validChoice = true; finish = true; } else { std::cout << "That was not a valid option, please enter 1 or 2: "; } } } std::cout << "Return to the main menu? (y/n) "; //Ask if you want to play again. std::cin >> again; std::cin.ignore(); std::cin.clear(); finish = false; } int randomNumberGenerator(void) { //######## Requirement #7 ######## int randomNum; srand(time(NULL)); randomNum = rand() % 100 + 1; return randomNum; } int main(int argc, char** argv) { //Setup the dynamic 2d array boardArray = new char*[boardArrayX]; //######## Requirement #18 ######## Requirement #22 ######## for(int i = 0; i < boardArrayX; ++i) { boardArray[i] = new char[boardArrayY]; //######## Requirement #17 ######## } //Initialize all the nodes node a('a'); node b('b'); node c('c'); node d('d'); node e('e'); node f('f'); node g('g'); node h('h'); node i('i'); node j('j'); node k('k'); node l('l'); //Setup A aziza::initializeMaze(&a, false, true, true, false); //######## Requirement #11 ######## aziza::initializeNeighbors(&a, NULL, &e, &b, NULL); //Setup B aziza::initializeMaze(&b, false, true, false, true); aziza::initializeNeighbors(&b, NULL, &f, NULL, &a); //Setup C aziza::initializeMaze(&c, false, true, true, false); aziza::initializeNeighbors(&c, NULL, &g, &d, NULL); //Setup D aziza::initializeMaze(&d, false, false, false, true); aziza::initializeNeighbors(&d, NULL, NULL, NULL, &c); //Setup E aziza::initializeMaze(&e, true, true, false, false); aziza::initializeNeighbors(&e, &a, &i, NULL, NULL); //Setup F aziza::initializeMaze(&f, true, false, true, false); aziza::initializeNeighbors(&f, &b, NULL, &g, NULL); //Setup G aziza::initializeMaze(&g, true, true, true, true); aziza::initializeNeighbors(&g, &c, &k, &h, &f); //Setup H aziza::initializeMaze(&h, false, true, false, true); aziza::initializeNeighbors(&h, NULL, &l, NULL, &g); //Setup I aziza::initializeMaze(&i, true, false, true, false); aziza::initializeNeighbors(&i, &e, NULL, &j, NULL); //Setup J aziza::initializeMaze(&j, false, false, false, true); aziza::initializeNeighbors(&j, NULL, NULL, NULL, &i); //Setup K aziza::initializeMaze(&k, true, false, false, false); aziza::initializeNeighbors(&k, &g, NULL, NULL, NULL); //Setup L aziza::initializeMaze(&l, true, false, false, false); aziza::initializeNeighbors(&l, &h, NULL, NULL, NULL); //Setup the board layout for help aziza::generateBoard(0, 0, a); aziza::generateBoard(0, 1, b); aziza::generateBoard(0, 2, c); aziza::generateBoard(0, 3, d); aziza::generateBoard(1, 0, e); aziza::generateBoard(1, 1, f); aziza::generateBoard(1, 2, g); aziza::generateBoard(1, 3, h); aziza::generateBoard(2, 0, i); aziza::generateBoard(2, 1, j); aziza::generateBoard(2, 2, k); aziza::generateBoard(2, 3, l); daInputSource = new CinInputSource(); //Main loop do{ std::cout << std::endl << std::endl << std::endl; std::cout << " __ __ ____________ _____ __ __ ______ " << std::endl; std::cout << " | \\/ | /\\ |___ / ____| / ____| /\\ | \\/ | ____|" << std::endl; std::cout << " | \\ / | / \\ / /| |__ | | __ / \\ | \\ / | |__ " << std::endl; std::cout << " | |\\/| | / /\\ \\ / / | __| | | |_ | / /\\ \\ | |\\/| | __| " << std::endl; std::cout << " | | | |/ ____ \\ / /__| |____ | |__| |/ ____ \\| | | | |____ " << std::endl; std::cout << " |_| |_/_/ \\_\\/_____|______| \\_____/_/ \\_\\_| |_|______|" << std::endl; std::cout << "Welcome to the MazeGame!" << std::endl; //######## Requirement #1 ######## if(argc <= 1) { //######## Requirement #4 ######## std::cout << "What's your name? "; std::cin >> name; //######## Requirement #2 ######## } else { aziza::getName(argv[1]); //######## Requirement #19 ######## } runGame(a); } while (again == 'y' || again == 'Y'); return 0; }
true
e15ec7cda477742c40ad54a351fe3a2e22ec6671
C++
DongDaYo/My-Data-Structure
/Data Structure/Data Structure Project/Exercise - DFSTraverse to find loop.cpp
GB18030
1,096
2.765625
3
[]
no_license
#include "MGraph.cpp" bool visited[MaxVertexNum]; int connect = 0; int connectivity[MaxVertexNum] = { 0 }; MGraph<char> graph(DG); map<char, int> mp; int loop = 0; bool back = false; template<typename T> void DFS(MGraph<T>& graph, int i) { visited[i] = true; connectivity[i] = connect; for (int j = graph.firstneighbor(i); j >= 0; j = graph.nextneighbor(i, j)) { if (visited[j] && !back && graph.adjacent(i,j) && connectivity[j]==connectivity[i]) { loop++; } if (!visited[j]) { back = false; DFS(graph, j); } } back = true; } template<typename T> void DFSTraverse(MGraph<T>& graph,int start) { int n = graph.getVexnum(); int i, j; for (i = start, j = 0; j < n; i = (i+1)%n, j++) { if (!visited[i]) { connect++; back = false; DFS(graph, i); } } } int main() { graph.initialize(mp); int n = graph.getVexnum(); int i; for (i = 0; i < n; i++) { visited[i] = false; connectivity[i] = 0; } DFSTraverse(graph, 0); if (loop == 0) { cout << "ͼ޻" << endl; } else { cout << "ͼл" << endl; } return 0; }
true
db403c037db62261fda4fa1d35745577bf8ced9d
C++
Gouravsingh21/DSA-Cpp
/arry2d/transpose.cpp
UTF-8
550
3.859375
4
[]
no_license
// create a 2 D array and make transpose of it. #include<iostream> #include<conio.h> using namespace std; void transpose(int arr[3][3]){ for(int i;i<3;i++){ for(int j;j<3;j++){ cout<<arr[j][i]; } cout<<endl; } } int main(){ cout<<"Enter the number of row and colounm"<<endl; // cin>>row>>col; int arr[3][3]={{1,2,3},{4,5,6},{7,8,9}}; cout<<"enter the elements of matrix"<<endl; for(int i;i<3;i++){ for(int j;j<3;j++){ // cin>>arr[i][j]; } } cout<<"the transpose of matrix :- "<<endl; transpose(arr); getch(); return 0; }
true
eea65999dd69b726e1cb350799e54032dd608db9
C++
JhoonGranados/SQL-2019-08
/desktop/final/Funciones/Ejercicio2/main.cpp
UTF-8
391
3.671875
4
[]
no_license
#include <iostream> using namespace std; /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int multiplicacion(int numero) { int mul = numero * 2; return mul; } int main(int argc, char** argv) { int n; cout<<"ingrese un numero: "; cin>>n; cout<<"el numero "<<n<<" * 2 es: "<<multiplicacion(n)<<endl; system("pause"); return 0; }
true
b8b2a6397f6c6d7285b991b2e0f49a113d98b614
C++
Archipel/cdWt
/CDWObject.h
UTF-8
3,749
2.8125
3
[]
no_license
/* * WObject.cpp * * Created on: 25-nov.-2014 * Author: thomas */ #include <Wt/WObject> namespace Wt { class CDWObject{ protected: WObject* wobject; public: CDWObject(WObject* wobject = 0): wobject(wobject) {} virtual ~CDWObject(){ delete wobject; } /* * Unique id's */ virtual unsigned rawUniqueId() const { return wobject->rawUniqueId(); } virtual const char* uniqueId() const { return wobject->uniqueId().c_str(); } /*! \brief Returns the (unique) identifier for this object * * For a %WWidget, this corresponds to the id of the DOM element * that represents the widget. This is not entirely unique, since a * \link WCompositeWidget composite widget\endlink shares the same * id as its implementation. * * By default, the id is auto-generated, unless a custom id is set * for a widget using WWidget::setId(). The auto-generated id is created * by concatenating objectName() with a unique number. * * \sa WWidget::jsRef() */ virtual const char* id() const { return wobject->id().c_str(); } /*! \brief Sets an object name. * * The object name can be used to easily identify a type of object * in the DOM, and does not need to be unique. It will usually * reflect the widget type or role. The object name is prepended to * the auto-generated object id(). * * The default object name is empty. * * \note Only letters ([A-Za-z]), digits ([0-9]), hyphens ("-"), * underscores ("_"), colons (":"), and periods (".") are allowed in * the id. * * \sa id() */ virtual void setObjectName(const char* name){ wobject->setObjectName(name); } /*! \brief Returns the object name. * * \sa setObjectName() */ virtual const char* objectName() const{ return wobject->objectName().c_str(); } /*! \brief Resets learned stateless slot implementations. * * Clears the stateless implementation for all slots declared to be * implemented with a stateless implementation. * * \sa resetLearnedSlot(), implementStateless() */ virtual void resetLearnedSlots(){ wobject->resetLearnedSlots(); } /*! \brief Adds a child object. * * Take responsibility of deleting the child object, together with this * object. * * \sa removeChild() */ virtual void addChild(WObject *child){ wobject->addChild(child); } /*! \brief Removes a child object. * * The child must have been previously added. * * \sa addChild() */ //virtual void removeChild(WObject *child) -> WObject implementation is OK /*! \brief Returns the children. */ virtual WObject** children(size_t& nAmount) const{ auto rv = wobject->children(); nAmount = rv.size(); return &rv[0]; } /*! \brief Returns the parent object. */ virtual WObject *parent() const { return wobject->parent(); } //virtual bool hasParent() const; //NOTPORTED //static void seedId(unsigned id); }; /*! \brief Create a %WObject with a given parent object. * * If the optional parent is specified, the parent object will * destroy all child objects. Set parent to \c 0 to create an object * with no parent. * * \sa addChild() */ inline CDWObject* construct(WObject* wobject = 0){ return new CDWObject(wobject); } /*! \brief Destructor. * * This automatically: * - deletes all child objects * - invalidates this object as sender or receiver in signals and slots */ inline void destruct(CDWObject* obj){ delete obj; } };
true
9565d2f361c5b979a847596f366f6bf018139612
C++
rajesh-06/lab10
/lab10_q3.cpp
UTF-8
1,612
4.65625
5
[]
no_license
/* Q3.Create a class for rectangle that stores data of length and breadth and has two functions : area() and perimeter(). Write a program that uses this class to create two rectangles (rectangle objects) of user inputted length and breadth. Compare the areas and perimeter of the those rectangles.*/ //include library #include <iostream> using namespace std; //Creating a class for rectangle class rectangle { public: double length; //lenth of the rectangle double breadth; //breadth of the rectangle }; int main(){ rectangle rectangle1; //Declare rectangle1 of type rectangle rectangle rectangle2; //Declare rectangle2 of type rectangle double area = 0.0; double perimeter = 0.0; //rectangle1 specification cout<<"Enter the length of rectangle1: "<<endl; cin>>rectangle1.length; cout<<"Enter the breadth of rectangle1: "<<endl; cin>>rectangle1.breadth; //rectangle2 specification cout<<"Enter the length of rectangle2: "<<endl; cin>>rectangle2.length; cout<<"Enter the breadth of rectangle2: "<<endl; cin>>rectangle2.breadth; //area of rectangle1 area = rectangle1.length * rectangle1.breadth; cout<< "Area of rectangle1 = "<<area<<endl; //area of rectangle2 area = rectangle2.length * rectangle2.breadth; cout << "Area of rectangle2 = " <<area << endl; //perimeter of rectangle1 perimeter = (rectangle1.length+rectangle1.breadth)*2; cout <<"Perimeter of rectangle1 = "<<perimeter <<endl; //perimeter of rectangle1 perimeter = (rectangle2.length+rectangle2.breadth)*2; cout <<"Perimeter of rectangle2 = "<<perimeter <<endl; //terminating the program return 0; }
true
93855ad7400ee9b598c55ce7c5cfdf950afe0fc3
C++
mwcorley79/MikeCorley
/lecture27/code/thread_demos/ThreadDemo1.cpp
UTF-8
1,774
3.125
3
[]
no_license
/////////////////////////////////////////////////////////////////////////////////// // Name : ThreadDemo1.cpp // Author : Jim Fawcett // Version : 1.0 // Description : Simple demo of threads and locks //============================================================================ // Compiler command: g++ -o DemoThreadDemo1 ThreadDemo1.cpp -lpthread // Run Command: ./DemoThreadDemo1 /////////////////////////////////////////////////////////////////////////////////// #include <iostream> #include <unistd.h> #include <pthread.h> using namespace std; // mutex is needed to keep parent and child output stream // from mingling pthread_mutex_t mutex; // todo: make global lock with static mutex //----< show process and thread ids with message >--------------------- void showIds(const char* s) { pid_t pid = getpid(); pthread_t tid = pthread_self(); cout << "\n " << s << " pid " << (unsigned int)pid << ", tid " << (unsigned int)tid; } //----< function defining child thread operation >--------------------- void* thrd_funct(void* arg) { pthread_mutex_lock(&mutex); showIds("child thread: "); cout << "\n child exit"; pthread_mutex_unlock(&mutex); return ((void*)0); } //----< thread demo entry >-------------------------------------------- int main() { pthread_mutex_init(&mutex, NULL); cout << "\n Thread Demo"; cout << "\n =============\n"; pthread_t ntid; int err = pthread_create(&ntid, NULL, thrd_funct, NULL); if(err != 0) { cout << "\n can't create child thread\n\n"; return 0; } sleep(1); pthread_mutex_lock(&mutex); showIds("main thread: "); pthread_mutex_unlock(&mutex); pthread_join(ntid, NULL); pthread_mutex_destroy(&mutex); cout << "\n parent exit\n\n"; return 0; }
true
5aabbb454688efc20321e837c697900875bdc291
C++
wzj423/OI
/luogu/聪明的质检员.cpp
UTF-8
1,887
2.8125
3
[]
no_license
/** 聪明的质检员 Luogu P1314 */ #include <iostream> #include <iomanip> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <cctype> #include <string> #include <algorithm> #include <queue> #include <stack> using namespace std; typedef long long LL; const int MAXN=200010; LL N,M,S; LL ww[MAXN],vv[MAXN]; LL sec[MAXN][2]; //预处理前缀和 LL preNum[MAXN];//前i个中满足条件的数量(包括第i个) LL preVV[MAXN];//前i个中满足条件的权值之和(包括第i个) //二分用变量 LL L=0; LL R=0; LL mid; LL ans=LL(INFINITY); // code LL ABS(LL a,LL b) { return (a>b?a-b:b-a); } void init() { scanf("%lld%lld%lld",&N,&M,&S); for(int i=1;i<=N;++i) { scanf("%lld%lld",&ww[i],&vv[i]); R=max(ww[i],R); } for(int i=1;i<=M;++i) { scanf("%lld%lld",&sec[i][0],&sec[i][1]); } } LL preCalc(int W) { LL ret=0; memset(preNum,0,sizeof(preNum)); memset(preVV,0,sizeof(preVV)); for(int i=1;i<=N;++i) { preNum[i]=preNum[i-1]+(ww[i]>=W); preVV[i]=preVV[i-1]+(ww[i]>=W?vv[i]:0); } for(int i=1;i<=M;++i) { int l=sec[i][0],r=sec[i][1]; ret+=(preNum[r]-preNum[l-1])*(preVV[r]-preVV[l-1]); } return ret; } void work() { LL t; while(L<=R) { mid=(L+R)/2; t=preCalc(mid); if(t>S)//t取大了,W太小了 { L=mid+1; if(t-S<ans) ans=t-S; } else if(t<S) { R=mid-1; if(S-t<ans) ans=S-t; } else { ans=0; break; } } } int main() { init(); work(); cout<<ans<<endl; //cout<<preCalc(4)-S<<endl; return 0; }
true
9556212eedffed5f7e261cad9d42a9d6bafa9329
C++
zeroslope/BZOJ-code
/BZOJ/2956 模积和.cpp
UTF-8
1,009
2.53125
3
[]
no_license
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; typedef long long LL; const LL MOD = 19940417; template<class T>inline void Read(T& x){ x=0; bool flag=0; char ch=getchar(); while(ch> '9' || ch< '0'){ if(ch=='-'){ flag=1; ch=getchar(); break; } ch=getchar();} while(ch>='0' && ch<='9'){ x=x*10+ch-48; ch=getchar(); } if(flag) x=-x; } LL N=0,M=0; inline LL Sum1(LL a,LL b){ return (LL)(b-a+1)*(a+b)/2%MOD; } inline LL Sum2(LL x){ return x*(x+1)%MOD * (2*x+1)%MOD * 3323403 % MOD; } inline LL Part1(LL n){ LL res=0; for(LL i=1,p=0;i<=n;i=p+1){ p=n/(n/i); res=( res+n*(p-i+1)%MOD-Sum1(i,p)*(n/i)%MOD )%MOD; } return (res+MOD)%MOD; } int main(){ Read(N); Read(M); LL Ans=Part1(N)*Part1(M)%MOD; if(N>M) swap(N,M); for(int i=1,p=0;i<=N;i=p+1){ p=min(N/(N/i),M/(M/i)); LL s1=N*M%MOD*(p-i+1)%MOD; LL s2=(N/i)*(M/i)%MOD*(Sum2(p)-Sum2(i-1)+MOD)%MOD; LL s3=(N/i*M+M/i*N)%MOD*Sum1(i,p)%MOD; Ans=(Ans-(s1+s2-s3)%MOD+MOD)%MOD; } printf("%lld\n",Ans); return 0; }
true
e326dd168bb4abbeb9cf79050ffa7f0b9e2f2a40
C++
EFanZh/Archived
/Visual Studio/Misc/LeetCode OJ/213. House Robber II/Solution.h
UTF-8
986
3.296875
3
[]
no_license
#pragma once class Solution { template <class T> static int robHelper(T first, T last) { if (first == last) { return 0; } else if (first + 1 == last) { return *first; } int prev2 = *(last - 1); int prev1 = max(*(last - 2), prev2); for (auto it = last - 3; it >= first; --it) { int current = max(*it + prev2, prev1); prev2 = prev1; prev1 = current; } return prev1; } public: int rob(const vector<int> &nums) { if (nums.empty()) { return 0; } else if (nums.size() < 4) { return *max_element(nums.cbegin(), nums.cend()); } int robFirst = nums.front() + robHelper(nums.cbegin() + 2, nums.cend() - 1); int notRobFirst = robHelper(nums.cbegin() + 1, nums.cend()); return max(robFirst, notRobFirst); } };
true
db4f73d6496be352503ae07a5d7387fe7b37f5f5
C++
sakanof/CGE
/Project/Components/SME/Include/Vector.h
UTF-8
4,602
3.078125
3
[]
no_license
#ifndef SME_Vector_H #define SME_Vector_H #include <vector> #include <list> #include <string> // Math Engine Includes #include "Definitions.h" namespace SME { namespace Vector { class SIMPLE_MATH_ENGINE_API Vec2 { public: union { struct { float x; float y; }; struct { float r; float g; }; struct { float s; float t; }; }; public: Vec2(); Vec2(float x, float y); Vec2(Vec3 v); Vec2(Vec4 v); public: Vec2 operator+(const Vec2& v); Vec2 operator-(const Vec2& v); Vec2 operator*(const float& scalar); Vec2 operator*(Vec2 v2); Vec2 operator*(Mat2 m2); Vec2 operator/(const float& scalar); Vec2& operator+=(const Vec2& v); Vec2& operator-=(const Vec2& v); Vec2& operator*=(const float& scalar); Vec2& operator*=(Vec2 v2); Vec2& operator*=(Mat2 m2); Vec2& operator/=(const float& scalar); Vec2& operator=(const Vec2& v); float& operator[](size_t i); float const& operator[](size_t i) const; bool operator!=(const Vec2& m2) const; bool operator==(const Vec2& m2) const; Vec2 Normalize() const; float Length() const; FloatVector ToVector(); std::string ToString() const; }; class SIMPLE_MATH_ENGINE_API Vec3 { public: union { struct { float x; float y; float z; }; struct { float r; float g; float b; }; struct { float s; float t; float p; }; }; public: Vec3(); Vec3(float x, float y, float z); Vec3(Vec2 v, float z = 0.0f); Vec3(Vec4 v); private: Vec3& operator=(const Vec2& v); Vec3& operator=(const Vec4& v); public: Vec3 operator+(const Vec3& v); Vec3 operator-(const Vec3& v); Vec3 operator*(const float& scalar); Vec3 operator*(const Vec3& v3); Vec3 operator*(const Mat3& m3); Vec3 operator*(const Mat4& m4); Vec3 operator/(const float& scalar); Vec3& operator+=(const Vec3& v); Vec3& operator-=(const Vec3& v); Vec3& operator*=(const float& scalar); Vec3& operator*=(const Vec3& v3); Vec3& operator*=(const Mat3& m3); Vec3& operator*=(const Mat4& m4); Vec3& operator/=(const float& scalar); Vec3& operator=(const Vec3& v); float& operator[](size_t i); float const& operator[](size_t i) const; bool operator!=(const Vec3& m3) const; bool operator==(const Vec3& m3) const; // Return a vector ponting Forward Vec3 Forward() const; // Return a vector ponting Backward Vec3 Backward() const; // Return a vector ponting Left Vec3 Left() const; // Return a vector ponting Right Vec3 Right() const; // Return a vector ponting Up Vec3 Up() const; // Return a vector ponting Down Vec3 Down() const; // Return the component that have the greatest value float Max() const; // Return a vector composed by the greatest values of the two vectors Vec3 Max(const Vec3& r) const; float DistanceFrom(const Vec3& v) const; float Dot(Vec3 v3) const; float Length() const; Vec3 Cross(const Vec3& r) const; Vec3 Reflect(Vec3 normal) const; Vec3 Normalize() const; Vec3 Rotate(const Quaternion& rotation); FloatVector ToVector(); std::string ToString() const; }; class SIMPLE_MATH_ENGINE_API Vec4 { public: union { struct { float x; float y; float z; float w; }; struct { float r; float g; float b; float a; }; struct { float s; float t; float p; float q; }; }; public: Vec4(); Vec4(float x, float y, float z, float w); Vec4(Vec2 v, float z = 0.0f, float w = 0.0f); Vec4(Vec3 v, float w = 0.0f); public: Vec4 operator+(const Vec4& v); Vec4 operator-(const Vec4& v); Vec4 operator*(const float& scalar); Vec4 operator*(Vec4 v4); Vec4 operator*(Mat4 m4); Vec4 operator/(const float& scalar); Vec4& operator+=(const Vec4& v); Vec4& operator-=(const Vec4& v); Vec4& operator*=(const float& scalar); Vec4& operator*=(Vec4 v4); Vec4& operator*=(Mat4 m4); Vec4& operator/=(const float& scalar); Vec4& operator=(const Vec4& v); float& operator[](size_t i); float const& operator[](size_t i) const; bool operator!=(const Vec4& m4) const; bool operator==(const Vec4& m4) const; Vec4 Normalize() const; float Length() const; FloatVector ToVector(); std::string ToString() const; }; inline Vector::Vec3 CalculateNormal(Vec3 v1, Vec3 v2, Vec3 v3) { return ((v2 - v1) * (v3 - v1)) / ((v2 - v1) * (v3 - v1)).Length(); } }; }; #endif // SME_Vector_H
true
f6109007a6c2ebca71e4c353b52da7037547ce85
C++
greybinhoe/PA1415-Programvarudesign
/Project1/Project1/Map.h
UTF-8
469
2.828125
3
[]
no_license
#ifndef MAP_H #define MAP_H #include "Point.h" #include "Tile.h" #include "Item.h" #include <string> class Map { private: Tile tileMap[120][25]; int sizeX = 120; int sizeY = 25; public: Map(); ~Map(); Item& pickUpItem(int y, int x); bool checkPos(int y, int x); void rowToCharArray(char * charArray, int row); int getRows() const; int getCols() const; std::string getItemDesc(int y, int x) const; std::string getItemName(int y, int x) const; }; #endif
true
994f244d601a0c1a439796d1ab359a475b7b1285
C++
scen/libembryo
/logger.h
UTF-8
1,124
2.546875
3
[ "MIT" ]
permissive
// // libembryo // // Copyright Stanley Cen 2013 // Released under the MIT License // #ifndef libembryo_log_h #define libembryo_log_h #include <boost/format.hpp> #include <iostream> #include <fstream> #include <string> using boost::format; namespace embryo { class logger { public: enum logflags { log_stdout = 1, log_file = 2, force_flush= 4, file_color = 8 }; static logger &get(); void init(int flags, const std::string &fn = ""); void error(const std::string &text); void error(const format &fmt); void warn(const std::string &text); void warn(const format &fmt); void info(const std::string &text); void info(const format &fmt); void verb(const std::string &text); void verb(const format &fmt); private: int flags; std::ofstream outFile; logger() {}; ~logger() {}; void write(const std::string &text, const std::string &col, const std::string &title); }; logger &log(); } #endif
true
86354f1a8c4e5e6f63ed5ef12e441428a2bf637c
C++
CryptoLover705/Game_Physics
/Vector3.hpp
UTF-8
3,095
3.53125
4
[]
no_license
#include <initializer_list> #include <cmath> class Vector3 { public: double v[3]; public: Vector3(); Vector3(double x, double y, double z); double &operator[](int index); double operator[](int index) const; Vector3 operator*(double scale) const; Vector3 operator/(double scale) const; Vector3 operator+(const Vector3 &other) const; Vector3 operator-(const Vector3 &other) const; Vector3 operator-() const; const Vector3 &operator*=(double scale); const Vector3 &operator/=(double scale); const Vector3 &operator+=(const Vector3 &other); const Vector3 &operator-=(const Vector3 &other); double Magnitude() const; Vector3 Normalize() const; double Dot(const Vector3 &other) const; Vector3 Cross(const Vector3 &other) const; Vector3 Project(const Vector3 &other) const; }; Vector3::Vector3() { v[0] = 0; v[1] = 0; v[2] = 0; } Vector3::Vector3(double x, double y, double z) { v[0] = x; v[1] = y; v[2] = z; } double &Vector3::operator[](int index) { return v[index]; } double Vector3::operator[](int index) const { return v[index]; } Vector3 Vector3::operator*(double scale) const { return Vector3(v[0] * scale, v[1] * scale, v[2] * scale); } Vector3 Vector3::operator/(double scale) const { return Vector3(v[0] / scale, v[1] / scale, v[2] / scale); } Vector3 Vector3::operator+(const Vector3 &other) const{ return Vector3(v[0] + other.v[0], v[1] + other.v[1], v[2] + other.v[2]); } Vector3 Vector3::operator-(const Vector3 &other) const { return Vector3(v[0] - other.v[0], v[1] - other.v[1], v[2] - other.v[2]); } Vector3 Vector3::operator-() const { return Vector3(-v[0], -v[1], -v[2]); } const Vector3 &Vector3::operator*=(double scale) { v[0] *= scale; v[1] *= scale; v[2] *= scale; return *this; } const Vector3 &Vector3::operator/=(double scale) { v[0] /= scale; v[1] /= scale; v[2] /= scale; return *this; } const Vector3 &Vector3::operator+=(const Vector3 &other) { v[0] += other.v[0]; v[1] += other.v[1]; v[2] += other.v[2]; return *this; } const Vector3 &Vector3::operator-=(const Vector3 &other) { v[0] -= other.v[0]; v[1] -= other.v[1]; v[2] -= other.v[2]; return *this; } double Vector3::Magnitude() const { return sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]); } Vector3 Vector3::Normalize() const { double m = sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]); return Vector3(v[0] / m, v[1] / m, v[2] / m); } double Vector3::Dot(const Vector3 &other) const { return v[0] * other.v[0] + v[1] * other.v[1] + v[2] * other.v[2]; } Vector3 Vector3::Cross(const Vector3 &other) const { return Vector3(v[1] * other.v[2] - v[2] * other.v[1], v[2] * other.v[0] - v[0] * other.v[2], v[0] * other.v[1] - v[1] * other.v[0]); } Vector3 Vector3::Project(const Vector3 &other) const { // a.n(b) n(b) = |a|cos(theta) n(b); return other.Normalize() * Dot(other.Normalize()); }
true
42a1877d247efc9d01696be9c9479172a963bac8
C++
jizecn/my_humanoid_robot
/src/actionDecision/include/EventActionPair.h
UTF-8
1,197
3.171875
3
[]
no_license
#ifndef __EVENT_ACTION_PAIR_H__ #define __EVENT_ACTION_PAIR_H__ #include <vector> #include "SinglePartEvent.h" #include "ActionCommand.h" class EventActionPair { public: EventActionPair() { } ~EventActionPair() { } void setEventKey(SinglePartEvent &key) { this->key = key; } bool ifSameKey(SinglePartEvent &nkey) { return key.compareWith(nkey); } SinglePartEvent getEventKey() { return this->key; } bool insertActionCommand(ActionCommand &cmd) { if(checkExisting(cmd)) { // duplicated std::cout << "Dupllicated item found. Not inserted" << std::endl; return false; } else { cmds.push_back(cmd); return true; } } bool decideActionCommand(ActionCommand &cmd) { // only the simplest mode here if(cmds.size() > 0) { cmd = cmds[0]; return true; } return false; } private: SinglePartEvent key; std::vector<ActionCommand> cmds; bool checkExisting(ActionCommand& ncmd) { for(int i = 0; i < cmds.size(); i++) { if(ncmd.compareWith(cmds[i])) { return true; } } return false; } }; #endif //__EVENT_ACTION_PAIR_H__
true
1a885a258a56fe3b098f2e0dd3ee025d122a9481
C++
RicardoSoz/Estructuras
/NodoFila.cpp
UTF-8
547
2.640625
3
[]
no_license
#include "NodoFila.h" #include <iostream> using namespace std; NodoFila::NodoFila() { dato = 0; sig = NULL; } NodoFila::NodoFila(int _dato) { dato = _dato; sig = NULL; } NodoFila::NodoFila(int _dato, char _caracter) { dato = _dato; caracter = _caracter; sig = NULL; } int NodoFila::getDato() { return dato; } void NodoFila::setDato(int _dato) { dato = _dato; } NodoFila* NodoFila::getSig() { return sig; } void NodoFila::setSig(NodoFila* _sig) { sig = _sig; } NodoFila::~NodoFila() { }
true
6ec5fe11c64d8eee967ac4b16d1c2221fb1f00e9
C++
Thecarisma/serenity
/AK/Tests/TestHashMap.cpp
UTF-8
2,649
3.359375
3
[ "BSD-2-Clause" ]
permissive
#include <AK/TestSuite.h> #include <AK/String.h> #include <AK/HashMap.h> TEST_CASE(construct) { typedef HashMap<int, int> IntIntMap; EXPECT(IntIntMap().is_empty()); EXPECT_EQ(IntIntMap().size(), 0); } TEST_CASE(populate) { HashMap<int, String> number_to_string; number_to_string.set(1, "One"); number_to_string.set(2, "Two"); number_to_string.set(3, "Three"); EXPECT_EQ(number_to_string.is_empty(), false); EXPECT_EQ(number_to_string.size(), 3); } TEST_CASE(range_loop) { HashMap<int, String> number_to_string; number_to_string.set(1, "One"); number_to_string.set(2, "Two"); number_to_string.set(3, "Three"); int loop_counter = 0; for (auto& it : number_to_string) { EXPECT_EQ(it.value.is_null(), false); ++loop_counter; } EXPECT_EQ(loop_counter, 3); } TEST_CASE(map_remove) { HashMap<int, String> number_to_string; number_to_string.set(1, "One"); number_to_string.set(2, "Two"); number_to_string.set(3, "Three"); number_to_string.remove(1); EXPECT_EQ(number_to_string.size(), 2); EXPECT(number_to_string.find(1) == number_to_string.end()); number_to_string.remove(3); EXPECT_EQ(number_to_string.size(), 1); EXPECT(number_to_string.find(3) == number_to_string.end()); EXPECT(number_to_string.find(2) != number_to_string.end()); } TEST_CASE(case_insensitive) { HashMap<String, int, CaseInsensitiveStringTraits> casemap; EXPECT_EQ(String("nickserv").to_lowercase(), String("NickServ").to_lowercase()); casemap.set("nickserv", 3); casemap.set("NickServ", 3); EXPECT_EQ(casemap.size(), 1); } TEST_CASE(assert_on_iteration_during_clear) { struct Object { ~Object() { m_map->begin(); } HashMap<int, Object>* m_map; }; HashMap<int, Object> map; map.set(0, { &map }); map.clear(); } TEST_CASE(hashmap_of_nonnullownptr_get) { struct Object { Object(const String& s) : string(s) {} String string; }; HashMap<int, NonnullOwnPtr<Object>> objects; objects.set(1, make<Object>("One")); objects.set(2, make<Object>("Two")); objects.set(3, make<Object>("Three")); { auto x = objects.get(2); EXPECT_EQ(x.has_value(), true); EXPECT_EQ(x.value()->string, "Two"); } { // Do it again to make sure that peeking into the map above didn't // remove the value from the map. auto x = objects.get(2); EXPECT_EQ(x.has_value(), true); EXPECT_EQ(x.value()->string, "Two"); } EXPECT_EQ(objects.size(), 3); } TEST_MAIN(HashMap)
true
1f2f68ff4f55c7a9dca16affcf6459e48dbc0479
C++
sharkprince/tank-game
/src/models/block.cpp
UTF-8
2,306
3.140625
3
[ "MIT" ]
permissive
#include "block.h" #include "../const/rotation.h" Block::Block(sf::Texture *texture, sf::Vector2f position, bool isBreakable, bool isSoft, bool isDeep) { Sprite = new sf::Sprite(); Sprite->setTexture(*texture); Sprite->setPosition(position.x, position.y); Sprite->setTextureRect(sf::IntRect(0, 0, BLOCK_WIDTH_PIXELS, BLOCK_HEIGHT_PIXELS)); Sprite->setRotation(0); this->isSoft = isSoft; this->isBreakable = isBreakable; this->isDeep = isDeep; } void Block::Update(Game *g) { g->DrawSprite(this->Sprite); } bool Block::Hit(float rotation) { if (!isBreakable) return false; sf::IntRect textureRect = Sprite->getTextureRect(); sf::Vector2f origin = Sprite->getOrigin(); if (rotation == LEFT_ROTATION) { Sprite->setOrigin(origin.x - FLOAT_BLOCK_HIT_DAMAGE, origin.y); Sprite->setTextureRect( sf::IntRect( textureRect.left + FLOAT_BLOCK_HIT_DAMAGE, textureRect.top, textureRect.width - FLOAT_BLOCK_HIT_DAMAGE, textureRect.height )); } if (rotation == UP_ROTATION) { Sprite->setOrigin(origin.x, origin.y - FLOAT_BLOCK_HIT_DAMAGE); Sprite->setTextureRect( sf::IntRect( textureRect.left, textureRect.top + FLOAT_BLOCK_HIT_DAMAGE, textureRect.width, textureRect.height - FLOAT_BLOCK_HIT_DAMAGE )); } if (rotation == RIGHT_ROTATION) { Sprite->setTextureRect( sf::IntRect( textureRect.left, textureRect.top, textureRect.width - FLOAT_BLOCK_HIT_DAMAGE, textureRect.height )); } if (rotation == DOWN_ROTATION) { Sprite->setTextureRect( sf::IntRect( textureRect.left, textureRect.top, textureRect.width, textureRect.height - FLOAT_BLOCK_HIT_DAMAGE )); } return false; } bool Block::GetIsSoft() { return isSoft; } bool Block::GetIsDeep() { return isDeep; }
true
037100e034254179fb86fe93035371a100731290
C++
sheirkahn/RCAS
/RCAS/RCASSession.cpp
UTF-8
2,848
2.625
3
[]
no_license
#include "RCASSession.h" #include <QFile> #include <QJsonArray> RCASSession::RCASSession () { mModified = false; } void RCASSession::writeToJson (QJsonObject& json) { json["session_id"] = mID; json["name"] = mAssessorName; json["date"] = mSessionDate; QJsonArray candidateArray; foreach (RCASCandidate cand, mCandidateList) { QJsonObject candJson; cand.writeToJson(candJson); candidateArray.append(candJson); } json["candidates"] = candidateArray; mModified = false; } void RCASSession::readFromJson (const QJsonObject &json) { if (json.contains("session_id") && json["session_id"].isDouble()) mID = json["session_id"].toInt(); if (json.contains("name") && json["name"].isString()) mAssessorName = json["name"].toString(); if (json.contains("date") && json["date"].isString()) mSessionDate = json["date"].toString(); if (json.contains("candidates") && json["candidates"].isArray()) { QJsonArray candJsonArray = json["candidates"].toArray(); mCandidateList.clear(); mCandidateList.reserve (candJsonArray.size()); for (int iCandidate = 0; iCandidate < candJsonArray.size(); ++iCandidate) { QJsonObject candJson = candJsonArray[iCandidate].toObject(); RCASCandidate cand; cand.readFromJson (candJson); mCandidateList.append(cand); } } } bool RCASSession::readCandidatesFromCSVFile (const QString &fileName) { QFile csvFile(fileName); if (!csvFile.open (QIODevice::ReadOnly)) { return false; } QByteArray header = csvFile.readLine (); if (header.isEmpty()) { return false; } QList <QByteArray> headerWords = header.split(','); int numHeaderWords = headerWords.size(); if (numHeaderWords != 11) { return false; } QList <QByteArray> lines; while (!csvFile.atEnd ()) { lines.append(csvFile.readLine ()); } int numCandidates = lines.size(); if (!numCandidates) { return false; } for (int i = 0; i < numCandidates; i++) { QList <QByteArray> candidateDetails = lines[i].split(','); RCASCandidate c; c.setName (QString (candidateDetails[1])); c.setUID (QString (candidateDetails[2])); c.setPhone (QString (candidateDetails[3])); c.setEmail (QString (candidateDetails[4])); c.setProcess (QString (candidateDetails[5])); c.setRecruiter (QString (candidateDetails[6])); c.setTL (QString (candidateDetails[7])); c.setCollege (QString (candidateDetails[8])); c.setSchool (QString (candidateDetails[9])); c.setLocation (QString (candidateDetails[10])); c.setModified (false); } return true; }
true
f6a47f26ed76e1a131c25a6b3a44228d2b7fa7c2
C++
JMikeJacob/roots-project-1
/main.cpp
UTF-8
2,927
3.265625
3
[]
no_license
#include <iostream> #include <fstream> #include <string> #include "polynomial.h" #include "rootfinder.h" #include "misc_functions.h" using namespace std; #define MAX_ORDER 20 using namespace std; bool g_fileExists = true;//global var for existence of text file void getpoly(string fileName, polynomial& Poly) { ifstream polyFile; int order = 0; polyFile.open(fileName.c_str()); if(polyFile.fail()) {//tells the program to exit if file not found cout << "Error opening file!"; g_fileExists = false; return; } cout << endl; polyFile >> order;//inserts first number (nth order) to int order double* polyArray = new double[order + 1];//stores coefs tmp. for(int i = 0; i <= order; i++) {//inserts consecutive coefs into the array until the nth coef polyFile >> polyArray[i]; } Poly.createPoly(order, polyArray);//creates polynomial to be used Poly.printPoly();//prints out polynomial delete [] polyArray;//deallocates memory of dynamic array polyFile.close(); } int main(int argc, char** argv) { polynomial Poly; rootfinder Groot; string fileName, save; //file reader: user input if (argc == 2) //case 1: file name declared along cmd line { fileName=argv[1]; } else if(argc == 1) //case 2: file name not initially given { cout<<"Filename:"; cin >> fileName; cin.clear(); cin.ignore(256, '\n'); } else //case 3: more than 3 inputs along cmd line { cout<< "Invalid input. Program name with or w/o file only."; return 0; } if(fileName.find(".txt") == string::npos) //adds file extension { fileName = fileName + ".txt"; } getpoly(fileName, Poly); //function for extracting from text file if(g_fileExists == false) {//ends program if file not found return 0; } Poly.normalizePoly();//normalizes polynomial s.t. x^n coef is 1 Groot.setup_finder(Poly.order, Poly.coef);//sets up dynamic arrays cout << endl; int n = Poly.order; while(n > 2) {//bairstow algorithm will loop as long as //a quadratic factor can be found Groot.bairstow(n); n -= 2; } Groot.extractRoots();//extracts roots from quadratic factors Groot.printRoots(); Groot.horner(Poly.coef, Poly.order);//evaluates roots in polynomial cout << endl; //asks if user wants to save results to a text file char ans = 0; while(1) { cout << "Do you want to save the results to a text file? (Y/N) "; cin.get(ans); cin.clear(); cin.ignore(256, '\n'); if(ans == 'Y' || ans == 'y') { cout << "Name of save file: "; cin >> save; cin.clear(); if(save.find(".txt") == string::npos) //adds file extension { save = save + ".txt"; } saveToFile(save,Poly,Groot); break; } else if(ans == 'N' || ans == 'n') { break; } } //deallocates memory of dynamic arrays Poly.deletePoly(); Groot.deleteFinder(); return 0; }
true
222fc49c7293498e19f649512d0fc645a70fef0b
C++
metaphysis/Code
/UVa Online Judge/volume012/1234 RACING/program.cpp
UTF-8
1,575
2.734375
3
[]
no_license
// RACING // UVa ID: 1234 // Verdict: Accepted // Submission Date: 2018-02-12 // UVa Run Time: 0.060s // // 版权所有(C)2018,邱秋。metaphysis # yeah dot net #include <bits/stdc++.h> using namespace std; const int MAXV = 10010, MAXE = 100010, INF = 0x7fffffff; struct edge { int from, to, cost; bool operator<(const edge& x) const { return cost > x.cost; } }; edge edges[MAXE]; int parent[MAXV], ranks[MAXV], n, m; void makeSet() { for (int i = 0; i <= n; i++) parent[i] = i, ranks[i] = 0; } int findSet(int x) { return (parent[x] == x ? x : parent[x] = findSet(parent[x])); } bool unionSet(int x, int y) { x = findSet(x), y = findSet(y); if (x != y) { if (ranks[x] > ranks[y]) parent[y] = x; else { parent[x] = y; if (ranks[x] == ranks[y]) ranks[y]++; } return true; } return false; } void kruskal() { int maxWeight = 0, totalWeight = 0; makeSet(); sort(edges, edges + m); for (int i = 0; i < m; i++) { totalWeight += edges[i].cost; if (unionSet(edges[i].from, edges[i].to)) maxWeight += edges[i].cost; } cout << totalWeight - maxWeight << '\n'; } int main(int argc, char *argv[]) { cin.tie(0), cout.tie(0), ios::sync_with_stdio(false); int cases; cin >> cases; for (int c = 1; c <= cases; c++) { cin >> n >> m; for (int i = 0; i < m; i++) { cin >> edges[i].from >> edges[i].to >> edges[i].cost; } kruskal(); } return 0; }
true
8c3dfa2f3a11586d6d403e6607c739283610e3a0
C++
nikku599/competitiveProgramming
/cpp/Counting even or odd.cpp
UTF-8
3,392
3.5
4
[]
no_license
#include<bits/stdc++.h> using namespace std; struct node { int num_of_odd , num_of_even; }; void buildTree (int* arr, node* tree, int start, int end, int tree_node) { if (start == end) { if (arr[start] % 2 == 0) { tree[tree_node].num_of_even = 1; tree[tree_node].num_of_odd = 0; } else { tree[tree_node].num_of_even = 0; tree[tree_node].num_of_odd = 1; } return; } int mid = (start+end)/2; buildTree(arr,tree,start,mid,2*tree_node); buildTree(arr,tree,mid+1,end,2*tree_node+1); node left = tree[2*tree_node]; node right = tree[2*tree_node+1]; tree[tree_node].num_of_odd = left.num_of_odd + right.num_of_odd; tree[tree_node].num_of_even = left.num_of_even + right.num_of_even; return; } node util (node x, node y) { node temp; temp.num_of_odd = x.num_of_odd + y.num_of_odd; temp.num_of_even = x.num_of_even + y.num_of_even; return temp; } node query(node* tree, int start, int end, int tree_node, int left, int right) { // Completely outside the given range node temp; temp.num_of_odd = 0; temp.num_of_even = 0; if (end < left || start > right) return temp; // completely inside the range if (left <= start && right >= end) return tree[tree_node]; // partially outside and partialy inside the range int mid = (start+end)/2; node ans1 = query(tree,start,mid,tree_node*2,left,right); node ans2 = query(tree,mid+1,end,2*tree_node+1,left,right); return util (ans1, ans2); } void update (int* arr, node* tree, int start, int end, int tree_node, int index, int value) { if (start == end) { if (value % 2 == 0) { tree[tree_node].num_of_even = 1; tree[tree_node].num_of_odd = 0; } else { tree[tree_node].num_of_odd = 1; tree[tree_node].num_of_even = 0; } return; } int mid = (start + end)/2; if (index <= mid); update(arr, tree, start, mid, 2*tree_node, index, value); else update(arr, tree,mid+1,end,2*tree_node+1,index, value); node left = tree[2*tree_node]; node right = tree[2*tree_node+1]; tree[tree_node].num_of_even = left.num_of_even + right.num_of_even; tree[tree_node].num_of_odd = left.num_of_odd + right.num_of_odd; return; } int main(){ int n; cin >> n; int arr[n]; for(int i=0;i<n;i++) cin >> arr[i]; node* tree = new node [4*n]; buildTree(arr, tree, 0, n-1, 1); int q; cin >> q; while(q--) { int action; cin >> action; if (action == 1) { // find even numbers int left, right; cin >> left >> right; node ans= query (tree, 0, n-1, 1, left-1, right-1); cout << ans.num_of_even << endl; } else if (action == 2) { //find odd numbers int left, right; cin >> left >> right; node ans= query (tree, 0, n-1, 1, left-1, right-1); cout << ans.num_of_odd << endl; } else if (action == 0) { // update function int index, value; cin << index << value; update(arr,tree,0,n-1,1,index,value); } } }
true
3ea7e8be883fb86d85875e0bfcb0afd8e7d15364
C++
bystc/SomeExercisesAboutC
/用嵌套循环写个小程序.cpp
UTF-8
381
2.703125
3
[]
no_license
#include<stdio.h> int main() // char ch='$'; // int i,j; // for(i=0;i<4;i++){ // // for(j=0;j<8;j++) // printf("%c",ch); // printf("\n"); // return 0; { char a; int i; printf("Please input a string end by #:"); for(i = 1; (a = getchar()) != '#'; i++) { printf("%c--%d\t",a,a); if(i%8 == 0) printf("\n"); } printf("\n"); return(0); }
true
8c5ea0ba24f107e824d71c6e165daf80faeee038
C++
fevralkolesnikova/studio
/storage.cpp
UTF-8
1,793
2.671875
3
[]
no_license
#include "storage.h" #include <QDebug> Storage::Storage(QWidget *parent) : QDialog(parent) { ui.setupUi(this); connect(ui.pushButton, SIGNAL(clicked()), this, SLOT(changeMaterials())); connect(ui.pushButton_2, SIGNAL(clicked()), this, SLOT(deleteMaterial())); connect(ui.pushButton_3, SIGNAL(clicked()), this, SLOT(comeback())); } void Storage::setup(int modeVal) { mode = modeVal; if (mode == -1) { ui.pushButton_2->hide(); ui.lineEdit->setText(""); ui.lineEdit_2->setText(""); ui.lineEdit_3->setText(""); ui.lineEdit_4->setText(""); } else { QSqlQuery query; query.prepare(R"( SELECT Material, Color, Price, Amount FROM Fabrics WHERE ID=?)"); query.addBindValue(modeVal); query.exec(); query.first(); ui.lineEdit->setText(query.value(0).toString()); ui.lineEdit_2->setText(query.value(1).toString()); ui.lineEdit_3->setText(query.value(3).toString()); ui.lineEdit_4->setText(query.value(2).toString()); } } void Storage::changeMaterials() { QSqlQuery query; if (mode == -1) { query.prepare(R"(INSERT INTO Fabrics(Material, Color, Price, Amount) values (:material, :color, :price, :amount))"); } else { query.prepare(R"( UPDATE Fabrics SET Material = :material, Color = :color, Price = :price, Amount = :amount WHERE ID = :id )"); query.bindValue(":id", mode); } query.bindValue(":material", ui.lineEdit->text()); query.bindValue(":color", ui.lineEdit_2->text()); query.bindValue(":price", ui.lineEdit_4->text()); query.bindValue(":amount", ui.lineEdit_3->text()); query.exec(); comeback(); } void Storage::comeback() { emit backSignal(); this->close(); } void Storage::deleteMaterial() { QSqlQuery query; query.prepare(R"(DELETE FROM FABRICS WHERE ID=:id)"); query.bindValue(":id", mode); query.exec(); comeback(); }
true
ad9cbba8ebe14235b949e8e82e1650625bf8161d
C++
Plypy/Lifestyle
/Usaoj/fence8.cpp
GB18030
2,428
2.734375
3
[]
no_license
/* ID : jake1994 PROG : fence8 LANG : C++ */ // ......... // // #include <iostream> #include <cstdlib> #include <fstream> #include <cstring> using namespace std; ifstream fin("fence8.in"); ofstream fout("fence8.out"); const int MAXN = 51; const int MAXR = 1024; int size[MAXN]; int backup[MAXN]; int len[MAXR]; int sum[MAXR]; int tot; int spare; int n, r; int ans; int mid; int cmp(const void *a, const void *b) { return (*(int *)a-*(int *)b); } bool dfs(int dep, int pos) { if (dep <= 0)//ɹ return true; if (spare>tot-sum[mid]) return false; bool flag = false; for (int i = pos; i <= n; i++) if (backup[i] >= len[dep]) { backup[i] -= len[dep]; if (backup[i] < len[1]) spare += backup[i]; if (len[dep] == len[dep-1]) { if (dfs(dep-1,i)) return true; } else if (dfs(dep-1,1)) return true; if (backup[i] < len[1]) spare -= backup[i]; backup[i] += len[dep]; } return false; } int main() { fin >> n; for (int i = 1; i <= n; i++) fin >> size[i]; fin >> r; for (int i = 1; i <= r; i++) fin >> len[i]; qsort(len+1,r,sizeof(int),cmp);// ʽ qsort(size+1,n,sizeof(int),cmp);// ʽ //ǵÿľĵļֵһģö̵ľıȻȳľĻ for (int i = 1; i <= n; i++) tot += size[i]; for (int i = 1; i <= r; i++) sum[i] = sum[i-1]+len[i]; while (sum[r] > tot)//Լ֦ //ľܳ볬ľĵܳпܽȡһľ r--; int bg = 0, ed = r; while (bg <= ed)//ּ { spare = 0; mid = (bg+ed)>>1; memcpy(backup, size, sizeof(size)); if (dfs(mid,1))//Լ֦ //ľľij޷ȡľ壬Ҳ޷Ҫ bg = mid+1; else ed = mid-1; } fout << ed << endl; return 0; }
true
eb136e62fc6b9c28fef491257e5f71144921f92c
C++
cunkoutangtou/Leetcode-Cpp
/二叉树/交换节点.cpp
UTF-8
2,096
3.53125
4
[]
no_license
给定数组b为n*2的数组,如果其中的每对元素不存在父子或者祖孙关系,则交换。 class Solution { public: unordered_map<int, TreeNode*> mp; unordered_map<int, int> fa; bool judge(TreeNode* a, int val){ if(!a) return false; if(a -> val == val) return true; return judge(a -> left, val) || judge(a -> right, val); } bool isFather(TreeNode* a, TreeNode* b){ return judge(a, b -> val) || judge(b, a -> val); } void swap(vector<int>& v){ if(isFather(mp[v[0]], mp[v[1]])) return; TreeNode* a = mp[fa[v[0]]]; TreeNode* ason = mp[v[0]]; TreeNode* b = mp[fa[v[1]]]; TreeNode* bson = mp[v[1]]; //下面一大段其实就是交换a,b的孩子,只不过要讨论是左子树还是右子树 if(a -> left == ason && b -> left == bson){ a -> left = bson; fa[bson -> val] = a -> val; b -> left = ason; fa[ason -> val] = b -> val; } else if(a -> left == ason && b -> right == bson) { a->left = bson; fa[bson->val] = a->val; b->right = ason; fa[ason->val] = b->val; } else if(a -> right == ason && b -> left == bson) { a->right = bson; fa[bson->val] = a->val; b->left = ason; fa[ason->val] = b->val; } else if(a -> right == ason && b -> right == bson){ a -> right = bson; fa[bson -> val] = a -> val; b -> right = ason; fa[ason -> val] = b -> val; } } void dfs(TreeNode* root, int f){ if(!root) return; mp[root -> val] = root;//记录val和节点的映射关系 fa[root -> val] = f; //记录节点父亲 dfs(root -> left, root -> val); dfs(root -> right, root -> val); } TreeNode* solve(TreeNode* root, vector<vector<int> >& b) { // write code here dfs(root, -1); for(auto& v : b){ swap(v); } return root; } };
true
5a4522293cb4eff7a2e3b4afd8fb0ec6299f6939
C++
sauravgupta2800/MyCodingPractice
/miscellaneous/jan1-2.cpp
UTF-8
945
2.8125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; typedef long long ll; int main() { ll t; cin>>t; while(t--) { ll bob=0,alice=0,common=0,i=0,n,b,a,item; vector<ll> v; cin>>n>>b>>a; for(i=0;i<n;i++) { cin>>item; v.push_back(item); if(v[i]%a==0 && v[i]%b==0) common++; else if(v[i]%b==0) bob++; else if(v[i]%a==0) alice++; } if(common>0)//ODDD { //alice ki turn hai!!!! if(bob>=alice)//0 , 1 { cout<<"BOB\n"; } else { cout<<"ALICE\n"; } } else//EVEN COMMON { //bob ki turn hai.!!!!! if(bob>alice) cout<<"BOB\n"; else cout<<"ALICE\n"; } } }
true
27b32a9608d5f0b95828789b413f139e2625941e
C++
Aradhana-Singh/DSA_CPP
/TwoPointers/2SUM_Closest_16.cpp
UTF-8
1,064
3.59375
4
[]
no_license
/* Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.*/ class Solution { public: int threeSumClosest(vector<int>& nums, int target) { int n = nums.size(); int sum = 0, dif = INT_MAX; if(n<3) return 5; sort( nums.begin() , nums.end() ); for(int i = 0 ; i < n-2 ; i++){ int low = i+1 ,high = n-1; while(low < high){ if(dif > abs(nums[i]+nums[low]+nums[high]-target)){ dif = abs(nums[i]+nums[low]+nums[high]-target); sum = nums[i]+nums[low]+nums[high]; if(nums[i]+nums[low]+nums[high] < target) low++; else high--; } else if(nums[i]+nums[low]+nums[high] < target){ low++; } else high--; } } return sum; } };
true
f9d921e4568a595f59efbb6364382e7ec2171e0c
C++
Mart95777/CppLinux
/general/copycontrol/unable_copyconstr.cpp
UTF-8
502
3.15625
3
[]
no_license
// unable to generate default #include <iostream> class Base { public: int n; Base(int n =1) : n(n) {} Base(const Base& b) : n(b.n) {} }; class Deriv : public Base { }; class Deriv2 : public Deriv { public: Deriv2() : Deriv() {} private: Deriv2(const Deriv2&); }; int main() { Base b1(3); Base b2(b1); Deriv d; Base b3 = d; volatile Base vb(7); // error Base b4 = vb; Deriv2 dt; // declared private copy constructor, cannot be used. //Deriv2 dt1 = dt; return 0; }
true
31b34836755d537888e0aaba5f1094dfd2818fd9
C++
thiagofigcosta/miniPearlInterpretor
/interpreter/command/IfCommand.cpp
UTF-8
519
2.890625
3
[]
no_license
#include "IfCommand.hpp" #include <cassert> IfCommand::IfCommand(IfHead* cond, Command* then, int line) : Command(line),cond_(cond),then_(then),else_(nullptr){ } IfCommand::IfCommand(IfHead* cond, Command* then, Command* elsecmd,int line) : Command(line),cond_(cond),then_(then),else_(elsecmd) { } IfCommand::~IfCommand() { delete cond_; delete then_; delete else_; } void IfCommand::execute() { if(cond_->expr()){ then_->execute(); }else if(else_){ else_->execute(); } }
true
b052605f785883e52d954af14e83f763fd3ad0ee
C++
Nikhil12321/codes
/longest_palindromic_subsequence.cpp
UTF-8
1,185
3.140625
3
[]
no_license
#include<iostream> #include<string> using namespace std; int maxi(int a, int b){ if(a>b) return a; return b; } string longestPalindrome(string str) { int l, i, j, n; n = str.size(); int ans[n][n]; int max = -1111; int posl = 0; int maxl = 1; for(i=0; i<n; i++){ ans[i][i] = 1; ans[i][0] = 0; } for(l=2; l<=n; l++){ for(i=0; (l+i)<=n; i++){ j = i+l-1; /* if(str[i]==str[j] && l==2){ ans[i][j] = 2; if(max < ans[i][j]){ max = ans[i][j]; posl = i; maxl = l; } } */ if(str[i]==str[j]){ ans[i][j] = ans[i+1][j-1]+2; if(max < ans[i][j]){ max = ans[i][j]; posl = i; maxl = l; } } else ans[i][j] = maxi(ans[i][j-1], ans[i+1][j]); } } return str.substr(posl, maxl); } int main(){ string s; cin>>s; string ans = longestPalindrome(s); cout<<ans<<endl; }
true
57d36bf4560467af3701ef6c486fd0aa919ad7c1
C++
dantswain/rhubarb
/sample_client.cpp
UTF-8
618
2.546875
3
[ "MIT" ]
permissive
/* * sample_client.cpp - shows simple usage of rhubarb client socket * * compiling: * *nix/OS X: g++ sample_client.cpp -o sample_client * * Copyright (c) 2011 Daniel T. Swain * See the file license.txt for copying permissions * */ #include <stdio.h> #include "clients/rhubarbSocket.h" int main(int argc, char** argv) { rhubarb_socket_t sock = getRhubarbSocket("127.0.0.1", 1234); std::cout << "Got: " << rhubarbMessage(sock, "get ultimateanswer") << std::endl; std::cout << "Got: " << rhubarbMessage(sock, "set ultimateanswer 54") << std::endl; closeRhubarbSocket(sock); }
true
0f50e6f8eb014aa2c9ff1d44e257688afc76daac
C++
Amrut182/data-structures
/linkedList.cpp
UTF-8
1,032
4.21875
4
[]
no_license
//Linked list with 3 nodes //Printing the values of 3 nodes //Printing the value of node at given index //Printing the index of given value after searching #include<bits/stdc++.h> using namespace std; class Node { public: int data; Node* next; }; void printList(Node *n) { while(n) { //n != NULL cout << n -> data << endl; n = n -> next; } } void printValueAtIndex(Node *n, int index) { while(index--) { n = n -> next; } cout << n -> data << endl; } void searchNode(Node *n, int value) { int count = 0; while(n) { if(value == n -> data) { cout << "found at index " << count << endl; return; } n = n -> next; count++; } } int main() { Node* head = NULL; Node* second = NULL; Node* third = NULL; //allocating 3 nodes in heap head = new Node(); second = new Node(); third = new Node(); head -> data = 1; head -> next = second; second -> data = 2; second -> next = third; third -> data = 3 ; third -> next = NULL; printList(head); printValueAtIndex(head, 0); searchNode(head, 1); }
true
a474ef120844fc1440d018274a2c3aee466d6757
C++
ryankall/find_max_of_function
/main.cpp
UTF-8
794
3.203125
3
[]
no_license
/* * File: main.cpp * Author: Ryan Kallicharran * * Created on April 23, 2015, 8:06 PM */ #include <cstdlib> #include <iostream> #include <math.h> #define ESP .01 using namespace std; //function double F(int x){ double function = -(x*x) -10; return function; } void findMaxofFunction(int a, int b, int count){ double x,y, f; double highest; double z; z = (-1 + sqrt(5))/2; y = a+ z*(b-a); x = a+ z*(y-a); while(fabs(F(y)-F(x)) > ESP){ if(F(x)< F(y)){ a = x; std::cout<< x<<","<< y<<std::endl; }else{ b = y; } y = a+ z*(b-a); x = a+ z*(y-a); } std::cout<< x<<","<< y<<std::endl; } /* * */ int main(int argc, char** argv) { findMaxofFunction(0,3,0); return 0; }
true
1c141e48656a690ba773afddcdf90187d7888fcf
C++
AppCrashExpress/DA-labs
/DA-lab-2/max_tree.cpp
UTF-8
10,121
3.34375
3
[]
no_license
#include <iostream> #include <string> #include <cstring> #include <cstdlib> #include <fstream> #include <unistd.h> bool equal(const char *str1, const char *str2){ if(str1 == nullptr || str2 == nullptr){ return false; } int i = 0; while(str1[i] != '\0' && str2[i] != '\0'){ if(str1[i] != str2[i]){ return false; } i++; } if(str1[i] == '\0' && str2[i] != '\0'){ return false; } if(str2[i] == '\0' && str1[i] != '\0'){ return false; } return true; } void to_lower_case(char *str){ if(str == nullptr){ return; } for(int i = 0; str[i] != '\0'; i++){ if(str[i] >= 'A' && str[i] <= 'Z'){ str[i] = 'a' + str[i] - 'A'; } } } struct myStructure{ char word[257]; unsigned long long number; }; std::ostream &operator<<(std::ostream &os, myStructure* &st){ os << st->word << ": " << st->number; return os; } std::istream &operator>>(std::istream &is, myStructure* &st){ st = new myStructure; is >> st->word; is >> st->number; return is; } struct node{ node *left; node *right; node *parent; myStructure *key; int height; }; class avl_tree{ public: avl_tree(): root(nullptr){} ~avl_tree(){ destroy_tree(root); root = nullptr; } void add(myStructure* &st){ to_lower_case(st->word); if(root != nullptr){ rebalance(add(st, root)); }else{ root = new node; root->left = root->right = nullptr; root->parent = nullptr; root->key = st; root->height = 1; std::cout << "OK\n"; } } void find(char *str){ to_lower_case(str); find(root, str); } void remove(char *str){ to_lower_case(str); remove(root, str); } void save(char *file){ std::ofstream ostr(file); if(ostr.is_open()){ save(root, ostr); ostr.close(); std::cout << "OK\n"; }else{ std::cout << "ERROR: can not open file to save tree\n"; } } void load(char *file){ std::ifstream istr(file); if(istr.is_open()){ destroy_tree(root); root = load(istr); istr.close(); std::cout << "OK\n"; }else{ std::cout << "Error: can not open file to load tree\n"; } } void print(){ print_tree(root); std::cout << "\n"; } private: node *root; node *add(myStructure* &st, node *n){ int string_diff = strcmp(st->word, n->key->word); if(string_diff < 0){ if(n->left == nullptr){ n->left = new node; n->left->left = n->left->right = nullptr; n->left->parent = n; n->left->key = st; n->left->height = 1; std::cout << "OK\n"; return n->left; }else{ return add(st, n->left); } }else if(string_diff > 0){ if(n->right == nullptr){ n->right = new node; n->right->left = n->right->right = nullptr; n->right->parent = n; n->right->key = st; n->right->height = 1; std::cout << "OK\n"; return n->right; }else{ return add(st, n->right); } }else{ delete st; std::cout << "Exist\n"; return nullptr; } } void print_tree(node *n){ static int l = 0; if(n != NULL){ l++; print_tree(n->right); for(int i = 1; i < l; i++){ std::cout << "\t"; } std::cout << "\\__" << n->key << std::endl; print_tree(n->left); l--; } } void destroy_tree(node *n){ if(n != nullptr){ destroy_tree(n->left); n->left = nullptr; destroy_tree(n->right); n->right = nullptr; n->parent = nullptr; delete n->key; delete n; } } void rebalance(node *n){ while(n != nullptr){ n->height = get_max_height(n->left, n->right)+1; int diff = get_diff(n->left, n->right); if(diff == -2){ switch(get_diff(n->right->left, n->right->right)){ case -1: case 0: left_rotate(n, n->right, n->right->left); break; case 1: big_left_rotate(n, n->right, n->right->left, n->right->left->left, n->right->left->right); break; } }else if(diff == 2){ switch(get_diff(n->left->left, n->left->right)){ case 0: case 1: right_rotate(n, n->left, n->left->right); break; case -1: big_right_rotate(n, n->left, n->left->right, n->left->right->left, n->left->right->right); break; } } root = n; n = n->parent; } } void left_rotate(node *x, node *y, node *beta){ if(x->parent != nullptr){ if(x->parent->left == x){ x->parent->left = y; }else{ x->parent->right = y; } } y->parent = x->parent; x->right = beta; if(beta != nullptr){ beta->parent = x; } y->left = x; x->parent = y; x->height = get_max_height(x->left, x->right)+1; y->height = get_max_height(y->left, y->right)+1; } void right_rotate(node *x, node *y, node *beta){ if(x->parent != nullptr){ if(x->parent->left == x){ x->parent->left = y; }else{ x->parent->right = y; } } y->parent = x->parent; x->left = beta; if(beta != nullptr){ beta->parent = x; } y->right = x; x->parent = y; x->height = get_max_height(x->left, x->right)+1; y->height = get_max_height(y->left, y->right)+1; } void big_left_rotate(node *x, node *y, node *z, node *beta, node *gamma){ z->left = x; z->right = y; if(x->parent != nullptr){ if(x->parent->left == x){ x->parent->left = z; }else{ x->parent->right = z; } } z->parent = x->parent; x->right = beta; if(beta != nullptr){ beta->parent = x; } y->left = gamma; if(gamma != nullptr){ gamma->parent = y; } x->parent = z; y->parent = z; x->height = get_max_height(x->left, x->right)+1; y->height = get_max_height(y->left, y->right)+1; z->height = get_max_height(z->left, z->right)+1; } void big_right_rotate(node *x, node *y, node *z, node *beta, node *gamma){ z->left = y; z->right = x; if(x->parent != nullptr){ if(x->parent->left == x){ x->parent->left = z; }else{ x->parent->right = z; } } z->parent = x->parent; y->right = beta; if(beta != nullptr){ beta->parent = y; } x->left = gamma; if(gamma != nullptr){ gamma->parent = x; } y->parent = z; x->parent = z; x->height = get_max_height(x->left, x->right)+1; y->height = get_max_height(y->left, y->right)+1; z->height = get_max_height(z->left, z->right)+1; } int get_max_height(const node *left, const node *right){ if(left == nullptr && right == nullptr){ return 0; } if(left == nullptr){ return right->height; } if(right == nullptr){ return left->height; } return std::max(left->height, right->height); } int get_diff(const node *left, const node *right){ if(left == nullptr && right == nullptr){ return 0; } if(left == nullptr){ return -(right->height); } if(right == nullptr){ return left->height; } return left->height - right->height; } void find(const node *n, char *str){ if(n == nullptr){ std::cout << "NoSuchWord\n"; return; } int string_diff = strcmp(str, n->key->word); if(string_diff < 0){ find(n->left, str); }else if(string_diff > 0){ find(n->right, str); }else{ std::cout << "OK: " << n->key->number << '\n'; } } void remove(node *n, char *str){ if(n == nullptr){ std::cout << "NoSuchWord\n"; return; } int string_diff = strcmp(str, n->key->word); if(string_diff < 0){ remove(n->left, str); }else if(string_diff > 0){ remove(n->right, str); }else{ if(n->left == nullptr && n->right == nullptr){ if(n->parent == nullptr){ delete n->key; delete n; root = nullptr; }else{ if(n->parent->left == n){ n->parent->left = nullptr; }else{ n->parent->right = nullptr; } rebalance(n->parent); delete n->key; delete n; } }else if(n->left == nullptr){ node *temp = n->right; while(temp->left != nullptr){ temp = temp->left; } if(temp->right != nullptr){ temp->right->parent = temp->parent; } if(temp->parent->left == temp){ temp->parent->left = temp->right; }else{ temp->parent->right = temp->right; } std::swap(temp->key, n->key); rebalance(temp->parent); delete temp->key; delete temp; }else{ node *temp = n->left; while(temp->right != nullptr){ temp = temp->right; } if(temp->left != nullptr){ temp->left->parent = temp->parent; } if(temp->parent->left == temp){ temp->parent->left = temp->left; }else{ temp->parent->right = temp->left; } std::swap(temp->key, n->key); rebalance(temp->parent); delete temp->key; delete temp; } std::cout << "OK\n"; } } void save(node *n, std::ofstream &os){ if(n == nullptr){ return; } os << n->key->word << '\t'; os << n->key->number << '\t'; os << n->height << '\t'; bool has_left = (n->left != nullptr); bool has_right = (n->right != nullptr); os << has_left << '\t'; os << has_right << '\t'; if(has_left){ save(n->left, os); } if(has_right){ save(n->right, os); } } node *load(std::ifstream &is){ node *n = new node; n->key = new myStructure; if(!(is >> n->key->word)){ return n; } is >> n->key->number; is >> n->height; bool has_left = false; bool has_right = false; is >> has_left; is >> has_right; if(has_left){ n->left = load(is); n->left->parent = n; }else{ n->left = nullptr; } if(has_right){ n->right = load(is); n->right->parent = n; }else{ n->right = nullptr; } n->parent = nullptr; return n; } }; int main(){ std::ios_base::sync_with_stdio(false); avl_tree tree; myStructure *st; char action[257]; char file_name[1000]; /* int k; std::cin >> k; for(int i = 0; i < k; i++){ std::cin >> st; tree.add(st); } //tree.print(); for(int i = 0; i < k; i++){ std::cin >> action; tree.remove(action); } return 0; */ while(std::cin >> action){ switch(action[0]){ case '+': std::cin >> st; tree.add(st); break; case '-': std::cin >> action; tree.remove(action); break; case '!':{ std::cin >> action; std::cin >> file_name; if(action[0] == 'S'){ //Save tree.save(file_name); }else{ //Load tree.load(file_name); } break; } default: tree.find(action); break; } } }
true
eabe9e8ad698fb166b66104b755521e12ce45239
C++
aebraryucel/Data-Structures-and-Algorithms-C
/GRAPHS2/Graph2.cpp
ISO-8859-9
13,346
3.234375
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> #define CAPACITY 999 struct AdjListNode //adj listelerindeki dm { int id; struct AdjListNode* next; }; struct AdjList //adj listesi { struct AdjListNode *head; int id; //hangi id ye ait listenin tutulduu }; struct Graph { int currentsize; //graftaki adj listesi says struct AdjList* array; //adj listelerini tutan array }; struct read{ //her satr ile okunan verileri tuttuumuz veri yaps char follower[10]; char followed[10]; }; struct AdjListNode* newAdjListNode(int id) { //adj listesi dm oluturan fonksiyon struct AdjListNode* newNode = (struct AdjListNode*) malloc(sizeof(struct AdjListNode)); newNode->id = id; newNode->next = NULL; return newNode; } struct Graph* createGraph(int maxsize) { //graf oluturan fonksiyon struct Graph* g = (struct Graph*) malloc(sizeof(struct Graph)); g->currentsize = 0; g->array = (struct AdjList*)malloc(maxsize*sizeof(struct AdjList)); for (int i=0;i<maxsize;i++) g->array[i].head = NULL; return g; } void printGraph(struct Graph* g) { //graf yazdran fonksiyon for (int i=1;i<g->currentsize;i++) { struct AdjListNode* current = g->array[i].head; printf("\n %d id li kullanicinin takip listesi : \n head ",g->array[i].id ); while (current) { printf("-> %d", current->id); current = current->next; } printf("\n"); } } int search(int id,struct Graph* g){//verilen id ye ait adjacency listesinin grafta olup olmadn kontrol eden yardmc fonksiyon int i=0; while(g->array[i].id!=0){ if(g->array[i].id==id){ return 1; } i++; } return 0; } void addFollowerList(struct Graph* g,int followerId){ //grafa adj listesi ekleyen yardmc fonksiyon int i=0; while(g->array[i].id!=0){ i++; } g->array[i].id=followerId; g->currentsize++; } void addFollowedNode(struct Graph* g,int followerId,int followedId){ //verilen adjacency listesine(follower) node(followed) ekleyen yardmc fonksiyon struct AdjListNode* node=newAdjListNode(followedId); int i=0; while(g->array[i].id!=followerId){ i++; } node->next=g->array[i].head; g->array[i].head=node; } void addEdge(struct Graph* g,int followerId,int followedId){ //verilen id lere gre grafa adjacency list(follower) ve adjacecency list node(followed) ekleyen fonksiyon if(search(followerId,g)){ //eer aranan adj listesi grafta varsa followed listeye eklenir addFollowedNode(g,followerId,followedId);//followed listeye ekle } else{ //eer liste yoksa liste grafa eklenir ardndan followed listeye eklenir. addFollowerList(g,followerId); //listeyi ekle addFollowedNode(g,followerId,followedId);//followed listeye ekle } if(!search(followedId,g)){ //followed adj listesi yoksa eklenir. addFollowerList(g,followedId);//listeyi ekle } } struct Graph* readcsv(struct Graph* g){ //csv dosyasn okuyarak graf yapsn oluturan fonksiyon,csv dosyasndaki satrlar "struct read" veri yapsna okunur.Okunan deerler integer'a evrilir elde edilen deerler id olarak kullanlr //Bu id deerleri iin "addEdge" fonksiyonuyla grafta tutulan adjacency listesi olup olmad kontrol edilir eer yoksa eklenir varsa gerekli balantlar yaplr. int followerId; int followedId; struct read* read=(struct read*)malloc(sizeof(struct read)); FILE* file=fopen("SNAgraph.csv","r"); if(file==NULL){ printf("Can't open file!\n"); return g; } char buff[1024]; int row_count=0; int field_count=0; int i=0; while(fgets(buff,10240,file)){ field_count=0; row_count++; char* field=strtok(buff,","); while(field){ if(field_count==0){ strcpy(read->follower,field); } if(field_count==1){ strcpy(read->followed,field); } field=strtok(NULL,","); field_count++; } i++; followerId=atoi(read->follower); followedId=atoi(read->followed); addEdge(g,followerId,followedId); } fclose(file); return g; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// int searchIndex(int id,struct Graph* g){ //Verilen id ye ait adj listesinin liste dizisindeki indeksini dndren fonksiyon int i=0; while(g->array[i].id!=0){ if(g->array[i].id==id){ return i; } i++; } return -1; } int followedcounter(int id,struct Graph* g){ //verilen adj. listesindeki dm saysn bulan fonksiyon,balant says hesabnda kullanlr. int count=0; int index=searchIndex(id,g); struct AdjListNode* current=g->array[index].head; while(current){ current=current->next; count++; } return count; } int followercounter(int id,struct Graph* g){ //verilen id nin dier id lere ait adj listelerinde ka balants olduunu bulan fonksiyon,balant says hesabnda kullanlr. int count=0; int index=searchIndex(id,g); struct AdjListNode* current; for(int i=0;i<g->currentsize;i++){ current=g->array[i].head; while(current){ if(current->id==id){ count++; } current=current->next; } } return count; } int findMin(int linkList[10]){ //en fazla balantya sahip 10 kullancy bulurken kullandmz verilen dizinin en kk elemannn indeksini bulan fonksiyon int min=linkList[0]; int index=0; for(int i=1;i<10;i++){ if(linkList[i]<=min){ min=linkList[i]; index=i; } } return index; } int idList[10]={0,0,0,0,0,0,0,0,0,0}; //en fazla balantya sahip 10 kullancnn id lerinin tutan dizi. int linkList[10]={0,0,0,0,0,0,0,0,0,0}; //en fazla balantya sahip 10 kullancnn balant saysn tutan dizi , id ve list dizisi ortak indeksle kullanlacak yani idList[0]'daki id'nin balant listesi linkList[0]'da tutulacak void TopTenLink(struct Graph* g){ //En fazla balantya sahip 10 kullancnn id lerini ve balant saysn idList ve linkList dizilerinde tutan fonksiyon //Her bir id iin takip ettiklerinin says,ka kii tarafndan takip edildii says toplanarak balant says bulunur. //Ve her id iin balant says hesaplanrken en fazla 10 balant saysn tutan dizi gncellenir. int count; int index; int currentid; for(int i=1;i<g->currentsize;i++){ count=followedcounter(g->array[i].id,g); count+=followercounter(g->array[i].id,g); index=findMin(linkList); if(count>linkList[index]){ idList[index]=g->array[i].id; linkList[index]=count; } } } void insertionSort(int arr[], int n) //medyan deerini bulmak iin kullanlacak yardmc fonksiyon { int i, key, j; for (i=1;i<n;i++) { key=arr[i]; j=i-1; while(j>=0 && arr[j]>key) { arr[j+1]=arr[j]; j=j-1; } arr[j+1]=key; } } void AvgAndMedian(struct Graph* g){ //ortalama ve medyan deerlerini hesaplayan fonksiyon //Tm balant saylar hesaplanr ve kullanc saysna blnrek ortalama hesaplanr,ardndan balant saylarn tutan dizi sralanarak medyan hesab yaplr. float avg; int median; int currentsize=g->currentsize; int linkcounts[currentsize]; for(int i=1;i<currentsize;i++){ //her bir adj listesindeki balant saylarnn srasyla linkcounts dizisine yerletirilmesi linkcounts[i]=followedcounter(g->array[i].id,g); linkcounts[i]+=followercounter(g->array[i].id,g); } float sum=0; for(int j=1;j<g->currentsize;j++){ //ortalama deerin hesaplanmas sum=linkcounts[j]+sum; } avg=sum/currentsize; printf("Average : %f \n",avg); insertionSort(linkcounts,currentsize); int medianIndex=currentsize/2; median=linkcounts[medianIndex]; //medyan hesab printf("Median : %d ",median); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //BFS iin queue implementasyonu int queue[CAPACITY]; unsigned int size = 0; unsigned int rear = CAPACITY - 1; unsigned int front = 0; int isFull() { return (size == CAPACITY); } int isEmpty() { return (size == 0); } int enqueue(int data) { if (isFull()) { return 0; } rear = (rear + 1) % CAPACITY; size++; queue[rear] = data; return 1; } int dequeue() { int data = INT_MIN; if (isEmpty()) { return INT_MIN; } data = queue[front]; front = (front + 1) % CAPACITY; size--; return data; } struct AdjListNode* searchID(int id,struct Graph* g){ //Grafta verilen id ye ait bir adj listesinin head pointer'n dndrrr. BFS'de kullanlmak zere yardmc fonksiyon. int i=0; while(g->array[i].id!=0){ if(g->array[i].id==id){ return g->array[i].head; } i++; } return NULL; } int followerIDs[2000];//followerlarn ID lerini tutan dizi int visitedIDs[2000];//ID lerin ziyaret edilip edilmediini tutan dizi void createFollowerArray(struct Graph* g){ //adj listelerini tutan dizide her indeksin hangi ID iin tutan diziyi oluturan fonksiyon. for(int i=1;i<g->currentsize;i++){ followerIDs[i]=g->array[i].id; } } int findIndexOfId(int id,struct Graph* g){ //IDleri tutan dizide aranan ID'nin indeksini dndren fonksiyon. for(int i=0;i<g->currentsize;i++){ if(id==followerIDs[i]){ return i; } } return -1; } int* findMinPath(struct Graph* g,int startID){ //BFS ile verilen id yi balang dm alarak dier dmlere olan minimum uzaklklar hesaplayp dizi olarak dndren fonksiyon struct AdjListNode* current=NULL; int qval; int i; struct path* prev; int currentfollowerIndex; int index; int* pathlengths=(int*)malloc((g->currentsize)*sizeof(int)); for(int j=0;j<g->currentsize;j++){ pathlengths[j]=999; visitedIDs[i]=0; } enqueue(startID); index=findIndexOfId(startID,g); visitedIDs[index]=1;//balang dmnn visited yaplmas pathlengths[index]=0; while(!isEmpty()){ qval=dequeue();//ilk elemann sradan alnmas current=searchID(qval,g);//elde edilen ID nin adj listesine erime i=searchIndex(qval,g); currentfollowerIndex=findIndexOfId(g->array[i].id,g);//bulunduumuz listenin followerIDs dizisindeki indeksi while(current){ index=findIndexOfId(current->id,g); if(!visitedIDs[index]){ pathlengths[index]=pathlengths[currentfollowerIndex]+1; visitedIDs[index]=1; enqueue(current->id); } current=current->next; } } return pathlengths; } void printOnePath(int id,struct Graph* g){ //id si verilen dmn ulalabilir tm dier dmlere olan uzakln gsteren fonksiyon int* pathArray=findMinPath(g,id); for(int i=1;i<g->currentsize;i++){ if(pathArray[i]!=999 && pathArray[i]!=0){ printf("id:%d 's path length to id:%d is %d",id,g->array[i].id,pathArray[i]); printf("\n"); } } } void allPaths(struct Graph* g){ //tm dmlerin dier dmlere olan minimum uzaklklarn hesaplayp yazdran fonksiyon int id; for(int i=1;i<g->currentsize;i++){ id=g->array[i].id; printOnePath(id,g); } } int main() { setbuf(stdout, NULL); struct Graph* g= createGraph(2000); g=readcsv(g); TopTenLink(g); for(int i=0;i<10;i++){ printf("id-> %d Linkcount->%d \n",idList[i],linkList[i]); } AvgAndMedian(g); // printGraph(g); // createFollowerArray(g); // printOnePath(8135,g); // allPaths(g); /* for(int i=0;i<g->currentsize;i++){ if(pathLengths[514][i]!=999 && pathLengths[514][i]!=0){ printf("%d\n",pathLengths[514][i]); } } */ //printPathLengths(g,pathLengths); return 0; }
true
7d6f5b4f2fcae4da0f9e1f6c392e62e8e1aafdd4
C++
kinasmith/ASRA
/hampshite_demo/src/sensor/sensor.cpp
UTF-8
3,674
2.75
3
[]
no_license
/** * Currently the EEPROM is really front loaded. * The time address is overwritten the most, and * the high addresses will never be used.figure out a way to balance the data load! */ #include <Arduino.h> #include <SPI.h> #include <Wire.h> #include "SHT2x.h" //https://github.com/misenso/SHT2x-Arduino-Library #include "Sleepy.h" //https://github.com/kinasmith/Sleepy #include "RFM69_ATC.h" //https://www.github.com/lowpowerlab/rfm69 #define NODEID 9 //unique for each node on same network #define NETWORKID 100 //the same on all nodes that talk to each other #define GATEWAYID 0 //The address of the datalogger #define FREQUENCY RF69_433MHZ //frequency of radio #define ATC_RSSI -70 //ideal Signal Strength of trasmission #define ACK_WAIT_TIME 100 // # of ms to wait for an ack #define ACK_RETRIES 10 // # of attempts before giving up #define SERIAL_BAUD 9600 // Serial comms rate #define LED 8 // UI LED #define SERIAL_EN //Comment this out to remove Serial comms and save a few kb's of space #ifdef SERIAL_EN #define DEBUG(input) {Serial.print(input); delay(1);} #define DEBUGln(input) {Serial.println(input); delay(1);} #define DEBUGFlush() { Serial.flush(); } #else #define DEBUG(input); #define DEBUGln(input); #define DEBUGFlush(); #endif // Functions float getBatVoltage(); void Blink(int); ISR(WDT_vect) { Sleepy::watchdogEvent(); } //watchdog for sleeping timer RFM69_ATC radio; //init radio //Data Structure for transmitting data packets to datalogger (10 bytes) struct Payload { float temp; float humidity; float voltage; }; Payload thePayload; const uint8_t BAT_EN = 3; void setup() { #ifdef SERIAL_EN Serial.begin(SERIAL_BAUD); #endif Wire.begin(); pinMode(BAT_EN, OUTPUT); pinMode(LED, OUTPUT); digitalWrite(LED, HIGH); delay(1000); digitalWrite(LED, LOW); randomSeed(analogRead(0)); //set random seed Wire.begin(); // Begin i2c radio.initialize(FREQUENCY,NODEID,NETWORKID); radio.setHighPower(); radio.encrypt(null); radio.enableAutoPower(ATC_RSSI); //Test to see if this is actually working at some point DEBUG("-- Network Address: "); DEBUG(NETWORKID); DEBUG("."); DEBUGln(NODEID); } void loop() { thePayload.temp = SHT2x.GetTemperature(); thePayload.humidity = SHT2x.GetHumidity(); thePayload.voltage = getBatVoltage(); DEBUG(thePayload.temp); DEBUG(","); DEBUG(thePayload.humidity); DEBUG(","); DEBUG(thePayload.voltage); DEBUGln(); digitalWrite(LED, HIGH); if(radio.sendWithRetry(GATEWAYID, (const void*)(&thePayload), sizeof(thePayload)), ACK_RETRIES, ACK_WAIT_TIME) { DEBUG("data - snd - "); DEBUG('['); DEBUG(GATEWAYID); DEBUG("] "); DEBUG(sizeof(thePayload)); DEBUGln(" bytes "); digitalWrite(LED, LOW); } else { DEBUGln("data - snd - Failed . . . no ack"); Blink(100); Blink(100); Blink(100); Blink(100); } DEBUG("sleep - sleeping for 1 "); DEBUG(" seconds"); DEBUGln(); DEBUGFlush(); radio.sleep(); Sleepy::loseSomeTime(500); } /** * [getBatVoltage description] * @return [description] */ float getBatVoltage() { /* Gets battery voltage from sensor. Does 10x average on the analog reading */ uint8_t BAT = A0; uint16_t readings = 0; digitalWrite(BAT_EN, HIGH); delay(10); for (byte i=0; i<3; i++) readings += analogRead(BAT); readings /= 3; float v = 3.3 * (readings/1023.0) * (4300.0/2700.0); //Calculate battery voltage digitalWrite(BAT_EN, LOW); return v; } /** * [Blink description] * @param PIN [description] * @param DELAY_MS [description] */ void Blink(int DELAY_MS) { digitalWrite(LED,HIGH); delay(DELAY_MS); digitalWrite(LED,LOW); delay(DELAY_MS); }
true
33cebeeb1d90aabd9dd2dd3c94d362b4b9cc294d
C++
ABX9801/Data-Structures
/pointers/char_arr2.cpp
UTF-8
323
3.375
3
[]
no_license
#include<iostream> using namespace std; // A functions that takes in a character pointer as an argument // A call-by-reference type function void print(char* C){ int i=0; while(*(C+i)!='\0'){ printf("%c",*(C+i)); i+=1; } } int main(void){ char* C = "Anurag"; print(C); return 0; }
true
8b2e65a2428c7e356fcdc46def26ffa7e96dabed
C++
AOS-Group-1/coen383
/assignment3/concert.h
UTF-8
683
2.953125
3
[]
no_license
#ifndef ASSIGNMENT3_CONCERT_H #define ASSIGNMENT3_CONCERT_H #include "customer.h" typedef struct { bool assigned; Customer *customer; } Seat; class Concert { private: static Concert *instance; // Private Constructor so that no objects can be created Concert(); Seat *seats[10][10]{}; pthread_mutex_t locks[10][10]{}; public: static Concert *getInstance() { if (!instance) instance = new Concert; return instance; } // returns false if could not set seat bool allocateSeat(Customer *customer, int row); void printSeats(); void printStats(int n, int time); bool isFull(); bool isRowFull(int row); }; #endif //ASSIGNMENT3_CONCERT_H
true
d95cd98f19412570d2ca5d40cf4621f79f4cf836
C++
wyc25013/leetcode
/79_Word_Search/79.cpp
UTF-8
2,078
3.375
3
[]
no_license
#include <vector> #include <string> #include <iostream> using namespace std; class Solution { public: bool exist(vector<vector<char> >& board, string word) { int row = board.size(); int col = board[0].size(); vector<vector<bool> > map; for(int i = 0; i < row; i++){ vector<bool> tmp(col,false); map.push_back(tmp); } bool ret = false; char first = word[0]; for(int i = 0; i < row; i++){ for(int j = 0; j < col; j++){ if(board[i][j] == first){ map[i][j] = true; helper(1,ret,board,word,map,i,j); if(ret) break; map[i][j] = false; } } if(ret) break; } return ret; } void helper(int pos, bool& ret,vector<vector<char> >& board, string& word, vector<vector<bool> >& map,int i, int j){ if(pos == word.length()){ ret = true; return; } else { int row = board.size(); int col = board[0].size(); char target = word[pos]; if(i < row-1 && board[i+1][j] == target && map[i+1][j] == false){ map[i+1][j] = true; helper(pos+1,ret,board,word,map,i+1,j); if(ret) return; map[i+1][j] = false; } if(i > 0 && board[i-1][j] == target && map[i-1][j] == false){ map[i-1][j] = true; helper(pos+1,ret,board,word,map,i-1,j); if(ret) return; map[i-1][j] = false; } if(j < col-1 && board[i][j+1] == target && map[i][j+1] == false){ map[i][j+1] = true; helper(pos+1,ret,board,word,map,i,j+1); if(ret) return; map[i][j+1] = false; } if(j > 0 && board[i][j-1] == target && map[i][j-1] == false){ map[i][j-1] = true; helper(pos+1,ret,board,word,map,i,j-1); if(ret) return; map[i][j-1] = false; } } } }; int main(){ char a[] = {'A','B','C','E'}; char b[] = {'S','F','C','S'}; char c[] = {'A','D','E','E'}; vector<char> A(a,a+4); vector<char> B(b,b+4); vector<char> C(c,c+4); vector<vector<char> > board; board.push_back(A); board.push_back(B); board.push_back(C); Solution soln; cout<<soln.exist(board,"ABCCED")<<" "<<soln.exist(board,"SEE")<<" "<<soln.exist(board,"ABCB")<<endl; }
true
0409b9f7befec8e523c98aff2b2364f7b38a257c
C++
jinseongbe/cpp_study
/CPP_52(정적다차원배열_MultiDimensionalArray)/CPP_52/main.cpp
UTF-8
2,427
3.765625
4
[]
no_license
#include <iostream> using namespace std; int main() { //2차원 array const int num_rows = 3; const int num_columns = 5; for(int row = 0; row < num_rows; ++row) { for(int col = 0; col < num_columns; ++col) { cout << '[' << row << ']' << '[' << col << ']' << '\t'; } cout << endl; } cout << endl << endl; int array[num_rows][num_columns]; // row-major <-> column-major array[0][0] = 1; // 일일이 초기화 하는 방법 array[0][1] = 2; int array1[num_rows][num_columns] = // cpp11 이후로는 등료를 빼도 정상적으로 사용 가능함! { {1, 2, 3, 4, 5}, // row 0 {6, 7, 8, 9, 10}, // row 1 {11, 12, 13, 14, 15} // row 2 }; for(int row = 0; row < num_rows; ++row) { for(int col = 0; col < num_columns; ++col) // cout << array1[row][col] << '\t'; cout << (long long)&array1[row][col] << '\t'; cout << endl; } cout << endl << endl; int array2[num_rows][num_columns] { {1, 2, }, // 빈칸은 0으로 자동으로 채워줌 {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15} }; for(int row = 0; row < num_rows; ++row) { for(int col = 0; col < num_columns; ++col) cout << array2[row][col] << '\t'; cout << endl; } cout << endl << endl; int array3[][num_columns] // row는 굳이 쓰지 않아도 되지만, column은 생략불가!! { {1, 2, }, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15} }; for(int row = 0; row < num_rows; ++row) { for(int col = 0; col < num_columns; ++col) cout << array3[row][col] << '\t'; cout << endl; } cout << endl << endl; int array4[num_rows][num_columns]{0}; // 한번에 0으로도 초기화 가능 for(int row = 0; row < num_rows; ++row) { for(int col = 0; col < num_columns; ++col) cout << array4[row][col] << '\t'; cout << endl; } cout << endl << endl; //3차원 이상 array! // 쓰는 방법은 동일: 뒤에서 더 자세히! int array3d[5][4][3]; cout << endl << endl; return 0; }
true
cb1a3e74349a2fe7cdd65ce343fbeb5b64563aa8
C++
SergeiNA/yamr
/test_utils.cpp
UTF-8
1,591
2.828125
3
[]
no_license
#define BOOST_TEST_MODULE min_prefix #include "utils.hpp" #include <iostream> #include <sstream> #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE(min_prefix) BOOST_AUTO_TEST_CASE(test_class_MinPrefix) { std::vector<std::string> input {"a","a","a", "ab","ab", "aab","aab", "aabc", "aabcd" }; yamr::ReduceList out {"1","2","3"}; MinPrefix min_pref; yamr::ReduceList rList; for(auto& s: input){ auto tredl = min_pref(s); if(!tredl.empty()) rList.emplace_back(tredl.at(0)); } BOOST_CHECK_EQUAL(rList.size(), 3); BOOST_CHECK_EQUAL_COLLECTIONS(rList.begin(),rList.end(),out.begin(),out.end()); } BOOST_AUTO_TEST_CASE(WordPrefixSplitter) { PrefixSplitter wPref_split; std::string input1 ("aabbcc"); std::string input2 ("aaaa"); std::string input3 ("abcd"); yamr::MappedWord out1 {"a","aa","aab","aabb","aabbc","aabbcc"}; yamr::MappedWord out2 {"a","aa","aaa","aaaa"}; yamr::MappedWord out3 {"a","ab","abc","abcd"}; yamr::MappedWord w1 = wPref_split(input1); yamr::MappedWord w2 = wPref_split(input2); yamr::MappedWord w3 = wPref_split(input3); BOOST_CHECK_EQUAL_COLLECTIONS(w1.begin(),w1.end(),out1.begin(),out1.end()); BOOST_CHECK_EQUAL_COLLECTIONS(w2.begin(),w2.end(),out2.begin(),out2.end()); BOOST_CHECK_EQUAL_COLLECTIONS(w3.begin(),w3.end(),out3.begin(),out3.end()); } BOOST_AUTO_TEST_SUITE_END()
true
7d8f50057373937d13cc32cf11ebceab9ad83682
C++
TJ95/cs488f19
/cs488/A3/JointNode.cpp
UTF-8
2,207
3.015625
3
[]
no_license
// Fall 2019 #include "JointNode.hpp" using namespace glm; #include <algorithm> //--------------------------------------------------------------------------------------- JointNode::JointNode(const std::string& name) : SceneNode(name) { m_nodeType = NodeType::JointNode; } //--------------------------------------------------------------------------------------- JointNode::~JointNode() { } //--------------------------------------------------------------------------------------- void JointNode::set_joint_x(double min, double init, double max) { m_joint_x.min = min; m_joint_x.init = init; m_joint_x.max = max; xangle = init; trans = glm::rotate(degreesToRadians(xangle), glm::vec3(1, 0, 0)) * trans; } //--------------------------------------------------------------------------------------- void JointNode::set_joint_y(double min, double init, double max) { m_joint_y.min = min; m_joint_y.init = init; m_joint_y.max = max; yangle = init; trans = glm::rotate(degreesToRadians(yangle), glm::vec3(0, 1, 0)) * trans; } //--------------------------------------------------------------------------------------- void JointNode::rotate(char axis, float angle) { vec3 rot_axis; switch (axis) { case 'x': rot_axis = vec3(1,0,0); if (xangle + angle > m_joint_x.max) { xangle = m_joint_x.max - angle; } else if (xangle+angle < m_joint_x.min) { xangle = m_joint_x.min + angle; } else { xangle = angle; } break; case 'y': rot_axis = vec3(0,1,0); if (yangle + angle > m_joint_y.max) { yangle = m_joint_y.max - angle; } else if (yangle + angle < m_joint_y.min) { yangle = m_joint_y.min + angle; } else { yangle = angle; } break; case 'z': rot_axis = vec3(0,0,1); break; default: break; } update_transformation(); } char JointNode::get_rot_axis(){return 'x';} //--------------------------------------------------------------------------------------- void JointNode::update_transformation() { if (get_rot_axis() == 'x') { trans *= glm::rotate(degreesToRadians(xangle), glm::vec3(1,0,0)); } else if (get_rot_axis() == 'y') { trans *= glm::rotate(degreesToRadians(yangle), glm::vec3(0,1,0)); } }
true
dafc670d139ba7d49604ecd7c6372c650575315f
C++
vynaloze/FoP-assignment
/FundOfProgr.cpp
UTF-8
1,203
3.203125
3
[]
no_license
#include "stdafx.h" #include "Person.h" #include "DataBase.h" int main() { DataBase dataBase = DataBase(); cout << "-----------------------------------------------------------" << endl << "Fundamentals Of Programming - Assesment: \"Database program\".\nCreated by Piotr Pawluk." << endl << "-----------------------------------------------------------" << endl; // try to open a file (until success) string fileName; do { cout << "Please provide a name of a file to open: "; getline(cin, fileName); } while (!dataBase.readFromFile(fileName)); dataBase.printAll(); // ask user what to do cout << "-----------------------------------------------------------" << endl << "Avaliable commands:" << endl << "Print the list: print" << endl << "Modify: mod [number of object (1-n)] [number of field (1-3)] [value to write]" << endl << "Add: add [value1] [value2] [value3]" << endl << "Remove: del [number of object (1-n)]" << endl << "Save: save [name of a fie]" << endl << "Exit: exit" << endl << "-----------------------------------------------------------" << endl; string s; while (s != "exit") { getline(cin, s); dataBase.processCommand(s); } return 0; }
true
f5a5b2bc74dc9587a4b70451b0f7742ccbcf8ce3
C++
cjdao/stl_example
/ex08/ex08-04.cpp
UTF-8
1,215
3.484375
3
[]
no_license
#include <iostream> #include <vector> #include <cassert> #include <iomanip> #include <algorithm> #include <functional> using namespace std; template <typename T> class less_with_count: public binary_function<T,T,bool> { public: less_with_count():counter(0),progenitor(0) {} less_with_count(less_with_count<T> &x):counter(0), progenitor(x.progenitor?x.progenitor:&x){} bool operator()(const T& x, const T& y) { counter++; return x<y;} long report(){return counter;} ~less_with_count() { if (progenitor) progenitor->counter += counter; } private: long counter; less_with_count<T> *progenitor; }; // 使用函数对象进行操作计数,版本2 int main() { cout << "Using a function object for operation counting, " << "second version." << endl; const long N1=1000, N2=128000; for (long N=N1; N<=N2; N*=2) { vector<int> vector1; for(int k=0; k<N; k++) vector1.push_back(k); random_shuffle(vector1.begin(), vector1.end()); less_with_count<int> comp_counter; sort(vector1.begin(), vector1.end(), comp_counter); cout << "Problem size " << setw(9) << N << ", comparisons performed: " << setw(9) << comp_counter.report() << endl; } return 0; }
true
8f670df48bbae237397c782f168452b8a93b156c
C++
2203juan/algorithm_workshops
/c++/general/cppPanama/1.cpp
UTF-8
683
3.75
4
[]
no_license
#include <bits/stdc++.h> using namespace std; double get_sueldo(double horas_trabajadas, double valor_hora){ double saldo = 0; if (horas_trabajadas > 40){ saldo += (40*valor_hora); horas_trabajadas -= 40; saldo += (horas_trabajadas*(2.0*valor_hora)); } else { saldo += horas_trabajadas*valor_hora; } return saldo; } int main(){ double horas_trabajadas = 0.0; double valor_hora = 0.0; cout<<"Ingrese las horas trabajadas en la semana"<<endl; cin>>horas_trabajadas; cout<<"Ingrese el valor pagado por hora"<<endl; cin>>valor_hora; double sueldo = get_sueldo(horas_trabajadas, valor_hora); cout<<"El sueldo semanal es: "<<sueldo<<endl; return 0; }
true
5b12731841fce358b9683269f13bfe15a4b885ec
C++
Juliyo/LastBullet
/Desarrollo/BulletTest/BulletTest/Motor/BasicSceneNode.cpp
UTF-8
2,455
2.625
3
[]
no_license
#include "BasicSceneNode.h" #include <GraphicEngine.h> #include <Util.h> BasicSceneNode::BasicSceneNode(TModel* node) : m_node(node) { } BasicSceneNode::~BasicSceneNode() { //m_node->removeNode(); //m_node = nullptr; //m_node->removeNode(); //delete m_node; } void BasicSceneNode::setTexture(const std::string & texture, int material) { //m_node->getMaterial(material).setTexture(0, m_irrDevice->getVideoDriver()->getTexture(texture)); } void BasicSceneNode::setPosition(const Vec3<float>& position) { m_node->setPosition(Vec3<float>(position.getX(), position.getY(), position.getZ())); } Vec3<float> BasicSceneNode::getPosition() { return m_node->getPosition(); } Vec3<float> BasicSceneNode::getRotation() { return m_node->getRotation(); } void BasicSceneNode::setScale(Vec3<float>& scale) { m_node->setScale(scale); } void BasicSceneNode::setRotationXYZ(Vec3<float>& rot) { m_node->setRotationXYZ(rot); } void BasicSceneNode::setOrientation(Vec3<float>& orientation) { //m_node->setOrientation(orientation); glm::mat4 m_matrix = glm::mat4(); glm::vec3 column1; glm::vec3 column2; glm::vec3 column3; glm::vec3 up = glm::vec3(0, 1, 0); glm::vec3 direction = glm::vec3(orientation.getX(), orientation.getY(), orientation.getZ()); glm::vec3 xaxis = glm::cross(up, direction); xaxis = glm::normalize(xaxis); glm::vec3 yaxis = glm::cross(direction, xaxis); yaxis = glm::normalize(yaxis); column1.x = xaxis.x; column1.y = yaxis.x; column1.z = direction.x; column2.x = xaxis.y; column2.y = yaxis.y; column2.z = direction.y; column3.x = xaxis.z; column3.y = yaxis.z; column3.z = direction.z; m_matrix[0][0] = column1.x; m_matrix[1][0] = column1.y; m_matrix[2][0] = column1.z; m_matrix[0][1] = column2.x; m_matrix[1][1] = column2.y; m_matrix[2][1] = column2.z; m_matrix[0][2] = column3.x; m_matrix[1][2] = column3.y; m_matrix[2][2] = column3.z; m_node->setRotationMatrix(m_matrix); } Vec3<float> BasicSceneNode::getScale() { return m_node->getScale(); } void BasicSceneNode::addChild(std::shared_ptr<SceneNode> child) { //m_node->addChild(child->getEntityNode()); } void BasicSceneNode::removeChild(std::shared_ptr<SceneNode> child) { m_node->removeChild(child->getEntityNode()); } void BasicSceneNode::setColor(const Vec3<float> color) { m_node->setModelColor(color.getX(), color.getY(), color.getZ()); } void BasicSceneNode::setVisible(bool visible) { m_node->setVisible(visible); }
true
bb92a5bb9d7a25ecba16cd6337db93769c8b2968
C++
gitcollect/backdoorCppCrossPlateform
/src/core/cli/Interface.cpp
UTF-8
4,484
2.796875
3
[]
no_license
// // Created by mfranc on 18/09/15. // #include "Interface.h" Interface::Interface(int argc, const char** argv) { this->setFlagIsValidOptions( this->setArgc(argc) .setArgv(argv) .initProgramOptions() ); } /** * Initialize programm option from CLI with C++ Boost lib */ bool Interface::initProgramOptions() { int argc = this->getArgc(); const char** argv = this->getArgv(); po::options_description optDesc("Usage"); optDesc.add_options() ("help,h", "Display usage") ("version,V", "Display version of programme") ("verbose,v", "Enable mode verbose") ("listen,l", "Enable listen mode (server socket mode)") // ("port,p", po::value<int>()->required(), "Set port number to use") // ("host,H", po::value<string>()->required(), "Set hostname to use") ("port,p", po::value<int>(), "Set port number to use") ("host,H", po::value<string>(), "Set hostname to use") ("input-file,f", po::value< vector<string> >(), "File wich conains query to send (doesn't work with -l option)") ; po::variables_map variablesMap; try{ po::store(po::parse_command_line(argc, argv, optDesc), variablesMap); po::notify(variablesMap); if (variablesMap.count("help")) { cout << optDesc << endl; return false; } if (variablesMap.count("version")) { cout << PRODUCT_NAME << " : Build " << BUILD << " Version " << VERSION << endl << "Author : " << AUTHOR << " (see: " << CONTACT << ")" << endl; return false; } if (variablesMap.count("verbose")) { cout << "Mode verbose enable" << endl; this->setModeVerbose(true); } if (variablesMap.count("listen")) { cout << "Mode listen enable" << endl; this->setModeListen(true); } if (variablesMap.count("input-file")) { if (variablesMap.count("listen")) throw std::logic_error("Unable to use -l|--listen option with -f|--input-file option"); this->setFilePath(variablesMap["input-file"].as<string>()); } if (!variablesMap.count("host")) { throw logic_error("the option '--host|-H' is required but missing"); } if (!variablesMap.count("port")) { throw logic_error("the option '--port|-p' is required but missing"); } this->setHost(variablesMap["host"].as<string>()); this->setPort(variablesMap["port"].as<int>()); if (1 == argc) { char buffer[100]; string message = "Missing some required arguments ! (nb passed: %d)"; const char* formatStringMessage = message.c_str(); int param1 = argc - 1; snprintf(buffer, sizeof(buffer), formatStringMessage, param1); throw logic_error(buffer); } } catch(exception &e) { cerr << "Error: " << e.what() << endl << optDesc << endl ; return false; } return true; } int Interface::getArgc() { return this->argc; } Interface & Interface::setArgc(int argc) { this->argc = argc; return *this; } const char** Interface::getArgv() const { return this->argv; } Interface & Interface::setArgv(const char** argv) { this->argv = argv; return *this; } const string& Interface::getHost() { return this->host; } Interface & Interface::setHost(const string &host) { this->host = host; return *this; } int Interface::getPort() { return this->port; } Interface & Interface::setPort(int port) { this->port = port; return *this; } bool Interface::isValidOptions() { return this->flagIsValidOptions; } Interface & Interface::setFlagIsValidOptions(bool flag) { this->flagIsValidOptions = flag; return *this; } bool Interface::isModeListenEnabled() const { return modeListen; } Interface & Interface::setModeListen(bool flag) { this->modeListen = flag; return *this; } bool Interface::isModeVerboseEnabled() const { return modeVerbose; } Interface & Interface::setModeVerbose(bool flag) { this->modeVerbose = flag; return *this; } const string & Interface::getFilePath() const { return this->filePath; } Interface & Interface::setFilePath(const string &filePath) { this->filePath = filePath; return *this; }
true
82feae985179f3af16c5292e7dd577ee94849642
C++
toksn/TINYTRAIN_2D
/TINYTRAIN_2D/Spline_CatmullRom.h
UTF-8
1,820
2.640625
3
[]
no_license
#pragma once #include "Spline.h" namespace tgf { namespace math { class Spline_CatmullRom : public Spline { public: // catmull rom type // see http://www.cemyuksel.com/research/catmullroparam_/catmullrom.pdf for more info enum class CatmullRomType { Uniform, // uniform is faster, can introduce self intersections Chordal, // chordal is more curvy, less intersections Centripetal // centripetal in between, no intersections }; Spline_CatmullRom(); ~Spline_CatmullRom(); bool cutSplineAtIndex(int spline_index); CatmullRomType type_; // a catmull rom spline needs 4 points (pt0, pt1, pt2, pt3) to create a segment from pt1 to pt2. // therefore, naturally the first and last control point are never hit by the spline. // To interpolate all given control points, the first and last control points have to be used twice in calculation of the spline. // // Note: This leads to changes in the last two spline segments when a new control point is appended! bool interpolateControlPointEnds_; // normals std::vector<sf::Vector2f> normals_; bool calcNormals_; bool drawNormals_; // index of the spline point thats marks the start of the most recent spline update int startIndex_lastUpdate_; protected: // Inherited via Spline virtual void onControlPointsAdded(int a_startindex = 0) override; virtual void onDraw(sf::RenderTarget* target) override; sf::Vector2f interpolateUniform(float u, sf::Vector2f pt0, sf::Vector2f pt1, sf::Vector2f pt2, sf::Vector2f pt3); sf::Vector2f interpolate(float u, sf::Vector2f pt0, sf::Vector2f pt1, sf::Vector2f pt2, sf::Vector2f pt3, float* time); sf::Vector2f tangent(float u, sf::Vector2f pt0, sf::Vector2f pt1, sf::Vector2f pt2, sf::Vector2f pt3, float * time); }; } }
true
b039d4b75e2eda7842b85567b61acd898cd8601d
C++
Yunying/Leetcode.cpp
/189_Rotate_Array.cpp
UTF-8
335
2.75
3
[]
no_license
class Solution { public: void rotate(vector<int>& nums, int k) { if (nums.size() == 0 || nums.size() == 1){ return; } k = k%nums.size(); for (int i=0; i<k; i++){ int tmp = nums.back(); nums.pop_back(); nums.insert(nums.begin(),tmp); } } };
true
517da3c9e10757400d23b62625e6907b4939e746
C++
johnvtan/Algorithms
/school/spring-2017/algorithms/project-3/grid.cpp
UTF-8
3,565
3.65625
4
[]
no_license
// Mary Forde // John Tan // Project 3 #include"grid.h" // This file implements the grid class using namespace std; grid::grid(const char* filename) //constructs a grid from the given file { ifstream myFile; myFile.open(filename); if(!myFile.is_open()) { throw fileOpenError(filename); } if(myFile.is_open()) { //get first two integers, which give us the array size int numRows, numCols; myFile >> numRows; myFile >> numCols; wordGrid.resize(numRows, numCols); char c; // iterating through and getting all chars in grid for (int i = 0; i < numRows; i ++) { for (int j = 0; j < numCols; j++) { myFile >> wordGrid[i][j]; } } } myFile.close(); generatePossibleWords(); } // end grid constructor vector<string> grid::getPossibleWords() // returns the possible words vector { return possibleWords; } matrix<char> grid::getWordGrid() // returns word grid matrix { return wordGrid; } void grid::generatePossibleWords() // generates all possible words in the word search grid { int numRows = wordGrid.rows(); int numCols = wordGrid.cols(); for(int i = 0; i < numRows; i++) { for(int j = 0; j < numCols; j++) { possibleWordsAt(i, j); } } } // end generatePossibleWords void grid::possibleWordsAt(int startRow, int startCol) // generates all the possible words to the right of the starting { // add first letter string startLetter = ""; startLetter += wordGrid[startRow][startCol]; possibleWords.push_back(startLetter); // Up generatePossibleWordsIncrementBy(startRow,startCol,1,0); // Down generatePossibleWordsIncrementBy(startRow,startCol,-1,0); // Right generatePossibleWordsIncrementBy(startRow,startCol,0,1); // Left generatePossibleWordsIncrementBy(startRow,startCol,0,-1); // Up Right generatePossibleWordsIncrementBy(startRow,startCol,-1,1); // Down Left generatePossibleWordsIncrementBy(startRow,startCol,1,1); // Down Right generatePossibleWordsIncrementBy(startRow,startCol,1,-1); // Up Left generatePossibleWordsIncrementBy(startRow,startCol,-1,-1); } // end possibleWordsAt void grid::generatePossibleWordsIncrementBy(int startRow, int startCol, int horInc, int vertInc) // Appends all possible strings to the possibleWords vector in grid class, // direction is based on the horizontal increment and vertical increment // arguments { int numRows = wordGrid.rows(); int numCols = wordGrid.cols(); // the starting letter string currWord = ""; currWord += wordGrid[startRow][startCol]; int i = startRow; int j = startCol; while(true) { // update i,j by increments i += vertInc; //rows j += horInc; //cols // bounds checking indexes if over/under if (vertInc > 0 && i >= numRows) { i = 0; } if (vertInc < 0 && i < 0) { i = numRows - 1; } if (horInc > 0 && j >= numCols) { j = 0; } if (horInc < 0 && j < 0) { j = numCols - 1; } if (i == startRow && j == startCol) { break; } // adding char from grid to current word currWord += wordGrid[i][j]; // appending it to vector possibleWords.push_back(currWord); } } // end generatePossibleWordsIncrementBy ostream& operator<<(ostream& ostr, grid& g) // Overloads the << operator { int numRows = g.wordGrid.rows(); int numCols = g.wordGrid.cols(); ostr << numRows << " " << numCols << endl; for (int i = 0; i < numCols; i ++) { for (int j = 0; j < numRows; j++) { ostr << g.wordGrid[i][j] << " "; } ostr << endl; } return ostr; } // end <<
true
b1837506d52855da5d7217de2f4751504f37de5a
C++
MarshallSCPT/aniware-internal
/aw-internal/shared/stack_frame/stack_frame.hpp
UTF-8
767
2.78125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#pragma once struct stack_frame_t { address_t m_fp; address_t m_ret; stack_frame_t( ) = default; stack_frame_t( void* ret ) : m_fp{} { setup( uintptr_t( ret ) ); } stack_frame_t( uintptr_t ret ) : m_fp{} { setup( ret ); } ~stack_frame_t( ) = default; void setup( uintptr_t ret ) { m_fp = address_t( ret - sizeof( uintptr_t ) ); m_ret = address_t( ret ).get( ); } uintptr_t get_frame_pointer( ) { return m_fp; } uintptr_t get_return_address( ) { return m_ret; } void previous( ) { m_fp.self_get( ); } template< typename t = uintptr_t > t get_var( std::ptrdiff_t offset ) { return m_fp.offset( offset ).cast< t >( ); } }; #define INIT_STACKFRAME( ) auto stack_frame = stack_frame_t( uintptr_t( _AddressOfReturnAddress( ) ) );
true
5d75d5a32a5cc3c6abc6b27c7be9ffb213121c0c
C++
rezanour/randomoldstuff
/Main/Shooter1/ContentPipeline/taskmanager.h
UTF-8
1,485
2.65625
3
[]
no_license
#pragma once enum class TaskType { None = 0, Texture, World, }; struct ContentTask { ContentTask(TaskType type, _In_z_ const wchar_t* source, _In_z_ const wchar_t* dest) : Type(type), Source(source), Dest(dest) {} std::wstring Source; std::wstring Dest; TaskType Type; }; struct TextureTask : ContentTask { TextureTask(_In_z_ const wchar_t* source, _In_z_ const wchar_t* dest, bool resize, uint32_t width, uint32_t height, bool generateMips) : ContentTask(TaskType::Texture, source, dest), Resize(resize), Width(width), Height(height), GenerateMips(generateMips) {} bool Resize; uint32_t Width; uint32_t Height; bool GenerateMips; }; struct WorldTask : ContentTask { WorldTask(_In_z_ const wchar_t* source, _In_z_ const wchar_t* dest) : ContentTask(TaskType::World, source, dest) {} }; class TaskManager { public: TaskManager(); void AddTask(_In_ _Post_invalid_ ContentTask* task); void Run(); private: OutputManager* GetOutputManager(); bool EvaluateTask(const std::unique_ptr<ContentTask>& task); void ProcessTask(const std::unique_ptr<ContentTask>& task); void ProcessTask(const TextureTask* task); void ProcessTask(const WorldTask* task); private: std::atomic<bool> _running; CriticalSection _lock; std::unique_ptr<OutputManager> _outputManager; std::vector<std::unique_ptr<ContentTask>> _tasks; };
true
687aa3a598bebd07e32107d68a0edb88cb1c6220
C++
yayankov/Projects
/Object-oriented-programming-Personal-project/OOP_Shop_19-20_fn62357_g1_d4-Final/User.cpp
UTF-8
555
3.1875
3
[]
no_license
#include "User.h" #include <iostream> #include <limits> #include <cstring> using namespace std; #define _CRT_SECURE_NO_WARNINGS User::User() { cart = Cart(); } void User::addToCart(Product* product) { cart.addToCart(product); } void User::removeFromCart() { std::cout << "Enter Product number to remove from cart: "; int pos; while (!(cin >> pos)) { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout << "Invalid input. Try again: "; } cart.removeFromCart(pos); } void User::printCart() const { cart.printCart(); }
true
2ad253a448512138b7b68fd3e2275f053ea326ad
C++
Nonoreve/OpenGLScene
/src/Shader.cpp
UTF-8
4,914
2.8125
3
[]
no_license
#include "Shader.h" #include "rendering/renderer.h" #include <glm/gtc/type_ptr.hpp> #include <cstdarg> Shader::Shader() : m_programID(0), m_vertexID(0), m_fragID(0) { } Shader::~Shader() { glDeleteProgram(m_programID); glDeleteShader(m_vertexID); glDeleteShader(m_fragID); } Shader* Shader::loadFromFiles(FILE* vertexFile, FILE* fragFile, unsigned int count, va_list args) { uint32_t vertexFileSize = 0; uint32_t fragFileSize = 0; char* vertexCodeC; char* fragCodeC; /* Determine the vertex and fragment shader sizes */ fseek(vertexFile, 0, SEEK_END); vertexFileSize = ftell(vertexFile); fseek(vertexFile, 0, SEEK_SET); fseek(fragFile, 0, SEEK_END); fragFileSize = ftell(fragFile); fseek(fragFile, 0, SEEK_SET); /* Read the files */ vertexCodeC = (char*)malloc(vertexFileSize + 1); fragCodeC = (char*)malloc(fragFileSize + 1); fread(vertexCodeC, 1, vertexFileSize, vertexFile); vertexCodeC[vertexFileSize] = '\0'; fread(fragCodeC, 1, fragFileSize, fragFile); fragCodeC[fragFileSize] = '\0'; /* Return the shader and free everything*/ Shader* s = loadFromStrings(std::string(vertexCodeC), std::string(fragCodeC), count, args); va_end(args); free(vertexCodeC); free(fragCodeC); return s; } Shader* Shader::loadFromStrings(const std::string& vertexString, const std::string& fragString, unsigned int count, va_list args) { Shader* shader = new Shader(); /* Create a program and compile each shader component (vertex, fragment) */ shader->m_programID = glCreateProgram(); shader->m_vertexID = loadShader(vertexString, GL_VERTEX_SHADER); shader->m_fragID = loadShader(fragString, GL_FRAGMENT_SHADER); /* Attach the shader components to the program */ glAttachShader(shader->m_programID, shader->m_vertexID); glAttachShader(shader->m_programID, shader->m_fragID); /* Do the attributes binding */ for (unsigned int i = 0; i < count; i++) { const char* name = va_arg(args, const char*); GLCall(glBindAttribLocation(shader->m_programID, i, name)); } va_end(args); /* Link the program. */ glLinkProgram(shader->m_programID); /* Check for errors and print error message */ int linkStatus; glGetProgramiv(shader->m_programID, GL_LINK_STATUS, &linkStatus); if (linkStatus == GL_FALSE) { char* error = (char*) malloc(ERROR_MAX_LENGTH * sizeof(char)); int length = 0; glGetProgramInfoLog(shader->m_programID, ERROR_MAX_LENGTH, &length, error); ERROR("Could not link shader-> : \n %s", error); delete shader; return NULL; } return shader; } int Shader::loadShader(const std::string& code, int type) { /* Create a shader component and compile it */ int shader = glCreateShader(type); const GLchar* s = code.c_str(); glShaderSource(shader, 1, &s, 0); glCompileShader(shader); /* Check for errors and print error message */ int compiled = 0; glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled); if (compiled == GL_FALSE) { char* error = (char*) malloc(ERROR_MAX_LENGTH * sizeof(char)); int length = 0; glGetShaderInfoLog(shader, ERROR_MAX_LENGTH, &length, error); ERROR("Could not compile shader %d : \n %s", type, error); glDeleteShader(shader); return 0; } return shader; } int Shader::getProgramID() const { return m_programID; } int Shader::getVertexID() const { return m_vertexID; } int Shader::getFragID() const { return m_fragID; } void Shader::Bind() const { GLCall(glUseProgram(m_programID)); } void Shader::Unbind() const { GLCall(glUseProgram(0)); } int Shader::GetUniformLocation(const std::string& name) { if (m_UniformLocationCache.find(name) != m_UniformLocationCache.end()) return m_UniformLocationCache[name]; GLCall(int location = glGetUniformLocation(m_programID, name.c_str())); if (location == -1) std::cout << "[OpenGL Warning] uniform '" << name << "' doesn't exist." << std::endl; m_UniformLocationCache[name] = location; return location; } void Shader::SetUniform1i(const std::string& name, int value) { GLCall(glUniform1i(GetUniformLocation(name), value)); } void Shader::SetUniform1f(const std::string& name, float value) { GLCall(glUniform1f(GetUniformLocation(name), value)); } void Shader::SetUniform3f(const std::string& name, float v0, float v1, float v2) { GLCall(glUniform3f(GetUniformLocation(name), v0, v1, v2)); } void Shader::SetUniform4f(const std::string& name, float v0, float v1, float v2, float v3) { GLCall(glUniform4f(GetUniformLocation(name), v0, v1, v2, v3)); } void Shader::SetUniformVec3f(const std::string& name, glm::vec3 vector) { GLCall(glUniform3fv(GetUniformLocation(name), 1, glm::value_ptr(vector))); } void Shader::SetUniformVec4f(const std::string& name, glm::vec4 vector) { GLCall(glUniform4fv(GetUniformLocation(name), 1, glm::value_ptr(vector))); } void Shader::SetUniformMat4f(const std::string& name, const glm::mat4& matrix){ GLCall(glUniformMatrix4fv(GetUniformLocation(name), 1, GL_FALSE, glm::value_ptr(matrix))); }
true
f658a36fa855cc32c168c2463edc788f76e280bf
C++
Krentin018/Tut2-Fraction
/Fractions.h
UTF-8
361
2.515625
3
[]
no_license
#pragma once class Fractions { public: int numer; int denom; int num; Fractions(); ~Fractions(); void setNumer(int); void setDenom(int); Fractions Fractions::add(Fractions &a); Fractions Fractions::subtract(Fractions &a); Fractions Fractions::multiply(Fractions &a); Fractions Fractions::divide(Fractions &a); void mixed(); void print(); };
true
26ef91562d167dd595d2febc4abd0745acfc6c06
C++
rkalyankumar/bplustree
/bplustree.cpp
UTF-8
18,139
2.546875
3
[ "Apache-2.0" ]
permissive
/** * Copyright 2014-15 Kalyankumar Ramaseshan * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <iostream> #include <cstdlib> #include <cstring> #include <cerrno> #include <cwchar> #include <cassert> #include <cstdio> #include <stdarg.h> #include <cctype> #include <limits> #include <algorithm> using std::max; #define UNUSED __attribute__((unused)) #define BPLUSTREE_VERSION 0.1 static void print_license(); static void DBUG(const char *fmt,...); // May compile & run on BSD, MacOSX, Solaris & AIX. // But restricting implementation to linux as // it's the only os platform that this code has // been developed & thoroughly tested. Any one // that is interested in running this code in OS // other than linux should comment below macros. // At your own risk beware! #if !defined(__linux) || !defined(__linux__) #error "Operating system not supported currently" #endif #include <unistd.h> #include <getopt.h> // parsing command line arguments using std::cout; using std::cin; using std::endl; const int DEFAULT_ORDER = 4; // A KEY Comparator abstraction. This is really very // useful when there are keys of type char */wchar_t * // that uses strncmp/wcsncmp respectively as comparision // functions instead of native operators. It also helps // to define a custom comparator API for completely different // types of keys. This abstraction avoids to provide complete // rewrite of Bplustree class specializations for special // types of keys such as char */wchar_t* or any other user // defined type that compares the keys in ways not using the // native comparision operators! template <typename KEY> class Comparator { public: Comparator() { } virtual int compare(const KEY &_k1,const KEY &_k2) const { if (_k1 > _k2) return 1; else if (_k1 < _k2) return -1; return 0; } virtual ~Comparator() { } }; // char* Comparator specialization template <> class Comparator<char *> { public: Comparator() { } virtual int compare(const char *const &_k1,const char *const &_k2) const { size_t k1_len = strlen(_k1); int cmp = strncmp(_k1,_k2,k1_len); if (cmp > 0) return 1; else if (cmp < 0) return -1; return 0; } virtual ~Comparator() { } }; // wchar_t* Comparator specialization template <> class Comparator<wchar_t *> { public: Comparator() { } virtual int compare(const wchar_t *const &_k1,const wchar_t *const &_k2) const { size_t k1_len = wcslen(_k1); int cmp = wcsncmp(_k1,_k2,k1_len); if (cmp > 0) return 1; else if (cmp < 0) return -1; return 0; } virtual ~Comparator() { } }; // following template specializations will result in // compilation errors! template <> class Comparator<void>; template <> class Comparator<void*>; // A simple in-memory B+Tree data structure. // TODO: // [1] mmap() + file (FD) based implementation for persistence // [2] concurrent & thread-safe index operations template <typename KEY,typename VALUE> class Bplustree { class BplustreeNode; class Stack; public: explicit Bplustree(int _order = DEFAULT_ORDER) : order(_order),root(0),key_compare() { } inline void insert(const KEY &_key,const VALUE &_value) { insert(root,_key,_value); } inline bool find(const KEY &_key,VALUE &_value) { return find(root,_key,_value); } inline bool is_empty() const { return root == 0; } inline void destroy() { destroy(root); } ~Bplustree() { destroy(); } inline void print(std::ostream &out = std::cout) { print_node(root,out); } private: inline void print_node(BplustreeNode *node, std::ostream &out) { if (node == 0) return; if (node->is_leaf()) cout << "L: "; else cout << "I: " ; for (int i = 0 ;i < node->num_keys; i++) { cout << "| " << node->keys[i] << " | "; } cout << endl; if (!node->is_leaf()) { for (int i = 0; i <= node->num_keys; i++) { print_node(node->ptrs[i],out); } } } // destroys the tree in top-down fashion recursively inline void destroy(BplustreeNode *_node) { if (_node == 0) return; if (!_node->is_leaf()) { for (int i = 0; i <= _node->num_keys; i++) { destroy(_node->ptrs[i]); } } delete _node; _node = 0; } // insert helper function void insert(BplustreeNode *_node,const KEY &_key,const VALUE &_value) { if (_node == 0 && is_empty()) { root = new BplustreeNode(order,true); root->insert(_key,_value); } else { Stack parent_nodes; KEY median; BplustreeNode *leaf_node = find_leaf(root,_key,parent_nodes); assert(leaf_node != 0); // fail if leaf node can't be located assert(leaf_node->is_leaf()); // fail if it's not a leaf node if (!leaf_node->insert(_key,_value)) { // split leaf_node BplustreeNode *new_leaf = leaf_node->split(_key,_value,median); // move up the median key BplustreeNode *parent = parent_nodes.pop(); insert_to_parent(parent,median,leaf_node,new_leaf,parent_nodes); } } } /* recursively pushes up the _key to the parent node. it can move all the way up to the root node. if root node is too full it creates a new root. if a new root is created the tree's height increases by 1 from current height. The recursion stops when one of the following happens: [1] A new root is created and the median keys is pushed there [2] If the _parent is not full & the _key & ptrs are inserted there */ void insert_to_parent(BplustreeNode *_parent,const KEY &_key,BplustreeNode *_left, BplustreeNode *_right,Stack &_parents) { if (_parent == 0) { /* A new root node is created */ BplustreeNode *new_root = new BplustreeNode(order,false); new_root->keys[0] = _key; new_root->ptrs[0] = _left; new_root->ptrs[1] = _right; ++new_root->num_keys; root = new_root; /* recursion stops here */ } else { if (!_parent->is_full()) { _parent->insert(_key,_right); /* recursion stops here */ } else { KEY median; BplustreeNode *new_parent_level_node = _parent->split(_key,_left,_right,median); /* recursively push the median key up to the parent */ BplustreeNode *parent = _parents.pop(); insert_to_parent(parent,median,_parent,new_parent_level_node,_parents); } } } // find helper function bool find(BplustreeNode *_node,const KEY &_key,VALUE &_value) { bool found = false; BplustreeNode *node = _node; if (node == 0) return found; int i = 0,cmp = 0; while (!node->is_leaf()) { i = 0; while (i < node->num_keys) { cmp = key_compare.compare(_key,node->keys[i]); if (cmp >= 0) i++; else break; } node = node->ptrs[i]; } assert(node->is_leaf()); for (i = 0;i < node->num_keys; i++) { if (key_compare.compare(_key,node->keys[i]) == 0) { found = true; _value = node->values[i]; break; } } return found; } // find leaf function - used for insert/delete key-value functions BplustreeNode *find_leaf(BplustreeNode *_node,const KEY &_key,Stack &parent_nodes) { BplustreeNode *node = _node; int i = 0; if (node == 0) return 0; if (!node->is_leaf()) { parent_nodes.push(node); } while (node != 0 && !node->is_leaf()) { i = 0; while (i < node->num_keys) { if (key_compare.compare(_key,node->keys[i]) == 1) i++; else break; } node = node->ptrs[i]; if (node != 0 && !node->is_leaf()) { parent_nodes.push(node); } } return node; } class BplustreeNode { friend class Stack; friend class Bplustree<KEY,VALUE>; private: const int max_children; bool leaf; int num_keys; KEY *keys; VALUE *values; BplustreeNode **ptrs; /*>! ptrs- stores max_children nodes if index *>! ptrs- stores 2-nodes(prev & next) if leaf */ Comparator<KEY> key_compare; public: explicit BplustreeNode( int _max_children,bool _leaf = false) : max_children(_max_children),leaf(_leaf), num_keys(0),keys(0),values(0),ptrs(0),key_compare() { init(); } inline bool is_leaf() const { return leaf; } inline BplustreeNode *prev() { if (!leaf) return 0; return ptrs[0]; } inline BplustreeNode *next() { if (!leaf) return 0; return ptrs[1]; } inline void set_next(BplustreeNode *_node) { if (leaf) { ptrs[1] = _node; } } inline void set_prev(BplustreeNode *_node) { if (leaf) { ptrs[0] = _node; } } /* inserts _key & _value to the leaf node. insertion will be based on _key's ascending order. Aborts if the node is not leaf. returns true if insertion is successful. returns false if the node is full. */ bool insert(const KEY &_key,const VALUE &_value) { assert(leaf); // fail if it's index if (is_full()) { return false; // no space left in node } int slot = find_slot(_key); for (int i = num_keys; i > slot; i--) { keys[i] = keys[i - 1]; values[i] = values[i - 1]; } keys[slot] = _key; values[slot] = _value; incr(); return true; } /* inserts _key & _node to the index node. insertion will be based on _key's ascending order. _node being the right child of the _key. Aborts if the node is not index. returns true if insertion is successful. returns false if the node is full; */ bool insert(const KEY &_key,BplustreeNode *_node) { assert(!leaf); // fail if it's leaf if (is_full()) { return false; // no space left in node } int slot = find_slot(_key); for (int i = num_keys; i > slot; i--) { keys[i] = keys[i - 1]; ptrs[i + 1] = ptrs[i]; } ptrs[slot + 1] = _node; keys[slot] = _key; incr(); return true; } inline int find_slot(const KEY &_key) { //TODO: check for num_keys/max_children // & do a binary search in case of 50(?) // or more keys. return sequential_search(_key); } /* split a full leaf node to two leaf nodes keeps first half of max_children/2 in the current (this) node moves second half of max_children/2 to the new leaf node copies the median key that needs to be pushed up to the parent node parent node is essentially an index node returns the new leaf node created during the split operation */ BplustreeNode *split(const KEY &_key,const VALUE &_value,KEY &_median) { assert(is_leaf()); // fail if it's not a leaf BplustreeNode *new_leaf = 0; KEY l_keys[max_children]; VALUE l_values[max_children]; int slot = find_slot(_key); int i = 0,j = 0; for (i = 0,j = 0; i < num_keys; i++,j++) { if (j == slot) j++; l_keys[j] = keys[i]; l_values[j] = values[i]; } l_keys[slot] = _key; l_values[slot] = _value; new_leaf = new BplustreeNode(max_children,true); int split_pos = 0; int cut_order = max_children - 1; if (cut_order % 2 == 0) split_pos = cut_order/2; else split_pos = (cut_order/2) + 1; /* fix [0,max_children/2) entries to the current full node */ num_keys = 0; for (i = 0; i < split_pos; i++) { keys[i] = l_keys[i]; values[i] = l_values[i]; ++num_keys; } /* move [max_children/2,max_children) entries to new leaf node */ for (i = split_pos,j = 0; i < max_children; i++,j++) { new_leaf->keys[j] = l_keys[i]; new_leaf->values[j] = l_values[i]; ++new_leaf->num_keys; } /* fix prev, next pointers */ new_leaf->set_next(next()); set_next(new_leaf); new_leaf->set_prev(this); /* copy the median key that needs to be inserted upto the parent */ _median = new_leaf->keys[0]; return new_leaf; } /* splits a full index node to two index nodes keeps first half of max_children/2 keys & ptrs in current (this) index node moves second half of max_children/2 keys & ptrs to new_index node copies median key that needs to be pushed up to the parent node parent node is essentially an index node returns the new index node created by the split operation */ BplustreeNode *split(const KEY &_key,BplustreeNode *_left UNUSED, BplustreeNode *_right,KEY &_median) { assert(!is_leaf()); // fail if it's not an index BplustreeNode *new_index = new BplustreeNode(max_children,false); KEY l_keys[max_children]; BplustreeNode *l_ptrs[max_children + 1]; int i =0, j = 0,split_pos = 0; if (max_children % 2 == 0) split_pos = max_children/2; else split_pos = (max_children/2) + 1; int slot = find_slot(_key); for (i = 0,j = 0; i < max_children; i++,j++) { if (j == slot) j++; l_keys[j] = keys[i]; } for (i = 0,j = 0; i < max_children + 1; i++,j++) { if (j == slot + 1) j++; l_ptrs[j] = ptrs[i]; } l_ptrs[slot + 1] = _right; l_keys[slot] = _key; num_keys = 0; for (i = 0; i < split_pos - 1; i++) { keys[i] = l_keys[i]; ptrs[i] = l_ptrs[i]; ++num_keys; } ptrs[i] = l_ptrs[i]; _median = l_keys[split_pos - 1]; for (++i,j = 0; i < max_children; i++,j++) { new_index->ptrs[j] = l_ptrs[i]; new_index->keys[j] = l_keys[i]; ++new_index->num_keys; } new_index->ptrs[j] = l_ptrs[i]; return new_index; } inline bool is_full() const { return num_keys == max_children - 1; } /* deallocates all the memory. called by destructor. can be called explicitly as well. */ void destroy() { if (keys != 0) delete [] keys; if (leaf && values != 0) delete [] values; if (ptrs != 0) delete [] ptrs; num_keys = -1; leaf = false; } ~BplustreeNode() { destroy(); } private: int sequential_search(const KEY &_key,UNUSED bool match_exact = false) { int slot = 0; while (slot < num_keys && key_compare.compare(_key,keys[slot]) == 1) slot++; return slot; } int binary_search(const KEY &_key,bool match_exact = false) { //TODO: Implement binary search return -1; } // constructor helper function void init() { num_keys = 0; keys = new KEY[max_children - 1]; if (leaf) { values = new VALUE[max_children - 1]; ptrs = new BplustreeNode*[2]; } else { values = 0; ptrs = new BplustreeNode*[max_children]; } } inline void incr() { ++num_keys; } inline void decr() { --num_keys; } // copy/assign disallowed BplustreeNode(const BplustreeNode &); const BplustreeNode &operator = (const BplustreeNode &); }; const int order; BplustreeNode *root; Comparator<KEY> key_compare; /* A Stack (LIFO Data Structure) is used to store parent nodes when searching for a leaf node to insert a key in the find_leaf() method of Bplustree.This is important when a leaf node is split and the median key needs to be pushed to parent & in case the parent is too full & needs split etc., which goes up till the root node which happens to be full a new root node will be created to accomodate the split triggered from the leaf node. Pop-ing from the stack returns the immediate parent of the node in question & the pop operation bottoms up to root whose parent is null. Another way to do these things is to keep a parent pointer in the BplustreeNode & keep the parent pointer reference updated when ever the node split happens. I find using stack is easy & quiet straight forward process to implement the insert/split operation easily. */ class Stack { private: struct Node { BplustreeNode *data; Node *next; }; Node *head; public: Stack() : head(0) { } inline void push(BplustreeNode *data) { Node *node = new Node(); node->data = data; if (head == 0) { head = node; } else { node->next = head; head = node; } } inline BplustreeNode *pop() { if (head == 0) return 0; Node *tmp_node = head->next; BplustreeNode *data = head->data; delete head; head = tmp_node; return data; } ~Stack() { while (head != 0) pop(); } private: // copy/assign disallowed Stack(const Stack &); const Stack &operator = (const Stack &); }; // copy/assign disallowed Bplustree(const Bplustree<KEY,VALUE> &); const Bplustree<KEY,VALUE> &operator = (const Bplustree<KEY,VALUE> &); }; // following template instantiations would result in compilation error! template<> class Bplustree<void ,void >; template<typename KEY> class Bplustree<KEY,void >; template<typename VALUE> class Bplustree<void ,VALUE>; template<> class Bplustree<void *,void *>; template<typename KEY> class Bplustree<KEY,void *>; template<typename VALUE> class Bplustree<void *,VALUE>; bool dbug = false; bool quiet = false; int order = DEFAULT_ORDER; static void handle_options(int argc,char **argv); // handles the command line arguments passed static void handle_options(int argc,char **argv) { int oc = -1,d = -1; while ((oc = getopt(argc,argv,":qo:d:")) != -1) { switch (oc) { case 'q': quiet = true; break; case 'o' : order = atoi(optarg); if (order < DEFAULT_ORDER) order = DEFAULT_ORDER; break; case 'd' : d = atoi(optarg); if (d == 1) dbug = true; break; case ':' : std::cerr << argv[0] << " option -'" << char(optopt) << "' requires an argument" << endl; break; case '?': default: break; }; } } static void print_license() { if (!quiet) { cout << "BPLUSTREE " << BPLUSTREE_VERSION << endl << "Unless & otherwise stated all" << " this code is licensed under Apache2.0" << " license."<< endl << "Copyright (c) 2014 - 15." << endl << "Author: Kalyankumar Ramaseshan" << endl << "email: rkalyankumar@gmail.com" << endl << endl; } } static void DBUG(const char *fmt,...) { if (dbug) { va_list args; va_start(args,fmt); vfprintf(stdout,fmt,args); va_end(args); fprintf(stdout,"\n"); } } int main(int argc,char **argv) { handle_options(argc,argv); print_license(); DBUG("%s","Test"); Bplustree<int,int> tree(order); tree.insert(1,1); tree.insert(12,12); tree.insert(10,10); tree.insert(14,14); tree.insert(11,11); tree.insert(15,15); tree.insert(13,13); tree.insert(2,2); tree.insert(5,5); tree.insert(3,3); tree.insert(4,4); tree.insert(9,9); tree.insert(16,16); tree.insert(18,18); tree.insert(6,6); tree.insert(7,7); tree.insert(8,8); tree.insert(17,17); tree.print(); return 0; }
true
1ad6c1fc7cf4bf0e70ab4141e6130bd6ceb661f4
C++
chris3will/Learn_the_data_structure_in_a_stupid_way
/软件包/软件包/hash_table.h
GB18030
6,059
3.828125
4
[]
no_license
#ifndef __HASH_TABLE_H__ #define __HASH_TABLE_H__ // ɢбģ template <class ElemType, class KeyType> class HashTable { protected: // ɢбĵݳԱ: ElemType *ht; // ɢб bool *empty; // Ԫ int m; // ɢб int p; // ij // ģ: int H(KeyType key) const; // ɢкģ int Collision(KeyType key, int i) const; // ͻĺģ bool SearchHelp(const KeyType &key, int &pos) const; // ѰؼΪkeyԪصλ public: // رϵͳĬϷ: HashTable(int size, int divisor); // 캯ģ ~HashTable(); // 캯ģ void Traverse(void (*visit)(const ElemType &)) const; // ɢб bool Search(const KeyType &key, ElemType &e) const ; // ѰؼΪkeyԪصֵ bool Insert(const ElemType &e); // Ԫe bool Delete(const KeyType &key); // ɾؼΪkeyԪ HashTable(const HashTable<ElemType, KeyType> &copy); // ƹ캯ģ HashTable<ElemType, KeyType> &operator= (const HashTable<ElemType, KeyType> &copy); // ظֵ }; // ɢбģʵֲ template <class ElemType, class KeyType> int HashTable<ElemType, KeyType>::H(KeyType key) const //: ɢеַ { return key % p; } template <class ElemType, class KeyType> int HashTable<ElemType, KeyType>::Collision(KeyType key, int i) const //: صiγͻַ̽ { return (H(key) + i) % m; } template <class ElemType, class KeyType> HashTable<ElemType, KeyType>::HashTable(int size, int divisor) // : sizeΪɢб, divisorΪijһյɢ { m = size; // ֵɢб p = divisor; // ֵ ht = new ElemType[m]; // 洢ռ empty = new bool[m]; // 洢ռ for (int pos = 0; pos < m; pos++) { // Ԫÿ empty[pos] = true; } } template <class ElemType, class KeyType> HashTable<ElemType, KeyType>::~HashTable() // : ɢб { delete []ht; // ͷht delete []empty; // ͷempty } template <class ElemType, class KeyType> void HashTable<ElemType, KeyType>::Traverse(void (*visit)(const ElemType &)) const // : ζɢбÿԪصú(*visit) { for (int pos = 0; pos < m; pos++) { // ɢбÿԪصú(*visit) if (!empty[pos]) { // Ԫطǿ (*visit)(ht[pos]); } } } template <class ElemType, class KeyType> bool HashTable<ElemType, KeyType>::SearchHelp(const KeyType &key, int &pos) const // : ѰؼΪkeyԪصλ,ҳɹ,true,posָʾ // Ԫɢбλ,򷵻false { int c = 0; // ͻ pos = H(key); // ɢбַ while (c < m && // ͻӦСm !empty[pos] && // Ԫht[pos]ǿ ht[pos] != key) // ؼֵ { pos = Collision(key, ++c); //һַ̽ } if (c >= m || empty[pos]) { // ʧ return false; } else { // ҳɹ return true; } } template <class ElemType, class KeyType> bool HashTable<ElemType, KeyType>::Search(const KeyType &key, ElemType &e) const // : ѰؼΪkeyԪصֵ,ҳɹ,true,eԪصֵ, // 򷵻false { int pos; // Ԫصλ if (SearchHelp(key, pos)) { // ҳɹ e = ht[pos]; // eԪֵ return true; // true } else { // ʧ return false; // false } } template <class ElemType, class KeyType> bool HashTable<ElemType, KeyType>::Insert(const ElemType &e) // : ɢбвԪe,ɹtrue,򷵻false { int pos; // λ if (!SearchHelp(e, pos) && empty[pos]) { // ɹ ht[pos] = e; // Ԫ empty[pos] = false; // ʾǿ return true; } else { // ʧ return false; } } template <class ElemType, class KeyType> bool HashTable<ElemType, KeyType>::Delete(const KeyType &key) // : ɾؼΪkeyԪ,ɾɹtrue,򷵻false { int pos; // Ԫλ if (SearchHelp(key, pos)) { // ɾɹ empty[pos] = true; // ʾԪΪ return true; } else { // ɾʧ return false; } } template <class ElemType, class KeyType> HashTable<ElemType, KeyType>::HashTable(const HashTable<ElemType, KeyType> &copy) // ɢбcopyɢбƹ캯ģ { m = copy.m; // ɢб p = copy.p; // ij ht = new ElemType[m]; // 洢ռ empty = new bool[m]; // 洢ռ for (int curPosition = 0; curPosition < m; curPosition++) { // Ԫ ht[curPosition] = copy.ht[curPosition]; // Ԫ empty[curPosition] = copy.empty[curPosition];// ԪǷΪֵ } } template <class ElemType, class KeyType> HashTable<ElemType, KeyType> &HashTable<ElemType, KeyType>:: operator=(const HashTable<ElemType, KeyType> &copy) // ɢбcopyֵǰɢбظֵ { if (&copy != this) { delete []ht; // ͷŵǰɢб洢ռ m = copy.m; // ɢб p = copy.p; // ij ht = new ElemType[m]; // 洢ռ empty = new bool[m]; // 洢ռ for (int curPosition = 0; curPosition < m; curPosition++) { // Ԫ ht[curPosition] = copy.ht[curPosition]; // Ԫ empty[curPosition] = copy.empty[curPosition];// ԪǷΪֵ } } return *this; } #endif
true
04d11dfd09c19c99dc9f4c2518a9c0653ed3cf50
C++
aniketnk/scapegoatTree
/include/iterators.hpp
UTF-8
2,970
3.1875
3
[]
no_license
#pragma once #include "scapeGoatTree.hpp" template <class T> class scapeGoatTree<T>::Iterator { private: Node<T> *node_it_, *root; public: using iterator_category = bidirectional_iterator_tag; using value_type = T; using difference_type = int; using pointer = T *; using reference = T &; explicit Iterator(Node<T> *node_it = nullptr, Node<T> *root = nullptr) : node_it_(node_it), root(root) {} bool operator==(const Iterator &rhs) const { return node_it_ == rhs.node_it_; } bool operator!=(const Iterator &rhs) const { return !(*this == rhs); } reference operator*() { return node_it_->value_; } Iterator &operator++(); Iterator operator++(int); Iterator &operator--(); Iterator operator--(int); }; template <class T> class scapeGoatTree<T>::revIterator { private: Node<T> *node_it_, *root; public: using iterator_category = bidirectional_iterator_tag; using value_type = T; using difference_type = int; using pointer = T *; using reference = T &; explicit revIterator(Node<T> *node_it = nullptr, Node<T> *root = nullptr) : node_it_(node_it), root(root) {} bool operator==(const revIterator &rhs) const { return node_it_ == rhs.node_it_; } bool operator!=(const revIterator &rhs) const { return !(*this == rhs); } reference operator*() { return node_it_->value_; } revIterator &operator++(); revIterator operator++(int); revIterator &operator--(); revIterator operator--(int); }; template <typename T> typename scapeGoatTree<T>::Iterator &scapeGoatTree<T>::Iterator::operator++() { node_it_ = scapeGoatTree<T>::inorder_successor(node_it_, root); return *this; } template <typename T> typename scapeGoatTree<T>::Iterator scapeGoatTree<T>::Iterator::operator++(int) { Iterator temp(*this); ++(*this); return temp; } template <typename T> typename scapeGoatTree<T>::Iterator &scapeGoatTree<T>::Iterator::operator--() { if (node_it_ == nullptr) node_it_ = scapeGoatTree<T>::maxValue(root); else node_it_ = scapeGoatTree<T>::inorder_predecessor(node_it_, root); return *this; } template <typename T> typename scapeGoatTree<T>::Iterator scapeGoatTree<T>::Iterator::operator--(int) { Iterator temp(*this); --(*this); return temp; } template <typename T> typename scapeGoatTree<T>::revIterator &scapeGoatTree<T>::revIterator::operator++() { node_it_ = scapeGoatTree<T>::inorder_predecessor(node_it_, root); return *this; } template <typename T> typename scapeGoatTree<T>::revIterator scapeGoatTree<T>::revIterator::operator++(int) { revIterator temp(*this); ++(*this); return temp; } template <typename T> typename scapeGoatTree<T>::revIterator &scapeGoatTree<T>::revIterator::operator--() { if (node_it_ == nullptr) node_it_ = scapeGoatTree<T>::minValue(root); else node_it_ = scapeGoatTree<T>::inorder_successor(node_it_, root); return *this; } template <typename T> typename scapeGoatTree<T>::revIterator scapeGoatTree<T>::revIterator::operator--(int) { revIterator temp(*this); --(*this); return temp; }
true
086137b2d8bc680484b3ddf7bcefd618cb17b6b1
C++
Borwe/PlayListPlayer
/handlers/handlers.h
UTF-8
2,707
3.296875
3
[]
no_license
#ifndef HANDLERS_H #define HANDLERS_H #include <iostream> #include <vector> #include <string> #include <boost/filesystem.hpp> #include <map> #include <memory> #include <cassert> #include <algorithm> namespace Handlers { using FilePath=boost::filesystem::path; using FilesVector=std::vector<boost::filesystem::path>; using SharedFilesVector=std::shared_ptr<FilesVector>; namespace { void recursiveGetFiles(const FilePath pf,SharedFilesVector fileHolder){ try { auto di=boost::filesystem::directory_iterator(pf); for(boost::filesystem::directory_entry &dir:di){ if(boost::filesystem::is_directory(dir.path()) && dir.path().string()!="./.." && dir.path().string()!="./."){ recursiveGetFiles(dir.path(),fileHolder); } if(boost::filesystem::is_regular_file(dir.path())){ fileHolder->push_back(dir.path()); } } } catch (std::exception &ex) { std::cerr<<"ERROR: "<<ex.what()<<"\n"; } } } SharedFilesVector getFilesInDir(const std::string &directory="./"); /** * @brief The PlayerHandler class * handles the creation and management of playlists. * - Playlists can be added based on directory that contains videos. * - TYpes to be considered as videos can also be added to the Player Handler * - Once a previous directory siezes to exist it should be removed from the Player Handler * - Player Handler stores all playlist directories added that contain atleast one video * - If in the process of adding a playlist, no video type is detected, consider adding a video type, * to PlayerHandler else, the directory will be ignored and not considered as a directory * containing any playlist. * - All the data is stored in data.db file where the executable is located */ class PlayerHandler{ private: std::vector<std::string> videoTypes; /** * @brief files * Used for storing files in a path inside a map. */ std::map<FilePath,FilesVector> files; void updateDirs(); public: PlayerHandler(); /** * @brief getSupportedVideoTypes * @return */ const std::vector<std::string> getSupportedVideoTypes()const{ return videoTypes; } /** * @brief addVideoType * @param type */ void addVideoType(const std::string &type){ videoTypes.push_back(type); } }; } #endif // HANDLERS_H
true
847e955d2b50729cb8b5fd1c9f736932997301e0
C++
hushhw/LQOJ
/BASIC/BASIC-25 回形取数.cpp
GB18030
1,316
3.546875
4
[]
no_license
/* ȡؾıȡǰȡѾȡת90ȡһʼλھϽǣ¡ ʽ һ200m, nʾкСmÿnʾ ʽ ֻһУmnΪȡõĽ֮һոָĩҪжĿո 3 3 1 2 3 4 5 6 7 8 9 1 4 7 8 9 6 3 2 5 3 2 1 2 3 4 5 6 1 3 5 6 4 2 */ #include <iostream> #include <string> using namespace std; int main(){ int m,n; cin>>m>>n; int a[201][201]; for(int i=0; i<m; i++){ for(int j=0; j<n; j++){ cin>>a[i][j]; } } int k=0, total=0; while(total<m*n){ for(int i=k; i<m-k&&total<=m*n; i++){ if(i==0 && k==0) cout<<a[i][k]; else cout<<" "<<a[i][k]; total++; } for(int i=k+1; i<n-k&&total<=m*n; i++){ cout<<" "<<a[m-k-1][i]; total++; } for(int i=m-k-2; i>=k&&total<=m*n; i--){ cout<<" "<<a[i][n-k-1]; total++; } for(int i=n-k-2; i>=k+1&&total<=m*n; i--){ cout<<" "<<a[k][i]; total++; } k++; } cout<<endl; system("pause"); return 0; }
true
bd18fdc1a969b83e26696be3c01df9f67d154aac
C++
Dakosia/Cpp
/Homework/OOP hw/InvoiceItem.h
UTF-8
421
2.765625
3
[]
no_license
#pragma once #include <string> #include <iostream> class InvoiceItem { private: std::string id; std::string desc; int qty; double unitPrice; public: InvoiceItem(); InvoiceItem(std::string, std::string, int, double); ~InvoiceItem(); std::string getID(); std::string getDesc(); int getQty(); void setQty(int); double getUnitPrice(); void setUnitPrice(double); double getTotal(); std::string toString(); };
true
604de7c1fcd87bd9ed5de0076e28e749878a5820
C++
ksuzu46/atcoder
/abc148/c.cpp
UTF-8
279
2.59375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; using ll = long long; ll gcd(ll a, ll b) { if(a % b == 0) return b; return gcd(b, a % b); } int main() { ll a, b; cin >> a >> b; ll res = (a * b) / gcd(a, b); cout << res << "\n"; return 0; }
true
765512d78f468332a753e1e40a2b85738c0aa65a
C++
Ivanmartinezperez/nestmc-proto
/src/fvm_cell.hpp
UTF-8
22,402
2.5625
3
[ "BSD-3-Clause" ]
permissive
#pragma once #include <algorithm> #include <iterator> #include <map> #include <set> #include <string> #include <vector> #include <algorithms.hpp> #include <cell.hpp> #include <event_queue.hpp> #include <ion.hpp> #include <math.hpp> #include <matrix.hpp> #include <mechanism.hpp> #include <mechanism_catalogue.hpp> #include <profiling/profiler.hpp> #include <segment.hpp> #include <stimulus.hpp> #include <util.hpp> #include <util/meta.hpp> #include <vector/include/Vector.hpp> /* * Lowered cell implementation based on finite volume method. * * TODO: Move following description of internal API * to a better location or document. * * Lowered cells are managed by the `cell_group` class. * A `cell_group` manages one lowered cell instance, which * may in turn simulate one or more cells. * * The outward facing interface for `cell_group` is defined * in terms of cell gids and member indices; the interface * between `cell_group` and a lowered cell is described below. * * The motivation for the following interface is to * 1. Provide more flexibility in lowered cell implementation * 2. Save memory and duplicated index maps by associating * externally visible objects with opaque handles. * * In the following, `lowered_cell` represents the lowered * cell class, and `lowered` an instance thereof. * * `lowered_cell::detector_handle` * Type of handles used by spike detectors to query * membrane voltage. * * `lowered_cell::probe_handle` * Type of handle used to query the value of a probe. * * `lowered_cell::target_handle` * Type of handle used to identify the target of a * postsynaptic spike event. * * `lowered_cell::value_type` * Floating point type used for internal states * and simulation time. * * `lowered_cell()` * Default constructor; performs no cell-specific * initialization. * * `lowered.initialize(const Cells& cells, ...)` * Allocate and initalize data structures to simulate * the cells described in the collection `cells`, * where each item is of type `nest::mc::cell`. * * Remaining arguments consist of references to * collections for storing: * 1. Detector handles * 2. Target handles * 3. Probe handles * * Handles are written in the same order as they * appear in the provided cell descriptions. * * `lowered.reset()` * * Resets state to initial conditiions and sets * internal simulation time to 0. * * `lowered.advance(value_type dt)` * * Advanece simulation state by `dt` (value in * milliseconds). For `fvm_cell` at least, * this corresponds to one integration step. * * `lowered.deliver_event(target_handle target, value_type weight)` * * Update target-specifc state based on the arrival * of a postsynaptic spike event with given weight. * * `lowered.detect_voltage(detector_handle)` * * Return membrane voltage at detector site as specified * by handle. * * `lowered.probe(probe_handle)` * * Return value of corresponding probe. * * `lowered.resting_potential(value_type potential)` * * Set the steady-state membrane voltage used for the * cell initial condition. (Defaults to -65 mV currently.) */ namespace nest { namespace mc { namespace fvm { template <typename Value, typename Index> class fvm_cell { public: fvm_cell() = default; /// the real number type using value_type = Value; /// the integral index type using size_type = Index; /// the container used for indexes using index_type = memory::HostVector<size_type>; /// the container used for values using vector_type = memory::HostVector<value_type>; /// API for cell_group (see above): using detector_handle = size_type; using target_handle = std::pair<size_type, size_type>; using probe_handle = std::pair<const vector_type fvm_cell::*, size_type>; void resting_potential(value_type potential_mV) { resting_potential_ = potential_mV; } template <typename Cells, typename Detectors, typename Targets, typename Probes> void initialize( const Cells& cells, // collection of nest::mc::cell descriptions Detectors& detector_handles, // (write) where to store detector handles Targets& target_handles, // (write) where to store target handles Probes& probe_handles); // (write) where to store probe handles void reset(); void deliver_event(target_handle h, value_type weight) { mechanisms_[synapse_base_+h.first]->net_receive(h.second, weight); } value_type detector_voltage(detector_handle h) const { return voltage_[h]; // detector_handle is just the compartment index } value_type probe(probe_handle h) const { return (this->*h.first)[h.second]; } void advance(value_type dt); /// Following types and methods are public only for testing: /// the type used to store matrix information using matrix_type = matrix<value_type, size_type>; /// mechanism type using mechanism_type = nest::mc::mechanisms::mechanism_ptr<value_type, size_type>; /// ion species storage using ion_type = mechanisms::ion<value_type, size_type>; /// view into index container using index_view = typename index_type::view_type; using const_index_view = typename index_type::const_view_type; /// view into value container using vector_view = typename vector_type::view_type; using const_vector_view = typename vector_type::const_view_type; /// build the matrix for a given time step void setup_matrix(value_type dt); /// which requires const_view in the vector library const matrix_type& jacobian() { return matrix_; } /// return list of CV areas in : /// um^2 /// 1e-6.mm^2 /// 1e-8.cm^2 const_vector_view cv_areas() const { return cv_areas_; } /// return the capacitance of each CV surface /// this is the total capacitance, not per unit area, /// i.e. equivalent to sigma_i * c_m const_vector_view cv_capacitance() const { return cv_capacitance_; } /// return the voltage in each CV vector_view voltage() { return voltage_; } const_vector_view voltage() const { return voltage_; } /// return the current in each CV vector_view current() { return current_; } const_vector_view current() const { return current_; } std::size_t size() const { return matrix_.size(); } /// return reference to in iterable container of the mechanisms std::vector<mechanism_type>& mechanisms() { return mechanisms_; } /// return reference to list of ions std::map<mechanisms::ionKind, ion_type>& ions() { return ions_; } std::map<mechanisms::ionKind, ion_type> const& ions() const { return ions_; } /// return reference to sodium ion ion_type& ion_na() { return ions_[mechanisms::ionKind::na]; } ion_type const& ion_na() const { return ions_[mechanisms::ionKind::na]; } /// return reference to calcium ion ion_type& ion_ca() { return ions_[mechanisms::ionKind::ca]; } ion_type const& ion_ca() const { return ions_[mechanisms::ionKind::ca]; } /// return reference to pottasium ion ion_type& ion_k() { return ions_[mechanisms::ionKind::k]; } ion_type const& ion_k() const { return ions_[mechanisms::ionKind::k]; } /// flags if solution is physically realistic. /// here we define physically realistic as the voltage being within reasonable bounds. /// use a simple test of the voltage at the soma is reasonable, i.e. in the range /// v_soma \in (-1000mv, 1000mv) bool is_physical_solution() const { auto v = voltage_[0]; return (v>-1000.) && (v<1000.); } value_type time() const { return t_; } std::size_t num_probes() const { return probes_.size(); } private: /// current time [ms] value_type t_ = value_type{0}; /// resting potential (initial voltage condition) value_type resting_potential_ = -65; /// the linear system for implicit time stepping of cell state matrix_type matrix_; /// index for fast lookup of compartment index ranges of segments index_type segment_index_; /// cv_areas_[i] is the surface area of CV i [µm^2] vector_type cv_areas_; /// alpha_[i] is the following value at the CV face between /// CV i and its parent, required when constructing linear system /// face_alpha_[i] = area_face / (c_m * r_L * delta_x); vector_type face_alpha_; // [µm·m^2/cm/s ≡ 10^5 µm^2/ms] /// cv_capacitance_[i] is the capacitance of CV i per unit area (i.e. c_m) [F/m^2] vector_type cv_capacitance_; /// the average current density over the surface of each CV [mA/cm^2] /// current_ = i_m - i_e vector_type current_; /// the potential in each CV [mV] vector_type voltage_; /// Where point mechanisms start in the mechanisms_ list. std::size_t synapse_base_; /// the set of mechanisms present in the cell std::vector<mechanism_type> mechanisms_; /// the ion species std::map<mechanisms::ionKind, ion_type> ions_; std::vector<std::pair<uint32_t, i_clamp>> stimuli_; std::vector<std::pair<const vector_type fvm_cell::*, uint32_t>> probes_; // mechanism factory using mechanism_catalogue = nest::mc::mechanisms::catalogue<value_type, size_type>; }; //////////////////////////////////////////////////////////////////////////////// //////////////////////////////// Implementation //////////////////////////////// //////////////////////////////////////////////////////////////////////////////// template <typename T, typename I> template <typename Cells, typename Detectors, typename Targets, typename Probes> void fvm_cell<T, I>::initialize( const Cells& cells, Detectors& detector_handles, Targets& target_handles, Probes& probe_handles) { if (util::size(cells)!=1u) { throw std::invalid_argument("fvm_cell accepts only one cell"); } const nest::mc::cell& cell = *(std::begin(cells)); size_type ncomp = cell.num_compartments(); // confirm write-parameters have enough room to store handles EXPECTS(util::size(detector_handles)==cell.detectors().size()); EXPECTS(util::size(target_handles)==cell.synapses().size()); EXPECTS(util::size(probe_handles)==cell.probes().size()); // initialize storage cv_areas_ = vector_type{ncomp, T{0}}; face_alpha_ = vector_type{ncomp, T{0}}; cv_capacitance_ = vector_type{ncomp, T{0}}; current_ = vector_type{ncomp, T{0}}; voltage_ = vector_type{ncomp, T{resting_potential_}}; using util::left; using util::right; const auto graph = cell.model(); matrix_ = matrix_type(graph.parent_index); auto parent_index = matrix_.p(); segment_index_ = graph.segment_index; auto seg_idx = 0; for(auto const& s : cell.segments()) { if(auto soma = s->as_soma()) { // assert the assumption that the soma is at 0 if(seg_idx!=0) { throw std::domain_error( "FVM lowering encountered soma with non-zero index" ); } auto area = math::area_sphere(soma->radius()); cv_areas_[0] += area; cv_capacitance_[0] += area * soma->mechanism("membrane").get("c_m").value; } else if(auto cable = s->as_cable()) { // loop over each compartment in the cable // each compartment has the face between two CVs at its centre // the centers of the CVs are the end points of the compartment // // __________________________________ // | ........ | .cvleft. | cv | // | ........ L ........ C R // |__________|__________|__________| // // The compartment has end points marked L and R (left and right). // The left compartment is assumed to be closer to the soma // (i.e. it follows the minimal degree ordering) // The face is at the center, marked C. // The full control volume to the left (marked with .) auto c_m = cable->mechanism("membrane").get("c_m").value; auto r_L = cable->mechanism("membrane").get("r_L").value; for(auto c : cable->compartments()) { auto i = segment_index_[seg_idx] + c.index; auto j = parent_index[i]; auto radius_center = math::mean(c.radius); auto area_face = math::area_circle( radius_center ); face_alpha_[i] = area_face / (c_m * r_L * c.length); auto halflen = c.length/2; auto al = math::area_frustrum(halflen, left(c.radius), radius_center); auto ar = math::area_frustrum(halflen, right(c.radius), radius_center); cv_areas_[j] += al; cv_areas_[i] += ar; cv_capacitance_[j] += al * c_m; cv_capacitance_[i] += ar * c_m; } } else { throw std::domain_error("FVM lowering encountered unsuported segment type"); } ++seg_idx; } // normalize the capacitance by cv_area for(auto i=0u; i<size(); ++i) { cv_capacitance_[i] /= cv_areas_[i]; } ///////////////////////////////////////////// // create mechanisms ///////////////////////////////////////////// // FIXME : candidate for a private member function // for each mechanism in the cell record the indexes of the segments that // contain the mechanism std::map<std::string, std::vector<unsigned>> mech_map; for (unsigned i=0; i<cell.num_segments(); ++i) { for (const auto& mech : cell.segment(i)->mechanisms()) { // FIXME : Membrane has to be a proper mechanism, // because it is exposed via the public interface. // This if statement is bad if(mech.name() != "membrane") { mech_map[mech.name()].push_back(i); } } } // Create the mechanism implementations with the state for each mechanism // instance. // TODO : this works well for density mechanisms (e.g. ion channels), but // does it work for point processes (e.g. synapses)? for (auto& mech : mech_map) { // calculate the number of compartments that contain the mechanism auto num_comp = 0u; for (auto seg : mech.second) { num_comp += segment_index_[seg+1] - segment_index_[seg]; } // build a vector of the indexes of the compartments that contain // the mechanism index_type compartment_index(num_comp); auto pos = 0u; for (auto seg : mech.second) { auto seg_size = segment_index_[seg+1] - segment_index_[seg]; std::iota( compartment_index.data() + pos, compartment_index.data() + pos + seg_size, segment_index_[seg] ); pos += seg_size; } // instantiate the mechanism mechanisms_.push_back( mechanism_catalogue::make(mech.first, voltage_, current_, compartment_index) ); } synapse_base_ = mechanisms_.size(); // Create the synapse mechanism implementations together with the target handles std::vector<std::vector<cell_lid_type>> syn_mech_map; std::map<std::string, std::size_t> syn_mech_indices; auto target_hi = target_handles.begin(); for (const auto& syn : cell.synapses()) { const auto& name = syn.mechanism.name(); std::size_t index = 0; if (syn_mech_indices.count(name)==0) { index = syn_mech_map.size(); syn_mech_indices[name] = index; syn_mech_map.push_back(std::vector<cell_lid_type>{}); } else { index = syn_mech_indices[name]; } size_type comp = find_compartment_index(syn.location, graph); *target_hi++ = target_handle{index, syn_mech_map[index].size()}; syn_mech_map[index].push_back(comp); } for (const auto& syni : syn_mech_indices) { const auto& mech_name = syni.first; index_type compartment_index(syn_mech_map[syni.second]); auto mech = mechanism_catalogue::make(mech_name, voltage_, current_, compartment_index); mech->set_areas(cv_areas_); mechanisms_.push_back(std::move(mech)); } ///////////////////////////////////////////// // build the ion species ///////////////////////////////////////////// for(auto ion : mechanisms::ion_kinds()) { // find the compartment indexes of all compartments that have a // mechanism that depends on/influences ion std::set<int> index_set; for(auto& mech : mechanisms_) { if(mech->uses_ion(ion)) { for(auto idx : mech->node_index()) { index_set.insert(idx); } } } std::vector<cell_lid_type> indexes(index_set.begin(), index_set.end()); // create the ion state if(indexes.size()) { ions_.emplace(ion, index_type(indexes)); } // join the ion reference in each mechanism into the cell-wide ion state for(auto& mech : mechanisms_) { if(mech->uses_ion(ion)) { mech->set_ion(ion, ions_[ion]); } } } // FIXME: Hard code parameters for now. // Take defaults for reversal potential of sodium and potassium from // the default values in Neuron. // Neuron's defaults are defined in the file // nrn/src/nrnoc/membdef.h auto all = memory::all; constexpr value_type DEF_vrest = -65.0; // same name as #define in Neuron ion_na().reversal_potential()(all) = 115+DEF_vrest; // mV ion_na().internal_concentration()(all) = 10.0; // mM ion_na().external_concentration()(all) = 140.0; // mM ion_k().reversal_potential()(all) = -12.0+DEF_vrest;// mV ion_k().internal_concentration()(all) = 54.4; // mM ion_k().external_concentration()(all) = 2.5; // mM ion_ca().reversal_potential()(all) = 12.5 * std::log(2.0/5e-5);// mV ion_ca().internal_concentration()(all) = 5e-5; // mM ion_ca().external_concentration()(all) = 2.0; // mM // add the stimuli for(const auto& stim : cell.stimuli()) { auto idx = find_compartment_index(stim.location, graph); stimuli_.push_back( {idx, stim.clamp} ); } // record probe locations by index into corresponding state vector auto probe_hi = probe_handles.begin(); for (auto probe : cell.probes()) { auto comp = find_compartment_index(probe.location, graph); switch (probe.kind) { case probeKind::membrane_voltage: *probe_hi = {&fvm_cell::voltage_, comp}; break; case probeKind::membrane_current: *probe_hi = {&fvm_cell::current_, comp}; break; default: throw std::logic_error("unrecognized probeKind"); } ++probe_hi; } // detector handles are just their corresponding compartment indices auto detector_hi = detector_handles.begin(); for (auto detector : cell.detectors()) { auto comp = find_compartment_index(detector.location, graph); *detector_hi++ = comp; } // initialise mechanism and voltage state reset(); } template <typename T, typename I> void fvm_cell<T, I>::setup_matrix(T dt) { using memory::all; // convenience accesors to matrix storage auto l = matrix_.l(); auto d = matrix_.d(); auto u = matrix_.u(); auto p = matrix_.p(); auto rhs = matrix_.rhs(); // The matrix has the following layout in memory // where j is the parent index of i, i.e. i<j // // d[i] is the diagonal entry at a_ii // u[i] is the upper triangle entry at a_ji // l[i] is the lower triangle entry at a_ij // // d[j] . . u[i] // . . . // . . . // l[i] . . d[i] // d(all) = cv_areas_; // [µm^2] for (auto i=1u; i<d.size(); ++i) { auto a = 1e5*dt * face_alpha_[i]; d[i] += a; l[i] = -a; u[i] = -a; // add contribution to the diagonal of parent d[p[i]] += a; } // the RHS of the linear system is // V[i] - dt/cm*(im - ie) auto factor = 10.*dt; // units: 10·ms/(F/m^2)·(mA/cm^2) ≡ mV for(auto i=0u; i<d.size(); ++i) { rhs[i] = cv_areas_[i]*(voltage_[i] - factor/cv_capacitance_[i]*current_[i]); } } template <typename T, typename I> void fvm_cell<T, I>::reset() { voltage_(memory::all) = resting_potential_; t_ = 0.; for (auto& m : mechanisms_) { m->nrn_init(); } } template <typename T, typename I> void fvm_cell<T, I>::advance(T dt) { using memory::all; PE("current"); current_(all) = 0.; // update currents from ion channels for(auto& m : mechanisms_) { PE(m->name().c_str()); m->set_params(t_, dt); m->nrn_current(); PL(); } // add current contributions from stimuli for (auto& stim : stimuli_) { auto ie = stim.second.amplitude(t_); // [nA] auto loc = stim.first; // note: current_ in [mA/cm^2], ie in [nA], cv_areas_ in [µm^2]. // unit scale factor: [nA/µm^2]/[mA/cm^2] = 100 current_[loc] -= 100*ie/cv_areas_[loc]; } PL(); // solve the linear system PE("matrix", "setup"); setup_matrix(dt); PL(); PE("solve"); matrix_.solve(); PL(); voltage_(all) = matrix_.rhs(); PL(); // integrate state of gating variables etc. PE("state"); for(auto& m : mechanisms_) { PE(m->name().c_str()); m->nrn_state(); PL(); } PL(); t_ += dt; } } // namespace fvm } // namespace mc } // namespace nest
true
0f68c2e992c940ba5705ccbd789fd62cbf29ec01
C++
ENTRAE/pruebasC
/area_circ.cpp
WINDOWS-1250
414
3.140625
3
[]
no_license
/* Programa: rea de una circunferencia (Solucin 1) */ #include <conio.h> #include <stdio.h> int main() { float area, radio; printf( "\n Introduzca radio: " ); scanf( "%f", &radio ); area = 3.141592 * radio * radio; printf( "\n El %crea de la circunferencia es: %.2f", 160, area ); printf( "\n\n Pulse una tecla para salir..." ); getch(); /* Pausa */ return 0; }
true
55c4c6c57b3f28b98bf6720c521c04ccd54545ee
C++
AnthonyJr/Misc-C-Programs
/l4p3.cpp
UTF-8
549
3.625
4
[]
no_license
#include <iostream> using namespace std; double average(double& totAl, doublet& nog) int main(){ int numOfGrades; double grade, total; total = 0; cout << " hello, enter the number of grades: " << endl; cin >> numOfGrades; for (int i = 0; i < numOfGrades; i++){ cout << " enter a numeric grade 1-100: " << endl; cin >> grade; total = grade + total;} double answer =average(total,numOfGrades); cout << " the total is " << answer << endl; return 0; } double average(double totAl,int nog) { double avg; avg = totAl / nog; return avg; }
true
3b15fceadd849b2c14a58e2306023e758b3e603c
C++
G00nza/TP2
/src/BaseDeDatos.h
UTF-8
12,634
3.046875
3
[]
no_license
#ifndef _BASEDEDATOS_H #define _BASEDEDATOS_H #include "Registro.h" #include "Restriccion.h" #include "Tabla.h" #include <utility> #include <list> #include <string> #include <map> #include "linear_map.h" #include "linear_set.h" #include "string_map.h" #include "utils.h" using namespace std; /** * @brief Una base de datos es un administrador de tablas con funciones de * búsqueda. * * Una base de datos permite administrar tablas identificadas por registro. * Permite saber si se puede agegar un registro a una tabla y luego agregarlo. * Permite realizar filtros del contenido de tablas mediante criterios de * búsqueda. Además mantiene estadísticas del uso de los criterios. * * **se explica con** TAD BaseDeDatos */ class BaseDeDatos { public: /** @brief Criterio de búsqueda para una base de datos */ typedef linear_set<Restriccion> Criterio; /** @brief Indice para un campo dado, el bool es false si es sobre int, true si es sobre string */ typedef tuple<map<int, linear_set<const Registro*> >, string_map<linear_set<const Registro*> >, bool > Indice; /** @brief Join entre dos tablas * Para cada clave del diccionario (registros de tabla1) tengo los registros de tabla2 que coinciden en el campo dado */ typedef linear_map<const Registro*, linear_set<const Registro*> > Join; //habria que definir un join_begin y un join_end de tipo join_iterator typedef pair<const Registro*, const Registro*> join_iterator; /** * @brief Inicializa una base de datos sin tablas. * * \pre true * \post \P{this} = nuevaDB * * \complexity{\O(1)} */ BaseDeDatos(); /** * @brief Crea una nueva tabla en la base de datos. * * @param nombre Nombre identificador de la tabla * @param claves Claves de la tabla a crear * @param campos Campos de la tabla a crear * @param tipos Tipos para los campos de la tabla a crear * * \pre db = \P{this} \LAND * \LNOT (nombre \IN tablas(\P{this})) \LAND * \LAND \LNOT \EMPTYSET?(claves) \LAND * \FORALL (c: campo) c \IN claves \IMPLICA c \IN campos \LAND * long(campos) = long(tipos) \LAND sinRepetidos(campos) * \post \P{this} = agregarTabla(nuevaTabla(claves, nuevoRegistro(campos, tipos)), db) * * \complexity{\O(C)} */ void crearTabla(const string &nombre, const linear_set<string> &claves, const vector<string> &campos, const vector<Dato> &tipos); /** * @brief Agrega un registro a la tabla parámetro * * @param r Registro a agregar * @param nombre Nombre de la tabla donde se agrega el registro * * \pre db = \P{this} \LAND nombre \IN tablas(\P{this}) \LAND * puedoInsertar?(r, dameTabla(\P{this})) * \post \P{this} = insertarEntrada(r, nombre, db) * * \complexity{\O(copy(reg) + C*(L+log(m)))} */ void agregarRegistro(const Registro &r, const string &nombre); /** * @brief Devuelve el conjunto de tablas existentes en la base. * * El conjunto de nombres se devuelve por referencia no-modificable. * * \pre true * \post \P{res} = tablas(\P{this}) * * \complexity{\O(1)} */ const linear_set<string> &tablas() const; /** * @brief Devuelve la tabla asociada al nombre. * * La tabla se devuelve por referencia no modificable. * * @param nombre Nombre de la tabla buscada. * * \pre nombre \IN tablas(\P{this}) * \post \P{res} = dameTabla(nombre, \P{this}) * * \complexity{O(1)} */ const Tabla &dameTabla(const string &nombre) const; /** * @brief Devuelve la cantidad de usos que tiene un criterio * * @param criterio Criterio por el cual se consulta. * * \pre nombre \IN tablas(\P{this}) * \post \P{res} = usoCriterio(criterio, \P{this}) * * \complexity{\O(#cs * cmp(Criterio))} */ int uso_criterio(const Criterio &criterio) const; /** * @brief Evalúa si un registro puede ingresarse en la tabla parámetro. * * @param r Registro a ingresar en la tabla. * @param nombre Nombre de la tabla. * * \pre nombre \IN tablas(\P{this}) * \post \P{res} = puedoInsertar?(r, dameTabla(nombre, \P{this})) * * \complexity{\O(C + (c*n*L))} */ bool registroValido(const Registro &r, const string &nombre) const; /** * @brief Evalúa si un criterio puede aplicarse en la tabla parámetro. * * @param c Criterio a utilizar. * @param nombre Nombre de la tabla. * * \pre tabla \IN tablas(\P{this}) * \post \P{res} = criterioValido(c, nombre, \P{this}) * * \complexity{\O(cr * C)} */ bool criterioValido(const Criterio &c, const string &nombre) const; /** * @brief Devuelve el resultado de buscar en una tabla con un criterio. * * @param c Criterio de búsqueda utilizado. * @param nombre Nombre de la tabla. * * \pre nombre \IN tablas(\P{this}) \LAND criterioValido(c, nombre, \P{this}) * \post \P{res} = buscar(c, nombre, \P{this}) * * \complexity{\O(T + cs * cmp(Criterio) + cr * n * (C + L + copy(reg)))} */ Tabla busqueda(const Criterio &c, const string &nombre); /** * @brief Devuelve los criterios de máximo uso. * * \pre true * \post \FORALL (c : Criterio) [c \IN \P{res} \IFF * \FORALL (c' : Criterio) usoCriterio(c, db) >= usoCriterio(c', db)] * * \complexity{\O(cs * copy(Criterio))} */ linear_set<Criterio> top_criterios() const; /** * @brief Crea un índice para una tabla de la base de datos en un campo de la misma. * * @param nombre Nombre de la tabla * @param campo Nombre del campo * * \pre nombre \IN _nombres_tablas \LAND campo \IN campos(dameTabla(nombre,bd)) \LAND bd = bd' * \post tieneIndice?(nombre, campo, bd) * * \complexity{\O(m[L+log(m)])} chamuyo (ver) */ void crearIndice(const string &nombre, const string &campo); /** * @brief Crea un join entre las dos tablas y devuelve join_begin(res) * * @param tabla1 Nombre de la tabla 1 * @param tabla2 Nombre de la tabla 2 * @param campo Nombre del campo sobre el cual realizar el join * * \pre tabla1 \IN _nombres_tablas \LAND campo \IN campos(dameTabla(tabla1)) \LAND * tabla2 \IN _nombres_tablas \LAND campo \IN campos(dameTabla(tabla2)) \LAND * (tieneIndice?(tabla1, campo, bd) \OR tieneIndice?(tabla2, campo, bd)) * \post El iterador itera sobre los registros de join(t,t2,c,db) en un orden no definido * * \complexity{\O(n*[L+log(m)])} */ join_iterator join(const string &tabla1, const string &tabla2, const string &campo); private: /////////////////////////////////////////////////////////////////////////////////////////////////// /** \name Representación * rep: basededatos \TO bool\n * rep(bd) \EQUIV * * _nombres_tablas = claves(_tablas) \LAND * * \FORALL (c : Criterio) c \IN claves(_uso_criterios) \IMPLIES * * ( * * \EXISTS (n : string) n \IN _nombres_tablas * * \LAND criterioValido(c, n, db) * * ) \LAND * * obtener(c, _uso_criterios) > 0 * * \FORALL (t : string) def?(t , _indices) \IMPLIES def?(t , _tablas) \LAND * * ( * * \FORALL (c : string) def? (c , obtener(t , _indices)) \IMPLIES * * c \IN campos(obtener(t , _tablas)) \LAND * * ( * * \FORALL (d : Dato) def?(d, obtener(c, obtener(t , _indices))) \IMPLIES * * \LNOT vacio?(obtener(d, obtener(c, obtener(t , _indices)))) \LAND * * ( * * \FORALL (r : Registro) r \IN obtener(d, obtener(c, obtener(t , _indices))) \IMPLIES * * r \IN registros (obtener(t, _tablas)) \LAND valor(c, r) = d * * ) * * ) * * ) * * abs: basededatos \TO BaseDeDatos\n * abs(bd) \EQUIV bd' \| * * _nombres_tablas = tablas(bd') \LAND * * (\FORALL nt : string) nt \IN _nombres_tablas \IMPLIES * * obtener(nt, _tablas) = dameTabla(nt, bd') \LAND * * (\FORALL c : criterio) * * (usoCriterio(c, bd') == 0 \LAND \LNOT def?(c, _uso_criterios)) \LOR * * (usoCriterio(c, db') == obtener(c, _uso_criterios)) \LAND * * (\FORALL t : string) t \IN tablas(bd') \LAND * * (\FORALL c : string) c \IN campos(dameTabla(t, bd')) * * tieneIndice?(t, c, bd') == def?(c, obtener(t, _indices)) */ ////////////////////////////////////////////////////////////////////////////////////////////////////// /** @{ */ linear_set<string> _nombres_tablas; string_map<Tabla> _tablas; linear_map<Criterio, int> _uso_criterios; string_map<string_map<Indice> >_indices; //Decidi implementarlo como que se guarda un puntero al último Join hecho asi no se invalida el iterador que devuelve join Join* _ultimo_join; /** @} */ /** @{ */ /** * @brief Revisa si los campos del registro y la tabla tienen el mismo tipo. * * \pre campos(r) == campos(t) * \post \P{res} == \FORALL (c : campo) c \IN campos(r) \IMPLIES * Nat?(valor(c, r)) == tipoCampo(c, t) * * \complexity{O(C)} */ bool _mismos_tipos(const Registro &r, const Tabla &t) const; /** * @brief Revisa si el registro no repite claves en la tabla. * * \pre compatible(r, t) * \post \P{res} = \FORALL (r' : Registro) r \IN registros(t) \IMPLIES * \EXISTS (c : campo) c \IN claves(t) \LAND valor(c, r') != valor(c, r) * * \complexity{O(c * n * L)} */ bool _no_repite(const Registro &r, const Tabla &t) const; /** * @brief Filtra la lista de registros parametro según el criterio. * * El resultado tiene aliasing con el parámetro registros. * * \pre \FORALL (r : Registro) r \IN registros \IMPLIES campo \IN * campos(r) \LAND tipo?(valor(campo, r)) = tipo?(valor) * \post \P{res} = filtrarRegistrosSegunRestriccion( * nueva(campo, valor, igualdad), registros) */ list<Registro> &_filtrar_registros(const string &campo, const Dato &valor, list<Registro> &registros, bool igualdad) const; /** * @brief Filtra la lista de registros parametro según el criterio. * * El resultado tiene aliasing con el parámetro registros. * * \pre \FORALL (r : Registro) r \IN registros \IMPLIES campo \IN * campos(r) \LAND tipo?(valor(campo, r)) = tipo?(valor) * \post \P{res} = filtrarRegistrosSegunRestriccion( * nueva(campo, valor, true), registros) */ list<Registro> &_filtrar_registros(const string &campo, const Dato &valor, list<Registro> &registros) const; /** * @brief Obtiene los campos y tipos de una tabla. * * \pre true * \post (\FORALL (c : Campo) está?(c, \P1(\P{res})) \IFF c \IN campos(t)) * \LAND #(campos(t)) = long(\P1(\P{res})) * \LAND \FORALL (i : Nat) 0 \LEQ i < #(campos(t)) \IMPLIES * tipo?(\P2(\P{res})[i]) = tipoCampo(\P1(\P{res})[i], t) */ pair<vector<string>, vector<Dato> > _tipos_tabla(const Tabla &t); /** * @brief Agrega un registro a un índice dado. * * @param indice Indice a modificar * @param registro Registro a agregar * @param campo Nombre del campo del indice * * \pre (\FORALL r: Registro) ((\EXISTS d: Dato) def?(d, indice) \LAND obtener(d, indice) = r) \IMPLIES * campos(r) = campos(registro) \LAND (\FORALL c: campo) c \IN campos(r) \IMPLIES tipo(valor(c,r)) = tipo(valor(c, registro)) * * \post (def?(valor(campo, registro), indice) \IMPLIES indice = definir(valor(campo, registro), Ag(registro, obtener(valor(campo,registro))), indice) )\LAND * ¬def?(valor(campo, registro), indice) \IMPLIES indice = definir(valor(campo, registro), registro) * * */ void agregarAIndice(Indice& indice, const Registro &registro, const string &campo); /** * @brief Devuelve un iterador al primer registro de un join * * @param join Join sobre el cual queremos iterar * * \pre True * * \post Devuelve el iterador del join */ join_iterator join_begin(Join join); /** @} */ }; #endif
true
06cf7f9f1addb6e55c76b4bc5e789d104a893b10
C++
danyfel80/pooAvancee
/TD6/POO-TD6/src/Fish.cpp
UTF-8
1,159
3.375
3
[]
no_license
/* * Fish.cpp * * Created on: Oct 31, 2018 * Author: daniel */ #include "Fish.h" #include <sstream> using namespace std; Fish::Fish(string name, bool female, int x, int y, int depth) : Animal(name, female, x, y) { cout << "Fish: default constructor" << endl; this->depth = depth; } Fish::Fish(const Fish& other) : Animal(other) { cout << "Fish: copy constructor" << endl; this->depth = other.depth; } Fish::~Fish() { cout << "Fish: destructor" << endl; } Fish& Fish::operator =(const Fish& other) { Animal::operator =(other); if (this != &other) { this->depth = other.depth; } return *this; } int Fish::getDepth() const { return depth; } void Fish::setDepth(int depth) { this->depth = depth; } void Fish::move() { setX(getX() + 1); setY(getY() + 1); } Fish* Fish::breed(bool female) const { Fish* baby = NULL; if (isFemale()) { stringstream ss; ss << getName() << "_" << (female? "daughter": "son"); baby = new Fish(ss.str(), female, getX(), getY(), depth); } return baby; } string Fish::toString() const { stringstream ss; ss << "Fish " << Animal::toString() << ", depth = " << depth; return ss.str(); }
true
c0742c01d198d57e2005e10825df820a7e720b83
C++
doctorrokter/qdropbox
/src/qdropbox/QDropboxUpload.cpp
UTF-8
2,431
2.59375
3
[]
no_license
/* * QDropboxUpload.cpp * * Created on: Dec 27, 2017 * Author: doctorrokter */ #include "../../include/qdropbox/QDropboxUpload.hpp" #include <QFile> #include "../../include/qdropbox/QDropbox.hpp" QDropboxUpload::QDropboxUpload(const QString& path, const QString& remotePath, QObject* parent) : QObject(parent), m_offset(0), m_size(0), m_uploadSize(0), m_path(path), m_remotePath(remotePath), m_sessionId("") {} QDropboxUpload::QDropboxUpload(const QDropboxUpload& upload) : QObject(upload.parent()) { swap(upload); } QDropboxUpload::~QDropboxUpload() {} QDropboxUpload& QDropboxUpload::operator =(const QDropboxUpload& upload) { return swap(upload); } const qint64& QDropboxUpload::getOffset() const { return m_offset; } const qint64& QDropboxUpload::getSize() const { return m_size; } const QString& QDropboxUpload::getPath() const { return m_path; } const QString& QDropboxUpload::getRemotePath() const { return m_remotePath; } const QString& QDropboxUpload::getSessionId() const { return m_sessionId; } QDropboxUpload& QDropboxUpload::setSessionId(const QString& sessionId) { m_sessionId = sessionId; return *this; } const qint64& QDropboxUpload::getUploadSize() const { return m_uploadSize; } QDropboxUpload& QDropboxUpload::setUploadSize(const qint64& uploadSize) { m_uploadSize = uploadSize; return *this; } QDropboxUpload& QDropboxUpload::swap(const QDropboxUpload& upload) { m_offset = upload.getOffset(); m_path = upload.getPath(); m_remotePath = upload.getRemotePath(); m_sessionId = upload.getSessionId(); resize(); return *this; } void QDropboxUpload::resize() { QFile file(m_path); m_size = file.size(); } void QDropboxUpload::increment() { m_offset += m_uploadSize; } bool QDropboxUpload::isNew() { return m_sessionId.isEmpty(); } bool QDropboxUpload::started() { return !m_sessionId.isEmpty(); } bool QDropboxUpload::lastPortion() { return m_size <= (m_offset + m_uploadSize); } QByteArray QDropboxUpload::next() { QByteArray data; QFile file(m_path); bool res = file.open(QIODevice::ReadOnly); if (res) { if (m_offset == 0) { data = file.read(m_uploadSize); } else { file.seek(m_offset); data = file.read(m_uploadSize); } file.close(); } else { qDebug() << "File didn't opened!!!" << endl; } return data; }
true
0549a30a2441b0992d05dec8b2811e0b7a9638b1
C++
fgolubic/Oblikovni
/Lab2.4/DistributionTester.cpp
UTF-8
750
3.1875
3
[]
no_license
#include "DistributionTester.h" #include<iostream> #include<sstream> #include <string> DistributionTester::DistributionTester(std::initializer_list<int> percentiles):percentiles_(percentiles) { } std::string printSequence(std::vector<int> const& distr) { std::ostringstream stream = std::ostringstream(); for (const auto& value : distr) { stream << value << " , "; } auto res = stream.str(); return res.substr(0, res.length() - 2) + " : "; } void DistributionTester::test(Generator const& gen, Percentil const& percCalc) const { auto seq = gen.generateNumbers(); std::cout << printSequence(seq); for(const auto& p : percentiles_) { std::cout << percCalc.calculatePercentil(seq, p)<< "/ "; } std::cout << std::endl; }
true
704532b0a29f91c6dc855a4935a627b0dec03c01
C++
CODECITM/1010_Game
/1010_Game/CheckBox.h
UTF-8
2,819
3.0625
3
[ "MIT" ]
permissive
#ifndef __CHECK_BOX__ #define __CHECK_BOX__ #include "Button.h" struct SDL_Texture; template <class Ret, class... Args> class CheckBox : public Button<Ret, Args...> { public: //Constructor template<class Ret, class... Args> CheckBox(Ret(*action)(Args...), bool* value, fPoint center, SDL_Rect spriteList[3], SDL_Texture* tex, bool dynamic = false, UIElement* parent = NULL, p2List<UIElement*>* children = NULL) : Button<Ret, Args...>(action, ui_type::BUTTON_CHECK, center, spriteList[0], tex, dynamic, parent, children), active(value) { stateSprites = new SDL_Rect[3]; for (int i = 0; i < 3; i++) { stateSprites[i] = spriteList[i]; } if (*active) { *sprite = stateSprites[1]; } else { *sprite = stateSprites[2]; } }; virtual ~CheckBox() { RELEASE(sprite); RELEASE_ARRAY(stateSprites); } //Button action calling Ret operator() (Args&... args) const { return (action)(args...); } Ret DoAction(Args&... args) const { return (action)(args...); } // Called each frame (framerate dependant) virtual bool UpdateTick(float dt) { bool ret = true; if (status != button_state::DISABLED) { CheckCurrentState(); ButtonStateEffects(); } return ret; } protected: virtual button_state CheckCurrentState() { switch (status) { case button_state::IDLE: if (MouseOnImage() == true) { OnHover(); status = button_state::HOVERING; } break; case button_state::HOVERING: if (App->input->GetMouseButtonDown(SDL_BUTTON_LEFT) == KEY_DOWN) { OnPress(); status = button_state::PRESSING; } else if (MouseOnImage() == false) { OnIdle(); status = button_state::IDLE; } break; case button_state::PRESSING: if (App->input->GetMouseButtonDown(SDL_BUTTON_LEFT) == KEY_UP || MouseOnImage() == false) { OnIdle(); status = button_state::IDLE; } break; } return status; } virtual button_state ButtonStateEffects() { switch (status) { case button_state::IDLE: WhileIdle(); break; case button_state::HOVERING: WhileHover(); break; case button_state::PRESSING: WhilePress(); break; } if (*active) { *sprite = stateSprites[1]; } else { *sprite = stateSprites[2]; } return status; } virtual void OnIdle() {} virtual void OnHover() {} virtual void OnPress() { App->audio->PlayFx(App->audio->buttonPressSfx.id, 0); DoAction(Args...); *active = !*active; } virtual void WhileIdle() {} virtual void WhileHover() {} virtual void WhilePress() {} //Enable/Disable virtual void Enable() { status = button_state::IDLE; } virtual void Disable() { status = button_state::DISABLED; *sprite = stateSprites[0]; } private: bool* active; SDL_Rect* stateSprites = nullptr; //Disabled, Idle, Hover, Pressed }; #endif //__ACTION_BOX_H__
true
1f9cfde860030c1218d38d519a73b0337e46d9a6
C++
mkvarner/mv2504740
/Hmwk/Assignment 4/Indiv. Problems/Problem11/main.cpp
UTF-8
1,342
3.46875
3
[]
no_license
/* * File: main.cpp * Author: Megan Varner * * Created on July 11, 2014, 8:43 PM * Predict population growth */ #include <iostream> #include <iomanip> using namespace std; int main() { int organisms = 0.0; int days_multiply = 0; float increase = 0.0; cout << "Enter the starting number of organisms: "; cin >> organisms; while(organisms < 2) { cout << "Enter the starting number of organisms: "; cin >> organisms; } cout << "Enter the average daily population increase (as a percentage): "; cin >> increase; while(increase < 0) { cout << "Enter the average daily population increase (as a percentage): "; cin >> increase; } cout << "Enter the number of days they will multiply: "; cin >> days_multiply; while(days_multiply < 1) { cout << "Enter the number of days they will multiply: "; cin >> days_multiply; } for (int count = 0; count != days_multiply; count++) { organisms = organisms + (organisms * increase); cout << "On day " << count + 1 << " the population size was "; cout << organisms << "." << endl; } return 0; }
true
953016d8d0ce316b1457dbb160c126f9d8d36fe0
C++
TimeVShow/PAT
/1009.cpp
UTF-8
950
2.703125
3
[]
no_license
#include <cstdio> #include <algorithm> #include <cstring> using namespace std; typedef struct{ int num; double sum; }node; node a[13]; node b[13]; double c[2003]; int n,m; void input(){ scanf("%d",&n); for(int i = 0;i < n;i++){ scanf("%d%lf",&a[i].num,&a[i].sum); } scanf("%d",&m); for(int i = 0;i < m;i++){ scanf("%d%lf",&b[i].num,&b[i].sum); } } void work(){ int count = 0; for(int i = 0;i < n;i++){ for(int j = 0;j < m;j++){ int num = a[i].num + b[j].num; double sum = a[i].sum*b[j].sum; if(c[num] < 1e-9){ count++; } c[num] += sum; } } printf("%d",count); for(int i = 2000;i>=0;i--){ if(c[i] < 1e-9){ continue; }else{ printf(" %d %.1lf",i,c[i]); } } } int main(){ memset(c,0,sizeof(z)); input(); work(); return 0; }
true
24917e6246fbc72f2883fe3000e38ff30bc8d5c6
C++
Yash-YC/Source-Code-Plagiarism-Detection
/gcj/dataset/zuko92/5631989306621952/1/extracted/A.cpp
UTF-8
1,617
3.453125
3
[]
no_license
#include <cstdio> #include <cmath> #include <vector> #include <cstdlib> #include <string> struct node { char ch; node* next; }; void Print(node ** first) { if (*first == NULL) { return; } node * temp = *first; while (temp->next != NULL) { printf("%c", temp->ch); temp = temp->next; } printf("%c", temp->ch); } void PrintStr(node ** first, char * str) { if (*first == NULL || str == NULL) { return; } node * temp = *first; int count = 0; while (temp->next != NULL) { str[count] = (temp->ch); temp = temp->next; count++; } str[count] = (temp->ch); str[count + 1] = '\0'; } void Insert(char a, node ** first) { node* ins = new node(); ins->ch = a; ins->next = NULL; if (*first == NULL) { *first = ins; return; } node * head = *first; // if new char < first char insert new char at last if (a < head->ch) { node * temp = head; while (temp->next != NULL) { temp = temp->next; } temp->next = ins; } else // new char >= first char insert new char at first { node* temp = *first; *first = ins; (*first)->next = temp; } } int main() { int Ntest; scanf("%d", &Ntest); getchar(); std::vector<std::string> output; for (int test = 0; test<Ntest; ++test) { node * head = NULL; int count = 0; char buf = getchar(); count++; while (buf != '\n') { Insert(buf, &head); count++; buf = getchar(); } char * out = new char[count]; PrintStr(&head, out); output.push_back(std::string(out)); delete[] out; } for (int test = 0; test<Ntest; ++test) { printf("Case #%d: %s\n", test+1, output[test].c_str()); } return 0; }
true
0ee8ed26cc2402072a2b861b2e4e40bfd4af14a9
C++
kkemppi/TIE-courses
/Ohjelmointi 2/student/11/library_system/loan.cpp
UTF-8
1,257
3.09375
3
[]
no_license
#include "loan.hh" #include "library.hh" #include "book.hh" #include "person.hh" #include "date.hh" #include <map> #include <iostream> #include <memory> #include <utility> Loan::Loan(Date* today, Person *borrower_id, Book *book_title, int renew_count): due_date_(new Date(today->getDay(), today->getMonth(), today->getYear())), borrower_id_(borrower_id), book_title_(book_title), renew_count_(renew_count) { // Due date was current date, move it forvard due_date_->advance_by_loan_length(); } Loan::~Loan(){ delete due_date_; due_date_ = nullptr; } void Loan::renew() { if (renew_count_ >= DEFAULT_RENEWAL_AMOUNT){ std::cout << OUT_OF_RENEWALS_ERROR << std::endl; }else{ due_date_->advance_by_loan_length(); renew_count_++; std::cout << "Renewal was successful. New due date: " << due_date_->to_string() << std::endl; } } Date* Loan::get_due_date() { return due_date_; } std::string Loan::get_borrower() { return borrower_id_->get_name(); } std::string Loan::get_book_title() { return book_title_->get_title(); } bool Loan::is_late(Date* today) { if (*due_date_ < *today){ return true; } else{ return false; } }
true
c3e4dc396be099dfca6846fbaf83945aa3474842
C++
aa0674118/HW5-2
/6.37/source/main.cpp
UTF-8
308
3.078125
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #define SIZE 3 int max(int a[], int n) { if (n == 1) { return a[0]; } else { int x; x = max(a, n - 1); if (a[n-1] > x) { return a[n-1]; } else { return x; } } } int main() { int a[SIZE] = { 8,4,6}; printf("%d",max(a,SIZE)); system("pause"); return 0; }
true
37f5745424748a7100965be9eff24ac95180d5b6
C++
MochHudda-TI-A-A2-1900106/UTS_DASAR_PEMROGRAMAN
/Bab 2/Tipecast.cpp
UTF-8
159
2.671875
3
[]
no_license
#include <iostream> using namespace std; int main() { char Kar = '*'; cout << "Nilai ASCCI "<< Kar << " adalah " << (int) Kar << endl; return 0; }
true
aa9327b32b35fe84db10afc689a6010c8a2d5b5b
C++
iTXCode/Review
/Test/static/static.cc
UTF-8
449
3.265625
3
[]
no_license
#include<iostream> using namespace std; class A{ public: A(){ } void Add(){ cout<<"Add()"<<endl; } static void Sum(){ cout<<A::i<<endl; //cout<<A::a<<endl;//静态成员函数不能访问非静态的成员变量 //Add(); //不能调用非静态的成员函数 } static int i; private: int a; }; int A::i=1; int main(){ A a; A b; cout<<a.i<<" "<<b.i<<endl; return 0; }
true
f6ffdc57620f98bc7ef2a819dc13c967bfd0510a
C++
polluxlabs/ispyarduino
/v.07_i_spy.ino
UTF-8
12,802
2.75
3
[]
no_license
long roundTime = 10000; // Time for player to find the color // include the library code: #include <LiquidCrystal_I2C.h> // define pins for color sensor #define S0 6 #define S1 7 #define S2 9 #define S3 8 #define sensorOut 10 long currentTime; //elapsed time in round long startTime = millis(); //start time of round // values of each color from color sensor int frequencyR = 0; int frequencyG = 0; int frequencyB = 0; int color = 0; // player points int pointsPlayer1 = 0; int pointsPlayer2 = 0; int newGame = 0; int keyRead = 0; int playerOnTurn = 2; int rightColorFound = 0; LiquidCrystal_I2C lcd(0x27, 20, 4); //Hier wird festgelegt um was für einen Display es sich handelt. In diesem Fall eines mit 16 Zeichen in 2 Zeilen und der HEX-Adresse 0x27. Für ein vierzeiliges I2C-LCD verwendet man den Code "LiquidCrystal_I2C lcd(0x27, 20, 4)" void setup() { pinMode(S0, OUTPUT); pinMode(S1, OUTPUT); pinMode(S2, OUTPUT); pinMode(S3, OUTPUT); pinMode(sensorOut, INPUT); pinMode(2, INPUT); //RED pinMode(3, INPUT); //YELLOW pinMode(4, INPUT); //GREEN pinMode(5, INPUT); //BLUE digitalWrite(S0,HIGH); digitalWrite(S1,LOW); Serial.begin(9600); lcd.init(); lcd.backlight(); } void loop() { if(pointsPlayer1 == 0 && pointsPlayer2 == 0 && newGame == 0){ startGame(); newGame = 1; } } void startGame(){ tone(11, 250, 150); delay(100); tone(11, 350, 150); delay(100); tone(11, 450, 150); delay(100); tone(11, 550, 150); lcd.clear(); lcd.setCursor(1,1); lcd.print("Welcome to Veo Veo"); delay(2500); player1Chooses(); } void player1Chooses(){ lcd.clear(); lcd.setCursor(6,0); lcd.print("Player 1"); lcd.setCursor(3,2); lcd.print("Choose a color"); while(keyRead == 0){ readKey(); } } void player2Chooses(){ lcd.clear(); lcd.setCursor(6,0); lcd.print("Player 2"); lcd.setCursor(3,2); lcd.print("Choose a color"); while(keyRead == 0){ readKey(); } } void showPoints(){ lcd.clear(); lcd.setCursor(7,0); lcd.print("Score:"); lcd.setCursor(4,2); lcd.print("Player 1: "); lcd.print(pointsPlayer1); lcd.setCursor(4,3); lcd.print("Player 2: "); lcd.print(pointsPlayer2); delay(5000); } void newRound(){ color = 0; keyRead = 0; if(playerOnTurn == 2){ playerOnTurn = 1; pointsPlayer2++; rightColorFound = 0; showPoints(); player2Chooses(); }else{ playerOnTurn = 2; pointsPlayer1++; rightColorFound = 0; showPoints(); player1Chooses(); } } void readKey(){ if(digitalRead(2) == HIGH){ color = 1; keyRead= 1; tone(11, 450, 150); delay(100); tone(11, 650, 150); delay(100); tone(11, 750, 150); lcd.clear(); lcd.setCursor(6,0); lcd.print("Player " + String(playerOnTurn)); lcd.setCursor(3,2); lcd.print("Find a RED thing"); startTime = millis(); while(rightColorFound == 0 && currentTime - startTime <= roundTime){ checkRed(); currentTime = millis(); } lcd.clear(); tone(11, 150, 150); delay(300); tone(11, 50, 150); lcd.setCursor(4,2); lcd.print("Time is up!"); delay(1500); proofBluff(); }else if(digitalRead(3) == HIGH){ color = 4; keyRead= 1; tone(11, 450, 150); delay(100); tone(11, 650, 150); delay(100); tone(11, 750, 150); lcd.clear(); lcd.setCursor(6,0); lcd.print("Player " + String(playerOnTurn)); lcd.setCursor(0,2); lcd.print("YELLOW! Find YELLOW!"); startTime = millis(); while(rightColorFound == 0 && currentTime - startTime <= roundTime){ checkYellow(); currentTime = millis(); } lcd.clear(); tone(11, 150, 150); delay(300); tone(11, 50, 150); lcd.setCursor(4,2); lcd.print("Time is up!"); delay(1500); proofBluff(); }else if(digitalRead(4) == HIGH){ color = 2; keyRead= 1; tone(11, 450, 150); delay(100); tone(11, 650, 150); delay(100); tone(11, 750, 150); lcd.clear(); lcd.setCursor(6,0); lcd.print("Player " + String(playerOnTurn)); lcd.setCursor(2,2); lcd.print("Something Green!"); startTime = millis(); while(rightColorFound == 0 && currentTime - startTime <= roundTime){ checkGreen(); currentTime = millis(); } lcd.clear(); tone(11, 150, 150); delay(300); tone(11, 50, 150); lcd.setCursor(4,2); lcd.print("Time is up!"); delay(1500); proofBluff(); }else if(digitalRead(5) == HIGH){ color = 3; keyRead= 1; tone(11, 450, 150); delay(100); tone(11, 650, 150); delay(100); tone(11, 750, 150); lcd.clear(); lcd.setCursor(6,0); lcd.print("Player " + String(playerOnTurn)); lcd.setCursor(4,2); lcd.print("Gimme BLUE!"); startTime = millis(); //Startzeit des Suchvorgangs while(rightColorFound == 0 && currentTime - startTime <= roundTime){ checkBlue(); currentTime = millis(); } lcd.clear(); tone(11, 150, 150); delay(300); tone(11, 50, 150); lcd.setCursor(4,2); lcd.print("Time is up!"); delay(1500); proofBluff(); } } void colorPicker(){ digitalWrite(S2,LOW); digitalWrite(S3,LOW); // Reading the output frequency frequencyR = pulseIn(sensorOut, LOW); //Remaping the value of the frequency to the RGB Model of 0 to 255 frequencyR = map(frequencyR, 25,72,255,0); if(frequencyR < 0){ frequencyR = 0; }else if(frequencyR > 255){ frequencyR = 255; } // Printing the value on the serial monitor Serial.print("R= ");//printing name Serial.print(frequencyR);//printing RED color frequency Serial.print(" "); // Setting Green filtered photodiodes to be read digitalWrite(S2,HIGH); digitalWrite(S3,HIGH); // Reading the output frequency frequencyG = pulseIn(sensorOut, LOW); //Remaping the value of the frequency to the RGB Model of 0 to 255 frequencyG = map(frequencyG, 30,90,255,0); if(frequencyG < 0){ frequencyG = 0; }else if(frequencyG > 255){ frequencyG = 255; } // Printing the value on the serial monitor Serial.print("G= ");//printing name Serial.print(frequencyG);//printing RED color frequency Serial.print(" "); // Setting Blue filtered photodiodes to be read digitalWrite(S2,LOW); digitalWrite(S3,HIGH); // Reading the output frequency frequencyB = pulseIn(sensorOut, LOW); //Remaping the value of the frequency to the RGB Model of 0 to 255 frequencyB = map(frequencyB, 25,70,255,0); if(frequencyB < 0){ frequencyB = 0; }else if(frequencyB > 255){ frequencyB = 255; } // Printing the value on the serial monitor Serial.print("B= ");//printing name Serial.print(frequencyB);//printing RED color frequency Serial.println(" "); } void checkRed(){ colorPicker(); if(frequencyR > 200 && frequencyG < 115 && frequencyB < 115){ lcd.clear(); tone(11, 450, 150); delay(100); tone(11, 650, 350); lcd.setCursor(6,2); lcd.print("Great!"); rightColorFound = 1; delay(3000); newRound(); } } void checkYellow(){ colorPicker(); if(frequencyR < 200 && frequencyG > 200 && frequencyB < 210){ lcd.clear(); tone(11, 450, 150); delay(100); tone(11, 650, 350); lcd.setCursor(6,2); lcd.print("Great!"); rightColorFound = 1; delay(3000); newRound(); } } void checkGreen(){ colorPicker(); if(frequencyR < 200 && frequencyG > 200 && frequencyB < 210){ lcd.clear(); tone(11, 450, 150); delay(100); tone(11, 650, 350); lcd.setCursor(6,2); lcd.print("Great!"); rightColorFound = 1; delay(3000); newRound(); } } void checkBlue(){ colorPicker(); if(frequencyR < 120 && frequencyG < 120 && frequencyB > 150){ lcd.clear(); tone(11, 450, 150); delay(100); tone(11, 650, 350); lcd.setCursor(6,2); lcd.print("Great!"); rightColorFound = 1; delay(3000); newRound(); } } void newRoundBluff(){ color = 0; keyRead = 0; //keyRead wieder zurücksetzen if(playerOnTurn == 2){ //Spieler switchen, Punkt geben, anderen spieler aufrufen playerOnTurn = 1; pointsPlayer1++; rightColorFound = 0; showPoints(); player2Chooses(); }else{ playerOnTurn = 2; pointsPlayer2++; // GEHT NICHT rightColorFound = 0; showPoints(); player1Chooses(); } } void proofBluff(){ if(color == 1){ tone(11, 450, 150); delay(100); tone(11, 650, 150); delay(100); tone(11, 750, 150); lcd.clear(); lcd.setCursor(5,0); lcd.print("Opponent!"); lcd.setCursor(0,2); lcd.print("Where is that color?"); startTime = millis(); while(rightColorFound == 0 && currentTime - startTime <= roundTime){ checkRedBluff(); currentTime = millis(); } lcd.clear(); tone(11, 150, 150); delay(300); tone(11, 50, 150); lcd.setCursor(4,2); lcd.print("Time is up!"); delay(1500); newRound(); }else if(color == 2){ tone(11, 450, 150); delay(100); tone(11, 650, 150); delay(100); tone(11, 750, 150); lcd.clear(); lcd.setCursor(5,0); lcd.print("Opponent!"); lcd.setCursor(0,2); lcd.print("Where is that color?"); startTime = millis(); while(rightColorFound == 0 && currentTime - startTime <= roundTime){ checkGreenBluff(); currentTime = millis(); } lcd.clear(); tone(11, 150, 150); delay(300); tone(11, 50, 150); lcd.setCursor(4,2); lcd.print("Time is up!"); delay(1500); newRound(); }else if(color == 4){ tone(11, 450, 150); delay(100); tone(11, 650, 150); delay(100); tone(11, 750, 150); lcd.clear(); lcd.setCursor(5,0); lcd.print("Opponent!"); lcd.setCursor(0,2); lcd.print("Where is that color?"); startTime = millis(); while(rightColorFound == 0 && currentTime - startTime <= roundTime){ checkYellowBluff(); currentTime = millis(); } lcd.clear(); tone(11, 150, 150); delay(300); tone(11, 50, 150); lcd.setCursor(4,2); lcd.print("Time is up!"); delay(1500); newRound(); }else if(color == 3){ tone(11, 450, 150); delay(100); tone(11, 650, 150); delay(100); tone(11, 750, 150); lcd.clear(); lcd.setCursor(5,0); lcd.print("Opponent!"); lcd.setCursor(0,2); lcd.print("Where is that color?"); startTime = millis(); while(rightColorFound == 0 && currentTime - startTime <= roundTime){ checkBlueBluff(); currentTime = millis(); } lcd.clear(); tone(11, 150, 150); delay(300); tone(11, 50, 150); lcd.setCursor(4,2); lcd.print("Time is up!"); delay(1500); newRound(); } } void checkRedBluff(){ colorPicker(); if(frequencyR > 200 && frequencyG < 115 && frequencyB < 115){ lcd.clear(); tone(11, 450, 150); delay(100); tone(11, 650, 350); lcd.setCursor(6,2); lcd.print("Great!"); rightColorFound = 1; delay(3000); newRoundBluff(); } } void checkYellowBluff(){ colorPicker(); if(frequencyR < 200 && frequencyG > 200 && frequencyB < 210){ lcd.clear(); tone(11, 450, 150); delay(100); tone(11, 650, 350); lcd.setCursor(6,2); lcd.print("Great!"); rightColorFound = 1; delay(3000); newRoundBluff(); } } void checkGreenBluff(){ colorPicker(); if(frequencyR < 200 && frequencyG > 200 && frequencyB < 210){ lcd.clear(); tone(11, 450, 150); delay(100); tone(11, 650, 350); lcd.setCursor(6,2); lcd.print("Great!"); rightColorFound = 1; delay(3000); newRoundBluff(); } } void checkBlueBluff(){ colorPicker(); if(frequencyR < 120 && frequencyG < 120 && frequencyB > 150){ lcd.clear(); tone(11, 450, 150); delay(100); tone(11, 650, 350); lcd.setCursor(6,2); lcd.print("Great!"); rightColorFound = 1; delay(3000); newRoundBluff(); } }
true
5f76630d40cb680fc36eb4f4e382a219cac740a7
C++
ArgentumHeart/mipt-1st-term
/midterm-exam/08_ping.cpp
UTF-8
1,113
3.171875
3
[]
no_license
#include <iostream> const int MAX_N = 1001; struct link { int x,y; int ping; }; link arr[MAX_N] = {}; int max_ping; int min_ping[MAX_N] = {}; int M, N; void read_link(int index ) { link temp = {}; std::cin >> temp.x >> temp.y >> temp.ping; arr[index] = temp; } void step (int current) { for (int i = 0; i < N; i++) { if (arr[i].x == current) { if (min_ping[arr[i].y] > arr[i].ping + min_ping[current]) { min_ping[arr[i].y] = arr[i].ping + min_ping[current]; step(arr[i].y); } } if (arr[i].y == current) { if (min_ping[arr[i].x] > arr[i].ping + min_ping[current]) { min_ping[arr[i].x] = arr[i].ping + min_ping[current]; step(arr[i].x); } } } } int main () { std::cin >> M >> N; for (int i = 0; i < N; i++) { read_link(i); } std::cin >> max_ping; for(int i = 2; i <= M; i++) { min_ping[i] = INT32_MAX; } step(1); std::cout << ((min_ping[M] <= max_ping) ? "YES" : "NO"); return 0; }
true
41575e996ad9cf3e7a39a1116dbf5c94f91564c3
C++
u32744/Others
/C语言/20181123/1.cpp
GB18030
2,747
3.546875
4
[]
no_license
#include <stdio.h> #include <iostream> using namespace std; /* bool xor(bool a,bool b); bool find(int **matrix,int rows,int cols,int num); bool xor(bool a,bool b){ return a&&!b || !a&&b; } bool find(int **matrix,int rows,int cols,int num) { if (!rows*cols)return false;//лΪ0 int x=rows-1,y=0;//½ if(*((int *)matrix+x*rows+y)==num) return true;//½Ԫؾֱӷtrue //ȥлȥУȡ½ǴС bool flag=*((int *)matrix+x*rows+y)>num; //ȥСкʹ while(xor(flag,*((int *)matrix+x*rows+y)<num)) { if(flag?x==0:y>=cols-1)break; flag?x--:y++; if(*((int *)matrix+x*rows+y)==num) return true; } while(xor(flag,*((int *)matrix+x*rows+y)>num)) { if(flag?y>=cols-1:x==0)break; flag?y++:x--; if(*((int *)matrix+x*rows+y)==num) return true; } return *((int *)matrix+x*rows+y)==num?true:false; } int main(){ int matrix[4][4]={{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}}; int **p; p=(int **)matrix; for(int i=1;i<=16;i++) cout<<find((int **)matrix,4,4,i)<<endl; }*/ /* class CMyString { public: CMyString(char *pData=NULL); CMyString(const CMyString& str); ~CMyString(void); private: char * m_pData; }; CMyString& CMyString::operator=(const CMyString &str) { if(this==&str)return *this; delete[]m_pData; m_pData=new char[strlen(str.m_pData)+1]; strcpy(m_pData,str.m_pData); return *this; }*/ /* class C{ private: int int_value; float float_value; char char_value; char *string_value; public: C(int n){int_value=n;} C(char c){char_value=c;} C(char *s){string_value=s;} C(float f){float_value=f;} void print_int(){cout<<int_value<<endl;} void print_float(){cout<<float_value<<endl;} void print_char(){cout<<char_value<<endl;} void print_string(){cout<<string_value<<endl;} void print_all(){ print_int(); print_float(); print_char(); print_string(); } }; int main(){ C c=10; c.print_int(); c='a'; c.print_char(); c="test"; c.print_string(); c=(float)2.333; c.print_float(); return 0; }*/ class threat//߳ { private: int num;//̱߳ public: threat(int n){num=n;} threat(threat &old_threat){num=old_threat.num+1;}//̱߳Ҫһ Print(){cout<<num<<endl;} }; int main(){ threat a=10; //bca threat b=a; threat c=a; a.Print(); b.Print(); c.Print(); //db threat d=b; d.Print(); return 0; } /* class A { private: int value; public: A(int n){cout<<"ֵͨ:";value=n;} A(const A &other){cout<<"ͱƣҪһ:";value=other.value+1;} void Print(){cout<<value<<endl;} }; int main(){ A a=10; a.Print(); A b=a; b.Print(); A c=b; c.Print(); return 0; }*/
true
03600de71e83c1c453f4b16b8ed132f05343ab84
C++
DavidHerel/PDV
/cv7/prob.cpp
UTF-8
5,688
2.96875
3
[]
no_license
#include <chrono> #include <vector> #include <cmath> #include <cstdlib> #include <immintrin.h> #include <iostream> // Pro ucely porovnani v nasem kodu pouzivame jednoduchou aproximaci // funkce exp(x) - jak pro skalarni tak vektorizovanou verzi. Pokud // byste chteli pouzit vyrazne presnejsi aproximaci, muzete vyuzit // funkce exp256_ps(...) z hlavickoveho souboru avx_mathfun.h . #include "avx_mathfun.h" inline float exp_scalar(float x) { float addthree = x + 3.0; float subthree = x - 3.0; return ( (addthree * addthree + 3) / (subthree * subthree + 3) ); } // Skalarni implementace funkce, ktera vypocte hodnotu hustotni funkce // normalniho rozdeleni (s parametry mu a sigma) nad polem dat 'data'. void normaldist_scalar(float mu, float sigma, float *data, size_t length) { float expdiv = -2 * sigma * sigma; float normalizer = sqrt(2 * M_PI * sigma * sigma); for(unsigned int i = 0 ; i < length ; i++) { float sc_data = data[i] - mu; sc_data = sc_data * sc_data; sc_data = sc_data / expdiv; sc_data = exp_scalar(sc_data); sc_data = sc_data / normalizer; data[i] = sc_data; } } // Vektorova implementace funkce 'exp_scalar(...)' inline __m256 exp_vec(__m256 x) { __m256 three = _mm256_set1_ps(3.0f); __m256 addthree = _mm256_add_ps(x, three); __m256 subthree = _mm256_sub_ps(x, three); return _mm256_div_ps( _mm256_add_ps(_mm256_mul_ps(addthree, addthree), three), _mm256_add_ps(_mm256_mul_ps(subthree, subthree), three) ); } // Vektorova implementace funkce 'normaldist_scalar(...)'. void normaldist_vec(float mu, float sigma, float * data, size_t length) { // Obdobne jako ve skalarni verzi vypoctu hustoty normalniho rozdeleni // (pocitane funkci 'normaldist_scalar'), budeme ve vektorovem vypoctu // potrebovat nekolik konstant. V pripade vektoroveho vypoctu je nutne, // aby tyto konstanty byly vektory (vektory obsahujici stejne hodnoty // na vsech pozicich. K tomu vyuzijeme funkci '_mm256_set1_ps(...)'. __m256 mm_expdiv = _mm256_set1_ps(-2 * sigma * sigma); __m256 mm_normalizer = _mm256_set1_ps(sqrt(2 * M_PI * sigma * sigma)); // Vsimnete si, ze hodnotu konstant pocitame skalarne (tedy standartne // ve floatech). Az pote, co si skalrni hodnotu konstanty spocteme ji // ulozime do vektoru. // Krome techto konstant potrebujeme i vektorovou verzi konstanty 'mu': __m256 mm_mu = _mm256_set1_ps(mu); for(unsigned int i = 0 ; i < length ; i += 8) { // Nejprve si nacteme 8 prvku zacinajicich na i-te pozici pole data. __m256 mm_data = _mm256_loadu_ps(&data[i]); // S nactenym vektorem muzeme delat operace obdobne jako se skalarnim // typem ve funkci 'normaldist_scalar'. Misto infixovych operatoru // pouzijeme _mm256_ funkce v prefixove notaci: mm_data = _mm256_sub_ps(mm_data, mm_mu); mm_data = _mm256_mul_ps(mm_data, mm_data); mm_data = _mm256_div_ps(mm_data, mm_expdiv); // Pro vypocet exponenciely pouzijeme aproximaci funkci 'exp_vec(...)'. // POZOR! Tato funkce je vhodna pouze pro velmi male vstupni hodnoty. // V opacnem pripade ma vysokou chybu. Lepsi aproximacni funkci muzete // najit v souboru avx_mathfun.h. mm_data = exp_vec(mm_data); mm_data = _mm256_div_ps(mm_data, mm_normalizer); // Na zaver musime zpracovana data nahrat zpet do pameti. _mm256_storeu_ps(&data[i], mm_data); } // POZNAMKA: Nekteri z vas si vsimli, ze je mozne dosahnout jeste vetsiho // zrychleni, pokud nahradite operace deleni (_mm256_div_ps) za nasobeni // vektorem obsahujicim hodnoty 1/x. To je skutecne pravda - deleni muze // byt vyrazne drazsi nez nasobeni. Tato optimalizace nicmene muze byt na // ukor presnosti. // // V pripade, ze presnost vypoctu floating-point operaci neni ve vasem kodu // az tak dulezita, muzete teto optimalizace samozrejme vyuzit. To jeste // muzete zvyraznit pouzitim prepinace kompilatoru '-ffast-math'. } int main() { using namespace std::chrono; // Vygenerujeme data constexpr size_t N = 8 * 10000000; std::vector<float> data(N); for(unsigned int i = 0 ; i < N ; i++) { data[i] = 3 * rand() / (float)RAND_MAX; } // Vytvorime kopie dat auto data1 = data; auto data2 = data; unsigned long elapsedScalar = 0ULL; // Pustime skalarni verzi { auto begin = steady_clock::now(); normaldist_scalar(0.0f, 1.0f, &data1[0], N); auto end = steady_clock::now(); elapsedScalar = duration_cast<microseconds>(end - begin).count(); printf("Cas skalarni verze: %dms \tspeedup 1x\n",elapsedScalar); } // Pustime vektorizovanou verzi { try { auto begin = steady_clock::now(); normaldist_vec(0.0f, 1.0f, &data2[0], N); auto end = steady_clock::now(); unsigned long elapsedVectorized = duration_cast<microseconds>(end - begin).count(); double speedup = (double) elapsedScalar / elapsedVectorized; printf("Cas vektorizovane verze: %dms \tspeedup %.2fx\n", elapsedVectorized, speedup); } catch(...){ printf("Cas vektorizovane verze: --- not implemented ---\n"); } } // Spocitame rozdily v approximaci double diff = 0.0f; for(unsigned int i = 0 ; i < N ; i++) { double cdiff = (double)data1[i] - (double)data2[i]; diff += (cdiff < 0 ? -cdiff : cdiff); } printf("Absolutni chyba vypoctu: %.2f\n",diff); return 0; }
true
933f1ead18cd979f219c6b4da0af9e2cd4db3b65
C++
muon012/principlesAndPractices
/Chapter_4/exercise_7.cpp
UTF-8
2,579
4.46875
4
[]
no_license
// Modify exercise 5 to accept spelled words as well as digits // This program does not catch the errors. #include<iostream> #include<string> #include<vector> using std::cout; using std::cin; using std::endl; using std::vector; using std::string; int return_digit(string s, vector<string> words){ for(int i = 0; i < words.size(); ++i){ if( s == words[i]){ return i; } } return -1; } int return_integer(string s, vector<int> digits){ for(int i=0; i < digits.size(); ++i){ if(stoi(s) == digits[i]){ return i; } } return -1; } int main(void){ vector<int> numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; vector<string> words = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}; // Declare the variables. string num_1{}; string num_2{}; char oper{' '}; double result{}; cout << "Enter two digits followed by an operator (+, -, *, /): "; cin >> num_1 >> num_2 >> oper; // Try to convert the string inputs into int types. int var_1 = return_digit(num_1, words); // Check if input was written as word. if(var_1 == -1){ // If it wasn't written as a word, then try to change it into an int type. var_1 = return_integer(num_1, numbers); } // Repeat previous steps for the second input. int var_2 = return_digit(num_2, words); if(var_2 == -1){ var_2 = return_integer(num_2, numbers); } // If both inputs were successfully changed into int types, then proceed as normal. if(var_1 != -1 && var_2 != -1){ switch(oper){ case '+': result = var_1 + var_2; cout << "The sum of " << num_1 << " and " << num_2 << " is " << result << endl; break; case '-': result = var_1 - var_2; cout << "The difference of " << num_1 << " and " << num_2 << " is " << result << endl; break; case '*': result = var_1 * var_2; cout << "The product of " << num_1 << " and " << num_2 << " is " << result << endl; break; case '/': result = double(var_1) / var_2; cout << "The quotient of " << num_1 << " and " << num_2 << " is " << result << endl; break; default: cout << "Sorry, I didn't understand you." << endl; break; } } else{ cout << "Something went wrong." << endl; } return 0; }
true
a0e9fba6b08a3a31b55b0991642ebafc0f4021ae
C++
pkuwangh/leetcode
/p122_best_time_to_trade_stock_2/best_time_to_trade_stock_2.cc
UTF-8
1,503
3.796875
4
[]
no_license
/* Say you have an array for which the ith element is the price of a given stock on day i. * * Design an algorithm to find the maximum profit. * You may complete as many transactions as you like * (ie, buy one and sell one share of the stock multiple times). * However, you may not engage in multiple transactions at the same time * (ie, you must sell the stock before you buy again). */ #include <iostream> #include <vector> using namespace std; class Solution { public: int maxProfit(vector<int>& prices) { if (prices.size() == 0) return 0; int aggr_profit = 0; int hold_price = -1; int last_price = prices[0]; for (unsigned int i = 1; i < prices.size(); ++i) { if (prices[i] < last_price) { if (hold_price >= 0) { // sell at last point aggr_profit += (last_price - hold_price); hold_price = -1; } } else { // buy at last point if (hold_price < 0) { hold_price = last_price; } } last_price = prices[i]; } if (hold_price >= 0) { aggr_profit += (last_price - hold_price); } return aggr_profit; } int maxProfitHelper(vector<int> prices) { return maxProfit(prices); } }; int main() { Solution obj; cout << obj.maxProfitHelper({2, 1, 2, 0, 1}) << endl; return 0; }
true
01298a4bda53b57a6a92d5f23be8506927a71781
C++
deskmel/online-judge-for-sjtu
/1206.cpp
UTF-8
969
2.890625
3
[]
no_license
#include <iostream> #include <string.h> using namespace std; int stack[40000]; int stack1[40000]; int top1=-1,top2=-1; char tmp[10000]; int main(int argc, char const *argv[]) { for (int i=0;i<40000;i++) stack[i]=-1; bool flag=true; while (cin>>tmp) { if (strcmp(tmp,"begin")==0) { stack[++top1]=0; } else if (strcmp(tmp,"if")==0) stack[++top1]=1; else if (strcmp(tmp,"then")==0) { if (top1==-1 || stack[top1]!=1) { flag=false; } else stack[top1]=2; } else if (strcmp(tmp,"end")==0) { do { if (top1==-1 || stack[top1]==1) { flag=false;break; } if (stack[top1--]==0) break; } while (true); if (!flag) break; } else if (strcmp(tmp,"else")==0) { if (top1==-1 || stack[top1--]!=2) flag=false; } if (!flag) break; } while (flag and top1!=-1) { if (stack[top1--]!=2) flag=false; } if (flag) cout << "Match!" << '\n'; else cout << "Error!" << '\n'; return 0; }
true
313d0510ce96f33f197415b8152229f9c83929db
C++
CarlosBravo00/CPlusPlusProjects
/Deportivo/Cancha.h
UTF-8
1,733
3.25
3
[]
no_license
#ifndef CANCHA_H_INCLUDED #define CANCHA_H_INCLUDED class Cancha:public Servicio{ public: Cancha(); Cancha(double costo,int maxpers, string deporte, string clave, int tiempoMax,char tipo); double getCostoXHr(); int getCantMaxPers(); string getDeporte(); void setCostoXHr(double costo); void setCantMaxPers(int cant); void setDeporte (string depor); void muestra(); double calculaCosto(int tiempo); private: double costoXHr; int cantMaxPers; string Deporte; }; Cancha::Cancha():Servicio(){ costoXHr=0; cantMaxPers=0; Deporte=""; } Cancha::Cancha(double costo,int maxpers, string deporte, string clave, int tiempoMax,char tipo):Servicio(clave,tiempoMax,tipo){ costoXHr=costo; cantMaxPers=maxpers; this->Deporte=deporte; } double Cancha::getCostoXHr(){ return costoXHr; } int Cancha::getCantMaxPers(){ return cantMaxPers; } string Cancha::getDeporte(){ return Deporte; } void Cancha::setCostoXHr(double costo){ costoXHr=costo; } void Cancha::setCantMaxPers(int cant){ cantMaxPers=cant; } void Cancha::setDeporte (string depor){ Deporte=depor; } void Cancha::muestra(){ cout<<"Servicio: Cancha"; cout<<"\nTipo: "; if(tipo=='T'){ cout<<"Cancha Tenis"; } else if(tipo=='F'){ cout<<"Cancha Fronton"; } else if(tipo=='V'){ cout<<"Cancha Volley Ball"; } cout<<"\nClave: "<<clave<<"\nTiempo Max: "<<tiempoMax; cout<<"\nDeporte: "<<Deporte<<"\nCantidad maxima de personas: "<<cantMaxPers<<"\nCosto por hora: "<<costoXHr; } double Cancha::calculaCosto(int tiempo){ double tiempodouble=tiempo; tiempodouble=tiempodouble/60; return tiempodouble*costoXHr; } #endif // CANCHA_H_INCLUDED
true