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
151507e9d3158ad4590ed0ef352d11f52ea59e7e
C++
Bernat417/TFG
/Code/CSV_handler.cpp
UTF-8
428
3.03125
3
[]
no_license
#include "CSV_handler.hpp" void CSV_handler::save_csv_file(string filename, vector<vector<string> > lines) { ofstream File (filename); //Opening file to print info to if(lines.size() >= 1) for(int j = 0; j < lines[0].size(); ++ j) { for(int i = 0; i < (lines.size()-1); ++i) File << lines[i][j] << ","; File << lines[(lines.size()-1)][j] << endl; } File.close(); }
true
64af586850ef4ec78bbdefce1c59ad05cf1b047f
C++
Vaa3D/vaa3d_tools
/released_plugins/v3d_plugins/bigneuron_siqi_stalker_v3d/lib/ITK_include/itkMinimumDecisionRule.h
UTF-8
2,286
2.515625
3
[ "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef __itkMinimumDecisionRule_h #define __itkMinimumDecisionRule_h #include "itkDecisionRule.h" namespace itk { namespace Statistics { /** \class MinimumDecisionRule * \brief A decision rule that returns the class label with the * smallest discriminant score. * * MinimumDecisionRule returns the class label with the smallest * discriminant score. * * \ingroup ITKStatistics */ class MinimumDecisionRule:public DecisionRule { public: /** Standard class typedefs */ typedef MinimumDecisionRule Self; typedef DecisionRule Superclass; typedef SmartPointer< Self > Pointer; typedef SmartPointer< const Self > ConstPointer; /** Run-time type information (and related methods) */ itkTypeMacro(MinimumDecisionRule, DecisionRule); /** Standard New() method support */ itkNewMacro(Self); /** Types for discriminant values and vectors. */ typedef Superclass::MembershipValueType MembershipValueType; typedef Superclass::MembershipVectorType MembershipVectorType; /** Types for class identifiers. */ typedef Superclass::ClassIdentifierType ClassIdentifierType; /** * Evaluate the decision rule, returning the class label associated * with the smallest discriminant score. */ virtual ClassIdentifierType Evaluate(const MembershipVectorType & discriminantScores) const; protected: MinimumDecisionRule() {} virtual ~MinimumDecisionRule() {} }; // end of class } // end of namespace Statistics } // end of namespace itk #endif
true
032c4b53eef8823a7cd55b0b3df84632dac75f94
C++
marcelomrocha/projetos_fisicarduino
/Psx_Servo/Psx_Servo/Psx_Servo.ino
UTF-8
2,676
2.671875
3
[]
no_license
/* PSX Controller Decoder Library (Psx.pde) Written by: Kevin Ahrendt June 22nd, 2008 Controller protocol implemented using Andrew J McCubbin's analysis. http://www.gamesx.com/controldata/psxcont/psxcont.htm Shift command is based on tutorial examples for ShiftIn and ShiftOut functions both written by Carlyn Maw and Tom Igoe http://www.arduino.cc/en/Tutorial/ShiftIn http://www.arduino.cc/en/Tutorial/ShiftOut */ // www.fisicarduino.wordpress.com #include <Servo.h> #include <WProgram.h> #include <Psx.h> #define dataPin 2 // nomeia o pino 2 como dataPin etc.... #define cmndPin 3 #define attPin 4 #define clockPin 5 #define LEDPin 13 Servo x_servo, y_servo; // Cria dois objetos do tipo Servo. Psx Psx; // inicializa a biblioteca unsigned int data = 0; // a variavel data armazena a resposta de controlador float x = 1; float y = 1; void setup() { // Define quais pinos serao usados // (Data Pin #, Cmnd Pin #, Att Pin #, Clk Pin #, Delay) // delay mede o relogio demora em cada estado, // medido em microsegundos. Psx.setupPins(dataPin, cmndPin, attPin, clockPin, 50); x_servo.attach(9); // Anexa o objeto x_servo ao pino 9 do arduino. y_servo.attach(10); // Anexa o objeto y_servo ao pino 10 do arduino. x_servo.write(0); // posiciona x_servo no angulo zero grau. y_servo.write(0); // posiciona y_servo no angulo zero grau. pinMode(LEDPin, OUTPUT); // coloca o LEDPin com saida } void loop() { data = Psx.read(); // Psx.read() inicia o controle e retorna os dados dos botoes if (data & psxDown) { digitalWrite(LEDPin, HIGH); // se a o botao seta baixo e' pressionado, incrementa a variavel y e acende o led y+=0.4; } else if (data & psxUp) { digitalWrite(LEDPin, HIGH); // se a o botao seta cima e' pressionado, decrementa a variavel y e acende o led y-=0.4; } else if (data & psxLeft) { digitalWrite(LEDPin, HIGH); // se a o botao seta esquerda e' pressionado, decrementa a variavel x e acende o led x-=0.4; } else if (data & psxRight) { digitalWrite(LEDPin, HIGH); // se a o botao seta direita e' pressionado, incrementa a variavel x e acende o led x+=0.4; } else { digitalWrite(LEDPin, LOW); // se nenhum botao e' pressionado, apaga o led } // limites 0 =< (x ou y) <=180 if (y > 180) y=180; // impede que as variaveis assumam valores incompativeis com os servo motores if (y < 0) y=0; if (x > 180) x=180; if (x < 0) x=0; // envia os valores para os servo motores x_servo.write(x); y_servo.write(y); // espera 10ms delay(10); }
true
2430963fd9790867e3a2e12beff2ff095d1b4429
C++
tbake0155/xQueueSys
/xqueuesys/src/priority_queue/src/process.h
UTF-8
3,292
3.34375
3
[]
no_license
/* * process.h - class declaration for Process object */ #ifndef PROCESS_H_INCLUDED #define PROCESS_H_INCLUDED #include <iostream> class Process { private: int status_num; // enumerate status for sorting int nice; // process priority pid_t pid; // process pid, only valid for a running process std::string process_path; // path to executable std::string status; // idle, waiting, running, blocked, failed std::string args; // args to be passed when executing /* * default contructor - not available */ Process(){} // can't touch this public: /* * contructor - create process with path, nice and args */ Process(std::string Process_Path, int How_Nice, std::string args); /* * contructor - create process with path and nice */ Process(std::string Process_Path, int How_Nice); /* * contructor - create process with path only */ Process(std::string Process_Path); /* * destructor */ ~Process(){} /* * Nice() - get value of nice */ int Nice(){return this->nice;} /* * Nice(int) - set value of nice */ void Nice(int Nice){this->nice=Nice;} /* * set_status_num() - set value of status num based on * current status */ void set_status_num(); /* * Pid() - get value of pid */ pid_t Pid(){return this->pid;} /* * Pid(pid_t) - set value of pid */ void Pid(pid_t Pid){this->pid=Pid;} /* * Process_Path() - get value of process_path */ std::string Process_Path(){return this->process_path;} /* * Status() - get value of status */ std::string Status(){return this->status;} /* * Status(string) - set value of status and status number */ void Status(std::string Child_Status){this->status=Child_Status; this->set_status_num();} /* * Args() - get value of args */ std::string Args(){return this->args;} /* * Args(string) - set value of args */ void Args(std::string Args){this->args=Args;} /* * operator - equality operator */ bool operator==(Process const& other)const; /* * operator - inequality operator */ bool operator!=(Process const& other)const; /* * operator - less than operator */ bool operator<(Process const& other)const; /* * path_to_name(string) - return process name from path * passed */ std::string path_to_name(std::string path); /* * path_to_name() - return process name from this processes's * path */ std::string path_to_name(); /* * Scrollable_List_Data(bool) - return formatted output for * gtk_list_item's label. bool * flag to include PID. */ std::string Scrollable_List_Data(bool include_pid); /* * match_process(string, bool) - match selected list_data * against our list data. bool * flag indicates if PID is included. */ bool match_process(std::string process_data, bool include_pid); }; #endif // PROCESS_H
true
7a58bde5b1c7f5be1ebbf5ef49569eb94f56cdbf
C++
q279003765/CppPrimerPlus6th
/CppPrimerPlus6th/list_6_9_condit.cpp
UTF-8
521
3.296875
3
[]
no_license
// // list_6_9_condit.cpp // CppPrimerPlus6th // // Created by xxin on 2020/10/26. // Copyright © 2020 xxin. All rights reserved. // #include "list_6_9_condit.hpp" #include <iostream> int condit(); /* * int main() { condit(); } */ int condit() { using namespace std; int a,b; cout << "Enter two integers:"; cin >> a >> b; cout << "The larger of " << a << " and " << b; int c = a > b ? a : b; // c = a if a > b, else c = b cout << " is " << c << endl; return 0; }
true
a99a1e2c0a5b3dfa1c105cca1034be958e3201b1
C++
1m188/playbricks
/playbricks_qt5/src/scene/DifficultyChooseScene.cpp
UTF-8
2,772
2.75
3
[]
no_license
#include "DifficultyChooseScene.h" #include "Director.h" #include "StartScene.h" #include "GameScene.h" #include "QLabel" #include "QPushButton" #include "QGridLayout" DifficultyChooseScene::DifficultyChooseScene(Window *parent) : Scene(parent) { } DifficultyChooseScene::~DifficultyChooseScene() { } void DifficultyChooseScene::init() { // 控件 QLabel *infoLabel = new QLabel(this); infoLabel->setAlignment(Qt::AlignCenter); infoLabel->setFont(QFont(u8"微软雅黑", 40)); infoLabel->setText(tr(u8"难 度 选 择")); QPushButton *easyButton = new QPushButton(this); easyButton->setObjectName("0"); easyButton->setFont(QFont(u8"微软雅黑", 15)); easyButton->setText(tr(u8"简单")); connect(easyButton, &QPushButton::clicked, this, &DifficultyChooseScene::difficultyChooseButtonClicked); QPushButton *mediumButton = new QPushButton(this); mediumButton->setObjectName("1"); mediumButton->setFont(QFont(u8"微软雅黑", 15)); mediumButton->setText(tr(u8"中等")); connect(mediumButton, &QPushButton::clicked, this, &DifficultyChooseScene::difficultyChooseButtonClicked); QPushButton *difficultButton = new QPushButton(this); difficultButton->setObjectName("2"); difficultButton->setFont(QFont(u8"微软雅黑", 15)); difficultButton->setText(tr(u8"困难")); connect(difficultButton, &QPushButton::clicked, this, &DifficultyChooseScene::difficultyChooseButtonClicked); QPushButton *returnToStartSceneButton = new QPushButton(this); returnToStartSceneButton->setFont(QFont(u8"微软雅黑", 15)); returnToStartSceneButton->setText(tr(u8"返回开始界面")); connect(returnToStartSceneButton, &QPushButton::clicked, this, &DifficultyChooseScene::returnToStartSceneButtonClicked); // 布局 QGridLayout *layout = new QGridLayout(this); layout->addWidget(infoLabel, 0, 0, 10, 15); layout->addWidget(easyButton, 10, 5, 2, 5); layout->addWidget(mediumButton, 12, 5, 2, 5); layout->addWidget(difficultButton, 14, 5, 2, 5); layout->addWidget(returnToStartSceneButton, 16, 5, 2, 5); } void DifficultyChooseScene::difficultyChooseButtonClicked() { GameScene *gameScene = new GameScene(Director::getInstance()->getWindow()); Director::getInstance()->setNowScene(gameScene); gameScene->init(sender()->objectName().toInt()); // 通过各自预先设置的objectname可以直接get到难度系数并用作初始化 gameScene->show(); deleteLater(); } void DifficultyChooseScene::returnToStartSceneButtonClicked() { StartScene *startScene = new StartScene(Director::getInstance()->getWindow()); Director::getInstance()->setNowScene(startScene); startScene->init(); startScene->show(); deleteLater(); }
true
dfa58b4d770c8117b7d3b7083c9c28f1076eab8b
C++
schmcory/CS162
/Project2_Schmidt_Cory/zoo.cpp
UTF-8
7,270
3.203125
3
[]
no_license
/********************************************************************* ** Author: Cory Schmidt ** Date: 02/05/2018 ** Description: "zoo.cpp" is the Zoo class implementation file *********************************************************************/ #include <ctime> #include <iostream> #include <cstdlib> using namespace std; //"zoo.hpp" is the Zoo class header file #include "zoo.hpp" int tigerPayoff; //default constructor Zoo::Zoo() { days = 0; budget = 100000; dayFoodCost = 10; bankrupt = false; numTigers = 0; numPenguins = 0; numTurtles = 0; tigers = new Tiger[numTigers]; penguins = new Penguin[numPenguins]; turtles = new Turtle[numTurtles]; } //destructor Zoo::~Zoo() { delete[] tigers; delete[] penguins; delete[] turtles; } int &Zoo::getDays() { return days; } double &Zoo::getBudget() { return budget; } double Zoo::getDayFoodCost() { return dayFoodCost; } bool Zoo::getBank() { return bankrupt; } void Zoo::setBank(bool x) { if(x == false) { bankrupt = false; } if (x == true) { bankrupt = true; } } /* TIGERS */ Tiger & Zoo::getTiger(int t) { return tigers[t]; } //void function adds tigers to the zoo void Zoo::addTiger() { int i; Tiger temp_array[numTigers]; for(int i = 0; i < numTigers; i++) { temp_array[i] = tigers[i]; } numTigers += 1; //deletes the old array delete[] tigers; tigers = new Tiger[numTigers]; for(i = 0; i < numTigers - 1; i++) { tigers[i].setAge(temp_array[i].getAge()); tigers[i].setCost(temp_array[i].getCost()); tigers[i].setNumberOfBabies(temp_array[i].getNumberOfBabies()); tigers[i].setFoodCost(temp_array[i].getFoodCost()); tigers[i].setPayoff(temp_array[i].getPayoff()); } } void Zoo::removeTiger(int r) { Tiger temp_array[numTigers]; for(int i = 0; i < r; i++) { temp_array[i] = tigers[i]; } for(int i = r + 1; i < numTigers; i++) { temp_array[i - 1] = tigers[i]; } numTigers--; delete[] tigers; tigers = new Tiger[numTigers]; cout << tigers << endl; for(int i = 0; i < numTigers; i++) { tigers[i].setAge(temp_array[i].getAge()); tigers[i].setCost(temp_array[i].getCost()); tigers[i].setNumberOfBabies(temp_array[i].getNumberOfBabies()); tigers[i].setFoodCost(temp_array[i].getFoodCost()); tigers[i].setPayoff(temp_array[i].getPayoff()); } } int Zoo::getNumOfTigers() { return numTigers; } /* END TIGERS */ /* PENGUINS */ Penguin & Zoo::getPenguin(int t) { return penguins[t]; } //void function adds tigers to the zoo void Zoo::addPenguin() { int i; Penguin temp_array[numPenguins]; for(int i = 0; i < numPenguins; i++) { temp_array[i] = penguins[i]; } numPenguins += 1; //deletes the old array delete[] penguins; penguins = new Penguin[numPenguins]; for(i = 0; i < numPenguins - 1; i++) { penguins[i].setAge(temp_array[i].getAge()); penguins[i].setCost(temp_array[i].getCost()); penguins[i].setNumberOfBabies(temp_array[i].getNumberOfBabies()); penguins[i].setFoodCost(temp_array[i].getFoodCost()); penguins[i].setPayoff(temp_array[i].getPayoff()); } } void Zoo::removePenguin(int r) { Penguin temp_array[numPenguins]; for(int i = 0; i < r; i++) { temp_array[i] = penguins[i]; } for(int i = r + 1; i < numPenguins; i++) { temp_array[i - 1] = penguins[i]; } numPenguins--; delete[] penguins; penguins = new Penguin[numPenguins]; cout << penguins << endl; for(int i = 0; i < numPenguins; i++) { penguins[i].setAge(temp_array[i].getAge()); penguins[i].setCost(temp_array[i].getCost()); penguins[i].setNumberOfBabies(temp_array[i].getNumberOfBabies()); penguins[i].setFoodCost(temp_array[i].getFoodCost()); penguins[i].setPayoff(temp_array[i].getPayoff()); } } int Zoo::getNumOfPenguins() { return numPenguins; } /* END PENGUINS */ /* TURTLES */ Turtle & Zoo::getTurtle(int t) { return turtles[t]; } //void function adds tigers to the zoo void Zoo::addTurtle() { int i; Turtle temp_array[numTurtles]; for(int i = 0; i < numTurtles; i++) { temp_array[i] = turtles[i]; } numTurtles += 1; //deletes the old array delete[] turtles; turtles = new Turtle[numTurtles]; for(i = 0; i < numTurtles - 1; i++) { turtles[i].setAge(temp_array[i].getAge()); turtles[i].setCost(temp_array[i].getCost()); turtles[i].setNumberOfBabies(temp_array[i].getNumberOfBabies()); turtles[i].setFoodCost(temp_array[i].getFoodCost()); turtles[i].setPayoff(temp_array[i].getPayoff()); } } void Zoo::removeTurtle(int r) { Turtle temp_array[numTurtles]; for(int i = 0; i < r; i++) { temp_array[i] = turtles[i]; } for(int i = r + 1; i < numTurtles; i++) { temp_array[i - 1] = turtles[i]; } numTurtles--; delete[] turtles; turtles = new Turtle[numTurtles]; cout << turtles << endl; for(int i = 0; i < numTurtles; i++) { turtles[i].setAge(temp_array[i].getAge()); turtles[i].setCost(temp_array[i].getCost()); turtles[i].setNumberOfBabies(temp_array[i].getNumberOfBabies()); turtles[i].setFoodCost(temp_array[i].getFoodCost()); turtles[i].setPayoff(temp_array[i].getPayoff()); } } int Zoo::getNumOfTurtles() { return numTurtles; } /* END TURTLES */ void Zoo::subtractFoodCost() { double tigerFoodCost; double penguinFoodCost; double turtleFoodCost; tigerFoodCost = (dayFoodCost*tigers[0].getFoodCost()*numTigers); penguinFoodCost = (dayFoodCost*penguins[0].getFoodCost()*numTigers); turtleFoodCost = (dayFoodCost*turtles[0].getFoodCost()*numTigers); budget -= (tigerFoodCost+penguinFoodCost+turtleFoodCost); } //function incremements each animal up 1 per day void Zoo::incrementAge() { days++; for(int i = 0; i < numTigers; i++) { tigers[i].setAge(tigers[i].getAge() + 1); } for(int i = 0; i < numPenguins; i++) { penguins[i].setAge(penguins[i].getAge() + 1); } for(int i = 0; i < numTurtles; i++) { turtles[i].setAge(turtles[i].getAge() + 1); } } //void function prints the payoff for the day, with or without the bonus applied void Zoo::printPayoff(int bonus) { srand(time(NULL)); int penguinPayoff; int turtlePayoff; int tigerPayoff; int tigerBonus; if(bonus == 1) { tigerPayoff = ((tigers[0].getPayoff())*numTigers); penguinPayoff = ((penguins[0].getPayoff())*numPenguins); turtlePayoff = ((turtles[0].getPayoff())*numTurtles); budget += (tigerPayoff+penguinPayoff+turtlePayoff); } if(bonus == 2) { tigerPayoff = ((tigers[0].getPayoff())*numTigers) + ((rand()%250)+250); penguinPayoff = ((penguins[0].getPayoff())*numPenguins); turtlePayoff = ((turtles[0].getPayoff())*numTurtles); budget += (tigerPayoff+penguinPayoff+turtlePayoff); } }
true
9a34b1ec77d592738de3c4134639eefc431c2e4d
C++
deletestvn/Leetcode
/src/Learn/LinkedList/addTwoNumbers.cpp
UTF-8
1,188
3.359375
3
[]
no_license
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { if(l1 == nullptr && l2 == nullptr) return nullptr; if(l1 == nullptr && l2 != nullptr) return l2; if(l1 != nullptr && l2 == nullptr) return l1; ListNode * sum = new ListNode(); ListNode * curr = sum; ListNode * digit1 = l1; ListNode * digit2 = l2; int carry = 0; while(digit1 != nullptr || digit2 != nullptr || carry != 0) { int x = (digit1 == nullptr) ? 0 : digit1 -> val; int y = (digit2 == nullptr) ? 0 : digit2 -> val; int digitSum = x + y + carry; carry = digitSum / 10; curr -> next = new ListNode(digitSum % 10); curr = curr -> next; if(digit1 != nullptr) digit1 = digit1 -> next; if(digit2 != nullptr) digit2 = digit2 -> next; } return sum -> next; } };
true
607bd1875f63d42eb96403d0372d9d1ef3b8b18d
C++
JoshuaMartinez30/C-_TDH_2
/hanoi_ascii.cpp
UTF-8
2,180
3.171875
3
[]
no_license
#include <iostream> #include <stdio.h> using namespace std; void impresion(int *M, int f, int colum, int numero){ int esp; for (int i = colum - 1; i >= 0; i--){ for (int j = 0; j < f; j++){ esp = (numero - M[colum * j + i]) / 2; for (int k = 0; k < esp; k++){ cout << " "; } for (int k = 0; k < M[colum * j + i]; k++){ printf("%c", 220); } for (int k = 0; k < esp; k++){ cout << " "; } cout << "\t"; } cout << "\n"; } } void movimientos(int *M, int f, int colum, int numero, int A_inicial, int A_destino){ int inicial, Destino; inicial = colum - 1; Destino = colum - 1; while (inicial >= 0 && M[colum * A_inicial + inicial] == 0){ inicial--; } if (inicial < 0){ inicial = 0; } do{ Destino--; } while (Destino >= 0 && M[colum * A_destino + Destino] == 0); M[colum * A_destino + Destino + 1] = M[colum * A_inicial + inicial]; M[colum * A_inicial + inicial] = 0; impresion(M, f, colum, numero); } void hanoi(int *M, int f, int colum, int discos, int numero, int A_inicial, int A_auxiliar, int A_destino) { if (discos == 1){ movimientos(M, f, colum, numero, A_inicial, A_destino); } else{ hanoi(M, f, colum, discos - 1, numero, A_inicial, A_destino, A_auxiliar); movimientos(M, f, colum, numero, A_inicial, A_destino); hanoi(M, f, colum, discos - 1, numero, A_auxiliar, A_inicial, A_destino); } } int main() { int f, colum, *M = NULL, discos, numero; f = 3; discos = 1; cout << "Ingrese la cantidad de discos: "; cin >> colum; M = (int *)malloc(sizeof(int) * f * colum); for (int i = 0; i < f; i++){ for (int j = colum - 1; j >= 0; j--){ if (i == 0){ M[(colum * i) + j] = discos; discos += 2; } else{ M[(colum * i) + j] = 0; } } } numero = discos; impresion(M, f, colum, numero); hanoi(M, f, colum, colum, numero, 0, 1, 2); }
true
0e3b67cdd40368009af9df03ece98227948f846d
C++
profeIMA/Exercicis-Programacio
/Exercicis_POO/Exercici6_VectorPunt2D/Vector_punt2D.h
UTF-8
1,513
3.453125
3
[]
no_license
/* Vector de punts 2D ordenat de menor a major distància a l'origen (si la distància és igual cal ordenar segons coordenada x) */ #ifndef Vector_punt2D_h #define Vector_punt2D_h #include "Punt2D.h" class Vector_punt2D { // Descripció: vector de punts 2D ordenat de menor a major distància a l'origen (si la distància és igual cal ordenar segons menor coordenada x) public: // Constructors Vector_punt2D(); // Pre: --; Post: vector buit de punts // Consultors double nombre_punts() const; // Pre: --; Post: retorna el nombre de punts double mitjana_distancies_origen() const; // Pre: nombre_punts()>0; Post: retorna la distància mitjana de tots els punts del vector a l'origen void mostrar() const; // Pre: --; Post: mostra tots els punts del vector numerats de 0 al nombre de punts-1 // Modificadors void inserir_punt(Punt2D punt); // Pre: nombre_punts()<MAX; Post: s'ha inserit ordenadament un punt en el vector de punts void esborrar_punt(int pos); // Pre: nombre_punts()>0 i 0<=pos<nombre_punts(); Post: s'esborra el punt que ocupa la posició pos private: // Constants static const unsigned MAX= 100; // Atributs Punt2D a_t[MAX]; // vector de punts unsigned a_n; // nombre de punts // Mètodes privats static bool es_menor(Punt2D p1, Punt2D p2); // Pre: --; Post: retorna cert si el punt actual és menor (més proper a l'origen) que p, fals en el cas contrari }; #endif /* Vector_punt2D_h */
true
c7444888595fb62f447905952b5300ba749b20ac
C++
take-pwave/lbed
/CCS_LBED_MAIN/samples/TestTone.cpp
UTF-8
472
2.640625
3
[]
no_license
#include "lbed.h" #include "Tone.h" int main(void) { int tones[]={262,294,330,392,440}; // C, D, E, G, A int toneDuration = 500; Serial pc(PA_1, PA_0); Tone tone(PB_5); // T1CCP1 DigitalOut myled(LEDR); pc.baud(19200); tone.noTone(); pc.println("Input number"); while (1) { char c = pc.read(); myled = !myled; if (c >= '1' && c <= '4') { int index = c - '1'; tone.tone(tones[index], toneDuration); } } return 0; }
true
2d4ddd603ced5a03f9b5c21ff7e1c26062bac9a8
C++
Soumya117/binarySearchTree
/BinaryTree.h
UTF-8
696
3.21875
3
[]
no_license
#include <vector> namespace binaryTree { class BinaryTree { private: struct Node { int data; Node *left; Node *right; }; Node *root; Node *createNode(const int& data); void addLeftChild(Node *, const int&); void addRightChild(Node *, const int&); void createSubTree(Node* node, const int& data); void printInOrder(Node* node); void printPreOrder(Node* node); void printPostOrder(Node* node); public: void createTree(const std::vector<int> &input); void displayInOrder(); void displayPreOrder(); void displayPostOrder(); }; }
true
ba53f01a97a666f46f72be0c07f4d4763c864316
C++
100sarthak100/DataStructures-Algorithms
/Code/Trees/sumRootToTreeNumbers.cpp
UTF-8
1,368
3.71875
4
[]
no_license
// Given a binary tree containing digits from 0-9 only, // each root-to-leaf path could represent a number. // An example is the root-to-leaf path 1->2->3 which represents // the number 123. // Find the total sum of all root-to-leaf numbers. // Note: A leaf is a node with no children. // Input: [1,2,3] // 1 // / \ // 2 3 // Output: 25 // Explanation: // The root-to-leaf path 1->2 represents the number 12. // The root-to-leaf path 1->3 represents the number 13. // Therefore, sum = 12 + 13 = 25. // Example 2: // Input: [4,9,0,5,1] // 4 // / \ // 9 0 // / \ // 5 1 // Output: 1026 // Explanation: // The root-to-leaf path 4->9->5 represents the number 495. // The root-to-leaf path 4->9->1 represents the number 491. // The root-to-leaf path 4->0 represents the number 40. // Therefore, sum = 495 + 491 + 40 = 1026. // time complexity is O(n) where n is the number of nodes in the // given binary tree. // pre order traversal class Solution { public: int treeSum(TreeNode* root, int sum) { if(root == NULL) return 0; sum = sum*10 + root->val; if(!root->left && !root->right) return sum; return treeSum(root->left, sum) + treeSum(root->right, sum); } int sumNumbers(TreeNode* root) { return treeSum(root, 0); } };
true
0583bb060fd629f912b7d0585a5e61307835f75d
C++
wcysai/CodeLibrary
/POJ/3532.cpp
UTF-8
2,895
3.1875
3
[]
no_license
#include <iostream> #include <algorithm> #include <vector> #include <cmath> using namespace std; #define LL long long #define MAX_N 20 + 8 int A, B, N, M; LL C[MAX_N][MAX_N]; // 生成组合数 void build_combinatorial_number() { for (int i = 0; i < MAX_N; ++i) { C[i][0] = C[i][i] = 1; for (int j = 1; j < i; ++j) C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } inline int to_index(int n, int m) { return n * M + m + 1; } // 高斯消元法求解线性方程组 ax = b ,增广矩阵A=[a,b] vector<double> gauss(vector< vector<double> >& A) { int n = A.size(); for (int i = 0; i < n; ++i) { // Search for maximum in this column double maxEl = abs(A[i][i]); int maxRow = i; for (int k = i + 1; k < n; ++k) { if (abs(A[k][i]) > maxEl) { maxEl = abs(A[k][i]); maxRow = k; } } // Swap maximum row with current row (column by column) for (int k = i; k < n + 1; ++k) { double tmp = A[maxRow][k]; A[maxRow][k] = A[i][k]; A[i][k] = tmp; } // Make all rows below this one 0 in current column for (int k = i + 1; k < n; ++k) { double c = -A[k][i] / A[i][i]; for (int j = i; j < n + 1; ++j) { if (i == j) { A[k][j] = 0; } else { A[k][j] += c * A[i][j]; } } } } // Solve equation Ax=b for an upper triangular matrix A vector<double> x(n); for (int i = n - 1; i >= 0; --i) { x[i] = A[i][n] / A[i][i]; for (int k = i - 1; k >= 0; --k) { A[k][n] -= A[k][i] * x[i]; } } return x; } inline double round(double x) { return x >= 0.0 ? floor(x + 0.5) : ceil(x - 0.5); } void solve() { const int size = N * M + 1; vector< vector<double> > mat(size, vector<double>(size + 1, 0.0)); mat[0][0] = 1.0; mat[0][size] = 1.0; // the coefficient of its highest-order term (ad) is one,于是增广矩阵第一行肯定是[1, 0, 0,..., 1] for (int d = 0; d < size; ++d) { for (int k = 0; k <= d; ++k) { mat[to_index(k % N, (d - k) % M)][d < N * M ? d + 1 : 0] += C[d][k] * pow((double)A, k / N) * pow((double)B, (d - k) / M); } } vector<double> x = gauss(mat); reverse(x.begin() + 1, x.end()); for (int i = 0; i < size; ++i) { printf("%d%c", int(round(x[i])), i == N * M ? '\n' : ' '); } } int main(int argc, char *argv[]) { build_combinatorial_number(); while (~scanf("%d%d%d%d", &A, &N, &B, &M) && A > 0) { solve(); } return 0; }
true
93e272d850b80192c008f9ddaf1b8d768395516a
C++
anupraas/SearchTextCPPProject
/Search Text/Search Text/Logger.cpp
UTF-8
1,745
2.8125
3
[]
no_license
// // Logger.cpp // Search Text // // Created by Prakhar Mehrotra on 28/07/17. // Copyright © 2017 Prakhar Mehrotra. All rights reserved. // #include "Logger.hpp" std::shared_ptr<Logger> Logger:: instance(nullptr); Logger::Logger() { } Logger::~Logger() { } std::string Logger::getCurrentTime() { std::time_t result = std::time(nullptr); return std::asctime(std::localtime(&result)); } void Logger::error(std::string str) { std::string message=getCurrentTime(); message = message.substr(0, message.size()-1); message=message + " Error: "; message+=str; message+="\n"; std::cout<<message<<std::endl; } void Logger::warn(std::string str) { std::string message=getCurrentTime(); message = message.substr(0, message.size()-1); message=message + " Warn: "; message+=str; message+="\n"; std::cout<<message<<std::endl; } void Logger::debug(std::string str) { std::string message=getCurrentTime(); message = message.substr(0, message.size()-1); message=message + " Debug: "; message+=str; message+="\n"; std::cout<<message<<std::endl; } void Logger::info(std::string str) { std::string message=getCurrentTime(); message = message.substr(0, message.size()-1); message=message + " Info: "; message+=str; message+="\n"; std::cout<<message<<std::endl; } void Logger::log(std::string str) { std::string message=getCurrentTime(); message = message.substr(0, message.size()-1); message=message + " Log: "; message+=str; message+="\n"; std::cout<<message<<std::endl; } std::shared_ptr<Logger> Logger::getLoggerInstance() { if (instance == nullptr) instance.reset(new Logger()); return instance; }
true
b9027f259e246e33164ff2867245251004de6521
C++
APVerlan/Algorithms-and-Data-Structure-coursera-specialization-
/Data Structures/week4_binary_search_trees/2_is_bst/is_bst.cpp
UTF-8
1,703
3.5625
4
[]
no_license
#include <algorithm> #include <iostream> #include <vector> using std::cin; using std::cout; using std::endl; using std::vector; struct Node { int key; int left; int right; Node() : key(0), left(-1), right(-1) {} Node(int key_, int left_, int right_) : key(key_), left(left_), right(right_) {} }; bool in_order_(int i, vector<int>& res, const vector<Node>& tree, bool flag=false) { if (tree[i].left > 0) { if (!in_order_(tree[i].left, res, tree)) return false; } else flag = true; if (!res.empty() && flag && res.back() == tree[i].key) res.push_back(tree[i].key); else if (!res.empty() && res.back() >= tree[i].key) return false; else res.push_back(tree[i].key); if (tree[i].right > 0) if (!in_order_(tree[i].right, res, tree)) return false; return true; } bool IsBinarySearchTree(const vector<Node>& tree) { // Implement correct algorithm here if (tree.empty()) return true; vector<int> result; // Finish the implementation // You may need to add a new recursive method to do that if (tree[0].left > 0) if (!in_order_(tree[0].left, result, tree)) return false; if (!result.empty() && result.back() >= tree[0].key) return false; else result.push_back(tree[0].key); if (tree[0].right > 0) if (!in_order_(tree[0].right, result, tree)) return false; return true; } int main() { int nodes; cin >> nodes; vector<Node> tree; for (int i = 0; i < nodes; ++i) { int key, left, right; cin >> key >> left >> right; tree.push_back(Node(key, left, right)); } if (IsBinarySearchTree(tree)) { cout << "CORRECT" << endl; } else { cout << "INCORRECT" << endl; } return 0; }
true
c11a90392478340755f9445a2d4fd19704d27407
C++
CompPhysics/ComputationalPhysics
/doc/Programs/LecturePrograms/programs/MPI/chapter07/program5.cpp
UTF-8
1,371
2.8125
3
[ "CC0-1.0" ]
permissive
// Reactangle rule and numerical integration usign MPI, example 1, send and Receive using namespace std; #include <mpi.h> #include <iostream> int main (int nargs, char* args[]) { int numprocs, my_rank, i, n = 1000; double local_sum, rectangle_sum, x, h; // MPI initializations MPI_Init (&nargs, &args); MPI_Comm_size (MPI_COMM_WORLD, &numprocs); MPI_Comm_rank (MPI_COMM_WORLD, &my_rank); // Read from screen a possible new vaue of n if (my_rank == 0 && nargs > 1) { n = atoi(args[1]); } h = 1.0/n; // Broadcast n and h to all processes MPI_Bcast (&n, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast (&h, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD); // Every process sets up its contribution to the integral local_sum = 0.; for (i = my_rank; i < n; i += numprocs) { x = (i+0.5)*h; local_sum += 4.0/(1.0+x*x); } local_sum *= h; if (my_rank == 0) { MPI_Status status; rectangle_sum = local_sum; for (i=1; i < numprocs; i++) { MPI_Recv(&local_sum,1,MPI_DOUBLE,MPI_ANY_SOURCE,500,MPI_COMM_WORLD,&status); rectangle_sum += local_sum; } cout << "Result: " << rectangle_sum << endl; } else MPI_Send(&local_sum,1,MPI_DOUBLE,0,500,MPI_COMM_WORLD); // End MPI MPI_Finalize (); return 0; }
true
c0a0f365506fd7cd32e0fac0e28772e1202782bc
C++
Jonariguez/ACM_Code
/HDU/2031.cpp
UTF-8
609
2.953125
3
[]
no_license
#include <iostream> #include <string> #include <math.h> using namespace std; string transform(int x,int y,string s){ string res=""; int sum=0; for(int i=0;i<s.length();i++){ if(s[i]=='-') continue; if(s[i]>='0' && s[i]<='9') sum=sum*x+s[i]-'0'; else sum=sum*x+s[i]-'A'+10; } while(sum){ char temp=sum%y; sum/=y; if(temp<=9) temp+='0'; else temp=temp-10+'A'; res=temp+res; } if(res.length()==0) return res='0'; if(s[0]=='-') res='-'+res; return res; } int main() { int n,r; string s,res; while(cin>>s>>r){ res=transform(10,r,s); cout<<res<<endl; } return 0; }
true
354d5b3b1c47708abb7512a90ddb00d07cf64bd5
C++
andre-bergner/funky
/funky/test.cpp
UTF-8
5,877
3.03125
3
[ "Apache-2.0" ]
permissive
#include <tuple> #include <functional> #include <type_traits> #include <memory> #include <iostream> template <typename Type> using remove_rvalue_reference_t = std::conditional_t < std::is_rvalue_reference<Type>::value , std::remove_reference_t<Type> , Type >; template <typename X> auto ref_or_move(X&& x) -> remove_rvalue_reference_t<X&&> { return std::forward<X>(x); } template <typename X> struct capture_t { remove_rvalue_reference_t<X&&> value; }; template <typename X> capture_t<X&&> capture(X&& x) { return {std::forward<X>(x)}; } #define FORWARD(x) std::forward<decltype(x)>(x) #define CAPTURE(x) capture(FORWARD(x)) struct source_tag {}; struct pipe_tag {}; struct sink_tag {}; template <typename Tag, typename Function> struct Element { Function f; }; template <typename ElementType> struct tag_of; template <typename Tag, typename F> struct tag_of<Element<Tag,F>> { using type = Tag; }; template <typename ElementType> using tag_of_t = typename tag_of<ElementType>::type; template <typename F> using Source = Element<source_tag,F>; template <typename F> using Pipe = Element<pipe_tag,F>; template <typename F> using Sink = Element<sink_tag,F>; template <typename F> Source<F> source( F&& f ) { return { FORWARD(f) }; } template <typename F> Pipe<F> pipe( F&& f ) { return { FORWARD(f) }; } template <typename F> Sink<F> sink( F&& f ) { return { FORWARD(f) }; } template <typename SourceT, typename PipeT> decltype(auto) compose( source_tag, pipe_tag, SourceT&& s, PipeT&& p ) { return source([ src = CAPTURE(s), pip=CAPTURE(p) ](auto&& sink) { return src.value.f(pip.value.f( FORWARD(sink) ) ); }); } template <typename SourceT, typename SinkT> decltype(auto) compose( source_tag, sink_tag, SourceT&& s, SinkT&& sk ) { s.f(sk.f); } template <typename LeftElem, typename RightElem> decltype(auto) operator|( LeftElem&& l, RightElem&& r ) { return compose( tag_of_t<LeftElem>{}, tag_of_t<RightElem>{} , std::forward<LeftElem>(l), std::forward<RightElem>(r) ); } /* template <typename F, typename G> auto operator|( Pipe<F> l, Pipe<G> r ) { return pipe([ f=l.f, g=r.f ](auto&& x){ return f(g((x))); }); } template <typename F, typename G> auto operator|( Pipe<F> p, Sink<G> s ) { return sink(p.f(s.f)); } */ template <int n> struct LifeTime { LifeTime() { std::cout << "⬆ " << n << std::endl; } LifeTime(LifeTime const &) { std::cout << "⬌ " << n << std::endl; } LifeTime(LifeTime&&) { std::cout << "⬆ " << n << std::endl; } ~LifeTime() { std::cout << "⬇ " << n << std::endl; } }; template <typename Source1, typename Source2> decltype(auto) merge( source_tag, source_tag, Source1&& src1, Source2&& src2 ) { return source([ src1 = CAPTURE(src1), src2 = CAPTURE(src2) ] (auto&& snk) { using sink_t = std::decay_t<decltype(snk)>; auto shared_sink = [shink = std::make_shared<sink_t>(FORWARD(snk))] (auto&& x){ return (*shink)(FORWARD(x)); }; src1.value.f(shared_sink); src2.value.f(shared_sink); }); } template <typename Source1, typename Source2> decltype(auto) merge( Source1&& src1, Source2&& src2 ) { return merge( tag_of_t<Source1>{}, tag_of_t<Source2>{} , std::forward<Source1>(src1), std::forward<Source2>(src2) ); } /* template <typename SourceT> auto merge_in( source_tag, SourceT&& src ) { return pipe([ src = CAPTURE(src) ](auto&& snk) { //LifeTime<0> l; auto s = CAPTURE(snk); src.value.f(std::ref(s.value)); return [ snk = CAPTURE(s.value), l = LifeTime<1>{} ](auto&& x) mutable { snk.value(FORWARD(x)); }; }); } template <typename SourceT> decltype(auto) merge_in( SourceT&& src ) { return merge_in( tag_of_t<SourceT>{}, std::forward<SourceT>(src) ); } */ auto take( size_t n ) { return pipe([n](auto&& a) { LifeTime<3> l; return [n=n,a=CAPTURE(a)](auto&& x) mutable { if (n > 0) { --n; a.value(FORWARD(x)); } }; }); } template <typename F> auto subscribe( F&& f ) { return sink([f=CAPTURE(f)](auto&& v){ f.value(FORWARD(v)); }); } int main() { std::function<void(int)> c1; std::function<void(char)> c2; auto connect1 = [&](auto&& f){ c1 = FORWARD(f); }; auto connect2 = [&](auto&& f){ c2 = FORWARD(f); }; // source(connect1) // | merge_in(source(connect2)) merge(source(connect1),source(connect2)) | take(3) | subscribe([](auto x){ std::cout << x; }); c1(3); c2('x'); c1(4); c2('y'); c1(5); c2('z'); std::cout << "\n" << std::endl; /* int n = 4; auto&& k1 = ref_or_move(n); auto&& k2 = ref_or_move(4); std::cout << std::is_lvalue_reference<decltype(k1)>::value << " " << typeid(k1).name() << std::endl; std::cout << std::is_lvalue_reference<decltype(k2)>::value << " " << typeid(k2).name() << std::endl; [](auto&& l1, auto&& l2){ return [k1 = capture(FORWARD(l1)), k2 = capture(FORWARD(l2))]{ std::cout << std::is_lvalue_reference<decltype(k1.value)>::value << " " << typeid(k1.value).name() << std::endl; std::cout << std::is_lvalue_reference<decltype(k2.value)>::value << " " << typeid(k2.value).name() << std::endl; }; }(n,4)(); */ }
true
38969bce3e0a3938f7f75fe5ec5d01870f924f0e
C++
ddaletski/labs
/c++/charset/charset.cpp
UTF-8
4,516
2.984375
3
[]
no_license
#include "charset.h"\ #define SET_SIZE 256 void charSet::_realloc() { if(_refersTo && _refersTo->_refCount == 0) _refersTo = NULL; if(_refCount || (_refersTo && _refersTo->_refCount)){ bitArray* tmp = new bitArray(SET_SIZE); *tmp = *_arr; _arr = tmp; _refCount = 0; _refersTo = NULL; std::cout << "reallocation\n"; } } charSet::charSet() { _arr = new bitArray(SET_SIZE); _refCount = 0; _refersTo = NULL; } charSet::charSet(const char *str) { _arr = new bitArray(SET_SIZE); _refCount = 0; _refersTo = NULL; for(uint i = 0; i < strlen(str); ++i) *this << str[i]; } charSet::charSet(const std::string &str) : charSet(str.c_str()) { } charSet::charSet(const charSet &set) { _arr = set._arr; _refCount = 0; const_cast<charSet&>(set)._refCount++; _refersTo = &set; } charSet::~charSet() { if(_refCount == 0 && _refersTo == NULL) delete _arr; else if(_refersTo) const_cast<charSet*>(_refersTo)->_refCount--; } /////////////////////////////////////////////////////////// charSet &charSet::operator =(const charSet &set) { _arr = set._arr; const_cast<charSet&>(set)._refCount++; _refersTo = &set; return *this; } charSet &charSet::operator <<(const char &ch) { _realloc(); (*_arr)[ch] = 1; return *this; } charSet &charSet::operator >>(const char &ch) { _realloc(); (*_arr)[ch] = 0; return *this; } charSet &charSet::operator -=(const charSet &set) { _realloc(); for(uint i = 0; i < SET_SIZE; ++i) if((*set._arr)[i]) (*_arr)[i] = 0; return *this; } charSet &charSet::operator ^=(const charSet &set) { _realloc(); for(uint i = 0; i < SET_SIZE; ++i) (*_arr)[i] ^= (*set._arr)[i]; return *this; } charSet &charSet::operator |=(const charSet &set) { _realloc(); for (uint i = 0; i < SET_SIZE; ++i) (*_arr)[i] |= (*set._arr)[i]; return *this; } charSet &charSet::operator &=(const charSet &set) { _realloc(); for(uint i = 0; i < SET_SIZE; ++i) (*_arr)[i] &= (*set._arr)[i]; return *this; } ///////////////////////////////////////////////////// charSet charSet::operator +(const char &ch) { charSet temp = *this; temp << ch; return temp; } charSet charSet::operator -(const char &ch) { charSet temp = *this; temp >> ch; return temp; } charSet charSet::operator -(const charSet &set) { charSet temp = *this; temp -= set; return temp; } charSet charSet::operator ^(const charSet &set) { charSet temp = *this; temp ^= set; return temp; } charSet charSet::operator |(const charSet &set) { charSet temp = *this; temp |= set; return temp; } charSet charSet::operator &(const charSet &set) { charSet temp = *this; temp &= set; return temp; } ////////////////////////////////////////////////////// bool charSet::operator ==(const charSet &set) const { for(uint i = 0; i < SET_SIZE; ++i) if((*_arr)[i] != (*set._arr)[i]) return false; return true; } bool charSet::operator !=(const charSet &set) const { for(uint i = 0; i < SET_SIZE; ++i) if((*_arr)[i] != (*set._arr)[i]) return true; return false; } bool charSet::operator <=(const charSet &set) const { for(uint i = 0; i < SET_SIZE; ++i) if((*_arr)[i] && !(*set._arr)[i]) return false; return true; } bool charSet::operator >=(const charSet &set) const { for(uint i = 0; i < SET_SIZE; ++i) if((*set._arr)[i] && !(*_arr)[i]) return false; return true; } bool charSet::operator <(const charSet &set) const { return (*this <= set && *this != set); } bool charSet::operator >(const charSet &set) const { return (*this >= set && *this != set); } bool charSet::contains(const char &ch) { return (*_arr)[ch]; } ///////////////////////////////////////////////////// std::ostream& operator << (std::ostream &stream, const charSet& set) { for(uint i = 0; i < SET_SIZE; ++i) if((*set._arr)[i]) stream << char(i) << "\n"; return stream; } //////////////////////////////////////////////////////// charSet make_charset(const char* str) { charSet set; for(uint i = 0; i < strlen(str); ++i) set << str[i]; return set; } charSet make_charset(const std::string& str) { charSet set; for(auto ch : str) set << ch; return set; }
true
6f218a296c40d41a020f14b37a85d50e3bd72996
C++
forgottencsc/ICPC
/Problems/repeatersVII/gen.cpp
UTF-8
1,257
2.6875
3
[]
no_license
#include <bits/stdc++.h> #include "../generator.h" using namespace std; void gen(int& id, const string& s, int t) { ofstream cout(to_string(++id) + ".in"); cout << s << endl << igr(t / 2, t) << endl; cout.close(); } void gen_batch(int& id, int n, int t) { gen(id, sqgp(n, "1111122211111", 0.001, '3', '5'), t); gen(id, sqgp(n, "1112111", 0.001, '3', '5'), t); gen(id, sqgp(n, "122221", 0.001, '3', '5'), t); gen(id, sqgp(n, "1145141919810", 0.001, '3', '5'), t); gen(id, sqgr(n, 0.01, '1', '2', '3'), t); gen(id, sqgr(n, 0.0001, '1', '2', '3'), t); gen(id, sqgr(n, 0.01, '1', '1', '1'), t); gen(id, sqgr(n, 0.01, '0', '1', '9'), t); gen(id, sgr(n, '0', '9'), t); gen(id, sgr(n, '0', '1'), t); gen(id, sgr(n, '1', '1'), t); } void solve(istream& cin, ostream& cout); int main(void) { ios::sync_with_stdio(0); cin.tie(0); #ifndef ONLINE_JUDGE ifstream cin("1.in"); #endif // ONLINE_JUDGE int id = 1; gen_batch(id, 100, 10000); gen_batch(id, 10000, 1000000); gen_batch(id, 1000000, 1000000000); for (int i = 1; i <= id; ++i) { ifstream cin(to_string(i) + ".in"); ofstream cout(to_string(i) + ".out"); solve(cin, cout); } return 0; }
true
5d20b3108ec8c1f232c622b2a15989a877b9e5de
C++
icerove/rosalind
/dna/main.cpp
UTF-8
746
3.25
3
[]
no_license
#include <iostream> #include <fstream> #include <string> #include <streambuf> void ComplementingStrandOfDNA(std::ifstream &input, std::ofstream &output) { // std::string str((std::istreambuf_iterator<char>(input)), // std::istreambuf_iterator<char>()); int result[20] = {0}; char c; while (input.good()) { input.get(c); if (input.fail()) break; result[c-'A']++; } output << result['A'-'A'] << ' ' << result['C'-'A'] << ' ' << result['G' - 'A'] <<' ' << result['T' - 'A']; } int main() { std::ifstream input("input.txt"); std::ofstream output("output.txt"); ComplementingStrandOfDNA(input, output); input.close(); output.close(); return 0; }
true
ead0083aa8502e4706ad6a24534927948683a98f
C++
Steve132/rs_led
/m_led/LedStripRS.cpp
UTF-8
484
3
3
[ "MIT" ]
permissive
#include <avr/pgmspace.h> uint32_t brighten(uint32_t color,uint8_t brightness) { uint32_t out=0; uint32_t r; r=color & 0xFF; r*=brightness; r>>=8; r++; out |= r; r=(color >> 8) & 0xFF; r*=brightness; r>>=8; r++; out |= r << 8; r=(color >> 16) & 0xFF; r*=brightness; r>>=8; r++; out |= r << 16; return out; } uint32_t slowdown(uint32_t delay,uint32_t sd) //fixed-point, 10 bit fraction. { uint32_t output=delay; output*=sd; output >>=10; return output; }
true
a06eabea0436b960142a69421c5bf14749e1dc77
C++
BCLab-UNM/Swarmathon-MC-Public
/src/hive/src/Cluster.cpp
UTF-8
2,285
3.40625
3
[]
no_license
#include "Cluster.h" Cluster::Cluster(std::string robotName, float clusterX, float clusterY, int numberOfRobots){ this->robotThatFoundCluster = robotName; assignedRobots.push_back(robotName); this->clusterX = clusterX; this->clusterY = clusterY; this->confirmCount = 0; this->notConfirmCount = 0; this->maxRobotsAssigned = 1; this->numberOfRobots = numberOfRobots; } //this method adds a confirm and calculates how many robots can work on a cluster void Cluster::addConfirm(){ this->confirmCount++; //if the amound of confirms can be divided by the amound of robots and we get a whole number if(confirmCount % numberOfRobots == 0){ //add more robots if we can if((int)(confirmCount/numberOfRobots) - numberOfRobots <= notConfirmCount){ if(maxRobotsAssigned < numberOfRobots) maxRobotsAssigned++; ROS_INFO("Adding confirm. Confirm count is: %d, numbers of robots is %d:", confirmCount, maxRobotsAssigned); } } } //if cluster has not been confirmed void Cluster::addUnconfirm(){ this->notConfirmCount++; //increase the not confirmed cound if(this->maxRobotsAssigned > 0){ //if the mas robot value is greater that 0 this->maxRobotsAssigned--; //reduce the robot count ROS_INFO("Adding unconfirm. Unconfirm count is %d, Confirm count is: %d, numbers of robots is %d:", notConfirmCount, confirmCount, maxRobotsAssigned); } //when max robot count hits 0 the hive will remove the cluster from its list } void Cluster::assignRobot(std::string robotName){ if(assignedRobots.size() < maxRobotsAssigned){ this->assignedRobots.push_back(robotName); ROS_INFO("Assigning robot %s:",robotName.c_str()); } } void Cluster::unassignRobot(std::string robotName){ if(this->robotThatFoundCluster != robotName){ //if it is not the robot that found the cluster for(int i = 0; i<assignedRobots.size(); i++){ //iterate through the robot list if((std::string)(assignedRobots[i]) == robotName){ //if robot name matches assignedRobots.erase(assignedRobots.begin() + i); //remove the robot ROS_INFO("Unassigning robot %s:",robotName.c_str()); } } } }
true
1139def2bb98cb853f553dc9ca500fd4291a44b8
C++
chandrarishabh/spoj-solutions
/POTHOLE.cpp
UTF-8
1,449
2.84375
3
[]
no_license
//FORD_FULKERSON MAX FLOW #include<bits/stdc++.h> #define debug(x) cout<<#x<<" = "<<x<<endl; using namespace std; int n,m; int graph[1000][1000]={0}; int paths[1000][1000]={0}; int parent[1000] = {0}; bool findpath(int s, int t) { bool visited[1000]; memset(visited,false,sizeof(visited)); queue<int> q; q.push(s); parent[s] = -1; visited[s]=true; while(!q.empty()) { int top = q.front(); q.pop(); if(top == t ) break; for(int i=1;i<=n;++i) { if(paths[top][i]>0 && visited[i]==false) { q.push(i); visited[i]=true; parent[i]=top; } } } return (visited[t]==true) ; } int ford(int s,int t) { for(int i=1;i<=n;++i) for(int j=1;j<=n;++j) paths[i][j]=graph[i][j]; int maxflow = 0; // debug("hello2"); while(findpath(s,t)) { // debug("hello3"); int minpath=INT_MAX; for(int i=t;i!=s;i=parent[i]) { int u = parent[i]; minpath = min(minpath,paths[u][i]); } for(int i=t;i!=s;i=parent[i]) { int u = parent[i]; paths[u][i] -= minpath; paths[i][u] += minpath; } maxflow += minpath; } return maxflow; } int main() { int t; cin>>t; while(t--) { memset(graph,0,sizeof(graph)); memset(paths,0,sizeof(paths)); memset(parent,0,sizeof(parent)); cin>>n; for(int i=1;i<=n-1;++i) { cin>>m; for(int j=0;j<m;++j) { int t; cin>>t; graph[i][t]=(i==1||t==n)?1:1000000; } } //debug("hello"); cout<<ford(1,n)<<endl; } }
true
de55823b0ece49aaea4377b23ef5a6b205e04b87
C++
PigGao/leetcode
/43-MultiplyStrings.cpp
UTF-8
817
2.875
3
[]
no_license
class Solution { public: string multiply(string num1, string num2) { int m = num1.length()-1; int n = num2.length()-1; int pos[m+n+2] = {0}; for(int i=m;i>=0;i--) for(int j=n;j>=0;j--) { int mul = (num1[i]-'0')*(num2[j]-'0'); int p1=i+j; int p2 = i+j+1; int sum = mul + pos[p2]; pos[p1] += sum/10; pos[p2] = sum%10; } string res=""; for(int p:pos) { if(p==0&&res.length()==0) { continue; } else { char c = '0'+p; res = res + c; } } return res.length()==0?"0":res; } };
true
49fecda96c94c2fd9462413a0f8aec23102ae3d3
C++
ayushkhanduri/dsa-algo
/Platforms/LeetCode/utils/LeetCode.hpp
UTF-8
1,213
3.6875
4
[]
no_license
#pragma once #include "iostream" #include "vector" using namespace std; class ListNode { public: int val; ListNode *next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode *next) : val(x), next(next) {} }; class Utility { public: static ListNode* createLLFromVector(vector<int> v) { int size = v.size(); if (!size) { ListNode* start = nullptr; return start; } ListNode* start = new ListNode(v.at(0)); ListNode* startCopy = start; for (int i = 1 ; i < v.size() ; i++) { ListNode* newNode = new ListNode(v.at(i)); startCopy -> next = newNode; startCopy = startCopy -> next; } return start; } static void travereLL (ListNode *node) { ListNode *startCopy = node; while (startCopy != nullptr) { cout << startCopy->val; startCopy = startCopy->next; } } static void swap_value(int from, int to, vector<int> &v) { int fromItem = v.at(from); v.at(from) = v.at(to); v.at(to) = fromItem; } static void print_vectors(vector<int> v) { cout << "["; for (int i = 0 ; i < v.size(); i ++ ) { cout << v.at(i); if (i != v.size() - 1) { cout << " , "; } } cout << "]" << endl; } };
true
28e58bfb4deebda568f496aa989ff2990023fb2c
C++
oguzhancevik/Cplusplus
/Dairenin Çevresini ve Alanını Bulma.cpp
UTF-8
477
3.203125
3
[]
no_license
#include <iostream> using namespace std; void main () { const float Pi = 3.14159; float YariCap; float Alan, Cevre; //1.Adim: YariCapi giriniz cout << "Dairenin yaricapinin giriniz ="; cin >> YariCap; //2.Adim: Alani hesapla Alan = Pi * YariCap * YariCap; //3.Adim: Cevreyi hesapla Cevre = 2 * Pi * YariCap; //4.Adim: Alani ve cevreyi yazdir cout << "Dairenin Alani = " << Alan << endl; cout << "Dairenin Cevresi = " << Cevre << endl; system("pause"); }
true
36868b38bbe421b8c28e950ac64fdd797bb5ef7b
C++
BurpTech/BurpStatus
/src/BurpStatus/Internal/Status.cpp
UTF-8
638
2.671875
3
[]
no_license
#include "Status.hpp" namespace BurpStatus { namespace Internal { void Status::set(Level level, Code code) { _level = level; _code = code; } const Status::Level Status::getLevel() const { return _level; } const Status::Code Status::getCode() const { return _code; } #define C_STR_LABEL "BurpStatus::Status" #define C_STR_CASE(CODE) BURP_STATUS_C_STR_CASE(C_STR_LABEL, CODE) #define C_STR_DEFAULT BURP_STATUS_C_STR_DEFAULT(C_STR_LABEL) const char * Status::c_str() const { switch (getCode()) { C_STR_CASE(ok); C_STR_DEFAULT; } } } }
true
0e7417b7e0f7fc020d1ec13bc2f9411a2dfc1db9
C++
iwtbam/leetcode
/code/lt剑指 Offer 61.cpp
UTF-8
752
2.890625
3
[]
no_license
// https://leetcode-cn.com/problems/bu-ke-pai-zhong-de-shun-zi-lcof/ // bu ke pai zhong de shun zi lcof class Solution { public: bool isStraight(vector<int>& nums) { int zero = 0, min_e = 13, max_e = 1; int size = nums.size(); unordered_set<int> set; for(int i = 0; i < size; i++){ if(nums[i] == 0){ zero++; continue; } if(set.count(nums[i])) return false; set.insert(nums[i]); min_e = min(min_e, nums[i]); max_e = max(max_e, nums[i]); } int len = max_e - min_e + 1; if(len > 5) return false; return len + zero >= 5; } };
true
13d29c97565e44c1a7f0ade573fb1e6d1e969a70
C++
sgalkin/CarND-T3P1
/src/protocol.cpp
UTF-8
1,177
3.25
3
[ "MIT" ]
permissive
#include "protocol.h" #include <cstring> #include <stdexcept> namespace { bool checkHeader(const std::string& request) { // "42" at the start of the message means there's a websocket message event. // The 4 signifies a websocket message. The 2 signifies a websocket event return request.length() > 2 && strncmp(request.data(), "42", 2) == 0; } } std::string WSProtocol::getPayload(std::string request) { if (!checkHeader(request)) { throw std::runtime_error("Unexpected message header"); } // Checks if the SocketIO event has JSON data. // If there is data the JSON object in string format will be returned, // else the empty string "" will be returned. auto b1 = request.find_first_of("["); auto b2 = request.find_last_of("]"); if (request.find("null") == std::string::npos && b1 != std::string::npos && b2 != std::string::npos) { return request.substr(b1, b2 - b1 + 1); } return ""; } std::string WSProtocol::formatResponse() { static const std::string manual = "42[\"manual\",{}]"; return manual; } std::string WSProtocol::formatResponse(std::string message) { return "42[\"control\"," + std::move(message) + "]"; }
true
ba7f30ccd572b6668076743d025319ba7804f6f6
C++
JagjitBhatia/PTU_Controller
/SerialAdapter.h
UTF-8
857
2.6875
3
[]
no_license
#ifndef SERIAL_H #define SERIAL_H // C library headers #include <iostream> #include <string.h> // Linux headers #include <fcntl.h> #include <errno.h> #include <termios.h> #include <unistd.h> #include <sys/file.h> class SerialAdapter { private: char* path; int flags; int conn; bool connected; int baud; speed_t toBaud(int rate); public: SerialAdapter(); SerialAdapter(char* path, int flags); SerialAdapter(char* path, int flags, int rate); ~SerialAdapter(); void setPath(char* path); void setFlags(int flags); void addFlag(int flag); void setRate(int rate); bool connect(); bool connect(int rate); void disconnect(); bool isConnected(); bool SerialWrite(char* buf, int size); bool SerialRead(int size, char* buf); bool SerialRead(char* &buf); char* SerialRead(int size); char* SerialRead(); }; #endif
true
1171f408fa6178322e94758d321ebfdd613f8f48
C++
pat-laugh/various-cpp
/various/smartIterator.hpp
UTF-8
1,823
3.375
3
[ "Apache-2.0" ]
permissive
//Copyright 2017 Patrick Laughrea //Licensed under the Apache License, Version 2.0 /* SmartIterator: wraps a stringstream object, providing a common interface to iterate both streams and strings. The class throws the exception ios_base::failure in case of a non-eof error. */ #pragma once #include <sstream> #include <string> namespace various { class SmartIterator { public: SmartIterator(SmartIterator&& it); SmartIterator(const SmartIterator& it) = delete; SmartIterator(std::stringstream&& in); SmartIterator(const std::stringstream& in) = delete; SmartIterator(std::string in); SmartIterator(std::streambuf* sb); SmartIterator& operator=(SmartIterator&& o); SmartIterator& operator=(const SmartIterator& o) = delete; SmartIterator& operator++(); //optimized equivalent of calling ++ twice SmartIterator& incTwo(); //the iterator must be good char operator*() const; bool good() const; bool end() const; //returns good() operator bool() const; bool operator!() const; //returns true if the iterator is good and it points to c, else false bool operator==(char c) const; bool operator!=(char c) const; //peek must be good char peek() const; bool peekGood() const; bool peekEnd() const; int getLine() const; //the current line (based on '\n'), 1-based index int getCharCount() const; //1-based index of currently pointed char on the current line private: std::stringstream in; char c1, c2; bool isValid = true, hasPeek = true; int line = 1, charCount = 0; void addLine(); //increases line and resets charCount to 0 void checkChar(char c); //if c is '\n', addLine(), else increases charCount void readStart(); //safely reads the next two chars on the stream void getPeek(); //safely reads the next char on the stream and assign peek }; }
true
d357b097a053e334b1bac3cfba466ea9bb91e205
C++
HyeongBinK/C_PlusPlus
/C++/학생정보관리시스템/Student.cpp
UHC
1,329
3.484375
3
[]
no_license
#include "Student.h" Student::Student() { } void Student::SetStudent(int Number) { int tmp; bool Pass = true; m_iNumber = Number+1; system("cls"); cout << m_iNumber << " л "<< endl; cout << "̸ : "; cin >> m_strName; cout << " : "; cin >> m_iAge; Pass = true; while (Pass) { cout << "г : "; cin >> tmp; m_eClass = (CLASS)tmp; switch (m_eClass) { case CLASS_1: case CLASS_2: case CLASS_3: Pass = false; break; default: cout << "߸ Էϼ̽ϴ.(1~3г )" << endl; break; } } Pass = true; while(Pass) { cout << " : "; cin >> tmp; m_eGender = (GENDER)tmp; switch (m_eGender) { case GENDER_MAN : case GENDER_WOMAN : Pass = false; break; default : cout << "߸ Էϼ̽ϴ.(0Ǵ 1 Է)" << endl; break; } } cout << m_eGender << endl; } void Student::ShowStudent() { cout << "====" << m_iNumber << " л====" << endl; cout << "̸ : " << m_strName << endl; cout << " : " << m_iAge << endl; cout << " : "; switch(m_eGender) { case GENDER_MAN : cout << "" << endl; break; case GENDER_WOMAN: cout << "" << endl; break; } cout << "г : " << m_eClass << endl; } Student::~Student() { }
true
147ef20356754142d97e3dd4e183ac8f0736c825
C++
kjanderson2/TopCoder
/ExerciseMachine.hpp
UTF-8
689
3.421875
3
[]
no_license
#include <iostream> #include <cmath> using namespace std; class ExerciseMachine{ private: int convertToSeconds(string time){ int answer = 0; string hoursString = time.substr(0,2); string minsString = time.substr(3,2); string secsString = time.substr(6,2); int hours = atoi(hoursString.c_str()); int mins = atoi(minsString.c_str()); int secs = atoi(secsString.c_str()); answer += secs; answer += mins*60; answer += hours*3600; return answer; } public: int getPercentages(string time){ int answer =0; int numSecs = convertToSeconds(time); for(int i=1; i<=numSecs; i++){ if(remainder((i*100),numSecs)==0){ answer += 1; } } return answer-1; } };
true
cf2389b11ac146779854ec6d69da041db1a20e73
C++
cpe-unr/group-project-pt48
/noisegate.cpp
UTF-8
1,222
3.046875
3
[]
no_license
//author: //date: //semester final project #include "noisegate.h" using namespace std; NoiseGate::NoiseGate(){ threshold = 100; } NoiseGate::NoiseGate(int threshold) : threshold(threshold){} void NoiseGate::processBuffer(unsigned char* buffer, int bufferSize){ Noisegate(buffer, bufferSize); } void NoiseGate::NoisegateStereo(unsigned char* buffer1 , unsigned char* buffer2, int buffers1, int buffers2){ NoisegateStereo(buffer1, buffer2, buffers1, buffers2); } void NoiseGate::Noisegate(unsigned char* buffer, int bufferSize){ for(int i = 0; i < bufferSize; i++){ if(buffer[i] > (uint8_t)128 - threshold && buffer[i] < (uint8_t)128 + threshold){ buffer[i] = (uint8_t)128; } } } void NoiseGate::processBufferStereo(unsigned char* buffer1, unsigned char* buffer2, int buffers1, int buffers2){ for(int i = 0; i < buffers1; i++){ if(buffer1[i] > (uint8_t)128 - threshold && buffer1[i] < (uint8_t)128 + threshold){ buffer1[i] = (uint8_t)128; } } for(int i = 0; i < buffers2; i++){ if(buffer2[i] > (uint8_t)128 - threshold && buffer2[i] < (uint8_t)128 + threshold){ buffer2[i] = (uint8_t)128; } } }
true
004a4422077b895dfae7939500d17cdaba869d59
C++
BigYvan/PAT-Basic-Level
/1081.cpp
UTF-8
938
2.703125
3
[]
no_license
#include <iostream> using namespace std; int main(int argc, const char * argv[]) { int n; cin >> n; getchar(); for (int i = 0; i < n; i++) { string temp; getline(cin, temp); if (temp.size() < 6) { printf("Your password is tai duan le.\n"); continue; } int numFlag = 0, alFlag = 0, luanFlag = 0; for (int j = 0; j < temp.size(); j++) { if (isalpha(temp[j])) alFlag = 1; if (temp[j] >= '0' && temp[j] <= '9') numFlag = 1; if (!isalpha(temp[j]) && !(temp[j] >= '0' && temp[j] <= '9') && temp[j] != '.') luanFlag = 1; } if (luanFlag == 1) printf("Your password is tai luan le.\n"); else if (numFlag == 0) printf("Your password needs shu zi.\n"); else if (alFlag == 0) printf("Your password needs zi mu.\n"); else printf("Your password is wan mei.\n"); } return 0; }
true
dab59bafd7c7633d7ca00fc5cd512ee07cdcb7b6
C++
pilipeikoko/Course2
/SDiIS/Lab3/TreetypeRepresentaionAndInterpretationOfArithmetical_task/tree_testing/tree_testing.cpp
UTF-8
6,816
2.90625
3
[]
no_license
#include "../Project3/Expression_tree.h" #include "../Project3/Assign_expression.h" #include "../Project3/Math_expression.h" #include "../Project3/Assign_expression.h" #include "CppUnitTest.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace Testingtree { TEST_CLASS(Testing_tree) { public: TEST_METHOD(single_positive_number_test1) { string line = "2"; Expression_tree tree; tree.build_tree(line); int result = tree.compute_value(); tree.delete_tree(); Assert::AreEqual(result, 2); } TEST_METHOD(single_positive_number_test2) { string line = "100"; Expression_tree tree; tree.build_tree(line); int result = tree.compute_value(); tree.delete_tree(); Assert::AreEqual(result, 100); } TEST_METHOD(single_negative_number_test1) { string line = "-2"; Expression_tree tree; tree.build_tree(line); int result = tree.compute_value(); tree.delete_tree(); Assert::AreEqual(result, -2); } TEST_METHOD(single_negative_number_test2) { string line = "-100"; Expression_tree tree; tree.build_tree(line); int result = tree.compute_value(); tree.delete_tree(); Assert::AreEqual(result, -100); } TEST_METHOD(operation_priority_test1) { string line = "2+2*2"; Expression_tree tree; tree.build_tree(line); int result = tree.compute_value(); tree.delete_tree(); Assert::AreEqual(result, 6); } TEST_METHOD(operation_priority_test2) { string line = "3*(2+2)+1*2"; Expression_tree tree; tree.build_tree(line); int result = tree.compute_value(); tree.delete_tree(); Assert::AreEqual(result, 14); } TEST_METHOD(sin_test1) { string line = "sin(0)"; Math_expression expression; int result = expression.compute_value(line); Assert::AreEqual(result, 0); } TEST_METHOD(sin_test2) { string line = "sin(1000-500*2)"; Math_expression expression; int result = expression.compute_value(line); Assert::AreEqual(result, 0); } TEST_METHOD(cos_test1) { string line = "cos(1)"; Math_expression expression; int result = expression.compute_value(line); Assert::AreEqual(result, 0); } TEST_METHOD(cos_test2) { string line = "cos(1000-500*2+1)"; Math_expression expression; int result = expression.compute_value(line); Assert::AreEqual(result, 0); } TEST_METHOD(sqrt_test1) { string line = "sqrt(4)"; Math_expression expression; int result = expression.compute_value(line); Assert::AreEqual(result, 2); } TEST_METHOD(sqrt_test2) { string line = "sqrt(840+1)"; Math_expression expression; int result = expression.compute_value(line); Assert::AreEqual(result, 29); } TEST_METHOD(tg_test) { string line = "tg(0)"; Math_expression expression; int result = expression.compute_value(line); Assert::AreEqual(result, 0); } TEST_METHOD(ctg_test) { string line = "ctg(1)"; Math_expression expression; int result = expression.compute_value(line); Assert::AreEqual(result, 0); } TEST_METHOD(log_test) { string line = "log(4)"; Math_expression expression; int result = expression.compute_value(line); //1 becouse int values Assert::AreEqual(result, 1); } }; TEST_CLASS(Testing_Assignemnt) { TEST_METHOD(assign_test_1) { Assign_expression assigment; string line = "a=5"; if (assigment.is_assgignment(line)) assigment.put_variables_into_kb(line); line = "a^2"; line = assigment.assign_variables(line); Assert::IsTrue(line == "5^2"); } TEST_METHOD(assign_test_2) { Assign_expression assigment; string line = "a=-5"; if (assigment.is_assgignment(line)) assigment.put_variables_into_kb(line); line = "a"; line = assigment.assign_variables(line); Assert::IsTrue(line == "-5"); } TEST_METHOD(assign_test_3) { Assign_expression assigment; string line = "a=b=5"; if (assigment.is_assgignment(line)) assigment.put_variables_into_kb(line); line = "a+b*a"; line = assigment.assign_variables(line); Assert::IsTrue(line == "5+5*5"); } TEST_METHOD(assign_test_4) { Assign_expression assigment; string line = "a=b=c=5"; if (assigment.is_assgignment(line)) assigment.put_variables_into_kb(line); line = "a+b+c"; line = assigment.assign_variables(line); Assert::IsTrue(line == "5+5+5"); } }; TEST_CLASS(Testing_unary_minus) { TEST_METHOD(unary_minus_test_1) { Expression_tree tree; string line = "-(-(-2))"; tree.build_tree(line); int result = tree.compute_value(); Assert::IsTrue(result == -2); } TEST_METHOD(unary_minus_test_2) { Expression_tree tree; string line = "-(-(20))"; tree.build_tree(line); int result = tree.compute_value(); Assert::IsTrue(result == 20); } TEST_METHOD(unary_minus_test_3) { Expression_tree tree; string line = "-(-(-2-3)+(-2)-3*3)"; tree.build_tree(line); int result = tree.compute_value(); Assert::IsTrue(result == 6); } TEST_METHOD(unary_minus_test_4) { Expression_tree tree; string line = "-(-3+3*2+3*(3-2^2))"; tree.build_tree(line); int result = tree.compute_value(); Assert::IsTrue(result == 0); } }; TEST_CLASS(Testing_math_calculations) { TEST_METHOD(division_test1) { Expression_tree tree; string line = "10/5"; tree.build_tree(line); int result = tree.compute_value(); Assert::AreEqual(result, 2); } TEST_METHOD(division_test2) { Expression_tree tree; string line = "(100/2)/5/2"; tree.build_tree(line); int result = tree.compute_value(); Assert::AreEqual(result, 5); } TEST_METHOD(multiplication_test1) { Expression_tree tree; string line = "100*12"; tree.build_tree(line); int result = tree.compute_value(); Assert::AreEqual(result, 1200); } TEST_METHOD(multiplication_test2) { Expression_tree tree; string line = "2*3*(4*5)*2*1"; tree.build_tree(line); int result = tree.compute_value(); Assert::AreEqual(result, 240); } TEST_METHOD(sum_test1) { Expression_tree tree; string line = "2+22"; tree.build_tree(line); int result = tree.compute_value(); Assert::AreEqual(result, 24); } TEST_METHOD(sum_test2) { Expression_tree tree; string line = "2+3+3+22"; tree.build_tree(line); int result = tree.compute_value(); Assert::AreEqual(result, 30); } TEST_METHOD(subtraction_test1) { Expression_tree tree; string line = "100-12"; tree.build_tree(line); int result = tree.compute_value(); Assert::AreEqual(result, 88); } TEST_METHOD(subtraction_test2) { Expression_tree tree; string line = "120-12-(-10-3-3-1)"; tree.build_tree(line); int result = tree.compute_value(); Assert::AreEqual(result, 125); } }; }
true
e2818d4228aed89fce8dffe0a603269fff8caf46
C++
cms-sw/cmssw
/DetectorDescription/Core/interface/DDMap.h
UTF-8
1,848
3.0625
3
[ "Apache-2.0" ]
permissive
#ifndef DD_DDMap_h #define DD_DDMap_h #include <iostream> #include <map> #include <memory> #include <string> #include "DetectorDescription/Core/interface/DDReadMapType.h" #include "DetectorDescription/Core/interface/DDBase.h" #include "DetectorDescription/Core/interface/DDName.h" class DDMap; //! output operator for printing ... std::ostream& operator<<(std::ostream& o, const DDMap& cons); //! simply a std::map<std::string,double> supporting an addional operator[] const using dd_map_type = ReadMapType<double>; //! a named constant corresponding to the DDL-XML tag <Constant> and <ConstantsVector> class DDMap : public DDBase<DDName, std::unique_ptr<dd_map_type> > { public: //! the type of the managed object using value_type = dd_map_type; //! size type for the size of the stored values using size_t = dd_map_type::size_type; //! an uninitialized constant; one can assign an initialized constant to make it valid DDMap(); //! a refenrence to a constant DDMap(const DDName& name); //! creation of a new named constant; if it already existed with the given name, it's overwritten with new values DDMap(const DDName& name, std::unique_ptr<dd_map_type> value); //! the size of the array of values size_t size() const { return rep().size(); } //! the stored values const dd_map_type& values() const { return rep(); } //! returns the value on position pos; does not check boundaries! const double& operator[](const std::string& name) const { const dd_map_type& r(rep()); return r[name]; } //! read-only iterator pointing to the begin of the stored values value_type::const_iterator mapBegin() const { return rep().begin(); } //! read-only iterator poining one place after the stored values value_type::const_iterator mapEnd() const { return rep().end(); } }; #endif // DD_DDMap_h
true
0701d2921ea649cdfa4dc44f4784f9d366aded12
C++
jbienias/Studies
/Algorytmy numeryczne/Grzybobranie/Source.cpp
UTF-8
3,130
2.6875
3
[]
no_license
#include <iostream> #include <iomanip> #include <fstream> #include <time.h> #include <stdlib.h> #include <ctime> #include <string> #include <windows.h> #include <Eigen/Dense> #include <Eigen/SparseLU> /* Barzowska Monika, 238143 * Bienias Jan, 238201 */ using namespace std; using namespace Eigen; #define CSVName "eigenoutput.csv" streamsize ss = std::cout.precision(); MatrixXd loadMatrix(string filename) { fstream myfile(filename, ios_base::in); int rows; int columns; myfile >> rows; myfile >> columns; MatrixXd matrix(rows, columns); for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { myfile >> matrix(i, j); } } return matrix; } SparseMatrix<double> loadMatrixSparse(string filename, VectorXi vector) { fstream myfile(filename, ios_base::in); int rows; int columns; myfile >> rows; myfile >> columns; SparseMatrix<double> matrix(rows, columns); matrix.reserve(vector); for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { double tmp; myfile >> tmp; if (tmp != 0) { // 0.0 matrix.insert(i, j) = tmp; } } } return matrix; } VectorXi sumOfNonZeroElements(MatrixXd matrix) { int mRows = matrix.rows(); int mCols = matrix.cols(); VectorXi vector(mCols); int counter = 0; for (int j = 0; j < mCols; j++) { counter = 0; for (int i = 0; i < mRows; i++) { if (matrix(i, j) != 0.0) counter++; } vector(j) = counter; } return vector; } void createCSV() { ofstream myfile; myfile.open(CSVName); myfile << "size;wynik_partialPivLU;wynik_SparseLU;czas_partialPivLU;czas_SparseLU\n"; myfile.close(); } void appendToCSV(string filename, int a, double b, double c, double d, double e) { fstream myfile; myfile.open(filename, fstream::app); myfile << fixed << setprecision(15) << a << ";" << b << ";" << c << ";" << fixed << setprecision(0)<< d << ";" << e << "\n"; myfile.close(); } void info() { srand((unsigned int)time(0)); clock_t start; clock_t end; MatrixXd matrix = loadMatrix("matrix.txt"); printf("Matrix normal loaded\n"); int matrixSize = matrix.rows(); VectorXi vectorOfNonZeroElem = sumOfNonZeroElements(matrix); printf("Non zero calculated\n"); SparseMatrix<double> matrixSparse = loadMatrixSparse("matrix.txt", vectorOfNonZeroElem); SparseLU<Eigen::SparseMatrix<double> > solverA; matrixSparse.makeCompressed(); solverA.analyzePattern(matrixSparse); solverA.factorize(matrixSparse); printf("Matrix sparse loaded\n"); VectorXd vector = loadMatrix("vector.txt"); printf("Vector normal loaded\n"); VectorXd vectorSparse = loadMatrix("vector.txt"); printf("Vector sparse loaded\n"); start = clock(); VectorXd resultVectorOfPivLU = matrix.partialPivLu().solve(vector); end = clock(); double pivLUTime = (double(end - start) / CLOCKS_PER_SEC) * 1000; start = clock(); VectorXd resultVectorOfSparseLU = solverA.solve(vectorSparse); end = clock(); double SparseLUTime = (double(end - start) / CLOCKS_PER_SEC) * 1000; appendToCSV(CSVName, matrixSize, resultVectorOfPivLU[0], resultVectorOfSparseLU[0], pivLUTime, SparseLUTime); cout << "DONE" << endl; } int main() { info(); return 0; }
true
e5a27ddbcf5cb9d359b8286634487883594c3e97
C++
Pixelzzz99/SashaVersionV2
/Files/Generator.cpp
UTF-8
699
2.9375
3
[]
no_license
#include "Generator.h" Generator::Generator() { srand(RAND_MAX); //srand(time(nullptr)); _new_n = random(MIN, MAX); int temp_P = random(MIN, MAX); if ((temp_P / 10) == 0) { _new_P = (double)temp_P / 10; } else { _new_P = (double)temp_P / 100; } } Generator::Generator(int N, int P, int M) { this->_new_n = N; this->_new_P = P; this->_new_M = M; } int Generator::getNewN() { return _new_n; } double Generator::getNewP() { return _new_P; } int Generator::getNewM() { return _new_M; } int Generator::random(int MIN, int MAX) { static const double fraction = 1.0 / (static_cast<double>(RAND_MAX) + 1.0); return static_cast<int>(rand() * fraction * (MAX - MIN + 1) + MIN); }
true
04a3771f53af72b038bb0873475b79fb1d7b2938
C++
nadezhdagub/cpp-labs-1st-sem
/gubenko.nadezhda/A3/main.cpp
UTF-8
2,058
3.25
3
[]
no_license
#include <iostream> #include <stdexcept> #include "rectangle.hpp" #include "circle.hpp" #include "composite-shape.hpp" using namespace gubenko; int main() { try { auto r = std::make_shared <Rectangle> (point_t {20.0, 25.0}, 9.0, 11.0); std::cout << "Creating Rectangle x=20, y=25, w=9, h=11" << std::endl; std::cout << *r << std::endl; std::cout << "Moving Rectangle by dx=3, dy=8" << std::endl; r -> move(3, 8); std::cout << "coordinates (" << r -> getFrameRect().pos.x << ", "<< r -> getFrameRect().pos.y << ") " << std::endl; std::cout << "Moving Rectangle to point x=33.41, y=15.41" << std::endl; r -> move({33.41, 15.41}); std::cout << "coordinates (" << r -> getFrameRect().pos.x << ", "<< r -> getFrameRect().pos.y << ") " << std::endl; std::cout << "scaled rectangle" << std::endl; r -> scale(2); std::cout << "scaling width and height (" << r -> getFrameRect().width << ", "<< r -> getFrameRect().height << ") " << std::endl; auto c = std::make_shared <Circle> (point_t {10.0, 14.0}, 2.0); std::cout << "Creating Circle x=10.0, y=14.0, r=2" << std::endl; std::cout << *c << std::endl; std::cout << "Moving Circle by dx=4, dy=7" << std::endl; c -> move(4, 7); std::cout << "coordinates (" << c -> getFrameRect().pos.x << ", "<< c -> getFrameRect().pos.y << ") " << std::endl; std::cout << "Moving Circle to point x=10.21, y=8.51" << std::endl; c -> move({10.21, 8.51}); std::cout << " coordinates (" << c -> getFrameRect().pos.x << ", "<< c -> getFrameRect().pos.y << ") " << std::endl; std::cout << "scaled circle" << std::endl; c -> scale(3); std::cout << "scaling width and height (" << c -> getFrameRect().width << ", "<< c -> getFrameRect().height << ") " << std::endl; CompositeShape s(r); std::cout << "Composite Shape created" << std::endl; s.addShape(c); std::cout << s << std::endl; } catch (const std::invalid_argument &e) { std::cerr << e.what() << std::endl; return 1; } return 0; }
true
09369fe94f58669c035c5aa6785d9baf9f21dded
C++
aaronyoo/wine
/src/lib/string.cpp
UTF-8
546
3.171875
3
[]
no_license
#include "string.hpp" String::String(const char* s) { size = strlen(s); value = (char*) memory::halloc(size); memcpy(value, s, size); } String::String() { size = 0; } String::~String() { memory::free(value); } String& String::operator=(const String& rhs) { memory::free(value); size = strlen(rhs.value); value = (char*) memory::halloc(size); memcpy(value, rhs.value, size); // TODO: it seems unclear if I should free the rhs help me return *this; } char* String::get_value() { return value; }
true
6aaf4d72dfda490ab9850b1b82ce3e49572cca8f
C++
Gullern/tdt4102_cpp
/oving08/shapes.cpp
UTF-8
2,189
3.4375
3
[]
no_license
#include "shapes.h" #include <iostream> /* Shape */ Shape::Shape(const Color &color) : color(color) { } /* Line */ Line::Line(unsigned int startX, unsigned int startY, unsigned int endX, unsigned int endY, const Color &color) : Shape(color), startX(startX), startY(startY), endX(endX), endY(endY) { } void Line::doDraw(Image &image) const { if (startX >= image.getWidth() || startY >= image.getHeight()) { return; } unsigned int ex = endX < image.getWidth() ? endX : image.getWidth(); unsigned int ey = endY < image.getHeight() ? endY : image.getHeight(); if (1.0 * (endY - startY) / (endX - startX) > 1) { for (unsigned int y = startY; y < ey; y++) { image.setColor(xValue(y), y, getColor()); } } else { for (unsigned int x = startX; x < ex; x++) { image.setColor(x, yValue(x), getColor()); } } } /* Rectangle */ Rectangle::Rectangle(const Line &diagonal) : Shape(diagonal.getColor()), diagonal(diagonal) { //Uses color from line } Rectangle::Rectangle(const Line &diagonal, const Color &color) : Shape(color), diagonal(diagonal) { //Custom color, leaves line color untouched } void Rectangle::doDraw(Image &image) const { Line left(diagonal.getStartX(), diagonal.getStartY(), diagonal.getStartX(), diagonal.getEndY(), getColor()); Line right(diagonal.getEndX(), diagonal.getStartY(), diagonal.getEndX(), diagonal.getEndY(), getColor()); Line top(diagonal.getStartX(), diagonal.getEndY(), diagonal.getEndX(), diagonal.getEndY(), getColor()); Line bottom(diagonal.getStartX(), diagonal.getStartY(), diagonal.getEndX(), diagonal.getStartY(), getColor()); left.draw(image); right.draw(image); top.draw(image); bottom.draw(image); } /* Circle */ Circle::Circle(unsigned int centerX, unsigned int centerY, unsigned int radius, const Color &color) : Shape(color), centerX(centerX), centerY(centerY), radius(radius) { } void Circle::doDraw(Image &image) const { double margin = 0.1; double diff = 0; for (unsigned int y = 0; y < image.getHeight(); y++) { for (unsigned int x = 0; x < image.getWidth(); x++) { diff = radiusValue(x, y) - radius; if (diff * diff < margin) { image.setColor(x, y, getColor()); } } } };
true
4bcdca35f64341b0860dc644211d59d402bcb7b0
C++
Pseudocode-Team/pseudocode
/src/utils.h
UTF-8
614
3.390625
3
[ "MIT" ]
permissive
#pragma once #include <iostream> void print(std::string message) { std::cout << message << std::endl; } void print(int message) { std::cout << message << std::endl; } #include <string> template <class Container> void split(const std::string& str, Container& cont, char delim = ' '){ std::size_t current, previous = 0; current = str.find(delim); while (current != std::string::npos) { cont.push_back(str.substr(previous, current - previous)); previous = current + 1; current = str.find(delim, previous); } cont.push_back(str.substr(previous, current - previous)); }
true
46b29081015e781b64c5c4afed7f6907d74164f7
C++
p-lots/codewars
/7-kyu/tv-remote/c++/solution.cpp
UTF-8
1,146
2.890625
3
[]
no_license
#include <map> #include <utility> #include <vector> using namespace std; const vector<vector<char> > lookup_table = { { 'a', 'b', 'c', 'd', 'e', '1', '2', '3' }, { 'f', 'g', 'h', 'i', 'j', '4', '5', '6' }, { 'k', 'l', 'm', 'n', 'o', '7', '8', '9' }, { 'p', 'q', 'r', 's', 't', '.', '@', '0' }, { 'u', 'v', 'w', 'x', 'y', 'z', '_', '/' } }; void make_lookup_map(map<char, pair<int, int> > &m) { for (unsigned i = 0; i < lookup_table.size(); i++) { for (unsigned j = 0; j < lookup_table[i].size(); j++) { m[lookup_table[i][j]] = make_pair(i, j); } } } int tv_remote(const string &word) { map<char, pair<int, int> > lookup_map; make_lookup_map(lookup_map); char prev_letter = 'a'; int ret = 0; for (const auto &c : word) { auto prev_letter_pair = lookup_map[prev_letter]; auto curr_letter_pair = lookup_map[c]; int dist = (abs(prev_letter_pair.first - curr_letter_pair.first) + abs(prev_letter_pair.second - curr_letter_pair.second)); ret += dist + 1; prev_letter = c; } return ret; }
true
9e9df32e173688257bb36d637571e6dfb853688c
C++
putnampp/clotho-dev
/include/utility/memory/impl/event_page_walker.2.hpp
UTF-8
2,959
2.953125
3
[ "BSD-2-Clause-Views", "BSD-2-Clause" ]
permissive
#ifndef EVENT_PAGE_WALKER_2_HPP_ #define EVENT_PAGE_WALKER_2_HPP_ #include <cassert> #include <iostream> // Forward Iterator for walking events in page relative object order // template < class EP > class EventPageWalker { public: typedef EP event_page_t; typedef typename event_page_t::event_node event_node_t; typedef typename event_page_t::rb_node object_node_t; typedef typename event_page_t::event_t event_t; typedef typename event_page_t::object_t object_t; typedef event_t & event_reference; typedef event_t * event_pointer; typedef object_t object_reference; EventPageWalker( event_page_t * page = NULL, object_node_t * s = NULL, object_node_t * e = NULL) : m_page(page), m_obj( ((s == NULL )? ((page != NULL) ? page->head_object() : NULL ) : s) ), m_stop_obj( ((e == NULL ) ? ((page != NULL) ? page->end_object() : NULL ) : e) ), m_en( ((m_obj != NULL )? m_obj->onode.events : NULL )), m_bObjectChange(m_obj != m_stop_obj) { } EventPageWalker( const EventPageWalker< EP > & epw ) : m_page( epw.m_page ), m_obj( epw.m_obj ), m_stop_obj( epw.m_stop_obj ), m_en( epw.m_en ), m_bObjectChange( epw.m_bObjectChange ) { } EventPageWalker< EP > & operator++() { if( m_page != NULL ) { if( m_en->next == NULL ) { // transition to next object with an event do { if( ++m_obj >= m_stop_obj ) { m_en = NULL; m_page = NULL; m_obj = NULL; break; } m_en = m_obj->onode.events; } while( m_en == NULL ); m_bObjectChange = true; } else { m_en = m_en->next; m_bObjectChange = false; } } return *(this); } bool operator!=( const EventPageWalker< EP > & rhs ) const { return !(operator==(rhs)); } bool operator==( const EventPageWalker< EP > & rhs ) const { return m_page == rhs.m_page && m_obj == rhs.m_obj && m_en == rhs.m_en; } bool HasObjectChanged() const { return m_bObjectChange; } EventPageWalker< EP > & operator=( const EventPageWalker< EP > & rhs ) { if( this != &rhs ) { m_page = rhs.m_page; m_obj = rhs.m_obj; m_stop_obj = rhs.m_stop_obj; m_en = rhs.m_en; } return *(this); } event_pointer getEvent() { return m_en->p_event; } object_reference getObjectID() { return m_obj->onode.object_id; } virtual ~EventPageWalker() { } protected: event_page_t * m_page; object_node_t * m_obj, *m_stop_obj; event_node_t * m_en; bool m_bObjectChange; }; #endif // EVENT_PAGE_WALKER_2_HPP_
true
0d7dbb98b376db71ba92ae7a72f030a038814e95
C++
iampkuhz/OnlineJudge_cpp
/leetcode/cpp/PassedProblems/MaximumDepthofBinaryTree.cpp
UTF-8
1,826
3.578125
4
[]
no_license
/* * MaximumDepthofBinaryTree.cpp * * Created on: Mar 24, 2015 * Author: hanzhe */ #include <iostream> #include <vector> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; /** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int maxDepth(TreeNode *root) { if(root == NULL) return 0; vector<TreeNode*> rLevel; rLevel.push_back(root); vector<TreeNode*> nLevel; int level = 0; while(rLevel.size() > 0) { int size = rLevel.size(); //cout << level << ":" << size << endl; // 2. make next level nLevel.clear(); for(int i = 0 ; i < size; i ++) { TreeNode * p = rLevel[i]; if(p->left != NULL) { nLevel.push_back(p->left); } if(p->right != NULL) { nLevel.push_back(p->right); } } rLevel.clear(); rLevel.insert(rLevel.end(), nLevel.begin(), nLevel.end()); level ++; } return level; } void test() { cout << maxDepth(NULL) << endl; TreeNode * a = new TreeNode(3); cout << maxDepth(a) << endl; TreeNode * b = new TreeNode(1); TreeNode * c = new TreeNode(3); a->left = b; a->right = c; cout << maxDepth(a) << endl; TreeNode * d = new TreeNode(7); TreeNode * e = new TreeNode(2); cout << maxDepth(a) << endl; TreeNode * f = new TreeNode(5); TreeNode * g = new TreeNode(-1); b->left = d; b->right = e; c->left = f; c->right = g; cout << maxDepth(a) << endl; } };
true
e3627c15cbc7ea5ee68cca3776d5f38e971403be
C++
AStepanyan21/AbstractScript
/AbstractScript/Parser.h
UTF-8
3,592
2.953125
3
[]
no_license
#ifndef PARSER_H #define PARSER_H #include <iostream> #include <stdint.h> #include <fstream> #include <codecvt> #include <fstream> #include <sstream> #include <string> #include <regex> #include <vector> using varTab = std::vector<std::string>; struct Alias{ std::wstring arm; std::wstring eng; }; class Parser { private: varTab commands; std::vector<varTab> splitting_commands; std::wstring findToken(std::wstring& code, const std::wstring& arm, const std::wstring& eng) { size_t nPos; nPos = code.find(arm); if (nPos != std::string::npos) { return code.replace(nPos, arm.length(), eng); } return code; } std::wstring translate(std::wstring code) { Alias Var; Var.arm = L"փոփ"; Var.eng = L"VAR"; Alias If; If.arm = L"եթե"; If.eng = L"IF"; Alias Print; Print.arm = L"տպել"; Print.eng = L"PRINT"; Alias While; While.arm = L"երբ"; While.eng = L"WHILE"; Alias EndIf; EndIf.arm = L"ապա-վերջ"; EndIf.eng = L"ENDIF"; Alias End; End.arm = L"վերջ"; End.eng = L"END"; code = findToken(code, Var.arm, Var.eng); code = findToken(code, If.arm, If.eng); code = findToken(code, Print.arm, Print.eng); code = findToken(code, While.arm, While.eng); code = findToken(code, EndIf.arm, EndIf.eng); code = findToken(code, End.arm, End.eng); return code; } std::wstring readFile(const char* filename) { std::wifstream wif(filename); std::wstring code; wif.imbue(std::locale(std::locale(), new std::codecvt_utf8<wchar_t>)); std::wstringstream wss; wss << wif.rdbuf(); code = this->translate(wss.str()); return code; } varTab splitting(std::string text){ varTab commands; std::string intermediate; std::stringstream check1(text); while(std::getline(check1, intermediate, ';')){ commands.push_back(intermediate); } return commands; } varTab splitCommand(std::string s){ std::regex reg("\\s*(\")|(([a-zA-Z]+)(\\d*)|[+*/-])|([0-9]+).([0-9]+)|([0-9]+)|!=|<=|>=|==|[=]|<|>|%\\s*"); varTab v; std::sregex_token_iterator iter(s.begin(), s.end(), reg, 0); std::sregex_token_iterator end; while(iter != end){ v.push_back(*iter); ++iter; } return v; } std::vector<varTab> parsingCommands(varTab command){ std::vector<varTab> splitting_commands; for(int i = 0; i < command.size(); i++){ splitting_commands.push_back(this->splitCommand(command[i])); } return splitting_commands; } std::string delete_tabs_and_newline(std::string& line){ std::regex reg("\n|\t"); std::string text = "" ; text = std::regex_replace(line, reg, ""); return text; } void parsing(char* filename) { std::wstring uCode = this->readFile(filename); std::string all_code(uCode.begin(), uCode.end()); std::string code = this->delete_tabs_and_newline(all_code); this->commands = this->splitting(code); this->splitting_commands = this->parsingCommands(this->commands); } public: Parser(char* filename) { this->parsing(filename); } std::vector<varTab> getCommands(){ return this->splitting_commands; } }; #endif
true
c0ac34db6c9c7ca076b79773b40ab264f039c324
C++
Mu-Ahmad/OOP-CMP-244-241
/Lecture Codes/Lecture 13/Lec13_4_4.cpp
UTF-8
746
3.375
3
[]
no_license
#include <iostream> #include <fstream> using namespace std; class RationalNumber{ int x, y; public: RationalNumber(int x=0, int y=1){ //Both parameterized and Non-parameterized constructor set(x, y); } void set(int x=0, int y=1){ if (y==0) y = 1; if ((x < 0 && y < 0) || (x >=0 && y < 0)){ x=-x; y=-y; } this->x = x; this->y = y; } int getX() const { return x; } int getY() const { return y; } }; bool operator > (RationalNumber &r1, RationalNumber &r2){ cout << "Operator Called\n"; return true; } /*RationalNumber& operator > (RationalNumber &r1, RationalNumber &r2){ cout << "Operator Called\n"; return r1; }*/ int main(){ RationalNumber r1, r2(3,-4), r3(-4, -5), r4(-5,4); r1 > r2; //r1 > r2 > r3; return 0; }
true
3f1647e8f1bd3ef6837553c01848a1b33ab198b1
C++
Arkrissym/Discord.CPP
/Discord.C++/static.cpp
UTF-8
1,304
2.75
3
[ "MIT" ]
permissive
#include "static.h" #include <boost/certify/https_verification.hpp> #include <string> #include <vector> void hexchar(unsigned char c, unsigned char& hex1, unsigned char& hex2) { hex1 = c / 16; hex2 = c % 16; hex1 += hex1 <= 9 ? '0' : 'a' - 10; hex2 += hex2 <= 9 ? '0' : 'a' - 10; } std::string urlencode(std::string s) { const char* str = s.c_str(); std::vector<char> v(s.size()); v.clear(); for (size_t i = 0, l = s.size(); i < l; i++) { char c = str[i]; if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '-' || c == '_' || c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || c == ')') { v.push_back(c); } else if (c == ' ') { v.push_back('+'); } else { v.push_back('%'); unsigned char d1, d2; hexchar(c, d1, d2); v.push_back(d1); v.push_back(d2); } } return std::string(v.cbegin(), v.cend()); } void load_ssl_certificates(boost::asio::ssl::context& ssl_context) { #if defined(_WIN32) || defined(__APPLE__) boost::certify::enable_native_https_server_verification(ssl_context); #else ssl_context.set_default_verify_paths(); #endif }
true
c65766bb35203fea91f8590ab773003688cd25ab
C++
jason967/algorithm
/Algo/2961.cpp
UTF-8
784
2.578125
3
[]
no_license
#include<cstdio> #include<vector> #include<algorithm> #define pii pair<int,int> using namespace std; const int INF = 1e9; int N; bool used[10]; int sel[10]; int ans = INF; vector<pii> v; void go(int cnt, int idx,int target) { if (cnt == target) { int S = 1; int B = 0; for (int i = 0; i < cnt; i++) { S *= v[sel[i]].first; B += v[sel[i]].second; } int diff = abs(S - B); if (ans > diff) ans = diff; return; } for (int i = idx; i < N; i++) { if (used[i]) continue; sel[cnt] = i; used[i] = true; go(cnt + 1, i, target); used[i] = false; } } int main() { scanf("%d", &N); for (int i = 0; i < N; i++) { int a, b; scanf("%d %d", &a, &b); v.push_back({ a,b }); } for (int i = 1; i <= N; i++) { go(0, 0, i); } printf("%d", ans); }
true
7fac9f30fca646c98906d3e52892019e010b2785
C++
MarkFSchneider/assignment4
/Mean.cpp
UTF-8
214
2.765625
3
[]
no_license
#include "Mean.h" using namespace std; Mean::Mean() { sum = 0; count = 0; } Mean::~Mean() { } void Mean::addElement(int d) { count++; sum+=d; } float Mean::calculate() { return (float)sum / count; }
true
a00b3e7572d21763c8c2ad51157f05173634cd96
C++
rodriguesfas/Cron
/cronos_serv/src_arduino/cronos/cronos.ino
UTF-8
2,742
2.953125
3
[ "MIT" ]
permissive
/** * **************************************************************************** Sofware: Cronos Descricion: Versino: 0.0.1 Date: 02 de junho de 2016 By; RodroguesFAS Contact: <http:/rodriguesfas.com.br> || <franciscosouzaacer@gmail.com> * **************************************************************************** */ #include <NewPing.h> #include <ThreadController.h> #include <Thread.h> #include <LiquidCrystal.h> // initialize the library with the numbers of the interface pins LiquidCrystal lcd(13, 12, 11, 10, 9, 8); /* Utilizado para configurar o sonar. */ #define MAX_DISTANCE 60 /* Distancia Máxima realizada pelo ping (em centimetros). distancis Máxima que o sensor verifica é 500cm, acima disso mutio erro nas leituras. */ /* NewPing configura os pinosde envio, recebimento, e distancia máxima. */ NewPing sonarBegin(3, 2, MAX_DISTANCE); NewPing sonarEnd(5, 4, MAX_DISTANCE); /* Declara uma thread "raiz ou mãe" um controle que agrupa as thread's filhas.. */ ThreadController cpu; /* Declara os objetos ultrasônico do tipo Thread's.. */ Thread threadSonarBegin; Thread threadSonarEnd; /** setup - */ void setup() { Serial.begin(9600); // set up the LCD's number of columns and rows: lcd.begin(20, 4); // Print a message to the LCD. lcd.setCursor(3, 0); lcd.print("II ROBOTS 2016"); /* Configura as Threads dos Objetos.. */ threadSonarBegin.setInterval(33); /* Define o tempo em que irá ser executada a thread.. */ threadSonarBegin.onRun(readPingSonarBegin); /* Define qual função irá ser execultada pela thread.. */ threadSonarEnd.setInterval(33); threadSonarEnd.onRun(readPingSonarEnd); /* Adiciona as thread's filhas a thread raiz ou mãe.. */ cpu.add(&threadSonarBegin); cpu.add(&threadSonarEnd); } /** loop - */ void loop() { /* Start a thread raiz.. */ cpu.run(); } /** readPingSonarBegin - */ void readPingSonarBegin() { unsigned int uS = sonarBegin.ping(); /* Enviar ping, recebe ping tempo em microsegundos (uS). */ uS = uS / US_ROUNDTRIP_CM; /* Converte ping tempo para uma distância e centimetros cm. */ if (uS > 3 && uS <= 12) { lcd.setCursor(1, 2); lcd.clear(); lcd.print("ROBO ENTROU!"); Serial.println(1); // Entrou robo no labirinto } //Serial.print("Sonar1: "); //Serial.print(uS); //Serial.print("cm"); //Serial.println(" "); } /** readPingSonarEnd - */ void readPingSonarEnd() { unsigned int uS = sonarEnd.ping(); uS = uS / US_ROUNDTRIP_CM; if (uS > 3 && uS <= 12) { lcd.setCursor(1, 2); lcd.clear(); lcd.print("ROBO SAIU!"); Serial.println(0); // Saiu robo do labirinto } //Serial.print("Sonar2: "); //Serial.print(uS); //Serial.print("cm"); //Serial.println(" "); }
true
1bed8ed4c509bc66aea52dc12ece26e621e2b5da
C++
fake-888/Ejercicios-lab3
/Tarea6/SeccionList.cpp
UTF-8
1,715
3.359375
3
[]
no_license
#include "SeccionLista.h" #include <iostream> #include <conio.h> #include <stdio.h> #include <string.h> using namespace std; SeccionLista::SeccionLista() : primero(nullptr) { } bool SeccionLista::estaVacia() { return primero == nullptr; } void SeccionLista::agregarAlumno(char* nombre1, float nota1) { AlumnoNodo* nuevo = new AlumnoNodo(nombre1, nota1, nullptr); if (estaVacia()) { primero = nuevo; } else { AlumnoNodo* actual = primero; bool flag = true; while (actual->getSiguiente() != nullptr) { if ((strcmp(nombre1, actual->getNombre()) > 0) && (strcmp(actual->getSiguiente()->getNombre(), nombre1) > 0)) { nuevo->setSiguiente(actual->getSiguiente()); actual->setSiguiente(nuevo); flag = false; } else { actual = actual->getSiguiente(); } } if (flag) { if (actual->getNombre() == primero->getNombre()) { if (strcmp(actual->getNombre(), nombre1) > 0) { nuevo->setSiguiente(actual); primero = nuevo; } else { actual->setSiguiente(nuevo); } } else actual->setSiguiente(nuevo); } } } void SeccionLista::listarSeccion() { AlumnoNodo* actual = primero; while (actual != nullptr) { cout << "Nombre: " << actual->getNombre() << "\nNota: " << actual->getNota() << "\n"; actual = actual->getSiguiente(); } cout << "\n"; } int SeccionLista::cantidadAprobados() { AlumnoNodo* actual = primero; int aprobados = 0; while (actual != nullptr) { if (actual->getNota() > 70) { aprobados++; actual = actual->getSiguiente(); } else { actual = actual->getSiguiente(); } } return aprobados; }
true
c53a5500dcc54709bd283aaf079eb0e079751902
C++
milon/UVa
/Volume-4/UVa_486.cpp
UTF-8
2,031
2.859375
3
[]
no_license
//UVa Problem-486(English-Number Translator) //Accepted //Running time: 0.012 sec //Author: Milon #include<cstdio> #include<cstring> #include<cctype> using namespace std; char sign[25]="negative"; char digit[20][25] = { "zero", "one", "two", "three", "four","five", "six", "seven", "eight", "nine", "ten","eleven", "twelve","thirteen", "fourteen", "fifteen", "sixteen", "seventeen","eighteen", "nineteen"}; char power[8][25] = { "twenty", "thirty", "forty", "fifty","sixty", "seventy", "eighty", "ninety"}; char ppp[25]="hundred"; char super[2][25]={"thousand", "million" }; long int digit_1[20]={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19}; long int power_1[11]={20,30,40,50,60,70,80,90}; long int ppp_1=100; long int super_1[2]={1000,1000000}; int solution(char *s){ char temp[20][25]; int i,j,k; long int num = 0; i=0; j=0; k=0; int sig = 0; long int di1,di2,po,pp,sp; int flag1,flag2,flag3,flag4; while(s[i]){ if(isalpha(s[i])){ temp[k][j]=s[i]; temp[k][j+1]=NULL; j++; } else{ if (j){ temp[k][j] = NULL; k++ ; } j = 0; } i++; } j = 0; if(strcmp(temp[0],sign) == 0){ sig = 1; j =1; } di1=0;po=0;pp=0;sp=0;di2 =0; for (i = j ; i <= k ; i++){ for (j = 0 ; j < 20 ; j++) if (strcmp(temp[i],digit[j]) == 0){ if(di1) di2 = digit_1[j]; else di1 = digit_1[j]; break; } for (j = 0 ; j < 8 ; j++) if (strcmp(temp[i],power[j]) == 0){ po = power_1[j]; break; } if(strcmp(ppp,temp[i]) == 0) pp = ppp_1; for (j = 0 ; j < 2 ; j++) if (strcmp(temp[i],super[j]) == 0){ sp = super_1[j]; break; } if(sp){ if(pp) if(di2) num += (di2+po+(di1*pp)) * sp; else num += (po+(di1*pp)) * sp; else num += (di1+po) * sp; sp = 0; pp = 0;po = 0;di1 = 0;di2 = 0; } } if(pp) if(di2) num += di2+po+(di1*pp) ; else num += po+(di1*pp) ; else num += di1+po; if(sig) num = num * (-1); printf("%ld\n",num); return 0; } int main(){ char s[1000]; while(gets(s)){ solution(s); } return 0; }
true
4dcd906552ad616fa856982a15a79745801552f4
C++
bigfishi/leetcode
/problems/128.longest-consecutive-sequence.cpp
UTF-8
1,093
3.4375
3
[ "MIT" ]
permissive
// 1. 先排序,然后判断 class Solution { public: int longestConsecutive(vector<int>& nums) { if (nums.size() < 2) return nums.size(); sort(nums.begin(), nums.end()); int cur = 1, res = 1, pre = nums[0]; int res = 0; for (int i = 1; i < nums.size(); i++) { if (nums[i] - pre == 1) { pre = nums[i]; cur++; if (cur > res) { res = cur; } } else if (nums[i] == pre) { } else { pre = nums[i]; cur = 1; } } return res; } }; // 2. 把数组放入map中,然后遍历数组,如果当前数-1不在map中,也就是当前数是序列第1个数,则自增判断连续序列,更新res,遍历结束后返回res即可。 class Solution { public: int longestConsecutive(vector<int>& nums) { if (nums.size() < 2) return nums.size(); map<int, int> m; for (auto num : nums) { m[num]++; } int res = 0; for (auto num : nums) { if (m.find(num - 1) == m.end()) { int i = num + 1; while (m.find(i)!=m.end()) { i++; } if (i - num > res) { res = i - num; } } } return res; } };
true
1ce8137d141037806d3c147853ee7e841bb227b3
C++
bheckel/code
/misc/c/array_class.h
UTF-8
1,565
3
3
[ "Apache-2.0" ]
permissive
// Modified: Sun 16 Feb 2003 15:24:41 (Bob Heckel) // Fig. 8.4: array1.h // Simple class Array (for integers only) #ifndef ARRAY1_H #define ARRAY1_H #include <iostream> using std::ostream; using std::istream; class Array { friend ostream &operator<<(ostream&, const Array&); friend istream &operator>>(istream&, Array&); public: Array(int = 3); // default constructor Array(const Array&); // copy constructor ~Array(); int getSize() const; // return size const Array &operator=(const Array&); // assign arrays bool operator==(const Array&) const; // compare equal // Determine if two arrays are not equal and return true, otherwise return // false (uses operator==). bool operator!=(const Array &right) const { return !(*this == right); } int& operator[](int); // subscript operator const int& operator[](int) const; // subscript operator static int getArrayCount(); // return count of arrays instantiated private: int size; // size of the array int* ptr; // pointer to first element of array static int arrayCount; // # of Arrays instantiated }; #endif /************************************************************************** * (C) Copyright 2000 by Deitel & Associates, Inc. and Prentice Hall. * * All Rights Reserved. * *************************************************************************/
true
d6e9f59d988a490492bc22fce674b1f6c2e58050
C++
erogers6264/google-cpp-class
/animal.cpp
UTF-8
610
3.34375
3
[]
no_license
// animal.cpp: Ethan Rogers // Description: Calculate how many horses, pigs, // and rabbits a farmer bought if he bought 100 // animals for $100 and Horses cost $10, pigs $3, // and rabbits #include <iostream> using namespace std; int main() { for (int h = 0; h < 10000; h++) { for (int p = 0; p < 10000; p++) { for (int r = 0; r < 10000; r++) { if ((h + p + r) == 10000) { if (((10 * h) + (3 * p) + (0.5 * r)) == 10000) { cout << "Found one! " << h << " horses " << p << " pigs " << r << " rabbits " << endl; } } } } } return 0; }
true
64e0eb169e692ad5207a62cd07dd54e97de84db6
C++
Capri2014/math
/test/unit/math/rev/scal/fun/log1m_test.cpp
UTF-8
958
2.65625
3
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#include <stan/math/rev/scal.hpp> #include <gtest/gtest.h> #include <test/unit/math/rev/scal/fun/nan_util.hpp> #include <test/unit/math/rev/scal/util.hpp> #include <limits> TEST(AgradRev, log1m) { using stan::math::log1m; AVAR a = 0.1; AVAR f = log1m(a); EXPECT_FLOAT_EQ(log(1 - 0.1), f.val()); AVEC x = createAVEC(a); VEC grad_f; f.grad(x, grad_f); EXPECT_FLOAT_EQ(-1 / (1 - 0.1), grad_f[0]); } TEST(AgradRev, excepts) { using stan::math::log1m; EXPECT_THROW(log1m(AVAR(10)), std::domain_error); } TEST(MathFunctions, log1m_inf_return) { EXPECT_EQ(-std::numeric_limits<double>::infinity(), stan::math::log1m(1)); } struct log1m_fun { template <typename T0> inline T0 operator()(const T0& arg1) const { return log1m(arg1); } }; TEST(AgradRev, log1m_NaN) { log1m_fun log1m_; test_nan(log1m_, false, true); } TEST(AgradRev, check_varis_on_stack) { AVAR a = 0.1; test::check_varis_on_stack(stan::math::log1m(a)); }
true
d378f2710df3fd23e50664a2397aaec1bec4bcce
C++
xinyuang/9_chapter_cpp_algorithm
/FLAG/Microsoft/41. Maximum Subarray.cpp
UTF-8
1,007
3.484375
3
[]
no_license
//41. Maximum Subarray //accumulate sum if negative, reset to 0 class Solution { public: /** * @param nums: A list of integers * @return: An integer indicate the sum of max subarray */ int maxSubArray(vector<int>& nums) { // write your code here if (nums.size() == 0) return 0; int sum = 0; int res = nums[0]; for (int i = 0; i < nums.size(); i++) { sum += nums[i]; res = max(res, sum); sum = max(0, sum); } return res; } }; class Solution { public: /** * @param nums: A list of integers * @return: An integer indicate the sum of max subarray */ int maxSubArray(vector<int>& nums) { // write your code here if (nums.size() == 0) return 0; vector<int> presum(nums.size() + 1, 0); for (int i = 0; i < nums.size(); i++) presum[i + 1] = presum[i] + nums[i]; int max_sum = nums[0]; int g_low = INT_MAX; for (int i = 0; i < presum.size(); i++) { max_sum = max(max_sum, presum[i] - g_low); g_low = min(g_low, presum[i]); } return max_sum; } };
true
e60c5836d26895934c9208c7d62efbfa91959a0c
C++
ZS167275/Five_SDL
/Five_AI/main.cpp
GB18030
2,955
2.578125
3
[]
no_license
/************************************************************************/ /* ļ޸ģֱ޸Five_AI.h */ /************************************************************************/ #include "SDL.h" #include "SDL_net.h" #include "SDL_ttf.h" #include "Five_AI.h" int main(int argc, char ** argv){ //Initialize all SDL subsystems if( SDL_Init( SDL_INIT_EVERYTHING ) == -1 ) { return 1; } //Set up the screen SDL_Surface * screen = NULL; screen = SDL_SetVideoMode( 200, 150, 32, SDL_SWSURFACE ); //If there was an error in setting up the screen if( screen == NULL ) { return 1; } //Initialize SDL_ttf if( TTF_Init() == -1 ) { return 1; } //Initialize SDL_net if(SDLNet_Init() == -1){ return 1; } //Set the window caption SDL_WM_SetCaption( "Five AI", NULL ); TTF_Font *font; //Open the font font = TTF_OpenFont( "font.ttf", 19 ); if( font == NULL ) { return 1; } //Set Font Style TTF_SetFontStyle(font, TTF_STYLE_BOLD | TTF_STYLE_ITALIC); //The color of the font SDL_Color textColor = { 215, 215, 215 }; SDL_Surface * msg = NULL; msg = TTF_RenderText_Solid(font,"Connecting",textColor); SDL_BlitSurface(msg,NULL,screen,NULL); IPaddress ip; TCPsocket tcpsock; // create a listening TCP socket on port 4700 (client) if(SDLNet_ResolveHost(&ip,"localhost",4700)==-1) { return 1; } bool quit = false; bool connected = false; bool success = false; bool finish = false; SDL_Event event; while(!quit) { //While there's an event to handle while( SDL_PollEvent( &event ) ) { //If the user has Xed out the window if( event.type == SDL_QUIT ) { //Quit the program quit = true; } } if(!connected){ tcpsock = SDLNet_TCP_Open(&ip); if(tcpsock){ msg = TTF_RenderText_Solid(font,"Connected",textColor); connected = true; } }else{ //success = false; char data[257]={0}; char response[3]={0}; if(SDLNet_TCP_Recv(tcpsock,data,257) > 0){ if(data[0] != 'e'){ int gameData[15][15] = {{0}}; int addX = -1,addY = -1; for(int i = 0 ; i < 255; i ++){ int temp = 0; if(data[i+1] != 0) temp = (data[i + 1]==data[0] ? 1 : 2); gameData[i/15][i%15] = temp; } AIwork(gameData,addX,addY); response[0] = addX; response[1] = addY; if(SDLNet_TCP_Send(tcpsock,response,3) == 3) success = true; }else{ finish = true; quit = true; } } if(success) msg = TTF_RenderText_Solid(font,"Working",textColor); } SDL_FillRect( screen, &screen->clip_rect, SDL_MapRGB( screen->format, 0x00, 0x00, 0x00 ) ); SDL_BlitSurface(msg,NULL,screen,NULL); SDL_Flip(screen); SDL_Delay( 10 ); } //Quit SDL_ttf TTF_Quit(); //Close Network if(!finish && connected){ SDLNet_TCP_Send(tcpsock,"e",2); SDLNet_TCP_Close(tcpsock); } //Quit SDL_net SDLNet_Quit(); //Quit SDL SDL_Quit(); return 0; }
true
5fc6f7979117c34d18dad90f4332caf9a1630fa5
C++
shusilshapkota/OptiPhi
/Optiφ/Utilities/BinaryArray.h
UTF-8
995
2.796875
3
[]
no_license
#include <stdlib.h> #include "Utilities.cpp" class BinaryArray { public: static BinaryArray inValidBinaryArray; static BinaryArray newCharArray; // Methods bool isValid(); int getLength(); //int* getData(); void addNewChar(); int numOnes(); int numZeros(); // Operators int& operator() (int index) const; BinaryArray operator + (const BinaryArray & arr) const; void operator += (const BinaryArray & arr) ; BinaryArray operator + (const bool b) const; void operator += (const bool b); void operator = (const BinaryArray & arr); bool operator == (const BinaryArray & p) const; // Constructors/Destructor BinaryArray(const int* data,const int length); BinaryArray(const BinaryArray & m); BinaryArray(); // Initialized matrix ~BinaryArray(); private: int _length; int* _data; friend std::ostream& operator<<(std::ostream& os, const BinaryArray& m); };
true
7d918a9596879642425ba59326c9a7dff9c440ab
C++
csdu/coding-club-sessions
/2020-01-31-data-structures-cpp-stl/generic_class_and_type.cpp
UTF-8
408
3.375
3
[]
no_license
#include <iostream> #include <utility> using namespace std; template <typename A> class abc { public: A a; abc(A x) { a = x; } }; template <typename A, typename B> using pp = pair<A, B>; int main() { pp<int, char> p = make_pair(1, 'A'); abc<float> a(3.14f); cout << "p: {" << p.first << ", " << p.second << "}\n\n"; cout << "a: " << a.a << '\n'; return 0; }
true
fb3b98b59dce7604fb560c6781aaa7d0b7141b50
C++
xivol/AM-PRO2-2016
/Class/triangle.cpp
WINDOWS-1251
2,729
3.296875
3
[]
no_license
#include "..\Polymorph\triangle.h" #include "triangle.h" #include <cmath> #include <iostream> triangle::triangle() : a(), b(), c() {} triangle::triangle(const point & a, const point & b, const point & c) { if (is_line(a, b, c)) throw std::invalid_argument(" "); this->a = a; this->b = b; this->c = c; } triangle & triangle::operator=(const triangle & t) { polygon::operator=(t); return *this; } point triangle::get_a() const { return a; } point triangle::get_b() const { return b; } point triangle::get_c() const { return c; } triangle::angle_type triangle::type() const { double ab = a.distance_to(b); ab *= ab; double bc = b.distance_to(c); bc *= bc; double ca = c.distance_to(a); ca *= ca; sort(ab, bc, ca, false); double dif = ab - bc - ca; if (abs(dif)<precision) return Right; if (dif>0) return Obtuse; return Acute; } double triangle::perimeter() const { double ab = a.distance_to(b); double bc = b.distance_to(c); double ca = c.distance_to(a); return ab + bc + ca; } double triangle::area() const { double ab = a.distance_to(b); double bc = b.distance_to(c); double ca = c.distance_to(a); double p = (ab + bc + ca) / 2.0; std::cout << ab << " " << bc << " " << ca << std::endl; std::cout << p << std::endl; return sqrt(p*(p - ab)*(p - bc)*(p - ca)); } double triangle::inradius() const { return area() / perimeter() / 2.0; } double triangle::circumradius() const { double ab = a.distance_to(b); double bc = b.distance_to(c); double ca = c.distance_to(a); return ab*bc*ca / sqrt((ab + bc + ca)*(-ab + bc + ca)*(ab - bc + ca)*(ab + bc - ca)); } void sort(double & a, double & b, double & c, bool asc) { double max, mid, min; if (a > b) if (b > c) max = a, mid = b, min = c; else if (c > a) max = c, mid = a, min = b; else max = a, mid = c, min = b; else if (a > c) max = b, mid = a, min = c; else if (c > b) max = c, mid = b, min = a; else max = b, mid = c, min = a; if (asc) { double t = min; min = max; max = t; } a = max; b = mid; c = min; } triangle get_triangle() { point a = get_point(); point b = get_point(); point c = get_point(); return triangle(a,b,c); } void print(const triangle & t) { std::cout << "A:"; print(t.get_a()); std::cout << ", B:"; print(t.get_b()); std::cout << ", C:"; print(t.get_c()); }
true
5d97e9fcb0921dc32a114bc1ed95a08026c29456
C++
longluo/leetcode
/Cpp/leetcode/editor/cn/230_kth-smallest-element-in-a-bst.cpp
UTF-8
1,790
3.296875
3
[ "MIT" ]
permissive
//给定一个二叉搜索树的根节点 root ,和一个整数 k ,请你设计一个算法查找其中第 k 个最小元素(从 1 开始计数)。 // // // // 示例 1: // // //输入:root = [3,1,4,null,2], k = 1 //输出:1 // // // 示例 2: // // //输入:root = [5,3,6,2,4,null,null,1], k = 3 //输出:3 // // // // // // // 提示: // // // 树中的节点数为 n 。 // 1 <= k <= n <= 10⁴ // 0 <= Node.val <= 10⁴ // // // // // 进阶:如果二叉搜索树经常被修改(插入/删除操作)并且你需要频繁地查找第 k 小的值,你将如何优化算法? // Related Topics 树 深度优先搜索 二叉搜索树 二叉树 👍 603 👎 0 // 2022-04-18 08:36:00 // By Long Luo #include <bits/stdc++.h> #include <TreeNode.h> using namespace std; //leetcode submit region begin(Prohibit modification and deletion) /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int kthSmallest(TreeNode *root, int k) { vector<TreeNode *> nodes; inOrder(root, nodes); return nodes[k - 1]->val; } void inOrder(TreeNode *root, vector<TreeNode *> &nodes) { if (root == nullptr) { return; } inOrder(root->left, nodes); nodes.push_back(root); inOrder(root->right, nodes); } }; //leetcode submit region end(Prohibit modification and deletion) int main() { Solution s; vector<int> data{7, 1, 5, 3, 6, 4}; }
true
7acb474d52640de67ad20ef5d82f54f73e82397c
C++
Sikurity/StudyAlgorithm
/Normal/13325_BinaryTree.cpp
UTF-8
1,093
2.828125
3
[]
no_license
/** * @link https://www.acmicpc.net/problem/13325 * @date 2017. 04. 08 * @author Sikurity * @method Use Binary Tree Made Of Array */ #include <stdio.h> #include <vector> #include <algorithm> using namespace std; int k; long long result; pair<int, int> adj[1 << 20]; long long absLL(long long num) { return num < 0 ? -num : num; } long long maxLL(long long a, long long b) { return a >= b ? a : b; } long long algorithm(int cur = 1, int acc = 0, int level = 1) { if( level > k ) return acc; long long l, r; l = algorithm(2 * cur, acc + adj[cur].first, level + 1); r = algorithm(2 * cur + 1, acc + adj[cur].second, level + 1); result += adj[cur].first + adj[cur].second + absLL(l - r); return maxLL(l, r); } int main() { int n, l, r; scanf("%d", &k); n = 1; for(int i = 0 ; i < k ; i++ ) n = n << 1; for(int i = 1 ; i < n ; i++) { scanf("%d %d", &l, &r); adj[i] = make_pair(l, r); } algorithm(); printf("%lld\n", result); return 0; }
true
e42c6f9380577654714ae5b8b74ed26ed1f2462e
C++
zhongjianhua163/BlackMoonKernelStaticLib
/krnln/krnln_write.cpp
GB18030
9,071
2.578125
3
[ "BSD-3-Clause" ]
permissive
#include "stdafx.h" #include "MyMemFile.h" #include "Myfunctions.h" //ļд - д /* øʽ ߼͡ д дݵļţͨ/ дݣ... - ϵͳֿ֧->ļд Ӣƣwrite Ӧ롰롱ʹãдһϵбĸʽݵļеǰдλôɹ棬ʧܷؼ١ ݵдʽΪ 1ֵ͡߼͡ʱ͡ӳָͣ ΪӦʵݣ 2ıͣ Ϊı + ֽ 0 3ֽڼͣ Ϊֽڼݳȣ + ֽڼʵݣ 4ϸ͵ݣ Ϊݸʽ˳СΪмһԱظӡ <1>ΪдݵļšΪͣintļɡļء <2>ΪдݡΪͨͣallṩʱͬʱṩݡдݵΪûԶⶨͣʧܡ */ LIBAPI(BOOL, krnln_write) { PFILEELEMENT pFile = (PFILEELEMENT)ArgInf.m_pCompoundData; if(pFile==NULL) return NULL; if(IsInFileMangerList(pFile)==FALSE)//Ϸ return NULL; PMDATA_INF pArgInf = &ArgInf; BOOL bRet = FALSE; if(pFile->nType ==1 || pFile->nType == 3)//ļ ļ { HANDLE hFile = (HANDLE)pFile->FileHandle; DWORD dwNumOfByteRead; bRet = TRUE; INT nPos; for(INT i=1;i < nArgCount;i++) { if(bRet == FALSE) break; if((pArgInf[i].m_dtDataType & DT_IS_ARY) == DT_IS_ARY)// { pArgInf[i].m_dtDataType &=~DT_IS_ARY; //ȥ־ if(pArgInf[i].m_dtDataType==SDT_TEXT) { DWORD dwSize; LPSTR* pAryData = (LPSTR*)GetAryElementInf(pArgInf[i].m_pAryData,dwSize); INT nData = 0; for(UINT n=0;n<dwSize;n++) { INT nLen; void* pData; if(pAryData[n]==NULL) { nLen = 1; pData = &nData; } else { nLen = mystrlen(pAryData[n])+1; pData = pAryData[n]; } void *pTMP = NULL; if (pFile->nType == 3) //ļ { pTMP = malloc(nLen); memcpy(pTMP, pData, nLen); nPos = SetFilePointer(hFile,0,NULL,FILE_CURRENT); E_RC4_Calc(nPos, (unsigned char*)pTMP, nLen, pFile->strTable, pFile->nCryptStart, pFile->strMD5); pData = pTMP; } if(WriteFile(hFile,pData,nLen,&dwNumOfByteRead,NULL)) { // if(FlushFileBuffers(hFile)==FALSE) // bRet = FALSE; } else bRet = FALSE; if (pTMP) { free(pTMP); pTMP = NULL; } if(bRet == FALSE) break; } }else if(pArgInf[i].m_dtDataType==SDT_BIN) { DWORD dwSize; LPINT* pAryData = (LPINT*)GetAryElementInf(pArgInf[i].m_pAryData,dwSize); INT nData = 0; for(UINT n=0;n<dwSize;n++) { void* pData; INT nLen; if(pAryData[n]==NULL) { pData = &nData; nLen = sizeof(INT); } else { LPINT p = pAryData[n]; nLen = p[1]+sizeof(INT); p++; pData = p; } void *pTMP = NULL; if (pFile->nType == 3) //ļ { pTMP = malloc(nLen); memcpy(pTMP, pData, nLen); nPos = SetFilePointer(hFile,0,NULL,FILE_CURRENT); E_RC4_Calc(nPos, (unsigned char*)pTMP, nLen, pFile->strTable, pFile->nCryptStart, pFile->strMD5); pData = pTMP; } if(WriteFile(hFile,pData,nLen,&dwNumOfByteRead,NULL)) { // if(FlushFileBuffers(hFile)==FALSE) // bRet = FALSE; } else bRet = FALSE; if (pTMP) { free(pTMP); pTMP = NULL; } if(bRet == FALSE) break; } }else{ INT nLen = GetSysDataTypeDataSize(pArgInf[i].m_dtDataType); if(nLen==0)//ֵ֧ continue; DWORD dwSize; void* pData = GetAryElementInf(pArgInf[i].m_pAryData,dwSize); nLen *= dwSize; void *pTMP = NULL; if (pFile->nType == 3) //ļ { pTMP = malloc(nLen); memcpy(pTMP, pData, nLen); nPos = SetFilePointer(hFile,0,NULL,FILE_CURRENT); E_RC4_Calc(nPos, (unsigned char*)pTMP, nLen, pFile->strTable, pFile->nCryptStart, pFile->strMD5); pData = pTMP; } if(WriteFile(hFile,pData,nLen,&dwNumOfByteRead,NULL)) { // if(FlushFileBuffers(hFile)==FALSE) // bRet = FALSE; } else bRet = FALSE; if (pTMP) { free(pTMP); pTMP = NULL; } if(bRet == FALSE) break; } } else {// INT nLen; void* pData; INT nData = 0; if(pArgInf[i].m_dtDataType==SDT_TEXT) { if(pArgInf[i].m_pText==NULL) { nLen = 1; pData = &nData; } else { nLen = mystrlen(pArgInf[i].m_pText)+1; pData = pArgInf[i].m_pText; } }else if(pArgInf[i].m_dtDataType==SDT_BIN) { if(pArgInf[i].m_pBin==NULL) { nLen = sizeof(INT); pData = &nData; } else { LPINT p = (LPINT)pArgInf[i].m_pBin; nLen = p[1]+sizeof(INT); p++; pData = p; } }else{ nLen = GetSysDataTypeDataSize(pArgInf[i].m_dtDataType); if(nLen==0)//ֵ֧ continue; pData = &pArgInf[i].m_int; } void *pTMP = NULL; if (pFile->nType == 3) //ļ { pTMP = malloc(nLen); memcpy(pTMP, pData, nLen); nPos = SetFilePointer(hFile,0,NULL,FILE_CURRENT); E_RC4_Calc(nPos, (unsigned char*)pTMP, nLen, pFile->strTable, pFile->nCryptStart, pFile->strMD5); pData = pTMP; } if(WriteFile(hFile,pData,nLen,&dwNumOfByteRead,NULL)) { // if(FlushFileBuffers(hFile)==FALSE) // bRet = FALSE; } else bRet = FALSE; if (pTMP) { free(pTMP); pTMP = NULL; } if(bRet == FALSE) break; } } }else if(pFile->nType ==2)//ڴļ { CMyMemFile* pMemFile = (CMyMemFile*) pFile->FileHandle; bRet = TRUE; for(INT i=1;i < nArgCount;i++) { if((pArgInf[i].m_dtDataType & DT_IS_ARY) == DT_IS_ARY)// { pArgInf[i].m_dtDataType &=~DT_IS_ARY; //ȥ־ if(pArgInf[i].m_dtDataType==SDT_TEXT) { DWORD dwSize; LPSTR* pAryData = (LPSTR*)GetAryElementInf(pArgInf[i].m_pAryData,dwSize); INT nData = 0; for(UINT n=0;n<dwSize;n++) { INT nLen; void* pData; if(pAryData[n]==NULL) { nLen = 1; pData = &nData; } else { nLen = mystrlen(pAryData[n])+1; pData = pAryData[n]; } pMemFile->Write(pData,nLen); } }else if(pArgInf[i].m_dtDataType==SDT_BIN) { DWORD dwSize; LPINT* pAryData = (LPINT*)GetAryElementInf(pArgInf[i].m_pAryData,dwSize); INT nData = 0; for(UINT n=0;n<dwSize;n++) { void* pData; INT nLen; if(pAryData[n]==NULL) { pData = &nData; nLen = sizeof(INT); } else { LPINT p = pAryData[n]; nLen = p[1]+sizeof(INT); p++; pData = p; } pMemFile->Write(pData,nLen); } }else{ INT nLen = GetSysDataTypeDataSize(pArgInf[i].m_dtDataType); if(nLen==0)//ֵ֧ continue; DWORD dwSize; void* pData = GetAryElementInf(pArgInf[i].m_pAryData,dwSize); nLen *= dwSize; pMemFile->Write(pData,nLen); } } else {// INT nLen; void* pData; INT nData = 0; if(pArgInf[i].m_dtDataType==SDT_TEXT) { if(pArgInf[i].m_pText==NULL) { nLen = 1; pData = &nData; } else { nLen = mystrlen(pArgInf[i].m_pText)+1; pData = pArgInf[i].m_pText; } }else if(pArgInf[i].m_dtDataType==SDT_BIN) { if(pArgInf[i].m_pBin==NULL) { nLen = sizeof(INT); pData = &nData; } else { LPINT p = (LPINT)pArgInf[i].m_pBin; nLen = p[1]+sizeof(INT); p++; pData = p; } }else{ nLen = GetSysDataTypeDataSize(pArgInf[i].m_dtDataType); if(nLen==0)//ֵ֧ continue; pData = &pArgInf[i].m_int; } pMemFile->Write(pData,nLen); } } } return bRet; }
true
6fc46a153c28691643cfc87d88190d4bc52765bf
C++
deadmorous/raytracer
/ray.h
UTF-8
989
3.03125
3
[]
no_license
#ifndef RAY_H #define RAY_H /// \file /// \brief Definition of the Ray data structure. #include "common.h" namespace raytracer { /// \brief Structure representing an instance of ray for use in the ray tracer. struct Ray { v3f origin; ///< \brief Ray origin. v3f dir; ///< \brief Ray direction (unit length vector). int generation; ///< \brief Ray generation number. v3f color; ///< \brief Ray color. /// \brief Default constructor (does nothing). Ray() {} /// \brief Constructor. /// \param origin Initializer for #origin. /// \param dir Initializer for #dir. /// \param color Initializer for #color. /// \param generation Initializer for #generation. Ray(const v3f& origin, const v3f& dir, const v3f& color, int generation) : origin(origin), dir(dir), generation(generation), color(color) {} }; } // end namespace raytracer #endif // RAY_H
true
e6631648f8c54f69bd7dfa9d09bee8d913a9761d
C++
navigateai/RobotMapping_SLAM_Assignments_In_Cpp
/EKF_Slam/C++/correction_step.h
UTF-8
4,231
2.84375
3
[ "MIT" ]
permissive
#pragma once #include "../../eigen/Eigen/Dense" #include "tools/read_data.h" #include "tools/normalize_all_bearings.h" using namespace Eigen; void correction_step(VectorXf &mu, MatrixXf &sigma, std::vector<Sensor> z, std::vector<bool> observedLandmarks){ /* Updates the belief, i. e., mu and sigma after observing landmarks, according to the sensor model The employed sensor model measures the range and bearing of a landmark mu: 2N+3 x 1 vector representing the state mean. The first 3 components of mu correspond to the current estimate of the robot pose [x; y; theta] The current pose estimate of the landmark with id = j is: [mu(2*j+2); mu(2*j+3)] sigma: 2N+3 x 2N+3 is the covariance matrix z: struct array containing the landmark observations. Each observation z(i) has an id z(i).id, a range z(i).range, and a bearing z(i).bearing The vector observedLandmarks indicates which landmarks have been observed at some point by the robot. observedLandmarks(j) is false if the landmark with id = j has never been observed before. */ // Number of measurements in this time step int m = z.size(); // Z: vectorized form of all measurements made in this time step: [range_1; bearing_1; range_2; bearing_2; ...; range_m; bearing_m] // ExpectedZ: vectorized form of all expected measurements in the same form. // They are initialized here and should be filled out in the for loop below VectorXf Z(m*2); VectorXf expectedZ(m*2); // Iterate over the measurements and compute the H matrix // (stacked Jacobian blocks of the measurement function) // H will be 2m x 2N+3 MatrixXf H(2*m, mu.size()); for(int i = 0; i < m; ++i){ // Get the id of the landmark corresponding to the i-th observation int landmarkId = z[i].id; int landmark_x_idx = 3 + landmarkId*2; int landmark_y_idx = 4 + landmarkId*2; // If the landmark is obeserved for the first time: if(observedLandmarks[landmarkId]==false){ // Initialize its pose in mu based on the measurement and the current robot pose: mu(landmark_x_idx) = mu(0) + z[i].range*std::cos(mu(2)+z[i].bearing); mu(landmark_y_idx) = mu(1) + z[i].range*std::sin(mu(2)+z[i].bearing); // Indicate in the observedLandmarks vector that this landmark has been observed observedLandmarks[landmarkId] = true; } // Add the landmark measurement to the Z vector Z(2*i) = z[i].range; Z(2*i+1) = z[i].bearing; // Use the current estimate of the landmark pose // to compute the corresponding expected measurement in expectedZ: float dx = mu(landmark_x_idx) - mu(0); float dy = mu(landmark_y_idx) - mu(1); float q = std::pow(dx,2)+std::pow(dy,2); float sq = std::sqrt(q); expectedZ(2*i) = sq; expectedZ(2*i+1) = normalize_angle(std::atan2(dy,dx) - mu(2)); // Compute the Jacobian Hi of the measurement function h for this observation MatrixXf F = MatrixXf::Zero(5,mu.size()); F(0,0) = 1; F(1,1) = 1; F(2,2) = 1; F(3, landmark_x_idx) = 1; F(4, landmark_y_idx) = 1; MatrixXf Hx(2,5); Hx << -sq*dx, -sq*dy, 0, sq*dx, sq*dy, dy, -dx, -q, -dy, dx; MatrixXf Hi = (1.0/q)*Hx*F; // Augment H with the new Hi H.block(i*Hi.rows(), 0, Hi.rows(), Hi.cols()) = Hi; } // Construct the sensor noise matrix Q MatrixXf Q = MatrixXf::Identity(2*m,2*m)*0.01; // Compute the Kalman gain MatrixXf K = sigma*H.transpose()*(H*sigma*H.transpose() + Q).inverse(); // Compute the difference between the expected and recorded measurements. // Remember to normalize the bearings after subtracting! // (hint: use the normalize_all_bearings function available in tools) VectorXf innov = Z - expectedZ; normalize_all_bearings(innov); // Finish the correction step by computing the new mu and sigma. // Normalize theta in the robot pose. mu = mu + K*innov; MatrixXf I = MatrixXf::Identity(mu.size(), mu.size()); sigma = (I - K*H)*sigma; }
true
3c0ef4dcc47e2cf39216bc4f295914aaa7945653
C++
loupus/pgfe
/test/pgfe/pgfe-unit-connection_options.cpp
UTF-8
9,007
2.515625
3
[ "Zlib" ]
permissive
// -*- C++ -*- // Copyright (C) Dmitry Igrishin // For conditions of distribution and use, see files LICENSE.txt #ifndef DMITIGR_PGFE_HEADER_ONLY #define DMITIGR_PGFE_HEADER_ONLY #endif #include <dmitigr/misc/testo.hpp> #include <dmitigr/pgfe/connection_options.hpp> #include <cstring> #include <iostream> #include <string> int main(int, char* argv[]) { namespace pgfe = dmitigr::pgfe; namespace defaults = pgfe::detail::defaults; using namespace dmitigr::testo; using Cm = pgfe::Communication_mode; try { pgfe::Connection_options co{Cm::net}; ASSERT(co.communication_mode() == Cm::net); #ifndef _WIN32 co = pgfe::Connection_options{Cm::uds}; ASSERT(co.communication_mode() == Cm::uds); #endif co = {}; ASSERT(co.communication_mode() == defaults::communication_mode); { const auto value = Cm::net; co.communication_mode(value); ASSERT(co.communication_mode() == value); } using ms = std::chrono::milliseconds; ASSERT(co.connect_timeout() == defaults::connect_timeout); { ms valid_value{}; co.connect_timeout(valid_value); ASSERT(co.connect_timeout() == valid_value); ms invalid_value{-1}; ASSERT(is_throw_works<std::runtime_error>([&]{ co.connect_timeout(invalid_value); })); } ASSERT(co.wait_response_timeout() == defaults::wait_response_timeout); { ms valid_value{}; co.wait_response_timeout(valid_value); ASSERT(co.wait_response_timeout() == valid_value); ms invalid_value{-1}; ASSERT(is_throw_works<std::runtime_error>([&]{ co.wait_response_timeout(invalid_value); })); } #ifndef _WIN32 ASSERT(co.uds_directory() == defaults::uds_directory); { co.communication_mode(Cm::uds); ASSERT(co.communication_mode() == Cm::uds); const auto valid_value = "/valid/directory/name"; co.uds_directory(valid_value); ASSERT(co.uds_directory() == valid_value); const auto invalid_value = "invalid directory name"; ASSERT(is_throw_works<std::runtime_error>([&]{ co.uds_directory(invalid_value); })); } ASSERT(co.uds_require_server_process_username() == defaults::uds_require_server_process_username); { const auto value = "some value"; co.uds_require_server_process_username(value); ASSERT(co.uds_require_server_process_username() == value); } // Testing the protection against the improper usage. { co.communication_mode(Cm::net); co.uds_directory(); co.uds_require_server_process_username(); } #endif ASSERT(co.is_tcp_keepalives_enabled() == defaults::tcp_keepalives_enabled); { const auto value = true; co.tcp_keepalives_enabled(value); ASSERT(co.is_tcp_keepalives_enabled() == value); co.tcp_keepalives_enabled(!value); ASSERT(co.is_tcp_keepalives_enabled() == !value); } ASSERT(co.tcp_keepalives_idle() == defaults::tcp_keepalives_idle); { using namespace std::chrono_literals; const auto value = 10s; co.tcp_keepalives_idle(value); ASSERT(co.tcp_keepalives_idle() == value); } ASSERT(co.tcp_keepalives_interval() == defaults::tcp_keepalives_interval); { using namespace std::chrono_literals; const auto value = 10s; co.tcp_keepalives_interval(value); ASSERT(co.tcp_keepalives_idle() == value); } ASSERT(co.tcp_keepalives_count() == defaults::tcp_keepalives_count); { const auto valid_value = 100; co.tcp_keepalives_count(valid_value); ASSERT(co.tcp_keepalives_count() == valid_value); const auto invalid_value = -100; ASSERT(is_throw_works<std::runtime_error>([&]() { co.tcp_keepalives_count(invalid_value); })); } ASSERT(co.net_address() == defaults::net_address); { const auto valid_value_ipv4 = "127.0.0.1"; co.net_address(valid_value_ipv4); ASSERT(co.net_address() == valid_value_ipv4); const auto valid_value_ipv6 = "::1"; co.net_address(valid_value_ipv6); ASSERT(co.net_address() == valid_value_ipv6); const auto invalid_value_ipv4 = "127.257.0.1"; ASSERT(is_throw_works<std::runtime_error>([&]() { co.net_address(invalid_value_ipv4); })); const auto invalid_value_ipv6 = "::zz"; ASSERT(is_throw_works<std::runtime_error>([&]() { co.net_address(invalid_value_ipv6); })); } ASSERT(co.net_hostname() == defaults::net_hostname); { const auto valid_value = "localhost"; co.net_hostname(valid_value); ASSERT(co.net_hostname() == valid_value); const auto invalid_value = "local host"; ASSERT(is_throw_works<std::runtime_error>([&]() { co.net_hostname(invalid_value); })); } ASSERT(co.port() == defaults::port); { const auto valid_value = 5432; co.port(valid_value); ASSERT(co.port() == valid_value); const auto invalid_value = 65536; ASSERT(is_throw_works<std::runtime_error>([&]() { co.port(invalid_value); })); } #ifndef _WIN32 // Testing the protection against the improper usage. { using namespace std::chrono_literals; co.communication_mode(pgfe::Communication_mode::uds); co.is_tcp_keepalives_enabled(); co.tcp_keepalives_idle(); co.tcp_keepalives_interval(); co.tcp_keepalives_count(); co.net_address(); co.net_hostname(); co.port(); } #endif ASSERT(co.username() == defaults::username); { const auto value = "some user name"; co.username(value); ASSERT(co.username() == value); } ASSERT(co.database() == defaults::database); { const auto value = "some database"; co.database(value); ASSERT(co.database() == value); } ASSERT(co.password() == defaults::password); { const auto value = "some password"; co.password(value); ASSERT(co.password() == value); } ASSERT(co.kerberos_service_name() == defaults::kerberos_service_name); { const auto value = "some name"; co.kerberos_service_name(value); ASSERT(co.kerberos_service_name() == value); } ASSERT(co.is_ssl_enabled() == defaults::ssl_enabled); { const auto value = !defaults::ssl_enabled; co.ssl_enabled(value); ASSERT(co.is_ssl_enabled() == value); } ASSERT(co.ssl_certificate_authority_file() == defaults::ssl_certificate_authority_file); { const auto value = "some value"; co.ssl_certificate_authority_file(value); ASSERT(co.ssl_certificate_authority_file() == value); } // Note: this options is depends on "ssl_certificate_authority_file". ASSERT(co.is_ssl_server_hostname_verification_enabled() == defaults::ssl_server_hostname_verification_enabled); { const auto value = true; co.ssl_server_hostname_verification_enabled(value); ASSERT(co.is_ssl_server_hostname_verification_enabled() == value); co.ssl_server_hostname_verification_enabled(!value); ASSERT(co.is_ssl_server_hostname_verification_enabled() == !value); } ASSERT(co.is_ssl_compression_enabled() == defaults::ssl_compression_enabled); { const auto value = true; co.ssl_compression_enabled(value); ASSERT(co.is_ssl_compression_enabled() == value); co.ssl_compression_enabled(!value); ASSERT(co.is_ssl_compression_enabled() == !value); } ASSERT(co.ssl_certificate_file() == defaults::ssl_certificate_file); { const auto value = "some value"; co.ssl_certificate_file(value); ASSERT(co.ssl_certificate_file() == value); } ASSERT(co.ssl_private_key_file() == defaults::ssl_private_key_file); { const auto value = "some value"; co.ssl_private_key_file(value); ASSERT(co.ssl_private_key_file() == value); } ASSERT(co.ssl_certificate_revocation_list_file() == defaults::ssl_certificate_revocation_list_file); { const auto value = "some value"; co.ssl_certificate_revocation_list_file(value); ASSERT(co.ssl_certificate_revocation_list_file() == value); } // Testing the protection against the improper usage. { co.ssl_enabled(false); co.is_ssl_server_hostname_verification_enabled(); co.is_ssl_compression_enabled(); co.ssl_certificate_file(); co.ssl_private_key_file(); co.ssl_certificate_authority_file(); co.ssl_certificate_revocation_list_file(); } // detail::pq::Connection_options { pgfe::detail::pq::Connection_options pco{co}; const char* const* keywords = pco.keywords(); const char* const* values = pco.values(); for (std::size_t i = 0; i < pco.count(); ++i) { ASSERT(keywords[i]); ASSERT(values[i]); std::cout << keywords[i] << " = " << "\"" << values[i] << "\"" << std::endl; } } } catch (const std::exception& e) { report_failure(argv[0], e); return 1; } catch (...) { report_failure(argv[0]); return 1; } }
true
ee2f82799d2b252062e83f3298118280d2ea7ec2
C++
myyrakle/BigNumber
/include/BigInteger.h
UTF-8
3,601
3.03125
3
[ "MIT" ]
permissive
#ifndef __BIG_INTEGER__ #define __BIG_INTEGER__ #include <vector> #include <string> #include <cstdint> #include <ostream> #include <istream> namespace bignumber { constexpr auto INTERVAL = '0'-0; class BigInteger { public: using Self = BigInteger; private: std::vector<char> num; bool sign = true; //부호비트 private: template <class Integer> BigInteger(Integer n, nullptr_t _) { std::string s; if(n<0) { sign = false; s = std::to_string(-n); } else { sign = true; s = std::to_string(n); } for(auto it = s.rbegin(); it!=s.rend(); it++) { num.push_back(*it - INTERVAL); } } public: BigInteger(signed char n); BigInteger(short n); BigInteger(int n); BigInteger(long n); BigInteger(long long n); BigInteger(unsigned char n); BigInteger(unsigned short n); BigInteger(unsigned int n); BigInteger(unsigned long n); BigInteger(unsigned long long n); BigInteger(const std::string& n); public: public: BigInteger(); virtual ~BigInteger() = default; public: BigInteger(const BigInteger&) = default; BigInteger& operator=(const BigInteger&) = default; BigInteger(BigInteger&&) = default; BigInteger& operator=(BigInteger&&) = default; public: //이항산술연산자 friend BigInteger operator+(const BigInteger& lhs, const BigInteger& rhs); friend BigInteger operator-(const BigInteger& lhs, const BigInteger& rhs); friend BigInteger operator*(const BigInteger& lhs, const BigInteger& rhs); friend BigInteger operator/(const BigInteger& lhs, const BigInteger& rhs); friend BigInteger operator%(const BigInteger& lhs, const BigInteger& rhs); public: friend BigInteger& operator+=(BigInteger& lhs, const BigInteger& rhs); friend BigInteger& operator-=(BigInteger& lhs, const BigInteger& rhs); friend BigInteger& operator*=(BigInteger& lhs, const BigInteger& rhs); friend BigInteger& operator/=(BigInteger& lhs, const BigInteger& rhs); friend BigInteger& operator%=(BigInteger& lhs, const BigInteger& rhs); public: //단항연산자 BigInteger& operator++(); BigInteger operator++(int); BigInteger operator+() const; BigInteger& operator--(); BigInteger operator--(int); BigInteger operator-() const; public: //비교연산자 friend bool operator<(const BigInteger& lhs, const BigInteger& rhs); friend bool operator>(const BigInteger& lhs, const BigInteger& rhs); friend bool operator<=(const BigInteger& lhs, const BigInteger& rhs); friend bool operator>=(const BigInteger& lhs, const BigInteger& rhs); friend bool operator==(const BigInteger& lhs, const BigInteger& rhs); friend bool operator!=(const BigInteger& lhs, const BigInteger& rhs); public: bool is_zero() const noexcept; bool is_odd() const noexcept; bool is_even() const noexcept; bool is_negative() const noexcept; bool is_positive() const noexcept; std::string to_string() const; public: operator int8_t() const; operator int16_t() const; operator int32_t() const; operator int64_t() const; operator uint8_t() const; operator uint16_t() const; operator uint32_t() const; operator uint64_t() const; operator std::string() const; }; std::ostream& operator<<(std::ostream& os, const BigInteger& n); std::istream& operator>>(std::istream& is, BigInteger& n); } bignumber::BigInteger operator ""bi(unsigned long long n); #endif
true
2dd79f72f49ec39b407fbef472cff7848fd23463
C++
upple/BOJ
/src/2000/2857.cpp14.cpp
UTF-8
249
2.953125
3
[ "MIT" ]
permissive
#include <iostream> #include <string> using namespace std; int main() { string str; bool FIND=false; for(int i=1; i<=5; i++) { cin>>str; if(str.find("FBI")!=string::npos) FIND=true, cout<<i<<" "; } if(!FIND) cout<<"HE GOT AWAY!"; }
true
919940f972e0ab5126dec12c66ce91f22a0b72c5
C++
PenguinGrape/algosy4
/1297.cpp
UTF-8
1,384
3.140625
3
[]
no_license
// // Created by grape on 07.06.2020. // #include <cstring> #include <iostream> int main(){ char s[1001]; int str_length; int max_length = 1; int pal_pos = 0; std::cin >> s; str_length = strlen(s); for (int i = 1; i < str_length; i-=-1) { int count = 0; for (int j = 1; i - j >= 0 && i + j < str_length; j-=-1) { if (s[i - j] == s[i + j]) { count-=-1; } else { break; } } int cur_length = 2 * count + 1; if(cur_length > max_length){ max_length = cur_length; pal_pos = i - count; } } for (int i = 0; i + 1 < str_length; i-=-1) { if (s[i] == s[i + 1]) { int count = 0; for (int j = 1; i - j >= 0 && i + 1 + j < str_length; j-=-1){ if (s[i - j] == s[i + 1 + j]) { count-=-1; } else { break; } } int cur_length = 2 * count + 2; if (cur_length > max_length || (cur_length == max_length && i - count < pal_pos)) { max_length = cur_length; pal_pos = i - count; } } } for (int i = 0; i < max_length; i-=-1) { std::cout << s[pal_pos + i]; } std::cout << std::endl; return 0; }
true
93d191c8a4781ac26a8c6a216805571cead48bd9
C++
NguyenVanTu1601/THCS2
/Contest6/BaiB.cpp
UTF-8
1,052
2.546875
3
[]
no_license
#include<iostream> #include<bits/stdc++.h> using namespace std; int snt(int i){ if(i < 2) return 0; if(i == 2) return 1; if(i > 2) { for(int j = 2; j <= sqrt(i); j++){ if(i % j == 0) return 0; } return 1; } } main(){ int dem = 0; long long arr[405]; for(int i = 2; i <= 2800; i++){ if(snt(i) == 1){ arr[dem] = i; dem++; if(dem > 400) break; } } int t; cin >> t; int z = 1; while(t -- ){ int n; cin >> n; long long a[n+1][n+1]; int d = 0; int gt = 0; int hang = n - 1; int cot = n - 1; while(d<=n/2){ for(int i=d;i<=cot;i++) { a[d][i]=arr[gt]; gt++; } for(int i=d+1;i<=hang;i++) { a[i][cot]=arr[gt]; gt++; } for(int i=cot-1;i>=d;i--){ a[hang][i]= arr[gt]; gt++; } for(int i=hang-1;i>d;i--) { a[i][d]= arr[gt]; gt++; } d++; hang--; cot--; } cout <<"Test " << z << ":" << endl; z++; for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ cout << a[i][j] << " "; } cout << endl; } } return 0; }
true
2568b0b0fb24ce7245d84de86a3f028969d6d848
C++
wuzhuorui/cpp_study
/public_protected_private.cpp
UTF-8
1,717
3.515625
4
[]
no_license
class BaseClass { public: int public_int; private: int private_int; protected: int protected_int; }; class DerivedClass :public BaseClass { public: void UsePublicInt() { public_int = 1; //正确 } void UserPrivateInt() { private_int = 1;//错误:成员 BaseClass::private_int不可访问 } void UserProtectedInt() { protected_int = 1; //正确 } }; //protected 对ProtectedDerivedClass的派生类和用户和友元函数产生影响,对ProtectedDerivedClass自身的成员函数无影响 class ProtectedDerivedClass :protected BaseClass { public: void UsePublicInt() { public_int = 1; //正确 BaseClass::public_int是公有的 } void UserPrivateInt() { private_int = 1;//错误:成员 BaseClass::private_int不可访问 } void UserProtectedInt() { protected_int = 1; //正确 } }; int main() { BaseClass baseclass; baseclass.public_int; //正确 baseclass.protected_int; //错误:成员 BaseClass::protected_int不可访问 baseclass.private_int; //错误:成员 BaseClass::private_int不可访问 DerivedClass derivedclass; derivedclass.public_int; //正确 derivedclass.protected_int; //错误:成员 BaseClass::protected_int不可访问 derivedclass.private_int; //错误:成员 BaseClass::private_int不可访问 ProtectedDerivedClass protectedderivedclass; protectedderivedclass.public_int = 1;//错误:成员 BaseClass::public_int不可访问 原因 ProtectedDerivedClass :protected DerivedClass,对ProtectedDerivedClass的用户而言public_int是protectd,所以无法访问 protectedderivedclass.protected_int; //错误:成员 BaseClass::protected_int不可访问 protectedderivedclass.private_int; //错误:成员 BaseClass::private_int不可访问 }
true
532d2b2707f540213fc8f8525a669cf76a275148
C++
FHead/JetMETAnalysis
/JetUtilities/interface/ProgressBar.hh
UTF-8
1,321
3.265625
3
[]
no_license
#include <iostream> #include <iomanip> #include <string> #include <math.h> using std::cout; using std::endl; using std::flush; using std::setw; using std::string; using std::remainder; const int r = 100; inline void loadbar2(unsigned int x, unsigned int n, unsigned int w = 50, string prefix = "") { if ( (x != n) && ((n >= 100) && x % (n/100) != 0) ) return; float ratio = x/(float)n; int c = ratio * w; cout << prefix << setw(3) << (int)(ratio*100) << "% ["; for (int x=0; x<c; x++) cout << "="; for (unsigned int x=c; x<w; x++) cout << " "; cout << "] (" << x << "/" << n << ")\r" << flush; } inline void loadbar3(unsigned int x, unsigned int n, unsigned int w = 50, string prefix = "") { if ( (x != n) && ((n >= 10000) && x % (n/10000) != 0) ) return; //// round to nearest r //unsigned int ntmp = n/10000; //ntmp += r/2; // 1: Add r/2. //ntmp /= r; // 2: Divide by r. //ntmp *= r; // 3: Multiply by r //if ( (x != n) && (remainder(x,ntmp) != 0) ) return; float ratio = x/(float)n; int c = ratio * w; cout << prefix << std::fixed << setw(8) << std::setprecision(2) << (ratio*100) << "% ["; for (int x=0; x<c; x++) cout << "="; for (unsigned int x=c; x<w; x++) cout << " "; cout << "] (" << x << "/" << n << ")\r" << flush; }
true
764f813923ab196ce918f54895fecd805ed0766c
C++
discoverfly/ACM_template
/string/ELFhash.cpp
UTF-8
748
2.78125
3
[]
no_license
class hash_table { public: unsigned int ELFhash(char *key) { unsigned int h = 0, g; while (*key) { h = (h << 4) + *key++; g = h & 0xf0000000L; if (g) h ^= g >> 24; h &= ~g; } return h % MOD; } int find(char * str, int judge = 0) { int t = ELFhash(str); for (hashCell * i = g[t]; i != NULL; i = i->next) if (!strcmp(i->str, str)) return i->p = judge ? i->p + 1: i->p; return 0; } void insert(char* str, int p) { if(find(str, 1)) return; unsigned t = ELFhash(str); strcpy(pp->str, str); pp->p = p; pp->next = g[t]; g[t] = pp++; } private: const static int MOD = 387173; const static int SIZE = 380001; struct hashCell { char str[20]; int p; hashCell * next; } pool[SIZE], *g[MOD], *pp; };
true
936d5dc8052020ad6ff18de40e42616d119e7e94
C++
ngahumwangi/Hackrank_Solutions
/vectors.cpp
UTF-8
1,096
3.265625
3
[]
no_license
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int num_of_arrays, num_of_queries, array_lengh, array_values, query_value_1, query_value_2; vector<vector<int>> vec; vector<int> temp; cin >> num_of_arrays >> num_of_queries; //read the values of arraries for (int i = 0; i < num_of_arrays; i++) { cin >> array_lengh; for (int j = 0; j < array_lengh; j++) { cin >> array_values; temp.push_back(array_values); } //Creating 2D array vec.push_back(temp); temp.resize(0); } /******Queries section*******/ for (int i = 0; i < num_of_queries; i++) { cin >> query_value_1 >> query_value_2; cerr << query_value_1 << query_value_2; temp.push_back(vec[query_value_1][query_value_2]); } //Print output for (int i = 0; i < num_of_queries; i++) { cout << temp[i] << endl; } return 0; }
true
3bfc249c68f8aa82c0e8f59290201037875b4ae0
C++
flores-jacob/exercism
/cpp/roman-numerals/roman_numerals.h
UTF-8
2,070
3.703125
4
[]
no_license
#include <string> namespace roman { std::string convert(int input) { std::string output_roman_numeral; int thousands = input / 1000; int hundreds = (input - (thousands * 1000)) /100; int tens = (input - (thousands * 1000) - (hundreds * 100))/ 10; int ones = input - (thousands * 1000) - (hundreds * 100) - (tens * 10); std::string thousands_portion(thousands, 'M'); std::string hundreds_portion; switch(hundreds){ case 1: hundreds_portion = "C"; break; case 2: hundreds_portion = "CC"; break; case 3: hundreds_portion = "CCC"; break; case 4: hundreds_portion = "CD"; break; case 5: hundreds_portion = "D"; break; case 6: hundreds_portion = "DC"; break; case 7: hundreds_portion = "DCC"; break; case 8: hundreds_portion = "DCCC"; break; case 9: hundreds_portion = "CM"; break; }; std::string tens_portion; switch(tens){ case 1: tens_portion = "X"; break; case 2: tens_portion = "XX"; break; case 3: tens_portion = "XXX"; break; case 4: tens_portion = "XL"; break; case 5: tens_portion = "L"; break; case 6: tens_portion = "LX"; break; case 7: tens_portion = "LXX"; break; case 8: tens_portion = "LXXX"; break; case 9: tens_portion = "XC"; break; }; std::string ones_portion; switch(ones){ case 1: ones_portion = "I"; break; case 2: ones_portion = "II"; break; case 3: ones_portion = "III"; break; case 4: ones_portion = "IV"; break; case 5: ones_portion = "V"; break; case 6: ones_portion = "VI"; break; case 7: ones_portion = "VII"; break; case 8: ones_portion = "VIII"; break; case 9: ones_portion = "IX"; break; }; return thousands_portion + hundreds_portion + tens_portion + ones_portion; }; };
true
6e3c44563346787f48b9a73de5610659b8d694bd
C++
Hachimori/onlinejudge
/uva/11100-/11185.cc
UTF-8
403
3.296875
3
[]
no_license
#include<iostream> #include<vector> using namespace std; int num; bool read(){ cin >> num; return num>=0; } void work(){ if(num==0){ cout << 0 << endl; return; } vector<int> digit; while(num>0){ digit.push_back(num%3); num /= 3; } for(int i=digit.size()-1;i>=0;i--) cout << digit[i]; cout << endl; } int main(){ while(read()) work(); return 0; }
true
4e222d454cc3682411eb829c14407a97472cb2b5
C++
AndroidStudySociety/cpp_demo
/Cplusplusext.cpp
UTF-8
1,244
3.28125
3
[]
no_license
// // Created by Jesson on 2019/12/1. // #include "Cplusplusext.h" #include <iostream> #include <iomanip> #include <cstring> using namespace std; int iabs(int a){ return a>0?a:-a; } double fabs(double a){ return a>0?a:-a; } //==============操作符重载 struct COMP{ float real; float image; }; COMP operator+(COMP one,COMP two){ one.real += two.real; one.image += two.image; return one; } int main() { //开始学习 char name[30]; int age; cout<<"pls input your name:"<<endl; // cin>>name; // cin>>age; cout<<"your name is: "<<name<<endl; cout<<"your age is: "<<age<<endl; //输出 printf("%c\n%d\n%f\n",'1',100,200.00); printf("%5c\n%5d\n%6.3f\n",'1',100,200.00); //进制输出 int i= 100; cout<<i<<endl; cout<<dec<<i<<endl; cout<<hex<<i<<endl; cout<<oct<<i<<endl; cout<<setbase(16)<<i<<endl; cout<<setw(10)<<1123<<endl; cout<<setw(10)<<setfill('w')<<1123<<endl; cout<<setw(10)<<setfill('w')<<setiosflags(ios::right)<<1123<<endl; //测试运算符重载 COMP one = {1,2}; COMP two = {100,200}; COMP result = operator+(one,two); cout<<result.image<<"====="<< result.real<<endl; return 0; }
true
0eb64daddcc8e80aebe992e1add43da36c73ab27
C++
lyswty/PAT-Advanced-Level-Solutions
/1089/1089 Insert or Merge (25 分).cpp
UTF-8
914
2.890625
3
[]
no_license
#include<iostream> #include<algorithm> #include<vector> #include<cmath> using namespace std; int main() { int n; bool ins = true; cin >> n; vector<int>a(n), b(n); for (int i = 0; i < n; i++) cin >> a[i]; for (int i = 0; i < n; i++) cin >> b[i]; int i; for (i = 1; i < n; i++) if (b[i] < b[i - 1]) break; for (int j = i; j < n; j++) if (a[j] != b[j]) ins = false; if (ins) { cout << "Insertion Sort" << endl; sort(b.begin(), b.begin() + i + 1); } else { cout << "Merge Sort" << endl; int min = n, cur = 1; for (int i = 1; i < n; i++) { if (b[i] >= b[i - 1]) cur++; else { if (cur < min) min = cur; cur = 1; } } min *= 2; int j; for (j = 0; j + min <= n; j += min) sort(b.begin() + j, b.begin() + j + min); if (j < n - 1) sort(b.begin() + j, b.end()); } for (int i = 0; i < n; i++) { cout << b[i]; if (i != n - 1) cout << ' '; } system("pause"); return 0; }
true
0f4237a2fadde23f1b9e0b628f2d1eee62001a8b
C++
vraxzeztan/Hackerrank-GFG-Practice-Codes
/Linked Lists/Insertion_Sorted_Circular_LL.cpp
UTF-8
2,955
3.859375
4
[]
no_license
#include<bits/stdc++.h> /* structure for a Node */ struct Node { int data; struct Node *next; }; void sortedInsert(struct Node**head_ref, int x); /* function to insert a new_Node in a list in sorted way. Note that this function expects a pointer to head Node as this can modify the head of the input linked list */ /* Function to print Nodes in a given linked list */ void printList(struct Node *start) { struct Node *temp; if(start != NULL) { temp = start; do { printf("%d ", temp->data); temp = temp->next; } while(temp != start); printf(""); } } /* Driver program to test above functions */ int main() { int t,n,x; scanf("%d",&t); int arr; while(t--){ scanf("%d",&n); int list_size, i; /* start with empty linked list */ struct Node *start = NULL; struct Node *temp,*r; /* Create linked list from the array arr[]. Created linked list will be 1->2->11->56->12 */ if(n>0){ scanf("%d",&arr); temp = (struct Node *)malloc(sizeof(struct Node)); temp->data=arr; temp->next=NULL; start=temp; r=start;} for (i = 0; i<n-1; i++) { scanf("%d",&arr); temp = (struct Node *)malloc(sizeof(struct Node)); temp->data = arr; temp->next=NULL; r->next=temp; r=r->next; } if(n>0) temp->next=start; // printList(start); scanf("%d",&x); sortedInsert(&start,x); printList(start); r=start; while(r!=start->next) { temp=start; start=start->next; free(temp); } free(start); } return 0; } /*Please note that it's Function problem i.e. you need to write your solution in the form of Function(s) only. Driver Code to call/invoke your function is mentioned above.*/ /* structure for a node */ /* struct Node { int data; Node *next; }; */ #include<iostream> using namespace std; void sortedInsert(Node** head_ref, int x) { //Your code here struct Node*head=*head_ref; if(!head) return ; // what if the insertion took place at the head only! if(head->data>x){ // find the tail struct Node*tail=head; while(tail->next!=head) { tail=tail->next; } struct Node*n=new Node; n->data=x;//due to the given question; n->next=head; tail->next=n; head=n; head_ref=&head; return;// this can happen since pointers are passed. } struct Node*prev=NULL; struct Node*curr=head; while(curr->next!=head && curr->data<=x){ prev=curr; // cout<<"current's data is : "<<curr->data<<endl; curr=curr->next; } struct Node*newNode=new Node; newNode->data=x; //case 1: when we reached the end of the Linked List and now we have to insert at all costs if(curr->next==head && x>curr->data) { //cout<<"here"<<endl; curr->next=newNode; newNode->next=head;} else{ //simple insertion prev->next=newNode; newNode->next=curr; } }
true
b445d29a9fef130b07df6c7cda340003c73382be
C++
kyung221/cse2022
/소스.cpp
UTF-8
4,153
3.171875
3
[]
no_license
#include <GLFW/glfw3.h> #include <cstring> #include <stdlib.h> // srand, rand #include <thread> // std::this_thread::sleep_for #include <chrono> // std::chrono::seconds #include "math.h" const int width = 640; const int height = 480; float* pixels = new float[width*height * 3]; void drawPixel(const int& i, const int& j, const float& red, const float& green, const float& blue) { pixels[(i + width* j) * 3 + 0] = red; pixels[(i + width* j) * 3 + 1] = green; pixels[(i + width* j) * 3 + 2] = blue; } // scratched from https://courses.engr.illinois.edu/ece390/archive/archive-f2000/mp/mp4/anti.html // see 'Rasterization' part. void drawLine(const int& i0, const int& j0, const int& i1, const int& j1, const float& red, const float& green, const float& blue) { if (i0 == i1) { for (int j = j0; j < j1; j++) drawPixel(i0, j, red, green, blue); return; } for (int i = i0; i <= i1; i++) { const int j = (j1 - j0)*(i - i0) / (i1 - i0) + j0; drawPixel(i, j, red, green, blue); } } void drawOnPixelBuffer() { //std::memset(pixels, 1.0f, sizeof(float)*width*height * 3); // doesn't work std::fill_n(pixels, width*height * 3, 1.0f); // white background //for (int i = 0; i<width*height; i++) { // pixels[i * 3 + 0] = 1.0f; // red // pixels[i * 3 + 1] = 1.0f; // green // pixels[i * 3 + 2] = 1.0f; // blue //} const int i = rand() % width, j = rand() % height; drawPixel(i, j, 0.0f, 0.0f, 0.0f); // drawing a line //TODO: anti-aliasing for(int i0=50 ; i0<=55 ; i0++) { for (int i1 = 200; i1 <= 205; i1++) { for (int j0 = 150; j0 <= 155; j0++) { for (int j1 = 280; j1 <= 285; j1++) drawLine(i0, i1, j0, j1, 1.0f, 0.0f, 0.0f); } } } drawLine(50, 50, 75, 100, 1.0f, 0.0f, 0.0f); drawLine(75, 100, 100, 50, 1.0f, 0.0f, 0.0f); drawLine(50, 50, 100, 50, 1.0f, 0.0f, 0.0f); //triangle drawLine(200, 50, 250, 50, 1.0f, 0.0f, 0.0f); drawLine(170, 100, 200, 50, 1.0f, 0.0f, 0.0f); drawLine(170, 100, 225, 150, 1.0f, 0.0f, 0.0f); drawLine(225, 150, 280, 100, 1.0f, 0.0f, 0.0f); drawLine(250, 50, 280, 100, 1.0f, 0.0f, 0.0f); //pentagon drawLine(170, 200, 250, 200, 1.0f, 0.0f, 0.0f); drawLine(170, 200, 170, 280, 1.0f, 0.0f, 0.0f); drawLine(170, 280, 250, 280, 1.0f, 0.0f, 0.0f); drawLine(250, 200, 250, 280, 1.0f, 0.0f, 0.0f); //rectangle const int i_center = 400, j_center = 250; const int thickness = 45; for(int j=j_center-thickness;j<j_center+thickness;j++) for (int i = i_center - thickness; i < i_center + thickness; i++) { drawPixel(i, j, 1.0f, 0.0f, 0.0f); } for (int a = 0; a < width; a++) { for (int b = 0; b < height; b++) { const int c1 = 400, c2 = 70; const int r = 50; if (sqrt((c1-a)*(c1-a) + (c2-b)*(c2-b)) < r) drawPixel(a, b, 1.0f, 0.0f, 0.0f); if (sqrt((400 - a)*(400 - a) + (70 - b)*(70 - b)) < 48) drawPixel(a, b, 1.0f, 1.0f, 1.0f); } } //TODO: try moving object } int main(void) { GLFWwindow* window; /* Initialize the library */ if (!glfwInit()) return -1; /* Create a windowed mode window and its OpenGL context */ window = glfwCreateWindow(width, height, "Hello World", NULL, NULL); if (!window) { glfwTerminate(); return -1; } /* Make the window's context current */ glfwMakeContextCurrent(window); glClearColor(1, 1, 1, 1); // while background /* Loop until the user closes the window */ while (!glfwWindowShouldClose(window)) { /* Render here */ //glClear(GL_COLOR_BUFFER_BIT); drawOnPixelBuffer(); //TODO: RGB struct //Make a pixel drawing function //Make a line drawing function glDrawPixels(width, height, GL_RGB, GL_FLOAT, pixels); /* Swap front and back buffers */ glfwSwapBuffers(window); /* Poll for and process events */ glfwPollEvents(); std::this_thread::sleep_for(std::chrono::milliseconds(100)); } glfwTerminate(); delete[] pixels; // or you may reuse pixels array return 0; }
true
dc0ef498e79686fe5f5e26fc0f45f5783beb939a
C++
GabrielVantuil/GabrielVantuil.github.io
/projects/pdi/3.2/3.2.2/labeling_3.2.2.cpp
UTF-8
2,370
2.5625
3
[]
no_license
#include <iostream> #include <opencv2/opencv.hpp> using namespace cv; using namespace std; int main(int argc, char** argv){ Mat image, mask,out; int width, height; int nobjects=0, nobj_buraco=0; int r=0,g=0,b=0; CvPoint p; image = imread(argv[1],CV_LOAD_IMAGE_GRAYSCALE); cvtColor(image, out, CV_GRAY2RGB); if(!image.data) cout << "nao abriu " <<argv[1]<< endl; width=image.size().width; height=image.size().height; p.x=0; p.y=0; //--------------------------- limpa bordas for(int i=0; i<height; i++) if( (out.at<Vec3b>(i,0)[0] == 255)&& (out.at<Vec3b>(i,0)[1] == 255)&& (out.at<Vec3b>(i,0)[2] == 255) || (out.at<Vec3b>(i,0)[0] == 255)&& (out.at<Vec3b>(i,0)[1] == 255)&& (out.at<Vec3b>(i,0)[2] == 255)){ p.x=0; p.y=i; floodFill(out,p,CV_RGB(0,0,0)); } for(int j=0; j<width; j++) if( (out.at<Vec3b>(0,j)[0] == 255)&& (out.at<Vec3b>(0,j)[1] == 255)&& (out.at<Vec3b>(0,j)[2] == 255) || (out.at<Vec3b>(0,j)[0] == 255)&& (out.at<Vec3b>(0,j)[1] == 255)&& (out.at<Vec3b>(0,j)[2] == 255)){ p.x=j; p.y=0; floodFill(out,p,CV_RGB(0,0,0)); } //--------------------------- nobjects=0; for(int i=0; i<height; i++) for(int j=0; j<width; j++) if( (out.at<Vec3b>(i,j)[0] == 255)&& (out.at<Vec3b>(i,j)[1] == 255)&& (out.at<Vec3b>(i,j)[2] == 255)){ p.x=j; p.y=i; nobjects++; r= nobjects%255; g=(nobjects/255)%255; b= nobjects/(255*255); floodFill(out,p,CV_RGB(r,g,b));//todos obj } p.x=0; p.y=0; floodFill(out,p,CV_RGB(100,100,100));//fundo for(int i=0; i<height; i++) for(int j=0; j<width; j++) if( (out.at<Vec3b>(i,j)[0] == 0)&& (out.at<Vec3b>(i,j)[1] == 0)&& (out.at<Vec3b>(i,j)[2] == 0)){ p.x=j; p.y=i; floodFill(out,p,CV_RGB(254,254,254));//buracos dentro de objetos nobj_buraco++; } cout<<"\nObjetos sem buracos "<<nobjects-nobj_buraco<<endl; cout<<"\nObjetos com buracos "<<nobj_buraco<<endl; imshow("image", image); waitKey(); imshow("saida", out); imwrite("resultado.png",out); waitKey(); return 0; }
true
de1e9287fa49245baaf4008fea3b95cf0a4a4f31
C++
ldg0005/boj
/1920(list,hashing).cpp
UTF-8
1,207
2.984375
3
[]
no_license
#include <stdio.h> #define MOD 1000003 typedef struct List { typedef struct Node { Node *next; int cost; int exist; Node() :cost(0) { next = nullptr; } }; Node *head, *tail; int size; List() :size(0) { head = new Node(); tail = new Node(); } void push(int cost) { Node *newnode = new Node(); newnode->cost = cost; if (head->next == nullptr) { head->next = newnode; tail = newnode; } else { tail->next = newnode; tail = tail->next; } size++; } bool find(int a) { Node *tmp = head; while (tmp->next != nullptr) { tmp = tmp->next; if (tmp->cost == a) return true; } return false; } void clear() { Node *tmp = head; while (tmp->next != nullptr) { Node *del = tmp->next; tmp->next = del->next; delete del; } } }; List table[MOD]; int N, M; inline int hashing(int a) { if (a < 0) a = -a; int ret=0; ret = a%MOD; return ret; } int main() { freopen("1920.txt", "r", stdin); scanf("%d", &N); int temp; for (int i = 0; i < N; i++) { scanf("%d", &temp); table[hashing(temp)].push(temp); } scanf("%d", &M); for (int i = 0; i < M; i++) { scanf("%d", &temp); printf("%d\n", table[hashing(temp)].find(temp)); } }
true
7d370cd99d25d59fd2612887c5804ad8c7ca1bed
C++
deltaduong/area-measurement
/selection.h
UTF-8
1,220
2.640625
3
[ "MIT" ]
permissive
#ifndef SELECTION_H #define SELECTION_H #include <QLineF> #include <QPolygonF> class Figure; struct Selection { enum Type { FIGURE, VERTEX, INSCRIPTION }; Figure* figure; Type type; int iVertex; Selection(); void clear(); void setFigure(Figure* figure__); void setVertex(Figure* figure__, int iVertex__); void setInscription(Figure* figure__); bool operator==(const Selection& other); bool operator!=(const Selection& other); bool isEmpty() { return !figure; } // bool isDraggable() const; void dragTo(QPointF newPos); private: void assign(Figure* figure__, Type type__, int iVertex__ = -1); }; class SelectionFinder { public: SelectionFinder(QPointF cursorPos); void testPolygon(QPolygonF polygon, Figure* figure); void testPolyline(QPolygonF polyline, Figure* figure); void testVertex(QPointF vertex, Figure* figure, int iVertex); void testInscription(QRectF boundingRect, Figure* figure); //bool hasSelection() const { return bestScore_ > 0.; } const Selection& bestSelection() const { return bestSelection_; } private: QPointF cursorPos_; Selection bestSelection_; double bestScore_; }; #endif // SELECTION_H
true
593e5810f956c39a1a00ce39038b25a361072316
C++
1337bugs/fb-labs-2019
/cp_2/skuratov_fb_74_demidenko_fb_72_cp_2/lab2.cpp
UTF-8
6,289
2.671875
3
[]
no_license
#include <iostream> #include <fstream> #include <math.h> #include <string> #include <map> using namespace std; string alphabet = "абвгдежзийклмнопрстуфхцчшщъыьэюя"; // без пробела string keygood; int count_letter = 0; int count_vzlom = 0; int letter_max = 0; double index_sum; double index(int size, string txt); int ciphers(char* txtq, string k2, int size); int vzlomm(string text, int a); int key(int size, string txt); int main() { setlocale(LC_ALL, "Russian"); string k2 = "до"; string k3 = "дух"; string k5 = "каска"; string k9 = "аллегория"; string k12 = "проспектлень"; string k15 = "скуратовильяста"; string k19 = "ялюблюсвоюмамуочень"; char file[] = "C:\\2.txt"; // текст char vzlom[] = "C:\\1.txt"; // текст ifstream go(vzlom); while (!go.eof()) { go.get(); count_vzlom++; } go.close(); char* vzl = new char[count_vzlom]; for (int i = 0; i < count_vzlom; i++) { vzl[i] = NULL; // заполняем нулями } ifstream goo(vzlom); int q = 0; while (!goo.eof()) { goo.get(vzl[q]); q++; } goo.close(); string u(vzl); ifstream in(file); while (!in.eof()) { in.get(); count_letter++; } in.close(); ifstream inn(file); char* mass = new char[count_letter]; for (int i = 0; i < count_letter; i++) { mass[i] = NULL; // заполняем нулями } ifstream in2(file); int i = 0; while (!in2.eof()) { char letter; in2.get(mass[i]); mass[i] = tolower(mass[i]); // в строчные if (alphabet.find(mass[i]) != -1) { i++; } else { mass[i] = NULL; count_letter--; } } in2.close(); char* mass2 = new char[count_letter]; for (int i = 0; i < count_letter; i++) { mass2[i] = NULL; } for (int i = 0; i < count_letter; i++) { mass2[i] = mass[i]; } string aa(mass2); cout << "Index for open text" << " = " << index(count_letter, aa) << endl<<endl; cout << "index for k2 : "; ciphers(mass2, k2, count_letter); cout << "index for k3 : "; ciphers(mass2, k3, count_letter); cout << "index for k5 : "; ciphers(mass2, k5, count_letter); cout << "index for k9 : "; ciphers(mass2, k9, count_letter); cout << "index for k12 : "; ciphers(mass2, k12, count_letter); cout << "index for k15 : "; ciphers(mass2, k15, count_letter); cout << "index for k19 : "; ciphers(mass2, k19, count_letter); cout << endl << endl; int a = 2; while (a < 31) { vzlomm(u, a); a++; } cout << endl << endl << "KEY: " << keygood<<endl; return 0; } double index(int size, string txt) { setlocale(LC_ALL, "Russian"); double sum = 0; int p = 0; int mo = -1; char* monogr = new char[size]; double index; for (int i = 0; i < size; i++) { mo++; monogr[mo] = NULL; int letter = 0; monogr[mo] = txt[i]; if (monogr[mo] != NULL) { for (int j = i; j < size; j++) { if (txt[j] == monogr[mo]) { letter++; } } index = (double(letter) * (double(letter) - 1)) / (double(size) * (double(size) - 1)); sum += index; //суммируем for (int z = i; z < size; z++) { if (txt[z] == monogr[mo]) txt[z] = NULL; } } } return sum; } int ciphers (char* txtq, string shifr, int size) { int l = std::size(shifr); int* mass = new int[size]; int* mass2 = new int[l]; int* mass3 = new int[size]; string shifro; char* k_ciphers = new char[size]; for (int i = 0; i < size; i++) { k_ciphers[i] = '\0'; // заполняем нулями } setlocale(LC_ALL, "Russian"); // массив с нашим текстом нумерация for (int i = 0; i < size; i++) { int j = 0; while (txtq[i] != alphabet[j]) { j++; } mass[i] = j; // cout << mass[i]<<" "; } //массив с ключем нумерация for (int i = 0; i < l; i++) { int j = 0; while ( shifr[i] != alphabet[j]) { j++; } mass2[i] = j; //cout << mass2[i] << " "; } // массив шифрованных букв for (int i = 0; i < size; i++) { mass3[i] = (mass[i] + mass2[i%l]) % 32; //cout << mass3[i]<<" "; } // массив с нашим текстом нумерация for (int i = 0; i < size; i++) { int k = 0; k = mass3[i]; k_ciphers[i] = alphabet[k]; //cout << k_ciphers[i] << " "; } k_ciphers[size] = '\0'; string gg(k_ciphers); //cout << k_ciphers; cout<<index(size, gg)<<endl; return 0; } int vzlomm(string text, int a) { setlocale(LC_ALL, "Russian"); map<int, string>z; for (int i = 0; i < a; i++) { z.emplace(i, "0"); } int b = 0; int j = 0; int v; int size = text.length(); string stud; //cout << size<<endl; for (int q = 0; q < a; q++) { stud.erase(); for (int i = q; i < size; i+=a) { if (text[i] != '\0') { stud.push_back(text[i]); } } z.at(q) = stud; } int r = 0; ////////////////// double sum = 0 ; for (int i = 0; i < a; i++) { r = z.at(i).length(); sum+=index(r, z.at(i)); //cout << "Index for " << a << " = " << index(r, z.at(i)) << endl; } cout<<"Index for "<<a<<" = "<< sum / a<<endl; if (a == 14) { for (int i = 0; i < a; i++) { int n = z.at(i).length(); key(n, z.at(i)); } } return 0; } int key(int size, string txt) { int count_max = 0; int count; int mesto; for (int j = 0; j < 32; j++) { count = 0; for (int i = 0; i < size; i++) { if (txt[i] == alphabet[j]) { count++; } } if (count > count_max) { count_max = count; mesto = j; } } //cout << mesto << endl << endl; int o_mesto = 14; int otvet_o = 0; otvet_o = abs(o_mesto - mesto); keygood.push_back(alphabet[otvet_o]); return 0; }
true
b4213516e831492af3dc86b33e50d7ec628afdae
C++
ruisleipa/kp2
/src/simulation/dynamometer.hpp
UTF-8
623
2.59375
3
[]
no_license
#ifndef SERVER_DYNAMOMETER_HPP #define SERVER_DYNAMOMETER_HPP #include "utils/curve.hpp" #include "vehicle.hpp" #include "vehiclesimulation.hpp" class Dynamometer { public: void run(); const Curve& getTorqueData(); const Curve& getPowerData(); const Curve& getIntakeData(); const Curve& getExhaustData(); const Curve& getBoostData(); const Curve& getIntakeTemperatureData(); Dynamometer(Vehicle& vehicle); private: VehicleSimulation simulation; Curve torqueData; Curve powerData; Curve intakeData; Curve exhaustData; Curve boostData; Curve intakeTemperatureData; }; #endif
true
1de89cd64906cb8594614ef20169420556ca7f7b
C++
primetong/LearningCollectionOfWitt
/2017.DigitalImageProcessing/ImgStiching/图像拼接小DEMO(只有直接拼接的).cpp
GB18030
2,548
2.546875
3
[ "MIT" ]
permissive
#include <opencv2/opencv.hpp> //#include<opencv2/nonfree/nonfree.hpp> //#include<opencv2/legacy/legacy.hpp> #include <opencv2/xfeatures2d.hpp> //#include<vector> //#include <iostream> //#include <iomanip> //#include "opencv2/core/core.hpp" //#include "opencv2/objdetect/objdetect.hpp" //#include "opencv2/features2d/features2d.hpp" #include "opencv2/highgui/highgui.hpp" //#include "opencv2/calib3d/calib3d.hpp" //#include "opencv2/imgproc/imgproc_c.h" using namespace std; using namespace cv; int main(){ Mat leftImg = imread("left.jpg"); Mat rightImg = imread("right.jpg"); if (leftImg.data == NULL || rightImg.data == NULL) return 0; //תɻҶͼ Mat leftGray; Mat rightGray; cvtColor(leftImg, leftGray, CV_BGR2GRAY); cvtColor(rightImg, rightGray, CV_BGR2GRAY); //**************Create SIFT class pointer Ptr<Feature2D> f2d = xfeatures2d::SIFT::create(); //***************Detect the keypoints,ȡ vector<KeyPoint> keypoints_left, keypoints_right; f2d->detect(leftGray, keypoints_left); f2d->detect(rightGray, keypoints_right); //***************Calculate descriptors (feature vectors),ȡ Mat descriptors_left, descriptors_right; f2d->compute(leftGray, keypoints_left, descriptors_left); f2d->compute(rightGray, keypoints_right, descriptors_right); FlannBasedMatcher matcher; vector<DMatch> matches; /* ٽƥ */ matcher.match(descriptors_left, descriptors_right, matches); int matchCount = descriptors_left.rows; if (matchCount>15) { matchCount = 15; //sort(matches.begin(),matches.begin()+descriptors_left.rows,DistanceLessThan); sort(matches.begin(), matches.begin() + descriptors_left.rows); } vector<Point2f> leftPoints; vector<Point2f> rightPoints; for (int i = 0; i < matchCount; i++) { leftPoints.push_back(keypoints_left[matches[i].queryIdx].pt); rightPoints.push_back(keypoints_right[matches[i].trainIdx].pt); } //ȡͼұͼͶӰӳϵ Mat homo = findHomography(leftPoints, rightPoints); Mat shftMat = (Mat_<double>(3, 3) << 1.0, 0, leftImg.cols, 0, 1.0, 0, 0, 0, 1.0); //ƴͼ Mat tiledImg; warpPerspective(leftImg, tiledImg, shftMat*homo, Size(leftImg.cols + rightImg.cols, rightImg.rows)); rightImg.copyTo(Mat(tiledImg, Rect(leftImg.cols, 0, rightImg.cols, rightImg.rows))); //ͼ imwrite("tiled.jpg", tiledImg); //ʾƴӵͼ imshow("tiled image", tiledImg); waitKey(0); return 0; }
true
14c49b5199f1040aef3615607c3458fd6d1deb9d
C++
dkonigsberg/mediaserviceutility
/src/media/FileType.cpp
UTF-8
1,000
2.65625
3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
#include "FileType.hpp" namespace bbext { namespace multimedia { FileType::FileType() { } FileType::~FileType() { } QDebug operator<<(QDebug dbg, const FileType::Type &fileType) { switch(fileType) { case FileType::Unknown: dbg << "FileType::Unknown"; break; case FileType::Audio: dbg << "FileType::Audio"; break; case FileType::Video: dbg << "FileType::Video"; break; case FileType::AudioVideo: dbg << "FileType::AudioVideo"; break; case FileType::Photo: dbg << "FileType::Photo"; break; case FileType::Device: dbg << "FileType::Device"; break; case FileType::Document: dbg << "FileType::Document"; break; case FileType::Other: dbg << "FileType::Other"; break; default: dbg << "FileType::Type(" << int(fileType) << ')'; break; } return dbg.maybeSpace(); } } // namespace multimedia } // namespace bbext
true
a7c53b8ec98ba4af3754239207872652bcf64c4e
C++
bluemix/Online-Judge
/POJ/2540 Hotter Colder.cpp
UTF-8
5,205
3.21875
3
[]
no_license
/* 14152374 840502 2540 Accepted 208K 0MS C++ 4384B 2015-05-01 23:01:05 */ #include<bits\stdc++.h> using namespace std; const double PI = acos(-1.0); const double EPS = 1e-9; double isZero(const double &x){ return fabs(x) <= EPS ? x : 0; } int sign(double x){ return fabs(x) < EPS ? 0 : (x > 0 ? 1 : -1); } struct Vector{ double x, y; Vector(){} Vector(double x, double y) :x(x), y(y){} Vector operator + (const Vector &a) { return Vector(x + a.x, y + a.y); } Vector operator - (const Vector &a) { return Vector(x - a.x, y - a.y); } double operator * (const Vector &a) { return x * a.y - y * a.x; } Vector operator * (const double &a){ return Vector(x*a, y*a); } double operator % (const Vector &a) { return x * a.x + y * a.y; } Vector operator / (double a){ return Vector(x / a, y / a); } bool operator == (Vector &a) { return isZero(x - a.x) == 0 && isZero(y - a.y); } Vector unitVector(double a) { a /= sqrt(x*x + y*y); return Vector(x * a, y * a); } double distance(Vector &a) { return sqrt((x - a.x)*(x - a.x) + (y - a.y)*(y - a.y)); } double length(){ return sqrt(x*x + y*y); } Vector leftRotate(double angle){ return Vector(x * cos(angle) - y * sin(angle), x * sin(angle) + y*cos(angle)); } }; struct Line{ Vector a, b; Line(){} Line(Vector a, Vector b) :a(a), b(b){} Line(double a, double b, double c){ if (sign(a) == 0) this->a = Vector(b < 0 ? -1 : 1, -c / b), this->b = Vector(b < 0 ? 1 : -1, -c / b); else if (sign(b) == 0) this->a = Vector(-c / a, a < 0 ? 1 : -1), this->b = Vector(-c / a, a < 0 ? -1 : 1); else if (b < 0) this->a = Vector(0, -c / b), this->b = Vector(1, -(a + c) / b); else this->a = Vector(1, -(a + c) / b), this->b = Vector(0, -c / b); } bool parallel(Line s){ return sign((b - a) * (s.b - s.a)) == 0; } int intersect(Line s, Vector &v){ double a1 = (b - a) * (s.a - a), a2 = (b - a) * (s.b - a); if (sign(a1) == 0 && sign(a2) == 0) return 2; // coincide if (sign(a1 - a2) == 0) return 0; // parallel v.x = (a2 * s.a.x - a1 * s.b.x) / (a2 - a1); v.y = (a2 * s.a.y - a1 * s.b.y) / (a2 - a1); return 1; } double angle(){ return atan2(b.y - a.y, b.x - a.x); } }; Line HP[205], b[205]; Vector P[205]; bool cmp(Line a, Line b){ if (sign(a.angle() - b.angle()) == 0) return (a.a - a.b) * (b.a - a.b) > 0; return a.angle() < b.angle(); } Vector intersection(Line a, Line b){ Vector v; a.intersect(b, v); return v; } int half_plane_cross(Line *a, int n, Vector *p){ sort(a, a + n, cmp); int L = 0, R = 1, m = 1; for (int i = 1; i < n; i++) if (sign(a[i].angle() - a[i - 1].angle()) > 0) a[m++] = a[i]; n = m, m = 0; b[0] = a[0], b[1] = a[1]; for (int i = 2; i < n; i++){ Vector v; if (b[R].parallel(b[R - 1]) || b[L].parallel(b[L + 1])) break; while (L < R && (a[i].a - a[i].b) * (intersection(b[R], b[R - 1]) - a[i].b) > 0) --R; while (L < R && (a[i].a - a[i].b) * (intersection(b[L], b[L + 1]) - a[i].b) > 0) ++L; b[++R] = a[i]; } while (L < R && (b[L].a - b[L].b) * (intersection(b[R], b[R - 1]) - b[L].b) > 0) --R; while (L < R && (b[R].a - b[R].b) * (intersection(b[L], b[L + 1]) - b[R].b) > 0) ++L; b[++R] = b[L]; for (int i = L; i < R; i++) p[m++] = intersection(b[i], b[i + 1]); return m; } int main(){ int n = 0; bool flag = false; char str[100]; double x1, x2, y1, y2; HP[n++] = Line(Vector(0, 0), Vector(10, 0)); HP[n++] = Line(Vector(10, 0), Vector(10, 10)); HP[n++] = Line(Vector(10, 10), Vector(0, 10)); HP[n++] = Line(Vector(0, 10), Vector(0, 0)); x1 = y1 = 0; while (~scanf("%lf%lf%s", &x2, &y2, str)){ double a = x1 - x2; double b = y1 - y2; double c = -(a * (x1 + x2) + b * (y1 + y2)) / 2; if (str[0] == 'C') HP[n++] = Line(-a, -b, -c); else if (str[0] == 'H') HP[n++] = Line(a, b, c); else flag = true; x1 = x2, y1 = y2; double ans = 0; if (!flag){ int m = half_plane_cross(HP, n, P); if (m > 2){ P[m] = P[0]; for (int i = 0; i < m; i++) ans += P[i] * P[i + 1]; } } printf("%.2lf\n", fabs(ans) / 2); } return 0; } /* Hotter Colder Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 2732 Accepted: 1130 Description The children's game Hotter Colder is played as follows. Player A leaves the room while player B hides an object somewhere in the room. Player A re-enters at position (0,0) and then visits various other positions about the room. When player A visits a new position, player B announces "Hotter" if this position is closer to the object than the previous position; player B announces "Colder" if it is farther and "Same" if it is the same distance. Input Input consists of up to 50 lines, each containing an x,y coordinate pair followed by "Hotter", "Colder", or "Same". Each pair represents a position within the room, which may be assumed to be a square with opposite corners at (0,0) and (10,10). Output For each line of input print a line giving the total area of the region in which the object may have been placed, to 2 decimal places. If there is no such region, output 0.00. Sample Input 10.0 10.0 Colder 10.0 0.0 Hotter 0.0 0.0 Colder 10.0 10.0 Hotter Sample Output 50.00 37.50 12.50 0.00 Source Waterloo local 2001.01.27 */
true
23d7339f169a22b4795693547d822e11c5a53c9d
C++
bxl295/m4extreme
/include/External/stlib/packages/shortest_paths/shortest_paths.h
UTF-8
61,975
3.140625
3
[ "BSD-2-Clause" ]
permissive
// -*- C++ -*- #if !defined(__shortest_paths_h__) #define __shortest_paths_h__ #include "GraphBellmanFord.h" #include "GraphDijkstra.h" #include "GraphMCC.h" #include "GraphMCCSimple.h" //============================================================================= //============================================================================= /*! \mainpage Single-Source Shortest Paths - \ref shortest_paths_introduction - \ref shortest_paths_dijkstra - \ref shortest_paths_greedier - \ref shortest_paths_complexity - \ref shortest_paths_performance - \ref shortest_paths_concurrency - \ref shortest_paths_future - \ref shortest_paths_conclusions */ //============================================================================= //============================================================================= /*! \page shortest_paths_introduction Introduction Consider a weighted, directed graph with \e V vertices and \e E edges. Let \e w be the weight function, which maps edges to real numbers. The weight of a path in the graph is the sum of the weights of the edges in the path. Given a vertex \e u, some subset of the vertices can be reached by following paths from \e u. The <em>shortest-path weight</em> from \e u to \e v is the minimum weight path over all paths from \e u to \e v. A <em>shortest path</em> from vertex \e u to vertex \e v is any path that has the minimum weight. Thus the shortest path is not necessarily unique. If there is no path from \e u to \e v then one can denote this by defining the shortest-path weight to be infinite. We consider the <em>single-source shortest-paths problem</em> cite{cormen:2001}: given a graph and a <em>source</em> vertex we want to find the shortest paths to all other vertices. There are several related shortest-paths problems. For the <em>single-destination shortest-paths problem</em> we want to find the shortest paths from all vertices to a given <em>destination</em> vertex. This problem is equivalent to the single-source problem. Just reverse the orientation of the edges. For the <em>single-pair shortest-path problem</em> we want to find the shortest path from a given source vertex to a given destination vertex. One can solve the single-pair problem by solving the single-source problem. Actually, there are no known single-pair algorithms with lower computational complexity than single-source algorithms. Finally, there is the <em>all-pairs shortest-paths problem</em>. For this we want to find the shortest paths between all pairs of vertices. For dense graphs, one typically solves this problem with the Floyd-Warshall algorithm cite{cormen:2001}. For sparse graphs, Johnson's algorithm cite{cormen:2001}, which computes the single-source problem for each vertex, is asymptotically faster. If the graph contains negative weight edges, then the shortest path between two connected vertices may not be well defined. This occurs if there is a negative weight cycle reachable between the source and the destination. Then one can construct a path between the source and the destination with arbitrarily low weight by repeating the negative weight cycle. Some shortest-path algorithms, like the Bellman-Ford algorithm, are able to detect negative weight cycles and then indicate that the shortest-paths problem does not have a solution. Other algorithms, like Dijkstra's algorithm, assume that the edge weights are nonnegative. We will consider only graphs with nonnegative weights. We can represent the shortest-path weights from a given source by storing this value as an attribute in each vertex. The distance of the source is defined to be zero (source.distance = 0), the distance of unreachable vertices is infinite. Some algorithms keep track of the <em>status</em> of the vertices. For the algorithms we will consider, a vertex is in one of three states: \c KNOWN if the distance is known to have the correct value, \c LABELED if the distance has been updated from a known vertex and \c UNLABELED otherwise. The shortest paths form a tree with root at the source. We can represent this tree by having each vertex store a <em>predecessor</em> attribute. The predecessor of a vertex is that vertex which comes directly before it in the shortest path from the source. The predecessor of the source and of unreachable vertices is defined to be the special value \c NONE . Note that while the shortest distance is uniquely defined, the predecessor is not. This is because there may be multiple shortest paths from the source to a given vertex. Below is the procedure for initializing a graph to solve the single-source shortest-paths problem for a specified source vertex. \verbatim initialize(graph, source): for vertex in graph.vertices: vertex.distance = Infinity vertex.predecessor = NONE vertex.status = UNLABELED source.distance = 0 source.status = KNOWN \endverbatim The algorithms that we will consider generate the shortest paths through a process of <em>labeling</em>. At each stage, the distance attribute of each vertex is an upper bound on the shortest-path weight. If the distance is not infinite, then it is the sum of the edge weights on some path from the source. This approximation of the shortest-path weight is improved by <em>relaxing</em> along an edge. For a known vertex, we see if the distance to its neighbors can be improved by going through its adjacent edges. For a \c knownVertex with an adjacent \c edge leading to a \c vertex , if <tt>knownVertex.distance + edge.weight < vertex.distance</tt> then we improve the approximation of \c vertex.distance by setting it to <tt>knownVertex.distance + edge.weight</tt>. We also update the predecessor attribute. The algorithms proceed by labeling the adjacent neighbors of known vertices and freezing the value of labeled vertices when they are determined to be correct. At termination, the distance attributes are equal to the shortest-path weights. Below is the procedure for labeling a single vertex and the procedure for labeling the neighbors of a known vertex. \verbatim label(vertex, knownVertex, edgeWeight): if vertex.status == UNLABELED: vertex.status = LABELED if knownVertex.distance + edgeWeight < vertex.distance: vertex.distance = knownVertex.distance + edgeWeight vertex.predecessor = knownVertex return \endverbatim \verbatim labelAdjacent(knownVertex): for each edge of knownVertex leading to vertex: if vertex.status != KNOWN: label(vertex, knownVertex, edge.weight) return \endverbatim <!----------------------------------------------------------------------------> \section shortest_paths_introduction_test Test Problems <!--\label{shortest paths, introduction, test problems}--> For the purpose of evaluating the performance of the shortest path algorithms we introduce a few simple test problems for weighted, directed graphs. The first problem is the <em>grid graph</em>. The vertices are arranged in a 2-D rectangular array. Each vertex has four adjacent edges to its neighboring vertices. Vertices along the boundary are periodically connected. Next we consider a <em>complete graph</em> in which each vertex has adjacent edges to every other vertex. Finally, we introduce the <em>random graph</em>. Each vertex has a specified number of adjacent and incident edges. These edges are selected through random shuffles. The figure below shows examples of the three test problems. \image html TestProblems.jpg "Examples of the three test problems: A 3 by 3 grid graph, a complete graph with 5 vertices and a random graph with 5 vertices and 2 adjacent edges per vertex are shown." \image latex TestProblems.pdf "Examples of the three test problems: A 3 by 3 grid graph, a complete graph with 5 vertices and a random graph with 5 vertices and 2 adjacent edges per vertex are shown." width=\textwidth <!--\label{figure test problems}--> The edge weights are uniformly, randomly distributed on a given interval. We characterize the distributions by the ratio of the upper to lower bound of the interval. For example, edge weights on the interval [1 / 2..1] have a ratio of \f$R = 2\f$ and edge weights on the interval [0..1] have an infinite ratio, \f$R = \infty\f$. */ //============================================================================= //============================================================================= /*! \page shortest_paths_dijkstra Dijkstra's Greedy Algorithm Dijkstra's algorithm cite{cormen:2001} cite{cherkassky/goldberg/radzik:1996} solves the single-source shortest-paths problem for the case that the edge weights are nonnegative. It is a labeling algorithm. Whenever the distance of a vertex becomes known, this known vertex labels its adjacent neighbors. The algorithm begins by labeling the adjacent neighbors of the source. The vertices with \c LABELED status are stored in the \c labeled set. The algorithm iterates until the \c labeled set is empty. This occurs when all vertices reachable from the source become \c KNOWN . At each step of the iteration, the labeled vertex with minimum distance is guaranteed to have the correct distance and a correct predecessor. The status of this vertex is set to \c KNOWN , it is removed from the \c labeled set and its adjacent neighbors are labeled. Below is Dijkstra's algorithm. The \c extractMinimum() function removes and returns the vertex with minimum distance from the \c labeled set. We postpone the discussion of why the \c labelAdjacent() function takes the \c labeled set as an argument. \verbatim Dijkstra(graph, source): initialize(graph, source) labeled.clear() labelAdjacent(labeled, source) while labeled is not empty: minimumVertex = extractMinimum(labeled) minimumVertex.status = KNOWN labelAdjacent(labeled, minimumVertex) return \endverbatim Dijkstra's algorithm is a greedy algorithm because at each step, the best alternative is chosen. That is, the labeled vertex with the smallest distance becomes known. Now we show how this greedy strategy produces a correct shortest-paths tree. Suppose that some of the vertices are known to have the correct distance and that all adjacent neighbors of these known vertices have been labeled. We assert that the labeled vertex \c v with minimum distance has the correct distance. Suppose that this distance to \c v is computed through the path \c source \f$\mapsto\f$ \c x \f$\to\f$ \c v. (Here \f$\mapsto\f$ indicates a (possibly empty) path and \f$\to\f$ indicates a single edge.) Each of the vertices in the path \c source \f$\mapsto\f$ \c x is known. We assume that there exists a shorter path, \c source \f$\mapsto\f$ \c y \f$\to\f$ \c u \f$\mapsto\f$ \c v, where \c y is known and \c u is labeled, and obtain a contradiction. First note that all paths from \c source to \c v have this form. At some point the path progresses from a known vertex \c y to a labeled vertex \c u. Since \c u is labeled, \c u.distance \f$\geq\f$ \c v.distance . Since the edge weights are nonnegative, \c source \f$\mapsto\f$ \c y \f$\to\f$ \c u \f$\mapsto\f$ \c v is not a shorter path. We conclude that \c v has the correct distance. Dijkstra's algorithm produces a correct shortest-paths tree. After initialization, only the source vertex is known. At each step of the iteration, one labeled vertex becomes known. The algorithm proceeds until all vertices reachable from the source have the correct distance. The figure below shows an example of using Dijkstra's algorithm to compute the shortest paths tree. First we show the graph, which is a \f$3 \times 3\f$ grid graph except that the boundary vertices are not periodically connected. In the initialization step, the lower left vertex is set to be the source and its two neighbors are labeled. We show known vertices in black and labeled vertices in red. The current labeling edges are green. Edges of the shortest-paths tree are shown in black, while the predecessor edges for labeled vertices are red. After initialization, there is one known vertex (namely the source) and two labeled vertices. In the first step, the minimum vertex has a distance of 2. This vertex becomes known and the edge from its predecessor is added to the shortest paths tree. Then this vertex labels its adjacent neighbors. In the second step, the three labeled vertices have the same distance. One of them becomes known and labels its neighbors. Choosing the minimum labeled vertex and labeling its neighbors continues until all the vertices are known. \image html DijkstraFigure.jpg "Dijkstra's algorithm for a graph with 9 vertices." \image latex DijkstraFigure.pdf "Dijkstra's algorithm for a graph with 9 vertices." width=\textwidth <!--\label{figure dijkstra figure}--> Now that we have demonstrated the correctness of Dijkstra's algorithm, we determine the computational complexity. Suppose that we store the labeled vertices in an array or a list. If there are \e N labeled vertices, the computational complexity of adding a vertex or decreasing the distance of a vertex is \f$\mathcal{O}(1)\f$. To extract the minimum vertex we examine each labeled vertex for a cost of \f$\mathcal{O}(N)\f$. There are \f$V - 1\f$ calls to \c push() and \c extractMinimum() . At any point in the shortest-paths computation, there are at most \e V labeled vertices. Hence the \c push() and \c extractMinimum() operations add a computational cost of \f$\mathcal{O}( V^2 )\f$. There are \e E labeling operations and less than \e E calls to \c decrease() which together add a cost of \f$\mathcal{O}( E )\f$. Thus the computational complexity of Dijkstra's algorithm using an array or list to store the labeled vertices is \f$\mathcal{O}(V^2 + E) = \mathcal{O}( V^2)\f$ Now we turn our attention to how we can store the labeled vertices so that we can more efficiently extract one with the minimum distance. The \c labeled set is a priority queue cite{cormen:2001} that supports three operations: - \c push() : Vertices are added to the set when they become labeled. - \c extractMinimum() : The vertex with minimum distance can be removed. - \c decrease() : The distance of a vertex in the labeled set may be decreased through labeling. . For many problems, a binary heap cite{cormen:2001} is an efficient way to implement the priority queue. Below are new functions for labeling vertices which now take the labeled set as an argument and use the \c push() and \c decrease() operations on it. \verbatim labelAdjacent(heap, knownVertex): for each edge of knownVertex leading to vertex: if vertex.status != KNOWN: label(heap, vertex, knownVertex, edge.weight) return \endverbatim \verbatim label(heap, vertex, knownVertex, edgeWeight): if vertex.status == UNLABELED: vertex.status = LABELED vertex.distance = knownVertex.distance + edgeWeight vertex.predecessor = knownVertex heap.push(vertex) else if knownVertex.distance + edgeWeight < vertex.distance: vertex.distance = knownVertex.distance + edgeWeight vertex.predecessor = knownVertex heap.decrease(vertex.heapPointer) return \endverbatim If there are \e N labeled vertices in the binary heap, the computational complexity of adding a vertex is \f$\mathcal{O}(1)\f$. The cost of extracting the minimum vertex or decreasing the distance of a vertex is \f$\mathcal{O}(\log N)\f$. The \f$V - 1\f$ calls to \c push() and \c extractMinimum() add a computational cost of \f$\mathcal{O}( V \log V )\f$. There are \e E labeling operations, \f$\mathcal{O}( E )\f$, and less than \e E calls to \c decrease(), \f$\mathcal{O}( E \log V )\f$. Thus the computational complexity of Dijkstra's algorithm using a binary heap is \f$\mathcal{O}( ( V + E ) \log V )\f$. */ //============================================================================= //============================================================================= /*! \page shortest_paths_greedier A Greedier Algorithm: Marching with a Correctness Criterion <!--\label{chapter sssp section aga:mwacc}--> If one were to solve by hand the single-source shortest-paths problem using Dijkstra's algorithm, one would probably note that at any given step, most of the labeled vertices have the correct distance and predecessor. Yet at each step only one vertex is moved from the labeled set to the known set. Let us quantify this observation. At each step of Dijkstra's algorithm (there are always \f$V - 1\f$ steps) we count the number of correct vertices and the total number of vertices in the labeled set. At termination we compute the fraction of vertices that had correct values. The fraction of correct vertices in the labeled set depends on the connectivity of the vertices and the distribution of edge weights. As introduced in the \ref shortest_paths_introduction_test "test problem section", we consider grid, random and complete graphs. We consider edges whose weights have a uniform distribution in a given interval. The interval is characterized by the ratio of its upper limit to its lower limit. We consider the ratios: 2, 10, 100 and \f$\infty\f$. The fractions of correctly determined labeled vertices are plotted below. (The graphs show log-linear plots of the ratio of correctly determined vertices to labeled vertices versus the number of vertices in the graph.) We see that this fraction depends on the edge weight ratio. This is intuitive. If the edge weights were all unity (or another constant) then we could solve the shortest-paths problem with a breadth first search. At each iteration of Dijkstra's algorithm, all the labeled vertices would have the correct value. We see that as the edge weight ratio increases, fewer of the labeled vertices are correct, but even when the ratio is infinite a significant fraction of the labeled vertices are correct. \image html DijkstraDeterminedGrid.jpg "Grid graph. Each vertex has an edge to its four adjacent neighbors." \image latex DijkstraDeterminedGrid.pdf "Grid graph. Each vertex has an edge to its four adjacent neighbors." width=0.5\textwidth \image html DijkstraDeterminedComplete.jpg "Dense graph. Each vertex has an edge to every other vertex." \image latex DijkstraDeterminedComplete.pdf "Dense graph. Each vertex has an edge to every other vertex." width=0.5\textwidth \image html DijkstraDeterminedRandom4.jpg "Random graph. Each vertex has edges to 4 randomly chosen vertices." \image latex DijkstraDeterminedRandom4.pdf "Random graph. Each vertex has edges to 4 randomly chosen vertices." width=0.5\textwidth \image html DijkstraDeterminedRandom32.jpg "Random graph. Each vertex has edges to 32 randomly chosen vertices." \image latex DijkstraDeterminedRandom32.pdf "Random graph. Each vertex has edges to 32 randomly chosen vertices." width=0.5\textwidth <!--\label{figure dijkstra determined}--> These observations motivate us to seek a new algorithm for the single-source shortest-paths problem. Dijkstra's algorithm is an example of a greedy algorithm. At each iteration the single best choice is taken. The labeled vertex with minimum distance is added to the known set. We seek a greedier algorithm. At each iteration we take as many correct choices as possible. Each labeled vertex that can be determined to have the correct distance is added to the known set. Below is this greedier algorithm. \verbatim marchingWithCorrectnessCriterion(graph, source): graph.initialize(source) labeled.clear() newLabeled.clear() labelAdjacent(labeled, source) // Loop until all vertices have a known distance. while labeled is not empty: for vertex in labeled: if vertex.distance is determined to be correct vertex.status = KNOWN labelAdjacent(newLabeled, vertex) // Get the labeled lists ready for the next step. removeKnown(labeled) labeled += newLabeled newLabeled.clear() return \endverbatim It is easy to verify that the algorithm is correct. It gives the correct result because only vertices with correct distances are added to the known set. It terminates because at each iteration at least one vertex in the labeled set has the correct distance. We call this algorithm <em>marching with a correctness criterion</em> (MCC). All we lack now is a good method for determining if a labeled vertex is correct. The rest of the algorithm is trivial. We do have one correctness criterion, namely that used in Dijkstra's algorithm: The labeled vertex with minimum distance is correct. Using this criterion would give us Dijkstra's algorithm with a list as a priority queue, which has computational complexity \f$\mathcal{O}( V^2 )\f$. We turn our attention to finding a better correctness criterion. Assume that some of the vertices are known to have the correct distance and that all adjacent neighbors of known vertices have been labeled. To determine if a labeled vertex is correct, we look at the labeling operations that have not yet occurred. If future labeling operations will not decrease the distance, then the distance must be correct. We formulate this notion by defining a lower bound on the distance of a labeled vertex. The distance stored in a labeled vertex is an upper bound on the actual distance. We seek to define a lower bound on the distance by using the current distance and considering future labeling operations. If the current distance is less than or equal to the lower bound, then the labeled vertex must be correct. We will start with a simple lower bound and then develop more sophisticated ones. Let \c minimumUnknown be the minimum distance among the labeled vertices. By the correctness criterion of Dijkstra's algorithm, any labeled vertex with distance equal to \c minimumUnknown is correct. The simplest lower bound for a labeled vertex is the value of \c minimumUnknown. We call this the level 0 lower bound. To get a more accurate lower bound, we use information about the incident edges. Let each vertex have the attribute \c minimumIncidentEdgeWeight, the minimum weight over all incident edges. The smaller of \c vertex.distance and <tt>(minimumUnknown + vertex.minimumIncidentEdgeWeight)</tt> is a lower bound on the distance. We consider why this is so. If the predecessor of this vertex in the shortest-paths tree is known, then it has been labeled from its correct predecessor and has the correct distance. Otherwise, the distance at its correct predecessor is currently not known, but is no less than \c minimumUnknown. The edge weight from the predecessor is no less than \c vertex.minimumIncidentEdgeWeight. Thus <tt>(minimumUnknown + vertex.minimumIncidentEdgeWeight)</tt> is no greater than the correct distance. We call the minimum of \c vertex.distance and <tt>(minimumUnknown + vertex.minimumIncidentEdgeWeight)</tt> the level 1 lower bound. \verbatim lowerBound1(vertex, minimumUnknown) return min(vertex.distance, minimumUnknown + vertex.minimumIncidentEdgeWeight) \endverbatim If the distance at a labeled vertex is less than or equal to the lower bound on the distance, then the vertex must have the correct distance. This observation allows us to define the level 1 correctness criterion. We define the \c isCorrect1() method for a vertex. For a labeled vertex, it returns true if the current distance is less than or equal to the level 1 lower bound on the distance and false otherwise. \verbatim isCorrect1(vertex, minimumUnknown, level) return (vertex.distance <= vertex.lowerBound1(minimumUnknown)) \endverbatim Below we show an example of using the MCC algorithm with the level 1 correctness criterion to compute the shortest-paths tree. First we show the graph, which is a \f$4 \times 4\f$ grid graph except that the boundary vertices are not periodically connected. In the initialization step, the lower, left vertex is set to be the source and its two neighbors are labeled. We show known vertices in black and labeled vertices in red. The labeling operations are shown in green. Edges of the shortest paths tree are shown in black, while the predecessor edges for labeled vertices are red. After initialization, there is one known vertex (namely the source) and two labeled vertices. Depictions of applying the correctness criterion are shown in blue. (Recall that the level 1 correctness criterion uses the minimum incident edge weight and the minimum labeled vertex distance to determine if a labeled vertex is correct.) Since future labeling operations will not decrease their distance, both labeled vertices become known in the first step. After labeling their neighbors, there are three labeled vertices in step 1. The correctness criterion shows that the vertices with distances 3 and 4 will not be decreased by future labeling operations, thus they are correct. However, the correctness criterion does not indicate that the labeled vertex with distance 8 is correct. The correctness criterion indicates that a vertex with a distance as small as 3 might label the vertex with an edge weight as small as 2. This gives a lower bound on the distance of 5. Thus in step 2, two of the three labeled vertices become known. We continue checking labeled vertices using the correctness criterion until all the vertices are known. Finally, we show the shortest-paths tree. \image html MCCFigure.jpg "Marching with a correctness criterion algorithm for a graph with 16 vertices." \image latex MCCFigure.pdf "Marching with a correctness criterion algorithm for a graph with 16 vertices." width=\textwidth <!--\label{figure mcc figure}--> We can get a more accurate lower bound on the distance of a labeled vertex if we use more information about the incident edges. For the level 1 formula, we used only the minimum incident edge weight. For the level 2 formula below we use all of the unknown incident edges. \f[ \min \left( \mathtt{vertex.distance}, \min_{\substack{\mathrm{unknown}\\ \mathrm{edges}}} (\mathtt{edge.weight + minimumUnknown}) \right) \f] The lower bound is the smaller of the current distance and the minimum over unknown incident edges of <tt>(edge.weight + minimumUnknown)</tt>. Let the method <tt>lowerBound(minimumUnknown, level)</tt> return the lower bound for a vertex. Since the level 0 lower bound is \c minimumUnknown, we can write the level 2 formula in terms of the level 0 formula. \f[ \mathtt{vertex.lowerBound( minimumUnknown, 2 )} = \f] \f[ \min \left( \mathtt{vertex.distance}, \min_{\substack{\mathrm{unknown}\\ \mathrm{edges}}} (\mathtt{edge.weight + edge.source.lowerBound( minimumUnknown, 0 )}) \right) \f] More generally, for \f$n \geq 2\f$ we can define the level \e n lower bound in terms of the level \e n - 2 lower bound. This gives us a recursive definition of the method. \f[ \mathtt{vertex.lowerBound( minimumUnknown, n )} = \f] \f[ \min \left( \mathtt{vertex.distance}, \min_{\substack{\mathrm{unknown}\\ \mathrm{edges}}} (\mathtt{edge.weight + edge.source.lowerBound( minimumUnknown, n - 2 )}) \right) \f] We consider why this is a correct lower bound. If the correct predecessor of this vertex is known, then it has been labeled from its predecessor and thus has the correct distance. Otherwise, the distance at its predecessor is currently not known. The correct distance is the correct distance of the predecessor plus the weight of the connecting, incident edge. The minimum over unknown edges of the sum of edge weight and a lower bound on the distance of the incident vertex is no greater than the correct distance. Thus the lower bound formula is valid. Below is the \c lowerBound method which implements the lower bound formulae. \verbatim lowerBound(vertex, minimumUnknown, level) if level == 0: return minimumUnknown if level == 1: return min(vertex.distance, minimumUnknown + vertex.minimumIncidentEdgeWeight) minimumDistance = vertex.distance for edge in vertex.incidentEdges: if edge.source.status != KNOWN: d = edge.weight + edge.source.lowerBound(minimumUnknown, level - 2) if d < minimumDistance: minimumDistance = d return minimumDistance \endverbatim Now we define the \c isCorrect() method for a vertex. For a labeled vertex, it returns true if the current distance is less than or equal to the lower bound on the distance and false otherwise. This completes the \c marchingWithCorrectnessCriterion() function. We give the refined version of this function below. \verbatim isCorrect(vertex, minimumUnknown, level) return (vertex.distance <= vertex.lowerBound(minimumUnknown, level)) \endverbatim \verbatim marchingWithCorrectnessCriterion(graph, source, level) graph.initialize(source) labeled.clear() newLabeled.clear() labelAdjacent(labeled, source) // Loop until all vertices have a known distance. while labeled is not empty: minimumUnknown = minimum distance in labeled for vertex in labeled: if vertex.isCorrect(minimumUnknown, level): vertex.status = KNOWN labelAdjacent(newLabeled, vertex) // Get the labeled lists ready for the next step. removeKnown(labeled) labeled += newLabeled newLabeled.clear() return \endverbatim The figure below depicts the incident edges used for the first few levels of correctness criteria. For each level, the correctness criterion is applied to the center vertex. We show the surrounding vertices and incident edges. The level 0 criterion does not use any information about the incident edges. The level 1 criterion uses only the minimum incident edge. The level 2 criterion uses all the incident edges from unknown vertices. The level 3 criterion uses the incident edges from unknown vertices and the minimum incident edge at each of these unknown vertices. The figure depicts subsequent levels up to level 6. If each vertex had \e I incident edges then the computational complexity of the level \e n correctness criterion would be \f$\mathcal{O}(I^{\lfloor n/2 \rfloor})\f$. \image html MCCLevel.jpg "A depiction of the incident edges used in the level n correctness criterion for n = 0, ..., 6." \image latex MCCLevel.pdf "A depiction of the incident edges used in the level n correctness criterion for n = 0, ..., 6." width=\textwidth <!--\label{figure mcc level}--> We examine the performance of these correctness criteria. From our analysis of correctly determined vertices in Dijkstra's algorithm we expect that the ratio of vertices which can be determined to be correct will depend on the connectivity of the edges and the distribution of edge weights. We also expect that for a given graph, the ratio of vertices which are determined to be correct will increase with the level of the correctness criterion. Again we consider grid, random and complete graphs with maximum-to-minimum edge weight ratios of 2, 10, 100 and \f$\infty\f$. The graphs below show the performance of the correctness criteria for each kind of graph with an edge weight ratio of 2. We run the tests for level 0 through level 5 criteria. We show the ideal algorithm for comparison. (The ideal correctness criterion would return true for all labeled vertices whose current distance is correct.) The level 0 correctness criterion (which is the criterion used in Dijkstra's algorithm) yields a very low ratio of correctly determined vertices. If the minimum weight of labeled vertices is unique, then only a single labeled vertex will become determined. The level 1 and level 2 criteria perform quite well. For the grid graphs and random graphs, about 3/4 of the labeled vertices are determined at each step. For the complete graph, all of the labeled vertices are determined at each step. For the ideal criterion, the ratio of determined vertices is close to or equal to 1 and does not depend on the number of vertices. The correctness criteria with level 3 and higher come very close to the ideal criterion. We see that the level 1 and level 3 criteria are the most promising for graphs with low edge weight ratios. The level 1 criterion yields a high ratio of determined vertices. The level 2 criterion yields only marginally better results at the cost of greater algorithmic complexity and higher storage requirements. Recall that the level 1 criterion only uses the minimum incident edge weight, while the level 2 criterion requires storing the incident edges at each vertex. The level 3 criterion comes very close to the ideal. Higher levels only add complexity to the algorithm. \image html MCCDeterminedGrid2.jpg "Grid graph. Each vertex has an edge to its four adjacent neighbors." \image latex MCCDeterminedGrid2.pdf "Grid graph. Each vertex has an edge to its four adjacent neighbors." width=0.5\textwidth \image html MCCDeterminedComplete2.jpg "Dense graph. Each vertex has an edge to every other vertex." \image latex MCCDeterminedComplete2.pdf "Dense graph. Each vertex has an edge to every other vertex." width=0.5\textwidth \image html MCCDeterminedRandom4Edges2.jpg "Random graph. Each vertex has edges to 4 randomly chosen vertices." \image latex MCCDeterminedRandom4Edges2.pdf "Random graph. Each vertex has edges to 4 randomly chosen vertices." width=0.5\textwidth \image html MCCDeterminedRandom32Edges2.jpg "Random graph. Each vertex has edges to 32 randomly chosen vertices." \image latex MCCDeterminedRandom32Edges2.pdf "Random graph. Each vertex has edges to 32 randomly chosen vertices." width=0.5\textwidth Next we show the performance of the correctness criteria for each kind of graph with an edge weight ratio of 10. Compared to the results for an edge weight ratio of 2, the determined ratio is lower for the ideal criterion and the determined ratios for levels 0 through 5 are more spread out. Around 3/4 of the vertices are determined at each time step with the ideal criterion; there is a slight dependence on the number of vertices. The level 1 criterion performs fairly well; it determines from about 1/4 to 1/2 of the vertices. The level 2 criterion determines only slightly more vertices than the level 1. Going to level 3 takes a significant step toward the ideal. Level 4 determines few more vertices than level 3. There is a diminishing return in going to higher levels. \image html MCCDeterminedGrid10.jpg "Grid graph. Each vertex has an edge to its four adjacent neighbors." \image latex MCCDeterminedGrid10.pdf "Grid graph. Each vertex has an edge to its four adjacent neighbors." width=0.5\textwidth \image html MCCDeterminedComplete10.jpg "Dense graph. Each vertex has an edge to every other vertex." \image latex MCCDeterminedComplete10.pdf "Dense graph. Each vertex has an edge to every other vertex." width=0.5\textwidth \image html MCCDeterminedRandom4Edges10.jpg "Random graph. Each vertex has edges to 4 randomly chosen vertices." \image latex MCCDeterminedRandom4Edges10.pdf "Random graph. Each vertex has edges to 4 randomly chosen vertices." width=0.5\textwidth \image html MCCDeterminedRandom32Edges10.jpg "Random graph. Each vertex has edges to 32 randomly chosen vertices." \image latex MCCDeterminedRandom32Edges10.pdf "Random graph. Each vertex has edges to 32 randomly chosen vertices." width=0.5\textwidth The graphs below show the performance of the correctness criteria when the edge weight ratio is 100. The determined ratio is lower still for the ideal criterion and the determined ratios for levels 0 through 5 are even more spread out. The determined ratios now have a noticeable dependence on the number of vertices. \image html MCCDeterminedGrid100.jpg "Grid graph. Each vertex has an edge to its four adjacent neighbors." \image latex MCCDeterminedGrid100.pdf "Grid graph. Each vertex has an edge to its four adjacent neighbors." width=0.5\textwidth \image html MCCDeterminedComplete100.jpg "Dense graph. Each vertex has an edge to every other vertex." \image latex MCCDeterminedComplete100.pdf "Dense graph. Each vertex has an edge to every other vertex." width=0.5\textwidth \image html MCCDeterminedRandom4Edges100.jpg "Random graph. Each vertex has edges to 4 randomly chosen vertices." \image latex MCCDeterminedRandom4Edges100.pdf "Random graph. Each vertex has edges to 4 randomly chosen vertices." width=0.5\textwidth \image html MCCDeterminedRandom32Edges100.jpg "Random graph. Each vertex has edges to 32 randomly chosen vertices." \image latex MCCDeterminedRandom32Edges100.pdf "Random graph. Each vertex has edges to 32 randomly chosen vertices." width=0.5\textwidth Finally, we show the performance of the correctness criteria with an infinite edge weight ratio. Compared to the results for lower edge weight ratios, the determined ratio is lower for the ideal criterion and the determined ratios for levels 0 through 5 are more spread out. For the infinite edge weight ratio, the correctness criteria yield fewer correctly determined vertices. \image html MCCDeterminedGridInfinity.jpg "Grid graph. Each vertex has an edge to its four adjacent neighbors." \image latex MCCDeterminedGridInfinity.pdf "Grid graph. Each vertex has an edge to its four adjacent neighbors." width=0.5\textwidth \image html MCCDeterminedCompleteInfinity.jpg "Dense graph. Each vertex has an edge to every other vertex." \image latex MCCDeterminedCompleteInfinity.pdf "Dense graph. Each vertex has an edge to every other vertex." width=0.5\textwidth \image html MCCDeterminedRandom4EdgesInfinity.jpg "Random graph. Each vertex has edges to 4 randomly chosen vertices." \image latex MCCDeterminedRandom4EdgesInfinity.pdf "Random graph. Each vertex has edges to 4 randomly chosen vertices." width=0.5\textwidth \image html MCCDeterminedRandom32EdgesInfinity.jpg "Random graph. Each vertex has edges to 32 randomly chosen vertices." \image latex MCCDeterminedRandom32EdgesInfinity.pdf "Random graph. Each vertex has edges to 32 randomly chosen vertices." width=0.5\textwidth Note that if the correctly determined ratio is \e D, then on average a labeled vertex will be tested 1 / \e D times before it is determined to be correct. For each of the correctness criteria, we see that the ratio of determined vertices is primarily a function of the edge weight ratio and the number of edges per vertex. The determined ratio decreases with both increasing edge weight ratio and increasing edges per vertex. Thus graphs with a low edge weight ratio and/or few edges per vertex seem well suited to the marching with a correctness criterion approach. For graphs with high edge weight ratios and/or many edges per vertex, the correctness criteria yield fewer determined vertices, so the method will be less efficient. Before analyzing execution times in the next section, we develop a more efficient implementation of the correctness criteria for levels 2 and higher. It is not necessary to examine all of the edges of a vertex each time \c isCorrect() is called. Instead, we amortize this cost over all the calls. The incident edges of each vertex are in sorted order by edge weight. Additionally, each vertex has a forward edge iterator, \c unknownIncidentEdge, which keeps track of the incident edge currently being considered. To see if a labeled vertex is determined, the incident edges are traversed in order. If we encounter an edge from an unknown vertex such that the sum of the edge weight and the lower bound on the distance of that unknown vertex is less than the current distance, then the vertex is not determined to be correct. The next time \c isCorrect() is called for the vertex, we start at the incident edge where the previous call stopped. This approach works because the lower bound on the distance of each vertex is non-increasing as the algorithm progresses. That is, as more vertices become known and more vertices are labeled, the lower bound on a given vertex may decrease but will never increase. Below is the more efficient implementation of \c isCorrect(). \verbatim isCorrect(vertex, minimumUnknown, level): if level <= 1: if vertex.distance > vertex.lowerBound(minimumUnknown, level): return false else: vertex.getUnknownIncidentEdge() while vertex.unknownIncidentEdge != vertex.incidentEdges.end(): if (vertex.distance > vertex.unknownIncidentEdge.weight + vertex.unknownIncidentEdge.source.lowerBound(minimumUnknown, level - 2)): return false ++vertex.unknownIncidentEdge vertex.getUnknownIncidentEdge() return true \endverbatim \verbatim getUnknownIncidentEdge(vertex): while (vertex.unknownIncidentEdge != vertex.incidentEdges.end() and vertex.unknownIncidentEdge.source.status == KNOWN): ++vertex.unknownIncidentEdge return \endverbatim */ //============================================================================= //============================================================================= /*! \page shortest_paths_complexity Computational Complexity Now we determine the computational complexity of the MCC algorithm. We will get a worst-case bound for using the level 1 correctness criterion. Let the edge weights be in the interval \f$[A \ldots B]\f$. As introduced before, let \f$R = B / A\f$ be the ratio of the largest edge weight to the smallest. We will assume that the ratio is finite. Consider the MCC algorithm in progress. Let \f$\mu\f$ be the minimum distance of the labeled vertices. The distances of the labeled vertices are in the range \f$[\mu \ldots \mu + B)\f$. When one applies the correctness criterion, at least all of the labeled vertices with distances less than or equal to \f$\mu + A\f$ will become known. Thus at the next step, the minimum labeled distance will be at least \f$\mu + A\f$. At each step of the algorithm, the minimum labeled distance increases by at least \e A. This means that a vertex may be in the labeled set for at most \f$B / A\f$ steps. The cost of applying the correctness criteria is \f$\mathcal{O}(R V)\f$. The cost of labeling is \f$\mathcal{O}(E)\f$. Since a vertex is simply added to the end of a list or array when it becomes labeled, the cost of adding and removing labeled vertices is \f$\mathcal{O}(V)\f$. Thus the computation complexity of the MCC algorithm is \f$\mathcal{O}(E + R V)\f$. */ //============================================================================= //============================================================================= /*! \page shortest_paths_performance Performance Comparison We compare the performance of Dijkstra's algorithm and the Marching with a Correctness Criterion algorithm. For the MCC algorithm, we consider level 1 and level 3 correctness criteria, which have better performance than other levels. Again we consider grid, random and complete graphs with maximum-to-minimum edge weight ratios of 2, 10, 100 and \f$\infty\f$. The graphs below show the execution times over a range of graph sizes for each kind of graph with an edge weight ratio of 2. The level 1 MCC algorithm has relatively low execution times. It performs best for sparse graphs. (The grid graph and the first random graph each have four adjacent and four incident edges per vertex.) For the random graph with 32 edges, it is still the fastest method, but the margin is smaller. For medium to large complete graphs, the execution times are nearly the same as for Dijkstra's algorithm. For small complete graphs, Dijkstra's algorithm is faster. The level 3 MCC algorithm performs pretty well for the sparser graphs, but is slower than the other two methods for the denser graphs. \image html ExecutionTimeGrid2.jpg "Grid graph. Each vertex has an edge to its four adjacent neighbors." \image latex ExecutionTimeGrid2.pdf "Grid graph. Each vertex has an edge to its four adjacent neighbors." width=0.5\textwidth \image html ExecutionTimeComplete2.jpg "Dense graph. Each vertex has an edge to every other vertex." \image latex ExecutionTimeComplete2.pdf "Dense graph. Each vertex has an edge to every other vertex." width=0.5\textwidth \image html ExecutionTimeRandom4Edges2.jpg "Random graph. Each vertex has edges to 4 randomly chosen vertices." \image latex ExecutionTimeRandom4Edges2.pdf "Random graph. Each vertex has edges to 4 randomly chosen vertices." width=0.5\textwidth \image html ExecutionTimeRandom32Edges2.jpg "Random graph. Each vertex has edges to 32 randomly chosen vertices." \image latex ExecutionTimeRandom32Edges2.pdf "Random graph. Each vertex has edges to 32 randomly chosen vertices." width=0.5\textwidth Next we show the execution times for graphs with an edge weight ratio of 10. Again the level 1 MCC algorithm has the best overall performance, however the margin is a little smaller than in the previous tests. \image html ExecutionTimeGrid10.jpg "Grid graph. Each vertex has an edge to its four adjacent neighbors." \image latex ExecutionTimeGrid10.pdf "Grid graph. Each vertex has an edge to its four adjacent neighbors." width=0.5\textwidth \image html ExecutionTimeComplete10.jpg "Dense graph. Each vertex has an edge to every other vertex." \image latex ExecutionTimeComplete10.pdf "Dense graph. Each vertex has an edge to every other vertex." width=0.5\textwidth \image html ExecutionTimeRandom4Edges10.jpg "Random graph. Each vertex has edges to 4 randomly chosen vertices." \image latex ExecutionTimeRandom4Edges10.pdf "Random graph. Each vertex has edges to 4 randomly chosen vertices." width=0.5\textwidth \image html ExecutionTimeRandom32Edges10.jpg "Random graph. Each vertex has edges to 32 randomly chosen vertices." \image latex ExecutionTimeRandom32Edges10.pdf "Random graph. Each vertex has edges to 32 randomly chosen vertices." width=0.5\textwidth The graphs below show the execution times for graphs with an edge weight ratio of 100. The level 1 MCC algorithm is no longer the best overall performer. It has about the same execution times as Dijkstra's algorithm for the complete graph and the random graph with 32 edges, but is slower than Dijkstra's algorithm for the grid graph and the random graph with 4 edges. \image html ExecutionTimeGrid100.jpg "Grid graph. Each vertex has an edge to its four adjacent neighbors." \image latex ExecutionTimeGrid100.pdf "Grid graph. Each vertex has an edge to its four adjacent neighbors." width=0.5\textwidth \image html ExecutionTimeComplete100.jpg "Dense graph. Each vertex has an edge to every other vertex." \image latex ExecutionTimeComplete100.pdf "Dense graph. Each vertex has an edge to every other vertex." width=0.5\textwidth \image html ExecutionTimeRandom4Edges100.jpg "Random graph. Each vertex has edges to 4 randomly chosen vertices." \image latex ExecutionTimeRandom4Edges100.pdf "Random graph. Each vertex has edges to 4 randomly chosen vertices." width=0.5\textwidth \image html ExecutionTimeRandom32Edges100.jpg "Random graph. Each vertex has edges to 32 randomly chosen vertices." \image latex ExecutionTimeRandom32Edges100.pdf "Random graph. Each vertex has edges to 32 randomly chosen vertices." width=0.5\textwidth Finally we show the execution times for graphs with an infinite edge weight ratio. Except for complete graphs, the level 1 MCC algorithm does not scale well as the number of vertices is increased. This makes sense upon examining the correctly determined ratio plots for an infinite edge weight. <!--CONTINUE in Figure ref{figure mcc determined infinity}--> As the size of the graph increases, the determined ratio decreases. The level 3 MCC algorithm scales better, but is slower than Dijkstra's algorithm for each size and kind of graph. \image html ExecutionTimeGridInfinity.jpg "Grid graph. Each vertex has an edge to its four adjacent neighbors." \image latex ExecutionTimeGridInfinity.pdf "Grid graph. Each vertex has an edge to its four adjacent neighbors." width=0.5\textwidth \image html ExecutionTimeCompleteInfinity.jpg "Dense graph. Each vertex has an edge to every other vertex." \image latex ExecutionTimeCompleteInfinity.pdf "Dense graph. Each vertex has an edge to every other vertex." width=0.5\textwidth \image html ExecutionTimeRandom4EdgesInfinity.jpg "Random graph. Each vertex has edges to 4 randomly chosen vertices." \image latex ExecutionTimeRandom4EdgesInfinity.pdf "Random graph. Each vertex has edges to 4 randomly chosen vertices." width=0.5\textwidth \image html ExecutionTimeRandom32EdgesInfinity.jpg "Random graph. Each vertex has edges to 32 randomly chosen vertices." \image latex ExecutionTimeRandom32EdgesInfinity.pdf "Random graph. Each vertex has edges to 32 randomly chosen vertices." width=0.5\textwidth Note that the four plots for complete graphs (with edge weight ratios of 2, 10, 100 and \f$\infty\f$) are virtually identical. Dijkstra's algorithm and the level 1 MCC algorithm both perform relatively well. For medium to large graphs, their execution times are very close. This is because there are many more edges than vertices, so labeling adjacent vertices dominates the computation. The costs of heap operations for Dijkstra's algorithm or correctness tests for the level 1 MCC algorithm are negligible. This is the case even for an infinite edge weight ratio where on average, each labeled vertex is checked many times before it is determined to be correct. For complete graphs, the level 3 MCC algorithm is slower than the other two. This is because all incident edges of a labeled vertex may be examined during a correctness check. Thus the level 3 correctness criterion is expensive enough to affect the execution time. Clearly the distribution of edge weights affects the performance of the MCC algorithm. One might try to use topological information to predict the performance. Consider planar graphs for example, i.e. graphs that can be drawn in a plane without intersecting edges. During the execution of the MCC algorithm (or Dijkstra's algorithm) one would expect the labeled vertices to roughly form a band that moves outward from the source. In this case, the number of labeled vertices would be much smaller than the total number of vertices. One might expect that the MCC algorithm would be well suited to planar graphs. However, this is not necessarily the case. The figure below shows two shortest-paths trees for a grid graph (a graph in which each vertex is connected to its four adjacent neighbors). The first diagram shows a typical tree. The second diagram shows a pathological case in which the shortest-paths tree is a single path that winds through the graph. For this case, the average number of labeled vertices is of the order of the number of vertices. Also, at each step of the MCC algorithm only a single labeled vertex can become known. For this pathological case, the complexity of the MCC algorithm is \f$\mathcal{O}(N^2)\f$. Unfortunately, one cannot guarantee reasonable performance of the MCC algorithm based on topological information. \image html GridGraphPathological.jpg "Two shortest-paths trees for a grid graph." \image latex GridGraphPathological.pdf "Two shortest-paths trees for a grid graph." width=\textwidth */ //============================================================================= //============================================================================= /*! \page shortest_paths_concurrency Concurrency Because of its simple data structures, the MCC method is easily adapted to a concurrent algorithm. The outer loop of the algorithm, <tt>while labeled is not empty</tt>, contains two loops over the labeled vertices. The first loop computes the minimum labeled distance and assigns this value to \c minimumUnknown. Though the time required to determine this minimum unknown distance is small compared to correctness checking and labeling, it may be done concurrently. The complexity of finding the minimum of \e N elements with \e P processors is \f$\mathcal{O}(N/P + \log_2 P)\f$ cite{vandevelde:1994}. The more costly operations are contained in the second loop. Each labeled vertex is tested to see if its distance can be determined to be correct. If so, it becomes known and labels its adjacent neighbors. These correctness checks and labeling may be done concurrently. Thus the complexity for both is then \f$\mathcal{O}(N/P)\f$. We conclude that the computational complexity of the MCC algorithm scales well with the number of processors. By contrast, most other shortest-paths algorithms, including Dijkstra's algorithm, are not so easily adapted to a concurrent framework. Consider Dijkstra's algorithm: The only operation that easily lends itself to concurrency is labeling vertices when a labeled vertex becomes known. That is, labeling each adjacent vertex is an independent operation. These may be done concurrently. However, this fine scale concurrency is limited by the number of edges per vertex. Because only one vertex may become known at a time, Dijkstra's algorithm is ill suited to take advantage of concurrency. */ //============================================================================= //============================================================================= /*! \page shortest_paths_future Future Work <!--\label{chapter sssp section fw}--> <!--------------------------------------------------------------------------> /*! \section shortest_paths_future_data A More Sophisticated Data Structure for the Labeled Set There are many ways that one could adapt the MCC algorithm. The MCC algorithm has a sophisticated correctness criterion and stores the labeled set in a simple container (namely, an array or a list). At each step the correctness criterion is applied to all the labeled vertices. By contrast, Dijkstra's algorithm has a simple correctness criterion and stores the labeled set in a sophisticated container. At each step the correctness criterion is applied to a single labeled vertex. An approach that lies somewhere between these two extremes may work well for some problems. That approach would be to employ both a sophisticated correctness criterion and a sophisticated vertex container. This more sophisticated container would need to be able to efficiently identify the labeled vertices on which the correctness test is likely to succeed. At each step, the correctness criterion would be applied to this subset of the labeled vertices. For example, the labeled set could be stored in a cell array, cell sorted by distance. The correctness criterion would be applied to vertices whose current distance is less than a certain threshold, as vertices with small distances are more likely to be correct than vertices with large distances. Alternatively, the labeled vertices could be cell sorted by some other quantity, perhaps the difference of the current distance and the minimum incident edge weight from an unknown vertex. Again, vertices with lower values are more likely to be correct. Yet another possibility would be to factor in whether the distance at a vertex decreased during the previous step. In summary, there are many possibilities for partially ordering the labeled vertices to select a subset to be tested for correctness. A more sophisticated data structure for storing the labeled set may improve performance, particularly for harder problems. One can use a cell array data structure to reduce the computational complexity of the MCC algorithm for the case that the edge weight ratio \e R is finite. As introduced before, let the edge weights be in the interval \f$[A .. B]\f$. Each cell in the cell array holds the labeled vertices with distances in the interval \f$[ n A .. (n+1) A)\f$ for some integer \e n. Consider the MCC algorithm in progress. Let \f$\mu\f$ be the minimum labeled distance. The labeled distances are in the range \f$[\mu .. \mu + B)\f$. We define \f$m = \lfloor \mu / A \rfloor\f$. The first cell in the cell array holds labeled vertices in the interval \f$[ m A .. (m+1) A)\f$. By the level 1 correctness criterion, all the labeled vertices in this cell are correct. We intend to apply the correctness criterion only to the labeled vertices in the first cell. If they labeled their neighbors, the neighbors would have distances in the interval \f$[\mu + A .. \mu + A + B)\f$. Thus we need a cell array with \f$\lceil R \rceil + 1\f$ cells in order to span the interval \f$[\mu .. \mu + A + B)\f$. (This interval contains all the currently labeled distances and the labeled distances resulting from labeling neighbors of vertices in the first cell.) At each step of the algorithm, the vertices in the first cell become known and label their neighbors. If an unlabeled vertex becomes labeled, it is added to the appropriate cell. If a labeled vertex decreases its distance, it is moved to a lower cell. After the labeling, the first cell is removed and an empty cell is added at the end. As Dijkstra's algorithm requires that each labeled vertex stores a pointer into the heap of labeled vertices, this modification of the MCC algorithm would require storing a pointer into the cell array. Now consider the computational complexity of the MCC algorithm that uses a cell array to store the labeled vertices. The complexity of adding or removing a vertex from the labeled set is unchanged, because the complexity of adding to or removing from the cell array is \f$\mathcal{O}(1)\f$. The cost of decreasing the distance of a labeled vertex is unchanged because moving a vertex in the cell array has cost \f$\mathcal{O}(1)\f$. We reduce the cost of applying the correctness criterion from \f$\mathcal{O}(R V)\f$ to \f$\mathcal{O}(V)\f$ because each vertex is ``tested'' only once. We must add the cost of examining cells in the cell array. Let \e D be the maximum distance in the shortest path tree. Then in the course of the computation, \f$D/A\f$ cells will be examined. The total computational complexity of the MCC algorithm with a cell array for the labeled vertices is \f$\mathcal{O}(E + V + D/A)\f$. Note that \e D could be as large as \f$(V-2)B + A\f$. In this case \f$D/A \approx R V\f$ and the computational complexity is the same as that for the plain MCC algorithm. <!--------------------------------------------------------------------------> /*! \section shortest_paths_future_reweighting Re-weighting the Edges Let <em>w(u,v)</em> be the weight of the edge from vertex \e u to vertex \e v. Consider a function \f$f : V \to \mathbb{R}\f$ defined on the vertices and a modified weight function \f$\hat{w}\f$: \f[ \hat{w}(u,v) = w(u,v) + f(u) - f(v) \f] It is straightforward to show that any shortest path with weight function \e w is also a shortest path with weight function \f$\hat{w}\f$ cite{cormen:2001}. %% Section 25.3 This is because \e any path from vertex \e a to vertex \e b is changed by \f$f(a) - f(b)\f$. The rest of the \e f terms telescope in the sum. It may be possible to re-weight the edges of a graph to improve the performance of the MCC algorithm. The number of correctness tests performed depends on the ratio of the highest to lowest edge weight. By choosing \e f to decrease this ratio, one could decrease the execution time. One might determine the function \e f as a preprocessing step or perhaps compute it on the fly as the shortest-paths computation progresses. Consider the situation at a single vertex. Assume that \e f is zero at all other vertices. Let \c minimumIncident, \c minimumAdjacent, \c maximumIncident and \c maximumAdjacent denote the minimum and maximum incident and adjacent edge weights. If <tt>minimumAdjacent < minimumIncident</tt> and <tt>maximumAdjacent < maximumIncident</tt>, then choosing \f[ f = \frac{\mathtt{minimumIncident} - \mathtt{minimumAdjacent}}{2} \f] will reduce the ratio of the highest to lowest edge weight at the given vertex. Likewise for the case: <tt>minimumAdjacent > minimumIncident</tt> and <tt>maximumAdjacent > maximumIncident</tt>. */ //============================================================================= //============================================================================= /*! \page shortest_paths_conclusions Conclusions Marching with a Correctness Criterion is a promising new approach for solving shortest path problems. MCC works well on easy problems. That is, if most of the labeled vertices are correct, then the algorithm is efficient. It requires few correctness tests before a vertex is determined to be correct. For such cases, the MCC algorithm outperforms Dijkstra's algorithm. For hard problems, perhaps in which the edge weight ratio is high and/or there are many edges per vertex, fewer labeled vertices have the correct distance. This means that the MCC algorithm requires more correctness tests. For such cases, Dijkstra's algorithm has lower execution times. */ #endif
true
01121fe7e6ee0d7f1b748a134f3019ef3f9d797c
C++
yt-project/libyt
/src/logging.cpp
UTF-8
4,818
2.5625
3
[ "BSD-3-Clause" ]
permissive
#define NO_PYTHON #include "yt_combo.h" #undef NO_PYTHON #include <string.h> #include <stdarg.h> // width of log prefix ==> [LogPrefixWidth] messages static const int LogPrefixWidth = 10; //------------------------------------------------------------------------------------------------------- // Function : log_info // Description : Print out basic messages to standard output // // Note : 1. Work only for verbose level >= YT_VERBOSE_INFO // --> Rely on the global variable "g_param_libyt" // 2. Messages are printed out to standard output with a prefix "[YT_INFO] " // 3. Use the variable argument lists provided in "stdarg" // --> It is equivalent to call "fprintf( stdout, format, ... ); fflush( Type );" // 4. Print INFO only in root rank. // // Parameter : format : Output format // ... : Arguments in vfprintf // // Return : None //------------------------------------------------------------------------------------------------------- void log_info( const char *format, ... ) { if ( g_myrank != 0 ) return; // work only for verbose level >= YT_VERBOSE_INFO if ( g_param_libyt.verbose < YT_VERBOSE_INFO ) return; // flush previous messages fflush( stdout ); // print messages va_list arg; va_start( arg, format ); fprintf( stdout, "[%-*s] ", LogPrefixWidth, "YT_INFO" ); vfprintf( stdout, format, arg ); fflush( stdout ); va_end( arg ); } // FUNCTION : log_info //------------------------------------------------------------------------------------------------------- // Function : log_warning // Description : Print out warning messages to standard error // // Note : 1. Similar to log_info, excpet that it works only for verbose level >= YT_VERBOSE_WARNING // 2. Messages are printed out to standard output with a prefix "[YT_WARNING] " // // Parameter : format : Output format // ... : Arguments in vfprintf // // Return : None //------------------------------------------------------------------------------------------------------- void log_warning( const char *format, ... ) { // work only for verbose level >= YT_VERBOSE_WARNING if ( g_param_libyt.verbose < YT_VERBOSE_WARNING ) return; // flush previous messages fflush( stderr ); // print messages va_list arg; va_start( arg, format ); fprintf( stderr, "[%-*s] ", LogPrefixWidth, "YT_WARNING" ); vfprintf( stderr, format, arg ); fflush( stderr ); va_end( arg ); } // FUNCTION : log_warning //------------------------------------------------------------------------------------------------------- // Function : log_debug // Description : Print out debug messages to standard output // // Note : 1. Similar to log_info, excpet that it works only for verbose level >= YT_VERBOSE_DEBUG // 2. Messages are printed out to standard output with a prefix "[YT_DEBUG] " // // Parameter : format : Output format // ... : Arguments in vfprintf // // Return : None //------------------------------------------------------------------------------------------------------- void log_debug( const char *format, ... ) { // work only for verbose level >= YT_VERBOSE_DEBUG if ( g_param_libyt.verbose < YT_VERBOSE_DEBUG ) return; // flush previous messages fflush( stderr ); // print messages va_list arg; va_start( arg, format ); fprintf( stderr, "[%-*s] ", LogPrefixWidth, "YT_DEBUG" ); vfprintf( stderr, format, arg ); fflush( stderr ); va_end( arg ); } // FUNCTION : log_debug //------------------------------------------------------------------------------------------------------- // Function : log_error // Description : Print out error messages to standard error // // Note : 1. Similar to log_info, excpet that messages are always printed out regardless of the // verbose level // 2. Messages are printed out to standard error with a prefix "[YT_ERROR] " // 3. A convenient macro "YT_ABORT" is defined in yt_macro.h, which calls log_error, print // out the line number, and returns YT_FAIL // // Parameter : format : Output format // ... : Arguments in vfprintf // // Return : None //------------------------------------------------------------------------------------------------------- void log_error( const char *format, ... ) { // flush previous messages fflush( stderr ); // print messages va_list arg; va_start( arg, format ); fprintf( stderr, "[%-*s] ", LogPrefixWidth, "YT_ERROR" ); vfprintf( stderr, format, arg ); fflush( stderr ); va_end( arg ); } // FUNCTION : log_error
true
fd4ea130c32e08364d011e8bf81df12919a158fb
C++
RockyYan1994/Algorithm
/42_trapping_rain_water.cpp
UTF-8
501
2.625
3
[]
no_license
/* */ class Solution { public: int trap(vector<int>& height) { int sum = 0; int left = 0, for(int i=0;i<height.size();i++){ int right = i; if(height[i]>=height[left]){ int temp = 0; for(int j=left+1;j<i;j++){ temp += height[left]-height[j]; } sum+=temp; left = i; } if(height[i]<height[left]&&left==i-1) } } };
true
8f734a7c2ae52adb0d22517f73f671157a4080da
C++
storypku/lucene-cpp
/util/file_reader.h
UTF-8
1,037
2.78125
3
[]
no_license
#ifndef FILE_READER_H #define FILE_READER_H #include "reader.h" namespace Lucene { /// Convenience class for reading character files. class FileReader : public Reader { public: /// Create a new FileReader, given the file name to read from. FileReader(const String& fileName); virtual ~FileReader(); LUCENE_CLASS(FileReader); protected: IfstreamPtr m_file; int64_t m_length_; ByteArray m_fileBuffer; public: static const int32_t FILE_EOF; static const int32_t FILE_ERROR; public: /// Read a single character. virtual int32_t read(); /// Read characters into a portion of an array. virtual int32_t read(char* buffer, int32_t offset, int32_t length); /// Close the stream. virtual void close(); /// Tell whether this stream supports the mark() operation. virtual bool mark_supported(); /// Reset the stream. virtual void reset(); /// The number of bytes in the file. virtual int64_t length(); }; } // namespace Lucene #endif // FILE_READER_H
true
742e31eef5e244628aa92315225b6558d29d65bd
C++
lisanna-dettwyler/HiddenWorlds
/HWClient/HWText.cpp
UTF-8
2,668
2.703125
3
[]
no_license
#include "pch.h" #include "HWText.h" HWText::HWText(HWFont* font, const std::string& text, glm::vec2 location, glm::vec4 color) { this->font = font; this->text = text; this->location = location; this->color = color; is_dirty = true; } HWText::~HWText() { } void HWText::Render() { if(is_dirty) { F32 r = color.r, g = color.g, b = color.b, a = color.a; std::vector<HWFontVertex> verts; std::vector<U16> indices; glm::vec2 pen; for(S32 i = 0; i < text.length(); ++i) { if(font->metrics.find(text[i]) != font->metrics.end()) { HWFontMetric glyph = font->metrics[text[i]]; if(i > 0 && glyph.kerning.find(text[i - 1]) != glyph.kerning.end()) { F32 kerning = glyph.kerning[text[i - 1]]; pen.x += kerning; } int x0 = (int)(pen.x + glyph.offset_x); int y0 = (int)(pen.y + glyph.offset_y); int x1 = (int)(x0 + glyph.width); int y1 = (int)(y0 - glyph.height); float s0 = glyph.s0; float t0 = glyph.t0; float s1 = glyph.s1; float t1 = glyph.t1; U16 base = i * 4; U16 idx[6] = { base, base + 1, base + 2, base, base + 2, base + 3, }; HWFontVertex v[4] = { { x0,y0,0, s0,t0, r,g,b,a }, { x0,y1,0, s0,t1, r,g,b,a }, { x1,y1,0, s1,t1, r,g,b,a }, { x1,y0,0, s1,t0, r,g,b,a }, }; AddVerts(verts, indices, v, idx); pen.x += glyph.advance_x; } } //font->model->AddVertexData(&verts[0], verts.size() * sizeof(verts[0])); //font->model->AddIndexData(&indices[0], indices.size() * sizeof(indices[0])); font->vertex_buffer->SetDataDirect(&verts[0], verts.size() * sizeof(verts[0])); font->index_buffer->SetDataDirect(&indices[0], indices.size() * sizeof(indices[0])); font->model->Transfer(); is_dirty = false; } font->shader_program->UseProgram(); font->model->Bind(); font->atlas->Bind(font->shader_program->GetUniformID("font_map")); glUniform1f(font->shader_program->GetUniformID("smoothness"), 0.0f); font->model->SetPosition(glm::vec3(location, 0.f)); font->shader_program->SetUniformValue("MVP", font->model->GetMatrix()); glDrawElements(GL_TRIANGLES, font->index_buffer->Count(), (GLenum)font->index_buffer->GetIndexType(), (void*)0); } void HWText::AddVerts(std::vector<HWFontVertex>& vec, std::vector<U16>& idx, HWFontVertex v[4], U16 i[6]) { vec.push_back(v[0]); vec.push_back(v[1]); vec.push_back(v[2]); vec.push_back(v[3]); idx.push_back(i[0]); idx.push_back(i[1]); idx.push_back(i[2]); idx.push_back(i[3]); idx.push_back(i[4]); idx.push_back(i[5]); } void HWText::SetText(const std::string& text) { if(this->text != text) { this->text = text; is_dirty = true; } }
true
bb31661ae7b9fb8167d1732837ea9337d14c6900
C++
dejbug/cathy
/Dragger.h
UTF-8
2,639
2.828125
3
[ "MIT" ]
permissive
#pragma once #include "lib/Cursor.h" template <class Chessboard> class Checker { private: Chessboard * chessboard; public: Checker () : chessboard(0) {} public: void Create (Chessboard * chessboard) { this->chessboard = chessboard; } bool CheckUserMove (unsigned char dstCellIndex) { return chessboard->CheckUserMove (dstCellIndex); } }; /* class ChessboardModel { public: typedef struct { HWND handle; Chessfont * font; int cellsize; } CHESSBOARDVIEWINFO; public: virtual bool GetCellIndexFromPoint (unsigned char & index, int x, int y) = 0; virtual unsigned char GetCellData (unsigned char index) = 0; virtual void SetCellData (unsigned char index, unsigned char data) = 0; virtual bool TranslateToken (char token, unsigned char & piece, unsigned char & color) = 0; virtual void GetPiece (unsigned index, unsigned char & piece, unsigned char & color) = 0; virtual void SetPiece (unsigned index, unsigned char & piece, unsigned char & color) = 0; virtual void GetWindowInfo (CHESSBOARDVIEWINFO & info) = 0; virtual void Invalidate () = 0; }; class Dragger { private: ChessboardModel * model; bool dragging; unsigned char draggedCellIndex; unsigned char draggedCellData; public: Dragger () : model(0), dragging(false), draggedCellIndex(0), draggedCellData(0) { } void Attach (ChessboardModel * model) { this->model = model; } public: bool DragPieceAtPoint (short x, short y) { unsigned char piece, color; model->GetCellIndexFromPoint (draggedCellIndex, x, y); draggedCellData = model->GetCellData (draggedCellIndex); if (0 == draggedCellData) return false; model->TranslateToken (draggedCellData, piece, color); model->SetCellData (draggedCellIndex, 0); model->Invalidate (); COLORREF transparentcolor = RGB(192,192,192); Surface surface; surface.Create (handle); surface.Resize (cellsize, cellsize); surface.Clear (transparentcolor); surface.Select (font); PaintPiece (surface, piece, color, 0, 0, cellsize); HICON temp = Cursor::CreateCursorFromBitmap (surface, surface, transparentcolor, cellsize); if (cursor) SetCursor (temp), DestroyCursor (cursor), cursor = temp; else SetCursor (cursor = temp); SetCapture (handle); dragging = true; return dragging; } bool DropPiece () { if (dragging) { dragging = false; ReleaseCapture (); if (cursor) DestroyCursor (cursor), cursor = 0; model->SetCellData (draggedCellIndex, draggedCellData); } model->Invalidate (); return true; } }; */
true
9117798db264d74e503830ffc78a23936e61b88a
C++
kopikopio/aizu-online-algorithm
/ALDS1_2/安定ソート(改良).cpp
UTF-8
1,922
3.65625
4
[]
no_license
#include <stdio.h> using namespace std; struct Card { char pattern; // 絵柄 int value; // 値 }; void printCard(Card* card, int N) { for (int i=0; i<N-1; i++) { printf("%c", card[i].pattern); printf("%d ", card[i].value); } printf("%c", card[N-1].pattern); printf("%d\n", card[N-1].value); } void change(Card* card, int i, int j) { char tmpP = card[i].pattern; int tmpV = card[i].value; // 絵柄交換 card[i].pattern = card[j].pattern; card[j].pattern = tmpP; // 値交換 card[i].value = card[j].value; card[j].value = tmpV; } // バブルソート void bublleSort(Card* card, int N) { int flag = 1; int count = 0; while(flag) { flag = 0; for (int j=N-1; j>=1; j--) { if(card[j].value < card[j-1].value) { change(card, j, j - 1); flag = 1; count++; } } } // 整列された配列 printCard(card, N); printf("%d\n", count); } // 選択ソート void selectingSort(Card* card, int N) { int count = 0; for(int i=0; i<=N-2; i++) { int minj = i; for(int j=i; j<=N-1; j++) { if(card[minj].value > card[j].value) { minj = j; } } change(card, i, minj); if (i != minj) count++; } // 整列された配列 printCard(card, N); printf("%d\n", count); } int checkStable(Card before, Card after) { } int main() { int N, i, j; Card card[100]; // 入力値取得 scanf("%d", &N); for (int i=0; i<N; i++) { card[i].pattern = getchar(); // 改行・空白文字を除去 while( card[i].pattern == ' ' || card[i].pattern == '\n') { card[i].pattern = getchar(); } scanf("%d", &card[i].value); } printCard(card, N); bublleSort(card, N); }
true