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
76ef3d60971cd9b285d0967522384d9661c0890b
C++
moukayz/AlgorithmTraining
/leetcode/344.cpp
UTF-8
971
4.25
4
[ "MIT" ]
permissive
/* Reverse String Write a function that reverses a string. The input string is given as an array of characters char[]. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. You may assume all the characters consist of printable ascii characters. Example 1: Input: ["h","e","l","l","o"] Output: ["o","l","l","e","h"] Example 2: Input: ["H","a","n","n","a","h"] Output: ["h","a","n","n","a","H"] */ #include <string> #include <vector> #include <iostream> #include <algorithm> using namespace std; class Solution { public: void reverseString(vector<char> &s) { auto len = s.size(); for (auto i = 0; i < len / 2; i++) { swap(s[i], s[len - i - 1]); } } }; int main() { vector<char> s = {'h', 'e', 'l', 'l', 'o'}; Solution().reverseString(s); for_each(s.begin(), s.end(), [](const char &x) { cout << x; }); cout << "\n"; }
true
5677bb9ffbb4ffdf583cb088beb2022b36e2f7e3
C++
VladasZ/Homework
/C++/Урок 32 - Виртуальные функции/Урок 32 - Виртуальные функции/Square.cpp
UTF-8
852
3.84375
4
[]
no_license
class Square{ public: virtual float square() = 0; }; class Rectangle: public Square{ public: int high; int length; Rectangle(int high, int length) : high(high), length(length){} virtual float square(){ return high*length; } }; class Circle : public Square{ public: int radius; Circle(int radius):radius(radius){} virtual float square(){ return radius*radius*3.14159262358; } }; class RightTriangle : public Square{ public: int high; int length; RightTriangle(int high, int length) : high(high), length(length){} virtual float square(){ return high*length/2; } }; class Trapeze : public Square{ public: int high; int topSide; int bottomSide; Trapeze(int high, int topSide, int bottomSide) : high(high), topSide(topSide), bottomSide(bottomSide) {} virtual float square(){ return (topSide+bottomSide)*high / 2; } };
true
ee4691971eb22afb223b391dd9c50776445ee433
C++
Etherealblade/Programming-Contest-Challenge-Book
/Chapter04/Section4-2/Nim/Nim/Nim.cpp
UTF-8
482
2.84375
3
[]
no_license
/* Page 311 */ #include <iostream> #include <algorithm> using namespace std; #define MAX_N 1024 int N, Arr[MAX_N]; void solve() { int x = 0; for (int i = 0; i < N; i++) { x ^= Arr[i]; } if (x != 0) { puts("Alice"); } else { puts("Bob"); } } int main() { FILE *file; freopen_s(&file, "input.txt", "r", stdin); int count = 2; while (count>0) { cin >> N; for (int i = 0; i < N; i++) { cin >> Arr[i]; } solve(); count--; } return 0; }
true
6d8ef61f883f2f6fc5eeaee6b6cf8cfdf0c5aa44
C++
HarshRaikwar/Leetcode-Submissions
/788.cpp
UTF-8
730
2.8125
3
[]
no_license
class Solution { public: int rotatedDigits(int n) { unordered_set<int> valid; valid.insert({2,5,6,9}); unordered_set<int> invalid; invalid.insert({3,4,7}); int count = 0; for(int i=1 ; i<=n ; i++){ int num = i; int flag = 1, cnt=0; while(num){ int d = num%10; if(invalid.find(d) != invalid.end()){ flag = 0; break; } if(valid.find(d) != valid.end()){ cnt++; } num /= 10; } if(flag && cnt>=1)count++; } return count; } };
true
dbb74a610e1e35c071acab22ff59083845f063cc
C++
bbw7561135/Numerical-Algorithms-2020
/001.cpp
UTF-8
6,260
2.71875
3
[]
no_license
#include<iostream> #include<cmath> #include<fstream> using namespace std; ///////////////////////////////////////////// //2nd-order finite-volume implementation of inviscid Burger's //with piecewise linear slope reconstruction //u_t + u*u_x = 0 with outflow conditions ///////////////////////////////////////////// //limiter is to reduce the slope near extreme //in case of overshoot or undershoot see Page76 of Zingale double max_u(double u[], int indlo,int indhi) { double temp = 0.0; for(int i=indlo; i<=indhi; i++) { if(fabs(u[i])>temp) { temp = fabs(u[i]); } } return temp; } ///////////////////////////////////////// //fill the boundary void fill_ghostcells(double u[],int indlo,int indhi,int ng) { ///////////////fill the boundary/////////////// for(int i=0;i<ng;i++) { //outflow u[indlo-1-i] = u[indlo]; //left u[indhi+1+i] = u[indhi]; } } //////////////////////////////////////////// //calculate the left and right interface states void cal_states_update(double u[], double unew[], double dx, double dt, int indlo, int indhi,int nx, int ng) { double slope[nx+2*ng]; double ul[nx+2*ng]; double ur[nx+2*ng]; double flux[nx+2*ng]; //MC limiter int ibegin = indlo -1; int iend = indhi + 1; double dc[nx+2*ng]; double dl[nx+2*ng]; double dr[nx+2*ng]; double d1[nx+2*ng]; double d2[nx+2*ng]; double ldeltau[nx+2*ng]; double shock_speed[nx+2*ng]; double ushock[nx+2*ng]; double urare[nx+2*ng]; double us[nx+2*ng]; for(int i=0;i<nx+2*ng;i++) { slope[i]=0.0; ul[i]=0.0; ur[i]=0.0; flux[i]=0.0; dc[i]=0.0; dl[i]=0.0; dr[i]=0.0; d1[i]=0.0; d2[i]=0.0; ldeltau[i]=0.0; shock_speed[i]=0.0; ushock[i]=0.0; urare[i]=0.0; us[i]=0.0; } //////////////////////////////////////MC limiter for(int i=ibegin; i<=iend; i++) { dc[i] = 0.5*(u[i+1]-u[i-1]); dl[i] = u[i+1]-u[i]; dr[i] = u[i] - u[i-1]; } for(int i=ibegin; i<=iend; i++) { if(fabs(dl[i])<fabs(dr[i])) { d1[i] = dl[i]; } else { d1[i] = dr[i]; } } for(int i=ibegin; i<=iend; i++) { if(fabs(dc[i])<fabs(d1[i])) { d2[i] = dc[i]; } else { d2[i] = d1[i]; } } for(int i=ibegin; i<=iend; i++) { if(dl[i]*dr[i]>0.0) { ldeltau[i] = d2[i]; } else { ldeltau[i] = 0.0; } } ///////////////////////////////////////////// for(int i=ibegin; i<=iend; i++) { ul[i+1] = u[i] + 0.5*(1.0-u[i]*dt/dx)*ldeltau[i]; ur[i] = u[i] - 0.5*(1.0+u[i]*dt/dx)*ldeltau[i]; } /////Riemann solver for(int i=0;i<nx+2*ng;i++) { shock_speed[i]= 0.5*(ul[i]+ur[i]); } for(int i=0;i<nx+2*ng;i++) { if(shock_speed[i]>0.0) { ushock[i]=ul[i]; } else { ushock[i]=ur[i]; } if(shock_speed[i]<1.0e-5) { ushock[i] = 0.0; } } for(int i=0;i<nx+2*ng;i++) { if(ur[i] < 0.0) { urare[i]=ur[i]; } else { urare[i]=0.0; } } for(int i=0;i<nx+2*ng;i++) { if(ul[i] > 0.0) { urare[i]=ul[i]; } else { urare[i]=urare[i]; } } for(int i=0;i<nx+2*ng;i++) { if(ul[i]>ur[i]) { us[i]=ushock[i]; } else { us[i]=urare[i];//this is u_i+0.5^n+0.5 in eq 6.16 } } for(int i=indlo;i<=indhi;i++) { unew[i] = u[i] + dt/dx*(0.5*us[i]*us[i]-0.5*us[i+1]*us[i+1]); } } /////////////////////////////////// int main() { //assign the initial conditions and grid int nx = 256;//nums of cells not include the ghost cells int ng = 2;//nums of ghost cells each boundary double xmin = 0.0;//left boundary of domian double xmax = 1.0;//right boundary of domian double cfl = 0.8;//cfl num double time = 0.0;//begin time double tmax = 0.22;//(xmax-xmin)/1.0;//tmax based on period for unit velocity int index_low = ng;//the first domain cell index int index_high = ng+nx-1;//the last domian cell index double dx = (xmax-xmin)/nx;//the cell width double x[nx+2*ng];//cell center position for(int i=0;i<nx+2*ng;i++) { x[i] = xmin + (i-ng+0.5)*dx;//use illustration to calculate //cout << (i-ng) << '\t' <<x[i] << endl; } double xl[nx+2*ng];//cell left boundary for(int i=0;i<nx+2*ng;i++) { xl[i] = xmin + (i-ng)*dx; //cout << (i-ng) << '\t' <<xl[i] << endl; } double xr[nx+2*ng];//cell right boundary for(int i=0;i<nx+2*ng;i++) { xr[i] = xmin + (i-ng+1.0)*dx; //cout << (i-ng) << '\t' << xr[i] << endl; } double u[nx+2*ng];//the solution double unew[nx+2*ng];//the update solution for(int i=0;i<nx+2*ng;i++) { u[i] = 0.0; unew[i] = 0.0; } //init the profile for(int i=0;i<nx+2*ng;i++) { u[i] = 1.0; if(x[i] > 0.5) { u[i] = 2.0; } } double timestep = cfl*dx/max_u(u,index_low,index_high); //main evoulution loop while(time < tmax) { fill_ghostcells(u,index_low,index_high,ng); timestep=cfl*dx/max_u(u,index_low,index_high); if(time+timestep>tmax) { timestep = tmax - time; } //get the interface states //cal riemann problem and update the solution cal_states_update(u, unew, dx, timestep, index_low, index_high, nx, ng); for(int i=0;i<nx+2*ng;i++) { u[i] = unew[i]; } time = time + timestep; } ofstream myfile("burgers022.dat"); myfile.precision(10); for(int i=ng;i<=ng+nx-1;i++) { myfile << x[i] << '\t' << u[i] << endl; } myfile.close(); return 0; }
true
8916b38213c056e4cd4443144e692a4912c5adff
C++
AshleySetter/AdventOfCode2019
/day2/part2.cpp
UTF-8
2,617
3.609375
4
[]
no_license
#include <iostream> #include <string> #include <fstream> #include <sstream> #include <vector> #include <typeinfo> // pass vector by reference as passing the vector intself creates a copy void read_initial_state(std::vector<int> &Intcode){ std::ifstream readfile; std::string filetext; readfile.open("input.txt"); getline(readfile, filetext); readfile.close(); // std::cout << filetext << "\n"; std::stringstream ss(filetext); // ss >> i reads the stringstream ss and because i is an integer // it reads characters which make up an integer until it gets // a character which can't be in a integer and stops // it also returns the condition true while integers are found // and returns false when an integer is not found so it // can't put any integer into i for(int i; ss >> i;){ Intcode.push_back(i); // pushes the extracted integer into the vector Intcode if (ss.peek() == ','){ // ss.peak returns the next character in the input sequence // without extracting it - allows you to check what it is ss.ignore(); // this line extracts the character from the input sequence and discards it // this is only performed if the next char is a ',' } } /* for(auto i = Intcode.begin(); i != Intcode.end(); i++){ std::cout << *i << "\n"; }*/ return; } // in this case we want to work on a copy of the original vector so we do not pass it as a reference int compute_output(int noun, int verb, std::vector<int> Intcode){ std::string token; Intcode.at(1) = noun; Intcode.at(2) = verb; for(int i=0; Intcode.at(i) != 99; i+=4){ if (Intcode.at(i) == 1){ Intcode.at(Intcode.at(i+3)) = Intcode.at(Intcode.at(i+1)) + Intcode.at(Intcode.at(i+2)); } else if (Intcode.at(i) == 2){ Intcode.at(Intcode.at(i+3)) = Intcode.at(Intcode.at(i+1)) * Intcode.at(Intcode.at(i+2)); } else{ std::cout << "Invalid Opcode, " << "got opcode " << Intcode.at(i) << "\n"; return -1; } } /* for(auto i = Intcode.begin(); i != Intcode.end(); i++){ std::cout << *i << "\n"; }*/ return Intcode.at(0); } int part2(){ std::vector<int> Intcode; int output; read_initial_state(Intcode); /* for(auto i = Intcode.begin(); i != Intcode.end(); i++){ std::cout << *i << "\n"; }*/ for(int noun=0; noun<100; noun++){ for(int verb=0; verb<100; verb++){ output = compute_output(noun, verb, Intcode); if(output == 19690720){ return 100*noun + verb; } } } return -1; } int main(){ int result; result = part2(); std::cout << result << "\n"; return 0; }
true
40661c37fc7934aab94bdf71db6eb25869d3f1d4
C++
blajzer/laminaFS
/src/util/Semaphore.h
UTF-8
627
2.890625
3
[ "MIT" ]
permissive
#pragma once // LaminaFS is Copyright (c) 2016 Brett Lajzer // See LICENSE for license information. #include <condition_variable> #include <mutex> #include <cstdio> namespace laminaFS { namespace util { class Semaphore { public: Semaphore(uint32_t value = 0) : _value(value) {} ~Semaphore() {} void notify() { { std::unique_lock<std::mutex> lock(_mutex); ++_value; } _cond.notify_one(); } void wait() { std::unique_lock<std::mutex> lock(_mutex); while (_value == 0) { _cond.wait(lock); } --_value; } private: std::condition_variable _cond; std::mutex _mutex; volatile uint32_t _value; }; } }
true
243f587eccacf598e58bd4c42daff623dff1dcb1
C++
chastis/TickTackToe
/Tick_Tack_Toe/Game.cpp
UTF-8
14,429
2.875
3
[]
no_license
#include "Game.h" #include <iostream> //size of cell in px #define CELL_SIZE 160 void merge(std::vector<Attack> &lines) { for (int i = 0; i < lines.size(); i++) { for (int j = i + 1; j < lines.size(); j++) { if (lines[i].line.end == lines[j].line.start && lines[i].line.type == lines[j].line.type) { lines[i].line.end = lines[j].line.end; lines[i].line.len += lines[j].line.len - 1; lines.erase(lines.begin() + j); i--; break; } if (lines[i].line.start == lines[j].line.end && lines[i].line.type == lines[j].line.type) { lines[i].line.start = lines[j].line.start; lines[i].line.len += lines[j].line.len - 1; lines.erase(lines.begin() + j); i--; break; } } } } int amount_nearby_cell(Game &game, int x, int y, cell this_cell) { int answer = 0; if (x != 0 && game._field[x - 1][y] == this_cell) answer++; if (x != game._size - 1 && game._field[x + 1][y] == this_cell) answer++; if (y != 0 && game._field[x][y - 1] == this_cell) answer++; if (y != game._size - 1 && game._field[x][y + 1] == this_cell) answer++; if (x != 0 && y != 0 && game._field[x - 1][y - 1] == this_cell) answer++; if (x != game._size - 1 && y != 0 && game._field[x + 1][y - 1] == this_cell) answer++; if (x != 0 && y != game._size - 1 && game._field[x - 1][y + 1] == this_cell) answer++; if (x != game._size - 1 && y != game._size - 1 && game._field[x + 1][y + 1] == this_cell) answer++; return answer; } int count_weight(std::vector<Attack>& attacks, int x, int y, int win_points) { int max_w = 0; //fork like in chess int count_of_fork = 0; for (int i = 0; i < attacks.size(); i++) { int temp_w = 0; if (attacks[i].is_content(x, y)) { //variants of forks if (attacks[i].potential == 2 && attacks[i].line.len == win_points - 2 || attacks[i].potential == 1 && attacks[i].line.len == win_points - 1 || attacks[i].space == 1 && attacks[i].line.len == win_points - 2 ) { count_of_fork++; } if (attacks[i].line.type == lines_type::point) { if (temp_w < 1) temp_w = 1; } else { //max possible dangereos; if (attacks[i].line.len == win_points) { temp_w = 99999; } //very dangereos; else if (attacks[i].line.len == win_points - 1 && attacks[i].potential == 2) { temp_w = 10000; } else { temp_w = attacks[i].line.len * attacks[i].line.len * 100 * attacks[i].potential; if (attacks[i].space > 0) temp_w += 200 / attacks[i].space; } } } max_w += temp_w; } if (count_of_fork >= 1) { max_w += count_of_fork * 1001; } if (max_w > 99999) max_w = 99999; return max_w; } Attack::Attack() { potential = -42; space = -42; } Attack::Attack(Game& game, int x1, int y1, int x2, int y2, cell my_cell) { { Line temp(x1, y1, x2, y2); line = temp; } potential = 8; space = -42; if (line.type == lines_type::point) { Point p(line.start.x, line.start.y); if (p.x == 0 || game._field[p.x - 1][p.y] != cell::empty) potential--; if (p.x == game._size - 1 || game._field[p.x + 1][p.y] != cell::empty) potential--; if (p.y == 0 || game._field[p.x][p.y - 1] != cell::empty) potential--; if (p.y == game._size - 1 || game._field[p.x][p.y + 1] != cell::empty) potential--; if (p.x == 0 || p.y == 0 || game._field[p.x - 1][p.y - 1] != cell::empty) potential--; if (p.x == game._size - 1 || p.y == 0 || game._field[p.x + 1][p.y - 1] != cell::empty) potential--; if (p.x == 0 || p.y == game._size - 1 || game._field[p.x - 1][p.y + 1] != cell::empty) potential--; if (p.x == game._size - 1 || p.y == game._size - 1 || game._field[p.x + 1][p.y + 1] != cell::empty) potential--; } else { //this cannot happen!!! std::cout << "NANI1\n"; } } void Attack::update(Game &game, cell my_cell) { potential = 2; space = -42; auto checking = [&](int &attack_place, int &temp_space, int &temp_x, int &temp_y) { if (game._field[temp_x][temp_y] == cell::empty) { attack_place++; temp_space++; } else { if (game._field[temp_x][temp_y] == my_cell) if (temp_space != 0 && (space <= 0 || temp_space < space)) space = temp_space; return false; } return true; }; auto vertical_search = [&](int &attack_place) { //start pos int temp_x = line.start.x, temp_y = line.start.y; //space to next attack int temp_space = 0; //search while (temp_y != 0) { temp_y--; if (!checking(attack_place, temp_space, temp_x, temp_y)) break; } //start pos temp_x = line.end.x; temp_y = line.end.y; //space to next attack temp_space = 0; while (temp_y != game._size - 1) { temp_y++; if (!checking(attack_place, temp_space, temp_x, temp_y)) break; } }; auto horizontal_search = [&](int &attack_place) { //start pos int temp_x = line.start.x, temp_y = line.start.y; //space to next attack int temp_space = 0; //search while (temp_x != 0) { temp_x--; if (!checking(attack_place, temp_space, temp_x, temp_y)) break; } //start pos temp_space = 0; temp_x = line.end.x; temp_y = line.end.y; while (temp_x != game._size - 1) { temp_x++; if (!checking(attack_place, temp_space, temp_x, temp_y)) break; } }; auto bot_left_top_right_search = [&](int &attack_place) { //start pos int temp_x = line.start.x, temp_y = line.start.y; //space to next attack int temp_space = 0; //search while (temp_x != 0 && temp_y != game._size - 1) { temp_y++; temp_x--; if (!checking(attack_place, temp_space, temp_x, temp_y)) break; } //start pos temp_space = 0; temp_x = line.end.x; temp_y = line.end.y; while (temp_x != game._size - 1 && temp_y != 0) { temp_y--; temp_x++; if (!checking(attack_place, temp_space, temp_x, temp_y)) break; } }; auto bot_right_top_left_search = [&](int &attack_place) { //start pos int temp_x = line.start.x, temp_y = line.start.y; //space to next attack int temp_space = 0; //search while (temp_y != 0 && temp_x != 0) { temp_y--; temp_x--; if (!checking(attack_place, temp_space, temp_x, temp_y)) break; } //start pos temp_space = 0; temp_x = line.end.x; temp_y = line.end.y; while (temp_y != game._size - 1 && temp_x != game._size - 1) { temp_y++; temp_x++; if (!checking(attack_place, temp_space, temp_x, temp_y)) break; } }; switch (line.type) { case lines_type::vertical: { //check attack place //we already have some points int attack_place = line.len; vertical_search(attack_place); if (attack_place < game._win_points) { potential = 0; break; } //check limits if (line.start.y == 0 || game._field[line.start.x][line.start.y - 1] != cell::empty) potential--; if (line.end.y == game._size - 1 || game._field[line.end.x][line.end.y + 1] != cell::empty) potential--; break; } case lines_type::horizontal: { //check attack place //we already have some points int attack_place = line.len; horizontal_search(attack_place); if (attack_place < game._win_points) { potential = 0; break; } //check limits if (line.start.x == 0 || game._field[line.start.x - 1][line.start.y] != cell::empty) potential--; if (line.end.x == game._size - 1 || game._field[line.end.x + 1][line.end.y] != cell::empty) potential--; break; } case lines_type::bot_left_top_right: { //check attack place //we already have some points int attack_place = line.len; bot_left_top_right_search(attack_place); if (attack_place < game._win_points) { potential = 0; break; } //check limits if (line.start.x == 0 || line.start.y == game._size - 1 || game._field[line.start.x - 1][line.start.y + 1] != cell::empty) potential--; if (line.end.x == game._size - 1 || line.end.y == 0 || game._field[line.end.x + 1][line.end.y - 1] != cell::empty) potential--; break; } case lines_type::bot_right_top_left: { //check attack place //we already have some points int attack_place = line.len; bot_right_top_left_search(attack_place); if (attack_place < game._win_points) { potential = 0; break; } if (line.start.x == 0 || line.start.y == 0 || game._field[line.start.x - 1][line.start.y - 1] != cell::empty) potential--; if (line.end.x == game._size - 1 || line.end.y == game._size - 1 || game._field[line.end.x + 1][line.end.y + 1] != cell::empty) potential--; break; } case lines_type::point: { potential = 8; Point p(line.start.x, line.start.y); if (p.x == 0 || game._field[p.x - 1][p.y] != cell::empty) potential--; if (p.x == game._size - 1 || game._field[p.x + 1][p.y] != cell::empty) potential--; if (p.y == 0 || game._field[p.x][p.y - 1] != cell::empty) potential--; if (p.y == game._size - 1 || game._field[p.x][p.y + 1] != cell::empty) potential--; if (p.x == 0 || p.y == 0 || game._field[p.x - 1][p.y - 1] != cell::empty) potential--; if (p.x == game._size - 1 || p.y == 0 || game._field[p.x + 1][p.y - 1] != cell::empty) potential--; if (p.x == 0 || p.y == game._size - 1 || game._field[p.x - 1][p.y + 1] != cell::empty) potential--; if (p.x == game._size - 1 || p.y == game._size - 1 || game._field[p.x + 1][p.y + 1] != cell::empty) potential--; //space to next attack int temp_space = 0; //start pos int temp_x = line.start.x, temp_y = line.start.y; // int attack_place = line.len; ///search vertical vertical_search(attack_place); ///search horizontal //start pos temp_space = 0; temp_x = line.end.x; temp_y = line.end.y; horizontal_search(attack_place); ///search from bottom left to top right //start pos bot_left_top_right_search(attack_place); ///search from bottom right to top left //start pos temp_space = 0; temp_x = line.end.x; temp_y = line.end.y; bot_right_top_left_search(attack_place); break; } } } void Attack::print() { line.print(); std::cout << " p: " << potential << " s: " << space << std::endl; } bool Attack::is_content(int x, int y) { switch (line.type) { case lines_type::horizontal: { if (line.start.y == y && line.start.x <= x && line.end.x >= x) return true; else return false; } case lines_type::vertical: { if (line.start.x == x && line.start.y <= y && line.end.y >= y) return true; else return false; } case lines_type::bot_left_top_right: { if (x - line.start.x == line.start.y - y && line.end.x - x == y - line.end.y) return true; else return false; } case lines_type::bot_right_top_left: { if (x - line.start.x == y - line.start.y && line.end.x - x == line.end.y - y) return true; else return false; } case lines_type::point: { if (x == line.start.x && y == line.start.y) return true; else return false; } } return false; } Game::Game(size_t n) { _playing = true; _first_p_turn = true; //we don't have latest point _last_x = 42; _last_y = 42; //sfml staff _texture.loadFromFile("images/xo6.png"); _sprite.setTexture(_texture); //by task _size = n; _turns = _size * _size; _win_points = _size <= 3 ? _size : _size < 8 ? 3 : _size > 11 ? 5 : 4; _prev_size = n; //scale's staff x_scale = y_scale = (float) 640 / (_size * CELL_SIZE); _sprite.setScale(x_scale, y_scale); //release memory _field = new cell* [_size]; for (size_t i = 0; i < _size; i++) { _field[i] = new cell[_size]; } //initialization for (size_t i = 0; i < _size; i++) { for (size_t j = 0; j < _size; j++) { _field[i][j] = cell::empty; } } } Game::~Game() { //discharge memory for (size_t i = 0; i < _size; i++) { delete[] _field[i]; } delete[] _field; } bool Game::playing() { //case for "nobody win" if (_turns == 0) return false; return _playing; } void Game::draw(sf::RenderWindow &window) { for (size_t i = 0; i < _size; i++) { for (size_t j = 0; j < _size; j++) { //cut our textures if (_field[i][j] == cell::empty) _sprite.setTextureRect(sf::IntRect(2 * CELL_SIZE, 0, CELL_SIZE, CELL_SIZE)); //!! //la béquille // there are some truble with scale //this make picture more fancy //!! if (_field[i][j] == cell::o || _field[i][j] == cell::win_o) if (_size % 2 == 0) _sprite.setTextureRect(sf::IntRect(CELL_SIZE - 1, 0, CELL_SIZE, CELL_SIZE)); else _sprite.setTextureRect(sf::IntRect(CELL_SIZE, 0, CELL_SIZE, CELL_SIZE)); // if (_field[i][j] == cell::x || _field[i][j] == cell::win_x) _sprite.setTextureRect(sf::IntRect(0, 0, CELL_SIZE, CELL_SIZE)); //painting cell into purple, if this is winning line if (_field[i][j] == cell::win_x || _field[i][j] == cell::win_o) { _sprite.setColor(sf::Color(140, 102, 255)); } //painting cell into yellow, if this latest put cell else if (_last_x == i && _last_y == j) { _sprite.setColor(sf::Color(255, 255, 153)); } else //return color back; { _sprite.setColor(sf::Color::White); } //put in correct place _sprite.setPosition(i * CELL_SIZE * x_scale, j * CELL_SIZE * y_scale); window.draw(_sprite); } } } bool Game::will_first_go() { return _first_p_turn; } void Game::reset() { _playing = true; _win_points = _size <= 3 ? _size : _size < 8 ? 3 : _size > 11 ? 5 : 4; _turns = _size * _size; _first_p_turn = true; //we don't have latest point _last_x = 42; _last_y = 42; //reset players _p1_attacks.clear(); _p2_attacks.clear(); //scale's staff x_scale = y_scale = (float) 640 / (_size * CELL_SIZE); _sprite.setScale(x_scale, y_scale); //discharge prev memory for (size_t i = 0; i < _prev_size; i++) { delete[] _field[i]; } delete _field; //release memory _field = new cell*[_size]; for (size_t i = 0; i < _size; i++) { _field[i] = new cell[_size]; } //initialization for (size_t i = 0; i < _size; i++) { for (size_t j = 0; j < _size; j++) { _field[i][j] = cell::empty; } } //update prev size _prev_size = _size; }
true
e480ca0e543b11d4e18234adede7133e91040cb2
C++
SanketChidrewar/Coding-Challenges
/CPP ASSIGNMENT/ASSIGN_5/ASSIGN_5_QUE_3/src/manager.h
UTF-8
477
2.734375
3
[]
no_license
/* * manager.h * * Created on: 09-Mar-2020 * Author: sunbeam */ #ifndef MANAGER_H_ #define MANAGER_H_ #include<iostream> #include"employee.h" using namespace std; class manager : public employee { private: float bonus; public: manager(); manager(int id,float sal,float bonus); int get_Bonus(); void set_Bonus(float bonus); virtual void display(); void accept(); void display_Manager(); void accept_Manager(); ~manager(); }; #endif /* MANAGER_H_ */
true
0d093e7523621eb4380224638f20f866afe87ed2
C++
lovelyyoshino/learnopencv
/Contour-Detection-using-OpenCV/cpp/contour_extraction/contour_extraction.cpp
UTF-8
1,985
2.78125
3
[]
no_license
#include<opencv2/opencv.hpp> #include <iostream> using namespace std; using namespace cv; int main() { /* Contour detection and drawing using different extraction modes to complement the understanding of hierarchies */ Mat image2 = imread("../../input/custom_colors.jpg"); Mat img_gray2; cvtColor(image2, img_gray2, COLOR_BGR2GRAY); Mat thresh2; threshold(img_gray2, thresh2, 150, 255, THRESH_BINARY); vector<vector<Point>> contours3; vector<Vec4i> hierarchy3; findContours(thresh2, contours3, hierarchy3, RETR_LIST, CHAIN_APPROX_NONE); Mat image_copy4 = image2.clone(); drawContours(image_copy4, contours3, -1, Scalar(0, 255, 0), 2); imshow("LIST", image_copy4); waitKey(0); imwrite("contours_retr_list.jpg", image_copy4); destroyAllWindows(); vector<vector<Point>> contours4; vector<Vec4i> hierarchy4; findContours(thresh2, contours4, hierarchy4, RETR_EXTERNAL, CHAIN_APPROX_NONE); Mat image_copy5 = image2.clone(); drawContours(image_copy5, contours4, -1, Scalar(0, 255, 0), 2); imshow("EXTERNAL", image_copy5); waitKey(0); imwrite("contours_retr_external.jpg", image_copy4); destroyAllWindows(); vector<vector<Point>> contours5; vector<Vec4i> hierarchy5; findContours(thresh2, contours5, hierarchy5, RETR_CCOMP, CHAIN_APPROX_NONE); Mat image_copy6 = image2.clone(); drawContours(image_copy6, contours5, -1, Scalar(0, 255, 0), 2); imshow("EXTERNAL", image_copy6); waitKey(0); imwrite("contours_retr_ccomp.jpg", image_copy6); destroyAllWindows(); vector<vector<Point>> contours6; vector<Vec4i> hierarchy6; findContours(thresh2, contours6, hierarchy6, RETR_TREE, CHAIN_APPROX_NONE); Mat image_copy7 = image2.clone(); drawContours(image_copy7, contours6, -1, Scalar(0, 255, 0), 2); imshow("EXTERNAL", image_copy7); waitKey(0); imwrite("contours_retr_tree.jpg", image_copy7); destroyAllWindows(); }
true
54b1210558d284a7af5e4c3e455c6a48bcd96f38
C++
Mewael/SpringMvcProject
/revision/linked_list/cpp/queue/queue.cpp
UTF-8
1,583
3.375
3
[]
no_license
//Filmon Gebreyesus //03/04/2015 //demo for data structure concepts #include<iostream> #include"queue.h" #include<string.h> using namespace std; Llist::Llist() { front=NULL; size=0; } Llist::~Llist() { while(front!=NULL) { tmpPtr=front; front=front->next; delete tmpPtr; } } void Llist::push_back(string data) { Node* new_node=new Node; new_node->data=data; new_node->next=NULL; if(is_empty()) { front=new_node; rear=front; } else { rear->next=new_node; rear=new_node; } } bool Llist::is_empty() { if(front==NULL) return true; else return false; } string Llist::pop() { if(!is_empty()) { tmpPtr=front; string poped=front->data; front=front->next; delete tmpPtr; tmpPtr=NULL; return poped; } else return "-1"; } string Llist::search_data(string search_data) { tmpPtr=front; while(tmpPtr!=NULL) { if((search_data.compare(tmpPtr->data))==0) return tmpPtr->data; tmpPtr=tmpPtr->next; } return ""; } void Llist::display() { tmpPtr=front; while(tmpPtr!=NULL) { cout<<tmpPtr->data<<endl; tmpPtr=tmpPtr->next; } } void Llist::obliterate(string delete_data) { tmpPtr=front; rear=front; while((tmpPtr!=NULL) && (delete_data.compare(tmpPtr->data))) { rear=tmpPtr; tmpPtr=tmpPtr->next; } if(tmpPtr==NULL) { cout << "Null " << endl; return; } else if ((tmpPtr!=NULL) && (!delete_data.compare(front->data))) { front=front->next; delete tmpPtr; tmpPtr=NULL; } else { rear->next=tmpPtr->next; delete tmpPtr; tmpPtr=NULL; } cout << delete_data << " deleted " << endl; }
true
431effeb2bb8796ec16178cd61f2cbe4cd5d8e17
C++
rjoleary/programming-problems
/project-euler/problem13.cpp
UTF-8
615
3.015625
3
[ "MIT" ]
permissive
#include <cstdint> #include <fstream> #include <iostream> #include <sstream> int main() { std::ifstream file("problem13.txt"); std::int64_t sum = 0; for (int i = 0; i < 100; i++) { // Only read the first 15 digits. It works out the same as // long as addition is concerned. char c[16] = {0}; file.read(c, 15); file.ignore(100, '\n'); std::int64_t n; std::istringstream(c) >> n; sum += n; } // Reduce the number to 10 digits. while (sum >= 1e10) sum /= 10; std::cout << sum << '\n'; }
true
afa7855f8ddf4d7e6868919f933c0e2e61abe5a7
C++
akuendig/algolab
/week_10_linear_and_quadratic_programming/1_diet/diet/main.cpp
UTF-8
2,295
2.671875
3
[]
no_license
#include <iostream> #include <cassert> #include <CGAL/basic.h> #include <CGAL/QP_models.h> #include <CGAL/QP_functions.h> #include <vector> #include <cmath> using namespace std; #ifdef CGAL_USE_GMP #include <CGAL/Gmpz.h> typedef CGAL::Gmpz ET; #else #include <CGAL/MP_Float.h> typedef CGAL::MP_Float ET; #endif // program and solution types typedef CGAL::Quadratic_program<int> Program; typedef CGAL::Quadratic_program_solution<ET> Solution; int ceil_to_double(const CGAL::Quotient<ET>& x) { double a = std::ceil(CGAL::to_double(x)); while (a < x) a += 1; while (a-1 >= x) a -= 1; return a; } void testcases() { size_t p; // const int X = 0; // const int Y = 1; // const int ZZ = 2; int num_nutrients, num_foods; int nutrients[41][2]; int food_nutrients[101][41]; int prices[101]; while (true) { cin >> num_nutrients >> num_foods; if (num_nutrients == 0 && num_foods == 0) { break; } for (int i=0; i<num_nutrients; i++) { cin >> nutrients[i][0] >> nutrients[i][1]; } for (int i=0; i<num_foods; i++) { cin >> prices[i]; for (int j=0; j<num_nutrients; j++) { cin >> food_nutrients[i][j]; } } int FOODS = 0; Program qp (CGAL::SMALLER, true, 0, false, 0); // function to minimize for (int i=0; i < num_foods; i++) { qp.set_c(FOODS+i, prices[i]); } int eq_counter = 0; for (int i=0; i<num_nutrients; i++) { for (int j=0;j<num_foods;j++) { qp.set_a(FOODS+j,eq_counter,food_nutrients[j][i]); } qp.set_b(eq_counter, nutrients[i][1]); eq_counter++; } for (int i=0; i<num_nutrients; i++) { for (int j=0;j<num_foods;j++) { qp.set_a(FOODS+j,eq_counter,food_nutrients[j][i]); } qp.set_b(eq_counter, nutrients[i][0]); qp.set_r(eq_counter, CGAL::LARGER); eq_counter++; } Solution s = CGAL::solve_nonnegative_quadratic_program(qp, ET()); if (s.is_optimal()) { cout << floor(CGAL::to_double(s.objective_value())) << endl; } else { cout << "No such diet.\n"; } } } int main() { std::cout << std::setiosflags(std::ios::fixed) << std::setprecision(0); cin.sync_with_stdio(false); cout.sync_with_stdio(false); testcases(); return 0; }
true
410417aed5f7ef090b0104cc53310e5aa612aff8
C++
jacktaylor2048/tone_piano
/tone_piano/src/main.cpp
UTF-8
3,235
3.21875
3
[]
no_license
#include <conio.h> #include <iostream> #include "note.h" const int CONSOLE_WIDTH = 64; const int CONSOLE_HEIGHT = 16; const unsigned char DEFAULT_NOTELENGTH = 150; const unsigned char MIN_NOTELENGTH = 10; const unsigned char MAX_NOTELENGTH = 255; const char ESCAPE_KEY = 27; // Clear console void clear() { DWORD n; FillConsoleOutputCharacter(GetStdHandle(STD_OUTPUT_HANDLE), TEXT(' '), 1024, {0}, &n); SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), {0}); } // Draw to console void draw(bool& redraw, bool& playmode, char& octave, unsigned char& notelength) { if (redraw) { clear(); std::cout << "\n\n Tone Piano 1.0 by Jack Taylor\n\n\n"; if (!playmode) std::cout << " 1 - 7: Set Octave 8: Random Note\n\n"; else std::cout << " Octave cannot be set while playing.\n\n"; std::cout << " -: Note length - 5 +: Note length + 5\n\n"; std::cout << " Octave: " << static_cast<int>(octave) << " Note Length: " << static_cast<int>(notelength) << "ms\n\n"; if (!playmode) std::cout << " SPACE: Toggle play mode (Currently OFF)\n\n"; else std::cout << " SPACE: Toggle play mode (Currently ON)\n\n"; std::cout << " ESC: Exit program"; redraw = false; } } // Main function int main() { bool redraw = true; bool playmode = false; char key = 0; char octave = BASE_OCTAVE; unsigned char notelength = DEFAULT_NOTELENGTH; srand(time_t(NULL)); // Initialise console window SetConsoleTitle("Tone Piano"); SMALL_RECT window = {0, 0, CONSOLE_WIDTH - 1, CONSOLE_HEIGHT - 1}; COORD buffer = {CONSOLE_WIDTH, CONSOLE_HEIGHT}; SetConsoleWindowInfo(GetStdHandle(STD_OUTPUT_HANDLE), TRUE, &window); SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), buffer); // Main loop while (key != ESCAPE_KEY) { draw(redraw, playmode, octave, notelength); Note cur_note; // Playmode OFF. Notes cannot be played, but octave can be configured. if (!playmode) { key = _getch(); // Octaves if (key == '1') octave = 1; else if (key == '2') octave = 2; else if (key == '3') octave = 3; else if (key == '4') octave = 4; else if (key == '5') octave = 5; else if (key == '6') octave = 6; else if (key == '7') octave = 7; // Note length configuration else if (key == '-' && notelength > MIN_NOTELENGTH) notelength -= 5; else if (key == '=' && notelength < MAX_NOTELENGTH) notelength += 5; // Space toggles playmode else if (key == ' ') playmode = true; redraw = true; // Play random note (does not require console redraw) if (key == '8') { cur_note.set_note(); cur_note.play(octave, notelength); redraw = false; } } // Playmode ON. Notes can be played, but octave cannot be configured. else { key = _getch(); if (key == '-' && notelength > MIN_NOTELENGTH) { notelength -= 5; redraw = true; } else if (key == '=' && notelength < MAX_NOTELENGTH) { notelength += 5; redraw = true; } else if (key == ' ') { playmode = false; redraw = true; } else { cur_note.set_note(key); cur_note.play(octave, notelength); } } } return 0; }
true
fdad5aca3fee4cbf751a8dfeb84e5f73c7ab2978
C++
prakharvk/ns3
/socket/server.c
UTF-8
1,413
2.984375
3
[]
no_license
#include <bits/stdc++.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <errno.h> #include <arpa/inet.h> #include <unistd.h> using namespace std; int main(){ int ssock, csock; unsigned int length; struct sockaddr_in server, client; if((ssock=socket(AF_INET, SOCK_STREAM, 0)) == -1){ perror("socket: not created"); exit(-1); } else{ cout << "socket created successfullly" << endl; } server.sin_family = AF_INET; server.sin_port = htons(10000); server.sin_addr.s_addr = INADDR_ANY; bzero(&server.sin_zero,0); length = sizeof(struct sockaddr_in); if((bind(ssock, (struct sockaddr *)&server, length)) == -1){ perror("bind error: binding falied "); exit(-1); } else { cout << "bind completed" << endl; } if((listen(ssock, 5)) == -1){ perror("listen error: server is not listening "); exit(-1); } else { cout << "server is listening" << endl; } if((csock=accept(ssock, (struct sockaddr *)&client, &length)) == -1){ perror("accept error: server is not accepting any packet "); exit(-1); } else { cout << "server is ready to accept packet" << endl; } while(1){ int a, b, c; recv(csock, &a, sizeof(a), 0); recv(csock, &b, sizeof(b), 0); c = a + b; send(csock, &c, sizeof(c), 0); cout << endl << "sent sum=: " << c << endl; } close(ssock); return 0; }
true
e38567c70f0477d0760c91d539bef0f25c238302
C++
tnotstar/tnotbox
/C++/Learn/Cplusplus4c/generic_arrsum.cpp
UTF-8
538
3.765625
4
[]
no_license
#include <iostream> using namespace std; template <class Summable> Summable arrsum(T *arr, int n) { Summable sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; return sum; } int main () { double arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; int n = sizeof(arr)/sizeof(arr[0]); cout << "The sum of following " << n << " items: "; for (int i = 0; i < n; ++i) { if (i > 0) cout << ", "; cout << arr[i]; } cout << "; it's " << arrsum(arr, n) << endl; return 0; }
true
9d7f1687abd89d1159538d20f2e88e9ccf52a22f
C++
JasonDeras/Proyecto2_CTJ_EDD1
/TDA_Tree.cpp
UTF-8
4,300
3.140625
3
[ "MIT" ]
permissive
#include "TDA_Tree.h" #include <iostream> #include <string> #include <vector> #include <queue> #include <fstream> #include <sstream> #include <vector> using namespace std; TDA_Tree::TDA_Tree(int Nodos){ this->root = 0; for (int i = 0; i < Nodos; i++){ nodes.push_back(new Tree_Node(nullptr,nullptr,nullptr,"")); } } TDA_Tree::TDA_Tree(vector<Tree_Node*> arbol){ this->nodes = arbol; } Tree_Node* TDA_Tree::Crear(string etiqueta,int nodo, int izquierdo, int derecho) { if(izquierdo != -1){ nodes[nodo]->setIzquierdo(nodes[izquierdo]); nodes[izquierdo]->setPadre(nodes[nodo]); } if (derecho != -1) { nodes[nodo]->setDerecho(nodes[derecho]); nodes[derecho]->setPadre(nodes[nodo]); } nodes[nodo]->setEtiqueta(etiqueta); return nodes[nodo]; } Tree_Node* TDA_Tree::Padre(Tree_Node* t_Node) { return t_Node->getPadre(); } Tree_Node* TDA_Tree::Hijo_Izquierdo(Tree_Node* t_Node){ return t_Node->getIzquierdo(); } Tree_Node* TDA_Tree::Hijo_Derecho(Tree_Node* t_Node){ return t_Node->getDerecho(); } Tree_Node* TDA_Tree::Raiz(){ return nodes[0]; } void TDA_Tree::Anula() { for(Tree_Node* t_Node : nodes){ delete t_Node; } nodes.clear(); } vector<string> Split(string line, char delimiter = ',') { vector<string> vect; string temp = ""; for (int i = 0; i < line.length(); i++) { if (line.at(i) == delimiter) { vect.push_back(temp); temp = ""; } else { temp += line.at(i); } } if(temp != "") vect.push_back(temp); return vect; } TDA_Tree* TDA_Tree::leerDeArchivo(string nombre) { ifstream archivo; archivo.open(nombre, ios::in); if (archivo.is_open()) { vector<vector<string>> lineas; string linea; getline(archivo, linea); int nLin = stoi(linea); for(int i = 0; i < nLin; i++) { if (getline(archivo, linea)) { lineas.push_back(Split(linea)); } else { lineas.push_back(Split("")); } } TDA_Tree* Arbol = new TDA_Tree(nLin); for (int i = 0; i < lineas.size(); i++) { if (lineas.at(i).size() == 2) { Arbol->Crear(to_string(i), i, stoi(lineas.at(i).at(0)), stoi(lineas.at(i).at(1))); } else if(lineas.at(i).size() == 1) { Arbol->Crear(to_string(i), i, stoi(lineas.at(i).at(0))); } else { Arbol->Crear(to_string(i), i); } } //cout << Arbol->raiz()->getIzq()->getEtiqueta(); archivo.close(); cout << "Arbol Cargado!\n\n\n"; return Arbol; } else { cout << "No fue posible leer el archivo!! Arbol no cargado!\n\n\n"; return nullptr; } } void TDA_Tree::PostOrder(Tree_Node* raiz) { if (raiz != NULL) { PostOrder(raiz->getIzquierdo()); PostOrder(raiz->getDerecho()); cout << raiz->toString() << " - "; } } void TDA_Tree::InOrder(Tree_Node* A){ if(A==nullptr){ return; }else{ InOrder(A->getIzquierdo()); cout<<A->getEtiqueta()<<" - "; InOrder(A->getDerecho()); } if(A == nodes[0]) cout << endl; } void TDA_Tree::PreOrder(Tree_Node* t_Node){ cout << t_Node->toString() << ","; if(t_Node->getIzquierdo() != nullptr) PreOrder(t_Node->getIzquierdo()); if (t_Node->getDerecho() != nullptr) PreOrder(t_Node->getDerecho()); if(t_Node == nodes[0]) cout << endl; } string TDA_Tree::Ruta(string etiqueta){ Tree_Node* target = nullptr; for (Tree_Node* t_Node : nodes){ if (t_Node->getEtiqueta() == etiqueta){ target = t_Node; break; } } if(target == nullptr) return ""; //Creamos la ruta string route; while (target != Raiz()) { Tree_Node* padre = target->getPadre(); if (padre->getIzquierdo() == target) { route = "0" + route; } else { route = "1" + route; } target = padre; } return route; } TDA_Tree::~TDA_Tree() { Anula(); }
true
1bdb5d07fe1e7aaa12039536dbd5f3f28c74bd71
C++
Kushagra-Kapoor25/Revising-CPP
/Searching/PairWithGivenSumInSortedArray.cpp
UTF-8
509
3.390625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; bool pairSum(int arr[], int size, int x) { int left = 0, right = size - 1; while (left < right) { if ((arr[left] + arr[right]) == x) return true; else if (x > (arr[left] + arr[right])) left++; else right--; } return false; } int main() { int arr[] = {2, 5, 8, 12, 30}; int size = sizeof(arr) / sizeof(arr[0]); int x = 2; cout << pairSum(arr, size, x); return 0; }
true
c951021c49c551c14d8d53813f47e148ee142dd0
C++
LeoBrilliant/OpenTS
/PriorityQueue.h
WINDOWS-1252
1,487
3.546875
4
[ "Apache-2.0" ]
permissive
/* * PriorityQueue.h * * Created on: 2016126 * Author: LeoBrilliant */ #ifndef STL_PriorityQueue_H_ #define STL_PriorityQueue_H_ #include <iostream> #include <vector> #include <queue> using namespace std; template<typename T, class Container = vector<T>, typename Compare = less<typename Container::value_type> > class PriorityQueue { private: priority_queue<T, Container, Compare> pqt; public: //Constructor PriorityQueue():pqt() { cout << "VectorOps Constructor: Default" << endl; } PriorityQueue(PriorityQueue<T, Container, Compare>& pq):pqt(pq.GetPqt()) { cout << "VectorOps Constructor: Copy" << endl; } PriorityQueue(typename Container::iterator first, typename Container::iterator last):pqt(first, last) { cout << "VectorOps Constructor: Fill dt with iterator from first to last" << endl; } //Destructor ~PriorityQueue() { while(!this->Empty()) { this->Pop(); } cout << "DequeOps Destructor: Default" << endl; } //Capacity bool Empty() const { return pqt.empty(); } size_t Size() const { return pqt.size(); } //Element access const T& Top() { return pqt.top(); } //Modifiers void Push(const T& t) { pqt.push(t); } void Pop() { pqt.top(); } //Getter const priority_queue<T, Container, Compare>& GetPqt() const { return pqt; } //Summary void GetSummary(); //Detail void GetDetail(const string &); }; #endif /* STL_PriorityQueue_H_ */
true
cfdbba43208e7014cab486f4a9c8ea5d6b4a18c5
C++
AltaOhms/desktop_buddy
/Desktop_buddy/Desktop_buddy.ino
UTF-8
5,333
2.6875
3
[]
no_license
/**************************************************************** Code to demonstrate how to control the microview to smile and frown base on values from a photoresistor SparkFun electronics. 24 Feb 2014 - Pamela - SparkFun Electronics @hello_techie Jim - SparkFun Electronics - Graphics for the smile and frown code Code used for the Desktop Buddy Demo for the SparkFun Inventors kit for MicroView video ****************************************************************/ #include <MicroView.h> #include <Servo.h> #define D_WIDTH uView.getLCDWidth() #define D_HEIGHT uView.getLCDHeight() #define SMILE 0 #define FROWN 1 #define SLEEP 2 int lightFrownThreshold = 0; //This needs to be changed base on the photoresistor's values int lightSmileMaxThreshold = 900; //This needs to be changed base on the photoresistor's values int RED = 6; // declare RED LED pin 6 int GREEN = 5; // declare GREEN LED pin 5 int BLUE = 3; // declare BLUE LED pin 3 int buttonPin = A0; // push button pin int buttonState = 0; // variable to store the pushbutton status int sensorPin = A2; // select the input pin for the photo resistor int sensorValue = 0; // variable to store the value coming from the sensor Servo servo; // declare servo object //Face Code byte eyeRadius = D_WIDTH/8; byte eyeY = D_HEIGHT/6; byte eyeLX = D_WIDTH/2 - eyeRadius*2; byte eyeRX = D_WIDTH/2 + eyeRadius*2; byte pupilRadius = eyeRadius/4; byte noseLength = D_HEIGHT/4; byte noseWidth = D_WIDTH/8; byte noseATX = D_WIDTH/2; byte noseATY = D_HEIGHT/4; byte noseABX = noseATX - noseWidth; byte noseABY = noseATY + noseLength; byte noseBBX = noseATX; byte noseBBY = noseABY + 1; byte smileH = D_HEIGHT/6; byte smileW = D_WIDTH/3; byte smileX = D_WIDTH/2; byte smileY = 3 * D_HEIGHT/4; byte frownH = D_HEIGHT/5; byte frownW = D_WIDTH/3; byte frownX = D_WIDTH/2; byte frownY = 3 * D_HEIGHT/4 + frownH/2; byte mouthLX = D_WIDTH/4; byte mouthLY = 3 * D_HEIGHT / 4; byte mouthRX = D_WIDTH - mouthLX; byte mouthRY = mouthLY; void setup() { pinMode(sensorPin,INPUT); // set sensor pin as INPUT digitalWrite(sensorPin,HIGH); // set Internal pull-up uView.begin(); // start MicroView uView.clear(PAGE); // clear page servo.attach(2); // servo control pin at D2 pinMode(buzzerPin, OUTPUT); pinMode(RED, OUTPUT); // set RED LED pin as OUTPUT pinMode(GREEN, OUTPUT); // set GREEN LED pin as OUTPUT pinMode(BLUE, OUTPUT); pinMode(buttonPin, INPUT); // initialize the pushbutton pin as an input digitalWrite(buttonPin,HIGH); // set Internal pull-up } void updateLight() { int sensorValue= analogRead(sensorPin); if (sensorValue < lightFrownThreshold) { drawFace(FROWN, map(sensorValue, 0, lightFrownThreshold, 100, 0), map(sensorValue, 0, lightFrownThreshold, 100, 0)); digitalWrite(RED, HIGH); // set LED pin HIGH voltage, LED will be on } else { drawFace(SMILE, map(sensorValue, 0, lightSmileMaxThreshold, 100, 0), map(sensorValue, 0, lightSmileMaxThreshold, 100, 0)); digitalWrite(RED, HIGH); // set LED pin HIGH voltage, LED will be on uView.display(); } } void loop() { buttonState = digitalRead(buttonPin); // read the state of the pushbutton value // check if the pushbutton is pressed. // if it is not pressed, the buttonState is HIGH: if (buttonState == LOW) { servo.write(70); // about 20 degree delay(1000); servo.write(90); // about 90 degree delay(1000); servo.write(120); // about 160 degree delay(1000); } else { updateLight(); delay(50); } } //void loop() //{ // if // updateLight(); // delay(50); //} void drawFace(byte mouth, byte mouthAngle, byte eyeOpenness) { int eyeH = eyeRadius * eyeOpenness / 100; int mouthH; uView.clear(PAGE); // Draw eyes drawUpArc(eyeLX, eyeY, eyeRadius, eyeH); drawDownArc(eyeLX, eyeY, eyeRadius, eyeH); uView.circleFill(eyeLX, eyeY, min(pupilRadius, eyeH)); drawUpArc(eyeRX, eyeY, eyeRadius, eyeH); drawDownArc(eyeRX, eyeY, eyeRadius, eyeH); uView.circleFill(eyeRX, eyeY, min(pupilRadius, eyeH)); // Draw nose uView.line(noseATX, noseATY, noseABX, noseABY); uView.line(noseABX, noseABY, noseBBX, noseBBY); // Draw mouth: switch(mouth) { case SMILE: mouthH = smileH * mouthAngle / 100; drawUpArc(smileX, smileY, smileW, mouthH); break; case FROWN: mouthH = frownH * mouthAngle / 100; drawDownArc(frownX, frownY, frownW, mouthH); break; case SLEEP: uView.line(mouthLX, mouthLY, mouthRX, mouthRY); break; } } void drawUpArc(int center_x, int center_y, int xRadius, int yRadius) { int radius = max(xRadius, yRadius); float angle_inc = 1.0/radius; int xpos, ypos; for (float angle = 0.0; angle <= PI; angle += angle_inc) { xpos = center_x + xRadius * cos(angle); ypos = center_y + yRadius * sin(angle); uView.pixel(xpos, ypos); } } void drawDownArc(int center_x, int center_y, int xRadius, int yRadius) { int radius = max(xRadius, yRadius); float angle_inc = 1.0/radius; int xpos, ypos; for (float angle = PI; angle <= 2*PI; angle += angle_inc) { xpos = center_x + xRadius * cos(angle); ypos = center_y + yRadius * sin(angle); uView.pixel(xpos, ypos); } }
true
f1884a09b0603f655ed9a81f7f0b44b21c25601e
C++
masumhabib/quest
/lib/src/negf/RgfResult.cpp
UTF-8
625
2.578125
3
[ "Apache-2.0" ]
permissive
/* * File: RgfResult.cpp * Copyright (C) 2014 K M Masum Habib <masum.habib@gmail.com> * * Created on February 13, 2014, 3:41 PM */ #include "negf/RgfResult.h" namespace quest{ namespace negf{ RgfResult::RgfResult(string tag, uint N, int ib, int jb): tag(tag), N(N), ib(ib), jb(jb) { } void RgfResult::save(ostream &out, bool isText){ if (isText){ out << tag << endl; out << R.size() << endl; out << ib << " " << jb << endl; out << N << endl; iter it; for (it = R.begin(); it != R.end(); ++it){ out << *it << endl; } }else{ } } } }
true
645ca884e7847c8106faff1c5e71c69ac1ed67f7
C++
john19950730/SpaProjectRepo
/source/LineOfCodeData.cpp
UTF-8
501
2.640625
3
[]
no_license
#pragma once #include<stdio.h> #include <iostream> #include <string> #include <vector> using namespace std; #include "LineOfCodeData.h" #include "Keywords.h" #include <regex> #include <stack> #include <utility> int LineOfCodeData::store(string type, string aData , std::stack <std::pair<int, string>> nestlevel) { typeOfData = type; actualData = aData; nesting_level = nestlevel; return 0; } std::stack <std::pair<int, string>> LineOfCodeData::getNestingLevel() { return nesting_level; }
true
7f5f858efc5bae982ed7ab47e6034f82d1acffdf
C++
kobakazu0429/atcoder-cpp
/src/APG4b/ex20/main.cpp
UTF-8
896
2.71875
3
[ "MIT" ]
permissive
#include <bits/stdc++.h> #define rep(i, n, init) for (int i = init, len = (n); i < len; ++i) #define ALL(x) (x).begin(), (x).end() #define len(x) ((int)(x).size()) #define int long long #define float long double using namespace std; int count_report_num(vector<vector<int>> &children, int x) { if (len(children[x]) == 0) return 1; int total = 1; for (auto c : children[x]) total += count_report_num(children, c); return total; } signed main() { cin.tie(0); ios::sync_with_stdio(false); int N; cin >> N; vector<int> p(N); p.at(0) = -1; rep(i, N, 1) cin >> p.at(i); // 組織の関係から2次元配列を作る vector<vector<int>> children(N); rep(i, N, 1) { int parent = p.at(i); children.at(parent).push_back(i); } // 各組織について、答えを出力 for (int i = 0; i < N; i++) { cout << count_report_num(children, i) << endl; } }
true
8c50b6c54b5d5e9828662fc4a7f9c117c589346e
C++
peteole/telemetryProtocol
/src/DataSchema.cpp
UTF-8
2,076
3
3
[]
no_license
#include "DataSchema.h" String BasicSensorValue::toJSON() { return "{\"name\": \"" + this->name + "\", \"size\": " + this->size + ", \"type\": \"" + this->type + "\"}"; } char *SensorValueList::getMessage() { uint16_t position = 0; for (int i = 0; i < this->length; i++) { char *partialMessage = this->sensorvalues[i]->getMessage(); for (int j = 0; j < this->sensorvalues[i]->size; j++) { this->messageBuffer[position] = partialMessage[j]; position++; } } return this->messageBuffer; } void SensorValueList::parse(char *data) { uint16_t position = 0; for (int i = 0; i < this->length; i++) { this->sensorvalues[i]->parse(data + position); position += this->sensorvalues[i]->size; } } String SensorValueList::toJSON() { String JSON = "{\"name\": \"" + this->name + "\",\n \"size\": " + this->size + ", \"values\": [\n"; for (int i = 0; i < this->length; i++) { JSON += this->sensorvalues[i]->toJSON() + (i + 1 < this->length ? ",\n" : "\n"); } JSON += "]\n}"; return JSON; } SensorValueList::SensorValueList(SensorValue **sensorvalues, uint16_t length, String name) { this->name = name; this->sensorvalues = sensorvalues; this->length = length; this->size = 0; for (int i = 0; i < this->length; i++) { this->size += this->sensorvalues[i]->size; } this->messageBuffer = new char[this->size]; } StringSensorValue::StringSensorValue(String name, int maxSize) { this->size = maxSize; this->name = name; } void StringSensorValue::parse(char *message) { this->value = String(message); if (this->value.length() > this->size) { // message too long this->value = ""; } } char *StringSensorValue::getMessage() { if (this->value.length() > this->size) { this->value = ""; } return this->value.begin(); } String StringSensorValue::toJSON() { return "{\"name\": " + this->name + ", \"size\":" + this->size + ",\"type\": \"string\"}"; }
true
0c88cde60957fb33fa8ff1f12c7b34c77db29b40
C++
NguyensAlot/CST320
/cAstNode.h
UTF-8
971
2.609375
3
[]
no_license
#pragma once //******************************************************* // Purpose: Base class for all AST nodes // // Author: Philip Howard // Email: phil.howard@oit.edu // // Editor: Anthony Nguyen // Email: anthony.nguyen@oit.edu // // Date: 2/20/2015 // //******************************************************* #include <iostream> #include "codegen.h" #include <string> class cAstNode { public: cAstNode() {mSemanticError = false;} // return a string representation of the class virtual std::string toString() = 0; // return true if a semantic error was detected in this node virtual bool SemanticError() { return mSemanticError; } // compute the offset for each variable and return offset virtual int Computeoffsets(int base) { return base; } // generate code for lab 7 virtual void GenerateCode() {} protected: bool mSemanticError; // true indicates this node has a semantic error int mBase; // offset of variable };
true
6baefd48aa1ec3f026f1f979925aa30b4774a1e8
C++
NikolayCheremnov/CalculationMethodsLabs
/Logger/ilogger.h
UTF-8
273
2.53125
3
[]
no_license
#ifndef ILOGGER_H #define ILOGGER_H #include <iostream> #include <ctime> using namespace std; class ILogger { protected: string get_current_time_str(); public: ILogger(); virtual ~ILogger() {}; virtual void log(string msg) = 0; }; #endif // ILOGGER_H
true
780907c73b56989066a36a04622c17a3d3d9b75c
C++
alexfordc/Quan
/Utilities/Socket/Thread.h
UTF-8
1,820
2.671875
3
[]
no_license
#if !defined(Thread_H) #define Thread_H #include "SysEvent.h" //#define UseWin32Thread #if !defined(UseWin32Thread) #include <process.h> #endif //////////////////////////////////////////////////////////////////////// // Thread class Thread { public: enum { idCancel, idSuspend, idResume, idEnd, idNoEvents }; public: Thread (); ~Thread (); // create/destroy bool create(void *pThreadData = NULL); void release(); // thread methods void *getData() { return m_pThreadData; } HANDLE getHandle() { return m_hThread; } DWORD getId() { return m_idThread; } // event methods bool createThreadEvents(); HANDLE getEvent(long id) { return m_events[id].getEvent(); } void setEvent(long id) { m_events[id].set(); } void resetEvent(long id) { m_events[id].reset(); } HANDLE getEndEvent() { return m_events[idEnd].getEvent(); } void setEndEvent() { m_events[idEnd].set(); } HANDLE getCancelEvent() { return m_events[idCancel].getEvent(); } void setCancelEvent() { m_events[idCancel].set(); } void resetCancelEvent() { m_events[idCancel].reset(); } // control void stop(); void suspend(); void resume(); void cancel(); // run method virtual long run(); // virtual idle method virtual void idle() {} // static thread proc #if defined(UseWin32Thread) static DWORD WINAPI threadProc ( LPVOID parameter ); #else static unsigned _stdcall threadProc(LPVOID parameter); #endif private: static long m_delayTime; // define time to delay for a thread sleep void *m_pThreadData; // data for this thread HANDLE m_hThread; // handle to thread DWORD m_idThread; // id of thread SysEvent m_events[idNoEvents]; // base thread events }; #endif
true
29ddc62053552b21974fb5629e002a2206f066ea
C++
acharras/piscine_cpp
/cpp_04/ex01/AWeapon.hpp
UTF-8
1,464
2.625
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* AWeapon.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: acharras <acharras@student.42lyon.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/05/31 14:34:28 by acharras #+# #+# */ /* Updated: 2021/06/07 13:38:25 by acharras ### ########lyon.fr */ /* */ /* ************************************************************************** */ #ifndef AWEAPON_H # define AWEAPON_H #include <iostream> #include <ostream> #include <cctype> #include <string> class AWeapon { protected: std::string Name; int APcost; int Damage; public: AWeapon(); AWeapon(std::string const & name, int apcost, int damage); AWeapon(AWeapon const& cpy); virtual ~AWeapon(); AWeapon& operator=(AWeapon const& str); std::string getName() const; int getAPCost() const; int getDamage() const; void setName(std::string new_name); void setAPCost(int ap); void setDamage(int da); virtual void attack() const = 0; }; #endif
true
f287e5ac73b02ec441367931c11e2b3c5b99ae3a
C++
bollu/proGenY
/src/util/logObject.h
UTF-8
4,447
3.296875
3
[]
no_license
#pragma once #include <iostream> #include <assert.h> #include "strHelper.h" #include <typeinfo> #include "../core/Hash.h" /*! @file logObject.h Logging objects are present on this file */ namespace util{ /*! \enum logLevel an Enum of various Logging levels available */ enum logLevel{ /*! Information. used for debugging / printing to the console*/ logLevelInfo = 0, /*! Warnings. The program can continue running, but is not ideal */ logLevelWarning, /*! Errors. The program will print the error to the console and halt execution_ */ logLevelError, /*! The log level to be set that will ensure that no log message_ will be emitted */ logLevelNoEmit, }; /*! a base class used to represent Logging objects \sa msgLog scopedLog */ class baseLog{ protected: baseLog(); //only logs that are >= threshold level are emitted static logLevel thresholdLevel; public: /*! only logs that have a logLevel greater than or equal to thresholdLevel are emitted. Use this function to set a threshold level for logObjects. only logObjects whose logLevels are greater than or equal to the threshold level. This can be used to turn off info and warning logs during Release builds. @param [in] logThreshold the logLevel that acts as the threshold for all logObjects. */ static void setThreshold(logLevel logThreshold){ baseLog::thresholdLevel = logThreshold; } virtual ~baseLog(); }; //sentinel. send to loggers to flush the log class Flush_ { public: Flush_() {}; }; static const Flush_ flush; /*! used to emit a quick logging message this logObject is typically used to print information to the console. if a logLevel of Error is used, then the program will halt after printing the error to the console. Otherwise, the message will be printed to the console and the program will continue to execute */ template <logLevel level> class msgLog : public baseLog{ public: msgLog(){}; /*! constructor used to create a msgLog If the logLevel is greater than the logThreshold set in baseLog, then the message will be emitted. If a logLevel of Error is used, and Error is above the log threshold, then the error will be emitted and the program will halt @param [in] msg the message to be printed @param [in] level the logLevel of the given message. \sa scopedLog */ /* msgLog(std::string msg){ if(level >= baseLog::thresholdLevel){ std::cout<<"\n"<<msg<<std::endl; if(level == logLevelError){ std::cout<<"\n\n Quitting from logObject due to error"<<std::endl; assert(false); } } };*/ template <typename T> msgLog & operator << (T toWrite){ if(level >= baseLog::thresholdLevel){ std::cout<<toWrite; } return *this; } msgLog & operator << (const Hash* toWrite){ if(level >= baseLog::thresholdLevel){ std::cout<<Hash::Hash2Str(toWrite); } return *this; } msgLog & operator <<(const Flush_ &f){ std::cout<<std::endl; return *this; } }; #pragma once #ifndef LOG_GLOBAL_OBJECTS #define LOG_GLOBAL_OBJECTS static util::msgLog<logLevelInfo> infoLog; static util::msgLog<logLevelError> errorLog; static util::msgLog<logLevelWarning> warningLog; #endif /*! used to emit messages when a scope is entered and exited the scopedLog can be used to quickly chart out scope by creating a scopedLog at the beginning of a block. when the block ends, the scopedLog is destroyed and the required message is emitted. it _must_ be created on the stack for it to send the destruction message. if created on the heap, it will send the destruction message when it is destroyed, which is rarely (if at all) useful \sa msgLog */ class scopedLog : public baseLog{ private: std::string onDestroyMsg; bool enabled; public: /*! constructor used to create a scopedLog @param [in] onCreateMsg message to send when created @param [in] onDestroyMsg message to send when destroyed @param [in] level the logging level of this message */ scopedLog(std::string onCreateMsg, std::string onDestroyMsg, logLevel level = logLevelInfo){ enabled = (level >= baseLog::thresholdLevel); this->onDestroyMsg = onDestroyMsg; if(enabled){ std::cout<<"\n"<<onCreateMsg<<std::endl; } } ~scopedLog(){ if(enabled){ std::cout<<"\n"<<onDestroyMsg<<std::endl; } } }; //end scopedLog } //end namespace
true
d41b74b15346877daeb7877a262ea0594918bf11
C++
zgansc/leetcode
/cpp/471-480/Encode String with Shortest Length.cpp
UTF-8
1,438
2.734375
3
[ "MIT" ]
permissive
class Solution { map<string, string> cache; string solve(string str) { string ans(str); int len = str.length(); for (int i = 1; i <= len/2; i++) { if (len % i != 0) continue; string part = str.substr(0, i); int dups = len / i; bool ff = true; for (int k = 0; k < dups; k++) { int idx = k * i; bool f = true; for (int j = 0; j < i; j++) { if (str[idx + j] != str[j]) { f = false; break; } } if (f == false) { ff = false; break; } } if (ff == false) continue; string temp = to_string(dups) + '[' + encode(part) + ']'; if (temp.length() < ans.length()) ans = temp; } //cout << str << " : " << ans << endl; return ans; } public: string encode(string s) { int len = s.length(); if (len <= 1) return s; if (cache.count(s) > 0) return cache[s]; string ans(s); for (int i = 1;i <= len; i++) { string left = s.substr(0, i); string right = s.substr(i); string temp = solve(left) + encode(right); if (temp.length() < ans.length()) ans = temp; } cache[s] = ans; return ans; } };
true
5e3d08d7c21258555d686c17b56990923cf310a2
C++
dakl/foobar
/photon-firmware.ino
UTF-8
1,344
2.578125
3
[]
no_license
/* * This is a minimal example, see extra-examples.cpp for a version * with more explantory documentation, example routines, how to * hook up your pixels and all of the pixel types that are supported. * */ #include "application.h" #include "neopixel/neopixel.h" // use for Build IDE // #include "neopixel.h" // use for local build SYSTEM_MODE(AUTOMATIC); // IMPORTANT: Set pixel COUNT, PIN and TYPE #define PIXEL_PIN D2 #define PIXEL_COUNT 8 #define PIXEL_TYPE WS2812B Adafruit_NeoPixel strip = Adafruit_NeoPixel(PIXEL_COUNT, PIXEL_PIN, PIXEL_TYPE); // Prototypes for local build, ok to leave in for Build IDE void rainbow(uint8_t wait); uint32_t Wheel(byte WheelPos); void setup() { strip.begin(); strip.show(); // Initialize all pixels to 'off' Particle.function("status", setStatus); } void loop() { //rainbow(20); } int setStatus(String args){ int value = args.toInt(); Spark.publish("value", value); int brightness = 10; int color = strip.Color(0, 0, 0); if( value == 1 ) { // started color = strip.Color(brightness, brightness, 0); }else if (value == 2) { // failed color = strip.Color(brightness, 0, 0); }else if (value == 0) { // success color = strip.Color(0, brightness, 0); } strip.setPixelColor(0, color); strip.show(); return value; }
true
76cc2c4442d74d0b6625aaa060d56948dc3dad3b
C++
yehyun3459/algorithm
/Baekjoon/P16986(인싸들의 가위바위보)/yhyh.cpp
UTF-8
1,504
2.953125
3
[]
no_license
//문제를 제대로 안봐서 한참 헤맴.. //1. 지우 순서 정함(순열) //2. 가위바위보 시뮬레이션 후 이기는지 확인 #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> int N, K; int A[10][10]; int rps[3][20]; int visited[10]; int win[3]; //승리한 횟수 bool isValid = false; bool Solve() { memset(win, 0, sizeof(win)); int p1 = 0, p2 = 1; //초기 플레이어 int tops[3] = { 0,0,0 }; int cmp1, cmp2; while(true) { if(win[0]==K||win[1]==K||win[2]==K||tops[0]>=N)break; //더이상 수행할 필요 없음 cmp1 = rps[p1][tops[p1]]; cmp2 = rps[p2][tops[p2]]; tops[p1]++; tops[p2]++; if(A[cmp1][cmp2]==2||(A[cmp1][cmp2]==1&&p1>p2))//p1이 이김 { win[p1]++; p2 = 3 - (p1 + p2); } else //p2가 이김 { win[p2]++; p1 = 3 - (p1 + p2); } } if (win[0] >= K)return true; else return false; } void makeSequence(int cnt)//지우의 순서 정하기 { if (isValid)return; if(cnt>=N) { if (Solve())isValid = true; return; } for(int i=1;i<=N;i++) { if (visited[i])continue; visited[i] = 1; rps[0][cnt] = i; makeSequence(cnt + 1); visited[i] = 0; } } int main() { scanf("%d %d", &N, &K); for(int i=1;i<=N;i++) { for (int j = 1; j <= N; j++)scanf("%d", &A[i][j]); } memset(rps, 0, sizeof(rps)); for (int i = 0; i < 20; i++)scanf("%d", &rps[1][i]); for (int i = 0; i < 20; i++)scanf("%d", &rps[2][i]); makeSequence(0); if (isValid)printf("%d\n", 1); else printf("%d\n", 0); }
true
91044d65b433ec272585bfc467a70a5fc111e577
C++
aleksandra-blasevac/cpp-qt-gui-zork
/room.h
UTF-8
1,118
2.78125
3
[]
no_license
#ifndef ROOM_H #define ROOM_H #include <map> #include <QString> #include <vector> #include "item.h" #include "npc.h" using namespace std; #include <utility> //for pair #define NORTH 0 #define EAST 1 #define SOUTH 2 #define WEST 3 class Room { private: QString description; QString mapImageFile; QString roomImageFile; Room* exits[4]; pair<bool, QString> locks[4]; vector<Entity*> entitiesInRoom; public: Room(QString description, QString mapImageFile = "mapNull.gif", QString roomImageFile = "roomNull.gif"); void setExits(Room *north, Room *east, Room *south, Room *west); void unlockAllDoor(); void setLock(int direction, bool locked, QString key = NULL); pair<bool, QString> getLocks(); QString getDescription(); void setDescription(QString newDescription); QString getMapImage(); QString getRoomImage(); pair<Room*, QString> nextRoom(int direction); void addEntity(Entity *inEntity); vector<Entity *> *getEntitiesVector(); void removeEntityFromRoom(int location); void destroyEntity(QString entityName); }; #endif // ROOM_H
true
9ac8e7cae7f4dbcc99d0fc6d8a93d6481b74c17c
C++
PhilipGe/CPPANN
/MNIST_Processing/support/MNISTTester.cpp
UTF-8
2,417
2.875
3
[]
no_license
#include <iostream> #include "MNISTTrainerV2.hpp" #include <eigen/Eigen/Dense> #include "../../include/Network.hpp" #include "../../FileStorage/NetworkSaver.cpp" #include <sqlite3.h> #include <string> #include "MNISTTester.hpp" int outputValue(MatrixXd outputMatrix){ double maxC = outputMatrix(0,0); int result; for(int x = 0;x < outputMatrix.rows();x++){ if(outputMatrix(x,0) >= maxC){ maxC = outputMatrix(x,0); result = x; } } return result; } MatrixXd * MNISTTester::TestImagesOnDatabase(string databaseAddress, string imagesAddress, string labelsAddress, int numberOfImagesToRead, bool printImages){ //(1) Set up image reading fstream imageFileStream = MNISTTrainerV2::initiateImageFileStream(imagesAddress); MatrixXd image; char charImage[784]; //(2) Set up label reading fstream labelFileStream = MNISTTrainerV2::initiateLabelFileStream(labelsAddress); int label; //(3) Get network that is going to be tested Network * net = NetworkSaver::NetworkGetter(databaseAddress.c_str()); //(4) Set up testing parameters int NUMBEROFIMAGESTOREAD = numberOfImagesToRead; MatrixXd output; //(5) Set up return array MatrixXd * returnArray= new MatrixXd[NUMBEROFIMAGESTOREAD]; int correctCount = 0; double cost = 0; //(6) Train Network for(int i = 0;i < NUMBEROFIMAGESTOREAD;i++){ MNISTTrainerV2::readOneImageToCharArray(&imageFileStream, charImage); image = MNISTTrainerV2::convertCharArrayToImageMatrix(charImage)/255; //The 255 is there to normalize the data label = MNISTTrainerV2::readOneLabel(&labelFileStream); if(printImages) MNISTTrainerV2::printImage(charImage, label); output = net->feedForward(image); returnArray[i] = output; MatrixXd loss = output-MNISTTrainerV2::getOutputMatrix(label); cost += (loss.array()*loss.array()).sum()/((double)NUMBEROFIMAGESTOREAD); // cout<<label<<" | "<<outputValue(output)<<endl; if(label == outputValue(output)) correctCount++; // cout<<"Desired: "<<label<<" | Actual: "<<outputValue(output)<<endl; // cout<<output<<endl; } cout << ((double)correctCount)/((double)numberOfImagesToRead)<<endl; cout<<"Cost: "<<cost<<endl; imageFileStream.close(); labelFileStream.close(); return returnArray; }
true
f23817d6625394cf58ea6451131908bae33acda8
C++
jpac1207/SPEA2-Paralelo
/SPEA2/PSO.h
UTF-8
1,291
2.53125
3
[]
no_license
#pragma once #include<cstdlib> #include<ctime> #include<math.h> #include<vector> #include<stdlib.h> #include"ObjectiveFunction.h" #include"ZDT.h" #include"Population.h" #include"Individual.h" using namespace std; class PSO { public: PSO(); ~PSO(); void run(Population* population); vector<double> getLimiteSuperior(); vector<double> getLimiteInferior(); void setLimiteSuperior(vector<double> limiteSuperior); void setLimiteInferior(vector<double> limiteInferior); private: double w = 0.9; const double c1 = 0.5; const double c2 = 0.5; const int numberOfIterations = 30; vector<double> limiteSuperior; vector<double> limiteInferior; ZDT* objective; void initPopulation(Population* population); double keepValuesInBounds(double value, double limiteInferior, double limiteSuperior); Individual *& getLeader(Population* population); Individual *& getMinFitnessObject(Population* population); Individual *& getLeaderMultiObjective(Population* population); bool isDominated(Individual * one, Individual* two); bool nonDominated(Individual * ind, Population * pop); vector<int> identifyExtremalPositions(vector<Individual*> individuals); int getWeakPos(vector<Individual*>& individuals, Individual *ind); vector<double> evaluateIndividual(Individual* individual); };
true
712ca0bf25425a8b63f22d722b7edcd6af28eb79
C++
yuanqinguo/MemPool
/TestObj.h
UTF-8
483
2.8125
3
[]
no_license
#ifndef TEST_OBJ_H #define TEST_OBJ_H #include <iostream> #include <string> int g_GlobalIndex = 0; class TestObj { public: TestObj() { m_index = g_GlobalIndex++; //std::cout<<"TestObj() Create Obj index = "<<m_index<<std::endl; } ~TestObj() { //std::cout<<"~TestObj() Delete Obj index = "<<m_index<<std::endl; } void ForTestPrint() { std::cout<<"TestObj()::ForTestPrint:: index = "<<m_index<<std::endl; } protected: private: int m_index; }; #endif//TEST_OBJ_H
true
c4c6ff472c02a6e6527ef5d9a0e348e1d3dc61e0
C++
yujingda/dogeBase
/dogeBase/record.h
GB18030
2,699
3.078125
3
[]
no_license
#pragma warning(disable:4996) #pragma once #include<string.h> #include"table.h" // int 1 float 2 long 3 char 4 varchar 5 double 6 date 7 //͵Ѿint͵ˣӶʱܷ class record { public: record(char* Tschema, table* t) { memset(tempRecord, 0, 4096); memset(schema, 0, 1000); strcpy(schema, Tschema); tableFile = t; } record(int* Tschema, table* t) { memset(tempRecord, 0, 4096); tableFile = t; memset(schema, 0, 1000); for (int i = 1; i < 100; i++) { if (Tschema[i] != 0) { schemaMap[i] = Tschema[i]; i++; } } } int createOneRecord(int onekind, void* readData, int RDP, int lengthVar); void schMapIntsch(); void copyArray(char* A, int &ax, char* B, int &bx, int len); private: char tempRecord[4096]; char schema[1000]; int schemaMap[100]; table* tableFile; }; /** һеֱֽӸƵһ֮ axA飨Ŀ飩ʼλã1ʼ bxB鸴ʼλ lenǸƳ */ void record::copyArray(char* A, int &ax, char* B, int &bx, int len) { A += ax - 1; for (int i = bx - 1; i < len + bx - 1; i++) { *A++ = *B++; } } /** * int 1 float 2 long 3 char 4 varchar 5 double 6 date 7 * ڴдһ¼д뻺֮ * date͵ݣ涨ʽΪYYYYMMDD */ int record::createOneRecord(int onekind, void* readData, int RDP, int lengthVar=-1) { int countSM = 0; int TRPosition = 1; int RDPosition = RDP; for (; countSM != 0; countSM++) { int kindofData = schemaMap[countSM]; switch (kindofData) { case 1: copyArray(tempRecord, TRPosition, (char*)readData, RDPosition, 4); TRPosition += 4; break; //strcat(tempRecord); case 2: copyArray(tempRecord, TRPosition, (char*)readData, RDPosition, 4); TRPosition += 4; break; case 3: copyArray(tempRecord, TRPosition, (char*)readData, RDPosition, 8); TRPosition += 8; break; case 4: copyArray(tempRecord, TRPosition, (char*)readData, RDPosition, lengthVar); TRPosition += lengthVar; break; case 5: char* tl = (char*)lengthVar; int tmp = 0; copyArray(tempRecord, TRPosition, tl, tmp, 4);//Ҫvarcharǰijдļ֮УǿִܻС˵ TRPosition += 4; copyArray(tempRecord, TRPosition, (char*)readData, RDPosition, 8); TRPosition += 8; break; case 6: copyArray(tempRecord, TRPosition, (char*)readData, RDPosition, 8); TRPosition += 8; break; case 7: //ʽδ֪ȷһ printf("Date is not sheji!\n"); break; default: break; } } }
true
fb2aaa85fad73e6b342fa50e2fcf31ac59670bdb
C++
xeonrsa/COS2611_ASSIGNMENT_4_CPP
/main.cpp
UTF-8
1,500
4.15625
4
[]
no_license
#include <iostream> #include <queue> using namespace std; bool isInLanguageL(queue<char> & w); int main() { string tString; queue<char> tQueue; cout << "Enter word:"; cin >> tString; for (int i = 0; i < tString.length(); i++) { tQueue.push(tString[i]); } cout << isInLanguageL(tQueue); return 0; } // Check if word belongs to language using queues bool isInLanguageL(queue<char> & w) { // Declare two queues to keep track of 'a's and 'b's queue<char> queueA; queue<char> queueB; // move through queue to push all 'a's into new queue while ((w.size() > 0) and (w.front() == 'a')) { queueA.push('a'); // Pop this first element in the queue to move through the queue w.pop(); } // move through queue to push all 'b's into new queue while ((w.size() > 0) and (w.front() == 'b')) { queueB.push('b'); // Pop this first element in the queue to move through the queue w.pop(); } // Compare two queue sizes, if queueA is equal to queueB then the word belongs to the language // Check if W size is 0, if not then there are letters not placed in correct order, making the word invalid // both sizes have to match and w.size() needs to be 0 for a word to pass if ((queueA.size() == (queueB.size())) && (w.size() == 0)) { return true; } else { return false; } }
true
ec7784a98d32f8adc41543a6946d0f6560649750
C++
Rishit-dagli/using-control-p5-in-processing-with-arduino
/_7_segment_arduino.ino
UTF-8
2,044
2.75
3
[ "MIT" ]
permissive
int x = 0 ; void setup() { pinMode( 2 , OUTPUT); pinMode( 3 , OUTPUT); pinMode( 4 , OUTPUT); pinMode( 5 , OUTPUT); pinMode( 6 , OUTPUT); pinMode( 7 , OUTPUT); pinMode( 8 , OUTPUT); pinMode( 9 , OUTPUT); Serial.begin(9600); digitalWrite(2, LOW); digitalWrite(3, LOW); digitalWrite(4, LOW); digitalWrite(5, LOW); digitalWrite(6, LOW); digitalWrite(7, LOW); digitalWrite(8, LOW); digitalWrite(9, LOW); } void loop() { if (( ( Serial.available() ) > ( 0 ) )) { int x = Serial.read() ; switch(x) { case 'a': if(digitalRead(2)==HIGH) { digitalWrite(2, LOW); } else { digitalWrite(2, HIGH); } break; case 'b': if(digitalRead(3)==HIGH) { digitalWrite(3, LOW); } else { digitalWrite(3, HIGH); } break; case 'c': if(digitalRead(4)==HIGH) { digitalWrite(4, LOW); } else { digitalWrite(4, HIGH); } break; case 'f': if(digitalRead(5)==HIGH) { digitalWrite(5, LOW); } else { digitalWrite(5, HIGH); } break; case 'e': if(digitalRead(6)==HIGH) { digitalWrite(6, LOW); } else { digitalWrite(6, HIGH); } break; case 'd': if(digitalRead(7)==HIGH) { digitalWrite(7, LOW); } else { digitalWrite(7, HIGH); } break; case 'g': if(digitalRead(8)==HIGH) { digitalWrite(8, LOW); } else { digitalWrite(8, HIGH); } break; case 'h': if(digitalRead(9)==HIGH) { digitalWrite(9, LOW); } else { digitalWrite(9, HIGH); } break; } } }
true
42d76ab4d84154bd6ff5a20c48590a42525f4ba4
C++
andrey-golubev/opencl-sandbox
/common/thread_pool.hpp
UTF-8
2,235
3.140625
3
[]
no_license
#pragma once #include <cstdint> #include <atomic> #include <functional> #include <future> #include <list> #include <mutex> #include <thread> #include <vector> #include "require.hpp" namespace thr { namespace detail { struct ThreadPool { ThreadPool(std::size_t threads) : m_alive(true) { REQUIRE(threads > 0); m_threads.reserve(threads); for (std::size_t _ = 0; _ < threads; ++_) { m_threads.emplace_back([this]() { while (m_alive) { std::packaged_task<void()> task; { std::unique_lock<std::mutex> lock(m_queue_mutex); m_queue_cv.wait(lock, [this]() { return !m_queue.empty() || !m_alive.load(); }); if (m_queue.empty()) { continue; } task = std::move(m_queue.front()); m_queue.pop_front(); } task(); } }); } } template<typename Callable, typename... Args> using task_return_t = typename std::result_of<Callable(Args...)>::type; template<typename Callable, typename... Args> std::future<task_return_t<Callable, Args...>> add_task(Callable f, Args&&... args) { using return_t = task_return_t<Callable, Args...>; std::packaged_task<return_t()> this_task([=]() { return f(args...); }); std::future<return_t> future = this_task.get_future(); { std::unique_lock<std::mutex> lock(m_queue_mutex); m_queue.emplace_back([t = std::move(this_task)]() mutable { t(); }); } m_queue_cv.notify_one(); return future; } ~ThreadPool() { m_alive = false; m_queue_cv.notify_all(); for (auto& t : m_threads) { REQUIRE(t.joinable()); t.join(); } } private: std::vector<std::thread> m_threads; std::list<std::packaged_task<void()>> m_queue; std::mutex m_queue_mutex; std::condition_variable m_queue_cv; std::atomic<bool> m_alive; }; } // namespace detail } // namespace thr
true
e4b0823fe987d114b12f9e788167059db4ee0658
C++
shehzarr/File-Compressor
/17L-4177.cpp
UTF-8
24,050
3.03125
3
[]
no_license
#include <iostream> #include <conio.h> #include <list> #include <fstream> using namespace std; class heap; template<class T> class bstnode; struct dat { char key; int freq; dat(char c = '\0', int f = 0) { key = c; freq = f; } void print() { cout << key << " "; cout << freq; cout << "\n"; } void printfreq() { cout << freq; } void printkey() { cout << key; } char getkey() { return key; } /*void storefrequency() { a[ind] = freq; ind++; }*/ friend ostream &operator <<(ostream& out, const dat& d) { out << d.key << " "; cout << d.freq << "\n"; return out; } }; template<class T> class Treenode { Treenode<T> * left; Treenode<T>* right; dat data; int height; friend class heap; friend class bstnode<T>; public: Treenode() { left = nullptr; right = nullptr; height = 0; } Treenode(T d, Treenode<T>* l = nullptr, Treenode<T>* r = nullptr) { left = l; right = r; data = d; height = 0; } bool checkleft() { if (left == nullptr) return false; return true; } void printbstnode() { data.print(); } bool checkright() { if (right == nullptr) return false; return true; } ~Treenode() { if (right != nullptr) { delete right; right = nullptr; } if (left != nullptr) { delete left; left = nullptr; } } }; template<class T> class bstnode { friend class heap; Treenode<T>* root; public: bstnode() { root = nullptr; } bstnode(T d) { if (d != nullptr) { root = new Treenode<T>(d); } } Treenode<T>* getroot() { return root; } ~bstnode() { if (root != nullptr) { delete root; root = nullptr; } } void printbstnode() { print(root); } void print(Treenode<T>* root) { if (root != nullptr) { root->printbstnode(); print(root->left); print(root->right); } } }; class heap { list<Treenode<dat>*>* _heap; public: heap() { _heap = new list<Treenode<dat>*>; } void addNew(Treenode<dat>* k) { if (k != nullptr) { list<Treenode<dat>*>::iterator it = _heap->begin(); for (; it != _heap->end() && k->data.freq > (*it)->data.freq; ++it); if (it != _heap->end()) _heap->insert(it, k); else _heap->push_back(k); } } bstnode<dat>* HuffTree() { bstnode<dat>* t = new bstnode<dat>; t->root = huffTree(); return t; } Treenode<dat>* huffTree() { if (_heap->size() > 1) { Treenode<dat>* temp = new Treenode<dat>; temp->data.freq = temp->data.freq + _heap->front()->data.freq; temp->left = _heap->front(); _heap->pop_front(); temp->data.freq = temp->data.freq + _heap->front()->data.freq; temp->right = _heap->front(); temp->data.key = '\0'; _heap->pop_front(); addNew(temp); huffTree(); } return _heap->front(); } void printHeap() { list<Treenode<dat>*>::iterator it = _heap->begin(); for (; it != _heap->end(); ++it) { (*it)->printbstnode(); } } void deleteheap(heap* & h) { if (h != nullptr) delete h; } ~heap() { delete _heap; } }; class HashTable { list<dat> *table[32] = { nullptr }; public: HashTable() { for (int i = 0; i < 32; i++) { table[i] = new list<dat>; } } void search(char k) { int i = k; i = i % 32; typename list<dat>::iterator it; it = table[i]->begin(); bool flag = false; for (;it != table[i]->end();++it) { if (k == it->key) { it->freq++; flag = true; break; } } if (flag == false) { dat temp(k, 1); table[i]->push_back(temp); } } void print() { for (int i = 0; i < 32; i++) { if (table[i] != nullptr) { for (list<dat>::iterator it = table[i]->begin(); it != table[i]->end(); ++it) { cout << *it; } } //cout << "\n\n\n"; } cout << "\n\n\n"; } heap* consHeap() { heap* Heap = new heap; for (int i = 0; i < 32; i++) { for (list<dat>::iterator it = table[i]->begin(); it != table[i]->end(); ++it) { Treenode<dat>* temp = new Treenode<dat>(*it); Heap->addNew(temp); } } return Heap; } ~HashTable() { for (int i = 0; i < 32; i++) { if (table[i] != nullptr) { table[i]->~list(); table[i] = nullptr; } } } void deletehashtable(HashTable*& h) { if (h != nullptr) delete h; } }; struct MinHeapNode { char data; unsigned freq; struct MinHeapNode *left, *right; }; struct MinHeap { unsigned size; unsigned capacity; struct MinHeapNode** array; }; struct MinHeapNode* newNode(char data, unsigned freq) { struct MinHeapNode* temp = (struct MinHeapNode*)malloc(sizeof(struct MinHeapNode)); temp->left = temp->right = NULL; temp->data = data; temp->freq = freq; return temp; } struct MinHeap* createMinHeap(unsigned capacity) { struct MinHeap* minHeap = (struct MinHeap*)malloc(sizeof(struct MinHeap)); minHeap->size = 0; minHeap->capacity = capacity; minHeap->array = (struct MinHeapNode**)malloc(minHeap->capacity * sizeof(struct MinHeapNode*)); return minHeap; } void swapMinHeapNode(struct MinHeapNode** a, struct MinHeapNode** b) { struct MinHeapNode* t = *a; *a = *b; *b = t; } void minHeapify(struct MinHeap* minHeap, int idx) { int smallest = idx; int left = 2 * idx + 1; int right = 2 * idx + 2; if (left < minHeap->size && minHeap->array[left]->freq < minHeap->array[smallest]->freq) smallest = left; if (right < minHeap->size && minHeap->array[right]->freq < minHeap->array[smallest]->freq) smallest = right; if (smallest != idx) { swapMinHeapNode(&minHeap->array[smallest], &minHeap->array[idx]); minHeapify(minHeap, smallest); } } int isSizeOne(struct MinHeap* minHeap) { return (minHeap->size == 1); } struct MinHeapNode* extractMin(struct MinHeap* minHeap) { struct MinHeapNode* temp = minHeap->array[0]; minHeap->array[0] = minHeap->array[minHeap->size - 1]; --minHeap->size; minHeapify(minHeap, 0); return temp; } void insertMinHeap(struct MinHeap* minHeap, struct MinHeapNode* minHeapNode) { ++minHeap->size; int i = minHeap->size - 1; while (i && minHeapNode->freq < minHeap->array[(i - 1) / 2]->freq) { minHeap->array[i] = minHeap->array[(i - 1) / 2]; i = (i - 1) / 2; } minHeap->array[i] = minHeapNode; } void buildMinHeap(struct MinHeap* minHeap) { int n = minHeap->size - 1; for (int i = (n - 1) / 2; i >= 0; --i) minHeapify(minHeap, i); } void printArr(int arr[], int n) { for (int i = 0; i < n; ++i) cout << arr[i]; cout << "\n"; } int isLeaf(struct MinHeapNode* root) { return !(root->left) && !(root->right); } struct MinHeap* createAndBuildMinHeap(char data[], int freq[], int size) { struct MinHeap* minHeap = createMinHeap(size); for (int i = 0; i < size; ++i) minHeap->array[i] = newNode(data[i], freq[i]); minHeap->size = size; buildMinHeap(minHeap); return minHeap; } struct MinHeapNode* buildHuffmanTree(char data[], int freq[], int size) { struct MinHeapNode *left, *right, *top; struct MinHeap* minHeap = createAndBuildMinHeap(data, freq, size); while (!isSizeOne(minHeap)) { left = extractMin(minHeap); right = extractMin(minHeap); top = newNode('$', left->freq + right->freq); top->left = left; top->right = right; insertMinHeap(minHeap, top); } return extractMin(minHeap); } void printCodes(struct MinHeapNode* root, int arr[], int top) { if (root->left) { arr[top] = 0; printCodes(root->left, arr, top + 1); } if (root->right) { arr[top] = 1; printCodes(root->right, arr, top + 1); } if (isLeaf(root)) { cout << root->data << ": "; printArr(arr, top); } } void huffmanENCODING(char data[], int freq[], int size) { struct MinHeapNode* root = buildHuffmanTree(data, freq, size); int arr[100], top = 0; printCodes(root, arr, top); } class avltree; class dnode; class tnode; template<class T> class dlist; template<class T> class stack; template<class T> class bst; template<class T> class Lnode { T data; Lnode<T> * next; Lnode<T> * prev; public: Lnode() { next = NULL; prev = NULL; } Lnode(T d, Lnode* n = NULL) { data = d; next = n; } friend class dlist<T>; }; template <class T> class dlist { private: Lnode<T> head; // dummy head //Nested class starts from here. class dlistiterator { Lnode<T> * curr; public: friend class dlist; dlistiterator(Lnode<T>* n = NULL) { curr = n; } Lnode<T>* getNext() { if (curr->next != NULL) { return (curr->next); } else return NULL; } dlistiterator & operator++() { if (curr != NULL) { curr = curr->next; } return *this; } dlistiterator & operator--() { if (curr != NULL) { curr = curr->prev; } return *this; } bool operator!= (dlistiterator &it) const { if (curr != it.curr) { return true; } else return false; } T& operator*() { return curr->data; } T& getdata() { return curr->next->data; } }; public: typedef dlistiterator diterator; dlist() { head.next = NULL; } void insertatstart(T d) { Lnode <T> *node = new Lnode <T>(d); node->next = head.next; node->prev = NULL; if (head.next != NULL) { head.next->prev = node; } head.next = node; } void insertafter(dlistiterator it, T d) { Lnode<T>* node = new Lnode<T>(d); node->next = it.curr->next; if (node->next != NULL) { node->next->prev = node; } node->prev = it.curr; it.curr->next = node; } bool IsEmpty() { bool flag = false; if (head.next == NULL) { flag = true; } if (flag == true) { return true; } else { return false; } } void Remove(dlistiterator it) { Lnode<T>* temp = head.next; if (it.curr->next != NULL) { while (temp != it.curr->next) { } it.curr->next = temp->next; delete temp; } } void insertSorted(T d) { Lnode<T>* node = new Lnode<T>(d); Lnode<T>* temp = head.next; while (temp->next != 0 && temp->data < d) //Traversing to the required node. { temp = temp->next; } node->next = temp; //storing value. if (temp == head.next) { head.next = node; } else { temp->prev->next = node; } } void Remove(T d) { Lnode<T>* temp; if (head->data == d) { //First node to be deleted temp = head.next; head = head->next; delete temp; } else { temp = head.next; while (temp->next != 0 && temp->next->data < d) { temp = temp->next; } if (temp->next != 0 && temp->next->data == d) { if (temp->next == head.next) { head.next = temp->next; } else { temp->prev->next = temp->next; } delete temp; } } } dlistiterator begin() { dlistiterator obj(head.next); return obj; } dlistiterator end() { dlistiterator obj; return obj; //which will be NULL. } void RemoveAll() { Lnode <T> * node = head.next; Lnode <T> * temp = node->next; while (node != NULL) { delete node; node = temp; } } ~dlist() { RemoveAll(); } void printlist() { diterator temp = head.next; while (temp != end()) { cout << *temp << "\t"; ++temp; } cout << endl; } }; void stringcopy(char* str1, char* str2) { int i = 0; for (i = 0; str2[i] != '\0'; i++) { str1[i] = str2[i]; } str1[i] = '\0'; } class Helper { public: static char* GetStringFromBuffer(char* str); static int stringlength(char* str); static bool stringcompare(char* str1, char* str2); }; int Helper::stringlength(char* str) { int count = 0; for (int i = 0; str[i] != '\0'; i++) { count++; } return count; } bool Helper::stringcompare(char* str1, char* str2) { bool flag = true; for (int i = 0; str1[i] != '\0'; i++) { if (str1[i] != str2[i]) { flag = false; break; } } return flag; } char* Helper::GetStringFromBuffer(char* str) { char* buffer = new char[strlen(str) + 1]; int i = 0; for (i = 0; str[i] != '\0'; i++) { buffer[i] = str[i]; } buffer[i] = '\0'; return buffer; } template<class T> class stack { private: T * s; int maxsize; int stackptr; public: stack(int _size = 10) { s = new T[_size]; maxsize = _size; stackptr = 0; } ~stack() { if (s != nullptr) { delete[]s; s = nullptr; } } int getstackptr() { return stackptr; } bool isempty() { if (stackptr < 0) return true; return false; } bool isfull() { if (stackptr == maxsize) return true; return false; } T* getS() { return s; } bool push(T data) { if (!isfull()) { s[stackptr] = data; stackptr++; return true; } return false; } bool pop(T &data) { if (isempty()) { cout << "\nList is empty.\n"; return false; } else { stackptr--; data = s[stackptr]; return true; } } bool top(T &data) { if (isempty()) { cout << "\nList is empty.\n"; return false; } data = s[stackptr - 1]; return true; } void printlist() { cout << "\n\t"; for (int i = stackptr - 1; i >= 0; i--) cout << s[i] << "\n\t"; } }; bool search(int* arr, int key, int size) { for (int i = 0; i < size; i++) { if (key == arr[i]) return true; } return false; } template<class T> bool found(T* obj, int key, int size) { for (int i = 0; i < size; i++) { if (obj[i] == key) return true; } return false; } class tnode { friend class avltree; int data; int _height; tnode * next; tnode * prev; tnode * left; tnode *right; public: tnode() { next = nullptr; prev = nullptr; left = nullptr; right = nullptr; } ~tnode() { delete next; delete prev; delete left; delete right; } tnode(int d) { data = d; } }; class avltree { tnode* root; friend class tnode; public: avltree() { root = nullptr; } /*~avltree() { if (issn != nullptr) delete[] issn; if (references != nullptr) delete[] references; if (issuable != nullptr) delete[] issuable; if (authornames != '\0') delete[] authornames; if (title != '\0') delete[]title; }*/ /*void rotateright(tnode* &y) { tnode *x = y->left; tnode *z = x->right; x->right = y; y->left = z; y->_height = max(height(y->left), height(y->right)) + 1; x->_height = max(height(x->left), height(x->right)) + 1; } void rotateleft(tnode* &x) { tnode *y = x->right; tnode *z = y->left; y->left = x; x->right = z; x->_height = max(height(x->left), height(x->right)) + 1; y->_height = max(height(y->left), height(y->right)) + 1; }*/ void rotateright(tnode* &x) { tnode *y = x->left; x->left = y->right; y->right = x; x = y; } void rotateleft(tnode* &x) { tnode *y = x->right; x->right = y->left; y->left = x; x = y; } void doublerotateright(tnode* &x) { rotateleft(x->left); rotateright(x); } void doublerotateleft(tnode* &x) { rotateright(x->right); rotateleft(x); } int height(tnode *&N) { if (N == nullptr) return -1; return N->_height; } void balance(tnode*& ptr) { if (ptr == nullptr) return; else if (height(ptr->left) - height(ptr->right) > 1) { if (height(ptr->left->left) >= height(ptr->left->right)) rotateright(ptr); else doublerotateright(ptr); } else if (height(ptr->right) - height(ptr->left) > 1) { if (height(ptr->right->right) >= height(ptr->right->left)) rotateleft(ptr); else doublerotateleft(ptr); ptr->_height = max(height(ptr->left), height(ptr->right)) + 1; } } int max(int a, int b) { if (a < b) return b; return a; } int findmax(tnode* ptr) { while (ptr->right != nullptr) { ptr = ptr->right; } return ptr->data; } void insert(tnode* &r, int d) { if (r == nullptr) { r = new tnode(d); return; } if (r->data > d) { insert(r->left, d); if (height(r->left) - height(r->right) == 2) { if (d < r->left->data) { rotateright(r); } else { doublerotateright(r); } } } else if (d > r->data) { insert(r->right, d); if (height(r->left) - height(r->right) == 2) { if (d < r->right->data) { rotateleft(r); } else { doublerotateleft(r); } } } r->_height = 1 + max(height(r->left), height(r->right)); } void deletenode(tnode* & ptr, int d) { if (ptr == nullptr) return; if (ptr->data == d) { if (ptr->left == nullptr) { tnode* temp = ptr; ptr = ptr->right; delete temp; return; } else if (ptr->right == nullptr) { tnode* temp = ptr; ptr = ptr->left; delete temp; return; } else if (ptr->left != 0 && ptr->right != 0) { ptr->data = findmax(ptr->left); deletenode(ptr->left, ptr->data); } } if (d > ptr->data) { deletenode(ptr->right, d); } if (d < ptr->data) { deletenode(ptr->left, d); } balance(ptr); } void deletenode(int d) { return deletenode(root, d); } void print() { printavl(root); } void printavl(tnode *_root) { if (_root != nullptr) { cout << _root->data << " "; printavl(_root->left); printavl(_root->right); } } void recursivedelete(tnode* r) { if (r != nullptr) { recursivedelete(r->left); recursivedelete(r->right); delete r; } } tnode* search(tnode* r, int d) { if (r == nullptr) return r; if (r->data == d) return r; if (r->data < d) return search(r->right, d); else return search(r->left, d); } tnode* _search(tnode*r, int d) { return search(r, d); } ~avltree() { recursivedelete(root); } }; template <class T> class node { T data; node* right; node* left; public: node() { right = nullptr; left = nullptr; } node(T d, node*r, node*l) { data = d; left = l; right = r; } ~node() { if (right != nullptr) { delete[]right; right = nullptr; } if (left != nullptr) { delete[]left; left = nullptr; } } }; template<class T> class bst { node* root; public: bst() { root = nullptr; } void removeall(node * _node) { if (_node != nullptr) { removeall(_node->left); removeall(_node->right); delete _node; } } ~bst() { removeall(root); } tnode* search(node* r, int d) { if (r == nullptr) return r; if (r->data == d) return r; if (r->data < d) return search(r->right, d); else return search(l->left, d); } void insert(node*&r, int d) { if (r == nullptr) r = new node(d); if (r->data > d) insert(r->left, d); else insert(r->right, d); } tnode* search(T d) { return search(root, d); } void insert(T d) { _insert(root, d); } void _insert(node*&r, int d) { if (r == nullptr) r = new node(d); if (r->data > d) _insert(r->left, d); else _insert(r->right, d); } void iterative_insert(T d) { if (root == nullptr) root = new node(d); node* curr = root; node* temp = nullptr; while (curr != nullptr) { temp = curr; if (d < curr->data) curr = curr->left; else curr = curr->right; } if (d < temp->data) temp->left = new node(d); else temp->right = new node(d); } void printsorted(node *r) { if (r != nullptr) { printsorted(r->left); cout << r->data; printsorted(r->right); } } tnode* min(tnode* _node) { tnode* curr = _node; while (curr->left != nullptr) { curr = curr->left; } return curr; } tnode* remove(tnode* _root, int d) { if (_root == nullptr) return _root; if (d < _root->d) _root->left = remove(_root->left, d); else if (d > _root->d) _root->right = remove(_root->right, d); else { if (_root->left == nullptr) { tnode *temp = _root->right; free(_root); return temp; } else if (_root->right == nullptr) { tnode* temp = _root->left; free(_root); return temp; } tnode* _temp = min(_root->right); _root->d = _temp->d; _root->right = remove(_root->right, _temp->d); } return _root; } }; class _MinHeap { int *arrheap; int maxsize; int heapsize; public: _MinHeap(int size = 10) { heapsize = 0; maxsize = size; arrheap = new int[size]; } void MinHeapify(int i) { int l = left(i); int r = right(i); int smallest = i; if (l < heapsize && arrheap[l] < arrheap[i]) smallest = l; if (r < heapsize && arrheap[r] < arrheap[smallest]) smallest = r; if (smallest != i) { swap(arrheap[i], arrheap[smallest]); MinHeapify(smallest); } } int parentnode(int i) { return (i - 1) / 2; } int left(int i) { return (2 * i + 1); } int right(int i) { return (2 * i + 2); } int extractMin() { if (heapsize <= 0) return INT_MAX; if (heapsize == 1) { heapsize--; return arrheap[0]; } int data = arrheap[0]; arrheap[0] = arrheap[heapsize - 1]; heapsize--; MinHeapify(0); return data; } void decreaseKey(int i, int new_val) { arrheap[i] = new_val; while (i != 0 && arrheap[parent(i)] > arrheap[i]) { swap(arrheap[i], arrheap[parent(i)]); i = parent(i); } } int getMin() { return arrheap[0]; } void deleteKey(int i) { decreaseKey(i, INT_MIN); extractMin(); } void insertKey(int k) { if (heapsize == maxsize) { return; } heapsize++; int i = heapsize; arrheap[i] = k; while (i > 0) { if (arrheap[i] > arrheap[i / 2]) { swap(arrheap[i], arrheap[arrheap[i / 2]]); i = i / 2; } else return; } } int getleftchildindex(int parentindex) { return 2 * parentindex + 1; } int getrightchildindex(int parentindex) { return 2 * parentindex + 2; } int getparentindex(int childindex) { return(childindex - 1) / 2; } bool hasleftchild(int index) { return getleftchildindex(index) < heapsize; } bool hasrightchild(int index) { return getrightchildindex(index) < heapsize; } bool hasparent(int index) { return getparentindex(index) >= heapsize; } int leftchild(int index) { return arrheap[getleftchildindex(index)]; } int rightchild(int index) { return arrheap[getrightchildindex(index)]; } int parent(int index) { return arrheap[getparentindex(index)]; } void ensureextracapacity() { if (heapsize == maxsize) { maxsize *= 2; } } int peek() { if (heapsize != 0) return arrheap[0]; return 0; } }; void swap(int *x, int *y) { int temp = *x; *x = *y; *y = temp; } /*string decode(bstnode<Treenode<dat>>* root, string encoded_str) { string res = ""; bstnode<Treenode<dat>>* node = root; for (int i = 0; i != encoded_str.size(); ++i) { if (encoded_str[i] == '0') { // left child node = node->left; } else { // rigth child assert(encoded_str[i] == '1'); node = node->right; } if (node->is_leaf() == true) { res += node->letter; node = root; } } return res; }*/ HashTable* Filing() { char ch; ifstream fin; fin.open("data.txt"); HashTable *Hptr = new HashTable; if (fin.is_open()) { while (!fin.eof()) { fin.get(ch); Hptr->search(ch); } } else cout << "File not opened. Please insert data.txt file.\n"; return Hptr; } string decode_file(struct MinHeapNode* root, string s) { string ans = ""; struct MinHeapNode* curr = root; for (int i = 0;i < s.size();i++) { if (s[i] == '0') curr = curr->left; else curr = curr->right; // reached leaf node if (curr->left == NULL and curr->right == NULL) { ans += curr->data; curr = root; } } // cout<<ans<<endl; return ans + '\0'; } int main() { cout << "\t\t\t\tReading from file.\n\n"; HashTable* Hptr = Filing(); Hptr->print(); cout << "\n\n\n\t\t\t\tPrinting from heap.\n\n"; heap* Heap = Hptr->consHeap(); Heap->printHeap(); bstnode<dat>* BSptr = Heap->HuffTree(); cout << "\n\n\n\t\t\t\tPrinting bstTree.\n\n"; BSptr->printbstnode(); char arr[] = { 'l', 'x', 's', 'm', 'y', 'b','n','z','c','o','d','p','e','q','f','r','g','s','h','t','i','u','j','v','k','w',' ' }; int freq[] = { 10,3,5,2,2,9,3,5,13,4,5,5,11,6,11,6,15,8,9,3,10,3,11,3,10,4,5 }; int size = sizeof(arr) / sizeof(arr[0]); cout << "\n\n\n\n\t\t\t\tencoded data of file data.txt.\n\n\n"; huffmanENCODING(arr, freq, size); cout << "\n\n\t\t\t\tdecoded data of file data.txt.\n\n\n"; //string decodedString = decode_file(Heap,encodedstring); //cout << "\nDecoded Huffman Data:\n" << decodedString << endl; Hptr->deletehashtable(Hptr); Heap->deleteheap(Heap); _getch(); }
true
b07250bbb4d4395c289a2036233e9d189e5c3b8f
C++
vinay-12345678/Cplus
/hashmap/sumit malik/v-2.cpp
UTF-8
1,140
2.59375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; vector <string> find(vector <vector <string> >v){ unordered_map <string,bool> m; unordered_map <string,string> mp; for(auto i:v){ mp[i[0]]=i[1]; if(m.count(i[0])){ m[i[0]]=0; } else m[i[0]]=1; m[i[1]]=0; } string start; for(auto i:m){ if(i.second==1) start=i.first; } vector <string> ans; ans.push_back(start); while(mp.count(start)){ ans.push_back(mp[start]); start=mp[start]; } return ans; } int main() { #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif int n; cin>>n; vector <vector <string> >arr; vector <string> ans; while(n--){ string s; vector <string> v; cin>>s; v.push_back(s); cin>>s; v.push_back(s); arr.push_back(v); } ans=find(arr); for(int i=0;i<ans.size();i++){ if(i==ans.size()-1) cout<<ans[i]<<endl; else cout<<ans[i]<<"->"; } }
true
6097df1c621f74dda40756088a872d9de9842227
C++
eddyc/Signals
/Signals/VectorMaths.hpp
UTF-8
529
2.546875
3
[]
no_license
// // VectorMaths.hpp // Signals // // Created by Edward Costello on 15/01/2018. // Copyright © 2018 Edward Costello. All rights reserved. // #ifndef VectorMaths_hpp #define VectorMaths_hpp Vector<T> &fill(const T); Vector<T> &clear(); Vector<T> &multiply(const T); Vector<T> &add(const T); static void add(const Vector<T> &inputA, const Vector<T> &inputB, Vector<T> &output); static void multiply(const Vector<T> &input, const T &scalar, Vector<T> &output); Vector<T> &ramp(const T start, const T increment); #endif /* VectorMaths_hpp */
true
4b7fa94408641f51d5f6f2b0d938e9244a818d3d
C++
kchaloux/kitten
/yarn/JumpIfNone.cpp
UTF-8
377
2.671875
3
[ "MIT" ]
permissive
#include "JumpIfNone.h" #include "Option.h" #include "State.h" #include <ostream> void JumpIfNone::write(std::ostream& stream) const { stream << "jn " << offset; } Offset JumpIfNone::exec(State& state) const { const auto a = state.pop_data(); const auto& value = a->value<Option>(); if (value) { state.push_data(value); return 1; } return offset + 1; }
true
518306271b31260a608e0c692ef876934e691aa7
C++
xiaoyu602/Heap
/Heap.cpp
GB18030
525
3.0625
3
[]
no_license
#include "Heap.h" //void Test() // //{ // int a[] = {10,16,18,12,11,13,15,17,14,19}; // Heap<int> hp(a,sizeof(a)/sizeof(a[0])); // //hp.Push(20); //Ԫ20 // hp.Push(2); //Ԫ2 // hp.Pop(); //ɾɾȼߣ //} void Test1() { int a[] = {10,16,18,12,11,13,15,17,14,19}; //Heap<int> hp(a,sizeof(a)/sizeof(a[0])); //ĬϽ Heap<int,Less<int> > hp1(a,sizeof(a)/sizeof(a[0])); //С } int main() { //Test(); Test1(); return 0; }
true
844428be34a14bd08d1ea9fbfc7d5f703a23bb34
C++
petricm/DDMarlinPandora
/src/DDScintillatorPpdDigi.cc
UTF-8
4,993
2.75
3
[]
no_license
#include "DDScintillatorPpdDigi.h" #include <assert.h> #include "CLHEP/Random/RandPoisson.h" #include "CLHEP/Random/RandGauss.h" #include "CLHEP/Random/RandBinomial.h" #include <iostream> using std::cout; using std::endl; // this applies some extra digitisation to scintillator+PPD hits (PPD=SiPM, MPPC) // - poisson fluctuates the number of photo-electrons according to #PEs/MIP // - applies PPD saturation according to #pixels // Daniel Jeans, Jan/Feb 2014. // (split off from ILDCaloDigi Aug'14.) DDScintillatorPpdDigi::DDScintillatorPpdDigi() { _pe_per_mip=-99; _calib_mip=-99; _npix=-99; _misCalibNpix=0; _pixSpread=0; _elecNoise=0; } void DDScintillatorPpdDigi::printParameters() { cout << "--------------------------------" << endl; cout << "DDScintillatorPpdDigi parameters" << endl; cout << " pe_per_mip = " << _pe_per_mip << endl; cout << " calib_mip = " << _calib_mip << endl; cout << " npix = " << _npix << endl; cout << " misCalibNpix = " << _misCalibNpix << endl; cout << " pixSpread = " << _pixSpread << endl; cout << " elecDynRange = " << _elecMaxDynRange_MIP << endl; cout << " elecNoise = " << _elecNoise << endl; cout << "--------------------------------" << endl; return; } float DDScintillatorPpdDigi::getDigitisedEnergy(float energy) { float correctedEnergy(energy); if (_pe_per_mip<=0 || _calib_mip<=0 || _npix<=0) { cout << "ERROR, crazy parameters for DDScintillatorPpdDigi: PE/MIP=" << _pe_per_mip << ", MIP calib=" << _calib_mip << ", #pixels=" << _npix << endl; cout << "you must specify at least the #PE/MIP, MIP calibration, and #pixels for realistic scintillator digitisation!!" << endl; cout << "refusing to proceed!" << endl; assert(0); } // 1. convert energy to expected # photoelectrons (via MIPs) float npe = _pe_per_mip*energy/_calib_mip; //oh: commented out Daniel's digitisation model. (npe -> poisson -> saturation -> stoykov smearing). // Stoykov smearing used with Gaussian shape for lack of better model. /* // 2. smear according to poisson (PE statistics) npe = CLHEP::RandPoisson::shoot( npe ); if (_npix>0) { // 3. apply average sipm saturation behaviour npe = _npix*(1.0 - exp( -npe/_npix ) ); // 4. apply intrinsic sipm fluctuations (see e.g arXiv:0706.0746 [physics.ins-det]) float alpha = npe/_npix; // frac of hit pixels float width = sqrt( _npix*exp(-alpha)*( 1. - (1.+alpha)*exp(-alpha) ) ); // make an integer correction int dpix = int( floor( CLHEP::RandGauss::shoot(0, width) + 0.5 ) ); npe += dpix; } */ //AHCAL TB style digitisation: npe -> saturation -> binomial smearing //shown to be mathematically equivalent to Daniel's model above, but slightly faster and automatically generates correct shape instead of Gaussian approximation if (_npix>0){ // apply average sipm saturation behaviour npe = _npix*(1.0 - exp( -npe/_npix ) ); //apply binomial smearing float p = npe/_npix; // fraction of hit pixels on SiPM npe = CLHEP::RandBinomial::shoot(_npix, p); //npe now quantised to integer pixels } if (_pixSpread>0) { // variations in pixel capacitance npe *= CLHEP::RandGauss::shoot(1, _pixSpread/sqrt(npe) ); } if ( _elecMaxDynRange_MIP > 0 ) { // limited dynamic range of readout electronics // Daniel moved this here, before the unfolding of saturation (September 2015) npe = std::min ( npe, _elecMaxDynRange_MIP*_pe_per_mip ); } if (_elecNoise>0) { // add electronics noise npe += CLHEP::RandGauss::shoot(0, _elecNoise*_pe_per_mip); } if (_npix>0) { // 4. unfold the saturation // - miscalibration of npix float smearedNpix = _misCalibNpix>0 ? _npix*CLHEP::RandGauss::shoot( 1.0, _misCalibNpix ) : _npix; //oh: commented out daniel's implmentation of dealing with hits>smearedNpix. using linearisation of saturation-reconstruction for high amplitude hits instead. /* // - this is to deal with case when #pe is larger than #pixels (would mean taking log of negative number) float epsilon=1; // any small number... if ( npe>smearedNpix-epsilon ) npe=smearedNpix-epsilon; // - unfold saturation npe = -smearedNpix * std::log ( 1. - ( npe / smearedNpix ) ); */ const float r = 0.95; //this is the fraction of SiPM pixels fired above which a linear continuation of the saturation-reconstruction function is used. 0.95 of nPixel corresponds to a energy correction of factor ~3. if (npe < r*smearedNpix){ //current hit below linearisation threshold, reconstruct energy normally: npe = -smearedNpix * std::log ( 1. - ( npe / smearedNpix ) ); } else { //current hit is aove linearisation threshold, reconstruct using linear continuation function: npe = 1/(1-r)*(npe-r*smearedNpix)-smearedNpix*std::log(1-r); } } // convert back to energy correctedEnergy = _calib_mip*npe/_pe_per_mip; return correctedEnergy; }
true
2852099d366467ef342297de605b4bb3d83df934
C++
codingnoye/cpp_project
/main.cpp
UTF-8
19,690
2.65625
3
[]
no_license
#include <ncurses.h> #include <chrono> #include <string> #include <ctime> #include <fstream> #include <deque> #include <cstring> using namespace std; const int TITLE1 = 14; const int TITLE2 = 15; const int MISSION = 11; const int INFO = 10; const int MISSION_X = 12; const int MISSION_V = 13; const int BKGRD = 16; const int BODY = 1; const int WALL = 2; const int IWALL = 3; const int POISON = 5; const int GROWTH = 6; const int GATE1 = 7; const int GATE2 = 8; const int EMPTY = 9; const int NONE = -1; const int DOWN = 0; const int UP = 1; const int LEFT = 2; const int RIGHT = 3; const int CLOCKWISE[4] = {LEFT, RIGHT, UP, DOWN}; int getms() { return chrono::duration_cast<chrono::milliseconds> ( chrono::system_clock::now().time_since_epoch() ).count(); } struct pos{ int y; int x; }; class Game{ public: int map[21][21]; int going = NONE; int item_pos[100][2]; pos gate_pos[2]; // int itemcooltime; int sc_growth = 0; int sc_poison = 0; int sc_gate = 0; int item_tick; int mission[4]; //B,Grwoth,Poison,Gate bool game_over = false; int gate_cooltime = 0; int current_length = 0; int max_length = 0; int stage; int time_limit; int speed; int item_speed; int item_quantity; int difficult; deque<pos> body; WINDOW* win; WINDOW* info; WINDOW* miss; Game(WINDOW* win, WINDOW* info, WINDOW* miss, int stage) { this->win = win; this->info = info; this->miss = miss; this->stage = stage; init_pair(EMPTY, COLOR_WHITE, COLOR_WHITE); init_pair(BODY, COLOR_YELLOW, COLOR_YELLOW); init_pair(WALL, COLOR_CYAN, COLOR_CYAN); init_pair(IWALL, COLOR_CYAN, COLOR_CYAN); init_pair(GROWTH, COLOR_GREEN, COLOR_GREEN); init_pair(POISON, COLOR_RED, COLOR_RED); init_pair(GATE1, COLOR_MAGENTA, COLOR_MAGENTA); init_pair(GATE2, COLOR_MAGENTA, COLOR_MAGENTA); } int load_map(string uri) { ifstream readfile; readfile.open(uri); if (readfile.is_open()) { char tmp[64]; for (int y=0; y<21; y++) { readfile.getline(tmp, 64); for (int x=0; x<21; x++) { map[y][x] = tmp[x]-48; if (map[y][x]==0) map[y][x]=EMPTY; else if (map[y][x]==BODY) body.push_back(pos{y, x}); } } readfile.getline(tmp, 64); speed = stoi(string(tmp)); readfile.getline(tmp, 64); item_speed = stoi(string(tmp)); readfile.getline(tmp, 64); item_quantity = stoi(string(tmp)); readfile.getline(tmp, 64); difficult = stoi(string(tmp)); } else { return 1; } return 0; } char* to_char(string a, char* b){ strcpy(b,a.c_str()); return b; } void add_mission(){ srand((unsigned int)time(0)); mission[0] = rand()%5 + 3 + difficult*2; mission[1] = rand()%3 + 1 + difficult; mission[2] = rand()%3 + 1 + difficult; mission[3] = rand()%2 + 1 + difficult; char b[20]; time_limit = 550 - difficult*50; wclear(info); wborder(info, '@','@','@','@','@','@','@','@'); mvwprintw(info, 1, 2, "[ Score Board ]"); mvwprintw(info, 3, 2, "B : 3/3"); mvwprintw(info, 4, 2, "+ : 0"); mvwprintw(info, 5, 2, "- : 0"); mvwprintw(info, 6, 2, "G : 0"); mvwprintw(info, 8, 2, "[ Item Cooltime ]"); string tmp = "Item : "+ to_string(item_tick); mvwprintw(info, 9, 2, to_char(tmp,b)); wclear(miss); wborder(miss, '@','@','@','@','@','@','@','@'); wattron(miss, COLOR_PAIR(MISSION)); mvwprintw(miss, 1, 2, "[ MISSION ]"); wattroff(miss, COLOR_PAIR(MISSION)); wattron(miss, COLOR_PAIR(MISSION)); tmp = "Time Limit : "+ to_string(time_limit); mvwprintw(miss, 3, 2, to_char(tmp, b)); wattroff(miss, COLOR_PAIR(MISSION)); wattron(miss, COLOR_PAIR(MISSION)); tmp = "B : "+ to_string(mission[0]); mvwprintw(miss, 4, 2, to_char(tmp, b)); wattroff(miss, COLOR_PAIR(MISSION)); wattron(miss, COLOR_PAIR(MISSION_X)); tmp = "(X)"; mvwprintw(miss, 4, 10, to_char(tmp, b)); wattroff(miss, COLOR_PAIR(MISSION_X)); wattron(miss, COLOR_PAIR(MISSION)); tmp = "+ : "+ to_string(mission[1]); mvwprintw(miss, 5, 2, to_char(tmp, b)); wattroff(miss, COLOR_PAIR(MISSION)); wattron(miss, COLOR_PAIR(MISSION_X)); tmp = "(X)"; mvwprintw(miss, 5, 10, to_char(tmp, b)); wattroff(miss, COLOR_PAIR(MISSION_X)); wattron(miss, COLOR_PAIR(MISSION)); tmp = "- : "+ to_string(mission[2]); mvwprintw(miss, 6, 2, to_char(tmp, b)); wattroff(miss, COLOR_PAIR(MISSION)); wattron(miss, COLOR_PAIR(MISSION_X)); tmp = "(X)"; mvwprintw(miss, 6, 10, to_char(tmp, b)); wattroff(miss, COLOR_PAIR(MISSION_X)); wattron(miss, COLOR_PAIR(MISSION)); tmp = "G : "+ to_string(mission[3]); mvwprintw(miss, 7, 2, to_char(tmp, b)); wattroff(miss, COLOR_PAIR(MISSION)); wattron(miss, COLOR_PAIR(MISSION_X)); tmp = "(X)"; mvwprintw(miss, 7, 10, to_char(tmp, b)); wattroff(miss, COLOR_PAIR(MISSION_X)); wrefresh(info); wrefresh(miss); } bool mission_check(int item){ string tmp; char b[20]; tmp = "B : " + to_string(current_length) + "/" + to_string(max_length); mvwprintw(info, 3, 2, to_char(tmp, b)); wattron(miss, COLOR_PAIR(MISSION_V)); if(max_length == mission[0]) mvwprintw(miss, 4, 10, "(V)"); wattroff(miss, COLOR_PAIR(MISSION_V)); switch(item){ case GROWTH: wattron(miss, COLOR_PAIR(INFO)); tmp = "+ : "+ to_string(sc_growth); mvwprintw(info, 4, 2, to_char(tmp, b)); wattroff(miss, COLOR_PAIR(INFO)); wattron(miss, COLOR_PAIR(MISSION_V)); if(sc_growth == mission[1]) mvwprintw(miss, 5, 10, "(V)"); wattroff(miss, COLOR_PAIR(MISSION_V)); break; case POISON: wattron(miss, COLOR_PAIR(INFO)); tmp = "- : "+ to_string(sc_poison); mvwprintw(info, 5, 2, to_char(tmp, b)); wattroff(miss, COLOR_PAIR(INFO)); wattron(miss, COLOR_PAIR(MISSION_V)); if(sc_poison == mission[2]) mvwprintw(miss, 6, 10, "(V)"); wattroff(miss, COLOR_PAIR(MISSION_V)); break; case GATE1: case GATE2: wattron(miss, COLOR_PAIR(INFO)); tmp = "G : "+ to_string(sc_gate); mvwprintw(info, 6, 2, to_char(tmp, b)); wattroff(miss, COLOR_PAIR(INFO)); wattron(miss, COLOR_PAIR(MISSION_V)); if(sc_gate == mission[3]) mvwprintw(miss, 7, 10, "(V)"); wattroff(miss, COLOR_PAIR(MISSION_V)); break; } wattroff(miss, COLOR_PAIR(MISSION_V)); if(mission[0] <= max_length && mission[1] <= sc_growth && mission[2] <= sc_poison && mission[3] <= sc_gate) return true; wrefresh(info); wrefresh(miss); return false; } void clear_item(){ for(int i = 0; i<item_quantity; i++){ if(map[item_pos[i][0]][item_pos[i][1]]!=BODY) map[item_pos[i][0]][item_pos[i][1]] = EMPTY; } wrefresh(win); } void clear_gate(){ map[gate_pos[0].y][gate_pos[0].x] = WALL; map[gate_pos[1].y][gate_pos[1].x] = WALL; wrefresh(win); } void random_item(){ srand((unsigned int)time(0)); int percent = rand()%(item_quantity+1); for(int i = 0; i<percent; i++){ while(true){ int item_y = rand()%17 + 2; //1~19 random int item_x = rand()%17 + 2; if(map[item_y][item_x] == EMPTY){ map[item_y][item_x] = GROWTH; item_pos[i][0] = item_y; item_pos[i][1] = item_x; break; } } } //growth for(int i = percent; i<item_quantity; i++){ while(true){ int item_y = rand()%17 + 2; //1~19 random int item_x = rand()%17 + 2; if(map[item_y][item_x] == EMPTY){ map[item_y][item_x] = POISON; item_pos[i][0] = item_y; item_pos[i][1] = item_x; break; } } } //poision } void random_gate() { srand((unsigned int)time(0)); int gate_y, gate_x; while(true){ gate_y = rand()%21; gate_x = rand()%21; if(map[gate_y][gate_x] == WALL){ gate_pos[0] = pos {gate_y, gate_x}; break; } } map[gate_y][gate_x] = GATE1; while(true){ gate_y = rand()%21; gate_x = rand()%21; if(map[gate_y][gate_x] == WALL){ gate_pos[1] = pos {gate_y, gate_x}; break; } } map[gate_y][gate_x] = GATE2; } bool init(string map_uri) { load_map(map_uri); going = LEFT; current_length = 3; max_length = 3; item_tick = item_speed; random_item(); random_gate(); add_mission(); return true; } bool tick(int lastinput) { if (item_tick-- == 0) { clear_item(); random_item(); item_tick = item_speed; } string tmp = "Item : "+ to_string(item_tick) + " "; char b[25]; mvwprintw(info, 9, 2, to_char(tmp,b)); if (gate_cooltime-- == 0) { clear_gate(); random_gate(); } if(time_limit-- == 0){ game_over = true; return false; } tmp = "Time Limit : "+ to_string(time_limit) + " "; mvwprintw(miss, 3, 2, to_char(tmp, b)); wrefresh(miss); wrefresh(info); return move(lastinput); } bool is_center(pos gate) { return !(gate.x==0 || gate.y==0 || gate.x==20 || gate.y==20); } bool using_gate(pos now_gate, pos other_gate) { bool ic = is_center(other_gate); if (ic) { while (true) { pos gate_go = pos {other_gate.y + (going==UP?-1:0) + (going==DOWN?1:0), other_gate.x + (going==LEFT?-1:0) + (going==RIGHT?1:0)}; int go_tile = map[gate_go.y][gate_go.x]; if (!((go_tile == GATE1) || (go_tile == GATE2) || (go_tile == WALL) || (go_tile == IWALL))) break; going = CLOCKWISE[going]; } } else { if (other_gate.y==20) going = UP; else if (other_gate.y==0) going = DOWN; else if (other_gate.x==20) going = LEFT; else if (other_gate.x==0) going = RIGHT; } gate_cooltime = current_length-1; pos go = pos {other_gate.y + (going==UP?-1:0) + (going==DOWN?1:0), other_gate.x + (going==LEFT?-1:0) + (going==RIGHT?1:0)}; if (can_go(go)) return move_and_get_item(go); game_over = true; return false; } bool move(int direction) { switch (direction) { case UP: if (going != DOWN){ going = UP; break; } else{ game_over = true; return false; } case DOWN: if (going != UP){ going = DOWN; break; } else{ game_over = true; return false; } case LEFT: if (going != RIGHT){ going = LEFT; break; } else{ game_over = true; return false; } case RIGHT: if (going != LEFT){ going = RIGHT; break; } else{ game_over = true; return false; } } if (going != NONE) { pos go = body.front(); switch (going) { case UP: go.y -= 1; break; case DOWN: go.y += 1; break; case LEFT: go.x -= 1; break; case RIGHT: go.x += 1; break; } if (can_go(go)) { return move_and_get_item(go); } else { game_over = true; return false; } } return true; } bool move_and_get_item(pos go) { int go_tile = map[go.y][go.x]; if (go_tile == EMPTY) { // Basic move pos tail = body.back(); body.pop_back(); map[tail.y][tail.x] = EMPTY; body.push_front(go); map[go.y][go.x] = BODY; } else if (go_tile == GROWTH) { sc_growth += 1; current_length += 1; max_length = current_length>max_length?current_length:max_length; if(mission_check(go_tile)) return false; body.push_front(go); map[go.y][go.x] = BODY; if (gate_cooltime>=0) gate_cooltime++; } else if (go_tile == POISON) { sc_poison += 1; current_length -= 1; if(mission_check(go_tile)) return false; pos tail = body.back(); body.pop_back(); map[tail.y][tail.x] = EMPTY; tail = body.back(); body.pop_back(); map[tail.y][tail.x] = EMPTY; body.push_front(go); map[go.y][go.x] = BODY; if (current_length<3){ game_over = true; return false; } if (gate_cooltime>0) gate_cooltime--; } else if (go_tile == GATE1 || go_tile == GATE2) { sc_gate += 1; if(mission_check(go_tile)) return false; pos now_gate = gate_pos[go_tile-GATE1]; pos other_gate = gate_pos[GATE2-go_tile]; return using_gate(now_gate, other_gate); } return true; } bool can_go(pos go) { if ((map[go.y][go.x] == WALL) || (map[go.y][go.x] == IWALL) || (map[go.y][go.x] == BODY)){ game_over = true; return false; } return true; } void draw() { for (int y=0; y<21; y++) { for (int x=0; x<21; x++) { int now = map[y][x]; wattron(win, COLOR_PAIR(now)); mvwprintw(win, y, x*2, "aa"); wattroff(win, COLOR_PAIR(now)); } } wrefresh(win); } }; int main() { // Ncurses setting WINDOW* game_win; WINDOW* score_win; WINDOW* mission_win; initscr(); start_color(); curs_set(0); noecho(); init_pair(TITLE1, COLOR_WHITE, COLOR_BLACK); init_pair(TITLE2, COLOR_BLACK, COLOR_GREEN); int title_x = 10; int title_y = 5; attron(COLOR_PAIR(TITLE1)); mvprintw(title_y-1, title_x, "By TEAM Young-Rock"); attron(A_BOLD); mvprintw(title_y+7, title_x+12, "Press any key to start game"); attroff(COLOR_PAIR(TITLE1)); attron(COLOR_PAIR(TITLE2)); mvprintw(title_y+0, title_x, " _________ _______ _____ ____ __.___________"); mvprintw(title_y+1, title_x, " / _____/ \\ \\ / _ \\ | |/ _|\\_ _____/"); mvprintw(title_y+2, title_x, " \\_____ \\ / | \\ / /_\\ \\| < | __)_ "); mvprintw(title_y+3, title_x, " / \\/ | \\/ | \\ | \\ | \\"); mvprintw(title_y+4, title_x, "/_______ /\\____|__ /\\____|__ /____|__ \\/_______ /"); mvprintw(title_y+5, title_x, " \\/ \\/ \\/ \\/ \\/ "); attroff(COLOR_PAIR(TITLE2)); attroff(A_BOLD); getch(); clear(); init_pair(BKGRD, COLOR_BLACK, COLOR_BLACK); border('*', '*', '*', '*', '*', '*', '*', '*'); refresh(); game_win = newwin(22, 42, 1, 1); wrefresh(game_win); init_pair(INFO, COLOR_WHITE, COLOR_MAGENTA); score_win = newwin(11, 30, 1, 47); wbkgd(score_win, COLOR_PAIR(INFO)); wattron(score_win, COLOR_PAIR(INFO)); wborder(score_win, '@','@','@','@','@','@','@','@'); wrefresh(score_win); init_pair(MISSION, COLOR_WHITE, COLOR_CYAN); init_pair(MISSION_X, COLOR_WHITE, COLOR_RED); init_pair(MISSION_V, COLOR_WHITE, COLOR_GREEN); mission_win = newwin(9, 30, 13, 47); wbkgd(mission_win, COLOR_PAIR(MISSION)); wborder(mission_win, '@','@','@','@','@','@','@','@'); wrefresh(mission_win); keypad(stdscr, TRUE); nodelay(stdscr, TRUE); for(int i = 1; i<=5; i++){ // Game setting Game game(game_win, score_win, mission_win, i); int lastinput = NONE; int lasttime = getms(); game.init("maps/" + to_string(i)); // Main loop while (true) { int inp = getch(); if (inp == 110 || inp == 78) { break; } if (258<=inp && inp<=261) lastinput = inp - 258; int now = getms(); int dt = now - lasttime; if (dt>=game.speed) { if (!game.tick(lastinput)) { // Game over break; } game.draw(); wrefresh(game_win); lasttime = now; lastinput = NONE; } } //game_over || game_clear if(game.game_over){ wclear(mission_win); mvwprintw(mission_win, 1, 8, "[ Game Over! ]"); mvwprintw(mission_win, 3, 11, "ReStart?"); mvwprintw(mission_win, 4, 13, "Y/N"); wborder(mission_win, '@','@','@','@','@','@','@','@'); wrefresh(mission_win); int b; while(true){ b = getch(); if(b == 121 || b == 89){ i--; break; } else if(b == 110 || b == 78) break; } if(b == 110 || b == 78) break; } else if(i == 4){ wclear(mission_win); mvwprintw(mission_win, 1, 7, "[ Game Clear! ]"); mvwprintw(mission_win, 3, 11, "ReStart?"); mvwprintw(mission_win, 4, 13, "Y/N"); wborder(mission_win, '@','@','@','@','@','@','@','@'); wrefresh(mission_win); int b; while(true){ b = getch(); if(b == 121 || b == 89){ i=0; break; } else if(b == 110 || b == 78) break; } if(b == 110 || b == 78) break; } getch(); } delwin(game_win); endwin(); return 0; }
true
2abb3240958479b8c05b5b5caba48746408750c9
C++
Jodonghyun/aa1-17
/aa1-17-rpt05/AA17_tmp36_sensor/AA17_tmp36_sensor.ino
UTF-8
587
2.8125
3
[]
no_license
// // AA00, TMP36 sensor // #define TEMP_INPUT 0 // or int TEMP_INPUT = 0; void setup() { Serial.begin(9600); } void loop() { //getting the voltage reading from the temperature sensor int value = analogRead(TEMP_INPUT); // Print value Serial.print("AA16,AA17,value="); Serial.print(value); Serial.print(" : "); float voltage=value*5.0*1000; voltage/=1023.0; Serial.print(voltage); Serial.print(" mV, "); float temperatureC=(voltage-500)/10; Serial.print(temperatureC); Serial.println("degress C"); delay(1000); }
true
13fc99bc63a1f09417bfb3d6da206f55492844c7
C++
henrygranados/Advanced_programming
/CASTLE/Location.cpp
UTF-8
2,090
3.515625
4
[]
no_license
#include "Location.h" Location::Location() : name("") { monster = 0; adventurer = 0; visited = false; } Location::Location(string n) : name (n) { monster = 0; adventurer = 0; visited = false; } void Location::setName(string n) { name = n; } void Location::setMonster(Monster * m) { monster = m; //new Monster( * m); } Monster * Location::getMonster() const { return monster; } Adventurer * Location::getAdventurer() const { return adventurer; } void Location::setAdventurer(Adventurer * a) { adventurer = a; //new Adventurer(*a); } void Location::fight() { cout << adventurer->getName() << " Entered in " << name << endl << endl; cout << monster->getName() << " resides at " << name << endl << endl; cout << "Combat Begins: " << endl << endl ; adventurer->chooseWeapon(); while( monster->getLife() > 0 && adventurer->getLife() > 0) { cout << adventurer->getName() << " swings " << adventurer->getWeaponName(); if ( adventurer->isHit() ) { int mLife = monster->getLife(); int damage = adventurer->getDamage(); int remaining = mLife - damage; cout << " Hits!. " << monster->getName() << " loses " << damage << " hits, and remaining "; cout << remaining << " Hist!" << endl << endl; monster->setLife(remaining); if ( monster->getLife() <= 0) { cout << monster->getName() << " is dead" << endl; cout << adventurer->getName() << " Won 100 Golds" << endl; adventurer->addGold(100); return; } } else cout << " Misses." << endl << endl; if ( monster->isHit()) { int mLife = adventurer->getLife(); int damage = monster->getDamage(); int remaining = mLife - damage; cout << " Hits!. " << adventurer->getName() << " loses " << damage << " hits, and remaining "; cout << remaining << " Hist!" << endl << endl; adventurer->setLife(remaining); if ( adventurer->getLife() <= 0) { cout << adventurer->getName() << " is dead" << endl; cout << adventurer->getName() << " Lost the Game" << endl; return; } } else cout << monster->getName() << " Misses." << endl; } }
true
37e004f9838af609a6a4a7aa10ff622e50fe4298
C++
shulgaalexey/CtCI
/3_6.cpp
UTF-8
1,568
4.0625
4
[]
no_license
// 3.6 Write a programm to sort a stack in ascending order (with biggest items on top). // You may use at most one additional stack to hold items, but you may not copy the elements // into any other data structure (such as an array). // The stack supports the following operations: push, pop, peek, isEmpty #include <iostream> #include <stack> #include <algorithm> #include <stdlib.h> #include <time.h> using namespace std; // Variation of optimized bubble sort template <class T> bool separate(stack<T> &s1, stack<T> &s2, bool big) { bool changed = false; while(!s1.empty()) { const T v1 = s1.top(); s1.pop(); if(s1.empty()) { s2.push(v1); break; } // It may be implemented with a single temporary variable // but the method will be the same const T v2 = s1.top(); s1.pop(); if(big) { // separating bigger items if(v1 < v2) changed = true; // Order was changed s2.push(max(v1, v2)); s1.push(min(v1, v2)); } else { // separating smaller items if(v1 > v2) changed = true; // Order was changed s2.push(min(v1, v2)); s1.push(max(v1, v2)); } } return changed; } template <class T> stack<T> *sort(stack<T> *s1, stack<T> *s2) { do { separate(*s1, *s2, true); if(!separate(*s2, *s1, false)) break; } while(true); return (s1->empty()) ? s2 : s1; } int main(void) { stack<int> s1; //unsorted stack<int> s2; // buffer s1.push(1); s1.push(5); s1.push(2); s1.push(8); s1.push(3); stack<int> *s = sort(&s1, &s2); while(!s->empty()) { cout << s->top() << " "; s->pop(); } cout << endl; return 0; }
true
9a5d7fe9f028828d1a98bccf255605c70d957709
C++
kamilmaj94/ConsoleCubes
/ConsoleCubes/Game.hpp
UTF-8
1,578
2.578125
3
[]
no_license
#pragma once #include "Console.hpp" #include "Field.hpp" #include "Block.hpp" #include "Timer.hpp" #include "Menu.hpp" #include "ParameterMenuOption.hpp" enum class GameMode { GAME = 1, MENU, }; class Game { Console mConsole; GameMode mCurrentMode; Field mField; Field mNextBlockField; Timer mGameTimer; uint32_t mFieldOffsetX; uint32_t mFieldOffsetY; bool mMainLoopActive; bool mNeedsRedraw; bool mCleanRowAnim; Block* mCurrentBlock; Block* mNextBlock; uint32_t mNextBlockInd; double mBlockFallTime; uint32_t mClearedRows[4]; uint32_t mClearedRowsCount; uint32_t mAnimationStep; double mAnimationCounter; uint32_t mScore; uint32_t mLevel; uint32_t mLines; uint32_t mCurrentLevelLines; // menu-related variables Menu mMainMenuScreen; Menu mSetupMenuScreen; Menu* mCurrentMenuScreen; ParameterMenuOptionPtr mLevelMenuOption; void SwitchMenuCallback(Menu* newMenu); void ExitGameMenuCallback(); void StartGameCallback(); void OnEvent(INPUT_RECORD* event); void AdvanceBlock(); void AddBlockToField(); void UpdateGame(double delta); void ProcessGameInput(uint32_t keyCode); void AddScore(const uint32_t clearedRows); void DrawGame(); void ProcessMenuInput(uint32_t keyCode); void DrawMenu(uint32_t menuOffsetX, uint32_t menuOffsetY); public: Game(); ~Game(); bool Create(); bool SwitchToGameMode(uint32_t fieldX, uint32_t fieldY); bool SwitchToMenuMode(); void MainLoop(); };
true
cd6d739988a6ba8151bae6fb75eb73da28171499
C++
Ruthercode/OOP_lab_Mironchenko_KTbo2-7
/lab2-3/interactor.cpp
UTF-8
3,990
3.265625
3
[]
no_license
#include <iostream> #include <fstream> #include "queue.h" #include "stack.h" #include "food.h" #include "customer.h" #include "interactor.h" #include "factory.h" void Interactor::_help() const { std::cout <<"===========================================\n"; std::cout << "Disclaimer: \nYou have a restaurant.\n"; std::cout << "He displays his dishes on the window.\n"; std::cout << "There is a line of customers to him.\n"; std::cout <<"Each client wants to buy the freshest dish.\n"; std::cout <<"===========================================\n"; std::cout << "Commands: \n"; std::cout << "1) Show clients\n"; std::cout << "2) Show dishes\n"; std::cout << "3) Customer buy a dish\n"; std::cout << "4) Add new dish\n"; std::cout << "5) Add new client\n"; std::cout << "6) Help\n"; std::cout << "0) Exit\n"; std::cout <<"===========================================\n"; } Interactor::Interactor(): _clients(nullptr), _food(nullptr), _factory(ContainerFactory()) {} Interactor::~Interactor() { delete _clients; delete _food; } void Interactor::_fileInput(const std::string& clients_list, const std::string& food_list) { std::ifstream fin(clients_list); int num_of_clients; fin >> num_of_clients; for (int i = 0; i < num_of_clients; ++i) { std::string name; int money; fin >> name >> money; _clients->push( Customer(name,money) ); } fin.close(); std::ifstream in(food_list); int num_of_food; in >> num_of_food; for (int i = 0; i < num_of_food; ++i) { std::string name; int cost; in >> name >> cost; _food->push(Food(name, cost)); } in.close(); } void Interactor::_interaction() { int command = 1; while (command) { std::cout << "#Command: "; std::cin >> command; std::string name; unsigned int x; switch (command) { case 1: std::cout << _clients->out(); break; case 2: std::cout << _food->out(); break; case 3: if (_clients->isEmpty()) { std::cout << "There are no customers in the queue.\n"; } else if (_food->isEmpty()) { std::cout << "There are no dishes in the stack.\n"; } else if (_clients->front().buyFood(_food->front())) { std::cout << _clients->front().getNameOfClient() << " bought " << _food->front().getNameOfFood() << " for $ " << _food->front().getCostOfFood() << '\n'; _clients->pop(); _food->pop(); } else { std::cout << "The client does not have enough money for food.\n"; _clients->pop(); } break; case 4: std::cout << "Enter the name of the dish and its cost: "; std::cin >> name >> x; _food->push(Food(name, x)); break; case 5: std::cout << "Enter the name of the client and the amount of his money: "; std::cin >> name >> x; _clients->push(Customer(name, x)); break; case 6: _help(); break; default: break; } } } void Interactor::init(const std::string& clients_list, const std::string& food_list) { std::cout << "Customers list are stack?(y/n)\n"; char ans; std::cin >> ans; ans = tolower(ans); _clients = _factory.getClientsList(ans == 'y'); std::cout << "Food list are stack?(y/n)\n"; std::cin >> ans; ans = tolower(ans); _food = _factory.getFoodList(ans == 'y'); _fileInput(clients_list, food_list); _help(); _interaction(); }
true
c5163986510ef4283f9cbac24bbcd26381d4171c
C++
eTakazawa/procon-archive
/atcoder.jp/future-meets-you-contest-2018-open/future2018career_a/Main.cpp
UTF-8
6,640
2.859375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; #if 0 #define LOG_OP(a, b, c, d, e) (cerr << a << " " << b << " " << c << " " << d << " " << e << endl) #define LOG(a) (cerr << a << endl) #else #define LOG_OP(a, b, c, d, e) (cout << a+1 << " " << b+1 << " " << c+1 << " " << d+1 << " " << e << endl) #define LOG(a) #endif struct segtree_min { int N; vector<int> dat, sum; segtree_min(int n) { N = 1; while(N < n) N <<= 1; dat.assign(2*N-1,0); sum.assign(2*N-1,0); } void add(int a, int b, int x) { add(a,b,x,0,0,N); } int add(int a, int b, int x, int k, int l, int r) { if(b <= l or r <= a) return dat[k]; if(a <= l and r <= b) { sum[k] += x; return dat[k] += x; } int m = (l+r)/2; return dat[k] = min(add(a,b,x,2*k+1,l,m),add(a,b,x,2*k+2,m,r))+sum[k]; } int minimum(int a, int b) { return minimum(a,b,0,0,N); } int minimum(int a, int b, int k, int l, int r) { if(b <= l or r <= a) return 2e9; if(a <= l and r <= b) return dat[k]; int m = (l+r)/2; return min(minimum(a,b,2*k+1,l,m),minimum(a,b,2*k+2,m,r))+sum[k]; } }; struct segtree_max { int N; vector<int> dat, sum; segtree_max(int n) { N = 1; while(N < n) N <<= 1; dat.assign(2*N-1,0); sum.assign(2*N-1,0); } void add(int a, int b, int x) { add(a,b,x,0,0,N); } int add(int a, int b, int x, int k, int l, int r) { if(b <= l or r <= a) return dat[k]; if(a <= l and r <= b) { sum[k] += x; return dat[k] += x; } int m = (l+r)/2; return dat[k] = max(add(a,b,x,2*k+1,l,m),add(a,b,x,2*k+2,m,r))+sum[k]; } int maximum(int a, int b) { return maximum(a,b,0,0,N); } int maximum(int a, int b, int k, int l, int r) { if(b <= l or r <= a) return -2e9; if(a <= l and r <= b) return dat[k]; int m = (l+r)/2; return max(maximum(a,b,2*k+1,l,m),maximum(a,b,2*k+2,m,r))+sum[k]; } }; /*struct LazySegmentTree { private: int n; vector<ll> node, lazy; public: LazySegmentTree(vector<ll> v) { int sz = (int)v.size(); n = 1; while(n < sz) n *= 2; node.resize(2*n-1); lazy.resize(2*n-1, 0); for(int i=0; i<sz; i++) node[i+n-1] = v[i]; for(int i=n-2; i>=0; i--) node[i] = node[i*2+1] + node[i*2+2]; } void eval(int k, int l, int r) { if(lazy[k] != 0) { node[k] += lazy[k]; if(r - l > 1) { lazy[2*k+1] += lazy[k] / 2; lazy[2*k+2] += lazy[k] / 2; } lazy[k] = 0; } } void add(int a, int b, ll x, int k=0, int l=0, int r=-1) { if(r < 0) r = n; eval(k, l, r); if(b <= l || r <= a) return; if(a <= l && r <= b) { lazy[k] += (r - l) * x; eval(k, l, r); } else { add(a, b, x, 2*k+1, l, (l+r)/2); add(a, b, x, 2*k+2, (l+r)/2, r); node[k] = node[2*k+1] + node[2*k+2]; } } ll getsum(int a, int b, int k=0, int l=0, int r=-1) { if(r < 0) r = n; eval(k, l, r); if(b <= l || r <= a) return 0; if(a <= l && r <= b) return node[k]; ll vl = getsum(a, b, 2*k+1, l, (l+r)/2); ll vr = getsum(a, b, 2*k+2, (l+r)/2, r); return vl + vr; } };*/ template<class T> class bit { public: vector<T> dat; int N; bit(){} bit(int N) : N(N) { dat.assign(N,0); } // sum [0,i) T sum(int i){ int ret = 0; for(--i; i>=0; i=(i&(i+1))-1) ret += dat[i]; return ret; } // sum [i,j) T sum(int i, int j) { return sum(j) - sum(i); } // add x to i void add(int i, T x) { for(; i < N; i|=i+1) dat[i] += x; } }; class Segtrees { public: bit<int> seg_sum; segtree_max seg_max; segtree_min seg_min; Segtrees(int n): seg_sum(n), seg_max(n), seg_min(n) {} void add(int l, int r, int a) { for (int i = l; i <= r; i++) seg_sum.add(i, a); seg_max.add(l, r + 1, a); seg_min.add(l, r + 1, a); } int getmax(int l, int r) { return seg_max.maximum(l, r + 1); } int getmin(int l, int r) { return seg_min.minimum(l, r + 1); } int getsum(int l, int r) { return seg_sum.sum(l, r + 1); } int sum_arange(int l, int r) { return (l + r + 2) * (r - l + 1) / 2; } }; int N, K; void op(int i, int j, int k, int l, int v, Segtrees& A) { LOG_OP(i, j, k, l, v); assert(i <= j && k <= l); assert(0 <= v && v <= N - 1); assert(j < k || l < i); assert(j - i == l - k); A.add(i, j, -v); A.add(k, l, v); } void proc1(int& maxdiff1, int& maxid1, Segtrees& A, int width, int start = 0) { for (int i = start; i < N - width; i+=5) { int diff = A.getsum(i, i + width) - A.sum_arange(i, i + width); int mn = A.getmin(i, i + width); if (diff <= 0 || mn <= 1) continue; diff = min(diff / (width + 1), mn - 1); if (maxdiff1 < diff) { maxdiff1 = diff; maxid1 = i; } } } void proc2(int& maxdiff2, int& maxid2, Segtrees& A, int width, int start) { for (int i = start; i < N - width; i+=5) { int diff = A.getsum(i, i + width) - A.sum_arange(i, i + width); int mx = A.getmax(i, i + width); if (diff >= 0 || mx >= N) continue; diff = min(abs(diff) / (width + 1), N - mx); if (maxdiff2 < diff) { maxdiff2 = diff; maxid2 = i; } } } int main(void) { cin >> N >> K; Segtrees A(N); for (int i = 0; i < N; i++) { int tmp;cin >> tmp; A.add(i, i, tmp); } int width = 30 - 1; int samelimit = 33; int prevt = -1, samecount = 0; for (int t = 0; t < K; t++) { int maxdiff1 = 0, maxid1 = -1; int maxdiff2 = 0, maxid2 = -1; if (t == prevt) { samecount++; if (samecount > samelimit) { width--; samecount = 0; } } if (width == 0) { for (; t < K; t++) { LOG_OP(1, 2, 3, 4, 0); } break; } prevt = t; if (rand() % 2 == 0) { proc1(maxdiff1, maxid1, A, width, 0); if (!(maxid1 != -1)) {t--; continue;} proc2(maxdiff2, maxid2, A, width, maxid1 + width + 1); if (!(maxid2 != -1)) {t--; continue;} } else { proc2(maxdiff2, maxid2, A, width, 0); if (!(maxid2 != -1)) {t--; continue;} proc1(maxdiff1, maxid1, A, width, maxid2 + width + 1); if (!(maxid1 != -1)) {t--; continue;} } assert(maxdiff1 > 0 && maxdiff2 > 0); int v = min(maxdiff1, maxdiff2); op(maxid1, maxid1+width, maxid2, maxid2+width, v, A); } return 0; }
true
c435b443ddfae5c7b4038fd34925280051f4862d
C++
ElliotSis/Projets
/C:C++/POO Polytechnique/TP1/include/chauffage.h
UTF-8
823
3.3125
3
[]
no_license
#ifndef CHAUFFAGE_H #define CHAUFFAGE_H /** \brief Classe représentant le Chauffage d'une Maison. * \author Elliot Sisteron * \date 16/09/2015 */ class Chauffage { public: /** \brief Constructeur par défaut. */ Chauffage(); /** \brief Destructeur par défaut. */ virtual ~Chauffage(); /** \brief Accède à la variable estAllume_. * \return La valeur de la variable estAllume_. */ bool obtenirEstAllume() const; /** \brief Allume le chauffage. * Ne change rien si le chauffage est déjà allumé. */ void allume(); /** \brief Éteint le chauffage. * Ne change rien si le chauffage est déjà éteint. */ void eteindre(); private: bool estAllume_; //!< État du chauffage. }; #endif // CHAUFFAGE_H
true
d0657b51ef9f2bc4c88426db1340bb43e84723bd
C++
aviaryal/cse1325
/elsa/sprint_1/order.cpp
UTF-8
841
3.203125
3
[]
no_license
#include "order.h" Order::Order(Customer &customer):_customer(customer) { } Order::~Order() { } /* Order::Order(const Order &rhs):_customer{rhs._customer},_product{rhs._product} { } Order & Order::operator=(const Order &order) { this->_customer=order._customer; this->_product=order._product; //for(auto v: this->_product) //order._product.push_back(v); } */ //is this void or int int Order::add_product(Desktop &desktop) { _product.push_back(&desktop); return _product.size()-1; } double Order::price() const { double cost=0; for(auto v: _product) { cost+=v->price(); } return cost; } std::ostream &operator<<(std::ostream &ost, const Order &order) { double total= order.price(); ost<<order._customer<<"\n"; for(auto v:order. _product) ost<<*v<<"\n"; ost<<std::to_string(total); return ost; }
true
944164da0bd43ea54d3ef64007120cc47605d26c
C++
aishjb/90-days-ofCode-c-
/8_vector_demo.cpp
UTF-8
559
3.25
3
[]
no_license
#include<iostream> #include<vector> using namespace std; int main() { vector<int>v; for(int i=0;i<100;i++) { cout<<"capacity"<<v.capacity()<<endl; cout<<"size"<<v.size()<<endl; v.push_back(i); } /* v.push_back(11); v.push_back(12); v.push_back(13); for(int i=0;i<v.size();i++) { cout<<v[i]<<endl; } v.pop_back(); cout<<v.size()<<endl; for(int i=0;i<v.size();i++) { cout<<v[i]<<endl; } cout<<v[0]<<endl; cout<<v[1]<<endl; cout<<v[2]<<endl; cout<<v.size()<<endl; //cout<<v.at(5); */ return 0; }
true
e319cd7fb25a70cd391679db963481f630c6afe5
C++
brandonjones085/finalZooTycoon
/Turtle.cpp
UTF-8
624
2.6875
3
[]
no_license
/******************************************************************************* ** Author: Brandon Jones ** Date: 04/21/2019 ** Description: This is the ant class for the langstons ant program *******************************************************************************/ #include "Turtle.hpp" Turtle::Turtle() { this->age = 1; this->cost = 100; this->numOfBabies = 10; this->baseFoodCost = 10; this->payoff = 0.05; } //Finds the food cost for the turtles double Turtle::turtleFoodCost() { double base = getBaseFoodCost(); return base * 0.5; } Turtle::~Turtle() { }
true
ec2f4a458e6d5055a0fbdf7f60def51b2ca81712
C++
azartheen/leetcode
/30days-challenge/202004/day4.cpp
UTF-8
1,147
3.8125
4
[ "MIT" ]
permissive
/* Move Zeroes Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. Example: Input: [0,1,0,3,12] Output: [1,3,12,0,0] Note: You must do this in-place without making a copy of the array. Minimize the total number of operations. */ class Solution { public: void moveZeroes(vector<int>& nums) { int k=0; int sz=nums.size(); // loop thru the array and check if it is non-zero // if so, move it to position k and increase k by 1 // 0 1 0 3 12 // k = 0 // ^ // 1 1 0 3 12 // k = 1 // ^ // 1 3 0 3 12 // k = 2 // ^ // 1 3 12 3 12 // k = 3 for(int i=0;i<sz;i++) if(nums[i]!=0) nums[k++]=nums[i]; // Starting from position k, replace all the number with 0 till nums.size()-1 // 1 3 12 3 12 // k = 3 // ^ // 1 3 12 0 0 for(int i=k;i<sz;i++) nums[i]=0; } }; static const auto io_sync_off = []() {std::ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);return 0;}();
true
1df3612653aa96be9917516bdbce6551c90e43e7
C++
zayim/ProgrammingIntro
/LV3/LV3Z4.cpp
UTF-8
337
3.171875
3
[]
no_license
#include <iostream> #include <cmath> using namespace std; int main() { float r=0.0,x; int i=-1,n; cout << "Unesi n: "; cin >> n; cout << "Unesi otpore: "; while (++i<n) { cin >> x; r+=(1.0/x); } cout << "Ukupan paralelni otpor: " << 1.0/r << endl; return 0; }
true
a0d685ef2456027017c17b66e0aec44bcbc5e5b4
C++
duand/wifi-car-esp8266
/WifiCarESP8266_AP/WifiCarESP8266_AP.ino
UTF-8
2,898
3.265625
3
[]
no_license
/** @file WifiCarESP8266_AP.ino @brief Simple example of Wifi Car controlled by a web server in AP Mode. See also : http://www.instructables.com/id/A-very-cheap-ESP8266-WiFi-smart-car-controlled-by-/ List of commands to control the car : - http://<YourIP>:<YourPort>/?State=F (Forward) - http://<YourIP>:<YourPort>/?State=B (Backward) - http://<YourIP>:<YourPort>/?State=R (TurnRight) - http://<YourIP>:<YourPort>/?State=L (TurnLeft) - http://<YourIP>:<YourPort>/?State=S (Stop) @author LACOUR Vincent @date 2018-01 */ #include <ESP8266WiFi.h> #include <ESP8266WebServer.h> const char *ssid = "Wifi_Car_ESP8266"; // SSID Name const char *password = "wificarpassword"; // SSID Password : Between 8 and 32 carateres IPAddress ip(192, 168, 4, 1); // IP Address IPAddress netmask(255, 255, 255, 0); // Netmask const int port = 80; // Port ESP8266WebServer server(port); // Motors pins static const uint8_t pwm_A = 5 ; static const uint8_t pwm_B = 4; static const uint8_t dir_A = 0; static const uint8_t dir_B = 2; // Motor speed = [0-1024] int motor_speed = 1024; void setup() { WiFi.mode(WIFI_AP); //Only Access point WiFi.softAPConfig(ip, ip, netmask); WiFi.softAP(ssid, password); // Declaration of motors pinMode(pwm_A, OUTPUT); // PMW A pinMode(pwm_B, OUTPUT); // PMW B pinMode(dir_A, OUTPUT); // DIR A pinMode(dir_B, OUTPUT); // DIR B // Start Server server.on("/", HTTP_GET, handleRoot); server.begin(); } void loop() { server.handleClient(); } void handleRoot() { if (server.hasArg("State")) { String command = server.arg("State"); if (command.equals("F")) { forward(); server.send(200, "text / plain", "Forward"); } else if (command.equals("B")) { backward(); server.send(200, "text / plain", "Backward"); } else if (command.equals("L")) { turn_left(); server.send(200, "text / plain", "Turn Left"); } else if (command.equals("R")) { turn_right(); server.send(200, "text / plain", "Turn Right"); } else if (command.equals("S")) { stop_motors(); server.send(200, "text / plain", "Stop"); } } } void stop_motors() { analogWrite(pwm_A, 0); analogWrite(pwm_B, 0); } void backward() { analogWrite(pwm_A, motor_speed); analogWrite(pwm_B, motor_speed); digitalWrite(dir_A, LOW); digitalWrite(dir_B, HIGH); } void forward() { analogWrite(pwm_A, motor_speed); analogWrite(pwm_B, motor_speed); digitalWrite(dir_A, HIGH); digitalWrite(dir_B, LOW); } void turn_left() { analogWrite(pwm_A, motor_speed); analogWrite(pwm_B, motor_speed); digitalWrite(dir_A, HIGH); digitalWrite(dir_B, HIGH); } void turn_right() { analogWrite(pwm_A, motor_speed); analogWrite(pwm_B, motor_speed); digitalWrite(dir_A, LOW); digitalWrite(dir_B, LOW); }
true
bbc4f1e2d2f93122ab5a549afb4158cd9e23c0ab
C++
Liuqianqian007/learncs
/algorithm/201101_oj380.cpp
UTF-8
863
2.96875
3
[]
no_license
/************************************************************************* > File Name: 201101_oj380.cpp > Author: liuqian > Mail: > Created Time: Tue 03 Nov 2020 04:46:32 PM CST ************************************************************************/ #include<iostream> #include<string> #include<algorithm> using namespace std; //大统领投票 //需要用到编号,把编号和票数放在一个结构体中 struct Node { int index; string data; }; Node arr[105]; bool cmp(Node a, Node b) { if (a.data.size() == b.data.size()) return a.data > b.data; return a.data.size() > b.data.size(); } int main() { int n; cin >> n; for (int i = 0; i < n; i++) { cin >> arr[i].data; arr[i].index = i + 1; } sort(arr, arr + n, cmp); cout << arr[0].index << endl << arr[0].data << endl; return 0; }
true
d9085d7e24b0d7fd3a14d4fea0b4005cbc20bc9f
C++
wzyy2/chromium-browser
/chrome/browser/installable/installable_task_queue_unittest.cc
UTF-8
2,998
2.765625
3
[ "BSD-3-Clause" ]
permissive
// Copyright 2017 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. #include "chrome/browser/installable/installable_manager.h" #include "testing/gtest/include/gtest/gtest.h" using IconPurpose = content::Manifest::Icon::IconPurpose; class InstallableTaskQueueUnitTest : public testing::Test {}; // Constructs an InstallableTask, with the supplied bools stored in it. InstallableTask CreateTask(bool check_installable, bool fetch_valid_primary_icon, bool fetch_valid_badge_icon) { InstallableTask task; task.first.check_installable = check_installable; task.first.fetch_valid_primary_icon = fetch_valid_primary_icon; task.first.fetch_valid_badge_icon = fetch_valid_badge_icon; return task; } bool IsEqual(const InstallableTask& task1, const InstallableTask& task2) { return task1.first.check_installable == task2.first.check_installable && task1.first.fetch_valid_primary_icon == task2.first.fetch_valid_primary_icon && task1.first.fetch_valid_badge_icon == task2.first.fetch_valid_badge_icon; } TEST_F(InstallableTaskQueueUnitTest, PausingMakesNextTaskAvailable) { InstallableTaskQueue task_queue; InstallableTask task1 = CreateTask(false, false, false); InstallableTask task2 = CreateTask(true, true, true); task_queue.Add(task1); task_queue.Add(task2); EXPECT_TRUE(IsEqual(task1, task_queue.Current())); // There is another task in the main queue, so it becomes current. task_queue.PauseCurrent(); EXPECT_TRUE(IsEqual(task2, task_queue.Current())); } TEST_F(InstallableTaskQueueUnitTest, PausedTaskCanBeRetrieved) { InstallableTaskQueue task_queue; InstallableTask task1 = CreateTask(false, false, false); InstallableTask task2 = CreateTask(true, true, true); task_queue.Add(task1); task_queue.Add(task2); EXPECT_TRUE(IsEqual(task1, task_queue.Current())); task_queue.PauseCurrent(); EXPECT_TRUE(IsEqual(task2, task_queue.Current())); task_queue.UnpauseAll(); // We've unpaused "1", but "2" is still current. EXPECT_TRUE(IsEqual(task2, task_queue.Current())); task_queue.Next(); EXPECT_TRUE(IsEqual(task1, task_queue.Current())); } TEST_F(InstallableTaskQueueUnitTest, NextDiscardsTask) { InstallableTaskQueue task_queue; InstallableTask task1 = CreateTask(false, false, false); InstallableTask task2 = CreateTask(true, true, true); task_queue.Add(task1); task_queue.Add(task2); EXPECT_TRUE(IsEqual(task1, task_queue.Current())); task_queue.Next(); EXPECT_TRUE(IsEqual(task2, task_queue.Current())); // Next() does not pause "1"; it just drops it, so there is nothing to // unpause. task_queue.UnpauseAll(); // "2" is still current. EXPECT_TRUE(IsEqual(task2, task_queue.Current())); // Unpausing does not retrieve "1"; it's gone forever. task_queue.Next(); EXPECT_FALSE(task_queue.HasCurrent()); }
true
0c23df45e3168f0086825d242272996197849a0a
C++
Masters-Akt/CS_codes
/leetcode_sol/2121-Intervals_Between_Identical_Elements.cpp
UTF-8
1,574
3.46875
3
[]
no_license
//M-1 - Brute Force - O(N2) - TLE class Solution { public: vector<long long> getDistances(vector<int>& arr) { map<int, vector<int>> m; for(int i=0;i<arr.size();i++) m[arr[i]].push_back(i); vector<long long> ans(arr.size(), 0); for(auto x: m){ vector<int> ind = x.second; for(int j=0;j<ind.size();j++){ long long sum = 0; for(int k=0;k<ind.size();k++){ sum+=abs(ind[j]-ind[k]); } ans[ind[j]] = sum; } } return ans; } }; //M-2 - Optimized class Solution { public: vector<long long> getDistances(vector<int>& arr) { //Formula Used /* Take example A, B, C, D, E calc for C : = |C-A|+|C-B|+|D-C|+|E-C| Hence first two can be opened as 2*C-(A+B) and later two as (D+E)-2*C Hence prefix sum concept to be used from both side of the array and final answer can be achieved */ unordered_map<int, long long> m; //keeping count entries unordered_map<int, long long> sum; //keepng prefix sum; vector<long long> ans(arr.size(), 0); for(int i=0;i<arr.size();i++){ ans[i]+=(m[arr[i]]*i*1ll-sum[arr[i]]); m[arr[i]]++; sum[arr[i]]+=i; } m.clear(); sum.clear(); for(int i=arr.size()-1;i>=0;i--){ ans[i]+=(sum[arr[i]]-(m[arr[i]]*i*1ll)); m[arr[i]]++; sum[arr[i]]+=i; } return ans; } };
true
b6906fdc14d9ce98450b4c2bc33d78a3ef05d847
C++
Kn-Jakub/SmartServer
/inc/Thread.h
UTF-8
2,014
3.125
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: Thread.h * Author: JosoP * * Created on Utorok, 2017, decembra 19, 16:57 */ #ifndef THREAD_H #define THREAD_H #include <pthread.h> #include "../lbr_c++/definitions.h" class Thread { public: Thread(){ /*must be emty*/}; /** * Function starts main thread with threadMain() function * @return true if the thread was successfully started, false if there was an error starting the thread */ bool StartInternalThread() { return (pthread_create(&thread, NULL, InternalThreadEntryFunc, this) == 0); } /** * Function starts second thread with threadControl() function * @return true if the thread was successfully started, false if there was an error starting the thread */ bool StartControlThread() { return (pthread_create(&threadControler, NULL, ControlThreadEntryFunc, this) == 0); } /** * Function is waiting until the internal thread has exited */ void WaitForInternalThreadToExit() { (void) pthread_join(thread, NULL); } /** * Function is waiting until the internal thread has exited */ void WaitForControlThreadToExit() { (void) pthread_join(threadControler, NULL); } ~Thread() {/* empty */} protected: /** Implement this method in your subclass with the code you want your thread to run. */ virtual void threadMain() {}; virtual void threadControl() {}; private: static void * InternalThreadEntryFunc(void * This) { ((Thread *)This)->threadMain(); return NULL; } static void * ControlThreadEntryFunc(void * This) { ((Thread *)This)->threadControl(); return NULL; } private: pthread_t thread; pthread_t threadControler; }; #endif /* THREAD_H */
true
0d78036a9ef4673287b663e54a326185be0bdd97
C++
GhermanCristian/Sem2_OOP
/Lab Tests/TestLab10OOP2018/userInterface.cpp
UTF-8
2,516
3.40625
3
[]
no_license
#include "userInterface.h" #include <iostream> #include <fstream> void UserInterface::addRefrigeratorInterface(){ int uniqueID; int weight; std::string usageClass; bool hasFreezer; std::cin >> uniqueID >> weight >> usageClass >> hasFreezer; this->actionController.addRefrigerator(uniqueID, weight, usageClass, hasFreezer); } void UserInterface::addDishWashingMachineInterface(){ int uniqueID; int weight; int washingCycleLength; int electricityPerHour; std::cin >> uniqueID >> weight >> washingCycleLength >> electricityPerHour; this->actionController.addDishWashingMachine(uniqueID, weight, washingCycleLength, electricityPerHour); } UserInterface::UserInterface(){ ; } void UserInterface::startProgram(){ int command; while (true) { std::cout << "0. Exit\n"; std::cout << "1. Add refrigerator (id weight usageClass hasFreezer)\n"; std::cout << "2. Add dish washing machine (id weight washingCycleLength electricityPerHour\n"; std::cout << "3. Show all appliances\n"; std::cout << "4. Show sorted appliances\n"; std::cout << "5. Save to file electricity < than\n"; std::cout << "\n"; std::cin >> command; if (command == 0) { std::cout << "Program has ended\n"; return; } else if(command == 1) { try { this->addRefrigeratorInterface(); } catch (std::exception& currentException) { std::cout << currentException.what() << "\n"; } } else if (command == 2) { try { this->addDishWashingMachineInterface(); } catch (std::exception& currentException) { std::cout << currentException.what() << "\n"; } } else if (command == 3) { std::vector<Appliance*> allAppliances = this->actionController.getAllAppliances(); for (auto currentAppliance : allAppliances) { std::cout << currentAppliance->toString() << "\n"; } } else if (command == 4) { std::vector<Appliance*> sortedAppliances = this->actionController.getAppliancesSortedByWeight(); for (auto currentAppliance : sortedAppliances) { std::cout << currentAppliance->toString() << "\n"; } } else if (command == 5) { int maximumElectricity; std::cin >> maximumElectricity; std::ofstream outputStream("savedAppliances.txt"); std::vector <Appliance*> filteredAppliances = this->actionController.getFilteredAppliances(maximumElectricity); for (auto currentAppliance : filteredAppliances) { outputStream << currentAppliance->toString() << "\n"; } outputStream.close(); } } } UserInterface::~UserInterface(){ ; }
true
488a5180869653afab731296d7d75c4d57576f7d
C++
variablemayank/competetive-programming-codes
/Problem b DIV 373.cpp
UTF-8
332
2.734375
3
[]
no_license
#include<stdio.h> int main() { int t; int arr[200000],i; scanf("%d",&t); while(t--) { int n; scanf("%d",&n); for( i=0;i<n;i++) { scanf("%d",&arr[i]); } for(i=0;i<n;i++) { if(arr[i]%2==1) { arr[i+1]= arr[i+1]-1; } } if(i==n-1 && arr[i]%2==1) printf("NO\n"); else printf("YES\n"); } }
true
dbac40bbceab85818ce89745d26db9560420ba56
C++
ssribeiro/abjalu
/arduino_codes/NodeMCU_SLAVE_ONE/protocol.ino
UTF-8
973
2.75
3
[]
no_license
const char BOARD_ADDRESS = '1'; /* * PROTOCOL * * sample: * * 0AR -> read board 0 sensor * 1AR -> read board 1 sensor * * 0A1S -> set relay for board 0 to ON (1) * 1A0S -> set relay for board 1 to OFF (0) */ void sayMaster(String s) { writeMode(); delay(500); rsSerial.println(s); rsSerial.flush(); delay(5); readMode(); } const char ADDRESS = 'a'; const char READ = 'r'; const char SET = 's'; char destination = 'n'; char lastByte = 'n'; void runProtocol(char c) { if(c != -1) { if(c == ADDRESS) destination = lastByte; if(destination == BOARD_ADDRESS) { if(c == READ) readOperation(); if(c == SET) writeOperation(lastByte); } lastByte = c; } } void readOperation() { String msg = "" + analogRead(A0); sayMaster(msg); } void writeOperation(char value) { if( value == '1') digitalWrite(loadPin, HIGH); else digitalWrite(loadPin, LOW); }
true
b65e51ad340f280febe2b976a326144421377efc
C++
matthewh806/mandelbrot
/mandelbrot/fractal_plotter.cpp
UTF-8
1,363
2.875
3
[]
no_license
// // fractal_plotter.cpp // mandelbrot // // Created by Matthew on 11/01/2019. // Copyright © 2019 Matthew Harris. All rights reserved. // #include "fractal_plotter.hpp" #include <FreeImage.h> const int N = 256; const int N3 = N * N * N; std::tuple<int, int, int> get_rgb_piecewise_linear(int n, int iter_max) { double t = (double)n/(double)iter_max; n = (int) ( t * (double)N3 ); int b = n / (N*N); int nn = n - b * N * N; int r = nn / N; int g = nn - r * N; return std::tuple<int, int, int>(r, g, b); } void plot(window<int> &scr, std::vector<int> &colors, int iter_max) { FreeImage_Initialise(); FIBITMAP *bitmap = FreeImage_Allocate(scr.width(), scr.height(), 32); int k = 0; for(int i = scr.y_min(); i < scr.y_max(); i++) { for(int j = scr.x_min(); j < scr.x_max(); j++) { int n = colors[k]; auto rgb = get_rgb_piecewise_linear(n, iter_max); RGBQUAD col; col.rgbRed = std::get<0>(rgb); col.rgbBlue = std::get<1>(rgb); col.rgbGreen = std::get<2>(rgb); FreeImage_SetPixelColor(bitmap, j, i, &col); k++; } } FreeImage_Save(FIF_PNG, bitmap, "mandelbrot.png"); FreeImage_Unload(bitmap); FreeImage_DeInitialise(); }
true
7fe51375146693dd0a424299ba2e42537b7e514c
C++
TomLott/ft_containers
/map.cpp
UTF-8
53,863
3.3125
3
[]
no_license
#include "map.hpp" #include <string> #include "utils.hpp" #include <vector> #include <list> #include <stack> bool singleDigit(const int& value) { return (value < 10); } struct isEven { bool operator()(const int& value) { return (value % 2) == 0; } }; bool sameRemainderOfDivision(int first, int second) { if (first % 10 == second % 10) return true; return false; } bool myComparison (int first, int second) { return (first > second); } //MARK: - Utilst list template <typename T> void listPushBackElem(std::list<T> &std, ft::list<T> &ft, unsigned long number) { T i; for (unsigned long l = 0; l < number; l++) { i = rand(); std.push_back(i); ft.push_back(i); } } template <typename T> void listPushFrontElem(std::list<T> &std, ft::list<T> &ft, unsigned long number) { T i; for (unsigned long l = 0; l < number; l++) { i = rand(); std.push_front(i); ft.push_front(i); } } template <typename T> void listPopFrontElem(std::list<T> &std, ft::list<T> &ft, unsigned long number) { T i; for (unsigned long l = 0; l < number; l++) { i = rand(); std.pop_front(); ft.pop_front(); } } template <typename T> void listPopBackElem(std::list<T> &std, ft::list<T> &ft, unsigned long number) { T i; for (unsigned long l = 0; l < number; l++) { i = rand(); std.pop_back(); ft.pop_back(); } } template <typename T> void VectorPushBackElem(std::vector<T> &std, ft::vector<T> &ft, unsigned long number) { T i; for (unsigned long l = 0; l < number; l++) { i = rand() % 100; std.push_back(i); ft.push_back(i); } } template <typename T> void VectorPopBackElem(std::vector<T> &std, ft::vector<T> &ft, unsigned long number) { T i; for (unsigned long l = 0; l < number; l++) { i = rand(); std.pop_back(); ft.pop_back(); } } template <typename T> void VectorFillStr(std::vector<T> &def, ft::vector<T> &my, std::string &std, std::string &ft) { for (typename std::vector<T>::iterator it = def.begin(); it != def.end(); it++) std += *it; for (typename ft::vector<T>::iterator it = my.begin(); it != my.end(); it++) ft += *it; std += def.size(); ft += my.size(); } //MARK: - Utilst map template <typename Key, typename T> void mapInsertElem(std::map<Key,T> &std, ft::map<Key,T> &ft, unsigned long number) { Key i; T j; for (unsigned long l = 0; l < number; l++) { i = rand(); j = rand(); std::pair<Key, T> res(i, j); std.insert(res); ft.insert(res); } } template <typename Key, typename T> void mapFillStr(std::map<Key,T> &def, ft::map<Key,T> &my, std::string &std, std::string &ft) { for (typename std::map<Key,T>::iterator it = def.begin(); it != def.end(); it++) { std += it->first; std += it->second; } for (typename ft::map<Key,T>::iterator it = my.begin(); it != my.end(); it++) { ft += it->first; ft += it->second; } std += def.size(); ft += my.size(); } //MARK: - Default constructor map void defaultCnstTestMap(std::string &std, std::string &ft) { std::cout << "Default constructor int test" << " "; std::map<int, int> def; ft::map<int, int> my; mapFillStr(def, my, std, ft); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void defaultCnstTestMapFloat(std::string &std, std::string &ft) { std::cout << "Default constructor float test" << " "; std::map<float, float> def; ft::map<float, float> my; mapFillStr(def, my, std, ft); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void defaultCnstTestMapStr(std::string &std, std::string &ft) { std::cout << "Default constructor std::string test" << " "; std::map<std::string, std::string> def; ft::map<std::string, std::string> my; mapFillStr(def, my, std, ft); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } //MARK: - Range constructor map void rangeCnstTestMap(std::string &std, std::string &ft) { std::cout << "Range constructor int test" << " "; std::map<int, int> test; for (int i = 0; i < 100; i++) { std::pair<int, int> res(rand(), rand()); test.insert(res); } std::map<int, int> def(++test.begin(), --test.end()); ft::map<int, int> my(++test.begin(), --test.end()); mapFillStr(def, my, std, ft); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void rangeCnstTestMapFloat(std::string &std, std::string &ft) { std::cout << "Range constructor float test" << " "; std::map<float, float> test; for (int i = 0; i < 100; i++) { std::pair<float, float> res(rand(), rand()); test.insert(res); } std::map<float, float> def(++test.begin(), --test.end()); ft::map<float, float> my(++test.begin(), --test.end()); mapFillStr(def, my, std, ft); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void rangeCnstTestMapStr(std::string &std, std::string &ft) { std::cout << "Range constructor std::string test" << " "; std::map<std::string, std::string> test; std::string key; std::string value; for (int i = 0; i < 100; i++) { key += rand(); value += rand(); std::pair<std::string, std::string> res(key, value); test.insert(res); } std::map<std::string, std::string> def(++test.begin(), --test.end()); ft::map<std::string, std::string> my(++test.begin(), --test.end()); mapFillStr(def, my, std, ft); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } //MARK: - Copy constructor map void copyCnstTestMap(std::string &std, std::string &ft) { std::cout << "Copy constructor int test" << " "; std::map<int, int> def; ft::map<int, int> my; mapInsertElem(def, my, 100); mapFillStr(def, my, std, ft); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void copyCnstTestMapFloat(std::string &std, std::string &ft) { std::cout << "Copy constructor float test" << " "; std::map<float, float> def; ft::map<float, float> my; mapInsertElem(def, my, 100); mapFillStr(def, my, std, ft); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void copyCnstTestMapStr(std::string &std, std::string &ft) { std::cout << "Copy constructor std::string test" << " "; std::map<std::string, std::string> def; ft::map<std::string, std::string> my; mapInsertElem(def, my, 100); mapFillStr(def, my, std, ft); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } //MARK: - Assignation map void assignTestMap(std::string &std, std::string &ft) { std::cout << "Assignation int test" << " "; std::map<int, int> def; ft::map<int, int> my; std::map<int, int> test; ft::map<int, int> myTest; mapInsertElem(test, myTest, 100); mapFillStr(def, my, std, ft); mapFillStr(test, myTest, std, ft); def = test; my = myTest; mapFillStr(def, my, std, ft); mapFillStr(test, myTest, std, ft); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void assignTestMapFloat(std::string &std, std::string &ft) { std::cout << "Assignation float test" << " "; std::map<float, float> def; ft::map<float, float> my; std::map<float, float> test; ft::map<float, float> myTest; mapInsertElem(test, myTest, 100); mapFillStr(def, my, std, ft); mapFillStr(test, myTest, std, ft); def = test; my = myTest; mapFillStr(def, my, std, ft); mapFillStr(test, myTest, std, ft); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void assignTestMapStr(std::string &std, std::string &ft) { std::cout << "Assignation std::string test" << " "; std::map<std::string, std::string> def; ft::map<std::string, std::string> my; std::map<std::string, std::string> test; ft::map<std::string, std::string> myTest; mapInsertElem(test, myTest, 100); mapFillStr(def, my, std, ft); mapFillStr(test, myTest, std, ft); def = test; my = myTest; mapFillStr(def, my, std, ft); mapFillStr(test, myTest, std, ft); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } //MARK: - Iterator map void iteratorTestMap(std::string &std, std::string &ft, int number) { std::map<int,int> testStd; ft::map<int,int> testFt; std::cout << "All iterator test" << " "; for (int i = 0; i < number; i++) { std::pair<int, int> res(rand(), rand()); testStd.insert(res); testFt.insert(res); } std::map<int,int>::iterator it = testStd.begin(); std::map<int,int>::iterator ite = testStd.end(); ft::map<int,int>::iterator itm = testFt.begin(); ft::map<int,int>::iterator item = testFt.end(); while (it != ite) { std += it->first; std += it->second; it++; } while (itm != item) { ft += itm->first; ft += itm->second; itm++; } it = testStd.begin(); itm = testFt.begin(); while (ite != it) { ite--; std += ite->first; std += ite->second; } while (item != itm) { item--; ft += item->first; ft += item->second; } if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } //MARK: - Const iteratot map void constIteratorTestMap(std::string &std, std::string &ft, int number) { std::map<int,int> testStd; ft::map<int,int> testFt; std::cout << "All const_iterator test" << " "; for (int i = 0; i < number; i++) { std::pair<int, int> res(rand(), rand()); testStd.insert(res); testFt.insert(res); } std::map<int,int>::const_iterator it = testStd.cbegin(); std::map<int,int>::const_iterator ite = testStd.cend(); ft::map<int,int>::const_iterator itm = testFt.begin(); ft::map<int,int>::const_iterator item = testFt.end(); while (it != ite) { std += it->first; std += it->second; it++; } while (itm != item) { ft += itm->first; ft += itm->second; itm++; } it = testStd.cbegin(); itm = testFt.begin(); while (ite != it) { ite--; std += ite->first; std += ite->second; } while (item != itm) { item--; ft += item->first; ft += item->second; } if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } //MARK: - Reverse iteratot map void reverseIteratorTestMap(std::string &std, std::string &ft, int number) { std::map<int,int> testStd; ft::map<int,int> testFt; std::cout << "All reverse_iterator test" << " "; for (int i = 0; i < number; i++) { std::pair<int, int> res(rand(), rand()); testStd.insert(res); testFt.insert(res); } std::map<int,int>::reverse_iterator it = testStd.rbegin(); std::map<int,int>::reverse_iterator ite = testStd.rend(); ft::map<int,int>::reverse_iterator itm = testFt.rbegin(); ft::map<int,int>::reverse_iterator item = testFt.rend(); while (it != ite) { std += it->first; std += it->second; it++; } while (itm != item) { ft += itm->first; ft += itm->second; itm++; } it = testStd.rbegin(); itm = testFt.rbegin(); while (ite != it) { ite--; std += ite->first; std += ite->second; } while (item != itm) { item--; ft += item->first; ft += item->second; } if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } //MARK: - Const reverse iteratot map void constReverseIteratorTestMap(std::string &std, std::string &ft, int number) { std::map<int,int> testStd; ft::map<int,int> testFt; std::cout << "All const_reverse_iterator test" << " "; for (int i = 0; i < number; i++) { std::pair<int, int> res(rand(), rand()); testStd.insert(res); testFt.insert(res); } std::map<int,int>::const_reverse_iterator it = testStd.crbegin(); std::map<int,int>::const_reverse_iterator ite = testStd.crend(); ft::map<int,int>::const_reverse_iterator itm = testFt.rbegin(); ft::map<int,int>::const_reverse_iterator item = testFt.rend(); while (it != ite) { std += it->first; std += it->second; it++; } while (itm != item) { ft += itm->first; ft += itm->second; itm++; } it = testStd.rbegin(); itm = testFt.rbegin(); while (ite != it) { ite--; std += ite->first; std += ite->second; } while (item != itm) { item--; ft += item->first; ft += item->second; } if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } //MARK: - Empty map void emptyMapTest(std::string &std, std::string &ft) { std::cout << "Empty int test" << " "; std::map<int, int> def; ft::map<int, int> my; std += def.empty(); ft += my.empty(); mapInsertElem(def, my, 10); std += def.empty(); ft += my.empty(); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void emptyMapTestFloat(std::string &std, std::string &ft) { std::cout << "Empty float test" << " "; std::map<float, float> def; ft::map<float, float> my; std += def.empty(); ft += my.empty(); mapInsertElem(def, my, 10); std += def.empty(); ft += my.empty(); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void emptyMapTestStr(std::string &std, std::string &ft) { std::cout << "Empty std::string test" << " "; std::map<std::string, std::string> def; ft::map<std::string, std::string> my; std += def.empty(); ft += my.empty(); mapInsertElem(def, my, 10); std += def.empty(); ft += my.empty(); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } //MARK: - Size map void sizeMapTest(std::string &std, std::string &ft) { std::cout << "Size int test" << " "; std::map<int, int> def; ft::map<int, int> my; std += def.size(); ft += my.size(); mapInsertElem(def, my, 10); std += def.size(); ft += my.size(); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void sizeMapTestFloat(std::string &std, std::string &ft) { std::cout << "Size float test" << " "; std::map<float, float> def; ft::map<float, float> my; std += def.size(); ft += my.size(); mapInsertElem(def, my, 10); std += def.size(); ft += my.size(); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void sizeMapTestStr(std::string &std, std::string &ft) { std::cout << "Size std::string test" << " "; std::map<std::string, std::string> def; ft::map<std::string, std::string> my; std += def.size(); ft += my.size(); mapInsertElem(def, my, 10); std += def.size(); ft += my.size(); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } //MARK: - Max size map void maxSizeTestMap(std::string &std, std::string &ft) { std::cout << "Max size int test" << " "; std::map<int, int> def; ft::map<int, int> my; std += def.max_size(); ft += my.max_size(); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void maxSizeTestMapFloat(std::string &std, std::string &ft) { std::cout << "Max size float test" << " "; std::map<float, float> def; ft::map<float, float> my; std += def.max_size(); ft += my.max_size(); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } //MARK: - Operator [] map void squareBracketsTestMap(std::string &std, std::string &ft) { std::cout << "Opetator[] int test" << " "; std::map<int, int> def; ft::map<int, int> my; mapInsertElem(def, my, 100); std::pair<int, int> test(21, 42); def.insert(test); my.insert(test); std += def[21]; ft += my[21]; std += def[42]; ft += my[42]; std += def[42]; ft += my[42]; if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void squareBracketsTestMapFloat(std::string &std, std::string &ft) { std::cout << "Opetator[] float test" << " "; std::map<float, float> def; ft::map<float, float> my; mapInsertElem(def, my, 100); std::pair<float, float> test(21, 42); def.insert(test); my.insert(test); std += def[21]; ft += my[21]; std += def[42]; ft += my[42]; std += def[42]; ft += my[42]; if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void squareBracketsTestMapStr(std::string &std, std::string &ft) { std::cout << "Opetator[] std::string test" << " "; std::map<std::string, std::string> def; ft::map<std::string, std::string> my; mapInsertElem(def, my, 100); std::pair<std::string, std::string> test("21", "42"); def.insert(test); my.insert(test); std += def["21"]; ft += my["21"]; std += def["42"]; ft += my["42"]; std += def["42"]; ft += my["42"]; if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } //MARK: - Insert map void singleInsertMap(std::string &std, std::string &ft) { std::cout << "Single insert int test" << " "; std::map<int, int> def; ft::map<int, int> my; mapFillStr(def, my, std, ft); std::pair<int, int> test(42, 21); def.insert(test); my.insert(test); mapFillStr(def, my, std, ft); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void singleInsertMapFloat(std::string &std, std::string &ft) { std::cout << "Single insert float test" << " "; std::map<float, float> def; ft::map<float, float> my; mapFillStr(def, my, std, ft); std::pair<float, float> test(42.21, 21.42); def.insert(test); my.insert(test); mapFillStr(def, my, std, ft); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void singleInsertMapStr(std::string &std, std::string &ft) { std::cout << "Single insert std::string test" << " "; std::map<std::string, std::string> def; ft::map<std::string, std::string> my; mapFillStr(def, my, std, ft); std::pair<std::string, std::string> test("42", "21"); def.insert(test); my.insert(test); mapFillStr(def, my, std, ft); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void withHitInsertMap(std::string &std, std::string &ft) { std::cout << "With hit insert int test" << " "; std::map<int, int> def; ft::map<int, int> my; mapFillStr(def, my, std, ft); std::pair<int, int> test(42, 21); def.insert(def.begin(),test); my.insert(my.begin(), test); mapFillStr(def, my, std, ft); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void withHitInsertMapFloat(std::string &std, std::string &ft) { std::cout << "With hit insert float test" << " "; std::map<float, float> def; ft::map<float, float> my; mapFillStr(def, my, std, ft); std::pair<float, float> test(42.21, 21.42); def.insert(def.begin(),test); my.insert(my.begin(), test); mapFillStr(def, my, std, ft); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void withHitInsertMapStr(std::string &std, std::string &ft) { std::cout << "With hit insert std::string test" << " "; std::map<std::string, std::string> def; ft::map<std::string, std::string> my; mapFillStr(def, my, std, ft); std::pair<std::string, std::string> test("42", "21"); def.insert(def.begin(),test); my.insert(my.begin(), test); mapFillStr(def, my, std, ft); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void rangeInsertMapTest(std::string &std, std::string &ft) { std::cout << "Range insert int test" << " "; std::map<int, int> test; for (int i = 0; i < 100; i++) { std::pair<int, int> l(rand(), rand()); test.insert(l); } std::map<int, int> def; ft::map<int, int> my; def.insert(test.begin(), test.end()); my.insert(test.begin(), test.end()); mapFillStr(def, my, std, ft); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void rangeInsertMapTestFloat(std::string &std, std::string &ft) { std::cout << "Range insert float test" << " "; std::map<float, float> test; for (int i = 0; i < 100; i++) { std::pair<float, float> l(rand(), rand()); test.insert(l); } std::map<float, float> def; ft::map<float, float> my; def.insert(test.begin(), test.end()); my.insert(test.begin(), test.end()); mapFillStr(def, my, std, ft); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void rangeInsertMapTestStr(std::string &std, std::string &ft) { std::cout << "Range insert std::string test" << " "; std::map<std::string, std::string> test; for (int i = 0; i < 100; i++) { std::string l1; std::string l2; l1 += rand(); l2 += rand(); std::pair<std::string, std::string> l(l1, l2); test.insert(l); } std::map<std::string, std::string> def; ft::map<std::string, std::string> my; def.insert(test.begin(), test.end()); my.insert(test.begin(), test.end()); mapFillStr(def, my, std, ft); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } //MARK: - Erase map void eraseSingleMapTest(std::string &std, std::string &ft) { std::cout << "Single erase int test" << " "; std::map<int, int> def; ft::map<int, int> my; mapInsertElem(def, my, 100); mapFillStr(def, my, std, ft); std::map<int, int>::iterator it = def.begin(); ft::map<int, int>::iterator mit = my.begin(); for (int i = 0; i < 10; i++) { it++; mit++; } for (int i = 0; i < 40; i++) { std::map<int, int>::iterator tmp = it; ft::map<int, int>::iterator mtmp = mit; it++; mit++; def.erase(tmp); my.erase(mtmp); mapFillStr(def, my, std, ft); } it = def.end(); mit = my.end(); it--; mit--; for (int i = 0; i < 20; i++) { std::map<int, int>::iterator tmp = it; ft::map<int, int>::iterator mtmp = mit; it--; mit--; def.erase(tmp); my.erase(mtmp); mapFillStr(def, my, std, ft); } if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void eraseSingleMapTestFloat(std::string &std, std::string &ft) { std::cout << "Single erase float test" << " "; std::map<float, float> def; ft::map<float, float> my; mapInsertElem(def, my, 100); mapFillStr(def, my, std, ft); std::map<float, float>::iterator it = def.begin(); ft::map<float, float>::iterator mit = my.begin(); for (int i = 0; i < 10; i++) { it++; mit++; } for (int i = 0; i < 40; i++) { std::map<float, float>::iterator tmp = it; ft::map<float, float>::iterator mtmp = mit; it++; mit++; def.erase(tmp); my.erase(mtmp); mapFillStr(def, my, std, ft); } it = def.end(); mit = my.end(); it--; mit--; for (int i = 0; i < 20; i++) { std::map<float, float>::iterator tmp = it; ft::map<float, float>::iterator mtmp = mit; it--; mit--; def.erase(tmp); my.erase(mtmp); mapFillStr(def, my, std, ft); } if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void eraseSingleMapTestStr(std::string &std, std::string &ft) { std::cout << "Single erase std::string test" << " "; std::map<std::string, std::string> def; ft::map<std::string, std::string> my; mapInsertElem(def, my, 100); mapFillStr(def, my, std, ft); std::map<std::string, std::string>::iterator it = def.begin(); ft::map<std::string, std::string>::iterator mit = my.begin(); for (int i = 0; i < 10; i++) { it++; mit++; } for (int i = 0; i < 40; i++) { std::map<std::string, std::string>::iterator tmp = it; ft::map<std::string, std::string>::iterator mtmp = mit; it++; mit++; def.erase(tmp); my.erase(mtmp); mapFillStr(def, my, std, ft); } it = def.end(); mit = my.end(); it--; mit--; for (int i = 0; i < 20; i++) { std::map<std::string, std::string>::iterator tmp = it; ft::map<std::string, std::string>::iterator mtmp = mit; it--; mit--; def.erase(tmp); my.erase(mtmp); mapFillStr(def, my, std, ft); } if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void eraseKeyMapTest(std::string &std, std::string &ft) { std::cout << "Key erase int test" << " "; std::map<int, int> def; ft::map<int, int> my; mapInsertElem(def, my, 100); std::pair<int, int> test(42, 42); def.insert(test); my.insert(test); def.erase(42); my.erase(42); def.erase(1); my.erase(1); mapFillStr(def, my, std, ft); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void eraseKeyMapTestFloat(std::string &std, std::string &ft) { std::cout << "Key erase float test" << " "; std::map<float, float> def; ft::map<float, float> my; mapInsertElem(def, my, 100); std::pair<float, float> test(42.21, 42.21); def.insert(test); my.insert(test); def.erase(42.21); my.erase(42.21); def.erase(1.7); my.erase(1.7); mapFillStr(def, my, std, ft); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void eraseKeyMapTestStr(std::string &std, std::string &ft) { std::cout << "Key erase std::string test" << " "; std::map<std::string, std::string> def; ft::map<std::string, std::string> my; mapInsertElem(def, my, 100); std::pair<std::string, std::string> test("42", "42"); def.insert(test); my.insert(test); def.erase("42"); my.erase("42"); def.erase("1"); my.erase("1"); mapFillStr(def, my, std, ft); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void eraseRangeTest(std::string &std, std::string &ft) { std::cout << "Range erase int test" << " "; std::map<int, int> def; ft::map<int, int> my; mapInsertElem(def, my, 100); std::map<int, int>::iterator it = def.begin(); std::map<int, int>::iterator ite = def.end(); ft::map<int, int>::iterator itm = my.begin(); ft::map<int, int>::iterator item = my.end(); for (int i = 0; i < 20; i++) { ++it; ++itm; --ite; --item; } def.erase(it, ite); my.erase(itm, item); mapFillStr(def, my, std, ft); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void eraseRangeTestFloat(std::string &std, std::string &ft) { std::cout << "Range erase float test" << " "; std::map<float, float> def; ft::map<float, float> my; mapInsertElem(def, my, 100); std::map<float, float>::iterator it = def.begin(); std::map<float, float>::iterator ite = def.end(); ft::map<float, float>::iterator itm = my.begin(); ft::map<float, float>::iterator item = my.end(); for (int i = 0; i < 20; i++) { ++it; ++itm; --ite; --item; } def.erase(it, ite); my.erase(itm, item); mapFillStr(def, my, std, ft); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void eraseRangeTestStr(std::string &std, std::string &ft) { std::cout << "Range erase std::string test" << " "; std::map<std::string, std::string> def; ft::map<std::string, std::string> my; mapInsertElem(def, my, 100); std::map<std::string, std::string>::iterator it = def.begin(); std::map<std::string, std::string>::iterator ite = def.end(); ft::map<std::string, std::string>::iterator itm = my.begin(); ft::map<std::string, std::string>::iterator item = my.end(); for (int i = 0; i < 20; i++) { ++it; ++itm; --ite; --item; } def.erase(it, ite); my.erase(itm, item); mapFillStr(def, my, std, ft); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; // std.clear(); // ft.clear(); } //MARK: - Swap map void swapTestMap(std::string &std, std::string &ft) { std::cout << "Swap int test" << " "; std::map<int, int> def; ft::map<int, int> my; std::map<int, int> toSwap; ft::map<int, int> mySwap; mapInsertElem(def, my, 100); mapInsertElem(toSwap, mySwap, 50); mapFillStr(def, my, std, ft); mapFillStr(toSwap, mySwap, std, ft); def.swap(toSwap); my.swap(mySwap); mapFillStr(def, my, std, ft); mapFillStr(toSwap, mySwap, std, ft); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void swapTestMapFloat(std::string &std, std::string &ft) { std::cout << "Swap float test" << " "; std::map<float, float> def; ft::map<float, float> my; std::map<float, float> toSwap; ft::map<float, float> mySwap; mapInsertElem(def, my, 100); mapInsertElem(toSwap, mySwap, 50); mapFillStr(def, my, std, ft); mapFillStr(toSwap, mySwap, std, ft); def.swap(toSwap); my.swap(mySwap); mapFillStr(def, my, std, ft); mapFillStr(toSwap, mySwap, std, ft); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void swapTestMapStr(std::string &std, std::string &ft) { std::cout << "Swap std::string test" << " "; std::map<std::string, std::string> def; ft::map<std::string, std::string> my; std::map<std::string, std::string> toSwap; ft::map<std::string, std::string> mySwap; mapInsertElem(def, my, 100); mapInsertElem(toSwap, mySwap, 50); mapFillStr(def, my, std, ft); mapFillStr(toSwap, mySwap, std, ft); def.swap(toSwap); my.swap(mySwap); mapFillStr(def, my, std, ft); mapFillStr(toSwap, mySwap, std, ft); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } //MARK: - Clear map void clearTestMap(std::string &std, std::string &ft) { std::cout << "Clear int test" << " "; std::map<int, int> def; ft::map<int, int> my; mapInsertElem(def, my, 100); mapFillStr(def, my, std, ft); def.clear(); my.clear(); mapFillStr(def, my, std, ft); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void clearTestMapFloat(std::string &std, std::string &ft) { std::cout << "Clear float test" << " "; std::map<float, float> def; ft::map<float, float> my; mapInsertElem(def, my, 100); mapFillStr(def, my, std, ft); def.clear(); my.clear(); mapFillStr(def, my, std, ft); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void clearTestMapStr(std::string &std, std::string &ft) { std::cout << "Clear std::string test" << " "; std::map<std::string, std::string> def; ft::map<std::string, std::string> my; mapInsertElem(def, my, 100); mapFillStr(def, my, std, ft); def.clear(); my.clear(); mapFillStr(def, my, std, ft); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } //MARK: - Key compare map void keyCompareTest(std::string &std, std::string &ft) { std::cout << "Key comp int test" << " "; std::map<int, int> def; ft::map<int, int> my; std::map<int,int>::key_compare comp = def.key_comp(); ft::map<int,int>::key_compare myComp = my.key_comp(); int i = 10000; mapInsertElem(def, my, 100); for (std::map<int, int>::iterator it = def.begin(); it != def.end(); ++it) { std += comp(i, it->first); ft += myComp(i, it->first); } if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void keyCompareTestFloat(std::string &std, std::string &ft) { std::cout << "Key comp float test" << " "; std::map<float, float> def; ft::map<float, float> my; std::map<float,float>::key_compare comp = def.key_comp(); ft::map<float,float>::key_compare myComp = my.key_comp(); float i = 10000.42; mapInsertElem(def, my, 100); for (std::map<float, float>::iterator it = def.begin(); it != def.end(); ++it) { std += comp(i, it->first); ft += myComp(i, it->first); } if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void keyCompareTestStr(std::string &std, std::string &ft) { std::cout << "Key comp std::string test" << " "; std::map<std::string, std::string> def; ft::map<std::string, std::string> my; std::map<std::string,std::string>::key_compare comp = def.key_comp(); ft::map<std::string,std::string>::key_compare myComp = my.key_comp(); std::string i = "10000"; mapInsertElem(def, my, 100); for (std::map<std::string, std::string>::iterator it = def.begin(); it != def.end(); ++it) { std += comp(i, it->first); ft += myComp(i, it->first); } if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } //MARK: - Value compare map void valueCompareTest(std::string &std, std::string &ft) { std::cout << "Value comp int test" << " "; std::map<int, int> def; ft::map<int, int> my; mapInsertElem(def, my, 100); std::pair<int, int> res(100,100); for (std::map<int, int>::iterator it = def.begin(); it != def.end(); ++it) { std += def.value_comp()(res, *it); ft += my.value_comp()(res, *it); } if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void valueCompareTestFloat(std::string &std, std::string &ft) { std::cout << "Value comp float test" << " "; std::map<float, float> def; ft::map<float, float> my; mapInsertElem(def, my, 100); std::pair<float, float> res(100.42,100.42); for (std::map<float, float>::iterator it = def.begin(); it != def.end(); ++it) { std += def.value_comp()(res, *it); ft += my.value_comp()(res, *it); } if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void valueCompareTestStr(std::string &std, std::string &ft) { std::cout << "Value comp std::string test" << " "; std::map<std::string, std::string> def; ft::map<std::string, std::string> my; mapInsertElem(def, my, 100); std::pair<std::string, std::string> res("100","100"); for (std::map<std::string, std::string>::iterator it = def.begin(); it != def.end(); ++it) { std += def.value_comp()(res, *it); ft += my.value_comp()(res, *it); } if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } //MARK: - Find map void findTest(std::string &std, std::string &ft) { std::cout << "Find int test" << " "; std::map<int, int> def; ft::map<int, int> my; mapInsertElem(def, my, 100); std::pair<int, int> test(42, 42); def.insert(test); my.insert(test); std::map<int, int>::iterator it; ft::map<int, int>::iterator ite; it = def.find(42); ite = my.find(42); std += it->first; std += it->second; ft += ite->first; ft += ite->second; if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void findTestFloat(std::string &std, std::string &ft) { std::cout << "Find float test" << " "; std::map<float, float> def; ft::map<float, float> my; mapInsertElem(def, my, 100); std::pair<float, float> test(42.21, 42.21); def.insert(test); my.insert(test); std::map<float, float>::iterator it; ft::map<float, float>::iterator ite; it = def.find(42.21); ite = my.find(42.21); std += it->first; std += it->second; ft += ite->first; ft += ite->second; if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void findTestStr(std::string &std, std::string &ft) { std::cout << "Find std::string test" << " "; std::map<std::string, std::string> def; ft::map<std::string, std::string> my; mapInsertElem(def, my, 100); std::pair<std::string, std::string> test("42", "42"); def.insert(test); my.insert(test); std::map<std::string, std::string>::iterator it; ft::map<std::string, std::string>::iterator ite; it = def.find("42"); ite = my.find("42"); std += it->first; std += it->second; ft += ite->first; ft += ite->second; if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } //MARK: - Count map void countTest(std::string &std, std::string &ft) { std::cout << "Count int test" << " "; std::map<int, int> def; ft::map<int, int> my; mapInsertElem(def, my, 100); std::pair<int, int> test(42, 42); std::pair<int, int> test1(21, 21); def.insert(test); my.insert(test); def.insert(test); my.insert(test); std += def.count(42); ft += my.count(42); std += def.count(21); ft += my.count(21); std += def.count(72); ft += my.count(72); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void countTestFloat(std::string &std, std::string &ft) { std::cout << "Count float test" << " "; std::map<float, float> def; ft::map<float, float> my; mapInsertElem(def, my, 100); std::pair<float, float> test(42.21, 42.21); std::pair<float, float> test1(21.42, 21.42); def.insert(test); my.insert(test); def.insert(test); my.insert(test); std += def.count(42.21); ft += my.count(42.21); std += def.count(21.42); ft += my.count(21.42); std += def.count(72.1); ft += my.count(72.1); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void countTestStr(std::string &std, std::string &ft) { std::cout << "Count std::string test" << " "; std::map<std::string, std::string> def; ft::map<std::string, std::string> my; mapInsertElem(def, my, 100); std::pair<std::string, std::string> test("42", "42"); std::pair<std::string, std::string> test1("21", "21"); def.insert(test); my.insert(test); def.insert(test); my.insert(test); std += def.count("42"); ft += my.count("42"); std += def.count("21"); ft += my.count("21"); std += def.count("72"); ft += my.count("72"); if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } //MARK: - Lover bound map void lowerBoundTest(std::string &std, std::string &ft) { std::cout << "Lower bound int test" << " "; std::map<int, int> def; ft::map<int, int> my; mapInsertElem(def, my, 100); std::pair<int, int> test(42, 42); def.insert(test); my.insert(test); std::map<int, int>::iterator it; ft::map<int, int>::iterator itm; it = def.lower_bound(42); itm = my.lower_bound(42); std += it->first; ft += itm->first; std += it->second; ft += itm->second; it = def.lower_bound(43); itm = my.lower_bound(43); std += it->first; ft += itm->first; std += it->second; ft += itm->second; it = def.lower_bound(-9999999); itm = my.lower_bound(-9999999); std += it->first; ft += itm->first; std += it->second; ft += itm->second; it = def.lower_bound(999999999); itm = my.lower_bound(999999999); std += it->first; ft += itm->first; std += it->second; ft += itm->second; if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void lowerBoundTestFloat(std::string &std, std::string &ft) { std::cout << "Lower bound float test" << " "; std::map<float, float> def; ft::map<float, float> my; mapInsertElem(def, my, 100); std::pair<float, float> test(42.21, 42.21); def.insert(test); my.insert(test); std::map<float, float>::iterator it; ft::map<float, float>::iterator itm; it = def.lower_bound(42.21); itm = my.lower_bound(42.21); std += it->first; ft += itm->first; std += it->second; ft += itm->second; it = def.lower_bound(43.21); itm = my.lower_bound(43.21); std += it->first; ft += itm->first; std += it->second; ft += itm->second; it = def.lower_bound(-9999999.0); itm = my.lower_bound(-9999999.0); std += it->first; ft += itm->first; std += it->second; ft += itm->second; it = def.lower_bound(999999999.0); itm = my.lower_bound(999999999.0); std += it->first; ft += itm->first; std += it->second; ft += itm->second; if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void lowerBoundTestStr(std::string &std, std::string &ft) { std::cout << "Lower bound std::string test" << " "; std::map<std::string, std::string> def; ft::map<std::string, std::string> my; mapInsertElem(def, my, 100); std::pair<std::string, std::string> test("42", "42"); def.insert(test); my.insert(test); std::map<std::string, std::string>::iterator it; ft::map<std::string, std::string>::iterator itm; it = def.lower_bound("42"); itm = my.lower_bound("42"); std += it->first; ft += itm->first; std += it->second; ft += itm->second; it = def.lower_bound("43"); itm = my.lower_bound("43"); std += it->first; ft += itm->first; std += it->second; ft += itm->second; it = def.lower_bound("a"); itm = my.lower_bound("a"); std += it->first; ft += itm->first; std += it->second; ft += itm->second; it = def.lower_bound("zzzzzzzzzzzzzzz"); itm = my.lower_bound("zzzzzzzzzzzzzzz"); std += it->first; ft += itm->first; std += it->second; ft += itm->second; if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } //MARK: - Upper bound map void upperBoundTest(std::string &std, std::string &ft) { std::cout << "Upper bound int test" << " "; std::map<int, int> def; ft::map<int, int> my; mapInsertElem(def, my, 100); std::pair<int, int> test(42, 42); def.insert(test); my.insert(test); std::map<int, int>::iterator it; ft::map<int, int>::iterator itm; it = def.upper_bound(42); itm = my.upper_bound(42); std += it->first; ft += itm->first; std += it->second; ft += itm->second; it = def.upper_bound(43); itm = my.upper_bound(43); std += it->first; ft += itm->first; std += it->second; ft += itm->second; it = def.upper_bound(-9999999); itm = my.upper_bound(-9999999); std += it->first; ft += itm->first; std += it->second; ft += itm->second; it = def.upper_bound(999999999); itm = my.upper_bound(999999999); std += it->first; ft += itm->first; std += it->second; ft += itm->second; if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void upperBoundTestFloat(std::string &std, std::string &ft) { std::cout << "Upper bound float test" << " "; std::map<float, float> def; ft::map<float, float> my; mapInsertElem(def, my, 100); std::pair<float, float> test(42.21, 42.21); def.insert(test); my.insert(test); std::map<float, float>::iterator it; ft::map<float, float>::iterator itm; it = def.upper_bound(42.21); itm = my.upper_bound(42.21); std += it->first; ft += itm->first; std += it->second; ft += itm->second; it = def.upper_bound(43.21); itm = my.upper_bound(43.21); std += it->first; ft += itm->first; std += it->second; ft += itm->second; it = def.upper_bound(-9999999.0); itm = my.upper_bound(-9999999.0); std += it->first; ft += itm->first; std += it->second; ft += itm->second; it = def.upper_bound(999999999.0); itm = my.upper_bound(999999999.0); std += it->first; ft += itm->first; std += it->second; ft += itm->second; if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void upperBoundTestStr(std::string &std, std::string &ft) { std::cout << "Upper bound std::string test" << " "; std::map<std::string, std::string> def; ft::map<std::string, std::string> my; mapInsertElem(def, my, 100); std::pair<std::string, std::string> test("42", "42"); def.insert(test); my.insert(test); std::map<std::string, std::string>::iterator it; ft::map<std::string, std::string>::iterator itm; it = def.upper_bound("42"); itm = my.upper_bound("42"); std += it->first; ft += itm->first; std += it->second; ft += itm->second; it = def.upper_bound("43"); itm = my.upper_bound("43"); std += it->first; ft += itm->first; std += it->second; ft += itm->second; it = def.upper_bound("a"); itm = my.upper_bound("a"); std += it->first; ft += itm->first; std += it->second; ft += itm->second; it = def.upper_bound("zzzzzzzzzzzzzzz"); itm = my.upper_bound("zzzzzzzzzzzzzzz"); std += it->first; ft += itm->first; std += it->second; ft += itm->second; if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } //MARK: - Equal range map void equalRangeTest(std::string &std, std::string &ft) { std::cout << "Equal range int test" << " "; std::map<int, int> def; ft::map<int, int> my; mapInsertElem(def, my, 100); std::pair<std::map<int, int>::iterator, std::map<int, int>::iterator> test; std::pair<ft::map<int, int>::iterator, ft::map<int, int>::iterator> myTest; test = def.equal_range(100); myTest = my.equal_range(100); std += test.first->first; std += test.first->second; std += test.second->first; std += test.second->second; ft += myTest.first->first; ft += myTest.first->second; ft += myTest.second->first; ft += myTest.second->second; std::pair<int, int> toTest(42, 42); def.insert(toTest); my.insert(toTest); test = def.equal_range(42); myTest = my.equal_range(42); std += test.first->first; std += test.first->second; std += test.second->first; std += test.second->second; ft += myTest.first->first; ft += myTest.first->second; ft += myTest.second->first; ft += myTest.second->second; if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void equalRangeTestFloat(std::string &std, std::string &ft) { std::cout << "Equal range float test" << " "; std::map<float, float> def; ft::map<float, float> my; mapInsertElem(def, my, 100); std::pair<std::map<float, float>::iterator, std::map<float, float>::iterator> test; std::pair<ft::map<float, float>::iterator, ft::map<float, float>::iterator> myTest; test = def.equal_range(100); myTest = my.equal_range(100); std += test.first->first; std += test.first->second; std += test.second->first; std += test.second->second; ft += myTest.first->first; ft += myTest.first->second; ft += myTest.second->first; ft += myTest.second->second; std::pair<float, float> toTest(42.21, 42.21); def.insert(toTest); my.insert(toTest); test = def.equal_range(42.21); myTest = my.equal_range(42.21); std += test.first->first; std += test.first->second; std += test.second->first; std += test.second->second; ft += myTest.first->first; ft += myTest.first->second; ft += myTest.second->first; ft += myTest.second->second; if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } void equalRangeTestStr(std::string &std, std::string &ft) { std::cout << "Equal range std::string test" << " "; std::map<std::string, std::string> def; ft::map<std::string, std::string> my; mapInsertElem(def, my, 100); std::pair<std::map<std::string, std::string>::iterator, std::map<std::string, std::string>::iterator> test; std::pair<ft::map<std::string, std::string>::iterator, ft::map<std::string, std::string>::iterator> myTest; test = def.equal_range("100"); myTest = my.equal_range("100"); std += test.first->first; std += test.first->second; std += test.second->first; std += test.second->second; ft += myTest.first->first; ft += myTest.first->second; ft += myTest.second->first; ft += myTest.second->second; std::pair<std::string, std::string> toTest("42", "42"); def.insert(toTest); my.insert(toTest); test = def.equal_range("42"); myTest = my.equal_range("42"); std += test.first->first; std += test.first->second; std += test.second->first; std += test.second->second; ft += myTest.first->first; ft += myTest.first->second; ft += myTest.second->first; ft += myTest.second->second; if (std == ft) std::cout << "\033[1;32m[OK]\033[0;0m" << std::endl; else std::cout << "\033[1;31m[FAIL]\033[0;0m" << std::endl; std.clear(); ft.clear(); } //MARK: - Map void testMap() { std::cout << " CONSTRUCTOR" << std::endl; std::string std; std::string ft; defaultCnstTestMap(std, ft); defaultCnstTestMapFloat(std, ft); defaultCnstTestMapStr(std, ft); rangeCnstTestMap(std, ft); rangeCnstTestMapFloat(std, ft); rangeCnstTestMapStr(std, ft); copyCnstTestMap(std, ft); copyCnstTestMapFloat(std, ft); copyCnstTestMapStr(std, ft); std::cout << " ASSIGNATION" << std::endl; assignTestMap(std, ft); assignTestMapFloat(std, ft); assignTestMapStr(std, ft); std::cout << " ITERATORS" << std::endl; iteratorTestMap(std, ft, 1000); constIteratorTestMap(std, ft, 1000); reverseIteratorTestMap(std, ft, 1000); constReverseIteratorTestMap(std, ft, 1000); std::cout << " CAPACITY" << std::endl; emptyMapTest(std, ft); emptyMapTestFloat(std, ft); emptyMapTestStr(std, ft); sizeMapTest(std, ft); sizeMapTestFloat(std, ft); sizeMapTestStr(std, ft); maxSizeTestMap(std, ft); maxSizeTestMapFloat(std, ft); std::cout << " ELEMENT ACCESS" << std::endl; squareBracketsTestMap(std, ft); squareBracketsTestMapFloat(std, ft); squareBracketsTestMapStr(std, ft); std::cout << " MODIFIERS" << std::endl; singleInsertMap(std, ft); singleInsertMapFloat(std, ft); singleInsertMapStr(std, ft); withHitInsertMap(std, ft); withHitInsertMapFloat(std, ft); withHitInsertMapStr(std, ft); rangeInsertMapTest(std, ft); rangeInsertMapTestFloat(std, ft); rangeInsertMapTestStr(std, ft); eraseSingleMapTest(std, ft); eraseSingleMapTestFloat(std, ft); eraseSingleMapTestStr(std, ft); eraseKeyMapTest(std, ft); eraseKeyMapTestFloat(std, ft); eraseKeyMapTestStr(std, ft); swapTestMap(std, ft); swapTestMapFloat(std, ft); swapTestMapStr(std, ft); clearTestMap(std, ft); clearTestMapFloat(std, ft); clearTestMapStr(std, ft); std::cout << " OBSERVERS" << std::endl; keyCompareTest(std, ft); keyCompareTestFloat(std, ft); keyCompareTestStr(std, ft); valueCompareTest(std, ft); valueCompareTestFloat(std, ft); valueCompareTestStr(std, ft); std::cout << " OPERATIONS" << std::endl; findTest(std, ft); findTestFloat(std, ft); findTestStr(std, ft); countTest(std, ft); countTestFloat(std, ft); countTestStr(std, ft); lowerBoundTest(std, ft); lowerBoundTestFloat(std, ft); lowerBoundTestStr(std, ft); upperBoundTest(std, ft); upperBoundTestFloat(std, ft); upperBoundTestStr(std, ft); equalRangeTest(std, ft); equalRangeTestFloat(std, ft); equalRangeTestStr(std, ft); } int main(){ testMap(); return 0; }
true
4ec9b5d2616b8607995c226b58e6facd97bbbde8
C++
Umarahmad87/Pacman
/Ghost.h
UTF-8
10,205
3.0625
3
[]
no_license
/* * Ghost.h * * Created on: Apr 30, 2016 * Author: umar */ #ifndef GHOST_H_ #define GHOST_H_ #include <GL/glut.h> #include <iostream> #include <set> #include "Board.h" #include "util.h" enum Movements { Left , Right , up , down }; class Ghost:public Board{ int move_r; int Frightened; public: Ghost(int x=13,int y=21):Board(x,y){ movement=1; move_r=down; Frightened=0; } void Start(int n=0){ x_cell=13; y_cell=21; x_axis=x_cell*20.0; y_axis=y_cell*20.0; } void Frightn(int n){ Frightened = n; } int Frightn(){ return Frightened; } void Load_Level(int lev){ if(lev==0 or lev==1){ for(int i=0;i<36;i++){ for(int j=0;j<28;j++){ board_array[i][j]=board_array1[i][j]; }} } else if(lev==2 or lev==3){ for(int i=0;i<36;i++){ for(int j=0;j<28;j++){ board_array[i][j]=board_array2[i][j]; }} } } bool Block_left(){ int x,y; x=ceil(x_cell); y=y_cell; if(board_array[35-y][x-1]==PEBB or board_array[35-y][x-1]==0 or board_array[35-y][x-1]==SB or board_array[35-y][x-1]==VE or board_array[35-y][x-1]==GH ) return 0; return 1; } bool Block_right(){ int x,y; x=floor(x_cell); y=y_cell; if(board_array[35-y][x+1]==PEBB or board_array[35-y][x+1]==0 or board_array[35-y][x+1]==SB or board_array[35-y][x+1]==VE or board_array[35-y][x+1]==GH ) return 0; return 1; } bool Block_up(){ int x,y; x=x_cell; y=floor(y_cell); if(board_array[35-y-1][x]==PEBB or board_array[35-y-1][x]==0 or board_array[35-y-1][x]==SB or board_array[35-y-1][x]==VE or board_array[35-y-1][x]==GH ) return 0; return 1; } bool Block_down(){ int x,y; x=x_cell; y=ceil(y_cell); if(board_array[35-y+1][x]==PEBB or board_array[35-y+1][x]==0 or board_array[35-y+1][x]==SB or board_array[35-y+1][x]==VE or board_array[35-y+1][x]==GH) return 0; return 1; } void Reset(int x,int y){ x_cell=x; y_cell=y; x_axis=x_cell*xcellsize; y_axis=y_cell*ycellsize; move_r=up; } void Search(int px,int py){ int x,y; x=x_cell; y=y_cell; static int hh=0; record=move_r; cout<<" hh= "<<hh<<endl; /*if(board_array[35-y][x]==GH){ if((hh%4==0 or hh%4==1) and board_array[35-y-1][x]==GH and Block_up()==1) y_cell +=1; else if((hh%4==2 or hh%4==3) and board_array[35-y+1][x]==GH and Block_down()==1) y_cell -=1; y_axis=20*y_cell; }*/ hh++; cout<<"Ghost x and y :"<<x<<" , "<<y<<endl; cout<<"Pacman x and y :"<<px<<" , "<<py<<endl; for(int xx=x,j=1;xx<=28;xx++,j++){ if(x+j==px and y==py and this->Block_right()==0 and move_r!=Left){ x_cell +=1; x_axis=20*x_cell; move_r=Right; return; break; }} for(int xx=x,j=1; xx>0 ;xx--,j++){ if(x-j==px and y==py and this->Block_left()==0 and move_r!=Right){ x_cell -=1; x_axis=20*x_cell; move_r=Left; return; break; }} for(int yy=y,j=1; yy>0 ;yy--,j++){ if(x==px and y-j==py and this->Block_down()==0 and move_r!=up){ y_cell -=1; y_axis=20*y_cell; move_r=down; return; break; }} for(int yy=y,j=1; yy<36 ;yy++,j++){ if(x==px and y+j==py and this->Block_up()==0 and move_r!=down){ y_cell +=1; y_axis=20*y_cell; move_r=up; return; break; }} Movement(); } void Movement(){ int x,y; x=x_cell; y=y_cell; if(this->x_cell==0){ x_cell=27; x_axis=20*x_cell; x_cell -=1; x_axis=20*x_cell; move_r=Left;} else if(this->x_cell==27){ x_cell=0; x_axis=20*0; x_cell +=1; x_axis=20*x_cell; move_r=Right; } // Simple End if(this->Block_right()==1 and this->Block_down()==1){ if(move_r==down){ if(Block_left()==0){ x_cell -= 1; x_axis = x_cell * 20.0; move_r = Left; }} else if(move_r==Right){ if(Block_up()==0){ y_cell += 1; y_axis = y_cell * 20.0; move_r = up; }} } else if(this->Block_left()==1 and this->Block_up()==1){ if(move_r==Left){ if(Block_down()==0){ y_cell -= 1; y_axis = y_cell * 20.0; move_r = down; }} else if(move_r==up){ if(Block_right()==0){ x_cell += 1; x_axis = x_cell * 20.0; move_r = Right; }} } else if(this->Block_left()==1 and this->Block_down()==1){ if(move_r==down){ if(Block_right()==0){ x_cell += 1; x_axis = x_cell * 20.0; move_r = Right; }} else if(move_r==Left){ if(Block_up()==0){ y_cell += 1; y_axis = y_cell * 20.0; move_r = up; }} } else if(this->Block_right()==1 and this->Block_up()==1){ if(move_r==up){ if(Block_left()==0){ x_cell -= 1; x_axis = x_cell * 20.0; move_r = Left; }} else if(move_r==Right){ if(Block_down()==0){ y_cell -= 1; y_axis = y_cell * 20.0; move_r = down; }} } // Special Condition 1 else if(this->Block_left()==0 and this->Block_right()==0){ if(move_r==up ){ int ran=rand()%3; if(ran==0){ move_r=Left; x_cell -= 1; x_axis = x_cell * 20.0; } else if (ran==1){ move_r=Right; x_cell += 1; x_axis = x_cell * 20.0; } else if(ran==2 and Block_up()==0){ move_r=up; y_cell += 1; y_axis=y_cell * 20.0;} } else if(move_r==down){ int ran=rand()%3; if(ran==0){ move_r=Left; x_cell -= 1; x_axis = x_cell * 20.0; } else if (ran==1){ move_r=Right; x_cell += 1; x_axis = x_cell * 20.0; } else if(ran==2 and Block_down()==0){ move_r=down; y_cell -= 1; y_axis=y_cell * 20.0;}} else if(Block_up()==1 and Block_down()==1){ if(move_r==Left) { move_r=Left; x_cell -= 1; x_axis = x_cell * 20.0; } else if(move_r==Right){ move_r=Right; x_cell += 1; x_axis = x_cell * 20.0; } } else if(move_r==Left){ if(Block_up()==0){ int ran2=rand()%2; if(ran2==0){ move_r=Left; x_cell -= 1; x_axis = x_cell * 20.0;} else if (ran2==1){ move_r=up; y_cell += 1; y_axis = y_cell * 20.0;} } else if(Block_down()==0){ int ran2=rand()%2; if(ran2==0){ move_r=Left; x_cell -= 1; x_axis = x_cell * 20.0;} else if (ran2==1){ move_r=down; y_cell -= 1; y_axis = y_cell * 20.0;} } } else if(move_r==Right){ if(Block_up()==0){ int ran2=rand()%2; if(ran2==0){ move_r=Right; x_cell += 1; x_axis = x_cell * 20.0;} else if (ran2==1){ move_r=up; y_cell += 1; y_axis = y_cell * 20.0;} } else if(Block_down()==0){ int ran2=rand()%2; if(ran2==0){ move_r=Right; x_cell += 1; x_axis = x_cell * 20.0;} else if (ran2==1){ move_r=down; y_cell -= 1; y_axis = y_cell * 20.0;} } } } // Special Condition End 1 // Up Down Condition starts else if(this->Block_up()==0 and this->Block_down()==0){ if(move_r == up or move_r==Right) { if(Block_right()==0 and Block_left()==0){ int ran3=rand()%3; if(ran3==0){ move_r=up; y_cell += 1; y_axis = y_cell * 20.0; } else if(ran3==1){ move_r=Right; x_cell += 1; x_axis=x_cell * 20.0; } else if(ran3==2){ move_r=Left; x_cell -= 1; x_axis=x_cell * 20.0; } } else if(Block_right()==1 and Block_left()==1){ move_r=up; y_cell += 1; y_axis = y_cell * 20.0;} else if(Block_right()==1 or Block_left()==1){ move_r=up; y_cell += 1; y_axis = y_cell * 20.0;} } else if(move_r == down or move_r==Left) { if(Block_right()==0 and Block_left()==0){ int ran3=rand()%3; if(ran3==0){ move_r=down; y_cell -= 1; y_axis = y_cell * 20.0; } else if(ran3==1){ move_r=Right; x_cell += 1; x_axis=x_cell * 20.0; } else if(ran3==2){ move_r=Left; x_cell -= 1; x_axis=x_cell * 20.0; } } else if(Block_right()==1 and Block_left()==1){ move_r=down; y_cell -= 1; y_axis = y_cell * 20.0;} else if(Block_right()==1 or Block_left()==1){ move_r=down; y_cell -= 1; y_axis = y_cell * 20.0;}} /* int ran=rand()%2; if(ran==0){ move_r=up; y_cell += 1; y_axis = y_cell * 20.0; } else if (ran==1){ move_r=down; y_cell -= 1; y_axis = y_cell * 20.0; }*/ } // Up Down Condition Ends // Extra else if(this->Block_left()==1 and this->Block_right()==1){ if(move_r==up){ if(Block_up()==0){ y_cell += 1; y_axis=y_cell*20; move_r=up;} } else if(move_r == down){ if(Block_down()==0){ y_cell -= 1; y_axis=y_cell*20; move_r=down;} } } else if(this->Block_up()==1 and this->Block_down()==1){ if(move_r== Left ){ if(Block_left()==0){ x_cell -= 1; x_axis=x_cell*20; move_r= Left;} } else if(move_r == Right){ if(Block_right()==0){ y_cell += 1; x_axis=x_cell*20; move_r=Right;} } } } void Movement2(){ if(move_r==Left and Block_left()==0){ if(Block_left()==0){ x_cell -= 1; x_axis = x_cell * 20.0; move_r= Left; }} else if(move_r==Right and Block_right()==0){ x_cell += 1; x_axis = x_cell * 20.0; move_r= Right; } else if(move_r==up and Block_up()==0){ y_cell += 1; y_axis = y_cell * 20.0; move_r= up; } else if(move_r==down and Block_down()==0){ y_cell -= 1; y_axis = y_cell * 20.0; move_r= down; } else Movement(); } }; #endif /* GHOST_H_ */
true
4e288345d12da8d92e2e0e3d7dacdb1e9d2612b2
C++
ndsev/zserio
/compiler/extensions/cpp/runtime/src/zserio/JsonParser.h
UTF-8
8,325
2.96875
3
[ "BSD-3-Clause" ]
permissive
#ifndef ZSERIO_JSON_PARSER_H_INC #define ZSERIO_JSON_PARSER_H_INC #include "zserio/AnyHolder.h" #include "zserio/JsonDecoder.h" #include "zserio/JsonTokenizer.h" #include "zserio/Span.h" namespace zserio { /** * Json Parser. * * Parses the JSON on the fly and calls an observer. */ template <typename ALLOC = std::allocator<uint8_t>> class BasicJsonParser { public: /** * Json Parser Observer. */ class IObserver { public: /** * Destructor. */ virtual ~IObserver() = default; /** * Called when a JSON object begins - i.e. on '{'. */ virtual void beginObject() = 0; /** * Called when a JSON objects ends - i.e. on '}'. */ virtual void endObject() = 0; /** * Called when a JSON array begins - i.e. on '['. */ virtual void beginArray() = 0; /** * Called when a JSON array ends - i.e. on ']'. */ virtual void endArray() = 0; /** * Called on a JSON key. * * \param key String view to the key name. */ virtual void visitKey(StringView key) = 0; /** * Call on a JSON null value. * * \param nullValue Null value. */ virtual void visitValue(std::nullptr_t nullValue) = 0; /** * Call on a JSON bool value. * * \param boolValue Bool value. */ virtual void visitValue(bool boolValue) = 0; /** * Call on a JSON signed integer value. * * \param intValue Signed integer value. */ virtual void visitValue(int64_t intValue) = 0; /** * Call on a JSON unsigned integer value. * * \param uintValue Unsigned integer value. */ virtual void visitValue(uint64_t uintValue) = 0; /** * Call on a JSON floating point value. * * \param doubleValue Floating point value. */ virtual void visitValue(double doubleValue) = 0; /** * Call on a JSON string value. * * \param stringValue String view to the string value. */ virtual void visitValue(StringView stringValue) = 0; }; /** * Constructor. * * \param in Text stream to parse. * \param observer Observer to use. * \param allocator Allocator to use. */ BasicJsonParser(std::istream& in, IObserver& observer, const ALLOC& allocator = ALLOC()) : m_tokenizer(in, allocator), m_observer(observer) {} /** * Parses single JSON element from the text stream. * * \return True when end-of-file is reached, false otherwise (i.e. another JSON element is present). * \throw JsonParserException When parsing fails. */ bool parse() { if (m_tokenizer.getToken() == JsonToken::BEGIN_OF_FILE) m_tokenizer.next(); if (m_tokenizer.getToken() == JsonToken::END_OF_FILE) return true; parseElement(); return m_tokenizer.getToken() == JsonToken::END_OF_FILE; } /** * Gets current line number. * * \return Line number. */ size_t getLine() const { return m_tokenizer.getLine(); } /** * Gets current column number. * * \return Column number. */ size_t getColumn() const { return m_tokenizer.getColumn(); } private: void parseElement(); void parseObject(); void parseMembers(); void parseMember(); void parseArray(); void parseElements(); void parseValue(); void visitValue() const; void checkToken(JsonToken token); void consumeToken(JsonToken token); JsonParserException createUnexpectedTokenException(Span<const JsonToken> expecting) const; static const std::array<JsonToken, 3> ELEMENT_TOKENS; BasicJsonTokenizer<ALLOC> m_tokenizer; IObserver& m_observer; }; template <typename ALLOC> const std::array<JsonToken, 3> BasicJsonParser<ALLOC>::ELEMENT_TOKENS = { JsonToken::BEGIN_OBJECT, JsonToken::BEGIN_ARRAY, JsonToken::VALUE }; template <typename ALLOC> void BasicJsonParser<ALLOC>::parseElement() { JsonToken token = m_tokenizer.getToken(); if (token == JsonToken::BEGIN_ARRAY) parseArray(); else if (token == JsonToken::BEGIN_OBJECT) parseObject(); else if (token == JsonToken::VALUE) parseValue(); else throw createUnexpectedTokenException(ELEMENT_TOKENS); } template <typename ALLOC> void BasicJsonParser<ALLOC>::parseObject() { consumeToken(JsonToken::BEGIN_OBJECT); m_observer.beginObject(); if (m_tokenizer.getToken() == JsonToken::VALUE) parseMembers(); consumeToken(JsonToken::END_OBJECT); m_observer.endObject(); } template <typename ALLOC> void BasicJsonParser<ALLOC>::parseMembers() { parseMember(); while (m_tokenizer.getToken() == JsonToken::ITEM_SEPARATOR) { m_tokenizer.next(); parseMember(); } } template <typename ALLOC> void BasicJsonParser<ALLOC>::parseMember() { checkToken(JsonToken::VALUE); const AnyHolder<ALLOC>& key = m_tokenizer.getValue(); if (!key.template isType<string<ALLOC>>()) { throw JsonParserException("JsonParser:") << getLine() << ":" << getColumn() << ": Key must be a string value!"; } m_observer.visitKey(key.template get<string<ALLOC>>()); m_tokenizer.next(); consumeToken(JsonToken::KEY_SEPARATOR); parseElement(); } template <typename ALLOC> void BasicJsonParser<ALLOC>::parseArray() { consumeToken(JsonToken::BEGIN_ARRAY); m_observer.beginArray(); if (std::find(ELEMENT_TOKENS.begin(), ELEMENT_TOKENS.end(), m_tokenizer.getToken()) != ELEMENT_TOKENS.end()) parseElements(); consumeToken(JsonToken::END_ARRAY); m_observer.endArray(); } template <typename ALLOC> void BasicJsonParser<ALLOC>::parseElements() { parseElement(); while (m_tokenizer.getToken() == JsonToken::ITEM_SEPARATOR) { m_tokenizer.next(); parseElement(); } } template <typename ALLOC> void BasicJsonParser<ALLOC>::parseValue() { visitValue(); m_tokenizer.next(); } template <typename ALLOC> void BasicJsonParser<ALLOC>::visitValue() const { const AnyHolder<ALLOC>& value = m_tokenizer.getValue(); if (value.template isType<std::nullptr_t>()) { m_observer.visitValue(nullptr); } else if (value.template isType<bool>()) { m_observer.visitValue(value.template get<bool>()); } else if (value.template isType<int64_t>()) { m_observer.visitValue(value.template get<int64_t>()); } else if (value.template isType<uint64_t>()) { m_observer.visitValue(value.template get<uint64_t>()); } else if (value.template isType<double>()) { m_observer.visitValue(value.template get<double>()); } else { m_observer.visitValue(value.template get<string<ALLOC>>()); } } template <typename ALLOC> void BasicJsonParser<ALLOC>::checkToken(JsonToken token) { if (m_tokenizer.getToken() != token) throw createUnexpectedTokenException({{token}}); } template <typename ALLOC> void BasicJsonParser<ALLOC>::consumeToken(JsonToken token) { checkToken(token); m_tokenizer.next(); } template <typename ALLOC> JsonParserException BasicJsonParser<ALLOC>::createUnexpectedTokenException( Span<const JsonToken> expecting) const { JsonParserException error("JsonParser:"); error << getLine() << ":" << getColumn() << ": unexpected token: " << m_tokenizer.getToken(); if (expecting.size() == 1) { error << ", expecting " << expecting[0] << "!"; } else { error << ", expecting one of ["; for (size_t i = 0; i < expecting.size(); ++i) { if (i > 0) error << ", "; error << expecting[i]; } error << "]!"; } return error; } /** Typedef to Json Parser provided for convenience - using default std::allocator<uint8_t>. */ using JsonParser = BasicJsonParser<>; } // namespace #endif // ZSERIO_JSON_PARSER_H_INC
true
28c4cc15759e75a895ab7f9d880af4693ce738f6
C++
mehtadome/Programming-Projects
/C++ Projects/Dictionary/utils.cpp
UTF-8
707
3.078125
3
[]
no_license
// // utils.cpp // C++ Final // // Created by Ruchir Mehta on 7/21/16. // Copyright © 2016 Rucker. All rights reserved. // #include <iostream> #include "utils.hpp" #include <string> int stringLength (const char* src) { // finds the string length of the user's input if (src == NULL) return false; int i = 0; while (src[i] != NULL) { i++; } return i; } bool stringCopy (const char* src, char* dest) { // copies the string which the user inputted if (src == NULL || dest == NULL) return false; int srcLen = stringLength(src); int i = 0; for (; i < srcLen;i++) { dest[i] = src[i]; } dest[i] = NULL; return true; }
true
14ff5849d013e5f19282157d0d9bf73973e858bd
C++
Psykomusic/MobileGame
/PlayerWithSwipper/src/additional_functions.cpp
UTF-8
954
2.828125
3
[ "BSD-2-Clause" ]
permissive
#include "additional_functions.hpp" using namespace std; vector<string> split(string data, string separateur) { vector<string> tab; size_t pos; if(separateur.length() > 0) { while ((pos = data.find(separateur)) != string::npos) { tab.push_back(data.substr(0, pos)); data.erase(0, pos + separateur.length()); } } tab.push_back(data); return tab; } vector<string> split(string data, char separateur) { vector<string> tab; size_t pos; //cout << "test séparateur : " << data << endl; while ((pos = data.find(separateur)) != string::npos) { tab.push_back(data.substr(0, pos)); data.erase(0, pos + 1); } tab.push_back(data); return tab; } void delay(int sec) { QTime dieTime= QTime::currentTime().addSecs(sec); while (QTime::currentTime() < dieTime) QCoreApplication::processEvents(QEventLoop::AllEvents, 100); }
true
321a18a8c3930879c56a6133f48745b029a8fb81
C++
Skb-Hssn/DU-Predator
/BCC.cpp
UTF-8
1,330
2.734375
3
[]
no_license
/* - 1 based indexing */ #include<bits/stdc++.h> using namespace std; const int N = 1e5 + 5; int timer = 0; vector<int> G[N]; vector<int> low(N), disc(N), par(N), vis(N); vector<pair<int, int>> ST; vector<vector<pair<int, int>>> BCC; void dfs(int cur) { disc[cur] = low[cur] = timer; timer++; vis[cur] = true; int child = 0; for(int to : G[cur]) { if(!vis[to]) { child++; ST.push_back({cur, to}); par[to] = cur; dfs(to); low[cur] = min(low[cur], low[to]); if((par[cur] == 0 && child > 1) || (par[cur] != 0 && low[to] >= disc[cur])) { vector<pair<int, int>> temps; while(ST.back() != make_pair(cur, to)) { temps.push_back(ST.back()); ST.pop_back(); } temps.push_back(ST.back()); ST.pop_back(); BCC.push_back(temps); } } else if(par[cur] != to && disc[to] < low[cur]) { low[cur] = disc[to]; ST.push_back({cur, to}); } } } void findBCC(int n) { for(int i = 1; i <= n; i++) { if(vis[i] == false) { dfs(i); vector<pair<int, int>> temps; while(ST.size()) { temps.push_back(ST.back()); ST.pop_back(); } if(temps.size()) { BCC.push_back(temps); } } } } int main() { int n, m; scanf("%d%d", &n, &m); while(m--) { int u, v; scanf("%d%d", &u, &v); G[u].push_back(v); G[v].push_back(u); } findBCC(n); }
true
797948aaafce126f3c49e79ce64409866c3a8938
C++
eunho5751/BarrageShooting
/source files/Character.cpp
UHC
1,110
2.515625
3
[]
no_license
#include "PCH.h" #include "Character.h" #include "EntityMgr.h" #include "InputMgr.h" #include "ImageData.h" #include "def.h" CCharacter::CCharacter(ImageData * _image, float _scale, float _speed, float _x, float _y) : CEntity(_image, _scale, 1.0f, _speed, 0.0f, _x, _y) { } void CCharacter::Update(float _time) { //ij ̵ float distance = m_fSpeed * _time * 300.0f; float vx = (float)(INPUT_MGR().IsKeyPushed(VK_LEFT) ? -1 : (INPUT_MGR().IsKeyPushed(VK_RIGHT) ? 1: 0)); float vy = (float)(INPUT_MGR().IsKeyPushed(VK_UP) ? -1 : (INPUT_MGR().IsKeyPushed(VK_DOWN) ? 1 : 0)); float dst_x = m_fX + vx * distance; float dst_y = m_fY + vy * distance; float dx = dst_x - m_fX; float dy = dst_y - m_fY; float d = sqrtf(dx*dx + dy*dy); if (d > distance) { dx *= distance / d; dy *= distance / d; } dst_x = m_fX + dx; dst_y = m_fY + dy; if (dst_x < 0 || dst_x + m_pImage->image->GetWidth() * m_fScale + 5 > WINDOW_WIDTH || dst_y + m_pImage->image->GetHeight() * m_fScale + 25 > WINDOW_HEIGHT || dst_y < 0) return; m_fX += dx; m_fY += dy; }
true
f2f7f09df05396668870b481b76a86ecb5e80f4a
C++
matthewguillory65/IntroToProgramming
/IntroToProgramming/Conditionals/Conditionals.cpp
WINDOWS-1250
3,923
4.25
4
[]
no_license
#include <iostream> int main() { int num3 = 0; int num4 = 0; char bleh = 0; int Whatever; //Number 1 int s; int z = 0; if (z == 0) { s = 100; } std::cout << s; std::cout << "\n"; //Number 2 std::cout << "Please input two numbers" << std::endl; int num1; int num2; std::cin >> num1 >> num2; std::cout << "The larger number will be displayed first" << std::endl; if (num1 < num2) { std::cout << num2 << std::endl; } else if (num1 > num2) { std::cout << num1 << std::endl; } //Number 3 int num[5]; int i = 0; for (i; i < 100; i++); std::cout << num[i]; //Number 4 std::cout << "Please input a number" << std::endl; int choice; std::cin >> choice; switch (choice) { case 1: std::cout << "1"; break; case 2: std::cout << "2 or 3"; break; case 3: std::cout << "4"; break; default: std::cout << "invalid"; break; } //Number 5 std::cout << "\n"; std::cout << "Please enter something" << std::endl; int x; std::cin >> x; int y = (x == 0) ? 0 : 10 / x; std::cout << y; //Number 6 /* Write a program that accepts from the user two numbers and a mathematical operation character (+, -, *, /, %). Make case breaks to do the problems the user inputs. Perform the appropriate maths based on which character is input. Explanitory */ std::cin >> num1 >> bleh >> num2; switch (bleh) { case '+': Whatever = num3 + num4; break; case '*': Whatever = num3 * num4; break; case '-': Whatever = num3 - num4; break; case '/': Whatever = num3 / num4; break; case '%': Whatever = num3 / num4; break; default: std::cout << "Incorrect operator, please enter (+ - / *) \n"; break; } std::cout << " \n"; std::cout << "The answer is " << Whatever << "\n"; //Number 7 /* Write a program that accepts an integer that represents the month of the year. cin mos def ; that cin gonna take an int that int is gonna be month so prolly not gonna be greater than 12 1 -> 31 2 -> 28 3 -> 31 4 -> 30 5 -> 31 6 -> 30 7 -> 31 8 -> 31 9 -> 30 10 -> 31 11 -> 30 12 -> 31 It should then display the number of days in that month. cout the number of days for the month they put If a number that doesnt correspond to amonth is entered then the program should display an error message. If month number is not put, dialog error message. must be x<1 but y>12 */ int input; std::cout << "Please give me a month to know how many days. "; std::cout << "\n"; std::cin >> input; if (input == 1) { std::cout << "January has 31 days."; std::cout << "\n "; } else if (input == 2) { std::cout << "Febuary has 28 days."; std::cout << "\n"; } else if (input == 3) { std::cout << "March has 31 days."; std::cout << "\n"; } else if (input == 4) { std::cout << "April has 30 days."; std::cout << "\n"; } else if (input == 5) { std::cout << "May has 31 days."; std::cout << "\n"; } else if (input == 6) { std::cout << "June has 30 days."; std::cout << "\n"; } else if (input == 7) { std::cout << "July has 31 days."; std::cout << "\n"; } else if (input == 8) { std::cout << "August has 31 days."; std::cout << "\n"; } else if (input == 9) { std::cout << "Spetember has 30 days."; std::cout << "\n"; } else if (input == 10) { std::cout << "October has 31 days."; std::cout << "\n"; } else if (input == 11) { std::cout << "November has 30 days."; std::cout << "\n"; } else if (input == 12) { std::cout << "December has 31 days."; std::cout << "\n"; } system("pause"); return 0; /* Number 8 a. False b. True c. False d. True e. True f. False g. False h. True i. False j. frstChar == 'J' */ /*Number 9 a. (a || b) || (a && b) T F b. !((!a) && (a)) || (a && b) F T c. !((5 || a) || (!b)) && (!(a) && b) T F d. a|| b && a T F e.!a&&b F */ }
true
854014653df33245f8a65b8e2e919cd9f5191c13
C++
drummerpva/GoStackRocketSeat
/mapa.cpp
ISO-8859-1
2,358
3.046875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <locale.h> /* Trabalho MAPA de Douglas Poma - Curso ADS - Unicesumar - 52/2019 */ struct livro{ int codigo = -1; char autor[50]; char nome[50]; char editora[50]; }; int menu = 3; int cod = 0; int i; main(){ setlocale(LC_ALL, "Portuguese"); livro livros[5]; while(menu != 0){ fflush(stdin); system("cls"); printf("==========> Biblio C - Beta <==========\n\n\n"); printf("Menu\n"); printf("1 - Inserir Livro\n"); printf("2 - Mostrar todos os Livros\n"); printf("0 - Encerrar\n"); printf("Digite o nmero da opo desejada e tecle ENTER.: "); scanf("%d",&menu); fflush(stdin); if(menu == 0 ){ continue; } else if(menu > 2 || menu < 0){ system("cls"); printf("==========> Biblio C - Beta <==========\n\n\n"); printf("Opo invalida, tente novamente!\n"); system("pause"); } else if(menu == 1){ fflush(stdin); system("cls"); printf("==========> Biblio C - Beta <==========\n\n\n"); printf("=========> Cadastro de Livros <========\n"); if(!(cod > 4)){ printf("Insira o nome do Livro.: "); scanf("%[A-Za-z 0-9]", &livros[cod].nome); fflush(stdin); printf("\nInsira o autor do Livro.: "); scanf("%[A-Za-z 0-9]", &livros[cod].autor); fflush(stdin); printf("\nInsira a editora do Livro.: "); scanf("%[A-Za-z 0-9]", &livros[cod].editora); fflush(stdin); livros[cod].codigo = cod; cod++; printf("Livro Cadastrado com Sucesso!\n"); system("pause"); }else{ printf("Sistema de cadastro lotado. No possivel armazenar mais informaes!\n"); system("pause"); } }else if(menu == 2){ fflush(stdin); system("cls"); printf("==========> Biblio C - Beta <==========\n\n\n"); printf("========> Relatrio de Livros <========\n"); if(cod > 0){ for(i = 0; i <= 4; i++){ if(livros[i].codigo != -1){ printf("%d Livro:\n", i+1); printf(" Titulo.: %s\n", livros[i].nome); printf(" Autor.: %s\n", livros[i].autor); printf(" Editora.: %s\n", livros[i].editora); } } }else{ printf("Lista Vazia!\n"); } system("pause"); } menu = 3; } system("cls"); printf("==========> Biblio C - Beta <==========\n\n\n\n\n"); printf("Obrigado por usar nosso sistema! Tenha um bom dia.\n\n\n\n\n"); system("pause"); return 0; }
true
a914f7bdb935b5daf287f76a00fd4cbe4c95217a
C++
rjLelis/lista-de-exercicio-de-programacao
/exercicio 7.cpp
UTF-8
470
3.796875
4
[]
no_license
/*Programa em C que receba três valores e calcule a expressão abaixo: √(cos(x)² + sen(y)² + sen(z²)²) ------------------------------- 2 + cos(3) + cos(4) */ #include<iostream> #include<math.h> using namespace std; main(){ float x, y, z, res; cout<<"Digite tres numeros: "; cin >> x >> y >> z; res = sqrt(cos(x) * cos(y) + sin(y) * sin(y) + sin (z * z) * sin(z * z)) / (2 + cos(3) + cos(4)); cout << "Resultado: " << res << "\n"; }
true
93cdeaec4d480299f614424e93eca41e8dcc49bc
C++
yaishenka/SomeStuff
/SomeDAFEstudy/алгоритмы/1 семестр/Задание 1/5_2.cpp
UTF-8
2,346
3.296875
3
[]
no_license
#include <iostream> #include <string> #include <vector> #include <algorithm> #include <cmath> using namespace std ; struct Deque { private: char *buffer; int end,size, capacity; void resize (int length) { char *new_buffer = new char[length]; for (int i=0; i<end;++i) { new_buffer[i]=buffer[i]; } delete[] buffer; buffer=new_buffer; //delete[] new_buffer; capacity*=2; } public: Deque () { buffer=new char(2); end=0; size=0; capacity=2; } ~Deque() { //delete[] buffer; } char pop_front() { char result; if (!size) { result=' '; } else { result=buffer[end-1]; end--; } return result; } void push_front (char number){ if (size==capacity) { resize(capacity*2); } buffer[end]=number; end++; size++; } int givesize () { return size; } char what_up () { char result; if (!size) { result=' '; } else { result=buffer[end-1]; } //cout<<"what up: "<<result<<"\n"; return result; } }; int main () { string str1,str2,ans; int position(0); int position2(0); cin>>str1>>str2; Deque stack; bool canwego(true); while (canwego==true and position2<str2.size()){ if (position<=str1.size()) { if (str1[position]==str2[position2]) { ans+=str1[position]; position2++; position++; } else { if (stack.what_up()==str2[position2]) { ans+=stack.pop_front(); position2 += 1; } else { stack.push_front(str1[position]); position +=1 ; } } } else { if (stack.givesize()==0 || stack.what_up()!=str2[position2]) { canwego=false; } else { ans+=stack.pop_front(); position2+=1; } } } if (ans==str2) { cout<<"YES"; } else cout<<"NO"; }
true
69f8f4df6de003ee01ffca2fa1e5381dadd023ef
C++
SabikAbtahee/Code-Problems
/lightoj-1043-Triangle partitioning/1043-Triangle partitioning.cpp
UTF-8
520
2.59375
3
[]
no_license
#include<bits/stdc++.h> using namespace std; void file(){ freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); } void solve(){ double AB,AC,BC,ratio; double R,AD; cin >> AB >> AC >> BC >> ratio; R=(ratio)/(ratio+1); AD=AB*sqrt(R); cout << setprecision(10)<<AD<<"\n"; } void run(){ int testCase; cin >> testCase; for(int i=1;i<=testCase;i++){ cout << "Case " << i <<": "; solve(); } } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); file(); run(); return 0; }
true
06582fa44498c8a685a1e6beb0c836acbaecb2ee
C++
SongM/HelpLeetcodeCPP
/p138_20200831.cpp
UTF-8
811
3.203125
3
[]
no_license
/* // Definition for a Node. class Node { public: int val; Node* next; Node* random; Node(int _val) { val = _val; next = NULL; random = NULL; } }; */ class Solution { public: Node* copyRandomList(Node* head) { if (head==NULL) return(NULL); unordered_map<Node*, Node*> m; m[head] = new Node(head->val); m[NULL] = NULL; Node* n=head; while(n!=NULL) { if (m.find(n->next)==m.end()) m[n->next] = new Node(n->next->val); m[n]->next = m[n->next]; if (m.find(n->random)==m.end()) m[n->random] = new Node(n->random->val); m[n]->random = m[n->random]; n = n->next; } return(m[head]); } };
true
12e05462ff2d4c84ece2c59a357f46ad48e7ac6d
C++
josterholt/turn_based_rpg_server
/gamestate.cpp
UTF-8
10,886
2.546875
3
[]
no_license
#include "gamestate.h" #include "gameclient.h" #include <fstream> #include "rapidjson/istreamwrapper.h" #include <iostream> #include "utils.h" #include <math.h> #include "npcs.hpp" #define PI 3.14159265 GameState::GameState() { char s[25]; gen_random(s, 24); s[24] = '\0'; strcpy(this->token, s); // Default scripted nodes std::vector<EventNode> nodes; nodes.push_back(EventNode(0, 2)); nodes.push_back(EventNode(3, 0)); nodes.push_back(EventNode(0, -2)); nodes.push_back(EventNode(-3, 0)); this->eventNodes.push_back(nodes); this->loadLevel("level1"); } GameState::~GameState() { std::cout << "Destroy gamestate\n"; for (GameMob* mob : this->mobs) { delete mob; } } void GameState::loadLevel(std::string level) { std::cout << "Loading level...\n"; std::string filename = "C:/Users/Justin/Misc Code/Game/combat_system/src/assets/tiled_map/" + level + ".json"; std::ifstream file(filename.c_str()); if ((file.rdstate() & std::ifstream::failbit) != 0) { std::cout << "Error opening file\n"; return; } rapidjson::Document doc; rapidjson::IStreamWrapper isw(file); doc.ParseStream(isw); file.close(); std::cout << doc.GetParseError() << "\n"; std::string decoded_string; rapidjson::Value tiles = doc["layers"][0]["data"].GetArray(); for (rapidjson::Value::ValueIterator it = tiles.Begin(); it != tiles.End(); ++it) { this->tiles.push_back(it->GetInt()); } /* //decoded_string = std::string(doc["layers"][0]["data"].GetString()); for (int i = 0; i < tiles.size(); i = i + 4) { this->tiles.push_back((unsigned char) decoded_string[i]); } */ //this->spawnPoint = std::make_pair(doc["layers"][5]["objects"][0]["x"].GetFloat(), doc["layers"][5]["objects"][0]["y"].GetFloat()); /* int mob_index = getLayerIndex(doc["layers"], "mobs"); rapidjson::Value mob_objects = doc["layers"][mob_index]["objects"].GetArray(); for (rapidjson::Value::ValueIterator it = mob_objects.Begin(); it != mob_objects.End(); ++it) { std::string mob_name = (*it)["properties"]["type"].GetString(); if (std::find(NPC_LIST.begin(), NPC_LIST.end(), mob_name) != NPC_LIST.end()) { if ("mob_name" == "skeleton") { GameMob* mob = new GameMob(); mob->health = skeleton.health; mob->width = skeleton.width; mob->height = skeleton.height; mob->setPosition((*it)["x"].GetInt(), (*it)["y"].GetInt()); mob->loadScript(this->eventNodes[0]); this->mobs.push_back(mob); //std::cout << (*it)["x"].GetInt() << ", " << (*it)["y"].GetInt() << "\n"; } } } */ std::cout << "Level loaded\n"; std::cout << "Num mobs: " << this->mobs.size() << "\n"; } int GameState::getLayerIndex(rapidjson::Value &layers, std::string name) { if (!layers.IsArray()) { return -1; } for (rapidjson::Value::ValueIterator it = layers.Begin(); it != layers.End(); ++it) { if ((*it)["name"].GetString() == name) { return it - layers.Begin(); } } return 0; } void GameState::addPlayer(GamePlayer* player) { this->players.push_back(player); } void GameState::addMOB(GameMob* mob) { this->mobs.push_back(mob); } GameStatus GameState::getStateUpdates() { GameStatus g; g.players = this->getPlayerPositions(); strcpy(g.status, status); return g; } std::vector<GamePlayer*> GameState::getPlayerPositions() { return this->players; } const char * GameState::getToken() { return token; } // @todo Should be locking player so that write doesn't occur while checking for collision. Alternatively, pass collision detection into updatePosition? bool GameState::canMove(GamePlayer* player, float x, float y) { int h_step = 15; double o = 0, a = 0; //std::cout << "Current Position: " << player->positionX << ", " << player->positionY << "\n"; // Distance of x axis; o = abs(player->positionX - x); a = abs(player->positionY - y); //std::cout << "Distance: " << o << ", " << a << "\n"; // Before checking path, check if final destination is valid if (!boxCheck(player, x, y)) { return false; } if (o == 0 && a == 0) { return true; } float distance = getDistance(player, x, y); /* if (fabsf(player->positionX - x) > player->maxSpeed) { return false; } if (fabsf(player->positionY - y) > player->maxSpeed) { return false; } */ double radians = atan(o / a) * 180 / PI; double path_length = sin(radians) * o; //std::cout << "Path Length: " << path_length << "\n"; // For every x pixels in path, check tile if (path_length > h_step) { int tmp_h = 1; double new_y = 0, new_x = 0; // @todo Should reduce length so last tile isn't being double checked while (tmp_h < path_length) { new_y = player->positionY + (sin(radians) * tmp_h); new_x = player->positionX + (cos(radians) * tmp_h); if (!boxCheck(player, new_x, new_y)) { return false; } //std::cout << "Interpolation Check: " << new_x << " " << new_y << "\n"; tmp_h += h_step; } } return true; } float GameState::getDistance(GamePlayer* player, float x, float y) { GameClient& c = player->gameClient; std::cout << "Distance: " << std::to_string(player->gameClient.lastUpdateTime) << "\n"; return 0; } bool GameState::boxCheck(GamePlayer* player, float x, float y) { if (!isWalkableTile(getTileIndex(x, y))) { return false; } if (!isWalkableTile(getTileIndex(x + player->width, y))) { return false; } if (!isWalkableTile(getTileIndex(x, y + player->height))) { return false; } if (!isWalkableTile(getTileIndex(x + player->width, y + player->height))) { return false; } return true; } int GameState::getTileIndex(float x, float y) { int row, col; col = floor(x / this->tileWidth); row = floor(y / this->tileHeight); return (row * this->tilesPerRow) + col; } bool GameState::isWalkableTile(int tile_index) { if (tile_index < 0) { return false; } if (tile_index > this->tiles.size()) { return false; } if (this->tiles[tile_index] > 0) { return true; } return false; } void GameState::updatePosition(int player_index, float x, float y, float velocity_x, float velocity_y, FacingDirection facing) { GamePlayer* player = players[player_index]; if(canMove(player, x, y)) { player->updatePosition(x, y, facing); player->velocityX = velocity_x; player->velocityY = velocity_y; } } /** * As of current coding, collision detection assumes no angular boxes (everything is 90 degrees) */ void GameState::attackTarget(int player_index, float player_x, float player_y, float hitbox_x, float hitbox_y, int player_facing) { // Get current weapon int weapon_width = 10; int weapon_height = 30; //float new_x = player_x + (hitbox_x * cos(hitbox_rotation) - hitbox_y * sin(hitbox_rotation)); //float new_y = player_y + (hitbox_y * cos(hitbox_rotation) + hitbox_x * sin(hitbox_rotation)); // Collision box points // 1------2 // | | // | | // 4------3 point_t p1, p2, p3, p4; if(player_facing == 3) { // Facing UP float x_offset = 0.0f; float y_offset = 0.0f; p1 = { player_x, player_y - weapon_width }; p2 = { player_x + weapon_height, player_y - weapon_width }; p3 = { player_x + weapon_height, player_y }; p4 = { player_x, player_y }; } else if (player_facing == 1) { // Facing LEFT p1 = { player_x - weapon_width, player_y }; p2 = { player_x, player_y }; p3 = { player_x, player_y + weapon_height }; p4 = { player_x - weapon_width, player_y + weapon_height }; } else if (player_facing == 4) { // Facing DOWN float x_offset = 0.0f; float y_offset = 48.0f; p1 = { player_x, player_y + y_offset }; p2 = { player_x + weapon_height, player_y + y_offset }; p3 = { player_x + weapon_height, player_y + y_offset + weapon_width }; p4 = { player_x, player_y + y_offset + weapon_width }; } else { // Facing RIGHT float x_offset = 32.0f; float y_offset = 0.0f; p1 = { player_x + x_offset, player_y }; p2 = { player_x + x_offset + weapon_width, player_y }; p3 = { player_x + x_offset + weapon_width, player_y + weapon_height }; p4 = { player_x + x_offset, player_y + weapon_height }; } xy_points_t hitbox_points = { { p1[0], p1[1] }, { p2[0], p2[1] }, { p3[0], p3[1] }, { p4[0], p4[1] } }; //hitboxes.push_back(hitbox_points); int mob_width = 32; // temporary int mob_height = 48; // temporary for (std::vector<GameMob*>::iterator it = this->mobs.begin(); it != this->mobs.end(); it++) { float mob_x = (*it)->positionX; float mob_y = (*it)->positionY; int width = (*it)->width; int height = (*it)->height; xy_points_t mob_points = { { { mob_x, mob_y }, { mob_x + mob_width , mob_y }, { mob_x + mob_width, mob_y + mob_height }, { mob_x, mob_y + mob_height } } }; bool intersects_mob = false; if (hitbox_points[0][0] < mob_x + mob_width && hitbox_points[1][0] > mob_x && hitbox_points[0][1] < mob_y + mob_height && hitbox_points[3][1] > mob_y) { intersects_mob = true; } if (!intersects_mob) { if (mob_x < hitbox_points[1][0] && mob_x + mob_width > hitbox_points[0][0] && mob_y < hitbox_points[2][1] && mob_y + mob_height > hitbox_points[0][1]) { intersects_mob = true; } } if (intersects_mob) { std::cout << "#### MOB hit ####\n"; (*it)->health -= players[player_index]->damage; } } } void GameState::update(double elapsed_time) { //std::cout << "GameState update\n"; //std::cout << "Update mobs " << this->mobs.size() << "\n"; this->cleanupTimer += elapsed_time; if (this->cleanupTimer > this->cleanupInterval) { this->cleanupTimer = 0; std::cout << "Cleaning up mobs...\n"; for (std::vector<GameMob*>::iterator it = this->mobs.begin(); it != this->mobs.end(); ) { if ((*it)->health == 0) { std::cout << "Cleaning up mob\n"; it = this->mobs.erase(it); } else { ++it; } } } int alive_mob_count = 0; for(std::vector<GameMob*>::iterator it = this->mobs.begin(); it != this->mobs.end(); it++) { if ((*it)->health > 0) { alive_mob_count += 1; } } if (alive_mob_count == 0) { GameMob* mob = new GameMob(); mob->health = 20; // Get player position int player_x = this->players[0]->positionX; int player_y = this->players[0]->positionY; // Spawn within x pixels // Make sure spawn point is on a tile int offset_x = rand() % 50 + 1, offset_y = rand() % 50 + 1;; int mob_x = player_x + 10, mob_y = player_y + 10; srand(time(NULL)); // Brute force spawn generation while (!this->isWalkableTile(this->getTileIndex(mob_x, mob_y))) { offset_x = rand() % 50 + 1; offset_y = rand() % 50 + 1; } std::cout << "Setting position " << mob_x << ", " << mob_y << "\n"; mob->setPosition(mob_x, mob_y); mob->loadScript(this->eventNodes[0]); std::cout << "Adding mob " << mob->token << " at " << mob->positionX << ", " << mob->positionY << "\n"; this->addMOB(mob); } for (std::vector<GameMob*>::iterator it = this->mobs.begin(); it != this->mobs.end(); ++it) { (*it)->update(elapsed_time); } }
true
18fda64dc0b4dd86e6f7837a3a18eb48d7e2baa3
C++
Maxswang/DataStructureAPI
/SeqStack/SeqStack/main.cpp
GB18030
638
3.359375
3
[]
no_license
// main.cpp // ˳ṹջIJԳ #include <stdio.h> #include "seqstack.h" void play() { int i = 0; SeqStack *stack = NULL; int a[10]; for (i = 0; i < 10; ++i) { a[i] = i + 1; } stack = SeqStack_Create(20); // ջ for (int i = 0; i < 5; ++i) { SeqStack_Push(stack, &a[i]); } printf("len:%d \n", SeqStack_Size(stack)); printf("capacity:%d \n", SeqStack_Capacity(stack)); printf("top:%d \n", *((int *)SeqStack_Top(stack))); // Ԫسջ while (SeqStack_Size(stack)) { printf("%d ", *((int *)SeqStack_Pop(stack))); } SeqStack_Destroy(stack); return; } int main() { play(); return 0; }
true
f73510bcbdf3a31e0af97ea3c4cae0eb46a6f5a8
C++
Guillembonet/Lemmings_VJ-FIB
/Button.cpp
UTF-8
2,366
2.71875
3
[]
no_license
#include <GL/glew.h> #include <GL/gl.h> #include <glm/gtc/matrix_transform.hpp> #include "Button.h" Button *Button::createButton(glm::vec2 geom[2], glm::vec2 texCoords[2], std::function<void()> callback, Texture *buttonTex, ShaderProgram *program) { Button *quad = new Button(geom, texCoords, callback, buttonTex, program); return quad; } Button::Button(glm::vec2 geom[2], glm::vec2 texCoords[2], std::function<void()> callback, Texture *buttonTex, ShaderProgram *program) { this->callback = callback; this->x = geom[0].x; this->y = geom[0].y; this->width = geom[1].x - geom[0].x; this->height = geom[1].y - geom[0].y; float vertices[24] = { geom[0].x, geom[0].y, texCoords[0].x, texCoords[0].y, geom[1].x, geom[0].y, texCoords[1].x, texCoords[0].y, geom[1].x, geom[1].y, texCoords[1].x, texCoords[1].y, geom[0].x, geom[0].y, texCoords[0].x, texCoords[0].y, geom[1].x, geom[1].y, texCoords[1].x, texCoords[1].y, geom[0].x, geom[1].y, texCoords[0].x, texCoords[1].y }; this->texture = buttonTex; this->shaderProgram = program; glGenVertexArrays(1, &vao); glBindVertexArray(vao); glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, 24 * sizeof(float), vertices, GL_STATIC_DRAW); posLocation = program->bindVertexAttribute("position", 2, 4 * sizeof(float), 0); texCoordLocation = program->bindVertexAttribute("texCoord", 2, 4 * sizeof(float), (void *)(2 * sizeof(float))); } void Button::render() const { glm::mat4 modelview = glm::mat4(1.0f); glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_TEXTURE_2D); shaderProgram->setTextureUnit("tex", 0); glActiveTexture(GL_TEXTURE0); this->texture->use(); glBindVertexArray(vao); glEnableVertexAttribArray(posLocation); glEnableVertexAttribArray(texCoordLocation); glDrawArrays(GL_TRIANGLES, 0, 6); glDisable(GL_TEXTURE_2D); } void Button::free() { glDeleteBuffers(1, &vbo); } bool Button::isMouseOver() { return mouseOver; } void Button::mouseMoved(int mouseX, int mouseY, bool bLeftButton, bool bRightButton) { if ((x <= mouseX / 3) && (mouseX / 3 <= (x + width)) && (y <= mouseY / 3) && (mouseY / 3 <= (y + height))) { mouseOver = true; if (bLeftButton || bRightButton) callback(); // En caso de que se haga click izquierdo o derecho, llamamos al callback } else { mouseOver = false; } }
true
75c7346713ec3f4ac5bdb70c41942cc54b4f6d7d
C++
codingpotato/Lox-modern-cpp
/src/compiler.cpp
UTF-8
657
2.75
3
[ "MIT" ]
permissive
#include "compiler.h" namespace lox { Compile_error Compiler::make_compile_error(const std::string& message, const Token& token) noexcept { return Compile_error{ "[line " + std::to_string(token.line) + "] Error at " + (token.type != Token::eof ? "'" + token.lexeme + "': " : "end") + message}; } Compile_error Compiler::make_compile_error(const std::string& message, bool from_current) const noexcept { auto it = from_current ? current : previous; ENSURES(it != tokens.cend()); return make_compile_error(message, *it); } } // namespace lox
true
650208af8b2055caea94a40a6744886929b2b6c2
C++
kaito1111/GameTemplete
/GameTemplate/myEngine/ksEngine/sound/WaveFileBank.h
SHIFT_JIS
1,780
3.171875
3
[]
no_license
/*! *@brief g`f[^oNB */ #pragma once #include <map> class WaveFile; using WaveFilePtr = std::shared_ptr<WaveFile>; using WaveFilePtrMap = std::map<unsigned int, WaveFilePtr>; /*! *@brief g`f[^oNB *@details * x[hꂽg`f[^oNɓo^邱Ƃo܂B * o^ꂽg`f[^͍ēǂݍ݂sKvȂAoNėp邱Ƃo܂B */ class WaveFileBank { public: WaveFileBank(); ~WaveFileBank(); /*! *@brief g`f[^o^B *@param[in] groupID O[vhcBwłhc̍őlMAX_GROUP-1B *@param[in] waveFile g`f[^B */ void RegistWaveFile(int groupID, WaveFilePtr waveFile); /*! *@brief Ŏw肵t@CpX̔g`f[^oNɓo^Ă邩B *@param[in] groupID O[vhcBwłhc̍őlMAX_GROUP-1B *@param[in] filePath t@CpXB *@return g`f[^Bo^ĂȂꍇNULLԂB */ WaveFilePtr FindWaveFile(int groupID, const wchar_t* filePath); /*! *@brief g`f[^oNo^B *@param[in] groupID O[vhcBwłhc̍őlMAX_GROUP-1B *@param[in] waveFile g`f[^B */ void UnregistWaveFile(int groupID, WaveFilePtr waveFile); /*! *@brief O[vPʂʼnB */ void Release(int groupID); /*! *@brief SĉB */ void ReleaseAll() { for (int i = 0; i < MAX_GROUP; i++) { Release(i); } } private: static const int MAX_GROUP = 256; WaveFilePtrMap m_waveFileMap[MAX_GROUP]; //!<wavet@C̃XgB };
true
988818b642f4edada255284dbefc4c82fd07e044
C++
sailor-ux/mycodes
/leetcode_vscode/sxl/sec9/9_6.cpp
GB18030
2,364
3.140625
3
[]
no_license
#include <algorithm> #include <iostream> #include <vector> using namespace std; class Solution { public: vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { sort(candidates.begin(), candidates.end()); vector<int> combination; vector<vector<int>> combinations; vector<bool> used(candidates.size(), false); dfs(combination, combinations, candidates, used, 0, target); return combinations; } void dfs(vector<int>& combination, vector<vector<int>>& combinations, const vector<int>& candidates, vector<bool>& used, int index, int target) { if (target == 0) { combinations.push_back(combination); return; } for (int i = index; i < candidates.size() && candidates[i] <= target; i++) { // ֦Ż if (i > 0 && candidates[i] == candidates[i - 1] && !used[i - 1]) { // ظȥ continue; } combination.push_back(candidates[i]); used[i] = true; dfs(combination, combinations, candidates, used, i + 1, target - candidates[i]); combination.pop_back(); used[i] = false; } } // usedʵȥأ vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { sort(candidates.begin(), candidates.end()); vector<int> combination; vector<vector<int>> combinations; vector<bool> used(candidates.size(), false); dfs(combination, combinations, candidates, 0, target); return combinations; } void dfs(vector<int>& combination, vector<vector<int>>& combinations, const vector<int>& candidates, int index, int target) { if (target == 0) { combinations.push_back(combination); return; } for (int i = index; i < candidates.size() && candidates[i] <= target; i++) { // ֦Ż if (i > index && candidates[i] == candidates[i - 1]) { // ظȥ continue; } combination.push_back(candidates[i]); dfs(combination, combinations, candidates, i + 1, target - candidates[i]); combination.pop_back(); } } }; int main() { system("pause"); return 0; }
true
a02900148777acf98cd6a37fe23681f605869c4e
C++
granjero/ifts_14_CA
/CA_guia1_ej5/main.cpp
UTF-8
800
3.78125
4
[]
no_license
/* * File: main.cpp * Author: juanmiguel * * Created on 21 de mayo de 2016, 15:00 */ #include <stdio.h> #include <math.h> /* * */ //declaro funciones float funcion(float); main() { //variables float x; float resultado; //recibe las variables que se igresan por teclado printf("Ingrese el valor de X entre -1 y 1:\n"); scanf("%f",&x); if (x >= -1 && x <= 1) { resultado = funcion(x); printf("Resultado %.5F\n",resultado); } else { printf("El valor de X debe estar entre -1 y 1"); } } //funciones float funcion(float X) { float resultado; resultado = X * (2 / M_PI) * (1 -(pow(X,2) / 6) + (pow(X,4) / 40) - (pow(X,6) / 336) + (pow(X,8) / 3456)); return resultado; }
true
c12b0ef719bfbe86738c5fc67e214f8d7a39fbeb
C++
etri3600/SandEngine
/SandEngine/Scene/Node.cpp
UTF-8
1,589
2.71875
3
[]
no_license
#include "Node.h" #include "STime.h" extern IGraphicsInterface* gGraphics; void SNode::Tick() { auto CurrentTime = STime::GetTime(); auto milliseconds = m_Time > 0 ? CurrentTime - m_Time : 0LL; m_Time = CurrentTime; double delta = static_cast<double>(milliseconds) / 1000.0; if (m_bDirty) { Draw(delta); m_bDirty = false; } UpdateObjects(delta); gGraphics->UpdateBoneTransform(m_MaterialObjs); for (auto it = m_Children.begin(); it != m_Children.end(); ++it) { (*it)->Tick(); } } void SNode::Queue(SSceneObj* obj) { if (obj) { m_MaterialObjs[obj->Material.Type].push_back(obj); } } SNode* SNode::GetParent() { return m_pParent; } void SNode::SetParent(SNode * pNode) { if (m_pParent) { m_pParent->RemoveChild(this); } m_pParent = pNode; } SNode* SNode::CreateChild() { auto child = new SNode(); child->SetParent(this); m_Children.push_back(child); return child; } void SNode::AddChild(SNode* pNode) { m_Children.push_back(pNode); } void SNode::RemoveChild(SNode* pNode) { auto cit = std::find(m_Children.cbegin(), m_Children.cend(), pNode); if(cit != m_Children.cend()) m_Children.erase(cit); } std::vector<SNode*> SNode::GetChildren() { return m_Children; } void SNode::Draw(double delta) { gGraphics->Update(delta, m_MaterialObjs); } void SNode::Reset() { m_MaterialObjs.clear(); } void SNode::UpdateObjects(double delta) { for (auto it = m_MaterialObjs.begin(); it != m_MaterialObjs.end(); ++it) { for (auto model_it = it->second.begin(); model_it != it->second.end(); ++model_it) { (*model_it)->Update(delta); } } }
true
37210d346e3f1548359ef43473a7fc69baab30f9
C++
kitoriaaa/CppLearn
/LearnFromScratch/Part04/4-3.cpp
UTF-8
378
3.0625
3
[]
no_license
#include <iostream> namespace A { int count = 2; namespace P { int count = 5; int GetCount() { return count; } } // namespace P } // namespace A namespace B { int count = 4; } // namespace B int main() { std::cout << A::count << std::endl; std::cout << B::count << std::endl; std::cout << A::P::GetCount() << std::endl; return 0; }
true
669326928a7c56607727eddae3ce3b10f00e4b2d
C++
wwwkkkp/Algorithm
/Leetcode/118. 杨辉三角_递推.cpp
UTF-8
749
3.265625
3
[]
no_license
//118. 杨辉三角 给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。 在杨辉三角中,每个数是它左上方和右上方的数的和。 示例: 输入: 5 输出: [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] //递推 class Solution { public: vector<vector<int>> generate(int n) { if(!n)return {}; vector<vector<int>>v; v.push_back({1}); if(n==1)return v; for(int i=2;i<=n;i++){ vector<int>v1(i); for(int j=0;j<i;j++){ if(j==0)v1[0]=1; else if(j==i-1)v1[j]=1; else v1[j]=v.back()[j-1]+v.back()[j]; } v.push_back(v1); } return v; } };
true
3b0509b6a58ec1d60f82eef314fc589e22d9e8d5
C++
ommmirage/MMO-Client-Server
/NetCommon/net_message.h
UTF-8
2,326
3.328125
3
[]
no_license
#pragma once #include "net_common.h" enum class MsgTypes { MovePlayer }; struct message_header { // Enum class ensures that the messages are valid at compile time MsgTypes type; uint32_t size = 0; }; struct message { message_header header; std::vector<uint8_t> body; size_t size() const { return sizeof(message_header) + body.size(); } friend std::ostream& operator << (std::ostream& os, const message& msg) { os << "ID:" << int(msg.header.type) << " Size:" << msg.header.size; return os; } // Pushes any POD (Plain Old Data) into the message buffer template<typename DataType> friend message& operator << (message& msg, const DataType& data) { // Check that the type of the data being pushed is trivially copyable static_assert(std::is_standard_layout<DataType>::value, "Data is too complex to be pushed into vector"); size_t i = msg.body.size(); msg.body.resize(msg.body.size() + sizeof(DataType)); std::memcpy(msg.body.data() + i, &data, sizeof(DataType)); msg.header.size = msg.size(); return msg; } // Pulls any POD-like data form the message buffer template<typename DataType> friend message& operator >> (message& msg, DataType& data) { // Check that the type of the data being pushed is trivially copyable static_assert(std::is_standard_layout<DataType>::value, "Data is too complex to be pulled from vector"); // Cache the location towards the end of the vector where the pulled data starts size_t i = msg.body.size() - sizeof(DataType); // Physically copy the data from the vector into the user variable std::memcpy(&data, msg.body.data() + i, sizeof(DataType)); // Shrink the vector to remove read bytes, and reset end position msg.body.resize(i); // Recalculate the message size msg.header.size = msg.size(); // Return the target message so it can be "chained" return msg; } }; class connection; // An "owned" message is identical to a regular message, but it is associated with // a connection. On a server, the owner would be the client that sent the message, // on a client the owner would be the server. struct owned_message { std::shared_ptr<connection> remote = nullptr; message msg; // String maker friend std::ostream& operator << (std::ostream& os, owned_message& o_msg) { os << o_msg.msg; return os; } };
true
addadc0559fb1f0c306519c64866092218c436d7
C++
jiaty/CPP
/20131009/main.cpp
BIG5
2,515
3.53125
4
[]
no_license
#include <cstdlib> #include <iostream> using namespace std; class Ctime{ public: int hour; int minute; int second; int duration() //00:00:00}l { return (hour*60*60)+(second*60)+(second); } }; int main(int argc, char *argv[]) { Ctime time1; Ctime time2; int hour1; int minute1; int second1; int hour2; int minute2; int second2; int control0=0; int control1=0; int control2=0; while(control0!=1){ cout << "Please enter two set of time, including hour, minute, and second. "<<endl << "Press 0 to start. "<<endl; cin >> control1; while(control1!=1){ cout << "TIME1_HOUR: "<<endl; cin >> hour1; cout << "TIME1_MINUTE: "<<endl; cin >> minute1; cout << "TIME1_SECOND: "<<endl; cin >> second1; //ˬdJ hour:0~23 minute, second:0~59, WXdYsJ if((hour1>23 || hour1<0)||(minute1>59 || minute1<0)||(second1>59 || second1<0)) { cout << "You enter the wrong time!" <<endl << "Please try again: "<<endl; control1 = 0; } else{time1.hour = hour1; time1.minute = minute1; time1.second = second1; break;} } cout << "Press 0 to continue: "; cin >> control2; while(control2!=1){ cout << "TIME2_HOUR: "<<endl; cin >> hour2; cout << "TIME2_MINUTE: "<<endl; cin >> minute2; cout << "TIME2_SECOND: "<<endl; cin >> second2; if(hour2>23 || hour2<0) { cout << "You enter the wrong hour!" <<endl << "Please try again: "<<endl; control2 = 1; break; } else{time2.hour = hour2;} if(minute2>59 || minute2<0) { cout << "You enter the wrong minute!" <<endl << "Please try again: "<<endl; control2 = 1; break; } else{time2.minute = minute2;} if(second2>59 || second2<0) { cout << "You enter the wrong second!" <<endl << "Please try again: "<<endl; control2 = 1; break; } else{time2.second = second2;} control0=1; break; } } cout << "TIME1's duration: " <<endl //Xtime1, time2 << time1.duration() <<endl << "TIME2's duration: " <<endl << time2.duration() <<endl; system("PAUSE"); return EXIT_SUCCESS; }
true
8177afee94fec87e1dee17bffd8276c4864d1198
C++
cding2/f21-cse20312
/Lec21_Code/include/deque.h
UTF-8
1,016
3.390625
3
[]
no_license
#ifndef DEQUE_H #define DEQUE_H #include "dllist.h" template< class T > class deque{ private: dllist<T>* the_list; public: deque() : the_list( new dllist<T>() ) {} ~deque() { delete the_list; } deque(const deque<T>& copy) : the_list( new dllist<T>() ) { *the_list = copy.the_list; } deque<T>& operator=(const deque<T>& assign){ // Check the address if(this != &assign){ *the_list = assign.the_list; } return *this; } void push_front( const T& new_data ){ the_list->push_front( new_data ); } void push_back( const T& new_data ){ the_list->push_back( new_data ); } T front(){ return the_list->front(); } T back(){ return the_list->back(); } bool is_empty(){ return the_list->is_empty(); } bool pop_front( ){ return the_list->pop_front(); } bool pop_back( ){ return the_list->pop_front(); } }; #endif
true
76993ce1c298c3b14a4fe5c8d3e816515cadcc15
C++
guaidoukx/LeetCode
/h0199.h
UTF-8
1,480
2.90625
3
[]
no_license
// // Created by 项雅丽 on 2019/12/12. // #ifndef LEETCODE_H0199_H #define LEETCODE_H0199_H #include <iostream> #include <map> #include <set> #include <vector> #include <queue> #include <stack> #include <cmath> #include <string> #include <memory> #include <numeric> using namespace std; namespace h0199 { struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: vector<int> rightSideView(TreeNode *root) { vector<int> res; if (root == NULL) return res; queue<TreeNode *> curs; TreeNode *tmp; curs.push(root); while (true) { queue<TreeNode *> nexts; bool toRecord = true; while (!curs.empty()) { tmp = curs.front(); curs.pop(); if (toRecord) { res.push_back(tmp->val); toRecord = false; } if (tmp->right != NULL) nexts.push(tmp->right); if (tmp->left != NULL) nexts.push(tmp->left); } if (nexts.empty()) break; curs = nexts; } return res; } }; } #endif //LEETCODE_H0199_H
true
8054de914b10a0f527cd9364f1876d54918041aa
C++
najosky/darkeden-v2-serverfiles
/src/server/gameserver/skill/ShineSword.cpp
UHC
2,809
2.53125
3
[]
no_license
////////////////////////////////////////////////////////////////////////////// // Filename : ShineSword.cpp // Written by : elca@ewestsoft.com // Description : ////////////////////////////////////////////////////////////////////////////// #include "ShineSword.h" #include "SimpleTileMissileSkill.h" #include "EffectCurseOfBloodGround.h" #include "Gpackets/GCAddEffectToTile.h" ////////////////////////////////////////////////////////////////////////////// // ̾ Ʈ ڵ鷯 ////////////////////////////////////////////////////////////////////////////// void ShineSword::execute(Slayer * pSlayer, ObjectID_t TargetObjectID, SkillSlot * pSkillSlot, CEffectID_t CEffectID) throw(Error) { __BEGIN_TRY //cout << "TID[" << Thread::self() << "]" << getSkillHandlerName() << " Begin" << endl; Zone* pZone = pSlayer->getZone(); Assert(pZone != NULL); Creature* pTargetCreature = pZone->getCreature(TargetObjectID); if (pTargetCreature==NULL) { executeSkillFailException(pSlayer, getSkillType()); return; } SkillInput input(pSlayer, pSkillSlot); SkillOutput output; computeOutput(input, output); SIMPLE_SKILL_INPUT param; param.SkillType = getSkillType(); param.SkillDamage = output.Damage; param.Delay = output.Delay; param.ItemClass = Item::ITEM_CLASS_SWORD; param.STRMultiplier = 8; param.DEXMultiplier = 1; param.INTMultiplier = 1; param.bMagicHitRoll = false; param.bMagicDamage = false; param.bAdd = true; SIMPLE_SKILL_OUTPUT result; g_SimpleTileMissileSkill.execute(pSlayer, pTargetCreature->getX(), pTargetCreature->getY(), pSkillSlot, param, result); if ( result.bSuccess ) { for ( int i=-2; i<=2; ++i ) for ( int j=-2; j<=2; ++j ) { ZoneCoord_t tx = pTargetCreature->getX()+i; ZoneCoord_t ty = pTargetCreature->getY()+j; if ( !isValidZoneCoord(pZone, tx, ty) ) continue; Tile& rTile = pZone->getTile(tx, ty); if ( !rTile.canAddEffect() ) continue; EffectCurseOfBloodGround* pEffect = new EffectCurseOfBloodGround(pZone, tx, ty); pEffect->setLevel( input.SkillLevel ); pEffect->setDeadline( output.Duration ); pZone->registerObject( pEffect ); if ( i != 0 || j != 0 ) pEffect->setBroadcastingEffect(false); else { GCAddEffectToTile gcAE; gcAE.setEffectID( pEffect->getSendEffectClass() ); gcAE.setXY( tx, ty ); gcAE.setObjectID( pEffect->getObjectID() ); gcAE.setDuration( output.Duration ); pZone->broadcastPacket( tx, ty, &gcAE ); // cout << tx << ", " << ty << " Effect broadcast" << endl; } pZone->addEffect( pEffect ); rTile.addEffect( pEffect ); // cout << tx << ", " << ty << " add Effect" << endl; } } //cout << "TID[" << Thread::self() << "]" << getSkillHandlerName() << " End" << endl; __END_CATCH } ShineSword g_ShineSword;
true
5aa983b354d46572adf82a691a3906d5353c35a4
C++
gsalomao/cppdbc
/include/cppdbc/database.hpp
UTF-8
3,265
2.609375
3
[ "MIT" ]
permissive
/* * Copyright (C) 2020 Gustavo Salomao * * 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. */ /** * @brief Database interface. * @file */ #ifndef DATABASE_HPP #define DATABASE_HPP #include <memory> #include "exception.hpp" #include "resultset.hpp" #include "statement.hpp" #include "transaction.hpp" namespace cppdbc { /** * @brief Database interface. * * The database object manages the connection with the database. */ class Database { public: /** * @brief Destroy database. * * Destructor of the database connection. */ virtual ~Database() = default; /** * @brief Check if database is valid. * * Check if the database connection is valid still valid. An invalid * connection can't be used to interact with the database. * * @retval true - database connection is valid. * @retval false - database connection is invalid. */ [[nodiscard]] virtual bool valid() const noexcept = 0; /** * @brief Create statement. * * Create SQL statement to be executed in the database. * * @param[in] query SQL to be executed. * * @return Pointer to the created statement. * @throw std::invalid_argument in case of invalid query. * @throw std::logic_error in case of failure to create statement. */ virtual std::shared_ptr<Statement> create_statement(const std::string& query) = 0; /** * @brief Create transaction. * * Create transaction in the database. A transaction shall be used to * execute various SQL statement as a single operation. * * @return Pointer to the created transaction. * @throw std::logic_error in case of failure to create transaction. */ virtual std::shared_ptr<Transaction> create_transaction() = 0; /** * @brief Check if table exists. * * Check if table exists in the database. * * @param[in] tableName Name of the table to check. * * @retval true - table exists. * @retval false - table doesn't exist. * @throw std::logic_error in case of failure to check if table exists. */ virtual bool has_table(const std::string& tableName) = 0; }; } // namespace cppdbc #endif // DATABASE_HPP
true
4b06cfd9367ae450b391d8654b23e196781f751f
C++
MaheshBharadwaj/Pharmacy-Management
/Pharmacy.cpp
UTF-8
3,178
2.921875
3
[]
no_license
///Pharmacy.cpp #include <iostream> #include <sstream> ///String Stream #include <string> #include <iomanip> ///Output alignment #include <conio.h> ///getch() #include <fstream> #include <ctime> ///current date-time #include <queue> ///STL Queue #include <dirent.h> ///directory accessing #include <windows.h> using namespace std; void SetupScreen(){ ///EMULATING ALT + ENTER KEY PRESS keybd_event(VK_MENU,0x38,0,0); keybd_event(VK_RETURN,0x1c,0,0); keybd_event(VK_RETURN,0x1c,KEYEVENTF_KEYUP,0); keybd_event(VK_MENU,0x38,KEYEVENTF_KEYUP,0); ///SETTING COLOUR system("color 9F"); } inline const char* AlignL(){ ///HORIZONTAL ALIGNMENT //********ASSUMING NEW COURIER SIZE 20******** return "\t\t\t\t\t "; } inline const char* AlignV(){ ///VERTICAL ALIGNMENT return "\n\n\n\n\n\n\n\n\n\n"; } inline void Div(int w){ for(int i=0;i<w;i++) cout<<"_"; } #define CLEAR "cls" ///FUNCTION AND CLASS PROTOTYPES #include "Prototypes.hpp" #include "Member Management.hpp" #include "Employee Management.hpp" #include "Drug Management.hpp" ///CLASS DEFINITION(S) #include "Class_Drug.hpp" #include "Class_Member.hpp" #include "Class_Employee.hpp" ///FUNCTION DEFINITION(S) #include "Member Management.cpp" #include "Employee Management.cpp" #include "Daily Operations.hpp" #include "Verification.hpp" #include "Drug Management.cpp" #include "Report.hpp" #include "Discount Management.hpp" #include "Administrator.hpp" #include "Billing.hpp" int main(int argc,char** argv){ SetupScreen(); //Colour and full screen bool login=false; //Login reqd for billing float Discount=0; //Discount for every bill(default discount) time_t t=time(0); struct tm*now = localtime(&t); const int CY = now->tm_year + 1900, CM = now->tm_mon + 1, CD = now->tm_mday; Check_For_Expiry(CD,CM,CY); short int opt; while(true){ system(CLEAR); cout<<AlignV(); cout<<'\n'<<AlignL(); Div(54); cout<<'\n'<<AlignL()<<" PHARMACY MANAGEMENT SYSTEM V3.0.6" <<'\n'<<AlignL(); Div(54); cout<<'\n' <<'\n'<<AlignL()<<"1 - ADMIN ACCESS" <<'\n'<<AlignL()<<"2 - BILLING" <<'\n'<<AlignL()<<"0 - EXIT" <<'\n' <<'\n'<<AlignL(); Div(54); cout<<'\n'<<AlignL()<<"Enter your choice: "; cin>>opt; cin.get(); if(!cin){ cin.clear(); cin.sync(); opt=-1; } switch(opt){ case 1 : if( Verify ( login ) ) ///Upon verification admin( login , &Discount , CY , CM , CD ); break; case 2 : Bill ( login , Discount ); break; ///to compute bill case 0 : return EXIT_SUCCESS; break; ///User terminated default:cout<<'\a'; } } return EXIT_FAILURE; ///(Nearly)impossible as loop is infinite. }
true
8ca48305689fff90fffdc11990329b5bcbbae198
C++
aking6083/kingTranAssn3
/kingTranAssn3/KingTran-assn3-main.cpp
UTF-8
2,348
2.71875
3
[]
no_license
/***************************************************************************** // CODE FILENAME: KingTran-assn3-main.cpp // DESCRIPTION: // CLASS/TERM: CS372 Spring 8 Week 1 // DESIGNER: Adam King & Christopher Tran // FUNCTIONS:main() // // //****************************************************************************/ #include "TranKing-assn3-common.h" #include "King-assn3-funcs.h" #include "Tran-assn3-funcs.h" #include <iostream> #include <iomanip> #include <time.h> using namespace std; /****************************************************************************** // FUNCTION: main // DESCRIP: Driver function for doing test and displaying results. // OUTPUT: // Parameters: // Return Val: 0 on successfull exit // CALLS TO: createList,getTableSize,initOpenTable,showResults,runTest, // initSeperateChain // IMPLEMENTED BY: Adam King & Chris Tran ******************************************************************************/ int main() { int *randomNums, *openTable, tableSize = 0, last = 0, count = 0, numToSearch = 0; double loadFactor = 0, avg = 0, kAvg = 0; bool allocated = false; chainNode** sepChain = NULL; // Random numbers created randomNums = createList(last); // Get table size tableSize = getTableSize(); // Initialize open addressing table for linear probe test allocated = initOpenTable(openTable, tableSize); if (allocated) //Linear Probe { // Show information applicable to all tests showResults(loadFactor, tableSize, count, avg, kAvg, numToSearch, NONE); // Run Linear probe test on open table. runTest(openTable, sepChain, randomNums, tableSize, PROBE, loadFactor, avg, kAvg, count, numToSearch); // Initialize open addressing table for double hash test allocated = initOpenTable(openTable, tableSize); if (allocated) //Double Hash { // Run Linear probe test on open table. runTest(openTable, sepChain, randomNums, tableSize, DBL_HASH, loadFactor, avg, kAvg, count, numToSearch); // Initialize separate chaining table for separate chain test sepChain = initSeperateChain(tableSize, allocated); if (allocated) //Separate Chain { // run separate chaining test on sepChain count = 0; runTest(openTable, sepChain, randomNums, tableSize, CHAIN, loadFactor, avg, kAvg, count, numToSearch); } } } system("PAUSE"); return 0; }
true
29120d5ceceb6f1ef7200d93c48e76f9c8d96fb6
C++
coreyabshire/ants
/t3.cc
UTF-8
5,356
2.625
3
[ "Apache-2.0" ]
permissive
#include <iostream> #include <vector> #include <cassert> using namespace std; typedef int v0i; typedef vector<int> v1i; typedef vector<v1i> v2i; typedef bool v0b; typedef vector<v0b> v1b; typedef vector<v1b> v2b; enum { _, X, O }; struct t3m { size_t x, y; t3m() : x(9999), y(9999) {}; t3m(size_t x, size_t y) : x(x), y(y) {}; }; struct t3s { int p, u; v2i board; v2b moves; t3s(); t3s(int h, int v); t3s(int p, int u, const v2i &b, const v2b &m); char at(size_t x, size_t y) const; }; typedef pair<t3m,t3s> t3ms; typedef vector<t3ms> vt3ms; class t3g { public: size_t h, v; int k; t3s initial; t3g(size_t, size_t, int); t3s make_move(const t3m &m, const t3s &s) const; int utility(const t3s &s, int p) const; int terminal(const t3s &s) const; void display(const t3s &s); bool k_in_row(const v2i &board, const t3m &m, int p, int dx, int dy) const; int compute_utility(const v2i &board, const t3m &m, int p) const; vt3ms successors(const t3s &s) const; }; template <class S, class G, class A> int min_value(const S &s, const G &g, int p); template <class S, class G, class A> int max_value(const S &s, const G &g, int p) { typedef pair<A,S> P; typedef vector<P> vP; if (g.terminal(s)) return g.utility(s, p); int v = -99999999; vP vas = g.successors(s); for (typename vP::iterator as = vas.begin(); as != vas.end(); as++) { v = max(v, min_value<S,G,A>((*as).second, g, p)); } return v; } template <class S, class G, class A> int min_value(const S &s, const G &g, int p) { typedef pair<A,S> P; typedef vector<P> vP; if (g.terminal(s)) return g.utility(s, p); int v = 99999999; vP vas = g.successors(s); for (typename vP::iterator as = vas.begin(); as != vas.end(); as++) { v = min(v, max_value<S,G,A>((*as).second, g, p)); } return v; } template <class S, class G, class A> A minimax_decision(const S &s, const G &g) { typedef pair<A,S> P; typedef vector<P> vP; int maxv = -9999; A maxa; int p = s.p; vP vas = g.successors(s); for (typename vP::iterator as = vas.begin(); as != vas.end(); as++) { int v = min_value<S,G,A>((*as).second, g, p); if (v > maxv) { maxv = v; maxa = (*as).first; } } return maxa; } t3s::t3s(int h, int v) : p(X), u(0), board(h, v1i(v, _)), moves(h, v1b(v, true)) {} t3s::t3s(int p, int u, const v2i &b, const v2b &m) : p(p), u(u), board(b), moves(m) {} t3s t3g::make_move(const t3m &m, const t3s &s) const { assert(s.moves[m.x][m.y]); int p = s.p == X ? O : X; v2i board(s.board); board[m.x][m.y] = s.p; v2b moves(s.moves); moves[m.x][m.y] = false; int u = compute_utility(board, m, s.p); t3s s2(p, u, board, moves); assert(!s2.moves[m.x][m.y]); return s2; } t3g::t3g(size_t h=3, size_t v=3, int k=3) : h(h), v(v), k(k), initial(h, v) {} int t3g::utility(const t3s &s, int p) const { return s.u; } int t3g::terminal(const t3s &s) const { int n = 0; for (int x = 0; x < (int) h; x++) for (int y = 0; y < (int) v; y++) if (s.moves[x][y]) ++n; //cout << "checking terminal " << s.u << " " << n << endl; return s.u != 0 || n == 0; } int t3g::compute_utility(const v2i &board, const t3m &m, int p) const { return (k_in_row(board, m, p, 0, 1) || k_in_row(board, m, p, 1, 0) || k_in_row(board, m, p, 1, -1) || k_in_row(board, m, p, 1, 1)) ? (p == X ? 1 : -1) : 0; } bool t3g::k_in_row(const v2i &board, const t3m &m, int p, int dx, int dy) const { int n = 0; int x, y; x = (int)m.x; y = (int)m.y; while (x < (int)h && y < (int)v && board[x][y] == p) { ++n; x += dx; y += dy; } x = (int)m.x; y = (int)m.y; while (x >= 0 && y >= 0 && board[x][y] == p) { ++n; x -= dx; y -= dy; } --n; // because we counted m itself twice //cout << "n is " << n << endl; return n >= k; } char t3s::at(size_t x, size_t y) const { switch (board[x][y]) { case X: return 'X'; case O: return 'O'; default: return ' '; } } void t3g::display(const t3s &s) { for (size_t y = 0; y < (size_t)v; ++y) { for (size_t x = 0; x < (size_t)h; ++x) cout << s.at(x,y) << '.'; cout << endl; } cout << "utility: " << s.u << "; player: " << s.p << endl; } vt3ms t3g::successors(const t3s &s) const { vt3ms ms; for (int x = 0; x < (int)h; x++) { for (int y = 0; y < (int)v; y++) { if (s.moves[x][y]) { t3m m(x,y); ms.push_back(t3ms(m, make_move(m, s))); } } } return ms; } int main(int argc, char **argv) { t3g g; t3s s = g.initial; int x, y; do { t3m a = minimax_decision<t3s, t3g, t3m>(s, g); cout << "minimax: " << a.x << "," << a.y << endl; s = g.make_move(a, s); assert(!s.moves[a.x][a.y]); if (g.terminal(s)) break; g.display(s); cout << "your move? "; if (!(cin >> x >> y)) break; if (x < 0 || x >= 3 || y < 0 || y >= 3) { cout << "invalid move" << endl; } else if (!s.moves[x][y]) { cout << "move already taken" << endl; } else { s = g.make_move(t3m(x, y), s); assert(!s.moves[a.x][a.y]); assert(!s.moves[x][y]); } } while (!g.terminal(s)); g.display(s); cout << "game over. " << (s.u == 1 ? "you lose." : s.u == 0 ? "tie game." : "you win.") << endl; }
true