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
c444c08759a22eadc04191dd870aeda2a088c3bf
C++
xiaodarbor/GET1033-Project
/rain_code/rain_code.ino
UTF-8
5,637
2.890625
3
[]
no_license
//define all LEDs int Row1 = 13; //level 1 int Row2 = 12; //level 2 int Row3 = 11; //level 3 int Col1 = 10; int Col2 = 9; int Col3 = 8; int Col4 = 7; int Col5 = 6; int Col6 = 5; int Col7 = 4; int Col8 = 3; int Col9 = 2; int rowmax = 3; int colmax = 9; int Col[9]; int Row[3]; void setup() { pinMode(Row1, OUTPUT); //Top pinMode(Row2, OUTPUT); //Middle pinMode(Row3, OUTPUT); //Bottom pinMode(Col1, OUTPUT); //Left pinMode(Col2, OUTPUT); //Middle pinMode(Col3, OUTPUT); //Right pinMode(Col4, OUTPUT); //Left pinMode(Col5, OUTPUT); //Middle pinMode(Col6, OUTPUT); //Right pinMode(Col7, OUTPUT); //Left pinMode(Col8, OUTPUT); //Middle pinMode(Col9, OUTPUT); //Right Col[0] = Col1; Col[1] = Col2; Col[2] = Col3; Col[3] = Col4; Col[4] = Col5; Col[5] = Col6; Col[6] = Col7; Col[7] = Col8; Col[8] = Col9; Row[0] = Row1; Row[1] = Row2; Row[2] = Row3; } void loop() { // put your main code here, to run repeatedly: rain(); delay(100); rainMed(); delay(100); rainHeavy(); delay(100); lightning(); delay(100); delay(300); } //functions to help perform animations void lightning(){ topPaneOn(); bottomPaneOn(); delay(25); topPaneOff(); bottomPaneOff(); delay(100); topPaneOn(); bottomPaneOn(); delay(25); topPaneOff(); bottomPaneOff(); topPaneOn(); bottomPaneOn(); delay(25); topPaneOff(); bottomPaneOff(); delay(100); } //Heavy rain void rainHeavy(){ int del = 80; int del2 = 60; randomSeed(analogRead(0)%10); //Serial.println("Analog input"); //testing //Serial.println(analogRead(0)%10); //testing for(int x= 0; x<50; x++){ int stCol = random(0,colmax); int stCol2 = random(0,colmax); int stCol3 = random(0,colmax); int stCol4 = random(0,colmax); int dropNum = random(0,9); //Serial.println(dropNum); //testing for(int y=rowmax-1;y>-1;y--){ if(y==rowmax-1) del2 = 80; //if first row onLED(Row[y], Col[stCol]); if(dropNum>=4){ onLED(Row[y], Col[stCol2]); } if(dropNum>=7){ onLED(Row[y], Col[stCol3]); } if(dropNum>=8){ onLED(Row[y], Col[stCol4]); } delay(del2); //turn off all even if they wern't turned on. offLED(Row[y], Col[stCol]); offLED(Row[y], Col[stCol2]); offLED(Row[y], Col[stCol3]); offLED(Row[y], Col[stCol4]); del2=30; } delay(del); } } //animate //light rain void rainLight(){ int del = 170; int del2 = 70; for(int x= 0; x<20; x++){ int stCol = random(0,colmax); for(int y=rowmax-1;y>-1;y--){ if(y==rowmax-1) del2 = 110; onLED(Row[y], Col[stCol]); delay(del2); offLED(Row[y], Col[stCol]); del2=70; } delay(del); } } //animate //Medium rain void rainMed(){ int del = 70; int del2 = 35; for(int x= 0; x<25; x++){ int stCol = random(0,colmax); for(int y=rowmax-1;y>-1;y--){ if(y==rowmax-1) del2 = 85; onLED(Row[y], Col[stCol]); delay(del2); offLED(Row[y], Col[stCol]); del2=35; } delay(del); } } //animate //light rain void rain(){ int del = 150; int del2 = 50; for(int x= 0; x<40; x++){ int stCol = random(0,colmax); for(int y=rowmax-1;y>-1;y--){ if(y==rowmax-1) del2 = 90; onLED(Row[y], Col[stCol]); delay(del2); offLED(Row[y], Col[stCol]); del2=50; } delay(del); } } void bottomPaneOn(){ digitalWrite(Row3, HIGH); digitalWrite(Col1, HIGH); digitalWrite(Col2, HIGH); digitalWrite(Col3, HIGH); digitalWrite(Col4, HIGH); digitalWrite(Col5, HIGH); digitalWrite(Col6, HIGH); digitalWrite(Col7, HIGH); digitalWrite(Col8, HIGH); digitalWrite(Col9, HIGH); } void bottomPaneOff(){ digitalWrite(Row3, LOW); digitalWrite(Col1, LOW); digitalWrite(Col2, LOW); digitalWrite(Col3, LOW); digitalWrite(Col4, LOW); digitalWrite(Col5, LOW); digitalWrite(Col6, LOW); digitalWrite(Col7, LOW); digitalWrite(Col8, LOW); digitalWrite(Col9, LOW); } void topPaneOn(){ digitalWrite(Row1, HIGH); digitalWrite(Col1, HIGH); digitalWrite(Col2, HIGH); digitalWrite(Col3, HIGH); digitalWrite(Col4, HIGH); digitalWrite(Col5, HIGH); digitalWrite(Col6, HIGH); digitalWrite(Col7, HIGH); digitalWrite(Col8, HIGH); digitalWrite(Col9, HIGH); } void topPaneOff(){ digitalWrite(Row1, LOW); digitalWrite(Col1, LOW); digitalWrite(Col2, LOW); digitalWrite(Col3, LOW); digitalWrite(Col4, LOW); digitalWrite(Col5, LOW); digitalWrite(Col6, LOW); digitalWrite(Col7, LOW); digitalWrite(Col8, LOW); digitalWrite(Col9, LOW); } //turn on LED based on row number and column number void onLED(int row, int col){ digitalWrite(row, HIGH); //turn on row digitalWrite(col, HIGH); //turn on col } //overload funtion - used to turn LED on with certain intensity void onLED(int row, int col, int value){ digitalWrite(row, HIGH); //turn on row analogWrite(col, value); //turn on col } //turn off LED based on row number and column number void offLED(int row, int col){ digitalWrite(row, LOW); //turn on row digitalWrite(col, LOW); //turn on col }
true
7912e919c3728c1f378384e32871c717a75c3f01
C++
salhyun/TerrainEditor
/RenderWare/LightScatteringData.h
UTF-8
2,651
2.53125
3
[]
no_license
#pragma once #include "Vector3.h" #include "Vector4.h" struct sLightScatteringShaderParams { Vector4 vBeta1; Vector4 vBeta2; Vector4 vBetaD1; Vector4 vBetaD2; Vector4 vSumBeta1Beta2; Vector4 vLog2eBetaSum; Vector4 vRcpSumBeta1Beta2; Vector4 vHG; Vector4 vConstants; Vector4 vTermMultipliers; Vector4 vSoilReflectivity; }; class cLightScatteringData { public: // Data Types & Constants... cLightScatteringData(); ~cLightScatteringData(){}; void setHenyeyG(float g); void setRayleighScale(float s); void setMieScale(float s); void setInscatteringScale(float s); void setExtinctionScale(float s); void setTerrainReflectionScale(float s); float getHenyeyG()const; float getRayleighScale()const; float getMieScale()const; float getInscatteringScale()const; float getExtinctionScale()const; float getTerrainReflectionScale()const; const sLightScatteringShaderParams* getShaderData()const; // the current light scattering // structure provided to the // vertex shaders sLightScatteringShaderParams m_shaderParams; private: // 'g' values used in the approximation // function designed by Henyey Greenstein float m_henyeyG; // scalars to control the size of // coefficients used for Rayleigh // and Mie light scattering float m_rayleighBetaMultiplier; float m_mieBetaMultiplier; // scalars to control the overall // amount of light scattering for // both inscattering and // extinction float m_inscatteringMultiplier; float m_extinctionMultiplier; // a scalar to adjust the reflective // nature of the terrain itself float m_reflectivePower; // the private function which updates the // the internal structure void recalculateShaderData(); }; // // Accessors // inline float cLightScatteringData::getHenyeyG()const { return m_henyeyG; } inline float cLightScatteringData::getRayleighScale()const { return m_rayleighBetaMultiplier; } inline float cLightScatteringData::getMieScale()const { return m_mieBetaMultiplier; } inline float cLightScatteringData::getInscatteringScale()const { return m_inscatteringMultiplier; } inline float cLightScatteringData::getExtinctionScale()const { return m_extinctionMultiplier; } inline float cLightScatteringData::getTerrainReflectionScale()const { return m_reflectivePower; } inline const sLightScatteringShaderParams* cLightScatteringData::getShaderData()const { return &m_shaderParams; } void atmosphericLighting(Vector3 eyeVector, Vector3 sunVector, Vector3 norm, Vector4 sunColor, float s, Vector4 &vExt, Vector4 &vIns, sLightScatteringShaderParams atm) ; //- End of cLightScatteringData ------------------------------------- //$Log: $
true
8d45598d3a5cbae2a2c05202b48fc500a083a6fe
C++
Sherry-Shi/hashtable
/hashtable_implementation.cpp
UTF-8
6,405
3.296875
3
[]
no_license
下面的代码实现,可以说还是算很标准的hashmap的实现,hashmap里面的hash function需要自己实现,就像priority_queue里面的comparator, hash_function也是作为一个template 参数进行定义的,需要用户自己去实现。 下面的hashmap实现, 包含: 1. getEntry, putEntry, remove, size, isEmpty()等api 2. 对hashmap经常可能出现的conflict进行了处理,用的是 separate chaining来做的; 3. 处理了当hashtable的存储空间超过了load_factor的时候,需要进行resize的需求 4. 采用了 mutex, C++的 thread 和 mutex类, 对里面的单元操作进行了lock, unlock. 从下面的实现可以看出来: hashtable: average的getEntry/find/putEntry的时间复杂度都是O(1), key--> hash_key-->table[hash_key] 但是如果有冲突并且冲突比较多, worst case 时间复杂度O(n), 需要遍历Linklist来寻找相应的位置。 /* the basic knowledge of datastructure and basic object-oriented class implementation */ //hashmap --> hashtable的实现 : using array of linklists with max size to implement hashtable //use chaining to solve the conflict template <typename K, typename V> class HashEntry { private: K key; V value; HashEntry* next; public: HashEntry(K key, V value, HashEntry* next) { this->key = key; this->value = value; this->next = next; } void setKey(K key) { this->key = key; } void setValue(V value) { this->value = value; } void setNext(HashEntry* next) { this->next = next; } K getKey() const{ return key; } V getValue() const{ return value; } HashEntry* getNext() const { return next; } }; const int TABLE_SIZE = 128; //Default hash function class template <typename K> struct KeyHash { unsigned long operator() (const K& key) const { return reinterpret_cast<unsigned long>(key) % TABLE_SIZE; } }; template <typename K, typename V, typename F = KeyHash<K>> class HashTable { private: HashEntry<K,V>** table; int size; float loadFactor; int Capacity; F hashFunc; mutex mtx; public: HashTable( float loadFactor) { this->Capacity = TABLE_SIZE; this->loadFactor = loadFactor; table = new HashEntry<K,V>*[Capacity]; for (int i = 0; i < Capacity; i++) { table[i] = NULL; } } ~HashTable() { for (int i = 0;i < Capacity; i++) { if (table[i] != NULL) { HashEntry<K,V>* tmp = table[i]; HashEntry<K,V>* d = tmp; while (tmp) { d = tmp; tmp = tmp->getNext(); delete d; } } table[i] = NULL; } delete[] table; } int getSize() { return size; } bool isEmpty() { return size == 0; } void clear() { for (int i = 0; i < size; i++) { table[i] = NULL; } } bool getValue(K key, V &value) { mtx.lock(); unsigned long hashValue = hashFunc(key); HashEntry<K,V>* entry = table[hashValue]; while (entry) { if (entry->getKey() == key) { value = entry->getValue(); return true; } entry = entry->getNext(); } mtx.unlock(); return false; } void putEntry(K key, V value) { mtx.lock(); unsigned long hashValue = hashFunc(key); HashEntry<K, V>* entry = table[hashValue]; HashEntry<K, V>* pre = NULL; while (entry) { if (entry->getKey() == key) { entry->setValue(value); return; } pre = entry; entry = entry->getNext(); } HashEntry<K, V> * newEntry = new HashEntry<K, V>(key, value, NULL); if (pre != NULL) { pre->setNext(newEntry); } else { //insert as first bucket element table[hashValue] = newEntry; } size++; mtx.unlock(); } void remove(K key) { mtx.lock(); unsigned long hashValue = hashFunc(key); HashEntry<K, V>* entry = table[hashValue]; HashEntry<K, V>* pre = NULL; if (entry == NULL) { return; } while (entry) { if (entry->getKey() == key) { break; } pre = entry; entry = entry->getNext(); } if (pre == NULL) { table[hashValue] = entry->getNext(); } else { pre->setNext(entry->getNext()); } size--; delete entry; mtx.unlock(); } bool needRehash() { return (size + 0.0) / TABLE_SIZE >= loadFactor; } void rehashing() { mtx.lock(); //create a new array with double size //maintain the newly created array HashEntry<K,V>** tmp = table; table = new HashEntry<K, V>[TABLE_SIZE*2]; //traverse all the nodes in the current array, and move them to the new array using putEntry for (int i = 0; i < TABLE_SIZE*2; i++) { while (tmp[i] != NULL) { HashEntry<K, V> cur = tmp[i]; tmp[i] = cur->getNext(); unsigned long hashValue = hashFunc(cur->getKey()); cur->setNext(table[hashValue]); table[hashValue] = cur; } } mtx.unlock(); } }; struct MyKeyHash { unsigned long operator()(const int& k) const { return k % 10; } }; int main(int argc, const char * argv[]) { // insert code here... std::cout << "Hello, World!\n"; int a[7] = {1,2,4,6,7,8,9}; vector<int> input(a, a+7); // vector<int> rst = getUnion() HashTable<int, string, MyKeyHash> hmap(0.7); hmap.putEntry(1, "val1"); hmap.putEntry(2, "val2"); hmap.putEntry(3, "val3"); string value; hmap.getValue(2, value); cout << value << endl; bool res = hmap.getValue(3, value); if (res) cout << value << endl; hmap.remove(3); res = hmap.getValue(3, value); if (res) cout << value << endl; return 0; }
true
2ba1379272f7f7a80146cd2a82c1e6aa981424b1
C++
cronin101/AcceleratedCPP
/Containers/bettergrader.cpp
UTF-8
1,052
3
3
[]
no_license
#include <algorithm> #include <iomanip> #include <ios> #include <iostream> #include <stdexcept> #include <string> #include <vector> #include "grade.h" #include "student_info.h" using namespace std; int main(const int argc, const char** argv) { vector<Student_Info> students; string::size_type max_name_len = 0; Student_Info record; while (read(cin, record)) { max_name_len = max(max_name_len, record.name.size()); students.push_back(record); } sort(students.begin(), students.end(), compareName); for (vector<Student_Info>::const_iterator it = students.begin(); it != students.end(); ++it) { Student_Info student = *it; string::size_type pad_length = max_name_len + 1 + student.name.size(); cout << student.name << string(pad_length, ' '); try { double finishing_grade = grade(student); streamsize prec = cout.precision(); cout << setprecision(3) << finishing_grade << setprecision(prec); } catch (domain_error e) { cout << e.what(); } cout << endl; } return 0; }
true
700b7f10b6dd8224581a288579c1af05d444424a
C++
kapilchhajer-zz/problem_solving
/leetcode/ReorderList.cpp
UTF-8
2,243
3.484375
3
[]
no_license
#include<iostream> #include<cstdio> using namespace std; /** * Definition for singly-linked list. */ struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode* split(ListNode *head){ ListNode *temp; temp = head->next; while(temp != NULL){ if(temp->next != NULL){ head = head->next; temp = temp->next; } temp = temp->next; } temp = head->next; head->next = NULL; return temp; } ListNode* reverse(ListNode *head){ ListNode *prevNode = head , *currNode = head->next, *temp; prevNode->next = NULL; // first next part is set by NULL while(currNode != NULL){ temp = currNode->next; currNode->next = prevNode; prevNode = currNode; currNode = temp; } return prevNode; } void mergeList(ListNode *first , ListNode *second){ ListNode *temp; while(second != NULL){ temp = first->next; first->next = second; second = second->next; first->next->next = temp; first = temp; } } void reorderList(ListNode *head) { if(head == NULL) return ; ListNode *secondListHead = split(head); if(secondListHead == NULL) return ; secondListHead = reverse(secondListHead); mergeList(head , secondListHead); } }; int main(){ ListNode *head; ListNode *node = new ListNode(1); head = node; Solution s; int i = 2; while( i < 9){ ListNode *tempNode = new ListNode(i); node->next = tempNode; node = tempNode; i++; } s.reorderList(head); while(head != NULL){ cout<<head->val<<endl; head = head->next; } return 0; }
true
86942e76658a9e9fe0ca7f37fa697756675f35de
C++
wurikiji/algorithm-PS
/acmicpc/1546.cpp
UTF-8
444
2.859375
3
[]
no_license
#include <cstdio> #include <vector> #include <algorithm> using namespace std; int main(void){ int n; vector<int> v; scanf("%d", &n); while(n--) { int temp; scanf("%d", &temp); v.push_back(temp); } sort(v.begin(), v.end()); double dap = 0.0; for(int i = 0 ;i < v.size();i++) { dap += (((double)v[i]/v[v.size()-1]) * 100); } printf("%2.2lf", dap/v.size()); return 0; }
true
d7d1e755bb54b6eef9ddb455bf47064256df0d67
C++
santiago-alvarezjulia/Taller2c
/TP3/common_socket.cpp
UTF-8
3,758
2.53125
3
[]
no_license
#define _POSIX_C_SOURCE 200112L #include <stdlib.h> #include <string.h> #include <stdio.h> #include <stdbool.h> #include <errno.h> #include <sys/socket.h> #include <arpa/inet.h> #include <unistd.h> #include <iostream> #include <string> #include "common_socket.h" #include "common_SocketError.h" #define OK 0 #define ERROR -1 #define MAX_CLIENTS_WAITING 10 using std::string; Socket::Socket() { int sock = socket(AF_INET, SOCK_STREAM, 0); if (sock < 0) { // throw excepcion SocketError string message_error = "Error: " + string(strerror(errno)); throw SocketError(message_error); } this->socket_fd = sock; } Socket::Socket(int fd) { this->socket_fd = fd; } Socket::Socket(Socket&& other) { this->socket_fd = other.socket_fd; other.socket_fd = -1; } void Socket::connect_(const char* hostname, const char* port) { struct sockaddr_in client; client.sin_family = AF_INET; client.sin_port = htons((uint16_t)atoi(port)); client.sin_addr.s_addr = inet_addr(hostname); if (connect(this->socket_fd, (struct sockaddr *)&client, sizeof(client)) < 0) { // throw excepcion SocketError string message_error = "Error: " + string(strerror(errno)); throw SocketError(message_error); } } void Socket::bind_and_listen(const char* port) { int val = 1; setsockopt(this->socket_fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)); struct addrinfo hints; struct addrinfo *result; int s = 0; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; s = getaddrinfo(NULL, port, &hints, &result); s = bind(this->socket_fd, result->ai_addr, result->ai_addrlen); if (s == -1) { // throw excepcion SocketError string message_error = "Error: " + string(strerror(errno)); throw SocketError(message_error); } freeaddrinfo(result); s = listen(this->socket_fd, MAX_CLIENTS_WAITING); if (s == -1) { // throw excepcion SocketError string message_error = "Error: " + string(strerror(errno)); throw SocketError(message_error); } } Socket Socket::accept_(){ int s = accept(this->socket_fd, NULL, NULL); if (s < 0) { // throw excepcion SocketError string message_error = "Error: " + string(strerror(errno)); throw SocketError(message_error); } return std::move(Socket(s)); } int Socket::send_(uint8_t* chunk, int sizeof_chunk) { int bytes_enviados = 0; int s; bool is_valid_socket = true; bool is_open_socket = true; while(bytes_enviados < sizeof_chunk && is_valid_socket && is_open_socket) { s = send(this->socket_fd, &chunk[bytes_enviados], sizeof_chunk - bytes_enviados, MSG_NOSIGNAL); if (s < 0) { is_valid_socket = false; } else if (s == 0) { is_open_socket = false; } else { bytes_enviados += s; } } if (is_valid_socket) { return OK; } return ERROR; } int Socket::receive_(uint8_t* chunk, int sizeof_chunk) { int bytes_recibidos = 0; int s; bool is_open_socket = true; bool is_valid_socket = true; while(bytes_recibidos < sizeof_chunk && is_valid_socket && is_open_socket) { s = recv(this->socket_fd, &chunk[bytes_recibidos], sizeof_chunk - bytes_recibidos, 0); if (s < 0) { is_valid_socket = false; } else if (s == 0) { is_open_socket = false; } else { bytes_recibidos += s; } } if (!is_open_socket && is_valid_socket) { return bytes_recibidos; } if (!is_valid_socket) { return ERROR; } if (!is_open_socket) { return OK; } return ERROR; } void Socket::shutdown_rd() { shutdown(this->socket_fd, SHUT_RD); } void Socket::shutdown_wr() { shutdown(this->socket_fd, SHUT_WR); } void Socket::shutdown_rdwr() { shutdown(this->socket_fd, SHUT_RDWR); } Socket::~Socket() { if (this->socket_fd != -1) { close(this->socket_fd); } }
true
45bc5b5db2569834082b7c22421f8503db5ef4f6
C++
ErickEnriquez/CSE-310
/Project 1/Code/project1.cpp
UTF-8
33,956
3.046875
3
[]
no_license
/*Erick Enriquez */ #include<cstring> #include <string> #include <iostream> #include "defns.h" using namespace std; // helperfunctions bool compare(mlb_stats,mlb_stats,std::string);//will compare 2 teams year bool checkEquality(mlb_stats,mlb_stats,string); bool compareName(mlb_stats,mlb_stats);// the function checks team name int findYearIndex(annual_stats*,int,int);// the function looks for a given year in an annual_stats array float getFloData(mlb_stats,std::string);//can return any of the float data within the struct int getIntData(mlb_stats,std::string);//can return any of the integer fields string getString(mlb_stats,std::string);//returns a string void printField(annual_stats*,int,int,std::string);//outputs the data of a given year and a given stat void printField(annual_stats*,mlb_stats*,int,int,string); int getTeamYear(annual_stats*,mlb_stats,int);//this function will give you the year of a team given an array of teams and a team that you want to look for void copyTeams(annual_stats*,mlb_stats*,int,int);//this function will copy all of the annual stats data into a team array to use for range //we will need more functions to do insertion sort, merge sort, ifind, and mfind //isort function void iSort(annual_stats*,int,int, std::string,std::string);//sorts the field given and order given void iSort(mlb_stats*,int,string,string);//for sorting and array of mlb_stats void ifind(annual_stats*,int,int,string,string); void mfind(annual_stats*,int,int,int,int,string,string); void mSort(annual_stats* ,int left ,int right ,int year,int numberofYears ,string field ,string order ); void merge(annual_stats* ,int left ,int mid ,int right,int year ,int numberOfYears ,string field ,string order ); /*mSort of a range of years*/ void mSort(mlb_stats*,int,int,string,string); void merge(mlb_stats*,int,int,int,string,string); int main(){ //variables int y, c ,startYear,endYear,startIndex,endIndex; //will be number of years and number of commands respectively std::string s1,s2,s3,s4,s5,s6; // 5 string variables that we will use to find out what command we want mlb_stats* teamArr ; std::cin>> y ; // read in the number of years that will be read int i = 1; annual_stats* tStats = new annual_stats[y];//allocate an array to store the total number of years that we will be using //the array will start indexing at 1 to n ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// while(i<=y)//while there are still years to read in { std::cin>> tStats[i].year>>tStats[i].no_teams;//read in the year we will be testing and the total number of teams tStats[i].stats = new mlb_stats[tStats[i].no_teams+1]; //allocate an array to store the number of teams in a given year 1 based int j = 1; do{ std::cin.getline(tStats[i].stats[j].Team,TEAM_NAME_LEN,'\t');//read in the name of the team until you reach a tab //read in all of the info of team j for year i std::cin>>tStats[i].stats[j].League >>tStats[i].stats[j].G >>tStats[i].stats[j].AB >>tStats[i].stats[j].R >>tStats[i].stats[j].H >>tStats[i].stats[j].B2 >>tStats[i].stats[j].B3 >>tStats[i].stats[j].HR >>tStats[i].stats[j].RBI >>tStats[i].stats[j].BB >>tStats[i].stats[j].SO >>tStats[i].stats[j].SB >>tStats[i].stats[j].CS >>tStats[i].stats[j].AVG >>tStats[i].stats[j].OBP >>tStats[i].stats[j].SLG >>tStats[i].stats[j].OPS; j++; // increment the count of the inner loop by 1 }while(j <= tStats[i].no_teams );// loop through and read all of the teams while there are still teams for that year i++;// increment the count by 1 for the outer loop }//end outer loop ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// std::cin>>c;//read in the total number of commands we will need while(c>0){//while there are more commands to do std::cin>>s1>>s2;//read in the first 2 lines to see what kind of command we will do if(s1 == "isort" && s2 == "range"){//if we are going to do an insertion sort on a range of years std::cin>>s3>>s4>>s5>>s6;//read in start year, end year, field,and order respectively startYear = stoi(s3);//get the start year endYear = stoi(s4);//get the end year int startIndex = findYearIndex(tStats,startYear,y); int endIndex = findYearIndex(tStats,endYear,y); int count = startIndex; int numOfTeams = 0; if(startIndex > endIndex){//if the stats were input in desending years while(count>= endIndex){ numOfTeams = numOfTeams + tStats[count].no_teams; count--; } } else if(startIndex < endIndex){ while(count <= endIndex){//loop through and add up all of the teams numOfTeams = numOfTeams + tStats[count].no_teams; count++; } } teamArr = new mlb_stats[numOfTeams];//allocate a pointer of size numOfTeams copyTeams(tStats,teamArr,startIndex,endIndex);//copy the 2 dimensional data into a 1d array of mlb_stats iSort(teamArr,numOfTeams-1,s5,s6);//sort the range printField(tStats,teamArr,numOfTeams,y,s5);//output the sorted Array of mlb_stats delete[] teamArr;//free the memory allocated for the array teamArr = NULL;//set the pointer to null } else if(s1 == "isort" && s2 != "range" ){ std::cin>>s3>>s4;//read in field, and order int year = std::stoi(s2); iSort(tStats,y,year,s3,s4);//call the isort function printField(tStats,year,y,s3); } else if(s1== "msort" && s2 == "range"){//doing msort on a range of years cin>>s3>>s4>>s5>>s6;//read in start year, end year, field, and order startYear = stoi(s3);//get the start year endYear = stoi(s4);//get the end year startIndex = findYearIndex(tStats,startYear,y); endIndex = findYearIndex(tStats,endYear,y); int count = startIndex; int numOfTeams = 0; if(startIndex > endIndex){//if the stats were input in desending years while(count>= endIndex){ numOfTeams = numOfTeams + tStats[count].no_teams; count--; } } else if(startIndex<endIndex){ while(count <= endIndex){//loop through and add up all of the teams numOfTeams = numOfTeams + tStats[count].no_teams; count++; } } teamArr = new mlb_stats[numOfTeams];//allocate a pointer of size numOfTeams copyTeams(tStats,teamArr,startIndex,endIndex);//copy the 2 dimensional data into a 1d array of mlb_stats mSort(teamArr,0,numOfTeams-1,s5,s6); printField(tStats,teamArr,numOfTeams,y,s5); delete[] teamArr;//delete the memory allocated for the array teamArr = NULL;//set the pointer to null } else if(s1 == "msort" && s2 != "range"){ std::cin>>s3>>s4;//read in field, and order int year = stoi(s2);//get the year we will be working on int yIndex = findYearIndex(tStats,year,y);//get the index of the year we are working on mSort(tStats,1,tStats[yIndex].no_teams,year,y,s3,s4); printField(tStats,year,y,s3); } else if(s1 =="mfind"){// std::cin>>s3>>s4;//read in field and select int year = stoi(s2); int yIndex = findYearIndex(tStats,year,y);; mfind(tStats,1,tStats[yIndex].no_teams,year,y,s3,s4); } else if(s1 == "ifind"){ std::cin>>s3>>s4;//read in field and select; int year = std::stoi(s2); ifind(tStats,y,year,s3,s4); } c--; } return 0; }//end main /** the function takes in 3 parameters an array of annual_stats, number of years, and a year, * and checks if the year is in the array and returns its position returns 0 if element isn't in array*/ int findYearIndex(annual_stats* arr,int year,int numOfYears){ for(int i = 1;i<=numOfYears;i++){ if(arr[i].year == year)//if we find a matching year in the array return its index return i; } return 0;// returns 0 if it loops through and can't find it } /**this function takes in 2 teams and a field, if t1 is larger than t2 return true * else return false, if 2 teams have the same stat then we will check the teamname */ bool compare(mlb_stats t1,mlb_stats t2, std::string field){ ////////////////////////////////////////////////////////////////////////// if(field == "Team"){ return(compareName(t1,t2));//calls compare name function and returns result } else if(field == "League"){ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } /////////////////////////////////////////////////////////////////////////// else if (field == "G"){ if(t1.G == t2.G) return compareName(t1,t2); if(t1.G >t2.G) return true; else return false; } else if (field =="AB"){ if(t1.AB == t2.AB) return compareName(t1,t2); if(t1.AB > t2.AB) return true; else return false; } else if(field == "R"){ if(t1.R == t2.R) return compareName(t1,t2); if(t1.R >t2.R) return true; else return false; } else if(field == "H"){ if(t1.H == t2.H) return compareName(t1,t2); if(t1.H >t2.H) return true; else return false; } else if(field == "B2"){ if(t1.B2 == t2.B2) return compareName(t1,t2); if(t1.B2 >t2.B2) return true; else return false; } else if(field == "B3"){ if(t1.B3 == t2.B3) return compareName(t1,t2); if(t1.B3 >t2.B3) return true; else return false; } else if(field == "HR"){ if(t1.HR == t2.HR) return compareName(t1,t2); if(t1.HR >t2.HR) return true; else return false; } else if(field == "RBI"){ if(t1.RBI == t2.RBI) compareName(t1,t2); if(t1.RBI >t2.RBI) return true; else return false; } else if(field == "BB"){ if(t1.BB == t2.BB) return compareName(t1,t2); if(t1.BB >t2.BB) return true; else return false; } else if(field == "SO"){ if(t1.SO == t2.SO) return compareName(t1,t2); if(t1.SO >t2.SO) return true; else return false; } else if(field == "SB"){ if(t1.SB == t2.SB) return compareName(t1,t2); if(t1.SB >t2.SB) return true; else return false; } else if(field == "CS"){ if(t1.CS == t2.CS) return compareName(t1,t2); if(t1.CS >t2.CS) return true; else return false; } ///////////////////////////////////////////////////////// else if(field == "AVG"){ if(t1.AVG == t2.AVG) return compareName(t1,t2); else if(t1.AVG>t2.AVG) return true; else return false; } else if(field == "OBP"){ if(t1.OBP == t2.OBP) return compareName(t1,t2); else if(t1.OBP>t2.OBP) return true; else return false; } else if(field == "SLG"){ if(t1.SLG == t2.SLG) return compareName(t1,t2); else if(t1.SLG>t2.SLG) return true; else return false; } else if(field =="OPS"){ if(t1.OPS == t2.OPS) return compareName(t1,t2); else if(t1.OPS>t2.OPS) return true; else return false; } ///////////////////////////////////////////////////////// return false;//if the field isn't one of the ones } /** The function takes in 2 team structs and checks their order alphabetically . returns false if t1 comes before t2 or true if otherwise */ bool compareName(mlb_stats t1,mlb_stats t2){ if(strncmp(t1.Team,t2.Team,TEAM_NAME_LEN) == -1) return false; else return true; } /*this function checks if 2 teams are equal in a given field stat, */ bool checkEquality(mlb_stats t1,mlb_stats t2,string field){ ////////////////////////////////////////////////////////////////////////// if(field == "Team"){ if(strncmp(t1.Team,t2.Team,TEAM_NAME_LEN) == 0) return true; else return false; } else if(field == "League"){ if(strncmp(t1.League,t2.League, LEAGUE_NAME ) == 0) return true; else return false; } /////////////////////////////////////////////////////////////////////////// else if (field == "G"){ if(t1.G == t2.G) return true; else return false; } else if (field =="AB"){ if(t1.AB == t2.AB) return true; else return false; } else if(field == "R"){ if(t1.R == t2.R) return true; else return false; } else if(field == "H"){ if(t1.H == t2.H) return true; else return false; } else if(field == "B2"){ if(t1.B2 == t2.B2) return true; else return false; } else if(field == "B3"){ if(t1.B3 == t2.B3) return true; else return false; } else if(field == "HR"){ if(t1.HR == t2.HR) return true; else return false; } else if(field == "RBI"){ if(t1.RBI == t2.RBI) return true; else return false; } else if(field == "BB"){ if(t1.BB == t2.BB) return true; else return false; } else if(field == "SO"){ if(t1.SO == t2.SO) return true; else return false; } else if(field == "SB"){ if(t1.SB == t2.SB) return true; else return false; } else if(field == "CS"){ if(t1.CS == t2.CS) return true; else return false; } ///////////////////////////////////////////////////////// else if(field == "AVG"){ if(t1.AVG == t2.AVG) return true; else return false; } else if(field == "OBP"){ if(t1.OBP == t2.OBP) return true; else return false; } else if(field == "SLG"){ if(t1.SLG == t2.SLG) return true; else return false; } else if(field =="OPS"){ if(t1.OPS == t2.OPS) return true; else return false; } return false; } /*this function sorts an year of stats given year, number of years, the field, and the order requested*/ void iSort(annual_stats* arr,int numbOfYears,int year, std::string field,std::string order){ int j;//index value mlb_stats key;//temp data int index = findYearIndex(arr,year,numbOfYears);//find the index of the year in question if(index == 0){//if the year exists in the array cout<<"year not found\n\n"; } else{ //if the sort is going to be in increasing order use this implementation if(order == "incr"){ for(int i = 2;i<=arr[index].no_teams;i++){ key = arr[index].stats[i]; j=i-1; while(j>0 && compare(arr[index].stats[j],key,field)== true){ arr[index].stats[j+1] = arr[index].stats[j]; j=j-1; } arr[index].stats[j+1]=key; } } //if the sort is going to be in decreasing order use this implementation else{ if(order == "dec"){ for(int i = 2;i<=arr[index].no_teams;i++){ key = arr[index].stats[i]; j=i-1; while(j>0 && compare(key,arr[index].stats[j],field)== true){ arr[index].stats[j+1] = arr[index].stats[j]; j=j-1; } arr[index].stats[j+1]=key; } } } } } /*this function works on a range of teams and will sort them in order given with respect to field given */ void iSort(mlb_stats* arr,int numOfTeams,string field,string order){ int i = 0; mlb_stats key; if(order == "incr"){ for(int j = 1 ; j <= numOfTeams;j++){ key = arr[j]; i=j-1; while(i>=0 && compare(arr[i],key,field)==true){ arr[i+1] = arr[i]; i=i-1; } arr[i+1] = key; } } else if (order == "decr"){ for(int j = 1 ; j <= numOfTeams;j++){ key = arr[j]; i=j-1; while(i>=0 && compare(key,arr[i],field)==true){ arr[i+1] = arr[i]; i=i-1; } arr[i+1] = key; } } } /*this function will sort the array in increasing order then it will give you back the print the select given*/ void ifind(annual_stats* arr,int numOfYears,int year,string field,string select){ int index = findYearIndex(arr,year,numOfYears); int i = arr[index].no_teams; int count = i-1; cout<<"\n\n\n"; iSort(arr,numOfYears,year,field,"incr");//call the iSort function and sort the array if(select=="max"){//if the function wants the max go through and check what field they want if(field=="Team" || field == "League"){//if the field is one of the strings cout<<select<<"\t"<<field<<"\n"<<arr[index].stats[i].Team<<" "<<getString(arr[index].stats[i],field)<<"\n"; while(count >= 1){ if(checkEquality(arr[index].stats[i],arr[index].stats[count],field)== true){//if the last team shares the same stats are team[count] print it out cout<<arr[index].stats[count].Team<<"\t"<<getString(arr[index].stats[count],field)<<"\n";//print the team and the value of matching stats for a field } count--;//decrement the count by 1 } } //if the field is a float else if(field =="AVG" ||field =="OBP" || field =="SLG" || field =="OPS"){ cout<<select<<"\t"<<field<<"\n"<<arr[index].stats[i].Team<<"\t"<<getFloData(arr[index].stats[i],field)<<"\n"; while(count >= 1){ if(checkEquality(arr[index].stats[i],arr[index].stats[count],field)== true){//if the last team shares the same stats are team[count] print it out cout<<arr[index].stats[count].Team<<"\t"<<getFloData(arr[index].stats[count],field)<<"\n";//print the team and the value of matching stats for a field } count--;//decrement the count by 1 } }//if the field is an inr else{ cout<<select<<"\t"<<field<<"\n"<<arr[index].stats[i].Team<<"\t"<<getIntData(arr[index].stats[i],field)<<"\n"; while(count >= 1){ if(checkEquality(arr[index].stats[i],arr[index].stats[count],field)== true){//if the last team shares the same stats are team[count] print it out cout<<arr[index].stats[count].Team<<"\t"<<getIntData(arr[index].stats[count],field)<<"\n";//print the team and the value of matching stats for a field } count--;//decrement the count by 1 } } } else if(select == "min"){ count = 2; if(field=="Team" || field == "League"){ cout<<select<<"\t"<<field<<"\n"<<arr[index].stats[1].Team<<"\t"<<getString(arr[index].stats[1],field)<<"\n"; while(count<=i){ if(checkEquality(arr[index].stats[1],arr[index].stats[count],field)== true){//if the last team shares the same stats are team[count] print it out cout<<arr[index].stats[count].Team<<"\t"<<getString(arr[index].stats[count],field)<<"\n";//print the team and the value of matching stats for a field } count++;//increment the count by 1 } } else if(field =="AVG" ||field =="OBP" || field =="SLG" || field =="OPS"){ cout<<select<<"\t"<<field<<"\n"<<arr[index].stats[1].Team<<"\t"<<getFloData(arr[index].stats[1],field)<<"\n"; while(count<=i){ if(checkEquality(arr[index].stats[1],arr[index].stats[count],field)== true){//if the last team shares the same stats are team[count] print it out cout<<arr[index].stats[count].Team<<"\t"<<getFloData(arr[index].stats[count],field)<<"\n";//print the team and the value of matching stats for a field } count++;//increment the count by 1 } } else{ cout<<select<<"\t"<<field<<"\n"<<arr[index].stats[1].Team<<"\t"<<getIntData(arr[index].stats[1],field)<<"\n"; while(count<=i){ if(checkEquality(arr[index].stats[1],arr[index].stats[count],field)== true){//if the last team shares the same stats are team[count] print it out cout<<arr[index].stats[count].Team<<"\t"<<getIntData(arr[index].stats[count],field)<<"\n";//print the team and the value of matching stats for a field } count++;//increment the count by 1 } } } else if(select == "average"){ if(field =="AVG" ||field =="OBP" || field =="SLG" || field =="OPS"){ float average = 0.0; for(int i = 1;i<=arr[index].no_teams;i++ ){ average = average + getFloData(arr[index].stats[i],field); } average = average/arr[index].no_teams; cout<<"\n\n\n\n\n" <<arr[index].year << " Average "<< field <<"\n"<< average<<"\n\n\n\n\n\n" ; } else{ int average = 0; for(int i = 1;i<=arr[index].no_teams;i++ ){ average = average + getIntData(arr[index].stats[i],field); } average = average/arr[index].no_teams; cout<<"\n\n\n\n\n" <<arr[index].year << " Average "<< field <<"\n"<< average<<"\n\n\n\n\n\n" ; } } else{//select is median cout<<"median\n"; if(field=="Team" || field =="League"){ cout<<getString(arr[index].stats[i/2],field); } else if(field =="AVG" ||field =="OBP" || field =="SLG" || field =="OPS"){ cout<<getFloData(arr[index].stats[i/2],field); } else{ cout<<getIntData(arr[index].stats[i/2],field); } } } void mfind(annual_stats* arr, int left, int right, int year, int num, string field, string select){ mSort(arr,left,right,year,num,field,"incr");// sort the array with mergesort int index = findYearIndex(arr,year,num); int i = arr[index].no_teams; int count = i-1; cout<<"\n\n\n"; if(select=="max"){//if the function wants the max go through and check what field they want if(field=="Team" || field == "League"){//if the field is one of the strings cout<<select<<"\t"<<field<<"\n"<<arr[index].stats[i].Team<<" "<<getString(arr[index].stats[i],field)<<"\n"; while(count >= 1){ if(checkEquality(arr[index].stats[i],arr[index].stats[count],field)== true){//if the last team shares the same stats are team[count] print it out cout<<arr[index].stats[count].Team<<"\t"<<getString(arr[index].stats[count],field)<<"\n";//print the team and the value of matching stats for a field } count--;//decrement the count by 1 } } //if the field is a float else if(field =="AVG" ||field =="OBP" || field =="SLG" || field =="OPS"){ cout<<select<<"\t"<<field<<"\n"<<arr[index].stats[i].Team<<"\t"<<getFloData(arr[index].stats[i],field)<<"\n"; while(count >= 1){ if(checkEquality(arr[index].stats[i],arr[index].stats[count],field)== true){//if the last team shares the same stats are team[count] print it out cout<<arr[index].stats[count].Team<<"\t"<<getFloData(arr[index].stats[count],field)<<"\n";//print the team and the value of matching stats for a field } count--;//decrement the count by 1 } }//if the field is an inr else{ cout<<select<<"\t"<<field<<"\n"<<arr[index].stats[i].Team<<"\t"<<getIntData(arr[index].stats[i],field)<<"\n"; while(count >= 1){ if(checkEquality(arr[index].stats[i],arr[index].stats[count],field)== true){//if the last team shares the same stats are team[count] print it out cout<<arr[index].stats[count].Team<<"\t"<<getIntData(arr[index].stats[count],field)<<"\n";//print the team and the value of matching stats for a field } count--;//decrement the count by 1 } } } else if(select == "min"){ count = 2; if(field=="Team" || field == "League"){ cout<<select<<"\t"<<field<<"\n"<<arr[index].stats[1].Team<<"\t"<<getString(arr[index].stats[1],field)<<"\n"; while(count<=i){ if(checkEquality(arr[index].stats[1],arr[index].stats[count],field)== true){//if the last team shares the same stats are team[count] print it out cout<<arr[index].stats[count].Team<<"\t"<<getString(arr[index].stats[count],field)<<"\n";//print the team and the value of matching stats for a field } count++;//increment the count by 1 } } else if(field =="AVG" ||field =="OBP" || field =="SLG" || field =="OPS"){ cout<<select<<"\t"<<field<<"\n"<<arr[index].stats[1].Team<<"\t"<<getFloData(arr[index].stats[1],field)<<"\n"; while(count<=i){ if(checkEquality(arr[index].stats[1],arr[index].stats[count],field)== true){//if the last team shares the same stats are team[count] print it out cout<<arr[index].stats[count].Team<<"\t"<<getFloData(arr[index].stats[count],field)<<"\n";//print the team and the value of matching stats for a field } count++;//increment the count by 1 } } else{ cout<<select<<"\t"<<field<<"\n"<<arr[index].stats[1].Team<<"\t"<<getIntData(arr[index].stats[1],field)<<"\n"; while(count<=i){ if(checkEquality(arr[index].stats[1],arr[index].stats[count],field)== true){//if the last team shares the same stats are team[count] print it out cout<<arr[index].stats[count].Team<<"\t"<<getIntData(arr[index].stats[count],field)<<"\n";//print the team and the value of matching stats for a field } count++;//increment the count by 1 } } } else if(select == "average"){ if(field =="AVG" ||field =="OBP" || field =="SLG" || field =="OPS"){ float average = 0.0; for(int i = 1;i<=arr[index].no_teams;i++ ){ average = average + getFloData(arr[index].stats[i],field); } average = average/arr[index].no_teams; cout<<"\n\n\n\n\n" <<arr[index].year << " Average "<< field <<"\n"<< average<<"\n\n\n\n\n\n" ; } else{ int average = 0; for(int i = 1;i<=arr[index].no_teams;i++ ){ average = average + getIntData(arr[index].stats[i],field); } average = average/arr[index].no_teams; cout<<"\n\n\n\n\n" <<arr[index].year << " Average "<< field <<"\n"<< average<<"\n\n\n\n\n\n" ; } } else{//select is median cout<<"median\n"; if(field=="Team" || field =="League"){ cout<<getString(arr[index].stats[i/2],field); } else if(field =="AVG" ||field =="OBP" || field =="SLG" || field =="OPS"){ cout<<getFloData(arr[index].stats[i/2],field); } else{ cout<<getIntData(arr[index].stats[i/2],field); } } } /*mergeSort function.divides the problem and then will call merge function in order to sort it back*/ void mSort(annual_stats* arr,int left,int right,int year,int numbOfYears,string field,string order){ if(left<right){ int mid = (left+right)/2; mSort(arr,left,mid,year,numbOfYears,field,order); mSort(arr,mid+1,right,year,numbOfYears,field,order); merge(arr,left,mid,right,year,numbOfYears,field,order); } } /*merges the array back in sorted order */ void merge(annual_stats* arr ,int left ,int mid ,int right,int year,int numbOfYears,string field ,string order ){ int i , j , k ; int n1 = mid-left+1 ; int n2 = right-mid; int index = findYearIndex(arr,year,numbOfYears); /*create temp arrays*/ mlb_stats* L = new mlb_stats[n1]; mlb_stats* R = new mlb_stats[n2]; /*copy data to temp arrays L[] and R[]*/ for(i=0;i<n1;i++){ L[i] = arr[index].stats[left+i]; } for(j=0;j<n2;j++){ R[j] =arr[index].stats[mid+1+j]; } i=0; j=0; k=left; if(order == "decr"){ while(i<n1 && j<n2){ if(compare(L[i],R[j],field)==true){ arr[index].stats[k] = L[i]; i++; } else{ arr[index].stats[k] = R[j]; j++; } k++; } /*copy remaining elements of L[] if they remain*/ while(i<n1){ arr[index].stats[k] = L[i]; i++; k++; } /*copy remaining elements of R[] if they remain*/ while(j<n2){ arr[index].stats[k] = R[j]; j++; k++; } } else{ while(i<n1 && j<n2){ if(compare(R[j],L[i],field)==true){ arr[index].stats[k] = L[i]; i++; } else{ arr[index].stats[k] = R[j]; j++; } k++; } /*copy remaining elements of L[] if they remain*/ while(i<n1){ arr[index].stats[k] = L[i]; i++; k++; } /*copy remaining elements of R[] if they remain*/ while(j<n2){ arr[index].stats[k] = R[j]; j++; k++; } } } void mSort(mlb_stats* arr,int left,int right, string field, string order){ if(left<right){ int mid = (right+left)/2; mSort(arr,left,mid,field,order); mSort(arr,mid+1,right,field,order); merge(arr,left,mid,right,field,order); } } void merge(mlb_stats* arr,int left,int mid, int right,string field,string order){ int i,j,k; int n1 = mid-left+1; int n2 = right-mid; /*create temp arrays*/ mlb_stats* L = new mlb_stats[n1]; mlb_stats* R = new mlb_stats[n2]; /*copy data to temp arrays L[] and R[]*/ for(i=0;i<n1;i++){ L[i] = arr[left+i]; } for(j = 0;j<n2;j++){ R[j] = arr[mid+1+j]; } /*merge the temp arrays back into arr[left...right]*/ i=0; j=0; k=left; if(order == "decr"){ while(i<n1 && j<n2){ if(compare(L[i],R[j],field)==true){ arr[k] = L[i]; i++; } else{ arr[k] = R[j]; j++; } k++; } /*copy remaining elements of L[] if they remain*/ while(i<n1){ arr[k] = L[i]; i++; k++; } /*copy remaining elements of R[] if they remain*/ while(j<n2){ arr[k] = R[j]; j++; k++; } } else{ while(i<n1 && j<n2){ if(compare(R[j],L[i],field)==true){ arr[k] = L[i]; i++; } else{ arr[k] = R[j]; j++; } k++; } /*copy remaining elements of L[] if they remain*/ while(i<n1){ arr[k] = L[i]; i++; k++; } /*copy remaining elements of R[] if they remain*/ while(j<n2){ arr[k] = R[j]; j++; k++; } } } /*the function returns the int values*/ int getIntData(mlb_stats t1, std::string s1){ if(s1=="G") return t1.G; else if(s1=="AB") return t1.AB; else if(s1 == "R") return t1.R; else if(s1 == "H") return t1.H; else if(s1 == "B2") return t1.B2; else if(s1 == "B3") return t1.B3; else if(s1 =="HR") return t1.HR; else if (s1 =="RBI") return t1.RBI; else if(s1 == "BB") return t1.BB; else if(s1 == "SO") return t1.SO; else if(s1 == "SB") return t1.SB; else if(s1 == "CS") return t1.CS; else return -1; } /*will give you the float value*/ float getFloData(mlb_stats t1,std::string s1){ if(s1=="AVG") return t1.AVG; else if(s1=="OBP") return t1.OBP; else if(s1== "SLG") return t1.SLG; else if(s1=="OPS") return t1.OPS; else return -1.0; } /*the function will give you back the char[] fields as strings*/ string getString(mlb_stats t1, std::string s1){ if(s1 == "Team") return t1.Team; else if(s1 == "League") return t1.League; return NULL; } /*this function will print out the team name and field given */ void printField(annual_stats* temp,int year, int num,std::string s1){ int i = findYearIndex(temp,year,num);//get the index of the starting year int x = 1; std::cout<<"\n\nTeam\t"<< year<<"\t"<<s1<<"\n"; if(s1 == "Team" || s1 == "League"){//if the field is a String while(x<=temp[i].no_teams){ std::cout<<temp[i].stats[x].Team<<"\t"<<getString(temp[i].stats[x],s1)<<"\n"; x++; } } else if(s1 == "AVG" || s1 == "OBP" || s1 == "SLG"|| s1 == "OPS"){//if the field is one of the floats while(x<=temp[i].no_teams){ std::cout<<temp[i].stats[x].Team<<"\t\t"<<getFloData(temp[i].stats[x],s1)<<"\n"; x++; } } else{ while(x <= temp[i].no_teams){ std::cout<<temp[i].stats[x].Team<<"\t\t"<<getIntData(temp[i].stats[x],s1)<<"\n"; x++; } } } /*this function prints out all of the teams in a given range*/ void printField(annual_stats* ptr,mlb_stats* arr,int size,int years,string field){ int i = 0; cout<<"\n\nYear\tTeam\t"<<field<<"\n"; while(i<size){ if(field=="Team" || field =="League"){ cout<<getTeamYear(ptr,arr[i],years)<<" "<<arr[i].Team<<" "<<getString(arr[i],field)<<"\n"; } else if(field == "AVG" || field =="OBP" || field == "SLG" || field == "SLG"){ cout<<getTeamYear(ptr,arr[i],years)<<" "<<arr[i].Team<<" "<<getFloData(arr[i],field)<<"\n"; } else{ cout<<getTeamYear(ptr,arr[i],years)<<" "<<arr[i].Team<<" "<<getIntData(arr[i],field)<<"\n"; } i++; } } /*this function checks an arry of annual stats and compares the team passed in with all of the teams in the annual stats and returns the year in which the team belongs*/ int getTeamYear(annual_stats* arr,mlb_stats t1,int years){ int i =1;//starting index of years stored int year = 0; while(i<=years){ int j = 1; do{ if( strncmp(t1.Team,arr[i].stats[j].Team,TEAM_NAME_LEN) == 0 && strncmp(t1.League,arr[i].stats[j].League,LEAGUE_NAME) == 0 && t1.G == arr[i].stats[j].G && t1.AB == arr[i].stats[j].AB && t1.R == arr[i].stats[j].R && t1.H == arr[i].stats[j].H && t1.B2 == arr[i].stats[j].B2 && t1.B3 == arr[i].stats[j].B3 && t1.HR == arr[i].stats[j].HR && t1.RBI == arr[i].stats[j].RBI && t1.BB == arr[i].stats[j].BB && t1.SO == arr[i].stats[j].SO && t1.SB == arr[i].stats[j].SB && t1.CS == arr[i].stats[j].CS && t1.AVG == arr[i].stats[j].AVG && t1.OBP == arr[i].stats[j].OBP && t1.SLG == arr[i].stats[j].SLG && t1.OPS == arr[i].stats[j].OPS ){ return arr[i].year; } else j++; }while(j<=arr[i].no_teams); i++; } return year; } /*will copy the data from an array of type annual stats into an array of mlb_stats*/ void copyTeams(annual_stats* arr,mlb_stats* teams,int startIndex,int endIndex){ int i = 0;//starting index for team array int k; if(startIndex < endIndex){ while(startIndex <= endIndex){ k=1; while(k <=arr[startIndex].no_teams){ teams[i]= arr[startIndex].stats[k]; i++; k++; } startIndex++; } } else{ while(endIndex <= startIndex){ k=1; while(k <= arr[endIndex].no_teams){ teams[i] = arr[endIndex].stats[k]; i++; k++; } endIndex++; } } }
true
ca838e442b494dfd7037eef57c503208ce2c4ce2
C++
luizinbrzado/FATEC
/Lista 3.1 - Ex7.cpp
ISO-8859-1
508
3.328125
3
[]
no_license
/*Criar um algoritmo que leia um nmero (NUM) e ento imprima os mltiplos de 3 e 5, ao mesmo tempo, no intervalo fechado de 1 a NUM*/ #include <stdio.h> #include <locale.h> main() { setlocale(LC_ALL, ""); int i, num, tres, cinco; printf("Coloque um nmero: "); scanf("%d", &num); for(i=1; i<=num; i++) { if(i%3==0) { printf("%d mltiplo de 3\n", i); } if(i%5==0) { printf("%d mltiplo de 5\n", i); } if(i%3==0 || i%5==0) printf("----------------\n"); } }
true
53de3520fc9326df28d4edc8ed7148f196b734e4
C++
mfc10001/baoluo
/ise/examples/game_server/game_core/GamePackage.cpp
UTF-8
5,047
2.6875
3
[ "Apache-2.0" ]
permissive
#include "GameItemManager.h" #include "../game_define/EntryBase.h" #include "GamePlayer.h" #include "../bass_class/Entry.h" #include "../game_define/ItemBase.h" #include "GameItem.h" PackageBase::PackageBase(GameItemManager* im, uint32 type) : m_size(0) , m_type(type) , m_im(im) { initCapacity(); } inline uint32 PackageBase::getValidCapacity() { return m_valid_grids; } bool PackageBase::checkLeftSpace() { return getValidCapacity() > m_size; } void PackageBase::initCapacity() { switch(m_type) { case PackageType_Equip: { m_valid_grids = PackageCap_Equip; m_upper_bound_grids = PackageCap_Equip; } break; case PackageType_Common: { m_valid_grids = PackageCap_CommonInit; m_upper_bound_grids = PackageCap_CommonMax; } break; case PackageType_Soul: { m_valid_grids = PackageCap_SoulInit; m_upper_bound_grids = PackageCap_SoulMax; } break; case PackageType_Treasure: { m_valid_grids = PackageCap_TreasureInit; m_upper_bound_grids = PackageCap_TreasureMax; } break; default: break; } } GameItem* PackageBase::getItemByThisID(uint32 thisid) { PackItemMap::iterator it = m_item_map.find(thisid); if(it==m_item_map.end()) { return NULL; } return (*it).second; } GameItem* PackageBase::getItemByBaseID(uint32 baseid) { return NULL; } GameItem* PackageBase::getItemByPosX(uint16 posX) { return NULL; } GamePlayer * PackageBase::getOwner() { m_im->getOwner(); } bool PackageBase::addItem(GameItem *item, AddItemAction act) { CheckCondition(item,false); CheckCondition(getValidCapacity(),false); GameItem* self_item = getItemByBaseID(item->getBaseID()); if(self_item) { self_item->incNumber(item->getItemNumber(),getOwner(),act); return true; } item->m_data.pack_type=m_type; if(m_im->addItem(item)) { m_item_map.insert(std::make_pair(item->id, item)); ++m_size; return true; } return false; } bool PackageBase::removeItem(GameItem* item, DelItemAction act, uint32 &err) { if (!item){ err = ERR_INNER; return false; } m_im->removeItem(item); m_item_map.erase(item->id); --m_size; return true; } bool PackageBase::moveItemIn(GameItem *item) { CheckCondition(item&&getValidCapacity(),false); item->m_data.pack_type=m_type; m_item_map.insert(std::make_pair(item->id, item)); ++m_size; return true; } bool PackageBase::moveItOut(GameItem *item) { PackItemMap::iterator it = m_item_map.find(item->getEntryID()); if(it == m_item_map.end()) { return false; } m_item_map.erase(it); return true; } ///// LuggablePackage::LuggablePackage(GameItemManager* im) :PackageBase(im, PackageType_Common) { } LuggablePackage::~LuggablePackage() { } //// TreasurePackage::TreasurePackage(GameItemManager* im) :PackageBase(im, PackageType_Treasure) { } TreasurePackage::~TreasurePackage() { } /// SoulPackage::SoulPackage(GameItemManager* im) :PackageBase(im, PackageType_Soul) { } SoulPackage::~SoulPackage() { } // EquipPackage::EquipPackage(GamePlayer *user): m_owner(user) { } EquipPackage::~EquipPackage() { } void EquipPackage::fillData(Json::Value &data) { for(uint8 i = EquipPosition_Begin;i<EquipPosition_Max;i++) { Json::Value temp; temp["pos"]=i; temp["level"]=m_equip_pos; } } uint32 EquipPackage::cost(uint32 level) { uint32 coststonenum=0; uint32 costmoney=100; uint32 money = m_owner->getMoney(MoneyType_Money); if(coststonenum != 0) { GameItem *stone = m_owner->m_pack_manager.m_commom_pack.getItemByBaseID(100001); CheckCondition(stone,ERR_STONE); CheckCondition(stone->getItemNumber()>coststonenum,ERR_STONE); } CheckCondition(money>=costmoney,ERR_MONEY); m_owner->subMoney(MoneyType_Money,costmoney,DelMoneyAction_EquipImprove); if(coststonenum != 0) { m_owner->m_pack_manager.reduceItemNumByBaseID(100001,coststonenum,DelItemAction_Improve); } return ERR_SUCCESS; } uint32 EquipPackage::Improve(uint8 type) { uint32 ret = cost(m_equip_pos[type].getLevel()); if(ret == ERR_SUCCESS) { m_equip_pos[type].levelUp(); } return ret; } /* GameItem * EquipPackage::getEquip(uint8 pos) { switch(pos) { case EquipPosition_Clothes: return getClothes(); case EquipPosition_Weapon: return getWeapon(); case EquipPosition_glove: return getGlove(); case EquipPosition_shoes: return getShoes(); default: return NULL; } } */ //// SoulEquipPackage::SoulEquipPackage(GameItemManager* im) :PackageBase(im, PackageType_Soul_Solt) { } SoulEquipPackage::~SoulEquipPackage() { } // TreasureSolt::TreasureSolt(GamePlayer *user): m_owner(user) { } TreasureSolt::~TreasureSolt() { } bool TreasureSolt::checkPosValid(uint8 type) { CheckCondition(type<TreasurePostion_Max,false); GameItem * item = m_treausre[type]; if(item) { return false; } return true; } uint32 TreasureSolt::onEquip(GameItem *item,uint8 pos) { CheckCondition(item,ERR_INNER); CheckCondition(checkPosValid(pos),ERR_POSITION); m_treausre[pos]=item; return ERR_SUCCESS; }
true
0f025fe854bf2af02948d5ef774524b5d3b634d8
C++
nian0601/CubeEngine
/Solution/Engine/CE_FileSystem.cpp
UTF-8
3,589
2.859375
3
[]
no_license
#include "stdafx.h" #include "CE_FileSystem.h" bool CE_FileSystem::GetAllFilesFromDirectory(const char* aDirectory, CE_GrowingArray<FileInfo>& someOutFilePaths) { CE_ASSERT(strlen(aDirectory) + 3 < MAX_PATH, "Path to directory is too long"); CE_String directory = aDirectory; directory += "/*"; WIN32_FIND_DATA data; HANDLE filehandle = FindFirstFile(directory.c_str(), &data); if (filehandle == INVALID_HANDLE_VALUE) return false; do { CE_String name = data.cFileName; if (name == "." || name == "..") continue; CE_String fullPath = aDirectory; fullPath += "/"; fullPath += name; if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { GetAllFilesFromDirectory(fullPath.c_str(), someOutFilePaths); } else { FileInfo& info = someOutFilePaths.Add(); info.myFileName = name; info.myFilePath = fullPath; info.myLastTimeModifiedLowbit = data.ftLastWriteTime.dwLowDateTime; info.myLastTimeModifiedHighbit = data.ftLastWriteTime.dwHighDateTime; RemoveFileExtention(name, info.myFileNameNoExtention); } } while (FindNextFile(filehandle, &data) != 0); if (GetLastError() != ERROR_NO_MORE_FILES) CE_ASSERT_ALWAYS("Something went wrong..."); FindClose(filehandle); return true; } void CE_FileSystem::GetFileName(const CE_String& aFilePath, CE_String& aNameOut) { int findIndex = aFilePath.RFind("/"); aNameOut = aFilePath.SubStr(findIndex + 1, aFilePath.Lenght()); } void CE_FileSystem::GetFileExtention(const CE_String& aFilePath, CE_String& aExtentionOut) { int findIndex = aFilePath.RFind("."); aExtentionOut = aFilePath.SubStr(findIndex + 1, aFilePath.Lenght()); } void CE_FileSystem::RemoveFileExtention(const CE_String& aFilePath, CE_String& aNameOut) { int findIndex = aFilePath.RFind("."); aNameOut = aFilePath.SubStr(0, findIndex-1); } bool CE_FileSystem::GetFileInfo(const CE_String& aFilePath, FileInfo& aFileInfoOut) { CE_ASSERT(aFilePath.Lenght() + 3 < MAX_PATH, "Filepath is too long"); WIN32_FIND_DATA data; HANDLE filehandle = FindFirstFile(aFilePath.c_str(), &data); if (filehandle == INVALID_HANDLE_VALUE) return false; aFileInfoOut.myFileName = data.cFileName; aFileInfoOut.myFilePath = aFilePath; aFileInfoOut.myLastTimeModifiedLowbit = data.ftLastWriteTime.dwLowDateTime; aFileInfoOut.myLastTimeModifiedHighbit = data.ftLastWriteTime.dwHighDateTime; FindClose(filehandle); return true; } bool CE_FileSystem::UpdateFileInfo(CE_GrowingArray<FileInfo>& someFiles) { bool somethingChanged = false; FileInfo newInfo; for (FileInfo& oldInfo : someFiles) { GetFileInfo(oldInfo.myFilePath, newInfo); FILETIME oldTime; oldTime.dwLowDateTime = oldInfo.myLastTimeModifiedLowbit; oldTime.dwHighDateTime = oldInfo.myLastTimeModifiedHighbit; FILETIME newTime; newTime.dwLowDateTime = newInfo.myLastTimeModifiedLowbit; newTime.dwHighDateTime = newInfo.myLastTimeModifiedHighbit; if (CompareFileTime(&oldTime, &newTime) != 0) somethingChanged = true; oldInfo.myLastTimeModifiedLowbit = newInfo.myLastTimeModifiedLowbit; oldInfo.myLastTimeModifiedHighbit = newInfo.myLastTimeModifiedHighbit; } return somethingChanged; } void CE_FileSystem::ReadEntireFile(const CE_String& aFilePath, FileContent& aFileContentOut) { FILE* file = fopen(aFilePath.c_str(), "rb"); fseek(file, 0, SEEK_END); long fileSize = ftell(file); fseek(file, 0, SEEK_SET); unsigned char* string = new unsigned char[fileSize + 1]; fread(string, fileSize, 1, file); fclose(file); string[fileSize] = 0; aFileContentOut.myContents = string; aFileContentOut.myFileSize = fileSize; }
true
74ee9b05d6841c57aa162cb755fe21a43c5d2a72
C++
hilbertanjou/OJ
/Codeforces/272 - Codeforces Round #167 (Div. 2)/C.cpp
UTF-8
1,414
2.515625
3
[]
no_license
#include <algorithm> #include <cstdio> using namespace std; #define l x << 1 #define r (l) + 1 typedef long long LL; const int MAXN = 444444; LL d[MAXN], e[MAXN]; inline void push(int x) { if (e[x]) { d[l] = d[r] = e[l] = e[r] = e[x]; e[x] = 0; } } inline void update(int x) { d[x] = max(d[l], d[r]); } void build(int x, int f, int t) { if (f == t) { scanf("%I64d", &d[x]); return; } int mid = f + t >> 1; build(l, f, mid); build(r, mid + 1, t); update(x); } LL query(int x, int f, int t, int qf, int qt) { if (qf <= f && t <= qt) return d[x]; push(x); int mid = f + t >> 1; LL a = 0, b = 0; if (qf <= mid) a = query(l, f, mid, qf, qt); if (qt > mid) b = query(r, mid + 1, t, qf, qt); return max(a, b); } void set(int x, int f, int t, int qf, int qt, LL v) { if (qf <= f && t <= qt) { d[x] = e[x] = v; return; } push(x); int mid = f + t >> 1; if (qf <= mid) set(l, f, mid, qf, qt, v); if (qt > mid) set(r, mid + 1, t, qf, qt, v); update(x); } int main() { int n, m; scanf("%d", &n); build(1, 1, n); scanf("%d", &m); while (m--) { int w, h; scanf("%d%d", &w, &h); LL b = query(1, 1, n, 1, w); printf("%I64d\n", b); set(1, 1, n, 1, w, b + h); } return 0; }
true
9afe09108614b63561e4b51e466c18fe29c54754
C++
aidanjoh/ENCM511_Fall2019
/Lab0_BF609_MOCKEDLEDandSwitches_Core0/src/Lab0_GeneralCode.cpp
UTF-8
6,221
2.578125
3
[]
no_license
/* * Lab0_GeneralCode.cpp * * Created on: September 19, 2019 * Author: Aidan */ #include <sys/platform.h> #include "adi_initialize.h" #include "Lab0_BF609_MOCKEDLEDandSwitches_Core0.h" #include <stdio.h> #define GARBAGE_VALUE 0xF2 //The garbage value was -1 before and (0xF2) static bool My_Init_SwitchInterface_Done = false; static bool My_Init_LEDInterface_Done = false; static unsigned char lastLEDValueWritten = GARBAGE_VALUE; //Underneath is a code stub void Start_Lab0(void) { printf("Here in Start_Lab0\n"); //unsigned char switchValueBad = My_ReadSwitches(); My_Init_SwitchInterface(); #if 1 My_Init_LEDInterface(); printf("Press Switch 1\n"); WaitTillSwitch1PressedAndReleased(); unsigned char intials[15] = {0x00, 0xe0, 0x1c, 0x13, 0x1c, 0xe0, 0x00, 0xc0, 0x00, 0xe0, 0xc3, 0xff, 0x03, 0x00, 0xc0}; int count = 0; unsigned char switchValue = 0; unsigned long long int intialTime; unsigned long long int WaitTime = 480000000; unsigned long long int time; while(1) { intialTime = ReadProcessorCyclesASM(); My_WriteLED(intials[count]); //printing intials line by line count = count + 1; //incrementing the counter switchValue = My_ReadSwitches(); if(switchValue == 1) { //WaitTillSwitch1PressedAndReleased(); WaitTime = WaitTime / 2; //decreasing the time to wait if(WaitTime == 0) { WaitTime = 480000000; } } else if(switchValue == 2) { //WaitTillSwitch2PressedAndReleased(); WaitTime = WaitTime * 2; //increasing the time to wait } time = ReadProcessorCyclesASM(); while(time < intialTime + WaitTime) { time = ReadProcessorCyclesASM(); } //This is making sure the count does not go past the amount of indexes in my intials array if(count == 16) { count = 0; } } /* unsigned char switchValue = My_ReadSwitches(); if (switchValue != 3) { printf("Bad switch read test -- value was 0x%x \n", switchValue); } */ #endif // This code I commented out below was for testing the functions at first /* unsigned char useLEDValue = 0x42; My_WriteLED(useLEDValue); unsigned char checkLEDValue = My_ReadLED(); if (checkLEDValue != useLEDValue) { printf("Bad LED read / write test\n"); } */ #if 0 for (useLEDValue = 0; useLEDValue <= 0x80; useLEDValue++) { My_WriteLED(useLEDValue); unsigned char checkLEDValue = My_ReadLED(); if (checkLEDValue != useLEDValue) { printf("Bad LED read / write test -- wrote %d and got back %d \n", useLEDValue, checkLEDValue); } else { printf("wrote %d and got back %d \n", useLEDValue, checkLEDValue); } } #elseif unsigned char intials[15] = {0x00, 0xe0, 0x1c, 0x13, 0x1c, 0xe0, 0x00, 0xc0, 0x00, 0xe0, 0xc3, 0xff, 0x03, 0x00, 0xc0}; for(int count = 0; count < 15; count++) { My_WriteLED(intials[count]); } #endif printf("leaving Start_Lab0\n"); } void My_Init_SwitchInterface(void) { printf("Stub for My_Init_SwitchInterface() \n"); My_Init_SwitchInterface_Done = true; #ifdef __ADSPBF609__ Init_GPIO_FrontPanelSwitches(); #endif } unsigned char My_ReadSwitches(void) { printf("Stub for My_ReadSwitches()\n"); if (My_Init_SwitchInterface_Done == false) { printf("Switch hardware not ready \n"); return GARBAGE_VALUE; } #ifdef __ADSPBF609__ FRONTPANEL_SWITCH_5BIT_VALUE activeLowValues = Read_GPIO_FrontPanelSwitches(); FRONTPANEL_SWITCH_5BIT_VALUE activeHighValues = ~activeLowValues; #define MASK_KEEP_LOWER_FIVE_BITS 0x1F // use bit-wise FRONTPANEL_SWITCH_5BIT_VALUE wantedSwitchValueActiveHigh = activeHighValues & MASK_KEEP_LOWER_FIVE_BITS; return wantedSwitchValueActiveHigh; #else return 0x55; #endif } unsigned char My_ReadLED(void) { printf("Stub for My_ReadLED()\n"); return lastLEDValueWritten; } void My_WriteLED(unsigned char neededLEDValue) { //printf("Stub for My_WriteLED() \n"); -> commented out to show clearly the intials if (My_Init_LEDInterface_Done == false) { printf("LED hardware not ready \n"); return; } #ifdef __ADSPBF609__ //Char array holding the values to print out unsigned char binaryArray[9]; charToBinary(neededLEDValue, binaryArray); Write_GPIO_FrontPanelLEDS(neededLEDValue); lastLEDValueWritten = neededLEDValue; #else //Char array holding the values to print out unsigned char binaryArray[9]; //Function converting the char to binary using the array holding the values charToBinary(neededLEDValue, binaryArray); printf("LED value - decimal %3d; hex 0x%2x; bit pattern %s \n", neededLEDValue, neededLEDValue, &binaryArray); lastLEDValueWritten = neededLEDValue; #endif } void My_Init_LEDInterface(void) { //printf("Stub for My_Init_LEDInterface() \n"); My_Init_LEDInterface_Done = true; #ifdef __ADSPBF609__ Init_GPIO_FrontPanelLEDS(); #endif } void charToBinary(unsigned char charValue, unsigned char* array) { unsigned char numberValueDuplicate = charValue; char i; for (i = 7; i >= 0; i--) { if (numberValueDuplicate & 0x01) array[i] = '1'; else array[i] = ' '; // change to '0' to get binary, I have the space to properly print intials numberValueDuplicate = numberValueDuplicate >> 1; } array[8] = 0; //To end the string with a null character } void WaitTillSwitch1PressedAndReleased() { FRONTPANEL_SWITCH_5BIT_VALUE switchValue = 0; while(1) { switchValue = My_ReadSwitches(); if(switchValue == 1) { printf("SW 1 was pressed\n"); while(1) { switchValue = My_ReadSwitches(); if(switchValue != 1) { printf("SW 1 was released\n"); return; } } } } } void WaitTillSwitch2PressedAndReleased() { FRONTPANEL_SWITCH_5BIT_VALUE switchValue = 0; while(1) { switchValue = My_ReadSwitches(); if(switchValue == 2) { printf("SW 2 was pressed"); while(1) { switchValue = My_ReadSwitches(); if(switchValue != 2) { printf("SW 2 was not released"); return; } } } } } void WaitTillSwitch3PressedAndReleased() { FRONTPANEL_SWITCH_5BIT_VALUE switchValue = 0; while(1) { switchValue = My_ReadSwitches(); if(switchValue == 4) { printf("SW 3 was pressed"); while(1) { switchValue = My_ReadSwitches(); if(switchValue != 4) { printf("SW 3 was not released"); return; } } } } }
true
819d73aa499e9b488ed0936d6f92a70d6aa721d9
C++
ekaterin17/Coursera-cpp
/4 Brown/Brown Belt Final/Transport A/parse.h
UTF-8
450
2.59375
3
[]
no_license
#pragma once #include <utility> #include <string_view> #include <optional> std::pair<std::string_view, std::optional<std::string_view>> SplitTwoStrict(std::string_view s, std::string_view delimiter = " "); std::pair<std::string_view, std::string_view> SplitTwo(std::string_view s, std::string_view delimiter = " "); std::string_view ReadToken(std::string_view& s, std::string_view delimiter = " "); double ConvertToDouble(std::string_view str);
true
c8f4c5c9040eb0dea6969cdd7ce468f1e56a2f2a
C++
Sarthak2/3rdSem-Data-Structures-Lab
/Labs_5_6_Application_Of_stacks/queueusingstack.cpp
UTF-8
672
2.90625
3
[]
no_license
#include <iostream> #include "stack1.cpp" using namespace std; class QusingStack{ stack1 s1, s2; public : void enQ(char ele) { while(!s1.isEmpty()) { s2.push(s1.pop()); } s1.push(ele); while(!s2.isEmpty()) { s1.push(s2.pop()); } } void dQ() { if(s1.isEmpty()) { cout << "Q is empty." << endl; } else { cout << s1.pop(); } } void display() { s1.display(); } }; int main() { QusingStack q ; q.enQ('a'); q.enQ('b'); q.enQ('c'); q.display(); }
true
fcc3185402ace4c15da5588431f8de33b0de3228
C++
vovadenisov/c-_project
/ourproject/container.h
UTF-8
2,117
2.890625
3
[]
no_license
#ifndef CONTAINER_H #define CONTAINER_H #include <string> #include <vector> #include <map> #include <SDL/SDL.h> #include <iostream> #include <stdio.h> #include <ctime> #include <stdlib.h> #include <SDL/SDL_ttf.h> #include <SDL/SDL_image.h> #include <form.h> #include <queue> #include <utility> using namespace std; class Container{ public: Container(read Params); //обрабатывает возможное нажатие принимает координаты нажатия мыши, //вызывает функцию класа virtual bool onClick(int x, int y, queue<string>* commands){ return false;} //вызывается при приходе очередного массива состояний. вытаскивает нужное состояние по имени virtual void change(pair<string, int> allState){} virtual void change(pair<string, string>& allState){} //возвращает объект картинки virtual img Drow() { return allImg[isActive]; } //возвращает номер группы int Group(){ return group; } virtual bool isName(string name); //включение модуля и связанных с ним сущностей virtual void enable(); //выключение модуля и связанных с ним сущностей virtual void decont(); //проверка видимости объекта bool isVisible(); void setVisible(bool param); protected: //функция перегружается для классов, где нужно движение или поворот virtual void move(int angle){} //массив изображений vector<img> allImg; //индекс активного изображения. int isActive = 0; //имя модуля string name; //группа по умолчанию -1 (без группы), кнопка выключения -2 int group = -1; //видимость объекта bool visible = true; }; #endif // CONTAINER_H
true
1cfcb4cb39be86ec52b44bc92d2169a3a42f926b
C++
WagnerMarcos/Algo2TP2
/include/Complex.h
UTF-8
3,645
3.265625
3
[]
no_license
#ifndef COMPLEX_H #define COMPLEX_H #include <iostream> #include <limits> #include <algorithm> #include <cmath> // Función para la comparación con margen de error: template<typename T> inline bool almostEqual(T a, T b); template <typename T = long double> class Complex { T x; T y; static T acceptableDelta; public: Complex(T real = T{}, T imag = T{}) : x(real), y(imag) {} Complex(const Complex& C) : x(C.x), y(C.y) {} ~Complex() {} T re() const { return x; } T im() const { return y; } static T acceptable_delta() { return Complex::acceptableDelta; } static T acceptable_delta(const T& delta) { return Complex::acceptableDelta = delta; } Complex conj() const { return Complex(x, -y); } T norm() const { return sqrt(x*x + y*y); } T arg() const { return std::atan2(y,x); } Complex operator+() const { return Complex(+x, +y); } Complex operator-() const { return Complex(-x, -y); } Complex operator+(const Complex& c) const { return Complex(x + c.x, y + c.y); } Complex operator-(const Complex& c) const { return Complex(x - c.x, y - c.y); } Complex operator*(const Complex& c) const { return Complex(x*c.x - y*c.y, y*c.x + x*c.y); } Complex operator/(const Complex& c) const { return Complex((x*c.x + y*c.y) / (c.x*c.x + c.y*c.y), (y*c.x - x*c.y) / (c.x*c.x + c.y*c.y)); } Complex& operator=(const Complex& c) { x = c.x; y = c.y; return *this; } Complex& operator+=(const Complex& c) { x += c.x; y += c.y; return *this; } Complex& operator-=(const Complex& c) { x -= c.x; y -= c.y; return *this; } Complex& operator*=(const Complex& c) { x = x*c.x - y*c.y; y = y*c.x + x*c.y; return *this; } Complex& operator/=(const Complex& c) { x = (x*c.x + y*c.y) / (c.x*c.x + c.y*c.y); y = (y*c.x - x*c.y) / (c.x*c.x + c.y*c.y); return *this; } bool operator==(const Complex & c) const { return almostEqual(x, c.x) && almostEqual(y, c.y); } bool operator!=(const Complex& c) const { return !almostEqual(x, c.x) || !almostEqual(y, c.y); } friend std::ostream& operator<<(std::ostream& os, const Complex& c) { return os << '(' << c.x << ',' << ' ' << c.y << ')'; } friend std::istream& operator>>(std::istream& is, Complex& c) { bool good = false; bool bad = false; T re = 0; T im = 0; char ch; if (is >> ch && ch == '(') { if (is >> re && is >> ch && ch == ',' && is >> im && is >> ch && ch == ')') good = true; else bad = true; } else if (is.good()) { is.putback(ch); if (is >> re) good = true; else bad = true; } if (good) { c.x = re; c.y = im; } else if (bad) is.setstate(std::ios::badbit); return is; } }; template <typename T> T Complex<T>::acceptableDelta = 10e-6; const Complex <long double> I(0, 1); // Función para la comparación que comprueba si dos números difieren en lo // suficientemente poco. // template <typename T> inline bool almostEqual(T a, T b) { const T absA = std::abs(a); const T absB = std::abs(b); const T absDelta = std::abs(a - b); if (a == b) // si son iguales, incluso inf return true; // si a o b son cero, o están lo suficientemente cerca // if (a == 0 || b == 0 || Complex<T>::acceptable_delta()) return true; // sino, usar el error relativo return Complex<T>::acceptable_delta() > absDelta / std::min<T>(absA + absB, std::numeric_limits<T>::max()); } template <typename T> Complex <T> exp(const Complex <T> & c) { return Complex<T>( std::exp (c.re()) * std::cos(c.im()), std::exp(c.re()) * std::sin(c.im())); } #endif //COMPLEX_H
true
488989dba26c8295737431defc1ad9bdcd716abb
C++
Turan-Chowdhury/Labs
/Data Structure Lab program/MID/Pattern Matching.cpp
UTF-8
597
3.265625
3
[]
no_license
#include<iostream> #include<cstring> using namespace std; int main() { char T[100], P[100]; cout<<endl<<"Enter a String Text : "; cin.getline(T,100); cout<<endl<<"Input Pattern : "; cin.getline(P,100); int s = strlen(T); int r = strlen(P); int k = 0; int max = s-r; while(k<=max) { for(int i=0; i<r; i++) { if(P[i] != T[k+i]) goto increment; } cout<<endl<<"Index : "<<k<<endl; return 0; increment: k++; } cout<<endl<<"Index : NULL"<<endl; return 0; }
true
69234fcc6ba4de9da0f40b3d2d5c969f71fc00e4
C++
NefedovDA/Huffman
/utility/main.cpp
UTF-8
3,447
2.71875
3
[]
no_license
#include <iostream> #include <vector> #include <cstring> #include "header/file_compress.h" #include "header/file_decompress.h" #include "header/file_writer.h" #include "header/file_reader.h" #include <ctime> #include <random> #include <cassert> //uint8_t buf[83886080]; int main(int argc, char **argv) { if (argc == 2) { if (std::strcmp(argv[1], "-h") != 0) { std::cerr << "use -h for help\n"; } else { std::cerr << "-h : help mode\n"; std::cerr << "-c SRC DST : compress file SRC and write result to DST\n"; std::cerr << "-d SRC DST : decompress file SRC and write result to DST\n"; } } else if (argc != 4) { std::cerr << "use -h for help\n"; } else { clock_t ts, te; if (std::strcmp(argv[1], "-c") == 0) { if (std::strcmp(argv[2], argv[3]) == 0) { std::cerr << "don't use one file for SRC and DST\n"; return 0; } std::cerr << "compressing...\n"; try { ts = clock(); file_compress(argv[2], argv[3]); te = clock(); } catch (std::runtime_error const &e) { std::cerr << "Failed to compress\n" << e.what(); return 0; } std::cerr << "finished in " << double(te - ts) / CLOCKS_PER_SEC << " sec\n"; } else if (std::strcmp(argv[1], "-d") == 0) { if (std::strcmp(argv[2], argv[3]) == 0) { std::cerr << "don't use one file for SRC and DST\n"; return 0; } std::cerr << "decompressing...\n"; try { ts = clock(); file_decompress(argv[2], argv[3]); te = clock(); } catch (std::runtime_error const &e) { std::cerr << "Failed to decompress\n" "problem: " << e.what(); return 0; } std::cerr << "finished in " << double(te - ts) / CLOCKS_PER_SEC << " sec\n"; } else { std::cerr << "use -h for help\n"; } } /*std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dist(0,255); for (unsigned char &i : buf) { i = dist(gen); } FILE *out = fopen("../test_files/rand/rand.txt", "wb"); fwrite(buf, 1, 83886080, out);*/ /*file_reader original("../test_files/rand/rand.txt"); file_reader copy("../test_files/rand/randret.txt"); while (!copy.eof()) { auto vo = original.read_symbol_block(); auto vc = copy.read_symbol_block(); for (size_t i = 0; i < vo.size(); ++i) { assert(vo[i] == vc[i]); } }*/ return 0; } // "-c" "../test_files/1/1.txt" "../test_files/1/1.huf" // "-d" "../test_files/1/1.huf" "../test_files/1/1ret.txt" // "-c" "../test_files/2/2.txt" "../test_files/2/2.huf" // "-d" "../test_files/2/2.huf" "../test_files/2/2ret.txt" // "-c" "../test_files/3/3.JPG" "../test_files/3/3.huf" // "-d" "../test_files/3/3.huf" "../test_files/3/3ret.JPG" // "-c" "../test_files/w_and_p/w_and_p.txt" "../test_files/w_and_p/w_and_p.huf" // "-d" "../test_files/w_and_p/w_and_p.huf" "../test_files/w_and_p/w_and_pret.txt" // "-c" "../test_files/rand/rand.txt" "../test_files/rand/rand.huf" // "-d" "../test_files/rand/rand.huf" "../test_files/rand/randret.txt"
true
9db20c08c17bbb4a410d359defe8fe78c24c2cb5
C++
MachineGunLin/LeetCode_Solutions
/无标签/284. 顶端迭代器.cpp
UTF-8
3,701
4.28125
4
[]
no_license
/* 这题给的类原型里PeekingIterator类公有继承自类Iterator,所以我们可以调用基类的next()和hasNext()方法。 虽然在class Iterator里只对next()和hasNext()方法做了声明,但是实际上类外肯定对这两个方法做了实现,所以我们 是可以直接调用Iterator::next()和Iterator::hasNext()来获取迭代器的下一个元素以及判断是否还存在下一个元素。 我们再来看子类PeekingIterator,这个类里我们要实现peek()、next()、hasNext(),还需要在构造函数里进行初始化。 先看peek(),因为返回值是int类型,是当前遍历到的元素的下一个元素,所以我们在类PeekingIterator里需要有一个int型 的data member - int cur,这里cur并不是我们已经迭代到的元素(而是我们迭代到的元素的下一个元素)。 再看hasNext(),我们需要在每一次迭代判断cur是不是最后一个元素,因此类PeekingIterator里还需要一个布尔变量记录cur 是不是最后一个元素,于是我们再声明一个变量bool isLast。 看一下具体的实现,构造函数里,一开始两个变量cur和isLast都没有初始化,构造函数里将isLast初始化为false。 因为一开始迭代器没指向任何元素,不过好在我们的cur是定义为当前元素的下一个元素,所以如果Iterator::hasNext()为真, 则将Iterator::next()的值赋值给cur,否则,说明没有元素了,把isLast赋值为真。 peek()函数需要返回下一个元素,由于这就是我们cur记录的就是下一个元素,所以直接return cur就可以了。 next()也返回下一个元素,但是调用了next()函数之后迭代器需要向后移动,所以我们用一个变量nextElement记录一下cur, 然后判断Iterator::hasNext()是否为真,如果为真,则cur = Iterator::next(); 否则,isLast = true; 这步是为了将cur 向后移动,返回的还是nextElement。对Iterator::hasNext()做判断的部分就是成员函数next()和成员函数peek()区别的地方。 hasNext()函数是判断当前元素后面是否还有元素,如果cur是最后一个元素,即isLast为true,则hasNext()为假,否则hasNext()为真。 所以这个函数里返回!isLast即可。 */ /* * Below is the interface for Iterator, which is already defined for you. * **DO NOT** modify the interface for Iterator. * * class Iterator { * struct Data; * Data* data; * Iterator(const vector<int>& nums); * Iterator(const Iterator& iter); * * // Returns the next element in the iteration. * int next(); * * // Returns true if the iteration has more elements. * bool hasNext() const; * }; */ class PeekingIterator : public Iterator { public: int cur; bool isLast; PeekingIterator(const vector<int>& nums) : Iterator(nums) { // Initialize any member here. // **DO NOT** save a copy of nums and manipulate it directly. // You should only use the Iterator interface methods. isLast = false; if(Iterator::hasNext() == true) { cur = Iterator::next(); } else { isLast = true; } } // Returns the next element in the iteration without advancing the iterator. int peek() { return cur; } // hasNext() and next() should behave the same as in the Iterator interface. // Override them if needed. int next() { if(isLast == true) { return -1; } int nextElement = cur; if(Iterator::hasNext() == true) { cur = Iterator::next(); } else { isLast = true; } return nextElement; } bool hasNext() const { return !isLast; } };
true
6eeec125afe7f64fd76b79d879d81a27ee836623
C++
emeitu/test
/boost/main.cpp
UTF-8
1,931
2.5625
3
[]
no_license
/************************************************************************* > File Name: main.cpp > Author: > Mail: > Created Time: Mon 20 Apr 2015 06:06:04 PM CST ************************************************************************/ #include<iostream> using namespace std; #include <boost/program_options.h> #include <string> #include <iostream> #pragma hdrstop int main(int argc, char* argv[]){ using std::string; using std::cout; using std::endl; namespace po = boost::program_options; po::options_description desc("My Commnad Line"); desc.add_options() ("help,h", "help message") ("author,a", "Author") ("string,s", po::value<string>(),"run as client and connect to the specified IP") ("int,i", po::value<int>(), "the number of concurrent connections") ; po::variables_map vm; try{ po::store( po::command_line_parser(argc, argv).options(desc).allow_unregistered().run(), vm); po::notify(vm); if (vm.count("author")) { cout << "Author: Chui-Wen Chiu" << endl; cout << "Blog: http://chuiwenchiu.spaces.live.com" << endl; } f (vm.count("help")) { cout << desc << endl; return 1; } if(vm.count("string")) { string sip = vm["string"].as<string>(); cout << "string: " << sip << endl; // connect to server... } f(vm.count("int")) { int t = vm["int"].as<int>(); cout << "int: " << t << endl; } }catch(boost::program_options::invalid_command_line_syntax&){ cout << "參數語法錯誤" << endl; cout << desc << endl; }catch(boost::bad_lexical_cast&){ cout << "參數型別錯誤" << endl; cout << desc << endl; }catch(...){ cout << "ERROR" << endl; } return 0; }
true
3274c670c8d79d10685571aaaaf81ad85a48d104
C++
Minusie357/Algorithm
/BackjoonAlgorithm/1043. 거짓말.cpp
UTF-8
1,608
2.59375
3
[ "Unlicense" ]
permissive
//#include <iostream> //#include <vector> //#include <queue> //using namespace std; // //#ifdef _DEBUG //#include "Utility.h" //#endif // _DEBUG // // // //constexpr int nmax = 51; //int main() //{ // ios::sync_with_stdio(false); // cin.tie(NULL); // // int n, m; // cin >> n >> m; // // int num_truth_people; // cin >> num_truth_people; // // vector<int> truth_people(num_truth_people); // for (int i = 0; i < num_truth_people; ++i) // { // cin >> truth_people[i]; // } // // vector<int> graph[nmax]; // vector<int> party[nmax - 1]; // int input; // for (int i = 0; i < m; ++i) // { // cin >> input; // party[i].resize(input); // for (int j = 0; j < input; ++j) // { // cin >> party[i][j]; // if (j > 0) // { // graph[party[i][j - 1]].push_back(party[i][j]); // graph[party[i][j]].push_back(party[i][j - 1]); // } // } // } // // queue<int> q; // bool visit[nmax] = { false }; // for (const auto& it : truth_people) // { // q.push(it); // visit[it] = true; // } // // while (q.empty() == false) // { // auto curr = q.front(); // q.pop(); // // int next; // for (int i = 0; i < graph[curr].size(); ++i) // { // next = graph[curr][i]; // if (visit[next]) // continue; // // visit[next] = true; // q.push(next); // } // } // // int answer = 0; // for (int i = 0; i < m; ++i) // { // bool unknown = true; // for (const auto& it : party[i]) // { // if (visit[it]) // { // unknown = false; // break; // } // } // // if (unknown) // { // //cout << "party(" << i << ") is unknown\n"; // answer++; // } // } // // cout << answer << "\n"; // return 0; //}
true
0cbb56203829eeb6772d831aff80c1aa162c1a41
C++
WillPlumHub/RPG
/commandMenu.cpp
UTF-8
1,713
3.890625
4
[]
no_license
/*This program is meant to manage the command selection. Firstsly, a menu is output to show the user their options. Secondly, the user is prompted to type the command they wish to execute. Then, the program should check the user's responce and take the appropriate action.*/ #include <iostream> #include <string> #include <algorithm> //Display command menu "graphics" void menu(std::string x) { if (x == "main") { std::cout << "0--------------------0\n|______COMMANDS______|\n| " << ">" << "Attack |\n| " << ">" << "Spells |\n| " << ">" << "Defend |\n0--------------------0" << std::endl; } else if (x == "spells" || x == "spell") { std::cout << "0--------------------0\n|______COMMANDS______|\n| >Flare-1 |\n| >Lightning-2 |\n0--------------------0" << std::endl; } } void spellManage() { std::string z; std::cout << "What spell?\n"; std::cin >> z; std::cout << z << " was selected" << std::endl; } //Choose action to be taken based off of user input void optManage(std::string x) { if (x == "spells" || x == "spell") { menu(x); spellManage(); } else if (x == "attack") { std::cout << "Selected the attack command\n"; } else if (x== "defend") { std::cout << "Selected the defence command\n"; } } int main() { std::string options[] = {"attack", "defence", "spell"}; std::string choice = "main"; menu(choice); std::cout << "Enter your choice\n"; std::cin >> choice; transform(choice.begin(), choice.end(), choice.begin(), ::tolower); for (auto x : options) { if (choice == x) { menu(choice); optManage(choice); } } return 0; }
true
dae7578e44a5ebc39fe481834e4bd12936d0c0ef
C++
pawanrj7/DSA
/Recersive_reverse_of_linklist.cpp
UTF-8
859
3.71875
4
[]
no_license
#include<iostream> using namespace std; struct node { int data; struct node *next; }*head=NULL; void create(int arr[], int n) { struct node *t, *last; head= new node; head->data=arr[0]; head->next= NULL; last=head; for(int i=1;i<n;i++) { t= new node; t->data=arr[i]; t->next= NULL; last->next=t; last=t; } } void display(struct node *p) { while(p!=NULL) { cout<<p->data<<" "; p=p->next; } } void reverse(struct node *q, struct node *p) { if(p!=NULL) { reverse(p,p->next); p->next=q; } else { head=q; } } int main() { int arr[]={1,3,4,5,6,7}; create(arr, 6); display(head); cout<<"\nList after reversing\n"; reverse(NULL ,head); display(head); return 0; }
true
90e09fedc2eb0c52ba13ecec06865fd71bc36f9e
C++
jongtae0509/codeup
/4000/4021_1.cpp
UTF-8
452
2.734375
3
[]
no_license
/************************************************************** 4021번 jongtae0509 C++ 정확한 풀이코드 길이:233 byte(s) 수행 시간:0 ms 메모리 :1120 kb ****************************************************************/ #include<stdio.h> int main(){ int a[8]; int i; int sum=0; for(i=0;i<7;i++){ scanf("%d",&a[i]); } for(i=0;i<7;i++){ if(a[i]%2!=0){ sum+=a[i]; } } if(sum!=0) printf("%d",sum); else printf("-1"); }
true
d9b98ce9024b7494f0e5363a8d13f81d802a1a2b
C++
teraNybble/rotateGame
/Projectile.cpp
UTF-8
706
3.078125
3
[]
no_license
#include "Projectile.h" Projectile::Projectile() : GameObject(Game2D::Rect(0, 0, 1, 1)) { Projectile(Game2D::Pos2(0, 0)); } Projectile::Projectile(Game2D::Pos2 pos) : GameObject(Game2D::Rect(pos,1,1)) { speed = 100; setSprite(Game2D::Sprite(Game2D::Rect(pos,1,1), Game2D::Rect(0, 0.5, 0.19921875, 0.19921875))); setColour(Game2D::Colour::White); } void Projectile::setDirection(Game2D::Pos2 direction) { //normalise the direction vector float c = sqrtf((direction.x * direction.x) + (direction.y * direction.y)); this->direction = Game2D::Pos2(direction.x/c,direction.y/c); } void Projectile::update(float time) { move(Game2D::Pos2(direction.x * time * speed, direction.y * time * speed)); }
true
d4b64a1f92accff17e0986bdae32929610ed1952
C++
AdrianSad/Gravity-Simulation
/Simulation/PlanetInfo.cpp
UTF-8
969
2.953125
3
[]
no_license
#include "PlanetInfo.hpp" #include <iostream> #include <iomanip> PlanetInfo::PlanetInfo(){ font.loadFromFile("fonts/Pixel.ttf"); text.setFont(font); text.setCharacterSize(12); text.setFillColor(sf::Color::White); text.setPosition(250, 10); } void PlanetInfo::update(float elapsedTime, Universe universe, RenderWindow & window) { Planet * planet = universe.getPlanet(sf::Vector2<double>(sf::Mouse::getPosition(window).x,sf::Mouse::getPosition(window).y)); if (planet) { text.setString("Speed : " + std::to_string((float)planet->getVel().x) + ", " + std::to_string((float)planet->getVel().y) + "\nPosition : " + std::to_string((int)planet->getPosition().x) + ", " + std::to_string((int)planet->getPosition().y) + "\nMass : " + std::to_string(planet->getMass())); } else { text.setString("Select planet to see more information"); } } void PlanetInfo::draw(sf::RenderTarget &target, sf::RenderStates states)const { target.draw(text, states); }
true
a9633cc5a9000a6c47b8d3703b79a5ae233d7f14
C++
allstarschh/training-handout
/debugging/ex_static_assertions_cpp/ex_static_assertions_cpp.cpp
UTF-8
306
3.0625
3
[ "BSD-3-Clause" ]
permissive
//--> slide enum E { A, B, C, NumElements }; static const char * strings[] = { "A", "B", "C" }; static_assert( sizeof strings / sizeof *strings == NumElements, "Oops, 'strings' and 'E' don't have the same number of elements" ); //<-- slide int main() { (void)strings; return 0; }
true
8e39325cdabecbb3a16ece198c1ccba3d8c32275
C++
a-quelle/CppStuff
/Chess/main.cpp
UTF-8
2,397
2.515625
3
[ "MIT" ]
permissive
#include "mainwindow.h" #include <QApplication> QImage emptyBoard; QImage blueBox; QImage redBox; QImage blackBox; QImage whiteBox; std::vector<QImage> pieceSprites; void loadAssets(){ QImageReader reader("/home/anton/QtCode/Chess/images/board.jpg"); reader.setAutoTransform(true); emptyBoard = reader.read(); emptyBoard = emptyBoard.mirrored(); reader.setFileName("/home/anton/QtCode/Chess/images/blackKing.png"); pieceSprites.push_back(reader.read()); reader.setFileName("/home/anton/QtCode/Chess/images/whiteKing.png"); pieceSprites.push_back(reader.read()); reader.setFileName("/home/anton/QtCode/Chess/images/blackQueen.png"); pieceSprites.push_back(reader.read()); reader.setFileName("/home/anton/QtCode/Chess/images/whiteQueen.png"); pieceSprites.push_back(reader.read()); reader.setFileName("/home/anton/QtCode/Chess/images/blackBishop.png"); pieceSprites.push_back(reader.read()); reader.setFileName("/home/anton/QtCode/Chess/images/whiteBishop.png"); pieceSprites.push_back(reader.read()); reader.setFileName("/home/anton/QtCode/Chess/images/blackKnight.png"); pieceSprites.push_back(reader.read()); reader.setFileName("/home/anton/QtCode/Chess/images/whiteKnight.png"); pieceSprites.push_back(reader.read()); reader.setFileName("/home/anton/QtCode/Chess/images/blackRook.png"); pieceSprites.push_back(reader.read()); reader.setFileName("/home/anton/QtCode/Chess/images/whiteRook.png"); pieceSprites.push_back(reader.read()); reader.setFileName("/home/anton/QtCode/Chess/images/blackPawn.png"); pieceSprites.push_back(reader.read()); reader.setFileName("/home/anton/QtCode/Chess/images/whitePawn.png"); pieceSprites.push_back(reader.read()); reader.setFileName("/home/anton/QtCode/Chess/images/blueBox.png"); blueBox = reader.read(); reader.setFileName("/home/anton/QtCode/Chess/images/redBox.png"); redBox = reader.read(); reader.setFileName("/home/anton/QtCode/Chess/images/blackBox.png"); blackBox = reader.read(); reader.setFileName("/home/anton/QtCode/Chess/images/whiteBox.png"); whiteBox = reader.read(); } int main(int argc, char *argv[]) { loadAssets(); QApplication a(argc, argv); QGuiApplication::setApplicationDisplayName(MainWindow::tr("Chess Application")); MainWindow w; w.show(); return a.exec(); }
true
7acb407ee532a58707bb7ef015b331c64083fe12
C++
rthomas67/te466-monster-moto-single-channel-arduino
/arduino/te466_driver/libraries/te466_driver/SignalInputPin.h
UTF-8
1,581
3.03125
3
[ "MIT" ]
permissive
#include <Arduino.h> #include "Signal.h" /* * SignalInputPin.h * * Created on: Nov 25, 2016 * Author: rrt */ #ifndef LIBRARIES_TE466_DRIVER_SIGNALINPUTPIN_H_ #define LIBRARIES_TE466_DRIVER_SIGNALINPUTPIN_H_ class SignalInputPin : public Signal { /* * The pin from which the digital state is read and compared with the signalOnValue */ uint8_t digitalPinNumber; /* Th signalOnValue variable holds HIGH or LOW, depending upon which of those represents the "signal-on" state * The default is LOW, which assumes the pin is initialized with INPUT_PULLUP (i.e. open == HIGH == "off") * If this object is constructed with a custom signalOnValue (which would be superfluous unless it is HIGH), * then isSignalActive() will return "true": * 1) UNLESS the pin is connected to ground, * or * 2) IF the pin is initialized as a normal INPUT (without using the built in PULLUP resistor). * * Note: If a digital pin is used without the internal pullup, it should use * an external pull-down resistor (~10K) */ uint8_t signalOnValue = LOW; boolean wasActiveOnPreviousCall = false; public: SignalInputPin(uint8_t digitalPinNumber); SignalInputPin(uint8_t digitalPinNumber, uint8_t signalOnValue); /* * Implemented to report true when the current digital state of the pin * matches the value of signalOnValue. */ boolean isSignalActive(); }; #endif /* LIBRARIES_TE466_DRIVER_SIGNALINPUTPIN_H_ */
true
dfdbaa3dc6e2350fa15512ee88e9267aa2dd9af7
C++
cbrown3010/EsperantoArduino
/EspernatoSketch.ino
UTF-8
908
3.265625
3
[]
no_license
#include <Servo.h> //Import the servo header Servo panCamera, tiltCamera; //Initialize both motors String data = ""; //Empty string to receive commands void setup() { servoPan.attach(10); //Assign servos to pins servoTilt.attach(11); Serial.begin(9600); //Set baudrate of 9600 } void loop() { while (Serial.available() > 0) //Check if data is received { char receivedChar = Serial.read(); //If received character is E pan camera if (receivedChar == 'T') { servoPan.write(data.toInt()); data = ""; // Clear string buffer } //If received character is E tilt camera else if (receivedChar == 'E') { servoTilt.write(data.toInt()); data = ""; // Clear string buffer } else { data += singleChar; //Append new data to string } } }
true
5a6fcd2ecb1d61b98dad2dad95e42b9ee7b018de
C++
yohshiy/programmers_notes
/lang/cpp/coroutine/EnumerableMixin.h
UTF-8
1,574
3.203125
3
[ "MIT" ]
permissive
/// /// Enumerable Mixin クラス /// /// #ifndef __ENUMERABLE_MIXIN_H__ #define __ENUMERABLE_MIXIN_H__ #include <boost/coroutine2/coroutine.hpp> /// Enumerable Mixin. /// 継承して Each メソッドを実装すると /// イテレーターを返す begin(), end() が使えるようになる template <typename ElementType> class EnumerableMixin { using coroutine_type = typename boost::coroutines2::coroutine<ElementType>::pull_type; public: using yield_type = typename boost::coroutines2::coroutine<ElementType>::push_type; using iterator = typename boost::coroutines2::detail::pull_coroutine<ElementType>::iterator; EnumerableMixin() :m_source(nullptr) {} virtual ~EnumerableMixin() {delete m_source; } inline iterator begin() { delete m_source; m_source = new coroutine_type([&](auto & yield){this->Each(yield);}); return boost::coroutines2::detail::begin(*m_source); } inline iterator end() { if (m_source == nullptr) { return boost::coroutines2::detail::end(*m_source); } return iterator::iterator(); } protected: /// 要素を逐次返すメソッド. /// @param yield 値を返すためのコルーチンオブジェクト /// /// yield を関数オブジェクト yield(elem) のように使い、 /// 要素を返す. /// 返す要素は ElementType で指定した型 /// virtual void Each(yield_type &yield) = 0; private: coroutine_type *m_source; }; #endif
true
8118adb1746dfdca81270fa5357bc4292339990a
C++
GreenStaradtil/AU-E19-E1OPRG
/L08/E8.1/AccessCode.cpp
UTF-8
1,755
3.078125
3
[]
no_license
#include <stdio.h> #include <string.h> #include "AccessCode.h" void createCode( char codeAlias[] ) { int ascii; srand( time(0) ); for( size_t index=0; index<CODE_SIZE; index++ ) { ascii = (rand()%75 + 48); // if ascii number is NOT a letter or digit (check ASCII table) if( 57<ascii && ascii<65 || 90<ascii && ascii<97 ) index--; else codeAlias[ index ] = ascii; } codeAlias[ CODE_SIZE ] = '\0'; } int checkCode( char correctCodeAlias[], char codeToCheckAlias[] ) { //if (strlen(correctCodeAlias) != strlen(codeToCheckAlias)) // return 0; int compareResult = strncmp(correctCodeAlias, codeToCheckAlias, CODE_BUFFER); return compareResult == 0 ? 1 : 0; } int changeCode( char currentCodeAlias[] ) { char inputCurrentCode[CODE_BUFFER]; char inputNewCode[CODE_BUFFER], inputNewCodeConfirm[CODE_BUFFER]; printf_s("Enter current code: "); scanf_s("%8s", inputCurrentCode, CODE_BUFFER); // Compare current code with the input code int compareCurrent = strcmp(currentCodeAlias, inputCurrentCode); // Code is invalid if (compareCurrent != 0) { return 0; } // Get the new code from user printf_s("Enter new code: "); scanf_s("%8s", inputNewCode, CODE_BUFFER); // Get the new code from user again to confirm printf_s("Enter new code: "); scanf_s("%8s", inputNewCodeConfirm, CODE_BUFFER); int compareNew = strcmp(inputNewCode, inputNewCodeConfirm); // New codes match and current code should be updated if (compareNew == 0) { strncpy(currentCodeAlias, inputNewCode, CODE_BUFFER); return 1; } // New codes did not match and current code should not be updated else { return 0; } }
true
fc957ef5fa320403a44c3489d1b454dddf434e4c
C++
shrutiarora312/Compiler-lab-codes
/accept string/string_accepted.cpp
UTF-8
779
3.28125
3
[]
no_license
#include<iostream> #include<conio.h> #include<string.h> #include<stdio.h> using namespace std; int main() { char string[20]; int state=0,count=0; cout<<"the grammar is: S->aS, S->Sb, S->ab \n"; cout<<"enter the string to be checked \n"; gets(string); while(string[count]!='\0') { switch(state) { case 0: if (string[count]=='a') state=1; else state=3; break; case 1: if (string[count]=='a') state=1; else if(string[count]=='b') state=2; else state=3; break; case 2: if (string[count]=='b') state=2; else state=3; break; default: break; } count++; if(state==3) break; } if(state==2) cout<<"string is accepted"; else cout<<"string is not accepted"; return 0; }
true
b5520f7d27156b0d981971460edff86611010f6f
C++
ThomasV42/Tete_Robotisee
/src/ServoMoteurRC.h
UTF-8
4,399
3.109375
3
[]
no_license
/** \file ServoMoteurRC.h \class ServoMoteurRC \brief Classe permettant le controle des servomoteurs fonctionnant en MLI Modulation par largeur d'impulsions) \version 1.00 */ #ifndef SERVOMOTEURRC_H #define SERVOMOTEURRC_H #include <iostream> #include <string> #include <vector> #include "serialib.h" #include "ServoMoteur.h" using namespace std; class ServoMoteurRC : public ServoMoteur { private: /* ATTRIBUTS */ /// Chaîne permettant de connaître l'erreur retournée string erreur; /// Entier qui permet d'identifier un servomoteur int ID; // voie de 0 à 5 pour les moteurs 0 à 5 /// Vecteur permettant de réaliser notre trame vector<unsigned char> trame; /// Création d'un objet serialib -> voie série serialib* VS; /// Définit le port utilisé pour la voie série char* device; /// Définit la vitesse de la voix série int speed; /** *\brief Méthode permettant de modifier la valeur dans la trame */ void valeurTrame(unsigned short newValeur); /** *\brief Méthode permettant d'envoyer la trame sur la voie série */ void envoyerTrame(); public: /* ENUM */ /** \enum TacheRealisee * Enumeration des fonctions realisables */ enum class TacheRealisee { setPosition = 0x84, ///< Modification de la position setVitesse = 0x87, ///< Modification de la vitesse setAcceleration = 0x89, ///< Modification de l'accélération getPosition = 0x90, ///< Récupération de la position getEtatMouvement = 0x93,///< Récupération de l'etat du servomoteur (actif ou inactif) getErrors = 0xA1 ///< Récupération des erreurs }; /* CONSTRUCTEUR */ /** *\brief Ce constructeur initialise les attributs de l'objet ServoMoteurRC */ ServoMoteurRC(); /** \brief Constructeur de la classe ServoMoteurRC avec le numéro du servomoteur souhaité * * Ce constructeur initialise les attributs de l'objet ServoMoteurRC * *\param[in] ID Identifiant d'un servomoteur */ ServoMoteurRC(int ID); /** \brief Destructeur de la classe ServoMoteurRC * * Ce destructeur supprime un objet ServoMoteurRC * */ ~ServoMoteurRC(); /* FCT VIRTUELLES */ /** \brief Fonction virtuelle d'initialisation * * Cette fonction permet l'initialisation des servomoteurs et l'ouverture de la voie série * * \param[in] New_Sexe Ce parametre est un std::string FEMME pour une voix de femme par defaut la voix est sur HOMME */ virtual bool init(int fileDes); /** \brief Fonction virtuelle de fermeture * * Cette fonction permet la fermeture de la voie série * */ virtual void arret(); /** \brief Fonction virtuelle de modification de position * * Cette fonction permet de modifier la position d'un servomoteur * * \param[in] newPosition Ce parametre est la valeur souhaitée pour la position à atteindre */ virtual int setPosition(unsigned short newPosition); /* FCT AJOUTEES */ /** \brief Fonction virtuelle de modification de la vitesse * * Cette fonction permet de modifier la vitesse d'un servomoteur * * \param[in] newVitesse Ce parametre est la valeur souhaitée pour la vitesse de deplacement */ void setDeviceVS(char* _device); /** \brief Fonction permettant de changer la vitesse de la voie série * * Cette fonction permet de modifier la vitesse de la voie série * * \param[in] _speed Ce parametre est la nouvelle vitesse à appliquer */ void setSpeedVS(int _speed); /** \brief Fonction permettant de réaliser la trame de commande * * Cette fonction permet de réaliser la trame de commande des servomoteurs * * \param[in] newTache Ce parametre est la nouvelle tache à effectuer * \param[in] valeur Ce parametre est la nouvelle valeur à communiquer */ void ecrireTrame(TacheRealisee newTache, unsigned short valeur); /** \brief Fonction permettant de lire la trame envoyée * * Cette fonction permet de debuger, et de vérifier l'exactitude de la trame envoyée au servomoteur * */ string AfficherTrame(); }; #endif /* SERVOMOTEURRC_H */
true
244960f57454810b1793a781c159c5472d7a2604
C++
RobertKraaijeveld/GrandeOmegaVisualization
/lib/DataProcesser/src/StatisticalAnalyzer/Classifiers/KNearestNeighbours/KNearestNeighbours.cpp
UTF-8
4,702
2.734375
3
[]
no_license
#include "KNearestNeighbours.h" #include "../../../Utilities/Utilities.h" #include "../../Point/IClusteringPoint.h" #include "../../GenericVector/GenericVector.h" #include <vector> #include <limits> #include <iostream> std::vector<std::shared_ptr<IClusteringPoint>> KNearestNeighbours::getNearestNeighbours(std::shared_ptr<IClusteringPoint>& subjectPoint, int maxNeighboursAmount, std::vector<std::vector<std::shared_ptr<IClusteringPoint>>>& clusters) { std::map<std::shared_ptr<IClusteringPoint>, float> neighboursAndDistances; //used to exclude distances lower than the lowest recorded nearest neighbour distance float maximumDistance = std::numeric_limits<float>::max(); for (size_t i = 0; i < clusters.size(); i++) { vector<std::shared_ptr<IClusteringPoint>> currentTrainingCluster = clusters[i]; for (size_t j = 0; j < currentTrainingCluster.size(); j++) { auto currTrainingPoint = currentTrainingCluster[j]; GenericVector subjectsVector = (*subjectPoint).getVector(); GenericVector currTrainingPointVector = (*currTrainingPoint).getVector(); float currentDistanceToTrainingPoint = subjectsVector.getEuclidDistance(currTrainingPointVector); if (currentDistanceToTrainingPoint < maximumDistance) { if (neighboursAndDistances.size() < maxNeighboursAmount) { neighboursAndDistances.insert(make_pair(currTrainingPoint, currentDistanceToTrainingPoint)); } else { bool getHighest = true; float highestDistance = Utilities::getHighestOrLowestValueKV(neighboursAndDistances, getHighest).second; std::shared_ptr<IClusteringPoint> neighbourWithHighestDistance = Utilities::getHighestOrLowestValueKV(neighboursAndDistances, getHighest).first; if (currentDistanceToTrainingPoint < highestDistance) { neighboursAndDistances.erase(neighbourWithHighestDistance); neighboursAndDistances.insert(make_pair(currTrainingPoint, currentDistanceToTrainingPoint)); //updating maximumDistance since the neighbours are now updated maximumDistance = Utilities::getHighestOrLowestValueKV(neighboursAndDistances, getHighest).second; } } } if (neighboursAndDistances.size() == maxNeighboursAmount) { bool getHighest = true; float highestDistance = Utilities::getHighestOrLowestValueKV(neighboursAndDistances, getHighest).second; maximumDistance = highestDistance; } } } return Utilities::getKeysOfMap(neighboursAndDistances); } int KNearestNeighbours::getNewClusterIdByVote(std::shared_ptr<IClusteringPoint> point, std::vector<std::shared_ptr<IClusteringPoint>> nearestNeighbours) { map<int, int> clusterIdsCounts; for (size_t i = 0; i < nearestNeighbours.size(); i++) { std::shared_ptr<IClusteringPoint> currentNeighbour = nearestNeighbours[i]; clusterIdsCounts[currentNeighbour->getClusterId()] += 1; } //bit of a waste bool getHighest = true; int mostCommonNeighbourClusterId = Utilities::getHighestOrLowestValueKV(clusterIdsCounts, getHighest).first; return mostCommonNeighbourClusterId; } std::vector<std::vector<std::shared_ptr<IClusteringPoint>>> KNearestNeighbours::getClassifiedPoints() { std::vector<std::vector<std::shared_ptr<IClusteringPoint>>> resultingClassifiedPoints; //Prepping resultingClassifiedPoints 2d vector for (size_t i = 0; i < trainingClusters.size(); i++) { std::vector<std::shared_ptr<IClusteringPoint>> newEmptyCluster; resultingClassifiedPoints.push_back(newEmptyCluster); } for (std::shared_ptr<IClusteringPoint> currPoint : inputPoints) { std::vector<std::shared_ptr<IClusteringPoint>> nearestNeighbours = KNearestNeighbours::getNearestNeighbours(currPoint, maxAmountOfNeighbours, trainingClusters); int newClusterIndexForThisPoint = getNewClusterIdByVote(currPoint, nearestNeighbours); resultingClassifiedPoints[newClusterIndexForThisPoint].push_back(currPoint); } int sumOfResultPoints = 0; for(size_t i = 0; i < resultingClassifiedPoints.size(); i++) { sumOfResultPoints += resultingClassifiedPoints[i].size(); } return resultingClassifiedPoints; }
true
904fcb2d3c3e6c365097fc3c6a61403d1ee71a1f
C++
krishauser/KrisLibrary
/meshing/TriMesh.h
UTF-8
3,170
3.265625
3
[]
permissive
#ifndef MESHING_TRIMESH_H #define MESHING_TRIMESH_H #include <KrisLibrary/math3d/primitives.h> #include <KrisLibrary/math3d/Triangle3D.h> #include <KrisLibrary/math3d/Ray3D.h> #include <KrisLibrary/utils/IntTriple.h> #include <vector> #include <iosfwd> /** @defgroup Meshing * @brief Classes defining operations on basic triangle meshes */ /** @ingroup Meshing * @brief The namespace for all classes/functions in the Meshing package. */ namespace Meshing { using namespace Math3D; using namespace std; /** @ingroup Meshing * @brief A basic triangle mesh. * * The mesh is represented by a list of vertices (Vector3's) and a list of * indexed triangles. A triangle is represented by a set of 3 integers * (an IntTriple) that index into the vertex list to produce the actual * triangle vertices. So a triangle whose vertices are verts[1], verts[2], * and verts[3] will be represented by the IntTriple [1,2,3]. * * There are several "types" of indices floating around: * * Vertex index - an index into the verts array. <br> * Triangle index - an index into the tris array. <br> * i'th vertex of a triangle t, i={0,1,2} - t[i] is a vertex index. <br> * j'th edge of a triangle t, j={0,1,2} - the edge between vertices * indexed by t[j+1] and t[j+2] (indices modulo 3), that is, the edge * opposite the j'th vertex of t. */ struct TriMesh { typedef IntTriple Tri; ///@name Accessors //@{ ///Returns the v'th vertex of triangle tri Vector3& TriangleVertex(int tri,int v); const Vector3& TriangleVertex(int tri,int v) const; ///Calculates the normal of triangle tri Vector3 TriangleNormal(int tri) const; ///Returns a Triangle3D structure for triangle tri void GetTriangle(int tri,Triangle3D& t) const; ///Calculates a list of triangle indices incident to vertex v. O(T) time. void GetIncidentTris(int v,vector<int>& tris) const; ///Same as above, but appends the triangles to the end of t void AppendIncidentTris(int v,vector<int>& t) const; ///Returns the vertex indices (v1,v2) of the e'th edge of triangle tri void GetEdge(int tri,int e,int& v1,int& v2) const; ///Returns the index of the triangle adjacent to tri, at the e'th edge ///or -1 if there is none. O(T) time. int GetAdjacentTri(int tri,int e) const; //@} ///@name Calculations //@{ bool IsValid() const; void GetAABB(Vector3& bmin, Vector3& bmax) const; //returns the closest/collided triangle int ClosestPoint(const Vector3& pt,Vector3& cp) const; int RayCast(const Ray3D& r,Vector3& pt) const; bool Intersects(const Plane3D&) const; bool PlaneSplits(const Plane3D&,Real& dmin,Real& dmax) const; //@} ///@name Modifiers //@{ void Transform(const Matrix4& mat); void FlipFaces(); void Merge(const vector<TriMesh>& meshes); void MergeWith(const TriMesh& mesh); void RemoveUnusedVerts(); //@} bool Load(const char* fn); bool Save(const char* fn) const; vector<Vector3> verts; vector<Tri> tris; }; istream& operator >> (istream& in,TriMesh& tri); ostream& operator << (ostream& out,const TriMesh& tri); bool LoadMultipleTriMeshes(const char* fn,TriMesh& tri); } //namespace Meshing #endif
true
e608fc2ec05569a79149f0da14881de93bd3fb11
C++
zfzackfrost/incredible_vulk
/include/ivulk/core/uniform_buffer.hpp
UTF-8
4,135
2.890625
3
[ "MIT" ]
permissive
/** * @file uniform_buffer.hpp * @author Zachary Frost * @copyright MIT License (See LICENSE.md in repostory root) * @brief `UniformBufferObject` class. */ #pragma once #include <ivulk/config.hpp> #include <ivulk/core/buffer.hpp> #include <ivulk/core/shader_stage.hpp> #include <iomanip> #include <typeindex> namespace ivulk { struct UniformBufferObjectInfo final { VkDeviceSize size = 0u; VmaMemoryUsage memoryMode = E_MemoryMode::CpuToGpu; VkShaderStageFlags stageFlags = E_ShaderStage::AllGraphics; uint32_t defaultBinding = 0u; }; class UniformBufferObject : public VulkanResource<UniformBufferObject, UniformBufferObjectInfo, Buffer::Ptr, VkDeviceSize, VkDescriptorSetLayoutBinding> { public: VkBuffer getBuffer() { return getHandleAt<0>()->getBuffer(); } VkDeviceSize getSize() { return getHandleAt<1>(); } VkDescriptorSetLayoutBinding getDescriptorSetLayoutBinding(uint32_t bindingIndex) { auto descrBinding = getHandleAt<2>(); descrBinding.binding = bindingIndex; return descrBinding; } template <typename BufferData> void setUniforms(const BufferData bufData) { constexpr VkDeviceSize SZ = sizeof(BufferData); if (SZ != getSize()) { throw std::runtime_error(utils::makeErrorMessage( "VK::UNIFORM", "Supplied buffer data does not match the size of the `UniformBufferObject`")); } if (auto buf = getHandleAt<0>()) { BufferData data[] = {bufData}; buf->fillBuffer(data, SZ); } } private: friend base_t; UniformBufferObject(VkDevice device, Buffer::Ptr buffer, VkDeviceSize sz, VkDescriptorSetLayoutBinding descrBinding) : base_t(device, handles_t {buffer, sz, descrBinding}) { } static UniformBufferObject* createImpl(VkDevice device, UniformBufferObjectInfo createInfo) { auto buffer = Buffer::create(device, { .size = createInfo.size, .usage = E_BufferUsage::Uniform, .memoryMode = createInfo.memoryMode, }); VkDescriptorSetLayoutBinding descrBinding { .binding = createInfo.defaultBinding, .descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, .descriptorCount = 1, .stageFlags = createInfo.stageFlags, }; return new UniformBufferObject(device, buffer, createInfo.size, descrBinding); } void destroyImpl() { if (auto b = getHandleAt<0>()) b->destroy(); } }; struct PipelineUniformBufferBinding final { UniformBufferObject::Ref ubo; uint32_t binding; vk::DescriptorSetLayoutBinding getDescriptorSetLayoutBinding() { vk::DescriptorSetLayoutBinding result; if (auto r = ubo.lock()) { result = r->getDescriptorSetLayoutBinding(binding); } return result; } VkBuffer getBuffer() const { if (auto r = ubo.lock()) { return r->getBuffer(); } return VK_NULL_HANDLE; } VkDeviceSize getSize() const { if (auto r = ubo.lock()) { return r->getSize(); } return 0u; } }; } // namespace ivulk
true
387bd7ecf3248eff03d636bf0384893bc6c8f3ef
C++
adarshkumar8225/practice_c-
/SOLDVAL.cpp
UTF-8
782
2.796875
3
[]
no_license
#include<iostream> #include<bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while(t--) { int n; cin>>n; vector<int> a(n),l(n); for(int i=0;i<n;i++) { cin>>a[i];l[i]=a[i];} vector<int> r=l; //starting from i=1 find min of l[i] and (l[i-1]+1) store it in l[i] for(int i=1;i<n;i++) l[i]=min(l[i],l[i-1]+1); //first make r=l then for r[i] take min of r[i] and r[i+1]+1 and store it in r[i]. for(int i=n-2;i>=0;i--) r[i]=min(r[i],r[i+1]+1); //print min of the two for every index for(int i=0;i<n;i++) cout<<min(l[i],r[i])<<" "; cout<<"\n"; } }
true
97e6bce8e23fcad79a6d4794c06778060f8add80
C++
Hunter54/Expression-Evaluator
/main.cpp
UTF-8
1,569
3.671875
4
[]
no_license
#include <iostream> #include <stack> #include "Parse_evaluate.h" #include <string> using namespace std; int main() { string a; int c; do{ cout<<"\n\n\n__________MENU__________"; cout<<"\n 1-Enter new expression:"; cout<<"\n 2-Parse to prefix notation"; cout<<"\n 3-Evaluate expression"; cout<<"\n 4-Display expression"; cout<<"\n 0-Exit\n"; cout<<"\n\nYour option: "; cin>>c; switch(c){ case 1:{ cout<<"Give a new infix expression: "; cin>>a; break; } case 2:{ if(a.empty()){ cout<<"No expression to parse"; } else { cout << "Prefix notation of the expression is: " << Expression::infixToPrefix(a); } break; } case 3:{ if(a.empty()){ cout<<"No expression to evaluate"; } else { cout << "Expression value is: " << Expression::evaluate(Expression::infixToPrefix(a)); } break; } case 4:{ cout<<"Expression is :"<<a; break; } case 0:{ break; } } }while(c!=0); //"2*(50+21)-6/(30-25)+25" // a="((12+32)*2)/5"; // cout<<infixToPrefix(a)<<endl; // cout<<endl<<evaluate(infixToPrefix(a)); return 0; }
true
35693b00bf75769e9fbb525ce8afef1d25b75835
C++
aivarasatk/Piltuvelis
/exportwindow.cpp
UTF-8
4,466
2.578125
3
[]
no_license
#include "exportwindow.h" #include <QHBoxLayout> #include <QDir> #include <QFileDialog> #include <QMessageBox> ExportWindow::ExportWindow(QStringList genOptions, QWidget *parent) : QDialog(parent) { //formuojam opcija kelti i gen faila optionExportToGen = new QCheckBox(textExportToGenFile); optionExportToGen->setCheckState(Qt::Checked); connect(optionExportToGen, SIGNAL(stateChanged(int)), this, SLOT(showGenFileSelection(int))); //gen failo opcijos UI genSelectionText = new QLabel(text1); genSelection = new QComboBox(); genSelection->addItems(genOptions); //eip failo pasirinkimo UI //connect(optionCheckFiles, SIGNAL(stateChanged(int)), this, SLOT(changeFileSelectVisability(int))); //testi UI continueButton = new QPushButton(text5); connect(continueButton, SIGNAL(clicked(bool)), this, SLOT(continuePressed())); //kuriam layouta mainLayout = new QVBoxLayout(); mainLayout->stretch(0); setLayout(mainLayout); createLayout(); optionExportToGen->setCheckState(Qt::Unchecked); } ExportWindow::~ExportWindow(){ cleanLayout(mainLayout); } void ExportWindow::createLayout(){ mainLayout->addWidget(optionExportToGen); QHBoxLayout* genOptionLayout = new QHBoxLayout; genOptionLayout->addWidget(genSelectionText); genOptionLayout->addWidget(genSelection); mainLayout->addLayout(genOptionLayout); mainLayout->addWidget(continueButton, 0, Qt::AlignCenter); } void ExportWindow::showGenFileSelection(int state){ if(state == Qt::Checked){ genSelection->show(); genSelectionText->show(); }else if (state == Qt::Unchecked){ genSelection->hide(); genSelectionText->hide(); } } void ExportWindow::changeFileSelectVisability(int state){ if(state == Qt::Checked){//sukuriam pasirinkima eipFileSelectionText = new QLabel(text3); selectedFileLine = new QLineEdit(); selectedFileLine->setEnabled(false); fileSelectButton = new QPushButton(text4); connect(fileSelectButton, SIGNAL(clicked(bool)), this, SLOT(selectFile())); QHBoxLayout* fileSelectionLayout = new QHBoxLayout; fileSelectionLayout->addWidget(eipFileSelectionText); fileSelectionLayout->addWidget(selectedFileLine); fileSelectionLayout->addWidget(fileSelectButton); mainLayout->insertLayout(mainLayout->indexOf(optionCheckFiles) + 1, fileSelectionLayout, 0); }else{//sunaikinam pasirinkima delete eipFileSelectionText; eipFileSelectionText = nullptr; delete selectedFileLine; selectedFileLine = nullptr; delete fileSelectButton; fileSelectButton = nullptr; delete mainLayout->itemAt(mainLayout->indexOf(optionCheckFiles) + 1); } } void ExportWindow::reset(){ optionExportToGen->setCheckState(Qt::Unchecked); genSelection->setCurrentIndex(0); } void ExportWindow::cleanLayout(QLayout* layout){ if(layout == nullptr){ return; } QLayoutItem *child; QLayout * sublayout; QWidget * widget; while ((child = layout->takeAt(0))) { if ((sublayout = child->layout()) != nullptr) { cleanLayout(sublayout);} else if ((widget = child->widget()) != nullptr) {delete widget;} else {delete child;} delete child; } layout = nullptr; } void ExportWindow::selectFile(){ selectedFile = QFileDialog::getOpenFileName(this, "Išsaugoti failą",QDir::currentPath(), "*.eip"); if(!selectedFile.isEmpty()){ selectedFileLine->setText(selectedFile); } } void ExportWindow::continuePressed(){ /*if(optionCheckFiles->checkState() == Qt::Checked && !selectedFileLine->text().isEmpty()){ genSelectionIndex = genSelection->currentIndex(); performFileCheck = true; success = true; close(); }else if(optionCheckFiles->checkState() == Qt::Checked && selectedFileLine->text().isEmpty()){ QMessageBox::information(this, "Klaida", "Nepasirinkta failas"); }*/ if(optionExportToGen->checkState() == Qt::Checked){ genSelectionIndex = genSelection->currentIndex(); success = true; exportToGen = true; close(); }else if(optionExportToGen->checkState() == Qt::Unchecked){ success = true; close(); } }
true
f257475deb5d650dde212e44fa913504dfd71d39
C++
JamShan/XYZGameEngine
/XYZGameEngine/Engine/Base/Collection/Array/Array.hpp
UTF-8
1,402
2.6875
3
[ "Apache-2.0" ]
permissive
// // Array.hpp // XYZGameEngine // // Created by Leo on 2016/11/28. // Copyright © 2016年 Leo. All rights reserved. // #ifndef Array_hpp #define Array_hpp #include <stdio.h> #include "Object.hpp" #include "Locker.h" namespace XYZGame { typedef struct _ArrayNode { public: _ArrayNode *next; _ArrayNode *pre; Object *object; _ArrayNode(Object *object) { this->next = nullptr; this->pre = nullptr; this->object = object; } }ArrayNode; typedef std::function<void(Object *, int)> ArrayEnunmerateFunc; class Array : public Object { private: Mutex lock; ArrayNode *first; ArrayNode *last; int size; void remove(ArrayNode *node); public: ~Array(); CreateInit(Array); void add(Object *object); void insert(int index, Object *object); bool contain(Object *object); void remove(Object *object); void removeAt(int index); void removeAll(); void enumerate(ArrayEnunmerateFunc func); Object *objectAt(int index); Object *firstObject(); Object *lastObject(); int count(); protected: virtual void dealloc(); }; } #endif /* Array_hpp */
true
d1f0c93ebd9797487239d31077cd4e01912f0403
C++
wildstang/2011_software
/CheesyPoofCode/matlab/mat.cpp
UTF-8
6,151
3.046875
3
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
#include <iostream> #include "matrix.h" const int num_inputs = 2; const int num_outputs = 2; const int num_states = 4; //this is some complex code written by Austin Schuh which was made obsolete //by the use of a different matrix library, but was kept because it //represents a lot of work and could possibly be recycled in the future /* MatrixXd s2z_A(MatrixXd A, MatrixXd B, double dt) { ComplexEigenSolver<MatrixXd> eigensolver(A); Matrix<std::complex<double>, num_states, num_states> diag(num_states, num_states); Matrix<std::complex<double>, num_states, num_states> diage(num_states, num_states); ComplexEigenSolver<MatrixXd>::EigenvalueType eval = eigensolver.eigenvalues(); for (int j = 0; j < num_states; j ++) { for (int i = 0; i < num_states; i ++) { diag(i, j) = 0.0; diage(i, j) = 0.0; } } for (int i = 0; i < num_states; i ++) { std::complex<double> lambda = eval(i, 0); diag(i, i) = std::exp(lambda * dt); if (std::abs(lambda) < 1.0e-14) { diag(i, i) = dt; } else { diag(i, i) = (std::exp(lambda * dt) - 1.0) / lambda; } } Matrix<std::complex<double>, num_states, num_states> dmy = (eigensolver.eigenvectors() * diag * eigensolver.eigenvectors().inverse()); MatrixXd ans(num_states, num_states); for (int j = 0; j < num_states; j ++) { for (int i = 0; i < num_states; i ++) { ans(i, j) = std::real(dmy(i, j)); } } return ans; } MatrixXd s2z_B(MatrixXd A, MatrixXd B, double dt) { ComplexEigenSolver<MatrixXd> eigensolver(A); Matrix<std::complex<double>, num_states, num_states> diag(num_states, num_states); Matrix<std::complex<double>, num_states, num_states> diage(num_states, num_states); ComplexEigenSolver<MatrixXd>::EigenvalueType eval = eigensolver.eigenvalues(); for (int j = 0; j < num_states; j ++) { for (int i = 0; i < num_states; i ++) { diag(i, j) = 0.0; diage(i, j) = 0.0; } } for (int i = 0; i < num_states; i ++) { std::complex<double> lambda = eval(i, 0); diag(i, i) = std::exp(lambda * dt); if (std::abs(lambda) < 1.0e-14) { diag(i, i) = dt; } else { diag(i, i) = (std::exp(lambda * dt) - 1.0) / lambda; } } Matrix<std::complex<double>, num_states, num_states> dmy = (eigensolver.eigenvectors() * diage * eigensolver.eigenvectors().inverse()); MatrixXd ans(num_states, num_states); for (int j = 0; j < num_states; j ++) { for (int i = 0; i < num_states; i ++) { ans(i, j) = std::real(dmy(i, j)); } } return ans; } */ /** * A state space controller * After being set up properly, this controller works as such: * Given two matrices: * r: the robot's goal position and velocity * y: the robot's current left and right encoder values * The controller will return a left and right voltage (with 12V being the * maximum voltage) to make the robot behave as well as possible */ class ss_controller { private: const int num_inputs; const int num_outputs; const int num_states; //the state matrices, calculated and imported from matlab struct matrix *A; struct matrix *C; struct matrix *L; struct matrix *B; struct matrix *D; struct matrix *K; //temporary matrices needed because of the C-style matrix lib struct matrix *xhat_a; struct matrix *xhat_b; struct matrix *xhat_l; struct matrix *outmat_r; struct matrix *outmat_xhat; //precompued matrices generated by matlab struct matrix *A_precomp; struct matrix *Br_precomp; public: struct matrix *xhat; public: ss_controller() : num_inputs(2), num_outputs(2), num_states(4) { //initalizes all the matrices A = init_matrix(num_states, num_states); C = init_matrix(num_outputs, num_states); L = init_matrix(num_states, num_outputs); B = init_matrix(num_states, num_inputs); D = init_matrix(num_outputs, num_inputs); K = init_matrix(num_inputs, num_states); xhat = init_matrix(num_states, 1); A_precomp = init_matrix(num_states, num_states); Br_precomp = init_matrix(num_states, num_states); xhat = init_matrix(num_states, 1); xhat_a = init_matrix(num_states, 1); xhat_b = init_matrix(num_states, 1); xhat_l = init_matrix(num_states, 1); outmat_r = init_matrix(num_outputs, 1); outmat_xhat = init_matrix(num_outputs, 1); //import the matlab-computed matrix values #include "controller.h" //A_precomp = A - (L * C) - (B * K); //Br_precomp = B * K; } void reset() { xhat = init_matrix(num_states, 1); for (int i = 0; i < num_states; i ++) { matrix_set(xhat,i,0,0.0); } } ~ss_controller() { free_matrix(A); free_matrix(C); free_matrix(L); free_matrix(B); free_matrix(D); free_matrix(K); free_matrix(xhat_a); free_matrix(xhat_b); free_matrix(xhat_l); free_matrix(xhat); free_matrix(A_precomp); free_matrix(Br_precomp); free(outmat_r); free(outmat_xhat); } /** * The heart of the state space controller * @param outmat the output matrix of left and right * voltages * @param r the r matrix, which holds the goal left * and right positions and velocities * @param y the current left and right distances */ void update(struct matrix *outmat, struct matrix *r, struct matrix *y) { //(ebakan): C-style computations = FFFFFFFFFFFFFUUUUUUU //MatrixXd nxhat = (A_precomp * xhat) + (Br_precomp * r) + (L * y); //compute xhat stuff matrix_mult(xhat_a, A_precomp, xhat); matrix_mult(xhat_b, Br_precomp, r); matrix_mult(xhat_l, L, y); matrix_add(xhat,xhat_a,xhat_b); matrix_add(xhat,xhat,xhat_l); //return K * r - K * xhat; matrix_mult(outmat_r, K, r); matrix_mult(outmat_xhat, K, xhat); matrix_minus(outmat, outmat_r, outmat_xhat); } }; /* int main() { MatrixXd y(2, 1); MatrixXd r(4, 1); ss_controller ssc; y << 1.0, 1.0; r << 0.0, 0.0, 0.0, 0.0; std::cout << ssc.update(r, y) << std::endl; } */
true
c4ec849b9ca76c9b0433f3f6a356ede3b685aedd
C++
Matthew-E-Gould/Past-Projects
/IoT Plant Grower Sim/CW1/Weather.cpp
UTF-8
1,079
3.296875
3
[]
no_license
#include "Classes.h" Weather::Weather(uint16_t random1, uint16_t random2, uint16_t random3) { //intialisation works similarly to nextday to on intialisation class will run nexday nextDay(random1, random2, random3); } Weather::~Weather() { } void Weather::nextDay(uint16_t random1, uint16_t random2, uint16_t random3) { // setting the random generated number modded by the max roll of it raining random1 = random1 % ROLL_MAX; // if the roll is less than the rain chance it will rain if (random1 <= ROLL_CHANCE) { rained = true; // setting the random generated number modded by the max rain amount plus 1 downpour = random2 % MAX_DOWNPOUR + 1; } else { // stting to neutral default values if it hasn't rained rained = false; downpour = 0; } // setting the random generated number modded by the max sunlight amount sunlight = random3 % MAX_SUNLIGHT; } bool Weather::getRained() { return rained; } uint16_t Weather::getDownpour() { return downpour; } uint16_t Weather::getSunlight() { return sunlight; }
true
3641b9ea487528c1490b09d3dce390040b550603
C++
jvont/bones
/bones/core/typedefs.h
UTF-8
988
2.921875
3
[]
no_license
#pragma once #include <cstdint> #include <functional> #include <memory> namespace bones { // signed integers using i8 = int8_t; using i16 = int16_t; using i32 = int32_t; using i64 = int64_t; // unsigned integers using u8 = uint8_t; using u16 = uint16_t; using u32 = uint32_t; using u64 = uint64_t; using byte = uint8_t; using word = uint16_t; using dword = uint32_t; // floating-point numbers using f32 = float; using f64 = double; template <typename R, typename... Args> using Function = std::function<R(Args...)>; // using Function = R(*)(Args...); template <typename... Args> using Callback = std::function<void(Args...)>; // using Callback = void(*)(Args...); // shared references template<typename T> using Ref = std::shared_ptr<T>; template<typename T, typename... Args> Ref<T> create_ref(Args... args) { return std::make_shared<T>(std::forward<Args>(args)...); } }
true
78003b32f21249dd024de337fe18aab613c799c2
C++
KushRohra/GFG_Codes
/Easy/Roof Top.cpp
UTF-8
387
2.625
3
[]
no_license
#include <iostream> using namespace std; int main() { int t; cin>>t; while(t--) { int n,i; cin>>n; int a[n]; for(i=0;i<n;i++) cin>>a[i]; i=0; int j=0,maxLen=-1; while(i<n) { j=i+1; while(j<n && a[j]>a[j-1]) j++; maxLen=max(maxLen,j-i-1); i=j; } cout<<maxLen<<endl; } return 0; }
true
99148efcd5f3a99a474512811f712c5d78c47dcb
C++
dzzhan/exam
/exam/candy.cpp
UTF-8
1,097
3.296875
3
[]
no_license
#include "pch.h" int candy(int* ratings, int ratingsSize) { int totalSize = ratingsSize; int i = 0; int* candyCnt = (int*)malloc(sizeof(int) * ratingsSize); memset(candyCnt, 0, sizeof(int) * ratingsSize); for (i = 0; i < (ratingsSize - 1); i++) { if ((ratings[i] < ratings[i + 1]) && (candyCnt[i] >= candyCnt[i + 1])) { candyCnt[i + 1] = candyCnt[i] + 1; } } for (i = (ratingsSize - 1); i > 0; i--) { if ((ratings[i - 1] > ratings[i]) && (candyCnt[i - 1] <= candyCnt[i])) { candyCnt[i - 1] = candyCnt[i] + 1; } } for (i = 0; i < ratingsSize; i++) { totalSize += candyCnt[i]; } free(candyCnt); return totalSize; } TEST_F(ExamCodeTest, candyTest0) { int rating[] = {1, 0, 2}; int num = candy(rating, sizeof(rating) / sizeof(rating[0])); EXPECT_EQ(num, 5); } TEST_F(ExamCodeTest, candyTest1) { int rating[] = { 1, 2, 2 }; int num = candy(rating, sizeof(rating) / sizeof(rating[0])); EXPECT_EQ(num, 4); } TEST_F(ExamCodeTest, candyTest2) { int rating[] = { 1,2,87,87,87,2,1 }; int num = candy(rating, sizeof(rating) / sizeof(rating[0])); EXPECT_EQ(num, 13); }
true
31adf87d4791a0441602c0a4630669fdd11124f1
C++
oldnick85/anamnesis
/anamnesis_trm/terminal/io/ctrmio_combine.cpp
UTF-8
452
2.671875
3
[ "MIT" ]
permissive
#include "ctrmio_combine.h" #include <iostream> #include <sstream> Result_t CTrmIO_Combine::ParseSamples(const std::string &str, std::list<std::string> &str_samples) const { if (str.empty()) return Result_t(RES_EMPTY_STRING); str_samples.clear(); std::stringstream str_stream(str); std::string token; while(getline(str_stream, token, ' ')) { str_samples.push_back(token); } return Result_t(RES_OK); }
true
c55174be3720cc574ae7133d22f6f5c894274e5d
C++
poleindraneel/NumericalFieldTheory
/ConsoleApplication/SquarePlate.h
UTF-8
535
3.0625
3
[]
no_license
#ifndef SQUAREPLATE_H #define SQUAREPLATE_H #pragma once class SquarePlate { private: int nX; // Must be not even int nY; // How many SmallSquares are used to approximate the plate int nN; // Total number of SmallSquares double side; //length of the side in meter Vektor<SmallSquare> vPlate; //Plate composed of SmallSquares public: SquarePlate(void); ~SquarePlate(void); void SetSide(const double aSide){side = aSide;}; //Set the side length of the plate void CreatePlate(); //Fillup Vektor to describe the plate }; #endif
true
4249f9bc4d48ee079b50b12f8d9e9666ff2fec96
C++
nabeelsiddiqui314/Picture-Sorting-Visualizer
/Picture_Sorting_Visualizer/Application.cpp
UTF-8
1,712
2.921875
3
[]
no_license
#include "stdafx.h" #include "Application.h" #include "Shuffle.h" #include "BubbleSort.h" Application::Application() { m_window.create(sf::VideoMode(800, 600), "Picture Sorter"); m_array = std::make_shared<PictureArray>(); applyTextureToImage(); const auto& pictureSize = m_array->getImageBuffer().getSize(); const auto& windowSize = m_window.getSize(); m_pictureQuad.setSize({ (float)pictureSize.x * 3, (float)pictureSize.y * 3}); m_pictureQuad.setPosition(windowSize.x / 2 - m_pictureQuad.getSize().x / 2, windowSize.y / 2 - m_pictureQuad.getSize().y / 2); } void Application::run() { while (m_window.isOpen()) { handleEvents(); m_window.clear(); runAlgorithmFor(30); applyTextureToImage(); m_window.draw(m_pictureQuad); m_window.display(); } } void Application::handleEvents() { sf::Event evnt; while (m_window.pollEvent(evnt)) { if (!m_algorithm) { if (evnt.type == sf::Event::KeyPressed) { if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)) { m_algorithm = std::make_unique<Shuffle>(m_array); } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::B)) { m_algorithm = std::make_unique<BubbleSort>(m_array); } } } if (evnt.type == sf::Event::Closed) { m_window.close(); } } } void Application::applyTextureToImage() { m_pictureTexture.loadFromImage(m_array->getImageBuffer()); m_pictureQuad.setTexture(&m_pictureTexture); } void Application::runAlgorithmFor(std::uint32_t times) { while (m_frameClock.getElapsedTime().asMilliseconds() < times) { if (m_algorithm) { m_algorithm->run(); if (m_algorithm->hasCompleted()) { m_algorithm.reset(); return; } } else { return; } } m_frameClock.restart(); }
true
1d0c91d15432d6906b2162468f562a8f2d047523
C++
arponbasu/CS101_1stSem
/Lab Sub/dept_main.cpp
UTF-8
524
2.734375
3
[]
no_license
#include "department.h" int main(){ department c; int inp, num, marks; cin>>inp; while(inp!=-1){ if(inp==1){ cin>>num>>marks; c.setMarks(num,marks); } else if(inp==2){ cout<<c.getHighest()<<endl; } else if(inp==3){ cout<<c.getAverage()<<endl; } else if(inp==4){ cin>>num; c.fetchStudent(num); } else if(inp==5){ char course_id[5]; cin>>course_id; c.addCourse((char*)course_id); } else if(inp==6){ c.listCourses(); } else cout<<"Invalid Input\n"; cin>>inp; } }
true
e5715750bf963319a7a36f686e8247ecccb6da4c
C++
piyushsoni/FactoryPattern
/Rectangle.h
UTF-8
269
2.65625
3
[]
no_license
#pragma once #include "Shape.h" #include <iostream> using namespace std; class Rectangle : public Shape { public: Rectangle(); virtual ~Rectangle(); virtual ShapeType GetType() { return Type_Rectangle; } private: float points[4][3]; };
true
2272e319956190cb8668f1cc0412f383b1012409
C++
vanshika1405/programming-assignment
/p25.cpp
UTF-8
299
2.609375
3
[]
no_license
#include<stdio.h> #include<conio.h> void main() { int n,r,sum=0,count=0; printf("enter a no"); scanf("%d",&n); while(n!=0) { r=n%10; sum=sum+r; n= n/10; count++; } printf(" sum is%d",sum); printf(" \ncount is%d",count); getch(); }
true
665731c18f043a455bd61fc52c277c7874f3b0bd
C++
thunderning/Wraiden2
/Wraiden2/Plane.h
GB18030
671
2.859375
3
[]
no_license
#pragma once #include "Item.h" class Plane : public Item { protected: int life; // int move_speed; //ƶٶȣÿxμƶһֵԽٶԽ Bullet bullet; //ӵ public: Plane(); ~Plane(); Bullet launch_bullet(); int get_life(); int change_life(int dmg); void flesh_bullet(); bool move_to_left(int k, int l, int h); //ֵ߽1~l1~hΪƶΧ bool move_to_right(int k, int l, int h); //ֵ߽1~l1~hΪƶΧ bool move_to_up(int k, int l, int h); //ֵ߽1~l1~hΪƶΧ bool move_to_down(int k, int l, int h); //ֵ߽1~l1~hΪƶΧ };
true
563825d2235ced8d71b5a20ca46e7fd234f9c571
C++
prasad-access/cpp
/remove_contDuplicates.cpp
UTF-8
1,090
3.4375
3
[]
no_license
/****************************************************************************** Program to remove continuous occurance of duplicates Example : I/P "MMMMMMMMMMMMMMMMMMMMMMMICCCROOOOFOCUUUUSS"; O/P : MICROFOCUS *******************************************************************************/ #include <iostream> using namespace std; void remove_duplicate(char str[],int * length) { int index_i = 0; int index_j = 1; int len = *length; while(index_i < len && index_j < len) { if(str[index_i] == str[index_j]) { index_j++; } else { index_i++; if(index_i != index_j) str[index_i] = str[index_j]; } } str[index_i+1] = '\0'; *length = index_i+1; return ; } int main() { char arr[] = "MMMMMMMMMMMMMMMMMMMMMMMICCCROOOOFOCUUUUSS"; int len = sizeof(arr)/sizeof(arr[0]) - 1; cout<<"Before : "<<arr<<" : length = "<<len<<endl; remove_duplicate(arr,&len); cout<<"After : "<<arr<<" : length = "<<len<<endl; return 0; }
true
06e12c488055e3a35b76b3efe0084a8321f3eb9f
C++
Superlokkus/code
/src/mkdt_example_client.cpp
UTF-8
4,618
2.6875
3
[ "MIT" ]
permissive
/*! @file mkdt_example_client.cpp * */ #include <iostream> #include <string> #include <map> #include <thread> #include <vector> #include <algorithm> #include <iterator> #include <functional> #include <boost/asio.hpp> #include <boost/log/trivial.hpp> #include <mkdt_lib.hpp> #include <object_remoting_mockup_adapter.hpp> const char *const menu_text{R"END_MENU_TEXT( Menu: ===== quit ---------- register service <name> use service <name> ---------- create object destroy object <id> expose object <id> consume object <uid> --------- object <id> example_method_1 <word> <number> )END_MENU_TEXT"}; struct example_client { example_client(uint16_t port) : io_context_{BOOST_ASIO_CONCURRENCY_HINT_SAFE}, work_guard_{boost::asio::make_work_guard(io_context_)}, registry_(io_context_, port) { const auto thread_count{std::max<unsigned>(std::thread::hardware_concurrency(), 1)}; std::generate_n(std::back_inserter(this->io_run_threads_), thread_count, [this]() { return std::thread{&example_client::io_run_loop, std::ref(this->io_context_)}; }); } ~example_client() { work_guard_.reset(); io_context_.stop(); std::for_each(this->io_run_threads_.begin(), this->io_run_threads_.end(), [](auto &thread) { if (thread.joinable()) thread.join(); }); } void connect() { } void disconnect() { } void register_service(mkdt::service_identifier name) { BOOST_LOG_TRIVIAL(info) << "Register service \"" << name << "\""; auto service_object = std::make_shared<mkdt::object_remoting_mockup:: stub_adapter<mkdt::object_remoting_mockup::server_stub>>(this->registry_); this->registry_.register_service(name, service_object, [=](auto error) { if (error) BOOST_LOG_TRIVIAL(error) << "Error while registering: " << error.what(); else BOOST_LOG_TRIVIAL(info) << "Registered service " << name; }); } void use_service(mkdt::service_identifier name) { BOOST_LOG_TRIVIAL(info) << "Use service \"" << name << "\""; this->registry_.use_service_interface(name, [name](auto error, auto object_identifier) { if (error) BOOST_LOG_TRIVIAL(error) << "Error trying to use service " << name << " : " << error.what(); else BOOST_LOG_TRIVIAL(info) << "Got object identifier \"" << boost::uuids::to_string(object_identifier) << "\" for service " << name; }); } private: boost::asio::io_context io_context_; boost::asio::executor_work_guard<boost::asio::io_context::executor_type> work_guard_; std::vector<std::thread> io_run_threads_; mkdt::registry registry_; static void io_run_loop(boost::asio::io_context &context) { while (true) { try { context.run(); break; } catch (std::exception &e) { BOOST_LOG_TRIVIAL(error) << e.what(); } } } }; int main(int argc, char *argv[]) { BOOST_LOG_TRIVIAL(info) << "MKDT example client\n"; uint16_t port{mkdt::mkdt_server_port_number}; if (argc == 1) { BOOST_LOG_TRIVIAL(info) << "Starting on default port " << mkdt::mkdt_server_port_number << "\n"; } else if (argc == 2) { port = std::stoul(argv[1]); BOOST_LOG_TRIVIAL(info) << "Start on on port " << port << "\n"; } else { std::cerr << "Usage " << argv[0] << "\n" << argv[0] << " <port>\n"; throw std::runtime_error{"Usage error"}; } example_client client{port}; std::cout << menu_text << "Input: "; for (std::string input; std::getline(std::cin, input); std::cout << "Input: ") { if (input == "quit") break; if (input == "disonnect") client.disconnect(); if (input == "reconnect") { client.disconnect(); client.connect(); } std::string input_prefix = "register service "; if (input.find(input_prefix) != std::string::npos) { client.register_service(input.substr(input.find(input_prefix) + input_prefix.size())); } input_prefix = "use service "; if (input.find(input_prefix) != std::string::npos) { client.use_service(input.substr(input.find(input_prefix) + input_prefix.size())); } } }
true
3b2a84ea0dbea257f1a2efe4cfff32bd11e2300b
C++
menghsun/pd2
/lec08/string_operations.cpp
UTF-8
954
3.265625
3
[]
no_license
#include <iostream> #include <string> using namespace std; int main() { string s1("happy"); string s2("birthday"); string s3; cout << "s1: " << s1; cout << "\ns2: " << s2; cout << "\ns3: " << s3; cout << "\ns2 == s1?: " << ((s2==s1)?"true":"false"); cout << "\ns2 != s1?: " << ((s2!=s1)?"true":"false"); cout << "\ns2 > s1?: " << ((s2>s1)?"true":"false"); cout << "\ns2 < s1?: " << ((s2<s1)?"true":"false"); cout << "\ns2 >= s1?: " << ((s2>=s1)?"true":"false"); cout << "\ns2 <= s1?: " << ((s2<=s1)?"true":"false"); cout << "\nIs s3 empty?: " << ((s3.empty())?"true":"false"); s3=s1; cout << "\ns3: " << s3; s1+=s2; cout << "\ns1: " << s1; s1+= "to you"; cout << "\ns1: " << s1; cout << "\ns1.substr(0,14): " << s1.substr(0,14); cout << "\ns1.substr(15): " << s1.substr(15); string s4(s1); cout << "\ns4: " << s4; s4=s4; cout << "\ns4: " << s4; s1[0]='H'; s1[6]='B'; cout << "\ns1: " << s1; s1.at(30)='D'; return 0; }
true
4d4ad2d94f1029ae4dcd756e14b28ec8caaf2ab7
C++
basanets/SoftwareDesignPatterns
/structural/bridge/bridge/radio.h
UTF-8
640
3.1875
3
[]
no_license
#ifndef RADIO_H #define RADIO_H #include "device.h" #include <string> class Radio : public Device { public: Radio(); virtual ~Radio() = default; Radio(const Radio & radio) = default; Radio(Radio && radio) = default; Radio & operator = (const Radio & radio) = default; Radio & operator = (Radio && radio) = default; public: void enable() override; void disable() override; void setVolume(uint32_t volume) override; bool isEnabled() const override; uint32_t volume() const override; std::string status() const; private: bool m_isEnabled; uint32_t m_volume; }; #endif // RADIO_H
true
716679d3be63839b2e15d03d58f94e8bec46dacf
C++
connectthefuture/psdmrepo
/PSQt/tags/V00-00-05/include/Logger.h
UTF-8
2,470
2.5625
3
[]
no_license
#ifndef LOGGER_H #define LOGGER_H //-------------------------- #include "PSQt/LoggerBase.h" #include <QObject> namespace PSQt { //-------------------------- // @addtogroup PSQt Logger /** * @ingroup PSQt Logger * * @brief Logger - singleton for LoggerBase * * Connects LoggerBase with GUILogger using method * new_record(Record& rec) - callback for re-implementation in subclass. * * * This software was developed for the LCLS project. If you use all or * part of it, please give an appropriate acknowledgment. * * @see GUIMain * * @version $Id:$ * * @author Mikhail Dubrovin * * * @anchor interface * @par<interface> Interface Description * * @li Include * @code * #include "PSQt/Logger.h" * @endcode * * @li Instatiation * \n * Instatiation is not requered, because this class is used as a singleton * with typedef-aliases to the methods like: * @code * Logger::getLogger()->some_method(...) * @endcode * * * @li Methods with aliases * @code * Print("some message is here"); // just print, message is not saved in the logger * MsgInLog(_name_(), INFO, "some message is here"); // regular message to the lagger * @endcode * @code * SaveLog(); // save log in default file with name like: "2015-02-09-10:49:36-log.txt" * // OR * SaveLog("file-name.txt"); // save log in specified file * @endcode * * * @li Methods without aliases * @code * Logger::getLogger()->setLevel(DEBUG); * LEVEL level = Logger::getLogger()->getLevel(); * std::string txt_error_msgs = Logger::getLogger()->strRecordsForLevel(ERROR); * Logger::getLogger()-> ... * @endcode * */ //-------------------------- class Logger : public QObject, public LoggerBase { Q_OBJECT // macro is needed for connection of signals and slots public: static Logger* getLogger(); protected: virtual void new_record(Record& rec); signals: void signal_new_record(Record&); private: static Logger* p_Logger; inline const std::string _name_(){return std::string("Logger");} Logger(); // private constructor! - singleton trick virtual ~Logger(){}; }; //-------------------------- #define MsgInLog Logger::getLogger()->message #define PrintMsg Logger::getLogger()->print #define SaveLog Logger::getLogger()->saveLogInFile //-------------------------- } // namespace PSQt #endif // LOGGER_H //-------------------------- //-------------------------- //--------------------------
true
e15a8f43902475e2f9cb8e9f677bce2d4bc78b21
C++
fincht96/Graphics-Output-Device
/RenderuC/BMPRead/src/memory.h
UTF-8
454
2.578125
3
[]
no_license
//******************************************************************************************************** // Memory class // // Base Memory class, used to allocate data to specifed memory locations, // #ifndef MEMORY_H #define MEMORY_H class Memory { public: // pure virtual function to be overwritten, will clear the data in the entire memory buffer region virtual void clearMemoryBuffer() = 0; }; #endif
true
b0e6c74b4aa6c723110b368c993269db15f1ce33
C++
Sarthakdtu/C-Codes
/Others/strange order.cpp
UTF-8
2,027
3.03125
3
[]
no_license
#include<bits/stdc++.h> #include<vector> using namespace std; void display(vector<int> v) { int a=0; vector<int>::iterator i; for(i = v.begin();i!= v.end();i++) { a++; cout<<*i<<" "; } // cout<<"no of elmnts "<<a; } void displayA(int *arr, int n) { for(int i=2;i<n+1;i++) cout<<i<<" : "<<arr[i]<<endl; } void multiplesLowestPrime(int n, int* fac) { for(int i=2;i<n+1;i++) { if(fac[i]==i) { for(int j=i;j<n+1;j+=i) { if(fac[j]==j) fac[j]=i; } } } } vector<int> fillVector(int a, int p, bool* arr, int n) { vector<int> v; for(int i=a;i>1;i-=p) { if(!arr[i]) { v.push_back(i); //cout<<"Currently at "<<i<<endl; } arr[i]=true; } return v; } int nextFactor(int a, int p) { a=a/p; while(a%p==0&&a!=1) { // cout<<a<<" "<<p<<endl; a=a/p; } return a; } void strangeOrder(int n) { bool *arr= new bool[n+1](); int *fac = new int[n+1]; for(int i =2;i<n+1;i++) fac[i] = i; fac[1]=0; fac[0]=0; multiplesLowestPrime(n, fac); //marks lowest prime factors //displayA(fac, n); vector<int> v; for(int i=n;i>1;i--) { if(!arr[i]) { //displayA(fac, n); vector<int> v1; v1 = fillVector(i, fac[i], arr, n); //manages the array int idx = nextFactor(i, fac[i]); //next Lowest Prime Factor fac[i] = 1; int lf = fac[idx]; fac[idx]=1; while(lf>1) { vector<int> v2; v2 = fillVector(i, lf, arr, n); v1.insert( v1.end(), v2.begin(), v2.end() ); idx = nextFactor(idx, lf); lf = fac[idx]; fac[idx]=1; } sort(v1.begin(), v1.end(), greater<int>()); v.insert( v.end(), v1.begin(), v1.end() ); } } v.push_back(1); display(v); } int main() { int n=631; strangeOrder(n); return 0; }
true
3f7830ff44188dd0f2fcbd43b37f24b30c9904d0
C++
daniellelshen/19-CMPE-126-Archive
/lab 9 - hash/Lab9 - cmpe126.1.cpp
UTF-8
1,428
3.109375
3
[]
no_license
//============================================================================ // Name : 1.cpp // Author : Danielle Shen // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> using namespace std; #include "hashtable.h" #include "hashtablechaining.h" int main() { HashT<int> myTable(9); myTable.print(); if( myTable.insert(9)){ cout << "Success :)" << endl; } else{ cout << "fail :(" << endl; } cout <<"DeleteT: " << myTable.deleteT(9) << endl; if( myTable.insert(12)){ cout << "Success :)" << endl; } else{ cout << "fail :(" << endl; } myTable.print(); cout << myTable.search(12) << endl; cout << myTable.search (6) << endl; if (myTable.search(20) == 20){ cout << "Success :)" << endl; } else{ cout << "fail :(" << endl; } HashTableChaining<int> myTableChain (10); cout << "###Testing Insert###" << endl; cout << "Insert: " << myTableChain.insert(50) << endl; myTableChain.print(); cout << "###Testing Insert###" << endl; myTableChain.insert(20); myTableChain.print(); cout << "###Testing Insert Bool###" << endl; cout << "Insert: " << myTableChain.insert(50) << endl; myTableChain.print(); cout << "search: " <<myTableChain.search(50) << endl; cout << "delete: " << myTableChain.deleteT(20) << endl; myTableChain.print(); }
true
4fb8508d31cdb1d52db6c840bea92b566040cff5
C++
abhikoh68/OOPS-lab
/object oriented programming/lab 3_1a.cpp
UTF-8
229
2.71875
3
[]
no_license
#include<iostream> using namespace std; void display(int); int main() { int n,i,k; cout<<"Enter a Number:- "; cin>>n; display(n); } void display(int m) { int i; for(i=0;i<m;i++) { cout<<"WELL DONE\n"; }}
true
650290035d4c7768dda5879481678ffac06a6192
C++
neha30/Data_structure
/sum_x.cpp
UTF-8
1,147
3.578125
4
[]
no_license
//Write a C program that, given an array A[] of n numbers and another number x, determines whether or not there exist two elements //in S whose sum is exactly x. //Let x be the given sum and MyVec[] be the array in which we need to find pair. //1) create the hasmap MyMap //2) Do following for each element MyVec[i] in MyVec[] // (a) If MyMap[x - MyVec[i]] is set then print the pair (MyVec[i], x - MyVec[i]) // (b) Set MyMap[MyVec[i]] #include<iostream> #include<vector> #include<algorithm> #include<map> using namespace std; int main(int argc, char const *argv[]) { vector<int> MyVec; //vector of integer map<int,int> MyMap; //creating map int total,val,x; cout<<"enter total element:"; cin>>total; for(int i=0;i<total;i++) { cin>>val; MyVec.push_back(val); } //vector<int>::iterator it; //sort(MyVec.begin(),MyVec.end()); cout<<"\nenter the value of x:"; cin>>x; map<int,int>::iterator it; for(int i=0;i<total;i++) { int temp=x - MyVec[i]; it=MyMap.find(temp); if(it!=MyMap.end()) { cout<<"\npirs is : "<<temp<<" "<<MyVec[i]<<endl; break; } MyMap[MyVec[i]]=1; } return 0; }
true
dfb0e8c8b866c0290b03d2b1ff25e98280d2420a
C++
Shada/Wanshift
/Renderer/ReaderINI.h
UTF-8
1,508
2.734375
3
[]
no_license
#pragma once #include <map> #include <string> #include <vector> typedef std::map<std::string,std::string> Attributes; struct Node_INI { private: Attributes attributes; public: std::string getValue(std::string _key) { Attributes::iterator aIt = attributes.find(_key); std::string value = "Invalid"; if(aIt != attributes.end()) { value = attributes[_key]; } return value; } Attributes getAllAttributes() { return attributes; } friend class ReaderINI; }; struct RootINI { std::map<std::string, Node_INI> nodes; public: Node_INI* getNode(const std::string& _name) { std::map<std::string,Node_INI>::iterator nIt = nodes.find(_name); if(nIt == nodes.end()) return nullptr; Node_INI* ni = &nIt->second; return ni; } bool getAllNodeAttributes(const std::string& _nodeName, Attributes& _inAttributes) { std::vector<std::string> temp; std::map<std::string,Node_INI>::iterator nIt = nodes.find(_nodeName); if(nIt == nodes.end()) return false; Node_INI t = nIt->second; _inAttributes = t.getAllAttributes(); return true; } }; class ReaderINI { public: ReaderINI(void); ~ReaderINI(void); bool generateIniData(); bool generateIniData(std::string _singleFile); RootINI& getInitData(); private: RootINI initData; void addAttributeToNode(std::string& _key, std::string& _value); void readNodeAttributes(std::string& _line); void createNode(std::string& _node); bool readSingleINI(const std::string& _file); std::string currentNode; };
true
a94d84bc9b3ed65bc4d7367965b5db9ad59ea322
C++
AndrewLam97/CS008
/Recursion/Recursion/random_fractal.h
UTF-8
2,426
3.890625
4
[]
no_license
#ifndef RANDOM_FRACTAL_H #define RANDOM_FRACTAL_H #include <cassert> #include <iomanip> #include "../../!includes/useful/useful.h" using namespace std; class fractal { private: int level = 0; int call = 0; public: // fractal::fractal(double left_height, double right_height, double width, double epsilon){ // this->left_height = left_height; // this->right_height = right_height; // this->width = width; // this->epsilon = epsilon; // } void random_fractal(double left_height, double right_height, double width, double epsilon); void generate_fractal(); }; void fractal::random_fractal( double left_height, double right_height, double width, double epsilon) // Precondition: width and epsilon are both positive. // Postcondition: The function has generated a random fractal from a line segment. The // parameters left_height and right_height are the heights of the line segment, and the // parameter width is the segment’s width. The generation of the random fractal stops when // the width of the line segments reaches epsilon or less. // Method of displaying the output: The height of the right endpoint of each line segment in // the random fractal is displayed by calling the function display(...). // Library facilities used: cassert, useful.h (from Appendix I) { double mid_height; // Height of the midpoint of the line segment assert(width > 0); assert(epsilon > 0); if (width <= epsilon){ //stopping case, display when width is less than or equal to epsilon cout << "Max width at reached at level: " << level-- << ", going down a level"; display(right_height); //cout << "Printing fractal" << endl; } else //else, keep dividing the segment { mid_height = (left_height + right_height) / 2; mid_height += random_real(-width, width); cout << "Segment max width not reached at level: " << level++ << ", dividing and going up a level" << endl; //cout << "Level: " << level++ << endl; random_fractal(left_height, mid_height, width / 2, epsilon); random_fractal(mid_height, right_height, width / 2, epsilon); //cout << "level: " << level-- << endl; } } void fractal::generate_fractal(){ random_fractal(10.0, 10.0, 16.0, 1.0); cout << "Max width reached at level 0, ending recursion..." << endl; } #endif // RANDOM_FRACTAL_H
true
28f3951af5b4707100e92cc2dcc672cec6ff40d7
C++
markusfoote/NVISII
/src/nvisii/transform.cpp
UTF-8
29,606
2.703125
3
[ "Apache-2.0" ]
permissive
#include <nvisii/transform.h> #include <nvisii/entity.h> #include <glm/gtx/matrix_decompose.hpp> namespace nvisii { std::vector<Transform> Transform::transforms; std::vector<TransformStruct> Transform::transformStructs; std::map<std::string, uint32_t> Transform::lookupTable; std::shared_ptr<std::recursive_mutex> Transform::editMutex; bool Transform::factoryInitialized = false; std::set<Transform*> Transform::dirtyTransforms; void Transform::initializeFactory(uint32_t max_components) { if (isFactoryInitialized()) return; transforms.resize(max_components); transformStructs.resize(max_components); editMutex = std::make_shared<std::recursive_mutex>(); factoryInitialized = true; } bool Transform::isFactoryInitialized() { return factoryInitialized; } bool Transform::isInitialized() { return initialized; } bool Transform::areAnyDirty() { return dirtyTransforms.size() > 0; }; std::set<Transform*> Transform::getDirtyTransforms() { return dirtyTransforms; } void Transform::updateComponents() { if (dirtyTransforms.size() == 0) return; for (auto &t : dirtyTransforms) { if (!t->isInitialized()) continue; transformStructs[t->id].localToWorld = t->getLocalToWorldMatrix(false); transformStructs[t->id].localToWorldPrev = t->getLocalToWorldMatrix(true); } dirtyTransforms.clear(); } void Transform::clearAll() { if (!isFactoryInitialized()) return; for (auto &transform : transforms) { if (transform.initialized) { Transform::remove(transform.name); } } } /* Static Factory Implementations */ Transform* Transform::create(std::string name, vec3 scale, quat rotation, vec3 position) { auto createTransform = [scale, rotation, position] (Transform* transform) { transform->setPosition(position); transform->setRotation(rotation); transform->setScale(scale); transform->markDirty(); }; try { return StaticFactory::create<Transform>(editMutex, name, "Transform", lookupTable, transforms.data(), transforms.size(), createTransform); } catch (...) { StaticFactory::removeIfExists(editMutex, name, "Transform", lookupTable, transforms.data(), transforms.size()); throw; } } Transform* Transform::createFromMatrix(std::string name, mat4 xfm) { auto createTransform = [xfm] (Transform* transform) { transform->setTransform(xfm); transform->markDirty(); }; try { return StaticFactory::create<Transform>(editMutex, name, "Transform", lookupTable, transforms.data(), transforms.size(), createTransform); } catch (...) { StaticFactory::removeIfExists(editMutex, name, "Transform", lookupTable, transforms.data(), transforms.size()); throw; } } std::shared_ptr<std::recursive_mutex> Transform::getEditMutex() { return editMutex; } Transform* Transform::get(std::string name) { return StaticFactory::get(editMutex, name, "Transform", lookupTable, transforms.data(), transforms.size()); } void Transform::remove(std::string name) { auto t = get(name); if (!t) return; int32_t oldID = t->getId(); StaticFactory::remove(editMutex, name, "Transform", lookupTable, transforms.data(), transforms.size()); dirtyTransforms.insert(&transforms[oldID]); } TransformStruct* Transform::getFrontStruct() { return transformStructs.data(); } Transform* Transform::getFront() { return transforms.data(); } uint32_t Transform::getCount() { return transforms.size(); } std::string Transform::getName() { return name; } int32_t Transform::getId() { return id; } int32_t Transform::getAddress() { return (this - transforms.data()); } std::map<std::string, uint32_t> Transform::getNameToIdMap() { return lookupTable; } void Transform::markDirty() { if (getAddress() < 0 || getAddress() >= transforms.size()) { throw std::runtime_error("Error, transform not allocated in list"); } dirtyTransforms.insert(this); auto entityPointers = Entity::getFront(); for (auto &eid : entities) { entityPointers[eid].markDirty(); } }; Transform::Transform() { initialized = false; } Transform::Transform(std::string name, uint32_t id) { initialized = true; this->name = name; this->id = id; } std::string Transform::toString() { std::string output; output += "{\n"; output += "\ttype: \"Transform\",\n"; output += "\tname: \"" + name + "\",\n"; // output += "\tid: \"" + std::to_string(id) + "\",\n"; // output += "\tscale: " + glm::to_string(getScale()) + "\n"; // output += "\tposition: " + glm::to_string(getPosition()) + "\n"; // output += "\trotation: " + glm::to_string(getRotation()) + "\n"; // output += "\tright: " + glm::to_string(right) + "\n"; // output += "\tup: " + glm::to_string(up) + "\n"; // output += "\tforward: " + glm::to_string(forward) + "\n"; // output += "\tlocal_to_parent_matrix: " + glm::to_string(getLocalToParentMatrix()) + "\n"; // output += "\tparent_to_local_matrix: " + glm::to_string(getParentToLocalMatrix()) + "\n"; output += "}"; return output; } vec3 Transform::transformDirection(vec3 direction, bool previous) { return vec3(getLocalToParentRotationMatrix(previous) * vec4(direction, 0.0)); } vec3 Transform::transformPoint(vec3 point, bool previous) { return vec3(getLocalToParentMatrix(previous) * vec4(point, 1.0)); } vec3 Transform::transformVector(vec3 vector, bool previous) { return vec3(getLocalToParentMatrix(previous) * vec4(vector, 0.0)); } vec3 Transform::inverseTransformDirection(vec3 direction, bool previous) { return vec3(getParentToLocalRotationMatrix(previous) * vec4(direction, 0.0)); } vec3 Transform::inverseTransformPoint(vec3 point, bool previous) { return vec3(getParentToLocalMatrix(previous) * vec4(point, 1.0)); } vec3 Transform::inverseTransformVector(vec3 vector, bool previous) { return vec3(getLocalToParentMatrix(previous) * vec4(vector, 0.0)); } glm::quat safeQuatLookAt( glm::vec3 const& lookFrom, glm::vec3 const& lookTo, glm::vec3 const& up, glm::vec3 const& alternativeUp) { glm::vec3 direction = lookTo - lookFrom; float directionLength = glm::length(direction); // Check if the direction is valid; Also deals with NaN if(!(directionLength > 0.0001)) return glm::quat(1, 0, 0, 0); // Just return identity // Normalize direction direction /= directionLength; // Is the normal up (nearly) parallel to direction? if(glm::abs(glm::dot(direction, up)) > .9999f) { // Use alternative up return glm::quatLookAt(direction, alternativeUp); } else { return glm::quatLookAt(direction, up); } } void Transform::lookAt(vec3 at, vec3 up, vec3 eye, bool previous) { if (previous) { useRelativeAngularMotionBlur = false; } if (glm::any(glm::isnan(eye))) { eye = (previous) ? this->prevPosition : this->position; } else { if (previous) { useRelativeLinearMotionBlur = false; } setPosition(eye, previous); } up = normalize(up); glm::vec3 forward = glm::normalize(at - eye); glm::quat rotation = safeQuatLookAt(eye, at, up, up); setRotation(rotation, previous); } // void Transform::nextLookAt(vec3 at, vec3 up, vec3 eye) // { // if (glm::any(glm::isnan(eye))) { // eye = position; // } // up = normalize(up); // // glm::vec3 forward = glm::normalize(at - eye); // // glm::quat rotation = safeQuatLookAt(eye, at, up, up); // nextWorldToLocalMatrix = glm::lookAt(eye, at, up); // glm::mat4 dNext = nextWorldToLocalMatrix * localToWorldMatrix; // glm::quat rot = glm::quat_cast(dNext); // glm::vec4 vel = glm::column(dNext, 3); // setLinearVelocity(vec3(vel)); // setAngularVelocity(rot); // // nextLocalToWorldMatrix = inverse(nextWorldToLocalMatrix); // // setAngularVelocity(rot * glm::inverse(rotation)); // // markDirty(); // } // void Transform::rotateAround(vec3 point, float angle, vec3 axis) // { // glm::vec3 direction = point - getPosition(); // glm::vec3 newPosition = getPosition() + direction; // glm::quat newRotation = glm::angleAxis(angle, axis) * getRotation(); // newPosition = newPosition - direction * glm::angleAxis(-angle, axis); // rotation = glm::normalize(newRotation); // localToParentRotation = glm::toMat4(rotation); // parentToLocalRotation = glm::inverse(localToParentRotation); // position = newPosition; // localToParentTranslation = glm::translate(glm::mat4(1.0), position); // parentToLocalTranslation = glm::translate(glm::mat4(1.0), -position); // updateMatrix(); // markDirty(); // } void Transform::rotateAround(vec3 point, glm::quat rot, bool previous) { if (previous) useRelativeAngularMotionBlur = false; glm::vec3 direction = point - getPosition(previous); glm::vec3 newPosition = getPosition(previous) + direction; glm::quat newRotation = rot * getRotation(previous); newPosition = newPosition - direction * glm::inverse(rot); glm::quat &r = (previous) ? prevRotation : rotation; glm::vec3 &t = (previous) ? prevPosition : position; // glm::mat4 &ltpr = (previous) ? prevLocalToParentRotation : localToParentRotation; // glm::mat4 &ptlr = (previous) ? prevParentToLocalRotation : parentToLocalRotation; // glm::mat4 &ltpt = (previous) ? prevLocalToParentTranslation : localToParentTranslation; // glm::mat4 &ptlt = (previous) ? prevParentToLocalTranslation : parentToLocalTranslation; r = glm::normalize(newRotation); // ltpr = glm::toMat4(rotation); // ptlr = glm::inverse(ltpr); t = newPosition; // ltpt = glm::translate(glm::mat4(1.0), t); // ptlt = glm::translate(glm::mat4(1.0), -t); updateMatrix(); markDirty(); } void Transform::setTransform(glm::mat4 transformation, bool decompose, bool previous) { if (previous) { useRelativeLinearMotionBlur = false; useRelativeAngularMotionBlur = false; useRelativeScalarMotionBlur = false; } if (decompose) { // glm::vec3 scale; // glm::quat rotation; // glm::vec3 translation; // translation = glm::vec3(glm::column(transformation, 3)); // glm::mat3 rot = glm::mat3(transformation); // float det = glm::determinant(rot); // // if (abs(det) < glm::epsilon<float>()) { // // throw std::runtime_error("Error: upper left 3x3 determinant must be non-zero"); // // } // scale.x = length(glm::column(rot, 0)); // scale.y = length(glm::column(rot, 1)); // scale.z = length(glm::column(rot, 2)); // if (det < 0) { // scale *= -1.f; // rot *= -1.f; // } // rotation = glm::normalize(glm::quat_cast(rot)); glm::vec3 scale; glm::quat rotation; glm::vec3 translation; glm::vec3 skew; glm::vec4 perspective; bool worked = glm::decompose(transformation, scale, rotation, translation, skew, perspective); /* If the above didn't work, throw an exception */ if (!worked) { throw std::runtime_error( std::string("Decomposition failed! Is the product of the 4x4 with the determinant of the upper left 3x3 nonzero?") + std::string("See Graphics Gems II: Decomposing a Matrix into Simple Transformations")); // setScale(vec3(1.f), previous); // setPosition(vec3(0.f), previous); // setRotation(quat(1.f, 0.f, 0.f, 0.f), previous); // setTransform(transformation, false, previous); // return; } if (glm::length(skew) > .0001f) { throw std::runtime_error( std::string("Decomposition failed! Skew detected in the upper left 3x3.") ); return; } /* Decomposition can return negative scales. We make the assumption this is impossible.*/ if (scale.x < 0.0) scale.x *= -1; if (scale.y < 0.0) scale.y *= -1; if (scale.z < 0.0) scale.z *= -1; scale = glm::max(scale, glm::vec3(.0001f)); if (!(glm::any(glm::isnan(translation)))) setPosition(translation, previous); if (!(glm::any(glm::isnan(scale)))) setScale(scale, previous); if (!(glm::any(glm::isnan(rotation)))) setRotation(rotation, previous); } else { if (previous) { this->prevLocalToParentTransform = transformation; // this->prevParentToLocalTransform = glm::inverse(transformation); } else { this->localToParentTransform = transformation; // this->parentToLocalTransform = glm::inverse(transformation); } updateMatrix(); } markDirty(); } quat Transform::getRotation(bool previous) { if (previous) return prevRotation; else return rotation; } void Transform::setRotation(quat newRotation, bool previous) { if (previous) useRelativeAngularMotionBlur = false; auto &r = (previous) ? prevRotation : rotation; r = glm::normalize(newRotation); updateRotation(); markDirty(); } void Transform::setAngleAxis(float angle, vec3 axis, bool previous) { setRotation(glm::angleAxis(angle, axis), previous); } void Transform::addRotation(quat additionalRotation, bool previous) { if (previous) useRelativeAngularMotionBlur = false; setRotation(getRotation(previous) * additionalRotation, previous); updateRotation(); markDirty(); } void Transform::addAngleAxis(float angle, vec3 axis, bool previous) { addRotation(glm::angleAxis(angle, axis), previous); } void Transform::updateRotation() { // localToParentRotation = glm::toMat4(rotation); // parentToLocalRotation = glm::inverse(localToParentRotation); // if (useRelativeMotionBlur) { // prevLocalToParentRotation = glm::toMat4(angularVelocity * rotation); // } else { // prevLocalToParentRotation = glm::toMat4(prevRotation); // } // prevParentToLocalRotation = glm::inverse(prevLocalToParentRotation); updateMatrix(); markDirty(); } vec3 Transform::getPosition(bool previous) { if (previous) return prevPosition; else return position; } vec3 Transform::getRight(bool previous) { if (previous) return glm::normalize(glm::vec3(glm::column(prevLocalToParentMatrix, 0))); else return glm::normalize(glm::vec3(glm::column(localToParentMatrix, 0))); } vec3 Transform::getUp(bool previous) { if (previous) return glm::normalize(glm::vec3(glm::column(prevLocalToParentMatrix, 1))); else return glm::normalize(glm::vec3(glm::column(localToParentMatrix, 1))); } vec3 Transform::getForward(bool previous) { if (previous) return glm::normalize(glm::vec3(glm::column(prevLocalToParentMatrix, 2))); else return glm::normalize(glm::vec3(glm::column(localToParentMatrix, 2))); } vec3 Transform::getWorldPosition(bool previous) { if (previous) return glm::vec3(glm::column(prevLocalToWorldMatrix, 3)); else return glm::vec3(glm::column(localToWorldMatrix, 3)); } vec3 Transform::getWorldRight(bool previous) { if (previous) return glm::normalize(glm::vec3(glm::column(prevLocalToWorldMatrix, 0))); else return glm::normalize(glm::vec3(glm::column(localToWorldMatrix, 0))); } vec3 Transform::getWorldUp(bool previous) { if (previous) return glm::normalize(glm::vec3(glm::column(prevLocalToWorldMatrix, 1))); else return glm::normalize(glm::vec3(glm::column(localToWorldMatrix, 1))); } vec3 Transform::getWorldForward(bool previous) { if (previous) return glm::normalize(glm::vec3(glm::column(prevLocalToWorldMatrix, 2))); else return glm::normalize(glm::vec3(glm::column(localToWorldMatrix, 2))); } void Transform::setPosition(vec3 newPosition, bool previous) { if (previous) useRelativeLinearMotionBlur = false; auto &p = (previous) ? prevPosition : position; p = newPosition; updatePosition(); markDirty(); } void Transform::addPosition(vec3 additionalPosition, bool previous) { if (previous) useRelativeLinearMotionBlur = false; setPosition(getPosition(previous) + additionalPosition, previous); updatePosition(); markDirty(); } void Transform::setLinearVelocity(vec3 newLinearVelocity, float framesPerSecond, float mix) { useRelativeLinearMotionBlur = true; mix = glm::clamp(mix, 0.f, 1.f); newLinearVelocity /= framesPerSecond; linearMotion = glm::mix(newLinearVelocity, linearMotion, mix); updatePosition(); markDirty(); } void Transform::setAngularVelocity(quat newAngularVelocity, float framesPerSecond, float mix) { useRelativeAngularMotionBlur = true; mix = glm::clamp(mix, 0.f, 1.f); newAngularVelocity[0] = newAngularVelocity[0] / framesPerSecond; newAngularVelocity[1] = newAngularVelocity[1] / framesPerSecond; newAngularVelocity[2] = newAngularVelocity[2] / framesPerSecond; angularMotion = glm::lerp(newAngularVelocity, angularMotion, mix); updateRotation(); markDirty(); } void Transform::setScalarVelocity(vec3 newScalarVelocity, float framesPerSecond, float mix) { useRelativeScalarMotionBlur = true; mix = glm::clamp(mix, 0.f, 1.f); newScalarVelocity /= framesPerSecond; scalarMotion = glm::mix(newScalarVelocity, scalarMotion, mix); updateScale(); markDirty(); } void Transform::clearMotion() { useRelativeLinearMotionBlur = true; useRelativeAngularMotionBlur = true; useRelativeScalarMotionBlur = true; scalarMotion = glm::vec3(0.f); angularMotion = glm::quat(1.f, 0.f, 0.f, 0.f); linearMotion = glm::vec3(0.f); updateMatrix(); markDirty(); } // void Transform::setPosition(float x, float y, float z) // { // setPosition(glm::vec3(x, y, z)); // markDirty(); // } // void Transform::addPosition(float dx, float dy, float dz) // { // addPosition(glm::vec3(dx, dy, dz)); // markDirty(); // } void Transform::updatePosition() { // localToParentTranslation = glm::translate(glm::mat4(1.0), position); // parentToLocalTranslation = glm::translate(glm::mat4(1.0), -position); // if (useRelativeMotionBlur) { // prevLocalToParentTranslation = glm::translate(glm::mat4(1.0), position + linearVelocity); // prevParentToLocalTranslation = glm::translate(glm::mat4(1.0), -position + linearVelocity); // } else { // prevLocalToParentTranslation = glm::translate(glm::mat4(1.0), prevPosition); // prevParentToLocalTranslation = glm::translate(glm::mat4(1.0), -prevPosition); // } updateMatrix(); markDirty(); } vec3 Transform::getScale(bool previous) { if (previous) return prevScale; else return scale; } void Transform::setScale(vec3 newScale, bool previous) { if (previous) useRelativeScalarMotionBlur = false; auto &s = (previous) ? prevScale : scale; s = newScale; updateScale(); markDirty(); } // void Transform::setScale(float newScale) // { // scale = vec3(newScale, newScale, newScale); // updateScale(); // markDirty(); // } void Transform::addScale(vec3 additionalScale, bool previous) { if (previous) useRelativeScalarMotionBlur = false; setScale(getScale(previous) + additionalScale, previous); updateScale(); markDirty(); } // void Transform::setScale(float x, float y, float z) // { // setScale(glm::vec3(x, y, z)); // markDirty(); // } // void Transform::addScale(float dx, float dy, float dz) // { // addScale(glm::vec3(dx, dy, dz)); // markDirty(); // } // void Transform::addScale(float ds) // { // addScale(glm::vec3(ds, ds, ds)); // markDirty(); // } void Transform::updateScale() { // localToParentScale = glm::scale(glm::mat4(1.0), scale); // parentToLocalScale = glm::scale(glm::mat4(1.0), glm::vec3(1.0 / scale.x, 1.0 / scale.y, 1.0 / scale.z)); // if (useRelativeMotionBlur) { // prevLocalToParentScale = glm::scale(glm::mat4(1.0), scale + scalarVelocity); // prevParentToLocalScale = glm::scale(glm::mat4(1.0), glm::vec3(1.0 / (scale.x + scalarVelocity.x), 1.0 / (scale.y + scalarVelocity.y), 1.0 / (scale.z + scalarVelocity.z))); // } else { // prevLocalToParentScale = glm::scale(glm::mat4(1.0), prevScale); // prevParentToLocalScale = glm::scale(glm::mat4(1.0), glm::vec3(1.0 / prevScale.x, 1.0 / prevScale.y, 1.0 / prevScale.z)); // } updateMatrix(); markDirty(); } void Transform::updateMatrix() { localToParentMatrix = (localToParentTransform * getLocalToParentTranslationMatrix(false) * getLocalToParentRotationMatrix(false) * getLocalToParentScaleMatrix(false)); parentToLocalMatrix = (getParentToLocalScaleMatrix(false) * getParentToLocalRotationMatrix(false) * getParentToLocalTranslationMatrix(false) * glm::inverse(localToParentTransform)); prevLocalToParentMatrix = (prevLocalToParentTransform * getLocalToParentTranslationMatrix(true) * getLocalToParentRotationMatrix(true) * getLocalToParentScaleMatrix(true)); prevParentToLocalMatrix = (getParentToLocalScaleMatrix(true) * getParentToLocalRotationMatrix(true) * getParentToLocalTranslationMatrix(true) * glm::inverse(prevLocalToParentTransform)); // right = glm::vec3(localToParentMatrix[0]); // up = glm::vec3(localToParentMatrix[1]); // forward = glm::vec3(localToParentMatrix[2]); // position = glm::vec3(localToParentMatrix[3]); // prevRight = glm::vec3(prevLocalToParentMatrix[0]); // prevUp = glm::vec3(prevLocalToParentMatrix[1]); // prevForward = glm::vec3(prevLocalToParentMatrix[2]); // prevPosition = glm::vec3(prevLocalToParentMatrix[3]); updateChildren(); markDirty(); } glm::mat4 Transform::computeWorldToLocalMatrix(bool previous) { glm::mat4 parentMatrix = glm::mat4(1.0); if (parent != -1) { parentMatrix = transforms[parent].computeWorldToLocalMatrix(previous); return getParentToLocalMatrix(previous) * parentMatrix; } else return getParentToLocalMatrix(previous); } // glm::mat4 Transform::computeNextWorldToLocalMatrix(bool previous) // { // glm::mat4 parentMatrix = glm::mat4(1.0); // if (parent != -1) { // parentMatrix = transforms[parent].computeNextWorldToLocalMatrix(); // return getNextParentToLocalMatrix() * parentMatrix; // } // else return getNextParentToLocalMatrix(); // } void Transform::updateWorldMatrix() { if (parent == -1) { worldToLocalMatrix = parentToLocalMatrix; localToWorldMatrix = localToParentMatrix; prevWorldToLocalMatrix = prevParentToLocalMatrix; prevLocalToWorldMatrix = prevLocalToParentMatrix; // worldScale = scale; // worldTranslation = position; // worldRotation = rotation; // worldSkew = glm::vec3(0.f, 0.f, 0.f); // worldPerspective = glm::vec4(1.0f, 1.0f, 1.0f, 1.0f); // not sure what this should default to... // prevWorldScale = prevScale; // prevWorldTranslation = prevPosition; // prevWorldRotation = prevRotation; // prevWorldSkew = glm::vec3(0.f, 0.f, 0.f); // prevWorldPerspective = glm::vec4(1.0f, 1.0f, 1.0f, 1.0f); // not sure what this should default to... } else { worldToLocalMatrix = computeWorldToLocalMatrix(/*previous=*/false); prevWorldToLocalMatrix = computeWorldToLocalMatrix(/*previous=*/true); localToWorldMatrix = glm::inverse(worldToLocalMatrix); prevLocalToWorldMatrix = glm::inverse(prevWorldToLocalMatrix); // glm::decompose(localToWorldMatrix, worldScale, worldRotation, worldTranslation, worldSkew, worldPerspective); // glm::decompose(prevLocalToWorldMatrix, prevWorldScale, prevWorldRotation, prevWorldTranslation, prevWorldSkew, prevWorldPerspective); // glm::decompose(nextLocalToWorldMatrix, worldScale, worldRotation, worldTranslation, worldSkew, worldPerspective); } markDirty(); } glm::mat4 Transform::getParentToLocalMatrix(bool previous) { if (previous) return prevParentToLocalMatrix; else return parentToLocalMatrix; } // glm::mat4 Transform::getNextParentToLocalMatrix() // { // return nextParentToLocalMatrix; // } glm::mat4 Transform::getLocalToParentMatrix(bool previous) { if (previous) return prevLocalToParentMatrix; else return localToParentMatrix; } // glm::mat4 Transform::getNextLocalToParentMatrix() // { // return nextLocalToParentMatrix; // } glm::mat4 Transform::getLocalToParentTranslationMatrix(bool previous) { if ((previous) && (useRelativeLinearMotionBlur)) return glm::translate(glm::mat4(1.0), position - linearMotion); else if (previous) return glm::translate(glm::mat4(1.0), prevPosition); else return glm::translate(glm::mat4(1.0), position); } glm::mat4 Transform::getLocalToParentScaleMatrix(bool previous) { if ((previous) && (useRelativeScalarMotionBlur)) return glm::scale(glm::mat4(1.0), scale - scalarMotion); else if (previous) return glm::scale(glm::mat4(1.0), prevScale); else return glm::scale(glm::mat4(1.0), scale); } glm::mat4 Transform::getLocalToParentRotationMatrix(bool previous) { if ((previous) && (useRelativeAngularMotionBlur)) return glm::toMat4(angularMotion * rotation); else if (previous) return glm::toMat4(prevRotation); else return glm::toMat4(rotation); } glm::mat4 Transform::getParentToLocalTranslationMatrix(bool previous) { if ((previous) && (useRelativeLinearMotionBlur)) return glm::translate(glm::mat4(1.0), -(position - linearMotion)); else if (previous) return glm::translate(glm::mat4(1.0), -prevPosition); else return glm::translate(glm::mat4(1.0), -position); } glm::mat4 Transform::getParentToLocalScaleMatrix(bool previous) { if ((previous) && (useRelativeScalarMotionBlur)) return glm::scale(glm::mat4(1.0), glm::vec3(1.0 / (scale - scalarMotion).x, 1.0 / (scale - scalarMotion).y, 1.0 / (scale - scalarMotion).z)); else if (previous) return glm::scale(glm::mat4(1.0), glm::vec3(1.0 / prevScale.x, 1.0 / prevScale.y, 1.0 / prevScale.z)); else return glm::scale(glm::mat4(1.0), glm::vec3(1.0 / scale.x, 1.0 / scale.y, 1.0 / scale.z)); } glm::mat4 Transform::getParentToLocalRotationMatrix(bool previous) { if ((previous) && (useRelativeAngularMotionBlur)) return glm::toMat4(glm::inverse(angularMotion * rotation)); else if (previous) return glm::toMat4(glm::inverse(prevRotation)); else return glm::toMat4(glm::inverse(rotation)); } Transform* Transform::getParent() { if ((this->parent < 0) || (this->parent >= transforms.size())) return nullptr; return &transforms[this->parent]; } std::vector<Transform*> Transform::getChildren() { std::vector<Transform*> children_list; for (auto &cid : this->children){ // in theory I don't need to do this, but better safe than sorry. if ((cid < 0) || (cid >= transforms.size())) continue; children_list.push_back(&transforms[cid]); } return children_list; } void Transform::setParent(Transform *parent) { if (!parent) throw std::runtime_error(std::string("Error: parent is empty")); if (!parent->isInitialized()) throw std::runtime_error(std::string("Error: parent is uninitialized")); if (parent->getId() == this->getId()) throw std::runtime_error(std::string("Error: a transform cannot be the parent of itself")); // check for circular relationships auto tmp = parent; while (tmp->getParent() != nullptr) { if (tmp->getParent()->getId() == this->getId()) { throw std::runtime_error(std::string("Error: circular dependency detected")); } tmp = tmp->getParent(); } this->parent = parent->getId(); transforms[parent->getId()].children.insert(this->id); updateChildren(); markDirty(); } void Transform::clearParent() { if ((parent < 0) || (parent >= transforms.size())){ parent = -1; return; } transforms[parent].children.erase(this->id); this->parent = -1; updateChildren(); markDirty(); } void Transform::addChild(Transform *object) { if (!object) throw std::runtime_error(std::string("Error: child is empty")); if (!object->isInitialized()) throw std::runtime_error(std::string("Error: child is uninitialized")); if (object->getId() == this->getId()) throw std::runtime_error(std::string("Error: a transform cannot be the child of itself")); object->setParent(&transforms[getId()]); } void Transform::removeChild(Transform *object) { if (!object) throw std::runtime_error(std::string("Error: child is empty")); if (!object->isInitialized()) throw std::runtime_error(std::string("Error: child is uninitialized")); if (object->getId() == this->getId()) throw std::runtime_error(std::string("Error: a transform cannot be the child of itself")); children.erase(object->getId()); transforms[object->getId()].parent = -1; transforms[object->getId()].updateWorldMatrix(); transforms[object->getId()].markDirty(); } glm::mat4 Transform::getWorldToLocalMatrix(bool previous) { if (previous) return prevWorldToLocalMatrix; else return worldToLocalMatrix; } glm::mat4 Transform::getLocalToWorldMatrix(bool previous) { if (previous) return prevLocalToWorldMatrix; else return localToWorldMatrix; } // glm::mat4 Transform::getNextWorldToLocalMatrix() { // return nextWorldToLocalMatrix; // } // glm::mat4 Transform::getNextLocalToWorldMatrix() { // return nextLocalToWorldMatrix; // } // glm::quat Transform::getWorldRotation(bool previous) { // if (previous) return prevWorldRotation; // else return worldRotation; // } // glm::vec3 Transform::getWorldTranslation(bool previous) { // if (previous) return prevWorldTranslation; // else return worldTranslation; // } // glm::vec3 Transform::getWorldScale(bool previous) { // if (previous) return prevWorldScale; // else return worldScale; // } // glm::mat4 Transform::getWorldToLocalRotationMatrix(bool previous) // { // return glm::toMat4(glm::inverse(worldRotation)); // } // glm::mat4 Transform::getLocalToWorldRotationMatrix(bool previous) // { // if (previous) glm::toMat4(prevWorldRotation); // return glm::toMat4(worldRotation); // } // glm::mat4 Transform::getWorldToLocalTranslationMatrix(bool previous) // { // glm::mat4 m(1.0); // m = glm::translate(m, -1.0f * (previous) ? prevWorldTranslation : worldTranslation); // return m; // } // glm::mat4 Transform::getLocalToWorldTranslationMatrix(bool previous) // { // glm::mat4 m(1.0); // m = glm::translate(m, (previous) ? prevWorldTranslation : worldTranslation); // return m; // } // glm::mat4 Transform::getWorldToLocalScaleMatrix(bool previous) // { // glm::mat4 m(1.0); // m = glm::scale(m, 1.0f / ((previous) ? prevWorldScale : worldScale)); // return m; // } // glm::mat4 Transform::getLocalToWorldScaleMatrix(bool previous) // { // glm::mat4 m(1.0); // m = glm::scale(m, (previous) ? prevWorldScale : worldScale); // return m; // } void Transform::updateChildren() { for (auto &c : children) { auto &t = transforms[c]; t.updateChildren(); } updateWorldMatrix(); markDirty(); } TransformStruct &Transform::getStruct() { return transformStructs[id]; } };
true
31b018c740cf94c027a0f9222a2e8d9384e35308
C++
sharanyakamath/Competitive-Programming
/codechef/XORIER.cpp
UTF-8
1,086
2.828125
3
[]
no_license
#include <bits/stdc++.h> #define lli long long int using namespace std; lli xorPairCount(lli arr[], lli n, lli x, lli y) { lli result = 0; unordered_map<lli, lli> m; for (lli i=0; i<n ; i++) { lli curr_xor1 = x^arr[i], curr_xor2 = y^arr[i]; if (m.find(curr_xor1) != m.end()) result += m[curr_xor1]; if (m.find(curr_xor2) != m.end()) result += m[curr_xor2]; m[arr[i]]++; } return result; } lli countXorPair(lli arr[], lli n) { lli odd = 0, even = 0; for (lli i = 0; i < n; i++) { if (arr[i] % 2 == 0) even++; else odd++; } return odd*(odd-1)/2 + even*(even-1)/2; } int main(){ lli t; cin>>t; while(t--){ lli n,i,j,x,count=0,sum=0; cin>>n; lli a[n]; for(i=0;i<n;i++){ cin>>a[i]; } sum+=xorPairCount(a,n,0,2); // cout<<"sum:"<<sum<<endl; // sum+=xorPairCount(a,n,2); // cout<<"sum:"<<sum<<endl; count+=countXorPair(a,n); // cout<<"count:"<<count<<endl; count-=sum; cout<<count<<endl; } }
true
d6636a0dcdeede2b2a1cfd49b45c64adc9c3bd85
C++
Aidan79225/Leetcode
/Medium/866. Smallest Subtree with all the Deepest Nodes.cpp
UTF-8
931
3.1875
3
[]
no_license
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* subtreeWithAllDeepest(TreeNode* root) { vector<int> dp(501, -1); int l = getDepth(root -> left, dp); int r = getDepth(root -> right, dp); if(l > r){ return subtreeWithAllDeepest(root -> left); }else if(l < r){ return subtreeWithAllDeepest(root->right); }else{ return root; } } int getDepth(TreeNode* root, vector<int>& dp){ if(root == nullptr)return 0; if(dp[root -> val] != -1)return dp[root -> val]; int l = getDepth(root -> left, dp); int r = getDepth(root -> right, dp); dp[root -> val] = max(l, r) + 1; return dp[root -> val]; } };
true
efc54830b2a668084201767237b045d4c810a4cc
C++
ABHISHEK-G0YAL/Competitive-Programming
/practice/SPOJ/Edit_Distance_Again.cpp
UTF-8
422
2.671875
3
[]
no_license
// https://www.spoj.com/problems/EDIT/ #include <iostream> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); string s; int c1,c2; while(cin>>s) { c1=0; c2=0; for(int i=0;i<s.length();i++) { if(i%2==0) { if(s[i]>90) ++c1; else ++c2; } else { if(s[i]>90) ++c2; else ++c1; } } cout<<min(c1,c2)<<endl; } return 0; }
true
4f9dd995191d9ba5f8ec8e1247c49713a4695516
C++
KireinaHoro/assignments
/week9/p_encode.cc
UTF-8
675
3.09375
3
[]
no_license
#include <iostream> #include <string> #include <algorithm> using namespace std; string itoa(int i) { string ans; while(i > 0) { ans.append(1, i % 10 + '0'); i /= 10; } reverse(ans.begin(), ans.end()); return ans; } string encode(string in) { if(!in.length()) return ""; if(in.length() == 1) return "1" + string(1, in[0]); int i = 0; while(in[i] == in[i + 1]) i ++; return itoa(i + 1) + string(1, in[i]) + encode(in.substr(i + 1)); } int main() { int n; cin >> n; while(n --) { string a; cin >> a; cout << encode(a) << endl; } return 0; }
true
eafc2be0bc2174e3fd03f93b4bb7f56631ae9406
C++
bathetrade/DeepBluesSimulation
/DeepBluesSimulation/Pawn.cpp
UTF-8
573
2.796875
3
[]
no_license
#include "Pawn.h" #include "ILevel.h" using namespace std; Pawn::Pawn() { SetPriority(1); } std::string Pawn::ToString() const { return "Pawn"; } vector<Point> Pawn::GeneratePossibleMoves() const { auto currentPosition = GetPosition(); vector<Point> possibleMoves = { currentPosition + Point(1,0) }; return possibleMoves; } vector<Point> Pawn::GeneratePossibleAttacks() const { vector<Point> attackPoints; auto position = GetPosition(); attackPoints.push_back(position + Point(1, 1)); attackPoints.push_back(position + Point(1, -1)); return attackPoints; }
true
7a31cd48f52a54833943fc3b4917aa16975e553f
C++
robostar-ye/data_structure
/exp5/exp5_1.cpp
GB18030
3,636
3.78125
4
[]
no_license
#include <stdio.h> #define MAX_LEN (100) // 󳤶 typedef int key_type; // ؼΪint typedef char info_type; typedef struct { key_type key; // ؼ info_type data; // ,Ϊinfo_type }rec_type; // Ԫص /*-----------------xy------------------*/ void swap_rec(rec_type &x, rec_type &y) // { rec_type tmp = x; x = y; y = tmp; } /*-----------------˳------------------*/ void create_list(rec_type recs[], key_type keys[], int n) { int i; for(i = 0; i < n; i++) // recs[0...n-1]¼ recs[i].key = keys[i]; } /*-----------------˳------------------*/ void disp_list(rec_type recs[], int n) { int i; for(i = 0; i < n; i++) printf("%d ", recs[i].key); printf("\n"); } /*-----------------Զij------------------*/ /*-----------------˳------------------*/ void create_list1(rec_type recs[], key_type keys[], int n) { int i; for(i = 1; i <= n; i++) // recs[1...n]¼ { recs[i].key = keys[i - 1]; } } /*-----------------˳------------------*/ void disp_list1(rec_type recs[], int n) { int i; for(i = 1; i <= n; i++) { printf("%d ", recs[i].key); } printf("\n"); } /*---------------ʾһ˻ֺĽ--------------*/ static void disp_partition(rec_type recs[], int s, int t) { static int i = 1; // ֲ̬ʼһ int j; printf("%dλ:", i); for(j = 0; j < s; j++) printf(" "); for(j = s; j <= t; j++) printf("%3d", recs[j].key); printf("\n"); i++; } /*---------------һ˻--------------*/ static int partition_recs(rec_type recs[], int s, int t) { int i = s, j = t;//ʼλã Ԫظ-1 rec_type tmp = recs[i]; // recs[i]Ϊ׼ [6, 8, 7, 9, 0, 1, 3, 2, 4, 5] while(i < j) // ˽мɨ,ֱi=jΪֹ { while(i < j && recs[j].key >= tmp.key) j--; // ɨ,һСtmp.keyrecs[j] recs[i] = recs[j]; // ҵrecs[j],recs[i] while(i < j && recs[i].key <= tmp.key) i++; // ɨ,һtmp.keyrecs[i] recs[j] = recs[i]; // ҵrecs[i],recs[j] } recs[i] = tmp; disp_partition(recs, s, t); return i; } static void quick_sort(rec_type recs[], int s, int t) { int i; if(s < t) // ٴԪص { i = partition_recs(recs, s, t); quick_sort(recs, s, i - 1); // ݹ quick_sort(recs, i + 1, t); // ݹ } } int main(int argc, char *argv[]) { int n = 8; rec_type recs[MAX_LEN]; key_type a[] = {10,80,45,3,65,23,98,8}; create_list(recs, a, n); printf("ǰ: "); disp_list(recs, n); quick_sort(recs, 0, n - 1); printf(": "); disp_list(recs, n); return 0; }
true
a1bd20c3dcbe7fb28eb7acddd821c7c82df35e08
C++
ankurag12/flippy
/include/LSM6DS33.h
UTF-8
2,295
2.71875
3
[]
no_license
#ifndef LSM6DS33_H_ #define LSM6DS33_H_ #include <cstdint> #include <map> typedef std::uint8_t byte; enum Axis { X = 0, Y = 2, Z = 4 }; class LSM6DS33 { public: LSM6DS33(int host_id = -1); bool init(uint odr_accel = 1660, uint fs_accel = 2, uint filter_bw_accel = 200, uint odr_gyro = 1660, uint fs_gyro = 245); double get_accel_reading(Axis axis); double get_gyro_reading(Axis axis); private: uint _odr_accel; uint _fs_accel; uint _filter_bw_accel; uint _odr_gyro; uint _fs_gyro; int _host_id = -1; int _i2c_handle; static constexpr byte _device_address = 0x6b; static constexpr byte _who_am_i_id = 0x69; static constexpr byte _dout_word_length = 16; static constexpr uint _dout_word_fs = (1 << _dout_word_length) - 1; // Map for full scale for the accelerometer in +/- g static const std::map<uint, byte> _fs_accel_map; // Map for anti-aliasing filter bandwidth for the accelerometer in Hz static const std::map<uint, byte> _filter_bw_accel_map; // Map for full scale for the gyro in +/- deg/s static const std::map<uint, byte> _fs_gyro_map; // Map for output data rate for accelerometer (ODR_XL) in Hz static const std::map<uint, byte> _odr_accel_map; // Map for output data rate for the gyro (ODR_G) in Hz static const std::map<uint, byte> _odr_gyro_map; // Not all registers are listed here enum _RegisterAddress { // Embedded functions configuration register FUNC_CFG_ACCESS = 0x01, ORIENT_CFG_G = 0x0B, // Who I am ID WHO_AM_I = 0x0F, // Accelerometer and gyroscope control registers CTRL1_XL = 0x10, CTRL2_G = 0x11, CTRL3_C = 0x12, CTRL4_C = 0x13, CTRL5_C = 0x14, CTRL6_C = 0x15, CTRL7_G = 0x16, CTRL8_XL = 0x17, CTRL9_XL = 0x18, CTRL10_C = 0x19, STATUS_REG = 0x1E, // Gyroscope output registers OUTX_L_G = 0x22, OUTX_H_G = 0x23, OUTY_L_G = 0x24, OUTY_H_G = 0x25, OUTZ_L_G = 0x26, OUTZ_H_G = 0x27, // Accelerometer output registers OUTX_L_XL = 0x28, OUTX_H_XL = 0x29, OUTY_L_XL = 0x2A, OUTY_H_XL = 0x2B, OUTZ_L_XL = 0x2C, OUTZ_H_XL = 0x2D }; }; #endif // LSM6DS33_H_
true
38bb39cbed20166c2ca5f29d76e66718821bf8a9
C++
Keigo-Iwakuma/LeetcodeSubmissions
/solutions/485.max-consecutive-ones.cpp
UTF-8
589
2.890625
3
[]
no_license
/* * @lc app=leetcode id=485 lang=cpp * * [485] Max Consecutive Ones */ // @lc code=start class Solution { public: int findMaxConsecutiveOnes(vector<int>& nums) { int max_l = 0; int p_z = -1; for (int i=0; i<nums.size(); i++) { if (nums[i] == 0) { if (i - p_z -1 > max_l) { max_l = i - p_z - 1; } p_z = i; } } if (nums.size() - p_z - 1 > max_l) { max_l = nums.size() - p_z - 1; } return max_l; } }; // @lc code=end
true
59bda80ebeab1287abcba800ff7307ca9928d334
C++
Cody-Duncan/ShadyTreeEngine2
/ShadyTreeEngine/Graphics/DirectX/DirectX_PrimitiveBatch.cpp
UTF-8
9,574
2.59375
3
[]
no_license
#include "Graphics\DirectX\DirectX_PrimitiveBatch.h" #include "Resources\BufferResourcer.h" #include "Resources\Resources.h" #include "Graphics\DirectX\DirectX_GraphicsDevice.h" #define BatchSize 4096 #define Invalid_Buffer_ID -1 DirectX_PrimitiveBatch::DirectX_PrimitiveBatch(GraphicsDevice* deviceIn) : PrimitiveBatch(DeviceAPI::DirectX11) { DirectX_GraphicsDevice* gDevice = dynamic_cast<DirectX_GraphicsDevice*>(deviceIn); if(!gDevice) { device = 0; DebugPrintf("Tried to use non-directX graphics device in directX spritebatch"); } else { device = gDevice; } } DirectX_PrimitiveBatch::~DirectX_PrimitiveBatch(void) { } //UTILITY FUNCTIONS void FillIndexBuffer(unsigned int* indices, ID3D11Buffer* buffer, ID3D11DeviceContext* context) { D3D11_MAPPED_SUBRESOURCE resource; context->Map(buffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &resource); //map the buffer to lock resource unsigned int* pI = (unsigned int*) resource.pData; //convert data to unisgned int* so it can be assigned DebugAssert(pI != 0, "Pointer to the dynamic index buffer is null. Error in allocating Buffer"); memcpy(pI, indices, sizeof( unsigned int ) * BatchSize*6); //memcopy the indices in context->Unmap(buffer, 0); //unmap to unlock resource } void FillVertexBuffer(std::vector<VertexCol>& vertices, int length, ID3D11Buffer* buffer, ID3D11DeviceContext* context) { D3D11_MAPPED_SUBRESOURCE resource; context->Map(buffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &resource); //map the buffer to lock resource VertexCol* pV = (VertexCol*) resource.pData; //convert data to Vertex* so we can set DebugAssert(pV != 0, "Pointer to Dynamic Vertex Buffer is null. Cannot modify vertices. Check allocation of buffer."); DebugAssert(vertices.size() <= BatchSize*4, "Too many vertices for buffer size. Crash now before we crash the graphics card. Tried to draw %d vertices", (unsigned int)vertices.size()); memcpy(pV, vertices.data(), sizeof( VertexCol ) * length); //memcopy the vertices in context->Unmap(buffer, 0); //unmap to unlock resource } void DirectX_PrimitiveBatch::Init() { //color shaders colorVertSH = Resources::Instance().LoadVertexShaderFile("resources/ColorShader.fx","VS", "vs_4_0"); Resources::Instance().VerifyVertexSize("resources/ColorShader.fx", sizeof(VertexCol)); colorPixSH = Resources::Instance().LoadPixelShaderFile("resources/ColorShader.fx","PS", "ps_4_0"); unsigned int* indices = new unsigned int[BatchSize *6]; for(int i = 0; i < BatchSize*6; ++i) { indices[i] = i; } ID3D11DeviceContext* context = device->getContext(); BufferResourcer& BR = BufferResourcer::Instance(); //----- INITIALIZE TRIANGLE INDEX BUFFER BR.createDynamicIndexBuffer(BatchSize*6, device->getDevice(), &triBatchIBuffer[Tri]); ID3D11Buffer* TriIndexBuffer = BR.getIBufferData(triBatchIBuffer[Tri]).getIndexBuffer(); FillIndexBuffer(indices, TriIndexBuffer, context); //----- INITIALIZE LINE INDEX BUFFER BR.createDynamicIndexBuffer(BatchSize*6, device->getDevice(), &triBatchIBuffer[Line]); ID3D11Buffer* LineIndexBuffer = BR.getIBufferData(triBatchIBuffer[Line]).getIndexBuffer(); FillIndexBuffer(indices, LineIndexBuffer, context); //unmap to unlock resource delete[] indices; //----- SET OTHER VALUES device->setClearColor(Color(0.4f,0.6f,0.9f,1.0f)); // cornflower blue } void DirectX_PrimitiveBatch::Dispose() { for(int i = 0; i < 2; ++i) { triBatchVBuffers[i].clear(); for(auto iter = triBatch[i].begin(); iter != triBatch[i].end(); ++iter) { iter->clear(); } triBatch[i].clear(); } } bool DirectX_PrimitiveBatch::hasBatchBuffer(unsigned int layer, PrimitiveType type) { return layer < triBatchVBuffers[type].size() && //cannot have index higher than size triBatchVBuffers[type][layer].VbufferID != Invalid_Buffer_ID; //vbuffer id must be valid } void DirectX_PrimitiveBatch::addBatchBuffer(unsigned int layer, PrimitiveType type) { if(!hasBatchBuffer(layer, type)) { DebugAssert(device, "Spritebatch's graphicsDevice is null"); VertexBufferHandle quadBuffer; BufferResourcer::Instance().createDynamicVertexBuffer(BatchSize*4, device->getDevice(), &quadBuffer); VertexBufferData& vbufdata = BufferResourcer::Instance().getVBufferData(quadBuffer); vbufdata.stride = sizeof(VertexCol); switch(type) { case Tri: vbufdata.primitiveTopology = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST; break; case Line: vbufdata.primitiveTopology = D3D11_PRIMITIVE_TOPOLOGY_LINELIST; break; } //assign vBuffer VertexBufferHandle invalidHandle = {Invalid_Buffer_ID}; triBatchVBuffers[type].resize(layer+1, invalidHandle); triBatchVBuffers[type][layer] = quadBuffer; //create a batch triBatch[type].resize(layer+1); triBatch[type][layer].reserve(BatchSize*4); } } void DirectX_PrimitiveBatch::resetBatchBuffer(unsigned int layer, PrimitiveType type) { if(hasBatchBuffer(layer, type)) { VertexBufferHandle triVBH = triBatchVBuffers[type][layer]; //reset startVertex on VBuffer data VertexBufferData& triBufferData = BufferResourcer::Instance().getVBufferData(triVBH); triBufferData.startVertex = 0; //reset batch triBatch[type][layer].clear(); } } void DirectX_PrimitiveBatch::resetAllBatchBuffers() { for(unsigned int i = 0; i < triBatch[Tri].size(); ++i) { resetBatchBuffer(i, Tri); } for(unsigned int i = 0; i < triBatch[Line].size(); ++i) { resetBatchBuffer(i, Line); } } void DirectX_PrimitiveBatch::DrawTriangles(unsigned int layer, Vector2* points, int pointLength, Matrix transform, Color c) { DrawPrimitive(layer, points, pointLength, transform, c, Tri); } void DirectX_PrimitiveBatch::DrawLines(unsigned int layer, Vector2* points, int pointLength, Matrix transform, Color c) { DrawPrimitive(layer, points, pointLength, transform, c, Line); } void DirectX_PrimitiveBatch::DrawPrimitive(unsigned int layer, Vector2* points, int pointLength, Matrix transform, Color c, PrimitiveType type) { if(!hasBatchBuffer(layer, type)) addBatchBuffer(layer, type); std::vector<VertexCol>& batchRef = triBatch[type][layer]; for(int i = 0; i < pointLength; ++i) { Vector2 temp = Vector2::Transform(points[i], transform); batchRef.push_back( VertexCol(Vector4(temp.x, temp.y, 0, 1), c) ); } VertexBufferData& triBufferData = BufferResourcer::Instance().getVBufferData(triBatchVBuffers[type][layer]); triBufferData.startVertex += pointLength; } void DirectX_PrimitiveBatch::DrawBatch(int layer, PrimitiveType type) { VertexBufferHandle triVBH = triBatchVBuffers[type][layer]; if(triVBH.VbufferID == Invalid_Buffer_ID) //do not draw invalid buffers return; VertexBufferData& quadBufferData = BufferResourcer::Instance().getVBufferData(triVBH); if(quadBufferData.startVertex > 0) //don't draw empty buffers { DebugAssert(triBatchIBuffer[type].IbufferID >= 0, "Batch Index Buffer ID is invalid. Value: %d", triBatchIBuffer[type].IbufferID ); device->Draw(triVBH, triBatchIBuffer[type]); } } void DirectX_PrimitiveBatch::sendBatchToBuffers(unsigned int layer, PrimitiveType type) { VertexBufferHandle triVBH = triBatchVBuffers[type][layer]; if(triVBH.VbufferID == Invalid_Buffer_ID) //do not draw invalid buffers return; VertexBufferData& triBufferData = BufferResourcer::Instance().getVBufferData(triVBH); std::vector<VertexCol>& currBatch = triBatch[type][layer]; if(triBufferData.startVertex == 0) return; ID3D11DeviceContext* context = device->getContext(); ID3D11Buffer* vertexBuffer = triBufferData.getVertexBuffer(); //update vertex buffer FillVertexBuffer(currBatch, triBufferData.startVertex, vertexBuffer, context); //set index buffer IndexBufferData& indexBufData = BufferResourcer::Instance().getIBufferData(triBatchIBuffer[type]); indexBufData.startIndex = currBatch.size(); //6 indices per 4 vertices } void DirectX_PrimitiveBatch::Begin(bool alphaBlend) { static Matrix m = Matrix::Identity(); device->setWorld(m); Vector4 eye(0.0f, 0.0f, 10.0f, 1.0f); Vector4 at(0.0f, 0.0f, 0.0f, 1.0f); Vector4 up(0.0f, 1.0f, 0.0f, 1.0f ); device->setView( eye, at, up ); device->setOrthographicProjection(); device->setBlend(alphaBlend); device->setVertexShader(colorVertSH); device->setPixelShader(colorPixSH); device->setTextureSampler(false); device->ToggleDepthBuffer(false); device->BeginDraw(); } void DirectX_PrimitiveBatch::End() { for(unsigned int i = 0; i < triBatchVBuffers[Tri].size(); ++i) { sendBatchToBuffers(i, Tri); DrawBatch(i, Tri); } for(unsigned int i = 0; i < triBatchVBuffers[Line].size(); ++i) { sendBatchToBuffers(i, Line); DrawBatch(i, Line); } resetAllBatchBuffers(); }
true
d9a0f909f3a8348408f9fe6ac9bf1c9618e18645
C++
WMostert1/COS132-Crash-Course
/DT/DT.cpp
UTF-8
543
3.484375
3
[]
no_license
#include <iostream> using namespace std; int main(){ cout << "Data Type : Size in bits" << endl; cout << "------------------------------" << endl; cout << "int : " << sizeof(int)*8 << endl; cout << "unsigned int : " << sizeof(unsigned int)*8 << endl; cout << "char : " << sizeof(char)*8 << endl; cout << "unsigned char : " << sizeof(unsigned char)*8 << endl; cout << "string : " << sizeof(string)*8 << endl; cout << "double : " << sizeof(double)*8 << endl; cout << "float : " << sizeof(float)*8 << endl; return 0; }
true
5fc2dd6d4442fafc59724ac2b5080787b29b69cd
C++
Lut99/RayTracer
/src/lib/animations/camera/CameraRotation.cpp
UTF-8
3,085
2.8125
3
[]
no_license
/* CAMERA ROTATION.cpp * by Lut99 * * Created: * 2/1/2020, 4:55:47 PM * Last edited: * 3/3/2020, 4:54:39 PM * Auto updated? * Yes * * Description: * The CameraRotation class models the movement of a Camera that circles * around a point. In this animation, the Camera looks at the same point * throughout the animation; just the lookfrom is changed. This * particular file is the implementation file for CameraRotation.hpp. **/ #define _USE_MATH_DEFINES #include <cmath> #include "JSONExceptions.hpp" #include "CameraRotation.hpp" #if defined MACOS || defined _WIN32 #define sinf64 sin #define cosf64 cos #define acosf64 acos #endif using namespace std; using namespace RayTracer; using namespace nlohmann; double CameraRotation::compute_speed(std::chrono::seconds circle_time) { double circle_dist = 2 * M_PI; return circle_dist / (((double) circle_time.count()) * 1000); } CameraRotation::CameraRotation(chrono::seconds circle_time) : CameraMovement(rotation), speed(this->compute_speed(circle_time)), loop_time(circle_time) {} void CameraRotation::recompute(Camera* target) { Vec3 lookat = target->lookat; Vec3 lookfrom = target->lookfrom; Vec3 lookfrom_circle(lookfrom.x, 0, lookfrom.z); this->center = Vec3(lookat.x, 0, lookat.z); this->angle = acosf64(dot(Vec3(0, 0, 1), (lookfrom_circle - center).normalize())); this->radius = (lookfrom_circle - this->center).length(); } void CameraRotation::update(chrono::milliseconds time_passed, Camera* target) { // Set the camera lookfrom to this new position target->lookfrom = Vec3( this->center.x + cosf64(this->angle) * this->radius, target->lookfrom.y, this->center.z + sinf64(this->angle) * this->radius ); this->angle += this->speed * time_passed.count(); while (this->angle >= 2 * M_PI) { this->angle -= 2 * M_PI; } // Recompute the camera variables target->recompute(); } json CameraRotation::to_json() const { json j; // First, let the parent add their general properties this->baseclass_to_json(j); // Now, add our own j["loop_time"] = this->loop_time.count(); return j; } CameraRotation* CameraRotation::from_json(json json_obj) { // Check if the object has an object type if (!json_obj.is_object()) { throw InvalidObjectFormat("CameraRotation", json::object().type_name(), json_obj.type_name()); } // Check if the required field exist if (json_obj["loop_time"].is_null()) { throw MissingFieldException("CameraRotation", "loop_time"); } // Try to parse the required fields chrono::seconds loop_time; try { loop_time = chrono::seconds(json_obj["loop_time"].get<long>()); } catch (nlohmann::detail::type_error&) { throw InvalidFieldFormat("CameraRotation", "loop_time", "long", json_obj["loop_time"].type_name()); } return new CameraRotation(loop_time); }
true
519551fb86df2133412dd165dbe140e5b4dce0c1
C++
afakihcpr/cpp-sort
/testsuite/sorters/default_sorter.cpp
UTF-8
2,870
3.03125
3
[ "MIT", "BSL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "LLVM-exception", "Zlib", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* * Copyright (c) 2015-2018 Morwenn * SPDX-License-Identifier: MIT */ #include <algorithm> #include <forward_list> #include <functional> #include <iterator> #include <list> #include <vector> #include <catch2/catch.hpp> #include <cpp-sort/sorters/default_sorter.h> #include <cpp-sort/sort.h> #include <testing-tools/distributions.h> TEST_CASE( "default sorter tests", "[default_sorter]" ) { // Collection to sort std::vector<int> vec; vec.reserve(80); auto distribution = dist::shuffled{}; distribution(std::back_inserter(vec), 80, 0); SECTION( "sort with random-access iterable" ) { cppsort::sort(vec); CHECK( std::is_sorted(std::begin(vec), std::end(vec)) ); } SECTION( "sort with random-access iterable and compare" ) { cppsort::sort(vec, std::greater<>{}); CHECK( std::is_sorted(std::begin(vec), std::end(vec), std::greater<>{}) ); } SECTION( "sort with random-access iterators" ) { cppsort::sort(std::begin(vec), std::end(vec)); CHECK( std::is_sorted(std::begin(vec), std::end(vec)) ); } SECTION( "sort with random-access iterators and compare" ) { cppsort::sort(std::begin(vec), std::end(vec), std::greater<>{}); CHECK( std::is_sorted(std::begin(vec), std::end(vec), std::greater<>{}) ); } SECTION( "sort with bidirectional iterators" ) { std::list<int> li(std::begin(vec), std::end(vec)); cppsort::sort(std::begin(li), std::end(li)); CHECK( std::is_sorted(std::begin(li), std::end(li)) ); } SECTION( "sort with bidirectional iterators and compare" ) { std::list<int> li(std::begin(vec), std::end(vec)); cppsort::sort(std::begin(li), std::end(li), std::greater<>{}); CHECK( std::is_sorted(std::begin(li), std::end(li), std::greater<>{}) ); } SECTION( "sort with forward iterators" ) { std::forward_list<int> li(std::begin(vec), std::end(vec)); cppsort::sort(std::begin(li), std::end(li)); CHECK( std::is_sorted(std::begin(li), std::end(li)) ); } SECTION( "sort with forward iterators and compare" ) { std::forward_list<int> li(std::begin(vec), std::end(vec)); cppsort::sort(std::begin(li), std::end(li), std::greater<>{}); CHECK( std::is_sorted(std::begin(li), std::end(li), std::greater<>{}) ); } SECTION( "sort with self-sortable iterable" ) { std::list<int> li(std::begin(vec), std::end(vec)); cppsort::sort(li); CHECK( std::is_sorted(std::begin(li), std::end(li)) ); } SECTION( "sort with self-sortable iterable and compare" ) { std::forward_list<int> li(std::begin(vec), std::end(vec)); cppsort::sort(li, std::greater<>{}); CHECK( std::is_sorted(std::begin(li), std::end(li), std::greater<>{}) ); } }
true
6ea918087c26b339ba3707fc4cb51dd7a0b61e29
C++
oninoni/OniEngine
/Engine/Engine/Mesh.cpp
UTF-8
2,533
2.546875
3
[]
no_license
#include "stdafx.h" #include "Vertex.h" #include "RecourceLoader.h" #include "Shader.h" #include "PhongShader.h" #include "ShaderHandler.h" #include "Mesh.h" Mesh::Mesh(ShaderHandler* shaderHandler, Vertex* vertices, uint nVert){ init(shaderHandler, vertices, nVert); } Mesh::Mesh(ShaderHandler* shaderHandler, string fileName) : Mesh(*(RecourceLoader::loadMesh(fileName, shaderHandler))){ } Mesh::Mesh(ShaderHandler* shaderHandler, MeshType type, float scale) { Vertex* vertices; uint nVert; switch (type) { default: case Plane: nVert = 6; vertices = new Vertex[nVert]; vertices[0] = Vertex(vec3(-1, -1, 0), vec3(0, 0, 1), vec2(0 , 0 ), vec3(1, 0, 0), vec3(0, -1, 0)); vertices[1] = Vertex(vec3( 1, -1, 0), vec3(0, 0, 1), vec2(scale, 0 ), vec3(1, 0, 0), vec3(0, -1, 0)); vertices[2] = Vertex(vec3(-1, 1, 0), vec3(0, 0, 1), vec2(0 , scale), vec3(1, 0, 0), vec3(0, -1, 0)); vertices[3] = Vertex(vec3( 1, -1, 0), vec3(0, 0, 1), vec2(scale, 0 ), vec3(1, 0, 0), vec3(0, -1, 0)); vertices[4] = Vertex(vec3( 1, 1, 0), vec3(0, 0, 1), vec2(scale, scale), vec3(1, 0, 0), vec3(0, -1, 0)); vertices[5] = Vertex(vec3(-1, 1, 0), vec3(0, 0, 1), vec2(0 , scale), vec3(1, 0, 0), vec3(0, -1, 0)); break; case Cube: nVert = 6 * 6; vertices = new Vertex[nVert]; //NOPE!!!!!!!!!! break; } init(shaderHandler, vertices, nVert); delete[] vertices; } Mesh::~Mesh() { glDeleteBuffers(NUM_BUFFERS, vaoBuffers); glDeleteVertexArrays(1, &vao); } void Mesh::init(ShaderHandler* shaderHandler, Vertex * vertices, uint nVert) { glGenVertexArrays(1, &vao); drawCount = nVert; glBindVertexArray(vao); glGenBuffers(NUM_BUFFERS, vaoBuffers); glBindBuffer(GL_ARRAY_BUFFER, vaoBuffers[VERTICE_BUFFER]); glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex) * nVert, vertices, GL_STATIC_DRAW); Shader* shader = shaderHandler->getPhongShader(); for (int j = 0; j < shader->getGLSLAttributeCount(); j++) { GLSLAttribute attribute = shader->getGLSLAttribute(j); glEnableVertexAttribArray(attribute.location); glVertexAttribPointer( attribute.location, attribute.size, attribute.type, GL_FALSE, shader->getStride(), (void*)attribute.offset ); } } void Mesh::render() { glBindVertexArray(vao); glDrawArrays(GL_TRIANGLES, 0, drawCount); }
true
af2be3061e472c451db388c292235b0d88e312ec
C++
etiennedub/TP_Algo
/TP2/reseau.cpp
UTF-8
12,674
3.375
3
[]
no_license
#include <set> #include "reseau.h" #include <algorithm> // // Created by etienned on 10/31/16. // /** \brief Constructeur de la classe Reseau. * * un objet est créer et mémorisé. * */ Reseau::Reseau(){ } /** * \brief Ajouter un nouveau sommet au graphe. * * \param numero: numero du sommet. * * \exception logic_error : lorsque le sommet existe déjà dans le graphe */ void Reseau::ajouterSommet(unsigned int numero) throw (std::logic_error){ try { liste_arcs temporaire; m_sommets.insert({numero, temporaire}); } catch (std::logic_error e){ throw (e); } } /** * \brief Enleve un sommet du graphe. * * \param numero: numero du sommet. * * \exception logic_error : lorsque le sommet n'est pas dans le graphe. */ void Reseau::enleverSommet(unsigned int numero) throw (std::logic_error){ try { m_sommets.erase(numero); } catch (std::logic_error e){ throw (e); } } /** * \brief Ajouter un arc au graphe. * * \param numOrigine: numero du sommet d'origine. * \param numDest: numero du sommet de la destination. * \param cout: le coût de l'arc. * \param type: le type d'arc (traversé par un bus ou parcour à pied). * * \exception logic_error: lorsque l'arc existe ou qu'un sommet n'existe pas */ void Reseau::ajouterArc(unsigned int numOrigine, unsigned int numDest, unsigned int cout, unsigned int type) throw (std::logic_error){ try { m_sommets[numOrigine].insert({numDest, std::pair<unsigned int, unsigned int>(cout, type)}); } catch (std::logic_error e){ throw (e); } } /** * \brief Supprimer un arc au graphe. * * \param numOrigine: numero du sommet d'origine. * \param numDest: numero du sommet de la destination. * * \exception logic_error: lorsque l'arc n'est pas dans le graphe. */ void Reseau::enleverArc(unsigned int numOrigine, unsigned int numDest) throw (std::logic_error){ try { m_sommets[numOrigine].erase(numDest); } catch (std::logic_error e){ throw (e); } } /** * \brief Mise à jour du coût d'un arc. * * \param numOrigine: numero du sommet d'origine. * \param numDest: numero du sommet de la destination. * \param cout: le nouveau coût de l'arc. * * \exception logic_error: lorsque l'arc n'est pas dans le graphe. */ void Reseau::majCoutArc(unsigned int numOrigine, unsigned int numDest, unsigned int cout) throw (std::logic_error){ try { m_sommets[numOrigine][numDest].first = cout; } catch (std::logic_error e){ throw (e); } } /** * \brief Le nombre de sommets. * \return le nombres de sommets. */ int Reseau::nombreSommets() const{ return m_sommets.size(); } /** * \brief Le nombre d'arc. * \return le nombres d'arc. */ int Reseau::nombreArcs() const{ int nbArcs = 0; for ( auto it = m_sommets.begin(); it != m_sommets.end(); ++it ){ nbArcs += it->second.size(); } } /** * \brief Vérifier si un graphe est vide. * \return vrai si vide. */ bool Reseau::estVide() const{ return m_sommets.empty(); } /** * \brief Vérifie si un sommet existe dans le graphe. * * \param numero: numero du sommet. * * \return vrai si le sommet existe. */ bool Reseau::sommetExiste(unsigned int numero) const{ return (m_sommets.find(numero) != m_sommets.end()); } /** * \brief Vérifie si un arc existe dan le graphe. * * \param numOrigine: numéro d'origine de l'arc. * \param numDest: numéro de la destination de l'arc. * * \return vrai si l'arc existe. */ bool Reseau::arcExiste(unsigned int numOrigine, unsigned int numDest) const throw (std::logic_error){ try { return(m_sommets.at(numOrigine).count(numDest) != 0); } catch (std::logic_error e){ throw (e); } } /** * \brief avoir le coût d'un arc. * * \param numOrigine: le numéro d'origine de l'arc. * \param numDest: le numéro de la destination de l'arc. * * \exception logic_error: lorsque l'arc n'existe pas. * * \return le coût de l'arc. */ int Reseau::getCoutArc(unsigned int numOrigine, unsigned int numDestination) const throw (std::logic_error){ try { return(m_sommets.at(numOrigine).at(numDestination).first); } catch (std::logic_error e){ throw (e); } } /** * \brief Retourne le type d'un arc. * * \param numOrigine: le numéro d'origine de l'arc. * \param numDest: le numéro de la destination de l'arc. * * \exception logic_error: lorsque l'arc n'existe pas. * * \return le type de l'arc. */ int Reseau::getTypeArc(unsigned int numOrigine, unsigned int numDestination) const throw (std::logic_error){ try { return(m_sommets.at(numOrigine).at(numDestination).second); } catch (std::logic_error e){ throw (e); } } /** * \brief algorithmes de Dijkstra. * * \param numOrigine: le numéro d'origine de l'arc. * \param numDest: le numéro de la destination de l'arc. *\param vector chemin: vecteur de sommet * \exception logic_error: lorsque le sommet n'existe pas. * * \return sommets. */ int Reseau::dijkstra(unsigned int numOrigine, unsigned int numDest, std::vector<unsigned int> & chemin) throw (std::logic_error){ try { // Distance_min, predeceseur std::unordered_map<unsigned int, std::pair<unsigned int, unsigned int>> information; for (auto it = m_sommets.begin(); it != m_sommets.end(); ++it ){ information.insert({it->first,std::pair<unsigned int, unsigned int>(INFINI, INFINI)}); } std::set<unsigned int> visite; visite.insert(numOrigine); information[numOrigine] = std::pair<unsigned int, unsigned int>(0, INFINI); while (visite.size() > 0) { // ID, Distance std::pair<unsigned int, unsigned int> distance_min (INFINI,INFINI); for (auto it = visite.begin(); it != visite.end(); ++it ){ if (information[(*it)].first < distance_min.second){ distance_min = std::pair<unsigned int, unsigned int> ((*it), information[(*it)].first); } } if (distance_min.first == numDest) break; // Minimun trouve visite.erase(distance_min.first); for (auto it = m_sommets[distance_min.first].begin(); it != m_sommets[distance_min.first].end(); ++it){ visite.insert(it->first); int sommet_from = distance_min.first; int sommet_to_do = it->first; int ancienne_distance = information[it->first].first; int nouvelle_distance = it->second.first; if (information[it->first].first > distance_min.second + it->second.first) { information[it->first].first = distance_min.second + it->second.first; information[it->first].second = distance_min.first; } } } auto it = information.at(numDest); while (it != information.at(numOrigine)){ int predeceseur = it.second; chemin.insert(chemin.begin(),it.second); it = information.at(predeceseur); } return information[numDest].first; } catch (std::logic_error e){ throw (e); } } /** * \brief algorithmes de bellmanford. * * \param numOrigine: le numéro d'origine de l'arc. * \param numDest: le numéro de la destination de l'arc. *\param vector chemin: vecteur de sommet * \exception logic_error: lorsque le sommet n'existe pas. * * \return sommets. */ int Reseau::bellmanFord(unsigned int numOrigine, unsigned int numDest, std::vector<unsigned int> & chemin) throw (std::logic_error){ bool relachement; // ID, Distance, Predeceseur std::unordered_map<unsigned int, std::pair<unsigned int, unsigned int>> information; for (auto it = m_sommets.begin(); it != m_sommets.end(); ++it ){ information.insert({it->first,std::pair<unsigned int, unsigned int>(INFINI, INFINI)}); } information[numOrigine] = std::pair<unsigned int, unsigned int>(0, INFINI); // NbSommet - 1 fois for (int i = 0; i < m_sommets.size() - 1; i++){ relachement = false; // NbArc for (auto itSommet = m_sommets.begin(); itSommet != m_sommets.end(); ++itSommet ){ for (auto itArc = itSommet->second.begin(); itArc != itSommet->second.end(); ++itArc ){ unsigned int destination = itArc->first; unsigned int source = itSommet->first; unsigned int coutInit = information[destination].first; unsigned int coutNouveau = information[source].first + itArc->second.first; if (coutNouveau < coutInit){ relachement = true; // Cout information[destination].first = coutNouveau; // Predeceseur information[destination].second = source; } } } if (relachement == false) break; } auto it = information.at(numDest); while (it != information.at(numOrigine)){ int predeceseur = it.second; chemin.insert(chemin.begin(),it.second); it = information.at(predeceseur); } return information[numDest].first; } /** * \brief obtenir la composantes fortements connexes * *\param vector composantes * * \return la taille de composante. */ int Reseau::getComposantesFortementConnexes(std::vector<std::vector<unsigned int> > & composantes) const{ Reseau sommet_inverse; std::set<unsigned int> dejaVisite; std::vector<unsigned int> pile; std::vector<unsigned int> composanteTemporaire; for (auto itSommet = m_sommets.begin(); itSommet != m_sommets.end(); ++itSommet) { sommet_inverse.ajouterSommet(itSommet->first); visite(itSommet->first, dejaVisite, pile); for (auto itArc = itSommet->second.begin(); itArc != itSommet->second.end(); ++itArc) { // inverse sommet sommet_inverse.ajouterSommet(itArc->first); sommet_inverse.ajouterArc(itArc->first, itSommet->first, INFINI); } } dejaVisite.clear(); std::vector<unsigned int> vide; for (auto itSommet = pile.end() - 1; itSommet != pile.begin(); --itSommet) { assigne((*itSommet), sommet_inverse.m_sommets, dejaVisite, composanteTemporaire); if(composanteTemporaire != vide){ composantes.push_back(composanteTemporaire); } composanteTemporaire = vide; } return composantes.size(); } /** * \brief vérifie si la compoposante est fortements connexes * *\param vector composantes * * \return return vrai si la composante est fortement connexe. */ bool Reseau::estFortementConnexe() const{ std::vector<std::vector<unsigned int> > composantes; return (this->getComposantesFortementConnexes(composantes) == 1); } /** * \brief Fonction recursive qui fait un parcour en profondeur et ajoute a la pile * *\param sommet: sommet à visiter *\param dejaVisite: set des sommets deja visiter * \param pile : pile de l'ordre des visite * */ void Reseau::visite(unsigned int sommet, std::set<unsigned int> &dejaVisite, std::vector<unsigned int> &pile) const{ if (dejaVisite.find(sommet) == dejaVisite.end()){ dejaVisite.insert(sommet); liste_arcs arcsSuivant = m_sommets.find(sommet)->second; for(auto it = arcsSuivant.begin(); it != arcsSuivant.end(); ++it){ visite(it->first, dejaVisite, pile); } pile.push_back(sommet); } } /** * \brief Fonction recursive qui fait un parcour en profondeur pour trouver composante connexe * *\param sommet: sommet à visiter *\param grapheInverse : graphe à utiliser *\param dejaVisite: set des sommets deja visiter *\param composanteTemporaire : ajout a composante si connexe * */ void Reseau::assigne(unsigned int sommet, std::unordered_map< unsigned int, liste_arcs> grapheInverse, std::set<unsigned int> &dejaVisite, std::vector<unsigned int> &composanteTemporaire) const{ if (dejaVisite.find(sommet) == dejaVisite.end()){ dejaVisite.insert(sommet); composanteTemporaire.push_back(sommet); liste_arcs arcsSuivant = grapheInverse.find(sommet)->second; for(auto it = arcsSuivant.begin(); it != arcsSuivant.end(); ++it){ assigne(it->first, grapheInverse, dejaVisite, composanteTemporaire); } } }
true
6c3c8f6de3e7b4a2793df54a43a8020ce9d9d7ad
C++
marc-hanheide/cogx
/subarchitectures/vision.sa/branches/spring-school-2011-DEPRECATED/src/c++/vision/components/ShapeDescriptor3D/DShape3D/Vector2I.hh
UTF-8
462
2.515625
3
[]
no_license
/** * $Id: Vector2I.hh,v 1.1.1.1 2008/02/29 10:12:02 jp Exp $ */ #ifndef VECTOR2I_HH #define VECTOR2I_HH #include "PNamespace.hh" namespace P { /** * Vector2 */ class Vector2I { public: int x, y; Vector2I(); Vector2I(const Vector2I &); Vector2I(int xx, int yy) : x(xx), y(yy) {} ~Vector2I(){} Vector2I &operator=(const Vector2I &rhs); int operator==(const Vector2I &rhs) const; int operator<(const Vector2I &rhs) const; }; } #endif
true
3dabaf434c3c2862d503bdbf6193e2136f5b1a5b
C++
Moonfish/smartrain2
/src/RelayController.cpp
UTF-8
1,912
2.765625
3
[]
no_license
/* * RelayController.cpp * * Created on: Dec 20, 2014 * Author: russell */ #include <linux/i2c-dev.h> #include <sys/ioctl.h> #include <fcntl.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <exception> #include <system_error> #include "RelayController.h" #include "util.h" RelayController::RelayController(int relayCount, const char* device, int i2cAddress) : m_currentlyOnValve(-1), m_fd(-1), m_relayCount(relayCount) { // Warmup ::usleep(100); m_fd = ::open(device, O_RDWR); if (m_fd < 0) throw std::system_error(); int chk = ::ioctl(m_fd, I2C_SLAVE, i2cAddress); if (chk < 0) throw std::system_error(); RelaysOff(); } RelayController::~RelayController() { RelaysOff(); } void RelayController::RelayOn(int relay) { constexpr int overlapDelay = 2000; if (relay < 0 || relay >= m_relayCount) throw std::invalid_argument("relay"); // Already on? if (IsRelayOn(relay)) return; if (m_currentlyOnValve == -1) { std::uint8_t bitsVal = ~(1 << relay); ::write(m_fd, &bitsVal, 1); util::msleep(50); } else { // Overlap valve on-times to avoid water pressure hammering std::uint8_t bitsCurrent = (1 << m_currentlyOnValve); std::uint8_t bitsVal = (1 << relay); std::uint8_t combined = ~(bitsVal | bitsCurrent); ::write(m_fd, &combined, 1); util::msleep(overlapDelay); bitsVal = ~bitsVal; ::write(m_fd, &bitsVal, 1); util::msleep(50); } m_currentlyOnValve = relay; } bool RelayController::IsRelayOn(int relay) { return (relay == m_currentlyOnValve); } void RelayController::RelaysOff() { if (m_currentlyOnValve == -1) return; m_currentlyOnValve = -1; std::uint8_t val = 0xFF; ::write(m_fd, &val, 1); util::msleep(50); } void RelayController::Test() { for (int i = 0; i < m_relayCount; ++i) { RelayOn(i); util::msleep(1000); } }
true
1189560694ea000a0c2b00e5f4c7aa8c476b9773
C++
giltolley/Data-Structures-and-Algorithms
/Linked-List/LinkedList/Test.cpp
UTF-8
1,729
3.359375
3
[]
no_license
#include "stdafx.h" #include "LinkedList.h" int main() { string userInput; char choice; bool exit = false; RecordList myRecord; vector<string> listView; string art; string title; string year; while (exit != true) { cout << "+================================================+" << endl; cout << "+ +" << endl; cout << "+ Press A to add a Record to the Record Record +" << endl; cout << "+ Press V to View the Record Record +" << endl; cout << "+ Press Q to Quit +" << endl; cout << "+ +" << endl; cout << "+================================================+" << endl; getline(cin, userInput); if (userInput.length() == 0) { choice = 'X'; } else { choice = userInput[0]; } switch (choice) { case 'A': case 'a': cout << "Please enter the Artist name: "; getline(cin, art); cout << endl; cout << "Please enter the Title of the CD: "; getline(cin, title); cout << endl; cout << "What year was it released?: "; getline(cin, year); cout << endl; myRecord.insertItem(art, title, stoi(year)); system("CLS"); break; case 'V': case 'v': listView = myRecord.printList(); cout << "Record List:"; cout << endl; for (vector<string>::iterator it = listView.begin(); it != listView.end(); ++it) cout << ' ' << *it; cout << endl; break; case 'Q': case 'q': exit = true; break; case 'X': case 'x': default: cout << "No valid input detected...Please try again."; cout << endl; } } return 0; }
true
799b06923363adf9b42654260d1e3ca94a9587c8
C++
NelsonGomesNeto/Competitive-Programming
/Online Judges/CodeForces/Contests/1241 - Codeforces Round #591 (Div. 2, based on Technocup 2020 Elimination Round 1)/E - Paint the Tree.cpp
UTF-8
1,903
2.6875
3
[]
no_license
#include <bits/stdc++.h> #define DEBUG if(0) #define lli long long int #define ldouble long double using namespace std; /* Tutorial: For each vertex, you can choose at most k edges to add to the answer (and you can't add the same edge twice). Formally, for each vertex u, you either choose or not the edge(u, parent[u]). Using dfs and DP we can calculate memo[u][false] and memo[u][true] for all u childsAns = {memo[v][true] + uv.cost - memo[v][false] for all childs of u} Sort childsAns descendelly We can choose (k - chose) edges, so: memo[u][chose] = max(sum(memo[v][false]), sum(memo[v][false]) + childsAns[0 : i] for i in [0 : k - chose)) */ const int maxN = 5e5; int n, k; struct Edge { int to; lli cost; }; vector<Edge> graph[maxN]; lli memo[maxN][2]; lli dfs(int u = 0, int prv = -1, bool chose = false) { if (memo[u][chose] == -1) { vector<lli> childAns; lli sum = 0; for (Edge &e: graph[u]) { if (e.to == prv) continue; childAns.push_back(dfs(e.to, u, true) + e.cost - dfs(e.to, u, false)); sum += memo[e.to][false]; } sort(childAns.begin(), childAns.end(), greater<lli>()); memo[u][chose] = sum; for (int i = 0; i < k - chose && i < childAns.size(); i ++) { sum += childAns[i]; memo[u][chose] = max(memo[u][chose], sum); } } return memo[u][chose]; } int main() { int q; scanf("%d", &q); while (q --) { scanf("%d %d", &n, &k); for (int i = 0; i < n; i ++) graph[i].clear(), memo[i][0] = memo[i][1] = -1; for (int i = 0; i < n - 1; i ++) { int u, v; lli w; scanf("%d %d %lld", &u, &v, &w); u --, v --; graph[u].push_back({v, w}), graph[v].push_back({u, w}); } lli ans = dfs(); DEBUG for (int i = 0; i < n; i ++) printf("%d %lld %lld\n", i + 1, memo[i][0], memo[i][1]); printf("%lld\n", ans); } return 0; }
true
50f176a0e23edf8362a048dd123de7d62e791b0c
C++
mistervunguyen/starting-out-with-c-plus-plus-early-objects-solutions
/Programming Challenges/Chapter09/9_11.cpp
UTF-8
3,515
3.875
4
[]
no_license
// Chapter 9 - Programming Challenge 11, Ascending Circles // This modifies Program 8-31 from Chapter 8 to create an array of 7 Circle // objects, use a Bubble Sort to arrange them in ascending order of radius // size, and then compute and display their areas. Displaying the circle radii // along with their areas is optional. The Circle.h file that defines the class // used by this program is located in the Chapter 9 Programs folder, and for // faculty is also in the same folder as this solution file. A copy of the // Circle.h file should be placed in the program's project directory. #include <iostream> #include <iomanip> #include "Circle.h" // Needed to create Circle objects using namespace std; // Function prototypes // These functions each receive an array of Circle objects void bubbleSort(Circle[]); void displayAreas(Circle[]); const int NUM_CIRCLES = 7; int main() { // Define an array of 8 Circle objects. Use an initialization list // to call the 1-argument constructor that sets their radii. Circle circle[NUM_CIRCLES] = {2.5, 4.0, 1.0, 3.0, 6.0, 5.5, 2.0}; // Call a function to sort the object according to radius size bubbleSort(circle); // Now call a function to display the area of each object cout << fixed << showpoint; cout << "Here are the areas of the " << NUM_CIRCLES << " circles.\n\n"; displayAreas(circle); return 0; } // End main /************************************************************* * bubbleSort * * Called by: main * * Passed : The array of Circle objects to be sorted * * Purpose : Sorts the objects into ascending radius order * *************************************************************/ void bubbleSort(Circle circle[]) { bool swap; Circle temp; do { swap = false; // There have been no swaps yet on this pass for (int count = 0; count < (NUM_CIRCLES - 1); count++) { if (circle[count].getRadius() > circle[count + 1].getRadius()) { // The 2 array elements are out of order, so swap them temp = circle[count]; circle[count] = circle[count + 1]; circle[count + 1] = temp; swap = true; } } } while (swap); // While there was a swap on the previous pass }// End function bubbleSort /************************************************************* * displayAreas * * Called by: main * * Passed : The array of Circle objects * * Purpose : Displays the radius and area of each circle * *************************************************************/ void displayAreas(Circle circle[]) { for (int index = 0; index < NUM_CIRCLES; index++) { cout << "circle " << (index+1) << " with radius " << setprecision(1) << circle[index].getRadius() << " has area = " << setw(6) << setprecision(2) << circle[index].findArea() << endl; } }// End function displayAreas /* CORRECT RESULTS Here are the areas of the 7 circles. circle 1 with radius 1.0 has area = 3.14 circle 2 with radius 2.0 has area = 12.56 circle 3 with radius 2.5 has area = 19.63 circle 4 with radius 3.0 has area = 28.26 circle 5 with radius 4.0 has area = 50.24 circle 6 with radius 5.5 has area = 94.98 circle 7 with radius 6.0 has area = 113.04 */
true
f14bdc11afb024b86ea9aeadc4320271ef60dab0
C++
JinhaJjing/Algorithm
/Algorithm/Solved/소수 만들기.cpp
WINDOWS-1252
564
3.46875
3
[]
no_license
// https://programmers.co.kr/learn/courses/30/lessons/12977 // ܼ #include <vector> #include <iostream> #include <cmath> using namespace std; bool isPrime(int num) { for (int i = 2; i <= sqrt(num); i++) if (num % i == 0) return false; return true; } int solution(vector<int> nums) { int answer = 0; for (int i = 0; i < nums.size(); i++) { for (int j = i + 1; j < nums.size(); j++) { for (int k = j + 1; k < nums.size(); k++) { int temp = nums[i] + nums[j] + nums[k]; if (isPrime(temp)) answer++; } } } return answer; }
true
9826a2c700c0aa68913dd38ec4e14909fae05904
C++
compagnb/compagnb_sims2014
/Wk3_HW_NotBallParticles/src/ofApp.cpp
UTF-8
2,443
2.65625
3
[]
no_license
// // // Wk3_HW_NotBallParticles // // Created by compagnb on 9/13/14. // // #include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ ofSetVerticalSync(true); //load the image surf.loadImage("images/test.jpg"); ofSetBackgroundAuto(false); ofSetFrameRate(60); ofEnableSmoothing(); ofEnableAlphaBlending(); ofBackground(0); } //-------------------------------------------------------------- void ofApp::update(){ for (int i = 0; i<particles.size(); i++){ particles[i].update(); } } //-------------------------------------------------------------- void ofApp::draw(){ for (int i=0; i<particles.size(); i++) { particle &p = particles[i]; //particle p = # p.draw();//draw particle } for (int i=0; i<100; i++) {//creates 100 particles createParticle(); } while (particles.size()>1000) { particles.erase(particles.begin()); //erase after 1000 particles are drawn } } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ } //-------------------------------------------------------------- void ofApp::createParticle() { particle p; //create a particle and name it p p.setup(); //run setup p.pos.set(ofRandomWidth(), ofRandomHeight());//set randomly p.color = surf.getColor(p.pos.x,p.pos.y);//gets the color from the x and y pos particles.push_back(p);// push it back in the vector }
true
06be442fef324ab7fafb37ece4b69ed33c06f113
C++
stank2010/code-competitive-programming
/cdoecube.in.th/183_Plagiarist.cpp
UTF-8
1,232
2.84375
3
[]
no_license
#include "stdio.h" struct sakan { int count,num; }tree[1100001],Null; int z[200000],n; int make_tree(int h,int l,int index) { if(h==l) { tree[index].num = z[h]; tree[index].count = 1; } else { int mid=(h+l)/2; tree[index].count += make_tree(h,mid,2*index+1); tree[index].count += make_tree(mid+1,l,2*index+2); return tree[index].count; } return tree[index].count; } int del_tree(int index,int seq) { int index_left = 2*index + 1; int index_right = 2*index + 2; if(tree[index_left].count == 0 && tree[index_right].count == 0) { int parent = (index - 1)/2 , val = tree[index].num; tree[index] = Null; if(index == parent*2 + 1) tree[parent] = tree[ parent*2 + 2 ]; else tree[parent] = tree[ parent*2 + 1 ]; return val; } tree[index].count--; if(seq <= tree[index_left].count) { return del_tree( index_left , seq ); } else { return del_tree( index_right , seq - tree[index_left].count ); } } int main() { scanf("%d",&n); for(int i=0;i<n;i++) scanf("%d",&z[i]); make_tree(0,n-1,0); int a; for(int i=0;i<n;i++) { scanf("%d",&a); printf("%d\n",del_tree(0,a)); } return 0; }
true
9e83cfdcc5b76152c40b33625dee7c5d72695632
C++
josewannan98/Practica1_EDD_2
/EDD_practica1_201612331/src/Lista_restaurantes.cpp
UTF-8
839
3.03125
3
[]
no_license
#include "Lista_restaurantes.h" Lista_restaurantes::Lista_restaurantes() { //ctor this->primero = nullptr; this->ultimo = nullptr; } Lista_restaurantes::~Lista_restaurantes() { //dtor } void Lista_restaurantes::ingresar_restaurante(NodoRestaurantes *nodo) { NodoRestaurantes *nuevo = nodo; nuevo->id = this->id_actual; if(primero==nullptr) { this->primero = nuevo; this->ultimo = nuevo; } else { this->ultimo->siguiente = nuevo; nuevo->anterior = this->ultimo; this->ultimo = nuevo; } } int Lista_restaurantes::personas_aqui() { NodoRestaurantes *pivote = this->primero; int personas = 0; while(pivote!=nullptr) { personas = personas + pivote->capacidad; pivote = pivote->siguiente; } return personas; }
true
943b8f52581478be0848005696238a1d9ebf8f66
C++
CR7-Messi/Algorithm
/Hashing-H.cpp
UTF-8
1,060
2.671875
3
[]
no_license
#include <iostream> #include <vector> #include <queue> using namespace std; const int N = 1000; int num[N], indegree[N]; struct cmp { bool operator()(int i, int j) { return num[i] > num[j]; }}; int main() { int i, j, n, m, k, flag = 0; scanf("%d", &n); vector<vector<int> > g(n); priority_queue<int, vector<int>, cmp> q; for (i = 0; i < n; i++) scanf("%d", &num[i]); for (i = 0; i < n; i++) { if (num[i] > 0) { k = num[i] % n; indegree[i] = (i + n - k) % n; if (indegree[i]) { for (j = 0; j <= indegree[i]; j++) g[(k + j) % n].push_back(i); } else q.push(i); }} while (!q.empty()) { i = q.top(); q.pop(); if (!flag) { flag = 1; printf("%d", num[i]); } else printf(" %d", num[i]); for (j = 0; j < g[i].size(); j++) { if (--indegree[g[i][j]] == 0) q.push(g[i][j]); } } return 0;}
true
9e7c5e21cb26f68df7d8bb08ec4d79032c6e1620
C++
WeAreChampion/notes
/c/base/Char A + B.cpp
UTF-8
418
3.578125
4
[ "Apache-2.0" ]
permissive
#include<iostream> using namespace std; int f(char a) { int value; if(a >= '0' && a <= '9') { //is number value = a - '0'; } else if(a >= 'a' && a <= 'z') { //is lower word[a-z] value = a - 87; } else if(a >= 'A' && a <= 'Z') { //is upper word[A-Z] value = a - 55; } return value; } int main() { char a[10], b[10]; while(cin>>a>>b) { //calculate a + b cout<<f(a[0]) + f(b[0])<<endl; } return 0; }
true
6f08b4af8df0daebfcb5bd2dc5ce2e4c8a3361a7
C++
wjddlsy/Algorithm
/Baekjoon/baek_2904_수학은너무쉬워/main.cpp
UTF-8
1,155
2.84375
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> #include <map> using namespace std; int gcd(int a, int b) { return b?gcd(b, a%b):b; } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int N; cin>>N; map<int, int> primes; vector<map<int, int>> numbers(N); for(int i=0; i<N; ++i) { int n; cin>>n; for(int d=2; d*d<=n; ++d) { while(n) { if(n%d!=0) break; primes[d]++; numbers[i][d]++; n/=d; } } if(n>1) { primes[n]++; numbers[i][n]++; } } map<int, int> ret; int cnt=0, greatest=1; for(auto &prime:primes) { ret[prime.first]=prime.second/N; } for(auto &number:numbers) { for(auto &r:ret) { if(number[r.first]>r.second) continue; cnt+=abs(number[r.first]-r.second); } } for(auto &r:ret) { for(int i=0; i<r.second; ++i) { greatest*=r.first; } } cout<<greatest<<" "<<cnt; return 0; }
true
edb70b638b2e3f9861892764fc5bce124810cb18
C++
uchihaitachi08/daily_code
/hackerearth/practice/e_test.cpp
UTF-8
1,015
3.40625
3
[]
no_license
#include<iostream> #include<stack> #include<cmath> using namespace std; void print_ver(int**arr,int top,int bottom,int col){ bool check = (top>bottom); for(int i=top;(check) ? (i>=bottom) : (i<=bottom); (check) ? i-- : i++){ cout<<arr[i][col]<<" "; } cout<<endl; } void print_hor(int** arr,int left,int right,int row){ bool check = (left > right); for(int i=left;(check) ? (i>=right) : (i<=right);(check) ? i-- : i++){ cout<<arr[row][i]<<" "; } cout<<endl; } void print_maze(int** arr,int n){ int i,j; print_ver(arr,n,0,0); for(i=n,j=1;i>=j;i--,j++){ print_hor(arr,j,i,j-1); print_ver(arr,j,i,i); if(i==j) break; print_hor(arr,i-1,j,i); print_ver(arr,i-1,j,j); } } int main(){ int n; cin>>n; int **arr = new int*[n]; for(int i=0;i<n;i++){ arr[i] = new int[n]; } for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ cin>>arr[i][j]; } } for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ cout<<arr[i][j]<<" "; } cout<<endl; } cout<<"========"<<endl; print_maze(arr,n-1); }
true
af1b340d45353f5dbe02d58820ca66758825c80a
C++
ablondal/comp-prog
/Practice/Club_Prac_5/f.cpp
UTF-8
1,141
2.5625
3
[]
no_license
#include <iostream> #include <vector> #include <iomanip> using namespace std; typedef long long ll; typedef long double ld; #define max(a,b) ((a>b)?a:b) #define min(a,b) ((a<b)?a:b) // const ld EPS = 1e-9; int n; ld m; int a[1001], sa[1001], b[1001], sb[1001]; bool canwork(ld fuel){ for(int i=0; i<n; ++i){ fuel = fuel - ((m+fuel) / a[i]); fuel = fuel - ((m+fuel) / b[i+1]); if (fuel < 0) return false; } return true; } int main(){ cin >> n >> m; for(int i=0; i<n; ++i){ cin >> a[i]; if (a[i] < 2){ cout << -1 << endl; return 0; } } for(int i=0; i<n; ++i){ cin >> b[i]; if (b[i] < 2){ cout << -1 << endl; return 0; } } b[n] = b[0]; ld fuel = 0; for(int i=n-1; i>=0; --i){ fuel = ( fuel + ((ld)m/b[i+1]) ) / ((ld)1.0 - ((ld)1.0/b[i+1])); fuel = ( fuel + ((ld)m/a[i]) ) / ((ld)1.0 - ((ld)1.0/a[i])); if (fuel > 2e9){ cout << -1 << endl; return 0; } } ld min = fuel - 10; ld max = fuel; ld mid; while(max-min > 1e-7){ mid = max/2.0 + min/2.0; if (canwork(mid)){ max = mid; }else{ min = mid; } } cout << std::setprecision(18) << max << endl; }
true
98bc2e8aa4123d8867c17de8d2a183cb65d7bf0f
C++
linaben1/ProjetCpp
/FilesCpp_h/Mini.cpp
UTF-8
1,136
2.6875
3
[]
no_license
#include "Projet.h" /********************************************************************************************************/ void DistributionPoints::InitAdvantages() { nbPointsFree = 15; nbPointsExperience = 0; } int DistributionPoints::GetExperience(int retirePoints) { nbPointsExperience = nbPointsExperience - retirePoints; return nbPointsExperience; } void DistributionPoints::setExperience(int initExp) { nbPointsExperience = initExp; } void DistributionPoints::changeFreePoints(string type) { if(type.compare("Attribute") == 0) { if(nbPointsFree > 0 && nbPointsFree - 5 >= 0) nbPointsFree = nbPointsFree - 5; } //Attribute 5 per dot //Ability 2 per dot //Discipline 7 per dot //Background 1 per dot //Virtue 2 per dot //Humanity 2 per dot //Willpower 1 per dot } void DistributionPoints::changeExperrience() { //New Ability:3 //New Discipline:10 //New Path:7 //Attribute:CRx4 //Ability:CRx2 //Clan Discipline:CRx5 //Other Discipline:CRx7 //Secondary Path:CRx4 //Virtue:CRx2 //Humanity or Path of Enlightenment:CR2 //Willpower:CR // !!*CR is the current rating of the trait }
true
f51ad31dc706a9437d4cf73faa88ed22dd9defaa
C++
AvihaiAdler/Coffee-Shop-STL
/CoffeeShop.cpp
UTF-8
3,677
3.34375
3
[]
no_license
#include "CoffeeShop.h" CoffeeShop::CoffeeShop(const std::string& name, const Address& address) : address(address) { setName(name); customersMaxSize = SIZE_MULTIPLIER; employeesMaxSize = SIZE_MULTIPLIER; shiftsMaxSize = 3; productsMaxSize = SIZE_MULTIPLIER; } CoffeeShop::CoffeeShop(CoffeeShop&& other) : address(std::move(other.address)) { if (this != &other) { customersMaxSize = other.customersMaxSize; employeesMaxSize = other.employeesMaxSize; shiftsMaxSize = other.shiftsMaxSize; productsMaxSize = other.productsMaxSize; name = other.name; customers = other.customers; employees = other.employees; products = other.products; shifts = other.shifts; } } CoffeeShop::CoffeeShop(const std::string& name, Address&& address) : address(std::move(address)) { setName(name); customersMaxSize = SIZE_MULTIPLIER; employeesMaxSize = SIZE_MULTIPLIER; shiftsMaxSize = 3; productsMaxSize = SIZE_MULTIPLIER; } // setters bool CoffeeShop::setName(const std::string& name) { this->name = name; return true; } bool CoffeeShop::setAddress(const Address& address) { if (&this->address == &address) return false; this->address = address; return true; } bool CoffeeShop::addNewEmployee(const Employee& employee) { if (employees.size() == employeesMaxSize) { employeesMaxSize *= SIZE_MULTIPLIER; employees.reserve(employeesMaxSize); } employees.push_back(employee); return true; } bool CoffeeShop::addNewEmployee(Employee&& employee) { if (employees.size() == employeesMaxSize) { employeesMaxSize *= SIZE_MULTIPLIER; employees.reserve(employeesMaxSize); } employees.push_back(employee); return true; } bool CoffeeShop::addNewProduct(const Product& product) { if (products.size() == productsMaxSize) { productsMaxSize *= SIZE_MULTIPLIER; products.reserve(productsMaxSize); } products.push_back(&product); return true; } bool CoffeeShop::addNewProduct(Product&& product) { if (products.size() == productsMaxSize) { productsMaxSize *= SIZE_MULTIPLIER; products.reserve(productsMaxSize); } products.push_back(product.clone()); return true; } bool CoffeeShop::addNewCustomer(const Customer& customer) { if (customers.size() == customersMaxSize) { customersMaxSize *= SIZE_MULTIPLIER; customers.reserve(customersMaxSize); } customers.push_back(customer); return true; } bool CoffeeShop::addNewCustomer(Customer&& customer) { Customer tmp = Customer(customer.getName(), customer.getPhoneNumber(), customer.isClubMember()); return addNewCustomer(tmp); } bool CoffeeShop::openShift(double clubDiscountPercent, const Date& date) { if (shifts.size() == shiftsMaxSize) { shiftsMaxSize *= SIZE_MULTIPLIER; shifts.reserve(shiftsMaxSize); } shifts.push_back(Shift(clubDiscountPercent, date)); return true; } Shift& CoffeeShop::getCurrentShift() { return shifts.back(); } std::ostream& operator<<(std::ostream& os, const CoffeeShop& coffeeShop) { os << "Coffee Shop: " << coffeeShop.name << "\nNumber of employees: " << coffeeShop.getEmployees().size() << "\nShifts: " << coffeeShop.getShifts().size() << std::endl; if (coffeeShop.shifts.size() != 0) { int counter = 1; for (auto shift : coffeeShop.getShifts()) { std::cout << counter << ". " << shift << std::endl; counter++; } } if (coffeeShop.products.size() != 0) { int counter = 1; os << "Products list:\n"; for (auto product : coffeeShop.products) { std::cout << counter << ". " << product << std::endl; counter++; } } return os; }
true
b8e9a87818a4f391d3a9cf35f3250e589be8e59c
C++
Rostin/NeuralNet
/RostinNE/RostinNE/Neuron.cpp
UTF-8
2,463
3.046875
3
[]
no_license
#include "stdafx.h" #include "Neuron.h" namespace Core { Neuron::Neuron(unsigned numOfOutputs, unsigned myIndex): m_myIndex {std::move(myIndex)} { m_outputWeights.reserve(numOfOutputs); for (auto c{ 0u }; c < numOfOutputs; ++c) { auto& w{ m_outputWeights.emplace_back() }; w.weight = getRandomWeight(); } } [[nodiscard]] auto Neuron::getOutputVal() const noexcept ->double { return m_outputVal; } void Neuron::setOutputVal(double val) noexcept { m_outputVal = std::move(val); } void Neuron::feedForward(const Layer& prevLayer) noexcept { const auto sum { std::accumulate(prevLayer.cbegin(), prevLayer.cend(), .0, [&](auto sum, auto & pLayer) { return sum + pLayer.getOutputVal() * pLayer.m_outputWeights[m_myIndex].weight; }) }; m_outputVal = transferFunction(sum); } void Neuron::calcOutputGradients(const double targetVal) noexcept { const auto delta{ targetVal - m_outputVal }; m_gradient = delta * transferFunctionDerivative(m_outputVal); } void Neuron::calcHiddenGradients(const Layer& nextLayer) noexcept { const auto dow{ sumDOW(nextLayer) }; m_gradient = dow * transferFunctionDerivative(m_outputVal); } void Neuron::updateInputWeights(Layer& prevLayer) noexcept { for(auto& neuron : prevLayer) { const auto oldDeltaWeight{ neuron.m_outputWeights[m_myIndex].deltaWeight }; const auto newDeltaWeight = eta * neuron.getOutputVal() * m_gradient + alpha * oldDeltaWeight; neuron.m_outputWeights[m_myIndex].deltaWeight = newDeltaWeight; neuron.m_outputWeights[m_myIndex].weight += newDeltaWeight; } } [[nodiscard]] auto Neuron::sumDOW(const Layer& nextLayer) const noexcept ->double { auto idx{ size_t{0} }; return std::accumulate(std::cbegin(m_outputWeights), std::cend(m_outputWeights), .0, [&](auto sum, auto & weights) { return sum + (weights.weight * nextLayer[idx++].m_gradient); }); } [[nodiscard]] auto Neuron::getRandomWeight() noexcept ->double { const auto seed{ std::chrono::high_resolution_clock::now().time_since_epoch().count() }; const auto dis{ std::uniform_real_distribution<double>(0, 1) }; auto gen{ std::mt19937_64(seed) }; return dis(gen); } [[nodiscard]] auto Neuron::transferFunction(const double x) noexcept ->double { return tanh(x); } [[nodiscard]] auto Neuron::transferFunctionDerivative(const double x) noexcept ->double { return 1.0 - std::pow(x, 2); } }
true
c3644fd9ea570f09ea061cecbc5e9853937400eb
C++
elkprostoelk/1year_cpp_labs
/лабы 1 курс с++/Lab6/Zavd1/Zavd1.cpp
UTF-8
454
3.4375
3
[]
no_license
#include<iostream> using namespace std; class Student { public: unsigned int age; string sex; float stypendia; }; int main() { Student std1, std2; std1 = { 20,"male",1300. }; std2 = { 21,"female",1600. }; Student stud[2] = { std1,std2 }; for (int i = 0; i < 2; i++) { cout << "Student " << i+1 << endl; cout << stud[i].age << "\t"; cout << stud[i].sex << "\t"; cout << stud[i].stypendia; cout << endl; } system("pause"); return 0; }
true
5ebabb26e1e0cdef02a8be524b84b6fb8571d7f8
C++
cs15b047/CF
/Problems/Practice/C/278.cpp
UTF-8
1,900
3.4375
3
[]
no_license
#include<bits/stdc++.h> using namespace std; typedef long long int ll; ll num_elements; vector<ll> elements; map<ll, ll> partition_1, partition_2; void initialize(){ scanf("%lld", &num_elements); elements.resize(num_elements); for(int i = 0;i < num_elements; i++)scanf("%lld", &elements[i]); } void populate_partitions(){ partition_1.clear(); partition_2.clear(); // populate partition 2 with all elements for(auto it: elements){ partition_2[it] += 1; } } void print_partitions(){ cout << "Partition 1"<< endl; for(auto it: partition_1){ cout << it.first << " : " << it.second << endl; } cout << "Partition 2"<< endl; for(auto it: partition_2){ cout << it.first << " : " << it.second << endl; } } void update_partitions(ll incoming_ele){ partition_1[incoming_ele] += 1; partition_2[incoming_ele] -= 1; if(partition_2[incoming_ele] == 0)partition_2.erase(incoming_ele); } bool can_divide(){ ll total_sum = 0; for(auto it: elements)total_sum += it; if(num_elements == 1 || total_sum % 2 == 1)return false; // initial setup ll sum_1 = 0, sum_2 = total_sum; populate_partitions(); for(int partition_idx = 0; partition_idx < num_elements; partition_idx++){ ll incoming_ele = elements[partition_idx]; // update counters update_partitions(incoming_ele); sum_1 += incoming_ele; sum_2 -= incoming_ele; // print_partitions(); // cout << "Sums: " << sum_1 << " " << sum_2<< endl; if(sum_1 == sum_2)return true; // check if swapping 1 element can make totals equal bool can_swap_and_fix; if(sum_1 < sum_2) can_swap_and_fix = (partition_2.find((sum_2 - sum_1)/2) != partition_2.end()); else can_swap_and_fix = (partition_1.find((sum_1 - sum_2)/2) != partition_1.end()); if(can_swap_and_fix)return true; } return false; } int main(){ initialize(); bool possible = can_divide(); if(possible)printf("YES\n"); else printf("NO\n"); }
true