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
a3b4ee8308295acacc3452c192b68b3771e5ec0e
C++
mengchun0120/interview
/src/counting_bits.cpp
UTF-8
2,098
3.6875
4
[]
no_license
/* Given a non negative integer num. For every numbers i in the range 0 <= i <= num, calculate the number of 1's in their binary representation and return them as an array. Example 1: Input 2, Output [0, 1, 1] Example 2: Input 5, Output [0, 1, 1, 2, 1, 2] Follow up: It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n), possibly in a single pass? Space complexiy should be O(n). */ #include <cassert> #include <vector> #include <list> using namespace std; struct Scope { unsigned start; unsigned end; Scope(unsigned s, unsigned e) : start(s) , end(e) {} }; void countBits(vector<int>& c, unsigned int n) { c.push_back(0); if(n < 1) { return; } list<Scope> scopes; int newCount; scopes.emplace_front(0,0); c.push_back(1); for(unsigned int i = 2; i <=n; ++i) { auto it = scopes.begin(); if(it->start == 0) { newCount = c[i-1] - it->end + it->start; unsigned int newEnd = it->end + 1; auto it2 = it; ++it; if(it == scopes.end() || it->start > newEnd + 1) { it2->start = newEnd; it2->end = newEnd; } else { scopes.pop_front(); it->start = newEnd; } } else { newCount = c[i-1] + 1; if(it->start == 1) { it->start = 0; } else { scopes.emplace_front(0,0); } } c.push_back(newCount); } } int main() { vector<int> r1; vector<int> e1{0}; countBits(r1, 0); assert(r1 == e1); vector<int> r2; vector<int> e2{0,1}; countBits(r2, 1); assert(r2 == e2); vector<int> r3; vector<int> e3{0,1,1,2,1}; countBits(r3, 4); assert(r3 == e3); vector<int> r4; vector<int> e4{0, 1,1,2,1,2,2,3,1,2,2, 3,2,3,3,4,1,2,2,3,2, 3,3,4,2,3,3,4,3,4,4}; countBits(r4, 30); assert(r4 == e4); }
true
ea2d77188c317e5030abf7fd23504c673c9d34fa
C++
reysub/SNC
/src/configuration/constants/ConstantsManager.h
UTF-8
935
2.5625
3
[]
no_license
#ifndef CONSTANTMANAGER_H_ #define CONSTANTMANAGER_H_ #include <string> namespace GlobalConstants { const int MASTER = 0; const int MAX_CHARS_PER_LINE = 4096; const std::string EXECUTION_FOLDER = "_Execution/"; } namespace ConfigurationConstants { const std::string FIELD_SEPARATION_SYMBOL = "="; const std::string VALUES_SEPARATION_SYMBOL = ":"; const std::string COMMENT_STARTING_SYMBOL = "#"; } namespace PreprocessingFolderConstants { const std::string PREPROCESSING_ROOT_FOLDER = "Preprocessing/"; const std::string MAPPING_FOLDER_1 = "Mapping/"; const std::string MAPPING_FOLDER_2 = "Mapping_Data/"; const std::string DEGREES_COMPUTATION_FOLDER_1 = "DegreesComputation/"; const std::string DEGREES_COMPUTATION_FOLDER_2 = "DegreesComputation_Data/"; const std::string PARTITIONING_FOLDER_1 = "Partitioning/"; const std::string PARTITIONING_FOLDER_2 = "Partitioning_Data/"; } #endif
true
f5d28ddf5fb7655d4f72b81d6afbaae55491e337
C++
mfkiwl/SLAM-KDQ
/SlamCodes/gauss_filter/app/test2.cpp
UTF-8
1,110
2.5625
3
[]
no_license
// // Created by kdq on 2021/6/22. // #include <stdio.h> #include <stdlib.h> #include "GslGaussFilter.hpp" #include <gsl/gsl_math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include "fstream" int main(void) { const size_t N = 500; /* length of time series */ const size_t K = 51; /* window size */ const double alpha[3] = { 0.5, 3.0, 10.0 }; /* alpha values */ GslGaussFilter f1(K,alpha[0]); GslGaussFilter f2(K,alpha[1]); GslGaussFilter f3(K,alpha[2]); std::vector<double> x; size_t i; double sum = 0.0; gsl_rng *r = gsl_rng_alloc(gsl_rng_default); /* generate input signal */ for (i = 0; i < N; ++i) { double ui = gsl_ran_gaussian(r, 1.0); sum += ui; x.push_back(sum); } std::vector<double> y1,y2,y3; y1 = f1.apply(x); y2 = f2.apply(x); y3 = f3.apply(x); std::ofstream file("test2.csv",std::ios::out); file << "y,y0_5,y3,y10" << std::endl; /* print filter results */ for (i = 0; i < N; ++i) { file << x[i] << "," << y1[i] << "," << y2[i] <<"," << y3[i] << std::endl; } return 0; }
true
0b7178d972195fa444391310cd4c2cad8560fc80
C++
tonycar12002/leetcode
/Cpp/454. 4Sum II.cpp
UTF-8
692
3.015625
3
[]
no_license
/* Author: Tony Hsiao Date: 2019/05/08 Topic: 454. 4Sum II Speed: 148 ms, 28.6 MB Note: Hash Table */ class Solution { public: int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) { unordered_map<int, int>numbers; for(int a=0;a<A.size();a++){ for(int b=0;b<B.size();b++){ numbers[A[a]+B[b]] += 1; } } int ans = 0; for(int c=0;c<C.size();c++){ for(int d=0;d<D.size();d++){ auto t = numbers.find(-C[c]-D[d]); if(t!=numbers.end()){ ans += t->second; } } } return ans; } };
true
bbd73a58861587a694b35a4e8a2d46646ce09063
C++
korca0220/Algorithm_study
/ACMICPC/SWtest/Problem/Review/a_ramp.cpp
UTF-8
1,465
2.84375
3
[]
no_license
#include <iostream> #include <vector> using namespace std; int N,L; bool check(vector<int> &line){ vector<int> c(N, false); for(int i=1; i<N; i++){ if(line[i-1] != line[i]){ int diff = abs(line[i-1] - line[i]); if(diff != 1) return false; if(line[i-1] < line[i]){ for(int j=1; j<=L; j++){ if(i-j<0) return false; if(line[i-1] != line[i-j]) return false; if(c[i-j]) return false; c[i-j] = true; } }else if(line[i-1] > line[i]){ for(int j=0; j<L; j++){ if(i+j >= N) return false; if(line[i] != line[i+j]) return false; if(c[i+j]) return false; c[i+j] = true; } } } } return true; } int main(){ ios::sync_with_stdio(false); cin >> N >> L; vector<vector<int>> in(N, vector<int>(N)); for(int i=0; i<N; i++){ for(int j=0; j<N; j++){ cin >> in[i][j]; } } vector<int> garo; vector<int> sero; int ans = 0; for(int i=0; i<N; i++){ garo.clear(); sero.clear(); for(int j=0; j<N; j++){ garo.push_back(in[i][j]); sero.push_back(in[j][i]); } if(check(garo)) ans += 1; if(check(sero)) ans += 1; } cout << ans; return 0; }
true
a44b8a82cbc893d47d1308a17a32ed90b51bf6c9
C++
1ln/solenoid-testing
/DelayState.cpp
UTF-8
394
2.515625
3
[]
no_license
#include "Arduino.h" #include "DelayState.h" DelayState::DelayState() { _limit = 0; _limit_reached = false; } bool DelayState::wait_interval(unsigned long interval) { if((millis() - _limit) >= interval) { _limit = millis(); //Serial.println("on"); _limit_reached = true; } else { //Serial.println("off"); _limit_reached = false; } return _limit_reached; }
true
24c56d400284c13270c6f11ee86d318386f81f57
C++
MaryChek/Cpp
/White/four_week/Rational/class_Rational_4.cpp
UTF-8
2,993
3.53125
4
[]
no_license
#include <iostream> #include <fstream> #include <sstream> #include <iomanip> # define abs(x) (x > 0) ? x : -x using namespace std; int GetGreatestCommonFactor(int a, int b) { a = abs(a); b = abs(b); while (a > 0 && b > 0){ if (a > b) a %= b; else b %= a; } return a + b; } class Rational { public: Rational() { p = 0; q = 1; } Rational(int numerator, int denominator) { p = numerator; q = Is_ZeroNumerator(denominator); NegativeValueCheck(p, q); GCF = GetGreatestCommonFactor(p, q); } int Numerator() const { return (p != 0) ? (p / GCF) : p; } int Denominator() const { return (p != 0) ? (q / GCF) : q; } private: int p, q, GCF; int Is_ZeroNumerator(int denominator) { return (p == 0) ? 1 : denominator; } void NegativeValueCheck(int& num, int& den) { if ((den < 0 && num > 0) || (num < 0 && den < 0)) { num *= -1; den *= -1; } } }; bool operator==(const Rational& r1, const Rational& r2) { if (r1.Numerator() == r2.Numerator() && r1.Denominator() == r2.Denominator()) return true; return false; } Rational operator+(const Rational& r1, const Rational& r2) { return {r1.Numerator() * r2.Denominator() + r2.Numerator() * r1.Denominator(), r2.Denominator() * r1.Denominator() }; } Rational operator-(const Rational& r1, const Rational& r2) { return { r1.Numerator() * r2.Denominator() - r2.Numerator() * r1.Denominator(), r2.Denominator() * r1.Denominator() }; } Rational operator*(const Rational& r1, const Rational& r2) { return { r1.Numerator() * r2.Numerator(), r1.Denominator() * r2.Denominator() }; } Rational operator/(const Rational& r1, const Rational& r2) { return { r1.Numerator() * r2.Denominator(), r1.Denominator() * r2.Numerator() }; } ostream& operator<<(ostream& stream, const Rational& fractional_num) { return stream << fractional_num.Numerator() << "/" << fractional_num.Denominator(); } istream& operator>>(istream& stream, Rational& fractional_num) { int a, b; char c; stream >> a; stream.ignore(1); stream >> b; if (stream) fractional_num = {a, b}; return stream; } int main() { { ostringstream output; output << Rational(-6, 8); if (output.str() != "-3/4") { cout << "Rational(-6, 8) should be written as \"-3/4\"" << endl; return 1; } } { istringstream input("5/7"); Rational r; input >> r; bool equal = r == Rational(5, 7); if (!equal) { cout << "5/7 is incorrectly read as " << r << endl; return 2; } } { istringstream input("5/7 10/8"); Rational r1, r2; input >> r1 >> r2; bool correct = r1 == Rational(5, 7) && r2 == Rational(5, 4); if (!correct) { cout << "Multiple values are read incorrectly: " << r1 << " " << r2 << endl; return 3; } input >> r1; input >> r2; correct = r1 == Rational(5, 7) && r2 == Rational(5, 4); if (!correct) { cout << "Read from empty stream shouldn't change arguments: " << r1 << " " << r2 << endl; return 4; } } cout << "OK" << endl; return 0; }
true
a26631db70359beef0c11e9d4de0058c1f05f4b5
C++
tbouchik/Araignee
/jeu.h
UTF-8
1,840
2.625
3
[]
no_license
#ifndef JEU_H #define JEU_H #include "piece.h" #include "joueur.h" #include "zonetext.h" #include <string> using namespace std ; class jeu : public QObject //Permet l'intéraction avec l'interface graphique { Q_OBJECT public: explicit jeu(string nom_Joueur1, string nom_Joueur2, QObject *parent = 0) ; Q_INVOKABLE void pilotage(int slot) ; void premiere_Etape(int slot) ; //gère la parti quand les 6 jetons ne sont pas encore mis void seconde_Etape(int slot) ; //gère la suite Q_INVOKABLE QList<QString> readPos() ; //liste des positions utilisées Q_INVOKABLE QList<QString> readBord() ; Q_INVOKABLE QList<bool> readVis() ; Q_PROPERTY(QList<QString> gameQML READ readPos NOTIFY changePos) ; //avec les mains : a chaque fois qu'on appelera depuis une fonction la signal "gameChanged", on appelera la fonction "readPos" (qui rend une Qliste actualisé des positions des jetons) et cette liste sera utilisé par l'interface sous le nom "gameQML" Q_PROPERTY(QList<QString> game2QML READ readBord NOTIFY changeBord) ; Q_PROPERTY(QList<bool> game3QML READ readVis NOTIFY changeVis) ; Q_INVOKABLE int getTour() ; Q_PROPERTY(QString currentText READ currentText NOTIFY changeTexte) ; void victoire() ; bool testVictoire(int *pPos) ; Q_INVOKABLE QString currentText() ; signals: void changePos() ; //signal qui sert à communiquer avec le jeu void changeBord() ; void changeVis() ; void changeTexte() ; public slots: private: int tours_compt ; //compteur des coups déjà faits, afin de savoir dans quelle partie du jeu on est zonetext message ; //objects avec les texts, joueurs et la liste dynamiques des jetons joueur Joueur1, Joueur2 ; piece *pieceListe ; bool victoire_jeu ; } ; #endif // JEU_H
true
dc5fc41aa7ea5e43274aa2c57fe4d931e5192891
C++
namanworld/LeetCode-Solutions-Time-Complexity-Optimized-
/817. Linked List Components.cpp
UTF-8
995
2.9375
3
[]
no_license
class Solution { public: int numComponents(ListNode* head, vector<int>& G) { if(!head) return 0; map<int, bool> seen; for(auto &x:G) seen[x] = true; int count = 0; bool found = false; while(head){ if(seen.count(head->val)>0) { if(!found) count++; found = true; } else if(seen.count(head->val)==0 && found==true){ found = false; } head = head->next; } return count; } }; APPROACH 2: class Solution { public: int numComponents(ListNode* head, vector<int>& G) { if(!head) return 0; set<int> s; for(int x:G) s.insert(x); ListNode* curr = head; int ans = 0; while(curr){ if(s.find(curr->val)!=s.end() && (curr->next==NULL || s.find(curr->next->val)==s.end())) ans++; curr = curr->next; } return ans; } };
true
24e82e209da97df20746d2a24864d35f7eac811c
C++
JakeMDuthie/BREAKOUT
/SRC/LevelLoader.h
UTF-8
594
2.640625
3
[]
no_license
#pragma once // This class contains a .csv parser for taking level data, creating blocks, and returning a vector of those blocks to the play state #include "GameObjects/Blocks.h" #include <vector> // includes for file writing #include <fstream> #include <iostream> struct blockData { float xPos; float yPos; int blockID; }; class LevelLoader { public: LevelLoader(); ~LevelLoader(); std::vector<BaseBlockObject*> LoadLevel(std::string filename); private: bool ParseFile(std::string filename); std::vector<BaseBlockObject*> BuildLevel(); std::vector<blockData> levelBlocks_; };
true
7c7acc5c617f8e8c57204649376173a325874dc9
C++
unflynaomi/algorithms
/3.BruteForceAndExhaustiveSearch/3.1SelectionSort.cpp
WINDOWS-1258
792
3.40625
3
[]
no_license
/*selection sort*/ #include <stdio.h> #include <stdlib.h> #define MAX 100 int main() { FILE *fp; if((fp=fopen("sortdata.txt","r"))==NULL) { printf("Cannot open file !"); exit(1); } int data[MAX]; int size=0; int tmp; int minIndex; while(!feof(fp)) //if it is not end of file { fscanf(fp,"%d",&data[size]); size++; } printf("input data are"); for(int i=0; i<size; i++) printf("%d ",data[i]); printf("\n"); //selection sort begin for(int i=0; i<size-1; i++) //who deserves the i's place in the array { minIndex=i; for(int j=i+1; j<size; j++) if(data[j]<data[minIndex]) minIndex=j; tmp=data[i]; data[i]=data[minIndex]; data[minIndex]=tmp; } printf("after selection sort"); for(int i=0; i<size; i++) printf("%d ",data[i]); fclose(fp); }
true
3e1d2d81da104f4df5f1c8eeb3abfb3a586ad264
C++
luksab/EZbuttonPresses
/EZbuttonPresses.cpp
UTF-8
1,115
2.59375
3
[ "Unlicense" ]
permissive
// ############################################################################# // # // # Scriptname : EZbuttonPresses.cpp // # Author : Lukas Sabatschus // # contact : lukas@luksab.de // # Date : 06.08.2016 // # Description: // # Sourcecode for the EZbuttonPresses Library // # // # Version : 0.1 // ############################################################################# #include "Arduino.h" #include "EZbuttonPresses.h" // ********************************************* // Public functions // ********************************************* EZbuttonPresses::EZbuttonPresses(int * Pins) { numPins=sizeof(Pins); pins = Pins; for(int i=0;i<numPins;i++) { pinMode(pins[i],INPUT_PULLUP); } } void EZbuttonPresses::check(boolean returnValue[]) { for(int i=0;i<numPins;i++) { if(digitalRead(pins[i]) == LOW) { if(pressed[i]) { returnValue[i] = false; } else { returnValue[i] = true; pressed[i] = true; } } else { pressed[i] = false; returnValue[i] = false; } } }
true
5d5e341775701bac81d99ec0dea5baa652e90543
C++
songzhenglian/song_zhenglian
/chap07ex_09/main.cpp
GB18030
1,159
2.90625
3
[]
no_license
a)#include<iostream> #include<array> using namespace const size_t rows=2; const size_t columns=3; void printArray(const array<array<int,columns>,rows>&); int main() { array<array<int,columns>,rows>t1; array<array<int,columns>,rows>t2; cout<<"Values in t1 by row are:"<<endl; printArray(t1); cout<<"\nValues in t2 by row are:"<<endl; printArray(t2); } b)2У c)3У d)6 e)1Уt[1][0],t[1][1],t[1][2]; f)2Уt[0][2], t[1][2], t[2][2]; g)t[1][2]=0; h)t[0][0]=0; t[0][1]=0; t[0][2]=0; t[1][0]=0; t[1][1]=0; t[1][2]=0; i)for(size_t row=0;row<t.size();++row) { for(size_t column=0;column<t[row].size();++column) t[row][column]=0; cout<<t[row][column]<<' '; cout<<endl; } j)for(auto const &row:t) { for(auto const &element:0) cout<<element<<' '; cout<<endl; } k)array<array<int,column>,row>t={Ԫصֵ}; l)int getMinimum()const array<array<int,column>,row>t; cout<<"\nLowest t[row][column] is"<<getMinimum()<<endl; m)cout<<t[1][0]<<' '<<t[1][1]<<' '<<t[1][2]<<endl; n)total=0; for(size_t row=0;row<t.size;++row) total+=t[row][1]; o)
true
b55740b07272c18f238c625f13b50889a358b293
C++
murrdock/contests
/1359/A.cpp
UTF-8
362
2.84375
3
[]
no_license
#include <iostream> #include <cmath> using namespace std; int main() { int t; cin >> t; while(t--) { int n, m, k; cin >> n >> m >> k; int cards = n/k; if(cards >= m) { cout << m << endl; } else { m = m - cards; cout << cards - ceil(double(m)/double(k-1)) << endl; } } return 0; }
true
c0de2e7546a348b5cc1cedc1663f55905e64625e
C++
dronperminov/LandscapeGenerator
/DiamondSquare.h
UTF-8
773
3.109375
3
[]
no_license
#include <iostream> #include <vector> #include <random> #include <ctime> class DiamondSquare { int size; // размер поля (2^n + 1) float R; // параметр для случайной величины float min; // минимальное значение высоты float max; // максимальное значение высоты float maxHeight; std::vector<std::vector<float>> field; float getRnd(float a, float b); float map(float value, float minIn, float maxIn, float minOut, float maxOut); void square(int step); void diamond(int step); void smooth(); void normalize(); public: DiamondSquare(int rows, int cols, float R = 1.0f, float maxHeight = 10); void start(); float operator()(int i, int j) const; int getSize() const; };
true
3f16ff9faa1f202ed8c71cbc7ad73a34f42af011
C++
CSUDHACM/DroneProject
/AutonomousDrone/CoDroneTHings.ino
UTF-8
3,198
2.609375
3
[]
no_license
#include <CoDrone.h> /* * Created by Maria Perez [2017 - 2018] * Modified By: * * Uses COM 7 & Rokit-SmartInventor-mega32_v2 * Sensors currently in use: * 18 = Rise * 14 = Spin widly * 12 = Change color to blue * 11 = Land * 11 + 14 + 18 = Force Stop * * */ unsigned long Timer; // for color void setup() { CoDrone.begin(115200); CoDrone.AutoConnect(NearbyDrone); //connects the drone } void loop() { startUP(); irSensors(); analogStick(); /* if(digitalRead(17)){//goes down [[ IN CONSTRUCTION ]] THROTTLE = -90; delay(250); CoDrone.Control(); } */ ///////////////LED Fun/////////////// [[ in progress ]] /* if(digitalRead(12)){ CoDrone.LedColor(ArmHold, PapayaWhip, 20); /*delay(200); CoDrone.LedColor(ArmDimming, HoneyDew ,20); delay(200); } if(digitalRead(13)){ } if(digitalRead(16)){ CoDrone.LedColor(EyeFlicker, MediumPurple, 20); } if(digitalRead(18)){ }*/ /* for(int i: 255) CoDrone.LedColor(mode, i, 1, 1, 5); for(int i: 255) CoDrone.LedColor(mode, 1, i, 1, 5); for(int i: 255) CoDrone.LedColor(mode, 1, 1, i, 5); for(int i: 255) CoDrone.LedColor(mode, i, 1, 1, 5); if(millis() - setTime){ Serial.print(millis()); Serial.print(": "); if(colorFlag == 0){ Serial.println("Color to Blue"); //coDrone.LedColor(ArmDimming, White, 10); //CoDrone.LedColor(mode, color, time interval); //CoDrone.LedColor(mode, R,G,B, time interval); colorFlag = 1; } else if(colorFlag == 1){ Serial.println("Color to Red"); colorFlag = 0; } setTime = millis(); } */ } void irSensors(){ ///////////////IR SENSORS ON BACK/////////////// if(digitalRead(11)){ //Left Sensor turns on device CoDrone.FlightEvent(Landing); } if(digitalRead(12)){//spins if you hold the 12 sensor for(int i = 0; i < 4; i++){ YAW = 90;//with the speed of 90 delay(250);// 1/4 OF A SECOND } CoDrone.Control(); } if(digitalRead(11) && digitalRead(14) && digitalRead(18)){//emergency off switch CoDrone.FlightEvent(Stop); } } void analogStick(){ ///////////////Analog Stick Part/////////////// if(PAIRING == true){//checks if drone is connected to the controller YAW = -1 * CoDrone.AnalogScaleChange(analogRead(22)); //normally analog read returns a number from 0 ~ 1023 ROLL = -1 * CoDrone.AnalogScaleChange(analogRead(24)); //thevariables YAW,THROTTLE, ETC PITCH = CoDrone.AnalogScaleChange(analogRead(25)); //only accepts numbers from -100~100 THROTTLE = CoDrone.AnalogScaleChange(analogRead(23)); //scale change scales the number down to -100 ~ 100 CoDrone.Control(SEND_INTERVAL); } if(millis() - Timer < 1000){ CoDrone.LedColor(ArmDimming, Cyan, 7); } else if(millis() - Timer < 2000){ CoDrone.LedColor(ArmDimming, Green, 7); } else{ Timer = millis(); } } void startUP(){ ///////////////The Start Up/////////////// if(digitalRead(18)){ //Turns on Drone CoDrone.FlightEvent(TakeOff); delay(250); CoDrone.Control(); //stabilizes } }
true
ac7665fa4736c39a6503caeba12207b6e6f6d2c6
C++
bishoyDHD/museMiniCkr
/src/plugins/MCpropagators/Geant4/detectorlib/include/spline_interp.h
UTF-8
7,774
3.15625
3
[]
no_license
// // Header containing the necessary spline interpolation classes for the magnetic // field interpolation routines (also included some base class material in case // we want to try other interpolation schemes) // // Created March 18, 2013 // // Brian S. Henderson (bhender1@mit.edu) // // Based on the cubic spline routines developed in Chapter 3 of Numerical // Recipes, Third Edition // #include <vector> #include <cmath> // Base structure for interpolation schemes (should we want to add more later) struct ibase { // Various integers needed int n, mm, jsav, cor, dj; // Data point storage const double *xx, *yy; // Constructor for interpolating on table of x and y (each length m) ibase(std::vector<double> &x, const double *y, int m) : n(x.size()), mm(m), jsav(0), cor(0), xx(&x[0]), yy(y) { dj = min(1,(int)pow((double)n,0.25)); } // Alternate constructer ibase(const std::vector<double> &x, const double *y, int m) : n(x.size()), mm(m), jsav(0), cor(0), xx(&x[0]), yy(y) { dj = min(1,(int)pow((double)n,0.25)); } // User output function double interp(double x) { // Call function to decide the grid location int jlo = cor ? hunt(x) : locate(x); return rawinterp(jlo,x); } // Grid location functions (uncorrelated and correlated) int locate (const double x); int hunt(const double x); // Virtual placeholder for the interpolation provided by the derived spline class double virtual rawinterp(int jlo, double x) = 0; }; // Base grid location function int ibase::locate(const double x) { int ju, jm, jl; // Temporary indices // Check to make sure the provided data is sane if (n<2 || mm<2 || mm > n) throw("\n\nData provided to locate is poorly sized!\n\n"); // Check to see if the data is in ascending order (true if yes) bool ascnd = (xx[n-1] >= xx[0]); // Initialize the upper and lower limits jl = 0; ju = n-1; // Bisect to find the right index while (ju-jl > 1) { // Compute the midpoint jm = (ju+jl) >> 1; // Adjust the right index if ((x >= xx[jm]) == ascnd) jl = jm; else ju = jm; } // See if it is worth using the hunt function next time cor = (abs((double) (jl-jsav)) > dj) ? 0 : 1; // Save the most recent lower bound index jsav = jl; // Return the index return max(0,min(n-mm,jl-((mm-2)>>1))); }; // A function that speeds up the grid bisection when subsequent points are close // together int ibase::hunt(const double x) { // Load the saved lower bound into the current lower bound int jl = jsav; // Declare the various integers needed int jm, ju, inc = 1; // Check to see if the data is in ascending order (true if yes) bool ascnd = (xx[n-1] >= xx[0]); // Check to see if the given indices are bad, if so skip to bijection if (jl<0 || jl>(n-1)) {jl = 0; ju = n-1;} // Else, do the hunt scan else { // Hunt upward in indices if ascending order if ((x >= xx[jl]) == ascnd) { for(;;) { // Set the upper index by the increment ju = jl + inc; // Check to make sure you haven't run off the list if (ju >= n-1) {ju = n-1; break;} // See if you have found the right index range else if ((x < xx[ju]) == ascnd) break; // If not, up the increment by a factor of two and loop else { jl = ju; inc += inc; } } } // Hunt downward if not ascending order else { // Reset the upper bound ju = jl; // Do the hunt down in the same fashion as above for(;;) { // Set the lower index by the increment jl = ju - inc; // Check to make sure you haven't run off the list if (jl <= 0) {jl = 0; break;} // See if you have found the right index range else if ((x >= xx[jl]) == ascnd) break; // If not, up the increment by a factor of two and loop else { ju = jl; inc += inc; } } } } // Now finish by bisecting while (ju-jl > 1) { // Compute the midpoint jm = (ju+jl) >> 1; // Adjust the right index if ((x >= xx[jm]) == ascnd) jl = jm; else ju = jm; } // See if it is worth using the hunt function next time cor = (abs((double) (jl-jsav)) > dj) ? 0 : 1; // Save the most recent lower bound index jsav = jl; // Return the index return max(0,min(n-mm,jl-((mm-2)>>1))); }; // Base 1D spline interpolation structure struct spline1D : ibase { std::vector<double> y2; // Vector of the second derivatives of the data // Constructor for 1D interpolation spline1D(std::vector<double> &xv, std::vector<double> &yv) : ibase(xv,&yv[0],2), y2(xv.size()) { sety2(&xv[0],&yv[0]); } // Constructors for 2D interpolation spline1D(std::vector<double> &xv, const double *yv) : ibase(xv,yv,2), y2(xv.size()) { sety2(&xv[0],yv); } // Constructor for 1D interpolation spline1D(const std::vector<double> &xv, std::vector<double> &yv) : ibase(xv,&yv[0],2), y2(xv.size()) { sety2(&xv[0],&yv[0]); } // Function to compute and store the second derivatives of the data void sety2(const double *xv, const double *yv); // Function that does the interpolation double rawinterp(int jl, double xv); }; // Function to compute the derivatives needed for the spline interpoloatoin void spline1D::sety2(const double *xv, const double *yv) { // Various doubles needed double p, qn, sig, un; // Get the size of the vectors involved int n = y2.size(); // Temporary storage vector std::vector<double> u(n-1); // Set "natural" spline boundary conditions (first and second derivatives // zero at endpoints) y2[0] = 0; qn = 0; u[0] = 0; un = 0; // Tridiagonal second derivative algorithm (see Numerical Recipes) for (int i = 1; i<(n-1); i++) { sig = (xv[i]-xv[i-1])/(xv[i+1]-xv[i-1]); p = sig*y2[i-1]+2; y2[i] = (sig-1)/p; u[i] = (yv[i+1]-yv[i])/(xv[i+1]-xv[i]) - (yv[i]-yv[i-1])/(xv[i]-xv[i-1]); u[i] = (6*u[i]/(xv[i+1]-xv[i-1])-sig*u[i-1])/p; } // Fill the second derivative vector by back-substitution for (int k = n-2; k >= 0; k--) { y2[k] = y2[k]*y2[k+1]+u[k]; } } // 1D Spline Interpolator using standard cubic spline formula double spline1D::rawinterp(int jl, double x) { int klo = jl, khi =jl+1; // Set the bounding indices double y, h, b, a; // Difference along the x vector h = xx[khi]-xx[klo]; if (h==0) throw("\n\nProvided points are at same x value!\n\n"); // Fractions along intervals of desired point a = (xx[khi]-x)/h; b = (x-xx[klo])/h; // Cubic spline formula y = a*yy[klo] + b*yy[khi] + ((a*a*a-a)-y2[klo] + (b*b*b-b)*y2[khi])*h*h/6; // Return the interpolated value return y; } // 2D Spline Interpolator (bicubic) struct spline2D { int m, n; // Dimensions of data // Matrix for storage of output values const std::vector< std::vector<double> > &y; // Placeholder vectors const std::vector<double> &x1; std::vector<double> yv; // Vector of 1D interpolations along the rows std::vector<spline1D*> srp; // Constructor spline2D(std::vector<double> &x1v, std::vector<double> &x2v, std::vector< std::vector<double> > &ym) : m(x1v.size()), n(x2v.size()), y(ym), yv(m), x1(x1v), srp(m) { // Yo dawg, I heard you like splines...so I put a spline in each row of your 2D data for (int i=0; i<m; i++) srp[i] = new spline1D(x2v,&y[i][0]); } // Destructor to take care of 1D spline pointers ~spline2D() {for (int i=0; i<m; i++) delete srp[i];} // Interpolation function double interp(double x1p, double x2p) { // Interpolate at x2p in every row for (int i=0; i<m; i++) yv[i] = (*srp[i]).interp(x2p); // Interpolate on the interpolation spline1D scol(x1,yv); return scol.interp(x1p); } }; // Final 3D spline struct spline3D { // Setup a 2D spline for each plane }; // Toy function to compute values for testing of the interpolation double toytest(double x, double y = 0) { double q = x*y+x*x*y*y*y-3*x-2*y*y*y*y; return q; }
true
746ee93914482bdd98e00bea1b54764b41d43605
C++
Eric-Ma-C/PAT-Advanced
/Advanced/AA1024/main/main.cpp
GB18030
1,632
3.25
3
[ "MIT" ]
permissive
#include<stdio.h> #include<stdlib.h> #include<algorithm> int num[25]; //180min typedef struct node{ int val,height; node *left,*right; }node; node* newnode(int v){ node* n=(node*)malloc(sizeof(node)); n->height=1; n->val=v; n->left=NULL; n->right=NULL; return n; } int geth(node *&root){ if(root==NULL) return 0; return root->height; } void updateH(node *&root){ root->height=std::max(geth(root->left),geth(root->right))+1; } int getBanFac(node *&n){ if(n==NULL) return 0; return geth(n->left)-geth(n->right); } void left(node *&root){// node *tmp=root->right; root->right=tmp->left; tmp->left=root; updateH(root);//ȸ updateH(tmp);//ٸ root=tmp; } void right(node *&root){// node *tmp=root->left; root->left=tmp->right; tmp->right=root; updateH(root);//ȸ updateH(tmp);//ٸ root=tmp; } void insertn(node *&n,int v){ if(n==NULL){ n=newnode(v); return; } if(n->val>v){ insertn(n->left,v); updateH(n); int fac1=getBanFac(n); int fac2=getBanFac(n->left); if(fac1==2){ if(fac2==1){//LL right(n); }else if(fac2==-1){//LR left(n->left); right(n); } } }else{ insertn(n->right,v); updateH(n); int fac1=getBanFac(n); int fac2=getBanFac(n->right); if(fac1==-2){ if(fac2==-1){//RR left(n); }else if(fac2==1){//RL right(n->right); left(n); } } } } int main(){ int t; scanf("%d",&t); for(int i=0;i<t;i++){ scanf("%d",num+i); } node* root=NULL; for(int i=0;i<t;i++){ insertn(root,num[i]); } printf("%d",root->val); getchar(); getchar(); return 0; }
true
0f61796fc73b3c4ce317ca353943fd18004af5b0
C++
preun/DirectX
/AStar/AStar.cpp
UHC
6,856
2.625
3
[]
no_license
#include "../../stdafx.h" #include "AStar.h" #include "PathFind.h" #include "Cell.h" AStar::AStar() { } AStar::~AStar() { } void AStar::SetCurrentCell(vector<D3DXVECTOR3> Vertex) { m_pPathFind = new PathFind; m_pPathFind->Setup(Vertex); m_vCurrentCell = m_pPathFind->GetNaviCell(); } void AStar::SetCell(int MyCellIndex, int TargetIndex) { //⺻ ʱȭ ܰ //ؿ Ӽ ϴ° ǵ۾ for (int i = 0; i < m_vCurrentCell.size(); i++) { m_vCurrentCell[i]->ZeroReset(); } /* Ȯο ּ SYNTHESIZE(float, m_fTotalCost, TotalCost); //ۺ ڽƮ SYNTHESIZE(float, m_fCostFromStart, CostFromStart); //ۺ ڽƮ SYNTHESIZE(float, m_fCostToGoal, CostToGal); // Ÿ Ÿ SYNTHESIZE(Cell*, m_pParentCell, ParentCell); // ִ Ÿ̳ SYNTHESIZE(bool, m_bIsOpen, IsOpen); */ //Ƶ Ŭ ϰ ٽ ´. m_vTotalList.clear(); m_vOpenList.clear(); m_vCloseList.clear(); //Ÿ //m_pStartCell = m_vCurrentCell[0]; m_pStartCell = m_vCurrentCell[MyCellIndex]; m_pStartCell->SetAttribute("start"); //Ÿ //m_pEndCell = m_vCurrentCell[m_vCurrentCell.size() - 1]; m_pEndCell = m_vCurrentCell[TargetIndex]; m_pEndCell->SetAttribute("end"); // m_pCurrentCell = m_pStartCell; for (int i = 0; i < m_vCurrentCell.size(); i++) { //߿ ε ڷ ޾Ƽ ŸƮ //if (i == 0) //if (i == MyCellIndex) //{ // //m_vCurrentCell[i]->SetAttribute("start"); // m_vTotalList.push_back(m_vCurrentCell[i]); //} ////ϴ //else if (i == m_vCurrentCell.size() - 1) //{ // //m_vCurrentCell[i]->SetAttribute("end"); // m_vTotalList.push_back(m_vCurrentCell[i]); //} //// ־ش //else //{ m_vTotalList.push_back(m_vCurrentCell[i]); //} } } vector<Cell*> AStar::addOpenList(Cell* currentCell) { //ﰢ ϳ ﰢ 3̹Ƿ for (int i = 0; i < 3; i++) { // ﰢ ٸ Ѿ if (!currentCell->GetNeighborCell()[i]) continue; // ﰢ ִٸ ϴ ݵ Cell* tempCell = currentCell->GetNeighborCell()[i]; // , , Ÿ Ѵ. if (!tempCell->GetIsOpen()) continue; if (tempCell->GetAttribute() == "start") continue; if (tempCell->GetAttribute() == "wall") continue; // ̴. tempCell->SetParentCell(m_pCurrentCell); //üũ Ұ bool addCell = true; for (m_viOpenList = m_vOpenList.begin(); m_viOpenList != m_vOpenList.end(); ++m_viOpenList) { // üũ ִ ߺ ʴ´ if (*m_viOpenList == tempCell) { addCell = false; break; } } //̹ ¸Ʈ  Ƽ if (!addCell) continue; m_vOpenList.push_back(tempCell); } return m_vOpenList; } void AStar::pathFinder(Cell* currentCell) { float tempTotalCost = 5000; Cell* tempCell = NULL; for (int i = 0; i < addOpenList(currentCell).size(); ++i) { /* Ʈ ִ° deltax = (ǥ.x - .x) deltay = (ǥ.y - .y) deltaz = (ǥ.z - .z) max(max(deltax, deltay), deltaz) ϴ */ //ǥ - D3DXVECTOR3 tempVec; tempVec = m_pEndCell->GetCenter() - m_vOpenList[i]->GetCenter(); m_vOpenList[i]->SetCostToGal( D3DXVec3Length(&tempVec) ); D3DXVECTOR3 center1 = m_vOpenList[i]->GetParentCell()->GetCenter(); D3DXVECTOR3 center2 = m_vOpenList[i]->GetCenter(); m_vOpenList[i]->SetCostFromStart( D3DXVec3Length(&(center1 - center2))); m_vOpenList[i]->SetTotalCost(m_vOpenList[i]->GetCostToGal() + m_vOpenList[i]->GetCostFromStart()); if (tempTotalCost > m_vOpenList[i]->GetTotalCost()) { tempTotalCost = m_vOpenList[i]->GetTotalCost(); tempCell = m_vOpenList[i]; } //ߺ bool addObj = true; for (m_viOpenList = m_vOpenList.begin(); m_viOpenList != m_vOpenList.end(); ++m_viOpenList) { if (*m_viOpenList == tempCell) { addObj = false; break; } } //˻ Ϸ m_vOpenList[i]->SetIsOpen(false); if (!addObj) continue; m_vOpenList.push_back(tempCell); } if (tempCell->GetAttribute() == "end") { while (m_pCurrentCell->GetParentCell() != NULL) { m_pCurrentCell = m_pCurrentCell->GetParentCell(); } return; } m_vCloseList.push_back(tempCell); //_vDibugList.push_back(tempTile); for (m_viOpenList = m_vOpenList.begin(); m_viOpenList != m_vOpenList.end(); ++m_viOpenList) { if (*m_viOpenList == tempCell) { m_viOpenList = m_vOpenList.erase(m_viOpenList); break; } } m_pCurrentCell = tempCell; pathFinder(m_pCurrentCell); } D3DXVECTOR3 AStar::GetNextCell(OUT vector<D3DXVECTOR3>* path) { if (!DEBUG) path->clear(); if (m_pStartCell == m_pEndCell) { if (!DEBUG) (*path).push_back(D3DXVECTOR3(-1, -1, -1)); return D3DXVECTOR3(-1, -1, -1); } pathFinder(m_pCurrentCell); if (m_vCloseList.size() <= 0) { if(!DEBUG) (*path).push_back(D3DXVECTOR3(-1, -1, -1)); return D3DXVECTOR3(-1, -1, -1); } if (!DEBUG) { //path->resize(m_vCloseList.size()); for (int i = 0; i<m_vCloseList.size(); ++i) { (*path).push_back( m_vCloseList[i]->GetCenter()); } (*path).push_back(D3DXVECTOR3(-1, -1, -1)); } return m_vCloseList[0]->GetCenter(); } int AStar::GetCellIndex(D3DXVECTOR3 pos) { return m_pPathFind->GetCellIndex(pos); } void AStar::Render(int MyCellIndex, int TargetIndex, D3DXVECTOR3* pos) { if (DEBUG) { SetCell(MyCellIndex, TargetIndex); GetNextCell(NULL); vector<D3DXVECTOR3> tempVector; tempVector.push_back(D3DXVECTOR3(m_vCurrentCell[MyCellIndex]->GetCenter().x, m_vCurrentCell[MyCellIndex]->GetCenter().y + 2 , m_vCurrentCell[MyCellIndex]->GetCenter().z)); for (int i = 0; i < m_vCloseList.size(); i++) { tempVector.push_back(D3DXVECTOR3(m_vCloseList[i]->GetCenter().x, m_vCloseList[i]->GetCenter().y+2, m_vCloseList[i]->GetCenter().z)); } tempVector.push_back(D3DXVECTOR3((*pos).x, (*pos).y+2, (*pos).z)); tempVector.push_back(D3DXVECTOR3((*pos).x, (*pos).y+2, (*pos).z)); tempVector.push_back(D3DXVECTOR3((*pos).x, (*pos).y+2, (*pos).z)); D3DXMATRIX matW; D3DXMatrixIdentity(&matW); DEVICE->SetTransform(D3DTS_WORLD, &matW); //DEVICE->SetRenderState(D3DRS_FILLMODE, D3DFILL_WIREFRAME); DEVICE->SetTexture(0, NULL); DEVICE->DrawPrimitiveUP(D3DPT_LINESTRIP, // ﰢ tempVector.size()-2, //ù ּ &tempVector[0], //ũ sizeof(D3DXVECTOR3)); } }
true
6a4e853b65ea02b535572d8cbddae111a4858594
C++
manouti/c-shell
/Guolice/include/Node.h
UTF-8
6,531
2.953125
3
[]
no_license
/** \file Node.h * Node Class * */ #ifndef NODE_H #define NODE_H #include <string> #include <vector> #include <AbstractGui.h> #include <map> #include <GuiCompare.h> #include <Solution.h> using namespace std; /** * \class Node * \brief Node Strunture of Graph * information: nodeType, dataType and value * */ class Node { public: enum NodeType { VAR, CONST, OP }; // Define the possible node types. /** * \brief Node() construnctor * \param none */ Node(); /** * \brief Node() constuctor intiates a node with string value * \param string v: value of node to be created */ Node(string v); /** * \brief Node() constructor: intiates a node with value and data type * \param string v: value of node to be created * \param string dType: data type */ Node(string v, string dType); /** * \brief Node() constructor: intiates a node with parent node * \param Node* node: parent Node */ Node(Node* node); //~Node(void); /** * \brief getValue() returns value set * \param none *\return string: value */ string getValue() const; /** * \brief setValue() setsValue * \param string v: value of Node *\return void */ void setValue(string v); /** * \brief setValue() setsValue * \param NodeType type: enum NodeType *\return void */ void setType(NodeType type); /** * \brief getType() returns type * \param none *\return NodeType: returns enum NodeType */ NodeType getType() const; /** * \brief setDataType() sets the Data Tyoe * \param string dType *\return void */ void setDataType(string dType); /** * \brief getDataType() returns data type * \param none *\return string: return data type */ string getDataType(); /** * \brief getChildren() returns vector of children * \param none *\return vector<Node*> returns a vector of Node pointers */ vector<Node*> getChildren() const; /** * \brief setChildren() sets Children * \param vector<Node*> vector of nodes *\return void */ void setChildren(vector<Node*> c); /** * \brief getParent() returns parent Node * \param none *\return Node* : a pointer to the parent Node */ Node* getParent() const; /** * \brief setParent() sets Parent * \param Node *: parent node *\return void */ void setParent(Node* p); /** * \brief addChild() add child to node * \param Node* child: pointer of child node *\return void */ void addChild(Node* child); /** * \brief addChild() add child to node with weight used for translation * \param Node* child: pointer of child node * \param string : weight of edge *\return void */ void addChild(Node* child, string weight); /** * \brief getChildrenWeight() gets the childrenWeight at i * \param int : child number *\return string: weight of child */ string getChildrenWeight(int i); /** * \brief printChildren() returns the children in string format * \param none *\return string */ string printChildren() const; /** * \brief toString() prints the node in string format: value, all children * \param none *\return string */ string toString() const; /** * \brief sets Node as visited * \param none *\return void */ void setVisited(); /** * \brief isVisited returns true if node has been visisted in traversal * \param none *\return boolean - true if visited */ bool isVisited(); string getMode() const; void setMode(string m); vector<vector<Solution> > getNodeSolution() const; void SetNodeSolution(vector<vector<Solution> > m); vector<vector<Solution> > evaluate(map<string, vector<AbstractGui*> > guiObject); private: string value; //!< The text value of the node. vector<Node*> children; //!< Vector of children of the node. vector<string> childrenWeight; //!< Weight coresponding to edge between node and child Node* parent; //!< Parent of the node. NodeType type; //!< Type of the node (VAR, CONST, OP). string dataType; //!< Data type of node(INT, STRING, BOOL, BOX, CIRCLE, TRIANGLE, LABEL). bool visited; //!< boolean true if visited string mode; //!< Mode of the node (Box, Circle, Triangle, Label). vector<vector<Solution> > nodeSolution; //!< contain the solution of the node }; #endif
true
415a0752ca6ff5d6c6a12e9a51826f0c8927775c
C++
ccappelle/PotatoProject
/synapse.cpp
UTF-8
1,293
2.84375
3
[]
no_license
#ifndef _SYNAPSE_CPP #define _SYNAPSE_CPP #include "iostream" #include "cmath" #include "synapse.h" SYNAPSE::SYNAPSE(void) { std::cin >> sourceNeuronIndex; std::cin >> targetNeuronIndex; std::cin >> start_weight; std::cin >> end_weight; std::cin >> start_time; std::cin >> end_time; weight = start_weight; weight_incr = 0.f; if (end_time-start_time<= 0){ weight_incr = 0.f; } else{ weight_incr = (end_weight-start_weight)/double(end_time-start_time); } } SYNAPSE::~SYNAPSE(void) { } int SYNAPSE::Get_Source_Neuron_Index(void) { return sourceNeuronIndex; } int SYNAPSE::Get_Target_Neuron_Index(void) { return targetNeuronIndex; } double SYNAPSE::Get_Weight(void) { return weight; } void SYNAPSE::Update_Weight(int t){ if (t>=start_time && t<end_time){ weight = weight + weight_incr; if (isnan(weight)){ std::cerr << " weight is nan "; } } } void SYNAPSE::Print(void) { std::cerr << sourceNeuronIndex << " "; std::cerr << targetNeuronIndex << " "; std::cerr << start_weight << " "; std::cerr << end_weight << " "; std::cerr << start_time << " "; std::cerr << end_time << "\n"; } #endif
true
f46d979dd414e51e49054bb783be8d4097825bd0
C++
cristianvanherp/game_engine_1
/game_engine_1/game_engine_1/Ambient.cpp
UTF-8
1,094
2.859375
3
[]
no_license
#include "Ambient.h" #include <cstdlib> Ambient::Ambient(ShaderProgram *shaderProgram) { this->shaderProgram = shaderProgram; this->camera = new Camera(); this->objects = std::vector<Object*>(); this->lightSources = std::vector<LightSource*>(); } Ambient::~Ambient() { } void Ambient::add_object(Object *object) { this->objects.push_back(object); } void Ambient::add_light_source(LightSource *lightSource) { this->add_object((Object*)lightSource); this->lightSources.push_back(lightSource); } void Ambient::draw() { for (std::vector<LightSource*>::iterator i = this->lightSources.begin(); i != this->lightSources.end(); ++i) { this->shaderProgram->use(); glUniform3fv(glGetUniformLocation(this->shaderProgram->ID, "lightPos"), 1, glm::value_ptr((*i)->translation)); glUniform3fv(glGetUniformLocation(this->shaderProgram->ID, "lightColor"), 1, glm::value_ptr((*i)->lightColor)); } for (std::vector<Object*>::iterator i = this->objects.begin(); i != this->objects.end(); ++i) { (*i)->render(this->shaderProgram, this->camera); } }
true
5c29f65baff51a93208da6ccbd4324f786eea9db
C++
marrod87/tecnologo
/PA/ob5/DateTime.cpp
UTF-8
10,222
3.8125
4
[]
no_license
#include "DateTime.h" using namespace std; // Constructores // Instancia DateTime con fecha y hora del sistema; DateTime::DateTime(){ time_t t; struct tm * now; t = time(NULL); now = localtime (&t); y = now->tm_year + 1900; m = now->tm_mon + 1; d = now->tm_mday; h = now->tm_hour; i = now->tm_min; } // ESTATICA: DateTime d(2014,3,28,15,10); // DINAMICA: DateTime d = new DateTime(2014,3,28,15,10); DateTime::DateTime(int yy, int mm, int dd, int hh, int ii){ if (yy < 0 || mm < 0 || dd < 0 || hh < 0 || ii < 0) throw invalid_argument("ERROR - La fecha no acepta valores negativos."); else if (mm > 12 || dd > obtenerMaximoDiaDelMes(mm, yy)) throw invalid_argument("ERROR - El mes o los dias son invalidos."); else if (hh > 24 || ii > 60) throw invalid_argument("ERROR - La hora o los minutos son invalidos."); else{ y = yy; m = mm; d = dd; h = hh; i = ii; } } // Instancia por copia DateTime::DateTime(const DateTime &dt){ y = dt.getAnio(); m = dt.getMes(); d = dt.getDia(); h = dt.getHora(); i = dt.getMinuto(); } // Destructor DateTime::~DateTime(){} // Selectores int DateTime::getAnio () const{ return y; } int DateTime::getMes () const{ return m; } int DateTime::getDia () const{ return d; } int DateTime::getHora () const{ return h; } int DateTime::getMinuto () const{ return i; } // Modificadores void DateTime::setAnio(int yy){ if (yy < 0) throw invalid_argument("ERROR - La fecha no acepta valores negativos."); else y = yy; } void DateTime::setMes(int mm){ if (mm < 0) throw invalid_argument("ERROR - La fecha no acepta valores negativos."); else if (mm < 1 || mm > 12) throw invalid_argument("ERROR - El mes tiene que ser un numero entre 1 y 12."); else m = mm; } void DateTime::setDia(int dd){ if (dd < 0) throw invalid_argument("ERROR - La fecha no acepta valores negativos."); else if(dd > obtenerMaximoDiaDelMes(this->getMes(),this->getAnio())) throw invalid_argument("ERROR - El mes no contiene esos dias"); else d = dd; } void DateTime::setHora(int hh){ if (hh < 0) throw invalid_argument("ERROR - La fecha no acepta valores negativos."); else if(hh > 23) throw invalid_argument("ERROR - La hora no puede ser mayor a 23"); else h = hh; } void DateTime::setMinuto(int ii){ if (ii < 0) throw invalid_argument("ERROR - La fecha no acepta valores negativos."); else if(ii > 59) throw invalid_argument("ERROR - Los minutos no pueden ser mayor de 59"); else i = ii; } void DateTime::printComp(Comparable * c){ DateTime *a = dynamic_cast<DateTime *>(c); cout << (*a) << endl; } //Operacion abstracta de Comparable int DateTime::comparar(Comparable *c){ DateTime *a = dynamic_cast<DateTime *>(c); if((*this) == (*a)) return 0; else if((*this) < (*a)) return -1; else if ((*this) > (*a)) return 1; return -2; } // Operaciones bool DateTime::operator == (DateTime dt){ return (this->getAnio()==dt.getAnio() && this->getMes()==dt.getMes() && this->getDia()==dt.getDia() && this->getHora()==dt.getHora() && this->getMinuto()==dt.getMinuto()); } bool DateTime::operator != (DateTime dt){ return (this->getAnio()!=dt.getAnio() || this->getMes()!=dt.getMes() || this->getDia()!=dt.getDia() || this->getHora()!=dt.getHora() || this->getMinuto()!=dt.getMinuto()); } bool DateTime::operator < (DateTime dt){ if(this->getAnio() < dt.getAnio()) return true; else if (this->getAnio() == dt.getAnio()){ if(this->getMes()< dt.getMes()) return true; else if(this->getMes() == dt.getMes()){ if (this->getDia() < dt.getDia()) return true; else if (this->getDia() == dt.getDia()){ if (this->getHora() < dt.getHora()) return true; else if (this->getHora() == dt.getHora()) return this->getMinuto() < dt.getMinuto(); } } } return false; } bool DateTime::operator > (DateTime dt){ return (dt < *this); } bool DateTime::operator <= (DateTime dt){ return (*this == dt || *this < dt); } bool DateTime::operator >= (DateTime dt){ return (*this == dt || *this > dt); } int* obtenerDiaHoraMinutoDesdeNumero(double d){ int* res = new int [3]; int dias = (int)d; double decimalValFact = d-(double)dias; //calculos minutos totales double mFact = decimalValFact*24*60; //calculo de la cantidad de horas int hora = mFact/60; //calulo de la cantidad de minutos restantes que no completan la hora res[0] = dias; res[1] = hora; res[2] = round((mFact/60-(double)hora)*60); return res; } //calculo del anio biciesto segun algoritmo bool DateTime::esBiciesto(int anio){ return (anio % 4 == 0 && ( anio % 100 != 0 || anio % 400 == 0 )); } int DateTime::obtenerMaximoDiaDelMes(int mes, int anio){ if(mes == 2) return (esBiciesto(anio)) ? 29 : 28; else{ if(mes<8) return (mes % 2 == 0) ? 30 : 31; else return (mes % 2 == 0) ? 31 : 30; } } DateTime DateTime::operator + (double d){ int maxDias = obtenerMaximoDiaDelMes(this->getMes(),this->getAnio()); int* listaDeValoresSegunDecimal= obtenerDiaHoraMinutoDesdeNumero(d); int anio = this->getAnio(); int mes = this->getMes(); //guardo en dia ya la suma de los dias que tengo con los que voy a agregar int dia = this->getDia()+listaDeValoresSegunDecimal[0]; //guardo en hora ya la suma de las horas que tengo con las que voy a agregar int hora = this->getHora()+listaDeValoresSegunDecimal[1]; //guardo en minuto ya la suma de los minutos que tengo con los que voy a agregar int minuto = this->getMinuto() + listaDeValoresSegunDecimal[2]; double diffDeDias = 0; // me fijo en el rango de minutos para saber si no agrego horas // repito el algoritmo de manera analoga para horas y dias if(minuto >= 60){ int horasParaAgregar = (int)(minuto / 60); minuto = minuto-(60*horasParaAgregar); hora += horasParaAgregar; } if(hora >= 24){ int diasParaAgregar = (int)(hora / 24); hora = hora-(24*diasParaAgregar); dia += diasParaAgregar; } if(dia > maxDias){ diffDeDias = dia-maxDias-1; dia = 1; mes++; } if(mes > 12){ mes = 1; anio++; } DateTime resultado (anio,mes,dia,hora,minuto); if(diffDeDias>0){ resultado = ((resultado) + diffDeDias); } return (resultado); } DateTime& DateTime::operator = (const DateTime& d){ this->setMinuto(d.getMinuto()); this->setHora(d.getHora()); this->setDia(d.getDia()); this->setMes(d.getMes()); this->setAnio(d.getAnio()); return (*this); } DateTime DateTime::operator - (double d){ int* listaDeValoresSegunDecimal= obtenerDiaHoraMinutoDesdeNumero(d); int anio = this->getAnio(); int mes = this->getMes(); //guardo en dia ya la suma de los dias que tengo con los que voy a agregar int dia = this->getDia()-listaDeValoresSegunDecimal[0]; //guardo en hora ya la suma de las horas que tengo con las que voy a agregar int hora = this->getHora()-listaDeValoresSegunDecimal[1]; //guardo en minuto ya la suma de los minutos que tengo con los que voy a agregar int minuto = this->getMinuto() - listaDeValoresSegunDecimal[2]; double diffDeDias = 0; // me fijo en el rango de minutos para saber si no agrego horas if( minuto < 0){ int horasParaQuitar = (int)(minuto / 60); minuto = (int)(60+minuto); hora -= horasParaQuitar; } if(hora < 0){ int diasParaQuitar= (int)(hora / 24); hora = (int)(24+hora); dia --; } if(dia < 1){ int prevMes = (this->getMes()==1)?12:this->getMes()-1; int lastDayOfPrevMonth = obtenerMaximoDiaDelMes(prevMes,this->getAnio()); diffDeDias = dia; dia = lastDayOfPrevMonth; mes--; } if(mes < 1){ mes = 12; anio--; } DateTime resultado (anio,mes,dia,hora,minuto); if(diffDeDias<0){ resultado = ((resultado) - -diffDeDias); } return (resultado); } double DateTime::operator - (DateTime d){ //if the DateTime are equals the difference between them if(this->getAnio() == d.getAnio() && this->getMes() == d.getMes() && this->getDia() == d.getDia())return 0; DateTime start; DateTime end; if((*this) > d){ start = d; end = (*this); }else{ end = d; start = (*this); } if(end.getAnio() == start.getAnio()){ int daysDiff = 0 ; if(start.getMes()!=end.getMes()){ int currentMonth = start.getMes()+1; while(currentMonth != end.getMes()){ daysDiff += DateTime::obtenerMaximoDiaDelMes(currentMonth,start.getAnio()); currentMonth++; } int dayDiffToEndMonth = DateTime::obtenerMaximoDiaDelMes(start.getMes(),start.getAnio())-start.getDia(); daysDiff += dayDiffToEndMonth + end.getDia(); return daysDiff; }else{ daysDiff += end.getDia()-start.getDia(); return daysDiff; } }else{ int daysDiff = 0 ; int currentMonth = start.getMes()+1; while(currentMonth <= 12){ daysDiff += DateTime::obtenerMaximoDiaDelMes(currentMonth,start.getAnio()); currentMonth++; } currentMonth = 1; while(currentMonth != end.getMes()){ daysDiff += DateTime::obtenerMaximoDiaDelMes(currentMonth,end.getAnio()); currentMonth++; } int dayDiffToEndMonth = DateTime::obtenerMaximoDiaDelMes(start.getMes(),start.getAnio())-start.getDia(); daysDiff += dayDiffToEndMonth+end.getDia(); int currentYear = start.getAnio()+1; while(currentYear != end.getAnio()){ daysDiff += (DateTime::esBiciesto(currentYear))? 366 : 365 ; currentYear++; } return daysDiff; } } std::ostream& operator<< (std::ostream& stream, const DateTime& d) { const char* pref1 = "0"; return cout << d.getAnio() << "/" << ((d.getMes() < 10) ? pref1 : "") << d.getMes() << "/" << ((d.getDia() < 10) ? pref1 : "") << d.getDia() << " " << ((d.getHora() < 10)? pref1 : "") << d.getHora() << ":" << ((d.getMinuto() < 10) ? pref1 : "") << d.getMinuto() << endl; } // std::istream& operator>> (std::istream& input,DateTime& o){ // int anio,dia,mes,hora,minuto; // cout<<"Ingrese Año: "<<endl; // input>>anio; // cout<<"Ingrese Mes: "<<endl; // input>>mes; // cout<<"Ingrese Dia: "<<endl; // input>>dia; // cout<<"Ingrese Hora: "<<endl; // input>>hora; // cout<<"Ingrese Minuto: "<<endl; // input>>minuto; // o.setAnio(anio); // o.setMes(mes); // o.setDia(dia); // o.setHora(hora); // o.setMinuto(minuto); // return input; // }
true
7c1224d4314d70203966bb45da3027e3de15e168
C++
dv1990/hexabus
/hostsoftware/libhexabus/libhexabus/serialization.cpp
UTF-8
14,093
2.65625
3
[]
no_license
#include <libhexabus/private/serialization.hpp> #include <stdexcept> #include <algorithm> #include <arpa/inet.h> #include "crc.hpp" #include "error.hpp" #include "../../../shared/hexabus_definitions.h" using namespace hexabus; // {{{ Binary serialization visitor class BinarySerializer : public PacketVisitor { private: std::vector<char>& _target; size_t _headerStart; void append_u8(uint8_t value); void append_u16(uint16_t value); void append_u32(uint32_t value); void append_float(float value); void appendHeader(const Packet& packet); void appendEIDHeader(const EIDPacket& packet); void appendValueHeader(const TypedPacket& packet); void appendValue(const ValuePacket<bool>& value); void appendValue(const ValuePacket<uint8_t>& value); void appendValue(const ValuePacket<uint32_t>& value); void appendValue(const ValuePacket<float>& value); void appendValue(const ValuePacket<boost::posix_time::ptime>& value); void appendValue(const ValuePacket<boost::posix_time::time_duration>& value); void appendValue(const ValuePacket<std::string>& value); void appendValue(const ValuePacket<boost::array<char, 65> >& value); void appendValue(const ValuePacket<boost::array<char, 16> >& value); void appendCRC(); public: BinarySerializer(std::vector<char>& target); virtual void visit(const ErrorPacket& error); virtual void visit(const QueryPacket& query); virtual void visit(const EndpointQueryPacket& endpointQuery); virtual void visit(const EndpointInfoPacket& endpointInfo); virtual void visit(const InfoPacket<bool>& info); virtual void visit(const InfoPacket<uint8_t>& info); virtual void visit(const InfoPacket<uint32_t>& info); virtual void visit(const InfoPacket<float>& info); virtual void visit(const InfoPacket<boost::posix_time::ptime>& info); virtual void visit(const InfoPacket<boost::posix_time::time_duration>& info); virtual void visit(const InfoPacket<std::string>& info); virtual void visit(const InfoPacket<boost::array<char, 16> >& info); virtual void visit(const InfoPacket<boost::array<char, 65> >& info); virtual void visit(const WritePacket<bool>& write); virtual void visit(const WritePacket<uint8_t>& write); virtual void visit(const WritePacket<uint32_t>& write); virtual void visit(const WritePacket<float>& write); virtual void visit(const WritePacket<boost::posix_time::ptime>& write); virtual void visit(const WritePacket<boost::posix_time::time_duration>& write); virtual void visit(const WritePacket<std::string>& write); virtual void visit(const WritePacket<boost::array<char, 65> >& write); virtual void visit(const WritePacket<boost::array<char, 16> >& write); }; BinarySerializer::BinarySerializer(std::vector<char>& target) : _target(target) { } void BinarySerializer::append_u8(uint8_t value) { _target.push_back(value); } void BinarySerializer::append_u16(uint16_t value) { union { uint16_t u16; char raw[sizeof(value)]; } c; c.u16 = htons(value); _target.insert(_target.end(), c.raw, c.raw + sizeof(c.raw)); } void BinarySerializer::append_u32(uint32_t value) { union { uint32_t u32; char raw[sizeof(value)]; } c = { htonl(value) }; _target.insert(_target.end(), c.raw, c.raw + sizeof(c.raw)); } void BinarySerializer::append_float(float value) { union { float f; uint32_t u32; char raw[sizeof(value)]; } c = { value }; c.u32 = htonl(c.u32); _target.insert(_target.end(), c.raw, c.raw + sizeof(c.raw)); } void BinarySerializer::appendHeader(const Packet& packet) { _headerStart = _target.size(); _target.insert(_target.end(), HXB_HEADER, HXB_HEADER + strlen(HXB_HEADER)); _target.push_back(packet.type()); _target.push_back(packet.flags()); } void BinarySerializer::appendEIDHeader(const EIDPacket& packet) { appendHeader(packet); append_u32(packet.eid()); } void BinarySerializer::appendValueHeader(const TypedPacket& packet) { appendEIDHeader(packet); append_u8(packet.datatype()); } void BinarySerializer::appendCRC() { uint16_t crc = hexabus::crc(&_target[_headerStart], _target.size() - _headerStart); append_u16(crc); } void BinarySerializer::visit(const ErrorPacket& error) { appendHeader(error); append_u8(error.code()); appendCRC(); } void BinarySerializer::visit(const QueryPacket& query) { appendEIDHeader(query); appendCRC(); } void BinarySerializer::visit(const EndpointQueryPacket& endpointQuery) { appendEIDHeader(endpointQuery); appendCRC(); } void BinarySerializer::appendValue(const ValuePacket<bool>& value) { appendValueHeader(value); append_u8(value.value()); appendCRC(); } void BinarySerializer::appendValue(const ValuePacket<uint8_t>& value) { appendValueHeader(value); append_u8(value.value()); appendCRC(); } void BinarySerializer::appendValue(const ValuePacket<uint32_t>& value) { appendValueHeader(value); append_u32(value.value()); appendCRC(); } void BinarySerializer::appendValue(const ValuePacket<float>& value) { appendValueHeader(value); append_float(value.value()); appendCRC(); } void BinarySerializer::appendValue(const ValuePacket<boost::posix_time::ptime>& value) { appendValueHeader(value); append_u8(value.value().time_of_day().hours()); append_u8(value.value().time_of_day().minutes()); append_u8(value.value().time_of_day().seconds()); append_u8(value.value().date().day()); append_u8(value.value().date().month()); append_u16(value.value().date().year()); append_u8(value.value().date().day_of_week()); appendCRC(); } void BinarySerializer::appendValue(const ValuePacket<boost::posix_time::time_duration>& value) { appendValueHeader(value); append_u32(value.value().total_seconds()); appendCRC(); } void BinarySerializer::appendValue(const ValuePacket<std::string>& value) { appendValueHeader(value); _target.insert(_target.end(), value.value().begin(), value.value().end()); _target.insert(_target.end(), ValuePacket<std::string>::max_length + 1 - value.value().size(), '\0'); appendCRC(); } void BinarySerializer::appendValue(const ValuePacket<boost::array<char, 16> >& value) { appendValueHeader(value); _target.insert(_target.end(), value.value().begin(), value.value().end()); appendCRC(); } void BinarySerializer::appendValue(const ValuePacket<boost::array<char, 65> >& value) { appendValueHeader(value); _target.insert(_target.end(), value.value().begin(), value.value().end()); appendCRC(); } void BinarySerializer::visit(const EndpointInfoPacket& endpointInfo) { appendValue(endpointInfo); } void BinarySerializer::visit(const InfoPacket<bool>& info) { appendValue(info); } void BinarySerializer::visit(const InfoPacket<uint8_t>& info) { appendValue(info); } void BinarySerializer::visit(const InfoPacket<uint32_t>& info) { appendValue(info); } void BinarySerializer::visit(const InfoPacket<float>& info) { appendValue(info); } void BinarySerializer::visit(const InfoPacket<boost::posix_time::ptime>& info) { appendValue(info); } void BinarySerializer::visit(const InfoPacket<boost::posix_time::time_duration>& info) { appendValue(info); } void BinarySerializer::visit(const InfoPacket<std::string>& info) { appendValue(info); } void BinarySerializer::visit(const InfoPacket<boost::array<char, 16> >& info) { appendValue(info); } void BinarySerializer::visit(const InfoPacket<boost::array<char, 65> >& info) { appendValue(info); } void BinarySerializer::visit(const WritePacket<bool>& write) { appendValue(write); } void BinarySerializer::visit(const WritePacket<uint8_t>& write) { appendValue(write); } void BinarySerializer::visit(const WritePacket<uint32_t>& write) { appendValue(write); } void BinarySerializer::visit(const WritePacket<float>& write) { appendValue(write); } void BinarySerializer::visit(const WritePacket<boost::posix_time::ptime>& write) { appendValue(write); } void BinarySerializer::visit(const WritePacket<boost::posix_time::time_duration>& write) { appendValue(write); } void BinarySerializer::visit(const WritePacket<std::string>& write) { appendValue(write); } void BinarySerializer::visit(const WritePacket<boost::array<char, 16> >& write) { appendValue(write); } void BinarySerializer::visit(const WritePacket<boost::array<char, 65> >& write) { appendValue(write); } // }}} std::vector<char> hexabus::serialize(const Packet& packet) { std::vector<char> result; BinarySerializer serializer(result); serializer.visitPacket(packet); return result; } // {{{ Binary deserialization class BinaryDeserializer { private: const char* _packet; size_t _offset; size_t _size; void checkLength(size_t min); void readHeader(); uint8_t read_u8(); uint16_t read_u16(); uint32_t read_u32(); float read_float(); template<size_t L> boost::array<char, L> read_bytes(); std::string read_string(); template<typename T> Packet::Ptr checkInfo(bool info, uint32_t eid, const T& value, uint8_t flags); template<typename T> Packet::Ptr check(const T& packet); public: BinaryDeserializer(const char* packet, size_t size) : _packet(packet), _offset(0), _size(size) { if (!packet) throw std::invalid_argument("packet"); } Packet::Ptr deserialize(); }; void BinaryDeserializer::checkLength(size_t min) { if (_size - _offset < min) throw BadPacketException("Packet too short"); } void BinaryDeserializer::readHeader() { checkLength(strlen(HXB_HEADER)); if (memcmp(HXB_HEADER, _packet + _offset, strlen(HXB_HEADER))) throw BadPacketException("Invalid header"); _offset += strlen(HXB_HEADER); } uint8_t BinaryDeserializer::read_u8() { checkLength(sizeof(uint8_t)); return *(_packet + _offset++); } uint16_t BinaryDeserializer::read_u16() { checkLength(sizeof(uint16_t)); union { char raw[sizeof(uint16_t)]; uint16_t u16; } c; memcpy(c.raw, _packet + _offset, sizeof(c.raw)); _offset += sizeof(uint16_t); return ntohs(c.u16); } uint32_t BinaryDeserializer::read_u32() { checkLength(sizeof(uint32_t)); union C { char raw[sizeof(uint32_t)]; uint32_t u32; } c; memcpy(c.raw, _packet + _offset, sizeof(c.raw)); _offset += sizeof(uint32_t); return ntohl(c.u32); } float BinaryDeserializer::read_float() { union { uint32_t u32; float f; } c = { read_u32() }; return c.f; } template<size_t L> boost::array<char, L> BinaryDeserializer::read_bytes() { checkLength(L); boost::array<char, L> result; std::copy(_packet + _offset, _packet + _offset + L, result.begin()); _offset += L; return result; } std::string BinaryDeserializer::read_string() { checkLength(ValuePacket<std::string>::max_length); if (!std::find(_packet + _offset, _packet + _offset + ValuePacket<std::string>::max_length, '\0')) throw BadPacketException("Unterminated string"); std::string result(_packet + _offset); _offset += ValuePacket<std::string>::max_length + 1; return result; } template<typename T> Packet::Ptr BinaryDeserializer::checkInfo(bool info, uint32_t eid, const T& value, uint8_t flags) { if (info) { return check(InfoPacket<T>(eid, value, flags)); } else { return check(WritePacket<T>(eid, value, flags)); } } template<typename T> Packet::Ptr BinaryDeserializer::check(const T& packet) { uint16_t crc = hexabus::crc(_packet, _offset); if (crc != read_u16()) { throw BadPacketException("Bad checksum"); } return Packet::Ptr(new T(packet)); } Packet::Ptr BinaryDeserializer::deserialize() { readHeader(); uint8_t type = read_u8(); uint8_t flags = read_u8(); switch (type) { case HXB_PTYPE_ERROR: { uint8_t code = read_u8(); return check(ErrorPacket(code, flags)); } case HXB_PTYPE_INFO: case HXB_PTYPE_WRITE: { bool info = type == HXB_PTYPE_INFO; uint32_t eid = read_u32(); uint8_t datatype = read_u8(); switch (datatype) { case HXB_DTYPE_BOOL: return checkInfo<bool>(info, eid, read_u8(), flags); case HXB_DTYPE_UINT8: return checkInfo<uint8_t>(info, eid, read_u8(), flags); case HXB_DTYPE_UINT32: return checkInfo<uint32_t>(info, eid, read_u32(), flags); case HXB_DTYPE_FLOAT: return checkInfo<float>(info, eid, read_float(), flags); case HXB_DTYPE_DATETIME: { uint8_t hour = read_u8(); uint8_t minute = read_u8(); uint8_t second = read_u8(); uint8_t day = read_u8(); uint8_t month = read_u8(); uint16_t year = read_u8(); uint8_t weekday = read_u8(); boost::posix_time::ptime dt( boost::gregorian::date(year, month, day), boost::posix_time::hours(hour) + boost::posix_time::minutes(minute) + boost::posix_time::seconds(second)); if (dt.date().day_of_week() != weekday) throw BadPacketException("Invalid datetime format"); return checkInfo<boost::posix_time::ptime>(info, eid, dt, flags); } case HXB_DTYPE_TIMESTAMP: return checkInfo<boost::posix_time::time_duration>(info, eid, boost::posix_time::seconds(read_u32()), flags); case HXB_DTYPE_128STRING: return checkInfo<std::string>(info, eid, read_string(), flags); case HXB_DTYPE_16BYTES: return checkInfo<boost::array<char, 16> >(info, eid, read_bytes<16>(), flags); case HXB_DTYPE_65BYTES: return checkInfo<boost::array<char, 65> >(info, eid, read_bytes<65>(), flags); default: throw BadPacketException("Invalid datatype"); } } case HXB_PTYPE_QUERY: { uint32_t eid = read_u32(); return check(QueryPacket(eid, flags)); } case HXB_PTYPE_EPQUERY: { uint32_t eid = read_u32(); return check(EndpointQueryPacket(eid, flags)); } case HXB_PTYPE_EPINFO: { uint32_t eid = read_u32(); uint8_t datatype = read_u8(); return check(EndpointInfoPacket(eid, datatype, read_string(), flags)); } default: throw BadPacketException("Unknown packet type"); } } // }}} void hexabus::deserialize(const void* packet, size_t size, PacketVisitor& handler) { deserialize(packet, size)->accept(handler); } Packet::Ptr hexabus::deserialize(const void* packet, size_t size) { return BinaryDeserializer(reinterpret_cast<const char*>(packet), size).deserialize(); }
true
ae462d2929d5a14f77b30c3b6ed4f252773e956a
C++
ameks94/PrataTasks
/10.1/main.cpp
UTF-8
507
2.828125
3
[]
no_license
#include "bank.h" void main () { Bank *bank = new Bank("Alex","MyAccount2",9860); cout << "Your information: " << endl; bank->ShowInfo(); float summ; input(&summ,"How much money would you like to put to your account: "); bank->AddBalance(summ); cout << "Your changed information: " << endl; bank->ShowInfo(); input(&summ,"How much money would you like to withdraw from your account: "); bank->SubBalance(summ); cout << "Your changed information: " << endl; bank->ShowInfo(); system("pause"); }
true
b3a8b719980451f91365f499b8937523ad2275db
C++
Inocustonner/controller-test-work
/src/RetranslatorActiveXLib/Hook.cpp
UTF-8
3,911
2.515625
3
[]
no_license
#include "Hook.hpp" #include <Windows.h> #include <functional> #include <magic_enum.hpp> #include <thread> #define WAIT_ONE FALSE #define InterlockedRead(var) InterlockedExchangeAdd(&(var), 0) extern "C" volatile long g_maxWeight; extern "C" volatile long g_minWeight; extern "C" volatile long g_corr; extern "C" volatile double g_reset_thr; // must match with 'EventType' enum static std::tuple hookFuncs = { (HookSet) nullptr, //SetMax (HookSet) nullptr, //SetMin (HookSet) nullptr, //SetCorr (HookNotify) nullptr, //SetNull (HookNotify) nullptr, //SetResetThr (HookNotify) nullptr, // ClearAuth }; static HANDLE events[magic_enum::enum_count<EventType>()] = {}; static bool stop = true; static std::thread listener_th; template <class Func, class Tuple, size_t N = 0> inline void runtime_get(Func func, Tuple &tup, size_t idx) { if (N == idx) { func(std::get<N>(tup)); return; } if constexpr (N + 1 < std::tuple_size_v<Tuple>) { return runtime_get<Func, Tuple, N + 1>(func, tup, idx); } } extern "C" { void fireEvent(EventType event) { SetEvent(events[event]); } void setEventHook(EventType event, void* onSet) { #pragma message("Enable checks for type of 'onSet' somewhere") runtime_get( [onSet](auto& hook_f) { hook_f = (std::remove_reference_t<decltype(hook_f)>)onSet; }, hookFuncs, event); } } static HANDLE createEvent(const char* name) { HANDLE h = CreateEventA(NULL, FALSE, FALSE, name); if (h == INVALID_HANDLE_VALUE) { throw std::exception("Error creating event"); } return h; } static void listenFunc() { while (!stop) { EventType event_t = static_cast<EventType>( WaitForMultipleObjects(std::size(events), events, WAIT_ONE, INFINITE)); #define CALL_CASE_FOR(enum_value, call) \ case EventType::enum_value: { \ auto f_ptr = std::get<EventType::enum_value>(hookFuncs); \ if (f_ptr != 0) \ f_ptr call; \ }break switch (event_t) { CALL_CASE_FOR(SetMaximalWeight, (InterlockedRead(g_maxWeight))); CALL_CASE_FOR(SetMinimalWeight, (InterlockedRead(g_minWeight))); CALL_CASE_FOR(SetCorr, (InterlockedRead(g_corr))); CALL_CASE_FOR(SetNull, ()); CALL_CASE_FOR(ClearAuth, ()); CALL_CASE_FOR(SetResetThr, ()); //case SetMaximalWeight: { // onSetMaximalWeightHook(InterlockedRead(g_maxWeight)); // break; //} //case SetMinimalWeight: { // onSetMinimalWeightHook(InterlockedRead(g_minWeight)); // break; //} //case SetCorr: { // onSetCorrHook(InterlockedRead(g_corr)); // break; //} //case SetNull: { // onSetNullHook(0); // break; //} //case ClearAuth: { // onClearAuthHook(0); // break; //} //case SetResetThr: { // onSetResetThrKoef(0); //} break; default: continue; } ResetEvent(events[event_t]); #undef CALL_CASE_FOR } } void initListener() { for (const auto& [index, name] : magic_enum::enum_entries<EventType>()) { events[index] = createEvent(name.data()); } // events[SetMaximalWeight] = createEvent("SetMaximalWeightEvent"); // events[SetMinimalWeight] = createEvent("SetMinimalWeightEvent"); // events[SetCorr] = createEvent("SetCorr"); // events[SetNull] = createEvent("SetNull"); // events[ClearAuth] = createEvent("ClearAuth"); // events[SetResetThr] = createEvent("SetResetThr"); } void startListener() { stop = false; listener_th = std::thread(listenFunc); } void stopListener() { stop = true; if (listener_th.joinable()) listener_th.join(); }
true
27b0ca7e8a69f7b4bd56fdabb230ea800b05ca93
C++
thenumbernine/Common
/include/Common/Sequence.h
UTF-8
9,618
3
3
[]
no_license
#pragma once #include "Common/Variadic.h" #include <utility> //integer_sequence<> namespace Common { // begin https://codereview.stackexchange.com/a/64702/265778 namespace details { template<typename Int, typename, Int Begin, bool Increasing> struct integer_range_impl; template<typename Int, Int... N, Int Begin> struct integer_range_impl<Int, std::integer_sequence<Int, N...>, Begin, true> { using type = std::integer_sequence<Int, N+Begin...>; }; template<typename Int, Int... N, Int Begin> struct integer_range_impl<Int, std::integer_sequence<Int, N...>, Begin, false> { using type = std::integer_sequence<Int, Begin-N...>; }; } template<typename Int, Int Begin, Int End> using make_integer_range = typename details::integer_range_impl< Int, std::make_integer_sequence<Int, (Begin<End) ? End-Begin : Begin-End>, Begin, (Begin < End) >::type; template<std::size_t Begin, std::size_t End> using make_index_range = make_integer_range<std::size_t, Begin, End>; // end https://codereview.stackexchange.com/a/64702/265778 // get the i'th value from an index_sequence // I'm putting that seq-type last so I can default use the integer_sequence type template<size_t i, typename T, typename R = typename T::value_type> constexpr R seq_get_v = {}; template<size_t i, typename T, T... I> constexpr T seq_get_v<i, std::integer_sequence<T, I...>> = variadic_get_v<i, T, I...>; // concat index_sequence //https://devblogs.microsoft.com/oldnewthing/20200625-00/?p=103903 // because there's a case that Seqs... is zero-sized, you do have to provide a default type. template<typename Int, typename... Seqs> struct seq_cat; template<typename Int> struct seq_cat<Int> { using type = std::integer_sequence<Int>; }; template<typename Int, Int... Ints1> struct seq_cat< Int, std::integer_sequence<Int, Ints1...> > { using type = std::integer_sequence<Int, Ints1...>; }; template<typename Int, Int... Ints1, Int... Ints2> struct seq_cat< Int, std::integer_sequence<Int, Ints1...>, std::integer_sequence<Int, Ints2...> > { using type = std::integer_sequence<Int, Ints1..., Ints2...>; }; template<typename Int, typename Seq1, typename Seq2, typename... Seqs> struct seq_cat<Int, Seq1, Seq2, Seqs...> { using type = typename seq_cat< Int, typename seq_cat<Int, Seq1, Seq2>::type, typename seq_cat<Int, Seqs...>::type >::type; }; template<typename Int, typename... Seqs> using seq_cat_t = typename seq_cat<Int, Seqs...>::type; // set the i'th value of an index_sequence template<typename R, R value, size_t i, typename T> struct seq_set; template<typename R, R value, size_t i, R first, R... rest> struct seq_set<R, value, i, std::integer_sequence<R, first, rest...>> { using type = seq_cat_t< R, std::integer_sequence<R, first>, typename seq_set<R, value, i-1, std::integer_sequence<R, rest...>>::type >; }; template<typename R, R value, R first, R... rest> struct seq_set<R, value, 0, std::integer_sequence<R, first, rest...>> { using type = seq_cat_t< R, std::integer_sequence<R, value>, std::integer_sequence<R, rest...> >; }; template<typename R, R value, R first> struct seq_set<R, value, 0, std::integer_sequence<R, first>> { using type = std::integer_sequence<R, value>; }; // for value's type to be dependent on T, value has to go last (unless you put the index last? // seq_set_t<seq, i, value> <=> seq[i] = value template<typename T, size_t i, typename T::value_type value> using seq_set_t = typename seq_set<typename T::value_type, value, i, T>::type; // index_sequence min value template<typename T> constexpr typename T::value_type seq_min_v = {}; template<typename T, T... I> constexpr T seq_min_v<std::integer_sequence<T, I...>> = variadic_min_v<T, I...>; // index_sequence min loc template<typename T> constexpr size_t seq_min_loc_v = {}; template<typename T, T... I> constexpr size_t seq_min_loc_v<std::integer_sequence<T, I...>> = variadic_min_loc_v<T, I...>; // seq get 2nd- to end template<typename T> struct seq_pop_front; template<typename T, T i, T... I> struct seq_pop_front<std::integer_sequence<T, i, I...>> { using type = std::integer_sequence<T, I...>; }; template<typename T, T i> struct seq_pop_front<std::integer_sequence<T, i>> { using type = std::integer_sequence<T>; }; template<typename T> using seq_pop_front_t = typename seq_pop_front<T>::type; // sort index_sequence template<typename T> struct seq_sort; template<typename R, R i1, R... I> struct seq_sort<std::integer_sequence<R, i1, I...>> { using seq = std::integer_sequence<R, i1, I...>; using rest = std::integer_sequence<R, I...>; static constexpr auto value() { //output type is decltype(value()) constexpr size_t j = variadic_min_loc_v<R, I...>; // index in subset, +1 for index in seq constexpr R ij = variadic_get_v<j, R, I...>; if constexpr (i1 > ij) { //set ij in the rest using rest_set_i = seq_set_t<rest, j, i1>; // sort the rest using rest_set_i_sorted = decltype(seq_sort<rest_set_i>::value()); // then prepend the first element using sorted = seq_cat_t<R, std::integer_sequence<R, ij>, rest_set_i_sorted>; return sorted(); } else { // i1 is good, sort I... return seq_cat_t< R, std::integer_sequence<R, i1>, decltype(seq_sort<std::integer_sequence<R, I...>>::value()) >(); } } }; template<typename R, R i> struct seq_sort<std::integer_sequence<R, i>> { using type = std::integer_sequence<R, i>; static constexpr auto value() { return type(); } }; template<typename T> using seq_sort_t = decltype(seq_sort<T>::value()); // seq compile time for loop template<typename T> struct for_seq_runtime_impl; template<typename T, T i, T... I> struct for_seq_runtime_impl<std::integer_sequence<T, i, I...>> { template<typename F> static constexpr bool exec(F f) { if (f(i)) return true; return for_seq_runtime_impl<std::integer_sequence<T,I...>>::exec(f); } }; template<typename T, T i> struct for_seq_runtime_impl<std::integer_sequence<T, i>> { template<typename F> static constexpr bool exec(F f) { return f(i); } }; // T is the sequence type and has to go first template<typename T, typename F> constexpr bool for_seq_runtime(F f) { return for_seq_runtime_impl<T>::template exec<F>(f); } // seq compile time for loop with template arg template<typename T, template<int> typename F, typename... Args> struct for_seq_impl; template<typename T, T i, T... I, template<int> typename F, typename... Args> struct for_seq_impl<std::integer_sequence<T, i, I...>, F, Args...> { static constexpr bool exec(Args&& ... args) { if (F<i>::exec(std::forward<Args>(args)...)) return true; return for_seq_impl<std::integer_sequence<T,I...>, F, Args...>::exec(std::forward<Args>(args)...); } }; template<typename T, template<int> typename F, typename... Args> struct for_seq_impl<std::integer_sequence<T>, F, Args...> { static constexpr bool exec(Args && ... args) { return false; } }; // T is the sequence type and has to go first template<typename T, template<int> typename F, typename ... Args> constexpr bool for_seq(Args && ... args) { return for_seq_impl<T, F, Args...>::exec(std::forward<Args>(args)...); } // sequence reverse template<typename T> struct seq_reverse_impl; template<typename T, T first, T... Rest> struct seq_reverse_impl<std::integer_sequence<T, first, Rest...>> { using seq_first = std::integer_sequence<T, first>; using rest = std::integer_sequence<T, Rest...>; using rest_reversed = typename seq_reverse_impl<rest>::type; using type = seq_cat_t<T, rest_reversed, seq_first>; }; template<typename T, T i1, T i2> struct seq_reverse_impl<std::integer_sequence<T, i1, i2>> { using type = std::integer_sequence<T, i2, i1>; }; template<typename T, T i> struct seq_reverse_impl<std::integer_sequence<T, i>> { using type = std::integer_sequence<T, i>; }; template<typename T> using seq_reverse_t = typename seq_reverse_impl<T>::type; template<typename T> struct seq_pop_back : public seq_reverse_impl<seq_pop_front_t<seq_reverse_t<T>>> {}; template<typename T> using seq_pop_back_t = typename seq_pop_back<T>::type; // apply a sequence to a templated type which accepts it template< typename Seq, template<auto ...> typename T > struct seq_apply; template< typename I, template<I...> typename T, I... is > struct seq_apply<std::integer_sequence<I, is...>, T> { using type = T<is...>; }; template<typename Seq, template<auto...> typename T> using seq_apply_t = typename seq_apply<Seq, T>::type; // TODO for all operations //https://stackoverflow.com/a/55247213 template<typename T, T... Args> constexpr T seq_plus(std::integer_sequence<T, Args...> = {}) { return (Args + ... + (0)); } template<typename T, T... Args> constexpr T seq_multiplies(std::integer_sequence<T, Args...> = {}) { return (Args * ... * (1)); } template<typename T, T... Args> constexpr T seq_logical_and(std::integer_sequence<T, Args...> = {}) { return (Args && ... && (true)); } // assumes F<I>::value produces Seq::value_type template<typename Seq, template<typename Seq::value_type> typename F> struct SeqToSeqMapImpl; template<typename I, I i1, I... is, template<I> typename F> struct SeqToSeqMapImpl<std::integer_sequence<I, i1, is...>, F> { using type = seq_cat_t< I, std::integer_sequence<I, F<i1>::value>, typename SeqToSeqMapImpl<std::integer_sequence<I, is...>, F>::type >; }; template<typename I, template<I> typename F> struct SeqToSeqMapImpl<std::integer_sequence<I>, F> { using type = std::integer_sequence<I>; }; template<typename Seq, template<typename Seq::value_type> typename F> using SeqToSeqMap = typename SeqToSeqMapImpl<Seq, F>::type; }
true
64b57770676ab14c20e08f50848e45a83c2d7323
C++
Krstar233/krits-code-workplace
/Old-Code/题解代码/acm/未命名3.cpp
UTF-8
516
2.53125
3
[]
no_license
#include <iostream> #include <algorithm> using namespace std; int n; char table[] = "ABCDE"; char res[1024]; void solve(int cur) { if (cur == n) { res[n] = 0; puts(res); return; } for (int i = 0; i < n; i++) { bool ok = true; for (int j = 0; j < cur; j++) { if (res[j] == table[i]) ok = false; } if (ok) { res[cur] = table[i]; solve(cur + 1); } } } int main() { // while (cin >> n) // solve(0); do { puts(table); }while (next_permutation(table, table+5)); return 0; }
true
7910b7a5fc87d1007566e83b95b9d9a797401fc4
C++
kenshimota/Learning-Cpp
/test6.cpp
UTF-8
533
3.09375
3
[]
no_license
//es este esplica que una vriable externa y interna pueden tener un mismo nombre y no un mismo valor #include <iostream> using namespace std; //bueno esto es una prueba int main(){ int exp = 3; while(exp){ cout << " Veamos cual es el valor de exp : " << exp << endl; if (exp & 1) cout << "Veamos si el valos es uno :(" << exp << ")" << endl; exp >>= 10; } cout << "prueba de que se le esta haciendo un cambio"; system("pause"); }
true
f88a247ace9c98b9779eb7a677e920f73676fd37
C++
jpmartinezv/snake
/field.hpp
UTF-8
376
2.71875
3
[ "Apache-2.0" ]
permissive
#include <vector> #pragma once class Painter; class Field { public: enum { WIDTH = 32, HEIGHT = 24 }; enum Type { EMPTY, SNAKE_BLOCK, FRUIT, WALL}; Field(); void update(std::vector< std::pair<int, int> > walls); void setBlock(Type type, int x, int y); Type block(int x, int y) const; void draw(Painter &) const; void newFruit(); private: Type m_[HEIGHT][WIDTH]; };
true
1e08a5435a05fe6f19c82bde28005deaaab6bd6e
C++
SachinSarin/Data_Structures_and_Algorithms
/Linked_List/Problem_4_Reverse_a_Linked_List.cpp
UTF-8
422
3.28125
3
[]
no_license
//ITERATIVE APPROACH struct Node* reverseList(struct Node *head) { struct Node* prev = NULL; struct Node* curr = head; struct Node* forward = head->next; while(curr->next!=NULL) { curr->next=prev; prev = curr; curr = forward; forward = forward->next; } curr->next= prev; return curr; }
true
c3793ddbd536b10a3bd6b957f900c5fe84ba3699
C++
maghoff/snygg
/src/gl-raii/texture.cpp
UTF-8
384
2.765625
3
[]
no_license
#include <algorithm> #include <GL/glew.h> #include "texture.hpp" namespace gl { texture::texture() { glGenTextures(1, &id); } texture::~texture() { glDeleteTextures(1, &id); } texture::texture(texture&& rhs) { std::swap(id, rhs.id); } texture& texture::operator = (texture&& rhs) { std::swap(id, rhs.id); return *this; } unsigned texture::get_id() const { return id; } }
true
0a08f0fcee9e7d5741f74849258cde1144123152
C++
geegatomar/Algorithms
/ModularArithmetic/fast_exponentiation_exponents_in_logN.cpp
UTF-8
354
3.078125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int f(int a, int n) { if(n == 1) return a; if(n <= 0) return 1; int x = f(a, n/2); if(n % 2 == 0) return x*x; else return x*x*a; } int main() { int i, j, n, m, a; cin >> a >> n; // calc a power n using divide and conquer ( fast eponentiation ) ( O (logn) ) cout << f(a, n) << endl; }
true
7f7f9c6d4cf5a67cd30a0570e82f6967f86741dc
C++
xyproto/spheremover
/include/points.hpp
UTF-8
2,049
3.328125
3
[ "MIT" ]
permissive
#pragma once #include <algorithm> #include <iomanip> #include <string> #include <vector> using namespace std::string_literals; using Points = std::vector<Vec3>; // Implement support for the << operator, by calling the Vec3 str methods inline std::ostream& operator<<(std::ostream& os, const Points& points) { bool first = true; for (auto v : points) { if (!first) { os << ", "s; } else { first = false; } os << v.str(); } return os; } // Find the index to the Vec3 in a std::vector<Vec3> that is // closest to the given point p. size_t index_closest(const Points xs, const Vec3 p) { size_t smallest_i = 0; // return the first point index, by default double smallest_squared_dist = std::numeric_limits<double>::max(); // Largest possible value // TODO: Cache the results from distance_squared for (size_t i = 0; i < xs.size(); ++i) { if (p.distance_squared(xs[i]) < smallest_squared_dist) { smallest_squared_dist = p.distance_squared(xs[i]); smallest_i = i; } } return smallest_i; } // Find the index to the Vec3 in a std::vector<Vec3> that is // closest to the given point p, except the given indices. size_t index_closest_except( const Points xs, const Vec3 p, const std::vector<size_t> except_indices) { int smallest_i = 0; // return the first point index, by default double smallest_squared_dist = std::numeric_limits<double>::max(); // Largest possible value // TODO: Cache the results from distance_squared for (size_t i = 0; i < xs.size(); ++i) { // Thanks Zac Howland at https://stackoverflow.com/a/19299611/131264 if (std::any_of(std::begin(except_indices), std::end(except_indices), [&](size_t i2) { return i2 == i; })) { continue; } if (p.distance_squared(xs[i]) < smallest_squared_dist) { smallest_squared_dist = p.distance_squared(xs[i]); smallest_i = i; } } return smallest_i; }
true
5d0231a39f6593e5f5bb0676d270c66c3abb1b22
C++
chrisoldwood/MDBL
/SQLParams.hpp
UTF-8
1,895
2.546875
3
[ "MIT" ]
permissive
/****************************************************************************** ** ** MODULE: SQLPARAMS.HPP ** COMPONENT: Memory Database Library. ** DESCRIPTION: The CSQLParams class declaration. ** ******************************************************************************* */ // Check for previous inclusion #ifndef SQLPARAMS_HPP #define SQLPARAMS_HPP #if _MSC_VER > 1000 #pragma once #endif #include "FwdDecls.hpp" #include "MDBLTypes.hpp" /****************************************************************************** ** ** The type used to hold column information. ** ******************************************************************************* */ struct SQLParam { size_t m_nSrcColumn; // The source column. COLTYPE m_eMDBColType; // The MDB column type. size_t m_nMDBColSize; // The MDB column size. int m_nBufType; // The input buffer type. size_t m_nBufSize; // The input buffer length. size_t m_nSQLColSize; // The SQL column size. }; /****************************************************************************** ** ** This is the base class for SQL statment parameters. ** ******************************************************************************* */ class CSQLParams { public: // // Constructors/Destructor. // CSQLParams(); virtual ~CSQLParams(); // // Accessors. // virtual size_t NumParams() const = 0; virtual SQLParam& Param(size_t n) const = 0; virtual void SetRow(CRow& oRow) = 0; protected: // // Members. // }; //! The default SQL parameters smart pointer type. typedef Core::SharedPtr<CSQLParams> SQLParamsPtr; /****************************************************************************** ** ** Implementation of inline functions. ** ******************************************************************************* */ inline CSQLParams::CSQLParams() { } inline CSQLParams::~CSQLParams() { } #endif //SQLPARAMS_HPP
true
2059c8968a363e9841c89a8103f947b034dd53ba
C++
nikolascm/pod-2018
/t1-nmcorrea/ordenacao.hpp
UTF-8
885
2.5625
3
[]
no_license
// Linha para compilação: g++ -std=c++11 ordenacao.cpp -o ordenacao // Execução: ./ordenacao "exemplo_entrada.txt" #include <vector> #include <locale> #include <string> #include <fstream> #include <iostream> #include <algorithm> using namespace std; struct Arquivo { string buffer; const int N = 200; ifstream meuArquivo; vector <string> palavras; int numeroArquivos = 0; int numeroPalavras = 0; int numeroCaracteres = 0; ofstream arquivoTemporario; ifstream primeiraEntrada; ifstream segundaEntrada; void extraiPalavras(); void comparaPalavras(); int criaArqsOrdenados(); void ordenacaoExterna(); void removeArquivosTmps(); void abreArquivo(char*nome); void ordenacaoInterna(vector<string>v); void abreParticoes(int index); void escreveNaParticao(int &index); bool verificaEstadoArquivo(ifstream &f); int calculaTamanhoEmBytes(vector <string> vetor); };
true
e5690fe19bf570acc2d22b8632dfc09d5398a135
C++
jgarzon94/SistemasDistribuidos
/conexion al servidor.ino
UTF-8
1,603
2.53125
3
[]
no_license
#include <b64.h> #include <HttpClient.h> #include <UIPEthernet.h> // Used for Ethernet // **** ETHERNET SETTING **** // Arduino Uno pins: 10 = CS, 11 = MOSI, 12 = MISO, 13 = SCK // Ethernet MAC address - must be unique on your network - MAC Reads T4A001 in hex (unique in your network) byte mac[] = { 0x74,0x69,0x69,0x2D,0x30,0x31 }; // For the rest we use DHCP (IP address and such) //EthernetClient client; int pinLed1 = 2; int pinLed2 = 3; int pinLed3 = 4; int pinLDR = 0; int valorLDR = 0; char server[] = { 192,168,0,101 }; // IP Adres (or name) of server to dump data to int interval = 5000; // Wait between dumps void setup() { pinMode(pinLed1, OUTPUT); pinMode(pinLed2, OUTPUT); pinMode(pinLed3, OUTPUT); Serial.begin(9600); Ethernet.begin(mac); } void loop() { HttpClient client; // if you get a connection, report back via serial: if (client.connect(server, 80)) { Serial.println("-> Connected"); valorLDR= analogRead(pinLDR)/7; Serial.println(valorLDR); if(valorLDR > 80) { digitalWrite(pinLed1, HIGH); } if(valorLDR > 100) { digitalWrite(pinLed2, HIGH); } if(valorLDR > 120) { digitalWrite(pinLed3, HIGH); } // Make a HTTP request: client.get("http://192.168.0.101/user/mysql.php?valor="); client.get(valorLDR); client.get( " HTTP/1.1"); client.stop(); } else { // you didn't get a connection to the server: Serial.println("--> connection failed/n"); } delay(interval); }
true
7e25e849b73fa6e55450504c9a71ec79944651e3
C++
MohammadRaziei/cuda-experiments
/cppHelper.cpp
UTF-8
1,235
2.890625
3
[]
no_license
#include <stdio.h> #include <chrono> #include <complex> #include <fstream> #include <iostream> #include <string> #include <vector> #define cat(x, y) x##y #define seeType(TYPE, arr, len) \ std::vector<TYPE> cat(seeVec_, arr)(arr, arr + len) #define seeComplex16(arr, len) seeType(complex16, arr, len) #define seeFloat(arr, len) seeType(float, arr, len) #define sendToMatlab(arr, len) writeToFile(std::string(#arr) + ".bin", arr, len) // Tools: printDev #define showDev(arr, len) \ printf("%s: ", #arr); \ printDev(arr, len); void printDev(const float* dev_arr, const uint32_t len = 1) { for (uint32_t i = 0; i < (uint32_t)min(10, len); ++i) printf("%f, ", dev_arr[i]); printf("\n"); } template <typename T> void writeToFile(const std::string& filename, T* data, uint32_t len) { std::ofstream outFile(filename, std::ios::out | std::ofstream::binary); if (!outFile.is_open()) { fprintf(stderr, "Cannot open: \"%s\"\n", filename.c_str()); return; } outFile.write(reinterpret_cast<const char*>(data), sizeof(T) * len); outFile.close(); } template <typename T> inline void writeToFile(const std::string& filename, std::vector<T>* data) { writeToFile(filename, data.data, static_cast<T>(data.size())); }
true
bce3c9d7171943cfd4eec48e9e1b9bba0c7f6024
C++
OC-MCS/lab10tasks-KobeBracey
/Employee/ProductionWorker.cpp
UTF-8
436
2.796875
3
[]
no_license
#include "ProductionWorker.h" #include "Employee.h" ProductionWorker::ProductionWorker(string n, string num, string date, int s, double pay) : Employee(n, num, date) { shift = s; payRate = pay; } int ProductionWorker::getShift() { return shift; } double ProductionWorker::getPayRate() { return payRate; } void ProductionWorker::setShift(int s) { shift = s; } void ProductionWorker::setPayRate(double pay) { payRate = pay; }
true
c76961e1f71db296c9cb8fc3d5ee8af07cd4ec21
C++
petyorusanov/Diablo_0.5
/Diablo_0.5/Source.cpp
UTF-8
3,627
3.234375
3
[]
no_license
#include<iostream> #include<iomanip> #include<cstring> #include<cassert> #include<cstdlib> #include "Character.h" #include "Barbarian.h" #include "BountyHunter.h" #include "Sorcerer.h" #include "Map.h" #include "PlayerTurn.h" using namespace std; class Enemy; class Character; void pickCharacter(int& character) { cout << "\nPlease select your character: " << endl; cout << "Type 1 for barbarian.\nType 2 for sorcerer.\nType 3 for bounty hunter.\n\n"; cin >> character; while (character != 1 && character != 2 && character != 3) { cout << "Please type again!\n"; cin >> character; } } void pickName(char* charName) { cout << "\nPlease type character's name: " << endl; cin >> charName; } PlayerTurn player; int main() { cout << setw(60) << "Welcome summoner!\n\n\n\n"; cout << "Are you ready to play Diabo? - Type yes or no\n\n"; char playerReady[4]; cin >> playerReady; while (strcmp(playerReady, "yes") && strcmp(playerReady, "no")) { cout << "Please type again!\n\n"; cin >> playerReady; } if (!strcmp(playerReady, "no")) { system("pause"); return 0; } if (system("CLS")) system("clear"); Character* hero; int playerPick; pickCharacter(playerPick); if (system("CLS")) system("clear"); char characterName[25]; pickName(characterName); switch (playerPick) { case 1: { hero = new Barbarian(characterName); } break; case 2: { hero = new Sorcerer(characterName); } break; case 3: { hero = new BountyHunter(characterName); } break; default: { cout << "Your default character is Barbarian!" << endl; hero = new Barbarian(characterName); } } if (system("CLS")) system("clear"); Map* gameMap; cout << "\nDo you want to set map size? - If no, default map size will be 10x10.\nType yes or no.\n"; cin >> playerReady; while (strcmp(playerReady, "yes") && strcmp(playerReady, "no")) { cout << "Please type again!\n\n"; cin >> playerReady; } int mapSize = 0; if (!strcmp(playerReady, "yes")) { cout << "\nPlease type map size:\n"; cin >> mapSize; while (mapSize < 10) { cout << "\nPlease type an integer, greater than 9.\n"; cin >> mapSize; } gameMap = new Map(mapSize); } else { gameMap = new Map(); mapSize = 10; } if (system("CLS")) system("clear"); gameMap->setMap(mapSize); gameMap->printMap(mapSize); while (player.turn() && hero->getHP() > 0 && gameMap->getDiablosAlive() > 0) { if (system("CLS")) system("clear"); switch (player.getPlayerChoice()) { case 'l': { player.moveLeft(*gameMap, *hero); }break; case 'r': { player.moveRight(*gameMap, *hero, mapSize); }break; case 'u': { player.moveUp(*gameMap, *hero); }break; case 'd': { player.moveDown(*gameMap, *hero, mapSize); }break; case 'm': { gameMap->printMap(mapSize); }break; case 'c': { player.printConsequences(); }break; case 'h': { cout << hero->getHP() << endl; } } } if (hero->getHP() <= 0) { if (system("CLS")) system("clear"); cout << "\n\n\n\n\n\n\n\n\n" << setw(60) << "Game over! You have died!" << "\n\n\n\n\n\n\n\n\n"; } else if (gameMap->getDiablosAlive() == 0) { if (system("CLS")) system("clear"); cout << "\n\n\n\n\n\n\n\n\n" << setw(60) << "You have won!" << "\n\n\n\n\n\n\n\n\n"; } else { if (system("CLS")) system("clear"); cout << "\n\n\n\n\n\n\n\n\n" << setw(60) << "Thanks for playing!" << "\n\n\n\n\n\n\n\n\n"; } system("pause"); delete hero; delete gameMap; return 0; }
true
ccb195e094c705983d3f73e6df686669a093de17
C++
SDIdo/SOLID_Principles
/MatrixTester.h
UTF-8
620
2.625
3
[]
no_license
// // Created by roy on 1/15/19. // #ifndef PROJECTPART2_MATRIXTESTER_H #define PROJECTPART2_MATRIXTESTER_H // // Created by idox on 1/14/19. // #include <iostream> #include <vector> #include <string> #include "Entry.h" using namespace std; class MatrixTester { private: vector<vector<int>> goalIsDest = {{1, 0, 1},{0, 1, -1},{2, 1, 0}}; Entry *start = new Entry(2,0); Entry *dest = new Entry(0,2); vector<vector<int>> createRandomMatrix(int, int); void printMatrix(vector<vector<int>> subject); public: void runTest(); void goalIsDestTest(); }; #endif //PROJECTPART2_MATRIXTESTER_H
true
9b45c62c5d01c07545b307c1acc074890dd1ab29
C++
mcc12357/acm-
/ny 15括号匹配.cpp
UTF-8
928
2.71875
3
[]
no_license
#include<iostream> using namespace std; #include<string.h> #include<stdio.h> const int aa = 1<<10; int min(int x,int y) { if(x<y) return x; else return y; } int main() { int n; scanf("%d",&n); while(n--) { char a[105]; int dp[105][105]; scanf("%s",a); int len = strlen(a); int i,j,k; for(i=0;i<len;i++) dp[i][i] = 1; for(i=0;i<len-1;i++) { dp[i][i+1] = 0; } for(i=1;i<=len;i++) { for(j=0;j+i<len;j++) { int r = i + j; dp[j][r] = aa; if(a[j]=='(' && a[r]==')' || a[j]=='[' && a[r]==']') { if(j+1>r-1) {dp[j][r] = 0;continue;} dp[j][r] = min(dp[j+1][r-1],dp[j][r]); } else if(a[j]==')' || a[j]==']') { dp[j][r] = min(dp[j+1][r],dp[j][r]) + 1; } else if(a[r]=='(' || a[r]=='[') dp[j][r] = min(dp[j+1][r],dp[j][r]) + 1; for(k=j;k<r;k++) dp[j][r] = min(dp[j][r],dp[j][k]+dp[k+1][r]); } } printf("%d\n",dp[0][len-1]); } return 0; }
true
fab7f02523a7f6b0d793a445937fbfc67e772210
C++
MASLAB/TAMProxy-Firmware
/src/Color.cpp
UTF-8
2,291
2.75
3
[ "MIT" ]
permissive
#include "Color.h" #include <cstdint> #include "Adafruit_TCS34725.h" #include "config.h" namespace tamproxy { Color::Color(int integrationTime, int gain) { init = false; tcs34725IntegrationTime_t it; if (integrationTime == 1) { it = TCS34725_INTEGRATIONTIME_2_4MS; } else if (integrationTime == 2) { it = TCS34725_INTEGRATIONTIME_24MS; } else if (integrationTime == 3) { it = TCS34725_INTEGRATIONTIME_50MS; } else if (integrationTime == 4) { it = TCS34725_INTEGRATIONTIME_101MS; } else if (integrationTime == 5) { it = TCS34725_INTEGRATIONTIME_154MS; } else if (integrationTime == 6) { it = TCS34725_INTEGRATIONTIME_700MS; } else { return; } tcs34725Gain_t g; if (gain == 1) { g = TCS34725_GAIN_1X; } else if (gain == 2) { g = TCS34725_GAIN_4X; } else if (gain == 3) { g = TCS34725_GAIN_16X; } else if (gain == 4) { g = TCS34725_GAIN_60X; } else { return; } tcs = new Adafruit_TCS34725(it, g); init = tcs->begin(); } Color::~Color() { delete tcs; } std::vector<uint8_t> Color::handleRequest(std::vector<uint8_t> &request) { if (request.size() != 1) { return {REQUEST_LENGTH_INVALID_CODE}; } else if (request[0] != COLOR_READ_CODE) { return {REQUEST_BODY_INVALID_CODE}; } else { uint16_t r, g, b, c, colorTemp, lux; tcs->getRawData(&r, &g, &b, &c); colorTemp = tcs->calculateColorTemperature(r, g, b); lux = tcs->calculateLux(r, g, b); // Return r, g, b, c, plus some extra info // Total: 12 bytes (6 uint16_t) if (init) { return {static_cast<uint8_t>((r >> 8) & 0xff), static_cast<uint8_t>(r & 0xff), static_cast<uint8_t>((g >> 8) & 0xff), static_cast<uint8_t>(g & 0xff), static_cast<uint8_t>((b >> 8) & 0xff), static_cast<uint8_t>(b & 0xff), static_cast<uint8_t>((c >> 8) & 0xff), static_cast<uint8_t>(c & 0xff), static_cast<uint8_t>((colorTemp >> 8) & 0xff), static_cast<uint8_t>(colorTemp & 0xff), static_cast<uint8_t>((lux >> 8) & 0xff), static_cast<uint8_t>(lux & 0xff)}; } else { return {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; } } } }
true
fc44d82b3318ae96f77f2e4eca1684344a0eb0fd
C++
marvinklimke/rwth-prit1
/Versuch05Teil2/main.cpp
ISO-8859-2
4,029
3.28125
3
[ "MIT" ]
permissive
/** * @file main.cpp * \brief content: main routine */ /** * @mainpage * * Praktikum Informatik 1 MMXVI@n * Versuch 5.2: Dynamische Datenstrukturen * */ #include <iostream> #include <string> #include "List.h" #include "Student.h" int main() { List testListe; Student stud1; char abfrage; std::cout << "Wollen sie die Liste selbst fuellen? (j)/(n) "; std::cin >> abfrage; if (abfrage != 'j') { stud1.matNr = 12345; stud1.adresse = "Ahornst.55"; stud1.date_of_birth = "23.04.1983"; stud1.name = "Siggi Baumeister"; testListe.enqueue_head(stud1); stud1.matNr = 23456; stud1.adresse = "Wuellnerstr.8"; stud1.date_of_birth = "15.10.1963"; stud1.name = "Walter Rodenstock"; testListe.enqueue_head(stud1); stud1.matNr = 34567; stud1.adresse = "Am Markt 1"; stud1.date_of_birth = "19.06.1971"; stud1.name = "Harro Simoneit"; testListe.enqueue_head(stud1); } do { std::cout << "\nMenue:" << std::endl << "-----------------------------" << std::endl << "(1): Datenelement vorne ergaenzen" << std::endl << "(6): Datenelement hinten ergaenzen" << std::endl << "(2): Datenelement abhaengen" << std::endl << "(3): Datenbank ausgeben" << std::endl << "(4): Datenbank in umgekehrter Reihenfolge ausgeben" << std::endl << "(5): Datenelement lschen" << std::endl << "(7): Beenden" << std::endl; std::cin >> abfrage; switch (abfrage) { case '1': std::cout << "Bitte geben sie die Daten fuer den Studenten ein.\nName: "; std::cin.ignore(10, '\n'); // Ignoriere das Zeichen '\n', das noch im Puffer ist std::getline(std::cin, stud1.name); // ganze Zeilen einlesen, inkl Leerzeichen std::cout << "Geburtsdatum: "; std::getline(std::cin, stud1.date_of_birth); std::cout << "Adresse: "; std::getline(std::cin, stud1.adresse); std::cout << "Matrikelnummer: "; std::cin >> stud1.matNr; testListe.enqueue_head(stud1); std::cout << "Das Datenelement wurde vorne angehaengt." << std::endl; break; case '6': std::cout << "Bitte geben sie die Daten fuer den Studenten ein.\nName: "; std::cin.ignore(10, '\n'); // Ignoriere das Zeichen '\n', das noch im Puffer ist std::getline(std::cin, stud1.name); // ganze Zeilen einlesen, inkl Leerzeichen std::cout << "Geburtsdatum: "; std::getline(std::cin, stud1.date_of_birth); std::cout << "Adresse: "; std::getline(std::cin, stud1.adresse); std::cout << "Matrikelnummer: "; std::cin >> stud1.matNr; testListe.enqueue_tail(stud1); std::cout << "Das Datenelement wurde hinten angehaengt." << std::endl; break; case '2': std::cout << "Das hintere Datenelemt wird abgehangen\n"; testListe.dequeue(stud1); break; case '3': std::cout << "Inhalt der Liste von vorne nach hinten\n"; testListe.print_forwards(); break; case '4': std::cout << "Inhalt der Liste von hinten nach vorne\n"; testListe.print_backwards(); break; case '5': std::cout << "Bitte geben Sie die Matrikelnummer ein: "; int matr; std::cin >> matr; if(testListe.delete_byMatrikel(matr)) std::cout << "Deletion successful!" << std::endl; else std::cout << "Deletion failed!" << std::endl; break; case '7': std::cout << "Das Programm wird nun beendet"; break; default : std::cout << "Falsche Eingabe, bitte nochmal"; } } while (abfrage != '7'); return 0; }
true
edfd65404e2f2e5ee8bb0604bd2e937ff5c06f25
C++
ZibeSun/DS-CodeTemplateCollection
/排序/基数排序.cpp
GB18030
1,730
3.625
4
[]
no_license
#include<iostream> using namespace std; // //ȶ class RadixSort { private: int* data; //Ҫ int len; //Ҫ鳤 //ݵλ int maxbit() { int maxData = data[0]; for (int i = 1; i < len; i++) { if (maxData < data[i]) maxData = data[i]; } int d = 1; while (maxData >= 10) { maxData /= 10; d++; } return d; } void Sort() { int d = maxbit(); int* temp = new int[len]; int* count = new int[10];// int** arr = new int* [10]; int radix = 1; int j, k, h; for (int i = 1; i <= d; i++) { for (j = 0; j < 10; j++) count[j] = 0;//ÿηǰռ for (j = 0; j < 10; j++) { arr[j] = NULL; } for (j = 0; j < len; j++) { k = (data[j] / radix) % 10; //ͳÿͰеļ¼ if (arr[k] == NULL) arr[k] = new int[len]; arr[k][count[k]] = data[j]; count[k]++; } for (j = 0; j < 10; j++) { cout << j << ":"; if (arr[j] == NULL) cout << "NULL" << endl; else { cout << "->"; for (h = 0; h < count[j]; h++) cout << arr[j][h] << "->"; cout << "^" << endl; } } for (j = 1; j < 10; j++) count[j] = count[j - 1] + count[j]; for (j = len - 1; j >= 0; j--) { k = (data[j] / radix) % 10; temp[count[k] - 1] = data[j]; count[k]--; } for (j = 0; j < len; j++) data[j] = temp[j]; radix *= 10; display(); } delete[]temp; delete[]count; } public: //캯 RadixSort(int* item, int n) { data = item; len = n; Sort(); } void display() { for (int i = 0; i < len; i++) { cout << data[i] << " "; } cout << endl; } };
true
10f85aeab383040463f08624cf8f816a30d76f07
C++
mouhssinelghazzali/50-programs-langage-c
/9 - Premier - Non premier.cpp
ISO-8859-1
566
2.75
3
[]
no_license
#include <conio.h> #include <stdio.h> #include <stdlib.h> main() { system("title Premier / Non premier"); long n,i; bool pnp; printf("Entrez une Valeur :"); scanf("%d",&n); pnp = true ; for ( i=2 ; i < n ; i++ ) { if ( n % i == 0 ) pnp = false ; } if ( pnp == true ) printf("\n\n \20 La valeur %d est Premier\n",n); else printf("\n\n \20 La valeur %d est NON Premier\n",n); getch(); } // Programme ralis par : BELBSIR SAD ;)
true
62a185b7d14a337523b9885fa68f292233b5d1e1
C++
CodeRex7/CodingPractice
/geekforgeeks/Top 10 Algorithms/Array/zigag.cpp
UTF-8
682
3.921875
4
[]
no_license
/* * Rearrange the elements of array in zig-zag fashion in O(n) time. * The converted array should be in form a < b > c < d > e < f */ #include<bits/stdc++.h> #define pb push_back using namespace std; void zigzag(vector<int> &arr){ bool flag=true; for(int i=0;i<arr.size()-1;i++){ //< expected if not then swap if(flag){ if(arr[i]>arr[i+1]) swap(arr[i],arr[i+1]); } //> expected if not then swap else{ if(arr[i]<arr[i+1]) swap(arr[i],arr[i+1]); } flag=!flag; } } int main(){ int n; cin>>n; vector<int>arr; for(int i=0;i<n;i++) { int a; cin>>a; arr.push_back(a); } zigzag(arr); for(int i=0;i<n;i++) cout<<arr[i]<<" "; cout<<endl; }
true
b09a5d25218fbcaad077afa13e9fd70905acea0c
C++
Jony635/Commando-1985-NES-Edition_v2
/Comando versión definitiva/Enemy.h
UTF-8
1,275
2.609375
3
[]
no_license
#ifndef __ENEMY_H__ #define __ENEMY_H__ #include "p2Point.h" #include "Animation.h" #include "Path.h" struct SDL_Texture; struct Collider; enum ENEMY_TYPES { NO_TYPE, WHITEGUARD, CAPTURERGUARD, BOSSLVL1, KNIFE, BOSSGRENADE, RUNNER, MOTORBIKE, HOLE, ROCKET, BUNKER, CAR, TRUCK, PATHWHITEGUARD }; enum MOVE_STATE { GOING_UP, GOING_DOWN, GOING_LEFT, GOING_RIGHT, NO_STATE }; class Enemy { protected: Animation* animation; Collider* collider; public: iPoint position; iPoint original_pos; public: friend class ModuleEnemies; Enemy(int x, int y, char* cpath="NULL"); virtual ~Enemy(); const Collider* GetCollider() const; virtual void Move() {}; virtual void Draw(SDL_Texture* sprites); ENEMY_TYPES type; virtual Animation getDie() = 0; Path path; char* cpath = "NULL"; virtual void OnCollision(Collider* collider); virtual void PathUp() {}; virtual void PathDown() {}; virtual void PathLeft() {}; virtual void PathRight() {}; virtual void ColPathUp() {}; virtual void ColPathDown() {}; virtual void ColPathLeft() {}; virtual void ColPathRight() {}; virtual void setMove(bool boolean) {}; virtual bool getRelax() { return false; }; virtual bool* getMoving() const { bool* buf = nullptr; return buf; }; }; #endif // __ENEMY_H__
true
0710724f2661921070d22c9af0d56364c2f01061
C++
ryuspace/Algorithm
/Codeforces/Codeforces Round #547 (Div. 3)/D - Colored Boots.cpp
UTF-8
1,881
2.828125
3
[]
no_license
#include <iostream> #include <algorithm> #include <queue> #include <vector> #include <string> using namespace std; queue<int> l[500]; queue<int> r[500]; vector<pair<int, int> > v; int l_cnt[500]; int r_cnt[500]; //알파벳끼리 매칭, 위쪽 ?와 아랫쪽 알파벳과 매칭, 위쪽 알파벳과 아래쪽 ?과 매칭, 위쪽 ?와 아랫쪽 ?과 매칭 int main() { ios_base::sync_with_stdio(0); int n; cin >> n; string a, b; cin >> a >> b; for (int i = 0; i < a.length(); i++) { l_cnt[a[i]]++; l[a[i]].push(i + 1); } for (int i = 0; i < a.length(); i++) { r_cnt[b[i]]++; r[b[i]].push(i + 1); } int minn = 1e9; for (int i = 'a'; i <= 'z'; i++) { minn = min(l_cnt[i], r_cnt[i]); for (int j = 0; j < minn; j++) { int front1 = l[i].front(); int front2 = r[i].front(); v.push_back({ front1,front2 }); l[i].pop(); r[i].pop(); l_cnt[i]--; r_cnt[i]--; } } minn = 1e9; for (int i = 'a'; i <= 'z'; i++) { minn = min(l_cnt['?'], r_cnt[i]); for (int j = 0; j < minn; j++) { int front1 = l['?'].front(); int front2 = r[i].front(); v.push_back({ front1,front2 }); l['?'].pop(); r[i].pop(); l_cnt['?']--; r_cnt[i]--; } } for (int i = 'a'; i <= 'z'; i++) { minn = min(l_cnt[i], r_cnt['?']); for (int j = 0; j < minn; j++) { int front1 = l[i].front(); int front2 = r['?'].front(); v.push_back({ front1,front2 }); l[i].pop(); r['?'].pop(); l_cnt[i]--; r_cnt['?']--; } } for (int i = 'a'; i <= 'z'; i++) { minn = min(l_cnt['?'], r_cnt['?']); for (int j = 0; j < minn; j++) { int front1 = l['?'].front(); int front2 = r['?'].front(); v.push_back({ front1,front2 }); l['?'].pop(); r['?'].pop(); l_cnt['?']--; r_cnt['?']--; } } cout << v.size() << "\n"; for (auto&i : v) { cout << i.first << " " << i.second << '\n'; } return 0; }
true
19f6f915c1ebbf766e3a0590c330934aacaf4f9d
C++
pidddgy/competitive-programming
/codeforces/connect.cpp
UTF-8
2,379
2.828125
3
[]
no_license
// http://codeforces.com/contest/1130/problem/C #include <bits/stdc++.h> #define pii pair<int, int> #define row first #define col second #define mp make_pair using namespace std; vector<pii> s; vector<pii> d; int N; void bfs(int R, int C, vector<vector<char>> A, char w) { queue<int> rQ; queue<int> cQ; bool vis[N+1][N+1]; for(int i = 1; i <= N; i++) { for(int j = 1; j <= N; j++) { vis[i][j] = false; } } rQ.push(R); cQ.push(C); vis[R][C] = true; while(!rQ.empty()) { int r = rQ.front(); int c = cQ.front(); if(w == 'S') s.emplace_back(mp(r, c)); else if (w == 'D') d.emplace_back(mp(r,c)); rQ.pop(); cQ.pop(); // up if(r-1 >= 1) if(!vis[r-1][c] && A[r-1][c] != 'W') { rQ.push(r-1); cQ.push(c); vis[r-1][c] = true; } // right if(c+1 <= N) if(!vis[r][c+1] && A[r][c+1] != 'W') { rQ.push(r); cQ.push(c+1); vis[r][c+1] = true; } // down if(r+1 <= N) { if(!vis[r+1][c] && A[r+1][c] != 'W') { rQ.push(r+1); cQ.push(c); vis[r+1][c] = true; } } // left if(c-1 >= 1) { if(!vis[r][c-1] && A[r][c-1] != 'W') { rQ.push(r); cQ.push(c-1); vis[r][c-1] = true; } } } } int main() { cin.sync_with_stdio(0); cin.tie(0); cin >> N; int r1, c1, r2, c2; cin >> r1 >> c1 >> r2 >> c2; vector<vector<char>> A(N+1); for(int i = 1; i <= N; i++) { A[i].emplace_back('.'); for(int j = 1; j <= N; j++) { char a; cin >> a; if(a == '0') A[i].emplace_back('L'); else if(a == '1') A[i].emplace_back('W'); } } bfs(r1, c1, A, 'S'); bfs(r2, c2, A, 'D'); int t = 2147483647; for(auto i: s) { if(i.row == r2 && i.col == c2) { cout << 0 << endl; return 0; } for(auto j: d) { int c = pow(abs(i.row - j.row), 2) + pow(abs(i.col - j.col), 2); t = min(t, c); } } cout << t << endl; }
true
2608b569879e9b04398540c8552120afebdc4347
C++
pwestrich/csc_2100
/lab_05/lab5part2.cpp
UTF-8
603
3.421875
3
[ "MIT" ]
permissive
//Lab 5 Part 2 //For-Loop Practice //by Philip Westrich //CSC-2101 //Tuesday, October 2, 2012 #include <iostream> int main(){ int count = 0; std::cout << "Please enter an integer between 1 and 30: "; std::cin >> count; std::cin.ignore(80, '\n'); while (count <=1 || count >= 30){ std::cout << "Invalid input! Please enter an integer between 1 and 30: "; std::cin >> count; } for (int i = 0; i < count; i++) { std::cout << "**"; } std::cout << std::endl; return 0; }
true
820699f06502bbe233776a26794030243e66ae69
C++
TylerBrock/books
/C++ Primer Plus/ch16/party.cpp
UTF-8
1,359
3.265625
3
[]
no_license
// party.cpp -- merge two sets of party invitees #include <iostream> #include <string> #include <set> #include <vector> #include <iterator> #include <algorithm> using std::set; using std::vector; using std::cout; using std::cin; using std::endl; using std::string; using std::inserter; using std::set_union; void print_name(const string& s); set<string> combine_names(set<string> a, set<string> b); set<string> collect_names(); int main() { set<string> mat = collect_names(); cout << "\ncollected the following names:\n"; for_each(mat.begin(), mat.end(), print_name); cout << endl << endl; set<string> pat = collect_names(); cout << "\ncollected the following names:\n"; for_each(pat.begin(), pat.end(), print_name); cout << endl; vector<string> merged; cout << "\nmerged lists:\n"; set_union(mat.begin(), mat.end(), pat.begin(), pat.end(), inserter(merged, merged.begin())); for_each(merged.begin(), merged.end(), print_name); cout << endl; } void print_name(const string& s) { cout << s << " "; } set<string> combine_names(set<string> a, set<string> b) { return set<string>(); } set<string> collect_names() { cout << "Enter some names for the list:\n"; string temp; set<string> names; while (cin >> temp && temp != "done") names.insert(temp); return names; }
true
f91f8ff5df0e48d2490db092bd28f275b7d03d94
C++
wwwkkkp/Algorithm
/Leetcode/5304. 子数组异或查询_二分_位运算.cpp
UTF-8
2,319
3.546875
4
[]
no_license
/* 5304. 子数组异或查询 有一个正整数数组 arr,现给你一个对应的查询数组 queries,其中 queries[i] = [Li, Ri]。 对于每个查询 i,请你计算从 Li 到 Ri 的 XOR 值(即 arr[Li] xor arr[Li+1] xor ... xor arr[Ri])作为本次查询的结果。 并返回一个包含给定查询 queries 所有结果的数组。 示例 1: 输入:arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]] 输出:[2,7,14,8] 解释: 数组中元素的二进制表示形式是: 1 = 0001 3 = 0011 4 = 0100 8 = 1000 查询的 XOR 值为: [0,1] = 1 xor 3 = 2 [1,2] = 3 xor 4 = 7 [0,3] = 1 xor 3 xor 4 xor 8 = 14 [3,3] = 8 示例 2: 输入:arr = [4,8,2,10], queries = [[2,3],[1,3],[0,0],[0,3]] 输出:[8,0,4,4] 提示: 1 <= arr.length <= 3 * 10^4 1 <= arr[i] <= 10^9 1 <= queries.length <= 3 * 10^4 queries[i].length == 2 0 <= queries[i][0] <= queries[i][1] < arr.length */ class Solution { public: int orq(vector<int>& arr,int L,int R){ //二分 if(L==R) return arr[L]; if(R-L==1) return arr[L]^arr[R]; else return orq(arr,L,L+(R-L)/2)^orq(arr,L+(R-L)/2+1,R); } vector<int> xorQueries(vector<int>& arr, vector<vector<int>>& q) { int n=arr.size(); int n1=q.size(); vector<int> vec(n1,0); map<vector<int>,int>up; for(int i=0;i<n1;i++){ int a; if(up.find(q[i])==up.end()){ a=orq(arr,q[i][0],q[i][1]); up.insert(make_pair(q[i],a)); }else{ a=up[q[i]]; } vec[i]=a; } return vec; } }; //上述办法有点笨,其实可以将所有异或算出来 通过范围直接得出结果 class Solution { public: vector<int> xorQueries(vector<int>& arr, vector<vector<int>>& queries) { int dp[arr.size()]; dp[0] = arr[0]; for (int i = 1; i < arr.size(); ++i) { //0到i每一位的异或运算 dp[i] = dp[i - 1] ^ arr[i]; } vector<int> res; for (int i = 0; i < queries.size(); ++i) { int l = queries[i][0]; int r = queries[i][1]; int num = l == 0 ? dp[r] : dp[r] ^ dp[l - 1];//异或的异或相当于没有异或 res.push_back(num); } return res; } };
true
378209ae2cfc34fc59917e09d8299e11b44c6efe
C++
exp111/ADHS
/P2.3/TreeNode.cpp
UTF-8
1,111
3.0625
3
[]
no_license
#include "TreeNode.h" using namespace std; TreeNode::TreeNode() { } TreeNode::TreeNode(string Name, int Alter, double Einkommen, int PLZ) { this->Name = Name; this->Alter = Alter; this->Einkommen = Einkommen; this->PLZ = PLZ; this->NodePosID = Alter + PLZ + int(Einkommen); } TreeNode::~TreeNode() { } string TreeNode::getName() { return Name; } int TreeNode::getAlter() { return Alter; } double TreeNode::getEinkommen() { return Einkommen; } int TreeNode::getPLZ() { return PLZ; } void TreeNode::setName(string name) { this->Name = name; } void TreeNode::setAlter(int alter) { this->Alter = alter; } void TreeNode::setEinkommen(double einkommen) { this->Einkommen = einkommen; } void TreeNode::setPLZ(int plz) { this->PLZ = plz; } void TreeNode::printData() { cout << "NodeID: " << to_string(this->NodeID) << ", Name: " << this->Name << ", Alter: " << to_string(this->Alter) << ", Einkommen: " << to_string(this->Einkommen) << ", PLZ: " << to_string(this->PLZ) << ", PosID: " << to_string(this->NodePosID) << endl; } void TreeNode::setID(int ID) { this->NodeID = ID; }
true
398a6f06c111efa53b18e9b1771839b595b6fae2
C++
arlm/pseudo
/Pseudo/TextWriter.hpp
UTF-8
873
2.6875
3
[]
no_license
// Copyright (c) John Lyon-Smith. All rights reserved. #pragma once #ifndef __PSEUDO_TEXT_WRITER_HPP__ #define __PSEUDO_TEXT_WRITER_HPP__ #pragma warning(push) #include <Pseudo\ValueType.hpp> #include <Pseudo\String.hpp> namespace Pseudo { /// <summary> /// TextWriter for writing encoded text /// </summary> class TextWriter { private: public: TextWriter() { } public: virtual ~TextWriter() { } public: virtual void Write(Char c) = 0; public: virtual void Write(const String& s) = 0; public: virtual void Write(const Char* p, ...) = 0; public: virtual void WriteLine() = 0; public: virtual void WriteLine(Char c) = 0; public: virtual void WriteLine(const String& s) = 0; public: virtual void WriteLine(const Char* p, ...) = 0; }; } #pragma warning(pop) #endif // __PSEUDO_TEXT_WRITER_HPP__
true
a5da423462bbc546f571e3a5a8963b968d45e881
C++
hessamg/random-Cpp-projects
/Random coding exercises/palindrom difference.cpp
UTF-8
1,559
3.4375
3
[]
no_license
//To do this exercise, follows two rules: // //You can only reduce the value of a letter by , i.e. he can change d to c, but he cannot change c to d or d to b. //The letter a may not be reduced any further. //Each reduction in the value of any letter is counted as a single operation. Find the minimum number of operations required to convert a given string into a palindrome. // //Input Format // //The first line contains an integer q, the number of queries. //The next q lines will each contain a string s. // //Constraints // // //All characters are lower case English letters, no spaces. // //Output Format // //A single line containing the number of minimum operations corresponding to each test case. // //Sample Input // //4 //abc //abcba //abcd //cba //Sample Output // //2 //0 //4 //2 //Explanation // //For the first test case, abc -> abb -> aba. //For the second test case, abcba is already a palindromic string. //For the third test case, abcd -> abcc -> abcb -> abca = abca -> abba. //For the fourth test case, cba -> bba -> aba. // #include <iostream> using namespace std; int main() { int q ; cin>>q ; while(q--){ string s ; cin>>s ; int i = 0 ; int j = s.length() - 1 ; int difference = 0 ; while(i <= j ) { difference+=abs(s[i]-s[j]); // calculate the ascii difference of the characters // cout<<s1[i]<<" "<<s1[j]<<" " <<ans <<endl; i++; j--; } cout<<difference<<"\n" ; } return 0; }
true
515ec62e68c00629d5c03a3181ab0ad87b22b604
C++
jucrs/Monster
/home.cpp
UTF-8
1,003
2.59375
3
[]
no_license
#include "home.h" void inithome(SDL_Surface *home, SDL_Surface *screen,SDL_Surface *home2, bool &play, bool &game,bool &quit) { applySurface(0,0,home,screen,NULL); SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: quit = true; break; case SDL_MOUSEBUTTONUP: { int x=event.button.x; int y=event.button.y; if ((x>265) && (x<350) && (y>320) && (y<700)) { play=true; } break; } case SDL_MOUSEMOTION: { int x=event.button.x; int y=event.button.y; if ((x>265) && (x<350) && (y>320) && (y<700)) { applySurface(0,0,home2,screen,NULL); } break; } } SDL_Flip(screen); } }
true
7d33a5971b73fe7b6f34d4681479aa8cc55a8cd9
C++
moriarty/Team2AMR
/src/plan/pathexecuter.cpp
UTF-8
5,032
2.96875
3
[ "MIT" ]
permissive
#include "pathexecuter.h" CREATE_LOGGER("PathExecuter"); PathExecuter::PathExecuter(Motor& motor) { this->motor = &motor; this->alreadyFound = false; this->path = NULL; LOG_CTOR << "Constructed." << std::endl; } PathExecuter::~PathExecuter() { abandonPath(); LOG_DTOR << "Destructed." << std::endl; } bool PathExecuter::executePosition() { if (path != NULL) { if (path->size() == 0) { motor->halt(); abandonPath(); MAKE_LOG << "Path Deleted." << std::endl; } else { //continue executing //get next Position to go to Position goal = path->getPosition(0); if (isArrived(goal)) { //check if at goal //take position off list path->removePosition(0); } else motor->goTo(goal); } //end continue executing return false; } //end if Path != NULL return true; } bool PathExecuter::executeMove(bool remove) { if (path != NULL) { MAKE_LOG << "PE executeMove()"<< std::endl; if (path->numOfMoves(0) == 0) { //0 moves to execute MAKE_LOG << "zero moves to execute" << std::endl; motor->halt(); if (remove && path != NULL) abandonPath(); return true; } else { //continue executing //get current move Move m = path->getMove(); Motion motion; if (m.isMeters) { //if moving double difference = lastLocation.calcDistTo(robotLocation); if (m.value < 0) //if moving backwards motion.x = (-1)*PathExecuter::SPEED; else motion.x = PathExecuter::SPEED; if (difference >= std::abs(m.value)) { //check if arrived path->removeMove(); lastLocation = robotLocation; } else { //continue current Move motor->setMotion(motion); motor->update(); } } else { // if turning if (m.value < 0) motion.yaw = (-1)*PathExecuter::TURNRATE; else motion.yaw = PathExecuter::TURNRATE; double angleDiff = std::abs(robotLocation.yaw - lastLocation.yaw); MAKE_LOG << "Angle diff : " << angleDiff << std::endl; MAKE_LOG << "angle to move : " << m.value*(180.0/M_PI) << std::endl; if (angleDiff >= std::abs(m.value)) { //check if arrived MAKE_LOG << "Removing move" << std::endl; path->removeMove(); lastLocation = robotLocation; } else { //continue turning MAKE_LOG << "updating" << std::endl; motor->setMotion(motion); motor->update(); } } } //end continue return false; } //end if path!=NULL return true; } bool PathExecuter::execute() { if (path != NULL) { if (path->size() == 0) { motor->halt(); abandonPath(); MAKE_LOG << "Path Deleted." << std::endl; } else { //continue executing //get next Position to go to Position goal = path->getPosition(0); if (alreadyFound || isArrived(goal)) { //check if at goal alreadyFound = true; //now execute moves //if (path->numOfMoves(0) > 0) if (executeMove(false)) { //take position off list path->removePosition(0); lastLocation = robotLocation; alreadyFound = false; } } else motor->goTo(goal); } //end continue executing return false; } //end if Path != NULL return true; } //bool PathExecuter::move(double distance, double rotation); void PathExecuter::setMotion(Motion m) { motor->setMotion(m); motor->update(); } void PathExecuter::halt() { motor->halt(); } void PathExecuter::setMotor(Motor& motor) { this->motor = &motor; } void PathExecuter::setPath(Path& path) { abandonPath(); this->path = &path; this->lastLocation = robotLocation; this->alreadyFound = false; } void PathExecuter::setLocal(Position pos) { robotLocation = pos; } bool PathExecuter::isArrived(Position goal) { double ACCURACY = 0.10; double DEG_ACCURACY = 0.1; if (robotLocation.calcDistTo(goal) <= ACCURACY) { if (std::abs(robotLocation.yaw*(180.0/M_PI) - goal.yaw*(180.0/M_PI)) <= DEG_ACCURACY) return true; } return false; } void PathExecuter::abandonPath() { //delete old path if not already deleted if (path != NULL) { delete path; path = NULL; } } std::string PathExecuter::toString() { return "PathExecuter"; }
true
bedd5c6c74ff9f7bd648af6a95681d53179849da
C++
jasonpfi/AlgoProject1b
/fitsmu-1b/fitsmu-1b/response.h
UTF-8
616
3.125
3
[]
no_license
// Project 1b // // Team: fitsmu // Jason Fitch // Sam Smucny // response.h: Header file defining the Response class // // This class holds the response to a guess: // - The number correct // - The number incorrect #include <iostream> class response { public: // Constructors response(const int& numberCorrect, const int& numberIncorrect); response(); // Setters void setNumCorrect(const int& numberCorrect); void setNumIncorrect(const int& numberIncorrect); // Getters int getNumCorrect() const; int getNumIncorrect() const; private: // Private data members int numberCorrect; int numberIncorrect; };
true
41ccfc38dec3d8bc7487fa7e076120286fef5e6d
C++
mars0522/Coding-Ninjas
/FamilyStructure.cpp
UTF-8
489
2.875
3
[]
no_license
string fun(int n, long long int k) { if (n == 1 or k == 1) return "Male"; else { long long int p = (k + 1) / 2; string ans = fun(n - 1, p); if (k == 2 * p - 1) return ans; else { if (ans == "Male") return "Female"; else return "Male"; } } } string kthChildNthGeneration(int n, long long int k) { // Write your code here return fun(n, k); }
true
225ba764a0728ecf9e4a51a9b25d3ae80e57ddb6
C++
asutosh97/college-labs
/6th-sem/OS/lab4/generalized.cpp
UTF-8
3,790
3.359375
3
[]
no_license
#include <iostream> #include <cstdlib> #include <vector> #include <queue> #include <algorithm> using namespace std; int greater(int a,int b) { return a > b; } class Process { public: int id, burst_time, arrival_time, waiting_time, turn_around_time, time_left, rr_priority, priority_value; // Process Constructor Process(int id, int burst_time, int arrival_time = 0, int priority_value = 0, int waiting_time = 0, int turn_around_time = 0) { this -> id = id; this -> burst_time = burst_time; this -> arrival_time = arrival_time; this -> waiting_time = waiting_time; this -> turn_around_time = turn_around_time; this -> time_left = burst_time; this -> rr_priority = 0; this -> priority_value = priority_value; } }; struct comparator { inline bool operator() (const Process& lhs, const Process& rhs) { /* for FCFS --> arrival_time for SJF --> burst_time for SRTF --> time_left for Priority --> priority_value for RR --> rr_priority */ return (lhs.priority_value > rhs.priority_value); } }; void insert_to_pq(priority_queue < Process,vector<Process>, comparator >& p, Process _p, int &priority_counter) { _p.rr_priority = ++priority_counter; p.push(_p); } void setQueue(priority_queue < Process,vector<Process>, comparator >& p, vector<Process>& vec,int timer, int &priority_counter) { for(auto i: vec) { if(i.arrival_time == timer) { insert_to_pq(p, i, priority_counter); } } } vector<Process> generalized(vector<Process>& vec, int tq, bool pre_emptive) { vector<Process> result; int priority_counter = 0; int timer = 0; priority_queue < Process,vector<Process>, comparator > p; // initialize pqueue with processes arrived at t = 0 setQueue(p, vec, timer, priority_counter); int process_left = vec.size(); while(process_left) { // if pqueue is not empty if (!p.empty()) { Process p1 = p.top(); p.pop(); // if non-preemptive, run till completion, else run till minimum of time quantum and time left int run_time = pre_emptive? min(tq, p1.time_left) : p1.time_left; p1.time_left = p1.time_left - run_time; int old_timer = timer; timer += run_time; // add the processes that have come while p1 was executed to the pqueue for (int i = old_timer + 1; i <= timer; i++) setQueue(p, vec, i, priority_counter); // if p1 completed, add it to result if(p1.time_left == 0){ p1.turn_around_time = timer - p1.arrival_time; p1.waiting_time = p1.turn_around_time - p1.burst_time; process_left--; result.push_back(p1); } // if p1 not completed, insert it to pqueue again else { insert_to_pq(p, p1, priority_counter); } } // if pqueue is empty, time lapse 1 unit and add the newly arrived processes else { timer++; setQueue(p,vec, timer, priority_counter); } } return result; } int main() { Process p1(1,11,0,2); Process p2(2,28,5,0); Process p3(3,2,12,3); Process p4(4,10,2,1); Process p5(5,16,9,4); vector<Process> vec; vec.push_back(p1); vec.push_back(p2); vec.push_back(p3); vec.push_back(p4); vec.push_back(p5); int tq = 1; bool pre_emptive = false; vector<Process> result = generalized(vec, tq, pre_emptive); for(auto i:result){ cout << "pid :" << i.id << endl; cout << "Waiting Time :" << i.waiting_time << endl; cout << "Turn Around Time :" << i.turn_around_time << endl; //cout << "Waiting Time :" << i.waiting_time << endl; } return 0; }
true
cb0dfeecffc52ba3eb745e903b65804ab4836a47
C++
hantingt/Demo_PWA
/GPUPWA/GPUPWA/GPUTensor.h
UTF-8
1,069
3.5625
4
[]
no_license
/// \file GPUTensor.h #pragma once #include <iostream> #include <cassert> #include <cstdlib> #include <vector> ///Base class for GPU based Tensors /** This is the base class for all GPU based Tensor calculations, it mainly serves as an abstraction for calculation input, in order to allow for the operater notation in user programs. A priori, GPUTensors have just one property, namely their rank. The constructors are protected to ensure only derived objects can be instantiated. */ class GPUTensor { public: /// Destructor virtual ~GPUTensor(void){}; /// Number of elements in the tensor int Size() const { return (1 << (mrank << 1)); }; /// Get the Tensors rank int Rank() const {return mrank;}; protected: /// Default Costructor -> Rank 0 GPUTensor(void):mrank(0) {}; // ,mlength(1,0) /// Costructor with Rank GPUTensor(int _rank):mrank(_rank) {}; //,mlength(1,0) /// Assert tensors have the same rank inline void RankAssert (const GPUTensor & _tbase) const { assert(this->mrank == _tbase.mrank);}; /// Rank of the tensor const int mrank; };
true
152b2c65213e949253368a3161c145ba23053333
C++
KitwareMedical/SlicerSkeletalRepresentation
/SRep/MRML/vtkMRMLSRepStorageNode.h
UTF-8
2,388
2.515625
3
[ "Apache-2.0" ]
permissive
#ifndef __vtkMRMLSRepJsonStorageNode_h #define __vtkMRMLSRepJsonStorageNode_h #include "vtkSlicerSRepModuleMRMLExport.h" #include "vtkMRMLStorageNode.h" #include "vtkMRMLSRepNode.h" class VTK_SLICER_SREP_MODULE_MRML_EXPORT vtkMRMLSRepStorageNode : public vtkMRMLStorageNode { public: static vtkMRMLSRepStorageNode *New(); vtkTypeMacro(vtkMRMLSRepStorageNode, vtkMRMLStorageNode); vtkMRMLNode* CreateNodeInstance() override; /// Get node XML tag name (like Storage, Model) const char* GetNodeTagName() override {return "SRepStorage";}; bool CanReadInReferenceNode(vtkMRMLNode *refNode) override; /// Creates a new SRep node with the given name and the file set by SetFileName. /// /// SRep is created in the same scene as this storage node. vtkMRMLSRepNode* CreateSRepNode(const char* nodeName); /// Gets the MRML node type of the SRep with the given file name /// /// The return value, if not empty, is suitable to be passed into /// vtkMRMLScene::AddNewNodeByClass as the class name for the same /// scene this node is in. /// \returns MRML node type of srep, empty string if no file name is set. std::string GetSRepType(); using SRepCoordinateSystemType = int; /// @{ /// Get set the coordinate system to write in. /// /// Choose either vtkMRMLStorageNode::CoordinateSystemRAS or vtkMRMLStorageNode::CoordinateSystemLPS /// Default is LPS. void SetCoordinateSystemWrite(SRepCoordinateSystemType system); SRepCoordinateSystemType GetCoordinateSystemWrite() const; void CoordinateSystemWriteRASOn(); void CoordinateSystemWriteLPSOn(); /// @} protected: vtkMRMLSRepStorageNode(); ~vtkMRMLSRepStorageNode() override; vtkMRMLSRepStorageNode(const vtkMRMLSRepStorageNode&) = delete; vtkMRMLSRepStorageNode(vtkMRMLSRepStorageNode&&) = delete; void operator=(const vtkMRMLSRepStorageNode&) = delete; void operator=(vtkMRMLSRepStorageNode&&) = delete; /// Initialize all the supported write file types void InitializeSupportedReadFileTypes() override; /// Initialize all the supported write file types void InitializeSupportedWriteFileTypes() override; /// Read data and set it in the referenced node int ReadDataInternal(vtkMRMLNode *refNode) override; /// Write data from a referenced node. int WriteDataInternal(vtkMRMLNode *refNode) override; private: int CoordinateSystemWrite; }; #endif
true
74dacd9970ed7839f781a7d8ccda3bf8b945136c
C++
hsmsek2019/CENG101
/Dosya islemleri/main.cpp
ISO-8859-9
1,528
2.828125
3
[]
no_license
#include<stdio.h> int main(){ /* FILE *fptr; int deger; fptr = fopen("deneme.txt", "r"); //fprintf(fptr, "\n%d", deger); fscanf(fptr, "%d", &deger); printf("Dosyadan okunan deger: %d\n", deger); fclose(fptr); */ // sayilar1.txt oluturalm. // ine 100 adet int atayalm /* FILE *fptr; fptr = fopen("sayilar1.txt", "w"); for(int i=0; i<100; i++){ fprintf(fptr, "%d ", i); } fclose(fptr); */ // sayilar1.txt deki sayilarn ortalamasn bulalm /* FILE *fptr; fptr = fopen("sayilar1.txt", "r"); int tmp=0; int toplam=0; for(int i=0; i<100; i++){ fscanf(fptr, "%d ", &tmp); toplam += tmp; } fclose(fptr); float ort = toplam / 100.0; printf("sayilar1.txt'nin ortalamasi: %f\n", ort); */ // while(!feof(fptr)){} /* FILE *fptr; fptr = fopen("sayilar1.txt", "r"); int tmp=0; int counter = 0; int toplam=0; while(!feof(fptr)){ fscanf(fptr, "%d ", &tmp); toplam += tmp; counter++; } fclose(fptr); float ort = toplam / (float)counter; printf("sayilar1.txt'nin ortalamasi: %f\n", ort); */ // ornek girdi satiri: //103442537 zahid kizmaz 50 60 /* FILE *fptr; fptr = fopen("notlar.txt", "r"); char no[15], isim[25], soyisim[35]; int vize=0, finl=0; while(!feof(fptr)){ fscanf(fptr, "%s %s %s %d %d\n",no, isim, soyisim, &vize, &finl); float ort = (vize * 0.4 + finl * 0.6); printf("Ogrenci Adi Soyadi: %s %s \t Ortalamasi: %.2f\n", isim, soyisim, ort); } fclose(fptr); */ return 0; }
true
b63af0670a27de1e24f73cce511fafa28033cacf
C++
hishamcse/CSE-203_204_DSAlgoI
/CSE 204/Week 8/1805004_C++/MissionController.h
UTF-8
2,989
3.125
3
[]
no_license
#ifndef INC_1805004_C___MISSIONCONTROLLER_H #define INC_1805004_C___MISSIONCONTROLLER_H #include <iostream> #include <vector> #include <string> using namespace std; class MissionController { CustomGraph *graph; vector<Location> locations; vector<Friend> friends; int noOfFriends; int noOfTotalPieces; bool checkInvalidCity(int city); bool checkInvalidFriend(int friendId) const; public: MissionController(int vertices, int noOfFriends); void addEdge(int vertex, int other); void addLocation(int city, int noOfPieces); void addFriend(int city, int friendId); string solveByDFS(); string solveByBFS(); }; MissionController::MissionController(int vertices, int noOfFriends){ this->noOfFriends = noOfFriends; graph = new CustomGraph(vertices); noOfTotalPieces = 0; } bool MissionController::checkInvalidCity(int city) { return city < 0 || city >= graph->getTotalVertices(); } bool MissionController::checkInvalidFriend(int friendId) const { return friendId < 0 || friendId > noOfFriends; } void MissionController::addEdge(int vertex, int other) { graph->edgeAddition(vertex, other); } void MissionController::addLocation(int city, int noOfPieces) { if (checkInvalidCity(city)) { throw exception("Invalid City"); } Location location(city, noOfPieces); locations.push_back(location); noOfTotalPieces += noOfPieces; } void MissionController::addFriend(int city, int friendId) { if (checkInvalidCity(city) || checkInvalidFriend(friendId)) { throw exception("Invalid City or Invalid Friend"); } Friend f(friendId, city); friends.push_back(f); } string MissionController::solveByDFS() { DFSTraversal dfs(*graph, locations, friends); int totalCollected = dfs.getTotalCollected(); string sb; sb.append(totalCollected == noOfTotalPieces ? "Mission Accomplished" : "Mission Impossible").append("\n"); sb.append(to_string(totalCollected)).append(" out of ").append(to_string(noOfTotalPieces)).append( " pieces are collected").append("\n"); for (Friend &f : friends) { sb.append(to_string(f.id)).append(" collected ").append(to_string(dfs.getCollectedIndividual(f.id))).append( " pieces").append("\n"); } return sb; } string MissionController::solveByBFS() { BFSTraversal bfs(graph, locations, friends); int totalCollected = bfs.getTotalCollected(); string sb; sb.append(totalCollected == noOfTotalPieces ? "Mission Accomplished" : "Mission Impossible").append("\n"); sb.append(to_string(totalCollected)).append(" out of ").append(to_string(noOfTotalPieces)).append( " pieces are collected").append("\n"); for (Friend &f : friends) { sb.append(to_string(f.id)).append(" collected ").append(to_string(bfs.getCollectedIndividual(f.id))).append( " pieces").append("\n"); } return sb; } #endif //INC_1805004_C___MISSIONCONTROLLER_H
true
6cc010621259d95cf28ab272a89da573b13459c1
C++
gaurav1620/CodeChef-1
/START01.cpp
UTF-8
220
2.578125
3
[]
no_license
#include<iostream> using namespace std; int main() { int n; cin>>n; if(0 <= n && n <= 100000) cout<<n<<endl; else cout<<"Constraints do not match ( 0 <= n <= 10^5)"<<endl; return 0; }
true
0c2699be2c338248d4a9d110125bf4ff3cf641eb
C++
anubhav-pandey1/Recursion
/Backtracking/sudokusolver.cpp
UTF-8
14,560
3.8125
4
[]
no_license
#include <bits/stdc++.h> using namespace std; bool checkInsertion(vector<vector<char>>& board, int row, int col, char test) { int topRow = 3 * (row / 3); // Top-row of a subgrid for a given value of rowCheck int leftCol = 3 * (col / 3); // Left-col of a subgrid for a given value of colCheck for (int x = 0; x < 9; x++) { // 9 comparisions required for the cell's row/col/subgrid if (board[row][x] == test) { // Check for test in the row of the cell, keeping row fixed return false; } if (board[x][col] == test) { // Look for test in the col of the cell, keeping col fixed return false; } if (board[topRow + (x / 3)][leftCol + (x % 3)] == test) { // Toprow + (0, 1, 2, .., 8) / 3 gives all the 3 row values in the subgrid return false; // It remains 0 for {0, 1, 2}, becomes 1 for {3, 4, 5} and 2 for {6, 7, 8} } // Leftcol + (0, 1, 2, .., 8) % 3 gives all the 3 col values in the subgrid } // It is 0 for {0, 3, 6}, becomes 1 for {1, 4, 7} and 2 for {2, 5, 8} return true; } bool solveSudoku(vector<vector<char>>& board) { // Can track row and col for more efficient implementation for (int r = 0; r < 9; r++) { // Looping a 2-D matrix to find the next empty cell to fill for (int c = 0; c < 9; c++) { // Base case will hit after both the loops have ended ie. no more cells to check if (board[r][c] == '.') { // Check if the cell is empty, otherwise move to next value of c for (char n = '1'; n <= '9'; n++) { // These chars represent our choices to fill the board, '1' + 1 == '2' if (checkInsertion(board, r, c, n)) { // Check if the char n can be inserted in the board at (r, c) board[r][c] = n; // If true, insert n in the board at (r, c) and prepare for recursive step // bool flag = sudokuSolver(board); // A flag based implementation can also be used inside the if() (flag == true) if (solveSudoku(board) == true) { // Recursive call inside the checkInsertion{}, else it will fill the next eligible n return true; // If recursive call returns true, you return true back to the upper call } // Can get stack overflow if recursion not inside cI{} as it will execute for n even when cI(n) is false else { // If true not returned from lower levels -> base case not hit -> wrong route taken board[r][c] = '.'; // Backtracking step: Revert the insertion of n if false and move to the next n value } // This must be inside the cI{} as well, complementing the boolean recursive call } // Check the next value of n, unless the recursion has already fallen to base case } // If none of the n values can be filled, return false so that it can backtrack further return false; // This false is not returned if recursion falls to the base case, starts returning trues back } // Once it starts returning trues for all preceeding calls, the main call will return true and end } // A dry-run is must to understand this weird recursive pattern without a clearly visible base case } // Also, instead of precalculating the index of empty cell, recursion is in the searching loops return true; // Base case:- After r == 8 and c == 8, it skips return false and jumps to this value } // If there are no more empty cells left, it also jumps straight to the base case // Slightly more efficient implementation, tracking row and col, but not worth it // Instead of starting search at r = 0 and c = 0, start it at row and col // (8 + row) % row == row except when row == 8, it wraps back to 0 // (8 + col) % col == col except when col == 8, it wraps back to 0 // This means for the last row, it starts search from (0, c) and then goes to the next still empty spot // Also, when c == 8, it starts the search from (r, 0) and then goes to the next still empty spot // (8, c) and (r, 8) will get missed in this implementation if search is not start from (0, c) and (r, 0) // r + (c/8) == r, unless c == 8, in which case it becomes r + 1 // (c + 1) % 9 == c + 1, unless c == 8, in which case it becomes 0 // solveSudoku(board, r + (c / 8), (c + 1) % 9) is basically solveSudoku(board, r, c) unless c == 8 bool solveSudoku(vector<vector<char>>& board, int row = 0, int col = 0) { for (int r = (8 + row) % 8; r < 9; r++) { for (int c = (8 + col) % 8; c < 9; c++) { if (board[r][c] == '.') { for (char n = '1'; n <= '9'; n++) { if (checkInsertion(board, r, c, n)) { board[r][c] = n; if (solveSudoku(board, r + (c / 8), (c + 1) % 9) == true) { return true; } else { board[r][c] = '.'; } } } return false; } } } return true; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif int testNum; cin >> testNum; while (testNum--) { vector<vector<char>> board; for (int r = 0; r < 9; r++) { vector<char> line; for (int c = 0; c < 9; c++) { char num; cin >> num; line.push_back(num); } board.push_back(line); } // for (int r = 0; r < 9; r++) { // for (int c = 0; c < 9; c++) { // cout << checkInsertion(board, r, c, '4') << " "; // } // cout << endl; // } // cout << "_________________" << endl; solveSudoku(board, 0, 0); for (auto& vec : board) { for (char& ch : vec) { cout << ch << " "; } cout << endl; } cout << "_________________" << endl; } return 0; } // My correct, but less efficient and inconcise implementation with bloated logic: // bool checkInsertion(vector<vector<char>>& board, int rowCheck, int colCheck, int test) { // char num = '0' + test; // Test needs to be input since we check before changing board // if (board[rowCheck][colCheck] != '.') { // Safety condition: Don't fill if not empty // return false; // } // if (test > 9 || test < 1) { // Safety condition: Don't fill if input incorrect // return false; // } // for (int x = 0; x < 9; x++) { // Check entire colCheck (all rows) and rowCheck (all cols) for test // if (x != rowCheck) { // x is a row, check all rows except the one cell where we will input // if (board[x][colCheck] == num) { // Check if any cell (using rows) in the col colCheck is equal to test // return false; // } // } // if (x != colCheck) { // x is a col, check all cols except the one cell where we will input // if (board[rowCheck][x] == num) { // Check if any cell (using cols) in the row rowCheck is equal to test // return false; // } // } // } // int topRow = 3 * (rowCheck / 3); // Top-line of a subgrid for a given value of rowCheck // int leftCol = 3 * (colCheck / 3); // Left-line of a subgrid for a given value of colCheck // for (int r = topRow; r <= topRow + 2; r++) { // Total 9 iterations in subgrid, from topline to topline + 2 (3 rows).. // for (int c = leftCol; c <= leftCol + 2; c++) { // and leftline to leftine + 2 (3 cols per row). Can we merge with x-loop? // if (r != rowCheck && c != colCheck) { // if (board[r][c] == num) { // return false; // } // } // } // } // return true; // If not in row, col or subgrid, return true // } // void sudokuSolver(vector<vector<char>>& board, int r, int c, bool& flag) { // Flag by-ref to notify when base case is hit to avoid further backtracking // if (r > 8) { // Base case: Only when all rows have been covered, next call to r = 9 made // // cout << "Base case: (" << r << ", " << c << ")" << endl; // Other base cases based on c = 9 are incorrect since we explicitly avoid c > 8 // flag = true; // Modify flag to notify base case is hit (Can we do this better?) // return; // } // while (board[r][c] != '.') { // Loop to take our pointer to next empty cell (Separate from induction steps?) // if (r == 8 && c == 8) { // Necessary to terminate at the last cell of the board, else base case gets hit early // // cout << "breaking at (8, 8)" << endl; // break; // } // if (c < 8) { // Increase c while possible, else reset it to 0 and increase r // c++; // Can this be done better? Notice the cyclicity in c and use modulus % // } // else { // c = 0; // r++; // } // } // for (int n = 1; n <= 9; n++) { // This loop reflects our choices ie. inserting 1 to 9 in the cells // if (checkInsertion(board, r, c, n)) { // If safe to insert n at (r,c).. // board[r][c] = ('0' + n); // Do it, then call the next insertion recursively // // cout << "(" << r << ", " << c << ") = " << n << endl; // if (c == 8) { // If at the last col in a row, begin checking from the next row, 0th col // sudokuSolver(board, r + 1, 0, flag); // } // else { // Else, begin checking from the next col in the current row // sudokuSolver(board, r, c + 1, flag); // } // } // if (flag == false) { // Backtracking step: Only valid while base case is not hit, otherwise result will be reversed // board[r][c] = '.'; // Will help restore the original board if we get out of checkInsertion() when it did not work out // // cout << "(" << r << ", " << c << ") = ." << endl; // If it did work out, we will keep calling recursively till the base case gets hit // } // We will only come out of checkInsertion() wit flag = false if it did not work out down the line // } // In which case, we must reverse this particular insertion and go back to previous call to find a new route // } // vector<vector<char>> solveSudoku(vector<vector<char>>& board) { // bool flag = false; // sudokuSolver(board, 0, 0, flag); // return board; // } // Test cases: // Inputs: // 3 // ..9748... // 7........ // .2.1.9... // ..7...24. // .64.1.59. // .98...3.. // ...8.3.2. // ........6 // ...2759.. // 53..7.... // 6..195... // .98....6. // 8...6...3 // 4..8.3..1 // 7...2...6 // .6....28. // ...419..5 // ....8..79 // ...2...63 // 3....54.1 // ..1..398. // .......9. // ...538... // .3....... // .263..5.. // 5.37....8 // 47...1... // Outputs: // 5 1 9 7 4 8 6 3 2 // 7 8 3 6 5 2 4 1 9 // 4 2 6 1 3 9 8 7 5 // 3 5 7 9 8 6 2 4 1 // 2 6 4 3 1 7 5 9 8 // 1 9 8 5 2 4 3 6 7 // 9 7 5 8 6 3 1 2 4 // 8 3 2 4 9 1 7 5 6 // 6 4 1 2 7 5 9 8 3 // _________________ // 5 3 4 6 7 8 9 1 2 // 6 7 2 1 9 5 3 4 8 // 1 9 8 3 4 2 5 6 7 // 8 5 9 7 6 1 4 2 3 // 4 2 6 8 5 3 7 9 1 // 7 1 3 9 2 4 8 5 6 // 9 6 1 5 3 7 2 8 4 // 2 8 7 4 1 9 6 3 5 // 3 4 5 2 8 6 1 7 9 // _________________ // 8 5 4 2 1 9 7 6 3 // 3 9 7 8 6 5 4 2 1 // 2 6 1 4 7 3 9 8 5 // 7 8 5 1 2 6 3 9 4 // 6 4 9 5 3 8 1 7 2 // 1 3 2 9 4 7 8 5 6 // 9 2 6 3 8 4 5 1 7 // 5 1 3 7 9 2 6 4 8 // 4 7 8 6 5 1 2 3 9 // _________________
true
93fa50960aa274b935200342a70317d8086bc953
C++
swertz/MEMcpp
/interface/binnedTF.h
UTF-8
1,642
2.65625
3
[]
no_license
#ifndef _INC_BINNEDTF #define _INC_BINNEDTF #include <string> #include <algorithm> #include "TH2.h" #include "TFile.h" class BinnedTF{ public: BinnedTF(const std::string particleName, const std::string histName, TFile* file); ~BinnedTF(); inline double Evaluate(const double &Erec, const double &Egen) const; inline double GetDeltaRange(const double &Erec) const; inline double GetDeltaMin(const double &Erec) const; inline double GetDeltaMax(const double &Erec) const; private: std::string _particleName; double _histDeltaMin, _histDeltaMax; double _deltaMin, _deltaMax, _deltaRange; double _EgenMax, _EgenMin; const TH2D* _TF; }; inline double BinnedTF::Evaluate(const double &Erec, const double &Egen) const { //std::cout << "Evaluating TF for particle " << _particleName << ": Erec = " << Erec << ", Egen = " << Egen << std::endl; double delta = Erec - Egen; if(Egen < _EgenMin || Egen > _EgenMax || delta > _deltaMax || delta < _deltaMin){ //std::cout << "... Out of range!" << std::endl; return 0.; } // Use ROOT's global bin number "feature" for 2-dimensional histograms const int bin = _TF->FindFixBin(Egen, delta); //std::cout << ", TF = " << _TF->GetBinContent(bin) << std::endl; return _TF->GetBinContent(bin); } inline double BinnedTF::GetDeltaRange(const double &Erec) const { return GetDeltaMax(Erec) - GetDeltaMin(Erec); } inline double BinnedTF::GetDeltaMin(const double &Erec) const { return std::max(_deltaMin, Erec - _EgenMax); } inline double BinnedTF::GetDeltaMax(const double &Erec) const { return std::min(_deltaMax, Erec - _EgenMin); } #endif
true
91426933e555c216373c44185607efbcaf82324b
C++
SR-Sunny-Raj/Hacktoberfest2021-DSA
/05. Searching/jump_search.cpp
UTF-8
1,114
3.40625
3
[ "MIT" ]
permissive
#include <iostream> #include <cmath> using namespace std; #define MAX 100 int search(int key); int a[MAX],n; int main() { int i,key,result; cout<<"\nEnter the number of elements: "; cin>>n; cout<<"\nEnter the elements of array: \n"; for(i=0;i<n;i++) { cin>>a[i]; } cout<<"\n\nEnter the key you want to search: "; cin>>key; result=search(key); if(result==-1) { cout<<"\nElement is not found in the array !\n"; } else { cout<<"\nElement "<<key<<" is present at position "<<result; } return 0; } int search(int key) { int jump_step,prev=0; jump_step=floor(sqrt(n)); while(a[prev]<key) { if(a[jump_step]>key || jump_step>=n) { break; } else { prev=jump_step; jump_step=jump_step+floor(sqrt(n)); } } while(a[prev]<key) { prev++; } if(a[prev]==key) { return prev+1; } else { return -1; } }
true
b85d5073d7aff7f4d974f5a89a547764bab3582c
C++
ShanzhongXinzhijie/DemolisherWeapon
/DemolisherWeapon/system/GameObject.h
SHIFT_JIS
15,149
2.75
3
[]
no_license
#pragma once #include <unordered_map> #include "../util/Util.h" namespace DemolisherWeapon { class IGameObject; class GameObjectManager; class GONewDeleteManager; class GOStatusReceiver; //Q[IuWFNgXe[^X struct GOStatus { bool m_isDead = false;//ɂ܂? }; //Xe[^XLX^[ class GOStatusCaster { public: GOStatusCaster(GOStatusReceiver* receiver) { m_receiver = receiver; } ~GOStatusCaster(); void ImDead() { m_alive = false; } bool GetAlive()const { return m_alive; } void Cast(const GOStatus& status); const GOStatusReceiver* const GetReceiver() const{ return m_receiver; } private: GOStatusReceiver* m_receiver = nullptr; bool m_alive = true; }; //Xe[^XV[o[ class GOStatusReceiver { public: ~GOStatusReceiver() { if(m_registerCaster) m_registerCaster->ImDead(); } //Ȃ񂩏ݒ //[U[͎gȂł void SetCaster(GOStatusCaster* caster) { m_registerCaster = caster; } //[U[͎gȂł void SetGameObject(IGameObject* go) { m_ptrGO = go; } //Xe[^XXV //[U[͎gȂł void SetStatus(const GOStatus& status) { m_status = status; } //͎gȂ //牺gĂ //Xe[^X{ const GOStatus& GetStatus()const { return m_status; } //Xe[^X̃Q[IuWFNg擾 IGameObject* GetGameObject()const { return m_ptrGO; } private: GOStatus m_status; IGameObject* m_ptrGO = nullptr; GOStatusCaster* m_registerCaster = nullptr; }; class GODeathListener; //SXi[o^NX struct GODeathListenerRegister { GODeathListenerRegister(GODeathListener* listener_ptr) { listener = listener_ptr; } ~GODeathListenerRegister(); bool enable = true; GODeathListener* listener = nullptr; }; //SXi[ class GODeathListener { public: ~GODeathListener() { if (m_resister) { m_resister->enable = false; } } //fXXi[̈ struct SDeathParam { IGameObject* gameObject = nullptr; }; //SʒmɎs֐ݒ void SetFunction(std::function<void(const SDeathParam& param)> func) { m_function = func; } //[U[͎gȂł void SetResister(GODeathListenerRegister* resister) { m_resister = resister; } //[U[͎gȂł void RunFunction(const SDeathParam& param) { m_function(param); } private: std::function<void(const SDeathParam& param)> m_function; GODeathListenerRegister* m_resister = nullptr; }; //Q[IuWFNgo^NX struct GORegister { GORegister(IGameObject* go, bool isQuickStart) : isEnableGO(true), isNoPendingkill(true), m_isQuickStartGO(isQuickStart), gameObject(go) {} bool isEnableGO = false;//Q[IuWFNgLԂ bool isStartedGO = false;//Q[IuWFNgStart֐sς݂ bool isNoPendingkill = false;//폜ԂłȂ private: IGameObject* gameObject = nullptr; bool nowOnHell = false;//GameObjectManager̍폜}[Np bool m_isQuickStartGO = false; bool GetIsStart(); //@GameObjectManager瑀ł friend GameObjectManager; }; class IDW_Class { public: virtual ~IDW_Class() {}; }; //Q[IuWFNg class IGameObject : public IDW_Class { public: IGameObject(bool isRegister = true, bool quickStart = false); virtual ~IGameObject(); IGameObject(const IGameObject& go) = delete;//Rs[RXgN^ IGameObject& operator=(const IGameObject&) = delete; IGameObject(IGameObject&&)noexcept = delete;// {};//[uRXgN^ IGameObject& operator=(IGameObject&&)noexcept = delete;// {}; private: //Jn void SetIsStart() { m_isStart = true; m_register->isStartedGO = true; OffIsRunVFunc(enStart);//sXg } //o^ void RegisterRegister(GORegister* regi) { m_register = regi; } //WX^[擾 GORegister* GetRegister()const { return m_register; } //Xe[^XV[o[ɑ void CastStatus() { auto it = m_statusCaster.begin(); auto endit = m_statusCaster.end(); while (it != endit) { if ((*it).GetAlive()) { (*it).Cast(m_status); it++; } else { it = m_statusCaster.erase(it);//폜 } } } //NewGOōƂ}[N‚ void MarkNewGOMark() { m_newgoMark = true; } //DeleteGOꂽ void O͂ł() { m_isDead = true; UpdateRegisterIsEnable(); } public: //NewGOō? bool GetNewGOMark() const { return m_newgoMark; } //DeleteGOĂ? bool O͂łH() const{ return m_isDead; } //L //TODO WX^[Q void SetEnable(bool e){ m_enable = e; UpdateRegisterIsEnable(); } //LȂ̂H bool GetEnable() const{ return m_enable && !m_isDead; } //z֐̗񋓎q enum VirtualFuncs { enStart, enPreLoopUpdate, enPreUpdate, enUpdate, enPostUpdate, enPostLoopUpdate, enPostLoopPostUpdate, enPre3DRender, enHUDRender, enPostRender, enVirtualFuncNum }; //z֐I[o[ChĂ邩? bool GetIsOverrideVFunc(VirtualFuncs funcType)const { return m_isRunFunc[funcType]; } //JnĂ̂H bool GetIsStart(){ if (m_quickStart) { if (GetEnable() && !m_isStart) { if (Start()) { SetIsStart(); } } } return m_isStart; } //NCbNX^[gݒ肩擾 bool GetIsQuickStart()const { return m_quickStart; } //o^Ă邩? bool IsRegistered() const{ if (m_register) { return true; } return false; } //Xe[^XV[o[o^ void AddStatusReceiver(GOStatusReceiver* receiver) { m_statusCaster.emplace_back(receiver); receiver->SetStatus(m_status); receiver->SetCaster(&m_statusCaster.back()); receiver->SetGameObject(this); } //Xe[^XV[o[o^ void RemoveStatusReceiver(GOStatusReceiver* receiver) { for (auto& C : m_statusCaster) { if (C.GetReceiver() == receiver) { C.ImDead(); } } } //SXi[o^ void AddDeathListener(GODeathListener* listener) { m_deathListeners.emplace_back(listener); listener->SetResister(&m_deathListeners.back()); } //SXi[o^ void RemoveDeathListener(GODeathListener* listener) { for (auto& R : m_deathListeners) { if (R.listener == listener) { R.enable = false; } } } //O‚ void SetName(const wchar_t* objectName); private: //z֐̎s߂ void OffIsRunVFunc(VirtualFuncs type); //WX^[IsEnableXV void UpdateRegisterIsEnable() { m_register->isEnableGO = GetEnable(); } public: //z֐ //JnɎs //߂lfalseƏJnȂ virtual bool Start() { OffIsRunVFunc(enStart); return true; } //Q[[vOɎs virtual void PreLoopUpdate() { OffIsRunVFunc(enPreLoopUpdate); } //Q[[vŎs virtual void PreUpdate() { OffIsRunVFunc(enPreUpdate); } virtual void Update() { OffIsRunVFunc(enUpdate); } virtual void PostUpdate() { OffIsRunVFunc(enPostUpdate); } //Q[[vɎs virtual void PostLoopUpdate() { OffIsRunVFunc(enPostLoopUpdate); } virtual void PostLoopPostUpdate() { OffIsRunVFunc(enPostLoopPostUpdate); } //3D`OɎs(ʂ) //int num s̉ʔԍ virtual void Pre3DRender(int num) { OffIsRunVFunc(enPre3DRender); } //̊֐HUD2DOtBbN` //int HUDNum `ΏۂHUD̔ԍ virtual void HUDRender(int HUDNum) { OffIsRunVFunc(enHUDRender); } //2DOtBbN̊֐ŕ`悵Ă //CFont,CSpriteȂ virtual void PostRender() { OffIsRunVFunc(enPostRender); } private: bool m_isDead = false;//S bool m_enable = true; bool m_isStart = false; bool m_quickStart = false; bool m_isRunFunc[enVirtualFuncNum];//z֐I[o[ChĂ邩?(s邩) GORegister* m_register = nullptr;//}l[W[ɓo^Ă邩(|C^) GOStatus m_status;// std::list<GOStatusCaster> m_statusCaster;//Ԃ𑗐M std::list<GODeathListenerRegister> m_deathListeners;//SXi[B bool m_newgoMark = false;//NewGOō? //@GameObjectManager瑀ł friend GameObjectManager; friend GONewDeleteManager; }; //œo^ȂQ[IuWFNg class INRGameObject : public IGameObject{ public: INRGameObject(bool quickStart = false) : IGameObject(false, quickStart) {}; virtual ~INRGameObject() {}; }; //ł葁JnQ[IuWFNg class IQSGameObject : public IGameObject { public: IQSGameObject(bool isRegister = true) : IGameObject(isRegister, true) {}; virtual ~IQSGameObject() {}; }; //Q[IuWFNg̃}l[W[ //Q[IuWFNgUpdateƂĂяo class GameObjectManager { public: ~GameObjectManager() { for (auto& go : m_gameObjectList) { if (go.isNoPendingkill) { go.gameObject->RegisterRegister(nullptr); } } } void Start(); void PreLoopUpdate(); void Update(); void PostLoopUpdate(); void Pre3DRender(int num); void HUDRender(int HUDNum); void PostRender(); //̏ void Hell(); private: //֐sXgQ[IuWFNgQƂ폜 void DeleteFromFuncList(); public: //̃t[GO폜ꂽ void EnableIsDeleteGOThisFrame() { m_isDeleteGOThisFrame = true; } //̃t[ɉz֐̎smFꂽ void EnableIsCheckVFuncThisFrame(IGameObject::VirtualFuncs ind) { m_isCheckVFuncThisFrame[ind] = true; } //Q[IuWFNg̓o^ void AddGameObj(IGameObject* go) { if (go == nullptr) { return; } //do^h if (go->IsRegistered()) { return; } //Q[IuWFNgXgo^ m_gameObjectList.emplace_back(go,go->GetIsQuickStart()); //Q[IuWFNgGORegistero^ go->RegisterRegister(&m_gameObjectList.back()); //s֐XgփQ[IuWFNgo^ //TODO NCbNX^[gXg for (auto& list : m_runFuncGOList) { list.emplace_back(&m_gameObjectList.back()); } } //Q[IuWFNgɖO‚ void SetNameGO(IGameObject* go, const wchar_t* objectName) { if (!go) { return; } GORegister* regiGo = go->GetRegister(); if (regiGo) { int nameKey = Util::MakeHash(objectName); m_gameObjectMap.emplace(nameKey, regiGo); } else { #ifndef DW_MASTER MessageBox(NULL, "o^ĂȂQ[IuWFNgɖO‚悤ƂĂ܂", "Error", MB_OK); std::abort(); #endif } } //Q[IuWFNǧ template<class T> T* FindGO(const wchar_t* objectName) { auto range = m_gameObjectMap.equal_range(Util::MakeHash(objectName)); for (auto it = range.first; it != range.second; ++it) { auto& regiGo = it->second; //LH if (regiGo->isNoPendingkill && regiGo->isEnableGO) { //‚B T* p = dynamic_cast<T*>(regiGo->gameObject); if (p != nullptr) { return p; } } } return nullptr; } template<class T> T* FindGO() { for (auto& regiGo : m_gameObjectList) { //LH if (regiGo.isNoPendingkill && regiGo.isEnableGO) { //‚B T* p = dynamic_cast<T*>(regiGo.gameObject); if (p != nullptr) { return p; } } } return nullptr; } template<class T> void QueryGOs(const wchar_t* objectName, std::function<bool(T* go)> func) { auto range = m_gameObjectMap.equal_range(Util::MakeHash(objectName)); for (auto it = range.first; it != range.second; ++it){ auto& regiGo = it->second; //LH if (regiGo->isNoPendingkill && regiGo->isEnableGO) { //‚B T* p = dynamic_cast<T*>(regiGo->gameObject); if (p != nullptr) { if (func(p) == false) { //NGfB return; } } } } } template<class T> void QueryGOs(std::function<bool(T* go)> func) { for (auto& regiGo : m_gameObjectList) { //LH if (regiGo.isNoPendingkill && regiGo.isEnableGO) { //‚B T* p = dynamic_cast<T*>(regiGo.gameObject); if (p != nullptr) { if (func(p) == false) { //NGfB return; } } } } } #ifndef DW_MASTER /// <summary> /// o^ĂGameObj̐擾 /// </summary> size_t GetGameObjNum()const{ return m_gameObjectList.size(); } #endif private: std::list<GORegister> m_gameObjectList;//Q[IuWFNg̃Xg std::list<GORegister*> m_runFuncGOList[IGameObject::enVirtualFuncNum];//e֐sQ[IuWFNg̃Xg std::unordered_multimap<int, GORegister*> m_gameObjectMap;//OtQ[IuWFNg̎ bool m_isDeleteGOThisFrame = false;//̃t[GO폜ꂽ? bool m_isCheckVFuncThisFrame[IGameObject::enVirtualFuncNum] = {};//̃t[ɉz֐̎smFꂽ? }; //Q[IuWFNg̐ƍ폜̃}l[W[ class GONewDeleteManager { public: template<class T, class... TArgs> T* NewGO(TArgs... ctorArgs) { //new+tO T* newObject = new T(ctorArgs...); newObject->MarkNewGOMark(); return newObject; } //(Q[IuWFNg̖tOBۂɃCX^X폜̂́ASĂGOPostUpdateIĂ) bool DeleteGO(IGameObject* gameObject, bool newgoCheck, bool instantKill = false) { if (!gameObject) { return false; } if (newgoCheck && !gameObject->GetNewGOMark()) { //NewgõtOĂȂG[ #ifndef DW_MASTER char message[256]; sprintf_s(message, "NewGOĂȂQ[IuWFNgDeleteGO悤ƂĂ܂B\n^:%s", typeid(gameObject).name()); MessageBox(NULL, message, "Error", MB_OK); std::abort(); #endif } else { if (!gameObject->O͂łH()) {//܂EĂȂ //ɎE if (instantKill) { delete gameObject; return true; } //ƂŎE // gameObject->O͂ł(); //EXgo^ m_deleteList.emplace_back(gameObject); return true; } } return false; } void FarewellDearDeadman() { //E for (auto& GO : m_deleteList) { delete GO; } m_deleteList.clear(); } private: std::list<IGameObject*> m_deleteList; }; }
true
a30ea1f9a275a925e1bab398dd1623b3bacfe532
C++
sunlanchang/Accepted
/search/hrbust1143.cpp
UTF-8
1,236
2.59375
3
[]
no_license
#include <iostream> #include <cstring> #include <cstdio> using namespace std; const int maxn = 1e3 + 10; bool vst[maxn][maxn]; int pic[maxn][maxn]; int M, N, SX, SY, ANS; int dir[4][2] = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}}; bool check(int x, int y) { //注意状态检测先检测边界!如果先检测vst会有数组越界的危险 if (x > 0 && x <= M && y > 0 && y <= N && !vst[x][y] && pic[x][y] <= pic[SX][SY]) return true; return false; } void DFS(int sx, int sy) { vst[sx][sy] = true; ANS++; // 不同于BFS这里没有目标状态的检测 for (int i = 0; i < 4; i++) { //构造下一次状态 int nx = sx + dir[i][0], ny = sy + dir[i][1]; //状态检测 if (check(nx, ny)) { //直接递归,不同于BFS,不需要改变状态数组vst DFS(nx, ny); } } } int main() { // freopen("in.txt", "r", stdin); while (~scanf("%d%d%d%d", &M, &N, &SX, &SY)) { for (int i = 1; i <= M; i++) for (int j = 1; j <= N; j++) scanf("%d", &pic[i][j]); ANS = 0; memset(vst, false, sizeof(vst)); DFS(SX, SY); printf("%d\n", ANS); } return 0; }
true
445695e2effe69b141eb70d183d01c4f654c088f
C++
chengyoude00/cstudy
/jingtai/jingtai/linklist.h
GB18030
2,703
3.71875
4
[]
no_license
#pragma once #include "node.h" //Ҫʹ #include <iostream> using namespace std; class Linklist { public: Linklist(int i, char c); //๹캯 Linklist(Linklist &l); //캯 ~Linklist(); // bool Locate(int i); //ҽ bool Locate(char c); //ַҽ bool Insert(int i = 0, char c = '0');//ڵǰ֮ bool Delete(); //ɾǰ void Show(); //ʾ void Destroy(); // private: Node head; //ͷ Node * pcurrent; //ǰָ }; Linklist::Linklist(int i, char c) :head(i, c) { cout << "Linklist constructor is running..." << endl; pcurrent = &head; } Linklist::Linklist(Linklist &l) : head(l.head) { cout << "Linklist Deep cloner running..." << endl; pcurrent = &head; Node * ptemp1 = l.head.readn(); while (ptemp1 != NULL) { Node * ptemp2 = new Node(ptemp1->readi(), ptemp1->readc(), pcurrent, NULL); pcurrent->setn(ptemp2); pcurrent = pcurrent->readn(); ptemp1 = ptemp1->readn(); } } Linklist::~Linklist() { cout << "Linklist destructor is running..." << endl; Destroy(); //DestoryͷԴ } bool Linklist::Locate(int i) { Node * ptemp = &head; while (ptemp != NULL) { if (ptemp->readi() == i) { pcurrent = ptemp; return true; } ptemp = ptemp->readn(); } return false; } bool Linklist::Locate(char c) { Node * ptemp = &head; while (ptemp != NULL) { if (ptemp->readc() == c) { pcurrent = ptemp; return true; } ptemp = ptemp->readn(); } return false; } bool Linklist::Insert(int i, char c) { if (pcurrent != NULL) { Node * temp = new Node(i, c, pcurrent, pcurrent->readn()); // if (pcurrent->readn() != NULL) { pcurrent->readn()->setp(temp); // } pcurrent->setn(temp); // return true; } else { return false; } } bool Linklist::Delete() { if (pcurrent != NULL && pcurrent != &head) { Node * temp = pcurrent; if (temp->readn() != NULL) { temp->readn()->setp(pcurrent->readp()); // } temp->readp()->setn(pcurrent->readn()); // pcurrent = temp->readp(); delete temp; // return true; } else { return false; } } void Linklist::Show() { Node * ptemp = &head; while (ptemp != NULL) { cout << ptemp->readi() << '\t' << ptemp->readc() << endl; ptemp = ptemp->readn(); } }void Linklist::Destroy() { Node * ptemp1 = head.readn(); while (ptemp1 != NULL) //һɾ { Node * ptemp2 = ptemp1->readn(); delete ptemp1; ptemp1 = ptemp2; } head.setn(NULL); }
true
52bd288e2fcdf4dcfb256b22a287fe1664eeda85
C++
kelby-amerson/binarytree
/ItemType.cpp
UTF-8
924
3.875
4
[]
no_license
#include "ItemType.h" #include <cstdlib> #include <iostream> using namespace std; /** * Constructor for ItemType * Post-Condition: ItemType object is created */ ItemType::ItemType(){} /** * * Constructor for ItemType * * Post-Condition: ItemType object is created with value instantiated * */ ItemType::ItemType(int value){ this->value = value; } /** * prints out the associated value * Pre-Condition: ItemType object has been initialized * Post-Condition: value instance variable is printed to stdout */ void ItemType::print(){ cout << getValue() << endl; } /** * initializes the value member * Pre-Condition: number parameter is initialized. * Post-Condition: the value instance vairable is set to number */ void ItemType::initialize(int number){ this->value = number; } /** * Returns the value of the DataType * @return int value */ int ItemType::getValue() const{ return value; }
true
5f261cce7de27f33881cae8dbf5465669c93f4fd
C++
HenVanGogh/emptyVessel
/EmptyVessel.ino
UTF-8
12,600
2.625
3
[]
no_license
#include "MPU6050.h" #include "Adafruit_VL53L0X.h" #include "KalmanFilter.h" KalmanFilter kalmanX1(0.001, 0.003, 0.03); KalmanFilter kalmanY1(0.001, 0.003, 0.03); KalmanFilter kalmanX2(0.001, 0.003, 0.03); KalmanFilter kalmanY2(0.001, 0.003, 0.03); KalmanFilter kalmanX3(0.001, 0.003, 0.03); KalmanFilter kalmanY3(0.001, 0.003, 0.03); Adafruit_VL53L0X lox = Adafruit_VL53L0X(); MPU6050 mpu1; MPU6050 mpu2; MPU6050 mpu3; struct orintationTable { double Xgyro; double Ygyro; double Xaccel; double Yaccel; }; orintationTable Main; orintationTable Cal1; orintationTable Cal2; void enableGyro(char which) { if (which == 1) { digitalWrite(8, LOW); digitalWrite(9, HIGH); digitalWrite(10, HIGH); } else if (which == 2) { digitalWrite(8, HIGH); digitalWrite(9, LOW); digitalWrite(10, HIGH); } else if (which == 3) { digitalWrite(8, HIGH); digitalWrite(9, HIGH); digitalWrite(10, LOW); } else { digitalWrite(8, HIGH); digitalWrite(9, HIGH); digitalWrite(10, HIGH); } delay(10); } void getOrientationMain() { enableGyro(1); float accPitch = 0; float accRoll = 0; float kalPitch = 0; float kalRoll = 0; Vector acc = mpu1.readNormalizeAccel(); Vector gyr = mpu1.readNormalizeGyro(); // Calculate Pitch & Roll from accelerometer (deg) Main.Xaccel = -(atan2(acc.XAxis, sqrt(acc.YAxis*acc.YAxis + acc.ZAxis*acc.ZAxis))*180.0) / M_PI; Main.Yaccel = (atan2(acc.YAxis, acc.ZAxis)*180.0) / M_PI; // Kalman filter Main.Xgyro = kalmanY1.update(accPitch, gyr.YAxis); Main.Ygyro = kalmanX1.update(accRoll, gyr.XAxis); //enableGyro(4); } void getOrientationCal1() { enableGyro(2); float accPitch = 0; float accRoll = 0; float kalPitch = 0; float kalRoll = 0; Vector acc = mpu2.readNormalizeAccel(); Vector gyr = mpu2.readNormalizeGyro(); // Calculate Pitch & Roll from accelerometer (deg) Cal1.Xaccel = -(atan2(acc.XAxis, sqrt(acc.YAxis*acc.YAxis + acc.ZAxis*acc.ZAxis))*180.0) / M_PI; Cal1.Yaccel = (atan2(acc.YAxis, acc.ZAxis)*180.0) / M_PI; // Kalman filter Cal1.Xgyro = kalmanY2.update(accPitch, gyr.YAxis); Cal1.Ygyro = kalmanX2.update(accRoll, gyr.XAxis); //enableGyro(4); } void getOrientationCal2() { enableGyro(3); float accPitch = 0; float accRoll = 0; float kalPitch = 0; float kalRoll = 0; Vector acc = mpu3.readNormalizeAccel(); Vector gyr = mpu3.readNormalizeGyro(); // Calculate Pitch & Roll from accelerometer (deg) Cal2.Xaccel = -(atan2(acc.XAxis, sqrt(acc.YAxis*acc.YAxis + acc.ZAxis*acc.ZAxis))*180.0) / M_PI; Cal2.Yaccel = (atan2(acc.YAxis, acc.ZAxis)*180.0) / M_PI; // Kalman filter Cal2.Xgyro = kalmanY3.update(accPitch, gyr.YAxis); Cal2.Ygyro = kalmanX3.update(accRoll, gyr.XAxis); //enableGyro(4); } short int getMeasurent() { VL53L0X_RangingMeasurementData_t measure; lox.rangingTest(&measure, false); // pass in 'true' to get debug data printout! if (measure.RangeStatus != 4) { // phase failures have incorrect data return(measure.RangeMilliMeter); } else { return(-1); } } void gryroSetup(){ enableGyro(1); while (!mpu1.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G)) { delay(500); } mpu1.calibrateGyro(); enableGyro(2); while (!mpu2.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G)) { delay(500); } mpu2.calibrateGyro(); enableGyro(3); while (!mpu3.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G)) { delay(500); } mpu3.calibrateGyro(); enableGyro(4); if (!lox.begin()) { Serial.println(F("Failed to boot VL53L0X")); while (1); } } #include <EasyTransfer.h> //create two objects EasyTransfer ETin, ETout; struct SEND_DATA_STRUCTURE{ //put your variable definitions here for the data you want to receive //THIS MUST BE EXACTLY THE SAME ON THE OTHER ARDUINO orintationTable gyro1; orintationTable gyro2; orintationTable gyro3; short int distance; }; struct RECEIVE_DATA_STRUCTURE{ //put your variable definitions here for the data you want to receive //THIS MUST BE EXACTLY THE SAME ON THE OTHER ARDUINO int poseTable[3][2]; bool legsOn; }; RECEIVE_DATA_STRUCTURE rxdata; SEND_DATA_STRUCTURE txdata; #define errorAnalysis #define P11 0 #define P12 3 #define P13 9 #define P14 10 #define P21 2 #define P22 1 #define P23 5 #define P24 4 #define L11 15 #define L12 14 #define L13 8 #define L14 7 #define L21 13 #define L22 12 #define L23 6 #define L24 11 double linearDistance = 60.357; long posP11;/////P//// long posP12; long posP13; long posP21; long posP22; long posP23; long posL11;/////L///// long posL12; long posL13; long posL21; long posL22; long posL23; long posP31; long posP32; long posP33;///// long posL31; long posL32; long posL33;///// double Ytest; double YposT; double ZposT; double Xpos = 0; double Ypos = 0; double Zpos = 0; double Leg0 = 56.3, Leg1 = 167, Leg2 = 136; double radian = 57.2958; #include <math.h> //SoftwareSerial gyroSerial(10, 11); #include <Wire.h> #include <Adafruit_PWMServoDriver.h> #include <Servo.h> Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver(0x40); int con = true; #include <SoftwareSerial.h>// import the serial library int BluetoothData; // the data given from Computer double staP11 = 373-150;/////P//// double staP12 = 579; double staP13 = 691; double staP21 = 318+150; double staP22 = 596; double staP23 = 318; double staL11 = 455;/////L///// double staL12 = 566; double staL13 = 565; double staL21 = 278; double staL22 = 325; double staL23 = 686+260; double staP31; double staP32; double staP33; double staL31; double staL32; double staL33; int Xp1 = 0; int Yp1 = 500; int Zp1 = 500; int Xp2 = 0; int Yp2 = 500; int Zp2 = 500; int Xl1 = 0; int Yl1 = 500; int Zl1 = 500; int Xl2 = 0; int Yl2 = 500; int Zl2 = 500; long valP11 = staP11;/////BIS long valP12 = staP12; //OFF 30 long valP13 = staP13;// long valP21 = staP21; //Change from 45 long valP22 = staP22;//////BIS long valP23 = staP23;// long valP31 = staP31; long valP32 = staP32; //OFF 30 long valP33 = staP33;// long valL11 = staL11; long valL12 = staL12;//////BIS long valL13 = staL13;// long valL21 = staL21; long valL22 = staL22; //OFF 60 long valL23 = staL23;//BIS long valL31 = staL31; long valL32 = staL32;//BIS long valL33 = staL33;// void setup() { // put your setup code here, to run once: Serial.begin(115200); //gyroSerial.begin(19200); ETin.begin(details(rxdata), &Serial); ETout.begin(details(txdata), &Serial); pwm.begin(); pwm.setPWMFreq(100); } class Runner{ bool Side; double pin1, pin2, pin3; double St1, St2, St3; double LT, L0, L1, L2, L3, L4, L5, L6, L7, X, Y, Z, T1, T2, T3, K1, K2, K3, K4, K5, K6; double radian = 57.2958; int Lp; public: Runner(double Pin1, double Pin2, double Pin3, double st1, double st2, double st3, bool side , int lp){ pin1 =Pin1; pin2 =Pin2; pin3 = Pin3; L0 = Leg0; L1 = Leg1; L2 = Leg2; St1 = st1; St2 = st2; St3 = st3; Side = side; Lp = lp; } void Step (double x, double y, double z) { if((y > 20) && (z > 17) && (x > 17) && (y < 250) && (z < 350) && (x < 350)){ bool error = false; X = x; Y = y; Z = z; double XZsafeFactor = sqrt(91809-(Y*Y)); //Serial.print("Safe Factor XZ - "); //Serial.println(XZsafeFactor); double sqrtZX = (Z*Z) + (X*X); if(sqrt(sqrtZX) > XZsafeFactor){ Serial.println("XZ Safe factor ERROR"); //Serial.println(sqrtZX); //Serial.println("WTF"); } if(Y > 300){ Serial.println("Y Safe factor ERROR"); Serial.println("WTF?"); } T1 = atan (Z/X); L5 = sqrt(sqrtZX); //L5 = LT- L0; L4 = sqrt((y*y) + (L5*L5)); K1 = acos(L5/L4); double PowL2L4 , PowL1 , subL2L4L1 ; PowL2L4 = ((L2*L2)+(L4*L4)); PowL1 = L1*L1; subL2L4L1 = PowL2L4 - PowL1; K2 = acos(subL2L4L1 /(2*L4*L2)); K3 = K1+K2; K5 = acos(((L1*L1)+ (L2*L2)- (L4*L4))/(2*L1*L2)); K6 = K3; T2 = 3.14159-(K5+ K6); T3 = 3.14159- K5; double TD1 = T1*radian*3.333; double TD2 = T2*radian*3.333; double TD3 = T3*radian*3.333; double pos1; double pos2; double pos3; /* if(isnan(pos1) == false || isnan(pos2) == true || isnan(pos3) == true){ Serial.print("ERROR LEG"); Serial.print(Lp); Serial.println("IS NAN"); } */ //pos1 = St1 - TD1; // To jest zamienione na IF pos2 = St2 - TD2; if( Lp == 2){ pos3 = St3 + TD3; }else{ pos3 = St3 - TD3; } if( Lp == 4 || Lp == 1){ pos1 = St1 + TD1; }else{ pos1 = St1 - TD1; } //pos3 = St3 - TD3; #ifdef errorAnalysis if(Lp == 1){ float exportValue1 = float(pos1); float exportValue2 = float(pos2); float exportValue3 = float(pos3); //Serial.println(exportValue1); //Serial.println(exportValue2); //Serial.println(exportValue3); } //Serial.print(Lp); //Serial.println(pos2); //Serial.println(pos3); if(isnan(pos1) == true){ Serial.print("ERROR_LEG 1_"); Serial.print(Lp); Serial.println("_IS NAN"); error = true; } if(isnan(pos2) == true){ Serial.print("ERROR_LEG 2_"); Serial.print(Lp); Serial.println("_IS NAN"); error = true; } if(isnan(pos3) == true){ Serial.print("ERROR_LEG 3_"); Serial.print(Lp); Serial.println("_IS NAN"); error = true; } #endif if(error == false){ pwm.setPWM(pin1, 0,pos1 ); pwm.setPWM(pin2, 0,pos2 ); pwm.setPWM(pin3, 0,pos3 ); }else{ Serial.print("ErrorCode = "); Serial.println(error); } }else{ Serial.print("DATA_ERROR LEG_NR : "); Serial.println(Lp); Serial.print("X : "); Serial.println(x); Serial.print("Y : "); Serial.println(y); Serial.print("Z : "); Serial.println(z); } } }; void fullReport(){ getOrientationMain(); getOrientationCal1; getOrientationCal2; txdata.gyro1.Xgyro = Main.Xgyro; txdata.gyro1.Ygyro = Main.Ygyro; txdata.gyro1.Xaccel = Main.Xaccel; txdata.gyro1.Yaccel = Main.Yaccel; txdata.gyro2.Xgyro = Cal1.Xgyro; txdata.gyro2.Ygyro = Cal1.Ygyro; txdata.gyro2.Xaccel = Cal1.Xaccel; txdata.gyro2.Yaccel = Cal1.Yaccel; txdata.gyro3.Xgyro = Cal2.Xgyro; txdata.gyro3.Ygyro = Cal2.Ygyro; txdata.gyro3.Xaccel = Cal2.Xaccel; txdata.gyro3.Yaccel = Cal2.Yaccel; ETout.sendData(); } Runner RunnerP1(P11,P12,P13,staP11,staP12,staP13,1,1); Runner RunnerP2(P21,P22,P23,staP21,staP22,staP23,1,2); Runner RunnerL1(L11,L12,L13,staL11,staL12,staL13,0,3); Runner RunnerL2(L21,L22,L23,staL21,staL22,staL23,0,4); void loop() { for(int i=0; i<5; i++){ ETin.receiveData(); } if(rxdata.legsOn){ RunnerP1.Step(rxdata.poseTable[0][0] , rxdata.poseTable[0][1] , rxdata.poseTable[0][2]); RunnerP2.Step(rxdata.poseTable[1][0] , rxdata.poseTable[1][1] , rxdata.poseTable[1][2]); RunnerL1.Step(rxdata.poseTable[2][0] , rxdata.poseTable[2][1] , rxdata.poseTable[2][2]); RunnerL2.Step(rxdata.poseTable[3][0] , rxdata.poseTable[3][1] , rxdata.poseTable[3][2]); } fullReport(); }
true
292d66dc2bfc463f6f0964ac6dd03129a821e133
C++
James51332/Papaya
/main/core/Input.cpp
UTF-8
6,062
2.59375
3
[ "Apache-2.0" ]
permissive
#include "papayapch.h" #include "Input.h" namespace Papaya { int Input::m_MouseX; int Input::m_MouseY; bool Input::s_KeyState[PAPAYA_TOTAL_KEYCODES]; bool Input::s_LastKeyState[PAPAYA_TOTAL_KEYCODES]; bool Input::s_MouseState[PAPAYA_TOTAL_MOUSECODES]; bool Input::s_LastMouseState[PAPAYA_TOTAL_MOUSECODES]; int Input::s_AsciiCapital[PAPAYA_TOTAL_KEYCODES]; int Input::s_AsciiLowercase[PAPAYA_TOTAL_KEYCODES]; bool Input::KeyPressed(KeyCode key) { return s_KeyState[key] && !s_LastKeyState[key]; } bool Input::KeyReleased(KeyCode key) { return !s_KeyState[key] && s_LastKeyState[key]; } bool Input::KeyDown(KeyCode key) { return s_KeyState[key]; } bool Input::MousePressed(MouseCode btn) { return s_MouseState[btn] && !s_LastMouseState[btn]; } bool Input::MouseReleased(MouseCode btn) { return !s_MouseState[btn] && s_LastMouseState[btn]; } bool Input::MouseDown(MouseCode btn) { return s_MouseState[btn]; } int Input::GetMouseX() { return m_MouseX; } int Input::GetMouseY() { return m_MouseY; } int Input::ToASCII(KeyCode key, bool capitalized) { return capitalized ? s_AsciiCapital[key] : s_AsciiLowercase[key]; } void Input::OnInit() { for (int i = 0; i < PAPAYA_TOTAL_KEYCODES; ++i) { s_KeyState[i] = false; s_LastKeyState[i] = false; } for (int i = 0; i < PAPAYA_TOTAL_MOUSECODES; ++i) { s_MouseState[i] = false; s_LastMouseState[i] = false; } memset(&s_AsciiCapital[0], 0, sizeof(s_AsciiCapital)); memset(&s_AsciiLowercase[0], 0, sizeof(s_AsciiLowercase)); s_AsciiCapital[KeyA] = 65; s_AsciiCapital[KeyB] = 66; s_AsciiCapital[KeyC] = 67; s_AsciiCapital[KeyD] = 68; s_AsciiCapital[KeyE] = 69; s_AsciiCapital[KeyF] = 70; s_AsciiCapital[KeyG] = 71; s_AsciiCapital[KeyH] = 72; s_AsciiCapital[KeyI] = 73; s_AsciiCapital[KeyJ] = 74; s_AsciiCapital[KeyK] = 75; s_AsciiCapital[KeyL] = 76; s_AsciiCapital[KeyM] = 77; s_AsciiCapital[KeyN] = 78; s_AsciiCapital[KeyO] = 79; s_AsciiCapital[KeyP] = 80; s_AsciiCapital[KeyQ] = 81; s_AsciiCapital[KeyR] = 82; s_AsciiCapital[KeyS] = 83; s_AsciiCapital[KeyT] = 84; s_AsciiCapital[KeyU] = 85; s_AsciiCapital[KeyV] = 86; s_AsciiCapital[KeyW] = 87; s_AsciiCapital[KeyX] = 88; s_AsciiCapital[KeyY] = 89; s_AsciiCapital[KeyZ] = 90; s_AsciiCapital[Key0] = 41; s_AsciiCapital[Key1] = 33; s_AsciiCapital[Key2] = 64; s_AsciiCapital[Key3] = 35; s_AsciiCapital[Key4] = 36; s_AsciiCapital[Key5] = 37; s_AsciiCapital[Key6] = 94; s_AsciiCapital[Key7] = 38; s_AsciiCapital[Key8] = 42; s_AsciiCapital[Key9] = 41; s_AsciiCapital[KeyGrave] = 126; s_AsciiCapital[KeyDash] = 95; s_AsciiCapital[KeyEquals] = 43; s_AsciiCapital[KeyLeftBracket] = 123; s_AsciiCapital[KeyRightBracket] = 125; s_AsciiCapital[KeyBackslash] = 124; s_AsciiCapital[KeySlash] = 63; s_AsciiCapital[KeyPeriod] = 62; s_AsciiCapital[KeyComma] = 60; s_AsciiCapital[KeyTab] = 9; s_AsciiCapital[KeyEscape] = 27; s_AsciiCapital[KeyBackspace] = 8; s_AsciiLowercase[KeySpace] = 32; s_AsciiLowercase[KeyA] = 97; s_AsciiLowercase[KeyB] = 98; s_AsciiLowercase[KeyC] = 99; s_AsciiLowercase[KeyD] = 100; s_AsciiLowercase[KeyE] = 101; s_AsciiLowercase[KeyF] = 102; s_AsciiLowercase[KeyG] = 103; s_AsciiLowercase[KeyH] = 104; s_AsciiLowercase[KeyI] = 105; s_AsciiLowercase[KeyJ] = 106; s_AsciiLowercase[KeyK] = 107; s_AsciiLowercase[KeyL] = 108; s_AsciiLowercase[KeyM] = 109; s_AsciiLowercase[KeyN] = 110; s_AsciiLowercase[KeyO] = 111; s_AsciiLowercase[KeyP] = 112; s_AsciiLowercase[KeyQ] = 113; s_AsciiLowercase[KeyR] = 114; s_AsciiLowercase[KeyS] = 115; s_AsciiLowercase[KeyT] = 116; s_AsciiLowercase[KeyU] = 117; s_AsciiLowercase[KeyV] = 118; s_AsciiLowercase[KeyW] = 119; s_AsciiLowercase[KeyX] = 120; s_AsciiLowercase[KeyY] = 121; s_AsciiLowercase[KeyZ] = 122; s_AsciiLowercase[Key0] = 48; s_AsciiLowercase[Key1] = 49; s_AsciiLowercase[Key2] = 50; s_AsciiLowercase[Key3] = 51; s_AsciiLowercase[Key4] = 52; s_AsciiLowercase[Key5] = 53; s_AsciiLowercase[Key6] = 54; s_AsciiLowercase[Key7] = 55; s_AsciiLowercase[Key8] = 56; s_AsciiLowercase[Key9] = 57; s_AsciiLowercase[KeyGrave] = 96; s_AsciiLowercase[KeyDash] = 45; s_AsciiLowercase[KeyEquals] = 61; s_AsciiLowercase[KeyLeftBracket] = 91; s_AsciiLowercase[KeyRightBracket] = 93; s_AsciiLowercase[KeyBackslash] = 92; s_AsciiLowercase[KeySlash] = 47; s_AsciiLowercase[KeyPeriod] = 46; s_AsciiLowercase[KeyComma] = 44; s_AsciiLowercase[KeyTab] = 9; s_AsciiLowercase[KeyEscape] = 27; s_AsciiLowercase[KeyBackspace] = 8; s_AsciiLowercase[KeySpace] = 32; } void Input::OnUpdate() { memcpy(s_LastKeyState, s_KeyState, sizeof(s_KeyState)); memcpy(s_LastMouseState, s_MouseState, sizeof(s_MouseState)); } void Input::OnEvent(const Scope<Event>& event) { if (!(event->GetCategoryFlags() & EventCategoryInput)) return; EventDispatcher::Dispatch<KeyPressEvent>(event, [](KeyPressEvent* e) { Input::s_KeyState[e->GetKeyCode()] = true; }); EventDispatcher::Dispatch<KeyReleaseEvent>(event, [](KeyReleaseEvent* e) { Input::s_KeyState[e->GetKeyCode()] = false; }); EventDispatcher::Dispatch<MousePressEvent>(event, [](MousePressEvent* e) { Input::s_MouseState[e->GetMouseCode()] = true; }); EventDispatcher::Dispatch<MouseReleaseEvent>(event, [](MouseReleaseEvent* e) { Input::s_MouseState[e->GetMouseCode()] = false; }); EventDispatcher::Dispatch<MouseMoveEvent>(event, [](MouseMoveEvent* event) { m_MouseX = static_cast<int>(event->GetXPosition()); m_MouseY = static_cast<int>(event->GetYPosition()); }); } } // namespace Papaya
true
4b2b3ca11de3f89c94b59156f0ef72c05adee4a4
C++
WeyrSDev/Game-Menu
/src/gamewindow.cpp
UTF-8
2,108
2.71875
3
[ "MIT" ]
permissive
#include "SFML/Graphics.hpp" #include "gamewindow.hpp" const GameWindow::ResolutionSetting GameWindow::w640h480 = GameWindow::ResolutionSetting(640, 480); const GameWindow::ResolutionSetting GameWindow::w1600h900 = GameWindow::ResolutionSetting(1600, 900); const GameWindow::ResolutionSetting GameWindow::w1920h1080 = GameWindow::ResolutionSetting(1920, 1080); const GameWindow::ResolutionSetting GameWindow::w2560h1440 = GameWindow::ResolutionSetting(2560, 1440); /*===========================================================================*/ /* GameWindow */ /*===========================================================================*/ GameWindow::GameWindow(const ResolutionSetting& res, const std::string& title) : _res(res) { _title = title; setFramerateLimit(res.get_framerate()); } void GameWindow::toggle_fullscreen() { /* toggle fullscreen */ } void GameWindow::set_resolution(const ResolutionSetting& res) { setSize(res.get_resolution()); } uint32_t GameWindow::get_height() const { return _res.get_height(); } uint32_t GameWindow::get_width() const { return _res.get_width(); } std::string GameWindow::get_title() const { return _title; } double GameWindow::get_framerate() const { return _res.get_framerate(); } /*===========================================================================*/ /* ResolutionSetting */ /*===========================================================================*/ GameWindow::ResolutionSetting::ResolutionSetting(const uint32_t& width, const uint32_t& height, const uint32_t& framerate) : _width(width), _height(height), _framerate(framerate) {} sf::Vector2u GameWindow::ResolutionSetting::get_resolution() const { return sf::Vector2u(_width, _height); } uint32_t GameWindow::ResolutionSetting::get_width() const { return _width; } uint32_t GameWindow::ResolutionSetting::get_height() const { return _height; } uint32_t GameWindow::ResolutionSetting::get_framerate() const { return _framerate; }
true
8a1a333c7bd874758b0defb7c460bd6e262fae82
C++
landylan/BlueErgo_Protype
/7_trackball/keyboard_with_trackball/direction.cpp
UTF-8
963
2.765625
3
[]
no_license
#include "direction.h" Direction::Direction(int pin1, int pin2) { pins[0] = pin1; pins[1] = pin2; pinMode(pins[0], INPUT); pinMode(pins[1], INPUT); } int Direction::read_action() { for(int i = 0; i < 2; ++i) { current_actions[i] = digitalRead(pins[i]); current_action_times[i] = millis(); if (current_actions[i] != last_actions[i]) { last_actions[i] = current_actions[i]; exponential = (exponential_bound - (current_action_times[i] - last_action_times[i])); exponential = (exponential > 0) ? exponential : 1; move_multiply = exponential_base; for (int i = 0; i < exponential; ++i) { move_multiply *= exponential_base; } last_action_times[i] = current_action_times[i]; if (i == 0) { return (-1) * base_move_pixels * move_multiply; } else { return base_move_pixels * move_multiply; } } } return 0; }
true
5ce43d2509de74710caa5f8c5ecf38cee09c235d
C++
AnishGRao/LeetCode
/leetcode_problems/zigzag_conversion/non_repeating_substring/main.cpp
UTF-8
859
3.234375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int lengthOfLongestSubstring(string s) { int longest = -1; unordered_map<char, int> check = {}; int i = 0; for (int itr = 0; itr < s.size(); itr++) { char character = s[itr]; int size_start = check.size(); check[character] = 0; int size_end = check.size(); if (size_end >= longest) { longest = check.size(); } if (size_start == check.size()) { check.clear(); itr = i; i++; } } return (longest == -1) ? 0 : longest; } int main() { cout << lengthOfLongestSubstring("abcabcbb") << "\n"; cout << lengthOfLongestSubstring("bbbbb") << "\n"; cout << lengthOfLongestSubstring("pwwkew") << "\n"; cout << lengthOfLongestSubstring("dvdf") << "\n"; }
true
300739879d41fc4d6f52cc4eb0a57b9975b7a5f2
C++
Crtl-F5/F5RC-Kernel
/src/main/cpp/Math/PIDController.cpp
UTF-8
1,018
2.6875
3
[ "MIT" ]
permissive
#include <time.h> #include <MathExtensions.hpp> #include <PIDController.hpp> namespace MathExtensions { PIDController::PIDController(float P, float I, float D, float loopLength) { this.P = P; this.I = I; this.D = D; this.loopLength = loopLength; this.integral = 0; this.lastValue = 0; this.target = 0; lastTimeStamp = clock(); } float PIDController::Update(float value) { offset = CircularLerp(value, target, .5, loopLength, MajorArc); value = (value + offset) % loopLength; adjustedTarget = (target + value) % loopLength; float error = adjustedTarget - value; clock_t currentTime = clock(); float deltaTime = CLOCKS_PER_SEC * error; integral += I * (float)(currentTime - lastTimeStamp) / CLOCKS_PER_SEC * error; lastTimeStamp = currentTime; float outVal = P * error + integral + D * error / deltaTime; lastError = error; return outVal; } }
true
196f5cf52a1419042d2cdf0c466319d375e8f8df
C++
djpetti/CSCI4230-DES
/key_exchange/client_node.cc
UTF-8
3,891
2.953125
3
[ "MIT" ]
permissive
#include "client_node.h" #include <stdint.h> #include <stdio.h> #include <string.h> #include <algorithm> #include "constants.h" namespace hw1 { namespace key_exchange { namespace { // Dummy key we use when we set up the client. We'll set the right key later // when we have it. const uint8_t kDummyKey[] = {0, 0}; } // namespace ClientNode::ClientNode(const char *kdc_address, const uint16_t port, uint8_t id) : transfer::common::Client(kDummyKey, kChunkSize), kdc_address_(kdc_address), kdc_port_(port), id_(id), key_manager_(kdc_address, port, id, &nonce_generator_) {} void ClientNode::AddNodeWithId(const char *address, uint8_t id) { printf("Adding node with address %s and ID %u.\n", address, id); node_ids_[address] = id; } bool ClientNode::Connect(const char *server, uint16_t port) { // Make sure that server is known to us. const auto &id_iter = node_ids_.find(server); if (id_iter == node_ids_.end()) { return false; } // Set the key for communicating with the KDC. uint8_t kdc_key[2]; if (!key_manager_.GetMasterKey(kdc_key)) { // Key exchange failed. printf("ERROR: Key exchange failed.\n"); return false; } SetKey(kdc_key); // When initiating a client connection, we first have to connect to the key // server and request a session key. if (!transfer::common::Client::Connect(kdc_address_, kdc_port_)) { // Failed to connect to the KDC. return false; } // Send the request. if (!RequestSessionKey(server)) { return false; } // Receive the response. uint8_t session_key[2]; char node_envelope[kHandshakeMessageSize]; if (!ReceiveSessionKey(session_key, node_envelope)) { return false; } // Now we have enough information to connect to the other node. Close(); if (!transfer::common::Client::Connect(server, port)) { // Faled to connect to the other node. return false; } // Send the envelope with the session key. if (!SendChunk(node_envelope, kHandshakeMessageSize)) { return false; } // Use the new encryption key for all further communications with this node. SetKey(session_key); return true; } bool ClientNode::SendMessage(const char *message) { // Calculate the length + the terminating null. const uint16_t length = strlen(message) + 1; // Write everything into the chunk buffer. const uint32_t max_write = ::std::min((uint32_t)length, kChunkSize - 2); memcpy(plain_chunk_buffer_, &length, 2); memcpy(plain_chunk_buffer_ + 2, message, max_write); // Make sure we have a \0 somewhere in there. plain_chunk_buffer_[kChunkSize - 1] = '\0'; // Send it to the client. return EncryptAndSendChunk(plain_chunk_buffer_, max_write + 2); } bool ClientNode::RequestSessionKey(const char *address) { // Format a request for a session key. const uint32_t nonce = nonce_generator_.Generate(); const uint8_t other_id = node_ids_[address]; char *write_at = plain_chunk_buffer_; memcpy(write_at++, &id_, 1); memcpy(write_at++, &other_id, 1); memcpy(write_at, &nonce, 4); write_at += 4; printf("Sending key request from %u to %u with nonce %u.\n", id_, other_id, nonce); // Send the request. if (!SendChunk(plain_chunk_buffer_, write_at - plain_chunk_buffer_)) { return false; } return true; } bool ClientNode::ReceiveSessionKey(uint8_t *session_key, char *node_envelope) { // Receive and decrypt the session key message. char *buffer; if (!ReceiveAndDecryptChunk(&buffer, kKeyMessageSize)) { // Failed to received the message. return false; } // Read the session key. memcpy(session_key, buffer, 2); // Read the envelope. memcpy(node_envelope, buffer + 7, kHandshakeMessageSize); printf("Will now use session key 0x%X 0x%X.\n", session_key[0], session_key[1]); return true; } } // namespace key_exchange } // namespace hw1
true
174558dd0079f9bbe884a4c0c4aefc1948c06f57
C++
tabahi/IoT-Arduino
/SyncBlutooth_HC05_AnB/Sync30Jan_simple/Serial/Serial.ino
UTF-8
449
2.65625
3
[ "MIT" ]
permissive
const int ledPin = 13; const int scopePin = 12; uint8_t Buffer[768]; void setup() { pinMode(ledPin, OUTPUT); pinMode(scopePin, OUTPUT); Serial.begin(9600); Serial.flush(); } void loop() { uint16_t length = Serial.available(); if (length > 0) { digitalWrite(ledPin, HIGH); Serial.readBytes((char *)Buffer, length); Serial.write(Buffer, length); Serial.send_now(); digitalWrite(ledPin, LOW); } }
true
ab49180e6b4c97aefe1325a87bc0daec3fdd26b2
C++
kicks2kill/C-plus-plus_practice
/practice/classes.cpp
UTF-8
1,082
2.609375
3
[]
no_license
class A { typedef int I; I f(); friend I g(I); static I x; template<int> struct Q; template<int> friend struct R; protected: struct B {}; }; A::I A::f() {return 0;} A::I g(A::I p = A::x); A::I g(A::I p) {return 0;} A::I A::x = 0; //why would we want to define this way? Just use int A::x = 0...right? template<A::I> struct A::Q {}; template<A::I> struct R {}; struct D: A::B, A {}; //Believe it or not, all of the uses here are well-formed because A::f, A::x, and A::q are members of class A and g and R are friends of class A. //This implies that access checking on the first use of A::I must be deferred until it is determined that this use is the return type of a member of class A. class B {}; template <class T> class C { protected: typedef T TT; }; template <class U, class V = typename U::TT> class D : public U {}; D <C<B>>* d; //access error because C::TT is protected ... class A {}; class B : private A {}; class C : public B { A* p; //this causes an error. injected-class-name A is inaccessible ::A* q; //this is okay. }
true
2a4effefbb7ab3f742ac176c7421ab4550a0e574
C++
0V/simple-raytracer
/src/include/objects/flip_normals.h
UTF-8
743
2.640625
3
[ "MIT" ]
permissive
#ifndef RAYTRACER_OBJECTS_FLIP_NORMALS_H_ #define RAYTRACER_OBJECTS_FLIP_NORMALS_H_ #include "vector_utility.h" #include "objects/hitable_base.h" class FlipNormals : public HitableBase { private: HitablePtr ptr_; public: FlipNormals(const HitablePtr &ptr) : ptr_(ptr){}; virtual bool hit(const Ray &r, const double &t_min, const double &t_max, HitRecord &dist) const { if (ptr_->hit(r, t_min, t_max, dist)) { dist.normal = -dist.normal; return true; } else { return false; } } virtual bool bounding_box(const double &t0, const double &t1, AABB &box) const { return ptr_->bounding_box(t0, t1, box); } }; #endif // RAYTRACER_OBJECTS_FLIP_NORMALS_H_
true
aba8ac803569717b8145ff96faccbb42465a7512
C++
danish-7627/Sorting_c-_graphics
/main.cpp
UTF-8
4,889
3.21875
3
[]
no_license
#include<bits/stdc++.h> #include<iostream> #include<vector> #include<cstdlib> #include<time.h> #include<graphics.h> #include<windows.h> using namespace std; // Class containing of all the sorting algorithms and the array class sorting_algo { private: vector<int>arr; // Array is private public: sorting_algo(); // Constructor declaration void output(); void swap(int a,int b); // Display functions void print_sol(int a,int b); int arrsize(); // Sorting functions and their subparts void bubblesort(); void insertionsort(); void selectionsort(); void merge(int l, int m, int r); void mergesort(int l,int r); int partition(int low,int high); void quicksort(int low,int high); }; int main() { // Load the graphics driver DWORD screenWidth = GetSystemMetrics(SM_CXSCREEN); DWORD screenHeight = GetSystemMetrics(SM_CYSCREEN); initwindow(screenWidth,screenHeight,"",true); sorting_algo s,s1,s2,s3,s4; outtextxy(0,0,"SELECTION SORT"); s.output(); s.selectionsort(); setfillstyle(SOLID_FILL,GREEN); s.output(); outtextxy(0,0,"INSERTION SORT"); s1.output(); s1.insertionsort(); setfillstyle(SOLID_FILL,GREEN); s1.output(); outtextxy(0,0,"QUICK SORT"); s2.output(); s2.quicksort(0,s.arrsize()); setfillstyle(SOLID_FILL,GREEN); s2.output(); outtextxy(0,0,"MERGE SORT"); s3.output(); s3.mergesort(0,s.arrsize()); setfillstyle(SOLID_FILL,GREEN); s3.output(); outtextxy(0,0,"BUBBLE SORT"); s4.output(); s4.bubblesort(); setfillstyle(SOLID_FILL,GREEN); s4.output(); getch(); //delay(3000); closegraph(); } // Constructor for the class to initialize the array sorting_algo::sorting_algo(){ srand(time(0)); for(int i = 0;i<250;i++) { arr.push_back(rand()%850+1); } } // Function to return the array size int sorting_algo::arrsize(){ return arr.size(); } // Function to display the whole array with solid bars void sorting_algo::output(){ for(int i = 0;i<arr.size();i++) { //line(2*i,851,2*i+1,851-arr[i]); bar(4*i,851,4*i+3,851-arr[i]); } } void sorting_algo::print_sol(int a,int b){ setfillstyle(SOLID_FILL,BLACK); bar(4*a,851,4*a+3,0); bar(4*b,851,4*b+3,0); } void sorting_algo::swap(int a,int b){ setfillstyle(SOLID_FILL,WHITE); bar(4*a,851,4*a+3,851-arr[a]); bar(4*(b),851,4*(b)+3,851-arr[b]); delay(1); } // Bubble sort algorithm void sorting_algo::bubblesort(){ for(int i = 0;i<arr.size();i++) { for(int j = 0;j<arr.size()-i-1;j++) { if(arr[j]>arr[j+1]) { setfillstyle(SOLID_FILL,BLACK); bar(4*j,851,4*j+3,0); bar(4*(j+1),851,4*(j+1)+3,0); swap(arr[j],arr[j+1]); swap(j,j+1); } } } } // Selection sort algorithm void sorting_algo::selectionsort() { for(int i = 0;i<arr.size();i++) { for(int j = i+1;j<arr.size();j++) { if(arr[i]>arr[j]) { print_sol(i,j); swap(arr[i],arr[j]); swap(i,j); } } } } // Insertion Sort Algorithm void sorting_algo::insertionsort() { for(int i = 1;i<arr.size();i++) { for(int j = 0;j<i;j++) { if(arr[i]<arr[j]) { print_sol(i,j); swap(arr[i],arr[j]); swap(i,j); } } } } // Partition member function for quick sort with last element as pivot int sorting_algo::partition(int low,int high) { int i = low,j=low-1; while(i<high){ { if(arr[i]<=arr[high]) { j++; print_sol(i,j); swap(arr[i],arr[j]); swap(i,j); } i++; } } print_sol(j+1,high); swap(arr[j+1],arr[high]); swap(j+1,high); return j+1; } // Quick sort algorithm void sorting_algo::quicksort(int low,int high) { if(low<high){ int i = partition(low,high); quicksort(low,i-1); quicksort(i+1,high); } } // Merge sort algorithm void sorting_algo::merge(int l, int m, int r){ int i = l; int j = m+1; int k = 0; vector<int>a; // Array to store the elements temporarily while merging while(i<=m&&j<=r) { if(arr[i]<arr[j]) { a.push_back(arr[i]); i++;k++; } else{ a.push_back(arr[j]); j++;k++; } } while(i<=m) { a.push_back(arr[i]); i++;k++; } while(j<=r) { a.push_back(arr[j]); j++;k++; } k = 0; for(int i = l;i<=r;i++) { arr[i]=a[k]; k++; } delay(3); cleardevice(); output(); } void sorting_algo::mergesort(int l,int r){ if (l < r) { int m = l+(r-l)/2; mergesort(l, m); // Dividing the array in two halves and calling mergesort on the two arrays mergesort( m+1, r); merge(l, m, r); // This function is used to merge the two sorted halves } }
true
3a3debe3a81691790a2ebb0f30e25ee0b632029c
C++
MarceloGennari/TextureGen
/Camera/camera.cpp
UTF-8
9,156
2.84375
3
[]
no_license
#include <../model.h> #include "camera.h" #include <iostream> #include <fstream> #include <sstream> #include <vector> #include <glm/gtc/type_ptr.hpp> Camera* Camera::cam; void Camera::keyBoardInput(unsigned char key, int x, int y){ /* * This is an FPS style of camera * wasd/zx controls your position * ijkl controls your angle * */ glm::vec3 Direction; glm::vec3 Right; float dirAbs; float vel = 0.1; float angle = 1; switch(key){ case 'w': Direction = cam->camPos - cam->targetPos; Direction = glm::normalize(Direction); cam->setCamPos(cam->camPos - Direction*vel); cam->setTargetPos(cam->targetPos - Direction*vel); break; case 'a': Direction = cam->camPos - cam->targetPos; Right = glm::cross(Direction, cam->upPos); Right = glm::normalize(Right); cam->setCamPos(cam->camPos + Right*vel); cam->setTargetPos(cam->targetPos + Right*vel); break; case 's': Direction = cam->camPos - cam->targetPos; Direction = glm::normalize(Direction); cam->setCamPos(cam->camPos + Direction*vel); cam->setTargetPos(cam->targetPos + Direction*vel); break; case 'd': Direction = cam->camPos - cam->targetPos; Right = glm::cross(Direction, cam->upPos); Right = glm::normalize(Right); cam->setCamPos(cam->camPos - Right*vel); cam->setTargetPos(cam->targetPos - Right*vel); break; case 'z': cam->setCamPos(cam->getCamPos()+glm::vec3(0.0f, vel, 0.0f)); cam->setTargetPos(cam->getTargetPos()+glm::vec3(0.0f, vel, 0.0f)); break; case 'x': cam->setCamPos(cam->getCamPos()+glm::vec3(0.0f, -vel, 0.0f)); cam->setTargetPos(cam->getTargetPos()+glm::vec3(0.0f, -vel, 0.0f)); break; case 'j': Direction = cam->camPos-cam->targetPos; dirAbs = glm::length(Direction); Direction = glm::normalize(Direction); Direction = glm::rotate(Direction, glm::radians(angle), cam->upPos); Direction = Direction*dirAbs; cam->setTargetPos( cam->camPos-Direction); break; case 'k': Direction = cam->camPos - cam->targetPos; Right = glm::cross(Direction, cam->upPos); Right = glm::normalize(Right); dirAbs = glm::length(Direction); Direction = glm::normalize(Direction); Direction = glm::rotate(Direction, glm::radians(angle), Right); Direction = Direction*dirAbs; cam->setTargetPos( cam->camPos-Direction); break; case 'i': Direction = cam->camPos - cam->targetPos; Right = glm::cross(Direction, cam->upPos); Right = glm::normalize(Right); dirAbs = glm::length(Direction); Direction = glm::normalize(Direction); Direction = glm::rotate(Direction, glm::radians(-angle), Right); Direction = Direction*dirAbs; cam->setTargetPos( cam->camPos-Direction); break; case 'l': Direction = cam->camPos-cam->targetPos; dirAbs = glm::length(Direction); Direction = glm::normalize(Direction); Direction = glm::rotate(Direction, glm::radians(-angle), cam->upPos); Direction = Direction*dirAbs; cam->setTargetPos( cam->camPos-Direction); break; default: break; } } void Camera::mouseInput(int button, int state, int x, int y){ // if(button == GLUT_LEFT_BUTTON){ // Camera* cam = Camera::getCam(); // int offsetX = x - cam->lastX; // int offsetY = y - cam->lastY; // cam->lastX = x; // cam->lastY = y; // float sensitivity = 0.5; // offsetX *= sensitivity; // offsetY *= sensitivity; // cam->yaw += offsetX; // cam->pitch += offsetY; // if(cam->pitch > 89.0f) // cam->pitch = 89.0f; // if(cam->pitch < -89.0f) // cam->pitch = -89.0f; // glm::vec3 front; // front.x = cos(glm::radians(cam->yaw)) * cos(glm::radians(cam->pitch)); // front.y = sin(glm::radians(cam->pitch)); // front.z = sin(glm::radians(cam->yaw)) * cos(glm::radians(cam->pitch)); // cam->setUpPos(glm::normalize(front)); // } } void Camera::initializeCalib(){ std::string directory = Model::getModel()->getDirectory(); std::string path = directory + "/calib.txt"; std::string line; std::ifstream calibFile(path.c_str()); std::vector<std::string> array; if(calibFile.is_open()){ while(getline(calibFile,line)){ std::size_t pos = 0, found; while((found = line.find_first_of(' ', pos)) != std::string::npos) { array.push_back(line.substr(pos, found - pos)); pos = found+1; } array.push_back(line.substr(pos)); } } float foc[2]; std::istringstream (array[2])>>foc[0]; std::istringstream (array[3])>>foc[1]; this->focal = glm::vec2(foc[0], foc[1]); float pp[2]; std::istringstream (array[4])>>pp[0]; std::istringstream (array[5])>>pp[1]; this->PrincPoint = glm::vec2(pp[0], pp[1]); float calib[12]; for(int k =0; k<12; k++) std::istringstream(array[k+14])>>calib[k]; this->KMat = glm::make_mat3x4(calib); } void Camera::getPose(const std::string &frameNr, glm::mat3 &Rot, glm::vec3 &Tra, glm::mat4 &Pose){ /* Notice that these matrices map points from the world coordinates to the camera coordinates * This means that in order to get the camera position in world coordinates from this, we have: * CameraCoord = Rotation*Position + Translation * Position = inverse(Rotation)*CameraCoord - inverse(Rotation)*Translation * * Also, since it is a Rotation Matrix, it has the property that inverse = transpose * */ std::string directory = Model::getModel()->getDirectory(); std::string line; std::string path = directory + "/Poses/Pose"+frameNr + ".txt"; std::ifstream pose(path.c_str()); std::vector<std::string> array; if(pose.is_open()){ while(getline(pose, line)){ std::size_t pos = 0, found; while((found = line.find_first_of(' ', pos)) != std::string::npos) { array.push_back(line.substr(pos, found - pos)); pos = found+1; } array.push_back(line.substr(pos)); } } float m[9]; float t[3]; float p[16]; for(int k = 0; k<9; k++) std::istringstream ( array[k] ) >> m[k]; for(int k=9; k<12; k++) std::istringstream( array[k] ) >> t[k-9]; for(int k = 12; k<28; k++) std::istringstream( array[k] ) >> p[k-12]; // Remember that glm::mat3 is stored column-wise in the same way as infiniTAM Rot = glm::make_mat3(m); //Rot = glm::transpose(Rot); // This makes Rot = Rot^-1 Pose = glm::make_mat4(p); Pose = glm::transpose(Pose); Tra = glm::vec3(t[0], t[1], t[2]); } void Camera::positionCameraFrN(const std::string &n){ glm::vec3 Translation; glm::vec3 Direction; glm::mat3 Rotation; glm::mat3 invRotation; glm::mat4 Pose; Camera::getCam()->getPose(n, Rotation, Translation, Pose); Camera::getCam()->initializeCalib(); Camera::getCam()->setProjection(glm::perspective(glm::radians(50.0f), 640.0f/480.0f, 0.05f, 10.0f)); /* * Apparently, this Rotation Matrix and Translation Vector maps from 3D world coordinates to 3D Camera Coordinates * Therefore, the camera position is not Translation, but -invRotation*Translation * * The Initial Direction of the camera is -1.0fz and the Initial Up Direction is -1.0fy * */ invRotation = glm::transpose(Rotation); Camera::getCam()->setCamPos(-invRotation*Translation); Direction = glm::vec3(0.0f, 0.0f, -1.0f); Direction = invRotation*Direction; Camera::getCam()->setUpPos(invRotation*glm::vec3(0.0f, -1.0f, 0.0f)); Camera::getCam()->setTargetPos(Camera::getCam()->getCamPos() - Direction); Camera::getCam()->setView(glm::lookAt(Camera::getCam()->getCamPos(), Camera::getCam()->getTargetPos(), Camera::getCam()->getUpPos())); } void Camera::updateView(){ this->view = glm::lookAt(this->getCamPos(), this->targetPos, this->upPos); } void Camera::setView(glm::mat4 view){ this->view =view; } void Camera::setProjection(glm::mat4 projection){ this->perspective =projection; } void Camera::setCamPos(glm::vec3 camPos){ this->camPos = camPos; this->updateView(); } void Camera::setUpPos(glm::vec3 upPos){ this->upPos = upPos; this->updateView(); } void Camera::setTargetPos(glm::vec3 targetPos){ this->targetPos = targetPos; this->updateView(); }
true
4a2053190620c523d763f9182a8bc5efea99bfde
C++
shadow-paw/cat
/libcat/src/cat_util_string.cpp
UTF-8
3,331
3.046875
3
[ "MIT" ]
permissive
#include "cat_util_string.h" #include <algorithm> #include <cctype> using namespace cat; // ---------------------------------------------------------------------------- std::string StringUtil::trim(const std::string& s) { std::string result = s; result.erase(result.begin(), std::find_if(result.begin(), result.end(), [](int ch) { return !std::isspace(ch); })); result.erase(std::find_if(result.rbegin(), result.rend(), [](int ch) { return !std::isspace(ch); }).base(), result.end()); return result; } // ---------------------------------------------------------------------------- std::vector<std::string> StringUtil::split(const std::string& s, const std::string& delimiter, bool should_trim) { std::vector<std::string> result; size_t cursor = 0, pos; while ((pos = s.find(delimiter, cursor)) != std::string::npos) { auto splitted = s.substr(cursor, pos - cursor); if (should_trim) splitted = StringUtil::trim(splitted); if (!splitted.empty()) result.push_back(splitted); cursor = pos +1; } auto splitted = s.substr(cursor); if (should_trim) splitted = StringUtil::trim(splitted); if (!splitted.empty()) result.push_back(splitted); return result; } // ---------------------------------------------------------------------------- // Windows // ---------------------------------------------------------------------------- #if defined(PLATFORM_WIN32) || defined(PLATFORM_WIN64) // ---------------------------------------------------------------------------- std::basic_string<TCHAR> StringUtil::make_tstring(const char*s) { std::basic_string<TCHAR> rez; if (!s) return rez; int len = MultiByteToWideChar(CP_UTF8, 0, s, -1, nullptr, 0); if (len == 0) return rez; rez.resize(len); len = MultiByteToWideChar(CP_UTF8, 0, s, -1, &rez[0], len); if (len == 0) { rez.resize(0); return rez; } rez.resize(len - 1); return rez; } // ---------------------------------------------------------------------------- std::basic_string<TCHAR> StringUtil::make_tstring(const std::string& s) { return make_tstring(s.c_str()); } // ---------------------------------------------------------------------------- std::string StringUtil::make_string(const TCHAR* s) { std::string rez; if (!s) return rez; int len = WideCharToMultiByte(CP_UTF8, 0, s, -1, nullptr, 0, NULL, NULL); if (len == 0) return rez; rez.resize(len); len = WideCharToMultiByte(CP_UTF8, 0, s, -1, &rez[0], len, NULL, NULL); if (len == 0) { rez.resize(0); return rez; } rez.resize(len - 1); return rez; } // ---------------------------------------------------------------------------- void StringUtil::tstrings_each(const TCHAR* s, std::function<bool(const std::string& s)> cb) { std::string rez; if (!s || s[0]==0) return; int len = WideCharToMultiByte(CP_UTF8, 0, s, -1, nullptr, 0, NULL, NULL); if (len > 0) { rez.resize(len); len = WideCharToMultiByte(CP_UTF8, 0, s, -1, &rez[0], len, NULL, NULL); rez.resize(len == 0 ? 0 : len - 1); if (!cb(std::move(rez))) return; if (len>0) return tstrings_each(s + len, cb); } } // ---------------------------------------------------------------------------- #endif
true
718d5ce71ebd8f0e819c6012e29374a5fe39480e
C++
Anubhav12345678/competitive-programming
/EfficientSearchInA2DMatrix.cpp
UTF-8
1,596
3.03125
3
[]
no_license
class Solution { public: bool binsearch(vector<vector<int>> &v,int x,int i,int jl,int jh) { while(jl<=jh) { int jm = (jl+jh)/2; if(v[i][jm]==x) return true; else if(v[i][jm]>x) jh=jm-1; else jl = jm+1; } return false; } bool searchMatrix(vector<vector<int>>& matrix, int target) { int m = matrix.size(); if(m==0) return 0; int n = matrix[0].size(); int i,j,k,l,p,q; if(m==0||n==0) return 0; i=0,j=n-1; if(m==1) return binsearch(matrix,target,0,0,n-1); int il = 0,ih = m-1,jm = n/2; while((il+1)<ih) { int im = (il+ih)/2; if(matrix[im][jm]==target) return true; else if(matrix[im][jm]>target) ih = im; else il=im; } if(il>=0&&il<m) { if(matrix[il][jm]==target) return true; if(matrix[il+1][jm]==target) return true; if(jm>=1&&target<=matrix[il][jm-1]) return binsearch(matrix,target,il,0,jm-1); else if((jm+1)<n&&target>=matrix[il][jm+1]&&target<=matrix[il][n-1]) return binsearch(matrix,target,il,jm+1,n-1); else if(jm>0&&target<=matrix[il+1][jm-1]) return binsearch(matrix,target,il+1,0,jm-1); else if(jm>0) return binsearch(matrix,target,il+1,jm+1,n-1); } return false; } };
true
2a2b52c2ee4758fce71899e5785913ce9c7e3342
C++
kuwt/miscTest
/misc/imageWrapper/imageWrapper.h
UTF-8
405
2.96875
3
[]
no_license
#pragma once class ImageWrapper { public: ImageWrapper(int width, int height); virtual ~ImageWrapper(); ImageWrapper(const ImageWrapper&other); ImageWrapper& operator=(const ImageWrapper& other); ImageWrapper(ImageWrapper&& other); ImageWrapper& operator=(ImageWrapper&& other); int getImageSize(); unsigned char * getData(); private: int m_imageSize = 0; unsigned char *m_p = NULL; };
true
dfa5810b7790fa95fc7a83ec3eb28fc40167a156
C++
Stasqq/Roulette_Game
/Player.cpp
UTF-8
5,761
3.359375
3
[]
no_license
// // Created by Stasiek on 2018-12-16. // #include "Player.h" Player::Player() { money = 0; bets = CyclicList<Bet>(); name = " "; } void Player::addBet(int howMuch, enum betType typ) { bets.pushBack(Bet(typ, howMuch)); money -= howMuch; } void Player::addBet(int howMuch, enum betType typ, int *numbers, int howMuchNumbers) { Bet nBet; nBet = Bet(typ, numbers, howMuch, howMuchNumbers); bets.pushBack(nBet); money -= howMuch; } void Player::checkBet(Bet *bet, Component *field) { int type = bet->getType(); switch (type) { case 1: { if (field->getColor() == "red") { money = money + bet->getHowMuch() * 2; std::cout<<name<<" won "<<bet->getHowMuch() * 2<<std::endl; } } break; case 2: { if (field->getColor() == "black") { money = money + bet->getHowMuch() * 2; std::cout<<name<<" won "<<bet->getHowMuch() * 2<<std::endl; } } break; case 3: { if (field->getValue() < 19 && field->getValue() != 0) { money = money + bet->getHowMuch() * 2; std::cout<<name<<" won "<<bet->getHowMuch() * 2<<std::endl; } } break; case 4: { if (field->getValue() > 18) { money = money + bet->getHowMuch() * 2; std::cout<<name<<" won "<<bet->getHowMuch() * 2<<std::endl; } } break; case 5: { if (field->getValue() % 2 == 0) { money = money + bet->getHowMuch() * 2; std::cout<<name<<" won "<<bet->getHowMuch() * 2<<std::endl; } } break; case 6: { if (field->getValue() % 2 == 1) { money = money + bet->getHowMuch() * 2; std::cout<<name<<" won "<<bet->getHowMuch() * 2<<std::endl; } } break; case 7: { if (field->getValue() > 0 && field->getValue() < 13) { money = money + bet->getHowMuch() * 3; std::cout<<name<<" won "<<bet->getHowMuch() * 3<<std::endl; } } break; case 8: { if (field->getValue() > 12 && field->getValue() < 25) { money = money + bet->getHowMuch() * 3; std::cout<<name<<" won "<<bet->getHowMuch() * 3<<std::endl; } } break; case 9: { if (field->getValue() > 24 && field->getValue() < 37) { money = money + bet->getHowMuch() * 3; std::cout<<name<<" won "<<bet->getHowMuch() * 3<<std::endl; } } break; case 10: { if (field->getValue() < 4) { money = money + bet->getHowMuch() * 7; std::cout<<name<<" won "<<bet->getHowMuch() * 7<<std::endl; } } break; case 11: { if (bet->checkValue(field->getValue())) { money = money + bet->getHowMuch() * 3; std::cout<<name<<" won "<<bet->getHowMuch() * 3<<std::endl; } } break; case 12: { if (bet->checkValue(field->getValue())) { money = money + bet->getHowMuch() * 6; std::cout<<name<<" won "<<bet->getHowMuch() * 6<<std::endl; } } break; case 13: { if (bet->checkValue(field->getValue())) { money = money + bet->getHowMuch() * 9; std::cout<<name<<" won "<<bet->getHowMuch() * 9<<std::endl; } } break; case 14: { if (bet->checkValue(field->getValue())) { money = money + bet->getHowMuch() * 12; std::cout<<name<<" won "<<bet->getHowMuch() * 12<<std::endl; } } break; case 15: { if (bet->checkValue(field->getValue())) { money = money + bet->getHowMuch() * 18; std::cout<<name<<" won "<<bet->getHowMuch() * 18<<std::endl; } } break; case 16: { if (field->getValue() == bet->getTab()[0]) { money = money + bet->getHowMuch() * 36; std::cout<<name<<" won "<<bet->getHowMuch() * 36<<std::endl; } } break; default: { } break; } } void Player::checkBets(Component *field) { if (bets.size() != 0) { int nrBet = bets.size(); for (int i = 0; i < nrBet; i++) { checkBet(bets.getByIndex(i), field); } } else { return; } } void Player::clearBets() { bets = CyclicList<Bet>(); } std::string Player::showBets() { std::string output; if (bets.size() != 0) { for (int i = 0; i < bets.size(); i++) { output += std::to_string(i + 1) + ". " + std::to_string(bets.getByIndex(i)->getType()) + " for " + std::to_string(bets.getByIndex(i)->getHowMuch()) + "\n"; } } else { output = "You have no bets\n"; } return output; } void Player::deleteBet(int index) { money += bets.getByIndex(index)->getHowMuch(); bets.deleteByIndex(index); } int Player::getMoney() { return money; } void Player::addMoney(int newMoney) { money += newMoney; } void Player::setName(std::string x) { name = x; } std::string Player::getName() { return name; } int Player::getBetsSize() { return bets.size(); } Bet *Player::getBet(int index) { return bets.getByIndex(index); }
true
1268e285bd426e121209bb6c1ad4eb453b6edc95
C++
john-ababa/ProjectEuler
/020/022.cpp
UTF-8
1,622
3.703125
4
[]
no_license
////////////////////////////////////////////////////////////////////// // Problem 22 // // 5000個以上の名前が書かれている46Kのテキストファイルnames.txt を用いる. // http://projecteuler.net/project/names.txt // // まずアルファベット順にソートせよ. // のち, 各名前についてアルファベットに値を割り振り, // リスト中の出現順の数と掛け合わせることで, 名前のスコアを計算する. // // たとえば, リストがアルファベット順にソートされているとすると, COLINはリストの938番目にある. // またCOLINは3 + 15 + 12 + 9 + 14 = 53という値を持つ. // よってCOLINは938 * 53 = 49714というスコアを持つ. // // ファイル中の全名前のスコアの合計を求めよ. ////////////////////////////////////////////////////////////////////// #include <iostream> #include <fstream> #include <string> #include <vector> #include <algorithm> #include <assert.h> int wordScore(const std::string& word, const int n) { int sum = 0; for (auto itr = word.cbegin(); itr != word.cend(); ++itr) { if (*itr != '"') sum += *itr - 'A' + 1; } return sum * n; } int problem22() { std::vector<std::string> words; std::ifstream ifs("names.txt"); std::string line; while (std::getline(ifs, line, ',')) words.push_back(line); std::sort(words.begin(), words.end()); int score = 0; for (size_t i = 0; i < words.size(); ++i) score += wordScore(words[i], i+1); return score; } int main(void) { assert(wordScore("\"COLIN\"", 938) == 49714); std::cout << problem22() << std::endl; }
true
d9e4dba1d549ee9f41ca726a049d818a718afcd8
C++
Rickym72/cpsc323ass2
/main.cpp
UTF-8
2,199
2.984375
3
[]
no_license
/* - Use g++ -Wall -c -g main.cpp -o main.o followed by g++ main.o -o main - Run the program with ./main */ // Include Libraries and header files #include <iostream> #include "FSM.h" #include "syntax.h" using namespace std; int main(int argc, char *argv[]) { //initalizing variables vector<string> codeVector; ofstream fout; ifstream fin; string file_name; string input; string line; //error message for incorrect command if(argc < 2) {cout << "ERROR - format should be: ./main inputFile\n"; exit(1);} else input = argv[1]; //Open our input fin.open(input); if (!fin.is_open()) {cerr << "File Opening Error\n"; exit(-1);} while (getline(fin, line)) {codeVector.push_back(line);} fin.close(); //LEXER cout << "Time for lexer to do its thing...." << endl; //vector data type creation vector<tokens> lexerStorage; FSM machine; //initializing int state = 0; int lexStart = 0; // These for loops need the integer type because of the return type of .size() and .length() for (long long unsigned int vecString = 0; vecString < codeVector.size(); vecString++) { for (long long unsigned int vecChar = 0; vecChar <= codeVector[vecString].length(); vecChar++) { if (state == 0) { lexStart = vecChar; } state = machine.check_input(state, machine.char_to_input(codeVector[vecString][vecChar])); if (machine.is_final_state(state)) { if (machine.should_back_up(state)) { vecChar--; } if (state != 7) { string lex = ""; for (long long unsigned int i = lexStart; i <= vecChar; i++) { lex += codeVector[vecString][i]; } if (machine.getTokenName(state, lex) != "OTHER") { lexerStorage.push_back(tokens(machine.getTokenName(state, lex), lex)); } }//set state state = 0; } } } //output file stream (tokens/lexemes) to text file. fout.open("output.txt"); if(!fout.is_open()){ cout << "Output File Error\n"; exit(1);} if (!syntaxAnalyze(lexerStorage, fout)) { cout << "Syntax error" << endl; fout << "ERROR: syntax error found in the source code" << endl; } fout.close(); return 0; }
true
3f8c5ca7508e119ef529604f4741c13b6b0edc97
C++
hfloresr/connect4
/search_settings.h
UTF-8
233
2.703125
3
[]
no_license
class SearchSettings { public: SearchSettings() : timeLimit(0) {} void SetTimeLimit(int timeInSeconds) { timeLimit = timeInSeconds; } int GetTimeLimit() const { return timeLimit; } private: int timeLimit; };
true
62d0cbd38dc2a469a9c489bfb767f591b43ae394
C++
Verdax97/Pongherillo
/pong.ino
UTF-8
11,531
2.734375
3
[]
no_license
#include <Wire.h> // This library allows you to communicate with I2C #include <Adafruit_GFX.h> // Adafruit GFX graphics core library #include <Adafruit_SSD1306.h> // Driver library for 'monochrome' 128x64 and 128x32 OLEDs /* Showing number 0-9 on a Common Anode 7-segment LED display Displays the numbers 0-9 on the display, with one second inbetween. A --- F | | B | G | --- E | | C | | --- D This example code is in the public domain. */ // Pin 2-8 is connected to the 7 segments of the display. // pin 9 is for buzzer #define pinA 2 #define pinB 3 #define pinC 4 #define pinD 5 #define pinE 6 #define pinF 7 #define pinG 8 #define BUZZER_PIN 9 #define D1 10 #define D2 11 #define D3 12 #define D4 13 // Define the PINS you're goint to use on your Arduino Nano int controller1 = 0; // ANALOG 0 int controller2 = 1; // ANALOG 1 //int ledPin = 4; // DIGITAL 4 int btnPin = 13; // DIGITAL 13 // Define variables int buttonState = 0; // HIGH = Pressed int gameState = 0; // 0 = Home, 1 = Game, 2 = End int controllerValue1 = 0; // variable to store the value coming from the potentiometer int controllerValue2 = 0; // variable to store the value coming from the potentiometer int paddlePositionPlayer1 = 0; int paddlePositionPlayer2 = 0; int scorePlayer1 = 0; int scorePlayer2 = 0; int ballX = 128 / 2; int ballY = 64 / 2; int ballSpeedX = 2; int ballSpeedY = 1; int maxScore; #define OLED_RESET 4 Adafruit_SSD1306 display(OLED_RESET); #if (SSD1306_LCDHEIGHT != 64) #error("Height incorrect, please fix Adafruit_SSD1306.h!"); #endif void setup() { pinMode(btnPin, INPUT); pinMode(pinA, OUTPUT); pinMode(pinB, OUTPUT); pinMode(pinC, OUTPUT); pinMode(pinD, OUTPUT); pinMode(pinE, OUTPUT); pinMode(pinF, OUTPUT); pinMode(pinG, OUTPUT); pinMode(BUZZER_PIN, OUTPUT); pinMode(D1, OUTPUT); pinMode(D2, OUTPUT); pinMode(D3, OUTPUT); pinMode(D4, OUTPUT); Serial.begin(9600); display.begin(SSD1306_SWITCHCAPVCC, 0x3C); // initialize with the I2C addr 0x3C (for the 128x64) display.clearDisplay(); // Status led on... } void loop() { // Read controller value and calculate paddle position controllerValue1 = analogRead(controller1); controllerValue1 = map(controllerValue1, 0, 1024, 1024, 0); controllerValue2 = analogRead(controller2); controllerValue2 = map(controllerValue2, 0, 1024, 1024, 0); paddlePositionPlayer1 = controllerValue1 * (46.0 / 1023.0); paddlePositionPlayer2 = controllerValue2 * (46.0 / 1023.0); // Set button state buttonState = digitalRead(btnPin); if ((buttonState == HIGH || controllerValue2 > 1000)&& (gameState == 0 || gameState == 2)) { gameState = 1; scorePlayer1 = 0; scorePlayer2 = 0; delay(100); } else if (buttonState == HIGH && (gameState == 1 || gameState == 2)) { gameState = 0; scorePlayer1 = 0; scorePlayer2 = 0; ballX = 128 / 2; ballY = 64 / 2; delay(100); } if (gameState == 0) { display.setTextSize(2); display.setTextColor(WHITE); display.setCursor(40, 18); display.println("PONG"); display.setTextSize(1); display.setTextColor(WHITE); display.setCursor(32, 38); display.println("press start"); display.setCursor(39, 50); display.print("goals: "); maxScore = map(controllerValue1, 0, 1024, 1, 30); display.println(maxScore); display.display(); display.clearDisplay(); ballSpeedX = 1; // play menu theme (totally uncopyrighted) tone(BUZZER_PIN, 510 ,100); delay ( 450); tone(BUZZER_PIN, 380 ,100); delay ( 400); tone(BUZZER_PIN, 320 ,100); delay ( 500); tone(BUZZER_PIN, 440 ,100); delay ( 300); tone(BUZZER_PIN, 480 ,80); delay ( 330); tone(BUZZER_PIN, 450 ,100); delay ( 150); tone(BUZZER_PIN, 430 ,100); delay ( 300); tone(BUZZER_PIN, 380 ,100); delay ( 200); tone(BUZZER_PIN, 660 ,80); delay ( 200); tone(BUZZER_PIN, 760 ,50); delay ( 150); tone(BUZZER_PIN, 860 ,100); delay ( 300); tone(BUZZER_PIN, 700 ,80); delay ( 150); tone(BUZZER_PIN, 760 ,50); delay ( 350); tone(BUZZER_PIN, 660 ,80); delay ( 300); tone(BUZZER_PIN, 520 ,80); delay ( 150); tone(BUZZER_PIN, 580 ,80); delay ( 150); tone(BUZZER_PIN, 480 ,80); delay ( 500); } if (gameState == 1) { int cifraSx, cifraDx; cifraSx = scorePlayer1 / 10; cifraDx = scorePlayer1 % 10; ScriviNumeri(0, cifraSx); drawField(scorePlayer1, scorePlayer2); cifraSx = scorePlayer2 / 10; collisionControl(); ScriviNumeri(1, cifraDx); drawBall(); cifraDx = scorePlayer2 % 10; ScriviNumeri(2, cifraSx); display.display(); ScriviNumeri(3, cifraDx); display.clearDisplay(); } if (gameState == 2) { drawField(scorePlayer1, scorePlayer2); display.setTextSize(1); display.setTextColor(WHITE); if (scorePlayer1 == maxScore) { display.setCursor(15, 30); } else if (scorePlayer2 == maxScore) { display.setCursor(77, 30); } display.println("winner!"); display.setCursor(65, 36); display.println(""); display.display(); display.clearDisplay(); } if (gameState != 1) { digitalWrite(D1, 1); digitalWrite(D2, 1); digitalWrite(D3, 1); digitalWrite(D4, 1); } } void ScriviNumeri(int cifra, int val) { digitalWrite(D1, 1); digitalWrite(D2, 1); digitalWrite(D3, 1); digitalWrite(D4, 1); if (cifra == 0) digitalWrite(D1, 0); if (cifra == 1) digitalWrite(D2, 0); if (cifra == 2) digitalWrite(D3, 0); if (cifra == 3) digitalWrite(D4, 0); switch (val) { case 0: Zero(); break; case 1: Uno(); break; case 2: Due(); break; case 3: Tre(); break; case 4: Quattro(); break; case 5: Cinque(); break; case 6: Sei(); break; case 7: Sette(); break; case 8: Otto(); break; case 9: Nove(); break; } delay(1); } void Zero() { digitalWrite(pinA, 1); digitalWrite(pinB, 1); digitalWrite(pinC, 1); digitalWrite(pinD, 1); digitalWrite(pinE, 1); digitalWrite(pinF, 1); digitalWrite(pinG, LOW); } void Uno() { digitalWrite(pinA, 0); digitalWrite(pinB, 1); digitalWrite(pinC, 1); digitalWrite(pinD, 0); digitalWrite(pinE, 0); digitalWrite(pinF, 0); digitalWrite(pinG, LOW); } void Due() { digitalWrite(pinA, 1); digitalWrite(pinB, 1); digitalWrite(pinC, 0); digitalWrite(pinD, 1); digitalWrite(pinE, 1); digitalWrite(pinF, 0); digitalWrite(pinG, 1); } void Tre() { digitalWrite(pinA, 1); digitalWrite(pinB, 1); digitalWrite(pinC, 1); digitalWrite(pinD, 1); digitalWrite(pinE, 0); digitalWrite(pinF, 0); digitalWrite(pinG, 1); } void Quattro() { digitalWrite(pinA, 0); digitalWrite(pinB, 1); digitalWrite(pinC, 1); digitalWrite(pinD, 0); digitalWrite(pinE, 0); digitalWrite(pinF, 1); digitalWrite(pinG, 1); } void Cinque() { digitalWrite(pinA, 1); digitalWrite(pinB, 0); digitalWrite(pinC, 1); digitalWrite(pinD, 1); digitalWrite(pinE, 0); digitalWrite(pinF, 1); digitalWrite(pinG, 1); } void Sei() { digitalWrite(pinA, 1); digitalWrite(pinB, 0); digitalWrite(pinC, 1); digitalWrite(pinD, 1); digitalWrite(pinE, 1); digitalWrite(pinF, 1); digitalWrite(pinG, 1); } void Sette() { digitalWrite(pinA, 1); digitalWrite(pinB, 1); digitalWrite(pinC, 1); digitalWrite(pinD, 0); digitalWrite(pinE, 0); digitalWrite(pinF, 0); digitalWrite(pinG, LOW); } void Otto() { digitalWrite(pinA, 1); digitalWrite(pinB, 1); digitalWrite(pinC, 1); digitalWrite(pinD, 1); digitalWrite(pinE, 1); digitalWrite(pinF, 1); digitalWrite(pinG, 1); } void Nove() { digitalWrite(pinA, 1); digitalWrite(pinB, 1); digitalWrite(pinC, 1); digitalWrite(pinD, 1); digitalWrite(pinE, 0); digitalWrite(pinF, 1); digitalWrite(pinG, 1); } void drawField(int score1, int score2) { display.fillRect(0, round(paddlePositionPlayer1), 2, 18, 1); display.fillRect(126, round(paddlePositionPlayer2), 2, 18, 1); display.setTextSize(1); display.setTextColor(WHITE); display.setCursor(55, 0); if (score1>9) display.setCursor(51,0); display.print(score1); display.print(":"); display.print(score2); display.fillRect(63, 12, 1, 5, 1); display.fillRect(63, 22, 1, 5, 1); display.fillRect(63, 32, 1, 5, 1); display.fillRect(63, 42, 1, 5, 1); display.fillRect(63, 52, 1, 5, 1); display.fillRect(63, 62, 1, 5, 1); } void collisionControl() { //bounce from top and bottom if (ballY >= 64 - 2 || ballY <= 0) { ballSpeedY *= -1; } //score points if ball hits wall behind player if (ballX >= 128 || ballX <= 0) { if (ballSpeedX > 0) { ballSpeedX = 1; scorePlayer1++; ballX = 128 / 4; } if (ballSpeedX < 0) { ballSpeedX = -1; scorePlayer2++; ballX = 128 / 4 * 3; } if (scorePlayer1 == maxScore || scorePlayer2 == maxScore) { gameState = 2; } } //bounce from player1 if (((ballX >= 128 - 2 - 2 && ballX <= 128 - 2) || (ballX + ballSpeedX <= 2)) && ballSpeedX < 0) { // play player1 tone tone(BUZZER_PIN, 510 ,100); if (ballY > round(paddlePositionPlayer1) - 2 && ballY < round(paddlePositionPlayer1) + 18) { if (abs(ballSpeedX) == 8) { ballSpeedX *= -1; } else ballSpeedX *= -2; ballX = 4; if (ballY <= round(paddlePositionPlayer1) + 9) { if (ballY <= round(paddlePositionPlayer1) + 6) ballSpeedY = -2; else ballSpeedY = -1; } else { if (ballY <= round(paddlePositionPlayer1) + 12) ballSpeedY = 1; else ballSpeedY = 2; } } } //bounce from player2 if (((ballX >= 128 - 2 - 2 && ballX <= 128 - 2) || (ballX + ballSpeedX >= 126)) && ballSpeedX > 0) { // play player2 tone tone(BUZZER_PIN, 380 ,100); if (ballY > round(paddlePositionPlayer2) - 2 && ballY < round(paddlePositionPlayer2) + 18) { if (abs(ballSpeedX) == 8) { ballSpeedX *= -1; } else ballSpeedX *= -2; ballX = 125; if (ballY <= round(paddlePositionPlayer2) + 9) { if (ballY <= round(paddlePositionPlayer2) + 4) ballSpeedY = -2; else ballSpeedY = -1; } else { if (ballY <= round(paddlePositionPlayer2) + 13) ballSpeedY = 1; else ballSpeedY = 2; } } } } void drawBall() { display.fillRect(ballX, ballY, 2, 2, 1); Serial.println(ballSpeedY); ballX += ballSpeedX; ballY += ballSpeedY; }
true
4e74bdba3d28e4704a4d4d57c218fc671b794013
C++
rintujrajan/DesignPattern
/PatternsCompunded/Vending_Machine/States/ReadyToTakeOrderState.cpp
UTF-8
1,842
3.1875
3
[]
no_license
#include "ReadyToTakeOrderState.h" #include <iostream> #include "../VendingMachine.h" ReadyToTakeOrderState::ReadyToTakeOrderState(VendingMachine* vendingMachine) { vendingMachineInstance = vendingMachine; } void ReadyToTakeOrderState::readyToTakeOrder() { int coffeeType = -1; int beverageSize = -1; float cost = 0; float cashReceived = 0; std::cout<<"\nMenu:" << "\n\t1. Black Coffee" << "\n\t2. Café au Lait(Black Coffee and Steamed milk)" << "\n\t3. Espresso" << "\n\t4. Latte(Espresso and Steamed milk)" << "\n\t5. Cappuccino(Espresso ,Steamed milk and Whip/Foam)" << "\n\t6. Mocha(Espresso, Chocolate and Steamed milk)" << "\n\t *****Enter 0 to Exit*****" << "\nYour beverage choice please:"; std::cin>>coffeeType; if(coffeeType!=0) { std::cout<<"\nAvailable Beverage Sizes :" << "\n\t1. Small" << "\n\t2. Medium" << "\n\t3. Large" << "\nYour beverage size please:"; std::cin>>beverageSize; vendingMachineInstance->selectBeverage(coffeeType,beverageSize); std::cout<<"Thanks, beverage selection done. Cost of selected beverage is "<<vendingMachineInstance->getCostOfSelectedBeverage(); vendingMachineInstance->setState(VendingMachine::MachineState::BEVERAGE_SELECTED); } } bool ReadyToTakeOrderState::beverageSelected() { std::cout<<"Invalid selection. Please select a beverage.\n"; return false; } bool ReadyToTakeOrderState::cashCollected() { std::cout<<"\n"; return false; } void ReadyToTakeOrderState::changeDispensed() { std::cout<<"\n"; } void ReadyToTakeOrderState::beverageDispensedOrCancelOperation() { std::cout<<"No action performed\n"; }
true
186266deae9eb8d7c71adffd64b73dbe1c6af2fc
C++
maikel1991p3/AlgoritmosClustering
/algoritmos/AlgMultiArranque.cpp
UTF-8
3,869
2.8125
3
[]
no_license
/* * AlgMultiArranque.cpp * * Created on: 12/04/2014 * Author: maikel */ #include "AlgMultiArranque.h" AlgMultiArranque::AlgMultiArranque(vector<Cluster*>& clusters, vector<Objeto*>& objetos) { setNombreAlgoritmo(" Técnica MultiArranque "); setObjetos(objetos); setClusters(clusters); setDimension(getClusters()[0]->getDimension()); int* sol = new int [getObjetos().size()]; _solActual = new int [getObjetos().size()]; _mejorSol = new int [getObjetos().size()]; for (unsigned int i = 0; i < getObjetos().size(); ++i) { sol[i] = -1; } setSolucion(sol); delete [] sol; _tecnicaLocal = NULL; _centroidesFin = new int *[getClusters().size()]; for (unsigned int i = 0; i < getClusters().size(); ++i) _centroidesFin[i] = new int[getDimension()]; } AlgMultiArranque::~AlgMultiArranque() { if (_mejorSol != NULL) delete [] _mejorSol; if (_solActual != NULL) delete [] _solActual; if (_tecnicaLocal != NULL) delete _tecnicaLocal; } void AlgMultiArranque::ejecutarAgrupamiento () { int contadorMejora = 0, tipo = 0; double desvMejor = 0.0; TIPO_TECN_LOCAL tecnicaLocal; cout << " Elija técnica local: 0 = LOCAL VORAZ, 1 = LOCAL GRASP " << endl; cin >> tipo; tecnicaLocal = (TIPO_TECN_LOCAL) tipo; // ****** Inicialización ****** generarCentroides(); _solActual = busquedaLocal(tecnicaLocal); desvMejor = calcularDesvAgrup(_solActual); guardarCentroides (getClusters()); copiarSolucion (_solActual, _mejorSol); // origen, destino // ****** Procedimiento MultiArranque ****** do { _solActual = busquedaLocal(tecnicaLocal); if (calcularDesvAgrup(_solActual) < desvMejor) { desvMejor = calcularDesvAgrup(_solActual); copiarSolucion(_solActual, _mejorSol); contadorMejora = 0; guardarCentroides(getClusters()); } ++contadorMejora; generarCentroides(); } while (hayMejora(contadorMejora)); // ****** Asignación de soluciones ****** setSolucion(_mejorSol); // Asigne la sol. global del problema recuperarCentroides (); // Recupera los centroides de la solución que mejoró la actual mejor asignarClusters (); // Asigne a cada objeto su clasificación final } void AlgMultiArranque::generarCentroides () { for (unsigned int i = 0; i < getClusters().size(); ++i) { for (int j = 0; j < getClusters()[i]->getDimension(); ++j) getClusters()[i]->getCaracteristicas()[j] = rand () % 10; } } int* AlgMultiArranque::busquedaLocal (enum TIPO_TECN_LOCAL tipo) { int* resultado = NULL; switch (tipo) { case VORAZ: if (_tecnicaLocal) delete _tecnicaLocal; _tecnicaLocal = new AlgVoraz(getClusters().size(), getObjetos()); _tecnicaLocal->ejecutarAgrupamiento(); resultado = _tecnicaLocal->getSolucion(); break; case GRASP: if (_tecnicaLocal) delete _tecnicaLocal; _tecnicaLocal = new AlgGRASP(getClusters(), getObjetos(), 2); // Nº candidatos LRC !! _tecnicaLocal->ejecutarAgrupamiento(); resultado = _tecnicaLocal->getSolucion(); break; /* IGNORAR */ case GRAVITACION: if (_tecnicaLocal) delete _tecnicaLocal; _tecnicaLocal = new AlgGravitacion (getClusters(), getObjetos()); _tecnicaLocal->ejecutarAgrupamiento(); resultado = _tecnicaLocal->getSolucion(); break; /* IGNORAR */ default: cerr << "ERROR: ASIGNE UN TIPO DE TÉCNICA COMO BÚSQUEDA LOCAL!!" << endl; } return resultado; } bool AlgMultiArranque::hayMejora (int c) { return (c < 5000) ? true : false; } void AlgMultiArranque::guardarCentroides (vector<Cluster*>& centr) { for (unsigned int i = 0; i < centr.size(); ++i) { for (int j = 0; j < getDimension(); ++j) { _centroidesFin[i][j] = centr[i]->getCaracteristicas()[j]; } } } void AlgMultiArranque::recuperarCentroides () { for (unsigned int i = 0; i < getClusters().size(); ++i) { for (int j = 0; j < getDimension(); ++j) { getClusters()[i]->getCaracteristicas()[j] = _centroidesFin[i][j]; } } }
true
8189fd2984d9df9b032715dc79ebebd7b1dc05a1
C++
legobridge/opengl-water-simulation
/src/scene.cpp
UTF-8
13,613
2.578125
3
[]
no_license
#include <iostream> #include "glad/glad.h" #include "GLFW/glfw3.h" #include "scene.h" using namespace std; // Constructor Scene::Scene() : modelShader("../src/shader/model.vs", "../src/shader/model.fs") , terrainModel("../model/terrain/terrain.obj", modelShader) , treeModel("../model/tree/tree.obj", modelShader) , grassModel("../model/grass/grass.obj", modelShader) , waterModel("../model/water/water.obj", modelShader) { time = -30.0f; prevTime = (float)glfwGetTime(); timescale = 16.0f; paused = true; k = 1; waterLevels.resize((size_t)WORLD_D); terrainExistence.resize((size_t)WORLD_D); for (size_t i = 0; i < waterLevels.size(); i++) { waterLevels[i].resize((size_t)WORLD_W); terrainExistence[i].resize((size_t)WORLD_W); for (size_t j = 0; j < waterLevels[i].size(); j++) { waterLevels[i][j].assign((size_t)WORLD_H, 0); terrainExistence[i][j].assign((size_t)WORLD_H, false); } } setupTerrainHeights(); setupTerrainObject(); setupTreeObjects(); setupGrassObjects(); setupWaterObjects(); } // Read in the heightmap and setup terrain heights void Scene::setupTerrainHeights() { ifstream heightMap; heightMap.open("../model/terrain/height_map.txt"); if (!heightMap) { cout << "Unable to open file height_map.txt" << endl; } else { for (size_t i = 0; i < terrainExistence.size(); i++) { int n; heightMap >> n; size_t j = 0; for (int x = 0; x < n; x++) { int m, h; heightMap >> m >> h; while (m--) { for (int k = 0; k < h; k++) { terrainExistence[i][j][k] = true; } j++; } } } } } // Generic setup function void Scene::setupObjects(vector<Object> objects, Model model) { vector<glm::mat4> modelMatrices(objects.size()); for (size_t i = 0; i < objects.size(); i++) { modelMatrices[i] = glm::translate(glm::mat4(1.0f), objects[i].position); modelMatrices[i] = glm::scale(modelMatrices[i], objects[i].scale); } unsigned int buffer; glGenBuffers(1, &buffer); glBindBuffer(GL_ARRAY_BUFFER, buffer); glBufferData(GL_ARRAY_BUFFER, objects.size() * sizeof(glm::mat4), &modelMatrices[0], GL_STATIC_DRAW); for (size_t i = 0; i < model.meshes.size(); i++) { unsigned int VAO = model.meshes[i].VAO; glBindVertexArray(VAO); glEnableVertexAttribArray(3); glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4), (void*)0); glEnableVertexAttribArray(4); glVertexAttribPointer(4, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4), (void*)(sizeof(glm::vec4))); glEnableVertexAttribArray(5); glVertexAttribPointer(5, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4), (void*)(2 * sizeof(glm::vec4))); glEnableVertexAttribArray(6); glVertexAttribPointer(6, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4), (void*)(3 * sizeof(glm::vec4))); glVertexAttribDivisor(3, 1); glVertexAttribDivisor(4, 1); glVertexAttribDivisor(5, 1); glVertexAttribDivisor(6, 1); } } // Prepare terrain object for instantiation void Scene::setupTerrainObject() { glm::vec3 position = glm::vec3(0.0f, 0.0f, 0.0f); Object terrain(&terrainModel, position); terrainObjects.push_back(terrain); setupObjects(terrainObjects, terrainModel); } // Prepare tree objects for instantiation void Scene::setupTreeObjects() { Object tree1(&treeModel, glm::vec3(9.0f, 8.0f, -7.0f), glm::vec3(2.0f, 2.0f, 2.0f)); treeObjects.push_back(tree1); Object tree2(&treeModel, glm::vec3(13.0f, 7.0f, -4.0f), glm::vec3(3.0f, 3.0f, 3.0f)); treeObjects.push_back(tree2); Object tree3(&treeModel, glm::vec3(-12.0f, 7.0f, -4.0f), glm::vec3(2.5f, 2.5f, 2.5f)); treeObjects.push_back(tree3); Object tree4(&treeModel, glm::vec3(-8.0f, 9.0f, -8.0f), glm::vec3(3.5f, 3.5f, 3.5f)); treeObjects.push_back(tree4); Object tree5(&treeModel, glm::vec3(8.0f, 4.0f, 3.0f), glm::vec3(2.0f, 2.0f, 2.0f)); treeObjects.push_back(tree5); Object tree6(&treeModel, glm::vec3(-7.0f, 5.0f, 1.0f), glm::vec3(2.5f, 2.5f, 2.5f)); treeObjects.push_back(tree6); setupObjects(treeObjects, treeModel); } // Prepare grass objects for instantiation void Scene::setupGrassObjects() { srand(500); for (int i = (int)WORLD_D - 1; i >= 0; i--) { for (int j = 1; j < 11; j++) { for (int k = 1; k <= 10; k++) { if (terrainExistence[i][j][k - 1] && !terrainExistence[i][j][k]) { glm::vec3 position = glm::vec3((float)j + 0.25f - 15.0f, (float)k, (float)i + 0.435f - 10.0f); glm::vec3 scale = glm::vec3(0.5f, (20.0f + rand() % 80) / 100.0f, 0.20f); Object water(&grassModel, position, scale); grassObjects.push_back(water); } } } for (int j = 20; j < (int)WORLD_W - 1; j++) { for (int k = 1; k <= 10; k++) { if (terrainExistence[i][j][k - 1] && !terrainExistence[i][j][k]) { glm::vec3 position = glm::vec3((float)j + 0.25f - 15.0f, (float)k, (float)i + 0.435f - 10.0f); glm::vec3 scale = glm::vec3(0.5f, (20.0f + rand() % 80) / 100.0f, 0.20f); Object water(&grassModel, position, scale); grassObjects.push_back(water); } } } } setupObjects(grassObjects, grassModel); } // Prepare water blocks for instantiation void Scene::setupWaterObjects() { for (int i = (int)WORLD_D - 1; i >= 0; i--) { for (int j = 0; j < WORLD_W; j++) { for (int k = 0; k <= 10; k++) { glm::vec3 position = glm::vec3((float)j + 0.25f - 15.0f, (float)k, (float)i + 0.435f - 10.0f); glm::vec3 scale = glm::vec3(0.0f, 0.0f, 0.0f); Object water(&waterModel, position, scale); waterObjects.push_back(water); } } } setupObjects(waterObjects, waterModel); } // Add water at the top void Scene::addWater() { int flow = 155; for (size_t j = 12; j < 18; j++) { waterLevels[0][j][10] = min(255, waterLevels[0][j][9] + flow); } } // Refresh scales of water blocks to match waterLevels void Scene::refreshLevels() { int z = 0; for (int i = (int)WORLD_D - 1; i >= 0; i--) { for (int j = 0; j < WORLD_W; j++) { for (int k = 0; k <= 10; k++) { float waterPresent = (waterLevels[i][j][k] > 0) ? 1.0f : 0.0f; waterObjects[z++].scale = glm::vec3(waterPresent, (float)waterLevels[i][j][k] / 255.0f, waterPresent); } } } setupObjects(waterObjects, waterModel); } // Update water levels void Scene::updateWaterObjects() { for (int i = (int)WORLD_D - 1; i >= 0; i--) { for (int j = (int)(WORLD_W / 2)- 1; j >= 0; j--) { if (!waterLevels[i][j][k] == 0) { if (!terrainExistence[i][j][k - 1]) { if (waterLevels[i][j][k - 1] < 255) { int capacity = 255 - waterLevels[i][j][k - 1]; int amount = min(capacity, waterLevels[i][j][k]); waterLevels[i][j][k] -= amount; waterLevels[i][j][k - 1] += amount; } } if (j > 0 && !terrainExistence[i][j - 1][k - 1]) { if (waterLevels[i][j - 1][k - 1] < waterLevels[i][j][k]) { int capacity = 255 - waterLevels[i][j - 1][k - 1]; int amount = min(capacity, waterLevels[i][j][k] / 2); waterLevels[i][j][k] -= amount; waterLevels[i][j - 1][k - 1] += amount; } } if (j < (int)WORLD_W - 1 && !terrainExistence[i][j + 1][k - 1]) { if (waterLevels[i][j + 1][k - 1] < waterLevels[i][j][k]) { int capacity = 255 - waterLevels[i][j + 1][k]; int amount = min(capacity, waterLevels[i][j][k] / 2); waterLevels[i][j][k] -= amount; waterLevels[i][j + 1][k - 1] += amount; } } if (i < (int)WORLD_D - 1 && !terrainExistence[i + 1][j][k]) { if (waterLevels[i + 1][j][k] < waterLevels[i][j][k]) { int capacity = 255 - waterLevels[i + 1][j][k]; int amount = min(capacity, waterLevels[i][j][k]); waterLevels[i][j][k] -= amount; waterLevels[i + 1][j][k] += amount; } } if (j > 0 && !terrainExistence[i][j - 1][k]) { if (waterLevels[i][j - 1][k] < waterLevels[i][j][k]) { int capacity = 255 - waterLevels[i][j - 1][k]; int amount = min(capacity, waterLevels[i][j][k] / 2); waterLevels[i][j][k] -= amount; waterLevels[i][j - 1][k] += amount; } } if (j < (int)WORLD_W - 1 && !terrainExistence[i][j + 1][k]) { if (waterLevels[i][j + 1][k] < waterLevels[i][j][k]) { int capacity = 255 - waterLevels[i][j + 1][k]; int amount = min(capacity, waterLevels[i][j][k] / 2); waterLevels[i][j][k] -= amount; waterLevels[i][j + 1][k] += amount; } } if (i > 0 && !terrainExistence[i - 1][j][k]) { if (waterLevels[i - 1][j][k] < waterLevels[i][j][k]) { int capacity = 255 - waterLevels[i - 1][j][k]; int amount = min(capacity, waterLevels[i][j][k] / 2); waterLevels[i][j][k] -= amount; waterLevels[i - 1][j][k] += amount; } } } if (!waterLevels[i][(int)WORLD_W - 1 - j][k] == 0) { if (!terrainExistence[i][(int)WORLD_W - 1 - j][k - 1]) { if (waterLevels[i][(int)WORLD_W - 1 - j][k - 1] < 255) { int capacity = 255 - waterLevels[i][(int)WORLD_W - 1 - j][k - 1]; int amount = min(capacity, waterLevels[i][(int)WORLD_W - 1 - j][k]); waterLevels[i][(int)WORLD_W - 1 - j][k] -= amount; waterLevels[i][(int)WORLD_W - 1 - j][k - 1] += amount; } } if ((int)WORLD_W - 1 - j < (int)WORLD_W - 1 && !terrainExistence[i][(int)WORLD_W - 1 - j + 1][k - 1]) { if (waterLevels[i][(int)WORLD_W - 1 - j + 1][k - 1] < waterLevels[i][(int)WORLD_W - 1 - j][k]) { int capacity = 255 - waterLevels[i][(int)WORLD_W - 1 - j + 1][k]; int amount = min(capacity, waterLevels[i][(int)WORLD_W - 1 - j][k] / 2); waterLevels[i][(int)WORLD_W - 1 - j][k] -= amount; waterLevels[i][(int)WORLD_W - 1 - j + 1][k - 1] += amount; } } if (j > 0 && !terrainExistence[i][j - 1][k - 1]) { if (waterLevels[i][j - 1][k - 1] < waterLevels[i][j][k]) { int capacity = 255 - waterLevels[i][j - 1][k - 1]; int amount = min(capacity, waterLevels[i][j][k] / 2); waterLevels[i][j][k] -= amount; waterLevels[i][j - 1][k - 1] += amount; } } if (i < (int)WORLD_D - 1 && !terrainExistence[i + 1][(int)WORLD_W - 1 - j][k]) { if (waterLevels[i + 1][(int)WORLD_W - 1 - j][k] < waterLevels[i][(int)WORLD_W - 1 - j][k]) { int capacity = 255 - waterLevels[i + 1][(int)WORLD_W - 1 - j][k]; int amount = min(capacity, waterLevels[i][(int)WORLD_W - 1 - j][k]); waterLevels[i][(int)WORLD_W - 1 - j][k] -= amount; waterLevels[i + 1][(int)WORLD_W - 1 - j][k] += amount; } } if ((int)WORLD_W - 1 - j < (int)WORLD_W - 1 && !terrainExistence[i][(int)WORLD_W - 1 - j + 1][k]) { if (waterLevels[i][(int)WORLD_W - 1 - j + 1][k] < waterLevels[i][(int)WORLD_W - 1 - j][k]) { int capacity = 255 - waterLevels[i][(int)WORLD_W - 1 - j + 1][k]; int amount = min(capacity, waterLevels[i][(int)WORLD_W - 1 - j][k] / 2); waterLevels[i][(int)WORLD_W - 1 - j][k] -= amount; waterLevels[i][(int)WORLD_W - 1 - j + 1][k] += amount; } } if ((int)WORLD_W - 1 - j > 0 && !terrainExistence[i][(int)WORLD_W - 1 - j - 1][k]) { if (waterLevels[i][(int)WORLD_W - 1 - j - 1][k] < waterLevels[i][(int)WORLD_W - 1 - j][k]) { int capacity = 255 - waterLevels[i][(int)WORLD_W - 1 - j - 1][k]; int amount = min(capacity, waterLevels[i][(int)WORLD_W - 1 - j][k] / 2); waterLevels[i][(int)WORLD_W - 1 - j][k] -= amount; waterLevels[i][(int)WORLD_W - 1 - j - 1][k] += amount; } } if (i > 0 && !terrainExistence[i - 1][(int)WORLD_W - 1 - j][k]) { if (waterLevels[i - 1][(int)WORLD_W - 1 - j][k] < waterLevels[i][(int)WORLD_W - 1 - j][k]) { int capacity = 255 - waterLevels[i - 1][(int)WORLD_W - 1 - j][k]; int amount = min(capacity, waterLevels[i][(int)WORLD_W - 1 - j][k] / 2); waterLevels[i][(int)WORLD_W - 1 - j][k] -= amount; waterLevels[i - 1][(int)WORLD_W - 1 - j][k] += amount; } } } } } } // Toggle time (on/off) void Scene::toggleTime() { paused = !paused; } // Slow down time void Scene::slowDownTime() { timescale = max(0.0f, timescale - 2.0f); } // Speed up time void Scene::speedUpTime() { timescale = min(100.0f, timescale + 2.0f); } // Update current time void Scene::updateTime() { float add = 0.0f; float cur = (float)glfwGetTime(); float deltaTime = cur - prevTime; prevTime = cur; if (!paused) { add = deltaTime * timescale; } time += add; } // Driver function to perform routine tasks void Scene::drawObjects() { updateTime(); float cosine = cos(glm::radians(time)); float sine = sin(glm::radians(time)); float sunX = WORLD_W * sine; float sunY = WORLD_W * cosine; float lightVal = max(0.3f, cosine); glm::vec3 lightPos(sunX, sunY, 0.0f); // Clear buffers glClearColor(lightVal * 140.0f / 255.0f, lightVal * 180.0f / 255.0f, lightVal * 220.0f / 255.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Setup shader modelShader.use(); glm::mat4 projection = glm::perspective(glm::radians(camera.zoom), (float)SCR_W / (float)SCR_H, 0.1f, 10.0f * WORLD_W); glm::mat4 view = camera.GetViewMatrix(); modelShader.setMat4("projection", projection); modelShader.setMat4("view", view); modelShader.setVec3("lightPos", lightPos); modelShader.setVec3("viewPos", camera.position); modelShader.setVec3("lightColor", glm::vec3(lightVal, lightVal, lightVal)); updateWaterObjects(); k++; if (k == (int)WORLD_H - 5) { k = 1; addWater(); refreshLevels(); } // Draw objects terrainModel.draw(terrainObjects.size()); grassModel.draw(grassObjects.size()); waterModel.draw(waterObjects.size()); treeModel.draw(treeObjects.size()); }
true
495f2cd708f5dcb4ee00aae7f4cb7cc21f1b923a
C++
Modifying/Algorithm
/PointToLine/main.cpp
GB18030
955
3.328125
3
[]
no_license
// һƽϵn, ҳֱϵĵ. #include <vector> #include <map> #include <algorithm> #include <list> struct Point { int x; int y; Point() : x(0), y(0) {} Point(int a, int b) : x(a), y(b) {} }; int MaxPoints(std::vector<Point> &points) { if (points.size() < 2) return points.size(); int size = points.size(); int ret = 0; for (int i = 0; i < size - 1; ++i) { int dup = 0; int cnt = 1; int max = 1; std::map<double, int> mp; for (int j = i + 1; j < size; ++j) { double x = points[i].x - points[j].x; double y = points[i].y - points[j].y; if (x == 0 && y == 0) ++dup; else if (x == 0) { ++cnt; max = std::max(cnt, max); } else { double slope = y / x; if (mp[slope] == 0) mp[slope] = 2; else ++mp[slope]; max = std::max(mp[slope], max); } } ret = std::max(ret, max + dup); } return ret; } int main() { return 0; }
true
74272c21f072a7102fef6bbc1b0d4ac1d78aa068
C++
LaylaHirsh/Victor
/Energy/Sources/RapdfPotential.h
UTF-8
2,775
2.90625
3
[]
no_license
/** * @Class RapdfPotential * @Project Victor **/ #ifndef _RAPDFPOTENTIAL_H_ #define _RAPDFPOTENTIAL_H_ // Includes: #include <vector> #include <Potential.h> // Global constants, typedefs, etc. (to avoid): const unsigned int MAX_BINS = 18; const unsigned int MAX_TYPES = 168; namespace Biopool { /** @brief class implements the all-atom residue. * * @Description Includes methods that allow to manipulate the all-atom residue specific probability // discriminatory function from Samudrala & Moult (JMB 1998). * */ class RapdfPotential : public Potential { public: // CONSTRUCTORS/DESTRUCTOR: RapdfPotential(); virtual ~RapdfPotential() { PRINT_NAME; } // PREDICATES: virtual long double calculateEnergy(Spacer& sp); virtual long double calculateEnergy(Spacer& sp, unsigned int index1, unsigned int index2); virtual long double calculateEnergy(AminoAcid& aa, Spacer& sp); virtual long double calculateEnergy(AminoAcid& aa, AminoAcid& aa2); virtual long double calculateEnergy(Atom& at1, Atom& at2, string aaType, string aaType2); // MODIFIERS: // OPERATORS: protected: // HELPERS: unsigned int pGetDistanceBinOne(double distance); unsigned int pGetGroupBin(const char* group_name); // ATTRIBUTES: double prob[MAX_BINS][MAX_TYPES][MAX_TYPES]; public: //static string RAPDF_PARAM_FILE; //error at runtime in a 64 bit architecture, uncomment this if you are in a no 64bits SO string path; private: }; // --------------------------------------------------------------------------- // RapdfPotential // -----------------x-------------------x-------------------x----------------- /** * @Description calculates the energy between two atoms * @param the references to the atoms (Atom&,Atom&)the amino acid types(string,string) * @return the value of maximum propensity(long double) */ inline long double RapdfPotential::calculateEnergy(Atom& at1, Atom& at2, string aaType, string aaType2){ double d = at1.distance(at2); if ((d >= 20.0) || (at1.getType() == "OXT") || (at2.getType() == "OXT") || ((at1.getType() == "CB") && (aaType == "GLY")) || ((at2.getType() == "CB") && (aaType2 == "GLY")) ) return 0.0; string tmp1 = threeLetter2OneLetter(aaType) + at1.getType(); string tmp2 = threeLetter2OneLetter(aaType2) + at2.getType(); unsigned int dist = pGetDistanceBinOne(d); unsigned int grp1 = pGetGroupBin(tmp1.c_str()); unsigned int grp2 = pGetGroupBin(tmp2.c_str()); if (dist + grp1 + grp2 < 999) return prob[dist][grp1][grp2]; else // ignore errors return 0; } } // namespace #endif //_RAPDFPOTENTIAL_H_
true
96a832151b02f6620bbe3d964ea24eab4b498de2
C++
marcbejerano/cpp-tools
/libProperties/properties.cc
UTF-8
3,483
3.21875
3
[ "BSD-3-Clause" ]
permissive
#include <Properties> #include <Tools> #include <sstream> using namespace hslib; /** * Set a new property or update an existing property. * \param key Property key * \param value Property value * \return Reference to this object */ Properties& Properties::setProperty(const std::string& key, const std::string& value) { propertyMap[key] = value; return *this; } /** * Return an existing property or the default value if the * property key does not exist. * \param key Property key * \param defaultValue Default property value if requested key does not exist * \return Property value or the defaultValue. */ const std::string Properties::getProperty(const std::string& key, const std::string& defaultValue) const { std::string result = defaultValue; if (propertyMap.find(key) != propertyMap.end()) result = propertyMap.at(key); return result; } /** * Return the set of keys used in this property container. * \return Set of keys */ const std::set<std::string> Properties::keys() const { std::set<std::string> result; for (auto ix = propertyMap.cbegin(); ix != propertyMap.cend(); ++ix) { result.insert(ix->first); } return result; } /** * Load the properties collection by parsing the input string. * \param text Properties as text * \return Reference to this object */ Properties& Properties::load(const std::string& text) { std::stringstream ss(text); std::string s; while (std::getline(ss, s)) { std::string line = trim_copy(s); // skip blank lines and comments if (line.empty()) { continue; } if (line.at(0) == '!' || line.at(0) == '#') { continue; } std::string key, value; size_t eqx = line.find('='); size_t cox = line.find(':'); size_t ix = (eqx == std::string::npos ? cox : eqx); // is the delimiter an equal sign or a colon? if (eqx != std::string::npos && cox != std::string::npos) ix = std::min(eqx, cox); // extract the key and value key = trim_copy(line.substr(0, ix)); value = trim_copy(line.substr(ix + 1)); // special case: does value terminate with a \? if (value.at(value.length() - 1) == '\\') { std::string tmpValue; while (value.at(value.length() - 1) == '\\') { value = trim_copy(value.substr(0, value.length() - 1)); tmpValue.append(value); if (std::getline(ss, s)) value = trim_copy(s); else value = ""; } tmpValue.append(value); value = tmpValue; } // set the property setProperty(key, value); } return *this; } /** * Load the properties collection from the given input stream. * \param in Input stream * \return Reference to this object */ Properties& Properties::load(std::istream& in) { std::istreambuf_iterator<char> eos; std::string text(std::istreambuf_iterator<char>(in), eos); return load(text); } Properties& Properties::store(std::string& target) { std::stringstream ss; for (auto key : keys()) { ss << key << "=" << getProperty(key) << std::endl; } target = ss.str(); return *this; } Properties& Properties::store(std::ostream& out) { std::string temp; store(temp); out.write(temp.data(), temp.length()); return *this; }
true
d7f8350ae2738cb390e859914b96ff5618f55683
C++
JackDrogon/ProgrammingSamples
/cpp/test/move_test.cc
UTF-8
645
3.6875
4
[]
no_license
#include <iostream> #include <memory> #include <string> using namespace std; struct Type { Type(int pi) : i(pi) { cout << "Ctor " << i << endl; } Type(Type &&t) : i(t.i) { t.i = 0; cout << "Move ctor " << i << endl; } ~Type() { cout << "dctor " << i << endl; } int i; }; // void f(string &&s) { cout << s + "11" << endl; } // int main() { // string s = "hello"; // cout << s << endl; // f(std::move(s)); // cout << s << endl; // return 0; // } // void f(Type &&t) { cout << "t.i " << t.i << endl; } int main() { Type t(10); cout << "t.i " << t.i << endl; f(std::move(t)); cout << "t.i " << t.i << endl; return 0; }
true