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
8a3d9ccbdd10c05232d4b31292528dbf1dc2997a
C++
sasaki-seiji/ProgrammingLanguageCPP4th
/part3/ch27/27-4-1-binary-tree/src/user.cpp
UTF-8
494
3.15625
3
[]
no_license
/* * user.cpp * * Created on: 2016/10/01 * Author: sasaki */ #include "binarytree.h" #include <vector> #include <iostream> using namespace std; using My_node = Node<double>; void user(const vector<double>& v) { My_node root{1.5}; int i = 0 ; for (auto x : v) { auto p = new My_node{x}; if (i++%2) root.add_left(p); else root.add_right(p); } root.print_tree(cout); } // add main int main() { vector<double> v {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0}; user(v); }
true
21808c238564b1dd3c26f30fb458bf4bd9a17309
C++
rodribat/algorithms
/find_digits.cpp
UTF-8
930
3.296875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; //version avoiding string conversions int findDigits(int n) { int divisors = 0; int d = n; while (d>0) { int divisor = d%10; d /= 10; if(divisor!=0 && n%divisor==0) divisors++; } return divisors; } int findDigitsOld(int n) { string s = std::to_string(n); int divisors = 0; for (int i=0; i<s.length(); i++) { //string to int conversion int divisor; stringstream convert(string(1,s[i])); convert >> divisor; if (divisor !=0 && n % divisor == 0) //division by zero avoidance divisors++; } return divisors; } int main() { int t; cin >> t; for(int a0 = 0; a0 < t; a0++){ int n; cin >> n; int result = findDigits(n); cout << result << endl; } return 0; }
true
c2384cf1c15d22ed73d4a1711ab2c0e8392ec99c
C++
Yaboi-Gengarboi/cs201
/homework/hw2/Money/money.cpp
UTF-8
1,840
4.15625
4
[]
no_license
/* money.cpp Justyn P. Durnford Created on 9/18/2019 Finished on 9/20/2019 This program asks the user for an amount for each unit of currency and then prints the units back before adding them up and printing the total value. */ #include <iostream> #include <string> using std::cout; using std::cin; using std::endl; using std::string; /* This function basically lets me determine whether the currency is plural or single. I didn't want to write a swicth for every type :P */ void printMoney(int amount, string type) { switch (amount) { case 0: break; case 1: cout << "You have 1 " << type << endl; break; default: cout << "You have " << amount << " " << type << "s" << endl; break; } } int main() { int nPennies = 0; int nNickels = 0; int nDimes = 0; int nQuarters = 0; int nHalfDollars = 0; int nDollars = 0; cout << "How many pennies do you have? "; cin >> nPennies; cout << "How many nickels do you have? "; cin >> nNickels; cout << "How many dimes do you have? "; cin >> nDimes; cout << "How many quarters do you have? "; cin >> nQuarters; cout << "How many half dollars do you have? "; cin >> nHalfDollars; cout << "how many dollars do you have? "; cin >> nDollars; double money = 0; money += nPennies * 0.01; money += nNickels * 0.05; money += nDimes * 0.1; money += nQuarters * 0.25; money += nHalfDollars * 0.5; money += nDollars; /* Pennies are the only currency I need do to something extra to for printMoney to work. */ switch (nPennies) { case 1: printMoney(nPennies, "penny"); break; default: printMoney(nPennies, "pennie"); break; } printMoney(nNickels, "nickel"); printMoney(nDimes, "dime"); printMoney(nQuarters, "quarter"); printMoney(nHalfDollars, "half dollar"); printMoney(nDollars, "dollar"); cout << "The total value of your cash is $" << money; return 0; }
true
11de79c5cb405ff2c6eeb4408006dacef80c7ee9
C++
longjianjiang/LeetOJ
/addition/offer_19.cpp
UTF-8
1,122
3.53125
4
[]
no_license
#include <iostream> #include <vector> #include <string> #include <stack> #include <queue> #include <map> #include <set> #include <unordered_set> #include <unordered_map> using namespace std; /* 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 -------------- 1,2,3,4,8,12,16,15,14,13,9,5,1,6,7,11,10 */ // 给定矩阵,从外向里以顺时针的顺序依次打印; // 找出边界的四个点,按顺时针方向,依次去取; class Solution { public: vector<int> printMatrix(vector<vector<int>> matrix) { int h = matrix.size(); if (h == 0) { return {}; } int w = matrix[0].size(); if (w == 0) { return {}; } vector<int> res; int bx = 0, ex = h-1; int by = 0, ey = w-1; while (true) { for (int i = by; i <= ey; ++i) { res.push_back(matrix[bx][i]); } if (++bx > ex) { break; } for (int i = bx; i <= ex; ++i) { res.push_back(matrix[i][ey]); } if (--ey < by) { break; } for (int i = ey; i >= by; --i) { res.push_back(matrix[ex][i]); } if (--ex < bx) { break; } for (int i = ex; i >= bx; --i) { res.push_back(matrix[i][by]); } if (++by > ey) { break; } } return res; } };
true
ded8214b246a3ee7bf832ccba7e5b27cf2bd3b68
C++
guffi8/OPERATING_SYSTEMS
/Block Chain/Block.cpp
UTF-8
2,268
2.84375
3
[]
no_license
/* * Block.cpp * * Created on: Apr 27, 2015 * Author: Yuval & Eric */ #include <unistd.h> #include <iostream> #include <cstdlib> #include <signal.h> #include <pthread.h> #include <queue> #include <list> #include "Block.h" #include <stdlib.h> /** * The constructor. construct new block. get the block's number and the block's father. */ Block::Block(int blockNum, Block* father): _blockNum(blockNum) { //Block::_blockNum = blockNum; Block::_blockData = NULL; Block::_father = father; if (Block::_father != NULL) { Block::_depth = Block::_father->_depth + 1; Block::_fatherBlockNum = father->getBlockNum(); } else { Block::_fatherBlockNum = 0; Block::_depth = 0; } Block::_isAttechd = false; Block::_toLongest = false; } /** * The de-constructor. free the block's data. */ Block::~Block() { if (Block::_blockData != NULL) { free(Block::_blockData); } Block::_blockData = NULL; } /** * Add new data to the block. */ void Block::addData(char* hashedData) { Block::_blockData = hashedData; } /** * return the block data. */ char* Block::getData() { return Block::_blockData; } /** * return the block's depth. */ int Block::getDepth() { return Block::_depth; } /** * return the block id number. */ int Block::getBlockNum() { return this->_blockNum; } /** * Mark the block as attached. */ void Block::setIsAtteched() { Block::_isAttechd = true; } bool Block::getIsAtteched() { return Block::_isAttechd; } /** * Set the block new father and update the block's depth according to the new father. */ void Block::setFather(Block* father) { Block::_father = father; Block::_depth = Block::_father->_depth + 1; Block::_fatherBlockNum = Block::_father->getBlockNum(); } /** * return the block's father. */ Block* Block::getFather() { return Block::_father; } /** * return true if lo_longest called for this block, false otherwise. */ bool Block::getToLongest() { return Block::_toLongest; } /** * Change the to_longest status of the block. */ void Block::setToLongest() { if(Block::_toLongest) { Block::_toLongest = false; } else { Block::_toLongest = true; } } /** * return the id number of the block's father. */ int Block::getFatherBlockNum() { return Block::_fatherBlockNum; }
true
8c2c51954645ecaff762bac2fb8b34ea081161f4
C++
arangodb/arangodb
/3rdParty/boost/1.78.0/libs/locale/examples/conversions.cpp
UTF-8
1,708
2.59375
3
[ "BSL-1.0", "Apache-2.0", "BSD-3-Clause", "ICU", "Zlib", "GPL-1.0-or-later", "OpenSSL", "ISC", "LicenseRef-scancode-gutenberg-2020", "MIT", "GPL-2.0-only", "CC0-1.0", "LicenseRef-scancode-autoconf-simple-exception", "LicenseRef-scancode-pcre", "Bison-exception-2.2", "LicenseRef-scancode...
permissive
// // Copyright (c) 2009-2011 Artyom Beilis (Tonkikh) // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #include <boost/locale.hpp> #include <boost/algorithm/string/case_conv.hpp> #include <iostream> #include <ctime> int main() { using namespace boost::locale; using namespace std; // Create system default locale generator gen; locale loc=gen(""); locale::global(loc); cout.imbue(loc); cout<<"Correct case conversion can't be done by simple, character by character conversion"<<endl; cout<<"because case conversion is context sensitive and not 1-to-1 conversion"<<endl; cout<<"For example:"<<endl; cout<<" German grüßen correctly converted to "<<to_upper("grüßen")<<", instead of incorrect " <<boost::to_upper_copy(std::string("grüßen"))<<endl; cout<<" where ß is replaced with SS"<<endl; cout<<" Greek ὈΔΥΣΣΕΎΣ is correctly converted to "<<to_lower("ὈΔΥΣΣΕΎΣ")<<", instead of incorrect " <<boost::to_lower_copy(std::string("ὈΔΥΣΣΕΎΣ"))<<endl; cout<<" where Σ is converted to σ or to ς, according to position in the word"<<endl; cout<<"Such type of conversion just can't be done using std::toupper that work on character base, also std::toupper is "<<endl; cout<<"not even applicable when working with variable character length like in UTF-8 or UTF-16 limiting the correct "<<endl; cout<<"behavior to unicode subset BMP or ASCII only"<<endl; } // vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 // boostinspect:noascii
true
7691a58d1632bd53b7b7ddda487738cd3c6ca244
C++
rafael-radkowski/HCI-557-CG
/gl_common/GLSurface.cpp
UTF-8
4,112
3
3
[ "MIT" ]
permissive
#include "GLSurface.h" #include <algorithm> GLSurface::GLSurface( vector<glm::vec3> &vertices, vector<glm::vec3> &normals): _vertices(vertices), _normals(normals) { } GLSurface::~GLSurface() { } /*! Init the geometry object */ void GLSurface::init(void) { initShader(); initVBO(); } /*! Create the vertex buffer object for this element */ void GLSurface::initVBO(void) { _num_vertices = _vertices.size(); // create memory for the vertices, etc. float* vertices = new float[_num_vertices * 3]; float* normals = new float[_normals.size() * 3]; // Copy all vertices for(int i=0; i<_vertices.size() ; i++) { glm::vec3 t = _vertices[i]; for (int j=0; j<3; j++) { vertices[(i*3)+j] = t[j]; } } // copy all normals for(int i=0; i<_normals.size() ; i++) { glm::vec3 n = _normals[i]; for (int j=0; j<3; j++) { normals[(i*3)+j] = n[j]; } } glGenVertexArrays(1, _vaoID); // Create our Vertex Array Object glBindVertexArray(_vaoID[0]); // Bind our Vertex Array Object so we can use it glGenBuffers(2, _vboID); // Generate our Vertex Buffer Object // vertices int locPos = glGetAttribLocation(_program, "in_Position"); glBindBuffer(GL_ARRAY_BUFFER, _vboID[0]); // Bind our Vertex Buffer Object glBufferData(GL_ARRAY_BUFFER, _num_vertices * 3 * sizeof(GLfloat), vertices, GL_STATIC_DRAW); // Set the size and data of our VBO and set it to STATIC_DRAW glVertexAttribPointer((GLuint)locPos, 3, GL_FLOAT, GL_FALSE, 0, 0); // Set up our vertex attributes pointer glEnableVertexAttribArray(locPos); // // normals int locNorm = glGetAttribLocation(_program, "in_Normal"); glBindBuffer(GL_ARRAY_BUFFER, _vboID[1]); // Bind our Vertex Buffer Object glBufferData(GL_ARRAY_BUFFER, _normals.size() * 3 * sizeof(GLfloat), &normals[0], GL_STATIC_DRAW); // Set the size and data of our VBO and set it to STATIC_DRAW glVertexAttribPointer((GLuint)locNorm, 3, GL_FLOAT, GL_FALSE, 0, 0); // Set up our vertex attributes pointer glEnableVertexAttribArray(locNorm); // glBindVertexArray(0); // Disable our Vertex Buffer Object } /* Inits the shader program for this object */ void GLSurface::initShader(void) { if(!_apperance.exists())return; // This loads the shader program from a file _program = _apperance.getProgram(); glUseProgram(_program); /////////////////////////////////////////////////////////////////////////////////////////////// // Vertex information / names glBindAttribLocation(_program, 0, "in_Position"); glBindAttribLocation(_program, 1, "in_Normal"); /////////////////////////////////////////////////////////////////////////////////////////////// // Define the model view matrix. _modelMatrix = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, 0.0f)); // Create our model matrix which will halve the size of our model addModelViewMatrixToProgram(_program); glUseProgram(0); } /*! Draw the objects */ void GLSurface::draw(void) { glUseProgram(_program); // Bind the buffer and switch it to an active buffer glBindVertexArray(_vaoID[0]); // this changes the camera location glm::mat4 rotated_view = rotatedViewMatrix(); glUniformMatrix4fv(_viewMatrixLocation, 1, GL_FALSE, &rotated_view[0][0]); // send the view matrix to our shader glUniformMatrix4fv(_inverseViewMatrixLocation, 1, GL_FALSE, &invRotatedViewMatrix()[0][0]); glUniformMatrix4fv(_modelMatrixLocation, 1, GL_FALSE, &_modelMatrix[0][0]); // //glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); // Draw the triangles glDrawArrays(GL_TRIANGLES, 0, _num_vertices); // Unbind our Vertex Array Object glBindVertexArray(0); } /*! Returns the number of vertices */ int GLSurface::size(void) { return _num_vertices; }
true
00170888f96799cc8c846ff011a159633abccfe6
C++
mavd09/notebook_unal
/Strings/Z algorithm.cpp
UTF-8
329
2.8125
3
[]
no_license
/// Complexity: O(|N|) /// Tested: https://tinyurl.com/yc3rjh4p vector<int> z_algorithm (string s) { int n = s.size(); vector<int> z(n); int x = 0, y = 0; for(int i = 1; i < n; ++i) { z[i] = max(0, min(z[i-x], y-i+1)); while (i+z[i] < n && s[z[i]] == s[i+z[i]]) x = i, y = i+z[i], z[i]++; } return z; }
true
5509f55fb20692a62a5e61e46c00db1b1ce66a96
C++
interestingLSY/intServer
/src/world/dim/chunk/block/block.hpp
UTF-8
930
2.921875
3
[]
no_license
#pragma once #include "base/common.hpp" namespace IntServer{ enum class BlockType : int{ GRASS_BLOCK, STONE }; class BlockProperties{ public: BlockType type; string name; }; BlockProperties blockProperties[16384]; class Block{ public: BlockType type; BlockProperties& GetProperties(){ return blockProperties[static_cast<int>(type)]; } }; } namespace IntServer::Blocks{ int blockCount = 0; Block GRASS_BLOCK; Block STONE; void RegisterBlock( Block &block , BlockType blockType , BlockProperties blockProperties ){ ++blockCount; block = Block{ type: blockType }; blockProperties.type = blockType; IntServer::blockProperties[static_cast<int>(blockType)] = blockProperties; } void RegisterDefaultBlocks(){ RegisterBlock(GRASS_BLOCK,BlockType::GRASS_BLOCK,{ type: BlockType::GRASS_BLOCK, name: "grass_block" }); RegisterBlock(STONE,BlockType::STONE,{ type: BlockType::STONE, name: "stone" }); } }
true
ff48df3f6d2d75f0e7083d48e85a28cd50efa4f0
C++
MohammadAliAfsahi/p.r.s.
/saver.cpp
UTF-8
8,586
2.625
3
[]
no_license
#include <stdio.h> #include<stdlib.h> #include <string.h> void teams(int b[32],int n); int main() { FILE *saved_game = fopen("c:\\Users\\eli\\Desktop\\teams2.txt","rb"); int i=0,j=0,s1=0,s2=0,s3=0,s4=0,s5=0,s6=0; char name[100]; char name_country[32][100]={NULL}; char group[32][100]; char num[32][100]; char fedrasion[32][100]; char sid[32][100]; char filename[32][100]; int b[32]; int z = 0,n; while(!(feof(saved_game))&&i<192){ fscanf(saved_game, "%99s", name); if(j%6==0){ // printf("%s\n",name); strcpy(name_country[s1],name); b[s1]=s1+1; s1++; } if(j%6 == 1){ //printf("%s\n",name); strcpy(group[s2],name); s2++; } if(j%6==2){ //printf("%s\n",name); strcpy(num[s3],name); s3++; } if(j%6==3){ //printf("%s\n",name); strcpy(fedrasion[s4],name); s4++; } if(j%6==4){ //printf("%s\n",name); strcpy(sid[s5],name); s5++; } if(j%6==5){ //printf("%s\n",name); strcpy(filename[s6],name); s6++; } j++; i++; } printf("please choose your team number:"); scanf("%d",&n); teams(b,n); } void teams(int b[32],int n){ int i=0; char p_name[10000]; FILE *player_name; printf("\nNUMBER NAME AGE POST SKILL FORM FITNES\n\n"); if(b[0]==n){ player_name= fopen("C:\\Users\\eli\\Desktop\\players\\Argentina.txt", "r"); while(!feof(player_name)) { fgets(p_name, 100000000, player_name); strtok(p_name, ","); printf("%s\n", p_name); } } if(b[1]==n){ player_name= fopen("C:\\Users\\eli\\Desktop\\players\\Australia.txt", "r"); while(!feof(player_name)) { fgets(p_name, 100000000, player_name); strtok(p_name, ","); printf("%s\n", p_name); } } if(b[2]==n){ player_name= fopen("C:\\Users\\eli\\Desktop\\players\\Belgium.txt", "r"); while(!feof(player_name)) { fgets(p_name, 100000000, player_name); strtok(p_name, ","); printf("%s\n", p_name); } } if(b[3]==n){ player_name= fopen("C:\\Users\\eli\\Desktop\\players\\Brazil.txt", "r"); while(!feof(player_name)) { fgets(p_name, 100000000, player_name); strtok(p_name, ","); printf("%s\n", p_name); } } if(b[4]==n){ player_name= fopen("C:\\Users\\eli\\Desktop\\players\\Colombia.txt", "r"); while(!feof(player_name)) { fgets(p_name, 100000000, player_name); strtok(p_name, ","); printf("%s\n", p_name); } } if(b[5]==n){ player_name= fopen("C:\\Users\\eli\\Desktop\\players\\Costarica.txt", "r"); while(!feof(player_name)) { fgets(p_name, 100000000, player_name); strtok(p_name, ","); printf("%s\n", p_name); } } if(b[6]==n){ player_name= fopen("C:\\Users\\eli\\Desktop\\players\\Croatia.txt", "r"); while(!feof(player_name)) { fgets(p_name, 100000000, player_name); strtok(p_name, ","); printf("%s\n", p_name); } } if(b[7]==n){ player_name= fopen("C:\\Users\\eli\\Desktop\\players\\Denmark.txt", "r"); while(!feof(player_name)) { fgets(p_name, 100000000, player_name); strtok(p_name, ","); printf("%s\n", p_name); } } if(b[8]==n){ player_name= fopen("C:\\Users\\eli\\Desktop\\players\\Egypt.txt", "r"); while(!feof(player_name)) { fgets(p_name, 100000000, player_name); strtok(p_name, ","); printf("%s\n", p_name); } } if(b[9]==n){ player_name= fopen("C:\\Users\\eli\\Desktop\\players\\England.txt", "r"); while(!feof(player_name)) { fgets(p_name, 100000000, player_name); strtok(p_name, ","); printf("%s\n", p_name); } } if(b[10]==n){ player_name= fopen("C:\\Users\\eli\\Desktop\\players\\France.txt", "r"); while(!feof(player_name)) { fgets(p_name, 100000000, player_name); strtok(p_name, ","); printf("%s\n", p_name); } } if(b[11]==n){ player_name= fopen("C:\\Users\\eli\\Desktop\\players\\Germany.txt", "r"); while(!feof(player_name)) { fgets(p_name, 100000000, player_name); strtok(p_name, ","); printf("%s\n", p_name); } } if(b[12]==n){ player_name= fopen("C:\\Users\\eli\\Desktop\\players\\Iceland.txt", "r"); while(!feof(player_name)) { fgets(p_name, 100000000, player_name); strtok(p_name, ","); printf("%s\n", p_name); } } if(b[13]==n){ player_name= fopen("C:\\Users\\eli\\Desktop\\players\\Iran.txt", "r"); while(!feof(player_name)) { fgets(p_name, 100000000, player_name); strtok(p_name, ","); printf("%s\n", p_name); } } if(b[14]==n){ player_name= fopen("C:\\Users\\eli\\Desktop\\players\\Japan.txt", "r"); while(!feof(player_name)) { fgets(p_name, 100000000, player_name); strtok(p_name, ","); printf("%s\n", p_name); } } if(b[15]==n){ player_name= fopen("C:\\Users\\eli\\Desktop\\players\\KoreaRepublic.txt", "r"); while(!feof(player_name)) { fgets(p_name, 100000000, player_name); strtok(p_name, ","); printf("%s\n", p_name); } } if(b[16]==n){ player_name= fopen("C:\\Users\\eli\\Desktop\\players\\Mexico.txt", "r"); while(!feof(player_name)) { fgets(p_name, 100000000, player_name); strtok(p_name, ","); printf("%s\n", p_name); } } if(b[17]==n){ player_name= fopen("C:\\Users\\eli\\Desktop\\players\\Morocco.txt", "r"); while(!feof(player_name)) { fgets(p_name, 100000000, player_name); strtok(p_name, ","); printf("%s\n", p_name); } } if(b[18]==n){ player_name= fopen("C:\\Users\\eli\\Desktop\\players\\Nigeria.txt", "r"); while(!feof(player_name)) { fgets(p_name, 100000000, player_name); strtok(p_name, ","); printf("%s\n", p_name); } } if(b[19]==n){ player_name= fopen("C:\\Users\\eli\\Desktop\\players\\Panama.txt", "r"); while(!feof(player_name)) { fgets(p_name, 100000000, player_name); strtok(p_name, ","); printf("%s\n", p_name); } } if(b[20]==n){ player_name= fopen("C:\\Users\\eli\\Desktop\\players\\Peru.txt", "r"); while(!feof(player_name)) { fgets(p_name, 100000000, player_name); strtok(p_name, ","); printf("%s\n", p_name); } } if(b[21]==n){ player_name= fopen("C:\\Users\\eli\\Desktop\\players\\Poland.txt", "r"); while(!feof(player_name)) { fgets(p_name, 100000000, player_name); strtok(p_name, ","); printf("%s\n", p_name); } } if(b[22]==n){ player_name= fopen("C:\\Users\\eli\\Desktop\\players\\Portugal.txt", "r"); while(!feof(player_name)) { fgets(p_name, 100000000, player_name); strtok(p_name, ","); printf("%s\n", p_name); } } if(b[23]==n){ player_name= fopen("C:\\Users\\eli\\Desktop\\players\\Russia.txt", "r"); while(!feof(player_name)) { fgets(p_name, 100000000, player_name); strtok(p_name, ","); printf("%s\n", p_name); } } if(b[24]==n){ player_name= fopen("C:\\Users\\eli\\Desktop\\players\\SaudiArabia.txt", "r"); while(!feof(player_name)) { fgets(p_name, 100000000, player_name); strtok(p_name, ","); printf("%s\n", p_name); } } if(b[25]==n){ player_name= fopen("C:\\Users\\eli\\Desktop\\players\\Senegal.txt", "r"); while(!feof(player_name)) { fgets(p_name, 100000000, player_name); strtok(p_name, ","); printf("%s\n", p_name); } } if(b[26]==n){ player_name= fopen("C:\\Users\\eli\\Desktop\\players\\Serbia.txt", "r"); while(!feof(player_name)) { fgets(p_name, 100000000, player_name); strtok(p_name, ","); printf("%s\n", p_name); } } if(b[27]==n){ player_name= fopen("C:\\Users\\eli\\Desktop\\players\\Spain.txt", "r"); while(!feof(player_name)) { fgets(p_name, 100000000, player_name); strtok(p_name, ","); printf("%s\n", p_name); } } if(b[28]==n){ player_name= fopen("C:\\Users\\eli\\Desktop\\players\\Sweden.txt", "r"); while(!feof(player_name)) { fgets(p_name, 100000000, player_name); strtok(p_name, ","); printf("%s\n", p_name); } } if(b[29]==n){ player_name= fopen("C:\\Users\\eli\\Desktop\\players\\Switzerland.txt", "r"); while(!feof(player_name)) { fgets(p_name, 100000000, player_name); strtok(p_name, ","); printf("%s\n", p_name); } } if(b[30]==n){ player_name= fopen("C:\\Users\\eli\\Desktop\\players\\Tunisia.txt", "r"); while(!feof(player_name)) { fgets(p_name, 100000000, player_name); strtok(p_name, ","); printf("%s\n", p_name); } } if(b[31]==n){ player_name= fopen("C:\\Users\\eli\\Desktop\\players\\Uruguay.txt", "r"); while(!feof(player_name)) { fgets(p_name, 100000000, player_name); strtok(p_name, ","); printf("%s\n", p_name); } } }
true
63851bbfc3b877739a93fd8189b6362b34f4c6a2
C++
fly8wo/Code----
/c&c++/Code/12m5d/求阶乘和.cpp
WINDOWS-1252
275
2.984375
3
[]
no_license
//׳˵ĺ #include <iostream> #include <cstdio> using namespace std; int main() { int n; cin >> n; int sum =0 ; int fac=1; for (int i=1;i<=n;++i){ // int fac=1; // for(int j = 1 ; j <=i;++j) fac *=i ; sum +=fac; } cout<<sum; return 0; }
true
9e6198865b4e6bfec1cb0e855477e74104c3bc92
C++
yangdongzju1976/c_language
/code_其他班级/20200410/12.cpp
GB18030
578
3.078125
3
[]
no_license
#include<stdio.h> int main() { int score = 0; printf("\n:"); scanf("%d", &score); if(score<30) printf("\n30֣"); if(score<60&&score>=30) printf("30֣С 60 ֣񣬽ϲ \n"); if (score >= 60&&score <= 80) printf("60С80еˮƽ\n"); if (score > 80 && score < 90) printf("80С90ɼ\n"); if ( score >= 90) printf("90ɼ\n"); return 0; }
true
a5decacf7a8f3010802a2b3595793ab86b62dbae
C++
sirzooro/RakeSearch
/RakeSearchV1/Square/Square/DLX_DLS.cpp
UTF-8
17,454
2.875
3
[]
no_license
#include "DLX_DLS.h" void orth_mate_search::generate_permutations(int n, vector<vector<int>> &perm, bool diag) { vector<int> seed; for (int i = 0; i < n; i++) { seed.push_back(i); } do { bool acc = true; if (diag == true) { int md = 0; int ad = 0; for (int j = 0; j < n; j++) { if (seed[j] == j) { md++; } if (seed[j] == n - j - 1) { ad++; } } if ((md != 1) || (ad != 1)) { acc = false; } } if (acc == true) { perm.push_back(seed); } } while (std::next_permutation(seed.begin(), seed.end())); //cout << "Generated " << perm.size() << "permutations" << endl; } void orth_mate_search::construct_square_from_tv(vector<vector<int>> &tv_set, vector<int> &tv_ind, vector<vector<int>> &SQ) { sort(tv_ind.begin(), tv_ind.end()); for (int i = 0; i < tv_ind.size(); i++) { for (int j = 0; j < tv_set[tv_ind[i]].size(); j++) { SQ[j][tv_set[tv_ind[i]][j]] = i; } } } void orth_mate_search::construct_squares_from_tv_set(vector<vector<int>>&tv_set, vector<vector<int>> &tv_index_sets, vector<vector<vector<int>>> &SQUARES) { for (int i = 0; i < tv_index_sets.size(); i++) { construct_square_from_tv(tv_set, tv_index_sets[i], SQUARES[i]); } } void TV_check(vector<vector<int>> &TVSET, vector<vector<int>> &LS, vector<int> &indices) { int n = LS.size(); for (int i = 0; i < TVSET.size(); i++) { vector<int> tmp(10); bool a = true; for (int u = 0; u < n; u++) { tmp[LS[u][TVSET[i][u]]]++; if (tmp[LS[u][TVSET[i][u]]]>1) { a = false; break; } } if (a == true) { indices.push_back(i); } } } void orth_mate_search::cover(DLX_column *&c) { //cout << "Covered " << c->column_number << endl; c->Right->Left = c->Left; c->Left->Right = c->Right; DLX_column *i; DLX_column *j; i = c->Down; while (i != c) { j = i->Right; while (j != i) { j->Down->Up = j->Up; j->Up->Down = j->Down; // cout << "covered element " << j->row_id << " in column " << j->column_number << endl; j->Column->size--; if (j->Column->size < 0) { cout << "We are in deep trouble" << endl; } j = j->Right; } i = i->Down; } } void orth_mate_search::uncover(DLX_column *&c) { //cout << "Uncovered " << c->column_number << endl; DLX_column *i; DLX_column *j; i = c->Up; while (i != c) { j = i->Left; while (j != i) { j->Column->size++; j->Down->Up = j; j->Up->Down = j; j = j->Left; } i = i->Up; } c->Right->Left = c; c->Left->Right = c; } void orth_mate_search::choose_c(DLX_column &h, DLX_column *&c) { DLX_column * j; j = h.Right; int min = j->size; c = j; while (j != &h) { if (j->size < min) { c = j; min = j->size; } j = j->Right; } } void orth_mate_search::print_solution(vector<DLX_column*> &ps) { cout << endl; for (int i = 0; i < ps.size(); i++) { cout << ps[i]->row_id << " "; } cout << endl; } void orth_mate_search::search_limited(int k, DLX_column &h, vector<DLX_column*> &ps, vector<vector<int>> &tvr, bool &cont, unsigned long long &limit, bool &count_only, unsigned long long &count) { //pd = partial solution if (k > 10) { cout << "we are in trouble" << endl; } // cout << "Search " << k << endl; if (cont == true) { if (h.Right == &h) { count++; if (count_only == false) { vector<int> tmpv; for (int i = 0; i < ps.size(); i++) { tmpv.push_back(ps[i]->row_id); } tvr.push_back(tmpv); } if (count > limit) { cont = false; } if (count % 10000000 == 0) { cout << count << endl; } //print_solution(ps); } else { DLX_column * c = NULL; choose_c(h, c); //cout << "picked column " << c->column_number << endl; cover(c); DLX_column * r = c->Down; while ((r != c) && (cont == true)) { ps.push_back(r); DLX_column * j; j = r->Right; while (j != r) { cover(j->Column); j = j->Right; } search_limited(k + 1, h, ps, tvr, cont, limit, count_only, count); r = ps.back(); //questionable. ps.pop_back(); c = r->Column; j = r->Left; while (j != r) { uncover(j->Column); j = j->Left; } r = r->Down; } uncover(c); //return; } } } void orth_mate_search::search(int k, DLX_column &h, vector<DLX_column*> &ps, vector<vector<int>> &tvr) { //pd = partial solution if (k > 10) { cout << "we are in trouble" << endl; } // cout << "Search " << k << endl; if (h.Right == &h) { vector<int> tmpv; for (int i = 0; i < ps.size(); i++) { tmpv.push_back(ps[i]->row_id); } tvr.push_back(tmpv); //cout << tvr.size() << endl; //print_solution(ps); } else { DLX_column * c = NULL; choose_c(h, c); // cout << "picked column " << c->column_number << endl; cover(c); DLX_column * r = c->Down; while (r != c) { ps.push_back(r); DLX_column * j; j = r->Right; while (j != r) { cover(j->Column); j = j->Right; } search(k + 1, h, ps, tvr); r = ps.back(); //questionable. ps.pop_back(); c = r->Column; j = r->Left; while (j != r) { uncover(j->Column); j = j->Left; } r = r->Down; } uncover(c); //return; } } void orth_mate_search::TVSET_TO_DLX(DLX_column &root, vector<vector<int>> & tvset, vector<DLX_column*> & elements) { int dimension = tvset[0].size(); root.Up = NULL; root.Down = NULL; root.Column = NULL; root.row_id = -1; root.size = -1; // root.column_number= -1; elements.push_back(&root); vector<DLX_column *> columns; DLX_column * lastleft = &root; for (int i = 0; i < dimension* dimension; i++) { DLX_column *ct; ct = new (DLX_column); // ct->column_number = i; ct->Down = ct; ct->Up = ct; ct->size = 0; ct->row_id = 0; ct->Column = ct; ct->Left = lastleft; lastleft->Right = ct; lastleft = ct; columns.push_back(ct); elements.push_back(ct); } lastleft->Right = &root; root.Left = lastleft; for (int i = 0; i < tvset.size(); i++) { vector<int> curtv = tvset[i]; vector<DLX_column *> tvrow; for (int j = 0; j < curtv.size(); j++) { DLX_column *ctve; ctve = new (DLX_column); //column corresponds to characteristic vector of LS or smth of that kind int k = j*dimension + curtv[j]; ctve->Column = columns[k]; ctve->Column->size++; ctve->Down = columns[k]; ctve->Up = columns[k]->Up; ctve->Up->Down = ctve; ctve->Down->Up = ctve; ctve->row_id = i; // ctve->column_number = k; ctve->size = -10; elements.push_back(ctve); tvrow.push_back(ctve); } for (int j = 0; j < tvrow.size() - 1; j++) { tvrow[j]->Right = tvrow[j + 1]; tvrow[j]->Right->Left = tvrow[j]; } tvrow[tvrow.size() - 1]->Right = tvrow[0]; tvrow[0]->Left = tvrow[tvrow.size() - 1]; } DLX_column *pr = &root; } void orth_mate_search::SQ_TO_DLX(DLX_column &root, vector<vector<int>> & SQ, vector<DLX_column*> & elements) { int dimension = SQ[0].size(); root.Up = NULL; root.Down = NULL; root.Column = NULL; root.row_id = -1; root.size = -1; // root.column_number= -1; elements.push_back(&root); vector<DLX_column *> columns; DLX_column * lastleft = &root; // first n - row number // n to 2n - column number //2n to 3n - value //3n+1 - diag //3n+2 - antidiag for (int i = 0; i < 3 * dimension + 2; i++) { DLX_column *ct; ct = new (DLX_column); // ct->column_number = i; ct->Down = ct; ct->Up = ct; ct->size = 0; ct->row_id = 0; ct->Column = ct; ct->Left = lastleft; lastleft->Right = ct; lastleft = ct; columns.push_back(ct); elements.push_back(ct); } lastleft->Right = &root; root.Left = lastleft; for (int i = 0; i < SQ.size(); i++) { for (int j = 0; j < SQ[i].size(); j++) { vector<DLX_column *> tvrow; DLX_column *ctve; ctve = new (DLX_column); ctve->Column = columns[i]; ctve->Column->size++; ctve->Down = columns[i]; ctve->Up = columns[i]->Up; ctve->Up->Down = ctve; ctve->Down->Up = ctve; ctve->row_id = i*dimension + j; // ctve->column_number = k; ctve->size = -10; elements.push_back(ctve); tvrow.push_back(ctve); ctve = new (DLX_column); //column corresponds to characteristic vector of LS or smth of that kind ctve->Column = columns[dimension + j]; ctve->Column->size++; ctve->Down = columns[dimension + j]; ctve->Up = columns[dimension + j]->Up; ctve->Up->Down = ctve; ctve->Down->Up = ctve; ctve->row_id = i*dimension + j; // ctve->column_number = k; ctve->size = -10; elements.push_back(ctve); tvrow.push_back(ctve); ctve = new (DLX_column); //column corresponds to characteristic vector of LS or smth of that kind ctve->Column = columns[2 * dimension + SQ[i][j]]; ctve->Column->size++; ctve->Down = columns[2 * dimension + SQ[i][j]]; ctve->Up = columns[2 * dimension + SQ[i][j]]->Up; ctve->Up->Down = ctve; ctve->Down->Up = ctve; ctve->row_id = i*dimension + j; // ctve->column_number = k; ctve->size = -10; elements.push_back(ctve); tvrow.push_back(ctve); if (i == j) { ctve = new (DLX_column); ctve->Column = columns[3 * dimension]; ctve->Column->size++; ctve->Down = columns[3 * dimension]; ctve->Up = columns[3 * dimension]->Up; ctve->Up->Down = ctve; ctve->Down->Up = ctve; ctve->row_id = i*dimension + j; // ctve->column_number = k; ctve->size = -10; elements.push_back(ctve); tvrow.push_back(ctve); } if (i == (dimension - j - 1)) { ctve = new (DLX_column); ctve->Column = columns[3 * dimension + 1]; ctve->Column->size++; ctve->Down = columns[3 * dimension + 1]; ctve->Up = columns[3 * dimension + 1]->Up; ctve->Up->Down = ctve; ctve->Down->Up = ctve; ctve->row_id = i*dimension + j; // ctve->column_number = k; ctve->size = -10; elements.push_back(ctve); tvrow.push_back(ctve); } for (int j = 0; j < tvrow.size() - 1; j++) { tvrow[j]->Right = tvrow[j + 1]; tvrow[j]->Right->Left = tvrow[j]; } tvrow[tvrow.size() - 1]->Right = tvrow[0]; tvrow[0]->Left = tvrow[tvrow.size() - 1]; } } DLX_column *pr = &root; } void orth_mate_search::TVSET_TO_DLX_EXT(DLX_column &root, vector<vector<int>> & tvset, vector<DLX_column*> & columns, vector<vector<DLX_column*>> &rows) { int dimension = tvset[0].size(); root.Up = NULL; root.Down = NULL; root.Column = NULL; root.row_id = -1; root.size = -1; // root.column_number= -1; columns.clear(); rows.clear(); DLX_column * lastleft = &root; for (int i = 0; i < dimension* dimension; i++) { DLX_column *ct; ct = new (DLX_column); // ct->column_number = i; ct->Down = ct; ct->Up = ct; ct->size = 0; ct->row_id = 0; ct->Column = ct; ct->Left = lastleft; lastleft->Right = ct; lastleft = ct; columns.push_back(ct); } lastleft->Right = &root; root.Left = lastleft; for (int i = 0; i < tvset.size(); i++) { vector<int> curtv = tvset[i]; vector<DLX_column *> tvrow; for (int j = 0; j < curtv.size(); j++) { DLX_column *ctve; ctve = new (DLX_column); //column corresponds to characteristic vector of LS or smth of that kind int k = j*dimension + curtv[j]; ctve->Column = columns[k]; ctve->Column->size++; ctve->Down = columns[k]; ctve->Up = columns[k]->Up; ctve->Up->Down = ctve; ctve->Down->Up = ctve; ctve->row_id = i; // ctve->column_number = k; ctve->size = -10; tvrow.push_back(ctve); } for (int j = 0; j < tvrow.size() - 1; j++) { tvrow[j]->Right = tvrow[j + 1]; tvrow[j]->Right->Left = tvrow[j]; } tvrow[tvrow.size() - 1]->Right = tvrow[0]; tvrow[0]->Left = tvrow[tvrow.size() - 1]; rows.push_back(tvrow); } } vector<vector<int>> orth_mate_search::find_tv_dlx(int n, vector<vector<int>> &SQ) { DLX_column *root; root = new (DLX_column); vector<DLX_column*> elements; SQ_TO_DLX(*root, SQ, elements); vector<DLX_column*> ps; ps.clear(); vector<vector<int>> tvr; search(0, *root, ps, tvr); //cout << "Found " << tvr.size() << " transversals\n"; for (int i = 0; i < tvr.size(); i++) { sort(tvr[i].begin(), tvr[i].end()); for (int j = 0; j < tvr[i].size(); j++) { tvr[i][j] = tvr[i][j] % n; } //printvector(tvr[i]); //cout << endl; } for (auto i = 0; i < elements.size(); i++) { delete elements[i]; } elements.clear(); return tvr; } // Find all orthogonal mates for a given DLS void orth_mate_search::check_dlx_rc1(vector<vector<int>> SQ, vector<vector<vector<int>>> &ort_SQ_vec ) { vector<vector<int>> trm = find_tv_dlx(SQ.size(), SQ); DLX_column *root; root = new (DLX_column); vector<DLX_column*> elements; TVSET_TO_DLX(*root, trm, elements); vector<DLX_column*> ps; ps.clear(); vector<vector<int>> tvr; search(0, *root, ps, tvr); for (int i = 0; i < tvr.size(); i++) sort(tvr[i].begin(), tvr[i].end()); for (int i = 0; i < elements.size(); i++) delete elements[i]; if (tvr.size() == 0) return; //cout << "LS with orthogonal mates found \n"; /*out.open(filename, ios::app); for (int i = 0; i < SQ.size(); i++) { for (int j = 0; j < SQ[i].size(); j++) { out << SQ[i][j] << " "; } out << endl; } out << "Found " << tvr.size() << " sets of disjoint transversals" << endl; out << "(DLX_refresh)Total: " << trm.size() << " transversals" << endl;*/ ort_SQ_vec.resize(tvr.size()); vector<vector<int>> ort_SQ(SQ.size(), vector<int>(SQ.size())); for (int i = 0; i < tvr.size(); i++) { for (auto u = 0; u < SQ.size(); u++) for (auto v = 0; v < SQ.size(); v++) ort_SQ[v][trm[tvr[i][u]][v]] = u; ort_SQ_vec[i] = ort_SQ; } } void orth_mate_search::generate_permutations_masked_rc1(int n, vector<vector<int>> &perm, vector<vector<int>> mask_LS, bool diag) { vector<vector<int>> MTV(10, vector<int>(10)); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { MTV[i][j] = -1; } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (mask_LS[i][j] != -1) { MTV[mask_LS[i][j]][i] = j; } } } vector<vector<int>> pm10; generate_permutations(n, pm10, diag); vector<vector<int>> res; for (int i = 0; i < pm10.size(); i++) { for (int k = 0; k < MTV.size(); k++) { bool acc = true; for (int j = 0; j < pm10[i].size(); j++) { if ((pm10[i][j] != MTV[k][j]) && (MTV[k][j] != -1)) { acc = false; break; } } if (acc == true) { res.push_back(pm10[i]); } } } perm = res; } bool orth_mate_search::isdiagls(int n, vector<vector<int>> &SQ) { bool b = true; for (auto i = 0; i < n; i++) { vector<int> r(n); //checking rows for (auto j = 0; j < n; j++) { r[SQ[i][j]]++; if (r[SQ[i][j]]>1) { b = false; return false; } } //checking columns vector<int> c(n); for (auto j = 0; j < n; j++) { c[SQ[j][i]]++; if (c[SQ[j][i]]>1) { b = false; return false; } } } vector<int> md(n); vector<int> ad(n); //checking diags; for (auto j = 0; j < n; j++) { md[SQ[j][j]]++; ad[SQ[j][n - j - 1]]++; if ((md[SQ[j][j]]>1) || (ad[SQ[j][n - j - 1]]>1)) { b = false; return false; } } return b; } void orth_mate_search::Generate_DLS_masked_DLXrefresh( int n, bool diag, unsigned long long limit, vector<vector<int>> mask, vector<vector<vector<int>>> &squares_vec) { vector<vector<int>> perm_diag; generate_permutations_masked_rc1(n, perm_diag, mask, diag); sort(perm_diag.begin(), perm_diag.end()); DLX_column *root; root = new (DLX_column); vector<DLX_column*> elements; TVSET_TO_DLX(*root, perm_diag, elements); vector<DLX_column*> ps; ps.clear(); vector<vector<int>> tvr; bool cont = true; double t1 = cpuTime(); unsigned long long count = 0; bool count_only = false; search_limited(0, *root, ps, tvr, cont, limit, count_only, count); double t2 = cpuTime(); //cout << tvr.size() << " squares generated in " << t2 - t1 << " seconds" << endl; double sc_t1 = cpuTime(); vector<vector<vector<int>>> SQUARES(tvr.size(), vector<vector<int>>(n, vector<int>(n))); construct_squares_from_tv_set(perm_diag, tvr, SQUARES); squares_vec = SQUARES; /* vector<vector<vector<int>>> ort_SQ_vec; double OLDDLX_check0_rc1 = cpuTime(); for (int i = 0; i < SQUARES.size(); i++) { check_dlx_rc1(SQUARES[i], ort_SQ_vec); } double OLDDLX_check1_rc1 = cpuTime(); cout << "checking squares with DLX_refresh algorithm finished\n"; //checking squares with new DLX implementation //check_dlx_rc1 cout << "RESULTS\n"; cout << "Checking all SQUARES using DLX refresh algorithm took " << OLDDLX_check1_rc1 - OLDDLX_check0_rc1 << " seconds\n"; //cout << "Checking all squares took " << sc_check_t2 - sc_check_t1 << " seconds,\n"; //check_squares_DLX(SQUARES, true, logname);*/ } void orth_mate_search::print_sq(vector<vector<int>> &SQ) { cout << endl; for (int i = 0; i < SQ.size(); i++) { for (int j = 0; j < SQ[i].size(); j++) { cout << SQ[i][j] << " "; } cout << endl; } } vector<vector<int>> orth_mate_search::compute_masked_LS(vector<vector<int>> &LS, vector<vector<int>> &MASK) { vector<vector<int>> res(LS); if (MASK.size() != LS.size()) { std::cout << "LS and MASK sizes dont match \n"; } for (int i = 0; i < MASK.size(); i++) { if (MASK[i].size() != LS[i].size()) { std::cout << "LS and MASK sizes dont match @ " << i << "\n"; } for (int j = 0; j < MASK[i].size(); j++) { if (MASK[i][j] == -1) { res[i][j] = -1; } } } return res; } vector<vector<int>> orth_mate_search::compute_masked_LS(vector<vector<int>> &LS, int k) { vector<vector<int>> res(LS); int n = LS.size(); for (int i = k; i < n*n; i++) { res[i / n][i%n] = -1; } return res; }
true
f552be53afa8ce613039346926c1bf38d95064bd
C++
TysonGomes/C---Facu
/C++ facu/Salario.cpp
UTF-8
253
2.53125
3
[]
no_license
#include<stdio.h> #include<conio.h> float sl(float s1 ){ //float s1; s1=s1-(s1*12/100); return s1; } int main() { float s1; printf ("digite seu salario: "); scanf ("%f",&s1); s1=sl(s1); printf("seu salario liquido e %.2f",s1); getch(); }
true
2959271222b1ce1b27f879a3fd287422edc6b16e
C++
bangiao/c_plus_plus_11
/保持与C99兼容/保持与C99兼容/[2]_Pragma.cpp
GB18030
380
2.671875
3
[]
no_license
#include <iostream> using namespace std; //1. #pragma _Pragma Чһ //2. _Pragma Ǻ궨, Ǻ sizeof һIJ //3. ʹ÷: _Pragma ("once"); // Ч #pragma once һ //4. ŵ: һЩ궨 /* #define PRAGMA(x) _Pragma(#x) */ // int main(void) // { // // // system("pause"); // return 0; // }
true
791f4393e1b62747c981257939f58d7a89ee408a
C++
kalderman/demo
/app/include/openglwindow.hpp
UTF-8
1,946
2.625
3
[ "MIT" ]
permissive
#ifndef __OPENGLWINDOW_H__ #define __OPENGLWINDOW_H__ #include <optional> #include <variant> #define GLFW_INCLUDE_NONE #include <GLFW/glfw3.h> #include <glbinding/gl/gl.h> #include <glbinding/glbinding.h> using namespace std; using namespace gl; struct InitializationFailed {}; struct WindowOrOpenGlContextCreationFailed {}; template<typename OnInput, typename OnRender> class OpenGlWindow { private: const OnInput& onInput; const OnRender& onRender; public: OpenGlWindow( const OnInput& onInput, const OnRender& onRender) : onInput(onInput), onRender(onRender) { } optional<variant<InitializationFailed, WindowOrOpenGlContextCreationFailed>> Show(){ if (!glfwInit()){ return InitializationFailed(); } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); auto* window = glfwCreateWindow(640, 480, "Turtle Graphics", NULL, NULL); if (!window){ return WindowOrOpenGlContextCreationFailed(); } glfwSetWindowUserPointer(window, (void *)this); glfwSetKeyCallback(window, key_callback); glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback( window, [](GLFWwindow* _, int width, int height){ glViewport(0, 0, width, height); }); glbinding::initialize(glfwGetProcAddress); while (!glfwWindowShouldClose(window)) { onRender(); glfwSwapBuffers(window); glfwPollEvents(); } glfwDestroyWindow(window); glfwTerminate(); return {}; } private: static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods){ auto that = (OpenGlWindow *)glfwGetWindowUserPointer(window); that->onInput(key, action); } }; #endif // __OPENGLWINDOW_H__
true
004f2ac73291bc31d834778a279055367618db65
C++
simeongbolo/prog-contests
/acm/solved/2005/answer.cpp
UTF-8
921
3.0625
3
[]
no_license
#include <iostream> #include <stdlib.h> #include <algorithm> using namespace std; int main(void) { int matrix[5][5]; for (int i = 0; i < 5; i++) for (int j = 0; j < 5; j++) cin >> matrix[i][j]; int p1 = matrix[0][1] + matrix[1][2] + matrix[2][3] + matrix[3][4]; int p2 = matrix[0][2] + matrix[2][1] + matrix[1][3] + matrix[3][4]; int p3 = matrix[0][2] + matrix[2][3] + matrix[3][1] + matrix[1][4]; int p4 = matrix[0][3] + matrix[3][2] + matrix[2][1] + matrix[1][4]; int m = min(min(min(p1, p2), p3), p4); if (p1 == m) { cout << p1 << endl; cout << "1 2 3 4 5" << endl; } else if (p2 == m) { cout << p2 << endl; cout << "1 3 2 4 5" << endl; } else if (p3 == m) { cout << p3 << endl; cout << "1 3 4 2 5" << endl; } else if (p4 == m) { cout << p4 << endl; cout << "1 4 3 2 5" << endl; } }
true
757038129990abe74417587b3eef15733dce04d0
C++
astanin/notch
/test/test_notch_pre.cpp
UTF-8
4,475
2.71875
3
[ "MIT" ]
permissive
#include "catch.hpp" #define NOTCH_ONLY_DECLARATIONS #include "notch.hpp" #include "notch_io.hpp" #include "notch_pre.hpp" using namespace std; using namespace notch; TEST_CASE("OneHotEncoder single-column encoding-decoding", "[pre]") { Dataset five {{5}, {1}, {4}, {3}, {2}}; // labels in range 1..5 OneHotEncoder enc {five}; Dataset fiveEncoded = enc.apply(five); // check expected encoding: Dataset expected {{0, 0, 0, 0, 1}, {1, 0, 0, 0, 0}, {0, 0, 0, 1, 0}, {0, 0, 1, 0, 0}, {0, 1, 0, 0, 0}}; for (size_t i = 0; i < fiveEncoded.size(); ++i) { CHECK(fiveEncoded[i].size() == 5u); float sum = 0; for(size_t j = 0; j < fiveEncoded[i].size(); ++j) { sum += fiveEncoded[i][j]; CHECK(fiveEncoded[i][j] == expected[i][j]); } CHECK(sum == 1.0); } // check decoding for (size_t i = 0; i < fiveEncoded.size(); ++i) { auto x = enc.unapply(fiveEncoded[i]); CHECK(x.size() == five[i].size()); for (size_t j = 0; j < x.size(); ++j) { CHECK(x[j] == five[i][j]); } } } TEST_CASE("OneHotEncoder two-column encoding-decoding", "[pre]") { Dataset twocols {{1,10},{3,20},{2,20},{4,30}}; // 4 and 3 distinct values OneHotEncoder enc(twocols); Dataset encoded = enc.apply(twocols); // check expected encoding: Dataset expected {{1, 0, 0, 0, 1, 0, 0}, {0, 0, 1, 0, 0, 1, 0}, {0, 1, 0, 0, 0, 1, 0}, {0, 0, 0, 1, 0, 0, 1}}; size_t col1_code_size = 4; size_t col2_code_size = 3; for (size_t i = 0; i < encoded.size(); ++i) { CHECK(encoded[i].size() == (col1_code_size + col2_code_size)); float sum = 0; for(size_t j = 0; j < encoded[i].size(); ++j) { sum += encoded[i][j]; CHECK(encoded[i][j] == expected[i][j]); } CHECK(sum == 2.0); // 2 columns } // check decoding for (size_t i = 0; i < encoded.size(); ++i) { auto x = enc.unapply(encoded[i]); CHECK(x.size() == twocols[i].size()); for (size_t j = 0; j < x.size(); ++j) { CHECK(x[j] == twocols[i][j]); } } } TEST_CASE("OneHotEncoder column selection (negative index)", "[pre]") { Dataset twocols {{1,10},{3,20},{2,20},{4,30}}; // 4 and 3 distinct values OneHotEncoder enc(twocols, {-2}); // the first (the last but one) column Dataset encoded = enc.apply(twocols); // check expected encoding: Dataset expected {{1, 0, 0, 0, 10}, {0, 0, 1, 0, 20}, {0, 1, 0, 0, 20}, {0, 0, 0, 1, 30}}; size_t col1_code_size = 4; for (size_t i = 0; i < encoded.size(); ++i) { CHECK(encoded[i].size() == col1_code_size + 1); float sum = 0; for(size_t j = 0; j < encoded[i].size(); ++j) { CHECK(encoded[i][j] == expected[i][j]); if (j < col1_code_size) { sum += encoded[i][j]; } } CHECK(sum == 1.0); // 1 column } // check decoding for (size_t i = 0; i < encoded.size(); ++i) { auto x = enc.unapply(encoded[i]); CHECK(x.size() == twocols[i].size()); for (size_t j = 0; j < x.size(); ++j) { CHECK(x[j] == twocols[i][j]); } } } TEST_CASE("SquareAugmented apply and unapply", "[pre]") { Dataset x1 {{1, 2}, {3, 4}}; Dataset expected {{1, 2, 1, 4}, {3, 4, 9, 16}}; Dataset x2 = SquareAugmented().apply(x1); // check apply CHECK(x2.size() == expected.size()); for (size_t i = 0; i < x2.size(); ++i) { CHECK(x2[i].size() == expected[i].size()); for(size_t j = 0; j < x2[i].size(); ++j) { CHECK(x2[i][j] == expected[i][j]); } } // check unapply for (size_t i = 0; i < x2.size(); ++i) { auto x = SquareAugmented().unapply(x2[i]); CHECK(x.size() == x1[i].size()); for (size_t j = 0; j < x.size(); ++j) { CHECK(x[j] == x1[i][j]); } } } TEST_CASE("Dataset inputDim() changes after transform", "[pre]") { LabeledDataset d {{{1, 2}, {1, 2, 3}}}; // 2 in, 3 out CHECK(d.inputDim() == 2u); CHECK(d.outputDim() == 3u); SquareAugmented square; d.apply(square); CHECK(d.inputDim() == 2*2u); CHECK(d.outputDim() == 3u); }
true
91e4c2a401e6c19cf431d48b088d5a659bad9a84
C++
Aman-mangu/IntermediateCpp
/assignmentsFolder/CodingTasksAssignment/Task3_Points/collection.h
UTF-8
620
2.609375
3
[]
no_license
#ifndef __COLLECTION_H_ #define __COLLECTION_H_ #include "points.h" #include <list> #include <vector> class collection { private: std::list<Points> points; public: void addPoint(int x,int y); void addPoint(const Points& ref); void DisplayAll(); int CountPointsInQuadrant(int quadrant); int CountPointsOnCircleBoundary(int radius); int CountPointsInCircle(int radius); std::list<Points> FindPointsInQuadrant(int quadrant); std::list<Points> FindPointsOnCircleBoundary(int radius); std::list<Points> FindPointsInCircle(int radius); }; #endif // #ifndef __COLLECTION_H_
true
fd30c8a20337f761cccb5fac1cfaaa48c0383ec5
C++
dovanduy/cppTopics
/Loops/8-bitCodeTable.cpp
UTF-8
130
2.515625
3
[ "MIT" ]
permissive
// To print 8-bit code table #include <cstdio> int main() { int i=0; for(i=0;i<256;i++) printf("%d %c\n",i,i) ; return 0; }
true
7b569837cc468f8ac79761e8d00f0a90dd76d4f0
C++
vimday/PlayWithLeetCode
/每日一题 6-8 月/Day0824_repeated-substring-pattern.cpp
UTF-8
631
2.5625
3
[]
no_license
/* * @Author :vimday * @Desc : * @Url : * @File Name :Day0824_repeated-substring-pattern.cpp * @Created Time:2020-08-24 23:08:35 * @E-mail :lwftx@outlook.com * @GitHub :https://github.com/vimday */ #include <bits/stdc++.h> using namespace std; void debug() { #ifdef LOCAL freopen("E:\\Cpp\\in.txt", "r", stdin); freopen("E:\\Cpp\\out.txt", "w", stdout); #endif } class Solution { public: bool repeatedSubstringPattern(string s) { string str = s + s; str = str.substr(1, str.size() - 2); if (str.find(s) == -1) return false; return true; } };
true
1ba36f2737d0c84064dd944f0b771bd64b864755
C++
sorphin/DC25
/firmware/src/RgbAnimations.h
UTF-8
1,920
2.640625
3
[]
no_license
#ifndef __RGB_ANI_H #define __RGB_ANI_H #include <stdint.h> #include <Arduino.h> #define NUM_RGB (8) // Number of WS281X we have connected #define NUM_BYTES (NUM_RGB*3) // Number of LEDs (3 per each WS281X) #define DIGITAL_PIN (PD2) // Digital port number #define PORT (PORTD) // Digital pin's port #define PORT_PIN (PORTD2) // Digital pin's bit position #define NUM_BITS (8) // Constant value: bits per byte #define COLOR(r, g, b) (((uint32_t)(r) << 16) | ((uint32_t)(g) << 8) | (b)) #define COLOR_R(r) ((uint8_t)(0xff0000 & (r)) >> 16) #define COLOR_G(g) ((uint8_t)(0x00ff00 & (g)) >> 8) #define COLOR_B(b) ((uint8_t)(0x0000ff & (b))) class RgbAnimations { private: long time; uint8_t delay; unsigned int currentAnimation; unsigned int currentPixel; unsigned int ledCount; uint8_t colors[16][3] = { {8, 0, 0}, {0, 8, 0}, {0, 0, 8}, {8, 8, 0}, {8, 0, 8}, {0, 8, 8}, {8, 0, 3}, {8, 3, 0}, {3, 8, 0}, {0, 8, 3}, {3, 0, 8}, {0, 3, 8}, {8, 8, 3}, {8, 3, 8}, {3, 8, 8}, {8, 8, 8} }; uint8_t black[3] = { 0, 0, 0 }; uint8_t currentColor[3]; uint8_t paintingColor[3]; uint8_t backgroundColor[3]; bool blankPixels; unsigned int counter; bool sleep; uint8_t* rgb_arr; uint32_t t_f; void setColorRGB(uint8_t idx, uint8_t *color); void setColorRGBInt(uint8_t idx, uint32_t color); uint32_t readColorRGBInt(uint8_t idx); void render(); void selectColor(); uint32_t wheel(byte WheelPos); void clear(); bool race(); bool circle(); bool circleColor(); bool bounceCircle(); bool theaterChase(); bool theaterChaseRainbow(); bool randomFlash(); bool randomFlashColor(); bool randomFlashMultiple(); public: RgbAnimations(long now); void selectAnimation(); bool run(long now, bool outsideSleep, bool wake); }; #endif
true
1fece33212e2fa8e565cdb4f26c0ee5d8847e200
C++
achieverForever/Raytracer
/Util.cpp
UTF-8
2,117
2.96875
3
[]
no_license
#include "Util.h" #include "Variables.h" Light::Light() : type(POINT), position(0.0f), color(0.0f), attenuation(1.0f, 0.0f, 0.0f) { } Light::Light(LightType t, float x, float y, float z, float r, float g, float b, float konst/* =1.0f */, float linear/* =0.0f */, float quad/* =0.0f */) { type = t; position = vec3(x, y, z); if(t == DIRECTIONAL) TransformDirection(position, currMatrix); else TransformPosition(position, currMatrix); color = Color(r, g, b); attenuation = vec3(konst, linear, quad); if(type == DIRECTIONAL) lightDir = glm::normalize(position); } Light::Light(LightType t, const vec3 &pos, const Color &col, const vec3 &atten/* =vec3 */) { type = t; position = pos; color = col; attenuation = atten; if(type == DIRECTIONAL) lightDir = glm::normalize(position); } vec3 & Light::GetLightDirection(const vec3 &target) { if(type == DIRECTIONAL) { return lightDir; } else { lightDir = glm::normalize(position - target); return lightDir; } } void RightMultiply(const mat4 & mat, stack<mat4> & matrixStack) { mat4 & T = matrixStack.top(); T = T * mat; } void LoadMatrix(const mat4 & mat, stack<mat4> & matrixStack) { mat4 & T = matrixStack.top(); T = mat; } vec3 & TransformDirection(vec3 & direction, const mat4 & matrix) { vec4 tmpDir(direction, 0.0f); direction = vec3(matrix * tmpDir); return direction; } vec3 & TransformNormal(vec3 & normal, const mat4 & matrix) { vec4 tmpN(normal, 0.0f); normal = glm::normalize(vec3(glm::transpose(matrix) * tmpN)); return normal; } vec3 & TransformPosition(vec3 & position, const mat4 & matrix) { vec4 tmpPos(position, 1.0f); tmpPos = matrix * tmpPos; position = vec3(tmpPos / tmpPos.w); //position = vec3(tmpPos); return position; } void TransformRay(Ray &ray, const mat4 &matrix) { TransformPosition(ray.origin, matrix); TransformDirection(ray.direction, matrix); ray.direction = glm::normalize(ray.direction); } void Clamp01(Color &c) { c = glm::clamp(c, Color(0.0f), Color(1.0f)); } ostream & operator<< (ostream &stream, const vec3 &v) { return stream << v.x << " " << v.y << " " << v.z << " "; }
true
4a4002f0e8387d002ee2d47ec38bd27f2e876a2e
C++
jbriede/Compiler
/source/Access.h
UTF-8
557
2.671875
3
[]
no_license
#ifndef Access_h #define Access_h #include <iostream> #include <stdio.h> #include <string> #include <string.h> #include "Operation.h" using namespace std; class Access : public Operation { public: Access(Id* array, Expression* index, Type* type, int line): Operation(new Word("[]", ARRAY, line), type, line) { _array = array; _index = index; } Id* get_array() { return _array; } Expression* get_index() { return _index; } private: Expression* _index; Id* _array; }; #endif
true
7b0005645368d3fceca2561ec8595f0f77400524
C++
atu-guda/stm32oxc
/inc/oxc_outstr.h
UTF-8
1,184
2.640625
3
[]
no_license
#ifndef _OXC_OUTSTR_H #define _OXC_OUTSTR_H #include <oxc_io.h> //* Class to use OutStream feature for string buffer //* Used external buffer, no locks - only for simple local usage class OutStr: public DevOut { public: OutStr( char *ext_buf, unsigned buf_sz ) : buf( ext_buf ), bsz( buf_sz ) { buf[0] = '\0'; }; OutStr( const OutStr& rhs ) = delete; OutStr& operator=( const OutStr &rhs ) = delete; virtual void reset_out() override; virtual int write( const char *s, int l ) override; virtual int puts( const char *s ) override; virtual int putc( char b ) override; virtual void flush_out() override; const char* c_str() const { return buf; } unsigned size() const { return sz; } bool empty() const { return sz == 0; } virtual const char* getBuf() const override { return buf; } char operator[]( unsigned i ) const { return (i<bsz) ? buf[i] : '\0'; } char& operator[]( unsigned i ) { return (i<bsz) ? buf[i] : fake; } protected: char *buf; unsigned bsz; unsigned sz = 0; char fake = '\0'; }; #define OSTR(x,sz) char x ## _buf[sz]; OutStr x ## _outstr( x ## _buf, sz ); OutStream x( & x ## _outstr ); #endif
true
b7782aee937387c081ef036fb401a03481d29fae
C++
taichuai/cpp_practice
/code/函数的分文件编写.cpp
UTF-8
740
3.359375
3
[ "Apache-2.0" ]
permissive
# include<iostream> # include<string> # include "swap.h" using namespace std; //函数的分文件编写 //实现两个数字的交换 // void swap(int a, int b); // void swap(int a, int b) // { // int temp = a; // a = b; // b = temp; // cout << "a= " << a << endl; // cout << "b= " << b << endl; // } // //1、创建 .h后缀名的头文件 // //2、创建 .cpp 后缀名的源文件 // //3、在头文件中写函数的声明 // //4、源文件中先函数的声明 int main() { //函数的调用 int a = 10; int b = 20; swap(a, b); //a和b称为 实际参数, 简称实参 //函数定义中的参数称为形参 // swap(a, b); // cout << "求和: " << c << endl; }
true
0c811d11de66b933d6a528de170713e420d7dba2
C++
OminousBlackCat/leetcode_algorithm_prac
/leetcode_32_longestParentheses_stack/leetcode_32_longestParentheses_stack/leetcode_32_longestParentheses_stack.cpp
UTF-8
1,779
3.171875
3
[]
no_license
// leetcode_32_longestParentheses_stack.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include <iostream> #include <vector> #include <string> #include <algorithm> using namespace std; int longestValidPatentheses(string s) { vector<int> stack; vector<int> produce; int answer = 0; int previous_success = 0; for (int i = 0; i < s.size(); i++) { if (s[i] == '(') { stack.push_back(i); } else{ if (stack.size() <= 0) { previous_success = i + 1; } else { produce.push_back(stack[stack.size() - 1]); produce.push_back(i); stack.pop_back(); if (stack.size() <= 0) { answer = max(answer, i - previous_success + 1); } else { answer = max(answer, i - stack[stack.size() - 1]); } } } } return answer; } int main() { std::cout << longestValidPatentheses(")(())))(())())"); } // 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单 // 调试程序: F5 或调试 >“开始调试”菜单 // 入门使用技巧: // 1. 使用解决方案资源管理器窗口添加/管理文件 // 2. 使用团队资源管理器窗口连接到源代码管理 // 3. 使用输出窗口查看生成输出和其他消息 // 4. 使用错误列表窗口查看错误 // 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目 // 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
true
86cbff5b10160fc5affa08037ef6371ede81c128
C++
AdamGray31/Programming
/Stage 3/CSC3223 - Graphics for Games/OpenGL Rasteriser/OpenGLGraphics/Renderer.h
UTF-8
1,220
2.625
3
[]
no_license
#pragma once #include "../nclgl/OGLRenderer.h" #include "RenderObject.h" #include <vector> using std::vector; struct Light { Vector3 position; float radius; Vector3 colour; }; class Renderer : public OGLRenderer { public: float time; GLuint brickTex; GLuint brokenBrickTex; GLuint heightMap; float tessLevelInner; float tessLevelOuter; Renderer(Window &parent); ~Renderer(void); virtual void RenderScene(); virtual void Render(const RenderObject &o); virtual void UpdateScene(float msec); void enableCulling(); void disableCulling(); void AddRenderObject(RenderObject &r) { renderObjects.push_back(&r); } void SetShaderLight(Vector3 position, Vector3 colour, float radius) { currentLight.position = position; currentLight.colour = colour; currentLight.radius = radius; } protected: vector<RenderObject*> renderObjects; Light currentLight; void ApplyShaderLight(GLuint program) { glUniform3fv(glGetUniformLocation(program, "lightPos"), 1, (float *)&(currentLight.position)); glUniform3fv(glGetUniformLocation(program, "lightColour"), 1, (float *)&(currentLight.colour)); glUniform1f(glGetUniformLocation(program, "lightRadius"), currentLight.radius); } };
true
7231c2abba31807d8bc4f4a895dc04113a88184b
C++
wxywxywxy921/wxywxywxy921
/8.data_structure/implement_stack/implement_stack.h
UTF-8
1,180
3.921875
4
[]
no_license
struct Node { int val; Node *next; Node *prev; }; class Stack { public: Node *curr; Stack() { curr = NULL; } // Push a new item into the stack void push(int x) { // Write your code here if(curr == NULL) { curr = new Node; curr->val = x; curr->prev = NULL; curr->next = NULL; } else { curr->next = new Node; curr->next->next = NULL; curr->next->val = x; curr->next->prev = curr; curr = curr->next; } } // Pop the top of the stack void pop() { // Write your code here if(curr != NULL) { Node *temp = curr; curr = curr->prev; if(curr != NULL) // !!!!!!!!!!!for the case the curr is NULL after pop { curr->next = NULL; } delete[] temp; } } // Return the top of the stack int top() { // Write your code here if(curr != NULL) { return curr->val; } else { return 0; } } // Check the stack is empty or not. bool isEmpty() { // Write your code here return curr == NULL; } };
true
4b214e78595bfb3cbab509dd10b95c6c4d81d63b
C++
watsonix/brainbotcode
/arduino/hrv_low_detect/hrv_low_detect/hrv_low_detect.ino
UTF-8
4,816
2.546875
3
[]
no_license
/* motor on every heartbeat rohan dixit 2014 ECG // baseline is the moving average of the signal - the middle of the waveform // the idea here is to keep track of a high frequency signal, HFoutput and a // low frequency signal, LFoutput // The HF signal is shifted downward slightly (heartbeats are negative peaks) // The high freq signal has some hysterisis added. When the HF signal is less than the // shifted LF signal, we have found a heartbeat. */ int motor_dur_ms = 5; int max_bpm = 120; int min_bpm = 30; int threshold = 55; //70 BPM above which the feedback will activate. set to zero to be on constantly. int counter = 0; int binOut; // 1 or 0 depending on state of heartbeat int BPM; int total; // all three LED reads added together unsigned long time = millis(); unsigned long looptime, motortimeon; int signalSize; // the heartbeat signal minus the offset int max = 0; int min = 1000; int intervals[5] = {0, 0, 0, 0, 0}; const int INTERVAL_LEN = 5; void setup() { // initialize the serial communication: Serial.begin(115200); pinMode(10, OUTPUT); digitalWrite(10, HIGH); pinMode(A1, OUTPUT); pinMode(A2, OUTPUT); digitalWrite(A1, LOW); digitalWrite(A2, LOW); } void loop() { static int valley = 0, peak = 0, smoothPeak, smoothValley, binOut, lastBinOut, BPM; static unsigned long lastTotal, lastMillis, valleyTime = millis(), lastValleyTime = millis(), peakTime = millis(), lastPeakTime = millis(), lastBeat, beat; static float baseline, HFoutput, HFoutput2, shiftedOutput, LFoutput, hysterisis; unsigned long start; int i = 0; int signalSize; start = millis(); //duration in milliseconds on motor unsigned long diff = millis() - motortimeon; if ( diff < motor_dur_ms) { digitalWrite(A1, HIGH); digitalWrite(A2, HIGH); //Serial.println('on'); } else { digitalWrite(A1, LOW); digitalWrite(A2, LOW); } int total = analogRead(A0); // Serial.println(total); baseline = smooth(total, 0.99, baseline); // HFoutput = smooth((total - baseline), 0.2, HFoutput); // recycling output - filter to slow down response HFoutput2 = HFoutput + hysterisis; LFoutput = smooth((total - baseline), 0.95, LFoutput); // heartbeat signal is inverted - we are looking for negative peaks shiftedOutput = LFoutput - (signalSize * .05); // We need to be able to keep track of peaks and valleys to scale the output for // user convenience. Hysterisis is also scaled. if (HFoutput > peak) peak = HFoutput; if (peak > 1500) peak = 1500; if (millis() - lastPeakTime > 1800) { // reset peak detector slower than lowest human HB smoothPeak = smooth((float)peak, 0.6, (float)smoothPeak); // smooth peaks peak = 0; lastPeakTime = millis(); } if (HFoutput < valley) valley = HFoutput; if (valley < -1500) valley = -1500; if (millis() - lastValleyTime > 1800) { // reset valleys detector slower than lowest human HB smoothValley = smooth((float)valley, 0.6, (float)smoothValley); // smooth valleys valley = 0; lastValleyTime = millis(); } signalSize = smoothPeak - smoothValley; // this the size of the smoothed HF heartbeat signal if (HFoutput2 < shiftedOutput) { lastBinOut = binOut; binOut = 1; // Serial.println("\ty"); hysterisis = - constrain((signalSize / 15), 35, 120) ; // you might want to divide by smaller number // if you start getting "double bumps" } else { // Serial.println("\tn"); lastBinOut = binOut; binOut = 0; hysterisis = constrain((signalSize / 15), 35, 120); // ditto above } //IF HEARTBEAT if (lastBinOut == 0 && binOut == 1) { lastBeat = beat; beat = millis(); int interval = beat - lastBeat; intervals[counter++%INTERVAL_LEN] = interval; for (int i = INTERVAL_LEN - 1; i >= 0; i--) Serial.print((String)intervals[i] + " "); Serial.println(); Serial.println("=="); Serial.println(); delay(50); BPM = 60000 / interval; if (BPM > min_bpm && BPM < max_bpm && BPM > threshold) { // Serial.println(BPM); motortimeon = millis(); } } // wait for Analog-Digital converter stabilization delay(2); } float scale_num(float input, float min_val, float max_val) { //scales an input, say heartbeat BPM, to 0-255 for analogWrite, returns scaled value return input * 255.0 / (max_val - min_val); } // simple smoothing function for heartbeat detection and processing float smooth(float data, float filterVal, float smoothedVal) { if (filterVal > 1) { // check to make sure param's are within range filterVal = .99; } else if (filterVal <= 0.0) { filterVal = 0.01; } smoothedVal = (data * (1.0 - filterVal)) + (smoothedVal * filterVal); return smoothedVal; }
true
d51dee8a5bdd0f49907aa9ae38cea6712a815f6f
C++
joshru/Maze_Generator_CPP_Port
/main.cpp
UTF-8
378
2.6875
3
[]
no_license
#include <iostream> #include "Maze.h" //struct Cell { // //}; int main() { using namespace std; // Maze m(5, 5, false); // m.display(); // cout << "Hello, World!" << endl; // Maze maze = Maze(5, 5, true); // maze.display(); Maze maze = Maze(10, 10, true); maze.display(); // maze = Maze(10, 10, false); // maze.display(); return 0; }
true
8c8ec62bc0301318affd3a0acc1f746b52e84ce8
C++
ravikr126/Data-Structures-And-Algorithms-Hacktoberfest18
/cpp/algorithms/substring_occurences.cpp
UTF-8
2,002
3.4375
3
[]
no_license
/*Найдите все вхождения шаблона в строку. Длина шаблона – p, длина строки ­– n. Время O(n + p), доп. память – O(p). -> Вариант 1. С помощью префикс-функции; Вариант 2. С помощью z-функции. Формат входного файла Шаблон, символ перевода строки, строка. Формат выходного файла Позиции вхождения шаблона в строке. Время: 100мс, память 3Mb.*/ #include <iostream> #include <string> #include <vector> using std::cout; using std::cin; using std::string; using std::vector; // Ищет префикс-функцию vector<int> find_prefix_func( const string& str ) { size_t len = str.length(); vector<int> prefix_func( len ); for (size_t i = 1; i < len; i++) { size_t j = prefix_func[i - 1]; while (j > 0 && str[i] != str[j]) { j = prefix_func[j - 1]; } if (str[i] == str[j]) ++j; prefix_func[i] = j; } return prefix_func; } inline int move_temp_str( const string& pattern, const vector<int>& prefix_func, const char symb, int pref ) { // pref - Предыдущее значение префикс-функции while (pref > 0 && symb != pattern[pref]) { pref = prefix_func[pref - 1]; } if (symb == pattern[pref]) ++pref; int prefix_func_val = pref; return prefix_func_val; } int main() { std::ios::sync_with_stdio( false ); string pattern; string str; cin >> pattern >> str; size_t p = pattern.length(); size_t s = str.length(); pattern = pattern + '#'; vector<int> prefix_func = find_prefix_func( pattern ); int prefix_func_val = 0; // значение от # равно 0 int pos = 0; for (size_t pos = 0; pos < s; pos++) { char symb = str[pos]; prefix_func_val = move_temp_str( pattern, prefix_func, symb, prefix_func_val ); if (prefix_func_val == p) { cout << pos - p + 1 << '\n'; } } return 0; }
true
97b068bf4e7f0dbeb33775a0e14f3299e6b8936b
C++
ultramagnus007/Matrix
/Tree/OddEvenDiff.cpp
UTF-8
648
3.4375
3
[]
no_license
#include <iostream> #include "BST.h" using namespace std; void OddEvenSum(node *ptr, int &OS, int &ES, int level) { if(ptr == NULL) return; if(level%2==0) ES+=ptr->key; else OS+=ptr->key; OddEvenSum(ptr->left, OS, ES, level+1); OddEvenSum(ptr->right, OS, ES, level+1); } int main() { BST bst; bst.insert(84);bst.insert(75);bst.insert(49);bst.insert(15);bst.insert(92); bst.insert(59);bst.insert(27);bst.insert(38);bst.insert(55);bst.insert(62); cout<<"Difference between odd level and even level is \n"; int OS = 0; int ES = 0; int level = 1; OddEvenSum(bst.root, OS, ES, level); cout<<OS-ES<<endl; return 0; }
true
9fb29a11d0a3cf117fa01d3db6bade95a02265ca
C++
acton393/incubator-weex
/weex_core/Source/include/wtf/DeprecatedOptional.h
UTF-8
1,468
2.609375
3
[ "Apache-2.0", "MIT", "BSD-3-Clause" ]
permissive
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ // This file contains a deprecated version of WTF::Optional which a released // version of Safari uses. Once Safari stops using this, we can remove this. // New code should use std::optional. #pragma once #include <type_traits> namespace WTF { template<typename T> class Optional { public: explicit operator bool() const { return m_isEngaged; } T& value() { return *asPtr(); } private: T* asPtr() { return reinterpret_cast<T*>(&m_value); } bool m_isEngaged; typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type m_value; }; template<typename T> using DeprecatedOptional = WTF::Optional<T>; } // namespace WTF
true
925b42875d34a0909cb8a18ff87125955b04a2c6
C++
strengthen/LeetCode
/C++/256.cpp
UTF-8
1,205
3.265625
3
[ "MIT" ]
permissive
__________________________________________________________________________________________________ class Solution { public: int minCost(vector<vector<int>>& costs) { if (costs.empty() || costs[0].empty()) return 0; vector<vector<int>> dp = costs; for (int i = 1; i < dp.size(); ++i) { for (int j = 0; j < 3; ++j) { dp[i][j] += min(dp[i - 1][(j + 1) % 3], dp[i - 1][(j + 2) % 3]); } } return min(min(dp.back()[0], dp.back()[1]), dp.back()[2]); } }; __________________________________________________________________________________________________ class Solution { public: int minCost(vector<vector<int>>& costs) { if (costs.empty() || costs[0].empty()) return 0; vector<vector<int>> dp = costs; for (int i = 1; i < dp.size(); ++i) { dp[i][0] += min(dp[i - 1][1], dp[i - 1][2]); dp[i][1] += min(dp[i - 1][0], dp[i - 1][2]); dp[i][2] += min(dp[i - 1][0], dp[i - 1][1]); } return min(min(dp.back()[0], dp.back()[1]), dp.back()[2]); } }; __________________________________________________________________________________________________
true
b2d92cac6b23fdeed73a3993b3c5f97ffadc12fb
C++
rishabkr/Competitive-Programming
/interviewbit_random/path_with_good_nodes.cpp
UTF-8
802
2.59375
3
[]
no_license
int result; int num; void dfs(int v, int count, vector<int> &A, vector<bool> vis, vector<vector<int>> &adj){ vis[v]=1; for(int child: adj[v]){ if(vis[child]==0){ if(A[child-1]) dfs(child, count+1, A, vis, adj); else dfs(child, count, A, vis, adj); } } if(adj[v].size()==1 && count<=num) result++; //is a leaf } int Solution::solve(vector<int> &A, vector<vector<int> > &B, int C) { int n=A.size(); result=0; num=C; vector<bool> vis(n+1, false); vector<vector<int>> adj(n+1); for(int i=0; i<n-1; i++){ adj[B[i][0]].push_back(B[i][1]); adj[B[i][1]].push_back(B[i][0]); } if(A[0]==1) dfs(1, 1, A, vis, adj); else dfs(1, 0, A, vis, adj); return result; }
true
3962b6db47b2a8e0abe3782bec1fc99c2e7caab4
C++
pazamelin/balanced-trees
/treelib/include/detail/splay.tpp
UTF-8
9,637
3.0625
3
[]
no_license
#pragma once #include <exception> #include <iostream> namespace tree { template <typename Key, typename Compare> splay<Key, Compare>::splay() = default; template <typename Key, typename Compare> void splay<Key, Compare>::clear_cache() const { cmp_cache.clear(); while (!path_cache.empty()) { path_cache.pop(); } } template <typename Key, typename Compare> splay<Key, Compare>::splay(const std::initializer_list<key_type>& data) { for (const auto& element : data) { this->insert(element); } } template <typename Key, typename Compare> splay<Key, Compare>::splay(std::initializer_list<key_type>&& data) { for (auto&& element : data) { this->insert(std::move(element)); } } template <typename Key, typename Compare> splay<Key, Compare>::splay(const splay <key_type, key_compare>& other) { for (const auto& element : other) { this->insert(element); } } template <typename Key, typename Compare> splay<Key, Compare>::splay(splay <key_type, key_compare>&& other) noexcept { std::swap(this->head, other.head); std::swap(this->m_size, other.m_size); } template <typename Key, typename Compare> splay<Key, Compare>::~splay() { this->clear(); } template <typename Key, typename Compare> typename splay<Key, Compare>::iterator splay<Key, Compare>::begin() { return iterator(head); } template <typename Key, typename Compare> typename splay<Key, Compare>::const_iterator splay<Key, Compare>::begin() const { return const_iterator(head); } template <typename Key, typename Compare> typename splay<Key, Compare>::const_iterator splay<Key, Compare>::cbegin() const { return const_iterator(head); } template <typename Key, typename Compare> typename splay<Key, Compare>::iterator splay<Key, Compare>::end() { return iterator(head, std::make_optional<node_ptr>(nullptr)); } template <typename Key, typename Compare> typename splay<Key, Compare>::const_iterator splay<Key, Compare>::end() const { return const_iterator(head, std::make_optional<node_ptr>(nullptr)); } template <typename Key, typename Compare> typename splay<Key, Compare>::const_iterator splay<Key, Compare>::cend() const { return const_iterator(std::make_optional<node_ptr>(nullptr)); } template <typename Key, typename Compare> bool splay<Key, Compare>::empty() const noexcept { return size() == 0; } template <typename Key, typename Compare> std::size_t splay<Key, Compare>::size() const noexcept { return m_size; } template <typename Key, typename Compare> void splay<Key, Compare>::clear() noexcept { while (! this->empty()) { erase(this->head->value); } } template <typename Key, typename Compare> typename splay<Key, Compare>::node_ptr splay<Key, Compare>::insert(key_type key) { node_ptr child = nullptr; if (head == nullptr) { head = new node_type(key); child = head; } else { node_ptr parent = head; node_ptr current = parent; while (current != nullptr) { if (current->value == key) { return current; } if (key_cmp(key, current->value)) { parent = current; current = current->left; } else if (key_cmp(current->value, key)) { parent = current; current = current->right; } } if (key_cmp(key, parent->value)) { child = new node_type{ key }; parent->left = child; } else if (key_cmp(parent->value, key)) { child = new node_type{ key }; parent->right = child; } } m_size++; splay_operation(child); return child; } template <typename Key, typename Compare> typename splay<Key, Compare>::iterator splay<Key, Compare>::find(const key_type& value) { node_ptr current = head; while (current != nullptr) { if (key_cmp(value, current->value)) { current = current->left; } else if (key_cmp(current->value, value)) { current = current->right; } else { break; } } splay_operation(current); return iterator(head, current); } template <typename Key, typename Compare> typename splay<Key, Compare>::const_iterator splay<Key, Compare>::find(const key_type& value) const { node_ptr current = head; while (current != nullptr) { if (key_cmp(value, current->value)) { current = current->left; } else if (key_cmp(current->value, value)) { current = current->right; } else { break; } } splay_operation(current); return const_iterator(head, current); } template <typename Key, typename Compare> void splay<Key, Compare>::erase(const key_type& key) { node_ptr current = head; node_ptr parent = head; bool is_left_child = false; while (current != nullptr) { if (key_cmp(key, current->value)) { parent = current; current = current->left; is_left_child = true; } else if (key_cmp(current->value, key)) { parent = current; current = current->right; is_left_child = false; } else { break; } } if (current == nullptr) { return; } else { node_ptr left_child = current->left; node_ptr right_child = current->right; if (is_left_child) { if (left_child != nullptr) { parent->left = left_child; node_ptr max = left_child; while (max->right != nullptr) { max = max->right; } max->right = right_child; delete current; splay_operation(max); } else { parent->left = right_child; delete current; if (right_child != nullptr) { splay_operation(right_child); } else { splay_operation(parent); } } } else { if (left_child != nullptr) { parent->right = left_child; node_ptr max = left_child; while (max->right != nullptr) { max = max->right; } max->right = right_child; if (current == head) { head = left_child; } delete current; splay_operation(max); } else { parent->right = right_child; if (current == head) { if (right_child != nullptr) { head = right_child; } else { head = nullptr; delete current; m_size--; return; } } delete current; if (right_child != nullptr) { splay_operation(right_child); } else { splay_operation(parent); } } } m_size--; } } template <typename Key, typename Compare> typename splay<Key, Compare>::node_ptr splay<Key, Compare>::find_place(const key_type& value, bool last_nonzero) const { cmp_cache.clear(); clear_cache(); node_ptr previous = nullptr; node_ptr current = head; while (current != nullptr) { previous = current; path_cache.push(previous); if (key_cmp(value, current->value)) { current = current->left; cmp_cache.push_back(false); } else if (key_cmp(current->value, value)) { current = current->right; cmp_cache.push_back(true); } else { break; } } return last_nonzero ? previous : current; } template <typename Key, typename Compare> void splay<Key, Compare>::rotate_left(node_ptr current) { find_place(current->value, 0); path_cache.pop(); node_ptr parent = path_cache.top(); path_cache.pop(); if (!path_cache.empty()) { node_ptr grand_parent = path_cache.top(); if (grand_parent->left == parent) { grand_parent->left = current; } else { grand_parent->right = current; } node_ptr tmp = current->left; current->left = parent; parent->right = tmp; clear_cache(); } else { node_ptr tmp = current->left; current->left = parent; parent->right = tmp; head = current; clear_cache(); } } template <typename Key, typename Compare> void splay<Key, Compare>::rotate_right(node_ptr current) { find_place(current->value, 0); path_cache.pop(); node_ptr parent = path_cache.top(); path_cache.pop(); if (!path_cache.empty()) { node_ptr grand_parent = path_cache.top(); if (grand_parent->left == parent) { grand_parent->left = current; } else { grand_parent->right = current; } node_ptr tmp = current->right; current->right = parent; parent->left = tmp; clear_cache(); } else { node_ptr tmp = current->right; current->right = parent; parent->left = tmp; head = current; clear_cache(); } } template <typename Key, typename Compare> void splay<Key, Compare>::splay_operation(node_ptr current) { if (current == nullptr) { return; } find_place(current->value, 0); std::stack<node_ptr> path = path_cache; if (path.size() == 1) { clear_cache(); head = current; return; } while (!path.empty()) { if (path.size() == 1) { break; } path.pop(); node_ptr parent = path.top(); path.pop(); if (parent->left == current) { if (path.empty()) { rotate_right(current); } else if (parent == path.top()->left) { rotate_right(parent); rotate_right(current); } else { rotate_right(current); rotate_left(current); } } else { if (path.empty()) { rotate_left(current); } else if (parent == path.top()->right) { rotate_left(parent); rotate_left(current); } else { rotate_left(current); rotate_right(current); } } } clear_cache(); head = current; } }
true
db76a3787d8edb8cd299db463bd399d586984777
C++
Yac836/leetcode
/139.wordBreak.cpp
UTF-8
650
2.640625
3
[]
no_license
// // Created by zhaohongyan on 2020/6/26. // #include <iostream> #include <vector> #include <string> #include <algorithm> using namespace std; bool wordBreak( string s, vector<string>& wordDict) { vector<bool> dp(s.size()+1); dp[0] = true; for (int i = 1; i <= s.size(); ++i) { for(int j = 0; j < i; j++){ if(dp[j] &&find(wordDict.begin(),wordDict.end(),s.substr(j,i-j)) != wordDict.end()){ dp[i] = true; break; } } } return dp[s.size()]; } int main(){ vector<string> a{"leet","code"}; string s = "leetcode"; cout << wordBreak(s,a) << endl; }
true
50c64cb0dda2db8fe7a2ab6a420610d206be8a3f
C++
kothiga/ACM-ICPC
/NARMR2011/5736/5736.cc
UTF-8
4,233
3.015625
3
[]
no_license
// // Solution for ACM-ICPC 5736 - Contour Tracing // (North America - Rocky Mountain Regional 2011) // // Compile : g++11 -std=c++11 -o 5736 5736.cc -Wall // Written by : Austin Kothig // Semester : SPRING 2017 // Problem : Given an 'image', trace any contours, then // compile a list of the contours that have // more than 5 bits to them. Sort them and print. // #include <iostream> #include <algorithm> #include <utility> #include <string.h> #include <vector> using namespace std; const int MAX_RC = 200; char bitM[MAX_RC][MAX_RC]; vector<int> objects; //vector< pair<int, int> > objects; // 0 1 2 3 4 5 6 7 // W NW N NE E SE S SW const int derR[8]{ 0, -1, -1, -1, 0, 1, 1, 1 }; const int derC[8]{ -1, -1, 0, 1, 1, 1, 0, -1 }; void trace(int x, int y) { int d = 0; pair<int, int> b, b0, b1, c, c0, c1, prev, next, contour; // we start looking at a pixel contour = make_pair(0, 1); // store the position of the first spec // and the neighbor west of this position b0 = make_pair(x, y); c0 = make_pair(x+derR[d], y+derC[d]); // check the position below for a bit. // if it is found, mark it as seen and // incriment the bit counter. this is // done the way it is because of a specific // edge case, where the length of a contour is // 4, but still has 5 bits in it. if(bitM[b0.first+derR[6]][b0.second+derC[6]] == '1') { bitM[b0.first+derR[6]][b0.second+derC[6]] = '2'; contour.second++; } // step 2 for(int num = 0; num < 8; num++) { prev = c0; d = (d+1)%8; c0 = make_pair(b0.first+derR[d], b0.second+derC[d]); if(bitM[c0.first][c0.second] == '1' || bitM[c0.first][c0.second] == '2') { // if this has not been seen, if(bitM[c0.first][c0.second] == '1') { // increase bit count contour.second++; // mark this as seen bitM[c0.first][c0.second] = '2'; } b1 = c0; c1 = prev; d = (8+d-2)%8; break; } // no contours around. leave. if(num == 7) return; } // step 3 b = b1; c = c1; // append to the contour contour.first++; // step 6 bool breakBool = true; while(breakBool) { // step 4 prev = c; for(int num = 0; num < 8; num++) { next = make_pair(b.first+derR[d], b.second+derC[d]); // exit condition of step 6 if(b == b0 && next == b1){breakBool = false; break;} // step 5 if(bitM[next.first][next.second] == '1' || bitM[next.first][next.second] == '2') { // increase length contour.first++; // if this bit has not been seen // before, add it. if(bitM[next.first][next.second] == '1') { contour.second++; // mark this bit as seen bitM[next.first][next.second] = '2'; } b = next; c = prev; d = (8+d-2)%8; break; } prev = next; d = (d+1)%8; } } // only store if the object // has more than 4 pixels if(contour.second > 4) objects.push_back(contour.first); } int main() { // setup int R, C; int CASE = 1; while(cin >> R >> C && R != 0 && C != 0) { objects.clear(); memset(bitM,'0', sizeof bitM); for(int i = 0; i < R; i++) for(int j = 0; j < C; j++) { cin >> bitM[i][j]; } // look for the start of a contour for(int i = 0; i < R; i++) for(int j = 0; j < C; j++) { if(bitM[i][j] == '1') { // mark the position // and trace around bitM[i][j] = '2'; trace(i, j); } // increment colomn until looking at a '0' if(bitM[i][j] == '2') { while(bitM[i][j] != '0') j++; } } // output int total = 0; cout << "Case " << CASE++ << "\n"; sort(objects.begin(), objects.end()); for(unsigned int i = 0; i < objects.size(); i++) { if(total) cout << " "; cout << objects[i]; total++; } // this occurs if all of our // traced contours are too small // or there were no traces at all if(total == 0) cout << "no objects found"; cout << endl; } }
true
0db5c4cba29a7a3b4b65ca55ee78a8541724262d
C++
AnimeGirl110/wasm-asteroids
/src/Asteroid.cpp
UTF-8
477
2.65625
3
[]
no_license
#include "Asteroid.hpp" #include <stdio.h> #define NUM_SIZES 4 #define SIZE_FACTOR 40 Asteroid::Asteroid() : size(NUM_SIZES), dimX(size * SIZE_FACTOR), dimY(dimX), posX(0), posY(0) { printf(" Asteroid::Asteroid()\n"); } Asteroid::Asteroid(Asteroid *parent) : size(parent->GetSize() - 1), dimX(size * SIZE_FACTOR), dimY(dimX), posX(GetPosX()), posY(GetPosY()) { printf(" Asteroid::Asteroid(Asteroid *)\n"); }
true
a08e713315f9c862f5f600695a8914339a630cae
C++
Rexagon/cybr
/app/GUI.h
WINDOWS-1251
1,421
2.703125
3
[ "Apache-2.0" ]
permissive
#pragma once #include <memory> #include <vector> #include <string> #include <map> #include "Layout.h" #include "VerticalLayout.h" #include "HorizontalLayout.h" #include "Widget.h" #include "Label.h" class GUI { public: enum Alignment { AlignLeft = 1 << 0, AlignRight = 1 << 1, AlignHCenter = 1 << 2, AlignTop = 1 << 3, AlignBottom = 1 << 4, AlignVCenter = 1 << 5, AlignCenter = AlignHCenter | AlignVCenter }; GUI(); // , , void update(); // void draw(); // widget_ptr getRootWidget() const { return m_rootWidget; } void prepareDeleting(Widget* widget); // GUI template<class T, class... Args> static std::shared_ptr<T> create(const Args&... args) { static_assert(std::is_base_of<Widget, T>::value, "GUI::Create template argument must be the child class of \"Widget\" class"); std::shared_ptr<T> widget = std::shared_ptr<T>(new T(args...)); return std::move(widget); } private: widget_ptr m_rootWidget; Widget* m_currentHoveredItem; Widget* m_currentPressedItem; Widget* m_currentFocusedItem; };
true
79affd0b85e1187a0b305180c3076cf335d8b0a8
C++
vxd7/labs
/Histogrammer/F/hgram.h
UTF-8
2,720
3.53125
4
[]
no_license
#include <iostream> #include <cstring> #include <vector> #include <algorithm> struct __barInfo { std::string name; int freq; }; class Histogram { public: /* Number of bars in the Histogram */ int barCount; /* Block type to print */ char block; /* Standart constructor */ Histogram(); /* * User Interface function. * Gets all of the input, parses it and creates the Histogram */ void parseData(std::string s); /* * Prints Histogram. * User Interface function for printing the while Histogram * to the STDOUT */ // TODO: add print to file feature void printHistogram(); void sortHistogram(bool ascending = true); private: /* * Process character. * Searches for a character in the Histogram. If found -- increases * its freq, if not a new bar is created. * * addBar(...) is called when a new bar is created */ void procData(std::string s); /* * Adds new bar to the Histogram. * Increases the barCount variable by one. */ void addBar(std::string newName, int newFreq = 1); /* * Calculate the percentage of each item. */ void computeRates(); std::vector<__barInfo> barInfo; }; Histogram::Histogram() { barCount = 0; block = '#'; } void Histogram::addBar(std::string newName, int newFreq) { struct __barInfo __tmp; __tmp.name = newName; __tmp.freq = newFreq; barInfo.push_back(__tmp); barCount++; } void Histogram::parseData(std::string s) { for(size_t i = 0; i < s.size(); ++i) { if(!isalpha(s[i])) continue; procData(s.substr(i, 1)); } /* * Equalize the histogram */ computeRates(); } void Histogram::procData(std::string name) { bool added = false; for(size_t i = 0; i < name.size(); ++i) name[i] = tolower(name[i]); for(size_t i = 0; i < barCount; ++i) { if(barInfo[i].name == name) { barInfo[i].freq++; added = true; break; } } if(!added) addBar(name); } void Histogram::printHistogram() { for(size_t i = 0; i < barCount; ++i) { std::cout << barInfo[i].name << '|'; for(size_t j = 0; j < barInfo[i].freq; ++j) std::cout << '#'; std::cout << std::endl; } } void Histogram::computeRates() { long int sum_t = 0; for(size_t i = 0; i < barCount; ++i) { sum_t += barInfo[i].freq; } double q = .0; for(size_t i = 0; i < barCount; ++i) { q = barInfo[i].freq * 1.0; q = (q / sum_t * 1.0); q *= 100.0; barInfo[i].freq = q; } } bool cmp(__barInfo b1, __barInfo b2) { if(b1.freq < b2.freq) return true; else return false; } void Histogram::sortHistogram(bool ascending) { if(ascending) std::sort(barInfo.begin(), barInfo.end(), cmp); else { std::sort(barInfo.begin(), barInfo.end(), cmp); std::reverse(barInfo.begin(), barInfo.end()); } }
true
2e47655a281fd0faadb66323f819471c91931941
C++
gsol10/r2p2
/linux-apps/lucene-r2p2/inc/lucene++/OpenBitSet.h
UTF-8
8,516
2.703125
3
[ "MIT" ]
permissive
///////////////////////////////////////////////////////////////////////////// // Copyright (c) 2009-2014 Alan Wright. All rights reserved. // Distributable under the terms of either the Apache License (Version 2.0) // or the GNU Lesser General Public License. ///////////////////////////////////////////////////////////////////////////// #ifndef OPENBITSET_H #define OPENBITSET_H #include "DocIdSet.h" namespace Lucene { /// An "open" BitSet implementation that allows direct access to the array of words storing the bits. /// /// The goals of OpenBitSet are the fastest implementation possible, and maximum code reuse. Extra /// safety and encapsulation may always be built on top, but if that's built in, the cost can never /// be removed (and hence people re-implement their own version in order to get better performance). class LPPAPI OpenBitSet : public DocIdSet { public: /// Constructs an OpenBitSet large enough to hold numBits. OpenBitSet(int64_t numBits = 64); /// Constructs an OpenBitSet from an existing LongArray. /// /// The first 64 bits are in long[0], with bit index 0 at the least significant bit, and bit /// index 63 at the most significant. Given a bit index, the word containing it is long[index/64], /// and it is at bit number index%64 within that word. /// /// numWords are the number of elements in the array that contain set bits (non-zero longs). /// numWords should be <= bits.length(), and any existing words in the array at position >= /// numWords should be zero. OpenBitSet(LongArray bits, int32_t numWords); virtual ~OpenBitSet(); LUCENE_CLASS(OpenBitSet); protected: LongArray bits; int32_t wlen; // number of words (elements) used in the array public: virtual DocIdSetIteratorPtr iterator(); /// This DocIdSet implementation is cacheable. virtual bool isCacheable(); /// Returns the current capacity in bits (1 greater than the index of the last bit) int64_t capacity(); /// Returns the current capacity of this set. Included for compatibility. This is *not* /// equal to {@link #cardinality} int64_t size(); /// Returns true if there are no set bits bool isEmpty(); /// Returns the long[] storing the bits LongArray getBits(); /// Sets a new long[] to use as the bit storage void setBits(LongArray bits); /// Gets the number of longs in the array that are in use int32_t getNumWords(); /// Sets the number of longs in the array that are in use void setNumWords(int32_t numWords); /// Returns true or false for the specified bit index. bool get(int32_t index); /// Returns true or false for the specified bit index. /// The index should be less than the OpenBitSet size bool fastGet(int32_t index); /// Returns true or false for the specified bit index bool get(int64_t index); /// Returns true or false for the specified bit index. /// The index should be less than the OpenBitSet size. bool fastGet(int64_t index); /// Returns 1 if the bit is set, 0 if not. /// The index should be less than the OpenBitSet size int32_t getBit(int32_t index); /// Sets a bit, expanding the set size if necessary void set(int64_t index); /// Sets the bit at the specified index. /// The index should be less than the OpenBitSet size. void fastSet(int32_t index); /// Sets the bit at the specified index. /// The index should be less than the OpenBitSet size. void fastSet(int64_t index); /// Sets a range of bits, expanding the set size if necessary /// @param startIndex lower index /// @param endIndex one-past the last bit to set void set(int64_t startIndex, int64_t endIndex); /// Clears a bit. /// The index should be less than the OpenBitSet size. void fastClear(int32_t index); /// Clears a bit. /// The index should be less than the OpenBitSet size. void fastClear(int64_t index); /// Clears a bit, allowing access beyond the current set size without changing the size. void clear(int64_t index); /// Clears a range of bits. Clearing past the end does not change the size of the set. /// @param startIndex lower index /// @param endIndex one-past the last bit to clear void clear(int32_t startIndex, int32_t endIndex); /// Clears a range of bits. Clearing past the end does not change the size of the set. /// @param startIndex lower index /// @param endIndex one-past the last bit to clear void clear(int64_t startIndex, int64_t endIndex); /// Sets a bit and returns the previous value. /// The index should be less than the OpenBitSet size. bool getAndSet(int32_t index); /// Sets a bit and returns the previous value. /// The index should be less than the OpenBitSet size. bool getAndSet(int64_t index); /// Flips a bit. /// The index should be less than the OpenBitSet size. void fastFlip(int32_t index); /// Flips a bit. /// The index should be less than the OpenBitSet size. void fastFlip(int64_t index); /// Flips a bit, expanding the set size if necessary void flip(int64_t index); /// Flips a bit and returns the resulting bit value. /// The index should be less than the OpenBitSet size. bool flipAndGet(int32_t index); /// Flips a bit and returns the resulting bit value. /// The index should be less than the OpenBitSet size. bool flipAndGet(int64_t index); /// Flips a range of bits, expanding the set size if necessary /// @param startIndex lower index /// @param endIndex one-past the last bit to flip void flip(int64_t startIndex, int64_t endIndex); /// @return the number of set bits int64_t cardinality(); /// Returns the popcount or cardinality of the intersection of the two sets. /// Neither set is modified. static int64_t intersectionCount(const OpenBitSetPtr& a, const OpenBitSetPtr& b); /// Returns the popcount or cardinality of the union of the two sets. /// Neither set is modified. static int64_t unionCount(const OpenBitSetPtr& a, const OpenBitSetPtr& b); /// Returns the popcount or cardinality of "a and not b" or "intersection(a, not(b))". /// Neither set is modified. static int64_t andNotCount(const OpenBitSetPtr& a, const OpenBitSetPtr& b); /// Returns the popcount or cardinality of the exclusive-or of the two sets. /// Neither set is modified. static int64_t xorCount(const OpenBitSetPtr& a, const OpenBitSetPtr& b); /// Returns the index of the first set bit starting at the index specified. /// -1 is returned if there are no more set bits. int32_t nextSetBit(int32_t index); /// Returns the index of the first set bit starting at the index specified. /// -1 is returned if there are no more set bits. int64_t nextSetBit(int64_t index); virtual LuceneObjectPtr clone(const LuceneObjectPtr& other = LuceneObjectPtr()); /// this = this AND other void intersect(const OpenBitSetPtr& other); /// this = this OR other void _union(const OpenBitSetPtr& other); /// Remove all elements set in other. this = this AND_NOT other void remove(const OpenBitSetPtr& other); /// this = this XOR other void _xor(const OpenBitSetPtr& other); /// see {@link intersect} void _and(const OpenBitSetPtr& other); /// see {@link union} void _or(const OpenBitSetPtr& other); /// see {@link remove} void andNot(const OpenBitSetPtr& other); /// Returns true if the sets have any elements in common bool intersects(const OpenBitSetPtr& other); /// Expand the LongArray with the size given as a number of words (64 bit longs). /// getNumWords() is unchanged by this call. void ensureCapacityWords(int32_t numWords); /// Ensure that the LongArray is big enough to hold numBits, expanding it if necessary. /// getNumWords() is unchanged by this call. void ensureCapacity(int64_t numBits); /// Lowers numWords, the number of words in use, by checking for trailing zero words. void trimTrailingZeros(); /// Returns the number of 64 bit words it would take to hold numBits. static int32_t bits2words(int64_t numBits); /// Returns true if both sets have the same bits set virtual bool equals(const LuceneObjectPtr& other); virtual int32_t hashCode(); protected: int32_t expandingWordNum(int64_t index); }; } #endif
true
1fddb5c1957ee904585907dda457daa5988c241f
C++
jt396/XOF-WolfX
/Audio/XOF_AudioRequest.hpp
UTF-8
2,393
2.75
3
[]
no_license
/* =============================================================================== XOF === File : XOF_AudioRequest.hpp Desc : Allows game objects to make requests of the audio system, used to implement basic batched upating. Objects submit requests then the game loop tells the audio system to processes requests, calling the appropriate audio functions. AUDIO API AGNOSTIC. API SPECIFIC FLAGS ARRAY TO BE ADDED TO RENDERER CLASS/IMPLEMENTATION. =============================================================================== */ #ifndef XOF_AUDIO_REQUEST_HPP #define XOF_AUDIO_REQUEST_HPP #include "../Platform/XOF_Platform.hpp" class Music; class SoundEffect; enum XOF_AUDIO_REQUEST_TYPE { // Music PLAY_MUSIC = 0, PAUSE_MUSIC, STOP_MUSIC, RESTART_MUSIC, // Sound FX PLAY_SOUND_EFFECT, PAUSE_SOUND_EFFECT, STOP_SOUND_EFFECT, RESTART_SOUND_EFFECT, INVALID_AUDIO_REQUEST, // etc... }; struct AudioRequest { // Default ctor, for use in request container only AudioRequest() { type = XOF_AUDIO_REQUEST_TYPE::INVALID_AUDIO_REQUEST; music = nullptr; soundEffect = nullptr; volume = 0.f; } AudioRequest( XOF_AUDIO_REQUEST_TYPE type, Music *music, SoundEffect *soundEffect, float volume, const std::string& audioFileName ) { XOF_ASSERT( type >= 0 && type < XOF_AUDIO_REQUEST_TYPE::INVALID_AUDIO_REQUEST ) this->type = type; if( type >= 0 && type <= XOF_AUDIO_REQUEST_TYPE::RESTART_MUSIC ) { this->music = music; } else if( type >= XOF_AUDIO_REQUEST_TYPE::PLAY_SOUND_EFFECT && type <= XOF_AUDIO_REQUEST_TYPE::RESTART_SOUND_EFFECT ) { this->soundEffect = soundEffect; } this->volume = volume; this->audioFileName = audioFileName; } AudioRequest( AudioRequest&& rhs ) { XOF_ASSERT( rhs.type >= 0 && rhs.type < XOF_AUDIO_REQUEST_TYPE::INVALID_AUDIO_REQUEST ) this->type = rhs.type; if( type >= 0 && type <= XOF_AUDIO_REQUEST_TYPE::RESTART_MUSIC ) { this->music = rhs.music; } else if( type >= XOF_AUDIO_REQUEST_TYPE::PLAY_SOUND_EFFECT && type <= XOF_AUDIO_REQUEST_TYPE::RESTART_SOUND_EFFECT ) { this->soundEffect = rhs.soundEffect; } this->volume = rhs.volume; this->audioFileName = rhs.audioFileName; } XOF_AUDIO_REQUEST_TYPE type; union { Music *music; SoundEffect *soundEffect; }; float volume; std::string audioFileName; }; #endif // XOF_AUDIO_REQUEST_HPP
true
f4b32686e89062be01a97131092381bb9324c4d5
C++
aishoot/CAPSolutions
/CCF201312/T3/main.cpp
UTF-8
516
2.921875
3
[]
no_license
#include <iostream> #include <algorithm> #include <vector> #include <fstream> using namespace std; int main() { int num,i,j; ifstream cin("test.txt"); while(cin>>num) { int area, max_area=0, t; vector<int> height; for(i=0;i<num;i++) { cin>>t; height.push_back(t); for(j=i;j>=0;j--) { area=(*min_element(height.begin()+(i-j),height.begin()+i+1))*(j+1); if(area>max_area) { max_area=area; } } } cout<<max_area<<endl; } return 0; }
true
9573af95c9c774fa2e0f267ea474f26c5f18870f
C++
xingfeT/c-practice
/day-001-100/day-012/problem-2/main.cpp
UTF-8
997
3.96875
4
[]
no_license
/* * Write, compile, and execute a C program that calculates the distance * between two points whose coordinates are (7, 12) and (3, 9). use the * fact that the distance between two points having coordinates (x1, y1) * and (x2, y2) is distance = sqrt((x1 - x2)^2 + (y1 - y2)^2). */ #include <stdio.h> #include <math.h> struct Vector2 { float X; float Y; }; inline Vector2 CreateVector(float, float); inline float ComputeDistanceBetweenVector2(Vector2 *, Vector2 *); inline void PrettyPrint(float); int main(void) { Vector2 v1 = CreateVector(7, 12); Vector2 v2 = CreateVector(3, 9); PrettyPrint(ComputeDistanceBetweenVector2(&v1, &v2)); return 0; } inline float ComputeDistanceBetweenVector2(Vector2 *v1, Vector2 *v2) { float result = sqrt(pow((v1->X - v2->X), 2) + pow((v1->Y - v2->Y), 2)); return result; } inline Vector2 CreateVector(float x, float y) { return Vector2 { x, y, }; } inline void PrettyPrint(float result) { printf("Distance: %.2f\n", result); }
true
b8938be4d32d30c90e7c075d22f6d53d9e66534c
C++
isysoi3/Programming
/c++/1 сем/english_money/english_money/english_money.cpp
WINDOWS-1251
1,562
3.578125
4
[]
no_license
// english_money.cpp: . // #include <iostream> #include "money.h" using namespace std; void input(long int *pound, int *shilling, double *pence) { long int a; int b; double c; cout << "Enter pounds "; cin >> a ; *pound = a; cout << "Enter shilings "; cin >> b; *shilling = b; cout << "Enter pences "; cin >> c; *pence = c; cout << endl; } int main() { long int pound = 0; int shilling = 0; double pence = 0; int check = 0; input(&pound, &shilling, &pence); Money *a = nullptr; Money *b = nullptr; try { a = new Money(pound, shilling, pence); check++; } catch (const exception& e) { cout << e.what() << endl; } input(&pound, &shilling, &pence); try { b = new Money(pound, shilling, pence); check++; } catch (const exception& e) { cout << e.what() << endl; } if (check == 2) { Money *rez; rez = new Money; try { if (*a == *b) cout << "equal"; else if (*a < *b) cout << "the second is more then the first"; else cout << "the first is more then the second"; cout << endl; *rez = *a + *b; cout << "a + b : "; rez->getMoney(); *rez = *b - *a; cout << "b - a : "; rez->getMoney(); *a += *a; cout << "a += a : "; a->getMoney(); *a -= *a; cout << "a -= a : "; a->getMoney(); *b = -(*b); cout << "b = -b : "; b->getMoney(); } catch (const exception& e) { cout << e.what() << endl; } delete rez; } delete a; delete b; return 0; }
true
9ee0b8f077aa68d891c80aa1ce63b12ce1852861
C++
liecn/algorithms
/CSE_830/hw2/hw2_1.cpp
UTF-8
614
2.96875
3
[]
no_license
#include <iostream> #include <new> #include <string> #include <algorithm> using namespace std; int main() { int n; int a, b; cin >> n; // read input matrix int *p = new int[n]; for (int i = 0; i < n; i++) { cin >> a >> b; p[i] = a - b; } int i,j = 0; for (i = 0; i < n; i++) { int sum = 0; int add_index=i; for (j = 0; j < n; j++) { sum+=p[add_index%n]; add_index+=1; if (sum<0) break; } if (j==n) break; } cout << i <<endl; delete[] p; return 0; }
true
f6bb31c982013513acd5d8400302eaefdfc48720
C++
jpan127/esp32-drivers
/main/tasks/TemperatureReadTask.hpp
UTF-8
1,010
2.859375
3
[]
no_license
#pragma once #include "DS18B20.hpp" #include <freertos/FreeRTOS.h> #include <esp_log.h> #include <driver/gpio.h> #define SENSOR_PIN (GPIO_NUM_23) void TemperatureReadTask(void *p) { DS18B20 sensor(SENSOR_PIN); ESP_LOGI("TemperatureReadTask", "Starting task..."); while (1) { vTaskDelay(1000 / portTICK_PERIOD_MS); ESP_LOGI("TemperatureReadTask", "%f\n", sensor.ReadTemperature()); } vTaskDelete(NULL); } float read_temperature(int n) { DS18B20 sensor(SENSOR_PIN); float temp = 0; float read = 0; for (int i=0; i<n; i++) { read = sensor.ReadTemperature(); // Making sure no bogus values if (read > 120) { ESP_LOGI("DS18B20", "Invalid reading %f reading again.", read); read = sensor.ReadTemperature(); } temp += read; ESP_LOGI("DS18B20", "%f\n", read); vTaskDelay(50 / portTICK_PERIOD_MS); } return temp / n; }
true
fe3afd3eaaaccdf07953fdd6f5e8d92381522717
C++
enaim/Competitive_Programming
/CodeChef/Smallest Numbers of Notes.cpp
UTF-8
648
2.609375
3
[]
no_license
#include <stdio.h> #include <string.h> #include <math.h> int main() { // freopen("in.txt","r",stdin); // freopen("output.txt","w",stdout); int tks,ks=1,cnt,n,x; scanf("%d",&tks); while(tks--) { cnt=0; scanf("%d",&n); x=n/100; n = n%100; cnt+=x; x=n/50; n = n%50; cnt+=x; x=n/10; n = n%10; cnt+=x; x=n/5; n = n%5; cnt+=x; x=n/2; n = n%2; cnt+=x; x=n/1; n = n%1; cnt+=x; printf("%d\n",cnt); } return 0; }
true
87be9ef59b110fdebab78303278929e17aea9674
C++
redcapital/algo
/timus/1924.cpp
UTF-8
566
3.5625
4
[]
no_license
// It doesn't matter if you put plus or minus sign between numbers, the overall // parity won't change. // Every pair will be reduced to either odd or even number. You'll get odd // if one of the numbers is odd and one is even, otherwise you get even number. // // In order for overall parity to be odd, the number of odd numbers must be // odd. In this case, grimy team wins. #include <iostream> using namespace std; int main(int argc, char const *argv[]) { int n; cin >> n; if (((n + 1) / 2) % 2 == 1) cout << "grimy"; else cout << "black"; return 0; }
true
bb80be0806e4741515681f1c8e12bff952844688
C++
LauraDiosan-CS/lab8-11-polimorfism-Teona09
/Lab 8-11/UI.cpp
UTF-8
3,350
3.28125
3
[]
no_license
#include "UI.h" void UI::menu() { cout << endl; cout << '\t' << "Menu:" << endl; cout << '\t' << "1.Log in" << endl; cout << '\t' << "2.Operating Menu" << endl; cout << '\t' << "3.Log out" << endl; cout << '\t' << "4.Exit" << endl; cout << '\t' << "Your option:" << endl; } void UI::logIn() { if (service.loggedIn() == true) cout << "already logged in\n"; else { char* username = new char[15]; char* password = new char[15]; cout << "Username: "; cin >> username; cout << "Password: "; cin >> password; if (service.logIn(username, password) == true) { cout << "logged in\n\n"; this->showAll(); } else cout << "Wrong username or password\nredirect to menu\n"; delete[] username, password; } } void UI::logOut() { try { service.logOut(); cout << "logged out\n"; } catch (MyException ex) { cout << ex.getMessage() << '\n'; } } void UI::menuOperations() { cout << endl; cout << '\t' << "Operating Menu:" << endl; cout << '\t' << "1.Add" << endl; cout << '\t' << "2.Show all" << endl; cout << '\t' << "3.Search producer" << endl; cout << '\t' << "4.Back" << endl; cout << '\t' << "Your option:" << endl; } void UI::operations() { if (service.loggedIn() == true) { char option; bool ok=true; while (ok == true) { menuOperations(); cin >> option; switch (option) { case '1': { this->add(); break; } case '2': { this->showAll(); break; } case '3': { this->searchProducer(); break; } case '4': { ok = false; break; } default : { cout << "not an option\n"; break; } } } } else cout << "not logged in\n"; } void UI::add() { cout << '\t' << "Add: " << '\n'; cout << '\t' << "1.Drone" << '\n'; cout << '\t' << "2.Phone: " << '\n'; cout << '\t' << "Your option: "; char option; cin >> option; switch (option) { case '1': { try { Drone d; cin >> d; Series* s = new Drone(d); service.addSeries(s); } catch (MyExceptionList ex) { for (int i = 0; i < ex.getErrors().size(); i++) cout << ex.getErrors()[i]; } break; } case '2': { try { Phone p; cin >> p; service.validatePhone(p); Series* s = new Phone(p); service.addSeries(s); } catch (MyExceptionList ex) { for (int i = 0; i < ex.getErrors().size(); i++) cout << ex.getErrors()[i]; } break; } default : { cout << "not an option\n"; break; } } } void UI::showAll(){ list<Series*> all = service.getAllSeries(); for (auto it = all.begin(); it != all.end(); it++) cout << (*it)->toString()<<'\n'; } void UI::searchProducer() { string producer; cout << "Producer to search: "; cin >> producer; list<Series*> foundObjects = service.getAllSeriesFromProducer(producer); if (foundObjects.empty() == true) cout << "no series from this producer\n"; else for (auto it = foundObjects.begin(); it != foundObjects.end(); it++) cout << (*it)->toString() << '\n'; } void UI::console() { char option; bool ok = true; while (ok == true) { menu(); cin >> option; switch (option) { case '1': { this->logIn(); break; } case '2': { this->operations(); break; } case '3': { this->logOut(); break; } case '4': { ok = false; cout << "program closed\n"; break; } default: { cout << "not an option\n"; break; } } } }
true
33a9959556cbe47453d629efa0494c7c2eab40ce
C++
marcinlos/zephyr
/Zephyr/src/zephyr/core/Task.hpp
UTF-8
1,136
3.140625
3
[]
no_license
/** * @file Task.hpp */ #ifndef ZEPHYR_CORE_TASK_HPP_ #define ZEPHYR_CORE_TASK_HPP_ #include <memory> namespace zephyr { namespace core { /** Pointer type holding the task */ typedef std::shared_ptr<class Task> TaskPtr; /** * Base class for tasks scheduled for execution in the main loop. Each * iteration, `update()` is called. */ class Task { public: /** * Invoked when the task is added to task scheduler. */ virtual void start(); /** * Invoked when the task is about to be removed from the active task * collection. */ virtual void stop(); /** * Invoked when the task is about to be suspended. */ virtual void suspend(); /** * Invoked when the task is resumed after being suspended. */ virtual void resume(); /** * Invoked in the main loop when the task is active. */ virtual void update() = 0; /** * Virtual destructor, since the class is designed to be used as a * polymorphic base. */ virtual ~Task() = 0; }; } /* namespace core */ } /* namespace zephyr */ #endif /* ZEPHYR_CORE_TASK_HPP_ */
true
a1d0846a68c1552c633bea4c5b35195d62007830
C++
miglesias91/herramientas_desarrollo
/utiles/source/Stemming.cpp
UTF-8
1,549
2.703125
3
[ "MIT" ]
permissive
#include <utiles/include/Stemming.h> // stl #include <locale> #include <codecvt> using namespace herramientas::utiles; stemming::spanish_stem<> Stemming::stem_spanish; Stemming::Stemming() { } Stemming::~Stemming() { } void Stemming::stemUTF8(std::string & string_a_hashear) { std::wstring_convert<std::codecvt_utf8<wchar_t>> conv; std::wstring word = conv.from_bytes(string_a_hashear.c_str()); stem_spanish(word); string_a_hashear = conv.to_bytes(word); } void Stemming::stemUTF8(std::vector<std::string> & vector_de_string_a_stemmear) { for (std::vector<std::string>::iterator it = vector_de_string_a_stemmear.begin(); it != vector_de_string_a_stemmear.end(); it++) { stemUTF8(*it); } } void Stemming::stem(std::string & string_a_hashear) { wchar_t * unicode_text_buffer = new wchar_t[string_a_hashear.length() + 1]; std::wmemset(unicode_text_buffer, 0, string_a_hashear.length() + 1); std::mbstowcs(unicode_text_buffer, string_a_hashear.c_str(), string_a_hashear.length()); std::wstring word = unicode_text_buffer; stem_spanish(word); std::wstring_convert<std::codecvt_utf8<wchar_t>> conv; string_a_hashear = conv.to_bytes(word); delete[] unicode_text_buffer; } void Stemming::stem(std::vector<std::string> & vector_de_string_a_stemmear) { for (std::vector<std::string>::iterator it = vector_de_string_a_stemmear.begin(); it != vector_de_string_a_stemmear.end(); it++) { stem(*it); } }
true
e4e907724a2b1498f9cbe03ab3512c70828c01e7
C++
XiaotaoChen/coding-interview
/swordfingeroffer/sum_in_bits.cc
UTF-8
298
2.78125
3
[]
no_license
#include "../swordfingeroffer.h" namespace sword_finger_offer { int sum_in_bits(int num1, int num2) { while(num2 != 0) { int cal = (num1 & num2) <<1; // 进位 num1 = num1 ^ num2; // 本位结果 num2 = cal; } return num1; } } // namespace sword_finger_offer
true
2678325f859004105bcb4775e6fa1ed67ffe0f4c
C++
BilalAli181999/Programming-Fundamentals-in-C_Plus_Plus
/Float to Binary/Float to Binary/IEEE.cpp
UTF-8
2,758
2.703125
3
[]
no_license
#include<iostream> #include<math.h> #include"IEEE.h" using namespace std; void binaryMant(int bin[],float mant,int i) { float c = mant; while (c != 0 && i<32) { bin[i] = c * 2; c = (c * 2) - (int)(c * 2); i++; } } int *binaryExp(int exp,int &i) { int *bin = new int[33]; while (exp != 0) { bin[i] = exp % 2; exp = exp / 2; i++; } int x = i; for (int j = 0; j < i / 2; j++) { int rep; rep = bin[j]; bin[j] = bin[x - 1]; bin[x - 1] = rep; x--; } return bin; } bool * convertToBinary(float f) { int exp; float mant; if (f >= 0) { exp = f; mant = f - (int)f; } if (f < 0) { exp = 100 - (100 + f); mant =-( f - (int)f); } bool *arr = new bool[33]; for (int i = 0; i < 33; i++) { arr[i] = 0; } int *bin; int expLen = 0; bin=binaryExp(exp, expLen); binaryMant(bin, mant, expLen); int newAdd; if (exp > 1 ) { bool status = true; for (int j = 0; j<expLen && status; j++) { if (bin[j] == 1) { newAdd = (expLen - 1) - j; status = false; } } } if (exp == 1) { newAdd = 0; } if (exp == 0) { bool status = true; for (int j = expLen; j < 33 && status; j++) { if (bin[j] == 1) { newAdd = -((j - expLen)+1); status = false; } } } int newBin = 127 + newAdd; int u; if (exp >= 2) { u = 1; while (newBin != 0) { arr[u] = newBin % 2; newBin = newBin / 2; u++; } } else { u = 2; while (newBin != 0) { arr[u] = newBin % 2; newBin = newBin / 2; u++; } } int z = u; int expLEN = u; if (exp >= 2 ) { for (int j = 1; j < u / 2; j++) { int rep; rep = arr[j]; arr[j] = arr[z - 1]; arr[z - 1] = rep; z--; } } if (f<1.00) { for (int j = 2; j < u / 2; j++) { int rep; rep = arr[j]; arr[j] = arr[z - 1]; arr[z - 1] = rep; z--; } } if (f < 0) { arr[0] = 1; } else { arr[0] = 0; } int d=0; if (newAdd > 0) { d = expLen - newAdd; } if (newAdd < 0) { d = -(newAdd); } if (exp >= 2) { for (int j = 9; j < 33; j++) { arr[j] = bin[d]; d++; } } else if(exp ==1) { for (int j = 8; j < 33; j++) { arr[j] = bin[d]; d++; } } else { for (int j = 9; j < 33; j++) { arr[j] = bin[d]; d++; } } return arr; } float convertToFloat(bool *arr) { int mant = 0; int y = 1; for (int i = 8; i >= 1; i--) { mant = mant + arr[i] * y; y = y * 2; } int powOf2; powOf2 = mant - 127; float mantissa = 0; double s = -1; for (int i = 9; i < 32; i++) { mantissa = mantissa + arr[i] * pow(2.0, s); s = s - 1; } int signBit = arr[0]; float result; if (powOf2 >= 0 ) return pow(-1, signBit)*(1.0 + mantissa)*pow(2.0, powOf2); else return pow(-1, signBit)*(mantissa)*pow(2.0, powOf2); }
true
9698b21ed78e980f142720753febbc92052e8e71
C++
Munvik/Tower-Defense
/iceTower.cpp
UTF-8
8,524
2.8125
3
[]
no_license
#include "pch.hpp" #include "iceTower.hpp" #include "mainGame.hpp" iceTower::iceTower() { textureName = "iceTower"; loadTexture(); setAttributes(); } iceTower::~iceTower() { } void iceTower::setAttributes() { cost = 150; power = 0; slow = 0.10f; range = 160.f; speed = 400.f; levelAcces = 5; bulletSpeed = 700.f; value = cost; timer = sf::milliseconds(sf::Int32(speed * 3 / 4)); attackCircle.setRadius(range); sf::Vector2f circlePos; circlePos.x = getPosition().x + getSize().x / 2 - attackCircle.getGlobalBounds().width / 2; circlePos.y = getPosition().y + getSize().y / 2 - attackCircle.getGlobalBounds().height / 2; attackCircle.setPosition(circlePos); description = "Slows enemys"; bulletTextureName = "iceTowerBullet"; } void iceTower::loadTexture() { texture = *mainGame::getInstance()->textures.getTowerTexture(textureName); sprite.setTexture(texture); sf::Vector2u textureSize = texture.getSize(); sprite.setTextureRect(sf::IntRect(0, 0, textureSize.x / 3, textureSize.y)); } void iceTower::handleBullets() { for (size_t i = 0; i < bullets.size(); ++i) { bullets[i].update(); } } void iceTower::searchTarget() { std::vector<wave*> & monsters = mainGame::getInstance()->getWaves(); std::vector<std::shared_ptr<monster>> monsts; for (size_t i = monsters.size(); i-- > 0;) { for (size_t j = monsters[i]->size(); j-- > 0;) { if (monsters[i]->operator[](int(j))->isUnavailable()) continue; else if (isTargetInRange(monsters[i]->operator[](int(j)))) { monsts.push_back(monsters[i]->operator[](int(j))); } } } if (monsts.empty()) return; else { targetingMonster = monsts[rand() % monsts.size()]; } } void iceTower::attackMonster(std::shared_ptr<monster> monst) { std::shared_ptr<monsterEffect> slow = std::make_shared<slowEffect>(monst, this->slow, slowDur); monst->getEffectHandler().addEffect(slow); } void iceTower::shoot() { bullet bulet(bulletTextureName, this); bullets.push_back(bulet); targetingMonster.reset(); } void iceTower::upgrade() { slow = round(slow * 1.4f * 100.f) / 100; range *= 1.2f; attackCircle.setRadius(range); sf::Vector2f circlePos; circlePos.x = getCenter().x - attackCircle.getGlobalBounds().width / 2; circlePos.y = getCenter().y - attackCircle.getGlobalBounds().height / 2; attackCircle.setPosition(circlePos); expand(); value += getUpgradeCost(); upgradeLevel++; } std::shared_ptr<tower> iceTower::getClassObject() { std::shared_ptr<tower> obj = std::make_shared<iceTower>(); return obj; } tower::workshopHandler * iceTower::getWorkshopTemplate() { if (!workshopTemplate) { workshopTemplate = std::make_unique<workshopHandler>(this); } return workshopTemplate.get(); } tower::shopTemplate * iceTower::getShopTemplate() { if (!storeTemplate) { storeTemplate = std::make_unique<shopTemplate>(this); } return storeTemplate.get(); } ////////////////////// ICEtower:: workshophandler //////////////////////////// ////////////////////// ICEtower:: workshophandler //////////////////////////// ////////////////////// ICEtower:: workshophandler //////////////////////////// void iceTower::workshopHandler::draw(sf::RenderTarget & target, sf::RenderStates states) const { target.draw(X); target.draw(slow); target.draw(range); target.draw(upgrader); target.draw(upgradeCost); target.draw(sellText); if (owner->rangeBuffFactor != 0.f) target.draw(rangeBuff); } void iceTower::workshopHandler::place() { sf::Vector2f wsSize = workshopOwner->getSize(); sf::Vector2f wsPos = workshopOwner->getPosition(); sf::Vector2f upgraderPos; upgraderPos.x = wsPos.x + wsSize.x * 3 / 4 - upgrader.getSize().x / 2; upgraderPos.y = wsPos.y + wsSize.y / 2 - upgrader.getSize().y / 4; upgrader.setPosition(upgraderPos); slow.setFont(*font); slow.setCharacterSize(25); slow.setColor(sf::Color::Red); sf::Vector2f slowPos; slowPos.x = wsPos.x + wsSize.x / 20; slowPos.y = wsPos.y + wsSize.y / 2 - slow.getGlobalBounds().height * 3 / 4; slow.setPosition(slowPos); range.setFont(*font); range.setCharacterSize(30); range.setColor(sf::Color::Red); sf::Vector2f rangePos; rangePos.x = wsPos.x + wsSize.x * 2 / 5; rangePos.y = wsPos.y + wsSize.y / 2 - range.getGlobalBounds().height * 3 / 4; range.setPosition(rangePos); rangeBuff.setFont(*font); rangeBuff.setCharacterSize(18); rangeBuff.setColor(sf::Color::Green); sf::Vector2f rangeBuffPos; rangeBuffPos.x = range.getPosition().x + range.getGlobalBounds().width + 3.f; rangeBuffPos.y = range.getPosition().y + range.getGlobalBounds().height / 2 - rangeBuff.getGlobalBounds().height * 0.3f; rangeBuff.setPosition(rangeBuffPos); upgradeCost.setFont(*font); upgradeCost.setCharacterSize(20); upgradeCost.setColor(sf::Color::Red); sf::Vector2f costPos; costPos.x = upgrader.getPosition().x + upgrader.getSize().x / 2 - upgradeCost.getGlobalBounds().width / 2; costPos.y = upgrader.getPosition().y - upgradeCost.getGlobalBounds().height*1.4f; upgradeCost.setPosition(costPos); sellText.setFont(*font); sellText.setCharacterSize(20); sellText.setColor(sf::Color::Red); sellText.setString("SELL"); sf::Vector2f sellTPos; sellTPos.x = wsPos.x + wsSize.x - sellText.getGlobalBounds().width; sellTPos.y = wsPos.y + wsSize.y - sellText.getGlobalBounds().height * 1.5f; sellText.setPosition(sellTPos); sf::Vector2f XPos; XPos.x = wsPos.x + wsSize.x - X.getGlobalBounds().width; XPos.y = wsPos.y; X.setPosition(XPos); placed = true; } void iceTower::workshopHandler::set() { slow.setString("slowFactor = " + floatToString(owner->slow* 100.f) + "%"); range.setString("range = " + floatToString(owner->range)); if (owner->getRangeBuffFactor() != 0.f) rangeBuff.setString("+ " + floatToString(round(owner->rangeBuffFactor * owner->range))); if (owner->isExtended()) { upgradeCost.setString("MAX"); } else upgradeCost.setString("upgrade cost = " + intToString(owner->getUpgradeCost())); sf::Vector2f costPos; costPos.x = upgrader.getPosition().x + upgrader.getSize().x / 2 - upgradeCost.getGlobalBounds().width / 2; costPos.y = upgrader.getPosition().y - upgradeCost.getGlobalBounds().height * 1.4f; upgradeCost.setPosition(costPos); } ////////////////////// ICEtower:: shoptemplate //////////////////////////// ////////////////////// ICEtower:: shoptemplate //////////////////////////// ////////////////////// ICEtower:: shoptemplate //////////////////////////// iceTower::shopTemplate::shopTemplate(iceTower *ownr) :owner(ownr), attackTower::shopTemplate::shopTemplate(ownr) { cost.setString("cost=" + intToString(owner->cost)); cost.setCharacterSize(charSize); cost.setColor(sf::Color(240, 24, 24)); slow.setFont(*font); slow.setString("slow =" + floatToString(owner->slow * 100.f) + "%"); slow.setCharacterSize(charSize); slow.setColor(sf::Color(240, 24, 24)); range.setFont(*font); range.setString("range=" + floatToString(owner->range)); range.setCharacterSize(charSize); range.setColor(sf::Color(240, 24, 24)); } void iceTower::shopTemplate::setPosition(sf::Vector2f position) { towerSprite.setPosition(position); sf::Vector2f padlockPos = getMiddlePosition(towerSprite.getGlobalBounds(), padlock.getGlobalBounds()); padlock.setPosition(padlockPos); sf::Vector2f costPos; costPos.x = towerSprite.getPosition().x + towerSprite.getGlobalBounds().width / 2 - cost.getGlobalBounds().width / 2; costPos.y = position.y + towerSprite.getGlobalBounds().height; cost.setPosition(costPos); sf::Vector2f slowPos; slowPos.x = towerSprite.getPosition().x + towerSprite.getGlobalBounds().width / 2 - slow.getGlobalBounds().width / 2; slowPos.y = position.y + towerSprite.getGlobalBounds().height + cost.getGlobalBounds().height + 1.f; slow.setPosition(slowPos); sf::Vector2f rangePos; rangePos.x = towerSprite.getPosition().x + towerSprite.getGlobalBounds().width / 2 - range.getGlobalBounds().width / 2; rangePos.y = position.y + towerSprite.getGlobalBounds().height + cost.getGlobalBounds().height + power.getGlobalBounds().height + 1.f; range.setPosition(rangePos); } void iceTower::shopTemplate::draw(sf::RenderTarget & target, sf::RenderStates states) const { tower::shopTemplate::draw(target, states); target.draw(slow); target.draw(range); }
true
eebcc9010946ecc4980bbaa2877b4d3a3043f538
C++
clambassador/seasick
/csv_filter_len.cc
UTF-8
1,145
2.828125
3
[]
no_license
#include <cassert> #include <iostream> #include <set> #include <string> #include "ib/fileutil.h" #include "ib/logger.h" #include "ib/tokenizer.h" using namespace ib; using namespace std; int main(int argc, char** argv) { if (argc != 4) { Logger::error("usage: % colnum op len", argv[0]); return -1; } size_t col = atoi(argv[1]); string op = string(argv[2]); size_t len = atoi(argv[3]); assert(col != 0); while (cin.good()) { string s; string val; getline(cin, s); if (s.empty()) continue; Tokenizer::fast_split(s, ',', col, &val); assert(val.length() > 4); assert(val[0] == '|'); assert(val[1] == '|'); assert(val[val.length() - 1] == '|'); assert(val[val.length() - 2] == '|'); int vals = 1; for (size_t i = 2; i < val.length() - 2; ++i) { if (val[i] == '|') { vals += 1; } } if (op == "EQ" && vals == len) cout << s << endl; if (op == "NEQ" && vals != len) cout << s << endl; if (op == "LEQ" && vals <= len) cout << s << endl; if (op == "LT" && vals < len) cout << s << endl; if (op == "GEQ" && vals >= len) cout << s << endl; if (op == "GT" && vals > len) cout << s << endl; } }
true
a641e08b6555451a7d5e253905c2305651ab9b5c
C++
Yobretaw/AlgorithmProblems
/Leetcode/Stack&Queue/evaluateReversePolishNotation.cpp
UTF-8
1,746
3.859375
4
[]
no_license
#include <iostream> #include <vector> #include <string> #include <string.h> #include <sstream> #include <stack> #include <queue> #include <utility> #include <unordered_map> using namespace std; int eval(int a, int b, string op); /* Evaluate the value of an arthimetic expression in * Reverse Polish Notation. * * Valid operator are +, -, *, /. Each oeprand may be * an integer or another expression. * * Some example: * * ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 * * ["4", "13", "5" "/", "+"] -> (4 + (13 / 5)) -> 6 */ int evaluate(const vector<string>& exp) { if(exp.size() == 0) return 0; stack<int> s; int a, b; for (int i = 0; i < exp.size(); ++i) { if(exp[i] == "+" || exp[i] == "-" || exp[i] == "*" || exp[i] == "/") { b = s.top(); s.pop(); a = s.top(); s.pop(); s.push(eval(a, b, exp[i])); } else { int val = atoi((char*)exp[i].c_str()); s.push(val); } } return s.top(); } int eval(int a, int b, string op) { if(op == "+") return a + b; if(op == "-") return a - b; if(op == "*") return a * b; if(op == "/") return a / b; return 0; } bool is_operator(const string& op) { return op.size() == 1 && string("+-*/").find(op) != string::npos; } // recursive way int eval2(vector<string>& tokens) { int x, y; string token = tokens.back(); tokens.pop_back(); if(is_operator(token)) { y = eval2(tokens); x = eval2(tokens); if(token[0] == '+') x += y; if(token[0] == '-') x -= y; if(token[0] == '*') x *= y; if(token[0] == '/') x /= y; } else { size_t i; x = stoi(token, &i); } return x; } int main() { vector<string> v = { "7", "3", "/" }; cout << eval2(v) << endl; return 0; }
true
a906c311ce63827cc745c353d2350587f0e2431c
C++
KhanhMachinLearning/Coding-Inteview
/Amazon/PythagoreanTriplet.cpp
UTF-8
646
3.203125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; bool Check_Pythagrean_Triplet(int a[],int n); int main(){ int t; cin>>t; while(t--){ int n; cin>>n; int a[n]; for(int i=0;i<n;i++) cin>>a[i]; if(Check_Pythagrean_Triplet(a,n)) cout<<"Yes"<<endl; else cout<<"No"<<endl; } return 0; } bool Check_Pythagrean_Triplet(int a[],int n){ for(int i=0;i<n;i++) a[i] = a[i] * a[i]; sort(a,a+n); for(int i=n-1;i>=2;i--){ int l = 0; int r = i-1; while(l<r){ if((a[l] + a[r]) == a[i]) return true; (a[l] + a[r] > a[i]) ? r-- : l++; } } return true; }
true
7fe8576ed8532c7aae1618a9b8673a9e186e7268
C++
muhammadhasan01/lembar-contekan-HMF
/DS/Bit Fenwick Tree.cpp
UTF-8
426
2.625
3
[]
no_license
int BIT[1000], a[1000], n; void update(int x, int val){ for(; x<=n ; x+=x&-x){ BIT[x] += val; } } void update2(int x, int val){ for(; x<0 ; x|=(x+1)){ BIT[x] += val; } } int query(int x){ int sum = 0; for(; x>0 ; x-=x&-x){ sum += BIT[x]; } return sum; } int query2(int x){ int sum = 0; for(;x>=0;x=(x&(x+1))-1){ sum += BIT[x]; } return sum }
true
418cae285ecf0c28d6e4d4bd171c81786e1436d3
C++
DvnOshin/ACM_CONTEST_QUESTIONS
/Append_And_Delete.cpp
UTF-8
3,672
4
4
[]
no_license
You have a string of lowercase English alphabetic letters. You can perform two types of operations on the string: Append a lowercase English alphabetic letter to the end of the string. Delete the last character in the string. Performing this operation on an empty string results in an empty string. Given an integer, k, and two strings, s and t, determine whether or not you can convert s to t by performing exactly k of the above operations on s. If it's possible, print Yes. Otherwise, print No. For example, strings s=[a,b,c] and t=[d,e,f]. Our number of moves,k=6 . To convert s to t, we first delete all of the characters in 3 moves. Next we add each of the characters of t in order. On the 6th move, you will have the matching string. If there had been more moves available, they could have been eliminated by performing multiple deletions on an empty string. If there were fewer than 6 moves, we would not have succeeded in creating the new string. FUNCTION DESCRIPTION Complete the appendAndDelete function in the editor below. It should return a string, either Yes or No. appendAndDelete has the following parameter(s): s: the initial string t: the desired string k: an integer that represents the number of operations INPUT FORMAT The first line contains a string s, the initial string. The second line contains a string t, the desired final string. The third line contains an integer k, the number of operations. OUTPUT FORMAT Print Yes if you can obtain string t by performing exactly k operations on s. Otherwise, print No. SAMPLE INPUT 0 hackerhappy hackerrank 9 SAMPLE OUTPUT 0 Yes Explanation 0 We perform 5 delete operations to reduce string s to hacker. Next, we perform 4 append operations (i.e., r, a, n, and k), to get hackerrank. Because we were able to convert s to t by performing exactly k=9 operations, we print Yes. SAMPLE INPUT 1 ashley ash 2 SAMPLE OUTPUT 1 No EXPLANATION 1 To convert ashley to ash a minimum of 3 steps are needed. Hence we print No as answer. -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- #include<bits/stdc++.h> using namespace std; int main() { int k,l,i; string s,t; cin>>s>>t>>k; l=s.size()+t.size(); for(i=0;s[i]==t[i];i++); if((l-i*2<=k && l%2==k%2) || l<k) cout<<"Yes"; else cout<<"No"; return 0; } EXPLANATION TO THE CODE First, we try to find the minimum number of operations needed. For this, we check how large the largest common prefix of the two strings is; eg. if we have "hello" and "hellno", our largest common prefix is "hell". We compute the length of this prefix by for(i = 0; s[i] == t[i]; i++);. If we didn't have such a prefix, we'd have to first delete s.size() characters, then append t.size() characters (s.size() + t.size() = L steps in total). However, since we have a prefix of length i, we can skip i deletions and i additions. Therefore, we need at least L - 2*i operations in total. If k is smaller than that, we can return early. L <= k + i*2 checks this. Now, if (k - (L - 2 * i)) % 2 == 0 (which is equivalent to k%2 == L%2), we can first do L - 2*i operations to get the string t, and then just append a character and immediately remove it. Since (k - (L - 2 * i)) % 2 == 0 means that the difference between k and L - 2*i is even, this is always possible. There is one more special case; since remove("") == "", if we have k >= L, we can just do s.size() deletions, then another k - L deletions, and t.size() additions. In this special case, we can always find a way to convert s to t using k operations.
true
024f26035441a532f701af59b8c057d4b1ff2355
C++
RichardAth/Projects
/Int128/int128.h
UTF-8
64,322
2.859375
3
[]
no_license
#pragma once #undef _CRT_SECURE_NO_WARNINGS // prevent warning message #define _CRT_SECURE_NO_WARNINGS 1 typedef struct { uint64_t i[2]; } _S2; typedef struct { unsigned int i[4]; } _S4; typedef struct { unsigned short s[8]; } _S8; typedef struct { unsigned char b[16]; } _S16; #define HI64(n) (n).s2.i[1] #define LO64(n) (n).s2.i[0] /* declarations for asm functions For X64 architecture use Int128x64.asm */ extern "C" { void int128add(void *dst, const void *x); // dst += x void int128sub(void *dst, const void *x); // dst -= x void int128mul(void *dst, const void *x); // dst *= x void int128div(void *dst, void *x); // dst /= x void int128rem(void *dst, void *x); // dst %=x void int128neg(void *x); // x = -x void int128inc(void *x); // x++ void int128dec(void *x); // x-- void int128shr(void *x, int shft); // x >>= shft void int128shl(void *x, int shft); // x <<= shft int int128cmp(const void *x1, const void *x2); /* 3 way compare. return -ve, 0, or +ve */ /* separate unsigned versions are needed for the following: */ void uint128div(void *dst, const void *x); // dst /= x void uint128rem(void *dst, const void *x); // dst %=x void uint128shr(void *x, int shft); // x >>= shft int uint128cmp(const void *x1, const void *x2);/* 3 way compare. return -ve, 0, or +ve */ }; class _int128 { /* note that the there are no private fields */ public: union { _S2 s2; _S4 s4; _S8 s8; _S16 s16; }; // constructors inline _int128() {} inline _int128(const unsigned __int64 &n) { HI64(*this) = 0; LO64(*this) = n; } inline _int128(const __int64 &n) { HI64(*this) = n < 0 ? -1 : 0; LO64(*this) = n; } inline _int128(unsigned long n) { HI64(*this) = 0; LO64(*this) = n; } inline _int128(long n) { HI64(*this) = n < 0 ? -1 : 0; LO64(*this) = n; } inline _int128(unsigned int n) { HI64(*this) = 0; LO64(*this) = n; } inline _int128(int n) { HI64(*this) = n < 0 ? -1 : 0; LO64(*this) = n; } inline _int128(unsigned short n) { HI64(*this) = 0; LO64(*this) = n; } inline _int128(short n) { HI64(*this) = n < 0 ? -1 : 0; LO64(*this) = n; } explicit inline _int128(const unsigned __int64 &hi, const unsigned __int64 &lo) { HI64(*this) = hi; LO64(*this) = lo; } /* get approximate value in floating point */ double ToDouble() const { bool neg = false; _int128 absThis; if ((*this).isNegative()) { absThis = *this; int128neg(&absThis); // split into 2 statements to avoid error C2593 neg = true; } else absThis = *this; /* absThis = abs(*this). Sign is in neg */ double l = (double)LO64(absThis); if (HI64(absThis) != 0) { double h = (double)HI64(absThis); l += h * pow(2.0, 64); } if (!neg) return l; else return -l; } // type operators operator unsigned __int64() const { return LO64(*this); } operator __int64() const { return LO64(*this); } operator unsigned long() const { return (unsigned long)LO64(*this); } operator long() const { return (long)LO64(*this); } operator unsigned int() const { return (unsigned int)LO64(*this); } operator int() const { return (int)LO64(*this); } inline operator bool() const { return LO64(*this) || HI64(*this); } operator double() const { return this->ToDouble(); } // assign operators inline _int128 &operator++() { // prefix-form int128inc(this); return *this; } inline _int128 &operator--() { // prefix-form int128dec(this); return *this; } inline _int128 operator++(int) { // postfix-form const _int128 result(*this); int128inc(this); return result; } inline _int128 operator--(int) { // postfix-form const _int128 result(*this); int128dec(this); return result; } inline bool isNegative() const { return ((int)s4.i[3] < 0); } inline bool isZero() const { return LO64(*this) == 0 && HI64(*this) == 0; } /* count number of bits set */ int popcnt() const { auto u = (int)__popcnt64(HI64(*this)); // count 1-bits in top half auto l = (int)__popcnt64(LO64(*this)); // count 1-bits in bottom half return (int)u + l; /* return total 1 bits */ } /* get bit number of most significant 1 bit bits are numbered from 0 to 127 */ int msb() const { DWORD index; if (HI64(*this) != 0) { auto rv = _BitScanReverse64(&index, HI64(*this)); return index + 64; } else if (LO64(*this) != 0) { auto rv = _BitScanReverse64(&index, LO64(*this)); return index; } else return -1; } /* get bit number of least significant 1 bit bits are numbered from 0 to 127 */ int lsb() const { DWORD index; if (LO64(*this) != 0) { auto rv = _BitScanForward64(&index, LO64(*this)); return index; } else if (HI64(*this) != 0) { auto rv = _BitScanForward64(&index, HI64(*this)); return index + 64; } else return -1; } }; class _uint128 { public: union { _S2 s2; _S4 s4; _S8 s8; _S16 s16; }; // constructors inline _uint128() {} inline _uint128(const _int128 &n) { HI64(*this) = HI64(n); LO64(*this) = LO64(n); } inline _uint128(const unsigned __int64 &n) { HI64(*this) = 0; LO64(*this) = n; } inline _uint128(const __int64 &n) { HI64(*this) = n < 0 ? -1 : 0; LO64(*this) = n; } inline _uint128(unsigned long n) { HI64(*this) = 0; LO64(*this) = n; } inline _uint128(long n) { HI64(*this) = n < 0 ? -1 : 0; LO64(*this) = n; } inline _uint128(unsigned int n) { HI64(*this) = 0; LO64(*this) = n; } inline _uint128(int n) { HI64(*this) = n < 0 ? -1 : 0; LO64(*this) = n; } inline _uint128(unsigned short n) { HI64(*this) = n < 0 ? -1 : 0; LO64(*this) = n; } inline _uint128(short n) { HI64(*this) = n < 0 ? -1 : 0; LO64(*this) = n; } inline _uint128(const unsigned __int64 &hi, const unsigned __int64 &lo) { HI64(*this) = hi; LO64(*this) = lo; } /* get approximate value in floating point */ double toDouble() const { double l = (double)LO64(*this); if (HI64(*this) != 0) { double h = (double)HI64(*this); return h * pow(2.0, 64) + l; } else return l; } // type operators inline operator _int128() const { return *(_int128*)(void*)this; } inline operator unsigned __int64() const { return LO64(*this); } inline operator __int64() const { return LO64(*this); } inline operator unsigned long() const { return (unsigned long)LO64(*this); } inline operator long() const { return (long)LO64(*this); } inline operator unsigned int() const { return (unsigned int)LO64(*this); } inline operator int() const { return (int)LO64(*this); } inline operator bool() const { return LO64(*this) || HI64(*this); } inline operator double() const { return this->toDouble(); } inline _uint128 &operator++() { // prefix-form int128inc(this); return *this; } inline _uint128 &operator--() { // prefix-form int128dec(this); return *this; } inline _uint128 operator++(int) { // postfix-form const _uint128 result(*this); int128inc(this); return result; } inline _uint128 operator--(int) { // postfix-form const _uint128 result(*this); int128dec(this); return result; } inline bool isNegative() const { return false; } inline bool isZero() const { return LO64(*this) == 0 && HI64(*this) == 0; } /* count number of bits set */ int popcnt() const { auto u = (int)__popcnt64(HI64(*this)); // count 1-bits in top half auto l = (int)__popcnt64(LO64(*this)); // count 1-bits in bottom half return (int)u + l; /* return total 1 bits */ } /* get bit number of most significant 1 bit bits are numbered from 0 to 127 */ int msb() const { DWORD index; if (HI64(*this) != 0) { auto rv = _BitScanReverse64(&index, HI64(*this)); return index + 64; } else if (LO64(*this) != 0) { auto rv = _BitScanReverse64(&index, LO64(*this)); return index; } else return -1; // indicate no bits set } /* get bit number of least significant 1 bit bits are numbered from 0 to 127 */ int lsb() const { DWORD index; if (LO64(*this) != 0) { auto rv = _BitScanForward64(&index, LO64(*this)); return index; } else if (HI64(*this) != 0) { auto rv = _BitScanForward64(&index, HI64(*this)); return index + 64; } else return -1; // indicate no bits set } }; // 4 version of all 5 binary arithmetic operators, // 3 binary logical operators and 6 compare-operators // signed op signed // signed op unsigned // unsigned op signed // unsigned op unsigned // For +, -, *, &, |, ^, ==, != the called function is the same // regardless of signed/unsigned combinations. // For /, %, <, >, <=, >= however the signed function is used // only for the "signed op signed" combination. // For left shift (<<) there is no difference for // signed and unsigned function, but for right shift (>>) // the leftmost bit (bit 127) indicates the sign, and will // be copied to all new bits comming in from left for _int128 // and 0-bits will be shifted in for _uint128 (because there // is no sign). // For assign-operators (+=,-=...) the same rules apply. // Versions for built in integral types are then defined // on top of these /* 4 basic combination of operator + (128-bit integers - don't care about signed/unsigned) changed to use _addcarry_u64 intrinsic when it's faster. */ inline _int128 operator + (const _int128 &lft, const _int128 &rhs) { /*_int128 result(lft); int128add(&result, &rhs);*/ _int128 result; auto c = _addcarry_u64(0, LO64(lft), LO64(rhs), &LO64(result)); auto c2 = _addcarry_u64(c, HI64(lft), HI64(rhs), &HI64(result)); /* if c2 does not match the sign bit we have an overflow */ return result; } /* changed to follow normal rule that when signed and and unsigned ints of the same size are combined the result is unsigned */ inline _uint128 operator + (const _int128 &lft, const _uint128 &rhs) { //_int128 result(lft); //int128add(&result, &rhs); _uint128 result; auto c = _addcarry_u64(0, LO64(lft), LO64(rhs), &LO64(result)); auto c2 = _addcarry_u64(c, HI64(lft), HI64(rhs), &HI64(result)); /* if c2 !=0 we have an overflow */ return result; } inline _uint128 operator + (const _uint128 &lft, const _int128 &rhs) { /*_uint128 result(lft); int128add(&result, &rhs);*/ _uint128 result; auto c = _addcarry_u64(0, LO64(lft), LO64(rhs), &LO64(result)); auto c2 = _addcarry_u64(c, HI64(lft), HI64(rhs), &HI64(result)); /* if c2 !=0 we have an overflow */ return result; } inline _uint128 operator + (const _uint128 &lft, const _uint128 &rhs) { /*_uint128 result(lft); int128add(&result, &rhs);*/ _uint128 result; auto c = _addcarry_u64(0, LO64(lft), LO64(rhs), &LO64(result)); auto c2 = _addcarry_u64(c, HI64(lft), HI64(rhs), &HI64(result)); /* if c2 !=0 we have an overflow */ return result; } // 4 basic combination of operator - (128-bit integers - don't care about signed/unsigned) inline _int128 operator - (const _int128 &lft, const _int128 &rhs) { _int128 result(lft); int128sub(&result, &rhs); return result; } inline _int128 operator - (const _int128 &lft, const _uint128 &rhs) { _int128 result(lft); int128sub(&result, &rhs); return result; } inline _uint128 operator - (const _uint128 &lft, const _int128 &rhs) { _uint128 result(lft); int128sub(&result, &rhs); return result; } inline _uint128 operator - (const _uint128 &lft, const _uint128 &rhs) { _uint128 result(lft); int128sub(&result, &rhs); return result; } // 4 basic combination of operator * (128-bit integers - don't care about signed/unsigned) inline _int128 operator * (const _int128 &lft, const _int128 &rhs) { _int128 result(lft); int128mul(&result, &rhs); return result; } inline _int128 operator * (const _int128 &lft, const _uint128 &rhs) { _int128 result(lft); int128mul(&result, &rhs); return result; } inline _uint128 operator * (const _uint128 &lft, const _int128 &rhs) { _uint128 result(lft); int128mul(&result, &rhs); return result; } inline _uint128 operator * (const _uint128 &lft, const _uint128 &rhs) { _uint128 result(lft); int128mul(&result, &rhs); return result; } // 4 basic combination of operator / - signed division only if both are signed inline _int128 operator / (const _int128 &lft, const _int128 &rhs) { _int128 result(lft), tmp(rhs); if (tmp.isZero()) throw std::exception("divide by zero"); int128div(&result, &tmp); return result; } inline _uint128 operator / (const _int128 &lft, const _uint128 &rhs) { _uint128 result(lft); if (rhs.isZero()) throw std::exception("divide by zero"); uint128div(&result, &rhs); return result; } inline _uint128 operator / (const _uint128 &lft, const _int128 &rhs) { _uint128 result(lft); if (rhs.isZero()) throw std::exception("divide by zero"); uint128div(&result, &rhs); return result; } inline _uint128 operator / (const _uint128 &lft, const _uint128 &rhs) { _uint128 result(lft); if (rhs.isZero()) throw std::exception("divide by zero"); uint128div(&result, &rhs); return result; } // 4 basic combination of operator% - signed % only if lft is signed // differs from C/C++ standards in that int%unsigned returns (signed) int inline _int128 operator % (const _int128 &lft, const _int128 &rhs) { _int128 result(lft), tmp(rhs); if (rhs.isZero()) throw std::exception("divide by zero"); int128rem(&result, &tmp); return result; } inline _int128 operator % (const _int128 &lft, const _uint128 &rhs) { _int128 result(lft); if (rhs.isZero()) throw std::exception("divide by zero"); uint128rem(&result, &rhs); return result; } inline _uint128 operator % (const _uint128 &lft, const _int128 &rhs) { _uint128 result(lft); if (rhs.isZero()) throw std::exception("divide by zero"); uint128rem(&result, &rhs); return result; } inline _uint128 operator % (const _uint128 &lft, const _uint128 &rhs) { _uint128 result(lft); if (rhs.isZero()) throw std::exception("divide by zero"); uint128rem(&result, &rhs); return result; } // 2 version of unary - (don't care about signed/unsigned) inline _int128 operator - (const _int128 &x) { // unary minus _int128 result(x); int128neg(&result); return result; } inline _uint128 operator - (const _uint128 &x) { _uint128 result; result = x; // value of result is such that result+x = 0 int128neg(&result); // even though they are both unsigned return result; // (overflow would occur) } // Basic bit operators // 4 basic combinations of operator & (bitwise AND) inline _int128 operator & (const _int128 &lft, const _int128 &rhs) { return _int128(HI64(lft) & HI64(rhs), LO64(lft) & LO64(rhs)); } inline _int128 operator & (const _int128 &lft, const _uint128 &rhs) { return _int128(HI64(lft) & HI64(rhs), LO64(lft) & LO64(rhs)); } inline _uint128 operator & (const _uint128 &lft, const _int128 &rhs) { return _uint128(HI64(lft) & HI64(rhs), LO64(lft) & LO64(rhs)); } inline _uint128 operator & (const _uint128 &lft, const _uint128 &rhs) { return _int128(HI64(lft) & HI64(rhs), LO64(lft) & LO64(rhs)); } // 4 basic combinations of operator | (inclusive OR) inline _int128 operator | (const _int128 &lft, const _int128 &rhs) { return _int128(HI64(lft) | HI64(rhs), LO64(lft) | LO64(rhs)); } inline _int128 operator | (const _int128 &lft, const _uint128 &rhs) { return _int128(HI64(lft) | HI64(rhs), LO64(lft) | LO64(rhs)); } inline _uint128 operator | (const _uint128 &lft, const _int128 &rhs) { return _uint128(HI64(lft) | HI64(rhs), LO64(lft) | LO64(rhs)); } inline _uint128 operator | (const _uint128 &lft, const _uint128 &rhs) { return _uint128(HI64(lft) | HI64(rhs), LO64(lft) | LO64(rhs)); } // 4 basic combinations of operator ^ (bitwise XOR) inline _int128 operator ^ (const _int128 &lft, const _int128 &rhs) { return _int128(HI64(lft) ^ HI64(rhs), LO64(lft) ^ LO64(rhs)); } inline _int128 operator ^ (const _int128 &lft, const _uint128 &rhs) { return _int128(HI64(lft) ^ HI64(rhs), LO64(lft) ^ LO64(rhs)); } inline _uint128 operator ^ (const _uint128 &lft, const _int128 &rhs) { return _uint128(HI64(lft) ^ HI64(rhs), LO64(lft) ^ LO64(rhs)); } inline _uint128 operator ^ (const _uint128 &lft, const _uint128 &rhs) { return _uint128(HI64(lft) ^ HI64(rhs), LO64(lft) ^ LO64(rhs)); } // 2 versions of operator ~ inline _int128 operator ~ (const _int128 &n) { return _int128(~HI64(n), ~LO64(n)); } inline _uint128 operator ~ (const _uint128 &n) { return _uint128(~HI64(n), ~LO64(n)); } // 2 version of operator >> (arithmetic shift for signed, logical shift for unsigned) inline _int128 operator >> (const _int128 &lft, const int shft) { _int128 copy(lft); if (shft != 0) int128shr(&copy, shft); return copy; } inline _uint128 operator >> (const _uint128 &lft, const int shft) { _uint128 copy(lft); if (shft != 0) uint128shr(&copy, shft); return copy; } // 2 version of operator << (dont care about signed/unsigned) inline _int128 operator << (const _int128 &lft, const int shft) { _int128 copy(lft); if (shft != 0) int128shl(&copy, shft); return copy; } inline _int128 operator << (const _uint128 &lft, const int shft) { _uint128 copy(lft); if (shft != 0) int128shl(&copy, shft); return copy; } // 4 basic combinations of operator ==. (don't care about signed/unsigned) inline bool operator == (const _int128 &lft, const _int128 &rhs) { return (LO64(lft) == LO64(rhs)) && (HI64(lft) == HI64(rhs)); } inline bool operator == (const _int128 &lft, const _uint128 &rhs) { return (LO64(lft) == LO64(rhs)) && (HI64(lft) == HI64(rhs)); } inline bool operator == (const _uint128 &lft, const _int128 &rhs) { return (LO64(lft) == LO64(rhs)) && (HI64(lft) == HI64(rhs)); } inline bool operator == (const _uint128 &lft, const _uint128 &rhs) { return (LO64(lft) == LO64(rhs)) && (HI64(lft) == HI64(rhs)); } // 4 basic combinations of operator != (don't care about signed/unsigned) inline bool operator != (const _int128 &lft, const _int128 &rhs) { return (LO64(lft) != LO64(rhs)) || (HI64(lft) != HI64(rhs)); } inline bool operator != (const _int128 &lft, const _uint128 &rhs) { return (LO64(lft) != LO64(rhs)) || (HI64(lft) != HI64(rhs)); } inline bool operator != (const _uint128 &lft, const _int128 &rhs) { return (LO64(lft) != LO64(rhs)) || (HI64(lft) != HI64(rhs)); } inline bool operator != (const _uint128 &lft, const _uint128 &rhs) { return (LO64(lft) != LO64(rhs)) || (HI64(lft) != HI64(rhs)); } // 4 basic combinations of operator > (signed compare only if both are signed) inline bool operator > (const _int128 &lft, const _int128 &rhs) { return int128cmp(&lft, &rhs) > 0; } inline bool operator > (const _int128 &lft, const _uint128 &rhs) { return uint128cmp(&lft, &rhs) > 0; } inline bool operator > (const _uint128 &lft, const _int128 &rhs) { return uint128cmp(&lft, &rhs) > 0; } inline bool operator > (const _uint128 &lft, const _uint128 &rhs) { return uint128cmp(&lft, &rhs) > 0; } // 4 basic combinations of operator >= (signed compare only if both are signed) inline bool operator >= (const _int128 &lft, const _int128 &rhs) { return int128cmp(&lft, &rhs) >= 0; } inline bool operator >= (const _int128 &lft, const _uint128 &rhs) { return uint128cmp(&lft, &rhs) >= 0; } inline bool operator >= (const _uint128 &lft, const _int128 &rhs) { return uint128cmp(&lft, &rhs) >= 0; } inline bool operator >= (const _uint128 &lft, const _uint128 &rhs) { return uint128cmp(&lft, &rhs) >= 0; } // 4 basic combinations of operator < (signed compare only if both are signed) inline bool operator < (const _int128 &lft, const _int128 &rhs) { return int128cmp(&lft, &rhs) < 0; } inline bool operator < (const _int128 &lft, const _uint128 &rhs) { return uint128cmp(&lft, &rhs) < 0; } inline bool operator < (const _uint128 &lft, const _int128 &rhs) { return uint128cmp(&lft, &rhs) < 0; } inline bool operator < (const _uint128 &lft, const _uint128 &rhs) { return uint128cmp(&lft, &rhs) < 0; } // 4 basic combinations of operator <= (signed compare only if both are signed) inline bool operator <= (const _int128 &lft, const _int128 &rhs) { return int128cmp(&lft, &rhs) <= 0; } inline bool operator <= (const _int128 &lft, const _uint128 &rhs) { return uint128cmp(&lft, &rhs) <= 0; } inline bool operator <= (const _uint128 &lft, const _int128 &rhs) { return uint128cmp(&lft, &rhs) <= 0; } inline bool operator <= (const _uint128 &lft, const _uint128 &rhs) { return uint128cmp(&lft, &rhs) <= 0; } // Assign operators // operator += (don't care about sign) inline _int128 &operator += (_int128 &lft, const _int128 &rhs) { /*int128add(&lft, &rhs);*/ auto c = _addcarry_u64(0, LO64(lft), LO64(rhs), &LO64(lft)); auto c2 = _addcarry_u64(c, HI64(lft), HI64(rhs), &HI64(lft)); /* if c2 does not match the sign bit we have an overflow */ return lft; } inline _int128 &operator += (_int128 &lft, const _uint128 &rhs) { //int128add(&lft, &rhs); auto c = _addcarry_u64(0, LO64(lft), LO64(rhs), &LO64(lft)); auto c2 = _addcarry_u64(c, HI64(lft), HI64(rhs), &HI64(lft)); /* if c2 does not match the sign bit we have an overflow */ return lft; } inline _uint128 &operator += (_uint128 &lft, const _int128 &rhs) { //int128add(&lft, &rhs); auto c = _addcarry_u64(0, LO64(lft), LO64(rhs), &LO64(lft)); auto c2 = _addcarry_u64(c, HI64(lft), HI64(rhs), &HI64(lft)); /* if c2 is not 0 we have an overflow */ return lft; } inline _uint128 &operator += (_uint128 &lft, const _uint128 &rhs) { //int128add(&lft, &rhs); auto c = _addcarry_u64(0, LO64(lft), LO64(rhs), &LO64(lft)); auto c2 = _addcarry_u64(c, HI64(lft), HI64(rhs), &HI64(lft)); /* if c2 is not 0 we have an overflow */ return lft; } // operator -= (don't care about sign) inline _int128 &operator -= (_int128 &lft, const _int128 &rhs) { int128sub(&lft, &rhs); return lft; } inline _int128 &operator -= (_int128 &lft, const _uint128 &rhs) { int128sub(&lft, &rhs); return lft; } inline _uint128 &operator -= (_uint128 &lft, const _int128 &rhs) { int128sub(&lft, &rhs); return lft; } inline _uint128 &operator -= (_uint128 &lft, const _uint128 &rhs) { int128sub(&lft, &rhs); return lft; } // operator *= (don't care about sign) inline _int128 &operator *= (_int128 &lft, const _int128 &rhs) { int128mul(&lft, &rhs); return lft; } inline _int128 &operator *= (_int128 &lft, const _uint128 &rhs) { int128mul(&lft, &rhs); return lft; } inline _uint128 &operator *= (_uint128 &lft, const _int128 &rhs) { int128mul(&lft, &rhs); return lft; } inline _uint128 &operator *= (_uint128 &lft, const _uint128 &rhs) { int128mul(&lft, &rhs); return lft; } // operator /= (use signed div only if both are signed) inline _int128 &operator /= (_int128 &lft, const _int128 &rhs) { _int128 tmp(rhs); if (rhs.isZero()) throw std::exception("divide by zero"); int128div(&lft, &tmp); return lft; } inline _int128 &operator /= (_int128 &lft, const _uint128 &rhs) { if (rhs.isZero()) throw std::exception("divide by zero"); uint128div(&lft, &rhs); return lft; } inline _uint128 &operator /= (_uint128 &lft, const _int128 &rhs) { if (rhs.isZero()) throw std::exception("divide by zero"); uint128div(&lft, &rhs); return lft; } inline _uint128 &operator /= (_uint128 &lft, const _uint128 &rhs) { if (rhs.isZero()) throw std::exception("divide by zero"); uint128div(&lft, &rhs); return lft; } // operator %= (use signed % only if both are signed) inline _int128 &operator %= (_int128 &lft, const _int128 &rhs) { _int128 tmp(rhs); if (rhs.isZero()) throw std::exception("divide by zero"); int128rem(&lft, &tmp); return lft; } inline _int128 &operator %= (_int128 &lft, const _uint128 &rhs) { if (rhs.isZero()) throw std::exception("divide by zero"); uint128rem(&lft, &rhs); return lft; } inline _uint128 &operator %= (_uint128 &lft, const _int128 &rhs) { if (rhs.isZero()) throw std::exception("divide by zero"); uint128rem(&lft, &rhs); return lft; } inline _uint128 &operator %= (_uint128 &lft, const _uint128 &rhs) { if (rhs.isZero()) throw std::exception("divide by zero"); uint128rem(&lft, &rhs); return lft; } // operator &= (don't care about sign) inline _int128 &operator &= (_int128 &lft, const _int128 &rhs) { LO64(lft) &= LO64(rhs); HI64(lft) &= HI64(rhs); return lft; } inline _int128 &operator &= (_int128 &lft, const _uint128 &rhs) { LO64(lft) &= LO64(rhs); HI64(lft) &= HI64(rhs); return lft; } inline _uint128 &operator &= (_uint128 &lft, const _int128 &rhs) { LO64(lft) &= LO64(rhs); HI64(lft) &= HI64(rhs); return lft; } inline _uint128 &operator &= (_uint128 &lft, const _uint128 &rhs) { LO64(lft) &= LO64(rhs); HI64(lft) &= HI64(rhs); return lft; } // operator |= (don't care about sign) inline _int128 &operator |= (_int128 &lft, const _int128 &rhs) { LO64(lft) |= LO64(rhs); HI64(lft) |= HI64(rhs); return lft; } inline _int128 &operator |= (_int128 &lft, const _uint128 &rhs) { LO64(lft) |= LO64(rhs); HI64(lft) |= HI64(rhs); return lft; } inline _uint128 &operator |= (_uint128 &lft, const _int128 &rhs) { LO64(lft) |= LO64(rhs); HI64(lft) |= HI64(rhs); return lft; } inline _uint128 &operator |= (_uint128 &lft, const _uint128 &rhs) { LO64(lft) |= LO64(rhs); HI64(lft) |= HI64(rhs); return lft; } // operator ^= (don't care about sign) inline _int128 &operator ^= (_int128 &lft, const _int128 &rhs) { LO64(lft) ^= LO64(rhs); HI64(lft) ^= HI64(rhs); return lft; } inline _int128 &operator ^= (_int128 &lft, const _uint128 &rhs) { LO64(lft) ^= LO64(rhs); HI64(lft) ^= HI64(rhs); return lft; } inline _uint128 &operator ^= (_uint128 &lft, const _int128 &rhs) { LO64(lft) ^= LO64(rhs); HI64(lft) ^= HI64(rhs); return lft; } inline _uint128 &operator ^= (_uint128 &lft, const _uint128 &rhs) { LO64(lft) ^= LO64(rhs); HI64(lft) ^= HI64(rhs); return lft; } inline _int128 &operator >>= (_int128 &lft, int shft) { if (shft != 0) int128shr(&lft, shft); return lft; } inline _uint128 &operator >>= (_uint128 &lft, const int shft) { if (shft != 0) { uint128shr(&lft, shft); } return lft; } inline _int128 &operator <<= (_int128 &lft, int shft) { if (shft != 0) int128shl(&lft, shft); return lft; } inline _uint128 &operator <<= (_uint128 &lft, int shft) { if (shft != 0) int128shl(&lft, shft); return lft; } // Now all combinations of binary operators for lft = 128-bit and rhs is // integral type // operator + for built in integral types as second argument inline _int128 operator+(const _int128 &lft, __int64 rhs) { return lft + (_int128)rhs; } inline _int128 operator+(const _int128 &lft, unsigned __int64 rhs) { return lft + (_uint128)rhs; } inline _int128 operator+(const _int128 &lft, long rhs) { return lft + (_int128)rhs; } inline _int128 operator+(const _int128 &lft, unsigned long rhs) { return lft + (_uint128)rhs; } inline _int128 operator+(const _int128 &lft, int rhs) { return lft + (_int128)rhs; } inline _int128 operator+(const _int128 &lft, unsigned int rhs) { return lft + (_uint128)rhs; } inline _int128 operator+(const _int128 &lft, short rhs) { return lft + (_int128)rhs; } inline _int128 operator+(const _int128 &lft, unsigned short rhs) { return lft + (_uint128)rhs; } inline _uint128 operator+(const _uint128 &lft, unsigned __int64 rhs) { //return lft + (_uint128)rhs; _uint128 sum; auto c = _addcarry_u64(0, LO64(lft), rhs, &LO64(sum)); HI64(sum) = HI64(lft) + c; return sum; } inline _uint128 operator+(const _uint128 &lft, __int64 rhs) { return lft + (_int128)rhs; } inline _uint128 operator+(const _uint128 &lft, long rhs) { return lft + (_int128)rhs; } inline _uint128 operator+(const _uint128 &lft, unsigned long rhs) { //return lft + (_uint128)rhs; _uint128 sum; auto c = _addcarry_u64(0, LO64(lft), rhs, &LO64(sum)); HI64(sum) = HI64(lft) + c; return sum; } inline _uint128 operator+(const _uint128 &lft, int rhs) { return lft + (_int128)rhs; } inline _uint128 operator+(const _uint128 &lft, unsigned int rhs) { //return lft + (_uint128)rhs; _uint128 sum; auto c = _addcarry_u64(0, LO64(lft), rhs, &LO64(sum)); HI64(sum) = HI64(lft) + c; return sum; } inline _uint128 operator+(const _uint128 &lft, short rhs) { return lft + (_int128)rhs; } inline _uint128 operator+(const _uint128 &lft, unsigned short rhs) { //return lft + (_uint128)rhs; _uint128 sum; auto c = _addcarry_u64(0, LO64(lft), rhs, &LO64(sum)); HI64(sum) = HI64(lft) + c; return sum; } // operator - for built in integral types as second argument inline _int128 operator-(const _int128 &lft, __int64 rhs) { return lft - (_int128)rhs; } inline _int128 operator-(const _int128 &lft, unsigned __int64 rhs) { return lft - (_uint128)rhs; } inline _int128 operator-(const _int128 &lft, long rhs) { return lft - (_int128)rhs; } inline _int128 operator-(const _int128 &lft, unsigned long rhs) { return lft - (_uint128)rhs; } inline _int128 operator-(const _int128 &lft, int rhs) { return lft - (_int128)rhs; } inline _int128 operator-(const _int128 &lft, unsigned int rhs) { return lft - (_uint128)rhs; } inline _int128 operator-(const _int128 &lft, short rhs) { return lft - (_int128)rhs; } inline _int128 operator-(const _int128 &lft, unsigned short rhs) { return lft - (_uint128)rhs; } inline _uint128 operator-(const _uint128 &lft, __int64 rhs) { return lft - (_int128)rhs; } inline _uint128 operator-(const _uint128 &lft, unsigned __int64 rhs) { return lft - (_uint128)rhs; } inline _uint128 operator-(const _uint128 &lft, long rhs) { return lft - (_int128)rhs; } inline _uint128 operator-(const _uint128 &lft, unsigned long rhs) { return lft - (_uint128)rhs; } inline _uint128 operator-(const _uint128 &lft, int rhs) { return lft - (_int128)rhs; } inline _uint128 operator-(const _uint128 &lft, unsigned int rhs) { return lft - (_uint128)rhs; } inline _uint128 operator-(const _uint128 &lft, short rhs) { return lft - (_int128)rhs; } inline _uint128 operator-(const _uint128 &lft, unsigned short rhs) { return lft - (_uint128)rhs; } // operator * for built in integral types as second argument inline _int128 operator*(const _int128 &lft, __int64 rhs) { return lft * (_int128)rhs; } inline _int128 operator*(const _int128 &lft, unsigned __int64 rhs) { return lft * (_uint128)rhs; } inline _int128 operator*(const _int128 &lft, long rhs) { return lft * (_int128)rhs; } inline _int128 operator*(const _int128 &lft, unsigned long rhs) { return lft * (_uint128)rhs; } inline _int128 operator*(const _int128 &lft, int rhs) { return lft * (_int128)rhs; } inline _int128 operator*(const _int128 &lft, unsigned int rhs) { return lft * (_uint128)rhs; } inline _int128 operator*(const _int128 &lft, short rhs) { return lft * (_int128)rhs; } inline _int128 operator*(const _int128 &lft, unsigned short rhs) { return lft * (_uint128)rhs; } inline _uint128 operator*(const _uint128 &lft, __int64 rhs) { return lft * (_int128)rhs; } inline _uint128 operator*(const _uint128 &lft, unsigned __int64 rhs) { return lft * (_uint128)rhs; } inline _uint128 operator*(const _uint128 &lft, long rhs) { return lft * (_int128)rhs; } inline _uint128 operator*(const _uint128 &lft, unsigned long rhs) { return lft * (_uint128)rhs; } inline _uint128 operator*(const _uint128 &lft, int rhs) { return lft * (_int128)rhs; } inline _uint128 operator*(const _uint128 &lft, unsigned int rhs) { return lft * (_uint128)rhs; } inline _uint128 operator*(const _uint128 &lft, short rhs) { return lft * (_int128)rhs; } inline _uint128 operator*(const _uint128 &lft, unsigned short rhs) { return lft * (_uint128)rhs; } // operator / for built in integral types as second argument inline _int128 operator/(const _int128 &lft, __int64 rhs) { return lft / (_int128)rhs; } inline _int128 operator/(const _int128 &lft, unsigned __int64 rhs) { return lft / (_int128)rhs; } inline _int128 operator/(const _int128 &lft, long rhs) { return lft / (_int128)rhs; } inline _int128 operator/(const _int128 &lft, unsigned long rhs) { return lft / (_int128)rhs; } inline _int128 operator/(const _int128 &lft, int rhs) { return lft / (_int128)rhs; } inline _int128 operator/(const _int128 &lft, unsigned int rhs) { return lft / (_int128)rhs; } inline _int128 operator/(const _int128 &lft, short rhs) { return lft / (_int128)rhs; } inline _int128 operator/(const _int128 &lft, unsigned short rhs) { return lft / (_int128)rhs; } inline _uint128 operator/(const _uint128 &lft, __int64 rhs) { return lft / (_int128)rhs; } inline _uint128 operator/(const _uint128 &lft, unsigned __int64 rhs) { return lft / (_uint128)rhs; } inline _uint128 operator/(const _uint128 &lft, long rhs) { return lft / (_int128)rhs; } inline _uint128 operator/(const _uint128 &lft, unsigned long rhs) { return lft / (_uint128)rhs; } inline _uint128 operator/(const _uint128 &lft, int rhs) { return lft / (_int128)rhs; } inline _uint128 operator/(const _uint128 &lft, unsigned int rhs) { return lft / (_uint128)rhs; } inline _uint128 operator/(const _uint128 &lft, short rhs) { return lft / (_int128)rhs; } inline _uint128 operator/(const _uint128 &lft, unsigned short rhs) { return lft / (_uint128)rhs; } // operator % for built in integral types as second argument inline _int128 operator%(const _int128 &lft, __int64 rhs) { return lft % (_int128)rhs; } inline _int128 operator%(const _int128 &lft, unsigned __int64 rhs) { return lft % (_int128)rhs; } inline _int128 operator%(const _int128 &lft, long rhs) { return lft % (_int128)rhs; } inline _int128 operator%(const _int128 &lft, unsigned long rhs) { return lft % (_int128)rhs; } inline _int128 operator%(const _int128 &lft, int rhs) { return lft % (_int128)rhs; } inline _int128 operator%(const _int128 &lft, unsigned int rhs) { return lft % (_int128)rhs; } inline _int128 operator%(const _int128 &lft, short rhs) { return lft % (_int128)rhs; } inline _int128 operator%(const _int128 &lft, unsigned short rhs) { return lft % (_int128)rhs; } inline _uint128 operator%(const _uint128 &lft, __int64 rhs) { return lft % (_int128)rhs; } inline _uint128 operator%(const _uint128 &lft, unsigned __int64 rhs) { return lft % (_uint128)rhs; } inline _uint128 operator%(const _uint128 &lft, long rhs) { return lft % (_int128)rhs; } inline _uint128 operator%(const _uint128 &lft, unsigned long rhs) { return lft % (_uint128)rhs; } inline _uint128 operator%(const _uint128 &lft, int rhs) { return lft % (_int128)rhs; } inline _uint128 operator%(const _uint128 &lft, unsigned int rhs) { return lft % (_uint128)rhs; } inline _uint128 operator%(const _uint128 &lft, short rhs) { return lft % (_int128)rhs; } inline _uint128 operator%(const _uint128 &lft, unsigned short rhs) { return lft % (_uint128)rhs; } // operator & for built in integral types as second argument inline _int128 operator&(const _int128 &lft, __int64 rhs) { return lft & (_int128)rhs; } inline _int128 operator&(const _int128 &lft, unsigned __int64 rhs) { return lft & (_int128)rhs; } inline _int128 operator&(const _int128 &lft, long rhs) { return lft & (_int128)rhs; } inline _int128 operator&(const _int128 &lft, unsigned long rhs) { return lft & (_int128)rhs; } inline _int128 operator&(const _int128 &lft, int rhs) { return lft & (_int128)rhs; } inline _int128 operator&(const _int128 &lft, unsigned int rhs) { return lft & (_int128)rhs; } inline _int128 operator&(const _int128 &lft, short rhs) { return lft & (_int128)rhs; } inline _int128 operator&(const _int128 &lft, unsigned short rhs) { return lft & (_int128)rhs; } inline _uint128 operator&(const _uint128 &lft, __int64 rhs) { return lft & (_int128)rhs; } inline _uint128 operator&(const _uint128 &lft, unsigned __int64 rhs) { return lft & (_uint128)rhs; } inline _uint128 operator&(const _uint128 &lft, long rhs) { return lft & (_int128)rhs; } inline _uint128 operator&(const _uint128 &lft, unsigned long rhs) { return lft & (_uint128)rhs; } inline _uint128 operator&(const _uint128 &lft, int rhs) { return lft & (_int128)rhs; } inline _uint128 operator&(const _uint128 &lft, unsigned int rhs) { return lft & (_uint128)rhs; } inline _uint128 operator&(const _uint128 &lft, short rhs) { return lft & (_int128)rhs; } inline _uint128 operator&(const _uint128 &lft, unsigned short rhs) { return lft & (_uint128)rhs; } // operator | for built in integral types as second argument inline _int128 operator|(const _int128 &lft, __int64 rhs) { return lft | (_int128)rhs; } inline _int128 operator|(const _int128 &lft, unsigned __int64 rhs) { return lft | (_int128)rhs; } inline _int128 operator|(const _int128 &lft, long rhs) { return lft | (_int128)rhs; } inline _int128 operator|(const _int128 &lft, unsigned long rhs) { return lft | (_int128)rhs; } inline _int128 operator|(const _int128 &lft, int rhs) { return lft | (_int128)rhs; } inline _int128 operator|(const _int128 &lft, unsigned int rhs) { return lft | (_int128)rhs; } inline _int128 operator|(const _int128 &lft, short rhs) { return lft | (_int128)rhs; } inline _int128 operator|(const _int128 &lft, unsigned short rhs) { return lft | (_int128)rhs; } inline _uint128 operator|(const _uint128 &lft, __int64 rhs) { return lft | (_int128)rhs; } inline _uint128 operator|(const _uint128 &lft, unsigned __int64 rhs) { return lft | (_uint128)rhs; } inline _uint128 operator|(const _uint128 &lft, long rhs) { return lft | (_int128)rhs; } inline _uint128 operator|(const _uint128 &lft, unsigned long rhs) { return lft | (_uint128)rhs; } inline _uint128 operator|(const _uint128 &lft, int rhs) { return lft | (_int128)rhs; } inline _uint128 operator|(const _uint128 &lft, unsigned int rhs) { return lft | (_uint128)rhs; } inline _uint128 operator|(const _uint128 &lft, short rhs) { return lft | (_int128)rhs; } inline _uint128 operator|(const _uint128 &lft, unsigned short rhs) { return lft | (_uint128)rhs; } // operator ^ for built in integral types as second argument inline _int128 operator^(const _int128 &lft, __int64 rhs) { return lft ^ (_int128)rhs; } inline _int128 operator^(const _int128 &lft, unsigned __int64 rhs) { return lft ^ (_int128)rhs; } inline _int128 operator^(const _int128 &lft, long rhs) { return lft ^ (_int128)rhs; } inline _int128 operator^(const _int128 &lft, unsigned long rhs) { return lft ^ (_int128)rhs; } inline _int128 operator^(const _int128 &lft, int rhs) { return lft ^ (_int128)rhs; } inline _int128 operator^(const _int128 &lft, unsigned int rhs) { return lft ^ (_int128)rhs; } inline _int128 operator^(const _int128 &lft, short rhs) { return lft ^ (_int128)rhs; } inline _int128 operator^(const _int128 &lft, unsigned short rhs) { return lft ^ (_int128)rhs; } inline _uint128 operator^(const _uint128 &lft, __int64 rhs) { return lft ^ (_int128)rhs; } inline _uint128 operator^(const _uint128 &lft, unsigned __int64 rhs) { return lft ^ (_uint128)rhs; } inline _uint128 operator^(const _uint128 &lft, long rhs) { return lft ^ (_int128)rhs; } inline _uint128 operator^(const _uint128 &lft, unsigned long rhs) { return lft ^ (_uint128)rhs; } inline _uint128 operator^(const _uint128 &lft, int rhs) { return lft ^ (_int128)rhs; } inline _uint128 operator^(const _uint128 &lft, unsigned int rhs) { return lft ^ (_uint128)rhs; } inline _uint128 operator^(const _uint128 &lft, short rhs) { return lft ^ (_int128)rhs; } inline _uint128 operator^(const _uint128 &lft, unsigned short rhs) { return lft ^ (_uint128)rhs; } // Compare operators where second argument is built in integral type // operator == for built in integral types as second argument inline bool operator==(const _int128 &lft, __int64 rhs) { return lft == _int128(rhs); } inline bool operator==(const _int128 &lft, unsigned __int64 rhs) { return lft == _int128(rhs); } inline bool operator==(const _int128 &lft, long rhs) { return lft == _int128(rhs); } inline bool operator==(const _int128 &lft, unsigned long rhs) { return lft == _int128(rhs); } inline bool operator==(const _int128 &lft, int rhs) { return lft == _int128(rhs); } inline bool operator==(const _int128 &lft, unsigned int rhs) { return lft == _int128(rhs); } inline bool operator==(const _int128 &lft, short rhs) { return lft == _int128(rhs); } inline bool operator==(const _int128 &lft, unsigned short rhs) { return lft == _int128(rhs); } inline bool operator==(const _uint128 &lft, __int64 rhs) { return lft == _int128(rhs); } inline bool operator==(const _uint128 &lft, unsigned __int64 rhs) { return lft == _uint128(rhs); } inline bool operator==(const _uint128 &lft, long rhs) { return lft == _int128(rhs); } inline bool operator==(const _uint128 &lft, unsigned long rhs) { return lft == _uint128(rhs); } inline bool operator==(const _uint128 &lft, int rhs) { return lft == _int128(rhs); } inline bool operator==(const _uint128 &lft, unsigned int rhs) { return lft == _uint128(rhs); } inline bool operator==(const _uint128 &lft, short rhs) { return lft == _int128(rhs); } inline bool operator==(const _uint128 &lft, unsigned short rhs) { return lft == _uint128(rhs); } // operator != for built in integral types as second argument inline bool operator!=(const _int128 &lft, __int64 rhs) { return lft != _int128(rhs); } inline bool operator!=(const _int128 &lft, unsigned __int64 rhs) { return lft != _int128(rhs); } inline bool operator!=(const _int128 &lft, long rhs) { return lft != _int128(rhs); } inline bool operator!=(const _int128 &lft, unsigned long rhs) { return lft != _int128(rhs); } inline bool operator!=(const _int128 &lft, int rhs) { return lft != _int128(rhs); } inline bool operator!=(const _int128 &lft, unsigned int rhs) { return lft != _int128(rhs); } inline bool operator!=(const _int128 &lft, short rhs) { return lft != _int128(rhs); } inline bool operator!=(const _int128 &lft, unsigned short rhs) { return lft != _int128(rhs); } inline bool operator!=(const _uint128 &lft, __int64 rhs) { return lft != _int128(rhs); } inline bool operator!=(const _uint128 &lft, unsigned __int64 rhs) { return lft != _uint128(rhs); } inline bool operator!=(const _uint128 &lft, long rhs) { return lft != _int128(rhs); } inline bool operator!=(const _uint128 &lft, unsigned long rhs) { return lft != _uint128(rhs); } inline bool operator!=(const _uint128 &lft, int rhs) { return lft != _int128(rhs); } inline bool operator!=(const _uint128 &lft, unsigned int rhs) { return lft != _uint128(rhs); } inline bool operator!=(const _uint128 &lft, short rhs) { return lft != _int128(rhs); } inline bool operator!=(const _uint128 &lft, unsigned short rhs) { return lft != _uint128(rhs); } // operator > for built in integral types as second argument inline bool operator>(const _int128 &lft, __int64 rhs) { return lft > _int128(rhs); } inline bool operator>(const _int128 &lft, unsigned __int64 rhs) { return lft > _uint128(rhs); } inline bool operator>(const _int128 &lft, long rhs) { return lft > _int128(rhs); } inline bool operator>(const _int128 &lft, unsigned long rhs) { return lft > _uint128(rhs); } inline bool operator>(const _int128 &lft, int rhs) { return lft > _int128(rhs); } inline bool operator>(const _int128 &lft, unsigned int rhs) { return lft > _uint128(rhs); } inline bool operator>(const _int128 &lft, short rhs) { return lft > _int128(rhs); } inline bool operator>(const _int128 &lft, unsigned short rhs) { return lft > _uint128(rhs); } inline bool operator>(const _uint128 &lft, __int64 rhs) { return lft > _int128(rhs); } inline bool operator>(const _uint128 &lft, unsigned __int64 rhs) { return lft > _uint128(rhs); } inline bool operator>(const _uint128 &lft, long rhs) { return lft > _int128(rhs); } inline bool operator>(const _uint128 &lft, unsigned long rhs) { return lft > _uint128(rhs); } inline bool operator>(const _uint128 &lft, int rhs) { return lft > _int128(rhs); } inline bool operator>(const _uint128 &lft, unsigned int rhs) { return lft > _uint128(rhs); } inline bool operator>(const _uint128 &lft, short rhs) { return lft > _int128(rhs); } inline bool operator>(const _uint128 &lft, unsigned short rhs) { return lft > _uint128(rhs); } // operator >= for built in integral types as second argument inline bool operator>=(const _int128 &lft, __int64 rhs) { return lft >= _int128(rhs); } inline bool operator>=(const _int128 &lft, unsigned __int64 rhs) { return lft >= _uint128(rhs); } inline bool operator>=(const _int128 &lft, long rhs) { return lft >= _int128(rhs); } inline bool operator>=(const _int128 &lft, unsigned long rhs) { return lft >= _uint128(rhs); } inline bool operator>=(const _int128 &lft, int rhs) { return lft >= _int128(rhs); } inline bool operator>=(const _int128 &lft, unsigned int rhs) { return lft >= _uint128(rhs); } inline bool operator>=(const _int128 &lft, short rhs) { return lft >= _int128(rhs); } inline bool operator>=(const _int128 &lft, unsigned short rhs) { return lft >= _uint128(rhs); } inline bool operator>=(const _uint128 &lft, __int64 rhs) { return lft >= _int128(rhs); } inline bool operator>=(const _uint128 &lft, unsigned __int64 rhs) { return lft >= _uint128(rhs); } inline bool operator>=(const _uint128 &lft, long rhs) { return lft >= _int128(rhs); } inline bool operator>=(const _uint128 &lft, unsigned long rhs) { return lft >= _uint128(rhs); } inline bool operator>=(const _uint128 &lft, int rhs) { return lft >= _int128(rhs); } inline bool operator>=(const _uint128 &lft, unsigned int rhs) { return lft >= _uint128(rhs); } inline bool operator>=(const _uint128 &lft, short rhs) { return lft >= _int128(rhs); } inline bool operator>=(const _uint128 &lft, unsigned short rhs) { return lft >= _uint128(rhs); } // operator < for built in integral types as second argument inline bool operator<(const _int128 &lft, __int64 rhs) { return lft < _int128(rhs); } inline bool operator<(const _int128 &lft, unsigned __int64 rhs) { return lft < _uint128(rhs); } inline bool operator<(const _int128 &lft, long rhs) { return lft < _int128(rhs); } inline bool operator<(const _int128 &lft, unsigned long rhs) { return lft < _uint128(rhs); } inline bool operator<(const _int128 &lft, int rhs) { return lft < _int128(rhs); } inline bool operator<(const _int128 &lft, unsigned int rhs) { return lft < _uint128(rhs); } inline bool operator<(const _int128 &lft, short rhs) { return lft < _int128(rhs); } inline bool operator<(const _int128 &lft, unsigned short rhs) { return lft < _uint128(rhs); } inline bool operator<(const _uint128 &lft, __int64 rhs) { return lft < _int128(rhs); } inline bool operator<(const _uint128 &lft, unsigned __int64 rhs) { return lft < _uint128(rhs); } inline bool operator<(const _uint128 &lft, long rhs) { return lft < _int128(rhs); } inline bool operator<(const _uint128 &lft, unsigned long rhs) { return lft < _uint128(rhs); } inline bool operator<(const _uint128 &lft, int rhs) { return lft < _int128(rhs); } inline bool operator<(const _uint128 &lft, unsigned int rhs) { return lft < _uint128(rhs); } inline bool operator<(const _uint128 &lft, short rhs) { return lft < _int128(rhs); } inline bool operator<(const _uint128 &lft, unsigned short rhs) { return lft < _uint128(rhs); } // operator <= for built in integral types as second argument inline bool operator<=(const _int128 &lft, __int64 rhs) { return lft <= _int128(rhs); } inline bool operator<=(const _int128 &lft, unsigned __int64 rhs) { return lft <= _uint128(rhs); } inline bool operator<=(const _int128 &lft, long rhs) { return lft <= _int128(rhs); } inline bool operator<=(const _int128 &lft, unsigned long rhs) { return lft <= _uint128(rhs); } inline bool operator<=(const _int128 &lft, int rhs) { return lft <= _int128(rhs); } inline bool operator<=(const _int128 &lft, unsigned int rhs) { return lft <= _uint128(rhs); } inline bool operator<=(const _int128 &lft, short rhs) { return lft <= _int128(rhs); } inline bool operator<=(const _int128 &lft, unsigned short rhs) { return lft <= _uint128(rhs); } inline bool operator<=(const _uint128 &lft, __int64 rhs) { return lft <= _int128(rhs); } inline bool operator<=(const _uint128 &lft, unsigned __int64 rhs) { return lft <= _uint128(rhs); } inline bool operator<=(const _uint128 &lft, long rhs) { return lft <= _int128(rhs); } inline bool operator<=(const _uint128 &lft, unsigned long rhs) { return lft <= _uint128(rhs); } inline bool operator<=(const _uint128 &lft, int rhs) { return lft <= _int128(rhs); } inline bool operator<=(const _uint128 &lft, unsigned int rhs) { return lft <= _uint128(rhs); } inline bool operator<=(const _uint128 &lft, short rhs) { return lft <= _int128(rhs); } inline bool operator<=(const _uint128 &lft, unsigned short rhs) { return lft <= _uint128(rhs); } // Assign operators where second argument is built in integral type // operator += for built in integral types as second argument inline _int128 &operator+=(_int128 &lft, __int64 rhs) { return lft += (_int128)rhs; } inline _int128 &operator+=(_int128 &lft, unsigned __int64 rhs) { return lft += (_uint128)rhs; } inline _int128 &operator+=(_int128 &lft, long rhs) { return lft += (_int128)rhs; } inline _int128 &operator+=(_int128 &lft, unsigned long rhs) { return lft += (_uint128)rhs; } inline _int128 &operator+=(_int128 &lft, int rhs) { return lft += (_int128)rhs; } inline _int128 &operator+=(_int128 &lft, unsigned int rhs) { return lft += (_uint128)rhs; } inline _int128 &operator+=(_int128 &lft, short rhs) { return lft += (_int128)rhs; } inline _int128 &operator+=(_int128 &lft, unsigned short rhs) { return lft += (_uint128)rhs; } inline _uint128 &operator+=(_uint128 &lft, __int64 rhs) { return lft += (_int128)rhs; } inline _uint128 &operator+=(_uint128 &lft, unsigned __int64 rhs) { //return lft += (_uint128)rhs; auto c = _addcarry_u64(0, LO64(lft), rhs, &LO64(lft)); HI64(lft) += c; return lft; } inline _uint128 &operator+=(_uint128 &lft, long rhs) { return lft += (_int128)rhs; } inline _uint128 &operator+=(_uint128 &lft, unsigned long rhs) { return lft += (_uint128)rhs; } inline _uint128 &operator+=(_uint128 &lft, int rhs) { return lft += (_int128)rhs; } inline _uint128 &operator+=(_uint128 &lft, unsigned int rhs) { return lft += (_uint128)rhs; } inline _uint128 &operator+=(_uint128 &lft, short rhs) { return lft += (_int128)rhs; } inline _uint128 &operator+=(_uint128 &lft, unsigned short rhs) { return lft += (_uint128)rhs; } // operator -= for built in integral types as second argument inline _int128 &operator-=(_int128 &lft, __int64 rhs) { return lft -= (_int128)rhs; } inline _int128 &operator-=(_int128 &lft, unsigned __int64 rhs) { return lft -= (_uint128)rhs; } inline _int128 &operator-=(_int128 &lft, long rhs) { return lft -= (_int128)rhs; } inline _int128 &operator-=(_int128 &lft, unsigned long rhs) { return lft -= (_uint128)rhs; } inline _int128 &operator-=(_int128 &lft, int rhs) { return lft -= (_int128)rhs; } inline _int128 &operator-=(_int128 &lft, unsigned int rhs) { return lft -= (_uint128)rhs; } inline _int128 &operator-=(_int128 &lft, short rhs) { return lft -= (_int128)rhs; } inline _int128 &operator-=(_int128 &lft, unsigned short rhs) { return lft -= (_uint128)rhs; } inline _uint128 &operator-=(_uint128 &lft, __int64 rhs) { return lft -= (_int128)rhs; } inline _uint128 &operator-=(_uint128 &lft, unsigned __int64 rhs) { return lft -= (_uint128)rhs; } inline _uint128 &operator-=(_uint128 &lft, long rhs) { return lft -= (_int128)rhs; } inline _uint128 &operator-=(_uint128 &lft, unsigned long rhs) { return lft -= (_uint128)rhs; } inline _uint128 &operator-=(_uint128 &lft, int rhs) { return lft -= (_int128)rhs; } inline _uint128 &operator-=(_uint128 &lft, unsigned int rhs) { return lft -= (_uint128)rhs; } inline _uint128 &operator-=(_uint128 &lft, short rhs) { return lft -= (_int128)rhs; } inline _uint128 &operator-=(_uint128 &lft, unsigned short rhs) { return lft -= (_uint128)rhs; } // operator*= for built in integral types as second argument inline _int128 &operator*=(_int128 &lft, __int64 rhs) { return lft *= (_int128)rhs; } inline _int128 &operator*=(_int128 &lft, unsigned __int64 rhs) { return lft *= (_uint128)rhs; } inline _int128 &operator*=(_int128 &lft, long rhs) { return lft *= (_int128)rhs; } inline _int128 &operator*=(_int128 &lft, unsigned long rhs) { return lft *= (_uint128)rhs; } inline _int128 &operator*=(_int128 &lft, int rhs) { return lft *= (_int128)rhs; } inline _int128 &operator*=(_int128 &lft, unsigned int rhs) { return lft *= (_uint128)rhs; } inline _int128 &operator*=(_int128 &lft, short rhs) { return lft *= (_int128)rhs; } inline _int128 &operator*=(_int128 &lft, unsigned short rhs) { return lft *= (_uint128)rhs; } inline _uint128 &operator*=(_uint128 &lft, __int64 rhs) { return lft *= (_int128)rhs; } inline _uint128 &operator*=(_uint128 &lft, unsigned __int64 rhs) { return lft *= (_uint128)rhs; } inline _uint128 &operator*=(_uint128 &lft, long rhs) { return lft *= (_int128)rhs; } inline _uint128 &operator*=(_uint128 &lft, unsigned long rhs) { return lft *= (_uint128)rhs; } inline _uint128 &operator*=(_uint128 &lft, int rhs) { return lft *= (_int128)rhs; } inline _uint128 &operator*=(_uint128 &lft, unsigned int rhs) { return lft *= (_uint128)rhs; } inline _uint128 &operator*=(_uint128 &lft, short rhs) { return lft *= (_int128)rhs; } inline _uint128 &operator*=(_uint128 &lft, unsigned short rhs) { return lft *= (_uint128)rhs; } // operator /= for built in integral types as second argument inline _int128 &operator/=(_int128 &lft, __int64 rhs) { return lft /= (_int128)rhs; } inline _int128 &operator/=(_int128 &lft, unsigned __int64 rhs) { return lft /= (_uint128)rhs; } inline _int128 &operator/=(_int128 &lft, long rhs) { return lft /= (_int128)rhs; } inline _int128 &operator/=(_int128 &lft, unsigned long rhs) { return lft /= (_uint128)rhs; } inline _int128 &operator/=(_int128 &lft, int rhs) { return lft /= (_int128)rhs; } inline _int128 &operator/=(_int128 &lft, unsigned int rhs) { return lft /= (_uint128)rhs; } inline _int128 &operator/=(_int128 &lft, short rhs) { return lft /= (_int128)rhs; } inline _int128 &operator/=(_int128 &lft, unsigned short rhs) { return lft /= (_uint128)rhs; } inline _uint128 &operator/=(_uint128 &lft, __int64 rhs) { return lft /= (_int128)rhs; } inline _uint128 &operator/=(_uint128 &lft, unsigned __int64 rhs) { return lft /= (_uint128)rhs; } inline _uint128 &operator/=(_uint128 &lft, long rhs) { return lft /= (_int128)rhs; } inline _uint128 &operator/=(_uint128 &lft, unsigned long rhs) { return lft /= (_uint128)rhs; } inline _uint128 &operator/=(_uint128 &lft, int rhs) { return lft /= (_int128)rhs; } inline _uint128 &operator/=(_uint128 &lft, unsigned int rhs) { return lft /= (_uint128)rhs; } inline _uint128 &operator/=(_uint128 &lft, short rhs) { return lft /= (_int128)rhs; } inline _uint128 &operator/=(_uint128 &lft, unsigned short rhs) { return lft /= (_uint128)rhs; } // operator %= for built in integral types as second argument inline _int128 &operator%=(_int128 &lft, __int64 rhs) { return lft %= (_int128)rhs; } inline _int128 &operator%=(_int128 &lft, unsigned __int64 rhs) { return lft %= (_uint128)rhs; } inline _int128 &operator%=(_int128 &lft, long rhs) { return lft %= (_int128)rhs; } inline _int128 &operator%=(_int128 &lft, unsigned long rhs) { return lft %= (_uint128)rhs; } inline _int128 &operator%=(_int128 &lft, int rhs) { return lft %= (_int128)rhs; } inline _int128 &operator%=(_int128 &lft, unsigned int rhs) { return lft %= (_uint128)rhs; } inline _int128 &operator%=(_int128 &lft, short rhs) { return lft %= (_int128)rhs; } inline _int128 &operator%=(_int128 &lft, unsigned short rhs) { return lft %= (_uint128)rhs; } inline _uint128 &operator%=(_uint128 &lft, __int64 rhs) { return lft %= (_int128)rhs; } inline _uint128 &operator%=(_uint128 &lft, unsigned __int64 rhs) { return lft %= (_uint128)rhs; } inline _uint128 &operator%=(_uint128 &lft, long rhs) { return lft %= (_int128)rhs; } inline _uint128 &operator%=(_uint128 &lft, unsigned long rhs) { return lft %= (_uint128)rhs; } inline _uint128 &operator%=(_uint128 &lft, int rhs) { return lft %= (_int128)rhs; } inline _uint128 &operator%=(_uint128 &lft, unsigned int rhs) { return lft %= (_uint128)rhs; } inline _uint128 &operator%=(_uint128 &lft, short rhs) { return lft %= (_int128)rhs; } inline _uint128 &operator%=(_uint128 &lft, unsigned short rhs) { return lft %= (_uint128)rhs; } // operator &= for built in integral types as second argument inline _int128 &operator&=(_int128 &lft, __int64 rhs) { return lft &= (_int128)rhs; } inline _int128 &operator&=(_int128 &lft, unsigned __int64 rhs) { return lft &= (_uint128)rhs; } inline _int128 &operator&=(_int128 &lft, long rhs) { return lft &= (_int128)rhs; } inline _int128 &operator&=(_int128 &lft, unsigned long rhs) { return lft &= (_uint128)rhs; } inline _int128 &operator&=(_int128 &lft, int rhs) { return lft &= (_int128)rhs; } inline _int128 &operator&=(_int128 &lft, unsigned int rhs) { return lft &= (_uint128)rhs; } inline _int128 &operator&=(_int128 &lft, short rhs) { return lft &= (_int128)rhs; } inline _int128 &operator&=(_int128 &lft, unsigned short rhs) { return lft &= (_uint128)rhs; } inline _uint128 &operator&=(_uint128 &lft, __int64 rhs) { return lft &= (_int128)rhs; } inline _uint128 &operator&=(_uint128 &lft, unsigned __int64 rhs) { return lft &= (_uint128)rhs; } inline _uint128 &operator&=(_uint128 &lft, long rhs) { return lft &= (_int128)rhs; } inline _uint128 &operator&=(_uint128 &lft, unsigned long rhs) { return lft &= (_uint128)rhs; } inline _uint128 &operator&=(_uint128 &lft, int rhs) { return lft &= (_int128)rhs; } inline _uint128 &operator&=(_uint128 &lft, unsigned int rhs) { return lft &= (_uint128)rhs; } inline _uint128 &operator&=(_uint128 &lft, short rhs) { return lft &= (_int128)rhs; } inline _uint128 &operator&=(_uint128 &lft, unsigned short rhs) { return lft &= (_uint128)rhs; } // operator |= for built in integral types as second argument inline _int128 &operator|=(_int128 &lft, __int64 rhs) { return lft |= (_int128)rhs; } inline _int128 &operator|=(_int128 &lft, unsigned __int64 rhs) { return lft |= (_uint128)rhs; } inline _int128 &operator|=(_int128 &lft, long rhs) { return lft |= (_int128)rhs; } inline _int128 &operator|=(_int128 &lft, unsigned long rhs) { return lft |= (_uint128)rhs; } inline _int128 &operator|=(_int128 &lft, int rhs) { return lft |= (_int128)rhs; } inline _int128 &operator|=(_int128 &lft, unsigned int rhs) { return lft |= (_uint128)rhs; } inline _int128 &operator|=(_int128 &lft, short rhs) { return lft |= (_int128)rhs; } inline _int128 &operator|=(_int128 &lft, unsigned short rhs) { return lft |= (_uint128)rhs; } inline _uint128 &operator|=(_uint128 &lft, __int64 rhs) { return lft |= (_int128)rhs; } inline _uint128 &operator|=(_uint128 &lft, unsigned __int64 rhs) { return lft |= (_uint128)rhs; } inline _uint128 &operator|=(_uint128 &lft, long rhs) { return lft |= (_int128)rhs; } inline _uint128 &operator|=(_uint128 &lft, unsigned long rhs) { return lft |= (_uint128)rhs; } inline _uint128 &operator|=(_uint128 &lft, int rhs) { return lft |= (_int128)rhs; } inline _uint128 &operator|=(_uint128 &lft, unsigned int rhs) { return lft |= (_uint128)rhs; } inline _uint128 &operator|=(_uint128 &lft, short rhs) { return lft |= (_int128)rhs; } inline _uint128 &operator|=(_uint128 &lft, unsigned short rhs) { return lft |= (_uint128)rhs; } // operator ^= for built in integral types as second argument inline _int128 &operator^=(_int128 &lft, __int64 rhs) { return lft ^= (_int128)rhs; } inline _int128 &operator^=(_int128 &lft, unsigned __int64 rhs) { return lft ^= (_uint128)rhs; } inline _int128 &operator^=(_int128 &lft, long rhs) { return lft ^= (_int128)rhs; } inline _int128 &operator^=(_int128 &lft, unsigned long rhs) { return lft ^= (_uint128)rhs; } inline _int128 &operator^=(_int128 &lft, int rhs) { return lft ^= (_int128)rhs; } inline _int128 &operator^=(_int128 &lft, unsigned int rhs) { return lft ^= (_uint128)rhs; } inline _int128 &operator^=(_int128 &lft, short rhs) { return lft ^= (_int128)rhs; } inline _int128 &operator^=(_int128 &lft, unsigned short rhs) { return lft ^= (_uint128)rhs; } inline _uint128 &operator^=(_uint128 &lft, __int64 rhs) { return lft ^= (_int128)rhs; } inline _uint128 &operator^=(_uint128 &lft, unsigned __int64 rhs) { return lft ^= (_uint128)rhs; } inline _uint128 &operator^=(_uint128 &lft, long rhs) { return lft ^= (_int128)rhs; } inline _uint128 &operator^=(_uint128 &lft, unsigned long rhs) { return lft ^= (_uint128)rhs; } inline _uint128 &operator^=(_uint128 &lft, int rhs) { return lft ^= (_int128)rhs; } inline _uint128 &operator^=(_uint128 &lft, unsigned int rhs) { return lft ^= (_uint128)rhs; } inline _uint128 &operator^=(_uint128 &lft, short rhs) { return lft ^= (_int128)rhs; } inline _uint128 &operator^=(_uint128 &lft, unsigned short rhs) { return lft ^= (_uint128)rhs; } _int128 _strtoi128(const char *str, char **end, int radix); _uint128 _strtoui128(const char *str, char **end, int radix); _int128 _wcstoi128(const wchar_t *str, wchar_t **end, int radix); _uint128 _wcstoui128(const wchar_t *str, wchar_t **end, int radix); char *_i128toa(_int128 value, char *str, int radix); char *_ui128toa(_uint128 value, char *str, int radix); wchar_t *_i128tow(_int128 value, wchar_t *str, int radix); wchar_t *_ui128tow(_uint128 value, wchar_t *str, int radix); struct fc { bool minus = false; bool plus = false; bool zero = false; bool blank = false; bool hash = false; }; int sPrintf128(char *buffer, const int buflen, const char* FormatStr, const _int128 &n); int sPrintf128(char *buffer, const int buflen, const char* FormatStr, const _uint128 &n); inline char radixLetter(unsigned int c) { return (c < 10) ? ('0' + c) : ('a' + (c - 10)); } /* return true if ch is a valid octal digit */ inline bool iswodigit(wchar_t ch) { return ('0' <= ch) && (ch < '8'); } extern const _int128 _I128_MIN, _I128_MAX; extern const _uint128 _UI128_MAX; /* input and output operators declaration */ std::istream &operator>>(std::istream &s, _int128 &n); std::ostream &operator<<(std::ostream &s, const _int128 &n); std::istream &operator>>(std::istream &s, _uint128 &n); std::ostream &operator<<(std::ostream &s, const _uint128 &n); std::wistream &operator>>(std::wistream &s, _int128 &n); std::wostream &operator<<(std::wostream &s, const _int128 &n); std::wistream &operator>>(std::wistream &s, _uint128 &n); std::wostream &operator<<(std::wostream &s, const _uint128 &n); typedef struct { _int128 quot; _int128 rem; } _int128div_t; _int128div_t divrem(const _int128 &a, const _int128 &b); typedef struct { _uint128 quot; _uint128 rem; } _uint128div_t; _uint128div_t divrem(const _uint128 &a, const _uint128 &b); /* calculate x^n. Beware of overflow! e.g. 2^128, 3^81, 4^64 etc will cause an overflow */ _int128 power(const _int128 &x, int n); /* find nth root of a i.e. return r such that abs(r^n) <= abs(a) if n < 1 there is no solution. If n is even and a is negative there is no solution. if n = 1 or a=0 or a = 1, r = a */ _int128 nthroot(const _int128 &aa, int n); /* calculate GCD of u and v. */ _uint128 gcd(_uint128 u, _uint128 v); _int128 extendedGcd(const _int128 &u, const _int128 &v, _int128 &x, _int128 &y); /* get modular inverse of a wrt m */ _int128 modMultInv(_int128 a, _int128 m); /* get absolute value of x */ static inline _int128 abs(const _int128 &x) { if (x.isNegative()) return -x; else return x; } /* convert double x to _int128. Number is truncated i.e. fractional part is discarded, like casting to int. */ _int128 doubleTo128(const double x); /* multiply 64 bit x 64 bit to get 128 bits. This is a more efficient alternative to casting each of the 64 bit values to 128 bits before multiplication, while still ensuring that overflow will not occur. */ /* this version is for unsigned integers. */ #define ui128mult(p128, a64, b64) \ LO64(p128) =_umul128(a64, b64, &HI64(p128)) /* this version is for signed integers. */ #define i128mult(p128, a64, b64) \ LO64(p128) =_mul128(a64, b64, (long long*)&HI64(p128))
true
b2b13efecb8aa37531de5dfb1cbfd6c46a8c1808
C++
GarryLiuN/CS343-Project
/src/nameserver.h
UTF-8
1,520
2.890625
3
[]
no_license
#ifndef __NAMESERVER_H__ #define __NAMESERVER_H__ #include <vector> #include "printer.h" #include "vendingmachine.h" _Task NameServer { private: // reference Printer& prt; // attributes unsigned int numVendingMachines; unsigned int numStudents; /** @brief studentIndex vector is used to store the last VM index each * student accessed, which will help to make sure that each student has a * chance to visit every machine */ std::vector<int> studentIndex; std::vector<VendingMachine*> machineList; /** @brief lastMachineIndex is used to store the last vm ID that assigned to * student who first time called getMachine */ unsigned int lastMachineIndex = -1; // local copy for machine that call VMregister VendingMachine* newMachine; void main(); public: NameServer( Printer & prt, unsigned int numVendingMachines, unsigned int numStudents ); /** * @brief VMregister will be called by a VM and the nameserver will save the * pointer to that machine into a vector */ void VMregister( VendingMachine * vendingmachine ); /** * @brief GetMachine will be called by a student, the id will be used to * select next VM in a round-robin fashion */ VendingMachine* getMachine( unsigned int id ); /** * @brief getMachineList will be called by truck and return the full list of * all VMs */ VendingMachine** getMachineList(); }; #endif
true
19a9a4cfe780e3f912e8d50605cd7a4b2792fc2c
C++
wlc123456/fsmlite
/tests/test_scoped.cpp
UTF-8
839
3.1875
3
[ "MIT" ]
permissive
#include <cassert> #include <type_traits> #include "fsm.h" enum class State { Init, Exit }; class state_machine: public fsmlite::fsm<state_machine, State> { friend class fsmlite::fsm<state_machine, State>; // base class needs access to transition_table public: struct event {}; private: using transition_table = table< // Row-Type Start Event Target // ----------+------------+------+-----------+- basic_row< State::Init, event, State::Exit > // ----------+------------+------+-----------+- >; static_assert(std::is_same<state_type, State>::value, "state_machine::state_type == State"); }; int main() { state_machine m; assert(m.current_state() == State::Init); m.process_event(state_machine::event()); assert(m.current_state() == State::Exit); return 0; }
true
e345ac70f9773fb6d51aab18cf1a074402dec092
C++
Caroline-Wendy/Beauty-of-Programming
/BoP_2.7_gcd.cpp
UTF-8
981
3.515625
4
[ "BSD-3-Clause" ]
permissive
/*From Beauty of Programming, By C.L.Wang*/ #include <iostream> using namespace std; typedef unsigned long long int ULLI; bool isEven(const ULLI& x){ unsigned int temp; temp = x%2; if(temp == 0){ return true; }else{ return false; } } ULLI gcd(const ULLI& x, const ULLI& y){ if(x < y) return gcd(y, x); if(y==0){ return x; }else{ if(isEven(x)){ if(isEven(y)) return (gcd(x>>1, y>>1) << 1); else return gcd(x>>1, y); }else{ if(isEven(y)) return gcd(x, y>>1); else return gcd(y, x-y); } } } int main(void){ //x = 125478536; y = 1631220968; ULLI x, y, z; std::cout << "Please input two numbers:" << std::endl; std::cin >> x >> y; std::cout << "Thanks! The numbers are " << x << " and " << y << ". " << std::endl; z = gcd(x, y); std::cout << "The greatest common divisor is " << z << ". " << std::endl; return 0; } /*simple method*/ ULLI simple_gcd(const ULLI& x,const ULLI& y){ return (!y)?x:simple_gcd(y, x%y); }
true
d0aebde07b510860897c90ec2020df12c957d9aa
C++
HuangZhiChao95/Data-Structure-HW
/homework2_2.cpp
UTF-8
1,132
3.15625
3
[]
no_license
struct SNode{ int data; SNode *next; SNode():data(0),next(NULL){} }; void mergeList(LinkList &HA,LinkList &HB,LinkList &HC){ /*第一个表的指针*/ SNode *fir=HA.head; /*第二个表的指针*/ SNode *sec=HB.head; /*结果表的指针,临时建立一个表头指针*/ SNode *res=new SNode(); /*保存表头指针*/ SNode *head=res; /*存储临时需要保存的下一节点*/ SNode *temp=0; while (fir!=0&&sec!=0) { if (fir.data<sec.data) { /*第一个链表节点较小,移动第一个*/ temp=fir; fir=fir->next; HA.head->next=fir; }else{ /*第二个链表节点较小,移动第二个*/ temp=sec; sec=sec->next; HB.head->next=sec; } /*加临时节点添加到结果表中并移动结果表节点*/ res->next=temp; res=res->next; } /*一个表到尽头后,将另一个表的所有节点加入*/ while (fir!=0) { temp=fir; fir=fir->next; HA.head->next=fir; res->next=temp; res=res->next; } while (sec!=0) { temp=sec; sec=sec->next; HB.head->next=sec; res->next=temp; res=res->next; } temp=head; head=head->next; delete temp; }
true
331ab68f07a33b51c7d889003cb520b7ea040c04
C++
hiragisorah/seed-engine
/seed-engine/texture.h
UTF-8
348
2.65625
3
[]
no_license
#pragma once namespace Seed { class Texture { public: virtual unsigned int width(void) { return 0; } virtual unsigned int height(void) { return 0; } public: template<class _Type> void width(void) { return static_cast<_Type>(this->width()); } template<class _Type> void height(void) { return static_cast<_Type>(this->height()); } }; }
true
391c650916a15242cf129953a45abb0c4ed8ce14
C++
nurnaff/logika_c
/inputarra.cpp
UTF-8
205
2.53125
3
[]
no_license
#include<stdio.h> #include<conio.h> main() { int nilai[5]; for(int i=0;i<5;i++){ printf("Nilai ke-%d",i+1);printf(":");scanf("%d",&nilai[i]); } for(int i=0;i<5;i++){ printf(" %d",nilai[i]); } getch(); }
true
ed95b92b4be9ea1fd54feae664cfb0e913fb90bd
C++
yogitaghadage/c-
/Bitwiseoperations.cpp
UTF-8
1,815
3.75
4
[]
no_license
#include<stdio.h> typedef unsigned int UINT; /*1.Write a program which accept one number from user and off 7th bit of that number. Return modified number.*/ UINT OffBit(UINT iNo) { UINT iresult=0; UINT mask=0x00000040; mask=~mask; iresult=iNo & mask; return mask; } //2. Write a program which accept one number from user and off 7th and 10th //bit of that number. Return modified number. UINT OffBitX(UINT iNo) { UINT iresult=0; UINT mask=0x00000240; mask=~mask; iresult=iNo & mask; return mask; } //3. Write a program which accept one number from user and toggle 7th bit of //that number. Return modified number. UINT ToggleBit(UINT iNo) { UINT iresult=0; UINT mask=0x00000040; iresult=iNo ^ mask; return mask; } //4. Write a program which accept one number from user and toggle 7th and //10th bit of that number. Return modified number. UINT ToggleBitX(UINT iNo) { UINT iresult=0; UINT mask=0x00000240; iresult=iNo & mask; return mask; } //5. Write a program which accept one number from user and on its first 4 //bits. Return modified number. UINT OnBit(UINT iNo) { UINT iresult=0; UINT mask=0x0000000F; iresult=iNo | mask; return mask; } int main() { UINT value=0; UINT iret=0; int choice=0; printf("enter number"); scanf("%d",&value); printf("enter choice"); scanf("%d",&choice); switch(choice) { case 1: iret=OffBit(value); printf("%d",iret); break; case 2: iret=OffBitX(value); printf("%d",iret); break; case 3: iret=ToggleBit(value); printf("%d",iret); break; case 4: iret=ToggleBitX(value); printf("%d",iret); break; case 5: iret=OnBit(value); printf("%d",iret); break; default: break; } return 0; }
true
ea6799d4edd83fc6c7486a17efd3436b3a6ce4a4
C++
mayotte203/Baka-Floppy
/Baka Keys/Baka_Keys.ino
UTF-8
1,930
2.59375
3
[]
no_license
#include <MIDI.h> //const byte rowsPins[6] = {12, 11, 10, 13, 14, 15}; const byte rowsPins[6] = {15, 14, 13, 10, 11, 12}; const byte columnsPins[6] = {9, 8, 7, 6, 5, 4}; bool buttonsStates[36] = {}; MIDI_CREATE_DEFAULT_INSTANCE(); int noteON = 144;//144 = 10010000 in binary, note on command int noteOFF = 128;//128 = 10000000 in binary, note off command void setup() { Serial.begin(31250); for(int i = 0; i < 6; ++i) { pinMode(rowsPins[i], OUTPUT); pinMode(columnsPins[i], INPUT); } } void MIDImessage(int command, int MIDInote, int MIDIvelocity) { Serial.write(command);//send note on or note off command Serial.write(MIDInote);//send pitch data Serial.write(MIDIvelocity);//send velocity data } bool keyboardStatus[36] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; byte ChannelCount = 16; byte playing[16] = {255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255}; void loop() { for(byte i = 0; i < 6; ++i) { digitalWrite(rowsPins[i], HIGH); for(byte j = 0; j < 6; ++j) { bool buttonState = digitalRead(columnsPins[j]); if(buttonsStates[6 * i + j] != buttonState) { buttonsStates[6 * i + j] = buttonState; if(buttonState) { for(byte z = 0; z < ChannelCount; ++z) { if(playing[z] == i + j * 6) { playing[z] = 255; MIDImessage(noteOFF + z, 6 * i + j + 24, 127); z = ChannelCount; } } } else { for(byte z = 0; z < ChannelCount; ++z) { if(playing[z] == 255) { playing[z] = i + j * 6; MIDImessage(noteON + z, 6 * i + j + 24, 127); z = ChannelCount; } } } } } digitalWrite(rowsPins[i], LOW); } }
true
c2d27da08567784c3d154e2ab5d2de50222db4e6
C++
weicse/CS446
/Project 01/ConfData.h
UTF-8
1,504
2.984375
3
[]
no_license
/** * @file ConfData.h * @brief Definition file for ConfData class * @author Wei Tong * @details Specifies all members of ConfData class * @version 1.00 * Wei Tong (7 February 2018) * Initial development, functions will possibly * be used in the future */ #include <string> #include <iostream> #include <sstream> #define Monitor 1 #define File 2 #define Both 3 class ConfData{ private: float version; std::string filePath; int monitorTime; int processorTime; int scannerTime; int hardDriveTime; int keyboardTime; int memoryTime; int projectorTime; int logLevel; std::string logPath; public: ConfData(); // Default constructor ~ConfData(); // Default deconstructor void setVer(float); // Sets the version number float getVer(); // Retrieves the version number void setFilePath(std::string); // Sets the path of the meta data file std::string getFilePath(); // Retrieves the path of the meta data file void setLogPath(std::string); // Sets the path of the log file std::string getLogPath(); // Retrieves the path of the log file void setLogLvl(int); // Sets the log level (ie. Monitor, File, Both) int getLogLvl(); // Retrieves the log level bool setCycleTime(std::string, int); // Takes name of cycle and the time as input int getCycleTime(std::string); // Returns cycle time of specified object int readLine(std::string); // Read function to take in data bool readStatus(); // Mark if read in was successful };
true
c31fa3c281c4ff6afeec2f7e08147e0e51abf4e2
C++
kckwan5/code_test_1
/order_book.h
UTF-8
2,292
2.890625
3
[]
no_license
#include <unordered_map> #include <mutex> #include <queue> #include <memory> namespace UnitTest { class Tester; } class OrderBookInterface { public: typedef uint64_t qty_type; typedef uint64_t stock_id_type; typedef uint64_t client_id_type; typedef uint64_t order_id_type; typedef uint64_t trader_id_type; enum ORDER_SIDE { BUY_ORDER, SELL_ORDER }; struct Order { order_id_type m_orderId; qty_type m_qty; qty_type m_remainQty; client_id_type m_clientId; trader_id_type m_traderId; stock_id_type m_stockId; ORDER_SIDE m_side; }; virtual void addOrder(Order const &order,std::vector<Order> &matchedOrder)=0; }; class OrderBook : public OrderBookInterface { public: friend class UnitTest::Tester; private: struct OrderQueue { OrderQueue():m_side(BUY_ORDER),m_totalRemainQty(0),m_queue(){} std::mutex m_mutex; // so concurrent order of same instrument will not have raise condition std::queue<Order> m_queue; // store pending order for current side ORDER_SIDE m_side; // current side of the queue orders, since there is no price all opposite order will immediately match until one side's order remain qty_type m_totalRemainQty; // total remain quantity of pending orders }; public: void addOrder(Order const &order,std::vector<Order> &matchedOrder); OrderBook(); virtual ~OrderBook(); private: typedef std::unordered_map<stock_id_type,std::shared_ptr<OrderQueue> > order_queues_type; order_queues_type m_order_queues; }; class OrderBookFactory { public: static std::auto_ptr<OrderBookInterface> CreateOrderBook() { return std::auto_ptr<OrderBookInterface>(new OrderBook()); } }; /* class Tester { public: static void dumpQueue(OrderBook const &orderbook, OrderBookInterface::stock_id_type stockId, bool &recordFound,std::queue<OrderBookInterface::Order> &queue,OrderBookInterface::qty_type &remainQty) { OrderBook::order_queues_type::const_iterator it=orderbook.m_order_queues.find(stockId); } }; */
true
78d9fd54b434f0127a651203de8b7b386f115562
C++
jamesmagnus/light_of_paladin
/Light_of_Paladin/ClassConsommable.cpp
UTF-8
969
2.65625
3
[]
no_license
#include "StdLibAndNewOperator.h" #include "ClassConsommable.h" #include "ExceptionPerso.h" using namespace std; Consommable::Consommable(Ogre::SceneNode *pNode, EShape shapeType, int prix, float poid, std::string const& nom, bool IsUnique, bool IsVisible) :Item(pNode, shapeType, prix, poid, nom, IsUnique, IsVisible) { mNombre = 1; } Consommable::~Consommable() { } unsigned int Consommable::getNombre() const { return mNombre; } void Consommable::addObjet() { mNombre++; } void Consommable::addObjet(unsigned int nbr) { mNombre += nbr; } bool Consommable::supprObjet() { mNombre--; if (mNombre > 0) { return true; } else // Il n'y a plus d'objet { delete this; return false; } } bool Consommable::supprObjet(unsigned int nbr) { if (mNombre - nbr >= 0) { mNombre -= nbr; } else { throw ExceptionPerso("Pas assez d'objet", ENiveau::INFO); } if (mNombre > 0) { return true; } else { delete this; return false; } }
true
303805926fbdf2c3de282f8a8a5665600919f276
C++
Capri2014/math
/stan/math/prim/mat/fun/inv_square.hpp
UTF-8
880
3.015625
3
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#ifndef STAN_MATH_PRIM_MAT_FUN_INV_SQUARE_HPP #define STAN_MATH_PRIM_MAT_FUN_INV_SQUARE_HPP #include <stan/math/prim/mat/vectorize/apply_scalar_unary.hpp> #include <stan/math/prim/scal/fun/inv_square.hpp> namespace stan { namespace math { /** * Structure to wrap inv_square() so that it can be vectorized. * @param x Variable. * @tparam T Variable type. * @return 1 / x squared. */ struct inv_square_fun { template <typename T> static inline T fun(const T& x) { return inv_square(x); } }; /** * Vectorized version of inv_square(). * @param x Container. * @tparam T Container type. * @return 1 / the square of each value in x. */ template <typename T> inline typename apply_scalar_unary<inv_square_fun, T>::return_t inv_square( const T& x) { return apply_scalar_unary<inv_square_fun, T>::apply(x); } } // namespace math } // namespace stan #endif
true
fc4256ed08caf8df4590dfae594a6600a7eff1c7
C++
coollama11/cpp
/tests/DDanh5.cpp
UTF-8
6,527
3.390625
3
[]
no_license
//=============================================================// // Name: Diana Danh // CSc 103 // Project 5 > Matching Game //=============================================================// #include <iostream> #include <vector> #include <cstdlib> #include <cassert> #include <algorithm> #include <ctime> #include <chrono> using namespace std; void printNBoard(vector<vector<int> > board){ //prints elements for(int i=0;i<board.size(); i++) { for (int j=0;j<board[i].size(); j++) { if(board[i][j] < 10){ //adding spacing so numbers line up cout << " "; } if(board[i][j]<65) cout << " " << board[i][j]; //prints what is in the row ONLY IF IT IS A numbers else cout << " " << (char)board[i][j]; //prints the char in that spot!! } cout << endl; } } vector<vector<char> > generateMatchs(int rowsInput, int colsInput) { //creates CHAR elements and puts into vector vector<char> tempChar; vector<vector<char> > boardChar; for(int w=0; w<rowsInput; w++){ // fills vector with zeros for(int i=0; i<colsInput; i++){ tempChar.push_back('0'); } boardChar.push_back(tempChar); tempChar.clear(); } srand (time(NULL)); char insertChar = 'A'; int randRow, randCol; for(int d = 0; d < ((rowsInput*colsInput)/2); d++){ for(int s = 0; s<2; s++){ randRow = rand()%rowsInput; randCol = rand()%colsInput; if(boardChar[randRow][randCol] == '0'){ // if zero is there, then replace it with letter boardChar[randRow][randCol] = insertChar; } else { s--; } } insertChar++; } return boardChar; } void printCBoard(vector<vector<char> > board){ // can delete this later //prints elements for(int i=0;i<board.size(); i++) { for (int j=0;j<board[i].size(); j++) { if(board[i][j] < 10){ //adding spacing so numbers line up cout << " "; } cout << " " << board[i][j]; //prints what is in the row } cout << endl; } } int main() { int rowsInput, colsInput; do { cout << "Size requirement: product of row x col must be between 16 and 64 and be even" << endl; cout << "Enter rows: "; cin >> rowsInput; cout << "Enter columns: "; cin >> colsInput; } while(rowsInput*colsInput<16 || rowsInput*colsInput>64 || ((rowsInput*colsInput)%2 == 1)); //creates NUMBER elements and puts into vector int positionNum = 0; vector<int> tempNum; vector<vector<int> > boardNums; for(int w=0; w<rowsInput; w++){ for(int i=0; i<colsInput; i++){ positionNum++; tempNum.push_back(positionNum); } boardNums.push_back(tempNum); tempNum.clear(); } vector<vector<int> > boardNumsLastCorrect = boardNums; //copy to another vector vector<vector<char> > boardChar = generateMatchs(rowsInput, colsInput); int amountOfPairs = (rowsInput*colsInput)/2; cout << "\n \n Allowing 30 seconds per pair" << "\n You will have " << ((amountOfPairs*30)/60) << " minutes and " << ((amountOfPairs*30)%30) << " seconds to find the " << amountOfPairs << " pairs." << "\n Let's play \n" << endl; printNBoard(boardNumsLastCorrect); cout << "\n \n \n"; int checkSlot1, checkSlot2, checkRow, checkCol, checkRow2, checkCol2, correctTurns = 0, totalTime=0, timeSec=0; bool winGame = false; while ( correctTurns < amountOfPairs) { totalTime = 0; auto startTime = chrono::steady_clock::now(); do { cout << "Enter first slot to view: "; cin >> checkSlot1; } while(rowsInput*colsInput < checkSlot1 || checkSlot1 < 1); //re-prompts if number is out of bounds do { cout << "Enter second slot to view: "; cin >> checkSlot2; } while(rowsInput*colsInput < checkSlot2 || checkSlot2 < 1 || checkSlot2 == checkSlot1); //re-prompts if number is out of bounds or the same as first guess checkRow = (checkSlot1- 1)/colsInput; //getting rows and columns to check for the guesses checkCol = (checkSlot1 - (checkRow*colsInput))- 1; checkRow2 = (checkSlot2- 1)/colsInput; checkCol2 = (checkSlot2 - (checkRow2*colsInput))- 1; boardNums[checkRow][checkCol] = boardChar[checkRow][checkCol]; //replacing the number with the eltter for the reveal boardNums[checkRow2][checkCol2] = boardChar[checkRow2][checkCol2]; printNBoard(boardNums); if(boardChar[checkRow][checkCol] == boardChar[checkRow2][checkCol2]){ //if matched! if(boardNumsLastCorrect == boardNums) { //re-prompts if previously matched cout << "Previously matched" << endl; } else { cout << "Match" << endl; cout << '\a'; boardNumsLastCorrect = boardNums; correctTurns++; } } else { boardNums = boardNumsLastCorrect; cout << "No Match" << endl; } auto endTime = chrono::steady_clock::now(); totalTime = chrono::duration_cast<chrono::seconds>(endTime-startTime).count(); timeSec += totalTime; if(timeSec > (amountOfPairs*30)) { //if overtime, breaks out of loop winGame = false; break; } if(amountOfPairs = correctTurns){ winGame = true; } } //ending game outputs if(winGame) { cout << "All matched within " << (timeSec/60) << " minutes and " << timeSec%60 << " seconds"; } else { cout << "Time has expired" << "\n You revealed:" << endl; printNBoard(boardNumsLastCorrect); cout << "\n All the pairs were at:" << endl; printCBoard(boardChar); } }
true
a942b8f652845154ec3acad1bf99acc404ee2c1f
C++
Tanjim131/Problem-Solving
/UVa/301.cpp
UTF-8
2,064
3.375
3
[]
no_license
#include <iostream> #include <tuple> #include <vector> #include <algorithm> class Order{ public: int source, destination, passangers; friend std::istream& operator >> (std::istream&, Order&); bool operator < (const Order &order) const{ return std::tie(source, destination, passangers) < std::tie(order.source, order.destination, order.passangers); } }; std::istream& operator >> (std::istream &in, Order &order){ in >> order.source >> order.destination >> order.passangers; return in; } int backtrack(const std::vector <Order> &orders, int total_passangers, int current_index = 0, int current_passangers = 0, int current_profit = 0, std::vector <int> destinations = std::vector<int>(8,0)){ if(current_index == orders.size()){ return current_profit; } for(int i = orders[current_index].source ; i > 0 ; --i){ if(destinations[i] > 0){ current_passangers -= destinations[i]; destinations[i] = 0; } } int s,d,p; std::tie(s,d,p) = std::tie(orders[current_index].source, orders[current_index].destination, orders[current_index].passangers); int ret1 = -1; if(current_passangers + p <= total_passangers){ int profit = (d - s) * p; destinations[d] += p; ret1 = backtrack(orders, total_passangers, current_index + 1, current_passangers + p, current_profit + profit, destinations); destinations[d] -= p; } int ret2 = backtrack(orders, total_passangers, current_index + 1, current_passangers, current_profit, destinations); return std::max(ret1, ret2); } int main(int argc, char const *argv[]) { int n, cityB, numOrders; while(std::cin >> n >> cityB >> numOrders){ if(!n && !cityB && !numOrders) break; std::vector <Order> orders(numOrders); for(int i = 0 ; i < numOrders ; ++i){ std::cin >> orders[i]; } std::sort(orders.begin(), orders.end()); std::cout << backtrack(orders, n) << '\n'; } return 0; }
true
1d7eebeb67eae9d9f95ee8dce818cf83937ba5b0
C++
jsunlove/wangdao-data-structure
/ch2/static-link/with.cpp
UTF-8
375
2.671875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #define MaxSize 10 struct Node { int data; int next; }; typedef struct { int data; int next; } SLinkList[MaxSize]; int main() { struct Node x; printf("sizeX=%d\n", sizeof(x)); struct Node a[MaxSize]; printf("sizeA=%d\n", sizeof(a)); SLinkList b; printf("sizeB=%d\n", sizeof(b)); return 0; }
true
99f21dc1f7cedbca4c22c96c8a511b090e7671a6
C++
tyszek00/DodatekDoEmerytury
/main.cpp
UTF-8
3,685
3.046875
3
[]
no_license
#include <iostream> #include <iomanip> #include <math.h> #include <conio.h> using namespace std; bool sprawdzPoprawnoscWprowadzonegoZnaku(char znak); bool sprawdzPoprawnoscWprowadzonegoZnakuDlaKapitalizacji(char znak); int main() { float pozadanaMiesiecznaEmerytura; float oprocentowanieLokaty; float podatek = 0.19; int wiekObecny; int wiekPrzejsciaNaEmeryture; char kapitalizacja; int kapitalizacjaInt; char wyjscieZprogramu; string czestotliwoscOdkladania; do { cout << "Ile masz obecnie lat?: "; cin >> wiekObecny; cout << "W jakim wieku chcesz przejsc na emeryture?: "; cin >> wiekPrzejsciaNaEmeryture; cout << "W jakiej wysokosci chcialbys miec dodatek do emerytury?: "; cin >> pozadanaMiesiecznaEmerytura; cout << "Podaj oprocentowanie lokaty (w procentach): "; cin >> oprocentowanieLokaty; cout << "Podaj kapitalizacje (c - codzienna; m - miesieczna; r - roczna): "; cin >> kapitalizacja; while (sprawdzPoprawnoscWprowadzonegoZnakuDlaKapitalizacji(kapitalizacja) != true) { cout << "Wcisnij klawisz 'c', 'm' lub 'r': "; cin >> kapitalizacja; } switch (kapitalizacja) { case 'c': kapitalizacjaInt = 365; czestotliwoscOdkladania = "codziennie"; break; case 'm': kapitalizacjaInt = 12; czestotliwoscOdkladania = "miesiecznie"; break; case 'r': kapitalizacjaInt = 1; czestotliwoscOdkladania = "rocznie"; break; } int lataPracy = wiekPrzejsciaNaEmeryture - wiekObecny; oprocentowanieLokaty = oprocentowanieLokaty / 100; float odsetkiWskaliRoku = 12 * pozadanaMiesiecznaEmerytura / (1 - podatek); float uzbieranaKwota = odsetkiWskaliRoku / oprocentowanieLokaty; float licznik = uzbieranaKwota * (oprocentowanieLokaty / kapitalizacjaInt) * (1 - podatek); float liczbaPotegowana = (1 + (oprocentowanieLokaty / kapitalizacjaInt) * (1 - podatek)); int wykladnik = lataPracy*kapitalizacjaInt; float mianownik = liczbaPotegowana*(pow(liczbaPotegowana, wykladnik) - 1); float skladka = licznik / mianownik; cout << endl << "Aby po " << lataPracy << " latach pracy, odkladane na lokate oprocentowana na " << (oprocentowanieLokaty*100) << " procent " << endl; cout << "miec miesieczny dodatek do emerytury w wysokosci " << pozadanaMiesiecznaEmerytura << " zl wyplacanych wylacznie z odsetek " << endl; cout << fixed << setprecision(2); cout << "nalezy " << czestotliwoscOdkladania << " odkladac " << skladka << " zl" << endl; cout << "To pozwoli Ci uzbierac kwote w wysokosci: " << uzbieranaKwota << " zl" << endl; cout << endl << "Czy chcesz wykonac nastepna kalkulacje? (t/n): "; cin >> wyjscieZprogramu; while (sprawdzPoprawnoscWprowadzonegoZnaku(wyjscieZprogramu) != true) { cout << "Wcisnij klawisz 't' lub 'n': "; cin >> wyjscieZprogramu; } } while (wyjscieZprogramu != 'n'); cout << endl << "Wcisnij dowolny klawisz, aby zamknac program..."; getch(); return 0; } bool sprawdzPoprawnoscWprowadzonegoZnaku(char znak) { if (znak == 'n' || znak == 't') return true; else return false; } bool sprawdzPoprawnoscWprowadzonegoZnakuDlaKapitalizacji(char znak) { if (znak == 'c' || znak == 'm' || znak == 'r') return true; else return false; }
true
3d18eeb975f844fc7cdfd19f8fc3bc5b8f918636
C++
rustysec/fuzzypp
/Roll.h
UTF-8
887
2.609375
3
[ "MIT" ]
permissive
#ifndef ROLL_H_ #define ROLL_H_ #include "FuzzyConstants.h" #include <vector> namespace FuzzyPP { class Roll { std::vector<unsigned char> _window = std::vector<unsigned char>(FuzzyConstants::I().RollingWindow); unsigned int _h1; unsigned int _h2; unsigned int _h3; unsigned int _n; public: unsigned int Sum(); /* * a rolling hash, based on the Adler checksum. By using a rolling hash * we can perform auto resynchronisation after inserts/deletes * internally, h1 is the sum of the bytes in the window and h2 * is the sum of the bytes times the index * h3 is a shift/xor based rolling hash, and is mostly needed to ensure that * we can cope with large blocksize values */ void Hash(unsigned char c); Roll(); }; } #endif /* ROLL_H_ */
true
366797fe53dcfe52e0b3fb600985fec710129895
C++
JoaoBarros93/AEDA
/src/area.cpp
UTF-8
947
3.265625
3
[]
no_license
#include "area.h" Area::Area(){ } Area::Area(stringstream& s) { string newAreaName, newSubAreaName, newAreaNameSigla, newSubAreaNameSigla; if (!getline(s, newAreaName, ';')) cout << "Error reading area name" << endl; this->areaName = newAreaName; if (!getline(s, newSubAreaName, ';')) cout << "Error reading sub area name" << endl; this->subAreaName = newSubAreaName; if (!getline(s, newAreaNameSigla, ';')) cout << "Error reading area name acronym" << endl; this->areaNameSigla = newAreaNameSigla; if (!getline(s, newSubAreaNameSigla, ';')) cout << "Error reading sub area name acronym" << endl; this->subAreaNameSigla = newSubAreaNameSigla; } string Area::getAreaName() { return areaName; } string Area::getSubAreaName(){ return subAreaName; } string Area::getAreaNameSigla(){ return areaNameSigla; } string Area::getSubAreaNameSigla(){ return subAreaNameSigla; }
true
69466771763d1494a357b1de3034e2e0bd622614
C++
matgrz/GenAlgorithm
/GenAlgorithm/dataplotting/DataWriter.cpp
UTF-8
1,185
3
3
[]
no_license
#include "DataWriter.h" #include <ctime> #include <fstream> namespace dataplotting { DataWriter::DataWriter(const std::string& path) : appPath{path} { if (!std::filesystem::exists(path + dataDirName)) std::filesystem::create_directory(path + dataDirName); } void DataWriter::saveData(const algorithm::types::ResultsPerIteration& results) { std::ofstream ofs(appPath / dataDirName / getFileName()); ofs << "iteration,value,x, y\n"; for (const auto& resultPair : results) { const int iteration = resultPair.first; for (const auto& result : resultPair.second) ofs << iteration << "," << result.z << "," << result.x << "," << result.y << "\n"; } ofs.close(); } std::string DataWriter::getFileName() { time_t now = time(0); tm* ltm = localtime(&now); std::string fileName{ std::to_string(1900 + ltm->tm_year) + "-" + std::to_string(1 + ltm->tm_mon) + "-" + std::to_string(ltm->tm_mday) + "_" + std::to_string(1 + ltm->tm_hour) + "-" + std::to_string(1 + ltm->tm_min) + "-" + std::to_string(1 + ltm->tm_sec) }; return fileName.append("_result.csv"); } }
true
fadf0a5e82f6f59feb6134834f69807b877a21e4
C++
karaketir16/competitive
/karaketir16/tst.cpp
UTF-8
2,445
2.546875
3
[]
no_license
#include <bits/stdc++.h> #define pb push_back #define fi first #define sc second #define inf 1000000000000000LL #define MP make_pair #define min3(a,b,c) min(a,min(b,c)) #define max3(a,b,c) max(a,max(b,c)) #define dbg(x) cerr<<#x<<":"<<x<<endl #define N 100005 #define MOD 1000000007 #define orta ((a+b)/2) using namespace std; #define pp pair<int,int> typedef long long int lint; //////////////////////////////////////////////////////////////////////////////////////// /* * Function that calculate how many times s is found in text * */ int KMP(string &s, string &text) { int found_number=0; int pn; pn=s.size(); int textn; textn=text.size(); vector<int> pat(pn,0); int len=0; for(int i=1;i<pn;) { if(s[len]==s[i]) { len++; pat[i]=len; i++; } else { if(len==0) { i++; } else { len=pat[len-1]; } } } for(int i=0,j=0;i<pn,j<textn;) { if(s[i]==text[j]) { if(i==pn-1) { found_number++; i=pat[i-1]; } else { i++; j++; } } else { if(i>0) { i=pat[i-1]; } else { j++; } } } return found_number; } ///////////////////////////////////////////////////////////////////////////// struct Compare { constexpr bool operator()(pair<lint, lint> const & a, pair<lint, lint> const & b) const noexcept { return a.first > b.first || (a.first == b.first && a.second > b.second); } }; priority_queue<pair<lint,lint>, vector<pair<lint,lint>>, Compare> pq_pair() { priority_queue<pair<lint,lint>, vector<pair<lint,lint>>, Compare> Q; return Q; } ////////////////////////////////////////////////////////////////////////////////// int main() { srand(time(NULL)); auto Q=pq_pair(); for(int i=0;i<10;i++) Q.push(MP(rand()%10,rand()%10)); for(int i=0;i<10;i++) { cout<<Q.top().fi<<" "<<Q.top().sc<<endl; Q.pop(); } return 0; }
true
f0d24012a0bbdf8db261537c6b02dbc290b13d65
C++
kunichan9292/Programing-contest
/AtCoder/APG4b/B-Minesweeper.cpp
UTF-8
1,019
2.53125
3
[]
no_license
#include<iostream> #define _GLIBCXX_DEBUG using namespace std; int main(){ int H,W; int c[30][50]; string S; cin >> H >> W; for(int i=0;i<H;i++){ for(int j=0;j<W;j++){ c[i][j]=0; } } for(int i=0;i<H;i++){ cin >> S; for(int j=0;j<W;j++){ if(S[j]=='#' && (i!=0 || i!=W-1)){ c[i][j]+=10; c[i-1][j-1]++; c[i-1][j]++; c[i-1][j+1]++; c[i][j-1]++; c[i][j+1]++; c[i+1][j-1]++; c[i+1][j]++; c[i+1][j+1]++; } else if(S[j]=='#' && i==0){ c[i][j]+=10; c[i][j-1]++; c[i][j+1]++; c[i+1][j-1]++; c[i+1][j]++; c[i+1][j+1]++; } else if(S[j]=='#' && i==W-1){ c[i][j]+=10; c[i][j-1]++; c[i][j+1]++; c[i-1][j-1]++; c[i-1][j]++; c[i-1][j+1]++; } } } for(int i=0;i<H;i++){ for(int j=0;j<W;j++){ if(c[i][j]>8){ cout << '#'; } else{ cout << c[i][j]; } } cout << endl; } }
true
bc0f2ded19fc619788167982ce2d1248c949ffee
C++
strengthen/LeetCode
/C++/736.cpp
UTF-8
6,121
3.4375
3
[ "MIT" ]
permissive
__________________________________________________________________________________________________ sample 8 ms submission #define DEBUG 0 class LispExpr { private: unordered_map<string, int> data; // store the data for current expression; a better name is "context" public: LispExpr () {} LispExpr (unordered_map<string, int>& data) : data(data) {} int parse(string& expr, int& ind) { // parse a value from expr, key, or number. if (expr[ind] == '(') return parseExpr(expr, ind); if (isdigit(expr[ind]) || expr[ind] == '-') return parseInt(expr, ind); if (isalpha(expr[ind])) return data[parseKey(expr, ind)]; return -1; } int parseExpr(string& expr, int& ind) { // deal with the expression parssing. if (expr.substr(ind + 1, 3) == "let") return processLet(expr, ind); if (expr.substr(ind + 1, 3) == "add") return processAdd(expr, ind); return processMult(expr, ind); } int processAdd(string& expr, int& ind) { ind += 5; int v1 = parse(expr, ind); // recursion with loops, parse -> parseExpr->processXXX -> parse -> ... ind++; int v2 = parse(expr, ind); ind++; return v1 + v2; } int processMult(string& expr, int& ind) { ind += 6; int v1 = parse(expr, ind); // recursion with loops, parse -> parseExpr->processXXX -> parse -> ... ind++; int v2 = parse(expr, ind); ind++; return v1 * v2; } int processLet(string& expr, int& ind) { // for Let, it means a new level of string to be processed. ind += 5; LispExpr cur(data); // copy the data to the new level while (true) { // Most difficult is about how to determine the current one is the final expression. string key = parseKey(expr, ind); // try to get key if (expr[ind] == ')') { // final loc reached case 1. ind++; // finish current level. if (key[0] == '-' || isdigit(key[0])) return stoi(key); return cur.getData(key); // it is the end } else if (key.empty()) { // final loc reached case 2. int res = cur.parse(expr, ind); ind++; return res; } else { // It is a key found, then, need to get data. ind++; int v = cur.parse(expr, ind); ind++; // move to the next key. cur.setData(key, v); } } } int getData(string key) { return data[key]; } void setData(string key, int v) { data[key] = v; } private: int parseInt(string& expr, int& ind) { // this way, it is like treating the string as a stream int v = 0; // I didn't expect negative values in the beginning. int sign = 1; if (expr[ind] == '-') { ind++; sign = -1; } while (isdigit(expr[ind])) v = v * 10 + (expr[ind++] - '0'); return v * sign; } string parseKey(string& expr, int& ind) { // I was assuming the key is pure alphabet, but it may contain number. string key; // Now, parsing the key is the most carful stuff. while (expr[ind] != ' ' && expr[ind] != ')' && expr[ind] != '(') key += expr[ind++]; return key; } }; class Solution { public: /* (let v1 e1 v2 e2 ... vn en expr) => value of expr (add e1 e2) (mult e1 e2) */ int evaluate(string expression) { LispExpr parser; int index = 0; return parser.parseExpr(expression, index); } }; __________________________________________________________________________________________________ sample 11740 kb submission string get_str(string& exp, int i) { string s; while (i < exp.size() && exp[i] != ' ' && exp[i] != ')') { s += exp[i++]; } return s; } class Solution { // eval exp from i, no left (, close with right ) int eval(string& exp, int &i, unordered_map<string, int>& values) { if (exp[i] != '(') { int rtn = 0; string s = get_str(exp, i); i += s.size(); if (isdigit(s[0]) || s[0] == '-') rtn = stoi(s); else rtn = values[s]; return rtn; } ++i; // first must be op, otherwise invalid string op = get_str(exp, i); i += op.size(); ++i; // skip space // copy last variables if (op == "let") { unordered_map<string, int> new_val(values); while (true) { if (exp[i] == '(') { int rtn = eval(exp, i, new_val); ++i; // ')' return rtn; } else { string var = get_str(exp, i); i += var.size(); if (isdigit(var[0]) || var[0] == '-') { int rtn = stoi(var); ++i; // ')' return rtn; } else if (exp[i] == ')') { // the return var int rtn = new_val[var]; ++i; // ')' return rtn; } else { // not return value, parse the next expression ++i; // ' ' int value = eval(exp, i, new_val); new_val[var] = value; ++i; // ')' } } } } else if (op == "add" || op == "mult") { int opnd1 = eval(exp, i, values); ++i; // ' ' int opnd2 = eval(exp, i, values); ++i; // ')' if (op == "add") return opnd1 + opnd2; else return opnd1 * opnd2; } return 0; } public: int evaluate(string expression) { unordered_map<string, int> values; int i = 0; return eval(expression, i, values); } }; __________________________________________________________________________________________________
true
f620e155123273fc04eb64c9ed0f2b56ad387df0
C++
laravignotto/books_exercises
/Programming_Principles_and_Practice_Using_C++/chapter-4/ch4-ex6.cpp
UTF-8
884
3.953125
4
[]
no_license
#include "std_lib_facilities.h" int main() { vector<string> v = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}; char choice = {' '}; cout << "Would you like to convert digits to words ('d') or words to digits ('w')?" << endl; cin >> choice; if (choice == 'd') { int digit = {0}; cout << "Insert a single digit and press [enter]." << endl; for (; cin >> digit;) cout << v[digit] << endl; } else if (choice == 'w') { string word = {" "}; cout << "Insert a spelled out digit and press [enter]." << endl; for (; cin >> word;) { for (int i=0; i<v.size(); ++i) { if (word == v[i]) cout << i << endl; } } } else cout << "Invalid input. Enter eiter 'd' or 'w'." << endl; }
true
03d10b07b263e66023ce664040634de862c6259c
C++
TheRoD2k/SquareCalculator
/Test/SquareCalculator.h
UTF-8
943
3
3
[]
no_license
#pragma once #include <variant> #include "Figure.h" class SquareCalculator { public: // SquareCalculator(Figure fig, ...); - other possible realization SquareCalculator(Figure fig, double x0, double y0, double radius); SquareCalculator(Figure fig, double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4); SquareCalculator(Figure fig, double x1, double y1, double x2, double y2, double x3, double y3); void SetFigure(Figure fig, double x0, double y0, double radius); void SetFigure(Figure fig, double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4); void SetFigure(Figure fig, double x1, double y1, double x2, double y2, double x3, double y3); double GetSquare() const; private: // Using std::variant to store different possible figures while using one interface std::variant<std::monostate, CircleFigure, QuadrangleFigure, TriangleFigure> _variant; Figure _fig; };
true
1d8a3f4d71bd77096161608dcaece345279322ba
C++
idadue/ComputationalPhysics
/project1/main.h
UTF-8
8,958
3.1875
3
[]
no_license
#ifndef MAIN_H #define MAIN_H #include <fstream> #include <string> #include <algorithm> #include <cmath> #include <iomanip> #include <armadillo> #include <time.h> /* * This part checks during pre proccessing what system the user is using. If the user is using windows, they should have * direct.h and io.h located on their system, and if the user has a unix based system, they should have unistd.h and sys/stat.h * on their system. We only want to include libraries that the user already has, and ignore the others, such that we do not get any compile errors. */ #if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__) #include <direct.h> #include <io.h> #define access _access_s #define GetCurrentDir _getcwd #define createFolder _mkdir #define F_OK 0 std::string slash = "//"; #else #include <unistd.h> #include <sys/stat.h> #define createFolder mkdir #define GetCurrentDir getcwd std::string slash = "/"; #endif /*Creates a folder in current path*/ void create_directory(std::string filename) { char *dir = const_cast<char *>(filename.c_str()); //mkdir and _mkdir take different arguments, so we need to make sure we are passing them correctly #if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__) createFolder(dir); #else createFolder(dir, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); #endif } /*Returns path to current directory*/ std::string get_current_dir() { char buff[FILENAME_MAX]; GetCurrentDir(buff, FILENAME_MAX); std::string current_working_dir(buff); for (int i = 0; i < int(current_working_dir.length()); i++) { if (current_working_dir[i] == '\\') { current_working_dir.replace(i, 1, slash); } } return current_working_dir; } /*Output data to file with the .csv type*/ void writeToFile(std::string filename, int n, double *v, double *u, double *rel_err = 0) { std::ofstream ofile; std::string file = filename; //Create a new folder in current directory and get path create_directory(filename); std::string dir = get_current_dir(); //Append filename with value of n, and give type; i.e filename_n.csv file.append("_" + std::to_string(n) + ".csv"); ofile.open(dir + slash + filename + slash + file, std::fstream::out); if (ofile.is_open()) { ofile << "Numeric,"; if (rel_err != 0) { ofile << "Analytic,"; ofile << "Relative Error:" << std::endl; for (int i = 0; i < n; i++) { ofile << v[i] << ","; ofile << u[i] << ","; ofile << rel_err[i] << std::endl; } } else { ofile << "Analytic" << std::endl; for (int i = 0; i < n; i++) { ofile << v[i] << ","; ofile << u[i] << std::endl; } } } ofile.close(); } /*Writes execution times to file*/ void writeExecTimeToFile(std::string filename, int n, double exec_time) { std::ofstream ofile; std::string file = filename; exec_time *= 1000; //converting to ms create_directory(filename); std::string dir = get_current_dir(); file.append("_" + std::to_string(n) + "_timing" + ".csv"); std::string fileDir = dir + slash + filename + slash + file; //access checks whether or not the file already exists if (access(fileDir.c_str(), F_OK) == 0) { ofile.open(fileDir, std::fstream::app); if (ofile.is_open()) { ofile << n << ","; ofile << std::fixed << std::setprecision(4) << exec_time << std::endl; } } else { ofile.open(fileDir, std::fstream::out); if (ofile.is_open()) { ofile << "n,"; ofile << std::fixed << std::setprecision(4) << "ms" << std::endl; ofile << n << ","; ofile << exec_time << std::endl; } } ofile.close(); } /* This function solves the general equation Av = h^2 *f, using a general algortihm a_v --- vector of constants a_1...a_n-1 b_v --- vector of constants b_1...b_n c_v --- vector of constants c_1...c_n-1 b_tilde = h^2*f(x_i) v - unknown f - known function A - tridiagonal matrix n - number of integration points h - step size */ double *generalSolver(int n, double h, int a, int b, int c) { /*Note: Declaring a_v, b_v and c_v as arrays and filling them with a singular value is technically redundant since the program can only take in one value for each, but since the performance hit is minimal, we will leave it as is.*/ double *a_v = new double[n - 1]; double *b_v = new double[n]; double *c_v = new double[n - 1]; double *b_tilde = new double[n]; double *v = new double[n]; b_v[0] = b; b_tilde[0] = h * h * 100 * std::exp(-10 * h); for (int i = 0; i < n - 1; i++) { a_v[i] = a; b_v[i + 1] = b; c_v[i] = c; b_tilde[i + 1] = h * h * 100 * exp(-10 * (i + 2) * h); //i + 2 to compensate for b_tilde[i + 1] } //Forwards substitution for (int i = 1; i < n; i++) { b_v[i] = b_v[i] - c_v[i - 1] * a_v[i - 1] / b_v[i - 1]; b_tilde[i] = b_tilde[i] - b_tilde[i - 1] * a_v[i - 1] / b_v[i - 1]; } //Apply backward substitution v[n - 1] = b_tilde[n - 1] / b_v[n - 1]; for (int i = n - 2; i > -1; i--) { v[i] = (b_tilde[i] - c_v[i] * v[i + 1]) / b_v[i]; } delete[] a_v, b_v, c_v, b_tilde; return v; } /* This function solves the general equation Av = h^2 *f for the specific tridiagonal case of -1, 2, -1 For details, see generalSolver() */ double *specSolver(int n, double h) { double *b_v = new double[n]; double *b_tilde = new double[n]; double *v = new double[n]; b_v[0] = 2; b_tilde[0] = h * h * 100 * std::exp(-10 * h); for (int i = 1; i < n; i++) { b_v[i] = (i + 2.0) / (i + 1.0); //analytical expression of b_v b_tilde[i] = h * h * 100 * exp(-10 * (i + 1) * h) + b_tilde[i - 1] / b_v[i - 1]; //immediately calculating b_tilde with forward substitution } v[n - 1] = b_tilde[n - 1] / b_v[n - 1]; //Solving the final row //Apply backward substitution for (int i = n - 2; i > -1; i--) { v[i] = (b_tilde[i] + v[i + 1]) / b_v[i]; } delete[] b_v, b_tilde; return v; } /* Using Armadillo for LU decomp. We have A*v = b_tilde Since A = L*U, we define U*v = w, which means L*w = b_tilde Then we solve first w and then v. */ double *lusolver(int n, double h, int a, int b, int c) { //using armadillo for the matrix handling arma::vec b_tilde(n); arma::vec w(n); arma::vec v(n); arma::mat A(n, n); double *v_pointer = new double[n]; //for compatibility with writeToFile //initializing the matrix A with -1 2 -1 A.fill(0.0); A(0, 0) = b; /*There is a better way of doing this, using armadillo A.diag()*/ for (int i = 1; i < n; i++) { A(i, i) = b; A(i - 1, i) = c; A(i, i - 1) = a; } //LU decomp arma::mat L, U; arma::lu(L, U, A); //solving w for (int i = 0; i < n; i++) { b_tilde(i) = h * h * 100 * std::exp(-10 * h * (i + 1)); w(i) = b_tilde(i); for (int j = 0; j < i; j++) { w(i) -= L(i, j) * w(j); } } //solving v for (int i = n - 1; i > -1; i--) { v(i) = w(i); for (int j = n - 1; j > i; j--) { v(i) -= U(i, j) * v(j); } v(i) /= U(i, i); v_pointer[i] = v(i); } return v_pointer; } /*Returns the analytical solution of equation u, with n integration points*/ double *analyticalSolution(int n, double h) { double *u = new double[n]; for (int i = 0; i < n; i++) { u[i] = 1 - (1 - std::exp(-10)) * (i + 1) * h - std::exp(-10 * (i + 1) * h); } return u; } /*Times and outputs the execution of the algorithms*/ void time_and_write(double *(*solver)(int, double, int, int, int), int n, int a, int b, int c, std::string task) { std::clock_t start, finish; double h = 1.0 / (n + 1); double *v; if (a == 0 || b == 0 || c == 0) { start = std::clock(); v = specSolver(n, h); finish = std::clock(); } else { start = std::clock(); v = solver(n, h, a, b, c); finish = std::clock(); } double *u = analyticalSolution(n, h); double execution_time = double(finish - start) / double(CLOCKS_PER_SEC); std::cout << "Execution time for n = " << n << " is " << std::fixed << std::setprecision(4) << execution_time * 1000 << "ms" << std::endl; writeToFile(task, n, v, u); writeExecTimeToFile(task, n, execution_time); delete[] v, u; } #endif
true
aa84e8594e392b21c4134c0adcd12467106ab626
C++
dedowsdi/journey
/gl4/demo/parallaxmap/parallaxmap.cpp
UTF-8
9,355
2.703125
3
[]
no_license
/* * Parallax map. * * Normalmap tried to use coarse grained geometry instead of fine grained * geometry, it reserved normals of fined grained geometry in normal map(tangent * space), but it doesn't reserve the surface detail, tangent space surface is * always flat, which means the vertex point you look at in a coarsed grained * geometry can not be the same vertex point as you llok at it's fine grained * cousin. Parallax map is used to overcome this problem, it was applied on * trangent space, with an extra depth map(invert of height map). In tangent * space xy component of viewdir is aligned to uv, and the offset is propotion * to depth (in a positive random way), so we can approximate the offset based * on depth, and apply the offset to texcoord to retrieve normal from normal * map. * */ #include <app.h> #include <bitmap_text.h> #include <sstream> #include <common.h> #include <light.h> #include <quad.h> #include <texutil.h> #include <program.h> #include <stream_util.h> namespace zxd { glm::mat4 m_mat; glm::mat4 v_mat; glm::mat4 p_mat; struct parallax_program : public program { GLint ul_normal_map; GLint ul_diffuse_map; GLint ul_depth_map; GLint ul_m_camera; GLint ul_height_scale; GLint ul_mvp_mat; GLuint parallax_method{0}; virtual void update_uniforms(const mat4 &m_mat) { mat4 mv_mat = v_mat * m_mat; // mat4 mv_mat_i = glm::inverse(mv_mat); // mat4 m_mat_i = glm::inverse(m_mat); mat4 mvp_mat = p_mat * mv_mat; glUniformMatrix4fv(ul_mvp_mat, 1, 0, glm::value_ptr(mvp_mat)); }; virtual void attach_shaders() { string_vector sv; sv.push_back("#version 430 core\n #define LIGHT_COUNT 1\n"); attach(GL_VERTEX_SHADER, sv, "shader4/parallaxmap.vs.glsl"); std::stringstream ss; ss << "#define PARALLAX_METHOD " << parallax_method << std::endl; sv.push_back(ss.str()); sv.push_back(stream_util::read_resource("shader4/blinn.frag")); attach(GL_FRAGMENT_SHADER, sv, "shader4/parallaxmap.fs.glsl"); name("parallaxmap"); } virtual void bind_uniform_locations() { ul_mvp_mat = get_uniform_location("mvp_mat"); ul_normal_map = get_uniform_location("normal_map"); ul_diffuse_map = get_uniform_location("diffuse_map"); ul_depth_map = get_uniform_location("depth_map"); ul_m_camera = get_uniform_location("m_camera"); ul_height_scale = get_uniform_location("height_scale"); } virtual void bind_attrib_locations() { bind_attrib_location(0, "vertex"); bind_attrib_location(1, "normal"); bind_attrib_location(2, "texcoord"); bind_attrib_location(3, "tangent"); }; } prg; GLuint normal_map, diffuse_map, depth_map; std::vector<zxd::light_source> lights; zxd::light_model light_model; zxd::material material; quad q; GLfloat height_scale = 0.05f; std::string parallax_methods[] = {"parallax_occlusion_map", "parallaxSteepMap", "parallax_map_with_offset", "parallaxMapWithoutOffset"}; class normal_map_app : public app { protected: public: normal_map_app() {} virtual void init_info() { app::init_info(); m_info.title = "hello world"; m_info.wnd_width = 512; m_info.wnd_height = 512; } virtual void create_scene() { glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); prg.parallax_method = 3; prg.init(); p_mat = glm::perspective(glm::radians(45.0f), 1.0f, 0.1f, 20.0f); v_mat = glm::lookAt(vec3(0, -5, 5), vec3(0.0f), vec3(0, 1, 0)); // init quad q.build_mesh({attrib_semantic::vertex, attrib_semantic::normal, attrib_semantic::texcoord, attrib_semantic::tangent}); // load maps fipImage diffuse_image = zxd::fipLoadResource("texture/bricks2.jpg"); fipImage normal_image = zxd::fipLoadResource("texture/bricks2_normal.jpg"); fipImage depth_image = zxd::fipLoadResource("texture/bricks2_disp.jpg"); glGenTextures(1, &diffuse_map); glBindTexture(GL_TEXTURE_2D, diffuse_map); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, diffuse_image.getWidth(), diffuse_image.getHeight(), 0, GL_BGR, GL_UNSIGNED_BYTE, diffuse_image.accessPixels()); glGenTextures(1, &normal_map); glBindTexture(GL_TEXTURE_2D, normal_map); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, normal_image.getWidth(), normal_image.getHeight(), 0, GL_BGR, GL_UNSIGNED_BYTE, normal_image.accessPixels()); glGenTextures(1, &depth_map); glBindTexture(GL_TEXTURE_2D, depth_map); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, depth_image.getWidth(), depth_image.getHeight(), 0, GL_BGR, GL_UNSIGNED_BYTE, depth_image.accessPixels()); // light zxd::light_source dir_light; dir_light.position = vec4(0, -1, 1, 0); dir_light.diffuse = vec4(1, 1, 1, 1); dir_light.specular = vec4(1, 1, 1, 1); dir_light.linear_attenuation = 1.0f; lights.push_back(dir_light); light_model.local_viewer = 1; // material material.ambient = vec4(0.2); material.diffuse = vec4(0.8); material.specular = vec4(0.8); material.shininess = 50; set_v_mat(&v_mat); bind_uniform_locations(prg); } virtual void display() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // draw low quality mesh with normal map glUseProgram(prg); prg.update_uniforms(m_mat); glUniform1i(prg.ul_diffuse_map, 0); glUniform1i(prg.ul_normal_map, 1); glUniform1i(prg.ul_depth_map, 2); glUniform1f(prg.ul_height_scale, height_scale); mat4 mv_mat_i = glm::inverse(v_mat * m_mat); mat4 m_mat_i = glm::inverse(m_mat); // get camera model position vec3 camera = vec3(glm::column(mv_mat_i, 3)); glUniform3fv(prg.ul_m_camera, 1, glm::value_ptr(camera)); for (int i = 0; i < lights.size(); ++i) { lights[i].update_uniforms(m_mat_i); } light_model.update_uniforms(); material.update_uniforms(); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, diffuse_map); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, normal_map); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, depth_map); q.draw(); glEnable(GL_BLEND); glDisable(GL_SCISSOR_TEST); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); std::stringstream ss; ss << "q : parallax method : " << parallax_methods[prg.parallax_method] << std::endl; ss << "w : height_scale : " << height_scale << std::endl; ss << "fps : " << m_fps << std::endl; m_text.print(ss.str(), 10, wnd_height()- 25); glDisable(GL_BLEND); } virtual void update() {} virtual void glfw_resize(GLFWwindow *wnd, int w, int h) { app::glfw_resize(wnd, w, h); } virtual void bind_uniform_locations(zxd::program &prg) { light_model.bind_uniform_locations(prg.get_object(), "lm"); for (int i = 0; i < lights.size(); ++i) { std::stringstream ss; ss << "lights[" << i << "]"; lights[i].bind_uniform_locations(prg.get_object(), ss.str()); } material.bind_uniform_locations(prg.get_object(), "mtl"); } virtual void glfw_key( GLFWwindow *wnd, int key, int scancode, int action, int mods) { if (action == GLFW_PRESS) { switch (key) { case GLFW_KEY_ESCAPE: glfwSetWindowShouldClose(m_wnd, GL_TRUE); break; case GLFW_KEY_Q: { prg.parallax_method = (prg.parallax_method + 1) % 4; prg.clear(); prg.init(); } break; break; default: break; } } if (action == GLFW_PRESS || action == GLFW_REPEAT) { switch (key) { case GLFW_KEY_W: if (mods & GLFW_MOD_SHIFT) { height_scale -= 0.002; height_scale = glm::max(height_scale, 0.0f); } else { height_scale += 0.002; } break; default: break; } } app::glfw_key(wnd, key, scancode, action, mods); } virtual void glfw_mouse_button( GLFWwindow *wnd, int button, int action, int mods) { app::glfw_mouse_button(wnd, button, action, mods); } virtual void glfw_mouse_move(GLFWwindow *wnd, double x, double y) { app::glfw_mouse_move(wnd, x, y); } virtual void glfw_mouse_wheel( GLFWwindow *wnd, double xoffset, double yoffset) { app::glfw_mouse_wheel(wnd, xoffset, yoffset); } }; } int main(int argc, char *argv[]) { zxd::normal_map_app app; app.run(); }
true
e8f7a74a0d77493e11efa47560cf4df9fde57e2a
C++
Gregory-Meyer/polymorphic-allocator
/include/pool_allocator.hpp
UTF-8
11,286
2.875
3
[]
no_license
#ifndef GREGJM_POOL_ALLOCATOR_HPP #define GREGJM_POOL_ALLOCATOR_HPP #include "polymorphic_allocator.hpp" // gregjm::PolymorphicAllocator, // gregjm::MemoryBlock, // gregjm::PolymorphicAllocatorAdaptor, // gregjm::NotOwnedException #include "stack_allocator.hpp" // gregjm::StackAllocator #include "dummy_mutex.hpp" // gregjm::DummyMutex #include <cstddef> // std::size_t, std::ptrdiff_t #include <cstring> // std::memcpy #include <algorithm> // std::make_heap, std::push_heap, std::find_if #include <memory> // std::unique_ptr #include <mutex> // std::scoped_lock #include <queue> // std::priority_queue #include <utility> // std::swap, std::forward #include <type_traits> // std::is_constructible_v, // std::is_nothrow_constructible_v namespace gregjm { namespace detail { // compare s.t. we get a maxheap based on the remaining size in a heap struct PoolAllocatorComparator { template <std::size_t N, typename D1, std::size_t M = N, typename D2> bool operator()(const std::unique_ptr<StackAllocator<N>, D1> &lhs, const std::unique_ptr<StackAllocator<M>, D2> &rhs) const { return lhs->max_size() < rhs->max_size(); } }; template <typename Allocator> class PoolAllocatorDeleter { public: PoolAllocatorDeleter() = delete; PoolAllocatorDeleter(Allocator &alloc) : alloc_{ &alloc } { } template <std::size_t N> void operator()(StackAllocator<N> *const pool) { pool->~StackAllocator<N>(); const MemoryBlock block{ pool, sizeof(StackAllocator<N>) }; alloc_->deallocate(block); } private: Allocator *alloc_; }; } // namespace detail template <std::size_t PoolSize, typename Allocator, typename Mutex = DummyMutex> class PoolAllocator final : public PolymorphicAllocator { using LockT = std::scoped_lock<Mutex>; using DoubleLockT = std::scoped_lock<Mutex, Mutex>; using PoolT = StackAllocator<PoolSize>; using OwnerT = std::unique_ptr<PoolT, detail::PoolAllocatorDeleter<Allocator>>; using VectorT = std::vector<OwnerT, PolymorphicAllocatorAdaptor<OwnerT>>; using IterMutT = typename VectorT::iterator; using IterT = typename VectorT::const_iterator; public: PoolAllocator(const PoolAllocator &other) = delete; PoolAllocator(PoolAllocator &&other) : mutex_{ } { const DoubleLockT lock{ mutex_, other.mutex_ }; alloc_ = std::move(other.alloc_); deleter_ = std::move(other.deleter_); pools_ = std::move(other.pools_); } template <typename ...Args, typename = std::enable_if_t<std::is_constructible_v<Allocator, Args...>>> PoolAllocator(Args &&...args) noexcept(std::is_nothrow_constructible_v<Allocator, Args...>) : alloc_{ std::forward<Args>(args)... } { } PoolAllocator& operator=(const PoolAllocator &other) = delete; PoolAllocator& operator=(PoolAllocator &&other) { if (this == &other) { return *this; } const LockT lock{ mutex_, other.mutex_ }; alloc_ = std::move(other.alloc_); deleter_ = std::move(other.deleter_); pools_ = std::move(other.pools_); return *this; } virtual ~PoolAllocator() = default; private: MemoryBlock allocate_impl(const std::size_t size, const std::size_t alignment) override { if (size > PoolSize) { throw BadAllocationException{ }; } const LockT lock{ mutex_ }; if (pools_.empty()) { return allocate_new(size, alignment); } try { const MemoryBlock block = pools_.front()->allocate(size, alignment); fix_down(); return block; } catch (const BadAllocationException&) { return allocate_new(size, alignment); } } MemoryBlock reallocate_impl(const MemoryBlock block, const std::size_t size, const std::size_t alignment) override { const LockT lock{ mutex_ }; const auto owner_iter = get_owner_iter(block); if (owner_iter == pools_.end()) { throw NotOwnedException{ }; } auto &owner = **owner_iter; try { return owner.reallocate(block, size, alignment); } catch (const BadAllocationException&) { const MemoryBlock new_block = allocate(size, alignment); std::memcpy(new_block.memory, block.memory, block.size); owner.deallocate(block); fix_up(owner_iter); return new_block; } } void deallocate_impl(const MemoryBlock block) override { const LockT lock{ mutex_ }; const auto owner_iter = get_owner_iter(block); if (owner_iter == pools_.end()) { throw NotOwnedException{ }; } auto &owner = **owner_iter; owner.deallocate(block); fix_up(owner_iter); } void deallocate_all_impl() override { const LockT lock{ mutex_ }; for (const auto &pool_ptr : pools_) { pool_ptr->deallocate_all(); } } std::size_t max_size_impl() const override { return PoolSize; } bool owns_impl(const MemoryBlock block) const override { const LockT lock{ mutex_ }; for (const auto &pool_ptr : pools_) { if (pool_ptr->owns(block)) { return true; } } return false; } // creates a new pool and allocates out of it // assumes count <= PoolSize // assumes we have a lock MemoryBlock allocate_new(const std::size_t count, const std::size_t alignment) { const MemoryBlock pool_block = alloc_.allocate(sizeof(PoolT), alignof(PoolT)); auto pool = new (pool_block.memory) PoolT{ }; const MemoryBlock allocated_block = pool->allocate(count, alignment); pools_.emplace_back(pool, detail::PoolAllocatorDeleter<Allocator>{ alloc_ }); std::push_heap(pools_.begin(), pools_.end(), detail::PoolAllocatorComparator{ }); return allocated_block; } IterMutT get_owner_iter(const MemoryBlock block) { return std::find_if(pools_.begin(), pools_.end(), [block](const OwnerT &owner) { return owner->owns(block); }); } bool has_left_child(const IterT element) const noexcept { const std::ptrdiff_t signed_size = pools_.size(); return 2 * (element - pools_.begin()) + 1 < signed_size; } bool has_right_child(const IterT element) const noexcept { const std::ptrdiff_t signed_size = pools_.size(); return 2 * (element - pools_.begin()) + 2 < signed_size; } IterMutT left_child(const IterMutT element) noexcept { return element + (element - pools_.begin()) + 1; } IterT left_child(const IterT element) const noexcept { return element + (element - pools_.begin()) + 1; } IterMutT right_child(const IterMutT element) noexcept { return element + (element - pools_.begin()) + 2; } IterT right_child(const IterT element) const noexcept { return element + (element - pools_.begin()) + 2; } IterMutT left_child_or(const IterMutT element) noexcept { if (has_left_child(element)) { return left_child(element); } return pools_.end(); } IterT left_child_or(const IterT element) const noexcept { if (has_left_child(element)) { return left_child(element); } return pools_.cend(); } IterMutT right_child_or(const IterMutT element) noexcept { if (has_right_child(element)) { return right_child(element); } return pools_.end(); } IterT right_child_or(const IterT element) const noexcept { if (has_right_child(element)) { return right_child(element); } return pools_.cend(); } // update priority of front heap element // assumes we have a lock // assumes nonempty void fix_down() noexcept(std::is_nothrow_swappable_v<OwnerT>) { const std::size_t size = pools_.front()->max_size(); for (auto current = pools_.begin(); current < pools_.end(); ) { using std::swap; const auto left = left_child_or(current); const auto right = right_child_or(current); if (right != pools_.end()) { // right and left are valid nodes if ((*left)->max_size() < (*right)->max_size()) { if (size >= (*right)->max_size()) { break; } swap(*right, *current); current = right; } else { if (size >= (*left)->max_size()) { break; } swap(*left, *current); current = left; } } else if (left != pools_.end()) { if (size >= (*left)->max_size()) { break; } swap(*current, *left); current = left; } else { break; } } } bool has_parent(const IterT element) const noexcept { return element - pools_.begin() > 0; } IterMutT parent(const IterMutT element) const noexcept { return element - (element - pools_.begin() + 2) / 2; } IterT parent(const IterT element) const noexcept { return element - (element - pools_.begin() + 2) / 2; } IterMutT parent_or(const IterMutT element) noexcept { if (has_parent(element)) { return parent(element); } return pools_.end(); } IterT parent_or(const IterT element) const noexcept { if (has_parent(element)) { return parent(element); } return pools_.cend(); } // update priority of given heap element // assumes we have a lock // assumes current is dereferencable void fix_up(IterMutT element) noexcept(std::is_nothrow_swappable_v<OwnerT>) { const auto size = (*element)->max_size(); for (; element > pools_.begin(); ) { const auto parent = parent_or(element); if (parent == pools_.end()) { return; } if ((*parent)->max_size() < size) { using std::swap; swap(*element, *parent); element = parent; } else { return; } } } mutable Mutex mutex_; Allocator alloc_; detail::PoolAllocatorDeleter<Allocator> deleter_{ alloc_ }; VectorT pools_{ make_adaptor<OwnerT>(alloc_) }; }; } // namespace gregjm #endif
true
81be886dbe3e737af3ee3835cfd91b6089c4003e
C++
zhaocc1106/my-leetcoding
/c++/translateNum.cpp
UTF-8
2,527
3.921875
4
[]
no_license
/** * 把数字翻译成字符串 * * 给定一个数字,我们按照如下规则把它翻译为字符串:0 翻译成 “a” ,1 翻译成 “b”,……,11 翻译成 “l”,……,25 翻译成 “z”。一个数字可能有多 * 个翻译。请编程实现一个函数,用来计算一个数字有多少种不同的翻译方法。 * * https://leetcode-cn.com/problems/ba-shu-zi-fan-yi-cheng-zi-fu-chuan-lcof/ */ #include <iostream> #include <vector> using namespace std; class Solution { public: int translateNum(int num) { string numStr = to_string(num); int n = numStr.size(); vector<int> dp(n + 1, 0); // 动态规划,每个元素代表前几个元素选择完之后最多的翻译方式 dp[0] = 1; dp[1] = 1; // 第一个元素可选择的翻译方式只有一种 for (int i = 2; i <= n; i++) { if (numStr[i - 2] == '1' || (numStr[i - 2] == '2' && numStr[i - 1] <= '5')) { // 如果前一个元素为1或者前一个元素为2,并且当前元素小于等于5,则有两种翻译方式 dp[i] = dp[i - 1] // 当前元素只选择独立自己翻译 + dp[i - 2]; // 当前元素和前一个元素联合翻译 } else { dp[i] = dp[i - 1]; // 当前元素只能选择自己独立翻译 } } /*for (auto i : dp) { cout << i << ", "; } */ return dp[n]; } int translateNum2(int num) { string numStr = to_string(num); int n = numStr.size(); int pre2 = 1; // 当前元素往前移动两个位置为截止元素的最多翻译方式 int pre1 = 1; // 当前元素往前移动一个位置为截止元素的最多翻译方式 int dp = 0; // 当前元素为截止,最多翻译方式 for (int i = 2; i <= n; i++) { if (numStr[i - 2] == '1' || (numStr[i - 2] == '2' && numStr[i - 1] <= '5')) { // 如果前一个元素为1或者前一个元素为2,并且当前元素小于等于5,则有两种翻译方式 dp = pre1 // 当前元素只选择独立自己翻译 + pre2; // 当前元素和前一个元素联合翻译 } else { dp = pre1; // 当前元素只能选择自己独立翻译 } pre2 = pre1; pre1 = dp; } return dp; } }; int main() { cout << Solution().translateNum2(1111); }
true
a82041771217b24f60a9ca26a6fb792d1dcc8435
C++
mugisaku/gamebaby-20180928-dumped
/libgbsnd/object.hpp
UTF-8
4,392
2.765625
3
[]
no_license
#ifndef LIBGBSND_OBJECT_HPP #define LIBGBSND_OBJECT_HPP #include<cstdint> #include<cstdio> #include<memory> #include"libgbstd/string.hpp" #include"libgbsnd/shared_string.hpp" #include"libgbsnd/device.hpp" #include"libgbsnd/list.hpp" namespace gbsnd{ class execution_context; namespace stmts{ class stmt; class stmt_list; class routine; } namespace objects{ class object; class routine; class value; class property { void* m_pointer=nullptr; int (*m_callback)(void* ptr, const int* v); public: constexpr property(void* pointer, int (*callback)(void*,const int*)) noexcept: m_pointer(pointer), m_callback(callback){} template<typename T> constexpr property(T& t, int (*callback)(T*,const int*)) noexcept: m_pointer(&t), m_callback(reinterpret_cast<int (*)(void*,const int*)>(callback)){} int get( ) const noexcept; void set(int v) const noexcept; }; class reference { object* m_pointer=nullptr; public: reference(object& o) noexcept: m_pointer(&o){} object& operator()() const noexcept{return *m_pointer;} property get_property(const identifier& id) const noexcept; }; struct system{}; class value { enum class kind{ null, integer, reference, routine, property, square_wave, noise, system, } m_kind=kind::null; union data{ int i; reference r; const stmts::routine* rt; property pr; square_wave* sq; noise* no; data(){} ~data(){} } m_data; public: value() noexcept{} value(bool b) noexcept{*this = b;} value(int i) noexcept{*this = i;} value(reference r) noexcept{*this = r;} value(const stmts::routine& rt) noexcept{*this = rt;} value(const property& pr) noexcept{*this = pr;} value(square_wave& sq) noexcept{*this = sq;} value(noise& no) noexcept{*this = no;} value(system sys) noexcept{*this = sys;} value(const value& rhs) noexcept{*this = rhs;} value( value&& rhs) noexcept{*this = std::move(rhs);} ~value(){clear();} value& operator=(bool b) noexcept; value& operator=(int i) noexcept; value& operator=(reference r) noexcept; value& operator=(const stmts::routine& rt) noexcept; value& operator=(const property& pr) noexcept; value& operator=(square_wave& sq) noexcept; value& operator=(noise& no) noexcept; value& operator=(system sys) noexcept; value& operator=(const value& rhs) noexcept; value& operator=( value&& rhs) noexcept; operator bool() const noexcept{return m_kind != kind::null;} void clear() noexcept; bool is_reference() const noexcept{return m_kind == kind::reference;} bool is_integer() const noexcept{return m_kind == kind::integer;} bool is_routine() const noexcept{return m_kind == kind::routine;} bool is_property() const noexcept{return m_kind == kind::property;} bool is_square_wave() const noexcept{return m_kind == kind::square_wave;} bool is_noise() const noexcept{return m_kind == kind::noise;} bool is_system() const noexcept{return m_kind == kind::system;} int get_integer() const noexcept{return m_data.i;} reference get_reference() const noexcept{return m_data.r;} const stmts::routine& get_routine() const noexcept; const property& get_property() const noexcept{return m_data.pr;} square_wave& get_square_wave() const noexcept{return *m_data.sq;} noise& get_noise() const noexcept{return *m_data.no;} int get_integer_safely() const noexcept; void print() const noexcept; }; class value_list: public list<value> { public: using list::list; }; class object: public value { gbstd::string m_name; public: object(value&& v, gbstd::string_view name) noexcept: value(std::move(v)), m_name(name){} object( gbstd::string_view name) noexcept: m_name(name){} void set_name(gbstd::string_view name) noexcept{m_name = name;} const gbstd::string& get_name( ) const noexcept{return m_name;} void print() const noexcept { printf("%s = ",m_name.data()); value::print(); } }; } using objects::reference; using objects::value; using objects::value_list; using objects::object; using objects::property; } #endif
true
f0f3e6547bab0eb324409a05e1a896aedceb1b38
C++
helderdantas/dca1202-sculptor3D_parte-2
/sculptor3D_parte2/cutbox.cpp
UTF-8
563
2.796875
3
[]
no_license
#include "cutbox.h" cutBox::cutBox(int x0, int x1, int y0, int y1, int z0, int z1) { x0_=x0;y0_=y0;z0_=z0; x1_=x1-1 ;y1_=y1-1;z1_=z1-1; } /* //Liberar a memória. cutBox::~cutBox(){ } */ // Desativa todos os voxels no intervalo x∈[x0,x1], y∈[y0,y1], z∈[z0,z1] e atribui aos mesmos a cor atual de desenho void cutBox::draw(Sculptor &t){ int i,j,k; for (k=z0; k<=z1_; k++){ for (i=x0_; i<=x1_; i++) { for (j=y0_; j<=y1_; j++) { t.cutVoxel(i,j,k); } } } }
true
c58d9ec78f5cc6f03eafdd0005716ebc797c8869
C++
YuLian-yl/LeetCode
/027. Remove Element.cpp
UTF-8
1,826
4.1875
4
[]
no_license
// // Created by yulian on 2019-01-23. // /*题目: * 给定一个数组 nums 和一个值 val,你需要原地移除所有数值等于 val 的元素,返回移除后数组的新长度。 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。 元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。 示例 1: 给定 nums = [3,2,2,3], val = 3, 函数应该返回新的长度 2, 并且 nums 中的前两个元素均为 2。 你不需要考虑数组中超出新长度后面的元素。 示例 2: 给定 nums = [0,1,2,2,3,0,4,2], val = 2, 函数应该返回新的长度 5, 并且 nums 中的前五个元素为 0, 1, 3, 0, 4。 注意这五个元素可为任意顺序。 你不需要考虑数组中超出新长度后面的元素。 * */ /*思路: *循环遍历数组,用一个变量标记数组中值为val的标志,把删除的数字往后面的交换,相当于把移除元素往后移。 * */ #include "head.h" class Solution { public: int removeElement(vector<int>& nums, int val) { //数组长度 int len = nums.size(); //标记找到val的下标 int index=0; //遍历数组,若该值不为val,则将该值赋值给index位置的数,并且index加1 for(int i=0;i<len;i++) { if(nums[i]!=val) { nums[index]=nums[i]; index++; } } for(int i=0;i<index;i++) cout<<nums[i]<<" "; cout<<endl; return index; } }; int main() { Solution s; int arr[]={3,2,2,3}; vector<int>number(begin(arr),end(arr)); int new_len=s.removeElement(number,3); cout<<"删除后数组长度为"<<new_len<<endl; return 0; }
true
2ccb5138d04a5b434489fb071356fd40e7b72516
C++
tectronics/infinite-bounty
/InfiniteBounty_Game/InfiniteBounty_Project/Source/Message.h
UTF-8
6,092
2.640625
3
[]
no_license
#ifndef MESSAGE_H_ #define MESSAGE_H_ #include "CMovingObject.h" enum messageType {MSG_NULL = 0, MSG_CREATE_ARROW, MSG_CREATE_BOMB, MSG_CREATE_FOOD, MSG_CREATE_SPIRIT_ARCHER,MSG_CREATE_SPIRIT_CHARGER, MSG_CREATE_BEE, MSG_CREATE_RAGGAMOFFYN, MSG_CREATE_FIREBALL, MSG_CREATE_FIREBREATH, MSG_CREATE_MINIFIREBALLS,MSG_CREATE_LIGHTNING, MSG_CREATE_ICECRYSTALS, MSG_CREATE_VOMIT, MSG_CREATE_MIMIC,MSG_CREATE_TRAP, MSG_DEAD_ENEMY,MSG_DESTROY_OBJECT, MSG_CREATE_PICKUP, MSG_DESTROY_FIREBREATH, MSG_DESTROY_FIREBALL,MSG_DESTROY_MINIFIREBALLS, MSG_DESTROY_LIGHTING,MSG_DESTROY_ICE_CRYSTALS,MSG_DESTROY_VOMIT, MSG_DESTROY_TRAP,}; class CMessage { public: CMessage(messageType ID); virtual ~CMessage(void); messageType GetMessageID(void) const {return msgID;} private: messageType msgID; }; class CCreateTrap: public CMessage { public: CCreateTrap(int x, int y, int e): CMessage(MSG_CREATE_TRAP) { X = x; Y = y; Effect = e; }; int GetX(){return X;} int GetY() {return Y;} int GetEffect(){return Effect;} private: int X,Y, Effect; }; class CDestroyObject : public CMessage { CBaseObject* to_destroy; public: CDestroyObject(CBaseObject* to_destroy) : CMessage(MSG_DESTROY_OBJECT) { this->to_destroy = to_destroy; } CBaseObject* GetToDestroy( void ) {return this->to_destroy;} }; class CDeadEnemy : public CMessage { public: CDeadEnemy(IBaseObject* object):CMessage(MSG_DEAD_ENEMY) { Enemy = object; } IBaseObject* GetObject( void ) { return Enemy; }; private: IBaseObject* Enemy; }; class CCreatePickUp : public CMessage { int x, y; public: CCreatePickUp(int x, int y) : CMessage(MSG_CREATE_PICKUP) { this->x = x; this->y = y; } int GetX( void ) {return this->x;} int GetY( void ) {return this->y;} }; class CCreateMimic :public CMessage { public: CCreateMimic() :CMessage(MSG_CREATE_MIMIC) { } }; class CCreateVomit : public CMessage { public: CCreateVomit(int x, int y) : CMessage(MSG_CREATE_VOMIT) { X = x; Y = y; } int GetX() {return X;} int GetY() {return Y;} private: int X,Y; }; class CDestroyVomit:public CMessage { public: CDestroyVomit(IBaseObject* obj) :CMessage(MSG_DESTROY_VOMIT) { OBJECT = obj; } IBaseObject* GetOwner() {return OBJECT;} private: IBaseObject* OBJECT; }; class CDestroyIce : public CMessage { public: CDestroyIce(IBaseObject* obj) : CMessage(MSG_DESTROY_ICE_CRYSTALS) { OBJECT = obj; } IBaseObject* GetObject() {return OBJECT;} private: IBaseObject* OBJECT; }; class CDestroyLightning :public CMessage { public: CDestroyLightning(IBaseObject* obj) : CMessage(MSG_DESTROY_LIGHTING) { OBJECT = obj; } IBaseObject* GetObject() {return OBJECT;} private: IBaseObject* OBJECT; }; class CCreateIce : public CMessage { public: CCreateIce(int x, int y, float movespeed, int direction, int angle) : CMessage(MSG_CREATE_ICECRYSTALS) { X = x; Y = y; MoveSpeed = movespeed; Direction = direction; Angle = angle; } int GetX() {return X;} int GetY() {return Y;} int GetDirection() {return Direction;} int GetAngle() {return Angle; } float GetMoveSpeed() {return MoveSpeed;} private: int X, Y, Direction, Angle; float MoveSpeed; }; class CCreateLightning :public CMessage { public: CCreateLightning(int x, int y, int direction, int hor_vert) : CMessage(MSG_CREATE_LIGHTNING) { X = x; Y = y; Hor_Vert = hor_vert; Direction = direction; }; int GetX() {return X;} int GetY() {return Y;} int GetHV(){return Hor_Vert;} int GetDirection() {return Direction;} private: int X, Y, Hor_Vert, Direction; }; class CCreateFireBreath : public CMessage { public: CCreateFireBreath(CMovingObject* owner) : CMessage(MSG_CREATE_FIREBREATH) { OWNER = owner; } CMovingObject* GetOwner() {return OWNER;} private: CMovingObject* OWNER; }; class CDestroyFireBreath : public CMessage { public: CDestroyFireBreath(CMovingObject* owner) :CMessage(MSG_DESTROY_FIREBREATH) { OWNER = owner; } CMovingObject* GetOwner() {return OWNER;} private : CMovingObject *OWNER; }; class CCreateFireBall : public CMessage { public: CCreateFireBall(float x,float y, float movespeed, int facing) : CMessage(MSG_CREATE_FIREBALL) { X= x; Y= y, MoveSpeed = movespeed; Facing = facing; } float GetX() {return X;} float GetY() {return Y;} float GetMoveSpeed() {return MoveSpeed;} int GetFacing() {return Facing;} private: float X,Y,MoveSpeed; int Facing; }; class CDestroyFireBall :public CMessage { public: CDestroyFireBall(IBaseObject* obj) : CMessage(MSG_DESTROY_FIREBALL) { OBJECT = obj; } IBaseObject* GetOwner() {return OBJECT;} private: IBaseObject* OBJECT; }; class CCreateFireMiniBall : public CMessage { public: CCreateFireMiniBall(float x, float y, float movespeed, int facing, int angle) : CMessage(MSG_CREATE_MINIFIREBALLS) { X = x; Y = y; MoveSpeed = movespeed; Facing = facing, Angle = angle; } float GetX() {return X;} float GetY() {return Y;} float GetMoveSpeed() {return MoveSpeed;} int GetFacing() {return Facing;} int GetAngle() {return Angle;} private: float X,Y, MoveSpeed; int Facing, Angle; }; class CDestroyFireMiniBall : public CMessage { public: CDestroyFireMiniBall(IBaseObject* obj) : CMessage(MSG_DESTROY_MINIFIREBALLS) { OBJECT = obj; } IBaseObject* GetOwner() {return OBJECT;} private: IBaseObject* OBJECT; };class CCreateArcher : public CMessage { public: CCreateArcher() : CMessage(MSG_CREATE_SPIRIT_ARCHER) { } }; class CCreateCharger : public CMessage { public: CCreateCharger():CMessage(MSG_CREATE_SPIRIT_CHARGER) { } }; class CCreateBee : public CMessage { public: CCreateBee():CMessage(MSG_CREATE_BEE) { } }; class CCreateRaggamoffyn : public CMessage { public: CCreateRaggamoffyn():CMessage(MSG_CREATE_RAGGAMOFFYN) { } }; #endif MESSAGE_H_
true
b89187d8276b1dcc2c1d139befa9c5af2392144c
C++
scottScottScott/WeAreTalkingAboutPractice
/old/QualifyingContest.cpp
UTF-8
644
2.96875
3
[]
no_license
#include <iostream> #include <vector> #include <utility> #include <string> #include <algorithm> using namespace std; typedef pair<int, string> pis; int main() { int N, M; cin >> N >> M; vector<vector<pis>> storage(M + 1); for(int n = 0; n < N; n++) { string name; int region, points; cin >> name >> region >> points; storage[region].emplace_back(points, name); } for(int i = 1; i <= M; i++) { sort(storage[i].rbegin(), storage[i].rend()); if(storage[i].size() > 2 and storage[i][1].first == storage[i][2].first) cout << "?" << endl; else cout << storage[i][0].second << " " << storage[i][1].second << endl; } }
true
f49a6f10d4e5e646b8b6d758f465ee90c16b0d62
C++
Arik096/Fahima-mam_oop_L2T1-codes
/1 extra(MAIN).cpp
UTF-8
438
3.484375
3
[]
no_license
#include<iostream> #include<math.h> using namespace std; class polar { public: float r,th,x,y; polar(float a,float b) { r=a; th=b; } void call() { x=r*cos(th); y=r*sin(th); } void show() { cout<<"x="<<x<<" and y="<<y; } }; int main() { float r,th; cout<<"Enter the inputs of r & theta"<<endl; cin>>r>>th; polar p(r,3.14/180); p.call(); p.show(); }
true
d727bade4badfad7b8e7ce1f9f8cd8dad128038a
C++
rusty34/uni_examples
/TextureLoader.cpp
UTF-8
5,683
2.5625
3
[]
no_license
/* Spatial AR Framework - CBL Copyright (c) 2012 Shane Porter If you use/extend/modify this code, add your name and email address to the AUTHORS file in the root directory. This code can be used by members of the Wearable Computer Lab, University of South Australia for research purposes. Commercial use is not allowed without written permission. This copyright notice is subject to change. */ #include <dirent.h> #include <iostream> #include <sstream> #include <iterator> #include <algorithm> #include <boost/foreach.hpp> #include <image/AbstractImage.h> #include <image/BufferedImage.h> #include "TextureLoader.h" #include "MessageType.h" #define MESSAGE_IMAGE_SEND "LibSAR Image Send Message" #ifndef foreach #define foreach BOOST_FOREACH #endif TextureLoader::TextureLoader() { } TextureLoader::~TextureLoader() { foreach(graphics::Texture* t, textureList) { delete t; } } bool TextureLoader::handleMessage(const Message* msg) { if(msg->type == Message::hashType(MESSAGE_IMAGE_SEND)) { const MessageType::ImageMessage* im = reinterpret_cast<const MessageType::ImageMessage*>(msg); unsigned int height = im->height; unsigned int width = im->width; image::AbstractImage::ImageFormat format = im->format; //std::cout << "Height " << height << ", Width " << width << std::endl; std::cout << "Making BufferedImage\n"; //std::cout << (int)im->data[40] << " " << (int)im->data[41] << " " << (int)im->data[42] << " " << (int)im->data[43] << std::endl; /*int numBytes = height * width * im->bpp; for(int i = 0; i<numBytes; i+=4) { std::cout << (int)im->data[i] << " " << (int)im->data[i+1] << " " << (int)im->data[i+2] << " " << (int)im->data[i+3] << std::endl; }*/ image::BufferedImage* image = new image::BufferedImage(width, height, format, im->data); graphics::Texture* texture = new graphics::Texture(image); textureList.push_back(texture); return true; } return false; } graphics::Texture* TextureLoader::getTextureAt(unsigned int i) { if(i >= textureList.size()) throw SARException("Array index out of bounds - TextureLoader"); return textureList[i]; } graphics::Texture* TextureLoader::getNewTexture() { return textureList.back(); } int TextureLoader::getFullDir(std::string dir, std::vector<std::string> &files) { std::vector<std::string> contents; getDirContents(dir, contents); for(unsigned int i = 0; i < contents.size(); i++) { std::string new_name = contents.at(i); std::cout << new_name << std::endl; } return 0; } int TextureLoader::getDirContents(std::string dir, std::vector<std::string> &files) { DIR *directory; struct dirent *dirp; if((directory = opendir(dir.c_str())) == NULL) { std::cout << "Error opening " << dir << std::endl; return 1; } while((dirp = readdir(directory)) != NULL) { if(dirp->d_name[0]!='.') { std::stringstream fullFilename; fullFilename << dir; fullFilename << dirp->d_name; if(dirp->d_type == DT_DIR) { fullFilename << "/"; std::cout << "directory: " << fullFilename.str() << std::endl; getDirContents(fullFilename.str(), files); } else if(dirp->d_type == DT_REG) { std::cout << "file: " << fullFilename.str() << std::endl; files.push_back(fullFilename.str()); } } } closedir(directory); return 0; } /*void TextureLoader::listPath(const char* dir) { listPath(path(dir)); }*/ /*void TextureLoader::listPath(path p) { try { if(exists(p)) { if(is_regular_file(p)) { //Add to list } else if (is_directory(p)) { cout << p << " contains:\n"; //Show folder typedef vector<path> vec; vec v; copy(directory_iterator(p), directory_iterator(), back_inserter(v)); sort(v.begin(), v.end()); for(vec::const_iterator it(v.begin()), it_end(v.end()); it != it_end; ++it) { cout << " " << *it << '\n'; } } else { cout << p << " exists, but is not a file or a directory.\n"; } } else { cout << p << " does not exist.\n"; } } catch (const filesystem_error& e) { cout << e.what() << '\n'; } }*/
true
3f91a5827fb498b76c2c5f948ea38f2088e59de6
C++
macyt357/MacyThomas-CSCI20-Fall2017
/lab22/lab22.cpp
UTF-8
462
3.265625
3
[]
no_license
//Macy Thomas //Lab 2.2 //Random Number Generator #include <iostream> #include <time.h> //allows for us to use srand using namespace std; void Random(){ cout << "Your Random Number is: "<< endl; //outputs the phrase "Your Random Number is:" srand (time(NULL)); //produces random number int number = rand() % 100 + 1; //sets boundary between 0-100 cout << number; //outputs our random number } int main(){ Random(); //runs our function }
true
f488478965ad397f061a818bad037f6043dc1d87
C++
isac322/BOJ
/10825/10825.cpp
UTF-8
663
3.078125
3
[ "MIT" ]
permissive
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; struct student { char name[11]; char a, b, c; bool operator<(const student &right) const { if (a == right.a) { if (b == right.b) { if (c == right.c) { return strcmp(name, right.name) < 0; } else return c > right.c; } else return b < right.b; } else return a > right.a; } }; int main() { int n; student students[100000]; scanf("%d", &n); for (int i = 0; i < n; ++i) scanf("%s %hhd %hhd %hhd", students[i].name, &students[i].a, &students[i].b, &students[i].c); sort(students, students + n); for (int i = 0; i < n; ++i) puts(students[i].name); }
true