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
51d74aafc5aa2669ce866a2a7c4d52baf2e5a192
C++
youngminpark2559/plang
/cpp/yk/018_array/005_concatenate_string/main.cpp
UTF-8
1,003
2.859375
3
[]
no_license
// cd /mnt/1T-5e7/mycodehtml/p_lang/cpp/yk/018_array/005_concatenate_string && \ // g++ \ // -std=c++11 \ // -o main \ // /mnt/1T-5e7/mycodehtml/p_lang/cpp/yk/018_array/005_concatenate_string/main.cpp && \ // rm e.l && ./main 2>&1 | tee -a e.l && code e.l #include <iostream> #include <cstring> using namespace std; int main() { // ====================================================================== char src_string[100]="C++ programming is very interesting!!!"; char dest_string[100]; char dest2_string[100]; char string[30]="science"; // ====================================================================== strcpy(dest_string,src_string); std::cout<<"dest_string: "<<dest_string<<std::endl; // dest_string: C++ programming is very interesting!!! // ====================================================================== strcat(dest_string,string); std::cout<<"dest_string: "<<dest_string<<std::endl; // dest_string: C++ programming is very interesting!!!science }
true
8a6596191cd8b3e0338bd14fe4e7dbf4e5e6a025
C++
Abinasbehera16/C-
/Practice/SWAP.CPP
UTF-8
313
2.921875
3
[]
no_license
#include<iostream.h> #include<conio.h> int main() {clrscr(); int a,b; void swap(int, int); cout<<"The no. is"<<"\n"; cin>>a>>b; swap(a,b); cout<<"a=="<<a<<" "<<"b=="<<b; cout<<"a=="<<a<<" "<<"b=="<<b; getch(); return 0; } void swap(int x,int y) { int temp; temp=x; x=y; y=temp; cout<<"x=="<<x<<"y=="<<y<<"\n"; }
true
6d88c6b7362ff7d54f777e833647c50aa2c4b64a
C++
rmarko/CORElearn
/src/random.h
UTF-8
1,596
2.9375
3
[]
no_license
/* * random.h * * Created on: 12.3.2010 * Author: rmarko */ #if !defined(RANDOM_H_) #define RANDOM_H_ #include <cstdlib> #include <ctime> #include "contain.h" class PseudoRandom { private: // internal state of generator mrg32k5a from L'Ecuyer99 double s10, s11, s12, s13, s14, s20, s21, s22, s23, s24; void mrg32k5aSetSeed(int n, int *seed); void mrg32k5aAddSeed(int n, int *seed); double MRG32k5a(); public: // constructors PseudoRandom() { initSeed((int) -time(NULL)); } PseudoRandom(int seed) { initSeed(seed); } PseudoRandom(int n, int *seed) { initSeed(n, seed); } // interface inline void initSeed(int seed) { mrg32k5aSetSeed(1, &seed); } inline void initSeed(int n, int *seed) { mrg32k5aSetSeed(n, seed); } inline void addSeed(int n, int *seed) { mrg32k5aAddSeed(n, seed); } inline double getDouble() { return MRG32k5a(); } int getBetween(int from, int to); double getBetween(double from, double to); }; class PseudoRandomStreams { private: marray<PseudoRandom> rng ; public: PseudoRandomStreams() { } ~PseudoRandomStreams() { destroy() ; } void initSeed(int m, int n, int *seed) { int idx ; rng.create(m) ; for (idx=0; idx<m; idx++) { rng[idx].initSeed(1, &idx) ; rng[idx].addSeed(n, seed) ; } } double getDouble(int idx) { return rng[idx].getDouble() ; } int getBetween(int idx, int from, int to) { return rng[idx].getBetween(from, to) ; } double getBetween(int idx, double from, double to) { return rng[idx].getBetween(from, to) ; } void destroy() { rng.destroy() ; } }; #endif /* RANDOM_H_ */
true
bc2dc94e8d0040f391e6b4815802a30b13982c79
C++
W1lliam/CloudEngine
/CloudEngine/CloudMath/src/Tools/Random.cpp
UTF-8
879
2.9375
3
[]
no_license
/** * Project AltMath * @author GP2021 * @version 1.0.0 */ #include "CloudMath/stdafx.h" #include "CloudMath/Tools/Random.h" std::default_random_engine CloudMath::MathTools::Random::s_generator = std::default_random_engine(static_cast<unsigned int>(time(0))); int CloudMath::MathTools::Random::GenerateInt(int p_min, int p_max) { if (p_min > p_max) throw std::logic_error("Min is superior than max"); return std::uniform_int_distribution<int>(p_min, p_max)(s_generator); } float CloudMath::MathTools::Random::GenerateFloat(float p_min, float p_max) { if (p_min > p_max) throw std::logic_error("Min is superior than max"); return std::uniform_real_distribution<float>(p_min, p_max)(s_generator); } bool CloudMath::MathTools::Random::CheckPercentage(float p_percentage) { return std::uniform_real_distribution<float>(0.f, 100.f)(s_generator) <= p_percentage; }
true
9043a470111458e760a605268d93990cc5333181
C++
MarkOates/tins2021
/tests/GameplayScreenTest.cpp
UTF-8
361
2.734375
3
[]
no_license
#include <gtest/gtest.h> #include <GameplayScreen.hpp> TEST(GameplayScreenTest, can_be_created_without_blowing_up) { GameplayScreen gameplay_screen; } TEST(GameplayScreenTest, run__returns_the_expected_response) { GameplayScreen gameplay_screen; std::string expected_string = "Hello World!"; EXPECT_EQ(expected_string, gameplay_screen.run()); }
true
9325bc2e8f32287e997f3c604698f8dfbf404e59
C++
vserousov/Algorithms-Course
/Sorting algorithms time comparison/program/BubbleSort.cpp
UTF-8
395
3.265625
3
[]
no_license
#include "BubbleSort.h" void BubbleSort::sort(int a[], int n) { for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { if (a[j] > a[j + 1]) { int temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; } } } } string BubbleSort::name() { return "Bubble sort"; }
true
c84619ba67aaa68cb269357f90401ff548bf6670
C++
RitikJainRJ/DailyCodingProblem-Practice
/reverse bit.cpp
UTF-8
227
2.84375
3
[]
no_license
uint32_t reverseBits(uint32_t n) { uint32_t res = 0; int k = 32; while(k--){ int x = n & 1; n = n >> 1; res = res | x; if(k != 0) res = res << 1; } return res; }
true
a0b35d36f98bc9dfcf2b33a6960c12473a85ad01
C++
utkarsh235/CPP-Programming
/if else.cpp
UTF-8
1,055
3.671875
4
[]
no_license
#include<iostream> using namespace std ; int main() { int a,c,b,d ; cout << "enter a no.\n 1 for addition \n 2 for sustraction \n 3 for multiplication \n 4 for obtaining remainder\n"; cin >> c; switch(c) { case 1: cout<< "enter first no\n"; cin>> a; cout<< "enter second no\n"; cin>> b; d = a+b ; cout<< d; break; case 2: cout<< "enter first no\n"; cin>> a; cout<< "enter second no\n"; cin>> b; d = a-b ; cout<< d; break; case 3: cout<< "enter first no\n"; cin>> a; cout<< "enter second no\n"; cin>> b; d = a*b ; cout<< d; break; case 4: cout<< "enter first no\n"; cin>> a; cout<< "enter second no\n"; cin>> b; d = a%b ; cout<< d; break; } return 0 ; }
true
a9546b269097406e1bc7a290ddc6f3d89f184eb1
C++
wisest30/AlgoStudy
/source/leetcode/1691/신입.cpp
UTF-8
1,622
2.671875
3
[]
no_license
class Solution { public: int maxHeight(vector<vector<int>>& cuboids) { vector<vector<int>> newCuboids; newCuboids.push_back({0, 0, 0}); for(auto &cuboid : cuboids) { set<vector<int>> uniqueCuboid; uniqueCuboid.insert({cuboid[0], cuboid[1], cuboid[2]}); uniqueCuboid.insert({cuboid[0], cuboid[2], cuboid[1]}); uniqueCuboid.insert({cuboid[1], cuboid[0], cuboid[2]}); uniqueCuboid.insert({cuboid[1], cuboid[2], cuboid[0]}); uniqueCuboid.insert({cuboid[2], cuboid[0], cuboid[1]}); uniqueCuboid.insert({cuboid[2], cuboid[1], cuboid[0]}); for(auto it = uniqueCuboid.begin(); it != uniqueCuboid.end() ; it++) newCuboids.push_back(*it); } sort(newCuboids.begin(), newCuboids.end(), [&](vector<int> &a, vector<int> &b) { if(a[0] != b[0]) return a[0] < b[0]; if(a[1] != b[1]) return a[1] < b[1]; return a[2] < b[2]; }); vector<int> ans(newCuboids.size()); ans[0] = 0; int ret = 0; for(int i=1;i<newCuboids.size();i++) { for(int j=i-1;j>=0;--j) { if(newCuboids[j][1] <= newCuboids[i][1] && newCuboids[j][2] <= newCuboids[i][2]) { ans[i] = max(ans[i], ans[j] + newCuboids[i][2]); } } ret = max(ret, ans[i]); } return ret; } };
true
03f02a4541f3c236d1d0bbfa6d337a84e6820163
C++
komiga/Cacophony
/Cacophony/String.hpp
UTF-8
610
2.65625
3
[ "MIT" ]
permissive
/** @copyright MIT license; see @ref index or the accompanying LICENSE file. @file @brief String type. */ #pragma once #include <Cacophony/config.hpp> #include <Cacophony/aux.hpp> #include <duct/char.hpp> namespace Cacophony { /** @addtogroup etc @{ */ /** @addtogroup string @{ */ /** Turn input into a UTF-8 encoded string literal. @param x_ C-string literal. */ #define CACOPHONY_STR_LIT(x_) u8 ## x_ /** String type. @note Contents must be UTF-8. */ using String = aux::basic_string<char>; /** @} */ // end of doc-group string /** @} */ // end of doc-group etc } // namespace Cacophony
true
8214b919043a5e10feb1a33b185d14e199689ee3
C++
Swess/RiskGame
/src/Map/MapDriver.cpp
UTF-8
5,955
3.171875
3
[]
no_license
#include <iostream> #include <cassert> #include "Map.h" using namespace std; namespace Board { namespace Driver { bool test_simple_graph() { Map map; // Insert 6 stub nodes for (int i = 0; i < 6; i++) map.insert_country(*new Country("Stub name")); vector<Country *> countries = map.get_countries(); // Link them a specific manner map.biconnect(*countries[0], *countries[1]); map.biconnect(*countries[0], *countries[2]); map.biconnect(*countries[1], *countries[2]); map.biconnect(*countries[2], *countries[3]); map.biconnect(*countries[3], *countries[4]); map.biconnect(*countries[4], *countries[5]); map.biconnect(*countries[3], *countries[5]); // Validate state vector<Country *> test = map.get_countries(); assert(map.get_countries().size() == 6); assert(map.are_adjacent(*countries[0], *countries[1])); assert(map.are_adjacent(*countries[0], *countries[2])); assert(map.are_adjacent(*countries[1], *countries[2])); assert(map.are_adjacent(*countries[2], *countries[3])); assert(map.are_adjacent(*countries[3], *countries[4])); assert(map.are_adjacent(*countries[4], *countries[5])); assert(map.are_adjacent(*countries[3], *countries[5])); // Test some cases that should not be true assert(!map.are_adjacent(*countries[0], *countries[5])); assert(!map.are_adjacent(*countries[0], *countries[3])); assert(!map.are_adjacent(*countries[1], *countries[4])); assert(!map.are_adjacent(*countries[5], *countries[2])); assert(map.is_connected()); //// // None connected graph Map map2; // Insert 6 stub nodes for (int i = 0; i < 6; i++) map2.insert_country(*new Country("Stub")); countries = map2.get_countries(); map2.biconnect(*countries[0], *countries[1]); map2.biconnect(*countries[0], *countries[2]); assert(!map2.is_connected()); return true; } bool test_continent_graph() { Map map; Continent continent("Continent test", &map); Country *c1 = new Country("1"); Country *c2 = new Country("2"); Country *c3 = new Country("3"); Country *c4 = new Country("4"); Country *c5 = new Country("5"); // Adding to continent adds to the map also, but already connected continent.insert_country(*c1); continent.insert_country(*c2); continent.insert_country(*c3); continent.insert_country(*c4); map.biconnect(*c1, *c2); map.biconnect(*c1, *c3); map.biconnect(*c1, *c4); map.biconnect(*c3, *c4); // Add one extra random country map.insert_country(*c5); assert(continent.is_connected()); assert(!map.is_connected()); assert(map.are_adjacent(*c1, *c2)); assert(map.are_adjacent(*c1, *c4)); assert(map.are_adjacent(*c3, *c4)); assert(!map.are_adjacent(*c2, *c4)); return true; } bool test_continent_country_exclusivity() { Map map; Country *c1 = new Country("1"); Country *c2 = new Country("2"); Country *c3 = new Country("3"); Country *c4 = new Country("4"); Continent continent1("Empire1", &map); continent1.insert_country(*c1); continent1.insert_country(*c2); continent1.insert_country(*c3); continent1.insert_country(*c4); map.biconnect(*c1, *c3); map.biconnect(*c2, *c3); Continent continent2("Empire2", &map); // This should assign the countries to continent2, and remove them from continent1 continent2.insert_country(*c3); continent2.insert_country(*c4); assert(continent1.get_size() == 2); assert(continent2.get_size() == 2); return true; } bool test_composed_map() { Map map; Continent continent1("America", &map); Continent continent2("Asia", &map); // Insert 5 stub country for (int i = 0; i < 5; i++) continent1.insert_country(*new Country("Stub Name")); for (int i = 0; i < 5; i++) continent2.insert_country(*new Country("Stub Name")); vector<Country *> countries = map.get_countries(); // Insert some stub edges in continents // Continent1 links map.biconnect(*countries[0], *countries[1]); map.biconnect(*countries[1], *countries[2]); map.biconnect(*countries[2], *countries[3]); map.biconnect(*countries[3], *countries[4]); map.biconnect(*countries[0], *countries[3]); map.biconnect(*countries[2], *countries[4]); // Continent2 links int c1_size = continent1.get_size(); map.biconnect(*countries[c1_size+0], *countries[c1_size+1]); map.biconnect(*countries[c1_size+1], *countries[c1_size+2]); map.biconnect(*countries[c1_size+2], *countries[c1_size+3]); map.biconnect(*countries[c1_size+3], *countries[c1_size+4]); map.biconnect(*countries[c1_size+0], *countries[c1_size+3]); map.biconnect(*countries[c1_size+2], *countries[c1_size+4]); // Make stub continent links map.biconnect(*countries[2], *countries[c1_size+0]); map.biconnect(*countries[4], *countries[c1_size+4]); assert(continent1.get_size() == 5); assert(continent2.get_size() == 5); assert(map.get_continents().size() == 2); // Still connected assert(continent1.is_connected()); assert(continent2.is_connected()); assert(map.is_connected()); return true; } bool run() { test_simple_graph(); test_continent_graph(); test_continent_country_exclusivity(); test_composed_map(); return true; }; } }
true
f3370e87bf5b081e35bfa7f5d856b90209d8f720
C++
YueNing/LC-learning
/C++/96.不同的二叉搜索树.cpp
UTF-8
501
2.75
3
[]
no_license
/* * @lc app=leetcode.cn id=96 lang=cpp * * [96] 不同的二叉搜索树 */ // @lc code=start class Solution { public: int numTrees(int n) { vector<int> generateTrees(n + 1, 0); generateTrees[0] = 1; generateTrees[1] = 1; for (int i = 2; i <= n; i++) { for (int j = 1; j <= i; j++){ generateTrees[i] += generateTrees[j - 1] * generateTrees[i - j]; } } return generateTrees[n]; } }; // @lc code=end
true
693220329874c987644f5c0848d609b82eb4e90d
C++
Vuean/ThinkingInCPlusPlus
/4. Data Abstraction/Exercise/ex13.cpp
UTF-8
531
3.046875
3
[]
no_license
#include "ex13.h" #include <iostream> using namespace std; void Vedio::print() { cout << "Film name: " << name << endl; cout << "Film duration: " << duration << endl; cout << "Film cost: " << cost << endl; cout << "Film actors: "; for(int i = 0; i < actors.size(); i++) cout << actors[i] << "; "; cout << endl; } void Vedio::release() { isReleased = true; } void Vedio::initialize() { name = ""; duration = 0.00; cost = 0.00; isReleased = false; } int main() { Vedio v; }
true
0a952515459c57ffe54828df78c8c493e19d6d37
C++
sqGlass/CPP_piscine
/01/ex00/main.cpp
UTF-8
1,779
2.828125
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sglass <sglass@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/04/08 14:24:18 by sglass #+# #+# */ /* Updated: 2021/04/08 17:14:05 by sglass ### ########.fr */ /* */ /* ************************************************************************** */ #include "Pony.hpp" void ponyOnTheHeap( void ) { Pony* littlePony1 = new Pony(7, "July", "icecream", "sglass"); littlePony1->ponyGreeting(); std::cout << std::endl << std::endl << std::endl << std::endl; std::cout << "Hey! I live and enjoy my life!!" << std::endl; std::cout << std::endl << std::endl << std::endl << std::endl; delete littlePony1; } void ponyOnTheStack( void ) { Pony littlePony2 (7, "July", "icecream", "sglass"); littlePony2.ponyGreeting(); std::cout << std::endl << std::endl << std::endl << std::endl; std::cout << "Hey! I live and enjoy my life!!" << std::endl; std::cout << std::endl << std::endl << std::endl << std::endl; } int main() { ponyOnTheHeap(); std::cout << std::endl; std::cout << "**************************************************************************************" << std::endl; std::cout << std::endl; ponyOnTheStack(); return 0; }
true
45ab3a67a1d98473766f54be7e7a2564d4fdb83d
C++
NikitaDmitryuk/Particle
/src/rotatingfield.cpp
UTF-8
596
3.140625
3
[]
no_license
#include "rotatingfield.h" RotatingField::RotatingField(Vector3d _tension) { tension = _tension; angleFi = Maths::computeFi(_tension); angleTetha = Maths::computeTetha(_tension); } void RotatingField::setTension(Vector3d _tension){ tension = _tension; } Vector3d RotatingField::getTension(){ return tension; } void RotatingField::setAngleFi(double _fi){ angleFi = _fi; double r = tension.norm(); tension[0] = r * sin(angleTetha) * cos(angleFi); tension[1] = r * sin(angleTetha) * sin(angleFi); } double RotatingField::getAngleFi(){ return angleFi; }
true
4c0ffd4917f513524363968df83aec3916dca088
C++
AdityaAgarwal436/daa-lab
/Week-6/isPath/isPath.cpp
UTF-8
1,095
3.265625
3
[]
no_license
#include <bits/stdc++.h> #include <stack> #define MAX 20 using namespace std; bool ispath(int **M, int V, int s, int d) { stack<int> st; bool *visited = new bool[V](); st.push(s); visited[s] = 1; while (!st.empty()) { int u = st.top(); st.pop(); for (int v = 0; v < V; ++v) { if (M[u][v] && v == d) return true; if (M[u][v] && !visited[v]) { st.push(v); visited[v] = 1; } } } return false; } int main() { int n; // cout<<"enter size: \n"; cin>>n; int **m; m=(int **)malloc(n*sizeof(int *)); for(int i=0;i<n;i++) m[i]=(int *)malloc(n*sizeof(int)); // cout<<"enter elements: \n"; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { cin>>m[i][j]; } } int s,d; cin>>s>>d; if(ispath(m,n,s-1,d-1)) cout<<"Path exists"; else cout<<"No Path does not exist"; return 0; }
true
b3df58ecc9472aa59e98a1060838b09949a42454
C++
ckj119940887/IntFlow
/tools/clang/test/CodeGen/ioc/cxx-explicit-cast.cpp
UTF-8
1,489
2.609375
3
[ "NCSA" ]
permissive
// Check explicit vs implicit cast handling in C++ // This is tricky because of the way implicit cast nodes are generated // to do the work for explicit casts, which become noop's. // Go through the various sources of integer casts here and check them. // RUN: %clang_cc1 -triple x86_64-apple-darwin10 -emit-llvm -o - %s \ // RUN: -fioc-implicit-conversion | FileCheck %s --check-prefix=IMPLICIT // RUN: %clang_cc1 -triple x86_64-apple-darwin10 -emit-llvm -o - %s \ // RUN: -fioc-explicit-conversion | FileCheck %s --check-prefix=EXPLICIT extern "C" int checkImplicit(long l); extern "C" int checkCStyle(long l); extern "C" int checkFunction(long l); extern "C" int checkStatic(long l); // IMPLICIT: define i32 @checkImplicit // EXPLICIT: define i32 @checkImplicit int checkImplicit(long l) { // IMPLICIT: call void @__ioc_report_conversion // EXPLICIT-NOT: call return l; } // IMPLICIT: define i32 @checkCStyle // EXPLICIT: define i32 @checkCStyle int checkCStyle(long l) { // IMPLICIT-NOT: call // EXPLICIT: call void @__ioc_report_conversion return (int)l; } // IMPLICIT: define i32 @checkFunction // EXPLICIT: define i32 @checkFunction int checkFunction(long l) { // IMPLICIT-NOT: call // EXPLICIT: call void @__ioc_report_conversion return int(l); } // IMPLICIT: define i32 @checkStatic // EXPLICIT: define i32 @checkStatic int checkStatic(long l) { // IMPLICIT-NOT: call // EXPLICIT: call void @__ioc_report_conversion return static_cast<int>(l); }
true
1fc1e3833d541063d859741cc05da76a27d9216a
C++
iter-yangxingya/linux
/system/code/fileio/copy.cpp
UTF-8
1,355
3.0625
3
[]
no_license
// // \file copy.cpp // \brief for copy existing file to new file. // #include <sys/stat.h> // for ??? #include <fcntl.h> // for ??? #include <header.h> // for my own error wrapper function. #include <string> #include <iostream> int main(int argc, char *argv[]) { if (argc == 2) { std::string argv1 = argv[1]; if (argv1 == "--help" || argv1 == "-h") usage_error("%s old-file new-file\n", argv[0]); } if (argc != 3) { std::cout << "Invalid argument" << std::endl; usage_error("%s old-file new-file\n", argv[0]); } int src_fd; if ((src_fd = open(argv[1], O_RDONLY)) == -1) error_exit("open file %s", argv[1]); int flags = O_CREAT | O_WRONLY | O_TRUNC; // rw-rw-rw- mode_t perms = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH; int dst_fd; if ((dst_fd = open(argv[2], flags, perms)) == -1) error_exit("open file %s", argv[2]); ssize_t len; char buf[1024]; while ((len = read(src_fd, buf, sizeof(buf))) > 0) if (write(dst_fd, buf, len) != len) fatal("couldn't write whole buffer"); if (len == -1) error_exit("read"); if (close(src_fd) == -1) error_exit("close source"); if (close(dst_fd) == -1) error_exit("close destination"); exit(EXIT_SUCCESS); }
true
dbec62ea462c6fdffa701b75d3e45ce2aa55ad9f
C++
DiamonJoy/DBScan
/ClusterAnalysis.h
UTF-8
8,171
3.328125
3
[]
no_license
/* 作者: DiamonJoy 维护: 2014.3.8 */ #include <iostream> #include <cmath> #include <fstream> #include <iosfwd> #include <math.h> #include <vector> #include "DataPoint.h" using namespace std; //聚类分析类型 class ClusterAnalysis { private: vector<DataPoint> dadaSets; //数据集合 unsigned int dimNum; //维度 double radius; //半径 unsigned int dataNum; //数据数量 unsigned int minPTs; //邻域最小数据个数 double GetDistance(DataPoint& dp1, DataPoint& dp2); //距离函数 void SetArrivalPoints(DataPoint& dp); //设置数据点的领域点列表 void KeyPointCluster( unsigned long i, unsigned long clusterId ); //对数据点领域内的点执行聚类操作 public: ClusterAnalysis(){} //默认构造函数 bool Init(char* fileName, double radius, int minPTs); //初始化操作 bool DoDBSCANRecursive(); //DBSCAN递归算法 bool WriteToFile(char* fileName); //将聚类结果写入文件 }; /* 函数:聚类初始化操作 说明:将数据文件名,半径,领域最小数据个数信息写入聚类算法类,读取文件,把数据信息读入写进算法类数据集合中 参数: char* fileName; //文件名 double radius; //半径 int minPTs; //领域最小数据个数 返回值: true; */ bool ClusterAnalysis::Init(char* fileName, double radius, int minPTs) { this->radius = radius; //设置半径 this->minPTs = minPTs; //设置领域最小数据个数 this->dimNum = DIME_NUM; //设置数据维度 ifstream ifs(fileName); //打开文件 if (! ifs.is_open()) //若文件已经被打开,报错误信息 { cout << "Error opening file\n"; //输出错误信息 exit (-1); //程序退出 } unsigned long i=0; //数据个数统计 while (! ifs.eof() ) //从文件中读取POI信息,将POI信息写入POI列表中 { DataPoint tempDP; //临时数据点对象 double tempDimData[DIME_NUM]; //临时数据点维度信息 for(int j=0; j<DIME_NUM; j++) //读文件,读取每一维数据 { ifs>>tempDimData[j]; } tempDP.SetDimension(tempDimData); //将维度信息存入数据点对象内 tempDP.SetDpId(i); //将数据点对象ID设置为i tempDP.SetVisited(false); //数据点对象isVisited设置为false tempDP.SetClusterId(-1); //设置默认簇ID为-1 dadaSets.push_back(tempDP); //将对象压入数据集合容器 i++; //计数+1 } ifs.close(); //关闭文件流 dataNum =i; //设置数据对象集合大小为i for(unsigned long k=0; k<dataNum;k++) { SetArrivalPoints(dadaSets[k]); //计算数据点领域内对象 } return true; //返回 } /* 函数:将已经过聚类算法处理的数据集合写回文件 说明:将已经过聚类结果写回文件 参数: char* fileName; //要写入的文件名 返回值: true */ bool ClusterAnalysis::WriteToFile(char* fileName ) { ofstream of1(fileName);//初始化文件输出流 for(int d=1; d<=DIME_NUM ; d++) //将维度信息写入文件 { of1<<"数据"<<d<<'\t'; if (d==DIME_NUM) of1<<"所属簇ID"<<'\t'<<endl; } for(unsigned long i=0; i<dataNum;i++) //对处理过的每个数据点写入文件 { for(int d=0; d<DIME_NUM ; d++) //将维度信息写入文件 of1<<dadaSets[i].GetDimension()[d]<<'\t'; if(dadaSets[i].GetClusterId() != -1) of1 << dadaSets[i].GetClusterId() <<endl; //将所属簇ID写入文件 else of1 <<"噪声点"<<endl; } of1.close(); //关闭输出文件流 return true; //返回 } /* 函数:设置数据点的领域点列表 说明:设置数据点的领域点列表 参数: 返回值: true; */ void ClusterAnalysis::SetArrivalPoints(DataPoint& dp) { for(unsigned long i=0; i<dataNum; i++) //对每个数据点执行 { double distance =GetDistance(dadaSets[i], dp);//获取与特定点之间的距离 //cout << dp.GetDpId()<<"to"<<i<<"is"<<distance<< endl; if(distance <= radius && i!=dp.GetDpId()) //若距离小于半径,并且特定点的id与dp的id不同执行 dp.GetArrivalPoints().push_back(i); //将特定点id压力dp的领域列表中 } if(dp.GetArrivalPoints().size() >= minPTs) //若dp领域内数据点数据量> minPTs执行 { dp.SetKey(true); //将dp核心对象标志位设为true return; //返回 } dp.SetKey(false); //若非核心对象,则将dp核心对象标志位设为false } /* 函数:执行聚类操作 说明:执行聚类操作 参数: 返回值: true; */ bool ClusterAnalysis::DoDBSCANRecursive() { unsigned long clusterId=0, k = 0; //聚类id计数,初始化为0 for(unsigned long i=0; i<dataNum;i++) //对每一个数据点执行 { DataPoint& dp=dadaSets[i]; //取到第i个数据点对象 if(!dp.isVisited() && dp.IsKey()) //若对象没被访问过,并且是核心对象执行 { dp.SetClusterId(clusterId); //设置该对象所属簇ID为clusterId dp.SetVisited(true); //设置该对象已被访问过 KeyPointCluster(i,clusterId); //对该对象领域内点进行聚类 clusterId++; //clusterId自增1 } /*if(!dp.IsKey()) { cout <<"噪声点"<<i<< endl; k++; }*/ } for(unsigned long j=0; j<dataNum;j++) { DataPoint& dptemp=dadaSets[j]; if(dptemp.GetClusterId()!=-1) cout << "数据点"<< dptemp.GetDpId()<< " 聚类ID为"<< dptemp.GetClusterId() << endl; else { cout <<"噪声点"<<j<< endl; k++; } } cout <<"\n共聚类" <<clusterId<<"个"<< endl; //算法完成后,输出聚类个数 cout <<"噪声点" <<k<<"个"<< endl; return true; //返回 } /* 函数:对数据点领域内的点执行聚类操作 说明:采用递归的方法,深度优先聚类数据 参数: unsigned long dpID; //数据点id unsigned long clusterId; //数据点所属簇id 返回值: void; */ void ClusterAnalysis::KeyPointCluster(unsigned long dpID, unsigned long clusterId ) { DataPoint& srcDp = dadaSets[dpID]; //获取数据点对象 if(!srcDp.IsKey()) return; vector<unsigned long>& arrvalPoints = srcDp.GetArrivalPoints(); //获取对象领域内点ID列表 for(unsigned long i=0; i<arrvalPoints.size(); i++) { DataPoint& desDp = dadaSets[arrvalPoints[i]]; //获取领域内点数据点 if(!desDp.isVisited()) //若该对象没有被访问过执行 { //cout << "数据点"<< desDp.GetDpId()<<" 聚类ID为" <<clusterId << endl; desDp.SetClusterId(clusterId); //设置该对象所属簇的ID为clusterId,即将该对象吸入簇中 desDp.SetVisited(true); //设置该对象已被访问 if(desDp.IsKey()) //若该对象是核心对象 { KeyPointCluster(desDp.GetDpId(),clusterId); //递归地对该领域点数据的领域内的点执行聚类操作,采用深度优先方法 } } } } //两数据点之间距离 /* 函数:获取两数据点之间距离 说明:获取两数据点之间的欧式距离 参数: DataPoint& dp1; //数据点1 DataPoint& dp2; //数据点2 返回值: double; //两点之间的距离 */ double ClusterAnalysis::GetDistance(DataPoint& dp1, DataPoint& dp2) { double distance =0; //初始化距离为0 for(int i=0; i<DIME_NUM;i++) //对数据每一维数据执行 { distance += pow(dp1.GetDimension()[i] - dp2.GetDimension()[i],2); //距离+每一维差的平方 } return pow(distance,0.5); //开方并返回距离 }
true
ae1322cc9745977c20486a01d67edadf47ddaaa8
C++
lineCode/Avatar
/Avatar/CFileManager.h
UTF-8
5,037
2.703125
3
[]
no_license
//================================================ // Copyright (c) 2020 周仁锋. All rights reserved. // ye_luo@qq.com //================================================ #ifndef _CFILEMANAGER_H_ #define _CFILEMANAGER_H_ #include "AvatarConfig.h" #include <string> #include <vector> using std::string; using std::vector; /** * @brief 文件管理器 */ class AVATAR_EXPORT CFileManager { public: //! 获取管理器实例 static CFileManager* GetInstance() { if (m_pInstance) return m_pInstance; m_pInstance = new CFileManager(); return m_pInstance; } //! 实例销毁 void Destroy(); public: //! 获取程序路径,包含'/' static string GetAppDirectory(); //! 获取文件扩展名,不包含'.' static string GetExtension(const string& path); //! 获取文件路径,包含'/' static string GetDirectory(const string& path); //! 获取文件名称 static string GetFileName(const string& path, bool withExt); //! 检查是否是全路径 static bool IsFullPath(const string& path); //! 设置资源目录 void SetDataDirectory(const string& directory); //! 获取资源目录 string GetDataDirectory(); //! 检查目录是否存在 bool DirectoryExists(const string& directory); //! 创建目录 bool DirectoryCreate(const string& directory); //! 检查文件是否存在 bool FileExists(const string& filename); //! 获取文件大小 size_t FileSize(const string& filename); //! 获取路径下所有文件 void GetFileList(const string& directory, vector<string>& file); public: //! 支持的文件类型 enum FileType { BIN, TXT, BMP, TGA, PNG, JPG, WAV, MP3 }; //! 文件数据类 class CFileData { public: FileType type; size_t size; unsigned char* contents; CFileData(FileType type) : type(type), size(0), contents(0) {} CFileData(FileType type, size_t size) : type(type), size(size) { contents = new unsigned char[size]; } virtual ~CFileData() { if (contents) delete[] contents; } }; //! 二进制文件 class CBinaryFile : public CFileData { public: CBinaryFile() : CFileData(BIN) {} CBinaryFile(size_t size) : CFileData(BIN, size) {} }; //! 文本文件 class CTextFile : public CFileData { public: CTextFile() : CFileData(TXT) {} CTextFile(size_t size) : CFileData(TXT, size + 1) {} }; //! 图片文件 class CImageFile : public CFileData { public: int channels; int width; int height; CImageFile(FileType type) : CFileData(type), channels(0), width(0), height(0) {} CImageFile(FileType type, size_t size) : CFileData(type, size), channels(0), width(0), height(0) {} CImageFile(FileType type, int c, int w, int h) : CFileData(type, c * w * h), channels(c), width(w), height(h) {} }; //! 音频文件 class CAudioFile : public CFileData { public: int channels; int sampleRate; int sampleBits; CAudioFile(FileType type) : CFileData(type), channels(0), sampleRate(0), sampleBits(0) {} CAudioFile(FileType type, size_t size) : CFileData(type, size), channels(0), sampleRate(0), sampleBits(0) {} }; public: //! 文件读操作 bool ReadFile(const string& filename, CFileData* file); //! 文件读操作 bool ReadFile(unsigned char* buffer, size_t size, CFileData* file); //! 文件写操作 bool WriteFile(CFileData* file, const string& filename); //! 文件写操作 bool WriteFile(CFileData* file, unsigned char* buffer, size_t* size); private: CFileManager(); ~CFileManager(); //! 解析各种文件方法 bool ParseBinFile(unsigned char* data, size_t size, CFileData* file); bool ParseTxtFile(unsigned char* data, size_t size, CFileData* file); bool ParseBmpFile(unsigned char* data, size_t size, CFileData* file); bool ParseTgaFile(unsigned char* data, size_t size, CFileData* file); bool ParsePngFile(unsigned char* data, size_t size, CFileData* file); bool ParseJpgFile(unsigned char* data, size_t size, CFileData* file); bool ParseWavFile(unsigned char* data, size_t size, CFileData* file); bool ParseMp3File(unsigned char* data, size_t size, CFileData* file); //! 各种文档的序列化 bool SerializeBinFile(CFileData* file, unsigned char** data, size_t* size); bool SerializeTxtFile(CFileData* file, unsigned char** data, size_t* size); bool SerializeBmpFile(CFileData* file, unsigned char** data, size_t* size); bool SerializeTgaFile(CFileData* file, unsigned char** data, size_t* size); bool SerializePngFile(CFileData* file, unsigned char** data, size_t* size); bool SerializeJpgFile(CFileData* file, unsigned char** data, size_t* size); bool SerializeWavFile(CFileData* file, unsigned char** data, size_t* size); bool SerializeMp3File(CFileData* file, unsigned char** data, size_t* size); private: //! 数据目录定义 typedef struct _SDirectory { string path; bool isCompressed; bool isRemoteUrl; } SDirectory; private: //! 当前文件目录 SDirectory* m_pCurrentDirectory; //! URL 请求接口 class CUrlConnection* m_pUrlConnection; //! ZIP 读取接口 class CZipReader* m_pZipReader; //! 实例 static CFileManager* m_pInstance; }; #endif
true
2e375040afd99e5daa5f48c1c27ae44d03521036
C++
Aufasder/Progra
/BoletosUI/BoletoUI/mainboletoswindow.cpp
UTF-8
1,843
2.515625
3
[]
no_license
#include "mainboletoswindow.h" #include "ui_mainboletoswindow.h" #include <QMessageBox> /* QVector <int> DFe; QVector <int> MFe; QVector <int> AFe; */ QVector <QString> Nev; QVector <int> Ven; MainBoletosWindow::MainBoletosWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainBoletosWindow) { ui->setupUi(this); ui->agregar->setText("Agregar"); ui->edit->setEnabled(false); ui->cancelar->setEnabled(false); ui->aceptar->setEnabled(false); } MainBoletosWindow::~MainBoletosWindow() { delete ui; } void MainBoletosWindow::on_aceptar_clicked() { QString nomnom; nomnom = ui->edit->text(); Nev.push_back(nomnom); Ven.push_back(0); ui->listWidget->addItem(nomnom); ui->listWidget_2->addItem(QString::number(0)); // QMessageBox::information(this, "message",nomnom); ui->edit->clear(); ui->cancelar->setEnabled(false); ui->aceptar->setEnabled(false); ui->edit->setEnabled(false); } void MainBoletosWindow::on_cancelar_clicked() { ui->edit->clear(); ui->cancelar->setEnabled(false); ui->aceptar->setEnabled(false); ui->edit->setEnabled(false); } void MainBoletosWindow::on_agregar_clicked() { ui->aceptar->setEnabled(true); ui->cancelar->setEnabled(true); ui->edit->setEnabled(true); } void MainBoletosWindow::on_listWidget_doubleClicked(const QModelIndex &index) { int numnum = ui->listWidget->currentRow(); // QMessageBox::information(this, "vendido", QString::number(numnum)); Ven[numnum]++; ui->listWidget_2->item(numnum)->setText(QString::number(Ven[numnum])); } void MainBoletosWindow::on_resumen_clicked() { int tam=Ven.size(); int tot=0; for (int i=0 ; i < tam ; i++){ tot = tot+ Ven [i]; } QMessageBox::information(this, "resumen", "Boletos Vendidos = " +QString::number(tot)); }
true
c4ceb13f10f985142c092493f76895323bd1df3a
C++
convict-git/sport_coding
/educational_cf/codeforces.com/Codeforces_Educational_Codeforces_Round_39/F._Fibonacci_String_Subsequences/main2.cpp
UTF-8
3,741
2.640625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; #define IOS ios_base::sync_with_stdio(false); cin.tie (nullptr) #define PREC cout.precision (10); cout << fixed #ifdef CONVICTION #include "/home/convict/Dropbox/myfiles/sport_coding/cplib/snippets/debug.h" #else #define debug(x...) #endif //Don’t practice until you get it right. Practice until you can’t get it wrong // @ O(|s|) vector <int> pref_func (string &s) { int n = (int)s.size(); vector <int> pi(n); pi[0] = 0; int sz = (int)s.size(); for (int i = 1; i < sz; ++i) { int len_j = pi[i-1]; int j = len_j - 1; while (len_j > 0 && s[j + 1] != s[i]) { len_j = pi[j]; j = len_j - 1; } if (s[len_j] == s[i]) ++len_j; pi[i] = len_j; } return pi; } // @ each state represents prefix length // @ transition : length * char -> length, O(|s| * |alpha|) vector <vector <int>> calc_fsm (string t) { int n = (int)t.size(); const int AlpSz = 2; t += '#'; vector <int> pi = pref_func(t); vector <vector <int>> fsm(n + 1, vector <int> (AlpSz)); for (int len = 0; len <= n; ++len) { for (int ch = 0; ch < AlpSz; ++ch) { if (len == 0 || t[len] == char('0' + ch)) fsm[len][ch] = len + (t[len] == char('0' + ch)); else fsm[len][ch] = fsm[pi[len - 1]][ch]; } } return fsm; } const int Mod = (int)1e9 + 7; inline int add (int x, int y) { return (1ll * x + y + (Mod << 1)) % Mod; } inline int sub (int x, int y) { return (1ll * x - y + (Mod << 1)) % Mod; } inline int mul (int x, int y) { return (int) (1ll*(x + Mod) * (y + Mod) % Mod); } inline int pow (int x, int y) { int res = 1; while (y) { if (y & 1) res = mul(res, x); x = mul(x, x), y >>= 1; } return res; } inline int inv (int x) { return pow(x, Mod - 2); } inline int dv (int x, int y) { return mul(x, inv(y)); } const int Maxn = 110; int M[Maxn][Maxn][Maxn]; // M(i, j, k), ith F, starting from jth state reaching kth state int lenS, xFibIdx; string S; // @ Brief Multiplies two matrices void mulMatrices (int toIdx, int fromFirstIdx, int fromSecondIdx) { for (int st = 0; st <= lenS; ++st) { // start state for (int en = 0; en <= lenS; ++en) { // end state int& updM = M[toIdx][st][en], lft, rt; for (int mid = 0; mid <= lenS; ++mid) { // mid state lft = M[fromFirstIdx][st][mid]; rt = M[fromSecondIdx][mid][en]; updM = add(updM, mul(lft, rt)); } } } } void showMat (int idx) { cerr << "Matrix : " << idx << endl; for (int st = 0; st <= lenS; ++st) { for (int en = 0; en <= lenS; ++en) { cerr << M[idx][st][en] << ' '; } cerr << '\n'; } } void preproc() { } void solve() { memset(M, 0, sizeof(M)); cin >> lenS >> xFibIdx >> S; vector <vector <int>> aut = calc_fsm(S); // initiate M[0] and M[1] // M[idx][st][st] = 1, st -> st, when you don't take a move for (int idx = 0; idx < 2; ++idx) { for (int st = 0; st <= lenS; ++st) { M[idx][st][st] = 1; } } // M[idx][st][aut[st][idx]]++ , st -> aut[st][idx], when you take a move for (int idx = 0; idx < 2; ++idx) { for (int st = 0; st <= lenS; ++st) { int nxtState = aut[st][idx]; M[idx][st][nxtState] += 1; } } // M[idx] = M[idx-1] * M[idx - 2] for (int idx = 2; idx <= xFibIdx; ++idx) { mulMatrices(idx, idx - 1, idx - 2); } // Final answer is M[xFibIdx][0][lenS] cout << M[xFibIdx][0][lenS] << '\n'; } signed main() { IOS; PREC; preproc(); int tc = 1; // cin >> tc; for (int Tt = 1; Tt <= tc; ++Tt) { // cout << "Case #" << Tt << ": "; solve(); } return EXIT_SUCCESS; }
true
2f82186f03e147e1c0b30941b55daae41c3e4e59
C++
suzuren/gamelearning
/cpp_new_features/enum_class.h
UTF-8
1,577
3.09375
3
[]
no_license
#ifndef __ENUM_CLASS_H_ #define __ENUM_CLASS_H_ enum class enum_class_value_t_1 { enum_class_value_1 = 3, enum_class_value_2, enum_class_value_3, enum_class_value_4, }; enum class enum_class_value_t_2 { enum_class_value_1 = 17, enum_class_value_2, enum_class_value_3, enum_class_value_4, }; class tets_class { public: tets_class() {}; ~tets_class() {}; int i; void init() { i = 1; } }; void test_enum_class() { cout << "test_enum_class - t_1:" << static_cast<int>(enum_class_value_t_1::enum_class_value_1) << endl; cout << "test_enum_class - t_1:" << static_cast<int>(enum_class_value_t_1::enum_class_value_2) << endl; cout << "test_enum_class - t_1:" << static_cast<int>(enum_class_value_t_1::enum_class_value_3) << endl; cout << "test_enum_class - t_1:" << static_cast<int>(enum_class_value_t_1::enum_class_value_4) << endl; cout << "test_enum_class - t_2:" << static_cast<int>(enum_class_value_t_2::enum_class_value_1) << endl; cout << "test_enum_class - t_2:" << static_cast<int>(enum_class_value_t_2::enum_class_value_2) << endl; cout << "test_enum_class - t_2:" << static_cast<int>(enum_class_value_t_2::enum_class_value_3) << endl; cout << "test_enum_class - t_2:" << static_cast<int>(enum_class_value_t_2::enum_class_value_4) << endl; cout << "test_enum_class - t_1 - is_pod::value " << is_pod<enum_class_value_t_1>::value << endl; cout << "test_enum_class - t_2 - is_pod::value " << is_pod<enum_class_value_t_2>::value << endl; cout << "test_enum_class - tets_class - is_pod::value " << is_pod<tets_class>::value << endl; } #endif
true
76fab1b400c5ead2c92225ee2aff49c1380a2001
C++
KushRohra/Codechef_codes
/COUPSYS.cpp
UTF-8
816
2.640625
3
[]
no_license
#include<iostream> using namespace std; int main() { int t; cin>>t; while(t--) { int i,n,c,l,d,max1=0,max2=0,max3=0,p1=1000,p2=1000,p3=1000,x,y,z; cin>>n; for(i=0;i<n;i++) { cin>>c>>l; if(l==1) { cin>>x; if(x>=max1) { if(x>max1) { max1=x; p1=c; } else { if(c<p1) p1=c; } } } else if(l==2) { cin>>y; if(y>=max2) { if(y>max2) { max2=y; p2=c; } else { if(c<p2) p2=c; } } } else if(l==3) { cin>>z; if(z>=max3) { if(z>max3) { max3=z; p3=c; } else { if(c<p3) p3=c; } } } } cout<<max1<<" "<<p1<<endl; cout<<max2<<" "<<p2<<endl; cout<<max3<<" "<<p3<<endl; } }
true
ae34c169f615aa9d86a31f7984327dce1c53f7d0
C++
weiho1122/LeetCode
/C++/293 Flip Game.cpp
UTF-8
1,168
3.21875
3
[]
no_license
class Solution { public: vector<string> generatePossibleNextMoves(string s) { vector<string> rlt; if(s=="") return rlt; set<string> store; store.insert(s); for(int i = 0; i < s.size()-1; i++){ if(s[i] == '+' && s[i] == s[i+1]){ string tmp = flip(s, i); if(store.find(tmp) == store.end()) store.insert(tmp); } } store.erase(s); for(auto s : store){ rlt.push_back(s); } return rlt; } string flip(string ss, int pos){ string s = ss; s[pos++] = '-'; s[pos] = '-'; return s; } }; /* class Solution { public: vector<string> generatePossibleNextMoves(string s) { vector<string> rlt; if(s=="") return rlt; for(int i = 0; i < s.size()-1; i++){ if(s[i] == '+' && s[i] == s[i+1]){ rlt.push_back(flip(s, i)); } } return rlt; } string flip(string ss, int pos){ string s = ss; s[pos++] = '-'; s[pos] = '-'; return s; } }; */
true
c4137829bd7ccb2c6d22952cbb4248b33d76555f
C++
denaxen/platformer_game
/src/player_states.h
UTF-8
2,733
2.59375
3
[]
no_license
#pragma once #include <SFML/Window.hpp> #include <SFML/Graphics.hpp> #include "animation.h" #include "player.h" class Player; class PlayerState { protected: Animation animation; public: PlayerState(); sf::Vector2i get_size(); void set_sprite(sf::Sprite& sprite, bool is_faced_right); virtual void handle_events(Player* player, const sf::Event& event); virtual void update(Player* player, float dt); virtual void hook(Player* player, sf::Vector2f position) = 0; virtual void attacked(Player* player) = 0; virtual void start_falling(Player* player) = 0; virtual void hit_ground(Player* player) = 0; virtual ~PlayerState(); }; class Idle : public PlayerState { public: Idle(Player* player); void update(Player* player, float dt); void handle_events(Player* player, const sf::Event& event); void hook(Player* player, sf::Vector2f position); void attacked(Player* player); void start_falling(Player* player); void hit_ground(Player* player); }; class Running : public PlayerState { private: static float running_speed; public: Running(Player* player); void update(Player* player, float dt); void handle_events(Player* player, const sf::Event& event); void hook(Player* player, sf::Vector2f position); void attacked(Player* player); void start_falling(Player* player); void hit_ground(Player* player); }; class Sliding : public PlayerState { private: static float sliding_time; float current_time; static float velocity_multiplier; static float velocity_decay; public: Sliding(Player* player); void update(Player* player, float dt); void handle_events(Player* player, const sf::Event& event); void hook(Player* player, sf::Vector2f position); void attacked(Player* player); void start_falling(Player* player); void hit_ground(Player* player); }; class Falling : public PlayerState { float initial_velocity_x; static float acceleration_x; static float max_velocity_x; static float max_velocity_y; public: Falling(Player* player); void update(Player* player, float dt); void handle_events(Player* player, const sf::Event& event); void hook(Player* player, sf::Vector2f position); void attacked(Player* player); void start_falling(Player* player); void hit_ground(Player* player); }; class Hooked : public PlayerState { public: static float max_hook_offset; static float hook_displacement; Hooked(Player* player); void update(Player* player, float dt); void handle_events(Player* player, const sf::Event& event); void hook(Player* player, sf::Vector2f position); void attacked(Player* player); void start_falling(Player* player); void hit_ground(Player* player); };
true
2e350107770d850af20e18f8531e47f759b91890
C++
msinyakova/Tinkoff_algorithm
/bag2.cpp
UTF-8
757
2.71875
3
[]
no_license
#include <iostream> #include <vector> using namespace std; int main() { int n, w; cin >> n >> w; vector<int> weights(n + 1, 0); for (int i = 1; i < n + 1; i++) cin >> weights[i]; vector<vector<int>> dp(n + 1, vector<int>(w + 1, -1000000)); dp[0][0] = 0; for (int i = 1; i < n + 1; i++) { for (int j = 0; j < w + 1; j++) { if (j - weights[i] < 0) { dp[i][j] = dp[i - 1][j]; } else { dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weights[i]] + weights[i]); } } } int max_w = -1000000; for (int k = 0; k < w + 1; k++) max_w = max(max_w, dp[n][k]); cout << max_w << endl; return 0; }
true
ba440e88d57a4a20f9495a7cd23f850d2855a8da
C++
codeBeefFly/bxg_cpp
/day04_05/day04_05_homework_01_correction/Student.cpp
GB18030
1,239
3.421875
3
[]
no_license
#include "Student.h" Student::Student() : Student("unknown" , {}) { std::cout << "..log::޲ι캯...\n"; } Student::Student(std::string name) : Student(name, {}) { std::cout << "..log::һι캯...\n"; } Student::Student(std::string name, std::vector<int> score_vector) : name{ new std::string(name) }, score_vector{ score_vector } { std::cout << "..log::ι캯...\n"; } Student::~Student() { std::cout << "..log::...\n"; std::cout << name << "\n"; delete name; // ͷ еĶѿռ //name = nullptr; } // Student::Student(const Student& stu) { std::cout << "..log::캯...\n"; //*name = *stu.name; // name ǿָ룬Ҫռ name = new std::string(*stu.name); score_vector = stu.score_vector; } void Student::updateScore() { std::cout << "..log::³ɼ...\n"; for (int& score : score_vector) { if (score < 60) { score = 60; } } } void Student::showInfo() { std::cout << "\n..log::ʾɼ...\n"; std::cout << "...ѧ::\t" << *name << "\n"; std::cout << "...::\t"; int score_index{ 0 }; for (int score : score_vector) { std::cout << score << "\t"; score_index++; } }
true
2246a9afb06cc48a4eff1a714e16c6abebaef246
C++
vaneet-hash/Competitive-Programming-codes-CPP
/VOTERSDI.cpp
UTF-8
1,473
3.28125
3
[]
no_license
/*#include <stdio.h> #include <stdlib.h> int main() { int x=5; int *ptr; *ptr=&x; printf("%d",printf("%d",ptr)); return 0; }*/ //------------------------------------------------------- // #include <iostream> // #include <algorithm> // using namespace std; // int main() // { // int tree[][4]={ // {2}, // {3,4}, // {6,5,7}, // {4,1,8,3}}; // int s=0; // for(int i=0;i<4;i++) // { // int min=1000007; // for(int j=0;j<4;j++) // { // if(tree[i][j]<min && tree[i][j] != 0) // min=tree[i][j]; // } // s+=min; // } // cout<<s; // return 0; // } //--------------------------------------------------------- // #include <iostream> // #include <cstring> // using namespace std; // int main() // { // bool test[10][10]; // memset(test, true, sizeof(test)); // for(int i=0;i<10;i++) // { // for(int j=0;j<10;j++) // { // cout<<test[i][j]<<" "; // } // } // } //------------------------------------------------------------- //Sieve of Eratosthenes // void sieveOfEratosthenes(int num) // { // bool prime[n+1]; // memset(prime, true, sizeof(prime)) //use cstring header // for(int i=2;i*i<=num;i++) // { // if(prime[i]) // { // for(int j=i*i;j<=n;j+=i) // prime[j]=false; // } // } // for(int i=0;i<n;i++) // if(prime[i]) // cout<<i<<" "; // } //--------------------------------------------------------------------
true
d101d855a7a2b86164b40b4c8988f8a4d3032a61
C++
cms-sw/cmssw
/L1Trigger/L1TCommon/interface/TriggerSystem.h
UTF-8
3,545
2.609375
3
[ "Apache-2.0" ]
permissive
#ifndef L1Trigger_L1TCommon_l1t_TriggerSystem_h #define L1Trigger_L1TCommon_l1t_TriggerSystem_h #include <vector> #include <string> #include <map> #include <set> #include "Parameter.h" #include "L1Trigger/L1TCommon/interface/Mask.h" namespace l1t { class TriggerSystem { private: std::string sysId; std::map<std::string, std::string> procToRole; // map of processors to their roles std::map<std::string, std::string> procToSlot; // map of processors to their slots in some crate std::map<std::string, bool> procEnabled; // processor is active/disabled (also including daqttc) std::map<std::string, std::string> daqttcToRole; // map of DAQ/TTC boards to their roles std::map<std::string, std::string> daqttcToCrate; // map of DAQ/TTC boards to the crates they sit in std::map<std::string, std::set<std::string> > roleForProcs; // map of roles, each describing a set of processors std::map<std::string, std::set<std::string> > crateForProcs; // map of crates, each containing a set of processors std::map<std::string, std::set<std::string> > roleForDaqttcs; // map of roles, each describing a set of DAQ/TTC boards std::map<std::string, std::map<std::string, Parameter> > procParameters; // setting objects found in the configuration for a given processor std::map<std::string, std::map<std::string, Mask> > procMasks; // mask objects found in the configuration for a given processor bool isConfigured; // lock allowing access to the system mutable std::ostream *logs; // print processing logs unless is set to a null pointer public: void configureSystemFromFiles(const char *hwCfgFile, const char *topCfgFile, const char *key); void addProcessor(const char *processor, const char *role, const char *crate, const char *slot); // must have all parameters void addDaq(const char *daq, const char *role, const char *crate); void addParameter( const char *id, const char *procOrRole, const char *type, const char *value, const char *delim = ","); void addTable(const char *id, const char *procOrRole, const char *columns, const char *types, const std::vector<std::string> &rows, const char *delim); void addMask(const char *id, const char *procOrRoleOrDaq); void disableProcOrRoleOrDaq(const char *procOrRoleOrDaq); const std::map<std::string, std::string> &getProcToRoleAssignment(void) const noexcept { return procToRole; } const std::map<std::string, std::set<std::string> > &getRoleToProcsAssignment(void) const noexcept { return roleForProcs; } const std::map<std::string, Parameter> &getParameters(const char *processor) const; const std::map<std::string, Mask> &getMasks(const char *processor) const; bool isMasked(const char *proccessor, const char *id) const; bool isProcEnabled(const char *proccessor) const; std::string systemId(void) const noexcept { return sysId; } void setSystemId(const char *id) noexcept { sysId = id; } void setConfigured(bool state = true) noexcept { isConfigured = state; } void setLogStream(std::ostream *s) const noexcept { logs = s; } TriggerSystem(void) { isConfigured = false; logs = nullptr; } ~TriggerSystem(void) {} }; } // namespace l1t #endif
true
c97e5db6adb791b5675dfaa261a3051baf3af6eb
C++
PopovaYarovaya/kursach-arkanoid-
/Arcanoid/Arcanoid/ball.cpp
WINDOWS-1251
5,297
2.703125
3
[]
no_license
#include "ball.h" #include <QDebug> #include "game.h" #include "brick.h" Ball::Ball(PlayerPlatform *playerPlatform) { speed = 1; image = QImage("../Arcanoid/resources/ball.png"); w = image.width(); h = image.height(); setData(QVariant::String, "Ball"); this->playerPlatform = playerPlatform; resetPosition(); } QRectF Ball::boundingRect() const { return QRect(x, y, image.width(), image.height()); } void Ball::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { painter->drawImage(this->x, this->y, image); } void Ball::resetPosition() { x = (Game::WIDTH - w) / 2; y = this->playerPlatform->y - h; } void Ball::startLeft() { direction = topLeft; speed = 1; } void Ball::startRight() { direction = topRight; speed = 1; } void Ball::advance(int phase) { //if(!phase) return; switch(direction){ case topRight: if (x + speed >= scene()->width()) { direction = topLeft; } else if (y - speed <= 0) { direction = bottomRight; } x += speed; y -= speed; break; case topLeft: if (x - speed <= 0) { direction = topRight; } else if (y - speed < 0) { direction = bottomLeft; } x -= speed; y -= speed; break; case bottomRight: if (x + speed >= scene()->width()) { direction = bottomLeft; } else if (y + speed >= scene()->height()) { direction = topRight; } x += speed; y += speed; break; case bottomLeft: if (x - speed <= 0) { direction = bottomRight; } else if (y + speed >= scene()->height()) { direction = topLeft; } x -= speed; y += speed; break; } if (y + image.width() > this->playerPlatform->y) { // if (this->boundingRect().intersects(this->playerPlatform->boundingRect())) { if (direction == bottomRight) { direction = topRight; } else { direction = topLeft; } } else { speed = 0; // TODO RESET } } foreach(QGraphicsItem *item, scene()->items()) { if (item->data(QVariant::String).toString() == "Brick") { Brick *b = (Brick*) item; if(this->boundingRect().intersects(b->boundingRect())) { // switch(direction) { case topRight: if ((y <= (b->y+b->h)) && (x + w >= b->x) && (x <= b->x + b->w)) { // direction = bottomRight; break; } if ((x + w >= b->x) && (y <= b->y + b->h) && (y + h >= b->y)) { // direction = topLeft; break; } break; case topLeft: if ((y <= (b->y+b->h)) && (x + w >= b->x) && (x <= b->x + b->w)) { // direction = bottomLeft; break; } if (x <= b->x + b->h && y <= b->y + b->h && y + h >= b->y) { // direction = topRight; break; } break; case bottomRight: if ((x + w >= b->x) && (y <= b->y + b->h) && (y + h >= b->y)) { // direction = bottomLeft; break; } if (y + h >= b->y && x + w >= b->x && x <= b->x + b->h) { // direction = topRight; break; } break; case bottomLeft: if (y + h >= b->y && x + w >= b->x && x <= b->x + b->h) { // direction = topLeft; break; } if (x <= b->x + b->h && y <= b->y + b->h && y + h >= b->y) { // direction = bottomRight; break; } break; } scene()->removeItem(b); } } } scene()->update(); }
true
d6a2bd3d7e3f36c0ad1e3869fa62972c4fc4cba6
C++
Andrewsher/Leetcode
/8_String_to_Integer_(atoi).cpp
UTF-8
733
3.109375
3
[]
no_license
class Solution { public: int myAtoi(string str) { int result = 0; int i = 0, tag = 1; i = str.find_first_not_of(' '); if(i == str.size()) return 0; if(str[i] == '+' || str[i] == '-') { if(str[i] == '+') tag = 1; else tag = -1; i++; } while(str[i] >= '0' && str[i] <= '9') { int temp = result * 10 + (str[i] - '0'); if(temp / 10 != result) { cout << "Up to limits!" << endl; if(tag == 1) return INT_MAX; else return -1 * INT_MAX - 1; } result = temp; i++; } result = result * tag; return result; } };
true
828fd361afc6f802e527fc5742f03e5057a797b0
C++
PlabonKumarsaha/University_Work
/Algoritms/ackermann function.cpp
UTF-8
520
3.21875
3
[]
no_license
#include <iostream> using namespace std; int ackermann_function(int m,int n){ if(m==0 && n>0){ return n+1; } if(n==0 && m>0){ ackermann_function(m-1,1); } if(m>0 && n>0){ ackermann_function(m-1,ackermann_function(m,n-1)); } } int main() { int i,j; for(i=0;i<=7;i++) { for(j=0;j<=7;j++) { if(i==0 && j==0) { } else cout<<ackermann_function(i,j)<<" "; } cout<<endl; } return 0; }
true
2b1ac0eb778f8d683eeca82e34e7400dec7778ff
C++
Saphal-Thammu/Leet-Code-solutions
/intersection-of-two-linked-lists/intersection-of-two-linked-lists.cpp
UTF-8
1,481
3.46875
3
[]
no_license
/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public:    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {                int lenA = 0; // length of 1st path        int lenB = 0; // length of second path        int diff; // difference between the lengths                ListNode* A=headA;        ListNode* B=headB;                while(A!=NULL){ // calc of length            lenA+=1;            A=A->next;       }                while(B!=NULL){  // calc of length            lenB+=1;            B=B->next;       }                if(lenA > lenB){            diff=lenA-lenB;            while(diff != 0){                headA = headA->next;                diff--;           }       }else{            diff = lenB-lenA;            while(diff > 0){                headB = headB->next;                diff--;           }                   }                while(headA != headB){            headA = headA->next;            headB = headB->next;       }                return headA;                                                                   } };
true
354e5caa2ee7f68457032f93eff35db1c2e67bfa
C++
ShacharMeir007/Flight_Simulator
/TextFunctions.h
UTF-8
944
2.6875
3
[]
no_license
// // Created by shachar Meir on 09/01/2020. // #ifndef FLIGHT_SIMULATOR__TEXTFUNCTIONS_H_ #define FLIGHT_SIMULATOR__TEXTFUNCTIONS_H_ #include <vector> #include <string> #include <iostream> //functions to help manage operations on strings void replace(char token1,const std::string & token2, std::string& str); void remove_redundant_signs(std::string& str); void remove_spaces(std::string& str); void remove_quotation(std::string& str); std::vector<std::string> split(char token, std::string& str); void strip(std::string& str); bool isVar(std::string& str); bool isInQuotations(std::string& str); bool isAssign(std::string& str); bool isCondition(std::string& str); bool isLogicOperator(std::string &str); bool isOpenDataServer(std::string &str); bool isConnectControlClient(std::string &str); bool isPrint(std::string &str); bool isSleep(std::string &str); void makeConditionBetSpaces(std::string &s); #endif //FLIGHT_SIMULATOR__TEXTFUNCTIONS_H_
true
f5511af781328e06ced9e4dc3707d40b8fae69bc
C++
AndyFernandes/programming-lab
/DictWithAVL/AVL.cpp
UTF-8
11,363
3.4375
3
[]
no_license
#include <iostream> #include <stdio.h> #include "avl.hpp" using namespace std; // Inicializa D como uma árvore vazia. void inicializar (DicAVL &D){ D.raiz = nullptr; } // Pega a altura do nó int height(Noh *no){ if(no == nullptr) return 0; return no->h; } // Serve para ver qual a altura do nó, dado a altura dos seus filhos esq e dir int max(int a, int b){ return (a > b)? a : b; } // Verificar se um nó é folha bool isLeaf(Noh* no){ if(no->esq == nullptr && no->dir == nullptr) return true; return false; } // Aloca um novo nó Noh* newNo(TC chave, TV value, int h){ Noh *no = new Noh(); no->chave = chave; no->valor = value; no->pai = nullptr; no->esq = nullptr; no->dir = nullptr; no->h = h; return no; } // Dá o fator de balanço de um nó: Está balanceado se retornar -1, 0 ou 1 int getBalance(Noh* no){ if(no == nullptr) return 0; return height(no->esq) - height(no->dir); } // Realiza a rotação a Esquerda de um nó, e muda o nó do dicionário se o pai desse nó for nulo (ser a raiz) Noh* rotationLeft(DicAVL &dicionario, Noh *x){ Noh* paiX = x->pai; Noh* y = x->dir; Noh* filhoEsqY = y->esq; // Ponteiro de PaiX -> muda filho do lugar de X pra Y if(paiX != nullptr){ if(paiX->esq == x) paiX->esq = y; else if(paiX->dir == x) paiX->dir = y; } else dicionario.raiz = y; // Filho direito de Y -> muda pai if(filhoEsqY != nullptr) filhoEsqY->pai = x; // X -> muda pai e muda filho direito if(x != nullptr) x->pai = y; if(x != nullptr) x->dir = filhoEsqY; // Y -> muda pai e muda filho esquerdo if(y != nullptr) y->pai = paiX; if(y != nullptr) y->esq = x; //Atualizando alturas if(y !=nullptr) y->h = max(height(y->esq), height(y->dir)) + 1; if(x != nullptr) x->h = max(height(x->esq), height(x->dir)) + 1; return y; } // Realiza a rotação a Direita de um nó, e muda o nó do dicionário se o pai desse nó for nulo (ser a raiz) Noh* rotationRight(DicAVL &dicionario, Noh *y){ Noh* paiY = y->pai; Noh* x = y->esq; Noh* filhoDirX = x->dir; // Ponteiro de PaiY -> muda filho do lugar de Y if(paiY != nullptr){ // Atualizando ponteiro do filho do pai de Y para no lugar de y ser x if(paiY->esq == y) paiY->esq = x; else if(paiY->dir == y) paiY->dir = x; } else dicionario.raiz = x; // Filho direito de Y -> muda pai if(filhoDirX != nullptr) filhoDirX->pai = y; // X -> muda pai e muda filho direito if(x != nullptr) x->pai = paiY; if(x != nullptr) x->dir = y; // Y é agora filho direito de y // Y -> muda pai e muda filho esquerdo if(y != nullptr) y->pai = x; // X agora é o pai de y if(y != nullptr) y->esq = filhoDirX; // Filho Direito de X agora vira filho Esquerdo de Y //Atualizando alturas if(y!=nullptr) y->h = max(height(y->esq), height(y->dir)) + 1; if(x!= nullptr) x->h = max(height(x->esq), height(x->dir)) + 1; return x; } // Retorna um ponteiro para o nó da chave procurada, ou nulo se a chave não estiver em D. Noh* procurar(DicAVL &D, TC c){ Noh* no = D.raiz; while(no != nullptr){ TC chave = no->chave; if(chave == c) return no; else if(chave > c) no = no->esq; else if(chave < c) no = no->dir; } cout << "Chave "<< c <<" nao encontrado!" << endl; return nullptr; } // Atualiza as alturas sucessivamente dos pais até chegar a raiz void atualizarAlturas(Noh* no){ if(no != nullptr) return; no->h = max(height(no->esq), height(no->dir)) + 1; atualizarAlturas(no->pai); } // Retorna um ponteiro para o novo nó ou nulo se erro de alocação Noh* inserir(DicAVL &D, TC c, TV v){ cout << "Insercao da chave: " << c << " : " << v << endl; // procurar no Noh* noBusca = D.raiz; while(noBusca != nullptr){ TC chave = noBusca->chave; if(chave == c) break; else if(chave > c) noBusca = noBusca->esq; else if(chave < c) noBusca = noBusca->dir; } if(noBusca != nullptr){ cout << "No com chave = " << c << " ja existente!" << endl; return nullptr; } Noh* novoNo = newNo(c, v, 1); Noh* root = D.raiz; Noh* noAnterior = nullptr; bool ladoAdicionado = true; // true -> lado esquerdo & false -> lado direito // caso a. Raiz nula => raiz é o nó if(root == nullptr){ D.raiz = novoNo; return novoNo; } // caso b. Raiz não nula => Insere e realiza balanceamento // Pega o nó a quem vou adicionar o novo nó while(root != nullptr){ noAnterior = root; if(c < root->chave)root = root->esq; else if(c > root->chave) root = root->dir; } // cout << "CHAVE NOANT" << noAnterior->chave << "NOANT->h" << noAnterior->h << endl << endl; root = noAnterior; // Ajuste de ponteiros de pai novoNo->pai = root; // Insere novo nó if(c < root->chave) root->esq = novoNo; else if(c > root->chave) root->dir = novoNo; // Propagando o +1 nas alturas dos nós posteriores ao inserido e balanceando a árvore (caso esteja desbalanceada) do { root->h = max(height(root->esq), height(root->dir)) + 1; int balance = getBalance(root); if(balance > 1 && c < root->esq->chave) root = rotationRight(D, root); // Left Left Case else if(balance < -1 && c > root->dir->chave) root = rotationLeft(D, root); // Right Right Case else if(balance > 1 && c > root->esq->chave){ // Left Right Case root->esq = rotationLeft(D, root->esq); root = rotationRight(D, root); }else if(balance < -1 && c < root->dir->chave){ // Right Left Case root->dir = rotationRight(D, root->dir); root = rotationLeft(D, root); } root->h = max(height(root->esq), height(root->dir)) + 1; root = root->pai; } while(root != nullptr); return novoNo; } // Retorna o nó posterior ao nó passado (que será o sucessor do nó) Noh* minNode(Noh* no){ Noh* corrente = no; while(corrente->esq != nullptr) corrente = corrente->esq; return corrente; } // n aponta para o nó a ser removido void remover(DicAVL &D, Noh *n){ if(n == nullptr) return; cout << "REMOCAO do no com chave: " << n->chave << endl; int balance; // se a raiz for nula.. nada a remover if(D.raiz == nullptr) return; // Verificando se o nó realmente pertence ao dicionário n = procurar(D, n->chave); if(n == nullptr) return; Noh* paiN = n->pai; bool alterouAltura = false; // Caso base a: é a raiz da árvore ou é um nó que tem apenas uma subarv DE 1 FOLHA esquerda ou direita if(n->esq != nullptr && n->dir == nullptr){ // nó n com 1 filho esquerdo if(paiN == nullptr) { // n é a raiz D.raiz = n->esq; n->esq->pai = nullptr; } else { // nó n é um nó qualquer // Reatribuição de pai ao filho esq de N e o filho esq de N toma o lugar dele no pai dele n->esq->pai = paiN; if(paiN->esq != nullptr && paiN->esq->chave == n->chave) paiN->esq = n->esq; else if(paiN->dir != nullptr && paiN->dir->chave == n->chave) paiN->dir = n->esq; alterouAltura = true; // tem de alterar a altura do pai de N } } else if(n->dir != nullptr && n->esq == nullptr){ // nó n com 1 filho direito if(paiN == nullptr) { // n é a raiz D.raiz = n->dir; n->dir->pai = nullptr; } else { // nó n é um nó qualquer // Reatribuição de pai ao filho dir de N e o filho dir de N toma o lugar dele no pai dele n->dir->pai = paiN; if(paiN->esq != nullptr && paiN->esq->chave == n->chave) paiN->esq = n->dir; else if(paiN->dir != nullptr && paiN->dir->chave == n->chave) paiN->dir = n->dir; alterouAltura = true; // tem de alterar a altura do pai de N } } else if(isLeaf(n)){ // n é um nó folha if(paiN == nullptr) D.raiz = nullptr; // n é o nó raiz else { // n é um nó qualquer na árvore if(paiN->esq != nullptr && paiN->esq->chave == n->chave) paiN->esq = nullptr; else if(paiN->dir != nullptr && paiN->dir->chave == n->chave) paiN->dir = nullptr; alterouAltura = true; // tem de alterar a altura do pai de N } } else { // nó com 2 filhos // botar esse nó TEMP no lugar do n Noh* temp = minNode(n->dir); // Pega o próximo nó que é maior que é folha Noh* paiTemp = temp->pai; // Inicio das modificações necessárias de ponteiros: Terei de mexer em 5 nós // TEMP: atualizar seu pai e seus filhos // FILHO ESQ e DIR de N -> atualizar o seu pai para TEMP // PAI DE N -> atualizar seu filho n para temp // PAI DE TEMP -> zerar o ponteiro pro seu filho esquerdo // FILHOS DE N // 1o: Atualiza filhos de n pro pai deles agora ser temp n->esq->pai = temp; temp->esq = n->esq; if(n->dir != temp){ temp->dir = n->dir; n->dir->pai = temp; } else{ temp->dir = nullptr; n->dir->pai = paiN; // mas isso meio que é duplicado na linha 276 } // PAI DE TEMP // 2o atribuir ao pai de temp que o filho que era tempp agr é nullptr if(paiTemp != nullptr) paiTemp->esq = nullptr; // PAI DE N = atribuição de filho do PAIN agora pra ser temp e atribuição do novo pai de temp temp->pai = paiN; if(paiN != nullptr){ // vendo qual filho n era do pai dele: se era esq ou direito if(paiN->esq == n) paiN->esq = temp; else if(paiN->dir == n) paiN->dir = temp; } else D.raiz = temp; // mudar altura do pai de temp if(paiTemp && paiTemp != n) paiN = paiTemp; else paiN = temp; alterouAltura = true; } delete(n); if(alterouAltura){ do { paiN->h = 1 + max(height(paiN->esq), height(paiN->dir)); balance = getBalance(paiN); if(balance > 1 && getBalance(paiN->esq) >= 0) paiN = rotationRight(D, paiN); //Left Left Case else if(balance < -1 && getBalance(paiN->dir) <= 0) paiN = rotationLeft(D, paiN); // Right Right Case else if(balance > 1 && getBalance(paiN->esq) < 0){ // Left Right Case paiN->esq = rotationLeft(D, paiN->esq); paiN = rotationRight(D, paiN); } else if(balance < -1 && getBalance(paiN->dir) > 0){ // Right Left Case paiN->dir = rotationRight(D, paiN->dir); paiN = rotationLeft(D, paiN); } paiN->h = 1 + max(height(paiN->esq), height(paiN->dir)); paiN = paiN->pai; } while(paiN != nullptr); } } void desalloc(Noh* node){ if(node == nullptr) return; desalloc(node->esq); desalloc(node->dir); cout << "No desalocado: " << node->chave << endl; delete(node); } // Desaloca os nós da árvore. void terminar (DicAVL &D){ // acessar a raiz do dicionario e visitar em pré-ordem desalocando os nós Noh* no = D.raiz; desalloc(no); D.raiz = nullptr; }
true
e7b4d0159e486bdfe9767c1068bc096f06587e43
C++
yuna16/Leetcode
/274.cpp
UTF-8
720
3.40625
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> using namespace std; class Solution { public: int hIndex(vector<int>& citations) { int N = citations.size(); int low = 0; int high = N; int h = 0; while (low < high) { int mid = low + ((high - low) >> 1); if (citations[mid] >(N - mid)) { h = this->max(h, (N - mid)); high = mid; } else { h = this->max(h, citations[mid]); low = mid + 1; } } return h; } private: int min(int a, int b) { return a < b ? a : b; } int max(int a, int b) { return a > b ? a : b; } }; int main() { Solution sol; vector<int> data; data.push_back(0); cout << sol.hIndex(data) << endl; system("pause"); return 0; }
true
53db4b375e50bf9d2a260831af92a670246cb219
C++
Mamun3058/Programming
/uva11764.cpp
UTF-8
568
2.640625
3
[]
no_license
#include<iostream> using namespace std; int main() { int t,i,n,temp=0,coun=0; cin>>t; for(i=1;i<=t;i++) { cin>>n; int arra[n]; arra[0]=-99; for(int j=1;j<=n;j++) { cin>>arra[j]; if(arra[j-1]<arra[j]) { temp++; } else if(arra[j-1]>arra[j]) { coun++; } } cout<<"case "<<i<<": "<<temp-1<<" "<<coun<<endl; temp=0; coun=0; } return 0; }
true
16658827e145572a5507114b19b122a4540dfdd9
C++
Bluemi/visualizer
/src/entity/creation/Creation.cpp
UTF-8
1,641
2.8125
3
[]
no_license
#include "Creation.hpp" #include <vector> #include "../Movable.hpp" #include "../../shape/ShapeInitializer.hpp" namespace visualizer { Creation::Creation(const ShapeGenerator& shape, const std::string& group) : _quantity(0), _position(), _size(glm::vec3(1.f, 1.f, 1.f)), _shape(shape), _group(group) {} Creation& Creation::with_quantity(const NumberGenerator<unsigned int>& quantity) { _quantity = quantity; return *this; } Creation& Creation::with_position(const VectorGenerator& position) { _position = position; return *this; } Creation& Creation::with_size(const VectorGenerator& size) { _size = size; return *this; } Creation& Creation::with_velocity(const VectorGenerator& velocity) { _velocity = velocity; return *this; } Creation& Creation::with_color(const VectorGenerator& color) { _color = color; return *this; } Creation& Creation::with_tag(const std::string& tag) { _tags.push_back(tag); return *this; } Creation& Creation::with_shape(const ShapeGenerator& shape) { _shape = shape; return *this; } Creation& Creation::with_group(const std::string& group) { _group = group; return *this; } std::pair<std::string, std::vector<Movable>> Creation::create() const { unsigned int quantity = _quantity.get(); std::vector<Movable> movables; movables.reserve(quantity); for (unsigned int i = 0; i < quantity; i++) { Movable m(_shape.get()); m.set_position(_position.get()); m.set_size(_size.get()); m.set_velocity(_velocity.get()); m.set_color(_color.get()); m.set_tags(_tags); movables.push_back(m); } return {_group, movables}; } }
true
3198dff168a52ac4946342cfce32456c0bed20e0
C++
scasta31/LuminitySensor
/src/sensors/sensor.h
UTF-8
988
3.15625
3
[ "MIT" ]
permissive
#ifndef SENSOR_H #define SENSOR_H #include <Arduino.h> #include <sensors/read.h> template<class T> class SensorABC { public: SensorABC(uint8_t id); bool hasChanged(); Read<T> getValue(); uint8_t getId(); void excecute(); private: bool changed; T raw_value; Read<T> value; uint8_t id; virtual T read(); }; template<class T> SensorABC<T>::SensorABC(uint8_t id){ this->id = id; } template<class T> Read<T> SensorABC<T>::getValue(){ this->changed = false; return this->value; } template<class T> uint8_t SensorABC<T>::getId(){ return this->value; } template<class T> bool SensorABC<T>::hasChanged(){ return this->changed; } template<class T> void SensorABC<T>::excecute(){ T new_value = this->read(); if(new_value != this->raw_value){ this->changed = true; this->raw_value = new_value; this->value = Read<T>(new_value, this->id); } } #endif
true
54939b462212038ddb1d6fccdacd67205fd8ca17
C++
colbrydi/cpp_params
/parameterTest.cpp
UTF-8
1,067
2.859375
3
[]
no_license
#include "parameter.h" #include <vector> int main(int argc, char *argv[]) { int test = 0; std::cout << "Testing = " << test << std::endl; std::vector<paramBase *> params; param <int> op(&test); op.name = "bob"; op.alias = "b"; params.push_back((paramBase *) &op); //op.assign(2); std::cout << "Testing = " << test << std::endl; op.print(); std::cout << "Setting up simulation parametersd " << argc << std::endl; int i=1; while(i < argc) { std::string arg (argv[i]); std::cout << "testing " << arg << std::endl; if( arg == "-"+op.name || arg == "-"+op.alias ) { std::cout << "found " << op.name << std::endl; i++; if(i >= argc) { printf("ERROR - Incorrect input arguments %s\n", arg.c_str()); return 1; } op.assign(argv[i]); } i++; } std::cout << "Testing = " << test << std::endl; //if(test != 2) // return 1; return 0; }
true
5af51c07c91366bcebaaf80c637ab6e9099021cb
C++
zhangwengame/LeetCode
/210.cpp
UTF-8
993
2.8125
3
[]
no_license
class Solution { public: vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) { map<int,vector<int>> edge; vector<int> indegree(numCourses,0); vector<int> ret; queue<int> topQueue; for (int i=0;i<prerequisites.size();i++){ edge[prerequisites[i].second].push_back(prerequisites[i].first); indegree[prerequisites[i].first]++; } for (int i=0;i<numCourses;i++) if (indegree[i]==0) topQueue.push(i); while (!topQueue.empty()){ int now=topQueue.front(); topQueue.pop(); ret.push_back(now); for (int i=0;i<edge[now].size();i++) { indegree[edge[now][i]]--; if (indegree[edge[now][i]]==0) topQueue.push(edge[now][i]); } } if (ret.size()!=numCourses) return vector<int>(); else return ret; } };
true
8ea944cba55ba77c17a545887479332165242b69
C++
YoneTestOrganization/TestRepository
/DX9Sample022S(Vertex3D)/DX9Sample022/Camera.cpp
SHIFT_JIS
2,545
2.984375
3
[]
no_license
#include "Camera.h" // B̃CX^X CCamera* CCamera::m_pInstance = NULL; // RXgN^ CCamera::CCamera(LPDIRECT3DDEVICE9 pd3dDevice) { m_pd3dDevice = pd3dDevice; m_vViewAngle = D3DXVECTOR3(0.0f, 0.0f, 0.0f); } // fXgN^ CCamera::~CCamera() { } // void CCamera::Create(LPDIRECT3DDEVICE9 pd3dDevice) { if ( ! m_pInstance) m_pInstance = new CCamera(pd3dDevice); } // j void CCamera::Destroy() { SAFE_DELETE( m_pInstance ); } // j // Jw // _ void CCamera::SetCamera(D3DXVECTOR3 vPosition) { // -------- r[ϊ@------- D3DXVECTOR3 vBaseEyePt( 0.0f, 0.0f, -10.0f ); // J̊ʒu D3DXVECTOR3 vEyePt; // J̈ʒu D3DXVECTOR3 vLookatPt ( 0.0f, 0.0f, 0.0f ); // J̒_ D3DXVECTOR3 vUpVec ( 0.0f, 1.0f, 0.0f ); // J̏ D3DXMATRIX matRotation; // ] // --- ]ړ --- D3DXMatrixRotationYawPitchRoll( &matRotation, // Zʂłsւ̃|C^ m_vViewAngle.y, // Y𒆐SƂ郈[(WAP) m_vViewAngle.x, // X𒆐SƂsb`(WAP) m_vViewAngle.z); // Z𒆐SƂ郍[(WAP) D3DXVec3TransformCoord( &vEyePt, // ZʂłxNgւ̃|C^ &vBaseEyePt, // Rs[ɂȂxNgւ̃|C^ &matRotation // Z̍sւ̃|C^ ); // ړ vEyePt += vPosition; vLookatPt = vPosition; D3DXMATRIX matView; // r[s // Wnr[s쐬 D3DXMatrixLookAtLH( &matView, // Zʂłsւ̃AhXw &vEyePt, // _`xNgւ̃AhXw &vLookatPt, // _`xNgւ̃AhXw &vUpVec ); // `xNgւ̃AhXw m_matView = matView; // ---------------------------- // --------- ˉeϊ --------- D3DXMATRIX matProjection; // ˉes // Wnߎˉes쐬 D3DXMatrixPerspectiveFovLH( &matProjection, // Zʂłsւ̃AhXw D3DX_PI / 4, // Y̎(WAP:45) 800.0f / 600.0f,// AXyNg(/)w // foCX擾悤 1.0f, // ߂r[ʂZl 2000.0f ); // r[ʂZl m_matProjection = matProjection; }
true
9eeba034ae6822e662577a1e3cb62e4aaee60a28
C++
zhaoshin/everything
/Everything/sort.cpp
UTF-8
6,234
3.5625
4
[]
no_license
// // sort.cpp // Everything // // Created by Zhao, Xing on 3/19/15. // Copyright (c) 2015 Zhao, Xing. All rights reserved. // #include <stdio.h> // number of occurence // frequence of occurence /* if x is present in arr[] then returns the index of FIRST occurrence of x in arr[0..n-1], otherwise returns -1 */ int first(int arr[], int low, int high, int x, int n) { if(high >= low) { int mid = (low + high)/2; /*low + (high - low)/2;*/ if( ( mid == 0 || arr[mid] > arr[mid-1]) && arr[mid] == x) return mid; else if(x > arr[mid]) return first(arr, (mid + 1), high, x, n); else return first(arr, low, (mid -1), x, n); } return -1; } /* if x is present in arr[] then returns the index of LAST occurrence of x in arr[0..n-1], otherwise returns -1 */ int last(int arr[], int low, int high, int x, int n) { if(high >= low) { int mid = (low + high)/2; /*low + (high - low)/2;*/ if( ( mid == n-1 || arr[mid] < arr[mid+1]) && arr[mid] == x ) return mid; else if(x < arr[mid]) return last(arr, low, (mid -1), x, n); else return last(arr, (mid + 1), high, x, n); } return -1; } /* if x is present in arr[] then returns the count of occurrences of x, otherwise returns -1. */ int count(int arr[], int x, int n) { int i; // index of first occurrence of x in arr[0..n-1] int j; // index of last occurrence of x in arr[0..n-1] /* get the index of first occurrence of x */ i = first(arr, 0, n-1, x, n); /* If x doesn't exist in arr[] then return -1 */ if(i == -1) return i; /* Else get the index of last occurrence of x. Note that we are only looking in the subarray after first occurrence */ j = last(arr, i, n-1, x, n); /* return count */ return j-i+1; } int rotated_binary_search(int A[], int N, int key) { int L = 0; int R = N - 1; while (L <= R) { // Avoid overflow, same as M=(L+R)/2 int M = L + ((R - L) / 2); if (A[M] == key) return M; // the bottom half is sorted if (A[L] <= A[M]) { if (A[L] <= key && key < A[M]) R = M - 1; else L = M + 1; } // the upper half is sorted else { if (A[M] < key && key <= A[R]) L = M + 1; else R = M - 1; } } return -1; } // pivot void swap(int& a, int& b) { a -= b; b += a;// b gets the original value of a a = (b - a);// a gets the original value of b } int pivot(int a[], int first, int last) { int p = first; int pivotElement = a[first]; for (int i = first + 1; i <= last; i++) { if (a[i] <= pivotElement) { p++; swap(a[i], a[p]); } } swap(a[p], a[first]); return p; } // select the kth number // quick select // kth largest // kth smallest int quick_select(int a[], int l, int r, int k) { if (l == r) { return a[l]; } int j = pivot(a, l, r); int length = j - l + 1; if (length == k) { return a[j]; } else if (k < length) { return quick_select(a, l, j - 1, k); } else { return quick_select(a, j + 1, r, k - length); } } void quickSort( int a[], int first, int last ) { int pivotElement; if(first < last) { pivotElement = pivot(a, first, last); quickSort(a, first, pivotElement-1); quickSort(a, pivotElement+1, last); } } #define RANGE 255 // pigeon // radix void countSort(int *a, int size) { int output[size]; int count[RANGE + 1] = {0}; for (int i = 0; i < size; i++) { count[a[i]]++; } for (int i = 1; i <= RANGE; i++) count[i] += count[i-1]; for (int i = 0; i < size; i++) { output[count[a[i]] - 1] = a[i]; count[a[i]]--; } for (int i = 0; i < size; i++) { a[i] = output[i]; } } void merge(int array[], int low, int mid, int high, int &res) { int i, j, k, c[100]; i = low; k = low; j = mid + 1; while (i <= mid && j <= high) { if (array[i]<array[j]) { c[k] = array[i]; k++; i++; } else { res += mid - low + 1; c[k] = array[j]; k++; j++; } } while (i <= mid) { c[k] = array[i]; k++; i++; } while (j <= high) { c[k] = array[j]; k++; j++; } for (i = low; i <= high; i++) { array[i] = c[i]; } } void my_merge_sort(int array[], int low, int high, int &res) { int mid; if (low < high) { mid = (low + high) / 2; my_merge_sort(array, low, mid, res); my_merge_sort(array, mid+1, high, res); merge(array, low, mid, high, res); } } // Heap sort // heapsort // maintain heap relationship for the triangle from low to high void shiftRight(int *arr, int low, int high) { int root = low; while (root * 2 + 1 <= high) { int leftChild = root * 2 + 1; int rightChild = leftChild + 1; int swapIndex = root; if (arr[swapIndex] < arr[leftChild]) { swapIndex = leftChild; } if (rightChild <= high && arr[swapIndex] < arr[rightChild]) { swapIndex = rightChild; } if (swapIndex != root) { swap(arr[root], arr[swapIndex]); root = swapIndex; } else { break; } } } // create heap structure // call shiftRigth from last triangle to the first triangle void heapify(int *arr, int low, int high) { int mid = low + (high - low)/2; while (mid >= 0) { shiftRight(arr, mid, high); mid --; } } // heapsort void heapSort(int *arr, int size) { heapify(arr, 0, size-1); int high = size - 1; while (high > 0) { swap(arr[high], arr[0]); high -- ; shiftRight(arr, 0, high); } }
true
ecf6827fde6762d83775f1f394b66264b4612147
C++
Cynwise/assignment7
/dvd.cc
UTF-8
2,014
3.3125
3
[]
no_license
//************************************* // // DVD class implementation file // // Corey Farnsworth // 07/07/18 // CS2401 Summer '18 // //************************************* #include "dvd.h" using namespace std; void Dvd::input(std::istream& ins){ char junk; ins.get(junk); if(&ins == &cin){ cout << "Enter movie title: "; } getline(cin, title); if(ins.eof())cout << "eof\n"; if(&ins == &cin){ cout << "Enter movie year: "; } ins >> year; if(&ins == &cin){ cout << "Enter movie run time: "; } ins >> run_time; ins.get(junk); if(&ins == &cin){ cout << "Enter movie type: "; } getline(cin, movie_type); if(ins.eof())cout << "eof\n"; do{ cout << "Enter a valid movie rating: "; getline(cin, rating); }while(rating != "G" && rating != "PG-13" && rating != "R" && rating != "X"); cout << endl; } void Dvd::output(std::ostream& outs)const{ if(&outs == &cout){ outs << "title: " << title << endl; outs << "year: " << year << endl; outs << "run time (in minutes): " << run_time << endl; outs << "movie type: " << movie_type << endl; outs << "rating: " << rating << endl << endl; } else{ outs << title << endl; outs << year << endl; outs << run_time << endl; outs << movie_type << endl; outs << rating << endl; } } string Dvd::get_title()const{ return title; } int Dvd::get_year()const{ return year; } int Dvd::get_run_time()const{ return run_time; } string Dvd::get_movie_type()const{ return movie_type; } string Dvd::get_rating()const{ return rating; } void Dvd::set_title(string t){ title = t; } void Dvd::set_year(int y){ year = y; } void Dvd::set_run_time(int rt){ run_time = rt; } void Dvd::set_movie_type(string mt){ movie_type = mt; } void Dvd::set_rating(string r){ rating = r; } std::ostream& operator <<(std::ostream& outs, const Dvd& dvd1){ dvd1.output(outs); return outs; } std::istream& operator >> (std::istream& ins, Dvd& dvd1){ dvd1.input(ins); return ins; }
true
ded9c51371a4595faaf7ac9f46d10e412df091ff
C++
greenfox-zerda-sparta/wekkew
/07week/2day/rpgGame/rpgGame/Skeleton.cpp
UTF-8
574
2.84375
3
[]
no_license
#include "Skeleton.h" Skeleton::Skeleton(vector<vector<int>>& victor) { posX = rand() % 8 + 1; posY = rand() % 8 + 1; while (victor[posY][posX] != 1) { posX = rand() % 9 + 1; posY = rand() % 9 + 1; } victor[posY][posX] = 2; /* 0 wall | 1 floor | 2 skeleton */ this->HealthPoint = 2 * (rand() % 6 + 1); this->DefensePoint = 2 * (rand() % 6 + 1); this->StrikePoint = rand() % 6 + 1; this->picName = "skeleton.bmp"; cout << "Skeleton HP: " << HealthPoint << ", DP: " << DefensePoint << ", SP: " << StrikePoint << endl; } Skeleton::~Skeleton() { }
true
47bba301aca7dbb53b957250b9f5ca3f0ed79ee0
C++
Anubhav2907/DSA
/LinkedList/hiren.cpp
UTF-8
633
2.984375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; struct Node{ int data; Node *next; Node(int x){ data=x; next=NULL; } }; Node *isLoop(Node *head){ Node *temp = new Node(0); Node *curr = head; Node *start = head; Node *next = head; while(curr!=NULL){ if(curr->next==temp){ while(start != curr) { next = start; start = start->next; delete next; } break; } Node *curr_next = curr->next; curr->next=temp; curr = curr_next; } return curr; }
true
7d70f4f0a29398584d5802f199c3a1953bca04aa
C++
teimeikichengmingchi/progrmming-contest
/uva/uva10044.cpp
UTF-8
4,038
2.65625
3
[]
no_license
#include <cstdio> #include <cstring> #include <iostream> #include <map> #include <vector> #include <queue> using namespace std; int main(){ int all_sen = 0, count_sen = 0; cin >> all_sen; char s[512]; while(all_sen--){ count_sen++; int lines, ques; cin >> lines >> ques; cin.getline(s, 512);//, '\n'); map<string, int> name_number; map<string, int>::iterator map_iter; int name_start_pos = 0; name_number["Erdos, P."] = 0; int curr_size = 1; vector<int> graph[4096]; while(lines--){ vector<int> author_list; cin.getline(s, 512);// '\n'); //cout << s << endl; name_start_pos = 0; for(int i = 0; ; i++){ if(s[i] == ',' && s[i - 1] == '.'){ s[i] = '\0'; map_iter = name_number.find(s + name_start_pos); if(map_iter == name_number.end()){ //cout << s + name_start_pos << " : " << curr_size << endl; name_number[s + name_start_pos] = curr_size; author_list.push_back(curr_size); curr_size++; } else{ //cout << map_iter -> first << " : " << map_iter -> second << endl; author_list.push_back(map_iter -> second); } name_start_pos = i + 2; } else if(s[i] == ':'){ s[i] = '\0'; map_iter = name_number.find(s + name_start_pos); if(map_iter == name_number.end()){ //cout << s + name_start_pos << " : " << curr_size << endl; name_number[s + name_start_pos] = curr_size; author_list.push_back(curr_size); curr_size++; } else{ //cout << map_iter -> first << " : " << map_iter -> second << endl; author_list.push_back(map_iter -> second); } break; } } for(vector<int>::iterator v_iter = author_list.begin(); v_iter != author_list.end(); v_iter++){ for(vector<int>::iterator v_iter2 = author_list.begin(); v_iter2 != author_list.end(); v_iter2++){ if(*v_iter2 != *v_iter){ graph[*v_iter].push_back(*v_iter2); } } } } queue<int> traverse; int visted[4096] = {}; int erdos[4096] = {}; traverse.push(0); int curr_erdos_num = 0; erdos[0] = -1; while(!traverse.empty()){ curr_erdos_num++; for(vector<int>::iterator v_iter = graph[traverse.front()].begin(); v_iter != graph[traverse.front()].end(); v_iter++){ if(erdos[*v_iter] == 0){ traverse.push(*v_iter); erdos[*v_iter] = curr_erdos_num; } } traverse.pop(); } cout << "Scenario " << count_sen << endl; while(ques--){ cin.getline(s, 512);//, '\n'); cout << s << " "; int tempI = -1; if(name_number.find(s) != name_number.end()) tempI = name_number[s]; //cout << tempI << " : "; if(erdos[tempI] == -1){ if(!strcmp(s, "Erdos, P.")) cout << "0" << endl; else cout << "infinity" << endl; } else if(erdos[tempI] == 0){ cout << "infinity" << endl; } else{ cout << erdos[tempI] << endl; } } } return 0; }
true
93a3af0d54a21e0c70e27334797b429a985de8d9
C++
tom-biskupic/LabPSU
/Firmware/LabPSU/CommandInterpreter.cpp
UTF-8
2,687
2.890625
3
[]
no_license
/* * CommandInterpreter.cpp * * Created: 19/07/2015 1:29:08 AM * Author: tom */ #include "CommandInterpreter.h" #include "VoltageSetCommand.h" #include "string.h" #include "stdio.h" namespace { const int LINE_SIZE=50; const int PARAM_SIZE=40; const int COMMAND_SIZE=20; const char EQUALS = '='; const char *INVALID_SYNTAX = "Invalid syntax. Expected command=param\r\n"; const char *UNKNOWN_COMMAND_ERROR = "Invalid command\r\n"; } CommandInterpreter::CommandInterpreter(LabPSU *psu) : m_commandFactory(), m_psu(psu) { } void CommandInterpreter::processNextCommand() { char nextLine[LINE_SIZE]; readLine(nextLine,LINE_SIZE); if ( nextLine[0] != '\0' ) { // // Split the line into command and param // printf("%s\r\n",nextLine); char commandName[COMMAND_SIZE]; char param[PARAM_SIZE]; if ( parseLine(nextLine,commandName,param) ) { Command *commandHandler = m_commandFactory.getCommand(commandName); if ( commandHandler == NULL ) { printf(UNKNOWN_COMMAND_ERROR); return; } if ( param[0] == '?' ) { commandHandler->handleGetCommand(m_psu); } else { commandHandler->handleSetCommand(param,m_psu); } } } } bool CommandInterpreter::parseLine( char *line, char *command, char *param ) const { char *equalsPos = strchr(line,EQUALS); if ( equalsPos == NULL ) { printf(INVALID_SYNTAX); return false; } int commandLen = (int)(equalsPos-line); if ( commandLen == 0 || commandLen > COMMAND_SIZE ) { printf(INVALID_SYNTAX); return false; } int paramLen = strlen(line)-commandLen-1; if ( paramLen == 0 || paramLen > PARAM_SIZE ) { printf(INVALID_SYNTAX); return false; } memcpy(command,line,commandLen); command[commandLen]='\0'; memcpy(param,equalsPos+1,paramLen); param[paramLen] = '\0'; return true; } void CommandInterpreter::readLine( char *buffer, size_t bufferLen ) const { bool foundEnd=false; unsigned int nextPos = 0; while(!foundEnd && nextPos < bufferLen ) { char c = getchar(); if ( c == '\r' || c == '\n' ) { foundEnd = true; } else if ( c != '\0' ) { buffer[nextPos++] = c; } } buffer[nextPos]='\0'; }
true
dd74518adfee3799555eb49db409484475c9b2aa
C++
Mott1223/post
/Algorithm/Basic/update.cc
UTF-8
555
3.265625
3
[]
no_license
/****************************************************************** * Content: Just update a item in the array ******************************************************************/ #include <stdio.h> int main(){ int arr[] = {3, 5, 6, 9, -1}; int i = 0, n = 5; int item = 55, j = 4; printf("arr is:\n"); for(i = 0; i < n; ++i){ printf("arr[%d]:%d\n", i, arr[i]); } if(j < n){ arr[j] = item; } printf("update arr is:\n"); for(i = 0; i < n; ++i){ printf("arr[%d]:%d\n", i, arr[i]); } }
true
52d21dddcac3bc08ab93f8f93c33c4e78f543fcd
C++
lsqyling/PrimerAdvanced
/part_3_classdesignertool/TextQuery.cpp
UTF-8
2,442
2.828125
3
[ "CC0-1.0" ]
permissive
// // Created by shiqing on 19-5-10. // #include <fstream> #include <sstream> #include "TextQuery.h" namespace query { std::map<string, int> TextQuery::wordCounts_; std::shared_ptr<vector<string>> TextQuery::lines_{std::make_shared<vector<string>>()}; std::shared_ptr<std::map<string, std::set<int>>> TextQuery::keyToLineNos_{ std::make_shared<std::map<string, std::set<int>>>()}; TextQuery::TextQuery(const string &file) { if (!wordCounts_.empty()) return; init(file); } void TextQuery::init(const string &file) { std::ifstream ifs(file, std::ifstream::in); if (ifs) { int lineNo = 0; string line, word; while (getline(ifs, line)) { ++lineNo; lines_->push_back(line); std::istringstream iss(line); while (iss >> word) { ++wordCounts_[word]; (*keyToLineNos_)[word].insert(lineNo); } } } } QueryResult TextQuery::query(string keyWord) const { auto it = keyToLineNos_->find(keyWord); if (it != keyToLineNos_->end()) { return QueryResult(lines_, std::make_shared<std::set<int>>(it->second), wordCounts_[keyWord]); } return QueryResult(); } std::ostream &query::operator<<(std::ostream &os, const QueryResult &rq) { for (const auto &n : *rq.getLineNoSet()) { os << "(line " << n << ")\t" << (*rq.getFileLines())[n - 1] << "\n"; } return os; } void runQueries() { TextQuery tq("../../part_3_classdesignertool/a little story"); while (true) { cout << "Please enter the key words that you want to query: " << endl; string expression; while (!getline(cin, expression) || expression.empty()); Convert convert(expression); Query q = convert.convertToQuery(); QueryResult result = q.eval(tq); cout << "Executing Query for: " << q.rep() << "\n\n" << q.rep() << " occurs " << result.getTimes() << " " << makePlural("time", "s", result.getTimes()) << "\n" << result << endl; cout << "please continue yes or no ?" << endl; string s; if (cin >> s && (s.size() == 2 && s[0] == 'n')) break; } } }
true
ed671594613433e8b3e36604da0b9843d8b4c293
C++
aurelien-brabant/ft_containers
/test/map/copy.test.cpp
UTF-8
1,730
3.265625
3
[]
no_license
#include "map_testing.hpp" TEST(test_map_assignment_operator) { map<unsigned, unsigned> m; unsigned baseN = 1000000; for (unsigned i = 0; i != baseN; ++i) { m.insert(FT_CONTAINER::make_pair(i, i)); } map<unsigned, unsigned> mCopy = m, *mptr = &mCopy; // test self-alignment mCopy = *mptr; p_assert_eq(mCopy.size(), m.size()); // ensure a deep copy has been performed for (map<unsigned, unsigned>::iterator it = m.begin(); it != m.end(); ++it) { it->second = 0; } size_t i = 0; for (map<unsigned, unsigned>::iterator it = mCopy.begin(); it != mCopy.end(); ++it) { p_assert_eq(it->second, i++); } p_assert_eq(i, baseN); return 0; } TEST(test_map_copy_constructor) { map<unsigned, unsigned> m; unsigned baseN = 1000000; for (unsigned i = 0; i != baseN; ++i) { m.insert(FT_CONTAINER::make_pair(i, i)); } map<unsigned, unsigned> mCopy(m); p_assert_eq(mCopy.size(), m.size()); // ensure a deep copy has been performed for (map<unsigned, unsigned>::iterator it = m.begin(); it != m.end(); ++it) { it->second = 0; } size_t i = 0; for (map<unsigned, unsigned>::iterator it = mCopy.begin(); it != mCopy.end(); ++it) { p_assert_eq(it->second, i++); } p_assert_eq(i, baseN); return 0; } TEST(test_map_copy_cleared) { map<unsigned, unsigned> m; for (unsigned i = 0; i != 42; ++i) { m.insert(FT_CONTAINER::make_pair(i, i)); } m.clear(); map<unsigned, unsigned> mCopy(m); p_assert_eq(mCopy.size(), 0); assert_expr(mCopy.begin() == mCopy.end()); return 0; }
true
2f37ff1259a9d1f9199045cfd6f69e8be327e6aa
C++
ajtopping/materia
/materia/gTreeNode.cpp
UTF-8
207
2.71875
3
[]
no_license
#include "gTreeNode.h" void gTreeNode::set_parent(gNode * new_parent) { parent_ = new_parent; } gNode * gTreeNode::get_parent() { return parent_; } void gTreeNode::clear_parent() { parent_ = nullptr; }
true
b22a825eab05e36d2534c43273fd82043a168c56
C++
avenatti/JPEGContentGuardISO10918
/guard/src/Config.cpp
UTF-8
4,323
3.15625
3
[]
no_license
/// @file Config.cpp /// /// @brief Implementation for Configuration class to parse configuration files. /// /// @author Michael W. Benson /// /// History: /// M. Benson 2/22/2020 Initial version. #include "Config.hpp" #include "logging.hpp" #include "utils.hpp" #include <sstream> #include <fstream> #include <algorithm> #include <experimental/filesystem> // Name spaces. using namespace std; namespace fs = std::experimental::filesystem; /// Constructor. /// @param[in] configFile Configuration file to parse. Config::Config (std::string& configFile) : m_file (configFile) { } /// Constructor (private). Config::Config () { } /// Destructor. Config::~Config () { } /// Parses the configuration file. /// @return true on success, false otherwise. bool Config::Parse () { bool result = false; string line; // Verify the config file exists. if (fs::exists (m_file) == true) { INFO_LOG ("Parsing configuration file \"" << m_file << "\"."); result = true; // Open the file as a string stream. ifstream infile (m_file.c_str ()); // Read in one line at a time and parse it. while (getline (infile, line)) ParseLine (line); // Ensure the image directory exists. if (fs::exists (m_settings.imageDir) == false) { ERR_LOG ("Image directory \"" << m_settings.imageDir << "\" doesn't exist"); result = false; } } else ERR_LOG ("Configuration (" << m_file << ") doesn't exist."); return (result); } /// Parses a configuration line of text. /// @param[in] line Text line to parse. /// @return void. void Config::ParseLine (string& line) { vector<string> tuples; string equalDelimiter = "="; // Prepare the string for tuple splitting. line.erase (remove (line.begin (), line.end (), ' '), line.end ()); line.erase (remove (line.begin (), line.end (), '\t'), line.end ()); // Split the line up into tuples. tuples = SplitStr (line, equalDelimiter); // Ensure there are exactly 2 tuples. if (tuples.size () == 2) { if (tuples[0].compare ("image-dir") == 0) { m_settings.imageDir = tuples[1]; } else if (tuples[0].compare ("accept-dir") == 0) { m_settings.acceptDir= tuples[1]; } else if (tuples[0].compare ("drop-dir") == 0) { m_settings.dropDir = tuples[1]; } else if (tuples[0].compare ("sequential-dct-mode") == 0) { if (tuples[1].compare ("enable") == 0) m_settings.sequentialDctMode = true; } else if (tuples[0].compare ("progressive-dct-mode") == 0) { if (tuples[1].compare ("enable") == 0) m_settings.progressiveDctMode = true; } else if (tuples[0].compare ("lossless-mode") == 0) { if (tuples[1].compare ("enable") == 0) m_settings.losslessMode = true; } else if (tuples[0].compare ("hierarchical-mode") == 0) { if (tuples[1].compare ("enable") == 0) m_settings.hierarchicalMode = true; } else if (tuples[0].compare ("huffman-encoding") == 0) { if (tuples[1].compare ("enable") == 0) m_settings.huffmanEncoding = true; } else if (tuples[0].compare ("arithmetic-encoding") == 0) { if (tuples[1].compare ("enable") == 0) m_settings.arithmeticEncoding = true; } } else { ERR_LOG ("Invalid config line \"" << line << "\"."); ERR_LOG ("Size = " << tuples.size ()); } } /// Gets the current settings. /// @return a copy of the settings. Settings Config::GetSettings () { return (m_settings); } /// Logs the structure contents. /// @return void. void Settings::Log () { DEBUG_LOG ("Configuration settings:"); DEBUG_LOG (" imageDir = " << imageDir); DEBUG_LOG (" acceptDir = " << acceptDir); DEBUG_LOG (" dropDir = " << dropDir); DEBUG_LOG (" sequentialDctMode = " << sequentialDctMode); DEBUG_LOG (" progressiveDctMode = " << progressiveDctMode); DEBUG_LOG (" losslessMode = " << losslessMode); DEBUG_LOG (" hierarchicalMode = " << hierarchicalMode); DEBUG_LOG (" huffmanEncoding = " << huffmanEncoding); DEBUG_LOG (" arithmeticEncoding = " << arithmeticEncoding); }
true
dc305645496a2a0dace5fcbb6e467ae7e2e1a8dc
C++
PaulBeaudet/suspender
/suspenders.ino
UTF-8
4,864
2.890625
3
[ "MIT" ]
permissive
// suspenders.ino ~ Copyright 2018 Paul Beaudet ~ License MIT // Gives a computer ability to sleep for a period of time // Server gives a signal with a timeout durration to sleep, arduino wakes system with a key press on durration lapse #include <Keyboard.h> // Built in library for HID keyboard actions #include <JS_Timer.h> // library from - https://github.com/paulbeaudet/JS_Timer #include <Adafruit_CircuitPlayground.h> // Library of prebuild functions for a specfic arduino compatiple from adafruit #define LEFTBUTTON 4 #define RIGHTBUTTON 19 #define BOUNCETIME 5 #define HOLDSTATE 300 JS_Timer timer = JS_Timer(); // create an instance of our timer object from timer library void setup() { Keyboard.begin(); // allows to act as USB HID device Serial.begin(115200); // comunicate with server byte buttonArray[]= {LEFTBUTTON, RIGHTBUTTON}; for(byte whichPin=0; whichPin < sizeof(buttonArray); whichPin++){ pinMode(buttonArray[whichPin], INPUT); } pinMode(LED_BUILTIN, OUTPUT); // set up LED on pin 13 digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW } void loop() { static byte automatedTimeoutId = 0; // keep track of automated callbacks yet to fire for interuption timer.todoChecker(); // Runs continually to see if timer callback needs to be executed static bool pressed = false; // only gets set first interation of loop byte leftButtonPress = leftPressEvent(); if(leftButtonPress){ // logic to prevent continually actuating event while button is pressed if(!pressed){ // AKA yet to be pressed timer.clearTimeout(automatedTimeoutId); automatedTimeoutId = 0; interuptingWake(); pressed = true; } } else {pressed = false;} // wait until button is done being pressed before actuating event again int newTime = recieveNextTime(); if(newTime){ automatedTimeoutId = timer.setTimeout(regularWake, newTime); } } //======================= Functions ========================= #define CYCLE_TIME 8000 void regularWake(){ Keyboard.print(" "); // Send a keystroke any keystroke to wake machine up timer.setTimeout(keepOnKeepingOn, CYCLE_TIME); // signal this is an automated interuption } void interuptingWake(){ Keyboard.print(" "); // Send keystroke to potentially wake machine up timer.setTimeout(interupt, CYCLE_TIME); // Wait for resume and reconnection } void keepOnKeepingOn(){Serial.println("c");} void interupt(){Serial.println("i");} // Signal that a human wants to provide a base case that stops cycle of resets //======================== Serial Data Transfer (INTERFACE) #define START_MARKER '<' #define END_MARKER '>' int recieveNextTime(){ static String placeholder= ""; static boolean inProgress = false; // note if read started if(Serial.available()) { // is there anything to be read char readChar = Serial.read(); // yes? read it if(inProgress){ // did we read start maker? if(readChar == END_MARKER){ // did we read end marker inProgress = false; // note finished int result = placeholder.toInt(); // return int placeholder = ""; return result; } else { // given still in progress placeholder += readChar; // concat this char } } else if(readChar == START_MARKER){inProgress = true;} // indicate when to read when start marker is seen } return 0; // in the case the message has yet to be recieved } // checks for a debounced button press event // TODO needs to be modified to handle more than one button byte leftPressEvent() { // remove default value to use in main sketch static unsigned long pressTime = millis(); static boolean timingState = false; // low is a press with the pullup if(digitalRead(LEFTBUTTON) == HIGH){ // if the button has been pressed if(timingState) { // given timer has started if(millis() - pressTime > BOUNCETIME){ // check if bounce time has elapesed if(millis() - pressTime > HOLDSTATE){// case button held longer return state 2 return 2; // return hold state } return 1; // return debounced press state } return 0; // still in potential "bounce" window } timingState = true; // note that the timing state is set pressTime = millis(); // placemark when time press event started return 0; // return with the timestate placeholder set } // outside of eventcases given no reading timingState = false; // in case the timing state was set, unset return 0; // not pressed }
true
414e42c69b5432cd33d49059d95302a2597e090c
C++
jainans/My-Leetcode-Solution-In-CPP
/CPP, C++ Solutions/134. Gas Station.cpp
UTF-8
1,172
3.140625
3
[ "MIT" ]
permissive
// TC - O(N^2) // SC - O(1) /*************************************************************** class Solution { public: int canCompleteCircuit(vector<int>& gas, vector<int>& cost) { int n = gas.size(); for(int i = 0; i < n; i++) { int gasRem = gas[i] - cost[i]; int itr = (i+1)%n; while(gasRem >= 0 && itr != i) { gasRem += gas[itr]; gasRem -= cost[itr]; if(gasRem < 0) break; itr = (itr+1)%n; } if(itr == i && gasRem >= 0) return itr; } return -1; } }; *************************************************************/ // TC - O(N) // SC - O(1) class Solution { public: int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { int start = gas.size()-1; int end = 0; int sum = gas[start] - cost[start]; while(start > end) { if (sum >= 0) { sum += gas[end] - cost[end]; ++end; } else { --start; sum += gas[start] - cost[start]; } } return sum >= 0 ? start : -1; } };
true
e734d64f11d50c47461ec41e49f58c3f295d9ca9
C++
mihirgadwalkar/Cyber-Cafe-Management-System
/Computer.h
UTF-8
10,354
2.96875
3
[]
no_license
#include<iostream> #include <string.h> #include <fstream> #include<conio.h> #include<iomanip> void ComputerEntryfun(); using namespace std; class Computer_Entry { protected: char Computer_name[30]; char ip_Adress[12]; int memory; char processor_model[20]; char motherbordcomp[20]; char unique_code[20]; public: void getComputerData(); void showComputerData() const; void storeComputer(); void readComputerRecord(); bool searchComputerRecord(); void searchComputerRecordEntry(); void delComputerRecord(); void updateComputerRecord(); void ComputerEntryfun(); }; void Computer_Entry::getComputerData() { int count = 0; fflush(stdin); cout<<"Enter Computer Name : "; cin.getline(Computer_name,30); char copyname[30]; strcpy(copyname,Computer_name); //ip adress getip: cout<<"Enter IP Address of Computer : "; cin.getline(ip_Adress,12); for(int i = 0;i<strlen(ip_Adress);i++) { if(isdigit(ip_Adress[i]) || ip_Adress[i] == '.') continue; else { cout<<"\nIP address cannot have anything except digits and .\n"; goto getip; } } if(strlen(ip_Adress) < 4 || strlen(ip_Adress) > 12) { cout<<"\nInvalid IP !!!!! Re-Enter\n"; goto getip; } for(int i = 0; i < strlen(ip_Adress) ; i++) { if(ip_Adress[i] == '.') count++; } if(count < 2) { cout<<"\nIP address must have atleast two \".\" \n"; goto getip; } //ip adress checks finished char copyip[50]; strcpy(copyip,ip_Adress); while(1) { cout<<"Enter Computer Memory : "; cin>>memory; if(cin.good()) break; cin.clear(); cout<<"Invalid Memory ! Re-Enter"<<endl; cin.ignore(10,'\n'); } int copymem; copymem = memory; fflush(stdin); cout<<"Enter Processor Model : "; cin.getline(processor_model,20); char copympd[20]; strcpy(copympd,processor_model); cout<<"Enter Motherboard Company : "; cin.getline(motherbordcomp,20); char copycomp[20]; strcpy(copycomp,motherbordcomp); setcode: cout<<"Enter Unique Code for Computer : "; cin.getline(unique_code,20); char copycod[20]; strcpy(copycod,unique_code); ifstream chkcomp; chkcomp.open("Computer_Entry.dat",ios::in|ios::binary); if(chkcomp.fail()) goto out; chkcomp.read(reinterpret_cast<char*>(this),sizeof(*this)); while(!chkcomp.eof()) { if(!strcmp(copycod,unique_code)) { cout<<"Unique Code already exists\n "; goto setcode; } chkcomp.read(reinterpret_cast<char*>(this),sizeof(*this)); } out: strcpy(Computer_name,copyname); strcpy(ip_Adress,copyip); memory = copymem ; strcpy(processor_model,copympd); strcpy(motherbordcomp,copycomp); strcpy(unique_code,copycod); } void Computer_Entry::showComputerData() const { cout<<"Computer Name : "<<Computer_name<<endl; cout<<"Computer IP_Address : "<<ip_Adress<<endl; cout<<"Computer Memory : "<<memory<<" GB"<<endl; cout<<"computer Processor Model : "<<processor_model<<endl; cout<<"Computer Motherboard Company : "<<motherbordcomp<<endl; cout<<"Computer Unique Code : "<<unique_code<<endl; cout<<"_________________________________________"<<endl; } void Computer_Entry::storeComputer() { ofstream strcomp; strcomp.open("Computer_Entry.dat",ios::app|ios::binary); strcomp.write(reinterpret_cast<char*>(this),sizeof(*this)); strcomp.close(); cout<<"Data saved to external file successfully"; } void Computer_Entry::readComputerRecord() { ifstream readcomp; readcomp.open("Computer_Entry.dat",ios::in|ios::binary); if(readcomp.fail()) { cout<<"Error in opening file !, file not found "; return ; } cout<<"...........Computer Data from the file........."<<endl; readcomp.read(reinterpret_cast<char*>(this), sizeof(*this)); while(!readcomp.eof()) { showComputerData(); readcomp.read(reinterpret_cast<char*>(this), sizeof(*this)); } readcomp.close(); } void Computer_Entry::searchComputerRecordEntry() { fflush(stdin); char ip[20]; cout<<"Enter the unique code of Computer to search : "; cin.getline(ip,20); int count = 0; ifstream searcomp; searcomp.open("Computer_Entry.dat",ios::in|ios::binary); if(searcomp.fail()) { cout<<"Error in opening file !,file not found"; return; } searcomp.read(reinterpret_cast<char*>(this),sizeof(*this)); while(!searcomp.eof()) { if(!strcmp(ip,unique_code)) { showComputerData(); count++; return; } searcomp.read(reinterpret_cast<char*>(this),sizeof(*this)); } if(!count) { cout<<"There is no computer with this unique code "; return; } searcomp.close(); } bool Computer_Entry::searchComputerRecord() { fflush(stdin); char ip[20]; cout<<"Enter the unique code of Computer to search : "; cin.getline(ip,20); int count = 0; ifstream seeusecomp; seeusecomp.open("Using_comp.dat",ios::binary); if(seeusecomp.fail()) { goto seeout; } seeusecomp.read(reinterpret_cast<char*>(this), sizeof(*this)); while(!seeusecomp.eof()) { if(!strcmp(ip,unique_code)) { cout<<"\t\t\tComputer already in use\n"; return false; } seeusecomp.read(reinterpret_cast<char*>(this), sizeof(*this)); } seeout: seeusecomp.close(); ifstream searcomp; searcomp.open("Computer_Entry.dat",ios::in|ios::binary); if(searcomp.fail()) { cout<<"Error in openning file!,file not found"; return false; } searcomp.read(reinterpret_cast<char*>(this),sizeof(*this)); while(!searcomp.eof()) { if(!strcmp(ip,unique_code)) { showComputerData(); count++; return true; } searcomp.read(reinterpret_cast<char*>(this),sizeof(*this)); } if(!count) { cout<<"There is no computer with this unique code "; return false; } searcomp.close(); } void Computer_Entry::delComputerRecord() { fflush(stdin); char s[20]; cout<<"Enter the unique code of Computer to delete : "; cin.getline(s,20); int count = 0; ofstream outfile; ifstream infile; infile.open("Computer_Entry.dat",ios::in|ios::binary); if(infile.fail()) { cout<<"Error in opening file!,file not found "; return; } outfile.open("tempcomp.dat",ios::out|ios::binary); infile.read(reinterpret_cast<char *>(this),sizeof(*this)); while(!infile.eof()) { if(!strcmp(s,unique_code)) { cout<<"\t\t\tComputer you want to delete found !\n"; cout<<"Are you sure you want to Delete (y/n)?\n"; if(getche() == 'n' || getche() == 'N') { outfile.close(); remove("tempcomp.dat"); return; } count++; } deleted: if(strcmp(s,unique_code)) outfile.write(reinterpret_cast<char *>(this),sizeof(*this)); infile.read(reinterpret_cast<char *>(this),sizeof(*this)); } infile.close(); outfile.close(); if(!count) cout<<"the computer you want to delete does not exist"; if(count) cout<<"Record deleted successfully"; remove("Computer_Entry.dat"); rename("tempcomp.dat","Computer_Entry.dat"); } void Computer_Entry::updateComputerRecord() { fflush(stdin); char a[20]; cout<<"Enter the unique code of computer to Update that particular computer : "; cin.getline(a,20); int count = 0; fstream inoutfile; inoutfile.open("Computer_Entry.dat",ios::in|ios::out|ios::ate|ios::binary); if(inoutfile.fail()) { cout<<"Error in opening file!,file not found "; return; } inoutfile.seekg(0); inoutfile.read(reinterpret_cast<char *>(this),sizeof(*this)); while(!inoutfile.eof()) { if(!strcmp(a,unique_code)) { cout<<"\t\t\tComputer you want to Update found \n"; cout<<"Are you sure you want to update (y/n)?\n"; if(getche() == 'n' || getche() == 'N') return; system("cls"); cout<<"\t\t\t\t Enter new data\n"; getComputerData(); inoutfile.seekp(inoutfile.tellp()-sizeof(*this)); inoutfile.write(reinterpret_cast<char *>(this),sizeof(*this)); count++; } inoutfile.read(reinterpret_cast<char *>(this),sizeof(*this)); } inoutfile.close(); if(!count) { cout<<"The record you want to update does not exist"; } if(count) { cout<<"Record updated successfully"; } } void Computer_Entry::ComputerEntryfun() { Computer_Entry c; int choice; while(true) { system("cls"); cout << "\n\n\n\n\t\t\t "; cout << "\n\n"; cout<<"\t\t\t MENU/MASTER ENTRY/COMPUTER ENTRY "; cout<< "\n\t\t\t\t __________________________"; cout<< "\n\t\t\t\t| |"; cout << "\n\t\t \t \t| 1. Add Computer |"; cout << "\n \t\t\t \t| 2. Show Computers |"; cout << "\n \t\t\t \t| 3. Search Computer |"; cout << "\n \t\t\t \t| 4. Delete Computer |"; cout << "\n \t\t\t \t| 5. Update Computer |"; cout << "\n \t\t\t \t| 6. Return |\n"; cout<< "\t\t \t\t|__________________________|\n"; cout << "\n\n"; while(1) { cout << "\t\t\t\t Select Your Choice ->> "; cin>>choice; if(cin.good()) break; cin.clear(); cout<<"\t\t\tInvalid choice enter a valid choice"<<endl; cin.ignore(10,'\n'); } switch(choice) { case 1: system("cls"); char ch; do { getComputerData(); storeComputer(); cout<<"\nDo you want to add another computer (y/n)"<<endl; cin>>ch; } while(ch == 'y'|| ch == 'Y'); break; case 2: system("cls"); readComputerRecord(); while(getche() != '\r'); break; case 3: system("cls"); searchComputerRecordEntry(); while(getche() != '\r'); break; case 4: system("cls"); delComputerRecord(); while(getche() != '\r'); break; case 5: system("cls"); updateComputerRecord(); while(getche() != '\r'); break; case 6: return ; break; default: cout<<"Invalid choice ! Re-Enter "; return ComputerEntryfun(); break; } } }
true
bbe7576e373bd9f84d3cc335b3dabdd4a73f35f5
C++
longshadian/zylib
/zylib/Tools.h
UTF-8
3,308
2.75
3
[]
no_license
#pragma once #include <cstring> #include <ctime> #include <string> #include <vector> #include <memory> #include <algorithm> #include <iterator> #include <sstream> struct timeval; namespace zylib { void Init(); std::vector<std::string> StrSplit(const std::string& s, char c); // 字符串替换,字符串str中的src字符替换成dest,返回替换个数 std::size_t StrReplace(std::string* str, char src, char dest); // 字符串删除, std::size_t StrRemove(std::string* str, char src); /* template <class RandomAccessIterator> void LinearRandomShuffle(RandomAccessIterator first, RandomAccessIterator last) { typename std::iterator_traits<RandomAccessIterator>::difference_type n = (last - first); if (n <= 0) return; while (--n) { std::swap(first[n], first[rand() % (n + 1)]); } } */ template <typename T> void BZzero(T* t) { static_assert(std::is_pod<T>::value, "T must be pod!"); std::memset(t, 0, sizeof(T)); } std::string CatFile(const char* f); bool CatFile(const std::string& path, std::string* out); std::string ToUpperCase(const std::string& src); std::string ToLowerCase(const std::string& src); std::string ToHex(const void* data, std::size_t len); struct tm* Localtime(const std::time_t* t, struct tm* output); std::string Localtime_HHMMSS(const std::time_t* t); std::string Localtime_YYYYMMDD_HHMMSS(const std::time_t* t); std::string Localtime_HHMMSS_F(); std::string Localtime_YYYYMMDD_HHMMSS_F(); std::string UTC_HHMMSS(const std::time_t* t); std::string UTC_YYYYMMDD_HHMMSS(const std::time_t* t); std::string UTC_HHMMSS_F(); std::string UTC_YYYYMMDD_HHMMSS_F(); // little/big endian conversion std::int16_t BigInt16(std::int16_t l); std::int16_t LittleInt16(std::int16_t l); std::int32_t BigInt32(std::int32_t l); std::int32_t LittleInt32(std::int32_t l); std::int64_t BigInt64(std::int64_t l); std::int64_t LittleInt64(std::int64_t l); std::uint16_t BigUInt16(std::uint16_t l); std::uint16_t LittleUInt16(std::uint16_t l); std::uint32_t BigUInt32(std::uint32_t l); std::uint32_t LittleUInt32(std::uint32_t l); std::uint64_t BigUInt64(std::uint64_t l); std::uint64_t LittleUInt64(std::uint64_t l); float BigFloat(float l); float LittleFloat(float l); double BigDouble(double l); double LittleDouble(double l); void BigRevBytes(void *bp, int elsize, int elcount); void LittleRevBytes(void *bp, int elsize, int elcount); void LittleBitField(void *bp, int elsize); template <typename E> static std::underlying_type_t<E> EnumValue(E e) { //static_assert(std::is_enum<E>::value, "E must be enum or enum class !"); return static_cast<std::underlying_type_t<E>>(e); } int Snprintf(char* buf, std::size_t buflen, const char* format, ...) #ifdef __GNUC__ __attribute__((format(printf, 3, 4))) #endif ; int Vsnprintf(char* buf, std::size_t buflen, const char* format, va_list ap) #ifdef __GNUC__ __attribute__((format(printf, 3, 0))) #endif ; void Gettimeofday(struct timeval *tp); void Gmtime(const std::time_t* t, struct tm* output); ////////////////////////////////////////////////////////////////////////// } namespace zylib { namespace detail { void Swap_Init(); } // namespace detail } // namespace zylib
true
e5f3e20fd7a716a4ff8949068918910b1935cb96
C++
hexu1985/cpp_code
/libstd_cpp/vector/insert11.cpp
UTF-8
1,208
3.375
3
[]
no_license
// vector::insert #include <iostream> #include "vector.h" int main () { int myarray[3] = { 11, 22, 33 }; Hx::vector<int> myvec; Hx::vector<int>::iterator it; it = myvec.insert ( myvec.begin(), 10 ); // 10 // ^ <- it it = myvec.insert ( it, 2, 20 ); // 20 20 10 // ^ it = myvec.insert ( it, myarray, myarray+3 ); // 11 22 33 20 20 10 // ^ it = myvec.end(); // ^ #if __cplusplus >= 201103L it = myvec.insert ( it, {1,2,3} ); // 11 22 33 20 20 10 1 2 3 // ^ #else it = myvec.insert ( it, (int []) {1,2,3} ); // 11 22 33 20 20 10 1 2 3 // ^ #endif std::cout << "myvec contains:"; #if __cplusplus >= 201103L for (int& x: myvec) std::cout << ' ' << x; #else for (size_t i = 0; i < myvec.size(); ++i) std::cout << ' ' << myvec[i]; #endif std::cout << '\n'; return 0; } /* Output: myvec contains: 11 22 33 20 20 10 1 2 3 */
true
87200fa7f26b635510adce26a702ba25cfd76659
C++
cmjeong/rashmi_oai_epc
/lte_enb/src/tenb_commonplatform/software/libs/messaging/messages/common/MfSetAdminStateReq.h
UTF-8
1,807
2.640625
3
[]
no_license
/////////////////////////////////////////////////////////////////////////////// // // MfSetAdminStateReq.h // // Commands a Managed Fing to change its admin state. // // Copyright radisys Limited // /////////////////////////////////////////////////////////////////////////////// #ifndef __MfSetAdminStateReq_h_ #define __MfSetAdminStateReq_h_ /////////////////////////////////////////////////////////////////////////////// // System Includes /////////////////////////////////////////////////////////////////////////////// #include <system/Serialisable.h> #include <system/SerialisationIds.h> #include <system/ManagedObject.h> #include <platform/ManagedFing.h> /////////////////////////////////////////////////////////////////////////////// // Classes /////////////////////////////////////////////////////////////////////////////// class MfSetAdminStateReq : public threeway::Serialisable { public: /** * Default constructor. For messaging internal use only. */ MfSetAdminStateReq(); /** * Construct a MfSetAdminStateReq. */ MfSetAdminStateReq(ManagedFing managedFing, threeway::ManagedObject::AdminState adminState); virtual ~MfSetAdminStateReq() {}; /** * Implement Serialisable pure virtuals. */ virtual u32 GetSerialisationId() const { return SERIALISATION_ID_MF_SET_ADMIN_STATE_REQ; }; virtual s32 Serialise(u8* data, u32 dataMaxBytes) const; virtual bool DeSerialise(const u8* data, u32 dataLen); virtual std::string ToString() const; /** * Setters/Getters */ ManagedFing GetManagedFing() { return m_managedFing; } threeway::ManagedObject::AdminState GetAdminState() { return m_adminState; } private: ManagedFing m_managedFing; threeway::ManagedObject::AdminState m_adminState; }; #endif
true
f729a4d4d479440dfd345077fe3d0ec0d045cb51
C++
sdouma/450-Compiler-Project
/Project7/utf8sequence.cpp
UTF-8
1,091
3
3
[]
no_license
#include "utf8sequence.h" #include <iostream> using namespace std; UTF8Sequence::UTF8Sequence(std::istream &is_) : is(is_) { offset = 0; } int UTF8Sequence::next() { int ans; restart: for (;;) { // loop past invalid starts ans = is.get(); if ((ans & 0x80) == 0 || ans == -1) return ans; if ((ans & 0xC0) != 0x80) break; } int extra = 0; while ((ans & 0x80)) { ++extra; ans = (ans << 1); } ans = ((ans & 0xFF) >> extra); --extra; while (extra > 0) { int part = is.get(); if (part == -1) return -1; if ((part & 0xC0) != 0x80) goto restart; ans = (ans << 6) | (part & 0x3F); --extra; } return ans; } size_t UTF8Sequence::at() { return offset - ahead.size(); } int UTF8Sequence::peek(unsigned delta) { while (ahead.size() <= delta) { ahead.push_back(next()); ++offset; } std::list < int > ::iterator i = ahead.begin(); while (delta > 0) { ++i; --delta; } return *i; } void UTF8Sequence::shift(unsigned delta) { while (ahead.size() < delta) { ahead.push_back(next()); ++offset; } while (delta > 0) { ahead.pop_front(); --delta; } }
true
b7e0075afce9a2d4e1eacc7733199f2b6f560def
C++
xuchuG/MySTL
/MySTL/stl_vector.h
GB18030
17,011
2.96875
3
[]
no_license
#pragma once #ifdef __STL_USE_STD_ALLOCATORS template <class _Tp,class _Allocator,bool _IsStatic> class _Vector_alloc_base { public: typedef typename _Alloc_traits(_Tp, _Allocator)::allocator_type allocator_type; allocator_type get_allocator() const { return _M_data_allocator; } _Vector_alloc_base(const allocator_type& __a) :_M_data_allocator(__a), _M_start(0), _M_finish(0), _M_end_of_storage(0) { } protected: allocator_type _M_data_allocator; _Tp* _M_start; _Tp* _M_finish; _Tp* _M_end_of_storage; _Tp* _M_allocate(size_t __n) { _M_data_allocator.allocate(__n); } void _M_deallocate(_Tp* __p, size_t __n) { _M_data_allocator.deallocate(__p, __n); } }; //û_M_data_allocatorƫػ template <class _Tp, class _Allocator> class _Vector_alloc_base<_Tp, _Allocator, true> { public: typedef typename _Alloc_traits<_Tp, _Allocator>::allocator_type allocator_type; allocator_type get_allocator() const { return allocator_type(); } _Vector_alloc_base(const allocator_type&) : _M_start(0), _M_finish(0), _M_end_of_storage(0) {} protected: _Tp * _M_start; _Tp* _M_finish; _Tp* _M_end_of_storage; typedef typename _Alloc_traits<_Tp, _Allocator>::_Alloc_type _Alloc_type; _Tp* _M_allocate(size_t __n) { return _Alloc_type::allocate(__n); } void _M_deallocate(_Tp* __p, size_t __n) { _Alloc_type::deallocate(__p, __n); } }; //_Vector_alloc_base̳ template <class _Tp,class _Alloc> struct _Vector_base : public _Vector_alloc_base<_Tp, _Alloc, _Alloc_traits<_Tp, _Alloc>::_S_instanceless> { typedef _Vector_alloc_base <_Tp, _Alloc, _Alloc_traits<_Tp, Alloc>::_S_instanceless> _Base; typedef typename _Base::allocator_type allocator_type; _Vector_base(const alloctor_type& __a):_Base(__a){} _Vector_base(size_t __n, const allocator_type& __a) :_Base(__a) { _M_start = _M_allocator(__n); _M_finish = _M_start; _M_end_of_storage = _M_start + __n; } ~_Vector_base() { _M_deallocate(_M_start, _M_end_of_storage - _M_start); } }; #else /* __STL_USE_STD_ALLOCATORS */ //ͳϵһ template <class _Tp, class _Alloc> class _Vector_base { public: typedef _Alloc allocator_type; allocator_type get_allocator() const { return allocator_type(); } _Vector_base(const _Alloc&) : _M_start(0), _M_finish(0), _M_end_of_storage(0) {} _Vector_base(size_t __n, const _Alloc&) : _M_start(0), _M_finish(0), _M_end_of_storage(0) { _M_start = _M_allocate(__n); _M_finish = _M_start; _M_end_of_storage = _M_start + __n; } ~_Vector_base() { _M_deallocate(_M_start, _M_end_of_storage - _M_start); } protected: _Tp * _M_start; _Tp* _M_finish; _Tp* _M_end_of_storage; typedef simple_alloc<_Tp, _Alloc> _M_data_allocator; _Tp* _M_allocate(size_t __n) { return _M_data_allocator::allocate(__n); } void _M_deallocate(_Tp* __p, size_t __n) { _M_data_allocator::deallocate(__p, __n); } }; #endif/* __STL_USE_STD_ALLOCATORS */ //_STL_DEFAULT_ALLOCATOR(_Tp)Ǻ⣬ΪʲôҪ_Tp //һdefine /*# ifndef __STL_DEFAULT_ALLOCATOR # ifdef __STL_USE_STD_ALLOCATORS # define __STL_DEFAULT_ALLOCATOR(T) allocator< T > # else # define __STL_DEFAULT_ALLOCATOR(T) alloc # endif # endif */ template <class _Tp,class _Alloc = _STL_DEFAULT_ALLOCATOR(_Tp)> class vector :protected _Vector_base<_Tp, _Alloc> { __STL_CLASS_REQUIRES(_Tp, _Assignable); private: typedef _Vector_base<_Tp, _Alloc> _Base; public: //ǶͶ typedef _Tp value_type; typedef value_type* pointer; typedef const value_type* const_pointer; typedef value_type* iterator; typedef const value_type* const_iterator; typedef value_type& reference; typedef const value_type& const_reference; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef typename _Base::allocator_type allocator_type; allocator_type get_allocator() const { return _Base::get_allocator(); } #ifdef __STL_CLASS_PARTIAL_SPECIALIZATION typedef reverse_iterator<const_iterator> const_reverse_iterator; typedef reverse_iterator<iterator> reverse_iterator; #else /* __STL_CLASS_PARTIAL_SPECIALIZATION */ typedef reverse_iterator<const_iterator, value_type, const_reference, difference_type> const_reverse_iterator; typedef reverse_iterator<iterator, value_type, reference, difference_type> reverse_iterator; #endif /* __STL_CLASS_PARTIAL_SPECIALIZATION */ protected: #ifdef __STL_HAS_NAMESPACES using _Base::_M_allocate; using _Base::_M_deallocate; using _Base::_M_start; using _Base::_M_finish; using _Base::_M_end_of_storage; #endif /* __STL_HAS_NAMESPACES */ protected: void _M_insert_aux(iterator __position, const _Tp& __x); void _M_insert_aux(iterator __position); public: iterator begin() { return _M_start; } const_iterator begin() const { return _M_start; } iterator end() { return _M_finish; } const iterator end()const { return _M_finish; } reverse_iterator rbegin() { return reverse_iterator(end()); } const_reverse_iterator rbegin()const { return const_reverse_iterator(end()); } reverse_iterator rend() { return reverse_iterator(begin()); } const_reverse_iterator rend()const { return const_reverse_iterator(begin()); } size_type size()const { return size_type(end() - begin()); } size_type max_size()const { return size_type(-1) / sizeof(_Tp); } size_type capacity()const { return size_type(_M_end_of_storage - begin()); } bool empty()const { return begin() == end(); } reference operator[](size_type __n) { return *(begin()+ __n); } const_reference operator[](size_type __n)const { return *(begin() + __n); } #ifdef __STL_THROW_RANGE_ERRORS void _M_range_check(size_type __n)const { if (__n >= this->size()) { __stl_throw_range_error("vector"); } } reference at(size_type __n) { _M_range_check(__n); return (*this)[__n]; } const_reference at(size_type __n)const { _M_range_check(__n); return (*this)[__n]; } #endif explicit vector(const allocator_type& __a = allocator_type()):_Base(__a) { } vector(size_type __n, const _Tp& __value,const allocator_type& __a = allocator_type()):_Base(__n,__a)//_Baseռ { // _M_finish = uninitialized_fill_n(_M_start, __n, __value); } explicit vector(size_type __n):_Base(__n,allocator_type()){ _M_finish = uninitialized_fill_n(_M_start, __n, _Tp()); } vector(const vector<_Tp, _Alloc>& __x) :_Base(__x.size(),__x.get_allocator()) { _M_finish = uninitialized_copy(__x.begin(), __x.end(), _M_start); } #ifdef __STL_MEMBER_TEMPLATES //һ template <class _InputIterator> vector(_InputIterator __first, _InputIterator __last, const allocator_type& __a = allocator_type()) : _Base(__a) { typedef typename _Is_inteeger<_InputIterator>::_Itegral _Integral; _M_initialize_aux(__first, __last, _Integral()); } //ڶ template<class _Integer> void _M_initialize_aux(_Integer __n, _Integer __value, __true_type) { _M_start = _M_allocate(__n); _M_end_of_storage = _M_start + __n; _M_finish = uninitialized_fill_n(_M_start, __n, __value); } template<class _InputIterator> void _M_initialize_aux(_InputIterator __first, _InputIterator __last, __false_type) { _M_range_initialize(__first, __last, __ITERATOR_CATEGORY(__first)); } #else vector < const _Tp* __first, const _Tp* __last, const allocator_type& __a = allocator_type()):_Base(__last - __first, __a){ _M_finish = uninitialized_copy(__first, __last, _M_start); } #endif/* __STL_MEMBER_TEMPLATES */ #ifdef __STL_MEMBER_TEMPLATES // template<class _InputIterator> void _M_range_initialize(_InputIterator __first, _InputIterator __last, input_iterator_tag) { for (; __first != __last; __first++) { push_back(*__first); } } template <class _ForwardgyIterator> void _M_range_initialize(_ForwardIterator __first, _ForwardIterator __last, forward_iterator_tag) { size_type __n = 0; distance(__first, __last, __n); _M_start = _M_allocate(__n); _M_end_of_storage = _M_start + __n; _M_finish = uninitialized_copy(__first,__last,_M_start); } #endif/* __STL_MEMBER_TEMPLATES */ ~vector() { destory(_M_start, _M_finish); } vector<_Tp, _Alloc>& operator=(const vector<_Tp, _Alloc>& __x); void reserve(size_type __n) { if (capacity() < __n) { const size_type __old_size = size(); iterator __tmp = _M_allocate_and_copy(__n, _M_start, _M_finish); // destroy(_M_start, _M_finish); _M_deallocate(_M_start, _M_end_of_storage - _M__start); _M_start = __tmp; _M_finish = __tmp + __old_size; _M_end_of_storage = _M_start + __n; } } //һ void assign(size_type __n, const _Tp& __val) { _M_fill_assign(__n, __val); } //ڶ,˴С void _M_fill_assign(size_type __n, const _Tp& __val) { if (__n > capacity()) { vector<_Tp, _Alloc> __tmp(__n, __val, get_allocator()); __tmp.swap(*this); } else if (__n > size()) { //Ŀռ䣬ܻҪҪͷһЩռ,⣬fillIJǵֵ֪мûжԵֵأжԵԭָĶӦУ fill(begin(), end(), __val); //ûбĿռ _M_finish = uninitialized_fill_n(end(), __n - size(), __val); } else { earase(fill_n(begin(), __n, __val), end()); } } #ifdef __STL_MEMBER_TEMPLATES template <class _InputIterator> void assign(_InputIterator __first, _InputIterator __last) { typedef typename _Is_integer<_InputIterator>::_Integral _Integral; _M_assign_dispatch(__first, __last, _Integral()); } template <class _Integer> void _M_assign_dispatch(_Integer __n, _Integer __val, __true_type) { _M_fill_assign((size_type)__n, (_Tp)__val); } template <class _InputIter> void _M_assign_dispatch(_InputIter __first, _InputIter __last, __false_type) { _M_assign_aux(__first, __last, __ITERATOR_CATEGORY(__first)); } template <class _InputIterator> void _M_assign_aux(_InputIterator __first, _InputIterator __last, input_iterator_tag); template <class _ForwardIterator> void _M_assign_aux(_ForwardIterator __first, _ForwardIterator __last, forward_iterator_tag); #endif /* __STL_MEMBER_TEMPLATES */ reference front() { return *begin(); } const_reference front()const { return *begin(); } reference back() { return *end(); } const_reference back()const { return *end(); } void push_back(const _Tp& __x) { if (_M_finish != _M_end_of_storage) { construct(_M_finish, __x); _M_finish++; } else { _M_insert_aux(end(),__x); } } void push_back() { if (_M_finish != _M_end_of_storage) { construct(_M_finish); _M_finish++; } else { _M_insert_aux(end()); } } void swap(vector<_Tp, _Alloc>& __x) { __STD::swap(_M_start, __x._M_start); __STD::swap(_M_finish, __x._M_finish); __STD::swap(_M_end_of_storage, __x._M_end_of_storage); } //positionλò__x iterator insert(iterator __position, const _Tp& __x) { size_type __n = __position - begin(); if (_M_finish != _M_end_of_storage && __position == end()) { construct(_M_finish, __x); _M_finish++; } else { _M_insert_aux(__position, __x); } return begin() + __n; } void vector<_Tp, _Alloc>::_M_insert_aux(iterator __position, const _Tp& __x) { if (_M_finish != _M_end_of_storage) { //ΪʲôҪĽһԪȹ죬ǽ߼ͺͳһ construct(_M_finish, *(_M_finish - 1)); ++_M_finish; //x_copyĿģ _Tp __x_copy = __x; copy_backward(__position, _M_finish - 2, _M_finish - 1); *position = __x_copy; } else { const size_type __old_size = size(); const size_type __len = __old_size != 0 ? 2 * __old_size : 1; iterator __new_start = _M_allocate(__len); iterator __new_finish = __new_start; __STL_TRY{//try __new_finish = uninitialized_copy(_M_start,__position,__new_start); consrtuct(_new_finish, __x); ++__new_finish; __new_finish = uninitialized_copy(__position, _M_finsh, __new_finish); }__STL_UNWIND((destroy(__new_start, __new_finish),//catch _M_deallocate(__new_start, __len))); destroy(begin(), end()); _M_deallocate(_M_start, _M_end_of_storage - _M_start); _M_start = __new_start; _M_finish = __new_finish; _M_end_of_storage = __new_start + __len; } } iterator insert(iterator __position) { size_type __n = __position - begin(); if (_M_finish != _M_end_of_storage && __position == end()) { construct(_M_finish); _M_finish++; } else { _M_insert_aux(__position); } return begin() + __n; } void vector<_Tp, _Alloc>::_M_insert_aux(iterator __position) { if (_M_finish != _M_end_of_storage) { construct(_M_finish, *(_M_finish - 1)); ++_M_finish; copy_backward(__position, _M_finish - 2, _M_finish - 1); *__position = _Tp(); } else { const size_type __old_size = size(); const size_type __len = __old_size != 0 ? 2 * __old_size : 1; iterator __new_start = _M_allocate(__len); iterator __new_finish = __new_start; __STL_TRY{ __new_finish = uninitialized_copy(_M_start, __position, __new_start); construct(__new_finish); ++__new_finish; __new_finish = uninitialized_copy(__position, _M_finish, __new_finish); } __STL_UNWIND((destroy(__new_start, __new_finish), _M_deallocate(__new_start, __len))); destroy(begin(), end()); _M_deallocate(_M_start, _M_end_of_storage - _M_start); _M_start = __new_start; _M_finish = __new_finish; _M_end_of_storage = __new_start + __len; } } #ifdef __STL_MEMBER_TEMPLATES // Check whether it's an integral type. If so, it's not an iterator. template <class _InputIterator> void insert(iterator __pos, _InputIterator __first, _InputIterator __last) { typedef typename _Is_integer<_InputIterator>::_Integral _Integral; _M_insert_dispatch(__pos, __first, __last, _Integral()); } template <class _Integer> void _M_insert_dispatch(iterator __pos, _Integer __n, _Integer __val, __true_type) { _M_fill_insert(__pos, (size_type)__n, (_Tp)__val); } template <class _InputIterator> void _M_insert_dispatch(iterator __pos, _InputIterator __first, _InputIterator __last, __false_type) { _M_range_insert(__pos, __first, __last, __ITERATOR_CATEGORY(__first)); } #else /* __STL_MEMBER_TEMPLATES */ void insert(iterator __position, const_iterator __first, const_iterator __last); #endif /* __STL_MEMBER_TEMPLATES */ void insert(iterator __pos, size_type __n, const _Tp& __x) { _M_fill_insert(__pos, __n, __x); } void _M_fill_insert(iterator __pos, size_type __n, const _Tp& __x) { if (__n != 0) { if (size_type(_M_end_of_storage - _M_finish) >= __n) { _Tp __x_copy = __x; const size_type __elems_after = _M_finish - __position; iterator __old_finish = _M_finish; if (__elems_after > __n) {//ڹ͸ֵڲ uninitialized_copy(_M_finish - __n, _M_finish, _M_finish); _M_finish += __n; copy_backward(__position, __old_finish - __n, __old_finish); fill(__position, __position + __n, __x_copy); } else { uninitialized_fill_n(_M_finish, __n - __elems_after, __x_copy); _M_finish += __n - __elems_after; uninitialized_copy(__position, __old_finish, _M_finish); _M_finish += __elems_after; fill(__position, __old_finish, __x_copy); } } else { const size_type __old_size = size(); const size_type __len = __old_size + max(__old_size, __n); iterator __new_start = _M_allocate(__len); iterator __new_finish = __new_start; __STL_TRY{ __new_finish = uninitialized_copy(_M_start, __position, __new_start); __new_finish = uninitialized_fill_n(__new_finish, __n, __x); __new_finish = uninitialized_copy(__position, _M_finish, __new_finish); } __STL_UNWIND((destroy(__new_start, __new_finish), _M_deallocate(__new_start, __len))); destroy(_M_start, _M_finish); _M_deallocate(_M_start, _M_end_of_storage - _M_start); _M_start = __new_start; _M_finish = __new_finish; _M_end_of_storage = __new_start + __len; } } } void pop_back() { _M_finish--; destroy(_M_finish); } iterator erase(iterator __position) { if (__position + 1 != end()) { copy(__position + 1, _M_finish, __position); } --_M_finish; destroy(_M_finish); return __position; } iterator erase(iterator __first, iterator __last) { iterator __i = copy(__last, _M_finish, __first); destroy(__i, _M_finish); _M_finish = _M_finish - (__last - __first); return __first; } void resize(size_type __new_size, const _Tp& __x) { if (__new_size < size()) erase(begin() + __new_size, end()); else insert(end(), __new_size - size(), __x); } void resize(size_type __new_size) { resize(__new_size, _Tp()); } void clear() { erase(begin(), end()); } //дstl_vector.h434(൱ԲôҪ)...... };
true
9329d8d8e64404f6b77f9f2e4fb5e69e9bcfd98c
C++
ph0ly/winutil
/io/File.h
GB18030
1,753
2.5625
3
[ "MIT" ]
permissive
#pragma once #include <vector> #include <string> #include <memory> #include "../pub/cmn.h" NAMESPACE_PH0LY_BEGIN(io) // // -> File ļ // Copyright (c) ph0ly 2013.03.13 . All rights reserved. // class PH0LY File { public: // FM -> File Mode enum Mode { FM_TEXT = 1, FM_BINARY = 2, FM_CREATE = 4 }; File(void); ~File(void); /** * ļǷ * @param lpszFileName ļ· */ static bool Exists( const char* lpszFileName ); /// ɾļ static bool Delete( const char* lpszFileName ); /// ļ static bool Create( const char* lpszPath ); /// ȡļǰ׺׺֣ static bool GetFilePrefix( const char* lpszName, char* lpszOut, int nMaxBuffer ); /// ȡļ static bool GetFileName( const char* lpszName, char* lpszOut, int nMaxBuffer ); /// ȡļ static bool GetFileNameWithExtension( const char* lpszName, char* lpszOut, int nMaxBuffer ); /// Ƿļ static bool IsFile( const char* lpszPath ); /// ǷĿ¼ static bool IsDirectory( const char* lpszPath ); /// ȡļ׺ static bool GetFileExtension( const char* lpszName, char* lpszOut, int nMaxBuffer ); /// ȡļĿ¼ static bool GetDirectory( const char* lpszPath, char * lpszOut, int nMaxBuffer ); /// Ŀ¼lpszDirеģlpszEndsΪ׺ļvOutFiles static bool FindFiles( const char* lpszDir, const char* lpszEnds, std::vector<std::string>& vOutFiles ); /// ȡıļ static bool ReadAllText( const char* lpszPath, std::string& strOutput ); /// ıļ static bool SaveAllText( const char* lpszPath, const std::string& strInput ); }; NAMESPACE_PH0LY_END
true
844ecc163cb6f0698c6687a30671b98f40d95a1d
C++
JM-W/DataStructure
/DataStructure/Graph/GQueue.h
UTF-8
502
2.53125
3
[]
no_license
#include "dGraph.h" #ifndef GQUEUE typedef int ElementType; class GQueue { public: class GList { public: GList(ElementType ele) :Element(ele),Next(NULL){}; ElementType Element; GList* Next; }; public: GQueue() { Ver = End = NULL; }; ~GQueue(){}; public: void Enqueue(ElementType ele); ElementType Dequeue(); void Print(); void DeleteQueue(); private://private GList *Ver; GList *End; }; #define GQUEUE #endif // !GQUEUE
true
2c11ce1b970f18fcbb85652e6d552f78961813e2
C++
CShatto99/C-Projects
/Fall 2018 Semester/Assignment4.cpp
UTF-8
2,859
3.828125
4
[]
no_license
//Name: Cameron Shatto //Class: 2018 Fall - COSC 1436.S01 //Project 4: Speed of Sound in Gases //Revision: 1.0 //Date: 10/08/18 //Description: This progam will utilize user I/O to determine the speed of sound in gases. #include "stdafx.h" #include <iostream> #include <iomanip> using namespace std; int main() { int gas; int seconds; int minSec = 0; int maxSec = 30; const double carbonDioxide_S = 258.0, air_S = 331.5, helium_S = 972.0, hydrogen_S = 1270.0; const int carbon = 1, air = 2, helium = 3, hydrogen = 4; cout << left << setw(25) << "Medium" << left << setw(25) << "Speed (Meters per Second)" << endl << left << setw(25) << "1. Carbon Dioxide" << left << setw(25) << "258.0" << endl << left << setw(25) << "2. Air" << left << setw(25) << "331.5" << endl << left << setw(25) << "3. Helium" << left << setw(25) << "972.0" << endl << left << setw(25) << "4. Hydrogen" << left << setw(25) << "1270.0" << endl << endl << "Choose the number of a gas that is listed: " << endl; cin >> gas; if (gas == carbon) { cout << "Enter the amount of seconds sound traveled through Carbon Dioxide: " << endl; cin >> seconds; if (seconds < maxSec && seconds > minSec) { double sourceDistance = seconds * 258.0; cout << "The source of the sound was " << sourceDistance << " meters away."; cin.get(); } else { cout << "Invalid response: enter a time between 0 and 30 seconds."; cin.get(); } } else if (gas == air) { cout << "Enter the amount of seconds sound traveled through Air: " << endl; cin >> seconds; if (seconds < maxSec && seconds > minSec) { double sourceDistance = seconds * 331.5; cout << "The source of the sound was " << sourceDistance << " meters away."; cin.get(); } else { cout << "Invalid response: enter a time between 0 and 30 seconds."; cin.get(); } } else if (gas == helium) { cout << "Enter the amount of seconds sound traveled through Helium: " << endl; cin >> seconds; if (seconds < maxSec && seconds > minSec) { double sourceDistance = seconds * 972.0; cout << "The source of the sound was " << sourceDistance << " meters away."; cin.get(); } else { cout << "Invalid response: enter a time between 0 and 30 seconds."; cin.get(); } } else if (gas == hydrogen) { cout << "Enter the amount of seconds sound traveled through Hydrogen: " << endl; cin >> seconds; if (seconds < maxSec && seconds > minSec) { double sourceDistance = seconds * 1270.0; cout << "The source of the sound was " << sourceDistance << " meters away."; cin.get(); } else { cout << "Invalid response: enter a time between 0 and 30 seconds."; cin.get(); } } else { cout << "Reboot the program and choose a gas that is listed."; cin.get(); } cin.get(); return 0; }
true
1338088ba1ca0ab0fc56329c892d449bbcd321ef
C++
lg878398509/gameproject
/goldminer/Classes/Gold.cpp
UTF-8
1,127
3.25
3
[]
no_license
#include "Gold.h" Gold* Gold::create(std::string type, Size size) { Gold *gold = new Gold(); if (gold && gold->init(type, size)) { gold->autorelease(); return gold; } else { CC_SAFE_DELETE(gold); gold = NULL; return NULL; } } bool Gold::init(std::string type, Size size) { if (type == "smallGold") { if (!initWithSpriteFrameName("gold-1-1.png")) { return false; } weight = 3; value = 50; } else if (type == "moddleGold") { if (!initWithSpriteFrameName("gold-0-0.png")) { return false; } weight = 4; value = 250; } else if (type == "bigGold") { if (!initWithSpriteFrameName("gold-0-0.png")) { return false; } weight = 5; value = 500; } else if (type == "smallstone") { if (!initWithSpriteFrameName("stone-0.png")) { return false; } weight = 7; value = 10; } else if (type == "bigstone") { if (!initWithSpriteFrameName("stone-1.png")) { return false; } weight = 8; value = 20; } setScale(size.width / this->getContentSize().width); return true; } int Gold::getWeight() { return this->weight; } int Gold::getValue() { return this->value; }
true
379d37d1005c6aa9969e2239bede7c0d5faf7094
C++
yshmnks/YoshiPBR
/include/YoshiPBR/ysArrayGF.h
UTF-8
822
2.515625
3
[]
no_license
#pragma once #include "YoshiPBR/ysTypes.h" //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <typename T, ys_int32 N> struct ysArrayGF { public: ysArrayGF(); ~ysArrayGF(); void Create(); void Destroy(); void SetCapacity(ys_int32); void SetCount(ys_int32); void PushBack(const T&); T* Allocate(); T* GetEntries(); ys_int32 GetCapacity() const; ys_int32 GetCount() const; T& operator[](ys_int32); const T& operator[](ys_int32) const; private: T m_buffer[N]; T* m_entries; ys_int32 m_capacity; ys_int32 m_count; };
true
0f8d41ff30a36ccf38322a8f7546bd2cac25ee11
C++
tianxia1221/Algorithm
/leetcode/547.1.cpp
UTF-8
460
2.859375
3
[]
no_license
class Solution { public: int findCircleNum(vector<vector<int>>& M) { int ret = 0; int size = M.size(); vector<bool> mark(size, false); for (int i = 0; i < size; i++) { if (false == mark[i]) { dfs(M, i, mark); ret++; } } return ret; } void dfs(vector<vector<int>>& M, int i, vector<bool>& mark) { mark[i] = true; for (int j = 0; j < mark.size(); j++) { if (M[i][j] && mark[j] == false) { dfs(M, j, mark); } } } };
true
32f2700175a26b772e41b0583f68fb82d271429c
C++
zhongjinda/exercise
/Algorithm/search/SkipList/SkipList.h
UTF-8
9,249
3.21875
3
[]
no_license
#ifndef SKIPLIST_H #define SKIPLIST_H #include <stdlib.h> #include <stdio.h> template<typename T> struct Less { bool operator()(const T& a, const T& b) { return a < b; } }; template<typename T> struct SkipListNode { SkipListNode<T>* next; SkipListNode<T>* below; T value; SkipListNode() : next(NULL), below(NULL) { } }; template<typename T> struct SkipListIterator { public: typedef SkipListNode<T> Node; SkipListIterator(Node* p) : node_(p) { } T& operator*() { return node_->value; } const T& operator*() const { return node_->value; } T* operator->() { return &(node_->value); } const T* operator->() const { return &(node_->value); } SkipListIterator& operator++() { node_ = node_->next; return *this; } SkipListIterator operator++(int) { SkipListIterator tmp = *this; node_ = node_->next; return tmp; } Node* node_; }; template<typename T> inline bool operator==(const SkipListIterator<T>& lhs, const SkipListIterator<T>& rhs) { return lhs.node_ == rhs.node_; } template<typename T> inline bool operator!=(const SkipListIterator<T>& lhs, const SkipListIterator<T>& rhs) { return !(lhs == rhs); } template<typename T> struct SkipListConstIterator { public: typedef SkipListNode<T> Node; SkipListConstIterator(Node* p) : node_(p) { } T& operator*() { return node_->value; } const T& operator*() const { return node_->value; } T* operator->() { return &(node_->value); } const T* operator->() const { return &(node_->value); } SkipListConstIterator& operator++() { node_ = node_->next; return *this; } SkipListConstIterator operator++(int) { SkipListConstIterator tmp = *this; node_ = node_->next; return tmp; } const Node* node_; }; template<typename T> inline bool operator==(const SkipListConstIterator<T>& lhs, const SkipListConstIterator<T>& rhs) { return lhs.node_ == rhs.node_; } template<typename T> inline bool operator!=(const SkipListConstIterator<T>& lhs, const SkipListConstIterator<T>& rhs) { return !(lhs == rhs); } template<typename T, typename Comp = Less<T> > class SkipList { public: typedef SkipListNode<T> Node; typedef SkipListIterator<T> iterator; typedef SkipListConstIterator<T> const_iterator; typedef size_t size_type; typedef T value_type; static const int kMaxLevel = 32; SkipList() : head_(new Node), root_(head_), level_(1), size_(0) { head_->next = new Node; root_end_ = root_->next; } ~SkipList() { for (Node* head = head_; head;) { for (Node* p = head->next; p;) { Node* deleter = p; p = p->next; delete deleter; } Node* tmp = head; head = head->below; delete tmp; } } size_type level() const { return level_; } size_type size() const { return size_; } iterator begin() { return iterator(root_->next); } const_iterator begin() const { return const_iterator(root_->next); } iterator end() { return iterator(root_end_); } const_iterator end() const { return const_iterator(root_end_); } void setInsertSrand(unsigned int seed) { srand(seed); } bool insert(iterator pos) { return insert(*pos); } bool insert(const value_type& val) { size_type k = makeLevel(); if (k <= level_) { return insertNormal(k, val); } else { return insertGreaterLevel(k, val); } } iterator find(const value_type& val) { Node* p = head_; while (p && p->next) { if (p->next->next != NULL) { if (compare_(p->next->value, val)) { p = p->next; } else { if (compare_(val, p->next->value)) { p = p->below; } else { return iterator(p->next); } } } else { p = p->below; } } return iterator(end()); } bool erase(iterator pos) { return erase(*pos); } bool erase(const value_type& val) { Node* p = head_; Node* current = p->next; bool erased = false; while (p) { while (current->next && compare_(current->value, val)) { p = current; current = current->next; } if (current->next == NULL || compare_(val, current->value)) { p = p->below; if (p) { current = p->next; } } else { p->next = current->next; delete current; p = p->below; if (p) { current = p->next; } erased = true; } } if (erased) { --size_; return true; } return false; } // for debug void print() { for (Node* head = head_; head; head = head->below) { for (Node* p = head->next; p->next; p = p->next) { printf("%d ", p->value); } printf("\n"); } } private: size_type makeLevel() { size_type k = 1; while (static_cast<double>(rand() & 0xffff) < 0.25 * 0xffff) { ++k; } return k < kMaxLevel ? k : kMaxLevel; } bool insertNormal(value_type k, const value_type& val) { value_type step = level_ - k; Node* head = head_; for (value_type i = 0; i < step; ++i) { head = head->below; } Node* p = head; Node* prev = NULL; Node* current = p->next; bool insert_once = false; while (p && current) { while (current->next && compare_(current->value, val)) { p = current; current = current->next; } if (current->next == NULL || compare_(val, current->value)) { Node* node = new Node; node->value = val; node->next = current; p->next = node; if (prev) { prev->below = node; } prev = node; p = p->below; if (p) { current = p->next; } insert_once = true; } else { return false; } } if (insert_once) { ++size_; return true; } return false; } bool insertGreaterLevel(value_type k, const value_type& val) { value_type step = k - level_; level_ = k; for (int i = 0; i < step; ++i) { Node* p = new Node; p->next = new Node; p->below = head_; head_ = p; } Node* p = head_; Node* prev = NULL; Node* current = p->next; bool insert_once = false; while (p && current) { while (current->next && compare_(current->value, val)) { p = current; current = current->next; } if (current->next == NULL || compare_(val, current->value)) { Node* node = new Node; node->value = val; node->next = current; p->next = node; if (prev) { prev->below = node; } prev = node; p = p->below; if (p) { current = p->next; } insert_once = true; } else { return false;; } } if (insert_once) { ++size_; return false; } return false; } Node* head_; Node* root_; Node* root_end_; size_type level_; size_type size_; Comp compare_; }; template<typename T, typename Comp> const int SkipList<T, Comp>::kMaxLevel; #endif
true
604ebc4c6b68e824335477b93a071332ca2b0b89
C++
STabaresG/CursoFCII_UdeA-2020-2
/Documentos/Parcial2/CC1035435726/ahorcado/Palabra.cpp
UTF-8
766
3.1875
3
[]
no_license
#include <string> #include "Palabra.h" #include <iostream> using namespace std; Palabra::Palabra(const string & p_) { setP(p_); setPParcial(string(p.length(), 'x')); } void Palabra::setP(const string & p_) { p = p_; } string Palabra::getP() const { return p; } void Palabra::setPParcial(const string & p_) { pparcial = p_; } string Palabra::getPParcial() const { return pparcial; } bool Palabra::adivinarLetra(const char & c) { bool correcto = false; for (int i = 0; i < getP().length(); i++) { if (c == getP().at(i)) { pparcial.at(i) = c; if (correcto != true) //para que no establezca el valor de correcto más de una vez correcto = true; } } return correcto; }
true
b7598687632efc9000278a65a8057151cd42651c
C++
jxzhsiwuxie/cppPrimer
/chap07/exercises/ex_7.24.cpp
UTF-8
1,307
4.15625
4
[]
no_license
//练习 7.24:给你的 Screen 类添加三个构造函数:一个默认构造函数;另一个构造函数接收宽和高的值, //然后将 contents 初始化成给定数量的空白符;第三个构造函数接收宽和高的值以及一个字符,该字符作为初始化之后屏幕的内容。 #include <cstddef> #include <string> class Screen { public: typedef std::string::size_type pos; Screen() = default; Screen(pos ht, pos wd) : height(ht), width(wd), contents(ht * width, ' ') {} Screen(pos ht, pos wd, char c) : height(ht), width(wd), contents(ht * width, c) {} inline char get() const { return contents[cursor]; } //读取光标处的字符。 inline char get(pos r, pos c) const; //读取特定位置(r行c列)的字符。 inline Screen &move(pos r, pos c); //移动到r行c列处。 void some_member() const; private: pos cursor = 0; pos height = 0, width = 0; std::string contents; mutable std::size_t access_ctr = 0; }; char Screen::get(pos r, pos c) const { pos row = r * width; return contents[row + c]; } Screen &Screen::move(pos r, pos c) { pos row = r * width; cursor = row + c; return *this; } void Screen::some_member() const { ++access_ctr; }
true
2b09b91f0871feafaf2fc11b1bcdb5a593aaa5ec
C++
abeaumont/competitive-programming
/kattis/quickbrownfox.cc
UTF-8
719
2.96875
3
[ "WTFPL", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// https://open.kattis.com/problems/quickbrownfox #include <cctype> #include <iostream> using namespace std; int main() { int t; cin >> t; string s; getline(cin, s); for (int i = 0; i < t; i++) { bool xs[26]; for (int j = 0; j < 26; j++) xs[j] = false; getline(cin, s); for (int j = 0; j < s.size(); j++) { char c = tolower(s[j]); if (c >= 'a' && c <= 'z') { xs[c - 'a'] = true; } } bool missing = false; for (int j = 0; j < 26; j++) { if (!xs[j]) { missing = true; break; } } if (missing) { cout << "missing "; for (int j = 0; j < 26; j++) { if (!xs[j]) { cout << char('a' + j); } } cout << endl; } else { cout << "pangram\n"; } } }
true
5c5fdff47e35c448ac905fb4fc04ec6da4eb2ce6
C++
KMACEL/TR-Cpp
/Adim1_Ornekler/29_Kalitim/src/main.cpp
UTF-8
1,017
2.734375
3
[ "Apache-2.0" ]
permissive
//============================================================================ // İsim : 22_Pointer // Yazan : Mert AceL // Version : 1.0 // Copyright : AceL // Açıklama :22_Pointer //============================================================================ #include<iostream> //#include"calisan.h" #include"muhendis.h" #include"error.h" using namespace std; int main () { // Calisan calisan("Mert", "Acel", "05437819000", "Kocaeli/Gebze", 1250); abstract olduğu çin hata // calisan.getBilgi(); Muhendis muhendis("Mert", "Acel", "05437819000", "Kocaeli/Gebze", 1250); muhendis.getBilgi(); muhendis.zam(200,3); muhendis.getBilgi(); try { muhendis.avans(8000); muhendis.getBilgi(); } catch (AvanasHata &a) { cout << "Avans Hata : " << a.limit() << endl; } try { muhendis.avans(3000); } catch (AvanasHata &a) { cout << "Avans Hata 2 : " << a.limit() << endl; } return 0; }
true
180f20271a4ac0131f25ee0c5aea7db5cf4e1c04
C++
JairFrancesco/DataStructuresDictionary
/DataStructures/NodoF.h
UTF-8
483
2.828125
3
[ "MIT" ]
permissive
#ifndef NODOF_H #define NODOF_H #include <list> template <class T> class NodoF { public: NodoF(T d) { this->valor=d; this->padre=0; this->marcado=false; } int get_grado() { return this->hijos.size(); } virtual ~NodoF(){} protected: public: T valor; NodoF<T>* padre; std::list<NodoF<T>* > hijos; bool marcado; }; #endif // NODOF_H
true
0da35069db731543699e268af0721608993bca65
C++
syvjohan/cppFun
/DoubleLinkedList/DoubleLinkedList/Main.cpp
UTF-8
904
3.046875
3
[]
no_license
//AB5785 Johan Fredriksson #include <iostream> #include <cassert> #include "List.h" int main() { _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); List<int> list; assert(list.Check(0)); list.PushBack(3); assert(list.Check(1)); list.PushBack(34); assert(list.Check(2)); assert(list.GetFirstNode()->value == 3); assert(list.GetLastNode()->value == 34); list.PopBack(); assert(list.GetLastNode()->value == 3); list.PopBack(); list.PopBack(); assert(list.Check(0)); /*list.PushBack(24); list.PushBack(25); list.PushBack(26); list.PushFront(14); list.PushFront(15); list.PushFront(16); list.PopFront(); list.PopBack(); list.PushBack(27); list.PushBack(28); list.PushFront(29); if (list.AmountOfNodes(25)) { printf("true\n"); } else { printf("false\n"); } printf("\nNumber of elements in the list are: %i", list.AmountOfNodes()); list.PrintList();*/ return 0; }
true
23257f3ba9572f993e6a177482d7f8079787ceac
C++
ostersc/arduino-touch-wall
/CharacterTouchWall/Game.h
UTF-8
847
2.828125
3
[]
no_license
#ifndef GAME_H #define GAME_H #include "Arduino.h" #include "CharacterConfig.h" #include "MP3Util.h" const int MAX_ROUND_DURATION = 12000; class Game { public: enum GameState { waiting_to_start, waiting_for_round, playing, waiting_to_end, ended }; //construtors Game(); Game(byte rounds); byte getScore(); long getRoundDuration(); bool answer(byte i); void noAnswer(); //state operations GameState getState(); bool nextRound(CharacterConfig c); // false if no remaining rounds void start(); void end(); void reset(); //deconstructor ~Game(); private: byte currentScore, currentRound, numRounds; GameState gameState; //round stuff String roundAudioFile; byte roundExpectedSensorPin; long roundStartTime; }; #endif
true
5277346355fee961d30d95d7cd5b31bab2c4a075
C++
gutucristian/examples
/cpp/asgn4/q3.cpp
UTF-8
1,462
4.15625
4
[]
no_license
#include <iostream> #include <iomanip> #include <math.h> #include <functional> /* * * Your task is to implement makeSineToOrder(k) * * This is templated by the type of values used in the calculation. * * It must yield a function that takes a value of the specified type and * * returns the sine of that value (in the specified type again) * */ long double radians(long double degrees) { long double radians; long double pi = 3.14159265358979323846264338327950288419716939937510L; radians = (pi/180)*degrees; return radians; } unsigned long long int factorial(int n) { unsigned long long int fact = 1; for(; n >= 1; n--) fact = fact * n; return fact; } long double power(long double x, int n) { long double res = 1; while (n > 0) { res = (x*res); n--; } return res; } template<class T> auto makeSineToOrder(int k) { using namespace std; return [k](T rad) -> T { int terms = k; long double cur = rad; long double sine = cur; for (long double y = 1; y <= 2*terms; y+=2) { if (y > 1) { cur = cur * (-1.0) * rad * rad / y / (y-1); sine += cur; } } return sine; }; } int main() { using namespace std; long double pi = 3.14159265358979323846264338327950288419716939937510L; for(int order = 1;order < 20; order++) { auto sine = makeSineToOrder<long double>(order); cout << "order(" << order << ") -> sine(pi) = " << setprecision(15) << sine(pi) << endl; } return 0; }
true
be7311b09870fff2ce3a4197167c7864d99a8ade
C++
wendajiang/leetcode
/cpp/1038.binary-search-tree-to-greater-sum-tree.cpp
UTF-8
2,554
3.625
4
[]
no_license
/* * @lc app=leetcode id=1038 lang=cpp * * [1038] Binary Search Tree to Greater Sum Tree * * https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/description/ * * algorithms * Medium (83.52%) * Likes: 1853 * Dislikes: 118 * Total Accepted: 94.8K * Total Submissions: 113.5K * Testcase Example: '[4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]' * * Given the root of a Binary Search Tree (BST), convert it to a Greater Tree * such that every key of the original BST is changed to the original key plus * sum of all keys greater than the original key in BST. * * As a reminder, a binary search tree is a tree that satisfies these * constraints: * * * The left subtree of a node contains only nodes with keys less than the * node's key. * The right subtree of a node contains only nodes with keys greater than the * node's key. * Both the left and right subtrees must also be binary search trees. * * * Note: This question is the same as 538: * https://leetcode.com/problems/convert-bst-to-greater-tree/ * * * Example 1: * * * Input: root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8] * Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8] * * * Example 2: * * * Input: root = [0,null,1] * Output: [1,null,1] * * * Example 3: * * * Input: root = [1,0,2] * Output: [3,3,2] * * * Example 4: * * * Input: root = [3,2,4,1] * Output: [7,9,4,10] * * * * Constraints: * * * The number of nodes in the tree is in the range [1, 100]. * 0 <= Node.val <= 100 * All the values in the tree are unique. * root is guaranteed to be a valid binary search tree. * */ // @lc code=start /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: TreeNode* bstToGst(TreeNode* root) { if (nullptr == root) return root; orderTravel(root); for (int i = 1; i < _vec_p.size(); i++) { _vec_p[i]->val += _vec_p[i - 1]->val; } return root; } void orderTravel(TreeNode* node) { if (node->right) orderTravel(node->right); _vec_p.push_back(node); if (node->left) orderTravel(node->left); } private: std::vector<TreeNode*> _vec_p; }; // @lc code=end
true
56717c09312ba321f38b481e25cee3269f467fa4
C++
rscharpf/XDE
/src/PotentialA.h
UTF-8
990
3.03125
3
[]
no_license
#ifndef POTENTIALA_H #define POTENTIALA_H #include "Potential.h" #include "Structure.h" #include "Random.h" class PotentialA : public Potential { public: PotentialA(const Structure *str); virtual ~PotentialA(void); double potential(Random &ran) const; Potential *copy(void) const; private: const Structure *str; }; inline PotentialA::PotentialA(const Structure *str) : Potential() { this->str = str; return; } inline PotentialA::~PotentialA(void) { return; } inline Potential *PotentialA::copy(void) const { Potential *pp = new PotentialA(str); return pp; } inline double PotentialA::potential(Random &ran) const { double pot = 0.0; int q; for (q = 0; q < str->Q; q++) { if (str->a[q] == 0.0) pot += - log(str->pA0); else if (str->a[q] == 1.0) pot += - log(str->pA1); else { pot += - log(1.0 - str->pA0 - str->pA1); pot += ran.PotentialBeta(str->alphaA,str->betaA,str->a[q]); } } return pot; } #endif
true
ee0a5fc1b9000bc113438381d8f58c7dda98cb1d
C++
bansheerubber/torquescript-interpreter
/src/components/mathExpression.cc
UTF-8
20,836
2.671875
3
[]
no_license
#include "mathExpression.h" #include "../interpreter/interpreter.h" #include "accessStatement.h" #include "booleanLiteral.h" #include "../interpreter/entry.h" #include "inlineConditional.h" #include "numberLiteral.h" #include "stringLiteral.h" #include "symbol.h" map<TokenType, int> MathExpression::Precedence = MathExpression::CreatePrecedenceMap(); bool MathExpression::IsOperator(TokenType type) { return type == PLUS || type == MINUS || type == SLASH || type == ASTERISK || type == MODULUS || type == NOT_EQUAL || type == EQUAL || type == STRING_EQUAL || type == STRING_NOT_EQUAL || type == LESS_THAN_EQUAL || type == GREATER_THAN_EQUAL || type == LESS_THAN || type == GREATER_THAN || type == LOGICAL_AND || type == LOGICAL_OR || type == SHIFT_LEFT || type == SHIFT_RIGHT || type == BITWISE_AND || type == BITWISE_OR || type == BITWISE_XOR || type == APPEND || type == SPC || type == TAB || type == NL; } bool MathExpression::ShouldParse(Component* lvalue, ts::Engine* engine) { Token &token = engine->tokenizer->peekToken(); if(lvalue == nullptr) { return ( ( ( NumberLiteral::ShouldParse(engine) || StringLiteral::ShouldParse(engine) || BooleanLiteral::ShouldParse(engine) || Symbol::ShouldParse(engine) ) && MathExpression::IsOperator(engine->tokenizer->peekToken(1).type) ) || token.type == LEFT_PARENTHESIS || token.type == LOGICAL_NOT || token.type == BITWISE_NOT || token.type == MINUS ); } else { return MathExpression::IsOperator(token.type); } } MathExpression* MathExpression::Parse(Component* lvalue, Component* parent, ts::Engine* engine) { MathExpression* output = new MathExpression(engine); output->parent = parent; if(lvalue != nullptr) { output->elements.push_back((MathElement){ component: lvalue, }); lvalue->setParent(output); } // if we start with a left parenthesis, make note of it bool parenthesis = false; if(engine->tokenizer->peekToken().type == LEFT_PARENTHESIS) { engine->tokenizer->getToken(); // absorb parenthesis output->elements.push_back((MathElement){ component: nullptr, specialOp: LEFT_PARENTHESIS_OPERATOR, }); parenthesis = true; } bool expectingOperator = lvalue != nullptr; while(!engine->tokenizer->eof()) { if(expectingOperator) { Token token = engine->tokenizer->peekToken(); if(MathExpression::IsOperator(token.type)) { output->elements.push_back((MathElement){ component: nullptr, op: token, }); expectingOperator = false; engine->tokenizer->getToken(); } else if(InlineConditional::ShouldParse(engine) && output->elements[0].specialOp == LEFT_PARENTHESIS_OPERATOR) { output->elements.erase(output->elements.begin()); MathExpression* newParent = new MathExpression(engine); newParent->elements.push_back((MathElement){ component: nullptr, specialOp: LEFT_PARENTHESIS_OPERATOR, }); newParent->parent = parent; output->parent = newParent; newParent->elements.push_back((MathElement){ component: InlineConditional::Parse(output, newParent, engine) }); engine->parser->expectToken(RIGHT_PARENTHESIS); newParent->elements.push_back((MathElement){ component: nullptr, specialOp: RIGHT_PARENTHESIS_OPERATOR, }); output = newParent; break; } else if(parenthesis && token.type == RIGHT_PARENTHESIS) { output->elements.push_back((MathElement){ component: nullptr, specialOp: RIGHT_PARENTHESIS_OPERATOR, }); engine->tokenizer->getToken(); break; // quit out of loop since our statement is now over } else { // if we see an end to the statement, quit out break; } } else { if(engine->tokenizer->peekToken().type == LEFT_PARENTHESIS) { // nested math expression output->elements.push_back((MathElement){ component: Component::AfterParse(MathExpression::Parse(nullptr, output, engine), output, engine), }); expectingOperator = true; } else if(engine->tokenizer->peekToken().type == LOGICAL_NOT) { engine->tokenizer->getToken(); // absorb token output->elements.push_back((MathElement){ component: nullptr, specialOp: LOGICAL_NOT_OPERATOR, }); expectingOperator = false; } else if(engine->tokenizer->peekToken().type == BITWISE_NOT) { engine->tokenizer->getToken(); // absorb token output->elements.push_back((MathElement){ component: nullptr, specialOp: BITWISE_NOT_OPERATOR, }); expectingOperator = false; } else if(engine->tokenizer->peekToken().type == MINUS) { engine->tokenizer->getToken(); // absorb token output->elements.push_back((MathElement){ component: nullptr, specialOp: MINUS_OPERATOR, }); expectingOperator = false; } // handles literals, accesses, calls, etc else if(Component::ShouldParse(output, engine)) { output->elements.push_back((MathElement){ component: Component::Parse(output, engine), }); expectingOperator = true; } else { break; // quit out since we didn't recognize something } } } // under this circumstance, we need to check if there is more math expression to parse if(parenthesis && parent->getType() != MATH_EXPRESSION && MathExpression::ShouldParse(output, engine)) { return MathExpression::Parse(output, parent, engine); } else if(parenthesis && output->elements.back().specialOp != RIGHT_PARENTHESIS_OPERATOR) { engine->parser->error("unclosed parenthesis"); } if(expectingOperator == false) { engine->parser->error("was expecting evaluatable expression, number literal, boolean literal, or string literal"); } return output; } string MathExpression::print() { string output; MathElement lastElement; for(MathElement element: this->elements) { if(element.component != nullptr) { output += element.component->print(); } else if(element.specialOp == LEFT_PARENTHESIS_OPERATOR) { output += "("; } else if(element.specialOp == RIGHT_PARENTHESIS_OPERATOR) { output += ")"; } else if(element.specialOp == LOGICAL_NOT_OPERATOR) { output += "!"; } else if(element.specialOp == BITWISE_NOT_OPERATOR) { output += "~"; } else if(element.specialOp == MINUS_OPERATOR) { if(this-engine->parser->minified && lastElement.op.type == MINUS) { output += " -"; } else { output += "-"; } } else { if(this->engine->parser->minified) { if(element.op.type == SPC || element.op.type == TAB || element.op.type == NL || element.op.type == MODULUS) { output += " " + element.op.lexeme + " "; continue; } } output += this->engine->parser->space + element.op.lexeme + this->engine->parser->space; } lastElement = element; } if(this->parent->requiresSemicolon(this)) { output += ";"; } return output; } string MathExpression::printJSON() { string output = "{\"type\":\"MATH_EXPRESSION\",\"expression\":["; for(MathElement element: this->elements) { if(element.component != nullptr) { output += element.component->printJSON() + ","; } else if(element.specialOp == LEFT_PARENTHESIS_OPERATOR) { output += "\"(\","; } else if(element.specialOp == RIGHT_PARENTHESIS_OPERATOR) { output += "\")\","; } else if(element.specialOp == LOGICAL_NOT_OPERATOR) { output += "\"!\","; } else if(element.specialOp == BITWISE_NOT_OPERATOR) { output += "\"~\","; } else if(element.specialOp == MINUS_OPERATOR) { output += "\"-\","; } else { output += "\"" + element.op.lexeme + "\","; } } if(output.back() == ',') { output.pop_back(); } output += "]}"; return output; } map<TokenType, int> MathExpression::CreatePrecedenceMap() { map<TokenType, int> output; // use the precedence map for logical operators, even though they aren't // handled using the normal postfix/prefix calculations output[LOGICAL_OR] = 0; output[LOGICAL_AND] = 1; // use C-style operator precedence output[BITWISE_OR] = 0; output[BITWISE_XOR] = 1; output[BITWISE_AND] = 2; output[EQUAL] = 3; output[NOT_EQUAL] = 3; output[STRING_EQUAL] = 3; output[STRING_NOT_EQUAL] = 3; output[LESS_THAN_EQUAL] = 4; output[GREATER_THAN_EQUAL] = 4; output[LESS_THAN] = 4; output[GREATER_THAN] = 4; output[SHIFT_LEFT] = 5; output[SHIFT_RIGHT] = 5; output[PLUS] = 6; output[MINUS] = 6; output[MODULUS] = 7; output[ASTERISK] = 7; output[SLASH] = 7; return output; } ts::instruction::InstructionType MathExpression::TypeToOperator(TokenType type) { switch(type) { case PLUS: return ts::instruction::MATH_ADDITION; case MINUS: return ts::instruction::MATH_SUBTRACT; case ASTERISK: return ts::instruction::MATH_MULTIPLY; case SLASH: return ts::instruction::MATH_DIVISION; case MODULUS: return ts::instruction::MATH_MODULUS; case EQUAL: return ts::instruction::MATH_EQUAL; case NOT_EQUAL: return ts::instruction::MATH_NOT_EQUAL; case STRING_EQUAL: return ts::instruction::MATH_STRING_EQUAL; case STRING_NOT_EQUAL: return ts::instruction::MATH_STRING_NOT_EQUAL; case LESS_THAN_EQUAL: return ts::instruction::MATH_LESS_THAN_EQUAL; case GREATER_THAN_EQUAL: return ts::instruction::MATH_GREATER_THAN_EQUAL; case LESS_THAN: return ts::instruction::MATH_LESS_THAN; case GREATER_THAN: return ts::instruction::MATH_GREATER_THAN; case BITWISE_AND: return ts::instruction::MATH_BITWISE_AND; case BITWISE_OR: return ts::instruction::MATH_BITWISE_OR; case BITWISE_XOR: return ts::instruction::MATH_BITWISE_XOR; case SHIFT_LEFT: return ts::instruction::MATH_SHIFT_LEFT; case SHIFT_RIGHT: return ts::instruction::MATH_SHIFT_RIGHT; case APPEND: return ts::instruction::MATH_APPEND; case SPC: return ts::instruction::MATH_SPC; case TAB: return ts::instruction::MATH_TAB; case NL: return ts::instruction::MATH_NL; default: return ts::instruction::INVALID_INSTRUCTION; } } vector<PostfixElement> MathExpression::convertToPostfix(vector<MathElement*>* list, bool prefixMod) { vector<PostfixElement> postfix; stack<MathElement*> operatorStack; if(prefixMod) { reverse(list->begin(), list->end()); } MathElement* lastElement = nullptr; bool pushedSpecialOp = false; for(auto it = list->begin(); it != list->end(); ++it) { MathElement* element = *it; if(element->specialOp == LEFT_PARENTHESIS_OPERATOR || element->specialOp == RIGHT_PARENTHESIS_OPERATOR) { continue; } if(element->component != nullptr) { // if the element is an operand, push it to the stack if(pushedSpecialOp) { postfix[postfix.size() - 1].element = element; } else { postfix.push_back((PostfixElement){ element: element }); lastElement = element; } } else if(element->specialOp != INVALID_OPERATOR) { if(prefixMod) { if(!pushedSpecialOp) { postfix.pop_back(); // pop last element, because we're stealing it postfix.push_back((PostfixElement){ element: lastElement, }); } postfix[postfix.size() - 1].unary.push_back(element->specialOp); pushedSpecialOp = true; } else { if(!pushedSpecialOp) { postfix.push_back((PostfixElement){ element: nullptr, }); } postfix[postfix.size() - 1].unary.push_front(element->specialOp); pushedSpecialOp = true; } continue; } else { if( operatorStack.size() == 0 || MathExpression::Precedence[operatorStack.top()->op.type] < MathExpression::Precedence[element->op.type] ) { operatorStack.push(element); } else { // push operators onto the final stack if the operators on the operator stack are greater precedence than // the current operator while( operatorStack.size() != 0 && ( prefixMod ? MathExpression::Precedence[operatorStack.top()->op.type] > MathExpression::Precedence[element->op.type] : MathExpression::Precedence[operatorStack.top()->op.type] >= MathExpression::Precedence[element->op.type] ) ) { postfix.push_back((PostfixElement){ element: operatorStack.top() }); operatorStack.pop(); } operatorStack.push(element); } } pushedSpecialOp = false; } // push rest of operators onto the stack while(operatorStack.size() != 0) { postfix.push_back((PostfixElement){ operatorStack.top() }); operatorStack.pop(); } return postfix; } ts::InstructionReturn MathExpression::compileList(vector<MathElement*>* list, ts::Engine* engine, ts::CompilationContext context) { ts::InstructionReturn output; vector<PostfixElement> postfix = this->convertToPostfix(list, TS_INTERPRETER_PREFIX); stack<Component*> componentStack; struct Value { Component* component; ts::Instruction* math; vector<ts::instruction::UnaryOperator> unary; Value(Component* component, ts::Instruction* math) { this->component = component; this->math = math; } }; // generate the ideal instruction execution order vector<Value*> instructionList; for(PostfixElement &element: postfix) { if(element.element->component == nullptr) { // handle an operator ts::Instruction* instruction = new ts::Instruction(); instruction->type = MathExpression::TypeToOperator(element.element->op.type); instruction->mathematics.lvalueEntry = ts::Entry(); instruction->mathematics.lvalueEntry.type = ts::entry::INVALID; instruction->mathematics.rvalueEntry = ts::Entry(); instruction->mathematics.rvalueEntry.type = ts::entry::INVALID; instruction->mathematics.lvalueStackIndex = -1; instruction->mathematics.rvalueStackIndex = -1; instructionList.push_back(new Value(nullptr, instruction)); // push empty value as dummy for our result } else if(element.unary.size() != 0) { Value* value = new Value(element.element->component, nullptr); for(SpecialOperator unaryOperator: element.unary) { switch(unaryOperator) { case BITWISE_NOT_OPERATOR: { value->unary.push_back(ts::instruction::BITWISE_NOT); break; } case LOGICAL_NOT_OPERATOR: { value->unary.push_back(ts::instruction::LOGICAL_NOT); break; } case MINUS_OPERATOR: { value->unary.push_back(ts::instruction::NEGATE); break; } default: { value->unary.push_back(ts::instruction::INVALID_UNARY); break; } } } instructionList.push_back(value); } else { instructionList.push_back(new Value(element.element->component, nullptr)); } } // go through instruction stack and evaluate it, determining which entries we should turn into literals stack<Value*> evaluationStack; vector<Value*> eraseList; for(Value* value: instructionList) { if(value->component != nullptr) { evaluationStack.push(value); } else if(value->math != nullptr) { Value* lvalue; Value* rvalue; if(TS_INTERPRETER_PREFIX) { lvalue = evaluationStack.top(); evaluationStack.pop(); rvalue = evaluationStack.top(); evaluationStack.pop(); } else { rvalue = evaluationStack.top(); evaluationStack.pop(); lvalue = evaluationStack.top(); evaluationStack.pop(); } // figure out if we should cache literal in instruction if(lvalue->component != nullptr && lvalue->unary.size() == 0) { if(lvalue->component->getType() == NUMBER_LITERAL) { value->math->mathematics.lvalueEntry.setNumber(((NumberLiteral*)lvalue->component)->getNumber()); eraseList.push_back(lvalue); } else if(lvalue->component->getType() == STRING_LITERAL) { value->math->mathematics.lvalueEntry.setString(((StringLiteral*)lvalue->component)->getString()); eraseList.push_back(lvalue); } else if( lvalue->component->getType() == ACCESS_STATEMENT && ((AccessStatement*)(lvalue->component))->isLocalVariable() && ((AccessStatement*)(lvalue->component))->chainSize() == 1 ) { value->math->mathematics.lvalueStackIndex = ((AccessStatement*)(lvalue->component))->getStackIndex(context.scope); eraseList.push_back(lvalue); } } if(rvalue->component != nullptr && rvalue->unary.size() == 0) { if(rvalue->component->getType() == NUMBER_LITERAL) { value->math->mathematics.rvalueEntry.setNumber(((NumberLiteral*)rvalue->component)->getNumber()); eraseList.push_back(rvalue); } else if(rvalue->component->getType() == STRING_LITERAL) { value->math->mathematics.rvalueEntry.setString(((StringLiteral*)rvalue->component)->getString()); eraseList.push_back(rvalue); } else if( rvalue->component->getType() == ACCESS_STATEMENT && ((AccessStatement*)(rvalue->component))->isLocalVariable() && ((AccessStatement*)(rvalue->component))->chainSize() == 1 ) { value->math->mathematics.rvalueStackIndex = ((AccessStatement*)(rvalue->component))->getStackIndex(context.scope); eraseList.push_back(rvalue); } } evaluationStack.push(value); } else { evaluationStack.push(value); } } // erase values we swapped for literals for(Value* value: eraseList) { instructionList.erase(find(instructionList.begin(), instructionList.end(), value)); delete value; } // finally add instructions to output for(Value* value: instructionList) { if(value->component != nullptr) { if(value->unary.size() != 0) { int stackIndex = -1; if( value->component->getType() == ACCESS_STATEMENT && ((AccessStatement*)(value->component))->isLocalVariable() && ((AccessStatement*)(value->component))->chainSize() == 1 ) { stackIndex = ((AccessStatement*)(value->component))->getStackIndex(context.scope); } else { output.add(value->component->compile(engine, context)); } for(ts::instruction::UnaryOperator operation: value->unary) { ts::Instruction* unaryInstruction = new ts::Instruction(); unaryInstruction->type = ts::instruction::UNARY_MATHEMATICS; unaryInstruction->unaryMathematics.operation = operation; unaryInstruction->unaryMathematics.stackIndex = stackIndex; output.add(unaryInstruction); stackIndex = -1; } } else { output.add(value->component->compile(engine, context)); } } else if(value->math != nullptr) { output.add(value->math); } delete value; } return output; } ts::InstructionReturn MathExpression::compile(ts::Engine* engine, ts::CompilationContext context) { ts::InstructionReturn output; // split along logical operators vector<LogicalElement> splitElements; vector<MathElement*>* current = new vector<MathElement*>(); for(MathElement &element: this->elements) { if(element.op.type == LOGICAL_OR) { LogicalElement value1 = { list: current }; splitElements.push_back(value1); LogicalElement value2 = { list: nullptr, op: element.op }; splitElements.push_back(value2); current = new vector<MathElement*>(); } else { current->push_back(&element); } } // push last value LogicalElement tempValue = { list: current }; splitElements.push_back(tempValue); // result of split: // 5 || 1 && 6 || 7 => [(5), (||), (1 && 6), (||), (7)] ts::Instruction* noop = nullptr; vector<MathElement*> andList; // place to temporarily store && operands for compilation for(LogicalElement &value: splitElements) { if(value.list != nullptr) { // parse potential && runs ts::Instruction* andNoop = nullptr; for(MathElement* element: *value.list) { if(element->component != nullptr) { andList.push_back(element); } else if(element->op.type != LOGICAL_AND) { andList.push_back(element); } else { output.add(this->compileList(&andList, engine, context)); andList.clear(); if(andNoop == nullptr) { andNoop = new ts::Instruction(); andNoop->type = ts::instruction::NOOP; } ts::Instruction* jumpIfFalse = new ts::Instruction(); jumpIfFalse->type = ts::instruction::JUMP_IF_FALSE; jumpIfFalse->jumpIfFalse.instruction = andNoop; jumpIfFalse->jumpIfFalse.pop = false; output.add(jumpIfFalse); ts::Instruction* pop = new ts::Instruction(); pop->type = ts::instruction::POP; output.add(pop); } } output.add(this->compileList(&andList, engine, context)); andList.clear(); output.add(andNoop); } else { // if we hit an || operator, compile the relevant instructions if(noop == nullptr) { noop = new ts::Instruction(); noop->type = ts::instruction::NOOP; } ts::Instruction* jumpIfTrue = new ts::Instruction(); jumpIfTrue->type = ts::instruction::JUMP_IF_TRUE; jumpIfTrue->jumpIfTrue.instruction = noop; jumpIfTrue->jumpIfTrue.pop = false; output.add(jumpIfTrue); ts::Instruction* pop = new ts::Instruction(); pop->type = ts::instruction::POP; output.add(pop); } } output.add(noop); delete current; return output; }
true
1668e5242f96def53341614811634221fab820ce
C++
sajithkp/cs-assignment-4b
/Lab5.Question8.cpp
UTF-8
208
3.21875
3
[]
no_license
#include<iostream> using namespace std; int sum(int n) { if(n>0) return (n%10)+sum(n/10); } int main() { int x; cout<<"enter positive intiger"; cin>> x; cout<<"sum of digits of"<<x<<"is"<<sum(x); return 0; }
true
c2f914c14836e790cc98288e31be9fe378eef8f3
C++
harshp8l/deep-learning-lang-detection
/data/train/cpp/ed27438fa4277cf3a53c6eef3da7816e53f3f3aasampled_filter.cpp
UTF-8
1,204
2.609375
3
[ "MIT" ]
permissive
#include "dort/filter.hpp" #include "dort/sampled_filter.hpp" namespace dort { SampledFilter::SampledFilter(std::shared_ptr<Filter> filter, Vec2i sample_radius): sample_radius(sample_radius), filter_to_sample_radius(Vec2(sample_radius) * filter->inv_radius), samples(sample_radius.x * sample_radius.y), radius(filter->radius) { Vec2 inv_sample_radius = 1.f / Vec2(this->sample_radius); for(int32_t y = 0; y < this->sample_radius.y; ++y) { for(int32_t x = 0; x < this->sample_radius.x; ++x) { uint32_t idx = y * this->sample_radius.x + x; float filter_x = float(x) * inv_sample_radius.x * filter->radius.x; float filter_y = float(y) * inv_sample_radius.y * filter->radius.y; this->samples.at(idx) = filter->evaluate(Vec2(filter_x, filter_y)); } } } float SampledFilter::evaluate(Vec2 p) const { Vec2i sample_p = floor_vec2i(abs(p) * this->filter_to_sample_radius); if(sample_p.x >= this->sample_radius.x) { return 0.f; } if(sample_p.y >= this->sample_radius.y) { return 0.f; } uint32_t idx = sample_p.y * this->sample_radius.x + sample_p.x; return this->samples.at(idx); } }
true
7da1ec4cafd86ce6a4773317ee7d084964fe3a9a
C++
ArtyomLinnik/Study
/Lab_4/AVLImpl.cpp
UTF-8
5,536
3.1875
3
[]
no_license
#include "AVLImpl.h" #include <string> #include <iostream> #include <exception> #include <utility> using namespace std; //---------------- THE GREAT 6 ---------------------------- AVLTree::AVLImpl::AVLImpl() : root(nullptr) { } AVLTree::AVLImpl::AVLImpl(const AVLImpl &other) : root(nullptr) { other.copy(this); } AVLTree::AVLImpl::AVLImpl(AVLImpl &&other) : root(nullptr) { swap (this->root, other.root); } AVLTree::AVLImpl& AVLTree::AVLImpl::operator=(const AVLImpl &other) { if (this != &other) { other.copy(this); } return *this; } AVLTree::AVLImpl& AVLTree::AVLImpl::operator=(AVLImpl &&other) { swap (this->root, other.root); return *this; } AVLTree::AVLImpl::~AVLImpl() { clear(); } //--------------- /THE GREAT 6 ---------------------------- //--------------- PRIVATE METHODS ------------------------ int AVLTree::AVLImpl::height(const AVLNode *node) const { if (node) return node->height; return 0; } char AVLTree::AVLImpl::heightDiff(const AVLNode *node) const { return height(node->right) - height(node->left); } void AVLTree::AVLImpl::updateHeight(AVLNode *node) { int leftHeight = height(node->left); int rightHeight = height(node->right); if (leftHeight > rightHeight) node->height = leftHeight + 1; else node->height = rightHeight + 1; } AVLTree::AVLImpl::AVLNode* AVLTree::AVLImpl::findMin(AVLNode *node) const { if (node->left) return findMin(node->left); return node; } AVLTree::AVLImpl::AVLNode* AVLTree::AVLImpl::rmMin(AVLNode *node) { if (!(node->left)) return node->right; node->left = rmMin(node->left); return balance(node); } AVLTree::AVLImpl::AVLNode* AVLTree::AVLImpl::rotateL(AVLNode *node) { AVLNode *nodeR = node->right; node->right = nodeR->left; nodeR->left = node; updateHeight(nodeR->left); updateHeight(nodeR); return nodeR; } AVLTree::AVLImpl::AVLNode* AVLTree::AVLImpl::rotateR(AVLNode *node) { AVLNode *nodeL = node->left; node->left = nodeL->right; nodeL->right = node; updateHeight(nodeL->right); updateHeight(nodeL); return nodeL; } AVLTree::AVLImpl::AVLNode* AVLTree::AVLImpl::balance(AVLNode *node) { updateHeight(node); if (heightDiff(node) == 2) { if (heightDiff(node->right) == -1) node->right = rotateR(node->right); return rotateL(node); } else if (heightDiff(node) == -2) { if (heightDiff(node->left) == 1) node->left = rotateL(node->left); return rotateR(node); } return node; } AVLTree::AVLImpl::AVLNode* AVLTree::AVLImpl::ins(AVLNode *node, int key, int val) { if (!node) return new AVLNode(key, val); if (key < node->key) node->left = ins(node->left, key, val); else node->right = ins(node->right, key, val); return balance(node); } AVLTree::AVLImpl::AVLNode* AVLTree::AVLImpl::rmv(AVLNode *node, int key) { if (!node) throw exception(); if (key < node->key) { node->left = rmv(node->left, key); } else if (key > node->key) { node->right = rmv(node->right, key); } else { AVLNode *left = node->left; AVLNode *right = node->right; delete node; if (!right) return left; AVLNode *min = findMin(right); min->right = rmMin(right); min->left = left; return balance(min); } return balance(node); } void AVLTree::AVLImpl::cp(const AVLNode *node, AVLImpl *drain) const { drain->insert(node->key, node->value); if (node->left) cp(node->left, drain); if (node->right) cp(node->right, drain); } void AVLTree::AVLImpl::mkVisit(void (*visitor)(int key, int val, string s), const AVLNode *node, string s) const { if (node) visitor(node->key, node->value, s); else return; mkVisit(visitor, node->left, s + "| "); mkVisit(visitor, node->right, s + " "); } //--------------- /PRIVATE METHODS ------------------------ //--------------- PUBLIC METHODS ------------------------- // Binary tree methods bool AVLTree::AVLImpl::isEmpty() const { return !root; } void AVLTree::AVLImpl::insert(int key, int val) { root = ins(root, key, val); } void AVLTree::AVLImpl::remove(int key) { root = rmv(root, key); } int AVLTree::AVLImpl::find(int key) const { AVLNode *current = root; do { if (key < current->key) { current = current->left; } if (key > current->key) { current = current->right; } if (key == current->key) { return current->value; } } while (current->key != key); throw exception(); } void AVLTree::AVLImpl::copy(AVLImpl *drain) const { drain->clear(); cp(root, drain); } void AVLTree::AVLImpl::clear() { while (root) { remove(root->key); } } void AVLTree::AVLImpl::makeVisit(void (*visitor)(int key, int val, string s)) const //public { mkVisit(visitor, root, ""); } //--------------- /PUBLIC METHODS ------------------------- /* void ConsoleImpl::draw(AVLNode *node, string s) const { if (node) { cout << (s.length() ? (s.substr(0, s.length() - 4) + "|---") : "") << "(" << node->key << ", " << node->value << "):[" << (int)node->height << "]" << endl; draw(node->right, s + "| "); draw(node->left, s + " "); } } */
true
0b6f6fc20899c938e62a1ea9870274236112c461
C++
FootprintGL/algo
/leetcode/423-reconstruct-original-digits-from-english.cpp
UTF-8
1,320
3.3125
3
[]
no_license
class Solution { public: string originalDigits(string s) { /* * 找规律 * zero, one, two, three, four, five, six, seven, eight, nine * 偶数标志性字符z - zero, w - two, u - four, x - six, g - eight * three/eight共有一个h, eight去掉之后,h - three * five/four共有一个f,four去掉以后,f - five * seven/six共有一个s,six去掉以后,s - seven * one/zero/two/four共有o, zero/two/four去掉以后,o - one * nine/five/six/eight共有i, five/six/eight去掉以后,i - nine */ vector<int> cnt(26, 0); vector<int> out(10, 0); for (auto &c : s) cnt[c - 'a']++; out[0] = cnt['z' - 'a']; out[2] = cnt['w' - 'a']; out[4] = cnt['u' - 'a']; out[6] = cnt['x' - 'a']; out[8] = cnt['g' - 'a']; out[3] = cnt['h' - 'a'] - out[8]; out[5] = cnt['f' - 'a'] - out[4]; out[7] = cnt['s' - 'a'] - out[6]; out[1] = cnt['o' - 'a'] - out[0] - out[2] - out[4]; out[9] = cnt['i' - 'a'] - out[5] - out[6] - out[8]; string res; for (int i = 0; i < 10; i++) { for (int j = 0; j < out[i]; j++) res.push_back(i + '0'); } return res; } };
true
ae9b64422f30b8bfde0ce4b4cc0821753ba8feac
C++
elct9620/seeker
/src/Ruby/Scene.cpp
UTF-8
2,476
2.6875
3
[ "Apache-2.0" ]
permissive
// Copyright 2016 Zheng Xian Qiu #include "Seeker.h" namespace Seeker { namespace Ruby { struct mrb_data_type Scene::Type = { "Scene", &Scene::mrb_free_scene }; void Scene::init(RClass* klass) { Engine* engine = Engine::Instance(); engine->DefineMethod(klass, "initialize", &Scene::mrb_initialize, MRB_ARGS_REQ(1)); engine->DefineMethod(klass, "add", &Scene::mrb_add, MRB_ARGS_REQ(1)); engine->DefineMethod(klass, "to", &Scene::mrb_to, MRB_ARGS_REQ(1)); } void Scene::mrb_free_scene(mrb_state* mrb, void* ptr) { Scene* scene = static_cast<Scene*>(ptr); if(scene) { // Object didn't move into C++ world, free it by Ruby scene->~Scene(); mrb_free(mrb, ptr); } } mrb_value Scene::mrb_initialize(mrb_state* mrb, mrb_value self) { Scene* scene = static_cast<Scene*>(DATA_PTR(self)); if(scene) { delete scene; } mrb_value name; mrb_get_args(mrb, "S", &name); string sceneName(mrb_str_to_cstr(mrb, name)); void* p = mrb_malloc(mrb, sizeof(Scene)); scene = new (p) Scene(mrb_obj_ptr(self), sceneName); DATA_PTR(self) = scene; DATA_TYPE(self) = &Type; return self; } mrb_value Scene::mrb_add(mrb_state* mrb, mrb_value self) { Scene* scene = static_cast<Scene*>(mrb_get_datatype(mrb, self, &Type)); mrb_value object; mrb_get_args(mrb, "o", &object); // TODO: Define GameObject data type Actor* actor = static_cast<Actor*>(mrb_get_datatype(mrb, object, &Actor::Type)); if(actor && scene) { scene->Add(actor); Engine::Instance()->FreezeObject(object); } else { // TODO: create ruby error Logger::Error("Cannot add non GameObject into Scene."); } return self; } mrb_value Scene::mrb_to(mrb_state* mrb, mrb_value self) { Scene* scene = static_cast<Scene*>(mrb_get_datatype(mrb, self, &Type)); mrb_value nextScene; mrb_get_args(mrb, "o", &nextScene); Scene* _nextScene = static_cast<Scene*>(mrb_get_datatype(mrb, nextScene, &Type)); if(_nextScene) { scene->To(_nextScene); // Move GC controller into C++ Engine::Instance()->FreezeObject(nextScene); } else { // TODO: create ruby error Logger::Error("Cannot transition to non Scene object"); } return self; } // Instance Method Scene::~Scene() { } } }
true
6a74d20751e3f7fd4dee19b4ddbc2a2380788cd8
C++
mgorshkov/MoexTask
/UdpClient.cpp
UTF-8
1,716
2.8125
3
[]
no_license
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <iostream> #include <sstream> #include <string.h> #include <netdb.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include "UdpClient.h" UdpClient::UdpClient(const std::string& aHost, int aPort, const std::string& aEvent) : mHost(aHost) , mPort(aPort) , mEvent(aEvent) , mSocket(-1) { } bool UdpClient::CreateSocket() { mSocket = socket(AF_INET, SOCK_DGRAM, 0); if (mSocket < 0) { std::cerr << "error opening socket" << std::endl; return false; } return true; } bool UdpClient::Init() { if (!CreateSocket()) return false; return true; } bool UdpClient::Run() { hostent *server = gethostbyname(mHost.c_str()); if (server == nullptr) { std::cerr << "error, no such host " << mHost << std::endl; return false; } sockaddr_in serveraddr = {0}; serveraddr.sin_family = AF_INET; bcopy((char *)server->h_addr, (char *)&serveraddr.sin_addr.s_addr, server->h_length); serveraddr.sin_port = htons(mPort); char buf[BufSize] = {0}; strcpy(buf, mEvent.c_str()); socklen_t serverlen = sizeof(serveraddr); int n = sendto(mSocket, buf, mEvent.length(), 0, (struct sockaddr*)&serveraddr, serverlen); if (n < 0) { std::cerr << "error on send" << std::endl; return false; } n = recvfrom(mSocket, buf, BufSize, 0, (sockaddr*)&serveraddr, &serverlen); if (n < 0) return false; #ifdef DEBUG_PRINT std::cout << "UDP: received " << n << " bytes" << std::endl; #endif std::cout << buf << std::endl; return true; }
true
c92fcbdc0478329cb80bb72a94727e205efd49a7
C++
DKarz/Sorting-Algorithms-Comparison
/InsertionSort.h
UTF-8
886
3.25
3
[]
no_license
#include <iostream> #include <list> #include "func.h" using namespace std; #ifndef PROBLEM_2_INSERTIONSORT_H #define PROBLEM_2_INSERTIONSORT_H template<typename T> void insertionSort(list<T>& list1) { T change; int ind; for (int i = 1; i < list1.size(); i++) { change = at(list1, i); ind = i - 1; while (ind >= 0 && at(list1, ind) > change) { ChangeAt(list1, ind + 1, at(list1, ind)); ind = ind - 1; } ChangeAt(list1, ind + 1, change); } } template<typename T> void insertionSort(T array[], size_t t) { T el; for (int i = 1; i < t; i++) { el = array[i]; int j = i - 1; while (j >= 0 && array[j] > el) { array[j + 1] = array[j]; j = j - 1; } array[j + 1] = el; } } #endif //PROBLEM_2_INSERTIONSORT_H
true
516d21c2b3bbb350e7a5f05089f38d0e9f76b30f
C++
rsimari/Sorting-Linked-Lists
/stl.cpp
UTF-8
637
2.796875
3
[]
no_license
// stl.cpp #include "lsort.h" #include <algorithm> #include <vector> #include <iostream> void stl_sort(List &l, bool numeric) { Node* temp = l.head; std::vector<Node*> vec; while (temp != nullptr) { vec.push_back(temp); temp = temp->next; } if (numeric) std::sort(vec.begin(), vec.end(), node_number_compare); else std::sort(vec.begin(), vec.end(), node_string_compare); l.head = vec[0]; temp = l.head; for (std::vector<Node*>::iterator it = vec.begin()+1; it != vec.end(); it++) { temp->next = (*it); temp = temp->next; } temp->next = nullptr; } // vim: set sts=4 sw=4 ts=8 expandtab ft=cpp:
true
c81ffa72a022086f30aeb338aca9babd79c0062c
C++
shreevatsa/misc-math
/qr-TU1yLp/calculate.cc
UTF-8
386
2.890625
3
[]
no_license
#include <cstdio> #include "FJ64_16k.h" // For a fast `is_prime` function: http://ceur-ws.org/Vol-1326/020-Forisek.pdf int main() { double ans = 0.5; for (uint64_t p = 0; ; ++p) { if (p % 1000000 == 0) { printf("%lld %.9f\n", p, ans); } if (!is_prime(p)) continue; if (p % 3 == 1) ans *= (p - 2.0) / (p - 1.0); if (p % 3 == 2) ans *= p / (p - 1.0); } }
true
eba2104f7d5ec9205b02f89e3d62669ac82ce471
C++
Neal854386/inter
/JumpGame.h
UTF-8
1,533
3.4375
3
[]
no_license
/* Author: Annie Kim, anniekim.pku@gmail.com Date: Apr 21, 2013 Update: Jul 12, 2013 Problem: Jump Game Difficulty: Easy Source: http://leetcode.com/onlinejudge#question_55 Notes: Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Determine if you are able to reach the last index. For example: A = [2,3,1,1,4], return true. A = [3,2,1,0,4], return false. Solution: Updated solution: try every reachable index. Thank to Wenxin Xing for kindly feedback and pointing out my big mistake:) */ // greedy class Solution { public: bool canJump(int A[], int n) { int start = 0, end = 0; while (start <= end && end < n-1) { end = max(end, start + A[start]); start++; } return end >= (n-1); } }; class Solution { public: bool canJump(int A[], int n) { int max_index = 0; for (int i = 0; i < n; i++) { if (i <= max_index) { max_index = max(max_index, i + A[i]); } } return max_index >= n - 1; } }; // dp class Solution { public: bool canJump(int A[], int n) { int dp[n]; dp[0] = 0; for(int i = 1; i < n; i++) { dp[i] = max(dp[i - 1], A[i - 1]) - 1; if(dp[i] < 0) { return false; } } return dp[n - 1] >=0; } };
true
bab30dd19ebc0a743386fe32c4d7b632711b81d5
C++
Irvanabdurrahman/My-Code
/Algoritma-dan-Pemrograman-2/Praktikum-11/pwrsn.cpp
UTF-8
873
3.0625
3
[]
no_license
#include <iostream.h> #include <conio.h> class pengaturan { protected: int alas, tinggi; public: void luas (int a, int b) {alas=a;tinggi=b;} }; class keluaran { public: void output (int i); }; void keluaran::output (int i) { cout <<"Outputnya = " << i <<endl; } class segitiga: public pengaturan, public keluaran { public: int area (void) {return (alas * tinggi * 0.5);} }; class segitiga_2:public pengaturan, public keluaran { public: int area (void) {return (alas * tinggi * 0.5);} }; void main () { clrscr(); cout <<"_______________________________________\n"; cout <<"\nMateri : Inheritance\n"; cout <<"Nama : Irvan Abdurrahman | 4510210003\n"; cout <<"Update : 6 Juni 2011\n"; cout <<"_______________________________________\n"; segitiga sg3; segitiga_2 segi3; sg3.luas (8,5); segi3.luas (4,5); sg3.output (sg3.area()); segi3.output (segi3.area()); getch(); }
true
523f2e1df98de07d721ab62a10c5d40da22929b6
C++
k-t-l-h/TP_Algorithm
/module_1/task_3_1.cpp
UTF-8
2,503
3.71875
4
[]
no_license
// // Created by ktlh on 10.03.2021. // /* * 3_1. Реализовать очередь с динамическим зацикленным буфером. */ #include <iostream> #define DEFAULT_SIZE 16 using namespace std; class Queue { public: ~Queue(); Queue(const Queue&) = delete; Queue(const Queue&&) = delete; Queue& operator=(const Queue&) = delete; Queue& operator=(Queue&&) = delete; Queue() : buffer_size(0), head(0), tail(0), size(0), buffer(nullptr) {} void push_back(int value); int pop_front(); private: int head; int tail; int* buffer; //максимальный размер int buffer_size; //реальный размер int size; void resize(); }; //увеличиваем наш буффер void Queue::resize() { if (buffer == nullptr) { buffer = new int[DEFAULT_SIZE]; buffer_size = DEFAULT_SIZE; return; } //увеличиваем сразу в два раза int new_size = buffer_size << 1; int* new_buffer = new int[new_size]; for (int i = 0; i < buffer_size; i++) { new_buffer[i] = buffer[(i + head) % buffer_size]; } delete[] buffer; buffer = new_buffer; head = 0; tail = size; buffer_size = new_size; } Queue::~Queue() { delete[] buffer; } void Queue::push_back(int value) { //если достигнут потолок if (size == buffer_size) { resize(); } buffer[tail] = value; tail = (tail + 1) % buffer_size; size++; }; int Queue::pop_front() { //если нет элементов if (!size) { return -1; } int value = buffer[head]; head = (head + 1) % buffer_size; size--; //облегчаем жизнь на будущее if (!size) { head = 0; tail = 0; } return value; }; int main() { Queue queue; int n; cin >> n; for (int i = 0; i < n; ++i) { int operation; int reference; int value; cin >> operation >> reference; switch (operation) { // pop case 2: value = queue.pop_front(); if (value != reference) { cout << "NO" << '\n'; return 0; } break; // push case 3: queue.push_back(reference); break; } } cout << "YES" << '\n'; return 0; }
true
08eb5f335b54c8067dfd38c24c0d8d8272d64586
C++
skanda99/Hackerrank-Leetcode
/leetcode375.cpp
UTF-8
621
3.125
3
[]
no_license
// problem: "https://leetcode.com/problems/guess-number-higher-or-lower-ii/" class Solution { public: int getMoneyAmount(int n) { vector<vector<int>>V(n+1,vector<int>(n+1,-1)); return getMinCost(1,n,V); } int getMinCost(int i,int j,vector<vector<int>>&V) { if(i >= j) return 0; if(V[i][j] == -1) { int k; V[i][j] = INT_MAX; for(k=i;k!=j+1;k++) V[i][j] = min(V[i][j],max(getMinCost(i,k-1,V),getMinCost(k+1,j,V))+k); } return V[i][j]; } };
true
98161e6e579f9b1556d49a65f57b3b1966ddc581
C++
AbeerVaishnav13/PADP-lab-programs
/sieve/sieve.cpp
WINDOWS-1252
2,653
3
3
[]
no_license
#include<math.h> #include<string.h> #include<omp.h> #include<iostream> using namespace std; int N = 10000; int number_threads = 2; double t = 0.0; inline long Strike( bool composite[], long i,long stride, long limit ) { for(; i <= limit; i += stride) composite[i] = true; return i; } long longCacheUnfriendlySieve( long n ) { long count = 0; long m = (long)sqrt((double)n); bool *composite = new bool[n+1]; memset( composite, 0, n ); t = omp_get_wtime(); for(long i = 2; i <= m; ++i) if(!composite[i]) { ++count; // Strike walks array of size n here. Strike( composite, 2*i, i, n ); } for( long i=m+1; i<=n; ++i ) if( !composite[i] ){ ++count; } t = omp_get_wtime() - t; delete[] composite; return count; } long longCacheFriendlySieve( long n ) { long count = 0; long m = (long)sqrt((double)n); //m=root n bool* composite = new bool[n+1]; memset( composite, 0, n ); long* factor = new long[m]; //factor holds all primes encountered in first segment(all p) long* striker = new long[m]; //holds the first multiple of all primes encountered in first segment (all 2p) long n_factor = 0; t= omp_get_wtime(); for( long i=2; i<=m; ++i ) //find all primes in first segment if( !composite[i] ) { ++count; striker[n_factor] = Strike( composite, 2*i, i, m ); //limit is sqrt n factor[n_factor++] = i; } // Chops sieve into windows of size sqrt(n) for( long window=m+1; window<=n; window+=m ) { long limit = min(window+m-1,n); //either window is of size m or size n omp_set_num_threads(number_threads); #pragma omp parallel for shared(striker, factor, composite, limit, n_factor) reduction(+:count) for( long k=0; k<n_factor; ++k ) // Strike walks window of size sqrt(n) here. striker[k] = Strike( composite, striker[k], factor[k],limit ); //get first multiple of all primes encountered in this segment to use for next segment for( long i=window; i<=limit; ++i ) if( !composite[i] ) //count all primes within one segment ++count; } t = omp_get_wtime() - t; delete[] striker; delete[] factor; delete[] composite; return count; } int main() { cout << "Enter N: "; cin >> N; cout << "Enter number of threads: "; cin >> number_threads; //long count = longCacheUnfriendlySieve(N); long count = longCacheFriendlySieve(N); cout << count << endl; cout << "Time : " << t << endl; }
true
e0b21ea29dc58c9cb3e2f5d116d31ffce1b2361c
C++
RISHITA189/RISHITAKATTA
/Day6/CString/date.h
UTF-8
261
2.578125
3
[]
no_license
#pragma once class Date { int dd, mm, yy; public: Date(); Date(int dd , int mm ,int yy); void accept_date(); void show_date(); /*friend istream& operator >> (istream& in, Date& c); friend ostream& operator << (ostream& out, Date& c);*/ };
true
1072aae03aa55352b288810fd140603fffcf6cd7
C++
XintongHu/leetcode
/CPP/GrayCode.cpp
UTF-8
342
2.53125
3
[]
no_license
class Solution { public: vector<int> grayCode(int n) { vector<int> ans; int base = 1; ans.push_back(0); for (int i = 1; i <= n; ++i) { for (int j = base - 1; j >= 0; --j) { ans.push_back(ans[j] + base); } base *= 2; } return ans; } };
true
91a10ed5742ddce8a653c3fd6cd4bf6871537fcc
C++
Akash16s/Tough_Questions
/SubstringRecursion.cpp
UTF-8
512
3.375
3
[]
no_license
// substrings using recurssion //find all the substring of string using recursion #include<iostream> using namespace std; void Subsequence(char *input,int i,char *output,int j){ //base case if(input[i]=='\0'){ output[j]='\0'; cout<<output<<endl; return ; } //first time output[j]=input[i]; Subsequence(input,i+1,output,j+1); //second time Subsequence(input,i+1,output,j); } int main(){ char a[]="abc"; char output[100]; Subsequence(a,0,output,0); return 0; }
true
036b5e114d017e03d11fffeea384ff7c487d4239
C++
junierr/hdoj
/牛客多校/1A.cpp
GB18030
879
2.9375
3
[]
no_license
/* һpʹab1pӴСֵ±ͬ ǵǰλߵһС±+1 ȫͬ */ #include<cstdio> #include<cstring> using namespace std; int a[100005],b[100005]; int l1[100005],l2[100005]; int main(){ int n; while(~scanf("%d",&n)){ for(int i=1;i<=n;i++) l1[i]=l2[i]=0; for(int i=1;i<=n;i++){ scanf("%d",&a[i]); l1[i]=i; while(l1[i]>0&&a[l1[i]-1]>=a[i]) l1[i]=l1[l1[i]-1]; } for(int i=1;i<=n;i++){ scanf("%d",&b[i]); l2[i]=i; while(l2[i-1]>0&&b[l2[i]-1]>=b[i]) l2[i]=l2[l2[i]-1]; } int ans=1; for(int i=1;i<=n;i++) printf("%d ",l1[i]); printf("\n"); for(int i=1;i<=n;i++) printf("%d ",l2[i]); printf("\n"); for(int i=1;i<=n;i++){ if(l1[i]!=l2[i]) break; ans=i; } printf("%d\n",ans); } return 0; }
true
b6e976126a1b4db2350f38c2c0afdfeed03551d1
C++
KingNormac/CPlusPlus-Opengl-Dragonbones
/DragonBones/DragonBones/DragonBones/objects/SkinData.h
UTF-8
826
2.796875
3
[]
no_license
#ifndef SKINDATA_H #define SKINDATA_H #include "SlotData.h" #include <string> #include <vector> namespace DragonBones { class SkinData { public: std::vector<SlotData*> _slotDataList; std::string name; //std::vector<SlotData*> getSlotDataList(){return _slotDataList;} SkinData() { name="";} ~SkinData() { for(SlotData* data : _slotDataList) { delete[] data; } _slotDataList.clear(); } SlotData* getSlotData(std::string slotName) { for(SlotData* data : _slotDataList) { if(data) { if(data->name== slotName) { return data; } } } //printf("USED! \n"); return 0; } void addSlotData(SlotData* slotData) { if(slotData) { _slotDataList.push_back(slotData); } else { printf("Tried to enter bad slotData into skinData \n"); } } }; }; #endif
true
2b565eabba4a285a0fd74bef8c554abfe4125c8b
C++
mmcclain117/School-Code
/College/Cplus-Book-Code/Catchup/pointers.cpp
UTF-8
1,608
3.796875
4
[ "Apache-2.0" ]
permissive
/* * Created on: Feb 19, 2018 * Author: Master Ward */ #include <iostream> #include <string> #include <memory> // Used for smart pointers using namespace std; /* Take into note that array pointers are not always sorted */ string *getFullName(string[]); int pointing() { int x[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50 }; int *ptr = nullptr; ptr = x; /* Illegal because not Compatible data types * float myFloat; * int *ft = &myFloat; */ int size = static_cast<int>(sizeof(x) / 4); // int *pint = &size; for (int count = 0; count < size; count++) { cout << *(x + count) << " "; } cout << endl << "Is the same as\n"; for (int count = 0; count < size; count++) { cout << x[count] << " "; } cout << endl << "And can use PTR reference\n"; for (int count = 0; count < size; count++) { cout << *ptr << " "; ptr++; } cout << *ptr << endl << endl; delete ptr; // Can only delete pointers // ptr = 12; // Can't Change the type cout << *ptr << endl; string fn[3]; string *arr = getFullName(fn); // cout << sizeof(arr); // Accurate on the size for once for (int count = 0; count < 3; count++) { cout << *arr++; } /* Smart pointers: Delete when done */ unique_ptr<int> po(new int); *po = 99; // Needs * to declare pointer cout << *po << endl; return 0; } /* Find the full name and return pointer to it */ string *getFullName(string fullname[]) { cout << "Enter first name: " << endl; fullname[0] = "John\n"; cout << "Enter middle name: " << endl; fullname[1] = "Long\n"; cout << "Enter last name: " << endl; fullname[2] = "Board\n"; return fullname; }
true