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
9f64d26f628b7081702a761a0d52715a1928a855
C++
JJuOn/Algorithm-Study
/11000~11999/11724.cpp
UTF-8
1,118
3.171875
3
[]
no_license
#include <iostream> #include <algorithm> #include <stack> #include <queue> #include <vector> using namespace std; bool visitable(vector<bool> visited, int& startNode) { int size = visited.size(); for (int i = 0; i < size; i++) { if (!visited[i]) { startNode = i; return true; } } return false; } void BFS(vector<int> a[], vector<bool>& visited, int currentNode, int n) { queue<int> q; q.push(currentNode); visited[currentNode] = true; while (!q.empty()) { int node = q.front(); q.pop(); for (int i = 0; i < a[node].size(); i++) { if (!visited[a[node][i]]) { visited[a[node][i]] = true; q.push(a[node][i]); } } } } int main() { ios::sync_with_stdio(false); cout.tie(NULL); cin.tie(NULL); int n, m, count = 0, startNode; vector<int> *a; cin >> n >> m; a = new vector<int>[n + 1]; vector<bool> visited(n + 1, false); visited[0] = true; for (int i = 0; i < m; i++) { int b, c; cin >> b >> c; a[b].push_back(c); a[c].push_back(b); } while (visitable(visited, startNode)) { BFS(a, visited, startNode, n); count++; } cout << count << "\n"; return 0; }
true
145667122646fbc182ad66c7d0cf4292ee41b397
C++
zacharyvincze/sdl2-boilerplate
/src/sdl2-boilerplate/graphics.cpp
UTF-8
2,032
2.984375
3
[]
no_license
#include "graphics.h" Graphics::Graphics(std::string title, int window_width, int window_height) { SDL_Init(SDL_INIT_EVERYTHING); IMG_Init(IMG_INIT_PNG); this->window = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, window_width, window_height, SDL_WINDOW_FULLSCREEN_DESKTOP); this->renderer = SDL_CreateRenderer(this->window, -1, SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_ACCELERATED); SDL_RenderSetLogicalSize(renderer, window_width, window_height); SDL_ShowCursor(SDL_FALSE); } Graphics::~Graphics() { for (std::map<std::string, SDL_Texture*>::iterator i = this->sprite_sheets.begin(); i != this->sprite_sheets.end(); i++) { SDL_DestroyTexture(i->second); } SDL_DestroyWindow(this->window); SDL_DestroyRenderer(this->renderer); this->renderer = NULL; this->window = NULL; } void Graphics::clear() { SDL_SetRenderDrawColor(this->renderer, 0, 0, 0, 1); SDL_RenderClear(this->renderer); } SDL_Texture* Graphics::loadImage(std::string file) { if (this->sprite_sheets.count(file) == 0) { SDL_Surface* surface = IMG_Load(file.c_str()); if (surface == NULL) printf("Could not load image!\n"); this->sprite_sheets[file] = SDL_CreateTextureFromSurface(this->renderer, surface); SDL_FreeSurface(surface); } return this->sprite_sheets[file]; } void Graphics::render(SDL_Texture *source, SDL_Rect *source_rect, SDL_Rect *destination_rect) { if (source_rect) { destination_rect->w = source_rect->w; destination_rect->h = source_rect->h; } SDL_RenderCopy(this->renderer, source, source_rect, destination_rect); } void Graphics::rect(SDL_Rect& rect) { SDL_RenderDrawRect(this->renderer, &rect); } void Graphics::present() { SDL_RenderPresent(this->renderer); } void Graphics::pixel(int x, int y) { SDL_RenderDrawPoint(this->renderer, x, y); } void Graphics::setDrawColor(uint8_t r, uint8_t g, uint8_t b, uint8_t a) { SDL_SetRenderDrawColor(this->renderer, r, g, b, a); } void Graphics::destroyTexture(SDL_Texture* texture) { SDL_DestroyTexture(texture); }
true
6565e67a072d651e06feef2d8970e857a25e476a
C++
zeroli/playground
/list/merge_sortedlist.cc
UTF-8
6,059
4.375
4
[]
no_license
/* Merge two sorted linked lists Write a SortedMerge() function that takes two lists, each of which is sorted in increasing order, and merges the two together into one list which is in increasing order. SortedMerge() should return the new list. The new list should be made by splicing together the nodes of the first two lists. For example if the first linked list a is 5->10->15 and the other linked list b is 2->3->20, then SortedMerge() should return a pointer to the head node of the merged list 2->3->5->10->15->20. There are many cases to deal with: either ‘a’ or ‘b’ may be empty, during processing either ‘a’ or ‘b’ may run out first, and finally there’s the problem of starting the result list empty, and building it up while going through ‘a’ and ‘b’. Method 1 (Using Dummy Nodes) The strategy here uses a temporary dummy node as the start of the result list. The pointer Tail always points to the last node in the result list, so appending new nodes is easy. The dummy node gives tail something to point to initially when the result list is empty. This dummy node is efficient, since it is only temporary, and it is allocated in the stack. The loop proceeds, removing one node from either ‘a’ or ‘b’, and adding it to tail. When we are done, the result is in dummy.next. Below image is a dry run of the above approach: /* C++ program to merge two sorted linked lists */ #include <bits/stdc++.h> using namespace std; /* Link list node */ class Node { public: int data; Node* next; }; /* pull off the front node of the source and put it in dest */ void MoveNode(Node** destRef, Node** sourceRef); /* Takes two lists sorted in increasing order, and splices their nodes together to make one big sorted list which is returned. */ Node* SortedMerge(Node* a, Node* b) { /* a dummy first node to hang the result on */ Node dummy; /* tail points to the last result node */ Node* tail = &dummy; /* so tail->next is the place to add new nodes to the result. */ dummy.next = NULL; while (1) { if (a == NULL) { /* if either list runs out, use the other list */ tail->next = b; break; } else if (b == NULL) { tail->next = a; break; } if (a->data <= b->data) MoveNode(&(tail->next), &a); else MoveNode(&(tail->next), &b); tail = tail->next; } return(dummy.next); } /* UTILITY FUNCTIONS */ /* MoveNode() function takes the node from the front of the source, and move it to the front of the dest. It is an error to call this with the source list empty. Before calling MoveNode(): source == {1, 2, 3} dest == {1, 2, 3} Affter calling MoveNode(): source == {2, 3} dest == {1, 1, 2, 3} */ void MoveNode(Node** destRef, Node** sourceRef) { /* the front source node */ Node* newNode = *sourceRef; assert(newNode != NULL); /* Advance the source pointer */ *sourceRef = newNode->next; /* Link the old dest off the new node */ newNode->next = *destRef; /* Move dest to point to the new node */ *destRef = newNode; } /* Function to insert a node at the beginging of the linked list */ void push(Node** head_ref, int new_data) { /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } /* Function to print nodes in a given linked list */ void printList(Node *node) { while (node!=NULL) { cout<<node->data<<" "; node = node->next; } } /* Driver code*/ int main() { /* Start with the empty list */ Node* res = NULL; Node* a = NULL; Node* b = NULL; /* Let us create two sorted linked lists to test the functions Created lists, a: 5->10->15, b: 2->3->20 */ push(&a, 15); push(&a, 10); push(&a, 5); push(&b, 20); push(&b, 3); push(&b, 2); /* Remove duplicates from linked list */ res = SortedMerge(a, b); cout << "Merged Linked List is: \n"; printList(res); return 0; } /* Method 2 (Using Local References) This solution is structurally very similar to the above, but it avoids using a dummy node. Instead, it maintains a struct node** pointer, lastPtrRef, that always points to the last pointer of the result list. This solves the same case that the dummy node did — dealing with the result list when it is empty. If you are trying to build up a list at its tail, either the dummy node or the struct node** “reference” strategy can be used (see Section 1 for details). */ Node* SortedMerge(Node* a, Node* b) { Node* result = NULL; /* point to the last result pointer */ Node** lastPtrRef = &result; while(1) { if (a == NULL) { *lastPtrRef = b; break; } else if (b==NULL) { *lastPtrRef = a; break; } if(a->data <= b->data) { MoveNode(lastPtrRef, &a); } else { MoveNode(lastPtrRef, &b); } /* tricky: advance to point to the next ".next" field */ lastPtrRef = &((*lastPtrRef)->next); } return(result); } /* Method 3 (Using Recursion) Merge is one of those nice recursive problems where the recursive solution code is much cleaner than the iterative code. You probably wouldn’t want to use the recursive version for production code however, because it will use stack space which is proportional to the length of the lists. */ Node* SortedMerge(Node* a, Node* b) { Node* result = NULL; /* Base cases */ if (a == NULL) return(b); else if (b == NULL) return(a); /* Pick either a or b, and recur */ if (a->data <= b->data) { result = a; result->next = SortedMerge(a->next, b); } else { result = b; result->next = SortedMerge(a, b->next); } return(result); }
true
311d77a43fb8b4fecba84b29492f7a959c454e50
C++
echener/Airship
/Code/RaspberryPi/hardware/motor/motor.cpp
UTF-8
2,048
2.859375
3
[]
no_license
#include <stdlib.h> #include <unistd.h> #include <stdexcept> #include "motor.h" //TODO: reduce TIMEs to minimum and find optimal values for PWs (pulse width) #define ZERO_PW 1100 #define MAX_PW (1900 - ZERO_PW) #define ZERO_TIME (500 * 1000) #define RELAIS_TIME (6 * 1000) //from datasheet #define ARM_TIME (2 * 1000 * 1000) //from datasheet Motor::Motor(int pwmPin, int relaisPin) : pwmPin(pwmPin), relaisPin(relaisPin) { this->pwmPin.setPinMode(PIN_OUTPUT); this->relaisPin.setPinMode(PIN_OUTPUT); this->relaisPin.writePin(LOW); usleep(RELAIS_TIME); powerOn(); lastThrust = 0; } Motor::~Motor() { powerOff(); } int Motor::thrust2pw(int thrust) { return ZERO_PW + abs(thrust) * MAX_PW / MAX_THRUST; } void Motor::setZero() { pwmPin.setPulsewidth(ZERO_PW); //turn motor off usleep(ZERO_TIME); //wait until it halts lastThrust = 0; } void Motor::setESC(int pw) { pwmPin.setPulsewidth(pw); } void Motor::setThrust(int thrust) { if(thrust > MAX_THRUST || thrust < -MAX_THRUST) throw std::invalid_argument("set motor thrust: thrust is out of bounds"); if(thrust > 0) { if(lastThrust < 0) { setZero(); relaisPin.writePin(LOW); //turn off the relais usleep(RELAIS_TIME); //wait until the relais switches position } setESC(thrust2pw(thrust)); } else if(thrust < 0) { if(lastThrust >= 0) { if(lastThrust > 0) setZero(); relaisPin.writePin(HIGH); //turn the relais on usleep(RELAIS_TIME); //wait until the relais switches position } setESC(thrust2pw(thrust)); } else if(lastThrust != 0) { //thrust == 0 setZero(); relaisPin.writePin(LOW); //turn off the relais usleep(RELAIS_TIME); //wait until the relais switches position } lastThrust = thrust; } void Motor::powerOn(){ pwmPin.setPulsewidth(ZERO_PW); usleep(ARM_TIME); } void Motor::powerOff() { setThrust(0); pwmPin.setPulsewidth(0); } int Motor::getThrust() { return lastThrust; }
true
286211938d723ab7b0717e8e576b3d10f89693f1
C++
zero0/zp4
/ZeroPoint4/RenderingOpenGL/zpOpenGLBuffer.h
UTF-8
899
2.609375
3
[]
no_license
#pragma once #ifndef ZP_OPENGL_BUFFER_H #define ZP_OPENGL_BUFFER_H class zpBufferImpl { public: zpBufferImpl(); ~zpBufferImpl(); void create( zpBufferType type, zpBufferBindType bind, zp_uint count, zp_uint stride, void* data = 0 ); void destroy(); void map( void** data, zpMapType mapType = ZP_MAP_TYPE_WRITE_DISCARD, zp_uint subResource = 0 ); void unmap( zp_uint subResource = 0 ); void update( zp_uint count, void* data ); zp_uint getCount() const; zp_uint getStride() const; zpBufferType getBufferType() const; zpDisplayFormat getFormat() const; zpBufferBindType getBufferBindType() const; private: zp_uint m_count; zp_uint m_stride; zpBufferType m_type; zpDisplayFormat m_format; zpBufferBindType m_bind; zp_uint m_target; zp_uint m_buffer; friend class zpRenderingEngineImpl; friend class zpRenderingContextImpl; }; #endif
true
b39cdde1ce91f3256237612ce2ad6f82b000a537
C++
camperjett/DSA_dups
/Datastructures/005 Trees/create_tree_iterative.cpp
UTF-8
5,160
3.578125
4
[]
no_license
#include<bits/stdc++.h> using namespace std; class node{ public: int data; node* lchild = nullptr; node* rchild = nullptr; node(int data){ this->data = data; } }; node* input_tree(){ cout<<"Enter root data: "<<endl; int temp; cin>>temp; node* root = new node(temp); queue <node* > q; q.push(root); while(!q.empty()){ node* p = q.front(); cout<<"Left y/n for "<<p->data<<" "<<endl; char c; cin>>c; if(c=='y'){ cout<<"Enter left child of "<<p->data<<" "<<endl; int temp; cin>>temp; node* left_child = new node(temp); p->lchild = left_child; q.push(p->lchild); } cout<<"Right y/n of "<<p->data<<" "<<endl; cin>>c; if(c=='y'){ cout<<"Enter right child of"<<p->data<<" "<<endl; int temp; cin>>temp; node* right_child = new node(temp); p->rchild = right_child; q.push(p->rchild); } q.pop(); } return root; } node* test_input(){ node* root = new node(1); root->lchild = new node(2); root->rchild = new node(3); root->lchild->lchild = new node(4); root->lchild->rchild = new node(5); root->rchild->lchild = new node(6); root->rchild->rchild = new node(7); return root; } void iterative_preorder(node* root){ stack <node* > st; while(!(root==nullptr && st.empty())){ if(root!=nullptr){ cout<<root->data<<" "; st.push(root); root = root->lchild; }else{ root = st.top(); st.pop(); root = root->rchild; } } } void iterative_inorder(node* root){ stack <node* > st; while(!(root==nullptr && st.empty())){ if(root!=nullptr){ st.push(root); root = root->lchild; }else{ root = st.top(); st.pop(); cout<<root->data<<" "; root = root->rchild; } } } // 0->left child // 1->right child // 2-> current node void iterative_postorder(node* root){ // stack < pair<node*, int>> st; // pair< node*, int> p; // p = make_pair(root, 0); // st.push(p); // while(!st.empty()){ // // p = st.top(); // st.pop(); // if(p.first==nullptr){ // continue; // } // if(p.second==0){ // p = make_pair(p.first, 1); // st.push(p); // if(p.first->lchild){ // p = make_pair(p.first->lchild, 0); // st.push(p); // } // }else if(p.second==1){ // p = make_pair(p.first, 2); // st.push(p); // if(p.first->rchild){ // p = make_pair(p.first->rchild, 0); // st.push(p); // } // }else if(p.second==2){ // cout<<p.first->data<<" "; // } // } stack <node* > st; while(!(root==nullptr && st.empty())){ if(root!=nullptr){ st.push(root); root = root->lchild; }else{ node* temp = st.top()->rchild; if(temp){ // check if the node has a right subtree. if it has, move node there. root = temp; }else{ temp = st.top(); st.pop(); cout<<temp->data<<" "; // at this point, we are sure that temp has no left child as well as right child, so print while(!st.empty() && temp == st.top()->rchild){ temp = st.top(); // after printing the right child in prev step, print the node itself now. st.pop(); cout<<temp->data<<" "; } } } } cout<<endl; } void level_order(node* root){ queue< node* > q; cout<<root->data<<" "; q.push(root); while(!q.empty()){ if(q.front()->lchild){ cout<<q.front()->lchild->data<<" "; q.push(q.front()->lchild); } if(q.front()->rchild){ cout<<q.front()->rchild->data<<" "; q.push(q.front()->rchild); } q.pop(); } } int count_(node* root){ if(root==nullptr){ return 0; } return count_(root->lchild)+count_(root->rchild)+1; } int height(node* root){ if(root==nullptr){ return 0; } int x = height(root->lchild); int y = height(root->rchild); if(x>y){ return x+1; }else{ return y+1; } } int fun(node* root){ if(root==nullptr){ return 0; } int x = fun(root->lchild); int y = fun(root->rchild); if(root->lchild==nullptr && root->rchild==nullptr){ // count leaf nodes. change this condition to get primary, secondary etc. return x+y+1; }else{ return x+y; } } int main(){ node* root = test_input(); iterative_postorder(root); iterative_inorder(root); cout<<endl; level_order(root); cout<<endl; cout<<count_(root)<<" "<<height(root)<<endl; cout<<fun(root)<<endl; return 0; }
true
5b4b18f6dfa3fa6a7b8c492f93ee88f9614f0ffe
C++
wideglide/CS3021
/Class711.cpp
UTF-8
936
3.5625
4
[]
no_license
//============================================================================ // Name : Classroom1.cpp // Author : // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> using namespace std; int mypower(int n, int i) { if (i < 0) { return -1; } int result = 1; while (i > 0) { result = n * result; //result *= n i--; } return result; } int square(int n) { return n * n; } int main() { int val = mypower(2, -4); if (val < 0) { cout << "Error"<< endl; } else { cout << "Result " << val << endl; } cout << "2 ** -4 " << mypower(2, -4) << endl; // cout << "5 ** 0 " << mypower(5, 0) << endl; /* int cnt = 1; while (cnt <= 10) { cout << cnt << " " << square(cnt) << endl; cnt = cnt + 1; //cnt += 1 or cnt++ } */ return 0; }
true
75f4e2f90f623f2cdde943f4c2b2644fc863b77b
C++
caffedrine/Arduino
/Projects/Tests/DRV8834_StepperMotorNonblockingLoop/DRV8834_StepperMotorNonblockingLoop.ino
UTF-8
1,113
2.984375
3
[]
no_license
/* Simple Stepper Motor Control * -- NON-BLOCKING LOOP -- */ #include <Arduino.h> #include "../libs/my_util.h" #include "StepperPWM.h" // All the wires needed for full functionality #define DIR 8 #define STEP 9 #define ENBL 13 // microsteps pins #define MS1 10 #define MS2 11 #define MS3 12 StepperPWM stepper(DIR, STEP, ENBL, MS1, MS2, MS3); void setup() { //Start serial communication Serial.begin(115200); Serial.println("---START---"); //Init motor if(stepper.init()) { Serial.println("Motor initialized!"); stepper.brake(); } else Serial.println("ERROR: Can't initialize motor with given pins!"); stepper.enable(); stepper.setFrequency(2000); } unsigned long speed = 200; //microseconds void loop() { if(Serial.available()) { int readVal = to_int ( Serial.readString() ); if(readVal == 0) { speed = 200; stepper.brake(); Serial.println("BRAKE!"); } else { speed = readVal; stepper.setFrequency(speed); stepper.enable(); stepper.run(); //Write val right away ^_^ Serial.println("NEW SPEED: " + to_string(speed)); } } stepper.run(); }
true
99cbff4ca211d668c55efbc90231beb50e369bba
C++
arushnagpal/fictional-disco
/leetcode/701.cpp
UTF-8
873
3.40625
3
[]
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: TreeNode* helperutil(TreeNode* root, int val){ if(root==NULL){ return root; } if(root->left!=NULL && val<=root->val){ helperutil(root->left, val); } if(root->right!=NULL && val>root->val){ helperutil(root->right, val); } if(root->right==NULL && val>root->val){ root->right = new TreeNode(val); } if(root->left==NULL && val<=root->val){ root->left = new TreeNode(val); } return root; } TreeNode* insertIntoBST(TreeNode* root, int val) { return helperutil(root, val); } };
true
f4ff8b87cf0b520e61ece39615b7d2916f470d66
C++
swizzley/skeksis
/type.hpp
UTF-8
5,711
3.078125
3
[]
no_license
#pragma once #include <map> #include <memory> #include <string> #include <vector> #include <iostream> #include "rapidjson/document.h" #include "rapidjson/writer.h" #include "rapidjson/stringbuffer.h" template <typename T> void toJson(const T& v, rapidjson::Document& document, const char* key) { document.AddMember(key, v, document.GetAllocator()); } template<> void toJson<std::string>(const std::string& str, rapidjson::Document& document, const char* key); // Define the "parameter" class. Right now this just has getters and // setters. It will eventually do validation, munging, // (de)serialization, etc. If you have special needs for validation, // etc you can simply subclass this and shadow methods. It's all // staticly resolved by the compiler, so there is no need for these to // be virtual. template<typename data_type, typename name_tag> class param { public: using type = data_type; type value; const char* name() const { return name_tag::name(); } const data_type& get() const { return value; }; // There's no reason this can't be templatized to support perfect // forwarding, I'm just lazy. void set(type v) { value = v; }; bool isValid() const { return true; }; }; // The base type, with no parameters. This should have base virtual // methods for dealing with (de)serialization and general interfacing // with the outside world, but right now it's empty. template<typename... parameters> class type; template<> class type<> { public: void param() const {}; virtual bool isValid() const { return true; } virtual void encodeParameters(rapidjson::Document&) const {}; std::string toJson() const { rapidjson::Document document; document.SetObject(); encodeParameters(document); rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); document.Accept(writer); return std::string(buffer.GetString()); } }; // This is the meat of this mess. This is a recursive template that // creates accessors for each parameter of the type. In the future it // will also define (de)serialization methods through a similar // recursive process. template<typename parameter, typename... rest> class type<parameter, rest...> : public type<rest...> { public: using type<rest...>::param; const parameter& param(parameter) const { return value; } parameter& param(parameter) { return value; }; virtual bool isValid() const { return value.isValid() && type<rest...>::isValid(); } virtual void encodeParameters(rapidjson::Document& document) const { toJson<typename parameter::type>(value.get(), document, value.name()); type<rest...>::encodeParameters(document); }; static int obj; private: parameter value; }; template <typename parameter, typename... rest> int type<parameter, rest...>::obj = 0; using type_ptr = std::unique_ptr<type<>>; class type_registry { public: class factory_base { public: virtual type_ptr create() const =0; virtual std::vector<type_ptr> instances() const =0; }; using factory_ptr = std::unique_ptr<factory_base>; static void register_factory(std::string name, factory_ptr factory) { factories[name] = std::move(factory); } static type_ptr create(std::string name) { return factories[name]->create(); } static std::vector<type_ptr> instances(std::string name) { if(factories[name]) return factories[name]->instances(); else return std::vector<type_ptr> {} ; } static std::vector<type_ptr> instances() { std::vector<type_ptr> result; for(auto& kv : factories) { auto instances = kv.second->instances(); std::move(instances.begin(), instances.end(), std::back_inserter(result)); } return result; } private: static std::map<std::string, factory_ptr> factories; }; template<typename type> class provider_registry { public: class factory_base { public: virtual std::vector<type_ptr> instances() const =0; }; using factory_ptr = std::unique_ptr<factory_base>; static void register_factory(factory_ptr factory) { factories.push_back(std::move(factory)); }; static std::vector<type_ptr> instances() { std::vector<type_ptr> result; for(auto& factory : factories) { auto instances = factory->instances(); std::move(instances.begin(), instances.end(), std::back_inserter(result)); } return result; }; private: static std::vector<factory_ptr> factories; }; template <typename T> std::vector<typename provider_registry<T>::factory_ptr> provider_registry<T>::factories; template <typename T> class register_type { public: class factory : public type_registry::factory_base{ type_ptr create() const { return std::unique_ptr<T>(new T); } std::vector<type_ptr> instances() const { return provider_registry<T>::instances(); } }; register_type<T>(std::string name) { type_registry::register_factory(name, std::unique_ptr<factory>(new factory)); }; }; template <typename type, typename T> class register_provider { public: class factory : public provider_registry<type>::factory_base { std::vector<type_ptr> instances() const { return T::instances(); } }; register_provider<type, T>() { provider_registry<type>::register_factory(std::unique_ptr<factory>(new factory)); }; }; #define PARAM(_name, type) struct _name##_tag { static const char* name() { return #_name; } }; using _name = param<type, _name##_tag>; #define REGISTER_TYPE(name) static register_type<name::type> register_##name(#name); #define REGISTER_PROVIDER(name, klass) static register_provider<name::type, klass> register_##name##_##klass;
true
bd1a8ff538f580b225db86a70a6cefcd397b2694
C++
Abdul-Hamid-k/CPP-Notes
/Polimorphism/BaseClassPointer/main.cpp
UTF-8
2,251
3.984375
4
[]
no_license
#include<iostream> #include<vector> using namespace std; class Account{ public: // For dinamic binding we need to make the function virtual, if we dont make the function virtual it will do static binding. // lets take a example Base and Derived are 2 class Derived inherit the Base, if I create a object on heap eg. Base *ptr = new Derived // it will point out the base becouse ptr is object of Base but created as Derived. // In simple words, Base *ptr = new Derived, will be object of- // 1.Base staticly, by default. // 2.Derived Dinemically, If virtual function is used. virtual void withdraw(double amount){ cout<<"In Account::Withdraw"<<endl; } }; class Saving:public Account{ public: virtual void withdraw(double amount){ cout<<"In Saving::Withdraw"<<endl; } }; class Checking:public Account{ public: virtual void withdraw(double amount){ cout<<"In Checking::Withdraw"<<endl; } }; class Trust:public Account{ public: virtual void withdraw(double amount){ cout<<"In Trust::Withdraw"<<endl; } }; int main(){ cout<<"========== Pointer =========="<<endl; Account *p1 = new Account (); Account *p2 = new Saving (); Account *p3 = new Checking (); Account *p4 = new Trust (); p1->withdraw(1000); p2->withdraw(1000); p3->withdraw(1000); p4->withdraw(1000); cout<<"========== Array =========="<<endl; Account *array[] = {p1,p2,p3,p4}; for (auto i = 0; i < 4; i++){ array[i]->withdraw(1000); } cout<<"========== Array =========="<<endl; array[0] = p4; for (auto i = 0; i < 4; i++){ array[i]->withdraw(1000); } cout<<"========== Vector =========="<<endl; vector<Account *> accounts {p1,p2,p3,p4}; for(auto acc_ptr: accounts){ acc_ptr->withdraw(1000); } cout<<"========== Vector =========="<<endl; accounts.push_back(p4); accounts.push_back(p4); for(auto acc_ptr: accounts){ acc_ptr->withdraw(1000); } cout<<"========== Clean up =========="<<endl; delete p1; delete p2; delete p3; delete p4; return 0; }
true
01939431a9b3b7982a0787a49fa578f4c0f2ae88
C++
ebshimizu/Lumiverse-Patcher
/Source/components/ControlsPanel.cpp
UTF-8
11,407
2.75
3
[]
no_license
#include "ControlsPanel.h" #include "../Main.h" LumiverseFloatPropertySlider::LumiverseFloatPropertySlider(string propertyName, DeviceSet devices, LumiverseFloat* val) : SliderPropertyComponent(propertyName, val->getMin(), val->getMax(), 0.001) { param = propertyName; // We don't want to immediately capture this device, so we don't calll the full // setVal here this->val = val->getVal(); slider.setValue(this->val); this->devices = devices; } void LumiverseFloatPropertySlider::setValue(double newValue) { val = newValue; slider.setValue(newValue); for (const auto& d : devices.getDevices()) { MainWindow::getRig()->getDevice(d->getId())->setParam(param, (float)newValue); } } void LumiverseFloatPropertySlider::sliderDragEnded(Slider* slider) { } LumiverseOrientationPropertySlider::LumiverseOrientationPropertySlider(string propertyName, DeviceSet devices, LumiverseOrientation* val) : SliderPropertyComponent(propertyName, val->getMin(), val->getMax(), 0.01) { param = propertyName; this->val = val->getVal(); slider.setValue(this->val); this->devices = devices; } void LumiverseOrientationPropertySlider::setValue(double newValue) { val = newValue; slider.setValue(newValue); for (const auto& d : devices.getDevices()) { MainWindow::getRig()->getDevice(d->getId())->setParam(param, (float)newValue); } } void LumiverseOrientationPropertySlider::sliderDragEnded(Slider* slider) { } LumiverseColorPropertySlider::LumiverseColorPropertySlider(string propertyName, string channelName, DeviceSet devices, double val) : SliderPropertyComponent(channelName, 0, 1, 0.001) { m_param = propertyName; m_channel = channelName; m_val = val; slider.setValue(m_val); m_devices = devices; } void LumiverseColorPropertySlider::setValue(double newVal) { m_val = newVal; slider.setValue(newVal); for (const auto& d : m_devices.getDevices()) { MainWindow::getRig()->getDevice(d->getId())->setParam(m_param, m_channel, newVal); } } void LumiverseColorPropertySlider::sliderDragEnded(Slider* slider) { } MetadataPropertyTextEditor::MetadataPropertyTextEditor(string propertyName, DeviceSet devices) : m_devices(devices), m_metadata(propertyName), TextPropertyComponent(propertyName, 128, false) { m_val = combineMetadataWithSameKey(devices.getAllMetadataForKey(m_metadata)); } string MetadataPropertyTextEditor::combineMetadataWithSameKey(set<string> metadata) { if (metadata.size() == 1) return *(metadata.begin()); else if (metadata.size() > 1) return "[Multiple Values]"; return "[Error: non-exist]"; } void MetadataPropertyTextEditor::setText(const String &newText) { if (newText.isEmpty()) { bool toDelete = false; { AlertWindow w("Delete Metadata", "Are you sure to delete this metadata field?", AlertWindow::QuestionIcon); w.addButton("Yes", 1, KeyPress(KeyPress::returnKey, 0, 0)); w.addButton("Cancel", 0, KeyPress(KeyPress::escapeKey, 0, 0)); toDelete = (w.runModalLoop() != 0); } if (toDelete) { for (Device *dev : m_devices.getDevices()) { dev->deleteMetadata(m_metadata); } } } else { for (Device *dev : m_devices.getDevices()) { dev->setMetadata(m_metadata, newText.toStdString()); } m_val = newText.toStdString(); } } void MetadataPropertyButton::buttonClicked() { bool hasInput = false; String name; String val; // The popped up window only exists in this block. So when // we go back to invoke update, it would be passed to the // right target (MainWindow). { AlertWindow w("New Metadata", "Enter a name and a value for the new metadata.", AlertWindow::QuestionIcon); w.addTextEditor("name", "Name", "List Name:"); w.addTextEditor("val", "Value", "List Value:"); w.addButton("Create", 1, KeyPress(KeyPress::returnKey, 0, 0)); w.addButton("Cancel", 0, KeyPress(KeyPress::escapeKey, 0, 0)); if (w.runModalLoop() != 0) // is they picked 'ok' { // this is the text they entered.. name = w.getTextEditorContents("name"); val = w.getTextEditorContents("val"); hasInput = true; } } if (hasInput) { for (Device *dev : m_devices.getDevices()) { dev->setMetadata(name.toStdString(), val.toStdString()); } } } //============================================================================== DMXPatchAddrProperty::DMXPatchAddrProperty(string patchID, string deviceID) : TextPropertyComponent(patchID + ": Address", 10, false), _patchID(patchID), _deviceID(deviceID) {} void DMXPatchAddrProperty::setText(const String& newText) { if (newText == "") { MainWindow::getRig()->getPatchAsDMXPatch(_patchID)->deleteDevice(_deviceID); } else { auto info = MainWindow::getRig()->getPatchAsDMXPatch(_patchID)->getDevicePatch(_deviceID); if (info != nullptr) { info->setBaseAddress(newText.getIntValue() - 1); } else { string dmxMap = MainWindow::getRig()->getDevice(_deviceID)->getType(); MainWindow::getRig()->getPatchAsDMXPatch(_patchID)->patchDevice(_deviceID, new DMXDevicePatch(dmxMap, newText.getIntValue() - 1, 0)); } } MainWindow::getApplicationCommandManager().invokeDirectly(MainWindow::refresh, false); } String DMXPatchAddrProperty::getText() const { auto info = MainWindow::getRig()->getPatchAsDMXPatch(_patchID)->getDevicePatch(_deviceID); if (info != nullptr) { return String(info->getBaseAddress() + 1); } else { return "Not Patched"; } } //============================================================================== DMXPatchUniverseProperty::DMXPatchUniverseProperty(string patchID, string deviceID) : TextPropertyComponent(patchID + ": Universe", 10, false), _patchID(patchID), _deviceID(deviceID) {} void DMXPatchUniverseProperty::setText(const String& newText) { if (newText == "") { MainWindow::getRig()->getPatchAsDMXPatch(_patchID)->deleteDevice(_deviceID); } else { auto info = MainWindow::getRig()->getPatchAsDMXPatch(_patchID)->getDevicePatch(_deviceID); if (info != nullptr) { info->setUniverse(newText.getIntValue() - 1); } else { string dmxMap = MainWindow::getRig()->getDevice(_deviceID)->getType(); MainWindow::getRig()->getPatchAsDMXPatch(_patchID)->patchDevice(_deviceID, new DMXDevicePatch(dmxMap, 0, newText.getIntValue() - 1)); } } MainWindow::getApplicationCommandManager().invokeDirectly(MainWindow::refresh, false); } String DMXPatchUniverseProperty::getText() const { auto info = MainWindow::getRig()->getPatchAsDMXPatch(_patchID)->getDevicePatch(_deviceID); if (info != nullptr) { return String(info->getUniverse() + 1); } else { return "Not Patched"; } } // ============================================================================ ControlsPanel::ControlsPanel() { properties.setName("Device Properties"); properties.setMessageWhenEmpty("No Devices Selected"); addAndMakeVisible(properties); } ControlsPanel::~ControlsPanel() { } void ControlsPanel::paint(Graphics& g) { g.fillAll(Colours::grey); } void ControlsPanel::resized() { properties.setBounds(getLocalBounds()); } void ControlsPanel::updateProperties(DeviceSet activeDevices) { // Process for this is to look at what components needed to be added, add and sort them // and then display them properties.clear(); // Start with active parameters // Multiple selection items will pull initial values from the first element found for now // Later, may add options for relative value adjustments // This will almost certainly need to be broken up and organized at some point. // Should probably have some maps that translate param to cleaner name + category. Array<PropertyComponent*> paramComponents; Array<PropertyComponent*> colorComponents; Array<PropertyComponent*> beamComponents; Array<PropertyComponent*> controlComponents; Array<PropertyComponent*> metadataComponents; set<std::string> metadata = activeDevices.getAllMetadata(); set<std::string> params = activeDevices.getAllParams(); const set<Device*>& devices = activeDevices.getDevices(); for (std::string param : params) { for (auto d : devices) { if (d->paramExists(param)) { // The update source matters mostly at this part, where we pick the data // we put into the programmer. If we're doing a cue, things get more complicated. LumiverseType* p = nullptr; // Pull value from rig p = MainWindow::getRig()->getDevice(d->getId())->getParam(param); if (p->getTypeName() == "float") { LumiverseFloatPropertySlider* comp = new LumiverseFloatPropertySlider(param, activeDevices, (LumiverseFloat*) p); paramComponents.add(comp); break; } else if (p->getTypeName() == "enum") { LumiverseEnumPropertyComponent* comp = new LumiverseEnumPropertyComponent(param, activeDevices, (LumiverseEnum*) p); if (param == "rainbow" || param == "colorWheel") colorComponents.add(comp); else if (param == "control" || param == "moveSpeed") controlComponents.add(comp); else if (param == "shutter" || param == "gobo" || param == "goboRot" || param == "prism") beamComponents.add(comp); else paramComponents.add(comp); break; } else if (p->getTypeName() == "color") { LumiverseColor* c = (LumiverseColor*)p; for (const auto& kvp : c->getColorParams()) { colorComponents.add(new LumiverseColorPropertySlider(param, kvp.first, activeDevices, kvp.second)); } break; } else if (p->getTypeName() == "orientation") { LumiverseOrientationPropertySlider* comp = new LumiverseOrientationPropertySlider(param, activeDevices, (LumiverseOrientation*) p); paramComponents.add(comp); break; } else { // Don't do anything for unknown types. Can't interact with what you don't understand. } } } } // Next add metadata. Values with multiples will be marked. for (std::string meta : metadata) { MetadataPropertyTextEditor* comp = new MetadataPropertyTextEditor(meta, activeDevices); metadataComponents.add(comp); } if (activeDevices.size() > 0) metadataComponents.add(new MetadataPropertyButton(activeDevices)); if (paramComponents.size() > 0) properties.addSection("General", paramComponents); if (beamComponents.size() > 0) properties.addSection("Beam", beamComponents); if (colorComponents.size() > 0) properties.addSection("Color", colorComponents); if (controlComponents.size() > 0) properties.addSection("Control", controlComponents); if (metadataComponents.size() > 0) properties.addSection("Metadata", metadataComponents); // Finally patch data if there's a single device selected. if (devices.size() == 1) { string deviceID = ""; for (auto d : devices) { deviceID = d->getId(); break; } Array<PropertyComponent*> patchComponents; for (const auto& kvp : MainWindow::getRig()->getPatches()) { if (kvp.second->getType() == "DMXPatch") { // Add DMX properties patchComponents.add(new DMXPatchUniverseProperty(kvp.first, deviceID)); patchComponents.add(new DMXPatchAddrProperty(kvp.first, deviceID)); } } properties.addSection("Patch", patchComponents); } }
true
c4f578f5ad0c8588eb7fee9009a77e90f904d520
C++
KevinPolez/Evolution
/include/Animation.h
UTF-8
752
2.5625
3
[]
no_license
#ifndef ANIMATION_H #define ANIMATION_H #include "Object.h" namespace evo { class Animation : public evo::Object { public: Animation(int width, int height); ~Animation(); void setTextureSprite(SDL_Texture *texture); void setAnimationFrameCount(int animationFrameCount); void setSpeed(int speed); void setFpsLimit(int fps); // override void nextAnimationFrame(); void draw(); protected: private: SDL_Texture* textureSprite; int animationFrameCount; int currentFrame; int speed; int fps; int line; int ticks; }; } #endif
true
3cdf94493b42f754c3001035219c7e149594fcff
C++
uofuseismo/rtseis
/include/rtseis/utilities/interpolation/linear.hpp
UTF-8
6,786
3.265625
3
[ "MIT" ]
permissive
#ifndef RTSEIS_UTILITIES_INTERPOLATION_LINEAR_HPP #define RTSEIS_UTILITIES_INTERPOLATION_LINEAR_HPP 1 #include <memory> namespace RTSeis::Utilities::Interpolation { /*! * @class Linear linear.hpp "rtseis/utilities/interpolation/linear.hpp" * @brief A class for performing linear interpolation. * @author Ben Baker (University of Utah) * @copyright Ben Baker distributed under the MIT license. * @ingroup rtseis_utils_math_interpolation */ class Linear { public: /*! @name Constructors * @{ */ /*! * @brief Default constructor. */ Linear(); /*! * @brief Move constructor. * @param[in,out] linear The linear interpolation class from which to * initialize this class. On exit, linear's behavior * is undefined. */ Linear(Linear &&linear) noexcept; /*! @} */ /*! * @brief Move assignment operator. * @param[in,out] linear The linear interoplation class to move. * On exit, linear's behavior is undefined. * @result Linear's memory onto this. */ Linear& operator=(Linear &&linear) noexcept; /*! @name Destructor * @{ */ /*! * @brief Default destructor. */ ~Linear(); /*! * @brief Releases all memory on the module and resets the class. */ void clear() noexcept; /*! @} */ /*! * @brief Initializes the linear interpolation over the closed interval * [xInterval.first, xInterval.second] with regularly spaced * function values \f$ y(x) \f$. * @param[in] npts The number of data points in y. This must be at * least 2. * @param[in] xInterval The closed interval which begins at xInterval.first * and ends at xInterval.second. xInterval.first must * be less than xInterval.second. * @param[in] y The function values. This is an array of dimension * [npts]. * @throws std::invalid_argument if any of the arguments are invalid. */ void initialize(int npts, const std::pair<double, double> xInterval, const double y[]); /*! * @brief Initializes the linear interpolation for data points defined * at \f$ y(x) \f$. * @param[in] npts The number of data points in x and y. This must be * at least 2. * @param[in] x The ordinates at which y is evaluated. This is an * array of dimension [npts] with the further caveat * that * \f$ x_i < x_{i+1} \forall i=0,\cdots,n_{pts}-2 \f$. * @param[in] y The function values. This is an array of dimension * [npts]. * @throws std::invalid_argument if any of the arguments are invalid. */ //void initialize(int npts, // const double x[], // const double y[]); /*! * @brief Determines if the class has been initialized or not. * @retval True indicates that the class was inititalized. */ bool isInitialized() const noexcept; /*! * @brief Gets the minimum x ordinate that can be interpolated. * @retval The minimum x value that can be interpolated. * @throws std::runtime_error if the class is not initialized. * @sa isInitialized() */ double getMinimumX() const; /*! * @brief Gets the maximum x ordinate that can be interpolated. * @retval The maximum x value that can be interpolated. * @throws std::runtime_error if the class is not initialized. * @sa isInitialized() */ double getMaximumX() const; /*! * @brief Interpolates function values \f$ y_q = f(x_q) \f$ where \f$ f \f$ * is the linear interpolating function. * @param[in] nq The number of points at which to interpolate. * @param[in] xq The abscissas at which to interpolate yq. This is * an array of dimension [nq]. Additionally, each * xq must be in the range * [\c getMinimumX(), \c getMaximumX()]. * @param[out] yq The interpolated values at \f$ x_q \f$. This is an * array of dimension [nq]. * @throws std::runtime_error if the class was not initialized. * @throws std::invalid_argument if xq or yq is NULL or any xq is * out of the interpolation range. * @sa isInitialized(), getMinimumX(), getMaximum() */ void interpolate(int nq, const double xq[], double *yq[]) const; /*! * @brief Initializes the linear interpolation for data points defined * at \f$ y(x) \f$. * @param[in] npts The number of data points in x and y. This must be * at least 2. * @param[in] x The ordinates at which y is evaluated. This is an * array of dimension [npts] with the further caveat * that * \f$ x_i < x_{i+1} \forall i=0,\cdots,n_{pts}-2 \f$. * @param[in] y The function values. This is an array of dimension * [npts]. * @throws std::invalid_argument if any of the arguments are invalid. */ void initialize(int npts, const double x[], const double y[]); /*! * @brief Interpolates the function faluves \f$ y_q = f(x_q) \f$ where * \f$ f \f$ is the linear interpolation function. This is for * evenly spaced points on the interval [xq.first, xq.second]. * @param[in] nq The number of points at which to interpolate. * @param[in] xq The interval over which to interpolate. Note, that * xq.first must be less than xq.second. * @param[out] yq The interpolated values at the evenly spaced points on * the interval given by \f$ x_q \f$. This is an array * of dimension [nq]. Note, \f$ y_q[0] = f(x_q.first) \f$ * and \f$ y_q[nq-1] = f(x_q.second \f$. * @throws std::runtime_error if the class was not initialized. * @throws std::invalid_argument if xq.first is less than \c getMinimumX() * or xq.second is greater than \c getMaximumX() * or xq.first >= xq.second. * @sa isInitialized(), getMinimumX(), getMaximum() */ void interpolate(int nq, const std::pair<double, double> xq, double *yq[]) const; private: class LinearImpl; std::unique_ptr<LinearImpl> pImpl; Linear& operator=(const Linear &linear) = delete; }; } #endif
true
8aef34e3b30f0d43c36b08e21c420dd5e9919036
C++
fuzh97/leetcode
/code/0139.单词拆分.cpp
UTF-8
1,306
3.234375
3
[]
no_license
/* * @lc app=leetcode.cn id=139 lang=cpp * * [139] 单词拆分 */ // @lc code=start class Solution { public: bool wordBreak(string s, vector<string>& wordDict) { queue<int> q; vector<bool> visited(s.size() + 1, false); q.push(0); visited[0] = true; while (!q.empty()) { int levelSize = q.size(); for (int i = 0; i < levelSize; i++) { int start = q.front(); q.pop(); for (string nextWord : wordDict) { int len = nextWord.length(); if (s.length() < start + len) continue; //如果起点位置加上当前位置已经超出本身长度 if (nextWord == s.substr(start)) return true; //下一个单词刚好为最后一个单词 if (visited[start + len]) continue; //该位置已经访问过 if (s.substr(start, len) == nextWord) { //判断能否匹配 q.push(start + len); visited[start + len] = true; // break; } } } } return false; } }; // @lc code=end
true
32aeb9357e54ae396d3da8461df63b9b94b41b8f
C++
mubai-victor/DataStructure
/Memory/AllocBuddy/Source/Function.cpp
UTF-8
2,652
2.734375
3
[]
no_license
#include "stdafx.h" #include "Function.h" #include "Test.h" using namespace std; cAlloc::cAlloc() { root = NULL; } cAlloc::~cAlloc() { delete[] root; root = NULL; } void cAlloc::Init() { for (int i = 0; i <= SIZE; i++) { a[i].first = NULL; a[i].nodesize = pow(2, i); } root = a[SIZE].first = new WORD_b[int(pow(2, SIZE))]; a[SIZE].first->kval = SIZE; a[SIZE].first->llink = a[SIZE].first; a[SIZE].first->rlink = a[SIZE].first; a[SIZE].first->tag = FREE; } Space cAlloc::AllocBuddy(int n) { Space p = NULL, pFree = NULL; int i = 0, k = 0; for (i = 0; i <= SIZE && (a[i].nodesize < n + 1 || a[i].first == NULL); i++); if (i > SIZE) { return NULL; } p = a[i].first; if (p->llink == p->rlink) { a[i].first = NULL; } else { a[i].first = p->llink; p->llink->rlink = p->rlink; p->rlink->llink = p->llink; } for (k = 1; a[i - k].nodesize >= n + 1; k++) { pFree = p + int(pow(2, i - k)); pFree->kval = i - k; pFree->llink = pFree; pFree->rlink = pFree; pFree->tag = FREE; a[i - k].first = pFree; } p->kval = i - k + 1; p->tag = USED; return p; } Space cAlloc::Buddy(Space p) { if ((p - root) % (int(pow(2, p->kval + 1))) == 0) { return p + int(pow(2, p->kval)); } else { return p - int(pow(2, p->kval)); } } void cAlloc::Reclaim(Space &p) { Space sBuddy = Buddy(p); while (p >= root&&p <= root + int(pow(2, SIZE)) && sBuddy->kval == p->kval&&sBuddy->tag == FREE) { if (sBuddy->rlink == sBuddy) { a[sBuddy->kval].first = NULL; } else { sBuddy->llink->rlink = sBuddy->rlink; sBuddy->rlink->llink = sBuddy->llink; if (a[sBuddy->kval].first == sBuddy) { a[sBuddy->kval].first = sBuddy->llink; } } if (sBuddy > p) { p->kval++; } else { sBuddy->kval++; p = sBuddy; } sBuddy = Buddy(p); } if (a[p->kval].first == NULL) { a[p->kval].first = p; p->llink = p; p->rlink = p; } else { p->rlink = a[p->kval].first; p->llink = a[p->kval].first->llink; p->llink->rlink = p; p->rlink->llink = p; a[p->kval].first = p; } p->tag = FREE; p = NULL; } void cAlloc::Print() { Space pTemp = NULL; for (int i = 0; i <= SIZE; i++) { pTemp = a[i].first; if (pTemp != NULL) { do { cout << "Size of block:" << a[i].nodesize << " Start address:" << pTemp << " State:" << ((pTemp->tag == FREE) ? "FREE" : "USED") << endl; pTemp = pTemp->rlink; } while (pTemp != a[i].first); } } } void cAlloc::PrintUser(Space p[]) { for (int i = 0; i <= SIZE; i++) { if (p[i] != NULL) { cout << "Size of blocks:" << a[p[i]->kval].nodesize << " Start address:" << p[i] << " State:" << ((p[i]->tag == FREE) ? "FREE" : "USED") << endl; } } }
true
611888a93ac680ad2fe9b09ae56de508cd394ba6
C++
LauZyHou/Algorithm-To-Practice
/AcWing/LeetCode究极班/542.cpp
UTF-8
1,140
2.8125
3
[ "MIT" ]
permissive
#define x first #define y second typedef pair<int, int> PII; class Solution { public: vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) { if (matrix.empty() || matrix[0].empty()) return matrix; int n = matrix.size(), m = matrix[0].size(); // 距离数组 vector<vector<int>> dist(n, vector<int>(m, -1)); // bfs队列 queue<PII> q; // 先将所有的0插入到队列里 for (int i = 0; i < n; i ++ ) for (int j = 0; j < m; j ++ ) if (matrix[i][j] == 0) { dist[i][j] = 0; q.push({i, j}); } // 四个方向 int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1}; while (q.size()) { auto t = q.front(); q.pop(); for (int i = 0; i < 4; i ++ ) { int a = t.x + dx[i], b = t.y + dy[i]; if (a >= 0 && a < n && b >= 0 && b < m && dist[a][b] == -1) { dist[a][b] = dist[t.x][t.y] + 1; q.push({a, b}); } } } return dist; } };
true
58120f600db985ea70fb80a8e7775e368e392f6e
C++
DKU-STUDY/Algorithm
/programmers/난이도별/level02.쿼드압축_후_개수_세기/6047198844.cpp
UTF-8
999
3.359375
3
[]
no_license
#include <string> #include <vector> using namespace std; int zero_one[2] = { 0,0 }; void divide_and_conquer(vector<vector<int>> &arr,int y, int x, int size) { if (size == 1) { zero_one[arr[y][x]]++; return; } bool check = true; for (int i = y; i < y + size; i++) { if (!check) break; for (int j = x; j < x + size; j++) { if (arr[y][x] != arr[i][j]) { check = false; break; } } } if (check) { zero_one[arr[y][x]]++; } else { divide_and_conquer(arr,y, x, size / 2); divide_and_conquer(arr,y + size / 2, x, size / 2); divide_and_conquer(arr,y, x + size / 2, size / 2); divide_and_conquer(arr,y + size / 2, x + size / 2, size / 2); } return; } vector<int> solution(vector<vector<int>> arr) { divide_and_conquer(arr,0, 0, arr[0].size()); vector<int> answer{ zero_one[0],zero_one[1] }; return answer; }
true
1233012e9895003523c839ff3d89f1f2d01866bf
C++
Aleks-P-97/Rings-Of-Time-3D-animation
/external/include/tygra/FileHelper.hpp
UTF-8
754
2.9375
3
[]
no_license
/** * @file FileHelper.hpp * @author Tyrone Davison * @date September 2012 */ #pragma once #ifndef __TYGRA_FILEHELPER__ #define __TYGRA_FILEHELPER__ #include <string> #include "Image.hpp" namespace tygra { /** * Construct a new string object with the contents of a text file. * @param A valid, full path to a text file to read. * @return The new new string object */ std::string stringFromFile(std::string filepath); /** * Construct a new image object with the contents of a PNG file. * @param A valid path to the PNG file to read. * @return The new image object. */ Image imageFromPNG(std::string filepath); } // end namespace tygra #endif
true
f72dae39a6ce7ffffa252f2a63b463f26e848e7c
C++
ZeroZhong/dataStructure
/stack_learn/stack/stack_c++.h
UTF-8
319
2.609375
3
[]
no_license
#include "../../vecter_learn/vector/vector_c++.h" namespace shitong { template <typename T> class Stack : Vector<T> { public: void push(T const &e) { insert(this->size(), e); } T pop() { return remove(this->size() - 1); } T &top() { return (*this)[this->size() - 1]; } }; }
true
a3f06fb52667a3ccd7af759fe1c5d1a437ccfc06
C++
ant512/WiredMunk
/client/trunk/src/wiredmunk/network/message.h
UTF-8
5,160
2.78125
3
[]
no_license
#ifndef _MESSAGE_H_ #define _MESSAGE_H_ #define MESSAGE_HEADER "WDMK" #define MESSAGE_HEADER_LENGTH 9 #include <string> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include "socketeventhandler.h" namespace WiredMunk { /** * Messages that are to be sent across the network should be sent as an * instance of this class. The message class formats the data into a * predefined structure that can be easily parsed and extracted at the * recipient. Each message has a type so that its purpose is clearly * identified. * * Messages can also include a response handler. This is a pointer to an * object that inherits from the SocketEventHandler class. If the pointer * is set and a reply to the message is received, the reply to the message * will cause the socket automatically to call the object's * handleResponseReceived() method. Responses to messages can therefore * be routed to specific objects. * * This enables a non-blocking design that allows for request/response * messaging. * * Message format: * 4 byte header: WDMK (identify message as a wired munk header) * 1 byte message type * 2 byte message length * 2 byte id number * n bytes data */ class Message { public: /** * Enum listing all types of message that can be sent/received. */ enum MessageType { MESSAGE_NONE = 1, /**< No message type; included for completeness */ MESSAGE_HANDSHAKE = 2, /**< Handshake between client and server sent at client startup */ MESSAGE_REJECT = 3, /**< Server rejects client's handshake because the session is full */ MESSAGE_STARTUP = 4, /**< Sent to clients to tell them to run their startup() method */ MESSAGE_READY = 5, /**< Sent to server to indicate client readiness and to clients to start session */ MESSAGE_PING = 6, /**< Not implemented */ MESSAGE_ACKNOWLEDGE = 7, /**< Not implemented */ MESSAGE_OBJECT_ID = 8, /**< Sent if client requesting a unique ID for an object */ MESSAGE_BODY = 9, /**< Message contains body data */ MESSAGE_SHAPE = 10, /**< Message contains shape data */ MESSAGE_SPACE = 11 /**< Message contains space data */ }; /** * Constructor. * @param type The type of the message. * @param dataLength The length of the message data. * @param data The message data. * @param responseHandler If not null, a response to this message is * sent to the specified SocketEventHandler. */ Message(MessageType type, unsigned short dataLength, const unsigned char* data, SocketEventHandler* responseHandler = NULL); /** * Constructor. Automatically splits data string into individual * message components. * @param data Data string containing message. * @param responseHandler If not null, a response to this message is * sent to the specified SocketEventHandler. */ Message(const unsigned char* data, SocketEventHandler* responseHandler = NULL); /** * Copy constructor. * @param copy Message to copy. */ Message(Message const& copy); /** * Destructor. */ ~Message(); /** * Get the message type. * @return The message type. */ inline const MessageType getType() const { return _type; }; /** * Get the message data. * @return The message data. */ inline const unsigned char* getData() const { return _data; }; /** * Get the SocketEventHandler that handles responses to this message. * @return The response handler. */ inline SocketEventHandler* getResponseHandler() const { return _responseHandler; }; /** * Get the ID of the message. * @return The ID of the message. */ inline unsigned short getId() const { return _id; }; /** * Get the length of the message data. * @return The length of the message data. */ inline unsigned short getDataLength() const { return _dataLength; }; /** * Get the entire message, with prefixed header, ready for transmission. * @param buffer Pointer to a buffer to fill with message data. * Buffer must be large enough to contain the entire formatted message; * use getFormattedMessageLength() to obtain this value. * @return Length of the message data. */ unsigned int getFormattedMessage(unsigned char* buffer) const; /** * Get the length of the formatted message. */ unsigned int getFormattedMessageLength() const; /** * Sets the message data. * @param data The message data. * @param dataLength The length of the message data. */ void setData(const unsigned char* data, unsigned short dataLength); private: unsigned short _dataLength; /**< Length of the data component */ MessageType _type; /**< Type of message */ unsigned char* _data; /**< Message data */ unsigned short _id; /**< Message ID */ SocketEventHandler* _responseHandler; /**< Handler for any received response */ static unsigned short _nextId; /**< ID of the next message */ /** * Get the ID of the next message to be created. */ inline unsigned short getNextId() { return _nextId++; }; }; } #endif
true
6f8b6fb1ff5ceeb139787e4c760232cc8c9cb80c
C++
buaaswf/ssss
/Bmpread.cpp
GB18030
1,816
2.65625
3
[]
no_license
#include <string.h> #include <stdio.h> /***һBMPͼƬõһά***/ typedef unsigned long DWORD; typedef unsigned short WORD; typedef unsigned int UINT; /* bitmap file header */ typedef struct tagBITMAPFILEHEADER { char type[2]; DWORD fileSize; WORD reserved1; WORD reserved2; DWORD offbits; } BITMAPFILEHEADER,*PBITMAPFILEHEADER; /* bitmap info header */ typedef struct tagBITMAPINFOHEADER { DWORD dwSize; DWORD width; DWORD height; WORD planes; WORD bpp; DWORD compression; DWORD sizeImage; DWORD hResolution; DWORD vResolution; DWORD colors; DWORD importantColors; } BITMAPINFOHEADER,*PBITMAPINFOHEADER; int LoadBMPHeader(BMP_Header *image, char *fileName) { image->fp = fopen(fileName, "rb"); if (image->fp == NULL) return -1;//ERR_FILE_CANT_OPEN; fseek(image->fp, 0, SEEK_SET); fread(&(image->fileHeader), sizeof(BITMAPFILEHEADER), 1, image->fp); fread(&(image->infoHeader), sizeof(BITMAPINFOHEADER), 1, image->fp); if (strncmp((char *)&(image->fileHeader.bfType), "BM", 2) != 0) { fclose(image->fp); return -1;//ERR_FMT_NOT_BMP } if (image->infoHeader.biCompression) { fclose(image->fp); return -1;//ERR_FMT_COMPRESSION } return 0; } /*main() { //char filename[255]; FILE* fp; BITMAPFILEHEADER fileHeader; BITMAPINFOHEADER infoHeader; DWORD width,height; //printf("input the filename of bitmap file:\n"); // scanf("%s",filename); //printf("%s\n",filename); fp=fopen("1.bmp","rb"); if(fp==NULL) { printf("open file error!\n"); exit(0); } fseek(fp,0,0); fread(&fileHeader,sizeof(fileHeader),1,fp); fseek(fp,sizeof(fileHeader),0); fread(&infoHeader,sizeof(infoHeader),1,fp); } */
true
de79cddd1dc68747f441fe18d2254253075e9cda
C++
rt77789/misc
/eps/hkmeans.cxx
UTF-8
5,493
2.640625
3
[]
no_license
#include <iostream> #include <cassert> #include <cstdio> #include <cmath> #include <vector> #include <set> #include <cstdlib> #include <fstream> #include <sstream> using namespace std; const int INF = 100000000; int label_num = 0; vector<vector<double> > vin; struct Node { // 199998 -> root_label. // [label|dims|childs] -> a block, write the block into the external space. vector<double> pos; vector<Node*> child; Node() {} Node(const vector<double> &_pos) { pos.assign(_pos.begin(), _pos.end()); } void insert_child(Node* _ch) { child.push_back(_ch); } void assign(vector<double> &_pos) { pos.assign(_pos.begin(), _pos.end()); } int get_dimension() const { return pos.size(); } vector<double>* get_pos() { return &pos; } vector<Node*>* get_child() { return &child; } }; vector<int> rand_medoids(int k, int n) { int seeds[n]; srand(time(0)); for(int i = 0; i < n; ++i) { seeds[i] = i; } for(int i = 0; i < k && i < n; ++i) { int index = rand() % (n-i) + i; int temp = seeds[i]; seeds[i] = seeds[index]; seeds[index] = temp; } vector<int> res; for(int i = 0; i < k && i < n; ++i) { res.push_back(seeds[i]); } return res; } pair<double, int> cross_correlation(const vector<double> &sa, const vector<double> &sb) { double ma = 0, mb = 0; assert(sa.size() == sb.size()); int len = sa.size(); for(int i = 0; i < len; ++i) { ma += sa[i]; mb += sb[i]; } ma /= len; mb /= len; double res = -INF; int offset = -INF; double deta = 0; double detb = 0; for(int i = 0; i < len; ++i) { deta += (sa[i] - ma) * (sa[i] - ma); detb += (sb[i] - mb) * (sb[i] - mb); } deta = sqrt(deta * detb); // cout << "-len " << -(int)len << endl; for(int d = -len; d < len; ++d) { // cout << "test" << endl; double num = 0; for(int i = 0; i < len; ++i) { num += (sa[i] - ma) * (sb[((i + d) % len + len) %len] - mb); } double rd = num / deta; if(rd > res) { res = rd; offset = d; } } // cout << "res: " << res << endl; return make_pair<double, int>(res, offset); } Node* build_tree(int K, vector<int> &belong, vector<vector<double> > &sigs) { assert(belong.size() > 0); assert(sigs.size() > 0); cout << "label: " << label_num++ << " " << belong.size() << endl; Node *ptr = new Node(); vector<double> mean(sigs[0].size(), 0); for(size_t j = 0; j < sigs[0].size(); ++j) { for(size_t i = 0; i < belong.size(); ++i) { mean[j] += sigs[belong[i]][j]; } mean[j] /= belong.size(); } ptr->assign(mean); if(belong.size() > 1) { vector<int> rbelong[K]; vector<int> medoids = rand_medoids(K, belong.size()); for(size_t i = 0; i < belong.size(); ++i) { int index = belong[i]; int mini = -1; // Max cross_correlation? double temp = -INF; for(int j = 0; j < K; ++j) { pair<double, int> res = cross_correlation(sigs[ belong[medoids[j]] ], sigs[index]); // cout << i << ' ' << j << ' ' << res.first << ' ' << res.second << endl; if(temp < res.first) { temp = res.first; mini = j; } } assert(mini != -1); rbelong[mini].push_back(index); } size_t rbsum = 0; for(int i = 0; i < K; ++i) { if(rbelong[i].size() > 0) { cout << "parent: " << label_num-1 << endl; Node *ch = build_tree(K, rbelong[i], sigs); ptr->insert_child(ch); } else { perror("rbelong[i].size() <= 0\n"); } rbsum += rbelong[i].size(); } assert(rbsum == belong.size()); } else if(belong.size() == 1) { // } return ptr; } vector<double> find_similar(Node *ptr, const vector<double> &sa) { assert((size_t)ptr->get_dimension() == sa.size()); vector<Node*> *child = ptr->get_child(); double sim = 0; Node *nn = NULL; for(size_t i = 0; i < child->size(); ++i) { vector<double> *pos = (*child)[i]->get_pos(); pair<double, int> temp = cross_correlation(*pos, sa); if(temp.first > sim) { sim = temp.first; nn = (*child)[i]; } cout << "temp.sim: " << temp.first << "\ttemp.offset: " << temp.second << endl; } cout << string(80, '-') << endl; if(nn != NULL) { return find_similar(nn, sa); } vector<double> *pos = ptr->get_pos(); pair<double, int> temp = cross_correlation(*pos, sa); cout << "sim: " << temp.first << " - [ "; for(size_t i = 0; i < pos->size(); ++i) { cout << (*pos)[i] << " "; } cout << " ]\n"; return *pos; } void load_in() { ifstream fin("fin"); assert(fin.is_open() == true); string line; while(getline(fin, line)) { istringstream sline(line); vector<double> dims; double m; while(sline >> m) { dims.push_back(m); } dims.reserve(dims.size()); vin.push_back(dims); } fin.close(); vin.reserve(vin.size()); } void print_vector(const vector<double> &v) { for(size_t i = 0; i < v.size(); ++i) { cout << v[i]; if(i + 1 == v.size()) cout << "\n"; else cout << "\t"; } } void print_now() { time_t t = time(0); char tmp[64]; strftime(tmp, sizeof(tmp), "%Y/%m/%d %X %A",localtime(&t)); puts(tmp); } void test() { assert(vin.size() > 0); print_vector(vin[0]); printf("search now...\n"); vector<int> belong; for(size_t i = 0; i < vin.size(); ++i) belong.push_back(i); Node *root = build_tree(2, belong, vin); vector<double> res = find_similar(root, vin[0]); printf("search over...\n"); print_vector(res); } int main() { print_now(); cout << "loading now..." << endl; load_in(); print_now(); cout << "loading over..." << endl; test(); print_now(); return 0; }
true
7e0477f07726fab4c410373a1df901e4e24185e5
C++
andrewome/kattis-problems
/guess.cpp
UTF-8
478
2.765625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { int guess = 500; int min = 1; int max = 1001; string input; cout << guess << endl; while(cin >> input) { if(input == "correct") { return 0; } if(input == "lower") { max = guess; } if(input == "higher") { min = guess; } guess = (max - min)/2 + min; cout << guess << endl; } }
true
b52e6046fea9ae0e577efe095cc55f6dee4b04ea
C++
showmic96/Online-Judge-Solution
/UVA/10312/12733852_AC_0ms_0kB.cpp
UTF-8
549
2.59375
3
[]
no_license
// In the name of Allah the Lord of the Worlds. #include<bits/stdc++.h> using namespace std; typedef long long ll; int main(void) { ll cat[30] , cat2[30]; cat[0] = 1; cat[1] = 1; cat2[0] = 1; cat2[1] = 1; cat2[2] = 1; cat2[3] = 3; for(ll i=1;i<30;i++){ cat[i] = cat[i-1]*2*(2*i+1)/(i+2); } for(ll i=4;i<30;i++){ cat2[i] = (3*(2*i-3)*cat2[i-1]-(i-3)*cat2[i-2])/i; } int n; while(scanf("%d",&n)==1){ printf("%lld\n",cat2[n]-cat[max(0, n-2)]); } return 0; }
true
a418d8a2e359bf7e5f4b37c955537781bb8ad33d
C++
Paulmburu/Primer_CPP
/M_t.cpp
UTF-8
485
3.171875
3
[]
no_license
#include <iostream> using namespace std; int main(){ constexpr size_t rowCnt = 3, colCnt = 4; int ia[rowCnt][colCnt]; // 12 uninitialized elements // for each row for (size_t i = 0; i != rowCnt; ++i) { // for each column within the row for (size_t j = 0; j != colCnt; ++j) { // assign the element's positional index as its value ia[i][j] = i * colCnt + j; } } for(int i=0;i!=rowCnt;++i){ for(int j=0;j!=colCnt;++j){ cout<<ia[i][j]<<" "; }cout<<endl; } }
true
a1d6d9d773309ebabf099a78fba8e1c6be45a7f1
C++
MinhazAbtahi/UVA
/11547 - Automatic Answer.cpp
UTF-8
344
2.640625
3
[]
no_license
#include <iostream> #include <algorithm> using namespace std; int main() { int t, n, result; cin>>t; for(int i=0;i<t;i++) { cin>>n; n *= 567; n /= 9; n += 7492; n *= 235; n /= 47; n -= 498; n = abs(n); result = (n/10)%10; cout<<result<<endl; } }
true
b847a46f7ac2a63c4d94e7316f6a4b2a758184cf
C++
0xGoerliMainnet/Zorro-Kraken-Plugin
/json.cpp
UTF-8
2,060
2.546875
3
[]
no_license
//#include <curl/curl.h> #include <stdlib.h> #include "json.h" #include "log.h" #include "buf.h" #define BUFFER_SIZE 32768 #define JSON_TOKENS 256 static size_t fetch_data(void *buffer, size_t size, size_t nmemb, void *userp) { buf_t *buf = (buf_t *)userp; size_t total = size * nmemb; if (buf->limit - buf->len < total) { buf = buf_size(buf, buf->limit + total); log_null(buf); } buf_concat(buf, buffer, total); return total; } char * json_fetch(char *url) { CURL *curl = curl_easy_init(); log_null(curl); curl_easy_setopt(curl, CURLOPT_URL, url); buf_t *buf = buf_size(NULL, BUFFER_SIZE); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fetch_data); curl_easy_setopt(curl, CURLOPT_WRITEDATA, buf); curl_easy_setopt(curl, CURLOPT_USERAGENT, "jsmn-example (https://github.com/alisdair/jsmn-example, alisdair@mcdiarmid.org)"); struct curl_slist *hs = curl_slist_append(NULL, "Accept: application/json"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, hs); CURLcode res = curl_easy_perform(curl); if (res != CURLE_OK) log_die("curl_easy_perform failed: %s", curl_easy_strerror(res)); curl_easy_cleanup(curl); curl_slist_free_all(hs); char *js = buf_tostr(buf); free(buf->data); free(buf); return js; } jsmntok_t * json_tokenise(char *js) { jsmn_parser parser; jsmn_init(&parser); unsigned int n = JSON_TOKENS; jsmntok_t *tokens = malloc(sizeof(jsmntok_t)* n); log_null(tokens); int ret = jsmn_parse(&parser, js, tokens, n); while (ret == JSMN_ERROR_NOMEM) { n = n * 2 + 1; tokens = realloc(tokens, sizeof(jsmntok_t)* n); log_null(tokens); ret = jsmn_parse(&parser, js, tokens, n); } if (ret == JSMN_ERROR_INVAL) log_die("jsmn_parse: invalid JSON string"); if (ret == JSMN_ERROR_PART) log_die("jsmn_parse: truncated JSON string"); return tokens; } bool json_token_streq(char *js, jsmntok_t *t, char *s) { return (strncmp(js + t->start, s, t->end - t->start) == 0 && strlen(s) == (size_t)(t->end - t->start)); } char * json_token_tostr(char *js, jsmntok_t *t) { js[t->end] = '\0'; return js + t->start; }
true
5f780233e0631bebbb8044414f469b4c031676f6
C++
uvbs/FullSource
/Source/Source/KG3DEngine/KG3DEngine/Helpers/KGHelperClasses.h
GB18030
7,380
3.0625
3
[ "MIT" ]
permissive
//////////////////////////////////////////////////////////////////////////////// // // FileName : KGHelperClasses.h // Version : 1.0 // Creator : Chen Tianhong // Create Date : 2007-3-20 19:18:47 /* Comment : ࣬ԲκҪκļĶ // ҲṩSceneEditorʹ 1.TTypeCopy ԶĻתԶ̫С Class A; Class B : public A; A a; B b; TTypeCopy<A>(&b, &a); 2.TTypeCmp ͬϣڻBinaryȽ 3.ForAll class AClass { public: HRESULT Render(); } std::map<xx,xx> AMap; KG_CUSTOM_HELPERS::ForAll(AMap, std::mem_func_ref(&AClass::Render)); ForAllҪעǣ΢std::mapfor_eachݲǺܺãҪForAllmapػ汾 4.TContainerDelete TContainerDelete(AMap); //ָУԶdelete 5.TContainerRelease ͬϣRelease涫 */ //////////////////////////////////////////////////////////////////////////////// #ifndef _INCLUDE_KGHELPERCLASSES_H_ #define _INCLUDE_KGHELPERCLASSES_H_ #include <map> #include <vector> #include <set> #include <algorithm> ////////////////////////////////////////////////////////////////////////// namespace KG_CUSTOM_HELPERS { /************************************************************************/ /*ģ岻ܾͷclassƫػֻأʵ class͵ classİ */ /************************************************************************/ template<int num> struct TNumToType { enum{result = num,}; }; /************************************************************************/ /*ָһ */ /************************************************************************/ struct NullType { }; /************************************************************************/ /* ѡһ */ /************************************************************************/ template<bool _Bool, typename T1, typename T2> struct TTypeSelector{typedef T1 Result;}; template<typename T1, typename T2> struct TTypeSelector<false, T1, T2>{typedef T2 Result;}; ////////////////////////////////////////////////////////////////////////// ///Ҫʽָģ template<class _DescStructBase> inline bool TTypeCopy(_DescStructBase* pDesc, const _DescStructBase* pSrc) { _ASSERTE(pDesc && pSrc); return 0 == memcpy_s(pDesc, sizeof(_DescStructBase), pSrc, sizeof(_DescStructBase)); } template<class _DescStructBase> inline bool TTypeCmp(_DescStructBase* pDesc, const _DescStructBase* pSrc) { return 0 == memcmp(pDesc, pSrc, sizeof(_DescStructBase)); } //for_eachǿ template<class _Container,class _Fn1> inline _Fn1 ForAll(_Container& Container, _Fn1 _Func) { return std::for_each(Container.begin(), Container.end(), _Func); } template<class _ContainedType,size_t _Size, class _Fn1> inline _Fn1 ForAll(_ContainedType (&Container)[_Size], _Fn1 _Func) { for (size_t i = 0; i < _Size; ++i) { _Func(Container[i]); } return _Func; } //std::mapfor_eachǿ棬KG_CUSTOM_HELPERS::ForAll(map, std::mem_func(&ClassA::DoSomething)); template<class _Key, class _Type, class _Fn1> inline _Fn1 ForAll(std::map<_Key, _Type>& Container, _Fn1 _Func) { typedef std::map<_Key, _Type> TypeMap; struct PairSeperator { _Fn1& m_Func; PairSeperator(_Fn1& Func):m_Func(Func){} void operator()(TypeMap::value_type& Value) { m_Func(Value.second); } operator _Fn1(){return m_Func;} }; return std::for_each(Container.begin(), Container.end(), PairSeperator(_Func)); }; namespace Private { template<class _Fn1, class _Cmp> class DoIf { _Fn1 m_Func; _Cmp m_CmpFunc; public: DoIf(_Fn1 _Func, _Cmp _CmpFunc):m_Func(_Func),m_CmpFunc(_CmpFunc){} template<class _Type> void operator()(_Type& A) { if(m_CmpFunc(A)) m_Func(A); } template<class _Type> void operator()(const _Type& A) { if(m_CmpFunc(A)) m_Func(A); } operator _Fn1(){return m_Func;} }; }; struct IsNotNull { bool operator()(LPVOID APointer){return APointer != NULL;} }; template<class _Container, class _Fn1, class _Cmp> inline _Fn1 ForAllIf(_Container& Container, _Fn1 _Func, _Cmp _CmpFunc) { return ForAll(Container, Private::DoIf<_Fn1, _Cmp>(_Func, _CmpFunc)); } template<class _Container, class _Fn1> inline _Fn1 ForAllIfNotNull(_Container& Container, _Fn1 _Func) { return ForAllIf(Container, _Func, IsNotNull()); } /************************************************************************/ /*ձ׼ */ /************************************************************************/ struct SafeDelete { template<class _Type> void operator()(_Type*& pType){SAFE_DELETE(pType);} }; struct SafeRelease { template<class _Type> void operator()(_Type*& pType){SAFE_RELEASE(const_cast<_Type*>(pType));} }; template<class _Type> BOOL TContainerDelete(_Type& Container) { ForAll(Container, SafeDelete()); Container.clear(); return TRUE; } template<class _Type, size_t _Size> BOOL TContainerDelete(_Type (&Container)[_Size]) { ForAll(Container, SafeDelete()); return TRUE; } template<class _Type> BOOL TContainerRelease(_Type& Container) { ForAll(Container, SafeRelease()); Container.clear(); return TRUE; } template<class _Type, size_t _Size> BOOL TContainerRelease(_Type (&Container)[_Size]) { ForAll(Container, SafeRelease()); return TRUE; } /* IteratorHolderԭܼ򵥡ʵַԭDzܱ¶ΪӿڣҲͲܱ¶iteratorΪӿڡ COMĽIEnumIEnumҪƵͷţҪƵʵĻԶջǺ¡ ڲʵIEnumResetNextôҪһiteratorӺܺãڹҲܼˡ Ƕױһ һܼ򵥵ĽһBufferΪHandleʵGetFirstGetNextͽӿڡôHandleκζ BufferֱӷiteratorĻôʵ־͸ˡͬʱҲΥOpenCloseԭHandleҪ κζģֻҪGetFirstGetNextܹ */ class IteratorHolder { enum { em_map_iterator_size = sizeof(std::map<int, int>::iterator), em_vector_iterator_size = sizeof(std::vector<int>::iterator), em_list_iterator_size = sizeof(std::list<int>::iterator), em_buffer_size_temp = em_vector_iterator_size > em_map_iterator_size ? em_vector_iterator_size : em_map_iterator_size, em_buffer_size = em_list_iterator_size > em_buffer_size_temp ? em_list_iterator_size : em_buffer_size_temp, }; private: BYTE m_Buffer[em_buffer_size]; }; template<class Type> inline IteratorHolder CreateIteratorHolder(Type& container) { typedef typename Type::iterator iterator; IteratorHolder holder; _ASSERTE(! container.empty()); iterator it = container.begin(); memcpy_s(&holder, sizeof(IteratorHolder), &it, sizeof(iterator)); return holder; } }; namespace KGCH = KG_CUSTOM_HELPERS; #endif //_INCLUDE_KGHELPERCLASSES_H_
true
f0854c8b174d68ebaac61fe919146fcec68db54f
C++
laureviens/histoires-interactives
/Tests/strintervalle.cpp
ISO-8859-1
2,203
3.1875
3
[]
no_license
//------------------------------------------------------------------------------------------------------------------------------------------------------ //0) Inclure les bonnes library et utiliser les raccourcis pour standard #include <iostream> //Pour les entres/sorties #include <string> //Pour utiliser les objets strings #include <cmath> //Pour utiliser la fonction round() et abs() #include <chrono> //Pour avoir un meilleur contrle du temps (en millisecondes) #include <fcntl.h> //Librairie comprenant la magie permettant d'afficher les unicodes dans la console //#define _WIN32_WINNT 0x0500 //Ncessaire pour la taille de la fentre: informe qu'on est sur Windows 2000 ou plus rcent (??? Optionnel?) #include <windows.h> //Ncessaire pour toute modification de la console sur Windows (utilie "Windows API") #include <windef.h> //Ncessaire pour savoir la position du curseur sur Windows #include <winuser.h> //Ncessaire pour savoir la position du curseur sur Windows #include <conio.h> //Ncessaire pour enregistrer les inputs du clavier #include <io.h> //Ncessaire pour changer l'encodage-out pour l'unicode #include <fcntl.h> //Ncessaire pour dcrypter les accents en unicode #include <stdlib.h> //Ncessaire pour jouer avec des nombres alatoires /* srand, rand */ using namespace std; //Pour faciliter l'utilisation de cout, cin, string, etc. (sans spcifier ces fonctions proviennent de quel enviro) //xi Fonction : strintervalle ; retourne un string string strintervalle(string str, int deb, int fin) { string nwstr; for(int pos=deb;pos<=fin;pos++) nwstr+=str[pos]; return(nwstr); } //Main: int main(void){ string objet = "Blaireau|Canard"; int pos = 0; bool found = false; while(!found){ if(objet[pos]=='|') found = true; pos++; } cout << strintervalle(objet,0,pos) << '\n' << strintervalle(objet,0,pos-2); } //La morale de cette histoire: Faut checker comme faut si: //a) On update "pos" APRS avoir commenc la boucle //b) "pos" reprsente bien la dernire lettre du string que l'on veut obtenir
true
070061aaa80213f7ff8fc6c6291b68ad2450c5ee
C++
WhiZTiM/coliru
/Archive2/f4/1b07c1d0912db2/main.cpp
UTF-8
792
2.78125
3
[]
no_license
#include <boost/archive/text_oarchive.hpp> typedef uint32_t WORD; typedef struct _SYSTEMTIME { WORD wYear; WORD wMonth; WORD wDayOfWeek; WORD wDay; WORD wHour; WORD wMinute; WORD wSecond; WORD wMilliseconds; } SYSTEMTIME, *PSYSTEMTIME; namespace boost { namespace serialization { template<typename Archive> void serialize(Archive& ar, SYSTEMTIME& st, const unsigned int version) { ar & st.wYear; ar & st.wMonth; ar & st.wDayOfWeek; ar & st.wDay; ar & st.wHour; ar & st.wMinute; ar & st.wSecond; ar & st.wMilliseconds; } } } int main() { boost::archive::text_oarchive oa(std::cout); SYSTEMTIME d { 1,2,3,4,5,6,7,8 }; oa << d; }
true
34670197d3f42e84b58935f737d5b78bf2489310
C++
timtingwei/prac
/cplus/value_type/prac_2.28.cpp
GB18030
409
2.84375
3
[]
no_license
#include <iostream> int prac_228() { //int i, *const cp; //ָһʼɣֵͲٸı //int i, *const cp = &i //ȷд //int *p1, *const p2; //ָ뱻ʼ //const int ic, &r = ic; //ʼ //const int *const p3; //ʼ const int *p; //pָһ system("pause"); return 0; }
true
04ef09b729cd530bac1ef51df338e9f5d94f1337
C++
Rashi103/practice-cpp
/binary_search_tree/bst_simple.cc
UTF-8
4,233
3.5625
4
[]
no_license
#include "bst_simple.h" namespace jw { BSTNode* GetNewNode(int value) { BSTNode* node = new BSTNode; node->data = value; node->left = nullptr; node->right = nullptr; return node; } BSTNode* Insert(BSTNode* node, int value) { if (node == nullptr) { node = GetNewNode(value); return node; } if (value < node->data) { node->left = Insert(node->left, value); } else if (value > node->data) { node->right = Insert(node->right, value); } return node; } bool Search(BSTNode* node, int value) { if (node == nullptr) { return false; } if (value < node->data) { return Search(node->left, value); } else if (value > node->data) { return Search(node->right, value); } else { return true; } } BSTNode* GetMinNode(BSTNode* node) { if (node == nullptr) { return nullptr; } if (node->left == nullptr) { return node; } return GetMinNode(node->left); } int GetMin(BSTNode* node) { if (node == nullptr) { return -1; } if (node->left == nullptr) { return node->data; } return GetMin(node->left); } int GetMax(BSTNode* node) { if (node == nullptr) { return -1; } if (node->right == nullptr) { return node->data; } return GetMax(node->right); } int GetHeight(BSTNode* node) { if (node == nullptr) { return 0; } return 1 + std::max(GetHeight(node->left), GetHeight(node->right)); } void DeleteTree(BSTNode* node) { if (node == nullptr) { return; } if (node->left != nullptr) DeleteTree(node->left); if (node->right != nullptr) DeleteTree(node->right); delete node; } void PrintBFS(BSTNode* node) { std::queue<BSTNode*> node_queue; BSTNode* current; node_queue.push(node); while (!node_queue.empty()) { current = node_queue.front(); node_queue.pop(); if (current != nullptr) { std::cout << current->data << " "; if (current->left != nullptr) node_queue.push(current->left); if (current->right != nullptr) node_queue.push(current->right); } } } void PrintInOrder(BSTNode* node) { if (node == nullptr) { return; } if (node->left != nullptr) PrintInOrder(node->left); std::cout << node->data << " "; if (node->right != nullptr) PrintInOrder(node->right); } bool IsBinarySearchTree(BSTNode* node) { return IsBetween(node, INT_MIN, INT_MAX); } bool IsBetween(BSTNode* node, int min, int max) { if (node == nullptr) return true; if (node->data > min && node->data < max && IsBetween(node->left, min, node->data) && IsBetween(node->right, node->data, max)) return true; else return false; } BSTNode* DeleteValue(BSTNode* node, int value) { if (node == nullptr) return nullptr; if (value < node->data) node->left = DeleteValue(node->left, value); else if (value > node->data) node->right = DeleteValue(node->right, value); else { // found node to delete if (node->left == nullptr && node->right == nullptr) { delete node; node = nullptr; } else if (node->left == nullptr) { BSTNode* temp = node; node = node->right; delete temp; } else if (node->right == nullptr) { BSTNode* temp = node; node = node->left; delete temp; } else { // 2 children BSTNode* temp = GetMinNode(node->right); node->data = temp->data; node->right = DeleteValue(node->right, temp->data); } } return node; } BSTNode* GetSuccessor(BSTNode* node, int value) { if (node == nullptr) return node; // find value BSTNode* target_node = node; while (target_node->data != value) { if (value < target_node->data) { target_node = target_node->left; } else if (value > target_node->data) { target_node = target_node->right; } } if (target_node->right != nullptr) { return GetMinNode(target_node->right); } else { // find deepest ancestor where value is in left subtree BSTNode* successor = nullptr; BSTNode* ancestor = node; while (ancestor != nullptr) { if (value < ancestor->data) { successor = ancestor; ancestor = ancestor->left; } else { ancestor = ancestor->right; } } return successor; } } } // namespace jw
true
7192fa22c58475bce22cafa4d9bf21384b3de29f
C++
asherpdang/JollyBanker
/Account.h
UTF-8
1,411
3.296875
3
[]
no_license
#pragma once #include "Transaction.h" #include "Fund.h" #include <iostream> #include <string> using namespace std; #ifndef ASS3_ACCOUNT_H #define ASS3_ACCOUNT_H /* * Creates account classes that store 10 funds * handles subtracting/adding/transferring money */ class Account { friend ostream& operator<<(ostream& out, Account& acnt); private: string firstName, lastName; int accountID; Fund arrayFund[10]; public: //Constructors Account(); Account(string firstName, string lastName, int accountID); ~Account(); //Methods void addToAccount(int fundNum, int amnt);//add money to account bool minusFunds(int fundNum, int amnt, Transaction &frontTrans);//subtract money from account void recordTrans(const Transaction &trans, int fundNum);//records transacion in specified fundID history void withdFromSimmilarAcct(int primaryFund, int secondaryFund, int amnt);//Takes money from 1 fund and another fund if not enough funds void printHistory();//prints whole history void printFundHistory(int fundNumber);//prints specified history fund void error(int amnt, string firstN, string lastN, int fundNum);//error //Getters int getAcntID() const;//gets account id int getBal(int fundNum)const;//gets balance of account string getFundName(int fundNum) const;//gets fund name string getFirstName()const;//gets first name string getLastName()const;//gets last name }; #endif //!ASS3_ACCOUNT_H
true
c3d1d2ad9177737bebf8cc0f32fdb47936a46cf5
C++
EsaZul/C-Cplusplus
/Software Implementation I/Go Fish!/card.cpp
UTF-8
3,391
3.546875
4
[]
no_license
//card.cpp #include "card.h" using namespace std; Card::Card(){ // default, ace of spades mySuit = spades; myRank = 1; } Card::Card(int rank, Suit s){ mySuit = s; myRank = rank; /* 1 = A; * 11 = J; * 12 = Q; * 13 = K; */ } string Card::toString()const{ // return string version e.g. Ac 4h Js string returnString= "00"; string returnString1= "F"; switch(mySuit){ case spades: returnString1 = "s"; break; case clubs: returnString1 = "c"; break; case hearts: returnString1 = "h"; break; case diamonds: returnString1 = "d"; break; default: returnString1 = "F"; } switch(myRank){ case 1: returnString = "A"; break; case 2: returnString = "2"; break; case 3: returnString = "3"; break; case 4: returnString = "4"; break; case 5: returnString = "5"; break; case 6: returnString = "6"; break; case 7: returnString = "7"; break; case 8: returnString = "8"; break; case 9: returnString = "9"; break; case 10: returnString = "10"; break; case 11: returnString = "J"; break; case 12: returnString = "Q"; break; case 13: returnString = "K"; break; default: returnString = "00"; } return(returnString + returnString1); } bool Card::sameSuitAs(const Card& c) const{ // true if suit same as c if(mySuit == c.mySuit){ return(true); } else{ return(false); } } int Card::getRank()const{ // return rank, 1..13 return(myRank); } string Card::suitString(Suit s)const{ // return "s", "h",... return("s"); } string Card::rankString(int r)const{ // return "A", "2", ..."Q" string c; if(r == 1){ c = "A"; } if(r == 11){ c = "J"; } if(r == 12){ c = "Q"; } if(r == 13){ c = "K"; } if((r>1)&&(r<11)){ c = r + '0'; } if(r == 10){ c = "10"; } return(c); } bool Card::operator == (const Card& rhs) const{ if(mySuit == rhs.mySuit) if(myRank == rhs.myRank){ return(true); } else{ return(false); } else{ return(false); } } bool Card::operator != (const Card& rhs) const{ if(mySuit == rhs.mySuit){ if(myRank == rhs.myRank){ return(false); } else{ return(true); } } else{ return(true); } } void Card::setSuit(Suit s){ mySuit = s; } void Card::setRank(int r){ myRank = r; } Card::Suit Card::getSuit(){ return(mySuit); } // Card::Card(const Card &c){ mySuit = c.mySuit; myRank = c.myRank; }
true
5862d22ad8d9f24d10c35f607940aa448e45a426
C++
FrozenSky7124/Project_MSVS
/C++/FrozenSky/SkyFileSync v1.0/FileTraveDel.cpp
GB18030
2,522
3.140625
3
[]
no_license
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <io.h> #include <direct.h> using namespace std; /* [Function] srcDir·µļļУdestDir·µļбȶԣɾsrcDir·destDir·ڵļļС curPathԼ¼· [Return Value] 0 : Success! -1: Error in _findfirst() -2: Error in _rmdir() -3: Error in remove() */ int fileTraveDel(const char *srcDir, const char *curPath, const char *destDir) { _finddata_t FileInfo; string srcDir_p = string(srcDir) + string(curPath) + "\\*"; long Handle = _findfirst(srcDir_p.c_str(), &FileInfo); if (Handle == -1) { cout << "Error: Can't Find SrcDir!" << endl; return -1; } do { if (FileInfo.attrib & _A_SUBDIR) //ǰļĿ¼ { if ((strcmp(FileInfo.name, ".") != 0) && (strcmp(FileInfo.name, "..") != 0)) //...Ŀ¼ { string tmpCurPath = string(curPath) + "\\" + string(FileInfo.name); string destDirPath = string(destDir) + tmpCurPath; fileTraveDel(srcDir, tmpCurPath.c_str(), destDir); //Ƚ¼Ŀ¼ݹ if (_access(destDirPath.c_str(), 0) == -1) //ĿĿ¼ { string delDirPath = string(srcDir) + tmpCurPath; cout << "ǷɾĿ¼ " << delDirPath.c_str() << " [Y/N]" << endl; char yorn; cin >> yorn; if (yorn == 'y' || yorn == 'Y') { if (_rmdir(delDirPath.c_str()) == -1) { cout << "ɾĿ¼ " << delDirPath.c_str() << "ʧ" << endl; _findclose(Handle); return -2; } else { cout << "ɾĿ¼ " << delDirPath.c_str() << endl; } } } } } else //ǰļļ { string tmpCurPath = string(curPath) + "\\" + string(FileInfo.name); string destFilePath = string(destDir) + tmpCurPath; if (_access(destFilePath.c_str(), 0) == -1) { string delFilePath = string(srcDir) + tmpCurPath; cout << "Ƿɾļ " << delFilePath.c_str() << " [Y/N]" << endl; char yorn; cin >> yorn; if (yorn == 'y' || yorn == 'Y') { if (remove(delFilePath.c_str()) == -1) { cout << "ɾļ " << delFilePath.c_str() << "ʧ" << endl; _findclose(Handle); return -3; } else { cout << "ɾļ " << delFilePath.c_str() << endl; } } } } } while (_findnext(Handle, &FileInfo) == 0); _findclose(Handle); return 0; }
true
7e3b933f29a226e2ac782635afa71e6f2fb7269e
C++
yaoReadingCode/VS2015project
/AssetManager2/AssetManager2/menuinterface.h
UTF-8
2,224
3.0625
3
[]
no_license
#ifndef MENUITERFACE_H #define MENUITERFACE_H #include <iostream> #include<memory> #include"date.h" #include"asset.h" #include"custodian.h" /** * @brief The MenuInterface class encapsulates all interaction with the asset management system. */ class MenuInterface { public: MenuInterface(std::ostream &display, std::istream &input); /** * @brief displayMainMenu write the main menu to the display device. */ void displayMainMenu() const; /** * @brief getCharacterInput get a single character input from the input device * and clear the buffer till the next newline character. * @return the character input. */ char getCharacterInput() const; /** * @brief processSelection process the selection for the menu. * @param selection the single character selection. * @return true to continue the program, false to quit. */ bool processSelection(char selection); private: std::ostream &_display; /**< the stream to pass all display output to */ std::istream &_input; /**< the stream to read all input from */ /** * @brief addAsset display and process the add asset task. */ void addAsset(); /** * @brief disposeAsset display and process the dispose asset task. */ void disposeAsset(); /** * @brief updateAsset display and process the update asset custodian or location task. */ void updateAsset(); /** * @brief addMaintenance display and process the add asset maintenance record task. */ void addMaintenance(); /** * @brief listAssetsByType display and process the list assets by type task. */ void listAssetsByType(); /** * @brief listAssetsByCustodian display and process the list assets by custodian task. */ void listAssetsByCustodian(); /** * @brief findAsset display and process the find asset task. */ void findAsset(); Date inputDate(); Custodian inputCustodian(); std::shared_ptr<Asset> retrieveAsset(); std::shared_ptr<Asset> retrieveAssetBySerial(); void custodianDetails(std::shared_ptr<Asset> asset); void maintenanceDetail(std::shared_ptr<Asset> asset); std::shared_ptr<Asset> findMenu(); void displayAsset(std::shared_ptr<Asset> asset); }; #endif // MENUITERFACE_H
true
1b8583e2c9f8331a20f4ee55cf45968b4b643d58
C++
redfern314/poe-lab1
/poe_lab1/poe_lab1.ino
UTF-8
3,419
3.046875
3
[]
no_license
/*Setup functions for a semi-sphere room sweep which detects the ambient light of its suroundings using a photoresistor. This interfaces with a Python 2 GUI and code which produces a graph in Python. Derek Redfern & Halie Murray-Davis */ //Get libraries: #include<Servo.h>; #include <stream.h>; //Define global variables, set initial positions for motors to zero: double theta = 0; //sets initial position so we can control servo's position range=[1,180]. double phi = 0; Servo servo1; //servos are servos Servo servo2; int pos; //positions for motors int pos2; int led = 13; boolean runScan = false; String data; double photoresistor=A0; //analog in chanel for photo resistor int i=0; //counter for data acquision from photo resistor. String inputString=""; boolean stringComplete = false; //stuff from serial port: char start; int precision=10; int angle=30; void setup() { Serial.begin(9600); //start serial port so we can write data to it. servo1.attach(3); //digital PWM pins for signal to the two servos servo2.attach(5); pinMode(photoresistor, INPUT); //set photoresisstor up as an input pinMode(led, OUTPUT); while (Serial.available() <= 0) { //wait for a response Serial.println("Arduino Ready"); // send a starting message delay(300); } } void movement(){ //define a function which will move the servos in a specified pattern. for(pos==0; pos<=180; pos = pos + 1) { //Step through an arch for the bottom servo. servo1.write(pos); delay (5); returndata(); if ((pos==0 || pos==180)){ //move the photo resistor up a step (size of which is determined by the percision value) at ends of arc. delay (70); pos2=pos2+precision; servo2.write(pos2); delay (10); returndata(); } } for (pos==180; pos>0; pos = pos - 1) { //this case accomplishes movement in the opposite direction servo1.write(pos); delay (5); returndata(); if (pos==0) { pos2=pos2+precision; servo2.write(pos2); delay (10); returndata(); } } if(pos2>=180) { pos=0; pos2=0; servo1.write(pos); servo2.write(pos2); Serial.print("@"); runScan=false; } } void returndata(){ //sets up a function which writes data to the serial port so we can use it in the python code to make a graph. int light=map(analogRead(photoresistor), 500, 1023, 0, 100); //reads the light from the photoresistor. Serial.print(pos); Serial.print("|"); Serial.print(pos2); Serial.print("|"); Serial.print(light); Serial.print("\n"); } void loop(){ if (stringComplete) { stringComplete=false; if(inputString[0]=='0') { runScan=false; } else if(inputString[0]=='1') { String str1 = String(inputString); precision = str1.substring(1,3).toInt(); runScan=true; pos=0; pos2=0; } inputString=""; } if (runScan) { movement(); //calls previously defined movement function. } } void serialEvent() { while (Serial.available()) { // get the new byte: char inChar = (char)Serial.read(); // add it to the inputString: inputString += inChar; // if the incoming character is a newline, set a flag // so the main loop can do something about it: if (inChar == '\n') { stringComplete = true; } } }
true
85d5543a5d4d03eb57a8d51a280de9ee9e83120f
C++
colsramble/Aircon2015-Firmware
/firmware/firmware.ino
UTF-8
2,479
2.578125
3
[]
no_license
#include <SPI.h> #include <Ethernet.h> #include "globals.h" #include "rpcserver.h" #include "hardware.h" #include "interrupt.h" // Enter a MAC address and IP address for your controller below. // The IP address will be dependent on your local network: byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; IPAddress ip(192,168,1,177); //IPAddress ip(169,254,1,1); // Initialize the Ethernet server library // with the IP address and port you want to use // (port 80 is default for HTTP): EthernetServer server(80); void setup() { memset(rxLine,0,sizeof(rxLine)); rxLinePos = 0; hardwareInit(); // start the Ethernet connection and the server: Ethernet.begin(mac,ip); server.begin(); // Setup interrupts interruptInit(); } ISR(TIMER1_COMPA_vect) { // Every REFRESH_SECONDS seconds we'll refresh the local cache interruptHandleTimer(); } void loop() { // listen for incoming clients EthernetClient client = server.available(); if (client) { boolean currentLineIsBlank = true; while (client.connected()) { if (client.available()) { char c = client.read(); // Buffer lines as they arrive if (rxLinePos < sizeof(rxLine) - 2) { rxLine[rxLinePos++] = c; } if (c == '\n') { // you're starting a new line currentLineIsBlank = true; parseBuffer(); } else if (c != '\r') { // you've gotten a character on the current line currentLineIsBlank = false; } // if you've gotten to the end of the line (received a newline // character) and the line is blank, the http request has ended, // so you can send a reply if (c == '\n' && currentLineIsBlank) { busy = 1; switch(cmd) { case CMD_STATUS: hdlStatus(client); break; case CMD_OPEN: hdlOpen(client); break; case CMD_CLOSE: hdlClose(client); break; case CMD_RESET: hdlReset(client); break; default: sendResponse(client, STATUS_NOT_FOUND); break; } cmd = CMD_NONE; busy = 0; break; } } } // give the web browser time to receive the data - ToDo: is this necessary? delay(1); // close the connection: client.stop(); } }
true
b2eddc4ecd2c9b42afec12a914ae919881e54436
C++
PatrDen/compress
/src/huffman.cpp
UTF-8
6,365
2.59375
3
[]
no_license
#include <iostream> #include "huffman.hpp" void print( const huffman::tree_node::ptr node, int s = 0 ) { for ( int i = 0; i < s; ++i ) cerr << " "; cerr << "'"; for ( int i = 0; i < BUF_LEN; ++ i ) if ( node->chars[i] ) cerr << (char) i; cerr << "' " << node->frequency << endl; if ( node->left != NULL ) { for ( int i = 0; i < s; ++i ) cerr << " "; cerr << " left:" << endl; print( node->left, s + 4 ); } if ( node->right != NULL ) { for ( int i = 0; i < s; ++i ) cerr << " "; cerr << " right:" << endl; print( node->right, s + 4 ); } cerr << endl; } void huffman::build_tree( huffman::nodes &nodes ) { int n = nodes.size(); while ( n-- > 1 ) { nodes::iterator i1 = nodes.end(); nodes::iterator i2 = nodes.end(); for ( nodes::iterator i = nodes.begin(); i != nodes.end(); ++i ) { if ( i1 == nodes.end() || (*i)->frequency <= (*i1)->frequency ) { i2 = i1; i1 = i; } else if ( i2 == nodes.end() || (*i)->frequency <= (*i2)->frequency ) i2 = i; } tree_node::ptr n1 = *i1; nodes.erase( i1 ); tree_node::ptr n2 = *i2; nodes.erase( i2 ); nodes.push_back( tree_node::ptr( new tree_node( n2, n1 ) ) ); } m_root = nodes.back(); // print( m_root ); } bool huffman::cread_block() { if ( m_input.eof() ) return false; nodes frequency( BUF_LEN ); bool br = false; while ( !m_input.eof() && !br ) { char chars[BUF_LEN]; size_t i = 0; size_t n = read( chars, BUF_LEN ); while ( i < n && !br ) { unsigned char ch = (unsigned char) chars[i++]; if ( frequency[ch] == NULL ) frequency[ch] = tree_node::ptr( new tree_node( ch ) ); else if ( frequency[ch]->frequency == MAX_FREQ - 1 ) br = true; else ++frequency[ch]->frequency; } } nodes::iterator fit = frequency.begin(); while ( fit != frequency.end() ) { if ( *fit == NULL ) fit = frequency.erase( fit ); else ++fit; } if ( frequency.empty() ) return false; build_tree( frequency ); return true; } void huffman::cwrite_block() { *m_output << *m_root << '\0' << '\0' << '\0'; vector<bitset> codes( BUF_LEN ); while ( !m_input.eof() && !m_root->empty() ) { char chars[BUF_LEN]; size_t i = 0; size_t n = read( chars, min( (size_t) m_root->frequency, (size_t) BUF_LEN ) ); while ( i < n ) { unsigned char ch = (unsigned char) chars[i++]; if ( codes[ch].empty() ) codes[ch] = m_root->encode( ch ); else --m_root->frequency; bitset tmp = codes[ch]; int buf_size = m_bits_buf.size(); for ( int j = 0; j < buf_size; ++j ) tmp.push_back( m_bits_buf[j] ); m_bits_buf = tmp; dump2output(); } } } bool huffman::dread_block() { char ch; return read( &ch, 1 ) > 0; } void huffman::dwrite_block() { #define CHARS_COUNT 3 size_t n; char entry[CHARS_COUNT]; nodes nodes; do { n = read( entry, CHARS_COUNT ); if ( n < CHARS_COUNT && n > 0 ) { cerr << "Unexpected EOF: " << entry[0] << endl; exit( 1 ); } if ( entry[0] == 0 && entry[1] == 0 && entry[2] == 0 ) break; nodes.push_back( tree_node::ptr( new tree_node( (unsigned char) entry[0], (((unsigned char) entry[1]) << 8) | (unsigned char) entry[2] ) ) ); } while ( !m_input.eof() ); if ( nodes.empty() ) { return; cerr << "Bad frequency table" << endl; exit( 1 ); } build_tree( nodes ); if ( m_root->empty() ) return; char chars[BUF_LEN]; bitset bits; size_t need = m_root->encoded_size() / 8 + ( m_root->encoded_size() % 8 ? 1 : 0 ); while ( !m_input.eof() && need > 0 ) { n = read( chars, min( need, (size_t) BUF_LEN ) ); need -= n; bitset tmp; while ( n-- > 0 ) tmp.append( chars[n] ); size_t bits_size = bits.size(); for ( size_t i = 0; i < bits_size; ++i ) tmp.push_back( bits[i] ); bits = tmp; size_t i = bits.size(); while ( !m_root->empty() ) { char tmp; if ( m_root->decode( bits, i, tmp ) ) { *m_output << tmp; continue; } bits.resize( i ); break; } } } huffman::tree_node::tree_node( unsigned char ch, unsigned fr ) { this->_init(); chars[ch] = true; frequency = fr; } huffman::tree_node::tree_node( const huffman::tree_node::ptr left, const huffman::tree_node::ptr right ) { this->_init(); for ( int i = 0; i < BUF_LEN; ++i ) this->chars[i] = left->chars[i] || right->chars[i]; this->frequency = left->frequency + right->frequency; this->left = left; this->right = right; } bool huffman::tree_node::compare( huffman::tree_node::ptr a, huffman::tree_node::ptr b ) { return a->frequency > b->frequency; } void huffman::tree_node::_init() { for ( int i = 0; i < BUF_LEN; ++i ) this->chars[i] = false; frequency = 0; m_encoded_size = 0; } size_t huffman::tree_node::encoded_size() { if ( !empty() && m_encoded_size == 0 ) m_encoded_size = _calculate_encoded_size(); return m_encoded_size; } size_t huffman::tree_node::_calculate_encoded_size( size_t depth ) { if ( left != NULL ) return left->_calculate_encoded_size( depth + 1 ) + right->_calculate_encoded_size( depth + 1 ); return depth * (size_t) frequency; } unsigned short huffman::tree_node::_char_frequency( unsigned char ch ) const { if ( left == NULL ) return frequency; if ( left->chars[ch] ) return left->_char_frequency( ch ); return right->_char_frequency( ch ); } bitset huffman::tree_node::encode( unsigned char ch ) { bitset tmp; --frequency; if ( left != NULL && left->chars[ch] ) { tmp = left->encode( ch ); tmp.push_back( false ); } else if ( right != NULL ) { tmp = right->encode( ch ); tmp.push_back( true ); } return tmp; } bool huffman::tree_node::decode( bitset &bits, size_t &idx, char &out ) { if ( idx == 0 && left != NULL && right != NULL ) return false; --frequency; tree_node::ptr node; if ( left != NULL && !bits[idx - 1] ) node = left; if ( right != NULL && bits[idx - 1] ) node = right; if ( node != NULL ) { if ( !node->decode( bits, --idx, out ) ) { ++idx; ++frequency; return false; } else return true; } for ( int i = 0; i < BUF_LEN; ++i ) if ( chars[i] ) { out = (char) i; return true; } cerr << "Not found code in Huffman-tree" << endl; exit( 1 ); } ostream& operator<<( ostream &stream, const huffman::tree_node &node ) { for ( short i = 0; i < BUF_LEN; ++i ) { if ( !node.chars[i] ) continue; unsigned short f = node._char_frequency( (unsigned char) i ); stream << (char) i << (char) (f >> 8) << (char) (f & 255); } return stream; }
true
ac0a734ad9096017048f4bdd39edbe8c3bd42949
C++
Yousifba/-Introduction-To-3D-Animations---Final-Project
/igl/opengl/Movable.cpp
UTF-8
1,432
3.140625
3
[ "Apache-2.0" ]
permissive
#include "Movable.h" #include <iostream> Movable::Movable() { T = Eigen::Transform<float, 3, Eigen::Affine>::Identity(); } Eigen::Matrix4f Movable::MakeTrans() { return T.matrix(); } Eigen::Transform<float, 3, Eigen::Affine>& Movable::getTrans() { return T; } void Movable::Move(Eigen::Vector4f new_coords) { Eigen::Matrix4f prev_transformation = T.matrix(); T.matrix().col(3) = new_coords; } void Movable::MyTranslate(Eigen::Vector3f amt, int axis) { switch (axis) { //T = Translation x Rotation x Scale case CAMERA_AXIS: { Eigen::Matrix4f prev_transformation = T.matrix(); float tmp[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, amt.x(), amt.y(), amt.z(), 0 }; Eigen::Matrix4f translation_matrix = Eigen::Map<Eigen::Matrix4f>(tmp); T = translation_matrix + prev_transformation; break; } case OBJECT_AXIS: T.translate(amt); break; } } //angle in radians void Movable::MyRotate(Eigen::Vector3f rotAxis, float angle) { T.rotate(Eigen::AngleAxisf(angle, rotAxis)); } void Movable::RotateAround(Eigen::Vector3f point, Eigen::Vector3f rotAxis, float angle) { /*Eigen::Vector3f delta = Eigen::Vector3f(point.x() - T.matrix().col(3).x(), point.y() - T.matrix().col(3).y(), point.z() - T.matrix().col(3).z());*/ T.translate(point); T.rotate(Eigen::AngleAxisf(angle, rotAxis)); T.translate(Eigen::Vector3f(-point)); } void Movable::MyScale(Eigen::Vector3f amt) { T.scale(amt); }
true
d5464b59f39ad9835165170e02ab3de8fc6f7ade
C++
lenmahaffey/ADT_Matrix
/ADT_Matrix/src/Matrix.h
UTF-8
11,083
3.34375
3
[]
no_license
#ifndef MATRIX_H #define MATRIX_H #include <string> #include <iostream> #include "Cell.h" namespace ADT { template <class T> class Matrix { public: Matrix<T>(); Matrix<T>(int columns, int rows, T defaultValue); Matrix<T>(const Matrix<T>& other); void Display(); int GetColumnCount() const; int GetRowCount() const; Cell<T> GetCell(const std::string& cell) const; Cell<T> GetCell(const int& column, const int& row) const; T GetCellContents(const std::string& cell) const; T GetCellContents(const int& column, const int& row) const; void SetCell(const std::string& cell, const Cell<T>& T); void SetCell(const int& col, const int& row, const Cell<T>& T); void SetCellIsEmpty(const std::string& cell, const bool& b); void SetCellIsEmpty(const int& col, const int& row, const bool& b); void SetCellContents(const std::string& cell, const T& contents); void SetCellContents(const int& col, const int& row, const T& contents); static CellAddress GetCellAddressFromAddressString(const std::string& a); ~Matrix(); Matrix<T> operator=(const Matrix<T>& other); Matrix<T> operator=(const Cell<T>& other); bool operator==(const Matrix<T>& other); bool operator!=(const Matrix<T>& other); private: int rowCount; int columnCount; Cell<T>** matrix; void deleteMatrix(); }; template <class T> Matrix<T>::Matrix() : columnCount(0), rowCount(0) { matrix = new Cell<T>*[columnCount]; for (int column = 0; column <= rowCount - 1; column++) { matrix[column] = new Cell<T>[rowCount]; for (int row = 0; row <= columnCount - 1; row++) { Cell<T> current; CellAddress currentAddress{ column, row }; current.SetContents(T{}); current.SetAddress(currentAddress); matrix[column][row] = current; } } } template <class T> Matrix<T>::Matrix(int columns, int rows, T defaultValue) : columnCount(columns), rowCount(rows) { if (columns <= 0 || columns > 700) { throw std::ColumnOutOfBounds("Class: Matrix<T> is limited to 700 columns"); } if (rows <= 0 || rows > 700) { throw std::RowOutOfBounds("Class: Matrix<T> is limited to 700 rows"); } matrix = new Cell<T>*[columns]; for (int c = 0; c < columns; c++) { matrix[c] = new Cell<T>[rows]; for (int r = 0; r < rows; r++) { CellAddress currentAddress(c, r); Cell<T> current{ c, r, defaultValue }; matrix[c][r] = current; } } } template <class T> Matrix<T>::Matrix(const Matrix<T>& other) { if (*this != other) { columnCount = other.GetColumnCount(); rowCount = other.GetRowCount(); matrix = new Cell<T>*[columnCount]; for (int c = 0; c < columnCount; c++) { matrix[c] = new Cell<T>[rowCount]; for (int r = 0; r < rowCount; r++) { matrix[c][r] = other.GetCell(c,r); } } } } template <class T> void Matrix<T>::Display() { int columns{ columnCount }; columns += 1; columns *= 6; std::cout << std::string(columns, '-') << std::endl; std::cout << " "; for (int i = 0; i < columnCount; i++) { std::cout << " | " << (char)(i + 65); } std::cout << " |" << std::endl; std::cout << std::string(columns, '-') << std::endl; for (int r = 0; r < rowCount; r++) { std::cout << " " << r + 1 << " |"; for (int c = 0; c < columnCount; c++) { std::cout << " " << GetCell(c, r) << " |"; } std::cout << std::endl; std::cout << std::string(columns, '-') << std::endl; } } template <class T> int Matrix<T>::GetColumnCount() const { return columnCount; } template <class T> int Matrix<T>::GetRowCount() const { return rowCount; } template <class T> Cell<T> Matrix<T>::GetCell(const int& c, const int& r) const { if (c < 0 || c > columnCount) { throw std::ColumnOutOfBounds("Column Error: The max row is " + std::to_string(columnCount)); } if (r < 0 || r > rowCount) { throw std::RowOutOfBounds("Row Error: The max column is " + std::to_string(rowCount)); } Cell<T> returnCell{ matrix[c][r] }; return returnCell; } template <class T> Cell<T> Matrix<T>::GetCell(const std::string& cellAddress) const { CellAddress test{ cellAddress }; if (test.GetColumn() < 0 || (test.GetColumn() + 1) > columnCount) { throw std::ColumnOutOfBounds("Column Error: The max column is " + std::to_string(columnCount)); } if (test.GetRow() < 0 || (test.GetRow() + 1) > rowCount) { throw std::RowOutOfBounds("Row Error: The max row is " + std::to_string(rowCount)); } int testC = test.GetColumn(); int testR = test.GetRow(); Cell<T> returnCell{ matrix[test.GetColumn()][test.GetRow()] }; return returnCell; } template <class T> T Matrix<T>::GetCellContents(const std::string& cellAddress) const { CellAddress test{ cellAddress }; if (test.GetColumn() < 0 || test.GetColumn() > columnCount) { throw std::ColumnOutOfBounds("Column Error: The max column is " + std::to_string(columnCount)); } if (test.GetRow() < 0 || test.GetRow() > rowCount) { throw std::RowOutOfBounds("Row Error: The max row is " + std::to_string(rowCount)); } Cell<T> c = matrix[test.GetColumn()][test.GetRow()]; T contents = c.GetContents(); return contents; } template <class T> T Matrix<T>::GetCellContents(const int& c, const int& r) const { if (c < 0 || c > columnCount) { throw std::ColumnOutOfBounds("Column Error: The max column is " + std::to_string(columnCount)); } if (r < 0 || r > rowCount) { throw std::RowOutOfBounds("Row Error: The max row is " + std::to_string(rowCount)); } Cell<T> c = matrix[c][r]; T contents = c.GetContents(); return contents; } template <class T> void Matrix<T>::SetCell(const std::string& cellAddress, const Cell<T>& newCell) { try { CellAddress test{ cellAddress }; if (test.GetColumn() < 0 || test.GetColumn() > columnCount) { throw std::ColumnOutOfBounds("Column Error: The max column is " + std::to_string(columnCount)); } if (test.GetRow() < 0 || test.GetRow() > rowCount) { throw std::RowOutOfBounds("Row Error: The max row is " + std::to_string(rowCount)); } matrix[test.GetColumn()][test.GetRow()] = newCell; } catch (std::exception e) { throw; } } template <class T> void Matrix<T>::SetCell(const int& c, const int& r, const Cell<T>& newCell) { if (c < 0 || c > columnCount) { throw std::ColumnOutOfBounds("Column Error: The max column is " + std::to_string(columnCount)); } if (r < 0 || r > rowCount) { throw std::RowOutOfBounds("Row Error: The max row is " + std::to_string(rowCount)); } Cell<T> currentCell{ matrix[c][r] }; matrix[c][r] = newCell; } template <class T> void Matrix<T>::SetCellIsEmpty(const std::string& cellAddress, const bool& b) { CellAddress test{ cellAddress }; if (test.GetColumn() < 0 || test.GetColumn() > columnCount) { throw std::ColumnOutOfBounds("Column Error: The max column is " + std::to_string(columnCount)); } if (test.GetRow() < 0 || test.GetRow() > rowCount) { throw std::RowOutOfBounds("Row Error: The max row is " + std::to_string(rowCount)); } ADT::Cell<T>* current = matrix[test.GetColumn()][test.GetRow()]; current->SetEmpty(b); } template <class T> void Matrix<T>::SetCellIsEmpty(const int& c, const int& r, const bool& b) { if (c < 0 || c > columnCount) { throw std::ColumnOutOfBounds("Column Error: The max column is " + std::to_string(columnCount)); } if (r < 0 || r > rowCount) { throw std::RowOutOfBounds("Row Error: The max row is " + std::to_string(rowCount)); } ADT::Cell<T>* current = &(matrix[c][r]); current->SetEmpty(b); } template <class T> void Matrix<T>::SetCellContents(const std::string& cellAddress, const T& newContents) { CellAddress test{ cellAddress }; if (test.GetColumn() < 0 || test.GetColumn() > columnCount) { throw std::ColumnOutOfBounds("Column Error: The max column is " + std::to_string(columnCount)); } if (test.GetRow() < 0 || test.GetRow() > rowCount) { throw std::RowOutOfBounds("Row Error: The max row is " + std::to_string(rowCount)); } Cell<T>* current = &(matrix[test.GetColumn()][test.GetRow()]); current->SetContents(newContents); } template <class T> void Matrix<T>::SetCellContents(const int& c, const int& r, const T& newContents) { if (c < 0 || c > columnCount) { throw std::ColumnOutOfBounds("Column Error: The max column is " + std::to_string(columnCount)); } if (r < 0 || r > rowCount) { throw std::RowOutOfBounds("Row Error: The max row is " + std::to_string(rowCount)); } Cell<T>* current = &matrix[c][r]; current->SetContents(newContents); } template <class T> CellAddress Matrix<T>::GetCellAddressFromAddressString(const std::string& a) { std::string c{}; std::string r{}; for (int i = 0; i < (int)a.length(); i++) { if (a[i] >= 'A' && a[i] <= 'Z') { c.push_back(a[i]); } else if (a[i] >= '0' && a[i] <= '9') { r.push_back(a[i]); } else { throw std::BadAddressString(); } } int column = CellAddress::CalculateIntForAddressString(c); int row = stoi(r) - 1; CellAddress temp(column, row); return temp; } template <class T> Matrix<T> Matrix<T>::operator=(const Matrix<T>& other) { if (*this != other) { deleteMatrix(); this->rowCount = other.GetRowCount(); this->columnCount = other.GetColumnCount(); matrix = new Cell<T>*[columnCount]; for (int c = 0; c < columnCount; c++) { matrix[c] = new Cell<T>[rowCount]; for (int r = 0; r < rowCount; r++) { matrix[c][r] = other.GetCell(c,r); } } } return *this; } template <class T> Matrix<T> Matrix<T>::operator=(const Cell<T>& other) { } template <class T> bool Matrix<T>::operator==(const Matrix<T>& other) { if (rowCount != other.rowCount || columnCount != other.columnCount) { return false; } for (int r = 0; r < rowCount; r++) { for (int c = 0; c < columnCount; c++) { try { Cell<T> thisCell{ matrix[c][r] }; Cell<T> otherCell{ other.matrix[c][r] }; if (thisCell.GetContents() != otherCell.GetContents()) { return false; } } catch (const std::exception& e) { throw; } } } return true; } template <class T> bool Matrix<T>::operator!=(const Matrix<T>& other) { if (rowCount != other.rowCount || columnCount != other.columnCount) { return true; } for (int c = 0; c < columnCount; c++) { for (int r = 0; r < rowCount; r++) { try { Cell<T> temp1{ matrix[c][r] }; Cell<T> temp2{ other.matrix[c][r] }; if (temp1.GetContents() != temp2.GetContents()) { return true; } } catch (const std::exception& e) { throw; } } } return false; } template <class T> void Matrix<T>::deleteMatrix() { for (int row = columnCount - 1; row >= 0; row--) { delete[] matrix[row]; } delete[] matrix; columnCount = 0; rowCount = 0; } template <class T> Matrix<T>::~Matrix() { if (rowCount > 0) { deleteMatrix(); } } } #endif //MATRIX_H
true
8df1fe547ae670b23dd097357bca877e867b0847
C++
sanjusss/leetcode-cpp
/0/400/470/472_20211228.cpp
UTF-8
2,184
3.078125
3
[]
no_license
/* * @Author: sanjusss * @Date: 2021-12-28 20:47:58 * @LastEditors: sanjusss * @LastEditTime: 2021-12-28 21:14:11 * @FilePath: \0\400\470\472_20211228.cpp */ #include "leetcode.h" class Solution { struct Node { bool end = false; Node* children[26] = { nullptr }; ~Node() { for (auto node : children) { delete node; } } }; struct Trie { void insert(const string& s) { Node* node = &root; for (char c : s) { int i = c - 'a'; if (node->children[i] == nullptr) { node->children[i] = new Node(); } node = node->children[i]; } node->end = true; } bool find(const string& s) { if (s.empty()) { return false; } vector<bool> used(s.size()); return find(s, 0, &root, used); } bool find(const string& s, int i, Node* node, vector<bool>& used) { if (i == s.size()) { return true; } while (i < s.size()) { int j = s[i] - 'a'; if (node->children[j] == nullptr) { return false; } node = node->children[j]; if (node->end && !used[i]) { used[i] = true; if (find(s, i + 1, &root, used)) { return true; } } ++i; } return node->end; } Node root; }; public: vector<string> findAllConcatenatedWordsInADict(vector<string>& words) { sort(words.begin(), words.end(), [](const string& a, const string& b) { return a.size() < b.size(); }); Trie tree; vector<string> ans; for (auto& s : words) { if (tree.find(s)) { ans.push_back(s); } tree.insert(s); } return ans; } }; TEST_EQUIVALENT(&Solution::findAllConcatenatedWordsInADict)
true
68aa668997a6cbe0b094f96a83525273f0788eb5
C++
Czar4ik/Repoz4
/ЛР_5/ConsoleApplication1/Button.h
UTF-8
495
2.75
3
[]
no_license
#pragma once #include "Element upravlenia.h" #include "iostream" using namespace std; class Button : public Element { public: Button() {} Button(char* name, int plosh) :Element(name) { this->plosh = plosh; }; char * getName() { return name; }; int getPlosh() { //cout << this->cost; return plosh; }; void Show() { cout << this->name; }; void Button::vlozh() { cout << "Button level: "; cout << this->num << endl; } protected: int num = 3; int plosh; };
true
f33b42dfe8df1c1593eb805bc6f4f69f75c7c86c
C++
Greencats0/university
/2/Fall/CPSC-131/Final Revew/Recursion/print_linked_list.cpp
UTF-8
392
3.15625
3
[]
no_license
#include <iostream> struct n { int data = 10; n* next = nullptr; // n* right = nullptr; }; void print(n* node){ while(node != nullptr){ std::cout << node->data << std::endl; node = node->next; } } void test(){ n* n1 = new n; n* n2 = new n; n1->next = n2; print(n1); delete n1; delete n2; n1 = nullptr; n2 = nullptr; } int main(){ test(); return 0; }
true
54d7edd8e301e613394538501deb87a9c7e571bb
C++
dhornyak/LEGO-Racers
/01_Middle/01_Middle/GeometryFactory.cpp
ISO-8859-2
17,705
2.875
3
[]
no_license
#include "GeometryFactory.h" #include "TrackSection.h" #include <vector> // Static cube parameters. const int GeometryFactory::N = 32; const float GeometryFactory::knobHeight = 1.8f; const float GeometryFactory::knobRadius = 2.4f; const float GeometryFactory::cubeWidthUnit = 8.0f; const float GeometryFactory::cubeWidthOffset = 0.1f; const float GeometryFactory::thinCubeHeightUnit = 3.2f; const float GeometryFactory::cubeTopWallThickness = 1.0f; const float GeometryFactory::cubeSideWallThickness = 1.2f; std::shared_ptr<Mesh> GeometryFactory::GetCuboid(glm::vec3 topLeftCorner, glm::vec3 bottomRightCorner) { auto cuboid = std::make_shared<Mesh>(); // calculate corner positions glm::vec3 a = topLeftCorner; glm::vec3 b = a; b.x = bottomRightCorner.x; glm::vec3 c = a; c.z = bottomRightCorner.z; glm::vec3 d = a; d.x = bottomRightCorner.x; d.z = bottomRightCorner.z; glm::vec3 h = bottomRightCorner; glm::vec3 e = h; e.x = topLeftCorner.x; e.z = topLeftCorner.z; glm::vec3 f = h; f.z = topLeftCorner.z; glm::vec3 g = h; g.x = topLeftCorner.x; // add sides glm::vec2 tex(0.0f, 0.0f); cuboid->addQuad(a, c, d, b, glm::vec3(0.0f, 1.0f, 0.0f), tex); // top cuboid->addQuad(c, g, h, d, glm::vec3(0.0f, 0.0f, 1.0f), tex); // front cuboid->addQuad(d, h, f, b, glm::vec3(1.0f, 0.0f, 0.0f), tex); // right cuboid->addQuad(b, f, e, a, glm::vec3(0.0f, 0.0f, -1.0f), tex); // back cuboid->addQuad(a, e, g, c, glm::vec3(-1.0f, 0.0f, 0.0f), tex); // left cuboid->addQuad(g, e, f, h, glm::vec3(0.0f, -1.0f, 0.0f), tex); // bottom return cuboid; } std::shared_ptr<Mesh> GeometryFactory::GetCircle(glm::vec3 center, glm::vec3 normal, float radius) { auto circle = std::make_shared<Mesh>(); for (int i = 0; i <= N; ++i) { float angle = (2 * M_PI / N) * i; glm::vec2 tex(0.25f * cos(angle + M_PI / 2.0f) + 0.5f, 0.25f * sin(angle + M_PI / 2.0f) + 0.5f); if (normal.x == 1.0f) { circle->addVertex({ glm::vec3(0.0f, radius * sin(angle), radius * cos(angle)) + center, normal, tex }); } else if (normal.x == -1.0f) { circle->addVertex({ glm::vec3(0.0f, radius * cos(angle), radius * sin(angle)) + center, normal, tex }); } else if (normal.y == 1.0f) { circle->addVertex({ glm::vec3(radius * cos(angle), 0.0f, radius * sin(angle)) + center, normal, tex }); } else if (normal.y == -1.0f) { circle->addVertex({ glm::vec3(radius * sin(angle), 0.0f, radius * cos(angle)) + center, normal, tex }); } else if (normal.z == 1.0f) { circle->addVertex({ glm::vec3(radius * sin(angle), radius * cos(angle), 0.0f) + center, normal, tex }); } else if (normal.z == -1.0f) { circle->addVertex({ glm::vec3(radius * cos(angle), radius * sin(angle), 0.0f) + center, normal, tex }); } } circle->addVertex({ center, normal, glm::vec2(0.5f, 0.5f) }); for (int i = 0; i < N; ++i) { circle->addTriangleIndices(N + 1, i + 1, i); } return circle; } std::shared_ptr<Mesh> GeometryFactory::GetCylinder(glm::vec3 bottomCenterPosition, glm::vec3 direction, float radius, float height, bool reverse) { auto cylinder = std::make_shared<Mesh>(); std::vector<glm::vec3> topCorners, bottomCorners; for (int i = 0; i <= N; ++i) { float angle = (2 * M_PI / N) * i; if (direction.x == 1.0f) { topCorners.push_back(glm::vec3(height, radius * sin(angle), radius * cos(angle)) + bottomCenterPosition); bottomCorners.push_back(glm::vec3(0.0f, radius * sin(angle), radius * cos(angle)) + bottomCenterPosition); } else if (direction.y == 1.0f) { topCorners.push_back(glm::vec3(radius * cos(angle), height, radius * sin(angle)) + bottomCenterPosition); bottomCorners.push_back(glm::vec3(radius * cos(angle), 0.0f, radius * sin(angle)) + bottomCenterPosition); } else if (direction.z == 1.0f) { topCorners.push_back(glm::vec3(radius * sin(angle), radius * cos(angle), height) + bottomCenterPosition); bottomCorners.push_back(glm::vec3(radius * sin(angle), radius * cos(angle), 0.0f) + bottomCenterPosition); } } for (int i = 0; i < N; ++i) { float middleAngle = (2 * M_PI / N) * (2 * i + 1) / 2.0f; glm::vec3 normal(cos(middleAngle), 0.0f, sin(middleAngle)); int currentIndex = i + 1, nextIndex = i; if (reverse) { currentIndex = i; nextIndex = i + 1; } cylinder->addQuad(topCorners[currentIndex], bottomCorners[currentIndex], bottomCorners[nextIndex], topCorners[nextIndex], normal, glm::vec2(0.0f, 0.0f)); } return cylinder; } glm::vec3 GeometryFactory::CalculateSphereCoordinate(float x, float y, float radius) { float u = 2 * M_PI * x; float v = M_PI * y; glm::vec3 vertex(radius * cos(u)*sin(v), radius * cos(v), radius * sin(u)*sin(v)); return vertex; } std::shared_ptr<Mesh> GeometryFactory::GetSphere(glm::vec3 center, float radius) { auto sphere = std::make_shared<Mesh>(); float delta = 1.0 / N; glm::vec2 tex(0.0f, 0.0f); for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) { float x = i * delta; float y = j * delta; // 1. hromszg: x,y x+delta,y y+delta,x auto a = CalculateSphereCoordinate(x, y, radius) + center; auto b = CalculateSphereCoordinate(x + delta, y, radius) + center; auto c = CalculateSphereCoordinate(x, y + delta, radius) + center; auto dir = glm::cross((b - a), (c - a)); // cross product sphere->addTriangle(a, b, c, dir / (float)dir.length(), tex); // 2. hromszg: x+delta,y x+delta,y+delta y+delta,x a = CalculateSphereCoordinate(x + delta, y, radius) + center; b = CalculateSphereCoordinate(x + delta, y + delta, radius) + center; c = CalculateSphereCoordinate(x, y + delta, radius) + center; dir = glm::cross((b - a), (c - a)); // cross product sphere->addTriangle(a, b, c, dir / (float)dir.length(), tex); } } return sphere; } std::shared_ptr<Mesh> GeometryFactory::GetKnob(glm::vec3 bottomCenterPosition) { auto knob = GetCylinder(bottomCenterPosition, glm::vec3(0.0f, 1.0f, 0.0f), knobRadius, knobHeight); knob->merge(GetCircle(bottomCenterPosition + glm::vec3(0.0f, knobHeight, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f), knobRadius).get()); return knob; } std::shared_ptr<Mesh> GeometryFactory::GetLegoCube(int rows, int cols, CubeHeight height) { float xWidth = cols * cubeWidthUnit - 2 * cubeWidthOffset; float zWidth = rows * cubeWidthUnit - 2 * cubeWidthOffset; float yTop = (int)height * thinCubeHeightUnit; float yBottom = 0.0f; // assemble a lego cube's sides auto cubeMesh = GeometryFactory::GetCuboid(glm::vec3(cubeWidthOffset, yTop, cubeWidthOffset), glm::vec3(cubeWidthOffset + xWidth, yTop - cubeTopWallThickness, cubeWidthOffset + zWidth)); // top cubeMesh->merge(GeometryFactory::GetCuboid(glm::vec3(cubeWidthOffset, yTop, cubeWidthOffset + zWidth - cubeSideWallThickness), glm::vec3(cubeWidthOffset + xWidth, yBottom, cubeWidthOffset + zWidth)).get()); // front cubeMesh->merge(GeometryFactory::GetCuboid(glm::vec3(cubeWidthOffset + xWidth - cubeSideWallThickness, yTop, cubeWidthOffset), glm::vec3(cubeWidthOffset + xWidth, yBottom, cubeWidthOffset + zWidth)).get()); // right cubeMesh->merge(GeometryFactory::GetCuboid(glm::vec3(cubeWidthOffset, yTop, cubeWidthOffset), glm::vec3(cubeWidthOffset + xWidth, yBottom, cubeWidthOffset + cubeSideWallThickness)).get()); // back cubeMesh->merge(GeometryFactory::GetCuboid(glm::vec3(cubeWidthOffset, yTop, cubeWidthOffset), glm::vec3(cubeWidthOffset + cubeSideWallThickness, yBottom, cubeWidthOffset + zWidth)).get()); // left // add knobs for (int r = 0; r < rows; ++r) { for (int c = 0; c < cols; ++c) { float knobZ = r * cubeWidthUnit + (cubeWidthUnit / 2.0f); float knobX = c * cubeWidthUnit + (cubeWidthUnit / 2.0f); cubeMesh->merge(GetKnob(glm::vec3(knobX, yTop, knobZ)).get()); } } return cubeMesh; } std::shared_ptr<Mesh> GeometryFactory::GetDriverTorso(glm::vec3 bottomCenterPosition) { auto torso = std::make_shared<Mesh>(); float height = 5.0f * thinCubeHeightUnit; float bottomXWidthHalf = 1.0f * cubeWidthUnit - cubeWidthOffset; float bottomZWidthHalf = 0.5f * cubeWidthUnit - cubeWidthOffset; float topXWidthHalf = 0.75f * cubeWidthUnit - cubeWidthOffset; float topZWidthHalf = 0.5f * cubeWidthUnit - cubeWidthOffset; glm::vec3 topCenterPosition = bottomCenterPosition; topCenterPosition.y += height; // corner positions glm::vec3 bottomE(bottomCenterPosition.x - bottomXWidthHalf, bottomCenterPosition.y, bottomCenterPosition.z - bottomZWidthHalf); glm::vec3 bottomF(bottomCenterPosition.x + bottomXWidthHalf, bottomCenterPosition.y, bottomCenterPosition.z - bottomZWidthHalf); glm::vec3 bottomG(bottomCenterPosition.x - bottomXWidthHalf, bottomCenterPosition.y, bottomCenterPosition.z + bottomZWidthHalf); glm::vec3 bottomH(bottomCenterPosition.x + bottomXWidthHalf, bottomCenterPosition.y, bottomCenterPosition.z + bottomZWidthHalf); glm::vec3 topA(topCenterPosition.x - topXWidthHalf, topCenterPosition.y, topCenterPosition.z - topZWidthHalf); glm::vec3 topB(topCenterPosition.x + topXWidthHalf, topCenterPosition.y, topCenterPosition.z - topZWidthHalf); glm::vec3 topC(topCenterPosition.x - topXWidthHalf, topCenterPosition.y, topCenterPosition.z + topZWidthHalf); glm::vec3 topD(topCenterPosition.x + topXWidthHalf, topCenterPosition.y, topCenterPosition.z + topZWidthHalf); glm::vec2 tex(0.0f, 0.0f); torso->addQuad(topA, topC, topD, topB, glm::vec3(0.0f, 1.0f, 0.0f), tex); // top torso->addQuad(topC, bottomG, bottomH, topD, glm::vec3(0.0f, 0.0f, 1.0f), tex); // front torso->addQuad(topD, bottomH, bottomF, topB, glm::vec3(1.0f, 0.0f, 0.0f), tex); // right torso->addQuad(topB, bottomF, bottomE, topA, glm::vec3(0.0f, 0.0f, -1.0f), tex); // back torso->addQuad(topA, bottomE, bottomG, topC, glm::vec3(-1.0f, 0.0f, 0.0f), tex); // left torso->addQuad(bottomG, bottomE, bottomF, bottomH, glm::vec3(0.0f, -1.0f, 0.0f), tex); // bottom return torso; } std::shared_ptr<Mesh> GeometryFactory::GetDriver() { auto driver = std::make_shared<Mesh>(); float xWidth = 1 * cubeWidthUnit - 2 * cubeWidthOffset; float zWidth = 2 * cubeWidthUnit - 2 * cubeWidthOffset; // left leg driver = GetCuboid( glm::vec3(cubeWidthOffset, 2.0 * thinCubeHeightUnit, cubeWidthOffset), glm::vec3(cubeWidthOffset + xWidth, 0.0f, cubeWidthOffset + zWidth)); driver->merge(GetCuboid( glm::vec3(cubeWidthOffset, 3.0 * thinCubeHeightUnit, cubeWidthOffset + zWidth - thinCubeHeightUnit), glm::vec3(cubeWidthOffset + xWidth, 0.0f, cubeWidthOffset + zWidth)).get()); // right leg driver->merge(GetCuboid( glm::vec3(2.0f * cubeWidthOffset + xWidth, 2.0 * thinCubeHeightUnit, cubeWidthOffset), glm::vec3(2.0f * cubeWidthOffset + 2.0f * xWidth, 0.0f, cubeWidthOffset + zWidth)).get()); driver->merge(GetCuboid( glm::vec3(2.0f * cubeWidthOffset + xWidth, 3.0 * thinCubeHeightUnit, cubeWidthOffset + zWidth - thinCubeHeightUnit), glm::vec3(2.0f * cubeWidthOffset + 2.0f * xWidth, 0.0f, cubeWidthOffset + zWidth)).get()); // torso driver->merge(GetDriverTorso(glm::vec3(cubeWidthOffset + xWidth, 2.0 * thinCubeHeightUnit + cubeWidthOffset, cubeWidthOffset + 0.5 * cubeWidthUnit)).get()); // left arm driver->merge(GetCuboid( glm::vec3(cubeWidthOffset, 5.5 * thinCubeHeightUnit, cubeWidthOffset), glm::vec3(cubeWidthOffset + xWidth / 2.0f, 4.5f * thinCubeHeightUnit, cubeWidthOffset + zWidth)).get()); // right arm driver->merge(GetCuboid( glm::vec3(2.0f * cubeWidthOffset + 1.5f * xWidth, 5.5 * thinCubeHeightUnit, cubeWidthOffset), glm::vec3(2.0f * cubeWidthOffset + 2.0f * xWidth, 4.5f * thinCubeHeightUnit, cubeWidthOffset + zWidth)).get()); // head driver->merge(GeometryFactory::GetSphere(glm::vec3(cubeWidthOffset + xWidth, 8.5 * thinCubeHeightUnit - cubeWidthOffset, cubeWidthOffset + 0.5 * cubeWidthUnit), cubeWidthUnit / 1.5 - cubeWidthOffset).get()); // driving wheel base driver->merge(GetCuboid( glm::vec3(cubeWidthOffset, thinCubeHeightUnit, 2 * cubeWidthOffset + zWidth), glm::vec3(2.0f * cubeWidthOffset + 2.0f * xWidth, 0.0f, 2 * cubeWidthOffset + zWidth + cubeWidthUnit)).get()); // driving wheel cylinder driver->merge(GetCylinder(glm::vec3(cubeWidthOffset + xWidth, 0.0f, 2.0f * cubeWidthOffset + 1.25f * zWidth), glm::vec3(0.0f, 1.0f, 0.0f), knobRadius / 2.0f, 6.0 * thinCubeHeightUnit).get()); // driving wheel circle driver->merge(GetCircle(glm::vec3(cubeWidthOffset + xWidth, 6.0 * thinCubeHeightUnit, 2.0f * cubeWidthOffset + 1.25f * zWidth), glm::vec3(0.0f, 1.0f, 0.0f), knobRadius / 2.0f).get()); // driving wheel driver->merge(GetCuboid( glm::vec3(cubeWidthOffset + xWidth / 2.0f, 7.0f * thinCubeHeightUnit, 2.0f * cubeWidthOffset + 1.20f * zWidth), glm::vec3(2.0f * cubeWidthOffset + 1.5f * xWidth, 5.0f * thinCubeHeightUnit, 2.0f * cubeWidthOffset + 1.30f * zWidth)).get()); return driver; } std::shared_ptr<Mesh> GeometryFactory::GetReflector() { auto reflector = GetLegoCube(1, 1, CubeHeight::THIN); reflector->merge(GetCylinder(glm::vec3(cubeWidthUnit / 2.0f, 0.0f, cubeWidthUnit / 2.0f), glm::vec3(0.0f, 1.0f, 0.0f), knobHeight / 2.0f, 3.0f * thinCubeHeightUnit).get()); reflector->merge(GetCuboid( glm::vec3(cubeWidthOffset, 6.0f * thinCubeHeightUnit, cubeWidthOffset), glm::vec3(cubeWidthOffset + cubeWidthUnit, 3.0f * thinCubeHeightUnit, cubeWidthOffset + cubeWidthUnit)).get()); reflector->merge(GetKnob(glm::vec3(cubeWidthUnit / 2.0f, 6.0f * thinCubeHeightUnit, cubeWidthUnit / 2.0f)).get()); reflector->merge(GetSphere(glm::vec3(cubeWidthUnit / 2.0f, 4.5f * thinCubeHeightUnit, cubeWidthUnit), 1.4f * knobRadius).get()); return reflector; } std::shared_ptr<Mesh> GeometryFactory::GetWheel() { // Outer rim. auto wheel = GetCylinder( glm::vec3(0.0f, 1.5f * cubeWidthUnit, 1.5f * cubeWidthUnit), glm::vec3(1.0f, 0.0f, 0.0f), 1.5f * cubeWidthUnit, cubeWidthUnit); wheel->merge(GetCircle( glm::vec3(0.0f, 1.5f * cubeWidthUnit, 1.5f * cubeWidthUnit), glm::vec3(-1.0f, 0.0f, 0.0f), 1.5f * cubeWidthUnit).get()); wheel->merge(GetCircle( glm::vec3(cubeWidthUnit, 1.5f * cubeWidthUnit, 1.5f * cubeWidthUnit), glm::vec3(1.0f, 0.0f, 0.0f), 1.5f * cubeWidthUnit).get()); // Inner rim. wheel->merge(GetCylinder( glm::vec3(cubeWidthUnit, 1.5f * cubeWidthUnit, 1.5f * cubeWidthUnit), glm::vec3(1.0f, 0.0f, 0.0f), 1.0f * cubeWidthUnit, 0.2f * cubeWidthUnit).get()); wheel->merge(GetCircle( glm::vec3(1.2f * cubeWidthUnit, 1.5f * cubeWidthUnit, 1.5f * cubeWidthUnit), glm::vec3(1.0f, 0.0f, 0.0f), 1.0f * cubeWidthUnit).get()); return wheel; } std::shared_ptr<Mesh> GeometryFactory::GetLineTrackMesh(std::shared_ptr<const Line> line, float halfWidth) { auto lineMesh = std::make_shared<Mesh>(); int quadNum = 16; for (int i = 0; i < 16; ++i) { switch (line->orientation) { case Line::Orientation::HORIZONTAL: { float width = abs(line->start.x - line->end.x); float startX = (line->start.x < line->end.x) ? 0.0f : -width; float currentX = (width / quadNum) * i + startX; float nextX = (width / quadNum) * (i + 1) + startX; float Y = line->start.y; // float zTop = line->start.z - halfWidth, zBottom = line->start.z + halfWidth; float zTop = 0.0f - halfWidth, zBottom = 0.0f + halfWidth; glm::vec3 a(currentX, Y, zTop); glm::vec3 b(currentX, Y, zBottom); glm::vec3 c(nextX, Y, zBottom); glm::vec3 d(nextX, Y, zTop); lineMesh->addQuadTex(a, b, c, d, glm::vec3(0.0f, 1.0f, 0.0f)); } break; case Line::Orientation::VERTICAL: { float height = abs(line->start.z - line->end.z); float startZ = (line->start.z < line->end.z) ? 0.0f : -height; float currentZ = (height / quadNum) * i + startZ; float nextZ = (height / quadNum) * (i + 1) + startZ; float Y = line->start.y; // float xLeft = line->start.x - halfWidth, xRight = line->start.x + halfWidth; float xLeft = 0.0f - halfWidth, xRight = 0.0f + halfWidth; glm::vec3 a(xLeft, Y, currentZ); glm::vec3 b(xLeft, Y, nextZ); glm::vec3 c(xRight, Y, nextZ); glm::vec3 d(xRight, Y, currentZ); lineMesh->addQuadTex(a, b, c, d, glm::vec3(0.0f, 1.0f, 0.0f)); } break; default: break; } } return lineMesh; } std::shared_ptr<Mesh> GeometryFactory::GetCornerTrackMesh(std::shared_ptr<const Corner> corner, float halfWidth) { auto cornerMesh = std::make_shared<Mesh>(); float Y = corner->center.y; /*glm::vec3 a(0.0f, Y, -2.0 * corner->radius); glm::vec3 b(0.0f, Y, -0.5f * corner->radius); glm::vec3 c(0.5f * corner->radius, Y, 0.0f); glm::vec3 d(2.0f * corner->radius, Y, 0.0f); glm::vec3 e(2.0f * corner->radius, Y, -1.5f * corner->radius); glm::vec3 f(1.5f * corner->radius, Y, -2.0f * corner->radius);*/ glm::vec3 a(0.0f, Y, -2.0 * corner->radius); glm::vec3 b(0.0f, Y, 0.0f); glm::vec3 c(2.0f * corner->radius, Y, 0.0f); glm::vec3 d(2.0f * corner->radius, Y, -1.5f * corner->radius); glm::vec3 e(1.5f * corner->radius, Y, -2.0f * corner->radius); glm::vec3 normal(0.0f, 1.0f, 0.0f); /*cornerMesh->addTriangleTex(a, b, f, normal); cornerMesh->addTriangleTex(f, b, c, normal); cornerMesh->addTriangleTex(f, c, e, normal); cornerMesh->addTriangleTex(e, c, d, normal);*/ cornerMesh->addTriangleTex(a, b, e, normal); cornerMesh->addTriangleTex(e, b, d, normal); cornerMesh->addTriangleTex(d, b, c, normal); return cornerMesh; } std::shared_ptr<Mesh> GeometryFactory::GetFinishLine(glm::vec3 center, float size) { auto finishLine = std::make_shared<Mesh>(); glm::vec3 a(center.x - size / 2.0f, center.y, center.z - size / 2.0f); glm::vec3 b(center.x - size / 2.0f, center.y, center.z + size / 2.0f); glm::vec3 c(center.x + size / 2.0f, center.y, center.z + size / 2.0f); glm::vec3 d(center.x + size / 2.0f, center.y, center.z - size / 2.0f); finishLine->addQuadTex(a, b, c, d, glm::vec3(0.0f, 1.0f, 0.0f)); return finishLine; }
true
417df2a5ce5b1afca02057d4e929bb70b8d269c1
C++
xiaohaoxiang/algo
/质因子分解Pollard_Rho与Miller_Rabin.cpp
UTF-8
2,934
2.75
3
[]
no_license
#include <algorithm> #include <cstdio> #include <cstdlib> #include <ctime> using namespace std; typedef unsigned long long ull; const int MAX_N = 1000; const int S = 32; // Miller_Rabin中的判断次数 ull factor[MAX_N]; // 分解出的质因子(无序) int fcnt; // 质因子数量, 需先归零 ull gcd(ull a, ull b); // 计算 gcd(a, b) ull mult_mod(ull a, ull b, ull m); // 计算 a*b % m ull pow_mod(ull x, ull p, ull m); // 计算 x^p % m bool check(ull a, ull n, ull x, ull t); // 进行一轮检测, 确定是合数返回 true, 否则返回 false bool Miller_Rabin(ull n); // 是素数返回 true, 否则返回 false void find_factor(ull x); // 对 x 进行素数分解, 调用前应将 fcnt 初始化为0 ull Pollard_rho(ull x, ull c); // 以随机种子 c 找到 x 的某个因子 int main() { return 0; } ull gcd(ull a, ull b) { if (a == 0) return 1; while (b) { ull t = a % b; a = b; b = t; } return a; } ull mult_mod(ull a, ull b, ull m) { a %= m; b %= m; ull res = 0; while (b) { if (b & 1) { res = (res + a) % m; } a <<= 1; if (a >= m) a -= m; b >>= 1; } return res; } ull pow_mod(ull x, ull p, ull m) { ull res = 1; x %= m; while (p) { if (p & 1) { res = mult_mod(res, x, m); } x = mult_mod(x, x, m); p >>= 1; } return res; } bool check(ull a, ull n, ull x, ull t) { ull res = pow_mod(a, x, n); ull last = res; for (int i = 1; i <= t; i++) { res = mult_mod(res, res, n); if (res == 1 && last != 1 && last != n - 1) return true; last = res; } if (res != 1) return true; return false; } bool Miller_Rabin(ull n) { if (n < 2) return false; if (n == 2) return true; if (!(n & 1)) return false; ull x = n - 1; ull t = 0; while (!(x & 1)) { x >>= 1; ++t; } for (int i = 0; i < S; i++) { ull a = rand() % (n - 1) + 1; if (check(a, n, x, t)) return false; } return true; } ull Pollard_rho(ull x, ull c) { ull i = 1, k = 2; ull x0 = rand() % x; ull y = x0; while (1) { i++; x0 = (mult_mod(x0, x0, x) + c) % x; ull d = gcd(y > x0 ? y - x0 : x0 - y, x); if (d != 1 && d != x) return d; if (y == x0) return x; if (i == k) { y = x0; k += k; } } } void find_factor(ull x) { if (Miller_Rabin(x)) { factor[fcnt++] = x; return; } ull p = x; while (p >= x) p = Pollard_rho(p, rand() % (x - 1) + 1); find_factor(p); find_factor(x / p); }
true
96f3a578b875df63cf4bf40c59c0428a49f007e1
C++
younnggsuk/cpp
/ch4/PrivateConstructor.cpp
UTF-8
468
3.359375
3
[]
no_license
#include <iostream> using std::cout; using std::cin; using std::endl; class AAA { private: int num; AAA(int n) : num(n) {} public: AAA() : num(0) {} AAA& InitObject(int n) { AAA *ptr = new AAA(n); return *ptr; } void ShowInfo() const { cout<<num<<endl; } }; int main(void) { AAA obj1; obj1.ShowInfo(); AAA &obj2 = obj1.InitObject(3); obj2.ShowInfo(); AAA &obj3 = obj1.InitObject(12); obj3.ShowInfo(); delete &obj2; delete &obj3; return 0; }
true
f60607304747be6c131157e38d6f6bfd76188e70
C++
chiuwe/ME405_Lab2_Motor_Driver
/motor_controller.h
UTF-8
2,440
2.984375
3
[]
no_license
//************************************************************************************** /** \file motor_controller.h * This file contains the header for a motor controller class which controls speed * and direction of a motor using a voltage measured from the A/D as input. A * potentiomiter is used for speed and a single button controls the break. One each * for each motor */ //************************************************************************************** // This define prevents this .h file from being included multiple times in a .cpp file #ifndef _MOTOR_CONTROLLER_H_ #define _MOTOR_CONTROLLER_H_ #include <stdlib.h> // Prototype declarations for I/O functions #include <avr/io.h> // Header for special function registers #include "FreeRTOS.h" // Primary header for FreeRTOS #include "task.h" // Header for FreeRTOS task functions #include "queue.h" // FreeRTOS inter-task communication queues #include "frt_task.h" // ME405/507 base task class #include "time_stamp.h" // Class to implement a microsecond timer #include "frt_queue.h" // Header of wrapper for FreeRTOS queues #include "frt_shared_data.h" // Header for thread-safe shared data #include "rs232int.h" // ME405/507 library for serial comm. #include "adc.h" // Header for A/D converter driver class #include "motor_driver.h" //------------------------------------------------------------------------------------- /** \brief This task controls the speed/direction of a motor using an analog input from * the A/D converter. * \details The A/D converter is run using a driver in files \c adc.h and \c adc.cpp. * An anolog input through a POT goes through the adc and is used to control the speed * of the motor. */ class motor_controller : public frt_task { private: // No private variables or methods for this class protected: // No protected variables or methods for this class public: // This constructor creates a generic task of which many copies can be made motor_controller (const char*, unsigned portBASE_TYPE, size_t, emstream*); // This method is called by the RTOS once to run the task loop for ever and ever. void run (void); }; #endif // _MOTOR_CONTROLLER_H_
true
52d7abdfbe3348de233ac542dc4d4d68f6b70709
C++
pratiksachaniya/Cpp
/STRUCT.CPP
UTF-8
642
3.453125
3
[]
no_license
/* Struct In C++ */ #include<iostream.h> #include<conio.h> struct student { int roll; char name[20]; int m1,m2,m3; float result() { return (m1+m2+m3)/3; } }; void main() { clrscr(); struct student s1; cout<<"Enter Student Roll Number:"; cin>>s1.roll; cout<<"Enter Student Name:"; cin>>s1.name; cout<<"Enter Marks of C++ Lang.:"; cin>>s1.m1; cout<<"Enter Marks of DS: "; cin>>s1.m2; cout<<"Enter Marks of HTML: "; cin>>s1.m3; clrscr(); cout<<"Student Roll No.: "<<s1.roll<<endl; cout<<"Student Name: "<<s1.name<<endl; cout<<"Student result: "<<s1.result()<<"%"; getch(); }
true
3f0371c309faf76c632547ef3461b0f7b0da16dd
C++
KFlaga/AutoRobo_Cpp
/AutoRobo_Cpp/src/ARSystemTimer.h
UTF-8
2,318
2.90625
3
[]
no_license
/* * ARTime.h * * Created on: Mar 23, 2017 * Author: Kamil */ #ifndef ARSYSTEMTIMER_H_ #define ARSYSTEMTIMER_H_ #include "ARTimeSpan.h" #include <functional> namespace AutoRobo { typedef unsigned int TimerId; // Represents global timer, which works for entire time and enables // to register callback which is fired after specified time passed // Based on SysTick timer class SystemTimer { public: static SystemTimer& getSystemTimer() { static SystemTimer timer; return timer; } private: SystemTimer(); // disable copying SystemTimer(const SystemTimer&) = delete; SystemTimer& operator=(const SystemTimer&) = delete; public: // Returns time of single timer tick TimeSpan getResolution(); // Sets resolution of timer - time of single tick bool setResolution(TimeSpan resolution); // Registers callback to be called after specified time passed // Callback is fired repeatedly until unregistered // Returns id which is used for unregistering // If interval is not multiply of resolution, callback is fired and // refreshed in same time as it would be rounded up to closest multiply. // Callbacks are fired in register order, after one-shots TimerId registerRepeatedCallback(std::function<void()> callback, TimeSpan interval); // Unregisters previously set callback // If id is invalid, nothing happens. // No callback should be unregistered inside a callback void unregisterRepeatedCallback(TimerId id); // Registers callback to be called after specified time passed one time // If interval is not multiply of resolution, callback is fired and // refreshed in same time as it would be rounded up to closest multiply. // Callbacks are fired in register order, before repeated-callbacks void registerOneShotCallback(std::function<void()> callback, TimeSpan interval); // TODO: implement this // Checks if there is a callback to be fired (waiting time = 0) // Should be called in low-priority loop or irq (if threads are available) // void update(); // Updates callback timers waiting time (for now also fires callbacks) // Should be called inside SysTick_Handler void updateTick(); }; // Blocks for specified TimeSpan (uses one shot on SystemTimer) void wait(TimeSpan waitTime); } #endif /* ARSYSTEMTIMER_H_ */
true
e95ca13dda0ee771556f06fb3ab799f72691e6fe
C++
zhouzora/Learning-C-skills
/exercise0507.cpp
UTF-8
722
3.078125
3
[]
no_license
#include<bits/stdc++.h> #include<string.h> #include<array> using namespace std; struct car { string supplier; int year; }; int main() { int cars_size=0; cout<<"how many cars do you wish to catalog: "; (cin>>cars_size).get(); car *cars=new car[cars_size]; for(int i=0;i<cars_size;i++) { cout<<"Car #"<<i+1<<":"<<endl; cout<<"Please enter the make:"; getline(cin,cars[i].supplier); cout<<"Please enter the year made:"; (cin>>cars[i].year).get(); } cout<<"Here is your collection:"<<endl; for(int i=0;i<cars_size;i++) { cout<<cars[i].year<<" "<<cars[i].supplier<<endl; } delete []cars; }
true
9b2e4469b1119c1c4f9690cc6d79027988553175
C++
kanchan1910/June-Leetcoding-Challenge-2021
/Construct Binary Tree from Preorder and Inorder Traversal.cpp
UTF-8
1,248
3.3125
3
[]
no_license
class Solution { public: unordered_map<int, int>m; TreeNode* fun(vector<int>& preorder, int& index, int l, int r) { // base case if(l > r) { return NULL; } int val = preorder[index]; index++; // forming the node TreeNode* node = new TreeNode(val); node->left = fun(preorder, index, l, m[val] - 1); node->right = fun(preorder, index, m[val] + 1, r); return node; } TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { int index = 0; // doing the work of searching the index in the inorder traversal for(int i = 0; i < inorder.size(); i++) { m[inorder[i]] = i; } return fun(preorder, index, 0, inorder.size() - 1); } }; // i // [3,9,20,15,7] // (9,0) (3,1) (15,2) (20,3) (7,4) // lr // [9,3,15,20,7] // val = 20 // 3 // 9 20 // NULL 15 7 // NULL // // preorder // // [3,9,20,15,7] // // inorder // // [9,3,15,20,7] // // 3 // // 9 20 // // 15 7 // // preorder // // [3,9,20] // // inorder // // [9,3,20] // // 3 // 9 20
true
491174ecfd7c02d57125da318e7a04678c2b0346
C++
ljshou/workspace
/algorithm/poj/1003.cc
UTF-8
239
2.75
3
[]
no_license
#include <iostream> using namespace std; int main(void) { double len, val; int i; while(cin >> len && len) { val = 0.0; for(i=1; val < len; ++i) val += 1.0/(i+1.0); cout << i-1 << " card(s)" << endl; } return 0; }
true
83e070fd8e99597697f81dc22cd6558a2e2792f8
C++
mfkiwl/cuda-flow2d
/src/optical_flow/optical_flow_base_2d.cpp
UTF-8
2,117
2.59375
3
[]
no_license
/** * @file 2D Optical flow using NVIDIA CUDA * @author Institute for Photon Science and Synchrotron Radiation, Karlsruhe Institute of Technology * * @date 2015-2018 * @version 0.5.0 * * * @section LICENSE * * This program is copyrighted by the author and Institute for Photon Science and Synchrotron Radiation, * Karlsruhe Institute of Technology, Karlsruhe, Germany; * * The current implemetation contains the following licenses: * * 1. TinyXml package: * Original code (2.0 and earlier )copyright (c) 2000-2006 Lee Thomason (www.grinninglizard.com). <www.sourceforge.net/projects/tinyxml>. * See src/utils/tinyxml.h for details. * */ #include "src/optical_flow/optical_flow_base_2d.h" #include <cmath> OpticalFlowBase2D::OpticalFlowBase2D(const char* name) : name_(name) { } const char* OpticalFlowBase2D::GetName() const { return name_; } size_t OpticalFlowBase2D::GetMaxWarpLevel(size_t width, size_t height, float scale_factor) const { /* Compute maximum number of warping levels for given image size and warping reduction factor */ size_t r_width = 1; size_t r_height = 1; size_t level_counter = 1; while (scale_factor < 1.f) { float scale = std::pow(scale_factor, static_cast<float>(level_counter)); r_width = static_cast<size_t>(std::ceil(width * scale)); r_height = static_cast<size_t>(std::ceil(height * scale)); if (r_width < 4 || r_height < 4 ) { break; } ++level_counter; } if (r_width == 1 || r_height == 1) { --level_counter; } return level_counter; } bool OpticalFlowBase2D::IsInitialized() const { if (!initialized_) { std::printf("Error: '%s' was not initialized.\n", name_); } return initialized_; } void OpticalFlowBase2D::ComputeFlow(Data2D& frame_0, Data2D& frame_1, Data2D& flow_u, Data2D& flow_v, OperationParameters& params) { std::printf("Warning: '%s' ComputeFlow() was not defined.\n", name_); } void OpticalFlowBase2D::Destroy() { initialized_ = false; } OpticalFlowBase2D::~OpticalFlowBase2D() { if (initialized_) { Destroy(); } }
true
004a5ad14ff521f05bf6ced91cd2e423ce3fa89a
C++
KoreanGinseng/CreativeLabo3
/その他/Sample0218/Observer05/Character.h
SHIFT_JIS
1,814
3.265625
3
[ "MIT" ]
permissive
#pragma once #include "Texture.h" #include "Subject.h" /** * LN^[NX */ class Character { private: /** LN^[̎c@ */ int life; /** LN^[̃RC */ int coin; /** LN^[̃XRA */ int score; /** LN^[͉摜 */ Texture texture; /** c@ύXʒm */ Subject<int> lifeSubject; /** RCύXʒm */ Subject<int> coinSubject; /** XRAύXʒm */ Subject<int> scoreSubject; public: /** * RXgN^ */ Character() : life(3) , coin(0) , score(0) , texture() , lifeSubject() , coinSubject() , scoreSubject() { } /** * fXgN^ */ ~Character() { } /** * @brief 摜̓ǂݍݏ */ bool Load() { return texture.Load("Player.png"); } /** * @brief S * c@炷 */ void Dead() { life -= 1; lifeSubject.Notify(life); std::cout << "vC[ł܂" << std::endl; } /** * @brief RC̊l * RC1₵āAXRA100₷ */ void AcquiredCoin() { coin += 1; score += 100; coinSubject.Notify(coin); scoreSubject.Notify(score); std::cout << "vC[RCl" << std::endl; } /** * @brief G| * XRA200₷ */ void KillEnemy() { score += 200; scoreSubject.Notify(score); std::cout << "vC[G|" << std::endl; } int GetLife() const { return life; } int GetCoin() const { return coin; } int GetScore() const { return score; } IObservable<int>* GetLifeSubject() { return &lifeSubject; } IObservable<int>* GetCoinSubject() { return &coinSubject; } IObservable<int>* GetScoreSubject() { return &scoreSubject; } };
true
9be45e8fb89fed1ded73ec712fd33d18701430e1
C++
jentos00/VIM
/model/Model.cpp
UTF-8
1,769
3.234375
3
[]
no_license
#include "Model.h" void Model::open(const std::string &filename) { std::ifstream in(filename); if (!in.is_open()) throw std::runtime_error("can't open file " + filename); read(in); m_filename = filename; } void Model::read(std::istream &in) { m_lines.clear(); std::string line; while (std::getline(in, line)) { m_lines.push_back(MyString(line)); } m_modified = false; if (m_lines.empty()) m_lines.emplace_back(""); m_filename = ""; } void Model::write(const std::string &l_filename) { std::string filename = l_filename.empty() ? m_filename : l_filename; std::ofstream out(filename); if (!out.is_open()) throw std::runtime_error("can't open file " + filename); for (auto& line : m_lines) { out << line << std::endl; } m_modified = false; } void Model::newLine(int i) { MyString str; m_lines.insert(m_lines.begin() + 1 + i, str); m_lines[i + 1].shrink_to_fit(); } MyString& Model::line(size_t line) { return m_lines[line]; } size_t Model::n_lines() const { return m_lines.size(); } size_t Model::lineSize(size_t i) { return m_lines[i].size(); } void Model::removeLine(size_t i) { m_modified = true; m_lines.erase(m_lines.cbegin() + i); } void Model::insert(size_t line, size_t pos, MyString str) { m_modified = true; m_lines[line].insert(pos, str.c_str()); } void Model::push_back() { m_lines.push_back("\0"); } void Model::erase(size_t line, size_t pos, size_t len) { m_modified = true; m_lines[line].erase(pos, len); } void Model::replace(size_t line, size_t pos, size_t len, char* const& str) { m_modified = true; m_lines[line].replace(pos, len, str); } bool Model::modified() { return m_modified; }
true
8eb145143390db08e3ebb1d5df234ccebe2f5409
C++
himanshu9345/cpp-practice
/2.variables.cpp
UTF-8
541
3.265625
3
[]
no_license
// // Created by himanshu on 10/29/19. // #include <iostream> int main(){ std::cout<<"Hello World"<< std::endl; //value will remain constant const double PI=3.14; //char 1byte in memory char myGrade = 'A'; //boolean true or false bool isEmpty = true; //float accurate upto 6 decimal places float myNum = 3.1488585; //double are accurate upt to 15 float newNum = 1.645678987654345678; std::cout<<"newNum :"<<newNum; std::cout<<"Size of my grade : "<< sizeof(myGrade); return 0; }
true
6645c94b596c44be01f3cf76bae2af32c7e54d03
C++
vandenoordj/Lab3
/ListArray.cpp
UTF-8
5,031
3.15625
3
[]
no_license
/* * ListArray.cpp * * Created on: Feb 16, 2015 * Author: vandenoordj */ #include "ListArray.h" template < typename DataType > List<DataType>::List (int maxNumber ){ maxSize = maxNumber; size = 0; cursor = -1; dataItems = new DataType[maxSize]; } template < typename DataType > List<DataType>::List ( const List& source ){ maxSize = source.maxSize; size = source.size; cursor = source.cursor; dataItems = new DataType[maxSize]; for(int i = 0 ; i < size; i++) dataItems[i] = source.dataItems[i]; } template < typename DataType > List<DataType>& List<DataType>::operator= ( const List& source ){ maxSize = source.maxSize; size = source.size; cursor = source.cursor; delete [] dataItems; dataItems = new DataType[maxSize]; for(int i = 0 ; i < size; i++) dataItems[i] = source.dataItems[i]; return *this; } template < typename DataType > List<DataType>::~List (){ delete dataItems; } template < typename DataType > void List<DataType>::insert ( const DataType& newDataItem ) throw ( logic_error ){ if(size != maxSize){ if(size == 0){ dataItems[0] = newDataItem; cursor = 0; }else{ for(int i = size+1; i > cursor; i--) dataItems[i] = dataItems[i-1]; dataItems[cursor + 1] = newDataItem; cursor++; } size++; }else throw logic_error("Too much data"); } template < typename DataType > void List<DataType>::remove () throw ( logic_error ){ if(size == 0) throw logic_error("no items"); for(int i = cursor ; i < size - 1; i++) dataItems[i] = dataItems[i+1]; size--; if(cursor >= size) cursor = 0; } template < typename DataType > void List<DataType>::replace ( const DataType& newDataItem ) throw ( logic_error ){ if(cursor >= 0 && cursor < size) dataItems[cursor] = newDataItem; else throw logic_error("cannot replace"); } template < typename DataType > void List<DataType>::clear(){ size = 0; cursor = -1; delete[] dataItems; dataItems = new DataType[maxSize]; } template < typename DataType > bool List<DataType>::isEmpty() const{ return size == 0; } template < typename DataType > bool List<DataType>::isFull() const{ return size == maxSize; } template < typename DataType > void List<DataType>::gotoBeginning () throw ( logic_error ){ if(size == 0) throw logic_error("no items"); else cursor = 0; } template < typename DataType > void List<DataType>::gotoEnd () throw ( logic_error ){ if(size == 0) throw logic_error("no items"); else cursor = size - 1; } template < typename DataType > bool List<DataType>::gotoNext () throw ( logic_error ){ if(size == 0) throw logic_error("no items"); else if(cursor != size - 1){ cursor++; return true; }else return false; } template < typename DataType > bool List<DataType>::gotoPrior () throw ( logic_error ){ if(size == 0) throw logic_error("no items"); else if(cursor != 0){ cursor--; return true; }else return false; } template < typename DataType > DataType List<DataType>::getCursor () const throw ( logic_error ){ if(size == 0) throw logic_error("no items"); else return dataItems[cursor]; } template < typename DataType > void List<DataType>:: showStructure () const // outputs the data items in a list. if the list is empty, outputs // "empty list". this operation is intended for testing/debugging // purposes only. { int j; // loop counter if ( size == 0 ) cout << "empty list" << endl; // The Ordered List code blows up below. Since this is just debugging // code, we check for whether the OrderedList is defined, and if so, // print out the key value. If not, we try printing out the entire item. // Note: This assumes that you have used the double-inclusion protection // in your OrderedList.cpp file by doing a "#ifndef ORDEREDLIST_CPP", etc. // If not, you will need to comment out the code in the section under // the "else", otherwise the compiler will go crazy in lab 4. // The alternative is to overload operator<< for all data types used in // the ordered list. else { cout << "size = " << size << " cursor = " << cursor << endl; for ( j = 0 ; j < maxSize ; j++ ) cout << j << "\t"; cout << endl; for ( j = 0 ; j < size ; j++ ) { if( j == cursor ) { cout << "["; cout << dataItems[j] #ifdef ORDEREDLIST_CPP .getKey() #endif ; cout << "]"; cout << "\t"; } else cout << dataItems[j] #ifdef ORDEREDLIST_CPP .getKey() #endif << "\t"; } cout << endl; } } template < typename DataType > void List<DataType>::moveToNth ( int n ) throw ( logic_error ){ if(size < n + 1){ throw logic_error("not enough items"); } DataType rep = dataItems[cursor]; this->remove(); cursor = n - 1; this->insert(rep); } template < typename DataType > bool List<DataType>::find ( const DataType& searchDataItem ) throw ( logic_error ){ if(size == 0) throw logic_error("no items"); for(int i = cursor; i < size; i++){ if(dataItems[i]==searchDataItem) return true; if(cursor+1<size) cursor++; } return false; }
true
c4ac51880e64996f2e5f0bf40e16e3439d788059
C++
MaeBung/Client
/Client_Source/CFPSTimer.cpp
UHC
632
2.640625
3
[]
no_license
#include "DXUT.h" #include "CFPSTimer.h" CFPSTimer::CFPSTimer() { } CFPSTimer::~CFPSTimer() { } void CFPSTimer::Update() { DWORD iCurTime = timeGetTime(); // ð float fTimeDelta = (iCurTime - m_iLastTime)*0.001f; //timeDelta(1 帥 ð) 1ʴ ٲش. m_fTimeElapsed += fTimeDelta; m_iFrameCount++; m_fFPS = (float)m_iFrameCount / m_fTimeElapsed; m_fDeltaTime = 1.0f / m_fFPS; if (m_fTimeElapsed >= 1.0f) //帥ð 1̸̻ ϰ ó { m_iFrameCount = 0; m_fTimeElapsed = 0.0f; } m_iLastTime = iCurTime; }
true
13cfbf13c297440def9b13a0cffea5b3d473a023
C++
zimnicky/knu-iii-s-labs-oop
/tasks/1/main.cpp
UTF-8
251
2.515625
3
[]
no_license
#include <fstream> #include "task.h" using namespace std; int main() { ifstream in("input.txt"); ofstream out("output.txt"); Task task; task.read(in); in.close(); out << task.solve() << endl; out.close(); return 0; }
true
60c0374cb1d5f9d01b6e96f79d1870af67c58581
C++
m00p1ng/UVa-problem
/Volume105/10530 - Guessing Game.cpp
UTF-8
1,115
3.109375
3
[]
no_license
#include <cstdio> int main() { bool board[10] = { false }; int number; char cmd[20]; char ig[10]; bool result = true; while(scanf("%d", &number)) { if(number == 0) break; scanf("%s %s", ig, cmd); switch(cmd[0]) { case 'l': for(int i = number - 1; i >= 0; i--) { if(board[i]) { result = false; break; } board[i] = true; } break; case 'h': for(int i = number - 1; i < 10; i++) { if(board[i]) { result = false; break; } board[i] = true; } break; case 'o': if(!board[number-1]) puts("Stan may be honest"); else puts("Stan is dishonest"); for(int i = 0; i < 10; i++) { board[i] = false; } result = true; break; } } }
true
6fe05ca1f46dacf04db3674eeb33b19845860715
C++
dineshmakkar079/My-DS-Algo-code
/interviewbit/Search_for_a_Range.cpp
UTF-8
1,260
3.28125
3
[]
no_license
/* Time : Sat Sep 02 2017 11:21:15 GMT+0530 (IST) URL : https://www.interviewbit.com/problems/search-for-a-range/ Given a sorted array of integers, find the starting and ending position of a given target value. Your algorithm’s runtime complexity must be in the order of O(log n). If the target is not found in the array, return [-1, -1]. Example: Given [5, 7, 7, 8, 8, 10] and target value 8, return [3, 4]. */ #include <bits/stdc++.h> using namespace std; vector<int> Solution::searchRange(const vector<int> &a, int k) { double kr = k+0.5, kl = k-0.5; std::vector<int> ans(2);ans[0] = -1; ans[1] = -1; if(!binary_search(a.begin(),a.end(),k)){ return ans; } int low = 0,high = a.size()-1,mid; while(low<=high){ mid = (low+high)/2; if(a[mid]>kr) high = mid - 1; else low = mid+1; } ans[1] = mid; if(a[mid]!=k){ if(mid+1 < a.size() && a[mid+1]==k)ans[1] = mid+1; if(mid-1 >= 0 && a[mid-1]==k)ans[1] = mid-1; } low = 0; high = a.size()-1; while(low<=high){ mid = (low+high)/2; if(a[mid]>kl) high = mid-1; else low = mid+1; } ans[0] = mid; if(a[mid]!=k){ if(mid+1 < a.size() && a[mid+1]==k)ans[0] = mid+1; if(mid-1 >= 0 && a[mid-1]==k)ans[0] = mid-1; } return ans; } int main(){ return 0; }
true
d9f0ccd286e8f5125ee01f9abe8634213f5e5db6
C++
BryanRobertson/Alba
/Source/Engine/Core/Core_Console.hpp
UTF-8
7,450
2.765625
3
[]
no_license
#pragma once #include "Core.hpp" #include "Core_StringView.hpp" #include "Core_Function.hpp" #include "Core_VectorMap.hpp" #include "Core_StronglyTypedId.hpp" #include "Core_ConsoleCommandInternal.hpp" namespace Alba { namespace Core { //----------------------------------------------------------------------------------------- // Name : ConsoleMessageType // Desc : Type of message printed to the console (can be used for output colouring, etc) //----------------------------------------------------------------------------------------- enum class ConsoleMessageType { Info, Warning, Error }; //----------------------------------------------------------------------------------------- // Name : Console // Desc : Standard Quake/style command console // Executes commands and registers config variables that can be modified at runtime //----------------------------------------------------------------------------------------- class ALBA_CORE_API Console final { public: //================================================================================= // Public Types //================================================================================= typedef FixedFunction<void(ConsoleMessageType aMessageType, StringView aStr)> PrintCallback; typedef StronglyTypedId<uint32, PrintCallback> PrintCallbackId; //================================================================================= // Public Constructors //================================================================================= Console(); ~Console(); //================================================================================= // Public Methods //================================================================================= //--------------------------------------------------------------------------------- // Register/Unregister commands //--------------------------------------------------------------------------------- // Functor/Lambda template <typename TCommand, typename ...TArgs, class=enable_if<is_invocable_v<int, TCommand, TArgs...> > > void RegisterCommand(StringView aCommandName, TCommand&& aCommand) { const auto& ourVTable = ConsoleInternal::MemberFunctionVTableLocator<TCommand>::GetVTable(); if (CommandStorage* storage = InsertCommand(aCommandName)) { storage->myVTable = &ourVTable; storage->myVTable->Store(*storage, (void*)&aCommand); } } // Member function pointer template <typename TClassType, typename ...TArgs> void RegisterCommand(StringView aCommandName, TClassType* anInstance, int (TClassType::*aCommand)(TArgs...) ) { RegisterCommand(aCommandName, [=](TArgs&&... args) -> int { return std::invoke(aCommand, anInstance, std::forward<TArgs>(args)...); }); } // Free function template <typename ...TArgs> void RegisterCommand(StringView aCommandName, int(*aCommand)(TArgs...)) { typedef int(*FunctionType)(TArgs...); const auto& ourVTable = ConsoleInternal::FreeFunctionVTableLocator<FunctionType>(aCommand); if (CommandStorage* storage = InsertCommand(aCommandName)) { storage->myVTable = &ourVTable; storage->myVTable->Store(*storage, (void*)aCommand); } } inline void UnregisterCommand(StringView aCommandName); inline void UnregisterCommand(NoCaseStringHash32 aCommandNameId); //--------------------------------------------------------------------------------- // Execute command //--------------------------------------------------------------------------------- void Execute(StringView aCommand); //--------------------------------------------------------------------------------- // Print //--------------------------------------------------------------------------------- template <typename... TArgs> inline void PrintInfo(StringView aFormat, TArgs&&... someArgs) { Print(ConsoleMessageType::Info, aFormat, std::forward<TArgs>(someArgs)...); } template <typename... TArgs> inline void PrintWarning(StringView aFormat, TArgs&&... someArgs) { Print(ConsoleMessageType::Warning, aFormat, std::forward<TArgs>(someArgs)...); } template <typename... TArgs> inline void PrintError(StringView aFormat, TArgs&&... someArgs) { Print(ConsoleMessageType::Error, aFormat, std::forward<TArgs>(someArgs)...); } template <typename... TArgs> inline void Print(ConsoleMessageType aMessageType, StringView aFormat, TArgs&&... someArgs); void Print(ConsoleMessageType aMessageType, StringView aStr); PrintCallbackId RegisterPrintCallback(const PrintCallback& aCallback); void UnregisterPrintCallback(PrintCallbackId anId); //--------------------------------------------------------------------------------- // Registered command iterator //--------------------------------------------------------------------------------- template <typename TIteratorFunc> void ForEach_RegisteredCommandName(TIteratorFunc&& anItrFunc) { for (const auto& itr : myCommandNames) { anItrFunc(StringView(itr.second)); } } private: //================================================================================= // Private Types //================================================================================= typedef ConsoleInternal::CommandStorage CommandStorage; //================================================================================= // Private Methods //================================================================================= CommandStorage* InsertCommand(StringView aCommandName); void RegisterInternalCommands(); //================================================================================= // Private Data //================================================================================= VectorMap<PrintCallbackId, PrintCallback> myPrintCallbacks; VectorMap<NoCaseStringHash32, CommandStorage> myCommands; VectorMap<NoCaseStringHash32, String> myCommandNames; }; //----------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------- template <typename... TArgs> void Console::Print(ConsoleMessageType aMessageType, StringView aFormat, TArgs&&... someArgs) { const auto outputStr = Core::FormatString<256>(aFormat.data(), std::forward<TArgs>(someArgs)...); Print(aMessageType, StringView(outputStr.c_str())); } //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- void Console::UnregisterCommand(StringView aCommandName) { const Core::NoCaseStringHash32 commandNameId{ aCommandName }; UnregisterCommand(commandNameId); } //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- void Console::UnregisterCommand(NoCaseStringHash32 aCommandNameId) { myCommands.erase(aCommandNameId); myCommandNames.erase(aCommandNameId); } } }
true
c10ede713930e4ee67d2181974de774f310e14de
C++
xulidong/c_cpp
/cpp/design/AbstractFactory.cpp
UTF-8
1,544
3.34375
3
[]
no_license
#include <iostream> using namespace std; class Fruit { public: virtual ~Fruit() {} virtual void sayName() = 0; }; class LocalApple: public Fruit { public: virtual void sayName() { cout << "LocalApple" << endl; } }; class LocalBanana: public Fruit { public: virtual void sayName() { cout << "LocalBanana" << endl; } }; class ImportApple: public Fruit { public: virtual void sayName() { cout << "ImportApple" << endl; } }; class ImportBanana: public Fruit { public: virtual void sayName() { cout << "ImportBanana" << endl; } }; class Factory { public: virtual ~Factory() {} // 水果种类写死 不符合开闭原则 virtual Fruit* createApple() = 0; virtual Fruit* createBanana() = 0; }; class LocalFactory: public Factory { public: Fruit* createApple() { return new LocalApple; } Fruit* createBanana() { return new LocalBanana; } }; class ImportFactory: public Factory { public: Fruit* createApple() { return new ImportApple; } Fruit* createBanana() { return new ImportBanana; } }; int main() { Factory* fac = NULL; Fruit* apple = NULL; Fruit* banana = NULL; // 本地水果 fac = new LocalFactory; apple = fac->createApple(); apple->sayName(); banana = fac->createBanana(); banana->sayName(); delete apple; delete banana; delete fac; // 进口水果 fac = new ImportFactory; apple = fac->createApple(); apple->sayName(); banana = fac->createBanana(); banana->sayName(); delete apple; delete banana; delete fac; return 0; }
true
83a8de00e4cbd17f5d4fb937279e163992c94b84
C++
DOGGY-SAINT/DesignPatternProject_TJ
/Composite/Composite.cpp
UTF-8
722
2.53125
3
[]
no_license
#include"FileSystemManager.h" int main() { FileSystemManager manager; string commandLine; string commands[6]; commands[0] = "mkdir luoyuxia"; commands[1] = "mkfile luoyuxia1997 20"; commands[2] = "mkdir user"; commands[3] = "mkdir temp"; commands[4] = "mkdir bin"; commands[5] = "cd user"; for (int i = 0; i < 6; i++) { manager.doCommand(commands[i]); } while (true) { cout << "/" + manager.getPath() + "$$ "; getline(cin, commandLine); trim_first_last(commandLine); if (commandLine== "") continue; if (_strcmpi(commandLine.c_str(), "exit")==0) break; try { manager.doCommand(commandLine); } catch (EnTryException& e) { e.printException(); } } system("pause"); }
true
34df3c06a78c660772e84e4c661b45889ae650ee
C++
adarshnanwani/cpp-course
/Basic/custom-functions.cpp
UTF-8
579
4.34375
4
[]
no_license
#include <iostream> double pow(double, int); // declaration int main() { int base; int exponent; std::cout << "Please enter the base number: "; std::cin >> base; std::cout << "Please enter the exponent: "; std::cin >> exponent; double result = pow(base, exponent); std::cout << base << " to the power " << exponent << " is " << result; return 0; } double pow(double base, int exponent) // definition { double final_number = 1; for (int i = 0; i < exponent; i++) { final_number *= base; } return final_number; }
true
300a854cd1fc61a95a551261a9a1aba34ba85294
C++
ajason6208/RL_Scheduling-
/RL_Scheduling/FileProcess.cpp
UTF-8
562
2.6875
3
[]
no_license
#include <string> #include <iostream> #include <fstream> #include <sstream> #include <boost/filesystem.hpp> #include "FileProcess.h" using namespace boost::filesystem; using namespace std; vector<string> FileProcess::Get_All_Files(string folder_path) { vector<string> all_files_name; path p(folder_path); for (auto i = directory_iterator(p); i != directory_iterator(); i++) { if (!is_directory(i->path())) //we eliminate directories { all_files_name.push_back(i->path().filename().string()); } else continue; } return all_files_name; }
true
fa242ef36c7555120f0dc46e9e8b63dd98876378
C++
AntonWilson123/OOP
/lab1/main.cpp
UTF-8
794
2.984375
3
[]
no_license
#include <iostream> #include "Quadrate.h" #include "Rectangle.h" #include "Trapeze.h" using namespace std; int main(int argc, char** argv){ Figure *figure1 = new Quadrate(); figure1->Print(); std::cout << "Площадь квадрата:" << figure1->Square() << "\n"; delete figure1; std::cout << "______________________________\n\n"; Figure *figure2 = new Rectangle(); figure2->Print(); std::cout << "Площадь прямоугольника:" << figure2->Square() << "\n"; delete figure2; std::cout << "______________________________\n\n"; Figure *figure3 = new Trapeze(); figure3->Print(); std::cout << "Площадь трапеции:" << figure3->Square() << "\n"; delete figure3; std::cout << "______________________________\n\n"; return 0; }
true
f744291af6fa84248aec95feb5ef25f1efc05f43
C++
rafipriatna/Belajar-Bahasa-Pemrograman
/C++/Latihan/gantiVocal.cpp
UTF-8
1,449
4.03125
4
[ "MIT" ]
permissive
/* * Soal : Buatlah contoh program mengenai penerapan Fungsi * dan Procedure pada bahasa pemrograman C++. */ #include <iostream> #include <string> using namespace std; // Fungsi & prosedur void gantiVocal(string kata){ // Output cout << "Bimsalabim => "; // Mengganti vocal dari kata yang diinput user for (int i = 0; i < kata.length(); i++){ // Looping sebanyak panjang katanya if (kata[i] == 'a' || kata[i] == 'i' || kata[i] == 'u' || kata[i] == 'e' || kata[i] == 'o'){ // Jika katanya mengandung a, i, u, e, o // Ganti ke i kata[i] = 'i'; } cout << kata[i]; } cout << endl; // baris baru } int berapaHuruf(string kata) { // Deklarasi variabel int totalHuruf; // Berapa huruf pada kata totalHuruf = kata.length(); for (int i = 0; i < kata.length(); i++){ if (kata[i] == ' '){ totalHuruf -= 1; } } return totalHuruf; } int main(){ // Judul cout << "====== :: Program Ganti Vocal :: ======" << endl; // Deklarasi variabel string kata; // Input cout << "Masukkan kata : "; getline(cin, kata); // Supaya bisa baca spasi cout << endl; // baris baru // Prosedur gantiVocal(kata); // Fungsi cout << "Kata tersebut mengandung " << berapaHuruf(kata) << " huruf"; cout << endl; return 0; }
true
0b6fc7a4b5e7d6123ea9e9e4fbfc7743c10e529a
C++
flywind2/nextclade
/packages/nextclade/src/io/formatMutation.cpp
UTF-8
4,096
2.515625
3
[ "MIT" ]
permissive
#include "formatMutation.h" #include <fmt/format.h> #include <nextclade/nextclade.h> #include <nextclade/private/nextclade_private.h> #include <string> #include "utils/contract.h" namespace Nextclade { std::string formatRange(const Range& range) { precondition_less(range.begin, range.end); if (range.begin >= range.end) { return "empty range"; } // NOTE: we (and C++ standard library) uses 0-based half-open ranges, // but bioinformaticians prefer 1-based, closed ranges const auto beginOne = range.begin + 1; const auto endOne = range.end; if (endOne == beginOne) { return std::to_string(beginOne); } return fmt::format("{}-{}", beginOne, endOne); } std::string formatMutation(const NucleotideSubstitution& mut) { // NOTE: by convention, in bioinformatics, nucleotides are numbered starting from 1, however our arrays are 0-based const auto positionOneBased = mut.pos + 1; return fmt::format("{}{}{}", nucToString(mut.refNuc), positionOneBased, nucToString(mut.queryNuc)); } std::string formatDeletion(const NucleotideDeletion& del) { return formatRange(Range{.begin = del.start, .end = del.start + del.length}); } std::string formatInsertion(const NucleotideInsertion& insertion) { // NOTE: by convention, in bioinformatics, nucleotides are numbered starting from 1, however our arrays are 0-based const auto positionOneBased = insertion.pos + 1; const auto insertedSequence = toString(insertion.ins); return fmt::format("{}:{}", positionOneBased, insertedSequence); } std::string formatInsertions(const std::vector<NucleotideInsertion>& insertions) { return formatAndJoin(insertions, formatInsertion, ";"); } std::string formatMissing(const NucleotideRange& missing) { return formatRange({.begin = missing.begin, .end = missing.end}); } std::string formatNonAcgtn(const NucleotideRange& nonAcgtn) { const auto range = formatRange({.begin = nonAcgtn.begin, .end = nonAcgtn.end}); return fmt::format("{}:{}", nucToString(nonAcgtn.character), range); } std::string formatPcrPrimerChange(const PcrPrimerChange& primerChange) { const auto& name = primerChange.primer.name; const auto& muts = formatAndJoin(primerChange.substitutions, formatMutation, ";"); return fmt::format("{}:{}", name, muts); } std::string formatAminoacidMutationWithoutGene(const AminoacidSubstitution& mut) { // NOTE: by convention, in bioinformatics, aminoacids are numbered starting from 1, however our arrays are 0-based const auto codonOneBased = mut.codon + 1; const auto ref = aaToString(mut.refAA); const auto query = aaToString(mut.queryAA); return fmt::format("{}{}{}", ref, codonOneBased, query); } std::string formatAminoacidMutation(const AminoacidSubstitution& mut) { const auto& gene = mut.gene; const auto notation = formatAminoacidMutationWithoutGene(mut); return fmt::format("{}:{}", gene, notation); } std::string formatAminoacidDeletionWithoutGene(const AminoacidDeletion& del) { // NOTE: by convention, in bioinformatics, aminoacids are numbered starting from 1, however our arrays are 0-based const auto codonOneBased = del.codon + 1; const auto ref = aaToString(del.refAA); return fmt::format("{}{}-", ref, codonOneBased); } std::string formatAminoacidDeletion(const AminoacidDeletion& del) { const auto& gene = del.gene; const auto notation = formatAminoacidDeletionWithoutGene(del); return fmt::format("{}:{}", gene, notation); } std::string formatClusteredSnp(const ClusteredSnp& csnp) { const auto range = formatRange(Range{.begin = csnp.start, .end = csnp.end}); const auto numberOfSNPs = std::to_string(csnp.numberOfSNPs); return fmt::format("{}:{}", range, numberOfSNPs); } std::string formatFrameShift(const FrameShift& frameShift) { return frameShift.geneName; } std::string formatStopCodon(const StopCodonLocation& stopCodon) { return fmt::format("{}:{}", stopCodon.geneName, stopCodon.codon); } }// namespace Nextclade
true
658e0cab472106f89c8a0f89eed19e829c8fe976
C++
SamJia/Oj
/SJTU_OJ/1349.cpp
UTF-8
568
2.84375
3
[]
no_license
#include <iostream> using namespace std; #define SIZE 20 int row_number, colomn_number; char map[SIZE][SIZE] = {}; int result[SIZE][SIZE] = {}; int main(){ cin >> row_number >> colomn_number; for(int i = 0; i < row_number; ++i) cin >> map[i]; result[row_number-1][colomn_number-1] = 1; for(int i = row_number - 2; i >= 0; --i) for(int j = colomn_number - 2; j >= 0; --j){ for(int r = i + 1; r < row_number; ++r) for(int c = j + 1; c < colomn_number; ++c) if(map[i][j] != map[r][c]) result[i][j] += result[r][c]; } cout << result[0][0]; }
true
dfdfdbbcda0ce775b954fbfd91582316b0487e6a
C++
goog/Algorithms
/clang/cxx/google.class/composer/test_composer.cxx
UTF-8
429
2.546875
3
[]
no_license
/* * test_composer.cxx * * Copyright 2013 googcheng <googcheng@gmail.com> * * * */ #include <iostream> #include "composer.h" #include <string> using namespace std; int main () { cout << "Testing the Composer class." << endl; Composer composer; composer.set_name("Ludwig van"); composer.set_yob(1770); composer.set_rank(); cout << composer.getRank() << endl; composer.Promote(2); composer.Demote(1); composer.Display(); }
true
234cc72f29856fb0ea2626cc925ab68f8abaf1d3
C++
andrey-islentyev/Neuro-Game
/SFMLServer/server.cpp
UTF-8
8,016
2.796875
3
[]
no_license
#include <SFML/Network.hpp> #include <SFML/System.hpp> #include <iostream> #include <queue> #include <random> #include <string> #include <vector> #define GAME_START_TIME 10.0 #define PLAYER_MAX 8 //10 milliseconds for handling messages from players #define RECV_PHASE_TIMEOUT 10.0 //hard limit of messages per one game loop #define RECV_MSG_HARD_LIMIT 10 struct PlayerInfo; void pause() { std::cout.flush(); #ifdef _WIN32 system("pause"); #endif } enum RequestToClientType { ChangePlantState = 1 }; struct PlayerInfo { sf::TcpSocket authSocket; sf::UdpSocket sendSocket, recvSocket; sf::Uint16 sendPort, recvPort; std::string nickname; sf::IpAddress ipAddress; std::queue<sf::Packet> messages; sf::Socket::Status sendToUdp(sf::Packet &packet) { sf::Socket::Status status = sendSocket.send(packet, ipAddress, sendPort); return status; } sf::Socket::Status receiveFromUdp(sf::Packet &packet) { return recvSocket.receive(packet, ipAddress, recvPort); } }; struct Plant { double x, y; sf::Int8 state; sf::Uint8 type; sf::Uint64 id; sf::Clock clock; float deadline; static std::uniform_real_distribution<float> timeDistribution; static std::default_random_engine *engine; bool deadlinePassed() { if(state == 1) return false; return clock.getElapsedTime().asSeconds() > deadline; } void generateNewDeadline() { deadline = timeDistribution(*engine); } void changeState() { if (state == 0) state = 1; if (state == 2) state = 0; std::cout << "state = " << (int)(int8_t)state << "\n"; } void grow(PlayerInfo *players, size_t playersCount) { if (state != 1) { changeState(); notify(players, playersCount); } } void notify(PlayerInfo *players, size_t playersCount) { for (size_t i = 0; i < playersCount; ++i) { PlayerInfo &info = players[i]; sf::Packet packet; packet << sf::Uint8{ChangePlantState}; packet << id; packet << type; packet << state; packet << x; packet << y; sf::Socket::Status status; if((status = info.sendToUdp(packet)) != sf::Socket::Done){ std::cout << "Error. Can't send packet with plant update " << status << "\n"; pause(); exit(EXIT_FAILURE); } } } }; std::uniform_real_distribution<float> Plant::timeDistribution; std::default_random_engine *Plant::engine = nullptr; void giveIpHint() { sf::IpAddress localAddress = sf::IpAddress::getLocalAddress(); sf::IpAddress publicAddress = sf::IpAddress::getPublicAddress(); std::cout << "Local address: " << localAddress.toString() << "\n"; std::cout << "Public address: " << publicAddress.toString() << "\n"; std::cout << "What port to use?: "; } int main() { std::default_random_engine engine; Plant::engine = &engine; Plant::timeDistribution = std::uniform_real_distribution<float>(20.0, 50.0); giveIpHint(); uint16_t port; std::cin >> port; sf::TcpListener listener; sf::Socket::Status status = listener.listen(port); if (status != sf::Socket::Done) { std::cout << "Error: can't listen on this port\n"; pause(); return EXIT_FAILURE; } std::cout << "Listening on the port: " << listener.getLocalPort() << "\n"; uint64_t playersCount = 0; PlayerInfo playersInfo[PLAYER_MAX]; sf::Clock clock; listener.setBlocking(false); int prevSec = -1; while (playersCount != PLAYER_MAX) { int timeLeft = (int)(GAME_START_TIME - clock.getElapsedTime().asSeconds()); if (timeLeft <= 0 && playersCount >= 2) { break; } if (listener.accept(playersInfo[playersCount].authSocket) == sf::Socket::Done) { std::cout << "Player with id #" << playersCount << " connected\n"; playersInfo[playersCount].ipAddress = playersInfo[playersCount].authSocket.getRemoteAddress(); playersCount++; if (playersCount >= 2) { clock.restart(); } } if (timeLeft != prevSec) { prevSec = timeLeft; if (playersCount >= 2) { if (prevSec >= 60) { int minutes = prevSec / 60; int seconds = prevSec % 60; std::cout << minutes << "m " << seconds << "s" << "\n"; } if ((prevSec % 60 == 0 || prevSec == 20 || prevSec == 30 || prevSec == 10 || prevSec <= 5)) std::cout << timeLeft << "s left" << std::endl; } } } std::cout << "Game started\n"; for (size_t i = 0; i < playersCount; ++i) { if (playersInfo[i].sendSocket.bind(0) != sf::Socket::Done) { std::cout << "Can't open udp socket\n"; pause(); return EXIT_FAILURE; } if (playersInfo[i].recvSocket.bind(0) != sf::Socket::Done) { std::cout << "Can't open udp socket\n"; pause(); return EXIT_FAILURE; } sf::Uint16 sendPort = playersInfo[i].sendSocket.getLocalPort(); sf::Uint16 recvPort = playersInfo[i].recvSocket.getLocalPort(); sf::Packet packet; packet << sendPort; packet << recvPort; if (playersInfo[i].authSocket.send(packet) != sf::Socket::Done) { std::cout << "Can't send server UDP port data\n"; pause(); return EXIT_FAILURE; } } for (size_t i = 0; i < playersCount; ++i) { sf::Packet packet; if (playersInfo[i].authSocket.receive(packet) != sf::Socket::Done) { std::cout << "Can't recieve client UDP port data\n"; pause(); return EXIT_FAILURE; } packet >> playersInfo[i].sendPort; packet >> playersInfo[i].recvPort; packet >> playersInfo[i].nickname; playersInfo[i].recvSocket.setBlocking(false); playersInfo[i].sendSocket.setBlocking(false); } for (size_t i = 0; i < playersCount; ++i) { std::cout << "#" << i << " nickname: " << playersInfo[i].nickname << "\n"; } //game state std::map<size_t, Plant> plants; double minx = 100; double miny = 100; double maxx = 400; double maxy = 400; std::uniform_real_distribution<double> xDistribution(minx, maxx); std::uniform_real_distribution<double> yDistribution(miny, maxy); std::uniform_int_distribution<int> typeDistribution(0, 6); for (size_t i = 0; i < 20; ++i) { plants[i].x = xDistribution(engine); plants[i].y = yDistribution(engine); plants[i].type = typeDistribution(engine); plants[i].id = i; plants[i].state = 2; plants[i].generateNewDeadline(); plants[i].notify(playersInfo, playersCount); } sf::Clock phaseClock; while (true) { phaseClock.restart(); //recieve packets stage while (phaseClock.getElapsedTime().asMilliseconds() <= RECV_PHASE_TIMEOUT) { for (size_t i = 0; i < playersCount; ++i) { sf::Packet packet; if (playersInfo[i].messages.size() >= RECV_MSG_HARD_LIMIT) { continue; } if (playersInfo[i].receiveFromUdp(packet) == sf::Socket::Done) { playersInfo[i].messages.push(packet); } } } //game update stage. for (size_t i = 0; i < plants.size(); ++i) { if (plants[i].deadlinePassed()) { plants[i].grow(playersInfo, playersCount); plants[i].generateNewDeadline(); std::cout << "State update\n"; } } //clear all queues for (size_t i = 0; i < playersCount; ++i) { while (!playersInfo[i].messages.empty()) { playersInfo[i].messages.pop(); } } } pause(); }
true
1df3d7de57c34a57764ca163328b408cbaeda13c
C++
Dibbo-56/cpp-programming
/Teach_Yourself_C++/chapter 4/4.4_2.cpp
UTF-8
411
3.265625
3
[]
no_license
#include <iostream> #include <cstring> using namespace std; class info{ char name[20],tele[15]; public: void set_nl(char nam[], char tel[]){ strcpy(name,nam); strcpy(tele,tel); } void show(){ cout<< name << " " << tele << endl; } }; int main() { info *p; p = new info; p->set_nl("Narwal","01234567789"); p->show(); delete p; return 0; }
true
8fee36458a364745b4e9cccd7392542dcc1cd822
C++
hchencn/leetcode
/best_time_to_buy_and_sell_stock_3.cc
UTF-8
1,060
2.875
3
[]
no_license
class Solution { public: int maxProfit(vector<int> &prices) { int len = prices.size(); if(len <= 1) return 0; vector<int> maxl(len, 0); vector<int> maxr(len, 0); int min = INT_MAX, max = INT_MIN; for(int i = 0; i < len; i++) { if(min > prices[i]) min = prices[i]; int tmp = prices[i] - min; if(tmp > max) max = tmp; maxl[i] = max; } int max1 = INT_MIN, max2 = INT_MIN; for(int i = len-1; i >= 0; i--) { if(max1 < prices[i]) max1 = prices[i]; int tmp = max1 - prices[i]; if(tmp > max2) max2 = tmp; maxr[i] = max2; } int maxp = INT_MIN; for(int i = 0; i < len-1; i++) { int sum = maxl[i] + maxr[i+1]; maxp = sum > maxp? sum:maxp; } if(maxp < maxl[len-1]) maxp = maxl[len-1]; return maxp; } };
true
01fd7484a1c48bbc1cabfa8806543657c1d6a005
C++
MohdImran001/dsa
/activity-selection.cpp
UTF-8
574
2.84375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; bool compare(pair<int, int> a, pair<int, int> b) { return a.second < b.second; } int main() { int t, n, s, e; vector<pair<int, int>> arr; cin >> t; while(t--) { cin >> n; for(int i=0; i<n; ++i) { cin >> s >> e; arr.push_back(make_pair(s, e)); } sort(arr.begin(), arr.end(), compare); int ans = 1; int finishTime = arr[0].second; for(int i=1; i<n; ++i) { if(arr[i].first > finishTime) { finishTime = arr[i].second; ans++; } } cout << ans << endl; arr.clear(); } return 0; }
true
4c7d252b922a47b3b455aa203e03f270d09e0841
C++
GJ-Lin/SJTUOJ
/4219.cpp
UTF-8
942
2.84375
3
[]
no_license
#include <iostream> #include <cstdio> using namespace std; const int MAXNUM = 300005; const int P = 1e9 + 7; int T, n; int arr[MAXNUM]{0}; void quicksort(int *arr, int low, int high) { if (low >= high) return; int k = arr[low], tmp; int lf = low, rh = high; while (lf < rh) { while (arr[rh] <= k && lf < rh) --rh; while (arr[lf] >= k && lf < rh) ++lf; if (lf < rh) { tmp = arr[rh]; arr[rh] = arr[lf]; arr[lf] = tmp; } } arr[low] = arr[lf]; arr[lf] = k; quicksort(arr, low, lf - 1); quicksort(arr, rh + 1, high); } int main() { arr[0] = 0; scanf("%d%d", &T, &n); for (int i = 1; i <= n; ++i) scanf("%d", &arr[i]); quicksort(arr, 1, n); for (int i = 1; i <= n; ++i) { arr[i] = (arr[i] + arr[i - 1]) % P; } int k; for (int i = 1; i <= T; ++i) { scanf("%d", &k); printf("%d\n", arr[k]); } return 0; }
true
4a680a34564929313b9304aad55731fc7ad367bf
C++
mihirbshah/algorithms
/src/diagonal_traverse_II.cpp
UTF-8
1,244
3.421875
3
[]
no_license
// 1424. Diagonal Traverse II #include <iostream> #include <vector> #include "util.h" #include <algorithm> using namespace std; // Solution gets TLEed // For O(m.n) solution, refer - https://leetcode.com/problems/diagonal-traverse-ii/discuss/597698/JavaC%2B%2B-HashMap-with-Picture-Clean-code-O(N) class Solution { public: vector<int> findDiagonalOrder(vector<vector<int>>& nums) { const int m = nums.size(); int n = 0; for (const auto& num : nums) n = max(n, (int)num.size()); vector<int> res; for (int r = 0; r < m; ++r) { for (int c = 0; c < (r == m - 1 ? n : 1); ++c) { int i = r, j = c; while (i >= 0 && j < n) { if (j < nums[i].size()) res.push_back(nums[i][j]); --i; ++j; } } } return res; } }; int main() { //vector<vector<int>> v({{1,2,3,4,5},{6,7},{8},{9,10,11},{12,13,14,15,16}}); vector<vector<int>> v({{1,2,3,4,5,6}}); Solution o; vector<int> res = o.findDiagonalOrder(v); cout << "res: " << stringify_container(res.begin(), res.end()) << "\n"; return 0; }
true
b347af58ddceefe61d4b7134357b62405a92ba53
C++
BioPP/bpp-phyl-example
/ExPhylo/ExPhylo.cpp
UTF-8
8,524
2.71875
3
[]
no_license
/* * File: ExPhylo.cpp * Created by: Julien Dutheil * Created on: Dec Wed 10 17:10 2008 * Last modified: Jan Wed 11 09:21 2012 * * Introduction to the classes and tools for phylogenetics. * * HOW TO USE THAT FILE: * - General comments are written using the * * syntax. * - Code lines are switched off using '//'. To activate those lines, just remove the '//' characters! * - You're welcome to extensively modify that file! */ /*----------------------------------------------------------------------------------------------------*/ /* * We start by including what we'll need, and sort the inclusions a bit: */ /* * From the STL: */ #include <iostream> //to be able to output stuff in the terminal. /* * We'll use the standard template library namespace: */ using namespace std; /* * From Bpp-Seq: */ #include <Bpp/Seq/Alphabet/AlphabetTools.h> /* this includes all alphabets in one shot */ #include <Bpp/Seq/Container/VectorSiteContainer.h> #include <Bpp/Seq/Container/SiteContainerTools.h> #include <Bpp/Seq/Io/Fasta.h> /* * From Bpp-Phyl: */ #include <Bpp/Phyl/Tree.h> /* this includes classes for tree manipulations */ #include <Bpp/Phyl/TreeTools.h> #include <Bpp/Phyl/Io/Newick.h> #include <Bpp/Phyl/Model/Nucleotide/K80.h> #include <Bpp/Phyl/Model/RateDistribution/ConstantRateDistribution.h> #include <Bpp/Phyl/Distance/DistanceEstimation.h> #include <Bpp/Phyl/Distance/BioNJ.h> #include <Bpp/Phyl/Likelihood/NNIHomogeneousTreeLikelihood.h> #include <Bpp/Phyl/OptimizationTools.h> #include <Bpp/Phyl/Simulation/HomogeneousSequenceSimulator.h> /* * All Bio++ functions are also in a namespace, so we'll use it: */ using namespace bpp; /*----------------------------------------------------------------------------------------------------*/ /* * Now starts the real stuff... */ int main(int args, char ** argv) { /* * We surround our code with a try-catch block, in case some error occurs: */ try { cout << "Hello World!" << endl; /* * In this exercise we're going to work with models. * This mostly concerns distance-based and maximum likelihood methods. */ /* * An important class in Bio++ Phylogenetic Library (PhylLib) is the SubstitutionModel class. * It describes the model of transitions between nucleotides, amino-acids or codons. * It is hence in tight connection with the Alphabet classes we saw before. * * Here is how it works. We will create a new instance of Kimura's 2 parameter model: */ SubstitutionModel* model = new K80(&AlphabetTools::RNA_ALPHABET, 2.5); //SubstitutionModel* model = new JCnuc(&AlphabetTools::RNA_ALPHABET); /* * SubstitutionModel objects are quite complexe. To keep things short: * - They implement the Parametrizable interface, which basically means that they have Parameter * objects that can be retrieved and modified. * - They compute the probabilities of transition between all states in the alphabet. * You can give a look at the documentation for classes SubstitutionModel, Parametrizable, ParameterList and Parameter. * Then try the following: */ cout << "This model has " << model->getNumberOfStates() << " states." << endl; ParameterList pl = model->getParameters(); cout << "This model has " << pl.size() << " parameters." << endl; pl.printParameters(cout); //pl.getParameter("K80.kappa").setValue(1); pl.printParameters(cout); /* Apply the parameter change: */ //model->setParametersValues(pl); /* And what about that? */ //pl.getParameter("K80.kappa").setValue(-1); /* INFO: The prefix "K80." is the namespace of the parameters, to avoid confusion when more complicated models are used. * Parameter values can also be directly accessed using: */ //cout << model->getParameterValue("kappa") << endl; /* This syntax is then independent of the namespace used. */ double t = 0.1; for(int i = 0; i < (int)model->getNumberOfStates(); i++) { for(int j = 0; j < (int)model->getNumberOfStates(); j++) { cout << "Probability of change from "; cout << model->getAlphabet()->intToChar(i) << " to "; cout << model->getAlphabet()->intToChar(j) << " is "; cout << model->Pij_t(i, j, t) << " for a branch of length "; cout << t << endl; } } /* ---------------- * QUESTION 1: Verify that the sum over of all Pij_t is equal to 1! * ---------------- */ /* * Another important set of objects are ones implementing the DiscreteDistribution interface. * They are also Parametrizable object, and so share a lot of methods with SubstitutionModel objects. * They are used here for modeling rate across site heterogeneity, but we will consider a Constant distribution for now: */ DiscreteDistribution* rateDist = new ConstantRateDistribution(); /* * We wil now use these models to build a distance matrix and a BioNJ tree: */ Fasta seqReader; SequenceContainer* sequences = seqReader.readSequences("SSU.fasta", &AlphabetTools::RNA_ALPHABET); SiteContainer* sites = new VectorSiteContainer(*sequences); delete sequences; cout << "There are " << sites->getNumberOfSites() << " positions in the alignment." << endl; SiteContainerTools::removeGapOnlySites(*sites); cout << "There are " << sites->getNumberOfSites() << " positions in the alignment that are not only made of gaps." << endl; SiteContainerTools::changeGapsToUnknownCharacters(*sites); cout << "Computing distance matrix..." << endl; DistanceEstimation distanceMethod(model, rateDist, sites); cout << endl; /* * Now we retrieve the computed distances: */ DistanceMatrix* distances = distanceMethod.getMatrix(); /* * Now we will build a BioNJ tree: */ cout << "Computing tree..." << endl; BioNJ bionj(*distances); cout << endl; Tree* tree = bionj.getTree(); /* * And write it to a file: */ Newick treeWriter; treeWriter.write(*tree, "SSU_BioNJ.dnd"); /* ---------------- * QUESTION 2: Modify the previous code in order to build a tree with a Tamura 92 model and a gamma distribution for substitution rates. * ---------------- */ /* * We will now use that tree to build a Maximum Likelihood tree. */ NNIHomogeneousTreeLikelihood* tl = new NNIHomogeneousTreeLikelihood(*tree, *sites, model, rateDist); tl->initialize(); cout << "Log likelihood before: " << tl->getLogLikelihood() << endl; tl = OptimizationTools::optimizeTreeNNI(tl, tl->getParameters(), true, 100, 0.000001, 300, 1, 0, 0, false, 3); cout << "Log likelihood after: " << tl->getLogLikelihood() << endl; tl->getParameters().printParameters(cout); TreeTemplate<Node> mlTree(tl->getTree()); treeWriter.write(mlTree, "SSU_ML.dnd"); /* ---------------- * QUESTION 3: Compare various models on this data set, for instance K80, HKY85, GTR +/- Gamma. * Tip: In class RandomTools (Bpp/Numeric/Random), there are tools to deal with a chi2 distribution... * ---------------- */ /* * Last but not least, we will now simulate data from the estimated model: */ TreeTemplate<Node>* mlTreeTT = new TreeTemplate<Node>(mlTree); HomogeneousSequenceSimulator* simulator = new HomogeneousSequenceSimulator(model, rateDist, mlTreeTT); size_t numberOfSites = 500; SiteContainer* simSites = simulator->simulate(numberOfSites); Fasta seqWriter; seqWriter.writeAlignment("Simulations.fasta", *simSites); /* ---------------- * QUESTION 4: Assess some properties of the model using simulations (parametric bootstrap) * * Simulate a hundred sites using a previously fitted GTR+Gamma model, * then reestimate a tree and model parameters on the simulated data set. * Then compute the mean and variance of the estimates obtained, and compare to the real values. * * BONUS QUESTION 1: compare results between a parametric and a non-parametric boostrap. * BONUS QUESTION 2: also compute the consensus tree with bootstrap values (browse the documentation first!) * ---------------- */ } catch(Exception& e) { cout << "Bio++ exception:" << endl; cout << e.what() << endl; return 1; } catch(exception& e) { cout << "Any other exception:" << endl; cout << e.what() << endl; return 1; } return 0; }
true
e63b2c29c521b9671a3e58b0aa7705ec0d5cf401
C++
quocnguyenx43/data-structure-algorithm
/data_structure_algorithms/graph/dfs_bfs/dfs.cpp
UTF-8
2,092
3.390625
3
[]
no_license
#include "../_library_graph_.h" // DFS // Độ phức tạp: // - Time: O(V * E) (Danh sách kề) // - Time: O(V^2) (Ma trận trọng số) void DFS_UseRecursion(Graph &g, Index vertex) { // In ra đỉnh vertex và đánh dấu đã đi qua g.vertices[vertex].visited = YES; cout << g.vertices[vertex].lable << " "; Index nextVertex; while (true) { // Tìm đỉnh cạnh kế tiếp nextVertex = FindAdjacentVertex(g, vertex); if (nextVertex == NULLINDEX) { break; } else { // Gọi lại đệ quy DFS_UseRecursion(g, nextVertex); } } } void DFS_UseStack(Graph &g, Index vertex) { // Tạo ra 1 cái stack<int> để lưu các đỉnh theo Index stack<Index> s; s.push(vertex); // In ra đỉnh vertex và đánh dấu đã đi qua cout << g.vertices[vertex].lable << " "; g.vertices[vertex].visited = YES; // Using stack Index currentVertex; Index nextVertex; while (true) { // Lấy thằng top ra & pop currentVertex = s.top(); // Tìm next của current nextVertex = FindAdjacentVertex(g, currentVertex); // Check if (nextVertex == NULLINDEX) { s.pop(); if (s.empty()) { break; } } else { // In ra thằng next và push lại vào trong cout << g.vertices[nextVertex].lable << " "; g.vertices[nextVertex].visited = YES; s.push(nextVertex); } } } // Start void Start(Graph g) { system("cls"); cout << "========== DFS ==========\n"; cout << "===== Press to start ====\n\n"; cout << "Press anything: "; char choose; cin >> choose; cin.ignore(); system("cls"); ResetVertex(g); OutputMatrixCost(g); cout << "DFS: "; DFS_UseRecursion(g, 0); cout << endl; system("pause"); } int main() { Graph g; Initialize(g, true); InputGraph(g, "../graph.txt"); Start(g); return 0; }
true
daae1df6fbe986d784c6a0aeac55075a6de69052
C++
intoyuniot/RGBmatrixPanel
/examples/testcolors_16x32/testcolors_16x32.ino
UTF-8
1,116
2.578125
3
[ "MIT" ]
permissive
#include <RGBmatrixPanel.h> #include <math.h> #define CLK D6 #define OE D7 #define LAT A4 #define A A0 #define B A1 #define C A2 RGBmatrixPanel matrix(A, B, C, CLK, LAT, OE, false); void setup() { matrix.begin(); uint8_t r=0, g=0, b=0; // 画上半部分 for (uint8_t x=0; x < 32; x++) { for (uint8_t y=0; y < 8; y++) { matrix.drawPixel(x, y, matrix.Color333(r, g, b)); r++; if (r == 8) { r = 0; g++; if (g == 8) { g = 0; b++; } } } } // 画下半部分 for (uint8_t x=0; x < 32; x++) { for (uint8_t y=8; y < 16; y++) { matrix.drawPixel(x, y, matrix.Color333(r, g, b)); r++; if (r == 8) { r = 0; g++; if (g == 8) { g = 0; b++; } } } } } void loop() { }
true
e4097e25ed828d42fdc780229e88992d74590c93
C++
WolodjaZ/sdizo
/part_2/PriorityQueue.h
UTF-8
901
2.859375
3
[]
no_license
// // Created by vladimir on 11.04.19. // #ifndef PART_2_PRIORITYQUEUE_H #define PART_2_PRIORITYQUEUE_H #include "Edge.h" #include <iostream> // Działanie PriorityQueue opiera się na kopcu gdzie na szczczycie jest minimalna liczba // kopiec działa na obiektach klasy Edge gdzie wartość bierze ze zmiennej weigth class PriorityQueue { private: Edge* root; int size; int actual_size; public: PriorityQueue(int size); ~PriorityQueue(); Edge first(); void push(Edge edge); void pop(); bool is_Empty(); // jedyna metoda objaśniona w cpp jako iż poprzednie metody były objaśnione w poprzednim projekcie void change_neighbours(int vertex, int value, int change_vertex); void print(); private: void queue_fix_up(int index); void queue_fix_down(int index); void print_helper(int index, int c); }; #endif //PART_2_PRIORITYQUEUE_H
true
9b0f9dbba9dab541db8a37c7d32cd9ac7d554a5e
C++
Manvikaul/coding-practice
/Palindrome number.cpp
UTF-8
314
2.796875
3
[]
no_license
//leetcode class Solution { public: bool isPalindrome(int x) { string s=to_string(x); for(int i=0;i<s.length()/2;i++) { if(s[i]!=s[s.length()-i-1]) { return false; } } return true; } };
true
eaf84a3d9232c6745e70fe7956fd72fc12c90e20
C++
machinamentum/htn
/src/Code_Structure.h
UTF-8
3,371
2.90625
3
[]
no_license
#ifndef CODE_STRUCTURE_H #define CODE_STRUCTURE_H #include <string> #include <vector> #include <cstdint> struct Variable { enum VType { DQString, VOID, CHAR, INT_8BIT, INT_16BIT, INT_32BIT, INT_64BIT, FLOAT_32BIT, POINTER, DEREFERENCED_POINTER, UNKNOWN }; std::string name; std::string dqstring; VType type; VType ptype; //used when type is a pointer intptr_t pvalue; float fvalue; bool is_type_const = false; bool is_ptype_const = false; }; struct Scope; struct Function { std::string name; std::vector<Variable> parameters; Scope *scope = nullptr; bool should_inline = false; bool plain_instructions = false; bool is_not_definition = false; Variable return_info; Function(); }; struct Conditional { enum CType { EQUAL, GREATER_THAN, LESS_THAN, GREATER_EQUAL, LESS_EQUAL }; Variable left; CType condition; Variable right; bool is_always_true = false; }; struct Instruction { enum IType { FUNC_CALL, SUBROUTINE_JUMP, //used mainly for loops ASSIGN, INCREMENT, BIT_OR }; IType type; std::string func_call_name; std::vector<Variable> call_target_params; Variable lvalue_data; Variable rvalue_data; bool is_conditional_jump = false; Conditional condition; }; struct Expression { std::vector<Instruction> instructions; /** * holds the variable data of the destination variable or * (in the case of a return) the data of a temporary, or const, * that the expression will evaluate to. */ Variable return_value; Scope *scope = nullptr; Expression(); }; struct Scope { std::vector<Function> functions; std::vector<Expression> expressions; std::vector<Variable> variables; //std::vector<Scope *> children; Scope *parent = nullptr; bool is_function = false; Function *function; Scope(Scope *p = nullptr) { parent = p; } bool contains_symbol(const std::string name) { for (auto& f : functions) { if (f.name.compare(name) == 0) { return true; } } for (auto &f : variables) { if (f.name.compare(name) == 0) { return true; } } return (parent ? parent->contains_symbol(name) : false); } Function *getFuncByName(const std::string name) { for (auto &f : functions) { if (f.name.compare(name) == 0) { return &f; } } return (parent ? parent->getFuncByName(name) : nullptr); } Variable *getVarByName(const std::string name) { for (auto &f : variables) { if (f.name.compare(name) == 0) { return &f; } } for (auto &func : functions) { for (auto &f : func.parameters) { if (f.name.compare(name) == 0) { return &f; } } } if (is_function) { for (auto &f : function->parameters) { if (f.name.compare(name) == 0) { return &f; } } } return (parent ? parent->getVarByName(name) : nullptr); } bool empty() { return !functions.size() && !expressions.size(); } }; #endif
true
e053243386e031b584c25286e535e256b4f1daf5
C++
cyberwizard1001/advanced_programming
/Cpp/cpp/30th August 2020/Q1.cpp
UTF-8
505
3.71875
4
[]
no_license
#include<iostream> using namespace std; class volume{ int side; int vol; void calc_vol() { vol = side*side*side; } public: volume() { side = 1; vol = 1; } volume(int i) { side = i; vol = 1; } int ret_vol() { calc_vol(); return vol; } }; int main() { volume obj; cout << "Default constructor volume: "<< obj.ret_vol(); volume obj1(5); cout << endl << "Parameterized constructor with side = 5 passed: " << obj1.ret_vol(); return 0; }
true
a89074a94d941974e28ce4a6854550d53c4e01c7
C++
ivanovdimitur00/programs
/Programs/zadachi praktikum 4/sum_proizvedenie_doNula.cpp
UTF-8
344
3.046875
3
[]
no_license
#include <iostream> int main() { int number; int sum = 0; int mult = 1; do { std::cin>>number; if (number == 0) { break; } sum += number; mult *= number; } while (number != 0); std::cout<<"sum = "<<sum<<"\n"; std::cout<<"mult = "<<mult<<"\n"; system("pause"); return 0; }
true
e6e63fc101b2ee10e07fad548395629503d14dbf
C++
wangdejun/C-introduction
/practice/2016-8-2(4)-files and structs.cpp
UTF-8
590
3.1875
3
[]
no_license
struct statsT{ int low; int high; double average; } statsT CalculateStatistics(string filename){ statsT stats; stats.low = 101; stats.high = -1; int total = 0; int count = 0; //open a file and makesure it worked ifstream in; in.open(filename.c_str()); if(in.fail()) Error("Could not read"+filename); while(true){ int num; in>>num; //check that we read good if(in.fail()) break; if(num<stats.low) stats.low = num;; if(num>stats.high) stats.high = num; total += num; count++; } stats.average = double(total)/count; in.close(); return false; }
true
f5eb576160fa023d8f1e351e687d441db4afdc3f
C++
WhiZTiM/coliru
/Archive2/97/0416bf9b5df1ec/main.cpp
UTF-8
542
2.796875
3
[]
no_license
#include <iostream> #include <iomanip> #include <string> #include <map> #include <boost/random.hpp> int main() { boost::mt19937 e2; boost::normal_distribution<> dist(70, 10); std::map<int, int> hist; for (int n = 0; n < 100000; ++n) { ++hist[round(dist(e2))]; } for ( std::map<int, int>::const_iterator i = hist.begin(); i != hist.end(); ++i ) { std::cout << std::fixed << std::setprecision(1) << std::setw(2) << i->first << ' ' << std::string(i->second/200, '*') << '\n'; } }
true
7d3a36440e62946aba66fbcf2c4cefa27799db6c
C++
lyb1234567/C-plus-plus-
/C++ primer plus/第九章/9.4/9.4/ns_f.cpp
UTF-8
1,435
3.046875
3
[]
no_license
#include<iostream> #include"ns.h" namespace SALES { void setsales(Sales& s, const double ar[], int n = QUARTERS) { double sum = 0; s.max = -99999999; s.min = 99999999; for (int i = 0; i < n + 1; ++i) { s.sales[i] = ar[i]; sum += s.sales[i]; s.max = ar[i] > s.max ? ar[i] : s.max; s.min = ar[i] < s.min ? ar[i] : s.min; } s.average = sum / n; } void setsales(Sales& s) { s.max = -99999999; s.min = 99999999; std::cout << "please input the array size: "; int sum = 0; int n; std::cin >> n; std::cout << "please input the data: "; for (int i = 0; i < n; ++i) std::cin >> s.sales[i], sum += s.sales[i]; for (int i = 0; i < n; ++i) { s.max = s.sales[i] > s.max ? s.sales[i] : s.max; s.min = s.sales[i] < s.min ? s.sales[i] : s.min; } s.average = sum / n; } void showsales(const Sales& s) { std::cout << "*****the info*****\n"; std::cout << "the sales:" << std::endl; for (int i = 0; i<(sizeof(s.sales)/sizeof(s.sales[0])); ++i) std::cout << s.sales[i] << "\t\n"; std::cout << "the average: " << s.average << "\n"; std::cout << "the min: " << s.min << "\n"; std::cout << "the max: " << s.max << "\n"; } }
true
f90bbb6714e9bc9221861ccbc9d24e943b7acf19
C++
kulakowskin/SHUNT
/Sqrt.cpp
UTF-8
1,187
2.9375
3
[]
no_license
#include <cstring> #include <string> #include <cmath> #include <sstream> #include <stdlib.h> #include "Sqrt.h" Sqrt::Sqrt(){ this->in = 0; } Sqrt::Sqrt(string expression){ this->expression = strstr((char*)expression.c_str(),expression.c_str()); parseNumbers(); } float Sqrt::getIn(){ return this->in; } string Sqrt::simRoots(){ this->factor_c = 0; this->mf = this->in/2; for(int i = this->mf; i > 0; i--) { if((this->in / i) == int(this->in / i)) { if(sqrt(this->in / i) == int(sqrt(this->in / i))) { this->multiplier = sqrt(this->in / i); this->radicand = this->in / (this->in / i); this->factor_c++; } } } if (this->factor_c > 0) { if (this->radicand == 1) { stringstream bb; bb << this->multiplier; return "( " + bb.str() + " )"; } else { stringstream ss; ss << this->multiplier; stringstream bb; bb << this->radicand; return "( " + ss.str() + " * sqrt:" + bb.str() + " )"; } } else { stringstream ss; ss << this->in; return "( sqrt:" + ss.str() + " )"; } } void Sqrt::parseNumbers(){ char* p; p = strtok(this->expression,"sqrt:"); this->in = atoi(p); }
true
933241d58935aa381c893d696affe57cafe8f531
C++
CiQiong/PAT
/平衡二叉树AVL.cpp
GB18030
2,741
3.9375
4
[]
no_license
#include<cstdio> #include<algorithm> #include<cmath> using namespace std; //ƽ struct node{ int v,height;//vΪȨֵheightΪǰ߶ node *lchild,*rchild;//Һӽڵַ }; //һ½㣬vΪȨֵ node* newNode(int v){ node* Node=new node;//һnodeͱĵַռ Node->v=v; Node->height=1; Node->lchild=Node->rchild=NULL; return Node; } //ȡrootΪĵǰheight int getHeight(node* root){ if(root==NULL)return 0; return root->height; } //rootƽ int getBalanceFactor(node* root){ //߶ȼ߶ return getHeight(root->lchild)-getHeight(root->rchild); } //½ӽrootheight void updateHeight(node* root){ //max(ӵheightкӵheight)+1 root->height=max(getHeight(root->lchild),getHeight(root->rchild)+1); } // //һ¼ÿȨֵͬ // //searchAVLΪxĽ void search(node* root,int x){ if(root==NULL){//ʧ printf("search failed\n"); return ; } if(x==root->v){//ҳɹ֮ printf("%d\n",root->v); }else if(x<root->v){ search(root->lchild,x); }else{ search(root->rchild,x); } } // //(Left Rotation) void L(node* &root){ node* temp=root->rchild; root->rchild=temp->lchild; temp->lchild=root; updateHeight(root);//¸߶ updateHeight(temp);//¸߶ root=temp; } //(Right Rotatio) void R(node* &root){ node* temp=root->lchild; root->lchild=temp->rchild; temp->rchild=root; updateHeight(root);//¸߶ updateHeight(temp);//¸߶ root=temp; } //ȨֵΪvĽ void insert(node* &root,int v){ if(root==NULL){//ս root=newNode(v); return; } if(v<root->v){//vȸȨֵС insert(root->lchild,v);// updateHeight(root);// if(getBalanceFactor(root)==2){ if(getBalanceFactor(root->lchild)==1){//LL R(root); }else if(getBalanceFactor(root->lchild)==-1){//LR L(root->lchild); R(root); } } } else { //vȸȨֵ insert(root->rchild,v);// updateHeight(root);// if(getBalanceFactor(root)==-2){ if(getBalanceFactor(root->rchild)==-1){//RR L(root); }else if(getBalanceFactor(root->rchild)==1){//RL R(root->rchild); L(root); } } } } //AVLĽ node* Create(int data[],int n){ node* root=NULL;//½ոroot for(int i=0;i<n;i++){ insert(root,data[i]);//data[0]~data[n-1]AVL } return root;//ظ } int main(){ return 0; }
true
8f0d362b711d1d278a49b945a26788e865ef2a2d
C++
Vdupendant/incendie
/outils.cpp
UTF-8
2,009
2.96875
3
[]
no_license
#include "outils.h" using namespace outils; // On initialise la taille du terrain int C=0; int L=0; // On créer ensuite deux plans en miroir int**PLAN; int**MIROIR; const int MAXI = 1000; const float SEUIL = 0.6*MAXI; // Les différentes valeurs possibles enum Types { ARBRE, TERRE, EAU, FEU, CENDRE, CETEINTE }; void dimension_console(void); void creer_matrices(void); void detruire__matrices(void); void init_bois(void); void affiche_plan(void); void mem_affiche_plan(void); void dimension_console() { cout << "Entrez largeur fenetre :" << endl; cin >> C; cout << "Entrez Hauteur fenetre :" << endl; cin >> L; // une taille minimum C = (C < 10) ? 10 : C; L = (L < 10) ? 10 : L; O_ConsoleResize(C, L); } void creer_matrices() { PLAN = new int*[L]; MIROIR = new int*[L]; for (int y = 0; y < L; y++) { PLAN[y] = new int[C]; MIROIR[y] = new int[C]; } } // Destruction des deux matrices void detruire__matrices() { for (int y = 0; y < L; y++) { delete[] PLAN[y]; delete[] MIROIR[y]; } delete[] PLAN; delete[] MIROIR; } void init_bois() { int x, y; for (y = 0; y<L; y++) for (x = 0; x<C; x++) { if ((rand() % MAXI)<SEUIL) PLAN[y][x] = ARBRE; else if PLAN[y][x] = TERRE; else PLAN[y][x] = EAU; } } // Affichage void affiche_plan() { int y, x; for (y = 0; y<L; y++) { for (x = 0; x<C; x++) { switch (PLAN[y][x]) { case ARBRE: O_Textcolor(6 * 16); break; case TERRE: O_Textcolor(7 * 16); break; case FEU: O_Textcolor(12 * 16); break; case CENDRE: O_Textcolor(2 * 16); break; case CETEINTE: O_Textcolor(0); break; } O_Gotoxy(x, y); putchar(' '); } } }
true
4552e210b85309bedcb5d3692ad5a79b127b2314
C++
arsh317/Data-stuctures-and-Algo
/Graphs/Shortest Distance in a Maze.cpp
UTF-8
2,960
3.4375
3
[]
no_license
/* Shortest Distance in a Maze Given a matrix of integers A of size N x M describing a maze. The maze consists of empty locations and walls. 1 represents a wall in a matrix and 0 represents an empty location in a wall. There is a ball trapped in a maze. The ball can go through empty spaces by rolling up, down, left or right, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction. Given two array of integers of size B and C of size 2 denoting the starting and destination position of the ball. Find the shortest distance for the ball to stop at the destination. The distance is defined by the number of empty spaces traveled by the ball from the starting position (excluded) to the destination (included). If the ball cannot stop at the destination, return -1. Note: Rows are numbered from top to bottom and columns are numbered from left to right. Assume the border of the maze are all walls. Both the starting position of the ball and the destination position of the ball exist on an empty space. Both the starting and destination positions will not be at the same position initially. */ struct node { int i,j,lv; char pr; node(int a,int b, int c,char ch) { i=a; j=b; lv=c; pr=ch; } }; int Solution::solve(vector<vector<int> > &A, vector<int> &B, vector<int> &C) { int n=A.size(),m=A[0].size(); vector<vector<int> > ans(n,vector<int>(m,0)); queue< node > q; node x(B[0],B[1],0,'s'); q.push(x); while(!q.empty()) { node p=q.front(); q.pop(); int i=p.i; int j=p.j; int lv=p.lv; char pr=p.pr; ans[i][j]=lv; int dc=0; if(pr=='s'){ dc=1; } else if(pr=='r' && (j-1<0 || A[i][j-1]==1)){ dc=1; } else if(pr=='l' && (j+1>=m || A[i][j+1]==1)){ dc=1; } else if(pr=='t' && (i+1>=n || A[i+1][j]==1)){ dc=1; } else if(pr=='d' && (i-1<0 || A[i-1][j]==1)){ dc=1; } else{ dc=0; } if(dc==0) { if(pr=='r' && A[i][j-1]!=2){ node t(i,j-1,lv+1,'r'); q.push(t); } if(pr=='l' && A[i][j+1]!=2){ node t(i,j+1,lv+1,'l'); q.push(t); } if(pr=='t' && A[i+1][j]!=2){ node t(i+1,j,lv+1,'t'); q.push(t); } if(pr=='d' && A[i-1][j]!=2){ node t(i-1,j,lv+1,'d'); q.push(t); } } else { A[i][j]=2; if(i==C[0] && j==C[1]){ return lv; } if(i-1>=0 && A[i-1][j]!=1 && A[i-1][j]!=2 && pr!='t'){ node t(i-1,j,lv+1,'d'); q.push(t); } if(i+1 <n && A[i+1][j]!=1 && A[i+1][j]!=2 && pr!='d'){ node t(i+1,j,lv+1,'t'); q.push(t); } if(j-1>=0 && A[i][j-1]!=1 && A[i][j-1]!=2 && pr!='l'){ node t(i,j-1,lv+1,'r'); q.push(t); } if(j+1 <m && A[i][j+1]!=1 && A[i][j+1]!=2 && pr!='r'){ node t(i,j+1,lv+1,'l'); q.push(t); } } } return -1; }
true
526b670545cbc5a109d7759bee2b8cb26fe7961a
C++
inhyeokk/Algorithm
/src/programmers/PRO_L3_입국심사.cpp
UTF-8
1,254
3.625
4
[]
no_license
/* 입국심사 * 이분탐색 * 2020.01.12 */ #include <algorithm> #include <vector> using namespace std; long long grantedPeople(vector<int> times, long long time) { long long people = 0L; for (auto t: times) { people += time / t; } return people; } long long solution(int n, vector<int> times) { sort(times.begin(), times.end()); // 탐색 범위 0 ~ 가장 오래 걸리는 심사대 * 인원수 long long low = 0; long long high = (long long) times.back()*n; // 명시적 형변환 long long answer = high; while (low <= high) { long long mid = (low+high)/2; long long people = grantedPeople(times, mid); // mid 시간내에 심사받은 사람들 if (people < n) { low = mid+1; } else { // people >= n /* grantedPeople의 값이 n보다 클 때 올바른 경우가 있다. * time=20, times={4, 10} 인 경우 n의 올바른 범위는 5 ~ 7이다. * 이때 n=6인 경우 범위내에 있으므로 정답의 가능성이 있기에 answer에 저장한다. */ high = mid-1; if (answer > mid) { answer = mid; } } } return answer; }
true
db086d3171d6f6da7e06c2e4064c638235372ae6
C++
Nnmjywg/isPrime
/src/main.cpp
UTF-8
1,712
3.453125
3
[]
no_license
// // main.cpp // isPrime // // Copyright © 2018 nnmjywg. All rights reserved. // #include <iostream> #include <stdlib.h> #include <unistd.h> #include "number.h" int main(int argc, char * argv[]) { char arg = '\0'; int workingNumber; if(argc <= 1) { std::cout << ">>>>> Please provide a number with [-n (number)]." << std::endl; return 1; } //std::cout << argc << std::endl; while((arg = getopt(argc, argv, "n:")) != -1) { switch(arg) { case 'n': //std::cout << "working number determined" << std::endl; char *pEnd; workingNumber = (int)strtol(optarg, &pEnd, 10); break; default: return 0; break; } } if(workingNumber == NULL || workingNumber < 0) { std::cout << ">>>> Enter an integer greater than or equal to 0." << std::endl << ">>>> Error code: -2" << std::endl; return -1; } number Prime(workingNumber); //std::cout << "Your number is: [" << Prime.getValue() << "]."<< std::endl; if(Prime.getValue() == 1) { std::cout << "[1] is not a prime number, but its only factor is [1] itself." << std::endl; } else if(Prime.getValue() == 2) { std::cout << "[2] is a prime number." << std::endl; } else if(Prime.getPrime()) { std::cout << "[" << Prime.getValue() << "] is a prime number." << std::endl; } else { std::cout << "[" << Prime.getValue() << "] is not a prime number. Divisble by: [" << Prime.getFirstFactor() << "]." << std::endl; } return 0; }
true
eb1b7c5c1a2836509d042a9fda2f3d386ff7ccd4
C++
irajankumar/ProjectEuler
/projecteuler3/main.cpp
UTF-8
591
3.171875
3
[]
no_license
#include <iostream> #include<vector> //This program finds out the largest prime factor of given input using namespace std; int main() { long int n,big; cin>>n; vector<long int>primes; for(long int l=2; l<n; l++) { int ct=0; for(int m=2;m<l;m++) { if(l%m==0) { ct++; break; } if(ct>0) break; } if(ct==0) primes.push_back(l); } for(int i=0; i<primes.size();i++) { if(n%primes[i]==0) big=primes[i]; } cout<<big; return 0; }
true
4899c3a1edc31ca2e7b22a3a1f2c9c0687b9a0eb
C++
Beta-Alf/glexamples
/source/animationexample/RiggedDrawable.h
UTF-8
1,059
2.53125
3
[ "MIT" ]
permissive
#pragma once #include <vector> #include <map> #include <glm/glm.hpp> #include <globjects/base/ref_ptr.h> #include <gloperate/primitives/PolygonalDrawable.h> namespace globjects { class Buffer; } class RiggedDrawable : public gloperate::PolygonalDrawable { public: /** * @brief * Constructor * * @param[in] geometry * CPU mesh representation * * @remarks * The geometry is only used once to generate the mesh representation * on the GPU and not used afterwards. */ RiggedDrawable(const gloperate::PolygonalGeometry & geometry); /** * @brief * Destructor */ virtual ~RiggedDrawable() = default; std::map<std::string,size_t> m_boneMapping; /**< Mapping from string to boneIndex > */ std::vector<glm::mat4> m_bindTransforms; /**< bind Matrices per bone> */ protected: globjects::ref_ptr<globjects::Buffer> m_vertexBoneIndices; globjects::ref_ptr<globjects::Buffer> m_vertexBoneWeights; };
true
10928812bcb2a50b7b416f319f795158a5919d15
C++
wshwbluebird/LC16
/leet21-40/28.ImplementstrStr().cpp
UTF-8
952
2.953125
3
[]
no_license
//// //// Created by wshwbluebird on 16/8/9. //// //#include <iostream> //#include <vector> // // //using namespace std; // // //class Solution { //public: // int strStr(string haystack, string needle) { // // if(needle.size()==0) return 0; // if(needle.length()>haystack.length()) return -1; // bool flag; // for (int i = 0; i < haystack.length()-needle.length()+1 ; ++i) { // if(haystack[i]!=needle[0]) continue; // else { // flag = true; // for (int j = 1; j < needle.length() ; ++j) { // if(needle[j]!= haystack[i+j]) { // flag = false; // break; // } // } // if(flag) return i; // } // } // return -1; // } //}; // // //int main(){ // Solution s; // cout<<s.strStr("werreere","ere")<<endl; // // // return 0; //}
true
4a580ba78d4a68f5336b26ca83caefb7f9a35279
C++
pvCuongvjppro/Demo1
/HIT_B4.cpp
UTF-8
1,663
3.203125
3
[]
no_license
#include<iostream> #include<string.h> using namespace std; void NhapChuoi(char s[]){ cout <<"Nhap Chuoi "; gets(s); cout <<" Da Nhap Vao: "<< s<<endl; } //void ChuanHoa( char s[]){ //Chuan hoa toan bo // while (a[0]==' ') strcpy(&a[0], &a[1]); // while(a[strlen(a)-1]==' '){ // // a[strlen(a)-1] = '\0'; // } // for(int i =0; i<strlen(a)-1;i++) // if(a[i]==' '&&a[i+1]==' '){ // strcpy(&a[i],&a[i+1]); // i--; // } // strlwr(a); // a[0]=toupper(a[0]); // for(int i=0;i< strlen(a)-1;i++) // if(a[i]==' ') a[i+1]=toupper(a[i+1]); // //} ////Xoa Theo Chi So //void DeleteSpace(char s[], int pos){ // for(int i=pos;i<strlen(s)-1;i++){ // s[i]=s[i+1]; // } // //n--; \0 // s[strlen(s)-1]='\0'; //} //void DeleteAllSpace(char s[]){ // //xoa khoang trang o dau // while(s[0]==' '){ // DeleteSpace(s,0); // } // //xoa khoang trang giua cuoi // for(int i=0;i<strlen(s); i++){ // if(s[i]==' '&&s[i+1]==' '){ // DeleteSpace(s,i); // i--; // } // } //} ////Xoa Theo Vi Tri void DeleteSpace(char s[],int pos){ for(int i=pos-1;i<strlen(s)-1;i++){ s[i]=s[i+1]; } //n--; \0 s[strlen(s)-1]='\0'; } void DeleteAllSpace(char s[]){ //xoa khoang trang o dau while(s[0] == ' '){ DeleteSpace(s, 1); } //xoa khoang trang giua cuoi for(int i=1; i<strlen(s); i++){ if(s[i] == ' ' && s[i+1] == ' '){ DeleteSpace(s, i+1); i--; } } } void ChargeChar(char s[]){ //chuyen ve viet thuong strlwr(s); //viet hoa ki tu dau tien s[0] -= 32; for(int i=1; i<strlen(s)-1; i++){ if(s[i] == ' ' && s[i+1] != ' ') s[i+1] -= 32; } } int main(){ char s[100]; NhapChuoi(s); DeleteAllSpace(s); ChargeChar(s); // ChuanHoa(s); cout<<s<<endl; }
true