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
8d2f6eab94d648a132218154e073744be1a04868
C++
JoaoDanielRufino/Online-Judges
/Uri-Online-Judge/Cpp/2484.cpp
UTF-8
578
2.609375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main(){ ios::sync_with_stdio(false); cin.tie(0); int space,count; string str; while(cin >> str){ count = 0; space = 1; for(int i = 0; i < str.size(); i++){ for(int j = 0; j < str.size()-count; j++){ if(!j) printf("%*c", space,str[j]); else printf(" %c", str[j]); } count++; space++; printf("\n"); } printf("\n"); } return 0; }
true
718ddb3693dd1870c57414bb13123f26450cd368
C++
qvajda/TAP-Sim
/Sim/Learner/SimplifiedLearner.cpp
UTF-8
1,080
2.75
3
[]
no_license
/* * SimplifiedLearner.cpp * * Created on: Sep 25, 2014 */ #include "SimplifiedLearner.h" SimplifiedLearner::SimplifiedLearner(const long n): NetworkLearner(n) { infos = SimpleRoadInfos(nbRoads); } void SimplifiedLearner::exitedRoad(Road* r, const double time, const double length){ infos[r->getId()].addInfo(length); } void SimplifiedLearner::enteredRoad(Road* r, const double time){ //nothing to do } double SimplifiedLearner::getPredTime(Road* r, const double time){ double pred = infos[r->getId()].avgLength; unsigned long long count = (infos[r->getId()]).counter; if(count == 0){ pred = r->getMinTravelTime(); //if no information learned at all ; only use basic heuristic to predict travel time }else if(count < MIN_INFO_THRESHOLD){ pred = (pred + r->getMinTravelTime())/2; //if not enough info learned ; add heuristic to prediction (with 0.5 weight) } return pred; } bool SimplifiedLearner::isFullyLearned(Road* r, const double time){ return (infos[r->getId()]).counter >= INFO_CERTAINTY_THRESHOLD; } SimplifiedLearner::~SimplifiedLearner() { }
true
f0e7672de54810f22251e9d3aa65b608ba0428fc
C++
pixelite1201/TraceMove
/src/GUI/ImageVotes.h
UTF-8
1,559
3.1875
3
[]
no_license
/*! \file ImageVotes.h \brief This file find the maximum votes per image */ #include "Grid.h" #include<vector> class ImageVotes{ public: //! Max location offset difference allowed between drawn patch and database patch int offsetSize; //! imgId for which votes are stored int imgId; //! Store the patch location for drawn image Grid grid; //! This is used to find the maximum displacement of the matching image /*! Since user drawn image may be slightly shifted from the database image, we need to find * this displacement and align the matching image to drawn image. For this, instead of * storing votes for the image, we will divide the votes in different bins where each * bin correspond to displacement of the matching patch and the drawn image patch. The * offset value of the bin with maximum votes is the final displacement of the matching * image. */ vector<vector<int> > offsets; //! maxVotes for the image int maxVotes; //! bin in X direction with maximum votes int maxbinX; //! bin in Y direction with maximum votes int maxbinY; //! Constructor ImageVotes(int imgId,Grid grid); //! Will alter votes in offsets on the basis of value provided by new descriptor. /*! dx and dy are the displacement of the matching patch to user drawn patch in x * and y direction. This will be used to increment the votes in corresponding bin. * and l is the maximum number of sketches of drawn image patch * that matches to database image patch.*/ int alterVotes(int dx,int dy,int l); };
true
aab101a9c986cd471c43d922679d6826d9010725
C++
MOYUtianming/simple-motion-counter
/1.camera & divide/PHOTOTOOLS/spare/mainc.cpp
UTF-8
4,353
3.015625
3
[]
no_license
#include "Windows.h" #include "stdio.h" #include "string.h" #include "malloc.h" unsigned char *pBmpBuf;//读入图像数据的指针 int bmpWidth;//图像的宽 int bmpHeight;//图像的高 RGBQUAD *pColorTable;//颜色表指针 int biBitCount;//图像类型,每像素位数 bool readBmp(char *bmpName) { //二进制读方式打开指定的图像文件 FILE *fp=fopen(bmpName,"rb"); if(fp==0) return 0; //跳过位图文件头结构BITMAPFILEHEADER fseek(fp, sizeof(BITMAPFILEHEADER),0); //定义位图信息头结构变量,读取位图信息头进内存,存放在变量head中 BITMAPINFOHEADER head; fread(&head, sizeof(BITMAPINFOHEADER), 1,fp); //获取图像宽、高、每像素所占位数等信息 bmpWidth = head.biWidth; bmpHeight = head.biHeight; biBitCount = head.biBitCount; //定义变量,计算图像每行像素所占的字节数(必须是4的倍数) int lineByte=(bmpWidth * biBitCount/8+3)/4*4; //灰度图像有颜色表,且颜色表表项为256 if(biBitCount==8){ //申请颜色表所需要的空间,读颜色表进内存 pColorTable=new RGBQUAD[256]; fread(pColorTable,sizeof(RGBQUAD),256,fp); } //申请位图数据所需要的空间,读位图数据进内存 pBmpBuf=new unsigned char[lineByte * bmpHeight]; fread(pBmpBuf,1,lineByte * bmpHeight,fp); printf("lineByte: %d\n,bmpHeight: %d\n",lineByte,bmpHeight); //关闭文件 fclose(fp); return 1; } bool saveBmp(char *bmpName, unsigned char *imgBuf, int width, int height, int biBitCount, RGBQUAD *pColorTable) { //如果位图数据指针为0,则没有数据传入,函数返回 if(!imgBuf) return 0; //颜色表大小,以字节为单位,灰度图像颜色表为1024字节,彩色图像颜色表大小为0 int colorTablesize=0; if(biBitCount==8) colorTablesize=1024; //待存储图像数据每行字节数为4的倍数 int lineByte=(width * biBitCount/8+3)/4*4; //以二进制写的方式打开文件 FILE *fp=fopen(bmpName,"wb"); if(fp==0) return 0; //申请位图文件头结构变量,填写文件头信息 BITMAPFILEHEADER fileHead; fileHead.bfType = 0x4D42;//bmp类型 //bfSize是图像文件4个组成部分之和 fileHead.bfSize= sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + colorTablesize + lineByte*height; fileHead.bfReserved1 = 0; fileHead.bfReserved2 = 0; //bfOffBits是图像文件前3个部分所需空间之和 fileHead.bfOffBits=54+colorTablesize; //写文件头进文件 fwrite(&fileHead, sizeof(BITMAPFILEHEADER),1, fp); //申请位图信息头结构变量,填写信息头信息 BITMAPINFOHEADER head; head.biBitCount=biBitCount; head.biClrImportant=0; head.biClrUsed=0; head.biCompression=0; head.biHeight=height; head.biPlanes=1; head.biSize=40; head.biSizeImage=lineByte*height; head.biWidth=width; head.biXPelsPerMeter=0; head.biYPelsPerMeter=0; //写位图信息头进内存 fwrite(&head, sizeof(BITMAPINFOHEADER),1, fp); //如果灰度图像,有颜色表,写入文件 if(biBitCount==8) fwrite(pColorTable, sizeof(RGBQUAD),256, fp); //写位图数据进文件 fwrite(imgBuf, height*lineByte, 1, fp); //关闭文件 fclose(fp); return 1; } int mainc() { char inFileName[90]="PHOTO/TWN.bmp",outFileName[90]="ttt.bmp"; /* char inFileName[90],outFileName[90]; printf("请输入原始位图文件的文件名:"); scanf("%s",inFileName); printf("请输入加密程序产生的新位图文件的文件名:"); scanf("%s",outFileName); */ //读入指定BMP文件进内存 readBmp(inFileName); //输出图像的信息 printf("width=%d,height=%d, biBitCount=%d\n",bmpWidth,bmpHeight, biBitCount); printf("sizeof DWORD: %d\n",sizeof(DWORD)); printf("sizeof LONG : %d\n",sizeof(LONG) ); printf("sizeof WORD : %d\n",sizeof(WORD) ); //将图像数据存盘 saveBmp(outFileName, pBmpBuf, bmpWidth, bmpHeight, biBitCount, pColorTable); //清除缓冲区,pBmpBuf和pColorTable是全局变量,在文件读入时申请的空间 delete []pBmpBuf; if(biBitCount==8) delete []pColorTable; }
true
9a5fe72c5709fa5735d65aca81e1e163fff482a5
C++
Avantika2799/30DayAprilLeetCodeChallenge
/Week of April 22-28/LRUCache.cpp
UTF-8
1,295
3
3
[]
no_license
/* https://leetcode.com/explore/featured/card/30-day-leetcoding-challenge/531/week-4/3309/ */ class LRUCache { int _capacity; list<int>Keys; unordered_map<int,pair<int,list<int>::iterator>>m; public: LRUCache(int capacity): _capacity(capacity) { } int get(int key) { if(m.find(key)!=m.end()) { //removing from last position and putting in first position Keys.erase(m[key].second); Keys.push_front(key); m[key].second=Keys.begin(); return m[key].first; } return -1; } void put(int key, int value) { //updating the value for the same key if(m.find(key)!=m.end()) { Keys.erase(m[key].second); Keys.push_front(key); m[key]={value,Keys.begin()}; }//new key -have to check capacity else{ if(Keys.size()==_capacity) { m.erase(Keys.back()); Keys.pop_back(); } Keys.push_front(key); m[key]={value,Keys.begin()}; } } }; /** * Your LRUCache object will be instantiated and called as such: * LRUCache* obj = new LRUCache(capacity); * int param_1 = obj->get(key); * obj->put(key,value); */
true
b15e15d7bc547b2d5d48335d254566021cd34f73
C++
Mrpye/boatbot
/boatbot.ino
UTF-8
2,610
3.109375
3
[]
no_license
/* * Ultrasonic Sensor HC-SR04 and Arduino Tutorial * * Crated by Dejan Nedelkovski, * www.HowToMechatronics.com * */ #include <Servo.h> // defines pins numbers const int right_trigPin = 2; const int right_echoPin = 3; const int left_trigPin = 4; const int left_echoPin = 5; // defines variables int left_distance[3]; int right_distance[3]; int left_avg_distance; int right_avg_distance; int pos = 0; Servo myservo; // create servo object to control a servo void setup() { pinMode(left_trigPin, OUTPUT); // Sets the trigPin as an Output pinMode(left_echoPin, INPUT); // Sets the echoPin as an Input pinMode(right_trigPin, OUTPUT); // Sets the trigPin as an Output pinMode(right_echoPin, INPUT); // Sets the echoPin as an Input myservo.attach(6); // attaches the servo on pin 9 to the servo object myservo.write(90); // tell servo to go to position in variable 'pos' delay(15); Serial.begin(9600); // Starts the serial communication } int getDistance(int trigPin,int echoPin){ int distance; long duration; // Clears the trigPin digitalWrite(trigPin, LOW); delayMicroseconds(2); // Sets the trigPin on HIGH state for 10 micro seconds digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); // Reads the echoPin, returns the sound wave travel time in microseconds duration = pulseIn(echoPin, HIGH); // Calculating the distance distance= duration*0.034/2; return distance; } void loop() { int mode=0; int walldist=5; int straight_at=4; int dist_constraint=50; int turn_intensity=10; if(mode==0){ //this make go straight down middle left_distance[0]=getDistance(left_trigPin,left_echoPin); right_distance[0]=getDistance(right_trigPin,right_echoPin); left_distance[1]=getDistance(left_trigPin,left_echoPin); right_distance[1]=getDistance(right_trigPin,right_echoPin); left_distance[2]=getDistance(left_trigPin,left_echoPin); right_distance[2]=getDistance(right_trigPin,right_echoPin); left_avg_distance=(left_distance[0]+left_distance[1]+left_distance[2])/2; right_avg_distance=(right_distance[0]+right_distance[1]+right_distance[2])/2; long n=(constrain(left_avg_distance,0,dist_constraint)-constrain(right_avg_distance,0,dist_constraint)); int walldist=10; //n=constrain(n,-40,40); if(n>=(-straight_at)&&n<=straight_at){ myservo.write(90); }else{ int val = map(-1*n, -(dist_constraint+turn_intensity), (dist_constraint+turn_intensity), 0, 200); myservo.write(val); } }else if(mode=1){ } delay(10); }
true
922bd9b2841522bbbbbdd51b9d4f63efe711eddc
C++
wolf2lyon/Clases_progra2_2021
/Semana 6 II/Controladora.cpp
UTF-8
2,915
2.75
3
[]
no_license
#include <iostream> #include <conio.h> #include "Controladora.h" using namespace System; using namespace System::Drawing; using namespace std; Controladora::Controladora() {} Controladora::~Controladora() { delete obj_monigote; delete obj_vehiculos; } void Controladora::Iniciar(int MAXW, int MAXH) { obj_monigote = new Monigote(); obj_vehiculos = new ArrBase_Movimiento(); ymeta = 1; termino = gano = false; frecuencia = 0; cantvidas = 3; obj_monigote->Cambiar_x(MAXW / 2); obj_monigote->Cambiar_y(MAXH - obj_monigote->Retornar_a()); } void Controladora::Run(int MAXW, int MAXH) { while (cantvidas > 0) { frecuencia++; if (frecuencia == 10) { Crear_Vehiculo(MAXW, MAXH); frecuencia = 0; } obj_vehiculos->Mover_todos(MAXW, MAXH); if (_kbhit()) { char t = getch(); if (toupper(t) == 'W') obj_monigote->Cambiar_direccion(movimiento::arriba); if (toupper(t) == 'S') obj_monigote->Cambiar_direccion(movimiento::abajo); if (toupper(t) == 'A') obj_monigote->Cambiar_direccion(movimiento::izquierda); if (toupper(t) == 'D') obj_monigote->Cambiar_direccion(movimiento::derecha); } obj_monigote->Mover(MAXW, MAXH); _sleep(50); for (int i = 0; !termino && i < obj_vehiculos->Retonar_n_elementos(); i++) termino = Colision(obj_monigote, obj_vehiculos->Retornar_elemento_enpos(i)); if (obj_monigote->Retornar_y() == ymeta) { termino = gano = true; cantvidas = 0; } if (termino) { cantvidas--; obj_monigote->Cambiar_x(MAXW / 2); obj_monigote->Cambiar_y(MAXH - obj_monigote->Retornar_a()); termino = false; } } Resumen(); } bool Controladora::Colision(Base_Movimiento* obj1, Base_Movimiento* obj2) { Rectangle rectangulo1; rectangulo1.X = obj1->Retornar_x(); rectangulo1.Y = obj1->Retornar_y(); rectangulo1.Height = obj1->Retornar_a(); rectangulo1.Width = obj1->Retornar_l(); Rectangle rectangulo2; rectangulo2.X = obj2->Retornar_x(); rectangulo2.Y = obj2->Retornar_y(); rectangulo2.Height = obj2->Retornar_a(); rectangulo2.Width = obj2->Retornar_l(); return rectangulo1.IntersectsWith(rectangulo2); } void Controladora::Crear_Vehiculo(int MAXW, int MAXH) { if ((rand() % 100) % 2 == 0) { obj_vehiculos->Insertar(new Auto()); obj_vehiculos->Cambiar_x(obj_vehiculos->Retonar_n_elementos() - 1, 1); obj_vehiculos->Cambiar_y(obj_vehiculos->Retonar_n_elementos() - 1, 1 + rand() % (MAXH - 10)); obj_vehiculos->Cambiar_dx(obj_vehiculos->Retonar_n_elementos() - 1, 1 + rand() % 3); } else { obj_vehiculos->Insertar(new Moto()); obj_vehiculos->Cambiar_x(obj_vehiculos->Retonar_n_elementos() - 1, MAXW - 7); obj_vehiculos->Cambiar_y(obj_vehiculos->Retonar_n_elementos() - 1, 1 + rand() % (MAXH - 10)); obj_vehiculos->Cambiar_dx(obj_vehiculos->Retonar_n_elementos() - 1, (1 + rand() % 3) * -1); } } void Controladora::Resumen() { if (gano) { cout << "LLEGO A LA META"; } else cout << "PERDIO"; }
true
fcc97d9e5b0348a137fdfde01f51217443cbe4c1
C++
Huijuan2015/MyLeetcodeSolutions
/cpp/370. Range Addition.cpp
UTF-8
576
2.796875
3
[]
no_license
class Solution { public: vector<int> getModifiedArray(int length, vector<vector<int>>& updates) { //只更新start end+1 index vector<int> calculateHelper(length, 0); vector<int> res(length, 0); for(auto update : updates){ calculateHelper[update[0]] += update[2]; if(update[1]+1 < length) calculateHelper[update[1]+1] -= update[2]; } int sum = 0; for(int i = 0; i < length; ++i){ sum += calculateHelper[i]; res[i] = sum; } return res; } };
true
f1351020954f02ec1b63f21378e6ab9e1fc87dd8
C++
HealthVivo/mumdex
/unstable/gene_info.cpp
UTF-8
2,778
2.65625
3
[]
no_license
// // gene_info.cpp // // Output gene information // // Copyright 2020 Peter Andrews @ CSHL // #include <algorithm> #include <exception> #include <iostream> #include <sstream> #include <string> #include <utility> #include <vector> #include "error.h" #include "genes.h" #include "mumdex.h" using std::cout; using std::cerr; using std::endl; using std::exception; using std::ostringstream; using std::pair; using std::string; using std::vector; using paa::ChromosomeIndexLookup; using paa::Error; using paa::GeneLookup; using paa::GeneXrefs; using paa::KnownGene; using paa::KnownGenes; using paa::Reference; int main(int argc, char * argv[]) try { // Check initial command line arguments const string usage{"usage: gene_info reference gene ..."}; if (--argc < 2) throw Error(usage); const string reference_file{argv[1]}; const Reference reference{reference_file}; const ChromosomeIndexLookup chr_lookup{reference}; const KnownGenes genes{chr_lookup, reference}; const GeneXrefs xref{reference}; const GeneLookup gene_lookup{genes, xref}; --argc; argv += 2; // Process all gene names for (int a{0}; a != argc; ++a) { const string gene{argv[a]}; if (a) cout << "\n"; cout << "Gene " << gene << "\n"; vector<pair<double, string>> ordered; const GeneLookup::ER isoforms{gene_lookup.isoforms(gene)}; for (GeneLookup::Iter isoform_iter{isoforms.first}; isoform_iter != isoforms.second; ++isoform_iter) { ostringstream out; const KnownGene & isoform{*isoform_iter->second}; uint64_t total_exon_length{0}; for (uint64_t exon{0}; exon != isoform.n_exons; ++exon) total_exon_length += isoform.exon_stops[exon] - isoform.exon_starts[exon]; out << isoform.name << ' ' << isoform.chr_name << ' ' << isoform.t_start + 1 << ' ' << isoform.t_stop + 1 << ' ' << isoform.c_start + 1 << ' ' << isoform.c_stop + 1 << ' ' << isoform.n_exons << ' ' << total_exon_length << "\n"; for (uint64_t exon{0}; exon != isoform.n_exons; ++exon) out << exon << ' ' << isoform.exon_starts[exon] + 1 << ' ' << isoform.exon_stops[exon] + 1 << ' ' << reference.subseq(isoform.chr, isoform.exon_starts[exon], isoform.exon_stops[exon]) << '\n'; ordered.emplace_back(-1.0 * total_exon_length, out.str()); } sort(ordered.begin(), ordered.end()); for (auto info : ordered) cout << info.second; } return 0; } catch (Error & e) { cerr << "paa::Error:" << endl; cerr << e.what() << endl; return 1; } catch (exception & e) { cerr << "std::exception" << endl; cerr << e.what() << endl; return 1; } catch (...) { cerr << "unknown exception was caught" << endl; return 1; }
true
25de161276663ea06d11712d222a4c8f43fa201e
C++
ericng349/Database-Project
/DataBase/main.cpp
UTF-8
420
2.59375
3
[]
no_license
/* * Author: Eric Ng * Project: Final Project - Database * Purpose: Creates a SQL database that allows users to input records, find * records, and make tables * Notes: * * //NOTE: */ #include "sql.h" #include <iostream> using namespace std; //Make it check for fields int main(int argc, char *argv[]) { SQL sql; //Creates a sql program sql.run(); //Run the sql return 0; }
true
1dd434439b5e5c18de564433b47e630dcfe68b1c
C++
rc1/WhereDidTheSelfiesTakeUs
/SelfiesOSX/src/OnionSkinRingBuffer.cpp
UTF-8
2,113
2.671875
3
[]
no_license
#include "OnionSkinRingBuffer.h" #pragma mark - Settings OnionSkinRingBufferSettings::OnionSkinRingBufferSettings () { numberFrames = 1; width = 800; height = 480; blendMode = OF_BLENDMODE_ALPHA; show = 4; } #pragma mark - Lifecycle OnionSkinRingBuffer::OnionSkinRingBuffer () { } OnionSkinRingBuffer::~OnionSkinRingBuffer () { } #pragma mark - Config void OnionSkinRingBuffer::init ( OnionSkinRingBufferSettings settings ) { this->settings = settings; layer.allocate( settings.width, settings.height, GL_RGBA ); ofLogNotice() << "Allocated Onionskin Buffer with " << ofToString( settings.width ) << "x" << ofToString( settings.height ) << "px"; // Create the Fbos with the same for ( int i=0; i < settings.numberFrames; ++i ) { OnionSkinFboPtr framePtr( new ofFbo() ); framePtr->allocate( settings.width, settings.height, GL_RGBA ); fbos.push_back( framePtr ); } currentFboIdx = 0; } #pragma mark - Frames void OnionSkinRingBuffer::next () { currentFboIdx++; if ( currentFboIdx >= settings.numberFrames ) { currentFboIdx = 0; } } OnionSkinFboPtr OnionSkinRingBuffer::getCurrentFboPtr () { return fbos[ currentFboIdx ]; } void OnionSkinRingBuffer::renderAll () { static bool hasRun = false; if ( !hasRun ) { for ( int i=0; i < settings.numberFrames; ++i ) { fbos[ i ]->begin(); ofClear( 0, 0, 0, 0 ); fbos[ i ]->end(); } hasRun = true; } layer.begin(); ofClear( 0, 0, 0, 0 ); for ( int i=0; i < settings.show; ++i ) { ofPushStyle(); int alpha = (int) ofMap( i, 0, settings.show, 200, 20 ); ofSetColor( 255, 255, 255, alpha ); int frameIdx = currentFboIdx - i; if ( frameIdx < 0 ) { frameIdx += settings.numberFrames; } ofEnableBlendMode( settings.blendMode ); fbos[ frameIdx ]->draw( 0, 0, settings.width, settings.height ); ofEnableBlendMode( OF_BLENDMODE_ALPHA ); ofPopStyle(); } layer.end(); }
true
cb38475aee5c7ccb0280a1030d83bca0b26e36c9
C++
emfkdlqjspdla/SGA47
/TimeAttack/20140514/Utility.hpp
UTF-8
447
2.921875
3
[]
no_license
#pragma once #define _USE_MATH_DEFINES #include <math.h> template<typename T> class singleton { protected : singleton(){} virtual ~singleton(){} public : static T& getReference() { static T inst; return inst; } }; template<typename T> void SafeDelete(T& pointer) { if (pointer) { delete pointer; pointer = NULL; } } // pi(radian) : 180(degree) = x(radian) : 1(degree) // 180 * x = pi // x = pi/180 #define D2R (M_PI/180.)
true
aa3feb42f0b862fa00ce34118cd93822e4d5091b
C++
pedro-maschio/AlgorithmseDS
/Sorting/mergewithqueue.cpp
UTF-8
1,201
2.875
3
[]
no_license
#include <bits/stdc++.h> #define ll long long #define N (ll)(2*1e5) #define EPS (double)(1e-12) #define M (ll)(1e9+7) using namespace std; void merge(vector<int>& arr, int l, int middle, int r) { queue<int> L, R; for(int i = l; i <= middle; i++) L.push(arr[i]); for(int i = middle+1; i <= r; i++) R.push(arr[i]); int i = l; while(!(L.empty() || R.empty())) { if(L.front() <= R.front()) arr[i++] = L.front(), L.pop(); else arr[i++] = R.front(), R.pop(); } while(!L.empty()) arr[i++] = L.front(), L.pop(); while(!R.empty()) arr[i++] = R.front(), R.pop(); } void mergeSort(vector<int>& arr, int l, int r) { int middle; if(l < r) { middle = (l+r)/2; mergeSort(arr, l, middle); mergeSort(arr, middle+1, r); merge(arr, l, middle, r); } } int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; vector<int> arr(n); for(int i = 0; i < n; i++) cin >> arr[i]; mergeSort(arr, 0, n-1); for(int i = 0; i < n; i++) cout << arr[i] << " "; return 0; }
true
d4937d6c6146e88e13d2fbfe9f7cfdffe5b58438
C++
danielteel/gpdslCPP
/helpers.cpp
UTF-8
3,788
3.25
3
[]
no_license
#include "helpers.h" #include <string> #include <cmath> bool isSpace(int chr) { if (chr <= 32) { return true; } return false; /*switch (chr) { case ' ': case '\t': case '\n': case '\v': case '\f': case '\r': return true; } return false;*/ } bool isDigit(int chr) { switch (chr) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return true; } return false; } bool isAlpha(int chr) { if ((chr >= 'a' && chr <= 'z') || (chr >= 'A' && chr <= 'Z')) { return true; } return false; } bool isAlNum(int chr) { return (isAlpha(chr) || isDigit(chr)); } bool compare_float(double x, double y, double epsilon) { if (fabs(x - y) < epsilon) return true; //they are same return false; //they are not same } std::string& ltrim(std::string& s, const char* t) { s.erase(0, s.find_first_not_of(t)); return s; } std::string& rtrim(std::string& s, const char* t) { s.erase(s.find_last_not_of(t) + 1); return s; } std::string& trim(std::string& s, const char* t) { return ltrim(rtrim(s, t), t); } std::string stringToLowerCopy(std::string str) { std::string retStr; for (auto & chr : str) { retStr += tolower(chr); } return retStr; } void stringToLower(std::string& str) { for (size_t i = 0; i < str.length();i++) { str[i] = tolower(str[i]); } } std::string doubleToString(double value, int decimalPlaces) { char buffer[64]; snprintf(buffer, sizeof(buffer), "%.*f", decimalPlaces, value); return std::string(buffer); } std::string trimmedDoubleToString(double value, int mostDecimalPlaces) { std::string doubleString = doubleToString(value, mostDecimalPlaces); int length = doubleString.length(); size_t index = doubleString.find_last_of("."); if (index != std::string::npos && length > 2) { for (size_t i = doubleString.length(); i > 0; i--) { if (doubleString[i - 1] == '0') { length--; } else { if (doubleString[i - 1] == '.') { length--; } break; } } } return doubleString.substr(0,length); } std::string trimmedDoubleToString(double value) { std::string doubleString = std::to_string(value); int length = doubleString.length(); size_t index = doubleString.find_last_of("."); if (index != std::string::npos && length > 2) { for (size_t i = doubleString.length(); i > 0; i--) { if (doubleString[i - 1] == '0') { length--; } else { if (doubleString[i - 1] == '.') { length--; } break; } } } return doubleString.substr(0, length); } std::string encodeString(std::string str) { std::string encoded; for (size_t i = 0; i < str.size(); i++) { switch (str[i]) { case 0: encoded += "%0"; case '\'': encoded += "%p"; break; case '"': encoded += "%q"; break; case '%': encoded += "%%"; break; case '\\': encoded += "%s"; break; case '\r': encoded += "%r"; break; case '\n': encoded += "%n"; break; default: encoded += str[i]; break; } } return encoded; } std::string decodeString(std::string str) { std::string decoded; for (size_t i = 0; i < str.size(); i++) { if (str[i] == '%') { i++; if (i < str.size()) { switch (str[i]) { case '0': decoded += '\0'; break; case 'p': decoded += '\''; break; case 'q': decoded += '"'; break; case '%': decoded += '%'; break; case 's': decoded += '\\'; break; case 'r': decoded += '\r'; break; case 'n': decoded += '\n'; break; } } } else { decoded += str[i]; } } return decoded; } std::string stripTrailingNumber(std::string str) { trim(str); int i; for (i = int(str.length()) - 1; i >= 0; i--) { if (!isDigit(str[i])) { break; } } return str.substr(0, i + 1); }
true
838e959ec2600559e2d7f29c2420cb11fb59ebbe
C++
mirabellej/WhenThingsSpeak
/1_PlayNote.ino
UTF-8
769
3.03125
3
[]
no_license
#include <Adafruit_CircuitPlayground.h> // Include the library for the Circuit Playrgound. void setup() { CircuitPlayground.begin(); // This initializes the Circuit Playground. delay(1000); // Warm up delay. Pause for 1 second. CircuitPlayground.playTone(500, 100); // This plays tone 500 for 100 milliseconds. delay(1000); // Silence for one second. // This is a comment. Because it begins with "//" the code will not run. // Try deleting the "//" in the statements below on line 13 and 14 to run the code. // CircuitPlayground.playTone(800, 100); // This plays tone 500 for 100 milliseconds. // delay(1000); // Silence for one second. } void loop() { // This is the loop. If you put code here, it will run over and over again. }
true
c469de2e855bf588750b3d96a84ed5ff30e79936
C++
kscharlund/kattis
/allpairspath/allpairspath.cpp
UTF-8
1,869
2.984375
3
[]
no_license
#include <iostream> #include <vector> using namespace std; static const int INF = 10000000; int main() { cin.sync_with_stdio(false); cin.tie(NULL); while (true) { int n, m, q; cin >> n >> m >> q; if (!(n || m || q)) { break; } // Read graph. vector<int> dist(n*n, INF); for (int i = 0; i < n; ++i) { dist[i*n + i] = 0; } for (int i = 0; i < m; ++i) { int u, v, w; cin >> u >> v >> w; // min because there may be several edges between u and v. dist[u*n + v] = min(dist[u*n + v], w); } // Floyd-Warshall all pairs shortest path. for (int k = 0; k < n; ++k) { for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (dist[i*n + k] < INF && dist[k*n + j] < INF) { dist[i*n + j] = min(dist[i*n + j], dist[i*n + k] + dist[k*n + j]); } } } } // Propagate negative cycles. for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { for (int k = 0; dist[i*n + j] != -INF && k < n; ++k) { if (dist[i*n + k] < INF && dist[k*n + j] < INF && dist[k*n + k] < 0) { dist[i*n + j] = -INF; } } } } // Process queries. for (int i = 0; i < q; ++i) { int u, v; cin >> u >> v; if (dist[u*n + v] == -INF) { cout << "-Infinity\n"; } else if (dist[u*n + v] == INF) { cout << "Impossible\n"; } else { cout << dist[u*n + v] << "\n"; } } cout << "\n"; } return 0; }
true
bb3e9a046bf2a16c6561d156ba71add8e2f1908f
C++
bino7/chromium
/base/callback.h
UTF-8
2,496
2.53125
3
[ "BSD-3-Clause" ]
permissive
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef BASE_CALLBACK_H_ #define BASE_CALLBACK_H_ #include "base/callback_forward.h" #include "base/callback_internal.h" // NOTE: Header files that do not require the full definition of Callback or // Closure should #include "base/callback_forward.h" instead of this file. // ----------------------------------------------------------------------------- // Usage documentation // ----------------------------------------------------------------------------- // // See //docs/callback.md for documentation. namespace base { template <typename R, typename... Args, internal::CopyMode copy_mode> class Callback<R(Args...), copy_mode> : public internal::CallbackBase<copy_mode> { private: using PolymorphicInvoke = R (*)(internal::BindStateBase*, Args&&...); public: // MSVC 2013 doesn't support Type Alias of function types. // Revisit this after we update it to newer version. typedef R RunType(Args...); Callback() : internal::CallbackBase<copy_mode>(nullptr) {} Callback(internal::BindStateBase* bind_state, PolymorphicInvoke invoke_func) : internal::CallbackBase<copy_mode>(bind_state) { using InvokeFuncStorage = typename internal::CallbackBase<copy_mode>::InvokeFuncStorage; this->polymorphic_invoke_ = reinterpret_cast<InvokeFuncStorage>(invoke_func); } bool Equals(const Callback& other) const { return this->EqualsInternal(other); } // Run() makes an extra copy compared to directly calling the bound function // if an argument is passed-by-value and is copyable-but-not-movable: // i.e. below copies CopyableNonMovableType twice. // void F(CopyableNonMovableType) {} // Bind(&F).Run(CopyableNonMovableType()); // // We can not fully apply Perfect Forwarding idiom to the callchain from // Callback::Run() to the target function. Perfect Forwarding requires // knowing how the caller will pass the arguments. However, the signature of // InvokerType::Run() needs to be fixed in the callback constructor, so Run() // cannot template its arguments based on how it's called. R Run(Args... args) const { PolymorphicInvoke f = reinterpret_cast<PolymorphicInvoke>(this->polymorphic_invoke_); return f(this->bind_state_.get(), std::forward<Args>(args)...); } }; } // namespace base #endif // BASE_CALLBACK_H_
true
3205ce948bcdfbaf3bacd3413b51a9a4902468b0
C++
ashih42/Nibbler
/srcs/SDLModule.cpp
UTF-8
7,365
2.734375
3
[]
no_license
#include "SDLModule.hpp" #include "ResourceManager.hpp" #include "NibblerException.hpp" # define CELL_WIDTH 24 extern "C" { IModule * createSDLModule(int boardWidth, int boardHeight, std::string title) { return (new SDLModule(boardWidth, boardHeight, title)); } } SDLModule::SDLModule(int boardWidth, int boardHeight, std::string title) : _boardWidth(boardWidth), _boardHeight(boardHeight), _isGridShown(false) { if (SDL_Init(SDL_INIT_EVERYTHING)) throw NibblerException("SDL_Init() failed"); if (!(this->_window = SDL_CreateWindow(title.c_str(), 0, 0, this->_boardWidth * CELL_WIDTH, this->_boardHeight * CELL_WIDTH, SDL_WINDOW_SHOWN))) throw NibblerException("SDL_CreateWindow() failed"); this->_context = SDL_GL_CreateContext(this->_window); if (!(this->_renderer = SDL_CreateRenderer(this->_window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC))) throw NibblerException("SDL_CreateRenderer() failed"); if ((IMG_Init(IMG_FLAGS) & IMG_FLAGS) != IMG_FLAGS) throw NibblerException("IMG_Init() failed"); this->_snakeHeadP1Texture = this->_initTexture(SNAKE_HEAD_P1_IMAGE); this->_snakeBodyP1Texture = this->_initTexture(SNAKE_BODY_P1_IMAGE); this->_snakeHeadP2Texture = this->_initTexture(SNAKE_HEAD_P2_IMAGE); this->_snakeBodyP2Texture = this->_initTexture(SNAKE_BODY_P2_IMAGE); this->_snakeDeadTexture = this->_initTexture(SNAKE_DEAD_IMAGE); this->_foodTextures.push_back(this->_initTexture(FOOD_IMAGE_0)); this->_foodTextures.push_back(this->_initTexture(FOOD_IMAGE_1)); this->_foodTextures.push_back(this->_initTexture(FOOD_IMAGE_2)); this->_foodTextures.push_back(this->_initTexture(FOOD_IMAGE_3)); this->_foodTextures.push_back(this->_initTexture(FOOD_IMAGE_4)); this->_enemyTextures.push_back(this->_initTexture(ENEMY_IMAGE_0)); this->_enemyTextures.push_back(this->_initTexture(ENEMY_IMAGE_1)); this->_enemyTextures.push_back(this->_initTexture(ENEMY_IMAGE_2)); this->_enemyTextures.push_back(this->_initTexture(ENEMY_IMAGE_3)); this->_enemyTextures.push_back(this->_initTexture(ENEMY_IMAGE_4)); this->_enemyTextures.push_back(this->_initTexture(ENEMY_IMAGE_5)); this->_enemyTextures.push_back(this->_initTexture(ENEMY_IMAGE_6)); this->_enemyTextures.push_back(this->_initTexture(ENEMY_IMAGE_7)); } SDL_Texture * SDLModule::_initTexture(std::string filename) { SDL_Texture * texture = IMG_LoadTexture(this->_renderer, ResourceManager::getInstance().getBasePath(filename).c_str()); if (!texture) throw NibblerException("IMG_LoadTexture() failed on \'" + filename + "\'"); return (texture); } SDLModule::~SDLModule(void) { SDL_DestroyRenderer(this->_renderer); SDL_DestroyWindow(this->_window); SDL_GL_DeleteContext(this->_context); SDL_DestroyTexture(this->_snakeHeadP1Texture); SDL_DestroyTexture(this->_snakeBodyP1Texture); SDL_DestroyTexture(this->_snakeHeadP2Texture); SDL_DestroyTexture(this->_snakeBodyP2Texture); SDL_DestroyTexture(this->_snakeDeadTexture); for (SDL_Texture * texture : this->_foodTextures) SDL_DestroyTexture(texture); for (SDL_Texture * texture : this->_enemyTextures) SDL_DestroyTexture(texture); IMG_Quit(); SDL_Quit(); } void SDLModule::disable(void) { SDL_HideWindow(this->_window); } void SDLModule::enable(void) { SDL_GL_MakeCurrent(this->_window, this->_context); SDL_ShowWindow(this->_window); } std::vector<e_event> SDLModule::getEvents(void) { std::vector<e_event> myEvents; SDL_Event event; while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) myEvents.push_back(EVENT_TERMINATE); else if (event.type == SDL_KEYDOWN && event.key.repeat == 0) this->_handleKeyPressEvent(myEvents, event); } return (myEvents); } void SDLModule::_handleKeyPressEvent(std::vector<e_event> & myEvents, SDL_Event & event) { switch (event.key.keysym.sym) { // Gameplay Controls case SDLK_ESCAPE: myEvents.push_back(EVENT_TERMINATE); break; case SDLK_LEFT: myEvents.push_back(EVENT_P1_TURN_LEFT); break; case SDLK_RIGHT: myEvents.push_back(EVENT_P1_TURN_RIGHT); break; case SDLK_KP_4: myEvents.push_back(EVENT_P2_TURN_LEFT); break; case SDLK_KP_6: myEvents.push_back(EVENT_P2_TURN_RIGHT); break; case SDLK_r: myEvents.push_back(EVENT_START_NEW_ROUND); break; // Graphics Controls case SDLK_1: myEvents.push_back(EVENT_SELECT_MODULE_1); break; case SDLK_2: myEvents.push_back(EVENT_SELECT_MODULE_2); break; case SDLK_3: myEvents.push_back(EVENT_SELECT_MODULE_3); break; case SDLK_g: this->_toggleGrid(); break; default: break; } } void SDLModule::_toggleGrid(void) { this->_isGridShown = !this->_isGridShown; } void SDLModule::_drawGrid(void) { SDL_SetRenderDrawColor(this->_renderer, 255, 255, 255, 0); // draw vertical lines int verticalLength = this->_boardHeight * CELL_WIDTH; for (int x = 0; x < this->_boardWidth; x++) { int xPosition = x * CELL_WIDTH; SDL_RenderDrawLine(this->_renderer, xPosition, 0, xPosition, verticalLength); } // draw horizontal lines int horizontalLength = this->_boardWidth * CELL_WIDTH; for (int y = 0; y < this->_boardHeight; y++) { int yPosition = y * CELL_WIDTH; SDL_RenderDrawLine(this->_renderer, 0, yPosition, horizontalLength, yPosition); } } void SDLModule::render(std::vector<t_cell_data> cellData) { SDL_SetRenderDrawColor(this->_renderer, 0, 0, 0, 0); SDL_RenderClear(this->_renderer); if (this->_isGridShown) this->_drawGrid(); for (t_cell_data & data : cellData) this->_renderCell(data); SDL_RenderPresent(this->_renderer); } void SDLModule::_renderCell(t_cell_data & cellData) { SDL_Rect dstRect; dstRect.x = cellData.posX * CELL_WIDTH; dstRect.y = cellData.posY * CELL_WIDTH; dstRect.w = CELL_WIDTH; dstRect.h = CELL_WIDTH; switch (cellData.type) { case CELL_SNAKE: this->_renderSnakeCell(cellData, dstRect); break; case CELL_FOOD: this->_renderFoodCell(cellData, dstRect); break; case CELL_ENEMY: this->_renderEnemyCell(cellData, dstRect); break; default: break; } } void SDLModule::_renderSnakeCell(t_cell_data & cellData, SDL_Rect & dstRect) { SDL_Texture * texture; double angle; switch (cellData.direction) { case NORTH: angle = 0.0; break; case EAST: angle = 90.0; break; case SOUTH: angle = 180.0; break; case WEST: angle = 270.0; break; default: angle = 0.0; break; } // Player dieded if (cellData.isDead && cellData.isHead) { texture = this->_snakeDeadTexture; } // Player 1 else if (cellData.isPlayer0) { if (cellData.isHead) texture = this->_snakeHeadP1Texture; else texture = this->_snakeBodyP1Texture; } // Player 2 else { if (cellData.isHead) texture = this->_snakeHeadP2Texture; else texture = this->_snakeBodyP2Texture; } SDL_RenderCopyEx(this->_renderer, texture, NULL, &dstRect, angle, NULL, SDL_FLIP_NONE); } void SDLModule::_renderFoodCell(t_cell_data & cellData, SDL_Rect & dstRect) { SDL_Texture * texture = this->_foodTextures[cellData.id % this->_foodTextures.size()]; SDL_RenderCopy(this->_renderer, texture, NULL, &dstRect); } void SDLModule::_renderEnemyCell(t_cell_data & cellData, SDL_Rect & dstRect) { SDL_Texture * texture = this->_enemyTextures[cellData.id % this->_enemyTextures.size()]; SDL_RenderCopy(this->_renderer, texture, NULL, &dstRect); }
true
9ee183fe393a84c2638eeb6cd2419577afb6fbfb
C++
gogokigen/Cpp17-DataStructure-and-Algorithm
/Leetcode/Medium/814_binary_tree_pruning.cpp
UTF-8
1,326
3.46875
3
[]
no_license
/******************************************************************* * https://leetcode.com/problems/binary-tree-pruning/ * Medium * * Conception: * 1. * * We are given the head node root of a binary tree, * where additionally every node's value is either a 0 or a 1. * Return the same tree where every subtree (of the given tree) not containing a 1 has been removed. * (Recall that the subtree of a node X is X, plus every node that is a descendant of X.) * * Example: * * Key: * 1. * * References: * 1. * *******************************************************************/ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: TreeNode* pruneTree(TreeNode* root) { return helper(root) ? root:NULL; } bool helper(TreeNode* root){ if(!root) return false; bool l = helper(root->left); bool r = helper(root->right); if(!l) root->left = NULL; if(!r) root->right = NULL; return root->val == 1 || l || r; } };
true
d24c23f01d02133f595137e1e009a5aef6d8dd3b
C++
Befezdow/databases-stuff
/PgC Procedure/cat.h
UTF-8
763
3.21875
3
[]
no_license
#ifndef CAT_H #define CAT_H #include <string> #include <iostream> class Cat { std::string name; std::string breed; unsigned short age; public: Cat(std::string name = "", std::string breed = "", unsigned short age = 0); std::string getName() const; void setName(const std::string &value); std::string getBreed() const; void setBreed(const std::string &value); unsigned short getAge() const; void setAge(unsigned short value); void print(); friend std::ostream &operator << (std::ostream& stream, Cat &data); friend std::istream &operator >> (std::istream& stream, Cat &data); }; std::ostream &operator << (std::ostream& stream, Cat &data); std::istream &operator >> (std::istream& stream, Cat &data); #endif // CAT_H
true
ec98c31a6e6df82b7d2a01d22c7905dbf37baa95
C++
parkeroth/EECS-678-P3
/nachos/threads/thread.h
UTF-8
9,115
2.875
3
[ "MIT-Modern-Variant" ]
permissive
// thread.h // Data structures for managing threads. A thread represents // sequential execution of code within a program. // So the state of a thread includes the program counter, // the processor registers, and the execution stack. // // Note that because we allocate a fixed size stack for each // thread, it is possible to overflow the stack -- for instance, // by recursing to too deep a level. The most common reason // for this occuring is allocating large data structures // on the stack. For instance, this will cause problems: // // void foo() { int buf[1000]; ...} // // Instead, you should allocate all data structures dynamically: // // void foo() { int *buf = new int[1000]; ...} // // // Bad things happen if you overflow the stack, and in the worst // case, the problem may not be caught explicitly. Instead, // the only symptom may be bizarre segmentation faults. (Of course, // other problems can cause seg faults, so that isn't a sure sign // that your thread stacks are too small.) // // One thing to try if you find yourself with seg faults is to // increase the size of thread stack -- ThreadStackSize. // // In this interface, forking a thread takes two steps. // We must first allocate a data structure for it: "t = new Thread". // Only then can we do the fork: "t->fork(f, arg)". // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #ifndef THREAD_H #define THREAD_H #pragma interface "threads/thread.h" #include "copyright.h" #include "utility.h" #include "defs.h" class AddrSpace; #ifdef USER_PROGRAM #include "machine.h" #include "addrspace.h" #include "fdt.h" #include "list.h" #include "synch.h" #include "stats.h" #endif #ifdef USE_PTHREAD #include <pthread.h> #endif // CPU register state to be saved on context switch. // The SPARC and MIPS only need 10 registers, but the Snake needs 18. // The Alpha needs to save 10 64bit registers // For simplicity, this is just the max over all architectures. #define MachineStateSize 20 // Size of the thread's private execution stack. // WATCH OUT IF THIS ISN'T BIG ENOUGH!!!!! #define StackSize (4 * 32768) // in words // Externally available function wrapper whose sole job is to call // Thread class method Print from MapCar when the readylist is being // operated on. extern void ThreadPrint(size_t arg); // The following class defines a "thread control block" -- which // represents a single thread of execution. // // Every thread has: // an execution stack for activation records ("stackTop" and "stack") // space to save CPU registers while not running ("machineState") // a "status" (running/ready/blocked) // // Some threads also belong to a user address space; threads // that only run in the kernel have a NULL address space. class Thread { private: // NOTE: DO NOT CHANGE the order of these first two members. // THEY MUST be in this position for SWITCH to work. unsigned int* stackTop; // the current stack pointer #ifdef HOST_ALPHA u_long machineState[MachineStateSize]; // all registers except for stackTop #else unsigned int machineState[MachineStateSize]; // all registers except for stackTop #endif public: Thread(); // initialize a Thread ~Thread(); // deallocate a Thread // NOTE -- thread being deleted // must not be running when delete // is called // basic thread operations int Fork(VoidFunctionPtr func, size_t arg); // Fork to create another thread void Yield(); // Yield to another thread #ifdef SMARTGDB void ForceYield( Thread * nextThread ); #endif void Sleep(); // Put the thread to sleep and void Sleep (ThreadStatus newstatus); void Finish(); // The thread is done executing void ReachedExit(); // done executing, but may be waiting // on children to finish bool HasReachedExit(); // query thread progress void CheckOverflow(); // Check if thread has // overflowed its stack void setStatus(ThreadStatus st); ThreadStatus getStatus () const; const char* GetName() const { return name; } void SetName (char *threadName) { strncpy (name, threadName, MAXFILENAMELENGTH); *(name + MAXFILENAMELENGTH) = '\0'; } void Print(); // Print the priority information of a thread OR just // the ThreadID depending on the ifdef Flag (F_PRIORITY). int Get_Id(); // Returns the ThreadID // This is the implementation for the new priority driven system int Get_Priority(void); void Prioritize(int p); // This is a class data member that holds the value of the -R // command line parameter. It is used in KU's EECS 678 PA2-2 // project. static double dpRetentionFactor; static bool wssContractionEnabled; #ifdef USER_PROGRAM // -------------------------------- // Child Stuff // -------------------------------- void Queue_Child( Thread * child );// Appends the child to the ChildList Thread* UnQueue_Child(); // Removes the child from the ChildList List ChildList; // List of Children for the currentThread Statistics *procStats; // Object to record performance metrics. Thread* Get_Parent_Ptr(); //Returns the Parent Pointer int Set_Parent_Ptr( Thread * parent ); // Sets the Parent pointer to parent. void Add_Child(); // Increment the Children variable void Remove_Child(); // Decrement the Children variable int Get_Num_Children(); // Returns the value of the variable Children int Children; // variable denoting the number of Children to the currentThread // ------------------------------- // Exit Stuff // ------------------------------- int Get_Exit_Val(); // Returns the value of exitval void Set_Exit_Val( int val ); // Sets the value of exitval to val KernelSemaphore* ChildExited; #endif bool thread_exit_status; // To signal to the parent that the child has finished execution #ifdef USE_PTHREAD pthread_t realThread; pthread_mutex_t schedLock; pthread_cond_t schedCond; bool runNow; #endif // book-keeping for when to reset the working set void resetWssRefreshCounter(); bool incrWssRefreshCounter(); void refreshWss(); private: // NOTE: some of the private data for this class is listed above (for byte-hacking reasons) bool hasReachedExit; // has the thread exhausted its code execution? unsigned int wssRefreshCounter; // how many more quanta before this // thread refreshes its working set // size? // period for refreshing the working set size (units = quanta) static const unsigned int WSS_REFRESH_PERIOD = 10; #ifdef USER_PROGRAM Thread* ParentPtr; int exitval; #endif unsigned int* stack; // Bottom of the stack; NULL if this is the // main thread (if so, don't deallocate stack) ThreadStatus tstatus; // ready, running or blocked char name [MAXFILENAMELENGTH + 1]; int ThreadID; #ifndef USE_PTHREAD void StackAllocate(VoidFunctionPtr func, size_t arg); // Allocate a stack for thread. // Used internally by Fork() #endif /* USE_PTHREAD */ int Priority; // The static priority of a process (thread) #ifdef USER_PROGRAM // A thread running a user program actually has *two* sets of CPU registers -- // one for its state while executing user code, one for its state // while executing kernel code. int userRegisters[NumTotalRegs]; // user-level CPU register state FDTEntry *FDTable [MAX_FD]; // File Descriptor Table entries public: void SaveUserState(); // save user-level register state void RestoreUserState(); // restore user-level register state void Write_Reg(int place, int value) { userRegisters[place] = value; } int Read_Reg(int place) { return userRegisters[place]; } AddrSpace *space; // User code this thread is running. // File descriptor routines int find_next_available_fd (); // finds the next available File descriptor for // the thread void setFD (int fd, FDTEntry *file); // set a file descriptor value FDTEntry *getFD (int fd); // Return's a file descriptor value #endif }; // Magical machine-dependent routines, defined in switch.s extern "C" { // First frame on thread execution stack; // enable interrupts // call "func" // (when func returns, if ever) call ThreadFinish() #ifdef USE_PTHREAD void *ThreadRoot (void *); #else void ThreadRoot(); // After Fork, execution starts from this function // so that returning from function or exiting is simple // and straight forward, otherwise there would be no // function to return to after execution of the function // passed as a parameter to the Fork routine. #endif // Stop running oldThread and start running newThread void SWITCH(Thread *oldThread, Thread *newThread); } #endif // THREAD_H
true
9b8600c91d207c43f900142638c50a70ff0555ea
C++
tomas0716/Square
/EsLib/Bezier4.cpp
UTF-8
2,399
2.53125
3
[]
no_license
#include "stdafx.h" #include "Bezier4.h" IBezier4::IBezier4() : m_ePlayType(ePlay_Stop), m_fTime(0), m_fCurrBezierTime(0), m_nBlockStep(0), m_vCurrPosition(GwVector(0,0,0)) { m_pDelegate_Complete = new IDelegate(); } IBezier4::~IBezier4() { m_PositionList.clear(); m_BlockTimeList.clear(); m_RealBlockTimeList.clear(); m_pDelegate_Complete->Release(); } bool IBezier4::Update(float fDeltaTime) { if( m_ePlayType == ePlay_Play ) { m_fTime += fDeltaTime; m_vCurrPosition = Update_Bezier4( m_PositionList[m_nBlockStep * 3], m_PositionList[m_nBlockStep * 3 + 1], m_PositionList[m_nBlockStep * 3 + 2], m_PositionList[m_nBlockStep * 3 + 3], m_BlockTimeList[m_nBlockStep]); if( m_BlockTimeList[m_nBlockStep] <= m_fTime ) { if( m_nBlockStep < (int)m_BlockTimeList.size() - 1 ) { m_fTime = m_fTime - m_BlockTimeList[m_nBlockStep]; m_nBlockStep += 1; return true; } else { m_ePlayType = ePlay_Complete; (*m_pDelegate_Complete)(); return true; } } } return false; } GwVector IBezier4::GetCurrPos() { return m_vCurrPosition; } void IBezier4::AddPos(GwVector vPos) { m_PositionList.push_back(vPos); } void IBezier4::OnPlay() { if( m_ePlayType == ePlay_Stop || m_ePlayType == ePlay_Complete ) { m_fTime = 0; m_nBlockStep = 0; } m_ePlayType = ePlay_Play; } void IBezier4::OnPause() { if( m_ePlayType == ePlay_Play ) { m_ePlayType = ePlay_Pause; } } void IBezier4::OnStop() { if( m_ePlayType == ePlay_Play || m_ePlayType == ePlay_Pause ) { m_ePlayType = ePlay_Stop; } } void IBezier4::ResetBlockTime() { m_BlockTimeList.clear(); } void IBezier4::SetBlockTime(int Index, float fTime) { if( Index >= (int)m_BlockTimeList.size() ) { m_BlockTimeList.resize(Index+1); } m_BlockTimeList[Index] = fTime; } void IBezier4::SetCallback(IDelegate * pDelegate) { m_pDelegate_Complete->Release(); m_pDelegate_Complete = pDelegate; m_pDelegate_Complete->AddRef(); } GwVector IBezier4::Update_Bezier4(GwVector vFirst, GwVector vSecond, GwVector vThird, GwVector vFourth, float fBlockTime) { float fRatio = m_fTime / fBlockTime; float mum1, mum13, mu3; mum1 = 1 - fRatio; mum13 = mum1 * mum1 * mum1; mu3 = fRatio * fRatio * fRatio; GwVector vCurrPos; vCurrPos = mum13*vFirst + 3*fRatio*mum1*mum1*vSecond + 3*fRatio*fRatio*mum1*vThird + mu3*vFourth; return vCurrPos; }
true
4076cea92b8d30d30f42c77763d8a271a82ff2c5
C++
WWology/336-A2
/src/VertexArray.cpp
UTF-8
864
2.546875
3
[]
no_license
// This is a personal academic project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++, C#, and Java: http://www.viva64.com #include "VertexArray.h" VertexArray::VertexArray() { glGenVertexArrays(1, &m_ArrayID); } VertexArray::~VertexArray() { glDeleteVertexArrays(1, &m_ArrayID); } void VertexArray::Bind() const { glBindVertexArray(m_ArrayID); } void VertexArray::Unbind() const { glBindVertexArray(0); } /** * @brief Add a Vertex Buffer Object * * @param t_Vb The Vertex Buffer Object to be added * @param t_Layout Layout specification for the Vertex Buffer Data */ void VertexArray::addBuffer(const VertexBuffer& t_Vb, const Layout& t_Layout) { Bind(); t_Vb.Bind(); glVertexAttribPointer(t_Layout.index, 3, GL_FLOAT, GL_FALSE, t_Layout.stride, t_Layout.offset); glEnableVertexAttribArray(t_Layout.index); }
true
c1c2b5c22ff617f9adf881d803dd8fe4f7204169
C++
LineageOS/android_frameworks_av
/media/libheadtracking/QuaternionUtil.cpp
UTF-8
3,432
2.84375
3
[ "LicenseRef-scancode-unicode", "Apache-2.0" ]
permissive
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "QuaternionUtil.h" #include <cassert> namespace android { namespace media { using Eigen::NumTraits; using Eigen::Quaternionf; using Eigen::Vector3f; namespace { Vector3f LogSU2(const Quaternionf& q) { // Implementation of the logarithmic map of SU(2) using atan. // This follows Hertzberg et al. "Integrating Generic Sensor Fusion Algorithms // with Sound State Representations through Encapsulation of Manifolds", Eq. // (31) // We use asin and acos instead of atan to enable the use of Eigen Autodiff // with SU2. const float sign_of_w = q.w() < 0.f ? -1.f : 1.f; const float abs_w = sign_of_w * q.w(); const Vector3f v = sign_of_w * q.vec(); const float squared_norm_of_v = v.squaredNorm(); assert(abs(1.f - abs_w * abs_w - squared_norm_of_v) < NumTraits<float>::dummy_precision()); if (squared_norm_of_v > NumTraits<float>::dummy_precision()) { const float norm_of_v = sqrt(squared_norm_of_v); if (abs_w > NumTraits<float>::dummy_precision()) { // asin(x) = acos(x) at x = 1/sqrt(2). if (norm_of_v <= float(M_SQRT1_2)) { return (asin(norm_of_v) / norm_of_v) * v; } return (acos(abs_w) / norm_of_v) * v; } return (M_PI_2 / norm_of_v) * v; } // Taylor expansion at squared_norm_of_v == 0 return (1.f / abs_w - squared_norm_of_v / (3.f * pow(abs_w, 3))) * v; } Quaternionf ExpSU2(const Vector3f& delta) { Quaternionf q_delta; const float theta_squared = delta.squaredNorm(); if (theta_squared > NumTraits<float>::dummy_precision()) { const float theta = sqrt(theta_squared); q_delta.w() = cos(theta); q_delta.vec() = (sin(theta) / theta) * delta; } else { // taylor expansions around theta == 0 q_delta.w() = 1.f - 0.5f * theta_squared; q_delta.vec() = (1.f - 1.f / 6.f * theta_squared) * delta; } return q_delta; } } // namespace Quaternionf rotationVectorToQuaternion(const Vector3f& rotationVector) { // SU(2) is a double cover of SO(3), thus we have to half the tangent vector // delta const Vector3f half_delta = 0.5f * rotationVector; return ExpSU2(half_delta); } Vector3f quaternionToRotationVector(const Quaternionf& quaternion) { // SU(2) is a double cover of SO(3), thus we have to multiply the tangent // vector delta by two return 2.f * LogSU2(quaternion); } Quaternionf rotateX(float angle) { return rotationVectorToQuaternion(Vector3f(1, 0, 0) * angle); } Quaternionf rotateY(float angle) { return rotationVectorToQuaternion(Vector3f(0, 1, 0) * angle); } Quaternionf rotateZ(float angle) { return rotationVectorToQuaternion(Vector3f(0, 0, 1) * angle); } } // namespace media } // namespace android
true
c896c0c34c8bebca24e5fba4e37e5998fa32a3fd
C++
Agrelimos/tutorials
/Win32/Drawing Shapes/win_main.cpp
WINDOWS-1252
10,520
3.046875
3
[ "MIT" ]
permissive
// Done by TheTutor /* This tutorial is an introduction to the many GDI (Graphical Device Interface) functions Windows has for drawing shapes. Using the Win32 API, we will generate the following shapes: Ellipse Arc Polygon Line So with that brief introduction lets head to the code and get drawing. */ #include <windows.h> #include <assert.h> //////////////// // Constants // ////////////// const int kWinWid = 640; // Width of window const int kWinHgt = 480; // Height of window const int kMaxShapes = 4; // Maximum number of shapes drawn by this tutorial const char kClassName[] = "GameTutorials_DrawingShapes"; // WNDCLASSEXs name ////////////// // Globals // //////////// HDC gHDC = NULL; // The window's device context RECT gRect = {0}; // The window's client area // Our global pens HPEN gPen = NULL; HPEN gOldPen = NULL; // Our global brushes HBRUSH gBrush = NULL; HBRUSH gOldBrush = NULL; // Standard callback function LRESULT CALLBACK WinProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam); // Selects a pen and brush into our window's HDC void SelectRandomPenAndBrush(); // Unselect and frees up the currently selected pen and brush in // our window's HDC void UnselectPenAndBrush(); // These four functions draw a random [ fill in the name of the shape ] to our window void DrawRandomEllipse(); void DrawRandomArc(); void DrawRandomLine(); void DrawRandomPolygon(); int WINAPI WinMain(HINSTANCE hinstance, HINSTANCE hprev, PSTR cmdline, int ishow) { HWND hwnd; MSG msg; WNDCLASSEX wndclassex = {0}; // Fill the fields we care about wndclassex.cbSize = sizeof(WNDCLASSEX); wndclassex.style = CS_HREDRAW | CS_VREDRAW; wndclassex.lpfnWndProc = WinProc; wndclassex.hInstance = hinstance; wndclassex.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); wndclassex.lpszClassName = kClassName; wndclassex.hCursor = (HCURSOR)LoadImage(NULL, MAKEINTRESOURCE(IDC_ARROW), IMAGE_CURSOR, 0, 0, LR_SHARED); // Load the default arrow cursor RegisterClassEx(&wndclassex); // Register the WNDCLASSEX // Create our window hwnd = CreateWindow(kClassName, "www.GameTutorials.com -- GDI Shape Drawing", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, // Window will receive a default X-Pos on screen CW_USEDEFAULT, // Window will receive a default Y-Pos on screen kWinWid, kWinHgt, NULL, NULL, hinstance, NULL); // Error check if(!hwnd) return EXIT_FAILURE; // Something really bad happened! srand( GetTickCount() ); // Seed the random number generator gHDC = GetDC(hwnd); // Get the window's device context //Error check if(!gHDC) return EXIT_FAILURE; // Couldn't get window's HDC // Get the client area of the window GetClientRect(hwnd, &gRect); // Make the window visible and draw it once to the screen ShowWindow(hwnd, ishow); UpdateWindow(hwnd); while(1) { // Get message(s) if there is one if(PeekMessage(&msg,NULL,0,0,PM_REMOVE)) { if(msg.message == WM_QUIT) break; TranslateMessage(&msg); DispatchMessage(&msg); } else { // Select a new pen and brush SelectRandomPenAndBrush(); // Randomly select one of our four shapes to draw switch(rand()%kMaxShapes) { case 0: DrawRandomEllipse(); break; case 1: DrawRandomArc(); break; case 2: DrawRandomLine(); break; case 3: DrawRandomPolygon(); break; } // Unselect the pen and brush so we can select a new pen and brush // the next time we draw UnselectPenAndBrush(); Sleep(1000); // Wait for a second, then draw another random shape } } // Free up the WNDCLASSEX that was registered UnregisterClass(kClassName, hinstance); return (int)msg.wParam; } // The WinProc LRESULT CALLBACK WinProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) { // Handle the messages we care about switch(message) { case WM_DESTROY: // Destroy the window ReleaseDC(hwnd,gHDC); // Free up global HDC PostQuitMessage(0); // Send WM_QUIT message return 0; } // end of switch(message) return DefWindowProc(hwnd, message, wparam, lparam); } void SelectRandomPenAndBrush() { // Calculate a random color for the pen and brush // each time we select a new one COLORREF penColor = RGB(rand()%256, rand()%256, rand()%256); COLORREF brushColor = RGB(rand()%256, rand()%256, rand()%256); // Create a pen and brush for using gPen = CreatePen(PS_SOLID, 2, penColor); // Solid pen 2 units wide gBrush = CreateSolidBrush(brushColor); // Solid colored brush assert((gPen != NULL) && (gBrush != NULL)); // Safety check // Select the pen and brush into the window's device context so // that we can draw with them gOldPen = (HPEN)SelectObject(gHDC, gPen); gOldBrush = (HBRUSH)SelectObject(gHDC, gBrush); assert((gOldPen != NULL) && (gOldBrush != NULL)); // Safety check } void UnselectPenAndBrush() { // Put back the original pen and brush SelectObject(gHDC, gOldPen); SelectObject(gHDC, gOldBrush); // Free up the pen and brush DeleteObject(gPen); DeleteObject(gBrush); } // Draw an ellipse using Win32 GDI void DrawRandomEllipse() { // Calculate the center of the client area of the window int cenX = gRect.right / 2; int cenY = gRect.bottom / 2; // Calculate two random offsets in the X and Y direction // The first is a number between 0 and (cenX - 1) // The second is a number between 0 and (cenY - 1) int x = rand()%cenX; int y = rand()%cenY; // Draw a random ellipse. You pass the GDI function a bounding rectangle // that you want the ellipse to be contained in. The center of the rectangle // is the center of the ellipse and the outer boundaries of the rectangle will // contain the ellipse. The ellipse will be outlined with the current pen and // filled in with the current brush. // Lets break down each parameter: // gHDC -- The device context to draw the ellipse to. Here gHDC is our // window's HDC so the ellipse will be drawn to our window. // cenX - x -- The upper-left X-position of the bounding rectangle of the ellipse // cenY - y -- The upper-left Y-position of the bounding rectangle of the ellipse // cenX + x -- The lower-right X-position of the bounding rectangle of the ellipse // cenY + y -- The lower-right Y-position of the bounding rectangle of the ellipse Ellipse(gHDC, cenX - x, cenY - y, cenX + x, cenY + y); } // Draw an arc using Win32 GDI void DrawRandomArc() { // Calculate the center of the client area of the window int cenX = gRect.right / 2; int cenY = gRect.bottom / 2; // Calculate two random offsets in the X and Y direction // The first is a number between 0 and (cenX - 1) // The second is a number between 0 and (cenY - 1) int x = rand()%cenX; int y = rand()%cenY; // Draw the arc. You pass GDI a bounding rectangle which will contain the arc. // Then you pass GDI the starting position and ending position of the arc. The // arc will be drawn with the currently selected pen. The currently selected // brush is ignored. // By parameter: // gHDC -- The device context to use for drawing the arc // cenX - x -- Upper-left X-position of bounding rectangle of arc // cenY - y -- Upper-left Y-position of bounding rectangle of arc // cenX + x -- Lower-right X-position of bounding rectangle of arc // cenY + y -- Lower-right Y-position of bounding rectangle of arc // cenX - (x / 2) -- Starting X-position of arc // cenY - (y / 2) -- Starting Y-position of arc // cenX + (x / 2) -- Ending X-position of arc // cenY + (y / 2) -- Ending Y-position of arc Arc(gHDC, cenX - x, cenY - y, cenX + x, cenY + y, cenX - (x / 2), cenY - (y / 2), cenX + (x / 2), cenY + (y / 2)); } // Draw a line using Win32 GDI void DrawRandomLine() { // Calculate a random starting (x,y) inside the client area of our window int startX = rand()%gRect.right; int startY = rand()%gRect.bottom; // Calculate a random ending (x,y) inside the client area of our window int endX = rand()%gRect.right; int endY = rand()%gRect.bottom; // First we position the tip of the pen to the location we want to // begin drawing a line from. // By parameter: // gHDC -- The device context to move the virtual tip of the pen on // startX -- X-position of where to begin drawing from // startY -- Y-position of where to begin drawing from // NULL -- This is an optional pointer to a POINT struct. If a valid // pointer was passed, it would be filled with the previous position // of the virtual tip of the pen MoveToEx(gHDC,startX,startY,NULL); // Draw the line. The line is drawn from where the tip of the pen is // (set by MoveToEx) up to, but not including, (endX, endY). The pen // will be drawn with whatever pen is currently selected. // By parameter: // gHDC -- The device context for the line to be drawn on // endX -- The ending X-position of the line // endY -- The ending Y-position of the line LineTo(gHDC,endX,endY); } // Draw a polygon using Win32 GDI void DrawRandomPolygon() { // Maximum number of points in our random polygon const int kMaxPoints = 4; // Create an array of four totally random points contained // within the client area of our window POINT points[kMaxPoints] = { {rand()%gRect.right, rand()%gRect.bottom}, {rand()%gRect.right, rand()%gRect.bottom}, {rand()%gRect.right, rand()%gRect.bottom}, {rand()%gRect.right, rand()%gRect.bottom} }; // Draw the polygon. You pass a list of points that define the // outside dimesion of the polygon and the number of points that define // the polygon. The polygon is then outlined with the current pen and // filled in with the current brush. // By parameter: // gHDC -- The device context we want to draw the polygon to // points -- An array of points that define the polygon's shape // kMaxPoints -- The number of points in the "points" array passed to the function Polygon(gHDC,points,kMaxPoints); } // Shape up or ship out! /* While not the fastest way to draw anything, GDI does provide a bunch of well tested functionality for drawing shapes. If it's a not a speed critical task, the Win32 GDI shape drawing functions should serve you well. Got a question? Be sure to post it at the forums on www.GameTutorials.com. */ /*-------------------------*\ | Programmed by: TheTutor | | 2005 GameTutorials, LLC | \*-------------------------*/
true
98b43f75149ba636c186529959e32aef72e92847
C++
killkelleyr/Programming
/College/C/Sort/Sort/Sort/Source.cpp
UTF-8
946
3.546875
4
[]
no_license
#include <stdio.h> int sort(int a[], int size); int main(void){ int duplicate; int num[5]; //int x; printf("Please enter 5 integers\n"); for (int x=0; x < 5; x++){ scanf_s("%d", &num[x]); } duplicate = sort(num, 5); if (duplicate == 0) printf("There were duplicates in the input\n"); if (duplicate == 1) printf("No duplicates in the input\n"); return (0); } int sort(int a[], int size){ int isit = 1; int hold = 0; for (int count = 0; count < 4; count++){ for (int check = 0; check < 4; check++){ if (a[check]>a[check + 1]) { hold = a[check]; a[check] = a[check + 1]; a[check + 1] = hold; } } } for (int count = 0; count < 5; count++){ for (int test = count + 1; test < 4; test++){ if (a[count] == a[test]){ isit = 0; } } } printf("\nHere is the sorted order\n"); for (int count = 0; count < 5; count++){ printf("%d\n", a[count]); } return(isit); }
true
414c19ced0341bd0a127813f219cfdde0265b4e8
C++
xCrosByx/KATET
/laba-2.1/Armament.cpp
WINDOWS-1251
5,793
3.1875
3
[]
no_license
#include "Armament.h" void Armament::get_manufacturer_country(string country) { manufacturer_country = country; } void Armament::get_name_of_armament(string name) { name_of_armament = name; } void Armament::get_cost(int price) { cost = price; } void Technics::get_number_of_people(int quantity) { number_of_people = quantity; } void Technics::get_fuel_quantity(int liter) { fuel_quantity = liter; } void Ship::get_displacement(int volume) { displacement = volume; } void Battle_ship::view() { setlocale(LC_ALL, "ru"); cout << " \n"; cout << " : " << name_of_armament << endl; cout << " : " << manufacturer_country << endl; cout << " () : " << displacement << endl; cout << " : " << number_of_people << endl; cout << " () : " << fuel_quantity << endl; cout << " $ : " << cost << endl; } void Plan::get_max_height(double height) { max_height = height; } void Plan::get_max_speed(int speed) { max_speed = speed; } void Battle_plan::view() { setlocale(LC_ALL, "ru"); cout << " \n"; cout << " : " << name_of_armament << endl; cout << " : " << manufacturer_country << endl; cout << " () : " << max_height << endl; cout << " (/) : " << max_speed << endl; cout << " : " << number_of_people << endl; cout << " () : " << fuel_quantity << endl; cout << " $ : " << cost << endl; } void Car::get_number_of_wheels(int quntity) { number_of_wheels = quntity; } void Car::get_weght(double mass) { weght = mass; } void Battle_car::view() { setlocale(LC_ALL, "ru"); cout << "-\n"; cout << " : " << name_of_armament << endl; cout << " : " << manufacturer_country << endl; cout << " : " << number_of_wheels << endl; cout << " () : " << weght << endl; cout << " : " << number_of_people << endl; cout << " () : " << fuel_quantity << endl; cout << " $ : " << cost << endl; } void Firearm::get_caliber(double number) { caliber = number; } void Firearm::get_ammunition(int quantity) { ammunition = quantity; } void Firearm::get_weight_gramm(int weight) { weight_gramm = weight; } void Firearm::get_starting_speed(int speed) { starting_speed = speed; } void Assault_rifle::get_rate_of_fire(int quantity) { rate_of_fire = quantity; } void Assault_rifle::view() { setlocale(LC_ALL, "ru"); cout << "\n"; cout << " : " << name_of_armament << endl; cout << " : " << manufacturer_country << endl; cout << " () : " << caliber << endl; cout << " (/) : " << rate_of_fire << endl; cout << " (/) : " << starting_speed << endl; cout << " : " << ammunition << endl; cout << " () : " << weight_gramm << endl; cout << " $ : " << cost << endl; } void Rifle::get_range_of_defeat(int range) { range_of_defeat = range; } void Rifle::view() { setlocale(LC_ALL, "ru"); cout << "\n"; cout << " : " << name_of_armament << endl; cout << " : " << manufacturer_country << endl; cout << " () : " << caliber << endl; cout << " () : " << range_of_defeat << endl; cout << " (/) : " << starting_speed << endl; cout << " : " << ammunition << endl; cout << " () : " << weight_gramm << endl; cout << " $ : " << cost << endl; } void Explosive_device::Grenade::view() { setlocale(LC_ALL, "ru"); cout << "\n"; cout << " : " << name_of_armament << endl; cout << " : " << manufacturer_country << endl; cout << " () : " << affected_area << endl; cout << " $ : " << cost << endl; } void Explosive_device::Grenade::get_affected_area(int radius) { affected_area = radius; } void Grenade_launcher::view() { setlocale(LC_ALL, "ru"); cout << "\n"; cout << " : " << name_of_armament << endl; cout << " : " << manufacturer_country << endl; cout << " () : " << caliber << endl; cout << " () : " << range_of_defeat << endl; cout << " () : " << affected_area << endl; cout << " (/) : " << starting_speed << endl; cout << " : " << ammunition << endl; cout << " () : " << weight_gramm << endl; cout << " $ : " << cost << endl; } void Grenade_launcher::get_affected_area_of_grenade_launcher(int radius) { get_affected_area(radius); }
true
8fd2eef8fa73ddeb5307a79d6cb23c59b67e783c
C++
gridem/ReplobPrototype
/tests/serialization_tests.cpp
UTF-8
8,700
2.515625
3
[ "Apache-2.0" ]
permissive
/* * Copyright 2015 Grigory Demchenko (aka gridem) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <vector> #include <cstring> #include <chrono> #include <synca/synca.h> #include <synca/log.h> #include "ut.h" using Ptr = Byte*; using PtrArray = Ptr*; using IntArray = int*; using Buf = std::vector<Byte>; constexpr size_t ptrSize = sizeof(Ptr); constexpr size_t intSize = sizeof(int); struct View { Ptr data; size_t size; }; Buf viewToBuf(View view) { return {view.data, view.data + view.size}; } struct IAllocator : IObject { virtual void* alloc(size_t sz) = 0; virtual void dealloc(void *p) = 0; }; struct DefaultAllocator { static void* alloc(size_t sz) { void *p = malloc(sz); VERIFY(p != nullptr, "Allocation failed"); return p; } static void dealloc(void *p) noexcept { free(p); } }; thread_local Buf t_buffer(1024*1024*10); thread_local IAllocator* t_allocator = nullptr; struct MemoryAllocator : IAllocator { MemoryAllocator() { t_allocator = this; } ~MemoryAllocator() { t_allocator = nullptr; if (nDealloc_) LOG("Deallocations: " << nDealloc_ << ": " << dp_); } void* alloc(size_t sz) override { Ptr p = t_buffer.data() + offset_; size_t diff = sz % ptrSize; if (diff) sz += ptrSize - diff; offset_ += sz; VERIFY(offset_ <= t_buffer.size(), "MemoryAllocator: allocation failed: oversize"); return p; } void dealloc(void *p) override { if (p >= t_buffer.data() && p < t_buffer.data() + t_buffer.size()) { ++ nDealloc_; dp_ = p; } else { DefaultAllocator::dealloc(p); } } size_t size() const { return offset_; } void setSize(size_t size) { offset_ = size; } private: size_t offset_ = 0; int nDealloc_ = 0; void* dp_ = nullptr; }; void* operator new(size_t sz) { return t_allocator ? t_allocator->alloc(sz) : DefaultAllocator::alloc(sz); } void operator delete(void *p) noexcept { t_allocator ? t_allocator->dealloc(p) : DefaultAllocator::dealloc(p); } void setAllocator(IAllocator* a) { t_allocator = a; } IAllocator* getAllocator() { return t_allocator; } template<typename T> Buf serialize(const T& t) { View v {t_buffer.data(), 0}; { MemoryAllocator a; new T(t); v.size = a.size(); } Buf buf = viewToBuf(v); std::memset(v.data, 0, v.size); // need to be zeroized to avoid diff collisions return buf; } template<typename T> T deserialize(const Buf& buf) { VERIFY(buf.size() <= t_buffer.size(), "Buffer is too large"); std::memcpy(t_buffer.data(), buf.data(), buf.size()); return *(T*)t_buffer.data(); } template<typename T> Buf serializeRelative(const T& t) { View v {t_buffer.data(), 0}; size_t total; { MemoryAllocator a; new T(t); v.size = a.size(); new T(t); total = a.size(); } VERIFY(v.size % ptrSize == 0, "Unaligned data"); // carefully!!! verify allocates the memory VERIFY(v.size * 2 == total, "Unpredictable copy constructor"); int pCount = v.size / ptrSize; int diffIndex = v.size / intSize; auto data = PtrArray(v.data); auto diffData = IntArray(v.data); for (int i = 0; i < pCount; ++ i) { int diff = data[i + pCount] - data[i]; if (diff) { //LOG("Diff: " << i << ", " << diff << ", " << diffIndex); VERIFY(diff == v.size, "Invalid pointers shift"); data[i] -= intptr_t(v.data); diffData[diffIndex ++] = i; } } diffData[diffIndex ++] = v.size / intSize; v.size = diffIndex * intSize; //LOG("diff index created: " << v.size << ", " << diffIndex << ", " << pCount); Buf buf = viewToBuf(v); std::memset(v.data, 0, total); return buf; } // perform in-place transformations template<typename T> T& deserializeRelative(Buf& buf) { VERIFY(buf.size() >= intSize, "Invalid buffer size: must be >= intSize"); VERIFY(buf.size() % intSize == 0, "Invalid buffer size: must be aligned"); int intCount = buf.size() / intSize - 1; // not to include the diff index auto intArray = IntArray(buf.data()); auto data = PtrArray(buf.data()); int diffIndex = intArray[intCount]; VERIFY(diffIndex <= intCount, "Invalid diff index"); int dataCount = diffIndex * intSize / ptrSize; for (int i = diffIndex; i < intCount; ++ i) { int dataIndex = intArray[i]; //LOG("Replacing: " << i << ", " << dataIndex); VERIFY(dataIndex < dataCount, "Invalid data index"); data[dataIndex] += intptr_t(buf.data()); } return *(T*)buf.data(); } template<typename T> std::ostream& operator<<(std::ostream& o, const std::vector<T>& v) { for (auto&& t: v) o << t << " "; return o; } template<typename F> void measure(const char* name, F f, size_t count) { auto beg = std::chrono::high_resolution_clock::now(); for (size_t i = 0; i < count; ++ i) f(); auto end = std::chrono::high_resolution_clock::now(); int ns = std::chrono::duration_cast<std::chrono::nanoseconds>(end - beg).count() * 1.0 / count; LOG(name << ": " << ns << "ns"); } TEST(serialization, vector) { std::vector<int> v {1, 2, 3, 10, 0x30}; auto buf = serialize(v); auto v2 = deserialize<std::vector<int>>(buf); ASSERT_EQ(v, v2); } TEST(serialization, relative) { try { std::vector<int> v {1, 2, 3, 10, 47, 5}; auto buf = serializeRelative(v); auto beg = IntArray(buf.data()); for (int i = 0; i < buf.size() / intSize; ++ i) { LOG(i << ": " << beg[i]); } auto v2 = deserializeRelative<std::vector<int>>(buf); for (auto val: v2) { LOG(val); } ASSERT_EQ(v, v2); } catch (std::exception& e) { LOG("Error: " << e.what()); } } TEST(serialization, relative2) { try { std::map<std::vector<int>, int> v {{{1, 2}, 1}, {{5, 3, 2}, 5}}; auto buf = serializeRelative(v); auto beg = IntArray(buf.data()); for (int i = 0; i < buf.size() / intSize; ++ i) { LOG(i << ": " << beg[i]); } auto v2 = deserializeRelative<std::map<std::vector<int>, int>>(buf); ASSERT_TRUE(v == v2); } catch (std::exception& e) { LOG("Error: " << e.what()); } } /* TEST(serialization, relative2BenchLite) { struct Lite { int32_t x; std::vector<int64_t> y; }; Lite l; l.x = 1; l.y = {10,11}; measure("serialize lite", [&]{ auto buf = serializeRelative(l); }, 1000000); } Buf toBuf(const char* s) { std::string c(s); return Buf{c.begin(), c.begin() + c.size()}; } TEST(serialization, relative2BenchHeavy) { struct Lite { int32_t x; std::vector<int64_t> y; }; struct Heavy { std::vector<int32_t> x; std::vector<Buf> s; std::vector<Lite> z; }; Heavy h; h.x = {1,2,3,4,5,6,7,8,9,10}; h.s = {toBuf("hello"), toBuf("yes"), toBuf("this"), toBuf("is"), toBuf("dog")}; h.z = {Lite{1, {10,11}}, Lite{2, {32,33,34,35}}}; measure("serialize heavy", [&]{ auto buf = serializeRelative(h); }, 100000); } TEST(deserialization, relative2BenchHeavy) { struct Lite { int32_t x; std::vector<int64_t> y; }; struct Heavy { std::vector<int32_t> x; std::vector<Buf> s; std::vector<Lite> z; }; Heavy h; h.x = {1,2,3,4,5,6,7,8,9,10}; h.s = {toBuf("hello"), toBuf("yes"), toBuf("this"), toBuf("is"), toBuf("dog")}; h.z = {Lite{1, {10,11}}, Lite{2, {32,33,34,35}}}; Buf buf = serializeRelative(h); measure("deserialize heavy", [&]{ Heavy& h = deserializeRelative<Heavy>(buf); }, 10000000); } */ TEST(math, test) { ASSERT_EQ(-2, -2 % 4); ASSERT_EQ(-2, -10 % 4); } CPPUT_TEST_MAIN
true
eff79413156aec15ebc56fdcd0f962d414243964
C++
esarver/svd-pca
/src/utility/program_options.hpp
UTF-8
3,881
3.203125
3
[ "MIT" ]
permissive
#pragma once #include <string> /** * @brief The ProgramOptions class is a singleton class with a * fully static interface. It contains all the information the user * provided on the command-line. */ class ProgramOptions { public: /** * @brief The AlgorithmSelection enum defines the 3 different supported * Algorithms used in this program. * * BFS: Breadth-First Search * FORD_FULKERSON: The Ford-Fulkerson algorithm implemented using the BFS * CIRCULATION: The solution for the circulation problem */ enum AlgorithmSelection { NONE = 0, TO_BINARY = 1, FROM_BINARY = 2, COMPRESSED_SVD = 3, FROM_COMPRESSED_SVD = 4, RANDOM_IMAGE = 5, QUICK = 6 }; /** * @brief Clears the current ProgramOptions instance * * There isn't much normal use for this method besides * in testing. */ static void clear(); /** * @brief Get the provided filepath of the graph text-file * @return The provided filepath string */ static const std::string graph_filepath(); /** * @brief Get the singleton instance of ProgramOptions * * Check to see if an instance already exists. * If it does return that. * Otherwise, instantiate an instance and return that one. * * @return The current singleton instance of ProgramOptions * */ static ProgramOptions* instance(); /** * @brief Parse the input options sent on the command line. * * Perform some basic error-checking. * * Example inputs: * `<program_name> -b file/path/name.ext 0 5` * `<program_name> -f file/path/name.ext` * `<program_name> -c file/path/name.ext` * * @throws std::string with the error-text. * * @param argc - The argc that is sent down from the system * @param argv - The argv that is sent down from the system */ static void parse(int argc, char** argv); /** * @brief Prints the help message. */ static void print_help(); /** * @brief Get the name of the program as it was run by the user * @return The name of the program as it was run by the user */ static const std::string& program_name(); /** * @brief Get which algorithm was selected * @return The enum the IDs the selected algorithm */ static AlgorithmSelection selected_algorithm(); /** * @brief Get the filepath given for the ASCII pgm * file * * @return The filepath string for the ASCII pgm file */ static const std::string& text_pgm_filepath(); /** * @brief Get the filepath given for the binary pgm * file * * @return The filepath string for the binary pgm file */ static const std::string& binary_pgm_filepath(); /** * @brief Get the filepath given for the pgm header * file * * @return The filepath string for the pgm header file */ static const std::string& pgm_header_filepath(); /** * @brief Get the filepath given for the SVD matrices * file * * @return The filepath string for the SVD matrices file */ static const std::string& svd_matrices_filepath(); /** * @brief Get the approximation rank * * @return the integer given for the approximation rank */ static int approximation_rank(); private: /** * @brief The hidden constructor for the ProgramOptions singleton. */ ProgramOptions(); AlgorithmSelection m_algorithm; std::string m_program_name; std::string m_text_pgm_filepath; std::string m_binary_pgm_filepath; std::string m_pgm_header_filepath; std::string m_svd_matrices_filepath; int m_approximation_rank; static ProgramOptions* s_instance; };
true
653cd4df555cceacba7b9c87477d486ae5bf6cc9
C++
Demi871023/UVa-Problem
/UVa10535/UVa10535.cpp
UTF-8
1,786
3.5625
4
[ "MIT" ]
permissive
//UVa 10535 Shooter /* 想法: 計算每個線段的端點極角,排列所有極角後,從最小角度開始掃描。 邊紀錄+1或-1值進入S[]。 最後再掃描一遍S[],取max值即為答案 */ #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <algorithm> using namespace std; const double eps = 1e-9; const double pi = acos(-1.0); //利用反餘弦求出3.14159... const int N = 1005; struct State { double t; int k; }; struct Point { double x1,y1,x2,y2; }; State s[N*2]; Point p[N]; int n, m; double x, y; bool cmp(const State &a, const State &b) { if(fabs(a.t-b.t) > eps) { return a.t < b.t; } return a.k > b.k; } int solve() { int ans = 0, c = 0; for(int i = 0 ; i < m ; i++) { c = c+ s[i].k; ans = max(ans, c); } return ans; } int main() { freopen("10535.in", "r", stdin); freopen("test.out", "w", stdout); while(scanf("%d", &n) && n) { m = 0; for(int i = 0 ; i < n ; i++) { scanf("%lf%lf%lf%lf", &p[i].x1, &p[i].y1, &p[i].x2, &p[i].y2); } scanf("%lf%lf", &x, &y); for(int i = 0 ; i < n ; i++) { double I = atan2(p[i].y1 - y, p[i].x1 - x); double R = atan2(p[i].y2 - y, p[i].x2 - x); if(I > R) { swap(R,I); } if(R - I >= pi) { //如果一道牆橫跨以射擊基準為X軸的上下,就要將牆分成兩個,以下圖解。 /* 牆面 | (x軸上部) | ----------。--------(將射擊點。為中心的x軸) | | (x軸下部) */ s[m].t = -pi; s[m++].k = 1; s[m].t = I; s[m++].k = -1; I = R; R = pi; } s[m].t = I; s[m++].k = 1; s[m].t = R; s[m++].k = -1; } sort(s, s+m, cmp); printf("%d\n", solve()); } return 0; }
true
d8caaad6584a55dbb86a4dbcf019346f07044724
C++
Taohid0/C-and-C-Plus-Plus
/vector2/main.cpp
UTF-8
506
3.125
3
[]
no_license
#include <bits/stdc++.h> int main() { std::vector<int>v(4); v.push_back(1); v.push_back(2); v.push_back(30); printf("%d\n",(int)v.size()); for(std::vector<int>::iterator itr = v.begin();itr!=v.end();itr++){ printf("%d ",*itr); } v.clear(); if(v.empty()){ printf("\nvector is empty"); } std::vector<int>vec2(v); for(std::vector<int>::iterator itr =v.begin();itr!=v.end();itr++){ printf("\n%d ",*itr); } return 0; }
true
f02e12d1f4f156b33f5bb0048f7364c0305d6492
C++
aliceresearch/MAGPIE
/src/scenarios/common/nodes/Prog2Node.h
UTF-8
596
2.890625
3
[]
no_license
#ifndef PROG2NODE_H #define PROG2NODE_H #include "../../../gp/Node.h" /** * {@link Lawnmower} node for joining two child nodes together. */ class Prog2Node : public Node { public: /** Constructs the node with an arity of 2 and the name 'Prog2' */ Prog2Node() : Node(2, "Prog2") { } /** Evaluate child nodes from left to right. */ void evaluate(Individual *individual, QStack<Node *> *programStack); /** Clones the node. */ Node *clone() const; /** Create a new {@link LeftNode} */ static Node *create() { return new Prog2Node(); } }; #endif // PROG2NODE_H
true
267504ddec0fbf24892834a474ba57cfcfd5476c
C++
cheyiwei/PAT_B
/1036_2.cpp
UTF-8
406
2.546875
3
[]
no_license
/* ID:PAT_B_1036 time@2018/2/4 author@cheyiwei */ #include<cstdio> int main(){ int edge,c; scanf("%d %c",&edge,&c); int i = 1,j = 1; int column = (edge+1)/2; for(i=1;i<=column;i++){ if(i==1 || i == column){ for(j=0;j<edge;j++){ printf("%c",c); } }else{ printf("%c",c); for(j=0;j<edge - 2;j++){ printf(" ",c); } printf("%c",c); } if(i!=column) printf("\n"); } }
true
1cb6521cbc67d1e32a8a934f9119f5e74f1121cb
C++
zhihengq/2048
/include/game_state.h
UTF-8
4,632
3.578125
4
[ "MIT" ]
permissive
#ifndef _GAME_STATE_H_ #define _GAME_STATE_H_ #include <cstdint> #include <vector> #include <ostream> #include "tile.h" #include "grid.h" namespace _2048 { /** * Represents a game state. */ class GameState { public: friend std::ostream &operator<<(std::ostream &os, const GameState &g); GameState &operator=(const GameState &) = delete; /** * A struct packing a row index and a col index. */ struct Position { uint32_t r; uint32_t c; explicit constexpr Position(uint32_t r = 0, uint32_t c = 0) noexcept : r(r), c(c) { } constexpr Position(const Position &p) noexcept : r(p.r), c(p.c) { } bool operator==(const Position &p) const noexcept { return r == p.r && c == p.c; } }; /** * The four directions that each move can be in. */ enum class Direction { UP, DOWN, LEFT, RIGHT }; /** * Construct an empty `GameState` of size `height` by `width`. * @param height the height of the game grid * @param width the width of the game grid * @throw std::invalid_argument if the size if empty */ GameState(uint32_t height, uint32_t width) : grid_(height, width) { } /** * Copy constructor * @param g the `GameState` to be copied * @throw std::runtime_error if `g` is not in a valid state */ GameState(const GameState &g) : grid_(g.grid_) { } /** * Move constructor. * The original game state `g` will be unusable. * @param g the `GameState` to be moved */ GameState(GameState &&g) noexcept : grid_(std::move(g.grid_)) { } /** * Get game grid height. * @return the height */ uint32_t height() const noexcept { return grid_.height; } /** * Get game grid width. * @return the width */ uint32_t width() const noexcept { return grid_.width; } /** * Equality * @param g the other `GameState` object * @return true if the two game states are identical, false otherwise * @throw std::runtime_error if `this` or `g` is not in a valid state */ bool operator==(const GameState &g) const { return grid_ == g.grid_; } /** * Inequality * @param g the other `GameState` object * @return false if the two game states are identical, true otherwise * @throw std::runtime_error if `this` or `g` is not in a valid state */ bool operator!=(const GameState &g) const { return grid_ != g.grid_; } /** * Get a tile. * @param pos the position of the tile * @return a read-only view of the tile * @throw std::out_of_range if the position is out of range * @throw std::runtime_error if `this` is not in a valid state */ const Tile &tile(Position pos) const { return grid_.tile(pos.r, pos.c); } /** * Get a list of empty tiles. * Generator side operation. * @return a vector of pointers to available tiles in the game grid * @throw std::runtime_error if `this` is not in a valid state */ std::vector<Position> GetEmptyTiles() const; /** * Generate a tile in the game grid. * Generator side operation. * @param pos the position of the new tile * @param power number in the new tile in terms of power of 2 * @return true if the tile is generated, false if the position is not empty * @throw std::out_of_range if the position is out of range * @throw std::runtime_error if `this` is not in a valid state */ bool GenerateTile(Position pos, uint8_t power); /** * Get the directions that can be moved in. * Player side operation. * @return a vector of directions that can be moved in * @throw std::runtime_error if `this` is not in a valid state */ std::vector<Direction> GetPossibleMoves() const; /** * Apply a move. * Player side operation. * @param dir the direction * @return true if the move is applied, false if the move is not possible * @throw std::runtime_error if `this` is not in a valid state */ bool Move(Direction dir); private: Grid grid_; /**< Underlying grid */ void GetPossibleDir(bool *left, bool *right, bool *up, bool *down) const; }; /** * Print the game grid as a human-readable string * @param os the output stream * @param g the `GameState` object * @return `os` * @throw std::runtime_error if `g` is not in a valid state */ inline std::ostream &operator<<(std::ostream &os, const GameState &g) { return os << g.grid_; } } // namespace _2048 #endif // _GAME_STATE_H_
true
a979a583bbea9d2fe0b6b841dc864f7997f4d0c6
C++
nmd2611/ADSL
/assign7.cpp
UTF-8
6,410
3.6875
4
[]
no_license
//============================================================================ // Name : assign7.cpp // Author : // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> using namespace std; class Node { public: string key; string type; //string size; int chain; Node() { key=type=""; chain=-1; } }; /* else { // first, check if the existing is atits correct position // if no, remove the existing element and push it // to the next empty position int ke = calculateKeyValue(table[pos].key) ; // calculate key of existing element if(ke == pos) // i.e. correct position of the existing element { // push the new element down int p=pos; while(table[p].key != "") { if(table[p].chain != -1) { p=table[p].chain; pos=p; } else p++; // goto that chain } table[p].key=k; table[p].type=t; table[pos].chain=p; } else { // place the new element at that position // and push the existing element down string temp1=table[pos].key; string temp2=table[pos].type; table[pos].key=k; table[pos].type=t; // new element has been placed // now push the existing element down int p=pos; while(table[p].key != "") { if(table[p].chain != -1) { p=table[p].chain; pos=p; } else p++; // goto that chain } table[p].key=temp1; table[p].type=temp2; } */ class SymbolTable { public: Node table[26]; // this is without replacement // int this , the new element to be added is pushed down irrespective of // whether the element at its position is correct or not // eg. // the new element will always be pushed down if its position is occupied void insertKey() { string k; string t; cout<<"Enter the Key"<<endl; cin>>k; cout<<"Enter the type"<<endl; cin>>t; int pos= calculateKeyValue(k); if(table[pos].key == "") { table[pos].key=k; table[pos].type=t; } else { int p=pos; while(table[p].key != "") { if(table[p].chain != -1 && table[p].key[0] == k[0]) { p=table[p].chain; pos=p; } else p++; // goto that chain } table[p].key=k; table[p].type=t; if(table[pos].key[0] == k[0]) table[pos].chain=p; } cout<<"Key Inserted Successfully !!"<<endl; } void insertWith() { string k; string t; cout<<"Enter the Key"<<endl; cin>>k; cout<<"Enter the type"<<endl; cin>>t; int pos= calculateKeyValue(k); // case 1: position is vacant // so elemnt is directly placed if(table[pos].key == "") { table[pos].key=k; table[pos].type=t; } else { // case 2: both (existing and new elemnt) have their correct position // then push the new element down if(table[pos].key[0] == k[0]) { // same code as without replacement int p=pos; while(table[p].key != "") { if(table[p].chain != -1 && table[p].key[0] == k[0]) { p=table[p].chain; pos=p; } else { p++; } // goto that chain } table[p].key=k; table[p].type=t; if(table[pos].key[0] == k[0]) table[pos].chain=p; } else { // if wrong position occupied by existing element // now store the existing element in a temporary variable string temp1= table[pos].key; string temp2= table[pos].type; //int temp3 = table[pos].chain; int tp; // now, find the chain value of the parent of this element // travese the list to find the position of the parent for(int i=0;i<26;i++) { if(table[i].chain == pos) { tp=i; break; } } table[pos].key = k; table[pos].type= t; int tp2=table[pos].chain; table[pos].chain=-1; int p=pos; while(table[p].key != "") { p++; } table[p].key=temp1; table[p].type=temp2; table[tp].chain=p; table[p].chain=tp2; } // now place the new element at its position } } void deleteKey() { string k; cout<<"Enter the key to be deleted"<<endl; //cin>>k; // this code is same as search int pos = searchKey(); if(pos == -1) cout<<"Not found"<<endl; else { // first find the chain of the parent int tp; for(int i=0;i<26;i++) { if(table[i].chain == pos) { tp=i; break; } } int tc=table[pos].chain; // chain of child table[pos].key=""; table[pos].chain=-1; table[tp].chain=tc; //table[tc].chain=pos; } } int searchKey() { int COUNT=0; string k; cout<<"Enter the key to be searched"<<endl; cin>>k; int flag=0; int val=calculateKeyValue(k); if(table[val].key == k) cout<<"Key found at position "<<val<<endl; // case for - if the position is empty else if(table[val].key == "") cout<<"Key not found "<<endl; else { // if the key is not found // check if chain is not -1 int tf=0; // take a temporary flag for this special case while(flag == 0 || COUNT<25) { if(table[val].key != "") { if(table[val].key[0] != k[0]) { val++; tf=1; } } else if(table[val].key == "") break; else if(table[val].chain == -1) { flag=0; val=-1; break; } if(tf != 1) val=table[val].chain; if(table[val].key == k) { flag=1; break; } COUNT++; } if(flag == 0) cout<<"Key not found"<<endl; else cout<<"Key found at position "<<val<<endl; } return val; } void printKey() { cout<<"Index \tKey \t \tChain"<<endl; for(int i=0;i<26;i++) cout<<i<<" \t "<<table[i].key<<" \t \t "<<table[i].chain<<endl; } int calculateKeyValue(string k) { int pos; pos=(int)k[0]; pos=pos%97; return pos; } }; int main() { SymbolTable T; int ch; do{ cout<<"1.Insert Key(without) \n2.Print Keys \n3.Insert With \n4.Search Key \n5.Delete Key \n9.EXIT"<<endl; cin>>ch; switch(ch) { case 1: T.insertKey(); break; case 2: T.printKey(); break; case 3: T.insertWith(); break; case 4: T.searchKey(); break; case 5: T.deleteKey(); break; case 9: break; default: cout<<"Wrong Choice"<<endl; break; } }while(ch !=9); return 0; }
true
08b4e0a798d825a3458abc714c37693fa08ff34f
C++
ShuhengLi/LeetCode
/week3/2.AddTwoNumbers.cpp
UTF-8
988
3.609375
4
[]
no_license
/*2. Add Two Numbers You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Example: Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807. */ class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { int carry = 0; ListNode* newhead = new ListNode(-1); ListNode* dummy = newhead; while(l1 || l2 || carry){ int num = (l1?l1->val:0) + (l2?l2->val:0) + carry; carry = num / 10; ListNode* node = new ListNode(num % 10); newhead->next = node; newhead = newhead->next; if(l1) l1 = l1->next; if(l2) l2 = l2->next; } return dummy->next; } };
true
d68fd3a4d059227ea0420e6e1fef6cfbb76b7e62
C++
MCOxford/ParticleExplosion
/ParticleExplosion/Swarm.h
UTF-8
336
2.53125
3
[]
no_license
#ifndef SWARM_H_ #define SWARM_H_ #include "Particle.h" #pragma once class Swarm { public: const static int NPARTICLES = 5000; private: Particle* m_pParticles; int m_LastTime; public: Swarm(); virtual ~Swarm(); const Particle * const getParticles() { return m_pParticles; }; void update(int elapsed); }; #endif // !SWARM_H_
true
7956b3382236e0974bd3afbc3a755a9b5feab70c
C++
lizj3624/mycode
/mystatic.cpp
GB18030
1,155
2.9375
3
[]
no_license
// $_FILEHEADER_BEGIN **************************** // ļƣmystatic.cpp // ڣ20150821 // ˣ LiZunju // ļ˵static.cpp // $_FILEHEADER_END ****************************** #include "mystatic.h" int myclass::my_i2 = 1; int my_i_3 = 33; static int my_i_4 = 44; myclass::myclass() { my_i = 1; } myclass::~myclass() { } void myclass::my_fun1() { std::cout << "fun1"<< std::endl; std::cout << "fun1 i3 = "<< my_i_3 << std::endl; std::cout << "fun1 i4 = "<< my_i_4 << std::endl; } void myclass::my_fun2() { static int fun2_i = 53; std::cout << "fun2" << std::endl; std::cout << "fun2 i3 = "<< my_i_3 << std::endl; std::cout << "fun2 i4 = "<< my_i_4 << std::endl; std::cout << "fun2_i = "<< fun2_i << std::endl; } void my_fun3() { std::cout << "fun3" << std::endl; std::cout << "fun3 i3 = "<< my_i_3 << std::endl; std::cout << "fun3 i4 = "<< my_i_4 << std::endl; my_fun4(); } static void my_fun4() { std::cout << "fun4" << std::endl; std::cout << "fun4 i3 = "<< my_i_3 << std::endl; std::cout << "fun4 i4 = "<< my_i_4 << std::endl; }
true
80979a1a647ad231dd6f9caf659191f8c05e3ff7
C++
zjxjwxk/PAT
/C++/Basic Level/B1028.cpp
UTF-8
1,412
3.40625
3
[]
no_license
#include <cstdio> struct Person { char name[6]; int year; int month; int day; } temp, oldest, youngest, left, right; int ifOlder(Person p1, Person p2) { if (p1.year != p2.year) { return p1.year <= p2.year; } else if (p1.month != p2.month) { return p1.month <= p2.month; } else { return p1.day <= p2.day; } } int ifYounger(Person p1, Person p2) { if (p1.year != p2.year) { return p1.year >= p2.year; } else if (p1.month != p2.month) { return p1.month >= p2.month; } else { return p1.day >= p2.day; } } void init() { oldest.year = right.year = 2014; youngest.year = left.year = 1814; oldest.month = youngest.month = left.month = right.month = 9; oldest.day = youngest.day = left.day = right.day = 6; } int main() { int n, count = 0; init(); scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%s %d/%d/%d", temp.name, &temp.year, &temp.month, &temp.day); if (ifOlder(temp, right) && ifYounger(temp, left)) { if (ifOlder(temp, oldest)) { oldest = temp; } if (!ifOlder(temp, youngest)) { youngest = temp; } count++; } } if (count == 0) { printf("0"); } else { printf("%d %s %s", count, oldest.name, youngest.name); } return 0; }
true
de73c34d3b8c0b4ed9caf27e1b74ee5b3db25cc9
C++
GreimuL/Competitive-programming
/BaekjoonOnlineJudge/implementation/sort/1427.cpp
UTF-8
532
2.96875
3
[]
no_license
#include<iostream> #include<algorithm> using namespace std; int squ(int a, int b) { int temp = 1; for (int i = 0; i < b; i++) { temp *= a; } return temp; } int main() { int realpo; int n; int tempn = 0; int num[12]; int po = 0; int i=0; cin >> n; while (tempn != n) { tempn = n % squ(10, po); po++; } po--; realpo = po; while (po>0) { num[i] = n / squ(10, po - 1); n %= squ(10,po-1); po--; i++; } sort(num, num + realpo); for (int i = realpo-1; i>=0; i--) { cout << num[i]; } }
true
fd54e8f417ac88d1db602e384eeb53b7401a2fdf
C++
Jenny-D/programmiersprachen-aufgabenblatt-2
/source/aufgaben_2_und_3.cpp
UTF-8
677
3.4375
3
[ "MIT" ]
permissive
#include <iostream> #include <list> #include <set> #include <iterator> #include <cstdlib> int main() { std::list<unsigned int> l; for (int i = 0; i < 100; i++) { unsigned int x = std::rand() % 101; l.push_back(x); } std::set<unsigned int> s; for (int i : l) { s.insert(i); } std::cout << "In der Liste sind " << s.size() << " unterschiedliche Zahlen.\n"; std::set<unsigned int> s2; for (int i = 0; i <= 100; i++) { auto x = s.find(i); if (x == s.end()) { s2.insert(i); } } std::cout << "Folgende Zahlen sind nicht in der Liste: "; for (std::set<unsigned int>::iterator pos = s2.begin(); pos != s2.end(); pos++) { std::cout << *pos << " "; } }
true
4dd849a7f461283eccf8b045421299c8469565eb
C++
aa18514/CNN_FPGA
/SIM/maxfiles/convolution_MAX3424A_DFE_SIM/scratch/software-sim/build/DebugStreams.h
UTF-8
1,300
2.546875
3
[]
no_license
#ifndef DEBUGSTREAMS_H_ #define DEBUGSTREAMS_H_ #include <boost/shared_ptr.hpp> #include <map> #include <string> #include <fstream> #include <stdint.h> #include "ManagerSync.h" namespace maxcompilersim { class DebugStreams { private: // first is the name of destination stream // second is the message typedef std::pair<std::string, std::string> Message; typedef std::tr1::unordered_map<std::string, boost::shared_ptr<std::ostream> > StreamMap; typedef std::vector<Message> MessageList; typedef std::map<int, MessageList > MessageSeqMap; const ManagerBlockSync *const m_owner; StreamMap m_open_streams; MessageSeqMap m_messages; std::string m_block_name; std::string m_dump_dir; public: explicit DebugStreams(const ManagerBlockSync *const block, const std::string &block_name); void write(const std::string &stream_name, int seq, const std::string &message); void finishCycle(); void reset(); void setDumpDirectory(const std::string &dir_name); void flush(); private: std::ostream &getStream(const std::string &stream_name, std::ostream& default_stream); std::ostream &getDefaultDebugOStream() const; std::ostream &getDebugBackupOStream() const; static void nullDeallocatorForCout(std::ostream *) {} }; } // maxcompilersim namespace #endif /* DEBUGSTREAMS_H_ */
true
07df0afe842ed7aacd3e73a7fd3af0eed94e2ca6
C++
Kannupriyasingh/CodeForces-Solutions
/LuckyNumber.cpp
UTF-8
457
3.203125
3
[ "MIT" ]
permissive
#include <bits/stdc++.h> using namespace std; int main() { // Input taking N. int N; cin>>N; bool flag=0; // All numbers of 1, 21 3digits of 4 and 7. int arr[12]={4,7,47,74,44,444,447,474,477,777,774,744}; // Checking if given number is satisfying condition or not. for(int i=0;i<12;i++) { if(N%arr[i]==0) { flag=true; } } // Printing Output if(flag) cout<<"YES"; else cout<<"NO"; return 0; }
true
bb7a60ca71b7ca3e85580c4bd06c50823c9e024f
C++
gustavo-candido/ONLINE-JUDGE
/URI/1235.cpp
UTF-8
533
2.703125
3
[]
no_license
#include <stdio.h> #include <string.h> main () { int c=0, z, half, i, j; char A [200], B[200]; scanf("%d", &z); while (c<z){ getchar(); scanf("%[^\n]", &A); half = strlen(A) / 2; for (i=0, j=half-1; i<=half; i++, j--) { B[i] = A[j]; } for (i=half, j=strlen(A)-1; i<strlen(A); i++, j--) { B[i] = A[j]; } for (i=0; i<strlen(A); i++) { printf("%c", B[i]); } printf("\n"); c++; } }
true
307f57d1c355e4c347ba6db4ab46a3fe72bcf864
C++
beneills/motion
/src/timer.cpp
UTF-8
1,236
2.828125
3
[]
no_license
#include <assert.h> #include <iostream> #include <sys/time.h> #include <SDL2/SDL.h> #include <timer.hpp> long long int Timer::ms_since_epoch() { struct timeval tp; gettimeofday(&tp, NULL); return tp.tv_sec * 1000 + tp.tv_usec / 1000; } void Timer::start() { assert( this->start_ms == -1 ); this->start_ms = this->ms_since_epoch(); } unsigned int Timer::stop() { assert( this->start_ms != -1 ); unsigned int elapsed = this->elapsed_ms(); this->start_ms = -1; return elapsed; } unsigned int Timer::elapsed_ms() { assert( this->start_ms != -1 ); return this->ms_since_epoch() - this->start_ms; } unsigned int Timer::ms_since_last_frame() { assert( this->start_ms != -1 ); return this->elapsed_ms() - this->last_frame_ms; } unsigned int Timer::seconds() { return this->elapsed_ms() / 1000; } void Timer::limit(unsigned int max_fps) { assert( this->start_ms != -1 ); unsigned int min_ms_per_frame = 1000 / max_fps; this->tick(); int to_wait_ms = min_ms_per_frame - ms_since_last_frame(); if ( to_wait_ms > 0 ) { SDL_Delay(to_wait_ms); } } void Timer::tick() { this->last_frame_ms = this->elapsed_ms(); } Timer::Timer() { this->start_ms = -1; this->last_frame_ms = -1; }
true
62cdbc0fe065bf549ebcff43e6b427d135df5c7a
C++
brandonq2/Robot-Code
/3-FlameCode/3-FlameCode.ino
UTF-8
1,996
3.1875
3
[]
no_license
// Libraries Needed #include <Servo.h> #include <Wire.h> // Motor Variables const int rightMotor = 6; const int leftMotor = 5; const int rightRelay = 4; const int leftRelay = 7; // Flame Sensor Vairables const int flameSensorLeft = A0; const int flameSensorMid = A1; const int flameSensorRight = A2; int flameValueLeft = 0; int flameValueMid = 0; int flameValueRight = 0; void setup() { // Basic setup Serial.begin(9600); // Motor pin modes and starting values pinMode(leftMotor, INPUT); pinMode(rightMotor, INPUT); pinMode(leftRelay, OUTPUT); pinMode(rightRelay, OUTPUT); digitalWrite(rightMotor, HIGH); // Robot starts off not moving digitalWrite(leftMotor, HIGH); digitalWrite(rightRelay, HIGH); // One is opposite because the motor is flipped digitalWrite(leftRelay, LOW); } void loop() { flameValueLeft = analogRead(flameSensorLeft); flameValueMid = analogRead(flameSensorMid); flameValueRight = analogRead(flameSensorRight); Serial.println(flameValueLeft); if (flameValueLeft < 700 || flameValueMid < 700 || flameValueRight < 700){ stopMotors(); } else if(flameValueLeft < 850){ slightTurnLeft(); Serial.println("Left"); } else if (flameValueRight < 850){ slightTurnRight(); Serial.println("Right"); } } // Movement Functions void slightTurnLeft(){ digitalWrite(rightMotor, HIGH); // Robot starts off not moving digitalWrite(leftMotor, HIGH); digitalWrite(leftRelay, HIGH); delay(80); digitalWrite(leftRelay, LOW); //digitalWrite(rightMotor, LOW); // Robot starts off not moving //digitalWrite(leftMotor, LOW); } void slightTurnRight(){ digitalWrite(rightMotor, HIGH); // Robot starts off not moving digitalWrite(leftMotor, HIGH); digitalWrite(rightRelay, LOW); delay(80); digitalWrite(rightRelay, HIGH); //digitalWrite(rightMotor, LOW); // Robot starts off not moving //digitalWrite(leftMotor, LOW); } void stopMotors(){ digitalWrite(leftMotor, LOW); digitalWrite(rightMotor, LOW); }
true
b2d5909a9415f23c8316ffe5a3b864bb7a94df5c
C++
Colo1396/Gestion-de-Stock
/TDA Camiones Tpv4/main.cpp
ISO-8859-2
1,769
2.609375
3
[]
no_license
#include <iostream> #include "Solicitud.h" #include "Reposicion.h" #include "Camion.h" #include <cstdlib> #include <stdio.h> #include <conio.h> #include <string> #include <time.h> #include <cstring> #include <iostream> #include <stdlib.h> #include <ctype.h> #include "FunnyProd.h" using namespace std; int main() { FILE *ptrING; //Puntero de archivo INGRESO. FILE *ptrSOL; //Puntero de archivo SOLICITUDES. ptrING=fopen("ingresos.db","r"); // LOS ABRIMOS EN EL MAIN PARA CERRARLOS ptrSOL=fopen("solicitudes.db","r"); // DENTRO DEL MISMO. //A modo de prueba, leemos la primer linea de cada archivo. correr(ptrING,ptrSOL); correr(ptrING,ptrSOL); correr(ptrING,ptrSOL); correr(ptrING,ptrSOL); correr(ptrING,ptrSOL); correr(ptrING,ptrSOL); correr(ptrING,ptrSOL); correr(ptrING,ptrSOL); correr(ptrING,ptrSOL); correr(ptrING,ptrSOL); correr(ptrING,ptrSOL); correr(ptrING,ptrSOL); correr(ptrING,ptrSOL); correr(ptrING,ptrSOL); correr(ptrING,ptrSOL); correr(ptrING,ptrSOL); correr(ptrING,ptrSOL); correr(ptrING,ptrSOL); correr(ptrING,ptrSOL); correr(ptrING,ptrSOL); correr(ptrING,ptrSOL); correr(ptrING,ptrSOL); correr(ptrING,ptrSOL); correr(ptrING,ptrSOL); correr(ptrING,ptrSOL); correr(ptrING,ptrSOL); correr(ptrING,ptrSOL); correr(ptrING,ptrSOL); correr(ptrING,ptrSOL); correr(ptrING,ptrSOL); correr(ptrING,ptrSOL); correr(ptrING,ptrSOL); correr(ptrING,ptrSOL); correr(ptrING,ptrSOL); correr(ptrING,ptrSOL); //Repetimos el paso para ver que pas. fclose(ptrING);// CERRAMOS LOS ARCHIVOS AL FINAL DEL PROGRAMA fclose(ptrSOL);// CERRAMOS LOS ARCHIVOS AL FINAL DEL PROGRAMA return EXIT_SUCCESS; }
true
d29df33c23c3f5ae1d098a0859807ee08e295cc1
C++
omelove20/ff
/ทดลองครั้งที่7.1.cpp
UTF-8
768
3.015625
3
[]
no_license
#include <stdio.h> int num_arr1,num_arr2,num_arr3,arr1[5],arr2[5],arr3[10]; fung_arr1(){ for(int i=0;i<=num_arr1-1;i++){ printf("arr1[%d] : ",i); scanf("%d",&arr1[i]); }} fung_arr2(){ for(int i=num_arr1;i<=num_arr3-1;i++){ printf("arr2[%d] : ",i); scanf("%d",&arr1[i]); }} fung_arr3(){ printf("Input Count = %d\n",num_arr3); for(int i=0;i<=num_arr3-1;i++){ arr3[i]=arr1[i]+arr2[i]; printf("Merge[%d] = %d \n",i,arr3[i]); }} int main() { printf("Please Enter Index Array : "); scanf("%d",&num_arr1); printf("Please Enter Index Array : "); scanf("%d",&num_arr2); num_arr3=num_arr1+num_arr2; printf("\n"); fung_arr1(); printf("\n"); fung_arr2(); printf("\n"); fung_arr3(); }
true
3e5a6d16f056237d0aaea42881e96d5c4ab2e88b
C++
Vaa3D/vaa3d_tools
/bigneuron_ported/erhan/PSF_tracing/functions/MatrixMultiplication.cpp
UTF-8
4,553
3.203125
3
[ "MIT" ]
permissive
/* C++ IMPLEMENTATION OF PRINCIPAL CURVE TRACING USING MEX INTERFACE Code developed by: Nikhila Srikanth M.S. Project Cognitive Systems Laboratory Electrical and Computer Engineering Department Northeastern University, Boston, MA Under the guidance of: Prof. Deniz Erdogmus and Dr. Erhan Bas Date Created: Jan 20, 2011 Date Last Updated: April 29, 2011 This code performs matrix multiplication in C. This code is meant to run on the Windows platform */ #include <math.h> #include "MatrixMultiplication.h" #define ROWCOL(row,col,tot_rows) (row + col*tot_rows) //pdInput1[ROWCOL(2,1,20)] #define TRUE 1 #define FALSE 0 double *Matrix_Multiply(double *pdInput1, double *pdInput2, int iRows_Input1, int iCols_Input1, int iRows_Input2, int iCols_Input2, bool bUse_Transpose_of_Inp_2) { int iSwapVar; double dProduct; if (bUse_Transpose_of_Inp_2 == TRUE) { iSwapVar = iRows_Input2; iRows_Input2 = iCols_Input2; iCols_Input2 = iSwapVar; } //A --> 10x20 //B --> 40x20 // When taking transpose, B becomes 20x40 //AB` --> 10x40 if(iCols_Input1 != iRows_Input2) { printf("\n Error:Matrix dimensions mismatch for multiplication"); exit (1); } double *pdOutput = new double[iRows_Input1*iCols_Input2]; int iIter_i, iIter_j, iIter_k; for(iIter_i = 0; iIter_i < iRows_Input1; iIter_i++) // 0 { for(iIter_j = 0; iIter_j < iCols_Input2; iIter_j++) // 39 { dProduct = 0; for(iIter_k = 0; iIter_k < iRows_Input2; iIter_k++) // 0 to start with.. { //dProduct += pdInput1[iIter_i + iIter_k*iRows_Input1] * pdInput2[iIter_k + iIter_j*iRows_Input2]; if (bUse_Transpose_of_Inp_2 == TRUE) { dProduct += pdInput1[ROWCOL(iIter_i, iIter_k, iRows_Input1)] * pdInput2[ROWCOL(iIter_j, iIter_k, iCols_Input2)]; } else { dProduct += pdInput1[ROWCOL(iIter_i, iIter_k, iRows_Input1)] * pdInput2[ROWCOL(iIter_k, iIter_j, iRows_Input2)]; } } pdOutput[ROWCOL(iIter_i, iIter_j, iRows_Input1)] = dProduct; } } // A:[10x20] B:[20x40] -- P = AB // to generate: P(1,1) --> a(1,1)*b(1,1) + a(1,2)*b(2,1) ...... a(1,20)*b(20,1) // P(1,40) --> a(1,1)*b(1,40) + a(1,2)*b(2,40) ....... a(1,20)*b(20,40) // A:[10x20] B:[40x20] -- P = AB` // iRows_Input2 = 20, iCols_Input2 = 40 // to generate: P(1,1) --> a(1,1)*b(1,1) + a(1,2)*b(1,2) ...... a(1,20)*b(1,20) // P(1,40) --> a(1,1)*b(40,1) + a(1,2)*b(40,2) ....... a(1,20)*b(40,20) return pdOutput; } void Int_Mat_Multiply(int *piInput1, int *piInput2, int iRows_Input1, int iCols_Input1, int iRows_Input2, int iCols_Input2, int **ppiOutput) { int iProduct; if(iCols_Input1 != iRows_Input2) { printf("\n Error:Matrix dimensions mismatch for multiplication"); exit (1); } *ppiOutput = (int*) malloc (iRows_Input1*iCols_Input2*sizeof(int)); int iIter_i, iIter_j, iIter_k; for(iIter_i = 0; iIter_i < iRows_Input1; iIter_i++) // 0 { for(iIter_j = 0; iIter_j < iCols_Input2; iIter_j++) // 39 { iProduct = 0; for(iIter_k = 0; iIter_k < iRows_Input2; iIter_k++) // 0 to start with.. { iProduct += piInput1[ROWCOL(iIter_i, iIter_k, iRows_Input1)] * piInput2[ROWCOL(iIter_k, iIter_j, iRows_Input2)]; } *ppiOutput[ROWCOL(iIter_i, iIter_j, iRows_Input1)] = iProduct; } } // A:[10x20] B:[20x40] -- P = AB // to generate: P(1,1) --> a(1,1)*b(1,1) + a(1,2)*b(2,1) ...... a(1,20)*b(20,1) // P(1,40) --> a(1,1)*b(1,40) + a(1,2)*b(2,40) ....... a(1,20)*b(20,40) } void Double_Mat_Multiply(double *pdInput1, double *pdInput2, int iRows_Input1, int iCols_Input1, int iRows_Input2, int iCols_Input2, double *pdOutput) { double dProduct; if(iCols_Input1 != iRows_Input2) { printf("\n Error:Matrix dimensions mismatch for multiplication"); exit (1); } int iIter_i, iIter_j, iIter_k; for(iIter_i = 0; iIter_i < iRows_Input1; iIter_i++) // 0 { for(iIter_j = 0; iIter_j < iCols_Input2; iIter_j++) // 39 { dProduct = 0; for(iIter_k = 0; iIter_k < iRows_Input2; iIter_k++) // 0 to start with.. { dProduct += pdInput1[ROWCOL(iIter_i, iIter_k, iRows_Input1)] * pdInput2[ROWCOL(iIter_k, iIter_j, iRows_Input2)]; } pdOutput[ROWCOL(iIter_i, iIter_j, iRows_Input1)] = dProduct; } } // A:[10x20] B:[20x40] -- P = AB // to generate: P(1,1) --> a(1,1)*b(1,1) + a(1,2)*b(2,1) ...... a(1,20)*b(20,1) // P(1,40) --> a(1,1)*b(1,40) + a(1,2)*b(2,40) ....... a(1,20)*b(20,40) }
true
4cba9f2f6caceeba159ad8a837268fb89f458d13
C++
SeaCanFly/CODE
/Study/Data struct/HomeWork/hw4/hw4_3/hw4_3/hw4_3.cpp
UTF-8
1,033
3.296875
3
[]
no_license
#include<stdio.h> typedef struct Node { int data; Node* next; Node(Node* pnode, int i_data) { data = i_data; next = pnode; } }Node; typedef struct List { Node* phead; List(int num) { phead = nullptr; Node* ptail = nullptr; int i = 1; while (num>=0) { phead = new Node(phead, num); if (i) { ptail = phead; i = 0; } num--; } ptail->next = phead; } void showList() { Node* p = phead; do{ printf("%p:%d,%p\n", p, p->data, p->next); p = p->next; } while (p != phead); printf("\n"); } ~List() { Node* p = phead; Node* c = phead; do{ p = p->next; printf("del:%p\n",phead); delete phead; phead = p; } while (phead != c); } }List; Node* search(List* plist, int data) { Node* head = plist->phead; Node* current = head->next; head->data = data; while (current->data!=data) { current = current->next; } return ((current == head) ? nullptr : current); } int main() { List a(2); a.showList(); printf("%p\n", search(&a, 4)); return 0; }
true
ccec949cfa29022099aaab21d13715b52d7b0de7
C++
rmmcosta/CppForCprogrammers
/Part A/week 1/sizes.cpp
UTF-8
277
2.65625
3
[]
no_license
#include "unitTestFramework.hpp" #include <iostream> using namespace std; template <class T> inline int length(T theArray[]) { return sizeof(theArray)/sizeof(T); } /*int main() { int nums[] = {1,3,4,5}; cout << "test passed: " << assertTrue(4, length(nums)); }*/
true
86fc67539dc688adb3edc96510570dfe5511d373
C++
John-Ad/Dijkstras-algorithm-implementation
/Source.cpp
UTF-8
8,755
3.234375
3
[]
no_license
#include <iostream> #include <vector> #define INF 999 using namespace std; //adjacency list graph implementation for a grid based graph //stores only the adjacent vertices of each vertex class graph { private: struct vertex { char v; bool visited; int distFromSrc; vertex* prev; }; struct adjVert { char v; int weight; }; vector<vertex> vertices; vector<vector<adjVert>> adjList; int vertSize; public: graph(char verts[], int nVerts) { vertSize = nVerts; vertex v; v.visited = false; v.distFromSrc = INF; v.prev = NULL; for (int i = 0; i < nVerts; i++) { v.v = verts[i]; vertices.push_back(v); } } void createEdges(int x) { // refer to a drawn grid consisting of 15 vertices to help understand the algorithm int xHolder{ x - 1 }; adjVert v; int weight = 1; int upW = 8; //controls weights for upwards edges int leftW = 2; //controls weights for leftwards edges for (int i = 0; i < vertices.size(); i++) { adjList.push_back(vector<adjVert>()); } for (int i = 0; i < adjList.size(); i++) // refer to a drawn grid when working through this algorithm { for (int e = 0; e < adjList.size(); e++) { if (e == i + 1 && i != xHolder) // links a vertex to the one to the right of it { v.v = vertices[e].v; v.weight = weight; adjList[i].push_back(v); weight += 1; } else if (e == i - 1 && e != xHolder) // links a vertex to the one to the left of it { if (i > vertSize - x) leftW = 1; v.v = vertices[e].v; v.weight = (weight - leftW); adjList[i].push_back(v); } else if (e == i + x) //links a vertex to the one under it { v.v = vertices[e].v; v.weight = weight; adjList[i].push_back(v); weight += 1; } else if (e == i - x) //links a vertext to the one above it { v.v = vertices[e].v; if (e == xHolder) //refer to a drawn 5x3 grid v.weight = (weight - upW) - 1; else v.weight = weight - upW; adjList[i].push_back(v); } if (e == xHolder + 1) //xholder signals the end of a row. Doubling it moves the algorithm to the next row { xHolder += 5; } } if (i >= vertSize - x) //changing upW in the e loop does not correctly decrease the variable upW -= 1; leftW = 2; xHolder = x - 1; } } int adjIndices(int v, vector<int>& adjInd) { if (adjInd.size() > 0) adjInd.clear(); for (int i = 0; i < adjList[v].size(); i++) { //cout << adjList[v][i].v << ", " << adjList[v][i].weight << endl; for (int e = 0; e < vertices.size(); e++) { if (adjList[v][i].v == vertices[e].v) adjInd.push_back(e); } } return adjInd.size(); } int adjEdges(int e, vector<adjVert>& adjEdg) { if (adjEdg.size() > 0) adjEdg.clear(); for (int i = 0; i < adjList[e].size(); i++) { adjEdg.push_back(adjList[e][i]); } return adjEdg.size(); } void shortestPath(int start, int end_) { int shortestDist = INF; int nextVert = INF; bool doneVisiting = false; vector<int>adjInd; vector<adjVert>adjEdg; vector<vertex>path; int currentVert = start; vertices[currentVert].distFromSrc = 0; do { adjIndices(currentVert, adjInd); adjEdges(currentVert, adjEdg); for (int i = 0; i < adjInd.size(); i++) { if (vertices[currentVert].distFromSrc + adjEdg[i].weight < vertices[adjInd[i]].distFromSrc) { vertices[adjInd[i]].distFromSrc = vertices[currentVert].distFromSrc + adjEdg[i].weight; vertices[adjInd[i]].prev = &vertices[currentVert]; } } for (int i = 0; i < 15; i++) { if (vertices[i].distFromSrc != INF) { if (vertices[i].visited == false && vertices[i].distFromSrc < shortestDist) { shortestDist = vertices[i].distFromSrc; nextVert = i; } } } vertices[currentVert].visited = true; shortestDist = INF; if (nextVert != INF) { currentVert = nextVert; nextVert = INF; } else doneVisiting = true; } while (!doneVisiting); //display path path.push_back(vertices[end_]); while (path[path.size() - 1].prev != NULL) { path.push_back(*path[path.size() - 1].prev); } for (int i = path.size() - 1; i >= 0; i--) { cout << path[i].v << endl; } } }; int main() { char verts[] = "ABCDEFGHIJKLMNO"; graph g(verts, 15); // 15 is the number of vertices g.createEdges(5); // 5 is the width. This specific graph will therefore be 5x3 in size g.shortestPath(10, 14); // eg 3=C, 11=L cin.get(); return 0; } /* //adjacency matrix unweighted graph implementation for a 5x3 grid class graph { private: vector<char> vertex; vector<vector<bool>> edge; public: graph(char verts[],int nVerts) { for (int i = 0; i < nVerts; i++) { vertex.push_back(verts[i]); } } void createEdges(int x) { int xHolder{ x - 1 }; for (int i = 0; i < vertex.size(); i++) { edge.push_back(vector<bool>()); for (int e = 0; e < vertex.size(); e++) { edge[i].push_back(false); } } for (int i = 0; i < edge.size(); i++) // refer to a drawn grid when working through this algorithm { for (int e = 0; e < edge[i].size(); e++) { if (e == i + 1 && i != xHolder) // links a vertex to the one to the right of it { edge[i][e] = true; } else if (e == i - 1 && e != xHolder) // links a vertex to the one to the left of it { edge[i][e] = true; } else if (e == i + x) //links a vertex to the one under it { edge[i][e] = true; } else if (e == i - x) //links a vertext to the one above it { edge[i][e] = true; } if (e == xHolder + 1) //xholder signals the end of a row. Doubling it moves the algorithm to the next row { xHolder = ((xHolder + 1) * 2) - 1; } } xHolder = x - 1; } } void adjVerts(int vert) { for (int i = 0; i < edge[vert].size(); i++) { if (edge[vert][i] == true) { cout << vertex[i] << endl; } } } }; int main() { char verts[] = "ABCDEFGHIJKLMNO"; graph g(verts, 15); g.createEdges(5); g.adjVerts(7); cin.get(); return 0; } */ /* class vertexList { private: vector<char> vertex; public: void insert(char& e) { vertex.push_back(e); } char operator[](int i) { return vertex[i]; } void display() { for (int i = 0; i < vertex.size(); i++) { cout << vertex[i] << endl; } } }; class edgeList { public: struct edge { char vert1; char vert2; }; void insert(char& v1, char& v2) { edges.push_back(edge()); edges[edges.size() - 1].vert1 = v1; edges[edges.size() - 1].vert2 = v2; } void incidentEdges(vector<edge>& eList, char& vert) { for (int i = 0; i < edges.size(); i++) { if (edges[i].vert1 == vert || edges[i].vert2 == vert) { eList.push_back(edges[i]); } } } bool isAdjacent(char& v1, char& v2) { for (int i = 0; i < edges.size(); i++) { if (edges[i].vert1 == v1 && edges[i].vert2 == v2) { return true; } if (edges[i].vert2 == v1 && edges[i].vert1 == v2) { return true; } } return false; } void endVerts(vector<char>& verts, int i) { verts.push_back(edges[i].vert1); verts.push_back(edges[i].vert2); } void display() { for (int i = 0; i < edges.size(); i++) { cout << "{" << edges[i].vert1 << "," << edges[i].vert2 << "}" << endl; } } private: vector<edge> edges; }; class graph { private: char vertices[5]{ 'A','B','C','D','E' }; vertexList vList; edgeList eList; vector<edgeList::edge> incEdges; public: graph() { for (int i = 0; i < 5; i++) { vList.insert(vertices[i]); } for (int i = 0; i < 4; i++) { eList.insert(vertices[i], vertices[i + 1]); } vList.display(); eList.display(); } void isAdj(int v1, int v2) { cout << eList.isAdjacent(vertices[v1], vertices[v2]) << endl << endl; } void iEdges(int vert){ eList.incidentEdges(incEdges, vertices[vert]); for (int i = 0; i < incEdges.size(); i++) { cout << "{" << incEdges[i].vert1 << "," << incEdges[i].vert2 << "}" << endl; } } void endVerts(int e) { vector<char>verts; eList.endVerts(verts, e); for (int i = 0; i < verts.size(); i++) { cout << verts[i] << endl; } } }; int main() { graph g; g.isAdj(0, 4); g.iEdges(4); g.endVerts(3); cin.get(); return 0; } */
true
d2649d563ac3c54548a55bc581e6cf83cc4e6a23
C++
chhetri28/LPU_workshop
/Day-5/seive.cpp
UTF-8
711
2.875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; const int N = 100; vector<int> primes; void seive() { p[0] = p[1] = 0; vector<bool> p(N, 1); for (int i = 2; i < N; i++) { if (p[i] == 0) continue; // it has to be a prime number if (p[i] == 1) primes.push_back(i); // cancel out all the multiples if i for (int j = i * i; j < N; j += i) { p[j] = 0; } } } int main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif // code seive(); // for (auto x : primes) { // cout << x << '\n'; // } // if (binary_search(primes.begin(), primes.end(), n)) cout << "Yes"; // else cout << "No"; }
true
44e7480c53e5216dd3295b289c5ec3b1a97f72ee
C++
LapusteB/StronglyConnectedComponets
/digraphMatrix.h
UTF-8
1,128
2.828125
3
[]
no_license
#ifndef __DIGRAPH_MATRIX_H #define __DIGRAPH_MATRIX_H #include <string> #include <stack> #include <unordered_map> #include <vector> using namespace std; enum mark_t { UNDISCOVERED, DISCOVERED, EXPLORED }; class DigraphMatrix { private: int e, v; vector<vector<bool>> a; stack<int> s; vector<vector<bool>> z; unordered_map<int,int> ID; public: //Reads in digraph from given file //Stores graph as an adjacency matrix DigraphMatrix(const string&); void DFS (const int& start, unordered_map<int, mark_t>& marks); void recDFS (int& start); void SecondDFS(const int& start, unordered_map<int, mark_t>& marks, int count, vector<int> &r); void recSecondDFS( int& start); vector<int> GetOutNeighbors (const int& v1); vector<int> GetOutNeighbors2 (const int& v1); void ReverseEdges(); //Returns number of vertices int getOrder() const { return v; } vector<vector<bool>> getMatrix() const {return a;} stack<int> getStack() const {return s;} //Returns vector containing component ID for each vertex vector<int> stronglyConnectedComponents(); }; #endif
true
bd4708c7be2077b4e19742ff3c8fca622e159bb0
C++
Koios1143/Algorithm-Code-Saved
/template/AC_machine.cpp
UTF-8
763
2.734375
3
[]
no_license
//By Koios1143 #include<bits/stdc++.h> using namespace std; const int Max = 26; struct Node{ Node *child[Max]; int fail; Node(){ for(int i=0 ; i<Max ; i++){ child[i]=NULL; } fail=-1; } }; struct Trie{ Node *root; void init(){ for(int i=0 ; i<Max ; i++){ root->child[i] = NULL; } } void build(const string &s){ Node *cur=root; for(char c : s){ if(cur->child[(int)c] == NULL){ cur->child[(int)c] = new Node(); } cur=cur->child[(int)c]; } } void build_fail(){ Node *cur = root; queue<int> q; for(int i=0 ; i<Max ; i++){ if(cur->child[i]!=NULL){ q.push(cur->child[i]); } } while(!q.empty()){ } } }; int main(){ return 0; }
true
2447661ed1145aea3ef4fad68b37f64369b5342d
C++
Gaurav3435/CPP-Practice
/constructor-in-derived-class.cpp
UTF-8
837
3.765625
4
[]
no_license
#include<iostream> using namespace std; class base1 { int data1; public: base1(int i) { data1=i; } void printbase1() { cout<<"The value in base1 is: "<<data1<<endl; } }; class base2 { int data2; public: base2(int i) { data2=i; } void printbase2() { cout<<"The value in base1 is: "<<data2<<endl; } }; class base3:public base1,public base2 { int data3; public: base3(int a,int b,int c):base1(a),base2(b) { data3=c; } void printbase3() { cout<<"The value in base1 is: "<<data3<<endl; } }; int main() { base3 b(1,2,3); b.printbase1(); b.printbase2(); b.printbase3(); return 0; }
true
e01b944064735f958fddce10d44af269000768be
C++
Kaermor/stepik-course363-cpp
/1-7-5z.cpp
UTF-8
342
2.671875
3
[ "Apache-2.0" ]
permissive
// // Created by grey on 18.10.2019. // #include <iostream> #include <vector> using namespace std; void foo_1_7_5z(){ int n, sh = 0; cin >> n; vector<int> a(n); //input, processing for (int i = 0; i < n; i++){ cin >> a[i]; if (a[i] > 0){ sh++; } } //output cout << sh; }
true
1d00987c8ba05d23645cab9d7a8ef894baf8fa26
C++
PimentaMateus/ProjetosArduino
/Carro/car_com_controle_para_liga/car_com_controle_para_liga.ino
UTF-8
882
2.78125
3
[]
no_license
int fPinA = 2; // Forward for motor A (left) int rPinA = 3; // Reverse for motor A (Left) int toggleA = 9; // Turns motor A on/off int fPinB = 4; // Forward for motor B (Right) int rPinB = 5; // Reverse for motor B (Right) int toggleB = 10; // Turns motor B on/off void setup() { pinMode( fPinA, OUTPUT ); pinMode( rPinA, OUTPUT ); pinMode( toggleA, OUTPUT ); pinMode( fPinB, OUTPUT ); pinMode( rPinB, OUTPUT ); pinMode( toggleB, OUTPUT ); } void loop() { digitalWrite( toggleA, HIGH ); // Turns motor A on digitalWrite( fPinA, HIGH ); // Makes motor A go forward digitalWrite( rPinA, LOW ); // Reverse not used digitalWrite( toggleB, HIGH ); // Turns motor B on digitalWrite( fPinB, HIGH ); // Makes motor B go forward digitalWrite( rPinB, LOW ); // Reverse not used }
true
f4fe76fe83086ba591aed61d2228f0af75f66e9d
C++
thegamer1907/Code_Analysis
/DP/420.cpp
UTF-8
488
2.828125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int main() { int b,g; cin>>b; int *boys = new int[b]; for (int i = 0; i < b; i++){ cin>>boys[i]; } cin>>g; int* girls = new int[g]; for (int i = 0; i < g; i++){ cin>>girls[i]; } int i = 0,j = 0,pairs = 0; sort(boys,boys+b); sort(girls,girls+g); while (i < b && j < g){ if (boys[i] < girls[j]-1){ i++; }else if (boys[i] > girls[j]+1){ j++; }else{ pairs++; i++; j++; } } cout<<pairs<<endl; return 0; }
true
14194d0f4f73d5285fc6b05f2102925126c848ee
C++
PradipBaral022/Cpp_Projects
/Lab_Works/Lab_1(AreaOfTriangle)/Simple_Method/areaOfTriangle_2.cpp
UTF-8
406
3.46875
3
[]
no_license
#include <iostream> #include <conio.h> #include <math.h> using namespace std; int main() { float base, height, areaOfTriangle; cout << "Enter the base of the triangle:"; cin >> base; cout << "Enter the height of the triangle:"; cin >> height; areaOfTriangle = 0.5 * (base * height); cout << "The area of the right angled triangle is:" << areaOfTriangle << endl; return 0; }
true
d249295e37fd3143d0e0002c40d4eb0cd8dd41f7
C++
FeniksComputerClub/montecarlo
/src/design.cxx
UTF-8
13,054
2.859375
3
[]
no_license
#include "sys.h" #include "debug.h" #include "utils/MultiLoop.h" #include "statefultask/AIStatefulTask.h" #include "statefultask/AIEngine.h" //=========================================================================== // Task struct Task : public AIStatefulTask { private: bool m_do_finish; protected: // The base class of this task. using direct_base_type = AIStatefulTask; // The different states of the task. enum design_state_type { Task_start = direct_base_type::max_state, Task_done, }; public: static state_type const max_state = Task_done + 1; // One beyond the largest state. public: // The derived class must have a default constructor. Task(); protected: // The destructor must be protected. /*virtual*/ ~Task(); protected: // The following virtual functions must be implemented: // Return human readable string for run_state. /*virtual*/ char const* state_str_impl(state_type run_state) const; // Handle initializing the object. /*virtual*/ void initialize_impl(); // Handle mRunState. /*virtual*/ void multiplex_impl(state_type run_state); // Handle aborting from current bs_multiplex state (the default AIStatefulTask::abort_impl() does nothing). /*virtual*/ void abort_impl() { } // Handle cleaning up from initialization (or post abort) state (the default AIStatefulTask::finish_impl() does nothing). /*virtual*/ void finish_impl() { } public: // Cause task to finish. void do_finish() { m_do_finish = true; signal(1); gMainThreadEngine.mainloop(); } }; Task::Task() : AIStatefulTask(true), m_do_finish(false) { } Task::~Task() { } char const* Task::state_str_impl(state_type run_state) const { switch(run_state) { AI_CASE_RETURN(Task_start); AI_CASE_RETURN(Task_done); } return "UNKNOWN"; } void Task::initialize_impl() { set_state(Task_start); } void Task::multiplex_impl(state_type run_state) { switch(run_state) { case Task_start: if (!m_do_finish) { wait(1); break; } set_state(Task_done); /*fall-through*/ case Task_done: finish(); break; } } //=========================================================================== // class Inserter : public MultiLoop { private: int m_i; // Runs over elements of tasks when calling add(). int m_N; // The number of tasks / for loops. int m_M; // The number of times insert will be called per inner loop. std::vector<boost::intrusive_ptr<Task>*> tasks; // N is size of this vector. public: Inserter(int n, int m) : MultiLoop(n), m_i(0), m_N(n), m_M(m), tasks(n) { } void add(boost::intrusive_ptr<Task>* task) { ASSERT(m_i < m_N); tasks[m_i++] = task; } int insert(int m) const; int number_of_insertions_at(int m); }; int Inserter::insert(int m) const { int finished = 0; for (int task = 0; task < m_N; ++task) if ((*this)[task] == m) { (*tasks[task])->do_finish(); ++finished; } return finished; } int Inserter::number_of_insertions_at(int m) { int count = 0; for (int task = 0; task < m_N; ++task) count += ((*this)[task] == m) ? 1 : 0; return count; } //=========================================================================== // TestSuite struct TestSuite final : public Task { protected: // The base class of this task. using direct_base_type = Task; // The different states of the task. enum design_state_type { Test1 = direct_base_type::max_state, Test2, Test3, Test4, Test5, Test6, Test7, Test8 }; public: static state_type const max_state = Test8 + 1; // One beyond the largest state. void test1(); void test2(); void test3(); void test4(); void test5(); void test6(); void test7(); void test8(); private: int m_run_test; public: boost::intrusive_ptr<Task> task1; boost::intrusive_ptr<Task> task2; boost::intrusive_ptr<Task> task3; boost::intrusive_ptr<Task> task4; void run_test(int test); TestSuite() : task1(new Task), task2(new Task), task3(new Task), task4(new Task) { } protected: /*virtual*/ ~TestSuite() { task1.reset(); task2.reset(); task3.reset(); task4.reset(); } /*virtual*/ char const* state_str_impl(state_type run_state) const; /*virtual*/ void initialize_impl(); /*virtual*/ void multiplex_impl(state_type run_state); }; char const* TestSuite::state_str_impl(state_type run_state) const { switch(run_state) { AI_CASE_RETURN(Test1); AI_CASE_RETURN(Test2); AI_CASE_RETURN(Test3); AI_CASE_RETURN(Test4); AI_CASE_RETURN(Test5); AI_CASE_RETURN(Test6); AI_CASE_RETURN(Test7); AI_CASE_RETURN(Test8); } ASSERT(run_state < direct_base_type::max_state); return direct_base_type::state_str_impl(run_state); } int main() { Debug(NAMESPACE_DEBUG::init()); boost::intrusive_ptr<TestSuite> testsuite; testsuite = new TestSuite; testsuite->run_test(1); testsuite.reset(); testsuite = new TestSuite; testsuite->run_test(2); testsuite.reset(); testsuite = new TestSuite; testsuite->run_test(3); testsuite.reset(); testsuite = new TestSuite; testsuite->run_test(4); testsuite.reset(); testsuite = new TestSuite; testsuite->run_test(5); testsuite.reset(); testsuite = new TestSuite; testsuite->run_test(6); testsuite.reset(); testsuite = new TestSuite; testsuite->run_test(7); testsuite.reset(); testsuite = new TestSuite; testsuite->run_test(8); testsuite.reset(); } void TestSuite::run_test(int test) { m_run_test = test; run(); } void TestSuite::initialize_impl() { set_state(Test1 + m_run_test - 1); } void TestSuite::multiplex_impl(state_type run_state) { switch(run_state) { case Test1: test1(); break; case Test2: test2(); break; case Test3: test3(); break; case Test4: test4(); break; case Test5: test5(); break; case Test6: test6(); break; case Test7: test7(); break; case Test8: test8(); break; } abort(); } //=========================================================================== // The actual tests. void TestSuite::test1() { DoutEntering(dc::notice, "TestSuite::test1()"); ASSERT(running()); // We are running. task1->run(this, 2); // Start one task. gMainThreadEngine.mainloop(); ASSERT(!*task1); // Task 1 is not finished (is still going to call the callback). ASSERT(!waiting()); // We are not idle. wait(2); // Go idle. ASSERT(waiting()); // We are idle. task1->do_finish(); // Task 1 finishes. ASSERT(*task1); // Task 1 is finished. ASSERT(!waiting()); // We are again not idle. } void TestSuite::test2() { DoutEntering(dc::notice, "TestSuite::test2()"); ASSERT(running()); // We are running. task1->run(this, 2); // Start one task. gMainThreadEngine.mainloop(); task1->do_finish(); // Task 1 finishes. ASSERT(*task1); // Task 1 is finished. ASSERT(running() && !waiting()); // We are running. wait(2); // Go idle. ASSERT(running() && !waiting()); // Still running. ASSERT(*task1); // Task 1 is finished. } void TestSuite::test3() { DoutEntering(dc::notice, "TestSuite::test3()"); task1->run(this, 2); // Start two tasks. task2->run(this, 4); gMainThreadEngine.mainloop(); ASSERT(running() && !waiting()); ASSERT(!*task1 && !*task2); // Neither task is finished. wait(2); // Go idle. ASSERT(waiting()); task1->do_finish(); // Task 1 finishes. ASSERT(*task1 && !*task2); // Task 1 is finished, task 2 isn't. wait(4); // Go idle. ASSERT(waiting()); task2->do_finish(); // Task 2 finishes. ASSERT(*task1 && *task2); // Both tasks finished. } void TestSuite::test4() { DoutEntering(dc::notice, "TestSuite::test4()"); task1->run(this, 2); // Start two tasks. task2->run(this, 4); gMainThreadEngine.mainloop(); wait(2); // Go idle. ASSERT(waiting()); task1->do_finish(); // Task 1 finishes. task2->do_finish(); // Task 2 finishes. wait(4); // Go idle. ASSERT(running() && !waiting()); } void TestSuite::test5() { DoutEntering(dc::notice, "TestSuite::test5()"); task1->run(this, 2); // Start two tasks. task2->run(this, 4); gMainThreadEngine.mainloop(); task1->do_finish(); // Task 1 finishes. wait(2); // Go idle. ASSERT(running() && !waiting()); wait(4); // Go idle. ASSERT(waiting()); task2->do_finish(); // Task 2 finishes. } void TestSuite::test6() { DoutEntering(dc::notice, "TestSuite::test6()"); task1->run(this, 2); // Start two tasks. task2->run(this, 4); gMainThreadEngine.mainloop(); task1->do_finish(); // Task 1 finishes. wait(2); // Go idle. ASSERT(running() && !waiting()); task2->do_finish(); // Task 2 finishes. wait(4); // Go idle. ASSERT(running() && !waiting()); } void TestSuite::test7() { DoutEntering(dc::notice, "TestSuite::test7()"); task1->run(this, 2); // Start two tasks. task2->run(this, 4); gMainThreadEngine.mainloop(); task1->do_finish(); // Task 1 finishes. task2->do_finish(); // Task 2 finishes. wait(2); // Go idle. ASSERT(running() && !waiting()); ASSERT(*task1 && *task2); // Both tasks finished. wait(4); // Go idle. ASSERT(running() && !waiting()); wait(2); ASSERT(waiting()); // Calling wait() twice on a row always causes us to go idle! } void TestSuite::test8() { DoutEntering(dc::notice, "TestSuite::test8()"); gMainThreadEngine.setMaxDuration(10000.f); int count = 0; int loops = 0; Inserter ml(4, 25); // 4 tasks, 7 insertion points. ml.add(&task1); ml.add(&task2); ml.add(&task3); ml.add(&task4); ASSERT(running() && !waiting()); wait(2); ASSERT(waiting()); for (; !ml.finished(); ml.next_loop()) for (; ml() < 25; ++ml) if (ml.inner_loop()) { // Continue running. signal(2); ASSERT(!waiting()); // Reset the tasks. task1 = new Task; task2 = new Task; task3 = new Task; task4 = new Task; ++loops; int wait_calls = 0; // Main task is running and not idle(). ASSERT(running() && !waiting()); task1->run(this, 2); // Start three tasks that signal 2 when they finish. task2->run(this, 2); task3->run(this, 2); task4->run(this, 2); gMainThreadEngine.mainloop(); int n = 0; bool nonsense = false; int finished = ml.insert(n++); for(;;) { bool task1t1 = *task1; finished += ml.insert(n++); bool task2t1 = *task2; finished += ml.insert(n++); bool task3t1 = *task3; finished += ml.insert(n++); bool task2t2 = *task2; finished += ml.insert(n++); bool task3t2 = *task3; finished += ml.insert(n++); bool task4t2 = *task4; finished += ml.insert(n++); if ((task1t1 && task2t1 && task3t1) || (task2t2 && task3t2 && task4t2)) // We need either task1, 2 and 3 to have finished, or 2, 3 and 4. break; finished += ml.insert(n++); wait(2); // Go idle until one or more tasks are finished. ++wait_calls; ASSERT((running() && !waiting()) || finished < 3 || (finished == 3 && *task1 && *task4)); if (waiting() && ml.number_of_insertions_at(n) == 0) { nonsense = true; break; // The test is nonsense. } finished += ml.insert(n++); ASSERT(running() && !waiting()); // We should only continue to run after a wait when we're really running ;). } if (nonsense) continue; ++count; for(;;) { int done = 0; done += *task1 ? 1 : 0; done += *task2 ? 1 : 0; done += *task3 ? 1 : 0; done += *task4 ? 1 : 0; while (running() && !waiting()) { wait(2); ++wait_calls; } if (done == 4) break; ASSERT(n < 25); finished += ml.insert(n++); } ASSERT(finished == 4); ASSERT(wait_calls <= 5); ASSERT(waiting()); } Dout(dc::notice, "count = " << count << "; loops = " << loops); }
true
571f5519c7a81e53dddde9ca3301f7225ce70364
C++
ZhongYingjia/Cpp-Primer
/ch12/ex12.28.cpp
UTF-8
1,208
2.9375
3
[]
no_license
#include <string> using std::string; #include <vector> using std::vector; #include <map> using std::map; #include <set> using std::set; #include <iostream> #include <fstream> #include <sstream> int main() { std::ifstream file("../data/storyDataFile.txt"); string text; vector<string> input; map<string,set<decltype(input.size())>> wm; while(std::getline(file, text)){ input.push_back(text); std::istringstream line(text); string word; auto lno = input.size() - 1; while(line >> word){ wm[word].insert(lno); } } while(true){ std::cout << "enter word to look for, or q to quit:"; string s; if(!(std::cin >> s) || s == "q") break; std::cout << s << " occurs "; auto q = wm.find(s); if(q == wm.end()){ std::cout << "0 time" << std::endl; continue; }else{ std::cout << q->second.size() <<(q->second.size() > 1?" times":" time") << std::endl; for(auto i : q->second){ std::cout << "\t(line " << i+1 << ") " << input[i] << std::endl; } } } return 0; }
true
cdf7a513cde19b970bf4172ec83641c2047c0df4
C++
akshya03/LoveBabbar-DSA-playlist
/binaryTree 13.cpp
UTF-8
1,848
3.59375
4
[]
no_license
//similar to vertical traversal // only diff is that only last dist is taken #include<bits/stdc++.h> using namespace std; struct Node{ int data; struct Node *left,*right; Node(int x){ data=x; left=right=NULL; } }; void bottomView(Node* root){ if(!root) return; Node* curr; int parentDist; queue<Node*> que; queue<int> dist; map<int,int> umap; //dist,list of Nodes at that vertical dist que.push(root); dist.push(0); while(!que.empty()){ curr=que.front(); parentDist=dist.front(); que.pop(); dist.pop(); //if(umap.find(parentDist) == umap.end()) // umap[parentDist].push_back(curr->data); umap[parentDist]=curr->data; if(curr->left){ que.push(curr->left); dist.push(parentDist-1); } if(curr->right){ que.push(curr->right); dist.push(parentDist+1); } } for(auto x:umap){ cout<<x.second<<" "; cout<<endl; } } int main() { // Create binary tree shown in above figure Node *root = new Node(1); root->left = new Node(2); root->right = new Node(3); root->left->left = new Node(4); root->left->right = new Node(5); root->right->left = new Node(6); root->right->right = new Node(7); root->right->left->right = new Node(8); root->right->right->right = new Node(9); cout << "Bottom view is \n"; bottomView(root); return 0; } /* 1 / \ 2 3 / \ / \ 4 5 6 7 #nodes at same lvl with same horizontal distance: take the last node at that lvl(of same dist( as they overwrite each other \ \ 8 9 Output: The output of print this tree vertically will be: 4 2 6 8 7 9 */
true
2e3c1705432015e565b9c4fa67fff5bc9cbaa6d1
C++
Pengxinjie/DataStructure-C
/DataStructure-C/队列2.cpp
GB18030
2,146
3.546875
4
[]
no_license
//#define _CRT_SECURE_NO_WARNINGS //#include<stdio.h> //#include<stdlib.h> //#include "2.h" // //int main() //{ // LinkQueue q; // initQueue(q); // int boo = 1, // te; // while (boo) // { // int temp; // printf("1.Ԫأӣ\n2.ɾԪأӣ\n3.ʾԪ\n4.ٶв˳\n"); // printf("ҪеĶв"); // scanf("%d", &temp); // switch (temp) { // case 1: // printf("ҪӵԪأ"); // int value; // scanf("%d", &value); // enQueue(q, value); // break; // case 2: // deQueue(q,te); // break; // case 3: // showFront(q,te); // break; // case 4: // destroyQueue(q); // boo = 0; // break; // default: // printf("Ч\n"); // } // // } // // system("pause"); // return 0; //} // //void initQueue(LinkQueue& Q) //{ // // һնQ // if (!(Q.front = Q.rear = (QueuePtr)malloc(sizeof(QNode)))) // return; // Q.front->next = NULL; //} // //void destroyQueue(LinkQueue& Q) //{ // ٶQ(ۿշ) // while (Q.front) { // Q.rear = Q.front->next; // free(Q.front); // Q.front = Q.rear; // } //} // //void enQueue(LinkQueue& Q, ElemType e) //{ // ԪeΪQµĶβԪ // QueuePtr p; // if (!(p = (QueuePtr)malloc(sizeof(QNode)))) //洢ʧ // return; // p->data = e; // p->next = NULL; // Q.rear->next = p; // Q.rear = p; //} // //void deQueue(LinkQueue& Q, ElemType& e) //{ // вգɾQĶͷԪأeֵOK //// 򷵻ERROR // QueuePtr p; // if (Q.front == Q.rear) { // printf("пգʧܣ\n"); // return; // } // p = Q.front->next; // e = p->data; // Q.front->next = p->next; // if (Q.rear == p) // Q.rear = Q.front; // free(p); // return; //} // //void showFront(LinkQueue Q, ElemType& e) //{ // вգeQĶͷԪأOK //// 򷵻ERROR // QueuePtr p; // if (Q.front == Q.rear) // { // printf("пգ\n"); // return; // } // p = Q.front->next; // e = p->data; // printf("ڶԪǣ%d\n", e); //}
true
7439913c22f071350b4e5ebc2ebf1bfc11ef6851
C++
juechen-zzz/C
/C_project/6_2 继承的基本概念/main.cpp
UTF-8
1,112
3.453125
3
[]
no_license
// // main.cpp // 6_2 继承的基本概念 // // Created by 倪浩鹏 on 2020/2/9. // Copyright © 2020 nihaopeng. All rights reserved. // // 父类子类(基类派生类) #include <iostream> #include <string> using namespace std; class Student{ public: Student(int id, string name){ this->id = id; this->name = name; } void printS(){ cout << "id = " << this->id << " name = " << this->name << endl; } private: int id; string name; }; // 创建一个新的学生类,增加分数功能 class Student2: public Student { public: // 在调用子类构造函数的时候,会自动调用父类的构造函数,不声明则为无参构造,还有析构函数 // 重名的时候,加上作用域即可 Student2(int id, string name, int score): Student(id, name) { this->score = score; } void printS(){ Student::printS(); cout << "score = " << this->score << endl; } private: int score; }; int main(int argc, const char * argv[]) { Student2 s(1, "A", 80); s.printS(); return 0; }
true
d4fda95cd5bb9f79851dceddbb9a4166a50ce8fb
C++
luzyong/Proyecto-Teoria
/gramatica.cpp
UTF-8
6,064
2.734375
3
[]
no_license
#include <stdio.h> #include <conio.h> #include<stdlib.h> #include <iostream> using namespace std; int main(){ int var,ter,pro,i,j,l,respuesta,positiva,desigual,epsilon=0; char terminales[5]; char produccion[pro]; char variable,terminal,produ,mayus,simbolo,minusc; do{ //EXPLICACIÓN SOBRE LAS GRAMÁTICAS cout<<"Gramaticas Libres de Contexto\nDefinicion:\nG=(V,T,P,S)\nDonde:\nV:variables\nT:terminales\nP:producciones\nS:simbolo inicial."<<endl; cout<<"\nUna produccion es el conjunto de simbolos que genera una variable, pudiendo ser una o varias terminales y/o variables.\nLas producciones pueden contener un simbolo especial llamado epsilon, que representa un conjunto vacio."<<endl; cout<<"\nCuando se utilizan varios simbolos pueden aparecer concatenados o con un operador llamado OR.\nLa concatenacion nos dice que ambos simbolos aparecen en esa misma operacion.\nEl OR nos indica que han aparecido varias producciones en una misma variable."<<endl; cout<<"\n Por ejemplo A-->a|Ab\nA y b estan concatenadas y la produccion a con la produccion Ab estan indicadas por el simbolo OR"<<endl; cout<<"Las gramaticas siempre tienen una variable inicial (S), que es por donde siempre se va a iniciar."<<endl; cout<<"\n\nPara hacer eficiente una GLC se realiza una limpieza para poder generar un lenguaje, en el que no existan simbolos sin utilizar ni cosas por el estilo.\n Para eso se dice que la gram�tica tiene que ser positiva y admisible.\nPositividad: que no exista ningun simbolo especial o epsilon\nAdmisible:que todas las variables definidas a la derecha (en la produccion) esten definidas tambien a la izquierda (en las variables)"<<endl; cout<<"Existen dos formas de representar las GLC una vez hechas admisibles y positivas: Forma Normal de Chomsky (FNC) y Forma Normal de Greibach (FNG)"<<endl; cout<<"FNC:se representa por una terminal o dos variables A-->a|AB\nFNG: se representa por una terminal seguida de cero o m�s variables A-->a|aA|aAB...\n"<<endl; cout<<"\nPaso 1: Hacer positiva la gramatica.\nDebemos eliminar el simbolo especial o epsilon.\n1.-Identificamos la variable que contenga el simbolo.\n2.-Identificamos las producciones que contengan dicha variable\n3.-Sustituimos en la produccion la variable por su equivalente\n4.-Volvemos a escribir la produccion con la variable y sin la variable, utilizando OR para separalo.\n5.-Se repite hasta eliminar epsilon de la gramatica."<<endl; cout<<"\n1.-A-->a\nB-->A|C\nC-->{\n2.-La variable que contiene el simbolo es C\n3.-A-->a\nB-->A|C|{\n\nA-->a\nB-->A|C\n\nPodemos ver que se elimino { y la variable que la tenia, asi que esta gramatica ya es positiva. Ahora hay que hacerla admisible"<<endl; cout<<"\nPara hacerla admisible solo hay que eliminar las variables que no aparecen en ambos lados.\nA-->a\nEsta gramatica ya es positiva, adisible y esta en su forma normal de Greibach y de Chomsky"<<endl; cout<<"Un automata de pila es una septupla AP([,T,Q,Ao,qo,f,F)\nDonde:\n[=Simbolos de entrada\nT=Simbolos de pila\nQ=Conjunto de estados\nAo=Simbolo inicial\nqo=Estado inicial\nf=Funcion de transicion\nF=Estados finales"<<endl; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //INGRESO DE DATOS PARA CONSTRUIR LA GRAMÁTICA(VARIABLES, TERMINALES) i j cout<<"Ingresa la variable (mayuscula)\n"<<endl; cin>>variable; cout<<"\n\nIngresa el numero de TERMINALES(maximo 5):"<<endl; cin>>ter; if(ter==1){ cout<<"Ingresa la terminal (letra minuscula)"<<endl; cin>>terminal; } if(ter>1){ for(i=0;i<ter;i++){ cout<<"Ingresa la terminal "<<i+1<<" de la variable (letra minuscula)"<<endl; cin>>terminales[i]; } } cout<<"Ingresa el numero de producciones de la variable"<<endl; cin>>pro; produccion[0]=variable; cout<<"\nNOTA:Si vas a ingresar el conjunto vacio o epsilon, ingresa ({)"<<endl; for(i=1;i<=pro;i++){ cout<<"Ingresa la produccion "<<i<<"de la variable"<<endl; cin>>produccion[i]; } cout<<"\n"<<produccion[0]<<"-->"; for(j=1;j<=pro;j++){ cout<<produccion[j]<<"|"; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //DETERMINA SI LA GRAMATICA ES POSITIVA p q positiva=0; for(i=1;i<=pro;i++){ if(produccion[i]=='{'){ cout<<"Tu gramatica no es positiva, hay una epsilon ({)en "<<produccion[0]<<endl; epsilon=1; } else{ positiva++; } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //SI LA GRAMATICA ES POSITIVA, DETERMINA SI ES ADMISIBLE a b if(positiva==pro){ simbolo=produccion[0]; for(i=1;i<=pro;i++){ if(produccion[i]>='A'&&produccion[i]<='Z'){ mayus=produccion[i]; cout<<mayus; if(mayus!=simbolo){ desigual++; } } else if(produccion[i]>='a'&&produccion[i]<='z') { desigual=0; } } if(desigual==0){ cout<<"\nFelicidades, tu gramatica ya es positiva y admisible"<<endl; } else{ cout<<"Tu gramatica aun no es admisible"<<endl; } } cout<<"\n[="<<produccion[0]; cout<<"\n"; if(ter==1){ cout<<"T="<<terminal<<endl; } else if(ter>1){ cout<<"T="; for(i=0;i<ter;i++){ cout<<terminales[i]<<", "; } } cout<<"\nS="<<simbolo<<endl; cout<<"Q="; cout<<"\n"<<produccion[0]<<"-->"; for(j=1;j<=pro;j++){ cout<<produccion[j]<<"|"; } cout<<"\nQué deseas hacer?\n1.-Iniciar gramatica\n2.-Salir"<<endl; cin>>respuesta; } while(respuesta!=2); getch(); return 0;}
true
ae0bf497fb68c3ca7fd3f57e094cc720ee3bc204
C++
eraymitrani/hackerrank
/bidding_game.cpp
UTF-8
2,298
3.125
3
[]
no_license
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <string.h> using namespace std; int calculate_bid(int player, int pos, int* first_moves, int* second_moves) { //Your logic to be put here int o_left = 100, t_left = 100, bid = 0, draw=0; int winning = 0, i = 0; if (pos > 5) winning = 1; else if (pos < 5) winning = -1; int* counter = first_moves; while (*(first_moves + i) != 0) { int bet1 = *(first_moves + i); int bet2 = *(second_moves + i); if (bet1 > bet2) { o_left -= bet1; } else if(bet2> bet1) t_left -= bet2; else{ draw++; if(draw%2){ o_left -= bet1; } else{ t_left -= bet2; } } i++; } if (pos > 8) { if (player == 1) { return o_left; } } if (pos < 2) { if (player == 2) { return t_left; } } if (player == 1) { bid = o_left / (10 - pos); if(bid == 0 && o_left > 0) return 1; if(bid > 19) return (20 - (rand()%6)); return bid; } if (player == 2) { bid = t_left / pos; if(bid == 0 && t_left > 0) return 1; if(bid > 19) return (20 - (rand()%6)); return bid; } return bid; } int main(void) { int player; //1 if first player 2 if second int scotch_pos; //position of the scotch int bid, iter = 0; //Amount bid by the player size_t buf_limit = 500; char *first_move = (char *)malloc(buf_limit); //previous bids of the first player char *second_move = (char *)malloc(buf_limit); //prevous bids of the second player char remove_new_line[2]; int first_moves[200] = { 0 }; int second_moves[200] = { 0 }; char *tok_1, *tok_2; cin >> player; cin >> scotch_pos; cin.getline(remove_new_line, 2); //removes a new line from the buffer cin.getline(first_move, 200); cin.getline(second_move, 200); tok_1 = strtok(first_move, " "); for (int i = 0; tok_1; i++) { first_moves[i] = atoi(tok_1); tok_1 = strtok(NULL, " "); } tok_2 = strtok(second_move, " "); for (int i = 0; tok_2; i++) { second_moves[i] = atoi(tok_2); tok_2 = strtok(NULL, " "); } bid = calculate_bid(player, scotch_pos, first_moves, second_moves); cout << bid; return 0; }
true
253a8e745ea3450931f975e00cc382ff596f66cb
C++
UBIC-repo/core
/App.h
UTF-8
1,340
2.59375
3
[ "MIT" ]
permissive
#ifndef TX_APP_H #define TX_APP_H #include "FS/FS.h" #if defined(_WIN32) #include <synchapi.h> #else #include <unistd.h> #endif class App { private: bool terminateSignal = false; bool reindexing = false; bool starting = false; uint32_t reindexingHeight = 0; public: static App& Instance(){ static App instance; return instance; } //@TODO use! void terminate() { terminateSignal = true; #if defined(_WIN32) Sleep(3000); #else sleep(3); #endif immediateTerminate(); } void immediateTerminate() { terminateSignal = true; if(FS::fileExists(FS::getLockPath())) { FS::deleteFile(FS::getLockPath()); } std::exit(0); } bool getTerminateSignal() { return this->terminateSignal; } bool isReindexing() { return this->reindexing; } bool setReindexing(bool value) { this->reindexing = value; } uint32_t getReindexingHeight() { return reindexingHeight; } void setReindexingHeight(uint32_t reindexingHeight) { this->reindexingHeight = reindexingHeight; } bool isStarting() { return this->starting; } void setIsStarting(bool isStarting) { this->starting = isStarting; } }; #endif //TX_APP_H
true
dcd6513a0a1041504ed1d9f26f554cc9a2a0dff9
C++
vishuchhabra/cpp_programs
/programs codes/simple program based on multiple inheritance .cpp
UTF-8
529
2.875
3
[]
no_license
#include<iostream> using namespace std; class vishu { private: int x,y; public: void setd() { cout<<"enter the two numbers "<<endl; int a,b; cin>>a>>b; x=a; y=b; } void print() { cout<<"yours values are following as "<<endl<<"x="<<x<<endl<<"y="<<y<<endl; } }; class chhabra :public vishu { }; class vinny :public vishu { }; int main() { vinny er; er.setd(); er.print(); chhabra gdd; gdd.setd(); gdd.print(); return 0; }
true
425a278f6af0078451e92b2208039e6ee299210e
C++
Yeeunbb/Lecture_Algorithm
/algo6/main4.cpp
UHC
3,930
3.015625
3
[]
no_license
#include <iostream> #include <string> #include <vector> #include <queue> #include <map> //ö using namespace std; struct Metro{ // ü string station; int index; }; int m, l, staionIndex; // m, ȣ l, ε staionIndex int visited[10000]; // 湮ߴ ǥ visited迭 string s1, s2, start, last; // 踦 Է¹ s1, s2, ۿ start, last vector<vector<Metro>> metro; //Ʈ Ÿ ö map<string, int> maap; // ε ϱ map queue<int> que; //bfsԼ ť int trace[10000]; //θ 迭 int reverT[1000]; //trace ΰ ǾǷ, ٽ 迭 int lastStation; // ε void bfs(int m); //ʺ켱Ž int main(){ cin >> m; metro.resize(m*2); //  Էµ 𸣹Ƿ Ƿ for(int i=0; i<m; i++){ cin >> l >> s1 >> s2; Metro S1, S2; if(maap.find(s1) == maap.end()){ //ó ̸ S1.station = s1; //̸ S1.index = staionIndex; // ε maap.insert(make_pair(s1, staionIndex)); //map ̸ ε staionIndex++; //ε } else{ //̹ ϴ , S1.station = s1; //̸ S1.index = maap.find(s1)->second; // ε } if(maap.find(s2) == maap.end()){ //ó ̸ S2.station = s2; S2.index = staionIndex; maap.insert(make_pair(s2, staionIndex)); staionIndex++; } else{ //̹ ϴ S2.station = s2; S2.index = maap.find(s2)->second; } metro[S1.index].push_back(S2); // 踦 metro[S2.index].push_back(S1); } cin >> start >> last; //߿ Է¹ lastStation = maap.find(last)->second; // ε bfs(maap.find(start)->second); //ۿ ε ʺ켱Ž if(visited[lastStation] == 0){ //ؾ 湮 cout << "-1"; } else{//ؾ 湮Ѱ cout << visited[maap.find(last)->second] << endl; // µ 湮 int w=0; int tmp = lastStation; while(tmp != -1){ //湮 ٽ reverT[w] = trace[tmp]; tmp = trace[tmp]; w++; } map<string, int>::iterator iterr; for(int i=w-2; i>=0; i--){ // θ ϱ ؼ for(iterr=maap.begin(); iterr!=maap.end(); iterr++){ if(reverT[i] == iterr->second){ cout << iterr->first << " "; } } } cout << last; // } return 0; } void bfs(int m){ //ʺ켱Ž visited[m] = 1; //湮 que.push(m); // ٸ Žϱ ť trace[m] = -1; //ۿ ΰ Ƿ -1 while(!que.empty()){ int x = que.front(); que.pop(); for(int i=0; i<metro[x].size(); i++){ int y = metro[x][i].index; // ε y if(visited[y] == 0){ // 湮 쿡 que.push(y); //ť Žϱ visited[y] = visited[x] + 1; //y µ 湮 , 湮 ǰ+1 trace[y] = x; // 湮 . θ ֱ } } } }
true
eca1d5a4d7b299fdd2f0ab6505af4888070d704a
C++
kfarsany/undergraduate
/ICS_45C/shapes/Shape.h
UTF-8
369
3.046875
3
[]
no_license
#ifndef SHAPE_H #define SHAPE_H #include <string> #include <iostream> using namespace std; class Shape { int centerX; int centerY; string name; public: Shape(int newX, int newY, string newName) : centerX(newX), centerY(newY), name(newName) {} virtual double area() = 0; virtual void draw() = 0; virtual ~Shape() {} }; #endif
true
372688a21f5a4c76cb0e1e163c45752dbe9c71d4
C++
Neutree/SmartHome
/demo/embedded/lib/src/F103_PWM.cpp
UTF-8
7,192
3.015625
3
[ "MIT" ]
permissive
#include "F103_PWM.h" /** *@brief 用于计算出Psc的值和Arr的值,分两种情况,第一种,72M能被frequency整除,第二种 72M不能被frequency整除 *@param quo 第一次计算之后的商 *@param quo2 第二次计算的商,由于在第一次计算里面已经定义了,就直接传过来了; *@param rem2 理由通quo2 *@param flagBest 标志是否找到最佳的Psc和Arr的值 */ void PWM::Calcute2(u32 quo,u32 quo2,u32 rem2,bool flagBest) { u16 i; for(i = 1;i<=1200;i++) { if(quo%i == 0 && quo/i < 65535){mPsc = i;mArr = quo/i;flagBest = true ;break;} } if(flagBest == false)//没有找到最佳值 { for( i = 1;i <= 1200;i++) { quo2 = quo / i; rem2 = quo % i; if(quo2 < 65535 && rem2 < 32758){mPsc = i;mArr = quo2;flagBest = true;break;} } } } /** *@brief 用于第一次计算,判断是否期望的频率能整除72M *@param frequency 期望的频率 */ void PWM::Calcute(u16 frequency) { bool flagBest = false; //标志是否找到最佳值 u32 quo = 72000000/frequency;//获得商数 u32 rem = 72000000%frequency;//获得余数 u32 quo2 = 0; u32 rem2 = 0; if(rem == 0)//1·F能整除72M;将除数quo再重1开始除,在能整除的情况下,取 { Calcute2(quo,quo2,rem2,flagBest); } else { if(rem > 32768)quo++; Calcute2(quo,quo2,rem2,flagBest); } } /** *@brief 构造函数 *@param timer 选择的时钟 *@param enCh1 通道1是否打开 *@param enCh2 通道2是否打开 *@param enCh3 通道3是否打开 *@param enCh4 通道4是否打开 *@param frequency 期望频率 *@param remap 引脚是否映射,这个版本还没有做 */ void PWM::PWMInit(TIM_TypeDef* timer,bool enCh1,bool enCh2,bool enCh3,bool enCh4,u16 frequency,bool remap)//传入选择的定时器,若没有传入参数,默认TIM2 { /* 根据频率设置PSC和ARR的值,以后再说,现在能够满足要求; // mPsc = 71; // mArr = (u16)((72000000)/((mPsc+1)*frequency))-1; */ mTimer = timer; //get the TIM of chosen RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);//open the PinA Timer RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);//open the PinB Timer RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE);//管脚复用打开 //因为swtich不支持TIM_TypeDef类型,强制转换之后会变成null,所以采用传统的if else来设置GPIO if(timer == TIM2) { RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE); GPIO_InitStruct.GPIO_Pin = (GPIO_Pin_0 & enCh1)| (GPIO_Pin_1 & enCh2<<1)| (GPIO_Pin_2 & enCh3<<2)| (GPIO_Pin_3 & enCh4<<3); GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_Init(GPIOA,&GPIO_InitStruct); } else { if(timer == TIM3) { RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE); GPIO_InitStruct.GPIO_Pin = (GPIO_Pin_6 & enCh1<<6)| (GPIO_Pin_7 & enCh2<<7); GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_Init(GPIOA,&GPIO_InitStruct); GPIO_InitStruct.GPIO_Pin = (GPIO_Pin_0 & enCh3)| (GPIO_Pin_1 & enCh4<<1); GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_Init(GPIOB,&GPIO_InitStruct); } else{ if(timer == TIM4) { RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4,ENABLE); GPIO_InitStruct.GPIO_Pin = (GPIO_Pin_6 & enCh1<<6)| (GPIO_Pin_7 & enCh2<<7)| (GPIO_Pin_8 & enCh3<<8)| (GPIO_Pin_9 & enCh4<<9); GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_Init(GPIOB,&GPIO_InitStruct); } } } //开始设置TIM TIM_TimeBaseStruct.TIM_Period = mArr-1;//设置ARR寄存器,就是计数多少次;PSC = 7199的话就以10KHZ计数5000次,就是5000×0.1ms = 500ms 2HZ TIM_TimeBaseStruct.TIM_Prescaler = mPsc-1;//预分频寄存器输入7200,计数时钟为10kHZ。72M/7200 = 10K TIM_TimeBaseStruct.TIM_ClockDivision = TIM_CKD_DIV1;//0; TIM_TimeBaseStruct.TIM_CounterMode = TIM_CounterMode_Up;//中间对齐,形成中间对齐的PWM波 TIM_CounterMode_Up;向上//TIM_CounterMode_CenterAligned1//中间对齐 TIM_TimeBaseInit(timer,&TIM_TimeBaseStruct);//初始化TIM //pwm设置,即初始化 TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;//选择定时器模式为pwm1模式 TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;//设置的输出极性,表现为占空比数值是高电平直接占还是低电平 //通道1--- TIM_OCInitStructure.TIM_Pulse = mArr/2;//占空比时间 TIM_OC1Init(timer,&TIM_OCInitStructure);//根据TIM_OCInitStructure结构体初始化TIM通道1 TIM_OC1PreloadConfig(timer,TIM_OCPreload_Enable);//使能预装载器 //通道2--- TIM_OCInitStructure.TIM_Pulse = mArr/2;//占空比时间 TIM_OC2Init(timer,&TIM_OCInitStructure);//根据TIM_OCInitStructure结构体初始化TIM通道2 TIM_OC2PreloadConfig(timer,TIM_OCPreload_Enable);//使能预装载器 //通道3--- TIM_OCInitStructure.TIM_Pulse = mArr/2;//占空比时间 TIM_OC3Init(timer,&TIM_OCInitStructure);//根据TIM_OCInitStructure结构体初始化TIM通道3 TIM_OC3PreloadConfig(timer,TIM_OCPreload_Enable);//使能预装载器 //通道4--- TIM_OCInitStructure.TIM_Pulse = mArr/2;//占空比时间 TIM_OC4Init(timer,&TIM_OCInitStructure);//根据TIM_OCInitStructure结构体初始化TIM通道4 TIM_OC4PreloadConfig(timer,TIM_OCPreload_Enable);//使能预装载器 TIM_Cmd(timer,ENABLE); } /** *@brief 改变一个通道的占空比 *@param channel 选择通道 *@param duty 设置占空比 *@param isSetPositiveDuty 设置高电平的占空比还是设置低电平的占空比 */ void PWM::SetDuty(u8 channel,float duty,bool isSetPositiveDuty) { if(isSetPositiveDuty) duty=100-duty; u16 arrTemp = (duty/100)*mArr; switch(channel) { case 1:mTimer->CCR1 = arrTemp;break; case 2:mTimer->CCR2 = arrTemp;break; case 3:mTimer->CCR3 = arrTemp;break; case 4:mTimer->CCR4 = arrTemp;break; } } /** *@brief 改变一个通道的占空比 *@param dutyCh1 设置通道1的占空比 *@param dutyCh2 设置通道2的占空比 *@param dutyCh3 设置通道3的占空比 *@param dutyCh4 设置通道4的占空比 *@param isSetPositiveDuty 设置高电平的占空比还是设置低电平的占空比 */ void PWM::SetDuty(float dutyCh1,float dutyCh2,float dutyCh3,float dutyCh4,bool isSetPositiveDuty) { if(isSetPositiveDuty) { dutyCh1=100-dutyCh1; dutyCh2=100-dutyCh2; dutyCh3=100-dutyCh3; dutyCh4=100-dutyCh4; } u16 ccr1Temp = (dutyCh1/100)*mArr; u16 ccr2Temp = (dutyCh2/100)*mArr; u16 ccr3Temp = (dutyCh3/100)*mArr; u16 ccr4Temp = (dutyCh4/100)*mArr; mTimer -> CCR1 = ccr1Temp; mTimer -> CCR2 = ccr2Temp; mTimer -> CCR3 = ccr3Temp; mTimer -> CCR4 = ccr4Temp; } u16 PWM::GetmFrequency() { return mFrequency; }
true
af65d2cc0f46f8aed07449a769a91a4e8196108f
C++
romanoprid/IOT-2019
/main.cpp
UTF-8
3,931
3.375
3
[]
no_license
#include <iostream> #include <math.h> #include <conio.h> #define _USE_MATH_DEFINES #define n 5 #define m 5 using namespace std; class Matrix { private: double M[m]; public: friend void inputArray(Matrix Array[]); friend void outputArray(Matrix Array[]); friend void sortArray(Matrix Array[]); void calcArray(Matrix Array[]); }; void inputArray(Matrix Array[]) { for (int row = 0; row < n; ++row) for (int column = 0; column < m; ++column) { cin >> Array[row].M[column]; } } void outputArray(Matrix Array[]) { for (int row = 0; row < n; ++row) { for (int column = 0; column < m; ++column) { cout << Array[column].M[row] << "\t"; } cout << endl; } } void sortArray(Matrix array[]) { for (int row = 0; row < n; row++) { for (int BlockSizeIterator = 1; BlockSizeIterator < n; BlockSizeIterator *= 2) { for (int BlockIterator = 0; BlockIterator < n - BlockSizeIterator; BlockIterator += 2 * BlockSizeIterator) { int LeftBlockIterator = 0; int RightBlockIterator = 0; int LeftBorder = BlockIterator; int MidBorder = BlockIterator + BlockSizeIterator; int RightBorder = BlockIterator + 2 * BlockSizeIterator; RightBorder = (RightBorder < n) ? RightBorder : n; int* SortedBlock = new int[RightBorder - LeftBorder]; while (LeftBorder + LeftBlockIterator < MidBorder && MidBorder + RightBlockIterator < RightBorder) { if (array[LeftBorder + LeftBlockIterator].M[row] < array[MidBorder + RightBlockIterator].M[row]) { SortedBlock[LeftBlockIterator + RightBlockIterator] = array[LeftBorder + LeftBlockIterator].M[row]; LeftBlockIterator++; } else { SortedBlock[LeftBlockIterator + RightBlockIterator] = array[MidBorder + RightBlockIterator].M[row]; RightBlockIterator++; } } while (LeftBorder + LeftBlockIterator < MidBorder) { SortedBlock[LeftBlockIterator + RightBlockIterator] = array[LeftBorder + LeftBlockIterator].M[row]; LeftBlockIterator++; } while (MidBorder + RightBlockIterator < RightBorder) { SortedBlock[LeftBlockIterator + RightBlockIterator] = array[MidBorder + RightBlockIterator].M[row]; RightBlockIterator++; } for (int MergeIterator = 0; MergeIterator < LeftBlockIterator + RightBlockIterator; MergeIterator++) { array[LeftBorder + MergeIterator].M[row] = SortedBlock[MergeIterator]; } delete SortedBlock; } } } } void Matrix::calcArray(Matrix Array[]) { double sumUnderDiagonal[n] = {0, 0, 0, 0, 0}; for(int column = 0; column < n; column++) { for(int row = n; row > n-column-1; row--) { sumUnderDiagonal[row]+=(Array[row].M[column]); } } double haunt = 1; for (int row = 1; row < n; row++) { haunt *= -1*pow(fabs(sumUnderDiagonal[row]), 1.0/4.0L); std::cout << "f(" << row << "): " << sumUnderDiagonal[row] << std::endl; } cout << "F(f(rowcolumn)): " << haunt << endl; } int main() { Matrix Array[n]; cout << "Enter elements of matrix:\n" << endl; inputArray(Array); cout << "\nYour matrix:\n" << endl; outputArray(Array); sortArray(Array); cout << "\nSorted matrix:\n" << endl; outputArray(Array); cout << "\nCalculations:\n" << endl; Array->calcArray(Array); }
true
fa5c8cdea34d07bc016395c8b18a3088d667d535
C++
misterpeddy/CS216
/Lab08/test.cpp
UTF-8
221
2.90625
3
[]
no_license
#include <iostream> using namespace std; void passIntValue(float value) { value = 0.0; } void passIntRef(float & value) { value = 0.0; } int main() { float value = 0.0; passIntValue(value); passIntRef(value); }
true
7972c4426e71ae8f59527f81b94dbb163c82daa5
C++
ea-evdokimov/3-semestr
/2-contest/2_B.cpp
UTF-8
3,460
3.09375
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> #include <stack> #include <cmath> #include <iomanip> #include <set> template<typename T> struct Point{ T x, y; T sq_len(const Point &a) const { return (a.x - x) * (a.x - x) + (a.y - y) * (a.y - y); } friend std::istream& operator>> (std::istream &in, Point<T> &p){ in >> p.x; in >> p.y; return in; } }; template<typename T> class Hull2D{ private: Point<T> p0; std::vector<Point<T>> points, convex_hull; T angle(const Point<T>& p, const Point<T>& p1, const Point<T>& p2){ return (p1.y - p.y) * (p2.x - p1.x) - (p1.x - p.x) * (p2.y - p1.y); } public: Hull2D(const std::vector<Point<T>> &v) : points(std::move(v)) {} void build_convex_hull(); friend std::ostream& operator<< (std::ostream &out, Hull2D<T> &h){ for(auto i : h.convex_hull) out << "(" << i.x << ";" << i.y << ")" << " "; return out; } double sum_len(){ double res = 0; for(size_t i = 0; i < convex_hull.size() - 1; ++i){ T len = convex_hull[i].sq_len(convex_hull[i + 1]); res += sqrt(len); } return res; } }; template<typename T> void Hull2D<T>::build_convex_hull(){ //сортируем по y, берем самую нижнюю правую std::sort(points.begin(), points.end(), [](const Point<T>& a, const Point<T>& b){ return std::tie(a.y, a.x) < std::tie(b.y, b.x); }); p0 = points[0]; std::sort(points.begin() + 1, points.end(), [&p0=p0](const Point<T>& q, const Point<T>& r){ //если на одной прямой, берем ту точку, которая дальше T a = (q.y - p0.y) * (r.x - q.x) - (q.x - p0.x) * (r.y - q.y); if (a == 0) return p0.sq_len(q) <= p0.sq_len(r); return a < 0; }); std::stack<Point<T>> s; //добавляем последнюю и 0 точки s.push(points[points.size() - 1]); s.push(points[0]); size_t i = 1; if(points.size() <= 3){ for(auto p : points){ convex_hull.push_back(p); } convex_hull.push_back(points[0]); } else{ while (i < points.size()) { Point<T> p_t0, p_t1; p_t0 = s.top(), s.pop(); p_t1 = s.top(), s.pop(); //берем последние две, проверяем угол if (angle(p_t1, p_t0, points[i]) <= 0) { //если имеем поворот и точки лежат на прямой, добавляем s.push(p_t1); s.push(p_t0); s.push(points[i]); ++i; } else { s.push(p_t1); } } while(!s.empty()){ convex_hull.push_back(s.top()); s.pop(); } } } int main() { std::vector<Point<int64_t>> v; size_t N; Point<int64_t> a; std::cin >> N; auto cmp = [](Point<int64_t> a, Point<int64_t> b) { return std::tie(a.x, a.y) < std::tie(b.x, b.y); }; std::set<Point<int64_t>, decltype(cmp)> s(cmp); for(size_t i = 0; i < N; ++i){ std::cin >> a; s.insert(a); } for(auto i : s) v.push_back(i); Hull2D<int64_t> p(v); p.build_convex_hull(); std::cout << std::setprecision(10) << p.sum_len() << '\n'; return 0; }
true
241621c7d59be46982f2df7ba2ca1c13018ddb50
C++
cies96035/CPP_programs
/TEST/test.cpp
UTF-8
866
3.140625
3
[]
no_license
#include<iostream> #include<fstream> #include<queue> using namespace std; class A{ public:A(){a=1;cout<<"AX"<<endl;} A(int x){a=x;cout<<"AX(int)"<<endl; if(x<0)throw(x); } ~A(){cout<<"DA:"<<a<<endl;} int a; }; class B:public A{ public: int b; B(): A(11){b=3;cout<<"CB"<<endl;} B(int y):A(y){b=y;cout<<"CB(int)"<<endl;} ~B(){cout<<"DB:"<<a<<"\t"<<b<<endl;} }; class C:public A{ public: C(){c=5;cout<<"CC"<<endl;} C(int z){c=z;cout<<"CC(int)"<<endl;} ~C(){cout<<"DC:"<<a<<"\t"<<c<<endl;} int c; }; void foo(int &n) { A a; B b1; B b2(n++); C *c =new C(++n); A* pa; pa=c; B* pb=static_cast<B*>(pa); cout<<pb<<endl; cout<<(*pb).b<<endl; } int main( ) { int n=8; try{ foo(n); }catch(int p) { cout<<'c'<<p<<endl; } return 0; }
true
9ea7aa94449e61fb02d1d88baf3ce0f1d55e4a54
C++
ademakov/Oroch
/oroch/integer_stats.h
UTF-8
2,951
2.703125
3
[ "MIT" ]
permissive
// integer_codec.h // // Copyright (c) 2015-2016 Aleksey Demakov // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #ifndef OROCH_INTEGER_STATS_H_ #define OROCH_INTEGER_STATS_H_ #include <array> #include <limits> #include "common.h" #include "integer_traits.h" namespace oroch { template <typename T> class integer_stats { public: using original_t = T; using unsigned_t = typename integer_traits<original_t>::unsigned_t; static constexpr size_t nbits = integer_traits<original_t>::nbits; // Collect basic sequence info: // * the number of values; // * the minimum value; // * the maximum value. template <typename Iter> integer_stats(Iter src, Iter const end) { for (; src != end; ++src) add(*src); } size_t nvalues() const { return nvalues_; } original_t min() const { return minvalue_; } original_t max() const { return maxvalue_; } size_t original_space() const { return nvalues() * sizeof(original_t); } // Collect info for bit-length histogram of values. template <typename Iter> void build_histogram(Iter src, Iter const end) { // Build the histogram. for (; src != end; ++src) stat(*src); } size_t histogram(std::size_t index) const { return histogram_[index]; } private: void add(original_t value) { nvalues_++; if (minvalue_ > value) minvalue_ = value; if (maxvalue_ < value) maxvalue_ = value; } void stat(original_t value) { unsigned_t delta = value - minvalue_; size_t index = integer_traits<unsigned_t>::usedcount(delta); histogram_[index]++; } // The total number of values. size_t nvalues_ = 0; // The minimum and maximum values in the sequence. original_t minvalue_ = std::numeric_limits<original_t>::max(); original_t maxvalue_ = std::numeric_limits<original_t>::min(); // The log2 histogram of values. std::array<size_t, nbits + 1> histogram_ = {}; }; } // namespace oroch #endif /* OROCH_INTEGER_STATS_H_ */
true
ea29e1067fe7dfc1013776febe5f0b2c9772ea8b
C++
iu-vail/iprimal
/iPrimal.h
UTF-8
4,994
2.9375
3
[ "MIT" ]
permissive
/////////////////////////////////////////////////////////////////////////////// // File name: iPrimal.h // This file defines the main algorithm of IMPROVED primal assignment Method. // The time complexity is improved to O(n^3 lg n), via merging multiple steps // into single stages of swap loop searching. // Min-heaps and trees are used to maintain searching results. // Lantao Liu, Jan 17, 2011 /////////////////////////////////////////////////////////////////////////////// #ifndef PRIMAL_H #define PRIMAL_H #include "Define.h" #include "Assignment.h" #include <math.h> #include <set> template<typename T> class less_comp; //defined later class Primal{ public: Primal(){ cerr<<"Not allowed."<<endl; exit(0); } Primal(mat& m){ row_size = m.size(); col_size = m[0].size(); assert(row_size <= col_size); //currently assume they are equal orig_matrix = m; oprt_matrix = m; } ~Primal(){} //some accessors inline void ClearExploited(void){ exploited_rows.clear(); exploited_cols.clear(); } inline void ClearSwapLoop(void){ swap_loop.clear(); } inline uint GetAssignedCol(uint _row_id){ return assignment[_row_id]; } inline uint GetAssignedRow(uint _col_id); vector<uint> GetAsgnVec(void){ return assignment; } uint GetSwapLoopLength(void){ return swap_loop.size(); } void InitAsgnPtrs(void){ asgn_ptrs.clear(); asgn_ptrs.resize(row_size); for(uint i=0; i<row_size; i++) asgn_ptrs[i] = NULL; } void InitSibPtrs(void){ sib_ptrs.clear(); sib_ptrs.resize(row_size); for(uint i=0; i<row_size; i++) sib_ptrs[i] = NULL; } // initiations void RandSolution(void); void InitSolution(const vector<uint>&); void InitStage(void); //approximations, remove these two does not hurt the algo(safely ignore them) void GreedyApprox1(vector<uint>&); //local greedy void GreedyApprox2(vector<uint>&); //global greedy // pre-process and create the heaps void Preprocess(void); // get the next starting cell, if returns (-1, -1), meaning all are >=0 cell NextStartEntry() const; cell NextStartEntry(uint) const; //void UpdateDualVars(const vector<double>& _deltas); void UpdateReducedCostMatrix(const vector<double>& _dual_rows, const vector<double>& _dual_cols); // search a swap loop using BFS bool SearchSwapLoop(cell& _start); // dual updates, return: -1 if simply update; 0 if no loop but feasible; 1 if a swap loop is found during the update, ie, root is changed & already covered. int DualUpdates(cell&, queue<tree_node*>&); // given a swap loop, tasks are swapped, matrix & assign-vec are updated void SwapTasks(void); //primal algo containing all compoments to get the ultimate solution //must init a solution before calling it void PrimalAlgo(void); // get current sum of costs based on current assignemnt solution double ComputeCostSum(const mat& _m, const vector<uint>& _as) const; // some display functions void DisplayMatrix(const mat&) const; void DisplayMatrix(const mat&, const vector<uint>&) const; void DisplayAssignment(void) const; void DisplaySet(const set<uint>&) const; void DisplayTree(tree_node* _root); template<typename T> void DisplayVec(const vector<T>& _vec); // destroy the whole tree, return number of nodes; uint DeleteTree(tree_node* _root); // for testing & debugging, not used in final algorithm void PrimalTest(void); // double check if all values in reduced cost matrix have become feasible void DoubleCheck(void); private: //basic data members uint row_size; uint col_size; vector<double> dual_row_vars; // dual row variables, ie, row labelling values vector<double> dual_col_vars; // dual col variables, ie, col labelling values vector<double> deltas; // vector to store accumulated updates set<uint> exploited_rows; // rows traversed during searching loop set<uint> exploited_cols; // cols traversed during searching loop mat orig_matrix; // a copy of original matrix mat oprt_matrix; // the so-called reduced cost matrix vector< priority_queue< pair<uint, double>, vector<pair<uint,double> >, less_comp<uint> > > min_heaps; // heaps to maintain searching status vector<uint> assignment; // indices of vector <-> values in the vector list<cell> swap_loop; vector<tree_node*> asgn_ptrs; // store the pointers only to assigned cells vector<tree_node*> sib_ptrs; // store the pointers of last siblings each row //set<uint> greedy_cols; // store greedily selected starting columns }; // for priority queue elements' comparison template<typename T> class less_comp{ public: less_comp(bool __switch = false){ _switch = __switch; }; bool operator() (const pair<T, double>& a, const pair<T, double>& b) const { if(!_switch) // output in increasing order return a.second > b.second ? true : false ; else // output in decreasing order return a.second < b.second ? true : false ; } private: bool _switch; }; #endif
true
3834ee8482cd4ddc2ff8e15af2204f7f5c3c3de2
C++
AnminQ97/UE4_World
/Source/U02_Action/Components/CInventoryComponent.cpp
UHC
1,229
2.90625
3
[]
no_license
#include "CInventoryComponent.h" #include "Global.h" #include "InventorySystem/CItem.h" UCInventoryComponent::UCInventoryComponent() { Capacity = 20; } void UCInventoryComponent::BeginPlay() { Super::BeginPlay(); /*for (auto& Item : DefaultItems) { AddItem(Item); }*/ } // ߰ bool UCInventoryComponent::AddItem(ACItem* Item) { //뷮 ʰ ų Null̸ if (Items.Num() >= Capacity) { return false; } Item->OwningInventroy = this; Item->World = GetWorld(); //ߺ̸ if (CheckItemName(Item->ItemDisplayName)) { } else//ƴϸ { Items.Add(Item); } //UI Ʈ OnInventroyUpdated.Broadcast(); return true; } // bool UCInventoryComponent::RemoveItem(ACItem* Item) { if (Item) { if (Item->count > 0) Item->count--; else { Item->OwningInventroy = nullptr; Item->World = nullptr; Items.RemoveSingle(Item); } OnInventroyUpdated.Broadcast(); return true; } return false; } bool UCInventoryComponent::CheckItemName(FText name) { for (auto& Item : Items) { if (Item->ItemDisplayName.ToString() == name.ToString()) { Item->count++; return true; } else Item->count++; } return false; }
true
a7c79a88b95525df4ce180f1cfac7817bd730862
C++
andrewbkbk/sf_project
/TaskPlugin.cpp
UTF-8
728
2.75
3
[]
no_license
#include "TaskPlugin.h" #include "Task.h" #include <iostream> namespace { class MyTask : public Task { public: virtual ~MyTask( ) { std::cout << "~MyTask" << std::endl; } virtual bool run( ) { std::cout << "Run!!" << std::endl; return true; } virtual int get_progress( ) { return 0; } virtual std::string get_status_msg( ) { return 0; } }; Task* create_task( ) { std::cout << "create_task() called" << std::endl; return new MyTask( ); } void delete_task( Task* task ) { std::cout << "delete_task() called" << std::endl; delete task; } } const PluginInfo plugin_info = {API_VERSION, API_NAME, create_task, delete_task};
true
6e6cfb0856ba40b7fd89503950bb12b313be2b14
C++
tnsgh9603/BOJ_Old
/트리의 순회.cpp
UHC
914
3.296875
3
[]
no_license
#include <iostream> using namespace std; int in_order[100001], post_order[100001], position[100001]; void solve(int is, int ie, int ps, int pe) { // is -> inorder_start, ie -> inorder_end // ps -> position_start, pe -> position_end if (is > ie || ps > pe) { return; } int root = post_order[pe]; cout << root << ' '; // Ʈ int ir = position[root]; // in_order 迭 irġ root ִ. int left = ir - is; solve(is, ir - 1, ps, ps + left - 1); // Ʈ Ž solve(ir + 1, ie, ps + left, pe - 1); // Ʈ Ž } int main() { int n; cin >> n; for (int i = 0; i < n; i++) { cin >> in_order[i]; } for (int i = 0; i < n; i++) { cin >> post_order[i]; } for (int i = 0; i < n; i++) { position[in_order[i]] = i; // in_order i ġ ϴ position 迭 } solve(0, n - 1, 0, n - 1); return 0; }
true
af47024eab12c9f10b2f69a46c50b616277d35e1
C++
defytheflow/libege
/numconv/old/tests.cpp
UTF-8
1,387
3.140625
3
[]
no_license
#include "common.h" #include "numconv.h" using namespace std; typedef string (*numConvFunc)(string, int); void test_error(string func, string test_case, string exp_res, string res) { cerr << "Test failed in function " + func << endl; cerr << "Testcase - " + test_case + ", Expected result - " + exp_res + ". Result - " + res << endl; } void test_success(string func) { cout << func << " - All tests are successful." << endl; } void test_func(numConvFunc func, string test_cases[], string exp_test_res[], int num_test_cases, int *numErrors) { for (int i {0}; i < num_test_cases; ++i) { string res = bin(test_cases[i], DECIMAL); if (res != exp_test_res[i]) { ++(*numErrors); test_error("bin()", test_cases[i], exp_test_res[i], res); } } } void test_bin() { #define NUM_TEST_CASES 7 int numErrors {0}; // DECIMAL --> BINARY string test_cases1[NUM_TEST_CASES] = {"0", "-2", "34", "21", "185", "1432", "3"}; // 'exp' stands for 'expected', 'res' for 'results' string exp_test_res1[NUM_TEST_CASES] = {"0", "", "100010", "10101", "10111001", "10110011000", "11"}; test_func(bin, test_cases1, exp_test_res1, NUM_TEST_CASES, &numErrors); if (numErrors == 0) test_success("bin()"); #undef NUM_TEST_CASES } int main() { test_bin(); return 0; }
true
62b9c94ec7c26ef5125818696c888036ebeb5250
C++
leehaei/HTN_UbiGame
/UbiGame/Source/GameEngine/Util/TextureManager.h
UTF-8
3,992
2.71875
3
[]
no_license
#pragma once #include <vector> #include <SFML/Graphics/Texture.hpp> #include <SFML/System/Vector2.hpp> namespace GameEngine { //TODO - if needed, move out of Engine part to some sort of loader on the game side of things namespace eTexture { enum type { None = -1, Player = 0, //PlayerIdle, //PlayerAttack, //PlayerDead, Tileset, BG, Particles, Ground, Cow, Blacksmith, Shopkeeper, BloodiedHammer, Panacea, GreenVial, Bell, Towncrier, PlagueDoctor, BGObject1, BGObject2, BGObject3, BGObject4, BGObject5, BGObject6, BGObject7, Count, }; } inline const char* GetPath(eTexture::type texture) { switch (texture) { case eTexture::Player: return "knight_animations.png"; //case eTexture::PlayerIdle: return "knight_idle.png"; //case eTexture::PlayerAttack: return "knight_attack.png"; //case eTexture::PlayerDead: return "knight_death.png"; case eTexture::Tileset: return "tileset.png"; case eTexture::BG: return "starry_background.png"; case eTexture::Particles: return "particles.png"; case eTexture::Ground: return "ground.png"; case eTexture::Cow: return "cow_animation.png"; case eTexture::Blacksmith: return "blacksmith.png"; case eTexture::Shopkeeper: return "shopkeeper.png"; case eTexture::Towncrier: return "town_crier.png"; case eTexture::PlagueDoctor: return "doctor.png"; case eTexture::BloodiedHammer: return "bloodied_hammer.png"; case eTexture::Panacea: return "panacea.png"; case eTexture::GreenVial: return "green_vial.png"; case eTexture::Bell: return "bell.png"; case eTexture::BGObject1: return "background1.png"; case eTexture::BGObject2: return "background2.png"; case eTexture::BGObject3: return "background3.png"; case eTexture::BGObject4: return "background4.png"; case eTexture::BGObject5: return "background5.png"; case eTexture::BGObject6: return "background6.png"; case eTexture::BGObject7: return "background7.png"; default: return "UnknownTexType"; } } class TextureManager { public: static TextureManager* GetInstance() { if (!sm_instance) sm_instance = new TextureManager(); return sm_instance; } ~TextureManager(); void LoadTextures(); void UnLoadTextures(); sf::Texture* GetTexture(eTexture::type texture) const { return m_textures[(int)texture]; } private: TextureManager(); static TextureManager* sm_instance; sf::Texture* m_textures[eTexture::Count]; }; } namespace TextureHelper { static sf::Vector2f GetTextureTileSize(GameEngine::eTexture::type texture) { switch (texture) { case GameEngine::eTexture::Player: return sf::Vector2f(420.0f, 341.0f); //case GameEngine::eTexture::PlayerIdle: return sf::Vector2f(252.f, 280.f); //case GameEngine::eTexture::PlayerAttack: return sf::Vector2f(272.f, 344.f); //case GameEngine::eTexture::PlayerDead: return sf::Vector2f(341.f, 288.f); case GameEngine::eTexture::Tileset: return sf::Vector2f(32.f, 32.f); case GameEngine::eTexture::BG: return sf::Vector2f(1920.f, 1200.f); case GameEngine::eTexture::Particles: return sf::Vector2f(31.f, 32.f); case GameEngine::eTexture::Ground: return sf::Vector2f(480.f, 100.f); case GameEngine::eTexture::Blacksmith: return sf::Vector2f(225.0f, 225.0f); case GameEngine::eTexture::Shopkeeper: return sf::Vector2f(225.0f, 225.0f); case GameEngine::eTexture::Towncrier: return sf::Vector2f(225.0f, 225.0f); case GameEngine::eTexture::PlagueDoctor: return sf::Vector2f(225.0f, 225.0f); case GameEngine::eTexture::BloodiedHammer: return sf::Vector2f(32.0f, 32.0f); case GameEngine::eTexture::Panacea: return sf::Vector2f(32.0f, 32.0f); case GameEngine::eTexture::GreenVial: return sf::Vector2f(32.0f, 32.0f); case GameEngine::eTexture::Bell: return sf::Vector2f(32.0f, 32.0f); case GameEngine::eTexture::Cow: return sf::Vector2f(476.f, 304.f); default: return sf::Vector2f(-1.f, -1.f); } } }
true
b1f97c38b443e274c22f6f838438d5c017ed4013
C++
scottyege/simplication
/SIMP/HalfMesh.h
UTF-8
14,593
2.875
3
[]
no_license
#ifndef HALFMESH_H #define HALFMESH_H #include "glm.h"//obj model loader #include<vector> using std::vector; #include<map> using std::map; using std::pair; using std::make_pair; #include<queue> using std::queue; struct HEVertex; struct HEFace; struct HalfEdge; #include<ctime> #include<cstdlib> #include<algorithm> using std::min_element; typedef float Point3D[3]; struct HEMetric { HalfEdge *he; float length; bool operator() (HEMetric a, HEMetric b) { return a.length < b.length; } static float edgeDistance(Point3D v1, Point3D v2) { return sqrtf((v1[0] - v2[0]) * (v1[0] - v2[0]) + (v1[1] - v2[1]) * (v1[1] - v2[1]) + (v1[2] - v2[2]) * (v1[2] - v2[2])); } }; struct HalfEdge { HEVertex* vertex_begin; HalfEdge* next_edge; HalfEdge* paired_edge; HEFace* left_face; GLuint id; }; struct HEVertex { GLuint id; Point3D coordinate; HalfEdge* heEdge; }; struct HEFace { GLuint id; HalfEdge* heEdge; bool isBoundaryFace; }; class HalfMesh { public: map<GLuint, HEVertex*> vertices; //pair<from, to> map< pair<GLuint, GLuint>, HalfEdge* > halfEdges; map<GLuint, HEFace*> heFaces; GLuint nextNewIdCount; HalfMesh(GLMmodel *m) { ////populate vertex coordinate data HEVertex *hv = NULL; GLuint idx; for(GLuint i = 0; i < m->numvertices; i++) { hv = new HEVertex(); idx = i * 3 + 3; hv->coordinate[0] = m->vertices[idx]; hv->coordinate[1] = m->vertices[idx + 1]; hv->coordinate[2] = m->vertices[idx + 2]; hv->heEdge = NULL; hv->id = i + 1; vertices.insert(make_pair(i + 1, hv)); } //// ////populate halfedge HalfEdge *he = NULL; HEFace *hef = NULL; GLMtriangle *mt = NULL; GLuint triangleIdx; GLuint heIdx = 1; GLMgroup *gp = m->groups; while(gp) { for(GLuint i = 0; i < gp->numtriangles; i++) { triangleIdx = gp->triangles[i]; mt = &m->triangles[triangleIdx]; hef = new HEFace(); hef->id = triangleIdx; heFaces.insert(make_pair(triangleIdx, hef)); GLuint edges[][2] = { {mt->vindices[0],mt->vindices[1]}, {mt->vindices[1],mt->vindices[2]}, {mt->vindices[2],mt->vindices[0]} }; HalfEdge *hes[3]; for(int j = 0; j < 3; j++) { GLuint u = edges[j][0]; GLuint v = edges[j][1]; he = new HalfEdge(); he->vertex_begin = vertices[u]; he->left_face = hef; he->id = heIdx; heIdx++; halfEdges.insert(make_pair(make_pair(u, v), he)); hes[j] = he; if(!vertices.find(u)->second->heEdge) { //if the vertex u has not associated to a half edge vertices.find(u)->second->heEdge = he; } } //assigne next half edge for each half edge in face F hes[0]->next_edge = hes[1]; hes[1]->next_edge = hes[2]; hes[2]->next_edge = hes[0]; hef->heEdge = hes[0]; } gp = gp->next; } //// assign half edge pair field map< pair<GLuint, GLuint>, HalfEdge* >::const_iterator citer = halfEdges.begin(); pair<GLuint, GLuint> e; pair<GLuint, GLuint> inverse_e; while(citer != halfEdges.end()) { e = citer->first; he = citer->second; inverse_e.first = e.second; inverse_e.second = e.first; if(halfEdges.find(inverse_e) != halfEdges.end()) { //a paired half edge is found halfEdges[inverse_e]->paired_edge = halfEdges[e]; halfEdges[e]->paired_edge = halfEdges[inverse_e]; } else { /*if a paired half edge is not found, it is a boundadry edge*/ HalfEdge *hee = new HalfEdge(); hee->left_face = NULL; hee->paired_edge = halfEdges[e]; hee->vertex_begin = vertices[e.second]; hee->next_edge = NULL; halfEdges[e]->paired_edge = hee; halfEdges.insert(make_pair(make_pair(inverse_e.first, inverse_e.second), hee)); } citer++; } //// //// //check citer = halfEdges.begin(); while(citer != halfEdges.end()) { if(!citer->second->paired_edge) printf("GGGGGGGGGGGGGGGG\n"); citer++; } map<GLuint, HEFace*>::iterator ic = heFaces.begin(); while(ic != heFaces.end()) { if(!ic->second->heEdge->paired_edge->left_face || !ic->second->heEdge->next_edge->paired_edge->left_face || !ic->second->heEdge->next_edge->next_edge->paired_edge->left_face) ic->second->isBoundaryFace = true; else ic->second->isBoundaryFace = false; ic++; } nextNewIdCount = vertices.size() + 2; } void randomCollapse() { map< pair<GLuint, GLuint>, HalfEdge* >::iterator iter = halfEdges.begin(); HEMetric mc; vector<HEMetric> cc; /* preprocess */ map< pair<GLuint, GLuint>, HalfEdge* > ee; while(iter != halfEdges.end()) { pair<GLuint, GLuint> pq = iter->first; pair<GLuint, GLuint> qp(pq.second, pq.first); if(ee.find(pq) == ee.end() && ee.find(qp) == ee.end()) ee.insert(*iter); iter++; } iter = ee.begin(); vector< pair<GLuint, GLuint> > delList; //store the halfedge with invalid end vertex while(iter != ee.end()) { mc.he = iter->second; if(vertices.find(iter->first.first) != vertices.end() && vertices.find(iter->first.second) != vertices.end()) { Point3D v1 = { vertices[iter->first.first]->coordinate[0], vertices[iter->first.first]->coordinate[1], vertices[iter->first.first]->coordinate[2], }; Point3D v2 = { vertices[iter->first.second]->coordinate[0], vertices[iter->first.second]->coordinate[1], vertices[iter->first.second]->coordinate[2], }; //mc.length = HEMetric::edgeDistance(vertices[iter->first.first]->coordinate, vertices[iter->first.second]->coordinate); mc.length = HEMetric::edgeDistance(v1, v2); cc.push_back(mc); } else { delList.push_back(iter->first); } iter++; } for(int i = 0; i < delList.size(); i++) { halfEdges.erase(delList[i]); } vector<HEMetric>::iterator m = min_element(cc.begin(), cc.end(), mc); GLuint u = m->he->vertex_begin->id; GLuint v = m->he->paired_edge->vertex_begin->id; while(halfEdges.find(make_pair(u, v)) == halfEdges.end()) { printf("cannot find edge %u, %u, regenerate\n", u, v); cc.erase(m); m = min_element(cc.begin(), cc.end(), mc); u = m->he->vertex_begin->id; v = m->he->paired_edge->vertex_begin->id; } //printf("collapse! %u, %u, length: %f\n", u, v, m->length); edgeCollapse(u, v); /*vector< pair<GLuint, GLuint> > delList; //store the halfedge with invalid end vertex while(iter != halfEdges.end()) { mc.he = iter->second; if(iter->second->left_face && !iter->second->left_face->isBoundaryFace) //exclude the boundary edge { if(vertices.find(iter->first.first) != vertices.end() && vertices.find(iter->first.second) != vertices.end()) { Point3D v1 = { vertices[iter->first.first]->coordinate[0], vertices[iter->first.first]->coordinate[1], vertices[iter->first.first]->coordinate[2], }; Point3D v2 = { vertices[iter->first.second]->coordinate[0], vertices[iter->first.second]->coordinate[1], vertices[iter->first.second]->coordinate[2], }; //mc.length = HEMetric::edgeDistance(vertices[iter->first.first]->coordinate, vertices[iter->first.second]->coordinate); mc.length = HEMetric::edgeDistance(v1, v2); cc.push_back(mc); } else { delList.push_back(iter->first); } } iter++; } for(int i = 0; i < delList.size(); i++) { halfEdges.erase(delList[i]); } vector<HEMetric>::iterator m = min_element(cc.begin(), cc.end(), mc); GLuint u = m->he->vertex_begin->id; GLuint v = m->he->paired_edge->vertex_begin->id; while(halfEdges.find(make_pair(u, v)) == halfEdges.end()) { printf("cannot find edge %u, %u, regenerate\n", u, v); cc.erase(m); m = min_element(cc.begin(), cc.end(), mc); u = m->he->vertex_begin->id; v = m->he->paired_edge->vertex_begin->id; } printf("collapse! %u, %u, length: %f\n", u, v, m->length); edgeCollapse(u, v); */ } void edgeCollapse(GLuint u, GLuint v) { pair<GLuint, GLuint> uv(u, v); pair<GLuint, GLuint> vu(v, u); ////calculate new vertex position Point3D mid = { (vertices[u]->coordinate[0] + vertices[v]->coordinate[0]) / 2.0f, (vertices[u]->coordinate[1] + vertices[v]->coordinate[1]) / 2.0f, (vertices[u]->coordinate[2] + vertices[v]->coordinate[2]) / 2.0f, }; HEVertex *hv_mid = new HEVertex(); hv_mid->coordinate[0] = mid[0]; hv_mid->coordinate[1] = mid[1]; hv_mid->coordinate[2] = mid[2]; GLuint hv_mid_id = nextNewIdCount; nextNewIdCount++; hv_mid->id = hv_mid_id; hv_mid->heEdge = halfEdges[uv]->next_edge->next_edge->paired_edge; vertices.insert(make_pair(hv_mid_id, hv_mid)); //// //will paring he11-he12, he21-he22 HalfEdge *he11 = halfEdges[uv]->next_edge->paired_edge; HalfEdge *he12 = halfEdges[uv]->next_edge->next_edge->paired_edge; HalfEdge *he21 = halfEdges[vu]->next_edge->paired_edge; HalfEdge *he22 = halfEdges[vu]->next_edge->next_edge->paired_edge; HEFace *face1 = halfEdges[uv]->left_face; HEFace *face2 = halfEdges[vu]->left_face; vector< pair< pair<GLuint, GLuint>, HalfEdge* > > candidates; //start from u HalfEdge *he = halfEdges[uv]->paired_edge->next_edge; do { candidates.push_back(make_pair(make_pair(he->vertex_begin->id, he->paired_edge->vertex_begin->id), he)); candidates.push_back(make_pair(make_pair(he->paired_edge->vertex_begin->id, he->vertex_begin->id), he->paired_edge)); he = he->paired_edge->next_edge; } while(he != halfEdges[uv]); //start from v he = halfEdges[vu]->paired_edge->next_edge; do { candidates.push_back(make_pair(make_pair(he->vertex_begin->id, he->paired_edge->vertex_begin->id), he)); candidates.push_back(make_pair(make_pair(he->paired_edge->vertex_begin->id, he->vertex_begin->id), he->paired_edge)); he = he->paired_edge->next_edge; } while(he != halfEdges[vu]); halfEdges.erase(uv); halfEdges.erase(vu); //printf("erase uv: %d\n", halfEdges.erase(uv)); //printf("erase vu: %d\n", halfEdges.erase(vu)); for(int i = 0; i < candidates.size(); i++) { pair<GLuint, GLuint> &pq = candidates[i].first; halfEdges.erase(pq); //printf("erase candidates: %d\n", halfEdges.erase(pq)); if(candidates[i].second->id == he12->paired_edge->id || candidates[i].second->id == he21->paired_edge->id || candidates[i].second->id == he11->paired_edge->id || candidates[i].second->id == he22->paired_edge->id ) { candidates[i].second = NULL; continue; } HalfEdge *he = candidates[i].second; if(pq.first == u || pq.first == v) { pq.first = hv_mid_id; he->vertex_begin = hv_mid; } else if(pq.second == u || pq.second == v) { pq.second = hv_mid_id; } else { printf("WTF?\n"); } } //pareing outer halfedges he11->paired_edge = he12; he12->paired_edge = he11; he21->paired_edge = he22; he22->paired_edge = he21; //add what should be add for(int i = 0; i < candidates.size(); i++) { if(candidates[i].second) halfEdges.insert(candidates[i]); } face1->heEdge = NULL; face2->heEdge = NULL; heFaces.erase(face1->id); heFaces.erase(face2->id); //printf("erase face 1: %d\n", heFaces.erase(face1->id)); //printf("erase face 2: %d\n", heFaces.erase(face2->id)); vertices.erase(u); vertices.erase(v); //printf("erase vertices u: %d\n", vertices.erase(u)); //printf("erase vertices v: %d\n", vertices.erase(v)); } }; #endif
true
11021d0dc96348d95e3cb0827a7af62b51527a29
C++
dmkorolevskii/OOP
/milestone/ErrorState.h
UTF-8
619
2.859375
3
[]
no_license
// Header file. Contains constructor, member functions, helper operator, error message declaration // File ErrorState.h // Date: 2018/03/22 // Author: Dmitrii Korolevskii #ifndef AMA_ERRORSTATE_H #define AMA_ERRORSTATE_H namespace AMA{ class ErrorState{ char* errorMessage; public: explicit ErrorState(const char* errorMessage = nullptr); ErrorState(const ErrorState&) = delete; ErrorState& operator=(const ErrorState&) = delete; virtual ~ErrorState(); void clear(); bool isClear() const; void message(const char*); const char* message()const; }; std::ostream& operator<<(std::ostream&, ErrorState&); } #endif
true
262ec91c9e5e154cae2a025eb4bcc323333fde12
C++
Databean/mipsify
/include/mips32/Instruction.h
UTF-8
12,101
2.953125
3
[]
no_license
#ifndef MIPS32_INSTRUCTION_H #define MIPS32_INSTRUCTION_H #include <iostream> #include <string> namespace mips32 { typedef unsigned short Register; extern const Register R_ZERO; extern const Register R_AT; extern const Register R_V0; extern const Register R_V1; extern const Register R_A0; extern const Register R_A1; extern const Register R_A2; extern const Register R_A3; extern const Register R_T0; extern const Register R_T1; extern const Register R_T2; extern const Register R_T3; extern const Register R_T4; extern const Register R_T5; extern const Register R_T6; extern const Register R_T7; extern const Register R_S0; extern const Register R_S1; extern const Register R_S2; extern const Register R_S3; extern const Register R_S4; extern const Register R_S5; extern const Register R_S6; extern const Register R_S7; extern const Register R_T8; extern const Register R_T9; extern const Register R_K0; extern const Register R_K1; extern const Register R_GP; extern const Register R_SP; extern const Register R_S8; extern const Register R_RA; std::string registerStr(Register r); class Instruction; std::ostream &operator<<(std::ostream& output, const Instruction&); /** * Superclass of all MIPS instructions. Globals and labels are included under * this, for simplicity. */ class Instruction { private: public: Instruction(); Instruction(const Instruction&) = delete; virtual ~Instruction(); virtual const Instruction& operator=(const Instruction&) = delete; virtual std::ostream& output(std::ostream& o) const = 0; virtual bool readsRegister(Register) const = 0; virtual bool writesToRegister() const = 0; virtual Register destinationRegister() const = 0; }; class ControlFlowInstruction : public Instruction { public: ControlFlowInstruction(); ControlFlowInstruction(const ControlFlowInstruction&) = delete; virtual ~ControlFlowInstruction(); virtual const ControlFlowInstruction& operator=(const ControlFlowInstruction&) = delete; virtual std::ostream& output(std::ostream& o) const = 0; virtual bool readsRegister(Register) const = 0; virtual bool writesToRegister() const = 0; virtual Register destinationRegister() const = 0; }; /** * Represents a label. This isn't executed directly, but is used for the assembler * to figure out the jump offsets necessary for the jump and branch instructions. */ class Label : public ControlFlowInstruction { private: std::string name; public: Label(const std::string& name); Label(const Label&) = delete; virtual ~Label(); virtual const Label& operator=(const Label&) = delete; virtual std::ostream& output(std::ostream& o) const; virtual bool readsRegister(Register) const; virtual bool writesToRegister() const; virtual Register destinationRegister() const; virtual const std::string& getName() const; }; /** * Instruction to perform an unconditional jump to a specific place in memory. * This takes in a string for which label it is a jump to. */ class Jump : public ControlFlowInstruction { private: std::string target; public: Jump(const std::string& target); Jump(const Jump&) = delete; virtual ~Jump(); virtual const Jump& operator=(const Jump&) = delete; virtual std::ostream& output(std::ostream& o) const; virtual bool readsRegister(Register) const; virtual bool writesToRegister() const; virtual Register destinationRegister() const; virtual const std::string& getTarget() const; }; /** * Instruction to perform an unconditional jump to a location taken from * a register. This takes in the target location register. */ class JumpRegister : public ControlFlowInstruction { private: Register target; public: JumpRegister(Register target); JumpRegister(const JumpRegister&) = delete; virtual ~JumpRegister(); virtual const JumpRegister& operator=(const JumpRegister&) = delete; virtual std::ostream& output(std::ostream& o) const; virtual bool readsRegister(Register) const; virtual bool writesToRegister() const; virtual Register destinationRegister() const; virtual Register getTarget() const; }; /** * Instruction to perform an unconditional jump to the label with the target * string. This also loads the current instruction address into the $ra register, * so that it can be jumped back to at a later point. */ class JumpAndLink : public ControlFlowInstruction { private: std::string target; public: JumpAndLink(const std::string& target); JumpAndLink(const JumpAndLink&) = delete; virtual ~JumpAndLink(); virtual const JumpAndLink& operator=(const JumpAndLink&) = delete; virtual std::ostream& output(std::ostream& o) const; virtual bool readsRegister(Register) const; virtual bool writesToRegister() const; virtual Register destinationRegister() const; virtual const std::string& getTarget() const; }; /** * Instruction that takes two registers and a target to jump to. It will * jump to the target label if the left and right registers are equal, and * will not jump if the two registers are not equal. */ class BranchOnEqual : public ControlFlowInstruction { private: Register left; Register right; std::string target; public: BranchOnEqual(Register left, Register right, const std::string& target); BranchOnEqual(const BranchOnEqual&) = delete; virtual ~BranchOnEqual(); virtual const BranchOnEqual& operator=(const BranchOnEqual&) = delete; virtual std::ostream& output(std::ostream& o) const; virtual bool readsRegister(Register) const; virtual bool writesToRegister() const; virtual Register destinationRegister() const; virtual Register getLeft() const; virtual Register getRight() const; virtual const std::string& getTarget() const; }; /** * Instruction that takes two registers and a target to jump to. It will * jump to the target label if the left and right registers are not equal, and * will not jump if the two registers are equal. */ class BranchNotEqual : public ControlFlowInstruction { private: Register left; Register right; std::string target; public: BranchNotEqual(Register left, Register right, const std::string& target); BranchNotEqual(const BranchNotEqual&) = delete; virtual ~BranchNotEqual(); virtual const BranchNotEqual& operator=(const BranchNotEqual&) = delete; virtual std::ostream& output(std::ostream& o) const; virtual bool readsRegister(Register) const; virtual bool writesToRegister() const; virtual Register destinationRegister() const; virtual Register getLeft() const; virtual Register getRight() const; virtual const std::string& getTarget() const; }; /** * Instruction to store a 32-bit word to a specific location at memory. It takes in * the register containing the data to store, the register containing the location in * memory, and an offset for where to store it relative to the location register. The offset * must be known at compile-time, and is specified as an integer. If the sum of the offset and the * location register is not a multiple of 4, the MIPS processor/emulator will throw an exception * at runtime. */ class StoreWord : public Instruction { private: Register data; Register location; int offset; public: StoreWord(Register data, Register location, int offset); StoreWord(const StoreWord&) = delete; virtual ~StoreWord(); virtual const StoreWord& operator=(const StoreWord&) = delete; virtual std::ostream& output(std::ostream& o) const; virtual bool readsRegister(Register) const; virtual bool writesToRegister() const; virtual Register destinationRegister() const; virtual Register getData() const; virtual Register getLocation() const; virtual int getOffset() const; }; /** * Instruction to load a 32-bit word into a register from a specific location in memory. * It takes in the register to store the data in, the register containing the location in memory, * and an offset for where to read the memory from relative to the location register. The offset * must be known at compile-time, and is specified as an integer. If the sum of the offset and the * location register is not a multiple of 4, the MIPS processor/emulator will throw an exception * at runtime. */ class LoadWord : public Instruction { private: Register data; Register location; int offset; public: LoadWord(Register data, Register location, int offset); LoadWord(const LoadWord&) = delete; virtual ~LoadWord(); virtual const LoadWord& operator=(const LoadWord&) = delete; virtual std::ostream& output(std::ostream& o) const; virtual bool readsRegister(Register) const; virtual bool writesToRegister() const; virtual Register destinationRegister() const; virtual Register getData() const; virtual Register getLocation() const; virtual int getOffset() const; }; /** * Psuedoinstruction that the assembler deals with. The instruction takes a register to load the * address into, and a string for a label in the assembly. The assembler will figure out the * actual integer address of the label, and put in an instruction to load that into the register. */ class LoadAddress : public Instruction { private: Register data; std::string address; public: LoadAddress(Register data, const std::string& address); LoadAddress(const LoadAddress&) = delete; virtual ~LoadAddress(); virtual const LoadAddress& operator=(const LoadAddress&) = delete; virtual std::ostream& output(std::ostream& o) const; virtual bool readsRegister(Register) const; virtual bool writesToRegister() const; virtual Register destinationRegister() const; virtual Register getData() const; virtual const std::string& getAddress() const; }; /** * Not technically an instruction. This creates an integer in the data segment with a specific * label attached to it, that can be referred to by LoadAddress. */ class IntGlobal : public Instruction { private: std::string name; unsigned int value; public: IntGlobal(const std::string& name, unsigned int value = 0); IntGlobal(const IntGlobal&) = delete; virtual ~IntGlobal(); virtual const IntGlobal& operator=(const IntGlobal&) = delete; virtual std::ostream& output(std::ostream& o) const; virtual bool readsRegister(Register) const; virtual bool writesToRegister() const; virtual Register destinationRegister() const; virtual const std::string& getName() const; virtual unsigned int getValue() const; }; /** * Not technically an instruction. This creates an array in the data segment with a specific size * (given in bytes). It can be referred to by LoadAddress. */ class ArrayGlobal : public Instruction { private: std::string name; int size; public: ArrayGlobal(const std::string& name, int size); ArrayGlobal(const ArrayGlobal&) = delete; virtual ~ArrayGlobal(); virtual const ArrayGlobal& operator=(const ArrayGlobal&) = delete; virtual std::ostream& output(std::ostream& o) const; virtual bool readsRegister(Register) const; virtual bool writesToRegister() const; virtual Register destinationRegister() const; virtual const std::string& getName() const; virtual int getSize() const; }; /** * Not technically an instruction. This creates a string in the data segment, with a specific value. * It can be referred to by LoadAddress. */ class StringGlobal : public Instruction { private: std::string name; std::string value; public: StringGlobal(const std::string& name, const std::string& value); StringGlobal(const StringGlobal&) = delete; virtual ~StringGlobal(); virtual const StringGlobal& operator=(const StringGlobal&) = delete; virtual std::ostream& output(std::ostream& o) const; virtual bool readsRegister(Register) const; virtual bool writesToRegister() const; virtual Register destinationRegister() const; virtual const std::string& getName() const; virtual const std::string& getValue() const; }; }; #endif
true
8916ad8e8b2ce0442956da0101ac2fcd5786e2b1
C++
Iraniya/code-for-today-for-everyDay
/code-for-today-for-everyDay/Practice/HackerRank/30Daysofcodes/day10/BinaryNumber/main.cpp
UTF-8
822
2.734375
3
[]
no_license
#include <map> #include <set> #include <list> #include <cmath> #include <ctime> #include <deque> #include <queue> #include <stack> #include <string> #include <bitset> #include <cstdio> #include <limits> #include <vector> #include <climits> #include <cstring> #include <cstdlib> #include <fstream> #include <numeric> #include <sstream> #include <iostream> #include <algorithm> using namespace std; int decimal_binary(int n) /* Function to convert decimal to binary.*/ { int rem,count=0,t=0; while (n>0) { rem=n%2; n/=2; if(rem==1){ count++; if(count>=t) t=count; } else count=0; } return t; } int main(){ int n; cin >> n; int r=0; int s = decimal_binary(n); cout<<s; return 0; }
true
67e4dc7878e2c4ee4a039ee995250358fd7c5137
C++
jzmrexu1s/leetcode-exercises
/LeetCode/Tree BFS/102. Binary Tree Level Order Traversal.cpp
UTF-8
1,360
3.390625
3
[]
no_license
// // Created by Chengwei Zhang on 5/20/20. // /* * 队列 * q.empty() 如果队列为空返回true,否则返回false * q.size() 返回队列中元素的个数 * q.pop() 删除队列首元素但不返回其值 * q.front() 返回队首元素的值,但不删除该元素 * q.push() 在队尾压入新元素 * q.back() 返回队列尾元素的值,但不删除该元素 */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int>> levelOrder(TreeNode* root) { queue<TreeNode*> q; vector<vector<int>> r; TreeNode* p; int size; int i = 0; if (!root) return r; q.push(root); while (!q.empty()) { vector<int> t = {}; r.push_back(t); size = q.size(); i = 0; while (i < size) { p = q.front(); q.pop(); if (p -> left) q.push(p -> left); if (p -> right) q.push(p -> right); r.back().push_back(p -> val); i ++; } } return r; } };
true
e1f587e1ff978bf227208c166967f5cfdf2fcb88
C++
dineshkumares/wotop
/include/logger.h
UTF-8
574
2.65625
3
[ "MIT" ]
permissive
#ifndef LOGGER #define LOGGER #include <iostream> #include <sstream> #include <mutex> enum LogLevel { DEBUG, VERB2, VERB1, INFO, WARN, ERROR}; const LogLevel logLevel = WARN; class logIt { public: logIt(LogLevel l); logIt(LogLevel l, const char *s); template <typename T> logIt & operator<<(T const & value __attribute__((unused))) { // _buffer << value; return *this; } ~logIt(); private: static std::ostringstream _buffer; bool toPrint; static std::mutex llock; }; #define logger(...) logIt(__VA_ARGS__) #endif
true
29a81e96be3328d4d09cc33fbedf6a4855863648
C++
tks3210/Atcoder
/abc126/abc126_d.cpp
UTF-8
1,185
2.65625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; #define MOD 1000000007 #define rep(i, n) for(int i = 0; i < (int)(n); i++) #define show(x) for(auto i: x){cout << i << " ";} #define showm(m) for(auto i: m){cout << m.x << " ";} typedef long long ll; typedef pair<int, ll> P; #define N_OVERSIZE 100050 vector<P> root[N_OVERSIZE]; int color[N_OVERSIZE] = {0}; //white 1, black -1 void dfs(int parent, int now, int now_color){ if (root[now].size() == 1 && now != 0){ return; } for (auto node : root[now]) { if (node.first != parent){ if (node.second%2 == 0){ color[node.first] = now_color; } else { color[node.first] = -now_color; } dfs(now, node.first, color[node.first]); } } } int main() { int n; cin >> n; rep(i, n -1){ int tmpu, tmpv, tmpw; cin >> tmpu >> tmpv >> tmpw; tmpu--; tmpv--; root[tmpu].push_back(P(tmpv, tmpw)); root[tmpv].push_back(P(tmpu, tmpw)); } color[0] = -1; dfs(-1, 0, -1); //white_start rep(i, n){ cout << (color[i] == 1 ? 1: 0) << endl; } }
true
08473746d00438f4816fdada0096ae0e44752ce1
C++
MonkeYKonG/Enchiladas-s-shmup
/lib/my_objects_lib/Panel.cpp
UTF-8
5,562
2.640625
3
[]
no_license
#include "Panel.hpp" namespace my { Panel::Panel() {} Panel::~Panel() {} bool Panel::IsIntersect(const sf::Vector2f & point) const noexcept { return (false); } bool Panel::IsIntersect(const sf::FloatRect & square) const noexcept { return (false); } const sf::FloatRect Panel::GetHitBox() const noexcept { return (sf::FloatRect()); } SpriteObject::SpriteObjectPtr Panel::GetBackground() const noexcept { return (m_background); } Border::BorderPtr Panel::GetBorder() const noexcept { return (m_border); } TextObject::TextObjectPtr Panel::GetTitle() const noexcept { return (m_title); } const Panel::SpriteButtons &Panel::GetSpriteButtons() const noexcept { return (m_spriteButtons); } const Panel::TextButtons &Panel::GetTextButtons() const noexcept { return (m_textButtons); } const Panel::TextList &Panel::GetTexts() const noexcept { return (m_texts); } const Panel::SpriteList &Panel::GetSprites() const noexcept { return (m_sprites); } const Panel::ProgressBarList &Panel::GetProgressBars() const noexcept { return (m_progressBars); } void Panel::SetBackground(SpriteObject::SpriteObjectPtr background) noexcept { m_background = background; } void Panel::SetBorder(Border::BorderPtr border) noexcept { m_border = border; } void Panel::SetTitle(TextObject::TextObjectPtr title) noexcept { m_title = title; m_title->SetOrigin(m_title->GetText().getGlobalBounds().width / 2, m_title->GetText().getGlobalBounds().height / 2); if (m_background) m_title->setPosition(0, -m_background->GetSprite().getGlobalBounds().height / 2 + m_title->GetText().getGlobalBounds().height); } void Panel::SetSpriteButtons(const Panel::SpriteButtons & buttons) noexcept { m_spriteButtons = buttons; } void Panel::AddSpriteButton(const Panel::PanelSpriteButton & newButton) noexcept { m_spriteButtons.push_back(newButton); } void Panel::SetTextButtons(const Panel::TextButtons & buttons) noexcept { m_textButtons.clear(); for (unsigned i = 0; i < buttons.size(); ++i) AddTextButton(buttons[i]); } void Panel::AddTextButton(const Panel::TextButton & newButton) noexcept { m_textButtons.push_back(newButton); newButton->SetOrigin(newButton->GetText().getGlobalBounds().width / 2, newButton->GetText().getGlobalBounds().height / 2); } void Panel::SetTexts(const Panel::TextList & texts) noexcept { m_texts.clear(); for (unsigned i = 0; i < texts.size(); ++i) AddText(texts[i]); } void Panel::AddText(const TextObject::TextObjectPtr & newText) noexcept { m_texts.push_back(newText); newText->SetOrigin(0, newText->GetText().getGlobalBounds().height / 2); } void Panel::SetSprites(const SpriteList & sprites) noexcept { m_sprites.clear(); for (unsigned i = 0; i < sprites.size(); ++i) AddSprite(sprites[i]); } void Panel::AddSprite(const SpriteObject::SpriteObjectPtr & newSprite) noexcept { m_sprites.push_back(newSprite); newSprite->SetOrigin(newSprite->GetHitBox().width / 2, newSprite->GetHitBox().height / 2); } void Panel::SetProgressBars(const ProgressBarList & progressBars) noexcept { m_progressBars.clear(); for (unsigned i = 0; i < progressBars.size(); ++i) AddProgressBars(progressBars[i]); } void Panel::AddProgressBars(const ProgressBar::ProgressBarPtr & newProgressBar) noexcept { m_progressBars.push_back(newProgressBar); } void Panel::UpdateBackground() noexcept { if (!m_background) return; m_background->Update(); } void Panel::UpdateBorder() noexcept { if (!m_border) return; m_border->Update(); } void Panel::UpdateTitle() noexcept { if (!m_title) return; m_title->Update(); } void Panel::UpdateSpriteButtons(const sf::Vector2f & mousePos) noexcept { for (unsigned i = 0; i < m_spriteButtons.size(); ++i) m_spriteButtons[i]->Update(mousePos); } void Panel::UpdateTextButtons(const sf::Vector2f & mousePos) noexcept { for (unsigned i = 0; i < m_textButtons.size(); ++i) m_textButtons[i]->Update(); } void Panel::UpdateButtons(const sf::Vector2f & mousePos) noexcept { UpdateSpriteButtons(mousePos); UpdateTextButtons(mousePos); } void Panel::UpdateSprites() noexcept { for (unsigned i = 0; i < m_sprites.size(); ++i) m_sprites[i]->Update(); } void Panel::UpdateProgressBars() noexcept { for (unsigned i = 0; i < m_progressBars.size(); ++i) m_progressBars[i]->Update(); } void Panel::Update(const sf::Vector2f & mousePos) noexcept { sf::Vector2f tranfromedMousePos; tranfromedMousePos = getTransform().getInverse().transformPoint(mousePos); UpdateBackground(); UpdateBorder(); UpdateTitle(); UpdateButtons(tranfromedMousePos); UpdateSprites(); UpdateProgressBars(); } void Panel::draw(sf::RenderTarget & target, sf::RenderStates states) const noexcept { if (!m_visible) return; Node::draw(target, states); states.transform *= getTransform(); if (m_background) target.draw(*m_background, states); if (m_border) target.draw(*m_border, states); if (m_title) target.draw(*m_title, states); for (unsigned i = 0; i < m_spriteButtons.size(); ++i) target.draw(*m_spriteButtons[i], states); for (unsigned i = 0; i < m_textButtons.size(); ++i) target.draw(*m_textButtons[i], states); for (unsigned i = 0; i < m_texts.size(); ++i) target.draw(*m_texts[i], states); for (unsigned i = 0; i < m_sprites.size(); ++i) target.draw(*m_sprites[i], states); for (unsigned i = 0; i < m_progressBars.size(); ++i) target.draw(*m_progressBars[i], states); } }
true
46268ad742fd3b05db3d3f9064c079de8c4f8983
C++
stdstring/leetcode
/Algorithms/Tasks.1501.2000/1503.LastMomentBeforeAllAntsFallOutOfPlank/solution.cpp
UTF-8
1,030
3.15625
3
[ "MIT" ]
permissive
#include <algorithm> #include <vector> #include "gtest/gtest.h" namespace { class Solution { public: [[nodiscard]] int getLastMoment(int n, std::vector<int> const &left, std::vector<int> const &right) const { const int leftMaxDistance = left.empty() ? 0 : *std::max_element(left.cbegin(), left.cend()); const int rightMaxDistance = right.empty() ? 0 : n - *std::min_element(right.cbegin(), right.cend()); return std::max(leftMaxDistance, rightMaxDistance); } }; } namespace LastMomentBeforeAllAntsFallOutOfPlankTask { TEST(LastMomentBeforeAllAntsFallOutOfPlankTaskTests, Examples) { const Solution solution; ASSERT_EQ(4, solution.getLastMoment(4, {4, 3}, {0, 1})); ASSERT_EQ(7, solution.getLastMoment(7, {}, {0, 1, 2, 3, 4, 5, 6, 7})); ASSERT_EQ(7, solution.getLastMoment(7, {0, 1, 2, 3, 4, 5, 6, 7}, {})); } TEST(LastMomentBeforeAllAntsFallOutOfPlankTaskTests, FromWrongAnswers) { const Solution solution; ASSERT_EQ(5, solution.getLastMoment(9, {5}, {4})); } }
true
7a973d55bf65dfb3b1602dadc5853cef639ddc20
C++
Finalcheat/leetcode
/src/cpp/Maximum-69-Number.cpp
UTF-8
1,278
3.703125
4
[]
no_license
/** * @file Maximum-69-Number.cpp * @brief Maximum 69 Number(https://leetcode.com/problems/maximum-69-number/) * @author Finalcheat * @date 2020-04-12 */ /** * Given a positive integer num consisting only of digits 6 and 9. * Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6). * Example 1: * Input: num = 9669 * Output: 9969 * Explanation: * Changing the first digit results in 6669. * Changing the second digit results in 9969. * Changing the third digit results in 9699. * Changing the fourth digit results in 9666. * The maximum number is 9969. * Example 2: * Input: num = 9996 * Output: 9999 * Explanation: Changing the last digit 6 to 9 results in the maximum number. * Example 3: * Input: num = 9999 * Output: 9999 * Explanation: It is better not to apply any change. */ /** * 将高位的第一个6变成9就是所求的结果 */ class Solution { public: int maximum69Number (int num) { string numStr = std::to_string(num); for (size_t i = 0; i < numStr.size(); ++i) { if (numStr[i] == '6') { numStr[i] = '9'; break; } } return std::stoi(numStr); } };
true
2d5549ddd1bc08465c36d3e2b739244ee1d79281
C++
kriogenia/the-parting-of-sarah
/ThePartingOfSarah/Door.cpp
UTF-8
304
2.65625
3
[ "MIT" ]
permissive
#include "Door.h" Door::Door(string filename, int x, int y, int width, int height, int fileWidth, int fileHeight, Game* game) : MappedTile(filename, x, y, width, height, fileWidth, fileHeight, DOOR_OPEN, game) { } void Door::open() { this->position = 1; } void Door::close() { this->position = 0; }
true
d4775d9f3f14358c505f0ef53ba6fa3b6484716e
C++
ksatyendra/REF
/C++ REF/Ch04pr01.cpp
UTF-8
4,041
3.75
4
[]
no_license
// Program Ch04pr01 // Program to maintain a linked list #include <iostream> using namespace std; class linklist { private : // structure containing a data part and link part struct node { int data ; node * link ; } *p ; public : linklist( ) ; void append ( int num ) ; void addatbeg ( int num ) ; void addafter ( int loc, int num ) ; void display( ) ; int count( ) ; void del ( int num ) ; ~linklist( ) ; } ; // initializes data member linklist :: linklist( ) { p = NULL ; } // adds a node at the end of a linked list void linklist :: append ( int num ) { node *temp, *r ; // if the list is empty, create first node if ( p == NULL ) { p = new node ; p -> data = num ; p -> link = NULL ; } else { // go to last node temp = p ; while ( temp -> link != NULL ) temp = temp -> link ; // add node at the end r = new node ; r -> data = num ; r -> link = NULL ; temp -> link = r ; } } // adds a new node at the beginning of the linked list void linklist :: addatbeg ( int num ) { node *temp ; // add new node temp = new node ; temp -> data = num ; temp -> link = p ; p = temp ; } // adds a new node after the specified number of nodes void linklist :: addafter ( int loc, int num ) { node *temp, *r ; temp = p ; // skip to desired portion for ( int i = 0 ; i < loc ; i++ ) { temp = temp -> link ; // if end of linked list is encountered if ( temp == NULL ) { cout << "\nThere are less than " << loc << " elements in list" << endl ; return ; } } // insert new node r = new node ; r -> data = num ; r -> link = temp -> link ; temp -> link = r ; } // displays the contents of the linked list void linklist :: display( ) { node *temp = p ; cout << endl ; // traverse the entire linked list while ( temp != NULL ) { cout << temp -> data << " " ; temp = temp -> link ; } } // counts the number of nodes present in the linked list int linklist :: count( ) { node *temp = p ; int c = 0 ; // traverse the entire linked list while ( temp != NULL ) { temp = temp -> link ; c++ ; } return c ; } // deletes the specified node from the linked list void linklist :: del ( int num ) { node *old, *temp ; temp = p ; while ( temp != NULL ) { if ( temp -> data == num ) { // if node to be deleted is the // first node in the linked list if ( temp == p ) p = temp -> link ; // deletes the intermediate nodes in the linked list else old -> link = temp -> link ; // free the memory occupied by the node delete temp ; return ; } // traverse the linked list till the last node is reached else { // old points to the previous node old = temp ; // go to the next node temp = temp -> link ; } } cout << "\n\nElement " << num << " not found" ; } // deallocates memory linklist :: ~linklist( ) { node *q ; while ( p != NULL ) { q = p -> link ; delete p ; p = q ; } } int main( ) { linklist l ; l.append ( 14 ) ; l.append ( 30 ) ; l.append ( 25 ) ; l.append ( 42 ) ; l.append ( 17 ) ; cout << "\nElements in the linked list: " ; l.display( ) ; l.addatbeg ( 999 ) ; l.addatbeg ( 888 ) ; l.addatbeg ( 777 ) ; cout << "\n\nElements in the linked list after addition at the beginning: " ; l.display( ) ; l.addafter ( 7, 0 ) ; l.addafter ( 2, 1 ) ; l.addafter ( 5, 99 ) ; cout << "\n\nElements in the linked list after addition at given position: " ; l.display( ) ; cout << "\nNo. of elements in the linked list " << l.count( ) ; l.del ( 99 ) ; l.del ( 1 ) ; l.del ( 10 ) ; cout << "\n\nElements in the linked list after deletion: " ; l.display( ) ; cout << "\nNo. of elements in the linked list: " << l.count( ) ; system("pause"); }
true
caca00dd2469fe57ce9b1a55cdf35aec030ee8d8
C++
j-p-e-g/AdventOfCode2017
/AdventOfCode/December21b.cpp
UTF-8
4,821
2.8125
3
[]
no_license
#include "stdafx.h" #include <iostream> #include "CoordPoint.h" #include "December21b.h" #include "Matrix.h" using namespace AdventOfCode::December21; PixelPatternB::PixelPatternB(const std::string& fileName) : PixelPattern() { ReadFile(fileName); } void PixelPatternB::OutputResultToConsole() const { std::cout << "December21.b: result = " << CountActivePixels() << std::endl; } bool PixelPatternB::ProcessRules(int numIterations) { int remainingIterations = ApplyRulesToMatrix(m_pattern, numIterations, true); std::cout << " final matrix size after " << numIterations << " iterations: " << m_pattern->GetWidth() << std::endl; return (remainingIterations == 0); } int PixelPatternB::ApplyRulesToMatrix(std::shared_ptr<Matrix::CharMatrix>& matrix, int numIterations, bool first) { if (numIterations <= 0) { // nothing else to do std::cout << "Invalid numIterations " << numIterations << "!" << std::endl; return -1; } const bool was4x4 = (matrix->GetWidth() == 4 && matrix->GetHeight() == 4); const std::string startPattern = DescribeMatrix(matrix); int remainingIterations = numIterations; if (was4x4) { auto& foundPattern = m_4x4Transformations.find(startPattern); if (foundPattern == m_4x4Transformations.end()) { // try the rotations instead const auto& foundRotation = m_4x4Rotations.find(startPattern); if (foundRotation != m_4x4Rotations.end()) { foundPattern = m_4x4Transformations.find(foundRotation->second); } } if (foundPattern != m_4x4Transformations.end()) { std::string pattern; for (int k = numIterations; k > 0; k--) { const auto& foundIterations = foundPattern->second.find(k); if (foundIterations != foundPattern->second.end()) { pattern = foundIterations->second; remainingIterations = numIterations - k; break; } } if (remainingIterations < numIterations) { matrix->Clear(); CreateMatrix(pattern, matrix); if (remainingIterations == 0) { return remainingIterations; } } } } if (matrix->GetWidth() >= 2 && matrix->GetWidth() <= 3) { if (!ApplyRulesToSubMatrix(matrix)) { return -1; } if (first && remainingIterations > 1) { return ApplyRulesToMatrix(matrix, remainingIterations - 1, false); } return remainingIterations - 1; } // try to split into submatrices of size 4, 2 or 3 std::map<Coord::Point, std::shared_ptr<Matrix::CharMatrix>> subMatrices; if ((was4x4 || !SplitMatrix(matrix, 4, subMatrices)) && !SplitMatrix(matrix, 2, subMatrices) && !SplitMatrix(matrix, 3, subMatrices)) { return -1; } int newRemainingIterations = -1; for (auto& m : subMatrices) { newRemainingIterations = ApplyRulesToMatrix(m.second, remainingIterations, false); if (newRemainingIterations < 0) { return -1; } } remainingIterations = newRemainingIterations; int oldMatrixSize = matrix->GetWidth(); if (!CombineMatrices(subMatrices, matrix)) { return -1; } if (remainingIterations > 0) { remainingIterations = ApplyRulesToMatrix(matrix, remainingIterations, false); if (remainingIterations < 0) { return -1; } } if (was4x4) { const std::string targetPattern = DescribeMatrix(matrix); auto& foundPattern = m_4x4Transformations.find(startPattern); if (foundPattern == m_4x4Transformations.end()) { std::map<int, std::string> patternMap; patternMap.emplace(numIterations, targetPattern); m_4x4Transformations.emplace(startPattern, patternMap); // store all rotations std::shared_ptr<Matrix::CharMatrix> startMatrix = std::make_shared<Matrix::CharMatrix>(); CreateMatrix(startPattern, startMatrix); std::set<std::string> rotations; GatherAllDescriptions(startMatrix, rotations); for (const auto& rot : rotations) { if (rot != startPattern) { m_4x4Rotations.emplace(rot, startPattern); } } } else { foundPattern->second.emplace(numIterations, targetPattern); } } return remainingIterations; }
true
73c020040d9574d95d21172fbaea715f6ea074d7
C++
preethichandra20/LeetCode
/Arrays/Easy/sortarraybyincreasingfrequency.cpp
UTF-8
723
2.609375
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int main(){ vector<int> nums={-1,1,-6,4,5,-6,1,4,1}; int n=nums.size(); map<int,int,greater<int>> mp; for(int i=0;i<nums.size();i++) { mp[nums[i]]++; } multimap<int,int> mp1; map<int,int>:: iterator itr; for(itr=mp.begin();itr!=mp.end();itr++) { mp1.insert({itr->second,itr->first}); } multimap<int,int>:: iterator itr1; nums.clear(); for(itr1=mp1.begin();itr1!=mp1.end();itr1++) { int key=itr1->first; int val=itr1->second; while(key!=0) { nums.push_back(val); key--; } } for(int i=0;i<n;i++){ cout<<nums[i]<<" "; } }
true
fc52b9cd5bca7b2bb243fefdbfeeb618ce0333cb
C++
phirasit/MyLib
/BinomialHeap.cpp
UTF-8
2,688
3.25
3
[]
no_license
#ifndef BINOMIAL_HEAP #define BINOMIAL_HEAP #include <vector> using namespace std; template<class Data> class BinomialHeap { public : class iterator { public : int id, deg; Data key; iterator *parent, *left, *right, *left_child; iterator(Data k) : key(k), deg(0), parent(NULL), left(NULL), left_child(NULL), right(NULL) {} ~iterator(void) {} }; int total_size; vector<iterator*> root; int min_idx; bool empty(void) { return min_idx == -1; } int size(void) { return total_size; } void insert_root(iterator *new_node) { if(new_node->deg >= root.size()) { root.resize(new_node->deg+1, NULL); } while(root[new_node->deg] != NULL) { iterator *v = root[new_node->deg]; if(v->key < new_node->key) { swap(new_node, v); } v->parent = new_node; v->left = NULL; v->right = new_node->left_child; if(v->right != NULL) v->right->left = v; new_node->left_child = v; root[new_node->deg++] = NULL; if(new_node->deg >= root.size()) { root.resize(new_node->deg+1, NULL); } } root[new_node->deg] = new_node; if(min_idx == -1 or root[min_idx] == NULL or root[new_node->deg]->key < root[min_idx]->key) { min_idx = new_node->deg; } } iterator* push(Data new_data) { iterator *new_node = new iterator(new_data); insert_root(new_node); total_size++; return new_node; } void decreasekey(iterator *current, Data new_key) { current->key = new_key; iterator *ancestor = current->parent; while(ancestor != NULL and current->key < ancestor->key) { swap(current->key, ancestor->key); current = current->parent; ancestor = ancestor->parent; } } void pop(void) { if(empty()) { return; } iterator *v = root[min_idx]->left_child; root[min_idx] = NULL; delete root[min_idx]; root[min_idx] = NULL; min_idx = -1; while(v != NULL) { iterator *nxt = v->right; v->parent = v->left = v->right = NULL; insert_root(v); v = nxt; } int last = 0; min_idx = -1; for(int i = 0;i < root.size();i++) { if(root[i] != NULL) { if(min_idx == -1 or root[i]->key < root[min_idx]->key) { min_idx = i; } last = i; } } root.resize(last+1, NULL); total_size--; } Data top(void) { if(not empty()) { return root[min_idx]->key; } } void meld(BinomialHeap<Data> H2) { if(empty()) return H2; if(H2.empty()) return *this; for(int i = 0;i < H2->root.size();i++) { if(H2->root[i] != NULL) { insert_root(H2->root[i]); } } } BinomialHeap(void) : min_idx(-1), total_size(0) {} }; #endif
true
dcaca1775ae31f1bf3960d98317b433a5e1a265a
C++
JSYoo5B/TIL
/PS/BOJ/2010/2010.cc
UTF-8
237
2.96875
3
[]
no_license
#include <iostream> using namespace std; int main(void) { int n_taps; cin >> n_taps; int total_holes = 1; for (int i = 0; i < n_taps; i++) { int n_holes; cin >> n_holes; total_holes += n_holes - 1; } cout << total_holes; }
true
e3b0698c128f0743b1d2243ae97a1b38e9f87d90
C++
mam28/cpp_for_profi
/ch02/listing_02_07.cpp
UTF-8
367
3.046875
3
[]
no_license
// Программа с логическими операторами #include <cstdio> int main() { bool t = true; bool f = false; printf("!true : %d\n", !t); printf("true && false: %d\n", t && f); printf("true && !false: %d\n", t && !f); printf("true || false: %d\n", t || f); printf("false || false: %d\n", f || f); return 0; }
true