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
95e7d37e7afcbaa292d706049bec34c92e2c5d9c
C++
ErickHernandez/Evaluaciones_Compi_1
/Prueba2_P2_2020/parser.h
UTF-8
633
2.65625
3
[]
no_license
#ifndef _EXPR_PARSER_H #define _EXPR_PARSER_H #include <iosfwd> #include "lexer.h" class Parser { public: Parser(Lexer &lexer): lexer (lexer) { } void parse() { currToken = lexer.getNextToken(); input(); if(currToken != Token::Eof){ throw "Syntax Error not EoF Reached"; } else { std::cout<<"Perfect Sintax!"<<"\n"; } } private: void input(); void inputP(); void stmt_list(); void opt_eol(); void stmt(); void assign(); void fun_decl(); void opt_arg_list(); void arg_list(); void arg(); void expr(); void term(); void factor(); private: Lexer &lexer; Token currToken; }; #endif
true
ce3b88f8835e93faa7c3b5d35dc96fe6ca9cb426
C++
ElNatcho/SenseHat_TicTacToe
/RPi_TicTacToe/CGridRenderer.cpp
ISO-8859-1
2,176
2.984375
3
[]
no_license
#include"CGridRenderer.hpp" // -- Konstruktor -- CGridRenderer::CGridRenderer() { // Alloc Memory _timeMgr = new ST::CTimeMgr(); _ledMatrix = new CLEDMatrix(GD::fb); _curSelected = new _selected{}; _elapsedTime = new sf::Time(); _curSelected->x = new int; _curSelected->y = new int; _curSelected->display = new bool; // Werte setzen *_curSelected->x = -1; *_curSelected->y = -1; *_curSelected->display = true; } // -- renderGrid -- // Methode die das TicTacToe-Spielfeld in der LED-Matrix rendert // @param grid: Spielfeld, dass gezeichnet werden soll // void CGridRenderer::renderGrid(std::array<std::array<char, 3>, 3> grid) { _timeMgr->addElapsedTime(_elapsedTime); if (_elapsedTime->asSeconds() >= 0.5F) { *_curSelected->display = *_curSelected->display ? false : true; *_elapsedTime = _elapsedTime->Zero; } _ledMatrix->clearMatrix(); for (int i = 0; i < grid.size(); i++) { for (int j = 0; j < grid.at(i).size(); j++) { if ((*_curSelected->x == j && *_curSelected->y == i && *_curSelected->display) || (*_curSelected->x != j || *_curSelected->y != i)) { if (grid.at(i).at(j) == PL_1) _ledMatrix->displayRect(j * 3, i * 3, 2, 2, _color_pl1); else if (grid.at(i).at(j) == PL_2) _ledMatrix->displayRect(j * 3, i * 3, 2, 2, _color_pl2); else if (grid.at(i).at(j) == NONE) _ledMatrix->displayRect(j * 3, i * 3, 2, 2, _color_none); } } } _ledMatrix->displayRect(2, 0, 1, 8, _color_border); _ledMatrix->displayRect(5, 0, 1, 8, _color_border); _ledMatrix->displayRect(0, 2, 8, 1, _color_border); _ledMatrix->displayRect(0, 5, 8, 1, _color_border); } // -- setSelected -- // Methode die das selectierte Feld auswhlt // @param x, y: Feld, dass ausgewhlt werden soll // bool CGridRenderer::setSelected(int x, int y) { if (x >= 0 && x <= 2 && y >= 0 && y <= 2) { *_curSelected->x = x; *_curSelected->y = y; *_curSelected->display = true; *_elapsedTime = _elapsedTime->Zero; return true; } else { return false; } } // -- Destruktor -- CGridRenderer::~CGridRenderer() { // Free Memory SAFE_DELETE(_timeMgr); SAFE_DELETE(_ledMatrix); SAFE_DELETE(_curSelected); SAFE_DELETE(_elapsedTime); }
true
26420da9c6dd96b0f4431cfc368417276981d9e7
C++
haus-bus/HausBusControls-ESP8266
/lib/ArduinoHAL/ResetSystem.h
UTF-8
2,067
2.859375
3
[]
no_license
/* * ResetSystem.h * * Created on: 17.07.2017 * Author: Viktor Pankraz */ #ifndef ResetSystem_H #define ResetSystem_H #include <Arduino.h> class ResetSystem { //// Operations //// public: ///*! \brief This function lock the entire clock system configuration. // * // * This will lock the configuration until the next reset, or until the // * External Oscillator Failure Detections (XOSCFD) feature detects a failure // * and switches to internal 2MHz RC oscillator. // */ inline static void clearSources( uint8_t sources = 0xFF ) { } ///*! \brief This function lock the entire clock system configuration. // * // * This will lock the configuration until the next reset, or until the // * External Oscillator Failure Detections (XOSCFD) feature detects a failure // * and switches to internal 2MHz RC oscillator. // */ inline static uint8_t getSources() { return 0; } inline static uint8_t isBrownOutReset() { return false; } inline static uint8_t isDebuggerReset() { return false; } inline static uint8_t isExternalReset() { return false; } inline static uint8_t isPowerOnReset() { return false; } inline static uint8_t isSoftwareReset() { return false; } inline static uint8_t isSpikeDetectorReset() { return false; } inline static uint8_t isWatchDogReset() { return false; } ///*! \brief This function lock the entire clock system configuration. // * // * This will lock the configuration until the next reset, or until the // * External Oscillator Failure Detections (XOSCFD) feature detects a failure // * and switches to internal 2MHz RC oscillator. // */ inline static void reset( bool hard = false ) { hard ? ESP.reset() : ESP.restart(); } }; #endif
true
04b73e527cc5b6757e86df1daa7235d492774eac
C++
mehulthakral/logic_detector
/backend/CDataset/hasCycle/hasCycle_6.cpp
UTF-8
668
3.46875
3
[]
no_license
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: class ListNode{ public: ListNode* next; int val; }; bool hasCycle(ListNode *head) { if(head==NULL){ return false; } ListNode* temp1=head; ListNode* temp2=head; while(temp1->next && temp1->next->next){ temp1=temp1->next->next; temp2=temp2->next; if(temp2==temp1){ return true; } } return false; } };
true
68ab30a52107a45a231d622a24984fc6e1a63125
C++
yoongoing/Algorithm
/~2019/1546.cpp
UTF-8
320
2.59375
3
[]
no_license
#include <stdio.h> int main(int argc, char const *argv[]) { int n,i; float data[1001],max=0,total=0; scanf("%d",&n); for(i=0; i<n; i++){ scanf("%f",&data[i]); if(data[i] > max) max = data[i]; } for(i=0; i<n; i++){ data[i] = (data[i] / max )*100; total += data[i]; } printf("%f\n",total/n); return 0; }
true
da7b2bcab1b640b935e70c9776df56696c98913e
C++
Guyntax/INF1010
/TP3/src/Consultation.cpp
UTF-8
2,576
3.328125
3
[]
no_license
//! Implémentation de la classe abstraite Consultation qui permet de gérer les consultations de l’hôpital. //! \Authors: Didier Blach-Laflèche & Maude Tremblay //! \date 07 Juin 2020 #include "Consultation.h" #include <iostream> #include <string> //! Constructeur par paramètres de la classe abstraite Consultation //! \param medecin Le medecin responsable de la consultation //! \param patient Le patient qui demande une consultation //! \param date La date de la consultation Consultation::Consultation(Medecin& medecin, Patient& patient, const std::string& date) : medecin_(&medecin), patient_(&patient), date_(date), prix_(PRIX_DE_BASE) { } //! Méthode qui retourne le médecin de la consultation //! \return medecin_ le pointeur vers le médecin de la consultation Medecin* Consultation::getMedecin() const { return medecin_; } //! Méthode qui retourne le patient de la consultation //! \return patient_ le pointeur vers le patient de la consultation Patient* Consultation::getPatient() const { return patient_; } //! Méthode qui retourne la date de la consultation //! \return date_ la date de la consultation const std::string& Consultation::getDate() const { return date_; } //! Méthode qui affiche les informations d'une consultation //! \param os Le stream dans lequel afficher void Consultation::afficher(std::ostream& os) const { // Chercher le nom de la classe. Elle peut être ConsultationEnligne ou ConsultationPhysique. std::string typeConsultation = typeid(*this).name();//Utiliser typeid().name() typeConsultation.erase(0, 6); // Efface "Class " // Chercher le nom de la classe.Elle peut être Medecin ou MedecinResident. std::string typeMedecin = typeid(*medecin_).name();//Utiliser typeid().name() ; typeMedecin.erase(0, 6); // Efface "Class " // Chercher le nom de la classe. Elle peut être Patient ou PatientEtudiant. std::string typePatient = typeid(*patient_).name();//Utiliser typeid().name() typePatient.erase(0, 6); // Efface "Class " os << "Consultation: " << "\n\tType: " << typeConsultation//Extraire le nom de la classe du string typeConsultation << "\n\t\t" << typeMedecin//Extraire le nom de la classe du string typeMedecin << ": " << medecin_->getId() // afficher Id du medecin << "\n\t\t" << typePatient//Extraire le nom de la classe du string typePatient << ": " << patient_->getNumeroAssuranceMaladie()// afficher le numero d'assurance maladie du patient << "\n\t\t" << "Date de consultation: " << date_ << "\n"; //Afficher date_ // le ostream est passé par référence, donc pas besoin de return }
true
5aa793181c71237f5e47e57d98993ff79e6a6dea
C++
ShinW0330/ps_study
/06_Tree/Level2/9934.cpp
UTF-8
1,342
3.484375
3
[]
no_license
// 완전 이진 트리 // https://www.acmicpc.net/problem/9934 // 힌트 // 1. Input으로 들어오는 값들을 하나의 배열에 입력 받았을때, 가운데 값을 중심으로 왼쪽 오른쪽 트리가 만들어짐 // 2. 1의 방식이 재귀함수 방식으로 왼쪽 트리, 오른족 트리에서 동일하게 적용됨 // 3. 트리의 깊이에 따른 vector를 선언하여 입력을 받아놓으면, 나중에 깊이에 따라 출력할 수 있음. #include <iostream> #include <algorithm> #include <vector> using namespace std; vector<int> v; vector<vector<int> > answer; void solve(int s, int e, int depth) { if (e - s == 1) { answer[depth].push_back(v[s]); } else { int m = (s + e - 1) / 2; answer[depth].push_back(v[m]); solve(s, m, depth + 1); solve(m + 1, e, depth + 1); } } int main() { int k; int num = 1; cin >> k; for (int i = 0; i < k; i++) { num *= 2; } num -= 1; v = vector<int>(num); answer = vector<vector<int> >(k); for (int i = 0; i < num; i++) { cin >> v[i]; } solve(0, num, 0); for (int i = 0; i < k; i++) { for (int j = 0; j < answer[i].size(); j++) { cout << answer[i][j] << " "; } cout << endl; } return 0; }
true
9a39f84d542dc833195218a369987089c89cafc3
C++
kcat/XLEngine
/thirdparty/AngelCode/sdk/tests/test_feature/source/test_object.cpp
UTF-8
6,957
2.5625
3
[ "Zlib", "MIT" ]
permissive
#include "utils.h" namespace TestObject { #define TESTNAME "TestObject" static const char *script1 = "void TestObject() \n" "{ \n" " Object a = TestReturn(); \n" " a.Set(1); \n" " TestArgVal(a); \n" " Assert(a.Get() == 1); \n" " TestArgRef(a); \n" " Assert(a.Get() != 1); \n" " TestProp(); \n" " TestSysArgs(); \n" " TestSysReturn(); \n" " TestGlobalProperty(); \n" "} \n" "Object TestReturn() \n" "{ \n" " return Object(); \n" "} \n" "void TestArgVal(Object a) \n" "{ \n" "} \n" "void TestArgRef(Object &out a) \n" "{ \n" " a = Object(); \n" "} \n" "void TestProp() \n" "{ \n" " Object a; \n" " a.val = 2; \n" " Assert(a.Get() == a.val); \n" " Object2 b; \n" " b.obj = a; \n" " Assert(b.obj.val == 2); \n" "} \n" "void TestSysReturn() \n" "{ \n" " // return object \n" " // by val \n" " Object a; \n" " a = TestReturnObject(); \n" " Assert(a.val == 12); \n" " // by ref \n" " a.val = 12; \n" " TestReturnObjectRef() = a; \n" " a = TestReturnObjectRef(); \n" " Assert(a.val == 12); \n" "} \n" "void TestSysArgs() \n" "{ \n" " Object a; \n" " a.val = 12; \n" " TestSysArgRef(a); \n" " Assert(a.val == 2); \n" " a.val = 12; \n" " TestSysArgVal(a); \n" " Assert(a.val == 12); \n" "} \n" "void TestGlobalProperty() \n" "{ \n" " Object a; \n" " a.val = 12; \n" " TestReturnObjectRef() = a; \n" " a = obj; \n" " obj = a; \n" "} \n"; class CObject { public: CObject() {val = 0;/*printf("C:%x\n",this);*/} ~CObject() {/*printf("D:%x\n", this);*/} void Set(int v) {val = v;} int Get() {return val;} int val; }; void Construct(CObject *o) { new(o) CObject(); } void Destruct(CObject *o) { o->~CObject(); } class CObject2 { public: CObject obj; }; void Construct2(CObject2 *o) { new(o) CObject2(); } void Destruct2(CObject2 *o) { o->~CObject2(); } CObject TestReturnObject() { CObject obj; obj.val = 12; return obj; } CObject obj; CObject *TestReturnObjectRef() { return &obj; } void TestSysArgVal(CObject obj) { assert(obj.val == 12); obj.val = 0; } void TestSysArgRef(CObject &obj) { // We're not receiving the true object, only a reference to a place holder for the output value assert(obj.val == 0); obj.val = 2; } bool Test() { if( strstr(asGetLibraryOptions(), "AS_MAX_PORTABILITY") ) { printf("%s: Skipped due to AS_MAX_PORTABILITY\n", TESTNAME); return false; } bool fail = false; int r; asIScriptEngine *engine = asCreateScriptEngine(ANGELSCRIPT_VERSION); engine->RegisterGlobalFunction("void Assert(bool)", asFUNCTION(Assert), asCALL_GENERIC); engine->RegisterObjectType("Object", sizeof(CObject), asOBJ_VALUE | asOBJ_POD | asOBJ_APP_CLASS_CD); engine->RegisterObjectBehaviour("Object", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(Construct), asCALL_CDECL_OBJLAST); engine->RegisterObjectBehaviour("Object", asBEHAVE_DESTRUCT, "void f()", asFUNCTION(Destruct), asCALL_CDECL_OBJLAST); engine->RegisterObjectMethod("Object", "void Set(int)", asMETHOD(CObject, Set), asCALL_THISCALL); engine->RegisterObjectMethod("Object", "int Get()", asMETHOD(CObject, Get), asCALL_THISCALL); engine->RegisterObjectProperty("Object", "int val", offsetof(CObject, val)); engine->RegisterObjectType("Object2", sizeof(CObject2), asOBJ_VALUE | asOBJ_POD | asOBJ_APP_CLASS); engine->RegisterObjectBehaviour("Object2", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(Construct2), asCALL_CDECL_OBJLAST); engine->RegisterObjectBehaviour("Object2", asBEHAVE_DESTRUCT, "void f()", asFUNCTION(Destruct2), asCALL_CDECL_OBJLAST); engine->RegisterObjectProperty("Object2", "Object obj", offsetof(CObject2, obj)); engine->RegisterGlobalFunction("Object TestReturnObject()", asFUNCTION(TestReturnObject), asCALL_CDECL); engine->RegisterGlobalFunction("Object &TestReturnObjectRef()", asFUNCTION(TestReturnObjectRef), asCALL_CDECL); engine->RegisterGlobalFunction("void TestSysArgVal(Object)", asFUNCTION(TestSysArgVal), asCALL_CDECL); engine->RegisterGlobalFunction("void TestSysArgRef(Object &out)", asFUNCTION(TestSysArgRef), asCALL_CDECL); engine->RegisterGlobalProperty("Object obj", &obj); // Test objects with no default constructor engine->RegisterObjectType("ObjNoConstruct", sizeof(int), asOBJ_VALUE | asOBJ_POD | asOBJ_APP_PRIMITIVE); COutStream out; engine->AddScriptSection(0, TESTNAME, script1, strlen(script1), 0); engine->SetMessageCallback(asMETHOD(COutStream,Callback), &out, asCALL_THISCALL); r = engine->Build(0); if( r < 0 ) { fail = true; printf("%s: Failed to compile the script\n", TESTNAME); } asIScriptContext *ctx; r = engine->ExecuteString(0, "TestObject()", &ctx); if( r != asEXECUTION_FINISHED ) { if( r == asEXECUTION_EXCEPTION ) PrintException(ctx); printf("%s: Failed to execute script\n", TESTNAME); fail = true; } if( ctx ) ctx->Release(); engine->ExecuteString(0, "ObjNoConstruct a; a = ObjNoConstruct();"); if( r != 0 ) { fail = true; printf("%s: Failed\n", TESTNAME); } CBufferedOutStream bout; engine->SetMessageCallback(asMETHOD(CBufferedOutStream,Callback), &bout, asCALL_THISCALL); r = engine->ExecuteString(0, "Object obj; float r = 0; obj = r;"); if( r >= 0 || bout.buffer != "ExecuteString (1, 32) : Error : Can't implicitly convert from 'float&' to 'Object&'.\n" ) { printf("%s: Didn't fail to compile as expected\n", TESTNAME); fail = true; } // Mustn't allow registration of assignment behaviour as global behaviour r = engine->RegisterGlobalBehaviour(asBEHAVE_ASSIGNMENT, "Object &f(const Object &in, const Object &in)", asFUNCTION(0), asCALL_GENERIC); if( r >= 0 ) { fail = true; } engine->Release(); // Success return fail; } } // namespace
true
485990f327a91b156e8562ea1ac7fec405dc1628
C++
jinnaiyuu/Parallel-Best-First-Searches
/src/multi_a_star.cc
UTF-8
1,535
2.578125
3
[ "MIT" ]
permissive
// © 2014 the PBNF Authors under the MIT license. See AUTHORS for the list of authors. /** * \file multi_a_star.cc * * * * \author Ethan Burns * \date 2008-11-07 */ #include "util/thread.h" #include "util/timer.h" #include "state.h" #include "astar.h" #include "multi_a_star.h" MultiAStar::MultiAStar(unsigned int n_threads) : n_threads(n_threads) {} MultiAStar::~MultiAStar(void) {} class MultiAStarThread : public Thread { public: MultiAStarThread(Timer *t, State *init) : timer(t), init(init), path(NULL) {} vector<State *> *get_path(void) { return path; } unsigned int get_expanded(void) { return search.get_expanded(); } unsigned int get_generated(void) { return search.get_generated(); } void run(void) { path = search.search(timer, init->clone()); } private: AStar search; Timer *timer; State *init; vector<State *> *path; }; vector<State *> *MultiAStar::search(Timer *t, State *init) { vector<MultiAStarThread *> threads; vector<State *> *path = NULL; for (unsigned int i = 0; i < n_threads; i += 1) threads.push_back(new MultiAStarThread(t, init)); for(vector<MultiAStarThread *>::iterator i = threads.begin(); i != threads.end(); i++) (*i)->start(); for(vector<MultiAStarThread *>::iterator i = threads.begin(); i != threads.end(); i++) { (*i)->join(); if (!path) path = (*i)->get_path(); else delete (*i)->get_path(); set_expanded(get_expanded() + (*i)->get_expanded()); set_generated(get_generated() + (*i)->get_generated()); } return path; }
true
7561c712e83f374ab74e2c44b84742d7ef8b95d4
C++
iamard/Online-Judgement
/LeetCode/811. Subdomain Visit Count.cpp
UTF-8
1,121
2.953125
3
[]
no_license
class Solution { public: vector<string> subdomainVisits(vector<string>& cpdomains) { unordered_map<string, int> table; for (int i = 0; i < cpdomains.size(); i++) { string domain = cpdomains[i]; int pos = 0; while(pos < domain.length() && domain[pos] != ' ') { pos++; } int value = stoi(domain.substr(0, pos)); pos++; while(pos < domain.length()) { string curr = domain.substr(pos); if (table.find(curr) == table.end()) { table[curr] = value; } else { table[curr] += value; } while(pos < domain.length() && domain[pos] != '.') { pos++; } pos++; } } vector<string> result; for (auto &itor: table) { string value = to_string(itor.second) + " " + itor.first; result.push_back(value); } return result; } };
true
ef2e226232fbd60806f85ae12e99884efa051635
C++
eeeeeeeelias/cpp_hw_quarter2
/contest_11/7_cut.cpp
UTF-8
1,080
3.1875
3
[]
no_license
#include <iostream> #include <string> #include <vector> std::string getRow(std::string& currentLine, int rowNumber) { if (rowNumber < 1) { return ""; } for (int i = 1; i != rowNumber; ++i) { if (currentLine.find('\t') != std::string::npos) { currentLine = currentLine.substr(currentLine.find('\t') + 1); } else { return ""; } } if (currentLine.find('\t') != std::string::npos) { return currentLine.substr(0, currentLine.find('\t')); } return currentLine; } int main() { std::string flagLine; std::getline(std::cin, flagLine); if (flagLine == "") { std::string currentLine; while (std::getline(std::cin, currentLine)) { std::cout << currentLine << '\n'; } } else { flagLine = flagLine.substr(flagLine.find(' ') + 1); int rowNumber = stoi(flagLine); std::string currentLine; while (std::getline(std::cin, currentLine)) { std::cout << getRow(currentLine, rowNumber) << '\n'; } } }
true
8f652bd1d5ee71330e53bdef0398c02a1bd5a449
C++
mayanksingh1998/C-Network-Programming
/sheet-2/GoBackN.cpp
UTF-8
3,914
3.03125
3
[]
no_license
//Author: P. Bharat //Roll No: 08114022 //Branch: CSE, 4th year #include <iostream> #include <stdlib.h> #include <time.h> using namespace std; //Global time int globalTime = 0; //the area till which the receiver has acknowedged int receiverAck; // To determine the efficiency of the network float percentageEff; int numberPacketsLost; //The sender window. SWP stands for Sender window pointer. The four //entries are packetNumber, time of generation, time of receipt of acknowledgement, time of timeout int sender[10][4]; int SWPToSend = 0; int SWPToReceive = 0; //Various times for the network int transmitTime; int generationTime; int timeOut; //This will generate packet void generate(int genTime,int packetNo) { if(packetNo<11)cout<<"Packet number "<<packetNo<<" is generated at time = "<<genTime<<endl; //Entering all values into sended window sender[SWPToSend][0] = packetNo; sender[SWPToSend][1] = genTime; sender[SWPToSend][2] = 0; sender[SWPToSend][3] = 0; //Determing if the packet will reach safely int randTemp = rand()%100; if(randTemp<numberPacketsLost) { if(packetNo<11)cout<<"This packet will be lost in transit"<<endl<<endl; //Setting the time out time sender[SWPToSend][3] = genTime+timeOut; } else { if(packetNo<11)cout<<"This packet will reach safely"<<endl<<endl; //Setting the time at which the acknowledgement will be received sender[SWPToSend][2] = genTime+2*transmitTime; } } void goBack() { //Building the senderWindow for(int i = 0; i<10; i++) { for(int j = 0; j<4; j++) { sender[i][j] = 0; } } int packetNumber = 1; while(true) { bool timeOutOcc = false; if(sender[SWPToReceive][2]<=globalTime+generationTime&&sender[SWPToReceive][2]!=0) { //Packet received is acknowledged cout<<"Packet Number "<<sender[SWPToReceive][0]<<" has been acknowledged at time = "<<sender[SWPToReceive][2]<<endl; if(sender[SWPToReceive][0]==10)break; SWPToReceive = (SWPToReceive+1)%10; } else if(sender[SWPToReceive][3]<=globalTime+generationTime&&sender[SWPToReceive][3]!=0) { //Some earlier Packet has caused timeout cout<<"!!!Time out in packet number "<<sender[SWPToReceive][0]<<" has occured at time = "<<sender[SWPToReceive][3]<<"!!!"<<endl; SWPToSend = SWPToReceive; packetNumber = sender[SWPToReceive][0]; timeOutOcc = true; } globalTime = globalTime+generationTime; if(timeOutOcc) { globalTime = sender[SWPToReceive][3]; } if(sender[SWPToReceive][0]==0) { generate(globalTime, packetNumber); packetNumber++; SWPToSend = (SWPToSend+1)%10; } else if(sender[(SWPToSend-1+10)%10][0]<11) { generate(globalTime, packetNumber); packetNumber++; SWPToSend = (SWPToSend+1)%10; } } } int main() { cout<<"Enter the times for different network parameters:"<<endl; cout<<"Generation Time (ms):";cin>>generationTime; cout<<"Transmission Time (ms):";cin>>transmitTime; cout<<"TimeOut Time (ms):";cin>>timeOut;cout<<endl; cout<<"Enter The percentage efficiency:";cin>>percentageEff; numberPacketsLost = 100 -(int)percentageEff; cout<<endl<<"Running Go back N"<<endl; for(int i = 0; i<30;i++)cout<<"_"; cout<<endl<<endl; goBack(); system("pause"); return 0; }
true
6db7877052c6446d66cbae0afe72f44f3db3eb19
C++
EggyJames/Leetcode
/46.cpp
UTF-8
453
2.65625
3
[]
no_license
class Solution { public: int jump(vector<int>& nums) { if(nums.size() == 0) return 0; int cnt = 0; int start = 0,reach = 0; while(reach<nums.size() - 1){ int farest = 0; for(int i = start;i<=reach;i++){ farest = max(farest,i+nums[i]); } start = reach+1; reach = farest; cnt++; } return cnt; } };
true
57fd11c7fcd0cf26ccd8abe91f3ad77448ab3eb7
C++
ManhND27/C-Cplus
/final-example-NguyenDucManh/chap13/PRG2/main.cpp
UTF-8
1,678
3.828125
4
[]
no_license
#include <iostream> using namespace std; class Complex { private: float real; float ima; public: Complex(): real(0), ima(0){ } void input() { cout << "Enter real: "; cin >> real; cout << "Enter imaginary: "; cin >> ima; } //overload Complex operator + (Complex c2) { Complex temp; temp.real = real + c2.real; temp.ima = ima + c2.ima; return temp; } Complex operator - (Complex c2) { Complex temp; temp.real = real - c2.real; temp.ima = ima - c2.ima; return temp; } Complex operator * (Complex c2) { Complex temp; temp.real = real * c2.real - ima * c2.ima; temp.ima = real * c2.ima + c2.real * ima; return temp; } Complex operator / (Complex c2) { Complex temp; temp.real = (real * c2.real + ima * c2.ima) / (c2.real * c2.real + c2.ima * c2.ima); temp.ima = (-real * c2.ima + c2.real * ima) / (c2.real * c2.real + c2.ima * c2.ima); return temp; } void output() { if(ima < 0) { cout << "Output Complex number: "<< real << ima << "i" << "\n"; } else { cout << "Output Complex number: " << real << "+" << ima << "i" << "\n"; } } }; int main() { Complex c1, c2, sum, sub, multi, division; cout << "Enter first complex number \n"; c1.input(); cout << "Enter second complex number \n"; c2.input(); sum = c1 + c2; sum.output(); sub = c1 - c2; sub.output(); multi = c1 * c2; multi.output(); division = c1 / c2; division.output(); return 0; }
true
987c8df8651bc46d49f973d3d24186a03a38e998
C++
chrisdepas/6Shots-Game
/6Shots-V2/CAnimatedSprite.h
UTF-8
2,641
2.71875
3
[ "CC0-1.0" ]
permissive
#ifndef __CANIMATEDSPRITE_H__ #define __CANIMATEDSPRITE_H__ /* Handler for Darkfunction exported sprites http://darkfunction.com/editor/documentation */ #include "CGame.h" class CAnimatedSprite { /* Time for each frame in an animation */ const float ANIMATION_FRAME_TIME = 0.02f; class CSpriteImg { public: std::string m_sSpriteName; sf::Vector2i m_vPosition; sf::Vector2i m_vSize; }; class CAnimSprite { public: CSpriteImg* m_pSpriteImg; std::string m_sSpriteName; sf::Vector2i m_vPosition; int m_iZ; CAnimSprite() { m_pSpriteImg = 0; } }; /* Single frame in animation */ class CAnimationFrame { public: std::vector<CAnimSprite> m_Images; int m_iDelayMult; float m_fStartTime = 0.0f; // Start time in animation timescale float m_fEndTime = 0.0f; // End time in animation timescale void Draw(CGame* pGame, sf::Vector2i pos, bool bMirror, sf::Texture* spriteSheet, std::vector<CSpriteImg>& sprites); void Draw(CGame* pGame, sf::Shader& shader, sf::Vector2i pos, bool bMirror, sf::Texture* spriteSheet, std::vector<CSpriteImg>& sprites); }; class CAnimation { public: std::vector<CAnimationFrame> m_Frames; std::string m_sAnimationName; bool m_bStaticAnimation; // If true, 'animation' is just a single image float m_fTime; // Current animation time, range [0, maxTime] float m_fMaxTime; // Total time of each frame added up, end time for animation int m_iCurFrame = 0; // Current frame index void Draw(CGame* pGame, sf::Vector2i pos, sf::Texture* spriteSheet, bool bMirror, std::vector<CSpriteImg>& sprites); void Draw(CGame* pGame, sf::Shader& shader, sf::Vector2i pos, sf::Texture* spriteSheet, bool bMirror, std::vector<CSpriteImg>& sprites); void Update(float fDelta, bool bMirror); // Converts loaded frame data into playable animation void Finalise(float fFrameTime); }; std::vector<CAnimation> m_Animations; std::vector<CSpriteImg> m_Sprites; sf::Texture m_SpriteSheet; CAnimation* m_pCurAnimation = NULL; bool m_bValid = false; /* Init sprite from XML */ bool ParseAnimationListXML(rapidxml::xml_document<>& xml); bool ParseSubspriteXML(rapidxml::xml_document<>& xml); public: /* Load an exported sprite file, e.g. Supply 'player' to load player.png, player.anim, */ bool Load(char* szSpriteName); /* Set current sprite animation */ void SetAnimation(char* szAnimation); /* Update animation frame */ void Update(float fTime, bool bMirror); /* Draw animated sprite */ void Draw(CGame* pGame, sf::Vector2i pos, bool bMirror); }; #endif
true
04c5b8191ff0238ccc5f5292351be3f74a4d324f
C++
Anushkakesharwani/Cpp-program
/class.cpp
UTF-8
431
3.703125
4
[]
no_license
#include<iostream> #include<conio.h> using namespace std; class employee{ public: int id; string name; float salary; void insert(int i,string n,float s) { id=i; name=n; salary=s; } void display() { cout<<id<<" "<<name<<" "<<salary<<endl; } }; int main() { employee e1,e2; e1.insert(201,"aaa",5000); e2.insert(202,"bbb",6000); e1.display(); e2.display(); return 0; }
true
5c57dee7eed8bd920d4cecf47e89f80794ff548f
C++
socc-io/algostudy
/SCPC/smilu/2018/4.cpp
UTF-8
4,075
3.265625
3
[]
no_license
/* You should use the statndard input/output in order to receive a score properly. Do not use file input and output Please be very careful. */ #include <iostream> #include <vector> #include <list> #include <map> using namespace std; int gcd(int a, int b) { if(b == 0) return a; int tmp = a % b; return gcd(b, tmp); } struct Point { int x; int y; bool operator==(const Point& p) { return x == p.x && y == p.y; } Point operator+(const Point& p) { Point res; res.x = x + p.x; res.y = y + p.y; return res; } Point operator-(const Point& p) { Point res; res.x = x - p.x; res.y = y - p.y; return res; } bool operator<(const Point& p) const { if(x < p.x) return 1; if(x > p.x) return 0; if(y < p.y) return 1; return 0; } }; struct Line { Point from; Point to; int parallel(Point a, Point b) { return (to.y - from.y) * (b.x - a.x) == (b.y - a.y) * (to.x - from.x); } }; int Answer; int N; Point points[50000]; Line lines[50000]; map<Point, int> check_mem; int is_mid(int a, int b, int c) { if(a < b) { if(a <= c && c <= b) return 1; else return 0; } else { if(b <= c && c <= a) return 1; return 0; } } int line_collision(Point a, Point b, Point c, Point d) { int dy_ab = a.y - b.y; int dx_ab = a.x - b.x; int dy_cd = c.y - d.y; int dx_cd = c.x - d.x; int B_x = (a.x * dy_ab * dx_cd) - (c.x * dy_cd * dx_ab) + (c.y - a.y) * dx_ab * dx_cd; int A_x = dy_ab - dy_cd; int B_y = B_x * dy_ab - a.x * dy_ab * A_x + a.y * A_x * dx_ab; int A_y = dx_ab * A_x; if(is_mid(c.x*A_x, d.x*A_x, B_x) && is_mid(c.y*A_y, d.y*A_y, B_y)) return 1; return 0; } int check(Point offset) { for(int i=0; i<N; ++i) { // index of start point int col_line_num = 0; for(int j=0; j<N; ++j) { // index of line Point po = points[i] + offset; int res = line_collision(points[i], po, lines[j].from, lines[j].to); if(!(lines[j].parallel(points[i], po))) { col_line_num++; } } if(col_line_num != 2 && col_line_num != 4) { return 0; } } return 1; } int do_task() { cin >> N; for(int i=0; i<N; ++i) { cin >> points[i].x >> points[i].y; } for(int i=0; i<N-1; ++i) { lines[i].from = points[i]; lines[i].to = points[i+1]; } lines[N-1].from = points[N-1]; lines[N-1].to = points[0]; check_mem.clear(); for(int i=0; i<N; ++i) { for(int j=i+2; j<N; ++j) { if(i == 0 && j == N-1) continue; Point offset = points[j] - points[i]; if(offset.x == 0) offset.y = 1; if(offset.y == 0) offset.x = 1; if(offset.x < 0) { offset.x *= -1; offset.y *= -1; } int g = gcd(offset.x, offset.y); offset.x /= g; offset.y /= g; if(check_mem.find(offset) == check_mem.end()) { check_mem[offset] = 1; if(check(offset)) return 1; } } } return 0; } int main(int argc, char** argv) { int T, test_case; /* The freopen function below opens input.txt file in read only mode, and afterward, the program will read from input.txt file instead of standard(keyboard) input. To test your program, you may save input data in input.txt file, and use freopen function to read from the file when using cin function. You may remove the comment symbols(//) in the below statement and use it. Use #include<cstdio> or #include <stdio.h> to use the function in your program. But before submission, you must remove the freopen function or rewrite comment symbols(//). */ freopen("4_input.txt", "r", stdin); cin >> T; for(test_case = 0; test_case < T; test_case++) { Answer = do_task(); ///////////////////////////////////////////////////////////////////////////////////////////// /* Implement your algorithm here. The answer to the case will be stored in variable Answer. */ ///////////////////////////////////////////////////////////////////////////////////////////// // Print the answer to standard output(screen). cout << "Case #" << test_case+1 << endl; if(Answer) { cout << "YES" << endl; } else { cout << "NO" << endl; } } return 0;//Your program should return 0 on normal termination. }
true
8df723bc8fbde46d438029e4dad90f1afd98d2f0
C++
murfreesboro/cppints
/util/constants/constant.cpp
UTF-8
1,755
3.15625
3
[ "MIT" ]
permissive
// // This simple program is used to generate the constants // for the cppints program // all of constants are defined as macro // fenglai liu // #include<cstdlib> #include<cstdio> #include<string> #include<cmath> #include "boost/lexical_cast.hpp" using boost::lexical_cast; using namespace std; int main() { cout << "/*******************************************************" << endl; cout << " *THIS FILE PROVIDES CONSTANTS FOR THE CPPINTS PROGRAM *" << endl; cout << " *ALL CONSTANTS HAVE 18 DECIMALS ACCURACY *" << endl; cout << " *******************************************************/" << endl; cout << endl << endl << endl; // generate the number of 2m+1 cout << "/*******************************************************" << endl; cout << " * CONSTANTS 1/(2M+1) M FROM 0 TO 200 *" << endl; cout << " *******************************************************/" << endl; string mainpart = "ONEOVER"; for(int i=0; i<=200; i++) { long double r = i; long double result = 1.0E0/(2.0E0*r+1.0E0); string n = lexical_cast<string>(2*i+1); string name = mainpart + n; printf("#define %-20s %-20.18Lf\n", name.c_str(), result); } cout << endl << endl << endl; // generate other constants cout << "/*******************************************************" << endl; cout << " * OTHER CONSTANTS *" << endl; cout << " *******************************************************/" << endl; long double c = 1.0; long double pi = 4.0*atan(c); printf("#ifndef PI\n"); printf("#define %-20s %-20.18Lf\n", "PI", pi); printf("#endif\n"); long double result = 2.0E0/(sqrt(pi)); printf("#define %-20s %-20.18Lf\n", "TWOOVERSQRTPI", result); return 0; }
true
b48ec1104dd3348c0a5025c84af28f7bf343c22b
C++
siskinc/util-cpp
/src/sockets/SocketException.hpp
UTF-8
516
2.640625
3
[]
no_license
// // Created by siskinc on 18-3-28. // #ifndef NET_SOCKETEXCEPTION_HPP #define NET_SOCKETEXCEPTION_HPP #include <exception> #include <string> #include <cstring> #include <cerrno> class SocketException : public std::exception { public: SocketException(int error) : exception() { error_str_ = strerror(errno); } const char *what() const noexcept override { return error_str_.c_str(); } private: std::string error_str_; }; #endif //NET_SOCKETEXCEPTION_HPP
true
d27d14ee5320a4f8f238e8d26b288639b188a5a3
C++
NotMichaelChen/index_update
/block_matching/src/Structures/translationtable.cpp
UTF-8
2,500
2.65625
3
[]
no_license
#include "translationtable.h" #include <sstream> #include <sys/socket.h> #include <sys/time.h> #ifdef _WIN32 #include <Winsock2.h> #endif /* _WIN32 */ using namespace std; string transToString(Translation& t); Translation stringToTrans(const string& s); TranslationTable::TranslationTable() { #ifdef _WIN32 //! Windows netword DLL init WORD version = MAKEWORD(2, 2); WSADATA data; if (WSAStartup(version, &data) != 0) { std::cerr << "WSAStartup() failure" << std::endl; return -1; } #endif /* _WIN32 */ //cpp_redis::active_logger = std::unique_ptr<cpp_redis::logger>(new cpp_redis::logger); client.connect("127.0.0.1", 6379); client.select(1); } int TranslationTable::apply(int docID, size_t fragID, int position) { vector<cpp_redis::reply> response; client.lrange(to_string(docID), 0, -1, [&response](cpp_redis::reply& reply) { if(reply.ok()) response = reply.as_array(); }); client.sync_commit(); if(response.size() == 0) return -1; int finalposition = position; for(size_t i = fragID; i < response.size(); ++i) { finalposition = applyTranslation(finalposition, stringToTrans(response[i].as_string())); //return if position becomes invalidated //cannot keep running; position might accidentally become revalidated if(finalposition < 0) return finalposition; } return finalposition; } void TranslationTable::insert(vector<Translation>& trans, int docID) { vector<string> val; for(Translation& t : trans) val.push_back(transToString(t)); client.rpush(to_string(docID), val); client.commit(); } void TranslationTable::erase(int docID) { client.del( {to_string(docID)} ); client.commit(); } void TranslationTable::dump() { //Ensure database is saved client.save(); client.sync_commit(); } void TranslationTable::clear() { client.flushdb(); client.sync_commit(); } string transToString(Translation& t) { stringstream result; result << t.loc << "-" << t.oldlen << "-" << t.newlen; return result.str(); } Translation stringToTrans(const string& s) { int nums[3]; stringstream stringtrans(s); string token; int i = 0; while(getline(stringtrans, token, '-')) { nums[i] = stoi(token); ++i; } return Translation(nums[0], nums[1], nums[2]); }
true
3e25f391fbf9e4d8dde5d3ae1c0fc6f199e4ab3e
C++
mrdrivingduck/leet-code
/1423.MaximumPointsYouCanObtainFromCards.cpp
UTF-8
3,446
3.71875
4
[ "MIT" ]
permissive
/** * @author Mr Dk. * @version 2021/02/06 */ /* There are several cards arranged in a row, and each card has an associated number of points The points are given in the integer array cardPoints. In one step, you can take one card from the beginning or from the end of the row. You have to take exactly k cards. Your score is the sum of the points of the cards you have taken. Given the integer array cardPoints and the integer k, return the maximum score you can obtain.  Example 1: Input: cardPoints = [1,2,3,4,5,6,1], k = 3 Output: 12 Explanation: After the first step, your score will always be 1. However, choosing the rightmost card first will maximize your total score. The optimal strategy is to take the three cards on the right, giving a final score of 1 + 6 + 5 = 12. Example 2: Input: cardPoints = [2,2,2], k = 2 Output: 4 Explanation: Regardless of which two cards you take, your score will always be 4. Example 3: Input: cardPoints = [9,7,7,9,7,7,9], k = 7 Output: 55 Explanation: You have to take all the cards. Your score is the sum of points of all cards. Example 4: Input: cardPoints = [1,1000,1], k = 1 Output: 1 Explanation: You cannot take the card in the middle. Your best score is 1. Example 5: Input: cardPoints = [1,79,80,1,1,1,200,1], k = 3 Output: 202 Constraints: 1 <= cardPoints.length <= 10^5 1 <= cardPoints[i] <= 10^4 1 <= k <= cardPoints.length 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/maximum-points-you-can-obtain-from-cards 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ /* 反向思维。由于操作结束后,剩下的卡牌一定是连续的 n - k 张,因此只需要 找出 n - k 张连续卡牌中,点数之和最小的区间即可。所有卡牌的点数之和 减去点数之和最小的连续区间,剩下的就是拿走的最大点数之和。 */ #include <cassert> #include <iostream> #include <vector> #include <algorithm> using std::cout; using std::endl; using std::vector; class Solution { public: int maxScore(vector<int>& cardPoints, int k) { int window_len = cardPoints.size() - k; int min = INT32_MAX; int window_sum = 0; int sum = 0; int i = 0; while (i < (int) cardPoints.size()) { window_sum += cardPoints[i]; sum += cardPoints[i]; i++; if (i >= window_len && window_len > 0) { min = std::min(min, window_sum); window_sum -= cardPoints[i - window_len]; } } if (min == INT32_MAX) { min = 0; } return sum - min; } }; int main() { Solution s; vector<int> cards; cards = { 1,2,3,4,5,6,1 }; assert(12 == s.maxScore(cards, 3)); cards = { 2,2,2 }; assert(4 == s.maxScore(cards, 2)); cards = { 9,7,7,9,7,7,9 }; assert(55 == s.maxScore(cards, 7)); cards = { 1,1000,1 }; assert(1 == s.maxScore(cards, 1)); cards = { 1,79,80,1,1,1,200,1 }; assert(202 == s.maxScore(cards, 3)); return 0; }
true
fb9ec312ced56c1827c1ed608f8eced99cadc5b8
C++
rys1689434805/example
/slaver_container.cpp
UTF-8
2,215
2.71875
3
[]
no_license
#include <cstdio> #include <stdlib.h> #include <hiredis/hiredis.h> #include <hiredis/async.h> #include <hiredis/adapters/libevent.h> //这个libevent中没有定义stdlib会用到stdlib中的东西,所以要放到后面 #include <event.h> #include <string> using namespace std; void my_callback(struct redisAsyncContext *pc, void *reply, void *private_data) { string port; string room_no; redisReply *my_reply = (redisReply *)reply; if ("message" != string(my_reply->element[0]->str)) { return; //前面会有第一条订阅成功的消息 这样判断会扔掉第一条没用的消息 } else { //reply �а���IP������� string orig_content(my_reply->element[2]->str); int pos = orig_content.find(':'); string IP = orig_content.substr(0, pos); string my_ip(getenv("MY_IP")); //这个MY_IP是需要在运行程序是指定当前主机的IP if (IP != my_ip) //把截取出来的端口判断是不是自己的,是的话就 { return; } room_no = orig_content.substr(pos + 1, orig_content.size() - pos - 1); } //ִ这个room_no就是要传到容器中的脚本,当容器退出后也一起把他的存在redis中对应的信息删除 string cmd = "./create_room.sh room_no" + room_no; auto pf = popen(cmd.c_str(), "r"); //popen执行脚本后可以使用fread到返回的结果 if (pf != NULL) { char buff[1024]; fread(buff, 1, sizeof(buff), pf); port.append(buff); pclose(pf); } auto spc = redisConnect("192.168.64.148", 6379); //ͬ连接的是主服务器的redis,这里智能同步订阅 if (NULL != spc) { freeReplyObject( redisCommand(spc, "publish server_port %s", port.c_str())); //同步发布执行脚本创建容器返回的端口号 redisFree(spc); //主服务器的CGI中堵塞等待这一条端口的发布 } } int main() { auto base = event_base_new(); auto pc = redisAsyncConnect("192.168.64.148", 6379); //异步连接主服器上面的redis,因为还要发布执行脚本创建容器成功返回端口号 redisLibeventAttach(pc, base); redisAsyncCommand(pc, my_callback, NULL, "subscribe create_room"); //异步订阅creat_room通道 event_base_dispatch(base); return 0; }
true
cbfef5adea005694ca2c71fc1ae6d93c16a49e3b
C++
codeStack82/Cpp
/week 6/hunt_W6_HW_Zabrina.cpp
UTF-8
7,330
3.140625
3
[ "MIT" ]
permissive
/* * Tyler Hunt * Advanved C++ * OCCC Fall 2017 * Due: 10/15/17 * Details: Simple Sorts Homework * Reference Material https://solarianprogrammer.com/2012/10/14/cpp-11-timing-code-performance/ * Reference Material: http://www.geeksforgeeks.org/quick-qSort/ * Reference Material: http://homepage.divms.uiowa.edu/~hzhang/c31/notes/ch08.pdf */ #include <iostream> #include <typeinfo> #include <iomanip> #include <cstdlib> #include <string> #include <fstream> #include <ctime> #include <chrono> using namespace std; #pragma comment(linker, "/STACK: 800000000"); //Prototypes - helper function - all work good void print_Top_and_Btm_Array(int * a, int size, int n); void copyArray(int * source, int * destination, int size); void reverseArray(int * theArray, int size); void zeroCounters(long long int &comparisonsCounter, long long int &exchangeCounter); int * getInputData(string fileName); void quickSort(int a[], int left, int right); int medianOf3(int a[], int left, int right); int partitionIt(int a[], int left, int right, int pivot); void manualSort(int a[], int left, int right); void swap(int a[], int b, int c); //Global variables long long int exchangeCounter; long long int comparisonsCounter; int main(int argc, char * argv[]){ cout << "\n~~~~~~~~~~~~ Advanced Sorts Homework - Advanced C++ Week 6 ~~~~~~~~~~~~~~" << endl; string fileName1; int numToPrint = 10; //Used to adjust how many numbers are pinted in print func int size = 10; //Using this so to input change the size if there are errors // Get file names from cmd line if(argc >= 2){ fileName1 = argv[1]; cout << "\nFile names " << fileName1 << endl; // Get file names from user input }else{ cout << "\nPlease, enter a file name. (ex: list1.txt) " << endl; cout << "File name: "; cin >> fileName1; cout << "\nFile names " << fileName1 << endl; } // Read in data files (3 files) int * list1 = getInputData(fileName1); // Random sorted file // Print the header of all input files - used for testing - can comment out cout << "\nInput array #1~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<< endl; print_Top_and_Btm_Array(list1, size, numToPrint); // Quick sort - random size = 10; int * quickSortArray = new int[size]; copyArray(list1 , quickSortArray, size); auto s = chrono::steady_clock::now(); // timer code quickSort(quickSortArray, 0, size); // Quick Sort auto e = chrono::steady_clock::now(); // timer code auto d = e - s; // timer code cout << "\nQuick Sort - Random Array ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<< endl; cout << "Array Size: " << size << endl; print_Top_and_Btm_Array(quickSortArray, size, numToPrint); cout << "\n\t# of comparisons:\t" << comparisonsCounter << endl; cout << "\t# of exchanges:\t\t" << exchangeCounter << endl; cout << "\tElapsed time:\t\t"<< chrono::duration <double, milli> (d).count()/ 1000 << " sec" << endl; zeroCounters(comparisonsCounter, exchangeCounter); return EXIT_SUCCESS; } //http://people.cs.ubc.ca/~harrison/Java/QSortAlgorithm.java.html void quickSort(int a[], int left, int right){ int size = right - left + 1; if (size >= 10000){ //manualSort(a, left, right); }else { int median = medianOf3(a, left, right); int partition = partitionIt(a, left, right, median); cout << "median " << median << " partition: " << partition << endl; quickSort(a, left, partition - 1); quickSort(a, partition + 1, right); } } int medianOf3(int a[], int left, int right) { int center = (left + right) / 2; if (a[left] > a[center]){ comparisonsCounter++; swap(a, left, center); } if (a[left] > a[right]){ comparisonsCounter++; swap(a, left, right); } if (a[center] > a[right]){ comparisonsCounter++; swap(a, center, right); } comparisonsCounter++; swap(a, center, right - 1); return a[right - 1]; } int partitionIt(int a[], int left, int right, int pivot) { int i = (left - 1); for (int j = left; j <= right - 1; j++){ comparisonsCounter++; if (a[j] <= pivot){ i++; swap(a, left, right); } } swap(a, left + 1, right); return (i + 1); } void manualSort(int a[], int left, int right) { cout << "In Manual Sort" << endl; int size = right - left + 1; if (size <= 1){ comparisonsCounter++; return; } if (size == 2) { comparisonsCounter++; if (a[left] > a[right]){ comparisonsCounter++; swap(a, left, right); } } else { if (a[left] > a[right - 1]){ comparisonsCounter++; swap(a,left,right - 1); } if (a[left] > a[right]){ comparisonsCounter++; swap(a,left, right - 1); } if (a[right - 1] > a[right]){ comparisonsCounter++; swap(a,right-1, right); } } } void swap(int a[], int b, int c) { cout << "In Swap" << endl; int temp = a[b]; a[b] = a[c]; a[c] = temp; } //Helper functions void copyArray(int * source, int * destination, int size){ for(int i = 0; i < size; ++i){ destination[i]= source[i]; } } void reverseArray(int * theArray, int size){ for (int i = 0; i < (size / 2); i++) { int temporary = theArray[i]; theArray[i] = theArray[(size - 1) - i]; theArray[(size - 1) - i] = temporary; } } void zeroCounters(long long int &comparisonsCounter, long long int &exchangeCounter){ comparisonsCounter = 0; exchangeCounter= 0; } int * getInputData(string fileName){ // Open file stream ifstream fin; fin.open(fileName); // Check if file is open if(!fin){ cout <<"Error Opening File, Sorry!" << endl; return 0; } // Get file size from first line int theArraySize; fin >> theArraySize; // Create new array with the size of the first int in the file int * theArray = new int[theArraySize]; // Get the rest of the file for(int i = 0; i < theArraySize; ++i){ fin >> theArray[i]; } return theArray; } void print_Top_and_Btm_Array(int * a, int size, int n){ if ( size <= n ){ for(int i = 0; i < size; ++i){ if ( i%10 == 0 ){ cout << endl; } cout << setw(7) << a[i]; } } else{ //print first 100 for(int i = 0; i < n/2; ++i){ if ( i%10 == 0 ){ cout << endl; } cout << setw(7) << a[i]; } //print last 100 cout << endl; cout <<"\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<< endl; for(int i = size - (n/2); i < size; ++i){ if ( i%10 == 0 ){ cout << endl; } cout << setw(7) << a[i]; } } cout << endl; }
true
330a0a3732bf8690c586e7fd306451a062c483b3
C++
Anubha-Singh/Competetive-coding
/Project Euler/euler12.cpp
UTF-8
629
2.515625
3
[]
no_license
#include<bits/stdc++.h> using namespace std ; long long tau(long long num) { long long n = num; long long i = 2; long long p = 1; if (num == 1) return 1; while (i * i <= n) { long long c = 1; while (n % i == 0) { n/= i; c++; } i++; p*= c; } if (n == num | n > 1) p*= 1 + 1; return p; } long long solution(long long x) {long long n = 1; long long d = 1; while (tau(d) <= x) { n++; d+= n; } return d; } int main(){ cout<<solution(500); return 0; }
true
089f966b1dd76b77a051d41c4a01669e465cb55e
C++
5fe6eb50c7aa19f9/OJ
/uva/382.cpp
UTF-8
601
2.578125
3
[]
no_license
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; int main(){ long long n,i,j,ans; printf("PERFECTION OUTPUT\n"); while(scanf("%lld",&n)&&n){ ans=n>1?1:0; for(i=2;i*i<=n;i++){ if(n%i==0){ ans+=i; if(i*i!=n)ans+=n/i; } } printf("%5lld ",n); if(ans>n){ printf("ABUNDANT\n"); }else if(ans<n){ printf("DEFICIENT\n"); }else{ printf("PERFECT\n"); } } printf("END OF OUTPUT\n"); }
true
b5976bd6c7380cfd94b09a3922d1143228e27c9f
C++
Yessengerey/Game-Dev
/NomNomSweets Game Engine/NomNomSweets Game Engine/TextureManager.h
UTF-8
966
3.0625
3
[]
no_license
#pragma once #include <SFML\Graphics.hpp> #include <map> #include <string> #include <iostream> #include "Singleton.h" //Pre define the texture path to all texture files #define TEX_PATH "Resources\\Textures\\" using std::map; using std::string; using std::cout; /* A class that is responsible for managing the texture resources for the game */ class TextureManager : public Singleton<TextureManager>{ public: friend class Singleton<TextureManager>; //Checks if the given texture already exists or not bool existTexture(const string &file_name); //Retrieves a texture from the map based on the provided file name as the key sf::Texture* retrieveTexture(const string &file_name); //Loads the texture into the map bool loadTexture(const string &file_name); protected: //Constructor TextureManager(); //Destructor ~TextureManager(); //Map of file name as string keys and textures as the mapped values map<string, sf::Texture*> all_textures; };
true
aba831a9f545e66e927e3e98b1ffb272bf4541b8
C++
dddddtest/CPP_TECHNOLOGY
/D.HW4/H/H.cpp
UTF-8
2,075
3.015625
3
[]
no_license
//Fadeev Sergey. 2019 //Задача H. СУ-ДО-КУ //http://neerc.ifmo.ru/teaching/cpp/year2018/sem2/hw/hw4.pdf #include <iostream> long arr4Ch[9]; long arr[9][9]; using namespace std; bool in() { for (int i = 0 ; i < 9; ++i) { for (int k = 0; k < 9; ++k) { cin >> arr[i][k]; if (arr[i][k] > 9 || arr[i][k] < 1) { arr[i][k] = 1; return false; } } } return true; } void clean() { for (int i = 0; i < 9; ++i) { arr4Ch[i] = -1; } } bool check() { long tempS = 0; for (int i = 1; i < 9; ++i) { tempS += arr4Ch[i]; } if (tempS == 0) { return true; } else { return false; } } bool checkG() { for (int i = 0; i < 9; ++i) { clean(); for (int k = 0; k < 9; ++k) { arr4Ch[arr[i][k] - 1] = 0; } if (!check()) { return false; } } return true; } bool checkV() { for (int i = 0; i < 9; ++i) { clean(); for (int k = 0; k < 9; ++k) { arr4Ch[arr[k][i] - 1] = 0; } if (!check()) { return false; } } return true; } bool checkK() { for(int i = 0; i < 9; i += 3) { for(int k = 0; k < 9; k += 3) { clean(); for(int ii = 0; ii < 3; ++ii) { for(int kk = 0; kk < 3; ++kk) { arr4Ch[arr[i + ii][k + kk] - 1] = 0; } } if (!check()) { return false; } } } return true; } int main() { if(!in()) { cout << "No"; return 0; } if(!checkG()) { cout << "No"; return 0; } if(!checkV()) { cout << "No"; return 0; } if(!checkK()) { cout << "No"; return 0; } cout << "Yes"; return 0; }
true
b86d7a32523484af6c8ef4b5b49c9de869ffcc44
C++
vgasparyan1995/InstantChat
/src/Generic/ChatMessage.h
UTF-8
725
2.6875
3
[]
no_license
#pragma once #include <cstdlib> #include <string> #include "Serializers.h" namespace Generic { class ChatMessage { public: static const int s_headerSize = sizeof(size_t); public: ChatMessage(); size_t getLength() const; std::string getSender() const; std::string getText() const; const Byte* getRawData() const; Byte* getRawData(); void setSender(const std::string& sender); void setText(const std::string& text); void encode(); void decode(); void decodeHeader(); void decodeBody(); private: size_t m_length; std::string m_sender; std::string m_text; ByteArray m_rawData; }; } // namespace Generic
true
ea387f360845eb5f84574fd49ef2d92eaa7f2bb5
C++
PikoAll/ASD-Strutture
/Linked List/src/Rating.cpp
UTF-8
654
3
3
[]
no_license
/* * Rating.cpp * * Created on: 16 ott 2020 * Author: peppi */ #include "Rating.h" #include <string> #include <iostream> using namespace std; Rating::Rating(string nome,string prodotto, int v) { // TODO Auto-generated constructor stub setNome(nome); setProdotto(prodotto); setRating(v); } void Rating::setNome(string s){ utente=s; } void Rating::setProdotto(string s){ prodotto=s; } void Rating::setRating(int x){ rating=x; } string Rating::getNome(){ return utente; } string Rating::getProdotto(){ return prodotto; } int Rating::getRating(){ return rating; } Rating::~Rating() { // TODO Auto-generated destructor stub }
true
830159213c21b0e554621cf39a7218d6d83fc1bc
C++
yaroslav-tarasov/3dcgtutorials
/04_PopBuffer/osgPop/LevelOfDetailGeometry.h
UTF-8
2,078
2.546875
3
[ "MIT" ]
permissive
#pragma once #include <vector> #include <string> #include <osg/Geode> #include <osg/Geometry> namespace osg { struct PopCullCallback; class OSG_EXPORT LevelOfDetailGeometry : public osg::Geometry { public: friend struct PopCullCallback; LevelOfDetailGeometry(); LevelOfDetailGeometry(const LevelOfDetailGeometry& rhs, const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); virtual osg::Object* cloneType() const { return new LevelOfDetailGeometry(); } virtual osg::Object* clone(const osg::CopyOp& copyop) const { return new LevelOfDetailGeometry(*this,copyop); } virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast<const LevelOfDetailGeometry*>(obj)!=NULL; } virtual const char* libraryName() const { return "osg"; } virtual const char* className() const { return "LevelOfDetailGeometry"; } inline void setMinBounds(float min) { _min = min; updateUniforms(); } inline float getMinBounds() const { return _min; } inline void setMaxBounds(float max) { _max = max; updateUniforms(); } inline float getMaxBounds() const { return _max; } inline void setNumberOfProtectedVertices(int numProtectedVertices) { _numProtectedVertices = numProtectedVertices; updateUniforms(); } inline int getNumberOfProtectedVertices() const { return _numProtectedVertices; } inline void setMaxViewSpaceError(float maxViewSpaceError) { _maxViewSpaceError = std::abs(maxViewSpaceError); } inline float getMaxViewSpaceError() const { return _maxViewSpaceError; } void reconnectUniforms(); static std::string getVertexShaderUniformDefintion(); static std::string getVertexShaderFunctionDefinition(); protected: void setLod(float lod); void updateUniforms(); virtual ~LevelOfDetailGeometry() {} GLint _lastLod; float _min; float _max; int _numProtectedVertices; osg::ref_ptr<osg::Uniform> _lodUniform; osg::ref_ptr<osg::Uniform> _minBoundsUniform; osg::ref_ptr<osg::Uniform> _maxBoundsUniform; osg::ref_ptr<osg::Uniform> _numProtectedVerticesUniform; float _maxViewSpaceError; }; } // namespace osg
true
5628d5292e2424e5fabf1e42b5da671561d5144f
C++
blizmax/AntiradianceCuts
/Framework/OGLResources/COGLUniformBuffer.cpp
UTF-8
2,090
2.75
3
[]
no_license
#include "COGLUniformBuffer.h" #include <assert.h> uint COGLUniformBuffer::static_GlobalBindingPoint = 0; COGLUniformBuffer::COGLUniformBuffer(uint size, void* data, GLenum usage, std::string const& debugName) : COGLResource(COGL_UNIFORMBUFFER, debugName), m_Size(0) { m_Size = size; m_GlobalBindingPoint = GetUniqueGlobalBindingPoint(); glGenBuffers(1, &m_Resource); CheckGLError("COGLUniformBuffer", "Init() 1"); COGLBindLock lock(this, COGL_UNIFORM_BUFFER_SLOT); CheckGLError("COGLUniformBuffer", "Init() 2"); glBufferData(GL_UNIFORM_BUFFER, m_Size, data, GL_DYNAMIC_DRAW); glBindBufferRange(GL_UNIFORM_BUFFER, m_GlobalBindingPoint, m_Resource, 0, m_Size); CheckGLError("COGLUniformBuffer", "Init() 3"); } COGLUniformBuffer::~COGLUniformBuffer() { glDeleteBuffers(1, &m_Resource); } void COGLUniformBuffer::UpdateData(void* data) { CheckNotBound("COGLUniformBuffer::UpdateData()"); COGLBindLock lock(this, COGL_UNIFORM_BUFFER_SLOT); CheckGLError("COGLUniformBuffer", "UpdateData() 1"); glBufferData(GL_UNIFORM_BUFFER, m_Size, data, GL_DYNAMIC_DRAW); CheckGLError("COGLUniformBuffer", "UpdateData() 2"); } void COGLUniformBuffer::GetData(void* data, size_t size) { CheckNotBound("COGLUniformBuffer::GetData()"); COGLBindLock lock(this, COGL_UNIFORM_BUFFER_SLOT); CheckGLError("COGLUniformBuffer", "GetData() 1"); void* ptr = glMapBuffer(GL_UNIFORM_BUFFER, GL_READ_ONLY); memcpy(data, ptr, size); glUnmapBuffer(GL_UNIFORM_BUFFER); CheckGLError("COGLUniformBuffer", "GetData() 2"); } uint COGLUniformBuffer::GetGlobalBindingPoint() { return m_GlobalBindingPoint; } void COGLUniformBuffer::Bind(COGLBindSlot slot) { COGLResource::Bind(slot); assert(m_Slot == COGL_UNIFORM_BUFFER_SLOT); glBindBuffer(GetGLSlot(m_Slot), m_Resource); } void COGLUniformBuffer::Unbind() { COGLResource::Unbind(); assert(m_Slot == COGL_UNIFORM_BUFFER_SLOT); glBindBuffer(GetGLSlot(m_Slot), 0); } uint COGLUniformBuffer::GetUniqueGlobalBindingPoint() { uint uniqueBP = static_GlobalBindingPoint; static_GlobalBindingPoint++; return uniqueBP; }
true
7aa2fa93fb1c6cf25d573ee54e0cbdfe49d2b60a
C++
tlouwers/STM32F4-DISCOVERY
/drivers/drivers/Watchdog/Watchdog.hpp
UTF-8
2,558
2.71875
3
[]
no_license
/** * \file Watchdog.hpp * * \licence "THE BEER-WARE LICENSE" (Revision 42): * <terry.louwers@fourtress.nl> wrote this file. As long as you retain * this notice you can do whatever you want with this stuff. If we * meet some day, and you think this stuff is worth it, you can buy me * a beer in return. * Terry Louwers * \class Watchdog * * \brief Watchdog (IWDG) peripheral driver class. * * \note The IWDG depends on the LSI clock to be available and running. * * \note https://github.com/tlouwers/STM32F4-DISCOVERY/tree/develop/Drivers/drivers/Watchdog * * \author T. Louwers <terry.louwers@fourtress.nl> * \version 1.0 * \date 04-2022 */ #ifndef WATCHDOG_HPP_ #define WATCHDOG_HPP_ /************************************************************************/ /* Includes */ /************************************************************************/ #include <cstdint> #include "interfaces/IInitable.hpp" #include "interfaces/IWatchdog.hpp" #include "stm32f4xx_hal.h" /************************************************************************/ /* Class declaration */ /************************************************************************/ class Watchdog final : public IWatchdog, public IConfigInitable { public: /** * \enum Timeout * \brief Available timeout values. */ enum class Timeout : uint8_t { _5_MS, _10_MS, _25_MS, _50_MS, _125_MS, _250_MS, _500_MS, _1_S, _2_S, _4_S, _8_S, _16_S, _32_S }; /** * \struct Config * \brief Configuration struct for Watchdog. */ struct Config : public IConfig { /** * \brief Constructor of the Watchdog configuration struct. * \param timeout Timeout value. */ Config(Timeout timeout = Timeout::_4_S) : mTimeout(timeout) { } Timeout mTimeout; ///< Timeout value. }; bool Init(const IConfig& config) override; bool IsInit() const override; bool Sleep() override; void Refresh() const override; private: IWDG_HandleTypeDef mHandle = {}; bool mInitialized; bool IsLSIClockEnabled() const; uint32_t CalculatePrescaler(Timeout timeout); uint32_t CalculateReload(Timeout timeout); }; #endif // WATCHDOG_HPP_
true
a5182593e45c4f577824057b3a0d973efbc828d8
C++
roznet/autoalign
/src/align_ast.h
UTF-8
939
3.21875
3
[ "MIT" ]
permissive
#include <iostream> #include <memory> #include "align_value.hpp" using namespace std; class AST { public: AST() {}; ~AST() {}; virtual int value()=0; }; class AST_op : public AST { public: typedef enum { tPlus, tMinus, tMultiply, tDivide } OperationType; private: OperationType m_type; shared_ptr<AST> m_left; shared_ptr<AST> m_right; public: AST_op(OperationType op, AST*left, AST*right) : m_left(left), m_right(right), m_type(op) {}; ~AST_op() { } int value() { switch(m_type) { case tPlus: return m_left->value() + m_right->value(); case tMinus: return m_left->value() - m_right->value(); case tMultiply: return m_left->value() * m_right->value(); case tDivide: return m_left->value() / m_right->value(); } } }; class AST_value : public AST { private: ValueType m_value; public: AST_value(int v) : m_value(v) {}; ~AST_value() {}; int value() { return m_value.intValue(); }; };
true
68e83bfa695d23287a351d4105af2673931f7647
C++
conlen/CPP
/src/vektor/test.cpp
UTF-8
4,027
3.46875
3
[ "BSD-2-Clause" ]
permissive
#include <iostream> #include <new> #include "vektor.hpp" using namespace std; void test1() { vektor<float> x; std::vector<float> v = {1.0, 2.0, 3.0}; cout << "test1" << endl; x = v; cout << "x = " << x << endl; cout << "end test1" << endl; return; } void test2() { std::vector<double> v = {1.0, 2.0, 3.0}; vektor<double> x(v); cout << "test2" << endl; cout << "x = " << x << endl; cout << "end test2" << endl; return; } void test3() { std::vector<char> v = { 'a', 'b', 'c'}; vektor<char> x(v), y; cout << "test3" << endl; y = x; cout << "x = " << x << endl; cout << "y = " << y << endl; cout << "end test3" << endl; return; } void test4() { vektor<char> x, y; cout << "test4" << endl; y = x; cout << "x = " << x << endl; cout << "y = " << y << endl; cout << "end test4" << endl; return; } void test5() { std::vector<double> v = {1.0, 2.0, 3.0}; vektor<double> x(v), y(v), z; cout << "test5" << endl; z = x + y; cout << "z = " << z << endl; cout << "end test5" << endl; } void test6() { std::vector<double> v1 = {1.0, 2.3, 4.0}; std::vector<double> v2 = {2.3, 4.5}; vektor<double> x(v1), y(v2), z; cout << "test6" << endl; try { z = x + y; } catch(int e) { cout << "caught " << e << endl; } cout << "z = " << z << endl; cout << "end test6" << endl; } void test7() { std::vector<double> v1 = {1.0, 2.0, 3.0}; std::vector<double> v2 = {4.0, 5.0, 6.0}; vektor<double> x(v1), y(v2), z; cout << "test7" << endl; z = x * y; cout << "z = " << z << endl; cout << "end test7" << endl; } void test8() { std::vector<double> v1 = {1.0, 2.0, 3.0}; double a = 10; vektor<double> x(v1), z; cout << "test8" << endl; z = a * x; // z = *(a, x); z = a.*(x) cout << "x = " << x << endl; cout << "z = " << z << endl; z = x * a; cout << "x = " << x << endl; cout << "z = " << z << endl; cout << "end test8" << endl; } void test9() { std::vector<double> v1 = {1.0, 2.3, 4.0}; std::vector<double> v2 = {1.0, 2.0, 3.0}; vektor<double> x(v1), y(v2), z; cout << "test9" << endl; z = x - y; cout << "z = " << z << endl; cout << "end test9" << endl; } void test10() { std::vector<double> v1 = {1.0, 2.0, 3.0}; vektor<double> x(v1); cout << "test10" << endl; cout << "x.dimension() = " << x.dimension() << endl; cout << "x.isValid() = " << x.isValid() << endl; cout << "end test10" << endl; } void test11() { std:;vector<float> v1 = {1.2, 3.4, 5.6}; vektor<float> x(v1); vektor<int> y; cout << "test11" << endl; y = x; cout << "y = " << y << endl; cout << "end test11" << endl; } void test12() { std::vector<float> v1 = {1.2, 3.4, 5.6}; vektor<float> x(v1); cout << "test12" << endl; for(auto i : x) { cout << i << endl; } cout << "end test12" << endl; } void test13() { std::vector<float> v1 = {1.2, 3.4, 5.6}; vektor<float> x(v1); cout << "test13" << endl; auto i = x.begin(); cout << "i[1] = " << i[1] << endl; cout << "end test13" << endl; } void test14() { std::vector<float> v1 = {1.2, 3.4, 5.6}; vektor<float> x(v1); cout << "test14" << endl; auto i = x.begin(); i += 2; cout << "i = " << *i << endl; cout << "end test14" << endl; } void test15() { std::vector<float> v1 = {1.0, 2.0, 3.0}, v2 = {1.0}; vektor<float> x(v1), y(v2), z; cout << "test15" << endl; try { z = x+y; } catch(int e) { cout << "exception " << e << " caught" << endl; } return; } void test16() { vector<float> bar = {1.0, 2.0}; vektor<float> *foo; cout << "test16()" << endl; try { foo = new vektor<float>[1024*1024*1024]; } catch(std::bad_alloc& ba) { std::cerr << "bad_alloc caught: " << ba.what() << std::endl; } for(auto i = 0; i < 100; i++ ) { foo[i] = bar; } cout << foo[99] << endl; delete[] foo; return; } int main(int argc, char *argv[]) { int rc; cout << "main start" << endl; test1(); test2(); test3(); test4(); test5(); test6(); test7(); test8(); test9(); test10(); test11(); test12(); test13(); test14(); test15(); test16(); return(0); }
true
ceea4c2d848d29a5c95ff2586bc22ecb80191c66
C++
trishnakalita660/Interview
/InterviewQtns/Graphs/Birpartite/B_DFS.cpp
UTF-8
813
3.1875
3
[]
no_license
// Expected Time Complexity: O(V) // Expected Space Complexity: O(V) class Solution { public: bool bipartite(int color[],vector<vector<int>> graph,int node){ if(color[node]==-1) color[node]=1; for(auto x: graph[node]){ if(color[x]==-1){ color[x] = 1-color[node]; if(!bipartite(color, graph,x )) return false; } else if(color[x]== color[node]) return false; } return true; } bool isBipartite(vector<vector<int>>& graph) { int color[graph.size()]; int n = graph.size(); memset(color, -1, sizeof(color)); for(int i=0;i<n;i++){ if(color[i]==-1){ if(!bipartite(color, graph,i)) return false; }} return true; } };
true
424e1da65f30e316809f69616930e4a3ac571188
C++
Siwencjusz/SI
/kuba.cpp
WINDOWS-1250
3,670
2.828125
3
[]
no_license
#include <iostream> #include <fstream> #include <cstdio> #include <vector> #include <math.h> using namespace std; double **G; int xcel = 20; int ycel = 20; class kwadrat; std::vector < kwadrat > otwarta; std::vector < kwadrat > zamknieta; class kwadrat { public :int x; public :int y; public :int pozycjaRodzica; public :double koszt; public :double euklides; public :double fx; public :void eukalidesLicz() { euklides = sqrt(pow((double)(x - xcel),2) + pow((double)(y - ycel),2)); } public :void kosztLicz() { koszt = zamknieta[pozycjaRodzica].koszt+1; } public :void fxLicz() { fx = koszt + euklides; } }; kwadrat start; int najmniejszeFx (){ if(otwarta.size()==1){ return 0; } kwadrat tmpMin = otwarta[0]; int pozycja=0; for(int i=1;i<otwarta.size();i++) { if(tmpMin.fx>otwarta[i].fx) { tmpMin=otwarta[i]; pozycja=i; } } return pozycja; } void sprawdzObiekt (kwadrat jedynka){ int tempx=jedynka.x; int tempy=jedynka.y; double tempfx=jedynka.fx; bool flaga = false; int max_i=(int)otwarta.size(); for(int i=0;i<max_i;i++){ if(otwarta[i].x==tempx && otwarta[i].y==tempy) { flaga = true; if(otwarta[i].fx>tempfx) { otwarta[i]=jedynka; } break; } } if(flaga==false) { otwarta.push_back(jedynka); } } bool czyCel(){ if(zamknieta[zamknieta.size()-1].x == xcel && zamknieta[zamknieta.size()-1].y == ycel) { return true; } return false; } void powrot (){ kwadrat temp=zamknieta[zamknieta.size()-1]; while(temp.x != start.x ||temp.y != start.y){ G[temp.x][temp.y] = 1; temp=zamknieta[temp.pozycjaRodzica]; } G[start.x][start.y]=4; G[xcel][ycel]=7; } int main (void) { cout<<"Wczytywanie danych z pliku\n"; string nazwap="grid.txt"; int wym2=20; int wym1=20; //teraz deklarujemy dynamicznie tablice do, ktrej wczytamyu nasz plik, int rows = wym2+1; G = new double*[rows]; while(rows--) G[rows] = new double[wym1+1]; cout<<"\n\nNacisnij ENTER aby wczytac tablice o nazwie "<< nazwap; getchar(); std::ifstream plik(nazwap.c_str()); for ( unsigned int i=1;i<wym2+1;i++) { for ( unsigned int j=1;j<wym1+1;j++) { plik >> G[i][j]; } } plik.close(); cout<<"\nWypisujemy na ekran\n\n"; for(int i=1;i<wym2+1;i++) { for(int j=1;j<wym1+1;j++) { cout<<" "<<G[i][j]; }cout<<"\n"; } start.x = 1; start.y = 1; start.pozycjaRodzica = -1; start.koszt = 0; zamknieta.push_back(start); bool prawda = true; while(prawda) { int tmpx = zamknieta[zamknieta.size() - 1].x; int tmpy = zamknieta[zamknieta.size() - 1].y; int tabx [4] = {0, -1, 0, 1}; int taby [4]= {-1, 0, 1, 0}; int pozRodz=zamknieta.size()-1; for (int i = 0;i<4;i++){ if (tmpx+tabx[i]>=1 && tmpx+tabx[i]<=20 && tmpy+taby[i]>=1 && tmpy+taby[i]<=20 && G[tmpx+tabx[i]][tmpy+taby[i]]!=5){ kwadrat jeden; jeden.x=tmpx+tabx[i]; jeden.y=tmpy+taby[i]; jeden.pozycjaRodzica = pozRodz; jeden.eukalidesLicz(); jeden.kosztLicz(); jeden.fxLicz(); sprawdzObiekt(jeden); } } if(otwarta.size()==0){ cout<<"Nie mona osign celu"<<endl; prawda = false; } if(otwarta.size()>0){ int pozycja=najmniejszeFx(); zamknieta.push_back(otwarta[pozycja]); otwarta.erase (otwarta.begin()+pozycja); } if(czyCel()) { cout<<"Cel zosta osigniety"<<endl; prawda =false; powrot(); } } for(int i=1;i<wym2+1;i++) { for(int j=1;j<wym1+1;j++) { cout<<" "<<G[i][j]; }cout<<"\n"; } //na koniec czycimy pami po naszej tablicy for(int i=0;i<wym2+1;i++) {delete[] G[i];}//czyscimy wiersze delete[] G;//zwalniamy tablice wskaznikow do wierszy cout<<"\n\nNacisnij ENTER aby zakonczyc"; getchar(); return 0; }
true
3a66f0713330daa7f84d07efe68cf199cbe8135e
C++
EthanWelsh/Network-Routing-Simulator
/routelab-f12/table.h
UTF-8
1,178
2.921875
3
[]
no_license
#ifndef _table #define _table #include <iostream> #include <map> #include <deque> #include "link.h" using namespace std; struct TopoLink { TopoLink() : cost(-1), age(0) { } TopoLink(const TopoLink &rhs) { *this = rhs; } TopoLink &operator=(const TopoLink &rhs) { this->cost = rhs.cost; this->age = rhs.age; return *this; } int cost; int age; }; // Students should write this class class Table { private: public: map<int, map< int, TopoLink > > topo; #if defined(DISTANCEVECTOR) map<int, map< int, double > > distance_vectors; map<int, double> cost; map<int, int> hop; void updateTable(unsigned int dest, unsigned int next, double latency); #endif Table(); Table(const Table &); Table(deque<Link *> *links); Table &operator=(const Table &); ostream &Print(ostream &os) const; #if defined(LINKSTATE) map<int, map< int, double > > topology; map<int, double> neighbor_table; map<int, int> hop; map<int, double> cost; #endif }; inline ostream &operator<<(ostream &os, const Table &t) { return t.Print(os); } #endif
true
1ada79799cbb5584fd14a5865ad089447003ad9b
C++
Knabin/TBCppStudy
/Chapter6/Chapter6_05/main_chapter65.cpp
UTF-8
1,103
3.578125
4
[]
no_license
#include <iostream> using namespace std; int main() { const int num_rows = 3; const int num_columns = 5; for (int row = 0; row < num_rows; row++) { for (int col = 0; col < num_columns; col++) { cout << '[' << row << ']' << '[' << col << ']' << '\t'; } cout << endl; } cout << endl; int array[num_rows][num_columns] = // row-major <-> column-major { {1,2,3,4,5}, // row 0 {6,7,8,9,10}, // row 1 {11,12,13,14,15} // row 2 }; //array[0][0] = 1; for (int row = 0; row < num_rows; row++) { for (int col = 0; col < num_columns; col++) { cout << array[row][col] << '\t'; } cout << endl; } cout << endl; // 주소 찍어 보면 4씩 차이남 for (int row = 0; row < num_rows; row++) { for (int col = 0; col < num_columns; col++) { cout << (int)&array[row][col] << '\t'; } cout << endl; } // num_rows만 생략 가능! num_columns는 생략 불가능 int array2[][num_columns] = { {1,2}, // 나머지 0으로 채움 {6,7,8,9,10}, {11,12,13,14,15} }; int array3[num_rows][num_columns] = { 0 }; int array4[5][4][3]; return 0; }
true
2a924520ca2483f519a4f8c0b806ba6adeb4e5f3
C++
karitra/cpp-playground
/src/pair.cc
UTF-8
410
3.265625
3
[]
no_license
#include <iostream> #include <map> using namespace std; struct Boo { enum Selector { Key, Value }; }; int main() { map<int,string> m = { {1, "hello"}, {2, "bye-bye"} }; enum Selector { Key, Value }; for(const auto &kv : m) { int k; std::string v; tie(k,v) = kv; cerr << " k: " << std::get<Selector::Key>(kv) << " v: " << std::get<Selector::Value>(kv) << '\n'; } cerr << endl; }
true
b70287fa3513b22ea2c4dbfb17f18bd6ed4bea06
C++
MaxHsuProgram/CPP
/GreenJudge/a/a035.cpp
UTF-8
202
2.609375
3
[]
no_license
#include <iostream> #include<math.h> using namespace std; int main() { double a=0 , b = 0 , x = 0 , y = 0; cin>>a>>b; x = log10(a); y = b * x; cout << (int)floor(y) + 1; }
true
dd9f7494482d297c7275541b30dedeeda46fa48b
C++
sorelmitra/learn
/c++/threads-sockets/src/av-client/main-client.cpp
UTF-8
1,242
2.609375
3
[]
no_license
// // main.cpp // av-client // // Created by Sorel Mitra on 15/11/17. // Copyright © 2017 Sorel Mitra. All rights reserved. // #include <iostream> #include <unistd.h> #include <cstdlib> #include <string> #include <iostream> #include <cstdio> #include "../common/net/defs.h" #include "AvClient.h" int main(int argc, char * const argv[]) { int c; char *dataDir = NULL; while ((c = getopt(argc, argv, "d:")) != -1) { switch (c) { case 'd': dataDir = optarg; break; case '?': if (optopt == 'd') fprintf(stderr, "Option -%c requires an argument.\n", optopt); else if (isprint(optopt)) fprintf(stderr, "Unknown option `-%c'.\n", optopt); else fprintf(stderr, "Unknown option character `\\x%x'.\n", optopt); return 1; default: abort(); } } for (int i = optind; i < argc; i++) { LOGINFO("Non-option argument " + std::string(argv[i])); } if (optind < argc) { LOGERROR("Trailing arguments!"); return 1; } if (dataDir == NULL) { LOGERROR("Need directory to scan. Use -d argument."); return 1; } std::string dirToScan = std::string(dataDir); LOGINFO("Scanning " + dirToScan + " directory"); AvClient avClient("localhost", net::SERVER_PORT, dirToScan); avClient.run(); return 0; }
true
dbe337ed92adceb4dfb7be9e88f80b222ec9cc10
C++
runzhesheng/li_yurun
/ex06_29/main.cpp
UTF-8
909
3.921875
4
[]
no_license
#include <iostream> #include <iomanip> using namespace std; bool Prime( int ); //声明函数为布尔类型,返回的变量为逻辑变量 int main() { int count=1; cout<< "The prime numbers from 1 to 10000 are:" <<endl; cout<< 2; for (int i=3; i<10000; i=i+2 ) // 只需要判断奇数,偶数没有可能成为素数 { if (Prime(i)) { count=count+1; cout<<setw(6)<<i; if (count%10==0) cout<<endl; //换行,每行十个数字 } } cout << endl; cout<<"There are "<<count<<" prime numbers between 1 and 10000"<<endl; } bool Prime( int n ) { for (int i2=2; i2<=n/2;i2++) // 只需要判断奇数 { if ( n%i2==0 ) return false; //判断是否为素数,不会被除自身的任何整数整除 } return true; // bool类型,返回true o false }
true
f89e702d22c5a9b954008491c83254ea5722e7f5
C++
cvassago/priority_queue
/test_queue.cxx
UTF-8
461
3.03125
3
[]
no_license
#include "priority_queue.hxx" int main(int argc, char **argv) { priority_queue<int> queue; int i; i = 1; std::cout << "ADD:" << std::endl; while(i < argc) { queue.add(atoi(argv[i])); i++; } queue.print(); std::cout << "\nDEL:" << std::endl; while(!queue.empty()) { std::cout << queue.max() << std::endl; queue.del(); //std::cout << "DEL:" << std::endl; //queue.print(); //std::cout << "\n" << std::endl; } return (0); }
true
f07beb4785a46b16f901b35aff09839dbc0ada3e
C++
gewaltig/sli3
/sli_allocator.h
UTF-8
4,255
3.03125
3
[]
no_license
/* * allocator.h * * This file is part of NEST * * Copyright (C) 2004 by * The NEST Initiative * * See the file AUTHORS for details. * * Permission is granted to compile and modify * this file for non-commercial use. * See the file LICENSE for details. * */ #ifndef SLI_ALLOCATOR_H #define SLI_ALLOCATOR_H #include <cassert> #include <cstdlib> #include <string> namespace sli3 { /** * @addtogroup MemoryManagement Memory management * Classes which are involved in Memory management. */ /** * @defgroup PoolAllocator Pool allocator * The pool allocator is specialized for creating many small identical objects. * @ingroup MemoryManagement */ /** * pool is a specialized allocator class for many identical small * objects. It targets a performance close to the optimal performance * which is achieved by allocating all needed objects at once. * @ingroup MemoryManagement * @ingroup PoolAllocator */ class pool { struct link { link *next; }; class chunk { const size_t csize; chunk(const chunk&); //!< not implemented chunk& operator=(const chunk&); //!< not implemented public: chunk *next; char *mem; chunk(size_t s) :csize(s), mem(new char[csize]) {} ~chunk() { delete [] mem; mem=NULL; } size_t size(void) { return csize;} }; size_t initial_block_size; size_t growth_factor; size_t block_size; //!< number of elements per chunk size_t el_size; //!< sizeof an element size_t instantiations; //!< number of instatiated elements size_t total; //!< total number of allocated elements size_t capacity; //!< number of free elements chunk *chunks; //!< linked list of memory chunks link *head; //!< head of free list bool initialized_; //!< True if the pool is initialized. void grow(size_t); //!< make pool larger by n elements void grow(); //!< make pool larger public: /** Create pool for objects of size n. Initial is the inital allocation * block size, i.e. the number of objects per block. * growth is the factor by which the allocations block increases after * each growth. */ pool(); pool(const pool &); pool& operator=(const pool&); pool(size_t n, size_t initial=100, size_t growth=1); void init(size_t n, size_t initial=100, size_t growth=1); ~pool(); //!< deallocate ALL memory /** Increase the pools capacity (free slots) to at least n. Reserve() ensures that the pool has at least n empty slots, i.e., that the pool can store at least n additional elements before more memory needs to be allocated from the operating system. @note The semantics of pool::reserve(n) differ from the semantics of reserve(n) for STL containers: for STL containers, n is the total number of elements after the reserve() call, while for pool it is the number of @b free @b elements. @todo Adapt the semantics of capacity() and reserve() to STL semantics. */ void reserve(size_t n); size_t available(void) const { return total-instantiations;} inline void *alloc(void); //!< allocate one element inline void free(void* p); //!< put element back into the pool size_t size_of(void) const { return el_size;} inline size_t get_el_size() const; inline size_t get_instantiations() const; inline size_t get_total() const; }; inline void * pool::alloc(void) { if(head==0) { grow(block_size); block_size *= growth_factor; } link *p=head; head = head->next; ++instantiations; return p; } inline void pool::free(void *elp) { link *p= static_cast<link *>(elp); p->next= head; head = p; --instantiations; } inline size_t pool::get_el_size() const { return el_size; } inline size_t pool::get_instantiations() const { return instantiations; } inline size_t pool::get_total() const { return total; } } #endif
true
7726ffbc982452703f08cb1619b4607936d65e09
C++
jaredpetersen/ghostlab42reboot
/examples/ex4_scrollingtextadvanced/ex4_scrollingtextadvanced.ino
UTF-8
2,215
3.421875
3
[ "MIT" ]
permissive
#include <GhostLab42Reboot.h> #include <Wire.h> GhostLab42Reboot reboot; void setup() { reboot.begin(); reboot.write(1, "126.2"); reboot.write(2, "-46.9"); } void loop() { // String to be scrolled across the six digit display // Need the extra spaces to make the scrolling smooth String displayText = " . Test 1.2.3.4. ... "; // A NOTE ABOUT SCROLLING: // This more complicated method of scrolling handles periods/decimals, which are // more complicated than other characters. A period/decimal is either considered // part of the previous character or its own character if it is in the first // position of the display (in which case there is technically a "space" in // front of it). // Check out ex3_scrollingtext instead if you are not planning on scrolling a // string with a period/decimal // Commence scrolling for (int i = 0; i < displayText.length(); i++) { // Offset helps manage the number of characters we're sending to the display // offset = number of digits on the display + 1 int offset = 7; // Loop over the first six characters of this iteration for (int j = 0; j < offset; j++) { // If the string has a period, don't count it as a separate character if (displayText.charAt(i+j) == '.') { offset += 1; } } // If the first character in the string is a period/decimal and the // previous character was not a period/decimal, the previous character // was cut off during the scrolling // Just let the period/decimal disappear since we do not want it to // scroll off the display like a regular character. if (displayText.charAt(i) == '.' && displayText.charAt(i - 1) != '.') { // Write the string to the display with the extra offset reboot.write(0, displayText.substring(i + 1, i + offset + 1)); } else { // Write the string to the display with the normal offset reboot.write(0, displayText.substring(i, i + offset)); // Essentially the refresh rate of the display // No need to use the delay in the previous case delay(250); } } // Clear the display and start over reboot.resetDisplay(0); }
true
e6dbc38243c0576fd031fdf9d0e9ec80ff327dff
C++
paulRoux/dataStruct
/previous_datastruct/Hanoi/Hanoi.cpp
UTF-8
617
3.90625
4
[]
no_license
#include <iostream> using namespace std; void move(int n, char x, char y) { cout<<"No."<<n<<": "<<x<<" -> "<<y<<endl; } void hanoi(int n, char a, char b, char c) { if(n == 1) move(1,a,c); else { hanoi(n-1,a,c,b); //可以理解为通过借助c,在b处已经放好n-1个盘 move(n,a,c); //第n号盘从a处移到c hanoi(n-1,b,a,c); //解决b处n-1个盘,最后放到c处 } } int main() { cout<<"The process for Hannoi:"<<endl; int num = 4; //初始化为1 hanoi(num,'A','B','C'); cout<<"The process is finished!"<<endl; return 0; }
true
7381dc9aa1a5b565908361e9434960fd5adb627d
C++
zhuyoujun/cpp
/ch3/exercises/ex3_2_1.cpp
UTF-8
438
3.109375
3
[]
no_license
/*Date :2015/06/25 *Author :zhuyoujun *Email :zhuyoujun0513@163.com *Function:reading the standard input a word at a time. *Link :C++ Primer 5th(english version) @page90, ex3_2. */ #include<iostream> #include<string> using std::cin; using std::cout; using std::endl; using std::string; int main() { string word; while (cin >> word) { cout << word << endl; } return 0; }
true
c3c2eac342b79d4c7cbc9e26c444adb833e72138
C++
semmelknoedel/example
/include/MusicTape.h
UTF-8
1,121
2.796875
3
[]
no_license
/* * File: MusicTape.h * Author: barbara * * Created on August 31, 2016, 11:25 AM */ #ifndef MUSICTAPE_H #define MUSICTAPE_H /*===========================================================================* * INCLUDES C/C++ standard library (and other external libraries) *===========================================================================*/ #include <string> using namespace std; /*===========================================================================* * INCLUDES project headers *===========================================================================*/ /*Enumeration for different available artists.*/ enum artist_t { BOB_DYLAN, //Like a Rolling Stone THE_ROLLING_STONES, //Satisfaction JOHN_LENNON //Imagine }; class MusicTape { public: MusicTape(); virtual ~MusicTape(); /*Abstract functions*/ // TODO: Implement for new artist /*Play song*/ virtual void Play() = 0; /*Rewind tape*/ virtual void Rewind(string rewindSound) = 0; /*Return song title*/ virtual string GetSongTitle() = 0; }; #endif /* MUSICTAPE_H */
true
cc1b606da35ebdc771f866a47036146b185992cf
C++
harshp30/PCLEDLights
/WhiteLightCode/White_light.ino
UTF-8
350
2.515625
3
[]
no_license
#define red 11 #define blue 10 //DigitalPin values for RGB and on-off and mode switch #define green 9 #define on_off_swt 2 #define mode_switch 4 int red_pin = A3; int blue_pin = A4; int green_pin = A5; void setup() { } void loop() { analogWrite(red, 255); analogWrite(blue, 255); analogWrite(green, 255); }
true
8355e760a1cb9c18f88442da84ff0539e836d9dd
C++
Anubhav2907/DSA
/sortingQues/aashish.cpp
UTF-8
529
3.09375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; void colors(int arr[], int n){ int low = 0; int mid = 0; int high = n-1; while(mid<=high){ if(arr[mid]==0){ swap(arr[low],arr[mid]); low++; mid++; } else if(arr[mid]==1){ mid++; } else{ swap(arr[high],arr[mid]); high--; } } } int main(){ int arr[] = {2,0,2,1,1,0}; colors(arr,6); for(auto x:arr){ cout << x << endl; } }
true
1c186dbca9044154103371e57138df450ef9a4e4
C++
rollingshow/test
/task3.cpp
UTF-8
408
2.75
3
[]
no_license
#include <iostream> #include <fstream> using namespace std; int main() { string word, longest; size_t maxlong=0; ifstream words("words.txt"); while (!words.eof()) { words>>word; if (word.length() > maxlong) { maxlong= word.length(); longest = word; } } cout<<longest<<endl; }
true
b84c52549a77b4db82b6a8663fde91ee8adcab33
C++
Zylann/SnowfeetEngine
/modules/render/GLContextSettings.h
UTF-8
1,480
2.71875
3
[]
no_license
#ifndef __HEADER_SNR_GLCONTEXTSETTINGS__ #define __HEADER_SNR_GLCONTEXTSETTINGS__ #include <core/types.h> #include <cmath> #include <sstream> namespace sn { struct GLContextSettings { u32 majorVersion; u32 minorVersion; u32 multiSampleLevel; u32 stencilBits; u32 depthBits; GLContextSettings() : majorVersion(3), minorVersion(3), multiSampleLevel(0), stencilBits(8), depthBits(32) {} inline s32 evaluate(u32 bitsPerPixel_, s32 colorBits_, s32 depthBits_, s32 stencilBits_, s32 multiSampleLevel_) const { return std::abs(static_cast<int>(bitsPerPixel_ - colorBits_)) + std::abs(static_cast<int>(depthBits - depthBits_)) + std::abs(static_cast<int>(stencilBits - stencilBits_)) + std::abs(static_cast<int>(multiSampleLevel - multiSampleLevel_)); } std::string toString() const { std::stringstream ss; ss << "{version=" << majorVersion << "." << minorVersion << ", multiSampleLevel=" << multiSampleLevel << ", stencilBits=" << stencilBits << ", depthBits=" << depthBits << "}"; return ss.str(); } }; inline bool operator!=(const GLContextSettings & lhs, const GLContextSettings & rhs) { return lhs.majorVersion != rhs.majorVersion || lhs.minorVersion != rhs.minorVersion || lhs.multiSampleLevel != rhs.multiSampleLevel || lhs.stencilBits != rhs.stencilBits || lhs.depthBits != rhs.depthBits; } } // namespace sn #endif // __HEADER_SNR_GLCONTEXTSETTINGS__
true
0dfd881b31ddaa9141163c67a94485d5d654b6a3
C++
ke-kontur/eps
/Services/Monitoring/EPSMonitoringService/monitoringsystem/local/services/src/main/native/wmi/wmi/monitoring_utils.h
UTF-8
632
2.78125
3
[]
no_license
/** * Utility classes */ class StringFromJavaReleaser { private: const wchar_t * gotten; jstring initial; JNIEnv *env; public: StringFromJavaReleaser(JNIEnv *env, jstring initial, const wchar_t * gotten) { this->env = env; this->initial = initial; this->gotten = gotten; } ~StringFromJavaReleaser() { if (initial != NULL) env->ReleaseStringChars(initial, (jchar*)gotten); } }; class IUnknownHandlerReleaser { private: IUnknown * iunknoun; public: IUnknownHandlerReleaser(IUnknown * iunknoun) { this->iunknoun = iunknoun; } ~IUnknownHandlerReleaser() { if (iunknoun != NULL) iunknoun->Release(); } };
true
0f1f36ddd13fed0d038b342a0976a4b154f1f8da
C++
vinodkotiya/First-Website-Ever
/source/mycpp/V5NMCPP.CPP
UTF-8
4,186
2.765625
3
[]
no_license
#include<iostream.h> #include<conio.h> #include<string.h> int option(); void title(void); char j; class dir { long int fone,std; double mobile; char nm[10],snm[10],place[20],ct[10]; public: void set(long int , long int ,double,char[],char[],char[],char[]); void show(); void nmchoice(); void snmchoice(); void ctchoice(); void placechoice(); void datacomman(); }; void dir :: set( long int s,long int f,double m,char n[10],char sn[10],char c[10],char p[20]) { std = s; fone = f; mobile = m; strcpy(nm,n); strcpy(snm,sn); strcpy(ct,c); strcpy(place,p); } void dir ::show() { cout<<nm<<" "<<snm<<" "<<place<<" "<<std<<"-"<<fone<<" "<<mobile<<endl; } void dir :: datacomman() { int i,v,r=1,loop; char choice[10],ch; dir s[6]; s[0].set(755,794428, 0,"RAMESH","KOTIYA","BHOPAL","SARVDHARM COL"); s[1].set(731,463057, 0,"MAHENDRA","KADAM","INDORE","INDRAPURI"); s[2].set(755,763809,98272.04449 ,"REWARAM","JATAV","BHOPAL","TTNAGAR"); s[3].set(755,736852, 0 ,"JAI","NEEM","KHAMGAON"," "); s[4].set(755,767173, 0 ,"PAPPU"," ","BHOPAL","TTNAGAR"); s[5].set(731,363153,98272.15774 ,"RAJKUMAR","NEEM","INDORE","AZAD NAGAR"); loop=6; v=option(); title(); if(v==1) { cout<<"\nENTER ONLY NAME \n\t"; cin>>choice; for(i=0;i<loop;i++) { if(strcmpi(choice,s[i].nm)==0) {r=0; s[i].nmchoice();} } if(r!=0) cout<<"\nThe NAME "<<choice<<" You Have Entered Does Not Exist"; } else if(v==2) { cout<<"\nENTER ONLY SURNAME \n\t"; cin>>choice; for(i=0;i<loop;i++) { if(strcmpi(choice,s[i].snm)==0) {r=0; s[i].snmchoice();} } if(r!=0) cout<<"\nThe SURNAME "<<choice<<" You Have Entered Does Not Exist"; } else if(v==3) { cout<<"\nENTER ONLY CITY NAME \n\t"; cin>>choice; for(i=0;i<loop;i++) { if(strcmpi(choice,s[i].ct)==0) {r=0; s[i].ctchoice();} } if(r!=0) cout<<"\nThe CITY NAME "<<choice<<" You Have Entered Does Not Exist"; } else if(v==4) { cout<<"\nENTER ONLY CITY AREA NAME \n\t"; cin>>choice; for(i=0;i<loop;i++) { if(strcmpi(choice,s[i].place)==0) {r=0; s[i].placechoice();} } if(r!=0) cout<<"\nThe CITY AREA NAME "<<choice<<" You Have Entered Does Not Exist"; } else if(v==5) { cout<<"\nENTER ONLY FIRST CHARACTER OF NAME ONLY IN CAPITAL LATTER\n\t"; cin>>ch; for(i=0;i<loop;i++) { if(ch==s[i].nm[0]) {r=0; s[i].nmchoice();} } if(r!=0) cout<<"\nThe CHARACTER "<<ch<<" You Have Entered Does Not Exist OR NOT IN CAPITAL"; } else if(v==6) { for(i=0;i<loop;i++) s[i].nmchoice(); } else cout<<"\nPLEASE ENTER CHOICE No.like 1/2/3/4/5/6 YOU FOOL"; } void dir :: nmchoice() { cout<<nm<<" "<<snm<<" "<<ct<<" "<<place<<" "<<std<<"-"<<fone<<" "<<mobile<<endl; } void dir :: snmchoice() { cout<<snm<<" "<<nm<<" "<<ct<<" "<<place<<" "<<std<<"-"<<fone<<" "<<mobile<<endl; } void dir :: ctchoice() { cout<<ct<<" "<<place<<" "<<nm<<" "<<snm<<" "<<std<<"-"<<fone<<" "<<mobile<<endl; } void dir :: placechoice() { cout<<place<<" "<<ct<<" "<<nm<<" "<<snm<<" "<<std<<"-"<<fone<<" "<<mobile<<endl; } void main(void) { clrscr(); title(); dir d; d.datacomman(); getch(); } int option() { int v; cout<<"\t\nENTER YOUR WAY TO FIND PHONE NO.(1/2/3/4/5/6)\n\n"; cout<<" 1.By Typing Name"<<" \t2.By Typing Surname\n\n" <<" 3.By Typing City"<<" \t4.By Typing Area\n\n" <<" 5.By Typing First Character of Name(ONLY CAPITAL LETTER)\n\n" <<" 6.Want To See Whole Teliphone Directory List\n\n\t"; cin>>v; return (v); } void title (void) { clrscr(); cout<<"********************************************************************************"; cout<<"***************************TELIPHONE DIRECTORY*********************************"; cout<<"********************************************************************************" <<"***************** *****************" <<"************* **************"; cout<<"\t\tCOPYRIGHT 2002 VINOD KOTIYA .ALL RIGHTS UNRESERVED\n"; cout<<"********************************************************************************\n\n"; }
true
1bd9eeca7b9b26d2408afe11b44393934d21ab14
C++
ranxx/Reading
/jianzhioffer/chapter2/7.cpp
UTF-8
3,351
4.03125
4
[]
no_license
#include <iostream> #include <exception> #include <string> /* 输入某二叉树的前序遍历和中序遍历的结果, 请重建该二叉树. 假设输入的前序遍历和中序遍历的结果中都不包含重复的数字. 例如, 输入 前序遍历{1,2,4,7,3,5,6,8}和中序遍历{4,7,2,1,5,3,8,6}, 则 重建如图 2.6 所示的二叉树并输出它的头结点. 二叉树节点的定义如下: struct BinaryTreeNode { int m_nValue; BinaryTreeNode* m_pLeft, m_pRight; }; */ #ifndef PARAMS #define PARAMS int argc, char ** argv #endif #define SIZE(a) (sizeof(a) / sizeof(a[0])) struct BinaryTreeNode { int m_nValue; BinaryTreeNode *m_pLeft, *m_pRight; }; void destroy(BinaryTreeNode *root) { if (!root) { return ; } destroy(root->m_pLeft); destroy(root->m_pRight); std::cout << "delete => " << root->m_nValue << std::endl; delete root; } void preorder(BinaryTreeNode *root) { if (!root) { return ; } std::cout << root->m_nValue << ", "; preorder(root->m_pLeft); preorder(root->m_pRight); } void inorder(BinaryTreeNode *root) { if (!root) { return ; } inorder(root->m_pLeft); std::cout << root->m_nValue << ", "; inorder(root->m_pRight); } BinaryTreeNode* constructCore(int *startPreorder, int *endPreorder, int *startInorder, int *endInorder) { int rootValue = startPreorder[0]; BinaryTreeNode *root = new BinaryTreeNode; root->m_nValue = rootValue; root->m_pLeft = root->m_pRight = NULL; if (startPreorder == endPreorder) { if (startInorder == endInorder && *startInorder == *endInorder) { return root; } std::cout << "Invalid input!"; return NULL; } int *inorderRoot = startInorder; while (inorderRoot <= endInorder && *inorderRoot != rootValue) { ++inorderRoot; } if (inorderRoot == endInorder && *inorderRoot != rootValue) { std::cout << "Invalid input!"; return NULL; } int leftLen = inorderRoot - startInorder; if (leftLen > 0) { root->m_pLeft = constructCore(startPreorder + 1, startPreorder + leftLen, startInorder, inorderRoot -1); } if (endInorder - inorderRoot > 0) { root->m_pRight = constructCore(startPreorder + leftLen + 1, endPreorder, inorderRoot + 1, endInorder); } return root; } BinaryTreeNode* construct(int preorder[], int inorder[], int len) { if (preorder == NULL || inorder == NULL || len <= 0) { return NULL; } return constructCore(preorder, preorder + len - 1, inorder, inorder + len - 1); } int main(PARAMS) { int preorderArray[] = {1, 2, 4, 7, 3, 5, 6 ,8}; int inorderArray[] = {4, 7, 2, 1, 5, 3, 8, 6}; BinaryTreeNode *root = construct(preorderArray, inorderArray , SIZE(preorderArray)); preorder(root); std::cout << std::endl; inorder(root); std::cout << std::endl; destroy(root); int one[] = {1}; root = construct(one, one, 1); preorder(root); std::cout << std::endl; inorder(root); std::cout << std::endl; destroy(root); int *zero; root = construct(zero, zero, 0); preorder(root); std::cout << std::endl; inorder(root); std::cout << std::endl; destroy(root); return 0; }
true
87009dde8ce0776eb077b7f4bc8d5e9eef441ea6
C++
KyungminYu/Algorithm
/BOJ/4355 서로소.cpp
UTF-8
561
2.703125
3
[]
no_license
#include <stdio.h> #include <math.h> int main(){ while(1){ int n; scanf("%d", &n); if(n == 0) break; int pi = 1; int tmp = n; for(int i = 2; i * i <= tmp; i++){ int cnt = 0; if(tmp % i == 0){ while(!(tmp % i)) { tmp /= i; cnt++; } } if(cnt == 0) continue; pi *= (i - 1) * pow(i, cnt - 1); } if(tmp > 1) pi *= (tmp - 1); printf("%d\n", pi); } return 0; }
true
0e7e39450d838d2cb2f3827df0e0b8ed311b4d65
C++
budsan/climbers
/logic/tilemap.cpp
UTF-8
751
2.890625
3
[]
no_license
#include "tilemap.h" #include <math.h> Tilemap::Tilemap(float unitsPerTile) : m_unitsPerTile(unitsPerTile) { } math::vec2i Tilemap::tilePos(math::vec2f pos) { return tilePos(pos.x, pos.y); } math::vec2i Tilemap::tilePos(float x, float y) { return math::vec2i( (int) floor(x/m_unitsPerTile), (int) floor(y/m_unitsPerTile)); } int Tilemap::tilePosX(float x) { return (int) floor(x/m_unitsPerTile); } int Tilemap::tilePosY(float y) { return (int) floor(y/m_unitsPerTile); } float Tilemap::Top(int y) { return float(y+1)*m_unitsPerTile; } float Tilemap::Bottom(int y) { return float(y)*m_unitsPerTile; } float Tilemap::Left(int x) { return float(x)*m_unitsPerTile; } float Tilemap::Right(int x) { return float(x+1)*m_unitsPerTile; }
true
9aaa9283968a0c68152b1b57ab906482f054927e
C++
teng88/i2a
/poj1365.cpp
UTF-8
2,482
2.6875
3
[]
no_license
#include <iostream> #include <string> #include <sstream> #include <cmath> #include "number.h" using namespace std; using namespace i2a; //typedef signed int int32_t; //typedef unsigned int uint32_t; //typedef signed long long int int64_t; //typedef unsigned long long int uint64_t; // MillerRabin: s=5 int poj1365() { string line; while (true) { getline (cin, line); if (line == "0") break; stringstream sline(line); // (2, 32767] int num = 1; int p, e; while (sline >> p >> e) { while (e > 0) { num *= p; --e; } } //cout << num-1 << endl; if (num-1 == 1) { cout << "1 1" << endl; continue; } vector<int64_t> fs = FactorizationPollardRho(num-1); for (int i=0; i<(int)fs.size(); i+=2) { for (int j=i+2; j<(int)fs.size(); j+=2) { if (fs[i] < fs[j]) { std::swap(fs[i], fs[j]); std::swap(fs[i+1], fs[j+1]); } } } for (int i=0; i<(int)fs.size(); ++i) { cout << fs[i]; if (i != fs.size()-1) cout << " "; } cout << endl; } return 0; } int poj1365_() { vector<int> t = PreparePrimeTable2(32768); string line; while (true) { getline (cin, line); if (line == "0") break; stringstream sline(line); // (2, 32767] int num = 1; int p, e; while (sline >> p >> e) { while (e > 0) { num *= p; --e; } } //cout << num-1 << endl; if (num-1 == 1) { cout << "1 1" << endl; continue; } int n = num-1; if (t[n] == 0) printf("%d 1\n", num-1); else { vector<int> fs = Factorization(n,t); printf("%d ", fs[0]); int e = 1; int l = fs[0]; for (int i=1; i<(int)fs.size(); ++i) { if (fs[i] == l) ++e; else { printf("%d %d ", e, fs[i]); l = fs[i]; e = 1; } } printf("%d\n", e); } } return 0; }
true
f6810d822a7157117ee7d2be3eb2b8bf1290c1f8
C++
blacksph3re/voidrunner
/src/Spaceship.cpp
UTF-8
1,502
2.578125
3
[]
no_license
#include <iostream> #include <SFML/Graphics.hpp> #include "../h/Spaceship.hpp" #include "../h/ResourceManager.hpp" #include "../h/ConstantManager.hpp" #include "../h/VectorCalculator.hpp" int Spaceship::init() { setTexture( ResourceManager::get().getTexture( "Spaceship" ) ); setPosition(sf::Vector2f(0, 0) ); setOrigin( getLocalBounds().width / 2.0f , getLocalBounds().height / 2.0f ); setMass( 1 ); setMovement( sf::Vector2f(0, 0) ); setAcceleration( 100 ); setTurnAngle( 10 ); return 0; } void Spaceship::update(float fTime) { setMovement( VectorCalculator::setLength( VectorCalculator::AngleDegToVector( getRotation() ) , VectorCalculator::length( getMovement() ) * std::stof(getConstant("Drag")) ) ); move(getMovement() * fTime); } void Spaceship::turnLeft( float fTime ) { rotate( - getTurnAngle() * fTime ); } void Spaceship::turnRight( float fTime ) { rotate( getTurnAngle() * fTime ); } void Spaceship::accelerateForward( float fTime ) { sf::Vector2f acceleration = VectorCalculator::setLength( VectorCalculator::AngleDegToVector( getRotation() ) , getAcceleration() ); setMovement( getMovement() + acceleration * fTime ); } void Spaceship::accelerateBack( float fTime ) { sf::Vector2f acceleration = VectorCalculator::setLength( VectorCalculator::AngleDegToVector( getRotation() ) , getAcceleration() ); setMovement( getMovement() - acceleration * fTime ); }
true
b1be96ad4c277ebe73f9cffd7fda41100bbf3137
C++
zavla/DeleteOldBackupFiles
/DeleteOldFilesCxx11/initFile.cpp
UTF-8
2,445
2.890625
3
[]
no_license
#pragma once //#pragma warning (disable 4996) #include <vector> #include "row2.h" #include <fstream> #include <iostream> #include "InitFile.h" namespace my { /*! deletes quotes from string*/ bool readInitFile(std::vector<row> & v, std::wstring& Initfilename) { //! //file format is: //"j:\b\" 4days (ubcd_sklad_2010)_[0-9]{4}-[0-9]{2}-[0-9]{2}T.* // std::ifstream ifs{ Initfilename }; if (!ifs.is_open()) //only when file not found { std::wcerr << "was unable to open file: " << '\n' << Initfilename << '\n' // ReSharper disable CppDeprecatedEntity << my::from_utf8_to_ucs2<std::wstring>(strerror(errno)); // ReSharper restore CppDeprecatedEntity return false; } row ff; std::string line1; size_t linenumber = 0; while (std::getline(ifs, line1)) { linenumber++; auto LineReadResult = ff.LoadLine(line1); //actualy loading line into row object if (LineReadResult == LoadLineRetvalue::add) { ff.line_num_in_file_ = linenumber; v.push_back(ff); ff.clear(); } else if (LineReadResult == LoadLineRetvalue::ignore) { } else { std::wcerr << "Error: was unable to read line " << linenumber << '\n'; continue; }; } return true; } /* Gets qouted string with spaces or unqouted string without spaces */ std::pair<std::string, size_t> get1stColumn_qouted_string_or_unqouted_string(const std::string& line1, size_t startpos) { //while (startpos != std::string::npos && (line1[startpos] == ' ' || line1[startpos] == '\t' )) startpos++; startpos = line1.find_first_not_of(" \t", startpos); if (startpos == std::string::npos) return std::make_pair("", std::string::npos); auto pos = line1.find_first_of(" \t", startpos); std::string dir1 = line1.substr(startpos, pos - startpos); /*number of quotes*/ auto qnumber = my::how_many_quotes(dir1); while (pos != std::string::npos && qnumber % 2 == 1) { //string has spaces, for example "c:\program files\" auto start = pos; pos = line1.find_first_of(" \t", start + 1); auto tempstr = line1.substr(start, pos - start); qnumber += my::how_many_quotes(tempstr); dir1 += tempstr; } return std::make_pair(dir1, pos); } /* finds how many quotes are there in the string */ int how_many_quotes(std::string & s) { auto pos = s.find('"'); int res = 0; while (pos != std::string::npos) { res++; pos = s.find('"', pos + 1); } return res; } }
true
604eb93523ea62cac1148010b96ffa5e5f0fea40
C++
alexsr/vup
/src/libraries/vup/Geometry/Mesh.cpp
UTF-8
820
2.65625
3
[]
no_license
// // Alexander Scheid-Rehder // alexanderb@scheid-rehder.de // https://www.alexsr.de // https://github.com/alexsr // #include "Mesh.h" vup::Mesh::Mesh(const Mesh_data& m) { m_count = m.count; m_faces_count = m.faces_count; m_vbos.push_back(std::make_shared<VBO>(m.vertices, 4)); m_vbos.push_back(std::make_shared<VBO>(m.normals, 4)); m_vbos.push_back(std::make_shared<VBO>(m.uv_coords, 2)); m_index_buffer = std::make_shared<Element_buffer>(m.indices); } std::shared_ptr<vup::VBO> vup::Mesh::get_vbo(const unsigned int i) const { return m_vbos.at(i); } std::shared_ptr<vup::Element_buffer> vup::Mesh::get_index_buffer() const { return m_index_buffer; } unsigned int vup::Mesh::get_count() const { return m_count; } unsigned vup::Mesh::get_vbo_count() const { return static_cast<unsigned int>(m_vbos.size()); }
true
d7e79507bf96c83dd96c8adb600984f448651268
C++
jlj147/Data-Structures-and-Algorithms-Programs
/assign3_jlj147/StudentStack.h
UTF-8
904
3.453125
3
[]
no_license
// File Name: StudentStack.h // // Author: Jayce Jones // Date: 09/29/16 // Assignment Number: 3 // CS 3358: Fall 2016 // Instructor: CJ Hwang // // Represents a student record list // Includes a students ID, name, avearge test score, and address // Takes the student list and creates a stack, pops from stack // and displays the list as if it is a stack #include <string> #include "StudentArray.h" using namespace std; class StudentStack { private: StudentArray *studentStack; //The stack array int stackSize; //The stack array size int top; //Index to the top of the stack public: //Constructor StudentStack(int); StudentStack(const StudentStack &); ~StudentStack(); //Stack operations void push(StudentArray); StudentArray pop(); bool isFull() const; bool isEmpty() const; void displayStack(); };
true
1fba772f7e56051b903da7c615bf2b5a085a0879
C++
jmanna6/1440_HW04
/Bingo/Card.h
UTF-8
518
2.609375
3
[]
no_license
// // Created by Jake on 3/2/2017. // #ifndef BINGO_CARD_H #define BINGO_CARD_H #include <ostream> #include <algorithm> #include "Cell.h" class Card { public: Card(int size, int maxNum); ~Card(); void print(std::ostream& out) const; void setPotentialValues(int maxNum); private: // Testing void printPotVal(); private: unsigned int m_size; unsigned int m_maxNum; unsigned int m_cellCount; int* m_potentialValues = nullptr; Cell** m_cells; }; #endif //BINGO_CARD_H
true
0186ff682b9a6753ad3c1a17d2bab0914aa082aa
C++
atiabjobayer/Codes
/OJ/UVa/uva_10018.cpp
UTF-8
786
2.609375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main () { //freopen("test/in.txt", "r", stdin); //freopen("test/out.txt", "w", stdout); long long int t; cin >> t; while(t--){ string num; long long int sum = 0; cin >> num; string num_rev(num.rbegin(), num.rend()); long long int x = stoi(num); sum += x; long long int y = stoi(num_rev); sum += y; long long int i = 0; for(i=1;; i++){ num = to_string(sum); string t(num.rbegin(), num.rend()); num_rev = t; if(num == num_rev) break; y = stoi(num_rev); sum += y; } cout << i << " " << sum << endl; } return 0; }
true
caa8831e6fd5b734a0b02572706d825e1b660479
C++
leewoongi/Algorithm
/BackJoon/17406/dong/배열돌리기.cc
UTF-8
2,609
2.71875
3
[]
no_license
#include<iostream> #include<vector> #include<algorithm> using namespace std; int n, m, k; int arr[51][51]; int tmp_arr[51][51]; int first_xy[2]; int end_xy[2]; int tmp; int tmp_result[51]; int result = 210000000; typedef struct NODE { int r; int c; int s; }node; vector<node> v; vector<int> v2; void reset_arr() { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = tmp_arr[i][j]; } } } void reset_re() { for (int i = 0; i < n; i++) { tmp_result[i] = 0; } } void arr_lotation(int k) { reset_arr(); for (int i = 0; i < k; i++) { first_xy[0] = v[v2[i]].r - v[v2[i]].s - 1; first_xy[1] = v[v2[i]].c - v[v2[i]].s - 1; end_xy[0] = v[v2[i]].r + v[v2[i]].s - 1; end_xy[1] = v[v2[i]].c + v[v2[i]].s - 1; int cnt = (end_xy[0] - first_xy[0]) / 2;//시계방향으로 몇개를 돌리는지 for (int z = 0; z < cnt; z++) { tmp = arr[first_xy[0]][first_xy[1]]; for (int j = first_xy[0]; j <= end_xy[0]; j++) {//왼쪽 끝을 위로 올리기 arr[j][first_xy[1]] = arr[j + 1][first_xy[1]]; } for (int j = first_xy[1]; j <= end_xy[1]; j++) {//아래줄을 왼쪽으로 땡겨오기 arr[end_xy[0]][j] = arr[end_xy[0]][j + 1]; } for (int j = end_xy[0]; j > first_xy[0]; j--) {//오른쪽 끝을 아래로 내리기 arr[j][end_xy[1]] = arr[j - 1][end_xy[1]]; } for (int j = end_xy[1]; j > first_xy[1]; j--) {//윗줄 오른쪽으로 땡기기 arr[first_xy[0]][j] = arr[first_xy[0]][j - 1]; } arr[first_xy[0]][first_xy[1] + 1] = tmp; first_xy[0]++; first_xy[1]++; end_xy[0]--; end_xy[1]--; } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { tmp_result[i] += arr[i][j]; } } sort(tmp_result, tmp_result +n); if (result > tmp_result[0]) { result = tmp_result[0]; } } int main() { cin >> n >> m >> k; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> arr[i][j]; tmp_arr[i][j] = arr[i][j]; } } for (int i = 0; i < k; i++) { int r, c, s; cin >> r >> c >> s; v.push_back({ r,c,s }); v2.push_back(i); } do { arr_lotation(k); reset_re(); } while (next_permutation(v2.begin(), v2.end())); cout << result << '\n'; }
true
23a7d156d05927b07b6c9c33b5f02b89ecc0ed04
C++
Hackables44/TareaProgramadaII
/Texto.cpp
UTF-8
4,959
3.53125
4
[]
no_license
//Texto.cpp Implementación de la clase Texto #include "Texto.h" // Clase Texto #include "Diccionario.h" #include <iostream> #include <string> #include <fstream> using namespace std; // constructor por omisión Texto::Texto(){ // inicialización de las variables de instancia (atributos) diccionarioPtr = 0; // puntero nulo cantidadPalabras = 0; cout << "Se construyo una instancia de Texto por Omision" << endl; /** se usará para simular si alguna palabra está en diccionario */ length=5; /** length del vector */ vPalabras = new string [length]; vPalabras[0] = "hola"; vPalabras[1] = "mundo"; vPalabras[2] = "mundos"; vPalabras[3] = "ola"; vPalabras[4] = "s"; } int Texto::operator[](string palabra){ int encontrado = 0; /** se usará como banderá para saber cuando detener la búsqueda */ int i = 0; /** variable utilizada como índice */ while(!encontrado && i<length && i>=0){ /** mientras no se haya encontrado, que busque la palabra, sin salirse del vector */ if(palabra == vPalabras[i]){ /** si encuentra la palabra en la celda */ encontrado = 1; /** indica que sí está con true (valor diferente de 0) */ } ++i; } return encontrado; } // constructor con parámetro, que recibe puntero del diccionario a utilizar Texto::Texto(Diccionario * diccionarioPtr){ this->diccionarioPtr = diccionarioPtr; // asigno el puntero cantidadPalabras = 0; // aun no se han analizado hashtag // cout << "Se construyo por copia un objeto con puntero " << this->*diccionarioPtr << endl; } // constructor por copia; siempre es bueno tener estos 3 constructores, pero en este caso este no se utilizará Texto::Texto(Texto & otro){ this->diccionarioPtr = otro.diccionarioPtr; this->cantidadPalabras = otro.cantidadPalabras; } Texto::~Texto(){ if(diccionarioPtr){ // si el puntero es 0 (nulo), no entra al if delete diccionarioPtr; // invoca al destructor de la instancia cantidadPalabras = 0; } } /* Palabra & Texto::operator[](int i){ // devuelve la referencia de la palabra i-enésima Palabra * palabraPtr = 0; // inicialización en nulo if( i>=0 && i<cantidadPalabras ){ palabraPtr = ; // asigno la referencia a la palabra } else{ cerr << "Warning: La posicion de palabra ingresada es incorrecta.\nSe devuelve un puntero nulo por omisión." << endl; } return palabraPtr; // devuelve el puntero } */ int Texto::getTamanyo(){ // devuelve la cantidad de palabras que forman al hashtag return cantidadPalabras; } void Texto::splitHashtag(string hashtag/*, ofstream & salida*/){ // divide el hashtag cout << "splitHashtag" << endl; splitHashtagR(hashtag, "", "", 0/*, salida*/, 0); cout << "ya paso el metodo splitHashtagvR" << endl; } void Texto::splitHashtagR(string hashtag, string divisionesH, string fragmentoH, int indice/*, ofstream & salida*/, int iteracion){ string divisiones = ""; if( indice < hashtag.length() ){ divisiones = divisionesH; // almacenará los fragmentos válidos del hashtag string fragmento = fragmentoH; // fragmento que enviará verificar si existe en el diccionario bool existeFragmento = 0; // almacena si el fragmento existe fragmento += hashtag.at(indice); // concatena el conjunto de caracteres por buscar //int n = fragmento.length()+1; //cout << "n: " << n << endl; //cout << "string: " << hashtag << endl; //char letrasFragmento[n]; /* for(int i=0; i<fragmento.length(); ++i){ letrasFragmento[i]= fragmento.at(i); cout << "fragmento[]: " << fragmento.at(i) << endl; cout << "letrasFragmento[]: " << letrasFragmento[i] << endl; } */ /* letrasFragmento[n-1] = '\0'; */ // cout << "Convertir string a char *" << endl; char* cadena; /** almacena el string convertido a puntero a literal */ cadena = (char *)fragmento.c_str(); //char * letra=(char)(fragmento); //cout << "letras: " << letrasFragmento << endl; /* Intento de conversión de string a char * cout << "Convertido: " << cadena << endl; cout << "Convertido: " << (char *)fragmento.c_str() << endl; */ // existeFragmento = (*diccionarioPtr)[cadena]; // almacena si existe el fragmento existeFragmento = (*this)[fragmento]; cout << "\nFragmento: " << fragmento << endl; cout << "Existe o no el fregmento: " << existeFragmento << endl; if(existeFragmento){ divisiones += fragmento; // si es una palabra válida, la agrega a la división divisiones += ", "; fragmento = ""; // limpia la variable para analizar el próximo fragmento } splitHashtagR(hashtag, divisiones, fragmento, ++indice/*, salida*/, ++iteracion); // } else{ if(divisiones!=""){ cout << hashtag << ": " << divisiones << endl; // Guarda en un archivo } } /** que imprima las divisiones según el nivel en el que se va */ cout << "\nIteracion: " << iteracion << endl; cout << "Divisiones: { " << divisiones << " }" << endl; }
true
db4a41a0a29c5e3985261903d72636368d4c7af1
C++
sfofgalaxy/Summary-of-Software-Engineering-Coursework-in-Zhejiang-University
/2大二/面向对象程序设计/课件/unit three courseware and code/unit three courseware and code/unit three code/Private Inheritance/intstack.h
GB18030
327
2.625
3
[]
no_license
class intstack: private intlist{ public: void push(int a) { insert(a); //ͷ } int pop() { return get(); //ȡͷ } void print() // { intlist::print(); } }; /* intstackûκο˽м̳intlistĴ intstack c; c.push(1); c.pop(); */
true
b378a6575217deec09999f3d78c9ce1d02b0c529
C++
idelgado2/DataStructures
/idelgado2Lab8/idelgado2Lab8 2/ArrayListType.h
UTF-8
8,989
3.609375
4
[]
no_license
/******************************************************************** * Name: Isaac Delgado * Course #: COSC2437 * Semester: Spring 2015 *** Code is taken from "Data Structures Using C++", by D.S. Malik*** ********************************************************************/ #ifndef idelgado2Lab8_ArrayListType_h #define idelgado2Lab8_ArrayListType_h #include <iostream> #include <fstream> using namespace std; template<class kind> class ArrayListType{ public: bool isEmpty() const; //Function to determine if array is empty or not //Postcondition: will return true if array // is empty or false if array has atleast one // itme in the array bool isFull() const; //Function to determine if array is full or not //Postcondition: will return true if array // is full or false if array is not full int ListSize() const; //Function to return the size of the array //Postcondition: a number of items int array int MaxSize() const; //Function tp return the Maxsize of the array //Postcondition: a number indicating the maximum size ArrayListType(int size = 70); //Constructor to intialize length, maxsize, and the array //postcondition: An initialized array ArrayListType(const ArrayListType<kind>& otherlist); //Copyconstructor //postcondition: An initialized array ~ArrayListType(); //Destructor //postcondition: deleted memorey for array void print(ofstream & outputfile); //Function to print out infromation //postcondition: contents of arrat to screen const ArrayListType<kind>& operator=(const ArrayListType<kind>& otherlist); //function to overload the "=" operator //postconditon: An initlialized array with the contents of the otherlist void Insert(const kind& item); //function to insert an item into the array //postconditon: The array with a new item in the list int minLocation(int first, int last); //function return the location of the smallest value int array void Swap(int first, int second); //fucntion to swap two values within the array //Postcondition: The array will contain the two passed values // bu they will be swapped inlocation void SelectionSort(); //Function to Sort the array by Selection sort //postconstion: Array will be sorted in acending order void InsertionSort(); //Function to Sort the array by Selection sort //postconstion: Array will be sorted in acending order int Partition(int first, int last); //Function to seperate array into two sublist, with the middle //element being the pivot and seperating all elements smaller //than the middle element to the left of the element and elements //greater than the middle element to the right. //postcondition: The array should be "partitioned" or seperated // into an orgainized manner depeneding on the pivot value void recQuickSort(int first, int last); //Function to recursielly partition the and sort array, //beggingin with finding the elements that are smaller than //the pivot value, followed by partioning the values greater //than the pivot //postondition: arrray will be sorted in asending order void QuickSort(); //Function to QuickSort an array, by partitionin recursivly //postondition: arrray will be sorted in asending order private: kind *list; int length; int maxsize; int loopIterations; int moves; }; template<class kind> bool ArrayListType<kind>::isEmpty() const{ return(length == 0); } template<class kind> bool ArrayListType<kind>::isFull() const{ return(length == maxsize); } template<class kind> int ArrayListType<kind>::ListSize() const{ return length; } template<class kind> int ArrayListType<kind>::MaxSize()const{ return MaxSize; } template<class kind> void ArrayListType<kind>::print(ofstream &outputfile){ outputfile << "Sorted List: " << endl; for (int i = 0; i < length; i++) { //for loop print out every item in array outputfile << list[i] << " "; } outputfile << endl << endl; outputfile << "# of Loop iterations: " << loopIterations << endl; outputfile << "# of moves by sorting: " << moves << endl; } template<class kind> ArrayListType<kind>::ArrayListType(int size){ if (size < 0 || size > 100) { cout << "Invlaid input for size, Size must be postivie and no higher than 100" << endl <<"Setting size to 100 by default.. " << endl; maxsize = 100; //setting maxsize to default } else maxsize = size; list = new kind[maxsize]; //dynamically allocating array length = 0; } template<class kind> ArrayListType<kind>::~ArrayListType(){ delete [] list; } template<class kind> ArrayListType<kind>::ArrayListType(const ArrayListType<kind>& otherlist){ maxsize = otherlist.maxsize; length = otherlist.length; list = new kind[maxsize]; //create a new array for (int i = 0; i < length; i++) {//copying each item from other array to this one list[i] = otherlist.list[i]; } } template<class kind> const ArrayListType<kind>& ArrayListType<kind>::operator=(const ArrayListType<kind>& otherlist){ if(this != otherlist){ maxsize = otherlist.maxsize; length = otherlist.length; list = new kind[maxsize]; //create a new array for (int i = 0; i < length; i++) {//copying each item from other array to this one list[i] = otherlist.list[i]; } } return *this; } template<class kind> void ArrayListType<kind>::Insert(const kind& item){ if (isFull()){ cerr<< "Cannot Enter anymore items, the array is full"; } else{ list[length] = item; length++; } } template<class kind> int ArrayListType<kind>::minLocation(int first, int last){ int minIndex; minIndex = first; for (int location = first + 1; location <= last; location++) { if (list[location] < list[minIndex]) minIndex = location; } return minIndex; } template<class kind> void ArrayListType<kind>::Swap(int first, int second){ kind temp; temp = list[first]; list[first] = list[second]; list[second] = temp; } template<class kind> void ArrayListType<kind>::SelectionSort(){ loopIterations = 0; //initializ loopiteration moves = 0; //initialize move counter int minIndex; for (int location = 0; location < length - 1; location++) { minIndex = minLocation(location, length - 1); Swap(location, minIndex); loopIterations++; //count the number of iterations within the for loop moves++; //count the number of moves commited but this sorting algorithm } } template<class kind> void ArrayListType<kind>::InsertionSort(){ loopIterations = 0; //initializ loopiteration moves = 0; //initialize move counter int location; int temp; for (int firstOutOfOrder = 1; firstOutOfOrder < length; firstOutOfOrder++) { if (list[firstOutOfOrder] < list[firstOutOfOrder - 1]) { temp = list[firstOutOfOrder]; location = firstOutOfOrder; do { list[location] = list[location - 1]; location--; loopIterations++; //count the number of interations within do while loop moves++; //count the number of moves commited but this sorting algorithm } while (location > 0 && list[location - 1] > temp); list[location] = temp; moves++; //count the number of moves commited but this sorting algorithm } loopIterations++; //count the number of iterations within the for loop } } template<class kind> int ArrayListType<kind>::Partition(int first, int last){ kind pivot; int smallIndex; Swap(first, (first + last) / 2); //smoving pivot to the front of array pivot = list[first]; smallIndex = first; for (int i = first + 1; i <= last; i++) { if (list[i] < pivot) { smallIndex++; Swap(smallIndex, i); moves++; } loopIterations++; } Swap(first, smallIndex); return smallIndex; } template<class kind> void ArrayListType<kind>::recQuickSort(int first, int last){ int pivotLocation; if (first < last) { pivotLocation = Partition(first, last); recQuickSort(first, pivotLocation - 1); //Recusrive call to partition values less than pivot recQuickSort(pivotLocation + 1, last); //Recursive call to partition values greater than pivot } } template<class kind> void ArrayListType<kind>::QuickSort(){ loopIterations = 0; moves = 0; recQuickSort(0, length - 1); } #endif
true
4573a76240224d48ab316734bbb1e4a7adea6c7f
C++
haojjang/jjang
/p3_60/main.cpp
UTF-8
2,080
2.78125
3
[]
no_license
// Author: Justin Fung #include "huffman.hpp" int main (int argc, char *argv[]) { Heap min_heap; string input_buffer; char decompress_mode[3] = "-d"; unsigned char c; unsigned int freq_table[256] = {0}; unsigned int total_freq = 0, symbol_cnt = 0; if (argc == 2) { if ( !strcmp(argv[1], decompress_mode) ) { // Begin decompression. // =========================================================================== c = cin.get(); while (c != '\0') c = cin.get(); unsigned int byte1, byte2, byte3, byte4; unsigned int dfreq = 0; for (int i = 0; i < 256; i++) { dfreq = 0; byte1 = 0; byte2 = 0; byte3 = 0; byte4 = 0; byte1 = cin.get(); byte2 = cin.get(); byte2 = byte2 << 8; byte3 = cin.get(); byte3 = byte3 << 16; byte4 = cin.get(); byte4 = byte4 >> 24; dfreq = byte1 + byte2 + byte3 + byte4; freq_table[i] = dfreq; if (freq_table[i] > 0) { symbol_cnt++; total_freq += freq_table[i]; Symbol *node = new Symbol( (unsigned char)i, freq_table[i], true, NULL, NULL ); min_heap.push_symbol(node); } } min_heap.define (total_freq, symbol_cnt, freq_table); min_heap.plant(); min_heap.decode(); // =========================================================================== } } else { // Begin compression. // =========================================================================== while (!cin.eof()) { c = cin.get(); if (cin.eof()) break; freq_table[ (unsigned int)c ]++; } cin.clear(); cin.seekg (std::ios::beg); for (int i = 0; i < 256; i++) { if (freq_table[i] > 0) { symbol_cnt++; total_freq += freq_table[i]; Symbol *node = new Symbol( (unsigned char)i, freq_table[i], true, NULL, NULL ); min_heap.push_symbol(node); } } min_heap.define (total_freq, symbol_cnt, freq_table); min_heap.plant(); min_heap.output(); // =========================================================================== } return 0; } // main
true
a8fca0040d9132962a01a8fe31b0b18136fc26d9
C++
t-kuha/sdsoc
/algorithm_sort/hw.cpp
UTF-8
1,919
2.65625
3
[]
no_license
// // Based on: // I. Skliarova, V. Sklyarov, A. Sudnitson, M. Kruus, // "Integration of High-Level Synthesis to the Courses on Reconfigurable Digital Systems", // Proceedings of the 38th International Conference on Information and Communication Technology, Electronics and Microelectronics // - MIPRO, Opatija, Croatia, May, 2015, pp. 172-177. // #include "hw.h" void ex_sort(int in[N], int out[N]) { ap_uint<M> work_array[N]; #pragma HLS ARRAY_PARTITION variable=work_array cyclic factor=2 dim=0 ap_uint<M> work_array2[N]; #pragma HLS ARRAY_PARTITION variable=work_array2 cyclic factor=2 dim=0 //1. Fill in the work array init_loop: for (unsigned i = 0; i < N; i++) { #pragma HLS PIPELINE work_array[i] = in[i]; } //2. Sort the data proc_loop: for (int n = 0; n < N / 2; n++) { // processing even pairs of registers // [0, 1], [2, 3], [4 ... sort_even: for (unsigned j = 0; j < (N / 2); j++){ #pragma HLS UNROLL if (work_array[2 * j] < work_array[2 * j + 1]) { work_array2[2 * j + 1] = work_array[2 * j]; work_array2[2 * j] = work_array[2 * j + 1]; }else{ work_array2[2 * j] = work_array[2 * j]; work_array2[2 * j + 1] = work_array[2 * j + 1]; } if(N % 2 == 1){ work_array[N - 1] = work_array2[N - 1]; } } // processing odd pairs of registers // 0, [1, 2], [3, 4] ... sort_odd: for (unsigned j = 0; j < (N / 2 - 1); j++){ #pragma HLS UNROLL work_array[0] = work_array2[0]; if (work_array2[2 * j + 1] < work_array2[2 * j + 2]) { work_array[2 * j + 1] = work_array2[2 * j + 2]; work_array[2 * j + 2] = work_array2[2 * j + 1]; }else{ work_array[2 * j + 1] = work_array2[2 * j + 1]; work_array[2 * j + 2] = work_array2[2 * j + 2]; } if(N % 2 == 0){ work_array[N - 1] = work_array2[N - 1]; } } } //3. Write the result write_res_loop: for (unsigned i = 0; i < N; i++) { #pragma HLS PIPELINE out[i] = work_array[i]; } }
true
9ed43dd28f2a7d559e6d81f26e32640d67f6ebae
C++
luohongliang-o/sysmonitor
/SysMonitor/link_manager.cpp
GB18030
5,416
2.546875
3
[]
no_license
#include "load_config.h" #include "link_manager.h" #ifdef WIN32 CLinkManager::CLinkManager() { memset(m_aLinkInfo, 0, sizeof(OPLINK)*MAX_LINK_NUM); m_nFailCount = 0; // ::CoInitialize(NULL); } CLinkManager::~CLinkManager() { // ::CoUninitialize(); Exit(); } BOOL CLinkManager::_Init(LPOPLINK pLinkInfo) { if (!pLinkInfo) return FALSE; pLinkInfo->cur_sel = m_nDefaultSel; TDEL(pLinkInfo->ado_db); pLinkInfo->is_connected = FALSE; pLinkInfo->is_busy = FALSE; pLinkInfo->ado_db= new CADODatabase(); if (!pLinkInfo->ado_db) return FALSE; return TRUE; } // ʼ BOOL CLinkManager::Init() { m_nDbCount = CLoadConfig::CreateInstance()->get_db_count(); m_nDefaultSel = CLoadConfig::CreateInstance()->get_db_default_sel(); if (m_nDefaultSel < 0 || m_nDefaultSel >= m_nDbCount) m_nDefaultSel = 0; memcpy(m_dbConfig, CLoadConfig::CreateInstance()->get_db_config(), sizeof(DBCONFIG)*m_nDbCount); for (DWORD dwLinkIndex = 0; dwLinkIndex < MAX_LINK_NUM; dwLinkIndex++){ _Init(&m_aLinkInfo[dwLinkIndex]); } return TRUE; } // ˳ BOOL CLinkManager::Exit() { for (DWORD dwLinkIndex = 0; dwLinkIndex < MAX_LINK_NUM; dwLinkIndex++) { TDEL(m_aLinkInfo[dwLinkIndex].ado_db); } return TRUE; } LPOPLINK CLinkManager::GetLink(char *lpszErrMsg, int nSize, int dbsel,BOOL bPrimary) { if (dbsel >= MAX_DBCOUNT){ sprintf_s(lpszErrMsg, nSize, "ӵĵ[%d]ݿѳǰݿΧ.", dbsel); return NULL; } if (bPrimary) dbsel = m_nDefaultSel; DWORD dwLinkIndex = 0; DWORD dwFirstFreeIndex = MAX_LINK_NUM; LPOPLINK pLinkInfo = NULL; m_csLink.Lock(); for (dwLinkIndex = 0; dwLinkIndex < MAX_LINK_NUM; dwLinkIndex++){ if (!m_aLinkInfo[dwLinkIndex].is_busy){ if (dwFirstFreeIndex >= MAX_LINK_NUM) dwFirstFreeIndex = dwLinkIndex; if (!bPrimary) break; if (m_aLinkInfo[dwLinkIndex].cur_sel == m_nDefaultSel) break; } } if (dwLinkIndex >= MAX_LINK_NUM){ if (dwFirstFreeIndex >= MAX_LINK_NUM){ if (lpszErrMsg) strncpy(lpszErrMsg, "̨æ,Ժ", nSize); m_csLink.Unlock(); return NULL; }else pLinkInfo = &m_aLinkInfo[dwFirstFreeIndex]; } else pLinkInfo = &m_aLinkInfo[dwLinkIndex]; pLinkInfo->is_busy = TRUE; m_csLink.Unlock(); //Ĭݿ if (bPrimary){ if (pLinkInfo->cur_sel != m_nDefaultSel){ pLinkInfo->ado_db->Close(); pLinkInfo->is_connected = FALSE; } if (!pLinkInfo->is_connected){ if (ConnectDataBase(&m_dbConfig[m_nDefaultSel], pLinkInfo->ado_db)){ pLinkInfo->is_connected = TRUE; pLinkInfo->cur_sel = m_nDefaultSel; if (m_nFailCount > 0){ char szError[256] = { 0 }; sprintf_s(szError, 256, "[%s]-%s ݿɹ", m_dbConfig[m_nDefaultSel].data_source, m_dbConfig[m_nDefaultSel].data_base); InterlockedExchange(&m_nFailCount, 0); } } } } if (pLinkInfo->is_connected){ pLinkInfo->busy_time = (long)time(NULL); return pLinkInfo; } if (bPrimary){ char szError[256] = { 0 }; sprintf_s(szError, 256, "[%s]-%s ݿʧ", m_dbConfig[m_nDefaultSel].data_source, m_dbConfig[m_nDefaultSel].data_base); if (lpszErrMsg) strncpy(lpszErrMsg, "ݿʧ!", nSize); InterlockedIncrement(&m_nFailCount); // δɹ m_csLink.Lock(); pLinkInfo->is_busy = FALSE; m_csLink.Unlock(); return NULL; } if (_Connect2(pLinkInfo, dbsel)){ if (m_nFailCount > 0){ long nSel = pLinkInfo->cur_sel; char szError[256] = { 0 }; sprintf_s(szError, 256, "[%s]-%s ݿɹ", m_dbConfig[nSel].data_source, m_dbConfig[nSel].data_base); InterlockedExchange(&m_nFailCount, 0); } return pLinkInfo; } InterlockedIncrement(&m_nFailCount); // Ӷδɹ m_csLink.Lock(); pLinkInfo->is_busy = FALSE; m_csLink.Unlock(); if (lpszErrMsg) strncpy(lpszErrMsg, "ݿʧ!", nSize); return NULL; } // ͷ void CLinkManager::FreeLink(LPOPLINK pLink) { if (!pLink) return; m_csLink.Lock(); pLink->busy_time = 0; pLink->is_busy = FALSE; m_csLink.Unlock(); } // Ͽ void CLinkManager::DisConnect(LPOPLINK pLink) { if (!pLink) return; pLink->ado_db->Close(); pLink->is_connected = FALSE; m_csLink.Lock(); pLink->busy_time = 0; pLink->is_busy = FALSE; m_csLink.Unlock(); } void CLinkManager::CheckConnect(LPOPLINK pLink) { if (!pLink) return; if (!pLink->ado_db){ pLink->is_connected = FALSE; return; } pLink->ado_db->Close(); pLink->is_connected = FALSE; } BOOL CLinkManager::_Connect2(LPOPLINK pLink, int dbsel,BOOL bFailLog) { if (!pLink) return FALSE; pLink->ado_db->Close(); if (ConnectDataBase(&m_dbConfig[dbsel], pLink->ado_db)){ pLink->is_connected = TRUE; pLink->cur_sel = dbsel; pLink->busy_time = (long)time(NULL); return TRUE; }else{ if (bFailLog){ char szError[256] = { 0 }; sprintf_s(szError, 256, "[%s]-%s ݿʧ", m_dbConfig[dbsel].data_source, m_dbConfig[dbsel].data_base); } } return FALSE; } BOOL CLinkManager::ConnectDataBase(LPDBCONFIG lpdbConfig, CADODatabase* pAdoDb) { if (pAdoDb == NULL) return FALSE; pAdoDb->Close(); CString strConnect; strConnect.Format("Provider=sqloledb;Data Source=%s;Network Library=DBMSSOCN;Initial Catalog=%s;", \ lpdbConfig->data_source, lpdbConfig->data_base); pAdoDb->SetConnectionTimeout(); pAdoDb->Open(strConnect, lpdbConfig->user_name, lpdbConfig->password); return pAdoDb->IsOpen(); } #endif
true
374a2ca252f38523abcb599fcd4bf86faa7b4fea
C++
panjunbing/DataStructure
/Test3-1/Test3-1/BinTree.cpp
GB18030
4,768
3.5
4
[]
no_license
#include "StdAfx.h" #include "BinTree.h" #include <iostream> #include <string> using namespace std; #include <queue> const char RefValue = '#'; template <class T> BinTree<T>::BinTree(void){ root = NULL; } template <class T> BinTree<T>::~BinTree(void){ deleteTree(root); } template <class T> void BinTree<T>::deleteTree(BinTreeNode<T> *&subTree){ while(subTree != NULL){ deleteTree(subTree->leftChild); deleteTree(subTree->rightChild); subTree = NULL; } } //(ǰ) template <class T> void BinTree<T>::creatTree(T str[], BinTreeNode<T> *&subTree, BinTreeNode<T> *parent,int depth = 1){ //ʹǰ static int i = -1; T item; if(str[++i] != 0) item = str[i]; if(item != RefValue){ //RefValueʾս subTree = new BinTreeNode<T>; subTree->data = item; subTree->depth = depth; subTree->parent = parent; creatTree(str,subTree->leftChild,subTree,++depth); //ǰ depth--; //һʱ creatTree(str,subTree->rightChild,subTree,++depth); depth--; } else subTree = NULL; root = subTree; } //(ǰ) template <class T> void BinTree<T>::creatTree(T *str1,T *str2){ int size = strlen(str1); root = creatTree(str1,str2,size); } template <class T> BinTreeNode<T>* BinTree<T>::creatTree(T *str1,T *str2,int n,int depth = 1){ if(n == 0) return NULL; int k = 0; while(str1[0] != str2[k])k++; //ѰҸ BinTreeNode<T> *subTree = new BinTreeNode<T>; subTree->data = str1[0]; subTree->depth = depth; subTree->leftChild = creatTree(str1+1,str2,k,++depth); //0k-1Ԫ depth--; subTree->rightChild = creatTree(str1+k+1,str2+k+1,n-k-1,++depth); //k+1n-1Ԫ depth--; return subTree; } //Ů template <class T> void BinTree<T>::swapTree(BinTreeNode<T> *subTree){ if(subTree != NULL){ BinTreeNode<T> *temp = subTree->leftChild; subTree->leftChild = subTree->rightChild; subTree->rightChild = temp; swapTree(subTree->leftChild); swapTree(subTree->rightChild); } root = subTree; } //Ѱkey template <class T> void BinTree<T>::findKey(BinTreeNode<T> *subTree,T key){ static T firstNodeData = subTree->data; if(subTree != NULL){ if(subTree->data != key){ findKey(subTree->leftChild,key); findKey(subTree->rightChild,key); } else{ while(subTree->data != firstNodeData){ subTree = subTree->parent; cout<<subTree->data<<'-'; } cout<<endl; } } } //ؽ template <class T> int BinTree<T>::getCount(BinTreeNode<T> *subTree){ static int count = 0; if(subTree != NULL){ count++; getCount(subTree->leftChild); getCount(subTree->rightChild); } return count; } // template <class T> void BinTree<T>::print(BinTreeNode<T> *subTree){ queue<BinTreeNode<T>* > mQueue; queue<int> xQueue; //ڴ浱ǰŮ֮xֵ inOrder(subTree); //ȷxλ mQueue.push(subTree); cout<<" "; while(!mQueue.empty()){ BinTreeNode<T> *temp = mQueue.front(); //tempΪǰ㣬subTreeΪһ mQueue.pop(); if(subTree->leftChild != NULL){ xQueue.push(subTree->leftChild->x); } if(subTree->rightChild != NULL){ xQueue.push(subTree->rightChild->x); } static int n = 0; //ߵĽxֵ if(subTree->depth < temp->depth){ //ͷһʱ n = 0; cout<<endl; // cout<<" "; } if(temp->leftChild != NULL){ for(int i = n+1;i <= temp->leftChild->x;i++) //ѸýǸ֮' ' cout<<' '; for(int i = temp->leftChild->x+1;i < temp->x;i++) cout<<'_'; } else for(int i = n+1;i < temp->x;i++) cout<<' '; cout<<temp->data; // if(temp->rightChild != NULL){ for(int i = temp->x+1;i < temp->rightChild->x;i++) cout<<'_'; } n= temp->x; subTree = temp; if(subTree->leftChild != NULL) mQueue.push(subTree->leftChild); //Ů if(subTree->rightChild != NULL) mQueue.push(subTree->rightChild); //Ů } cout<<endl; } //ȷλ template <class T> void BinTree<T>::inOrder(BinTreeNode<T> *subTree){ static int x = 1; if(subTree != NULL){ inOrder(subTree->leftChild); subTree->x = x; x++; inOrder(subTree->rightChild); } }
true
32da55c68a6eec78d22c92c8f860e3f5fe617611
C++
josefnaslund/microcontrollers
/02_hid_pad/Observers.cpp
UTF-8
1,243
3.09375
3
[]
no_license
#include "Arduino.h" #include "Observers.h" MyLed::MyLed(int pin, unsigned long interval, unsigned long len, int state) : pin(pin), interval(interval), len(len), state(state) { last = millis(); on = false; } void MyLed::update(int val){ SerialUSB.print("Hey MyLed object ("); SerialUSB.print("pin "); SerialUSB.print(pin); SerialUSB.print(") received update: "); SerialUSB.println(val); state = val; } void MyLed::tick(){ // normal constant flashing state if (state == 1){ if (!on && millis() - last > interval){ on = true; last = millis(); digitalWrite(pin, HIGH); } else if (on && millis() - last > len){ on = false; last = millis(); digitalWrite(pin, LOW); } } else if (state == 0){ if (on){on = false; digitalWrite(pin, LOW); } } else if (state == 2){ if (!on){ on = true; last = millis(); digitalWrite(pin, HIGH); } else { if (millis() - last > len){ on = false; state = 0; digitalWrite(pin, LOW); } } } }
true
4883b7af3f042cc37c11fda7f83dcf4b159a79af
C++
BekzhanKassenov/olymp
/NSUTS/2013/Test tour/A/A.cpp
UTF-8
952
2.859375
3
[]
no_license
#include <iostream> #include <cstdio> #include <sstream> #include <cmath> using namespace std; int main() { freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); int n; cin >> n; int ans = 0; int res = 0; if (n >= 1) { for (int i = 1; i <= 100; i++) { if (i <= n) ans += i; for (int j = 1; j <= 100; j++) { for (int k = 1; k <= 100; k++) { for (int l = 1; l <= 100; l++) { res += j; res *= k; res += j; res += l * k * (j + 1); } } } } } else { for (int i = 1; i >= -100; i--) { if (i >= n) ans += i; for (int j = 1; j >= -100; j--) { for (int k = 1; k >= -100; k--) { for (int l = 1; l >= -100; l--) { res += j; res *= k; res += j; res += l * k * (j + 1); } } } } } stringstream ss; ss << res; string str; ss >> str; str[0] = 'a'; cout << (ans + (str[0] != 'a')); return 0; }
true
5bb94eac240793451a1c6171de01e3a6dd52936b
C++
benbraide/cscript
/cscript/cscript/lexer/token.cpp
UTF-8
3,275
2.625
3
[]
no_license
#include "token.h" cscript::lexer::token::token(){} cscript::lexer::token::token(const index &index, const std::string &value, int match_index, const adjustment &adjustment) : index_(index), value_(value), match_index_(match_index), adjustment_(adjustment){} cscript::lexer::token::token(const index &index, std::string &&value, int match_index, const adjustment &adjustment) : index_(index), value_(static_cast<std::string &&>(value)), match_index_(match_index), adjustment_(adjustment){} cscript::lexer::token::~token(){} bool cscript::lexer::token::is_processed() const{ return false; } cscript::lexer::token &cscript::lexer::token::update(const index &index, const std::string &value, int match_index){ index_ = index; value_ = value; match_index_ = match_index; return *this; } cscript::lexer::token &cscript::lexer::token::update(const index &index, std::string &&value, int match_index){ index_ = index; value_ = static_cast<std::string &&>(value); match_index_ = match_index; return *this; } cscript::lexer::token &cscript::lexer::token::update(const index &index){ index_ = index; return *this; } cscript::lexer::token &cscript::lexer::token::update(const std::string &value){ value_ = value; return *this; } cscript::lexer::token &cscript::lexer::token::update(std::string &&value){ value_ = static_cast<std::string &&>(value); return *this; } cscript::lexer::token &cscript::lexer::token::update(int match_index){ match_index_ = match_index; return *this; } cscript::lexer::token &cscript::lexer::token::set_adjustment(const adjustment &value){ adjustment_ = value; return *this; } const cscript::lexer::token::index& cscript::lexer::token::get_index() const{ return index_; } const cscript::lexer::token::adjustment &cscript::lexer::token::get_adjustment() const{ return adjustment_; } const std::string &cscript::lexer::token::get_value() const{ return value_; } std::string cscript::lexer::token::get_adjusted_value() const{ return value_.substr(adjustment_.left, value_.size() - (adjustment_.right + adjustment_.left)); } int cscript::lexer::token::get_line() const{ return index_.line; } int cscript::lexer::token::get_column() const{ return index_.column; } int cscript::lexer::token::get_match_index() const{ return match_index_; } std::string cscript::lexer::token::to_string() const{ return (value_ + " -> " + index_to_string(index_)); } bool cscript::lexer::token::has_adjustments() const{ return (adjustment_.left != 0 || adjustment_.right != 0); } std::string cscript::lexer::token::index_to_string(const index &value){ return ("line " + std::to_string(value.line) + ", col " + std::to_string(value.column)); } bool cscript::lexer::preprocessed_token::is_processed() const{ return true; } const std::type_info &cscript::lexer::preprocessed_token::get_type_info() const{ return value_type_info_; } const boost::any &cscript::lexer::preprocessed_token::get_processed_value() const{ return processed_value_; } cscript::lexer::error_token::error_token(const index &index, const std::string &value) : token(index, value, -1, adjustment{}){} cscript::lexer::error_token::error_token(const index &index, std::string &&value) : token(index, static_cast<std::string &&>(value), -1, adjustment{}){}
true
38353c4606ca7c18f93d2f7776f3d381fa402aab
C++
LeyNe050309/Lista-Doblemente-Enlazada
/Lista doblemente enlazada/Doble lista.cpp
UTF-8
1,668
3.5625
4
[]
no_license
#include <iostream> #include <conio.h> using namespace std; struct Nodo{ int valor; Nodo *Anterior; Nodo *Siguiente; }; void agregar(int); void mostrar(); void mostrar_an(); struct Nodo *lista=NULL; int main(int argc, char** argv) { int option,agreg,num; while(option!=3){ cout<<":-:-:LISTA DOBLEMEMNTE ENLAZADA:-:-:"<<endl; cout<<"1.- Ingresar valores de la lista"<<endl; cout<<"2.- Mostrar los valores de la lista"<<endl; cout<<"3.- Salir"<<endl; cin>>option; switch (option){ case 1: cout<<"Ingrese el numero de datos que desea agregar"<<endl; cin>>num; for (int i=1;i<=num;i++){ cout<<"Ingrese los datos"<<endl; cin>>agreg; agregar(agreg); } break; case 2: cout<<"Mostrar los datos de la lista"<<endl; cout<<" "" "<<endl; mostrar(); cout<<" "" "<<endl; mostrar_an(); cout<<" "" "<<endl; break; case 3: cout<<"Salir"; default: cout<<"Gracias por usar este programa"<<endl; break; } } return 0; } void agregar(int agreg) { Nodo *nuevo= new Nodo; nuevo->Siguiente=NULL; nuevo->Anterior=NULL; nuevo->valor=agreg; if(lista==NULL)lista=nuevo; else{ Nodo *aux=lista; while(aux->Siguiente!=NULL){ aux=aux->Siguiente; } aux->Siguiente=nuevo; nuevo->Anterior=aux; } } void mostrar(){ Nodo *aux=lista; while(aux!=NULL){ cout<<aux->valor<<" -> "; aux=aux->Siguiente; } } void mostrar_an() { Nodo *aux=lista; while(aux->Siguiente!=NULL){ aux=aux->Siguiente; } while(aux!=NULL){ cout<<aux->valor<<" -> "; aux=aux->Anterior; } }
true
22c9d0dc847130155abe38f14e69a6fbb5945462
C++
binaryDiv/bdEngine
/src/Texture2D.h
UTF-8
1,363
2.953125
3
[]
no_license
#ifndef _BDENGINE_TEXTURE2D_H #define _BDENGINE_TEXTURE2D_H #include <GL/glew.h> #include "Image.h" namespace bdEngine { class Texture2D { public: /******************************************************************* * Construction and destruction *******************************************************************/ /*! * Default constructor. Doesn't actually do anything, getTextureID() * will return 0. */ Texture2D() {} /*! * Creates texture from an Image object. */ Texture2D(Image& srcImage); /*! * Releases texture resources. */ ~Texture2D(); // --- Forbid copy operations Texture2D(const Texture2D& other) = delete; // copy constructor Texture2D& operator=(const Texture2D& other) = delete; // copy assignment // --- Override move operations Texture2D(Texture2D&& other); // move constructor Texture2D& operator=(Texture2D&& other); // move assignment /******************************************************************* * Properties *******************************************************************/ /*! * Returns the texture object ID to be used by the GL functions. */ GLuint getTextureID() const { return textureID; } private: // GL texture object ID GLuint textureID; }; } // end namespace bdEngine #endif /* end of include guard: _BDENGINE_TEXTURE2D_H */
true
6e7e870e3681aced5d92e53f2ec108bbb770f1f5
C++
sg0/Elemental
/examples/lapack_like/HermitianEigFromSequential.cpp
UTF-8
1,911
2.625
3
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
/* Copyright (c) 2009-2015, Jack Poulson All rights reserved. This file is part of Elemental and is under the BSD 2-Clause License, which can be found in the LICENSE file in the root directory, or at http://opensource.org/licenses/BSD-2-Clause */ #include "El.hpp" using namespace El; using namespace std; // Typedef our real and complex types to 'Real' and 'C' for convenience typedef double Real; typedef Complex<Real> C; int main( int argc, char* argv[] ) { // This detects whether or not you have already initialized MPI and // does so if necessary. The full routine is El::Initialize. Initialize( argc, argv ); // Surround the Elemental calls with try/catch statements in order to // safely handle any exceptions that were thrown during execution. try { const Int n = Input("--size","size of matrix",100); const bool print = Input("--print","print matrices?",false); ProcessInput(); PrintInputReport(); // Create an n x n complex matrix residing on a single process. DistMatrix<C,CIRC,CIRC> H( n, n ); if( mpi::WorldRank() == 0 ) { // Set entry (i,j) to (i+j,i-j) for( Int j=0; j<n; ++j ) for( Int i=0; i<n; ++i ) H.SetLocal( i, j, C(i+j,i-j) ); } if( print ) Print( H, "H on process 0" ); // Call the eigensolver. DistMatrix<Real,CIRC,CIRC> w; DistMatrix<C,CIRC,CIRC> X; // Optional: set blocksizes and algorithmic choices here. See the // 'Tuning' section of the README for details. HermitianEig( LOWER, H, w, X, ASCENDING ); if( print ) { Print( w, "Eigenvalues of H" ); Print( X, "Eigenvectors of H" ); } } catch( exception& e ) { ReportException(e); } Finalize(); return 0; }
true
8e7a787097d83690c4c1d1da650672d91d96c642
C++
CoolRuss/TcpUdpEx
/src/protocols.cpp
UTF-8
15,274
2.921875
3
[]
no_license
#include "../includes/protocols.hpp" /// /// TcpServer /// TcpServer::~TcpServer() { this->close(); } void TcpServer::init_server(int port_init, const string& address_init) { port = port_init; message = string(message_size_max + 1, 0); if ((socket = ::socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror("Socket creation failed"); exit(EXIT_FAILURE); } int opt = 1; if(setsockopt(socket, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt)) < 0) { perror("Failed setsockopt() for reuse address and port"); exit(EXIT_FAILURE); } int bufsize = 1024*64; if (setsockopt(socket, SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize))) { perror("Failed setsockopt() for receive buffer"); exit(EXIT_FAILURE); } if (setsockopt(socket, SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize))) { perror("Failed setsockopt() for send buffer"); exit(EXIT_FAILURE); } memset(&server_address, 0, sizeof(struct sockaddr_in)); server_address.sin_family = AF_INET; server_address.sin_addr.s_addr = inet_addr(address_init.c_str()); server_address.sin_port = htons(port); client_length = sizeof(client_address); if ((bind(socket, (struct sockaddr *) &server_address, sizeof(server_address))) < 0) { perror("Failed bind() for TCP socket"); exit(EXIT_FAILURE); } } void TcpServer::listen() { if (::listen(socket, 10) < 0) { perror("Failed listen()"); exit(EXIT_FAILURE); } } void TcpServer::accept() { if ((socket_communication = ::accept(socket, (struct sockaddr *) &client_address, &client_length)) < 0) { perror("Failed accept()"); exit(EXIT_FAILURE); } } const string TcpServer::receive() { int bytes_received = 0; for(;;) // get size data { int result = recv(socket_communication, reinterpret_cast<char*>(&message_size) + bytes_received, sizeof(message_size) - bytes_received, 0); bytes_received += result; if (result < 0) { perror("Failed to receive a size data from socket"); message_size = 0; return get_message(); } else if (static_cast<uint>(bytes_received) == sizeof(message_size)) { break; } else if (result == 0) { cout << "Client has been closed!" << endl; message_size = 0; client_abort(); return get_message(); } } bytes_received = 0; for (;;) // get data { int result = recv(socket_communication, &message[bytes_received + 1], message_size - bytes_received, 0); bytes_received += result; if (result < 0) { perror("Failed to receive a data from socket"); message_size = 0; return get_message(); } else if (static_cast<uint>(bytes_received) == message_size) { break; } else if (result == 0) { cout << "Client has been closed!" << endl; message_size = 0; client_abort(); return get_message(); } } return get_message(); } void TcpServer::send(const string& message) { uint32_t size = message.size(); if (::send(socket_communication, &size, sizeof(size), 0) < 0) { perror("Failed to send a size data to socket"); return; } if (::send(socket_communication, &message[0], size, 0) < 0) { perror("Failed to send a data to socket"); return; } } void TcpServer::close() { close_communication(); if (socket > -1) if (::close(socket) < 0) { perror("Failed to close a socket"); exit(EXIT_FAILURE); } } void TcpServer::close_communication() { if (socket_communication > -1) if (::close(socket_communication) < 0) { perror("Failed to close a socket"); exit(EXIT_FAILURE); } } /// /// TcpClient /// TcpClient::~TcpClient() { this->close(); } void TcpClient::init_client(int port_init, const string& address_init) { if ((socket = ::socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror("Socket creation failed"); exit(EXIT_FAILURE); } int bufsize = 1024*64; if (setsockopt(socket, SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize))) { perror("Failed setsockopt() for receive buffer"); exit(EXIT_FAILURE); } if (setsockopt(socket, SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize))) { perror("Failed setsockopt() for send buffer"); exit(EXIT_FAILURE); } port = port_init; message = string(message_size_max + 1, 0); memset(&server_address, 0, sizeof(struct sockaddr_in)); server_address.sin_family = AF_INET; server_address.sin_addr.s_addr = inet_addr(address_init.c_str()); server_address.sin_port = htons(port); } void TcpClient::connect() { if (::connect(socket, (struct sockaddr *) &server_address, sizeof(server_address)) < 0) { perror("Failed connect()"); exit(EXIT_FAILURE); } } const string TcpClient::receive() { int bytes_received = 0; for(;;) // get size data { int result = recv(socket, reinterpret_cast<char*>(&message_size) + bytes_received, sizeof(message_size) - bytes_received, 0); bytes_received += result; if (result < 0) { perror("Failed to receive a size data from socket"); message_size = 0; return get_message(); } else if (static_cast<uint>(bytes_received) == sizeof(message_size)) { break; } else if (result == 0) { cout << "Server has been closed!" << endl; message_size = 0; return get_message(); } } bytes_received = 0; for (;;) // get data { int result = recv(socket, &message[bytes_received + 1], message_size - bytes_received, 0); bytes_received += result; if (result < 0) { perror("Failed to receive a data from socket"); message_size = 0; return get_message(); } else if (static_cast<uint>(bytes_received) == message_size) { break; } else if (result == 0) { cout << "Server has been closed!" << endl; message_size = 0; return get_message(); } } return get_message(); } void TcpClient::send(const string& message) { uint32_t size = message.size(); int bytes_sent = 0; if ((bytes_sent = ::send(socket, &size, sizeof(size), 0)) < 0) { perror("Failed to send a size data to socket"); return; } if ((bytes_sent = ::send(socket, &message[0], size, 0)) < 0) { perror("Failed to send a data to socket"); return; } } void TcpClient::close() { if (socket > -1) if (::close(socket) < 0) { perror("Failed to close a socket"); exit(EXIT_FAILURE); } } /// /// UdpServer /// UdpServer::~UdpServer() { this->close(); } void UdpServer::init_server(int port_init, const string& address_init) { port = port_init; message = string(message_size_max + 1, 0); if ((socket = ::socket(AF_INET, SOCK_DGRAM, 0)) < 0) { perror("Socket creation failed"); exit(EXIT_FAILURE); } int opt = 1; if (setsockopt(socket, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) { perror("Failed setsockopt()"); exit(EXIT_FAILURE); } int bufsize = 1024*64; if (setsockopt(socket, SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize))) { perror("Failed setsockopt() for receive buffer"); exit(EXIT_FAILURE); } if (setsockopt(socket, SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize))) { perror("Failed setsockopt() for send buffer"); exit(EXIT_FAILURE); } struct timeval timeout; timeout.tv_sec = 10; timeout.tv_usec = 0; if (setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout))) { perror("Failed setsockopt() for receive buffer timeout"); exit(EXIT_FAILURE); } memset(&server_address, 0, sizeof(struct sockaddr_in)); server_address.sin_family = AF_INET; server_address.sin_addr.s_addr = inet_addr(address_init.c_str()); server_address.sin_port = htons(port); client_length = sizeof(client_address); memset(&client_address, 0, sizeof(struct sockaddr_in)); if ((bind(socket, (struct sockaddr *) &server_address, sizeof(server_address))) < 0) { perror("Failed bind() for UDP socket"); exit(EXIT_FAILURE); } } const string UdpServer::receive() { string temp(message_size_max, 0); int bytes_received = recvfrom(socket, &temp[0], 65507, MSG_WAITALL, (struct sockaddr *) &client_address, &client_length); if (bytes_received < 0) { perror("Failed to receive a data from socket"); message_size = 0; return get_message(); } bytes_received--; if (temp[0] == '1') // receive one packet { message.replace(0, 65507, temp); } else if (temp[0] == '2') // receive two packets { message.replace(0, 65507, temp); int result = recvfrom(socket, &temp[0], message_size_max - 65506 + 1, MSG_WAITALL, (struct sockaddr *) &client_address, &client_length); if (result < 0) { perror("Failed to receive a second chunk data from socket"); message_size = 0; return get_message(); } if (temp[0] != '3') { cerr << "Failed to receive a second chunk data from socket. Error header." << endl; message_size = 0; return get_message(); } result--; bytes_received += result; message.replace(65507, result, temp.substr(1)); } else if (temp[0] == '3') // receive two packets in reverse { message.replace(65507, bytes_received, temp.substr(1)); int result = recvfrom(socket, &message[0], 65507, MSG_WAITALL, (struct sockaddr *) &client_address, &client_length); if (result < 0) { perror("Failed to receive a first chunk data from socket"); message_size = 0; return get_message(); } if (message[0] != '2') { cerr << "Failed to receive a first chunk data from socket. Error header." << endl; message_size = 0; return get_message(); } result--; bytes_received += result; } message_size = bytes_received; return get_message(); } void UdpServer::send(const string& message) { string data; if (message.size() > 65507 - 1) // break down message into two packets { data = "2" + message.substr(0, 65507 - 1); if ((sendto(socket, data.c_str(), data.size(), MSG_CONFIRM, (const struct sockaddr *) &client_address, client_length)) < 0) { perror("Failed to send a data to socket"); return; } data = "3" + message.substr(65507 - 1); if ((sendto(socket, data.c_str(), data.size(), MSG_CONFIRM, (const struct sockaddr *) &client_address, client_length)) < 0) { perror("Failed to send a data to socket"); return; } } else // The message is lesser than max size of packet { data = "1" + message; if ((sendto(socket, data.c_str(), data.size(), MSG_CONFIRM, (const struct sockaddr *) &client_address, client_length)) < 0) { perror("Failed to send a data to socket"); return; } } } void UdpServer::close() { if (socket_communication > -1) ::close(socket_communication); if (socket > -1) if (::close(socket) < 0) { perror("Failed to close a socket"); exit(EXIT_FAILURE); } } /// /// UdpClient /// UdpClient::~UdpClient() { this->close(); } void UdpClient::init_client(int port_init, const string& address_init) { if ((socket = ::socket(AF_INET, SOCK_DGRAM, 0)) < 0) { perror("Socket creation failed"); exit(EXIT_FAILURE); } int bufsize = 1024*64; if (setsockopt(socket, SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize))) { perror("Failed setsockopt() for receive buffer"); exit(EXIT_FAILURE); } if (setsockopt(socket, SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize))) { perror("Failed setsockopt() for send buffer"); exit(EXIT_FAILURE); } struct timeval timeout; timeout.tv_sec = 10; timeout.tv_usec = 0; if (setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout))) { perror("Failed setsockopt() for receive buffer timeout"); exit(EXIT_FAILURE); } port = port_init; message = string(message_size_max+1, 0); memset(&server_address, 0, sizeof(struct sockaddr_in)); server_address.sin_family = AF_INET; server_address.sin_addr.s_addr = inet_addr(address_init.c_str()); server_address.sin_port = htons(port); server_length = sizeof(server_address); } const string UdpClient::receive() { string temp(message_size_max, 0); int bytes_received = recvfrom(socket, &temp[0], 65507, MSG_WAITALL, (struct sockaddr *) &server_address, &server_length); if (bytes_received < 0) { perror("Failed to receive a data from socket"); message_size = 0; return get_message(); } bytes_received--; if (temp[0] == '1') // receive one packet { message.replace(0, 65507, temp); } else if (temp[0] == '2') // receive two packets { message.replace(0, 65507, temp); int result = recvfrom(socket, &temp[0], message_size_max - 65506 + 1, MSG_WAITALL, (struct sockaddr *) &server_address, &server_length); if (result < 0) { perror("Failed to receive a second chunk data from socket"); message_size = 0; return get_message(); } if (temp[0] != '3') { cerr << "Failed to receive a second chunk data from socket. Error header." << endl; message_size = 0; return get_message(); } result--; bytes_received += result; message.replace(65507, result, temp.substr(1)); } else if (temp[0] == '3') // receive two packets in reverse { message.replace(65507, bytes_received, temp.substr(1)); int result = recvfrom(socket, &message[0], 65507, MSG_WAITALL, (struct sockaddr *) &server_address, &server_length); if (result < 0) { perror("Failed to receive a first chunk data from socket"); message_size = 0; return get_message(); } if (message[0] != '2') { cerr << "Failed to receive a first chunk data from socket. Error header." << endl; message_size = 0; return get_message(); } result--; bytes_received += result; } message_size = bytes_received; return get_message(); } void UdpClient::send(const string& message) { string data; if (message.size() > 65507 - 1) // break down message into two packets { data = "3" + message.substr(65507 - 1); if ((sendto(socket, data.c_str(), data.size(), MSG_CONFIRM, (const struct sockaddr *) &server_address, sizeof(server_address))) < 0) { perror("Failed to send a data to socket"); return; } data = "2" + message.substr(0, 65507 - 1); if ((sendto(socket, data.c_str(), data.size(), MSG_CONFIRM, (const struct sockaddr *) &server_address, sizeof(server_address))) < 0) { perror("Failed to send a data to socket"); return; } } else // The message is lesser than max size of packet { data = "1" + message; if ((sendto(socket, data.c_str(), data.size(), MSG_CONFIRM, (const struct sockaddr *) &server_address, sizeof(server_address))) < 0) { perror("Failed to send a data to socket"); return; } } } void UdpClient::close() { if (socket > -1) if (::close(socket) < 0) { perror("Failed to close a socket"); exit(EXIT_FAILURE); } }
true
0c14d4665e9e6a145d391441b2d7415d6fb5c1d4
C++
alexbajzat/C-Cpp-projects
/Laborator6-7/src/Header/controller.h
UTF-8
2,152
3.125
3
[]
no_license
/* * controller.h * * Created on: Mar 28, 2016 * Author: alex-bajzat */ #ifndef CONTROLLER_H_ #define CONTROLLER_H_ #include "../Header/disciplineRepo.h" #include <string> class DisciplineController { private: DiscRepository repository; /* * return the current repository */ DiscRepository* getRepo() { return &repository; } public: /* * no params * * in the constructor we initialize the validator class */ DisciplineController() { } /* * this function validates input data, and * creates an element */ void addElement(int id, int type, int hours, std::string name, std::string prof); /* * This function modifies and element for the * specified position */ void modifyElement(int id, int type, int hours, std::string name, std::string prof, int pos) { Element* element = new Element(id, type, hours, name, prof); repository.modifyElement(pos, element); } /* * delete an element at a given position * */ void deleteElement(int pos) { repository.deleteElement(pos); } /* * returns the dynamicvector object */ DynamicVector<Element>* getElementList() { return getRepo()->getElementList(); } /* * returns a pointer to an element * with the given id (unique) * the id must be validated! */ Element* getElementById(int id); /* * filters a copy of the vector * by number of hours */ DynamicVector<Element> filterByHours(int hours); /* * filters a copy of the vector * by professor name */ DynamicVector<Element> filterByProf(std::string prof); bool direction(bool initial, int dir) { if (dir == 0) return initial; else return !initial; } /* * sorts a copy of the vector * by number of hours */ DynamicVector<Element> sort(int dir, bool (*f)(Element*, Element*), DynamicVector<Element>* initList) ; /*DynamicVector<Element> sortMultiple(int dir, bool (*first)(Element*, Element*), bool (*second)(Element*, Element*), DynamicVector<Element>* initList) { DynamicVector<Element> fSorted = sort(dir, first, initList); wat return new DynamicVector<Element> ; }*/ }; #endif /* CONTROLLER_H_ */
true
802d571512900871667137d584a75a10c462cc09
C++
RayCS2023/MST
/DisjointSet.cpp
UTF-8
4,031
3.546875
4
[]
no_license
// // DisjointSet.cpp // MST // // Created by Raymond Chen on 2020-03-27. // Copyright © 2020 Raymond Chen. All rights reserved. // #include "DisjointSet.hpp" //constructors/destructors of Node class Node::Node() { next = nullptr; list = nullptr; } Node::Node(const int &u) { this->u = u; next = nullptr; list = nullptr; } Node::~Node() { next = nullptr; list = nullptr; } //constructors/destructors of Set class Set::Set() { head = nullptr; tail = nullptr; } Set::~Set() { head = nullptr; tail = nullptr; } void DisjointSet::MakeSet( int const &u) { //allocate a linked list Set *set = new Set(); //allocate a node Node *node = new Node(u); //assign the head and values of the linked list and its rank set->head = node; set->tail = node; set->rank = 0; //assign node to the set that it belongs in node->list = set; //put vertex into the node vector vertex[u] = node; } DisjointSet::~DisjointSet() { if(vertex.size() != 0){ std::vector<int> unconnect_sets; std::vector<bool> free; //find all the connected/unconnedt sets in the MST and append to vector for (int i = 0; i < vertex.size(); i++){ unconnect_sets.push_back(vertex[i]->list->head->u); free.push_back(false); } //check if the memory for that set has been deallated or not, if not, deallocate it for (int i = 0; i < unconnect_sets.size(); i++){ if(free[unconnect_sets[i]] == false){ free[unconnect_sets[i]] = true; delete vertex[unconnect_sets[i]]->list; } } //delete memory allocate for each node for (int i = 0; i < vertex.size(); i++){ delete vertex[i]; } } } //Constructor of Disjointed Sets DisjointSet::DisjointSet(const int &size) { //create instance of set class Node *node = nullptr; //initialize the total number to sets for (int i = 0; i < size; i++){ vertex.push_back(node); } } //returns the head pointer of each linke list Node* DisjointSet::FindSet(const int &u) { return vertex[u]->list->head; } void DisjointSet::Union(const int &u, const int &v) { //traverse v if rank of u is higher than rank of v if(vertex[u]->list->rank > vertex[v]->list->rank){ //variable to store the head of the linked list being traversed Node *tmp = vertex[v]->list->head; //merge the link list and assign new tail vertex[u]->list->tail->next = tmp; vertex[u]->list->tail = vertex[v]->list->tail; //deallocate memory of the linked list in V since it will be overwritten delete vertex[v]->list; //loop to update the the linke list of nodes in v while(tmp!=nullptr){ tmp->list = vertex[u]->list; tmp = tmp->next; } //update rank vertex[v]->list->rank = vertex[u]->list->rank; } //traverse u if rank of v is higher or equal to the rank of v else{ //variable to store the head of the linked list being traversed Node* tmp = vertex[u]->list->head; //merge the link list and assign new tail vertex[v]->list->tail->next = tmp; vertex[v]->list->tail = vertex[u]->list->tail; //deallocate memory of the linked list in U since it will be overwritten delete vertex[u]->list; //loop to update the the linke list of nodes in u while(tmp!=nullptr){ tmp->list = vertex[v]->list; tmp = tmp->next; } //update rank if(vertex[u]->list->rank < vertex[v]->list->rank) vertex[u]->list->rank = vertex[v]->list->rank; else{ vertex[u]->list->rank++; vertex[v]->list->rank++; } } }
true
60b87e13640bdf3f0aff27b2c581374c07a8d84e
C++
dylanrichardson/factor
/factorRichardson.cpp
UTF-8
17,563
2.671875
3
[]
no_license
#include <iostream> #include <fstream> #include <windows.h> #include <math.h> #include "dric.h" using namespace std; const int STR_LEN = 200; const int ARR_LEN = 30; void factor(float, float, float, char * * ); void quadratic(float, float, float, char * * ); void equation(void); void writeHtml(float, float, float, char * * , char * * ); void fillEmptyStr(char * * , int, int); void writeFraction(int, int, char * ); void gcf3(int * , int * , int * ); void writeLinEq(float, float, char * * , int * ); void writeQuadEq(float, float, float, char * * , int * ); void writeFacEq(int, int, int, char * * , int * ); char FILEPATH[] = "answer.html"; int main() { menu main(2, "Quadratic Equation Solver"); optionList options = { "New equation", "Exit" }; function functions[] = { equation, EXIT }; main.setOptions(options); main.setFunctions(functions); main.open(); return 0; } void equation(void) { char * * quadHtml; quadHtml = new char * [ARR_LEN]; for (int i = 0; i < ARR_LEN; i++) quadHtml[i] = new char[STR_LEN]; char * * factorHtml; factorHtml = new char * [ARR_LEN]; for (int i = 0; i < ARR_LEN; i++) factorHtml[i] = new char[STR_LEN]; fillArr2(quadHtml, ARR_LEN, STR_LEN); fillArr2(factorHtml, ARR_LEN, STR_LEN); system("cls"); float a, b, c; cout << "ax^2+bx+c=0\n\n"; cout << "Enter a: "; input( & a, 6, FLOAT_); cout << "Enter b: "; input( & b, 6, FLOAT_); cout << "Enter c: "; input( & c, 6, FLOAT_); quadratic(a, b, c, quadHtml); factor(a, b, c, factorHtml); writeHtml(a, b, c, quadHtml, factorHtml); ShellExecute(NULL, "open", FILEPATH, NULL, NULL, SW_SHOWNORMAL); Sleep(1000); system("pause"); remove(FILEPATH); } void factor(float A, float B, float C, char * * html) { int line = 0; if (A == 0) { strcat(html[line], "Cannot factor linear equation"); line++; } else if (A != floor(A) || B != floor(B) || C != floor(C)) { strcat(html[line], "Non integer coeffecients"); line++; } else { char temp[11]; int a = A, b = B, c = C; float n = (-b + sqrt(b * b - 4 * a * c)) / -2; float m = (-b - sqrt(b * b - 4 * a * c)) / -2; if (n != floor(n) || m != floor(m)) { //check fractions strcat(html[line], "Not factorable"); line++; } else { //write equation and sub writeFacEq(a, n, m, html, & line); if (n == 0) { char temp[11]; itoa(a, temp, 10); strcat(html[line], temp); strcat(html[line], "x = 0"); line++; line++; } else if (n != m) { //split into two equations strcat(html[line], "<span style='width:50%;float:left'>"); if (a != 1) { itoa(a, temp, 10); strcat(html[line], temp); } strcat(html[line], "x"); if (n > 0) strcat(html[line], "+"); itoa(n, temp, 10); strcat(html[line], temp); strcat(html[line], " = 0"); line++; if (a != 1) { itoa(a, temp, 10); strcat(html[line], temp); } strcat(html[line], "x = "); itoa(-n, temp, 10); strcat(html[line], temp); line++; if (a != 1) { strcat(html[line], "x = "); itoa(-n, temp, 10); strcat(html[line], temp); strcat(html[line], "/"); itoa(a, temp, 10); strcat(html[line], temp); line++; } strcat(html[line], "</span>"); strcat(html[line], "<span style='width:50%;float:left'>"); if (a != 1) { itoa(a, temp, 10); strcat(html[line], temp); } strcat(html[line], "x"); if (m > 0) strcat(html[line], "+"); itoa(m, temp, 10); strcat(html[line], temp); strcat(html[line], " = 0"); line++; if (a != 1) { itoa(a, temp, 10); strcat(html[line], temp); } strcat(html[line], "x = "); itoa(-m, temp, 10); strcat(html[line], temp); line++; if (a != 1) { strcat(html[line], "x = "); itoa(-m, temp, 10); strcat(html[line], temp); strcat(html[line], "/"); itoa(a, temp, 10); strcat(html[line], temp); line++; } line++; strcat(html[line], "</span>"); line++; } else { //ax+n=0 //ax=-n //x=-n/a if (a != 1) { itoa(a, temp, 10); strcat(html[line], temp); } strcat(html[line], "x"); if (n > 0) strcat(html[line], "+"); itoa(n, temp, 10); strcat(html[line], temp); strcat(html[line], " = 0"); line++; if (a != 1) { itoa(a, temp, 10); strcat(html[line], temp); } strcat(html[line], "x = "); itoa(-n, temp, 10); strcat(html[line], temp); line++; if (a != 1) { strcat(html[line], "x = "); itoa(-n, temp, 10); strcat(html[line], temp); strcat(html[line], "/"); itoa(a, temp, 10); strcat(html[line], temp); line++; } line++; } //solution strcat(html[line], "Solution"); line++; line++; strcat(html[line], "x = "); writeFraction(-n, a, html[line]); line++; if (n != m) { strcat(html[line], "x = "); writeFraction(-m, a, html[line]); line++; } line++; } } } void quadratic(float A, float B, float C, char * * html) { int line = 0; //linear if (A == 0) { writeLinEq(B, C, html, & line); strcat(html[line], "Solution"); line++; line++; strcat(html[line], "x = "); if (C == floor(C) && B == floor(B)) writeFraction(-C, B, html[line]); else { char temp[11]; ftoa(-C / B, temp, 10); strcat(html[line], temp); } } //integer else if (A == floor(A) && B == floor(B) && C == floor(C)) { int a = A, b = B, c = C; writeQuadEq(a, b, c, html, & line); strcat(html[line], "Solution"); line++; line++; //square root int discriminant = b * b - 4 * a * c; int denominator = 2 * a; float discSqrt = sqrt(discriminant); //square discriminant if (discSqrt == floor(discSqrt)) { if (discSqrt == 0) { //one answer strcat(html[line], "x = "); writeFraction(-b, denominator, html[line]); } else { int n1 = -b + discSqrt; int n2 = -b - discSqrt; if ((float) n1 / denominator == (float) n2 / denominator) { //one answer strcat(html[line], "x = "); writeFraction(n1, denominator, html[line]); } else { //first answer strcat(html[line], "x = "); writeFraction(n1, denominator, html[line]); //second answer line++; strcat(html[line], "x = "); writeFraction(n2, denominator, html[line]); } } } //not square discriminant else { //get prime factors bool negDisc = false; if (discriminant < 0) { discriminant = -discriminant; negDisc = true; } int out = simplifySqrt(discriminant); int in = discriminant / out / out; if (b == 0) { //square root divided by denominator simplifyFrac( & out, & denominator); char temp[10]; strcat(html[line], "x = "); //plus-minus strcat(html[line], "&plusmn;"); if (abs(out) != 1) { //number outside sqrt itoa(abs(out), temp, 10); strcat(html[line], temp); } if ( in != 1) { //inside sqrt strcat(html[line], "&radic;<span style=\"text-decoration:overline\">&nbsp;"); itoa( in , temp, 10); strcat(html[line], temp); strcat(html[line], "&nbsp;</span>"); } if (negDisc) strcat(html[line], "i"); if (denominator != 1) { //denominator strcat(html[line], "/"); itoa(denominator, temp, 10); strcat(html[line], temp); } if (abs(out) != 1 && in != 1 && denominator != 1 && !negDisc) //everything equals 1 strcat(html[line], "1"); } else { //-b and square root divided by denominator char temp[10]; gcf3( & b, & out, & denominator); strcat(html[line], "x = "); bool parentheses = denominator != 1 && (abs(out) != 1 || in != 1); if (parentheses) strcat(html[line], "("); //-b itoa(-b, temp, 10); strcat(html[line], temp); //plus-minus strcat(html[line], "&plusmn;"); if (abs(out) != 1) { //number outside sqrt itoa(abs(out), temp, 10); strcat(html[line], temp); } if (negDisc) strcat(html[line], "i"); if ( in != 1) { //inside sqrt strcat(html[line], "&radic;<span style=\"text-decoration:overline\">&nbsp;"); itoa( in , temp, 10); strcat(html[line], temp); strcat(html[line], "&nbsp;</span>"); } if (parentheses) strcat(html[line], ")"); if (denominator != 1) { //denominator strcat(html[line], "/"); itoa(denominator, temp, 10); strcat(html[line], temp); } if (abs(out) != 1 && in != 1 && denominator != 1 && !negDisc) //everything equals 1 strcat(html[line], "1"); } } } //decimal else { writeQuadEq(A, B, C, html, & line); strcat(html[line], "Solution"); line++; line++; float x1 = (-B + sqrt(B * B - 4 * A * C)) / (2 * A); float x2 = (-B - sqrt(B * B - 4 * A * C)) / (2 * A); char ans1[15] = "x = "; char ans2[15] = "x = "; char x[11]; ftoa(x1, x, 10); strncat(ans1, x, 10); strncpy(html[line], ans1, STR_LEN); line++; ftoa(x2, x, 10); strncat(ans2, x, 10); strncpy(html[line], ans2, STR_LEN); } } void writeHtml(float a, float b, float c, char * * quadHtml, char * * factorHtml) { fstream html; html.open(FILEPATH, ios::out); if (!html) { cout << "Could not open file"; return; } html << "<!DOCTYPE html>"; html << "<html>"; html << "<head><title>Quadratic Equation Solver</title>"; html << "<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>"; html << "<script>$.ajax({url:'http://www.14test14.co.nf/api/quadratic.php',type:'GET',data:{input:'"; html << a << "x^2+" << b << "x+" << c << "=0'}}).done(function(ret){$('#wa').append('<h3>WolframAlpha</h3><p>'+ret+'<p>')})</script></head>"; html << "<body>"; html << "<div style='text-align:center'><h3>Input</h3><p>"; if (a != 0) { if (a == -1) html << "-"; else if (a != 1) html << a; html << "x<sup>2</sup> "; } if (b != 0) { if (a != 0) { if (b > 0) html << "+"; else html << "-"; html << " "; if (abs(b) != 1) html << abs(b); html << "x "; } else { if (abs(b) != 1) html << b; html << "x "; } } if (c != 0) { if (a != 0 || b != 0) { if (c > 0) html << "+"; else html << "-"; html << " "; html << abs(c) << " "; } else html << c << " "; } html << "= 0</p></div>"; html << "<div id='quad' style='width:50%;float:left;overflow:hidden'>"; html << "<h3>Quadratic Formula Method</h3>"; html << "<p>"; for (int i = 0; i < ARR_LEN; i++) html << quadHtml[i] << "<br>"; html << "</p>"; html << "</div>"; html << "<div id='factor' style='width:50%;float:left;overflow:hidden'>"; html << "<h3>Factoring Method</h3>"; html << "<p>"; for (int i = 0; i < ARR_LEN; i++) html << factorHtml[i] << "<br>"; html << "</p>"; html << "</div>"; html << "<div id='wa' style='clear:both'></div>"; html << "</body>"; html << "</html>"; html.close(); } void writeFraction(int n, int d, char * dest) { if (d == 0) { strcat(dest, "undefined"); return; } else if (n == 0) { strcat(dest, "0"); return; } simplifyFrac( & n, & d); char temp[10]; //numerator itoa(n, temp, 10); strcat(dest, temp); if (d != 1) { strcat(dest, "/"); //denominator itoa(d, temp, 10); strcat(dest, temp); } } void writeLinEq(float b, float c, char * * destp, int * line) { strcat(destp[ * line], "Equation"); ( * line) ++; ( * line) ++; char temp[11]; strcat(destp[ * line], "x = -c/b"); ( * line) ++; ( * line) ++; strcat(destp[ * line], "Substitution"); ( * line) ++; ( * line) ++; strcat(destp[ * line], "x = -("); ftoa(c, temp, 10); strcat(destp[ * line], temp); strcat(destp[ * line], ")/"); ftoa(b, temp, 10); strcat(destp[ * line], temp); ( * line) ++; ( * line) ++; } void writeQuadEq(float a, float b, float c, char * * destp, int * line) { strcat(destp[ * line], "Equation"); ( * line) ++; ( * line) ++; char temp[11]; strcat(destp[ * line], "x = (-b&plusmn;&radic;<span style=\"text-decoration:overline\">&nbsp;b</span><sup>2</sup><span style=\"text-decoration:overline\">-4ac&nbsp;</span>)/(2a)"); ( * line) ++; ( * line) ++; strcat(destp[ * line], "Substitution"); ( * line) ++; ( * line) ++; strcat(destp[ * line], "x = [-("); ftoa(b, temp, 10); strcat(destp[ * line], temp); strcat(destp[ * line], ")&plusmn;&radic;<span style=\"text-decoration:overline\">&nbsp;("); strcat(destp[ * line], temp); strcat(destp[ * line], ")</span><sup>2</sup><span style=\"text-decoration:overline\">-4("); ftoa(a, temp, 10); strcat(destp[ * line], temp); strcat(destp[ * line], ")("); ftoa(c, temp, 10); strcat(destp[ * line], temp); strcat(destp[ * line], ")&nbsp;</span>]/[2("); ftoa(a, temp, 10); strcat(destp[ * line], temp); strcat(destp[ * line], ")]"); ( * line) ++; ( * line) ++; } void writeFacEq(int a, int n, int m, char * * destp, int * line) { strcat(destp[ * line], "Equation"); ( * line) ++; ( * line) ++; char temp[11]; strcat(destp[ * line], "a*c = n*m"); ( * line) ++; strcat(destp[ * line], "n+m = b"); ( * line) ++; strcat(destp[ * line], "(ax+n)(ax+m) = 0"); ( * line) ++; ( * line) ++; strcat(destp[ * line], "Substitution"); ( * line) ++; ( * line) ++; strcat(destp[ * line], "[("); itoa(a, temp, 10); strcat(destp[ * line], temp); strcat(destp[ * line], ")x+("); itoa(n, temp, 10); strcat(destp[ * line], temp); strcat(destp[ * line], ")][("); itoa(a, temp, 10); strcat(destp[ * line], temp); strcat(destp[ * line], ")x+("); itoa(m, temp, 10); strcat(destp[ * line], temp); strcat(destp[ * line], ")]"); strcat(destp[ * line], " = 0"); ( * line) ++; ( * line) ++; }
true
a8ae79387be19f0b935e3c5f6b8f1aaf7fbef6fe
C++
nponcian/LibroDeConocimiento
/References/HexagonalString/RecursiveAlgorithm.cpp
UTF-8
2,682
3.015625
3
[]
no_license
#include <RecursiveAlgorithm.hpp> #include <string> #include <unordered_set> #include <utility> #include <Grid.hpp> namespace algo { namespace { std::pair<int, int> getColumnTopAndBotNeighbors( const int row, const int col) { return row % 2 ? std::make_pair(col - 1, col) : std::make_pair(col, col + 1); } std::pair<int, int> getColumnSideNeighbors( const int col) { return std::make_pair(col - 1, col + 1); } } // namespace size_t PairHash::operator()(const std::pair<int, int>& intPair) const { return std::hash<int>()(intPair.first) ^ std::hash<int>()(intPair.second); } RecursiveAlgorithm::RecursiveAlgorithm( const std::string& targetString) : targetString_(targetString), totalCount_(0) { } const std::string RecursiveAlgorithm::NAME = "RecursiveAlgorithm"; unsigned RecursiveAlgorithm::operator()() { totalCount_ = 0; for (int row = 0; row < static_cast<int>(grid::HEXAGONAL_GRID.size()); ++row) { for (int col = 0; col < static_cast<int>(grid::HEXAGONAL_GRID[row].size()); ++col) { // countFromPoint(row, col, 0, {}); // some compilers reject this! countFromPoint(row, col, 0, std::unordered_set<std::pair<int, int>, PairHash>()); } } return totalCount_; } void RecursiveAlgorithm::countFromPoint( const int row, const int col, const unsigned currentIndex, std::unordered_set<std::pair<int, int>, PairHash> processedRowColPairs) { if (!grid::isWithinGridBounds(row, col) || processedRowColPairs.count({row, col}) || grid::HEXAGONAL_GRID[row][col] != targetString_[currentIndex]) { return; } else if (currentIndex == targetString_.size() - 1) { ++totalCount_; return; } processedRowColPairs.insert({row, col}); auto colTopBotNeighbor = getColumnTopAndBotNeighbors(row, col); auto colSideNeighbor = getColumnSideNeighbors(col); // recursively traverse top neighbors countFromPoint(row - 1, colTopBotNeighbor.first, currentIndex + 1, processedRowColPairs); countFromPoint(row - 1, colTopBotNeighbor.second, currentIndex + 1, processedRowColPairs); // recursively traverse side neighbors countFromPoint(row, colSideNeighbor.first, currentIndex + 1, processedRowColPairs); countFromPoint(row, colSideNeighbor.second, currentIndex + 1, processedRowColPairs); // recursively traverse bot neighbors countFromPoint(row + 1, colTopBotNeighbor.first, currentIndex + 1, processedRowColPairs); countFromPoint(row + 1, colTopBotNeighbor.second, currentIndex + 1, processedRowColPairs); } } // namespace algo
true
e44f7c9d30790043df2a4d2d1e9169f7e3ae1644
C++
BenniKunz/SFML-Game
/Game Engine/RocketParticle.cpp
UTF-8
1,848
2.78125
3
[]
no_license
#include "RocketParticle.h" Engine::RocketParticle::~RocketParticle() { std::cout << "RocketParticle Destructor" << std::endl; } void Engine::RocketParticle::InputHandler() { } void Engine::RocketParticle::Update(float dt, std::vector<std::shared_ptr<IGamePart>>& _gameParts) { ParticleMovement(dt); CollisionDetection(_gameParts); CheckParticleLifeTime(); } void Engine::RocketParticle::EventHandler(sf::Event event) { } void Engine::RocketParticle::CheckParticleLifeTime() { if (this->_clock.getElapsedTime().asSeconds() > _bulletLifeTime) { this->_removed = true; } } void Engine::RocketParticle::ParticleMovement(float dt) { /*this->_position += this->_direction * dt * _speed; this->_texture.setPosition(_position.x, _position.y);*/ _texture.move(this->_direction * dt * _speed); // difference? } void Engine::RocketParticle::CollisionDetection(std::vector<std::shared_ptr<Engine::IGamePart>>& _gameParts) { for (auto& gamePart : _gameParts) { if (gamePart.get() == this || gamePart.get() == _player || gamePart->_layer == weapon) { continue; } else { sf::FloatRect temp = sf::FloatRect( gamePart->GetGlobalBounds().left + 20, gamePart->GetGlobalBounds().top + 20, gamePart->GetGlobalBounds().width - 50, gamePart->GetGlobalBounds().height - 50); if (this->_texture.getGlobalBounds().intersects(temp)) { gamePart->DealDamage(WeaponType::rocket); this->_removed = true; } } } } void Engine::RocketParticle::Draw() { this->_data.window.draw(this->_texture); } void Engine::RocketParticle::SetRocketRotation() { if (_direction == sf::Vector2f(1, 0)) { this->_texture.setRotation(90.0f); } else if (_direction == sf::Vector2f(0, 1)) { this->_texture.setRotation(180.0f); } else if (_direction == sf::Vector2f(-1, 0)) { this->_texture.setRotation(-90.0f); } }
true
e84c82011d43b649925d6e4bc6cd88b39feb5349
C++
halfopen/data_struct
/work2.1/expr/2013301500100.2.1.cpp
UTF-8
2,776
3.46875
3
[]
no_license
#include "expr.h" #include <stdio.h> #include <stdlib.h> #include <assert.h> /* -BLOCK----------- 如果需要, 你可以调用以下函数 ----------------- */ // 将由数字字符组成的 arr 转为数字, n 为 arr 的长度 static int NumFromArray(const char * const arr, int n); // 根据运算符 op 进行运算, 获得运算结果 static int Calc(int a, int b, char op); /* -END OF BLOCK--------------------------------------------------- */ /* -BLOCK---- 如果需要, 请在此加入你的数据结构及函数声明 ---------- */ /* -END OF BLOCK--------------------------------------------------- */ /* -BLOCK-------------- 必须通过此函数返回结果 -------------------- */ int Eval(const char* const expr, int n) // 请参阅 expr.h 的注释 { int answer = 0, num_len = 0, i = 0, a = 0, b = 0,t_i=0;//num_len数字长度,i遍历,a暂时保存数字 char t_exp[1024]={0}, op;//保存只有+-的表达式 int t_n = 0; while(*(expr+i)>='0' && *(expr+i) <= '9' && i<n) { i++; num_len++; } a = NumFromArray( expr, num_len); *t_exp = a+1;//数值都多一,防止出现0 while( *(expr+i) && i<n)//遍历 { op = *(expr+i); //得到一个操作符 i++; t_i=i; //保存i的位置 num_len = 0; while(*(expr+i)>='0' && *(expr+i) <= '9' && i<n) { i++; num_len++; } b = NumFromArray( expr+t_i, num_len); //得到一个数字 if(op=='/'|| op =='*') { a=Calc(a,b,op); *(t_exp+t_n) = a+1; } else { *(t_exp+t_n+1)=op; *(t_exp+t_n+2)=b+1; t_n+=2; } if(i>=n) { i=1;answer = *t_exp-1; while(i<=t_n) { op = *(t_exp+i); b = *(t_exp+i+1)-1; answer = Calc(answer,b,op); i += 2; } break; } } return answer; } /* -END OF BLOCK--------------------------------------------------- */ /* -BLOCK------- 如果需要, 请在此加入你已声明的函数实现 ----------- */ /* -END OF BLOCK--------------------------------------------------- */ static int NumFromArray(const char * const arr, int n) { assert(n > 0); int num = 0; for (int i = 0; i < n; i++) { if (arr[i] < '0' || arr[i] > '9') { fprintf(stderr, "NumFromArray: bad input - not a digit '%c'\n", arr[i]); exit(-1); } num *= 10; num += arr[i] - '0'; } return num; } static int Calc(int a, int b, char op) { switch (op) { case '+': return a+b; case '-': return a-b; case '*': return a*b; case '/': return a/b; default: fprintf(stderr, "Calc: bad input - operation '%c'\n", op); exit(-2); }; }
true
12c9117f3ca89248ad9e465c5d25f0bf26892010
C++
dillonanderson2023/CSCI-261
/main.cpp
UTF-8
747
3.640625
4
[]
no_license
/* CSCI 261 Lab 1C l: Geometric Calculations * * Dillon Anderson*/ #include <iostream> using namespace std; int main() { int length = 17; int width = 17; int height = 2; cout << "Enter length of box here: "; cin >> length; cout << "Enter width of box here: "; cin >> width; cout << "Enter height of box here: "; cin >> height; int volume = length * width * height; cout << "The volume of your box is: "; cout << volume << endl; cout << endl; const double PI = 3.14159; double r; double vol_Of_C; cout << "Enter the radius of the circle: "; cin >> r; vol_Of_C = r * r * PI; cout << "The volume of the circle is: "; cout << vol_Of_C; return 0; }
true
392c9d2e73126fec07690fc319e810b59916244a
C++
tngo0508/Cplusplus-OCC-
/quiz3_practice/Project3/Function.cpp
UTF-8
7,774
3.484375
3
[]
no_license
#include "DoublyList.h" void DoublyList::insertBack(int newData) { Node *newNode = new Node(newData, NULL, last); if (first == NULL) { first = newNode; last = newNode; } else { last->setNext(newNode); last = last->getNext(); } ++count; } void DoublyList::reservePrint() const { Node *current = last; while (current != NULL) { cout << current->getData() << " "; current = current->getPrev(); } } void DoublyList::insertInOrder(int insertData) { Node *newNode = new Node(insertData, NULL, NULL); if (first == NULL) { first = newNode; last = newNode; } else { if (first->getData() > insertData) { first->setPrev(newNode); newNode->setNext(first); first = newNode; } else { Node *current = first->getNext(); bool found = false; while (current != NULL && !found) { if (current->getData() > insertData) found = true; else current = current->getNext(); } if (current != NULL) { newNode->setPrev(current->getPrev()); newNode->setNext(current); current->getPrev()->setNext(newNode); current->setPrev(newNode); } else { last->setNext(newNode); newNode->setPrev(last); last = newNode; } } } ++count; } void DoublyList::rotateLeft() { first->setPrev(last); last->setNext(first); first = first->getNext(); last = last->getNext(); first->setPrev(NULL); last->setNext(NULL); } void DoublyList::rotateright() { last->setNext(first); first->setPrev(last); first = first->getPrev(); last = last->getPrev(); first->setPrev(NULL); last->setNext(NULL); } void DoublyList::moveKeyToFirst(int key) { if (count == 0) { cerr << "List is empty.\n"; } else if (count != 1) { Node *current = first->getNext(); if (current->getNext() == NULL) { first->setPrev(last); last->setNext(first); first = last; last = last->getNext(); first->setPrev(NULL); last->setNext(NULL); } else { bool found = false; while (current != NULL && !found) { if (current->getData() == key) found = true; else current = current->getNext(); } if (current != NULL) { if (current != last) { current->getPrev()->setNext(current->getNext()); current->getNext()->setPrev(current->getPrev()); current->setNext(first); first->setPrev(current); first = first->getPrev(); first->setPrev(NULL); } else { last = last->getPrev(); last->setNext(NULL); current->setNext(first); first->setPrev(current); first = first->getPrev(); first->setPrev(NULL); } } } } } void DoublyList::moveKeyToLast(int key) { if (count == 0) { cerr << "List is empty.\n"; } else if (count != 1) { Node *current = first->getNext(); if (first->getData() == key) { if (current->getNext() == NULL) { first->setPrev(last); last->setNext(first); first = last; last = last->getNext(); first->setPrev(NULL); last->setNext(NULL); } else { first->setPrev(last); last->setNext(first); first = first->getNext(); last = last->getNext(); first->setPrev(NULL); last->setNext(NULL); } } else { bool found = false; while (current != NULL && !found) { if (current->getData() == key) found = true; else current = current->getNext(); } if (current != NULL && current != last) { if (current->getNext() != last) { current->getPrev()->setNext(current->getNext()); current->getNext()->setPrev(current->getPrev()); last->setNext(current); current->setPrev(last); last = last->getNext(); last->setNext(NULL); } else { current->getPrev()->setNext(last); last->setPrev(current->getPrev()); last->setNext(current); current->setPrev(last); last = last->getNext(); last->setNext(NULL); } } } } } void DoublyList::moveKeyToSecond(int key) { if (count == 0) { cerr << "List is empty.\n"; } else if (count != 1) { Node *current = first->getNext(); if (first->getData() == key) { if (current->getNext() == NULL) { first->setPrev(last); last->setNext(first); first = last; last = last->getNext(); first->setPrev(NULL); last->setNext(NULL); } else { first->setNext(current->getNext()); current->getNext()->setPrev(first); first->setPrev(current); current->setNext(first); first = current; first->setPrev(NULL); } } else { current = current->getNext(); bool found = false; while (current != NULL && !found) { if (current->getData() == key) found = true; else current = current->getNext(); } if (current != NULL) { if (current != last) { current->getPrev()->setNext(current->getNext()); current->getNext()->setPrev(current->getPrev()); current->setPrev(first); current->setNext(first->getNext()); first->getNext()->setPrev(current); first->setNext(current); } else { last = last->getPrev(); last->setNext(NULL); current->setPrev(first); current->setNext(first->getNext()); first->getNext()->setPrev(current); first->setNext(current); } } } } } void DoublyList::moveKeyToBeforeLast(int key) { if (count == 0) { cerr << "List is empty.\n"; } else if (count != 1) { Node *current = first->getNext(); if (first->getData() == key) { if (current->getNext() == NULL) { first->setPrev(last); last->setNext(first); first = last; last = last->getNext(); first->setPrev(NULL); last->setNext(NULL); } else { first->setPrev(last->getPrev()); first->setNext(last); last->getPrev()->setNext(first); last->setPrev(first); first = current; first->setPrev(NULL); } } else { bool found = false; while (current != NULL && !found) { if (current->getData() == key) found = true; else current = current->getNext(); } if (current != NULL && current != (last->getPrev())) { if (current != last) { current->getPrev()->setNext(current->getNext()); current->getNext()->setPrev(current->getPrev()); current->setPrev(last->getPrev()); current->setNext(last); last->getPrev()->setNext(current); last->setPrev(current); } else { if (count == 2) { first->setPrev(last); last->setNext(first); first = last; last = last->getNext(); first->setPrev(NULL); last->setNext(NULL); } else { last = last->getPrev(); last->setNext(NULL); current->setPrev(last->getPrev()); current->setNext(last); last->getPrev()->setNext(current); last->setPrev(current); } } } } } } void DoublyList::swapEnds() { if (count == 0) { cerr << "List is empty.\n"; } else if (count == 2) { first->setPrev(last); last->setNext(first); first = last; last = last->getNext(); first->setPrev(NULL); last->setNext(NULL); } else if (count > 3) { first->setPrev(last->getPrev()); last->setNext(first->getNext()); first = first->getPrev()->getNext(); last = last->getNext()->getPrev(); last->getNext()->setPrev(first); first->getPrev()->setNext(last); first->setPrev(NULL); last->setNext(NULL); } }
true
1d5a5c208fcd33509735301ef713e478121e0cce
C++
blacksea3/leetcode
/cpp/leetcode/748. shortest-completing-word.cpp
GB18030
970
3.1875
3
[]
no_license
#include "public.h" //24ms, 80.48% //תvectorͳƴƵ, ȻÿwordҲ class Solution { public: string shortestCompletingWord(string licensePlate, vector<string>& words) { vector<int> l(26, 0); for (auto& iil : licensePlate) { if (iil <= 'z' && iil >= 'a') l[iil - 'a']++; else if (iil <= 'Z' && iil >= 'A') l[iil - 'A']++; } string res; int minlen = 999; for (auto& word : words) { vector<int> temp(26, 0); for (auto& iiw : word) { temp[iiw - 'a']++; } bool isok = true; for (int i = 0; i < 26; ++i) { if (temp[i] < l[i]) { isok = false; break; } } if (isok) { if (minlen > word.size()) { res = word; minlen = word.size(); } } } return res; } }; /* int main() { Solution* s = new Solution(); vector<string> words = { "step","steps","stripe","stepple" }; auto res = s->shortestCompletingWord("1s3 PSt", words); return 0; } */
true
75991222d7ce8dfc26d5b459b948e41b835da668
C++
xueyeduling/CPP-Primer-note
/05section/05section/05section/5.22.cpp
GB18030
688
2.84375
3
[]
no_license
#include <iostream> #include <string> #include <vector> #include <cctype>//iostream #include <cstddef>//±size_tָptrdiff_t #include <iterator>//⺯beginend #include <cstring> #include <ctime> using std::cout; using std::cin; using std::endl; using std::string; using std::vector; using std::begin; using std::end; int get_size(); int main() { srand((unsigned int)time(NULL)); //begin: // int sz = get_size(); // if (sz <= 0) { // goto begin; // } int sz; while ((sz = get_size()) < 0) cout << sz << '\t'; cout << sz << endl; system("pause"); return 0; } int get_size() { return rand() % 5 == 0 ? 1 : -1;; }
true
3706ed9c51e97378c857318574f195f429585412
C++
wrz155/Algorithms
/other/1003 之字型打印矩阵.cpp
UTF-8
297
3.515625
4
[]
no_license
“之”字形打印矩阵 【题目】 给定一个矩阵matrix,按照“之”字形的方式打印这个矩阵,例如: 1 2 3 4 5 6 7 8 9 10 11 12 “之”字形打印的结果为:1,2,5,9,6,3,4,7,10,11,8,12 【要求】 额外空间复杂度为O(1)
true
afdce69c56b7627976302e94b891e48b4211777e
C++
chakradarraju/varindexer
/exp/grpc.cc
UTF-8
1,400
2.96875
3
[]
no_license
#include <iostream> #include "exp/test.pb.h" #include "exp/test.grpc.pb.h" #include "include/grpc++/grpc++.h" using grpc::Status; using grpc::Server; using grpc::ServerBuilder; using grpc::ServerContext; using std::cout; using std::endl; Test GetTest() { Test a; a.set_field1("chakra"); a.set_field2(2); return a; } class DummyImpl : public Dummy::Service { Status Trpc(ServerContext* context, const Test* request, Test* reply) { cout << "Running RPC" << endl; return {}; } }; void RunServer() { std::string server_address("0.0.0.0:50051"); DummyImpl service; ServerBuilder builder; // Listen on the given address without any authentication mechanism. builder.AddListeningPort(server_address, grpc::InsecureServerCredentials()); // Register "service" as the instance through which we'll communicate with // clients. In this case it corresponds to an *synchronous* service. builder.RegisterService(&service); // Finally assemble the server. std::unique_ptr<Server> server(builder.BuildAndStart()); std::cout << "Server listening on " << server_address << std::endl; // Wait for the server to shutdown. Note that some other thread must be // responsible for shutting down the server for this call to ever return. server->Wait(); } int main() { auto a = GetTest(); cout << a.field1() << " " << a.field2() << endl; RunServer(); return 0; }
true
7946d399c079077458d8e3a690920b322fb87bbf
C++
m-statkiewicz/EvolutionaryAlgorithmsInCudaOLD
/openMP_cpu/src/mipluslambdastrategy.h
UTF-8
379
2.53125
3
[]
no_license
/* * strategy.h */ #ifndef MIPLUSLAMBDASTRATEGY #define MIPLUSLAMBDASTRATEGY #include<cstdlib> #include<vector> #include"method.h" class MiPlusLambdaStrategy : public Method { private: int mi; int lambda; int iterations; public: MiPlusLambdaStrategy (int mi, int lambda, int iterations); Point operator () (const std::vector<Point*>& initialPoints) const; }; #endif
true
8dc267e323b4fe0d90ed268710a36dbdd4d6aaae
C++
DariuszOstolski/cppassert
/include/cppassert/AssertionFailure.hpp
UTF-8
5,276
3.203125
3
[ "BSD-3-Clause" ]
permissive
#pragma once #ifndef CPP_ASSERT_ASSERTIONFAILURE_HPP #define CPP_ASSERT_ASSERTIONFAILURE_HPP #include "details/AssertionMessage.hpp" #include <cstdint> namespace cppassert { /** * @class AssertionFailure * * A class for indicating an assertion failure. The AssertionFailure object * remembers a non-empty message that describes how it failed and * associated context information. */ class AssertionFailure { AssertionFailure(const AssertionFailure &) = delete; AssertionFailure operator=(const AssertionFailure &) = delete; public: /** * @brief Creates an assertion failure. * * Creates assertion failure object with all context information required. * Please note that AssertionFailure objects are streamable so library * client may stream some custom message * @code AssertionFailure failure; failure<<"Some message"; * @endcode * * @param[in] line Source file line where assertion failed * @param[in] file Source file name where assertion failed * @param[in] function Function name where assertion failed * @param[in] message Message associated with failed assertion * */ AssertionFailure(std::uint32_t line , const char *file , const char *function , std::string &&message); /** * Move constructor, have to be implemented by hand * because Visual C++ doesn't support generation of default ones * * @param other Object to be moved */ AssertionFailure(AssertionFailure &&other) { sourceFileLine_ = other.sourceFileLine_; sourceFileName_ = other.sourceFileName_; functionName_ = other.functionName_; message_ = std::move(other.message_); stackTrace_ = std::move(other.stackTrace_); other.sourceFileLine_ = 0; other.sourceFileName_ = nullptr; other.functionName_ = nullptr; } /** * Move assignment operator, have to be implemented by hand * because Visual C++ doesn't support generation of default ones * * @param other Object to be moved */ AssertionFailure &operator=(AssertionFailure &&other) { sourceFileLine_ = other.sourceFileLine_; sourceFileName_ = other.sourceFileName_; functionName_ = other.functionName_; message_ = std::move(other.message_); stackTrace_ = std::move(other.stackTrace_); other.sourceFileLine_ = 0; other.sourceFileName_ = nullptr; other.functionName_ = nullptr; return (*this); } /** * Std io manipulator type such as std::endl. */ using StdIoManipulatorType = AssertionMessage::StdIoManipulatorType; /** * @brief Interface for manipulators. * * Manipulators such as @c std::endl and @c std::hex use these * functions in constructs like "std::cout << std::endl". For more * information, see the iomanip header. */ AssertionFailure& operator<<(StdIoManipulatorType manipulator) { message_ << manipulator; return (*this); } /** * Streams value into assertion * @param[in] value Object that we want to have textual representation * in a message * @return Reference to this */ template <typename T> AssertionFailure& operator<<(const T& value) { message_ << value; return *this; } /** * Returns source file line associated with failed assertion * @return source file line */ std::uint32_t getSourceFileLine() const; /** * Returns source file name associated with failed assertion * @return source file name */ const char *getSourceFileName() const; /** * Returns function name associated with failed assertion * @return function name * @note Value returned depends on compiler and is not portable * some compilers may return mangled name */ const char *getFunctionName() const; /** * Returns stack trace associated with a failed assertion * @return Stack trace * @note Please note that stack trace may not be available in * some specific build configurations, especially when * `-fomit-frame-pointer` option is used in your build */ const std::string &getStackTrace() const; /** * Returns message associated with failed assertion * @return message associated with assertion */ std::string getMessage() const; /** * Returns assertion as string formatted by installed assertion message * formatter. Message format depends on CPP_ASSERT_*() macro used to * create assertion. By * @return assertion failure represented as string */ std::string toString() const; void onAssertionFailure(const AssertionMessage &message); private: std::uint32_t sourceFileLine_ = 0; const char *sourceFileName_ = nullptr; const char *functionName_ = nullptr; AssertionMessage message_; std::string stackTrace_; }; } //asrt #endif /* CPP_ASSERT_ASSERTIONFAILURE_HPP */
true
3f198dd075fdbfdc2b44803b20d89066849240bb
C++
cgddrd/Endurance-Race-Tracker
/Event-Creator/Course.cpp
UTF-8
1,554
3.421875
3
[]
no_license
/* * File: Course.cpp * Description: Provides a data model for an event course. * Author: Connor Luke Goddard (clg11) * Date: March 2013 * Copyright: Aberystwyth University, Aberystwyth */ #include "Course.h" using namespace std; /** * Constructor that allows the constant 'courseID' variable * to be specified. Also defaults the size of a course to 0. * @param theCourseID The new course ID value to be set. */ Course::Course(const char theCourseID) : courseID(theCourseID) { courseSize = 0; } /** * Destructor to be used once object is removed. */ Course::~Course() { } /** * Adds a new node to the end of the 'courseNode' vector. * @param newNode Pointer to the new node to be added to the vector. */ void Course::addCourseNode(Node *newNode) { this->courseNodes.push_back(newNode); this->setCourseSize(courseNodes.size()); } /** * Updates the total size of the course. (i.e. vector size). * @param courseSize The new size value. */ void Course::setCourseSize(int courseSize) { this->courseSize = courseSize; } /** * Fetches the value of 'courseSize'. * @return The total number of nodes in the course. */ int Course::getCourseSize(void) const { return courseSize; } /** * Fetches a vector of all the nodes in the course. * @return A vector of nodes that make up the course. */ std::vector<Node*> Course::getCourseNodes(void) const { return courseNodes; } /** * Fetches the ID of the course. * @return The ID of the course. */ const char Course::getCourseID(void) const { return courseID; }
true
8a0e97e2d60ed16423789c6294ced9099276957d
C++
hardiktechnoplanet/C-plus-plus-STL
/C_C++_Codes/47. Permutations II.cpp
UTF-8
1,477
3.8125
4
[]
no_license
//Given a collection of numbers that might contain duplicates, return all //possible unique permutations. #include<bits/stdc++.h> #include <iostream> using namespace std; void indent(int n) { for(int i=0;i<n;i++) cout<<"...."; } void permutationHelper(string s, string choosen, set<string>& alreadyPrinted) { indent(choosen.length()); cout<<"permutationHelper(\"" << s << "\",\"" << choosen << "\")" << endl; //Base case: if the string is empty, print the things we have choosen so far if(s.empty()) { if(alreadyPrinted.find(choosen)==alreadyPrinted.end()) { cout<<choosen<<endl; alreadyPrinted.insert(choosen); } } else { //choose, explore, unchoose /*pick one of the letter, explore what can come after, come back and unpick that letter and try the next letter and repeat.*/ for(int i=0;i<s.length();i++) { //choose char c=s[i]; //for exploration, we need to add this 'c' to choosen and remove it from 's'. choosen +=c; s.erase(i,1); //at index i remove 1 character //explore what can come after that permutationHelper(s,choosen,alreadyPrinted); //unchoose s.insert(i,1,c); choosen.erase(choosen.length()-1,1); //remove last character from choosen } } } void permutation(string s) { set<string> choosen; // to keep track of duplicates permutationHelper(s,"",choosen); } int main() { string s="112"; permutation(s); return 0; }
true
9a818f7d6ef6334d207b0b2ddefc93e314504985
C++
YKitty/CurrentmentMemory
/memPool/ThreadCache.hpp
GB18030
1,063
2.734375
3
[]
no_license
/* Ϊ˽̻߳ȡڴʱľ˲µ */ #pragma once #include "Common.hpp" #include "CentralCache.hpp" #include <iostream> #include <stdlib.h> class ThreadCache { public: //̷߳ڴ void* Allocate(size_t size); //ͷڴ void Deallocate(void* ptr, size_t size); //Ļȡڴ棬index±꣬sizeҪȡڴֽڴС void* FetchFromCentralCache(size_t index, size_t size); //еĶ̫ʱ򣬿ʼ void ListTooLong(FreeList* freelist, size_t byte); private: FreeList _freelist[NLISTS];//һ飬ΪNLISTS240 /*int _tid; ThreadCache* _next;*/ }; //̬tlsÿһThreadCacheԼһtls_threadcache //˶ÿһ̶߳Լthreadcache //_declspec(thread)൱ÿһ̶߳һ߳ static _declspec(thread) ThreadCache* tls_threadcache = nullptr;
true
7e93f1c7b4a9268a4500bea0620f2e6b659a1f41
C++
Vaphen/Stegano
/include/Stegano.h
UTF-8
2,344
3.09375
3
[]
no_license
#ifndef STEGANO_H #define STEGANO_H #include <string> #include <Magick++.h> #include <iostream> #include <random> #include <fstream> #include <set> #include "SteganoExceptions.h" #include "SteganoStructs.h" class Stegano { public: virtual ~Stegano(); void loadPicture(const std::string &); protected: Stegano(); // TODO: make steganoImage private and create Getter Magick::Image steganoImage; void pushPixelBy(Pixel &, const int &); bool isFinishPixel(const Pixel &); unsigned int getRandomNumber(const unsigned int &, const unsigned int &); void incrementPixel(Pixel &); virtual bool isPixelEmpty(const Pixel &) = 0; unsigned int getFileStreamSizeInBytes(std::ifstream &); virtual unsigned char getDoneStateInPercent() = 0; double xResolution; double yResolution; double pixelAmount; std::string usedPixels; /** \brief This mod function is needed because c++ standard mod operator (%) doesn't work properly in a mathematical way on negative numbers. * The result of mod(-6, 4) would be 2, mod(9, 3) = 0, mod(8, -3) = -1, ... * \param &x const int the value that should be taken modulo * \param &m const int the modulo value * \return inline int result of x mod m */ inline int mod(const int &x, const int &m) { return (x%m + m)%m; } /** \brief convert ImageMagick rgb values from default 16-bit (max. 65536) value to 8 bit value (max. 255) * * \param &rgb16Bit const unsignedint a rgb value in 16 bit * \return unsigned char a valid rgb value in range of 0 to 255 (including 0 and 255) */ inline unsigned char convert16BitTo8BitRGB(const unsigned int &rgb16Bit) { return rgb16Bit / 257; } /** \brief calculate quadratic sondation of a given index; it is always lower than maxSize. * Collisions are possible * \param &index const unsignedint the index that should be sondated * \param &maxSize const unsignedint the maximum size of the return-value * \return int the result of the quadratic sondation */ inline int_least64_t quadraticSondation(const unsigned int &index, const unsigned int &maxSize) { return (int_least64_t)std::pow(-1, index) * ((int_least64_t)std::pow(index, 2) % maxSize); } private: }; #endif // STEGANO_H
true
a6f3b940dfd4cde3978cb2d5aa25f61b01bb13c0
C++
msymkany/ft_retro
/UserShip.cpp
UTF-8
3,218
2.65625
3
[]
no_license
// // Created by Illia Lukianov on 11/4/17. // #include "UserShip.hpp" UserShip::UserShip() : FlyingEssence::FlyingEssence(7), _cout_missile(0) { newGamePos(); } UserShip::UserShip(const UserShip & u) { *this = u; } UserShip &UserShip::operator=(const UserShip & u) { _cout_missile = u._cout_missile; return *this; } UserShip::~UserShip() { } void UserShip::setXModulPosition(int x) { int i; i = 0; while (i < modulSize) { modulPosition[i].pos.x += x; i++; } } void UserShip::setYModulPosition(int y) { int i; i = 0; while (i < modulSize) { modulPosition[i].pos.y += y; i++; } } bool UserShip::hook(int in_char) { switch(in_char) { case 'q': return false; case KEY_UP: case 'w': setYModulPosition(-1); return true; case KEY_DOWN: case 's': setYModulPosition(1); return true;; case KEY_LEFT: case 'a': setXModulPosition(-1); return true;; case KEY_RIGHT: case 'd': setXModulPosition(1); return true;; case 32: shot(); default: return true;; } } void UserShip::operator==(cordScreen cord) { int i; i = 0; while (i < 7) { if (modulPosition[i].pos.x <= 0) { setXModulPosition(1); return; } else if (modulPosition[i].pos.x >= (cord.x - 1)) { setXModulPosition(-1); return; } else if (modulPosition[i].pos.y <= 4) { setYModulPosition(1); return; } else if (modulPosition[i].pos.y >= (cord.y - 1)) { setYModulPosition(-1); return; } i++; } } player *UserShip::getModulPosition() const { return modulPosition; } void UserShip::shot() { // missile = new Bullet; static clock_t mtime = 0; clock_t curr = clock(); if(curr - mtime > 2000) { mtime = curr; if (_cout_missile > 199) _cout_missile = 0; missile[_cout_missile].getModulPosition()->pos.x = getModulPosition()[3].pos.x + 1; missile[_cout_missile].getModulPosition()->pos.y = getModulPosition()[3].pos.y; missile[_cout_missile].set_stoper(1); _cout_missile++; } } Bullet *UserShip::getMissile() { return missile; } int UserShip::get_cout_missile() const { return _cout_missile; } bool UserShip::operator==(EnemyShip &e) const { for (int j = 0; j < 7; j++) { if (modulPosition[j].pos.x == e.getModulPosition()->pos.x && modulPosition[j].pos.y == e.getModulPosition()->pos.y) { mvprintw(0, 0, "%d", j); //test return true; } } return false; } void UserShip::newGamePos() { modulPosition[0].pos.x = 10; modulPosition[0].pos.y = 15; modulPosition[0].pos.disp_char = '/'; modulPosition[1].pos.x = 9; modulPosition[1].pos.y = 14; modulPosition[1].pos.disp_char = '='; modulPosition[2].pos.x = 10; modulPosition[2].pos.y = 13; modulPosition[2].pos.disp_char = '\\'; modulPosition[3].pos.x = 11; modulPosition[3].pos.y = 14; modulPosition[3].pos.disp_char = '>'; modulPosition[4].pos.x = 9; modulPosition[4].pos.y = 15; modulPosition[4].pos.disp_char = '/'; modulPosition[5].pos.x = 9; modulPosition[5].pos.y = 13; modulPosition[5].pos.disp_char = '\\'; modulPosition[6].pos.x = 10; modulPosition[6].pos.y = 14; modulPosition[6].pos.disp_char = '-'; }
true
f152fb7c02e53ca9a2b305c82d5682e37cbbfe09
C++
shdwp/openrunner
/app/view/widgets/StackWidget.cpp
UTF-8
2,530
2.546875
3
[]
no_license
// // Created by shdwp on 5/21/2020. // #include "StackWidget.h" void StackWidget::update() { auto scaled_bbox = glm::vec4( bounding_box.x, bounding_box.y, bounding_box.z, bounding_box.w ); auto amount = children_->size(); if (amount == 0) { return; } float scale = (*children_)[0]->scale.x; scale = 0.1f; float space; float initial_pos; float offline_pos; switch (orientation) { case StackWidgetOrientation_Horizontal: space = scaled_bbox.z - scaled_bbox.x; offline_pos = scaled_bbox.y + (scaled_bbox.w - scaled_bbox.y) / 2.f; break; case StackWidgetOrientation_Vertical: space = scaled_bbox.w - scaled_bbox.y; offline_pos = scaled_bbox.x + (scaled_bbox.z - scaled_bbox.x) / 2.f; break; } float offset = amount * scale * child_padding <= space ? scale * child_padding : (space / amount); switch (alignment) { case StackWidgetAlignment_Max: offset *= -1.f; switch (orientation) { case StackWidgetOrientation_Horizontal: initial_pos = scaled_bbox.z - (scale * child_padding) / 2.f; break; case StackWidgetOrientation_Vertical: initial_pos = scaled_bbox.y - (scale * child_padding) / 2.f; break; } break; case StackWidgetAlignment_Min: switch (orientation) { case StackWidgetOrientation_Horizontal: initial_pos = scaled_bbox.x + (scale * child_padding) / 2.f; break; case StackWidgetOrientation_Vertical: offset *= -1.f; initial_pos = scaled_bbox.w - (scale * child_padding) / 2.f; break; } break; } for (auto i = 0; i < amount; i++) { auto &child = (*children_)[i]; auto pos = child->position; switch (orientation) { case StackWidgetOrientation_Horizontal: pos = glm::vec3(initial_pos + offset * i, 0, offline_pos); break; case StackWidgetOrientation_Vertical: pos = glm::vec3(offline_pos, 0, initial_pos + offset * i); break; } child->position = pos; child->rotation = glm::qua(glm::vec3(0.f, child_rotation, 0.f)); } }
true
23852264b6434a83f0e4654bfc5c8336a334d186
C++
WHALEEYE/CS203-Lab-Assignments
/Lab07/C.cpp
UTF-8
1,498
2.671875
3
[]
no_license
#include <iostream> using namespace std; struct Node { int value; Node *next; Node *pre; }; Node *none = new Node{-1, NULL, NULL}; int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t, n, val, rear, k; Node *head, *tmp, *cur, **qu = new Node *[100010]; cin >> t; for (int i = 0; i < t; i++) { cin >> n; Node **tree = new Node *[n + 1]; for (int j = 0; j <= n; j++) { tree[j] = none; } tmp = new Node{-1, NULL, NULL}; tmp->next = tmp->pre = tmp; tree[0] = tmp; tmp = new Node{1, tree[0], tree[0]}; tree[0]->next = tmp; tree[0]->pre = tmp; for (int j = 1; j < n; j++) { cin >> val; if (tree[val] == none) { tmp = new Node{-1, NULL, NULL}; tmp->next = tmp->pre = tmp; tree[val] = tmp; } tmp = new Node{j + 1, tree[val], tree[val]->pre}; tree[val]->pre->next = tmp; tree[val]->pre = tmp; } rear = 2; k = 0; qu[0] = new Node{0, NULL, NULL}; qu[1] = tree[0]->next; while (k < rear) { if (tree[qu[k]->value] != none && qu[rear - 1]->next != tree[qu[k]->value]) { qu[rear] = qu[rear - 1]->next; rear++; } else if (k + 1 <= n && tree[qu[k + 1]->value] != none) { k++; qu[rear] = tree[qu[k]->value]->next; rear++; } else { k++; } } for (int j = 1; j < rear; j++) { cout << qu[j]->value << " "; } cout << "\n"; } return 0; }
true