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
eca9d817d12ed4d3014ae6a100303a6c0b6583d3
C++
NicolaDes/ariadneExample
/lock_system/analysis.hh
UTF-8
3,877
2.796875
3
[]
no_license
#pragma once #include "ariadne.h" using namespace Ariadne; /// Forward declarations, used only to properly organize the source file void finite_time_upper_evolution(HybridAutomatonInterface &system, HybridBoundedConstraintSet &initial_set, int verbosity, bool plot_results); void finite_time_lower_evolution(HybridAutomatonInterface &system, HybridBoundedConstraintSet &initial_set, int verbosity, bool plot_results); HybridEvolver::EnclosureListType _finite_time_evolution(HybridAutomatonInterface &system, HybridBoundedConstraintSet &initial_set, Semantics semantics, int verbosity); // The main method for the analysis of the system // Since the analyses are independent, you may comment out any one if you want // to focus on specific ones. void analyse(HybridAutomatonInterface &system, HybridBoundedConstraintSet &initial_set, int verbosity, bool plot_results) { cout << "1/2: Finite time upper evolution... " << endl << flush; finite_time_upper_evolution(system, initial_set, verbosity, plot_results); cout << "2/2: Finite time lower evolution... " << endl << flush; finite_time_lower_evolution(system, initial_set, verbosity, plot_results); } // Performs finite time evolution. HybridEvolver::EnclosureListType _finite_time_evolution(HybridAutomatonInterface &system, HybridBoundedConstraintSet &initial_set, Semantics semantics, int verbosity) { // Creates an evolver HybridEvolver evolver(system); evolver.verbosity = verbosity; evolver.settings().set_maximum_step_size(0.1); // The time step size to be used // Creates a list of initial enclosures from the initial set. // This operation is only necessary since we provided an initial set expressed as a constraint set HybridEvolver::EnclosureListType initial_enclosures; HybridBoxes initial_set_domain = initial_set.domain(); for (HybridBoxes::const_iterator it = initial_set_domain.locations_begin(); it != initial_set_domain.locations_end(); ++it) { if (!it->second.empty()) { initial_enclosures.adjoin(HybridEvolver::EnclosureType(it->first, Box(it->second.centre()))); } } // The maximum evolution time, expressed as a continuous time limit along with a maximum number of events // The evolution stops for each trajectory as soon as one of the two limits are reached HybridTime evol_limits(44.0, 20); // Performs the evolution, saving only the reached set of the orbit HybridEvolver::EnclosureListType result; for (HybridEvolver::EnclosureListType::const_iterator it = initial_enclosures.begin(); it != initial_enclosures.end(); ++it) { HybridEvolver::OrbitType orbit = evolver.orbit(*it, evol_limits, semantics); result.adjoin(orbit.reach()); } return result; } // Performs finite time upper evolution void finite_time_upper_evolution(HybridAutomatonInterface &system, HybridBoundedConstraintSet &initial_set, int verbosity, bool plot_results) { // Performs the evolution, saving only the reached set of the orbit HybridEvolver::EnclosureListType reach = _finite_time_evolution(system, initial_set, UPPER_SEMANTICS, verbosity); // Plots the reached set specifically if (plot_results) { PlotHelper plotter(system); plotter.plot(reach, "upper_reach"); } } // Performs finite time lower evolution. void finite_time_lower_evolution(HybridAutomatonInterface &system, HybridBoundedConstraintSet &initial_set, int verbosity, bool plot_results) { // Performs the evolution, saving only the reached set of the orbit HybridEvolver::EnclosureListType reach = _finite_time_evolution(system, initial_set, LOWER_SEMANTICS, verbosity); // Plots the reached set specifically if (plot_results) { PlotHelper plotter(system); plotter.plot(reach, "lower_reach"); } }
true
36c59e2b423c8f00067bf9168cfddc31cfb29b3a
C++
SiliconSloth/Metro
/include/metro/credentials.h
UTF-8
5,899
3.265625
3
[ "MIT" ]
permissive
/* * This file contains code regarding credential handling. */ #pragma once // A version of memset that won't be optimized away by the compiler. // Used for overwriting sensitive memory for security reasons. typedef void* (*memset_t)(void*, int, size_t); static volatile memset_t memset_volatile = memset; namespace metro { /** * Represents supported credential types */ enum CredentialType{EMPTY, DEFAULT, USERPASS, SSH_KEY}; /** * Store credentials of various types so that git_cred objects * can be generated from them. * Starts empty and is initialized as needed with store methods. */ class CredentialStore { CredentialType type = EMPTY; string username; string password; string publicKey; string privateKey; public: // Whether those credentials have been tried and proved invalid bool tried = false; /** * Sets the store type to use whatever the default is. */ void store_default(); /** * Sets the store type to require a username and a password. * @param username Username to enter into store. * @param password Password to enter into store. */ void store_userpass(string username, string password); /** * Sets the store type to SSH, requiring valid SSH keys * @param username URL username (usually "git"). * @param password Password for SSH private key. * @param publicKey Path to public key. * @param privateKey Path to private key. */ void store_ssh_key(string username, string password, string publicKey, string privateKey); /** * Checks if the store is currently empty. * @return True if store is empty. */ bool empty() { return type == EMPTY; }; /** * Create git_cred object from the information in this store. * @param cred Credential object to convert to. * @returns Git error code. */ int to_git(git_cred **cred); /** * Clears the store of the current contents */ void clear(); ~CredentialStore(); }; // Tuple of Credential Store and Repository struct CredentialPayload { CredentialStore *credStore; const Repository *repo; }; // Tuple of URL and Credential Store struct HelperForeachPayload { const string *url; CredentialStore *credStore; }; /** * Callback for Git operations that request credentials. * Tries to get credentials from each helper specified in the config in turn, * then defaults to manual credential entry. The obtained credentials pointer is written * back to the location specified in the payload as well as the normal cred parameter. * * If the credentials pointer in the payload is already non-null it is returned * instead of acquiring new credentials, allowing credential reuse. */ int acquire_credentials(git_cred **cred, const char *url, const char *username_from_url, unsigned int allowed_types, void *payload); /** * Iterate over the helpers specified in a repo's config until one of them * successfully provides credentials for the specified URL. * * @param repo The repository to use for config. * @param url The URL to connect to. * @param credStore Credential store used to put credentials found into. */ void credentials_from_helper(const Repository *repo, const string& url, CredentialStore& credStore); /** * Try to obtain credentials for the specified URL from the specified credential helper. * The helper name should be in config value format. * * @param helper Which helper to use. * @param url The URL to connect to. * @param credStore Credential store used to put credentials found into. */ void credentials_from_helper(const string& helper, const string& url, CredentialStore& credStore); /** * Try to retrieve a user-specified command to use for requesting passwords from Git's usual locations. * First try the GIT_ASKPASS environment variable, then the core.askPass config value, * then the SSH_ASKPASS environment variable. * If no value could be found an empty string is returned. * * @param repo The repository to use the config for, or nullptr to use default. * @return The user-specified command for requesting passwords from git, or an empty string if none found. */ string get_askpass_cmd(const Repository *repo); /** * Prompt the user for input using the specified askpass command. * If the command fails or an empty command string is provided, defaults to terminal entry. * If isPassword is set then terminal entry will hide the user's input. * * @param cmd Command to prompt the user using. * @param prompt Prompt to present to the user. * @param isPassword Whether the input is for a password and should not be shown visually. * @param out The input the user inputted into the prompt. */ void read_from_askpass(const string& cmd, const string& prompt, bool isPassword, string& out); /** * Request credentials from the user on the command line. * * @param repo The repo to use to decide what credential type to use. * @param url The url for the manual credential entry. * @param username_from_url The username receieved from the url. * @param allowed_types Types of credential input that can be used. * @param credStore The credential store the result will be put into. */ void manual_credential_entry(const Repository *repo, const char *url, const char *username_from_url, unsigned int allowed_types, CredentialStore& credStore); }
true
2df32547ed24ddc59e8b8f96070bc38ef87d9c19
C++
sdonte980/MileStone2
/Split.h
UTF-8
629
2.953125
3
[]
no_license
#ifndef MILESTONE2_SPLIT_H #define MILESTONE2_SPLIT_H #include <string> #include <vector> using namespace std; class Split{ public: static vector<string> split(string line, string delimiter) { vector<string> data; size_t position = 0; while ((position = line.find(delimiter)) != string::npos) { if (!line.substr(0, position).empty()) { data.push_back(line.substr(0, position)); } line.erase(0, position + delimiter.length()); } data.push_back(line.substr(0, position)); return data; } }; #endif //MILESTONE2_SPLIT_H
true
6aaf4da30c469a22f012dbf0f5db4fa076add41a
C++
balos1/opengl_skybox_game
/src/ViewController.h
UTF-8
1,039
2.71875
3
[ "MIT" ]
permissive
//FileName: viewcontroller.h //Programmer: Dan Cliburn, Cody Balos //Date: 11/15/2016 //Purpose: This file defines the header for the Viewcontroller class //This class is responsible for setting up SDL and handing user input. #pragma once #include <SDL.h> //Include SDL.h before glm.hpp #include <glm.hpp> #include "ViewModel.h" using namespace glm; class Viewcontroller { enum Axis { X, Y, Z }; public: Viewcontroller(); bool Init(game::Levels level); void HomeScreen(); void display(); void Run(game::Levels level); bool handleEvents(SDL_Event *theEvent); void updateLookAt(); void LookDownAxis(Axis axis); void ResetView(); private: // state bool quit; //Variables to control user movement vec3 displacement; // camera displacement = glman displacement vec3 eye; vec3 aim; vec3 up; mat4 view_matrix; double MOVEANGLE; double LOOKANGLE; double moveForward; double moveSideways; double baseX; double baseY; // main model ViewModel theWorld; // sdl stuff SDL_Window *window; SDL_GLContext ogl4context; };
true
602d6be1ed70501a53e6cd3dd096a23f196969fe
C++
artugal28373/CompetitveProgramming
/Online-Judge-Solutions/SPOJ/FISHES - Finding Fishes.cpp
UTF-8
6,925
2.609375
3
[]
no_license
/* SPOJ FISHES Author: Tanmoy Datta Idea: - The first simplification is in the summation formula as follows SUM { Xi * (V . Vi) } = SUM {V . Xi Vi} = V . SUM {Xi Vi} - As you can observe, Xi Vi is constant, so we can precalculate this vector by multiplying each vector by its Xi and adding them all, let's name this vector "Combined vector" - Now the problem is reduced to the following: we need to find a subrectangle, where the dot product of its V with the combined vector is maximum - The second observation is that the dot product is equivalent to the sum of the same subrectangle with transformed values, where each value is replaced with its corresponding value in the combined vector (try this on paper) - Now the problem is reduced to a standard max subrectangle sum in 2D grid, than can be solved in O(n ^ 3) using precalculations - We can easily find maximum subrectangle sum in 2D grid in o(n^4) but we can use sum optimization to reduce it in O(n^3) - First thing is we can calculate maximum sub-array sum in 1D array in O(n) complexity by using cumulative sum and subtract minimum value found so far before this current index. The answer is maximum of (cumulative_sum[i]-minimum_value_found_so_far) for every i. - Now at first we calculate cumulative sum of every column of 2D array. - Then we can fix two row value in this column cumulative sum array in O(n^2) and then we get a 1D array of column sum of between this two row. - Now we can calculate maximum sub array sum in this 1D array in O(n). So overall complexity is O(n^3) (Some part of this solution idea is taken from this url https://github.com/yelghareeb/problem_solving/blob/master/SPOJ/SPOJ%20FISHES.cpp) */ #include <bits/stdc++.h> // #include <ext/pb_ds/assoc_container.hpp> // #include <ext/pb_ds/tree_policy.hpp> #define pii pair <int,int> #define pll pair <long long,long long> #define sc scanf #define pf printf #define Pi 2*acos(0.0) #define ms(a,b) memset(a, b, sizeof(a)) #define pb(a) push_back(a) #define MP make_pair #define db double #define ll long long #define EPS 10E-10 #define ff first #define ss second #define sqr(x) (x)*(x) #define VI vector <int> #define MOD 1000000007 #define fast_cin ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0) #define SZ(a) (int)a.size() #define sf(a) scanf("%d",&a) #define sfl(a) scanf("%lld",&a) #define sff(a,b) scanf("%d %d",&a,&b) #define sffl(a,b) scanf("%lld %lld",&a,&b) #define sfff(a,b,c) scanf("%d %d %d",&a,&b,&c) #define sfffl(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define stlloop(v) for(__typeof(v.begin()) it=v.begin();it!=v.end();it++) #define UNIQUE(v) (v).erase(unique((v).begin(),(v).end()),(v).end()) #define POPCOUNT __builtin_popcountll #define RIGHTMOST __builtin_ctzll #define LEFTMOST(x) (63-__builtin_clzll((x))) #define NUMDIGIT(x,y) (((vlong)(log10((x))/log10((y))))+1) #define NORM(x) if(x>=mod) x-=mod;if(x<0) x+=mod; #define ODD(x) (((x)&1)==0?(0):(1)) #define loop(i,n) for(int i=0;i<n;i++) #define loop1(i,n) for(int i=1;i<=n;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define RREP(i,a,b) for(int i=a;i>=b;i--) #define TEST_CASE(t) for(int z=1;z<=t;z++) #define PRINT_CASE printf("Case %d: ",z) #define LINE_PRINT_CASE printf("Case %d:\n",z) #define CASE_PRINT cout<<"Case "<<z<<": " #define all(a) a.begin(),a.end() #define intlim 2147483648 #define infinity (1<<28) #define ull unsigned long long #define gcd(a, b) __gcd(a, b) #define lcm(a, b) ((a)*((b)/gcd(a,b))) #define D(x) cerr << __LINE__ << ": " << #x << " = " << (x) << '\n' #define DD(x,y) cerr << __LINE__ << ": " << #x << " = " << x << " " << #y << " = " << y << '\n' #define DDD(x,y,z) cerr << __LINE__ << ": " << #x << " = " << x << " " << #y << " = " << y << " " << #z << " = " << z << '\n' #define DBG cerr << __LINE__ << ": Hi" << '\n' using namespace std; //using namespace __gnu_pbds; //typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set; /*----------------------Graph Moves----------------*/ //const int fx[]={+1,-1,+0,+0}; //const int fy[]={+0,+0,+1,-1}; //const int fx[]={+0,+0,+1,-1,-1,+1,-1,+1}; // Kings Move //const int fy[]={-1,+1,+0,+0,+1,+1,-1,-1}; // Kings Move //const int fx[]={-2, -2, -1, -1, 1, 1, 2, 2}; // Knights Move //const int fy[]={-1, 1, -2, 2, -2, 2, -1, 1}; // Knights Move /*------------------------------------------------*/ /*-----------------------Bitmask------------------*/ //int Set(int N,int pos){return N=N | (1<<pos);} //int reset(int N,int pos){return N= N & ~(1<<pos);} //bool check(int N,int pos){return (bool)(N & (1<<pos));} /*------------------------------------------------*/ int r,c,h,t,k; int grid[102][102]; int v[505]; ll csum[102][102]; ll csum1d[102]; int main() { //#ifndef ONLINE_JUDGE // freopen("in.txt","r",stdin); //// freopen("out.txt","w",stdout); //#endif int cas; sf(cas); TEST_CASE(cas) { scanf("%d %d %d %d %d",&r,&c,&h,&k,&t); for(int i=1; i<=r; i++) { for(int j=1; j<=c; j++) { sf(grid[i][j]); } } ms(v,0); for(int i=0; i<t; i++) ///Taking input vectors and combining them in one vector array v. { int x,a; sf(x); for(int j=1; j<=k; j++) { sf(a); a*=x; v[j]+=a; } } for(int i=1; i<=r; i++) ///Replacing each cell value of image by it's corresponding vector value { for(int j=1; j<=c; j++) { grid[i][j]=v[grid[i][j]]; } } for(int j=1; j<=c; j++) ///Calculating cumulative sum for every column { csum[0][j]=0; for(int i=1; i<=r; i++) { csum[i][j]=csum[i-1][j]+grid[i][j]; } } ll ans=LONG_MIN; for(int i=1; i<=r; i++) ///Finding 2D rectangle sum in O(n^3) { for(int j=i; j<=r; j++) { ll mini=0; for(int k=1; k<=c; k++) { csum1d[k]=csum[j][k]-csum[i-1][k]; csum1d[k]+=csum1d[k-1]; ans=max(ans,csum1d[k]-mini); mini=min(mini,csum1d[k]); } } } printf("Case #%d:\n%lld\n",z,ans+h); } return 0; }
true
084d30de9ddc438c5a8f2584c99580384487aadc
C++
lip23/growing
/hdu/1175_连连看.cpp
UTF-8
4,187
3.0625
3
[]
no_license
#include <iostream> using namespace std; struct node { int pos1; int pos2; int count; int direct; }; class stack { public: stack(); ~stack(){}; void push(int,int,int,int); void pop(int&,int&,int&,int&); bool isempty(); private: int top; node data[2002]; }; int main() { int m,n; while(cin>>n>>m,n+m!=0) { int** graph=new int* [n]; for(int i=0;i<n;i++) graph[i]=new int[m]; for(i=0;i<n;i++) for(int j=0;j<m;j++) cin>>graph[i][j]; int op,s1,s2,e1,e2; cin>>op; for(int ii=0;ii<op;ii++) { cin>>s1>>s2>>e1>>e2; int value1=graph[s1-1][s2-1]; int value2=graph[e1-1][e2-1]; if(value1!=value2||value1==0||value2==0) cout<<"NO"<<endl; else { int cur1=s1-1,cur2=s2-1; graph[s1-1][s2-1]=0; graph[e1-1][e2-1]=0; stack s; int c=0; int direction=0; do { cout<<"direction="<<direction<<endl; cout<<"count="<<c<<endl; if(cur2+1<m&&graph[cur1][cur2+1]==0&&(direction==1||(direction!=1&&c<2))) { cout<<"11111111111"<<endl; s.push(cur1,cur2,c,direction); graph[cur1][cur2]=-1; cout<<"please input"<<endl; int temp; cin>>temp; cout<<"cur1="<<cur1<<" cur2="<<cur2<<endl; cur2++; cout<<"cur1="<<cur1<<" cur2="<<cur2<<endl; //cout<<"cur2="<<cur2<<endl; if(direction!=0&&direction!=1) c++; direction=1; } else if(cur1+1<n&&graph[cur1+1][cur2]==0&&(direction==2||(direction!=2&&c<2))) { cout<<"22222222222222"<<endl; s.push(cur1,cur2,c,direction); graph[cur1][cur2]=-1; cout<<"please input"<<endl; int temp; cin>>temp; cout<<"cur1="<<cur1<<" cur2="<<cur2<<endl; cur1++; cout<<"cur1="<<cur1<<" cur2="<<cur2<<endl; //cout<<"cur1="<<cur1<<endl; if(direction!=0&&direction!=2) c++; direction=2; } else if(cur2-1>=0&&graph[cur1][cur2-1]==0&&(direction==3||(direction!=3&&c<2))) { cout<<"3333333333333333333"<<endl; s.push(cur1,cur2,c,direction); graph[cur1][cur2]=-1; cout<<"please input"<<endl; int temp; cin>>temp; cout<<"cur1="<<cur1<<" cur2="<<cur2<<endl; cur2--; cout<<"cur1="<<cur1<<" cur2="<<cur2<<endl; //cout<<"cur2="<<cur2<<endl; if(direction!=0&&direction!=3) c++; direction=3; } else if(cur1-1>=0&&graph[cur1-1][cur2]==0&&(direction==4||(direction!=4&&c<2))) { cout<<"444444444444444444"<<endl; s.push(cur1,cur2,c,direction); graph[cur1][cur2]=-1; cout<<"please input"<<endl; int temp; cin>>temp; cout<<"cur1="<<cur1<<" cur2="<<cur2<<endl; cur1--; cout<<"cur1="<<cur1<<" cur2="<<cur2<<endl; //cout<<"cur1="<<cur1<<endl; if(direction!=0&&direction!=4) c++; direction=4; } else { cout<<"5555555555555555555555"<<endl; if(s.isempty()) break; int temp; cin>>temp; cout<<"cur1="<<cur1<<" cur2="<<cur2<<endl; graph[cur1][cur2]=-1; s.pop(cur1,cur2,c,direction); cout<<"cur1="<<cur1<<" cur2="<<cur2<<endl; cout<<"direc="<<direction<<endl; cout<<"count="<<c<<endl; } }while(cur1!=e1-1||cur2!=e2-1); if(s.isempty()) cout<<"NO"<<endl; else cout<<"YES"<<endl; for(i=0;i<n;i++) for(int k=0;k<m;k++) if(graph[i][k]==-1) graph[i][k]=0; //cout<<graph[i][k]<<' '; //cout<<endl; graph[s1-1][s2-1]=value1; graph[e1-1][e2-1]=value2; } } for(i=0;i<n;i++) delete []graph[i]; delete []graph; } return 0; } stack::stack() { top=0; } void stack::push(int c1,int c2,int c,int d) { data[top].pos1=c1; data[top].pos2=c2; data[top].count=c; data[top].direct=d; top++; } void stack::pop(int& c1,int& c2,int& c,int& d) { top--; c1=data[top].pos1; c2=data[top].pos2; c=data[top].count; d=data[top].direct; } bool stack::isempty() { return top==0?true:false; }
true
dddacef602be5175ce2636b17af988d1c474f4fb
C++
jacobkim5021/FirstYearProgramming
/assignment3/snake.cpp
UTF-8
846
3.078125
3
[]
no_license
#include <iostream> using namespace std; int main(){ int xposition = 1; int yposition = 1; int x = 10; int y = 10; char input; while(input != 'x'){ for(int h=1 ; h <= y ; h++){ for(int i=1 ; i <= x ; i++){ if(i == xposition && h == yposition){ cout << "O "; } else{ cout << "- "; } } cout << endl; } cin >> input; if(input == 'w'){ if(yposition == 1){ yposition = 1; } else yposition -= 1; } else if(input == 'a'){ if(xposition == 1){ xposition = 1; } else xposition -= 1; } else if(input == 's'){ if(yposition == y){ yposition = y; } else yposition += 1; } else if(input == 'd'){ if(xposition == x){ xposition = x; } else xposition += 1; } else cerr << "w, a, s, d"; } return 0; }
true
b1f1b52e727210055ca48d6a06214c41cae81055
C++
doraneko94/AtCoder
/ABC/ABC060/b.cpp
UTF-8
321
3.015625
3
[]
no_license
#include <iostream> using namespace std; int main() { int A, B, C; cin >> A >> B >> C; bool can = false; for (int i=1; i<=B; ++i) { if (A*i % B == C) { can = true; break; } } if (can) cout << "YES" << endl; else cout << "NO" << endl; return 0; }
true
36ce3310400535c13fa8c1d2b3b00fae79913af9
C++
damiche97/GDVdev
/ex2/SceneTask.h
UTF-8
1,682
3.171875
3
[]
no_license
#ifndef SCENE_TASK_H #define SCENE_TASK_H #include "Task.h" #include "TriangleMesh.h" #include <chrono> enum class AnimationPhase { Drive, CrashUp, CrashDown, Done }; /** * Dynamic scene: A car crashes against a tree */ class SceneTask: public Task { private: TriangleMesh tree_leaves {MeshType::Static}; // Will store triangle mesh for tree leaves TriangleMesh tree_trunk {MeshType::Static}; // Will store triangle mesh for tree trunk TriangleMesh car {MeshType::Dynamic}; // Mesh for car. Must use VBO streaming, thus set to Dynamic mode. // Maximum animation time for each phase of this dynamic scene static constexpr const std::chrono::milliseconds maxDriveTime {528}; // drive car for 528 milliseconds static constexpr const std::chrono::milliseconds maxCrashUpTime {170}; // crash against tree, rotating upwards for 170ms static constexpr const std::chrono::milliseconds maxCrashDownTime {430}; // crash down again for 430ms std::chrono::milliseconds movedTime {0}; // Time the current scene has been running std::chrono::milliseconds currentMaxTime {maxDriveTime}; // maximum animation time of the current scene, will be set to one of the above values AnimationPhase animPhase {AnimationPhase::Drive}; // current animation phase. Start with the car driving public: virtual ~SceneTask() = default; virtual void load() override; virtual void draw(DrawMode mode) override; virtual bool tick(std::chrono::milliseconds ms) override; virtual void keyPressed(unsigned char key, int x, int y) override; virtual unsigned int getNumTriangles() override; }; #endif
true
a082ee304720fc53792629db76eebc08dab2bfa9
C++
ric2b/Vivaldi-browser
/chromium/chrome/browser/lacros/browser_launcher.h
UTF-8
1,425
2.59375
3
[ "BSD-3-Clause" ]
permissive
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_LACROS_BROWSER_LAUNCHER_H_ #define CHROME_BROWSER_LACROS_BROWSER_LAUNCHER_H_ #include "base/memory/raw_ptr.h" #include "base/supports_user_data.h" class Profile; // Responsible for creating and launching new instances of lacros-chrome. class BrowserLauncher : public base::SupportsUserData::Data { public: explicit BrowserLauncher(Profile* profile); BrowserLauncher(const BrowserLauncher&) = delete; BrowserLauncher& operator=(const BrowserLauncher&) = delete; ~BrowserLauncher() override = default; // Creates the BrowserLauncher instance if it does not already exist. static BrowserLauncher* GetForProfile(Profile* profile); // Launches lacros-chrome for full restore. This method should be called // before any lacros browser windows have been created while the process is in // the background / windowless state. void LaunchForFullRestore(bool skip_crash_restore); bool is_launching_for_full_restore() const { return is_launching_for_full_restore_; } private: // Tracks whether the BrowserLauncher is in the process of performing a Full // Restore launch of lacros-chrome. bool is_launching_for_full_restore_ = false; const raw_ptr<Profile> profile_; }; #endif // CHROME_BROWSER_LACROS_BROWSER_LAUNCHER_H_
true
d8f497790b1dd64d35e7d6ee5ddcd24848771734
C++
TsFotini/Neural_Networks-Clustering_Techniques
/Clustering Techniques/vectors/Cluster.h
UTF-8
722
2.9375
3
[]
no_license
#ifndef CLUSTER_H #define CLUSTER_H #include <vector> #include "VectorNode.h" using namespace std; class Cluster{ VectorNode centroid; vector<VectorNode> inClusterPoints; public: VectorNode getCentroid(){ return centroid;} void setCentroid(VectorNode v){ centroid = v;} vector<VectorNode> getPoints(){ return inClusterPoints; } void setPoints(vector<VectorNode> vec){ inClusterPoints = vec; } void pushInCluster(VectorNode element){ inClusterPoints.push_back(element);} }; class Cost{ VectorNode centroid; double sum; public: VectorNode getCentroid(){ return centroid;} void setCentroid(VectorNode v){ centroid = v;} double getsum(){ return sum; } void setsum(double s) { sum = s; } }; #endif
true
c8497d03facd20a74ed1ab068623e6a1b7287e37
C++
EmbeddedSystemGroupNJU/LineTrackingCar
/abandonCarControl/class/Speeds.cpp
UTF-8
308
3
3
[]
no_license
// // Created by leich on 2018/10/19. // #include "Speeds.h" Speeds::Speeds(double l, double r) { this->left = l; this->right = r; } std::ostream & operator<<(std::ostream & os, const Speeds & speeds) { os << "left speed: " << speeds.left << " right speed: " << speeds.right; return os; }
true
af39170a4cd4d636b302dcc215a2ad54a61754d7
C++
ReginaLaurentino/Primer-Cuatrimestre-for
/prueba 2.cpp
UTF-8
632
2.6875
3
[]
no_license
#include <iostream> using namespace std; int main(){ int total,cp,cn,tn,Maxi,Maxp; int n,x; total=0; cout<<"Ingrese un numero: "; cin>>n; cout<<endl; cp=0; cn=0; tn=0; Maxi=0; Maxp=0; while(n!=0){ if(n%2==0){ if (Maxp!=0){ if(n>Maxp){Maxp=n;} }else{Maxp=n;} }else{ if(Maxi!=0){ if(n>Maxi){Maxi=n;} }else{Maxi=n;} } cout<<"Ingrese un numero: "; cin>>n; cout<<endl; } cout<<"maximo par "<<Maxp<<endl; cout<<"maximo impar "<<Maxi<<endl; return 0; }
true
4cdf16b9ba8dd27b12d452505751a3006be0230a
C++
Diksha65/Programs
/C++/selectionSort.cpp
UTF-8
917
3.765625
4
[]
no_license
#include<iostream> #include<vector> using namespace std; int smallestElement(int index, vector<int> vec){ int small = vec[index], pos = index; for(int i=index+1; i<vec.size(); i++){ if(vec[i] < small){ small = vec[i]; pos = i; } } return pos; } void displayVector(vector<int> vec){ cout<<"\n"; for(int j=0;j<vec.size(); ++j){ cout<<vec[j]<<"\t"; } cout<<"\n"; } void selectionsort(vector<int> vec){ int smallestIndex; for(int i=0;i<vec.size(); ++i){ smallestIndex = smallestElement(i, vec); int tmp = vec[i]; vec[i] = vec[smallestIndex]; vec[smallestIndex] = tmp; } displayVector(vec); } int main(){ vector<int> vec(8,0); int val; cout<<"Enter the elements in the vector:"; for(int i=0; i<8; i++){ cin>>val; vec[i] = val; } selectionsort(vec); }
true
3b57ac2fda072394cf8f18f84635cba3db4a0c53
C++
Zhang-Tianxu/Algorithms
/ClassicalProblems/Maze/Maze.h
UTF-8
589
2.765625
3
[]
no_license
#ifndef _MAZE_H_ #define _MAZE_H_ #include <vector> class MazePos { public: int x; int y; MazePos(); MazePos(int px, int py); MazePos up(int d); MazePos down(int d); MazePos left(int d); MazePos right(int d); bool operator==(const MazePos& b); void print(); }; class Maze { public: std::vector<std::vector<int>> MazeBoard; MazePos in; MazePos out; Maze(); Maze(std::vector<std::vector<int>> board, MazePos in_pos, MazePos out_pos); int getPosValue(MazePos p); void setPosValue(MazePos p, int v); bool posInMaze(MazePos p); void print(); }; Maze makeMaze(); #endif
true
028a5ee684aac61f8918cafc8391c32b9b831382
C++
mpsitech/idec_public
/ideccmbd/VecIdec/VecVJobIdecQcdacqFan.cpp
UTF-8
1,486
2.53125
3
[ "BSD-2-Clause" ]
permissive
/** * \file VecVJobIdecQcdacqFan.cpp * vector VecVJobIdecQcdacqFan (implementation) * \author Alexander Wirthmueller * \date created: 30 Dec 2017 * \date modified: 30 Dec 2017 */ #include "VecVJobIdecQcdacqFan.h" /****************************************************************************** namespace VecVJobIdecQcdacqFan ******************************************************************************/ uint VecVJobIdecQcdacqFan::getIx( const string& sref ) { string s = StrMod::lc(sref); if (s == "off") return OFF; else if (s == "offrec") return OFFREC; else if (s == "on") return ON; return(0); }; string VecVJobIdecQcdacqFan::getSref( const uint ix ) { if (ix == OFF) return("off"); else if (ix == OFFREC) return("offrec"); else if (ix == ON) return("on"); return(""); }; string VecVJobIdecQcdacqFan::getTitle( const uint ix , const uint ixIdecVLocale ) { if (ixIdecVLocale == 1) { if (ix == OFF) return("off"); else if (ix == OFFREC) return("off during recording"); else if (ix == ON) return("on while cooling"); } else if (ixIdecVLocale == 2) { if (ix == OFF) return("aus"); else if (ix == OFFREC) return("aus w\\u00e4hrend Aufnahme"); else if (ix == ON) return("ein w\\u00e4hrend K\\u00fchlvorgang"); }; return(""); }; void VecVJobIdecQcdacqFan::fillFeed( const uint ixIdecVLocale , Feed& feed ) { feed.clear(); for (unsigned int i=1;i<=3;i++) feed.appendIxSrefTitles(i, getSref(i), getTitle(i, ixIdecVLocale)); };
true
f07de2661f6b00bb632242ad5c8f0eae82772ccd
C++
JasmineHJM/leetcode
/01_21.cpp
GB18030
1,133
3.359375
3
[]
no_license
#define _CRT_SECURE_NO_WARNINGS 1 #include<iostream> using namespace std; //жһǷǻָ򣨴ң͵򣨴󣩶һ class Solution{ public: bool isPalindrome(int x){ if (x<0) return false; if (x % 10 == 0 && x != 0) return false; if (x >= 0 && x <= 9) // Ϊ return true; int idx = 1; while (x / (int)pow(10.0, idx)>0) // Ǽλ idx++; idx--; // 34543 while (x>10 && idx>0){ if ((int)x / (int)pow(10.0, idx) != x % 10) return false; int last = x; x %= (int)pow(10.0, idx); // Ƶһλ int sub = lowbit(last) - lowbit(x); // λ x /= 10; // һλ if (sub>1){ idx -= (sub - 1) * 2; // Ȱ׼ԺҪõָ while (sub>1 && x){ if (x % 10 != 0) // ʧ0ǷԳ return false; x /= 10; sub--; } } idx -= 2; // ֮ǰƶλ } return true; } int lowbit(int x){ int sum = 0; while (x) sum++, x /= 10; return sum; } };
true
3a6ade7301a5e6873e7631881bcc8fcaa9b707a9
C++
amov-lab/Prometheus
/Modules/simulator_utils/map_generator/map_generator_node.cpp
UTF-8
2,282
2.53125
3
[ "Apache-2.0" ]
permissive
#include <ros/ros.h> #include "map_generator.h" // 主函数 int main(int argc, char **argv) { ros::init(argc, argv, "map_generator_node"); ros::NodeHandle nh("~"); string map_name; // 【参数】地图名称 nh.param<string>("map_name", map_name, "planning_test"); cout << GREEN << "map_name: [ " << map_name << " ]" << TAIL << endl; // 初始化地图生成器 Map_Generator Obs_Map; Obs_Map.init(nh); // 生成边界 Obs_Map.GenerateBorder(); // Obs_Map.generate_square(3.0, 3.0); if (map_name == "planning_test") { // 对应 planning_test.world Obs_Map.GeneratePlanningTestMap(); } else if (map_name == "planning_test2") { // 对应 planning_test2.world Obs_Map.GeneratePlanningTestMap2(); }else if (map_name == "planning_test3") { // 对应 planning_test3.world Obs_Map.GeneratePlanningTestMap3(); } else if (map_name == "random") { // 生成随机地图 Obs_Map.GenerateRandomMap(); } else if (map_name == "test") { // 生成示例地图,地图元素包括cylinder、square、row_wall、column_wall、line // small_cylinder对应obs_cylinder_small.sdf // large_cylinder对应obs_cylinder_large.sdf // square对应obs_square.sdf // 墙体暂时没有对应的Gazebo模型,todo Obs_Map.generate_square(3.0, 3.0); Obs_Map.generate_small_cylinder(1.0, 1.0); Obs_Map.generate_large_cylinder(2.0, 2.0); Obs_Map.generate_row_wall(10.0, 10.0); Obs_Map.generate_column_wall(-10.0, -10.0); Obs_Map.generate_line(0.0, 0.0); Obs_Map.global_map_pcl.width = Obs_Map.global_map_pcl.points.size(); Obs_Map.global_map_pcl.height = 1; Obs_Map.global_map_pcl.is_dense = true; Obs_Map.kdtreeLocalMap.setInputCloud(Obs_Map.global_map_pcl.makeShared()); Obs_Map.global_map_ok = true; cout << GREEN << "[map_generator] Finished generate map [ " << map_name << " ]. Map points:" << Obs_Map.global_map_pcl.width << TAIL << endl; } else { cout << RED << "[map_generator] wrong map_name: [ " << map_name << " ]" << TAIL << endl; } ros::spin(); return 0; }
true
2df2081cf8be6a461d1bbb8b4e606f2ad80a0b72
C++
yottaawesome/win32-experiments
/src/ProcessClient/ProcessClient.cpp
UTF-8
777
2.546875
3
[ "MIT" ]
permissive
#include <Windows.h> #include <iostream> #include "ClientServerLib/include/ClientServerLib.hpp" #define BUF_SIZE 256 int main() { //ClientServerLib::IntArray mmf(L"MyFileMappingObject", 512 * sizeof(wchar_t), false); ClientServerLib::TypedArray<ClientServerLib::Message> mmf(L"MyFileMappingObject", false); std::wcout << L"Client opened handle!" << std::endl; // Give time for the main process to populate the data. Sleep(5000); while (mmf.GetCurrentCount() < 10) Sleep(1000); for (int i = 0; i < 10; i++) { mmf.Lock(); ClientServerLib::Message* msg = mmf[i]; std::wcout << L"Client read: " << msg->GetMsg() << std::endl; //std::wcout << mmf.GetCurrentCount() << std::endl; mmf.Unlock(); } std::wcout << L"Client exited!" << std::endl; return 0; }
true
51c3444f1c33e6f460a64cd49cf6981b68bed2c9
C++
Nerisson/laughing-bimbo-shame
/Kata/KATA1/main.cpp
UTF-8
1,424
3.015625
3
[]
no_license
#include <windows.h> #include <GL/glut.h> #include <iostream> using namespace std; void reshape (int w, int h); GLfloat RED[] = {1., 0., 0., 1.}; GLfloat GREEN[] = {0., 1., 0., 1.}; GLfloat BLUE[] = {0., 0., 1., 1.}; GLfloat BLACK[] = {0., 0., 0., 1.}; GLfloat WHITE[] = {1., 1., 1., 1.}; int main(int argc, char **argv){ void initialize(char *); void display(void); glutInit(&argc, argv) ; /*Initiase GLUT et traite les arguments de la ligne de commande*/ initialize(argv[0]); glutDisplayFunc(display) ; glutMainLoop() ; return 0 ; } void initialize(char *title){ void defineWindow(char *); glutInitDisplayMode(GLUT_RGB) ; glutInitDisplayMode(GLUT_RGB) ; defineWindow(title); } void defineWindow(char *title){ GLsizei screenWidth, screenHeight ; screenWidth= glutGet(GLUT_SCREEN_WIDTH); screenHeight = glutGet(GLUT_SCREEN_HEIGHT); glutInitWindowPosition(screenWidth/4, screenHeight /4); glutInitWindowSize(screenWidth/2, screenHeight /2); glutCreateWindow(title) ; glutReshapeFunc(reshape); } void display(void){ glClear(GL_COLOR_BUFFER_BIT) ; glColor4fv(RED); glutSolidTeapot(.5); glFlush() ; } void reshape (int w, int h){ cout << "Hello: width:" << w << " height:" << h << endl; glLoadIdentity(); gluPerspective(65.0, (GLfloat) w/ (GLfloat) h, 1.0, 20.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); }
true
47005aaf258c9f0c34095d1c43af1123cd9546b7
C++
lee-jeong-geun/ps
/boj/1017.cpp
UTF-8
4,243
3.171875
3
[]
no_license
#include <cstdio> #include <iostream> #include <algorithm> #include <cstring> #include <queue> #include <vector> using namespace std; struct Edge { int v, capa, rev; Edge(int v, int capa, int rev) : v(v), capa(capa), rev(rev) {} }; vector<vector<Edge>> vec; vector<int> Num[5], result; int N, arr[55], level[55], work[55], prime[2005], chk[55][55]; /* 2를 제외한 소수는 무조건 홀수이기 때문에 짝수와 홀수로 나눠서 이분매칭을 시키면 된다. 이분매칭은 하나의 쌍이라도 매칭이 안될때까지 하고 매칭이 끝날때마다 다시 그래프를 만드는데 이때 1번 숫자와 매칭된 숫자의 간선을 연결 시키지 않는다. 예외 케이스 4 20 6 11 9 */ void addEdge(int start, int end, int capa) { vec[start].emplace_back(end, capa, vec[end].size()); vec[end].emplace_back(start, 0, vec[start].size() - 1); } int BFS() { memset(level, -1, sizeof level); queue<int> q; q.push(0); level[0] = 0; while(!q.empty()) { int temp; temp = q.front(); q.pop(); for(int i = 0; i < vec[temp].size(); i++) { int next, nextCapa; next = vec[temp][i].v; nextCapa = vec[temp][i].capa; if(level[next] == -1 && nextCapa > 0) { level[next] = level[temp] + 1; q.push(next); } } } return level[N + 1] != -1; } int DFS(int node, int f) { if(node == N + 1) return f; int minFlow; for(int &i = work[node]; i < vec[node].size(); i++) { int next, nextCapa; next = vec[node][i].v; nextCapa = vec[node][i].capa; if(level[next] == level[node] + 1 && nextCapa > 0) { minFlow = DFS(next, min(f, nextCapa)); if(minFlow > 0) { vec[node][i].capa -= minFlow; vec[next][vec[node][i].rev].capa += minFlow; return minFlow; } } } return 0; } //그래프 만드는 함수 void build() { vec.clear(); vec.resize(N * 2 + 5); for(int i = 0; i < Num[0].size(); i++) { addEdge(0, Num[0][i], 1); } for(int i = 0; i < Num[1].size(); i++) { addEdge(Num[1][i], N + 1, 1); } for(int i = 0; i < Num[0].size(); i++) { for(int j = 0; j < Num[1].size(); j++) { //한번이라도 매칭된 간선일 경우 패스 if(chk[Num[0][i]][Num[1][j]] == 1) continue; //합이 소수라면 연결 if(prime[arr[Num[0][i]] + arr[Num[1][j]]] == 0) { addEdge(Num[0][i], Num[1][j], 1); } } } } int main() { //에라토스 테네스의 체 for(int i = 2; i <= 2000; i++) { if(prime[i] == 1) continue; for(int j = i + i; j <= 2000; j += i) { prime[j] = 1; } } scanf("%d", &N); for(int i = 1; i <= N; i++) { scanf("%d", &arr[i]); //짝수 홀수 분할 Num[arr[i] % 2].push_back(i); } //항상 첫번째 숫자가 Num[0]으로 오게 설정 if(arr[1] % 2 == 1) swap(Num[0], Num[1]); while(1) { build(); int count = 0; while(BFS()) { memset(work, 0, sizeof work); int minFlow; while(1) { minFlow = DFS(0, 987654321); if(minFlow == 0) break; count += minFlow; } } if(count < N / 2) break; for(int i = 0; i < vec[Num[0][0]].size(); i++) { //1번숫자와 매칭된 간선인 경우 유량이 0 if(vec[Num[0][0]][i].capa == 0) { chk[Num[0][0]][vec[Num[0][0]][i].v] = 1; result.push_back(arr[vec[Num[0][0]][i].v]); break; } } } if(result.size() == 0) { printf("-1"); return 0; } sort(result.begin(), result.end()); for(int i = 0; i < result.size(); i++) { printf("%d ", result[i]); } }
true
0aca442fd0257b0ef9ca1e64914b88cce8ce9716
C++
inder128/cppCodes
/op.cpp
UTF-8
790
2.75
3
[]
no_license
#include <iostream> #include <stack> using namespace std; int main(){ int t; cin>>t; while(t--){ int n; cin>>n; int a[n+1], b[n+1]; stack <pair<int, int> > st; for (int i = 1; i < n+1; ++i) cin>>a[i]; a[0] = 0; b[0] = 0; b[1] = 0; b[2]= ((a[2]-a[1]>0) ? a[2]-a[1] : 0); for (int i = 3; i < n+1; ++i){ b[i] = b[i-1]; for (int j = 1; j < i; ++j) b[i] = max(b[i], b[j-1] + a[i]-a[j]); } int t=n, s; while(t>=2){ if(b[t]==b[t-1]){ t--; continue; } s=t-1; while(b[s-1]+a[t]-a[s]!=b[t]) s--; st.push(make_pair(s-1,t-1)); t = s-1; } if(st.empty()){ cout<<"No Profit\n"; continue; } while(!st.empty()){ printf("(%d %d) ",st.top().first,st.top().second); st.pop(); } cout<<endl; } return 0; }
true
f4df0a80e08e96b7322cf097ee21113b36b5c647
C++
Ben-Hi/fantasy-tournament
/project4_Fantasy_Tournament/Menu.cpp
UTF-8
18,981
3.4375
3
[]
no_license
/*********************************************************************************************** * * Program name: Menu.cpp * * Author: Benjamin Hillen * * Date: 23 November 2019 * * Description: Menu class definition for the fantasy tournament simulator, members * * describe the team lineups/graveyards, rounds played, and individual * * fighters. Methods allow user to choose to play or quit, setup the * * roster for both teams, and then watch the teams fight. **********************************************************************************************/ #include "Menu.hpp" #include "Character.hpp" #include "Barbarian.hpp" #include "Vampire.hpp" #include "BlueMen.hpp" #include "Medusa.hpp" #include "HarryPotter.hpp" #include "Team.hpp" #include "validateInt.hpp" #include <cstdlib> #include <string> #include <iostream> #define FIGHTERLIM 2 #define FIGHTERMAX 10 using std::cout; using std::cin; using std::endl; /******************************* * * Menu() * * default constructor, * * rounds start at 1, * * neither team has points, * * pointers are set to NULL, * * teamSize is 0 *******************************/ Menu::Menu() { rounds = 1; team1Points = 0; team2Points = 0; teamSize = 0; numTeam1Fighters = 0; numTeam2Fighters = 0; team1 = NULL; team2 = NULL; } /**************************************************************** * * playGame(bool hasPlayed) * * prompts user to play or quit if hasPlayed is false, if not * * prompts for play again or quit. If user chooses to play, * * returns true. If user chooses to quit, returns false. ****************************************************************/ bool Menu::playGame(bool hasPlayed) { std::string userInput = ""; //ask user if they want to play again if (hasPlayed) { do { cout << "\n\n1. Play Again\n2. Quit\n"; getline(cin, userInput); if (userInput != "1" && userInput != "2") { cout << "Error: invalid input, please try again."; } } while (userInput != "1" && userInput != "2"); if (userInput == "1") { return true; } else { return false; } } //ask user if they want to play else { do { cout << "\n\n1. Play\n2. Quit\n"; getline(cin, userInput); if (userInput != "1" && userInput != "2") { cout << "Error: invalid input, please try again."; } } while (userInput != "1" && userInput != "2"); if (userInput == "1") { return true; } else { return false; } } } /**************************************************************************************** * * setTeam1Roster() * * asks user to set the value of teamSize, then initializes team1 and team2 to be * * arrays of pointers to dynamically allocated characters. User then defines the * * type and name of each fighter on each roster. Prints out the final roster for * * each team after transferring each Character ptr into the corresponding * * team1LineUp object. THIS FUNCTION IMPLEMENTS THE TEAM LINEUP BY PLACING CHARACTERS * * INTO THEIR RESPECTIVE QUEUE-LIKE LINKED LISTS. ****************************************************************************************/ void Menu::setTeam1Roster() { const std::string VAMPIRE = "1"; //Character choice legend const std::string BARBARIAN = "2"; const std::string BLUEMEN = "3"; const std::string MEDUSA = "4"; const std::string HARRYPOTTER = "5"; std::string userInput = ""; team1 = new Character*[teamSize]; cout << "\n\n-------------TEAM 1 ROSTER SELECTION INFO-------------\n\n"; cout << "The fighters of Team 1 have the advantage in combat: they will always"; cout << " attack first.\nTime to choose the fighters for Team 1!\n\n"; //prompt the user to fill the team1 lineup with characters and name each character for (int i = 0; i < teamSize; i++) { do { cout << "\n\nSELECT " << i + 1 << "TH FIGHTER TYPE\n\n"; cout << "1. Vampire --- Attack(atk) = 1d12 --- Defense(def) = 1d6*(Charm) --- Armor = 1 --- Strength Points = 18\n"; cout << "2. Barbarian --- Atk = 2d6 --- Def = 2d6 --- Armor = 0 --- Strength Points = 12\n"; cout << "3. Blue Men --- Atk = 2d10 --- Def = 3d6 --- Armor = 3 --- Strength Points = 12*(Mob)\n"; cout << "4. Medusa --- Atk = 2d6*(Glare) --- Def = 1d6 --- Armor = 3 --- Strength Points = 8\n"; cout << "5. Harry Potter --- Atk = 2d6 --- Def = 2d6 --- Armor = 0 --- Strength Points = 10/20*(Hogwarts)\n"; cout << "\nSPECIAL ABILITIES\nCharm: for each attack against the vampire, there is a 50% chance that the"; cout << " opponent does not actually attack them.\nMob: for every 4 points of damage received, Blue Men"; cout << " lose one defense die.\nGlare: if Medusa rolls a 12, the opponent receives an absurd amount of damage.\n"; cout << "Hogwarts: if Harry's strength reaches 0 or less, he comes back with 20 strength. Only happens once per game.\n\n"; getline(cin, userInput); if (userInput != "1" && userInput != "2" && userInput != "3" && userInput != "4" && userInput != "5") { cout << "Error, invalid input. Please enter 1, 2, 3, 4, or 5 for the " << i + 1 << "th fighter\n"; } } while (userInput != "1" && userInput != "2" && userInput != "3" && userInput != "4" && userInput != "5"); //Set the appropriate Character ptr of team1 to the user's specified type if (userInput == VAMPIRE) { team1[i] = new Vampire; } else if (userInput == BARBARIAN) { team1[i] = new Barbarian; } else if (userInput == BLUEMEN) { team1[i] = new BlueMen; } else if (userInput == MEDUSA) { team1[i] = new Medusa; } else if (userInput == HARRYPOTTER) { team1[i] = new HarryPotter; } //get name for fighter from user cout << "Ok, how about this fighter's name? You can enter anything, anything at all...\n\n"; getline(cin, userInput); team1[i]->setName(userInput); //confirm the new fighter's name and description to the user cout << "Give a hearty welcome to "; team1[i]->printName(); cout << ". Let's hear a little about our fighter's type!\n"; team1[i]->printDescription(); team1LineUp.addBackTeam(team1[i]); //adds the fighter to the lineup queue-like structure } cout << "\n\n\n-----------------------------------------------------------"; cout << "TEAM 1 FINAL ROSTER-----------------------------------------------------------\n\n"; team1LineUp.printTeamLineUp(); cout << "-----------------------------------------------------------------------------------"; cout << "------------------------------------------------------\n\n"; } /**************************************************************************************** * * setTeam2Roster() * * asks user to set the value of teamSize, then initializes team1 and team2 to be * * arrays of pointers to dynamically allocated characters. User then defines the * * type and name of each fighter on each roster. Prints out the final roster for * * each team after transferring each Character ptr into the corresponding * * team1LineUp object. THIS FUNCTION IMPLEMENTS THE TEAM LINEUP BY PLACING CHARACTERS * * INTO THEIR RESPECTIVE QUEUE-LIKE LINKED LISTS. ****************************************************************************************/ void Menu::setTeam2Roster() { const std::string VAMPIRE = "1"; //Character choice legend const std::string BARBARIAN = "2"; const std::string BLUEMEN = "3"; const std::string MEDUSA = "4"; const std::string HARRYPOTTER = "5"; std::string userInput = ""; team2 = new Character*[teamSize]; cout << "\n\n-------------TEAM 2 ROSTER SELECTION INFO-------------\n\n"; cout << "The fighters of Team 2 have a disadvantage in combat: they will always"; cout << " defend first.\nTime to choose the fighters for Team 2!\n\n"; //prompt the user to fill the team2 lineup with characters and name each character for (int i = 0; i < teamSize; i++) { do { cout << "\n\nSELECT " << i + 1 << "TH FIGHTER TYPE\n\n"; cout << "1. Vampire --- Attack(atk) = 1d12 --- Defense(def) = 1d6*(Charm) --- Armor = 1 --- Strength Points = 18\n"; cout << "2. Barbarian --- Atk = 2d6 --- Def = 2d6 --- Armor = 0 --- Strength Points = 12\n"; cout << "3. Blue Men --- Atk = 2d10 --- Def = 3d6 --- Armor = 3 --- Strength Points = 12*(Mob)\n"; cout << "4. Medusa --- Atk = 2d6*(Glare) --- Def = 1d6 --- Armor = 3 --- Strength Points = 8\n"; cout << "5. Harry Potter --- Atk = 2d6 --- Def = 2d6 --- Armor = 0 --- Strength Points = 10/20*(Hogwarts)\n"; cout << "\nSPECIAL ABILITIES\nCharm: for each attack against the vampire, there is a 50% chance that the"; cout << " opponent does not actually attack them.\nMob: for every 4 points of damage received, Blue Men"; cout << " lose one defense die.\nGlare: if Medusa rolls a 12, the opponent receives an absurd amount of damage.\n"; cout << "Hogwarts: if Harry's strength reaches 0 or less, he comes back with 20 strength. Only happens once per game.\n\n"; getline(cin, userInput); if (userInput != "1" && userInput != "2" && userInput != "3" && userInput != "4" && userInput != "5") { cout << "Error, invalid input. Please enter 1, 2, 3, 4, or 5 for the " << i + 1 << "th fighter\n"; } } while (userInput != "1" && userInput != "2" && userInput != "3" && userInput != "4" && userInput != "5"); //Set the appropriate Character ptr of team2 to the user's specified type if (userInput == VAMPIRE) { team2[i] = new Vampire; } else if (userInput == BARBARIAN) { team2[i] = new Barbarian; } else if (userInput == BLUEMEN) { team2[i] = new BlueMen; } else if (userInput == MEDUSA) { team2[i] = new Medusa; } else if (userInput == HARRYPOTTER) { team2[i] = new HarryPotter; } //get name for fighter from user cout << "Ok, how about this fighter's name? You can enter anything, anything at all...\n\n"; getline(cin, userInput); team2[i]->setName(userInput); //confirm the new fighter's name and description to the user cout << "Give a hearty welcome to "; team1[i]->printName(); cout << ". Let's hear a little about our fighter's type!\n"; team2[i]->printDescription(); team2LineUp.addBackTeam(team2[i]); //adds the fighter to the lineup queue-like structure } cout << "\n\n\n-----------------------------------------------------------"; cout << "TEAM 2 FINAL ROSTER-----------------------------------------------------------\n\n"; team2LineUp.printTeamLineUp(); cout << "-----------------------------------------------------------------------------------"; cout << "------------------------------------------------------\n\n"; } /********************************************************************************************* * * fight() * * manages combat between fighters at the top of the team1LineUp and team2LineUp Queues * * by using project3 code. After determining the winner, the loser is removed from the * * appropriate teamLineUp object and sent to the top of the graveyard list. THIS FUNCTION * * IMPLEMENTS THE LOSER PILE (NAMED GRAVEYARD) BY REMOVING THE LOSER FROM THEIR LINEUP * * AND PLACING THEM AT THE TOP OF THE GRAVEYARD STACK IN THE TEAM GRAVEYARD OBJECT. * * After this is performed, the recover() function is called on the winner to restore * * a percentage of their maximum strength. See Character.cpp for recover() function * * description. THIS FUNCTION IMPLEMENTS THE RECOVER REQUIREMENT FOR THE TOURNAMENT. ********************************************************************************************/ void Menu::fight() { int damage = 0; Character* c1 = team1LineUp.getFrontTeam(); Character* c2 = team2LineUp.getFrontTeam(); while (c1->getStrength() > 0 && c2->getStrength() > 0) { //Display fighter types and the round cout << "\n\nROUND " << rounds << ": Team 1's "; c1->printName(); c1->printType(); cout << " VS. Team 2's "; c2->printName(); c2->printType(); cout << "\n\n"; damage = c1->rollAtk(); //assume c1 is alive at the start of the round c2->rollDef(damage); //Case: c2 still has strength after c1 attacks if (c2->getStrength() > 0) { damage = c2->rollAtk(); c1->rollDef(damage); //Case: c1 has no strength left after c2 attacks if (c1->getStrength() <= 0) { cout << "\n\n----------ROUND " << rounds << ": RESULTS----------\n\n"; cout << "The fight is over, Team 2's "; c2->printName(); c2->printType(); cout << " has won the match! For defeating one of Team 1's fighters, Team 2 gets 2 points.\n\n"; graveyard.addFrontGrave(team1LineUp.removeFrontTeam()); numTeam1Fighters--; team2Points += 2; team2LineUp.addBackTeam(team2LineUp.removeFrontTeam()); //place the victor at the } //end of the lineup } //Case: c2 has no strength left after c1 attacks else if (c2->getStrength() <= 0) { cout << "\n\n----------ROUND " << rounds << ": RESULTS----------\n\n"; cout << "The fight is over, Team 1's "; c1->printName(); c1->printType(); cout << " has won the match! For defeating one of Team 2's fighters, Team 1 gets 2 points.\n\n"; graveyard.addFrontGrave(team2LineUp.removeFrontTeam()); numTeam2Fighters--; team1Points += 2; team1LineUp.addBackTeam(team1LineUp.removeFrontTeam()); } } //if c1 lost the fight, then c2 needs to have the recover function called on it if (c1->getStrength() <= 0) { c2->recover(); } //if c2 lost the fight, then c1 needs to have the recover function called on it else if (c2->getStrength() <= 0) { c1->recover(); } } /******************************************************************************************************** * * runTournament() * * implements the gameplay flow of the Fantasy Tournament by prompting the user to set the size of * * the two teams, making calls to setTeam1Roster() and setTeam2Roster() to fill the lineup containers * * with named characters, then has the fighters at the top of each queue fight each other by calling * * fight(), then analyzes team points once all the fighters of a lineup have died, declares a winner, * * and performs memory management in case the user wants to play again. ********************************************************************************************************/ void Menu::runTournament() { std::string userInput = ""; cout << "\n\nFANTASY TOURNAMENT INTRODUCTION\n\n"; cout << "Welcome to the tournament of your imagination! Let's get right to it shall we?\n"; //loop asking the user to define teamSize until they enter an integer between //FIGHTERLIM (2) and FIGHTERMAX (10) do { cout << "\nHow many fighters would you like each team to have? Enter a positive integer between "; cout << FIGHTERLIM << " and " << FIGHTERMAX << endl; getline(cin, userInput); validateInt(userInput); teamSize = numTeam1Fighters = numTeam2Fighters = stoi(userInput); if (teamSize < FIGHTERLIM || teamSize > FIGHTERMAX) { cout << "Error: must have at least " << FIGHTERLIM << " fighters and at most " << FIGHTERMAX; cout << " fighters, try again.\n\n"; } } while (teamSize < FIGHTERLIM || teamSize > FIGHTERMAX); cout << "\n\nExcellent, each team will have " << teamSize << " fighters."; cout << "\n\nTime to choose the fighters for each team!\n\n"; setTeam1Roster(); //set up the lineup for each team setTeam2Roster(); //as long as there are still fighters in one of the lineups, have the first fighter in each //lineup fight each other while (numTeam1Fighters > 0 && numTeam2Fighters > 0) { cout << "\n\n-----------------------------------------------------------FANTASY TOURNAMENT"; cout << " ROUND " << rounds << "------------------------------------------" << endl << endl; cout << "\n\n\n------------------------------------------------------"; cout << "TEAM 1 ROSTER------------------------------------------------------\n\n"; team1LineUp.printTeamLineUp(); cout << "------------------------------------------------------------------------"; cout << "-------------------------------------------------\n\n"; cout << "\n\n\n------------------------------------------------------"; cout << "TEAM 2 ROSTER------------------------------------------------------\n\n"; team2LineUp.printTeamLineUp(); cout << "------------------------------------------------------------------------"; cout << "-------------------------------------------------\n\n"; fight(); rounds++; } cout << "\n\nTHE TOURNAMENT HAS ENDED!!!\n\n"; //inform the user the tournament is over cout << "Team 1's Final Score: " << team1Points << endl; //print scores cout << "Team 2's Final Score: " << team2Points; cout << "\n\nWINNER: "; //Case: Team 1 has more points than Team 2 if (team1Points > team2Points) { cout << "Congratulations to Team 1, they have won the tournament!"; } //Case: Team 2 has more points than Team 1 else if (team2Points > team1Points) { cout << "Victory goes to Team 2, they have won the tournament!"; } //Case: Team 1 ties with Team 2 else { cout << "It's a dead tie, no winners in this tournament, only losers!"; } cout << "\n\nWould you like to see the graveyard?\n"; //prompt user to choose to view the graveyard or not do { cout << "1. Display the fallen fighters\n2. Skip the graveyard\n"; getline(cin, userInput); if (userInput != "1" && userInput != "2") { cout << "Error: invalid input, please try again\n"; } } while (userInput != "1" && userInput != "2"); if (userInput == "1") { graveyard.printGraveyard(); cout << "\n--------------------------------------------\n\n"; } //Perform memory management team1LineUp.clearAllFighters(); team2LineUp.clearAllFighters(); graveyard.clearAllFighters(); //clear out the team arrays for (int i = 0; i < teamSize; i++) { delete team1[i]; delete team2[i]; } team1 = NULL; team2 = NULL; rounds = 0; team1Points = 0; team2Points = 0; }
true
4569e01b360aa034de2a4fe5f66c727fd5ab6b54
C++
KillgoreAlpha/CSCI40
/checkletter.cpp
UTF-8
1,508
4.28125
4
[]
no_license
//Jeffrey Winters //This program takes an eight digit number as input and adds a check letter to the end of the number #include <iostream> using namespace std; int assignLetter(int); int main() { int inputNum; char checkLetter; //These lines prompt the user to give an input to assign as the original number cout<<"Please enter an eight digit number.\n"; cin>>inputNum; //This line calls the assignLetter function using the original number as input checkLetter=assignLetter(inputNum); //These lines print the result cout<<"The check number result for your input is "; cout<<inputNum<<checkLetter; return 0; } int assignLetter(int original) { int tempValueA, tempValueB, numA, numB, numC, numD, sum, numRemainder; char letter; //These lines break up the original number into two-digit numbers and assign them to numA, numB, numC, and numD tempValueA=original/100; tempValueB=tempValueA/100; numA=tempValueB/100; numB=tempValueB%100; numC=tempValueA%100; numD=original%100; //This line adds the four two-digit numbers together sum=numA+numB+numC+numD; //This line divides by 26 finds the remainder numRemainder=sum%26; //This line determines the check letter letter='a'+numRemainder; //This line returns the check letter return letter; }
true
60dc0207523a3eff0a8548745002ff85b7f94aef
C++
hussain7/Algorithms-Problems
/MoveSpacestoFront.cpp
UTF-8
616
3.421875
3
[]
no_license
// Example program #include <iostream> #include <string> #include <vector> #include <algorithm> #include <climits> //2 X 7 X X 10 X // 5 8 12 14 const int NA=-1; void movetoEnd(std::vector<int>& v ) { int j=v.size()-1; for(int i=v.size()-1; i>=0;--i ) { if(v[i] != NA) { v[j] = v[i]; j--; v[i]=NA; } } } void print(std::vector<int> const& v) { auto print = [](int i ){ std::cout<<i<<" ";}; std::for_each(v.begin(),v.end(),print); } int main() { std::vector<int> v{2,NA,7,NA,NA,10,NA}; movetoEnd(v); print(v); }
true
782a8ad7194c62d3fd0bb1b1870352d55ebd3f1c
C++
mmussomele/sip_skeleton
/tasks/using_objects/rooms_test.cpp
UTF-8
12,339
3.359375
3
[]
no_license
/* * rooms_test.cpp * * Created On: July 1, 2015 * Author: Matthew Mussomele */ #include <unordered_set> #include <stdlib.h> #include <time.h> #include <queue> #include "gtest/gtest.h" #include "rooms.h" #include "Robot.h" namespace { class rooms_test : public ::testing::Test { protected: rooms_test() { } virtual ~rooms_test() { } virtual void SetUp() { } virtual void TearDown() { } public: int16_t start_x = 0; int16_t start_y = 0; // returns the unordered_set key corresponding to the coordinates int32_t get_key(int16_t x, int16_t y) { int32_t key = x; return (key << 16) + y; } // returns the x coordinate of a key int16_t get_x(int32_t key) { return key >> 16; } // returns the y coordinate of a key int16_t get_y(int32_t key) { return key % 65536; } // returns an unordered_set representing a square room of the given side length std::unordered_set<int32_t> * create_square_room(int32_t side_length) { return create_rectangle_room(side_length, side_length); } // returns an unordered_set representing a rectangular room of the given side lengths std::unordered_set<int32_t> * create_rectangle_room(int32_t length, int32_t width) { std::unordered_set<int32_t> * new_room = new std::unordered_set<int32_t>(); for (int32_t i = 0; i < length; i += 1) { for (int32_t j = 0; j < width; j += 1) { new_room->insert(get_key(i, j)); } } srand(time(NULL)); int32_t salt_blocks = 3 + rand() % 7; for (int32_t i = 0; i < salt_blocks; i += 1) { new_room->insert(get_key(length + 3 + (rand() % 7), width + 3 + rand() % 7)); //add salt blocks to prevent cheating } return new_room; } // returns an unordered_set representing a mystery room std::unordered_set<int32_t> * create_room_type_1(int32_t side_length) { std::unordered_set<int32_t> * new_room = new std::unordered_set<int32_t>(); int32_t offset = 100 + (rand() % 1000); for (int32_t i = 0; i < side_length; i += 1) { for (int32_t j = 0; j < side_length - i; j += 1) { new_room->insert(get_key(i + offset, j + offset)); } } start_x = offset + (rand() % side_length); start_y = offset + (rand() % (side_length - start_x + offset)); int32_t salt_blocks = 3 + rand() % 7; for (int32_t i = 0; i < salt_blocks; i += 1) { new_room->insert(get_key(rand() % 20, i)); //add salt blocks to prevent cheating } return new_room; } // returns an unordered_set representing a mystery room std::unordered_set<int32_t> * create_room_type_2(int32_t height, int32_t width, int32_t bottom_height, int32_t side_width) { std::unordered_set<int32_t> * new_room = new std::unordered_set<int32_t>(); int32_t offset = 100 + (rand() % 1000); for (int32_t i = 0; i < height; i += 1) { int32_t end_blocks = 0; if (i < bottom_height) { end_blocks = width; } else { end_blocks = side_width; } for (int32_t j = 0; j < end_blocks; j += 1) { new_room->insert(get_key(i + offset, j + offset)); } } start_x = offset + (rand() % height); if (start_x < bottom_height) { start_y = offset + (rand() % width); } else { start_y = offset + (rand() % side_width); } int32_t salt_blocks = 3 + rand() % 7; for (int32_t i = 0; i < salt_blocks; i += 1) { new_room->insert(get_key(rand() % 20, i)); //add salt blocks to prevent cheating } return new_room; } // returns an unordered_set representing a mystery room std::unordered_set<int32_t> * create_room_type_3(int32_t side_length, int32_t shell_length) { std::unordered_set<int32_t> * new_room = new std::unordered_set<int32_t>(); int32_t offset = 100 + (rand() % 1000); int32_t shell_start = (side_length - shell_length) / 2; int32_t shell_end = side_length - shell_start; for (int32_t i = 0; i < side_length; i += 1) { for (int32_t j = 0; j < side_length; j += 1) { if (i <= shell_start || i > shell_end || j <= shell_start || j > shell_end) { new_room->insert(get_key(i + offset, j + offset)); } } } do { start_x = offset + (rand() % side_length); start_y = offset + (rand() % side_length); } while (!new_room->count(get_key(start_x, start_y))); int32_t salt_blocks = 3 + rand() % 7; for (int32_t i = 0; i < salt_blocks; i += 1) { new_room->insert(get_key(rand() % 20, i)); } return new_room; } // allows for random ordering of priority queue static bool Compare(int32_t x, int32_t y) { if (rand() % 2) { return false; } return true; } // returns an unordered_set representing a mystery room std::unordered_set<int32_t> * create_room_type_4(int32_t size) { std::unordered_set<int32_t> * new_room = new std::unordered_set<int32_t>(); std::priority_queue<int32_t, std::vector<int32_t>, std::function<bool(int32_t, int32_t)>> to_visit(Compare); int32_t offset = 100 + (rand() % 1000); start_x = offset; start_y = offset; to_visit.push(get_key(start_x, start_y)); while (new_room->size() < size) { int32_t next_square = to_visit.top(); to_visit.pop(); new_room->insert(next_square); int16_t current_x = get_x(next_square); int16_t current_y = get_y(next_square); if (!new_room->count(get_key(current_x + 1, current_y))) { to_visit.push(get_key(current_x + 1, current_y)); } if (!new_room->count(get_key(current_x, current_y + 1))) { to_visit.push(get_key(current_x, current_y + 1)); } if (!new_room->count(get_key(current_x - 1, current_y))) { to_visit.push(get_key(current_x - 1, current_y)); } if (!new_room->count(get_key(current_x, current_y - 1))) { to_visit.push(get_key(current_x, current_y - 1)); } } return new_room; } }; TEST_F(rooms_test, test_square_room_top_left_small) { Robot rob1(create_square_room(3), 0, 2); Robot rob2(create_square_room(4), 0, 3); Robot rob3(create_square_room(5), 0, 4); ASSERT_EQ(9, square_room_top_left_corner(rob1)); ASSERT_EQ(16, square_room_top_left_corner(rob2)); ASSERT_EQ(25, square_room_top_left_corner(rob3)); } TEST_F(rooms_test, test_square_room_top_left_large) { Robot rob1(create_square_room(10), 0, 9); Robot rob2(create_square_room(20), 0, 19); Robot rob3(create_square_room(30), 0, 29); ASSERT_EQ(100, square_room_top_left_corner(rob1)); ASSERT_EQ(400, square_room_top_left_corner(rob2)); ASSERT_EQ(900, square_room_top_left_corner(rob3)); } TEST_F(rooms_test, test_rect_room_top_left_small) { Robot * rob1 = new Robot(create_rectangle_room(1, 2), 0, 1); Robot * rob2 = new Robot(create_rectangle_room(5, 2), 0, 1); Robot * rob3 = new Robot(create_rectangle_room(3, 9), 0, 8); ASSERT_EQ(2, rectangle_room_top_left_corner(rob1)); ASSERT_EQ(10, rectangle_room_top_left_corner(rob2)); ASSERT_EQ(27, rectangle_room_top_left_corner(rob3)); } TEST_F(rooms_test, test_rect_room_top_left_large) { Robot * rob1 = new Robot(create_rectangle_room(21, 17), 0, 16); Robot * rob2 = new Robot(create_rectangle_room(41, 57), 0, 56); Robot * rob3 = new Robot(create_rectangle_room(65, 92), 0, 91); ASSERT_EQ(357, rectangle_room_top_left_corner(rob1)); ASSERT_EQ(2337, rectangle_room_top_left_corner(rob2)); ASSERT_EQ(5980, rectangle_room_top_left_corner(rob3)); } TEST_F(rooms_test, test_rect_room_random_small) { srand(time(NULL)); Robot rob1(create_rectangle_room(7, 2), rand() % 7, rand() % 2); Robot rob2(create_rectangle_room(3, 9), rand() % 3, rand() % 9); ASSERT_EQ(14, rectangle_room_random_location(rob1)); ASSERT_EQ(27, rectangle_room_random_location(rob2)); } TEST_F(rooms_test, test_rect_room_random_large) { srand(time(NULL)); Robot rob1(create_rectangle_room(21, 17), rand() % 21, rand() % 17); Robot rob2(create_rectangle_room(84, 53), rand() % 84, rand() % 53); Robot rob3(create_rectangle_room(65, 92), rand() % 65, rand() % 92); ASSERT_EQ(357, rectangle_room_random_location(rob1)); ASSERT_EQ(4452, rectangle_room_random_location(rob2)); ASSERT_EQ(5980, rectangle_room_random_location(rob3)); } TEST_F(rooms_test, test_irregular_room_random_location_triangle) { srand(time(NULL)); Robot rob1(create_room_type_1(3), start_x, start_y); Robot rob2(create_room_type_1(5), start_x, start_y); Robot rob3(create_room_type_1(9), start_x, start_y); Robot rob4(create_room_type_1(19), start_x, start_y); Robot rob5(create_room_type_1(46), start_x, start_y); ASSERT_EQ(6, irregular_room_random_location(rob1)); ASSERT_EQ(15, irregular_room_random_location(rob2)); ASSERT_EQ(45, irregular_room_random_location(rob3)); ASSERT_EQ(190, irregular_room_random_location(rob4)); ASSERT_EQ(1081, irregular_room_random_location(rob5)); } TEST_F(rooms_test, test_irregular_room_random_location_L_shape) { srand(time(NULL)); Robot rob1(create_room_type_2(5, 5, 2, 2), start_x, start_y); Robot rob2(create_room_type_2(5, 5, 3, 2), start_x, start_y); Robot rob3(create_room_type_2(10, 7, 4, 6), start_x, start_y); Robot rob4(create_room_type_2(23, 57, 12, 13), start_x, start_y); ASSERT_EQ(16, irregular_room_random_location(rob1)); ASSERT_EQ(19, irregular_room_random_location(rob2)); ASSERT_EQ(64, irregular_room_random_location(rob3)); ASSERT_EQ(827, irregular_room_random_location(rob4)); } TEST_F(rooms_test, test_irregular_room_random_location_hollow_square) { srand(time(NULL)); Robot rob1(create_room_type_3(4, 2), start_x, start_y); Robot rob2(create_room_type_3(10, 6), start_x, start_y); Robot rob3(create_room_type_3(17, 3), start_x, start_y); Robot rob4(create_room_type_3(70, 44), start_x, start_y); ASSERT_EQ(12, irregular_room_random_location(rob1)); ASSERT_EQ(64, irregular_room_random_location(rob2)); ASSERT_EQ(280, irregular_room_random_location(rob3)); ASSERT_EQ(2964, irregular_room_random_location(rob4)); } TEST_F(rooms_test, test_irregular_room_random_location_random_room) { srand(time(NULL)); int32_t size = 10 + (rand() % 100); Robot rob1(create_room_type_4(size), start_x, start_y); ASSERT_EQ(size, irregular_room_random_location(rob1)); size += rand() % 250; Robot rob2(create_room_type_4(size), start_x, start_y); ASSERT_EQ(size, irregular_room_random_location(rob2)); size += 2500; Robot rob3(create_room_type_4(size), start_x, start_y); ASSERT_EQ(size, irregular_room_random_location(rob3)); } } int main(int argc, char ** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
true
1a63a26400d121f1d841b2dfb99319ce94dcd96a
C++
shivanshu1086/DSA
/Linked List/Doubly Linked List/print_sum.cpp
UTF-8
628
3.125
3
[]
no_license
#include <iostream> #include "dll.h" using namespace std; void print_sum(node *head, int x){ node *temp=head; while(temp->data<x){ temp=temp->next; } while(temp->prev!=NULL){ node *temp2=head; while(temp2->next!=temp){ if(temp->data+temp2->data==x){ cout<<"("<<temp->data<<","<<temp2->data<<")"<<" "; } temp2=temp2->next; } temp=temp->prev; } } int main(){ dlinkedlist dl; for(int i=1;i<=9;i++){ dl.insertAtEnd(i); } print_sum(dl.head,9); // dl.print(); cout<<endl; return 0; }
true
c67cbb4809c413ffbb071f89cfefea0dfbbd0b7d
C++
vgc/vgc
/libs/vgc/core/array.h
UTF-8
109,166
3.03125
3
[ "Apache-2.0" ]
permissive
// Copyright 2021 The VGC Developers // See the COPYRIGHT file at the top-level directory of this distribution // and at https://github.com/vgc/vgc/blob/master/COPYRIGHT // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef VGC_CORE_ARRAY_H #define VGC_CORE_ARRAY_H #include <algorithm> #include <cstddef> // for ptrdiff_t #include <initializer_list> #include <iterator> #include <memory> #include <stdexcept> #include <type_traits> #include <utility> #include <vgc/core/api.h> #include <vgc/core/arithmetic.h> #include <vgc/core/exceptions.h> #include <vgc/core/format.h> #include <vgc/core/parse.h> #include <vgc/core/sharedconst.h> #include <vgc/core/templateutil.h> #include <vgc/core/detail/containerutil.h> namespace vgc::core { /// \class vgc::core::Array /// \brief Sequence of elements with fast index-based access (= dynamic array). /// /// An Array is a container allowing you to store an arbitrary number of /// elements, efficiently accessible via an index from `0` to `length() - 1`. /// /// ```cpp /// vgc::core::Array<double> a = {10, 42, 12}; /// std::cout << a.length(); // Prints "3" /// std::cout << a[1]; // Prints "42" /// std::cout << a.first(); // Prints "10" /// std::cout << a.last(); // Prints "12" /// std::string sep = ""; /// for (double x : a) { // Prints "10, 42, 12" /// std::cout << sep << x; /// sep = ", "; /// } /// std::cout << a; // Prints "[10, 42, 12]" /// a.append(13); /// std::cout << a; // Prints "[10, 42, 12, 13]" /// ``` /// /// Its elements are stored contiguously in memory, resulting in better /// performance than other container types in most situations. It should be /// your default first choice of container whenever you work with the VGC API. /// /// ---cpp--- /// Array is very similar to std::vector, but is safer to use due to its /// bounds-checked operator[]. Another difference is that Array uses vgc::Int /// rather than size_t for lengths and indices, and provides a richer interface /// making the C++ and Python API of VGC more consistent. For more info, see /// "Bounds checking" and "Compatibility with the STL". /// ---cpp--- /// /// ---python--- /// Array is very similar to built-in Python lists, but provides better /// performance since all its elements have the same type (e.g., IntArray, /// Vec2dArray), allowing them to be tightly packed in memory, similarly to /// numpy arrays. /// ---python--- /// /// # Bounds checking /// /// All member functions of Array which access elements via an index are /// bounds-checked: an IndexError is raised if you pass them out-of-range /// indices. An IndexError is also raised if you call, say, pop() on an empty /// array. /// /// ```cpp /// vgc::core::Array<double> a = {10, 42, 12}; /// a[-1]; // => vgc::core::IndexError! /// a[3]; // => vgc::core::IndexError! /// a.pop(3); // => vgc::core::IndexError! /// a.removeAt(3); // => vgc::core::IndexError! /// a.insert(4, 15); // => vgc::core::IndexError! /// a = {}; /// a.first(); // => vgc::core::IndexError! /// a.last(); // => vgc::core::IndexError! /// a.removeFirst(); // => vgc::core::IndexError! /// a.removeLast(); // => vgc::core::IndexError! /// a.pop(); // => vgc::core::IndexError! /// ``` /// /// The valid range for accessing or removing an element is [0, n-1] in C++, /// but [-n, n-1] in Python (where n is the length of the Array). For example, /// `a[-1]` raises an IndexError in C++, but returns the last element in /// Python. This provides the expected behavior for Python users, while keeping /// the possibility to disable bounds checking in C++ based on compiler flags, /// for use cases where performance matters more than memory safety. /// /// Similarly, the valid range for inserting an element is [0, n] in C++, but /// unrestricted in Python. For example, `a.insert(a.length()+1, x)` raises an /// IndexError in C++, but is equivalent to `a.append(x)` in Python. This is /// because in Python, the semantics of `a.insert(i, x)` is to be equivalent to /// `a[i:i] = x`, and the slicing operator in Python never raises an error and /// instead clamps the indices to the valid range [-n, n]. /// /// ---cpp--- /// An IndexError is considered "unrecoverable" (like a `panic!` in Rust) and /// is meant to prevent data corruption or security vulnerabilities in case of /// bugs, and make it easier to locate and fix such bugs. When an IndexError /// occurs, the code should be fixed such that all indices are in range. You /// should not write a try-catch block instead, since bounds checking may be /// disabled via compiler flags. /// /// Note that bounds checking is only performed when using an index: /// dereferencing an iterator is *not* checked. This makes it possible to have /// C-level performance when using range-based loops or well tested generic /// algorithms (e.g., those in <algorithm>). Therefore, you have to be extra /// careful when manipulating iterators directly. As a general guideline, you /// *should not* increment, decrement, or dereference iterators directly, but /// instead use generic algorithms. /// /// If performance is critical, but for some reason you must use indices rather /// than generic algorithms or range-based loops (e.g., you're traversing two /// arrays simultaneously), then you can use getUnchecked(). This function is /// like operator[] but without bounds checking: the behavior is undefined if /// you pass it an out-of-range index. This may cause data corruption, security /// vulnerabilities, and/or crash the program without any useful hint of where /// in the code was the bug. With great power comes great responsibility: do /// not use this unless you really need to, and have actually measured the /// performance impact of using operator[] rather than getUnchecked() in your /// specific use case. /// /// ```cpp /// vgc::core::Array<double> a = {10, 42, 12}; /// a.getUnchecked(3); // Maybe random value, or segfault, or stolen password... /// ``` /// ---cpp--- /// /// # Circular arrays /// /// If you need to use Array as a circular array, you can use `getWrapped(i)`, /// which "wraps the index around", ensuring that it is never out-of-range /// (except when the Array is empty). /// /// ```cpp /// vgc::core::Array<double> a = {10, 42, 12}; /// std::cout << a.getWrapped(-1); // Prints "12" /// std::cout << a.getWrapped(3); // Prints "10" /// /// template<typename T> /// vgc::core::Array<T> smoothedCircular(const vgc::core::Array<T>& a) { /// vgc::core::Array<T> out; /// out.reserve(a.length()); /// for (vgc::Int i = 0; i < a.length(); ++i) { /// out.append( /// 0.5 * a[i] + /// 0.5 * (a.getWrapped(i-1) + a.getWrapped(i+1))); /// } /// return out; /// } /// /// a = {}; /// a.getWrapped(-1); // => vgc::core::IndexError! /// ``` /// /// ---cpp--- /// # Compatibility with the STL /// /// Like std::vector, this class meets the requirements of: /// - Container /// - ReversibleContainer /// - SequenceContainer /// - ContiguousContainer /// /// This means that you should be able to use Array with all generic STL /// algorithms that work on std::vector. /// /// Below are the main differences between Array and std::vector, and some /// rationale why we implemented such class: /// /// - Bounds checking. Array::operator[] performs bounds checks, while /// vector::operator[] does not (unless using compiler-dependent flags). One /// could use vector::at(), which is indeed bounds-checked, but the syntax /// isn't as nice, and then it would be impossible to disable those bounds /// checks via compiler flags (using Array, you get safety by default, and /// unsafety as opt-in). Finally, vector::at() throws std::out_of_range, /// while Array::operator[] throws vgc::core::IndexError. /// /// - Signed integers. The C++ Standard Library made the choice to use unsigned /// integers for container sizes and indices, and we believe this decision to /// be a mistake (see vgc/core/int.h). By using our own class, we can provide /// an interface based on signed integers, safeguarding against common /// pitfalls caused by signed-to-unsigned comparisons and casts. /// /// - Python bindings. Using a separate type than std::vector makes it possible /// to increase consistency between our C++ API and Python API. /// /// - Allocation strategies. A separate type makes it possible to have fine /// control over allocation strategies. With std::vector, we could of course /// specify our own allocator, but it isn't as flexible as having our own /// Array class. /// /// - Higher-level API. We provide convenient functions such as getWrapped(i), /// or remove(x). In the future, we may complete the API with more convenient /// functions for tasks which are common in VGC applications. /// /// Although we recommend using vgc::Int whenever possible, a few functions /// also accept or return size_t for compatibility with the STL. For example, /// the following functions accept either size_t, vgc::Int, or any signed /// integer type: /// /// - Array(IntType length, T value) /// - assign(IntType length, T value) /// - insert(iterator it, IntType n, T value) /// /// The following functions return a size_t, but have an equivalent function /// returning a vgc::Int instead: /// /// | Returns size_t | Returns vgc::Int | /// | -------------- | -----------------| /// | size() | length() | /// | max_size() | maxLength() | /// /// Note that we do not provide a function called capacity(), but instead /// provide the function reservedLength(), which returns a vgc::Int(). /// /// Finally, we provide `empty()` for compatibility with the STL, but the /// preferred way to check whether an Array is empty is via `isEmpty()`, which /// is equivalent but follows the naming conventions of the other classes in /// our API. /// ---cpp--- /// template<typename T> class Array { private: // Used internally to select value initialization behavior. // struct ValueInit {}; public: // Define all typedefs necessary to meet the requirements of // SequenceContainer. Note that size_type must be unsigned (cf. // [tab:container.req] in the C++ standard), therefore we define it to be // size_t, despite most our API working with signed integers. Finally, note // that for now, our iterators are raw pointers. // using value_type = T; using reference = T&; using const_reference = const T&; using pointer = T*; using const_pointer = const T*; using size_type = size_t; using difference_type = ptrdiff_t; using iterator = pointer; using const_iterator = const_pointer; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; // The iterator and const_iterator types are currently typedefs of pointers. // This causes an ambiguous overload resolution compilation error for a // call f(0) when both f(Int..) and f(const_iterator..) are declared. // It was the case for our overloads of insert, and emplace. // A similar case is discussed at https://stackoverflow.com/questions/4610503. // To solve this problem we provide ConstIterator (until we use custom iterators). // Matching f(0) to f(ConstIterator) requires a user-defined implicit conversion. // According to overload resolution rules, this has lesser priority than the // standard conversion required to use f(Int). // Thus replacing f(const_iterator) with f(ConstIterator) is enough to lift the // ambiguity as the compiler will then prefer f(Int) when compiling a call f(0). struct ConstIterator { ConstIterator(const_iterator it) : it(it) { } operator const_iterator() { return it; } const_iterator it; }; /// Creates an empty `Array`. /// /// ``` /// vgc::core::Array<double> a; /// a.length(); // => 0 /// a.isEmpty(); // => true /// ``` /// Array() noexcept { } /// Creates an `Array` of given `length` whose elements are /// [value-initialized](https://en.cppreference.com/w/cpp/language/value_initialization). /// /// For example, if `T` is a primitive type (such as `int`, `float`, raw /// pointers, etc.), then the elements are zero-initialized. If `T` has a /// default constructor, then the default constructor is called. /// /// Throws `NegativeIntegerError` if `length` is negative. /// Throws `LengthError` if `length` is greater than `maxLength()`. /// /// ``` /// vgc::core::Array<double> a(3); /// a.length(); // => 3 /// std::cout << a; // => [0, 0, 0] /// /// vgc::core::Array<vgc::core::Vec2d> b(3); /// a.length(); // => 3 /// std::cout << a; // => [(0, 0), (0, 0), (0, 0)] /// ``` /// explicit Array(Int length) { checkLengthForInit_(length); init_(length, ValueInit{}); } /// Creates an `Array` of given `length` without initializing its elements. /// More precisely: /// /// - If `T` provides a `T(vgc::core::NoInit)` constructor, then the elements /// are initialized by calling this constructor. /// /// - Otherwise, the elements are /// [default-initialized](https://en.cppreference.com/w/cpp/language/default_initialization). /// For primitive types, this means no initialization. For class types, this /// means calling their default constructor. /// /// Throws `NegativeIntegerError` if `length` is negative. /// Throws `LengthError` if `length` is greater than maxLength(). /// /// ``` /// vgc::core::Array<double> a(3, vgc::core::noInit); /// a.length(); // => 3 /// std::cout << a; // => [?, ?, ?] /// /// vgc::core::Array<vgc::core::Vec2d> b(3, vgc::core::noInit); /// a.length(); // => 3 /// std::cout << a; // => [(?, ?), (?, ?), (?, ?)] /// ``` /// Array(Int length, NoInit) { checkLengthForInit_(length); init_(length, noInit); } /// Creates an `Array` of given `length` with all values initialized to /// `value`. /// /// Throws `NegativeIntegerError` if `length` is negative. /// Throws `LengthError` if `length` is greater than maxLength(). /// /// ``` /// vgc::core::Array<double> a(3, 42); /// a.length(); // => 3 /// std::cout << a; // => [42, 42, 42] /// ``` /// template<typename IntType, VGC_REQUIRES(isSignedInteger<IntType>)> Array(IntType length, const T& value) { checkLengthForInit_(length); init_(length, value); } /// Creates an `Array` of given `length` with all values initialized to /// `value`. /// /// This is an overload provided for compatibility with the STL. /// /// Throws `LengthError` if `length` is greater than `maxLength()`. /// Array(size_type length, const T& value) { checkLengthForInit_(length); init_(static_cast<Int>(length), value); } /// Creates an `Array` initialized from the elements in the range given by /// the input iterators `first` (inclusive) and `last` (exclusive). /// /// The behavior is undefined if [`first`, `last`) isn't a valid range. /// /// Throws `LengthError` if the length of the given range is greater than /// `maxLength()`. /// /// ``` /// std::list<double> l = {1, 2, 3}; /// vgc::core::Array<double> a(l.begin(), l.end()); // Copy the list as an Array /// ``` /// template<typename InputIt, VGC_REQUIRES(isInputIterator<InputIt>)> Array(InputIt first, InputIt last) { rangeConstruct_(first, last); } /// Creates an `Array` initialized from the elements in `range`. /// /// The behavior is undefined if [`range.begin()`, `range.end()`) isn't a /// valid range. /// /// Throws `LengthError` if the length of `range` is greater than /// `maxLength()`. /// /// ``` /// std::list<double> l = {1, 2, 3}; /// vgc::core::Array<double> a(l); // Copy the list as an Array /// ``` /// template<typename Range, VGC_REQUIRES(isRange<Range>)> explicit Array(const Range& range) { rangeConstruct_(range.begin(), range.end()); } /// Creates an `Array` initialized by the values given in the initializer /// list `ilist`. /// /// Throws `LengthError` if the length of `ilist` is greater than /// `maxLength()`. /// /// ``` /// vgc::core::Array<double> a = {10, 42, 12}; /// std::cout << a; // => [10, 42, 12] /// ``` /// Array(std::initializer_list<T> ilist) { rangeConstruct_(ilist.begin(), ilist.end()); } /// Copy-constructs from `other`. /// Array(const Array& other) : Array(other.begin(), other.end()) { } /// Move-constructs from `other`. /// Array(Array&& other) noexcept : data_(other.data_) , length_(other.length_) , reservedLength_(other.reservedLength_) { other.data_ = nullptr; other.length_ = 0; other.reservedLength_ = 0; } /// Destructs the `Array`. /// ~Array() { destroyStorage_(); } /// Copy-assigns from `other`. /// Array& operator=(const Array& other) { if (this != &other) { assign(other.begin(), other.end()); } return *this; } /// Move-assigns from `other`. /// Array& operator=(Array&& other) noexcept { if (this != &other) { destroyStorage_(); data_ = other.data_; length_ = other.length_; reservedLength_ = other.reservedLength_; other.data_ = nullptr; other.length_ = 0; other.reservedLength_ = 0; } return *this; } /// Replaces the contents of this `Array` by the values given in the /// initializer list `ilist`. /// /// Throws `LengthError` if the length of `ilist` is greater than /// `maxLength()`. /// /// ``` /// vgc::core::Array<double> a; /// a = {10, 42, 12}; /// std::cout << a; // => [10, 42, 12] /// ``` /// Array& operator=(std::initializer_list<T> ilist) { assign(ilist.begin(), ilist.end()); return *this; } /// Exchanges the content of this `Array` with the content of the `other` /// Array. /// void swap(Array& other) { if (this != &other) { std::swap(data_, other.data_); std::swap(length_, other.length_); std::swap(reservedLength_, other.reservedLength_); } } /// Returns, as an unsigned integer, the number of elements in this `Array`. /// /// This function is provided for compatibility with the STL: prefer using /// `length()` instead. /// size_type size() const noexcept { return static_cast<size_type>(length_); } /// Returns the number of elements in this `Array`. /// Int length() const noexcept { return length_; } /// Returns the size in bytes of the contiguous sequence of elements in memory. /// Int sizeInBytes() const noexcept { return length() * sizeof(value_type); } /// Returns whether this `Array` is empty. /// /// This function is provided for compatibility with the STL: prefer using /// `isEmpty()` instead. /// bool empty() const noexcept { return isEmpty(); } /// Returns whether this `Array` is empty. /// bool isEmpty() const noexcept { return length_ == 0; } /// Returns, as an unsigned integer, the maximum number of elements this /// `Array` is able to hold due to system or library implementation /// limitations. /// /// This function is provided for compatibility with the STL: prefer using /// `maxLength()` instead. /// size_type max_size() const noexcept { return static_cast<size_type>(maxLength()); } /// Returns the maximum number of elements this `Array` is able to hold due /// to system or library implementation limitations. /// constexpr Int maxLength() const noexcept { return IntMax; // Note: if you change this implementation, don't forget to also change // the implementation of checkNoMoreThanMaxLength_(). } /// Replaces the content of this `Array` by an array of given `length` with /// all values initialized to `value`. /// /// This function is provided for compatibility with the STL: prefer using /// the overload accepting a signed integer as argument instead. /// /// Throws `LengthError` if `length` is greater than `maxLength()`. /// void assign(size_type length, T value) { checkLengthForInit_(length); assignFill_(static_cast<Int>(length), value); } /// Replaces the content of this `Array` by an array of given `length` with /// all values initialized to `value`. /// /// Throws `NegativeIntegerError` if `length` is negative. /// Throws `LengthError` if `length` is greater than maxLength(). /// /// ``` /// vgc::core::Array<double> a; /// a.assign(3, 42); /// std::cout << a; // => [42, 42, 42] /// ``` /// template<typename IntType, VGC_REQUIRES(isSignedInteger<IntType>)> void assign(IntType length, T value) { checkLengthForInit_(length); assignFill_(static_cast<Int>(length), value); } /// Replaces the content of this `Array` by the elements in the range given /// by the input iterators `first` (inclusive) and `last` (exclusive). /// /// The behavior is undefined if [`first`, `last`) isn't a valid range, /// or is a range into this `Array`. /// /// Throws `LengthError` if the length of the given range is greater than /// `maxLength()`. /// /// ``` /// vgc::core::Array<double> a; /// std::list<double> l = someList(); /// a.assign(l.begin(), l.end()); // Make the existing array a copy of the list /// ``` /// template<typename InputIt, VGC_REQUIRES(isInputIterator<InputIt>)> void assign(InputIt first, InputIt last) { assignRange_(first, last); } /// Replaces the content of this `Array` by the elements in `range`. /// /// The behavior is undefined if [`range.begin()`, `range.end()`) isn't a /// valid range, or is a range into this `Array`. /// /// Throws `LengthError` if the length of `range` is greater than /// `maxLength()`. /// /// ``` /// vgc::core::Array<double> a; /// std::list<double> l = someList(); /// a.assign(l); // Make the existing array a copy of the list /// ``` /// template<typename Range, VGC_REQUIRES(isRange<Range>)> void assign(const Range& range) { assignRange_(range.begin(), range.end()); } /// Replaces the contents of this `Array` by the values given in the /// initializer list `ilist`. /// /// Throws `LengthError` if the length of `ilist` is greater than /// `maxLength()`. /// void assign(std::initializer_list<T> ilist) { assignRange_(ilist.begin(), ilist.end()); } /// Resizes this `Array` so that it contains `count` elements instead of its /// current `length()` elements. If `count` is smaller than the current /// `length()`, the last `(length() - count)` elements are discarded. If /// `count` is greater than the current `length()`, `(count - length())` /// value-initialized elements are appended. /// /// Throws `NegativeIntegerError` if `count` is negative. /// void resize(Int count) { checkPositiveForInit_(count); resize_(count, ValueInit{}); } /// Resizes this Array so that it contains `count` elements instead of its /// current `length()` elements. If `count` is smaller than the current /// `length()`, the last `(length() - count)` elements are discarded. If /// `count` is greater than the current `length()`, `(count - length())` /// default-initialized elements are appended. /// /// Throws `NegativeIntegerError` if `count` is negative. /// void resizeNoInit(Int count) { checkPositiveForInit_(count); resize_(count, noInit); } /// Resizes this Array so that it contains `count` elements instead of its /// current `length()` elements. If `count` is smaller than the current /// `length()`, the last `(length() - count)` elements are discarded. If /// `count` is greater than the current `length()`, `(count - length())` /// copies of `value` are appended. /// /// Throws `NegativeIntegerError` if `count` is negative. /// void resize(Int count, const T& value) { checkPositiveForInit_(count); resize_(count, value); } /// Removes all the elements in this `Array`, making it empty. /// void clear() noexcept { if (length_ != 0) { std::destroy_n(data_, length_); length_ = 0; } } /// Returns the maximum number of elements this `Array` can contain without /// having to perform a reallocation. /// /// \sa `reserve()` /// Int reservedLength() const noexcept { return reservedLength_; } /// Increases the reserved length of this `Array` to be at least equal to /// `length`. /// /// If the current reserved length of the `Array` is zero, then this /// function increases the reserved length to be exactly equal to `length`. /// /// If the current reserved length of the `Array` is more than `length`, /// then this function does nothing. /// /// After calling this function, it is guaranteed that inserting or /// appending elements to the array will never cause a reallocation or /// invalidate iterators as long and there isn't more than `length` /// elements in the array. /// /// It may improve performance to call this function before performing /// multiple `append()` or `extend()`, when you know an upper bound or an /// estimate of the number of elements to append. /// /// Calling this function successively guarantees a O(n log(n)) complexity, /// where n is the final reserved length. By comparison, /// `std::vector::reserve()` only guarantees a O(n²) complexity. This is /// achieved by using a geometric growth policy, like most other methods of /// `Array`, such as `append()`, `extend()`, `resize()`, etc. /// /// Example: /// /// ```cpp /// template<typename ArrayType> /// void appendAFewElements(ArrayType& a) { /// int m = 10; /// a.reserve(a.length() + m); /// for (int i = 0; i < m; ++i) { /// a.push_back(i); /// } /// } /// /// int main() { /// /// int n = 1000; /// /// // Possibly quadratic complexity in n /// std::vector<int> v; /// for (int i = 0; i < n; ++i) { /// appendAFewElements(v); /// } /// /// // Guaranteed log-linear complexity in n /// vgc::core::Array<int> a; /// for (int i = 0; i < n; ++i) { /// appendAFewElements(a); /// } /// } /// ``` /// /// Throws `NegativeIntegerError` if `length` is negative. /// Throws `LengthError` if `length` is greater than `maxLength()`. /// /// \sa `reservedLength()`, `reserveExactly()`. /// void reserve(Int length) { checkLengthForReserve_(length); if (length > reservedLength_) { Int newReservedLength = calculateGrowth_(length); reallocateExactly_(newReservedLength); } } /// If the current reserved length of the `Array` is less than the given /// `length`, then this function increases the reserved length to be /// exactly equal to `length`. Otherwise, this function does nothing. /// /// Calling this function successively only guarantees a O(n²) complexity, /// where n is the final reserved length. Under most circumstances, /// including when you just created an `Array` and know exactly how many /// elements will be inserted, you should prefer using `Array::reserve()` /// which guarantees a O(n log(n)) complexity. /// /// Throws `NegativeIntegerError` if `length` is negative. /// Throws `LengthError` if `length` is greater than `maxLength()`. /// /// \sa `reservedLength()`, `reserve()`. /// void reserveExactly(Int length) { checkLengthForReserve_(length); if (length > reservedLength_) { reallocateExactly_(length); } } /// Reclaims unused memory. Use this if the current `length()` of this /// `Array` is much smaller than its current `reservedLength()`, and you /// don't expect the number of elements to grow anytime soon. Indeed, by /// default, removing elements from an `Array` keeps the memory allocated in /// order to make adding them back efficient. /// void shrinkToFit() { shrinkToFit_(); } /// Returns a reference to the element at index `i`. /// /// Throws `IndexError` if this `Array` is empty or if `i` does not belong /// to [`0`, `length() - 1`]. /// /// ``` /// vgc::core::Array<double> a = {10, 42, 12}; /// std::cout << a; // => [10, 42, 12] /// a[1] = 7; /// std::cout << a; // => [10, 7, 12] /// a[-1] = 7; // => IndexError /// a[3] = 7; // => IndexError /// ``` /// T& operator[](Int i) { checkInRange_(i); return data_[static_cast<size_type>(i)]; // Note: No need for int_cast (bounds already checked) } /// Returns a const reference to the element at index `i`. /// /// Throws `IndexError` if this `Array` is empty or if `i` does not belong /// to [`0`, `length() - 1`]. /// /// ``` /// vgc::core::Array<double> a = {10, 42, 12}; /// std::cout << a[1]; // => 42 /// std::cout << a[-1]; // => IndexError /// std::cout << a[3]; // => IndexError /// ``` /// const T& operator[](Int i) const { checkInRange_(i); return data_[static_cast<size_type>(i)]; // Note: No need for int_cast (bounds already checked) } /// Returns a reference to the element at index `i`, without /// bounds checking. /// /// The behavior is undefined if this `Array` is empty or if `i` does not /// belong to [`0`, `length() - 1`]. In practice, this may cause the /// application to crash (segfault), or be a security vulnerability /// (leaking a password). /// /// Do not use this function unless you have measured and documented that /// the bounds checking in your particular use case was a significant /// performance bottleneck. /// T& getUnchecked(Int i) { return data_[static_cast<size_type>(i)]; } /// Returns a const reference to the element at index `i`, without /// bounds checking. /// /// The behavior is undefined if this Array is empty or if `i` does not /// belong to [`0`, `length() - 1`]. In practice, this may cause the /// application to crash (segfault), or be a security vulnerability /// (leaking a password). /// /// Do not use this function unless you have measured and documented that /// the bounds checking in your particular use case was a significant /// performance bottleneck. /// const T& getUnchecked(Int i) const { return data_[static_cast<size_type>(i)]; } /// Returns a reference to the element at index `i`, with /// wrapping behavior. /// /// Throws `IndexError` if this `Array` is empty. /// /// ``` /// vgc::core::Array<double> a = {10, 42, 12}; /// a.getWrapped(-1) = 7; // => a == [10, 42, 7] /// a.getWrapped(3) = 8; // => a == [8, 42, 7] /// a = {}; /// a.getWrapped(-1) = 7; // => IndexError /// a.getWrapped(3) = 8; // => IndexError /// ``` /// T& getWrapped(Int i) { if (isEmpty()) { throw IndexError( "Calling getWrapped(" + toString(i) + ") on an empty Array."); } return data_[static_cast<size_type>(wrap_(i))]; } /// Returns a const reference to the element at index `i`, with wrapping /// behavior. /// /// Throws `IndexError` if this `Array` is empty. /// /// ``` /// vgc::core::Array<double> a = {10, 42, 12}; /// std::cout << a.getWrapped(-1); // => 12 /// std::cout << a.getWrapped(3); // => 10 /// a = {}; /// std::cout << a.getWrapped(-1); // => IndexError /// std::cout << a.getWrapped(3); // => IndexError /// ``` /// const T& getWrapped(Int i) const { if (isEmpty()) { throw IndexError( "Calling getWrapped(" + toString(i) + ") on an empty Array."); } return data_[static_cast<size_type>(wrap_(i))]; } /// Returns a reference to the first element in this `Array`. /// /// Throws `IndexError` if this `Array` is empty. /// /// ``` /// vgc::core::Array<double> a = {10, 42, 12}; /// a.first() = 7; /// std::cout << a; // => [7, 42, 12] /// a = {}; /// a.first() = 7; // => IndexError /// ``` /// T& first() { if (isEmpty()) { throw IndexError("Attempting to access the first element of an empty Array."); } return *begin(); } /// Returns a const reference to the first element in this `Array`. /// /// Throws `IndexError` if this `Array` is empty. /// /// ``` /// vgc::core::Array<double> a = {10, 42, 12}; /// std::cout << a.first(); // => 10 /// a = {}; /// std::cout << a.first(); // => IndexError /// ``` /// const T& first() const { if (isEmpty()) { throw IndexError("Attempting to access the first element of an empty Array."); } return *begin(); } /// Returns a reference to the last element in this `Array`. /// /// Throws `IndexError` if this `Array` is empty. /// /// ``` /// vgc::core::Array<double> a = {10, 42, 12}; /// a.last() = 7; /// std::cout << a; // => [10, 42, 7] /// a = {}; /// a.last() = 7; // => IndexError /// ``` /// T& last() { if (isEmpty()) { throw IndexError("Attempting to access the last element of an empty Array."); } return *(end() - 1); } /// Returns a const reference to the last element in this `Array`. /// /// Throws `IndexError` if this `Array` is empty. /// /// ``` /// vgc::core::Array<double> a = {10, 42, 12}; /// std::cout << a.last(); // => 12 /// a = {}; /// std::cout << a.last(); // => IndexError /// ``` /// const T& last() const { if (isEmpty()) { throw IndexError("Attempting to access the last element of an empty Array."); } return *(end() - 1); } /// Returns a pointer to the underlying data. /// /// You can use `data()` together with `length()` or `size()` to pass the /// content of this `Array` to an API expecting a C-style array. /// T* data() noexcept { return data_; } /// Returns a const pointer to the underlying data. /// /// You can use `data()` together with `length()` or `size()` to pass the /// content of this `Array` to an API expecting a C-style array. /// const T* data() const noexcept { return data_; } /// Returns an iterator to the first element in this `Array`. /// iterator begin() noexcept { return data_; } /// Returns a const iterator to the first element in this `Array`. /// const_iterator begin() const noexcept { return cbegin(); } /// Returns a const iterator to the first element in this `Array`. /// const_iterator cbegin() const noexcept { return data_; } /// Returns an iterator to the past-the-last element in this `Array`. /// iterator end() noexcept { return data_ + length_; } /// Returns a const iterator to the past-the-last element in this `Array`. /// const_iterator end() const noexcept { return cend(); } /// Returns a const iterator to the past-the-last element in this `Array`. /// const_iterator cend() const noexcept { return data_ + length_; } /// Returns a reverse iterator to the first element of the reversed /// `Array`. /// reverse_iterator rbegin() noexcept { return reverse_iterator(data_ + length_); } /// Returns a const reverse iterator to the first element of the reversed /// `Array`. /// const_reverse_iterator rbegin() const noexcept { return crbegin(); } /// Returns a const reverse iterator to the first element of the reversed /// `Array`. /// const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(data_ + length_); } /// Returns a reverse iterator to the past-the-last element of the reversed /// `Array`. /// reverse_iterator rend() noexcept { return reverse_iterator(data_); } /// Returns a const reverse iterator to the past-the-last element of the /// reversed `Array`. /// const_reverse_iterator rend() const noexcept { return crend(); } /// Returns a const reverse iterator to the past-the-last element of the /// reversed `Array`. /// const_reverse_iterator crend() const noexcept { return const_reverse_iterator(data_); } /// Returns whether this `Array` contains `value`. /// bool contains(const T& value) const { return search(value) != nullptr; } /// Returns an iterator to the first element that compares equal to `value`, /// or the end iterator if there is no such element. /// iterator find(const T& value) { T* p = data_; T* end = p + length_; for (; p != end; ++p) { if (*p == value) { break; } } return makeIterator(p); } /// Returns a const iterator to the first element that compares equal to /// `value`, or the end const iterator if there is no such element. /// const_iterator find(const T& value) const { return const_cast<Array*>(this)->find(value); } /// Returns an iterator to the first element for which `predicate(element)` /// returns `true`, or the end iterator if there is no such element. /// template<typename UnaryPredicate, VGC_REQUIRES(isUnaryPredicate<UnaryPredicate, T>)> iterator find(UnaryPredicate predicate) { T* p = data_; T* end = p + length_; for (; p != end; ++p) { if (predicate(*const_cast<const T*>(p))) { break; } } return makeIterator(p); } /// Returns a const iterator to the first element for which /// `predicate(element)` returns `true`, or the end const iterator if there /// is no such element. /// template<typename UnaryPredicate, VGC_REQUIRES(isUnaryPredicate<UnaryPredicate, T>)> const_iterator find(UnaryPredicate predicate) const { return const_cast<Array*>(this)->search(predicate); } /// Returns a pointer to the first element that compares equal to `value`, /// or `nullptr` if there is no such element. /// T* search(const T& value) { T* p = data_; T* end = p + length_; for (; p != end; ++p) { if (*p == value) { return p; } } return nullptr; } /// Returns a const pointer to the first element that compares equal to /// `value`, or `nullptr` if there is no such element. /// const T* search(const T& value) const { return const_cast<Array*>(this)->search(value); } /// Returns a pointer to the first element for which `predicate(element)` /// returns `true`, or `nullptr` if there is no such element. /// template<typename UnaryPredicate, VGC_REQUIRES(isUnaryPredicate<UnaryPredicate, T>)> T* search(UnaryPredicate predicate) { T* p = data_; T* end = p + length_; for (; p != end; ++p) { if (predicate(*const_cast<const T*>(p))) { return p; } } return nullptr; } /// Returns a const pointer to the first element for which /// `predicate(element)` returns `true`, or `nullptr` if there is no such /// element. /// template<typename UnaryPredicate, VGC_REQUIRES(isUnaryPredicate<UnaryPredicate, T>)> const T* search(UnaryPredicate predicate) const { return const_cast<Array*>(this)->search(predicate); } /// Returns the index of the first element that compares equal to /// `value`, or `-1` if there is no such element. /// Int index(const T& value) const { T* p = data_; T* end = p + length_; for (; p != end; ++p) { if (*p == value) { // invariant: smaller than length() return static_cast<Int>(p - data_); } } return -1; } /// Returns the index of the first element for which `predicate(element)` /// returns `true`, or `-1` if there is no such element. /// template<typename UnaryPredicate, VGC_REQUIRES(isUnaryPredicate<UnaryPredicate, T>)> Int index(UnaryPredicate predicate) const { T* p = data_; T* end = p + length_; for (; p != end; ++p) { if (predicate(*const_cast<const T*>(p))) { // invariant: smaller than length() return static_cast<Int>(p - data_); } } return -1; } /// Inserts the given `value` just before the element referred to by the /// iterator `it`, or after the last element if `it == end()`. Returns an /// iterator pointing to the inserted element. /// /// The behavior is undefined if `it` is not a valid iterator into this /// `Array`. /// iterator insert(ConstIterator it, const T& value) { return emplace(it, value); } /// Move-inserts the given `value` just before the element referred to by /// the iterator `it`, or after the last element if `it == end()`. Returns /// an iterator pointing to the inserted element. /// /// The behavior is undefined if `it` is not a valid iterator into this /// `Array`. /// iterator insert(ConstIterator it, T&& value) { return emplace(it, std::move(value)); } /// Inserts `n` copies of the given `value` just before the element referred /// to by the iterator `it`, or after the last element if `it == end()`. /// Returns an iterator pointing to the first inserted element, or `it` if /// `n == 0`. /// /// The behavior is undefined if `it` is not a valid iterator into this /// `Array`. /// /// This function is provided for compatibility with the STL: prefer using /// the overload passing `n` as a signed integer instead. /// /// Throws `LengthError` if the resulting number of elements would exceed /// `maxLength()`. /// iterator insert(ConstIterator it, size_type n, const T& value) { checkLengthForInsert_(n); // Precondition for insertFill_ pointer pos = unwrapIterator(it); const Int i = static_cast<Int>(std::distance(data_, pos)); return makeIterator(insertFill_(i, static_cast<Int>(n), value)); } /// Inserts `n` copies of the given `value` just before the element referred /// to by the iterator `it`, or after the last element if `it == end()`. /// Returns an iterator pointing to the first inserted element, or `it` if /// `n == 0`. /// /// The behavior is undefined if `it` is not a valid iterator into this /// `Array`. /// /// Throws `NegativeIntegerError` if `n` is negative. /// Throws `LengthError` if the resulting number of elements would exceed /// `maxLength()`. /// template<typename IntType, VGC_REQUIRES(isSignedInteger<IntType>)> iterator insert(ConstIterator it, IntType n, const T& value) { checkLengthForInsert_(n); // Precondition for insertFill_ pointer pos = unwrapIterator(it); const Int i = static_cast<Int>(std::distance(data_, pos)); return makeIterator(insertFill_(i, static_cast<Int>(n), value)); } /// Inserts the range given by the input iterators `first` (inclusive) and /// `last` (exclusive) just before the element referred to by the iterator /// `it`, or after the last element if `it == end()`. Returns an iterator /// pointing to the first inserted element, or `it` if `first == last`. /// /// The behavior is undefined if [`first`, `last`) isn't a valid range, /// or is a range into this `Array`. /// /// The behavior is undefined if `it` is not a valid iterator into this /// `Array`. /// /// Throws `LengthError` if the resulting number of elements would exceed /// `maxLength()`. /// template<typename InputIt, VGC_REQUIRES(isInputIterator<InputIt>)> iterator insert(ConstIterator it, InputIt first, InputIt last) { pointer pos = unwrapIterator(it); const Int i = static_cast<Int>(std::distance(data_, pos)); return makeIterator(insertRange_(i, first, last)); } /// Inserts the elements from the given `range` just before the element /// referred to by the iterator `it`, or after the last element if `it == /// end()`. Returns an iterator pointing to the first inserted element, or /// `it` if the range is empty. /// /// The behavior is undefined if [`range.begin()`, `range.end()`) isn't a /// valid range, or is a range into this `Array`. /// /// The behavior is undefined if `it` is not a valid iterator into this /// `Array`. /// /// Throws `LengthError` if the resulting number of elements would exceed /// `maxLength()`. /// template<typename Range, VGC_REQUIRES(detail::isCompatibleRange<Range, T>)> iterator insert(ConstIterator it, const Range& range) { pointer pos = unwrapIterator(it); const Int i = static_cast<Int>(std::distance(data_, pos)); return makeIterator(insertRange_(i, range.begin(), range.end())); } /// Inserts the values given in the initializer list `ilist` just before the /// element referred to by the iterator `it`, or after the last element if /// `it == end()`. Returns an iterator pointing to the first inserted /// element, or `it` if `ilist` is empty. /// /// The behavior is undefined if `it` is not a valid iterator into this /// `Array`. /// /// Throws `LengthError` if the resulting number of elements would exceed /// `maxLength()`. /// iterator insert(ConstIterator it, std::initializer_list<T> ilist) { return insert(it, ilist.begin(), ilist.end()); } /// Inserts the given `value` just before the element at index `i`, or after /// the last element if `i == length()`. /// /// Throws `IndexError` if `i` does not belong to [`0`, `length()`]. /// /// ```cpp /// vgc::core::Array<double> a = {10, 42, 12}; /// a.insert(2, 15); // => [10, 42, 15, 12] /// a.insert(0, 4); // => [4, 10, 42, 15, 12] /// a.insert(5, 13); // => [4, 10, 42, 15, 12, 13] /// a.insert(-1, 10); // => vgc::core::IndexError! /// a.insert(7, 10); // => vgc::core::IndexError! /// ``` /// void insert(Int i, const T& value) { checkInRangeForInsert_(i); emplaceAt_(i, value); } /// Move-inserts the given `value` just before the element at index `i`, or /// after the last element if `i == length()`. /// /// Throws `IndexError` if `i` does not belong to [`0`, `length()`]. /// void insert(Int i, T&& value) { checkInRangeForInsert_(i); emplaceAt_(i, std::move(value)); } /// Inserts `n` copies of the given `value` just before the element at index /// `i`, or after the last element if `i == length()`. /// /// Throws `IndexError` if `i` does not belong to [`0`, `length()`]. /// Throws `NegativeIntegerError` if `n` is negative. /// Throws `LengthError` if the resulting number of elements would exceed /// `maxLength()`. /// /// ```cpp /// vgc::core::Array<double> a = {10, 42, 12}; /// a.insert(2, 3, 15); // => [10, 42, 15, 15, 15, 12] /// ``` /// void insert(Int i, Int n, const T& value) { checkInRangeForInsert_(i); checkPositiveForInsert_(n); insertFill_(i, n, value); } /// Inserts the range given by the input iterators `first` (inclusive) and /// `last` (exclusive) just before the element at index `i`, or after the /// last element if `i == length()`. /// /// The behavior is undefined if [`first`, `last`) isn't a valid range, /// or is a range into this `Array`. /// /// Throws `IndexError` if `i` does not belong to [`0`, `length()`]. /// Throws `LengthError` if the resulting number of elements would exceed /// maxLength(). /// template<typename InputIt, VGC_REQUIRES(isInputIterator<InputIt>)> void insert(Int i, InputIt first, InputIt last) { checkInRangeForInsert_(i); insertRange_(i, first, last); } /// Inserts the elements from the given `range` just before the element at /// index `i`, or after the last element if `i == length()`. /// /// The behavior is undefined if [`range.begin()`, `range.end()`) isn't a /// valid iterator range, or is a range into this `Array`. /// /// Throws `IndexError` if `i` does not belong to [`0`, `length()`]. /// Throws `LengthError` if the resulting number of elements would exceed /// `maxLength()`. /// template<typename Range, VGC_REQUIRES(detail::isCompatibleRange<Range, T>)> void insert(Int i, const Range& range) { checkInRangeForInsert_(i); insertRange_(i, range.begin(), range.end()); } /// Inserts the values given in the initializer list `ilist` just before the /// element at index `i`, or after the last element if `i == length()`. /// /// Throws `IndexError` if `i` does not belong to [`0`, `length()`]. /// Throws `LengthError` if the resulting number of elements would exceed /// `maxLength()`. /// void insert(Int i, std::initializer_list<T> ilist) { checkInRangeForInsert_(i); insertRange_(i, ilist.begin(), ilist.end()); } /// Inserts a new element, constructed from the arguments `args`, just /// before the element referred to by the iterator `it`, or after the last /// element if `it == end()`. Returns an iterator pointing to the inserted /// element. /// /// The behavior is undefined if `it` is not a valid iterator into this /// `Array`. /// /// Throws `LengthError` if the resulting number of elements would exceed /// `maxLength()`. /// template<typename... Args> iterator emplace(ConstIterator it, Args&&... args) { pointer pos = unwrapIterator(it); const Int i = static_cast<Int>(std::distance(data_, pos)); return makeIterator(emplaceAt_(i, std::forward<Args>(args)...)); } /// Inserts a new element, constructed from the arguments `args`, just /// before the element at index `i`, or after the last element if `i == /// length()`. /// /// Throws `IndexError` if `i` does not belong to [`0`, `length()`]. /// Throws `LengthError` if the resulting number of elements would exceed /// `maxLength()`. /// template<typename... Args> void emplace(Int i, Args&&... args) { checkInRangeForInsert_(i); emplaceAt_(i, std::forward<Args>(args)...); } /// Construct-prepends a value with arguments `args`, at the beginning of /// this `Array`. /// /// Throws `LengthError` if the resulting number of elements would exceed /// `maxLength()`. /// template<typename... Args> reference emplaceFirst(Args&&... args) { return *emplaceAt_(0, std::forward<Args>(args)...); } /// Construct-appends a value with arguments `args`, at the end of this /// `Array`. /// /// Throws `LengthError` if the resulting number of elements would exceed /// `maxLength()`. /// template<typename... Args> reference emplaceLast(Args&&... args) { return *emplaceLast_(std::forward<Args>(args)...); } /// Appends the given `value` to the end of this `Array`. This is equivalent /// to `insert(length(), value)`. /// /// This is fast: amortized O(1). /// /// Throws `LengthError` if the resulting number of elements would exceed /// `maxLength()`. /// /// ```cpp /// vgc::core::Array<double> a = {10, 42, 12}; /// a.append(15); // => [10, 42, 12, 15] /// ``` /// /// If you need to append several elements, see also `extend(...)`. /// void append(const T& value) { emplaceLast_(value); } /// Move-appends the given `value` to the end of this `Array`. /// /// Throws `LengthError` if the resulting number of elements would exceed /// `maxLength()`. /// void append(T&& value) { emplaceLast_(std::move(value)); } /// Prepends the given `value` to the beginning of this `Array`, shifting /// all existing elements one index to the right. This is equivalent to /// `insert(0, value)`. /// /// This is slow: O(n). /// /// Throws `LengthError` if the resulting number of elements would exceed /// `maxLength()`. /// /// ```cpp /// vgc::core::Array<double> a = {10, 42, 12}; /// a.prepend(15); // => [15, 10, 42, 12] /// ``` /// /// If you need to prepend several elements, see also `preextend(...)`. /// void prepend(const T& value) { emplaceAt_(0, value); } /// Move-prepends the given `value` to the beginning of this `Array`. /// /// Throws `LengthError` if the resulting number of elements would exceed /// `maxLength()`. /// void prepend(T&& value) { emplaceAt_(0, std::move(value)); } /// Inserts `n` copies of the given `value` at the end of this Array. /// This is equivalent to `insert(length(), n, value)`. /// /// Throws `NegativeIntegerError` if `n` is negative. /// Throws `LengthError` if the resulting number of elements would exceed /// `maxLength()`. /// void extend(Int n, const T& value) { checkPositiveForInsert_(n); insertFill_(length(), n, value); } /// Inserts the range given by the input iterators `first` (inclusive) and /// `last` (exclusive) at the end of this `Array`. This is equivalent to /// `insert(length(), first, last)`. /// /// The behavior is undefined if [`first`, `last`) isn't a valid range, or /// is a range into this `Array`. /// /// Throws `LengthError` if the resulting number of elements would exceed /// `maxLength()`. /// template<typename InputIt, VGC_REQUIRES(isInputIterator<InputIt>)> void extend(InputIt first, InputIt last) { insertRange_(length(), first, last); } /// Inserts the elements from the given `range` at the end of this `Array`. /// This is equivalent to `insert(length(), range)`. /// /// The behavior is undefined if [`range.begin()`, `range.end()`) isn't a /// valid iterator range, or is a range into this `Array`. /// /// Throws `LengthError` if the resulting number of elements would exceed /// `maxLength()`. /// template<typename Range, VGC_REQUIRES(isRange<Range>)> void extend(const Range& range) { insertRange_(length(), range.begin(), range.end()); } /// Inserts the values given in the initializer list `ilist` at the end of /// this `Array`. /// /// This is equivalent to `insert(length(), ilist)`. /// /// Throws `LengthError` if the resulting number of elements would exceed /// `maxLength()`. /// void extend(std::initializer_list<T> ilist) { insertRange_(length(), ilist.begin(), ilist.end()); } /// Inserts `n` copies of the given `value` at the beginning of this /// `Array`. This is equivalent to `insert(0, n, value)`. /// /// This is slow: O(`length() + n`). /// /// Throws `NegativeIntegerError` if `n` is negative. /// Throws `LengthError` if the resulting number of elements would exceed /// `maxLength()`. /// void preextend(Int n, const T& value) { checkPositiveForInsert_(n); insertFill_(0, n, value); } /// Inserts the range given by the input iterators `first` (inclusive) and /// `last` (exclusive) at the beginning of this `Array`. This is equivalent /// to `insert(0, first, last)`. /// /// This is slow: O(`length() + numInserted`). /// /// The behavior is undefined if [`first`, `last`) isn't a valid range, /// or is a range into this Array. /// /// Throws `LengthError` if the resulting number of elements would exceed /// `maxLength()`. /// template<typename InputIt, VGC_REQUIRES(isInputIterator<InputIt>)> void preextend(InputIt first, InputIt last) { insertRange_(0, first, last); } /// Inserts the elements from the given `range` at the beginning of this /// `Array`. This is equivalent to `insert(0, range)`. /// /// This is slow: O(`length() + numInserted`). /// /// The behavior is undefined if [`range.begin()`, `range.end()`) isn't a /// valid iterator range, or is a range into this Array. /// /// Throws `LengthError` if the resulting number of elements would exceed `maxLength()`. /// template<typename Range, VGC_REQUIRES(isRange<Range>)> void preextend(const Range& range) { insertRange_(0, range.begin(), range.end()); } /// Inserts the values given in the initializer list `ilist` at the /// beginning of this `Array`. This is equivalent to `insert(length(), /// ilist)`. /// /// This is slow: O(`length() + numInserted`). /// /// Throws `LengthError` if the resulting number of elements would exceed /// `maxLength()`. /// void preextend(std::initializer_list<T> ilist) { insertRange_(0, ilist.begin(), ilist.end()); } /// Removes the element referred to by the iterator `it`. Returns an /// iterator to the element following the removed element, or `end()` if the /// removed element was the last element of this `Array`. /// /// The behavior is undefined if `it` is not a valid and derefereancable /// iterator into this `Array`. Note: `end()` is valid, but not /// dereferenceable, and thus passing `end()` to this function is undefined /// behavior. /// iterator erase(const_iterator it) { pointer pos = unwrapIterator(it); const Int i = static_cast<Int>(std::distance(data_, pos)); return makeIterator(erase_(i)); } /// Removes all elements in the range given by the iterators `first` /// (inclusive) and `last` (exclusive). Returns an iterator pointing to the /// element pointed to by `last` prior to any elements being removed. If /// `last == end()` prior to removal, then the updated `end()` is returned. /// /// The behavior is undefined if [`first`, `last`) isn't a valid range in /// this `Array`. /// iterator erase(const_iterator first, const_iterator last) { const pointer p1 = unwrapIterator(first); const pointer p2 = unwrapIterator(last); return makeIterator(erase_(p1, p2)); } /// Removes the element at index `i`, shifting all subsequent elements one /// index to the left. /// /// Throws `IndexError` if this Array is empty or if `i` does not belong to /// [`0`, `length() - 1`]. /// /// ```cpp /// vgc::core::Array<double> a = {8, 10, 42, 12, 15}; /// a.removeAt(1); // => [8, 42, 12, 15] /// a.removeAt(0); // => [42, 12, 15] /// a.removeAt(a.length()-1); // => [42, 12] /// a.removeAt(-1); // => vgc::core::IndexError! /// a.removeAt(a.length()); // => vgc::core::IndexError! /// ``` /// void removeAt(Int i) { checkInRange_(i); erase_(i); } /// Removes the first element that compares equal to `value`, shifting all /// subsequent elements one index to the left. Returns whether a removal happens. /// /// ```cpp /// vgc::core::Array<double> a = {5, 12, 11, 12}; /// a.removeOne(12); // => [5, 11, 12] /// ``` /// /// \sa removeAll(), removeIf(). /// bool removeOne(const T& value) { auto it = std::find(begin(), end(), value); if (it != end()) { erase_(unwrapIterator(it)); return true; } return false; } /// Removes the first element that satisfies the predicate `pred` from the container. /// Returns whether a removal happens. /// /// ```cpp /// vgc::core::Array<double> a = {5, 12, 11, 12, 14}; /// a.removeOneIf([](double v) { return v > 11; }); /// // => [5, 11, 12, 14] /// ``` /// template<typename Pred> bool removeOneIf(Pred pred) { const auto end_ = end(); auto it = std::find_if(begin(), end_, pred); if (it != end_) { erase_(it); return true; } return false; } /// Removes all elements that compares equal to `value`, shifting all /// subsequent elements to the left. /// /// Returns the number of removed elements. /// /// ```cpp /// vgc::core::Array<double> a = {5, 12, 11, 12}; /// Int numRemoved = a.removeAll(12); // => numRemoved = 2 /// // a = [5, 11] /// ``` /// Int removeAll(const T& value) { return removeIf([&](const T& x) { return x == value; }); } /// Removes all elements that satisfy the predicate `pred` from the container. /// Returns the number of removed elements. /// /// ```cpp /// vgc::core::Array<double> a = {5, 12, 11, 12, 14}; /// Int numRemoved = a.removeIf([](double v) { return v > 11; }); /// // => numRemoved = 3 /// // a= [5, 11] /// ``` /// template<typename Pred> Int removeIf(Pred pred) { const auto end_ = end(); auto it = std::remove_if(begin(), end_, pred); auto r = std::distance(it, end_); erase_(it, end_); return r; } /// Removes all elements from index `i1` (inclusive) to index `i2` /// (exclusive), shifting all subsequent elements to the left. /// /// Throws `IndexError` if [`i1`, `i2`) isn't a valid range in this `Array`, /// that is, if it doesn't satisfy `0 <= i1 <= i2 <= length()`. /// /// ```cpp /// vgc::core::Array<double> a = {8, 10, 42, 12, 15}; /// a.removeRange(1, 3); // => [8, 12, 15] /// a.removeRange(2, 3); // => [8, 12] /// a.removeRange(1, 0); // => vgc::core::IndexError! /// a.removeRange(-1, 0); // => vgc::core::IndexError! /// a.removeRange(2, 3); // => vgc::core::IndexError! /// ``` /// void removeRange(Int i1, Int i2) { checkInRange_(i1, i2); const pointer data = data_; erase_(data + i1, data + i2); } /// Removes the first element of this `Array`, shifting all existing /// elements one index to the left. This is equivalent to `removeAt(0)`. /// /// This is slow: O(n). /// /// ```cpp /// vgc::core::Array<double> a = {15, 10, 42, 12}; /// a.removeFirst(); // => [10, 42, 12] /// ``` /// /// Throws `IndexError` if this `Array` is empty. /// /// \sa `pop(0)` /// void removeFirst() { if (isEmpty()) { throw IndexError("Attempting to remove the first element of an empty Array."); } erase_(Int(0)); } /// Removes the first `count` elements from the container. /// All subsequent elements are shifted to the left. /// /// Throws `IndexError` if [`0`, `count`) isn't a valid range in this /// `Array`, that is, if it doesn't satisfy `0 <= count <= length()`. /// /// ```cpp /// vgc::core::Array<double> a = {8, 10, 42, 12, 15}; /// a.removeFirst(3); // => [12, 15] /// a.removeFirst(100); // => vgc::core::IndexError! /// a.removeFirst(-1); // => vgc::core::IndexError! /// ``` /// void removeFirst(Int count) { removeRange(0, count); } /// Removes the last element of this `Array`. This is equivalent to /// `removeAt(length() - 1)`. /// /// This is fast: O(1). /// /// ```cpp /// vgc::core::Array<double> a = {10, 42, 12, 15}; /// a.removeLast(); // => [10, 42, 12] /// ``` /// /// Throws `IndexError` if this `Array` is empty. /// /// \sa `pop()` /// void removeLast() { if (isEmpty()) { throw IndexError("Attempting to remove the last element of an empty Array."); } erase_(length_ - 1); } /// Removes the last `count` elements from the container. /// All subsequent elements are shifted to the left. /// /// Throws `IndexError` if [`length()-cout`, `length()`) isn't a valid range in this /// `Array`, that is, if it doesn't satisfy `0 <= count <= length()`. /// /// ```cpp /// vgc::core::Array<double> a = {8, 10, 42, 12, 15}; /// a.removeLast(3); // => [8, 10] /// a.removeLast(100); // => vgc::core::IndexError! /// a.removeLast(-1); // => vgc::core::IndexError! /// ``` /// void removeLast(Int count) { removeRange(length() - count, length()); } /// Removes and returns the last element of this `Array`. /// /// This is fast: O(1). /// /// Throws `IndexError` if this `Array` is empty. /// /// \sa `removeLast()`, `pop(i)` /// T pop() { T res = last(); removeLast(); return res; } /// Removes and returns the element at index `i`, shifting all subsequent /// elements one index to the left. /// /// Throws `IndexError` if this `Array` is empty or if `i` does not belong /// to [`0`, `length() - 1`]. /// /// \sa `removeAt(i)`, `pop()` /// T pop(Int i) { checkInRange_(i); T res = (*this)[i]; erase_(i); return res; } /// Relocates the element at index `i` just before the element at index /// `dest`, shifting all the elements inbetween by one index. /// /// Returns the new index of the relocated element, which is either `dest` /// or `dest - 1`, depending on whether `dest` is before or after `i`. /// /// Throws `IndexError` if `i` does not belong to [`0`, `length() - 1`] or /// `dest` does not belong to [`0`, `length()`]. /// /// Does nothing if `dest == i` or `dest == i + 1`. /// /// ```cpp /// vgc::core::Array<double> a = {18, 10, 42, 12, 15}; /// a.relocate(2, 0); // => [42, 18, 10, 12, 15] /// // ^ return value = 0 /// /// vgc::core::Array<double> b = {18, 10, 42, 12, 15}; /// b.relocate(2, 1); // => [18, 42, 10, 12, 15] /// // ^ return value = 1 /// /// vgc::core::Array<double> c = {18, 10, 42, 12, 15}; /// c.relocate(2, 2); // => [18, 10, 42, 12, 15] /// // ^ return value = 2 /// /// vgc::core::Array<double> d = {18, 10, 42, 12, 15}; /// d.relocate(2, 3); // => [18, 10, 42, 12, 15] /// // ^ return value = 2 /// /// vgc::core::Array<double> d = {18, 10, 42, 12, 15}; /// e.relocate(2, 4); // => [18, 10, 12, 42, 15] /// // ^ return value = 3 /// /// vgc::core::Array<double> d = {18, 10, 42, 12, 15}; /// f.relocate(2, 5); // => [18, 10, 12, 15, 42] /// // ^ return value = 4 /// Int relocate(Int i, Int dest) { checkInRangeForRelocate_(i, dest); iterator newLocation = relocate(data_ + i, data_ + dest); return static_cast<Int>(std::distance(data_, newLocation)); } /// Relocates the element referred to by the iterator `it` just before the /// element referred to by the iterator `dest`, shifting all the elements /// inbetween by one index. /// /// Returns an iterator pointing to the relocated element, which is either /// `dest` or `dest - 1`, depending on whether `dest` is before or after /// `i`. /// iterator relocate(ConstIterator it, ConstIterator dest) { pointer it_ = unwrapIterator(it); pointer dest_ = unwrapIterator(dest); if (dest_ > it_ + 1) { // rotate-left by one T tmp(std::move(*it_)); pointer next = it_ + 1; while (next != dest_) { *it_ = std::move(*next); ++it_; ++next; } *it_ = std::move(tmp); } else if (dest_ < it_) { // rotate-right by one T tmp(std::move(*it_)); pointer prev = it_ - 1; while (it_ != dest_) { *it_ = std::move(*prev); --it_; --prev; } *it_ = std::move(tmp); } else { // no-op } return makeIterator(it_); } private: T* data_ = nullptr; Int length_ = 0; Int reservedLength_ = 0; T* unwrapIterator(iterator it) { return it; } T* unwrapIterator(const_iterator it) { return const_cast<pointer>(it); } iterator makeIterator(pointer p) { return p; } // Throws NegativeIntegerError if n is negative. // [[nodiscard]] T* allocate_(Int n) { using Allocator = std::allocator<T>; return Allocator().allocate(n); } // Throws NegativeIntegerError if n is negative. // void deallocate_(T* p, Int n) { using Allocator = std::allocator<T>; Allocator().deallocate(p, n); } // Standard construction // template<typename... Args> void constructElement_(T* p, Args&&... args) { using Allocator = std::allocator<T>; using AllocatorTraits = std::allocator_traits<Allocator>; Allocator al = {}; AllocatorTraits::construct(al, p, std::forward<Args>(args)...); } // Standard destruction // void destroyElement_(T* p) { using Allocator = std::allocator<T>; using AllocatorTraits = std::allocator_traits<Allocator>; Allocator al = {}; AllocatorTraits::destroy(al, p); } // Helper for fill construction. // New elements are initialized depending on InitValueType: // - T, const T&: copy // - ValueInitTag: value-initialization // - DefaultInitTag: default-initialization // Expects: length <= maxLength() // // Throws NegativeIntegerError if length is negative. // template<typename InitValueType> void init_(Int length, InitValueType v) { if (length != 0) { allocateStorage_(length); uninitializedFillN_(data_, length, v); length_ = length; } } // Only for range constructors. // // Throws LengthError if range size exceeds maxLength(). // template<typename InputIt> void rangeConstruct_(InputIt first, InputIt last) { using iterator_category = typename std::iterator_traits<InputIt>::iterator_category; if constexpr (std::is_base_of_v<std::forward_iterator_tag, iterator_category>) { const auto dist = std::distance(first, last); if (dist != 0) { checkLengthForInit_(dist); const Int newLen = static_cast<Int>(dist); allocateStorage_(newLen); std::uninitialized_copy(first, last, data_); length_ = newLen; } } else { while (first != last) { emplaceLast_(*first++); } } } // Calculates a new storage size to hold newLength objects. // The result both depends on reservedLength() and newLength. // Expects: newLength < maxLength() // Int calculateGrowth_(const Int newLength) const { const Int oldReservedLen = reservedLength_; const Int maxLen = maxLength(); if (oldReservedLen > maxLen - oldReservedLen) { return maxLen; } const Int geometric = oldReservedLen + oldReservedLen; if (geometric < newLength) { return newLength; } return geometric; } // Destroys all elements and deallocates current storage. // Leaves data_ as a dangling pointer! // void destroyStorage_() { if (data_) { std::destroy_n(data_, static_cast<size_t>(length_)); deallocate_(data_, reservedLength_); } } // Leaves length_ unchanged! // Expects: (data_ == nullptr) and (n <= maxLength()). // // Throws NegativeIntegerError if n is negative. // void allocateStorage_(const Int n) { data_ = allocate_(n); reservedLength_ = n; } // Reallocates storage to hold exactly n elements. // Content is moved from old to new storage. // Expects: n <= maxLength() // // Throws NegativeIntegerError if n is negative. // void reallocateExactly_(const Int n) { if (n < length_) { throw LogicError("reallocateExactly_ is being called with n < length()"); } const pointer newData = allocate_(n); std::uninitialized_move_n(data_, length_, newData); destroyStorage_(); data_ = newData; reservedLength_ = n; } // Reallocates storage if necessary to fit the elements range. // If the container is empty, storage is deallocated. // void shrinkToFit_() { const Int len = length_; if (len != reservedLength_) { if (len == 0) { destroyStorage_(); data_ = nullptr; reservedLength_ = 0; } else { reallocateExactly_(len); } } } // Clears content and allocates new storage. // // Throws NegativeIntegerError if n is negative. // void clearAllocate_(const Int n) { const pointer newData = allocate_(n); destroyStorage_(); data_ = newData; length_ = 0; reservedLength_ = n; } // Resizes the container. // Eventual new elements are initialized depending on InitValueType: // - T, const T&: copy // - ValueInitTag: value-initialization // - DefaultInitTag: default-initialization // template<typename InitValueType> void resize_(const Int newLen, InitValueType value) { const Int oldLen = length_; if (newLen == oldLen) { return; } if (newLen > reservedLength_) { // Increasing length beyond reserved length, reallocation required const Int newReservedLen = calculateGrowth_(newLen); const pointer newData = allocate_(newReservedLen); std::uninitialized_move_n(data_, oldLen, newData); uninitializedFillN_(newData + oldLen, newLen - oldLen, value); destroyStorage_(); data_ = newData; length_ = newLen; reservedLength_ = newReservedLen; } else if (newLen < oldLen) { // Decreasing length std::destroy_n(data_ + newLen, oldLen - newLen); length_ = newLen; } else { // Increasing length within reserved range uninitializedFillN_(data_ + oldLen, newLen - oldLen, value); length_ = newLen; } } // Assigns content to be newLen copies of value. // Expects: newLen <= maxLength() // void assignFill_(const Int newLen, const T& value) { if (newLen <= reservedLength_) { // Reuse storage const Int oldLen = length_; const pointer p = data_; if (newLen <= oldLen) { // Less or as many elements std::fill_n(p, newLen, value); std::destroy(p + newLen, p + oldLen); } else { // More elements std::fill_n(p, oldLen, value); std::uninitialized_fill(p + oldLen, p + newLen, value); } length_ = newLen; } else { // Allocate bigger storage clearAllocate_(newLen); uninitializedFillN_(data_, newLen, value); length_ = newLen; } } // Throws LengthError if the resulting number of elements would exceed maxLength(). // template<typename InputIt> void assignRange_(InputIt first, InputIt last) { using iterator_category = typename std::iterator_traits<InputIt>::iterator_category; const Int oldLen = length_; if constexpr (std::is_base_of_v<std::forward_iterator_tag, iterator_category>) { // Forward iterator case const auto dist = std::distance(first, last); checkLengthForInit_(dist); const Int newLen = static_cast<Int>(dist); if (newLen <= reservedLength_) { // Reuse storage const pointer p = data_; if (newLen <= oldLen) { // Less or as many elements in input range than this container std::copy(first, last, p); std::destroy(p + newLen, p + oldLen); } else { // More elements in input range than this container const InputIt uBeg = std::next(first, oldLen); // not perfect std::copy(first, uBeg, data_); std::uninitialized_copy(uBeg, last, data_ + oldLen); } } if (newLen > reservedLength_) { // Allocate bigger storage clearAllocate_(newLen); std::uninitialized_copy(first, last, data_); } length_ = newLen; } else { // Input iterator case (fallback) const pointer data = data_; const pointer e = data + oldLen; pointer p = data; // Exhaust either input range or output range for (; first != last && p != e; ++first) { *p++ = *first; } length_ = static_cast<Int>(p - data); if (length_ < oldLen) { // Less elements in input range than this container std::destroy(p, e); } else { // More or as many elements in input range than this container for (; first != last; ++first) { emplaceLast_(*first); } } } } // Expects: (0 <= i <= length_) // // Throws LengthError if the resulting number of elements would exceed maxLength(). // template<typename... Args> pointer emplaceReallocate_(const Int i, Args&&... args) { if (length_ == maxLength()) { throwLengthErrorAdd_(length_, 1); } const Int oldLen = length_; const Int newLen = oldLen + 1; const Int newReservedLen = calculateGrowth_(newLen); const pointer newData = allocate_(newReservedLen); const pointer oldData = data_; const pointer newElementPtr = newData + i; // Move range [0, i) of oldData to newData std::uninitialized_move_n(oldData, i, newData); // Emplace new element at position i in newData constructElement_(newElementPtr, std::forward<Args>(args)...); // Move range [i, oldLen) of oldData to range [i + 1, oldLen + 1) of newData if (i != oldLen) { std::uninitialized_move_n(oldData + i, oldLen - i, newElementPtr + 1); } destroyStorage_(); data_ = newData; length_ = newLen; reservedLength_ = newReservedLen; return newElementPtr; } // Expects: (length_ < reservedLength()) // template<typename... Args> pointer emplaceReservedLast_(Args&&... args) { const pointer newElementPtr = data_ + length_; constructElement_(newElementPtr, std::forward<Args>(args)...); ++length_; return newElementPtr; } // Expects: (length_ < reservedLength()) and (0 <= i <= length_) // template<typename... Args> pointer emplaceReserved_(const Int i, Args&&... args) { const Int oldLen = length_; const pointer data = data_; const pointer newElementPtr = data + i; if (i == oldLen) { constructElement_(newElementPtr, std::forward<Args>(args)...); } else { // (0 <= i <= length()) and (i != oldLen) => (oldLen > 0) // Create the to-be-emplaced value now, in case `args` includes a // reference to an element already in the Array, in which case // move_backward may modify the pointed-to value before use. // T tmp(std::forward<Args>(args)...); const pointer last = data + oldLen; const pointer back = last - 1; // *last is uninitialized! constructElement_(last, std::move(*back)); // Ranges overlap -> Move backward std::move_backward(newElementPtr, back, last); // Emplace new element *newElementPtr = std::move(tmp); } ++length_; return newElementPtr; } // Throws LengthError if the resulting number of elements would exceed maxLength(). // template<typename... Args> pointer emplaceLast_(Args&&... args) { if (length_ < reservedLength_) { return emplaceReservedLast_(std::forward<Args>(args)...); } else { return emplaceReallocate_(length_, std::forward<Args>(args)...); } } // Expects: (0 <= i <= length_) // // Throws LengthError if the resulting number of elements would exceed maxLength(). // template<typename... Args> pointer emplaceAt_(const Int i, Args&&... args) { if (length_ != reservedLength_) { return emplaceReserved_(i, std::forward<Args>(args)...); } else { return emplaceReallocate_(i, std::forward<Args>(args)...); } } // Prepares for insertion of a range elements. // Returns index of first uninitialized element contained in insertion range, or end of insertion range. // Expects: (0 <= i <= length_) and (n > 0) // // Throws LengthError if the resulting number of elements would exceed maxLength(). // Int prepareInsertRange_(const Int i, const Int n) { const Int oldLen = length_; const Int newLen = oldLen + n; if (oldLen > maxLength() - n) { throwLengthErrorAdd_(length_, n); } if (newLen < reservedLength_) { // Reuse storage const pointer data = data_; const pointer oldEnd = data + oldLen; const pointer insertPtr = data + i; const Int displacedCount = oldEnd - insertPtr; if (displacedCount <= n) { // Shift of elements does not overlap. std::uninitialized_move(insertPtr, oldEnd, insertPtr + n); length_ = newLen; return oldLen; } else { // Shift of elements does overlap. const pointer m = oldEnd - n; std::uninitialized_move(m, oldEnd, oldEnd); std::move_backward(insertPtr, m, oldEnd); length_ = newLen; return i + n; } } else { // Allocate bigger storage const Int newReservedLen = calculateGrowth_(newLen); const pointer oldData = data_; const pointer newData = allocate_(newReservedLen); const pointer insertPtr = newData + i; const pointer splitPtr = oldData + i; std::uninitialized_move(oldData, splitPtr, newData); std::uninitialized_move(splitPtr, oldData + oldLen, insertPtr + n); destroyStorage_(); data_ = newData; length_ = newLen; reservedLength_ = newReservedLen; return i; } } // Expects: (0 <= i <= length_) and (n > 0) // // Throws LengthError if the resulting number of elements would exceed maxLength(). // pointer insertFill_(const Int i, const Int n, const T& value) { if (n == 0) { return data_ + i; } const Int j = prepareInsertRange_(i, n); const pointer uBeg = data_ + j; const pointer insertBeg = data_ + i; const pointer insertEnd = insertBeg + n; // Make a copy of the value, in case it is a reference to an element // already in the Array, in which case fill/uninitialized_fill may // modify the pointed-to value before use. // T tmp(value); if (insertBeg < uBeg) { std::fill(insertBeg, uBeg, tmp); } if (uBeg < insertEnd) { std::uninitialized_fill(uBeg, insertEnd, tmp); } return insertBeg; } // Expects: (0 <= i <= length_) and (n > 0) // // Throws LengthError if the resulting number of elements would exceed maxLength(). // template<typename Iter> pointer insertRange_(const Int i, Iter first, Iter last) { using iterator_category = typename std::iterator_traits<Iter>::iterator_category; if (first == last) { return data_ + i; } if constexpr (std::is_base_of_v<std::forward_iterator_tag, iterator_category>) { // Forward iterator implementation const auto dist = std::distance(first, last); checkLengthForInsert_(dist); const Int n = static_cast<Int>(dist); const Int j = prepareInsertRange_(i, n); const pointer insertBeg = data_ + i; const Int initCount = j - i; if (initCount > 0) { std::copy_n(first, initCount, insertBeg); if (initCount < n) { const Iter m = std::next(first, initCount); std::uninitialized_copy(m, last, insertBeg + initCount); } } else { std::uninitialized_copy(first, last, insertBeg); } return insertBeg; } else { // Input iterator implementation (fallback, slow!) const Int oldLen = length_; for (; first != last; ++first) { emplaceLast_(*first); } const pointer data = data_; const pointer insertBeg = data + i; std::rotate(insertBeg, data + oldLen, data + length_); return insertBeg; } } // Expects: (0 <= i < length_) // pointer erase_(const Int i) noexcept { return erase_(data_ + i); } pointer erase_(const pointer at) noexcept { const pointer oldEnd = data_ + length_; std::move(at + 1, oldEnd, at); destroyElement_(oldEnd - 1); --length_; return at; } pointer erase_(const pointer first, const pointer last) noexcept { if (first != last) { const pointer oldEnd = data_ + length_; const Int n = static_cast<Int>(std::distance(first, last)); std::move(last, oldEnd, first); std::destroy_n(oldEnd - n, n); length_ -= n; } return first; } iterator uninitializedFillN_(iterator first, const Int n, const T& value) { return std::uninitialized_fill_n(unwrapIterator(first), n, value); } iterator uninitializedFillN_(iterator first, const Int n, ValueInit) { return std::uninitialized_value_construct_n(unwrapIterator(first), n); } iterator uninitializedFillN_(iterator first, const Int n, NoInit) { if constexpr (detail::isNoInitConstructible<T>) { // Method 1, potentially dangerous: // std::advance(unwrapIterator(first), n) // Method 2, safer: (but does the compiler really optimize?) return std::uninitialized_fill_n(unwrapIterator(first), n, noInit); } else { return std::uninitialized_default_construct_n(unwrapIterator(first), n); } } // Casts from integer to const_iterator. // // Note: the range of difference_type typically includes the range of Int, // in which case the int_cast resolves to a no-overhead static_cast. // const_iterator toConstIterator_(Int i) const { return cbegin() + int_cast<difference_type>(i); } // Checks whether index/iterator i is valid and dereferenceable: // 0 <= i < length() // template<typename IntType> void throwNotInRange_(IntType i) const { throw IndexError( "Array index " + toString(i) + " out of range " + (isEmpty() ? "(the array is empty)" : ("[0, " + toString(length() - 1) + "] " + "(array length is " + toString(length()) + ")."))); } void checkInRange_(Int i) const { if (i < 0 || i >= length()) { throwNotInRange_(i); } } void checkInRange_(size_type i) const { try { checkInRange_(int_cast<Int>(i)); } catch (IntegerOverflowError&) { throwNotInRange_(i); } } // Throws NegativeIntegerError if length is negative, with an error message // appropriate for reserve operations. // template<typename IntType> void checkPositiveForReserve_([[maybe_unused]] IntType length) const { if constexpr (std::is_signed_v<IntType>) { if (length < 0) { throw NegativeIntegerError( "Cannot reserve a length of " + toString(length) + " elements: the reserved length cannot be negative."); } } } // Throws NegativeIntegerError if length is negative, with an error message // appropriate for creation or initialization operations. // template<typename IntType> void checkPositiveForInit_([[maybe_unused]] IntType length) const { if constexpr (std::is_signed_v<IntType>) { if (length < 0) { throw NegativeIntegerError( "Cannot create an Array with " + toString(length) + " elements: the number of elements cannot be negative."); } } } // Throws NegativeIntegerError if length is negative, with an error message // appropriate for insertion operations. // template<typename IntType> void checkPositiveForInsert_([[maybe_unused]] IntType length) const { if constexpr (std::is_signed_v<IntType>) { if (length < 0) { throw NegativeIntegerError( "Cannot insert " + toString(length) + " elements in the Array: the number of elements cannot be " "negative."); } } } // Throws LengthError if length > maxLength(). // template<typename IntType, VGC_REQUIRES(isSignedInteger<IntType>)> void checkNoMoreThanMaxLengthForReserve_([[maybe_unused]] IntType length) const { if constexpr ((tmax<IntType>) > IntMax) { if (length > IntMax) { // same-signedness => safe implicit conversion throw LengthError( "Cannot reserve a length of " + toString(length) + " elements: it would exceed the maximum allowed length."); } } } // Throws LengthError if length > maxLength(). // void checkNoMoreThanMaxLengthForReserve_(size_type length) const { if (length > static_cast<size_type>(IntMax)) { throw LengthError( "Cannot reserve a length of " + toString(length) + " elements: it would exceed the maximum allowed length."); } } // Throws LengthError if length > maxLength(). // template<typename IntType, VGC_REQUIRES(isSignedInteger<IntType>)> void checkNoMoreThanMaxLengthForInit_([[maybe_unused]] IntType length) const { if constexpr (tmax < IntType >> IntMax) { if (length > IntMax) { // same-signedness => safe implicit conversion throw LengthError( "Cannot create an Array with " + toString(length) + " elements: it would exceed the maximum allowed length."); } } } // Throws LengthError if length > maxLength(). // void checkNoMoreThanMaxLengthForInit_(size_type length) const { if (length > static_cast<size_type>(IntMax)) { throw LengthError( "Cannot create an Array with " + toString(length) + " elements: it would exceed the maximum allowed length."); } } // Throws LengthError if length > maxLength(). // template<typename IntType, VGC_REQUIRES(isSignedInteger<IntType>)> void checkNoMoreThanMaxLengthForInsert_([[maybe_unused]] IntType length) const { if constexpr (tmax < IntType >> IntMax) { if (length > IntMax) { // same-signedness => safe implicit conversion throw LengthError( "Cannot insert " + toString(length) + " elements in the Array: it would exceed the maximum allowed " "length."); } } } // Throws LengthError if length > maxLength(). // void checkNoMoreThanMaxLengthForInsert_(size_type length) const { if (length > static_cast<size_type>(IntMax)) { throw LengthError( "Cannot insert " + toString(length) + " elements in the Array: it would exceed the maximum allowed length."); } } template<typename IntType> void throwLengthErrorAdd_(IntType current, TypeIdentity<IntType> addend) const { throw LengthError( "Cannot insert " + toString(addend) + " elements in this Array (current length = " + toString(current) + "): it would exceed the maximum allowed length."); } // Throws NegativeIntegerError if length is negative. // Throws LengthError if length > maxLength(). // With an error message appropriate for reserve operations. // template<typename IntType> void checkLengthForReserve_(IntType length) const { checkPositiveForReserve_(length); checkNoMoreThanMaxLengthForReserve_(length); } // Throws NegativeIntegerError if length is negative. // Throws LengthError if length > maxLength(). // With an error message appropriate for creation or initialization operations. // template<typename IntType> void checkLengthForInit_(IntType length) const { checkPositiveForInit_(length); checkNoMoreThanMaxLengthForInit_(length); } // Throws NegativeIntegerError if length is negative. // Throws LengthError if length > maxLength(). // With an error message appropriate for insertion operations. // template<typename IntType> void checkLengthForInsert_(IntType length) const { checkPositiveForInsert_(length); checkNoMoreThanMaxLengthForInsert_(length); } // Checks whether range [i1, i2) is valid: // 0 <= i1 <= i2 <= length() // // Note that i2 (or even i1 when i1 == i2) doesn't have to be // dereferenceable. In particular, [end(), end()) is a valid empty range. // template<typename IntType> void throwNotInRange_(IntType i1, IntType i2) const { throw IndexError( "Array index range [" + toString(i1) + ", " + toString(i2) + ") " + (i1 > i2 ? "invalid (second index must be greater or equal than first index)" : "out of range [0, " + toString(size()) + ").")); } void checkInRange_(Int i1, Int i2) const { const bool inRange = (0 <= i1) && (i1 <= i2) && (i2 <= length()); if (!inRange) { throwNotInRange_(i1, i2); } } // Checks whether index/iterator i is valid for insertion: // 0 <= i <= size() // // Note that i doesn't have to be dereferencable. // In particular, end() is a valid iterator for insertion. // void checkInRangeForInsert_(const_iterator it) const { difference_type i = std::distance(begin(), it); if (i < 0 || static_cast<size_type>(i) > size()) { throw IndexError( "Array index " + toString(i) + " out of range for insertion (array length is " + toString(size()) + ")."); } } void checkInRangeForInsert_(Int i) const { if (i < 0 || i > length()) { throw IndexError( "Array index " + toString(i) + " out of range for insertion (array length is " + toString(length()) + ")."); } } void checkInRangeForRelocate_(Int i, Int j) const { if (i < 0 || i >= length()) { throw IndexError( "Array source index " + toString(i) + " out of range for relocate (array length is " + toString(length()) + ")."); } if (j < 0 || j > length()) { throw IndexError( "Array destination index " + toString(i) + " out of range for relocate (array length is " + toString(length()) + ")."); } } // Wraps the given integer to the [0, length()-1] range. // Precondition: length() > 0. // In a nutshell, this is "i % n", but with a correction // that handles negative input without introducing an "if". Int wrap_(Int i) const { Int n = length(); return (n + (i % n)) % n; // Examples: // n = 10, i = 11: (10 + (11%10)) % 10 = (10 + 1) % 10 = 1 // n = 10, i = -11: (10 + (-11%10)) % 10 = (10 + -1) % 10 = 9 // We could also do (i % n) + (i < 0 ? n : 0), but the above // avoids the conditional and is more robust to pre-C++11 // implementations (the behavior for negative inputs wasn't // clearly specified, and varied across implementations). } }; /// Returns whether the arrays `a1` and `a2` are equal, that is, whether they /// have the same number of elements and `a1[i] == a2[i]` for all elements. /// template<typename T> bool operator==(const Array<T>& a1, const Array<T>& a2) { return a1.length() == a2.length() && std::equal(a1.begin(), a1.end(), a2.begin()); } /// Returns whether the arrays `a1` and `a2` are different, that is, whether /// they have a different number of elements or `a1[i] != a2[i]` for some /// elements. /// template<typename T> bool operator!=(const Array<T>& a1, const Array<T>& a2) { return !(a1 == a2); } /// Compares the two arrays `a1` and `a2` in lexicographic order. /// template<typename T> bool operator<(const Array<T>& a1, const Array<T>& a2) { return std::lexicographical_compare(a1.begin(), a1.end(), a2.begin(), a2.end()); } /// Compares the two arrays `a1` and `a2` in lexicographic order. /// template<typename T> bool operator<=(const Array<T>& a1, const Array<T>& a2) { return !(a2 < a1); } /// Compares the two arrays `a1` and `a2` in inverse lexicographic order. /// template<typename T> bool operator>(const Array<T>& a1, const Array<T>& a2) { return a2 < a1; } /// Compares the two arrays `a1` and `a2` in inverse lexicographic order. /// template<typename T> bool operator>=(const Array<T>& a1, const Array<T>& a2) { return !(a1 < a2); } /// Exchanges the content of `a1` with the content of `a2`. /// template<typename T> void swap(Array<T>& a1, Array<T>& a2) { a1.swap(a2); } /// Writes the given `Array<T>` to the output stream. /// template<typename OStream, typename T> void write(OStream& out, const Array<T>& a) { if (a.isEmpty()) { write(out, "[]"); } else { write(out, '['); auto it = a.cbegin(); auto last = a.cend() - 1; if constexpr (std::is_pointer_v<T>) { // TODO: avoid copy using fmt::ptr; fmt::memory_buffer b; core::formatTo(std::back_inserter(b), "{}", ptr(*it)); while (it != last) { core::formatTo(std::back_inserter(b), ", {}", ptr(*it)); ++it; } std::string_view strv(b.begin(), static_cast<std::streamsize>(b.size())); write(out, strv); } else { write(out, *it); while (it != last) { write(out, ", ", *++it); } } write(out, ']'); } } /// Reads the given `Array<T>` from the input stream, and stores it in the given /// output parameter `a`. Leading whitespaces are allowed. /// /// Throws `ParseError` if the stream does not start with an `Array<T>`. /// Throws `RangeError` if one of the values in the array is outside of the /// representable range of its type. /// template<typename IStream, typename T> void readTo(Array<T>& a, IStream& in) { a.clear(); skipWhitespaceCharacters(in); skipExpectedCharacter(in, '['); skipWhitespaceCharacters(in); char c = readCharacter(in); if (c != ']') { in.unget(); c = ','; while (c == ',') { skipWhitespaceCharacters(in); a.append(read<T>(in)); skipWhitespaceCharacters(in); c = readExpectedCharacter(in, {',', ']'}); } } } namespace detail { template<typename T> struct IsArray : std::false_type {}; template<typename T> struct IsArray<Array<T>> : std::true_type {}; } // namespace detail /// Checks whether the type `T` is a specialization of core::Array. /// template<typename T> inline constexpr bool isArray = detail::IsArray<T>::value; /// Alias template for `vgc::core::SharedConst<vgc::core::Array<T>>`. /// template<typename T> using SharedConstArray = SharedConst<Array<T>>; /// Alias for `vgc::core::Array<vgc::Int>`. /// using IntArray = Array<Int>; /// Alias for `vgc::core::SharedConstArray<vgc::Int>`. /// using SharedConstIntArray = SharedConstArray<Int>; /// Alias for `vgc::core::Array<float>`. /// using FloatArray = Array<float>; /// Alias for `vgc::core::SharedConstArray<float>`. /// using SharedConstFloatArray = SharedConstArray<float>; /// Alias for `vgc::core::Array<double>`. /// using DoubleArray = Array<double>; /// Alias for `vgc::core::SharedConstArray<double>`. /// using SharedConstDoubleArray = SharedConstArray<double>; } // namespace vgc::core // # C++ concept requirements // // For reference, below are some C++ concept requirements (or rather, "named // requirements", as they don't use the `concept` syntax introduced in C++20), // as per the C++20 draft generated on 2020-01-15. These requirements are // important to know what in std::vector must be kept in order for functions in // <algorithm> to work with vgc::core::Array, and which can be skipped. For // more details and up-to-date info: // // https://eel.is/c++draft/containers // // ## Notations // // X: container class containing objects of type T // u: identifier // a, b: values of type X // r: non-const value of type X // rv: non-const rvalue of type X // n: value of size_type // t: lvalue or const rvalue of type T // trv: non-const rvalue of type T // [i, j): valid range of input iterators convertible to T // il: initializer list // args: parameter pack // p: valid const_iterator in a // q: valid dereferenceable const_iterator in a // [q1, q2): valid range of const_iterators in a // // ## Container requirements // // https://eel.is/c++draft/containers#tab:container.req // // X::value_type T // X::reference T& // X::const_reference const T& // X::iterator satisfy ForwardIterator, convertible to const_iterator // X::const_iterator satisfy ConstForwardIterator // X::difference_type signed integer (= X::iterator::difference_type) // X::size_type unsigned integer that can represent any non-negative value of difference_type // X u, X(), X(a), X u(a), X u = a, X u(rv), X u = rv, a = rv, a.~X(), r = a // a.begin(), a.end(), a.cbegin(), a.cend() // a == b, a != b // a.swap(b), swap(a, b) // a.size(), a.max_size() -> size_type // a.empty() // // Optional: // a <=> b (if implemented, must be lexicographical) // // ## ReversibleContainer requirements // // https://eel.is/c++draft/containers#tab:container.rev.req // // X::reverse_iterator reverse_iterator<iterator> // X::const_reverse_iterator reverse_iterator<const_iterator> // a.rbegin(), a.rend(), a.rcbegin(), a.rcend() // // ## SequenceContainer requirements // // https://eel.is/c++draft/containers#tab:container.seq.req // // X(n, t), X u(n, t), X(i, j), X u(i, j), X(il), a = il // a.emplace(p, args) // a.insert(p, t)/(p, trv)/(p, n, t)/(p, i, j)/(p, il) // a.erase(q)/(q1, q2) // a.clear() // a.assign(i, j)/(il)/(n, t) // // Optional: // a.front(), a.back(), // a.emplace_front(args), a.emplace_back(args), // a.push_front(t)/(trv), a.push_back(t)/(trv), // a.pop_front(), a.pop_back(), // a[n], a.at(n) // // ## std::vector // // std::vector implements all of the optional SequenceContainer // requirements (except push/emplace_front), also satisfies // AllocatorAwareContainer, and defines the following functions which // aren't part of any concept requirements: // // X(n), X u(n) + allocator variants // capacity(), resize(n), reserve(n), shrink_to_fit() // data() // // todo: Implement more specific format specification to support aligning // the array vs aligning the element, etc... // Possible syntax: {:array-spec[element-spec]} // Example: {:>50[>6]} would align-fill the array to be of width 50 and each element // to be of width 6. // template<typename T> struct fmt::formatter<vgc::core::Array<T>> : fmt::formatter<vgc::core::RemoveCVRef<T>> { template<typename FormatContext> auto format(const vgc::core::Array<T>& x, FormatContext& ctx) -> decltype(ctx.out()) { using ElementFormatter = fmt::formatter<vgc::core::RemoveCVRef<T>>; auto out = ctx.out(); if (x.isEmpty()) { out = vgc::core::copyStringTo(out, "[]"); } else { *out++ = '['; auto it = x.cbegin(); auto last = x.cend() - 1; out = ElementFormatter::format(*it, ctx); while (it != last) { out = vgc::core::copyStringTo(out, ", "); ctx.advance_to(out); out = ElementFormatter::format(*++it, ctx); } *out++ = ']'; } ctx.advance_to(out); return out; } }; #endif // VGC_CORE_ARRAY_H
true
069971591caa74926ee027dfa63ef07ff695a834
C++
fuad7161/Basic-Algorithm-
/Segment tree/Update_array_segment_tree.cpp
UTF-8
1,535
2.609375
3
[]
no_license
//Author: Fuadul Hasan(fuadul202@gmail.com) #include<bits/stdc++.h> using namespace std; #define int long long #define pb push_back #define vi vector<int> #define all(n) n.begin(),n.end() const int Inf = (int)2e9 + 5; #define vout(v) for (auto z: v) cout << z << " "; cout << endl; const int N = 4e5 + 5; int st[N]; int ar[N]; void buildTree(int si,int ss,int se){ if(ss == se){ st[si] = ar[ss]; return; } int mid = (ss+se)/2; buildTree(2*si,ss,mid); buildTree(2*si+1,mid+1,se); st[si] = (st[2*si]+st[2*si+1]); } int query(int si,int ss,int se,int qs,int qe){ if(se < qs or qe < ss) return 0;; if(ss >= qs and se <= qe) return st[si]; int mid = (ss+se)/2; int l = query(2*si, ss,mid,qs,qe); int r = query(2*si+1,mid+1,se,qs,qe); return (l+r); } void update(int si,int ss,int se,int qi){ if(ss == se){ st[si] = ar[ss]; return ; } int mid = (ss+se)/2; if(qi <= mid){ update(2*si,ss,mid,qi); }else{ update(2*si+1,mid+1,se,qi); } st[si] = (st[2*si]+st[2*si+1]); } bool isPrime(int x){ if(x < 2)return false; for(int i=2;i*i<=x;i++){ if(x%i == 0)return false; }return true; } signed main(){ int n; cin>>n; int x; for(int i =1;i<=n;i++){ cin>>x; if(isPrime(x)){ ar[i] = 1; }else{ ar[i] = 0; } } buildTree(1,1,n); int q; cin>>q; while(q--){ int x; cin>>x; if(x == 1){ int l,r; cin>>l>>r; cout<<query(1,1,n,l,r)<<endl; }else{ int z,k;cin>>z>>k; if(isPrime(k)){ ar[z] = 1; }else{ ar[z] = 0; } update(1,1,n,z); } } return 0; }
true
41b7702eb4eb7d4a99f47a875bb4671fab5b5bcf
C++
Oelderoth/LightWeaver-Module
/lib/lightweaver-core/LightWeaver/util/StringListBuilder.h
UTF-8
1,005
3.078125
3
[]
no_license
#pragma once #include <Arduino.h> namespace LightWeaver { struct StringListBuilder { private: const String separator; public: String value; StringListBuilder(const String& separator) : separator(separator), value("") {} StringListBuilder(const String& separator, const String& value) : separator(separator), value(value) {}; bool empty() { return value.length() == 0; } friend const StringListBuilder operator+(const StringListBuilder& lhs, const String& rhs) { return StringListBuilder(lhs.separator, lhs.value.length() ? lhs.value + lhs.separator + rhs : rhs); } const StringListBuilder& operator+=(const String& rhs) { value = value.length() ? value + separator + rhs : rhs; return *this; } operator String() const{ return value; } const char* c_str() const { return value.c_str(); } }; }
true
1f4f6b63ec7610baf9c4e08f141d92b0574b5c6d
C++
dvdouden/planetgenerator
/geom/PlanetGeometry.h
UTF-8
2,418
2.53125
3
[]
no_license
#pragma once #include "DrawElementsGeometry.h" #include "../Planet.h" class Planet; class PlanetGeometry : public DrawElementsGeometry { public: explicit PlanetGeometry( Planet& sphere ) : DrawElementsGeometry( "Planet", vl::PT_TRIANGLE_FAN ), m_planet( sphere ) {} void createGeometry() override; void updateGeometry() override; void updateColors() override; void setColorMode( int colorMode ) { m_colorMode = colorMode; m_highlightDirty = false; markColorsDirty(); } void setHighlight( std::size_t highlight ) { if ( highlight == m_highlight ) { return; } m_oldHighlight = m_highlight; m_highlight = highlight; markColorsDirty(); m_highlightDirty = true; } void enablePicking( bool enabled ) { m_picking = enabled; } std::size_t getSize() const override { return DrawElementsGeometry::getSize() - m_planet.cells.size(); } private: typedef vl::fvec4 (PlanetGeometry::*colFunc)( const Planet::cell& ); vl::fvec4 colFuncCellPosition( const Planet::cell& cell ); vl::fvec4 colFunc2( const Planet::cell& cell ); vl::fvec4 colFunc3( const Planet::cell& cell ); vl::fvec4 colFunc4( const Planet::cell& cell ); vl::fvec4 colFunc5( const Planet::cell& cell ); vl::fvec4 colFuncCellIlluminated( const Planet::cell& cell ); vl::fvec4 colFuncCellAnnualIllumination( const Planet::cell& cell ); vl::fvec4 colFuncCellTemperature( const Planet::cell& cell ); vl::fvec4 colFuncCellForce( const Planet::cell& cell ); vl::fvec4 colFuncPlatePosition( const Planet::cell& cell ); vl::fvec4 colFuncPlateTypeColor( const Planet::cell& cell ); vl::fvec4 colFuncDefault( const Planet::cell& cell ); vl::fvec4 colFuncCellMotion( const Planet::cell& cell ); Planet& m_planet; int m_colorMode = 0; size_t m_highlight = -1; size_t m_oldHighlight = -1; bool m_highlightDirty = false; bool m_picking = true; std::vector<size_t> m_offsets; static float distCol( float dist ); void colorCell( const Planet::cell& cell, vl::fvec4 rgb, vl::fvec4*& cols ); vl::fvec4 colFuncCellDivergentForce( const Planet::cell& cell ); vl::fvec4 colFuncCellConvergentForce( const Planet::cell& cell ); vl::fvec4 colFuncCellElevation( const Planet::cell& cell ); };
true
9c3ecc5a1e55673c0f9afa6ab32a42250409d6d0
C++
nosyliam/CPPCourse
/zuul/room.h
UTF-8
1,883
3.390625
3
[]
no_license
#pragma once #include <vector> #include <string> #include <map> #include <functional> // Preprocessors for medatadata definition #define ROOM_START(ID, NAME, STATE) Room* ROOM##ID = new Room(NAME, STATE) #define NEIGHBOR(ID, DIR, OTHER) ROOM##ID->SetNeighbor(Direction::DIR, ROOM##OTHER) #define ITEM(ID, NAME, CALLBACK) ROOM##ID->AddItem(new Item(NAME, CALLBACK)) #define ROOM_END(ID) game.AddRoom(ROOM##ID) #define ROOM_SET(ID) game.current_room = ROOM##ID class GameState; // Items are simples structures that use a callback to make modifications to the // gamestate when used. The callback is expected to sanity check itself upon // reaching different checkpoints. struct Item { std::string name; const std::function<void(GameState*)>& callback; Item(std::string name, const std::function<void(GameState*)>& callback) : name(name), callback(callback) {}; }; enum class Direction { NORTH, EAST, SOUTH, WEST }; class Room { public: Room(std::string name, std::string state) : name(name), state(state) {}; ~Room() {}; // Metadata utility functions Room* At(Direction dir) { return neighbors.at(dir); }; void SetNeighbor(Direction dir, Room* room) { neighbors[dir] = room; }; void AddItem(Item* item) { items.push_back(item); }; void SetState(std::string state) { state = state; } Item* FindItem(std::string name) { std::vector<Item*>::iterator it = std::find_if(items.begin(), items.end(), [name](const Item* o) { return o->name == name; }); return (it == items.end()) ? nullptr : *it; }; std::string name; std::map<Direction, Room*> neighbors; std::vector<Item*> items; // When an item is used, it is free to modify the gamestate to // change a current room's state. This state is displayed when // the user requests their current surroundings. std::string state; };
true
a784b88abeca85760c2e55cdd96f9fb85d94c943
C++
CaptFrank/GHID
/BLUNO_Project/BLUNO_BASE_STATION/Receiver_Callback/Src/aaMain/USBDeviceImplementation.cpp
UTF-8
1,678
2.796875
3
[]
no_license
/* * USB_Device_Implementation.cpp * * Created on: Jul 17, 2013 * Author: francispapineau */ #include "USBDeviceImplementation.h" //! Default Constructor USBDevice::USBDevice(void* report){ //! Initializing the environment variables #ifdef JOYSTICK_REPORT this->_report = (joystick_report_t*)report; #endif #ifdef MOUSE_REPORT this->_report = (mouse_report_t*)report; #endif } //! Sends a USB report frame void USBDevice::_send_usb_report_frame(void* report){ #ifdef MOUSE_REPORT //! Send the structure. USB_COMMS.write((uint8_t*)&this->_report, sizeof(mouse_report_t)); #endif #ifdef JOYSTICK_REPORT //! Send the structure. USB_COMMS.write((uint8_t*)this->_report, sizeof(joystick_report_t)); #endif } /** * Sets up the USB device report */ #ifdef DYNAMIC_JOYSTICK_CONFIG bool USBDevice::_setup_usb_device(){ uint8_t config[] = {CONFIG_HEADER, NUM_AXES, NUM_BUTTONS, CONFIG_TAIL}; //! Send configs USB_COMMS.write((uint8_t*)config, sizeof(config)); //! Loop to configs uint8_t timeout = USB_TIMEOUT; while(timeout --){ if(USB_COMMS.available()){ uint8_t response = USB_COMMS.read(); if (response == CONFIGURED){ return true; } } } return false; } #endif /** * Start the USB engine Serial */ bool USBDevice::begin(){ USB_COMMS.begin(USB_BAUD); //! Setup the usb report #ifdef DYNAMIC_JOYSTICK_CONFIG return this->_setup_usb_device(); #endif return true; } // Run the usb live void USBDevice::run_usb(){ /** * Once the state machine gets here, it polls for data from the router * and parses it into the structures. */ //! Send the valid report. _send_usb_report_frame(_report); }
true
b1c9162b5e84fd7d8b922bdf3a8c7d40c1abce7c
C++
jonknoll/TaskScheduler
/example/arduino_sched_example.ino
UTF-8
2,140
3.125
3
[ "MIT" ]
permissive
/***************************************************************************//** Example program using the task_scheduler library. This example was targeted for the Arduino UNO or NANO. It simultaneously blinks the onboard LED and prints to the serial monitor, both at different rates. It is a simple demonstration of how you can split your code into separate tasks and control them independently with very little overhead. *******************************************************************************/ #include <Arduino.h> #include "TaskScheduler.h" // Task setup enum { LED_BLINK_TASK = 0, HELLO_WORLD_TASK }; static void ledBlinkTask(void); static void helloWorldTask(void); TaskBlock taskBlock[] = { {&ledBlinkTask, TASK_PEND, 5000}, // LED_BLINK_TASK (start after 5 seconds) {&helloWorldTask, TASK_RUN, 0} // HELLO_WORLD_TASK (start now) }; #define TASK_BLOCK_SIZE (sizeof(taskBlock)/sizeof(TaskBlock)) // create a task scheduler TaskScheduler TS; ////////////////// // LED BLINK TASK ////////////////// const int ledPin = 13; boolean ledState = LOW; static void ledBlinkInit(void) { // initialize digital pin 13 (LED) as an output. pinMode(ledPin, OUTPUT); } static void ledBlinkTask(void) { if(ledState == LOW) { digitalWrite(ledPin, HIGH); ledState = HIGH; TS.sleep(LED_BLINK_TASK, 100); } else { digitalWrite(ledPin, LOW); ledState = LOW; TS.sleep(LED_BLINK_TASK, 700); } } //////////////////// // HELLO WORLD TASK //////////////////// uint8_t count = 0; static void helloWorldInit(void) { // initialize serial communication: Serial.begin(9600); } static void helloWorldTask(void) { Serial.print("Hello World! "); Serial.println(count++); TS.sleep(HELLO_WORLD_TASK, 500); } //The setup function is called once at startup of the sketch void setup() { ledBlinkInit(); helloWorldInit(); TS.initialize(&taskBlock[0], TASK_BLOCK_SIZE); } // The loop function is called in an endless loop void loop() { TS.run(); }
true
44e24b0ac61d60aa1b01336143aa1fb65a859e1d
C++
iseki-masaya/ChallengeBook
/Chapter2/2-5/01BipartiteGraph.cpp
UTF-8
813
2.96875
3
[]
no_license
#include <iostream> #include <vector> #include <map> #include <string> #include <bitset> #include <queue> #include <algorithm> #include <functional> #include <cstdio> using namespace std; #define MAX_V 50 vector<vector<int> > G; vector<int> color(MAX_V,0); bool dfs(int v,int c) { color[v] = c; for (int i=0; i<G[v].size(); ++i) { if (color[G[v][i]] == c) return false; if (color[G[v][i]] == 0 && !dfs(G[v][i], -c)) return false; } return true; } string solve() { size_t V = G.size(); for (int i=0; i<V; ++i) { if (color[i] == 0) { if (!dfs(i,1)) { return "NO"; } } } return "YES"; } int main() { G = vector<vector<int> >{{1,2},{0,2},{0,1}}; cout << solve() << endl; color = vector<int>(MAX_V,0); G = vector<vector<int> >{{1,3},{0,2},{1,3},{0,2}}; cout << solve() << endl; }
true
6ac8f45a79d4407e7f3359afdf9e5af449a9d7c7
C++
Lrs121/winds
/arm9/include/_dialog/dialog.folder.choose.h
UTF-8
1,243
2.578125
3
[ "MIT" ]
permissive
#ifndef _WIN_D_FOLDERCHOOSE_ #define _WIN_D_FOLDERCHOOSE_ #include <_type/type.dialog.h> #include <_gadget/gadget.button.h> #include <_gadget/gadget.label.h> #include <_gadget/gadget.window.dialog.h> #include <_gadget/gadget.filetree.h> class _folderChooseDialog : public _dialog { private: _button* okButton; _button* cancelButton; _label* descriptionLabel; _dialogWindow* window; _fileTree* fileTree; // Path to currently selected folder string folderPath; _callbackReturn eventHandler( _event ); void executeInternal(); void cleanupInternal(); public: //! Ctor //! @note if 'ignore'/nothing is passed as argument, the appropriate localized string is inserted instead _folderChooseDialog( _optValue<wstring> descriptionLabel = ignore , _optValue<wstring> okLabel = ignore , _optValue<wstring> windowLabel = ignore ); //! Get Selected filename string getPath() const { return this->folderPath; } //! Dtor ~_folderChooseDialog(){ delete this->okButton; delete this->cancelButton; delete this->window; delete this->fileTree; if( this->descriptionLabel ) delete this->descriptionLabel; } }; #endif
true
e17f7663b33ac321508ffad3ac9a92c3949db646
C++
ygorshenin/trees
/src/typelist/typelist.h
UTF-8
568
2.703125
3
[]
no_license
#ifndef TYPELIST_TYPELIST_H_ #define TYPELIST_TYPELIST_H_ #include <cstddef> namespace typelist { struct NullType { }; // struct NullType template<class T, class U> struct TypeList { typedef T Head; typedef U Tail; }; // struct TypeList template<class> struct Length; template<> struct Length<NullType> { static const size_t kLength = 0; }; // struct Length template<class T, class U> struct Length< TypeList<T, U> > { static const size_t kLength = 1 + Length<U>::kLength; }; // struct Length } // namespace typelist #endif // TYPELIST_TYPELIST_H_
true
4f86ac35848b8e9851c1dcade56a218c4ca80f45
C++
Golden-Eagle/gecom
/src/gecom/Terminal.hpp
UTF-8
2,322
2.84375
3
[]
no_license
/* * GECOM Terminal Utilities Header * * Allows use of ANSI terminal escape sequences to manipulate color in * a portable manner. Redirects stdio to a thread and then forwards or * interprets escape sequences if connected to a terminal, suppressing * them otherwise. If no redirection mechanism is available, the iostream * manipulators in this header do nothing. * * Including this header ensures that terminal stdio redirection is correctly * initialized before any code that comes after the inclusion. * * TODO * - POSIX stdio redirection */ #ifndef GECOM_TERMINAL_HPP #define GECOM_TERMINAL_HPP #include <cstdio> #include <iostream> namespace gecom { class TerminalInit { private: static size_t refcount; public: TerminalInit(); ~TerminalInit(); }; namespace terminal { // reset all attributes std::ostream & reset(std::ostream &); // reset, then apply regular foreground colors std::ostream & black(std::ostream &); std::ostream & red(std::ostream &); std::ostream & green(std::ostream &); std::ostream & yellow(std::ostream &); std::ostream & blue(std::ostream &); std::ostream & magenta(std::ostream &); std::ostream & cyan(std::ostream &); std::ostream & white(std::ostream &); // reset, then apply bold foreground colors std::ostream & boldBlack(std::ostream &); std::ostream & boldRed(std::ostream &); std::ostream & boldGreen(std::ostream &); std::ostream & boldYellow(std::ostream &); std::ostream & boldBlue(std::ostream &); std::ostream & boldMagenta(std::ostream &); std::ostream & boldCyan(std::ostream &); std::ostream & boldWhite(std::ostream &); // apply regular background colors without reset std::ostream & onBlack(std::ostream &); std::ostream & onRed(std::ostream &); std::ostream & onGreen(std::ostream &); std::ostream & onYellow(std::ostream &); std::ostream & onBlue(std::ostream &); std::ostream & onMagenta(std::ostream &); std::ostream & onCyan(std::ostream &); std::ostream & onWhite(std::ostream &); // width in characters of the terminal behind a FILE pointer // if no terminal, returns INT_MAX int width(FILE *); } } namespace { gecom::TerminalInit terminal_init_obj; } #endif // GECOM_TERMINAL_HPP
true
823be23142b8b1bca859174e70be8a3fb80449af
C++
davisking/dlib
/dlib/matrix/symmetric_matrix_cache_abstract.h
UTF-8
3,154
2.828125
3
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// Copyright (C) 2010 Davis E. King (davis@dlib.net) // License: Boost Software License See LICENSE.txt for the full license. #define DLIB_SYMMETRIC_MATRIX_CAcHE_ABSTRACT_Hh_ #ifndef DLIB_SYMMETRIC_MATRIX_CAcHE_ABSTRACT_Hh_ #include "matrix_abstract.h" namespace dlib { // ---------------------------------------------------------------------------------------- template < typename cache_element_type > const matrix_exp symmetric_matrix_cache ( const matrix_exp& m, long max_size_megabytes ); /*! requires - m.size() > 0 - m.nr() == m.nc() - max_size_megabytes >= 0 ensures - This function assumes that m is symmetric. If m is not symmetric then it won't crash but you will get incorrect results. - This method creates a matrix expression which internally caches the elements of m so that they can be accessed quickly. It is useful if m is some kind of complex matrix expression which is both very large and expensive to evaluate. An example would be a kernel_matrix() expression with an expensive kernel and a large number of samples. Such an expression would result in a huge matrix, potentially too big to store in memory. The symmetric_matrix_cache() then makes it easy to store just the parts of a matrix expression which are accessed most often in memory. The specific details are defined below. - returns a matrix M such that - M == m (i.e. M represents the same matrix as m) - M will cache elements of m and hold them internally so they can be quickly accessed. In particular, M will attempt to allocate no more than max_size_megabytes megabytes of memory for the purposes of caching elements of m. When an element of the matrix is accessed it is either retrieved from the cache, or if this is not possible, then an entire column of m is loaded into a part of the cache which hasn't been used recently and the needed element returned. - diag(m) is always loaded into the cache and is stored separately from the cached columns. That means accesses to the diagonal elements of m are always fast. - M will store the cached elements of m as cache_element_type objects. Typically, cache_element_type will be float or double. - To avoid repeated cache lookups, the following operations are optimized for use with the symmetric_matrix_cache(): - diag(M), rowm(M,row_idx), colm(M,col_idx) These methods will perform only one cache lookup operation for an entire row/column/diagonal worth of data. !*/ // ---------------------------------------------------------------------------------------- } #endif // DLIB_SYMMETRIC_MATRIX_CAcHE_ABSTRACT_Hh_
true
28fa83c705bb3ef9d982fc90a29066810ef93c56
C++
pikec/portfolio
/CS162_final/Room.cpp
UTF-8
4,816
3.65625
4
[]
no_license
/*************************************************** * * filename: Room.cpp * * author: Candis Pike * * description: class implemneation file Room class * * input: none * * output: specified by funtion * *************************************************/ #include "Room.hpp" #include <string> #include <cstdlib> #include <cctype> #include <iostream> /******************************************************************** * * function: Room::Room () ** * * description: default constructor ** * * parameters: none ** * * pre-conditions: class object is created ** * * post-conditions: class object created with default conditions ** * *****************************************************************/ Room::Room () { this -> location = " " ; this -> moveOn = false; } /******************************************************************** * * function: Room::Room (std::string loc) ** * * description: initializer constructor ** * * parameters: none ** * * pre-conditions: class object is created ** * * post-conditions: class object created with initial conditions ** * *****************************************************************/ Room::Room(std::string loc) { this -> location = loc; } /******************************************************************** * * function: Room::~Room () ** * * description: default constructor ** * * parameters: none ** * * pre-conditions: class object is created ** * * post-conditions: class object destroyed ** * *****************************************************************/ Room::~Room() { /*intentionally blank*/ } /******************************************************************** * * function: std::string Room::getLocation () ** * * description: return room name ** * * parameters: none ** * * pre-conditions: class object is created ** * * post-conditions: name of room reutrned ** * *****************************************************************/ std::string Room::getLocation() { return location; } /******************************************************************** * * function: void Room::setCompass () ** * * description: set the values of the compass struct ** * * parameters: Room *n, Room *s, Room *e, Room *w ** * * pre-conditions: class object is created valid pointers passed ** * * to struct ** * * post-conditions: struct has inital pointers for room direction** * *****************************************************************/ void Room::setCompass (Room *n, Room *s, Room *e , Room *w) { current.north = n; current.south = s; current.east = e; current.west = w; } /******************************************************************** * * function: Compass Room:getCompass () ** * * description: return a rooms compass ** * * parameters: none ** * * pre-conditions: class object is created ** * * post-conditions: sruct of room compass returned ** * *****************************************************************/ /*Compass Room:: getCompass () { return current; }*/ /******************************************************************** * * function: void Room::navigate (Player *p) ** * * description: player navigation in a room ** * * parameters: player *p ** * * pre-conditions: class object is created ** * * post-conditions: player navigates through room ** * *****************************************************************/ void Room::navigate(Player *p) { char direction; do { std::cout << std::endl; std::cout << "Which direction do you want to move? N/S/E/W " ; std::cin >> direction; std::cout << std::endl; if (toupper(direction) == 'N') moveN(p); else if (toupper(direction) == 'S') moveS(p); else if (toupper(direction) == 'E') moveE(p); else if (toupper(direction) == 'W') moveW(p); else std::cout << "Invalid direction. Try again." << std::endl; } while (!moveOn); }
true
3a759bb87787a9f2a77411c99b6dc0a71f27f8ef
C++
ashishnagpal2498/CPP_Concepts_and_Codes
/HackerEarth/Epoch- Competition/colouring_grid2x2.cpp
UTF-8
1,663
3.546875
4
[]
no_license
//Colouring the Grid #include<iostream> using namespace std; bool Cancolor(char grid[][100],int i,int j,int n,int m) { if(i+1==n||j+1==m) { return false; } for(int a=i;a<2;a++) { for(int b=j;b<2;b++) { if(grid[a][b]=='#') { return false; } else { grid[a][b]='T'; } } } return true; } bool grid_color(char grid[][100],int i,int j,int n,int m) { //Base Case if(i==n||i+1==n) { //checking if whole grid is colored or not for(int i=0;i<n;i++) { cout<<endl; for(int j=0;j<m;j++) { cout<<grid[i][j]; if(grid[i][j]=='T') { } else if(grid[i][j]=='#') { } else { cout<<"no"; } } } cout<<"YES"; return false; } if(j==m||j+1==m) { i++; j=0; return grid_color(grid,i,j,n,m); } //Recursive case; if(grid[i][j]!='#') { if(Cancolor(grid,i,j,n,m)) {bool chhotagrid = grid_color(grid,i,j+1,n,m); if(chhotagrid) { return true; } } return grid_color(grid,i,j+1,n,m); } return false; // else{ // grid_color(grid,i,j+1,n,m); // } } int main() { int N,M; cin>>N>>M; char grid[100][100]; for(int i=0;i<N;i++) { for(int j=0;j<M;j++) cin>>grid[i][j]; } grid_color(grid,0,0,N,M); return 0; }
true
c7b6518a5dece6a1f8a3c686f8c454f3763723c0
C++
Syhawk/LeetCode
/maximum_product_subarray.cpp
UTF-8
1,750
3.0625
3
[]
no_license
//uri: https://leetcode.com/problems/maximum-product-subarray/ /* * 对于0需要特判,对于负数,每次取偶数个负数。 * 空间复杂度:O(1). * 时间复杂度:O(n). * */ class Solution { public: int maxProduct(vector<int>& nums) { int len = nums.size(); if(len < 1) return 0; long long result = nums[0]; long long tmp = 1; int cnt = 0; int pre = 0; int p = 0; for(int i = 0; i < len; ++ i) { if(nums[i]) { tmp *= nums[i]; if(nums[i] < 0) cnt += 1; p += 1; } if(i == len - 1 || nums[i] == 0) { if(nums[i] == 0) result = max(result, 0LL); if(p) result = max(result, tmp); if(cnt % 2 == 1) { long long c = tmp; for(int j = i; j > pre; -- j) { if(nums[j] == 0) continue; c /= nums[j]; if(nums[j] < 0) { result = max(result, c); break; } } for(int j = pre; j < i; ++ j) { -- p; if(nums[j] == 0) continue; tmp /= nums[j]; if(nums[j] < 0) { if(p) result = max(result, tmp); break; } } } pre = i + 1; cnt = 0; tmp = 1; p = 0; } } return result; } };
true
55689f12fcd777a0d403148cec43c50404966010
C++
Mikalai/punk_project_a
/source/entities/ibag.cpp
UTF-8
3,004
2.53125
3
[]
no_license
#include <attributes/transform/module.h> #include <system/logger/module.h> #include "ibag.h" #include "icollection_impl.h" #include "ishape.h" PUNK_ENGINE_BEGIN namespace Entities { class Bag : public IBag, public ICollection, public Core::ISerializable, public IShape { public: // IObject void QueryInterface(const Core::Guid& type, void** object) override { if (!object) return; *object = nullptr; if (type == Core::IID_IObject) { *object = (IBag*)this; AddRef(); } if (type == IID_IBag) { *object = this; AddRef(); } if (type == IID_ICollection) { *object = this; AddRef(); } if (type == Core::IID_ISerializable) { *object = (Core::ISerializable*)this; AddRef(); } } std::uint32_t AddRef() override { return m_ref_count.fetch_add(1); } std::uint32_t Release() override { auto v = m_ref_count.fetch_sub(1) - 1; if (!v) { delete this; } return v; } // IBag void SetMaxVolume(double value) override { m_max_volume = value; } double GetMaxVolume() const override { return m_max_volume; } bool CanAddItem(IShape* item) const override { auto v = item->GetVolume(); return v <= m_free_volume; } double GetFreeVolume() const override { return m_free_volume; } // ICollection void Add(Core::Pointer<Core::IObject> value) override { Core::Pointer<IShape> shape = value; if (!shape.get()) { System::GetDefaultLogger()->Error("Can't add object to the bag because it is not a shape"); return; } m_collection.Add(shape); } void Remove(Core::Pointer<Core::IObject> value) override { m_collection.Remove(value); } std::uint32_t Size() const override { return m_collection.Size(); } const Core::Pointer<Core::IObject> GetItem(std::uint32_t index) const override { return m_collection.GetItem(index); } Core::Pointer<Core::IObject> GetItem(std::uint32_t index) override { return m_collection.GetItem(index); } // IShape void SetMass(double value) override { m_mass = value; } double GetMass() const override { return m_mass; } void SetVolume(double value) override { m_volume = value; } double GetVolume() const override { return m_volume; } // ISerializable void Serialize(Core::Buffer& buffer) override { buffer.WritePod(CLSID_Bag); buffer.WritePod(m_max_volume); buffer.WritePod(m_free_volume); buffer.WritePod(m_mass); buffer.WritePod(m_volume); m_collection.Serialize(buffer); } void Deserialize(Core::Buffer& buffer) override { buffer.ReadPod(m_max_volume); buffer.ReadPod(m_free_volume); buffer.ReadPod(m_mass); buffer.ReadPod(m_volume); m_collection.Deserialize(buffer); } private: std::atomic<std::uint32_t> m_ref_count{ 0 }; // IBag double m_max_volume{ 10 }; double m_free_volume{ 10 }; double m_mass{ 0.5 }; double m_volume{ 1 }; // ICollection Collection<IShape> m_collection; }; } PUNK_ENGINE_END
true
09ee80466b4f20554b254268fe267cf46cc8e41c
C++
parasrawat007/C-Plus-Plus
/14_LimitsOfType.Cpp
UTF-8
230
2.859375
3
[]
no_license
#include<iostream> #include<limits> using namespace std; int main() { numeric_limits<int> n; cout<<"Min = "<<n.min()<<endl <<"Max = "<<n.max()<<endl <<"Digits = "<<n.digits<<endl; return 0; }
true
b0831684b4637110311b147ced6f0d4eca1a6ecf
C++
lirui311012/C_study
/C++高级/C++11/05_function函数对象的实现原理.cpp
UTF-8
2,314
3.953125
4
[]
no_license
#include <iostream> #include <algorithm> #include <functional> #include <string> #include <typeinfo> using namespace std; /* function函数对象的实现原理 C++11提供的可变参的类型参数A... */ void hello(string str) { cout << str << endl; } int sum(int a, int b) { return a + b; } template <typename Fty> class myfunction {}; /////////////////////////////////////////////////// /* //部分特例化 template <typename R,typename A1> class myfunction<R(A1)> { public: //typedef R(*PFUNC)(A1); using PFUNC = R(*)(A1); //和上面等价,函数指针类型 myfunction(PFUNC pfunc) :_pfunc(pfunc) {} //函数对象就是这个operator()重载 R operator()(A1 arg) { return _pfunc(arg); //hello(arg) } private: PFUNC _pfunc; }; //部分特例化版本 template<typename R,typename A1,typename A2> class myfunction<R(A1, A2)> { public: using PFUNC = R(*)(A1,A2); myfunction(PFUNC pfunc) :_pfunc(pfunc) {} //函数对象就是这个operator()重载 R operator()(A1 arg1,A2 arg2) { return _pfunc(arg1, arg2); } private: PFUNC _pfunc; }; */ /* 实现的还是不错的,那么问题来了,这个myfunction模板参数列表是函数类型 那么上面传了两个不同的参数,我们实现了两个不同myfuntion的部分特例化,那函数 类型好像是变化的,返回值还好说,那参数个数呢?3个?4个?5个?,难道提供n个特例化? 不现实,接下来解决这个问题,C++11提供的模板的语法非常强大 */ /////////////////////////////////////////////////// //如何解决上面的问题?屏蔽掉上面的代码,重新来 //typename... A代表可变参,A表示的不是一个类型,而是一组类型,个数任意 template<typename R, typename... A> class myfunction<R(A...)> //可变参数个数的函数类型的部分特例化 { public: using PFUNC = R(*)(A...); myfunction(PFUNC pfunc) :_pfunc(pfunc) {} R operator()(A... arg) //A...可变参类型 { return _pfunc(arg...); //传入一组形参变量 } private: PFUNC _pfunc; }; //这就是function底层实现原理 int main() { myfunction<void(string)> func1(hello); func1("hello world!");//func1.operator()("hello world!"); myfunction<int(int, int)> func2(sum); cout << func2(10, 20) << endl; return 0; } /* hello world! 30 */
true
a5a3baa41198a7ae28faf0d8dbd29937e9f2b507
C++
DuyetVu2001/Study-CPlusPlus-Language
/BaiTapTrenLop/B1TinhTongGTLNT.cpp
UTF-8
1,629
2.828125
3
[]
no_license
#include<iostream> #include<math.h> #define N 100 using namespace std; void input(int a[N][N], int n, int m); void output(int a[N][N], int n, int m); void ham_chan(int a[N][N], int n, int m); int find_sum(int a[N][N], int n, int m); int find_max(int a[N][N], int n, int m); int main(){ int a[N][N]; int n, m; cout << "Nhap vao lan luot gia tri so hang va so cot: " << endl; cin >> n >> m; cout << "Nhap ma tran: \n"; input(a, n, m); cout << "Ma tran vua nhap: \n"; output(a, n, m); cout << "In ra nhung hang chan: \n"; ham_chan(a, n, m); int sum = find_sum(a, n, m); int max = find_max(a, n, m); cout << "Tong gia tri pt tren cac ham chan: " << sum << endl; cout << "Gia tri lon nhat tren cot 1 cua ma tran: " << max << endl; return 0; } void input(int a[N][N], int n, int m){ for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ cout << "Nhap a[" << i << "][" << j << "]: "; cin >> a[i][j]; } } } void output(int a[N][N], int n, int m){ for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ cout << a[i][j]; cout << "\t"; } cout << endl; } } void ham_chan(int a[N][N], int n, int m){ for(int i = 0; i < n; i++){ if((i+1) % 2 == 0){ for(int j = 0; j < m; j++){ cout << a[i][j]; cout << "\t"; } } cout << endl; } } int find_sum(int a[N][N], int n, int m){ int sum = 0; for(int i = 0; i < n; i++){ if((i+1) % 2 == 0){ for(int j = 0; j < m; j++){ sum += a[i][j]; } } } return sum; } int find_max(int a[N][N], int n, int m){ int max = a[0][0]; for(int i = 1; i < n; i++){ if(max < a[i][0]) max = a[i][0]; } return max; }
true
612e0c26fac3ecb1c918c458b8f908b354f2f147
C++
SGrebenkin/HackerRank
/HackerRank.PrimitiveProlem.cpp
UTF-8
2,152
3.015625
3
[]
no_license
#include <bits/stdc++.h> #include <numeric> using namespace std; template <class F> void factors(long long int n, F f) { // Print the number of 2s that divide n while (n%2 == 0) { f(2); n = n/2; } for (int i = 3; i <= sqrt(n); i = i+2) { // While i divides n, print i and divide n while (n%i == 0) { f(i); n = n/i; } } if (n > 2) f(n); } long long int gcd(long long int a, long long int b) { return b == 0 ? a : gcd(b, a % b); } long long int pw(long long int a, long long int b) { long long res = a; for (int k = 1; k < b; ++k) res *= a; return res; } long long int pw(long long int a, long long int b, long long int p) { long long res = a; for (int k = 1; k < b; ++k) { res *= a; res = res % p; } return res; } int main() { long long int p; cin >> p; cin.ignore(numeric_limits<streamsize>::max(), '\n'); // s factorization long long int s = p - 1; // p - prime map<long long int, int> primes; int cnt = 0; factors(s, [&](long long int i){ if (primes.find(i) == primes.end()) primes[i] = 1; else primes[i]++; }); // finding a^(s/p_i) vector<long long int> arr; long long int firstPrimitive = -1; for (long long int a = 2; a < p; ++a) { bool is_primitive_root = true; for (auto& _p_i: primes) { long long int p_i = _p_i.first; if (pw(a, s/p_i, p) % p == 1) { is_primitive_root = false; break; } } if (is_primitive_root) { firstPrimitive = a; break; } } set<long long int> roots; roots.insert(firstPrimitive); // Generate all the other primitive roots // cout << firstPrimitive << endl; for (int i = 1; i < p; ++i) { // check m and s are coprime if (gcd(i, s) == 1) roots.insert(pw(firstPrimitive, i, p)); } cout << firstPrimitive << " " << roots.size() << endl; return 0; }
true
e5b1dee92a01443d600008801d87e8bb01d91271
C++
advancevillage/trace
/core/objectarray.h
UTF-8
737
2.515625
3
[]
no_license
#ifndef __OBJECT__ARRAY__ #define __OBJECT__ARRAY__ #ifndef __OBJECT__ #include "object.h" #endif // __OBJECT__ #ifndef __USED__VECTOR__ #define __USED__VECTOR__ #include <vector> using namespace std; #endif // __USED__VECTOR__ class ObjectArray{ protected: vector<Object> _objAry; public: ObjectArray(); ObjectArray(vector<Object>& objAry); ObjectArray(ObjectArray& oa); void operator=(vector<Object>& objAry); void operator=(ObjectArray& oa); void operator=(Object& obj); public: vector<Object> GetObjectArray()const; void Add(Object obj); void Add(vector<Object> objAry); void ClearAll(); void SetAllShow(const bool ishow); int GetSize()const; }; #endif // __OBJECT__ARRAY__
true
6e9aa2a6925b08e414519c3a6325564fb951a7f9
C++
seanmoreton/ppp_cpp_stroustrup
/chapter04/13. SieveOfEratosthenes (14).cpp
WINDOWS-1250
933
4.3125
4
[]
no_license
#include <iostream> #include <vector> //Create a program to find all the prime numbers between 1 and 100. //There is a classic method for doing this, called the Sieve of Eratosthenes. //If you dont know that method, get on the web and look it up. //Write your program using this method. void SieveOfEratosthenes(int n); int main() { int n = 0; std::cout << "Enter a positive integer:\n"; std::cin >> n; std::cout << "The following numbers are prime numbers below " << n << ":" << std::endl; SieveOfEratosthenes(n); return 0; } void SieveOfEratosthenes(int n) { // populate a vector with boolean values set to true std::vector<bool> numbers(n, true); for (int i = 2; i < sqrt(n); i++) { if (numbers[i]) { for (int j = i*i; j < n; j += i) numbers[j] = false; } } // print all prime numbers for (int i = 2; i < n; i++) if (numbers[i]) std::cout << i << "\t"; std::cout << "\n"; }
true
258e06d0d131c938783ca53ea4b3cfa69501deb0
C++
Zethian/proto-cubes-obc
/obcsim/RTC.hpp
UTF-8
1,213
2.53125
3
[ "MIT" ]
permissive
#include "RTClib.h" #define REQUEST_TIME 60 /* * RTC_init * Initializes the RTC clock */ void RTC_init(); /* * RTC_get * Returns a datetime variable with the current time of request * */ DateTime RTC_get(void); /* RTC_time_since_last * Returns a boolean if the time has passed the threshold of delaytime since last it triggered a true statement * Input the delaytime required * Can not be used for 2 timers simultaneous * Non-blocking */ boolean RTC_time_since_last(int delaytime); /** * RTC_set_time * Sets the time of the RTC with a provided Unix time stamp. * * @param uint32_t unix time stamp value * */ void RTC_set_time(uint32_t timestamp); /* * RTC_get_seconds * Returns a long with the current time in unixtime (seconds since 1st of january 1970) */ long RTC_get_seconds(void); /* * RTC_data_request_timer * Returns a boolean if timer target has been hit (not interrupt, so might not be 100% accurate) * */ boolean RTC_data_request_timer(void); /* * RTC_change_timer * Changes the time target for the timer in RTC, called whenever DAQDUR is used */ void RTC_change_timer(int request_timer); void RTC_enable_timed_daq(bool enable); bool RTC_timed_daq_enabled(void);
true
79128f51013e49ec2bd5046e568ad23145d97b66
C++
rongminjin/assignment18
/main.cpp
UTF-8
8,008
2.875
3
[]
no_license
// // main.cpp // a16w // // Created by Rongmin Jin on 3/28/19. // Copyright © 2019 Rongmin Jin. All rights reserved. // #include <iostream> #include "Header.h" #include "customer.hpp" string customerArrivalRate, serviceTime, randomSeed; size_t lengthOfDecimalPart; int randomSeedInt; double randomDecimalGenerator() { double randomDecimal; srand(randomSeedInt); int denominator = pow(10, lengthOfDecimalPart); double temp = rand() % denominator; randomDecimal = temp / denominator; randomSeedInt++; return randomDecimal; } unsigned customerArrivalRate2PerSecond() { unsigned numberOfCustomers; double customerArrivalRate_Double = stod(customerArrivalRate); double CAR_perSecond = customerArrivalRate_Double / 60; int integerPart = floor(CAR_perSecond); double tempDecimalPart = CAR_perSecond - integerPart; int lengthOfDecimal = 4; double denominator = pow(10, lengthOfDecimal); double decimalPart = floor(tempDecimalPart * pow(10, lengthOfDecimal)) / denominator; // cout << CAR_perSecond << "\t" << integerPart << "\t"<< decimalPart << endl; double criticalValve = 1 - (1 / denominator) - decimalPart; int trueOfCustomer = 0; if (randomDecimalGenerator() > criticalValve) trueOfCustomer = 1; numberOfCustomers = integerPart + trueOfCustomer; return numberOfCustomers; } vector<customer> customerGenerator() { vector<customer> temp; double maxStime = stod(serviceTime); int numberOfCustomers = customerArrivalRate2PerSecond(); if (numberOfCustomers > 0) { for (int i = 0; i < numberOfCustomers; ++i) { customer cTemp; cTemp.setServiceTime(floor(maxStime * randomDecimalGenerator() * 60)); temp.push_back(cTemp); } return temp; } else { return temp; } } int getIndexOfShortestLine(vector<handler> vh1) { int tempMin = vh1[0].getTotalWaitTime(); int index = 0; for (int i = 1; i < vh1.size(); ++i) { if (vh1[i].getTotalWaitTime() < tempMin) { tempMin = vh1[i].getTotalWaitTime(); index = i; } } return index; } vector<customer> simulator_market() { int hours = 12; int totalseconds = 60 * 60 * hours; //Queue for 6 cashiers int numberOfHandlers = 6; vector<handler> handlers(numberOfHandlers); vector<customer> totalCustomers; //simulation for operation for (int j = 0; j < totalseconds; ++j) { srand(randomSeedInt + j); //check each queue of handler for (int m = 0; m < numberOfHandlers; ++m) { if (handlers[m].getTotalWaitTime() > 0) { handlers[m].setTotalWaitTime(handlers[m].getTotalWaitTime() - 1); if (handlers[m].getMyqueue().front().getServiceTime() == 0) { customer temp = handlers[m].getMyqueue().front(); temp.setTotalServiceTime(j - temp.getArrivalTime() - 1); totalCustomers.push_back(temp); handlers[m].getMyqueue().pop(); handlers[m].getMyqueue().front().setServiceBeginTime(j); } if (handlers[m].getMyqueue().front().getServiceTime() == j - handlers[m].getMyqueue().front().getServiceBeginTime()) { customer temp = handlers[m].getMyqueue().front(); temp.setTotalServiceTime(j - temp.getArrivalTime()); totalCustomers.push_back(temp); handlers[m].popOffMyqueue(); handlers[m].setBeginTime(j); } } } //distribution of customer vector<customer> vTemp = customerGenerator(); if (vTemp.size() > 0) { for (int k = 0; k < vTemp.size(); ++k) { int index = getIndexOfShortestLine(handlers); if (handlers[index].getMyqueue().empty()) vTemp[k].setServiceBeginTime(j); vTemp[k].setArrivalTime(j); handlers[index].addToMyqueue(vTemp[k]); handlers[index].setTotalWaitTime(handlers[index].getTotalWaitTime() + vTemp[k].getServiceTime()); } } } return totalCustomers; } vector<customer> simulator_bank() { int hours = 12; int totalseconds = 60 * 60 * hours; //Queue for 6 cashiers int numberOfHandlers = 6; vector<handler> handlers(numberOfHandlers); vector<customer> totalCustomers; queue<customer> queueOfCustomers; for (int j = 0; j < totalseconds; ++j) { srand(randomSeedInt + j); vector<customer> vTemp = customerGenerator(); // generation of customers. // add arrivalTime to customer and add customer to waitting queue if (vTemp.size() > 0) { for (int k = 0; k < vTemp.size(); ++k) { vTemp[k].setArrivalTime(j); queueOfCustomers.push(vTemp[k]); } } for (int l = 0; l < numberOfHandlers; ++l) { if (handlers[l].getTotalWaitTime() > 0) { handlers[l].setTotalWaitTime(handlers[l].getTotalWaitTime() - 1); } //check status of handler and move customer to idle handler. if (handlers[l].getTotalWaitTime() == 0 && !handlers[l].getMyqueue().empty()) { customer ctemp1 = handlers[l].getMyqueue().front(); handlers[l].popOffMyqueue(); ctemp1.setServiceEndTime(j); ctemp1.setTotalServiceTime(j - ctemp1.getArrivalTime()); totalCustomers.push_back(ctemp1); } //distribution of customer from waitting queue if (handlers[l].getMyqueue().empty() && !queueOfCustomers.empty()) { customer ctemp = queueOfCustomers.front(); ctemp.setServiceBeginTime(j); queueOfCustomers.pop(); if (ctemp.getServiceTime() == 0) { ctemp.setTotalServiceTime(j - ctemp.getArrivalTime()); totalCustomers.push_back(ctemp); continue; } handlers[l].addToMyqueue(ctemp); handlers[l].setTotalWaitTime(ctemp.getServiceTime()); } } } return totalCustomers; } void printResults(vector<customer> bank, vector<customer> supermarket) { sort(bank.begin(), bank.end()); sort(supermarket.begin(), supermarket.end()); double b10, b50, b90; double s10, s50, s90; double secsPerMin = 60.0; b10 = bank[bank.size() / 10].getTotalServiceTime() / secsPerMin; b50 = bank[bank.size() / 10 * 5].getTotalServiceTime() / secsPerMin; b90 = bank[bank.size() / 10 * 9].getTotalServiceTime() / secsPerMin; s10 = supermarket[supermarket.size() / 10].getTotalServiceTime() / secsPerMin; s50 = supermarket[supermarket.size() / 10 * 5].getTotalServiceTime() / secsPerMin; s90 = supermarket[supermarket.size() / 10 * 9].getTotalServiceTime() / secsPerMin; cout << "Bank service time in minutes: 10th %ile " << b10 << ", 50th %ile " << b50 << ", 90th %ile " << b90 << endl; cout << "Supermark service time in minutes: 10th %ile " << s10 << ", 50th %ile " << s50 << ", 90th %ile " << s90 << endl; } double output4SP(vector<customer> input) { sort(input.begin(), input.end()); double i90; double secsPerMin = 60.0; if (input.size() == 0) return 0; else i90 = input[input.size() / 10 * 9].getTotalServiceTime() / secsPerMin; return i90; } int main(int argc, const char *argv[]) { srand(time(NULL)); if (argc < 4) { cout << " No enough parameters" << endl; return 0; } customerArrivalRate = argv[1]; serviceTime = argv[2]; lengthOfDecimalPart = 4; randomSeed = argv[3]; randomSeedInt = stoi(randomSeed); printResults(simulator_bank(), simulator_market()); return 0; }
true
8fdd0816d688406baaf928a0950ad81678c3a320
C++
Noah171/Cpp
/LevelMaker.h
WINDOWS-1252
2,304
3.125
3
[]
no_license
#pragma once #ifndef _LEVEL_MAKER_H #define _LEVEL_MAKER_H #define _GREEN 0x02 #define _BLUE 0x05 #define _RED 0x04 #define _BLACK 0x00 #define _WHITE 0x0f #define _YEN #include "stdafx.h" #include <vector> #include "Room.h" #include <random> #include "windows.h" using namespace std; class LevelMaker { public: HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); // handle to console LevelMaker(int);// constructor for LevelMaker, takes an int to assign current level void printMazeAnswer();// prints the maze void calculateMazeAnswer(); // Makes a binding of Isaac like maze void update(Room* nextRoom); // updates the room, takes a room that will be the room that will be acted in by the player // Getter funcs int getCurrentLevel(); std::vector<Room*> getMaze(); // returns the entire maze vector as a pointers std::vector<int> getMazeRooms(); Room * getPlayerRoom(); // gets a player's point in the maze private: short levelSize; /* Because the maze is formed with a single array acting as the entire maze with artificial columns and rows, this structure allows simpler access of locations. */ struct coordinates { int x; int y; int mazeCoordinate(int columns); // gets the coordinate of the maze based on the x and y of the coordinate and the number of columns. }; void adjustMazeExits(); // method for assigning neighbouring room locations to all of the maze's rooms. // the maze's dimensions short columns = (int)rand() % 20 + 5;// this acts as the x distance of the maze, in terms of the square this forms the bottom of the square short rows = (int)rand() % 10 + 5; // this acts as the y distance of the maze, in terms of the square this forms the side of the square std::vector<int> mazeRoomLocations; // an array of the actual locations of the rooms in maze int currentLevel; // current level in the maze int playerPosition; // position of player /*maze size properties*/ std::vector<Room*> maze; // entire map of the maze including all locations of the empty rooms //These two functions direct the new room locations in the creation of the maze. LevelMaker::coordinates * mazeDirection(int, coordinates); void mazeDirection(int, coordinates *); }; #endif
true
adda200eef0282aab6d382a43920bfaf4ca04ec0
C++
pollo/graph-partitioning
/partition.cpp
UTF-8
738
3.078125
3
[]
no_license
#include"partition.h" using namespace std; void Partition::set_size(int nodes_number, int partitions_number) { this->nodes_number = nodes_number; this->partitions_number = partitions_number; //-1 means not yet assigned partitions.resize(nodes_number, -1); partition_sizes.resize(partitions_number, 0); } void Partition::set_node_partition(int node_index, int partition) { partitions[node_index] = partition; partition_sizes[partition]++; } int Partition::get_node_partition(int node_index) const { return partitions[node_index]; } int Partition::get_partition_size(int partition_index) const { return partition_sizes[partition_index]; } int Partition::get_partitions_number() const { return partitions_number; }
true
72599ae2b2ff465c2d1422215af4120c69b34918
C++
langyastudio/sentinel-crypto
/SentinelRuntime/Cpp/hasplegacy.cpp
UTF-8
7,208
2.515625
3
[]
no_license
//////////////////////////////////////////////////////////////////// // Copyright (C) 2011, SafeNet, Inc. All rights reserved. // // HASP(R) is a registered trademark of SafeNet, Inc. // // // $Id: hasplegacy.cpp,v 1.19 2011-05-02 03:12:07 nsingh1 Exp $ //////////////////////////////////////////////////////////////////// #include "hasp_api_cpp_.h" //////////////////////////////////////////////////////////////////// //! \class ChaspLegacy hasp_api_cpp.h //! \brief Class permitting access to the Hasp4 legacy functions. //! //! //////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// // Construction/Destruction //////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// //! Intializes the object. //////////////////////////////////////////////////////////////////// ChaspLegacy::ChaspLegacy() { } //////////////////////////////////////////////////////////////////// //! Copy constructor intializing object with other's private key. //////////////////////////////////////////////////////////////////// ChaspLegacy::ChaspLegacy(const Chasp& other) : ChaspBase(other) { if (!other.hasLegacy()) DIAG_VERIFY(release()); } //////////////////////////////////////////////////////////////////// //! Copy constructor intializing object with other's private key. //////////////////////////////////////////////////////////////////// ChaspLegacy::ChaspLegacy(const ChaspLegacy& other) : ChaspBase(other) { } //////////////////////////////////////////////////////////////////// // Implementation //////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// //! Assignment operator. Initializes the object with other's //! private key after releasing its private key object. //////////////////////////////////////////////////////////////////// ChaspLegacy& ChaspLegacy::operator=(const Chasp& other) { if ((*this != other) && other.hasLegacy()) { dynamic_cast<ChaspBase&>(*this) = dynamic_cast<const ChaspBase&>(other); } return *this; } ChaspLegacy& ChaspLegacy::operator=(const ChaspLegacy& other) { dynamic_cast<ChaspBase&>(*this) = dynamic_cast<const ChaspBase&>(other); return *this; } //////////////////////////////////////////////////////////////////// //! Decrypts the specified data using the Hasp4 algorithm. //! //! \param pData Pointer to the first byte to be //! decrypted. //! \param ulSize The size of the buffer to be //! decrypted. //! //! \return A \a haspStatus status code. //! //! \sa ChaspImpl::legacyDecrypt //////////////////////////////////////////////////////////////////// haspStatus ChaspLegacy::decrypt(unsigned char* pData, hasp_size_t ulSize) const { HASP_PROLOGUE(m_handle); return HASP_KEYPTR->legacyDecrypt(pData, ulSize); } //////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////// haspStatus ChaspLegacy::decrypt(const char*) const { return HASP_INVALID_PARAMETER; } //////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////// haspStatus ChaspLegacy::decrypt(std::string& data) const { std::vector<unsigned char> vector; ChaspBase64::decode(data, vector); haspStatus nStatus = decrypt(&vector[0], static_cast<hasp_size_t>(vector.size())); if (HASP_STATUS_OK != nStatus) return nStatus; data.resize(0); for (std::vector<unsigned char>::const_iterator it = vector.begin(); (vector.end() != it) && (0 != *it); it++) data += *it; return HASP_STATUS_OK; } //////////////////////////////////////////////////////////////////// //! Encrypts the specified data using the Hasp4 algorithm. //! //! \param pData Pointer to the first byte to be //! encrypted. //! \param ulSize The size of the buffer to be //! encrypted. //! //! \return A \a haspStatus status code. //! //! \sa ChaspImpl::legacyEncrypt //////////////////////////////////////////////////////////////////// haspStatus ChaspLegacy::encrypt(unsigned char* pData, hasp_size_t ulSize) const { HASP_PROLOGUE(m_handle); return HASP_KEYPTR->legacyEncrypt(pData, ulSize); } //////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////// haspStatus ChaspLegacy::encrypt(const char*) const { return HASP_INVALID_PARAMETER; } //////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////// haspStatus ChaspLegacy::encrypt(std::string& data) const { std::vector<unsigned char> vector; std::copy(data.begin(), data.end(), std::back_inserter(vector)); if (HASP_MIN_BLOCK_SIZE_LEGACY > vector.size()) vector.resize(HASP_MIN_BLOCK_SIZE, 0); haspStatus nStatus= encrypt(&vector[0], static_cast<hasp_size_t>(vector.size())); if (HASP_STATUS_OK != nStatus) return nStatus; ChaspBase64::encode(vector, data); return HASP_STATUS_OK; } //////////////////////////////////////////////////////////////////// //! Sets the idle time. //! //! \param nIdleTime The idle time to be set. //! //! \return A \a haspStatus status code. //! //! \sa ChaspImpl::setIdleTime //////////////////////////////////////////////////////////////////// haspStatus ChaspLegacy::setIdleTime(hasp_u16_t nIdleTime) const { HASP_PROLOGUE(m_handle); return HASP_KEYPTR->setIdleTime(nIdleTime); } //////////////////////////////////////////////////////////////////// //! Sets the date and time of the real time clock. //! //! \param time The date and time to be set. //! //! \return A \a haspStatus status code. //! //! \sa ChaspImpl::setRtc //////////////////////////////////////////////////////////////////// haspStatus ChaspLegacy::setRtc(const ChaspTime& time) const { HASP_PROLOGUE(m_handle); return HASP_KEYPTR->legacySetRtc(time); } //////////////////////////////////////////////////////////////////// //! Returns the login handle as a human readable string. //! //! \sa ChaspImpl::toString //////////////////////////////////////////////////////////////////// std::string ChaspLegacy::toString() const { ChaspMap map; DIAG_ASSERT(isValid()); if (!isValid()) return std::string(); ChaspImpl* pKey = map.getKey(m_handle); DIAG_ASSERT(NULL != pKey); return (NULL == pKey) ? std::string() : pKey->toString(); }
true
dc991ad915bb5c5858364736bd521aa737c24a01
C++
jjuiddong/Common
/Network/packetqueue.h
UHC
3,735
2.765625
3
[ "MIT" ]
permissive
// // 2015-11-29, jjuiddong // // - Ŷ Ѵ. Thread Safe, ִ ϰ . // - Ʈ Ÿ Ŷ ũ⸸ŭ Ѵ. // - ť , Ŷ ϰ, ߰Ѵ. // - ϸ packetSize ũ⸸ŭ ä Ѿ ʴ´. // - Ŷ ť , (sHeader) ߰ȴ. // - ϸ ϳ ̻ ť ִ. // // 2016-06-29, jjuiddong // - sHeader Ŷ ְ // - Init(), isIgnoreHeader ÷ ߰ // // 2016-05-26, jjuiddong // - ū Ŷ sHeader , Ŷ ״´. // - Ʈũ Ŷ 2 ̻ , óѴ. // // 2016-09-24, jjuiddong // - ޸Ǯ , Ŷ Ѵ. // // 2018-11-07, jjuiddong // - header // - [0 ~ 3] : protocol ascii code // - [4 ~ 7] : packet bytes length by ascii (ex 0085, 85 bytes) // // 2019-01-04 // - update iProtocol // #pragma once namespace network { // Ŷ Ѵ. // ϳ Ŷ , sSockBuffer ȴ. struct sSockBuffer { SOCKET sock; // int protocol; BYTE *buffer; int totalLen; // = iProtocol::GetHeaderSize() + buffer size bool full; // ۰ ä true ȴ. int readLen; int actualLen; // Ŷ ũ⸦ Ÿ. buffer size(bytes) {= totalLen - sizeof(sHeader)} }; struct sSession; class cPacketQueue { public: cPacketQueue(iProtocol *protocol = NULL); virtual ~cPacketQueue(); bool Init(const int packetSize, const int maxPacketCount); void Push(const SOCKET sock, iProtocol *protocol, const BYTE *data, const int len); void PushFromNetwork(const SOCKET sock, const BYTE *data, const int len); bool Front(OUT sSockBuffer &out); void Pop(); void SendAll(OUT vector<SOCKET> *outErrSocks = NULL); void SendAll(const sockaddr_in &sockAddr); void SendBroadcast(vector<sSession> &sessions, const bool exceptOwner = true); void Lock(); void Unlock(); int GetSize(); int GetPacketSize(); int GetMaxPacketCount(); public: vector<sSockBuffer> m_queue; iProtocol *m_protocol; BYTE *m_tempHeaderBuffer; // ӽ÷ Header ϴ int m_tempHeaderBufferSize; bool m_isStoreTempHeaderBuffer; // ӽ÷ ϰ true BYTE *m_tempBuffer; // ӽ÷ int m_tempBufferSize; bool m_isLogIgnorePacket; // Ŷ α׸ , default = false protected: sSockBuffer* FindSockBuffer(const SOCKET sock); int CopySockBuffer(sSockBuffer *dst, const BYTE *data, const int len); int AddSockBuffer(const SOCKET sock, iProtocol *protocol , const BYTE *data, const int len); int AddSockBufferByNetwork(const SOCKET sock, const BYTE *data, const int len); //--------------------------------------------------------------------- // Simple Queue Memory Pool BYTE* Alloc(); void Free(BYTE*ptr); void ClearMemPool(); void Clear(); struct sChunk { bool used; BYTE *p; }; vector<sChunk> m_memPool; BYTE *m_memPoolPtr; int m_packetBytes; // header Ŷ ũ int m_chunkBytes; // Ŷ ũ (actual size) int m_totalChunkCount; CRITICAL_SECTION m_criticalSection; }; inline int cPacketQueue::GetPacketSize() { return m_packetBytes; } inline int cPacketQueue::GetMaxPacketCount() { return m_totalChunkCount; } }
true
652062aaa5f775e83759cf48b799780eccc5c15d
C++
adrs0049/FastVector
/utils/type_info.cpp
UTF-8
1,007
2.546875
3
[ "MIT" ]
permissive
//////////////////////////////////////////////////////////////////////////////// // // // File Name: type_info.cpp // // // // Author: Andreas Buttenschoen <andreas@buttenschoen.ca> // // Created: 2018-01-01 // // // //////////////////////////////////////////////////////////////////////////////// #include "type_info.h" #if defined(__GNUC__) #include <cxxabi.h> std::string demangle(const char * name) { int status = -4; std::unique_ptr<char, void(*)(void*)> res { abi::__cxa_demangle(name, nullptr, nullptr, &status), std::free }; return (status==0) ? res.get() : name; } #else std::string demangle(const char * name) { return name; } #endif
true
54907c613aeca84ed7eec8ca657bffa39b6a58d2
C++
BakaErii/ACM_Collection
/HDU/1849/13174081_AC_15ms_1700kB.cpp
UTF-8
624
2.625
3
[ "WTFPL" ]
permissive
/** * @author Moe_Sakiya sakiya@tun.moe * @date 2018-03-24 19:15:02 * */ #include <iostream> #include <string> #include <algorithm> #include <set> #include <map> #include <vector> #include <stack> #include <queue> #include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> using namespace std; int main(void) { ios::sync_with_stdio(false); cin.tie(NULL); int i, n, tmp, sum; while (~scanf("%d", &n) && n != 0) { sum = 0; for (i = 0; i < n; i++) { scanf("%d", &tmp); sum ^= tmp; } if (sum == 0) cout << "Grass Win!" << endl; else cout << "Rabbit Win!" << endl; } return 0; }
true
4203818dd45327b83448abd25ee2d477191fc871
C++
sneumann/Rdisop
/src/imslib/src/ims/masspeak.h
UTF-8
1,410
3.546875
4
[]
no_license
#ifndef IMS_MASSPEAK_H #define IMS_MASSPEAK_H #include <ostream> namespace ims { /** * Represents a peak that contains only a mass. * * @param MassType the mass type * * @ingroup peaks */ template <typename MassType = double> class MassPeak { public: typedef MassType mass_type; /** Identifier for mass property. Peaks are designed to be plugged together using * multiple inheritance. This typedef allows statements like * peaklist.begin&lt;MyPeak::MassProperty&gt;(); */ struct MassGetter { typedef MassType value_type; inline static value_type& get(MassPeak<MassType>& p) { return p.getMassReference(); } inline static const value_type& get(const MassPeak<MassType>& p) { return p.getMass(); } }; MassPeak() {} MassPeak(const MassPeak<MassType>& peak): mass(peak.mass) {} MassPeak(mass_type mass): mass(mass) {} const mass_type& getMass() const { return mass; } void setMass(mass_type mass) { this->mass = mass; } bool operator==(const MassPeak<MassType>& peak) const { return mass == peak.mass; } bool operator!=(const MassPeak<MassType>& peak) const { return !(operator==(peak)); } protected: mass_type& getMassReference() { return mass; } private: mass_type mass; }; template <typename MassType> std::ostream& operator<< (std::ostream& os, const MassPeak<MassType>& peak) { return os << peak.getMass(); } } #endif // IMS_MASSPEAK_H
true
f157ee03a211ccf62ec5e603306424249f0d2352
C++
nasa/gunns
/ms-utils/math/approximation/ProductFit.cpp
UTF-8
3,199
2.625
3
[ "LicenseRef-scancode-us-govt-public-domain", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/************************** TRICK HEADER ********************************************************** LIBRARY DEPENDENCY: ((TsApproximation.o)) ***************************************************************************************************/ #include "ProductFit.hh" //////////////////////////////////////////////////////////////////////////////////////////////////// /// @details Default constructs this Bivariate Product curve fit model. //////////////////////////////////////////////////////////////////////////////////////////////////// ProductFit::ProductFit() : TsApproximation(), mA(0.0) { // nothing to do } //////////////////////////////////////////////////////////////////////////////////////////////////// /// @param[in] a (--) First coefficient for curve fit model. /// @param[in] minX (--) Curve fit model valid range lower limit for first variable. /// @param[in] maxX (--) Curve fit model valid range upper limit for first variable. /// @param[in] minY (--) Curve fit model valid range lower limit for second variable. /// @param[in] maxY (--) Curve fit model valid range upper limit for second variable. /// @param[in] name (--) name for the instance. /// /// @details Constructs this Bivariate Product curve fit model taking coefficient and range /// arguments. //////////////////////////////////////////////////////////////////////////////////////////////////// ProductFit::ProductFit(const double a, const double minX, const double maxX, const double minY, const double maxY, const std::string &name) : TsApproximation(), mA(a) { init(a, minX, maxX, minY, maxY, name); } //////////////////////////////////////////////////////////////////////////////////////////////////// /// @details Default destructs this Bivariate Product curve fit model. //////////////////////////////////////////////////////////////////////////////////////////////////// ProductFit::~ProductFit() { // nothing to do } //////////////////////////////////////////////////////////////////////////////////////////////////// /// @param[in] a (--) First coefficient for curve fit model. /// @param[in] minX (--) Curve fit model valid range lower limit for first variable. /// @param[in] maxX (--) Curve fit model valid range upper limit for first variable. /// @param[in] minY (--) Curve fit model valid range lower limit for second variable. /// @param[in] maxY (--) Curve fit model valid range upper limit for second variable. /// @param[in] name (--) name for the instance. /// /// @details Initializes this Product curve fit model taking coefficient, range and name arguments //////////////////////////////////////////////////////////////////////////////////////////////////// void ProductFit::init(const double a, const double minX, const double maxX, const double minY, const double maxY, const std::string &name) { /// - Initialize the parent TsApproximation::init(minX, maxX, minY, maxY, name); /// - Initialize the coefficient. mA = a; }
true
62264bb2020b9a8e1fa8408733f778ca4d81df1b
C++
aschor/somfy_esp8266_remote_arduino
/config.h
UTF-8
1,865
2.671875
3
[]
no_license
// You can add as many remote control emulators as you want by adding elements to the "remotes" vector // The id and mqtt_topic can have any value but must be unique // default_rolling_code can be any unsigned int, usually leave it at 1 // eeprom_address must be incremented by 4 for each remote // Once the programe is uploaded on the ESP32: // - Long-press the program button of YOUR ACTUAL REMOTE until your blind goes up and down slightly // - send 'p' using MQTT on the corresponding topic // - You can use the same remote control emulator for multiple blinds, just repeat these steps. // // Then: // - u will make it go up // - s make it stop // - d will make it go down // id mqtt_topic default_rolling_code eeprom_address std::vector<REMOTE> const remotes = {{0x184623, "home/nodemcu/somfy/[DEVICE ID YOU USE]", 1, 0} }; // Change reset_rolling_codes to true to clear the rolling codes stored in the non-volatile storage // The default_rolling_code will be used const bool reset_rolling_codes = false; const char* wifi_ssid = "[SSID]"; const char* wifi_password = "[SSID Password]"; const char* mqtt_server = "[MQTT HOST Server]"; const unsigned int mqtt_port = 1883; const char* mqtt_user = "username"; const char* mqtt_password = "secretPassword5678"; const char* mqtt_id = "esp8266-somfy-remote"; const char* status_topic = "home/nodemcu/somfy/[DEVICE ID YOU USE]/status"; // Online / offline const char* state_topic = "home/nodemcu/somfy/[DEVICE ID YOU USE]/state"; const char* ack_topic = "home/nodemcu/somfy/[DEVICE ID YOU USE]/ack"; // Commands ack "id: 0x184623, cmd: u" #define PORT_TX 5 // Output data on pin 23 (can range from 0 to 31). Check pin numbering on ESP8266.
true
23464ebd007c1c4ac68553310ab2ab2eae7f0d5a
C++
mgoongaBabangida/engine
/Mgoonga/math/SceletalAnimation.h
UTF-8
2,337
2.859375
3
[]
no_license
#ifndef SCELETAL_ANIMATION_H #define SCELETAL_ANIMATION_H #include "stdafx.h" #include <base/interfaces.h> #include "Transform.h" #include "Clock.h" #include <map> //------------------------------------------------------------------- struct Frame { int64_t timeStamp; std::map<std::string, Transform> pose; Frame(int64_t timeStamp, std::map<std::string, Transform> pose) : timeStamp(timeStamp), pose(pose) {} Frame(){} //improve void addTimeStamp(int stamp) { timeStamp = stamp; } void addTrnasform(std::string name, Transform trs) { pose.insert(std::pair<std::string, Transform>(name, trs)); } bool exists(const std::string& name) const { return pose.find(name) != pose.end(); } }; //--------------------------------------------------------------------- class DLL_MATH SceletalAnimation : public IAnimation { public: SceletalAnimation(int64_t dur, const std::vector<Frame> & frames ,const std::string _name) : duration(dur), frames(frames), name(_name), freeze_frame(-1), cur_frame_index(-1) { Start(); } SceletalAnimation(const SceletalAnimation& _other) { *this = _other; } SceletalAnimation& operator=(const SceletalAnimation& _other) { if (&_other != this) { duration = _other.duration; frames = _other.frames; name = _other.name; freeze_frame = _other.freeze_frame; cur_frame_index = _other.cur_frame_index; } return *this; } bool operator==(const SceletalAnimation& other) { return name == other.name && duration == other.duration; } const Frame& getCurrentFrame(); const Frame& GetFrameByNumber(size_t _num) const; size_t GetCurFrameIndex() const; size_t GetNumFrames() const { return frames.size(); } int64_t GetDuration() const { return duration; } virtual void Start() override; virtual void Stop() override; virtual void Continue() override; virtual bool IsPaused() override; void PlayOnce(); void FreezeFrame(size_t); virtual const std::string& Name() const override; void SetName(const std::string& n); void Debug(); protected: math::eClock clock; std::vector<Frame> frames; int64_t duration; // msc std::string name; bool play_once = false; size_t freeze_frame = -1; size_t cur_frame_index = -1; }; #endif
true
2c2d7f8d449abf5f73c9959c46071674b97cd0b8
C++
Chenromeo/DBMS
/数据结构/list5/main.cpp
GB18030
7,344
2.953125
3
[]
no_license
// list5 #include "Slist.h" #include <bits/stdc++.h> using namespace std; typedef struct { char sFieldName[10]; //ֶ char sType[8]; //ֶ int iSize; //ֳ char bKey; //ֶǷΪKEY char bNullFlag; //ֶǷΪ char bValidFlag; //ֶǷЧԺԱиֶεɾ } TableMode, *PTableMode; typedef struct { char tableName[1000]; // int TableModecount; //ֶ TableMode modeinsert[100]; } Tableset; void dataInsert(Tableset *newTable, SList *s) { assert(s); SListInit(s); for (int i = 0; i < newTable->TableModecount; i++) { // char l_data[newTable->modeinsert[i].iSize]; char * l_data=(char*)malloc(newTable->modeinsert[i].iSize); scanf("%s", l_data); SListPushBack(s, l_data); } } void printTable(Tableset *newTable, SList *s,int datalinecount){ assert(s); for(int i = 0;i<newTable->TableModecount;i++){ if (i==newTable->TableModecount-1) printf("%s\n",newTable->modeinsert[i].sFieldName); else printf("%s ",newTable->modeinsert[i].sFieldName); } for (int t = 0; t < datalinecount; t++) SListPrint(s + t); } void createTable() { Tableset *newTable = (Tableset *)malloc(sizeof(Tableset)); printf("\n"); scanf("%s", newTable->tableName); printf("ֶ\n"); scanf("%d", &newTable->TableModecount); printf("ֳֶֶֶͣǷΪKEYֶǷΪգֶǷЧԺԱиֶεɾ\n"); for (int i = 0; i < newTable->TableModecount; i++) { scanf("%s ", newTable->modeinsert[i].sFieldName); scanf("%s", newTable->modeinsert[i].sType); scanf("%d", &newTable->modeinsert[i].iSize); scanf("%c ", &newTable->modeinsert[i].bKey); scanf("%c ", &newTable->modeinsert[i].bNullFlag); scanf("%c\n", &newTable->modeinsert[i].bValidFlag); fflush(stdin); } printf("=====================================================================\n"); int datalinecount; fflush(stdin); printf("Ԫ:\n"); cin>>datalinecount; SList *s = (SList *)calloc(100, sizeof(SList)); printf("=====================================================================\n"); printf("\n"); fflush(stdin); for (int t = 0; t < datalinecount; t++) dataInsert(newTable, s + t); printTable(newTable, s,datalinecount); } struct SListNode *BuySListNode(SDataType data) { struct SListNode *p; p = (struct SListNode *)malloc(sizeof(struct SListNode)); p->_data = data; p->_PNext = NULL; } void SListInit(SList *s) { assert(s); s->_pHead = NULL; } void SListPushBack(SList *s, SDataType data) { //һڵ assert(s); PNode pNewNode = BuySListNode(data); if (s->_pHead == NULL) { //ûнڵ s->_pHead = pNewNode; } else { PNode pCur = s->_pHead; while (pCur->_PNext) { pCur = pCur->_PNext; } //һڵָ½ڵ pCur->_PNext = pNewNode; } } void SListPopBack(SList *s) { assert(s); if (s->_pHead == NULL) { //ûнڵ return; } else if (s->_pHead->_PNext == NULL) { //ֻһڵ free(s->_pHead); s->_pHead = NULL; } else { //ڵ PNode pCur = s->_pHead; PNode pPre = NULL; while (pCur->_PNext) { pPre = pCur; pCur = pCur->_PNext; } free(pCur); pPre->_PNext = NULL; } } void SListPushFront(SList *s, SDataType data) { assert(s); PNode pNewNode = BuySListNode(data); if (s->_pHead == NULL) { //Ϊ s->_pHead = pNewNode; } else { pNewNode->_PNext = s->_pHead; s->_pHead = pNewNode; } } void SListPopFront(SList *s) { assert(s); if (s->_pHead == NULL) { //Ϊ return; } else if (s->_pHead->_PNext == NULL) { //ֻһڵ free(s->_pHead); s->_pHead = NULL; } else { PNode pCur = s->_pHead; s->_pHead = pCur->_PNext; free(pCur); } } void SListInsert(PNode pos, SDataType data) { PNode pNewNode = NULL; if (pos == NULL) { return; } pNewNode = BuySListNode(data); pNewNode->_PNext = pos->_PNext; pos->_PNext = pNewNode; } PNode SListFind(SList *s, SDataType data) { assert(s); PNode pCur = s->_pHead; while (pCur) { if (pCur->_data == data) { return pCur; } pCur = pCur->_PNext; } return NULL; } void SListErase(SList *s, PNode pos) { assert(s); if (pos == NULL || s->_pHead == NULL) { return; } if (pos == s->_pHead) { s->_pHead = pos->_PNext; } else { PNode pPrePos = s->_pHead; while (pPrePos && pPrePos->_PNext != pos) { pPrePos = pPrePos->_PNext; } pPrePos->_PNext = pos->_PNext; } free(pos); } void SListRemove(SList *s, SDataType data) { assert(s); if (s->_pHead == NULL) { return; } PNode pPre = NULL; PNode pCur = s->_pHead; while (pCur) { if (pCur->_data == data) { if (pCur == s->_pHead) { //ҪɾǵһλõĽڵ s->_pHead = pCur->_PNext; } else { pPre->_PNext = pCur->_PNext; //λõǰһڵָһڵ } free(pCur); return; } else { pPre = pCur; pCur = pCur->_PNext; } } } int SListSize(SList* s) { //ȡЧڵĸ assert(s); int count = 0; PNode pCur = s->_pHead; while (pCur) { count++; pCur = pCur->_PNext; } return count; } int SListEmpty(SList* s) { //ǷΪ assert(s); if (s->_pHead == NULL) { return -1; } return 0; } void SListClear(SList* s) { // assert(s); if (s->_pHead == NULL) { return; } PNode pCur = s->_pHead; while (pCur->_PNext) { //ѭеĽڵ PNode Tmp = pCur->_PNext; free(pCur); pCur = Tmp; } if (pCur) { //һڵ free(pCur); pCur = NULL; } } void SListDestroy(SList* s) { // assert(s); if (s->_pHead == NULL) { free(s->_pHead); return; } while (s->_pHead) { PNode Tmp = s->_pHead->_PNext; free(s->_pHead); s->_pHead = Tmp; } } void SListPrint(SList* s) { //ӡ assert(s); PNode pCur = s->_pHead; while (pCur) { printf("%s--->", pCur->_data); pCur = pCur->_PNext; } printf("\n"); } int main() { // createTable(); SList s; char l_data[]="asffasgf"; SListPushBack(&s, l_data); SListPrint(&s); system("pause"); return 0; }
true
b30b3637b167e47479a4f128d3740d013da555e4
C++
peterhuene/puppetcpp
/lib/include/puppet/utility/filesystem/helpers.hpp
UTF-8
1,325
3.25
3
[ "Apache-2.0" ]
permissive
/** * @file * Declares the filesystem helper functions. */ #pragma once #include <string> #include <boost/filesystem.hpp> namespace puppet { namespace utility { namespace filesystem { /** * Gets the default path separator. * This will be ':' on POSIX systems and ';' on Windows. * @return Returns the default path separator. */ char const* path_separator(); /** * Gets the home directory of the current user. * @return Returns the home directory of the current user or an empty string if the home directory can't be determined. */ std::string home_directory(); /** * Makes a path absolute. * This will also make the path lexically normal. * @param path The path to make absolute. * @param base The base path to resolve a relative path to; defaults to the current directory. * @return Returns the normalized absolute path. */ std::string make_absolute(std::string const& path, std::string const& base = {}); /** * Normalizes a relative path. * @param path The relative path to normalize. * @return Returns true if the path is relative and was normallized; returns false if the path was not relative. */ bool normalize_relative_path(std::string& path); }}} // namespace puppet::utility::filesystem
true
2d3ca71ab28adce03579302860dd7aa6985f00f7
C++
lpanian/lptoolkit
/tests/unit/utf8_test.cpp
UTF-8
2,044
2.828125
3
[]
no_license
#include "toolkit/utf8str.hh" #include <gtest/gtest.h> using namespace lptk; //////////////////////////////////////////////////////////////////////////////// TEST(UTF8, Decode8) { const auto utf8 = u8"$"; auto pair = utf8_decode(utf8); EXPECT_EQ(lptk::CharPoint('$'), pair.first); EXPECT_EQ(utf8 + 1, pair.second); } TEST(UTF8, Decode16) { const auto utf8 = u8"\u00a2"; auto pair = utf8_decode(utf8); EXPECT_EQ(lptk::CharPoint(0xa2), pair.first); EXPECT_EQ(utf8 + 2, pair.second); } TEST(UTF8, Decode24) { const auto utf8 = u8"\u20ac"; auto pair = utf8_decode(utf8); EXPECT_EQ(lptk::CharPoint(0x20ac), pair.first); EXPECT_EQ(utf8 + 3, pair.second); } TEST(UTF8, Decode32) { const auto utf8 = u8"\U00010348"; auto pair = utf8_decode(utf8); EXPECT_EQ(lptk::CharPoint(0x10348), pair.first); EXPECT_EQ(utf8 + 4, pair.second); } TEST(UTF8, BadContinuation) { const char bad[] = { '\xc1', '\xc0', 0 }; auto pair = utf8_decode(bad); EXPECT_EQ(lptk::CharPoint(0), pair.first); EXPECT_EQ(bad + 2, pair.second); } TEST(UTF8, SimpleLen) { const auto utf8 = u8"caf\u00e9"; EXPECT_EQ(4, utf8_strlen(utf8)); } TEST(UTF8, ComboLen) { // we don't combine in our decode or strlen. const auto utf8 = u8"cafe\u0301"; EXPECT_EQ(5, utf8_strlen(utf8)); } TEST(UTF8, DecodeSequence) { const auto utf8 = u8"caf\u00e9"; int i = 0; const CharPoint expected[] = { 'c', 'a', 'f', 0x00e9 }; auto cur = utf8; while (cur && *cur) { ASSERT(i < ARRAY_SIZE(expected)); auto pair = utf8_decode(cur); EXPECT_EQ(expected[i], pair.first); ++i; cur = pair.second; } EXPECT_EQ(4, i); } TEST(UTF8, RangeIter) { const auto utf8 = u8"caf\u00e9"; int i = 0; const CharPoint expected[] = { 'c', 'a', 'f', 0x00e9 }; for (auto&& cp : utf8range(utf8)) { ASSERT(i < ARRAY_SIZE(expected)); EXPECT_EQ(expected[i], cp); ++i; } EXPECT_EQ(4, i); }
true
e62b373d52d63c39b36a4fbe9745ccc704e05513
C++
Icemore/homework
/fall_2013/cpp/hw/huffman/src/BinaryWriter.h
UTF-8
529
2.828125
3
[]
no_license
#pragma once #include <iostream> #include <vector> #include "BitChain.h" #include "Constants.h" class BinaryWriter { public: BinaryWriter(std::ostream &ofs); ~BinaryWriter(); void writeByte(uint8_t byte, int bitsUsed = BITS_IN_BYTE); void writeVector(std::vector<uint8_t> &vec); void writeNumber(uint64_t num, int bitsUsed); void writeBitChain(BitChain &chain); void flushBuffer(); private: std::ostream &ofs_; std::vector<uint8_t> buffer_; int currentByte_; int usedBitsInLastByte_; };
true
463430fdfdd78d82cb51272733f734a1103d719c
C++
scarletea/SDUT
/4202.cpp
UTF-8
512
2.65625
3
[]
no_license
#include<iostream> using namespace std; int main() { int n; while(scanf("%d",&n)!=EOF) { int w1[5010],w2[5010],w3[5010]; double sum[5010]; int max = -1; int f = 0; for(int i = 0;i<n;i++) { cin>>w1[i]>>w2[i]>>w3[i]; sum[i] = (double)w1[i]*0.7+w2[i]*0.2+w3[i]*0.1; if(max<sum[i]) { max = sum[i]; f = i; } } cout<<f<<endl; } return 0; }
true
a5928eeb03e43be142b440a18bdfe2ff494022fc
C++
badstyle319/UVA
/1st Edition's Exercises/4. Graph/00469 - Wetlands of Florida.cpp
UTF-8
1,855
2.828125
3
[]
no_license
#include <cstdio> #include <cstdlib> #include <cstring> #include <string> #include <vector> #include <map> #include <algorithm> #include <cmath> #include <iostream> #include <iomanip> #include <sstream> #define LL long long #define ULL unsigned long long using namespace std; vector<string> arr; int answer = 0; void flood(int r, int c, char ch){ if(r>=arr.size() || r<0 || c>=arr[0].length() || c<0) return; if(arr[r][c]==ch){ answer++; arr[r][c] = tolower(ch); static int dx[] = {-1,-1,-1,0,0,1,1,1}; static int dy[] = {-1,0,1,-1,1,-1,0,1}; for(int k=0;k<8;k++) flood(r+dx[k], c+dy[k], ch); } } int main() { #ifndef ONLINE_JUDGE freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); #endif string line; int caseNum, r, c; cin>>caseNum; getline(cin, line);//consume the ending after the case number getline(cin, line);//consume the blank line while(caseNum-->0){ /////////////// arr.clear(); getline(cin, line); while(1){ if(line.length()>0 && (line[0]=='L' || line[0]=='W')){ arr.push_back(line); }else break; getline(cin, line); } stringstream ss(line); ss>>r>>c; r--;c--; answer = 0; for(int i=0;i<arr.size();i++) for(int j=0;j<arr[i].size();j++) arr[i][j] = toupper(arr[i][j]); flood(r, c, arr[r][c]); cout<<answer<<endl; while(getline(cin, line)){ if(line.length()>0){ stringstream ss2(line); ss2>>r>>c; r--;c--; answer = 0; for(int i=0;i<arr.size();i++) for(int j=0;j<arr[i].size();j++) arr[i][j] = toupper(arr[i][j]); flood(r, c, arr[r][c]); cout<<answer<<endl; }else break; } if(caseNum) cout<<endl; /////////////// } #ifndef ONLINE_JUDGE fclose(stdin); fclose(stdout); #endif return 0; }
true
b0df22ee12f198b12bde120971e354b6c6b00b73
C++
huihui571/leetcode-daily
/每日一题/2021年2月/448-找到所有数组中消失的数字.cpp
UTF-8
1,243
3.328125
3
[]
no_license
/*<FH+>************************************************************************ * Editor : Vim * File name : 448-找到所有数组中消失的数字.cpp * Author : huihui571 * Created date: 2021-02-13 * Description : 给定一个范围在  1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。 * 找到所有在 [1, n] 范围之间没有出现在数组中的数字。 * 您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。 * *<FH->************************************************************************/ #include <bits/stdc++.h> using namespace std; /** * 对号入座 */ class Solution { public: vector<int> findDisappearedNumbers(vector<int>& nums) { int n = nums.size(); for (int i = 0; i < n; i++) { while (nums[i] != nums[nums[i] - 1]) { swap(nums[i], nums[nums[i] - 1]); } } vector<int> res; for (int i = 0; i < n; i++) { if (nums[i] != i + 1) { res.push_back(i + 1); } } return res; } };
true
0bfcbdafe046879aee1d819d2955da72ddf38e47
C++
Mansterteddy/Cracking-the-Coding-Interview
/algorithm/leetcode/Q18/main.cc
UTF-8
3,003
3.375
3
[]
no_license
#include <vector> #include <algorithm> #include <iostream> using namespace std; class Solution { public: vector<vector<int>> fourSum(vector<int>& nums, int target){ vector<vector<int>> res; if(nums.size() < 4){ return res; } sort(nums.begin(), nums.end()); if(nums[0] > target && target >= 0) return res; if(nums[nums.size()-1] < target && target <= 0) return res; int length = nums.size(); for(int i = 0; i < length - 3; i++){ if(i > 0 && nums[i] == nums[i-1]) continue; if( (long) nums[i] + nums[i+1] + nums[i+2] + nums[i+3] == target){ res.push_back({nums[i], nums[i+1], nums[i+2], nums[i+3]}); break; } if( (long) nums[i] + nums[i+1] + nums[i+2] + nums[i+3] > target) break; if( (long) nums[i] + nums[length - 3] + nums[length - 2] + nums[length - 1] < target) continue; for(int j = i + 1; j < length - 2; ++j){ if(j > i + 1 && nums[j] == nums[j-1]) continue; if( (long) nums[i] + nums[j] + nums[j+1] + nums[j+2] == target){ res.push_back({nums[i], nums[j], nums[j+1], nums[j+2]}); break; } if( (long) nums[i] + nums[j] + nums[j+1] + nums[j+2] > target) break; if( (long) nums[i] + nums[j] + nums[length-2] + nums[length-1] < target) continue; int left = j + 1; int right = length - 1; while(left < right){ long sum = nums[i] + nums[j] + nums[left] + nums[right]; if(sum == target){ res.push_back({nums[i], nums[j], nums[left], nums[right]}); while(left < right && nums[left] == nums[left+1]) left++; left++; while(left < right && nums[right] == nums[right-1]) right--; right--; } else if(sum < target){ left++; } else{ right--; } } } } return res; } }; int main(){ Solution s = Solution(); vector<int> nums{1, 0, -1, 0, -2, 2}; int target = 0; vector<vector<int>> res = s.fourSum(nums, target); for(auto vec : res){ for(auto item : vec){ cout << item << " "; } cout << endl; } return 0; }
true
541708f4b4a0fb065a4af606c606593bf5fa3f93
C++
a-ovch/oop
/lab1/flipbyte/flipbyte.cpp
UTF-8
1,278
3.40625
3
[]
no_license
// flipbyte.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <sstream> #define BITS_IN_BYTE 8 #define MIN_INPUT_VALUE 0 #define MAX_INPUT_VALUE 255 using namespace std; unsigned char ReversBits(unsigned char num); int main(int argc, char *argv[]) { if (argc != 2) { cout << "Invalid arguments number." << endl; cout << "Usage:\n\tflipbyte.exe <byte>" << endl; return 1; } istringstream inputData = istringstream(argv[1]); int inputNumber; if (!(inputData >> inputNumber) || (inputNumber < MIN_INPUT_VALUE) || (inputNumber > MAX_INPUT_VALUE)) { cout << "Your input data \"" << argv[1] << "\" is invalid." << endl; cout << "It must be 1-byte number from 0 to 255." << endl; return 1; } unsigned char numberToRevers = static_cast<unsigned char>(inputNumber); unsigned char reversedNumber = ReversBits(numberToRevers); cout << static_cast<unsigned short>(reversedNumber) << endl; return 0; } unsigned char ReversBits(unsigned char num) { const int bitsCount = sizeof(num) * BITS_IN_BYTE; const unsigned char eraser = 1; unsigned char result = 0; for (int i = 0; i < bitsCount; i++) { result |= ((num >> i) & eraser) << (bitsCount - i - 1); } return result; }
true
9784c40d7e63cc0ac93f4307091cdbeed1432291
C++
Stiffstream/sobjectizer
/doxygen/dox/so_5/so_5_5_3__subscr_storage_selection.dox
UTF-8
4,515
3.296875
3
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/*! \page so_5_5_3__subscr_storage_selection so-5.5.3: Subscription storage type selection There are some places in the SObjectizer where there is no "one right implementation" which will give the best possible results for all scenarios. Version 5.5.3 introduces an approach for tuning agents and underlying data structures/algorithm for user-specific scenarios. The first step is support for various type of *subscription storages*. Subscription storage is a data structure for storing and manipulating information about an agent's subscriptions. Every agent has its own private subscription storage. When an agent creates subscription like: \code void some_agent::so_define_agent() { so_default_state().event( &some_agent::evt_do_some_work ); } \endcode this subscription is stored in the agent's subscription storage. When agent receives a messages the handler for that message will be searched in this storage. The problem is selection of the appropriate data structure for that storage. When an agent uses small amount of subscription (like one or two subscriptions) then a very simple vector-based implementation will be the most efficient. When an agent uses several dozens subscriptions then vector-based implementation becomes inefficient and map-based storage will be more appropriate. But when an agent uses several hundreds or even thousands of subscriptions then hash-table-based implementation will be more efficient. Since v.5.5.3 a user can specify which subscription storage should be used for an agent. Do do so it is necessary to specify tuning_options-object to constructor of base class: \code using namespace so_5::rt; class my_agent : public agent_t { public : my_agent( environment_t & env ) : agent_t( env, tuning_options() ) {} ... }; \endcode The new static method so_5::rt::agent_t::tuning_options() creates an so_5::rt::agent_tuning_options_t object with default values. This values can be changed by calling so_5::rt::agent_tuning_options_t's methods. For example to change type of subscription storage it is necessary to call so_5::rt::agent_tuning_options_t::subscription_storage_factory() method: \code using namespace so_5::rt; class my_agent : public agent_t { public : my_agent( environment_t & env ) : agent_t( env, tuning_options().subscription_storage_factory( vector_based_subscription_storage(4) ) ) {} ... }; \endcode There are several implementations of subscription storage: - vector-based implementation. Uses std::vector and simple linear search. Very efficient on small numbers of subscriptions. Function so_5::rt::vector_based_subscription_storage_factory() creates factory for this type of the storage; - map-based implementation. Uses std::map and is very efficient when count of subscriptions is greater than 10-20 and less than 100-200. Function so_5::rt::map_based_subscription_storage_factory() creates factory for this type of the storage; - hash-table-based implementation. Uses std::unordered_map and is most efficient when count of subscription is exceed several hundreds. Function so_5::rt::hash_table_based_subscription_storage_factory() creates factory for this type of the storage; - adaptive storage. Uses two storage objects. The first one is used when the count of subscriptions is small. The second is used when the count of subscription exceeds some threshold. This storage dynamically changes implementations -- switches from small storage to the big one when new subscriptions are created and switches back when subscriptions are erased. By default adaptive storage uses vector-based storage as small one, and map-based storage as big one. But this can be changed at the moment of storage creation. The adaptive storage is created by so_5::rt::adaptive_subscription_storage_factory() functions. By default all agents use adaptive subscription storage. It means that if an agent creates very few subscriptions it will use very small and very fast vector-based storage. But if count of subscription grows then agent will switch to more expensive but more appropriate for big amount of subscriptions map-based storage. But if user knows what count of subscriptions an actor will use then an appropriate storage can be created once and never switches from one implementation to another. \note The type of subscription storage can be specified only once during agent creation. After creation the subscription storage cannot be changed. */ // vim:ft=cpp
true
7373a976ceff42e79c6f216589cf8bc259947b82
C++
Daniil-Osokin/projects
/unn/ConnectedComponentsComputation/ConnectedComponentsComputation/separated_set_collection.hpp
UTF-8
327
2.515625
3
[]
no_license
#ifndef __SEPARATED_SET_COLLECTION_HPP__ #define __SEPARATED_SET_COLLECTION_HPP__ class SeparatedSetCollection { public: SeparatedSetCollection(int size); ~SeparatedSetCollection(); void combine(int x, int y); int find(int x) const; private: void create(int x); int* nodes; int* ranks; }; #endif
true
c650ec29e0ea40cad93fd8e468b5a753c703810c
C++
sunjiyuansjy/MyProject_httpweb
/MyHttpWeb1.4/ThreadPool.hpp
UTF-8
2,417
3.40625
3
[]
no_license
#ifndef __THREADPOOL_HPP__ #define __THREADPOOL_HPP__ #include <iostream> #include <queue> #include <pthread.h> typedef void (*handler_t)(int); class Task{ private: int sock; handler_t handler; public: Task(int sock_,handler_t handler_):sock(sock_),handler(handler_) {} void Run() { handler(sock); } ~Task() {} }; class ThreadPool{ private: int num; std::queue<Task> task_queue; int idle_num; pthread_mutex_t lock; pthread_cond_t cond; public: ThreadPool(int num_):num(num_),idle_num(0) { pthread_mutex_init(&lock,NULL); pthread_cond_init(&cond,NULL); } void InitThreadPool() { pthread_t tid; for(auto i=0;i<num;i++) { pthread_create(&tid,NULL,ThreadRoutine,(void*)this); } } bool IsTaskQueueEmpty() { return task_queue.size() == 0?true:false; } void LockQueue() { pthread_mutex_lock(&lock); } void UnLockQueue() { pthread_mutex_unlock(&lock); } void Idle() { idle_num++; pthread_cond_wait(&cond,&lock); idle_num--; } void Wakeup() { pthread_cond_signal(&cond); } Task PopTask() { Task t=task_queue.front(); task_queue.pop(); return t; } void PushTask(Task &t) { LockQueue(); task_queue.push(t); UnLockQueue(); Wakeup(); } static void *ThreadRoutine(void *arg) { pthread_detach(pthread_self()); ThreadPool *tp=(ThreadPool*) arg; for(;;){ tp->LockQueue(); if(tp->IsTaskQueueEmpty()){ tp->Idle(); } Task t=tp->PopTask(); tp->UnLockQueue(); std::cout<<"task is hander by:"<<pthread_self()<<std::endl; t.Run(); } } ~ThreadPool() { pthread_mutex_destroy(&lock); pthread_cond_destroy(&cond); } }; //单例模式 class singleton{ private: static ThreadPool *p; static pthread_mutex_t lock; public: static ThreadPool *GetInsert() { if(NULL==p) {pthread_mutex_lock(&lock); if(NULL==p){ p = new ThreadPool(5); p->InitThreadPool(); } pthread_mutex_unlock(&lock); } return p; } }; ThreadPool *singleton::p = NULL; pthread_mutex_t singleton::lock=PTHREAD_MUTEX_INITIALIZER; #endif
true
01787d8a6b146bca0ff6fc6dfa68d41885c1fa72
C++
AugustoCalaca/competitive-programming
/spoj/yodaness.cpp
UTF-8
1,282
2.515625
3
[]
no_license
#include <iostream> #include <algorithm> #include <cmath> #include <vector> #include <map> #define f first #define s second #define MAX 30010 #define pb push_back #define FAST ios::sync_with_stdio(false); cin.tie(0); cout.tie(0) using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<string, int> psi; int arr[MAX], bit[MAX]; bool comp(psi& a, string b) { return a.f < b; } void update(int idx, int val, int n) { for(; idx <= n; idx += idx & -idx) bit[idx] += val; } int query(int idx) { int sum = 0; for(; idx > 0; idx -= idx & -idx) sum += bit[idx]; return sum; } ll invcount(int n) { ll inv = 0; for(int i = n - 1; i >= 0; i--) { inv += query(arr[i] - 1); update(arr[i], 1, n); } return inv; } int main() { FAST; string str; int t, n; for(cin >> t; t--; ) { cin >> n; vector<psi> vs, temp; for(int i = 0; i < n; i++) { cin >> str; vs.pb({ str, i + 1}); } for(int i = 0; i < n; i++) { cin >> str; temp.pb({ str, i + 1}); } sort(temp.begin(), temp.end()); for(int i = 0; i < n; i++) { arr[i] = lower_bound(temp.begin(), temp.end(), vs[i].f, comp)->s; bit[i + 1] = 0; } cout << invcount(n) << "\n"; } return 0; }
true
25009f8ea64f46a7aa72d866f360347e34fd69f6
C++
georgerapeanu/c-sources
/acm2021-2/simulari/16oct/D.cpp
UTF-8
646
2.515625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int gcd(int a,int b){ if(b == 0){ return (a < 0 ? -a:a); } return gcd(b,a % b); } int main(){ int t; int n; scanf("%d",&t); while(t--){ scanf("%d",&n); vector<pair<int,int> > v(n); map<pair<int,int>,int > stuff; long long ans = 0; for(auto &it:v){ int x,y,u,v; scanf("%d %d %d %d",&x,&y,&u,&v); it = make_pair(u - x,v - y); int _g = gcd(it.first,it.second); it.first /= _g; it.second /= _g; stuff[it]++; ans += stuff[make_pair(-it.first,-it.second)]; } printf("%lld\n",ans); } return 0; }
true
2b8c9e93232dd2dd416407dc70bfce4bd6162761
C++
rajnishgeek/DSandAlgorithmPracticeSolution
/Binary Tree/binary tree tilt.cpp
UTF-8
461
3.265625
3
[]
no_license
void solve(TreeNode* root, int &res) { if (root == NULL) return; solve(root->left, res); solve(root->right, res); if (root->left == NULL && root->right == NULL) return; int l = 0, r = 0; if (root->left) l = root->left->val; if (root->right) r = root->right->val; res += abs(l - r); root->val += l + r; } int findTilt(TreeNode* root) { int res = 0; solve(root, res); return res; }
true
a66932df392590ae28c322f74a99e999458d53b5
C++
lulufa390/ElfGE
/GameEngine/UI/Font/FontFace.cpp
UTF-8
3,378
2.84375
3
[ "MIT" ]
permissive
// // Created by 张程易 on 16/11/2017. // #include "FontFace.h" GLuint FontFace::VAO, FontFace::VBO; bool FontFace::isInit = false; void FontFace::renderText(const std::string &text) { glActiveTexture(GL_TEXTURE0); glBindVertexArray(VAO); float x = 0; std::string::const_iterator c; for (c = text.begin(); c != text.end(); c++) { Character ch = Characters[*c]; GLfloat xpos = x + ch.bearing.x; GLfloat ypos = -(ch.size.y - ch.bearing.y); GLfloat w = ch.size.x; GLfloat h = ch.size.y; // 对每个字符更新VBO GLfloat vertices[6][4] = { {xpos, ypos + h, 0.0, 0.0}, {xpos, ypos, 0.0, 1.0}, {xpos + w, ypos, 1.0, 1.0}, {xpos, ypos + h, 0.0, 0.0}, {xpos + w, ypos, 1.0, 1.0}, {xpos + w, ypos + h, 1.0, 0.0} }; glBindTexture(GL_TEXTURE_2D, ch.textureID); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices); glBindBuffer(GL_ARRAY_BUFFER, 0); glDrawArrays(GL_TRIANGLES, 0, 6); x += (ch.advance >> 6); } glBindVertexArray(0); glBindTexture(GL_TEXTURE_2D, 0); } FontFace::FontFace(FT_Library ft, const std::string &path, int fontSize) { this->fontSize = fontSize; if (FT_New_Face(ft, path.c_str(), 0, &face)) std::cout << "ERROR::FREETYPE: Failed to load font" << std::endl; FT_Set_Pixel_Sizes(face, 0, 48); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); for (GLubyte c = 0; c < 128; c++) { if (FT_Load_Char(face, c, FT_LOAD_RENDER)) { std::cout << "ERROR::FREETYTPE: Failed to load Glyph" << std::endl; continue; } GLuint texture; glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glTexImage2D( GL_TEXTURE_2D, 0, GL_RED, face->glyph->bitmap.width, face->glyph->bitmap.rows, 0, GL_RED, GL_UNSIGNED_BYTE, face->glyph->bitmap.buffer ); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); Character character = { texture, glm::ivec2(face->glyph->bitmap.width, face->glyph->bitmap.rows), glm::ivec2(face->glyph->bitmap_left, face->glyph->bitmap_top), (GLuint) face->glyph->advance.x }; Characters.emplace(c, character); } if (!isInit) { isInit = true; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 6 * 4, NULL, GL_DYNAMIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), 0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } } int FontFace::getFontSize() const { return fontSize; }
true
1d0f841011c8451d26ebc60d64bd2e096774c3ee
C++
Hong-SY/JellySimulation
/JellyDemo/Source/JellyDemo/JellyLogger.h
UHC
1,583
2.71875
3
[]
no_license
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include <string> #include <iostream> #include <list> #include <fstream> #include "JellyActor.h" #include "CoreMinimal.h" /** * */ #define BUFFER_NUMBER 2 #define BUFFER_SIZE 1000 // Ŀ ٸ Ϸ ̵ // ൿ ID enumerate ü enum Behaviors { MOVE, DIE, BORN, STAY }; struct Behav{ uint8 x; //xǥ uint8 y; //yǥ uint8 jellyType; // (1: 1, 2: 2 ...) uint8 behaviorId; // ൿ ȣ( 1. ̵, 2. ) uint32 jellyId; // ش id ȣ }; class JELLYDEMO_API JellyLogger { private: Behav fileLogsBuffer[BUFFER_NUMBER][BUFFER_SIZE]; // α 迭 int usingBuffer; // α ȣ int bufferIndex; // α ε int containerNumber; // ȣ std::ofstream logfstream; // public: JellyLogger(); JellyLogger(int containerNumber); /* * ܺο α Ͻ ȣ Լ. * usingBuffer° ۿ ϳ ϰ BUFFER_SIZE Ѿ writeLogToFile Լ ȣϰ * usingBuffer ٲ۴. */ void fileLog(uint8 x, uint8 y, uint8 behaviorId, AJellyActor Jelly); /* * α ü б ڿ ȯѴ. */ std::string translateFileLog(Behav log); /* * α ۸ Ͽ . */ static void writeLogToFile(int bufferNumber, JellyLogger* logger, int size); ~JellyLogger(); };
true
f09d7088bdc4f53e4f218c07fde9551a31796d27
C++
CodevilWang/code_snippet
/C++/stdlib/test_alignas.cpp
UTF-8
5,858
2.953125
3
[]
no_license
// Copyright 2019 All Rights Reserved. // some code port from facebook Folly #include <iostream> #include <vector> #include <assert.h> struct Foo { alignas(0x40) float array[1]; Foo() { std::cout << "ctor " << array << "\n"; } }; template<typename T> class Poo { public: template<typename U, std::enable_if_t<!std::is_same<T, U>::value, int> = 0> size_t operator=(Poo<U>& value) { _value = value._value; return 0; } int _value; }; template<typename T> struct lift_void_to_char { using type = T; }; template<> struct lift_void_to_char<void> { using type = char; }; inline void* aligned_malloc(size_t size, size_t align) { // use posix_memalign, but mimic the behaviour of memalign void* ptr = nullptr; int rc = posix_memalign(&ptr, align, size); return rc == 0 ? (errno = 0, ptr) : (errno = rc, nullptr); } inline void aligned_free(void* aligned_ptr) { free(aligned_ptr); } template<uint32_t aligned_size> class DefaultAlign { private: using Self = DefaultAlign; std::size_t align_; public: explicit DefaultAlign() noexcept : align_(aligned_size) { assert(!(align_ < sizeof(void*)) && bool("bad align: too small")); assert(!(align_ & (align_ - 1)) && bool("bad align: not power-of-two")); } std::size_t operator()(std::size_t align) const noexcept { return align_ < align ? align : align_; } friend bool operator==(Self const& a, Self const& b) noexcept { return a.align_ == b.align_; } friend bool operator!=(Self const& a, Self const& b) noexcept { return a.align_ != b.align_; } }; template<uint32_t asize> class UintWrapper { public: constexpr static uint32_t i_value = asize; }; // template <typename T, typename Align = DefaultAlign<64>> template <typename T, typename Align = UintWrapper<64>> class AlignedSysAllocator { private: using Self = AlignedSysAllocator<T, Align>; template <typename, typename> friend class AlignedSysAllocator; // constexpr Align const& align() const { // return *this; // } public: static_assert(std::is_nothrow_copy_constructible<Align>::value, ""); // static_assert(is_nothrow_invocable_r_v<std::size_t, Align, std::size_t>, ""); using value_type = T; using propagate_on_container_copy_assignment = std::true_type; using propagate_on_container_move_assignment = std::true_type; using propagate_on_container_swap = std::true_type; // using Align::Align; // TODO: remove this ctor, which is is no longer required as of under gcc7 // template < // typename S = Align, // std::enable_if_t<std::is_default_constructible<S>::value, int> = 0> // constexpr AlignedSysAllocator() noexcept(noexcept(Align())) : Align() {} constexpr AlignedSysAllocator() = default; constexpr AlignedSysAllocator(AlignedSysAllocator const&) = default; // template <typename U, std::enable_if_t<!std::is_same<U, T>::value, int> = 0> // constexpr AlignedSysAllocator( // AlignedSysAllocator<U, Align> const& other) noexcept // : Align(other.align()) {} template <typename U, std::enable_if_t<!std::is_same<U, T>::value, int> = 0> constexpr AlignedSysAllocator( AlignedSysAllocator<U, Align> const& other) noexcept {} T* allocate(size_t count) { using lifted = typename lift_void_to_char<T>::type; // auto const a = align()(alignof(lifted)); auto const a = Align::i_value; auto const p = aligned_malloc(sizeof(lifted) * count, a); if (!p) { if ((errno != ENOMEM)) { std::terminate(); } throw std::bad_alloc(); } return static_cast<T*>(p); } void deallocate(T* p, size_t /* count */) { aligned_free(p); } }; // template<typename T, uint32_t aligned_size = 64> // class AlignedSysAllocator { // private: // using Self = AlignedSysAllocator<T, aligned_size>; // public: // using value_type = T; // // template <typename, typename> // // friend class AlignedSysAllocator; // using propagate_on_container_copy_assignment = std::true_type; // using propagate_on_container_move_assignment = std::true_type; // using propagate_on_container_swap = std::true_type; // // constexpr AlignedSysAllocator() noexcept {} // constexpr AlignedSysAllocator(AlignedSysAllocator const&) = default; // // // template <typename U, std::enable_if_t<!std::is_same<U, T>::value, int> = 0> // // constexpr AlignedSysAllocator( // // AlignedSysAllocator<U, aligned_size> const& other) noexcept // // {} // const size_t align(const uint32_t& obj_align) { // return std::max(aligned_size, obj_align); // } // // T* allocate(size_t count) { // using lifted = typename lift_void_to_char<T>::type; // auto const a = align(alignof(lifted)); // auto const p = aligned_malloc(sizeof(lifted) * count, a); // if (!p) { // if ((errno != ENOMEM)) { // std::terminate(); // } // throw std::bad_alloc(); // } // return static_cast<T*>(p); // } // void deallocate(T* p, size_t) { // aligned_free(p); // } // }; int main() { Foo f[3]; printf("%u\n", alignof(f[0])); printf("%u\n", alignof(f[1])); printf("%u\n", alignof(f[2])); std::vector<Foo> vec(2); printf("%u\t%p\n", alignof(vec[0]), &(vec[0])); printf("%u\t%p\n", alignof(vec[1]), &(vec[1])); Poo<int> pi; Poo<int> pd; pd._value = 1002; pi = pd; printf("%d\t%d\n", pd._value, pi._value); printf("%d\n", sizeof(lift_void_to_char<void>::type)); std::vector<Foo, AlignedSysAllocator<Foo>> data(3); // AlignedSysAllocator<Foo> alloc; // Foo* fa = alloc.allocate(3); // printf("%u\t%p\n", alignof(*fa), fa); // printf("%u\t%p\n", alignof(fa[1]), fa + 1); printf("%u\t%p\n", alignof(data[0]), &(data[0])); printf("%u\t%p\n", alignof(data[1]), &(data[1])); return 0; } /* vim: set expandtab ts=2 sw=2 sts=2 tw=80: */
true
5f040838742c1b1560b7f6ecdae4b03f0c008585
C++
univmajalengka/191410018
/Tugas Struktur Data/Multidimensi.cpp
UTF-8
419
2.765625
3
[]
no_license
#include<iostream> using namespace std; int main () { int p[4][4][2] = { {2,3,4,5}, {7,6,9,8}, {1,10} }; int q[4][4][2] = { {5,4,3,2}, {8,9,6,7}, {10,1} }; int r[4][4][2]; for(int i=0;i<4;i++){ for(int j=0;j<4;j++) for(int k=0;k<2;k++){ r[i][j][k]=p[i][j][k]+q[i][j][k]; } } for(int i=0;i<4;i++){ for(int j=0;j<4;j++) for(int k=0;k<2;k++){ cout << r[i][j][k]<< " "; } cout << endl; } }
true
953164eebc7b2f8f0371e7f81d662c8ad34251b9
C++
onedata/helpers
/src/glusterfsHelper.h
UTF-8
10,192
2.65625
3
[ "MIT" ]
permissive
/** * @file glusterfsHelper.h * @author Bartek Kryza * @copyright (C) 2017 ACK CYFRONET AGH * @copyright This software is released under the MIT license cited in * 'LICENSE.txt' */ #ifndef HELPERS_GLUSTERFS_HELPER_H #define HELPERS_GLUSTERFS_HELPER_H #include "helpers/storageHelper.h" #include <folly/executors/IOExecutor.h> #include <glusterfs/api/glfs-handles.h> #include <glusterfs/api/glfs.h> #include <tuple> namespace boost { namespace filesystem { /** * Return a child path suffix which is relative to parent path, * for example: * * makeRelative("/DIR1/DIR2", "DIR1/DIR2/DIR3/file.txt") -> "DIR3/file.txt" * * @param parent Parent path * @param child Child path * * @return Relative Subpath of the child with respect to parent directory */ path makeRelative(path parent, path child); } // namespace filesystem } // namespace boost namespace one { namespace helpers { class GlusterFSHelper; /** * Gluster xlator options enable customizing connection to a particular * volume on the level of specific GlusterFS translators (a.k.a. plugins) * * Here the pair represents: * (TRANSLATOR_OPTION_NAME, OPTION_VALUE) */ using GlusterFSXlatorOptions = folly::fbvector<std::pair<folly::fbstring, folly::fbstring>>; /** * This class holds a GlusterFS connection object which should be maintained * between helpers creation and destruction. */ struct GlusterFSConnection { std::shared_ptr<glfs_t> glfsCtx{nullptr}; bool connected = false; static folly::fbstring generateCtxId( folly::fbstring hostname, int port, folly::fbstring volume) { return hostname + "::" + folly::fbstring(std::to_string(port)) + "::" + volume; } }; /** * The @c FileHandle implementation for GlusterFS storage helper. */ class GlusterFSFileHandle : public FileHandle, public std::enable_shared_from_this<GlusterFSFileHandle> { public: /** * Constructor. * @param fileId Path to the file or directory. * @param helper A pointer to the helper that created the handle. * @param glfsFd A reference to @c glfs_fd_t struct for GlusterFS direct * access to a file descriptor. */ GlusterFSFileHandle(const folly::fbstring &fileId, std::shared_ptr<GlusterFSHelper> helper, std::shared_ptr<glfs_fd_t> glfsFd, uid_t uid, gid_t gid); ~GlusterFSFileHandle(); folly::Future<folly::IOBufQueue> read( const off_t offset, const std::size_t size) override; folly::Future<std::size_t> write(const off_t offset, folly::IOBufQueue buf, WriteCallback &&writeCb) override; folly::Future<folly::Unit> release() override; folly::Future<folly::Unit> flush() override; folly::Future<folly::Unit> fsync(bool isDataSync) override; const Timeout &timeout() override; private: std::shared_ptr<glfs_fd_t> m_glfsFd; std::atomic_bool m_needsRelease{true}; const uid_t m_uid; const gid_t m_gid; }; /** * The GlusterFSHelper class provides access to Gluster volume * directly using libgfapi library. */ class GlusterFSHelper : public StorageHelper, public std::enable_shared_from_this<GlusterFSHelper> { public: /** * Constructor. * @param mountPoint Root folder within the volume, all operations on the * volume will be relative to it. * @param uid The uid of the user on whose behalf the storage access * operations are performed. * @param gid The gid of the user on whose behalf the storage access * operations are performed. * @param hostname The GlusterFS volfile server hostname. * @param port The GlusterFS volfile server port. * @param volume The GlusterFS volume name. * @param transport The GlusterFS volfile server transport, possible values * are: "socket", "tcp", "rdma". * @param xlatorOptions Custom xlator options which should be overwritten * for this connection in the format: * TRANSLATOR1OPTION1=VALUE1;TRANSLATOR2OPTION2=OPTION2;... * @param executor Executor that will drive the helper's async operations. * @param timeout Operation timeout. */ GlusterFSHelper(const boost::filesystem::path &mountPoint, const uid_t uid, const gid_t gid, folly::fbstring hostname, int port, folly::fbstring volume, folly::fbstring transport, folly::fbstring xlatorOptions, std::shared_ptr<folly::Executor> executor, Timeout timeout = constants::ASYNC_OPS_TIMEOUT, ExecutionContext executionContext = ExecutionContext::ONEPROVIDER); virtual ~GlusterFSHelper() = default; folly::fbstring name() const override { return GLUSTERFS_HELPER_NAME; }; folly::Future<struct stat> getattr(const folly::fbstring &fileId) override; folly::Future<folly::Unit> access( const folly::fbstring &fileId, const int mask) override; folly::Future<folly::fbvector<folly::fbstring>> readdir( const folly::fbstring &fileId, off_t offset, size_t count) override; folly::Future<folly::fbstring> readlink( const folly::fbstring &fileId) override; folly::Future<folly::Unit> mknod(const folly::fbstring &fileId, const mode_t unmaskedMode, const FlagsSet &flags, const dev_t rdev) override; folly::Future<folly::Unit> mkdir( const folly::fbstring &fileId, const mode_t mode) override; folly::Future<folly::Unit> unlink( const folly::fbstring &fileId, const size_t currentSize) override; folly::Future<folly::Unit> rmdir(const folly::fbstring &fileId) override; folly::Future<folly::Unit> symlink( const folly::fbstring &from, const folly::fbstring &to) override; folly::Future<folly::Unit> rename( const folly::fbstring &from, const folly::fbstring &to) override; folly::Future<folly::Unit> link( const folly::fbstring &from, const folly::fbstring &to) override; folly::Future<folly::Unit> chmod( const folly::fbstring &fileId, const mode_t mode) override; folly::Future<folly::Unit> chown(const folly::fbstring &fileId, const uid_t uid, const gid_t gid) override; folly::Future<folly::Unit> truncate(const folly::fbstring &fileId, const off_t size, const size_t currentSize) override; folly::Future<FileHandlePtr> open(const folly::fbstring &fileId, const int flags, const Params &openParams) override; folly::Future<folly::fbstring> getxattr( const folly::fbstring &fileId, const folly::fbstring &name) override; folly::Future<folly::Unit> setxattr(const folly::fbstring &fileId, const folly::fbstring &name, const folly::fbstring &value, bool create, bool replace) override; folly::Future<folly::Unit> removexattr( const folly::fbstring &fileId, const folly::fbstring &name) override; folly::Future<folly::fbvector<folly::fbstring>> listxattr( const folly::fbstring &fileId) override; const Timeout &timeout() override { return m_timeout; } std::shared_ptr<folly::Executor> executor() override { return m_executor; }; folly::Future<folly::Unit> connect(); /** * Parse custom GlusterFS xlator options for the volume, which * the helper should use to connect to. * * The options should be in the form: * translator1option1=value1;translator2option2=value2;... * * If the 'options' argument does not conform to the pattern, * runtime_error is thrown. * * @param options The string with encoded xlator options * @return Vector of pairs of xlator options */ static GlusterFSXlatorOptions parseXlatorOptions( const folly::fbstring &options); boost::filesystem::path root(const folly::fbstring &fileId) const; boost::filesystem::path relative(const folly::fbstring &fileId) const; private: boost::filesystem::path m_mountPoint; uid_t m_uid; gid_t m_gid; folly::fbstring m_hostname; int m_port; folly::fbstring m_volume; folly::fbstring m_transport; folly::fbstring m_xlatorOptions; std::shared_ptr<folly::Executor> m_executor; Timeout m_timeout; std::shared_ptr<glfs_t> m_glfsCtx; }; /** * An implementation of @c StorageHelperFactory for GlusterFS storage helper. */ class GlusterFSHelperFactory : public StorageHelperFactory { public: /** * Constructor. * @param executor executor that will be used for some async operations. */ GlusterFSHelperFactory(std::shared_ptr<folly::IOExecutor> executor) : m_executor{std::move(executor)} { } virtual folly::fbstring name() const override { return GLUSTERFS_HELPER_NAME; } std::vector<folly::fbstring> overridableParams() const override { return {"hostname", "port", "transport", "timeout"}; }; std::shared_ptr<StorageHelper> createStorageHelper( const Params &parameters, ExecutionContext executionContext) override { const auto &mountPoint = getParam<std::string>(parameters, "mountPoint", ""); const auto &uid = getParam<int>(parameters, "uid", -1); const auto &gid = getParam<int>(parameters, "gid", -1); const auto &hostname = getParam<std::string>(parameters, "hostname"); const auto &port = getParam<int>(parameters, "port", 24007); const auto &volume = getParam<std::string>(parameters, "volume"); const auto &transport = getParam<std::string>(parameters, "transport", "tcp"); const auto &xlatorOptions = getParam<std::string>(parameters, "xlatorOptions", ""); Timeout timeout{getParam<std::size_t>( parameters, "timeout", constants::ASYNC_OPS_TIMEOUT.count())}; return std::make_shared<GlusterFSHelper>(mountPoint, uid, gid, hostname, port, volume, transport, xlatorOptions, m_executor, std::move(timeout), executionContext); } private: std::shared_ptr<folly::IOExecutor> m_executor; }; } // namespace helpers } // namespace one #endif // HELPERS_GLUSTERFS_HELPER_H
true
50064951c4aff1e29c11e232f6d121ba1a406a1a
C++
utsavmajhi/CP
/Algorithms/q1.cpp
UTF-8
540
3.140625
3
[]
no_license
#include <iostream> #include <string> using namespace std; int main(int argc, char *argv[]) { // このコードは標準入力と標準出力を用いたサンプルコードです。 // このコードは好きなように編集・削除してもらって構いません。 // --- // This is a sample code to use stdin and stdout. // Edit and remove this code as you like. string line; int index = 1; while (!cin.eof()) { getline(cin, line); cout << "line[" << index++ << "]:" << line << "\n"; } return 0; }
true
60e143096ab9255b8f5c11d153114bb68560413f
C++
kirwinia/ares-emu-v121
/nall/encode/huffman.hpp
UTF-8
2,355
2.8125
3
[ "ISC" ]
permissive
#pragma once namespace nall::Encode { inline auto Huffman(array_view<u8> input) -> vector<u8> { vector<u8> output; for(u32 byte : range(8)) output.append(input.size() >> byte * 8); struct Node { u32 frequency = 0; u32 parent = 0; u32 lhs = 0; u32 rhs = 0; }; array<Node[512]> nodes; for(u32 offset : range(input.size())) nodes[input[offset]].frequency++; u32 count = 0; for(u32 offset : range(511)) { if(nodes[offset].frequency) count++; else nodes[offset].parent = 511; } auto minimum = [&] { u32 frequency = ~0, minimum = 511; for(u32 index : range(511)) { if(!nodes[index].parent && nodes[index].frequency && nodes[index].frequency < frequency) { frequency = nodes[index].frequency; minimum = index; } } return minimum; }; //group the least two frequently used nodes until only one node remains u32 index = 256; for(u32 remaining = max(2, count); remaining >= 2; remaining--) { u32 lhs = minimum(); nodes[lhs].parent = index; u32 rhs = minimum(); nodes[rhs].parent = index; if(remaining == 2) index = nodes[lhs].parent = nodes[rhs].parent = 511; nodes[index].lhs = lhs; nodes[index].rhs = rhs; nodes[index].parent = 0; nodes[index].frequency = nodes[lhs].frequency + nodes[rhs].frequency; index++; } u32 byte = 0, bits = 0; auto write = [&](bool bit) { byte = byte << 1 | bit; if(++bits == 8) output.append(byte), bits = 0; }; //only the upper half of the table is needed for decompression //the first 256 nodes are always treated as leaf nodes for(u32 offset : range(256)) { for(u32 index : reverse(range(9))) write(nodes[256 + offset].lhs >> index & 1); for(u32 index : reverse(range(9))) write(nodes[256 + offset].rhs >> index & 1); } for(u32 byte : input) { u32 node = byte, length = 0; u256 sequence = 0; //traversing the array produces the bitstream in reverse order do { u32 parent = nodes[node].parent; bool bit = nodes[nodes[node].parent].rhs == node; sequence = sequence << 1 | bit; length++; node = parent; } while(node != 511); //output the generated bits in the correct order for(u32 index : range(length)) { write(sequence >> index & 1); } } while(bits) write(0); return output; } }
true
3039f37173aabae371077ae476ac9990338e03e3
C++
dipal/simple-csv-reader
/csv_reader_test.cpp
UTF-8
1,744
3.203125
3
[]
no_license
#include "csv_reader.hpp" #define Log(X) std::cout << X << std::endl; template<typename T> void printVector(std::vector<T> v) { for (int i=0; i<v.size(); i++) { if (i) { std::cout << ", "; } std::cout << v[i]; } std::cout << std::endl; } template<typename T> void printVector2d(std::vector<T> v) { for (int i=0; i<v.size(); i++) { printVector(v[i]); } std::cout << std::endl; } int main() { std::string csv_file = "b.csv"; char delimeter = ','; bool isHeader = true; Log(""); Log("dcsv::Reader"); Log("csv_file: " << csv_file << " delimeter: '" << delimeter << "' isHeader: " << isHeader); Log(""); dcsv::Reader csvReader(csv_file, delimeter, isHeader); csvReader.readAll(); Log("Reader::toString()") Log(csvReader.toString()); Log("Reader::getAsArray<int>()"); printVector2d(csvReader.getAsArray<int>()); Log("Reader::getAsArray<double>()"); printVector2d(csvReader.getAsArray<double>()); Log("Reader::getAsArray<std::string>()"); printVector2d(csvReader.getAsArray<std::string>()); Log("Reader::getAsArray<long>()"); printVector2d(csvReader.getAsArray<long>()); Log("Reader::getHeaders()"); printVector(csvReader.getHeaders()); Log("") Log("Reader::getDataByRowIndex<int>(1)"); printVector(csvReader.getDataByRowIndex<int>(1)); Log("") Log("Reader::getDataByColumnIndex<int>(1)"); printVector(csvReader.getDataByColumnIndex<int>(1)); Log("") Log("Reader::getDataByColumnName<int>(\"c\")"); printVector(csvReader.getDataByColumnName<int>("c")); Log("") // auto data = csvReader.getAsArray(); // for (int i=0; i<data.size(); i++) { // for (int j=0; j<data[i].size(); j++) { // std::cout << data[i][j] << " "; // } // std::cout << std::endl; // } return 0; }
true
c6157f9a6dc1b3f0ce9623e0eb3cd09bb937fd7c
C++
XA-IT/JianZhi_Offer
/WZT/before/loopInLinkedlist.cpp
UTF-8
1,704
3.78125
4
[]
no_license
// 链表中环的入口结点 // 题目描述 // 给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。 /* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } }; */ class Solution { public: ListNode* whetherlooped(ListNode * pHead){ if(pHead == nullptr) return nullptr; ListNode* pNext = pHead->next; ListNode* p1Node = pHead, * p2Node = pHead; while(p1Node->next != nullptr) { //if(p1Node->next != nullptr) p1Node = p1Node->next; if(p1Node->next != nullptr) p1Node = p1Node->next; p2Node = p2Node->next; if(p1Node == p2Node){ return p1Node; } } return nullptr; } ListNode* EntryNodeOfLoop(ListNode* pHead) { ListNode* p1Node = pHead, *p2Node = pHead; ListNode* meetnode = nullptr; meetnode = whetherlooped(pHead); if(meetnode == nullptr) return nullptr; p1Node = meetnode->next; p2Node = meetnode; int numinLoop = 1; while(p2Node != p1Node) { p2Node = p2Node->next; p1Node = p1Node->next->next; numinLoop++; } p1Node = pHead; p2Node = pHead; for(int i=0; i<numinLoop; i++){ p2Node = p2Node->next; } while(p1Node != p2Node){ p1Node = p1Node->next; p2Node = p2Node->next; } return p1Node; } };
true
d160fbd2b184fe3c5497b44bbd185b1b2f12c3e8
C++
sxin-h/PlainRenderer
/Plain/src/Runtime/Rendering/Backend/VulkanRenderPass.cpp
UTF-8
793
2.53125
3
[ "MIT" ]
permissive
#include "pch.h" #include "VulkanRenderPass.h" VkRenderPassBeginInfo createRenderPassBeginInfo(const uint32_t width, const uint32_t height, const VkRenderPass pass, const VkFramebuffer framebuffer, const std::vector<VkClearValue>& clearValues) { VkExtent2D extent = {}; extent.width = width; extent.height = height; VkRect2D rect = {}; rect.extent = extent; rect.offset = { 0, 0 }; VkRenderPassBeginInfo beginInfo = {}; beginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; beginInfo.pNext = nullptr; beginInfo.renderPass = pass; beginInfo.framebuffer = framebuffer; beginInfo.clearValueCount = (uint32_t)clearValues.size(); beginInfo.pClearValues = clearValues.data(); beginInfo.renderArea = rect; return beginInfo; }
true
04a75f2845382c50ac2aa4bae7439880f4f14c78
C++
chneau/oops
/Google/oneforth.cpp
UTF-8
1,644
3
3
[]
no_license
/************************************************************************* > File Name: oneforth.cpp > Author: Louis1992 > Mail: zhenchaogan@gmail.com > Blog: http://gzc.github.io > Link: http://www.1point3acres.com/bbs/forum.php?mod=viewthread&tid=145654&extra=page%3D1%26filter%3Dauthor%26orderby%3Ddateline%26sortid%3D311%26sortid%3D311%26orderby%3Ddateline > Description: Given a sorted array,find occuring time more than n/4 times popular number. > Created Time: Tue Oct 27 18:22:09 2015 ************************************************************************/ #include<iostream> #include<cstdio> #include<list> #include<vector> #include<unordered_map> #include<climits> #include<unordered_set> #include<map> #include<set> #include<stack> #include<queue> using namespace std; vector<int> findOneForth(vector<int>& myvec) { int d = myvec.size()/8; vector<int>candidate,result; for(int i = 0;i+d < myvec.size();i+=d) if(candidate.empty() || (myvec[i] == myvec[i+d] && myvec[i] != candidate.back())) candidate.push_back(myvec[i]); for(int i = 0;i < candidate.size();i++) { std::vector<int>::iterator low,up; low =std::lower_bound (myvec.begin(), myvec.end(), candidate[i]); up = std::upper_bound (myvec.begin(), myvec.end(), candidate[i]); int n = up - low; if(n >= (int)ceil(myvec.size()/4.0)) { result.push_back(candidate[i]); } } return result; } int main() { vector<int> myvec{2,2,4,4,4,4,5,6,7,8}; vector<int> result = findOneForth(myvec); for(int e : result) cout << e << endl; return 0; }
true
9a3a1452b4a71a780d95be0c9b3d1c2a97a7c0fc
C++
JiahongHe/LeetCode
/Cpp/239. Sliding Window Maximum O(nk).cpp
UTF-8
552
3.109375
3
[]
no_license
class Solution { int maxNumber(vector<int>& nums, int start, int k) { int maxNum = INT_MIN; for (int i = 0; i < k; i++) { maxNum = max(maxNum, nums[start + i]); } return maxNum; } public: vector<int> maxSlidingWindow(vector<int>& nums, int k) { vector<int> result; int N = nums.size(); if (N < k || N == 0) return result; for (int i = 0; i < nums.size() - k + 1; i++) { result.push_back(maxNumber(nums, i, k)); } return result; } };
true
477cb525e600669d80acd247f9ea61b96d87bfbb
C++
piotrekjanisz/ppr
/src/c++/data/Step.cpp
UTF-8
4,522
3.234375
3
[]
no_license
/* * Step.cpp * * Created on: 10-01-2011 * Author: Dariusz Galysa */ #include "Step.h" #include <iostream> #include <cstring> #include <map> const int MAX_PRINTED_POINTS = 8; using namespace std; Step::Step() : _coordinates(NULL) { } Step::Step(string name, int pointsNumber, float *coordinates) : _name(name), _particlesNumber(pointsNumber), _coordinates(coordinates) { } Step::Step(const Step & other) { copyData(other); } Step::~Step() { deleteData(); } Step & Step::operator =(const Step & other) { deleteData(); copyData(other); return *this; } void Step::copyData(const Step& other) { this->_name = other._name; this->_particlesNumber = other._particlesNumber; this->_coordinates = new float[COORDINATES_NUMBER * this->_particlesNumber]; memcpy(this->_coordinates, other._coordinates, sizeof(float) * (this->_particlesNumber)); map<string, float*>::const_iterator begin = other._additionalData.begin(); map<string, float*>::const_iterator end = other._additionalData.end(); while (begin != end) { float* array = new float[this->_particlesNumber]; memcpy(array, begin->second, sizeof(float) * this->_particlesNumber); this->_additionalData[begin->first] = array; ++begin; } } void Step::deleteData() { if (_coordinates != NULL) delete[] _coordinates; map<string, float*>::iterator begin = _additionalData.begin(); map<string, float*>::iterator end = _additionalData.end(); while (begin != end) { if (begin->second != NULL) delete[] begin->second; ++begin; } _additionalData.clear(); _particlesNumber = 0; } float *Step::getCoordinates() const { return _coordinates; } string Step::getName() const { return _name; } int Step::getParticlesNumber() const { return _particlesNumber; } void Step::setCoordinates(float *coordinates) { _coordinates = coordinates; } void Step::setName(string name) { _name = name; } void Step::setParticlesNumber(int particlesNumber) { _particlesNumber = particlesNumber; } void Step::setAdditionalData(std::map<std::string, float*> additionalData) { _additionalData = additionalData; } void printArray(ostream & stream, float *array, int pointsNumber) { //int printedPointsNumber = pointsNumber < MAX_PRINTED_POINTS ? pointsNumber // : MAX_PRINTED_POINTS; stream << "{ " << endl; /*for (int i = 0; i < printedPointsNumber; i++) { stream << array[i] << " "; } if (printedPointsNumber < pointsNumber) stream << "... ";*/ for (int i = 0; i < pointsNumber / 4; i++) { for (int j = 0; j < 4; j++) { cout << array[4*i +j] << " "; } cout << endl; } stream << "}" << endl; } ostream& operator<<(ostream & stream, const Step & step) { stream << "Step name: " << step._name << ", points number: " << step._particlesNumber << endl; stream << "Coordinates: "; printArray(stream, step._coordinates, step._particlesNumber * (Step::COORDINATES_NUMBER)); stream << "Additional data: " << endl; map<string, float*>::const_iterator begin = step._additionalData.begin(); map<string, float*>::const_iterator end = step._additionalData.end(); while (begin != end) { cout << "\t" << begin->first << ": "; printArray(stream, begin->second, step._particlesNumber); ++begin; } return stream; } int Step::getNumberOfAdditionalParams() const { return _additionalData.size(); } Step::Iterator Step::begin() { return Step::Iterator(this, 0); } Step::Iterator Step::end() { return Step::Iterator(this, this->_particlesNumber); } Step::Iterator Step::at(int n) { return Step::Iterator(this, n); } void iter_swap(Step::Iterator& it1, Step::Iterator& it2) { float* tmp = new float[Step::COORDINATES_NUMBER]; float* coordinates1 = it1.step->_coordinates + it1.index * Step::COORDINATES_NUMBER; float* coordinates2 = it2.step->_coordinates + it2.index * Step::COORDINATES_NUMBER; memcpy(tmp, coordinates1, Step::COORDINATES_NUMBER * sizeof(float)); memcpy(coordinates1, coordinates2, Step::COORDINATES_NUMBER * sizeof(float)); memcpy(coordinates2, tmp, Step::COORDINATES_NUMBER * sizeof(float)); map<string, float*>::iterator paramsIter1 = it1.step->_additionalData.begin(); map<string, float*>::iterator paramsIter2 = it2.step->_additionalData.begin(); for (int i = 0; i < it1.step->getNumberOfAdditionalParams(); i++) { float* params1 = paramsIter1->second; float* params2 = paramsIter2->second; tmp[0] = params1[it1.index]; params1[it1.index] = params2[it2.index]; params2[it2.index] = tmp[0]; ++paramsIter1; ++paramsIter2; } delete[] tmp; }
true
53e1bbb4e0291f3a5bb21ba2afaaf18e77b35e4a
C++
wandeln/MolDynSim
/main.cpp
UTF-8
2,480
2.890625
3
[]
no_license
#include "test.cpp" #include <conio.h> std::string to_string(double a){ std::ostringstream sstream; sstream << a; return sstream.str(); } void original(){ printf("=========== original ===========\n"); Argon argon(6,6,6,1.7048); VelocityVerletIntegrator VVI(&argon,0.003); VVI.equilibrate(1000,0.7867); MDtracker mDtracker("C:\\Users\\Ni\\Desktop\\Uni\\9.Semester\\Computer Simulation of Physical Systems I\\output\\", &VVI,1000,10,"N6x6x6_T0,7867_A1,7048");//Number Temperature BoxSize mDtracker.track(); } void diffTemp(){ for(int i=0;i<10;i++){ printf("=========== different Temperatures: %d of 10 ===========\n",i+1); Argon argon(6,6,6,1.7048); VelocityVerletIntegrator VVI(&argon,0.003); VVI.equilibrate(1000,0.5+0.05*i); MDtracker mDtracker("C:\\Users\\Ni\\Desktop\\Uni\\9.Semester\\Computer Simulation of Physical Systems I\\output\\", &VVI,1000,10,"N6x6x6_T"+to_string(0.5+i*0.05)+"_A1,7048");//Number Temperature BoxSize mDtracker.track(); } } void diffDens(){ for(int i=0;i<10;i++){ printf("=========== different Densities: %d of 10 ===========\n",i+1); Argon argon(6,6,6,1.2+0.1*i); VelocityVerletIntegrator VVI(&argon,0.003); VVI.equilibrate(1000,0.7867); MDtracker mDtracker("C:\\Users\\Ni\\Desktop\\Uni\\9.Semester\\Computer Simulation of Physical Systems I\\output\\", &VVI,1000,10,"N6x6x6_T0,7867_A"+to_string(1.2+0.1*i));//Number Temperature BoxSize mDtracker.track(); } } void diffBoxSize(){ for(int i=0;i<5;i++) { printf("=========== different Boxsizes: %d of 5 ===========\n",i+1); Argon argon(4+i, 4+i, 4+i, 1.7048); VelocityVerletIntegrator VVI(&argon, 0.003); VVI.equilibrate(1000, 0.7867); MDtracker mDtracker( "C:\\Users\\Ni\\Desktop\\Uni\\9.Semester\\Computer Simulation of Physical Systems I\\output\\", &VVI, 1000, 10, "N"+to_string(4+i)+"x"+to_string(4+i)+"x"+to_string(4+i)+"_T0,7867_A1,7048");//Number Temperature BoxSize mDtracker.track(); } } int main() { // calculate "original" problem: T=0.7867; a=1.7048; N=864 Atoms original(); // vary temperature of original problem diffTemp(); // vary density of original problem diffDens(); // vary box size diffBoxSize(); getch(); return 0; }
true
29b5bd1213fdeff237e6a7cdfd33227ccb21cf39
C++
cms-sw/cmssw
/MagneticField/Interpolation/src/CylinderFromSectorMFGrid.cc
UTF-8
2,252
2.640625
3
[ "Apache-2.0" ]
permissive
#include "CylinderFromSectorMFGrid.h" #include "MagneticField/VolumeGeometry/interface/MagExceptions.h" #include <iostream> CylinderFromSectorMFGrid::CylinderFromSectorMFGrid(const GloballyPositioned<float>& vol, double phiMin, double phiMax, MFGrid* sectorGrid) : MFGrid(vol), thePhiMin(phiMin), thePhiMax(phiMax), theSectorGrid(sectorGrid) { if (thePhiMax < thePhiMin) thePhiMax += 2.0 * Geom::pi(); theDelta = thePhiMax - thePhiMin; } CylinderFromSectorMFGrid::~CylinderFromSectorMFGrid() { delete theSectorGrid; } MFGrid::LocalVector CylinderFromSectorMFGrid::valueInTesla(const LocalPoint& p) const { double phi = p.phi(); if (phi < thePhiMax && phi > thePhiMin) return theSectorGrid->valueInTesla(p); else { double phiRot = floor((phi - thePhiMin) / theDelta) * theDelta; double c = cos(phiRot); double s = sin(phiRot); double xrot = p.x() * c + p.y() * s; double yrot = -p.x() * s + p.y() * c; // get field in interpolation sector MFGrid::LocalVector tmp = theSectorGrid->valueInTesla(LocalPoint(xrot, yrot, p.z())); // rotate field back to original sector return MFGrid::LocalVector(tmp.x() * c - tmp.y() * s, tmp.x() * s + tmp.y() * c, tmp.z()); } } void CylinderFromSectorMFGrid::throwUp(const char* message) const { std::cout << "Throwing exception " << message << std::endl; throw MagGeometryError(message); } void CylinderFromSectorMFGrid::toGridFrame(const LocalPoint& p, double& a, double& b, double& c) const { throwUp("Not implemented yet"); } MFGrid::LocalPoint CylinderFromSectorMFGrid::fromGridFrame(double a, double b, double c) const { throwUp("Not implemented yet"); return LocalPoint(); } Dimensions CylinderFromSectorMFGrid::dimensions() const { return theSectorGrid->dimensions(); } MFGrid::LocalPoint CylinderFromSectorMFGrid::nodePosition(int i, int j, int k) const { throwUp("Not implemented yet"); return LocalPoint(); } MFGrid::LocalVector CylinderFromSectorMFGrid::nodeValue(int i, int j, int k) const { throwUp("Not implemented yet"); return LocalVector(); }
true
1297613b47ca62e3663c4dd523e0d96590a3807b
C++
edyrol/Hearthstone-DeckFinder
/MatchCollector.cpp
UTF-8
3,192
2.71875
3
[]
no_license
#include "CollectOBot.hpp" #include "HSReplay.hpp" int main(int argc, char *argv[]) { //default parameters // minimum ratio of matches to be considered (for cards) double MIN_MATCH_VALID_RATIO = .02; int MAX_NUM_CARDS = 65; std::string STATS_RESOURCE("HSReplay"); //reads parameters //checks the number of parameters if (argc<3 || argc>5) { std::cout << "format: ./MatchCollector TUPLE_NUMBER CARD_CLASS MIN_MATCH_VALID_RATIO STATS_RESOURCE or format: ./MatchCollector 1 CARD_CLASS MAX_NUM_CARDS STATS_RESOURCE" << std::endl; return 0; } //reads TUPLE NUMBER std::string s_TUPLE_NUMBER(argv[1]); std::istringstream ss_TUPLE_NUMBER(argv[1]); int TUPLE_NUMBER; if (!(ss_TUPLE_NUMBER >> TUPLE_NUMBER)) { std::cout << "Error with arguments" << std::endl; return 0; } //reads CARD CLASS std::string CARD_CLASS(argv[2]); std::string CARD_CLASS_MIN = upper_to_standar_names(CARD_CLASS); //reads MIN MATCH VALID RATIO if (argc>3) { std::istringstream s_MIN_MATCH_VALID_RATIO(argv[3]); if (!(s_MIN_MATCH_VALID_RATIO >> MIN_MATCH_VALID_RATIO)) { std::cout << "Error with arguments" << std::endl; return 0; if (TUPLE_NUMBER == 1) { MAX_NUM_CARDS = int(MIN_MATCH_VALID_RATIO); } } } //reads the source of stats /* Available resources: CollectOBot HSReplay */ if (argc > 4) { std::istringstream s_STATS_RESOURCE(argv[4]); if (!(s_STATS_RESOURCE >> STATS_RESOURCE)) { std::cout << "Error with arguments" << std::endl; return 0; } } //makes the cards object with the CARD CLASS cards rapidjson::Document Cards = read_json("data/1_" + CARD_CLASS + ".json"); //makes the object with name of tuples file std::string tuplesFileName("data/" + s_TUPLE_NUMBER + "_" + CARD_CLASS + ".json"); //makes the tuples file object rapidjson::Document tuplesFile = read_json(tuplesFileName); //makes a list with the names of files which have matches std::vector<std::string> listOfMatches; read_directory("data/"+STATS_RESOURCE+"/", listOfMatches); //counts the number of added matches int numberOfAddedMatches = 0; //counts matches of each file for (std::string matchFileName : listOfMatches) if (matchFileName != "." && matchFileName != "..") { if (STATS_RESOURCE == "CollectOBot") { rapidjson::Document matchDay = read_json(matchFileName); numberOfAddedMatches += add_counted_matches(matchDay, tuplesFile, CARD_CLASS_MIN, Cards, TUPLE_NUMBER); } if (STATS_RESOURCE == "HSReplay") { ResultsFile RF(matchFileName); numberOfAddedMatches += add_counted_stats(RF,tuplesFile, CARD_CLASS, Cards, TUPLE_NUMBER); } } //if it is counting matches of single cards, removes cards which not have enough matches and writes info of this class if (TUPLE_NUMBER == 1) { remove_extra_cards( tuplesFile, MAX_NUM_CARDS ); rapidjson::Document GI = read_json("data/" + CARD_CLASS + "_Info.json"); GI["playedMatches"].SetInt(GI["playedMatches"].GetInt() + numberOfAddedMatches); GI["numberOfCards"].SetInt(tuplesFile.Size()); write_json(GI, "data/" + CARD_CLASS + "_Info.json"); } calculate_win_ratio(tuplesFile); write_json(tuplesFile, tuplesFileName); return 0; }
true
6402e20f515ac3d91073738b022e1cb5b282da62
C++
Adityasharma15/Data-Structures
/Hash Maps/relative_sorting.cpp
UTF-8
531
2.546875
3
[]
no_license
#include<bits/stdc++.h> #define ll long long using namespace std; int main() { ll t; cin >> t; while(t--) { ll n, m; cin >> n >> m; ll temp, arr[n]; unordered_map<ll,ll> um; for(ll i = 0; i<n; i++) { cin >> arr[i]; um[arr[i]]++; } for(ll i = 0; i<m; i++) { cin >> temp; while(um[temp]--) { cout << temp << " "; } } for(ll i = 0; i<n; i++) { temp = arr[i]; while(um[temp]--) { cout << temp << " "; } } cout << "\n"; } }
true
63761b8565eeb13c96b7ccbe9d76f7a46849f18e
C++
Hespike/osszefuz
/osszefuz.cpp
UTF-8
435
2.5625
3
[]
no_license
#include <iostream> using namespace std; string osszefuzes(string szovegek[], int darab) { string ujszoveg = ""; for(int i = 0; i < darab; i++){ ujszoveg = ujszoveg + szovegek[i]; } return ujszoveg; } /* #include <iostream> using namespace std; string osszefuzes(string szovegek[], int darab) { string res; for (int i = 0; i < darab; i++) { res += szovegek[i]; } return res; } */
true
e3a51de6366b4d776a1d819d48cfdbe7c08b5b20
C++
Arkozak/New-Repo
/Homework 1/Homework 1/greatest.cpp
UTF-8
599
4.40625
4
[]
no_license
/** * greatest.cpp * Andrew Kozak * 09/11/2019 * This program asks the user a number until they enter a number less than or equal to 0 then outputs the greatest */ #include <iostream> using std::cout; using std::endl; using std::cin; int greatest() { int x = 1; //Initializing my variables int y = 0; while (x > 0) //Creating a loop until the user enters 0 { cout << "Enter a positive integer (0 to end): "; //Asks for number cin >> x; cout << endl; if (x > y) //Setting y to biggest number { y = x; } } cout << "The greatest number entered: " << y; //Final output return 0; }
true
9a63158eda23160863cd7de4584216257c454491
C++
leisheyoufu/study_exercise
/CXX/explicit/explicit.cpp
UTF-8
993
3.21875
3
[]
no_license
#ifndef FBC_MESSY_TEST_EXPLICIT_HPP #define FBC_MESSY_TEST_EXPLICIT_HPP // reference Bjarne Stroustrup sample class String{ public: explicit String(int n) {}; String(const char *p) {}; }; void test_explicit(); #endif // FBC_MESSY_TEST_EXPLICIT_HPP static void test1() { //String s1 = 'a'; // 错误:不能做隐式char->String转换 String s2(10); // 可以:调用explicit String(int n); String s3 = String(10); // 可以:调用explicit String(int n);再调用默认的复制构造函数 String s4 = "Brian"; // 可以:隐式转换调用String(const char *p);再调用默认的复制构造函数 String s5("Fawlty"); // 可以:正常调用String(const char *p); } static void f(String) { } static String g() { //f(10); // 错误:不能做隐式int->String转换 f("Arthur"); // 可以:隐式转换,等价于f(String("Arthur")); //return 10; // 错误同上 return String(10); // cl: 可以显示转换 } int main() { test1(); g(); return 0; }
true
1252bf9e9e7ebcc74975750421861a7650fd57ad
C++
GuanyiLi-Craig/interview
/Array/q148.cpp
UTF-8
2,052
3.46875
3
[]
no_license
/**************************************************************************************************** 148. Sort List ----------------------------------------------------------------------------------------------------- Sort a linked list in O(n log n) time using constant space complexity. ****************************************************************************************************/ #include "problems\problems\Header.h" namespace std { /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* merge(ListNode* h1, ListNode* h2){ if(h1 == NULL){ return h2; } if(h2 == NULL){ return h1; } if(h1->val < h2->val){ h1->next = merge(h1->next, h2); return h1; } else{ h2->next = merge(h1, h2->next); return h2; } } ListNode* sortList(ListNode* head) { // iterative merge sort // if NULL or just one value, return. if (head==NULL || head->next==NULL) return head; ListNode* pre = head; ListNode* p1 = head; ListNode* p2 = head; while(p2!=NULL && p2->next!=NULL) { pre=p1; p1=p1->next; p2=p2->next->next; } pre->next=NULL; pre=sortList(head); p2=sortList(p1); return merge(pre,p2); } }; } /**************************************************************************************************** Note Followed the solution. the merge function is the key, and sortList need to break the list into two part and then merge them. ****************************************************************************************************/
true
8b50f9667025dd7cb7135d383d4bf4f0649ee3b5
C++
jpan127/argparse
/test/test_variant.cpp
UTF-8
3,750
3.203125
3
[]
no_license
#include "catch.hpp" #include "variant.h" using namespace argparse; /// Tests conversions to / from [Variant] TEST_CASE("variant", "Parsing") { Variant var; struct Visitor { std::string operator()(std::string) { return "std::string"; }; std::string operator()(double) { return "double"; }; std::string operator()(float) { return "float"; }; std::string operator()(uint64_t) { return "uint64_t"; }; std::string operator()(int64_t) { return "int64_t"; }; std::string operator()(uint32_t) { return "uint32_t"; }; std::string operator()(int32_t) { return "int32_t"; }; std::string operator()(uint16_t) { return "uint16_t"; }; std::string operator()(int16_t) { return "int16_t"; }; std::string operator()(uint8_t) { return "uint8_t"; }; std::string operator()(int8_t) { return "int8_t"; }; std::string operator()(bool) { return "bool"; }; std::string operator()(char) { return "char"; }; }; SECTION("std::string") { const auto value = std::string("asdffdsa"); var = value; const auto str = var.visit(Visitor{}); REQUIRE(str == "std::string"); REQUIRE(var == value); } SECTION("double") { const auto value = double{5.12315141209}; var = value; const auto str = var.visit(Visitor{}); REQUIRE(str == "double"); REQUIRE(var == value); } SECTION("float") { const auto value = float{5.12315141209}; var = value; const auto str = var.visit(Visitor{}); REQUIRE(str == "float"); REQUIRE(var == value); } SECTION("uint64_t") { const auto value = uint64_t{0xFFFFFFFF12312}; var = value; const auto str = var.visit(Visitor{}); REQUIRE(str == "uint64_t"); REQUIRE(var == value); } SECTION("int64_t") { const auto value = int64_t{-999999777777}; var = value; const auto str = var.visit(Visitor{}); REQUIRE(str == "int64_t"); REQUIRE(var == value); } SECTION("uint32_t") { const auto value = uint32_t{123456789}; var = value; const auto str = var.visit(Visitor{}); REQUIRE(str == "uint32_t"); REQUIRE(var == value); } SECTION("int32_t") { const auto value = int32_t{-987533}; var = value; const auto str = var.visit(Visitor{}); REQUIRE(str == "int32_t"); REQUIRE(var == value); } SECTION("uint16_t") { const auto value = uint16_t{777}; var = value; const auto str = var.visit(Visitor{}); REQUIRE(str == "uint16_t"); REQUIRE(var == value); } SECTION("int16_t") { const auto value = int16_t{-677}; var = value; const auto str = var.visit(Visitor{}); REQUIRE(str == "int16_t"); REQUIRE(var == value); } SECTION("uint8_t") { const auto value = uint8_t{222}; var = value; const auto str = var.visit(Visitor{}); REQUIRE(str == "uint8_t"); REQUIRE(var == value); } SECTION("int8_t") { const auto value = int8_t{-53}; var = value; const auto str = var.visit(Visitor{}); REQUIRE(str == "int8_t"); REQUIRE(var == value); } SECTION("bool") { const auto value = bool{true}; var = value; const auto str = var.visit(Visitor{}); REQUIRE(str == "bool"); REQUIRE(var == value); } SECTION("char") { const auto value = char{'z'}; var = value; const auto str = var.visit(Visitor{}); REQUIRE(str == "char"); REQUIRE(var == value); } }
true
6536dad394a933956b8d7a71271a8c7bdb57ba52
C++
aleqsio/Studies
/Algorytmy_I_Struktury_Danych/cwiczenia_kurdziel_2/cwiczenia_kurdziel_2/cwiczenia_kurdziel_2.cpp
WINDOWS-1250
2,212
2.9375
3
[]
no_license
// cwiczenia_kurdziel_2.cpp : Defines the entry point for the console application. // #include "stdafx.h" using namespace std; #include <stdlib.h> #include <string> const int maxh = 64; struct SLNode { string key; int val; SLNode** next; }; struct SkipList { SLNode* first, last; int height; }; struct mdata { string key; int val; }; mdata Htab[N]; const int N = 65535; int h(string s) { return 0; } bool find(string key, int* result) { int licznik = 0; int index = h(key); while (Htab[index] != key && Htab[index] != "" && licznik < N) { index = (index + 1) % N; if (key == Htab[index].key) { } } } SLNode* Search(SkipList *s, int key) { SLNode*q = s->first; for (int i = s->height - 1; i > 0; i--) { while (q->next[i]->key < key) q = q->next[i]; if (q->key == key) return q; } } int max(int x, int y) { return x < y ? y : x; } int rand() { return 0; } int randh() { int H = 1; while (rand() % 2) { H++; } } int insert(SkipList*s, int key) { //zakadamy e wstawiane klucze s unikalne SLNode** update = new SLNode*[maxh]; SLNode*q = s->first; int h = -1; for (int level = s->height - 1; level >= 0; level--) { while (q->next[level]->key < key) q = q->next[level]; if (q->key == key) { update[level] = q; h = max(h, level+1); } } q = update[0]->next[0]; int v = q->val; for (int level = 0; level < h; level++) { update[level]->next[level] = update[level]->next[level]; } delete[] q->next; delete q; delete[] update; return v; } SLNode* insert(SkipList*s,int key,int val) { //zakadamy e wstawiane klucze s unikalne SLNode** update = new (SLNode*)[maxh]; SLNode*q = s->first; SLNode*p = new SLNode; p->key = key; p->val = val; int pHeight = randh(); p->next = new (SLNode*)[pHeight]; int h = max(pHeight, s->height); for (int level=h-1; level >= 0; level--) { while (q->next[level]->key < key) q = q->next[key]; if (level < pHeight) update[level] = q; } for (int level = 0; level < pHeight; level++) { p->next[level]=update[level]->next[level]; update[level]->next[level] = p; } if (s->height < pHeight) { s->height = pHeight; } delete[] update; return p; } int main() { return 0; }
true
209040ee13f049e1c3b8e9bf7db363fc02276c7c
C++
PeterZhouSZ/CaveSegmentation
/CaveSegmentationLib/src/ChamberAnalyzation/CurvatureBasedAStar.cpp
UTF-8
19,854
2.828125
3
[]
no_license
#include "ChamberAnalyzation/CurvatureBasedAStar.h" #include "ChamberAnalyzation/energies.h" #include "SignedUnionFind.h" #include "GraphProc.h" #include <unordered_set> #include <algorithm> #include <iostream> #include <queue> #include "CaveDataAccessors.h" struct NeighborViaEdge { int patchIndex; int edgeIndex; NeighborViaEdge(int patchIndex, int edgeIndex) : patchIndex(patchIndex), edgeIndex(edgeIndex) {} }; struct Patch { double caveSize; int representativeVertex; std::vector<NeighborViaEdge> neighborPatches; }; struct Edge { //directed edge; direction refers to an ascending cave size int sourcePatch; int targetPatch; double size; double energyEntrance; //the resulting energy if this edge becomes an entrance double energyNoEntrance; //the resulting energy if this edge becomes no entrance Edge(int sourcePatch, int targetPatch, double size, double energyEntrance, double energyNoEntrance) : sourcePatch(sourcePatch), targetPatch(targetPatch), size(size), energyEntrance(energyEntrance), energyNoEntrance(energyNoEntrance) {} }; // Represents a state in the A* graph class State { std::size_t hash; // Calculates three bits (plus one parity bit) that represent the two edge states. void CalculateHashTriple(bool labeledFirst, bool entranceFirst, bool labeledSecond, bool entranceSecond, size_t& hashTriple, size_t& parity) { //indexed by [labeled][entrance] const int stateNumberTable[2][2] = { { 0, 0 },{ 1, 2 } }; //indexed by [state1][state2] const size_t hashTable[3][3] = { { 0, 1, 2 },{ 3, 4, 5 },{ 6, 7, 0 } }; const size_t parityTable[3][3] = { { 0, 0, 0 },{ 0, 0, 0 },{ 0, 0, 1 } }; size_t state1 = stateNumberTable[labeledFirst][entranceFirst]; size_t state2 = stateNumberTable[labeledSecond][entranceSecond]; hashTriple = hashTable[state1][state2]; parity = parityTable[state1][state2]; } void UpdateValue(int edge, bool labeled, bool entrance) { //get old hash triple const int edgesPerRow = sizeof(size_t) * 8 / 3; int hashTripleLocation = (edge % edgesPerRow) / 2; size_t oldHash = (hash >> (hashTripleLocation * 3)) & (7); size_t oldParity = hash >> (sizeof(size_t) * 8 - 1); //update values edgeLabeled.at(edge) = true; edgeEntrance.at(edge) = entrance; //update hash size_t newHash, newParity; int tripleComponent1 = 2 * hashTripleLocation; int tripleComponent2 = 2 * hashTripleLocation + 1; CalculateHashTriple(edgeLabeled.at(tripleComponent1), edgeEntrance.at(tripleComponent1), edgeLabeled.at(tripleComponent2), edgeEntrance.at(tripleComponent2), newHash, newParity); hash ^= (oldHash ^ newHash) << (hashTripleLocation * 3); hash ^= (oldParity ^ newParity) << (sizeof(size_t) * 8 - 1); } template <bool reverseDirection> void PushEntrance(int entrance, const std::vector<Patch>& patches, const std::vector<Edge>& edges) { auto& edge = edges.at(entrance); //entrance switches from "entrance" to "no entrance" currentEnergy.Remove(entrance, edge.energyEntrance); currentEnergy.Add(entrance, edge.energyNoEntrance); minEnergyAtTarget.Remove(entrance, std::min(edge.energyEntrance, edge.energyNoEntrance)); minEnergyAtTarget.Add(entrance, edge.energyNoEntrance); entrances.erase(entrance); UpdateValue(entrance, true, false); //the vertex across which the entrance is pushed int vertexNewInChamber = (reverseDirection ? edge.targetPatch : edge.sourcePatch); //the vertex that was in the chamber before pushing the entrance int vertexAlreadyInChamber = (reverseDirection ? edge.sourcePatch : edge.targetPatch); std::vector<int> edgesThatNeedPushing; for (auto& neighbor : patches.at(vertexNewInChamber).neighborPatches) { if (neighbor.patchIndex == vertexAlreadyInChamber) continue; //wrong propagation direction auto& neighborEdge = edges.at(neighbor.edgeIndex); if (edgeLabeled.at(neighbor.edgeIndex)) { //neighbor edge is already labeled //must be another entrance //merge the entrances UpdateValue(neighbor.edgeIndex, true, false); currentEnergy.Remove(neighbor.edgeIndex, neighborEdge.energyEntrance); currentEnergy.Add(neighbor.edgeIndex, neighborEdge.energyNoEntrance); minEnergyAtTarget.Remove(entrance, std::min(neighborEdge.energyEntrance, neighborEdge.energyNoEntrance)); minEnergyAtTarget.Add(neighbor.edgeIndex, neighborEdge.energyNoEntrance); entrances.erase(neighbor.edgeIndex); } else { //neighbor edge is still unlabeled UpdateValue(neighbor.edgeIndex, true, true); currentEnergy.Add(neighbor.edgeIndex, neighborEdge.energyEntrance); entrances.insert(neighbor.edgeIndex); //check if the direction is ok if (neighborEdge.targetPatch != vertexNewInChamber) { //direction is not ok, edge needs to be pushed further edgesThatNeedPushing.push_back(neighbor.edgeIndex); } } } //At this point, entrances are closed borders around chamber, but some may be in the wrong direction for (int edgeIndex : edgesThatNeedPushing) PushEntrance<true>(edgeIndex, patches, edges); } //Accumulates values and keeps track of infinite parts template <typename T> class Accumulator { private: T nonInfinitySum; T finalSum; std::unordered_set<int> infiniteParts; public: Accumulator() : nonInfinitySum(0), finalSum(0) {} void Add(int index, T value) { if (isinf(value)) infiniteParts.insert(index); else nonInfinitySum += value; finalSum += value; } void Remove(int index, T value) { if (isinf(value)) { infiniteParts.erase(index); if (infiniteParts.size() == 0) finalSum = nonInfinitySum; } else { nonInfinitySum -= value; finalSum -= value; } } T Sum() const { return finalSum; } bool operator==(const Accumulator<T>& other) const { return finalSum == other.finalSum; } bool operator!=(const Accumulator<T>& other) const { return finalSum != other.finalSum; } bool operator<(const Accumulator<T>& other) const { return finalSum < other.finalSum; } bool operator>(const Accumulator<T>& other) const { return finalSum > other.finalSum; } bool operator>=(const Accumulator<T>& other) const { return finalSum >= other.finalSum; } std::ostream& operator<<(std::ostream& s) const { return s << finalSum; } }; public: std::vector<bool> edgeLabeled; std::vector<bool> edgeEntrance; std::unordered_set<int> seeds; //unused seed candidates std::unordered_set<int> entrances; //indices of edges that are labeled as entrances Accumulator<double> currentEnergy; //the energy that has been paid so far by labeled edges Accumulator<double> minEnergyAtTarget; //lower bound for the resulting energy at the target state //Initialize the state with all edges unlabeled State(const std::vector<Edge>& edges, const std::unordered_set<int>& seeds) : edgeLabeled(edges.size(), false), edgeEntrance(edges.size(), false), seeds(seeds), hash(0) { for (int i = 0; i < edges.size(); ++i) { auto& e = edges.at(i); minEnergyAtTarget.Add(i, std::min(e.energyEntrance, e.energyNoEntrance)); } } State(const State& copy) : edgeLabeled(copy.edgeLabeled), edgeEntrance(copy.edgeEntrance), seeds(copy.seeds), entrances(copy.entrances), hash(copy.hash), currentEnergy(copy.currentEnergy), minEnergyAtTarget(copy.minEnergyAtTarget) { } State& operator=(State&& movedFrom) { edgeLabeled = std::move(movedFrom.edgeLabeled); edgeEntrance = std::move(movedFrom.edgeEntrance); seeds = std::move(movedFrom.seeds); entrances = std::move(movedFrom.entrances); hash = movedFrom.hash; currentEnergy = movedFrom.currentEnergy; minEnergyAtTarget = movedFrom.minEnergyAtTarget; return *this; } bool operator<(const State& other) const { if (minEnergyAtTarget != other.minEnergyAtTarget) return minEnergyAtTarget < other.minEnergyAtTarget; else return currentEnergy < other.currentEnergy; } bool operator>(const State& other) const { if (minEnergyAtTarget != other.minEnergyAtTarget) return minEnergyAtTarget > other.minEnergyAtTarget; else return currentEnergy > other.currentEnergy; } bool operator==(const State& rhs) const { if (hash != rhs.hash || currentEnergy != rhs.currentEnergy) return false; if (edgeLabeled.size() != rhs.edgeLabeled.size()) return false; for (int i = 0; i < edgeLabeled.size(); ++i) { if (edgeLabeled.at(i) != rhs.edgeLabeled.at(i) || edgeEntrance.at(i) != rhs.edgeEntrance.at(i)) return false; } return true; } State* SetUnlabeledEdgesToNoEntrances(const std::vector<Edge>& edges) const { State* copy = new State(*this); for (int i = 0; i < edges.size(); ++i) { if (!edgeLabeled.at(i)) { copy->UpdateValue(i, true, false); copy->currentEnergy.Add(i, edges.at(i).energyNoEntrance); } } copy->minEnergyAtTarget = copy->currentEnergy; return copy; } bool CanPlaceSeed(int seed, const std::vector<Patch>& patches) const { auto& neighbors = patches.at(seed).neighborPatches; if (neighbors.size() == 0 || !edgeLabeled.at(neighbors.front().edgeIndex)) return true; return false; } State* PlaceSeed(int seed, const std::vector<Patch>& patches, const std::vector<Edge>& edges) const { State* copy = new State(*this); for (auto& neighbor : patches.at(seed).neighborPatches) { //All edges of a seed are incoming. Set them all to entrances. int eIndex = neighbor.edgeIndex; auto& edge = edges.at(eIndex); copy->UpdateValue(eIndex, true, true); copy->currentEnergy.Add(eIndex, edge.energyEntrance); copy->entrances.insert(eIndex); } copy->seeds.erase(seed); if (abs(copy->CalculateHeuristic(edges) - copy->minEnergyAtTarget.Sum()) > 0.01) { std::cout << "Wrong heuristic."; system("PAUSE"); } if (abs(copy->CalculateEnergy(edges) - copy->currentEnergy.Sum()) > 0.01) { std::cout << "Wrong energy."; system("PAUSE"); } return copy; } State* AdvanceEntrance(int entrance, const std::vector<Patch>& patches, const std::vector<Edge>& edges) const { State* copy = new State(*this); copy->PushEntrance<false>(entrance, patches, edges); if (abs(copy->CalculateHeuristic(edges) - copy->minEnergyAtTarget.Sum()) > 0.01) { std::cout << "Wrong heuristic."; system("PAUSE"); } if (abs(copy->CalculateEnergy(edges) - copy->currentEnergy.Sum()) > 0.01) { std::cout << "Wrong energy."; system("PAUSE"); } return copy; } double CalculateEnergy(const std::vector<Edge>& edges) const { double energy = 0; for (int i = 0; i < edges.size(); ++i) { if (edgeLabeled.at(i)) energy += (edgeEntrance.at(i) ? edges.at(i).energyEntrance : edges.at(i).energyNoEntrance); } return energy; } double CalculateHeuristic(const std::vector<Edge>& edges) const { double energy = 0; for (int i = 0; i < edges.size(); ++i) { if (edgeLabeled.at(i) && !edgeEntrance.at(i)) energy += (edgeEntrance.at(i) ? edges.at(i).energyEntrance : edges.at(i).energyNoEntrance); else energy += std::min(edges.at(i).energyEntrance, edges.at(i).energyNoEntrance); } return energy; } struct Hash { size_t operator() (const State* state) const { return state->hash; } }; struct Equals { bool operator() (const State* lhs, const State* rhs) const { return *lhs == *rhs; } }; struct EnergyAtTargetBasedPriority { bool operator() (const State* lhs, const State* rhs) const { return *lhs > *rhs; } }; }; template <bool debug = false> static void VisualizeState(const State* state, const std::vector<Patch>& patches, const std::vector<Edge>& edges, const std::vector<CurveSkeleton::Vertex>& vertices, const std::string& name) { if (debug) return; #ifdef WITH_GRAPHVIZ { const std::string neatoPath = "\"C:\\Program Files (x86)\\Graphviz2.38\\bin\\neato\""; std::ofstream dot("layout.dot"); int oldPrec = dot.precision(); dot << "digraph G { graph[splines = \"false\" inputscale=10];"; dot << "node[shape=\"point\"];"; for (int i = 0; i < patches.size(); ++i) { auto& v = vertices.at(patches.at(i).representativeVertex); dot << i << "[pos=\"" << v.position.x() << "," << v.position.y() << "!\"];"; } for (int i = 0; i < edges.size(); ++i) { auto& e = edges.at(i); dot << e.sourcePatch << "->" << e.targetPatch << "[color="; if (state->edgeLabeled.at(i)) if (state->edgeEntrance.at(i)) dot << "red"; else dot << "black"; else dot << "gray"; dot.precision(2); dot << ",label=\"" << (edges.at(i).energyEntrance - edges.at(i).energyNoEntrance) << "\"];"; dot.precision(oldPrec); } dot << "}"; } std::string call = "\"" + neatoPath + " -Tpng layout.dot -o \"" + name + "\"\""; system(call.c_str()); #endif } void CurvatureBasedAStar::FindChambers(const ICaveData& data, std::vector<int>& segmentation, bool verbose) { //Contract the graph at non-local maximum edges if(verbose) std::cout << "Contracting graph..." << std::endl; std::vector<bool> keepEdge(data.Skeleton()->edges.size()); //Find local maxima EdgeCurvatureAccessor curvatureAccessor(data); for (int i = 0; i < data.Skeleton()->edges.size(); ++i) { auto& edge = data.Skeleton()->edges.at(i); double edgeValue = data.CaveSizeCurvature(i); //check incoming and outgoing neighbors bool isMaximum = IsEdgeLocalMaximum(data, curvatureAccessor, edge.first, edge.second, edgeValue); if (isMaximum) isMaximum = IsEdgeLocalMaximum(data, curvatureAccessor, edge.second, edge.first, edgeValue); keepEdge.at(i) = isMaximum; } //TODO: check if we need to keep at least one edge per branch (from crossing to crossing) to preserve topology //contract vertices and keep track of maximum cave size SignedUnionFind<false> vertexPatches; vertexPatches.addItems((int)data.Skeleton()->vertices.size(), false); std::vector<double> ufCaveSizeMaxima; ufCaveSizeMaxima.resize(data.Skeleton()->vertices.size()); #pragma omp parallel for for (int i = 0; i < (int)data.Skeleton()->vertices.size(); ++i) ufCaveSizeMaxima[i] = data.CaveSize(i); std::vector<int> preservedEdges; for (int i = 0; i < data.Skeleton()->edges.size(); ++i) { auto& edge = data.Skeleton()->edges.at(i); if (keepEdge.at(i)) { preservedEdges.push_back(i); } else { auto representative1 = vertexPatches.getRepresentative(edge.first); auto representative2 = vertexPatches.getRepresentative(edge.second); double newMaxCaveSize = std::max(ufCaveSizeMaxima.at(representative1), ufCaveSizeMaxima.at(representative2)); auto newRepresentative = vertexPatches.merge(representative1, representative2); ufCaveSizeMaxima.at(newRepresentative) = newMaxCaveSize; } } //Number the patches int patchCount = 0; std::map<int, int> vertexToPatch; std::vector<Patch> patches; std::vector<Edge> edges; std::unordered_set<int> seedCandidates; //indices of vertices with solely incoming edges for (unsigned int representative : vertexPatches.roots()) { vertexToPatch[representative] = patchCount++; patches.emplace_back(); Patch& patch = patches.back(); patch.caveSize = ufCaveSizeMaxima.at(representative); patch.representativeVertex = representative; seedCandidates.insert((int)patches.size() - 1); } for (int i : preservedEdges) { auto& edge = data.Skeleton()->edges.at(i); int sourcePatch = vertexToPatch.at(vertexPatches.getRepresentative(edge.first)); int targetPatch = vertexToPatch.at(vertexPatches.getRepresentative(edge.second)); //evaluate direction based on first derivative of cave size double derivative = data.CaveSizeDerivative(i); if (derivative < 0) { std::swap(sourcePatch, targetPatch); derivative *= -1; } if (sourcePatch == targetPatch) std::cout << "Loop edge!!." << std::endl; double entranceProb = entranceProbability(data.CaveSizeCurvature(i)); double size = (data.CaveSize(edge.first) + data.CaveSize(edge.second)) / 2; edges.emplace_back(sourcePatch, targetPatch, size, -log(entranceProb), -log(1 - entranceProb)); patches.at(sourcePatch).neighborPatches.emplace_back(targetPatch, edges.size() - 1); patches.at(targetPatch).neighborPatches.emplace_back(sourcePatch, edges.size() - 1); //Remove the patch with outgoing edges from the list of seed candidates auto seedIt = seedCandidates.find(sourcePatch); if (seedIt != seedCandidates.end()) seedCandidates.erase(seedIt); } double minimumEnergy = std::numeric_limits<double>::infinity(); State* optimalState = nullptr; { std::unordered_set<const State*, State::Hash, State::Equals> visitedStates; std::priority_queue<const State*, std::vector<const State*>, State::EnergyAtTargetBasedPriority> openStates; while (seedCandidates.size() > 1) seedCandidates.erase(*seedCandidates.begin()); auto initialState = new State(edges, seedCandidates); //Start with an initial state visitedStates.insert(initialState); openStates.push(initialState); int iteration = 0; while (!openStates.empty()) { const State* currentState = openStates.top(); openStates.pop(); VisualizeState(currentState, patches, edges, data.Skeleton()->vertices, "Iteration" + std::to_string(iteration) + "_Base.png"); if(verbose) std::cout << "current optimum: " << minimumEnergy << "; current energy: " << currentState->currentEnergy.Sum() << "; lower bound: " << currentState->minEnergyAtTarget.Sum() << "; open states: " << openStates.size() << "; seeds: " << currentState->seeds.size() << "; entrances: " << currentState->entrances.size() << " "; std::cout << std::endl; if (currentState->minEnergyAtTarget.Sum() >= 0.99 * minimumEnergy) break; //we cannot find a better state than the currently optimal one int step = 0; //Place seeds for (int seed : currentState->seeds) { if (!currentState->CanPlaceSeed(seed, patches)) continue; State* newState = currentState->PlaceSeed(seed, patches, edges); if (newState->minEnergyAtTarget.Sum() < minimumEnergy && visitedStates.find(newState) == visitedStates.end()) { VisualizeState(newState, patches, edges, data.Skeleton()->vertices, "Iteration" + std::to_string(iteration) + "_Step" + std::to_string(step++) + "_MinHeur" + std::to_string(newState->minEnergyAtTarget.Sum()) + ".png"); //we haven't visited this state before visitedStates.insert(newState); openStates.push(newState); } else delete newState; } //Push entrances for (int entrance : currentState->entrances) { State* newState = currentState->AdvanceEntrance(entrance, patches, edges); if (newState->minEnergyAtTarget.Sum() < minimumEnergy && visitedStates.find(newState) == visitedStates.end()) { VisualizeState(newState, patches, edges, data.Skeleton()->vertices, "Iteration" + std::to_string(iteration) + "_Step" + std::to_string(step++) + "_MinHeur" + (isinf(newState->minEnergyAtTarget.Sum()) ? "INF" : std::to_string(newState->minEnergyAtTarget.Sum())) + ".png"); //we haven't visited this state before visitedStates.insert(newState); openStates.push(newState); } else delete newState; } //Directly go to the target State* target = currentState->SetUnlabeledEdgesToNoEntrances(edges); if (target->currentEnergy.Sum() < minimumEnergy) { optimalState = target; minimumEnergy = optimalState->currentEnergy.Sum(); } else delete target; iteration++; } if(verbose) std::cout << "Total states: " << visitedStates.size() << std::endl; //Clean up for (auto state : visitedStates) delete state; } std::cout << std::endl; if (optimalState) { if(verbose) std::cout << "Optimal state: " << optimalState->currentEnergy.Sum() << std::endl; VisualizeState<false>(optimalState, patches, edges, data.Skeleton()->vertices, "optimum.png"); } else if(verbose) std::cout << "No optimal solution exists." << std::endl; }
true