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
04468615bce1c6cdecb5194ce411fd8b8aed2a93
C++
liruida/kaoyan-data-structure
/00-Keypoint_in_WangDao/Chapter_05-Tree/00-Binary_Tree/00-Basic_Binary_Tree/01-Create_BiTree/03-Full_BiTree_PreOrder_to_PostOrder.cpp
UTF-8
1,114
3.65625
4
[ "MIT" ]
permissive
#include <iostream> using namespace std; typedef char ElemType; void printArray(ElemType arr[], int length) { for (int i = 0; i < length; i++) cout << arr[i] << " "; cout << endl; } // 满二叉树 // 根据先序遍历序列,得到后序遍历序列 void preToPost(ElemType preOrder[], int preOrderSize, ElemType postOrder[], int postOrderSize) { if (postOrderSize <= 0) return; postOrder[postOrderSize - 1] = preOrder[0]; int half = preOrderSize / 2; // 满二叉树结点数一定是奇数,因此不用考虑奇偶数的问题; preToPost(preOrder + 1, half , postOrder, half); // 左子树 preToPost(preOrder + 1 + half, preOrderSize - (half + 1), postOrder + half, postOrderSize - (half + 1)); // 右子树 } void test(ElemType arr[], int length) { ElemType postOrder[length]; preToPost(arr, length, postOrder, length); printArray(postOrder, length); } int main() { ElemType arr[] = {'A','B','C','D','E','F','G'}; int length = sizeof(arr) / sizeof(arr[0]); test(arr, length); return 0; } // 运行结果: // C D B F G E A
true
a20b17265eae6aa18fa73839c691acd120ca3896
C++
pzenie1/Pipeline
/Project1/Clipper.cpp
UTF-8
3,475
3.0625
3
[]
no_license
// // Clipper.cpp // // Created by Warren R. Carithers on 01/15/14. // Based on a version created by Joe Geigel on 11/30/11. // Copyright 2014 Rochester Institute of Technology. All rights reserved. // // Contributor: Paul Zenie, pxz5572 // #include "Vertex.h" #include "Clipper.h" /// // Simple module that performs clipping /// /// // Constructor /// Clipper::Clipper() { } /* Finds if a point is inside in reference to an edge */ bool inside(Vertex s, Vertex bound0, Vertex bound1) { if (bound0.x == bound1.x) { if (bound1.y > bound0.y) { return s.x <= bound0.x; } else if(bound0.y > bound1.y) { return s.x >= bound0.x; } } else { if (bound1.x > bound0.x) { return s.y >= bound0.y; } else if (bound0.x > bound1.x) { return s.y <= bound0.y; } } return false; } /* Finds the point where the line between p and s instersects the edge Which is the line from bound0 to bound1 */ Vertex intersect(Vertex p, Vertex s, Vertex bound0, Vertex bound1) { Vertex intersect; if (bound0.x == bound1.x) { intersect.x = bound0.x; intersect.y = p.y + (bound0.x - p.x) * (s.y - p.y) / (s.x - p.x); } else { intersect.y = bound0.y; intersect.x = p.x + (bound0.y - p.y) * (s.x - p.x) / (s.y - p.y); } return intersect; } void SHCP(const Vertex inV[], Vertex outV[], int in, int &out, Vertex bound0, Vertex bound1) { //out = 0; Vertex p = inV[in - 1]; for (int j = 0; j < in; j++) { Vertex s = inV[j]; if (inside(s, bound0, bound1)) { if (inside(p, bound0, bound1)) // if point inside in ref to edge keep it { outV[out] = s; out++; } else // if point comes inside find intersect and add it to vector array { Vertex i = intersect(p, s, bound0, bound1); outV[out] = i; out++; outV[out] = s; out++; } } else { if (inside(p, bound0, bound1)) { Vertex i = intersect(p, s, bound0, bound1); outV[out] = i; out++; } } p = s; } } /// // clipPolygon // // Clip the polygon with vertex count in and vertices inV against the // rectangular clipping region specified by lower-left corner ll and // upper-right corner ur. The resulting vertices are placed in outV. // // The routine should return the with the vertex count of polygon // resulting from the clipping. // // @param in the number of vertices in the polygon to be clipped // @param inV the incoming vertex list // @param outV the outgoing vertex list // @param ll the lower-left corner of the clipping rectangle // @param ur the upper-right corner of the clipping rectangle // // @return number of vertices in the polygon resulting after clipping // /// int Clipper::clipPolygon( int in, const Vertex inV[], Vertex outV[], Vertex ll, Vertex ur ) { int out = 0; Vertex *out1, *out2, *out3; // vertex arrays to hold intermediate vertices Vertex bound; // edge of clipping box bound.x = ur.x; bound.y = ll.y; SHCP(inV, outV, in, out, ll, bound);//call shcp for each edge in = out; out1 = new Vertex[out*out]; out = 0; SHCP(outV, out1, in, out, bound, ur); in = out; out2 = new Vertex[out*out]; out = 0; bound.x = ll.x; bound.y = ur.y; SHCP(out1, out2, in, out, ur, bound); in = out; out3 = new Vertex[out*out]; out = 0; SHCP(out2, out3, in, out, bound, ll); for (int i = 0; i < out; i++) //populate outV with correct vertices { outV[i] = out3[i]; } delete[] out1, out2, out3; return( out ); // remember to return the outgoing vertex count! }
true
b60a2387ef9cfd810f86e317616da4f30b7815ee
C++
givenone/practice
/groom/cost.cpp
UTF-8
429
2.78125
3
[]
no_license
#include<iostream> #include<algorithm> using namespace std; int interval[3000]; int num[3000]; int main() { int N, K; cin >> N >> K; for(int i=0; i<N;i++) cin >> num[i]; for(int i=0; i<N-1;i++) interval[i] = num[i+1]-num[i]; sort(interval, interval + N-1); // 0 ~ N-2 (N-1개) int sum = 0; for(int i=1; i <= K-1; i++) sum += interval[N-i-1]; cout << (num[N-1]-num[0] - sum) << endl; }
true
ed6819adb251d941ae486201bc694f0b367d27e7
C++
nicolaslopez99/lista
/main.cpp
UTF-8
1,418
3.65625
4
[]
no_license
#include <iostream> using namespace std; int main(){ lista a; int aux=0; int n; int valor; int pos; do{ cout<<"1.Saber el tamano de la lista"<<endl; cout<<"2.Saber si la lista esta vacia"<<endl; cout<<"3.Ingresar un nuevo elemento"<<endl; cout<<"4.Ingresar un nuevo elemento al final de la lista"<<endl; cout<<"5.Mostrar la lista"<<endl; cout<<"6.Eliminar elemento"<<endl; cout<<"7.Mostrar un elemento de la lista"<<endl; cout<<"8.Salir del menu"<<endl; cin>>n; if(n==1){ cout<<"EL tamano de la lista es: "<<a.tamano_lista()<<endl; }else if(n==2){ if(a.lista_vacia()==0){ cout<<"La lista no esta vacia"<<endl; } else{ cout<<"La lista esta vacia"<<endl; } } else if(n==3){ cout<<"Ingrese el nuevo valor y la posicion en la que se encuentra "<<endl; cin>>valor; cin>>pos; a.insertar(valor,pos); }else if(n==4){ cout<<"Ingrese el nuevo valor "<<endl; cin>>valor; a.insertar_final(valor); }else if(n==5){ cout<<"La lista es "<<endl; a.imprimir_lista(); } else if(n==6){ cout<<"Ingresar la posicion que desea eliminar "<<endl; cin>>pos; a.eliminar(pos); }else if(n==7){ cout<<"Ingresar la posicion que desea ver "<<endl; cin>>pos; a.imprimir_dato(pos); }else if(n==8){ aux=aux+1; } else{ cout<<"Opcion incorrecta"<<endl; } }while(aux==0); return 0; }
true
0ba16a51f535988f5e02ec0e3d6bf57f6984651c
C++
DronMDF/zond
/http/HttpHeader.cpp
UTF-8
973
2.5625
3
[ "MIT" ]
permissive
// Copyright (c) 2018-2019 Andrey Valyaev <dron.valyaev@gmail.com> // // This software may be modified and distributed under the terms // of the MIT license. See the LICENSE file for details. #include "HttpHeader.h" #include <regex> using namespace std; HttpHeader::HttpHeader(const string &header) : header(header) { } string HttpHeader::method() const { smatch match; regex rx(R"(^([A-Z]+)\s+)"); if (regex_search(header, match, rx)) { return match[1]; } throw runtime_error("Incorrect HTTP header format"); } string HttpHeader::uri() const { smatch match; regex rx(R"(^[A-Z]+\s+(.*)\s+HTTP/)"); if (regex_search(header, match, rx)) { return match[1]; } throw runtime_error("Incorrect HTTP header format"); } string HttpHeader::getField(const string &name, const string &default_value) const { smatch match; regex rx(R"(\r\n)" + name + R"(:\s+(.*)\s*\r\n)", regex_constants::icase); if (regex_search(header, match, rx)) { return match[1]; } return default_value; }
true
91fa01c41d498af63777c9908db761d41958d4f7
C++
mvlahovi/Home-Weather-Station
/IndoorUnit/lib/Adafruit_FRAM_I2C-master/Adafruit_EEPROM_I2C.cpp
UTF-8
4,505
2.921875
3
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
/**************************************************************************/ /*! * @file Adafruit_EEPROM_I2C.cpp */ /**************************************************************************/ #include <math.h> #include <stdlib.h> #include "Adafruit_EEPROM_I2C.h" /*========================================================================*/ /* CONSTRUCTORS */ /*========================================================================*/ /**************************************************************************/ /*! Constructor */ /**************************************************************************/ Adafruit_EEPROM_I2C::Adafruit_EEPROM_I2C(void) {} /*========================================================================*/ /* PUBLIC FUNCTIONS */ /*========================================================================*/ /*! * @brief Sets up the hardware and initializes I2C * @param addr * The I2C address to be used. * @param theWire * The Wire object to be used for I2C connections. * @return True if initialization was successful, otherwise false. */ bool Adafruit_EEPROM_I2C::begin(uint8_t addr, TwoWire *theWire) { i2c_addr = addr; _wire = theWire; _wire->begin(); // A basic scanner, see if it ACK's _wire->beginTransmission(i2c_addr); if (_wire->endTransmission() == 0) { return true; } return false; } /**************************************************************************/ /*! @brief Writes a byte at the specific EEPROM address @param[in] addr The 16-bit address to write to in EEPROM memory @param[in] value The 8-bit value to write at addr */ /**************************************************************************/ void Adafruit_EEPROM_I2C::write8(uint16_t addr, uint8_t value) { _wire->beginTransmission(i2c_addr); _wire->write(addr >> 8); _wire->write(addr & 0xFF); _wire->write(value); _wire->endTransmission(); // Wait until it acks! while (1) { _wire->beginTransmission(i2c_addr); if (_wire->endTransmission() == 0) { return; } delay(1); } } /**************************************************************************/ /*! @brief Reads an 8 bit value from the specified EEPROM address @param addr The 16-bit address to read from in EEPROM memory @returns The 8-bit value retrieved at addr */ /**************************************************************************/ uint8_t Adafruit_EEPROM_I2C::read8(uint16_t addr) { _wire->beginTransmission(i2c_addr); _wire->write(addr >> 8); _wire->write(addr & 0xFF); _wire->endTransmission(); size_t recv = _wire->requestFrom(i2c_addr, (uint8_t)1); if (recv != 1) { return 0; } return _wire->read(); } /*************************************************************************/ uint16_t Adafruit_EEPROM_I2C::write16(uint16_t addr, uint16_t value) { write8 (addr, (uint8_t)(value>>8)); write8 (addr+1, (uint8_t)(value & 0x00FF)); /* uint8_t* p; p = (uint8_t*) &value; uint16_t i; _wire->beginTransmission(i2c_addr); _wire->write(addr >> 8); _wire->write(addr & 0xFF); for (i = 0; i < 2; i++) { _wire->write(*p); p++; } _wire->endTransmission(); // Wait until it acks! while (1) { _wire->beginTransmission(i2c_addr); if (_wire->endTransmission() == 0) { return i; } delay(1); } return i; */ } uint16_t Adafruit_EEPROM_I2C::read16(uint16_t addr) { uint16_t i; i = ((uint16_t)read8 (addr)) << 8; i = i | ((uint16_t)read8 (addr + 1) & 0x00FF); return i; /* uint8_t* p; p = (uint8_t*) &value; uint16_t i; _wire->beginTransmission(i2c_addr); _wire->write(addr >> 8); _wire->write(addr & 0xFF); _wire->endTransmission(); _wire->requestFrom(i2c_addr,sizeof(value)); for (i = 0; i < 2; i++) if(_wire->available()) *p++ = _wire->read(); return i; */ } ///////////////////////////////////////////////////////////////////// uint32_t Adafruit_EEPROM_I2C::read32(uint16_t addr) { uint32_t data; data = ((uint32_t)read16( addr )) <<16; data = data | (((uint32_t)read16( addr + 2 )) & 0x0000FFFF); return ( data); } void Adafruit_EEPROM_I2C::write32(uint16_t addr, uint32_t data) { write16( addr, (uint16_t)((data >> 16) & 0x0000FFFF)); write16( addr+2, (uint16_t)(data & 0x0000FFFF)); }
true
dce0aba2142cd6a2eae33d50a9c4e0aa3687b182
C++
AleChelli/oF_Project
/RandomWalkerMouse/RandomWalker.cpp
UTF-8
453
2.875
3
[]
no_license
#include "RandomWalker.h" RandomWalker::RandomWalker(){ x= ofGetWindowWidth()/2; y=ofGetWindowHeight()/2; } void RandomWalker::display(){ ofSetColor(ofColor::black); ofVertex(x,y,0); } void RandomWalker::step(){ int choice = int(random(4)); if (choice == 0){ x++; } else if (choice==1){ x--; } else if (choice==2) { y++; } else { y--; } }
true
9d4031f3eda57407efdf29a7b39b7e3cfa85e6f8
C++
FilipaDurao/Advent-Of-Code-2016
/Day5/Day5 Part1.cpp
UTF-8
823
2.859375
3
[]
no_license
/* * Day5 Part1.cpp * * Created on: 03/11/2017 * Author: filipa */ #include <iostream> #include "md5.h" using namespace std; bool checkIf5Zeros(string hashed){ if(hashed.substr(0,5) == "00000"){ return true; } else return false; } int main(){ string password = "", input = "ojvtpuvg"; string character; int counter = 367403; unsigned int index; while (true){ character = input; character += to_string(counter); if (checkIf5Zeros(md5(character))){ password += md5(character)[5]; cout << "\n\n\n\n\nELEMENT\n\n\n\n\n" << endl; if(password.size() == 8){ break; } } else{ index = character.find_last_of(to_string(counter)); character.erase(index, to_string(counter).size()); } cout << counter << endl; counter++; } cout << password; }
true
51334bffd73ad805427efba86696d96afd9a9ff2
C++
yjfdl123/unix
/01multithread/download.cpp
UTF-8
1,134
2.84375
3
[]
no_license
#include <iostream> #include <stdio.h> #include <pthread.h> #include <unistd.h> #include <semaphore.h> using namespace std; sem_t sem; void* downloader(void* data) { if (sem_wait(&sem) == 0){ printf("tid:%ld\t begin\n",pthread_self()); sleep(5); printf("tid:%ld\t end\n",pthread_self()); sem_post(&sem); }else{ printf("tid:%ld\t fail\n",pthread_self()); } return (void*)0; } void control_download() { int tnum=5; int maxdnum = 2; if (sem_init(&sem, 0, maxdnum)==0){ cout<<"succ"<<endl; }else{ cout<<"fail"<<endl; } int snum = 0; sem_getvalue(&sem, &snum); cout<<"snum:"<<snum<<endl; pthread_t threads[tnum]; for (int i=0;i<tnum;i++) { int ret = pthread_create( &threads[i], NULL, downloader, NULL); if (ret == -1) { printf("%dth bad\n",i); } } void * ret; for (int i=0;i<tnum;i++){ pthread_join(threads[i],NULL); } sem_destroy(&sem); } int main() { cout<<"downloader:"<<endl; int totalbytes = 0; control_download(); return 0; }
true
922afcd8efdbf0e60fd8ef1b243d8a5fa8235577
C++
hanmon/ameba-arduino-samples
/ReedRelay/build/sketch/ReedRelay.ino.cpp
UTF-8
1,334
2.578125
3
[]
no_license
#include <Arduino.h> #line 1 "d:\\project\\ameba-arduino-samples\\ReedRelay\\ReedRelay.ino" const int reedPin=3,ledPin=9,buzzerPin=4; static bool lastState; #line 3 "d:\\project\\ameba-arduino-samples\\ReedRelay\\ReedRelay.ino" void setup(); #line 13 "d:\\project\\ameba-arduino-samples\\ReedRelay\\ReedRelay.ino" void loop(); #line 29 "d:\\project\\ameba-arduino-samples\\ReedRelay\\ReedRelay.ino" int checkReedRelayState(); #line 3 "d:\\project\\ameba-arduino-samples\\ReedRelay\\ReedRelay.ino" void setup() { pinMode(reedPin,INPUT); pinMode(ledPin,OUTPUT); pinMode(buzzerPin,OUTPUT); Serial.begin(115200); Serial.print("Example:ReedRelay"); lastState=digitalRead(reedPin); } void loop() { switch(checkReedRelayState()){ case 1: Serial.println("Door Opened"); digitalWrite(ledPin,HIGH); digitalWrite(buzzerPin,HIGH); break; case 2: Serial.println("Door Closed"); digitalWrite(ledPin,LOW); digitalWrite(buzzerPin,LOW); break; } } int checkReedRelayState(){ if(digitalRead(reedPin)!=lastState){ delay(20); if(digitalRead(reedPin)!=lastState){ lastState=digitalRead(reedPin); return lastState?1:2; } } else return 0; }
true
79003c032f3e6def1d59b296a425a4d08c1706e8
C++
jonmarinello/hammerhead
/HhUnitTestFramework/utHhUnitTestFramework/utHhUnitTestFramework.cpp
UTF-8
2,783
2.9375
3
[]
no_license
/* * Copyright (c) 2003-2005, Jon Marinello * */ #include <HhUnitTestFramework/UnitTest.h> class UtHhUnitTest : public HH_UnitTest { public: UtHhUnitTest( bool& variableDataGeneration, bool interactive ) : HH_UnitTest( variableDataGeneration, interactive ), m_stringValue( "defaultStringValue" ), m_boolValue( true ) {} protected: virtual void TestCommands(); virtual void HelpForTestCommands(); private: bool m_boolValue; std::string m_stringValue; }; void UtHhUnitTest::HelpForTestCommands() { std::cout << "SetBool <bool> - saves away a bool in a member variable." << std::endl << std::endl; std::cout << "GetBool - displays the bool member variable." << std::endl << std::endl; std::cout << "SetStringValue <string> - saves away stringValue as a member variable." << std::endl << std::endl; std::cout << "GetStringValue - displays the _stringValue member variable." << std::endl << std::endl; std::cout << "TestMultipleParams \"<multiple token string>\" <string> <intNumber> <doubleNumber> - tests use of multiple test arguments." << std::endl << std::endl; } void UtHhUnitTest::TestCommands() { HH_TESTCMD( "SetBool" ) { HH_TESTCMD_PARAM( bool, boolValue ); m_boolValue = boolValue; } HH_TESTCMD( "GetBool" ) { std::cout << m_boolValue << std::endl; } HH_TESTCMD( "SetStringValue" ) { HH_TESTCMD_PARAM( std::string, stringValue ); m_stringValue = stringValue; } HH_TESTCMD( "GetStringValue" ) { std::cout << m_stringValue << std::endl; } HH_TESTCMD( "TestMultipleParams" ) { HH_TESTCMD_PARAM( HH_MultiTokenString, multiTokenString ); HH_TESTCMD_PARAM( std::string, string ); HH_TESTCMD_PARAM( bool, boolValue ); HH_TESTCMD_PARAM( int, intNumber ); HH_TESTCMD_PARAM( double, doubleNumber ); std::cout << "multiTokenString = " << multiTokenString << std::endl; std::cout << "string = \"" << string << "\"" << std::endl; std::cout << "boolValue = " << boolValue << std::endl; std::cout << "intNumber = " << intNumber << std::endl; std::cout << "doubleNumber = " << doubleNumber << std::endl; } HH_TESTCMD( "Test2MultiTokenStrings" ) { HH_TESTCMD_PARAM( HH_MultiTokenString, multiTokenString1 ); HH_TESTCMD_PARAM( HH_MultiTokenString, multiTokenString2 ); std::cout << "multiTokenString1 = " << multiTokenString1 << std::endl; std::cout << "multiTokenString2 = " << multiTokenString2 << std::endl; } } void main( int argc, char*[] ) { bool variableDataGeneration = false; UtHhUnitTest utHhUnitTest( variableDataGeneration, argc == 1 ); utHhUnitTest.Run(); }
true
c42e468301ca8399cead71d346e499edcf6fe599
C++
technopizza/kdesrosiers_jaconklin_PA5
/pa5kms/bank.cpp
UTF-8
5,406
2.984375
3
[]
no_license
/* * bank.cpp * * Created on: Oct 4, 2018 * Author: kdesrosiers */ #include <iostream> #include <cstdlib> #include <cmath> #include "teller.h" #include "customer.h" #include "tellerevent.h" #include "customerevent.h" #include <time.h> #include "tellerqueue.h" #include "eventqueue.h" using namespace std; const int MAXIDLE = 150; int numOfCustomers; //number of customers in simulation. int numOfTellers; //# of tellers in simulation float simTime; //total simulation time in minutes float avgServiceTime; //average time spent with each customer unsigned int seed; float simClock = 0; //the clock for keeping track of the time float waitTime = 0; float totalServiceTime = 0; //total amount of service time int totalTellerIdleTime = 0; //total amount of teller idle time int main(int argc, char** argv) { //if # of arguments greater than or equal to 5 and less than 7 if (argc >= 5 && argc <= 7) { numOfCustomers = atoi(argv[1]); //numOfCustomers is the 2nd argument numOfTellers = atoi(argv[2]); //numOfTellers is the 3rd argument simTime = atof(argv[3]); //simTime is the 4th argument avgServiceTime = atof(argv[4]); //avgServiceTime is the 5th argument seed = time(0); } //if not any of above, error else { cout << "unexpected number of arguments!!" << endl; return EXIT_FAILURE; } //if the # of arguments is 7, use a seed if (argc == 7) { seed = atoi(argv[5]); } //After getting seed input or generating a seed, use seed for RNG srand(seed); //initialize teller queue to store customers TellerQueue *onlyLine = new TellerQueue(); //initialize EventQueue to stor customer events EventQueue* eventqueue = new EventQueue(numOfCustomers); Customer* tmpCustomer; //placeholder pointer for initializing each new customer //Initiialize all customers (and thus their events) for (int i = 0; i < numOfCustomers; i++) { tmpCustomer = new Customer(simTime * (rand() / float(RAND_MAX))); eventqueue->enqueue(tmpCustomer->getArrival()); } //add all customers to tellerqueue by pulling and running event actions from event priority queue while (eventqueue->size() > 0) { eventqueue->dequeue()->action(onlyLine); } //initialize array for storing customer wait times float waitTimes[numOfCustomers] = { 0 }; //initialize array for tracking individual teller status float tellerLastPriority[numOfTellers] = { 0 }; int idx = 0; //index to track current customer in wait times array //continue pulling from tellerqueue until no more customers while (onlyLine->sizeOfQueue() > 0) { //pop customer off of queue, save arrival time float arrivalTime = onlyLine->removeFromLine()->getArrival()->getPriority(); cout << "Customer" << idx << " arrives at " << arrivalTime << " minutes" << endl; if (arrivalTime < simTime) { //discard customers who arrive after closing int i = 0; //index for finding open teller int minIdx = i; //variable to store index of open teller float start = tellerLastPriority[i]; //cout << "Priority of Teller" << i << ": " << tellerLastPriority[i] << endl; //search for teller with min value to ensure shortest wait time if (numOfTellers > 1) { i = 1; while (i < numOfTellers) { if (tellerLastPriority[i] < start) { minIdx = i; } //cout << "Priority of Teller" << minIdx << ": " << tellerLastPriority[i] << endl; i++; } } start = tellerLastPriority[minIdx]; //cout << "END Finding lowest prioirty line" << endl; //customer arrived before teller was open if (arrivalTime <= start) { waitTimes[idx] += start - arrivalTime; cout << " He/She goes to teller" << minIdx << " at " << start << " minutes." << endl; cout << " He/She waited in line for " << (start - arrivalTime) << " minutes." << endl; } else { //customer arrived and teller was open float tellerIdleTime = arrivalTime - start; totalTellerIdleTime += tellerIdleTime; start = arrivalTime; cout << " He/She goes to teller" << minIdx << " at " << start << " minutes." << endl; cout << " Teller" << minIdx << " has been unoccupied for " << tellerIdleTime << " minutes." << endl; } //compute random service time based on input, and update arrays float serviceTime = 2 * avgServiceTime * rand() / float(RAND_MAX); cout << " It took Teller" << minIdx << " " << serviceTime << " minutes to serve Customer" << idx << endl; waitTimes[idx] += serviceTime; totalServiceTime += serviceTime; tellerLastPriority[minIdx] += (start + serviceTime); } else { numOfCustomers--; //if customers with invalidly high priority come, exclude them from array } idx++; } //calculate average and standard deviation of wait times waitTime = 0; for (int i = 0; i < numOfCustomers; i++) { waitTime += waitTimes[i]; } float avgWaitTime = waitTime / numOfCustomers; float stdSumSquaredDiffs = 0; for (int i = 0; i < numOfCustomers; i++) { stdSumSquaredDiffs += pow((waitTimes[i] - avgWaitTime), 2); } float std = sqrt(stdSumSquaredDiffs / numOfCustomers); cout << "Number of customers served: " << numOfCustomers << endl; cout << "Number of tellers: " << numOfTellers << endl; cout << "Total teller service time: " << totalServiceTime << endl; cout << "Total teller idle time: " << totalTellerIdleTime << endl; cout << "The mean customer wait time was " << avgWaitTime << " with a standard deviation of " << std << endl; return 0; }
true
3f0f11c6eefa8cf9a72e4b6992037afe4195443b
C++
buptlxb/leetcode-utility
/include/tester.h
UTF-8
877
2.546875
3
[]
no_license
#ifndef TESTER_H #define TESTER_H #include <cassert> #include <lc_config.h> #include <iostream> __LC_NAMESPACE_BEGIN struct Verify; class Tester { friend Verify; static int livecount; const Tester* self; public: Tester() :self(this) {++livecount;} Tester(const Tester&) :self(this) {++livecount;} ~Tester() {assert(self==this);--livecount;} Tester& operator=(const Tester& b) { assert(self==this && b.self == &b); return *this; } void cfunction() const {assert(self==this);} void mfunction() {assert(self==this);} friend std::ostream &operator<< (std::ostream &os, const Tester &t) { os << typeid(t).name() << "@" << std::hex << t.self << std::dec; return os; } }; int Tester::livecount=0; struct Verify { ~Verify() { assert(Tester::livecount==0); } }varifier; __LC_NAMESPACE_END #endif
true
31ddc2e5bd46925e96091817a4b496751562c88a
C++
mzry1992/workspace
/OJ/CDOJ/Ideal Path.cpp
UTF-8
1,606
2.65625
3
[]
no_license
#include <iostream> #include <cstring> #include <cstdio> #include <queue> using namespace std; struct Edge { int to,c,next; }; Edge edge[400000],nedge[400000]; queue<int> Q; int dis[100000],head[100000],nhead[100000],nL,L,n,m,u,v,c; void init(int n) { nL = L = 0; for (int i = 0;i < n;i++) { head[i] = nhead[i] = -1; dis[i] = 19921005; } } void addedge0(int u,int v,int c) { nedge[nL].to = v; nedge[nL].c = c; nedge[nL].next = nhead[u]; nhead[u] = nL++; } void addedge(int u,int v,int c) { edge[L].to = v; edge[L].c = c; edge[L].next = head[u]; head[u] = L++; } int pre[100000]; void Gao() { while (!Q.empty()) Q.pop(); dis[0] = 0; Q.push(0); int now; while (!Q.empty()) { now = Q.front(); Q.pop(); for (int i = nhead[now];i != -1;i = nedge[i].next) if (dis[nedge[i].to] > dis[now]+1) { dis[nedge[i].to] = dis[now]+1; Q.push(nedge[i].to); } } printf("%d\n",dis[n-1]); for (int i = 0;i < n;i++) for (int j = nhead[i];j != -1;j = nedge[j].next) if (dis[nedge[j].to] == dis[i]+1) addedge(i,nedge[j].to,nedge[j].c); } int main() { int t; scanf("%d",&t); for (int ft = 1;ft <= t;ft++) { scanf("%d%d",&n,&m); init(n); for (int i = 0;i < m;i++) { scanf("%d%d%d",&u,&v,&c); u--; v--; addedge0(u,v,c); addedge0(v,u,c); } Gao(); } return 0; }
true
1c5dd6282b5d8a34f776c1717d588fffaa0c4a8d
C++
JoeyTeng/OI
/Google Code Jam/2020/Round 1C/overrandomized.cpp
UTF-8
4,050
2.640625
3
[]
no_license
// Overrandomized #include <bits/stdc++.h> const int64_t QUERIES = 10000; auto input() { int64_t U = 0; std::vector<std::pair<int64_t, std::string>> query; std::cin >> U; for (int i = 0; i < QUERIES; ++i) { int64_t q; std::string r; std::cin >> q >> r; query.push_back(std::make_pair(q, r)); } return std::make_tuple(U, query); } template <typename T> auto processA(const T& inputs) { auto U = std::get<0>(inputs); auto records = std::get<1>(inputs); std::map<int, char> d2c; std::map<char, int> c2d; std::set<char> chars; std::sort(records.begin(), records.end()); std::queue<std::pair<int64_t, std::string>> qr; for (auto&& record : records) { qr.push(record); } // auto a = qr.front(); // std::cerr << a.first << ' ' << a.second << std::endl; // int64_t LOOP_COUNT = 0; while (!qr.empty()) { // LOOP_COUNT++; // if (LOOP_COUNT % 100 == 0) { // std::cerr << LOOP_COUNT // << "-th iteration: queue size: " << qr.size() // << std::endl; // } auto pair = qr.front(); qr.pop(); auto query = pair.first; auto response = pair.second; auto base = std::pow(10, response.size() - 1); for (auto&& c : response) { chars.insert(c); } if (query < std::pow(10, response.size() - 1)) { continue; } auto d = query / base; auto c = response[0]; if (c2d.find(c) != c2d.end()) { continue; } int counter = 0; int pos = -1; for (int i = 1; i <= d; ++i) { if (d2c.find(i) == d2c.end()) { counter++; pos = i; } } if (counter > 1) { qr.push(pair); } else { // counter == 1; d2c[pos] = c; c2d[c] = pos; } } for (auto&& c : chars) { if (c2d.find(c) == c2d.end()) { d2c[0] = c; c2d[c] = 0; break; } } std::string result; for (int i = 0; i < 10; ++i) { result.push_back(d2c[i]); } return result; } template <typename T> auto processB(const T& inputs) { auto U = std::get<0>(inputs); auto records = std::get<1>(inputs); std::map<char, int64_t> chars; std::set<char> non_zero; for (auto&& pair : records) { // LOOP_COUNT++; // if (LOOP_COUNT % 100 == 0) { // std::cerr << LOOP_COUNT // << "-th iteration: queue size: " << qr.size() // << std::endl; // } auto query = pair.first; auto response = pair.second; auto base = std::pow(10, response.size() - 1); for (auto&& c : response) { if (chars.find(c) == chars.end()) { chars[c] = 0; } chars[c]++; } if (query >= std::pow(10, response.size() - 1)) { non_zero.insert(response[0]); } } for (auto&& c : chars) { if (non_zero.find(c.first) == non_zero.end()) { chars[c.first] = INT_MAX; break; } } std::vector<std::pair<int64_t, char>> freq; for (auto&& pair : chars) { freq.push_back(std::make_pair(pair.second, pair.first)); } std::sort(freq.begin(), freq.end(), std::greater<>()); std::string result; for (auto&& pair : freq) { result.push_back(pair.second); } return result; } template <typename T> auto process(const T& inputs) { auto qr = std::get<1>(inputs); if (qr[0].first != -1) { return processA(inputs); } return processB(inputs); } int main() { int T = 0; std::cin >> T; for (auto i = 0; i < T; ++i) { auto tuple = input(); auto result = process(tuple); std::cout << "Case #" << i + 1 << ": " << result << std::endl; } return 0; }
true
838e1b1d727bbfd821be4451d75bb9ddedcfdb4f
C++
AllenWang0217/DesignPatterns
/TestHelper/TestBuilder.h
UTF-8
777
3.0625
3
[]
no_license
#pragma once #include "../BuilderPattern/Director.h" #include "../BuilderPattern/CBuilder1.h" #include "../BuilderPattern/CBuilder2.h" #include "../BuilderPattern/Product.h" class TestBuilder { public: TestBuilder() { IBuilder* builder = new CBuilder1(); Director* director = new Director(builder); director->Construct(); Product* product = builder->getProduct(); if (product == NULL){ std::cout << "The product is NULL" << endl;; } product->display(); builder = new CBuilder2(); director->setBuilder(builder); director->Construct(); product = builder->getProduct(); if (product == NULL) { std::cout << "The product is NULL" << endl;; } product->display(); delete builder; builder = NULL; delete director; director = NULL; } };
true
c270d3f77ee75124f353ca30b5a86922e562eee9
C++
Iviyan/RPGgame
/RPGgame/helper.cpp
WINDOWS-1251
8,036
3.203125
3
[]
no_license
#include "helper.h" int ReadInt(const char* text, std::function<bool(int i, string& msg)> pred, bool nl) { int val = 0; cout << text; while (1) { if (!(cin >> val)) { cin.clear(); cin.ignore(INT_MAX, '\n'); cout << " " << std::endl << "_> "; continue; } cin.ignore(INT_MAX, '\n'); string predMsg; if (pred != nullptr && !pred(val, predMsg)) { if (predMsg.empty()) cout << " "; else cout << predMsg; cout << std::endl << "> "; continue; } if (nl) cout << std::endl; return val; } } string ReadString(const char* text, std::function<bool(string s, string& msg)> pred, bool nl) { string val;; cout << text; while (1) { std::getline(cin, val); string predMsg; if (pred != nullptr && !pred(val, predMsg)) { if (predMsg.empty()) cout << " "; else cout << predMsg; cout << std::endl << "> "; continue; } if (nl) cout << std::endl; return val; } } int rnd(int min, int max) { static std::random_device rd; static std::mt19937 rng(rd()); std::uniform_int_distribution<int> uni(min, max); return uni(rng); } bool chance(int count, int of) { return rnd(count, of) <= count; } bool chance(int of) { return rnd(1, of) == 1; } using std::endl; void WriteEnhancement(Enhancement* enhancement) { switch (enhancement->Type) { case EnhancementType::Health: cout << ""; break; case EnhancementType::MagicPower: cout << " "; break; case EnhancementType::Mana: cout << ""; break; case EnhancementType::Attack: { AttackEnhancement* aenh = dynamic_cast<AttackEnhancement*>(enhancement); if (aenh == nullptr) { cout << ""; break; } switch (aenh->AttackType) { case AttackEnhancementType::GeneralAttack: cout << ""; break; case AttackEnhancementType::PhysicalAttack: cout << ". "; break; case AttackEnhancementType::MagicalAttack: cout << ". "; break; case AttackEnhancementType::SlashAttack: cout << " "; break; case AttackEnhancementType::StabAttack: cout << " "; break; case AttackEnhancementType::ColdAttack: cout << " "; break; case AttackEnhancementType::FireAttack: cout << " "; break; case AttackEnhancementType::LightningAttack: cout << " "; break; case AttackEnhancementType::SacredMagicAttack: cout << " "; break; } } break; case EnhancementType::Protection: { ProtectionEnhancement* penh = dynamic_cast<ProtectionEnhancement*>(enhancement); if (penh == nullptr) { cout << ""; break; } switch (penh->ProtectionType) { case ProtectionEnhancementType::GeneralProtection: cout << ""; break; case ProtectionEnhancementType::PhysicalProtection: cout << ". "; break; case ProtectionEnhancementType::MagicalProtection: cout << ". "; break; case ProtectionEnhancementType::SlashAttackProtection: cout << " "; break; case ProtectionEnhancementType::StabAttackProtection: cout << " "; break; case ProtectionEnhancementType::ColdProtection: cout << " "; break; case ProtectionEnhancementType::FireProtection: cout << " "; break; case ProtectionEnhancementType::LightningProtection: cout << " "; break; case ProtectionEnhancementType::SacredMagicProtection: cout << " "; break; } } break; } cout << " " << enhancement->Multiplier * 100 << "%"; } void WriteEnhancements(vector<Enhancement*>& enhancements, int indent) { for (Enhancement* enh : enhancements) { cout << string(indent, ' ') << "- "; WriteEnhancement(enh); cout << endl; } } void WriteArtifactInfo(Artifact* artifact, int indent) { cout/* << string(indent, ' ')*/ << artifact->Name << endl; cout << string(indent, ' ') << "- :" << endl; WriteEnhancements(artifact->Enhancements, indent + 1); cout << string(indent, ' ') << "- :" << endl; for (ActiveSkill* skill : artifact->ActiveSkills) cout << string(indent + 1, ' ') << "- " << skill->Name << endl; } void WriteActiveSkillInfo(ActiveSkill* skill) { cout << "*"; switch (skill->Type) { case ActiveSkillType::Attack: cout << ""; break; case ActiveSkillType::Buff: cout << ""; break; case ActiveSkillType::Debuff: cout << ""; break; } cout << "* - "; cout << skill->Name << ", ( " << skill->ManaUsage << "Mn, " << skill->StepsToRestore << " STR ) ( " << skill->Description << " )" << endl;; } void WritePassiveSkillInfo(PassiveSkill* skill) { cout << skill->Name << ", ( " << skill->Description << " )" << endl; } void WriteCharacterStats(Character* ch) { AdvancedCharacter* hero = dynamic_cast<AdvancedCharacter*>(ch); cout << ch->Name << " ( " << ch->GetLevel() << "L, "; if (hero != nullptr) cout << hero->GetExperience() << "/" << hero->GetRequiredExperience() << "Exp, "; if (ch->GetMaxHealth() != ch->GetHealth()) cout << ch->GetHealth() << "/"; cout << ch->GetMaxHealth() << "H, " << ch->GetProtection() << "Pr, " << ch->GetAttack() << "PD, " << ch->GetMagicPower() << "MD, "; if (ch->GetMaxMana() != ch->GetMana()) cout << ch->GetMana() << "/"; cout << ch->GetMaxMana() << "Mn )" << endl; } void WriteCharacterInfo(Character* ch, int indent) { WriteCharacterStats(ch); auto artifacts = ch->GetArtifactsList(); if (artifacts.size() > 0) { cout << string(indent, ' ') << ":" << endl; for (Artifact* art : artifacts) { cout << string(indent, ' ') << " - "; WriteArtifactInfo(art, indent + 2); } } auto askills = ch->GetActiveSkills(); if (askills.size() > 0) { cout << string(indent, ' ') << " :" << endl; for (ActiveSkill* askill : askills) { cout << string(indent, ' ') << " - "; WriteActiveSkillInfo(askill); } } auto pskills = ch->GetPassiveSkills(); if (pskills.size() > 0) { cout << string(indent, ' ') << " :" << endl; for (PassiveSkill* pskill : pskills) { cout << string(indent, ' ') << " - "; WritePassiveSkillInfo(pskill); } } } void WriteCharacterBattleInfo(GroupMember* gm) { Character* ch = gm->character; if (ch->IsDead()) { cout << ch->Name << " - " << endl; return; } cout << ch->Name << " ( " << ch->GetHealth() << "/" << ch->GetMaxHealth() << "H, " << ch->GetMana() << "/" << ch->GetMaxMana() << "Mn )"; if (gm->buffs.size() > 0 || gm->debuffs.size() > 0) { cout << " | "; for (Buff& buff : gm->buffs) cout << "+" << buff.buff->Name << "(" << buff.remainingSteps << "), "; for (Buff& debuff : gm->debuffs) cout << "-" << debuff.buff->Name << "(" << debuff.remainingSteps << "), "; cout << "|"; } cout << endl; } void WriteInventory(Inventory& inv) { Artifact* mainWeapon = inv.GetMainWeapon(); Artifact* additionalWeapon = inv.GetAdditionalWeapon(); if (mainWeapon != nullptr) { cout << " :" << endl << " "; WriteArtifactInfo(mainWeapon, 1); cout << endl; } if (additionalWeapon != nullptr) { cout << " :" << endl << " "; WriteArtifactInfo(additionalWeapon, 1); cout << endl; } if (inv.GetHelmet() != nullptr) { cout << ":" << endl << " "; WriteArtifactInfo(inv.GetHelmet(), 1); cout << endl; } if (inv.GetBreastplate() != nullptr) { cout << ":" << endl << " "; WriteArtifactInfo(inv.GetBreastplate(), 1); cout << endl; } if (inv.GetBoots() != nullptr) { cout << ":" << endl << " "; WriteArtifactInfo(inv.GetBoots(), 1); cout << endl; } }
true
8458cfae2b7a89fafe0c75517165d445c41c6b4c
C++
uechoco/CompetitionProgramming
/AtCoder/BeginnersSelection/Qiita/AGC012A.cpp
UTF-8
444
2.546875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main(){ int64_t n; cin >> n; std::vector<int64_t> a(3 * n, 0); for (int i = 0; i < 3 * n; ++i) { cin >> a[i]; } // 先頭から2つずつとっていったときの2つめの値がチームの強さ sort(a.begin(), a.end(), std::greater<int64_t>()); int64_t total = 0; for (int i = 0; i < n; ++i) { total += a[i * 2 + 1]; } cout << total << endl; return 0; }
true
b2f620703c54cdaa45c68c2287aa3ec00a62e1e0
C++
Coolchirutha/CP
/Step2/349.intersection-of-two-arrays.cpp
UTF-8
457
2.9375
3
[]
no_license
/* * @lc app=leetcode id=349 lang=cpp * * [349] Intersection of Two Arrays */ #include <bits/stdc++.h> using namespace std; // @lc code=start class Solution { public: vector<int> intersection(vector<int> &nums1, vector<int> &nums2) { set<int> hashmap(nums1.begin(), nums1.end()); vector<int> result; for (auto &i : nums2) { if (hashmap.erase(i)) { result.push_back(i); } } return result; } }; // @lc code=end
true
bcb641efaf6b11667a3a9d6203abe08ed6dec90b
C++
pointwind/PWL
/code/functional.h
GB18030
5,902
3.34375
3
[]
no_license
#pragma once #include<cstddef> namespace PWL { template<class Arg, class Result> struct Unarg_Function { using arguemnt_type = Arg; using result_type = Result; }; template<class Arg1,class Arg2,class Result> struct Binary_Function { using first_argument_type = Arg1; using second_argument_type = Arg2; using result_type = Result; }; template<class T> struct Plus : Binary_Function<T,T,T> { auto operator()(const T& lhs,const T& rhs) { return lhs + rhs; } }; template <class T> struct Minus :public Binary_Function<T, T, T> { T operator()(const T& x, const T& y) const { return x - y; } }; // 󣺳˷ template <class T> struct Multiplies :public Binary_Function<T, T, T> { T operator()(const T& x, const T& y) const { return x * y; } }; // 󣺳 template <class T> struct Divides :public Binary_Function<T, T, T> { T operator()(const T& x, const T& y) const { return x / y; } }; // ģȡ template <class T> struct Modulus :public Binary_Function<T, T, T> { T operator()(const T& x, const T& y) const { return x % y; } }; // 󣺷 template <class T> struct Negate :public Unarg_Function<T, T> { T operator()(const T& x) const { return -x; } }; // ӷ֤ͬԪ template<class T> auto Identity_Element(Plus<T>) { return T(0); } // ˷֤ͬԪ template <class T> auto Identity_Element(Multiplies<T>) { return T(1); } // 󣺵 template <class T> struct Equal_To :public Binary_Function<T, T, bool> { bool operator()(const T& x, const T& y) const { return x == y; } }; // 󣺲 template <class T> struct Not_Equal_To :public Binary_Function<T, T, bool> { bool operator()(const T& x, const T& y) const { return x != y; } }; // 󣺴 template <class T> struct Greater :public Binary_Function<T, T, bool> { bool operator()(const T& x, const T& y) const { return x > y; } }; // С template <class T> struct Less :public Binary_Function<T, T, bool> { bool operator()(const T& x, const T& y) const { return x < y; } }; // 󣺴ڵ template <class T> struct Greater_Equal :public Binary_Function<T, T, bool> { bool operator()(const T& x, const T& y) const { return x >= y; } }; // Сڵ template <class T> struct Less_Equal :public Binary_Function<T, T, bool> { bool operator()(const T& x, const T& y) const { return x <= y; } }; // ߼ template <class T> struct Logical_And :public Binary_Function<T, T, bool> { bool operator()(const T& x, const T& y) const { return x && y; } }; // ߼ template <class T> struct Logical_Or :public Binary_Function<T, T, bool> { bool operator()(const T& x, const T& y) const { return x || y; } }; // ߼ template <class T> struct Logical_Not :public Unarg_Function<T, bool> { bool operator()(const T& x) const { return !x; } }; // ֤ͬıԪأر template <class T> struct Identity :public Unarg_Function<T, bool> { const T& operator()(const T& x) const { return x; } }; // ѡһ pairصһԪ template <class Pair> struct Selectfirst :public Unarg_Function<Pair, typename Pair::first_type> { const typename Pair::first_type& operator()(const Pair& x) const { return x.first; } }; // ѡһ pairصڶԪ template <class Pair> struct Selectsecond :public Unarg_Function<Pair, typename Pair::second_type> { const typename Pair::second_type& operator()(const Pair& x) const { return x.second; } }; // ڴ󲿷ͣhash function ʲô template <class Key> struct Hash {}; template<class T> struct Hash<T*> { size_t operator()(T* p) const noexcept { return reinterpret_cast<size_t>(p); } }; // ֻͣǷԭֵ #define PWL_TRIVIAL_HASH_FCN(Type) \ template <> struct Hash<Type> \ { \ size_t operator()(Type val) const noexcept \ { return static_cast<size_t>(val); } \ }; PWL_TRIVIAL_HASH_FCN(bool) PWL_TRIVIAL_HASH_FCN(char) PWL_TRIVIAL_HASH_FCN(signed char) PWL_TRIVIAL_HASH_FCN(unsigned char) PWL_TRIVIAL_HASH_FCN(wchar_t) PWL_TRIVIAL_HASH_FCN(char16_t) PWL_TRIVIAL_HASH_FCN(char32_t) PWL_TRIVIAL_HASH_FCN(short) PWL_TRIVIAL_HASH_FCN(unsigned short) PWL_TRIVIAL_HASH_FCN(int) PWL_TRIVIAL_HASH_FCN(unsigned int) PWL_TRIVIAL_HASH_FCN(long) PWL_TRIVIAL_HASH_FCN(unsigned long) PWL_TRIVIAL_HASH_FCN(long long) PWL_TRIVIAL_HASH_FCN(unsigned long long) #undef MYSTL_TRIVIAL_HASH_FCN // ڸλϣ inline size_t Bitwise_Hash(const unsigned char* first, size_t count) { #if (_MSC_VER && _WIN64) || ((__GNUC__ || __clang__) &&__SIZEOF_POINTER__ == 8) const size_t fnv_offset = 14695981039346656037ull; const size_t fnv_prime = 1099511628211ull; #else const size_t fnv_offset = 2166136261u; const size_t fnv_prime = 16777619u; #endif size_t result = fnv_offset; for (size_t i = 0; i < count; ++i) { result ^= (size_t)first[i]; result *= fnv_prime; } return result; } template <> struct Hash<float> { size_t operator()(const float& val) { return val == 0.0f ? 0 : Bitwise_Hash((const unsigned char*)&val, sizeof(float)); } }; template <> struct Hash<double> { size_t operator()(const double& val) { return val == 0.0f ? 0 : Bitwise_Hash((const unsigned char*)&val, sizeof(double)); } }; template <> struct Hash<long double> { size_t operator()(const long double& val) { return val == 0.0f ? 0 : Bitwise_Hash((const unsigned char*)&val, sizeof(long double)); } }; }
true
320586e930eb9b4d6060fae238d62d3c5e752260
C++
Elizabethvk/UP-2020
/Assessment_1/Assessment_1_task03.cpp
UTF-8
3,228
3.265625
3
[]
no_license
/* Задача 3: Напишете програма, която прочита от стандартния вход размера (цяло число n, по-малко от 1000000) и елементите на масив от числа с плаваща точка. След това програмата ви трябва да провери дали има такoва число k (0 < k < n-1), за което всички числа в масива, намиращи се на разстояние k едно от друго, се различават с една и съща стойност - m (например, ако k = 2 и m = 2, то модул от разликата на всички числа на позиции i и i+2 трябва да е 2). Ако има такова k, изведете го на екрана заедно със стойността на m. При повече от една стойност на k с това свойство изведете най-голямата. Ако няма такова k, изведете текста “No solution”. Пример: Вход: Изход: 5 2 3 1 2 4 5 7 */ // // �� "��. ������� ��������" // �������� �� ���������� � ����������� // ���� ���� � �������������� 2020/21 // ��������� 1 // 2020-11-29 // // ������� ���: 09:00 // ���: �������� �������� ������ // ��: 82173 // �����������: ���������� ����� // ����: 1 ���� // ��������������� �����: 3. // ��������� ����������: Visual C // // note: // if k is allowed to be =n-1, there is always a solution when m=abs(input[0] - input[n-1]) // for the problem to make any sense, I've decided to set k<=n-2 #include <iostream> #include <cmath> const unsigned max_size = 1000000; //it's out because I have some error issues int main() { double arr[max_size]; unsigned n = 0; int k=0, m=0; std::cin >> n; //cin the size of the array if (n < 0 || n>1000000) { std::cout << "Bad input!" << std::endl; } for (int i = 0; i < n; i++) { std::cin >> arr[i]; //input the array } bool solutionFound = false; for (int k = n - 2; k >= 1; k--) { const double diff = abs(arr[0] - arr[k]); //abs difference because we don't know which is bigger, absolute diff bool fail = false; //bool if the output we want, would be correct for (int i = 0; i < n-k; i++) { if (abs(arr[i] - arr[i + k]) != diff) { fail = true; //checking the step break; } } if (!fail) { //if everything work fine - success! std::cout << k << ' ' << diff << std::endl; solutionFound = true; break; } } if (!solutionFound) { //if there're no numbers matching std::cout << "No solution" << std::endl; } return 0; }
true
4060a32bcbcee66231cc32166bb985a8b5b695d4
C++
Kullsno2/C-Cpp-Programs
/Diameter.cpp
UTF-8
1,986
3.640625
4
[]
no_license
#include<algorithm> #include<utility> #include<windows.h> #include<map> #include<vector> #include<iostream> using namespace std ; struct node{ int val ; struct node * left ; struct node * right ; node(int x) : val(x) , left(NULL) , right(NULL) {} }; int diameter(struct node * root,int &height) { if(!root){ height = 0; return 0; } int lh = 0,rh=0; int l = diameter(root->left,lh) ; int r = diameter(root->right,rh ) ; height = max(lh,rh) + 1 ; return max(max(l,r) , lh+rh+1); } bool isBalanced(struct node * root,int &height) { if(root==NULL) { height = 0; return true ; } int lh=0,rh=0; bool l = isBalanced(root->left,lh) ; bool r = isBalanced(root->right,rh ) ; height = lh > rh ? lh + 1 : rh+ 1 ; return (l && r && abs(lh-rh) < 2) ; } int main() { struct node * root = NULL ; /* 20 / \ 8 22 / \ / \ 5 3 4 25 / \ 10 14 \ 14 \ 14 */ root = new node(20); root -> left = new node(8) ; root -> right = new node(22); root -> right -> left = new node(4); root -> left -> left = new node(5) ; root -> left -> right = new node(3) ; root -> right -> right = new node(25) ; root -> left->right->left = new node(10); root -> left -> right -> right = new node(14); // root -> left -> right -> right -> right= new node(14); // root -> left -> right -> right ->right -> right= new node(14); struct node * root1 = new node(10) ; root1 -> left = new node(8) ; root1 -> right = new node(2) ; root1 -> left ->left = new node(3) ; root1 -> left -> right = new node(5); root1 -> right -> right = new node(2) ; int height = 0; cout<<isBalanced(root,height)<<endl; height = 0; cout<<diameter(root,height) ; }
true
ff494eef2f81c2066780c867ab4de3697e2bec3e
C++
PratAm/Algorithms
/testMiddle.cpp
UTF-8
742
3.15625
3
[]
no_license
#include<iostream> using namespace std; int main(){ int array[]={9,7,5}; int start = 0; int end =2; int middle_index = (end-start+1)/2; cout<<"middle"<<middle_index<<endl; int first = 0; int second = -1; int high = array[start]; int high2= -1; if (high< array[middle_index]){ high = array[middle_index]; second = first; first = middle_index; high2 = high; }else if(high2<array[middle_index]){ high2 = array[middle_index]; second = middle_index; } if (high < array[end]){ high = array[end]; second = first; first = end; high2= high; }else if(high2<array[end]){ high2= array[end]; second = end; } cout<< "value is "<< array[second]<<endl; return 1; }
true
ad5d4a0e303e8d1f0fca31f9f1c020c4f8a69e2a
C++
StumpyTheStump/Graphics-Engine-2020
/Graphics Engine/Graphics/camera.cpp
UTF-8
1,823
2.703125
3
[]
no_license
#include "camera.h" //glm::mat4 projection = glm::perspective(glm::radians(90.0f), 16 / 9.0f, 0.1f, 100.0f); // //glm::mat4 model = glm::mat4(1); // //const float radius = 10.0f; //float camX = sin(glfwGetTime() * radius); //float camZ = cos(glfwGetTime() * radius); // //glm::vec3 cameraPos = glm::vec3(0.0f, 0.0f, 3.0f); //glm::vec3 cameraFront = glm::vec3(0.0f, 0.0f, -1.0f); //glm::vec3 cameraUp = glm::vec3(0.0f, 1.0f, 0.0f); // //glm::mat4 view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp); // //glm::vec3 camreaTarget = glm::vec3(0.0f, 0.0f, 0.0f); //glm::vec3 cameraDirection = glm::normalize(cameraPos - camreaTarget); // //glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f); //glm::vec3 cameraRight = glm::normalize(glm::cross(up, cameraDirection)); void camera::update(float deltaTime) { } void camera::setSpeed(float speed) { } void camera::setPerspective(float fieldOfView, float apsectRatio, float, float) { } void camera::setLookAt(glm::vec3 from, glm::vec3 to, glm::vec3 up) { } void camera::setPosition(glm::vec3 position) { } void camera::getWorldTransform(glm::mat4) { } void camera::getView(glm::mat4) { } void camera::getProjection(glm::mat4) { } void camera::getProjectionView(glm::mat4) { } void camera::updateProjectionViewTransform() { } void camera::processInput(GLFWwindow* window) { /*const float cameraSpeed = 0.05f; if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) cameraPos += cameraSpeed * cameraFront; if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) cameraPos -= cameraSpeed * cameraFront; if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) cameraPos -= glm::normalize(glm::cross(cameraFront, cameraUp)) * cameraSpeed; if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) cameraPos += glm::normalize(glm::cross(cameraFront, cameraUp)) * cameraSpeed;*/ }
true
1fa840837a3db4c5ff4a9cc7a06e2d29e2a01a00
C++
seddon-software/cplusplus
/10_TypeCasting/09.RuntimeTypeInformation.cpp
UTF-8
913
3.21875
3
[]
no_license
/////////////////////////////////////////////////////////////// // // Runtime Type Information // /////////////////////////////////////////////////////////////// #include <iostream> #include <typeinfo> using namespace std; /* * Run Time Type Information (RTTI) is appended to the v-table * Only the namespace and class name is available and then * usually as a mangled name */ namespace RTTI // namespace info included in RTTI { class Person // class must have a V-Table { public: virtual ~Person() {} }; class Employee : public Person {}; class Salesman : public Employee {}; } ///// void determineClass(const RTTI::Person& p); int main() { RTTI::Person p; RTTI::Employee e; RTTI::Salesman s; determineClass(p); determineClass(e); determineClass(s); } void determineClass(const RTTI::Person& p) { cout << typeid(p).name() << endl; }
true
8f2430292d5163868f8cc8d6d1d95a79395ff2c6
C++
duchedwa/ne697-lectures
/lecture09/map_demo.cpp
UTF-8
1,790
4
4
[]
no_license
#include <iostream> #include <map> #include <string> using namespace std; int main(int argc, char* argv[]) { // We must specify both types, the key type and the value type // These can be whatever you want map<string, int> my_map = { {"one", 1}, {"one thousand", 1000}, {"two", 2} }; // Access with [key] cout << my_map["one"] << endl; // Different ways to loop over the map // 1. Using iterators (these are just pointers, hence the ->) for (auto it = my_map.begin(); it != my_map.end();++it) { cout << "key: " << it->first << ", value: " << it->second << endl; } // Ranged-based for loop // Note that the type of the map elements is // std::pair<const KeyType, ValueType> - the keys cannot be changed! for (auto item : my_map) { cout << "key: " << item.first << ", value: " << item.second << endl; // To modify the values, we need to be careful what we're working with // "item" is a local copy in this loop; this will not persist outside of // it item.second -= 100; // This will stick because we're accessing the container my_map[item.first] += 100; } // To modify the values, we need to get the reference to the elements for (auto& item : my_map) { cout << "key: " << item.first << ", value: " << item.second << endl; // Now this persists outside the loop item.second = 10000; } // New with C++17 (need -std=c++17) for (auto const& [key, value] : my_map) { cout << "key: " << key << ", value: " << value << endl; } // Same deal with the type of the keys and values: it's auto, auto&, or // auto const&, depending on whether you want to modify the values (you // will typically use the last 2, since making a copy of the std::pair // might be pretty expensive) return 0; }
true
67ee0f994c75a3054eeabb3acdd7e10a9991c6f0
C++
kkisic/Procon
/CPP/AtCoder/arc/043/a.cpp
UTF-8
876
2.609375
3
[]
no_license
#include <cmath> #include <iostream> #include <vector> #include <queue> #include <algorithm> #include <utility> #include <iomanip> #define int long long int using namespace std; typedef pair<int, int> P; const int inf = 1e15; signed main(){ int n, a, b; cin >> n >> a >> b; vector<double> s(n); for(int i = 0; i < n; i++){ cin >> s[i]; } double sMax = *max_element(s.begin(), s.end()); double sMin = *min_element(s.begin(), s.end()); double diff = sMax - sMin; if(diff == 0 && b > 0 || diff > 0 && b == 0){ cout << -1 << endl; return 0; } double p = (double)b / (double)diff; double ss = 0; for(int i = 0; i < n; i++){ s[i] *= p; ss += s[i]; } ss /= n; cout << fixed << setprecision(6) << p << " " << fixed << setprecision(6) << a - ss << endl;; return 0; }
true
2ea206a13c2ddbec86b65c4277d0dbe0a0d0d0a0
C++
slealq/estructuras_abstractas
/Lab8/principal.cpp
UTF-8
1,023
3.109375
3
[]
no_license
#include "heap.h" void test(void){ // Probar el heap C_Heap heap_min = C_Heap(1, 20); C_Heap heap_max = C_Heap(0, 20); cout << "Insertando secuencia 0, 1, 2,.. 19" << endl; for(int i =0; i<20; i++){ heap_min.insert(i); heap_max.insert(i); } cout << "Heap MAX: " << endl; heap_max.print_heap(); cout << "Heap MIN: " << endl; heap_min.print_heap(); cout << "De aca en adelante se probará sólo en HEAP MAX" << endl; cout << "Probar get max" << endl; cout << "Maximo: " << heap_max.getMax() << endl; cout << "Probar delete max" << endl; heap_max.delMax(); heap_max.print_heap(); cout << "Probar capacity" << endl; cout << "Capacity: " << heap_max.capacity() << endl; cout << "Probar count" << endl; cout << "Count: " << heap_max.count() << endl; cout << "Probar resize a 25" << endl; heap_max.resize(25); heap_max.print_heap(); cout << "Probar resize a 10" << endl; heap_max.resize(5); heap_max.print_heap(); } int main(void){ test(); };
true
319b144a98d071f06e0d37fb4c52c2e84f2dbecd
C++
Parul-Gupta/Data-Structures
/cStack.hpp
UTF-8
2,179
3.671875
4
[]
no_license
#ifndef CSTACK_HPP #define CSTACK_HPP #include<iostream> using namespace std; template <typename E> class cStack { // an interface for a stack private: E* arr; int size; //max capacity of the cStack int red_top; //index of the top elem of red_stack int blue_top; //index of the top elem of blue_stack public: cStack(int cap=100); // constructor from capacity int redsize() const; // number of items in stack bool redempty() const; // is the stack empty? const E& redtop() const; // the top element void redpush(const E& e); // push x onto the stack void redpop(); // remove the top element int bluesize() const; // number of items in stack bool blueempty() const; // is the stack empty? const E& bluetop() const; // the top element void bluepush(const E& e); // push x onto the stack void bluepop(); // remove the top element }; template <typename E> cStack<E>::cStack(int cap){ arr=new E[cap]; red_top=-1; size=blue_top=cap; } template <typename E> int cStack<E>::redsize() const{ return red_top+1; } template <typename E> bool cStack<E>::redempty() const{ return (red_top<0); } template <typename E> const E& cStack<E>::redtop()const{ return arr[red_top]; } template <typename E> void cStack<E>::redpush(const E& e){ if(blue_top-red_top<=1){ cout<<"Stack overflow.\n"; } else{ arr[++red_top]=e; } } template <typename E> void cStack<E>::redpop(){ if(red_top<0){ cout<<"Stack underflow.\n"; } else{ red_top--; } } template <typename E> int cStack<E>::bluesize() const{ int x=size-blue_top; return x; } template <typename E> bool cStack<E>::blueempty() const{ return (blue_top>=size); } template <typename E> const E& cStack<E>::bluetop()const{ return arr[blue_top]; } template <typename E> void cStack<E>::bluepush(const E& e){ if(blue_top-red_top<=1){ cout<<"Stack overflow.\n"; } else{ arr[--blue_top]=e; } } template <typename E> void cStack<E>::bluepop(){ if(blue_top>=size){ cout<<"Stack underflow.\n"; } else{ blue_top++; } } #endif
true
39d5cab773662028acd853604500d1630a078261
C++
storm3d/cw-icfpc-2017
/solver/Solver.h
UTF-8
2,329
3.03125
3
[]
no_license
#ifndef CW_ICFPC_2017_SOLVER_H #define CW_ICFPC_2017_SOLVER_H #include "GameState.h" #include "Empire.h" /** A decision proposed by a strategy */ struct StrategyDecision { River river; /** Immediate score increase */ score_t scoreIncrease{0}; /** * How much score we're risking if we don't take this move. * Like, how much we'll lose on an unclaimed Future. * Multiplied by probability... or should we account for probability separately? * */ score_t riskIfNot{0}; inline bool isEmpty() const { return river == River::EMPTY; }; StrategyDecision() : river(River::EMPTY) {} }; class ISolverStrategy : public IGameUpdater { protected: GameState &game; Empire &empire; public: ISolverStrategy(GameState &game, Empire &empire) : game(game), empire(empire) {}; /** Select a move somehow */ virtual StrategyDecision proposedMove() = 0; /** Evaluate a move, maybe proposed by different strategy */ virtual StrategyDecision evaluateMove(River r) = 0; virtual ~ISolverStrategy() = default; void claimEdge(vert_t i, vert_t j, punter_t punter) override {} }; struct Prolongate : public ISolverStrategy { Prolongate(GameState &game, Empire &empire) : ISolverStrategy(game, empire) {}; StrategyDecision proposedMove() override; StrategyDecision evaluateMove(River r) override; }; struct Incept : public ISolverStrategy { Incept(GameState &game, Empire &empire) : ISolverStrategy(game, empire) {}; StrategyDecision proposedMove() override; /** @deprecated Not implemented yet */ StrategyDecision evaluateMove(River r) override; }; //struct CompositeSolver : public ISolverStrategy { // CompositeSolver(GameState &game, Empire &empire) : ISolverStrategy(game) {}; // StrategyDecision proposedMove() override; // /** @deprecated Not implemented yet */ // StrategyDecision evaluateMove(River r) override; //}; class Solver : public IGameUpdater { GameState &game; Empire empire; Prolongate prolongateStrategy; Incept inceptStrategy; std::vector<ISolverStrategy *> strategies; public: explicit Solver(GameState &game); River riverToClaim(); const Empire &getEmpire() const; void claimEdge(vert_t i, vert_t j, punter_t punter) override; }; #endif //CW_ICFPC_2017_SOLVER_H
true
c73da9db983e5257e7f2f2618700243d8c28edd8
C++
da96jdm/rf_sniffer
/arduino/rf_sniffer.ino
UTF-8
2,677
2.96875
3
[]
no_license
#define ledPin 7 // Onboard LED on shield #define buttonPin 6 // Onboard button attached on the shield #define RxAdataPin A0 //RF Receiver data pin = Analog pin 0 int rxAdata = 0; const int dataSize = 200; //Arduino memory is limited (max=1700) byte storedData[dataSize]; //Create an array to store the data unsigned long storedTime[dataSize]; //Create an array to store the data int maxSignalLength = 255; //Set the maximum length of the signal int lowCnt = 0; int highCnt = 0; unsigned long startTime = 0; //Variable to record the start time unsigned long endTime = 0; //Variable to record the end time unsigned long smplTime = 0; unsigned long signalDuration = 0; //Variable to record signal reading time const unsigned int highThreshold = 100; //upper threshold value const unsigned int lowThreshold = 80; //lower threshold value // put your setup code here, to run once: void setup() { Serial.begin(115200); pinMode(ledPin, OUTPUT); pinMode(buttonPin, INPUT); } // put your main code here, to run repeatedly: void loop() { if (digitalRead(buttonPin) == LOW) { Serial.println("Listening for Signal"); for (int i = 0; i < 3; i = i + 1) { InitVariables(); SampleSignal(); } } delay(20); } void InitVariables() { for (int i = 0; i < dataSize; i++) { storedData[i] = 0; } startTime = micros(); lowCnt = 0; highCnt = 0; } void SampleSignal() { do { rxAdata = analogRead(RxAdataPin); if (rxAdata<lowThreshold) { lowCnt++; } else { lowCnt = 0; } //Wait here until a LOW signal is received Serial.println(rxAdata); //Serial.print(", "); //Serial.println(micros()); } while((rxAdata<lowThreshold) || (lowCnt < 2)); startTime=micros(); //Update start time with every cycle. smplTime=startTime; digitalWrite(ledPin, HIGH); //Turn LED ON //Read and store the rest of the signal into the storedData array for (int i = 0; i < dataSize; i = i + 1) { storedData[i] = analogRead(RxAdataPin); storedTime[i] = micros() - smplTime; smplTime = micros(); } endTime = micros(); //Record the end time of the read period. signalDuration = endTime - startTime; digitalWrite(ledPin, LOW);//Turn LED OFF //Send report to the Serial Monitor Serial.println("====================="); Serial.print("Read duration: "); Serial.print(signalDuration); Serial.println(" microseconds"); Serial.println("====================="); Serial.println("Analog data"); delay(20); for (int i = 0; i < dataSize; i = i + 1) { Serial.print(storedTime[i]); Serial.print(", "); Serial.println(storedData[i]); } }
true
33380cb1d9a5a0f899d0a2bf1e7538ae238360d8
C++
MuhammadUsaid/GameProject
/MyGame/MenuScreen.cpp
UTF-8
3,456
2.859375
3
[]
no_license
#include "MenuScreen.h" #include "TextManager.h" #include "Button.h" MenuScreen::MenuScreen() { state = 0; running = true; // Screen::pause = 0; backGround = TextureManager::LoadTexture("Images/menu.png"); fontSheet = TextureManager::LoadTexture("Images/font.png"); newGameButton = new Button(fontSheet, " New Game ", 500, 400); loadGameButton = new Button(fontSheet, "Load Game", 500, 500); quitGameButton = new Button(fontSheet, "Quit Game", 500, 600); } void MenuScreen::HandleEvents() { SDL_Event e; bool onNewGame; bool onLoadGame; bool onQuitGame; while(SDL_PollEvent(&e)) { SDL_GetMouseState(&mouseX, &mouseY); onNewGame = ((newGameButton->GetX() - newGameButton->GetWidth()/2) < mouseX) && ((newGameButton->GetX() + newGameButton->GetWidth()/2) > mouseX) && ((newGameButton->GetY() - newGameButton->GetHeight()/2) < mouseY && (newGameButton->GetY() + newGameButton->GetHeight()/2) > mouseY); onLoadGame = ((loadGameButton->GetX() - loadGameButton->GetWidth()/2) < mouseX) && ((loadGameButton->GetX() + loadGameButton->GetWidth()/2) > mouseX) && ((loadGameButton->GetY() - loadGameButton->GetHeight()/2) < mouseY && (loadGameButton->GetY() + loadGameButton->GetHeight()/2) > mouseY); onQuitGame = ((quitGameButton->GetX() - quitGameButton->GetWidth()/2) < mouseX) && ((quitGameButton->GetX() + quitGameButton->GetWidth()/2) > mouseX) && ((quitGameButton->GetY() - quitGameButton->GetHeight()/2) < mouseY && (quitGameButton->GetY() + quitGameButton->GetHeight()/2) > mouseY); switch(e.type) { case SDL_QUIT: running = false; break; case SDL_MOUSEMOTION: if(onNewGame) { newGameButton->ChangeState(Hover); } else { newGameButton->ChangeState(Normal); if(onLoadGame) { loadGameButton->ChangeState(Hover); } else { loadGameButton->ChangeState(Normal); if(onQuitGame) { quitGameButton->ChangeState(Hover); } else { quitGameButton->ChangeState(Normal); } } } break; case SDL_MOUSEBUTTONDOWN: if(e.button.button == SDL_BUTTON_LEFT) { if(onNewGame) { newGameButton->ChangeState(Clicked); state = 1; } else if(onLoadGame) { loadGameButton->ChangeState(Clicked); } else if(onQuitGame) { quitGameButton->ChangeState(Clicked); running = false; } } break; } } } void MenuScreen::Update() { } void MenuScreen::Render() { SDL_RenderCopy(Game::renderer, backGround, nullptr, nullptr); newGameButton->Render(); loadGameButton->Render(); quitGameButton->Render(); } MenuScreen::~MenuScreen() { SDL_DestroyTexture(backGround); SDL_DestroyTexture(fontSheet); delete newGameButton; delete loadGameButton; delete quitGameButton; }
true
af0c15fa53b09f7e8fd6d2f7c6344648699d5939
C++
geranium12/Algorithms
/DataStructures/BinaryHeap/BinaryHeap/Source.cpp
UTF-8
517
2.96875
3
[]
no_license
#include <fstream> #include <vector> using namespace std; int main() { ifstream fin("input.txt"); ofstream fout("output.txt"); long n; fin >> n; vector<long> v(n); for (int i = 0; i < n; i++) { fin >> v[i]; } bool f = true; for (int i = 1; i <= n && f; i++) { long a = 2 * i; long b = 2 * i + 1; if (a <= n && v[i - 1] > v[a - 1]) { f = false; } if (b <= n && v[i - 1] > v[b - 1]) { f = false; } } if (f) { fout << "Yes" << endl; } else { fout << "No" << endl; } return 0; }
true
9a5e4572a583d42fca0c72080a9d268283246c51
C++
DavidHoskins/SpaceInvaders
/SpaceInvader.h
UTF-8
1,090
2.546875
3
[]
no_license
#ifndef SPACEINVADER_H #define SPACEINVADER_H #include <SFML/Graphics.hpp> #include <SFML/System.hpp> #include "AlienHandler.h" #include "NetworkHandler.h" #include "Player.h" #include "MenuScreen.h" class SpaceInvader { public: //Constructor & Destructor. SpaceInvader(); ~SpaceInvader(); //Public methods. void MainLoop(); //Public enums. enum gameState { start, main, end, network}; private: //Private consts. const int m_kScreenWidth = 1920; const int m_kScreenHeight = 1080; //Private variables. gameState m_CurrentGameState; InputHandler m_CurrentInputHandler; Player m_CurrentPlayer[2]; AlienHandler m_CurrentAliens; NetworkHandler m_CurrentNetworkHandler; MenuScreen m_CurrentMenuScreen; int m_iValue = 100; //Private methods. void render(); void update(); void networkUpdate(); void networkRender(sf::RenderWindow* window); void localLogic(); void networkLogic(); void checkForEnd(); void resetGame(); void startMenuUpdate(); void startMenuRender(); //Private render variables. sf::RenderWindow* m_pWindow; }; #endif //!SPACEINVADERS_H
true
b18155fd054a0861c76b36b2cbd30f8eb01eaa5e
C++
theJinFei/C-Test
/CCF/t1/main.cpp
UTF-8
579
2.875
3
[]
no_license
#include <iostream> #include <vector> using namespace std; int main() { int n, k; cin >> n >> k; int ans = 0; vector<int> v1; for(int i = 0; i < n; i++){ int temp; cin >> temp; v1.push_back(temp); } for(int i = 0; i < v1.size();){ if(v1[i] >= k || (i == v1.size()-1 && v1[i] < k)){ ans ++; i ++; }else { int temp = 0; temp = v1[i]; ++i; v1[i] = temp + v1[i]; continue; } } cout << ans <<endl; return 0; }
true
9932e899e19e4a642d3cec05c1b3a5b56dfbbe77
C++
mkoldaev/bible50cpp
/lang/ur/gen/Bible53.h
UTF-8
10,969
2.546875
3
[]
no_license
#include <map> #include <string> class Bible53 { struct ur1 { int val; const char *msg; }; struct ur2 { int val; const char *msg; }; struct ur3 { int val; const char *msg; }; public: static void view1() { struct ur1 poems[] = { {1, "1 پَولُس اور سِلوانُس اور تِیمُتھِیُس کی طرف سے تھِسّلُنیکِیوں کی کلِیسیا کے نام جو ہمارے باپ خُدا اور خُداوند یِسُوع مسِیح میں ہے۔ "}, {2, "2 فضل اور اِطمینان خُدا باپ اور خُداوند یِسُوع مسِیح کی طرف سے تُمہیں حاصِل ہوتا رہے۔ "}, {3, "3 اَے بھائِیوں! تُمہارے بارے میں ہر وقت خُدا کا شُکر کرنا ہم پر فرض ہے اور یہ اِس لِئے مُناسِب ہے کہ تُمہارا اِیمان بہُت بڑھتا جاتا ہے اور تُم سب کی محبّت آپس میں زِیادہ ہوتی جاتی ہے۔ "}, {4, "4 یہاں تک کہ ہم آپ خُدا کی کلِیسیاؤں میں تُم پر فخر کرتے ہیں کہ جِتنے ظُلم اور مُصِیبتیں تُم اُٹھاتے ہو اُن سب میں تُمہارا صبر اور اِیمان ظاہِر ہوتا ہے۔ "}, {5, "5 یہ خُدا کی سَچّی عدالت کا صاف نِشان ہے تاکہ تُم خُدا کی بادشاہی کے لائِق ٹھہرو جِس کے لِئے تُم دُکھ بھی اُٹھاتے ہو۔ "}, {6, "6 کِیُونکہ خُدا کے نزدِیک یہ اِنصاف ہے کہ بدلے میں تُم پر مُصِیبت لانے والوں کو مُصِیبت۔ "}, {7, "7 اور تُم مُصِیبت اُٹھانے والوں کو ہمارے ساتھ آرام دے جب خُداوند یِسُوع اپنے قوی فرِشتوں کے ساتھ بھڑکتی ہُوئی آگ میں آسمان سے ظاہِر ہوگا۔ "}, {8, "8 اور جو خُدا کو نہِیں پہچانتے اور ہمارے خُداوند یِسُوع کی خُوشخَبری کو نہِیں مانتے اُن سے بدلہ لے گا۔ "}, {9, "9 وہ خُداوند کے چہرہ اور اُس کی قُدرت کے جلال سے دُور ہوکر ابدی ہلاکت کی سزا پائیں گے۔ "}, {10, "10 یہ اُس دِن ہوگا جب کہ وہ اپنے مُقدّسوں میں جلال پانے اور سب اِیمان لانے والوں کے سبب سے تعّجُب کا باعِث ہونے کے لِئے آئے گا کِیُونکہ تُم ہماری گواہی پر اِیمان لائے۔ "}, {11, "11 اِسی واسطے ہم تُمہارے لِئے ہر وقت دُعا بھی کرتے رہتے ہیں کہ ہمارا خُدا تُمہیں اِس بُلاوے کے لائِق جانے اور نیکی کی ہر ایک خواہِش اور اِیمان کے ہر ایک کام کو قُدرت سے پُورا کرے۔ "}, {12, "12 تاکہ ہمارے خُدا اور خُداوند یِسُوع مسِیح کے فضل کے مُوافِق ہمارے خُداوند یِسُوع کا نام تُم میں جلال پائے اور تُم اُس میں۔ "}, }; size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);} } static void view2() { struct ur2 poems[] = { {1, "1 اَے بھائِیو! ہم اپنے خُداوند یِسُوع مسِیح کے آنے اور اُس کے پاس اپنے جمع ہونے کی بابت تُم سے دَرخواست کرتے ہیں۔ "}, {2, "2 کہ کِسی رُوح یا کلام یا خط سے جو گویا ہماری طرف سے ہو یہ سَمَجھ کر کہ خُداوند کا دِن آ پہُنچا ہے تُمہاری عقل دفعتہً پریشان نہ ہو جائے اور نہ تُم گھبراؤ۔ "}, {3, "3 کِسی طرح سے کِسی کے فریب میں نہ آنا کِیُونکہ وہ دِن نہِیں آئے گا جب تک کہ پہلے برگشتگی نہ ہو اور وہ گُناہ کا شَخص یعنی ہلاکت کا فرزند ظاہِر نہ ہو۔ "}, {4, "4 جو مُخالفت کرتا ہے اور ہر ایک سے جو خُدا یا معبُود کہلاتا ہے اپنے آپ کو بڑا ٹھہراتا ہے۔ یہاں تک کہ وہ خُدا کے مَقدِس میں بَیٹھ کر اپنے آپ کو خُدا ظاہِر کرتا ہے۔ "}, {5, "5 کیا تُمہیں یاد نہِیں کہ جب میں تُمہارے پاس تھا تو تُم سے یہ باتیں کہا کرتا تھا؟ "}, {6, "6 اب جو چِیز اُسے روک رہی ہے تاکہ وہ اپنے خاص وقت پر ظاہِر ہو اُس کو تُم جانتے ہو۔ "}, {7, "7 کِیُونکہ بے دِینی کا بھید تو اَب بھی تاثِر کرتا جاتا ہے مگر اَب ایک روکنے والا ہے اور جب تک وہ دُور نہ کِیا جائے روکے رہے گا۔ "}, {8, "8 اُس وقت وہ بے دِین ظاہِر ہوگا جِسے خُداوند یِسُوع اپنے مُنہ کی پھُونک سے ہلاک اور اپنی آمد کی تجلّی سے نِیست کرے گا۔ "}, {9, "9 اور جِس کی آمد شَیطان کی تاثِر کے مُوافِق ہر طرح کی جھُوٹی قُدرت اور نِشانوں اور عجِیب کاموں کے ساتھ۔ "}, {10, "10 اور ہلاک ہونے والوں کے لِئے ناراستی کے ہر طرح کے دھوکے کے ساتھ ہوگی اِس واسطے کہ اُنہوں نے حق کی محبّت کو اِختیّار نہ کِیا جِس سے اُن کی نِجات ہوتی۔ "}, {11, "11 اِسی سبب سے خُدا اُن کے پاس گُمراہ ہونے والی تاثِر بھیجے گا تاکہ وہ جھُوٹ کو سَچ جانیں۔ "}, {12, "12 اور جِتنے لوگ حق کا یقِین نہِیں کرتے بلکہ ناراستی کو پسند کرتے ہیں وہ سب سزا پائیں۔ "}, {13, "13 لیکِن تُمہارے بارے میں اَے بھائِیو! خُداوند کے پیارو ہر وقت خُدا کا شُکر کرنا ہم پر فرض ہے کِیُونکہ خُدا نے تُمہیں اِبتدا ہی سے اِس لِئے چُن لِیا تھا کہ رُوح کے ذرِیعہ سے پاکِیزہ بن کر اور حق پر اِیمان لا کر نِجات پاؤ۔ "}, {14, "14 جِس کے لِئے اُس نے تُمہیں ہماری خُوشخَبری کے وسِیلہ سے بُلایا تاکہ تُم ہمارے خُداوند یِسُوع مسِیح کا جلال حاصِل کرو۔ "}, {15, "15 پَس اَے بھائِیو! ثابِت قدم رہو اور جِن رِوایَتوں کی تُم نے ہماری زبانی یہ خط کے ذرِیعہ سے تعلِیم پائی اُن پر قائِم رہو۔ "}, {16, "16 اب ہمارا خُداوند یِسُوع مسِیح خُود اور ہمارا باپ خُدا جِس نے ہم سے محبّت رکھّی اور فضل سے ابدی تسلّی اور اچھّی اُمِید بخشی۔ "}, {17, "17 تُمہارے دِلوں کو تسلّی دے اور ہر ایک نیک کام اور کلام میں مضبُوط کرے۔ "}, }; size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);} } static void view3() { struct ur3 poems[] = { {1, "1 غرض اَے بھائِیو! ہمارے حق میں دُعا کرو کہ خُداوند کا کلام اَیسا جلد پھیل جائے اور جلال پائے جَیسا تُم میں۔ "}, {2, "2 اور کجَرو اور بُرے آدمِیوں سے ہم بچے رہیں کِیُونکہ سب میں اِیمان نہِیں۔ "}, {3, "3 مگر خُداوند سَچّا ہے۔ وہ تُم کو مضبُوط کرے گا اور اُس شرِیر سے محفُوظ رکھّے گا۔ "}, {4, "4 اور خُداوند میں ہمیں تُم پر بھروسہ ہے کہ جو حُکم ہم تُمہیں دیتے ہیں اُس پر عمل کرتے ہو اور کرتے بھی رہو گے۔ "}, {5, "5 خُداوند تُمہارے دِلوں کو خُدا کی محبّت اور مسِیح کے صبر کی ہدایت کرے۔ "}, {6, "6 اَے بھائِیو! ہم اپنے خُداوند یِسُوع مسِیح کے نام سے تُمہیں حُکم دیتے ہیں کہ ہر ایک اَیسے بھائِی سے کِنارہ کرو جو بے قاعدہ چلتا ہے اور اُس رِوایَت پر عمل نہِیں کرتا جو اُس کو ہماری طرف سے پہُنچی۔ "}, {7, "7 کِیُونکہ تُم آپ جانتے ہو کہ ہماری مانِند کِس طرح بننا چاہئے اِس لِئے کہ ہم تُم میں بے قاعدہ نہ چلتے تھے۔ "}, {8, "8 اور کِسی کی روٹی مُفت نہ کھاتے تھے بلکہ محنت مُشقّت سے رات دِن کام کرتے تھے تاکہ تُم میں سے کِسی پر بوجھ نہ ڈالیں۔ "}, {9, "9 اِس لِئے نہِیں کہ ہم کو اِختیّار نہ تھا بلکہ اِس لِئے کہ اپنے آپ کو تُمہارے واسطے نمُونہ ٹھہرائیں تاکہ تُم ہماری مانِند بنو۔ "}, {10, "10 اور جب ہم تُمہارے پاس تھے اُس وقت بھی تُم کو یہ حُکم دیتے تھے کہ جِسے محنت کرنا نہ منظُور نہ ہو وہ کھانے بھی نہ پائے۔ "}, {11, "11 ہم سُنتے ہیں کہ تُم میں بعض بے قاعدہ چلتے ہیں اور کُچھ کام نہِیں کرتے بلکہ اَوروں کے کام میں دخل دیتے ہیں۔ "}, {12, "12 اَیسے شَخصوں کو ہم خُداوند یِسُوع مسِیح میں حُکم دیتے اور نصِیحت کرتے ہیں کہ چُپ چاپ کام کر کے اپنی ہی روٹی کھائیں۔ "}, {13, "13 اور تُم اَے بھائِیو! نیک کام کرنے میں ہِمّت نہ ہارو۔ "}, {14, "14 اور اگر کوئی ہمارے اِس خط کی بات کو نہ مانے تو اُسے نِگاہ میں رکھّو اور اُس سے صحُبت نہ رکھّو تاکہ وہ شرمِندہ ہو۔ "}, {15, "15 لیکِن اُسے دُشمن نہ جانو بلکہ بھائِی سَمَجھ کر نصِیحت کرو۔ "}, {16, "16 اب خُداوند جو اِطمینان کا چشمہ ہے آپ ہی تُم کو ہمیشہ اور ہر طرح سے اِطمینان بخشے۔ خُداوند تُم سب کے ساتھ رہے۔ "}, {17, "17 مَیں پَولُس اپنے ہاتھ سے سَلام لِکھتا ہُوں۔ ہر خط میں میرا یہی نِشان ہے۔ مَیں اِسی طرح لِکھتا ہُوں۔ "}, {18, "18 ہمارے خُداوند یِسُوع مسِیح کا فضل تُم سب پر ہوتا رہے۔ "}, }; size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);} } };
true
3acea11bf249b385c125f65fce42f4fb9d185ed3
C++
Towkir7970/Operating-System-Algorithms-Implementation-In-C-
/Deadlock/Deadlock_Detection.cpp
UTF-8
1,197
2.90625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; vector<int> graph[100]; int color[100], cycle[100], ara[100]; int nodes, edges, top=-1, track; void print() { int j=0, i; while(cycle[top]!=track){ ara[j]=cycle[top]; color[cycle[top]]=-1; top--; j++; } ara[j]=cycle[top]; for(i=j; i>0; i--) printf("%d-->", ara[i]); printf("%d\n", ara[i]); } void dfs(int node) { if(color[node]==0){ color[node]=1; cycle[++top]=node; for(int i=0; i<graph[node].size(); i++){ if(color[graph[node][i]]==0 || color[graph[node][i]]==1){ dfs(graph[node][i]); } } color[node]=-1; top--; } else if(color[node]==1){ track=node; print(); } } int main() { int node1, node2; printf("Number of nodes: "); scanf("%d", &nodes); printf("Number of Edges:: "); scanf("%d", &edges); printf("Edges:: \n"); for(int i=1; i<=edges; i++){ scanf("%d %d", &node1, &node2); graph[node1].push_back(node2); } printf("Cycle::\n"); for(int i=1; i<=nodes; i++){ if(color[i]==0) dfs(i); } }
true
0c898be2f835d1dfa8130a6a4cff03984065c06c
C++
Isabelle-Angrignon/Labyrinthe
/LabyrintheConsole/LabyrintheConsole/Commande.h
UTF-8
384
2.9375
3
[]
no_license
#pragma once #include <Windows.h> class CCommande { public: CCommande(int vkKey) :m_Key{ vkKey }{} bool operator==(const CCommande &c) const { return GetKey() == c.GetKey(); } bool operator!=(const CCommande &c) const{ return !CCommande::operator==(c); } int GetKey()const { return m_Key; } CCommande() :m_Key{ VK_ESCAPE }{} ~CCommande() = default; private: int m_Key; };
true
d639d0c69a72ba8de93254b0169a3e939ab2302d
C++
bsc-ssrg/hermes
/include/hermes/transport.hpp
UTF-8
4,269
2.546875
3
[]
no_license
#ifndef __HERMES_TRANSPORT_HPP__ #define __HERMES_TRANSPORT_HPP__ #include <cstddef> #include <stdexcept> #include <unordered_map> namespace hermes { /** Valid transport types (i.e. transport types supported by Mercury) */ enum class transport : std::size_t { // BMI plugin bmi_tcp = 0, // MPI plugin mpi_dynamic, mpi_static, // Shared memory plugin na_sm, // CCI plugin cci_tcp, cci_verbs, cci_gni, cci_sm, // OFI plugin ofi_sockets, ofi_tcp, ofi_verbs, ofi_psm2, ofi_gni, // special value: MUST ALWAYS BE LAST! // (it's used when defining the supported_transports constexpr std::array count }; using transport_metadata = std::tuple<transport, const char* const, const char* const>; static const constexpr std::array< transport_metadata, static_cast<std::size_t>(transport::count) > supported_transports = { // BMI plugin std::make_tuple( transport::bmi_tcp, "bmi+tcp://", "bmi+tcp://" ), // MPI plugin std::make_tuple( transport::mpi_dynamic, "mpi+dynamic://", "mpi+dynamic://" ), std::make_tuple( transport::mpi_static, "mpi+static://", "mpi+static://" ), // Shared memory plugin std::make_tuple( transport::na_sm, "na+sm://", "na+sm://" ), // CCI plugin std::make_tuple( transport::cci_tcp, "cci+tcp://", "cci+tcp://" ), std::make_tuple( transport::cci_verbs, "cci+verbs://", "cci+verbs://" ), std::make_tuple( transport::cci_gni, "cci+gni://", "cci+gni://" ), std::make_tuple( transport::cci_sm, "cci+sm://", "cci+sm://" ), // OFI plugin std::make_tuple( transport::ofi_sockets, "ofi+sockets://", "ofi+sockets://" ), std::make_tuple( transport::ofi_tcp, "ofi+tcp://", "ofi+tcp://" ), std::make_tuple( transport::ofi_verbs, "ofi+verbs://", "ofi+verbs://" ), std::make_tuple( transport::ofi_psm2, "ofi+psm2://", "ofi+psm2://" ), std::make_tuple( transport::ofi_gni, "ofi+gni://", "ofi+gni://fi_addr_gni://" ) }; } // namespace hermes namespace { static constexpr std::size_t mid(const std::size_t low, const std::size_t high) { return (low & high) + ((low ^ high) >> 1); } template <std::size_t SIZE> static constexpr std::size_t find_transport(const std::array<hermes::transport_metadata, SIZE>& transports, const hermes::transport key, const std::size_t low = 0, const std::size_t high = SIZE) { return (high < low) ? throw std::logic_error("Invalid transport") : (key == std::get<0>(transports[::mid(low, high)])) ? ::mid(low, high) : (key < std::get<0>(transports[::mid(low, high)])) ? find_transport(transports, key, low, ::mid(low, high) - 1) : find_transport(transports, key, ::mid(low, high) + 1, high); } } // anonymous namespace namespace hermes { static constexpr const char* get_transport_prefix(transport id) { return std::get<1>( supported_transports[ ::find_transport(supported_transports, id)]); } static constexpr const char* get_transport_lookup_prefix(transport id) { return std::get<2>( supported_transports[ ::find_transport(supported_transports, id)]); } static inline transport get_transport_type(const std::string& prefix) { for(auto&& t : hermes::supported_transports) { if(std::string(std::get<1>(t)).find(prefix) != std::string::npos) { return std::get<0>(t); } } throw std::runtime_error("Invalid transport prefix"); } } // namespace hermes #endif // __HERMES_TRANSPORT_HPP__
true
46cab20b508f64f218d2a2c5daac2ef897f4240c
C++
ETalienwx/Linux
/RingQueue/ring.cc
UTF-8
1,725
3.3125
3
[]
no_license
#include <iostream> #include <pthread.h> #include <stdlib.h> #include <time.h> #include <semaphore.h> #include <unistd.h> #define NUM 16 class ring{ private: int Ring[NUM]; sem_t blank_sem; sem_t data_sem; int p_step; int c_step; public: void P(sem_t *sem) { sem_wait(sem); } void V(sem_t *sem) { sem_post(sem); } public: ring() :p_step(0),c_step(0) { sem_init(&blank_sem,0,NUM); sem_init(&data_sem,0,0); } void PushData(const int &data) { P(&blank_sem); Ring[p_step]=data; p_step++; p_step%=NUM; V(&data_sem); } void PopData(int &data) { P(&data_sem); data=Ring[c_step]; c_step++; c_step%=NUM; V(&blank_sem); } ~ring() { sem_destroy(&blank_sem); sem_destroy(&data_sem); } }; void *product(void *arg) { ring *r=(ring *)arg; srand((unsigned long)time(NULL)); while(1) { int data=rand()%100+1; r->PushData(data); std::cout<<"product done:"<<data<<std::endl; } } void *consume(void *arg) { ring *r=(ring *)arg; while(1) { int data; r->PopData(data); std::cout<<"consume done:"<<data<<std::endl; sleep(1); } } int main() { ring r; pthread_t p,c; pthread_create(&p,NULL,product,(void *)&r); pthread_create(&c,NULL,consume,(void *)&r); pthread_join(p,NULL); pthread_join(c,NULL); return 0; }
true
49a1ce077b16529c6773f3e2bacdf4eaa13e14fc
C++
grahamjx/cpp-graph
/source/main.cpp
UTF-8
7,991
3.734375
4
[]
no_license
/* Name: Joel Graham Course: CS 163 Programming Assignment #5 File: main.cpp Purpose: This program simulates a topic / dependency graph. Each topic will be passed into the corresponding ADT which handles storage and manipulation of the data. Each topic will be stored in one data structure, adjacency list. The topics (vertices) are inserted into the adjacency list starting at element zero in the array. The user has the option to add a topic (add_vertex), set a dependency (add_edge), view dependencies associated with a particular topic (retrieve_adj) and display the topics using a depth first traversal method starting at a user defined postion. Input: When executing this program, a_graph (graph.h) object is created as well as a vertex_info object that passes the user information into the corresponding ADT. The data provided to the graph is managed by the struct "vertex_info" (See vertex_info.h). The overall structure of the program back-end is managed by the graph class (graph.h / graph.cpp). Output: The topics (vertices) can be displayed using a depth-first traversal method. The user is prompted to enter a topic in which to start from. If there is a vertex matching the topic, the recursive display will take place. All additional output comes from this main.cpp file and relates to the user menu and various user prompts. */ #include "graph.h" #include <iostream> #include <cstring> using namespace std; const int MAX_CHAR = 101; void call_menu(void); char read_input(const char prompt[]); void run_input(char command, graph& a_graph); void read_string (const char prompt[],char input_string[], int max_char); void add_topic(graph& a_graph); void add_depend(graph& a_graph); void search_depend(graph& a_graph); void display(graph& a_graph); /*The function primarily handles how the client side of the program is structured. After declaring some class objects and other local variables, the function proceeds to displaying the menu screen. User input from the menu is processed through the function 'read_input' before passing 'input' and the object 'a_graph' as an argument into the 'run_input' function to perform additional processes. When the user is ready to quit the program, the input of 'q' will cause the program to terminate. */ int main () { graph a_graph; char input; call_menu(); input = read_input("Please enter an option from the list: "); while (input != 'q') { run_input(input, a_graph); call_menu(); input = read_input("Please enter an option from the list: "); } return 0; } //Displays the menu options to the user. void call_menu(void) { cout << "\nWelcome to Graph Creator!" << endl << "A. Add a Topic" << endl << "S. Set a Dependency" << endl << "V. View a topic's dependencies" << endl << "D. Display - Depth First" << endl << "Q. Quit the program" << endl << endl; } /* Accepts a prompt from the main() function and displays it. Accepts user input, converts it to lower case and passes it back to the main() function. */ char read_input(const char prompt[]) { char cmd; cout << prompt; cin >> cmd; cin.clear(); cin.ignore(100, '\n'); return tolower(cmd); } /* User input and object 'a_graph' are passed into the function. A switch statement is used to process the command argument. The object is passed to this function and then passed again to add_topic in order to start adding topics (vertices). The objects also get passed as references into add_depend, search_depend and display functions in order to have access to the class member functions. Any command other than the ones outlined in the menu is considered invalid and it returns back to main() */ void run_input(char command,graph& a_graph) { switch (command) { case 'a': add_topic(a_graph); break; case 's': add_depend(a_graph); break; case 'v': search_depend(a_graph); break; case 'd': display(a_graph); break; default: cout << "\nInvalid option, please select again." << endl; break; } } /* Prompts the user to enter a topic for the graph. The vertex_info object is then passed into the table class member function "add_vertex" for insertion into the adjacency list. */ void add_topic(graph& a_graph) { vertex_info a_vertex; char topic[MAX_CHAR]; int duplicate; int bounds; read_string("\nPlease enter a topic (Ex. Linear Linked List): ",topic,MAX_CHAR); duplicate = a_graph.search(topic); if (duplicate != -1) { cout <<"\nThe topic you entered already exists" << endl; } else { a_vertex.topic = new char[strlen(topic)+1]; strcpy(a_vertex.topic, topic); bounds = a_graph.add_vertex(a_vertex); if (bounds == 0) { cout << "\nSorry, graph has reached it's maximum size" << endl; } } } /* Prompts the user to enter a topic and a dependency. The two character arrays get passed to the add_edge function which determines if the topic / dependency exists before setting the dependency (adding it to the chosen topic's edge list). */ void add_depend(graph& a_graph) { char topic[MAX_CHAR]; char depend[MAX_CHAR]; int match; read_string("\nPlease enter a Topic (Ex. Linear Linked List): ",topic,MAX_CHAR); read_string("\nPlease enter a Dependency (Ex. Pointers): ",depend,MAX_CHAR); match = a_graph.add_edge(topic, depend); if (match == 0) { cout << "\nThe topic '" << topic << "' does not exist, please add it to the graph" << endl; } else if(match == -1) { cout << "\nThe dependency '" << depend << "' does not exist, please add it to the graph" << endl; } } /* Prompts the user to enter a topic. The character array gets passed to the retrieve_adj function which determines if the topic exists before calling a recursive function that copies all the vertex information relating to the topic's edge list. The resulting edge list (adjacent nodes to the topic) are then displayed out to the user. */ void search_depend(graph& a_graph) { int size; vertex_info results[GRAPH_SIZE]; char topic[MAX_CHAR]; read_string("\nPlease enter a topic (Ex. Linear Linked List): ",topic,MAX_CHAR); size = a_graph.retrieve_adj(topic, results); if (size == -1) { cout << "\nThe topic '" << topic << "' does not exist, please add it to the graph" << endl; } else if(size == 0) { cout << "\nThe topic '" << topic << "' currently has no dependencies associated with it" << endl; } else { for (int i = 0; i < size; i++) { cout << "\nDependency " << (i+1) << ": " << results[i].topic << endl; } } } /*Prompts the user to enter a topic. The character array gets passed to the a_graph.display function which determines if the topic exists before calling the depth-first display recursive function. */ void display(graph& a_graph) { int check; char topic[MAX_CHAR]; read_string("\nPlease enter a topic (Ex. Linear Linked List): ",topic,MAX_CHAR); check = a_graph.display(topic); if(check == 0) { cout << "\nThe topic '" << topic << "' does not exist!" << endl; } } /*This function accepts a prompt, a string of characters and a max length in which to process user input. Essentially, before the data is stored into and object, it is cut down to it's approximate size since the user is only allowed a certain number of characters for each data field. */ void read_string (const char prompt[],char input_string[], int max_char) { cout << prompt; cin.get(input_string, max_char, '\n'); while(!cin) { cin.clear (); cin.ignore (100, '\n'); cin.get(input_string, max_char, '\n'); } cin.clear(); cin.ignore (100, '\n'); }
true
7a07b7c8386d5295c24a29863e9995c4f41ec181
C++
ftiasch/ccpc-final-2020
/main/kmp/gen.cc
UTF-8
8,533
2.859375
3
[]
no_license
#include "testlib.h" #include <algorithm> #include <cstring> #include <vector> using i64 = long long; // Two Efficient Algorithms for Linear Suffix Array Construction #define pushS(x) sa[--cur[(int)s[x]]] = x #define pushL(x) sa[cur[(int)s[x]]++] = x class SuffixArray { public: std::vector<int> sa; std::vector<int> rank; std::vector<int> lcp; template <class T> void build(const T *s, int n); template <class T> void build(const T *s, int n, int m); int size() const { return sa.size() - 1; } private: using SLTypes = std::vector<bool>; int *buffer, *freq, *cur; int len; void buildRankTable(); template <class T> void computeLCPArray(const T *s); template <class T> void countFrequency(const T *s, int n, int m); template <class T> void induce(const T *s, int *sa, int m, const SLTypes &t); template <class T> void sa_is(const T *s, int *sa, int n, int m); }; template <class T> void SuffixArray::build(const T *s, int n) { this->len = n; int m = *std::max_element(s, s + n) + 1; build(s, n, m); buildRankTable(); computeLCPArray(s); } template <class T> void SuffixArray::build(const T *s, int n, int m) { sa.resize(n + 1); if (n == 0) sa[0] = 0; else { // memory usage: sa + buffer + types // = 4 * (n + max(m * 2, n)) + 2 * n / 8 + O(1) bytes std::vector<int> buffer((std::max(m, (n + 1) / 2) + 1) * 2); this->buffer = &buffer[0]; sa_is<T>(s, &sa[0], n + 1, m); } } void SuffixArray::buildRankTable() { int n = size() + 1; rank.resize(n); for (int i = 0; i < n; ++i) rank[sa[i]] = i; } template <class T> void SuffixArray::computeLCPArray(const T *s) { const int n = size() + 1; lcp.resize(n); for (int i = 0, h = lcp[0] = 0; i < n; ++i) if (rank[i]) { int j = sa[rank[i] - 1]; while (i + h < n && j + h < n && s[i + h] == s[j + h]) ++h; if (lcp[rank[i]] = h) --h; } } template <class T> void SuffixArray::countFrequency(const T *s, int n, int m) { memset(freq, 0, sizeof(int) * m); for (int i = 0; i < n; ++i) ++freq[(int)s[i]]; for (int i = 1; i < m; ++i) freq[i] += freq[i - 1]; memcpy(cur, freq, sizeof(int) * m); } template <class T> void SuffixArray::induce(const T *s, int *sa, int m, const SLTypes &t) { const int n = t.size(); memcpy(cur + 1, freq, sizeof(int) * (m - 1)); for (int i = 0; i < n; ++i) { int p = sa[i] - 1; if (p >= 0 && t[p]) pushL(p); } memcpy(cur, freq, sizeof(int) * m); for (int i = n - 1; i > 0; --i) { int p = sa[i] - 1; if (p >= 0 && !t[p]) pushS(p); } } template <class T> void SuffixArray::sa_is(const T *s, int *sa, int n, int m) { SLTypes t(n); memset(sa, 0, sizeof(int) * n); for (int i = n - 2; ~i; --i) { t[i] = (s[i] == s[i + 1]) ? t[i + 1] : s[i] > s[i + 1]; } freq = buffer, cur = buffer + m; countFrequency(s, n, m); for (int i = 1; i < n; ++i) if (t[i - 1] > t[i]) pushS(i); induce(s, sa, m, t); int n1 = 0, order = 0; for (int i = 0, p; i < n; ++i) { if ((p = sa[i]) && t[p - 1] > t[p]) sa[n1++] = p; } int *s1 = sa + n1; memset(s1, -1, sizeof(int) * (n - n1)); s1[(sa[0] - 1) / 2] = order++; for (int i = 1; i < n1; ++i) { bool diff = true; for (int x = sa[i - 1], y = sa[i];; ++x, ++y) { if (s[x] != s[y] || t[x] != t[y]) break; else if (t[x] > t[x + 1] && t[y] > t[y + 1]) { diff = (s[x + 1] != s[y + 1]); break; } } s1[(sa[i] - 1) / 2] = (order += diff) - 1; } for (int i = 0, x = 0; i < n - n1; ++i) { if (~s1[i]) s1[x++] = s1[i]; } if (order != n1) { sa_is<int>(s1, sa, n1, order); for (int i = 0; i < n1; ++i) s1[sa[i]] = i; } for (int i = 1, j = 0; i < n; ++i) { if (t[i - 1] > t[i]) sa[s1[j++]] = -i; } memset(s1, 0, sizeof(int) * (n - n1)); freq = buffer, cur = buffer + m; countFrequency(s, n, m); for (int i = n1 - 1; ~i; --i) pushS(-sa[i]); induce(s, sa, m, t); } // random std::string gen_rand(int n, int c) { std::string s(n, 'a'); for (int i = 0; i < n; ++i) { s[i] = 'a' + rnd.next(0, c - 1); } return s; } // antihash string std::string gen_thue_morse(int n, int m) { std::string s(n, 'a'); for (int i = 1; i <= n; ++i) { int w = 0, j = i - 1; while (j) { w = (w + j) % m; j /= m; } s[i - 1] = w + 'a'; } return s; } // prefix of fibonacci word std::string gen_fib(int n) { std::string s(n, 'a'); s[0] = s[1] = rnd.next(0, 25) + 'a'; while (s[0] == s[1]) { s[1] = rnd.next(0, 25) + 'a'; } int a = 1, b = 2; for (int i = 3; i <= n; ++i) { if (a + b < i) { a += b; std::swap(a, b); } s[i - 1] = s[i - b - 1]; } return s; } // string with period p std::string gen_period(int n, const std::string &p) { std::string s(n, 'a'); for (int i = 0; i < n; ++i) s[i] = p[i % p.size()]; return s; } // the probability of letter p is \frac{1}{m^p} std::string gen_geo(int n, int m) { std::vector<char> letters; for (char i = 'a'; i <= 'z'; ++i) { letters.push_back(i); } shuffle(letters.begin(), letters.end()); std::string s(n, 'a'); for (int i = 1; i <= n; ++i) { int p = 0; while (p < 25 && !rnd.next(0, m - 1)) ++p; s[i - 1] = letters[p]; } return s; } // i-th character is a + ctz(i) std::string gen_abacaba(int n, int c) { std::vector<char> letters; for (char i = 'a'; i <= 'z'; ++i) { letters.push_back(i); } shuffle(letters.begin(), letters.end()); std::string s(n, 'a'); for (int i = 1; i <= n; ++i) { s[i - 1] = letters[std::min(__builtin_ctz(i), c)]; } return s; } // string with many borders std::string gen_border(int n, const std::vector<int> &diff) { std::string s = "a"; for (auto d : diff) { std::string p = s; s = ""; for (int j = 0; j < d; ++j) s += p; s.back()++; } s.pop_back(); return s; } const int N = 1e6 + 10; std::vector<int> edges[N]; int subtree_size[N]; int pi[N]; void dfs(int u) { subtree_size[u] = 1; for (auto &v : edges[u]) { dfs(v); subtree_size[u] += subtree_size[v]; } } int main(int argc, char **argv) { registerGen(argc, argv, 1); int N = 1000000; int type = std::atoi(argv[1]); int min_n = std::atoi(argv[2]); int max_n = std::atoi(argv[3]); int t_type = std::atoi(argv[4]); std::vector<int> ns; while (N >= min_n) { ns.emplace_back(rnd.next(min_n, std::min(N, max_n))); N -= ns.back(); } if (N) ns.emplace_back(N); for (int i = 0; i < (int)ns.size(); ++i) { int n = ns[i]; std::string s, t; if (type == 1) { int c = std::atoi(argv[5]); s = gen_rand(n, c); } else if (type == 2) { int c = std::atoi(argv[5]); s = gen_thue_morse(n, c); } else if (type == 3) { s = gen_fib(n); } else if (type == 4) { std::string period = std::string(argv[5]); s = gen_period(n, period); } else if (type == 5) { int c = std::atoi(argv[5]); s = gen_geo(n, c); } else if (type == 6) { int c = std::atoi(argv[5]); s = gen_abacaba(n, c); } else if (type == 7) { std::vector<int> diff; for (int i = 5; i < argc - 1; ++i) { diff.push_back(std::atoi(argv[i])); } s = gen_border(n, diff); } n = s.size(); if (t_type == 0) { int l = rnd.next(s.size()); int r = rnd.next(s.size()); if (l > r) std::swap(l, r); t = s.substr(l, r - l + 1); } else { SuffixArray sa; sa.build(s.data(), s.size()); for (int i = 0; i <= n; ++i) { edges[i].clear(); subtree_size[i] = 0; } pi[0] = -1; for (int i = 1, j = -1; i < n; ++i) { while (j >= 0 && s[j + 1] != s[i]) j = pi[j]; pi[i] = (s[j + 1] == s[i]) ? ++j : j; } for (int i = 0; i < n; ++i) { edges[pi[i] + 1].push_back(i + 1); } dfs(0); int m = rnd.next(n / 4, n / 3); i64 best_sum = -1; int best_pos = 0; for (int i = 1, j; i <= n; i = j) { i64 sum = subtree_size[sa.sa[i]]; for (j = i + 1; j <= n && sa.lcp[j] >= m; ++j) { sum += subtree_size[sa.sa[j]]; } if (n - sa.sa[i] >= m && sum > best_sum) { best_sum = sum; best_pos = sa.sa[i]; } } t = s.substr(best_pos, m); fprintf(stderr, "%lld\n", best_sum); } printf("%s\n", s.c_str()); printf("%s\n", t.c_str()); } return 0; }
true
93841780a1cac575538693a9ea7f054a681b6fb8
C++
fengjixuchui/liblgpp
/src/lgpp/repl.hpp
UTF-8
517
2.78125
3
[ "MIT" ]
permissive
#ifndef LGPP_REPL_HPP #define LGPP_REPL_HPP #include <iostream> #include <optional> #include <sstream> namespace lgpp { using namespace std; struct REPL { REPL(istream &in, ostream &out): in(in), out(out) {} istream &in; ostream &out; function<bool (const string &line)> on_getline; }; inline void enter(REPL &repl) { stringstream buf; string line; while (getline(repl.in, line)) { if (repl.on_getline && !repl.on_getline(line)) { break; } } } } #endif
true
d4b003305d37c53d6501aaa2500124e16b3ab58d
C++
menomuel/amazing_maze
/renderobject.cpp
UTF-8
2,024
2.734375
3
[]
no_license
#include "renderobject.h" RenderObject::RenderObject() : indexBuf_(QOpenGLBuffer::IndexBuffer) { initializeOpenGLFunctions(); // Generate 2 VBOs arrayBuf_.create(); indexBuf_.create(); } RenderObject::~RenderObject() { arrayBuf_.destroy(); indexBuf_.destroy(); } void RenderObject::render(QOpenGLShaderProgram *program) { // Initialize VBOs arrayBuf_.bind(); arrayBuf_.allocate(pMesh_->vertices.data(), pMesh_->vertices.size() * sizeof(Mesh::vertexType)); indexBuf_.bind(); indexBuf_.allocate(pMesh_->indices.data(), pMesh_->indices.size() * sizeof(Mesh::indexType)); // Tell OpenGL which VBOs to use arrayBuf_.bind(); indexBuf_.bind(); // Tell OpenGL programmable pipeline how to locate vertex position data int positionLocation = program->attributeLocation("position"); program->enableAttributeArray(positionLocation); program->setAttributeBuffer(positionLocation, GL_FLOAT, offsetof(Mesh::vertexType, position), Mesh::vertexType::positionTupleSize, sizeof(Mesh::vertexType)); // Set corresponding normal int normalLocation = program->attributeLocation("normal"); program->enableAttributeArray(normalLocation); program->setAttributeBuffer(normalLocation, GL_FLOAT, offsetof(Mesh::vertexType, normal), Mesh::vertexType::normalTupleSize, sizeof(Mesh::vertexType)); // Set texture coordinates int textureLocation = program->attributeLocation("texCoord"); program->enableAttributeArray(textureLocation); program->setAttributeBuffer(textureLocation, GL_FLOAT, offsetof(Mesh::vertexType, texCoord), Mesh::vertexType::textureTupleSize, sizeof(Mesh::vertexType)); // Draw cube facets using indices glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_POLYGON_OFFSET_FILL); glPolygonOffset(2, 1); glDrawElements(GL_TRIANGLES, indexBuf_.size() / sizeof(Mesh::indexType), GL_UNSIGNED_SHORT, nullptr); }
true
415e53781c9df39ffd675d00c0a4c1816a76a3da
C++
disklogrrr/LA_Enigma
/Enigma.cpp
UTF-8
6,870
2.59375
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <windows.h> #include <time.h> void setcolor(unsigned short text, unsigned short back) { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), text | (back << 4)); } int InvMatrix(int n, const double* A, double* b) { double m; register int i, j, k; double* a = new double[n * n]; if (a == NULL) return 0; for (i = 0; i < n * n; i++) a[i] = A[i]; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { b[i * n + j] = (i == j) ? 1. : 0.; } } for (i = 0; i < n; i++) { if (a[i * n + i] == 0.) { if (i == n - 1) { delete[] a; return 0; } for (k = 1; i + k < n; k++) { if (a[i * n + i + k] != 0.) break; } if (i + k >= n) { delete[] a; return 0; } for (j = 0; j < n; j++) { m = a[i * n + j]; a[i * n + j] = a[(i + k) * n + j]; a[(i + k) * n + j] = m; m = b[i * n + j]; b[i * n + j] = b[(i + k) * n + j]; b[(i + k) * n + j] = m; } } m = a[i * n + i]; for (j = 0; j < n; j++) { a[i * n + j] /= m; b[i * n + j] /= m; } for (j = 0; j < n; j++) { if (i == j) continue; m = a[j * n + i]; for (k = 0; k < n; k++) { a[j * n + k] -= a[i * n + k] * m; b[j * n + k] -= b[i * n + k] * m; } } } delete[] a; return 1; } int Det(int(*a)[3]) { double det; det = a[0][0] * (a[1][1] * a[2][2] - a[2][1] * a[1][2]) - a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0]) + a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0]); return det; } void print_zero_one() { int i, cnt = 1; while (cnt++ <= 200) { cnt % 2 == 0 ? setcolor(2, 0) : setcolor(8, 0); i = rand() % 2; printf("%d", i); if (cnt == 101) printf("\n"); } printf("\n"); } void print_title_explain() { setcolor(10, 0); printf(" ########### ############# ### ############ #### #### ######## \n"); printf(" #### ### ## ### ### ### ## ## ### ### ## \n"); printf(" #### ### ## ### ### ### ## ## ### ### ## \n"); printf(" #### ### ## ### ### ###### ### ## ## ### ############ \n"); printf(" #### ### ## ### ### ### ### ## ### ### ## \n"); printf(" #### ### ## ### ### ## ### ### ### ## \n"); printf(" ########### ### ## ### ########### ### ### ### ## \n");setcolor(10, 0); printf("* Ver. 1.0"); printf("\n* 2017113356 Kim Min sung"); printf("\n* 2017116965 Jun geon min\n"); } int main() { print_zero_one(); print_title_explain(); print_zero_one(); char input[100]; char encrypt[100]; char output[100]; double input_digit[10][10] = { 0 }; double output_digit[10][10] = { 0 }; double in_deter_digit[10][10] = { 0 }; double out_deter_digit[10][10] = { 0 }; double encrypt_digit[10][10] = { 0 }; double key[10][10] = { {0,2,4,6,8,10,12,14,16,18},{-2,-4,-6,-8,-10,-12,-14,-16,-18,0},{4,6,8,10,12,14,16,18,0,2},{6,8,10,12,14,16,18,0,2,4}, {8,10,12,14,16,18,0,2,4,6},{-10,-12,-14,-16,-18,0,-2,-4,-6,-8},{12,14,16,18,0,2,4,6,8,10},{14,16,18,0,2,4,6,8,10,12}, {16,18,0,2,4,6,8,10,12,14},{-18,0,-2,-4,-6,-8,-10,-12,-14,-16} }; double inverse_key[10][10]; int det_key[3][3] = { {1,3,5},{-5,3,-1},{3,-1,5} }; int i, j, k = 0, det = Det(det_key); InvMatrix(10, (double*)key, (double*)inverse_key); setcolor(10, 0); printf("\n\t[ Press letters to encrypt ]\n\n"); setcolor(15, 0); scanf_s("%[^.]", input, sizeof(input)); //fgets(input, sizeof(input), stdin); setcolor(10, 0); setcolor(4, 0); printf("\n\t[ Phase 1 ..... Initial input ]\n\n"); Sleep(1000); setcolor(2, 0); while (true) { for (int i = 0;i < 10;i++) { for (int j = 0;j < 10;j++) { input_digit[i][j] = input[k]; k++; } } for (i = 0;i < 10;i++) { for (j = 0;j < 10;j++) { printf("\t%6.1f", input_digit[i][j]); Sleep(10); } Sleep(10); printf("\n\n"); } printf("\n"); break; } setcolor(4, 0); printf("\n\t[ Phase 2 ..... Using determine ]\n\n"); Sleep(1000); setcolor(2, 0); while (true) { for (int i = 0;i < 10;i++) { for (int j = 0;j < 10;j++) { in_deter_digit[i][j] = input_digit[i][j] - det; } } for (i = 0;i < 10;i++) { for (j = 0;j < 10;j++) { printf("\t%6.1f", in_deter_digit[i][j]); Sleep(10); } Sleep(10); printf("\n\n"); } printf("\n"); break; } setcolor(4, 0); printf("\n\t[ Phase 3 ..... Using key matrix ]\n\n"); Sleep(1000); setcolor(2, 0); while (true) { for (i = 0; i < 10; i++) { for (j = 0; j < 10; j++) { for (k = 0; k < 10; k++) { encrypt_digit[i][j] += key[i][k] * in_deter_digit[k][j]; } } } for (i = 0;i < 10;i++) { for (j = 0;j < 10;j++) { printf("\t%5.1f", encrypt_digit[i][j] + -1 *(rand() % 10000) + 5000); Sleep(10); } Sleep(10); printf("\n\n"); } printf("\n"); break; } setcolor(4, 0); printf("\n\t[ Phase 4 ..... Using inverse key matrix ]\n\n"); Sleep(1000); setcolor(2, 0); while (true) { for (i = 0; i < 10; i++) { for (j = 0; j < 10; j++) { for (k = 0; k < 10; k++) { out_deter_digit[i][j] += inverse_key[i][k] * encrypt_digit[k][j]; } } } for (i = 0; i < 10; i++) { for (j = 0; j < 10; j++) { printf("\t%6.1f", out_deter_digit[i][j]); Sleep(10); } Sleep(10); printf("\n\n"); } printf("\n"); break; } setcolor(4, 0); printf("\n\t[ Phase 5 ..... Using determine ]\n\n"); Sleep(1000); setcolor(2, 0); while (true) { k = 0; for (int i = 0;i < 10;i++) { for (int j = 0;j < 10;j++) { output_digit[i][j] = (out_deter_digit[i][j] + det); } } for (i = 0; i < 10; i++) { for (j = 0; j < 10; j++) { printf("\t%6.1f", output_digit[i][j]); Sleep(10); } Sleep(10); printf("\n\n"); } break; } setcolor(4, 0); printf("\n\t[ Phase 6 ..... Decoded output ]\n\n"); Sleep(1000); setcolor(2, 0); while (true) { printf("\t"); for (i = 0; i < 10; i++) { for (j = 0; j < 10; j++) { output[k] = output_digit[i][j] + 0.5; k++; setcolor(8, 0); printf("."); Sleep(20); } } break; } printf("\n\n"); setcolor(10, 0); printf("\t[ Your initial letter ] \n\n", output); setcolor(10, 0); setcolor(15, 0); Sleep(1000); i = 0; while (output[i]) { printf("%c", output[i]); Sleep(150); i++; } printf("\n\n"); return 0; }
true
e6d48160b50bafc70abdafe9d4dd16abb081f6e2
C++
Kingwl/MiniStl
/mini stl/Stack/Stack.cpp
GB18030
304
2.84375
3
[]
no_license
// Stack.cpp : ̨Ӧóڵ㡣 // #include "stdafx.h" #include "Stack.hpp" int _tmain(int argc, _TCHAR* argv[]) { Stack<int> s; s.push(1); s.push(2); std::cout << s.top(); s.pop(); std::cout << s.top(); s.pop(); std::cout << s.size(); system("pause"); return 0; }
true
e7f631d772933ab87146ce0a1ee3ec2befae3919
C++
neowei1987/Zeus
/algorithm/dfs.cc
UTF-8
2,206
3
3
[]
no_license
#include "iostream" #include <vector> #include <sstream> #include <stack> #include "defines.h" #include <map> using namespace std; /* dfs */ class Solution { public: void dfs(vector<vector<char>>& grid, int m, int n, int i, int j, vector<bool>& visit) { //方向数组 pair<int, int> ds[4] = { {1, 0}, {-1, 0}, {0, 1}, {0, -1}, }; for (int di = 0; di < sizeof(ds) / sizeof(ds[0]); ++di) { int ni = i + ds[di].first; int nj = j + ds[di].second; if (ni >= 0 && ni < m && nj >= 0 && nj < n //范围合法 && grid[ni][nj] == '1' //陆地 && !visit[ni * n + nj] //没有访问过 ) { visit[ni * n + nj] = true; dfs(grid, m, n, ni, nj, visit); } } } //模型:最大连通子图数 int numIslands(vector<vector<char>>& grid) { int m = grid.size(); if (m == 0) { return 0; } int n = grid[0].size(); if (n == 0) { return 0; } vector<bool> visit(m * n, false); int count = 0; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (grid[i][j] == '1' && !visit[i * n + j]) { visit[i * n + j] = true; count++; dfs(grid, m, n, i, j, visit); } } } return count; } }; int main() { std::stringstream ss; ss << "[1,2,3,4]"; std::vector<int> pushed; std::vector<int> popped; int k = 0; //std::cin >> nums; //std::cin >> k; ss >> pushed; ss.str(""); ss << "[2]"; ss >> popped; int ret = 0; Solution problem; //problem.printNumbers(5); //cout << problem.validateStackSequences(pushed, popped); //cout << problem.search(nums, k); //problem.permute(pushed); //cout << problem.majorityElement(popped); //problem.getLeastNumbers(popped, 0); ret = problem.coinChange(popped, 3); cout << "result: " << ret << "\n"; return 0; }
true
b28906b69bcb72f40e557c8e3198c3dac66dbdb5
C++
sraihan73/Lucene-
/core/src/test/org/apache/lucene/util/automaton/TestLevenshteinAutomata.cpp
UTF-8
12,755
2.59375
3
[]
no_license
using namespace std; #include "TestLevenshteinAutomata.h" namespace org::apache::lucene::util::automaton { using LuceneTestCase = org::apache::lucene::util::LuceneTestCase; // import static // org.apache.lucene.util.automaton.Operations.DEFAULT_MAX_DETERMINIZED_STATES; void TestLevenshteinAutomata::testLev0() { assertLev(L"", 0); assertCharVectors(0); } void TestLevenshteinAutomata::testLev1() { assertLev(L"", 1); assertCharVectors(1); } void TestLevenshteinAutomata::testLev2() { assertLev(L"", 2); assertCharVectors(2); } void TestLevenshteinAutomata::testNoWastedStates() { assertFalse(Operations::hasDeadStatesFromInitial( (make_shared<LevenshteinAutomata>(L"abc", false))->toAutomaton(1))); } void TestLevenshteinAutomata::assertCharVectors(int n) { int k = 2 * n + 1; // use k + 2 as the exponent: the formula generates different transitions // for w, w-1, w-2 int limit = static_cast<int>(pow(2, k + 2)); for (int i = 0; i < limit; i++) { // C++ TODO: There is no native C++ equivalent to 'toString': wstring encoded = Integer::toString(i, 2); assertLev(encoded, n); } } void TestLevenshteinAutomata::assertLev(const wstring &s, int maxDistance) { shared_ptr<LevenshteinAutomata> builder = make_shared<LevenshteinAutomata>(s, false); shared_ptr<LevenshteinAutomata> tbuilder = make_shared<LevenshteinAutomata>(s, true); std::deque<std::shared_ptr<Automaton>> automata(maxDistance + 1); std::deque<std::shared_ptr<Automaton>> tautomata(maxDistance + 1); for (int n = 0; n < automata.size(); n++) { automata[n] = builder->toAutomaton(n); tautomata[n] = tbuilder->toAutomaton(n); assertNotNull(automata[n]); assertNotNull(tautomata[n]); assertTrue(automata[n]->isDeterministic()); assertTrue(tautomata[n]->isDeterministic()); assertTrue(Operations::isFinite(automata[n])); assertTrue(Operations::isFinite(tautomata[n])); assertFalse(Operations::hasDeadStatesFromInitial(automata[n])); assertFalse(Operations::hasDeadStatesFromInitial(tautomata[n])); // check that the dfa for n-1 accepts a subset of the dfa for n if (n > 0) { assertTrue( Operations::subsetOf(Operations::removeDeadStates(automata[n - 1]), Operations::removeDeadStates(automata[n]))); assertTrue( Operations::subsetOf(Operations::removeDeadStates(automata[n - 1]), Operations::removeDeadStates(tautomata[n]))); assertTrue( Operations::subsetOf(Operations::removeDeadStates(tautomata[n - 1]), Operations::removeDeadStates(automata[n]))); assertTrue( Operations::subsetOf(Operations::removeDeadStates(tautomata[n - 1]), Operations::removeDeadStates(tautomata[n]))); assertNotSame(automata[n - 1], automata[n]); } // check that Lev(N) is a subset of LevT(N) assertTrue( Operations::subsetOf(Operations::removeDeadStates(automata[n]), Operations::removeDeadStates(tautomata[n]))); // special checks for specific n switch (n) { case 0: // easy, matches the string itself assertTrue(Operations::sameLanguage( Automata::makeString(s), Operations::removeDeadStates(automata[0]))); assertTrue(Operations::sameLanguage( Automata::makeString(s), Operations::removeDeadStates(tautomata[0]))); break; case 1: // generate a lev1 naively, and check the accepted lang is the same. assertTrue(Operations::sameLanguage( naiveLev1(s), Operations::removeDeadStates(automata[1]))); assertTrue(Operations::sameLanguage( naiveLev1T(s), Operations::removeDeadStates(tautomata[1]))); break; default: assertBruteForce(s, automata[n], n); assertBruteForceT(s, tautomata[n], n); break; } } } shared_ptr<Automaton> TestLevenshteinAutomata::naiveLev1(const wstring &s) { shared_ptr<Automaton> a = Automata::makeString(s); a = Operations::union_(a, insertionsOf(s)); a = MinimizationOperations::minimize(a, DEFAULT_MAX_DETERMINIZED_STATES); a = Operations::union_(a, deletionsOf(s)); a = MinimizationOperations::minimize(a, DEFAULT_MAX_DETERMINIZED_STATES); a = Operations::union_(a, substitutionsOf(s)); a = MinimizationOperations::minimize(a, DEFAULT_MAX_DETERMINIZED_STATES); return a; } shared_ptr<Automaton> TestLevenshteinAutomata::naiveLev1T(const wstring &s) { shared_ptr<Automaton> a = naiveLev1(s); a = Operations::union_(a, transpositionsOf(s)); a = MinimizationOperations::minimize(a, DEFAULT_MAX_DETERMINIZED_STATES); return a; } shared_ptr<Automaton> TestLevenshteinAutomata::insertionsOf(const wstring &s) { deque<std::shared_ptr<Automaton>> deque = deque<std::shared_ptr<Automaton>>(); for (int i = 0; i <= s.length(); i++) { shared_ptr<Automaton> a = Automata::makeString(s.substr(0, i)); a = Operations::concatenate(a, Automata::makeAnyChar()); a = Operations::concatenate(a, Automata::makeString(s.substr(i))); deque.push_back(a); } shared_ptr<Automaton> a = Operations::union_(deque); a = MinimizationOperations::minimize(a, DEFAULT_MAX_DETERMINIZED_STATES); return a; } shared_ptr<Automaton> TestLevenshteinAutomata::deletionsOf(const wstring &s) { deque<std::shared_ptr<Automaton>> deque = deque<std::shared_ptr<Automaton>>(); for (int i = 0; i < s.length(); i++) { shared_ptr<Automaton> a = Automata::makeString(s.substr(0, i)); a = Operations::concatenate(a, Automata::makeString(s.substr(i + 1))); deque.push_back(a); } shared_ptr<Automaton> a = Operations::union_(deque); a = MinimizationOperations::minimize(a, DEFAULT_MAX_DETERMINIZED_STATES); return a; } shared_ptr<Automaton> TestLevenshteinAutomata::substitutionsOf(const wstring &s) { deque<std::shared_ptr<Automaton>> deque = deque<std::shared_ptr<Automaton>>(); for (int i = 0; i < s.length(); i++) { shared_ptr<Automaton> a = Automata::makeString(s.substr(0, i)); a = Operations::concatenate(a, Automata::makeAnyChar()); a = Operations::concatenate(a, Automata::makeString(s.substr(i + 1))); deque.push_back(a); } shared_ptr<Automaton> a = Operations::union_(deque); a = MinimizationOperations::minimize(a, DEFAULT_MAX_DETERMINIZED_STATES); return a; } shared_ptr<Automaton> TestLevenshteinAutomata::transpositionsOf(const wstring &s) { if (s.length() < 2) { return Automata::makeEmpty(); } deque<std::shared_ptr<Automaton>> deque = deque<std::shared_ptr<Automaton>>(); for (int i = 0; i < s.length() - 1; i++) { shared_ptr<StringBuilder> sb = make_shared<StringBuilder>(); sb->append(s.substr(0, i)); sb->append(s[i + 1]); sb->append(s[i]); sb->append(s.substr(i + 2, s.length() - (i + 2))); wstring st = sb->toString(); if (st != s) { deque.push_back(Automata::makeString(st)); } } shared_ptr<Automaton> a = Operations::union_(deque); a = MinimizationOperations::minimize(a, DEFAULT_MAX_DETERMINIZED_STATES); return a; } void TestLevenshteinAutomata::assertBruteForce(const wstring &input, shared_ptr<Automaton> dfa, int distance) { shared_ptr<CharacterRunAutomaton> ra = make_shared<CharacterRunAutomaton>(dfa); int maxLen = input.length() + distance + 1; int maxNum = static_cast<int>(pow(2, maxLen)); for (int i = 0; i < maxNum; i++) { // C++ TODO: There is no native C++ equivalent to 'toString': wstring encoded = Integer::toString(i, 2); bool accepts = ra->run(encoded); if (accepts) { assertTrue(getDistance(input, encoded) <= distance); } else { assertTrue(getDistance(input, encoded) > distance); } } } void TestLevenshteinAutomata::assertBruteForceT(const wstring &input, shared_ptr<Automaton> dfa, int distance) { shared_ptr<CharacterRunAutomaton> ra = make_shared<CharacterRunAutomaton>(dfa); int maxLen = input.length() + distance + 1; int maxNum = static_cast<int>(pow(2, maxLen)); for (int i = 0; i < maxNum; i++) { // C++ TODO: There is no native C++ equivalent to 'toString': wstring encoded = Integer::toString(i, 2); bool accepts = ra->run(encoded); if (accepts) { assertTrue(getTDistance(input, encoded) <= distance); } else { assertTrue(getTDistance(input, encoded) > distance); } } } int TestLevenshteinAutomata::getDistance(const wstring &target, const wstring &other) { std::deque<wchar_t> sa; int n; std::deque<int> p; //'previous' cost array, horizontally std::deque<int> d; // cost array, horizontally std::deque<int> _d; // placeholder to assist in swapping p and d /* The difference between this impl. and the previous is that, rather than creating and retaining a matrix of size s.length()+1 by t.length()+1, we maintain two single-dimensional arrays of length s.length()+1. The first, d, is the 'current working' distance array that maintains the newest distance cost counts as we iterate through the characters of std::wstring s. Each time we increment the index of std::wstring t we are comparing, d is copied to p, the second int[]. Doing so allows us to retain the previous cost counts as required by the algorithm (taking the minimum of the cost count to the left, up one, and diagonally up and to the left of the current cost count being calculated). (Note that the arrays aren't really copied anymore, just switched...this is clearly much better than cloning an array or doing a System.arraycopy() each time through the outer loop.) Effectively, the difference between the two implementations is this one does not cause an out of memory condition when calculating the LD over two very large strings. */ sa = target.toCharArray(); n = sa.size(); p = std::deque<int>(n + 1); d = std::deque<int>(n + 1); constexpr int m = other.length(); if (n == 0 || m == 0) { if (n == m) { return 0; } else { return max(n, m); } } // indexes into strings s and t int i; // iterates through s int j; // iterates through t wchar_t t_j; // jth character of t int cost; // cost for (i = 0; i <= n; i++) { p[i] = i; } for (j = 1; j <= m; j++) { t_j = other[j - 1]; d[0] = j; for (i = 1; i <= n; i++) { cost = sa[i - 1] == t_j ? 0 : 1; // minimum of cell to the left+1, to the top+1, diagonally left and up // +cost d[i] = min(min(d[i - 1] + 1, p[i] + 1), p[i - 1] + cost); } // copy current distance counts to 'previous row' distance counts _d = p; p = d; d = _d; } // our last action in the above loop was to switch d and p, so p now // actually has the most recent cost counts return abs(p[n]); } int TestLevenshteinAutomata::getTDistance(const wstring &target, const wstring &other) { std::deque<wchar_t> sa; int n; std::deque<std::deque<int>> d; // cost array sa = target.toCharArray(); n = sa.size(); constexpr int m = other.length(); // C++ NOTE: The following call to the 'RectangularVectors' helper class // reproduces the rectangular array initialization that is automatic in Java: // ORIGINAL LINE: d = new int[n+1][m+1]; d = RectangularVectors::ReturnRectangularIntVector(n + 1, m + 1); if (n == 0 || m == 0) { if (n == m) { return 0; } else { return max(n, m); } } // indexes into strings s and t int i; // iterates through s int j; // iterates through t wchar_t t_j; // jth character of t int cost; // cost for (i = 0; i <= n; i++) { d[i][0] = i; } for (j = 0; j <= m; j++) { d[0][j] = j; } for (j = 1; j <= m; j++) { t_j = other[j - 1]; for (i = 1; i <= n; i++) { cost = sa[i - 1] == t_j ? 0 : 1; // minimum of cell to the left+1, to the top+1, diagonally left and up // +cost d[i][j] = min(min(d[i - 1][j] + 1, d[i][j - 1] + 1), d[i - 1][j - 1] + cost); // transposition if (i > 1 && j > 1 && target[i - 1] == other[j - 2] && target[i - 2] == other[j - 1]) { d[i][j] = min(d[i][j], d[i - 2][j - 2] + cost); } } } // our last action in the above loop was to switch d and p, so p now // actually has the most recent cost counts return abs(d[n][m]); } } // namespace org::apache::lucene::util::automaton
true
f2e5741ab72774f84d873a18381b352c173bffee
C++
Wingedcross/UCR-CS14-Lab6
/Lab 6/AVLTree.h
UTF-8
752
2.8125
3
[]
no_license
#pragma once #ifndef __AVLTREE_H #define __AVLTREE_H #include "Node.h" #include <fstream> #include <string> using std::string; using std::ofstream; // Class declaration for EVLTree class AVLTree { private: Node * root; Node * findUnbalancedNode(const string &); void insert(const string &, Node *); void visualizeTree(ofstream &, Node *); void updateHeight(Node *); void printBalanceFactors(Node *); void setChild(Node *, const string &, Node *); void replaceChild(Node *, Node *, Node *); void rotateLeft(Node *); void rotateRight(Node *); void rebalance(const string &, Node *); public: AVLTree(); int balanceFactor(Node*); void insert(const string &); void printBalanceFactors(); void visualizeTree(const string &); }; #endif
true
ff78e14bdbf7942c352edc7e186a11d08c5624c1
C++
MarcosK11/Campo-Minado
/main.cpp
UTF-8
6,625
2.8125
3
[]
no_license
#include <iostream> #include <stdlib.h> #include <time.h> #define NADA 0 #define MINA -1 using namespace std; int main() { int bombas, auxBombas, posL=0, posC=0, Lin, Col, qtlinha, qtcoluna, auxCoord, entradaLinha, entradaColuna, qtdJogadas = 0, fimDeJogo = 0; srand(time(NULL)); // Entrada de dados cout << "Insira quantidade de linhas: " ; cin >> qtlinha; cout << "Insira quantidade de colunas: "; cin >> qtcoluna; cout << "Insira quantidade de bombas: "; cin >> bombas; // Verificando se todas as entradas estão corretas while(qtlinha < 2){ cout << "Tamanho incorreto, insira novamente a quantidade de linhas:"; cin >> qtlinha; } while(qtcoluna < 2){ cout << "Tamanho incorreto, insira novamente a quantidade de colunas:"; cin >> qtcoluna; } while(bombas < 2 || bombas > (qtlinha * qtcoluna)){ cout << "Numero insuficiente ou excedente de bombas! Insira novamente a quantidade de bombas: "; cin >> bombas; } // criando o mapa int campo_1[qtlinha][qtcoluna]; char campo_2[qtlinha][qtcoluna]; for(Lin=0; Lin < qtlinha; Lin++){ for(Col=0;Col < qtcoluna; Col++){ campo_1[Lin][Col] = NADA; campo_2[Lin][Col] = ' '; } } auxBombas = bombas; /// sorteio das bombas rand() while(auxBombas>0){ posL=rand()%qtlinha; posC=rand()%qtcoluna; // Verifica se posL e posC estão nos limites do campo (linha e coluna) if(posL >= 0 && posL < qtlinha && posC >= 0 && posC < qtcoluna) { if(campo_1[posL][posC] != MINA){ campo_1[posL][posC] = MINA; // Verifica se posC + 1 está nos limites da coluna e se posC + 1 não é uma mina if(posC + 1 < qtcoluna && campo_1[posL][posC + 1] != MINA) { campo_1[posL][posC + 1]++; } // Verifica se o posC - 1 esta nos limites da coluna e se posC - 1 não é uma mina if(posC - 1 >= 0 && campo_1[posL][posC - 1] != MINA) { campo_1[posL][posC - 1]++; } // Verfica se o posL + 1 esta nos limites da linha e se posL + 1 não é uma mina if(posL + 1 < qtlinha && campo_1[posL + 1][posC] != MINA) { campo_1[posL + 1][posC]++; } // Verifica se o posL - 1 esta nos limites da linha e se posL -1 não é uma mina if(posL - 1 >= 0 && campo_1[posL - 1][posC] != MINA) { campo_1[posL - 1][posC]++; } // Verifica se posL - 1 esta nos limites da linha e se posC + 1 esta nos limites da coluna e se posL - 1 e pos C + 1 não é uma mina if(posL - 1 >= 0 && posC + 1 < qtcoluna && campo_1[posL - 1][posC + 1] != MINA) { campo_1[posL - 1][posC + 1]++; } // Verifica se posL - 1 esta nos limites da linha e se posC - 1 esta nos limites da coluna e se posL -1 e posC - 1 não é uma mina if(posL - 1 >= 0 && posC -1 >= 0 && campo_1[posL - 1][posC - 1] != MINA) { campo_1[posL - 1][posC - 1]++; } // Verifica se posL + 1 esta nos limites da linha e se posC + 1 esta nos limites da coluna e se posL + 1 e posC + 1 não é uma mina if(posL + 1 < qtlinha && posC + 1 < qtcoluna && campo_1[posL + 1][posC + 1] != MINA) { campo_1[posL + 1][posC + 1]++; } // Verifica se posL + 1 esta nos limites da linha posC - 1 esta nos limites da coluna e se posL + 1 e posC - 1 não é uma mina if(posL + 1 < qtlinha && posC - 1 >= 0 && campo_1[posL + 1][posC - 1] != MINA) { campo_1[posL + 1][posC - 1]++; } auxBombas--; } } } // enquanto fimDeJogo = 0, continua o while while(fimDeJogo == 0) { system("CLS"); cout << "\t"; // Imprime as coordenadas das colunas for(auxCoord=0; auxCoord < qtlinha; auxCoord++) { cout << auxCoord + 1 << "\t"; } cout << endl; cout << "\t"; for(auxCoord=0; auxCoord < qtlinha; auxCoord++) { cout << "-" << "\t"; } cout << endl; for(Lin=0;Lin<qtlinha; Lin++){ for(Col=0;Col<qtcoluna;Col++){ // Caso seja a primeira coluna, imprime a coordenada da linha if(Col == 0) { cout << Lin + 1 << " | " << "\t"; } // Imprime o valor do campo atual cout << campo_2[Lin][Col] << "\t"; } cout << endl; } cout << endl; // Leitura da jogada, linha e coluna cout << "Informe uma linha: "; cin >> entradaLinha; cout << "Informe uma coluna: "; cin >> entradaColuna; // Verifica se a jogada na linha está dentro dos limites do campo if(entradaLinha > 0 && entradaLinha <= qtlinha ) { // Verifica se a jogada na coluna está dentro dos limites do campo if(entradaColuna > 0 && entradaColuna <= qtcoluna) { // Salva valor no campo2, somase o char '0' + o valor inteiro para gerar o valor em char campo_2[entradaLinha-1][entradaColuna-1] = '0' + campo_1[entradaLinha-1][entradaColuna-1]; // verifica se a jogada acertou uma mina if(campo_1[entradaLinha-1][entradaColuna-1] == MINA) { // Define fim de jogo fimDeJogo = 1; // Imprime mensagem e o numero de jogadas validas cout << endl << "Você acertou uma mina, fim de jogo!" << endl; cout << "Nr de jogadas validas: " << qtdJogadas; // break; } else { // Soma a quantidade de jogadas válidas qtdJogadas++; } // Verifica se a quantidade de jogadas válidas é igual ao numero de campos livres menos o numero de bombas if (qtdJogadas == ((qtlinha * qtcoluna) - bombas)) { // Define fim de jogo fimDeJogo = 1; // Imprime mensagem e o numero de jogadas validas cout << endl << "Você venceu !" << endl; cout << "Nr de jogadas validas: " << qtdJogadas << endl; } } else { // Imprime aviso de coluna invalida cout << endl << "Coluna inválida, informe um valor válido para linha!" << endl << endl; } } else { // Imprime aviso de linha invalida cout << endl << "Linha inválida, informe um valor válido para linha!" << endl << endl; } } return 0; }
true
db37b785876f65251640881f1cb7997c52e789a1
C++
averywallis/Assorted-Arduino-Code
/alternate_SD_logging/alternate_SD_logging.ino
UTF-8
2,173
2.921875
3
[]
no_license
/* SD card test This example shows how use the utility libraries on which the' SD library is based in order to get info about your SD card. Very useful for testing a card when you're not sure whether its working or not. The circuit: SD card attached to SPI bus as follows: ** MOSI - pin 11 on Arduino Uno/Duemilanove/Diecimila ** MISO - pin 12 on Arduino Uno/Duemilanove/Diecimila ** CLK - pin 13 on Arduino Uno/Duemilanove/Diecimila ** CS - depends on your SD card shield or module. Pin 4 used here for consistency with other Arduino examples created 28 Mar 2011 by Limor Fried modified 9 Apr 2012 by Tom Igoe */ // include the SD library: #include <SPI.h> #include "SdFat.h" #include "wiring_private.h" // pinPeripheral() function SPIClass SPI_2 (&sercom1, 12, 13, 11, SPI_PAD_0_SCK_1, SERCOM_RX_PAD_3); //SPIClass mySPI(2); // set up variables using the SD utility library functions: SdFat sd2(&SPI_2); //SdFat sd2(SPIClass mySPI (&sercom1, 12, 13, 11, SPI_PAD_0_SCK_1, SERCOM_RX_PAD_3)); SdFile file; // change this to match your SD shield or module; // Arduino Ethernet shield: pin 4 // Adafruit SD shields and modules: pin 10 // Sparkfun SD shield: pin 8 // MKRZero SD: SDCARD_SS_PIN const int chipSelect = 2; void setup() { // Open serial communications and wait for port to open: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for native USB port only } SPI_2.begin(); // Assign pins 11, 12, 13 to SERCOM functionality pinPeripheral(11, PIO_SERCOM); pinPeripheral(12, PIO_SERCOM); pinPeripheral(13, PIO_SERCOM); Serial.print("\nInitializing SD card..."); // we'll use the initialization code from the utility libraries // since we're just testing if the card is working! while (!sd2.begin(2)) { sd2.initErrorPrint("sd2:"); Serial.println("Init error"); delay(200); } Serial.println("SD init correctly"); } void loop(void) { // Force data to SD and update the directory entry to avoid data loss. file.print("potatoe"); if (!file.sync() || file.getWriteError()) { Serial.println("Write error"); } file.close(); delay(1000); }
true
63a392fa8599d378473429fac24f12cc0f4b4375
C++
KertAles/Osvajalec-Game
/queueitem.cpp
UTF-8
306
2.515625
3
[]
no_license
#include "mainwindow.h" #include "queueitem.h" extern MainWindow* w; QueueItem::QueueItem(){ owner = nullptr; pos = nullptr; } void QueueItem::countdown() { turnsLeft--; qDebug() << "Countdown for" << type << " Left: " << turnsLeft; if(turnsLeft < 1) { createItem(); } }
true
f85154e8ec9b8c26c5f7217ac2c3778afb1d29e5
C++
aquan0/C-
/hoanvi.cpp
UTF-8
539
2.671875
3
[]
no_license
#include<iostream> using namespace std; int Bool[30] = {0}; int arr[30] = {0}; int n; void xuat(); void Try(int i); int main() { cin >> n; Try(1); } void xuat() { for(int i = 1; i <= n; i++) { cout << arr[i]; } cout << " "; } void Try(int k) { for(int i = 1; i <= n; i++) { if(!Bool[i]) { arr[k] = i; Bool[i] = 1; if(k == n) { xuat(); } else { Try(k+1); } Bool[i] = 0; } } }
true
48bbf05dc00f845717ece3a541b38244c2057f72
C++
yangqi137/lattices
/src/lattices/bravias3d/offset.hpp
UTF-8
2,528
2.75
3
[ "MIT" ]
permissive
#ifndef LATTICES_BRAVIAS3D_OFFSET_HPP #define LATTICES_BRAVIAS3D_OFFSET_HPP #include "lattice.hpp" #include <type_traits> #include <cassert> #include <algorithm> namespace lattices { namespace bravias3d { template <typename TAG, typename SIZE_TYPE> struct OffsetCat { typedef TAG Tag; typedef SIZE_TYPE VSize; typedef LatticeCat<TAG, VSize> LatticeCat; typedef typename LatticeCat::Lattice Lattice; typedef typename LatticeCat::Vertex Vertex; typedef typename LatticeCat::Vid Vid; typedef typename std::make_signed<Vid>::type OffsetType; static void offset_rewind(Vid& x, OffsetType dx, Vid l) { assert(dx > -((OffsetType)l)); if (dx < 0) dx += l; x += dx; x %= l; } struct Offset { OffsetType dx; OffsetType dy; OffsetType dz; }; static Vid dx_max(const Lattice& l) { return l.lx / 2; } static Vid dy_max(const Lattice& l) { return l.ly / 2; } static Vid dz_max(const Lattice& l) { return l.lz / 2; } static void shift(Vertex& v, const Vertex& dv, const Lattice& l) { v.x += dv.x; v.x %= l.lx; v.y += dv.y; v.y %= l.ly; v.z += dv.z; v.z %= l.lz; } static void shift(Vertex& v, const Offset& dv, const Lattice& l) { offset_rewind(v.x, dv.dx, l.lx); offset_rewind(v.y, dv.dy, l.ly); offset_rewind(v.z, dv.dz, l.lz); } static void shift(Vid& vid, Vid dvid, const Lattice& l) { Vertex v = LatticeCat::vertex(vid, l); Vertex dv = LatticeCat::vertex(dvid, l); shift(v, dv, l); vid = LatticeCat::vid(v, l); } static Offset offset(const Vertex& v0, const Vertex& v1) { Offset dv = {v1.x - v0.x, v1.y - v0.y, v1.z - v0.z}; return dv; } static Vid dv2id(const Offset& dv, const Lattice& l) { Vertex v = LatticeCat::vertex(0, l); shift(v, dv, l); return LatticeCat::vid(v, l); } static Offset reverse_offset(const Offset& dv, const Lattice& l) { Offset dv2 = {-dv.dx, -dv.dy, -dv.dz}; return dv2; } static void minus(Vertex& v, const Lattice& l) { v.x = (l.lx - v.x) % l.lx; v.y = (l.ly - v.y) % l.ly; v.z = (l.lz - v.z) % l.lz; } static void minus(Vid& vid, const Lattice& l) { Vertex v = LatticeCat::vertex(vid, l); minus(v, l); vid = LatticeCat::vid(v, l); } }; } } #endif
true
d82f3c12b30ef534598dcb77f6b496fb7e49f10e
C++
intoxicated/Graphics
/Vector/Vector.cpp
UTF-8
6,493
3.65625
4
[]
no_license
/** * Vector Implementation * * Purpose: Vector class allows an application to perform * vector arithmatic in a simple manner. * * Author: Wooyoung Chung * * Date: Jan 13th, 2014 * * This work complies with the JMU Honor Code. */ #include "Vector.h" #pragma mark - Constructors Vector::Vector(int size) { this->setSize(size, Vector::ROW); this->allocateMemory(); this->setValues(0.0); } Vector::Vector(int size, char orientation) { this->setSize(size, orientation); this->allocateMemory(); this->setValues(0.0); } Vector::Vector(const Vector& original) { this->setSize(original.size, original.orientation); this->allocateMemory(); this->setValues(original.values); } Vector::~Vector() { this->deallocateMemory(); } #pragma mark - Access members methods double Vector::get(int i) const { if(this->size < i || 0 >= i) throw std::out_of_range("Out of range"); //throw exception return this->values[i-1]; } char Vector::getOrientation() const { return this->orientation; } int Vector::getSize() const { return this->size; } #pragma mark - Norm related methods double norm(const Vector& a) { double retNorm = 0; for(int i = 0; i < a.size; ++i) retNorm += pow(a.values[i], 2); return sqrt(retNorm); } Vector normalized(const Vector& a) { Vector normVector(a.size, a.orientation); double normVal = norm(a); for(int i = 0; i < a.size; ++i) normVector.values[i] = a.values[i] / normVal; return normVector; } #pragma mark - Overloading operator methods double& Vector::operator()(int i) { if( this->size < i|| 0 >= i) throw std::out_of_range("Out of range"); //throw exception return this->values[i-1]; } Vector& Vector::operator=(std::initializer_list<double> values) { if(values.size() != this->size) throw std::length_error("Size is not matched"); //clean perivous allocation std::initializer_list<double>::iterator it; int i; for(i = 0, it = values.begin(); it != values.end(); ++it, ++i) this->values[i] = *it; return *this; } Vector& Vector::operator=(const Vector &other) { if(this->size != other.size) throw std::length_error("Two vector's length is not same"); // throw exception if(this->orientation != other.orientation) throw std::length_error("Two vector's orientation is not same"); this->setValues(other.values); return *this; } Vector operator+(const Vector& a, const Vector& b) { if(a.size != b.size) throw std::length_error("Two vector's length is not same"); // throw exception if(a.orientation != b.orientation) throw std::length_error("Two vector's orientation is not same"); Vector *c = new Vector(a.size, a.orientation); for(int i = 0; i < a.size; ++i) c->values[i] = a.values[i] + b.values[i]; return *c; } Vector operator-(const Vector& a, const Vector& b) { if(a.size != b.size) throw std::length_error("Two vector's length is not same"); // throw exception if(a.orientation != b.orientation) throw std::length_error("Two vector's orientation is not same"); Vector *c = new Vector(a.size, a.orientation); for(int i = 0; i < a.size; ++i) c->values[i] = a.values[i] - b.values[i]; return *c; } double operator*(const Vector& a, const Vector& b) { if(a.size != b.size) throw std::length_error("Two vector's length is not same"); // throw exception if(a.orientation != b.orientation) throw std::length_error("Two vector's orientation is not same"); double ret = 0; for(int i = 0; i < a.size; ++i) ret += a.values[i] * b.values[i]; return ret; } Vector operator*(double k, const Vector& a) { Vector * retVector = new Vector(a.size, a.orientation); for(int i = 0; i < a.size; ++i) retVector->values[i] = a.values[i] * k; return *retVector; } Vector operator*(const Vector& a, double k) { Vector * retVector = new Vector(a.size, a.orientation); for(int i = 0; i < a.size; ++i) retVector->values[i] = a.values[i] * k; return *retVector; } bool operator==(const Vector& a, const Vector& b) { if(a.size != b.size || a.orientation != b.orientation) return false; bool ret = true; for(int i = 0; i < a.size; ++i) { if(a.values[i] != b.values[i]) { ret = false; break; } } return ret; } bool operator!=(const Vector& a, const Vector& b) { if(a.size != b.size || a.orientation != b.orientation) return true; bool ret = false; for(int i = 0; i < a.size; ++i) { if(a.values[i] != b.values[i]) { ret = true; break; } } return ret; } #pragma mark - Miscellaneous methods Vector trans(const Vector& a) { Vector retVector(a); if(a.orientation == Vector::ROW) retVector.orientation = Vector::COLUMN; else retVector.orientation = Vector::ROW; return retVector; } #pragma mark - Debug helper methods double * Vector::get_content() const { /*printf("====== Vector Information =====\n"); printf("= vector size : %d\n", this->size); printf("= vector orientation : %s\n", this->orientation == 0 ? "Column" : "Row"); printf("= vector values start\n"); for(int i = 0; i < this->size; ++i) { printf("%2f ", this->values[i]); } printf("\n= vector values end\n"); printf("======= Vector Info End ======\n"); */ return this->values; } #pragma mark - Protected methods void Vector::allocateMemory() { this->values = new double[this->size]; } void Vector::deallocateMemory() { delete[] this->values; } void Vector::setSize(int size, char orientation) { if(size < 0) throw std::invalid_argument("Negative size is invalid"); //throw exception if(orientation != this->ROW && orientation != this->COLUMN) throw std::invalid_argument("Not valid orientation"); //throw exception this->size = size; this->orientation = orientation; } void Vector::setValues(double value) { for(int i = 0; i < this->size; ++i) this->values[i] = value; } void Vector::setValues(const double *values) { for(int i = 0; i < this->size; ++i) { this->values[i] = values[i]; } }
true
91d77c2ab452d46992da5bfad460084cdd239be9
C++
DinCahill/ury-playd
/src/tokeniser.cpp
UTF-8
2,682
3.015625
3
[ "MIT", "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// This file is part of playd. // playd is licensed under the MIT licence: see LICENSE.txt. /** * @file * Definition of the Tokeniser class. * @see tokeniser.hpp */ #include <algorithm> #include <cassert> #include <cctype> #include <cstdint> #include "response.hpp" #include "tokeniser.hpp" Tokeniser::Tokeniser() : escape_next(false), in_word(false), quote_type(Tokeniser::QuoteType::NONE) { } std::vector<std::vector<std::string>> Tokeniser::Feed(const std::string &raw) { // The list of ready lines should be cleared by any previous Feed. assert(this->ready_lines.empty()); for (char c : raw) { if (this->escape_next) { this->Push(c); continue; } switch (this->quote_type) { case QuoteType::SINGLE: if (c == '\'') { this->quote_type = QuoteType::NONE; } else { this->Push(c); } break; case QuoteType::DOUBLE: switch (c) { case '\"': this->quote_type = QuoteType::NONE; break; case '\\': this->escape_next = true; break; default: this->Push(c); break; } break; case QuoteType::NONE: switch (c) { case '\n': this->Emit(); break; case '\'': this->in_word = true; this->quote_type = QuoteType::SINGLE; break; case '\"': this->in_word = true; this->quote_type = QuoteType::DOUBLE; break; case '\\': this->escape_next = true; break; default: isspace(c) ? this->EndWord() : this->Push(c); break; } break; } } auto lines = this->ready_lines; this->ready_lines.clear(); return lines; } void Tokeniser::Push(const char c) { assert(this->escape_next || !(this->quote_type == QuoteType::NONE && isspace(c))); this->in_word = true; this->current_word.push_back(c); this->escape_next = false; assert(!this->current_word.empty()); } void Tokeniser::EndWord() { // Don't add a word unless we're in one. if (!this->in_word) return; this->in_word = false; this->words.push_back(this->current_word); this->current_word.clear(); } void Tokeniser::Emit() { // Since we assume these, we don't need to set them later. assert(this->quote_type == QuoteType::NONE); assert(!this->escape_next); // We might still be in a word, in which case we treat the end of a // line as the end of the word too. this->EndWord(); this->ready_lines.push_back(this->words); this->words.clear(); // The state should now be clean and ready for another command. assert(this->quote_type == QuoteType::NONE); assert(!this->escape_next); assert(this->current_word.empty()); }
true
39d1c3314c39f49da17655008eac0a25250bc3ef
C++
antoinechalifour/Cpp_TP4
/main.cpp
UTF-8
2,922
3.3125
3
[]
no_license
#include <iostream> #include <stdio.h> #include "Chaine.h" #include "CTableGType.h" #include "DynamicTable.h" using namespace std; template <class T> void swapT(T&a, T&b){ T tmp; tmp=a; a=b; b=tmp; } ostream& operator<<(ostream& os, const Chaine& c){ os<<c.getString(); return os; } int main(){ // --------------- SWAP /* int i=5; int j=6; cout<<"i= "<<i<<" j= "<<j<<endl; swapT<int>(i,j); cout<<"i= "<<i<<" j= "<<j<<endl; double f=5.55, g=6.66; cout<<"f= "<<f<<" g= "<<g<<endl; swapT<double>(f,g); cout<<"f= "<<f<<" g= "<<g<<endl; Chaine s="chaine_1", t="chaine2"; cout<<"s= "<<s<<" t= "<<t<<endl; swapT<Chaine>(s,t); cout<<"s= "<<s<<" t= "<<t<<endl; */ //-------------- Table generique /* CTableGType<int, 15> table; int i, elmnt; table.pushElement(0); table.pushElement(1); table.pushElement(2); table.pushElement(3); cout<<"La table contient "<<table.getSize()<<" elements :"<<endl; for(i=0; i<table.getSize() ; i++) cout<<"table["<<i<<"] = "<<table[i]<<endl; table[2]=5; elmnt=table.popElement(); cout<<"La table contient "<<table.getSize()<<" elements :"<<endl; for(i=0; i<table.getSize() ; i++) cout<<"table["<<i<<"] = "<<table[i]<<endl; cout<<"elmnt : "<<elmnt<<endl; try{ elmnt=table[10]; } catch(int e){ cout<<e<<" - bad index exception"<<endl; } */ DynamicTable<int, 2> dt; DynamicTable<int, 2> dt2; int i=1, j=2, k=3, l=4, m=5; try{ cout<<"Remplissage de dt..."<<endl; dt.pushElement(i); dt.pushElement(j); dt.pushElement(k); dt.pushElement(l); dt.pushElement(m); cout<<"Affichage de dt..."<<endl; cout<<"dt > i ="<<dt[0]<<endl; cout<<"dt > j ="<<dt[1]<<endl; cout<<"dt > k ="<<dt[2]<<endl; cout<<"dt > l ="<<dt[3]<<endl; cout<<"dt > m ="<<dt[4]<<endl<<endl; cout<<"Remplissage de dt2 via = sur dt..."<<endl; dt2=dt; cout<<"Popage de dt2..."<<endl; cout<<"dt2 > m ="<<dt2.popElement()<<endl; cout<<"dt2 > l ="<<dt2.popElement()<<endl; cout<<"dt2 > k ="<<dt2.popElement()<<endl; cout<<"dt2 > j ="<<dt2.popElement()<<endl; cout<<"dt2 > i ="<<dt2.popElement()<<endl<<endl; cout<<"Creation de dt3 par recopie de dt..."<<endl; DynamicTable<int, 2> dt3=dt; cout<<"Affichage de dt..."<<endl; cout<<"dt > i ="<<dt[0]<<endl; cout<<"dt > j ="<<dt[1]<<endl; cout<<"dt > k ="<<dt[2]<<endl; cout<<"dt > l ="<<dt[3]<<endl; cout<<"dt > m ="<<dt[4]<<endl<<endl; cout<<"Affichage de dt3..."<<endl; cout<<"dt3 > i ="<<dt3[0]<<endl; cout<<"dt3 > j ="<<dt3[1]<<endl; cout<<"dt3 > k ="<<dt3[2]<<endl; cout<<"dt3 > l ="<<dt3[3]<<endl; cout<<"dt3 > m ="<<dt3[4]<<endl<<endl; } catch (int e){ cout<<"An exception occured. Code : "<<e; } }
true
8c810cf8c53dafb32fd92d2cbcb7a4773b5ffcf1
C++
lesroad/Linux_System_Programming
/进程/mmap2.cpp
UTF-8
609
2.75
3
[]
no_license
//有血缘关系匿名映射区 #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <sys/mman.h> #include <unistd.h> #include <cstring> #include <sys/wait.h> using namespace std; int main(int argc, char **argv) { int length = 4096; void *ptr = mmap(NULL, length, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANON, -1, 0); if(ptr == MAP_FAILED) { perror("mmap error"); exit(1); } pid_t pid = fork(); if(pid == 0) { strcpy((char *)ptr, "有血缘关系匿名映射区"); } else { sleep(0.1);//因为非阻塞 puts((char *)ptr); wait(NULL); } munmap(ptr, length); return 0; }
true
01ac9ecb9379073b8e828c382709c1d867f684bb
C++
jean-tu/GoogleTu
/searcheng.h
UTF-8
1,030
2.53125
3
[]
no_license
#ifndef SEARCHENG_H #define SEARCHENG_H #include <map> #include <vector> #include <string> #include "webpage.h" #include "myset.h" #include "pageparser.h" class SearchEng { public: SearchEng(); ~SearchEng(); void add_parse_from_index_file(std::string index_file, PageParser* parser); void add_parse_page(std::string filename, PageParser* parser); /**** Add other desired member functions here *****/ std::map<std::string, WebPage* > getPages() const; //to return allPages; const myset<WebPage*>& getWebPages(std::string); private: /**** Add other desired data members here *****/ NewParse newparser; //filename, Webpage associated with it //string = data1.txt //webpage* = an object webpage std::map<std::string, WebPage* > allPages; myset<WebPage*> webpointers; //hold webpage pointers, so i can iterate through later std::map<std::string, myset<WebPage*> > word_to_setWeb; myset<std::string> inserted; //stores the files that have already been searched }; #endif
true
3569058f16184eefd2d6a59eb25f3d288b0214b7
C++
yaoReadingCode/University-SVN
/2019/s2/pssd/week09practice/main.cpp
UTF-8
543
2.875
3
[]
no_license
#include "VeryInterestingMovie.hpp" #include <iostream> #include <string> #include <vector> #include <ctype.h> using namespace std; int main() { vector<string> test32; test32.push_back("YYYYYYN"); test32.push_back("YYYYNYY"); test32.push_back("NYYYNYY"); test32.push_back("NYYYYYN"); test32.push_back("YYYYYYN"); test32.push_back("NYYNYNY"); test32.push_back("YYYYYYY"); /* vector<int> test33; test33.push_back(2); test33.push_back(2);*/ VeryInterestingMovie test; cout << test.maximumPupils(test32) << endl; return 0; }
true
f8a3a5d3ae5d528bbccaace93c0fd399e9d9c953
C++
objective-audio/db
/db/additions/object/yas_db_object_utils.cpp
UTF-8
2,748
2.578125
3
[ "MIT" ]
permissive
// // yas_db_object_utils.cpp // #include "yas_db_object_utils.h" #include <cpp_utils/yas_stl_utils.h> #include "yas_db_entity.h" #include "yas_db_model.h" #include "yas_db_relation.h" using namespace yas; std::vector<std::optional<db::const_object_ptr>> db::get_const_relation_objects( db::const_object_ptr const &object, db::const_object_map_map_t const &objects, std::string const &rel_name) { auto const rel_ids = object->relation_ids(rel_name); std::string const &tgt_entity_name = object->entity().relations.at(rel_name).target; if (objects.count(tgt_entity_name) > 0) { auto const &entity_objects = objects.at(tgt_entity_name); return to_vector<std::optional<db::const_object_ptr>>( rel_ids, [&entity_objects, entity_name = object->entity_name()](db::object_id const &rel_id) { db::integer::type const &stable = rel_id.stable(); if (entity_objects.count(stable) > 0) { return std::make_optional(entity_objects.at(stable)); } return std::optional<db::const_object_ptr>(std::nullopt); }); } return {}; } std::optional<db::const_object_ptr> db::get_const_relation_object(db::const_object_ptr const &object, db::const_object_map_map_t const &objects, std::string const &rel_name, std::size_t const idx) { db::integer::type const &rel_id = object->relation_ids(rel_name).at(idx).stable(); std::string const &tgt_entity_name = object->entity().relations.at(rel_name).target; if (objects.count(tgt_entity_name) > 0) { auto const &entity_objects = objects.at(tgt_entity_name); if (entity_objects.count(rel_id) > 0) { return entity_objects.at(rel_id); } } return std::nullopt; } db::object_map_map_t yas::to_object_map_map(db::object_vector_map_t objects_vector) { db::object_map_map_t objects_map; for (auto &entity_pair : objects_vector) { std::string const &entity_name = entity_pair.first; auto entity_objects = to_object_map(std::move(entity_pair.second)); objects_map.emplace(entity_name, std::move(entity_objects)); } objects_vector.clear(); return objects_map; } db::object_map_t yas::to_object_map(db::object_vector_t vec) { db::object_map_t map; auto it = vec.begin(); auto end = vec.end(); while (it != end) { db::object_ptr const &obj = *it; db::integer::type obj_id = obj->object_id().stable(); map.emplace(std::move(obj_id), std::move(obj)); ++it; } vec.clear(); return map; }
true
f79bb720abbab372603ce05bdfb03ad912c06098
C++
Luis-Lamat/Coding_Challenges
/UVa/nlogonia.cpp
UTF-8
916
3.359375
3
[]
no_license
/* * UVa problem: 11498 - Division of Nlogonia */ #include <iostream> #include <string> using namespace std; int main () { // initial user inputs int queries, centerX, centerY, X, Y; cin >> queries >> centerX >> centerY; do { // query while loop while (queries--){ // house coordinates input cin >> X >> Y; // resetting the string string position = ""; // check house coordinates relative to the // center point of the division if (X == centerX || Y == centerY) // if house is in border position = "divisa"; else { // else house is in other quadrant position += (Y < centerY) ? "S" : "N"; position += (X < centerX) ? "O" : "E"; } cout << position << endl; } cin >> queries; if (!queries) return 0; cin >> centerX >> centerY; } while (queries); return 0; }
true
322a4808999813b5580afb65a8fdd969412dd5a3
C++
sohardforaname/ACM_ICPC_practice
/POJ/3393.cpp
GB18030
1,953
2.5625
3
[]
no_license
#include <iostream> using namespace std; int num[10010][15][2]; const int ping[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; const int run[12] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int getnum(int y, int m) { if ((y < 1582 && y % 4 == 0) || y == 1700) return run[m - 1]; else if (y >= 1582 && ((y % 4 == 0 && y % 100) || y % 400 == 0)) return run[m - 1]; else return ping[m - 1]; } void init() { num[0][12][0] = 0, num[0][12][1] = 0; int x, s = 5; for (int i = 1; i < 10005; ++i) { for (int j = 1; j <= 12; ++j) { x = getnum(i, j); //cout << i << j << s << endl; for (int k = 1; k <= x; ++k) { if (k == 1) { if (s == 5 || s == 6 || s == 0) //һ { if (j != 1) num[i][j][0] = num[i][j - 1][0] + 1; else num[i][j][0] = num[i - 1][12][0] + 1; } else { if (j != 1) num[i][j][0] = num[i][j - 1][0]; else num[i][j][0] = num[i - 1][12][0]; } } else if (k == x) { if (s == 4 || s == 5 || s == 6) // { if (j != 1) num[i][j][1] = num[i][j - 1][1] + 1; else num[i][j][1] = num[i - 1][12][1] + 1; } else { if (j != 1) num[i][j][1] = num[i][j - 1][1]; else num[i][j][1] = num[i - 1][12][1]; } } if (i != 1752 || j != 9 || (k > 13 || k < 3)) { ++s; if (s == 7) s = 0; } } //cout << i << j << s << endl; } } } int main() { ios::sync_with_stdio(0); cin.tie(0); init(); int n, a, b, c, d; cin >> n; while (n--) { cin >> a >> b >> c >> d; if (b != 1) cout << num[c][d][1] - num[a][b - 1][1] << " " << num[c][d][0] - num[a][b - 1][0] << endl; else cout << num[c][d][1] - num[a - 1][12][1] << " " << num[c][d][0] - num[a - 1][12][0] << endl; } return 0; }
true
a6938563fb82c1974e08d7b320c7ef5b4a6ddb00
C++
ut0s/atcoder
/ABC/ABC125/c.cpp
UTF-8
1,772
3.25
3
[]
no_license
/** @date Time-stamp: <2019-04-29 08:35:45 tagashira> @file c.cpp @url https://atcoder.jp/contests/abc125/tasks/abc125_c **/ #include <algorithm> #include <chrono> #include <cmath> #include <iomanip> #include <iostream> #include <string> #include <vector> using namespace std; uint gcd(uint a, uint b) { if (b == 0) { return a; } return gcd(b, a % b); } uint multi_gcd(vector<uint> a) { if (a.size() == 2) { return gcd(a[0], a[1]); } else { vector<uint> tmp(a.begin() + 1, a.end()); return gcd(a[0], multi_gcd(tmp)); } } int main(int argc, char* argv[]) { uint N; cin >> N; vector<uint> A(0, N); uint tmpA; uint i; for (i = 0; i < N; i++) { cin >> tmpA; A.push_back(tmpA); } // gcd test // cout << gcd(1071, 1029) << "\n"; //21 // mluti gcd test // chrono::system_clock::time_point start, end; // cout << multi_gcd({4, 6, 8}) << "\n"; //2 // start = chrono::system_clock::now(); // for (i = 0; i < 100; i++) { // multi_gcd({4, 6, 8}); // } // end = chrono::system_clock::now(); // double time = static_cast<double>(chrono::duration_cast<chrono::microseconds>(end - start).count() / 1000.0); // printf("gcd time %lf[ms]\n", time / 100); // 累積 GCD (左と右両方) vector<uint> left(N + 1, 0), right(N + 1, 0); for (i = 0; i < N; ++i) { left[i + 1] = gcd(A[i], left[i]); } for (i = N - 1; i > 0; --i) { //right は集計の際にi+1から始まるからidxの0は不必要 right[i] = gcd(A[i], right[i + 1]); } // 集計 vector<uint> M; for (i = 0; i < N; ++i) { // 左側 uint l = left[i]; // 右側 uint r = right[i + 1]; M.push_back(gcd(l, r)); } cout << *max_element(M.begin(), M.end()) << endl; return 0; }
true
3a9b3f55e57a79d1254896bbc15112e0f1d5afac
C++
vindarten/game_server
/include/Parser.h
UTF-8
2,444
2.640625
3
[]
no_license
#ifndef PARSER_H #define PARSER_H #include "Ipn.h" #include "StackOperations.h" #include "automat.h" class ParsExc { public: ParsExc() {} virtual ~ParsExc() {} virtual void PrintError() const = 0; }; class ParsExcLParen: public ParsExc { char *str; public: ParsExcLParen(const char *s) { str = MyStrdup(s); } virtual ~ParsExcLParen() { delete [] str; } virtual void PrintError() const { printf("\"(\" expected after \"%s\" ", str); } }; class ParsExcComma: public ParsExc { char *str; public: ParsExcComma(const char *s) { str = MyStrdup(s); } virtual ~ParsExcComma() { delete [] str; } virtual void PrintError() const { printf("\",\" expected after the first argument of \"%s\" ", str); } }; class ParsExcRParen: public ParsExc { char *str; public: ParsExcRParen(const char *s) { str = MyStrdup(s); } virtual ~ParsExcRParen() { delete [] str; } virtual void PrintError() const { printf("\")\" expected after the arguments of \"%s\" ", str); } }; class Parser { Automat automat; Ipn *ipn; Lexeme *current, *last; int LexNum, LineNum, EndSec; FILE *f; void next(); void S(); void Action(); void IntDesc(); void RealDesc(); void StringDesc(); void WhileDesc(); void PutDesc(); void IfElseDesc(); void ProdDesc(); void SellDesc(); void BuyDesc(); void PrintMyInfoDesc(); void PrintMarketInfoDesc(); void PrintPlayerInfoDesc(); void PlayerProdDesc(); void PlayerRawDesc(); void PlayerMoneyDesc(); void PlayerFactDesc(); void PlayerAfactDesc(); void PlayerActiveDesc(); void PlayerDifBoughtDesc(); void PlayerDifSoldDesc(); void PlayerLastBoughtDesc(); void PlayerLastSoldDesc(); void PlayerLastDifBoughtDesc(); void PlayerLastDifSoldDesc(); void ArrayDesc(int DefVal, int RFst, int RScd, int ValFst, int ValScd); void Expression(IntStack *stack, int RParenErr, int ValOrIdentErr); void ExpOr(IntStack *stack, int RParenErr, int ValOrIdentErr); void ExpAnd(IntStack *stack, int RParenErr, int ValOrIdentErr); void ExpComp(IntStack *stack, int RParenErr, int ValOrIdentErr); void ExpAddSub(IntStack *stack, int RParenErr, int ValOrIdentErr); void ExpMulDiv(IntStack *stack, int RParenErr, int ValOrIdentErr); void ExpLast(IntStack *stack, int RParenErr, int ValOrIdentErr); int CheckComp(int n); int CheckInExp(int ErrNum); int CheckExp(); public: Parser() : automat(), current(0), last(0), LexNum(0), EndSec(0), f(0) { ipn = new Ipn; } Ipn *analyze(FILE *file); }; #endif
true
f043e7315e63c3f93aea675b70cc784a5f2367e8
C++
MichaelAPatel/NNSB_Pipe_Analysis
/utilities/ArrayUtilities.cpp
UTF-8
2,110
3.0625
3
[]
no_license
//============================================================================ // Name : ArrayUtilities.cpp // Author : Michael Patel, Jeffrey McKaig, Gracen Dickens, // Chase Ziegler, and Jessica Masterson // Version : 0.1.0 // Description : //============================================================================ #include "../user_includes/ArrayUtilities.h" #include <vector> #include <string> #include <iostream> void printMatrix(std::vector<std::vector<double>> & matrix) { for(unsigned int i = 0; i < matrix.size(); i++) { for(unsigned int j = 0; j < matrix[i].size(); j++) { std::cout << matrix[i][j] << " "; } std::cout << std::endl; } } float det(std::vector<std::vector<double>> & matrix, int index) { float determinant = 0; int sign = 1; if (index == 1) return matrix[0][0]; std::vector<std::vector<double>> coFactors; coFactors.resize(matrix.size(), std::vector<double>(matrix.size(), 0)); for (int i = 0; i < index; i++) { if(matrix[0][i] == 0.0) { sign = -sign; continue; } else { getCofactor(matrix, coFactors, 0, i, index); determinant += sign * matrix[0][i] * det(coFactors, index - 1); sign = -sign; } } return determinant; } void getCofactor(std::vector<std::vector<double>> & matrix, std::vector<std::vector<double>> & coFactors, int p, int q, int n) { int i = 0, j = 0; for (int row = 0; row < n; row++) { for (int col = 0; col < n; col++) { if (row != p && col != q) { coFactors[i][j++] = matrix[row][col]; if (j == n - 1) { j = 0; i++; } } } } } float getCurrent(std::vector<std::vector<double>> & matrix, std::vector<double> & array, float detA, int n) { std::vector<std::vector<double>> tempMatrix; tempMatrix.resize(matrix.size(), std::vector<double>(matrix.size(), 0)); for(unsigned int i = 0; i < matrix.size(); i++) { for(unsigned int j = 0; j < matrix[i].size(); j++) { tempMatrix[i][j] = matrix[i][j]; } } for(unsigned int i = 0; i < array.size(); i++) { tempMatrix[i][n] = array[i]; } float detAn = det(tempMatrix, matrix.size()); float current = detAn / detA; return current; }
true
2ee919609d714789ad35bd3be15ad5ec6603eebb
C++
Snektron/Anaconda
/src/ast/expr/variablenode.h
UTF-8
634
2.53125
3
[]
no_license
#ifndef SRC_AST_EXPR_VARIABLENODE_H_ #define SRC_AST_EXPR_VARIABLENODE_H_ #include <string> #include "ast/expr/expressionnode.h" class VariableNode : public ExpressionNode { private: std::string variable; DataTypeBase* datatype; public: VariableNode(const std::string&); virtual ~VariableNode(); virtual void print(std::ostream&, size_t) const; virtual void generate(BrainfuckWriter&); virtual void checkTypes(BrainfuckWriter&); virtual DataTypeBase* getType(); virtual void declareLocals(BrainfuckWriter&); std::string getName(); }; #endif
true
d4359edacfe7c933377d8abc99d6dcfc09c1099f
C++
MSTSIGGame/Megaminer-6
/client/c/game.cpp
UTF-8
23,035
2.59375
3
[]
no_license
//Copyright (C) 2009 - Missouri S&T ACM AI Team //Please do not modify this file while building your AI //See AI.h & AI.cpp for that #pragma warning(disable : 4996) #include <string> #include <cstring> #include <cstdlib> #include <iostream> #include <sstream> #include <fstream> #include <vector> #include <algorithm> #include "game.h" #include "network.h" #include "structures.h" #include "sexp/sfcompat.h" #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #ifdef _WIN32 //Doh, namespace collision. namespace Windows { #include <Windows.h> }; #else #include <unistd.h> #endif #ifndef THREADLESS #define LOCK(X) pthread_mutex_lock(X) #define UNLOCK(X) pthread_mutex_unlock(X) #else #define LOCK(X) #define UNLOCK(X) #endif using namespace std; DLLEXPORT Connection* createConnection() { Connection* c = new Connection; c->socket = -1; #ifndef THREADLESS pthread_mutex_init(&c->mutex, NULL); #endif c->turnNumber = 0; c->playerID = 0; c->boardX = 0; c->boardY = 0; c->gameNumber = 0; c->player0Time = 0; c->player1Time = 0; c->player0Name = 0; c->player1Name = 0; c->Bots = NULL; c->BotCount = 0; c->Frames = NULL; c->FrameCount = 0; c->Walls = NULL; c->WallCount = 0; c->Types = NULL; c->TypeCount = 0; return c; } DLLEXPORT int serverConnect(Connection* c, const char* host, const char* port) { c->socket = open_server_connection(host, port); return c->socket + 1; //false if socket == -1 } DLLEXPORT int serverLogin(Connection* c, const char* username, const char* password) { string expr = "(login \""; expr += username; expr += "\" \""; expr += password; expr +="\")"; send_string(c->socket, expr.c_str()); sexp_t* expression, *message; char* reply = rec_string(c->socket); expression = extract_sexpr(reply); delete[] reply; message = expression->list; if(message->val == NULL || strcmp(message->val, "login-accepted") != 0) { cerr << "Unable to login to server" << endl; destroy_sexp(expression); return 0; } destroy_sexp(expression); return 1; } DLLEXPORT int createGame(Connection* c) { sexp_t* expression, *number; send_string(c->socket, "(create-game)"); char* reply = rec_string(c->socket); expression = extract_sexpr(reply); delete[] reply; number = expression->list->next; c->gameNumber = atoi(number->val); destroy_sexp(expression); std::cout << "Creating game " << c->gameNumber << endl; c->playerID = 0; return c->gameNumber; } DLLEXPORT int joinGame(Connection* c, int gameNum) { sexp_t* expression; stringstream expr; c->gameNumber = gameNum; expr << "(join-game " << c->gameNumber << ")"; send_string(c->socket, expr.str().c_str()); char* reply = rec_string(c->socket); expression = extract_sexpr(reply); delete[] reply; if(strcmp(expression->list->val, "join-accepted") != 0) { cerr << "Game " << c->gameNumber << " doesn't exist." << endl; destroy_sexp(expression); return 0; } destroy_sexp(expression); c->playerID = 1; send_string(c->socket, "(game-start)"); return 1; } DLLEXPORT void endTurn(Connection* c) { LOCK( &c->mutex ); send_string(c->socket, "(end-turn)"); UNLOCK( &c->mutex ); } DLLEXPORT void getStatus(Connection* c) { LOCK( &c->mutex ); send_string(c->socket, "(game-status)"); UNLOCK( &c->mutex ); } static int distance(_Bot* bot, _Wall* target) { int x = 0, y = 0; if(target->x < bot->x) x = bot->x - target->x; else if(target->x > (x + bot->size-1)) x = target->x - (bot->x + bot->size-1); if(target->y < bot->y) y = bot->y - target->y; else if(target->y > (bot->y + bot->size-1)) y = target->y - (bot->y + bot->size-1); return x + y; } static int distance(_Bot* bot, _Bot* target) { int x = 0, y = 0; if(bot->x > target->x + target->size-1) x = bot->x - (target->x + target->size-1); else if(target->x > bot->x + bot->size-1) x = target->x - (bot->x + bot->size-1); if(bot->y > target->y + target->size-1) y = bot->y - (target->y + target->size-1); else if(target->y > bot->y + bot->size-1) y = target->y - (bot->y + bot->size-1); return x + y; } static int distance(_Bot* bot, _Frame* target) { int x = 0, y = 0; if(bot->x > target->x + target->size-1) x = bot->x - (target->x + target->size-1); else if(target->x > bot->x + bot->size-1) x = target->x - (bot->x + bot->size-1); if(bot->y > target->y + target->size-1) y = bot->y - (target->y + target->size-1); else if(target->y > bot->y + bot->size-1) y = target->y - (bot->y + bot->size-1); return x + y; } DLLEXPORT int unitTalk(_Unit* object, const char* message) { stringstream expr; expr << "(game-talk " << object->id << " \"" << escape_string(message) << "\"" << ")"; LOCK( &object->_c->mutex); send_string(object->_c->socket, expr.str().c_str()); UNLOCK( &object->_c->mutex); return 1; } DLLEXPORT int botTalk(_Bot* object, const char* message) { stringstream expr; expr << "(game-talk " << object->id << " \"" << escape_string(message) << "\"" << ")"; LOCK( &object->_c->mutex); send_string(object->_c->socket, expr.str().c_str()); UNLOCK( &object->_c->mutex); return 1; } DLLEXPORT int botMove(_Bot* object, const char* direction) { stringstream expr; if(object->steps < 1) return 0; int x = 0, y = 0; if(direction[0] == 'u' || direction[0] == 'U') y = -1; if(direction[0] == 'd' || direction[0] == 'D') y = 1; if(direction[0] == 'l' || direction[0] == 'L') x = -1; if(direction[0] == 'r' || direction[0] == 'R') x = 1; if(object->x + x < 0 || object->x + x >= object->_c->boardX || object->y + y < 0 || object->y + y >= object->_c->boardY) return 0; expr << "(game-move " << object->id << " \"" << escape_string(direction) << "\"" << ")"; LOCK( &object->_c->mutex); send_string(object->_c->socket, expr.str().c_str()); UNLOCK( &object->_c->mutex); object->steps--; //GAH! vector<_Unit*> victims; _Wall* walls = object->_c->Walls; _Bot* bots = object->_c->Bots; _Frame* frames = object->_c->Frames; for(int i = 0; i < object->_c->WallCount; i++) { if(distance(object, walls+i) == 1 && walls[i].health > 0) { if(y == -1 && walls[i].y < object->y) victims.push_back((_Unit*) (walls+i)); else if(x == -1 && walls[i].x < object->x) victims.push_back((_Unit*) (walls+i)); else if(y == 1 && walls[i].y == object->y+object->size) victims.push_back((_Unit*) (walls+i)); else if(x == 1 && walls[i].x == object->x+object->size) victims.push_back((_Unit*) (walls+i)); } } for(int i = 0; i < object->_c->BotCount; i++) { if(distance(object, bots+i) == 1 && bots[i].health > 0) { if(y == -1 && bots[i].y+bots[i].size == object->y) victims.push_back((_Unit*) (bots+i)); else if(x == -1 && bots[i].x+bots[i].size == object->x) victims.push_back((_Unit*) (bots+i)); else if(y == 1 && bots[i].y == object->y+object->size) victims.push_back((_Unit*) (bots+i)); else if(x == 1 && bots[i].x == object->x+object->size) victims.push_back((_Unit*) (bots+i)); } } for(int i = 0; i < object->_c->FrameCount; i++) { if(distance(object, frames+i) == 1 && frames[i].health > 0) { if(y == -1 && frames[i].y+frames[i].size == object->y) victims.push_back((_Unit*) (frames+i)); else if(x == -1 && frames[i].x+frames[i].size == object->x) victims.push_back((_Unit*) (frames+i)); else if(y == 1 && frames[i].y == object->y+object->size) victims.push_back((_Unit*) (frames+i)); else if(x == 1 && frames[i].x == object->x+object->size) victims.push_back((_Unit*) (frames+i)); } } if(victims.size()) { int victimHealth = 0; for(int i = 0; i < victims.size(); i++) victimHealth += victims[i]->health; int damage = min(victimHealth, object->size*object->size) * 4; object->health -= damage; bool alive = false; for(int i = 0; i < victims.size(); i++) { damage = (victims[i]->health * object->size*object->size + victimHealth - 1) / victimHealth * 4; victims[i]->health -= damage; if(victims[i]->health > 0) alive = true; } if(alive) return 1; } object->x += x; object->y += y; return 1; } DLLEXPORT int botAttack(_Bot* object, _Unit* target) { if(object->actions < 1) return 0; object->actions--; target->health -= object->damage; stringstream expr; expr << "(game-attack " << object->id << " " << target->id << ")"; LOCK( &object->_c->mutex); send_string(object->_c->socket, expr.str().c_str()); UNLOCK( &object->_c->mutex); return 1; } DLLEXPORT int botHeal(_Bot* object, _Bot* target) { if(object->actions < 1) return 0; if(distance(object, target) > object->range+1) return 0; if(object->owner != target->owner) return 0; object->actions--; target->health += target->maxHealth * object->buildRate / (4 * target->size*target->size); if(target->health > target->maxHealth) target->health = target->maxHealth; stringstream expr; expr << "(game-heal " << object->id << " " << target->id << ")"; LOCK( &object->_c->mutex); send_string(object->_c->socket, expr.str().c_str()); UNLOCK( &object->_c->mutex); return 1; } DLLEXPORT int botBuild(_Bot* object, _Type* type, int x, int y, int size) { if(object->buildRate == 0) return 0; if(object->actions < 1) return 0; if(x < 0 or y < 0 or x+size > object->_c->boardX or y+size > object->_c->boardY) return 0; if(size > object->size) return 0; object->actions = 0; object->steps = 0; stringstream expr; expr << "(game-build " << object->id << " " << type->id << " " << x << " " << y << " " << size << ")"; LOCK( &object->_c->mutex); send_string(object->_c->socket, expr.str().c_str()); UNLOCK( &object->_c->mutex); return 1; } DLLEXPORT int botCombine(_Bot* object, _Bot* bot2, _Bot* bot3, _Bot* bot4) { if(object->size != bot2->size) return 0; if(bot2->size != bot3->size) return 0; if(bot3->size != bot4->size) return 0; int x = min( min(object->x, bot2->x), min(bot3->x, bot4->x) ); int y = min( min(object->y, bot2->y), min(bot3->y, bot4->y) ); if(!(object->x == x && object->y == y) && !(bot2->x == x && bot2->y == y)&& !(bot3->x == x && bot3->y == y) && !(bot4->x == x && bot4->y == y)) return 0; x += object->size; if(!(object->x == x && object->y == y) && !(bot2->x == x && bot2->y == y)&& !(bot3->x == x && bot3->y == y) && !(bot4->x == x && bot4->y == y)) return 0; y += object->size; if(!(object->x == x && object->y == y) && !(bot2->x == x && bot2->y == y)&& !(bot3->x == x && bot3->y == y) && !(bot4->x == x && bot4->y == y)) return 0; x -= object->size; if(!(object->x == x && object->y == y) && !(bot2->x == x && bot2->y == y)&& !(bot3->x == x && bot3->y == y) && !(bot4->x == x && bot4->y == y)) return 0; object->steps = 0; object->actions = 0; bot2->steps = 0; bot2->actions = 0; bot3->steps = 0; bot3->actions = 0; bot4->steps = 0; bot4->actions = 0; stringstream expr; expr << "(game-combine " << object->id << " " << bot2->id << " " << bot3->id << " " << bot4->id << ")"; LOCK( &object->_c->mutex); send_string(object->_c->socket, expr.str().c_str()); UNLOCK( &object->_c->mutex); return 1; } DLLEXPORT int botSplit(_Bot* object) { if(object->actions < 1) return 0; if(object->size < 2) return 0; object->health = 0; object->actions = 0; object->steps = 0; stringstream expr; expr << "(game-split " << object->id << ")"; LOCK( &object->_c->mutex); send_string(object->_c->socket, expr.str().c_str()); UNLOCK( &object->_c->mutex); return 1; } DLLEXPORT int botMaxActions(_Bot* object) { return object->actitude / (object->size * object->size); } DLLEXPORT int botMaxSteps(_Bot* object) { return object->movitude / (object->size * object->size); } DLLEXPORT int frameTalk(_Frame* object, const char* message) { stringstream expr; expr << "(game-talk " << object->id << " \"" << escape_string(message) << "\"" << ")"; LOCK( &object->_c->mutex); send_string(object->_c->socket, expr.str().c_str()); UNLOCK( &object->_c->mutex); return 1; } DLLEXPORT int wallTalk(_Wall* object, const char* message) { stringstream expr; expr << "(game-talk " << object->id << " \"" << escape_string(message) << "\"" << ")"; LOCK( &object->_c->mutex); send_string(object->_c->socket, expr.str().c_str()); UNLOCK( &object->_c->mutex); return 1; } //Utility functions for parsing data void parseMappable(Connection* c, _Mappable* object, sexp_t* expression) { sexp_t* sub; sub = expression->list; object->_c = c; object->id = atoi(sub->val); sub = sub->next; object->x = atoi(sub->val); sub = sub->next; object->y = atoi(sub->val); sub = sub->next; } void parseUnit(Connection* c, _Unit* object, sexp_t* expression) { sexp_t* sub; sub = expression->list; object->_c = c; object->id = atoi(sub->val); sub = sub->next; object->x = atoi(sub->val); sub = sub->next; object->y = atoi(sub->val); sub = sub->next; object->owner = atoi(sub->val); sub = sub->next; object->health = atoi(sub->val); sub = sub->next; object->maxHealth = atoi(sub->val); sub = sub->next; object->size = atoi(sub->val); sub = sub->next; } void parseBot(Connection* c, _Bot* object, sexp_t* expression) { sexp_t* sub; sub = expression->list; object->_c = c; object->id = atoi(sub->val); sub = sub->next; object->x = atoi(sub->val); sub = sub->next; object->y = atoi(sub->val); sub = sub->next; object->owner = atoi(sub->val); sub = sub->next; object->health = atoi(sub->val); sub = sub->next; object->maxHealth = atoi(sub->val); sub = sub->next; object->size = atoi(sub->val); sub = sub->next; object->actions = atoi(sub->val); sub = sub->next; object->steps = atoi(sub->val); sub = sub->next; object->damage = atoi(sub->val); sub = sub->next; object->range = atoi(sub->val); sub = sub->next; object->movitude = atoi(sub->val); sub = sub->next; object->actitude = atoi(sub->val); sub = sub->next; object->buildRate = atoi(sub->val); sub = sub->next; object->partOf = atoi(sub->val); sub = sub->next; object->building = atoi(sub->val); sub = sub->next; object->type = atoi(sub->val); sub = sub->next; } void parseFrame(Connection* c, _Frame* object, sexp_t* expression) { sexp_t* sub; sub = expression->list; object->_c = c; object->id = atoi(sub->val); sub = sub->next; object->x = atoi(sub->val); sub = sub->next; object->y = atoi(sub->val); sub = sub->next; object->owner = atoi(sub->val); sub = sub->next; object->health = atoi(sub->val); sub = sub->next; object->maxHealth = atoi(sub->val); sub = sub->next; object->size = atoi(sub->val); sub = sub->next; sub = sub->next; object->completionTime = atoi(sub->val); sub = sub->next; } void parseWall(Connection* c, _Wall* object, sexp_t* expression) { sexp_t* sub; sub = expression->list; object->_c = c; object->id = atoi(sub->val); sub = sub->next; object->x = atoi(sub->val); sub = sub->next; object->y = atoi(sub->val); sub = sub->next; object->owner = atoi(sub->val); sub = sub->next; object->health = atoi(sub->val); sub = sub->next; object->maxHealth = atoi(sub->val); sub = sub->next; object->size = atoi(sub->val); sub = sub->next; } void parseType(Connection* c, _Type* object, sexp_t* expression) { sexp_t* sub; sub = expression->list; object->_c = c; object->id = atoi(sub->val); sub = sub->next; object->name = new char[strlen(sub->val)+1]; strncpy(object->name, sub->val, strlen(sub->val)); object->name[strlen(sub->val)] = 0; sub = sub->next; object->maxHealth = atoi(sub->val); sub = sub->next; object->damage = atoi(sub->val); sub = sub->next; object->range = atoi(sub->val); sub = sub->next; object->movitude = atoi(sub->val); sub = sub->next; object->actitude = atoi(sub->val); sub = sub->next; object->buildRate = atoi(sub->val); sub = sub->next; } DLLEXPORT int networkLoop(Connection* c) { while(true) { sexp_t* base, *expression, *sub, *subsub; char* message = rec_string(c->socket); string text = message; base = extract_sexpr(message); delete[] message; expression = base->list; if(expression->val != NULL && strcmp(expression->val, "game-winner") == 0) { expression = expression->next->next->next; int winnerID = atoi(expression->val); if(winnerID == c->playerID) { cout << "You win!" << endl << expression->next->val << endl; } else { cout << "You lose. :(" << endl << expression->next->val << endl; } stringstream expr; expr << "(request-log " << c->gameNumber << ")"; send_string(c->socket, expr.str().c_str()); return 0; } else if(expression->val != NULL && strcmp(expression->val, "log") == 0) { ofstream out; stringstream filename; expression = expression->next; filename << expression->val; filename << ".gamelog"; expression = expression->next; out.open(filename.str().c_str()); if (out.good()) out.write(expression->val, strlen(expression->val)); else cerr << "Error : Could not create log." << endl; out.close(); return 0; } else if(expression->val != NULL && strcmp(expression->val, "game-accepted")==0) { char gameID[30]; expression = expression->next; strcpy(gameID, expression->val); cout << "Created game " << gameID << endl; } else if(expression->val != NULL && strcmp(expression->val, "ident")==0) { if(c->player0Name) delete[] c->player0Name; int length = strlen(expression->next->list->list->next->next->val)+1; c->player0Name = new char[length]; strcpy(c->player0Name, expression->next->list->list->next->next->val); c->player0Name[length-1] = 0; if(c->player1Name) delete[] c->player1Name; length = strlen(expression->next->list->next->list->next->next->val)+1; c->player1Name = new char[length]; strcpy(c->player1Name, expression->next->list->next->list->next->next->val); c->player1Name[length-1] = 0; } else if(expression->val != NULL && strstr(expression->val, "denied")) { cout << expression->val << endl; cout << expression->next->val << endl; } else if(expression->val != NULL && strcmp(expression->val, "status") == 0) { while(expression->next != NULL) { expression = expression->next; sub = expression->list; if(string(sub->val) == "game") { sub = sub->next; c->turnNumber = atoi(sub->val); sub = sub->next; c->playerID = atoi(sub->val); sub = sub->next; c->boardX = atoi(sub->val); sub = sub->next; c->boardY = atoi(sub->val); sub = sub->next; c->gameNumber = atoi(sub->val); sub = sub->next; c->player0Time = atoi(sub->val); sub = sub->next; c->player1Time = atoi(sub->val); sub = sub->next; } else if(string(sub->val) == "Bot") { if(c->Bots) { for(int i = 0; i < c->BotCount; i++) { } delete[] c->Bots; } c->BotCount = sexp_list_length(expression)-1; //-1 for the header c->Bots = new _Bot[c->BotCount]; for(int i = 0; i < c->BotCount; i++) { sub = sub->next; parseBot(c, c->Bots+i, sub); } } else if(string(sub->val) == "Frame") { if(c->Frames) { for(int i = 0; i < c->FrameCount; i++) { } delete[] c->Frames; } c->FrameCount = sexp_list_length(expression)-1; //-1 for the header c->Frames = new _Frame[c->FrameCount]; for(int i = 0; i < c->FrameCount; i++) { sub = sub->next; parseFrame(c, c->Frames+i, sub); } } else if(string(sub->val) == "Wall") { if(c->Walls) { for(int i = 0; i < c->WallCount; i++) { } delete[] c->Walls; } c->WallCount = sexp_list_length(expression)-1; //-1 for the header c->Walls = new _Wall[c->WallCount]; for(int i = 0; i < c->WallCount; i++) { sub = sub->next; parseWall(c, c->Walls+i, sub); } } else if(string(sub->val) == "Type") { if(c->Types) { for(int i = 0; i < c->TypeCount; i++) { delete[] c->Types[i].name; } delete[] c->Types; } c->TypeCount = sexp_list_length(expression)-1; //-1 for the header c->Types = new _Type[c->TypeCount]; for(int i = 0; i < c->TypeCount; i++) { sub = sub->next; parseType(c, c->Types+i, sub); } } } return 1; } else { #ifdef SHOW_WARNINGS cerr << "Unrecognized message: " << text << endl; #endif } } } DLLEXPORT _Bot* getBot(Connection* c, int num) { return c->Bots + num; } DLLEXPORT int getBotCount(Connection* c) { return c->BotCount; } DLLEXPORT _Frame* getFrame(Connection* c, int num) { return c->Frames + num; } DLLEXPORT int getFrameCount(Connection* c) { return c->FrameCount; } DLLEXPORT _Wall* getWall(Connection* c, int num) { return c->Walls + num; } DLLEXPORT int getWallCount(Connection* c) { return c->WallCount; } DLLEXPORT _Type* getType(Connection* c, int num) { return c->Types + num; } DLLEXPORT int getTypeCount(Connection* c) { return c->TypeCount; } DLLEXPORT int getTurnNumber(Connection* c) { return c->turnNumber; } DLLEXPORT int getPlayerID(Connection* c) { return c->playerID; } DLLEXPORT int getBoardX(Connection* c) { return c->boardX; } DLLEXPORT int getBoardY(Connection* c) { return c->boardY; } DLLEXPORT int getGameNumber(Connection* c) { return c->gameNumber; } DLLEXPORT int getPlayer0Time(Connection* c) { return c->player0Time; } DLLEXPORT int getPlayer1Time(Connection* c) { return c->player1Time; } DLLEXPORT char* getPlayer0Name(Connection* c) { return c->player0Name; } DLLEXPORT char* getPlayer1Name(Connection* c) { return c->player1Name; }
true
ce6378b5da1f4b46210e1bd65c104f7d4a5a497e
C++
1160208849wfl/cpp-primer5e
/src/concurrency/chapter6/stack/stack.cc
UTF-8
1,710
3.828125
4
[]
no_license
// // C++ concurrency in Action. // #include <exception> #include <memory> #include <mutex> #include <stack> #include <thread> #include <iostream> template <typename T> class thread_safe_stack { private: std::stack<T> data; mutable std::mutex m; public: thread_safe_stack() = default; // copy-ctor, important to held source lock across copy thread_safe_stack(const thread_safe_stack &other) { std::lock_guard<std::mutex> lock(other.m); data = other.data; } thread_safe_stack &operator=(const thread_safe_stack &) = delete; void push(T new_value) { std::lock_guard<std::mutex> lock(m); data.push(std::move(new_value)); } std::shared_ptr<T> pop() { std::lock_guard<std::mutex> lock(m); if (data.empty()) { return nullptr; } // if T support move-ctor std::shared_ptr<T> res = std::make_shared<T>(std::move(data.top())); data.pop(); return res; } bool pop(T &value) { std::lock_guard<std::mutex> lock(m); if (data.empty()) { return false; } // if T support move-assignment value = std::move(data.top); data.pop(); return true; } bool empty() const { std::lock_guard<std::mutex> lock(m); return data.empty(); } }; // cout is not thread safe, so output will interleaved template <typename T> void worker(thread_safe_stack<T> &stack) { int count = 0; while (stack.pop()) { count++; } } int main() { thread_safe_stack<int> stack; for (int i = 0; i < 1000; ++i) { stack.push(i); } std::thread t1(worker<int>, std::ref(stack)); std::thread t2(worker<int>, std::ref(stack)); std::thread t3(worker<int>, std::ref(stack)); t1.join(); t2.join(); t3.join(); }
true
b78f20223a0df8018ac418ab0cb9a58a2941bb9c
C++
WasifMTahir/CPP-Mini-Projects
/Airline Ticketing System/task2.cpp
UTF-8
9,986
2.96875
3
[]
no_license
#include<iostream> using namespace std; void login(string grid[][8], string roll[][8], string students[][2]); void logoff(string grid[][8], string roll[][8]); void reset(string grid[][8], string roll[][8], string students[][2], string request[][2]); void message(string grid[][8], string roll[][8], string students[][2], string request[][2]); void arrangement(string grid[][8]); void trace(string grid[][8], string roll[][8], string students[][2]); void viewreq(string grid[][8], string roll[][8], string students[][2], string request[][2]); void change(string grid[][8], string roll[][8], string students[][2], string request[][2]); int mode(int choice, string grid[][8], string roll[][8], string students[][2], string request[][2]); int main() { string grid[4][8]; string pass[4][8]; string roll[4][8]; string request[10][2]; for (int i=0;i<4;i++) { for (int j=0;j<8;j++) { grid[i][j]="*"; pass[i][j]="*"; roll[i][j]="*"; } } cout << "\t"; for (int q=0;q<8;q++) { cout << "Col[" << q+1 << "]\t"; } cout << "\n\n"; for (int p=0;p<4;p++) { cout << "Row[" << p+1 << "]\t"; for (int o=0;o<8;o++) { cout << grid[p][o] << "\t"; } cout << endl; } string students[10][2]; students[0][0]="19100001"; students[0][1]="abc123"; students[1][0]="19100002"; students[1][1]="abc456"; students[2][0]="19100003"; students[2][1]="abc789"; students[3][0]="19100004"; students[3][1]="def123"; students[4][0]="19100005"; students[4][1]="def456"; students[5][0]="19100006"; students[5][1]="def789"; students[6][0]="19100007"; students[6][1]="xyz123"; students[7][0]="19100008"; students[7][1]="xyz456"; students[8][0]="19100009"; students[8][1]="xyz789"; students[9][0]="19100010"; students[9][1]="xyz123"; for (int i=0;i<10;i++) { request[i][0]="*"; request[i][1]="*"; } int choice = 1; while (choice!=-1) { cout << "Press 1 to log in to a computer\nPress 2 to log off from a computer\n"; cout << "Press 3 to request for password reset\nPress 4 to view message from Helpdesk\n"; cout << "Press 5 to view Lab seating arrangement\nPress 6 to switch mode\nPress -1 to exit\n\nEnter your choice: "; cin >> choice; if (choice == -1) return 0; else if (choice == 1) login(grid,roll,students); else if (choice == 2) logoff(grid,roll); else if (choice == 3) reset(grid,roll,students,request); else if (choice == 4) message(grid,roll,students,request); else if (choice == 5) arrangement(grid); else if (choice == 6) mode(choice,grid,roll,students,request); else cout << "Please enter a valid input"; } return 0; } void login(string grid[][8], string roll[][8], string students[][2]) { int row,col,test=0,test1=0; string rol,pass; cout << "Enter your Roll number: "; cin >> rol; cout << "Enter your password: "; cin >> pass; cout << "Enter Row Number: "; cin >> row; cout << "Enter Column Number: "; cin >> col; for (int i=0; i<4; i++) { for (int j=0; j<8; j++) if (roll[i][j]==rol) { cout << "You can't login to multiple computers at the same time!\n"; break; } else test++; } if (test==32) { for (int i=0; i<10; i++) { if (students[i][0]==rol && students[i][1]==pass) { grid[row-1][col-1]="o"; roll[row-1][col-1]=rol; cout << "You have successfully logged into computer #" << (row-1)*8+col; break; } else test1++; } if (test1==10) { cout << "ERROR!! Incorrect Credentials!"; } cout << "\n\t"; for (int q=0;q<8;q++) { cout << "Col[" << q+1 << "]\t"; } cout << "\n\n"; for (int p=0;p<4;p++) { cout << "Row[" << p+1 << "]\t"; for (int o=0;o<8;o++) { cout << grid[p][o] << "\t"; } cout << endl; } } } void logoff(string grid[][8], string roll[][8]) { string roll2; int test=0; cout << "Please Enter your Roll No.: "; cin >> roll2; for (int i=0; i<4; i++) { for (int j=0;j<8;j++) { if (roll[i][j]==roll2) { grid[i][j]="*"; cout << "You have successfully been logged off"; } else test++; } } if (test==32) { cout << "You cant logoff unless you've logged in first"; } cout << "\n\n"; } void reset(string grid[][8], string roll[][8], string students[][2], string request[][2]) { string roll2; int test=0,test1=0; cout << "Please Enter your Roll No.: "; cin >> roll2; for (int i=0; i<4; i++) { for (int j=0;j<8;j++) { if (roll[i][j]==roll2) { cout << "You can't request a password change while logged in\n"; } else test++; } } if (test==32) { for (int i=0;i<10;i++) { if (students[i][0]==roll2 && request[i][0]=="o") { cout << "You already have a pending request!"; break; } else if (students[i][0]==roll2) { request[i][0]="o"; cout << "You have successfully requested a password reset\n"; } else test1++; } if (test1==10) cout << "ERROR!! Unregistered Roll Number!\n"; } } void message(string grid[][8], string roll[][8], string students[][2], string request[][2]) { string roll2; int test=0,test1=0; cout << "Please Enter your Roll No.: "; cin >> roll2; for (int i=0;i<10;i++) { if (students[i][0]==roll2 && request[i][1]=="o") { cout << "You have no new messages!\n"; break; } else if (students[i][0]==roll2) { request[i][1]="o"; cout << "Dear " << roll2 << ", Thank you for contacting IST Helpdesk.\n"; cout << "It is our top priority to resolve your issue in the most timely manner.\n"; } else test1++; } if (test==10) cout << "ERROR!! Unregistered Roll Number!\n"; } void arrangement(string grid[][8]) { for (int q=0;q<8;q++) { cout << "Col[" << q+1 << "]\t"; } cout << "\n\n"; for (int p=0;p<4;p++) { cout << "Row[" << p+1 << "]\t"; for (int o=0;o<8;o++) { cout << grid[p][o] << "\t"; } cout << endl; } } int mode(int choice, string grid[][8], string roll[][8], string students[][2], string request[][2]) { int choice1=1; while (choice1!=-1) { cout << "**********Admin Mode**********\n"; cout << "Press 1 to trace a student\nPress 2 to view password change requests\n"; cout << "Press 3 to change password for a student\nPress 4 to view Lab seating arrangement\n"; cout << "Press 5 to switch mode\nPress -1 to exit\n\nEnter your choice: "; cin >> choice1; if (choice1 == -1) return 0; else if (choice1 == 1) trace(grid,roll,students); else if (choice1 == 2) viewreq(grid,roll,students,request); else if (choice1 == 3) change(grid,roll,students,request); else if (choice1 == 4) arrangement(grid); else if (choice1 == 5) return choice; else cout << "Please enter a valid input"; } } void trace(string grid[][8], string roll[][8], string students[][2]) { string rol; int test=0; cout << "Enter Roll No. of student: "; cin >> rol; for (int i=0;i<4;i++) { for (int j=0;j<8;j++) { if (roll[i][j]==rol) { cout << "Student Roll No.: " << rol; cout << "\nComputer No. : " << i*8+j+1; cout << "\nRow No.: " << i+1; cout << "\nColumn No.: " << j+1 << endl; } else test++; } } if (test==32) cout << "There is no student with Roll no. " << rol << " logged in!\n"; } void viewreq(string grid[][8], string roll[][8], string students[][2], string request[][2]) { cout << "Following students have requested for password change:\n"; for (int i=0;i<10;i++) { if (request[i][0]=="o") { cout << students[i][0] << endl; } } } void change(string grid[][8], string roll[][8], string students[][2], string request[][2]) { string rol,pas; int val,test=0; cout << "Enter Roll No. of student: "; cin >> rol; for (int i=0;i<10;i++) { if (request[i][0]=="o" && students[i][0]==rol) { val=i; break; } else test++; } if (test==10) { cout << "Wrong Roll. No entered!"; return; } cout << "Enter new password: "; cin >> pas; students[val][1]=pas; cout << "Password Changed Successfully!!\n"; request[val][0]="*"; request[val][1]="Your password has been reset. Your new password is: " + pas + "\n"; }
true
63e0f827d4b33caefb8639cb24a3d2c75819ad32
C++
socc-io/algostudy
/codeforce/1365/c2.cpp
UTF-8
403
2.609375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; const double pi = 3.14159265358979323846264338327950288; void solve() { int n; scanf("%d", &n); n <<= 1; double t = pi/2 - pi/n; double k; k = sqrt(1/(cos(t)*cos(t)) - 3.0/4.0); printf("%lf\n", k); k = tan(t); printf("%lf\n", k); k = 1/cos(t); printf("%lf\n", k); } int main(void) { int t; scanf("%d", &t); while (t--) solve(); }
true
0d3d53142b1a7ab74cc011b56602f6701a06374b
C++
aaronwhitesell/Massasauga
/Massasauga/Engine/globals.h
UTF-8
1,014
2.921875
3
[]
no_license
#ifndef GLOBALS_H #define GLOBALS_H #include "keyboard.h" #include "FrameRateRegulator.h" #include "../Game/game.h" #include "SDL.h" // alw - 6/10/10 - Using the Singleton design pattern // Modern C++ Design: Generic Programming and Design Patterns Applied class Globals { public: static Globals* Instance(); int getQuit() const {return m_quit;} void setQuit(bool quit) {m_quit = quit;} SDL_Event& getEvent() {return m_event;} Keyboard& getKeyboard() {return m_keyboard;} Game& getGame() {return m_game;} FrameRateRegulator& GetFrameRateRegulator() {return m_frameRateRegulator;} private: Globals(); // available only to members and friends ~Globals(); // prevents others from deleting our single instance Globals(const Globals &); // disallow copy constructor Globals & operator=(const Globals &); // disallow assignment operator static Globals* pInstance_; bool m_quit; SDL_Event m_event; Keyboard m_keyboard; Game m_game; FrameRateRegulator m_frameRateRegulator; }; #endif
true
84ab6a35984814ecf604c05336abae2cc1b72daa
C++
changx03/pacman_homage
/source_file/pacman_ver041/mesh_utils.cpp
UTF-8
6,600
2.984375
3
[]
no_license
#include "mesh_utils.h" #include "render.h" namespace mesh_utils{ void PrintSceneInfro(const aiScene *mScene){ std::cout << "-------------PRINT SCENE INFORMATION-------------\n"; std::cout << "lights = " << mScene->mNumLights << std::endl; std::cout << "material = " << mScene->mNumMaterials << std::endl; std::cout << "texture = " << mScene->mNumTextures << std::endl; std::cout << "meshes = " << mScene->mNumMeshes << std::endl; /* print vertices */ for (size_t i = 0; i < mScene->mNumMeshes; i++){ size_t vertexBufferLength = mScene->mMeshes[i]->mNumVertices * 3; std::cout << "vertices[" << i << "] = " << vertexBufferLength << std::endl; } /* print materials */ // 1st material always has gray color. No use! for (size_t i = 0; i < mScene->mNumMaterials; i++){ aiString mName; aiColor4D mColor(0.0f, 0.0f, 0.0f, 0.0f); aiGetMaterialColor(mScene->mMaterials[i], AI_MATKEY_COLOR_DIFFUSE, &mColor); std::cout << "Index[" << i << "] R = " << mColor.r << " G = " << mColor.g << " B = " << mColor.b << std::endl; } std::cout << "-------------------------------------------------\n"; } void LoadMeshVertices(const aiScene *scene, size_t meshIdx, std::vector<GLfloat> &vertices){ // incorrect mesh index number or fail to load scene if (meshIdx >= scene->mNumMeshes){ std::cerr << "Error: Incorrect mesh index or invalid scene pointer. Exit" << std::endl; return; } // reserve memory vertices.clear(); const size_t vertexBufferLength = scene->mMeshes[meshIdx]->mNumVertices; vertices.reserve(vertexBufferLength * 3); // load data for (size_t i = 0; i < vertexBufferLength; i++){ const aiVector3D &tempVertex = scene->mMeshes[meshIdx]->mVertices[i]; GLfloat x = tempVertex.x; GLfloat y = tempVertex.y; GLfloat z = tempVertex.z; vertices.push_back(x); vertices.push_back(y); vertices.push_back(z); } } void LoadMeshTextureCoord(const aiScene *scene, size_t meshIdx, std::vector<GLfloat> &textureCoords){ if (meshIdx >= scene->mNumMeshes){ std::cerr << "Error: Incorrect mesh index or invalid scene pointer. Exit" << std::endl; return; } if (scene->mMeshes[meshIdx]->HasTextureCoords(0) == false){ std::cerr << "Error: The mesh[" << meshIdx << "] has no texture coords. Exit" << std::endl; return; } // reserve memory textureCoords.clear(); const size_t length = scene->mMeshes[meshIdx]->mNumVertices; textureCoords.reserve(length * 2); // for (size_t i = 0; i < length; i++){ const aiVector3D &tempTextureCoord = scene->mMeshes[meshIdx]->mTextureCoords[0][i]; //std::cout << tempTextureCoord.x << std::endl; //std::cout << tempTextureCoord.y << std::endl; //std::cout << tempTextureCoord.z << std::endl; // constant '0'? GLfloat u = tempTextureCoord.x; GLfloat v = tempTextureCoord.y; textureCoords.push_back(u); textureCoords.push_back(v); //getchar(); } } // Note: material index = mesh index - 1. materials[0].color always equals to 0.6 void LoadMaterialColor(const aiScene *scene, size_t meshIdx, glm::vec3 &color){ // incorrect material index number or fail to load scene if (meshIdx >= scene->mNumMeshes){ std::cerr << "Error: Incorrect material index or invalid scene pointer. Exit" << std::endl; exit(0); } size_t matIdx = scene->mMeshes[meshIdx]->mMaterialIndex; if (matIdx == 0){ // if material is empty, this color will return 0.6 (gray) std::cerr << "Error: the input mesh has no associated material. Return BLACK color." << std::endl; color = glm::vec3(0.6f, 0.6f, 0.6f); return; } aiColor4D mColor(0.0f, 0.0f, 0.0f, 0.0f); aiGetMaterialColor(scene->mMaterials[matIdx], AI_MATKEY_COLOR_DIFFUSE, &mColor); color = glm::vec3(mColor.r, mColor.g, mColor.b); } void LoadMeshNormals(const aiScene *scene, size_t meshIdx, std::vector<GLfloat> &normals){ // incorrect mesh index number or fail to load scene if (meshIdx >= scene->mNumMeshes || scene->mMeshes[meshIdx]->mNormals == NULL){ std::cerr << "Error: Unable to load normals. Exit" << std::endl; return; } // reserve memory normals.clear(); const size_t normalBufferLength = scene->mMeshes[meshIdx]->mNumVertices; normals.reserve(normalBufferLength * 3); // load data for (size_t i = 0; i < normalBufferLength; i++){ aiVector3D tempNormal = scene->mMeshes[meshIdx]->mNormals[i]; normals.push_back(tempNormal.x); normals.push_back(tempNormal.y); normals.push_back(tempNormal.z); } } void LoadMeshIdx(const aiScene *scene, size_t meshIdx, std::vector<GLuint> &indices){ // check mesh if (meshIdx >= scene->mNumMeshes){ std::cerr << "Error: Incorrect material index or invalid scene pointer. Exit" << std::endl; return; } // check faces if (scene->mMeshes[meshIdx]->mFaces == NULL){ std::cerr << "Erroc: Cannot load faces in mesh " << meshIdx << ". Exit." << std::endl; return; } // clean previous data indices.clear(); // load indices for (size_t i = 0; i < scene->mMeshes[meshIdx]->mNumFaces; i++){ const aiFace &face = scene->mMeshes[meshIdx]->mFaces[i]; indices.insert(indices.end(), &face.mIndices[0], &face.mIndices[face.mNumIndices]); } } std::vector<Model> LoadModels(Shader shader, const aiScene *scene, bool isColor, bool isTexture){ std::vector<Model> modelsOut; // initialize buffer const size_t numMesh = scene->mNumMeshes; std::vector<GLfloat> verticesBuffer; std::vector<GLfloat> normalsBuffer; std::vector<GLfloat> textureBuffer; // no use in pacman std::vector<GLuint> indicesBuffer; glm::vec3 colorBuffer; for (size_t idx = 0; idx < numMesh; idx++){ LoadMeshVertices(scene, idx, verticesBuffer); LoadMeshNormals(scene, idx, normalsBuffer); LoadMeshIdx(scene, idx, indicesBuffer); if (isColor) LoadMaterialColor(scene, idx, colorBuffer); else colorBuffer = glm::vec3(0.6f, 0.6f, 0.6f); // no color, set color value to gray Model modelBuffer; if (isTexture == false){ render::LoadModelData(modelBuffer, verticesBuffer, normalsBuffer, indicesBuffer); } else{ modelBuffer = Model(3); LoadMeshTextureCoord(scene, idx, textureBuffer); render::LoadModelData(modelBuffer, verticesBuffer, normalsBuffer, indicesBuffer, textureBuffer); } modelBuffer.Set_shaderProgram(shader.GetProgram()); modelBuffer.Set_Color(colorBuffer); modelBuffer.Set_indicesSize(indicesBuffer.size()); verticesBuffer.clear(); normalsBuffer.clear(); textureBuffer.clear(); indicesBuffer.clear(); modelsOut.push_back(modelBuffer); } return modelsOut; } }
true
4d10535c717bc07ab6f9a67027ec38ee1a47d8ae
C++
jash-git/Jash-good-idea-20210419-001
/C++ Builder example/CBuilder6(BCB6)与Windows API经典范例/Ch3_Window Functions/ch03-49-2/Unit2.cpp
GB18030
2,419
2.5625
3
[]
no_license
//--------------------------------------------------------------------------- //ĿģɶʱʱĻλãѡȡӴ //--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "Unit2.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TForm1 *Form1; //--------------------------------------------------------------------------- __fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) {//Ĭ CheckBox1->Checked = false; CheckBox1->Caption = "ѹر껬ѡȡӴ"; CheckBox1->Width = 170; //㹻 Timer1->Interval = 100; //ʱƵ Timer1->Enabled = false; //ȹرնʱ } //--------------------------------------------------------------------------- //ڳʾʱ4Ӵ void __fastcall TForm1::FormShow(TObject *Sender) { for(int i=0;i<4;i++) { TForm *form = new TForm(this); form->Parent = Form1; form->FormStyle = fsMDIChild; form->Name = "form_" + AnsiString(i); form->Width = 120; form->Height = 60; form->Top = i*50; form->Left = i*30; form->Color = (TColor)RGB(255,i*50,255-i*50); } } //--------------------------------------------------------------------------- //ڳرʱر4Ӵ void __fastcall TForm1::FormClose(TObject *Sender, TCloseAction &Action) { for(int i=0; i<MDIChildCount; i++) MDIChildren[i]->Close(); } //--------------------------------------------------------------------------- //ƶʱأ޸״̬˵ַ void __fastcall TForm1::CheckBox1Click(TObject *Sender) { Timer1->Enabled = !Timer1->Enabled; if (Timer1->Enabled) CheckBox1->Caption ="껬ѡȡӴ"; else CheckBox1->Caption ="ѹر껬ѡȡӴ"; } //--------------------------------------------------------------------------- //ɶʱʱĻλãѡȡӴ void __fastcall TForm1::Timer1Timer(TObject *Sender) { POINT P; ::GetCursorPos(&P);//ȡĻλ //ȡλ´handle HWND HWindow = ::WindowFromPoint(P); //˴ if (HWindow) ::SetFocus(HWindow); } //---------------------------------------------------------------------------
true
166a1c8547b3ad82f30df29be3c9bb082e7989c6
C++
ZNika/kurs
/Model/lib/Search/search_tests.cpp
UTF-8
10,143
2.671875
3
[]
no_license
#include <gtest/gtest.h> #include <iostream> #include "include/GraphInterface/GraphInterface.h" #include <include/Graph/Graph.h> #include <GraphNode/GraphNode.h> #include <include/Search/Search.h> #include <GraphConnection/GraphConnection.h> // ConnectionParams using namespace Polaris; TEST( SearchTest, SimpleSearchHandle) { //************************************************************************* // o-o //************************************************************************* GraphInterface g; GraphNode n1{}, n2{}; ConnectionParams c; c.cost = 4; g.AddNode( n1 ); g.AddNode( n2 ); g.AddConnection( n1.GetId(), n2.GetId(), c ); auto res = Search::FindPath( g, n1.GetId(), n2.GetId() ); std::string res_str; for( auto & e: res) res_str += std::to_string( e.GetId() ) + " "; std::string correct = std::to_string( n1.GetId() ) + " " + std::to_string( n2.GetId() ) + " "; EXPECT_EQ( res_str, correct ); } TEST( SearchTest, LineSearchHandle) { //************************************************************************* // o-o-o-o-o-o-o-o-o-o //************************************************************************* GraphInterface g; std::vector< GraphNode > nodes; for( int i = 0; i < 10; i++ ) nodes.emplace_back( ); ConnectionParams c{}; c.cost = 4; for( int i = 0; i < 10; i++ ) g.AddNode( nodes[ i ] ); for( int i = 0; i < 9; i++ ) g.AddConnection( nodes[ i ].GetId(), nodes[ i + 1].GetId(), c ); auto res = Search::FindPath( g, nodes[ 0 ].GetId(), nodes[ nodes.size() - 1 ].GetId() ); std::string res_str, correct; for( auto & e: res) res_str += std::to_string( e.GetId() ) + " "; for( int i = 0; i < 10; i++ ) correct += std::to_string ( nodes[ i ].GetId() ) + " "; EXPECT_EQ( res_str, correct ); } TEST( SearchTest, NotLineSearchHandle) { //************************************************************************* // o-o-o-o-o-o-o-o-o-o // |___________| // all prices equal //************************************************************************* GraphInterface g; std::vector< GraphNode > nodes; for( int i = 0; i < 10; i++ ) nodes.emplace_back( ); ConnectionParams c{}; c.cost = 4; for( int i = 0; i < 10; i++ ) g.AddNode( nodes[ i ] ); g.AddConnection( nodes[ 0 ].GetId(), nodes[ 6 ].GetId() , c ); for( int i = 0; i < 9; i++ ) g.AddConnection( nodes[ i ].GetId(), nodes[ i + 1].GetId(), c ); auto res = Search::FindPath( g, nodes[ 0 ].GetId(), nodes[ nodes.size() - 1 ].GetId() ); std::string res_str, correct; for( auto & e: res) res_str += std::to_string( e.GetId() ) + " "; correct += std::to_string ( nodes[ 0 ].GetId() ) + " "; for( int i = 6; i < 10; i++ ) correct += std::to_string ( nodes[ i ].GetId() ) + " "; EXPECT_EQ( res_str, correct ); } TEST( SearchTest, NotLineSearchHandle2) { //************************************************************************* // o-o-o-o-o-o-o-o-o-o // |___________| // very hich price here //************************************************************************* GraphInterface g; std::vector< GraphNode > nodes; for( int i = 0; i < 10; i++ ) nodes.emplace_back( ); ConnectionParams c{}, c1{}; c.cost = 4; c1.cost = 100000; for( int i = 0; i < 10; i++ ) g.AddNode( nodes[ i ] ); g.AddConnection( nodes[ 0 ].GetId(), nodes[ 6 ].GetId() , c1 ); for( int i = 0; i < 9; i++ ) g.AddConnection( nodes[ i ].GetId(), nodes[ i + 1].GetId(), c ); auto res = Search::FindPath( g, nodes[ 0 ].GetId(), nodes[ nodes.size() - 1 ].GetId() ); std::string res_str, correct; for( auto & e: res) res_str += std::to_string( e.GetId() ) + " "; for( int i = 0; i < 10; i++ ) correct += std::to_string ( nodes[ i ].GetId() ) + " "; EXPECT_EQ( res_str, correct ); } TEST( SearchTest, NotLineSearchHandle3) { //************************************************************************* // o-o-o-o-o-o-O-o-o-o // | | // |_________o-o //************************************************************************* GraphInterface g; std::vector< GraphNode > nodes; for( int i = 0; i < 10; i++ ) nodes.emplace_back( ); ConnectionParams c{}, c1{}; c.cost = 4; c1.cost = 100000; for( int i = 0; i < 10; i++ ) g.AddNode( nodes[ i ] ); GraphNode n1{}, n2{}; g.AddNode( n1 ); g.AddNode( n2 ); g.AddConnection(nodes[ 0 ].GetId() , n1.GetId(), c ); g.AddConnection( n1.GetId(), n2.GetId(), c ); g.AddConnection( n2.GetId(), nodes[ 6 ].GetId(), c ); for( int i = 0; i < 9; i++ ) g.AddConnection( nodes[ i ].GetId(), nodes[ i + 1].GetId(), c ); auto res = Search::FindPath( g, nodes[ 0 ].GetId(), nodes[ 6 ].GetId() ); std::string res_str, correct; correct = std::to_string( nodes[0].GetId() ) + " " + std::to_string( n1.GetId() ) + " " + std::to_string( n2.GetId() ) + " " + std::to_string( nodes[6].GetId() ) + " "; for( auto & e: res) res_str += std::to_string( e.GetId() ) + " "; EXPECT_EQ( res_str, correct ); } TEST( SearchTest, NotLineSearchHandle4) { //************************************************************************* // o-o-O-o-o-o-o-o-o-o // | | // |_________o-o //************************************************************************* GraphInterface g; std::vector< GraphNode > nodes; for( int i = 0; i < 10; i++ ) nodes.emplace_back( ); ConnectionParams c{}, c1{}; c.cost = 4; c1.cost = 100000; for( int i = 0; i < 10; i++ ) g.AddNode( nodes[ i ] ); GraphNode n1{}, n2{}; g.AddNode( n1 ); g.AddNode( n2 ); g.AddConnection(nodes[ 0 ].GetId() , n1.GetId(), c ); g.AddConnection( n1.GetId(), n2.GetId(), c ); g.AddConnection( n2.GetId(), nodes[ 6 ].GetId(), c ); for( int i = 0; i < 9; i++ ) g.AddConnection( nodes[ i ].GetId(), nodes[ i + 1].GetId(), c ); auto res = Search::FindPath( g, nodes[ 0 ].GetId(), nodes[ 2 ].GetId() ); std::string res_str, correct; for( int i = 0; i < 3; i++ ) correct += std::to_string ( nodes[ i ].GetId() ) + " "; for( auto & e: res) res_str += std::to_string( e.GetId() ) + " "; EXPECT_EQ( res_str, correct ); } TEST( SearchTest, NotLineSearchHandle5) { //************************************************************************* // o-o-o-o-o-O-o-o-o-o // | | // |_________o-o //************************************************************************* GraphInterface g; std::vector< GraphNode > nodes; for( int i = 0; i < 10; i++ ) nodes.emplace_back( ); ConnectionParams c{}, c1{}; c.cost = 4; c1.cost = 100000; for( int i = 0; i < 10; i++ ) g.AddNode( nodes[ i ] ); GraphNode n1{}, n2{}; g.AddNode( n1 ); g.AddNode( n2 ); g.AddConnection(nodes[ 0 ].GetId() , n1.GetId(), c ); g.AddConnection( n1.GetId(), n2.GetId(), c ); g.AddConnection( n2.GetId(), nodes[ 6 ].GetId(), c ); for( int i = 0; i < 9; i++ ) g.AddConnection( nodes[ i ].GetId(), nodes[ i + 1].GetId(), c ); auto res = Search::FindPath( g, nodes[ 0 ].GetId(), nodes[ 5 ].GetId() ); std::string res_str, correct; for( auto & e: res) res_str += std::to_string( e.GetId() ) + " "; correct = std::to_string( nodes[0].GetId() ) + " " + std::to_string( n1.GetId() ) + " " + std::to_string( n2.GetId() ) + " " + std::to_string( nodes[6].GetId() ) + " " + std::to_string( nodes[5].GetId() ) + " "; EXPECT_EQ( res_str, correct ); } TEST( SearchTest, NoPathHandle ) { //************************************************************************* // o o //************************************************************************* GraphInterface g; GraphNode n1{}, n2{}; g.AddNode( n1 ); g.AddNode( n2 ); auto res = Search::FindPath( g, n1.GetId(), n2.GetId() ); std::string res_str, correct; for( auto & e: res) res_str += std::to_string( e.GetId() ) + " "; correct = ""; EXPECT_EQ( res_str, correct ); } TEST( SearchTest, NoPathHandle2 ) { //************************************************************************* // o-o o //************************************************************************* GraphInterface g; GraphNode n1{}, n2{}, n3{}; g.AddNode( n1 ); g.AddNode( n2 ); g.AddNode( n3 ); ConnectionParams c; c.cost = 4; g.AddConnection( n1, n2, c ); auto res = Search::FindPath( g, n1.GetId(), n3.GetId() ); std::string res_str, correct; for( auto & e: res) res_str += std::to_string( e.GetId() ) + " "; correct = ""; EXPECT_EQ( res_str, correct ); } TEST( SearchTest, SQPATH ) { //Test failed in demo. GraphInterface g; GraphNode n1{}, n2{}, n3{}, n4{}; g.AddNode( n1 ); g.AddNode( n2 ); g.AddNode( n3 ); g.AddNode( n4 ); ConnectionParams c12, c23, c13, c34; c12.cost = 4; c23.cost = 5; c13.cost = 4; c34.cost = 3; g.AddConnection( n1, n2, c12 ); g.AddConnection( n2, n3, c23 ); g.AddConnection( n1, n3, c13 ); g.AddConnection( n3, n4, c34 ); auto res = Search::FindPath( g, n1.GetId(), n4.GetId() ); std::string res_str, correct; for( auto & e: res) res_str += std::to_string( e.GetId() ) + " "; correct = std::to_string( n1.GetId() ) + " " + std::to_string( n3.GetId() ) + " " + std::to_string( n4.GetId() ) + " "; EXPECT_EQ( res_str, correct ); } int main(int argc, char **argv) { testing::InitGoogleTest(); return RUN_ALL_TESTS(); }
true
37bfae130d3ef002b75817a8fcb35e8a7ec837aa
C++
uiuc-cs126/NaiveBayesWorkshop
/interface/expression.h
UTF-8
2,354
3.359375
3
[]
no_license
#ifndef EXPRESSION_H #define EXPRESSION_H #include <iostream> #include "operation.h" //============== // How NOT to define constants // This method is C-style, and we should avoid it for a few reasons //============== /* #define PI 3.14 #define E 2.7 */ namespace math { //================== // Constants (The right way) //================== const char kSpecialCharacterDelim = '$'; const char kPiChar = 'p'; const char kEChar = 'e'; const double kPiVal = 3.14; const double kEVal = 2.72; const size_t kConstantStrLen = 2; class Expression { friend class ExpressionHasher; public: //=================== // Constructors //=================== Expression() = default; Expression(const std::string& input); double ComputeSolution() const; /** * Operator overload for == used in the hashing operation. */ bool operator==(const Expression& rhs) const; /** * Operator overload for << (ostream). Declared as friend to the Expression class * to access data members. */ friend std::ostream& operator<<(std::ostream& os, const Expression& expression); /** * Opeartor overload for >> (ostream). Declared as friend to the Expression class * to access data members. */ friend std::istream& operator>>(std::istream& is, Expression& expresson); private: //============== // Helping Functions //============== /** * Takes the raw input and checks for errors while also filling in the data members * for the operator and lhs and rhs numbers. */ void ParseRawInput(const std::string& input); /** * Takes a string containing only a number and checks for correctness and returns * the number contained in the string. It will also check to see if a constant was called. */ double ParseNumber(std::string num_str); //============== // Data members //============== double lhs_number_; double rhs_number_; Operation operator_; }; //================== // Hashing for Expression //================== struct ExpressionHasher { inline size_t operator()(const Expression& exp) const { return ((std::hash<double>()(exp.lhs_number_) ^ (std::hash<double>()(exp.rhs_number_) << 1)) >> 1) ^ (std::hash<int>()(exp.operator_) << 1); } }; } //namespace math #endif
true
448705f7b96e18767b098932a83a286218c79a36
C++
burnian/Online-Judge
/HangDian/HangDian/2014_09_1.h
WINDOWS-1252
405
2.671875
3
[]
no_license
//date: 2019/2/1 //author: burnian //des: #pragma once #include<iostream> using namespace std; #define N 10000 void Solution() { bool flag[N + 1] = { false }; int n, temp, sum = 0; cin >> n; for (int i = 0; i < n; i++) { cin >> temp; flag[temp] = true; if (temp - 1 >= 0 && flag[temp - 1]) sum++; if (temp + 1 <= N && flag[temp + 1]) sum++; } cout << sum << endl; }
true
5b51d7e111e08b863e0fc469b402a3866aac6aa8
C++
channyHuang/leetcodeOJ
/2075.cpp
UTF-8
698
2.828125
3
[]
no_license
class Solution { public: string decodeCiphertext(string encodedText, int rows) { int len = encodedText.length(); if (len == 0) return ""; string res; int cols = len / rows; for (int j = 0; j <= (cols - rows) + 1; ++j) { for (int i = 0; i < rows; ++i) { if (i + j >= cols) break; int idx = getindex(rows, cols, i, i + j); res += encodedText.substr(idx, 1); } } int pos = res.length() - 1; while (res[pos] == ' ') pos--; return res.substr(0, pos + 1); } int getindex(int rows, int cols, int i, int j) { return (i * cols + j); } };
true
faf7eeb8de581f811d86110d6295fb75fffb206a
C++
pombredanne/MI
/ankit/Templates/StackT.cpp
UTF-8
885
3.8125
4
[ "Unlicense" ]
permissive
#include<iostream> using namespace std; template<class T> class Stack { private: class Node { private: T data; Node *next; public: Node(T d):data(d){} Node *getNext(){return next;} void setNext(Node *temp){ next=temp;} T getData(){ return data;} }; Node *top; public: Stack<T>(); void push(T data); T pop(); }; template<class T> Stack<T>::Stack() { top = NULL; } template<class T> void Stack<T>::push(T d) { if(top ==NULL) { top = new Node(d); top->setNext(NULL); } else { Node *temp = new Node(d); temp->setNext(top); top=temp; } } template<class T> T Stack<T>::pop() { if(top == NULL) { cout<<"stack empty"; return NULL; } else { Node *temp=top; top=top->getNext(); T d = temp->getData(); delete temp; return d; } } int main(){ Stack<int> s; s.push(4); s.push(5); cout<<s.pop()<<s.pop(); return 0; }
true
f7416ff5e72fe06bf4c540c9ee9ce849b7a1246c
C++
mkbn-consultancy/modern_cpp
/type traits/6_enable_if_2.cpp
UTF-8
1,367
3.28125
3
[]
no_license
//-------- MKBN Training and Consultancy --------// //--------------- miri@mkbn.co.il ---------------// #include <iostream> #include <type_traits> #include <limits> //example from : https://stackoverflow.com/questions/25251380/stdnumeric-limits-as-a-condition template<typename T> void isInt(T t){} template<typename T> void isFloat(T t){} template<typename T> void isString(T t){} template < typename T > void foo( const T& param ) { if( std::numeric_limits< T >::is_integer) { isInt( param ); } else if( std::numeric_limits< T >::is_specialized ) { isFloat( param ); } else { isString( param ); } } //the more elegant way using enable_if to make the compiler choose the right //function instead of paying at runtime on the branch: template<typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0> void bar(const T& param) { isInt(param); } template<typename T, typename std::enable_if<std::is_floating_point<T>::value, int>::type = 0> void bar(const T& param) { isFloat(param); } template<typename T, typename std::enable_if<!std::is_integral<T>::value && !std::is_floating_point<T>::value, int>::type = 0> void bar(const T& param) { isString(param); } int main(){ int x = 5; foo(x); bar(x); }
true
ad6b9816b79fec0a0bde89c5cd461db646ec87eb
C++
TeodorKolev/c-tasks
/chetvurta_zadacha.cpp
UTF-8
1,380
3.671875
4
[]
no_license
#include <iostream> #include <math.h> using namespace std; double greaterThanZero(int point, int pointMinusOne, int pointPlusOne) { return (((pow(pointMinusOne, 2) ) - (point * 2) + (pow(pointPlusOne, 2))) / (pointMinusOne - pointPlusOne)); } double lessThanZero(int point, int pointMinusOne, int pointPlusOne) { return (((pow(pointMinusOne, 2) ) - (point * 2) + (pow(pointPlusOne, 2))) / (pointPlusOne - pointMinusOne)); } int main() { int size, point; while (true) { cout << "Enter number of points in vector A: "; cin >> size; if (size <= 50) break; else { cin.clear(); cout << "Invalid input! Number must be equal or less than 50 " << endl; } } double vectorB[size]; for (int i = 0; i < size; i++) { cout << "Enter point: "; cin >> point; int pointMinusOne = (point - 1); int pointPlusOne = (point + 1); if (point > 0) vectorB[i] = greaterThanZero(point, pointMinusOne, pointPlusOne); else if (point == 0) vectorB[i] = 0; else if (point < 0) vectorB[i] = lessThanZero(point, pointMinusOne, pointPlusOne); } cout << "Vector B points are: " << endl; for (int j = 0; j < size; j++) { cout << vectorB[j] << " "; } return 0; }
true
cfd86845ea5aad29efa7a6201ff37c9d56656fb9
C++
frankbozar/Competitive-Programming
/Solo Practice/UVa/AC/11103.cpp
UTF-8
620
2.546875
3
[]
no_license
#include<cstdio> #include<cstring> #include<string> using namespace std; string sol(const string& S) { string T, K, N, P; for(char c : S) { if( strchr("KACE", c) ) K+=c; else if( strchr("pqrst", c) ) P+=c; else N+=c; } if( P=="" ) return "no WFF possible"; T=P.back(); for(int i=P.size()-2, j=K.size()-1; j>=0 && i>=0; i--, j--) T=K[j]+T+P[i]; return N+T ; } int main() { for(char s[1<<10]; scanf("%s", s) && strcmp(s, "0"); printf("%s\n", sol(s).c_str())); } /* qKpNq KKN 0 */
true
281f5385f7efac0952b8eb2c4187c78257d19613
C++
NataliaD/SE2P
/Software/SE2P2/Thread.cpp
UTF-8
1,013
2.578125
3
[]
no_license
/* * Thread.cpp * * Created on: 02.10.2013 * Author: Jannik Schick (2063265) * Philipp Kloth (2081738) * Rutkay Kuepelikilinc (2081831) * Natalia Duske (2063265) */ #include "Thread.h" #include <iostream> #include <unistd.h> #include "HWaccess.h" #include "HAL.h" #include "Test.h" #include "Serial.h" using namespace std; namespace thread { //Default Konstruktor der Klasse Thread Thread::Thread() { // TODO Auto-generated constructor stub } // Default Destruktor Klasse Thread Thread::~Thread() { // TODO Auto-generated destructor stub } void Thread::shutdown() { //HAL* hal = HAL::getInstance(); Serial* serial = Serial::getInstance(); cout << "Shutting down..." << endl; //hal->engine_stop(); serial->close_serial(); } void Thread::execute(void *arg) { //HAL* hal = HAL::getInstance(); Serial* serial = Serial::getInstance(); serial->open_serial("/dev/ser1"); Test test; while(!isStopped()){ //test.componentTest(hal); test.serialTest(serial); sleep(2); } } }
true
5518be50b6f1075a0ccbbc74db0a61d8f70c9ef1
C++
ajimenezduque/MonteCarloEngine
/src/Option/Option.cpp
UTF-8
11,004
2.859375
3
[]
no_license
// // Created by alejandro on 17/06/19. // #include "Option.h" #include <cmath> #include <boost/math/distributions/exponential.hpp> #include <boost/math/distributions/normal.hpp> #include <iostream> #include <numeric> using namespace std; OptionBS::OptionBS (optionType tipo,double interesAnual, double strike, double spot, double sigma, double tau): tipo(tipo),interesAnual(interesAnual),strike(strike),spot(spot),sigma(sigma),tau(tau) { factorDescuento = exp(-interesAnual*tau); forward = spot/factorDescuento; } Call::Call(double interesAnual, double strike, double spot, double sigma, double tau): interesAnual(interesAnual),strike(strike),spot(spot),sigma(sigma),tau(tau), griegas(call,interesAnual,strike,spot,sigma,tau) { factorDescuento = exp(-interesAnual*tau); forward = spot/factorDescuento; } Greeks::Greeks(const Greeks &p) : tipo(call),interesAnual(interesAnual),strike(strike),spot(spot),sigma(sigma),tau(tau),factorDescuento(factorDescuento),forward(forward) {} Put::Put(double interesAnual, double strike, double spot, double sigma, double tau): interesAnual(interesAnual),strike(strike),spot(spot),sigma(sigma),tau(tau),griegas(put,interesAnual,strike,spot,sigma,tau) { factorDescuento = exp(-interesAnual*tau); forward = spot/factorDescuento; } Greeks::Greeks(optionType tipo,double interesAnual, double strike, double spot, double sigma, double tau): tipo(tipo),interesAnual(interesAnual),strike(strike),spot(spot),sigma(sigma),tau(tau) { factorDescuento = exp(-interesAnual*tau); forward = spot/factorDescuento; }; double Call::evaluate(vector<double> values){ double price{}; price = max(values.back() - strike,0.0); // cout<<"evaluate Call"<<endl; // cout<<price<<endl; return price; }; double Put::evaluate(vector<double> values){ double price{}; price = max(strike - values.back(),0.0); //cout<<"evaluate Put"<<endl; //cout<<price<<endl; return price; }; /*vector<double> Asian::valuesAsian(vector<double> values){ auto it = max_element(values.begin(),values.end()); vector<double> result; result.push_back(*it); return result; };*/ double Put::getExpiry(){ return this->tau; } double Call::getExpiry() { return this->tau; } double Asian::getExpiry(){ return innerOption->getExpiry(); } double Asian::evaluate(vector<double> values){ double v{}; vector<double> result; if(!values.empty()) { if (tipo == max_) { auto it = max_element(values.begin(), values.end()); result.push_back(*it); } else if (tipo == min_) { auto it = min_element(values.begin(), values.end()); result.push_back(*it); } else if (tipo == avg_) { v = accumulate(values.begin(), values.end(), 0.0) / values.size(); result.push_back(v); } else { cout << "ERROR" << endl; } }else{ cout << "VectorValues vacio" << endl; } v=innerOption->evaluate(result); //Decorator::evaluate(values); return v; }; double Greeks::delta(){ double delta{}; double dplus{}; double logFK = log(forward/strike); double inverseSigma = 1 / (sigma * sqrt(tau)); double medioSigma = 0.5 * sigma*sigma*tau; dplus = inverseSigma*(logFK + medioSigma); boost::math::normal normalDistribution; delta = boost::math::cdf(normalDistribution,dplus); switch (tipo){ case call: break; case put: delta = delta -1; break; default: cout<<"Error"<<endl; break; } return delta; } double Greeks::vega(){ double vega{}; double dplus{}; double logFK = log(forward/strike); double inverseSigma = 1 / (sigma * sqrt(tau)); double medioSigma = 0.5 * sigma*sigma*tau; dplus = inverseSigma*(logFK + medioSigma); double spotSqrTau = spot*sqrt(tau); double distribucionPrima = (1/(sqrt(2*M_PI)))*exp(-(dplus*dplus)/2); vega = spotSqrTau*distribucionPrima; return vega; } double Greeks::theta(){ double theta{}; double dplus{}; double dminus{}; double logFK = log(forward/strike); double inverseSigma = 1 / (sigma * sqrt(tau)); double medioSigma = 0.5 * sigma*sigma*tau; dplus = inverseSigma*(logFK + medioSigma); double distribucionPrima = (1/(sqrt(2*M_PI)))*exp(-(dplus*dplus)/2); dminus = inverseSigma*(logFK - medioSigma); boost::math::normal normalDistribution; double distribucionMinus{}; switch (tipo){ case call: distribucionMinus = boost::math::cdf(normalDistribution,dminus); //cout<<"Call Distribucion Minus: "<< distribucionMinus<<endl; //normalCDF(dminus); theta = -(spot*distribucionPrima*sigma)/(2*sqrt(tau)) - (interesAnual*strike*exp(-interesAnual*tau)*(distribucionMinus)); break; case put: distribucionMinus = boost::math::cdf(normalDistribution,-dminus); //cout<<" Put Distribucion Minus: "<< distribucionMinus<<endl; //normalCDF(-dminus); //CFD(-dminus); theta = -((spot*distribucionPrima*sigma)/(2*sqrt(tau))) + (interesAnual*strike*exp(-interesAnual*tau)*(distribucionMinus)); break; default: cout<<"Error"<<endl; theta = -11111111; break; } return theta; } double OptionBS::price(){ double dplus{}; double dminus{}; double sigma_sqr = sigma*sigma; double inverseSigma = 1 / (sigma * sqrt(tau)); double logFK = log(forward/strike); double medioSigma = 0.5 * sigma_sqr*tau; boost::math::normal normalDistribution; dplus = inverseSigma*(logFK + medioSigma); dminus = inverseSigma*(logFK - medioSigma); auto distribucionPlus = boost::math::cdf(normalDistribution,dplus); auto distribucionMinus = boost::math::cdf(normalDistribution,dminus); auto negDistribucionPlus = boost::math::cdf(normalDistribution,-dplus); auto negDistribucionMinus = boost::math::cdf(normalDistribution,-dminus); double result{}; switch (tipo){ case call: result = factorDescuento * ((distribucionPlus * forward) - (distribucionMinus * strike)); break; case put: result = factorDescuento * ((negDistribucionMinus * strike) - (negDistribucionPlus * forward)); break; default: cout<<"Error"<<endl; result = -11111111; break; } return result; } /*Option::Option(optionType tipo, double interesAnual, double strike, double spot, double sigma, double tau): tipo(tipo),interesAnual(interesAnual),strike(strike),spot(spot),sigma(sigma),tau(tau){ factorDescuento = exp(-interesAnual*tau); forward = spot/factorDescuento; } Option::Option(){} Asian::Asian(){} double normalCDF(double x){ cout<<"normalCDF: "<<erfc(-x / sqrt(2))*0.5<<endl; return erfc(-x / sqrt(2))*0.5;; } double CFD(double x){ const double root = sqrt(0.5); cout<<"CFD: "<< 0.5*(1.0 + erf(x*root))<<endl; return 0.5*(1.0 + erf(x*root)); } double Option::evaluate() { cout<<"Option"<<endl; return 55; } double Option::delta(){ double delta{}; double dplus{}; double logFK = log(forward/strike); double inverseSigma = 1 / (sigma * sqrt(tau)); double medioSigma = 0.5 * sigma*sigma*tau; dplus = inverseSigma*(logFK + medioSigma); boost::math::normal normalDistribution; delta = boost::math::cdf(normalDistribution,dplus); // normalCDF(dplus); //CFD(dplus); switch (tipo){ case call: break; case put: delta = delta -1; break; default: cout<<"Error"<<endl; break; } return delta; } double Option::vega(){ double vega{}; double dplus{}; double logFK = log(forward/strike); double inverseSigma = 1 / (sigma * sqrt(tau)); double medioSigma = 0.5 * sigma*sigma*tau; dplus = inverseSigma*(logFK + medioSigma); double spotSqrTau = spot*sqrt(tau); double distribucionPrima = (1/(sqrt(2*M_PI)))*exp(-(dplus*dplus)/2); vega = spotSqrTau*distribucionPrima; return vega; } double Option::theta(){ double theta{}; double dplus{}; double dminus{}; double logFK = log(forward/strike); double inverseSigma = 1 / (sigma * sqrt(tau)); double medioSigma = 0.5 * sigma*sigma*tau; dplus = inverseSigma*(logFK + medioSigma); double distribucionPrima = (1/(sqrt(2*M_PI)))*exp(-(dplus*dplus)/2); dminus = inverseSigma*(logFK - medioSigma); boost::math::normal normalDistribution; double distribucionMinus{}; switch (tipo){ case call: distribucionMinus = boost::math::cdf(normalDistribution,dminus); //cout<<"Call Distribucion Minus: "<< distribucionMinus<<endl; //normalCDF(dminus); theta = -(spot*distribucionPrima*sigma)/(2*sqrt(tau)) - (interesAnual*strike*exp(-interesAnual*tau)*(distribucionMinus)); break; case put: distribucionMinus = boost::math::cdf(normalDistribution,-dminus); //cout<<" Put Distribucion Minus: "<< distribucionMinus<<endl; //normalCDF(-dminus); //CFD(-dminus); theta = -((spot*distribucionPrima*sigma)/(2*sqrt(tau))) + (interesAnual*strike*exp(-interesAnual*tau)*(distribucionMinus)); break; default: cout<<"Error"<<endl; theta = -11111111; break; } return theta; } double Option::price(){ double dplus{}; double dminus{}; double sigma_sqr = sigma*sigma; double inverseSigma = 1 / (sigma * sqrt(tau)); double logFK = log(forward/strike); double medioSigma = 0.5 * sigma_sqr*tau; boost::math::normal normalDistribution; dplus = inverseSigma*(logFK + medioSigma); dminus = inverseSigma*(logFK - medioSigma); auto distribucionPlus = boost::math::cdf(normalDistribution,dplus); auto distribucionMinus = boost::math::cdf(normalDistribution,dminus); auto negDistribucionPlus = boost::math::cdf(normalDistribution,-dplus); auto negDistribucionMinus = boost::math::cdf(normalDistribution,-dminus); /*cout<<"factorDescuento"<< factorDescuento<<endl; cout<<"inverseSigma"<< inverseSigma<<endl; cout<<"logFK"<< logFK<<endl; cout<<"medioSigma"<< medioSigma<<endl; cout<<"dplus"<< dplus<<endl; cout<<"dminus"<< dminus<<endl; cout<<"distribucionPlus"<< distribucionPlus<<endl; cout<<"distribucionMinus"<< distribucionMinus<<endl; cout<<"negDistribucionPlus"<< negDistribucionPlus<<endl; cout<<"negDistribucionMinus"<< negDistribucionMinus<<endl; double result{}; switch (tipo){ case call: result = factorDescuento * ((distribucionPlus * forward) - (distribucionMinus * strike)); break; case put: result = factorDescuento * ((negDistribucionMinus * strike) - (negDistribucionPlus * forward)); break; default: cout<<"Error"<<endl; result = -11111111; break; } return result; } double Asian::evaluate() { cout<<"Asian"<<endl; return 5.0; } */
true
7d27f8817aa2777ebceceae4f3abd14a90c4c0a0
C++
Yapele/Fingerprint-scanner-for-exam-room
/yun_camera/yun_camera.ino
UTF-8
1,545
2.796875
3
[]
no_license
// Sketch to upload pictures to Dropbox when motion is detected #include <Bridge.h> #include <Process.h> int flag = 1; // Picture process Process picture; // Filename String filename; // Pin int accessgranted = 13; // Path String path = "/mnt/sda1/"; void setup() { Serial.begin(9600); pinMode(accessgranted,INPUT); // For debugging, wait until the serial console is connected delay(4000); while(!Serial); // Bridge Bridge.begin(); Serial.println("YUN ready"); } void loop(void) { // Set pin mode if (digitalRead(accessgranted) == HIGH) { flag=1; } if (flag == 1){ if (digitalRead(accessgranted) == LOW) { flag=0; Serial.println("Access granted take a picture"); // Generate filename with timestamp filename = ""; picture.runShellCommand("date +%s"); while(picture.running()); while (picture.available()>0) { char c = picture.read(); filename += c; //Serial.println(c); } filename.trim(); filename += ".jpg"; // Take picture picture.runShellCommand("fswebcam " + path + filename + " -S10"); while(picture.running()); Serial.print("Took a picture: "); Serial.println(path + filename); // Set pin mode pinMode(accessgranted,OUTPUT); digitalWrite(accessgranted,HIGH); //Tell UNO to open the gate (Servo) // Upload to Dropbox picture.runShellCommand("python " + path + "upload_picture_main.py " + path + filename); while(picture.running()); Serial.println("Uploaded to Dropbox"); } } }
true
dd8433571fafadf7d5012907e432d47ac9922606
C++
Anton94/OOP-Cplusplus
/SD semester projects mostly/Homework three/MyTestStruct.h
UTF-8
557
2.703125
3
[]
no_license
#pragma once #include <iostream> #include <vector> // My type for testing, it can be with very big data if it needs... for now it`s only int value for comparation and some load for bad swapping! struct MyTestStruct { friend std::ostream& operator<<(std::ostream& out, MyTestStruct & val); public: MyTestStruct& operator=(int val); bool operator==(const MyTestStruct& other); bool operator!=(const MyTestStruct& other); bool operator<(const MyTestStruct& other); bool operator>(const MyTestStruct& other); private: int data; long long load[42]; };
true
260f969f8a10bdfc989fca76dddc3f74c6567b61
C++
jstnhuang/rapid
/rapid_pr2/include/rapid_pr2/joint_states.h
UTF-8
736
2.703125
3
[ "BSD-3-Clause" ]
permissive
#ifndef _RAPID_PR2_JOINT_STATES_H_ #define _RAPID_PR2_JOINT_STATES_H_ #include <map> #include <string> namespace rapid { namespace pr2 { // JointStates holds default joint values for the PR2. // These can be replaced as needed, and passed to a RobotStatePublisher. // The default joint values are with the wheels facing forward, the robot // looking straight ahead, and with both arms outstretched. class JointStates { public: JointStates(); void Set(const std::map<std::string, double>& joint_positions); std::map<std::string, double> joint_positions() const; private: void Initialize(); std::map<std::string, double> joint_positions_; }; } // namespace pr2 } // namespace rapid #endif // _RAPID_PR2_JOINT_STATES_H_
true
7d6e51e1eaefcd72ac32a9fdc054cff75a4cc15e
C++
yuzhuowen/codingpractice
/poj/poj3006.cpp
UTF-8
619
2.96875
3
[]
no_license
#include<iostream> #include<cmath> using namespace std; bool isprime ( int k ) { if(k==2||k==1)return true; for ( int i = 2 ; i <= sqrt (k) ; i ++ ) { if ( k % i == 0 ) { return false ; } } return true ; } int main() { int a,d,n,j,i; while(1) { cin>>a>>d>>n; j=0; i=a; while(1) { if(isprime(i)==true) { ++j; } if(j==n) { break; } i+=d; } cout<<i<<endl; } return 0; }
true
95b09399f16c275f525497cf77db93ca7a49939c
C++
kokay/CodingPractice
/TopCoder/VolumeGuess.cc
UTF-8
1,008
3.25
3
[]
no_license
#include <iostream> #include <vector> #include <sstream> #include <algorithm> #include <set> using namespace std; class VolumeGuess { public: int correctVolume(vector<string> queries, int numBoxes, int ithBox) { string strIdx1, strIdx2, strVol; vector<set<int>> memo(numBoxes + 1); vector<int> volumes(numBoxes + 1, -1); for (int i = 0; i < queries.size(); ++i) { istringstream ss(queries[i]); getline(ss, strIdx1, ','); getline(ss, strIdx2, ','); getline(ss, strVol, ','); int idx1 = stoi(strIdx1); int idx2 = stoi(strIdx2); int vol = stoi(strVol); if (memo[idx1].find(vol) == memo[idx1].end()) memo[idx1].insert(vol); else volumes[idx1] = vol; if (memo[idx2].find(vol) == memo[idx2].end()) memo[idx2].insert(vol); else volumes[idx2] = vol; } return volumes[ithBox]; } }; //int main() { // VolumeGuess v; // cout << v.correctVolume( // { "1,02,10","2,3,010","1,3,20" } // ,3 // ,2) << endl; //} //
true
4e129f5cc0eb643d8b8a775756efeb97642b8948
C++
ji12345ba/CS225-UIUC
/mp7/tests/GraphTests.cpp
UTF-8
2,798
3.28125
3
[]
no_license
#include "../cs225/catch/catch.hpp" #include "../Graph.h" #include "../Edge.h" #include "../Vertex.h" Graph<Vertex, Edge> createTestGraph() { /* _ b /--------- h / | _/ | a -- c -- e f -- g \_ _/ d */ Graph<Vertex, Edge> g; g.insertVertex("a"); g.insertVertex("b"); g.insertVertex("c"); g.insertVertex("d"); g.insertVertex("e"); g.insertVertex("f"); g.insertVertex("g"); g.insertVertex("h"); // Edges on `a`: g.insertEdge("a", "b"); g.insertEdge("a", "c"); g.insertEdge("a", "d"); // Additional edges on `b`: g.insertEdge("b", "c"); // Additional edges on `c`: g.insertEdge("c", "e"); g.insertEdge("c", "h"); // Additional edges on `d`: g.insertEdge("d", "e"); // Additional edges on `e`: (none) // Additional edges on `f`: g.insertEdge("f", "g"); // Additional edges on `g`: g.insertEdge("g", "h"); // Additional edges on `h`: (none) return g; } TEST_CASE("Graph::size returns the vertex count", "[weight=1]") { Graph<Vertex, Edge> g; g.insertVertex("a"); g.insertVertex("b"); REQUIRE( g.size() == 2 ); g.insertVertex("c"); g.insertVertex("d"); g.insertVertex("e"); REQUIRE( g.size() == 5 ); } TEST_CASE("Graph::edges::size returns the edge count", "[weight=1]") { Graph<Vertex, Edge> g; g.insertVertex("a"); g.insertVertex("b"); g.insertVertex("c"); g.insertVertex("d"); g.insertVertex("e"); REQUIRE( g.edges() == 0 ); g.insertEdge("a", "c"); g.insertEdge("b", "d"); g.insertEdge("a", "e"); REQUIRE( g.edges() == 3 ); //modified g.removeEdge("a", "c"); REQUIRE(g.edges() == 2); g.removeVertex("d"); REQUIRE(g.size() == 4); } TEST_CASE("Eight-vertex test graph has correct properties", "[weight=1]") { Graph<Vertex, Edge> g = createTestGraph(); REQUIRE( g.size() == 8 ); REQUIRE( g.edges() == 9 ); } TEST_CASE("Graph::incidentEdges contains incident edges (origin-only test)", "[weight=1]") { Graph<Vertex, Edge> g = createTestGraph(); REQUIRE( g.incidentEdges("a").size() == 3 ); } TEST_CASE("Graph::incidentEdges contains incident edges (dest-only test)", "[weight=1]") { Graph<Vertex, Edge> g = createTestGraph(); REQUIRE( g.incidentEdges("h").size() == 2 ); } TEST_CASE("Graph::incidentEdges contains incident edges (hybrid test)", "[weight=1]") { Graph<Vertex, Edge> g = createTestGraph(); REQUIRE( g.incidentEdges("d").size() == 2 ); } TEST_CASE("Graph::isAdjacent is correct (same-order test)", "[weight=1]") { Graph<Vertex, Edge> g = createTestGraph(); REQUIRE( g.isAdjacent("a", "d") == true ); } TEST_CASE("Graph::isAdjacent is correct (opposite-order test)", "[weight=1]") { Graph<Vertex, Edge> g = createTestGraph(); REQUIRE( g.isAdjacent("a", "d") == true ); }
true
902b3651f440443a6d1cff281b856e6b43b0084e
C++
newparts/TAPOO
/Observer/main.cpp
UTF-8
2,920
3.453125
3
[ "MIT" ]
permissive
#include <iostream> #include <vector> using namespace std; class Subiect { vector < class Observator * > observatori; bool scor; // trigger, event public: // se inregistreaza singur void attach(Observator *obs) { observatori.push_back(obs); } // event // set daca se marcheaza si notifica pe fiecare void setScor(bool Scorx) { scor = Scorx; notify(); } bool getScor() { return scor; } // notifica implementarea void notify(); }; class Observator { Subiect *subj; int exciteLevel; // stare public: Observator(Subiect *mod, int excLevel) { subj = mod; exciteLevel = excLevel; // Observatorii se inregistreaza si se ataseaza la subiect subj->attach(this); } virtual void update() = 0; protected: Subiect *getSubiect() { return subj; } void setExciteLevel(int excLevel) { exciteLevel = excLevel; } int getExciteLevel() { return exciteLevel; } }; //notifica observatorii pentru update void Subiect::notify() { for (int i = 0; i < observatori.size(); i++) observatori[i]->update(); } class Old_ConcretObservator: public Observator { public: // Apeleaza constructorul parinte pentru a se inregistra la subiect Old_ConcretObservator(Subiect *mod, int div) :Observator(mod, div){} // Pentru old daca nivelul de excitatie creste peste intervine riscul void update() { bool scor = getSubiect()->getScor(); setExciteLevel(getExciteLevel() + 1); if (scor && getExciteLevel() > 150) { cout << "Echipa celor batrani a inscris!!" << " Nivelul de excitatie al lor este " << getExciteLevel() << " atentie la riscuri"<<endl; }else{ cout << "Echipa nu a marcat. Nu trebuie sa va faceti griji" << endl; } } // sgarsit update() }; class Young_ConcretObservator: public Observator { public: // Apeleaza constructorul parinte pentru a se inregistra la subiect Young_ConcretObservator(Subiect *mod, int div) : Observator(mod, div){} void update() { bool scor = getSubiect()->getScor(); setExciteLevel(getExciteLevel() + 1); if (scor && getExciteLevel() > 100) { cout << "Echipa tinerilor a marcat!!" << " Nivelul lor de excitatie este " << getExciteLevel() << " atentie la riscuri!!" << endl; }else{ cout << "Echipa tinerilor nu a marcat. Nu ne facem griji!" << endl; } } // sfarsit update() }; int main() { Subiect subj; Young_ConcretObservator youngObs1(&subj, 100); Old_ConcretObservator oldObs1(&subj, 150); Young_ConcretObservator youngObs2(&subj, 52); subj.setScor(true); }
true
91f0cb9bd6ea7c2f116e1d63d15e7917e8ba0ca4
C++
aliasvishnu/leetcode
/Solutions/523***-ContinuousSubarraySum.cpp
UTF-8
767
2.78125
3
[]
no_license
class Solution { public: bool checkSubarraySum(vector<int>& nums, int k) { int sum = 0; bool nonzero = false; unordered_set<int> st; // if( k < 0) k *= 1; if(k == 0){ for(int i = 0; i < nums.size()-1; i++) if(nums[i] == 0 && nums[i+1] == 0) return true; return false; } for(int num: nums){ if(num != 0) nonzero = true; sum = (sum%k + num%k) % k; cout << sum << endl; if(st.find(sum) != st.end()) return true; st.insert(sum); } if(!nonzero) return false; sum = 0; for(int num: nums) sum = (sum%k + num%k) %k; if(sum == 0 && nums.size() >= 2) return true; return false; } };
true
6d37dd698953da2d315ec18a6eaf2d0c663c007f
C++
DavidLee528/Cpp_Primer_5th_edition
/ex/3-5.cpp
UTF-8
290
2.765625
3
[]
no_license
/* * @ Author: 李天昊 * @ Description: * @ Date: * @ E-mail: 13121515269@163.com */ #include<iostream> using namespace std; int main() { string tmp; string str; while ( cin >> tmp ) { str += tmp + ' '; } cout << str << endl; return 0; }
true
eb70d12a0478ceab76aee837f91e077851347e18
C++
hilkojj/CG-windesheim-OpenGL
/Project1/source/graphics/ShaderProgram.cpp
UTF-8
1,876
2.828125
3
[]
no_license
#include "ShaderProgram.h" #include <vector> #include <iostream> ShaderProgram::ShaderProgram(std::string name, const char* vertSource, const char* fragSource) : name(std::move(name)) { compile(vertSource, fragSource); } void ShaderProgram::compile(const char* vertSource, const char* fragSource) { programId = glCreateProgram(); GLuint vertShaderId = glCreateShader(GL_VERTEX_SHADER); GLuint fragShaderId = glCreateShader(GL_FRAGMENT_SHADER); compileAndAttach(vertSource, vertShaderId, "VERTEX"); compileAndAttach(fragSource, fragShaderId, "FRAGMENT"); glLinkProgram(programId); // check program: GLint success = GL_FALSE; int logLength; glGetProgramiv(programId, GL_COMPILE_STATUS, &success); glGetProgramiv(programId, GL_INFO_LOG_LENGTH, &logLength); if (logLength > 1) { std::vector<char> log(logLength + 1); glGetProgramInfoLog(programId, logLength, NULL, &log[0]); std::cout << name << " compilation log:\n" << &log[0] << std::endl; } glDetachShader(programId, vertShaderId); glDetachShader(programId, fragShaderId); glDeleteShader(vertShaderId); glDeleteShader(fragShaderId); compiled_ = success; } void ShaderProgram::compileAndAttach(const char* source, GLuint shaderId, const char* shaderType) { const char* sources[] = { source }; glShaderSource(shaderId, 1, sources, NULL); glCompileShader(shaderId); glAttachShader(programId, shaderId); } bool ShaderProgram::compiled() const { return compiled_; } GLuint ShaderProgram::id() const { return programId; } GLuint ShaderProgram::location(const char* uniformName) const { return glGetUniformLocation(programId, uniformName); } void ShaderProgram::use() { glUseProgram(programId); } ShaderProgram::~ShaderProgram() { glDeleteProgram(programId); }
true
c5418c0b022239467eda198bd997d8f84e010942
C++
Menooker/Kuai
/src/Kuai/ConcurrentHashMap.hpp
UTF-8
8,409
2.75
3
[ "Apache-2.0" ]
permissive
#pragma once #include "SpinLock.hpp" #include "ListNode.hpp" #include "LogicalClock.hpp" #include <stdint.h> #include <utility> namespace Kuai { struct PolicyNoRemove { static void updateLocalClock() { } struct DeletionFlag { constexpr bool isDeleted() { return false; } }; struct DeletionQueue { typedef void (*Deleter)(DeletionFlag *); DeletionQueue(Deleter v) {} }; static constexpr bool canRemove = false; }; struct PolicyCanRemove { static constexpr bool canRemove = true; static void updateLocalClock() { // sync local clock with global clock, indicating this core has seen the events with logical tick // less than the current global clock ThreadClock::updateLocalClock(); } struct DeletionFlag { std::atomic<uint64_t> deleteTick = {0}; void markDeleted() { // push up the global clock, indicating there is a new event that may not be seen by other cores auto clockv = ++GlobalClock::clock.logicalClock; deleteTick.store(clockv); // update the clock for the current thread because we have already seen it ThreadClock::tls_clock.logicalClock.store(clockv, std::memory_order::memory_order_relaxed); } bool readyToDelete() { return GlobalClock::clock.get_min_lock() >= deleteTick.load(); } bool isDeleted() { // It is safe if a thread checks isDeleted before another thread marks it deleted. Since the global clock is increased, // by node deletion and the thread has not yet updated the local lock, the thread's local lock will be less than the // deleteTick return deleteTick.load(); } }; struct DeletionQueue { std::mutex lock; std::vector<DeletionFlag *> queue; typedef void (*Deleter)(DeletionFlag *); Deleter deleter; DeletionQueue(Deleter deleter) : deleter(deleter) {} void enqueue(DeletionFlag *p) { std::lock_guard<std::mutex> guard(lock); queue.emplace_back(p); } void doGC() { updateLocalClock(); std::lock_guard<std::mutex> guard(lock); for (auto itr = queue.begin(); itr != queue.end();) { if ((*itr)->readyToDelete()) { deleter(*itr); itr = queue.erase(itr); } else { ++itr; } } } ~DeletionQueue() { for (auto &p : queue) { deleter(p); } } }; }; template <typename BucketPolicy, typename K, typename V, typename Hasher = std::hash<K>, typename Comparer = std::equal_to<K>> struct ConHashMap : private BucketPolicy::DeletionQueue { struct HashListNode : public BucketPolicy::DeletionFlag { K k; V v; HashListNode *next; }; struct Bucket { HashListNode *ptr = {nullptr}; SpinLock bucketLock; }; Bucket *buckets; unsigned bucketNum; Hasher hasher; Comparer cmper; private: Bucket &getBucket(const K &k) { BucketPolicy::updateLocalClock(); uint32_t hashv = hasher(k); return buckets[hashv % bucketNum]; } HashListNode *makeNewNode(const K &k, V &&v, HashListNode *next) { HashListNode *ret = new HashListNode(); ret->next = next; ret->k = k; ret->v = std::move(v); return ret; } HashListNode *makeNewNode(const K &k, const V &v, HashListNode *next) { HashListNode *ret = new HashListNode(); ret->next = next; ret->k = k; ret->v = v; return ret; } HashListNode *findNode(HashListNode *&head, const K &k, HashListNode *&prevNode) { for (;;) { prevNode = nullptr; HashListNode *headNode = head; // reload head node if we met a deleted node bool retry = false; while (headNode) { if (headNode->isDeleted()) { retry = true; break; } if (cmper(headNode->k, k)) { return headNode; } prevNode = headNode; headNode = headNode->next; } if (!retry) return nullptr; } } HashListNode *findNode(HashListNode *&headNode, const K &k) { HashListNode *prevNode; return findNode(headNode, k, prevNode); } static void nodeDeleter(typename BucketPolicy::DeletionFlag *node) { delete static_cast<HashListNode *>(node); } public: ConHashMap(size_t numBuckets) : BucketPolicy::DeletionQueue(nodeDeleter) { buckets = new Bucket[numBuckets]; bucketNum = numBuckets; } ~ConHashMap() { for (size_t i = 0; i < bucketNum; i++) { HashListNode *cur = buckets[i].ptr; while (cur) { auto next = cur->next; delete cur; cur = next; } } delete[] buckets; } V *get(const K &k) { Bucket &buck = getBucket(k); HashListNode *cur = findNode(buck.ptr, k); if (cur) { return &cur->v; } return nullptr; } template <typename VType> void set(const K &k, VType &&v) { Bucket &buck = getBucket(k); std::lock_guard<SpinLock> guard(buck.bucketLock); HashListNode *headNode = buck.ptr; HashListNode *cur = findNode(buck.ptr, k); if (cur) { cur->v = std::forward<VType>(v); return; } buck.ptr = makeNewNode(k, std::forward<VType>(v), headNode); } template <typename Dummy = BucketPolicy> typename std::enable_if<Dummy::canRemove>::type remove(const K &k) { Bucket &buck = getBucket(k); std::lock_guard<SpinLock> guard(buck.bucketLock); HashListNode *prevNode; HashListNode *cur = findNode(buck.ptr, k, prevNode); if (cur) { if (prevNode) { prevNode->next = cur->next; } else { buck.ptr = cur->next; } cur->markDeleted(); this->enqueue(cur); return; } throw std::runtime_error("Cannot find the key!"); } template <typename Dummy = BucketPolicy> typename std::enable_if<Dummy::canRemove>::type garbageCollect() { this->doGC(); } template <typename VType> V *setIfAbsent(const K &k, VType &&v) { Bucket &buck = getBucket(k); std::lock_guard<SpinLock> guard(buck.bucketLock); HashListNode *headNode = buck.ptr; HashListNode *cur = findNode(buck.ptr, k); if (cur) { return &cur->v; } buck.ptr = makeNewNode(k, std::forward<VType>(v), headNode); return nullptr; } }; } // namespace Kuai
true
32452cbb11659126a70a5d985cb7bf13266cec16
C++
thomaszhang/coding-challenges
/cpp/to_lower_case.cpp
UTF-8
515
2.859375
3
[]
no_license
/* Find out why "if (str[i] >= 'A' && str[i] <= 'Z')" is needed? Line 64: Char 16: runtime error: index -123 out of bounds for type 'std::__cxx11::string [256]' (_Serializer_.cpp) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior _Serializer_.cpp:73:16 */ class Solution { public: string toLowerCase(string str) { for (int i = 0; i < str.size(); i++) { if (str[i] >= 'A' && str[i] <= 'Z') str[i] = char(int(str[i])+32); } return str; } };
true
c604f06259e8dbdb50842a61f4f6382b8bfbee63
C++
yuansun97/Data-Structures-cpp
/mp_traversals/imageTraversal/ImageTraversal.cpp
UTF-8
4,266
3.25
3
[]
no_license
#include <cmath> #include <iterator> #include <iostream> #include "../cs225/HSLAPixel.h" #include "../cs225/PNG.h" #include "../Point.h" #include "ImageTraversal.h" ImageTraversal::~ImageTraversal() { } /** * Calculates a metric for the difference between two pixels, used to * calculate if a pixel is within a tolerance. * * @param p1 First pixel * @param p2 Second pixel * @return the difference between two HSLAPixels */ double ImageTraversal::calculateDelta(const HSLAPixel & p1, const HSLAPixel & p2) { double h = fabs(p1.h - p2.h); double s = p1.s - p2.s; double l = p1.l - p2.l; // Handle the case where we found the bigger angle between two hues: if (h > 180) { h = 360 - h; } h /= 360; return sqrt( (h*h) + (s*s) + (l*l) ); } /** * Default iterator constructor. */ ImageTraversal::Iterator::Iterator(const Point & endPoint) { /** @todo [Part 1] */ traversal_ = NULL; currentPoint_.x = endPoint.x; currentPoint_.y = endPoint.y; } ImageTraversal::Iterator::Iterator(ImageTraversal & traversal) : traversal_(&traversal) { /** @todo [Part 1] */ currentPoint_ = traversal_->peek(); tolerance_ = traversal_->getTolerance(); start_ = traversal_->getStart(); } ImageTraversal::Iterator::~Iterator() { if (traversal_ != NULL) { delete traversal_; traversal_ = NULL; } } /** * Iterator increment opreator. * * Advances the traversal of the image. */ ImageTraversal::Iterator & ImageTraversal::Iterator::operator++() { /** @todo [Part 1] */ // ---------------- Pop -------------- // if (traversal_->empty()) { // currentPoint_.x = traversal_->getWidth(); // currentPoint_.y = traversal_->getHeight(); // return *this; // } currentPoint_ = traversal_->pop(); // ---------------- Add -------------- unsigned x = currentPoint_.x; unsigned y = currentPoint_.y; unsigned width = traversal_->getWidth(); unsigned height = traversal_->getHeight(); const Point & pRight = Point(x + 1, y); // right point const Point & pDown = Point(x, y + 1); // down point const Point & pLeft = Point(x - 1, y); // left point const Point & pAbove = Point(x, y - 1); // above point const HSLAPixel & pix0 = traversal_->getPixel(start_); // right if (pRight.x < width && !traversal_->isVisited(pRight)) { const HSLAPixel & pix1 = traversal_->getPixel(pRight); double delta = ImageTraversal::calculateDelta(pix0, pix1); if (delta < tolerance_) { traversal_->add(pRight); } } // down if (pDown.y < height && !traversal_->isVisited(pDown)) { const HSLAPixel & pix2 = traversal_->getPixel(pDown); double delta = ImageTraversal::calculateDelta(pix0, pix2); if (delta < tolerance_) { traversal_->add(pDown); } } // left if (pLeft.x < width && !traversal_->isVisited(pLeft)) { const HSLAPixel & pix3 = traversal_->getPixel(pLeft); double delta = ImageTraversal::calculateDelta(pix0, pix3); if (delta < tolerance_) { traversal_->add(pLeft); } } // above if (pAbove.y < height && !traversal_->isVisited(pAbove)) { const HSLAPixel & pix4 = traversal_->getPixel(pAbove); double delta = ImageTraversal::calculateDelta(pix0, pix4); if (delta < tolerance_) { traversal_->add(pAbove); } } // ---------------- Peek -------------- while (!traversal_->empty() && traversal_->isVisited(traversal_->peek())) { traversal_->pop(); } if (traversal_->empty()) { currentPoint_.x = width; currentPoint_.y = height; } else { currentPoint_ = traversal_->peek(); } return *this; } /** * Iterator accessor opreator. * * Accesses the current Point in the ImageTraversal. */ Point ImageTraversal::Iterator::operator*() { /** @todo [Part 1] */ return currentPoint_; } /** * Iterator inequality operator. * * Determines if two iterators are not equal. */ bool ImageTraversal::Iterator::operator!=(const ImageTraversal::Iterator &other) { /** @todo [Part 1] */ // std::cout << "currPoint: (" << currentPoint_.x << ", " << currentPoint_.y << ")" << std::endl; // std::cout << "otherPoint: (" << other.currentPoint_.x << ", " << other.currentPoint_.y << ")" << std::endl; return !(currentPoint_ == other.currentPoint_); }
true
3456cb46e9e877d41861cf6461782c6a89b24cdc
C++
casual-hostility/symmetrical-palm-tree
/conditional statements.cpp
UTF-8
205
3.15625
3
[]
no_license
int main() { int x = 0; 42 == x; //Equality 42 != x; //Inequality 100 > x; //Greater than 123 >= x; //Greater than or equal to -10 < x; //Less than -99 <= x; //Less than or equal to
true
fafee456e6bf9f5b8360bc15f206a9f53756f2e8
C++
reisdima/Trabalho-DCC146
/ProjetoTrabalho/Tag.cpp
UTF-8
1,228
3.484375
3
[]
no_license
#include "Tag.h" #include <stack> Tag::Tag(string tag) { primeiro = NULL; } Tag::~Tag() { //dtor } void Tag::InserirElemento(string a, string b){ ElementoTag *elemento1 = new ElementoTag(a); ElementoTag *elemento2 = new ElementoTag(b); elemento1->SetProx(elemento2); if(primeiro == NULL){ primeiro = elemento1; } else{ ElementoTag *aux = primeiro; while(aux->GetProx() != NULL) aux = aux->GetProx(); aux->SetProx(elemento1); } } void Tag::PrintTag(){ ElementoTag *aux = primeiro; while(aux != NULL){ cout << aux->GetValor() << " "; aux = aux->GetProx(); } cout << endl; } void Tag::CriarTag(string tag){ stack<string> pilha; int i = 0; while(tag[i] != '\0'){ if(tag[i] == '+'){ if(!pilha.empty()){ string a = pilha.top(); pilha.pop(); string b = pilha.top(); pilha.pop(); InserirElemento(a, b); } } else if(tag[i] == '*'){ } else{ string aux = ""; aux += tag[i]; pilha.push(aux); } i++; } }
true
3ed930b8c19e33eb2cdd4e8a1068cf499d10e881
C++
MathProgrammer/CodeForces
/2020/Practice/Programs/Line.cpp
UTF-8
746
3.171875
3
[]
no_license
#include <iostream> #include <string> #include <algorithm> using namespace std; long long extended_gcd(long long A, long long B, long long &x, long long &y) { if(B == 0) { x = 1; y = 0; return A; } long long x1, y1; long long gcd = extended_gcd(B, A%B, x1, y1); y = x1 - (A/B)*y1; x = y1; //cout << "(" << A << "," << B << ") = " << x << "," << y << "\n"; return gcd; } int main() { long long A, B, C; cin >> A >> B >> C; long long X = 0, Y = 0; long long gcd_A_B = extended_gcd(A, B, X, Y); X *= (-C/gcd_A_B); Y *= (-C/gcd_A_B); if(C%gcd_A_B == 0) cout << X << " " << Y << "\n"; else cout << "-1\n"; return 0; }
true