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
b9056ff03b1f233eb08d02c44f8c1623900dde6b
C++
arthurteisseire-epitech/CPP_rtype_2019
/server/src/engine/protocol/TypeProtocol.hpp
UTF-8
884
2.59375
3
[]
no_license
/* ** EPITECH PROJECT, 2019 ** rtype ** File description: ** TypeProtocol.hpp */ #ifndef RTYPE_TYPEPROTOCOL_HPP #define RTYPE_TYPEPROTOCOL_HPP #include <unordered_map> #include <string_view> #include "CBulletType.hpp" namespace ecs { class TypeProtocol { public: enum Type { SHIP_NORMAL, ENEMY_SHIP, ENEMY_SHIP2, ALIEN, ALIEN2, PLAYER_LASER, ENEMY_BLAST1_STAGE1, ENEMY_BLAST1_STAGE2, ENEMY_BLAST1_STAGE3, VORTEX, POWERUP }; static std::string_view get(Type type); static std::string_view get(CBulletType::BulletType type); private: static const std::unordered_map<Type, std::string_view> types; static const std::unordered_map<CBulletType::BulletType, Type> bulletTypes; }; } #endif
true
8cfdeb9f0f03521482f5c8b3fdc4e33fc75b2f2c
C++
theAnton-forks/Competitive-Programming-Portfolio
/Match/src.cpp
UTF-8
761
2.59375
3
[]
no_license
#include <bits/stdc++.h> typedef long long ll; const int maxn = 1e6 + 1e2; int n; std::string s; std::string assigned; bool works(){ std::stack<char> sc; for(int i = 0; i < n; i++){ if(assigned[i] == '('){ sc.push(s[i]); } else if(assigned[i] == ')'){ if(sc.empty() or sc.top() != s[i]){ return false; } sc.pop(); } else if(!sc.empty() and sc.top() == s[i]){ sc.pop(); } else { sc.push(s[i]); } } return sc.empty(); } int main(){ std::ios::sync_with_stdio(false); std::cin >> s; n = s.size(); assigned = std::string(n, '0'); for(int i = 0; i < n; i++){ assigned[i] = '('; if(!works()){ assigned[i] = ')'; } } if(!works()){ std::cout << -1 << '\n'; return 0; } std::cout << assigned << '\n'; }
true
44b2c9e590b58bc4700f5841d97fe931baf83c1f
C++
bieddes-blade/CBS-2021
/ctSolution.h
UTF-8
1,538
2.546875
3
[]
no_license
#ifndef CTSOLUTION_H #define CTSOLUTION_H #include "search.h" #include "ctNode.h" #include "pairVert.h" #include <queue> #include <vector> // a comparator for comparing constraint tree nodes struct CompareCBS { bool operator()(CTNode& one, CTNode& two) { return one.cost < two.cost; } }; // an object for storing a CBS problem and its solution class CTSolution { public: std::priority_queue<CTNode, std::vector<CTNode>, CompareCBS> heap; Map map; std::vector<Agent> agents; std::map<pairVert, int, pvCompare> distMap; bool useDijkstraPrecalc; bool useCAT; std::string heuristic; bool prioritizeConflicts; bool useBypass; bool useFocal; double omega; bool useSymmetry; bool online; std::vector<std::vector<std::pair<int, int>>> goalLocs; int horizon; int replanning; bool printPaths; CTSolution(Map& map_read, std::vector<Agent>& agents_read, bool useDijkstraPrecalc_read, bool useCAT_read, std::string heuristic_read, bool prioritizeConflicts_read, bool useBypass_read, bool useFocal_read, double omega_read, bool useSymmetry_read, bool online_read, std::vector<std::vector<std::pair<int, int>>>& goalLocs_read, int horizon, int replanning, bool printPaths_read); std::map<pairVert, int, pvCompare> dijkstraPrecalc(Map& map); Path lowLevelSearch(CTNode node, int i); std::vector<Path> highLevelSearch(); void solve(); }; #endif
true
67490022b8ee7adb61dbeb47ef8532ffed20edd4
C++
welkin-qing/C
/c语言代码/其他/指向指针.cpp
UTF-8
273
2.84375
3
[]
no_license
#include<stdio.h> main() { char *name[]={"forgive", "forget", "remeber", "togher" }; char **p=name; printf("%s\n",*p); printf("%c\n",**p); printf("%s\n",*(p+1)); printf("%c",*(*(p+1)+2)); }
true
061d61638ca260099f75fa2534eb5c7451b37da1
C++
exnotime/NaiveEngine
/source/gfx/MaterialBank.cpp
UTF-8
4,204
2.5625
3
[]
no_license
#include "MaterialBank.h" #include <fstream> #include <assimp/scene.h> #include "Model.h" #include "Material.h" #include "gfxutility.h" gfx::MaterialBank::MaterialBank() { } gfx::MaterialBank::~MaterialBank() { ClearMaterials(); } gfx::MaterialBank& gfx::MaterialBank::GetInstance() { static MaterialBank m_Bank; return m_Bank; } void gfx::MaterialBank::Initialize(){ m_DefaultAlbedo = LoadTexture("asset/texture/whitePixel.png", TEXTURE_COLOR); m_DefaultNormal = LoadTexture("asset/texture/normal.dds", TEXTURE_COLOR); m_DefaultRoughness = LoadTexture("asset/texture/roughness.png", TEXTURE_GREYSCALE); m_DefaultMetal = LoadTexture("asset/texture/metal.png", TEXTURE_GREYSCALE); } void gfx::MaterialBank::LoadMaterials(Model& model, std::string filename, const aiScene* scene) { model.MaterialOffset = (unsigned int)m_Materials.size(); if (scene->mNumMaterials == 0) { Material* defaultMat = new Material(); defaultMat->SetAlbedoTexture(m_DefaultAlbedo); defaultMat->SetNormalTexture(m_DefaultNormal); defaultMat->SetRoughnessTexture(m_DefaultRoughness); defaultMat->SetMetalTexture(m_DefaultMetal); m_Materials.push_back(defaultMat); } for (unsigned int i = 0; i < scene->mNumMaterials; i++) { Material* modelMat = new Material(); const aiMaterial* mat = scene->mMaterials[i]; //get name aiString name; mat->Get(AI_MATKEY_NAME, name); modelMat->SetName(std::string(name.C_Str())); //albedo if (mat->GetTextureCount(aiTextureType_DIFFUSE) > 0) { aiString path; if (mat->GetTexture(aiTextureType_DIFFUSE, 0, &path, NULL, NULL, NULL, NULL, NULL) == AI_SUCCESS) { std::string fullpath = GetDirectoryFromFilePath(filename) + "/" + path.data; modelMat->SetAlbedoTexture(LoadTexture(fullpath.c_str(), TEXTURE_COLOR)); } } else { modelMat->SetAlbedoTexture(m_DefaultAlbedo); } //normal map if (mat->GetTextureCount(aiTextureType_HEIGHT) > 0) { aiString path; if (mat->GetTexture(aiTextureType_HEIGHT, 0, &path, NULL, NULL, NULL, NULL, NULL) == AI_SUCCESS) { std::string fullpath = GetDirectoryFromFilePath(filename) + path.data; modelMat->SetNormalTexture(LoadTexture(fullpath.c_str(), TEXTURE_COLOR)); } } else { modelMat->SetNormalTexture(m_DefaultNormal); } //roughness map if (mat->GetTextureCount(aiTextureType_SPECULAR) > 0) { aiString path; if (mat->GetTexture(aiTextureType_SPECULAR, 0, &path, NULL, NULL, NULL, NULL, NULL) == AI_SUCCESS) { std::string fullpath = GetDirectoryFromFilePath(filename) + path.data; modelMat->SetRoughnessTexture(LoadTexture(fullpath.c_str(), TEXTURE_GREYSCALE)); } } else { modelMat->SetRoughnessTexture(m_DefaultRoughness); } //Metal map if (mat->GetTextureCount(aiTextureType_AMBIENT) > 0) { //use ambient texture as metal map for now aiString path; if (mat->GetTexture(aiTextureType_AMBIENT, 0, &path, NULL, NULL, NULL, NULL, NULL) == AI_SUCCESS) { std::string fullpath = GetDirectoryFromFilePath(filename) + path.data; modelMat->SetMetalTexture(LoadTexture(fullpath.c_str(), TEXTURE_GREYSCALE)); } } else { modelMat->SetMetalTexture(m_DefaultMetal); } m_Materials.push_back(modelMat); } } void gfx::MaterialBank::ClearMaterials() { for (int i = 0; i < m_Materials.size(); i++) { delete m_Materials[i]; } for (int i = 0; i < m_Textures.size(); i++) { delete m_Textures[i]; } m_Materials.clear(); m_MatMap.clear(); } gfx::Material* gfx::MaterialBank::GetMaterial(int matIndex) { if(matIndex == -1) return nullptr; return m_Materials[matIndex]; } gfx::Material* gfx::MaterialBank::GetMaterial(const std::string& name) { std::map<std::string, Material*>::iterator it = m_MatMap.find(name); if(it != m_MatMap.end()) { return m_MatMap[name]; } else return nullptr; } TextureHandle gfx::MaterialBank::LoadTexture(const char* filename, TextureType type) { for (int i = 0; i < m_Textures.size(); ++i){ if (m_Textures[i]->GetFilename() == std::string(filename)) { return i; } } Texture* tex = new Texture(); tex->Init(filename, type); m_Textures.push_back(tex); return m_Numerator++; } gfx::Texture* gfx::MaterialBank::GetTexture(TextureHandle handle) { return m_Textures[handle]; }
true
ccdf89c431a691e500dad5d291f3d2f2449ac75c
C++
i7sharath/geeks4geeks
/Trees/65_SerializeDeserialize.cpp
UTF-8
2,153
3.515625
4
[]
no_license
#include <bits/stdc++.h> using namespace std; struct TreeNode { int data; TreeNode *left,*right; }; TreeNode *createNewNode(int data) { if(data==-1) return NULL; TreeNode *newNode=(TreeNode*)malloc(sizeof(TreeNode)); newNode->data=data; newNode->left=NULL; newNode->right=NULL; return newNode; } TreeNode *createTree(TreeNode *root,vector<int> &vec) { int n=vec.size(); if(n==0) return NULL; queue<TreeNode*> q; root=createNewNode(vec[0]); q.push(root); int i=1; while(i<n && !q.empty()) { TreeNode *temp=q.front(); q.pop(); temp->left=createNewNode(vec[i]); if(temp->left) q.push(temp->left); i++; if(i>=n) break; temp->right=createNewNode(vec[i]); i++; if(temp->right) q.push(temp->right); } return root; } void inorder(TreeNode *root) { if(root==NULL) return; inorder(root->left); cout<<root->data<<" "; inorder(root->right); return; } void SerializeHelper(TreeNode *root,string &data) { if(root==NULL) { data+="null "; return; } data+=to_string(root->data)+" "; SerializeHelper(root->left,data); SerializeHelper(root->right,data); return; } string serialize(TreeNode *root) { string data; if(root==NULL) return data; SerializeHelper(root,data); return data; } TreeNode *DeserializeHelper(vector<string>&vec,int &index) { if(vec[index]=="null") { index++; return NULL; } TreeNode *root=(struct TreeNode*)malloc(sizeof(TreeNode)); root->data=stoi(vec[index++]); root->left=DeserializeHelper(vec,index); root->right=DeserializeHelper(vec,index); return root; } TreeNode* Deserialize(string data) { if(data.size()==0) return NULL; stringstream ss(data); vector<string> vec; string word; while(ss>>word) vec.push_back(word); int index=0; TreeNode *root=DeserializeHelper(vec,index); return root; } int main() { int n; cin>>n; vector<int> vec(n); for(int i=0;i<n;i++) cin>>vec[i]; TreeNode *root1=NULL; root1=createTree(root1,vec); string data=serialize(root1); cout<<data<<endl; TreeNode *root=Deserialize(data); inorder(root); cout<<endl; return 0; }
true
329d0921692fa60868d3e6fb02a6586ea9d2b7ad
C++
loading21th/stl_test
/settest.cpp
UTF-8
989
3.453125
3
[]
no_license
#include <iostream> #include <set> #include<utility> using namespace std; void settest(){ set<int> settest; set<int>::iterator it; set<int>::iterator it1; pair<set<int>::iterator,bool> insetr_pair; if (settest.begin()==settest.end()) { cout<<"this is empty!\n"; } for (int i=1;i<10;i++) { insetr_pair=settest.insert(i); if(insetr_pair.second==true) cout<<"success"<<endl;//不支持数组插入 else cout<<"fail!"<<endl; } for(it=settest.begin();it!=settest.end();it++) cout<<" "<<*it; it=settest.find(4); if(it!=settest.end()) cout<<"\n存在这个元素"<<endl; else cout<<"\n不存在这个元素"<<endl; int n=settest.erase(4); cout<<n<<endl; it=settest.begin(); it1=settest.end(); settest.erase(it);//这里是空类型 不会有返回值 //settest.erase(it,it1);//这样用会出现异常 应该是删除完之后 end()指向删除元素的后一个元素 settest.clear(); if (settest.begin()==settest.end()) { cout<<"this is empty!\n"; } }
true
db75db3c1bc0bf88636321a66fc70fe74f4b420e
C++
akv25710/Coding
/Array/maxLengthBitonic.cpp
UTF-8
623
3.5
4
[]
no_license
#include<iostream> using namespace std; int maxLengthBitonic(int ar[], int low, int high){ if(low>high) return 0; if(low==high) return 1; if(ar[low]<=ar[low+1]) return 1+maxLengthBitonic(ar,low+1,high); if(ar[high]<=ar[high-1]) return 1+maxLengthBitonic(ar,low,high-1); if(ar[low]>ar[low+1]) return maxLengthBitonic(ar,low+1,high); if(ar[high]>ar[high-1]) return maxLengthBitonic(ar,low,high-1); } int main() { int arr[] = {20, 4, 1, 2, 3, 4, 2, 10}; int n = sizeof(arr)/sizeof(arr[0]); printf("\nLength of max length Bitnoic Subarray is %d", maxLengthBitonic(arr, 0, n-1)); return 0; }
true
1699e07d365701786cba0ffcd2ee02b008f6932f
C++
suhwanhwang/problem-solving
/google/2017/qr/c/c.cpp
UTF-8
4,024
2.96875
3
[ "MIT" ]
permissive
#include <iostream> #include <algorithm> #include <string> #include <vector> #include <queue> #include <map> #include <cassert> #include <ctime> using namespace std; typedef long long ll; pair<ll, ll> solution2(ll n, ll k) { auto cmp = [](pair<ll, ll> l, pair<ll, ll> r) { return l.second - l.first < r.second - r.first; }; priority_queue<pair<ll, ll>, vector<pair<ll, ll>>, decltype(cmp)> pq(cmp); pq.push(make_pair(0, n - 1)); int mid; int ls; int rs; for (ll i = 0; i < k; ++i) { auto t = pq.top(); pq.pop(); mid = (t.first + t.second) / 2; ls = mid - t.first; rs = t.second - mid; if (ls > 0) { pq.push(make_pair(t.first, mid - 1)); } if (rs > 0) { pq.push(make_pair(mid + 1, t.second)); } } //cout << max(ls, rs) << " " << min(ls, rs) << endl; return make_pair(max(ls,rs), min(ls,rs)); } pair<ll, ll> solution3(ll n, ll k) { ll ls, rs; priority_queue<ll> q; q.push(n); for (ll i = 0; i < k; ++i) { ll f = q.top(); q.pop(); if (f == 0) { rs = ls = 0; break; } rs = (f - 1) / 2; ls = rs + (f - 1) % 2; q.push(ls); q.push(rs); } //cout << ls << " " << rs << endl; return make_pair(ls, rs); } pair<ll, ll> solution4(ll n, ll k) { ll ls, rs; ll last_i = 0; pair<ll, ll> prev0 = make_pair(n, 1); pair<ll, ll> prev1 = make_pair(n - 1, 0); for (ll i = 1; i <= k / 2; i *= 2) { ll n0 = prev0.first; ll c0 = prev0.second; ll n1 = prev1.first; ll c1 = prev1.second; ll next1 = (n0 - 1) / 2; ll next0 = (n0 - 1) - next1; if (next0 == next1) { prev0.first = next0; prev0.second = c0 * 2; prev1.first = next0 - 1; prev1.second = 0; } else { prev0.first = next0; prev0.second = c0; prev1.first = next1; prev1.second = c0; } if (c1 > 0) { next1 = (n1 - 1) / 2; next0 = (n1 - 1) - next1; if (next0 == next1) { prev1.second += c1 * 2; } else { prev0.second += c1; prev1.second += c1; } } last_i = i; } if (last_i == 0) { rs = (n - 1) / 2; ls = (n - 1) - rs; } else { ll offset = k - last_i * 2; if (offset < prev0.second) { rs = (prev0.first - 1) / 2; ls = (prev0.first - 1) - rs; } else { rs = (prev1.first - 1) / 2; ls = (prev1.first - 1) - rs; } } return make_pair(ls, rs); } pair<ll, ll> solution(ll n, ll k) { map<ll, ll, greater<ll>> m; m[n] = 1; ll pos = 0; while(true) { auto top = m.begin(); ll rs = (top->first - 1) / 2; ll ls = (top->first - 1) - rs; pos += top->second; if (pos >= k) { return make_pair(ls, rs); } else { m[ls] += top->second; m[rs] += top->second; m.erase(top); } } assert("Not found"); } void printSolution(ll n, ll k) { pair<ll, ll> ans = solution(n, k); cout << ans.first << " " << ans.second << endl; } void test(void) { for (ll i = 1; i <= 10000; ++i) { cerr << i << " : "; for (ll j = 1; j <= i; ++j) { pair<ll, ll> ans = solution(i, j); pair<ll, ll> ans3 = solution3(i, j); assert(ans == ans3); } cerr << "OK" << endl; } } int main(int argc, char *argv[]) { // test(); // return 0; clock_t tick = clock(); int t; cin >> t; for (int i = 1; i <= t; ++i) { ll n, k; cin >> n >> k; cout << "Case #" << i << ": "; printSolution(n, k); } cerr << "time = " << clock() - tick << endl; return 0; }
true
7da3d383a56cec7fa5ca612f014c199d53cae66c
C++
AntraJoshi/Programs
/Patterns/Pattern15.cpp
UTF-8
342
2.671875
3
[]
no_license
#include<iostream> using namespace std; int main(){ int i,j,n,k; cin>>n; for(i=0;i<n/2+1;i++){ for(j=0;j<n/2-i;j++) cout<<" "; for(k=1;k<=(i*2)+1;k++) cout<<k; cout<<"\n"; } for(i=0;i<n/2;i++){ for(j=0;j<i+1;j++) cout<<" "; for(k=1;k<=(n/2-i)*2-1;k++) cout<<k; cout<<"\n"; } return 0; }
true
9200743cea6885e2a53ddbdafc24d3e354e6256d
C++
Sefjor/home-light
/sketch_jun05b.ino
UTF-8
1,353
2.609375
3
[]
no_license
#include <SPI.h> #include "nRF24L01.h" #include "RF24.h" RF24 radio(9,10); int role = 1; // 1=tranciever, 2=reciever void setup() { Serial.begin(9600); Serial.println("BEGINNING"); pinMode(7, OUTPUT); radio.begin(); if ( role == 1)//tranciever pinMode(6, INPUT); radio.openWritingPipe(0xF0F0F0E0E1LL); if ( role == 2) //reciever { radio.openReadingPipe(1, 0xF0F0F0E0E1LL); radio.startListening(); } } void loop() { if (role == 1) //tranciever { int sensorVal = digitalRead(6); Serial.print("Sending "); Serial.print(sensorVal); bool ok = radio.write(&sensorVal, sizeof(int)); delay(100); if (ok) Serial.println("ok"); else Serial.println("fail"); } if ( role == 2) //reciever { if ( radio.available() ) { // Dump the payloads until we've gotten everything unsigned long got_time; bool done = false; while (!done) { // Fetch the payload, and see if this was the last one. done = radio.read( &got_time, sizeof(unsigned long) ); //Serial.print("got it: "); Serial.println(got_time); // Delay just a little bit to let the other unit // make the transition to receiver delay(20); } if (got_time == HIGH) digitalWrite(7, HIGH); else digitalWrite(7, LOW); } } }
true
fb56cb9162708ab802a763b27a39c993f3197dfb
C++
trv001/lab3-bst
/Sequence.h
UTF-8
659
3.171875
3
[]
no_license
#pragma once #include "DynamicArray.h" #include "LinkedList.h" template <class T> class Sequence { public: virtual T GetFirst() const = 0; virtual T GetLast() const = 0; virtual T Get(int index) const = 0; virtual int GetLength() const = 0; virtual int GetReserved() const = 0; virtual void Append(T item) = 0; virtual void Prepend(T item) = 0; virtual void InsertAt(T item, int index) = 0; virtual void Set(int index, T value) = 0; virtual Sequence<T>* Concat(Sequence<T>* lst) = 0; virtual Sequence<T>* GetSubsequence(int startIndex, int endIndex) const = 0; };
true
96742d4ab5c30e126253e2e0bdba14e4b5214403
C++
2020lwy/CppPratice
/C++/ref.cpp
UTF-8
336
3.203125
3
[]
no_license
#include <iostream> void print(int &a,int &b){ std::cout << "a = " << a << std::endl; std::cout << "b = " << b << std::endl; a = 1000; b = 120; } int main(void){ int a = 100; int b = 200; print(a,b); std::cout << "a = " << a << std::endl; std::cout << "b = " << b << std::endl; return 0; }
true
f60f10fc0470e6cc28277d9083077483c9ffab53
C++
gdgf/PAT-Practice
/BPAT/Bpat1072_error.cpp
UTF-8
998
2.765625
3
[]
no_license
#include<cstdio> #include<iostream> #include<set> #include<map> using namespace std; struct info{ string name; int data[100]; int count=0; }; int main(){ int N,M; cin>>N>>M; //scanf("%d %d",&N,&M); set<int> goods; for(int i=0;i<M;i++){ int temp; cin>>temp; goods.insert(temp); } int sum=0; //map<string,int> data; info data[N]; int falg[N]={0}; for(int i=0;i<N;i++){ string name; int n; cin>>name>>n; //scanf("%d",&n); int temp[n]; for(int j=0;j<n;j++){ scanf("%d",&temp[j]); if(goods.find(temp[j])){ //货物在其中 info[sum].name=name; info[sum].data[info[sum].count]=temp[j]; info[sum].count++; sum++; } } } cout<<sum<<endl; for(int i=0;i<sum;i++){ cout<<info[i].name<<" "info[i].count<<endl; } system("pause"); return 0; }
true
9157543b826aa8320bbf2134cff6611af1a8d6a9
C++
cbmeeks/CLK
/Machines/AppleII/Video.cpp
UTF-8
3,962
2.671875
3
[ "MIT" ]
permissive
// // Video.cpp // Clock Signal // // Created by Thomas Harte on 14/04/2018. // Copyright 2018 Thomas Harte. All rights reserved. // #include "Video.hpp" using namespace AppleII::Video; namespace { struct ScaledByteFiller { ScaledByteFiller() { VideoBase::setup_tables(); } } throwaway; } VideoBase::VideoBase() : crt_(new Outputs::CRT::CRT(455, 1, Outputs::CRT::DisplayType::NTSC60, 1)) { // Set a composite sampling function that assumes 1bpp input, and uses just 7 bits per byte. crt_->set_composite_sampling_function( "float composite_sample(usampler2D sampler, vec2 coordinate, vec2 icoordinate, float phase, float amplitude)" "{" "uint texValue = texture(sampler, coordinate).r;" "texValue >>= int(icoordinate.x) % 7;" "return float(texValue & 1u);" "}"); crt_->set_integer_coordinate_multiplier(7.0f); // Show only the centre 75% of the TV frame. crt_->set_video_signal(Outputs::CRT::VideoSignal::Composite); crt_->set_visible_area(Outputs::CRT::Rect(0.115f, 0.117f, 0.77f, 0.77f)); } Outputs::CRT::CRT *VideoBase::get_crt() { return crt_.get(); } uint16_t VideoBase::scaled_byte[256]; uint16_t VideoBase::low_resolution_patterns[2][16]; void VideoBase::setup_tables() { for(int c = 0; c < 128; ++c) { const uint16_t value = ((c & 0x01) ? 0x0003 : 0x0000) | ((c & 0x02) ? 0x000c : 0x0000) | ((c & 0x04) ? 0x0030 : 0x0000) | ((c & 0x08) ? 0x0140 : 0x0000) | ((c & 0x10) ? 0x0600 : 0x0000) | ((c & 0x20) ? 0x1800 : 0x0000) | ((c & 0x40) ? 0x6000 : 0x0000); uint8_t *const table_entry = reinterpret_cast<uint8_t *>(&scaled_byte[c]); table_entry[0] = static_cast<uint8_t>(value & 0xff); table_entry[1] = static_cast<uint8_t>(value >> 8); } for(int c = 128; c < 256; ++c) { uint8_t *const source_table_entry = reinterpret_cast<uint8_t *>(&scaled_byte[c & 0x7f]); uint8_t *const destination_table_entry = reinterpret_cast<uint8_t *>(&scaled_byte[c]); destination_table_entry[0] = static_cast<uint8_t>(source_table_entry[0] << 1); destination_table_entry[1] = static_cast<uint8_t>((source_table_entry[1] << 1) | (source_table_entry[0] >> 6)); } for(int c = 0; c < 16; ++c) { // Produce the whole 28-bit pattern that would cover two columns. const int reversed_c = ((c&0x1) ? 0x8 : 0x0) | ((c&0x2) ? 0x4 : 0x0) | ((c&0x4) ? 0x2 : 0x0) | ((c&0x8) ? 0x1 : 0x0); int pattern = 0; for(int l = 0; l < 7; ++l) { pattern <<= 4; pattern |= reversed_c; } // Pack that 28-bit pattern into the appropriate look-up tables. uint8_t *const left_entry = reinterpret_cast<uint8_t *>(&low_resolution_patterns[0][c]); uint8_t *const right_entry = reinterpret_cast<uint8_t *>(&low_resolution_patterns[1][c]); left_entry[0] = static_cast<uint8_t>(pattern);; left_entry[1] = static_cast<uint8_t>(pattern >> 7); right_entry[0] = static_cast<uint8_t>(pattern >> 14); right_entry[1] = static_cast<uint8_t>(pattern >> 21); } } void VideoBase::set_graphics_mode() { use_graphics_mode_ = true; } void VideoBase::set_text_mode() { use_graphics_mode_ = false; } void VideoBase::set_mixed_mode(bool mixed_mode) { mixed_mode_ = mixed_mode; } void VideoBase::set_video_page(int page) { video_page_ = page; } void VideoBase::set_low_resolution() { graphics_mode_ = GraphicsMode::LowRes; } void VideoBase::set_high_resolution() { graphics_mode_ = GraphicsMode::HighRes; } void VideoBase::set_character_rom(const std::vector<uint8_t> &character_rom) { character_rom_ = character_rom; // Bytes in the character ROM are stored in reverse bit order. Reverse them // ahead of time so as to be able to use the same scaling table as for // high-resolution graphics. for(auto &byte : character_rom_) { byte = ((byte & 0x40) ? 0x01 : 0x00) | ((byte & 0x20) ? 0x02 : 0x00) | ((byte & 0x10) ? 0x04 : 0x00) | ((byte & 0x08) ? 0x08 : 0x00) | ((byte & 0x04) ? 0x10 : 0x00) | ((byte & 0x02) ? 0x20 : 0x00) | ((byte & 0x01) ? 0x40 : 0x00) | (byte & 0x80); } }
true
a5de826af90e442e502ef534caabfcc567e885a2
C++
karan-saj/Data_Structure_Practise
/ll_merge.cpp
UTF-8
1,950
3.953125
4
[]
no_license
#include<iostream> using namespace std; struct node // Create linked list structure { int d; node *next; }; node *head=NULL; //Initialise head = NULL node *head1=NULL; //Initialise head1 = NULL node *hed=NULL; class Linked_List { public: void insert(int nu,int c) //Insert node at end of list { if(c==1) { node *temp,*t; temp=create(nu); if(head==NULL) { head=temp; cout<<"\nList was empty. Element inserted at head"; } else { t=head; while(t->next!=NULL) { t=t->next; } t->next=temp; temp->next=NULL; } } else { node *temp,*t; temp=create(nu); if(head1==NULL) { head1=temp; cout<<"\nList was empty. Element inserted at head"; } else { t=head; while(t->next!=NULL) { t=t->next; } t->next=temp; temp->next=NULL; } } } node* create(int nu) // Create a node { node *p=new node; p->d=nu; p->next=NULL; return p; } void display() { node *t; t=head; if(head==NULL) { cout<<"\nThere is no list"; } else { while(t!=NULL) { cout<<t->d<<endl; t=t->next; } } } void del() { node *t,*t1,*n; t=head; t1=head1; n=hed; cout<<endl; while(n->next!=NULL) { if(t!=NULL) { n=t; t=t->next; n=n->next; } if(t1!=NULL) { n=t1; t1=t1->next; n=n->next; } } } }; int main() { Linked_List l; int n,c=0,i=0,v; while(c!=4) { cout<<"\nSelect option :\n1. Insert \n2. Display the list \n3. Merge \n4. End\n"; cin>>c; switch(c) { case 1:{ int f; cout<<"\nSelect option : \n1. First LL\n2. Second LL \n"; cin>>f; cout<<"\nEnter Data : "; cin>>n; l.insert(n,f); break; } case 2: { l.display(); break; } case 3: { l.del(); break; } case 4: { break; } default :{ cout<<"\nInvalid option selected"; break; } } } return 0; }
true
d72e0be13cbf6424ad8071b0a68cf1f87b1022f9
C++
GH2005/myLeetcodeSolutions
/485. Max Consecutive Ones.cpp
UTF-8
312
2.890625
3
[]
no_license
class Solution { public: int findMaxConsecutiveOnes(vector<int>& nums) { int res = 0; int currConsecutive = 0; for (int value : nums) { if (value == 0) currConsecutive = 0; else res = max(res, ++currConsecutive); } return res; } };
true
9aa73ee17498e32049b5f7e507a0a799cf07e6b7
C++
qawbecrdtey/BOJ-sol
/problems/acmicpc_14614.cpp
UTF-8
175
2.625
3
[ "MIT" ]
permissive
#include <iostream> #include <string> using namespace std; int main() { int a, b; string c; cin >> a >> b >> c; if((c.back() - '0') & 1) cout << (a ^ b); else cout << a; }
true
0cd5e2cdb174e42f476d54ec2a840d48aad86ef7
C++
herzbube/libsgfcplusplus
/src/parsing/propertyvaluetypedescriptor/SgfcPropertyComposedValueTypeDescriptor.h
UTF-8
3,670
2.515625
3
[ "Apache-2.0", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
// ----------------------------------------------------------------------------- // Copyright 2020 Patrick Näf (herzbube@herzbube.ch) // // 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. // ----------------------------------------------------------------------------- #pragma once // Project includes #include "../../interface/internal/ISgfcPropertyValueTypeDescriptor.h" // C++ Standard Library includes #include <memory> namespace LibSgfcPlusPlus { /// @brief The SgfcPropertyComposedValueTypeDescriptor class provides an /// implementation of the ISgfcPropertyValueTypeDescriptor interface. /// See the interface header file for documentation. /// /// @ingroup internals /// @ingroup parsing /// /// SgfcPropertyComposedValueTypeDescriptor expresses the fact that for some /// properties the raw SGF property value is composed of two values, separated /// by a colon (":") character. GetDescriptorValueType1() returns a descriptor /// for the value type of the first value, GetDescriptorValueType2() returns a /// descriptor for the value type of the second value. /// /// @note The two descriptors must be SgfcPropertyBasicValueTypeDescriptor /// objects, and their value types must not be SgfcPropertyValueType::None. /// /// Example: The "AP" property value is composed of two SimpleText values /// separated by a ":" character. Both GetDescriptorValueType1() and /// GetDescriptorValueType2() in this case return /// SgfcPropertyBasicValueTypeDescriptor objects which both have the basic /// value type SgfcPropertyValueType::SimpleText. class SgfcPropertyComposedValueTypeDescriptor : public ISgfcPropertyValueTypeDescriptor { public: /// @brief Initializes a newly constructed /// SgfcPropertyComposedValueTypeDescriptor object. /// /// @exception std::logic_error Is thrown if one or both of the two /// descriptor objects are not SgfcPropertyBasicValueTypeDescriptor objects, /// or if the basic value type is SgfcPropertyValueType::None. SgfcPropertyComposedValueTypeDescriptor( std::shared_ptr<ISgfcPropertyValueTypeDescriptor> descriptorValueType1, std::shared_ptr<ISgfcPropertyValueTypeDescriptor> descriptorValueType2); /// @brief Destroys and cleans up the /// SgfcPropertyComposedValueTypeDescriptor object. virtual ~SgfcPropertyComposedValueTypeDescriptor(); virtual SgfcPropertyValueTypeDescriptorType GetDescriptorType() const override; virtual const SgfcPropertyComposedValueTypeDescriptor* ToComposedValueTypeDescriptor() const override; /// @brief Returns an ISgfcPropertyValueTypeDescriptor object that describes /// the value type of the first value. virtual std::shared_ptr<ISgfcPropertyValueTypeDescriptor> GetDescriptorValueType1() const; /// @brief Returns an ISgfcPropertyValueTypeDescriptor object that describes /// the value type of the second value. virtual std::shared_ptr<ISgfcPropertyValueTypeDescriptor> GetDescriptorValueType2() const; private: std::shared_ptr<ISgfcPropertyValueTypeDescriptor> descriptorValueType1; std::shared_ptr<ISgfcPropertyValueTypeDescriptor> descriptorValueType2; }; }
true
aef130e2edd7dc81224fc54671a3ca34353cc30d
C++
Aura-zx/zhx-Leetcode
/LeetCode/215_Kth_Largest_Element_in_an_Array.h
UTF-8
1,011
3.46875
3
[]
no_license
#ifndef KTH_LARGEST_ELEMENT_IN_AN_ARRAY_H #define KTH_LARGEST_ELEMENT_IN_AN_ARRAY_H #include <vector> class Solution_215 { private: void swap(std::vector<int>& nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } int QuickSelect(std::vector<int>& nums, int k, int start, int end) { int pivot = nums[end]; int left = start; int right = end; while (true) { while (nums[left] < pivot && left < right) { left++; } while (nums[right] >= pivot && right > left) { right--; } if (left == right) { break; } swap(nums, left, right); } swap(nums, left, end); if (k == left + 1) { return pivot; } else if (k < left + 1) { return QuickSelect(nums, k, start, left - 1); } else { return QuickSelect(nums, k, left + 1, end); } } public: int findkthLargest(std::vector<int>& nums, int k) { return QuickSelect(nums, nums.size( ) - k+1, 0, nums.size( ) - 1); } }; #endif // !Kth_LARGEST_ELEMENT_IN_AN_ARRAY_H
true
f68a15ba0377e18f12db0d95150afe0d0949644d
C++
jpugliesi/PA6
/Die.h
UTF-8
242
2.8125
3
[]
no_license
//Die.h #ifndef DIE_H #define DIE_H class Die{ private: int numSides; //number of sides on the die public: //constructors Die(); ~Die(); //functions int rollDie(); //generates and returns random value between 1 and 6 }; #endif
true
79b3e7097319c7b3f1a06223937101db1cd4602f
C++
octavio1594/Intermediate-Level-Course-work
/Lab8/Lab8b.cpp
UTF-8
1,084
4.21875
4
[]
no_license
#include <iostream> #include <string> using namespace std; bool isFibonacci(int num); long fib(int n); int main() { int num; cout << "Enter a number (enter a negative number to quit): "; cin >> num; while (num >= 0) { if (isFibonacci(num) == true) cout << "Yes, you got it, " << num << " is a Fibonacci number." << endl; if (isFibonacci(num) == false) cout << "!!!!! Sorry " << num << " is not a Fibonacci number." << endl; cout << "Enter a number (enter a negative number to quit): "; cin >> num; } } //------------------------------------------------------------------------------------------ bool isFibonacci(int num) { int n = 0; while (n < n + 1) { int fibNo = fib(n); if(fibNo == num) return true; if(fibNo > num) return false; n++; } } //----------------------------------------------------------------------------------------- long fib(int n) { if (n == 0) return 0; if ((n == 1)||(n == 2)) return 1; int a = fib(n - 1); int b = fib(n - 2); return a + b; }
true
fe5913bce3cc04eb6c2e6b39657291521fa0eac6
C++
Sackdima/msu_spring_2019
/03/matrix.h
UTF-8
666
3.421875
3
[]
no_license
#pragma once #include <cstdlib> class Matrix { private: size_t rows; size_t columns; int *matrix; public: class Row { private: size_t columns; int *row_ptr; public: Row(int *row, size_t cols); int &operator[](size_t index); const int &operator[](size_t index) const; }; Matrix(size_t rows_count = 1, size_t columns_count = 1); Matrix(const Matrix &m); ~Matrix() { delete[] matrix; } size_t getRows() const; size_t getColumns() const; bool operator==(const Matrix& other) const; bool operator!=(const Matrix& other) const; Matrix &operator*=(const int& a); Row operator[](size_t index); const Row operator[](size_t index) const; };
true
4de00dd77984c7801df776a2461191824d6de44f
C++
Sadman007/DevSkill-Programming-Course---Basic---Public-CodeBank
/DevSkill_CP/Advanced/Batch 3/Class 25/nPr.cpp
UTF-8
865
2.8125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; /** 1) DP optimization --> i) D&C ii) Knuth iii) Alien Trick iv) CHT (Convex Hull Trick) 2) Sibling DP 3) Interval DP 4) Tree DP 5) Graph DP **/ bool checkBit(int n, int pos) { int val = n & (1 << pos); return val > 0; } int setBit(int n, int pos) { return n | (1 << pos); } int bcnt(int mask) { return __builtin_popcount(mask); } int n, r; /// 101011 int dp[12][(1 << 12) + 1]; int f(int pos, int mask) { if(pos >= n) return bcnt(mask) == r; int &ret = dp[pos][mask]; if(ret != -1) return ret; ret = 0; ret += f(pos + 1, mask); /// skip if(checkBit(mask, pos) == 0) ret += (r - bcnt(mask)) * f(pos + 1, setBit(mask, pos)); return ret; } int main() { cin >> n >> r; memset(dp, -1, sizeof(dp)); cout << f(0, 0) << "\n"; return 0; }
true
7930372a04df203ea7ad2fac56f920cdaec766b3
C++
zachnicoll/cpp-video-app
/src/gui/rect/rect.cpp
UTF-8
838
3.125
3
[]
no_license
#include "../gui.hpp" Rect::Rect(float _x1, float _y1, float _x2, float _y2, void (*on_click)()) { x1 = _x1; y1 = _y1; x2 = _x2; y2 = _y2; OnClickFunc = on_click; } void Rect::Draw() { float height = this->y1 - this->y2; glColor3f(1.0, 0.0, 0.0); glBegin(GL_QUADS); // top left glTexCoord2f(0.0f, 1.0f); glVertex3f(this->x1, this->y1, 0.0f); // bottom left glTexCoord2f(0.0f, 0.0f); glVertex3f(this->x1, this->y2, 0.0f); // bottom right glTexCoord2f(1.0f, 0.0f); glVertex3f(this->x2, this->y2, 0.0f); // top right glTexCoord2f(1.0f, 1.0f); glVertex3f(this->x2, this->y1, 0.0f); glEnd(); reset_colour(); } bool Rect::CheckClicked(float x_pos, float y_pos) { if ( x_pos > x1 && x_pos < x2 && y_pos > y1 && y_pos < y2) { return true; } return false; }
true
0dde45f0e687a58d7a88475f64366b47f6b00659
C++
fabianchis/integra
/IntegraTEC/CE-Experience2019/CE-Experience2019.ino
UTF-8
3,218
2.796875
3
[]
no_license
//ESTOS SON LOS LEDS int ledRojo = 10; int ledAzul = 13; int ledVerde = 11; int ledAmarillo = 12; //ESTOS SON LOS BOTONES int botonRojo = 8; int botonAzul = 9; int botonVerde = 7; int botonAmarillo = 6; //ESTOS SON LOS CABLES int cable1 = 3; int cable2 = 5; int cable3 = 2; int cable4 = 4; int contCorrectos = 0; void setup() { Serial.begin(9600); Serial.setTimeout(50); pinMode(ledRojo,OUTPUT); pinMode(ledAzul,OUTPUT); pinMode(ledVerde,OUTPUT); pinMode(ledAmarillo,OUTPUT); pinMode(botonRojo,INPUT); pinMode(botonAzul,INPUT); pinMode(botonVerde,INPUT); pinMode(botonAmarillo,INPUT); pinMode(cable1,INPUT); pinMode(cable2,INPUT); pinMode(cable3,INPUT); pinMode(cable4,INPUT); } void loop() { //ACA SOLO RECIBE UNA DE LAS DOS INSTRUCCIONES "cables" o "simon" if (Serial.available()) { //String data = Serial.readStringUntil('\n'); //String data = "cables"; //clasificar(data); } else{ String data = "simon"; clasificar(data); } } void clasificar(String accion){ if(accion == "simon"){ digitalWrite(ledAmarillo,HIGH); simonDice(); } if(accion == "cables"){ funcionCables(); } else{ loop(); } } void funcionCables(){ if (digitalRead(cable1)==LOW){ Serial.println("correcto"); delay(500); loop(); } if (digitalRead(cable2)==LOW){ Serial.println("Incorrecto"); delay(500); } if (digitalRead(cable3)==LOW){ Serial.println("Incorrecto"); delay(500); } if (digitalRead(cable4)==LOW){ Serial.println("Incorrecto"); delay(500); } else{ funcionCables(); } } void simonDice(){ if (digitalRead(ledRojo)==HIGH && digitalRead(botonAzul) == HIGH){ contCorrectos++; digitalWrite(ledAmarillo,HIGH); digitalWrite(ledVerde,LOW); digitalWrite(ledAzul,LOW); digitalWrite(ledRojo,LOW); simonDice(); } if (digitalRead(ledAmarillo)==HIGH && digitalRead(botonVerde)==HIGH){ contCorrectos++; digitalWrite(ledAzul,HIGH); digitalWrite(ledVerde,LOW); digitalWrite(ledAmarillo,LOW); digitalWrite(ledRojo,LOW); simonDice(); } if(digitalRead(ledVerde)==HIGH && digitalRead(botonAmarillo)==HIGH){ contCorrectos++; digitalWrite(ledRojo,HIGH); digitalWrite(ledAmarillo,LOW); digitalWrite(ledAzul,LOW); digitalWrite(ledVerde,LOW); simonDice(); } if(digitalRead(ledAzul)==HIGH && digitalRead(botonRojo)==HIGH){ contCorrectos++; digitalWrite(ledVerde,HIGH); digitalWrite(ledRojo,LOW); digitalWrite(ledAzul,LOW); digitalWrite(ledAmarillo,LOW); simonDice(); } if (contCorrectos == 5){ Serial.println("correcto"); contCorrectos=0; digitalWrite(ledVerde,LOW); digitalWrite(ledRojo,LOW); digitalWrite(ledAzul,LOW); digitalWrite(ledAmarillo,LOW); loop(); } else{ simonDice(); } }
true
29f65eafff01b8502f6dd0f3a47558684033fc42
C++
cartmanie/leetcode
/algorithms/ValidateBinarySearchTree/Solution.cpp
UTF-8
2,213
3.609375
4
[]
no_license
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isValidBST(TreeNode* root) { if (root == NULL) { return true; } if (root->left && root->right) { return isLeftValid(root,root->left) && isRightValid(root,root->right) && isValidBST(root->left) && isValidBST(root->right); } if (root->left && !root->right) { return isLeftValid(root,root->left) && isValidBST(root->left); } if (!root->left && root->right) { return isRightValid(root,root->right) &&isValidBST(root->right); } return true; } private: //root > all of left bool isLeftValid(TreeNode* root,TreeNode* left) { if (left == NULL) return true; //visitRoot(left); if (!(root->val > left->val)) return false; //visitLeft(left->left); //root->val > all of left->left; if (!isLeftValid(root,left->left)) return false; //visitRight(left->right); //root->val > all of left->right; if (!isLeftValid(root,left->right)) return false; return true; } // root < all of right bool isRightValid(TreeNode* root,TreeNode* right) { if (right == NULL) return true; //visitRoot(right); if (!(root->val < right->val)) return false; //visitLeft(right->left); //root->val < all of right->left; if (!isRightValid(root,right->left)) return false; //visitRight(right->right); //root->val < all of right->right; if (!isRightValid(root,right->right)) return false; return true; } };
true
00f6a087a3c11bd308ecc5081d56d03abcb4d43e
C++
decipher07/Payroll-Mangement
/Project_Payroll_Mangement.cpp
UTF-8
26,545
2.859375
3
[]
no_license
#include <iostream.h> #include <fstream.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <ctype.h> #include <conio.h> #include <dos.h> class MENU { public: void MAIN_MENU(); void EDIT_MENU(); void INTRODUCTION(); } M; class EMPLOYEE { public: void NEW_EMPLOYEE(); void MODIFICATION(); void DELETION(); void DISPLAY(); void LIST(); void SALARY_SLIP(); private: void ADD_RECORD(int, char[], char[], char[], int, int, int, char[], char, char, char, float, float); void MODIFY_RECORD(int, char[], char[], char[], char[], char, char, char, float, float); void DELETE_RECORD(int); int LASTCODE(); int RECORDNO(int); int FOUND_CODE(int); void DISPLAY_RECORD(int); int VALID_DATE(int, int, int); int code, dd, mm, yy; char name[31], address[41], phone[10], desig[21]; char grade, house, conveyence; float loan, basic; } E; void MENU::INTRODUCTION() { cout << "\nWELCOME\n"; cout << "\n*****************\n "; cout << " "; cout << "\nTHIS IS PAYROLL MANAGEMENT SYSTEM OF SAFAL INTERNATIONAL \n "; cout << " "; cout << " "; cout << " "; cout << " "; cout << "\n PRESS ANY KEY TO CONTINUE....\n"; getch(); clrscr(); gotoxy(8, 2); cout << " ABOUT THE COMPANY \n\n"; cout << " The Company SAFAL INTERNATIONAL was established.\n"; cout << " in the year 1997,the prime business of company \n"; cout << " is distribution of MEDICINES.\n"; cout << " The company has been a leading company in\n"; cout << " and is striving to continue the tradition"; gotoxy(2, 25); cout << "PRESS ANY KEY TO CONTINUE ...."; getch(); clrscr(); } void MENU::MAIN_MENU() { char ch; while (1) { clrscr(); gotoxy(28, 8); cout << "SAFAL INTERNATIONAL\n "; gotoxy(20, 9); cout << "************************************"; gotoxy(30, 11); cout << "1: NEW EMPLOYEE"; gotoxy(30, 12); cout << "2: DISPLAY EMPLOYEE"; gotoxy(30, 13); cout << "3: LIST OF EMPLOYEES"; gotoxy(30, 14); cout << "4: SALARY SLIP"; gotoxy(30, 15); cout << "5: EDIT"; gotoxy(30, 16); cout << "0: QUIT"; gotoxy(30, 18); cout << "ENTER YOUR CHOICE :"; ch = getch(); if (ch == 27 || ch == '0') break; else if (ch == '1') E.NEW_EMPLOYEE(); else if (ch == '2') E.DISPLAY(); else if (ch == '3') E.LIST(); else if (ch == '4') E.SALARY_SLIP(); else if (ch == '5') EDIT_MENU(); } } void MENU::EDIT_MENU() { char ch; while (1) { clrscr(); gotoxy(31, 9); cout << "E D I T M E N U"; gotoxy(30, 13); cout << "1: DELETE RECORD"; gotoxy(30, 14); cout << "2: MODIFY RECORD"; gotoxy(30, 15); cout << "0: EXIT"; gotoxy(30, 17); cout << "ENTER YOUR CHOICE :"; ch = getch(); if (ch == 27 || ch == '0') break; else if (ch == '1') E.DELETION(); else if (ch == '2') E.MODIFICATION(); } } void EMPLOYEE::ADD_RECORD(int ecode, char ename[31], char eaddress[41], char ephone[10], int d, int m, int y, char edesig[21], char egrade, char ehouse, char econv, float eloan, float ebasic) { fstream file; file.open("EMPLOYEE.dat", ios::app); code = ecode; strcpy(name, ename); strcpy(address, eaddress); strcpy(phone, ephone); dd = d; mm = m; yy = y; strcpy(desig, edesig); grade = egrade; house = ehouse; conveyence = econv; loan = eloan; basic = ebasic; file.write((char * ) this, sizeof(EMPLOYEE)); file.close(); } void EMPLOYEE::MODIFY_RECORD(int ecode, char ename[31], char eaddress[41], char ephone[10], char edesig[21], char egrade, char ehouse, char econv, float eloan, float ebasic) { int recno; recno = RECORDNO(ecode); fstream file; file.open("EMPLOYEE.DAT", ios::out | ios::ate); strcpy(name, ename); strcpy(address, eaddress); strcpy(phone, ephone); strcpy(desig, edesig); grade = egrade; house = ehouse; conveyence = econv; loan = eloan; basic = ebasic; int location; location = (recno - 1) * sizeof(EMPLOYEE); file.seekp(location); file.write((char * ) this, sizeof(EMPLOYEE)); file.close(); } void EMPLOYEE::DELETE_RECORD(int ecode) { fstream file; file.open("EMPLOYEE.DAT", ios:: in ); fstream temp; temp.open("temp.dat", ios::out); file.seekg(0, ios::beg); while (!file.eof()) { file.read((char * ) this, sizeof(EMPLOYEE)); if (file.eof()) break; if (code != ecode) temp.write((char * ) this, sizeof(EMPLOYEE)); } file.close(); temp.close(); file.open("EMPLOYEE.dat", ios::out); temp.open("temp.dat", ios:: in ); temp.seekg(0, ios::beg); while (!temp.eof()) { temp.read((char * ) this, sizeof(EMPLOYEE)); if (temp.eof()) break; file.write((char * ) this, sizeof(EMPLOYEE)); } file.close(); temp.close(); } int EMPLOYEE::LASTCODE() { fstream file; file.open("EMPLOYEE.dat", ios:: in ); file.seekg(0, ios::beg); int count = 0; while (file.read((char * ) this, sizeof(EMPLOYEE))) count = code; file.close(); return count; } int EMPLOYEE::FOUND_CODE(int ecode) { fstream file; file.open("EMPLOYEE.dat", ios:: in ); file.seekg(0, ios::beg); int found = 0; while (file.read((char * ) this, sizeof(EMPLOYEE))) { if (code == ecode) { found = 1; break; } } file.close(); return found; } int EMPLOYEE::RECORDNO(int ecode) { fstream file; file.open("EMPLOYEE.dat", ios:: in ); file.seekg(0, ios::beg); int recno = 0; while (file.read((char * ) this, sizeof(EMPLOYEE))) { recno++; if (code == ecode) break; } file.close(); return recno; } void EMPLOYEE::LIST() { clrscr(); int row = 6, found = 0, flag = 0; char ch; gotoxy(31, 2); cout << "LIST OF EMPLOYEES"; gotoxy(30, 3); cout << "~~~~~~~~~~~~~~~~~~~"; gotoxy(1, 4); cout << "CODE NAME PHONE DOJ DESIGNATION GRADE SALARY"; gotoxy(1, 5); cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"; fstream file; file.open("EMPLOYEE.dat", ios:: in ); file.seekg(0, ios::beg); while (file.read((char * ) this, sizeof(EMPLOYEE))) { flag = 0; found = 1; gotoxy(2, row); cout << code; gotoxy(6, row); cout << name; gotoxy(31, row); cout << phone; gotoxy(40, row); cout << dd << "/" << mm << "/" << yy; gotoxy(52, row); cout << desig; gotoxy(69, row); cout << grade; if (grade != 'E') { gotoxy(74, row); cout << basic; } else { gotoxy(76, row); cout << "-"; } if (row == 23) { flag = 1; row = 6; gotoxy(1, 25); cout << "Press any key to continue or Press<ESC> to exit"; ch = getch(); if (ch == 27) break; clrscr(); } else row++; } if (!found) { gotoxy(5, 10); cout << "\7Records not found"; } if (!flag) { gotoxy(1, 25); cout << "Press any key to continue..."; getch(); } file.close(); } void EMPLOYEE::DISPLAY_RECORD(int ecode) { fstream file; file.open("EMPLOYEE.dat", ios:: in ); file.seekg(0, ios::beg); while (file.read((char * ) this, sizeof(EMPLOYEE))) { if (code == ecode) { gotoxy(5, 5); cout << "Employee Code # " << code; gotoxy(5, 6); cout << "~~~~~~~~~~~~~"; gotoxy(5, 7); cout << "Name : " << name; gotoxy(5, 8); cout << "Address : " << address; gotoxy(5, 9); cout << "Phone no. : " << phone; gotoxy(5, 11); cout << "JOINING DATE"; gotoxy(5, 12); cout << "~~~~~~~~~~~~"; gotoxy(5, 13); cout << "Day : " << dd; gotoxy(5, 14); cout << "Month : " << mm; gotoxy(5, 15); cout << "Year : " << yy; gotoxy(5, 17); cout << "Designation :" << desig; gotoxy(5, 18); cout << "Grade :" << grade; if (grade != 'E') { gotoxy(5, 19); cout << "House (y/n) : " << house; gotoxy(5, 20); cout << "Conveyence (y/n) : " << conveyence; gotoxy(5, 22); cout << "Basic Salary : " << basic; } gotoxy(5, 21); cout << "Loan : " << loan; } } file.close(); } void EMPLOYEE::NEW_EMPLOYEE() { clrscr(); char ch, egrade, ehouse = 'N', econv = 'N'; char ename[31], eaddress[41], ephone[10], edesig[21], t1[10]; float t2 = 0.0, eloan = 0.0, ebasic = 0.0; int d, m, y, ecode, valid; gotoxy(72, 2); cout << "<0>=EXIT"; gotoxy(28, 3); cout << "ADDITION OF NEW EMPLOYEE"; gotoxy(5, 5); cout << "Employee Code # "; gotoxy(5, 6); cout << "~~~~~~~~~~~~~"; gotoxy(5, 7); cout << "Name :"; gotoxy(5, 8); cout << "Address :"; gotoxy(5, 9); cout << "Phone no. :"; gotoxy(5, 11); cout << "JOINING DATE"; gotoxy(5, 12); cout << "~~~~~~~~~~~~"; gotoxy(5, 13); cout << "Day :"; gotoxy(5, 14); cout << "Month :"; gotoxy(5, 15); cout << "Year :"; gotoxy(5, 17); cout << "Designation:"; gotoxy(5, 18); cout << "Grade :"; gotoxy(5, 21); cout << "Loan :"; ecode = LASTCODE() + 1; gotoxy(21, 5); cout << ecode; do { valid = 1; gotoxy(5, 25); clreol(); cout << "Enter the name of the Employee"; gotoxy(20, 7); clreol(); gets(ename); strupr(ename); if (ename[0] == '0') return; if (strlen(ename) < 1 || strlen(ename) > 30) { valid = 0; gotoxy(5, 25); clreol(); cout << "\7Enter correctly (Range: 1..30)"; getch(); } } while (!valid); do { valid = 1; gotoxy(5, 25); clreol(); cout << "Enter Address of the Employee"; gotoxy(20, 8); clreol(); gets(eaddress); strupr(eaddress); if (eaddress[0] == '0') return; if (strlen(eaddress) < 1 || strlen(eaddress) > 40) { valid = 0; gotoxy(5, 25); clreol(); cout << "\7Enter correctly (Range: 1..40)"; getch(); } } while (!valid); do { valid = 1; gotoxy(5, 25); clreol(); cout << "Enter Phone no. of the Employee or Press <ENTER> for none"; gotoxy(20, 9); clreol(); gets(ephone); if (ephone[0] == '0') return; if ((strlen(ephone) < 7 && strlen(ephone) > 0) || (strlen(ephone) > 10)) { valid = 0; gotoxy(5, 25); clreol(); cout << "\7Enter correctly"; getch(); } } while (!valid); if (strlen(ephone) == 0) strcpy(ephone, "-"); char tday[3], tmonth[3], tyear[5]; int td; do { valid = 1; do { gotoxy(5, 25); clreol(); cout << "ENTER DAY OF JOINING"; gotoxy(13, 13); clreol(); gets(tday); td = atoi(tday); d = td; if (tday[0] == '0') return; } while (d == 0); do { gotoxy(5, 25); clreol(); cout << "ENTER MONTH OF JOINING"; gotoxy(13, 14); clreol(); gets(tmonth); td = atoi(tmonth); m = td; if (tmonth[0] == '0') return; } while (m == 0); do { gotoxy(5, 25); clreol(); cout << "ENTER YEAR OF JOINING"; gotoxy(13, 15); clreol(); gets(tyear); td = atoi(tyear); y = td; if (tyear[0] == '0') return; } while (y == 0); if (d > 31 || d < 1) valid = 0; else if (((y % 4) != 0 && m == 2 && d > 28) || ((y % 4) == 0 && m == 2 && d > 29)) valid = 0; else if ((m == 4 || m == 6 || m == 9 || m == 11) && d > 30) valid = 0; else if (y < 1990 || y > 2020) valid = 0; if (!valid) { valid = 0; gotoxy(5, 25); clreol(); cout << "\7Enter correctly"; getch(); gotoxy(13, 14); clreol(); gotoxy(13, 15); clreol(); } } while (!valid); do { valid = 1; gotoxy(5, 25); clreol(); cout << "Enter Designation of the Employee"; gotoxy(20, 17); clreol(); gets(edesig); strupr(edesig); if (edesig[0] == '0') return; if (strlen(edesig) < 1 || strlen(edesig) > 20) { valid = 0; gotoxy(5, 25); clreol(); cout << "\7Enter correctly (Range: 1..20)"; getch(); } } while (!valid); do { gotoxy(5, 25); clreol(); cout << "Enter Grade of the Employee (A,B,C,D,E){in capitals}"; gotoxy(20, 18); clreol(); egrade = getch(); if (egrade == '0') return; } while (egrade < 'A' || egrade > 'E'); if (egrade != 'E') { gotoxy(5, 19); cout << "House (y/n) : "; gotoxy(5, 20); cout << "Conveyence(y/n): "; gotoxy(5, 22); cout << "Basic Salary : "; do { gotoxy(5, 25); clreol(); cout << "ENTER IF HOUSE ALLOWANCE IS ALLOTED TO EMPLOYEE OR NOT"; gotoxy(22, 19); clreol(); ehouse = getche(); ehouse = toupper(ehouse); if (ehouse == '0') return; } while (ehouse != 'Y' && ehouse != 'N'); do { gotoxy(5, 25); clreol(); cout << "ENTER IF CONVEYENCE ALLOWANCE IS ALLOTED TO EMPLOYEE OR NOT"; gotoxy(22, 20); clreol(); econv = getche(); econv = toupper(econv); if (econv == '0') return; } while (econv != 'Y' && econv != 'N'); } do { valid = 1; gotoxy(5, 25); clreol(); cout << "ENTER LOAN AMOUNT IF ISSUED"; gotoxy(22, 21); clreol(); gets(t1); t2 = atof(t1); eloan = t2; if (eloan > 50000) { valid = 0; gotoxy(5, 25); clreol(); cout << "\7SHOULD NOT GREATER THAN 50000"; getch(); } } while (!valid); if (egrade != 'E') { do { valid = 1; gotoxy(5, 25); clreol(); cout << "ENTER BASIC SALARY OF THE EMPLOYEE"; gotoxy(22, 22); clreol(); gets(t1); t2 = atof(t1); ebasic = t2; if (t1[0] == '0') return; if (ebasic > 50000) { valid = 0; gotoxy(5, 25); clreol(); cout << "\7SHOULD NOT GREATER THAN 50000"; getch(); } } while (!valid); } gotoxy(5, 25); clreol(); do { gotoxy(5, 24); clreol(); cout << "Do you want to save (y/n) "; ch = getche(); ch = toupper(ch); if (ch == '0') return; } while (ch != 'Y' && ch != 'N'); if (ch == 'N') return; ADD_RECORD(ecode, ename, eaddress, ephone, d, m, y, edesig, egrade, ehouse, econv, eloan, ebasic); } void EMPLOYEE::DISPLAY() { clrscr(); char t1[10]; int t2, ecode; gotoxy(72, 2); cout << "<0>=EXIT"; gotoxy(5, 5); cout << "Enter code of the Employee "; gets(t1); t2 = atoi(t1); ecode = t2; if (ecode == 0) return; clrscr(); if (!FOUND_CODE(ecode)) { gotoxy(5, 5); cout << "\7Record not found"; getch(); return; } DISPLAY_RECORD(ecode); gotoxy(5, 25); cout << "Press any key to continue..."; getch(); } void EMPLOYEE::MODIFICATION() { clrscr(); char ch, egrade, ehouse = 'N', econv = 'N'; char ename[31], eaddress[41], ephone[10], edesig[21], t1[10]; float t2 = 0.0, eloan = 0.0, ebasic = 0.0; int ecode, valid; gotoxy(72, 2); cout << "<0>=EXIT"; gotoxy(5, 5); cout << "Enter code of the Employee "; gets(t1); t2 = atoi(t1); ecode = t2; if (ecode == 0) return; clrscr(); if (!FOUND_CODE(ecode)) { gotoxy(5, 5); cout << "\7Record not found"; getch(); return; } gotoxy(72, 2); cout << "<0>=EXIT"; gotoxy(22, 3); cout << "MODIFICATION OF THE EMPLOYEE RECORD"; DISPLAY_RECORD(ecode); do { gotoxy(5, 24); clreol(); cout << "Do you want to modify this record (y/n) "; ch = getche(); ch = toupper(ch); if (ch == '0') return; } while (ch != 'Y' && ch != 'N'); if (ch == 'N') return; clrscr(); fstream file; file.open("EMPLOYEE.DAT", ios:: in ); file.seekg(0, ios::beg); while (file.read((char * ) this, sizeof(EMPLOYEE))) { if (code == ecode) break; } file.close(); gotoxy(5, 5); cout << "Employee Code # " << ecode; gotoxy(5, 6); cout << "~~~~~~~~~~~~~"; gotoxy(40, 5); cout << "JOINING DATE : "; gotoxy(40, 6); cout << "~~~~~~~~~~~~~~"; gotoxy(55, 5); cout << dd << "/" << mm << "/" << yy; gotoxy(5, 7); cout << "Name : "; gotoxy(5, 8); cout << "Address : "; gotoxy(5, 9); cout << "Phone no. : "; gotoxy(5, 10); cout << "Designation : "; gotoxy(5, 11); cout << "Grade : "; gotoxy(5, 14); cout << "Loan : "; do { valid = 1; gotoxy(5, 25); clreol(); cout << "Enter the name of the Employee or <ENTER> FOR NO CHANGE"; gotoxy(20, 7); clreol(); gets(ename); strupr(ename); if (ename[0] == '0') return; if (strlen(ename) > 25) { valid = 0; gotoxy(5, 25); clreol(); cout << "\7Enter correctly (Range: 1..30)"; getch(); } } while (!valid); if (strlen(ename) == 0) { strcpy(ename, name); gotoxy(20, 7); cout << ename; } do { valid = 1; gotoxy(5, 25); clreol(); cout << "Enter Address of the Employee or <ENTER> FOR NO CHANGE"; gotoxy(20, 8); clreol(); gets(eaddress); strupr(eaddress); if (eaddress[0] == '0') return; if (strlen(eaddress) > 30) { valid = 0; gotoxy(5, 25); clreol(); cout << "\7Enter correctly (Range: 1..40)"; getch(); } } while (!valid); if (strlen(eaddress) == 0) { strcpy(eaddress, address); gotoxy(20, 8); cout << eaddress; } do { valid = 1; gotoxy(5, 25); clreol(); cout << "Enter Phone no. of the Employee or or <ENTER> FOR NO CHANGE"; gotoxy(20, 9); clreol(); gets(ephone); if (ephone[0] == '0') return; if ((strlen(ephone) < 7 && strlen(ephone) > 0) || (strlen(ephone) > 9)) { valid = 0; gotoxy(5, 25); clreol(); cout << "\7Enter correctly"; getch(); } } while (!valid); if (strlen(ephone) == 0) { strcpy(ephone, phone); gotoxy(20, 9); cout << ephone; } do { valid = 1; gotoxy(5, 25); clreol(); cout << "Enter Designation of the Employee or <ENTER> FOR NO CHANGE"; gotoxy(20, 10); clreol(); gets(edesig); strupr(edesig); if (edesig[0] == '0') return; if (strlen(edesig) > 15) { valid = 0; gotoxy(5, 25); clreol(); cout << "\7Enter correctly (Range: 1..15)"; getch(); } } while (!valid); if (strlen(edesig) == 0) { strcpy(edesig, desig); gotoxy(20, 10); cout << edesig; } do { gotoxy(5, 25); clreol(); cout << "Enter Grade of the Employee (A,B,C,D,E) or <ENTER> FOR NO CHANGE"; gotoxy(20, 11); clreol(); egrade = getche(); egrade = toupper(egrade); if (egrade == '0') return; if (egrade == 13) { egrade = grade; gotoxy(20, 11); cout << grade; } } while (egrade < 'A' || egrade > 'E'); if (egrade != 'E') { gotoxy(5, 12); cout << "House (y/n) : "; gotoxy(5, 13); cout << "Conveyence (y/n) : "; gotoxy(5, 15); cout << "Basic Salary : "; do { gotoxy(5, 25); clreol(); cout << "ALLOTED HOUSE ALLOWANCE ? or <ENTER> FOR NO CHANGE"; gotoxy(22, 12); clreol(); ehouse = getche(); ehouse = toupper(ehouse); if (ehouse == '0') return; if (ehouse == 13) { ehouse = house; gotoxy(22, 12); cout << ehouse; } } while (ehouse != 'Y' && ehouse != 'N'); do { gotoxy(5, 25); clreol(); cout << "ALLOTED CONVEYENCE ALLOWANCE or <ENTER> FOR NO CHANGE"; gotoxy(22, 13); clreol(); econv = getche(); econv = toupper(econv); if (econv == '0') return; if (econv == 13) { econv = conveyence; gotoxy(22, 13); cout << econv; } } while (econv != 'Y' && econv != 'N'); } do { valid = 1; gotoxy(5, 25); clreol(); cout << "ENTER LOAN AMOUNT or <ENTER> FOR NO CHANGE"; gotoxy(22, 14); clreol(); gets(t1); t2 = atof(t1); eloan = t2; if (eloan > 50000) { valid = 0; gotoxy(5, 25); clreol(); cout << "\7SHOULD NOT GREATER THAN 50000"; getch(); } } while (!valid); if (strlen(t1) == 0) { eloan = loan; gotoxy(22, 14); cout << eloan; } if (egrade != 'E') { do { valid = 1; gotoxy(5, 25); clreol(); cout << "ENTER BASIC SALARY or <ENTER> FOR NO CHANGE"; gotoxy(22, 15); clreol(); gets(t1); t2 = atof(t1); ebasic = t2; if (t1[0] == '0') return; if (ebasic > 50000) { valid = 0; gotoxy(5, 25); clreol(); cout << "\7SHOULD NOT GREATER THAN 50000"; getch(); } } while (!valid); if (strlen(t1) == 0) { ebasic = basic; gotoxy(22, 15); cout << ebasic; } } gotoxy(5, 25); clreol(); do { gotoxy(5, 18); clreol(); cout << "Do you want to save (y/n) "; ch = getche(); ch = toupper(ch); if (ch == '0') return; } while (ch != 'Y' && ch != 'N'); if (ch == 'N') return; MODIFY_RECORD(ecode, ename, eaddress, ephone, edesig, egrade, ehouse, econv, eloan, ebasic); gotoxy(5, 23); cout << "\7Record Modified"; gotoxy(5, 25); cout << "Press any key to continue..."; getch(); } void EMPLOYEE::DELETION() { clrscr(); char t1[10], ch; int t2, ecode; gotoxy(72, 2); cout << "<0>=EXIT"; gotoxy(5, 5); cout << "Enter code of the Employee "; gets(t1); t2 = atoi(t1); ecode = t2; if (ecode == 0) return; clrscr(); if (!FOUND_CODE(ecode)) { gotoxy(5, 5); cout << "\7Record not found"; getch(); return; } gotoxy(72, 2); cout << "<0>=EXIT"; gotoxy(24, 3); cout << "DELETION OF THE EMPLOYEE RECORD"; DISPLAY_RECORD(ecode); do { gotoxy(5, 24); clreol(); cout << "Do you want to delete this record (y/n) "; ch = getche(); ch = toupper(ch); if (ch == '0') return; } while (ch != 'Y' && ch != 'N'); if (ch == 'N') return; DELETE_RECORD(ecode); gotoxy(5, 23); cout << "\7Record Deleted"; gotoxy(5, 25); cout << "Press any key to continue..."; getch(); } int EMPLOYEE::VALID_DATE(int d1, int m1, int y1) { int valid = 1; if (d1 > 31 || d1 < 1) valid = 0; else if (((y1 % 4) != 0 && m1 == 2 && d1 > 28) || ((y1 % 4) == 0 && m1 == 2 && d1 > 29)) valid = 0; else if ((m1 == 4 || m1 == 6 || m1 == 9 || m1 == 11) && d1 > 30) valid = 0; return valid; } void EMPLOYEE::SALARY_SLIP() { clrscr(); char t1[10]; int t2, ecode, valid, d1, m1, y1; gotoxy(72, 2); cout << "<0>=EXIT"; gotoxy(5, 5); cout << "Enter code of the Employee "; gets(t1); t2 = atoi(t1); ecode = t2; if (ecode == 0) return; clrscr(); if (!FOUND_CODE(ecode)) { gotoxy(5, 5); cout << "\7Record not found"; getch(); return; } fstream file; file.open("EMPLOYEE.dat", ios:: in ); file.seekg(0, ios::beg); while (file.read((char * ) this, sizeof(EMPLOYEE))) { if (code == ecode) break; } file.close(); char * mon[12] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "November", "December" }; gotoxy(31, 2); cout << "COSMOS INTERNATIONAL"; gotoxy(34, 4); cout << "SALARY SLIP"; gotoxy(6, 7); cout << "Employee Name : " << name; gotoxy(6, 8); cout << "Designation : " << desig; gotoxy(67, 8); cout << "Grade : " << grade; int days, hours; if (grade == 'E') { do { valid = 1; gotoxy(10, 21); cout << "ENTER NO. OF DAYS WORKED IN THE MONTH "; gotoxy(10, 11); cout << "No. of Days : "; gets(t1); t2 = atof(t1); days = t2; if (!VALID_DATE(days, m1, y1)) { valid = 0; gotoxy(10, 21); cout << "\7ENTER CORRECTLY "; getch(); gotoxy(10, 11); cout << " "; } } while (!valid); do { valid = 1; gotoxy(10, 21); cout << "ENTER NO. OF HOURS WORKED OVER TIME"; gotoxy(10, 13); cout << "No. of hours : "; gets(t1); t2 = atof(t1); hours = t2; if (hours > 8 || hours < 0) { valid = 0; gotoxy(10, 21); cout << "\7ENTER CORRECTLY "; getch(); gotoxy(10, 13); cout << " "; } } while (!valid); gotoxy(10, 21); cout << " "; gotoxy(10, 11); cout << " "; gotoxy(10, 13); cout << " "; } gotoxy(10, 10); cout << "Basic Salary : Rs."; gotoxy(10, 12); cout << "ALLOWANCE"; if (grade != 'E') { gotoxy(12, 13); cout << "HRA : Rs."; gotoxy(12, 14); cout << "CA : Rs."; gotoxy(12, 15); cout << "DA : Rs."; } else { gotoxy(12, 13); cout << "OT : Rs."; } gotoxy(10, 17); cout << "DEDUCTIONS"; gotoxy(12, 18); cout << "LD : Rs."; if (grade != 'E') { gotoxy(12, 19); cout << "PF : Rs."; } gotoxy(10, 21); cout << "NET SALARY Rs."; gotoxy(6, 24); cout << "CASHIER"; gotoxy(68, 24); cout << "EMPLOYEE"; float HRA = 0.0, CA = 0.0, DA = 0.0, PF = 0.0, LD = 0.0, OT = 0.0, allowance, deduction, netsalary; if (grade != 'E') { if (house == 'Y') HRA = (15 * basic) / 100; if (conveyence == 'Y') CA = (2 * basic) / 100; DA = (15 * basic) / 100; PF = (5 * basic) / 100; LD = (5 * loan) / 100; allowance = HRA + CA + DA; deduction = PF + LD; } else { basic = days * 120; LD = (15 * loan) / 100; OT = hours * 150; allowance = OT; deduction = LD; } netsalary = (basic + allowance) - deduction; gotoxy(36, 10); cout << basic; if (grade != 'E') { gotoxy(22, 13); cout << HRA; gotoxy(22, 14); cout << CA; gotoxy(22, 15); cout << DA; gotoxy(22, 19); cout << PF; } else { gotoxy(22, 13); cout << OT; } gotoxy(22, 18); cout << LD; gotoxy(33, 15); cout << "Rs." << allowance; gotoxy(33, 19); cout << "Rs." << deduction; gotoxy(36, 21); cout << netsalary; gotoxy(2, 1); getch(); } void main() { textcolor(0); textbackground(WHITE); clrscr(); MENU m; m.INTRODUCTION(); m.MAIN_MENU(); }
true
229a9acd13c36f70c79d731c0f409366e833ed25
C++
ueclectic/Quiz
/Quiz/player.h
UTF-8
360
2.8125
3
[]
no_license
#pragma once #include <string> namespace quiz { class Player { public: Player(std::string firstName, std::string lastName); ~Player(); std::string getFirstName() const; std::string getLastName() const; int getScore() const; void addPoints(const int points); private: std::string firstName_; std::string lastName_; int score_; }; }
true
2bf228fe63ebcbde1026c0ca7a7d48d402cec388
C++
someonefighting/test
/mytest/StaveDetection.h
UTF-8
1,932
2.59375
3
[]
no_license
#ifndef StaveDetection_HEAD #define StaveDetection_HEAD #include "cv.h" #include "highgui.h" #include <stdio.h> #include <math.h> #include <string.h> #include<vector> #include <iostream> #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "NoteHead.h" #include "StavePeaks.h" #include"StaveParameters.h" #include"YProjection.h" #include "Staves.h" using namespace std; using namespace cv; /** * The <code> StaveDetection </code> class is responsible for detecting all the staves present in a BufferedImage. * Since the stave detection algorithm needs relies on knowing the stave parameters (n1, n2, d1 and d1) along with * the Y-Projection of the image, they need to be passed in the constructor. * <p> * The <code> StaveDetection </code> class is used as follows: * <p> * <code> * StaveDetection sDetection = new StaveDetection(yProj, sParams); <br> * sDetection.setParameters(0.80, 0.80); //This is optional as the StaveThreshold and PeakThreshold are both defaulted to 0.75 <br> * sDetection.locateStaves(); <br> * sDetection.calcNoteDistance(); <br> * </code> */ namespace omr_engine { class StaveDetection { public: StaveDetection(); ~StaveDetection(); double STAVE_THRESHOLD; double PEAK_THRESHOLD; int width; int height; int *bPixels; vector<StavePeaks> localMaxList; StaveParameters staveParams; vector<Staves> staveList; int stavesfound; StaveDetection(YProjection yproj, StaveParameters staveParams); void locateStaves(); void calcNoteDistance(); //iterator begin(); vector<Staves>::iterator getStaveInfo(); void setParameters(double STAVE_THRESHOLD, double PEAK_THRESHOLD); void findLocalMaximums(); vector<StavePeaks>::iterator StaveDetection::getToSamePosition(vector<StavePeaks>::iterator it1, StavePeaks tester); StavePeaks findNextStave(int min, int max, int val, vector<StavePeaks>::iterator iter); }; } #endif
true
2d9355999549a417c730eabaf23d916ee16a60a8
C++
gjones1911/GraphUtilities
/node.h
UTF-8
1,034
2.953125
3
[]
no_license
#include <iostream> #include <cstdio> #include <cmath> #include <string> #include <cstdlib> #include <vector> using namespace std; //a node in a graph class node { public: //public data vector<int> adj; //the adjacent list for the node int v; //the nodes visited field node * next; node * prev; int dist; //distance from start node //functions node(); ~node(); int getIdx(); void* getVal(); void TracePath(node * sn); int idx; //the index in the graph where this node resides void * val; //will hold some form of informaiton }; class graph { public: vector <node *> Graph; void GInit(int num); int Has_cycle(node * np); int Component_number(); int PathFinder(node * sn, node * en); vector<int> shortest(node *sn, node en); void Print(); void Reset(int zo); int Has_cycle(int idx); //will till if a cycle exits void component_cnt(int idx, int cn); //counts # of connected components }; /*Graph functions*/ /*Node functions*/
true
d032d7b00bf74a6b733b5d27a6b1c6f0e4608265
C++
1980744819/ACM-code
/2017.12.28/My-RegexEngine-master/main.cpp
UTF-8
1,103
2.9375
3
[ "Apache-2.0" ]
permissive
#include "RE.h" #include <iostream> using namespace std; int main() { RE re("ab|abcde"); string test_str; test_str = "abcde"; if (re.match(test_str)) cout << test_str << "ƥ��ɹ�" << endl; else cout << test_str << "ƥ�䲻�ɹ�" << endl; test_str = "abcd"; if (re.match(test_str)) cout << test_str << "ƥ��ɹ�" << endl; else cout << test_str << "ƥ�䲻�ɹ�" << endl; test_str = "aadacaaaababcabcabcdabcde"; vector<string> result; if (re.search(test_str, result)) { for (auto it = result.begin(); it != result.end(); ++it) cout << *it << endl; } re.replace("a(b|c)*"); test_str = "abcbcbc"; if (re.match(test_str)) cout << test_str << "ƥ��ɹ�" << endl; else cout << test_str << "ƥ�䲻�ɹ�" << endl; test_str = "abcbcd"; if (re.match(test_str)) cout << test_str << "ƥ��ɹ�" << endl; else cout << test_str << "ƥ�䲻�ɹ�" << endl; test_str = "abcbcdeaaabcbcbccccbacbfew"; if (re.search(test_str, result)) { for (auto it = result.begin(); it != result.end(); ++it) cout << *it << endl; } return 0; }
true
27a9eac930df7da695cd9a21a39d2745e5799bb8
C++
patryk7891/jimp2
/lab4/geometry/Point.cpp
UTF-8
850
3.5
4
[]
no_license
//Definicja znajduje się w pliku Point.cpp #include <cmath> #include <ostream> #include "Point.h" namespace geometry { using ::std::ostream; using ::std::endl; using ::std::pow; using ::std::sqrt; /* Aby wskazać, ze definicja funkcji dotyczy metody danej klasy stosujemy tzw. operator zasięgu - "::" */ //Specjalna inicjalizacja zmiennych. Zmienne są inicjowane //nim zostanie wywołane ciało konstruktora Point::Point() : x_(0), y_(0) { } Point::Point(double x, double y) { x_ = x; y_ = y; } Point::~Point() { } double Point::GetX() const{ return x_; } double Point::GetY() const{ return y_; } double Point::Distance(const Point &other) const { return sqrt(pow(GetX() - other.GetX(), 2) + pow(GetY() - other.GetY(), 2)); } }
true
f196e92d74d782a37dd36fee7f78390f1a31b371
C++
NicoG60/OpenOrganigram
/src/Control/ModInst/f_ModInst_Ope.cpp
UTF-8
2,967
2.515625
3
[]
no_license
//------------------------------------------------------------------------------- /** * @file f_ModInst_Ope.cpp * @brief Fenetre de modification d'une insturction * * @author N.Jarnoux * @author STS IRIS, Lycée Nicolas APPERT, ORVAULT (FRANCE) * @since 04/03/14 * @version 1.0 * @date 04/03/14 * * Classe affichant une interface de modification des propriété d'une instruction "Opération sur une variable" * * Fabrication OpenOrganigram.pro * * @todo Tester si la classe est fonctionnelle * * @bug / */ //------------------------------------------------------------------------------- //===== Headers standards ===== //===== Headers Peros ===== #include "f_ModInst_Ope.h" #include "ui_f_ModInst_Ope.h" /** * Constructeur * * @brief f_ModInst_Ope::f_ModInst_Ope(Inst_Ope * InstructionAModif, QWidget * parent) * @param InstructionAModif Instruction à modifier * @param parent vers le widget parent */ f_ModInst_Ope::f_ModInst_Ope(Inst_Ope * InstructionAModif, QWidget * parent) : QDialog (parent), InstructionAModif (InstructionAModif), ui (new Ui::f_ModInst_Ope) { this->ui->setupUi(this) ; int nIndexCBVar (InstructionAModif->getIndiceVariable()) ; this->ui->CB_Variable->setCurrentIndex(nIndexCBVar) ; switch(InstructionAModif->getOperation()) { case AFFECTER : this->ui->Radio_Affecter->setChecked(true) ; break ; case INCREMENTER : this->ui->Radio_Inc->setChecked(true) ; break ; case DECREMENTER : this->ui->Radio_Dec->setChecked(true) ; break ; case AJOUTER : this->ui->Radio_Ajouter->setChecked(true) ; break ; case SOUSTRAIRE : this->ui->Radio_Soustraire->setChecked(true) ; break ; } } /** * Destructeur de la classe, il met à jour l'instruction avant la destruction * * @brief f_ModInst_Ope::~f_ModInst_Ope() */ f_ModInst_Ope::~f_ModInst_Ope() { delete ui; } /** * Retourne la description de l'operation. C'est à dire la valeur de tous les paramètres necessaires. * * @brief f_ModInst_Ope::~f_ModInst_Ope() */ DescOperation f_ModInst_Ope::getDescription() { DescOperation Retour; TypeOperation Operation ; if(this->ui->Radio_Affecter->isChecked()) { Operation = AFFECTER ; } if(this->ui->Radio_Ajouter->isChecked()) { Operation = AJOUTER ; } if(this->ui->Radio_Dec->isChecked()) { Operation = DECREMENTER ; } if(this->ui->Radio_Inc->isChecked()) { Operation = INCREMENTER ; } if(this->ui->Radio_Soustraire->isChecked()) { Operation = SOUSTRAIRE ; } Retour.nIndiceVariable = this->ui->CB_Variable->currentIndex() ; Retour.Operation = Operation ; Retour.nValeur = this->ui->SB_Valeur->value() ; return Retour ; }
true
8a994c7911e26ff5d2e0167bfd3e56535bfe0914
C++
TinSlam/ProblemSolver
/ProblemSolver/ClassicalSearch/Algorithm/SearchAlgorithm.cpp
UTF-8
353
2.71875
3
[ "Apache-2.0" ]
permissive
#include "SearchAlgorithm.h" std::list<Action*>* SearchAlgorithm::constructPath(SearchNode* node){ std::list<Action*>* path = new std::list<Action*>(); if(node != nullptr){ while(node->getParent() != nullptr){ path->push_front(node->getAction()); SearchNode* temp = node->getParent(); delete(node); node = temp; } } return path; }
true
b86da33e8833a28837b637d99b65311f6c2cfed1
C++
keelimeguy/Darnel-Engine
/Darnel/include/Renderer/Renderer.h
UTF-8
2,550
2.875
3
[]
no_license
#pragma once #include "Window.h" #include "VertexArray.h" #include "VertexBuffer.h" #include "VertexBufferLayout.h" #include "IndexBuffer.h" #include "Shader.h" #include <glm/glm.hpp> namespace darnel { class RendererAPI { public: enum class API { None = 0, OpenGL3 }; virtual void Init() = 0; virtual void SetViewport(uint32_t x, uint32_t y, uint32_t width, uint32_t height) = 0; virtual void SetClearColor(const glm::vec4 &color) = 0; virtual void SetClearColor(float f0 = 0.0f, float f1 = 0.0f, float f2 = 0.0f, float f3 = 1.0f) = 0; virtual void Clear() = 0; virtual void Draw(const VertexArray &va, const IndexBuffer &ib) = 0; inline static API GetAPI() { return s_API; } static std::shared_ptr<RendererAPI> Create(); private: static API s_API; }; class Renderer { public: Renderer() { m_RendererAPI = RendererAPI::Create(); } inline std::shared_ptr<RendererAPI> GetRendererAPI() { return m_RendererAPI; } virtual void Submit(const VertexArray &va, const IndexBuffer &ib, const Shader &shader) { shader.Bind(); m_RendererAPI->Draw(va, ib); } virtual void BeginScene() = 0; virtual void EndScene() = 0; virtual void Terminate(std::vector<std::shared_ptr<Window>> *windows = nullptr) = 0; inline static RendererAPI::API GetAPI() { return RendererAPI::GetAPI(); } static Renderer *Get(); private: std::shared_ptr<RendererAPI> m_RendererAPI; }; class RenderCommand { public: inline static void Init() { Renderer::Get()->GetRendererAPI()->Init(); } inline static void SetViewport(uint32_t x, uint32_t y, uint32_t width, uint32_t height) { Renderer::Get()->GetRendererAPI()->SetViewport(x, y, width, height); } inline static void SetClearColor(const glm::vec4 &color) { Renderer::Get()->GetRendererAPI()->SetClearColor(color); } inline static void SetClearColor(float f0 = 0.0f, float f1 = 0.0f, float f2 = 0.0f, float f3 = 1.0f) { Renderer::Get()->GetRendererAPI()->SetClearColor(f0, f1, f2, f3); } inline static void Clear() { Renderer::Get()->GetRendererAPI()->Clear(); } inline static void Draw(const VertexArray &va, const IndexBuffer &ib) { Renderer::Get()->GetRendererAPI()->Draw(va, ib); } }; }
true
95d3477136a7af6a79fea7dcd20e15dcd570a210
C++
7956968/CameraExperiment
/videoframe.cpp
UTF-8
922
2.78125
3
[]
no_license
#include "videoframe.h" VideoFrame::VideoFrame(QObject *parent): QObject(parent), m_surface(nullptr) { registerMetaType(); } VideoFrame::VideoFrame(const QByteArray & data, const int & width, const int & height, QObject * parent) : VideoFrame(parent) { m_surface.reset(new Surface(data, width, height)); } VideoFrame::~VideoFrame() { } void VideoFrame::registerMetaType() { static bool registered = false; if (!registered) { qRegisterMetaType<VideoFramePtr>("VideoFrame*"); registered = true; } } bool VideoFrame::map(GLuint name) { if (!m_surface) return false; return m_surface->map(name); } void VideoFrame::unmap(GLuint name) { if (!m_surface) return; m_surface->unmap(name); } int VideoFrame::width() { if (!m_surface) return 0; return m_surface->width(); } int VideoFrame::height() { if (!m_surface) return 0; return m_surface->height(); }
true
82357e48c41f1af13568fa64f06310595b6ec51a
C++
harshmehra31/MyCodeTree
/mycodeschool/factorial.cpp
UTF-8
676
3.21875
3
[]
no_license
#include<stdio.h> #include<conio.h> /* Include other headers as needed */ int pow(int a,int b){ int t=1; while(b){ if(a>0){ t*=a; } else if(a<0){ t/=a; } else { return 1; } b--; } return t; }; int main() { int count,i,loop_count,x,number; printf("Enter number of loop-count:\t"); scanf("%d",&loop_count); count=loop_count; while(count){ x=0; printf("\nEnter number:\t"); scanf("%d",&number); for(i=1;i<number;i++) {x+=(number/pow(5,i));} printf("\nNumber of zeroes:\t"); printf("%d\n",x); count--; } getch(); return 0; }
true
ae41218bf423924ddaf3b9087bfa2c98caf23b0c
C++
Alvaro9366/Bomberman
/Source/Jugador.cpp
WINDOWS-1250
3,316
2.953125
3
[]
no_license
#include "../Headers/Jugador.h" #include "../Headers/Escenario.h" Jugador::Jugador(int x, int y) { //Posicin del jugador this->x = x; this->y = y; //Desplazamiento del jugador dx = 0; dy = 0; //Animacin del sprite ancho = 17; alto = 26; indiceX = 0; indiceY = 0; direccion = Direcciones::Ninguna; ultima = Direcciones::Abajo; } Jugador::~Jugador() { } int Jugador::getX() { return x + 2 * 3; } int Jugador::getY() { return y + 15 * 3; } void Jugador::dibujarJugador(Graphics^ g, Bitmap^ bmpJugador, int** matriz) { int i = 3; //Factor de escala CDI = Rectangle(x + 2 * i + dx, y + 15 * i, (ancho - 6) * i - 2, (alto - 15) * i); CAA = Rectangle(x + 2 * i, y + 15 * i + dy, (ancho - 6) * i - 2, (alto - 15) * i); g->DrawRectangle(Pens::Transparent, CDI); g->DrawRectangle(Pens::Transparent, CAA); validarMovimiento(matriz); Rectangle Selector = Rectangle(indiceX * ancho, indiceY * alto, ancho, alto); Rectangle Escala = Rectangle(x, y, ancho * i - 2, alto * i - 2); g->DrawImage(bmpJugador, Escala, Selector, GraphicsUnit::Pixel); x += dx; y += dy; } void Jugador::moverJugador(Graphics^ g, Bitmap^ bmpJugador, int** matriz) { //direccion == Arriba ? ancho = 17 : ancho = 18; if (direccion == Arriba || direccion == Abajo) { ancho = 17; } else { if (direccion == Izquierda || direccion == Derecha) { ancho = 18; } } switch (direccion) { case Direcciones::Arriba: indiceY = 0; if (indiceX >= 0 && indiceX < 3) { indiceX++; } else { indiceX = 0; } dx = 0; dy = -10; ultima = Arriba; break; case Direcciones::Abajo: indiceX = 0; switch (aux) { case 0: case 2: indiceY = 2; aux++; break; case 1: indiceY = 1; aux++; break; case 3: indiceY = 3; aux = 0; break; } dx = 0; dy = 10; ultima = Abajo; break; case Direcciones::Izquierda: indiceY = 3; switch (aux) { case 0: case 2: indiceX = 1; aux++; break; case 1: indiceX = 2; aux++; break; case 3: indiceX = 3; aux = 0; break; } dx = -10; dy = 0; ultima = Izquierda; break; case Direcciones::Derecha: indiceY = 1; switch (aux) { case 0: case 2: indiceX = 1; aux++; break; case 1: indiceX = 2; aux++; break; case 3: indiceX = 3; aux = 0; break; } dx = 10; dy = 0; ultima = Derecha; break; case Direcciones::Ninguna: dx = 0; dy = 0; if (ultima == Direcciones::Arriba) { indiceX = 0; indiceY = 0; } if (ultima == Direcciones::Abajo) { indiceX = 0; indiceY = 2; } if (ultima == Direcciones::Izquierda) { indiceX = 1; indiceY = 3; } if (ultima == Direcciones::Derecha) { indiceX = 1; indiceY = 1; } break; default: break; } dibujarJugador(g, bmpJugador, matriz); } void Jugador::setDireccion(Direcciones direccion) { this->direccion = direccion; } void Jugador::validarMovimiento(int** matriz) { int X{ 0 }; int Y{ 0 }; for (int i{ 0 }; i < filas; i++) { X = 0; for (int j{ 0 }; j < columnas; j++) { Rectangle Bloqueo = Rectangle(X, Y, 50, 50); if (matriz[i][j] == 0 || matriz[i][j] == 1) { if (CDI.IntersectsWith(Bloqueo)) { dx = 0; } if (CAA.IntersectsWith(Bloqueo)) { dy = 0; } } X += 50; } Y += 50; } }
true
2640a83c89f3425e85afde930c27a6253f4d46f6
C++
rpringst/ProjectEulerCPP
/problem9.cpp
UTF-8
735
3.3125
3
[]
no_license
#include <iostream> #include <cmath> #include <vector> struct Triples{ int _a, _b, _c; Triples(int a, int b, int c) : _a(a), _b(b), _c(c) {} int sum() {return _a + _b + _c;} int product() {return _a * _b * _c;} }; bool pSq(int n, double& sq){ sq = sqrt(n); return sq == floor(sq); } int main(void){ std::vector<Triples> ptgn {}; int prod = 0; double k; for(int i = 1; i <= 1000; ++i) for(int j = 1; i + j <= 1000; ++j) if(pSq(i*i + j*j, k)){ Triples t {i, j, (int)k}; ptgn.push_back(t); } for(auto x : ptgn) if(x.sum() == 1000) prod = x.product(); std::cout << prod << std::endl; return 0; }
true
8ee30ef4b0f0f41808945be382e80e19d9457644
C++
ceosss/dsa
/tree/tree.h
UTF-8
1,590
3.875
4
[]
no_license
#include <iostream> #include <queue> using namespace std; class Tree { public: Tree *left; int data; Tree *right; void create(); void inorder(Tree *); void preorder(Tree *); void postorder(Tree *); } * root; Tree *newTreeNode(int n) { Tree *newnode = new Tree(); newnode->left = NULL; newnode->right = NULL; newnode->data = n; return newnode; } void Tree::create() { cout << "Enter root" << endl; int n; cin >> n; Tree *node = newTreeNode(n); root = node; queue<Tree *> q; q.push(node); while (!q.empty()) { Tree *t = q.front(); q.pop(); int n; cout << "Insert to the left of " << t->data << " ?" << endl; cin >> n; if (n != -1) { Tree *newnode = newTreeNode(n); q.push(newnode); t->left = newnode; } cout << "Insert to the right of " << t->data << " ?" << endl; cin >> n; if (n != -1) { Tree *newnode = newTreeNode(n); q.push(newnode); t->right = newnode; } } } void Tree::inorder(Tree *itr) { if (itr) { inorder(itr->left); cout << itr->data << " "; inorder(itr->right); } } void Tree::preorder(Tree *itr) { if (itr) { cout << itr->data << " "; preorder(itr->left); preorder(itr->right); } } void Tree::postorder(Tree *itr) { if (itr) { postorder(itr->left); postorder(itr->right); cout << itr->data << " "; } }
true
57a9fffbbf7411d403d95f51fc29f045dea09622
C++
213519433/Tut2
/Fraction tut/Main.cpp
UTF-8
1,619
3.359375
3
[]
no_license
/***************************** * Fraction Program : Class * *****************************/ #include <iostream> #include <string> #include <math.h> #include "Fractions.h" using namespace std; int main() { int Nunom1, Dnom1, Nunom2, Dnom2; cout << endl << endl << " Testing of Fractions Class" << endl << " ============================" << endl; cout << " Enter first fraction:" << endl << " Numarater(1): "; /* Inputs of first fraction */ cin >> Nunom1; cout << " Denominater(1): "; cin >> Dnom1; cout << endl << " ----------------------------" << endl; cout << " Enter second fraction:" << endl << " Numarater(2): "; /* Inputs of second fraction */ cin >> Nunom2; cout << " Denominater(2): "; cin >> Dnom2; cout << " ----------------------------" << endl; Fractions fract(Nunom1, Dnom1, Nunom2, Dnom2); // Object cout << endl << " " << Nunom1 << " / " << Dnom1 << " + " << Nunom2 << " / " << Dnom2 << " = "; fract.Add(); // ADDITION of fractions results cout << endl << " " << Nunom1 << " / " << Dnom1 << " - " << Nunom2 << " / " << Dnom2 << " = "; fract.Subtract(); // SUBTRACTION of fractions results cout << endl << " " << Nunom1 << " / " << Dnom1 << " * " << Nunom2 << " / " << Dnom2 << " = "; fract.Multiply(); // MULTIPLICATION of fractions results cout << endl << " " << Nunom1 << " / " << Dnom1 << " / " << Nunom2 << " / " << Dnom2 << " = "; fract.Divide(); // DIVISION of fractions results cout << endl << " ----------------------------" << endl; fract.~Fractions(); cout << " ============================" << endl << " **End**" << endl << endl; system("pause"); return 0; }
true
e55236e6f7459c7e11c452729d400ee527e0120e
C++
sp9103/Koistudy_solution
/quiz/Q1.cpp
WINDOWS-1252
503
2.90625
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <time.h> int main(){ srand(time(NULL)); int arr[20]; int ans[20]; for(int i = 0; i < 20; i++){ arr[i] = rand() % 100; printf("%d\t", arr[i]); } // int max; int idx = -1; for(int i = 0; i < 20; i++){ max = -1; for(int j = 0; j < 20; j++){ if(max < arr[j]){ max = arr[j]; idx = j; } } arr[idx] = -1; ans[i] = max; } for(int i = 0; i < 20; i++){ printf("%d\t", ans[i]); } printf("\n"); return 0; }
true
df0f7c347587bc431d8e465c75b3a6133639540a
C++
Apexsf/DES
/des.hpp
GB18030
2,066
3.40625
3
[]
no_license
#ifndef DES_H #define DES_H #include <bitset> #include <vector> #include <iostream> using namespace std; class DES { public: using bit64 = bitset<64>; using bit56 = bitset<56>; using bit48 = bitset<48>; using bit32 = bitset<32>; using bit28 = bitset<28>; DES(bit64 key); //keyйDES vector<bit48> get_subkeys(); //16Կ bit64 encode(bit64 block); //ܺ bit64 decode(bit64 block); //ܺ template<int N> static bitset<N> left_shift_bit(bitset<N> bits, int shift); //Nbitbitset template<int N> static void print_bits(bitset<N> bits); //˳,ӵλλӡbitsetԪ static bit64 permute_block(bit64 block); //Ĵblockû static bit48 bit_select(bit32 bits); //32ΪbitûΪ48Ϊbit static bit32 box_convert(bit48 bits); //S box û static bit32 p_permute(bit32 bits); // Pû private: void make_subkeys(); //Կ bit64 process(bit64 block, bool encode_flag = true); //ܻ߽ܴӿ bit64 m_key; //ʼԿ vector<bit48> m_subkeys = vector<bit48>(16); //Կ }; template<int N> bitset<N> DES::left_shift_bit(bitset<N> bits, int shift) { // bitsetƺ vector<unsigned char> temp(shift, 0); //ڴ洢ʼshiftλõbit for (int i = 0; i < shift; i++) { if (bits[i]) temp[i] = 1; } bits >>= shift; //ƣעbitsetеbitӵλλҪ>> for (int i = 0; i < shift; i++) { //ʼshiftλõbitǵƺbitsĩβѭλ bits[N - shift + i] = (temp[i] == 1); } return bits; } //ӵλλӡbitsʹ template<int N> void DES::print_bits(bitset<N> bits) { for (int i = 0; i < N; i++) { cout << bits[i]; } cout << endl; } #endif
true
3d4bf5506142bac035a9bcefbd02ffa0dd72a61e
C++
andresyusti/Practica04
/proyecto04/enrutador.h
UTF-8
678
2.5625
3
[]
no_license
#ifndef ENRUTADOR_H #define ENRUTADOR_H #include <iostream> #include <string> #include <map> #include <sstream> #include<fstream> #include<ostream> #include <list> #include <cstdlib> #include<time.h> using namespace std; class enrutador { private: map<char,int> router; map<char,int>::iterator it; //map<char, int> router_suma; //map<char, int>::iterator its; public: bool agregar_enlace(char nombre, int costo); bool eliminar_enlace(char nombre); bool modificar_enlace(char nombre, int costo); void imprimir_valores(); void imprimir_tabla(); string numero_menor(string camino, map<char, int> *router_suma); }; #endif // ENRUTADOR_H
true
8ab5c6f1f7f750f1c8d27c7b57c553d874e42b2c
C++
singhdharmveer311/PepCoding
/Level-1/11. Time and Space Complexity/Selection_Sort.cpp
UTF-8
884
3.546875
4
[ "Apache-2.0" ]
permissive
#include <bits/stdc++.h> using namespace std; bool isSmaller(vector<int> &arr, int i, int j) { cout << "Comparing " << arr[i] << " and " << arr[j] << endl; if (arr[i] < arr[j]) { return true; } else { return false; } } void swap(vector<int> &arr, int i, int j) { cout << "Swapping " << arr[i] << " and " << arr[j] << endl; int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } void selectionSort(vector<int> &v){ for(int i=0;i<v.size()-1;i++){ int min=v[i]; int idx=i; for(int j=i+1;j<v.size();j++){ if(isSmaller(v,j,idx)){ min=v[j]; idx=j; } } swap(v,i,idx); } } int main(){ int n; cin >> n; vector<int> v(n); for(int i=0;i<n;i++){ cin >> v[i]; } selectionSort(v); for(auto x:v){ cout << x << endl; } return 0; }
true
fc3d3fbe49d6922497648a8da0c364e8ca9ed82d
C++
pasirin/BTVN
/BTVN/Tuần 2/Untitled-2.cpp
UTF-8
880
3.1875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; struct NS{ int ngay, thang, nam; NS(int ng, int th, int n){ ngay =ng; thang=th; nam = n; };//ham tao co doi NS () {};//ham tao khong doi void nhapdl () { char ch; cin>>ngay>>ch>>thang>>ch>>nam; } }; int sosanh (NS ng1, NS ng2) { if(ng1.nam <ng2.nam) return 1; if(ng2.nam < ng1.nam) return 2; if(ng1.thang <ng2.thang) return 1; if(ng2.thang < ng1.thang) return 2; if(ng1.ngay <ng2.ngay) return 1; if(ng2.ngay <ng1.ngay) return 2; return 0; } main() { NS ngay1; NS ngay2 (2, 4, 2000); ngay1.nhapdl(); if(sosanh (ngay1, ngay2)==1) cout<<"Ban 1 sinh truoc"; else if (sosanh(ngay1,ngay2)==2) cout<<"Ban 2 sinh truoc"; else cout<<"Hai dua cung ngay sinh"; }
true
fd05b6553e77052bd8e1c81cd909ebcf46117a1f
C++
anuragroy11/GeeksForGeeks
/SudoPlacements/Hash/09.CheckContiguous.cpp
UTF-8
673
3.015625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; bool isContiguous(vector<int> a) { int min = *min_element(a.begin(), a.end()); int max = *max_element(a.begin(), a.end()); for (int i = min; i <= max; i++) { if (find(a.begin(), a.end(), i) == a.end()) return false; } return true; } int main() { int t; cin >> t; while (t--) { int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; i++) cin >> a[i]; if (isContiguous(a)) cout << "Yes" << endl; else cout << "No" << endl; } return 0; }
true
7a02709780fc210e9bc7ba10a5b6b56733d0263d
C++
SnowFleur/Coding-Test-Collection
/백트래킹/[백준] 15649 N과M.cpp
UHC
802
3.546875
4
[]
no_license
#include<iostream> #include<vector> /* N: 1 N M: ߺ */ int g_N, g_M; std::vector<int> g_v; std::vector<bool> g_visited; void BackTracking(int curr) { //curr 4̸ if (curr > g_M) { for (const auto& i : g_v) std::cout << i << " "; std::cout << "\n"; return; } //ݺ Ѵ for (int i = 1; i <= g_N; ++i) { //尡 true ƴϸ . true̸ ̹ 湮ߴ. if (g_visited[i] != true) { g_visited[i] = true; g_v.emplace_back(i); BackTracking(curr + 1); //ī͸ Ų. g_v.pop_back(); // ƿ κ g_visited[i] = false; } } } int main() { std::cin >> g_N >> g_M; g_visited.assign(g_N + 1, false); BackTracking(1); //0 }
true
448d70a9b2b9f964b018d15c1fa0b8e0a28ebfae
C++
marcoafo/OpenXLSX
/OpenXLSX/sources/XLDateTime.cpp
UTF-8
7,104
3.21875
3
[ "BSD-3-Clause" ]
permissive
// // Created by Kenneth Balslev on 28/08/2021. // #include "XLDateTime.hpp" #include "XLException.hpp" #include <string> #include <cmath> namespace { /** * @brief * @param year * @return */ bool isLeapYear(int year) { if (year == 1900) return true; if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) return true; return false; } /** * @brief * @param month * @param year * @return */ int daysInMonth(int month, int year) { switch (month) { case 1: return 31; case 2: return (isLeapYear(year) ? 29 : 28); case 3: return 31; case 4: return 30; case 5: return 31; case 6: return 30; case 7: return 31; case 8: return 31; case 9: return 30; case 10: return 31; case 11: return 30; case 12: return 31; default: return 0; } } /** * @brief * @param serial * @return */ int dayOfWeek(double serial) { auto day = static_cast<int32_t>(serial) % 7; return (day == 0 ? 6 : day - 1); } } // namespace namespace OpenXLSX { /** * @details Conctructor. Default implementation. */ XLDateTime::XLDateTime() = default; /** * @details Constructor taking an Excel date/time serial number as an argument. */ XLDateTime::XLDateTime(double serial) : m_serial(serial) { if (serial < 1.0) throw XLDateTimeError("Excel date/time serial number is invalid (must be >= 1.0.)"); } /** * @details Constructor taking a std::tm object as an argument. */ XLDateTime::XLDateTime(const std::tm& timepoint) { // ===== Check validity of tm struct. // ===== Only year, month and day of the month are checked. Other variables are ignored. if (timepoint.tm_year < 0) throw XLDateTimeError("Invalid year. Must be >= 0."); if (timepoint.tm_mon < 0 || timepoint.tm_mon > 11) throw XLDateTimeError("Invalid month. Must be >= 0 or <= 11."); if (timepoint.tm_mday <= 0 || timepoint.tm_mday > daysInMonth(timepoint.tm_mon + 1, timepoint.tm_year + 1900)) throw XLDateTimeError("Invalid day. Must be >= 1 or <= total days in the month."); // ===== Count the number of days for full years past 1900 for (int i = 0; i < timepoint.tm_year; ++i) { m_serial += (isLeapYear(1900 + i) ? 366 : 365); } // ===== Count the number of days for full months of the last year for (int i = 0; i < timepoint.tm_mon; ++i) { m_serial += daysInMonth(i + 1, timepoint.tm_year + 1900); } // ===== Add the number of days of the month, minus one. // ===== (The reason for the 'minus one' is that unlike the other fields in the struct, // ===== tm_day represents the date of a month, whereas the other fields typically // ===== represents the number of whole units since the start). m_serial += timepoint.tm_mday - 1; // ===== Convert hour, minute and second to fraction of a full day. int32_t seconds = timepoint.tm_hour * 3600 + timepoint.tm_min * 60 + timepoint.tm_sec; m_serial += seconds / 86400.0; } /** * @details Constructor taking a unixtime format (seconds since 1/1/1970) as an argument. */ XLDateTime::XLDateTime(time_t unixtime) { // There are 86400 seconds in a day // There are 25569 days between 1/1/1970 and 30/12/1899 (the epoch used by Excel) m_serial = static_cast<double>(unixtime) / 86400 + 25569; } /** * @details Copy constructor. Default implementation. */ XLDateTime::XLDateTime(const XLDateTime& other) = default; /** * @details Move constructor. Default implementation. */ XLDateTime::XLDateTime(XLDateTime&& other) noexcept = default; /** * @details Destructor. Default implementation. */ XLDateTime::~XLDateTime() = default; /** * @details Copy assignment operator. Default implementation. */ XLDateTime& XLDateTime::operator=(const XLDateTime& other) = default; /** * @details Move assignment operator. Default implementation. */ XLDateTime& XLDateTime::operator=(XLDateTime&& other) noexcept = default; /** * @details */ XLDateTime& XLDateTime::operator=(double serial) { XLDateTime temp(serial); std::swap(*this, temp); return *this; } /** * @details */ XLDateTime& XLDateTime::operator=(const std::tm& timepoint) { XLDateTime temp(timepoint); std::swap(*this, temp); return *this; } /** * @details */ XLDateTime::operator std::tm() const { return tm(); } /** * @details Get the time point as an Excel date/time serial number. */ double XLDateTime::serial() const { return m_serial; } /** * @details Get the time point as a std::tm object. */ std::tm XLDateTime::tm() const { // ===== Create and initialize the resulting object. std::tm result {}; result.tm_year = 0; result.tm_mon = 0; result.tm_mday = 0; result.tm_wday = 0; result.tm_yday = 0; result.tm_hour = 0; result.tm_min = 0; result.tm_sec = 0; result.tm_isdst = -1; double serial = m_serial; // ===== Count the number of whole years since 1900. while (true) { auto days = (isLeapYear(result.tm_year + 1900) ? 366 : 365); if (days > serial) break; serial -= days; ++result.tm_year; } // ===== Calculate the day of the year, and the day of the week result.tm_yday = static_cast<int>(serial) - 1; result.tm_wday = dayOfWeek(m_serial); // ===== Count the number of whole months in the year. while (true) { auto days = daysInMonth(result.tm_mon + 1, 1900 + result.tm_year); if (days > serial) break; serial -= days; ++result.tm_mon; } // ===== Calculate the number of days. result.tm_mday = static_cast<int>(serial); serial -= result.tm_mday; // ===== Calculate the number of hours. result.tm_hour = static_cast<int>(serial * 24); serial -= (result.tm_hour / 24.0); // ===== Calculate the number of minutes. result.tm_min = static_cast<int>(serial * 24 * 60); serial -= (result.tm_min / (24.0 * 60.0)); // ===== Calculate the number of seconds. result.tm_sec = static_cast<int>(lround(serial * 24 * 60 * 60)); return result; } } // namespace OpenXLSX
true
06bfd2583685c42fcab170fbf1bd6706443196d8
C++
ramaym13/Arduino
/Modul 1/2a/2a.ino
UTF-8
330
2.796875
3
[]
no_license
int ledred = 12; int i; void setup() { // put your setup code here, to run once: pinMode(ledred, OUTPUT); } void loop() { // put your main code here, to run repeatedly: for(i=0; i<=255; i+=5){ digitalWrite(ledred, i); delay(100); } for(i=255; i>=0; i-=5){ digitalWrite(ledred, i); delay(100); } }
true
98d785945bade9caf09b57809fa6a290928efd4d
C++
USEPA/OME
/include/OMERuntime/omeobjects/EvalTable.h
UTF-8
3,208
2.78125
3
[]
no_license
#pragma once #include "XMLLoadable.h" #include "OMEDefines.h" /** Table of values that can be accessed by Evaluable expressions.*/ class __EXPORT__ EvalTable : public XMLLoadable { public: typedef ARRAY_TYPE<OME_SCALAR> DataArray; ///< Type that contains a list of values. EvalTable(); EvalTable(const STLString & id, const IndVec & dims,const DataArray &data); EvalTable(const STLString & id, const IndVec & dims, const STLString & filepath, const STLString & colName, const DataArray &data); EvalTable(const STLString & id, const IndVec & dims, const STLString & filepath, const STLString & colName); EvalTable(const EvalTable & et); EvalTable(TI2Element* pCurrElem,const STLString & tag, const STLString & filename); EvalTable& operator=(const EvalTable & rhs); virtual ~EvalTable(); /** @return The EvalTable's unique id.*/ inline STLString GetID() const {return m_tblID;} /** @param id The unique id to assign to the EvalTable. */ inline void SetID(const STLString & id) {m_tblID=id; } /** @return path to CSV used to populate EvalTable. */ inline STLString GetFilePath() const { return m_filepath; } /** Set path for loading Table values. @param fp The path to the CSV file. */ inline void SetFilePath(const STLString & fp) { m_filepath = fp; } /** @return name of CSV column containing table values. */ inline STLString GetColumnName() const { return m_colName; } /** Set name of CSV column containing table values. @param cn The name of the column. */ inline void SetColumnName(const STLString & cn) { m_colName = cn; } virtual bool GetValue(OME_SCALAR & val,const unsigned int ind) const; virtual bool GetValue(OME_SCALAR & val,const unsigned int* inds, const unsigned int indCount) const; virtual bool SetValue(const OME_SCALAR & val,const unsigned int ind); virtual bool SetValue(const OME_SCALAR & val,const unsigned int* inds, const unsigned int indCount); unsigned int GetDimensionCount() const; IndVec GetAllDims() const; DataArray GetAllVals() const; virtual STLString GetXMLRepresentation(const unsigned int indent=0,const unsigned int inc=4); virtual const OMEChar* GetXMLTag() const { return "table_data"; } virtual void GetXMLAttributes(StrArray & out) const; virtual void GetXMLSubNodes(StrArray & out,const unsigned int indent=0,const unsigned int inc=4); bool PopulateFromCSV(const STLString & filepath, const STLString & colname); bool PopulateFromCSV(); protected: virtual void GetXMLAttributeMap(XMLAttrVector & out); virtual int PopulateFromComplexElements(TI2Element* pCurrElem,const STLString & tag, const STLString & filename); void Duplicate(const EvalTable & et); bool CheckBounds(const unsigned int* inds, const unsigned int indCount) const; OME_SCALAR ValForIndex(const unsigned int* inds, const unsigned int indCount) const; void SetValAtIndex(const OME_SCALAR val,const unsigned int* inds, const unsigned int indCount); IndVec m_dims; ///< Dimensions used when accessing an element. DataArray m_vals; ///< Raw value storage. STLString m_tblID;///< Unique Identifier for table. STLString m_filepath; ///< Optional path for file. STLString m_colName; ///< Name of column containing values. };
true
bf1b3cfe03da3c806efde2c11a868d1d382c91ec
C++
itiievskyi/42-CPP-Pool
/day00/ex01/Contact.class.hpp
UTF-8
2,119
2.5625
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Contact.class.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: itiievsk <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/09/20 16:08:39 by itiievsk #+# #+# */ /* Updated: 2018/09/20 16:08:41 by itiievsk ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef CONTACT_CLASS_H # define CONTACT_CLASS_H class Contact { public: Contact(void); ~Contact(void); std::string getFirstName(void) const; void setFirstName(std::string firstName); std::string getLastName(void) const; void setLastName(std::string lastName); std::string getNickName(void) const; void setNickName(std::string nickName); std::string getLogin(void) const; void setLogin(std::string login); std::string getAddress(void) const; void setAddress(std::string address); std::string getEmail(void) const; void setEmail(std::string email); std::string getPhone(void) const; void setPhone(std::string phone); std::string getBirthday(void) const; void setBirthday(std::string birthday); std::string getMeal(void) const; void setMeal(std::string meal); std::string getUnderwear(void) const; void setUnderwear(std::string underwear); std::string getSecret(void) const; void setSecret(std::string secret); private: std::string _firstName; std::string _lastName; std::string _nickName; std::string _login; std::string _address; std::string _email; std::string _phone; std::string _birthday; std::string _meal; std::string _underwear; std::string _secret; }; #endif
true
7e8506efc9cfa759c28e6ca80521105221d4ae88
C++
TMalicki/ParticleSystem
/windowSettings.cpp
UTF-8
5,042
2.546875
3
[]
no_license
#include "windowSettings.h" windowSettings::windowSettings(sf::RenderWindow& window, float border) : m_gui{ window }, m_type{ ParticleType::Vertex } { auto windowSize = sf::Vector2f{ static_cast<float>(window.getSize().x), static_cast<float>(window.getSize().y) }; m_activeWindowSize = sf::Vector2f{ windowSize.x - border, windowSize.y }; m_GUIWindowSize = sf::Vector2f{ border, windowSize.y }; m_AirResistanceOn = false; m_FrictionOn = false; m_GravityOn = false; m_WindOn = false; m_LifeTimeOn = false; m_amountChanged = false; } void windowSettings::loadGUI() { m_gui.loadWidgetsFromFile("GUI/SideGUI.txt"); m_GravitySwitch = getGravityButton(); m_FrictionSwitch = getFrictionButton(); m_AirResistanceSwitch = getAirResistanceButton(); m_WindSwitch = getWindSwitch(); m_WindDirection = getWindDirectionKnob(); m_EffectText = getEffectType(); m_LifeTime = getLifeTime(); m_borderType = getBorder(); m_amount = getAmountText(); m_forceRange = getForceRange(); m_ObjectType = getObjectsType(); m_forceVectorRange = sf::Vector2f{ m_forceRange->getSelectionStart(), m_forceRange->getSelectionEnd() }; } std::vector<sf::Vector2f> windowSettings::transitionBorders(const std::vector<sf::Vector2f>& positions) { std::vector<sf::Vector2f> tempPositions = positions; size_t size{}; std::for_each(positions.begin(), positions.end(), [&](auto& position) { if (position.y < 0) tempPositions[size] = sf::Vector2f{ position.x, m_activeWindowSize.y }; else if (position.y > m_activeWindowSize.y) tempPositions[size] = sf::Vector2f{ position.x, 0.0f }; else if (position.x < 0) tempPositions[size] = sf::Vector2f{ m_activeWindowSize.x, position.y }; else if (position.x > m_activeWindowSize.x) tempPositions[size] = sf::Vector2f{ 0.0f, position.y }; size++; }); return tempPositions; } std::vector<size_t> windowSettings::erasingBorders(const std::vector<sf::Vector2f>& positions) { std::vector<sf::Vector2f> tempPositions = positions; std::vector<size_t> toErase{}; size_t index{}; std::for_each(positions.begin(), positions.end(), [&](auto& position) { if (position.y <= 0 || position.y >= m_activeWindowSize.y) toErase.push_back(index); else if (position.x <= 0 || position.x >= m_activeWindowSize.x) toErase.push_back(index); index++; }); return toErase; } std::vector<sf::Vector2f> windowSettings::reboundBorders(const std::vector<sf::Vector2f>& positions, const std::vector<sf::Vector2f>& velocities) { std::vector<sf::Vector2f> tempPositions = positions; std::vector<sf::Vector2f> tempVelocities = velocities; size_t index{}; std::for_each(positions.begin(), positions.end(), [&](auto& position) { if (position.y <= 0 || position.y >= m_activeWindowSize.y) { tempVelocities[index] = sf::Vector2f{ tempVelocities[index].x, -tempVelocities[index].y }; } else if (position.x <= 0 || position.x >= m_activeWindowSize.x) { tempVelocities[index] = sf::Vector2f{ -tempVelocities[index].x, tempVelocities[index].y }; } index++; }); return tempVelocities; } windowSettings::BorderType windowSettings::getBorderType() { BorderType borderType{}; if (m_borderType->getSelectedItem() == "Rebound Border") { borderType = BorderType::ReboundBorder; } else if (m_borderType->getSelectedItem() == "Erasing Border") { borderType = BorderType::ErasingBorder; } else if (m_borderType->getSelectedItem() == "Transition Border") { borderType = BorderType::TransitionBorder; } return borderType; } void windowSettings::updateLogicGUI() { if (m_GravitySwitch->getValue() == 0.0f) m_GravitySwitch->connect("ValueChanged", [&]() { m_GravityOn = true; }); else m_GravitySwitch->connect("ValueChanged", [&]() { m_GravityOn = false; }); if (m_FrictionSwitch->getValue() == 0.0f) m_FrictionSwitch->connect("ValueChanged", [&]() { m_FrictionOn = true; }); else m_FrictionSwitch->connect("ValueChanged", [&]() { m_FrictionOn = false; }); if (m_AirResistanceSwitch->getValue() == 0.0f) m_AirResistanceSwitch->connect("ValueChanged", [&]() { m_AirResistanceOn = true; }); else m_AirResistanceSwitch->connect("ValueChanged", [&]() { m_AirResistanceOn = false; }); if (m_WindSwitch->getValue() == 0.0f) m_WindSwitch->connect("ValueChanged", [&]() { m_WindOn = true; }); else m_WindSwitch->connect("ValueChanged", [&]() { m_WindOn = false; }); if (m_ObjectType->getSelectedItem() == "Vertex") { m_type = ParticleType::Vertex; } else if (m_ObjectType->getSelectedItem() == "Circle") { m_type = ParticleType::CircleShape; }; m_forceRange->connect("RangeChanged", [&]() { m_forceVectorRange = sf::Vector2f{ m_forceRange->getSelectionStart(), m_forceRange->getSelectionEnd() }; }); m_amount->connect("TextChanged", [&]() { auto temp = m_amount->getText(); m_amountChanged = true; }); m_LifeTime->connect("Checked", [&]() { m_LifeTimeOn = true; }); m_LifeTime->connect("unchecked", [&]() { m_LifeTimeOn = false; }); }
true
5ad78dcc7ab8d65849bc1c093364394d4b9e4fa5
C++
kozel-stas/TIIT
/Lab3TIIT/Lab3TIIT/Lab3TIIT.cpp
WINDOWS-1251
2,113
3.203125
3
[]
no_license
// Lab3TIIT.cpp: . // #include "stdafx.h" #include <iostream> #include <string> using namespace std; string *Source, *dopSource,*CutStr1,*CutStr2; int NumberofSource = 0; void Add (string str); void Cut(string str1, string str2); string *Cutting(string str); int main() { setlocale(LC_ALL, "rus"); bool Cycle = true; int What; string str; CutStr1=Cutting("{151561,55,69}"); while (Cycle == true) { cout << " 1- \n 2-\n"; cin >> What; switch (What) { case 1: cout << " ({1,2,6})\n"; cin >> str; Add(str); break; case 2: Cycle = false; break; default: cout << " ."; break; } } } void Add(string str) { dopSource = new string[NumberofSource]; for (int i = 0; i < NumberofSource; i++) { dopSource[i] = Source[i]; } Source = new string[NumberofSource + 1]; for (int i = 0; i < NumberofSource; i++) { Source[i] = dopSource[i]; } dopSource = new string[0]; Source[NumberofSource] = str; NumberofSource++; } string *Cutting(string str) { string *Info; int i1, i2, shet, height, Number = 0; i1 = i2 = 0; height = str.length(); shet = 0; for (int i = 0; i < height; i++) { if (str[i] == ',') shet++; } shet++; Info = new string[shet]; for (int i = 0; i < shet; i++) { if (i == 0) { for (int g = 1; g < height; g++) { if (str[g] == ',') { i1 = g; break; } } Info[Number] = str.substr(1, i1 - 1); Number++; } if (i != shet - 1 && i != 0) { for (int g = i1+1; g < height; g++) { if (str[g] == ',') { i2 = i1; i1 = g; break; } } Info[Number] = str.substr(i1+1, i2-i1-1); Number++; } if (i == shet - 1) { for (int g = i1+1; g < height; g++) { if (str[g] == ',') { i2 = g; break; } } Info[Number] = str.substr(i2+1, height-i2-1); Number++; } } return Info; } void Cut(string str1, string str2) { }
true
138ea9a99988f70931acf26d813e8534b9f4b0a3
C++
kanikakala02/DAA
/week6/problem2.cpp
UTF-8
1,132
3.703125
4
[]
no_license
#include <bits/stdc++.h> using namespace std; vector <int> g[100]; void bfs(int *color,int curr,int src) { queue <int> q; color[src]=curr; q.push(src); while(!q.empty()) { int f=q.front(); q.pop(); if(color[f]==1) curr=2; else curr=1; for(auto j:g[f]) { if(color[j]==0) { q.push(j); color[j]=curr; } } } } bool bipartite(int *color,int curr,int src,int v) { bfs(color,curr,src); int i; for(i=1;i<=v;i++) { for(auto j:g[i]) { if(color[j]==color[i]) return false; } } return true; } int main() { int v,e,i; cout<<"enter the number of vertices "; cin>>v; cout<<"enet rthe number of edges "; cin>>e; int color[v]; cout<<"enter the edge list "; for(i=0;i<e;i++) { int u,v; cin>>u>>v; g[u].push_back(v); g[v].push_back(u); } for(i=1;i<=v;i++) color[i]=0; if(bipartite(color,1,1,v)) cout<<"bipartite"; else cout<<"not bipartite"; }
true
3e7903809c6dae6aac4c67313ade12e263368b19
C++
vincentfiestada/CacheLoadSim.Win32
/Cache Load Sim For Win32/Cache Load Sim For Win32.cpp
UTF-8
3,301
2.90625
3
[]
no_license
// Cache Load Sim For Win32.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "Cache.h" #include <iostream> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { // Initialize vector<DataChunk> MainMemory; int size = 0; int mapalgo = 1; int repalgo = 0; int mainmemsize = 0; unsigned int addresstoload = 0; int tempBuff = 0; // Collect simulation settings from user cout << "Cache Load Simulator (Win32)" << endl; cout << "(c) 2014 Vincent Fiestada" << endl; cout << "See README.txt for more info" << endl; cout << "+++++++++++++++++++++++++++++++++++++" << endl; cout << "SIMULATION SETTINGS:" << endl; cout << "Cache size: (2, 4 or 8)"; cin >> size; // assert if (size != 2 && size != 4 && size != 8) { cout << "ERROR! Cache Size must be either 2, 4 or 8." << endl << "Enter anything to exit simulation" << endl; cin >> tempBuff; return 1; } cout << endl << "Mapping Algorithm ( 0 - Direct, 1 - Set Assoc, 2 - Full Assoc )" << endl; cout << "Enter choice: "; cin >> mapalgo; // assert if (mapalgo < 0 || mapalgo > 2) { cout << "ERROR! Mapping algorithm index out of range" << endl << "Enter anything to exit simulation" << endl; cin >> tempBuff; return 2; } cout << endl << "Replacement Algorithm (0 - FIFO, 1 - LRU, 2 - LFU )" << endl; cout << "Enter choice: "; cin >> repalgo; // assert if (repalgo < 0 || repalgo > 2) { cout << "ERROR! Replacement algorithm index out of range" << endl << "Enter anything to exit simulation" << endl; cin >> tempBuff; return 3; } mainmemsize = size*size; cout << "Main Memory size is " << mainmemsize << endl; cout << "You can load addresses from 0 to " << mainmemsize - 1 << endl; Cache ProcessorCache(size, mapalgo, repalgo, &MainMemory); int dataToPut = 0x00; // Populate Main Memory for (int i = 0; i < 16; i++) { MainMemory.push_back(DataChunk(i, dataToPut)); dataToPut += 0x11; } while (addresstoload != -1) { cout << "Enter address to load ( 0 - " << mainmemsize - 1 << ")" << endl << "Enter -1 to exit" << endl; cin >> addresstoload; // Check for out of range address if (addresstoload >= MainMemory.size()) { cout << "Address is out of range" << endl; continue; } else if (addresstoload < 0) { break; } ProcessorCache.loadAddress(addresstoload); cout << "=======================================" << endl; cout << "Cache Slots: " << endl; for (int i = 0; i < size; i++) { cout << i << " : " << "ref address "; auto addressToShow = ProcessorCache.getAtSlot(i)->Address; auto dataToShow = ProcessorCache.getAtSlot(i)->Data; if (addressToShow < 0) { cout << "NOTHING"; } else { cout << addressToShow; } cout << " : contains "; if (dataToShow < 0) { cout << "NOTHING"; } else { cout << dataToShow; } cout << endl; } cout << "---------------------------------------" << endl; cout << "TOTAL HITS: " << ProcessorCache.getTotalHits() << endl; cout << "TOTAL HIT TIME: " << ProcessorCache.getHitTime() << endl; cout << "TOTAL MISSES: " << ProcessorCache.getTotalMisses() << endl; cout << "TOTAL MISS PENALTY: " << ProcessorCache.getTotalMisses() << endl; cout << "=======================================" << endl; } return 0; }
true
f36e72d398133ce429e11cd4d33bcf1cf54bc051
C++
proqk/Algorithm
/BruteForce/7568 덩치_cpp.cpp
UTF-8
707
3.25
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> using namespace std; bool cmp(pair<int, int>& a, pair<int, int>& b) { if (a.first == b.first) return a.second > b.second; else return a.first > b.first; } int main() { int n; cin >> n; vector<pair<int, int>> v; // v(51)로 범위를 잡아버리면 제대로 출력 안 됨 왜지? for (int i = 0; i < n; i++) { int x, y; cin >> x >> y; v.push_back({ x,y }); } int go = 1; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { //더 큰 게 있으면 등수 다운 if (v[i].first < v[j].first && v[i].second < v[j].second) go++; } cout << go << " "; go = 1; } } //5 //88 186 //60 175 //55 185 //58 183 //46 155
true
4220ac0e7f0d772ca0dd12e83b1c2ca758073b7b
C++
SifuUA/Picine-CPP
/day05/ex00/main.cpp
UTF-8
877
3.078125
3
[]
no_license
#include <iostream> #include "Bureaucrat.h" int main() { Bureaucrat bureaucrat = Bureaucrat("BILL", 145); std::cout << bureaucrat << std::endl; try { for (int i = 0; i < 13; ++i) { bureaucrat.decrement(); } }catch (std::exception &e) { std::cout << "Exception catched from " << bureaucrat.getName() << std::endl; } Bureaucrat bureaucrat1 = Bureaucrat("JACK", 10); std::cout << bureaucrat1 << std::endl; try { for (int i = 0; i < 13; ++i) { bureaucrat1.increment(); } }catch (std::exception &e) { std::cout << "Exception catch from " << bureaucrat1.getName() << std::endl; } Bureaucrat bureaucrat2; try { bureaucrat2 = Bureaucrat("BRED", 0); }catch (std::exception &e) { std::cout << "Exception catched from BRED" << std::endl; } }
true
29120df8af744ee42298b8dee672720baee43bac
C++
vuyyurii/decaffcompiler
/Phase-3/genera.h
UTF-8
745
2.796875
3
[]
no_license
#ifndef CODEGEN_H #define CODEGEN_H #include "ClassDefs.h" class Codegen : public Codegenerator{ public: static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction, const std::string &VarName, string type) { /* Allocates memory for local variables on the stack of the function */ /* Get the builder for current context */ IRBuilder<> TmpB(&TheFunction->getEntryBlock(), TheFunction->getEntryBlock().begin()); AllocaInst* Alloca; if(type == "int"){ Alloca = TmpB.CreateAlloca(Type::getInt32Ty(getGlobalContext()), 0, VarName.c_str()); } else if (type == "boolean"){ Alloca = TmpB.CreateAlloca(Type::getInt1Ty(getGlobalContext()), 0, VarName.c_str()); } return Alloca; } }; #endif /* CODEGEN_H */
true
7b2ac0f07e535aa62b89b4f82f2e8a1c7049f7cc
C++
sequeto/ED2
/Trabalho Fase 2/main.cpp
UTF-8
2,575
2.65625
3
[]
no_license
/** UNIVERSIDADE FEDERAL DE JUIZ DE FORA INSTITUTO DE CIÊNCIAS EXATAS DEPARTAMENTO DA CIẼNCIA DA COMPUTAÇÃO TRABALHO DE ESTRUTURA DE DADOS 2(||) - 2020.3 (ERE) PROF.DR.MARCELO CANIATO RENHE GRUPO: BEATRIZ CUNHA RODRIGUES MAT 201776038 IVANYLSON HONORIO GONÇALVES MAT 201776002 JOÃO PEDRO SEQUETO NASCIMENTO MAT 201776022 main.cpp *** comando pra rodar *** MAC/LINUX: clear && g++ -std=c++11 *.h *.cpp -o main && ./main WINDOWS: cls & g++ -std=c++11 *.h *.cpp -o main & main */ #include <iostream> #include <fstream> #include <string> #include <locale.h> #include <time.h> #include <iomanip> #include <algorithm> #include <chrono> #include <random> #include <vector> // Inclusão dos TADs #include "AVLTree.h" #include "ArvoreB.h" #include "QuadTree.h" #include "City.h" #include "Hash.h" #include "Data_Casos.h" #include "Utils.h" #include "Estatisticas.h" #include "Analise.h" #include "moduloTestes.h" using namespace std; ///***Funções**** /**Cabeçalho**/ void prefacioTrabalho() ///Capa do trabalho { cout << "Trabalho de Estrutura de Dados 2 (UFJF/ICE/DCC) 2020.3(ERE)" << endl; cout << "Grupo:" << endl; cout << "BEATRIZ CUNHA RODRIGUES - MAT 201776038 "<<endl; cout << "IVANYLSON HONORIO GONCALVES - MAT 201776002" <<endl; cout << "JOAO PEDRO SEQUETO NASCIMENTO - MAT 201776022 "<< endl; cout << "Observacao: Para executar o código segue abaixo: " << endl; cout << "MAC/LINUX: clear && g++ -std=c++11 *.h *.cpp -o main && ./main " << endl; cout << "WINDOWS: cls & g++ -std=c++11 *h *.cpp -o main & main " << endl; cout <<endl; } void mainMenu() ///Menu contendo o que foi pedido no relatório { int opcaoN=0; while(opcaoN!=-1) ///Entrando no menu { cout << "Qual das partes do trabalho voce quer executar?" << endl; cout << "(1) - Modulo de Testes:" << endl; cout << "(2) - Analise das estruturas balanceadas:" << endl; cout << "(-1) - Para a saida " << endl; cout << "Numero desejado: "; cin >> opcaoN; /// Ler a opção N cout << endl; switch (opcaoN) { case -1: { exit(0); } case 1: { modulo(); break; } case 2: { analise(); break; } default: /// Caso não seja nenhuma opção válida { cout << "Valor invalido! Insira outro" << endl; } ///Fechando default }///Fechando switch }///Fechando while }///Fechando função mainMenu int main() { prefacioTrabalho(); mainMenu(); return 0; }
true
8c68c08fbad32159411af3dceb4dc031a85990a7
C++
BiteSnail/BaekJoon
/BaekJoon/5052.cpp
UTF-8
1,091
3.046875
3
[]
no_license
#include <iostream> #include <algorithm> #include <string> using namespace std; int T; int N; string phoneNumbers[10010]; typedef struct TRIE{ bool is_end = false; struct TRIE *child[10] = {0, }; }TRIE; //911 bool isPrefix(int I, TRIE *cur, string & phoneNumber){ if(I==phoneNumber.length()){ cur->is_end = true; return false; } int index = (phoneNumber[I] - '0'); if(cur->is_end){ return true; } if((cur->child)[index] == nullptr){ (cur->child)[index] = new TRIE(); } return isPrefix(I+1, (cur->child)[index], phoneNumber); } bool getResult(){ TRIE root; bool result = false; cin >> N; for(int i=0;i<N;i++){ cin >> phoneNumbers[i]; } sort(phoneNumbers, phoneNumbers+N); for(int i=0;i<N;i++){ if(result) break; result = isPrefix(0, &root, phoneNumbers[i]); } return result; } int main(){ cin >> T; for(int i=0;i<T;i++){ if(getResult()) cout<<"NO" << '\n'; else cout<<"YES" <<'\n'; } return 0; }
true
851ad231e25f61e7aa55c1ac8f1ae2bc153028f6
C++
fazhang/myLeetCode
/leetCode/backup/3.cpp
UTF-8
1,001
3.375
3
[]
no_license
https://leetcode.com/problems/longest-substring-without-repeating-characters/ class Solution { public: int lengthOfLongestSubstring(string s) { //最长不重复子串。 一维动态规划 //dp 的定义是, 以当前item 结尾的最长不重复串是多长 int strLen = s.size(); vector<int> dp(strLen,1);//至少是1 //需要一个辅助数组,记录某个字符,最后一次出现的位置 vector<int> charLastIndex(256,-1); int start = 0 ; int maxLen = 0 ; for( int i = 0 ; i < strLen ; i++){ char x = s.at(i); int lastIndex = charLastIndex[int(x)];//这个字符出现的最后一次的位置 if( lastIndex != -1){ start = std::max(lastIndex+1, start); } charLastIndex[x] = i; dp[i] = i - start +1 ; if(dp[i] > maxLen){ maxLen = dp[i]; } } return maxLen; } };
true
801516906225820cbc774a5f340873ecb87aeeb2
C++
pampersrocker/MathLib
/MathLib/MathLibUnitTest/AABBtpl2DTest.cpp
UTF-8
2,836
2.578125
3
[]
no_license
#include "stdafx.hpp" #include "CppUnitTest.h" #include "Vector2.hpp" #include "ClassicalMechanics/Volumes/AABB.hpp" using namespace ClassicalMechanics::Volumes; using namespace Microsoft::VisualStudio::CppUnitTestFramework; template class __declspec ( dllexport )LinearMath::Vector2_tpl< float >; template class __declspec ( dllexport )AABB_tpl< LinearMath::Vector2_tpl< float > >; typedef LinearMath::Vector2_tpl< float > Vector2; typedef AABB_tpl< LinearMath::Vector2_tpl< float > > AABB_tpl2D; namespace MathLibUnitTest { TEST_CLASS( AABB_tpl2DTestClass ) { public: TEST_METHOD( AABBConstructorTest ) { AABB_tpl2D aabb( Vector2( 0.0f, 0.0f ), Vector2( 1.0f, 1.0f ) ); Vector2 min = aabb.Min(); Vector2 max = aabb.Max(); Assert::AreEqual( 0.0f, min.X ); Assert::AreEqual( 0.0f, min.Y ); Assert::AreEqual( 1.0f, max.X ); Assert::AreEqual( 1.0f, max.Y ); aabb = AABB_tpl2D( Vector2( 1.0f, 1.0f ), Vector2( 0.0f, 0.0f ) ); min = aabb.Min(); max = aabb.Max(); Assert::AreEqual( 0.0f, min.X ); Assert::AreEqual( 0.0f, min.Y ); Assert::AreEqual( 1.0f, max.X ); Assert::AreEqual( 1.0f, max.Y ); } TEST_METHOD( AABBIntersectTest ) { AABB_tpl2D aabb1 = AABB_tpl2D( Vector2( 0.0f ), Vector2( 2.0f ) ); AABB_tpl2D aabb2 = AABB_tpl2D( Vector2( 1.0f ), Vector2( 3.0f ) ); AABB_tpl2D aabb3 = AABB_tpl2D( Vector2( 10.0f ), Vector2( 20.0f ) ); Assert::IsTrue( aabb1.Intersects( aabb2 ) ); Assert::IsTrue( aabb2.Intersects( aabb1 ) ); Assert::IsFalse( aabb1.Intersects( aabb3 ) ); Assert::IsFalse( aabb3.Intersects( aabb1 ) ); Assert::IsTrue( aabb1.Intersects( aabb1 ) ); } TEST_METHOD( AABBContainsTest ) { AABB_tpl2D aabb1 = AABB_tpl2D( Vector2( 0.0f ), Vector2( 1.0f ) ); AABB_tpl2D aabb2 = AABB_tpl2D( Vector2( 0.1f ), Vector2( 0.9f ) ); AABB_tpl2D aabb3 = AABB_tpl2D( Vector2( 0.0f ), Vector2( 0.1f, 2.0f ) ); Vector2 point1( 0.5f ); Vector2 point2( 1.0f ); Vector2 point3( 2.0f ); Assert::IsTrue( aabb1.Contains( point1 ) ); Assert::IsTrue( aabb1.Contains( point2 ) ); Assert::IsFalse( aabb1.Contains( point3 ) ); Assert::IsTrue( aabb1.Contains( aabb2 ) ); Assert::IsFalse( aabb1.Contains( aabb3 ) ); } TEST_METHOD( AABBFillBounds ) { AABB_tpl2D aabb( Vector2( 0.0f ), Vector2( 1.0f ) ); Vector2 tmp[ 6 ] = { Vector2( -1.0f ), Vector2( -1.0f ), Vector2( -1.0f ), Vector2( -1.0f ), Vector2( -1.0f ), Vector2( -1.0f ) }; aabb.FillBounds( tmp + 1 ); Assert::IsTrue( tmp[ 0 ] == Vector2( -1.0f ) ); Assert::IsTrue( tmp[ 1 ] == Vector2( 0.0f ) ); Assert::IsTrue( tmp[ 2 ] == Vector2( 1.0f, 0.0f ) ); Assert::IsTrue( tmp[ 3 ] == Vector2( 0.0f, 1.0f ) ); Assert::IsTrue( tmp[ 4 ] == Vector2( 1.0f, 1.0f ) ); Assert::IsTrue( tmp[ 5 ] == Vector2( -1.0f ) ); } }; }
true
ccd21c14c0a31f42ea9472e41e1e88d7bf41ce4e
C++
Etherealblade/CLRS
/Chapter 6/MinHeap/MinHeap/main.cpp
UTF-8
517
3.421875
3
[]
no_license
// MinHeap.cpp : This file contains the 'main' function. Program execution begins and ends there. // https://www.geeksforgeeks.org/binary-heap/ #include <iostream> #include "MinHeap.h" using namespace std; // Driver program to test above functions int main() { MinHeap h(11); h.insertKey(3); h.insertKey(2); h.deleteKey(1); h.insertKey(15); h.insertKey(5); h.insertKey(4); h.insertKey(45); cout << h.extractMin() << " "; cout << h.getMin() << " "; h.decreaseKey(2, 1); cout << h.getMin(); return 0; }
true
2fc3ee8182b0bb1d7c0942cc9db450ab823482a2
C++
andyvans/Arduino
/first-robot/first-robot.ino
UTF-8
3,958
2.953125
3
[]
no_license
#include <Servo.h> //include Servo library const int dangerThresh = 10; //threshold for obstacles (in cm) int leftDistance, rightDistance; //distances on either side Servo panMotor; long duration; //time it takes to recieve PING))) signal #define trigPin 13 #define echoPin 12 // Motor 1 int dir1PinA = 2; int dir2PinA = 3; int speedPinA = 9; // Needs to be a PWM pin to be able to control motor speed // Motor 2 int dir1PinB = 4; int dir2PinB = 5; int speedPinB = 10; // Needs to be a PWM pin to be able to control motor speed void setup() { Serial.begin(9600); //Define L298N Dual H-Bridge Motor Controller Pins pinMode(dir1PinA,OUTPUT); pinMode(dir2PinA,OUTPUT); pinMode(speedPinA,OUTPUT); pinMode(dir1PinB,OUTPUT); pinMode(dir2PinB,OUTPUT); pinMode(speedPinB,OUTPUT); panMotor.attach(6); //attach motors to proper pins panMotor.write(90); //set PING))) pan to center setup_edm(); } void setup_edm() { // distance pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); Motor1(1); Motor2(1); } void loop() { int distanceFwd = Ping(); if (distanceFwd == -1 || distanceFwd > dangerThresh) //if path is clear { //move forward Motor1(1); Motor2(1); } else //if path is blocked { // stop Motor1(0); Motor2(0); panMotor.write(0); delay(500); rightDistance = Ping(); //scan to the right delay(500); panMotor.write(180); delay(700); leftDistance = Ping(); //scan to the left delay(500); panMotor.write(90); //return to center delay(100); compareDistance(); } } void compareDistance() { if (leftDistance > rightDistance) //if left is less obstructed { // turn left Motor1(-1); Motor2(1); delay(500); } else if (rightDistance>leftDistance) //if right is less obstructed { // turn right Motor1(1); Motor2(-1); delay(500); } else //if they are equally obstructed { // turn 180 Motor1(1); Motor2(-1); delay(1000); } } void Motor1(int dir) { switch(dir) { case 1: // Motor 1 Forward analogWrite(speedPinA, 255); digitalWrite(dir1PinA, LOW); digitalWrite(dir2PinA, HIGH); Serial.println("Motor 1 Forward"); Serial.println(" "); break; case 0: // Motor 1 Stop (Freespin) analogWrite(speedPinA, 0); digitalWrite(dir1PinA, LOW); digitalWrite(dir2PinA, LOW); Serial.println("Motor 1 Stop"); Serial.println(" "); break; case -1: // Motor 1 Reverse analogWrite(speedPinA, 255); digitalWrite(dir1PinA, HIGH); digitalWrite(dir2PinA, LOW); Serial.println("Motor 1 Reverse"); Serial.println(" "); break; } } void Motor2(int dir) { switch(dir) { case 1: // Motor 2 Forward analogWrite(speedPinB, 255); digitalWrite(dir1PinB, LOW); digitalWrite(dir2PinB, HIGH); Serial.println("Motor 2 Forward"); Serial.println(" "); break; case 0: // Motor 1 Stop (Freespin) analogWrite(speedPinB, 0); digitalWrite(dir1PinB, LOW); digitalWrite(dir2PinB, LOW); Serial.println("Motor 2 Stop"); Serial.println(" "); break; case -1: // Motor 2 Reverse analogWrite(speedPinB, 255); digitalWrite(dir1PinB, HIGH); digitalWrite(dir2PinB, LOW); Serial.println("Motor 2 Reverse"); Serial.println(" "); break; } } long Ping() { long duration, distance, returnValue; digitalWrite(trigPin, LOW); // Added this line delayMicroseconds(2); // Added this line digitalWrite(trigPin, HIGH); delayMicroseconds(10); // Added this line digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH); distance = (duration/2) / 29.1; if (distance > 200) { returnValue = -1; } else { returnValue = distance; } Serial.print(returnValue); Serial.println(" cm"); return returnValue; }
true
5f34ae4e1215e8be8ced074c4b6f8c08399e1327
C++
Saransh-kalra/Data-Structures-Lab
/LinkedListLecture/LinkedListLecture/LinkedList.hpp
UTF-8
845
3.078125
3
[]
no_license
// // LinkedList.hpp // LinkedListLecture // // Created by Saransh Kalra on 9/28/18. // Copyright © 2018 Saransh Kalra. All rights reserved. // #ifndef LinkedList_hpp #define LinkedList_hpp #include <stdio.h> class Node { int datum; Node *next; public: Node(int); // we do not need a descructor because it will delete every element except the first one. int get_datum(); void set_datum(int); Node* get_next(); void set_next(Node*); }; class LinkedList { Node *head; int size; public: LinkedList(); ~LinkedList(); void destr_helper(Node*); void insert(int, int); int remove(int); // this will ouput the number we are deleting, does not need to be int, can be void int get_size(); int get(int); void set(int, int); void print_list(); }; #endif /* LinkedList_hpp */
true
480634acc1b832968db19a5368ea635a5ba29b20
C++
neiljonlouie/project-euler
/solutions/0000-0009/euler_0009.cpp
UTF-8
875
3.03125
3
[]
no_license
#include <iostream> void generate_triplet(int m, int n, int& a, int& b, int &c) { a = m * m - n * n; b = 2 * m * n; c = m * m + n * n; } int main(int argc, char **argv) { int a, b, c, d, desired = 1000; bool done = false; for (int n = 1; n <= 25; n++) { for (int m = n + 1; m <= 25; m++) { d = 1; generate_triplet(m, n, a, b, c); while (d * (a + b + c) <= 1000) { if (d * (a + b + c) == 1000) { std::cout << d * a << ", " << d * b << ", " << d * c << std::endl; std::cout << (d * a) * (d * b) * (d * c) << std::endl; done = true; break; } d++; } if (done) break; } if (done) break; } return 0; }
true
5b762fe72e93f9410671eb6269ca6832e63d4741
C++
xiaokimi/RayTracing
/RayTraceDemo/src/PerlinNoise.cpp
UTF-8
2,235
2.953125
3
[]
no_license
#include "rtpch.h" #include "PerlinNoise.h" PerlinNoise& PerlinNoise::getInstance() { static PerlinNoise m_Noise; return m_Noise; } float PerlinNoise::getNoise(const Point3& point) const { float u = point.x() - std::floorf(point.x()); float v = point.y() - std::floorf(point.y()); float w = point.z() - std::floorf(point.z()); int i = std::floorf(point.x()); int j = std::floorf(point.y()); int k = std::floorf(point.z()); Vector3f c[2][2][2]; for (int di = 0; di < 2; di++) { for (int dj = 0; dj < 2; dj++) { for (int dk = 0; dk < 2; dk++) { c[di][dj][dk] = m_RandomVector[m_PermX[(i + di) & 255] ^ m_PermY[(j + dj) & 255] ^ m_PermZ[(k + dk) & 255]]; } } } return trilinearInterp(c, u, v, w); } float PerlinNoise::getTurb(const Point3& point, const int& depth /*= 7*/) const { float accum = 0.0f; float weight = 1.0f; Vector3f temp = point; for (int i = 0; i < depth; i++) { accum += weight * getNoise(temp); weight *= 0.5f; temp *= 2; } return std::fabsf(accum); } PerlinNoise::PerlinNoise() { std::cout << "Perlin Noise create...\n"; perlinGenerate(); perlinGeneratePerm(m_PermX); perlinGeneratePerm(m_PermY); perlinGeneratePerm(m_PermZ); } PerlinNoise::~PerlinNoise() { } void PerlinNoise::perlinGenerate() { for (int i = 0; i < PerlinSize; i++) { m_RandomVector[i] = Vector3f(-1.0f + 2 * dis(gen), -1.0f + 2 * dis(gen), -1.0f + 2 * dis(gen)).normalize(); } } void PerlinNoise::permute(int* p) { for (int i = PerlinSize - 1; i > 0; i--) { int target = dis(gen) * (i + 1); std::swap(p[i], p[target]); } } void PerlinNoise::perlinGeneratePerm(int* p) { for (int i = 0; i < PerlinSize; i++) { p[i] = i; } permute(p); } float PerlinNoise::trilinearInterp(Vector3f c[2][2][2], float u, float v, float w) const { float uu = u * u * (3 - 2 * u); float vv = v * v * (3 - 2 * v); float ww = w * w * (3 - 2 * w); float accum = 0.0f; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { for (int k = 0; k < 2; k++) { Vector3f weightV(u - i, v - j, w - k); accum += (i * uu + (1 - i) * (1 - uu)) * (j * vv + (1 - j) * (1 - vv)) * (k * ww + (1 - k) * (1 - ww)) * dot(c[i][j][k], weightV); } } } return accum; }
true
28c72623824e72aab90295aa4dea9c3f8e97e4cc
C++
Jeblas/Parallel-Fourier-Transforms
/src/complex.cc
UTF-8
1,300
3.171875
3
[ "MIT" ]
permissive
#include "complex.h" #include <cmath> const float PI = 3.14159265358979f; Complex::Complex() : real(0.0f), imag(0.0f) {} Complex::Complex(float r) : real(r), imag(0.0f) {} Complex::Complex(float r, float i) : real(r), imag(i) {} Complex::Complex(const Complex & rhs) : real(rhs.real), imag(rhs.imag) {} Complex Complex::operator+(const Complex &b) const { return Complex(real + b.real, imag + b.imag); } Complex Complex::operator-(const Complex &b) const { return Complex(real - b.real, imag - b.imag); } Complex Complex::operator*(const Complex &b) const { float real_comp = (real * b.real) - (imag * b.imag); float imag_comp = (real * b.imag) + (imag * b.real); return Complex(real_comp, imag_comp); } float Complex::mag() const { return sqrt(pow(imag, 2) + pow(real, 2)); } float Complex::angle() const { return atan2(imag, real); } Complex Complex::conj() const { return Complex(real, -1 * imag); } std::ostream& operator<< (std::ostream& os, const Complex& rhs) { Complex c = rhs; if(fabsf(rhs.imag) < 1e-10) c.imag = 0.0f; if(fabsf(rhs.real) < 1e-10) c.real = 0.0f; /* TODO Will this affect the output file if(rhs.imag < 1e-10) { os << c.real; } */ os << "(" << c.real << "," << c.imag << ")"; return os; }
true
313aa8e98b74fef91f432a402602487cd492cae3
C++
sosswald/nao_calibration
/src/data_capturing/MarkerDetection.cpp
UTF-8
1,377
2.515625
3
[]
no_license
/* * MarkerDetection.cpp * * Created on: 22.12.2013 * Author: stefan */ #include "../../include/data_capturing/MarkerDetection.h" #include <cv_bridge/cv_bridge.h> #include <ros/ros.h> #include <sensor_msgs/image_encodings.h> namespace kinematic_calibration { using namespace std; namespace enc = sensor_msgs::image_encodings; MarkerDetection::MarkerDetection() { } MarkerDetection::~MarkerDetection() { } bool MarkerDetection::writeImage( const string& filename) { cv::Mat image; this->getImage(image); this->drawMarker(image); if(!image.data) { cout << "Image data was not set!" << endl; } cout << "writing image with size " << image.rows << " x " << image.cols << endl; bool success = cv::imwrite(filename, image); if(!success) { cout << "Could not save the image " << filename << endl; } return success; } void MarkerDetection::setMarkerId(const int& markerId) { this->markerId = markerId; } void MarkerDetection::msgToImg(const sensor_msgs::ImageConstPtr& in_msg, cv::Mat& out_image) { cv_bridge::CvImageConstPtr cv_ptr; // Convert from ROS message to OpenCV image. try { cv_ptr = cv_bridge::toCvShare(in_msg, enc::BGR8); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); } out_image = cv_ptr->image; } } /* namespace kinematic_calibration */
true
0f34aa67631c8361dbc798973f9d917081406e3e
C++
zzzbf/PAT
/PAT_A1166.h
UTF-8
1,484
2.828125
3
[]
no_license
#include<iostream> #include<vector> #include<unordered_map> using namespace std; int parent[210]; int Find(int a) { return a == parent[a] ? a : parent[a] = Find(parent[a]); } void Union(int a, int b) { int pa = Find(a); int pb = Find(b); if (pa != pb) parent[pb] = pa; } bool check(vector<vector<bool>> &isFriend, vector<int> heads) { for (int i = 0; i < heads.size(); i++) { for (int j = i + 1; j < heads.size(); j++) if (!isFriend[heads[i]][heads[j]]) return false; } return true; } int main() { int n, m, a, b; scanf("%d %d", &n, &m); vector<vector<bool>> isFriend(n + 1, vector<bool>(n + 1, false)); for (int i = 0; i < 211; i++) parent[i] = i; for (int i = 0; i < m; i++) { scanf("%d %d", &a, &b); isFriend[a][b] = true; isFriend[b][a] = true; Union(a, b); } int testn, num; scanf("%d", &testn); for (int j = 0; j < testn; j++) { scanf("%d", &num); unordered_map<int, bool> mp; vector<int> heads(num); for (int k = 0; k < num; k++) { scanf("%d", &heads[k]); mp[heads[k]] = true; } if (!check(isFriend, heads)) { printf("Area %d needs help.\n", j + 1); continue; } int k; bool flag = true; for (k = 1; k <= n; k++) { if (mp.find(k) != mp.end()) continue; int t = 0; for (; t < num && isFriend[heads[t]][k]; t++); if (t == num) { flag = false; break; } } if (!flag) printf("Area %d may invite more people, such as %d.\n", j + 1, k); else printf("Area %d is OK.\n", j + 1); } return 0; }
true
531854ee1a0525e6cfa6608f45f84f1b2039f211
C++
ZengFLab/PyroTools
/src/GenericReadBins.cpp
UTF-8
1,944
3
3
[]
no_license
#include "GenericReadBins.h" using namespace GenericSequenceTools; #include <sstream> void GenericReadBins_Clear_Stringstream(std::stringstream& ss) { ss.str(std::string()); ss.clear(); } GenericReadBins::GenericReadBins(int binMin, int binMax, int binStep) : m_binMin(binMin) , m_binMax(binMax) , m_binStep(binStep) { // knots of bins std::vector<int> binKnots; for (int i=m_binMin; i<=m_binMax; i+=m_binStep) binKnots.push_back(i); binKnots.push_back(std::numeric_limits<int>::max()); // number of bins m_binNum = binKnots.size()-1; // the lower and upper boundaries of bins for (int i=0; i<m_binNum; i++) m_binIntervals.push_back(std::tuple<int,int>(binKnots[i], binKnots[i+1])); // the labels of bins for (int i=0; i<m_binNum; i++) { std::stringstream strBuf; strBuf << "["; strBuf << binKnots[i]; strBuf << ","; if (binKnots[i+1]==std::numeric_limits<int>::max()) strBuf << "inf"; else strBuf << binKnots[i+1]; strBuf << ")"; m_binLabels.push_back(strBuf.str()); GenericReadBins_Clear_Stringstream(strBuf); } } GenericReadBins& GenericReadBins::operator =(const GenericReadBins& toCopy) { this->m_binMin = toCopy.m_binMin; this->m_binMax = toCopy.m_binMax; this->m_binStep = toCopy.m_binStep; this->m_binNum = toCopy.m_binNum; this->m_binLabels.assign(toCopy.m_binLabels.begin(), toCopy.m_binLabels.end()); this->m_binIntervals.assign(toCopy.m_binIntervals.begin(), toCopy.m_binIntervals.end()); return *this; } int GenericReadBins::binIndex(int x) { int idx = 0; std::vector<std::tuple<int,int>>::iterator iter; for (iter=m_binIntervals.begin(); iter!=m_binIntervals.end(); ++iter, ++idx) { if (x>=std::get<0>(*iter) && x<std::get<1>(*iter)) break; } return idx; }
true
4a2ef033cfbe8f9f3d35d55e30f4253bcba88e7b
C++
kiranmuddam/leetcode
/problems/valid_palindrome/solution.cpp
UTF-8
904
3.421875
3
[]
no_license
class Solution { public: bool isPalindrome(string s) { if (s == " ") { return true; } int startPointer = 0; int endPointer = s.size() - 1; while (startPointer < endPointer) { if (!(isalpha(s[startPointer]) || isdigit(s[startPointer]))) { startPointer++; } if (!(isalpha(s[endPointer]) || isdigit(s[endPointer]))) { endPointer--; } if ((isalpha(s[startPointer]) || isdigit(s[startPointer])) && (isalpha(s[endPointer]) || isdigit(s[endPointer]))) { if (tolower(s[startPointer]) == tolower(s[endPointer])) { startPointer++; endPointer--; } else { return false; } } } return true; } };
true
080e27e69a2bb876b034b3294b905d0995aeafef
C++
AwkwardDev/Descent-core-scripts-3.3.5
/src/arcemu-shared/MemManager/GarbageCollector.h
UTF-8
1,815
2.59375
3
[]
no_license
#ifndef _GARBAGE_COLLECTOR_H_ #define _GARBAGE_COLLECTOR_H_ #include "Singleton.h" //the whole point of this is to avoid using dead pointers due to thread concurency //the solution sucks but it comes to patch an already badly syncronized system // The idea is simple : // instead direct delete and object we insert it here and mark it as deleted // references to object should check if this object is marked as deleted. If yes then loose reference before Garbage collector really deletes them class Object; class WorldSession; //#define GARBAGE_DELETE_DELAY 2*60*1000 //#define GARBAGE_DELETE_DELAY_WS 1*60*1000 //must be smaller then char delete or inverse ? Crashes both ways :( //#define GARBAGE_COLLECTOR_UPDATE_INTERVAL ( GARBAGE_DELETE_DELAY / 2) //do not spam list update #define GARBAGE_DELETE_DELAY 10*60*1000 #define GARBAGE_DELETE_DELAY_WS 20*60*1000 //must be smaller then char delete or inverse ? Crashes both ways :( #define GARBAGE_COLLECTOR_UPDATE_INTERVAL ( 60000 ) //do not spam list update class DelayedObjectDeletor: public Singleton<DelayedObjectDeletor> { public: DelayedObjectDeletor() { NextUpdateStamp = 0; } ~DelayedObjectDeletor(); void AddObject(Object *p); //check what needs to be indeed Deleted void Update(); //not sure we should use this due to performance issue. However in the future for debugging it might be used // bool HasObject(Object *); private: //expected size of the list is not larger then 1000 elements //pets, totems, temp summons.... should be inserted here std::map<Object *,uint32> delete_list; //store objects in a list and delete them after a while Mutex list_lock; //make sure to not add/remove from list at the same time uint32 NextUpdateStamp; }; #define sGarbageCollection DelayedObjectDeletor::getSingleton() #endif
true
507af3839de2b54ee9adf1407229ae34297553f1
C++
v-biryukov/cs_mipt_faki
/term2/seminar07_move/classroom_tasks/code/1move/14return_no_rvo.cpp
UTF-8
1,314
3.765625
4
[]
no_license
/* Но что если RVO оптимизация неприменима? Например, если мы возвращаем из функции один из его аргументов, то RVO неприменима. Нужно ли в этом случае писать std::move при возврате из функции? Ответ: нет, не нужно. Дело в том, что в этом случае объект будет перемещён автоматически, даже если вы не напишите std::move. */ #include <vector> #include <iostream> #include <utility> using std::cout, std::endl; std::vector<int> duplicate1(std::vector<int> v) { cout << "Address of v: " << &v << ", address of v[0] " << &v[0] << endl; return v; } std::vector<int> duplicate2(std::vector<int> v) { cout << "Address of v: " << &v << ", address of v[0] " << &v[0] << endl; return std::move(v); } int main() { std::vector a {10, 20, 30, 40, 50}; auto b = duplicate1(a); cout << "Address of b: " << &b << ", address of b[0] " << &b[0] << endl; } /* Запустите программу и убедитесь, что, когда не срабатывает RVO, объект перемещается автоматически. */
true
bf5405a967da8056d1bfe3e8377fb35ea2202692
C++
StSiRe/Algoritms
/Algorithms and Data Structures/Second task/second/main.cpp
UTF-8
6,711
3.25
3
[]
no_license
#include <iostream> #include <cmath> #include <ctime> bool isMaxRequired = false; float func(float x) { if(isMaxRequired) return -(pow(x,3)-x+exp(-x)); return pow(x,3)-x+exp(-x); } void PassiveSearch(float left,float right, float e) { srand(time(0)); int steps = 0; float minPoint = 0; float minVal = 99999999; for (float i = left; i <= right; i+=e) { steps++; float tmp = func(i); if(minVal > tmp) { minVal = tmp; minPoint = i; } } if(isMaxRequired) std::cout << "Result X:" << minPoint << " Y:" << -func(minPoint) <<" Steps:"<< steps<<" Time:" << clock()/1000.0<< std::endl; else std::cout << "Result X:" << minPoint << " Y:" << func(minPoint) <<" Steps:"<< steps<<" Time:" << clock()/1000.0<< std::endl; } void Task1_SearchHalfPart(float a,float b,float e){ float x1; float a1=0,b1 = 999999; float a0 = a; float b0 = b; srand(time(0)); int steps = 0; while(b1-a1 > e) { float om = (b0 - a0) / 10; float alp0 = (a0 + b0) / 2 - om; float bet0 = alp0 + 2 * om; float fAlp = func(alp0); float fBet = func(bet0); if (fAlp <= fBet) { x1 = alp0; a1 = a0; b1 = bet0; } else { a1 = alp0; x1 = bet0; b1 = b0; } a0 = a1; b0 = b1; steps++; if(isMaxRequired) std::cout << "x:" << (a1+b1)/2 << " y:" << -func((a1+b1)/2) << std::endl; else std::cout << "x:" << (a1+b1)/2 << " y:" << func((a1+b1)/2) << std::endl; } float res = (a1 + b1) / 2; if(isMaxRequired) std::cout << "Result X:" << res << " Y:" << -func(res) <<" Steps:"<< steps<<" Time:" << clock()/1000.0 << std::endl; else std::cout << "Result X:" << res << " Y:" << func(res) <<" Steps:"<< steps<<" Time:" << clock()/1000.0 << std::endl; } void Task1_SearchGoldCut(float a,float b,float e){ float x1; float a1=0,b1 = 999999; float a0 = a; float b0 = b; srand(time(0)); int steps = 0; while(b1-a1 > e) { float om = b0 - a0; float alp0 =a0+(2*om)/(3+sqrt(5)); float bet0 = a0+(2*om)/(1+sqrt(5)); float fAlp = func(alp0); float fBet = func(bet0); if (fAlp <= fBet) { x1 = alp0; a1 = a0; b1 = bet0; } else { a1 = alp0; x1 = bet0; b1 = b0; } a0 = a1; b0 = b1; steps++; if(isMaxRequired) std::cout << "x:" << (a1+b1)/2 << " y:" << -func((a1+b1)/2) << std::endl; else std::cout << "x:" << (a1+b1)/2 << " y:" << func((a1+b1)/2) << std::endl; } float res = (a1 + b1) / 2; if(isMaxRequired) std::cout << "Result X:" << res << " Y:" << -func(res) <<" Steps:"<< steps<<" Time:" << clock()/1000.0 << std::endl; else std::cout << "Result X:" << res << " Y:" << func(res) <<" Steps:"<< steps<<" Time:" << clock()/1000.0 << std::endl; } float Fib(int n) { if(n == 0) return 1; if(n== 1) return 1; return Fib(n-1) + Fib(n-2); } void Task1_SearchFib(float a, float b, float e) { int f0 = 1; int f1=1; float a0 = a; float b0 = b; float d0 = b0-a0; int N = 1; srand(time(0)); int steps = 0; while(d0/Fib(N) >= e) { N++; } float x1=0; float a1=0,b1 = 999999; int k =0; while(b1-a1 > e) { float om = b0 - a0; float alp0 = a0 + Fib(N-k-2)/Fib(N-k)*om; float bet0 = a0 + Fib(N-k-1)/Fib(N-k)*om; float fAlp = func(alp0); float fBet = func(bet0); if (fAlp <= fBet) { x1 = alp0; a1 = a0; b1 = bet0; } else { a1 = alp0; x1 = bet0; b1 = b0; } a0 = a1; b0 = b1; k++; steps++; if(isMaxRequired) std::cout << "x:" << (a1+b1)/2 << " y:" << -func((a1+b1)/2) << std::endl; else std::cout << "x:" << (a1+b1)/2 << " y:" << func((a1+b1)/2) << std::endl; } float res = (a1 + b1) / 2; if(isMaxRequired) std::cout << "Result X:" << res << " Y:" << -func(res) <<" Steps:"<< steps<<" Time:" << clock()/1000.0 << std::endl; else std::cout << "Result X:" << res << " Y:" << func(res) <<" Steps:"<< steps<<" Time:" << clock()/1000.0 << std::endl; } int main() { float left,right,e; // std::cout << "Current function y=x^3-x+e^(-x)" << std::endl; // std::cout << "Type left limit:"; // std::cin >> left; // std::cout << "Type right limit:"; // std::cin >> right; // std::cout << "Type accuracy:"; // std::cin >> e; // std::cout<<std::endl; // // PassiveSearch(left,right,e); e= 0.000001; std::cout<< "Task 2 Functions(accuracy = 0.001)" << std::endl; std::cout << std::endl<<"Part 1: Searching extremum in range[-5,-3]" << std::endl; left = -5; right = -3; std::cout <<std::endl<< "Method 1: Classic search: "<< std::endl; PassiveSearch(left,right,e); std::cout <<std::endl<< "Method 2: Like-binary search: "<< std::endl;Task1_SearchHalfPart(left,right,e); std::cout <<std::endl<< "Method 3: Gold-cut search: "<< std::endl;Task1_SearchGoldCut(left,right,e); std::cout <<std::endl<< "Method 4: Fib search: "<< std::endl;Task1_SearchFib(left,right,e); std::cout << std::endl<<"Part 2: Search Max-points in range [-3,0]"; std::cout << std::endl; left = -3; right = 0; isMaxRequired = true; std::cout <<std::endl<< "Method 1: Classic search: "<< std::endl; PassiveSearch(left,right,e); std::cout <<std::endl<< "Method 2: Like-binary search: "<< std::endl;Task1_SearchHalfPart(left,right,e); std::cout <<std::endl<< "Method 3: Gold-cut search: "<< std::endl;Task1_SearchGoldCut(left,right,e); std::cout <<std::endl<< "Method 4: Fib search: "<< std::endl;Task1_SearchFib(left,right,e); isMaxRequired = false; std::cout <<std::endl << "Part 3: Search Min-points in range [0,3]"; std::cout << std::endl; left = 0; right = 3; std::cout <<std::endl<< "Method 1: Classic search: "<< std::endl; PassiveSearch(left,right,e); std::cout <<std::endl<< "Method 2: Like-binary search: "<< std::endl;Task1_SearchHalfPart(left,right,e); std::cout <<std::endl<< "Method 3: Gold-cut search: "<< std::endl;Task1_SearchGoldCut(left,right,e); std::cout <<std::endl<< "Method 4: Fib search: "<< std::endl;Task1_SearchFib(left,right,e); std::cout <<std::endl<< "End. Thanks for using our software" << std::endl; return 0; }
true
353b94c89d3361a55acdc8e5c7878aa2d43463af
C++
sgioia9/Live-Shader
/SGraphic/Sources/worldobject.cpp
UTF-8
1,149
2.609375
3
[]
no_license
#include <glm/gtc/matrix_transform.hpp> #include "worldobject.hpp" namespace Core { WorldObject::WorldObject( const std::shared_ptr<Model>& model, const glm::mat4& transform) : _model(model), _transform(transform) {} WorldObject::WorldObject(const std::shared_ptr<Model>& model) : WorldObject(model, glm::mat4()) { } void WorldObject::scaleUp() { glm::mat4 scaleUpMatrix; scaleUpMatrix = glm::scale(scaleUpMatrix, glm::vec3(1.1f, 1.1f, 1.1f)); _transform = scaleUpMatrix * _transform; } void WorldObject::scaleDown() { glm::mat4 scaleDownMatrix; scaleDownMatrix = glm::scale(scaleDownMatrix, glm::vec3(0.9f, 0.9f, 0.9f)); _transform = scaleDownMatrix * _transform; } void WorldObject::rotateYAxis(float speed) { glm::mat4 rotMatrix; rotMatrix = glm::rotate(rotMatrix, speed, glm::vec3(0.0f, 1.0f, 0.0f)); _transform = rotMatrix * _transform; } void WorldObject::rotateXAxis(float speed) { glm::mat4 rotMatrix; rotMatrix = glm::rotate(rotMatrix, speed, glm::vec3(1.0f, 0.0f, 0.0f)); _transform = rotMatrix * _transform; } }
true
f7399e23d31764749ce26c54b1607ae30c86f918
C++
SvBoichuk/EmployeeDataManagement
/employee.cpp
UTF-8
655
3.015625
3
[]
no_license
#include "employee.h" Employee::Employee() { } Employee::Employee(const EmployeeData &d) { data = d; } Employee::Employee(const QString &f_name, const QString &m_name, const QString &l_name, int range, float tariff, int shop_numb) { data.first_name = f_name; data.middle_name = m_name; data.last_name = l_name; data.range = range; data.tariff = tariff; data.shop_number = shop_numb; } Employee::Employee(Employee && other) { data = std::move(other.data); } Employee & Employee::operator=(Employee && other) { data = std::move(other.data); return *this; } Employee::~Employee() { }
true
186c225f49f5b64ad0be4a011cb6cf1714572c06
C++
venGaza/starwars
/src/randomNumber.cpp
UTF-8
615
3.703125
4
[ "MIT" ]
permissive
/* * Function: randomNumber * Usage: randomNumber(int min, int max) * ------------------------- * This function takes two parameters whicha are the min and max values and returns a random number * between those values. */ #include "randomNumber.hpp" #include <random> int randomNumber(int min, int max) { std::random_device rd; //Create seed object std::minstd_rand0 engine(rd()); //Seed the engine std::uniform_int_distribution<int> work(min, max); //Set range for distribution int randomNumber = work(engine); return randomNumber; }
true
f9db14b05aa5ed739220aa52a754ad11ba5fa2e8
C++
q4a/DirectxSample-Snowman
/d3dMySkyBox/D3DUtility.cpp
GB18030
8,390
2.625
3
[]
no_license
#include "D3DUtility.h" CD3DUtility::CD3DUtility(void) { _backWidth = 0; _backHeight = 0; _windowed = true; _d3dDeviceType = D3DDEVTYPE_HAL; } CD3DUtility::~CD3DUtility(void) { } void CD3DUtility::SetHW(UINT width, UINT height, bool windowed) { _backWidth = width; _backHeight = height; _windowed = windowed; } void CD3DUtility::GetRect(RECT* rect) { rect->left = 0; rect->top = 0; rect->right = _backWidth; rect->bottom = _backHeight; } void CD3DUtility::SetDeviceType(D3DDEVTYPE deviceType) { _d3dDeviceType = deviceType; } IDirect3DDevice9* CD3DUtility::GetDevicePoint() { return _d3dDevice9; } /* ʼD3D豸,ɹ1ʧܷ0 */ bool CD3DUtility::InitD3D(HWND hwnd) { HRESULT hr = 0; // Step 1: Create the IDirect3D9 object. if(!(_d3d9 = Direct3DCreate9(D3D_SDK_VERSION))) { ::MessageBox(0, _T("Direct3DCreate9() - FAILED"), 0, 0); return false; } // Step 2: Check for hardware vp. D3DCAPS9 caps; _d3d9->GetDeviceCaps(D3DADAPTER_DEFAULT, _d3dDeviceType, &caps); int vp = 0; if( caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT ) vp = D3DCREATE_HARDWARE_VERTEXPROCESSING; else vp = D3DCREATE_SOFTWARE_VERTEXPROCESSING; // Retrieves the current display mode of the adapter. D3DDISPLAYMODE d3ddm; if(FAILED(_d3d9->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &d3ddm))) { ::MessageBox(0, _T("GetAdapterDisplayMode() - FAILED"), 0, 0); return false; } // Step 3: Fill out the D3DPRESENT_PARAMETERS structure. _d3dpp.BackBufferWidth = _backWidth; _d3dpp.BackBufferHeight = _backHeight; _d3dpp.BackBufferFormat = d3ddm.Format; //D3DFMT_A8R8G8B8; _d3dpp.BackBufferCount = 1; _d3dpp.MultiSampleType = D3DMULTISAMPLE_NONE; _d3dpp.MultiSampleQuality = 0; _d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; _d3dpp.hDeviceWindow = hwnd; _d3dpp.Windowed = _windowed; _d3dpp.EnableAutoDepthStencil = true; _d3dpp.AutoDepthStencilFormat = D3DFMT_D24S8; _d3dpp.Flags = 0; _d3dpp.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT; _d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; // Step 4: Create the device. hr = _d3d9->CreateDevice( D3DADAPTER_DEFAULT, // primary adapter _d3dDeviceType, // device type hwnd, // window associated with device vp, // vertex processing &_d3dpp, // present parameters &_d3dDevice9); // return created device if( FAILED(hr) ) { _d3d9->Release(); // done with d3d9 object ::MessageBox(0, _T("CreateDevice() - FAILED"), 0, 0); return false; } _d3d9->Release(); // done with d3d9 object return true; } void CD3DUtility::SetWorldTransform() { _d3dDevice9->SetTransform(D3DTS_WORLD, &_transMatrix); } void CD3DUtility::SetWorldTransform(D3DXMATRIX* matrix) { _d3dDevice9->SetTransform(D3DTS_WORLD, matrix); } void CD3DUtility::MutliTransformMatrix(D3DXMATRIX* matrix) { _transMatrix *= *matrix; } void CD3DUtility::ResetTransformMatrix() { D3DXMatrixIdentity(&_transMatrix); } void CD3DUtility::SetTranslation(D3DXVECTOR3 pos) { SetTranslation(pos.x, pos.y, pos.z); } void CD3DUtility::SetScaling(D3DXVECTOR3 pos) { SetScaling(pos.x, pos.y, pos.z); } void CD3DUtility::SetRotation(D3DXVECTOR3 axis, float angle) { D3DXMATRIX world; D3DXMatrixRotationAxis(&world, &axis, angle); _transMatrix *= world; } void CD3DUtility::SetTranslation(float x, float y, float z) { D3DXMATRIX world; D3DXMatrixTranslation(&world, x, y, z); _transMatrix *= world; } void CD3DUtility::SetScaling(float sx, float sy, float sz) { D3DXMATRIX world; D3DXMatrixScaling(&world, sx, sy, sz); _transMatrix *= world; } void CD3DUtility::SetRotation(float ax, float ay, float az, float angle) { D3DXVECTOR3 axis(ax, ay, az); SetRotation(axis, angle); } void CD3DUtility::SetRotationY(float angle) { D3DXMATRIX world; D3DXMatrixRotationY(&world, angle); _transMatrix *= world; } void CD3DUtility::SetViewTransform(float x, float y, float z) { D3DXVECTOR3 pos(x, y, z); D3DXVECTOR3 target(0.0f, 0.0f, 10.0f); D3DXVECTOR3 up(0.0f, 1.0f, 0.0f); D3DXMATRIX V; D3DXMatrixLookAtLH(&V, &pos, &target, &up); _d3dDevice9->SetTransform(D3DTS_VIEW, &V); } void CD3DUtility::SetProjectionTransform(float fovy, float zn, float zf) { // Set the projection matrix. D3DXMATRIX proj; D3DXMatrixPerspectiveFovLH(&proj, fovy, (float)_backWidth / (float)_backHeight, zn, zf); _d3dDevice9->SetTransform(D3DTS_PROJECTION, &proj); } void CD3DUtility::SetDirectionLight(D3DXVECTOR3 dir, D3DXCOLOR color) { D3DLIGHT9 light = d3d::InitDirectionalLight(&dir, &color); _d3dDevice9->SetLight(0, &light); _d3dDevice9->LightEnable(0, true); _d3dDevice9->SetRenderState(D3DRS_NORMALIZENORMALS, true); _d3dDevice9->SetRenderState(D3DRS_SPECULARENABLE, true); } void CD3DUtility::UpdateView(CCamera* camera) { if(_d3dDevice9) { // Update the view matrix representing the cameras // new position/orientation. D3DXMATRIX V; camera->getViewMatrix(&V); _d3dDevice9->SetTransform(D3DTS_VIEW, &V); } } void CD3DUtility::BeginRender() { //_d3dDevice9->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0x00000000, 1.0f, 0); _d3dDevice9->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0xffffffff, 1.0f, 0); _d3dDevice9->BeginScene(); } void CD3DUtility::EndRender() { _d3dDevice9->EndScene(); _d3dDevice9->Present(0, 0, 0, 0); } // d3d namespace members const DWORD d3d::TextureVertex::FVF = D3DFVF_XYZ | D3DFVF_TEX1; const DWORD d3d::Vertex::FVF = D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_TEX1; D3DLIGHT9 d3d::InitDirectionalLight(D3DXVECTOR3* direction, D3DXCOLOR* color) { D3DLIGHT9 light; ::ZeroMemory(&light, sizeof(light)); light.Type = D3DLIGHT_DIRECTIONAL; light.Ambient = *color * 0.4f; light.Diffuse = *color; light.Specular = *color * 0.6f; light.Direction = *direction; return light; } D3DLIGHT9 d3d::InitPointLight(D3DXVECTOR3* position, D3DXCOLOR* color) { D3DLIGHT9 light; ::ZeroMemory(&light, sizeof(light)); light.Type = D3DLIGHT_POINT; light.Ambient = *color * 0.4f; light.Diffuse = *color; light.Specular = *color * 0.6f; light.Position = *position; light.Range = 1000.0f; light.Falloff = 1.0f; light.Attenuation0 = 1.0f; light.Attenuation1 = 0.0f; light.Attenuation2 = 0.0f; return light; } D3DLIGHT9 d3d::InitSpotLight(D3DXVECTOR3* position, D3DXVECTOR3* direction, D3DXCOLOR* color) { D3DLIGHT9 light; ::ZeroMemory(&light, sizeof(light)); light.Type = D3DLIGHT_SPOT; light.Ambient = *color * 0.4f; light.Diffuse = *color; light.Specular = *color * 0.6f; light.Position = *position; light.Direction = *direction; light.Range = 1000.0f; light.Falloff = 1.0f; light.Attenuation0 = 1.0f; light.Attenuation1 = 0.0f; light.Attenuation2 = 0.0f; light.Theta = 0.5f; light.Phi = 0.7f; return light; } D3DMATERIAL9 d3d::InitMtrl(D3DXCOLOR a, D3DXCOLOR d, D3DXCOLOR s, D3DXCOLOR e, float p) { D3DMATERIAL9 mtrl; mtrl.Ambient = a; mtrl.Diffuse = d; mtrl.Specular = s; mtrl.Emissive = e; mtrl.Power = p; return mtrl; } d3d::BoundingBox::BoundingBox() { // infinite small _min.x = d3d::INFINITY; _min.y = d3d::INFINITY; _min.z = d3d::INFINITY; _max.x = -d3d::INFINITY; _max.y = -d3d::INFINITY; _max.z = -d3d::INFINITY; } bool d3d::BoundingBox::isPointInside(D3DXVECTOR3& p) { if( p.x >= _min.x && p.y >= _min.y && p.z >= _min.z && p.x <= _max.x && p.y <= _max.y && p.z <= _max.z ) { return true; } else { return false; } } d3d::BoundingSphere::BoundingSphere() { _radius = 0.0f; } float d3d::GetRandomFloat(float lowBound, float highBound) { if( lowBound >= highBound ) // bad input return lowBound; // get random float in [0, 1] interval float f = (rand() % 10000) * 0.0001f; // return float in [lowBound, highBound] interval. return (f * (highBound - lowBound)) + lowBound; } void d3d::GetRandomVector( D3DXVECTOR3* out, D3DXVECTOR3* min, D3DXVECTOR3* max) { out->x = GetRandomFloat(min->x, max->x); out->y = GetRandomFloat(min->y, max->y); out->z = GetRandomFloat(min->z, max->z); } DWORD d3d::FtoDw(float f) { return *((DWORD*)&f); } float d3d::Lerp(float a, float b, float t) { return a - (a*t) + (b*t); }
true
859a9ebf07fc8ec868459bcd55eb5fcc8465230b
C++
teodoraalexandra/Data-Structures-And-Algorithms
/DSALAB5/Heap.h
UTF-8
1,107
2.90625
3
[]
no_license
// // Created by Teodora Dan and her groupmate <3 on 2019-05-07. // #pragma once #include <utility> #include <vector> #include "DynamicArray.h" typedef int TElem; using namespace std; typedef bool(*Relation)(TElem p1, TElem p2); //removes the last k elements from the vector (considering the relation) //if k is less than or equal to zero, throws an exception //if k is greater than the size of the array, all elements will be removed /* FROM OLD IMPLEMENTATION void removeLast(vector<TElem>& elements, Relation r, int k); void bubble_down(DynamicArray dynamicArray, int len, int index, Relation r); void buildHeap(DynamicArray dynamicArray, int n, Relation r); void extractRoot(DynamicArray dynamicArray, int &n, Relation r); */ void removeLast(vector<TElem>& elements, Relation r, int k); void restoreDown(DynamicArray& vec, int len, int index, Relation r); DynamicArray buildHeap(vector<TElem>& elements, int k, Relation r); void extractRoot(DynamicArray& vec, int k, Relation r); void restoreUp(DynamicArray& vec, int index, Relation r); void insert(DynamicArray& vec, int k, int elem, Relation r);
true
537ae343e0f5f6e408c543e5315e3d438b2ea92f
C++
rkdehdduq92/AlgorithmsPractice
/baekjoon/14888.cpp
UTF-8
800
3.28125
3
[]
no_license
#include<iostream> #include<cstdio> using namespace std; int N; int * nums; int * opers; int maxnum, minnum; void calculate(int n, int cal); int calc(int c, int n, int i); int main(){ cin>>N; nums=new int[N]; opers=new int[4]; for(int i=0; i<N; i++) cin>>nums[i]; cin>>opers[0]>>opers[1]>>opers[2]>>opers[3]; maxnum=-1000000001; minnum=1000000001; calculate(1, nums[0]); cout<<maxnum<<endl; cout<<minnum<<endl; } void calculate(int n, int cal){ if(n>=N){ maxnum=(cal>maxnum)? cal: maxnum; minnum=(cal<minnum)? cal: minnum; } for(int i=0; i<4; i++){ if(opers[i]>0){ opers[i]--; calculate(n+1, calc(cal, nums[n], i)); opers[i]++; } } } int calc(int c, int n, int i){ if(i==0) return c+n; if(i==1) return c-n; if(i==2) return c*n; if(i==3) return c/n; }
true
3dd37fde6320a712635a666fa164fc52ad5a8414
C++
henrybetts/ofxLaunchpad2
/example-basic-drawing/src/ofApp.cpp
UTF-8
2,684
2.609375
3
[]
no_license
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ ofSetBackgroundAuto(false); ofBackground(0); //allocate frame buffer fbo.allocate(9, 9); //allocate pixel buffer pixels.allocate(9, 9, OF_PIXELS_RGB); pixels.setColor(ofColor::black); //attempt to open launchpad if (launchpad.open()){ ofLog(OF_LOG_NOTICE, "Opened launchpad!"); }else{ ofLog(OF_LOG_ERROR, "Failed to open launchpad"); } } //-------------------------------------------------------------- void ofApp::update(){ //increase the size of the circle size += 0.01; if (size > 1){ //start a new circle size = 0; color.setHsb(ofRandom(255), ofRandom(100, 255), ofRandom(100, 255)); } } //-------------------------------------------------------------- void ofApp::draw(){ if (launchpad.isOpen()){ //begin frame buffer fbo.begin(); //draw circle ofSetColor(color); ofDrawCircle(4.5, 4.5, size*9); //end frame buffer fbo.end(); //get pixels from frame buffer and send to launchpad fbo.readToPixels(pixels); launchpad.setPixels(pixels); } //draw circle on main display as well ofSetColor(color); ofDrawCircle(ofGetWidth()/2, ofGetHeight()/2, size*ofGetWidth()); } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
true
7f2075bd3cb2a4a80b16855f35052a1b435522e7
C++
AhmedShalaby92/Lexical-Analyzer
/LexicalAnalyzer/DFA_Generator.h
UTF-8
1,536
2.515625
3
[]
no_license
/* * DFAGenerator.h * * Created on: 10 Apr 2013 * Author: Mohamed */ #ifndef DFAGENERATOR_H_ #define DFAGENERATOR_H_ #include "DNode.h" #include <vector> #include <stack> #include "Table_obj.h" #include <string> namespace std { class DFA_Generator { public: vector<vector<Table_obj*> > NTransitions; DFA_Generator(vector<vector<Table_obj*> > NFA, vector<string> input, vector<int> finalStates, vector<string> patternName, vector<string> pattern); DNode* getUnmarked(vector<DNode*> states); vector<Table_obj*> move(vector<vector<Table_obj*> > transitions, string input, vector<Table_obj*> states); vector<Table_obj*> epsilon_closure(vector<Table_obj*> nodes, vector<vector<Table_obj*> > transitions); bool contains(vector<DNode*> states, DNode* node); DNode* check(vector<DNode*> states, vector<Table_obj*> v1); vector<vector<DNode*> > constructDFA(vector<string> inputs, vector<DNode*> states, vector<vector<Table_obj*> > transitions); vector<vector<DNode*> > generateDFA(vector<string> inputs, vector<vector<Table_obj*> > transitions, Table_obj* nStartState, vector<int> finalStates, vector<string> patternName, vector<string> pattern); void printDFA(vector<vector<DNode*> > DTransitions); void printNFA(vector<vector<Table_obj*> > transitions); void AccStates(vector<DNode*> states); vector <bool>isFinal; vector <string> patterns; vector<vector<DNode *> > Dstates; vector<DNode*> DeterministecS; virtual ~DFA_Generator(); }; } /* namespace std */ #endif /* DFAGENERATOR_H_ */
true
2b3706e957faa3ebfd8ec0b27dd4dd61d5caefb0
C++
XzoRit/boost_playground
/exception/test_exceptions.cpp
UTF-8
6,616
2.9375
3
[]
no_license
#include <boost/test/unit_test.hpp> #include <boost/exception/all.hpp> #include <stdexcept> #include <string> #include <iostream> class current_location { public: current_location() : m_func_name("") , m_file("") , m_line(0) {} current_location(const char* func_name, const char* file, int line) : m_func_name(func_name) , m_file(file) , m_line(line) {} const char* func() const { return m_func_name; } const char* file() const { return m_file ; } int line() const { return m_line ; } std::string str() const { return std::string(file()) + '(' + std::to_string(line()) + "): " + func(); } private: const char* m_func_name; const char* m_file; int m_line; }; std::ostream& operator<<(std::ostream& str, const current_location& loc) { str << loc.str(); return str; } #define CURRENT_LOCATION() \ current_location(BOOST_CURRENT_FUNCTION, __FILE__, __LINE__) #if defined(EXCEPTIONS_DISABLED) void throw_exception( const std::exception&, const current_location&); #else template<class E> BOOST_NORETURN void throw_exception(const E& e, const current_location& cur_loc) { throw ::boost::enable_error_info(e) << ::boost::throw_function(cur_loc.func()) << ::boost::throw_file(cur_loc.file()) << ::boost::throw_line(cur_loc.line()); } #endif #define THROW_EXCEPTION_WITH_INFO(e,i) \ ::throw_exception( \ ::boost::enable_error_info(e) << (i), \ CURRENT_LOCATION()) #define THROW_EXCEPTION(e) \ ::throw_exception( \ e, \ CURRENT_LOCATION()) class exception_base : public virtual std::exception , public virtual boost::exception {}; class error_a : public virtual exception_base {}; class error_b : public virtual exception_base {}; class error_c : public virtual exception_base {}; typedef boost::error_info<struct tag_error_code, int> error_code; bool c(bool ok) { if(!ok) THROW_EXCEPTION_WITH_INFO(error_c(), error_code(666)); else return ok; } typedef boost::error_info<struct tag_error_string, std::string> error_string; bool b(bool bok, bool cok) { try { if(!bok) THROW_EXCEPTION_WITH_INFO(error_b(), error_string("not ok")); else return c(cok); } catch(const error_c& e) { e << error_string("b() was called :-)"); throw; } } typedef boost::error_info<struct tag_another_error_code, int> another_error_code; bool a(bool aok, bool bok, bool cok) { try { if(!aok) THROW_EXCEPTION_WITH_INFO(error_a(), another_error_code(456)); else return b(bok, cok); } catch(const error_c& e) { e << another_error_code(123); throw; } catch(const error_b& e) { e << another_error_code(123); throw; } } void stream_exception(std::ostream& str) { try { throw; } catch(const boost::exception& e) { str << '\n' << boost::diagnostic_information(e); } catch(const std::exception& e) { str << '\n' << e.what(); } catch(...) { str << "\nUnknown exception"; } } template<class ParamType> void stream_exception(std::ostream& str, ParamType param) { str << param; stream_exception(str); } template<class ParamType, class... RestParamType> void stream_exception(std::ostream& str, ParamType param, RestParamType... rest_params) { str << param << ' '; stream_exception(str, rest_params...); } template<class... ParamTypes> void stream_exception(std::ostream& str, const current_location& loc, ParamTypes... params) { str << loc << ' '; stream_exception(str, params...); } bool stream_exception_and_map_to_bool(std::ostream& str, int p1, float p2, const char* p3) { try { static_cast<void>(a(true, true, false)); return true; } catch(...) { stream_exception( str, CURRENT_LOCATION(), "p1 =",p1, "p2 =",p2, "p3 =",p3); } return false; } namespace utf = boost::unit_test; bool contains_error_infos_cba(const error_c& e) { BOOST_TEST((*boost::get_error_info<boost::throw_function>(e)) == "bool c(bool)"); BOOST_TEST((*boost::get_error_info<boost::throw_file>(e)) == "test_exceptions.cpp"); BOOST_TEST((*boost::get_error_info<error_code>(e)) == 666); BOOST_TEST((*boost::get_error_info<error_string>(e)) == "b() was called :-)"); BOOST_TEST((*boost::get_error_info<another_error_code>(e)) == 123); BOOST_TEST_MESSAGE(boost::diagnostic_information(e)); return true; } bool contains_error_infos_ba(const error_b& e) { BOOST_TEST((*boost::get_error_info<boost::throw_function>(e)) == "bool b(bool, bool)"); BOOST_TEST((*boost::get_error_info<boost::throw_file>(e)) == "test_exceptions.cpp"); BOOST_TEST((*boost::get_error_info<error_string>(e)) == "not ok"); BOOST_TEST((*boost::get_error_info<another_error_code>(e)) == 123); BOOST_TEST_MESSAGE(boost::diagnostic_information(e)); return true; } bool contains_error_infos_a(const error_a& e) { BOOST_TEST((*boost::get_error_info<boost::throw_function>(e)) == "bool a(bool, bool, bool)"); BOOST_TEST((*boost::get_error_info<boost::throw_file>(e)) == "test_exceptions.cpp"); BOOST_TEST((*boost::get_error_info<another_error_code>(e)) == 456); BOOST_TEST_MESSAGE(boost::diagnostic_information(e)); return true; } BOOST_AUTO_TEST_SUITE(exceptions) BOOST_AUTO_TEST_CASE(test_1) { BOOST_CHECK_EXCEPTION(a(true, true, false), error_c, contains_error_infos_cba); BOOST_CHECK_EXCEPTION(a(true, false, true), error_b, contains_error_infos_ba ); BOOST_CHECK_EXCEPTION(a(false, true, true), error_a, contains_error_infos_a ); } BOOST_AUTO_TEST_CASE(test_2) { try { a(true, true, false); } catch(...) { std::ostringstream oStr; oStr << "**********\n"; oStr << CURRENT_LOCATION() << '\n' << boost::current_exception_diagnostic_information(); oStr << "**********\n"; BOOST_TEST_MESSAGE(oStr.str()); } } BOOST_AUTO_TEST_CASE(test_3) { std::ostringstream oStr; oStr << "---\n"; BOOST_TEST(!stream_exception_and_map_to_bool(oStr, 1, 1.23, "param3")); oStr << "---\n"; BOOST_TEST_MESSAGE(oStr.str()); } BOOST_AUTO_TEST_SUITE_END()
true
65a5f4ce234abafb6ace7602585a9da7feba1623
C++
alexandraback/datacollection
/solutions_1285485_0/C++/yongheng5871/main.cpp
UTF-8
2,325
2.75
3
[]
no_license
#include<cstdio> #include<iostream> #include <cstring> #include <cmath> #include <vector> using namespace std; const int Maxn=33; char map[Maxn][Maxn]; int n,m; double d,x[2],y[2]; int eps(double x,double y) { if(fabs(x-y)<1e-10)return 0; return x<y?-1:1; } int dirx[]={-1,-1,1,1}; int diry[]={-1,1,-1,1}; int sx[]={0,0,1,1}; int sy[]={0,1,0,1}; struct Seg { double x,y; bool s; Seg(){s=0;} Seg(double _x,double _y):x(_x),y(_y){s=0;} double operator *(const Seg &a)const { return x*a.x+y*a.y; } double operator ^(const Seg &a)const { return x*a.y-y*a.x; } }; vector<Seg>vec; int main() { freopen("in.txt","r",stdin); freopen("out.txt","w",stdout); int t; scanf("%d",&t); for(int cas=1;cas<=t;++cas) { scanf("%d%d%lf",&n,&m,&d); for(int i=0;i<n;++i) { scanf("%s",map[i]); for(int j=0;j<m;++j) { if(map[i][j]=='X') { x[0]=2*j-1; x[1]=2*(m-1-j)-1; y[0]=2*i-1; y[1]=2*(n-1-i)-1; } } } int cnt=0; if(eps(x[0],d)<=0)cnt++; if(eps(x[1],d)<=0)cnt++; if(eps(y[0],d)<=0)cnt++; if(eps(y[1],d)<=0)cnt++; vec.clear(); for(int k=0;k<4;++k) { double xx=0; for(int i=sx[k];;i++) { xx+=dirx[k]*x[i&1]; if(eps(xx*xx,d*d)>0)break; double yy=0; for(int j=sy[k];;++j) { yy+=diry[k]*y[j&1]; if(eps(xx*xx+yy*yy,d*d)>0)break; vec.push_back(Seg(xx,yy)); } } } for(vector <Seg>::iterator it=vec.begin();it!=vec.end();it++) { if(it->s==1)continue; cnt++; for(vector <Seg>::iterator it2=it;it2!=vec.end();it2++) { if(it==it2)continue; if(eps((*it2)^(*it),0)==0&&eps((*it2)*(*it),0)>0) it2->s=1; } } printf("Case #%d: %d\n",cas,cnt); } }
true
99479cdacba59ccffdd505997b09d7f8ff511e0a
C++
leminhtr/PluriNotes_LO21
/waffichercouple.cpp
UTF-8
1,634
2.53125
3
[]
no_license
#include "waffichercouple.h" #include "relation.h" #include <QLabel> #include <QListWidget> #include <QLayout> #include <QPushButton> WindowAfficherCouple::WindowAfficherCouple(QString& relation_name, QWidget *parent): QWidget(parent) { setFixedSize(320,350); //NotesManager *NM = NotesManager::getInstance(); RelationManager* RM = RelationManager::getRelationManager(); Relation* r = RM->getRelationFromTitle(relation_name); titre_relation = new QHBoxLayout; titre_st = new QLabel("Les couples disponibles :"); couples = new QListWidget(this); QString arrow; if (r->getOrientee()) arrow = "------>"; else arrow = "------"; for (Relation::iterator it = r->begin(); it != r->end(); it++) { couples->addItem((*it)->getLabel()+": "+(*it)->getNote1().getId() + arrow + (*it)->getNote2().getId()); } fermer = new QPushButton("Fermer"); QObject::connect(fermer, SIGNAL(clicked()),this, SLOT(close())); creer_couple = new QPushButton("Creer couple"); //QObject::connect(creer_relation_orientee, SIGNAL(clicked()),this, SLOT(creerRelation())); supprimer_couple = new QPushButton("Supprimer couple"); //QObject::connect(supprimer_relation, SIGNAL(clicked()),this, SLOT(supprimerRelation())); horiz1 = new QHBoxLayout; horiz1->addWidget(supprimer_couple); horiz1->addWidget(fermer); horiz2 = new QHBoxLayout; horiz2->addWidget(creer_couple); verti = new QVBoxLayout; verti->addLayout(titre_relation); verti->addWidget(couples); verti->addLayout(horiz1); verti->addLayout(horiz2); setLayout(verti); }
true
776eec4c183e90634b338241b8d847c4f96bd52a
C++
KPO-2020-2021/zad5_1-Szymon-Sobczak
/tests/test_Scene.cpp
UTF-8
1,324
2.5625
3
[ "Unlicense" ]
permissive
#include "../tests/doctest/doctest.h" #include "Scene.hh" TEST_CASE("Test konstrukotra z parametrem klasy Scene wraz z metodami pozwlajacymi na pobieranie stalych danych o dronach ze sceny oraz zmiane aktywnego drona."){ PzG::LaczeDoGNUPlota Link; Scene Example(Link); CHECK ((Example.get_active_drone().get_drone_location()[0] == 100 && Example.get_active_drone().get_drone_location()[1] == 100 && Example.get_active_drone().get_drone_location()[2] == 3)); Example.choose_drone(2); CHECK ((Example.get_active_drone().get_drone_location()[0] == 50 && Example.get_active_drone().get_drone_location()[1] == 50 && Example.get_active_drone().get_drone_location()[2] == 3)); } TEST_CASE("Test reakcji metody,sluzacej do zmany aktywnego drona, na podanie blednego nueru indeksu. "){ PzG::LaczeDoGNUPlota Link; Scene Example(Link); WARN_THROWS(Example.choose_drone(-15)); } TEST_CASE("Test metody pozwalajacej na pobranie drona ze sceny w celu jego modyfikacji- zadaniu kata obrotu. "){ PzG::LaczeDoGNUPlota Link,Link2; Scene Example(Link); Vector3D test; CHECK ((Example.get_active_drone().get_angle() == 0)); Example.use_active_drone().update_angle(30); CHECK ((Example.get_active_drone().get_angle() == 30)); }
true
5a7306ae0abd5217218b3a1508004c2164a5f461
C++
AlikhanAldabergenov/TASK1-100
/16.cpp
UTF-8
208
2.796875
3
[]
no_license
#include <iostream> #include <cmath> #define _USE_MATH_DEFINES using namespace std; int main() { double a,b,c,x; cin>>a>>b>>c; x=a*2+(b-3)+pow(c,2); cout<<"Sum of 3 numbers:"<<x; return 0; }
true
16d6c6e0f3d248bfb05fd059eeea269a7e77ad1b
C++
Madfish5415/CCP_plazza_2019
/src/pizza/Recipe.cpp
UTF-8
1,908
3.015625
3
[]
no_license
/* ** EPITECH PROJECT, 2020 ** CPP_plazza_2019 ** File description: ** Recipe.cpp */ #include "Recipe.hpp" #include <regex> #include <utility> pizza::Recipe::Recipe() = default; pizza::Recipe::Recipe(std::string type, std::map<std::string, unsigned int> ingredients, unsigned int cookTime) : _type(std::move(type)), _ingredients(std::move(ingredients)), _cookTime(cookTime) { } pizza::Recipe::~Recipe() = default; std::string pizza::Recipe::getType() const { return this->_type; } const std::map<std::string, unsigned int>& pizza::Recipe::getIngredients() const { return this->_ingredients; } unsigned int pizza::Recipe::getCookTime() const { return this->_cookTime; } std::string pizza::Recipe::pack() const { std::string string; string += "type=\"" + this->_type + "\";"; string += "ingredients="; for (const auto& ingredient : this->_ingredients) { if (ingredient != *this->_ingredients.begin()) string += ","; string += "\"" + ingredient.first + "\":" + std::to_string(ingredient.second); } string += ";"; string += "cookTime=" + std::to_string(this->_cookTime) + ";"; return string; } void pizza::Recipe::unpack(const std::string& pack) { std::regex type("type=\"(.*?)\";"); std::regex ingredients("ingredients=(.*?);"); std::regex ingredient("\"([^:]+)\":(\\d+)"); std::regex cookTime("cookTime=(.*?);"); std::smatch match; if (std::regex_search(pack, match, type)) this->_type = match.str(1); if (std::regex_search(pack, match, ingredients)) { std::string find = match.str(1); while (std::regex_search(find, match, ingredient)) { this->_ingredients[match.str(1)] = std::stoi(match.str(2)); find = match.suffix(); } } if (std::regex_search(pack, match, cookTime)) this->_cookTime = std::stoi(match.str(1)); }
true
1d676680de3f1b04d16370c8b9ad213708565beb
C++
ousttrue/im3d_dll
/samples/win32_window.cpp
UTF-8
5,257
2.546875
3
[]
no_license
#include "win32_window.h" #include <Windows.h> #include <windowsx.h> // GET_X_LPARAM macros #include <assert.h> static LRESULT CALLBACK WindowProc(HWND _hwnd, UINT msg, WPARAM wParam, LPARAM lParam); class Win32WindowImpl *g_window = nullptr; static ATOM GetOrRegisterWindowClass(HINSTANCE hInstance, const TCHAR *className) { static ATOM wndclassex = 0; if (wndclassex == 0) { WNDCLASSEX wc = {0}; wc.cbSize = sizeof(wc); wc.style = CS_OWNDC; // | CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = WindowProc; wc.hInstance = hInstance; wc.lpszClassName = className; wc.hCursor = LoadCursor(0, IDC_ARROW); wndclassex = RegisterClassEx(&wc); } return wndclassex; } class Win32WindowImpl { HWND m_hwnd = NULL; int m_width = 0; int m_height = 0; MouseState m_mouseState = {0}; public: Win32WindowImpl(HWND hWnd) : m_hwnd(hWnd) { assert(g_window == nullptr); g_window = this; RECT rect; GetClientRect(hWnd, &rect); m_width = rect.right - rect.left; m_height = rect.bottom - rect.top; } ~Win32WindowImpl() { if (m_hwnd) { DestroyWindow(m_hwnd); } } HWND GetHandle() const { return m_hwnd; } void Resize(int w, int h) { m_width = w; m_height = h; } bool IsRunning() { MSG msg; while (PeekMessage(&msg, 0, 0, 0, PM_REMOVE) && msg.message != WM_QUIT) { TranslateMessage(&msg); DispatchMessage(&msg); } if (msg.message == WM_QUIT) { return false; } return true; } std::tuple<int, int> GetSize() const { return std::make_tuple(m_width, m_height); } const MouseState &GetMouseState() const { return m_mouseState; } MouseState &GetMouseState() { return m_mouseState; } }; static LRESULT CALLBACK WindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_SIZE: { auto w = (int)LOWORD(lParam); auto h = (int)HIWORD(lParam); g_window->Resize(w, h); break; } case WM_PAINT: ValidateRect(hWnd, 0); break; case WM_CLOSE: PostQuitMessage(0); break; case WM_MOUSEMOVE: { auto &mouse = g_window->GetMouseState(); mouse.X = GET_X_LPARAM(lParam); mouse.Y = GET_Y_LPARAM(lParam); return 0; } case WM_LBUTTONDOWN: { auto &mouse = g_window->GetMouseState(); mouse.Down(ButtonFlags::Left); return 0; } case WM_LBUTTONUP: { auto &mouse = g_window->GetMouseState(); mouse.Up(ButtonFlags::Left); return 0; } case WM_MBUTTONDOWN: { auto &mouse = g_window->GetMouseState(); mouse.Down(ButtonFlags::Middle); return 0; } case WM_MBUTTONUP: { auto &mouse = g_window->GetMouseState(); mouse.Up(ButtonFlags::Middle); return 0; } case WM_RBUTTONDOWN: { auto &mouse = g_window->GetMouseState(); mouse.Down(ButtonFlags::Right); return 0; } case WM_RBUTTONUP: { auto &mouse = g_window->GetMouseState(); mouse.Up(ButtonFlags::Right); return 0; } case WM_MOUSEWHEEL: { auto &mouse = g_window->GetMouseState(); mouse.Wheel = GET_WHEEL_DELTA_WPARAM(wParam); return 0; } default: break; }; return DefWindowProc(hWnd, msg, wParam, lParam); } Win32Window::Win32Window() { } Win32Window::~Win32Window() { if (m_impl) { delete m_impl; m_impl = nullptr; } } bool Win32Window::Create(int w, int h, const wchar_t *title) { auto hInstance = GetModuleHandle(0); auto wndClass = GetOrRegisterWindowClass(hInstance, L"Win32WindowImpl"); auto hWnd = CreateWindowEx( WS_EX_APPWINDOW | WS_EX_WINDOWEDGE, MAKEINTATOM(wndClass), title, WS_OVERLAPPEDWINDOW | WS_MINIMIZEBOX | WS_SYSMENU | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, CW_USEDEFAULT, CW_USEDEFAULT, w, h, nullptr, nullptr, hInstance, this); if (hWnd == NULL) { return false; } m_impl = new Win32WindowImpl(hWnd); ShowWindow(hWnd, SW_SHOW); return true; } bool Win32Window::IsRunning() { return m_impl->IsRunning(); } void *Win32Window::GetHandle() const { return m_impl->GetHandle(); } std::tuple<int, int> Win32Window::GetSize() const { return m_impl->GetSize(); } bool Win32Window::HasFocus() const { return m_impl->GetHandle() == GetFocus(); } MouseState Win32Window::GetMouseState() const { auto state = m_impl->GetMouseState(); m_impl->GetMouseState().Wheel = 0; // clear return state; } float Win32Window::GetTimeSeconds() const { return timeGetTime() * 0.001f; }
true
6ce6bcc7678b08d74a0a995838dd84939b5be89b
C++
fpawel/hromat900
/Source/Application/BinStream.hpp
WINDOWS-1251
2,597
2.765625
3
[]
no_license
#ifndef MY_BIN_STREAM_HLPR #define MY_BIN_STREAM_HLPR #define VCL_IOSTREAM #include "MyIostream.h" #include "MyExcpt.hpp" #include "crc16.h" DECLARATE_AND_DEFINE_MY_EXCEPTION_CLASS_(CantReadIStream, Exception ); DECLARATE_AND_DEFINE_MY_EXCEPTION_CLASS_(CantWriteOStream, Exception ); class MyBinaryIStreamHlpr : public CalcCRC16Hlpr { public: typedef void (__closure *OnReadMthd)(const char*, unsigned); explicit MyBinaryIStreamHlpr( std::istream& strm, bool enableThrow = true, unsigned short crc16 = 0xFFFF ) : CalcCRC16Hlpr( crc16 ), strm_(strm), enableThrow_(enableThrow) {} template<class T> void operator>>(T& t ) const { DoRead<T*>( &t, sizeof(t) ); } template<class T> T Get() const { T t; DoRead<T*>( &t, sizeof(T) ); return t; } template<class T> void ReadArray(T* p, unsigned size ) const { DoRead<T*>( p, size*sizeof(T) ); } bool CheckCRC16() const { this->Get<unsigned char>(); this->Get<unsigned char>(); return this->GetCRC16()==0; } private: mutable std::istream& strm_; const bool enableThrow_; template<class T> void DoRead( T t, unsigned sz ) const { char* p = reinterpret_cast<char*>( t ); strm_.read( p, sz ); if( strm_.fail() && enableThrow_ ) MY_THROW_CLASS_(MyCantReadIStreamException, " ."); UpdateCRC16( (unsigned char*) p, sz ); } }; class MyBinaryOStreamHlpr : public CalcCRC16Hlpr { public: explicit MyBinaryOStreamHlpr( std::ostream& strm, unsigned short crc16 = 0xFFFF ) : CalcCRC16Hlpr( crc16 ), strm_(strm) {} template<class T> void operator<<(const T& t ) const { DoWrite<const T*>( &t, sizeof(t) ); } template<class T> void WriteArray(const T* p, unsigned size ) const { DoWrite<const T*>( p, size*sizeof(T) ); } void FixCRC16() const { const unsigned short crc16 = this->GetCRC16(); const unsigned char ch[2] = {crc16 >> 8, crc16 }; WriteArray<unsigned char>(ch,2); assert( this->GetCRC16()==0 ); } private: mutable std::ostream& strm_; template<class T> void DoWrite( T t, unsigned sz ) const { const char* p = reinterpret_cast<const char*>( t ); strm_.write( p, sz ); if( strm_.fail() ) MY_THROW_CLASS_(MyCantWriteOStreamException, " "); UpdateCRC16( (unsigned char*) p, sz ); } }; #endif
true
d3ff0b4b6762a989c5ccd9dd585e222bee1a9eb5
C++
luklieb/waveguide
/waveguide.cpp
UTF-8
2,049
2.734375
3
[]
no_license
#include <stdlib.h> #include <stdio.h> #include <iostream> #include <fstream> #include <string> #include <cmath> #include "Source/Colsamm.h" typedef struct{ double x; double y; } point; typedef struct{ uint16_t v0; uint16_t v1; uint16_t v2; } face; void readInput( point* points, face* faces ){ double i, x, y; double v0, v1, v2; // read points std::string line; std::ifstream infile ("unit_circle.txt"); if (infile.is_open()) { std::getline(infile, line); std::getline(infile, line); for(int j=0; j<= 1038; j++) { infile >> i >> x >> y; points[j].x = x; points[j].y = y; } // read faces std::getline(infile, line); std::getline(infile, line); for(int j=0; j<= 1976; j++) { infile >> v0 >> v1 >> v2; faces[j].v0 = v0; faces[j].v1 = v1; faces[j].v2 = v2; } infile.close(); } else std::cout << "Unable to open file"; } void setK( point* points, double* k, double delta ){ for( int i =0; i <= 1039; i++ ){ k[i] = (100.0 + delta )* std::exp( -50.0 * ((points[i].x*points[i].x) + (points[i].y*points[i].y)) ) - 100.0; } } void testK( point* points, double* k ){ double x, y, k2; std::ifstream infile ("ksq-ref.txt"); for(int j=0; j<= 1038; j++) { infile >> x >> y >> k2; if( points[j].x != x || points[j].y != y || k[j] != k2 ){ std::cout << "Error: x: " << x << " y: " << y << " k: " << k2 << std::endl; std::cout << "Expected: x: " << points[j].x << " y: " << points[j].y << " k: " << k[j] << std::endl; } } } int main( int args, char** argv ){ if( args != 3 ){ std::cout << "Usage: ./waveguide delta epsilon" << std::endl; exit( EXIT_SUCCESS ); } double delta = 0.0; //double epsilon = 0.0; point points[1039]; face faces[1977]; double k[1039]; delta = atof( argv[1] ); //epsilon = atof( argv[2] ); readInput( points, faces ); setK( points, k, delta ); testK( points, k ); exit( EXIT_SUCCESS ); }
true
d7eb71548e4c695ec6903d96d265147e8203c4c7
C++
aliceresearch/MAGPIE
/src/scenarios/ant/nodes/AntLeftNode.h
UTF-8
605
2.96875
3
[]
no_license
#ifndef ANTLEFTNODE_H #define ANTLEFTNODE_H #include "../../../gp/Node.h" /** * {@link Ant} node for turning left 90&deg;. * @author David Bennett */ class AntLeftNode : public Node { public: /** Constructs the node with an arity of 0 and the name 'Left'. */ AntLeftNode() : Node(0, "Left") { } /** Turns the {@link Ant} left 90&deg;. */ void evaluate(Individual *individual, QStack<Node *> *programStack); /** Clones the node. */ Node *clone() const; /** Create a new {@link AntLeftNode} */ static Node *create() { return new AntLeftNode(); } }; #endif // ANTLEFTNODE_H
true
67317e3b7d6196606fb417711742c887eb45ec67
C++
1135037047/-
/每日一题/7.16/7.16/test.cpp
UTF-8
811
3.09375
3
[]
no_license
#if 0 #include <iostream> #include <vector> using namespace std; bool IsLeapYear(const int& year) { if (year % 4 == 0) { if (year % 100 == 0) { if (year % 400 == 0) { return true; } else { return false; } } else { return true; } } else { return false; } } int main() { int year, month, day; while (cin >> year >> month >> day) { int res = 0; if (year < 0 || month > 12 || month < 0 || day < 0) { cout << -1 << endl; //return 0; continue; } vector<int> moday{ 0,31,28,31,30,31,30,31,31,30,31,30,31 }; if (IsLeapYear(year)) { moday[2] += 1; } if (day > moday[month]) { cout << -1 << endl; //return 0; continue; } for (int i = 1; i < month; i++) { res += moday[i]; } res += day; cout << res << endl; } return 0; } #endif
true
21d9b6470318caea31d6e0e9478e193e22e2db26
C++
tenawalcott/cc3k-project
/main.cc
UTF-8
8,593
3.15625
3
[]
no_license
#include <iostream> #include <string> #include <fstream> #include <memory> #include "floor.h" #include "display.h" #include "character.h" #include <sstream> #include "item.h" class Shade; class Vampire; class Goblin; class Drow; class Troll; using namespace std; string intToStr(int num) { string result; stringstream ss; ss << num; result = ss.str(); return result; } int main(int argc, const char* argv[]) { while (1) { Shade shade; Vampire v; Goblin g; Drow d; Troll t; bool hostile = false; Player *p = &shade;// default setting cout<<"Welcome to the world of CC3K! Please chouse your character race"<<endl; string r; // s, d, v, g, t: specifies the race the player wishes to be when starting a game. cout << "v for Vampire || Health: 50 || Attack: 25 || Defence: 25 || Skills: gain 5HP for every successful attack." << endl; cout << "g for Goblin || Health: 110 || Attack: 15 || Defence: 20 || Skills: steal 5 gold from every enemy slained." << endl; cout << "d for Drow || Health: 150 || Attack: 25 || Defence: 15 || Skills: all potions' effect are magnified by 1.5." << endl; cout << "t for Troll || Health: 120 || Attack: 25 || Defence: 15 || Skills: regain 5HP every turn." << endl; cout << "s for Shade || Health: 125 || Attack: 25 || Defence: 25 || Skills: no skills."<<endl; cout << "Max health of all race except vampire is capped at their starting HP." << endl; cout << "Warning: If an invalid command is taken, the default character Shade will be chosen" << endl; string race = "Shade"; cin >> r; if(r == "v"){ p = &v; race = "Vampire"; } else if (r =="g"){ p = &g; race = "Goblin"; } else if(r == "d"){ p = &d; race = "Drow"; } else if(r == "t"){ p = &t; race = "Troll"; } Floor f; if(argc == 2){ string filename = argv[1]; Floor floor {filename, p,1}; f = floor; } else if(argc==1){ // we don't have command line arguments Floor floor {p,1}; f = floor; } string s; string action = "Player character has spawned."; // used to print action mode int n = 1; cout<< f <<endl; cout<<"Race: "<<race<<" Gold: "<< p->getGold(); cout<<" Floor: "<< n << endl; cout<<"HP: "<<p->getHealth()<<endl; cout<<"Atk: "<<p->getAttack()<<endl; cout<<"Def: "<<p->getDefence()<<endl; cout << "Action: "; cout<<action<<endl; while(true){ if(p->getSign()== 'T'){ p->change(5); if (p->getHealth() >= 120) { p->setHealth(); } } action = ""; cin>> s; if(s == "no" || s == "ne" || s == "ea" || s == "se" || s == "so" || s == "sw" || s == "we" || s == "nw"){ string direction; if(s == "no"){ direction = "North"; } else if(s == "ne"){ direction = "NorthEast"; } else if(s == "ea"){ direction = "East"; } else if(s == "se"){ direction = "SouthEast"; } else if(s == "so"){ direction = "South"; } else if(s == "sw"){ direction = "SouthWest"; } else if(s == "we"){ direction = "West"; } else if(s == "nw"){ direction = "NorthWest"; } action += "PC moves "; action += direction; f.move_player(s, action); if(f.getState()){ n++; if(n == 6){ cout<<"Congratulation! You reach the end of adventure."<<endl; int shade_gold = 0; string gold; if (p->getSign() == 'S') { shade_gold = p->getGold()*1.5; gold = intToStr(shade_gold); } else { gold = intToStr(p->getGold()); } cout << "In this game, you have scored " + gold + "." << endl; cout<<"Do you want to play again: r to play again, q to quit"<<endl; } else { p->changeCorrection(); p->setCorrection(); if(argc == 2){ string filename = argv[1]; Floor floor {filename, p,n}; f = floor; } else if(argc==1){ // we don't have command line arguments Floor floor {p,n}; f = floor; } if (hostile) { f.setHostile(); } action += " and go upstair"; } } else { f.move_enemy(action); shared_ptr<Display> display = f.getDisplay(); bool state = false; for(int i = -1;i<2;i++){ for(int j = -1;j<2;j++){ char c = display->getChar(p->getRow()+i,p->getCol()+j); if(c=='P'){ action +=" and see an unknown Potion"; state = true; break; } } if(state) break; } } } else if(s == "a"){ cin>>s; if(s == "no" || s == "ne" || s == "ea" || s == "se" || s == "so" || s == "sw" || s == "we" || s == "nw"){ f.attack(s,action); f.move_enemy(action); if (f.getMerchantHostile()) { hostile = true; } } } else if(s == "u"){ cin>>s; if(s == "no" || s == "ne" || s == "ea" || s == "se" || s == "so" || s == "sw" || s == "we" || s == "nw"){ f.use_potion(s,action); f.move_enemy(action); } } else if(s=="r"){ int shade_gold = 0; string gold; if (p->getSign() == 'S') { shade_gold = p->getGold()*1.5; gold = intToStr(shade_gold); } else { gold = intToStr(p->getGold()); } cout << "In this game, you have scored " + gold + "." << endl; break; } else if(s=="q"){ int shade_gold = 0; string gold; if (p->getSign() == 'S') { shade_gold = p->getGold()*1.5; gold = intToStr(shade_gold); } else { gold = intToStr(p->getGold()); } cout << "In this game, you have scored " + gold + "." << endl; cout<<"Thanks for your adventure. Good luck next time."<<endl; break; } else { action = "Invalid command"; } if (n <= 5) { cout<<f; cout<<"Race:: "<<race<<" Gold: "<< p->getGold(); cout<<" "<<"Floor: "<<n << endl; cout<<"HP: "<<p->getHealth()<<endl; cout<<"Atk: "<<p->getAttack()<<endl; cout<<"Def: "<<p->getDefence()<<endl; cout << "Action: "; cout<< action <<"."<<endl; } if (f.isLost()) { string read; int shade_gold = 0; string gold; if (p->getSign() == 'S') { shade_gold = p->getGold()*1.5; gold = intToStr(shade_gold); } else { gold = intToStr(p->getGold()); } cout << "In this game, you have scored " + gold + "." << endl; cout << "DEFEATED. You have been slained by enemies." << endl; cout << "Do you wanna try again?"<<endl; cout<<endl<<endl; cout<<"r for yes and q for no"<<endl; while (1) { cin >> read; if (read == "r" || read == "q") { break; } cout << "Invalid Command. Please choose r for yes and q for no."; } if (read == "q") { s = "q"; } break; } } if (s == "q") { cout<<"Game ended."<<endl; break; } } }
true
34f64465012bd74a4cb6fa50a5876a8da5a258d3
C++
JCiroR/Competitive-programming
/Problems/Topic-specific/ProblemSolvingParadigms/DP/10664Luggage.cpp
UTF-8
1,046
2.78125
3
[]
no_license
#include <cstring> #include <cstdio> #include <algorithm> #include <string> #include <sstream> #include <iostream> using namespace std; const int MAXM = 21; const int MAXT = 200; int nums[MAXM]; bool knap[MAXT + 1]; bool func(int target, int n) { knap[0] = true; for(int i = 0; i < n; i++) for(int j = MAXT; j >= 0; j--) { if(knap[j] && j + nums[i] <= MAXT) knap[j + nums[i]] = true; } return knap[target]; } int main(void) { int m; scanf("%d", &m); string temp3; getline(cin, temp3); while(m--) { string temp; int temp2; getline(cin, temp); memset(nums, 0, sizeof(nums)); memset(knap, false, sizeof(knap)); stringstream ss; ss << temp; int n = 0; int total = 0; for(int i = 0; ss >> temp2; i++) { nums[i] = temp2; total += temp2; n++; } if(total % 2 == 0 && func(total/2, n)) cout << "YES\n"; else cout << "NO\n"; } return 0; }
true
83779ca5dbef83a95792c9d516ffd03e6715ffdc
C++
vik228/SpojCodes
/SUMFOUR.cpp
UTF-8
947
2.6875
3
[]
no_license
#include<iostream> #include<algorithm> #include<cstdlib> #include<cstdio> #include<cstring> using namespace std; int a[4000],b[4000],c[4000],d[4000]; int lhs[16000001],rhs[16000001]; int main() { int n; int* lhs_ptr; int* rhs_ptr; lhs_ptr=lhs; rhs_ptr=rhs; scanf("%d",&n); for(int i=0;i<n;i++) scanf("%d%d%d%d",&a[i],&b[i],&c[i],&d[i]); int it1=0; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { lhs[it1]=a[i]+b[j]; rhs[it1++]=-(c[i]+d[j]); } } sort(lhs_ptr,lhs_ptr+it1); sort(rhs_ptr,rhs_ptr+it1); int ans=0; pair<int*,int*> pi; for(int i=0;i<it1;i++) { int val=lhs[i]; /* int* low = lower_bound(rhs_ptr,rhs_ptr+it1,val); int index_low = low - rhs_ptr; int* high = upper_bound(rhs_ptr,rhs_ptr+it1,val); int index_high = high - rhs_ptr; ans+=index_high-index_low; */ pi=equal_range(rhs_ptr,rhs_ptr+it1,val); ans+=(pi.second-rhs_ptr)-(pi.first-rhs_ptr); } printf("%d\n",ans); return 0; }
true
97e3c983292da190a1c5fb8aa592436bdb4ae050
C++
AhJo53589/leetcode-cn
/problems/longest-palindromic-substring/SOLUTION.cpp
UTF-8
1,213
3.15625
3
[]
no_license
////////////////////////////////////////////////////////////////////////// void findPalindrome(string s, int &low, int &high) { while (s[low] == s[high]) { low--; high++; if (low < 0 || high > s.size() - 1) break; } low++; high--; } string longestPalindrome(string s) { if (s.size() == 1) return s; string ans; ans.push_back(s[0]); for (int i = 1; i < s.size(); i++) { if (s[i] == s[i - 1]) { int low = i - 1; int high = i; findPalindrome(s, low, high); if (high - low + 1 > ans.size()) { ans = s.substr(low, high - low + 1); } } if ((i + 1 < s.size()) && s[i - 1] == s[i + 1]) { int low = i - 1; int high = i + 1; findPalindrome(s, low, high); if (high - low + 1 > ans.size()) { ans = s.substr(low, high - low + 1); } } } return ans; } ////////////////////////////////////////////////////////////////////////// string _solution_run(string s) { return longestPalindrome(s); } //#define USE_SOLUTION_CUSTOM //string _solution_custom(TestCases &tc) //{ //} ////////////////////////////////////////////////////////////////////////// //#define USE_GET_TEST_CASES_IN_CPP //vector<string> _get_test_cases_string() //{ // return {}; //}
true