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
7f3b646c3bba74434afb0a85e0ac24a44a9226fb
C++
jobtalle/File
/utils/stringUtils.h
UTF-8
337
2.703125
3
[ "MIT" ]
permissive
#pragma once #include <string> namespace Utils { class String final { public: static std::string ltrim(const std::string &string); static std::string rtrim(const std::string &string); static std::string trim(const std::string &string); protected: String() = default; private: static const std::string WHITESPACES; }; }
true
78146b5e83f9a31f42da423df6638e9c53399054
C++
prabhashrai02/practicing
/coockoff3.cpp
UTF-8
809
2.546875
3
[]
no_license
#include<iostream> #include<algorithm> #include<cmath> #include<climits> #include<string> #include<queue> #include<vector> #include<set> #include<map> #define lli long long int using namespace std; int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int test; cin>>test; while(test--){ int n, x; cin>>n>>x; int a[n]; for(int i=0; i<n; i++){ cin>>a[i]; } set<int> s; for(int i=0; i<n; i++){ s.insert(a[i]); } if(n - s.size() >= x){ cout<<s.size()<<endl; } else{ int temp = x- (n-s.size()); int ans= s.size()-temp; cout<<ans<<" \n"; } }; return 0; }
true
fc36f368727bca365db3443e5cf035b1ed0d0fd0
C++
cxFreeze/TP_Prog
/C++TP_2/liste.hh
UTF-8
8,898
3.609375
4
[]
no_license
/*OUBAH ROCHE TP2*/ #ifndef LISTE_HH_ #define LISTE_HH_ #include <iostream> #include <cassert> #include "cyclicNode.h" template <class T> class Liste { protected: typedef DataStructure::cyclicNode<T> Chainon; private: Chainon * sentinelle; int m_size; public: //Constructeur : initialise sentinelle Liste() : m_size(0) { sentinelle = new Chainon(); } private: /* * initialise une liste a partir d'une autre */ void copy(const Liste<T> & list) { m_size = 0; //sera incremente par push_back sentinelle = new Chainon(); Liste<T>::const_iterator it = list.begin(); while (it != list.end()) { this->push_back(*it); it++; } } public: // Constructeur copie Liste(const Liste<T> & list) { copy(list); } /* * surcharge de l'operateur = */ Liste<T> & operator = (const Liste<T> & list) { copy(list); return *this; } /* * surcharge de l'operateur + */ Liste<T> operator + (Liste<T> & list) { return add(*this, list); } /* * additionner deux listes */ Liste<T> add(Liste<T> & l1, Liste<T> & l2) { Liste<T> l3(l1); Liste<T>::iterator it = l2.begin(); while (it != l2.end()) { l3.push_back(*it); ++it; } return l3; } /* * renvoi true si vide */ bool empty() const { return m_size == 0; } /* * renvoi la taille de la liste */ int size() const { return m_size; } /* * renvoi le premier element * @pre Liste non vide */ T & front() { assert(!this->empty()); return sentinelle->next()->data(); } /* * renvoi le premier element * @pre Liste non vide */ const T & front() const { assert(!this->empty()); return sentinelle->next()->data(); } /* * renvoi le dernier element * @pre Liste non vide */ T & back() { assert(!this->empty()); return sentinelle->previous()->data(); } /* * renvoi le dernier element * @pre Liste non vide */ const T & back() const { assert(!this->empty()); return sentinelle->previous()->data(); } /* * ajouter l'element a la fin de la liste */ void push_back(const T & val) { Chainon * c = new Chainon(val); sentinelle->insertBefore(c); m_size++; } /* * ajouter l'element au debut de la liste */ void push_front(const T & val) { Chainon * c = new Chainon(val); sentinelle->insertAfter(c); m_size++; } /* * supprime le dernier element * @pre Liste non vide */ void pop_back() { assert(!this->empty()); Chainon * prev = sentinelle->previous(); sentinelle->previous()->detach(); delete(prev); m_size--; } /* * supprime le premier element * @pre Liste non vide */ void pop_front() { assert(!this->empty()); Chainon * prev = sentinelle->next(); sentinelle->next()->detach(); delete(prev); m_size--; } /* * Desctructeur */ virtual ~Liste() { while (sentinelle->next() != sentinelle) { pop_back(); } delete sentinelle; } /* --- Const_Iterator --- */ class const_iterator { private: friend class Liste; const Chainon * current; const Chainon * const sentinelle; public: /*Constructeur * si end = true : initialise sur la fin de la liste, au debut sinon. */ const_iterator(Chainon * senti, bool end) :sentinelle(senti) { if (end) { current = sentinelle; } else { current = sentinelle->next(); } } /* * surcharge post-incrementation */ const_iterator & operator ++() { assert(current != sentinelle); current = current->next(); return *this; } /* * surcharge pre-incrementation */ const_iterator & operator ++(int useless) { assert(current != sentinelle); current = current->next(); return *this; } /* * surcharge post-decrementation */ const_iterator & operator --() { assert(current != sentinelle->next()); current = current->previous(); return *this; } /* * surcharge pre-decrementation */ const_iterator & operator --(int useless) { assert(current != sentinelle->next()); current = current->previous(); return *this; } /* * Surcharge de l'operateur * pour acceder aux donnees stockees dans un chainon */ const T & operator * () const { assert(current != sentinelle); return current->data(); } /* * Surcharge de l'operateur -> pour acceder a l'adresse des donnees stockees dans un chainon */ const T * operator -> () const { assert(current != sentinelle); return &(current->data()); } /* * Surcharge de l'operateur == */ bool operator == (const const_iterator & it) const { return this->current == it.current; } /* * Surcharge de l'operateur != */ bool operator != (const const_iterator & it) const { return this->current != it.current; } //Destructeur ~const_iterator() {} }; /* --- Const_Iterator --- */ /* --- Iterator --- */ class iterator { private: friend class Liste; Chainon * current; Chainon * const sentinelle; public: /* Constructeur * si end = true : initie sur la fin de la liste, au debut sinon. */ iterator(Chainon * senti, bool end) :sentinelle(senti) { if (end) { current = sentinelle; } else { current = sentinelle->next(); } } /* * surcharge de l'operateur de post-incrementation */ iterator & operator ++() { assert(current != sentinelle); current = current->next(); return *this; } /* * surcharge de l'operateur de pre-incrementation */ iterator & operator ++(int useless) { assert(current != sentinelle); current = current->next(); return *this; } /* * surcharge de l'operateur de post-decrementation */ iterator & operator --() { assert(current != sentinelle->next()); current = current->previous(); return *this; } /* * surcharge de l'operateur de pre-decrementation */ iterator & operator --(int useless) { assert(current != sentinelle->next()); current = current->previous(); return *this; } /* * Surcharge de l'operateur * pour acceder aux donnees stockees dans un chainon */ T & operator * () { assert(current != sentinelle); return current->data(); } /* * Surcharge de l'operateur -> pour acceder a l'adresse des donnees stockees dans un chainon */ T * operator -> () { assert(current != sentinelle); return &(current->data()); } /* * surcharge de l'operateur == */ bool operator == (const iterator & it) const { return this->current == it.current; } /* * surcharge de l'operateur != */ bool operator != (const iterator & it) const { return this->current != it.current; } //Destructeur ~iterator() {} }; /* --- Iterateur --- */ public: /* * Renvoi un iterateur sur le premier element de la liste si non vide ou un iterateur sur la sentinelle */ const_iterator begin() const { const_iterator it(sentinelle, this->empty()); return it; } /* * Renvoi un iterateur sur le premier element de la liste si non vide ou un iterateur sur la sentinelle */ iterator begin() { iterator it(sentinelle, this->empty()); return it; } /* * Renvoi un iterateur sur le dernier element de la liste si non vide ou un iterateur sur la sentinelle */ const_iterator end() const { const_iterator it(sentinelle, true); return it; } /* * Renvoi un iterateur sur le dernier element de la liste si non vide ou un iterateur sur la sentinelle */ iterator end() { iterator it(sentinelle, true); return it; } /* * Insere val avant la postion de l'iterateur * si position = end() val est insere a la derniere position */ iterator insert(iterator position, const T & val) { Chainon * c = new Chainon(val); if (position == this->end()) { sentinelle->insertBefore(c); } else { Chainon * current = sentinelle->next(); /*while (current != sentinelle && current->data() != *position) { current = current->next(); }*/ current->insertBefore(c); } m_size++; return position--; } /* * supprime l'element a la position pointe par l'iterateur en parametre * @pre : iterator != end() */ iterator erase(iterator position) { assert(position != this->end()); Chainon * current = sentinelle->next(); /*while (current != sentinelle && current->data() != *position) { current = current->next(); }*/ iterator ret = position++; current->detach(); delete(current); m_size--; return ret; } }; template <class T> typename Liste<T>::iterator find(typename Liste<T>::iterator premier, typename Liste<T>::iterator dernier, const T & val) { typename Liste<T>::iterator find = premier; while (find != dernier && *find != val) { find++; } return find; } template <class T> std::ostream & operator << (std::ostream& out, Liste<T> & list) { display_list(list); return out; } template <class T> void display_list(const Liste<T> & list) { typename Liste<T>::const_iterator it = list.begin(); while (it != list.end()) { std::cout << "[" << *it << "] -> "; it++; } std::cout << std::endl; } #endif LISTE_HH_
true
5a04fdcb72220a6e606f03e1bf0c0bf5d825156f
C++
JoshLmao/5CS025-OctoSpork
/Octo-Spork/Octo-Spork/Room.h
UTF-8
1,787
3.578125
4
[]
no_license
#pragma once #include <string> #include <vector> #include "Item.h" #include "NPC.h" struct Room { public: std::string Name; Room(); Room(std::string name, std::string desc, std::vector<std::string> exits); Room(std::string name, std::string desc, std::vector<std::string> exits, std::vector<Item*> items); ~Room(); /* Gets an item inside this room, from its index. Returns a nullptr if out of bounds */ Item* GetItem(int index); /* Adds an item for this room*/ void AddItem(Item* item); /* Removes an item from this room */ Item* RemoveItem(std::string itmName); /* Does the Items in this room contain this item */ bool ItemsContains(std::string name); /* Returns the amount of items inside this room */ int GetItemsSize(); /* Gets an exit from it's index. Returns empty std::string if index is out of bounds */ std::string GetExit(int index); /* Gets the amount of exits set for the room */ int GetExitsSize(); /* Adds an exit to the room */ void AddExit(std::string exitName); /* Sets the NPC for this room, limited to only one*/ void AddNPC(NPC* npc); /* Gets an NPC by their index. Returns a nullptr if out of bounds */ NPC* GetNPC(int index); /* Gets an NPC from it's name. Returns a nullptr if not found */ NPC* GetNPC(std::string npcName); /* Gets the amount of NPCs inside this room */ int GetNPCSize(); /*Gets the print out room description for the room*/ std::string GetDescription(); /* Sets the description of the room */ void SetDescription(std::string desc); private: /* Standard description of this room */ std::string m_description; /* All exits available in this room */ std::vector<std::string> m_exits; /* Items inside the room */ std::vector<Item*> m_items; /* All NPCs inside this room */ std::vector<NPC*> m_npcs; };
true
aefa58ea5d353eacd9fe0bf528e3970f1c90a44e
C++
sahcaks/C_PLusPLus
/2Лабораторная 20/Лабораторная 20.3/Лабораторная 20.3/Лабораторная 20.3.cpp
UTF-8
3,993
3.203125
3
[]
no_license
#include <iostream> using namespace std; void input(int size); void output(); void finds(char lastName[]); void findh(int h, int m); typedef struct Train { char city[16]; char num[16]; int dateh; int datem; } STUD; int number, adateh = 0, adatem = 0; FILE *f; errno_t err; int main() { system("color 02"); setlocale(LC_ALL, "Russian"); int choice; char city[16]; do { cout << "\n1. Ввод данных с клавиатуры и запись в файл\n"; cout << "2. Вывод данных из файла\n"; cout << "3. Поиск по пункту назначения\n"; cout << "4. Поиск позже определенного времени отправления\n"; cout << "0. Выход из программы\n\n"; cout << "Введите номер операции: "; cin >> choice; switch (choice) { case 1: cout << "Введите количество рейсов, информацию о которых вы хотите ввести: "; cin >> number; input(number); cout << endl; break; case 2: output(); break; case 3: { cout << "Введите пункт назначения: "; cin >> city; finds(city); break; } case 4: { cout << "Введите время отправления (часы, 0-23)"; cin >> adateh; cout << "Введите время отправления (минуты, 0-59)"; cin >> adatem; findh(adateh, adatem); break; } case 0: exit(0); break; } } while (choice != 0); } void input(int size) { STUD buf = { ' ', ' ' }; if (!fopen_s(&f, "C:\\Users\\Vasilisa\\Desktop\\lab203.txt", "ab")) { for (int p = 0; p < size; p++) { cout << "Пункт назначения: "; cin >> buf.city; cout << "Номер рейса: "; cin >> buf.num; cout << "Время отправления (часы): "; cin >> buf.dateh; cout << "Время отправления (минуты): "; cin >> buf.datem; cout << endl; fwrite(&buf, sizeof(buf), 1, f); } fclose(f); } else { cout << "Ошибка открытия файла"; return; } } void output() { STUD buf; if (!fopen_s(&f, "C:\\Users\\Vasilisa\\Desktop\\lab203.txt", "rb")) { cout << "\nПункт назначения Номер рейса Время отправления\n"; fread(&buf, sizeof(buf), 1, f); while (!feof(f)) { cout << buf.city << "\t \t \t " << buf.num << "\t \t " << buf.dateh << ":" << buf.datem << endl; fread(&buf, sizeof(buf), 1, f); } cout << endl; fclose(f); } else { cout << "Ошибка открытия файла"; return; } } void finds(char lastName[16]) { bool flag = false; STUD buf; if (!fopen_s(&f, "C:\\Users\\Vasilisa\\Desktop\\lab203.txt", "rb")) { while (!feof(f)) { fread(&buf, sizeof(buf), 1, f); if (strcmp(lastName, buf.city) == 0) { cout << "\nПункт назначения Номер рейса Время отправления\n"; cout << buf.city << "\t \t \t " << buf.num << "\t \t " << buf.dateh << ":" << buf.datem << endl; flag = true; break; } } fclose(f); if (!flag) cout << "Ничего не найдено\n"; } else { cout << "Ошибка открытия файла"; return; } } void findh(int h, int m) //функция, которая находит времечко { bool flag = false; STUD buf; if (!fopen_s(&f, "C:\\Users\\Vasilisa\\Desktop\\lab203.txt", "rb")) { while (!feof(f)) { fread(&buf, sizeof(buf), 1, f); if ((buf.dateh > h) || (h == buf.dateh && buf.datem > m)) { cout << "\nПункт назначения Номер рейса Время отправления\n"; cout << buf.city << "\t \t \t " << buf.num << "\t \t " << buf.dateh << ":" << buf.datem << endl; flag = true; break; } } fclose(f); if (!flag) cout << "Ничего не найдено\n"; } else { cout << "Ошибка открытия файла"; return; } }
true
157d39af7de19ec415e337c760c8569de6086e73
C++
StephenGuanqi/leetcode
/cpp/stack&string/CheckWordAbbreviation.cpp
UTF-8
903
3.21875
3
[]
no_license
// // Created by Guanqi Yu on 1/10/18. // #include <iostream> #include <algorithm> #include <queue> #include <vector> #include <cmath> #include <string> using namespace std; class Solution { public: /* * @param word: a non-empty string * @param abbr: an abbreviation * @return: true if string matches with the given abbr or false */ bool validWordAbbreviation(string word, string abbr) { int i = 0, j = 0; while (i < word.size() && j < abbr.size()) { if (isdigit(abbr[j])) { if (abbr[j] == '0') return false; int num = 0; while (j < abbr.size() && isdigit(abbr[j])) num = 10 * num + abbr[j++] - '0'; i += num; } else if (word[i++] != abbr[j++]) return false; } return i == word.size() && j == abbr.size(); } }; //int main() { // string word = "internationalization"; // string abbrev = "i12iz4n"; // Solution().validWordAbbreviation(word, abbrev); //}
true
87f619a540abc1b1a3252627b53cf6c316b5bfd4
C++
akhilchoudhary2k/Solutions-CSES-Problem-Set
/traffic_lights.cpp
UTF-8
1,471
3.125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; set<int> position; // will save the positions of lights added till now map<int,int> heap; // will save the max length till now int getmax(){ if(heap.empty()) return 0; auto it = heap.rbegin(); return it->first; } int main(){ int x,n; cin >> x >> n; position.insert(0); position.insert(x); heap[x]++; for(int i=0;i<n;i++){ // left means the nearest light towards left fo current added light simillarly right int left, right, num; cin >> num; auto it2 = position.lower_bound(num); if(it2 == position.begin()) left = num; else { it2--; left = *it2; } auto it3 = position.upper_bound(num); if(it3 == position.end()) right = num; else{ right = *it3; } position.insert(num); int curmax = getmax(); int a = num - left; int b = right - num; int larger = max(a,b); int curlen = right - left; // cout << "i=" << i << " left=" << left << " right=" << right << endl; // cout <<"maxheap:" ; // for(auto x : heap) cout << "(" << x.first << "," << x.second << ") "; cout << endl; // cout << "curlen=" << curlen << " curmax=" << curmax << endl; if(curlen == curmax){ heap[curmax]--; if(heap[curmax] == 0) heap.erase(curmax); int newcurmax = getmax(); cout << max( larger , newcurmax ) << " "; } else{ cout << curmax << " "; heap[curlen]--; if(heap[curlen] == 0) heap.erase(curlen); } heap[a]++; heap[b]++; } return 0; }
true
e66673028f329b65c92886399c81953316b240e0
C++
Kertic/classes-backup
/Data structures labs/Project2_BrennanRodriguez/Project2_BrennanRodriguez/Inventory.h
UTF-8
1,393
3.40625
3
[]
no_license
#pragma once #include "SLList.h" #include <iostream> #include "Item.h" using namespace std; class Player { private: SLList<Item> inventory; unsigned int gold, weight, maxWeight; public: Player() { gold = 5000; weight = 0; maxWeight = 50; } unsigned int getGold() { return gold; } void setGold(int inGold) { if (inGold >= 0) { gold = inGold; } else { gold = 0; } } unsigned int getWeight() { return weight; } void setWeight(int inWeight) { if (inWeight >= 0) { weight = inWeight; } else { weight = 0; } } unsigned int getMaxWeight() { return maxWeight; } void AddItem(Item inItem) { inventory.addHead(inItem); } bool RemoveItem(Item inItem) {//returns if it removed successfully or not bool found = false; SLLIter<Item> iter(inventory); for (unsigned int i = 0; i < inventory.size() && found == false; i++) { if (iter.current().name == inItem.name) { inventory.remove(iter); found = true; } } return found; } void DisplayInventory() { SLLIter<Item> iter(inventory); cout << "Name\t\tType\t\t\tWeight\tCost\n"; for (unsigned int i = 0; i < inventory.size(); i++) { cout << iter.current().name << "\t"; cout << iter.current().type << "\t"; cout << iter.current().weight << "\t"; cout << iter.current().cost << "\t"; cout << "\n"; ++iter; } } };
true
06fd1ed74de658f78521734f1afd6240cbf17e5d
C++
DimitarKolevSI/University
/OOP_Shop_19-20_fn62295_g4_d1/Store.h
UTF-8
548
2.90625
3
[]
no_license
#pragma once class Store { private: char* Name = nullptr; void setName(const char* Name); //Variables to be added: //List of users, //List of products public: Store(); Store(const char* Name); Store(const Store& copyStore); Store& operator=(const Store& copyStore); const char* getName() const; //Functions to be added //addUser //removeUser //printInvertory //displayByCategory //sortByPrice //addProduct //removeProduct //addAmountToAProduct //sortByRating //Discount on everything //Discount by category ~Store(); };
true
55d3c74384ed230853f067831e3828eca4cd6a53
C++
JaechanAn/algorithm-study
/Jinaria/three problem per day/2020.1/2020.1.6/10942.cpp
UTF-8
1,868
2.65625
3
[]
no_license
#include <cstdio> #include <vector> #include <algorithm> #include <utility> #include <cstring> using namespace std; typedef pair<int, int> P; // d[가운데위치][길이] int d[2001][2001]; int main() { int N; scanf("%d", &N); vector<int> numbers(N + 1); for (int i = 1; i <= N; ++i) scanf("%d", &numbers[i]); int M; scanf("%d", &M); vector<P> question(M + 1); for (int i = 1; i <= M; ++i) scanf("%d %d", &question[i].first, &question[i].second); for (int i = 0; i <= N; ++i) memset(d[i], -1, N + 1); for (int i = 1; i <= N; ++i) d[i][1] = 1; for (int i = 1; i <= N - 1; ++i) if (numbers[i] == numbers[i + 1]) d[i][2] = 1; else d[i][2] = 0; for (int len = 3; len <= N; ++len) { int wing = len / 2; if (len & 1) { for (int idx = 1 + wing; idx <= N - wing; ++idx) { if (d[idx][len - 2]) { if (numbers[idx - wing] == numbers[idx + wing]) d[idx][len] = 1; else d[idx][len] = 0; } else { d[idx][len] = 0; } } } else { for (int idx = 1 + wing - 1; idx <= N - wing; ++idx) { if (d[idx][len - 2]) { if (numbers[idx - wing + 1] == numbers[idx + wing]) d[idx][len] = 1; else d[idx][len] = 0; } else { d[idx][len] = 0; } } } } auto iter = question.begin(); for (iter++; iter != question.end(); ++iter) { printf("%d\n", d[(iter->first + iter->second) / 2][iter->second - iter->first + 1]); } }
true
4cd11f40866709bb51f76f0e0379f2e24e8218df
C++
007kevin/Accelerated_CPP
/Chapter04/4-2.cpp
UTF-8
932
3.796875
4
[]
no_license
/* Exercise 4-2 * Write a program to calculate the squares of int values up to * 100. The program should write two columns: The first lists the value; the * second contains the square of the value. Use setw to manage the output so * that the values line up in columns */ #include <iostream> #include <ios> #include <iomanip> #include <string> #define LIMIT 100 using std::setw; using std::string; using std::streamsize; using std::to_string; using std::cout; using std::endl; int main(){ // First get the size of the largest digit for proper padding string::size_type size = std::to_string(LIMIT*LIMIT).size(); for (int i = 1; i <= LIMIT; i++){ cout << setw(3) << i << setw(size + 1) << i*i << cout.width(0) // reset field width value << endl; } return 0; } /* Note: had to compile with 'g++ -std=c++11' in order to use the std::to_string function */
true
725c01b7aeedf9a97ee679f3fb6a35c9619a1547
C++
IsaacDG/Interpreter
/Test.cpp
UTF-8
478
3.34375
3
[]
no_license
#include <iostream> #include <iomanip> int main(int arc, char** argv){ int size = 0; // std::cout << "Enter a size for the array: "; // std::cin >> size; int array[4] = {0}; std::cout << "&array = " << &array << std::endl; int* ptr = array; std::cout << "&array++ = " << ++ptr << std::endl; // for(int i = 0; i < size; i++){ // array[i] = i; // } // for(int i = 0; i < size; i++){ // std::cout << array[i] << std::endl; // } // delete [] array; return 0; }
true
8e5bcbe23390ea47cffa0b1003595ff90a4dee45
C++
yucelalbar/cpp-kursu-kodlar
/sorted_range_algorithms/lower_bound_02.cpp
UTF-8
763
3.484375
3
[]
no_license
#include <vector> #include <algorithm> #include <iterator> #include <iostream> int main() { using namespace std; vector<int> ivec{ 2, 5, 5, 7, 9, 9, 9, 9, 12, 12, 16, 35 }; copy(begin(ivec), end(ivec), ostream_iterator<int>(cout, " ")); int ival; cout << "\nbir deger girin: "; cin >> ival; auto iter_lower = lower_bound(ivec.begin(), ivec.end(), ival); auto iter_upper = upper_bound(ivec.begin(), ivec.end(), ival); std::cout << "distance for lower bound : " << distance(ivec.begin(), iter_lower) << "\n"; std::cout << "distance for upper bound : " << distance(ivec.begin(), iter_upper) << "\n"; cout << "distance for equal range " << distance(iter_lower, iter_upper) << "\n"; copy(iter_lower, iter_upper, ostream_iterator<int>(cout, " ")); }
true
57f37c3fd79b34b68af011fb1a7ccada52100c1d
C++
icyflame/rsa-implementation
/rsa.cpp
UTF-8
20,989
2.65625
3
[]
no_license
#include <iostream> #include <fstream> #include <cstdlib> #include <ctime> #include <stdio.h> #include <libgen.h> #include <sys/stat.h> #include <string.h> #include "gmp/gmp.h" #define OPTION_HELP_1 "--help" #define OPTION_HELP_2 "help" #define OPTION_GENERATE_1 "generate" #define OPTION_GENERATE_2 "keygen" #define OPTION_ENCRYPT "encrypt" #define OPTION_DECRYPT "decrypt" #define OPTION_CONVERT_INT_TO_STRING "int2string" #define OPTION_CONVERT_STRING_TO_INT "string2int" #define ARGS_BITLENGTH "-b" #define ARGS_FILENAME "-f" #define ARGS_KEY "-k" #define FILENAME_TEMP_P "temp_p" #define FILENAME_TEMP_Q "temp_q" #define FILENAME_CIPHERTEXT "ciphertext" #define FILENAME_ENCRYPTED_FILE_SUFFIX ".encrypted" #define FILENAME_PRIVATE_KEY "rsa.private" #define FILENAME_PUBLIC_KEY "rsa.public" #define MIN_PUBLIC_EXPONENT 65537 #define DEFAULT_PRIME_LENGTH 64 #define DEFAULT_FILENAME "rsa" #define INFO 1 #define TIMESTAMP 1 #define DEBUG 1 #define VERBOSE 0 #define log_debug if (DEBUG) printf("\n"); gmp_printf #define log_info if (INFO) printf("\n"); printf #define log_verbose if (VERBOSE) printf("\n"); gmp_printf ///////////////////////////////////////////// // HELPER FUNCTIONS //////////////////////////////////////////// void log_timestamp(const char * label) { if (!TIMESTAMP) return; time_t rawtime; struct tm * timeinfo; time (&rawtime); timeinfo = localtime (&rawtime); printf ("\n%s: %s", label, asctime(timeinfo)); } inline bool file_exists (const std::string& name) { struct stat buffer; return (stat (name.c_str(), &buffer) == 0); } using namespace std; /** * Writes a randomly generated bit_length length binary number * to the filename */ void write_random_to_file(const char * filename, int bit_length) { ofstream fout; fout.open(filename, ios::out); fout << 1; for(int i = 1; i < bit_length; ++i) { fout << (rand() % 2); } fout.close(); } /** * Store the values of p, q, Dp, Dq and q_inv (mod p) in the private key * file. * Resource: * https://en.wikipedia.org/wiki/RSA_(cryptosystem)#Using_the_Chinese_remainder_algorithm * RFC 3447 - Section 3.2 - 2nd representation */ void write_private_key_to_file(mpz_t &p, mpz_t &q, mpz_t &private_exponent, const char * filename) { FILE * stream; char * priv_key_filename = new char[strlen(filename)]; strcpy(priv_key_filename, filename); strcat(priv_key_filename, ".private"); stream = fopen(priv_key_filename, "w"); gmp_fprintf(stream, "%Zx\n%Zx\n", p, q); mpz_t temp; mpz_init(temp); mpz_sub_ui(temp, p, 1); mpz_mod(temp, private_exponent, temp); gmp_fprintf(stream, "%Zx\n", temp); mpz_sub_ui(temp, q, 1); mpz_mod(temp, private_exponent, temp); gmp_fprintf(stream, "%Zx\n", temp); mpz_invert(temp, q, p); gmp_fprintf(stream, "%Zx\n", temp); fclose(stream); free(priv_key_filename); mpz_clear(temp); } /** * Get the stored private key parameters from the private key file */ void read_private_key_from_file(const char * filename, mpz_t &p, mpz_t &q, mpz_t &dp, mpz_t &dq, mpz_t &q_inv) { FILE * stream; stream = fopen(filename, "r"); gmp_fscanf(stream, "%Zx", p); gmp_fscanf(stream, "%Zx", q); gmp_fscanf(stream, "%Zx", dp); gmp_fscanf(stream, "%Zx", dq); gmp_fscanf(stream, "%Zx", q_inv); fclose(stream); } void write_public_key_to_file(mpz_t modulus, long unsigned int public_exponent, const char * filename) { FILE * stream; char * pub_key_filename = new char[strlen(filename)]; strcpy(pub_key_filename, filename); strcat(pub_key_filename, ".public"); stream = fopen(pub_key_filename, "w"); gmp_fprintf(stream, "%Zx\n%x", modulus, public_exponent); free(pub_key_filename); fclose(stream); } void read_public_key_from_file(const char * filename, mpz_t &modulus, mpz_t &public_exponent) { FILE * stream; stream = fopen(filename, "r"); gmp_fscanf(stream, "%Zx", modulus); gmp_fscanf(stream, "%Zx", public_exponent); fclose(stream); } void generate_key_pair(int PRIMES_BIT_LENGTH, const char * filename) { mpz_t temp_1, prime_p, prime_q, totient, private_exponent; // Generate random P and Q values // log_timestamp("START Generation random numbers"); write_random_to_file(FILENAME_TEMP_P, PRIMES_BIT_LENGTH); write_random_to_file(FILENAME_TEMP_Q, PRIMES_BIT_LENGTH); log_timestamp("END Generation of random numbers"); mpz_init(prime_p); mpz_init(prime_q); mpz_init(temp_1); // Read the random temp values from the file // Find the next smallest prime P and Q log_timestamp("START Find next prime of random numbers"); FILE * stream; stream = fopen(FILENAME_TEMP_P, "r"); mpz_inp_str(temp_1, stream, 2); fclose(stream); mpz_nextprime(prime_p, temp_1); stream = fopen(FILENAME_TEMP_Q, "r"); mpz_inp_str(temp_1, stream, 2); fclose(stream); mpz_nextprime(prime_q, temp_1); while (mpz_cmp(prime_p, prime_q) == 0) { mpz_nextprime(prime_q, prime_q); } log_timestamp("END Find next prime of random numbers"); // TODO: Find a safe prime // A safe prime is one which is equal to 2*p + 1 where p is also a prime // number. // Calculate the totient mpz_init(totient); mpz_set_ui(totient, 1); mpz_sub_ui(temp_1, prime_p, 1); mpz_mul(totient, totient, temp_1); mpz_sub_ui(temp_1, prime_q, 1); mpz_mul(totient, totient, temp_1); // Find public exponent that has gcd 1 with totient log_timestamp("START Find a public exponent"); unsigned long int public_exponent = MIN_PUBLIC_EXPONENT; while (mpz_gcd_ui(NULL, totient, public_exponent) != 1 && public_exponent > 0) { public_exponent ++; } log_timestamp("END Find a public exponent"); log_verbose("Public exponent: %lu\n", public_exponent); // Calculate the private exponent log_timestamp("START Find the private exponent (invert public exponent)"); mpz_init(private_exponent); mpz_set_ui(temp_1, public_exponent); mpz_invert(private_exponent, temp_1, totient); log_timestamp("END Find the private exponent (invert public exponent)"); log_verbose("Private exponent: %Zd", private_exponent); // Calculate the modulus, to put inside the public key file mpz_mul(temp_1, prime_p, prime_q); log_timestamp("START Write pub key to file"); write_public_key_to_file(temp_1, public_exponent, filename); log_timestamp("END Write pub key to file"); log_timestamp("START Write private key to file"); write_private_key_to_file(prime_p, prime_q, private_exponent, filename); log_timestamp("END Write private key to file"); mpz_clear(private_exponent); mpz_clear(totient); mpz_clear(prime_p); mpz_clear(prime_q); mpz_clear(temp_1); } void encrypt_integer_rsa(mpz_t &plaintext, const char * pubkey_filepath, const char * ciphertext_filepath, const char * file_open_mode) { mpz_t modulus, public_exponent, temp1; mpz_init(modulus); mpz_init(public_exponent); mpz_init(temp1); read_public_key_from_file(pubkey_filepath, modulus, public_exponent); log_verbose("Writing encrypted content to %s", ciphertext_filepath); log_verbose("Modulus: %Zd\n", modulus); log_verbose("Public exponent: %Zd", public_exponent); // REMEMBER: Encrypted number should ALWAYS be less than the modulus! FILE * stream = fopen(ciphertext_filepath, file_open_mode); log_verbose("Ciphertext: %Zd", modulus); do { mpz_fdiv_qr(plaintext, temp1, plaintext, modulus); log_debug("PT Chunk: %Zd", temp1); // Re-using the same variable to store the ciphertext instead of using a new // variable mpz_powm(temp1, temp1, public_exponent, modulus); log_debug("CT Chunk: %Zd", temp1); gmp_fprintf(stream, "%Zx\n", temp1); } while (mpz_cmp_ui(plaintext, 0) > 0); fclose(stream); mpz_clear(temp1); mpz_clear(modulus); mpz_clear(public_exponent); mpz_clear(plaintext); } void encrypt_integer_rsa(mpz_t &plaintext, const char * pubkey_filepath, const char * ciphertext_filepath) { encrypt_integer_rsa(plaintext, pubkey_filepath, ciphertext_filepath, "w"); } void decrypt_integer_rsa(const char * ciphertext_filepath, const char * private_key_filepath, mpz_t &plaintext, unsigned long int &octet_len) { mpz_t p, q, dp, dq, q_inv; mpz_init(p); mpz_init(q); mpz_init(dp); mpz_init(dq); mpz_init(q_inv); // Read the private key from the file read_private_key_from_file(private_key_filepath, p, q, dp, dq, q_inv); log_verbose("P: %Zd\nQ: %Zd\ndp: %Zd\ndq: %Zd\nQ_inv: %Zd", p, q, dp, dq, q_inv); mpz_t modulus; mpz_init(modulus); mpz_mul(modulus, p, q); mpz_t temp_1, temp_2, intermediary_pt; mpz_init(temp_1); mpz_init(temp_2); mpz_init(intermediary_pt); // Read the ciphertext's integer representation mpz_t ciphertext_integer_rep; mpz_init(ciphertext_integer_rep); FILE * stream = fopen(ciphertext_filepath, "r"); gmp_fscanf(stream, "%x", &octet_len); log_verbose("Octet length: %d", octet_len); mpz_set_ui(plaintext, 0); unsigned long int i = 0; while(1 == gmp_fscanf(stream, "%Zx", ciphertext_integer_rep)) { log_debug("CT chunk %d: %Zd", i, ciphertext_integer_rep); // Start the decryption process // As per RSADP: 5.1.2 on RFC 3447 log_timestamp("START Decryption of chunk according to RFC"); mpz_powm(temp_1, ciphertext_integer_rep, dp, p); mpz_powm(temp_2, ciphertext_integer_rep, dq, q); mpz_sub(temp_1, temp_1, temp_2); mpz_mul(temp_1, temp_1, q_inv); mpz_mod(temp_1, temp_1, p); // Now, temp_1 consists h mpz_mul(temp_1, temp_1, q); mpz_add(intermediary_pt, temp_2, temp_1); mpz_mod(intermediary_pt, intermediary_pt, modulus); log_debug("PT Chunk: %Zd", intermediary_pt); if (i == 0) { mpz_add(plaintext, plaintext, intermediary_pt); } else { mpz_pow_ui(temp_1, modulus, i); mpz_mul(temp_1, temp_1, intermediary_pt); mpz_add(plaintext, plaintext, temp_1); } ++i; } fclose(stream); log_verbose("That CT decrypts to: %Zd\n", plaintext); log_timestamp("END Decryption according to RFC"); mpz_clear(p); mpz_clear(q); mpz_clear(dp); mpz_clear(dq); mpz_clear(q_inv); mpz_clear(ciphertext_integer_rep); mpz_clear(temp_1); mpz_clear(temp_2); mpz_clear(intermediary_pt); } void printHelp() { printf("\n----------------------------------"); printf("\nRSA Implementation - Using GNU GMP\n\n"); printf("\nrsa keygen -b 512 -f filename"); printf("\nrsa generate -b 512 -f filename"); printf("\nrsa encrypt -f filename -key siddharth.pub"); printf("\nrsa decrypt -f ciphertext -key my.private.key"); printf("\nTESTING OPTIONS"); printf("\nrsa int2string 7881696744884301945 8"); printf("\nrsa convert string2int \"main2.py\""); printf("\n----------------------------------"); } void convert_string_to_integer(const char * plaintext, mpz_t &string_representation, mpz_t &octet_len) { // Find the string size unsigned long int lSize = strlen(plaintext); mpz_set_ui(octet_len, lSize); mpz_set_ui(string_representation, 0); mpz_t temp; mpz_init(temp); for(int i = 0; i < lSize; ++i) { char this_char = plaintext[i]; mpz_ui_pow_ui(temp, 256, lSize - i - 1); mpz_mul_ui(temp, temp, this_char); mpz_add(string_representation, string_representation, temp); } // log_verbose("\nInteger repesentation of %s is: %Zd\nwith octet length of %Zd", plaintext, string_representation, octet_len); mpz_clear(temp); } void convert_file_to_integer(const char * filepath, mpz_t &file_representation, mpz_t &octet_len) { if (!file_exists(string(filepath))) { return; } FILE * stream = fopen(filepath, "rb"); char * values; // Find the file size fseek (stream, 0, SEEK_END); unsigned long int lSize = ftell (stream); rewind (stream); values = new char[lSize * sizeof(char)]; size_t result = fread(values, 1, lSize, stream); if (result != lSize) { printf("ERROR! File couldn't be converted to it's integer representation."); return; } mpz_set_ui(file_representation, 0); mpz_set_ui(octet_len, lSize); mpz_t temp; mpz_init(temp); for(int i = 0; i < lSize; ++i) { char this_char = values[i]; mpz_ui_pow_ui(temp, 256, lSize - i - 1); mpz_mul_ui(temp, temp, this_char); mpz_add(file_representation, file_representation, temp); } // log_verbose("\nInteger repesentation of that file is: %Zd\nwith octet length of %Zd", file_representation, octet_len); mpz_clear(temp); fclose(stream); } char * convert_integer_to_string(mpz_t &int_rep, unsigned long int octet_len) { char * string_rep = new char[(octet_len+1) * sizeof(char)]; log_timestamp("START Converting the given integer to it's octet string representation"); mpz_t divisor, remainder; mpz_init(divisor); mpz_init(remainder); mpz_set(divisor, int_rep); mpz_t OCTET_BASE; mpz_init(OCTET_BASE); mpz_set_ui(OCTET_BASE, 256); string_rep[octet_len] = '\0'; --octet_len; while(mpz_cmp_ui(int_rep, 0) > 0 && octet_len >= 0) { string_rep[octet_len--] = (char) mpz_fdiv_qr_ui(int_rep, remainder, int_rep, 256); // log_verbose("Integer representation of this character: %u, %c; Remainder: %Zd", string_rep[octet_len+1], string_rep[octet_len+1], remainder); } log_verbose("Integer rep now: %Zd", int_rep); log_verbose("Octet length now: %d", octet_len); log_verbose("\nGiven integer represents the string %s", string_rep); mpz_clear(divisor); mpz_clear(remainder); return string_rep; } char * convert_integer_to_string(unsigned long int int_rep, unsigned long int octet_len) { mpz_t int_rep_gmp; mpz_init(int_rep_gmp); mpz_set_ui(int_rep_gmp, int_rep); char * result = convert_integer_to_string(int_rep_gmp, octet_len); mpz_clear(int_rep_gmp); return result; } void convert_integer_to_file(mpz_t &int_rep, unsigned long int octet_len, const char * output_filename) { FILE * stream = fopen(output_filename, "w"); char * string_rep = convert_integer_to_string(int_rep, octet_len); fprintf(stream, "%s", string_rep); free(string_rep); fclose(stream); } //void convert_integer_to_file(mpz_t &file_representation, mpz_t &filename_representation) { //} // void encrypt_message(mpz_t message, mpz_t modulus, mpz_t public_exponent); // void decrypt_message(mpz_t ciphertext, mpz_t modulus, mpz_t // private_exponent); int main(int argc, char **ARGV) { // INIT int LENGTH_PRIMES_BITS; srand(time(NULL)); // DECIDE BIT LENGTH OF THE PRIMES LENGTH_PRIMES_BITS = DEFAULT_PRIME_LENGTH; // Command line argument parsing int matched = 0; if (argc == 1) { printf("ERROR! You must use one of the available options."); printHelp(); return 1; } if (strcmp(ARGV[1], OPTION_HELP_1) == 0 || strcmp(ARGV[1], OPTION_HELP_2) == 0) { matched = 1; printHelp(); } if (strcmp(ARGV[1], OPTION_GENERATE_1) == 0 || strcmp(ARGV[1], OPTION_GENERATE_2) == 0) { matched = 1; printf("\nWe will generate a set of keys now"); int bitlength = DEFAULT_PRIME_LENGTH; char * keys_filename= new char[strlen(DEFAULT_FILENAME)]; strcpy(keys_filename, DEFAULT_FILENAME); if (argc == 4 || argc == 6) { // More options may have been passed if (strcmp(ARGV[2], ARGS_BITLENGTH) == 0) { bitlength = atoi(ARGV[3]); } if (strcmp(ARGV[2], ARGS_FILENAME) == 0) { free(keys_filename); keys_filename = new char[strlen(ARGV[3])]; strcpy(keys_filename, ARGV[3]); } if (argc == 6) { if (strcmp(ARGV[4], ARGS_FILENAME) == 0) { free(keys_filename); keys_filename = new char[strlen(ARGV[5])]; strcpy(keys_filename, ARGV[5]); } if (strcmp(ARGV[4], ARGS_BITLENGTH) == 0) { bitlength = atoi(ARGV[5]); } } } log_info("\nGenerating keys with prime bitlength %d and name %s", bitlength, keys_filename); generate_key_pair(bitlength, keys_filename); } if (strcmp(ARGV[1], OPTION_ENCRYPT) == 0) { if (argc == 4 || argc == 6) { matched = 1; // Check that atleast one option is the file to encrypt if (strcmp(ARGV[2], ARGS_FILENAME) != 0 && (argc > 4 ? strcmp(ARGV[4], ARGS_FILENAME) != 0 : 0)) { matched = 0; } else { printf("\nWe can try to encrypt the file now"); char * pubkey_filename = new char[strlen(DEFAULT_FILENAME)]; strcpy(pubkey_filename, DEFAULT_FILENAME); strcat(pubkey_filename, ".public"); char * plaintext; if (strcmp(ARGV[2], ARGS_FILENAME) == 0) { plaintext = new char[strlen(ARGV[3])]; strcpy(plaintext, ARGV[3]); } if (strcmp(ARGV[2], ARGS_KEY) == 0) { free(pubkey_filename); pubkey_filename = new char[strlen(ARGV[3])]; strcpy(pubkey_filename, ARGV[3]); } if (argc == 6) { if (strcmp(ARGV[4], ARGS_FILENAME) == 0) { plaintext = new char[strlen(ARGV[5])]; strcpy(plaintext, ARGV[5]); } if (strcmp(ARGV[4], ARGS_KEY) == 0) { free(pubkey_filename); pubkey_filename = new char[strlen(ARGV[5])]; strcpy(pubkey_filename, ARGV[5]); } } if (!file_exists(string(plaintext))) { printf("\nERROR! Plaintext file %s doesn't exist!\n", plaintext); return 1; } if (!file_exists(string(pubkey_filename))) { printf("\nERROR! Public key file %s doesn't exist!\n", pubkey_filename); return 1; } log_info("\nEncryption the file %s using the public key %s", plaintext, pubkey_filename); // TODO: Hook up the function that will directly encrypt the given // filepath // Get the integer representation of the file mpz_t file_rep, octet_len; mpz_init(file_rep); mpz_init(octet_len); convert_file_to_integer(plaintext, file_rep, octet_len); // Get the filename of the ciphertext char * filename_base = basename(plaintext); char * ciphertext_filename = new char[strlen(filename_base) + strlen(FILENAME_ENCRYPTED_FILE_SUFFIX)]; strcpy(ciphertext_filename, filename_base); strcat(ciphertext_filename, FILENAME_ENCRYPTED_FILE_SUFFIX); // Write the octet len of the integer to the file FILE * stream = fopen(ciphertext_filename, "w"); gmp_fprintf(stream, "%Zx\n", octet_len); fclose(stream); // Now, write the ciphertext to the file // Append it to this file, instead of writing it to a new file // While reading, read with gmp_fscanf(stream, "%Zx\n%Zx", octet_len, ciphertext_int_rep); encrypt_integer_rsa(file_rep, pubkey_filename, ciphertext_filename, "a"); } } } if (strcmp(ARGV[1], OPTION_DECRYPT) == 0) { if (argc == 4 || argc == 6) { matched = 1; // Check that atleast one option is the file to decrypt if (strcmp(ARGV[2], ARGS_FILENAME) != 0 && (argc > 4 ? strcmp(ARGV[4], ARGS_FILENAME) != 0 : 0)) { matched = 0; } else { printf("\nWe can try to decrypt the file now"); char * priv_key_filename = new char[strlen(DEFAULT_FILENAME)]; strcpy(priv_key_filename, DEFAULT_FILENAME); strcat(priv_key_filename, ".private"); char * ciphertext; if (strcmp(ARGV[2], ARGS_FILENAME) == 0) { ciphertext = new char[strlen(ARGV[3])]; strcpy(ciphertext, ARGV[3]); } if (strcmp(ARGV[2], ARGS_KEY) == 0) { free(priv_key_filename); priv_key_filename = new char[strlen(ARGV[3])]; strcpy(priv_key_filename, ARGV[3]); } if (argc == 6) { if (strcmp(ARGV[4], ARGS_FILENAME) == 0) { ciphertext = new char[strlen(ARGV[5])]; strcpy(ciphertext, ARGV[5]); } if (strcmp(ARGV[4], ARGS_KEY) == 0) { free(priv_key_filename); priv_key_filename = new char[strlen(ARGV[5])]; strcpy(priv_key_filename, ARGV[5]); } } if (!file_exists(string(ciphertext))) { printf("\nERROR! Ciphertext file %s doesn't exist!\n", ciphertext); return 1; } if (!file_exists(string(priv_key_filename))) { printf("\nERROR! Private key file %s doesn't exist!\n", priv_key_filename); return 1; } log_info("\nDecrypting the file %s using the private key %s", ciphertext, priv_key_filename); // TODO: Hook up the function that will decrypt the given // filepath // Decrypt the file to get the plaintext integer representation and the // octet length of the plaintext itself mpz_t plaintext; mpz_init(plaintext); unsigned long int octet_len = 0; decrypt_integer_rsa(ciphertext, priv_key_filename, plaintext, octet_len); // Now, find the name of the plaintext file // before encryption string plaintext_filename = string(ciphertext).substr(0, strlen(ciphertext) - strlen(FILENAME_ENCRYPTED_FILE_SUFFIX)); convert_integer_to_file(plaintext, octet_len, plaintext_filename.c_str()); } } } if (strcmp(ARGV[1], OPTION_CONVERT_INT_TO_STRING) == 0 && argc == 4) { matched = 1; char * end; mpz_t int_rep; mpz_init(int_rep); gmp_sscanf(ARGV[2], "%Zd", int_rep); unsigned long int octet_len = atoi(ARGV[3]); convert_integer_to_string(int_rep, octet_len); mpz_clear(int_rep); } if (strcmp(ARGV[1], OPTION_CONVERT_STRING_TO_INT) == 0 && argc == 3) { matched = 1; mpz_t rep, octet_len; mpz_init(rep); mpz_init(octet_len); convert_string_to_integer(ARGV[2], rep, octet_len); mpz_clear(rep); mpz_clear(octet_len); } if (!matched) { printf("\nERROR! Invalid option. Run `rsa --help` for help text\n"); return 1; } printf("\n"); return 0; }
true
4da978355edb6494509a6ea11ab83011177ae55e
C++
itstepP12814/ChehovHW
/C++/ClassWorks/CW27/WordFilter/src/List.cpp
UTF-8
3,145
3.609375
4
[]
no_license
#include "List.h" List::List() { begin=nullptr; end=nullptr; //ctor } List::List(string str) { begin=nullptr; end=nullptr; s=str; } void List::push_front(string str) { if (begin == nullptr) { // for the 1st element begin = new word; end=begin; begin->next = nullptr; begin->prev = nullptr; } else { // for following elements begin->prev = new word; begin->prev->prev = nullptr; begin->prev->next = begin; begin = begin->prev; } begin->wrd = str; } void List::push_back(string str) { if(end==nullptr) { end=new word; begin=end; end->next=nullptr; end->prev=nullptr; } else { end->next=new word; end->next->next=nullptr; end->next->prev=end; end=end->next; } end->wrd=str; } void List:: parser(int index) { word* iterator=begin; word* temp=nullptr; string s_dot=s+'.'; if((begin->wrd==s || begin->wrd==s_dot)&&begin->next!=nullptr) { begin=begin->next; begin->prev=nullptr; iterator->next=nullptr; iterator->prev=nullptr; delete iterator; iterator=begin; } for(int i=0; i<index; ++i) { if(iterator->next!=nullptr) { iterator=iterator->next; if(iterator->wrd==s || iterator->wrd==s_dot) { if(iterator->next!=nullptr) { iterator->next->prev=iterator->prev; iterator->prev->next=iterator->next; temp=iterator->prev; iterator->next=nullptr; iterator->prev=nullptr; delete iterator; iterator=temp; } else { iterator->prev->next=nullptr; delete iterator; //cout << "end of list in parser error3" <<endl; } } } else { //cout<< "end of list error1" <<endl; } } } void List::show(int index) const { word* iterator=begin; if(iterator!=nullptr) { /**т.к в первый вывод нам будет показат iterator->next это не будет вывод первого элемента списка слов, а только второго и далее, поэтому я вывожу первый элемент еще до запуска цикла для вывода всех иостальных эл-тов. Т.к интуитивно хочется передать в функцию все количество слов, а выводить в циуле мы будем все, кроме первого поэтому i<index-1**/ cout<< iterator->wrd << " "; for(int i=0; i<index; ++i) { if(iterator->next!=nullptr) { iterator=iterator->next; cout<< iterator->wrd <<" "; } else { //cout<< "list shown" << endl; } } } else { cout<< "list is empty" <<endl; } } List::~List() { //dtor }
true
fd945b8c285e7942b222b4914700788102dd4c39
C++
AhJo53589/leetcode-cn
/problems/smallest-common-region/SOLUTION.cpp
UTF-8
1,066
2.890625
3
[]
no_license
////////////////////////////////////////////////////////////////////////// string findSmallestRegion(vector<vector<string>>& regions, string region1, string region2) { unordered_map<string, string> rr; for (auto vs : regions) { for (size_t i = 1; i < vs.size(); i++) { rr[vs[i]] = vs[0]; } } unordered_set<string> rs; string temp = region1; while (true) { rs.insert(temp); if (rr.count(temp) == 0) break; temp = rr[temp]; } temp = region2; while (true) { if (rs.count(temp)) break; //if (rr.count(temp) == 0) break; temp = rr[temp]; } return temp; } ////////////////////////////////////////////////////////////////////////// string _solution_run(vector<vector<string>>& regions, string region1, string region2) { return findSmallestRegion(regions,region1,region2); } //#define USE_SOLUTION_CUSTOM //string _solution_custom(TestCases &tc) //{ //} ////////////////////////////////////////////////////////////////////////// //#define USE_GET_TEST_CASES_IN_CPP //vector<string> _get_test_cases_string() //{ // return {}; //}
true
3a01d54487efc922642845198674f5cea41b8f18
C++
zhouxinzx/niuniu
/树的高度.cpp
UTF-8
780
3.125
3
[]
no_license
#include<iostream> using namespace std; int max(int x,int y) { if(x>y) return x; else return y; } int getheight(int x,int **p,int num) { int flag=0; int sig[2]={-1,-1}; for(int i=0;i<num-1;i++) { if(p[i][0]==x) { sig[flag]=i; flag++; } if(flag==2) break; } if(flag==1) return 1+getheight(p[sig[0]][1],p,num); else if(flag==2) { int temp1=getheight(p[sig[0]][1],p,num); int temp2=getheight(p[sig[1]][1],p,num); return 1+max(temp1,temp2); } else return 1; } int main() { int n; while(cin>>n) { int **p=new int*[n-1]; for(int i=0;i<n-1;i++) p[i]=new int[2]; for(int i=0;i<n-1;i++) for(int j=0;j<2;j++) cin>>p[i][j]; cout<<getheight(p[0][0],p,n); } return 0; }
true
14cfaecb1e9f64fe39a144833f91534b1aa114f9
C++
Zycon42/Heightmap
/src/engine/Terrain.h
WINDOWS-1250
729
3.03125
3
[ "MIT" ]
permissive
/** * @file Terrain.h * * @author Jan Duek <xdusek17@stud.fit.vutbr.cz> * @date 2013 */ #ifndef TERRAIN_H #define TERRAIN_H #include "Mesh.h" #include "Material.h" #include <glm/glm.hpp> struct HeightMap { size_t width, height; std::vector<float> heights; }; class Terrain { public: explicit Terrain(const HeightMap& heightMap); Mesh* mesh() { return &m_mesh; } IMaterial* material() { return m_material.get(); } void setMaterial(std::shared_ptr<IMaterial> material) { m_material = std::move(material); } private: static std::vector<uint32_t> computeIndices(const HeightMap& map); static std::vector<char> computeVertices(const HeightMap& map); Mesh m_mesh; std::shared_ptr<IMaterial> m_material; }; #endif // !TERRAIN_H
true
986ff116634f7d97570c11390debb5cf042b7545
C++
thnoh1212/Practice
/프로그래머스/2 x n 타일링.cpp
UTF-8
281
2.578125
3
[]
no_license
#include <string> #include <vector> using namespace std; int solution(int n) { long long answer[60001] = { 0 }; answer[1] = 1; answer[2] = 2; for (int i = 3; i <= n; i++){ answer[i] = answer[i - 1] + answer[i - 2]; answer[i] %= 1000000007; } return answer[n]; }
true
3d2d2ce817f284575028ccd3c7b9b1d72ae489e8
C++
JTensai/HiveEngine
/HiveEngine/HiveEngine/IGameWorld.h
UTF-8
1,100
2.5625
3
[]
no_license
#pragma once #include <vector> #include <GL\glew.h> #include <glm\glm.hpp> #include "XMLInterface.h" #include "Graph.h" #include "Data.h" namespace Hive { /** * Assumes 0,0,0 is the bottomleft corner of the map * Y is the up axis * If the world scale is 1: * Y of 1 is walkable terrain for now * 1,1,1 is the corner between grid spaces 0,0; 1,0; 0,1; and 1,1 * All the area between 0,1,0 and 1,1,1 is the space of grid 0,0 */ class IGameWorld { public: virtual int width() = 0; virtual int depth() = 0; virtual int get_map_index(int x, int y) = 0; virtual const std::vector<char>& grid() = 0; virtual const glm::vec3& ambient() = 0; virtual const glm::vec4& light() = 0; virtual const glm::vec3& light_direction() = 0; virtual const glm::vec3& background() = 0; virtual Graph* get_nav_mesh() = 0; virtual void load(GLuint shader, XMLIterator map_iter, UnitHandle& player_unit_handle) = 0; virtual void update(float delta) = 0; virtual void draw(const glm::mat4& VP) = 0; virtual void close() = 0; IGameWorld() {} virtual ~IGameWorld() {} }; }
true
d5c91e27f2804bec9c3d208937afd1dc4e678f5f
C++
lyMeiSEU/Data-Structures-Homework
/P119-9.CPP
GB18030
810
3.109375
3
[]
no_license
/*Pat: a b c a b c a c a b -1 -1 -1 0 1 2 3 -1 0 1*/ #include<iostream> using namespace std; void FailureFunction(string pat,int *f) { int lengthP=pat.length(); f[0]=-1; for(int i=0;i<lengthP;i++)//f[i] { int nj=-1; for(int j=0;j<i;j++) //ȡk { if(j==0&&pat[0]==pat[i]) { nj=0; continue; } for(int k=0;k<j;++k)//ַȽ { if(pat[k]!=pat[i-j+k]) break; } if(k==j) nj=j-1; } f[i]=nj; } } int main() { string pat="abcabcacab"; int *f=new int [pat.length()]; FailureFunction(pat,f); for(int i=0;i<pat.length();++i) cout<<f[i]<<" "; cout<<endl; delete[]f; return 0; } //patǰϴʱ¹ϺʱܶԭϺ
true
24728d3bfd5ab888f95004576682db4e5cdf7d6b
C++
godgnidoc/alioth-dev
/inc/imm.hpp
UTF-8
4,836
2.734375
3
[ "MIT" ]
permissive
#ifndef __imm__ #define __imm__ #include <llvm/IR/Value.h> #include <llvm/IR/IRBuilder.h> #include "operatordef.hpp" #include "methoddef.hpp" #include "eproto.hpp" namespace alioth { using namespace llvm; /** * @struct imm : 立即单元 * @desc : * 立即单元是表达式的计算产物 * 它可能是立即对象,也可能是立即寻址 * 比如一个元素本身,就是一个立即寻址 * 一个基础数据类型的加法运算中间结果就是一个立即对象 * 立即对象直接存储数据,也直接存储数据类型 * 立即寻址存储地址,存储元素原型 * * 满足Alioth语言规定的数据类型的对象,指针,共称 单元 unit * 对象,指针,引用,重载都能被元素直接寻址,共称 实例 instance * 对对象来说,地址是元素 * 对指针来说,地址是元素 * 对被引用管理的单元,地址是引用 * 对被重载管理的单元,地址是重载 */ struct imm; using $imm = agent<imm>; class Sengine; struct imm : thing { public: enum immt { ele, // v 是元素,对于VAR和PTR存储了对象的地址Obj*, 对于REF和VAL存储了对象的指针的地址Obj** ins, // v 是实例,对于VAR和PTR存储了对象本身Obj, 对于REF和VAL存储了对象的指针Obj* fun, // v 是函数 mem, // v 是成员运算符 }; private: /** * @member t : 立即单元类型 * @desc : * 此标记标定此立即单元是否为立即对象或其他类型的立即单元 */ immt t; /** * @member v : 地址或值 * @desc : * 若此单元为立即寻址,v保存元素,元素的本质就是对象的地址 * 此值可以用于产生load或store指令 * 若此单元是立即对象,v保存对象 * 若此对象为函数,则v实际上是函数入口GV */ Value* v; /** * @member p : 元素原型或数据类型 * @desc : * 若单元为立即寻址或立即对象,则其中存储元素原型eproto * 若单元为实体,则其中存储类定义ClassDef * 若单元为立即函数,则其中存储函数原型MethodDef */ anything p; public: /** * @member h : 宿主 * @desc : * 可选的,如果此对象表示成员运算的结果,h指向成员运算的宿主,避免重复计算 */ $imm h; public: imm() = default; imm( immt T, Value* V, anything P, $imm H = nullptr ); imm( const imm& ) = default; imm( imm&& ) = default; imm& operator=( const imm& ) = default; imm& operator=( imm&& ) = default; ~imm() = default; bool is( immt )const; immt is()const; /** 存入元素 */ static $imm element( Value* addr, $eproto proto, $imm host = nullptr ); /** 存入实例 */ static $imm instance( Value* obj, $eproto proto ); $eproto eproto()const; static $imm entity( Value* addr, $ClassDef def ); static $imm function( Value* fp, $MethodDef prototype, $imm host = nullptr ); $MethodDef prototype()const; static $imm member( Value* fp, $OperatorDef member, $imm host = nullptr ); $OperatorDef member()const; Value* raw()const; /** * 获取可以直接参与运算的Value* * 1. 对于立即寻址,执行load * 2. 对于引用和右值,再执行load */ Value* asunit( IRBuilder<>& builder, Sengine& sengine )const; /** * 获取可以执行store存储对象的Value* * 1. 对于立即对象,REF和VAL,直接返回v,其他返回空 * 2. 对于立即寻址,REF和VAL,执行load后返回,其他直接返回 */ Value* asaddress( IRBuilder<>& builder, Sengine& sengine )const; bool hasaddress()const; /** * 获取可用于传参Value* 要确保请求类型和源类型完全一致 * 1. 对立即对象 * 若请求引用或重载,失败 * 对其他情况,直接返回 * 2. 对立即寻址 * 若请求对象 * 若复合数据类型,直接返回 * 否则,执行load后返回 * 若请求指针 * 若不是指针数据类型,失败 * 否则,执行load后返回 * 若请求引用或重载 * 直接返回 */ Value* asparameter( IRBuilder<>& builder, Sengine& sengine, etype e )const; Value* asfunction()const; }; using imms = chainz<$imm>; using bundles = map<string,$imm>; } #endif
true
79a4644528174504d42cc40e2f0827b198bc5d47
C++
oO777Oo/LeetCode
/Number Theory/Add two fractionsProblem146/main.cpp
UTF-8
818
3.78125
4
[]
no_license
#include <iostream> #include <utility> #include <vector> std::pair<int,int> solve(int x, int y , int z, int w); int noodOfTwoNumbers(int x, int y); int main() { int firstTop = 0; int firstBot = 0; int secondTop = 0; int secondBot = 0; std::cin >> firstTop >> firstBot >> secondTop >> secondBot; std::pair<int,int> ans = solve(firstTop, firstBot, secondTop, secondBot); std::cout<< ans.first << " " << ans.second; return 0; } std::pair<int,int> solve(int x, int y , int z, int w) { std::pair<int,int> ans; int numberBot = y * w; int numberTop = x * w + z * y; int bd = noodOfTwoNumbers(numberTop, numberBot); ans.first = numberTop / bd; ans.second = numberBot / bd; return ans; } int noodOfTwoNumbers(int x, int y) { if(x == 0) { return y; } else { return noodOfTwoNumbers(y % x, x); } }
true
4be1e99a3f578af19b79a7d49d6f7b950003c28d
C++
zhanglingfeng911/zlf_leetcode
/OJ_Exe/2.cpp
UTF-8
676
2.75
3
[]
no_license
// // Created by zlf on 2021/3/26. // // // Created by zlf on 2021/3/26. // #include<iostream> #include<string> #include<vector> #include<algorithm> #include <sstream> using namespace std; int main02() { string s; while (getline(cin,s)) { istringstream sss(s);//将输入的一行字符串用空格分开分割成一个字符串数组 vector<string>vec; string tmp; while(getline(sss,tmp,',')) { vec.push_back(tmp); } sort(vec.begin(),vec.end()); for (int i = 0; i < vec.size()-1; ++i) { cout<<vec[i]<<','; } cout<<vec.back()<<endl; } return 0; }
true
f3b1628e2087c7bd17b66ccb7f3f273f615ea996
C++
Neverous/xivlo08-11
/OBOZY/2010 - Październik/perm2.cpp
UTF-8
1,177
2.875
3
[]
no_license
/* 2010 * Maciej Szeptuch * XIV LO Wrocław */ #include<cstdio> //#define DEBUG(args...) fprintf(stderr, args) #define DEBUG(args...) int tests, size, speedup[51][51]; inline static int gimmeh(int parts, int left); inline static int permutations(int num); inline static int NWD(int a, int b); inline static int MAX(int a, int b); int main(void) { scanf("%d", &tests); for(int t = 0; t < tests; ++ t) { scanf("%d", &size); printf("%d\n", permutations(size)); } return 0; } inline static int permutations(int num) { int result = 1; for(int i = 1; i <= num; ++ i) result = MAX(result, gimmeh(i, num)); return result; } inline static int NWD(int a, int b) { if(a < b) return NWD(b, a); if(b == 0) return a; return NWD(b, a % b); } inline static int MAX(int a, int b) { return a>b?a:b; } inline static int gimmeh(int parts, int left) { if(speedup[parts][left]) return speedup[parts][left]; int gh; speedup[parts][left] = left; if(parts == 1) return speedup[parts][left]; for(int l = 1; l < left; ++ l) { gh = gimmeh(parts - 1, left - l); speedup[parts][left] = MAX(speedup[parts][left], l * gh / NWD(l, gh)); } return speedup[parts][left]; }
true
4070e7d4fe070f5d8f2e9beab264a4d187ae3d53
C++
skkyal/DSA
/CSES problems/flight_routes.cpp
UTF-8
930
2.53125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; typedef long long ll; void kthShotestPath(vector<pair<ll,ll>>adj[],ll n,ll k){ ll INF=9e15; vector<vector<ll>>dist(n+1,vector<ll>(k,INF)); dist[1][0]=0; priority_queue<pair<ll,ll>>q; q.push({0,1}); while(!q.empty()){ ll d=-1*q.top().first,u=q.top().second; q.pop(); if(dist[u][k-1]<d) continue; for(auto e:adj[u]){ ll v=e.first,w=e.second; if(dist[v][k-1]>d+w){ dist[v][k-1]=d+w; q.push({-dist[v][k-1],v}); sort(dist[v].begin(),dist[v].end()); } } } for(ll i=0;i<k;i++) cout<<dist[n][i]<<" "; } void solve(){ ll n,m,k; cin>>n>>m>>k; vector<pair<ll,ll>>adj[n+1]; for(ll i=0;i<m;i++){ ll u,v,w; cin>>u>>v>>w; adj[u].push_back({v,w}); } kthShotestPath(adj,n,k); } int main() { #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("op.txt","w",stdout); #endif int t=1; //cin>>t; while(t--){ solve(); } }
true
645b3cb2e179beae245fe8b785365cdfd4891ab8
C++
refractionpcsx2/RefNES
/RefNES/Mappers/MapperAxROM.h
UTF-8
921
2.5625
3
[]
no_license
#pragma once #ifndef MAPPERAXROM_H #define MAPPERAXROM_H #include "../mappers.h" class AXROM : public Mapper { public: AXROM(unsigned int SRAMTotalSize, unsigned int PRGRAMTotalSize, unsigned int CHRRAMTotalSize); ~AXROM(); void Reset(); void CPUWrite(unsigned short address, unsigned char value); unsigned char CPURead(unsigned short address); void PPUWrite(unsigned short address, unsigned char value); unsigned char PPURead(unsigned short address); private: unsigned int SRAMSize; unsigned int CHRRAMSize; unsigned int PRGSize; unsigned int currentProgramAddr; unsigned char SRAM[0x2000]; //Max SRAM 16k unsigned char CHRRAM[0x2000]; //Max CHR-RAM 8k unsigned char singleScreenBank = 0; unsigned char currentProgram = 0; unsigned char ReadCHRROM(unsigned short address); void WriteCHRRAM(unsigned short address, unsigned char value); }; #endif
true
a261e8f851708e00e5222c08b5ca2716596bc281
C++
KanColleTool/kct-viewer
/test/test_KVTranslator.cpp
UTF-8
1,004
2.921875
3
[]
no_license
#include <catch.hpp> #include <KVTranslator.h> SCENARIO("Strings can be translated") { KVTranslator tl; GIVEN("Data for Naka, none for Maruyu") { tl.translation.insert(QString("124853853"), "Naka"); // 那珂 (Naka) tl.translation.insert(QString("3440185848"), QVariant()); // まるゆ (Maruyu) tl.state = KVTranslator::loaded; THEN("isLoaded() should be true") { REQUIRE(tl.isLoaded()); } THEN("Naka's name should be translated") { REQUIRE(tl.translate("那珂") == QString("Naka")); REQUIRE(tl.translate("\\u90A3\\u73C2") == QString("Naka")); } THEN("Maruyu's name should be untouched") { REQUIRE(tl.translate("まるゆ") == QString("まるゆ")); REQUIRE(tl.translate("\\u307E\\u308B\\u3086") == QString("\\u307E\\u308B\\u3086")); } THEN("Unknwn strings should be untouched") { REQUIRE(tl.translate("テスト") == QString("テスト")); REQUIRE(tl.translate("\\u307E\\u308B\\u3086") == QString("\\u307E\\u308B\\u3086")); } } }
true
35d29bdd274181dedf5b29956fc9e3fa601af937
C++
moxcodes/classical_cryptanalysis
/rksolve.cpp
UTF-8
9,282
2.703125
3
[]
no_license
#include <string> #include <iostream> #include <stdlib.h> #include <math.h> #include "dicttree.h" #include <fstream> #include <stdio.h> using namespace dicttree; std::string CleanString(std::string generalString); std::vector<std::string>* ImportWordList(std::string filename); void runningKeySolve(std::string puzzle,std::string progress,std::string keyprogress, int prevBounds[2], int prevKeyBounds[2], Dicttree* keySTree,Dicttree* codeSTree,Dicttree* keyBTree,Dicttree* codeBTree,int depthTrigger); Dicttree* simpleTree; Dicttree* bigTree; Dicttree* doubleTree; Dicttree* outputTree; std::string CleanString(std::string generalString) { std::string nuString=""; for(int i=0;i<generalString.size();i++) { if((int)generalString.at(i)>=(int)'a' && (int)generalString.at(i)<=(int)'z') nuString+=generalString.at(i); if((int)generalString.at(i)>=(int)'A' && (int)generalString.at(i)<=(int)'Z') nuString+=(char)((int)generalString.at(i)+ 32); } return nuString; } //get the english wordlist std::vector<std::string>* ImportWordList(std::string filename) { std::ifstream wordFile(filename.c_str()); std::vector<std::string>* wordList= new std::vector<std::string>(); std::string word; while(getline(wordFile,word)) { wordList->push_back(CleanString(word)); } wordFile.close(); return wordList; } //puzzle - the cipher //progress - the plaintext so far //keyprogress - the key so far //KeyStree - simple subtree for the key string //codeStree - simple subtree for the plaintext string //KeyBtree - big tree for the key string //codeBtree - big tree for the plaintext string //void runningKeySolve(std::string puzzle,std::string progress,std::string keyprogress, int prevBounds[2], int prevKeyBounds[2], // Dicttree* keySTree,Dicttree* codeSTree,Dicttree* keyBTree,Dicttree* codeBTree,int depthTrigger,std::string prefix) /*void runningKeySolve(std::string puzzle,std::string progress,std::string keyprogress, int prevBounds[2], int prevKeyBounds[2], Dicttree* keySTree,Dicttree* codeSTree,int depthTrigger,std::string prefix) { if(depthTrigger <= 0){ std::cout<<progress<<'\n'; std::cout<<keyprogress<<"\n\n"; } if(puzzle.size()==0){ std::string output=progress.substr(0,depthTrigger) + keyprogress.substr(0,depthTrigger); if(!(outputTree->contains(output))) { outputTree->add(output); std::cout<<progress.substr(0,depthTrigger) + " " + keyprogress.substr(0,depthTrigger)<<'\n'; } return; } if(progress.size()>depthTrigger && outputTree->contains(progress.substr(0,depthTrigger) + keyprogress.substr(0,depthTrigger))) return; //condition the trees -assume root has children, is not leaf, or permanent loop... //note that this implementation insists on following short word paths first, otherwise is alphabetical //leaf in simple tree implies leaf in full tree - int nuBounds[2]; if((codeSTree!=NULL) &&(codeSTree->isLeaf)) { if(prevBounds[0]==prevBounds[1] || doubleTree->contains(progress.substr(prevBounds[0],progress.size()-prevBounds[0]))) { nuBounds[0]=prevBounds[1]; nuBounds[1]=progress.size(); runningKeySolve(puzzle,progress,keyprogress,nuBounds,prevKeyBounds, keySTree,simpleTree,depthTrigger,prefix); } } if(keySTree!=NULL && keySTree->isLeaf) { if(prevKeyBounds[0]==prevKeyBounds[1] || doubleTree->contains(keyprogress.substr(prevKeyBounds[0],progress.size()-prevKeyBounds[0]))) { nuBounds[0]=prevKeyBounds[1]; nuBounds[1]=keyprogress.size(); runningKeySolve(puzzle,progress,keyprogress,prevBounds,nuBounds, simpleTree,codeSTree,bigTree,codeBTree,depthTrigger,prefix); } } if(codeBTree->isLeaf && (codeSTree==NULL || !(codeSTree->isLeaf))) { nuBounds[0]=progress.size(); nuBounds[1]=progress.size(); runningKeySolve(puzzle,progress,keyprogress,nuBounds,prevKeyBounds, keySTree,simpleTree,keyBTree,bigTree,depthTrigger,prefix); } if(keyBTree->isLeaf && (keySTree==NULL || !(keySTree->isLeaf))) { nuBounds[0]=progress.size(); nuBounds[1]=progress.size(); runningKeySolve(puzzle,progress,keyprogress,prevBounds,nuBounds, simpleTree,codeSTree,bigTree,codeBTree,depthTrigger,prefix); } //now, we need to compute for(int i=0;i<26;i++){ if((prefix=="" || (prefix.at(0) -97) ==i) && (codeBTree->children[i]!=NULL && (keyBTree->children[((( (int)puzzle.at(0) -97) - i) +26)%26] != NULL))) { Dicttree* nuKeySTree = NULL; Dicttree* nuCodeSTree = NULL; std::string nuPrefix=""; if(prefix!="") nuPrefix=prefix.substr(1); if(codeSTree!=NULL && codeSTree->children[i]!=NULL) nuCodeSTree = codeSTree->children[i]; if(keySTree!=NULL && keySTree->children[((( (int)puzzle.at(0) -97) - i) +26)%26]!=NULL) nuKeySTree = keySTree->children[((( (int)puzzle.at(0) -97) - i) +26)%26]; //this is an unattractively long function call runningKeySolve(puzzle.substr(1),progress + ((char)(i+97)),keyprogress + (char)(((( (int)puzzle.at(0) -97) - i) +26)%26 +97), prevBounds,prevKeyBounds,nuKeySTree,nuCodeSTree, keyBTree->children[(((int)puzzle.at(0) -97) - i + 26)%26],codeBTree->children[i],depthTrigger,nuPrefix); } } return; }*/ //Okay above is the 'complicated' version of the running key solver. //The easiest possible that might actually generate results is to make naive probability estimates double highscore=0; void runningKeySolve(std::string puzzle,std::string progress,std::string keyprogress,int depthTrigger,double runningScore) { //first, score each 'next step' for each of the strings if(highscore!=0 && runningScore < highscore) return; if(progress.size()==puzzle.size()&&(highscore==0 || runningScore >= highscore )) { std::cout<<highscore<<"\n"; std::cout<<runningScore<<"\n\n"; highscore=runningScore; std::cout<<progress<<"\n"; std::cout<<keyprogress<<"\n\n"; return; } if(progress.size()==puzzle.size()&&(highscore==0 || runningScore >= highscore - 100 )) { std::cout<<highscore<<"\n"; std::cout<<runningScore<<"\n\n"; std::cout<<progress<<"\n"; std::cout<<keyprogress<<"\n\n"; } if(progress.size()==puzzle.size()) return; /* if(depthTrigger<=0) { std::cout<<progress<<"\n"; std::cout<<keyprogress<<"\n\n"; }*/ double plainScore[26]; double keyScore[26]; double fullScore[26]; double minprob=.00000000000000000000000000000001; std::vector<int> maxFullScores; int k =0; for(int i=0;i<26;i++) { plainScore[i]=0; keyScore[i]=0; std::string nuProgress=progress+(char)(i+97); std::string nuKey = keyprogress+(char)(((puzzle.at(progress.length())-97 - i + 26)%26) + 97); for(int j=0;j<std::min((int)nuProgress.size(),6);j++) { plainScore[i]+=log(std::max(simpleTree->getFrequency(nuProgress.substr(nuProgress.length()-1-j,j+1)),minprob)); keyScore[i]+=log(std::max(simpleTree->getFrequency(nuKey.substr(nuKey.length()-1-j,j+1)),minprob)); } fullScore[i]=keyScore[i]+plainScore[i]; k=0; while(k<maxFullScores.size()&&fullScore[maxFullScores[k]]>fullScore[i]) k++; if(k==maxFullScores.size()) maxFullScores.push_back(i); else maxFullScores.insert(maxFullScores.begin()+k,i); } // for(int i=0;i<bestN;i++) int i=0; while(i<26 && fullScore[maxFullScores[i]]>= 1.5*fullScore[maxFullScores[0]]) { // if(depthTrigger<=0) // std::cout<<fullScore[maxFullScores[i]]<<"\n"; runningKeySolve(puzzle,progress+(char)(maxFullScores[i] + 97), keyprogress +(char)((puzzle.at(progress.length()) - 97 - maxFullScores[i] + 26)%26 + 97), depthTrigger-1,runningScore+fullScore[maxFullScores[i]]); i++; } return; //now, maxFullScores has an ordered list of the best to worst next choices, so we should iterate down the tree } int main(int argc, char* argv[]) { //obtain wordlist if(argc!=7 && argc != 5){ std::cout <<"Usage: rksolve <mystery string> <simple list filename> <advanced list filename> <double list filename>"<<'\n'; return 0; } // std::vector<std::string>* simpleList=ImportWordList(std::string(argv[2])); // std::vector<std::string>* bigList=ImportWordList(std::string(argv[3])); // std::vector<std::string>* doubleList=ImportWordList(std::string(argv[4])); //make the english tree simpleTree = new Dicttree(std::string(argv[2])); outputTree=new Dicttree(); //simpleTree->PrintTree(""); //recursively probe the dictionary tree to solve the constraint - print if current attempt gets at least 5 deep or if end is reached // int codeBounds[2]={0,0}; // int keyBounds[2]={0,0}; // if(argc==6) if(argc==5) runningKeySolve(CleanString(std::string(argv[1])),"","",atoi(argv[3]),atoi(argv[4])); if(argc==7) runningKeySolve(CleanString(std::string(argv[1])),std::string(argv[5]),std::string(argv[6]),atoi(argv[3]),atoi(argv[4])); // if(argc==7) // runningKeySolve(CleanString(std::string(argv[1])),"","",codeBounds,keyBounds, // simpleTree,simpleTree,bigTree,bigTree,atoi(argv[5]),std::string(argv[6])); // //better free that wordlist simpleTree->~Dicttree(); free(simpleTree); return 0; }
true
fb2807487e27e4e1031fdbbb5eee2404efdce617
C++
leofravega51/Arduino
/TP2/Ej9.ino
UTF-8
835
2.890625
3
[]
no_license
#define redPin 6 #define bluePin 5 #define greenPin 3 #define puls 2 long redRandom, blueRandom, greenRandom; void setup() { Serial.begin (9600); //Define inputs and outputs pinMode(redPin, OUTPUT); pinMode(bluePin, OUTPUT); pinMode(greenPin, OUTPUT); pinMode(puls, INPUT); } void loop() { Serial.println(digitalRead(puls)); if (digitalRead(puls) == HIGH) { //Generate random numbers from 0-255 for a random rgb color redRandom = random(256); blueRandom = random(256); greenRandom = random(256); analogWrite(redPin, redRandom); analogWrite(bluePin, blueRandom); analogWrite(greenPin, greenRandom); delay(2000); //Turn on rgb random color for 2 seconds } else { //Turn off rgb analogWrite(redPin, 0); analogWrite(bluePin, 0); analogWrite(greenPin, 0); } }
true
e9171b69ec8f372925dbd5eb604c8c7322528372
C++
japdhaes/cpproject1
/atomwavefunction.cpp
UTF-8
4,378
2.71875
3
[]
no_license
#include "atomwavefunction.h" AtomWavefunction::AtomWavefunction(int _nParticles, double _alpha, double _beta): slater(_alpha, _nParticles, 0), jastrow(_beta, _nParticles), charge(_nParticles), nParticles(_nParticles), nDimensions(3), h(5e-3), h2(1.0/h/h) { } void AtomWavefunction::setAlpha(const double alpha){ this->slater.setAlpha(alpha); } void AtomWavefunction::setR(double R){} void AtomWavefunction::setBeta(const double beta){ if(beta<0){ cout << "Setting a negative beta value. Exiting."<<endl; exit(1); } this->jastrow.setBeta(beta); } void AtomWavefunction::initialize(const mat &r){ this->slater.initialize(r); this->jastrow.initialize(r); } double AtomWavefunction::evaluate(const mat &r) { return jastrow.evaluate(r)*slater.evaluate(r); } void AtomWavefunction::setCurrentParticle(const int &i) { this->cp=i; this->slater.setCurrentParticle(i); this->jastrow.setCurrentParticle(i); } void AtomWavefunction::setNewPos(const mat &r){ this->slater.setNewPosition(r); this->jastrow.setNewPosition(r); } double AtomWavefunction::calcRatio(){ double ans=this->slater.calcRatio()*this->jastrow.calcRatio(); return ans*ans; } double AtomWavefunction::getRatio(){ double ans=this->slater.getRatio()*this->jastrow.getRatio(); return ans*ans; } void AtomWavefunction::acceptMove(){ this->slater.acceptMove(); this->jastrow.acceptMove(); } void AtomWavefunction::rejectMove(){ this->slater.rejectMove(); this->jastrow.rejectMove(); } double AtomWavefunction::localEnergyCF(const mat &r){ double kinetic=localKineticCF(); double potential=this->potentialEnergy(r); // cout << r << endl; // cout << "CLOSED FORM: Kin " << kinetic << " pot " << potential << " tot " << kinetic+potential<<endl; return kinetic+potential; } double AtomWavefunction::localKineticCF(){ //slide 173 double kin=0.0; for(int i=0; i<this->nParticles;i++){ kin+=slater.localLaplacian(i); kin+=jastrow.localLaplacian(i); kin+=2.0*dot(slater.localGradient(i),jastrow.localGradient(i)); } kin*=-0.5; return kin; } double AtomWavefunction::potentialEnergy(const mat &r){ double potentialEnergy = 0; double rSingleParticle = 0; // Contribution from electron-nucleus potential for(int i = 0; i < nParticles; i++) { rSingleParticle = 0; for(int j = 0; j < nDimensions; j++) { rSingleParticle += r(i,j)*r(i,j); } potentialEnergy -= charge / sqrt(rSingleParticle); } // Contribution from electron-electron potential double r12 = 0; for(int i = 0; i < nParticles; i++) { for(int j = i + 1; j < nParticles; j++) { r12 = 0; for(int k = 0; k < nDimensions; k++) { r12 += (r(i,k) - r(j,k)) * (r(i,k) - r(j,k)); } potentialEnergy += 1 / sqrt(r12); } } return potentialEnergy; } double AtomWavefunction::localEnergyNum(const mat &r) { mat rPlus = zeros<mat>(nParticles, nDimensions); mat rMinus = zeros<mat>(nParticles, nDimensions); rPlus = rMinus = r; double waveFunctionMinus = 0; double waveFunctionPlus = 0; double waveFunctionCurrent = evaluate(r); // Kinetic energy double kineticEnergy = 0; for(int i = 0; i < nParticles; i++) { for(int j = 0; j < nDimensions; j++) { rPlus(i,j) += h; rMinus(i,j) -= h; waveFunctionMinus = evaluate(rMinus); waveFunctionPlus = evaluate(rPlus); kineticEnergy -= (waveFunctionMinus + waveFunctionPlus - 2 * waveFunctionCurrent); rPlus(i,j) = r(i,j); rMinus(i,j) = r(i,j); } } kineticEnergy = 0.5 * h2 * kineticEnergy / waveFunctionCurrent; // Potential energy double potentialEnergy = this->potentialEnergy(r); //cout << "kinetic energy "<<kineticEnergy<< " potential energy " <<potentialEnergy<<" total " << kineticEnergy + potentialEnergy<<endl; return kineticEnergy + potentialEnergy; } mat AtomWavefunction::localGradient(){ mat gradient=zeros(nParticles, nDimensions); gradient.zeros(); for(int j=0; j<nParticles;j++){ gradient.row(j) = slater.localGradient(j)+jastrow.localGradient(j); } return gradient; }
true
a34a832e72f8116c8d8caa970053335857d50e10
C++
graywzc/leetcode2
/Combination_Sum_III/csi.cc
UTF-8
1,030
3.046875
3
[]
no_license
class Solution { public: combinationSum3(vector<vector<int>>& res, vector<int>& tmp, int n, int i, int k) { if(k>0 && i<=9) { int count = 0; while(n>=0 && (k-count)>=0) { if(n==0) { res.push_back(tmp); break; } else if(n>i) { combinationSum3(res,tmp,n,i+1,k-count); tmp.push_back(i); n-=i; count++; } else break; } while(count>0) { tmp.pop_back(); count--; } } } vector<vector<int>> combinationSum3(int k, int n) { if(k<=0 || n>k*9 || n<k*1) return vector<vector<int>>(); vector<vector<int>> res; vector<int> tmp; combinationSum3(res, tmp, n, 1, k); } };
true
b3008070c38b12f9dff30e46fa1678e6cab2c5cc
C++
HannahTin/Leetcode
/剑指offer/31.cpp
UTF-8
1,233
3.703125
4
[]
no_license
/** 栈的压入、弹出序列 题目描述: 输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如,序列 {1,2,3,4,5} 是某栈的压栈序列,序列 {4,5,3,2,1} 是该压栈序列对应的一个弹出序列,但 {4,3,5,1,2} 就不可能是该压栈序列的弹出序列。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/zhan-de-ya-ru-dan-chu-xu-lie-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 **/ #include <vector> #include <stack> #include <iostream> using namespace std; bool validateStackSequences(vector<int>& pushed, vector<int>& popped) { stack<int> res; int pop_index = 0; for(int i = 0;i<pushed.size();i++){ res.push(pushed.at(i)); while(!res.empty() and popped[pop_index] == res.top()){ res.pop(); pop_index ++; } } if (res.empty()) return true; else return false; } int main(){ vector<int> pushed= {1,2,3,4,5}; vector<int> popped = {4,5,3,2,1}; cout<<validateStackSequences(pushed,popped)<<endl; // 1(true) }
true
bddf6116717634a0c49f47e669ff5bddbc7b6da9
C++
papicheng/offer-boom
/.vscode/min cnt for arr sort.cpp
WINDOWS-1252
637
2.953125
3
[]
no_license
/*ܣ*/ #include<bits/stdc++.h> using namespace std; int main() { int num = 1, max = 1; int n; cin>> n; vector<int> vec(n); vector<int> vec2(n); int tmp; for(int i = 0; i < n; ++i){ cin>> tmp; vec[i] = tmp; } for(int i = 0 ; i < n; ++i){ vec2[i] = vec[i]; for(int j = i + 1; j <n; ++j){ vec2[j] = vec[j]; if(vec2[i] + 1 == vec2[j]){ num += 1; vec2[i] = vec2[j]; } } if(num > max){ max = num; } num = 1; } cout<< n - max; return 0; }
true
1872db9b47d19515fa67f28f3bac4d0ff751807a
C++
AranyaSamaiyar/Data-Structures-and-Algorithms
/Geeks/Ugly Prime.cpp
UTF-8
456
2.96875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; bool isUglyPrime(int m) { int n =m; int ugly_prime[] = {2,3,5}; for(int i=0;i<3;i++) { while((n%ugly_prime[i])==0) { n=n/ugly_prime[i]; } if(n<2) return true; } if(n>2) return false; return true; } int main() { int n; cin>>n; int i=0, cnt=0; while(cnt<n) { //cout<<"hello"; i++; if(isUglyPrime(i)) cnt++; } cout<<i; }
true
242d46a2c151d9cbcd7a9d0fac5421d31e3b5938
C++
n4rus/pi
/nrsdirectory/CGPsys/PI/PI 4.0/coding_0/coding/qe2.cpp
UTF-8
797
3
3
[]
no_license
#include <iostream> #include <cmath> using namespace std; #define g 10 double y, v, x, t, j, w, i, q, c; main () { cout << "Formula: y = y0 + v0yt + 1/2gt², x = x0 + v0xt"; cout << "Valores em order y0, v0, x0, t: "; cin >> y >> v >> x >> t; cout << "y0 = " << y << ", v0 = " << v << ", x0 = " << x << ", t = " << t << endl; if ((y - v - x) == y - v - x) c = g; j = ((v * y) * t); w = t * t; i = ((y + j) + (0.5 * (c * w))); cout << "Para \"y = y0 + v0yt + 1/2gt²\", y = " << ((y + j) + (0.5 * (c * w))) << endl; //function that relates y to x: //x = x0 + v0xt q = (i / (v * (x * t))); cout << "Para \" relacao entre y e x = x0 + v0xt\", y = " << (i / (v * (x * t))) << endl; //repairs: for functions with inputs equals 0 }
true
f6c6b33aabab3b07eef1c3f0dcec79202c47c865
C++
valentin-mille/CCP_plazza_2019
/src/IPC/InterProcessCom.cpp
UTF-8
3,009
3.015625
3
[]
no_license
/* ** EPITECH PROJECT, 2019 ** InterProcessCom ** File description: ** interProcessCom implementation */ #include <algorithm> #include <cstdio> #include <iostream> #include <mutex> #include <stdio.h> #include <string> #include <unistd.h> #include "InterProcessCom.hpp" std::mutex mutex; std::mutex debug_mutex; InterProcessCom::InterProcessCom() { createPipe(); } InterProcessCom::~InterProcessCom() { close(this->receptionFdRead_); close(this->kitchenFdRead_); close(this->receptionFdWrite_); close(this->kitchenFdWrite_); } int InterProcessCom::createPipe() { int pfdsReception[2]; int pfdsKitchen[2]; if (pipe(pfdsReception) == -1) { std::cerr << "==> Reception pipe fatal error" << std::endl; return 1; } if (pipe(pfdsKitchen) == -1) { std::cerr << "==> Kitchen pipe fatal error" << std::endl; return 1; } this->receptionFdRead_ = pfdsReception[0]; this->receptionFdWrite_ = pfdsReception[1]; this->kitchenFdRead_ = pfdsKitchen[0]; this->kitchenFdWrite_ = pfdsKitchen[1]; return 0; } std::string InterProcessCom::readInformations(int fd) { // The reception has to send a "[1...9][0...9]*[-]" string to work bool process = true; char buf[BUFFER_SIZE + 1]; char *end = NULL; std::string finalStrSize; char *finder = 0; size_t i = 0; while (process) { read(fd, buf, BUFFER_SIZE); buf[BUFFER_SIZE] = '\0'; end = buf + sizeof(buf) / sizeof(buf[0]); finder = std::find(buf, end, '\n'); if (finder != std::end(buf)) { while (buf[i] != '\n') { finalStrSize += buf[i]; ++i; } return finalStrSize; } finalStrSize += buf; } return ""; } std::string InterProcessCom::readReceptionBuffer() { std::lock_guard<std::mutex> lock(mutex); std::string buffer = this->readInformations(this->receptionFdRead_); return buffer; } std::string InterProcessCom::readKitchenBuffer() { std::lock_guard<std::mutex> lock(mutex); std::string buffer = this->readInformations(this->kitchenFdRead_); return buffer; } void InterProcessCom::writeInformations(const std::string &infos, int fd) { // Lock the program if a mutex is already blocked std::lock_guard<std::mutex> lock(mutex); std::string finalStr; finalStr += infos + "\n"; // Send the size of the data and data write(fd, finalStr.c_str(), finalStr.size()); // release the locked mutex automatically at the end of the scope } void InterProcessCom::printOutput(std::string const &toPrint) { std::lock_guard<std::mutex> lock(debug_mutex); std::cout << toPrint << std::endl; } void InterProcessCom::writeToKitchenBuffer(const std::string &infos) { this->writeInformations(infos, this->kitchenFdWrite_); } void InterProcessCom::writeToReceptionBuffer(const std::string &infos) { this->writeInformations(infos, this->receptionFdWrite_); }
true
42a503a400eb0d9b867349ceff4b963726cc34f3
C++
maxymkuz/cs_first_semester
/algo_club/lection2/string.cpp
UTF-8
295
3.25
3
[]
no_license
#include <iostream> #include <algorithm> using namespace std; int main(){ string mine; string second = "to swap"; if (mine.empty()){ mine += "was empty"; mine.push_back('A'); mine.swap(second); mine.erase(0, 1); } cout<<mine; return 0; }
true
620530d2b0cc3782bad492cf5f7c3ca869096ac5
C++
hchc32/linux-hc
/c++pp/c++pratice/mytime0.cpp
UTF-8
299
2.703125
3
[]
no_license
#include <iostream> #include"mytime0.h" using namespace std; Time::Time() { hours = minutes = 0; } Time::Time(int h , int m) { hours = h; minutes = m; } void Time::AddMin(int m) { minutes += m; hours += minutes / 60; minutes %= 60; } int main() { return 0; }
true
11345c5876d88540fc3d0f6aa8e3d2147b1af872
C++
articainstruments/Example_Tutorials
/03_MUX_ANALOG/03_MUX_ANALOG.ino
UTF-8
1,447
3.265625
3
[]
no_license
/** * This example demonstrates how to read analog signals * It assumes there are potentiometers connected * to the 16 channels of the 74HC4067 mux/demux * * For more about the interface of the library go to * https://github.com/pAIgn10/MUX74HC4067 */ #include "MUX74HC4067.h" // Creates a MUX74HC4067 instance // 1st argument is the Arduino PIN to which the EN pin connects // 2nd-5th arguments are the Arduino PINs to which the S0-S3 pins connect MUX74HC4067 mux1(14, 9, 10, 11, 12); MUX74HC4067 mux2(17, 9, 10, 11, 12); void setup() { Serial.begin(9600); // Initializes serial port // Waits for serial port to connect. Needed for Leonardo only while ( !Serial ) ; // Configures how the SIG pin will be interfaced // e.g. The SIG pin connects to PIN A0 on the Arduino, // and PIN A0 is a analog input mux1.signalPin(A1, INPUT, ANALOG); mux2.signalPin(A2, INPUT, ANALOG); } // Reads the 16 channels and reports on the serial monitor // the corresponding value read by the A/D converter void loop() { int data; for (byte i = 0; i < 16; ++i) { // Reads from channel i. Returns a value from 0 to 1023 data = mux1.read(i); Serial.print(data); Serial.print(" "); } Serial.print(" | "); for (byte i = 0; i < 16; ++i) { // Reads from channel i. Returns a value from 0 to 1023 data = mux2.read(i); Serial.print(data); Serial.print(" "); } Serial.println(); delay(50); }
true
e11b55057d48747c2a979002c803fdde5999d3c3
C++
mhmdgad97/UGV_Localization_Maping_Matlab
/arduino codes/serial_send_test/serial_send_test.ino
UTF-8
1,316
2.84375
3
[]
no_license
/* Blink Turns on an LED on for one second, then off for one second, repeatedly. This example code is in the public domain. */ // Pin 13 has an LED connected on most Arduino boards. // give it a name: // the setup routine runs once when you press reset: void setup() { // initialize the digital pin as an output. Serial.begin(9600); } // the loop routine runs over and over again forever: void loop() { Serial.println("0300000300"); delay(50); Serial.println("0900000300"); delay(2000); Serial.println("0900000101"); delay(2000); Serial.println("0300000101"); delay(2000); Serial.println("0000000051"); delay(2000); Serial.println("0000000011"); delay(20); Serial.println("0000000011"); delay(20); Serial.println("0000000011"); delay(20); Serial.println("0000000011"); delay(20); Serial.println("0000000011"); delay(20); Serial.println("0000000011"); delay(20); Serial.println("0000000011"); delay(20); Serial.println("0000000011"); delay(20); Serial.println("0000000011"); delay(20); Serial.println("0000000011"); delay(20); Serial.println("0000000011"); delay(20); Serial.println("0000000011"); delay(20); Serial.println("0000000011"); delay(20); }
true
ac7690d407dc4983cdadc3f4ac5815f5525a2427
C++
solo1d/c-Network
/内存池/main.cpp
UTF-8
1,003
3.03125
3
[]
no_license
/* * 内存池测试 * 2020.4.4 21:47 */ #include "Alloctor.h" #include <iostream> #include <thread> #include <mutex> //互斥锁 #include "CELLTimestamp.hpp" /* * 线程部分 */ std::mutex m; const int tCount = 8; const int mCount = 100000; //所有线程申请内存次数的最大值 const int nCount = mCount/tCount; //每个线程申请的次数 void workFun(int index){ char* data[nCount]; for (size_t i =0; i < nCount; i++){ data[i] = new char[ (unsigned)(rand()) % 1024 +1 ]; } for (size_t i =0; i < nCount; i++){ delete[] data[i]; } /* for ( int n = 0; n < nCount; n++){ } */ } int main(void){ std::thread t[tCount]; for ( int n=0; n < tCount; n++) t[n] = std::thread(workFun, n); CELLTimestamp tTime; for ( int n=0; n < tCount; n ++) t[n].join(); std::cout << tTime.getElapsedTimeInMilliSec() << ", Hello ,main thread" << std::endl; return 0; }
true
d920cbde108410d8a6b2e8bde007e4af5e65de22
C++
cashinqmar/DSALGO
/pepcoding/IP/ImageMultiplication.cpp
UTF-8
1,352
2.796875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; #define mod 1000000007 class TreeNode { public: TreeNode* left=NULL; TreeNode* right=NULL; int val; TreeNode(int val){ this->val=val; } }; void helper(TreeNode *root1,TreeNode* root2,long long int &ans){ if(root1==NULL||root2==NULL)return ; ans=(ans%mod+(root1->val*root2->val)%mod)%mod; helper(root1->right,root2->left,ans); helper(root1->left,root2->right,ans); } long long int image(TreeNode*root){ if(!root)return 0; long long int ans=(root->val)*(root->val); helper(root->left,root->right,ans); return ans; } int main(){ int t; cin>>t; while(t--){ int n; cin>>n; unordered_map<int,TreeNode*> m; int par; int child; char dir; TreeNode *root=NULL; bool first=false; for(int i=0;i<n;i++){ cin>>par; cin>>child; cin>>dir; if(m.find(par)==m.end()){ m[par]=new TreeNode(par); } if(first==false){ root=m[par]; first=true; } if(m.find(child)==m.end()){ m[child]=new TreeNode(child); } if(dir=='L'){ m[par]->left=m[child]; } if(dir=='R'){ m[par]->right=m[child]; } } cout<<image(root)<<"\n"; } }
true
d931140614509596353cf0206b8c1e01f0765369
C++
Jay-Nindu/OnTheRoad
/OnTheRoad.cpp
UTF-8
2,016
2.875
3
[]
no_license
#include <bits/stdc++.h> #define MAX_N INT_MAX/2 using namespace std; int main(){ int nodeAmount, edgeAmount, stallAmount, start, end; cin >> nodeAmount >> edgeAmount >> stallAmount >> start >> end; vector < vector< pair <int, int> > >adjacencyList; vector < pair <int, int> > emptyVector; for(int i = 0; i < nodeAmount; i++ ){ adjacencyList.push_back(emptyVector); } int currentNode, otherNode, currentWeight; for(int i = 0; i < edgeAmount; i++){ cin >> currentNode >> otherNode >> currentWeight; adjacencyList[currentNode].push_back(make_pair(currentWeight, otherNode)); adjacencyList[otherNode].push_back(make_pair(currentWeight, currentNode)); } vector<int> stalls(stallAmount); for(int i = 0; i < stallAmount; i++){ cin >> currentNode; stalls[i] = currentNode; } vector <int> dist(nodeAmount, MAX_N); priority_queue <pair<int, int> > q; q.push(make_pair(0, start)); int DistS; while(!q.empty()){ currentNode = q.top().second; DistS = -1*(q.top().first); q.pop(); if(dist[currentNode] > DistS){ dist[currentNode] = DistS; for(pair<int, int> i : adjacencyList[currentNode]){ if(dist[i.second] > i.first + DistS){ q.push(make_pair( -1*(i.first + DistS), i.second)); } } } } vector <int> newDist(nodeAmount, MAX_N); q.push(make_pair(0, end)); while(!q.empty()){ currentNode = q.top().second; DistS = -1*(q.top().first); q.pop(); if(newDist[currentNode] > DistS){ newDist[currentNode] = DistS; for(pair<int, int> i : adjacencyList[currentNode]){ if(newDist[i.second] > i.first + DistS){ q.push(make_pair( -1*(i.first + DistS), i.second)); } } } } priority_queue <pair <int, int > > output; for(int i = 0; i < stallAmount; i++){ output.push(make_pair(-1*(dist[stalls[i]]) + -1*(newDist[stalls[i]]), -1*(stalls[i]))); } cout << -1*(output.top().first) << " " << -1*(output.top().second); return 0; }
true
7e2e2fa9b5913a1652d7850e68f6a9e30d3c1516
C++
TheOctan/Labs-in-cpp
/Basics of programming/Laba №8/Task 7/Task1-7.cpp
UTF-8
194
2.921875
3
[]
no_license
#include<iostream> #include<cmath> using namespace std; double mix(double n) { return sqrt(n) + n; } int main() { cout << mix(6) / 2 + mix(13) / 2 + mix(21) / 2; system("pause"); return 0; }
true
5e82a619a9923ec2fcf14c6888db93e21459ecda
C++
NguyenThanh55/C-
/Danh sách đặc-Bài 2.cpp
UTF-8
3,079
3.09375
3
[]
no_license
//Bai 3 //Them pt cuoi ds co van de #include <iostream> #include <conio.h> using namespace std; struct Node { int info; Node* link; }; Node* first; void init() { first = NULL; } void process_list() { Node* p; p = first; while (p != NULL) { cout << p->info << endl; p = p->link; } } Node* search(int x) { Node* p = first; while (p != NULL && p->info != x) { p = p->link; } return p; } void insertFirst(int x) { Node* p = new Node; p->info = x; p->link = first; first = p; } int deleteFirst() { if (first != NULL) { Node* p = first; first = first->link; delete p; return 1; } return 0; } void insertLast(int x) { Node* p = new Node; p->info = x; p->link = NULL; Node* q = first; if (q->link != NULL) q=q->link; q->link = p; } void deleteLast() { Node* p, * q = new Node; p = first; if (p != NULL) while (p->link != NULL) { q = p; p = p->link; } q->link = NULL; delete p; } int Delete(int x) { Node* p = first, *q = new Node; q->info = x; if (p != NULL) { while (p->info == q->info) { //q = p; p = p->link; } p->link = p->link->link; delete q; return 1; } return 0; } int main() { int chon; bool in = false; do { system("cls"); cout << "Menu\n1.Khoi tao ds rong\n2.Xuat\n3.Tim pt\n4.Them pt vao dau ds\n5.Xoa pt dau ds\n6.Them pt cuoi ds\n7.Xoa pt cuoi ds\n8.Tim va xoa pt\nBan chon:"; cin >> chon; switch (chon) { case 1: init(); in = true; break; case 2: if (in) { process_list(); } else cout << "Ban vui long tao ds rong!\n"; break; case 3: if (in) { int x; cout << "Gia trị ban muon tim: "; cin >> x; if (search(x) != NULL) cout << "Sucessful!\n"; else cout << "Failed!\n"; } else cout << "Ban vui long tao ds rong!\n"; break; case 4: { if (in) { int x; cout << "Phan tu ban muon them vao dau ds la: "; cin >> x; insertFirst(x); cout << "Sucessful!\n"; } else cout << "Ban vui long tao ds rong!\n"; break; } case 5: if (in) { if (deleteFirst() == 1) cout << "Sucessful!\n"; else cout << "Failed!\n"; } else cout << "Ban vui long tao ds rong!\n"; break; case 6: if (in) { int x; cout << "Gia tri ban muon them: "; cin >> x; insertLast(x); cout << "Sucessful!\n"; } else cout << "Ban vui long tao ds rong!\n"; break; case 7: if (in) { cout << "Sau khi xoa :"; deleteLast(); cout << "Secessful!\n"; } else cout << "Ban vui long tao ds rong!\n"; break; case 8: if (in) { int x; cout << "Gia tri ban muon tim va xoa: "; cin >> x; if (search(x) != NULL) { Delete(x); cout << "Sucessful!\n"; } else cout << "Failed!\n"; } else cout << "Ban vui long tao ds rong!\n"; break; default : cout << "Ban chon thoat!\n"; } _getch(); } while (chon > 0 && chon < 9); }
true
733bf84a131cadcf621bc26b8324157ad42f5f60
C++
skyqnaqna/MyCode
/Algorithm/Algorithm/BOJ_1197.cpp
UTF-8
1,117
2.953125
3
[]
no_license
#include <iostream> #include <algorithm> #include <vector> using namespace std; int n,m,u,v,cost,result(0); int parent[10001]; vector <pair<int, pair<int,int> > > edge; int getParent(int); bool cmpSameParent(int,int); void unionEdge(int,int); void kruskal(); int main() { scanf("%d %d", &n, &m); for (int i = 1; i <= m; ++i) { scanf("%d %d %d", &u, &v, &cost); edge.push_back(make_pair(cost, make_pair(u,v))); } for (int i = 1; i <= n; ++i) parent[i] = i; sort(edge.begin(),edge.end()); kruskal(); return 0; } int getParent(int i) { if (parent[i] == i) return i; else return parent[i] = getParent(parent[i]); } bool cmpSameParent(int a, int b) { a = getParent(a); b = getParent(b); if ( a == b ) return true; else return false; } void unionEdge(int u, int v) { u = getParent(u); v = getParent(v); parent[v] = u; } void kruskal() { for (int i = 0; i < m; ++i) { if (cmpSameParent(edge[i].second.first, edge[i].second.second) == false) { unionEdge(edge[i].second.first, edge[i].second.second); result += edge[i].first; } } printf("%d\n", result); }
true
0ea9990c1652f8b19a70d8ba391d17a5e3648d47
C++
Tignite/ALMA
/Abgabe4/Student.h
UTF-8
763
2.96875
3
[]
no_license
#ifndef STUDENT_H_ #define STUDENT_H_ #include <string> /* string */ #include <iostream> /* cin, cout */ #include <stdlib.h> /* srand, rand */ typedef struct Student { public: Student(); Student(long matnr, short* geb, short studienfach, short fachsemester); virtual ~Student(); void print(); bool setMatnr(long matnr); bool setGeb(short* geb); bool setStudienfach(short studienfach); bool setFachsemester(short fachsemester); long getMatnr(); std::string getGeb(); long getGebLong(); short getStudienfach(); short getFachsemester(); void randMatnr(); private: long matnr; short geb [3]; short studienfach; short fachsemester; int pseudoRand(int limit); bool schaltjahr(short n); void randGeb(); }Student; #endif /* STUDENT_H_ */
true
386053250c0570089f7ad51a3c23cced44c6fdf5
C++
tiankonguse/ACM
/tmpleate-2020/code/Graph/弦图判断.cpp
UTF-8
1,859
2.890625
3
[]
no_license
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #include <vector> #include <set> using namespace std; const int N=1005; /* 弦图定义:不存在环满足(长度大于3)&&(环上任意非相邻点间无边) 的一个图。 完美消除序列的性质是: 对于序列中第i个点Vi。 令S={Vj | (j>i) && ((Vi,Vj) in E)},那么S+Vi成一个团。 一个图是弦图当且仅当存在完美消除序列. 另有求弦图色数的经典性质: { 色数(用最少种颜色涂满图中的点,使得每条边两端的点颜色都不同)>=团数(最大团的点数) 因为是弦图,由完美消除序列的性质可以构造得色数=团数,于是达到下界。 于是直接利用完美消除序列的性质求出团数即可。 } 使用说明: 点标号从1~n,mat[x][y]=1表示有边. */ int n,m; int label[N]; int Cnt[N]; int mat[N][N]; int Q[N]; vector <int> vec; void make_sequence(){ for (int i=1;i<=n;i++) Cnt[i]=label[i]=0; for (int i=n;i>=1;i--){ int Max=-1; int Maxi=-1; for (int j=1;j<=n;j++) if (!label[j] && Cnt[j]>Max){ Max=Cnt[j]; Maxi=j; } label[Maxi]=i; Q[i]=Maxi; for (int j=1;j<=n;j++) if (label[j]==0 && mat[Maxi][j]) Cnt[j]++; } } bool check(){ for (int i=1;i<=n;i++){ vec.clear(); for (int j=1;j<=n;j++) if (mat[i][j] && label[j]>label[i]) vec.push_back(j); for (int j=1;j<vec.size();j++) if (label[vec[j]]<label[vec[0]]) swap(vec[j],vec[0]); for (int j=1;j<vec.size();j++) if (!mat[vec[0]][vec[j]]) return false; } return true; } int main(){ while (1){ scanf("%d%d",&n,&m); if (!n && !m) break; memset(mat,0,sizeof(mat)); for (int i=0;i<m;i++){ int x,y; scanf("%d%d",&x,&y); mat[x][y]=mat[y][x]=1; } make_sequence(); if (check()) printf("Perfect\n\n"); else printf("Imperfect\n\n"); } }
true
fdf2166b3f6685f19eaa0cd7a90f5b672164a695
C++
Facenapalm/interpreter
/source/values.h
UTF-8
2,086
3.34375
3
[ "MIT" ]
permissive
#ifndef VALUES_H #define VALUES_H #include <string> enum ValueType { vtNone, vtInteger, vtString, vtBoolean, vtReal }; typedef long long Integer; typedef std::string String; typedef bool Boolean; typedef double Real; class Value { public: virtual Value *clone() const = 0; virtual ValueType get_type() const; virtual Integer to_integer() const = 0; virtual String to_string() const = 0; virtual Boolean to_boolean() const = 0; virtual Real to_real() const = 0; virtual ~Value() = default; }; class IntegerValue: public Value { private: Integer value; public: explicit IntegerValue(Integer value); explicit IntegerValue(const String &str); Value *clone() const override; ValueType get_type() const override; Integer to_integer() const override; String to_string() const override; Boolean to_boolean() const override; Real to_real() const override; }; class StringValue: public Value { private: String value; public: explicit StringValue(const String &value); Value *clone() const override; ValueType get_type() const override; Integer to_integer() const override; String to_string() const override; Boolean to_boolean() const override; Real to_real() const override; }; class BooleanValue: public Value { private: Boolean value; public: explicit BooleanValue(Boolean value); explicit BooleanValue(const String &str); Value *clone() const override; ValueType get_type() const override; Integer to_integer() const override; String to_string() const override; Boolean to_boolean() const override; Real to_real() const override; }; class RealValue: public Value { private: Real value; public: explicit RealValue(Real value); explicit RealValue(const String &str); Value *clone() const override; ValueType get_type() const override; Integer to_integer() const override; String to_string() const override; Boolean to_boolean() const override; Real to_real() const override; }; #endif // VALUES_H
true
b4bc7f936379ac4143e9f2d0c83405a3f5a6754e
C++
nguyenlamlll/directx-game
/Game/Game/ClimbArea.cpp
UTF-8
960
2.796875
3
[ "MIT" ]
permissive
#include "stdafx.h" #include "ClimbArea.h" ClimbArea::ClimbArea(float x, float y, float width, float height, bool isDebug) : GameObject(x, y, width, height, Tag::ClimbAreaTag) { this->setPosition(D3DXVECTOR2(x, y)); m_isDebugVisible = isDebug; if (isDebug) { m_debugSprite = new Sprite(L"Resources/climb-area.png", D3DCOLOR_XRGB(106, 148, 1)); m_debugSprite->setPositionX(x); m_debugSprite->setPositionY(y); } else { m_debugSprite = nullptr; } } ClimbArea::~ClimbArea() { if (m_debugSprite != nullptr) { delete m_debugSprite; } } void ClimbArea::setIsDebugVisible(bool value) { m_isDebugVisible = value; } Box ClimbArea::GetBoundingBox() { Box box; box.x = x - width / 2 + 20; box.y = y - height / 2; box.width = width - 40; box.height = height; box.vx = vx; box.vy = vy; return box; } void ClimbArea::Update(float deltaTime) { } void ClimbArea::Draw() { if (m_isDebugVisible == true) { m_debugSprite->Draw(); } }
true
e71c0221675effef2432f09d231b340dec15f47c
C++
matyle/DesignPatternCPP
/03Observer/Observer.cc
UTF-8
782
2.78125
3
[]
no_license
//观察者和观察目标 //使用weak_ptr和shared_ptr实现,解决线程安全,以及循环引用问题 //一个观察目标中(被观察)可能有多个观察者 //而每个观察者对应一个观察目标 //观察目标会notify观察者,同时观察者会根据通知做出响应 //观察者类会添加目标,移除目标。由于移除目标(这时不知道目标对象的生死) #include<iostream> #include<memory> #include<vector> using namespace std; //公众号订阅者 class Observer { private: /* data */ public: Observer(/* args */); ~Observer(); }; //目标 girls 公众号 class Subject { private: /* data */ vector<weak_ptr<Observer>> observers_; //多个观察者 public: Subject(/* args */); ~Subject(); };
true
1773b53b9adcac28d4c75854ea4a194486a97a0b
C++
Shouraya/OOPs-Lab-Assignment
/Lab Assignment 8/5.cpp
UTF-8
626
3.21875
3
[]
no_license
#include<iostream> #include<stdio.h> #include<fstream> #include<string> using namespace std; int main() { string str; cout<<"Enter a String: "<<endl; getline(cin, str); cout<<"Length of the string is: "<<sizeof(str)/sizeof(str[0])<<endl; ofstream ofile("StringFile.txt", ios::out); int i=0; char ch; cout<<"Writing to file...."<<endl; while(str[i]!='\0') { ofile.put(str[i]); i++; } ofile.close(); ifstream ifile("StringFile.txt", ios::in); cout<<"The contents of File are..."<<endl; while(ifile.get(ch)) { cout<<ch; } return 0; }
true
a52b46037d10f0cbbe9a6b961e751586e27bb7e5
C++
SamuelFlo/Extra_Lab5SamuelFlores
/platos.h
UTF-8
724
2.609375
3
[ "MIT" ]
permissive
#ifndef PLATOS_H #define PLATOS_H #include <iostream> #include <string> #include <vector> #include "ingredientes.h" using namespace std; class Platos{ public: vector<Ingredientes*>cantidad; string origen; int cantidadsabor; int registrococinado; int precio; int valoracionpromedio; Platos(); Platos(string,int,int,int,int); //getter Ingredientes* getCantidad(int); string getOrigen(); int getCantidadsabor(); int getRegistrococinado(); int getPrecio(); int getValoracionpromedio(); //setter void setCantidad(Ingredientes*); void setOrigen(string); void setCantidadsabor(int); void setPrecio(int); void setRegistrococinado(int); void setValoracionpromedio(int); }; #endif
true
d3cf1eed8627503e3c6a4e31526bb4907f448fbf
C++
esteve/gpt
/src/theseus/theSetBelief.h
UTF-8
6,430
2.578125
3
[]
no_license
// Theseus // theSetBelief.h -- Set Belief Implementation // // Blai Bonet, Hector Geffner // Universidad Simon Bolivar, 1998, 1999, 2000, 2001, 2002 #ifndef _theSetBelief_INCLUDE_ #define _theSetBelief_INCLUDE_ #include <iostream> #include <set> #include <map> #include <theseus/theBelief.h> #include <theseus/theBeliefCache.h> #include <theseus/theNonDetModel.h> #include <theseus/theUtils.h> /////////////////////////////////////////////////////////////////////////////// // // Set Belief Class // class setBeliefClass : public beliefClass { private: // members set<int > bel; // static members static nonDetModelClass* model; // private methods setBeliefClass( const setBeliefClass& belief ) { *this = belief; } // private virtual methods virtual void print( ostream& os ) const { set<int>::const_iterator it; os << "[ "; for( it = bel.begin(); it != bel.end(); ++it ) os << *it << " "; os << "]"; } public: // constructors/destructors setBeliefClass() { } virtual ~setBeliefClass() { } // methods const nonDetModelClass* getModel( void ) const { return( model ); } void clean( void ) { bel.erase( bel.begin(), bel.end() ); } // virtual methods virtual void setModel( modelClass* m ) { model = dynamic_cast<nonDetModelClass*>( m ); } virtual beliefClass::constructor_t getConstructor( void ) const { return( (beliefClass *(*)(void)) &setBeliefClass::constructor ); } virtual bool check( void ) const { return( bel.size() > 0 ); } virtual bool check( int state ) const { set<int>::const_iterator it; for( it = bel.begin(); it != bel.end(); ++it ) if( state == *it ) return( true ); return( false ); } virtual void checkModelAvailability( modelClass* model ) const { static set<int>::const_iterator it; for( it = bel.begin(); it != bel.end(); ++it ) model->checkModelFor( *it ); } virtual const map<int,float>* cast( void ) const; virtual void insert( int state, float probability ) { if( !check( state ) ) bel.insert( state ); } virtual unsigned randomSampling( void ) const { return( ::randomSampling( bel ) ); } virtual void nextPossibleObservations( int action, map<int,float> &result ) const; virtual int plausibleState( int action, int observation ) const; virtual beliefClass* updateByA( beliefCacheClass* cache, bool useCache, int action ) const; virtual beliefClass* updateByAO( beliefCacheClass* cache, bool useCache, int action, int observation ) const; virtual beliefClass* clone( void ) const { return( new setBeliefClass( *this ) ); } virtual float heuristicValue( void ) const { return( heuristic == NULL ? 0.0 : heuristic->value( this ) ); } virtual void support( set<int> &result ) const { set<int>::const_iterator it; result.clear(); for( it = bel.begin(); it != bel.end(); ++it ) result.insert( *it ); } virtual int supportSize( void ) const { return( bel.size() ); } // operator overload virtual beliefClass& operator=( const setBeliefClass& b ) { bel = b.bel; return( *this ); } virtual beliefClass& operator=( const beliefClass& b ) { *this = (setBeliefClass&)b; return( *this ); } virtual bool operator==( const setBeliefClass& b ) const { return( (bel == b.bel) ); } virtual bool operator==( const beliefClass& b ) const { return( *this == (setBeliefClass&)b ); } // hash virtual methods virtual unsigned hashDataFunction( void ) const; virtual void* hashDataCopy( void ) const { return( (void*)clone() ); } virtual bool hashDataCompare( const void* data ) const { return( !(bel == ((setBeliefClass*)data)->bel) ); } virtual void hashDataWrite( ostream& os ) const { write( os ); } virtual void* hashDataRead( istream& is ) const { return( beliefClass::read( is ) ); } // serialization static void checkIn( void ); virtual void write( ostream& os ) const; static setBeliefClass* read( istream& is ); static setBeliefClass* constructor( void ); static void fill( istream& is, beliefClass* bel ); static void fill( istream& is, setBeliefClass* bel ); // friends friend class setBeliefHashClass; friend class searchPOMDPClass; friend class nonDetModelClass; }; /////////////////////////////////////////////////////////////////////////////// // // Set Belief Hash Class // class setBeliefHashClass : public beliefHashClass { private: // private methods setBeliefHashClass( const setBeliefHashClass& hash ) { *this = hash; } public: // constructors/destructors setBeliefHashClass() { } virtual ~setBeliefHashClass() { clean(); } // virtual hash functions (since this is a hashClass derived class) virtual unsigned dataFunction( const void* data ) { return( ((setBeliefClass*)data)->hashDataFunction() ); } virtual void* dataCopy( const void* data ) { return( ((setBeliefClass*)data)->hashDataCopy() ); } virtual bool dataCompare( const void* newData, const void* dataInHash ) { return( !(*((setBeliefClass*)newData) == *((setBeliefClass*)dataInHash)) ); } virtual void dataDelete( void* data ) { delete (setBeliefClass*)data; } virtual void dataPrint( ostream& os, const void* data ) { os << "[ " << *((setBeliefClass*)data) << "] "; } virtual void dataWrite( ostream& os, const void* data ) const { ((setBeliefClass*)data)->write( os ); } virtual void* dataRead( istream& is ) { return( beliefClass::read( is ) ); } virtual void statistics( ostream& os ) { hashClass::statistics( os ); } // virtual quantization functions virtual void quantize( bool useCache, bool saveInHash, const beliefClass* belief, hashEntryClass*& quantization ); // serialization static void checkIn( void ); virtual void write( ostream& os ) const; static setBeliefHashClass* read( istream& is ); static setBeliefHashClass* constructor( void ); static void fill( istream& is, setBeliefHashClass* hash ); }; #endif // _theSetBelief_INCLUDE
true
97e21cf2d7c89e9620e79a7bb072030994fb0693
C++
renanleonellocastro/cplusplus_header_generator
/src/gerador.cpp
UTF-8
2,803
3.25
3
[ "MIT" ]
permissive
#include "gerador.hpp" #include <sstream> namespace GeradorCpp { Gerador::Gerador() : m_classeErro("erro", false) { } void Gerador::adicionarClasse(std::string nome, bool classeBase) { Classe c(nome, classeBase); m_classes.push_back(c); } std::string Gerador::gerarCodigo() { unsigned int i; unsigned int j; unsigned int k; std::stringstream retorno; for (i = 0; i < m_classes.size(); ++i) { bool primeiraHeranca = false; retorno << "class " << m_classes[i].getNome(); for (j = 0; j < m_classes[i].getQtdRelacionamentos(); ++j) { if (m_classes[i].getRelacionamento(j).getTipo() == HERANCA) { if (!primeiraHeranca) { primeiraHeranca = true; retorno << ": public " << m_classes[i].getRelacionamento(j).getNomeClasseRelacionada(); } else { retorno << ", public " << m_classes[i].getRelacionamento(j).getNomeClasseRelacionada(); } } } retorno << "\n{\npublic:\n"; for (j = 0; j < m_classes[i].getQtdMetodos(); ++j) { retorno << "\t" + m_classes[i].getMetodo(j).getTipoRetorno() << " " << m_classes[i].getMetodo(j).getNome() << "("; for (k = 0; k < m_classes[i].getMetodo(j).getQtdParametros(); ++k) { retorno << m_classes[i].getMetodo(j).getParametro(k).tipo << " " << m_classes[i].getMetodo(j).getParametro(k).nome; if (k != m_classes[i].getMetodo(j).getQtdParametros() - 1) { retorno << ", "; } } retorno << ");\n"; } retorno << "private:\n"; for (j = 0; j < m_classes[i].getQtdRelacionamentos(); ++j) { if (m_classes[i].getRelacionamento(j).getTipo() != HERANCA) { retorno << "\t" << m_classes[i].getRelacionamento(j).getNomeClasseRelacionada() << " " << "m_" << m_classes[i].getRelacionamento(j).getNomeClasseRelacionada() << ";" << "\n"; } } for (j = 0; j < m_classes[i].getQtdAtributos(); ++j) { retorno << "\t" + m_classes[i].getAtributo(j).tipo << " " << m_classes[i].getAtributo(j).nome << ";" << "\n"; } retorno << "};\n\n"; } return retorno.str(); } Classe *Gerador::getClassePorNome(std::string nome) { unsigned int i; bool achou = false; for (i = 0; i < m_classes.size(); ++i) { if (m_classes[i].getNome() == nome) { achou = true; break; } } if (achou) { return &m_classes[i]; } else { std::cout << "Classe nao encontrada!" << std::endl; return &m_classeErro; } } }
true
5bf1b77d3b80489b7962cbc07eca85ee3550fc24
C++
VladSach/ITG-Quoridor
/include/Player.h
UTF-8
1,688
3.28125
3
[ "MIT" ]
permissive
#ifndef PLAYER_H #define PLAYER_H #include <vector> #include <utility> #include "utility.h" class IPlayer { private: int m_X; int m_Y; int m_EndY; const char* m_Name; public: virtual ~IPlayer() {}; virtual const char *getName() const = 0; virtual int getWallsCounter() const = 0; virtual coordinates getPosition() const = 0; virtual int getEndY() const = 0; virtual void reduceWall() = 0; virtual void returnWall() = 0; virtual bool needsToTakeInput() = 0; virtual void move(const int x, const int y) = 0; // rhs means "right hand side" bool operator == (const IPlayer &rhs) const { return this->m_X == rhs.m_X && this->m_Y == rhs.m_Y && this->m_Name == rhs.m_Name && this->m_EndY == rhs.m_EndY; } private: IPlayer& operator=(const IPlayer&); }; class Player : public IPlayer { private: int m_X; int m_Y; int m_EndY; const char *m_Name; int m_WallsCounter = WallsAmount; public: Player(const int x, const int y, const char *name); Player() = default; ~Player() = default; const char *getName() const; int getWallsCounter() const; coordinates getPosition() const; int getEndY() const; void reduceWall(); void returnWall(); bool needsToTakeInput(); void move(const int x, const int y); Player& operator=(const Player& rhs) { // Guard self assignment if (this == &rhs) return *this; this->m_X = rhs.m_X; this->m_Y = rhs.m_Y; this->m_Name = rhs.m_Name; this->m_EndY = rhs.m_EndY; return *this; }; }; #endif // PLAYER_H
true
c1d47ffc33bbd2f0f74f6f6c30a56eec9b9033ba
C++
fashaikh/Workshops
/IoT Code FINAL/GetMacAddress/GetMacAddress.ino
UTF-8
426
2.5625
3
[]
no_license
/* * this code retrieves the MAC Address of your ESP board and * publishes it to the Serial Monitor * Load this sketch and open the Serial Monitor */ #include <ESP8266WiFi.h> void setup(){ Serial.begin(115200); delay(500); } void loop(){ Serial.println(); Serial.print("MAC: "); Serial.println(WiFi.macAddress()); delay(2000); } //http://openwifi //Add your MAC Address to get access to open wifi
true
2f1e3f17ed3e783675eebf973f72891d3e219959
C++
DanNixon/CSC8501_AdvancedProgrammingForGames
/Coursework/CourseworkLib/Decoder.cpp
UTF-8
3,994
3.109375
3
[]
no_license
/** @file */ #include "Decoder.h" #include <algorithm> #include <sstream> using namespace CircuitSimulator; namespace Coursework { /** * @brief Measures the hamming distance between two strings. * @param a First string * @param b Second string * @return Hamming distance */ const size_t Decoder::HammingDist(const std::string &a, const std::string &b) { size_t dist = 0; auto aIt = a.cbegin(); auto bIt = b.cbegin(); while (aIt != a.cend() && bIt != b.cend()) { if (*(aIt++) != *(bIt++)) dist++; } return dist; } /** * @brief Creates a new decoder with a given Trellis. * @param trellis Trellis to use for decoding */ Decoder::Decoder(const Trellis &trellis) : m_trellis(trellis) { } Decoder::~Decoder() { } /** * @brief Decodes a bit stream using the trellis. * @param observations Bit stream received * @param results Reference to storage for decoded result * @return Best path metric */ size_t Decoder::decode(const CircuitSimulator::BitStream &observations, BitStream &results) { std::vector<std::string> strObs; strObs.reserve(observations.size() / 2); for (auto it = observations.cbegin(); it != observations.cend();) { bool bits[] = {*(it++), *(it++)}; std::stringstream o; o << bits[0] << bits[1]; strObs.push_back(o.str()); } return decode(strObs, results); } /** * @brief Decodes a sequence of bit pairs using the trellis. * @param observations Bit pairs (as vector of string) received * @param results Reference to storage for decoded result * @return Best path metric */ size_t Decoder::decode(const std::vector<std::string> &observations, BitStream &results) { // Keep track of all nodes for deletion later (this is lazy) std::vector<ViterbiNode *> garbage; ViterbiNode **states = new ViterbiNode *[m_trellis.numStates()]; ViterbiNode **statesNext = new ViterbiNode *[m_trellis.numStates()]; // Initial states for (size_t i = 0; i < m_trellis.numStates(); i++) { statesNext[i] = new ViterbiNode(); garbage.push_back(statesNext[i]); } // Process trellis and build paths for (auto obsIt = observations.begin(); obsIt != observations.end(); ++obsIt) { // Move current trellis frame for (size_t i = 0; i < m_trellis.numStates(); i++) { states[i] = statesNext[i]; statesNext[i] = new ViterbiNode(); garbage.push_back(statesNext[i]); } // Process states in current trellis frame for (size_t i = 0; i < m_trellis.numStates(); i++) { // Get mappings std::vector<TrellisMapping> mappings; m_trellis.getMappingsForDestinationState(mappings, i); // Compute new path metrics and find best branch TrellisMapping bestMapping; bestMapping.tempCost = std::numeric_limits<size_t>::max(); // For each mapping to this state in th trellis for (size_t j = 0; j < mappings.size(); j++) { mappings[j].tempCost = states[mappings[j].srcState]->pathMetric + HammingDist(mappings[j].code, *obsIt); // Check if this is the new lowest cost if (mappings[j].tempCost < bestMapping.tempCost) bestMapping = mappings[j]; } // Add best branch to tree statesNext[i]->bit = bestMapping.bit; statesNext[i]->pathMetric = bestMapping.tempCost; statesNext[i]->parent = states[bestMapping.srcState]; } } // Find best path (lowest path metric) ViterbiNode *best = statesNext[0]; for (size_t i = 1; i < 4; i++) if (statesNext[i]->pathMetric < best->pathMetric) best = statesNext[i]; size_t bestPathMetric = best->pathMetric; // Backtrack do { results.push_back(best->bit); best = best->parent; } while (best->parent != nullptr); // Backtracking gives reverse path std::reverse(results.begin(), results.end()); // Free memory delete[] states; delete[] statesNext; for (auto it = garbage.begin(); it != garbage.end(); ++it) delete *it; return bestPathMetric; } }
true
8caa318aff85e20565e0c04397038053856bb75f
C++
InfiBeyond/CCC
/WATERLOO/2015/2015S3/main.cpp
UTF-8
1,548
3.359375
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> using namespace std; //we nee to keep track of the original sequence even after we sorted it. bool compare(vector<int> a, vector<int> b) { int lena = a.size(); int lenb = b.size(); if(lena < lenb) { return true; } else if(lena == lenb) { if(a[lena-1]<b[lenb-1]) { return true; } } return false; } int comparePlane(vector<int> *p, vector<int> *g,int plane = 0, int gate = 0) { if(p->empty()||g->empty()||plane==p->size()||gate==g->size()) { return 0; } if((*p)[plane] == (*g)[gate]) { g->erase(g->begin(),g->begin()+1); return 1; } else if((*p)[plane] > (*g)[gate]) { gate++; } else { plane++; } comparePlane(p,g,plane,gate); } int main() { int g; int p; cin >> g >> p; int temp; vector<vector<int>> plane; for(int i = 0; i<p; i++) { cin >> temp; plane.emplace_back(vector<int>{}); for(int j = 1; j <= temp; j++) { plane[i].emplace_back(j); } } sort(plane.begin(),plane.end(),compare); vector<int> gate; for(int i = 1; i<=g; i++) { gate.emplace_back(i); } int ans = 0; for(int i = 0; i < p; i++) { temp = comparePlane(&plane[i],&gate); if(temp == 0) { cout << ans; return 0; } ans += temp; } cout <<ans; return 0; }
true
133e44c04a9ab4ad0801be76c01855c1a766575f
C++
0xl2oot/notes
/面向对象/AB.cpp
UTF-8
640
3.546875
4
[]
no_license
#include <iostream> using namespace std; class AB { public: AB(int i, int j) { a = i; b = j; } AB(int i) { a = i; b = i*i; } int Add(int x, int y) { a = x; b = y; return a + b; } int Add(int x) { a = b = x; return a + b; } int Add() { return a + b; } int aout() { return a; } int bout() { return b; } private: int a, b; }; int main(int argc, char *argv[]) { AB a(5, 8), b(7); cout<<"a = "<<a.aout()<<", "<<a.bout()<<endl; cout<<"b = "<<b.aout()<<", "<<b.bout()<<endl; int i = a.Add(); int j = a.Add(4); int k = a.Add(3, 9); cout<<i<<endl<<j<<endl<<k<<endl; }
true
cf7625d6003b0508f71edcf3b240864a8c1e8014
C++
mlupa29/TestLiczbZespolonych
/src/LZespolona.cpp
UTF-8
2,978
3.1875
3
[ "MIT" ]
permissive
#include "LZespolona.hh" //funkcja wyswietlajaca liczbe zespolona void Wyswietl(LZespolona Skl1) { cout << "(" << Skl1.re << showpos << Skl1.im << noshowpos << "i)"; } //funkcja wczytujaca liczbe zespolona void Wczytaj(LZespolona& Skl1) { char tab[3]; cin >> tab[0]; cin >> Skl1.re; cin >> Skl1.im; cin >> tab[1]; cin >> tab[2]; if (tab[0] != '(' || tab[1] != 'i' || tab[2] != ')') { //sprawdzenie bledu zapisu podczas wejscia cin.setstate(ios_base::badbit); } } //funkcja wyswietlajaca liczbe zespolona ostream& operator << (ostream& wyj, LZespolona Skl1) { wyj << "(" << Skl1.re << showpos << Skl1.im << noshowpos << "i)"; return wyj; } /*Fukcja porownania liczb zespolonych*/ bool operator == (LZespolona Skl1, LZespolona Skl2) { /*zastosowanie if-a ktory ma zabobiegaac bledowi przyblizenia*/ if (abs(Skl1.im - Skl2.im) < 0.1 && abs(Skl1.re - Skl2.re) < 0.1) return true; return false; } //funkcja wczytujaca od uzytkownika liczbe zespolona i sprawdzajaca jej poprawnosc wpisania istream& operator >> (istream& wej, LZespolona& Skl1) { char tab[3]; wej >> tab[0]; wej >> Skl1.re; wej >> Skl1.im; wej >> tab[1]; wej >> tab[2]; //warunki aby liczba zespolona spelniala warunki podane w zadaniu if (tab[0] != '(' || tab[1] != 'i' || tab[2] != ')') { //sprawdzenie bledu zapisu podczas wejscia wej.setstate(ios_base::badbit); } return wej; } LZespolona Sprzezenie(LZespolona x) { x.im = -x.im; return x; } /*! * Realizuje dodanie dwoch liczb zespolonych. * Argumenty: * Skl1 - pierwszy skladnik dodawania, * Skl2 - drugi skladnik dodawania. * Zwraca: * Sume dwoch skladnikow przekazanych jako parametry. */ LZespolona operator + (LZespolona Skl1, LZespolona Skl2) { LZespolona Wynik; Wynik.re = Skl1.re + Skl2.re; Wynik.im = Skl1.im + Skl2.im; return Wynik; } LZespolona operator + (LZespolona Arg) { return Arg; } LZespolona operator - (LZespolona Skl1, LZespolona Skl2) { LZespolona Wynik; Wynik.re = Skl1.re - Skl2.re; Wynik.im = Skl1.im - Skl2.im; return Wynik; } LZespolona operator - (LZespolona Arg) { Arg.re = -Arg.re; Arg.im = -Arg.im; return Arg; } LZespolona operator * (LZespolona Skl1, LZespolona Skl2) { LZespolona Wynik; Wynik.re = Skl1.re * Skl2.re - Skl1.im * Skl2.im; Wynik.im = Skl1.re * Skl2.im + Skl1.im * Skl2.re; return Wynik; } double Modul2(LZespolona Skl1) { return Skl1.re * Skl1.re + Skl1.im * Skl1.im; } LZespolona operator / (LZespolona Skl1, double Skl2) { LZespolona Wynik; assert(Skl2 != 0); Wynik.re = Skl1.re / Skl2; Wynik.im = Skl1.im / Skl2; return Wynik; } LZespolona operator / (LZespolona Skl1, LZespolona Skl2) { LZespolona Wynik; assert(Modul2(Skl2) != 0); Wynik = (Skl1 * Sprzezenie(Skl2)) / Modul2(Skl2); return Wynik; }
true
d7d45056a37fc3ee7ecfa681f68f574d91d34830
C++
joe-zxh/OJ
/程序员代码面试指南/第7章 位运算/2. 不用做任何比较判断运算符找出两个整数中的较大的值.cpp
UTF-8
336
3.21875
3
[]
no_license
#include<iostream> using namespace std; int big(int a, int b) { int signa = (a >> 31 & 1); int signb = (b >> 31 & 1); if (signa - signb) { // 符号不同 return signa == 1 ? b : a; } else { return a - b > 0 ? a : b; } } int main() { int a, b; cin >> a >> b; cout << big(a, b) << endl; return 0; }
true
c16735a11a5819e1da927014bf8e32cfc58264d6
C++
markynich/schoolAssignments
/Desktop/school/Spring2017/CS116/Lab4_ver2/printMeFirst.cpp
UTF-8
681
3.609375
4
[]
no_license
#include <iostream> #include <ctime> #include <string> #include <iomanip> using namespace std; /** Purpose: Print out the programmer’s information such as name, class information and date/time the program is run @author Ron Sha @version 1.0 1/27/2017 @param name - the name of the programmer @param courseInfo - the name of the course @return - none */ void printMeFirst(string name, string courseInfo) { cout <<" Program written by: "<< name << endl; // put your name here cout <<" Course info: "<< courseInfo << endl; time_t now = time(0); // current date/time based on current system char* dt = ctime(&now); // convert now to string for cout << " Date: " << dt << endl; }
true
902274b5a3805714c4cbbf1903c6b609031f22c9
C++
MonkeyThumbs/Box2D-DebugDraw-SFML
/DebugDraw.h
UTF-8
1,050
2.546875
3
[ "MIT" ]
permissive
#pragma once #include <Box2D.h> #include <SFML/System.hpp> #include <SFML/Graphics.hpp> class DebugDraw : public b2Draw { public: DebugDraw(sf::RenderWindow &window); virtual ~DebugDraw(); void DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) override; void DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) override; void DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color) override; void DrawSolidCircle(const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color) override; void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color) override; void DrawTransform(const b2Transform& xf) override; void DrawPoint(const b2Vec2& p, float32 size, const b2Color& color) override; void DrawAABB(b2AABB* aabb, const b2Color& color); sf::Color B2SFColor(const b2Color &color, int alpha); void DrawMouseJoint(b2Vec2& p1, b2Vec2& p2, const b2Color &boxColor, const b2Color &lineColor); private: sf::RenderWindow *m_window; };
true
03a72b03425c8afc05eb0b0676a0c413426208c7
C++
Emma926/LLFI
/llvm_passes/FICustomSelectorManager.cpp
UTF-8
2,042
2.609375
3
[ "LicenseRef-scancode-unknown-license-reference", "NCSA" ]
permissive
#include "llvm/Support/raw_ostream.h" #include "FIInstSelector.h" #include "FIRegSelector.h" #include "FICustomSelectorManager.h" namespace llfi { // fault injection instruction selector manager FICustomInstSelectorManager *FICustomInstSelectorManager::getCustomInstSelectorManager() { static FICustomInstSelectorManager instsel_manager; return &instsel_manager; } void FICustomInstSelectorManager::addCustomInstSelector( const std::string &name, FIInstSelector *instselector) { if (optionname_instselector.find(name) == optionname_instselector.end()) { optionname_instselector[name] = instselector; } else { errs() << "ERROR: Duplicate custom fault injection instruction selector: " << name << "\n"; exit(1); } } FIInstSelector *FICustomInstSelectorManager::getCustomInstSelector( const std::string &name) { if (optionname_instselector.find(name) != optionname_instselector.end()) { return optionname_instselector[name]; } else { errs() << "ERROR: Unknown custom fault injection instruction selector: " << name << "\n"; exit(1); } } // fault injection register selector manager FICustomRegSelectorManager *FICustomRegSelectorManager::getCustomRegSelectorManager() { static FICustomRegSelectorManager regsel_manager; return &regsel_manager; } void FICustomRegSelectorManager::addCustomRegSelector( const std::string &name, FIRegSelector *regselector) { if (optionname_regselector.find(name) == optionname_regselector.end()) { optionname_regselector[name] = regselector; } else { errs() << "ERROR: Duplicate custom fault injection register selector: " << name << "\n"; exit(1); } } FIRegSelector *FICustomRegSelectorManager::getCustomRegSelector( const std::string &name) { if (optionname_regselector.find(name) != optionname_regselector.end()) { return optionname_regselector[name]; } else { errs() << "ERROR: Unknown custom fault injection register selector: " << name << "\n"; exit(1); } } }
true
242f13b7476338f8a823290e13927019498f256c
C++
Fructokinase/dungeon-game
/vampire.cc
UTF-8
3,349
2.890625
3
[]
no_license
#include "vampire.h" #include "enemy.h" #include <cmath> #include "human.h" #include "dwarf.h" #include "halfling.h" #include "elf.h" #include "orcs.h" #include "merchant.h" #include "dragon.h" #include <iostream> using namespace std; Vampire::Vampire(Cell* spawnedIn, int x, int y):Player(spawnedIn, x, y), perHeal(5){ Player::init(50, 25, 25); Character::setHPBoundary(0, 2147483647); }; Vampire::~Vampire(){}; void Vampire::attack(Enemy& e) { e.beAttackedBy(*this); }; void Vampire::heal(){ Character::hp+=perHeal; notifyObservers(SubscriptionType::textDisplay); } void Vampire::beAttackedBy (Human& h) { int damage = ceil(100.0 / (100 + Character::def)) * h.getAtk(); if (rand() % 2 == 0) damage = 0; Character::hp-=damage; if(Character::hp < 0) Character::hp = 0; notifyObservers(SubscriptionType::textDisplay); if(Character::hp <= 0) { Player::die(); } } void Vampire::beAttackedBy (Dwarf& d) { int damage = ceil(100.0 / (100 + Character::def)) * d.getAtk(); if (rand() % 2 == 0) damage = 0; Character::hp-=damage; if(Character::hp < 0) Character::hp = 0; notifyObservers(SubscriptionType::textDisplay); if(Character::hp <= 0) { Player::die(); } } void Vampire::beAttackedBy(Halfling& l) { int damage = ceil(100.0 / (100 + Character::def)) * l.getAtk(); if (rand() % 2 == 0) damage = 0; Character::hp-=damage; if(Character::hp < 0) Character::hp = 0; notifyObservers(SubscriptionType::textDisplay); if(Character::hp <= 0) { Player::die(); } }; void Vampire::beAttackedBy(Elf& e) { int damage = ceil(100.0 / (100 + Character::def)) * e.getAtk(); // elf gets two attacks against every race except drow for (int i = 0; i < 2; ++i) { if (rand() / 2 == 0) { damage = 0; } Character::hp-=damage; if(Character::hp < 0) Character::hp = 0; notifyObservers(SubscriptionType::textDisplay); } if(Character::hp <= 0) { Player::die(); } }; void Vampire::beAttackedBy (Orcs& o) { int damage = ceil(100.0 / (100 + Character::def)) * o.getAtk(); if (rand() % 2 == 0) damage = 0; Character::hp-=damage; if(Character::hp < 0) Character::hp = 0; notifyObservers(SubscriptionType::textDisplay); if(Character::hp <= 0) { Player::die(); } } void Vampire::beAttackedBy(Merchant& m) { int damage = ceil(100.0 / (100 + Character::def)) * m.getAtk(); if (rand() % 2 == 0) damage = 0; Character::hp-=damage; if(Character::hp < 0) Character::hp = 0; notifyObservers(SubscriptionType::textDisplay); if(Character::hp <= 0) { Player::die(); } }; void Vampire::beAttackedBy(Dragon& d) { int damage = ceil(100.0 / (100 + Character::def)) * d.getAtk(); if (rand() % 2 == 0) damage = 0; Character::hp-=damage; if(Character::hp < 0) Character::hp = 0; notifyObservers(SubscriptionType::textDisplay); if(Character::hp <= 0) { Player::die(); } }; int Vampire::getGold() { return Player::gold; } string Vampire::objectType() const { return "Vampire"; } Info Vampire::getInfo() const { return Info{-1, -1, true, '@', ' ', nullptr, "Vampire", Character::hp, Character::atk, Character::def, Player::gold}; }
true
7aa7c31899c97aa1110d719a25800b6ade620cf5
C++
finrocmirror/make_builder
/enum_strings_builder/enum_strings.h
UTF-8
5,956
2.59375
3
[]
no_license
/** * You received this file as part of an experimental * build tool ('makebuilder') - originally developed for MCA2. * * Copyright (C) 2011 Max Reichardt, * Robotics Research Lab, University of Kaiserslautern * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ //---------------------------------------------------------------------- /*!\file enum_strings.h * * \author Max Reichardt * * \date 2011-08-24 * * \brief Contains methods to retrieve auto-generated string constants * for enum types */ //---------------------------------------------------------------------- #ifndef __make_builder__enum_strings_builder_h__ #define __make_builder__enum_strings_builder_h__ //---------------------------------------------------------------------- // External includes (system with <>, local with "") //---------------------------------------------------------------------- #include <vector> #include <string> #include <typeinfo> #include <stdexcept> //---------------------------------------------------------------------- // Debugging //---------------------------------------------------------------------- #include <cassert> //---------------------------------------------------------------------- // Namespace declaration //---------------------------------------------------------------------- namespace make_builder { //---------------------------------------------------------------------- // Forward declarations / typedefs / enums //---------------------------------------------------------------------- enum class tEnumStringsFormat { NATURAL, UPPER, LOWER, CAMEL, DIMENSION }; namespace internal { struct tEnumStrings { const char * const *strings[static_cast<size_t>(tEnumStringsFormat::DIMENSION)]; const size_t size; const void * const non_standard_values; }; const tEnumStrings &GetEnumStrings(const char *type_name); template <typename TEnum> const tEnumStrings &GetEnumStrings() { static const tEnumStrings &enum_strings(GetEnumStrings(typeid(TEnum).name())); return enum_strings; } /*! * (Typically, only used in generated code) * * Utility struct to intialize enum strings in static context */ struct tRegisterEnumStrings { /*! * \param type_name Normalized namespace and typename (normalized = without any template arguments) * \param strings Enum strings to register (should be terminated with null pointer) */ tRegisterEnumStrings(const char *type_name, const tEnumStrings &strings); }; } //---------------------------------------------------------------------- // Function declaration //---------------------------------------------------------------------- template <typename TEnum> inline size_t GetEnumStringsDimension() { return internal::GetEnumStrings<TEnum>().size; } /*! * \return Enum strings for this enum data type */ template <typename TEnum> const char * const *GetEnumStrings(tEnumStringsFormat format = tEnumStringsFormat::NATURAL) { assert(static_cast<size_t>(format) < static_cast<size_t>(tEnumStringsFormat::DIMENSION)); return internal::GetEnumStrings<TEnum>().strings[static_cast<size_t>(format)]; } /*! * \param value enum constant * \return Enum string for this enum constant */ template <typename TEnum> inline const char *GetEnumString(TEnum value, tEnumStringsFormat format = tEnumStringsFormat::NATURAL) { const internal::tEnumStrings& enum_strings = internal::GetEnumStrings<TEnum>(); if (enum_strings.non_standard_values) { const TEnum* values = static_cast<const TEnum*>(enum_strings.non_standard_values); for (size_t i = 0; i < enum_strings.size; i++) { if (values[i] == value) { return enum_strings.strings[static_cast<size_t>(format)][i]; } } throw std::runtime_error("Could not find enum string for value '" + std::to_string(static_cast<uint64_t>(value)) + "'!"); } assert(static_cast<size_t>(value) < enum_strings.size); return enum_strings.strings[static_cast<size_t>(format)][static_cast<size_t>(value)]; } template <typename TEnum> inline TEnum GetEnumValueFromString(const std::string &string, tEnumStringsFormat expected_format = tEnumStringsFormat::DIMENSION) { TEnum result; size_t format_begin = static_cast<size_t>(expected_format); size_t format_end = format_begin + 1; if (expected_format == tEnumStringsFormat::DIMENSION) { format_begin = 0; format_end = static_cast<size_t>(tEnumStringsFormat::DIMENSION); } for (size_t format = format_begin; format != format_end; ++format) { const internal::tEnumStrings& enum_strings = internal::GetEnumStrings<TEnum>(); const char * const *strings = enum_strings.strings[static_cast<size_t>(format)]; for (size_t i = 0; i < GetEnumStringsDimension<TEnum>(); ++i) { if (string == strings[i]) { if (enum_strings.non_standard_values) { return static_cast<const TEnum*>(enum_strings.non_standard_values)[i]; } return static_cast<TEnum>(i); } } } throw std::runtime_error("Could not find enum value for string '" + string + "'!"); return result; } //---------------------------------------------------------------------- // End of namespace declaration //---------------------------------------------------------------------- } #endif
true
b9080aac7a0c199a42ce3cc628a8d40c072b0d73
C++
mlu1109/advent_of_code
/2016/c++/day14.cpp
UTF-8
2,081
3.421875
3
[]
no_license
#include "md5.hpp" #include <string> #include <vector> #include <iostream> #include <sstream> #include <algorithm> #include <unordered_map> const std::string INPUT = "yjdafjpo"; const int MD5_DIGEST_STR_LENGTH = 32; bool five_in_a_row(char c, const std::string &md5) { int count = 0; for (int i = 0; i < MD5_DIGEST_STR_LENGTH; ++i) { if (count == 5) return true; else if (md5[i] == c) count += 1; else count = 0; } return false; } char three_in_a_row(const std::string &md5) { for (int i = 0; i < MD5_DIGEST_STR_LENGTH - 2; ++i) if (md5[i] == md5[i + 1] && md5[i] == md5[i + 2]) return md5[i]; return '-'; } void part1() { std::vector<int> key_indices; std::string md5_str[2]; for (int i = 0; key_indices.size() < 64; ++i) { md5_str[0] = md5(INPUT + std::to_string(i)); char tiar = three_in_a_row(md5_str[0]); if (tiar == '-') continue; for (int j = i + 1; j < i + 1000; ++j) { md5_str[1] = md5(INPUT + std::to_string(j)); if (five_in_a_row(tiar, md5_str[1])) { key_indices.push_back(i); break; } } } std::cout << "Part 1: " << key_indices[63] << '\n'; } std::string hash_2017_times(const std::string &str) { std::string hashed = md5(str); for (int i = 0; i < 2016; ++i) hashed = md5(hashed); return hashed; } void part2() { std::vector<int> key_indices; std::unordered_map<int, std::string> hashes; std::string md5_str[2]; int reached = 0; for (int i = 0; key_indices.size() < 64; ++i) { if (i < reached) md5_str[0] = hashes[i]; else md5_str[0] = hash_2017_times(INPUT + std::to_string(i)); char tiar = three_in_a_row(md5_str[0]); if (tiar == '-') continue; for (int j = i + 1; j < i + 1000; ++j) { if (j < reached) md5_str[1] = hashes[j]; else { md5_str[1] = hash_2017_times(INPUT + std::to_string(j)); hashes[j] = md5_str[1]; reached = j; } if (five_in_a_row(tiar, md5_str[1])) { key_indices.push_back(i); break; } } } std::cout << "Part 2: " << key_indices[63] << '\n'; } int main() { //part1(); part2(); }
true
35a40b5f5c5f9bb04e55f90baa64472823c80ad4
C++
Studio509/freshman
/任文娟/C++程序/019两个数的简单计算器/源代码.cpp
UTF-8
491
3.25
3
[]
no_license
#include <iostream> using namespace std; #include <cmath> int main() { int x,y; char ch; cin>>x>>ch>>y; switch(ch) { case '+':cout<<x+y<<endl;break; case '-':cout<<x-y<<endl;break; case '*':cout<<x*y<<endl;break; case '/': { if(y!=0) cout<<x/y<<endl;break; } case '%': { if(y!=0) cout<<x%y<<endl;break; } default:cout<<"ERROR"<<endl;break; } return 0; }
true
446a1e3c41c66c8ca236f899878f080ffd41e8e0
C++
xaviSalazar/IHMstage
/saveloadfile.h
UTF-8
2,367
2.734375
3
[]
no_license
#ifndef SAVELOADFILE_H #define SAVELOADFILE_H #include <QFile> #include <QTextStream> #include <QObject> #include <QVector> #include <QString> #include <QDebug> /*! \class saveLoadFile * \brief this class allows to save, load and load from a file all data */ class saveLoadFile: public QObject { Q_OBJECT public: /*! \brief Constructor */ saveLoadFile(); /*! * \brief saveData: This function allows to save the data from a current session * \param QVector<QString> &Current: To pass currentVal vector created in mainwindow class. * \param QString &Sampling : To pass String S created in mainwindow class. * \param QString &Period: To pass String P created in mainwindow class. * \param QString &Cycles: To pass String C created in mainwindow class. * \param QString &Amplitude: To pass String A created in mainwindow class. */ void saveData(QVector<QString> &Current, QString Sampling, QString Period, QString Cycles, QString Amplitude); /*! \brief loadData This function allows to load data from a saved session. * \param QVector<QString> &Current: To pass currentVal vector created in mainwindow class. * \param QString &Sampling : To pass String S created in mainwindow class. * \param QString &Period: To pass String P created in mainwindow class. * \param QString &Cycles: To pass String C created in mainwindow class. * \param QString &Amplitude: To pass String A created in mainwindow class. */ void loadData(QVector<QString> &Current,QString &Sampling, QString &Period, QString &Cycles, QString &Amplitude); /*! \brief loadData: This function allows to load data from a csv file. * \param QString fileName: To pass the directory location when a file is selected. * \param QVector<QString> &Current: To pass currentVal vector created in mainwindow class. * \param QString &Sampling : To pass String S created in mainwindow class. * \param QString &Period: To pass String P created in mainwindow class. * \param QString &Cycles: To pass String C created in mainwindow class. * \param QString &Amplitude: To pass String A created in mainwindow class. */ void loadData(QString fileName, QVector<QString> &Current,QString &Sampling, QString &Period,QString &Cycles, QString &Amplitude); }; #endif // SAVELOADFILE_H
true
08a32a9aa3ac398420a138ef190cfdeb42b5bbe5
C++
S920105123/codebook
/added/computational_geometry.cpp
UTF-8
4,375
3.21875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; const double PI=acos(-1); struct Point { // Also a vector double x,y; Point operator+(const Point &p) const { return {x+p.x,y+p.y}; } Point operator-(const Point &p) const { return {x-p.x,y-p.y}; } Point operator*(double mul) const { return {x*mul,y*mul}; } Point operator/(double mul) const { return {x/mul,y/mul}; } bool operator==(const Point &p) const { return x==p.x&&y==p.y; } double cross(const Point &v) const { return x*v.y-y*v.x; } double dot(const Point &v) const { return x*v.x+y*v.y; } Point normal() { // Normal vector return {-y,x}; } double len() const { // length return sqrt(x*x+y*y); } double angle(const Point &v) const { // Angle from *this to v in [-pi,pi]. return atan2(cross(v),dot(v)); } Point rotate_about(double theta, const Point &p) const { // Rotate this point conterclockwise by theta about p double nx=x-p.x,ny=y-p.y; return {nx*cos(theta)-ny*sin(theta)+p.x,nx*sin(theta)+ny*cos(theta)+p.y}; } }; struct Line { // Also a segment Point p1,p2; double a,b,c; // ax+by+c=0 Line(){} Line(const Point &_p1, const Point &_p2) { p1=_p1; p2=_p2; pton(); } void pton() { // IMPORTANT if you don't use constructor. a=p1.y-p2.y; b=p2.x-p1.x; c=-a*p1.x-b*p1.y; } int relation(const Point &p) { // For line, 0 if point on line // -1 if left, 1 if right Point dir=p2-p1; double crs=dir.cross(p-p1); return crs==0?0:crs<0?-1:1; } Point normal() { Point dir=p2-p1; return {-dir.y,dir.x}; } bool on_segment(const Point &p) { // Point on segment return relation(p)==0&&(p2-p).dot(p1-p)<=0; } bool parallel(const Line &l) { // Two line parallel return (p2-p1).cross(l.p2-l.p1)==0; } bool equal(const Line &l) { // Two line equal return relation(l.p1)==0&&relation(l.p2)==0; } bool cross_seg(const Line &seg) { // Line intersect segment Point dir=p2-p1; return dir.cross(seg.p1-p1)*dir.cross(seg.p2-p1)<=0; } int seg_intersect(const Line &s) const{ // Two segment intersect // 0 -> no, 1 -> one point, -1 -> infinity Point dir=p2-p1, dir2=s.p2-s.p1; double c1=dir.cross(s.p2-p1); double c2=dir.cross(s.p1-p1); double c3=dir2.cross(p2-s.p1); double c4=dir2.cross(p1-s.p1); if (c1==0&&c2==0) { if((s.p2-p1).dot(s.p1-p1)>0&&(s.p2-p2).dot(s.p1-p2)>0&& (p1-s.p1).dot(p2-s.p1)>0&&(p1-s.p2).dot(p2-s.p2)>0)return 0; if(p1==s.p1&&(p2-p1).dot(s.p2-p1)<=0)return 1; if(p1==s.p2&&(p2-p1).dot(s.p1-p1)<=0)return 1; if(p2==s.p1&&(p1-p2).dot(s.p2-p2)<=0)return 1; if(p2==s.p2&&(p1-p2).dot(s.p1-p2)<=0)return 1; return -1; }else if(c1*c2<=0&&c3*c4<=0)return 1; return 0; } Point line_intersection(const Line &l) const{ // Intersection of lines // pton(); l.pton(); double deno=a*l.b-l.a*b; if (deno!=0) { return { (l.c*b-c*l.b)/deno, (l.a*c-a*l.c)/deno}; } // Reaches here means no intersection. (parallel) return {1234,4321}; } Point seg_intersection(Line &s) const { Point dir=p2-p1, dir2=s.p2-s.p1; // pton(); l.pton(); double c1=dir.cross(s.p2-p1); double c2=dir.cross(s.p1-p1); double c3=dir2.cross(p2-s.p1); double c4=dir2.cross(p1-s.p1); if (c1==0&&c2==0) { if(p1==s.p1&&(p2-p1).dot(s.p2-p1)<=0)return p1; if(p1==s.p2&&(p2-p1).dot(s.p1-p1)<=0)return p1; if(p2==s.p1&&(p1-p2).dot(s.p2-p2)<=0)return p2; if(p2==s.p2&&(p1-p2).dot(s.p1-p2)<=0)return p2; }else if(c1*c2<=0&&c3*c4<=0)return line_intersection(s); // Reaches here means either INF or NOT ANY // Use seg_intersect to check OuO return {1234,4321}; } double dist(const Point &p, bool is_segment) const { // Point to Line/segment Point dir=p2-p1,v=p-p1; if (is_segment) { if (dir.dot(v)<0) return v.len(); if ((p1-p2).dot(p-p2)<0) return (p-p2).len(); } double d=abs(dir.cross(v))/dir.len(); return d; } }; struct Polygon { vector<Point> V; // Counterclockwise double area() const { double res=0; for (int i=1;i+1<V.size();i++) { res+=(V[i]-V[0]).cross(V[i+1]-V[0]); } return abs(res/2.0); } bool contain(const Point &p) { // Point can't on side int i, j, k = 0; for(i = 0, j = V.size()-1; i < V.size(); j = i++) { if(V[i].y > p.y != V[j].y > p.y && p.x < (V[j].x-V[i].x)*(p.y-V[i].y)/(V[j].y-V[i].y)+V[i].x) k++; } return k&1; } };
true
c69a2a53efeee992da7bb1ee51df35480e8c4343
C++
stdunn/DominionCardGame
/CPP_Files/ActionCard_Festival.cpp
UTF-8
424
2.78125
3
[]
no_license
#include "ActionCard_Festival.h ActionCard_Festival::ActionCard_Festival(std::string cardName) : Card(cardName) { cost = 5; type = CardType::Action; } /* Description: * + 2 Actions * + 1 Buy * + $2 */ void ActionCard_Festival::play() { Player* currentPlayer = GameState::currentPlayer(); currentPlayer->addActions(2); currentPlayer->addBuys(1); currentPlayer->addTreasure(2); }
true
75a7ae14203754e7317c04e49f31f1a16c1c52e1
C++
lmaruvada/Trees
/palindrome.cpp
UTF-8
432
3.515625
4
[]
no_license
#include <iostream> #include<string.h> #include<stdio.h> using namespace std; bool palindrome(char * st, int len){ int i = 0; int j = len-1; while(i<=j){ if(st[i] != st[j]) return false; i++; j--; } }; int main(){ char str[200]; cout << "Enter a string: " << endl; gets (str); if(palindrome(str, strlen(str))) cout << "is true" << endl; else cout << "is false" << endl; return 0; }
true
b3471d724b4f9d976066ab922945c6ef01eacdff
C++
JoshuaMasci/USG
/src/Common/Physics/SingleRigidBody.hpp
UTF-8
461
2.625
3
[]
no_license
#ifndef SINGLE_RIGIDBODY_HPP #define SINGLE_RIGIDBODY_HPP #include "Common/Physics/RigidBody.hpp" class SingleRigidBody : public RigidBody { public: SingleRigidBody(Entity* entity); ~SingleRigidBody(); void setShape(CollisionShape* shape); CollisionShape* getShape(); virtual RigidBodyType getType() { return RigidBodyType::SINGLE; }; private: CollisionShape* shape = nullptr; btEmptyShape* empty_shape = nullptr; }; #endif //SINGLE_RIGIDBODY_HPP
true
8bdfd3cf4d7f371cfb22053dd4ac9750ec3dd93f
C++
erikajob91/drake
/geometry/test/meshcat_manual_test.cc
UTF-8
1,050
2.71875
3
[ "BSD-3-Clause" ]
permissive
#include <future> #include "drake/geometry/meshcat.h" /** To test, you must manually run `bazel run //geometry:meshcat_manual_test`. It will print two URLs to console. Navigating your browser to the first, you should see that the normally blue meshcat background is not visible (the background will look white). In the second URL, you should see the default meshcat view, but the grid that normally shows the ground plane is not visible. */ int main() { drake::geometry::Meshcat meshcat; // Note: this will only send one message to any new server. meshcat.SetProperty("/Background", "visible", false); meshcat.SetProperty("/Background", "visible", true); meshcat.SetProperty("/Background", "visible", false); // Demonstrate that we can construct multiple meshcats (and they will serve on // different ports). drake::geometry::Meshcat meshcat2; meshcat2.SetProperty("/Grid", "visible", false); // Sleep forever (we require the user to SIGINT to end the program). std::promise<void>().get_future().wait(); return 0; }
true
af7285fdf29da1eb3288aca76b6b6491d76d0f62
C++
kartikeya72001/ArraysCpp
/KthRoot.cpp
UTF-8
1,018
3.078125
3
[]
no_license
// You are given two integers n and k. Find the greatest integer x, such that, x^k <= n. // // Input Format // First line contains number of test cases, T. Next T lines contains integers, n and k. // // Constraints // 1<=T<=10 1<=N<=10^15 1<=K<=10^4 // // Output Format // Output the integer x // // Sample Input // 2 // 10000 1 // 1000000000000000 10 // Sample Output // 10000 // 31 // Explanation // For the first test case, for x=10000, 10000^1=10000=n #include <iostream> #include<math.h> #define ll long long using namespace std; bool is_Answer(ll n,ll k,ll ans){ if(pow(ans,k)<=n) return true; return false; } int main() { int t=0; cin>>t; for(int i=0;i<t;i++) { ll n,k; cin>>n>>k; ll s=1,e=n; ll ans=0; while(s<=e){ ll mid=(s+e)/2; if(is_Answer(n,k,mid)){ ans=mid; s=mid+1; } else e=mid-1; } cout<<ans<<endl; } return 0; }
true
0a4b77b2d2a862d6e64a76c87a031ed8f0a22ab8
C++
sjkelleyjr/codeforces
/724/C/C.cc
UTF-8
2,003
2.90625
3
[]
no_license
// Create your own template by modifying this file! #include <bits/stdc++.h> using namespace std; #ifdef DEBUG #define debug(args...) {dbg,args; cerr<<endl;} #else #define debug(args...) // Just strip off all debug tokens #endif struct debugger { template<typename T> debugger& operator , (const T& v) { cerr<<v<<" "; return *this; } } dbg; const long long NUMLINES = 1000000; bool checkCorner(long long x, long long y,long long n, long long m){ if((x == n && y == m) || (x == n && y == 0) || (x == 0 && y ==m)){ return true; } return false; } bool inBeam(long long a_x, long long a_y, long long b_x, long long b_y, long long c_x, long long c_y){ double cross = (c_y - a_y) * (b_x - a_x) - (c_x - a_x)*(b_y-a_y); if((abs(cross) > .1)){ return false; } double dot = (c_x - a_x) * (b_x - a_x) + (c_y - a_y) * (b_y - a_y); if(dot < 0){ return false; } double sqLength = (b_x -a_x)*(b_x-a_x) + (b_y-a_y)*(b_y-a_y); if(dot > sqLength){ return false; } return true; } void genBeam(long long lastX, long long lastY, long long x, long long y, long long n, long long m){ //gen sum //when we go up we want the sum, when we go down we want the diff. //gen diff } int main() { long long n,m,k; cin >> n >> m >> k; //array of coordinates long long arr[k][2]; //long long beams[NUMLINES][2]; vector<long long> sensorIndexes; for(long long i = 0; i < k; i++){ long long x,y; cin >> x >> y; arr[i][0] = x; arr[i][1] = y; } //the first beam... long long x = 3; long long y = 3; long long lastX = 0; long long lastY = 0; //create a new beam //if(checkCorner(x,y,n,m)){ // break; //} ////check all of our sensors with this new beam //for(long long i = 0; i< k ;i++){ // cout << inBeam(lastX,lastY,x,y,arr[i][0],arr[i][1]) << endl; // //cout << checkCorner(x,y,n,m) << endl; // cout << arr[i][0] << " " << arr[i][1] << endl; //} //if this new beam is a corner, we're done. }
true
1cd5f54767a017b7c78203c431974af17fbd6fbd
C++
Szelethus/cpp_courses
/2018-19-2/friday8-10/02_ex/return_value.cpp
UTF-8
170
2.90625
3
[]
no_license
#include <iostream> int* f(int p) { p++; return &p; } int main() { int a = 3; int *return_val = f(a); int t[0]; std::cout << *return_val << std::endl; }
true
93566af0c3b9490483ca33a4ca99f36543438ce7
C++
sibashish99/Algo-in-C-Cpp
/interview prep/sum pairs.cpp
UTF-8
455
3.28125
3
[]
no_license
#include<iostream> using namespace std; void getPair(int a[],int n,int sum){ for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ if(a[i]+a[j]==sum){ printf("%d %d\n",a[i],a[j]); } } } } int main(){ int n; cout<<"How many nos:\n"; cin>>n; int a[100]; cout<<"Enter value:\n"; for(int i=0;i<n;i++){ cin>>a[i]; } cout<<"Enter the sum value:\n"; int sum; cin>>sum; cout<<"Pairs are:\n"; getPair(a,n,sum); }
true
5e8a5471fc1d87e88f9529885178c3aae9f1e133
C++
missio-cpp/missio
/src/json/src/object.cpp
UTF-8
3,418
2.90625
3
[ "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
//--------------------------------------------------------------------------- // // This file is part of Missio.JSON library // Copyright (C) 2011, 2012, 2014 Ilya Golovenko // //--------------------------------------------------------------------------- // Application headers #include <missio/json/object.hpp> #include <missio/json/value.hpp> // BOOST headers #include <boost/range/algorithm_ext.hpp> #include <boost/range/algorithm.hpp> // STL headers #include <iterator> #include <utility> namespace missio { namespace json { object::object(std::initializer_list<value_type> values) { for(auto const& value : values) { insert(value); } } object& object::operator=(std::initializer_list<value_type> values) { values_.clear(); for(auto const& value : values) { insert(value); } return *this; } bool object::empty() const { return values_.empty(); } std::size_t object::size() const { return values_.size(); } object::iterator object::begin() { return values_.begin(); } object::const_iterator object::begin() const { return values_.begin(); } object::iterator object::end() { return values_.end(); } object::const_iterator object::end() const { return values_.end(); } object::iterator object::find(string const& key) { return boost::find_if(values_, [&key](value_type const& value){ return value.first == key; }); } object::const_iterator object::find(string const& key) const { return boost::find_if(values_, [&key](value_type const& value){ return value.first == key; }); } bool object::contains(string const& key) const { return find(key) != values_.end(); } void object::clear() { values_.clear(); } void object::erase(iterator pos) { values_.erase(pos); } void object::erase(iterator first, iterator last) { values_.erase(first, last); } void object::erase(string const& key) { boost::remove_erase_if(values_, [&key](value_type const& value){ return value.first == key; }); } bool object::insert(value_type&& value) { return insert(end(), std::forward<value_type>(value)); } bool object::insert(value_type const& value) { return insert(end(), value); } bool object::insert(iterator pos, value_type&& value) { if(!contains(value.first)) { values_.insert(pos, std::forward<value_type>(value)); return true; } return false; } bool object::insert(iterator pos, value_type const& value) { if(!contains(value.first)) { values_.insert(pos, value); return true; } return false; } void object::insert(std::initializer_list<value_type> values) { for(auto const& value : values) { insert(value); } } value& object::operator[](string const& key) { iterator position(find(key)); if(position == values_.end()) { values_.emplace_back(key, value()); position = std::prev(values_.end()); } return position->second; } value const& object::operator[](string const& key) const { const_iterator position(find(key)); if(position == values_.end()) throw exception("value not found"); return position->second; } bool operator==(object const& lhs, object const& rhs) { return lhs.values_ == rhs.values_; } bool operator<(object const& lhs, object const& rhs) { return lhs.values_ < rhs.values_; } } // namespace json } // namespace missio
true
0995b2b5eccd32f1042591653610986e73d6b22b
C++
MatteoNasci/engineECS
/EngineECS/MeshManager.cpp
UTF-8
3,649
2.640625
3
[ "MIT" ]
permissive
#include "MeshManager.h" engineECS::Mesh& engineECS::MeshManager::getMesh(const int index) { return meshes[index]; } engineECS::SkeletalMesh& engineECS::MeshManager::getSkeletalMesh(const int index) { return skeletalMeshes[index]; } int engineECS::MeshManager::getMaxMeshesCount() const { return engineECS::MaxUniqueMeshes; } int engineECS::MeshManager::getMaxSkeletalMeshesCount() const { return engineECS::MaxUniqueMeshes; } int engineECS::MeshManager::getMeshesCount() const { return getMaxMeshesCount() - static_cast<int>(meshRecycler.size()); } int engineECS::MeshManager::getSkeletalMeshesCount() const { return getMaxSkeletalMeshesCount() - static_cast<int>(skeletalRecycler.size()); } const engineECS::Mesh* engineECS::MeshManager::getMeshes() const { return meshes; } const engineECS::SkeletalMesh* engineECS::MeshManager::getSkeletalMeshes() const { return skeletalMeshes; } engineECS::MeshManager::MeshManager() { for (register int i = 0; i < engineECS::MaxUniqueMeshes; ++i) { engineECS::MeshManager::skeletalRecycler.push(i); engineECS::MeshManager::meshRecycler.push(i); } } bool engineECS::MeshManager::tryAddMesh(const engineECS::Mesh& mesh, int& outIndex) { if (engineECS::MeshManager::meshRecycler.size() == 0) { outIndex = -1; return false; } outIndex = engineECS::MeshManager::meshRecycler.front(); engineECS::MeshManager::meshRecycler.pop(); meshes[outIndex] = mesh; meshes[outIndex].upload(); return true; } bool engineECS::MeshManager::tryCreateMesh(const physx::PxShape* shape, int& outMeshIndex) { if (!shape) { return false; } return tryAddMesh(engineECS::Mesh(shape), outMeshIndex); } bool engineECS::MeshManager::tryAddSkeletalMesh(const engineECS::SkeletalMesh& mesh, int& outIndex) { if (engineECS::MeshManager::skeletalRecycler.size() == 0) { outIndex = -1; return false; } outIndex = engineECS::MeshManager::skeletalRecycler.front(); engineECS::MeshManager::skeletalRecycler.pop(); skeletalMeshes[outIndex] = mesh; skeletalMeshes[outIndex].upload(); return true; } bool engineECS::MeshManager::tryCreateSkeletalMesh(const std::vector<glm::vec3>& vertices, const std::vector<glm::vec3>& normals, const std::vector<glm::vec2>& uvs, const std::vector<glm::mat4>& bindPoses, const std::vector<std::array<int, 4>>& bones, const std::vector<std::array<float, 4>>& weights, const std::map<std::string, std::vector<std::vector<glm::mat4>>>& animations, int& outMeshIndex) { return tryAddSkeletalMesh(engineECS::SkeletalMesh(vertices, normals, uvs, bindPoses, bones, weights, animations), outMeshIndex); } bool engineECS::MeshManager::tryCreateSkeletalMesh(const std::vector<ffh::Vector3>& vertices, const std::vector<ffh::Vector3>& normals, const std::vector<ffh::Vector2>& uvs, const std::vector<ffh::Matrix4>& bindPoses, const std::vector<std::array<int, 4>>& bones, const std::vector<std::array<float, 4>>& weights, const std::map<std::string, std::vector<std::vector<ffh::Matrix4>>>& animations, int& outMeshIndex) { return tryAddSkeletalMesh(engineECS::SkeletalMesh(vertices, normals, uvs, bindPoses, bones, weights, animations), outMeshIndex); } bool engineECS::MeshManager::tryCreateMesh(const std::vector<glm::vec3>& vertices, const std::vector<glm::vec3>& normals, const std::vector<glm::vec2>& uvs, int& outMeshIndex) { return tryAddMesh(engineECS::Mesh(vertices, normals, uvs), outMeshIndex); } bool engineECS::MeshManager::tryCreateMesh(const std::vector<ffh::Vector3>& vertices, const std::vector<ffh::Vector3>& normals, const std::vector<ffh::Vector2>& uvs, int& outMeshIndex) { return tryAddMesh(engineECS::Mesh(vertices, normals, uvs), outMeshIndex); }
true
5543fe78967bf205f9cbc497ccced3a8add530bc
C++
duaboola/hacktoberfest2020-1
/Areaofpolygons.cpp
UTF-8
1,325
3.921875
4
[]
no_license
#include<iostream.h> #include<conio.h> #include<stdio.h> //Area of rectangle void area(int l,int b) { int area=l*b; cout<<area; } //Area of triangle void area(int base,float h) { int area; area=(0.5*base*h); cout<<area; } //Area of circle void area(float r) { int area; area=(3.14*r*r); cout<<area; } //Area of square void area(int s) { int area; area=s*s; cout<<area; } void main() { clrscr; int choice; cout<<"Enter 1 for displaying area of rectangle, 2 for area of triangle, 3 for area of circle and 4 for area of square"; cin>>choice; switch(choice) { case 1: int l,b; cout<<"enter the length and breadth of rectangle"; cin>>l>>b; area(l,b); break; case 2: int b,float h; cout<<"enter the base and height of triangle"; cin>>b>>h; area(b,h); break; case 3: float r; cout<<"enter the radius of the circle"; cin>>r; area(r); break; case 4: int s; cout<<"enter the side of the square"; cin>>s; area(s); break; default: cout<< "Option entered is wrong."; getch(); }
true
a8e9254a43641343cce185c2dd2975c8f5e92691
C++
Guy-Pelc/ex2os
/thread.h
UTF-8
792
2.859375
3
[]
no_license
#ifndef THREAD_H #define THREAD_H #include <setjmp.h> #define STACK_SIZE 4096 enum Status {READY,BLOCKED,RUNNING}; class Thread { private: char stack[STACK_SIZE] = {0}; bool is_blocked = false; bool is_sleeping = false; public: bool get_is_blocked() {return is_blocked;} bool get_is_sleeping() {return is_sleeping;} int quantums = 0; Status status; int tid = 0; sigjmp_buf env = {0}; void resume() { is_blocked = false; if (!is_sleeping) { status = READY; } return; } void block() {is_blocked = true; status = BLOCKED; return;} void sleep() {is_sleeping = true; status = BLOCKED;return;} void wake() { is_sleeping = false; if (!is_blocked) { status = READY; } return; } Thread(int tid); Thread(int tid, void (*f)(void)); ~Thread(); }; #endif
true
b62934ce62a0870fba7bc565ad238200ba4d8571
C++
BarbaraPriwitzerGitHubRT/neuro-stat
/neurocorr/arch/v1/neuron.hpp
UTF-8
778
2.703125
3
[]
no_license
#ifndef NC_NEURON_INCLUDED #define NC_NEURON_INCLUDED 1 #include "record.hpp" //! forward declaration class NeuroData; //! Neuron : each Record is a Trial. class Neuron : public Records { public: explicit Neuron(size_t nTrials); virtual ~Neuron() throw(); const size_t &trials; //!< alias Records::size void buildFrom( NeuroData &data, const size_t neuronIndex ); private: YOCTO_DISABLE_COPY_AND_ASSIGN(Neuron); }; //! base class for Neurons typedef dynamic_slots<Neuron> NeuronsBase; //! holding multiple neurons class Neurons : public NeuronsBase { public: explicit Neurons(const size_t numNeurons); virtual ~Neurons() throw(); void buildFrom( NeuroData &data ); private: YOCTO_DISABLE_COPY_AND_ASSIGN(Neurons); }; #endif
true
24420e3b2b85c0baf7a41926c4172c041bab89c2
C++
dpnguyen94/VNOI
/diamond/diamond.cpp
UTF-8
1,820
2.6875
3
[]
no_license
#include <stdio.h> #include <math.h> #include <memory.h> #include <algorithm> using namespace std; #define FOR(i,a,b) for (int i=(a),_b=(b);i<=_b;i++) #define DOW(i,a,b) for (int i=(a),_b=(b);i>=_b;i--) const int LM = 505; int m, n, h[LM], f1[LM][LM], f2[LM][LM], f3[LM][LM], f4[LM][LM]; char a[LM][LM]; void input() { scanf("%d %d\n", &m, &n); FOR(i,1,m) { FOR(k,1,n) scanf("%c", &a[i][k]); scanf("\n"); } } void calc(char ch) { memset(h,0,sizeof(h)); FOR(i,1,m) { FOR(k,1,n) if (a[i][k] == ch) h[k] ++; else h[k] = 0; FOR(k,1,n) if (h[k] > f1[i][k - 1]) f1[i][k] = f1[i][k - 1] + 1; else f1[i][k] = min(h[k],f1[i][k - 1]); DOW(k,n,1) if (h[k] > f2[i][k + 1]) f2[i][k] = f2[i][k + 1] + 1; else f2[i][k] = min(h[k],f2[i][k + 1]); } memset(h,0,sizeof(h)); DOW(i,m,1) { FOR(k,1,n) if (a[i][k] == ch) h[k] ++; else h[k] = 0; FOR(k,1,n) if (h[k] > f3[i][k - 1]) f3[i][k] = f3[i][k - 1] + 1; else f3[i][k] = min(h[k],f3[i][k - 1]); DOW(k,n,1) if (h[k] > f4[i][k + 1]) f4[i][k] = f4[i][k + 1] + 1; else f4[i][k] = min(h[k],f4[i][k + 1]); } } void process() { int r, c, res = -1, fmin; for (char ch = 'A'; ch <= 'Z'; ch ++) { calc(ch); FOR(i,1,m) FOR(k,1,n) { fmin = min(min(f1[i][k],f2[i][k]),min(f3[i][k],f4[i][k])) - 1; if (fmin > res) { res = fmin; r = i, c = k; } } } printf("%d %d %d\n", r, c, res); } void output() { } int main() { freopen("diamond.in1", "r", stdin); freopen("diamond.out", "w", stdout); input(); process(); output(); return 0; }
true
95ac5b303d949ed6b1afb08e02bc60c4755a6360
C++
Wprofessor/Leetcode_Practice
/DFS_algorithms/二叉树的层次遍历.cpp
UTF-8
650
2.78125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; }; vector<vector<int>> saveCount; void assistDFS(TreeNode *root, int level) { if (saveCount.size() == level) { vector<int> temp; saveCount.push_back(temp); } if(root) saveCount[level].push_back(root->val); if (root->left) assistDFS(root->left, level + 1); if (root->right) assistDFS(root->right, level + 1); } vector<vector<int>> levelOrder(TreeNode *root) { if(!root) return saveCount; assistDFS(root, 0); return saveCount; } int main() { return 0; }
true
121f0cc890a7900734adb56ea702fda34d6ddb98
C++
pranayspeed/Arduino-Projects
/demomotor/demomotor.ino
UTF-8
3,681
2.515625
3
[]
no_license
#include <Servo.h> #define MOTORLATCH D12 #define MOTORCLK D4 #define MOTORENABLE D7 #define MOTORDATA D8 #define MOTOR1_A D2 #define MOTOR1_B D3 #define MOTOR2_A D1 #define MOTOR2_B D4 #define MOTOR3_A D5 #define MOTOR3_B D7 #define MOTOR4_A D0 #define MOTOR4_B D6 #define MOTOR1_PWM D11 #define MOTOR2_PWM D3 #define MOTOR3_PWM D6 #define MOTOR4_PWM D5 #define SERVO1_PWM D10 #define SERVO2_PWM D9 #define FORWARD 1 #define BACKWARD 2 #define BRAKE 3 #define RELEASE 4 Servo servo_1; Servo servo_2; void setup() { Serial.begin(9600); Serial.println("Simple Adafruit Motor Shield sketch"); servo_1.attach(SERVO1_PWM); servo_2.attach(SERVO2_PWM); } void loop() { motor(1, FORWARD, 255); motor(2, FORWARD, 255); motor(3, FORWARD, 255); motor(4, FORWARD, 255); delay(2000); // Be friendly to the motor: stop it before reverse. motor(1, RELEASE, 0); motor(2, RELEASE, 0); motor(3, RELEASE, 0); motor(4, RELEASE, 0); delay(100); motor(1, BACKWARD, 128); motor(2, BACKWARD, 128); motor(3, BACKWARD, 128); motor(4, BACKWARD, 128); delay(2000); motor(1, RELEASE, 0); motor(2, RELEASE, 0); motor(3, RELEASE, 0); motor(4, RELEASE, 0); delay(100); } void motor(int nMotor, int command, int speed) { int motorA, motorB; if (nMotor >= 1 && nMotor <= 4) { switch (nMotor) { case 1: motorA = MOTOR1_A; motorB = MOTOR1_B; break; case 2: motorA = MOTOR2_A; motorB = MOTOR2_B; break; case 3: motorA = MOTOR3_A; motorB = MOTOR3_B; break; case 4: motorA = MOTOR4_A; motorB = MOTOR4_B; break; default: break; } switch (command) { case FORWARD: motor_output (motorA, HIGH, speed); motor_output (motorB, LOW, - 1); //-1: no PWM set break; case BACKWARD: motor_output (motorA, LOW, speed); motor_output (motorB, HIGH, - 1); //-1: no PWM set break; case BRAKE: motor_output (motorA, LOW, 255); // 255: fully on. motor_output (motorB, LOW, - 1); //-1: no PWM set break; case RELEASE: motor_output (motorA, LOW, 0); // 0: output floating. motor_output (motorB, LOW, - 1); // -1: no PWM set break; default: break; } } } void motor_output (int output, int high_low, int speed) { int motorPWM; switch (output) { case MOTOR1_A: case MOTOR1_B: motorPWM = MOTOR1_PWM; break; case MOTOR2_A: case MOTOR2_B: motorPWM = MOTOR2_PWM; break; case MOTOR3_A: case MOTOR3_B: motorPWM = MOTOR3_PWM; break; case MOTOR4_A: case MOTOR4_B: motorPWM = MOTOR4_PWM; break; default: speed = - 3333; break; } if (speed != -3333) { shiftWrite(output, high_low); // set PWM only if it is valid if (speed >= 0 && speed <= 255) { analogWrite(motorPWM, speed); } } } void shiftWrite(int output, int high_low) { static int latch_copy; static int shift_register_initialized = false; // Do the initialization on the fly, // at the first time it is used. if (!shift_register_initialized) { // Set pins for shift register to output pinMode(MOTORLATCH, OUTPUT); pinMode(MOTORENABLE, OUTPUT); pinMode(MOTORDATA, OUTPUT); pinMode(MOTORCLK, OUTPUT); // Set pins for shift register to default value (low); digitalWrite(MOTORDATA, LOW); digitalWrite(MOTORLATCH, LOW); digitalWrite(MOTORCLK, LOW); // Enable the shift register, set Enable pin Low. digitalWrite(MOTORENABLE, LOW); // start with all outputs (of the shift register) low latch_copy = 0; shift_register_initialized = true; } // The defines HIGH and LOW are 1 and 0. // So this is valid. bitWrite(latch_copy, output, high_low); shiftOut(MOTORDATA, MOTORCLK, MSBFIRST, latch_copy); delayMicroseconds(5); // For safety, not really needed. digitalWrite(MOTORLATCH, HIGH); delayMicroseconds(5); // For safety, not really needed. digitalWrite(MOTORLATCH, LOW); }
true
321ba3decf1c5b033e80aead54e1708e1ef3f4d9
C++
15831944/objectzrxDomeCode
/ZWCAD二次开发DemoCode/6第六章:扩展数据、扩展记录和对象字典/ZrxTemplate1/LineUtil.h
GB18030
953
2.53125
3
[]
no_license
#pragma once class CLineUtil { public: CLineUtil(); ~CLineUtil(); static AcDbObjectId Add(const AcGePoint3d &startPoint, const AcGePoint3d &endPoint); // Ƿ static bool ThreePointIsCollinear(const AcGePoint2d &pt1, const AcGePoint2d &pt2, const AcGePoint2d &pt3); // жϵǷֱߵֱࣨߵ㵽յΪ۲췽 // tol: ʸƽıεڷֵΪ0ԵرȽ // ֵ1ʾֱߵ࣬0ʾֱϣ-1ʾֱߵҲ static int PtInLeftOfLine(const AcGePoint3d &ptStart, const AcGePoint3d &ptEnd, const AcGePoint3d &pt, double tol = 1.0E-7); static int PtInLeftOfLine(const AcGePoint2d &ptStart, const AcGePoint2d &ptEnd, const AcGePoint2d &pt, double tol = 1.0E-7); static int PtInLeftOfLine(double x1, double y1, double x2, double y2, double x3, double y3, double tol = 1.0E-7); };
true
07dabd81f0177a6c8350f200434f35295fbe60c9
C++
wensespl/AED
/ArbolBinario.cpp
UTF-8
1,428
3.59375
4
[]
no_license
#include<iostream> using namespace std; typedef string Tipo; class Nodo{ private: Tipo dato; Nodo *izq, *der; public: Nodo(Tipo x){ dato = x; izq = der = NULL; } Nodo(Nodo* nodoIzq, Tipo x, Nodo* nodoDer){ dato = x; izq = nodoIzq; der = nodoDer; } Tipo getValor(){return dato;} Nodo* subArbolIzq(){return izq;} Nodo* subArbolDer(){return der;} void setValor(Tipo x){dato = x;} void setNodoIzq(Nodo* n){izq = n;} void setNodoDer(Nodo* n){der = n;} }; class ArbolBinario{ private: Nodo* raiz; public: ArbolBinario(){raiz = NULL;} bool vacio(){return raiz == NULL;} Nodo* getRaiz(){ if(vacio()) cout << "Arbol vacio\n"; else return raiz; } Nodo* hijoIzq(){ if(vacio()) cout << "Arbol vacio\n"; else return raiz->subArbolIzq(); } Nodo* hijoDer(){ if(vacio()) cout << "Arbol vacio\n"; else return raiz->subArbolDer(); } Nodo* nuevoArbol(Nodo* nodoIzq, Tipo d, Nodo* nodoDer){return new Nodo(nodoIzq, d, nodoDer);} void setRaiz(Nodo* r){raiz = r;} Nodo* getRaiz(){return raiz;} }; int main(int argc, char const *argv[]){ ArbolBinario a; Tipo e = a.getRaiz()->getValor(); return 0; }
true
57120158ae4578f3d4f81d8cd0d559690bf73d77
C++
shengLin-alex/leetcode-exercise
/0113. Path Sum II/path_sum_ii.cpp
UTF-8
1,222
3.875
4
[]
no_license
// Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. // Note: A leaf is a node with no children. // Example: // Given the below binary tree and sum = 22, // 5 // / \ // 4 8 // / / \ // 11 13 4 // / \ / \ // 7 2 5 1 // Return: // [ // [5,4,11,2], // [5,8,4,5] // ] #include "tree_helper.hpp" #include <vector> void trav_root(TreeNode *node, int sum, std::vector<std::vector<int>> &res, std::vector<int> &tmp) { if (node == nullptr) return; tmp.push_back(node->val); sum -= node->val; // 檢查是否為一組解且為最後的葉節點 if (sum == 0 && node->left == nullptr && node->right == nullptr) res.push_back(tmp); trav_root(node->left, sum, res, tmp); trav_root(node->right, sum, res, tmp); tmp.pop_back(); // call stack 回朔到上一層時要 pop 最後的值 } std::vector<std::vector<int>> pathSum(TreeNode *root, int sum) { std::vector<std::vector<int>> res; std::vector<int> tmp; trav_root(root, sum, res, tmp); return res; } int main() { TreeNode *root = stringToTreeNode("[5,4,8,11,null,13,4,7,2,null,null,5,1]"); auto res = pathSum(root, 22); return 0; }
true
3b0918120d5c9ac2e7c62ffd96edfd2169ead040
C++
ssynn/PAT_advanced
/1111. Online Map.cpp
GB18030
2,537
2.8125
3
[]
no_license
#include<iostream> #include<queue> #include<vector> #include<algorithm> #include<limits.h> using namespace std; int n, m, start, dest; const int INF = 10000000; int min_time = 10000000; int min_len = 10000000; vector<int>ans, ans1,temp; vector<bool>v; //¼Ѿҵ·Ľ vector<vector<int>>len, t; int Dijkstria(vector<vector<int>>&a) { vector<int>cost(n, INF); vector<bool>in(n, 0); in[start] = 1; //ѾҵС· for (int i = 0; i < n; i++) //· cost[i] = a[start][i]; for (int i = 1; i < n; i++) { int min_cost = INF; //¼· int j; //¼СĽ for (int k = 0; k < n; k++) { if (in[k] == 0 && cost[k] < min_cost) { j = k; min_cost = cost[j]; } } in[j] = 1; for (int k = 0; k < n; k++) //¸ڵ { if (in[k] == 0 && ((cost[j] + a[j][k]) < cost[k])) cost[k] = cost[j] + a[j][k]; } } return cost[dest]; } void DFS1(int p, int lenth, int time) { if (p == dest) { if (lenth == min_len && time < min_time) { ans = temp; min_time = time; } } if (lenth > min_len) return; for(int i=0;i<n;i++) if (v[i] == 0 && len[p][i] < INF) { v[i] = 1; temp.push_back(i); DFS1(i, lenth + len[p][i], time + t[p][i]); temp.pop_back(); v[i] = 0; } } void DFS2(int p,int time) { if (p == dest) { if (ans1.size() == 0 || time == min_time&&temp.size() < ans1.size()) ans1 = temp; } if (time > min_time) return; for(int i=0;i<n;i++) if (v[i] == 0 && t[p][i] < INF) { v[i] = 1; temp.push_back(i); DFS2(i, time + t[p][i]); temp.pop_back(); v[i] = 0; } } int main() { cin >> n >> m; len.resize(n, vector<int>(n,INF)); t.resize(n, vector<int>(n,INF)); while (m--) { int a, b, c, d, w; scanf_s("%d %d %d %d %d", &a, &b, &w, &c, &d); len[a][b] = c; t[a][b] = d; if (!w) { t[b][a] = t[a][b]; len[b][a] = len[a][b]; } } cin >> start >> dest; v.resize(n); v[start] = 1; min_len = Dijkstria(len); DFS1(start, 0, 0); min_time = Dijkstria(t); DFS2(start, 0); if (ans == ans1) { cout << "Distance = " << min_len << "; " << "Time = " << min_time << ": " << start; for (auto i : ans) cout << " -> " << i; } else { cout << "Distance = " << min_len << ": " << start; for (auto i : ans) cout << " -> " << i; cout << "\nTime = " << min_time << ": " << start; for (auto i : ans1) cout << " -> " << i; } system("pause"); return 0; }
true
25ed427cd24803a08d515eb3508fa49b5edc185b
C++
privorotskii/Scanner
/Scanner/Scanner.cpp
WINDOWS-1251
5,969
3.09375
3
[]
no_license
#include "stdafx.h" #include "string.h" #include "defs.h" #include "Scanner.h" TScaner::TScaner(char * FileName) { GetData(FileName); SetUK(0); line = 1; } TypeLex Keyword[MAX_KEYW] = { "long", "short", "int", "if", "main", "const", "void", "return", "else"}; int IndexKeyword[MAX_KEYW] = { Tlong, Tshort, Tint, Tif, Tmain, Tconst, Tvoid, Treturn, Telse}; void TScaner::SetUK(int i) // { uk = i; } int TScaner::GetUK(void) // { return uk; } void TScaner::PrintError(char * err, char * a) // { if (a[0] == '\0') printf(" (line: %d) : %s %s\n", line, err, a); else printf(" : %s. %s\n", err, a); system("pause"); exit(0); } int TScaner::Scaner(TypeLex l) { //int typ; // int i; // for (i = 0; i < MAX_LEX; i++) l[i] = 0; // i = 0; // i start: while ((t[uk] == ' ') || (t[uk] == '\n') || (t[uk] == '\t')) { if (t[uk] == '\n') line++; uk++; // } if (t[uk] == '/') { if (t[uk + 1] == '/') { // , \n uk = uk + 2; while (t[uk] != '\n') uk++; //line++; goto start; } if (t[uk + 1] == '*') { uk = uk + 2; while (1) { if (t[uk] == '\n') line++; if ((t[uk] == '*') && (t[uk + 1] == '/')) { uk += 2; break; } if (t[uk] == '\0') return Tend; uk++; } goto start; } } if (t[uk] == '\0') { l[0] = '\0'; return Tend; } else { N0: //constx if (t[uk] == '0') { l[i++] = t[uk++]; //const16 if (t[uk] == 'x') { l[i++] = t[uk++]; if ((((t[uk] <= '9') && (t[uk] >= '0')) || ((t[uk] <= 'F') && (t[uk] >= 'A')))) { while (((t[uk] <= '9') && (t[uk] >= '0')) || ((t[uk] <= 'F') && (t[uk] >= 'A'))) l[i++] = t[uk++]; return Tconst16; } else // 0, 16 return Terror; } i--; uk--; } //const10 if ((t[uk] <= '9') && (t[uk] >= '0')) { l[i++] = t[uk++]; if ((t[uk] >= 'a') && (t[uk] <= 'z')) { while ((t[uk] != ' ') && (t[uk] != '\n') && (t[uk] != '\t')) l[i++] = t[uk++]; return Terror; } while ((t[uk] <= '9') && (t[uk] >= '0')) // N1 l[i++] = t[uk++]; return Tconst10; } else if (((t[uk] >= 'a') && (t[uk] <= 'z'))|| ((t[uk] >= 'A') && (t[uk] <= 'Z'))) { l[i++] = t[uk++]; while ((t[uk] <= '9') && (t[uk] >= '0') || // N2 ((t[uk] >= 'a') && (t[uk] <= 'z')) || ((t[uk] >= 'A') && (t[uk] <= 'Z'))) l[i++] = t[uk++]; //int j; // : for (int j = 0; j < MAX_KEYW; j++) { if (strcmp(l, Keyword[j]) == 0) return IndexKeyword[j]; } return Tid; } else if (t[uk] == '=') { l[i++] = t[uk++]; if (t[uk] == '=') { l[i++] = t[uk++]; return Tequalequal; } return Tequal; } else if (t[uk] == '!') { l[i++] = t[uk++]; if (t[uk] == '=') { l[i++] = t[uk++]; return TnotEqual; } } else if (t[uk] == '>') { l[i++] = t[uk++]; if (t[uk] == '=') { l[i++] = t[uk++]; return Tequalmore; } if (t[uk] == '>') { l[i++] = t[uk++]; return Tshiftr; } return Tmore; } else if (t[uk] == '<') { l[i++] = t[uk++]; if (t[uk] == '=') { l[i++] = t[uk++]; return Tequalless; } if (t[uk] == '<') { l[i++] = t[uk++]; return Tshiftl; } return Tless; } else if (t[uk] == '+') { l[i++] = t[uk++]; if (t[uk] == '+') { l[i++] = t[uk++]; return Tplusplus; } return Tplus; } else if (t[uk] == '-') { l[i++] = t[uk++]; if (t[uk] == '-') { l[i++] = t[uk++]; return Tminusminus; } return Tminus; } else if (t[uk] == '&') { l[i++] = t[uk++]; if (t[uk] == '&') { l[i++] = t[uk++]; return Tand; } return Tand; } else if (t[uk] == '|') { l[i++] = t[uk++]; if (t[uk] == '|') { l[i++] = t[uk++]; return Tor; } return Tor; } else if (t[uk] == '*') { l[i++] = t[uk++]; return Tmul; } else if (t[uk] == '/') { l[i++] = t[uk++]; return Tdiv; } else if (t[uk] == '%') { l[i++] = t[uk++]; return Tpercent; } else if (t[uk] == ',') { l[i++] = t[uk++]; return Tcomma; } else if (t[uk] == ';') { l[i++] = t[uk++]; return Tsemicolon; } else if (t[uk] == '{') { l[i++] = t[uk++]; return Topenblock; } else if (t[uk] == '}') { l[i++] = t[uk++]; return Tcloseblock; } else if (t[uk] == ')') { l[i++] = t[uk++]; return Tclosebracket; } else if (t[uk] == '(') { l[i++] = t[uk++]; return Topenbracket; } else { //PrintError(10); // return Terror; } } } // Scaner void TScaner::GetData(char * FileName) { // FileName, char aa; FILE * in = fopen(FileName, "r"); if (in == NULL) { PrintError(" ", ""); exit(1); } int i = 0; while (!feof(in)) { fscanf(in, "%c", &aa); if (!feof(in)) t[i++] = aa; if (i >= MAX_TEXT - 1) { PrintError(" ", ""); break; } } t[i] = '\0'; // \0 fclose(in); } void TScaner::SetL(int i) { line = i; } int TScaner::GetL() { return line; }
true
c42c1a337610a5c822310166d3ed47dcf342f89e
C++
mattmw/charsim
/framework/MorphMesh.cpp
UTF-8
1,579
3.03125
3
[ "MIT" ]
permissive
/* * MorphMesh.cpp * * Author: MMW */ #include "MorphMesh.h" MorphMesh::MorphMesh(String meshId) : Mesh(meshId), _vertexOffset{0} { } MorphMesh::~MorphMesh() { } void MorphMesh::setMorphVertices(const Vec3Array vertices) { _morphVertices = vertices; } Vec3Array MorphMesh::getMorphVertices() const { return _morphVertices; } void MorphMesh::setMorphNormals(const Vec3Array normals) { _morphNormals = normals; } Vec3Array MorphMesh::getMorphNormals() const { return _morphNormals; } void MorphMesh::setVertexOffset(const int vertexOffset) { _vertexOffset = vertexOffset; } uint MorphMesh::getVertexOffset() const { return _vertexOffset; } void MorphMesh::loadMorphVertexBuffers() { glGenBuffers(1, &_vertexMorphBuffer._vertexBuffer); glBindBuffer(GL_ARRAY_BUFFER, _vertexMorphBuffer._vertexBuffer); glBufferData(GL_ARRAY_BUFFER, _morphVertices.size() * sizeof(Vec3), &_morphVertices[0], GL_STATIC_DRAW); glGenBuffers(1, &_vertexMorphBuffer._normalBuffer); glBindBuffer(GL_ARRAY_BUFFER, _vertexMorphBuffer._normalBuffer); glBufferData(GL_ARRAY_BUFFER, _morphNormals.size() * sizeof(Vec3), &_morphNormals[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); } const VertexMorphBuffer& MorphMesh::getMorphVertexBuffer() const { return _vertexMorphBuffer; } void MorphMesh::printVertices() { for (uint i = 0; i < _morphVertices.size(); i++) { cout<<glm::to_string(_morphVertices[i])<<endl; } }
true
6b46a40a7a1f25e51b43cf24c035705a769f13c1
C++
GuiHeinrichs/GerenciadorDePessoas_POO-C-
/Empregado.hpp
UTF-8
962
3.1875
3
[]
no_license
#ifndef Empregado_hpp #define Empregado_hpp #include "Pessoa.hpp" #include <iomanip> /* Desenvolva, como subclasse da classe Pessoa, a classe Empregado. Considere que: a. Cada instância da classe Empregado tem, para além dos atributos que caracterizam a classe Pessoa, os atributos: i. CodigoSetor (inteiro) ii. SalarioBase (vencimento base) iii. Imposto (porcentagem retida dos impostos). b. Implemente um método calcularSalario(). c. Escreva um programa de teste adequado para a classe Empregado. */ class Empregado:public Pessoa{ public: Empregado(){}; Empregado(int CodigoSetor, double SalarioBase, double Imposto); void setCodigoSetor(int CodigoSetor); void setSalarioBase(double SalarioBase); void setImposto(double Imposto); int getCodigoSetor(); double getSalarioBase(); double getImposto(); virtual double calcularSalario(); void toString(); protected: int CodigoSetor; double SalarioBase; double Imposto; }; #endif
true
73bce85b54d17de1cda1a0d6291409638f0b4804
C++
afdsilva/trabalho-ippd
/src/gui/FPS.cpp
UTF-8
659
2.65625
3
[]
no_license
/* * FPS.cpp * * Created on: 23/06/2014 * Author: andref */ #include "FPS.h" FPS FPS::FPSControl; FPS::FPS() { this->maxFrame = 60; this->oldTime = 0; this->lastTime = 0; this->speedFactor = 0; frames = 0; numFrames = 0; } void FPS::OnLoop() { sf::Time elapsed = clock.getElapsedTime(); if (oldTime + 1000 < elapsed.asMilliseconds()) { oldTime = elapsed.asMilliseconds(); numFrames = frames; frames = 0; } speedFactor = ((elapsed.asMilliseconds() - lastTime) / 1000.0f) * 32.0f; frames++; lastTime = elapsed.asMilliseconds(); } int FPS::GetFPS() { return numFrames; } float FPS::GetSpeedFactor() { return speedFactor; }
true
b3744068baf654a0a32f9c4b3de1f22ff846f9d9
C++
saxena11ashish/CPP
/Leetcode/11. Container With Most Water.cpp
UTF-8
983
3.5625
4
[]
no_license
// Runs in 28ms, beats 93% solutions class Solution { public: int maxArea(vector<int>& a) { int water = 0,temp=0; for(int i=0,j=a.size()-1; i<j ; ){ temp = (j-i)*min(a[i],a[j]); water = max(water,temp); a[i] < a[j] ? i++ : j--; } return water; } }; /* NOT FAST ENOUGH, Runs in 36ms class Solution { public: int maxArea(vector<int>& a) { int water = 0,temp=0; bool l_increasing = true,r_increasing = true; for(int i=0,j=a.size()-1; i<j ; ){ if(l_increasing || r_increasing){ temp = (j-i)*min(a[i],a[j]); water = max(water,temp); } if(a[i] < a[j]){ i++; l_increasing = (a[i-1]>=a[i] ? false: true); } else{ j--; r_increasing = (a[j+1]>=a[j] ? false: true); } } return water; } }; */
true
2ad68aaa69aa15e220bb2d1eea8ec178f62bff07
C++
cholovirus/123
/codigos ccomp I 2019/ultimos trabajos 14-16-19/point template.cpp
UTF-8
1,075
3.625
4
[]
no_license
#include <iostream> using namespace std; template <typename T> class Point { private: T x, y; public: Point(const T u, const T v) : x(u), y(v) {} T getX() { return x; } T getY() { return y; } Point<T> operator+(const Point<T> o) { Point<T> tmp(0, 0); tmp.x = x + o.x; tmp.y = y + o.y; return tmp; } }; template <typename A> ostream& operator<<(ostream& output, Point<A>&o){ output<<o.getX()<<","<<o.getY()<<endl; return output; } template <typename T> T sum(const T a, const T b) { return a + b; } int main() { Point<float> p(4.3, 5.6); Point<float> q(3.3, 8.6); Point<float> res = p + q; cout << res << endl; //cout << res.getX() << ", " << res.getY() << endl; // Point<float> q(3.3, 8.6); // cout << p.getX() << endl; // cout << p.getY() << endl; // // Point<float> x = sum<Point>(p, q); // cout << x.getX() << endl; return 0; }
true
d771ff1a01c2111af798ab4c95e026c9bc48acb8
C++
Ruki185/cpp
/assignment08/main.cpp
UTF-8
841
3.21875
3
[]
no_license
#include "forwardlist.hpp" #include <iostream> using namespace a08; int main() { ForwardList<int> list; ForwardList<int> other; other.push_front(7); // int test = 5; std::cout << "Size: " << list.size() << std::endl; list.push_front(1); std::cout << "Size: " << list.size() << std::endl; list.push_front(2); std::cout << "Size: " << list.size() << std::endl; list.push_front(3); std::cout << "Size: " << list.size() << std::endl; list.push_front(4); for(const auto &elem : list) std::cout << " " << elem; std::cout << "size: " << list.size() << std::endl; list.pop_front(); list.front() = 9; list.insert_after(list.begin(), 5); other = list; for(auto i: other){ std::cout << i << std::endl; } std::cout << list.front() << std::endl; }
true
a2338bb72eb4896c2814669e068dd8622c53dac8
C++
aadarshkumar-singh/Network_Gateway_Application
/myCode/CPort.h
UTF-8
3,216
3.203125
3
[]
no_license
/*************************************************************************** *============= Copyright by Darmstadt University of Applied Sciences ======= **************************************************************************** * Filename : CPORT.H * Author : Aadarsh Kumar Singh * Description : Header file that defines APIs to store the transmission * and reception data in a ring buffer when establishing * communication between ports via Gateway. * ****************************************************************************/ #ifndef CPORT_H #define CPORT_H #include "global.h" #include "CRingBuffer.h" #include <string> /** * \brief Base class which defines API to store the transmission * and reception data in a ring buffer when establishing * communication between ports via Gateway */ class CPort { protected: /** * \brief Ring buffer to store Transmission data */ CRingBuffer m_ringBufferTx; /** * \brief Ring buffer to store Reception data */ CRingBuffer m_ringBufferRx; public: /** * \brief Creates Transmission and reception buffer of given size * @param txSize Transmit Buffer size * @param rxSize Receive Buffer Size */ CPort(uint16_t txSize = 10, uint16_t rxSize = 10); /** * \brief Sends one Byte to the buffer * * \param data string : IN Byte to be transmitted * \return RC_t: * RC_SUCCESS - byte was transmitted * RC_BUFFEROVERFLOW - in case of full buffer */ RC_t writeByteStream(std::string const& data); /** * \brief Receive one Byte from the buffer * * @param data string& : OUT Byte received * @return RC_t: * RC_SUCCESS - byte was received * RC_BUFFERUNDERFLOW - in case of empty buffer */ RC_t readByteStream(std::string& data); /** * \brief Will transmit all data from TX buffer to hardware * @return RC_t * RC_SUCCESS - all ok * Specific error code in case of error */ RC_t portTx_isr(); /** * \brief Will transmit all data from RX hardware to buffer * @return * RC_SUCCESS - all ok * Specific error code in case of error */ RC_t portRx_isr(); /** * \brief Destructor of the Port */ virtual ~CPort(); /** * \brief Get the size of a package for the peripheral * @return package size in byte */ virtual uint16_t getDriverPackageSize() = 0; private: /** * \brief Sends one Package to the hardware * @param data that has to be written to hardware * @return RC_t: * RC_SUCCESS - byte was transmitted */ virtual RC_t writePackage_hw(CRingBuffer& data) = 0; /** * \brief Data to be read from hardware is populated in the * Ringbuffer passed as parameter. * @param data - Data to be read from hardware * @return RC_SUCCESS - byte was received * RC_NODATA - No data present to recieve */ virtual RC_t readPackage_hw(CRingBuffer& data) = 0; }; /******************** ** CLASS END *********************/ #endif /* CPORT_H */
true