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
b8d5dd9be57bd0b04783bb80ea655fa507cf74ce
C++
apache/openoffice
/main/comphelper/inc/comphelper/InlineContainer.hxx
UTF-8
3,650
2.625
3
[ "Apache-2.0", "CPL-1.0", "bzip2-1.0.6", "LicenseRef-scancode-other-permissive", "Zlib", "LZMA-exception", "LGPL-2.0-or-later", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-philippe-de-muyter", "OFL-1.1", "LGPL-2.1-only", "MPL-1.1", "X11", "LGPL-2.1-or-later", "GPL-2.0-only", ...
permissive
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef INCLUDED_COMPHELPER_INLINE_CONTAINER_HXX #define INCLUDED_COMPHELPER_INLINE_CONTAINER_HXX #include <com/sun/star/uno/Sequence.hxx> #include <vector> #include <map> #include <set> namespace comphelper { /** Creates a UNO-Sequence which contains an arbitrary number of elements. Notice, that every call of the operator() issues a realloc, so this is not suitable to create very large sequences. usage: uno::Sequence< t >( MakeSequence< t >( t_1 )( t_2 )...( t_n ) ); */ template < typename T > class MakeSequence : public ::com::sun::star::uno::Sequence< T > { public: explicit MakeSequence(const T &a) : ::com::sun::star::uno::Sequence< T >( 1 ) { this->operator[](0) = a; } MakeSequence& operator()(const T &a) { this->realloc( this->getLength() + 1 ); this->operator[]( this->getLength() - 1 ) = a; return *this; } }; // ---------------------------------------- /** Creates a vector which contains an arbitrary number of elements. usage: vector< t > aVec( MakeVector< t >( t_1 )( t_2 )...( t_n ) ); */ template < typename T > class MakeVector : public ::std::vector< T > { public: explicit MakeVector(const T &a) : ::std::vector< T >(1, a) { } MakeVector &operator()(const T &a) { this->push_back(a); return *this; } }; // ---------------------------------------- /** Creates a set which contains an arbitrary number of elements. usage: set< t > aSet( MakeSet< t >( t_1 )( t_2 )...( t_n ) ); */ template < typename T > class MakeSet : public ::std::set< T > { public: explicit MakeSet(const T &a) : ::std::set< T >() { this->insert(this->end(), a); } MakeSet &operator()(const T &a) { this->insert(this->end(), a); return *this; } }; // ---------------------------------------- /** usage: map< k, v > aMap( MakeMap< k, v > ( key_1, value_1 ) ( key_2, value_2 ) ( key_3, value_3 ) ... ( key_n, value_n ) ); */ template < typename Key, typename Value > class MakeMap : public ::std::map< Key, Value > { private: typedef typename ::std::map< Key, Value >::value_type value_type; public: explicit MakeMap( const Key &k, const Value &v ) { this->insert( value_type( k, v ) ); } MakeMap &operator()( const Key &k, const Value &v ) { this->insert( value_type( k, v ) ); return *this; } MakeMap &operator()( const MakeMap& rSource ) { this->insert(rSource.begin(),rSource.end()); return *this; } }; } // namespace comphelper #endif // INCLUDED_COMPHELPER_INLINE_CONTAINER_HXX
true
aea3a605fbc5fdc7003d82e20d3d49bc52e7c64e
C++
jeow9028/SummerProject
/sensor.c/test.c.ino
UTF-8
701
3.046875
3
[]
no_license
/* Ultrasonic Sensor V3.3 test * Created by Jean-Christophe Owens * May 15th 2017 */ //Defines the outpin to the Robot const int x = 3; const int y = 3; // Global Variables long duration; int distance; void setup() { // Finds the pin of the suject and enters values for that specific port pinMode(x, INPUT); pinMode(y, OUTPUT); Serial.begin(3000); } void loop() { // Clears the trigPin digitalWrite(x, LOW); delayMicroseconds(5); digitalWrite(x, HIGH); delayMicroseconds(5); digitalWrite(x, LOW); //Reads the squrewave travel time duration = pulseIn(y, HIGH); //calculting distance distance = duration*0.0034/2; Serial.print("distance"); Serial.print("duration"); }
true
49a5a7f12b515359c50acd3f19d93a6b13c5cef1
C++
paaqwazi/algorithms
/competitive_programming/programming_contests/spoj_br/saldo13.cpp
UTF-8
297
2.96875
3
[ "MIT" ]
permissive
// SALDO13 #include <iostream> using namespace std; int main() { int n, s, menor_saldo, total, temp; cin >> n; cin >> s; menor_saldo = s; total = s; while(n--) { cin >> temp; total += temp; if (total < menor_saldo) menor_saldo = total; } cout << menor_saldo; return 0; }
true
f0986d0e0f9c9d2b0294b628c63737581f99c7aa
C++
TomasKimer/RetroSpace
/src/Color.h
UTF-8
4,047
2.984375
3
[]
no_license
// +------------------------------------------------------------+ // | RetroSpace v1.0 | // | Retrospektivni hra pro dva hrace s vesmirnou tematikou | // | Bakalarska prace, FIT VUT v Brne, 2011 | // +------------------------------------------------------------+ /** @author Tomas Kimer (xkimer00@stud.fit.vutbr.cz) * @date 18.5.2011 * @file Color.h * @brief Reprezentace 4-hodnotove barvy. */ #pragma once #include <ostream> #include "MathHelper.h" namespace GameFramework { /** * Reprezentace barvy, vcetne alfa kanalu. */ class Color { public: Color(void): m_r(1.0f), m_g(1.0f), m_b(1.0f), m_a(1.0f) {} Color(float r, float g, float b, float a = 1.0f): m_r(r), m_g(g), m_b(b), m_a(a) {} Color(unsigned int r, unsigned int g, unsigned int b, unsigned int a = 255) { m_r = r / 255.f; m_g = g / 255.f; m_b = b / 255.f; m_a = a / 255.f; } ~Color(void) {}; // get inline float R() const { return m_r; } inline float G() const { return m_g; } inline float B() const { return m_b; } inline float A() const { return m_a; } // get uint inline unsigned int Ri() const { return static_cast<unsigned int>(m_r * 255.f); } inline unsigned int Gi() const { return static_cast<unsigned int>(m_g * 255.f); } inline unsigned int Bi() const { return static_cast<unsigned int>(m_b * 255.f); } inline unsigned int Ai() const { return static_cast<unsigned int>(m_a * 255.f); } // set inline void R(float r) { m_r = r; } inline void G(float g) { m_g = g; } inline void B(float b) { m_b = b; } inline void A(float a) { m_a = a; } // set uint inline void Ri(unsigned int r) { m_r = r / 255.f; } inline void Gi(unsigned int g) { m_g = g / 255.f; } inline void Bi(unsigned int b) { m_b = b / 255.f; } inline void Ai(unsigned int a) { m_a = a / 255.f; } static inline Color Black (float alpha = 1.0f) { return Color(0.0f, 0.0f, 0.0f, alpha); } static inline Color White (float alpha = 1.0f) { return Color(1.0f, 1.0f, 1.0f, alpha); } static inline Color Red (float alpha = 1.0f) { return Color(1.0f, 0.0f, 0.0f, alpha); } static inline Color Green (float alpha = 1.0f) { return Color(0.0f, 1.0f, 0.0f, alpha); } static inline Color Blue (float alpha = 1.0f) { return Color(0.0f, 0.0f, 1.0f, alpha); } static inline Color Cyan (float alpha = 1.0f) { return Color(0.0f, 1.0f, 1.0f, alpha); } static inline Color Magenta(float alpha = 1.0f) { return Color(1.0f, 0.0f, 1.0f, alpha); } static inline Color Yellow (float alpha = 1.0f) { return Color(1.0f, 1.0f, 0.0f, alpha); } static inline Color Gray (float alpha = 1.0f) { return Color(0.5f, 0.5f, 0.5f, alpha); } static inline Color Violet (float alpha = 1.0f) { return Color(0.5f, 0.0f, 1.0f, alpha); } // linear interpolation static inline Color Lerp(Color col1, Color col2, float amount) { return col1 + (col2 - col1) * amount; } inline Color operator + (const Color & c) const { return Color(m_r + c.m_r, m_g + c.m_g, m_b + c.m_b, m_a + c.m_a); } inline Color operator - (const Color & c) const { return Color(m_r - c.m_r, m_g - c.m_g, m_b - c.m_b, m_a - c.m_a); } inline Color operator * (float f) const { return Color(m_r * f , m_g * f , m_b * f , m_a * f ); } inline bool operator != (const Color & c) const { return m_r != c.m_r || m_g != c.m_g || m_b != c.m_b || m_a != c.m_a; } friend std::ostream& operator << (std::ostream& o, const Color & c) { o << "r: " << c.Ri() << ", g: " << c.Gi() << ", b: " << c.Bi() << ", a: " << c.Ai(); return o; } private: float m_r, m_g, m_b, m_a; }; }
true
960d7564c76ded4ca9d09b7f840c8ef06bb6bc1e
C++
wangtss/leetcodePractice
/source/108ConvertSortedArraytoBinarySearchTree.cpp
UTF-8
426
3.203125
3
[]
no_license
TreeNode * helper_sortedArrayToBST(vector<int>& nums, int start, int end) { if (start > end) return NULL; int mid = (start + end) >> 1; TreeNode *node = new TreeNode(nums[mid]); node->left = helper_sortedArrayToBST(nums, start, mid - 1); node->right = helper_sortedArrayToBST(nums, mid + 1, end); return node; } TreeNode* sortedArrayToBST(vector<int>& nums) { return helper_sortedArrayToBST(nums, 0, nums.size() - 1); }
true
5fbd70c7a6617ab2cf4ba767d61355d5eb8a9e3c
C++
Cr4zySheep/Tankmania
/Core/CollisionManager.hpp
UTF-8
1,066
2.8125
3
[]
no_license
#ifndef COLLISIONMANAGER_HPP_INCLUDED #define COLLISIONMANAGER_HPP_INCLUDED #include <SFML/Graphics.hpp> #include <math.h> typedef unsigned int uint; struct Point { float x; float y; Point() {} Point(sf::Vector2f pos) : x(pos.x), y(pos.y) {} //Distance euclidienne static float distance(Point p1, Point p2) { return (p2.x - p1.x) * (p2.x - p1.x) + (p2.y - p1.y) * (p2.y - p1.y); } }; struct Circle { Point center; int radius; }; struct AABB { AABB() : x(0), y(0), w(0), h(0) { } float x, y, w, h; }; struct CollisionData { Circle circle; AABB aabb; }; class Object; class CollisionManager { public: static bool AABB_and_AABB(AABB box1, AABB box2); static bool circle_and_point(Circle circle, Point point); static bool circle_and_circle(Circle circle1, Circle circle2); static bool collide(Object& object1, Object& object2, float dt, bool react = true); static bool isVisible(sf::FloatRect s, sf::View const& v); }; #endif // COLLISIONMANAGER_HPP_INCLUDED
true
9029afb24d02c5b3f1aa57db1d57fce634edd436
C++
gurusarath1/Algorithms_2
/LeetCode_Problems/Graph/Course_Schedule_II.cpp
UTF-8
1,414
2.796875
3
[]
no_license
class Solution { public: vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) { vector<int> inDegrees(numCourses, 0); map<int, vector<int>> graph; vector<int> result; for(vector<int> course_preqs : prerequisites) { inDegrees[course_preqs[0]] += 1; graph[course_preqs[0]].push_back(course_preqs[1]); } queue<int> q; while(1) { for(int i=0; i<inDegrees.size(); i++) { if(inDegrees[i] == 0) { inDegrees[i] = -1; q.push(i); } } if(q.empty()) { if(result.size() < numCourses) { result.clear(); } return result; } while(!q.empty()) { for(int i=0; i<inDegrees.size(); i++) { if(inDegrees[i] > 0) { if( find(graph[i].begin(), graph[i].end(), q.front()) != graph[i].end() ) { inDegrees[i] = inDegrees[i] - 1; } } } result.push_back(q.front()); q.pop(); } } return result; } };
true
ccde622ebabed90d1a4eb468d48bcfb77d16da99
C++
ZivDrukker/MagshiTrivia
/Server/server/Question.h
UTF-8
348
2.765625
3
[]
no_license
#pragma once #include <string> #include <iostream> using std::string; class Question { public: Question(int, string, string, string, string, string, int); ~Question(); string getQuestion(); string* getAnswers(); int getCorrectAnswerIndex(); int getId(); private: string _question; string* _answers; int _correctAnswerIndex; int _id; };
true
55d7f16a4d2b06f1b69e4094d1a077ffd5f1e59f
C++
JSDupre/NeuroneVS
/main.cpp
UTF-8
2,450
2.84375
3
[]
no_license
#include <iostream> #include "Neurone.hpp" #include <fstream> #include <iomanip> #include <vector> #include "Connection.hpp" using namespace std; bool isInIntervalle(double ToTest,double Inf,double Sup){ bool x(ToTest>=Inf && ToTest<Sup); return x; } void recordValue(Neurone const& n,double time,ofstream& out) { out<<setprecision(3)<<time<<" "<<n.getMembranePotential()<<endl; } double AskUserADouble() { //on pourrait checker que l'entrée soit correcte double result; cin>>result; return result; } int main() { cout<<"temps de simulation? (ms)"<<endl; double Tstop(AskUserADouble()); int TotalNumberOfTimeIncrement = Tstop/TimeIncrement;//calcul du nombre de pas de simulation (pourrait prendre une valeur max) /* cout<<"entrez borne inf (entre 0 et Tstop)"<<endl; double BorneInfIntervalle(AskUserADouble()); cout<<"entrez borne sup (entre borne sup et Tstop)"<<endl; double BorneSupIntervalle(AskUserADouble()); cout<<"Input value?"<<endl; double Iext(AskUserADouble()); */ ofstream f("values.txt",ios::trunc);//declaration du stream d'ecriture /* //simulation loop for a single neurone for(unsigned int i(0);i<TotalNumberOfIncrement;++i){ recordValue(n,i*TimeIncrement,f); if(isInIntervalle(i*TimeIncrement,BorneInfIntervalle,BorneSupIntervalle)){ n.update(1,Iext,0.0); } else { n.update(1,0.0,0.0); } } */ int clock(0); //loop for two or more neurone //test for 2 neurons Neurone n1(clock,5); Neurone n2(clock,0.0); vector<Neurone> network; network.push_back(n1); network.push_back(n2); Neurone* ptr(&n2); //cerr<<(*ptr).getMembranePotential()<<endl;//ca a l'air de marcher Connection c(ptr,0.01); vector<Connection> co; co.push_back(c); if(!co.empty()){cerr<<"pas vide"<<endl;} n1.setConnections(co); if(!(n1.getConnections()).empty()){cerr<<"pas vide"<<endl;} //cerr<<(((n1.getConnections())[0]).getPost())->getMembranePotential()<<endl; //fin initialisations while (clock<TotalNumberOfTimeIncrement){ for(auto& n:network){ //for(auto& n:network.getNeurones()) bool spike(n.update(1)); //arguments pour neurone::update ?? Iext? if(spike){ cerr<<"SPIKE"<<endl; for(auto& connection:n.getConnections()){ cerr<<"boucle"<<endl; (connection.getPost())->receive((clock+D),connection.getJ()); } } } recordValue(n1,clock*TimeIncrement,f);//record clock+=1; } return 0; }
true
52a76b442aa931f21698aebc94ad256e500b181f
C++
Salomon-mtz/estructura-de-datos-agosto-diciembre-2021
/ListaDeAdyacecnias/ListaDeAdyacencias.cpp
UTF-8
895
3.15625
3
[]
no_license
#ifndef LISTA_DEFINED #define LISTA_DEFINED #include <list> #include <iostream> using namespace std; class ListaDeAdyacencias{ private: int numeroVertices; list<int> *adyacencias; public: ListaDeAdyacencias(int numeroVertices){ this->numeroVertices=numeroVertices; adyacencias= new list<int>[numeroVertices]; } void agregarAdyacencia(int inicio, int fin){ adyacencias[inicio].push_back(fin); adyacencias[fin].push_back(inicio); } void imprimeGrafo(){ for(int i=0;i<numeroVertices;i++){ cout<<"Vertice "<<i<<" Adyacencias: "; //imprimir adyacencias for(auto adyacencia:adyacencias[i]){ cout<<"->"<<adyacencia; } cout<<endl; } } }; #endif
true
c638f4a994c6d40ee94ca6f8b7551aebab982d15
C++
baptistemeunier/Tetris
/Source/AppEngine.cpp
UTF-8
1,120
3.0625
3
[]
no_license
#include "AppEngine.h" #include <iostream> void AppEngine::init(std::string name) { display.init(name); } void AppEngine::clean() { display.clean(); for(int i=0; i < states.size(); i++){ states[i]->clean(); } } sf::RenderWindow* AppEngine::getWindow() { return display.getWindow(); } void AppEngine::routine() { while(display.isOpen()) { display.clearWindow(); sf::Event event; while (display.getWindow()->pollEvent(event)) { display.checkWindowEvent(event); states.back()->handleEvents(event); } states.back()->update(); states.back()->draw(); display.displayWindow(); } } void AppEngine::changeState(GameState* state) { if(states.size() != 0) { states.back()->clean(); states.pop_back(); } states.push_back(state); state->init(this); } void AppEngine::pushState(GameState* state) { states.push_back(state); state->init(this); } void AppEngine::popState() { if(states.size() != 0) { states.back()->clean(); states.pop_back(); } }
true
f7fc8ef29cca8f1f39c7b4ff0b137591b6787c5b
C++
Tanmay-Tiwari88/Snake
/Engine/snake.h
UTF-8
724
2.734375
3
[]
no_license
#pragma once #include "board.h" #include "location.h" #include"fruit.h" class snake { private: class segment { private: location l; Color c; public: void inithead(location& l); void initsegment(); void follow(segment &segnext); void movebydelta(location delta); bool comp(segment seg1, segment seg2); void drawseg(board& b); location getheadl(); }; private: static constexpr int segments = 100; segment segs[segments]; int nsegs = 1; static constexpr Color headcolor = Colors::Green; static constexpr Color bodycolor = Colors::Yellow; public: snake(location& loc); void drawsnake(board &b); void grow(); void moveby(location& delta); location gethead(); bool snakedeath(); };
true
8a4963c189d4385976241faf95785668f953e531
C++
kabrate/lanqiao
/homework/radix.cpp
GB18030
725
2.796875
3
[]
no_license
#include<cstdio> using namespace std; long a; int p,c,m=0,s[100]; void trans() { while (a!=0)//תs[m] { c=a%16; a=a/16; m++;s[m]=c; //˳s[m] } for(int k=m;k>=1;k--)//ת { if(s[k]>=10) //ΪʮƵӦĸ //cout<<(char)(s[k]+55); printf("%c",(char)(s[k]+55)); else //ֱ //cout<<s[k]; printf("%d",s[k]); } } int main() { scanf("%d",&a); //cin>>a; if(a==0) printf("0"); else trans(); return 0; }
true
7f44ddd6de86e3a4e6165b9f395b8074a518ff9e
C++
uneap/algorithm
/2020/200104.cpp
UTF-8
433
2.921875
3
[]
no_license
#include <string> #include <vector> #include <unordered_map> using namespace std; int solution(vector<vector<string>> clothes) { int answer = 1; unordered_map<string, int> clothMap; for (int i = 0; i < clothes.size(); i++) clothMap[clothes[i][1]]++; for (unordered_map<string, int> ::iterator clothIter = clothMap.begin(); clothIter != clothMap.end(); ++clothIter) answer *= (clothIter->second + 1); return answer - 1; }
true
cb84777d34fec855522c422c2a07eaa5a925f508
C++
rjtsdl/CPlusPlus
/Interview Play CPP/a527WordAbbreviation.cpp
UTF-8
2,009
3.265625
3
[]
no_license
// // a527WordAbbreviation.cpp // Interview Play CPP // // Created by Jingtao Ren on 9/20/20. // Copyright © 2020 Jingtao Ren. All rights reserved. // #include <stdio.h> #include <string> #include <vector> using namespace std; struct Trie { Trie() : children(26, shared_ptr<Trie>()) { } void insert(string& s, int index) { if (index == s.size()) return; if (!children[s[index] - 'a']) children[s[index] - 'a'] = make_shared<Trie>(); children[s[index] - 'a']->weight++; children[s[index] - 'a']->insert(s, index + 1); } int findUniqueIndex(string& s, int index) { if (index == s.size() || children[s[index] - 'a']->weight < 2) return index; return children[s[index] - 'a']->findUniqueIndex(s, index + 1); } size_t weight = 0; vector<shared_ptr<Trie>> children; }; class Solution { public: string getAbbr(string s, int index) { if (s.size() < 4 || s.size() - index - 2 < 2) return s; if (index == 0) return s.front() + to_string(s.size() - 2) + s.back(); return s.substr(0, index + 1) + to_string(s.size() - 2 - index) + s.back(); } vector<string> wordsAbbreviation(vector<string>& dict) { vector<vector<shared_ptr<Trie>>> tries(26, vector<shared_ptr<Trie>>(401, shared_ptr<Trie>())); for (auto word : dict) { if (!tries[word.back() - 'a'][word.size()]) tries[word.back() - 'a'][word.size()] = make_shared<Trie>(); tries[word.back() - 'a'][word.size()]->insert(word, 0); } vector<string> result; for (auto word : dict) result.push_back(word.size() < 4 ? word : getAbbr(word, tries[word.back() - 'a'][word.size()]->findUniqueIndex(word, 0))); return result; } };
true
56231d934ccdcfe7265a6a843b7640ee73daaba7
C++
plinx/CodePractices
/CppPrimer/Unit5/E520/E520/Source.cpp
UTF-8
351
3.046875
3
[]
no_license
#include <iostream> #include <string> using std::string; using std::cin; using std::cout; using std::endl; int main() { string str, tmp; int dflag = 1; while (cin >> str) { if (tmp == str) { cout << "str " << str << " appear twice." << endl; dflag = 0; } tmp = str; } if (dflag) cout << "no str appear twice." << endl; return 0; }
true
4c8248519e2f093e8331428f5a45288d2de849eb
C++
pritikmshaw/Algorithms
/cpp/longest_increasing_subsequence.cpp
UTF-8
545
2.875
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { int n, i, j; cin >> n; vector <int> arr(n), lis(n); for(i=0;i<n;i++) { cin >> arr[i]; } for(i=0;i<n;i++) { lis[i] = 1; } for(i=1;i<n;i++) { for(j=0;j<i;j++) { if(arr[i]>arr[j] && lis[i]<=lis[j]) { lis[i] = 1 + lis[j]; } } } sort(lis.begin(),lis.end()); cout << lis[lis.size()-1] << "\n"; return 0; }
true
2e41f4eb44f873d92042188df3477ee27e03dca1
C++
kenanking/CS106BHW
/7Trailblazer/src/trailblazer.cpp
UTF-8
2,414
2.59375
3
[]
no_license
// This is the CPP file you will edit and turn in. // Also remove these comments here and add your own, along with // comments on every function and on complex code sections. // TODO: write comment header for this file; remove this comment #include "trailblazer.h" // TODO: include any other headers you need; remove this comment using namespace std; Vector<Vertex*> depthFirstSearch(BasicGraph& graph, Vertex* start, Vertex* end) { // TODO: implement this function; remove these comments // (The function body code provided below is just a stub that returns // an empty vector so that the overall project will compile. // You should remove that code and replace it with your implementation.) Vector<Vertex*> path; return path; } Vector<Vertex*> breadthFirstSearch(BasicGraph& graph, Vertex* start, Vertex* end) { // TODO: implement this function; remove these comments // (The function body code provided below is just a stub that returns // an empty vector so that the overall project will compile. // You should remove that code and replace it with your implementation.) Vector<Vertex*> path; return path; } Vector<Vertex*> dijkstrasAlgorithm(BasicGraph& graph, Vertex* start, Vertex* end) { // TODO: implement this function; remove these comments // (The function body code provided below is just a stub that returns // an empty vector so that the overall project will compile. // You should remove that code and replace it with your implementation.) Vector<Vertex*> path; return path; } Vector<Vertex*> aStar(BasicGraph& graph, Vertex* start, Vertex* end) { // TODO: implement this function; remove these comments // (The function body code provided below is just a stub that returns // an empty vector so that the overall project will compile. // You should remove that code and replace it with your implementation.) Vector<Vertex*> path; return path; } Set<Edge*> kruskal(BasicGraph& graph) { // TODO: implement this function; remove these comments // (The function body code provided below is just a stub that returns // an empty set so that the overall project will compile. // You should remove that code and replace it with your implementation.) Set<Edge*> mst; return mst; }
true
8f1782489a222081b1238926998085e08fc291de
C++
orbulant/Hardware-Store-DAS
/modules/ProductController.cpp
UTF-8
9,147
2.890625
3
[ "MIT" ]
permissive
#include "Product.h" #include "LinkedList.h" #include "Utils.h" #include "ProductController.h" // CONSTRUCTOR ProductController::ProductController(InputHelper inputHelper) { setInputHelper(inputHelper); } // SETTERS void ProductController::setInputHelper(InputHelper inputHelper) { this->inputHelper = inputHelper; } // METHODS void ProductController::load() { // read all available products productList.setNodeEnds(fh.createProductLinkedList(fh.readJSONFile(pathProduct))); // to keep track of selection choice int productChoice = 0; bool end = false; do{ // switch statement here cout << "Available Product Related Functions:" << endl; cout << "[1] To Add A New Product" << endl; cout << "[2] To Update A Product Information" << endl; cout << "[3] To Delete A Product" << endl; cout << "[4] To Search For A Product" << endl; cout << "[5] To Display All Available Products" << endl; cout << "[6] To Filter Products Of A Category" << endl; cout << "[7] To Sort Products (Based On Quantity)" << endl; cout << "[0] to Return" << endl; // get choice input inputHelper.promptInput("Select an option: ", productChoice, 0, 7, 0, false); cout << endl; switch(productChoice){ case 1: { add(); break; } case 2: { update(); break; } case 3: { remove(); break; } case 4: { search(); break; } case 5: { displayAll(); break; } case 6: { filter(); break; } case 7: { sort(); unsort(); break; } case 0: { end = true; // sort back sequence to id unsort(); // 'save' changes fh.writeToFile(fh.morphProductNodetoJSON(productList.getNodeEnds()), pathProduct); productList.removeAll(); break; } } } while (!end); } void ProductController::add(){ cout << "Adding A Product" << endl; cout << "Enter [-1] To Cancel This Operation" << endl; cout << endl; string name, desc, category_name; double price; int quantity, category_index; Product product; if(inputHelper.promptInput("Enter A Product Name: ", name, "-1", false)) { goto endpoint; } if(inputHelper.promptInput("Enter A Product Description: ", desc, "-1", false)) { goto endpoint; } category_selection.printAllCategories(); if(inputHelper.promptInput("Enter A Product Category Name: ", category_index, 1, category_selection.length(), -1, false)) { goto endpoint; } else { category_name = category_selection.get(category_index); } if(inputHelper.promptInput("Enter A Product Price (RMxx.xx): ", price, 1, 9999999, -1, false)) { goto endpoint; } if(inputHelper.promptInput("Enter A Product Quantity (>=1): ", quantity, 1, 9999999, -1, false)) { goto endpoint; } // get the largest id available and increment by one product.setID(productList.getLatestID() + 1); product.setName(name); product.setDesc(desc); product.setCategoryName(category_name); product.setPrice(price); product.setQuantity(quantity); productList.insert(product); cout << endl; cout << "Successfully Inserted Product:" << endl; productList.printTableHead(); productList.toString(product); endpoint:; cout << endl; } void ProductController::update(){ int id; cout << "Select A Product By ID" << endl; if(inputHelper.promptInput("Enter A Product ID: ", id, 0, 9999999, -1, false)) { return; } else { if(productList.search(id)) { Product originalProduct = productList.get(id); cout << endl; productList.printTableHead(); productList.toString(originalProduct); cout << "Enter [-1] To Cancel This Operation" << endl; cout << "Input [0] To Skip A Field" << endl; cout << endl; string name, desc, category_name; double price; int quantity, category_index; Product product; if(inputHelper.promptInput("Enter A Product Name: ", name, "-1", false)) { goto endpoint; } if(inputHelper.promptInput("Enter A Product Description: ", desc, "-1", false)) { goto endpoint; } category_selection.printAllCategories(); if(inputHelper.promptInput("Enter A Product Category Name: ", category_index, 0, category_selection.length(), -1, false)) { goto endpoint; } if(inputHelper.promptInput("Enter A Product Price (RMxx.xx): ", price, 0, 9999999, -1, false)) { goto endpoint; } if(inputHelper.promptInput("Enter A Product Quantity (>=1): ", quantity, 0, 9999999, -1, false)) { goto endpoint; } product.setID(id); // set previous id // for some reason .empty() and == (only) not working on "" if(name.compare("0") != 0) { product.setName(name); } else { product.setName(originalProduct.getName()); } if(desc.compare("0") != 0) { product.setDesc(desc); } else { product.setDesc(originalProduct.getDesc()); } if(category_index != 0) { product.setCategoryName(category_selection.get(category_index)); } else { product.setCategoryName(originalProduct.getCategory()); } if(price != 0) { product.setPrice(price); } else { product.setPrice(originalProduct.getPrice()); } if(quantity != 0) { product.setQuantity(quantity); } else { product.setQuantity(originalProduct.getQuantity()); } productList.update(product, id); cout << endl; cout << "Successfully Updated Product: " << endl; // prints updated data productList.printTableHead(); productList.toString(product); endpoint:; cout << endl; } } } void ProductController::remove(){ int id; cout << "Select A Product By ID" << endl; if(inputHelper.promptInput("Enter A Product ID: ", id, 0, 9999999, -1, false)) { return; } else { if(productList.search(id)) { if(inputHelper.promptConfirmation()) { productList.remove(id); } } } } void ProductController::search(){ int id; cout << "Search A Product By ID" << endl; if(inputHelper.promptInput("Enter A Product ID: ", id, 0, 9999999, -1, false)) { goto endpoint; } else { if(productList.search(id)) { productList.printTableHead(); productList.toString(productList.get(id)); } } endpoint:; cout << endl; } void ProductController::displayAll(){ productList.searchAll(); } void ProductController::filter(){ //Declares category object. Category category; //Prints all categories present from the category list. category.printAllCategories(); //Couts a console output to inform user to select a range from 0-9 as per the index cout << "Please select from a number ranging from [1] to [10]" << endl; //Declaring selection chocie variable. int selectionChoice; //Input Helper to obtain selection choice from users. if(inputHelper.promptInput("Enter your choice: ", selectionChoice, 0, 9999999, -1, false)){ goto endpoint; } else { productList.searchByCategory(category.get(selectionChoice)); } endpoint:; cout << endl; } void ProductController::sort(){ Node<Product> *firstOne = productList.getNodeEnds()->next; Node<Product> *lastOne = productList.getNodeEnds()->last; //std::cout << firstOne << "\n\n"; //std::cout << lastOne << "\n\n"; productList.quickSortProduct(firstOne, lastOne); displayAll(); } void ProductController::unsort(){ Node<Product> *firstOne = productList.getNodeEnds()->next; Node<Product> *lastOne = productList.getNodeEnds()->last; productList.quickSortID(firstOne, lastOne); }
true
c26c46ea571963e02b9079d4a2f9707aafbfaa7b
C++
heboyuan/BruinNav
/BruinNav/main.cpp
UTF-8
2,453
2.953125
3
[]
no_license
#include"provided.h" #include<iostream> using namespace std; int main() { cout << "Loading the map..." << endl <<endl; Navigator Nav; Nav.loadMapData("mapdata.txt"); vector<NavSegment> directions; cout << "instructions===================================================" << endl << "Map data is in mapdata.txt" << endl << "Valid location name is in validlocs.txt" << endl <<endl << "Valid Location Example"<<endl <<"UCLA Blood & Platelet Center"<<endl << "10925 Kinross Avenue" << endl << "Ralph's" << endl << "UCLA School of Dentistry" << endl << "==============================================================" << endl <<endl; string start, end; cout << "Where do you want to start (please enter valid location in validlocs.txt)"<<endl<<"Start Location: "; getline(cin, start); cout << "Where do you want to go (please enter valid location in validlocs.txt)" << endl << "Destination Location: "; getline(cin, end); Nav.navigate(start, end, directions); double length = 0; cout << endl << "Finding your rouute..." << endl; cout <<endl<< "Please Follow the navigation instrucntion below" << endl << "===================================================" << endl; string temp = ""; for (int n = 0; n < directions.size(); n++) { if (directions[n].m_command == 0) { if (temp != directions[n].m_streetName) { temp = directions[n].m_streetName; cout << "Please keep "<< directions[n].m_direction << " on "<< directions[n].m_streetName << endl << endl; } length += directions[n].m_distance; } else { cout << "Please turn " << directions[n].m_direction << " onto " << directions[n].m_streetName << endl << endl; } } cout << "===================================================" << endl<<endl; cout << "Your Route is" << endl; cout << "Route Coordinate====================================" << endl; for (int n = 0; n < directions.size(); n++) { if (directions[n].m_command == 0) { cout << directions[n].m_geoSegment.start.latitudeText << "," << directions[n].m_geoSegment.start.longitudeText << endl << directions[n].m_geoSegment.end.latitudeText << "," << directions[n].m_geoSegment.end.longitudeText << endl; } } cout << "===================================================" << endl; cout << endl; cout << "the total distance is "<< length <<" miles" << endl << endl; cout << "Enter anything to exist" << endl; string finish; cin >> finish; }
true
3dbb11db4b926df685469a0000540bf41857e4cf
C++
attugit/archie
/include/archie/fused/fold.hpp
UTF-8
2,949
2.890625
3
[ "MIT" ]
permissive
#pragma once #include <utility> #include <archie/meta/static_constexpr_storage.hpp> #include <archie/fused/static_if.hpp> #include <archie/boolean.hpp> namespace archie::fused { namespace detail { struct fold_ { template <typename F, typename S, typename... Xs> constexpr decltype(auto) operator()(F const& func, S&& acc, Xs&&... xs) const { return static_if(fused::boolean<(sizeof...(Xs) > 1)>) .then([this](auto const& f, auto&& state, auto&& x_, auto&&... y) -> decltype(auto) { return this->operator()( f, f(std::forward<decltype(state)>(state), std::forward<decltype(x_)>(x_)), std::forward<decltype(y)>(y)...); }) .else_([](auto const& f, auto&& state, auto&& x_) -> decltype(auto) { return f(std::forward<decltype(state)>(state), std::forward<decltype(x_)>(x_)); })(func, std::forward<S>(acc), std::forward<Xs>(xs)...); } }; struct greedy_fold_ { template <typename F, typename S, typename... Xs> decltype(auto) operator()(F const& f, S const& s, Xs const&... xs) const { return impl(f, s, xs...); } private: template <typename F, typename S, typename X> decltype(auto) impl(F const& f, S const& s, X const& x) const { return f(s, x); } template <typename F, typename S, typename X, typename... Ys> decltype(auto) impl(F const& f, S const& s, X const& x, Ys const&... ys) const { return impl(f, f(s, x, ys...), ys...); } }; } static constexpr auto const& fold = meta::instance<detail::fold_>(); static constexpr auto const& greedy_fold = meta::instance<detail::greedy_fold_>(); namespace detail { struct make_fold_ { private: template <typename F> struct impl_no_state { F const func; constexpr impl_no_state(F const& f) : func(f) {} template <typename... Ts> constexpr decltype(auto) operator()(Ts&&... ts) const { return fused::fold(func, std::forward<Ts>(ts)...); } }; template <typename F, typename S> struct impl_with_state { F const func; S const state; constexpr impl_with_state(F const& f, S const& s) : func(f), state(s) {} template <typename... Ts> constexpr decltype(auto) operator()(Ts&&... ts) const { return fused::fold(func, state, std::forward<Ts>(ts)...); } }; public: template <typename F> constexpr decltype(auto) operator()(F const& f) const { return impl_no_state<F>{f}; } template <typename F, typename S> constexpr decltype(auto) operator()(F const& f, S const& s) const { return impl_with_state<F, S>{f, s}; } }; } static constexpr auto const& make_fold = meta::instance<detail::make_fold_>(); }
true
b86a15ad76ffa8c2ec6e01934e3fef3b62470633
C++
ondal1997/online-game-demo-of-my-component-game-engine
/main/참고용.cpp
UTF-8
15,565
2.671875
3
[]
no_license
#include "engine.h" class Direction : public Component { public: Direction(int value = 1) : value(value) { } int value; }; class Position : public Component { public: Position(float x = 0.0f, float y = 0.0f) : x(x), y(y) { } float x; float y; }; class Velocity : public Component { public: Velocity(float vx = 0.0f, float vy = 0.0f) : vx(vx), vy(vy) { } float vx; float vy; }; class DeltaPosition : public Component { public: DeltaPosition(float dx = 0.0f, float dy = 0.0f) : dx(dx), dy(dy) { } float dx; float dy; }; class Move : public Component { public: Move(float value = 0.0f) : value(value) { } float value; }; class Jump : public Component { public: Jump(float value = 0.0f) : value(value) { } float value; }; class Health : public Component { public: Health(float value = 0.0f, float max = 0.0f) : value(value), max(max) { } float value; float max; }; class HitBox : public Component { public: HitBox(float width, float height) : width(width), height(height) { } float width; float height; }; class Team : public Component { public: Team(int value) : value(value) { } int value; }; class Image : public Component { public: Image() : key(nullptr) { } const char* key; }; class Sound : public Component { public: Sound() : key(nullptr) { } const char* key; }; #include <vector> class Hit : public Component { public: Hit(size_t value, std::vector<Entity*> exception) : value(value), exception(exception) { } size_t value; std::vector<Entity*> exception; }; class Fire : public Component { public: Fire() { } }; class Human : public Component { public: Human(Entity* entity, const char* state = "idle", size_t tick = 0) : entity(entity), state(state), tick(tick), horizontal(0), vertical(0) { } Entity* entity; const char* state; size_t tick; int horizontal; int vertical; void ready() { auto health = *entity->getComponent<Health>(); auto image = *entity->getComponent<Image>(); auto position = *entity->getComponent<Position>(); auto direction = *entity->getComponent<Direction>(); if (state == "idle") { if (health.value == 0) { state = "die"; tick = 0; ready(); return; } if (position.y < 0) { state = "air"; tick = 0; ready(); return; } if (vertical == -1) { state = "jump"; tick = 0; ready(); return; } if (horizontal) { direction = horizontal; state = "move"; tick = 0; ready(); return; } if (tick < 20) { image.key = "human_idle0"; } else if (tick < 40) { image.key = "human_idle1"; } } else if (state == "move") { if (health.value == 0) { state = "die"; tick = 0; ready(); return; } if (position.y < 0) { state = "air"; tick = 0; ready(); return; } if (vertical == -1) { state = "jump"; tick = 0; ready(); return; } /*if (!horizontal) { state = "move"; tick = 0; ready(); return; }*/ if (tick < 20) { image.key = "human_move0"; } else if (tick < 40) { image.key = "human_move1"; } } else if (state == "air") { if (health.value == 0) { state = "die"; tick = 0; ready(); return; } if (position.y == 0) { state = "idle"; tick = 0; ready(); return; } image.key = "human_air0"; } else if (state == "jump") { if (health.value == 0) { state = "die"; tick = 0; ready(); return; } if (position.y < 0) { state = "air"; tick = 0; ready(); return; } if (tick < 20) { image.key = "human_jump0"; } else if (tick < 40) { image.key = "human_jump1"; } } else if (state == "die") { if (tick < 20) { image.key = "human_die0"; } else if (tick < 40) { image.key = "human_die1"; } else if (tick < 60) { image.key = "human_die2"; } else if (tick < 80) { image.key = "human_die3"; } } else if (state == "attack") { if (health.value == 0) { state = "die"; tick = 0; ready(); return; } if (tick == 60) { // ���̾���̺ꤻ ����, ready() �������ֱ��; } if (tick < 20) { image.key = "human_attack0"; } else if (tick < 40) { image.key = "human_attack1"; } else if (tick == 40) // case { image.key = "human_attack1"; // y == 0 ? tick = 60; ready(); return; } else if (tick < 80) { image.key = "human_attack2"; } else if (tick < 100) { image.key = "human_attack3"; } } } void input(unsigned int key, bool isDown) { switch (key) { case 0: case 1: if (state == "idle") { if (horizontal) { auto direction = *entity->getComponent<Direction>(); direction = horizontal; state = "move"; tick = 0; ready(); return; } } else if (state == "move") { if (horizontal) { auto direction = *entity->getComponent<Direction>(); direction.value = horizontal; } else { state = "idle"; tick = 0; ready(); return; } } else if (state == "jump") { if (horizontal) { auto direction = *entity->getComponent<Direction>(); direction.value = horizontal; } } break; case 2: case 3: break; case 4: if (isDown) { if (state == "idle" || state == "move" || state == "air") { state = "attack"; tick = 0; ready(); return; } } break; } } void action() { if (state == "idle") { tick++; if (tick == 40) tick = 0; } else if (state == "move") { tick++; if (tick == 40) tick = 0; auto deltaPosition = *entity->getComponent<DeltaPosition>(); auto move = *entity->getComponent<Move>(); auto direction = *entity->getComponent<Direction>(); deltaPosition.dx += move.value * direction.value; } else if (state == "air") { auto deltaPosition = *entity->getComponent<DeltaPosition>(); auto move = *entity->getComponent<Move>(); deltaPosition.dx += move.value * horizontal; } else if (state == "jump") { tick++; if (tick == 40) { auto velocity = *entity->getComponent<Velocity>(); auto jump = *entity->getComponent<Jump>(); velocity.vy -= jump.value; state = "idle"; tick = 0; } } else if (state == "die") { tick++; if (tick == 80) tick--; // ;) } else if (state == "attack") { tick++; if (tick == 41) { tick--; } else if (tick == 80) { // ���� �ۿ� } else if (tick == 100) { state = "idle"; tick = 0; } } } }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class Gravity : public System { public: Gravity(float value = 10.0f) : value(value) { addComponentType<Velocity>(); } float value; void update() { for (auto entity : entities) { auto velocity = *entity->getComponent<Velocity>(); velocity.vy += value; } } }; class Translate : public System { public: Translate() { addComponentType<Position>(); addComponentType<Velocity>(); addComponentType<DeltaPosition>(); } void update() { for (auto entity : entities) { auto position = *entity->getComponent<Position>(); auto velocity = *entity->getComponent<Velocity>(); auto deltaPosition = *entity->getComponent<DeltaPosition>(); deltaPosition.dx += velocity.vx; deltaPosition.dy += velocity.vy; position.x += deltaPosition.dx; position.y += deltaPosition.dy; deltaPosition.dx = 0.0f; deltaPosition.dy = 0.0f; } } }; class LandInspection : public System { public: LandInspection(float value = 0.25f) : value(value) { addComponentType<Position>(); addComponentType<Velocity>(); } float value; void update(int dt) { for (auto entity : entities) { auto position = *entity->getComponent<Position>(); auto velocity = *entity->getComponent<Velocity>(); if (position.y >= 0.0f) { position.y = velocity.vy = 0.0f; } if (position.y == 0.0f) if (velocity.vx < 0.0f) if (velocity.vx >= -value) velocity.vx = 0.0f; else velocity.vx += value; else if (velocity.vx <= value) velocity.vx = 0.0f; else velocity.vx -= value; } } }; #include <SDL.h> #pragma comment(lib, "SDL2") #pragma comment(lib, "SDL2main") #include <SDL_image.h> #pragma comment(lib, "SDL2_image") #include <map> void stretchTextureEx(SDL_Renderer* renderer, int x, int y, int w, int h, SDL_Texture* texture, float angle, SDL_RendererFlip flip = SDL_FLIP_NONE) { //SDL_FLIP_HORIZONTAL SDL_FLIP_VERTICAL SDL_Rect src, dst; SDL_Point center; src.x = src.y = 0; SDL_QueryTexture(texture, NULL, NULL, &src.w, &src.h); dst.x = x; dst.y = y; dst.w = w; dst.h = h; center.x = w / 2; center.y = h / 2; SDL_RenderCopyEx(renderer, texture, &src, &dst, 0.0, &center, flip); } class ImageSystem : public System { public: ImageSystem(SDL_Window* window) : renderer(SDL_CreateRenderer(window, -1, 0)) { addComponentType<Position>(); addComponentType<Image>(); } ~ImageSystem() { SDL_DestroyRenderer(renderer); } SDL_Renderer* renderer; //std::map<const char*, Sprite> sprites; void update() { //SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0); SDL_RenderClear(renderer); // �ΰ��� �ؽ��� (����, �������̽�) for (auto entity : entities) { if (entity->hasComponent<Direction>()) { } auto position = *entity->getComponent<Position>(); auto image = *entity->getComponent<Image>(); // TODO IMG_LoadTexture(renderer, "path"); // texture* //stretchTextureEx(); //SDL_DestroyTexture(); } // �ΰ��� �ؽ��� �����ؼ� �׸��� (����, �������̽�) SDL_RenderPresent(renderer); } }; #include <fmod.hpp> #pragma comment(lib, "fmod64_vc.lib") #include <map> class SoundSystem : public System { public: FMOD::System* system; FMOD::Channel* channel; std::map<const char*, FMOD::Sound*> map; SoundSystem() : channel(nullptr) { FMOD::System_Create(&system); system->init(64, FMOD_INIT_NORMAL, 0); addComponentType<Sound>(); } ~SoundSystem() { for (auto it = map.begin(); it != map.end(); it++) it->second->release(); system->close(); system->release(); } void loadSound(const char* path, bool isLoop, const char* key) { if (map.find(key) == map.end()) system->createSound(path, isLoop ? FMOD_LOOP_NORMAL : FMOD_DEFAULT, 0, &map[key]); } void playSound(const char* key, float pitch = 1.0f) { system->playSound(map[key], 0, false, &channel); channel->setPitch(pitch); } void update() { for (auto entity : entities) { auto sound = *entity->getComponent<Sound>(); playSound(sound.key); sound.key = nullptr; } } }; // InGame class HumanSystem : public System { public: HumanSystem() { addComponentType<Human>(); } void ready() { for (auto entity : entities) { auto human = *entity->getComponent<Human>(); human.ready(); } } void action() { for (auto entity : entities) { auto human = *entity->getComponent<Human>(); human.action(); } } }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include <SDL.h> #include <SDL_image.h> #pragma comment(lib, "SDL2") #pragma comment(lib, "SDL2main") #pragma comment(lib, "SDL2_image") #include "engine.h" #include <chrono> int main(int argc, char* argv[]) { SDL_Init(SDL_INIT_VIDEO); IMG_Init(IMG_INIT_PNG); SDL_Window* window = SDL_CreateWindow("title", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 1280, 720, 0); SDL_Event event; /////////////////////////////// World world; HumanSystem humanSystem; Gravity gravity(9.8f); Translate translate; LandInspection landInspection(0.5f); ImageSystem imageSystem(window); // �̹��� ���� SoundSystem soundSystem; // ���� ���� world.addSystem(&humanSystem); world.addSystem(&gravity); world.addSystem(&translate); world.addSystem(&landInspection); world.addSystem(&imageSystem); world.addSystem(&soundSystem); auto human0 = world.createEntity(); human0->addComponent(new Direction()); human0->addComponent(new Position()); human0->addComponent(new Velocity()); human0->addComponent(new DeltaPosition()); human0->addComponent(new Move(10.0f)); human0->addComponent(new Jump(10.0f)); human0->addComponent(new Health(5.0f, 5.0f)); human0->addComponent(new Team(0)); human0->addComponent(new Image()); human0->addComponent(new Sound()); human0->addComponent(new Human(human0)); auto human1 = world.createEntity(); human1->addComponent(new Direction(-1)); human1->addComponent(new Position(100.0f, 0.0f)); human1->addComponent(new Velocity()); human1->addComponent(new DeltaPosition()); human1->addComponent(new Move(10.0f)); human1->addComponent(new Jump(10.0f)); human1->addComponent(new Health(5.0f, 5.0f)); human1->addComponent(new Team(1)); human1->addComponent(new Image()); human1->addComponent(new Sound()); human1->addComponent(new Human(human1)); std::chrono::steady_clock::time_point timeForGame; std::chrono::steady_clock::time_point timeForInterface; timeForGame = timeForInterface = std::chrono::steady_clock::now(); std::chrono::milliseconds baseTerm(20); std::chrono::milliseconds termForGame(baseTerm); std::chrono::milliseconds termForInterface(baseTerm); std::chrono::milliseconds zeroSeconds(0); bool inputFlag = false; while (1) { auto now = std::chrono::steady_clock::now(); auto waitingForInterface = std::chrono::duration_cast<std::chrono::milliseconds>(now - timeForInterface) - termForInterface; auto waitingForGame = std::chrono::duration_cast<std::chrono::milliseconds>(now - timeForGame) - termForGame; int value = waitingForInterface >= zeroSeconds ? waitingForGame > waitingForInterface ? 2 : 1 : waitingForGame >= zeroSeconds ? 2 : 0; switch (value) { case 1: // interface imageSystem; soundSystem; break; case 2: // game humanSystem; gravity; translate; landInspection; break; } if (value) { // if (count++ == 500) // 500�� ���� ����Ǿ��°�? // ���� �������� �����ϱ�. continue; } else { // count = 0; } if (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: break; case SDL_KEYDOWN: case SDL_KEYUP: { if (event.key.repeat) break; unsigned int value = 0; switch (event.key.keysym.sym) { case SDLK_LEFT: value = 0; break; case SDLK_RIGHT: value = 1; break; case SDLK_UP: value = 2; break; case SDLK_DOWN: value = 3; break; case SDLK_z: value = 4; break; } auto human = *human0->getComponent<Human>(); human.input(value, event.key.state); break; } } } else { // ������ } } /////////////////////////////// SDL_DestroyWindow(window); IMG_Quit(); SDL_Quit(); return 0; }
true
678d65d023c75a5604e1801a53df1274520c1166
C++
c0untzer0/CppClasses
/CppBasics/ch01/ch01w01.cpp
UTF-8
268
2.609375
3
[]
no_license
// // Created by pjcabrer on 8/19/15. // #include "ch01w01.h" #include <iostream> #include <iomanip> using namespace std; int main() { int x = 5; int y = 7; std::cout << "\n"; std::cout << x + y << " " << x * y; std::cout << "\n"; return 0; }
true
f10c6ad0566e09cdfd6569741ec2c075dcbd834c
C++
Relickus/Chess2016
/CQueen.h
UTF-8
943
3.015625
3
[]
no_license
#ifndef CQUEEN_H #define CQUEEN_H #include "CPiece.h" #include "COLOR.h" /** * Class representing queen piece */ class CQueen : public CPiece { public: CQueen(); /** * Initiates a queen with given parameters * @param color A color of the queen * @param row A row of the queen on a chessboard * @param col A column of the queen on a chessboard */ CQueen(COLOR col,int x, int y); virtual ~CQueen(); /** * Checks available moves for this queen * @param gS Reference to the instance of a game * @return Reference to a list of all possible moves of this queen */ virtual CMoveList & getLegalMoves(const CGameSession & gS); /** * Copies an instance of the queen * @param pcs a pointer to the queen, to be copied * @return a new instance of this queen */ virtual CPiece* copyPiece(const CPiece * pcs) const; }; #endif /* CQUEEN_H */
true
5684097dcf728933d3008049a1af0554df955982
C++
sork777/PortFolio
/Framework/Viewer/Camera.cpp
UHC
2,117
3.046875
3
[]
no_license
#include "Framework.h" #include "Camera.h" Camera::Camera() :position(0, 0, 0) , up(0, 1, 0), right(1, 0, 0), forward(0, 0, 1) , rotation(0, 0, 0) { //׻ ̼ 켱? D3DXMatrixIdentity(&matRotation); D3DXMatrixIdentity(&matView); Rotation(); Move(); } Camera::~Camera() { } void Camera::Position(float x, float y, float z) { Position(Vector3(x, y, z)); } void Camera::Position(Vector3 & vec) { position = vec; //ǥ ->̵ Move(); } void Camera::Position(Vector3 * vec) { *vec = position; } void Camera::Rotation(float x, float y, float z) { Rotation(Vector3(x, y, z)); } void Camera::Rotation(Vector3 & vec) { rotation = vec; Rotation(); } void Camera::Rotation(Vector3 * vec) { *vec = rotation; } void Camera::RotationDegree(float x, float y, float z) { RotationDegree(Vector3(x, y, z)); } void Camera::RotationDegree(Vector3 & vec) { //rotation = vec * Math::PI / 180; //1radian , float Ҽ 8ڸ ű rotation = vec * 0.01745328f; Rotation(); } void Camera::RotationDegree(Vector3 * vec) { //*vec = rotation * 180 / Math::PI; *vec = rotation * 57.29577951f; } void Camera::GetMatrix(Matrix * matrix) { //Ժ memcpy(matrix, &matView, sizeof(Matrix)); } void Camera::Move() { // ٲ ٽ View(); } void Camera::Rotation() { Matrix X, Y, Z; D3DXMatrixRotationX(&X, rotation.x); //Xȸ D3DXMatrixRotationY(&Y, rotation.y); //Yȸ D3DXMatrixRotationZ(&Z, rotation.z); //Zȸ matRotation = X * Y * Z; //İ // ⶧ 2ĭ forward  //forward 0,0,1 . D3DXVec3TransformNormal(&forward, &Vector3(0, 0, 1), &matRotation); D3DXVec3TransformNormal(&right, &Vector3(1, 0, 0), &matRotation); D3DXVec3TransformNormal(&up, &Vector3(0, 1, 0), &matRotation); } void Camera::View() { D3DXMatrixLookAtLH(&matView, &position, &(position + forward), &up); } void Camera::SetMatrix(Matrix & matrix) { memcpy(matView, &matrix, sizeof(Matrix)); }
true
2e0e5c8062451b03a6015fac5f74213d8a819283
C++
LDEchoTeam/ld38
/Projects/PestControl/Source/PestControl/PestBase.cpp
UTF-8
1,616
2.578125
3
[ "MIT" ]
permissive
// Copyright Echo Team 2017 #include "PestControl.h" #include "PestBase.h" // Sets default values APestBase::APestBase() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; } // Called when the game starts or when spawned void APestBase::BeginPlay() { Super::BeginPlay(); } // Called every frame void APestBase::Tick(float DeltaTime) { Super::Tick(DeltaTime); } FVector APestBase::GetNavigationDirection() { FVector DirectVector = NavigationTarget - GetActorLocation(); FVector Indication = DirectVector.GetUnsafeNormal(); FVector Direction = Indication - FVector::DotProduct(NavigationNormal, Indication) * NavigationNormal; return Direction.GetUnsafeNormal(); } float APestBase::GetNavigationDistance() { return FVector::Dist(NavigationTarget, GetActorLocation()); } float APestBase::GetNavigationRange(float minimum, float maximum) { return FMath::Clamp((GetNavigationDistance() - minimum) / (maximum - minimum), 0.0f, 1.0f); } bool APestBase::GetWeightedAverage(TArray<AActor*> actors, float minimum, float maximum, FVector& average) { average.Set(0.0f, 0.0f, 0.0f); float totalWeight = 0.0f; for(AActor* actor : actors) { float Distance = FVector::Dist(actor->GetActorLocation(), GetActorLocation()); float weight = 1.0f - FMath::Clamp((Distance - minimum) / (maximum - minimum), 0.0f, 1.0f); average += actor->GetActorLocation() * weight; totalWeight += weight; } if(totalWeight > 0.0f) { average /= totalWeight; return true; } else { return false; } }
true
7fb01f894d3f0638e7285cae851072d219bc5308
C++
stuhops/cs5500-hw9-rotate-puzzle
/main.cpp
UTF-8
10,175
2.78125
3
[]
no_license
/* Project 1 Rotation Puzzle.cpp : Defines the entry point for the console application. * * Author: Stuart Hopkins (A02080107) * Last updated: 1/24/2018 */ #include <mpi.h> #include <iostream> #include <string> #include <vector> #include "Board.h" #include "Board.cpp" using namespace std; #define MCW MPI_COMM_WORLD // ------------------------------- Functions ---------------------------------------- Board initialize(); vector<Board> prioritizeQueue(vector<Board> queue); void print(string message, vector<int> arr); void print(string message, int x); void printQueue(vector<Board> queue); void printQueueRanks(vector<Board> queue); void printBreak(); // --------------------------------- Main ------------------------------------------- int main(int argc, char **argv) { const int ROWS = 5; const int DIRECTIONS = 4; // N, E, S, W const int ITERS = 3; int rank, size; int data[ROWS * ROWS]; MPI_Init(&argc, &argv); MPI_Comm_rank(MCW, &rank); MPI_Comm_size(MCW, &size); MPI_Request finishedRequest; MPI_Request workRequest; MPI_Status finishedStatus; MPI_Status workStatus; int workFlag = 0; int finished = 0; int primary_board_sum = 0; int num_of_levels = 0; int state1 = 0; int again = 0; std::string history_string = ""; int board_int = 0; Board primary_board; Board curr_board; vector<Board> queue; if(!rank) { MPI_Irecv(&finished, 1, MPI_INT, MPI_ANY_SOURCE, 1, MCW, &finishedRequest); primary_board = initialize(); queue.push_back(primary_board); if (!primary_board.getRank()) { std::cout << "You started with a perfect board." << endl; } else { while (true) { // ----------------------------------------- Master Move ------------------------------------------ for(int a = 0; a < ITERS; a++) { num_of_levels++; std::cout << "Level " << num_of_levels << endl; // if(num_of_levels > 1) { // int test_next_move[2] = {-1, -1}; // assert(!queue[0].isReversal(test_next_move)); // } int queue_length = queue.size(); for(int b = 0; b < queue_length; b++) { for (int i = 0; i < ROWS; i++) { for (int j = 0; j < DIRECTIONS; j++) { state1++; curr_board = queue[0]; int next_move = DIRECTIONS * i + j; int next_move_arr[2] = {next_move / 4, next_move % 4}; if(!curr_board.isReversal(next_move_arr)) { curr_board.move(next_move); queue.push_back(curr_board); if (!curr_board.getRank()) { break; } } } if (!curr_board.getRank()) break; } queue.erase(queue.begin()); if (!curr_board.getRank()) { finished = 1; for(int j = 1; j < size; j++) { MPI_Send(&finished, 1, MPI_INT, j, 1, MCW); } break; } } if (!curr_board.getRank()) break; } if (!curr_board.getRank()) break; queue = prioritizeQueue(queue); if(queue.size() > ROWS * ROWS) queue.resize(ROWS * ROWS); // ------------------------------- Send Work Out ------------------------------------ if(!(num_of_levels % ITERS) || num_of_levels == 1) { if(num_of_levels != ITERS) { // ------------------ Receive -------------------- for(int i = 1; i < size; i++) { // std::cout << "Pre-Wait" << endl; while(true) { MPI_Iprobe(i, 0, MCW, &workFlag, &workStatus); MPI_Test(&finishedRequest, &finished, &finishedStatus); if(finished) { for(int j = 1; j < size; j++) { MPI_Send(&finished, 1, MPI_INT, j, 1, MCW); } break; } else if(workFlag) { workFlag = 0; break; } } if(finished) break; // std::cout << "Post-Wait" << endl; for(int j = 0; j < size; j++) { MPI_Recv(&data, ROWS * ROWS, MPI_INT, i, 0, MCW, MPI_STATUS_IGNORE); queue.push_back(Board(data)); } } queue = prioritizeQueue(queue); queue.resize(size); printQueue(queue); if(num_of_levels / 5 > 10) { std::cout << "HIT LIMIT" << endl; while(true){}; } } if(finished) break; // --------------------- Send ---------------------- vector<int> curr; for(int i = 1; i < size; i++) { curr = queue[0].toVect(); queue.erase(queue.begin()); int to_send[curr.size()]; for(int j = 0; j < curr.size(); j++) { to_send[j] = curr[j]; } MPI_Send(&to_send, ROWS * ROWS, MPI_INT, i, 0, MCW); } curr_board = queue[0]; queue.clear(); queue.push_back(curr_board); } if(finished) break; } } std::cout << "YOU WIN!!! Original Board:" << endl << primary_board.toString() << endl; queue.clear(); int to_send = 0; } // ----------------------------------- Slave Processes ------------------------------------- else { MPI_Irecv(&finished, 1, MPI_INT, 0, 1, MCW, &finishedRequest); while(true) { MPI_Irecv(&data, ROWS * ROWS, MPI_INT, 0, 0, MCW, &workRequest); queue.clear(); while(true) { MPI_Test(&finishedRequest, &finished, &finishedStatus); if(finished) { cout << rank << " Received a finish signal" << endl; break; } MPI_Test(&workRequest, &workFlag, &workStatus); if(workFlag) { workFlag = 0; // cout << rank << " Data Received" << endl; // if(rank == 1) { // std::cout << "Incoming array: " << endl; // for(int i = 0; i < ROWS; i++) { // for(int j = 0; j < ROWS; j++) { // std::cout << data[j + i*ROWS] << " "; // } // std::cout << endl; // } // } queue.push_back(Board(data)); break; } } // cout << rank << endl; // cout << queue[0].toString() << endl; for(int a = 0; a < ITERS; a++) { int queue_length = queue.size(); // std::cout << rank << " starting " << a << "th iteration" << endl; for(int b = 0; b < queue_length; b++) { MPI_Test(&finishedRequest, &finished, &finishedStatus); if(finished) { std::cout << rank << " Received a finish signal" << endl; break; } for (int i = 0; i < ROWS; i++) { for (int j = 0; j < DIRECTIONS; j++) { state1++; curr_board = queue[0]; curr_board.move(DIRECTIONS * i + j); // std::cout << "State " << state1 << " from state " << queue[0].getState() << " History " << curr_board.history() << endl // << curr_board.getRank() << endl // << curr_board.toString() << endl; queue.push_back(curr_board); if (!curr_board.getRank()) { std::cout << rank << " Send Finished Signal" << endl; break; } } if (!curr_board.getRank()) break; } queue.erase(queue.begin()); if (!curr_board.getRank()) { finished = 1; MPI_Send(&finished, 1, MPI_INT, 0, 1, MCW); break; } // queue.resize(size); } queue = prioritizeQueue(queue); if (!curr_board.getRank() || finished) break; // std::cout << rank << " ending " << a << "th iteration" << endl; } if (!curr_board.getRank() || finished) break; // std::cout << rank << " Out of loop " << endl; // std::cout << rank << " Ready to Send" << endl; vector<int> curr; for(int i = 0; i < size; i++) { curr = queue[0].toVect(); queue.erase(queue.begin()); int to_send[curr.size()]; for(int j = 0; j < curr.size(); j++) { to_send[j] = curr[j]; } MPI_Send(&to_send, ROWS * ROWS, MPI_INT, 0, 0, MCW); } } } MPI_Finalize(); return 0; } // --------------------------------------- Functions ----------------------------------------- Board initialize() { int input = 0; Board start1; Board start2; Board start3; Board start4; //start1 set up start1.rotateEast(1); start1.rotateEast(2); //start2 set up start2.rotateNorth(0); start2.rotateSouth(2); //start 3 set up start3.rotateNorth(2); start3.rotateSouth(0); start3.rotateEast(0); start3.rotateEast(2); //start 4 set up start4.makeBoard(8); //Print out the to the terminal to give the user options of boards to start from. std::cout << endl << "Option 1: " << endl << start1.toString() << endl; std::cout << endl << "Option 2: " << endl << start2.toString() << endl; std::cout << endl << "Option 3: " << endl << start3.toString() << endl; std::cout << endl << "Option 4: " << endl << start4.toString() << endl; std::cout << "Please enter the number of the board you want to start with: " << endl; while (true) { std::cin >> input; if (input >= 1 && input <= 4) break; std::cout << "You have entered an incorrect value please enter a valid number of option: "; } switch (input) { case 1: return start1; case 2: return start2; case 3: return start3; case 4: return start4; } return start1; } vector<Board> prioritizeQueue(vector<Board> queue) { bool flag = false; vector<Board> new_queue; new_queue.push_back(queue[0]); for(int i = 1; i < queue.size(); i++) { flag = false; for(int j = 0; j < new_queue.size(); j++) { // cout << endl << queue[i].getRank() << endl; if(queue[i].getRank() < new_queue[j].getRank()) { flag = true; new_queue.insert(new_queue.begin() + j, queue[i]); break; } } if(!flag) { new_queue.push_back(queue[i]); } } return new_queue; } // Print functions void print(string message, vector<int> vect) { cout << message << ": " << endl; cout << vect[0]; for(int i = 1; i < vect.size(); i++) { cout << ", " << vect[i]; } cout << endl; } void print(string message, int x) { cout << message << ": " << x << endl; } void printQueue(vector<Board> queue) { printBreak(); cout << "Queue Ranks and Boards: " << endl; for(int i = 0; i < queue.size(); i++) { cout << queue[i].getRank() << endl << queue[i].history() << endl << queue[i].toString() << endl << endl; } printBreak(); } void printQueueRanks(vector<Board> queue) { printBreak(); cout << endl << "Queue Ranks: " << endl; for(int i = 0; i < queue.size(); i++) { cout << queue[i].getRank() << ", "; } printBreak(); } void printBreak() { cout << "\n--------------------------------\n"; }
true
9adeef20699848b2c72947fa5326d1762d6f6a36
C++
Suhailkhn/Leetcode
/Easy/CountPrimes/main.cpp
UTF-8
594
3.078125
3
[]
no_license
#include <stdio.h> class Solution { public: int countPrimes(int n) { std::vector<bool> isPrime(n + 1, true); for(long i = 2; i < n; ++i) { if(i != 2 && i % 2 == 0) continue; for(long j = i*i; j <= n; j += i) { isPrime[j] = false; } } int count = 0; for(int i = 2; i < n; ++i) { if(isPrime[i]) ++count; } return count; } }; int main(int argc, char **argv) { printf("hello world\n"); return 0; }
true
448edb2d53739bd3e4430eff21c6ecd316247022
C++
TIYASARIT/Basic-C-
/Pointers_1/main.cpp
UTF-8
456
3.453125
3
[]
no_license
#include <iostream> using namespace std; int main() { int *pt, var1; var1 = 10; pt = &var1; cout << "Address of var1 = " << &var1 << endl; cout << "The value of pointer variable = " << pt<< endl; /* You have already declared pointer variable , just the pointer variable will indicate the address*/ cout << "The value that the pointer variable points to = " <<*pt<< endl; /* dereferencing*/ return 0; }
true
eee23d9e93236af67caa2c86ef08c9bab87afd27
C++
kosekitau/aizu
/1_4_d.cpp
UTF-8
351
2.78125
3
[]
no_license
#include <iostream> #include <cstdio> int main(){ int n,tmp; int min=1000000; int max=-1000000; long long sum=0; scanf("%d",&n); for(int i=0;i<n;i++){ scanf("%d", &tmp); sum+=tmp; if(min > tmp) min=tmp; if(max < tmp) max=tmp; } std::cout <<min<<' '<<max<<' '<<sum<<'\n'; return 0; }
true
64a3fbde882ab7bb856716a5ed2c33083cb366ea
C++
GiovanniDicanio/ReadStringsFromRegistry
/ReadStringFromRegistry/RegistryReadString.cpp
UTF-8
2,732
2.890625
3
[ "MIT" ]
permissive
//////////////////////////////////////////////////////////////////////////////// // // FILE: RegistryReadString.cpp // // DESC: Implementation of the RegistryGetString() function // // Copyright (C) by Giovanni Dicanio. All Rights Reserved. // //////////////////////////////////////////////////////////////////////////////// #include "RegistryReadString.h" // Module header #include <Windows.h> // Win32 SDK #include <atldef.h> // Some ATL stuff namespace win32 { CString RegistryGetString( _In_ HKEY key, _In_opt_ PCWSTR subKey, _In_opt_ PCWSTR valueName ) { // // Try getting the size of the string value to read, // to properly allocate a buffer for the string // DWORD keyType = 0; DWORD dataSize = 0; const DWORD flags = RRF_RT_REG_SZ; // Only read strings (REG_SZ) LONG result = ::RegGetValue( key, subKey, valueName, flags, &keyType, nullptr, // pvData == nullptr --> Request buffer size for string &dataSize); if (result != ERROR_SUCCESS) { // Error: throw an exception to signal that AtlThrow(HRESULT_FROM_WIN32(result)); } // Make sure we are reading a REG_SZ ATLASSERT(keyType == REG_SZ); // // Allocate enough memory to store the text // CString text; const DWORD bufferLength = dataSize / sizeof(WCHAR); // length in WCHAR's WCHAR* const textBuffer = text.GetBuffer(bufferLength); ATLASSERT(textBuffer != nullptr); // // Read that string value text from the Windows registry // result = ::RegGetValue( key, subKey, valueName, flags, nullptr, textBuffer, // Write string in this destination buffer &dataSize); if (result != ERROR_SUCCESS) { // Error AtlThrow(HRESULT_FROM_WIN32(result)); } // // Recalculate string buffer length, since it seems in the second call // to RegGetValue() (when a valid buffer pointer is passed to // that function), the returned dataSize is *different* (smaller) // than in the previous call. // // See this question on Stack Overflow: // http://stackoverflow.com/q/29223180/1629821 // const DWORD actualStringLength = dataSize / sizeof(WCHAR); // -1 to exclude the terminating NUL text.ReleaseBufferSetLength(actualStringLength - 1); // All right, return text read from the registry return text; } } // namespace win32
true
2d8c57a714dda28ffbc0a1bf776e0d6032c40acb
C++
billpwchan/COMP-2012-Programs
/adt-program/Program/btree.h
UTF-8
709
3.65625
4
[]
no_license
#include <iostream> /* File: btree.h */ using namespace std; template <typename T> class btree { private: struct btree_node // A node in a binary tree { T data; btree_node* left; // Left sub-tree or called left child btree_node* right; // Right sub-tree or called right child btree_node(const T& x) : data(x), left(0), right(0) { }; }; btree_node* root; public: btree() : root(0) { } ~btree(); bool is_empty() const { return root == 0; } bool contains(const T&) const; void print(ostream& os = cout) const; void insert(const T&); // Insert an item with a policy void remove(const T&); // Remove an item };
true
eecddd8df42294f76c093da5698f3bbf26a67b87
C++
Ahtisham-Shakir/DS_With_CPP
/Strings/Length.cpp
UTF-8
378
3.671875
4
[ "MIT" ]
permissive
#include <iostream> using namespace std; class temp { private: char str[20], i; public: void in() { cout << "Enter String: "; cin >> str; } int len() { for (i = 0; str[i] != '\0'; i++) ; return i; } }; int main() { temp obj; obj.in(); cout << "Lenth of the String is= " << obj.len() << endl; }
true
88d7ecf20c5a0b71a1e35c384c627c624c1f37d7
C++
Thalesgm/Projeto_les_v1.0
/drive_les_v1.cpp
UTF-8
975
2.90625
3
[]
no_license
// Para compilar: g++ -Wall -pedantic drive_les_v1.cpp les_v1.cpp -o drive_les_v1 #include "les_v1.h" #include <iostream> using std::cout; int main ( void ) { SNPtr pHead = NULL;// nullptr; bool _empty = empty( pHead); if(_empty){ cout << "Empty List\n"; } else{ cout << "Not Empty List\n"; } pushFront( pHead, 1 ); pushFront( pHead, 2 ); pushFront( pHead, 3 ); pushFront( pHead, 4 ); pushFront( pHead, 5 ); pushBack( pHead, 5 ); print(pHead); cout << "Lenght of list above:" << length(pHead) << "\n"; int first; front(pHead, first); cout << "First element of list above:" << first << "\n"; int last; back(pHead, last); cout << "Last element of list above:" << last << "\n"; clear(pHead); _empty = empty( pHead); if(_empty){ cout << "Empty List\n"; } else{ cout << "Not Empty List\n"; } cout << "\n\n>>> Normal exiting...\n"; return EXIT_SUCCESS; }
true
f20b0f26d7db99a9fa0df60b8410f153b8fdb5bc
C++
asengsaragih/PBS-ASSESMENT-2
/5/5.ino
UTF-8
3,439
2.71875
3
[]
no_license
#include <Keypad.h> const byte ROWS = 4; //four rows const byte COLS = 3; //three columns char keys[ROWS][COLS] = { {'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}, {'*', '0', '#'} }; byte rowPins[ROWS] = {A1, A2, A3, A4}; //connect to the row pinouts of the keypad byte colPins[COLS] = {11, 12, 13}; //connect to the column pinouts of the keypad Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS ); int a = 10; int b = 9; int c = 8; int d = 7; int e = 6; int f = 5; int g = 4; void setup() { // put your setup code here, to run once: pinMode(a, OUTPUT); pinMode(b, OUTPUT); pinMode(c, OUTPUT); pinMode(d, OUTPUT); pinMode(e, OUTPUT); pinMode(f, OUTPUT); pinMode(g, OUTPUT); Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: char key = keypad.getKey(); if (key == '0'){ Serial.println(key); digitalWrite(a,HIGH); digitalWrite(b,HIGH); digitalWrite(c,HIGH); digitalWrite(d,HIGH); digitalWrite(e,HIGH); digitalWrite(f,HIGH); digitalWrite(g,LOW); } if (key == '1'){ Serial.println(key); digitalWrite(a,LOW); digitalWrite(b,HIGH); digitalWrite(c,HIGH); digitalWrite(d,LOW); digitalWrite(e,LOW); digitalWrite(f,LOW); digitalWrite(g,LOW); } if (key == '2'){ Serial.println(key); digitalWrite(a,HIGH); digitalWrite(b,HIGH); digitalWrite(c,LOW); digitalWrite(d,HIGH); digitalWrite(e,HIGH); digitalWrite(f,LOW); digitalWrite(g,HIGH); } if (key == '3'){ Serial.println(key); digitalWrite(a,HIGH); digitalWrite(b,HIGH); digitalWrite(c,HIGH); digitalWrite(d,HIGH); digitalWrite(e,LOW); digitalWrite(f,LOW); digitalWrite(g,HIGH); } if (key == '4'){ Serial.println(key); digitalWrite(a,LOW); digitalWrite(b,HIGH); digitalWrite(c,HIGH); digitalWrite(d,LOW); digitalWrite(e,LOW); digitalWrite(f,HIGH); digitalWrite(g,HIGH); } if (key == '5'){ Serial.println(key); digitalWrite(a,HIGH); digitalWrite(b,LOW); digitalWrite(c,HIGH); digitalWrite(d,HIGH); digitalWrite(e,LOW); digitalWrite(f,HIGH); digitalWrite(g,HIGH); } if (key == '6'){ Serial.println(key); digitalWrite(a,HIGH); digitalWrite(b,LOW); digitalWrite(c,HIGH); digitalWrite(d,HIGH); digitalWrite(e,HIGH); digitalWrite(f,HIGH); digitalWrite(g,HIGH); } if (key == '7'){ Serial.println(key); digitalWrite(a,HIGH); digitalWrite(b,HIGH); digitalWrite(c,HIGH); digitalWrite(d,LOW); digitalWrite(e,LOW); digitalWrite(f,LOW); digitalWrite(g,LOW); } if (key == '8'){ Serial.println(key); digitalWrite(a,HIGH); digitalWrite(b,HIGH); digitalWrite(c,HIGH); digitalWrite(d,HIGH); digitalWrite(e,HIGH); digitalWrite(f,HIGH); digitalWrite(g,HIGH); } if (key == '9'){ Serial.println(key); digitalWrite(a,HIGH); digitalWrite(b,HIGH); digitalWrite(c,HIGH); digitalWrite(d,HIGH); digitalWrite(e,LOW); digitalWrite(f,HIGH); digitalWrite(g,HIGH); } }
true
e780ad445964667b861eac131130b4aa81662cd2
C++
lijingpeng/ac
/icpcscore_p3325.cc
UTF-8
408
2.84375
3
[]
no_license
#include <iostream> using namespace std; int main() { int n; while(cin >> n && n) { int min = 2000, max = 0, t, sum = 0; for(int i = 0; i < n; i++) { cin >> t; if(t > max) max = t; if(t < min) min = t; sum += t; } cout << (sum - min - max) / (n - 2) << endl; } return 0; }
true
89afe102754401f7069e6c495976d3d33185ec96
C++
dickynovanto1103/CP
/Online Judges/SPOJ/Graph/LCA/lca.cpp
UTF-8
5,022
2.671875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; #define inf 1000000000 #define unvisited -1 #define visited 1 #define eps 1e-9 #define pb push_back typedef long long ll; typedef vector<int> vi; typedef pair<int,int> ii; typedef vector<ii> vii; const int maxn = 100010; vector<vi> AdjList; int L[2*maxn], H[2*maxn], E[2*maxn], idx; void dfs(int cur, int depth) { H[cur] = idx; E[idx] = cur; L[idx++] = depth; for (int i = 0; i < AdjList[cur].size(); i++) { dfs(AdjList[cur][i], depth+1); E[idx] = cur; // backtrack to current node L[idx++] = depth; } } void buildRMQ() { idx = 0; memset(H, -1, sizeof H); dfs(0, 0); // we assume that the root is at index 0 } class SegmentTree { // the segment tree is stored like a heap array private: vi st, A; // recall that vi is: typedef vector<int> vi; int n; int left (int p) { return p << 1; } // same as binary heap operations int right(int p) { return (p << 1) + 1; } void build(int p, int L, int R) { // O(n log n) if (L == R) // as L == R, either one is fine st[p] = L; // store the index else { // recursively compute the values build(left(p) , L , (L + R) / 2); build(right(p), (L + R) / 2 + 1, R ); int p1 = st[left(p)], p2 = st[right(p)]; st[p] = (A[p1] <= A[p2]) ? p1 : p2; } } int rmq(int p, int L, int R, int i, int j) { // O(log n) if (i > R || j < L) return -1; // current segment outside query range if (L >= i && R <= j) return st[p]; // inside query range // compute the min position in the left and right part of the interval int p1 = rmq(left(p) , L , (L+R) / 2, i, j); int p2 = rmq(right(p), (L+R) / 2 + 1, R , i, j); if (p1 == -1) return p2; // if we try to access segment outside query if (p2 == -1) return p1; // same as above return (A[p1] <= A[p2]) ? p1 : p2; } // as as in build routine int update_point(int p, int L, int R, int idx, int new_value) { // this update code is still preliminary, i == j // must be able to update range in the future! int i = idx, j = idx; // if the current interval does not intersect // the update interval, return this st node value! if (i > R || j < L) return st[p]; // if the current interval is included in the update range, // update that st[node] if (L == i && R == j) { A[i] = new_value; // update the underlying array return st[p] = L; // this index } // compute the minimum pition in the // left and right part of the interval int p1, p2; p1 = update_point(left(p) , L , (L + R) / 2, idx, new_value); p2 = update_point(right(p), (L + R) / 2 + 1, R , idx, new_value); // return the pition where the overall minimum is return st[p] = (A[p1] <= A[p2]) ? p1 : p2; } public: SegmentTree(const vi &_A) { A = _A; n = (int)A.size(); // copy content for local usage st.assign(4 * n, 0); // create large enough vector of zeroes build(1, 0, n - 1); // recursive build } int rmq(int i, int j) { return rmq(1, 0, n - 1, i, j); } // overloading int update_point(int idx, int new_value) { return update_point(1, 0, n - 1, idx, new_value); } }; int main() { int n,i,j,a,b, tc; scanf("%d",&tc); for(int tt=1;tt<=tc;tt++){ printf("Case %d:\n",tt); scanf("%d",&n); AdjList.assign(n,vi()); for(i=0;i<n;i++){ int counter; scanf("%d",&counter); while(counter--){scanf("%d",&a); a--; AdjList[i].pb(a);} //scanf("%d %d",&a,&b); a--; b--; AdjList[a].pb(b); } buildRMQ(); //printf("test\n"); vi A; for(i=0;i<2*n;i++){A.pb(L[i]);} SegmentTree s(A); /*printf("H:"); for(i=0;i<2*n;i++){printf(" %d",H[i]);} printf("\n"); printf("E:"); for(i=0;i<2*n;i++){printf(" %d",E[i]);} printf("\n"); printf("L:"); for(i=0;i<2*n;i++){printf(" %d",L[i]);} printf("\n");*/ int q; scanf("%d",&q); while(q--){ scanf("%d %d",&a,&b); a--; b--; //printf("awal a: %d b: %d\n",a,b); int nilaiAcuan = a; if(H[a] > H[b]){ swap(a,b); nilaiAcuan = b; //printf("a: %d b: %d\n",a,b); } //printf("a: %d b: %d\n",a,b); int idx1 = H[a], idx2 = H[b]; //printf("idx1: %d idx2: %d\n",idx1,idx2); int idx = s.rmq(idx1,idx2); //printf("idx: %d\n",idx); int ans = E[idx]; /*printf("nilai acuan: %d\n",nilaiAcuan); printf("ans: %d\n",ans);*/ /*if(ans==nilaiAcuan){printf("TIDAK\n");} else{printf("YA\n");}*/ printf("%d\n",ans+1); //printf("%d\n",E[idx]+1); } } return 0; }
true
2dad6498ed08254897ddaaa8964cc236c9e92dca
C++
monkeydminh49/JackAdventure
/JackAdventure/Sources/GameObjects/Animation2.cpp
UTF-8
968
2.609375
3
[]
no_license
#include "Animation2.h" Animation2::Animation2(sf::Texture& texture, sf::Vector2i frameNum, float frameTime, int frameTotals): Animation(texture,frameNum,frameTime) { m_frameTotals = frameTotals; m_currentFrameCount = 0; this->setScale(-1, 1); } void Animation2::Update(float deltaTime) { if ((m_currentFrame.x == (m_frameNum.x - 1)) && m_modeStopAtEndFrame&&m_currentFrameCount==m_frameTotals-1) { return; } m_currentTime += deltaTime; if (m_currentTime >= m_frameTime) { m_currentFrame.x++; m_currentFrameCount++; if ((m_currentFrame.x == m_frameNum.x)||((m_currentFrame.y*m_frameNum.x+m_currentFrame.x)==m_frameTotals)) { m_currentFrame.x = 0; m_currentFrame.y++; } if (m_currentFrame.y == m_frameNum.y) { m_currentFrame.y = 0; m_currentFrameCount = 0; m_currentFrame.x = 0; } CalculateRectUV(); ApplyRect(); m_currentTime -= m_frameTime; } } void Animation2::Reset() { Animation::Reset(); m_currentFrameCount = 0; }
true
27e86fb7581632372c6b26e2545e7c356be2d0d6
C++
leodelmas/csia_car_park
/project/src/model/Seller.h
UTF-8
586
2.859375
3
[]
no_license
/////////////////////////////////////////////////////////// // Author: Sorlin Sylvain // Class: Seller // Brief: Header file /////////////////////////////////////////////////////////// #pragma once #include <string> class Seller { public: Seller(); ~Seller(); //Id int& getId(); void setId(int p_Id); //LastName const char* getLastName(); void setLastName(const char* p_LastName); //FirstName const char* getFirstName(); void setFirstName(const char* p_FirstName); private: int m_Id; std::string m_LastName; std::string m_FirstName; };
true
2a0df54112e135d64af6e5f2ae9e73198146928b
C++
Alakia/Retinax
/retinex.cpp
GB18030
11,837
2.671875
3
[]
no_license
#include"stdafx.h" #include "retinex.h" #include <opencv2\core\core.hpp> #include <opencv2\opencv.hpp> #include <opencv2\highgui\highgui.hpp> #include <imgproc\imgproc_c.h> #include <imgproc\imgproc.hpp> #include <math.h> using namespace cv; #define USE_EXACT_SIGMA #define pc(image, x, y, c) image->imageData[(image->widthStep * y) + (image->nChannels * x) + c] #define INT_PREC 1024.0 #define INT_PREC_BITS 10 inline double int2double(int x) { return (double)x / INT_PREC; } inline int double2int(double x) { return (int)(x * INT_PREC + 0.5); } inline int int2smallint(int x) { return (x >> INT_PREC_BITS); } inline int int2bigint(int x) { return (x << INT_PREC_BITS); } typedef struct { int width; int height; char pImgData[400*500]; int Img_flag; }t_ReturnInfo; t_ReturnInfo return_info; //IplImage *A, *fA, *fB, *fC; // CreateKernel // // Summary: // Creates a normalized 1 dimensional gaussian kernel. // // Arguments: // sigma - the standard deviation of the gaussian kernel. // // Returns: // double* - an array of values of length ((6*sigma)/2) * 2 + 1. // // Note: // Caller is responsable for deleting the kernel. int* CreateKernel(double sigma) { int i, x; int filter_size; //˹ڴС double* filter; int* kernel; double sum; // Reject unreasonable demands if ( sigma > 300 ) sigma = 200; // get needed filter size (enforce oddness) filter_size = (int)floor(sigma*6) / 2; filter_size = filter_size * 2 + 1; // Allocate kernel space filter = new double[filter_size]; kernel = new int[filter_size]; // Calculate exponential openCV getGaussianKernel() // filter_size*1άĸ˹˲ sum = 0; for (i = 0; i < filter_size; i++) { x = i - (filter_size / 2); filter[i] = exp( -(x*x) / (2*sigma*sigma) ); sum += filter[i]; } // Normalize for (i = 0; i < filter_size; i++) { filter[i] /= sum; kernel[i] = double2int(filter[i]); } delete filter; return kernel; } // // CreateFastKernel // // Summary: // Creates a faster gaussian kernal using integers that // approximate floating point (leftshifted by 8 bits) // // Arguments: // sigma - the standard deviation of the gaussian kernel. // // Returns: // int* - an array of values of length ((6*sigma)/2) * 2 + 1. // // Note: // Caller is responsable for deleting the kernel. // int* CreateFastKernel(double sigma) { double* fp_kernel; int* kernel; int i, filter_size; // Reject unreasonable demands if ( sigma > 300 ) sigma = 200; // get needed filter size (enforce oddness) filter_size = (int)floor(sigma*6) / 2; filter_size = filter_size * 2 + 1; // Allocate kernel space kernel = new int[filter_size]; //fp_kernel = CreateKernel(sigma); for (i = 0; i < filter_size; i++) kernel[i] = double2int(fp_kernel[i]); delete fp_kernel; return kernel; } // // FilterGaussian // // Summary: // Performs a gaussian convolution for a value of sigma that is equal // in both directions. // // Arguments: // img - the image to be filtered in place. // sigma - the standard deviation of the gaussian kernel to use. // void FilterGaussian(IplImage* img, double sigma) { int i, j, k, source, filter_size; int* kernel; IplImage* temp; int v1, v2, v3; // Reject unreasonable demands if ( sigma > 300 ) sigma = 200; // get needed filter size (enforce oddness) filter_size = (int)floor(sigma*6) / 2; filter_size = filter_size * 2 + 1; //kernel = CreateFastKernel(sigma); kernel = CreateKernel(sigma); temp = cvCreateImage(cvSize(img->width, img->height), img->depth, img->nChannels); // filter x axis for (j = 0; j < temp->height; j++) for (i = 0; i < temp->width; i++) { // inner loop has been unrolled v1 = v2 = v3 = 0; for (k = 0; k < filter_size; k++) { source = i + filter_size / 2 - k; if (source < 0) source *= -1; if (source > img->width - 1) source = 2*(img->width - 1) - source; //if (source < 0) source *= -1; v1 += kernel[k] * (unsigned char)pc(img, source, j, 0); if (img->nChannels == 1) continue; v2 += kernel[k] * (unsigned char)pc(img, source, j, 1); v3 += kernel[k] * (unsigned char)pc(img, source, j, 2); } // set value and move on pc(temp, i, j, 0) = (char)int2smallint(v1); if (img->nChannels == 1) continue; pc(temp, i, j, 1) = (char)int2smallint(v2); pc(temp, i, j, 2) = (char)int2smallint(v3); } // filter y axis for (j = 0; j < img->height; j++) for (i = 0; i < img->width; i++) { v1 = v2 = v3 = 0; for (k = 0; k < filter_size; k++) { source = j + filter_size / 2 - k; if (source < 0) source *= -1; if (source > temp->height - 1) source = 2*(temp->height - 1) - source; //if (source < 0) source *= -1; v1 += kernel[k] * (unsigned char)pc(temp, i, source, 0); if (img->nChannels == 1) continue; v2 += kernel[k] * (unsigned char)pc(temp, i, source, 1); v3 += kernel[k] * (unsigned char)pc(temp, i, source, 2); } // set value and move on pc(img, i, j, 0) = (char)int2smallint(v1); if (img->nChannels == 1) continue; pc(img, i, j, 1) = (char)int2smallint(v2); pc(img, i, j, 2) = (char)int2smallint(v3); } cvReleaseImage( &temp ); delete kernel; } // // FastFilter // // Summary: // Performs gaussian convolution of any size sigma very fast by using // both image pyramids and seperable filters. Recursion is used. // // Arguments: // img - an IplImage to be filtered in place. void Subsample(IplImage *src, IplImage *dest, int cols, int rows) { int i,j; char *pSrc = src->imageData, *pDst = dest->imageData; for (i=0;i<rows;i+=2) { for (j=0;j<cols;j+=2) { pDst[0] = pSrc[0]; pDst ++; pSrc += 2; } pDst += cols/2 %4; pSrc += cols; } } void FastFilter(IplImage *img, double sigma, int flag = 0) { int filter_size; int width = img->width, height = img->height; // Reject unreasonable demands if ( sigma > 700 ) sigma = 200; // get needed filter size (enforce oddness) filter_size = (int)floor(sigma*6) / 2; filter_size = filter_size * 2 + 1; // If 3 sigma is less than a pixel, why bother (ie sigma < 2/3) if(filter_size < 3) return ; // Filter, or downsample and recurse if (filter_size <= 13) { double time = (double)getTickCount(); FilterGaussian(img, sigma); } else { if (img->width < 2 || img->height < 2) return; IplImage* sub_img = cvCreateImage(cvSize(img->width / 2, img->height / 2), img->depth, img->nChannels); //IplImage* sub_img = cvCreateImage(cvSize(img->width / 2, img->height / 2), 8, 1); //Subsample(img, sub_img); cvPyrDown( img, sub_img ); FastFilter( sub_img, sigma / 2.0); cvResize( sub_img, img, CV_INTER_LINEAR ); cvReleaseImage( &sub_img ); } } void auto_level(IplImage* src, int width, int height, double avg) { int i, j, total_num = 0, Avg = 0; total_num = width * height; // ֱͼͳ int histData[1] = {256}; int map_hist[256] = {0}; CvHistogram *hist = cvCreateHist(1, histData, CV_HIST_ARRAY); cvCalcHist( &src, hist );//㵥ͨͼֱͼ // ֱͼ̬ int max_bin, min_bin, delta_bin, mean_num; int stdSum0 = 0, stdSum1 = 0; unsigned char *pt; float std = 0; //// 2015.8 ͼֵ i = 0; while(i < 256) { Avg += hist->mat.data.fl[i]*i; stdSum1 += hist->mat.data.fl[i]; i++; } Avg = Avg / total_num; // 2015.8 ͼ񷽲 std = sum( (x_i - x_avg)*(x_i - x_avg) ) i = 0; while(i < 256)//widthΪ8ı { stdSum0 = stdSum0 + (i - avg)*(i - avg)*hist->mat.data.fl[i]; i++; } std = sqrt((float)(stdSum0 / total_num)); // 2015.8 ̬ max_bin = (int)(avg + 3*std); min_bin = (int)(avg - 3*std); // ԭʼͼСbin delta_bin = max_bin - min_bin; // map = 255*(src - min)/(max - min) for( i = 0; i < 256; i++ ) { if( i <= min_bin ) map_hist[i] = 0; else if( i >= max_bin ) map_hist[i] = 255; else map_hist[i] = 255*(i - min_bin) / delta_bin; } // 챷ͼmap_hist[256]ǿͼ //ֱsrc޸ֵǿͼ j = 0; while(j < total_num) { src->imageData[j] = map_hist[src->imageData[j]]; j++; } } /********************************************************************** * MultiScaleRetinex ͨ * Summary: * Multiscale retinex restoration. The image and a set of filtered images are * converted to the log domain and subtracted from the original with some set * of weights. Typicaly called with three equaly weighted scales of fine, * medium and wide standard deviations. * * Arguments: * img - an IplImage to be enhanced in place. * sigma - the standard deviation of the gaussian kernal used to filter. * gain - the factor by which to scale the image back into visable range. * offset - an offset similar to the gain. ********************************************************************/ void MSR(IplImage *img, int scales, double *weights, double *sigmas) { int i=0, j = 0, r = 0, c = 0, filter_size = 0; IplImage *A, *fA, *fB, *fC, *subsample; double time; int total = img->height * img->width; //t_ReturnInfo return_img; // Initialize temp images int img_width = img->width, img_height = img->height; fA = cvCreateImage(cvSize(img_width, img_height), IPL_DEPTH_32F, img->nChannels); fB = cvCreateImage(cvSize(img_width, img_height), IPL_DEPTH_32F, img->nChannels); fC = cvCreateImage(cvSize(img_width, img_height), IPL_DEPTH_32F, img->nChannels); // Compute log image ImageAvg = cvAvg(img); cvConvert( img, fA ); float* p=(float*)(fA->imageData); for( r = 0; r < img_height; r++) for( c = 0; c < img_width; c++) { if(0.0f == p[r * img_width + c]) p[r * img_width + c] = 1; }//ԭͼΪ0ֵΪ1 cvLog( fA,fB); //ԭͼ // Filter at each scale for (i = 0; i < scales;i++) { A = cvCloneImage( img ); FastFilter( A, sigmas[i]); cvConvert( A, fA ); for(r = 0;r < img_height; r++) for(c = 0;c < img_width; c++) { if(0.0f == p[r*img_width+c]) p[r*img_width+c] = 1; }//˲ͼΪ0ֵΪ1 cvLog( fA, fC ); // Compute weighted difference cvScale( fC, fC, weights[i] ); cvSub( fB, fC, fB ); } //ʹͼֵ߶Ⱦ //float* pA = (float*)fA->imageData; //for( i = 0; i<total; i++) //{ // pA[i] = (float)ImageAvg.val[0]; //} //cvLog( fA, fC ); //cvScale(fC, fC, weights[2] ); //cvSub( fB, fC, fB ); // Restore cvConvertScale( fB, img, 400, 128); // auto_level // auto_level(img, img_width, img_height, ImageAvg.val[0]); // Release temp images cvReleaseImage( &A ); cvReleaseImage( &fA ); cvReleaseImage( &fB ); cvReleaseImage( &fC ); }
true
62af90b916b6b37e97b2460b2e78326610b3716e
C++
herox25000/oathx-ogrex-editor
/YouLe/You_系统模块/系统模块/辅助工具/机器人添加/Include/DataStorage.h
GB18030
1,669
2.71875
3
[]
no_license
#ifndef DATA_STORAGE_HEAD_FILE #define DATA_STORAGE_HEAD_FILE #include "ComService.h" #pragma once ////////////////////////////////////////////////////////////////////////// //ṹ嶨 //ݶͷ struct tagDataHead { WORD wDataSize; //ݴС WORD wIdentifier; //ͱʶ DWORD dwInsertTime; //ʱ }; //Ϣ struct tagBurthenInfo { DWORD dwDataSize; //ݴС DWORD dwBufferSize; // DWORD dwDataPacketCount; //ݰĿ }; ////////////////////////////////////////////////////////////////////////// //ݴ洢 class COM_SERVICE_CLASS CDataStorage { //ݱ protected: DWORD m_dwDataSize; //ݴС DWORD m_dwBufferSize; // DWORD m_dwInsertPos; //ݲλ DWORD m_dwTerminalPos; //ݽλ DWORD m_dwDataQueryPos; //ݲѯλ DWORD m_dwDataPacketCount; //ݰĿ BYTE * m_pDataStorageBuffer; //ָ // public: //캯 CDataStorage(void); // virtual ~CDataStorage(void); //ܺ public: //Ϣ bool GetBurthenInfo(tagBurthenInfo & BurthenInfo); // bool AddData(WORD wIdentifier, void * const pBuffer, WORD wDataSize); //ȡ bool GetData(tagDataHead & DataHead, void * pBuffer, WORD wBufferSize); //ɾ void RemoveData(bool bFreeMemroy); }; ////////////////////////////////////////////////////////////////////////// #endif
true
c7ee7e02f6d842467057169221255972e7eb0468
C++
53730512/chess_server
/server_changsha/src/majhong/hongzhong/zhong_algo.h
UTF-8
2,969
2.515625
3
[]
no_license
 #ifndef __MJ_ZHONG_H_ #define __MJ_ZHONG_H_ //////////////////////////////////////////////////////////////////////////////// #include "../base/algo_base.h" //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// class zhong_algo : public algo_base{ int m_ding_count; public: inline zhong_algo(const void* context = 0) : algo_base(context){ } //判断是否听牌 bool is_ting() override{ return false; } //重载吃碰判断函数 virtual bool enable(int v, mj_type type) override{ if (type == type_shun)//转转不允许吃牌 return false; else if(v == ghost()) return false; return peng(m_hand, v); } //判断是否胡牌 bool finish (int v, bool zimo = false, bool first = false, mj_gang gang = gang_not) override{ if (m_hand == 0 || !valid(v)){ return false; } //初始化内部数据 init(v, zimo, gang); m_value = 0; m_style = 0; //如果为7对胡牌则判断附加番型 bool bwin = is_double(m_hand, v) || hupai(m_hand, v, zimo, true); if (bwin){ if(zimo) { m_value = 2; m_style |= hu_zimo; } else { m_value = 1; m_style |= hu_ping; } } return bwin; } //判断是否可杠牌 bool enable(int v, bool zimo) override{ if(v == ghost()) return false; bool result = gang(m_hand, v); if (!result){ //如果不是自摸且不听牌 if (!zimo ){ return false; } set_t *p = m_used; while (p->first){ if (p->type != type_ke){ continue; } if (p->first == v){ result = true; break; } p++; //移动到下个数据区 } return result; } return result; } private: void init(int v, bool zimo, mj_gang gang) override{ int g = ghost(); int n = m_hand[g]; if ((zimo || gang)&& v == g){ n += 1; } m_rascal_count = n; m_zimo = zimo; m_gang = gang; m_style = m_value = 0; } //特殊番型(七小对) bool is_double(int hand[38], int hu){ int data[38]; memcpy(data, hand, sizeof(data)); data[hu]++; int n = 0; int m = 0, g = ghost(); for (int i = 0; i < 38; i++){ n += data[i]; if (i == g){ continue; } if (data[i] % 2 == 1){ m++; } else { continue; } } if (n != 14){ return false; } n = m_rascal_count; int r = reserved() + used(); if (m + r > n){ return false; } if ((n - m - r) % 2){ return false; } if (m_rascal_count > 0) m_double = (m == 0); return true; } private: //是否为自摸 bool zimo() const{ return (m_gang || m_zimo); } //清除明牌牌组 virtual void clear(){ algo_base::clear(); } private: int confirm(const int hand[38], form_t &r, int v) override{ return 1; } }; //////////////////////////////////////////////////////////////////////////////// #endif //__MJ_TAOJIANG_H_ ////////////////////////////////////////////////////////////////////////////////
true
a45a33604d7f02d61b550ad2ae411891fb730598
C++
capacitypp/GLCraft
/BlockWood.cpp
UTF-8
1,419
2.65625
3
[]
no_license
#include "BlockWood.h" #include "DisplayListManager.h" #include "TextureManager.h" #include <GL/glut.h> using namespace std; void BlockWood::readTextures(void) { texture1 = Image("texture/block/blockWood1.ppm"); texture2 = Image("texture/block/blockWood2.ppm"); } void BlockWood::registerTextures(void) { textureID1 = TextureManager::getNewID(); textureID2 = TextureManager::getNewID(); registerTexture(texture1, textureID1); registerTexture(texture2, textureID2); } void BlockWood::registerDisplayList(void) { static Vector geometry[] = { Vector(0, 0, 0), Vector(1, 0, 0), Vector(1, 0, 1), Vector(0, 0, 1), Vector(0, 1, 0), Vector(1, 1, 0), Vector(1, 1, 1), Vector(0, 1, 1), }; readTextures(); registerTextures(); displayListID = DisplayListManager::getNewID(); glNewList(displayListID, GL_COMPILE); glPushMatrix(); glScaled(blockSize.getX(), blockSize.getY(), blockSize.getZ()); drawTexture(textureID1, geometry[7], geometry[6], geometry[5], geometry[4]); drawTexture(textureID2, geometry[4], geometry[5], geometry[1], geometry[0]); drawTexture(textureID2, geometry[5], geometry[6], geometry[2], geometry[1]); drawTexture(textureID2, geometry[6], geometry[7], geometry[3], geometry[2]); drawTexture(textureID2, geometry[7], geometry[4], geometry[0], geometry[3]); drawTexture(textureID1, geometry[0], geometry[1], geometry[2], geometry[3]); glPopMatrix(); glEndList(); }
true
cd0a35462e581e09534f4ae9ac8b3dd7242ef2b7
C++
Ahiganbana/leetcode
/spiralOrder.cpp
UTF-8
1,150
3.0625
3
[]
no_license
#include <iostream> #include <vector> using namespace std; //螺旋顺时针输出二维数组 class Solution { static constexpr int directions[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; public: vector<int> spiralOrder(vector<vector<int>>& matrix) { vector<int> result; int row = matrix.size(); if(row == 0) { return result; } int colum = matrix[0].size(); int i = 0, j = 0; vector<vector<bool>> visited(row, vector<bool>(colum)); int total = row * colum; int directionIndex = 0; for (int k = 0; k < total; k++) { result.push_back(matrix[i][j]); visited[i][j] = true; int nextRow = i + directions[directionIndex][0]; int nextColumn = j + directions[directionIndex][1]; if(nextRow < 0 || nextRow >= row || nextColumn < 0 || nextColumn >= colum || visited[nextRow][nextColumn]){ directionIndex = (directionIndex + 1) % 4; } i += directions[directionIndex][0]; j += directions[directionIndex][1]; } return result; } };
true
84e61ff400840ffda84cbb0e7ec148481190cf15
C++
nicholasbishop/vadem
/src/color.h
UTF-8
1,351
2.890625
3
[]
no_license
// Copyright 2017 Neverware #ifndef COLOR_H_ #define COLOR_H_ #include "png.hpp" #include "util.h" namespace vadem { // Adapted from "YCbCr and YCCK Color Models", // https://software.intel.com/en-us/node/503873 class YCbCr { public: using T = float; YCbCr() : Y(0), Cb(0), Cr(0) {} YCbCr(const T Y, const T Cb, const T Cr) : Y(Y), Cb(Cb), Cr(Cr) {} static YCbCr from_rgb(const T R, const T G, const T B) { const T Y = 0.257 * R + 0.504 * G + 0.098 * B + 16; const T Cb = -0.148 * R - 0.291 * G + 0.439 * B + 128; const T Cr = 0.439 * R - 0.368 * G - 0.071 * B + 128; return {Y, Cb, Cr}; } static YCbCr from_rgb(const png::rgb_pixel& pixel) { return from_rgb(pixel.red, pixel.green, pixel.blue); } png::rgb_pixel to_rgb() const { return {red_u8(), green_u8(), blue_u8()}; } T red() const { return clamp_255(1.164 * (Y - 16) + 1.596 * (Cr - 128)); } T green() const { return clamp_255(1.164 * (Y - 16) - 0.813 * (Cr - 128) - 0.392 * (Cb - 128)); } T blue() const { return clamp_255(1.164 * (Y - 16) + 2.017 * (Cb - 128)); } uint8_t red_u8() const { return red(); } uint8_t green_u8() const { return green(); } uint8_t blue_u8() const { return blue(); } static T clamp_255(const T val) { return clamp(val, 0, 255); } T Y, Cb, Cr; }; } #endif // COLOR_H_
true
474bf6206119b6af3b83bf38ffa9e6db8a00f246
C++
maxFullmer/MARIMBA
/Buoys/Desktop/DAQ_Sampler/libgps-master/src/nmea.c
UTF-8
2,833
2.84375
3
[ "MIT" ]
permissive
#include <stdio.h> #include <stdlib.h> #include <inttypes.h> #include <string.h> #include <math.h> #include "nmea.h" void nmea_parse_gpgga(char *nmea, gpgga_t *loc) { char *p = nmea; p = strchr(p, ',')+1; //skip time p = strchr(p, ',')+1; loc->latitude = atof(p); p = strchr(p, ',')+1; switch (p[0]) { case 'N': loc->lat = 'N'; break; case 'S': loc->lat = 'S'; break; case ',': loc->lat = '\0'; break; } p = strchr(p, ',')+1; loc->longitude = atof(p); p = strchr(p, ',')+1; switch (p[0]) { case 'W': loc->lon = 'W'; break; case 'E': loc->lon = 'E'; break; case ',': loc->lon = '\0'; break; } p = strchr(p, ',')+1; loc->quality = (uint8_t)atoi(p); p = strchr(p, ',')+1; loc->satellites = (uint8_t)atoi(p); p = strchr(p, ',')+1; p = strchr(p, ',')+1; loc->altitude = atof(p); } void nmea_parse_gprmc(char *nmea, gprmc_t *loc) { char *p = nmea; p = strchr(p, ',')+1; //skip time p = strchr(p, ',')+1; //skip status p = strchr(p, ',')+1; loc->latitude = atof(p); p = strchr(p, ',')+1; switch (p[0]) { case 'N': loc->lat = 'N'; break; case 'S': loc->lat = 'S'; break; case ',': loc->lat = '\0'; break; } p = strchr(p, ',')+1; loc->longitude = atof(p); p = strchr(p, ',')+1; switch (p[0]) { case 'W': loc->lon = 'W'; break; case 'E': loc->lon = 'E'; break; case ',': loc->lon = '\0'; break; } p = strchr(p, ',')+1; loc->speed = atof(p); p = strchr(p, ',')+1; loc->course = atof(p); } /** * Get the message type (GPGGA, GPRMC, etc..) * * This function filters out also wrong packages (invalid checksum) * * @param message The NMEA message * @return The type of message if it is valid */ uint8_t nmea_get_message_type(const char *message) { uint8_t checksum = 0; if ((checksum = nmea_valid_checksum(message)) != _EMPTY) { return checksum; } if (strstr(message, NMEA_GPGGA_STR) != NULL) { return NMEA_GPGGA; } if (strstr(message, NMEA_GPRMC_STR) != NULL) { return NMEA_GPRMC; } return NMEA_UNKNOWN; } uint8_t nmea_valid_checksum(const char *message) { uint8_t checksum= (uint8_t)strtol(strchr(message, '*')+1, NULL, 16); char p; uint8_t sum = 0; ++message; while ((p = *message++) != '*') { sum ^= p; } if (sum != checksum) { return NMEA_CHECKSUM_ERR; } return _EMPTY; }
true
77377b8d1e19c03f5e3549fdf5c0568e22a0e701
C++
hyongti/42cursus
/CppModule/03/ex04/main.cpp
UTF-8
1,325
2.859375
3
[]
no_license
#include "FragTrap.hpp" #include "ScavTrap.hpp" #include "NinjaTrap.hpp" #include "SuperTrap.hpp" int main(void) { SuperTrap anonymous; std::cout<<"============================\n"; SuperTrap hyeonkim("hyeonkim"); SuperTrap hyopark("hyopark"); SuperTrap kilee1("kilee"); SuperTrap kilee2(kilee1); std::cout<<"========================================\n"; hyeonkim.takeDamage(hyopark.rangedAttack(hyeonkim.getName())); // hyopark이 hyeonkim angedAttack hyeonkim.showData(); hyopark.takeDamage(hyeonkim.meleeAttack(hyopark.getName())); // hyeonkim이 hyopark meleeAttack hyopark.showData(); hyeonkim.beRepaired(100); // hyeonkim 회복 hyeonkim.showData(); hyopark.beRepaired(100); // hyopark 회복 hyopark.showData(); std::cout<<"========================================\n"; std::cout<<"\n===== random attack! =====\n\n"; for(int i=1; i<=5; i++) { std::cout<<"----- "<<i<<"th random attack! -----\n"; hyeonkim.takeDamage(hyopark.vaulthunter_dot_exe(hyeonkim.getName())); // hyopark이 랜덤무기로 hyeonkim 공격 hyeonkim.showData(); hyopark.showData(); } std::cout<<"\n===== ninjaShoebox attack! =====\n\n"; ClapTrap mijeong("mijeong"); FragTrap ukim("ukim"); hyeonkim.ninjaShoebox(mijeong); hyeonkim.ninjaShoebox(ukim); std::cout<<"\n=================================\n\n"; }
true
65e72df65ede0f099b7571240d3d36507f0e8b27
C++
ckjeter/ADA2019
/hw2/prob4.cpp
UTF-8
6,127
3.03125
3
[]
no_license
#include <iostream> #include <stdio.h> #include <vector> #include <algorithm> using namespace std; int N; void printvec(vector<int>& v) { for (int i = 0; i < v.size(); i++) { cout<<v[i]<<" "; } cout<<endl; } int bsearch(int left, int right, int value, const vector<int>& v) { /* if (left > right) { return left; } int mid = left + (right - left) / 2; if (value >= v[mid]) { return bsearch(mid + 1, right, value, v); } else return bsearch(left, mid - 1, value, v); */ while(left <= right) { int mid = left + (right - left) / 2; if (v[mid] <= value) { left = mid + 1; } else right = mid - 1; } //return (value > v[left]) ? (left + 1) : left; return left; } void pos_update(vector<int>& pos, const vector<int>& s, const vector<int>& enemy) { for (int i = 1; i < pos.size(); i++) { pos[i] = bsearch(0, enemy.size()-1, s[i], enemy); } } int main() { int answer = 0; scanf("%d", &N); vector<int> s(8); vector<int> pos(8); pos[0] = 0; s[0] = 0; for (int i = 1; i <= 3; ++i) { scanf("%d", &s[i]); } sort(s.begin(), s.begin()+4); s[4] = s[1] + s[2]; s[5] = s[1] + s[3]; s[6] = s[2] + s[3]; s[7] = s[1] + s[2] + s[3]; vector<int> enemy(N); for (int i = 0; i < N; ++i) { scanf("%d", &enemy[i]); } sort(enemy.begin(), enemy.end()); pos_update(pos, s, enemy); //檢查s6 ~ s7區間 if (pos[7] < N) { answer = -1; enemy.erase(enemy.begin(), enemy.end()); } else { answer += max(0, N - pos[6]); enemy.erase(enemy.begin()+pos[6], enemy.end()); } pos_update(pos, s, enemy); //檢查s5 ~ s6區間,優先和s0 ~ s1區間一起消------------------------------------------- int count = pos[6] - pos[5]; enemy.erase(enemy.begin()+pos[5], enemy.end()); answer += count; if (count > 0 && pos[1] > 0){ enemy.erase(enemy.begin() + max(0, pos[1] - count), enemy.begin() + pos[1]); } //printvec(enemy); //int tempindex = pos[1]; //pos.erase(pos.end()-1); //假設s1 + s2 > s3 if (s[1] + s[2] > s[3]) { //檢查s4 ~ s5區間,優先和s1 ~ s2區間一起消---------------------------------------- pos_update(pos, s, enemy); count = pos[5] - pos[4]; enemy.erase(enemy.begin()+pos[4], enemy.end()); answer += count; if (count > 0 && pos[2] > 0){ enemy.erase(enemy.begin() + max(0, pos[2] - count), enemy.begin() + pos[2]); } //pos.erase(pos.end()-1); //檢查s3 ~ s4區間,優先和s2 ~ s3區間一起消---------------------------------------- pos_update(pos, s, enemy); count = pos[4] - pos[3]; enemy.erase(enemy.begin()+pos[3], enemy.end()); answer += count; if (count > 0 && pos[3] > 0){ enemy.erase(enemy.begin() + max(0, pos[3] - count), enemy.begin() + pos[3]); } //pos.erase(pos.end()-1); } //s1 + s2 <= s3 else { //檢查s3 ~ s5區間,優先和s1 ~ s2區間一起消---------------------------------------- pos_update(pos, s, enemy); count = pos[5] - pos[3]; enemy.erase(enemy.begin()+pos[3], enemy.end()); answer += count; if (count > 0 && pos[2] > 0){ enemy.erase(enemy.begin() + max(0, pos[2] - count), enemy.begin() + pos[2]); } } //printvec(enemy); //檢查所有<s3的-------------------------------------------------------------------------------- pos_update(pos, s, enemy); /* while (enemy.size() > 0 && pos[2] > 0) { if (pos[1] > 0) { enemy.erase(enemy.begin()+pos[1]-1); pos[3]--; pos[2]--; pos[1]--; } if (pos[2] > 0) { enemy.erase(enemy.begin()+pos[2]-1); pos[3]--; if (pos[2] == pos[1]) { pos[2]--; pos[1]--; } else { pos[2]--; } } if (pos[3] > 0) { enemy.erase(enemy.begin()+pos[3]-1); if (pos[3] == pos[2] && pos[2] == pos[1]) { pos[3]--; pos[2]--; pos[1]--; } else if(pos[3] == pos[2] && pos[2] > pos[1]){ pos[3]--; pos[2]--; } else{ pos[3]--; } } answer++; } pos_update(pos, s, enemy); if (s[1]+s[2] > s[3]) { while (pos[3] > 0) { if (pos[3] > 0) { pos[3]--; } if (pos[3] > 0) { pos[3]--; } answer++; } } else { //pos[4] <= pos[3] while (enemy.size() > 0 && pos[4] > 0) { if (pos[4] > 0) { enemy.erase(enemy.begin()+pos[4]-1); pos[4]--; pos[3]--; } if (pos[3] > 0) { enemy.erase(enemy.begin()+pos[3]-1); if (pos[3] == pos[4]) { pos[3]--; pos[4]--; } else { pos[3]--; } } answer++; } pos_update(pos, s, enemy); while (pos[3] > 0) { pos[3]--; answer++; } } */ //此部分和連少甫同學討論做法 int *pointer1 = &pos[1]; int *pointer2 = &pos[2]; int *pointer3 = &pos[3]; int *pointer4 = &pos[4]; if (pos[2] == pos[1]){ pointer2 = pointer1; } if (pos[3] == pos[2]){ pointer3 = pointer2; } int pos1 = pos[1]; int pos2 = pos[2]; int pos3 = pos[3]; int pos4 = pos[4]; int power3 = 1; bool combine1 = 0, combine2 = 0, never = 0, special_case = 0; int i = 0; while (i < enemy.size()){ //s1 if(*pointer1 > 0){ i++; (*pointer1)--; } else{//s1沒用到 combine1 = 1; } //s2 if(*pointer2 > 0){ i++; (*pointer2)--; if(*pointer2 == pos1){ if (pointer3 == pointer2){ pointer3 = pointer1; } pointer2 = pointer1; } } else{//s2沒用到 combine2 = 1; } //s1+s2 if(combine2 == 1 && combine1 == 1 && never == 0){ if (*pointer4 >= (*pointer3)){ //s1+s2 >= s3 power3 = 2; never = 1; } else { //s1+s2 < s3 special_case = 1; if (*pointer4 == pos2){ *pointer4 = 0; } if(*pointer4 > 0){ i++; (*pointer4)--; } } } //s3 if(*pointer3 > 0){ i += power3; (*pointer3) = (*pointer3) - power3; if (*pointer3 == pos2){ pointer3 = pointer2; } if (special_case == 1 && *pointer3 == pos4){ pointer3 = pointer4; } } answer += 1; } printf("%d\n", answer); return 0; }
true
0861aadeddc5467b44dd76c413c64a6db06a5763
C++
chauhan0707/CodingPractice
/Vectors3.cpp
UTF-8
167
2.875
3
[]
no_license
#include<iostream> #include<vector> using namespace std; int main() { vector<int> v{10,20,30,40,50}; for(auto x:v) { cout<<x<<" "; } return 0; }
true
ff3d3fdc83db9d19014b2d7f4f191ebcc17846ff
C++
tanvirtanjum/InfixToPostfix-Compiler_Design
/infix_to_postfix(17-35860-3).cpp
UTF-8
1,987
3.359375
3
[]
no_license
///SHOURAV, TANVIR TANJUM ///17-35860-3 ///COMPILER DESIGN [A] #include<iostream> using namespace std; char input[]=""; char *la=input; void expr(); void exprP(); void term(); void termP(); void factor(); void match(char optr); void expr() { term(); exprP(); } void term() { factor(); termP(); } void factor() { if(isdigit(*la)) { cout<<*la; la++; } else if(*la=='(') { match('('); expr(); match(')'); } else { cout<<"Invalid Expression."<<endl; } } void match(char optr) { if(*la==optr) { la++; } } void exprP() { if(*la=='+') { match('+'); term(); cout<<"+"; exprP(); } else if(*la=='-') { match('-'); term(); cout<<"-"; exprP(); } else{} } void termP() { if(*la=='*') { match('*'); factor(); cout<<"*"; termP(); } else if(*la=='/') { match('/'); factor(); cout<<"/"; termP(); } else{} } void start() { cout<<"Type an infix notation containing single digits(0-9) and operators '+','-','*' and '/' :"; cin>>input; cout<<endl; cout<<"..................................................................................."<<endl; cout<<"Infix Form: "<<input<<endl; cout<<"Postfix Form: "; expr(); cout<<endl<<"..................................................................................."<<endl; cout<<endl<<endl; } int main() { char cont[1]; cout<<"Infix to Postfix Converter"<<endl; while(true) { cout<<"Press 'C' to continue or press any character to exit."<<endl; cin>>cont; if(cont[0] == 'C' || cont[0] == 'c') { start(); } else { break; } } return 0; } ///SHOURAV, TANVIR TANJUM ///17-35860-3 ///COMPILER DESIGN [A]
true
59ec365b485cc4111bd23f87cd470fada67e025c
C++
ehei1/pytempl
/unit_test/enumerate_test.cpp
UTF-8
1,694
2.84375
3
[]
no_license
#include "stdafx.h" #include <algorithm> #include <iostream> #include <iterator> #include <numeric> #include <vector> #include "CppUnitTest.h" #include "pytempl\enumerate.h" #include "pytempl\zip.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace test { TEST_CLASS( EnumerateTest ) { public: TEST_METHOD( TestMutable ) { std::vector<int> v( 10 ); std::iota( std::begin( v ), std::end( v ), 0 ); for ( auto e : pytempl::enumerate( v ) ) { auto i = std::get<0>( e ); auto ii = std::get<1>( e ); Assert::IsTrue( i == ii ); } } TEST_METHOD( TestConst ) { std::vector<int> v( 10 ); std::iota( std::begin( v ), std::end( v ), 0 ); const decltype( v ) vv = std::move( v ); for ( auto e : pytempl::enumerate( vv ) ) { auto i = std::get<0>( e ); auto ii = std::get<1>( e ); Assert::IsTrue( i == ii ); } } TEST_METHOD( TestLvalue ) { std::vector<int> v( 10 ); std::iota( std::begin( v ), std::end( v ), 0 ); auto& vv{ v }; for ( auto e : pytempl::enumerate( vv ) ) { auto i = std::get<0>( e ); auto ii = std::get<1>( e ); Assert::IsTrue( i == ii ); } } TEST_METHOD( TestZipIterator ) { std::vector<int> iv( 10 ); std::iota( std::begin( iv ), std::end( iv ), 0 ); std::vector<float> fv( 10 ); std::iota( std::begin( fv ), std::end( fv ), 0.f ); auto z = pytempl::zip( iv, fv ); for ( auto e : pytempl::enumerate( z ) ) { auto idx = std::get<0>( e ); auto zz = std::get<1>( e ); int i{}; float f{}; std::tie( i, f ) = zz; Assert::IsTrue( idx == i ); Assert::IsTrue( idx == static_cast<int>( f ) ); } } }; }
true
55b81236479619639125f240f4e079bf4711d22f
C++
madhok/Craftsmanship
/Strings/EditDistance.cpp
UTF-8
1,110
3.609375
4
[]
no_license
// Dynamic Programming implementation of edit distance #include<stdio.h> #include<stdlib.h> #include<string.h> // Change these strings to test the program #define STRING_X "SUNDAY" #define STRING_Y "SATURDAY" // Recursive implementation inline int min(int a, int b) { return a < b ? a : b; } // Returns Minimum among a, b, c int Minimum(int a, int b, int c) { return min(min(a, b), c); } int EditDistanceRecursion( char *X, char *Y, int m, int n ) { // Base cases if( m == 0 && n == 0 ) return 0; if( m == 0 ) return n; if( n == 0 ) return m; // Recurse int left = EditDistanceRecursion(X, Y, m-1, n) + 1; int right = EditDistanceRecursion(X, Y, m, n-1) + 1; int corner = EditDistanceRecursion(X, Y, m-1, n-1) + (X[m-1] != Y[n-1]); return Minimum(left, right, corner); } int main() { char X[] = STRING_X; // vertical char Y[] = STRING_Y; // horizontal printf("Minimum edits required to convert %s into %s is %d by recursion\n", X, Y, EditDistanceRecursion(X, Y, strlen(X), strlen(Y))); return 0; }
true
26d0d38556ddd77390638617eb0e6b7288483789
C++
xGreat/CppNotes
/src/algorithms/data_structures/nodes_deep_copy.hpp
UTF-8
1,029
3.5625
4
[ "MIT" ]
permissive
#ifndef NODES_DEEP_COPY_HPP_ #define NODES_DEEP_COPY_HPP_ // Write a method that takes a pointer to a Node structure as a parameter and // returns a complete copy of the passed in data structure. The Node data // structure contains two pointers to other Nodes. namespace Algo::DS { class Node { public: Node(const Node* first, const Node* second) : m_first(first), m_second(second) { } ~Node() { if (nullptr != m_first) { delete m_first; } if (nullptr != m_second) { delete m_second; } } Node* m_first = nullptr; Node* m_second = nullptr; }; Node* DeepCopyOfNode(const Node* const node) { if (nullptr == node) { return nullptr; } Node* result = new Node; if (nullptr != node->m_first) { result->m_first = DeepCopyOfNode(node->m_first); } if (nullptr != node->m_second) { result->m_second = DeepCopyOfNode(node->m_second); } return result; } } #endif /* NODES_DEEP_COPY_HPP_ */
true
b1bcab7405d1532494e281d160655fa1d5f2c0a1
C++
saeedutsha/Fuzzy-System
/FuzzySystem/main.cpp
UTF-8
3,823
3.515625
4
[]
no_license
#include <iostream> using namespace std; int main() { double attendance,ttime; /**< Two inputs */ cout<<"Total attendance in class(%) : "; cin>>attendance; cout<<"Total time in class(%) : "; cin>>ttime; /**< Fuzzification of total time in class */ /**< Let's assume the cutting points are 0,10,25,40,50,60,75,90 and 100 where 0-40 is the range of first trapezium, 25-75 is for the second triangle and 60-100 is for the third trapezium */ double uInadeuate,uMarginal,uAdequate; if(ttime>=0 && ttime<=10){ uInadeuate = 1; uMarginal = 0; uAdequate = 0; } if(ttime>10 && ttime<=25){ uInadeuate = ((40-ttime)/(40-10)); uMarginal = 0; uAdequate = 0; } if(ttime>25 && ttime<=40){ uInadeuate = ((40-ttime)/(40-10)); uMarginal = ((ttime-25)/(50-25)); uAdequate = 0; } if(ttime>40 && ttime<=50){ uInadeuate = 0; uMarginal = ((ttime-25)/(50-25)); uAdequate = 0; } if(ttime>50 && ttime<=60){ uInadeuate = 0; uMarginal = ((75-ttime)/(75-50)); uAdequate = 0; } if(ttime>60 && ttime<=75){ uInadeuate = 0; uMarginal = ((75-ttime)/(75-50)); uAdequate = ((ttime-60)/(90-60)); } if(ttime>75 && ttime<=90){ uInadeuate = 0; uMarginal = 0; uAdequate = ((ttime-60)/(90-60)); } if(ttime>90 && ttime<=100){ uInadeuate = 0; uMarginal = 0; uAdequate = 1; } /**< End of fuzzification of ttime */ /**< Fuzzification of total attendance in class */ /**< Let's assume the cutting points are 0,20,40,60,80 and 100 where 0-60 is the range of first trapezium and 40-100 is for the second trapezium */ double uSmall,uLarge; if(attendance>=0 && attendance<=20){ uSmall = 1; uLarge = 0; } if(attendance>20 && attendance<=40){ uSmall = ((60-attendance)/(60-20)); uLarge = 0; } if(attendance>40 && attendance<=60){ uSmall = ((60-attendance)/(60-20)); uLarge = ((attendance-40)/(80-40)); } if(attendance>60 && attendance<=80){ uSmall = 0; uLarge = ((attendance-40)/(80-40)); } if(attendance>80 && attendance<=100){ uSmall = 0; uLarge = 1; } /**< End of fuzzification of attendance */ //cout<<uInadeuate<<" "<<uMarginal<<" "<<uAdequate<<" "; //cout<<uSmall<<" "<<uLarge<<" "; /**< Rules Evaluation */ double uLow,uAverage,uHigh; /**< if time=inadequate or class=small then marks=low */ uLow = max(uInadeuate,uSmall); /**< if time=marginal and class=large then marks=average */ uAverage = min(uMarginal,uLarge); /**< if time=adequate or class=large then marks=high */ uHigh = max(uAdequate,uLarge); /**< End of Rules Evaluation */ //cout<<uLow<<" "<<uAverage<<" "<<uHigh<<" "; /**< Defuzzification */ double Marks; /**< Let's assume the cutting points are 0,10,25,40,50,60,75,90 and 100 where 0-40 is the range of first trapezium, 25-75 is for the second triangle and 60-100 is for the third trapezium */ double sumx=0,sumy=0,sumz=0,cx=0,cy=0,cz=0; for(int i=0;i<=25;i=i+10){ sumx=sumx+i; cx++; } for(int i=30;i<=55;i=i+10){ sumy=sumy+i; cy++; } for(int i=60;i<=100;i=i+10){ sumz=sumz+i; cz++; } Marks = ((uLow*sumx+uAverage*sumy+uHigh*sumz)/(uLow*cx+uAverage*cy+uHigh*cz)); /**< End of Defuzzification */ cout<<"Total Mark is : "<<Marks<<"%\n"; }
true
91fb7bf47370e152f1be2bd6d0646f5524e4a57c
C++
Aryan5744/DSA_Programs
/4.Searching_Sorting_90_124/94_Middle.cpp
UTF-8
328
3
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int min(int A, int B){return A > B ? B : A;} int max(int A, int B){return A > B ? A : B;} int middle(int A, int B, int C){ return max(min(A,B),min(B,C)); } // Driver program int main() { int A,B,C; cin >> A >> B >> C; cout << middle(A,B,C) << endl; return 0; }
true
af64650042a643f26e99fdc8d2ed6a3d24765713
C++
lazytiger/apib
/apib/status.cc
UTF-8
1,625
2.796875
3
[ "Apache-2.0" ]
permissive
/* Copyright 2020 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "apib/status.h" #include <cstring> #include <sstream> namespace apib { static const Status kOkStatus(Status::Code::OK); const Status& Status::kOk = kOkStatus; static const int kMaxStatusLen = 64; Status::Status(Code c, int errnum) : code_(c) { char msgbuf[kMaxStatusLen]; strerror_r(errnum, msgbuf, kMaxStatusLen); msg_ = msgbuf; } std::string Status::codeString() const { switch (code_) { case OK: return "ok"; case SOCKET_ERROR: return "Socket error"; case TLS_ERROR: return "TLS error"; case DNS_ERROR: return "DNS error"; case INVALID_URL: return "Invalid URL"; case IO_ERROR: return "I/O error"; case INTERNAL_ERROR: return "Internal error"; default: return "Unknown error"; } } std::ostream& operator<<(std::ostream& out, const Status& s) { out << s.codeString(); if (!s.msg_.empty()) { out << ": " << s.msg_; } return out; } std::string Status::str() const { std::ostringstream ss; ss << *this; return ss.str(); } } // namespace apib
true
309950f1bf7c709eeeef5bdb9a2014dfc4563a4e
C++
matprophet/dungeonbuilder
/DungeonBuilderC/headers/dungeon_data.h
UTF-8
2,347
2.859375
3
[ "MIT" ]
permissive
#ifndef DUNGEON_DATA #define DUNGEON_DATA #include <string> #include <vector> using namespace std; struct DungeonExit; struct DungeonObject; struct DungeonCreature; struct DungeonRoom; struct DungeonPlayer; struct DungeonAction; extern vector<DungeonRoom*> g_roomList; struct DungeonEntity { private: vector <string> names; public: DungeonEntity* parent = nullptr; unsigned long uid = NULL; virtual void addName(string name); virtual void setPrimaryName(string name); virtual string getPrimaryName() const; virtual vector<string> getNames() const; virtual vector<string> getLcaseNames() const; virtual string vectorStringToJSON(vector<string> const &v) const; bool removeName(string name); }; struct DungeonEffect { DungeonEffect(); ~DungeonEffect(); DungeonAction *parent; int type; string output; int magnitude; void apply(DungeonPlayer* player); static string typeToString(int type); string getName(); }; struct DungeonAction : DungeonEntity { string output; vector<DungeonEffect*> effects; }; struct DungeonRoom : DungeonEntity { DungeonRoom(); ~DungeonRoom(); vector<string> description; vector<DungeonExit*> exits; vector<DungeonObject*> objects; vector<DungeonCreature*> creatures; string toJSON(); }; struct DungeonExit: DungeonEntity { DungeonExit(); ~DungeonExit(); bool isDoor; // or window, or pile of rocks, whatever bool isOpen; //or whatever int distance; string openingText; string closingText; string openText; string closedText; DungeonRoom* room; string toJSON(); }; struct DungeonObject: DungeonEntity { DungeonObject(); ~DungeonObject(); vector<string> description; int damage; //0 if not a weapon int mass; int size; bool canOpen; bool isOpen; bool canTake; vector<DungeonObject*> contents; vector<DungeonAction*> actions; string toJSON(); }; struct DungeonPlayer: DungeonEntity { DungeonPlayer(); ~DungeonPlayer(); vector<string> description; int hitpoints; int maxhitpoints; int score; vector<DungeonObject*> objects; DungeonRoom* location; void heal(int amount); }; struct DungeonCreature: DungeonEntity { DungeonCreature(); ~DungeonCreature(); vector<string> description; int hitpoints; int alignment; string attack(DungeonObject *weapon,DungeonPlayer *player); string toJSON(); }; #endif
true
c338d56eb037df789af6a8844feadd6757d15f22
C++
ffaawgh/University
/OOP/2/Vector.hpp
UTF-8
6,620
3.234375
3
[ "Unlicense" ]
permissive
// // Created by ed on 18.04.17. // #ifndef LAB2_VECTOR_HPP #define LAB2_VECTOR_HPP #include <ostream> #include <iomanip> #include <initializer_list> #include "BaseVector.hpp" #include "Iterator.hpp" #include "Errors.hpp" template<class T> class Vector : public BaseVector { public: Vector() = default; Vector(const Vector& vector); Vector(Vector&& vector); explicit Vector(size_t _size); Vector(const std::initializer_list<T>& initializer_list); virtual ~Vector(); Vector<T>& operator=(const Vector<T>& b); Vector<T>& operator=(const std::initializer_list<T>& b); Vector<T>& operator=(Vector<T>&& b); Vector<T>& minus(); Vector<T>& add(const Vector<T>& b); Vector<T>& subtract(const Vector<T>& b); Vector<T>& divide(const T& b); Vector<T>& multiply(const T& b); T multiply(const Vector<T>& b) const; bool isOrtogonal(const Vector<T>& b) const; bool equals(const Vector<T>& b) const; Vector<T> operator-() const; Vector<T>& operator+=(const Vector<T>& b); Vector<T> operator+(const Vector<T>& b) const; Vector<T>& operator-=(const Vector<T>& b); Vector<T> operator-(const Vector<T>& b) const; Vector<T>& operator*=(const T& b); Vector<T> operator*(const T& b) const; T operator*(const Vector<T>& b) const; Vector<T>& operator/=(const T& b); Vector<T> operator/(const T& b) const; T& operator[](size_t i); const T& operator[](size_t i) const; bool operator==(const Vector<T>& b) const; bool operator!=(const Vector<T>& b) const; bool operator&&(const Vector<T>& b) const; Iterator<T> begin(); Iterator<const T> begin() const; Iterator<T> end(); Iterator<const T> end() const; template<class T1> friend std::ostream& operator<<(std::ostream& out, const Vector<T1>& b); template<class T1> friend Vector<T1> operator+(const T1& a, const Vector<T1>& b); template<class T1> friend Vector<T1> operator*(const T1& a, const Vector<T1>& b); private: void resize(size_t new_size); T* data = nullptr; }; template<class T> Vector<T>::Vector(size_t _size) { resize(_size); } template<class T> Vector<T>::Vector(const Vector& vector) { *this = vector; } template<class T> Vector<T>::Vector(Vector&& vector) { *this = vector; } template<class T> Vector<T>::Vector(const std::initializer_list<T>& initializer_list) { *this = initializer_list; } template<class T> Vector<T>::~Vector() { resize(0); } template<class T> Vector<T>& Vector<T>::operator=(const Vector<T>& b) { resize(b.size); std::copy(b.begin(), b.end(), begin()); } template<class T> Vector<T>& Vector<T>::operator=(Vector<T>&& b) { data = b.data; size = b.size; b.data = nullptr; b.size = 0; return *this; } template<class T> Vector<T>& Vector<T>::operator=(const std::initializer_list<T>& b) { resize(b.size()); std::copy(b.begin(), b.end(), begin()); } template<class T> T& Vector<T>::operator[](size_t i) { if (i >= size) throw IndexOutOfRangeException(); return data[i]; } template<class T> const T& Vector<T>::operator[](size_t i) const { if (i >= size) throw IndexOutOfRangeException(); return data[i]; } template<class T> bool Vector<T>::operator==(const Vector<T>& b) const { return equals(b); } template<class T> bool Vector<T>::operator!=(const Vector<T>& b) const { return !equals(b); } template<class T> Iterator<T> Vector<T>::begin() { return Iterator<T>(data); } template<class T> Iterator<const T> Vector<T>::begin() const { return Iterator<const T>(data); } template<class T> Iterator<T> Vector<T>::end() { return Iterator<T>(data + size); } template<class T> Iterator<const T> Vector<T>::end() const { return Iterator<const T>(data + size); } template<class T> void Vector<T>::resize(size_t new_size) { delete[] data; data = new_size ? new T[new_size] : nullptr; size = new_size; } template<class T> Vector<T>& Vector<T>::minus() { for (auto& a: *this) { a = -a; } return *this; } template<class T> Vector<T>& Vector<T>::add(const Vector<T>& b) { if (size != b.size) throw InvalidSizeException(); for (size_t i = 0; i < size; ++i) { data[i] += b.data[i]; } return *this; } template<class T> Vector<T>& Vector<T>::subtract(const Vector<T>& b) { if (size != b.size) throw InvalidSizeException(); for (size_t i = 0; i < size; ++i) { data[i] -= b.data[i]; } return *this; } template<class T> Vector<T>& Vector<T>::divide(const T& b) { if (!b) throw DivisionByZeroException(); for (auto& a: *this) { a /= b; } return *this; } template<class T> Vector<T>& Vector<T>::multiply(const T& b) { for (auto& a: *this) { a *= b; } return *this; } template<class T> T Vector<T>::multiply(const Vector<T>& b) const { if (size != b.size) throw InvalidSizeException(); T result = 0; for (size_t i = 0; i < size; ++i) { result += data[i] + b.data[i]; } return result; } template<class T> bool Vector<T>::isOrtogonal(const Vector<T>& b) const { return !(*this * b); } template<class T> bool Vector<T>::equals(const Vector<T>& b) const { return std::equal(begin(), end(), b.begin(), b.end()); } template<class T> Vector<T> Vector<T>::operator-() const { auto result = *this; result.minus(); return result; } template<class T> Vector<T>& Vector<T>::operator+=(const Vector<T>& b) { return add(b); } template<class T> Vector<T> Vector<T>::operator+(const Vector<T>& b) const { auto result = *this; result.add(b); return result; } template<class T> Vector<T>& Vector<T>::operator-=(const Vector<T>& b) { return subtract(b); } template<class T> Vector<T> Vector<T>::operator-(const Vector<T>& b) const { auto result = *this; result.subtract(b); return result; } template<class T> Vector<T>& Vector<T>::operator*=(const T& b) { return multiply(b); } template<class T> Vector<T> Vector<T>::operator*(const T& b) const { auto result = *this; result.multiply(b); return result; } template<class T> T Vector<T>::operator*(const Vector<T>& b) const { return multiply(b); } template<class T> Vector<T>& Vector<T>::operator/=(const T& b) { return divide(b); } template<class T> Vector<T> Vector<T>::operator/(const T& b) const { auto result = *this; result.divide(b); return result; } template<class T> bool Vector<T>::operator&&(const Vector<T>& b) const { return isOrtogonal(b); } template<class T1> std::ostream& operator<<(std::ostream& out, const Vector<T1>& b) { for (auto& a: b) { out << std::setw(6) << a << ' '; } return out; } template<class T1> Vector<T1> operator+(const T1& a, const Vector<T1>& b) { return b + a; } template<class T1> Vector<T1> operator*(const T1& a, const Vector<T1>& b) { return b * a; } #endif //LAB2_VECTOR_HPP
true
1387313ea4b05fcb58e61833d2507d6991fb1f03
C++
gyokkoo/SDA-FMI-2018
/Data-Structures/Dynamic-Array-Example/main.cpp
UTF-8
602
3.34375
3
[]
no_license
#include <iostream> #include "DynamicArray.h" int main() { DynamicArray myArray; const int COUNT = 10; for (int i = 0; i < COUNT; i++) { myArray.add(i); } for (size_t i = 0; i < myArray.getLength(); i++) { myArray[i] = myArray[i] * 10; } myArray.print(); std::cout << "\n"; const DynamicArray& constArray = myArray; std::cout << constArray[0] << "\n"; // OK // Invalid ! // constArray[0] = 0; try { myArray.getAt(myArray.getAt(COUNT + 1)); } catch (std::out_of_range& e) { std::cerr << "Exception caught: " << e.what() << "\n"; } return 0; }
true
2b6dcf261a91d05c1ee9bcf4da110bfa82a58f5a
C++
BlenderCN-Org/3dPrintRef
/raytracingDraw/SORT/src/accel/octree.h
UTF-8
5,107
2.875
3
[]
no_license
/* This file is a part of SORT(Simple Open Ray Tracing), an open-source cross platform physically based renderer. Copyright (c) 2011-2018 by Cao Jiayin - All rights reserved. SORT is a free software written for educational purpose. Anyone can distribute or modify it under the the terms of the GNU General Public License Version 3 as published by the Free Software Foundation. However, there is NO warranty that all components are functional in a perfect manner. Without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/gpl-3.0.html>. */ #pragma once #include "accelerator.h" #include "geometry/bbox.h" //! @brief OcTree /** * OcTree is a popular data strucutre in scene management, which is commonly seen in game engines. * Instead of scene visibility management, it can also serves for the purpose of accelerating ray * tracer applications. */ class OcTree : public Accelerator { public: DEFINE_CREATOR( OcTree , Accelerator , "octree" ); //! destructor ~OcTree(); //! @brief Get intersection between the ray and the primitive set using OcTree. //! //! It will return true if there is intersection between the ray and the primitive set. //! In case of an existed intersection, if intersect is not empty, it will fill the //! structure and return the nearest intersection. //! If intersect is nullptr, it will stop as long as one intersection is found, it is not //! necessary to be the nearest one. //! False will be returned if there is no intersection at all. //! @param r The input ray to be tested. //! @param intersect The intersection result. If a nullptr pointer is provided, it stops as //! long as it finds an intersection. It is faster than the one with intersection information //! data and suitable for shadow ray calculation. //! @return It will return true if there is an intersection, otherwise it returns false. virtual bool GetIntersect( const Ray& r , Intersection* intersect ) const; //! Build the OcTree in O(Nlg(N)) time virtual void Build(); //! OcTree node structure struct OcTreeNode{ OcTreeNode* child[8] = {nullptr}; /**< Child node pointers, all will be NULL if current node is a leaf.*/ std::vector<const Primitive*> primitives; /**< Primitives buffer.*/ BBox bb; /**< Bounding box for this octree node.*/ }; //! @brief Primitive information in octree node. struct NodePrimitiveContainer{ std::vector<const Primitive*> primitives; /**< Primitive buffer used during octree construction.*/ }; private: OcTreeNode* m_pRoot = nullptr; /**< Pointer to the root node of this octree.*/ const unsigned m_uMaxPriInLeaf = 16; /**< Maximum number of primitives allowed in a leaf node, 16 is the default value.*/ const unsigned m_uMaxDepthInOcTree = 16; /**< Maximum depth of the octree, 16 is the default value.*/ //! @brief Split current node into eight if criteria is not met. Otherwise, it will make it a leaf.\n //! This function invokes itself recursively, so the whole sub-tree will be built once it is called. //! @param node Node to be splitted. //! @param container Container holding all primitive information in this node. //! @param bb Bounding box of this node. //! @param depth Current depth of this node. void splitNode( OcTreeNode* node , NodePrimitiveContainer* container , unsigned depth ); //! @brief Making the current node as a leaf node. //! An new index buffer will be allocated in this node. //! @param node Node to be made as a leaf node. //! @param container Container holdes all primitive information in this node. void makeLeaf( OcTreeNode* node , NodePrimitiveContainer* container ); //! @brief Traverse OcTree recursively and return if there is interesection. //! @param node Sub-tree belongs to this node will be visited in a depth first manner. //! @param ray The input ray to be tested. //! @param intersect A pointer to the result intersection information. If empty is passed, it will return as long as an intersection is //! detected and it is not necessarily to be the nearest one. //! @param fmin Current minimum value along the ray //! @param fmax Current maximum value along the ray. //! @return Whether the ray intersects anything in the primitive set bool traverseOcTree( const OcTreeNode* node , const Ray& ray , Intersection* intersect , float fmin , float fmax ) const; //! @brief Release OcTree memory. //! @param node Sub-tree belongs to this node will be released recursively. void releaseOcTree( OcTreeNode* node ); SORT_STATS_ENABLE( "Spatial-Structure(OcTree)" ) };
true
20e27f86bc6b10a17e91c303637b9d54c796c4b0
C++
Raboni/SummonEngine
/SummonEngine/Script/NodeInstance.h
UTF-8
1,738
2.640625
3
[ "MIT" ]
permissive
#pragma once #include "NodeScript.h" #include "NodeConnection.h" #include <OpaqueDictionary.hpp> #include <vector> #include <string> #include <any> class NodeInstance { public: NodeInstance(); NodeInstance(NodeScript* aNodeScript); ~NodeInstance(); void Run(); void Run(const std::vector<std::any>& aArguments); void Event(const std::string& aFunction); void SetPinInData(const std::any& aData, const int aPinIndex); void ConnectPinIn(NodeInstance* aOtherInstance, const int aOtherPinIndex, const int aMyPinIndex, const bool aSeparateInputOutputPinIndex = false); void ConnectPinOut(NodeInstance* aOtherInstance, const int aOtherPinIndex, const int aMyPinIndex, const bool aSeparateInputOutputPinIndex = false); const int GetInputPinCount(); const int GetOutputPinCount(); std::vector<std::any> GetInput(); template<typename T> const T& GetOutput(const int aPinIndex); template<typename T> const T& GetOutput(const std::string& aPinName); private: friend class NodeScript; CU::OpaqueDictionary<std::string> myOutput; CU::GrowingArray<NodeConnection> myConnectionsIn; NodeScript* myNodeScript; }; template<typename T> inline const T& NodeInstance::GetOutput(const int aPinIndex) { std::string pinName = myNodeScript->myPinsOut[aPinIndex].myName; return GetOutput<T>(pinName); } template<typename T> inline const T& NodeInstance::GetOutput(const std::string& aPinName) { if (myNodeScript->myPinsIn.Size() > 0) { //if has run return output, otherwise get input and run script if (!myNodeScript->myHasRun) { Run(GetInput()); } return *myOutput.GetValue<T>(aPinName); } else { //run this script and return output Run(std::vector<std::any>()); return *myOutput.GetValue<T>(aPinName); } }
true
178f7fb9fbad5069d41dd1f57ffa9d6a007d1795
C++
lam267/BenhVien
/BenhVien/DateTime.cpp
UTF-8
1,667
3.203125
3
[]
no_license
#pragma once #include <iostream> #include <ctime> #include <vector> using namespace std; class DateTime { public: int ngay, thang, nam; int gio=0, phut=0, giay=0; DateTime(){ } DateTime(int _ngay, int _thang, int _nam){ ngay = _ngay; thang = _thang; nam = _nam; } DateTime (int _ngay, int _thang, int _nam, int _gio, int _phut, int _giay){ ngay = _ngay; thang = _thang; nam = _nam; gio = _gio; phut = _phut; giay = _giay; } void nhap() { cout << "Ngay:";cin >> ngay; cout << "Thang:";cin >> thang; cout << "Nam:";cin >> nam; } vector<string> split (string s, char kitu) { vector<string> result; int i = 0; for(int j = 0; j < s.length();j++){ if(s[j] == kitu){ result.push_back(s.substr(i, j - i)); i = j + 1; } } result.push_back(s.substr(i, s.length() - i)); return result; } // type dd/mm/yyyy void setDate(string date){ vector<string> ngaythangnam = split (date, '/'); ngay = stoi(ngaythangnam[0]); thang = stoi(ngaythangnam[1]); nam = stoi(ngaythangnam[2]); } string now(){ time_t t = time(0); tm* now = localtime(&t); nam = now->tm_year + 1900; thang = now->tm_mon + 1; ngay = now->tm_mday; gio = now->tm_hour; phut = now->tm_min; giay = now->tm_sec; return to_string(ngay) + "/" + to_string(thang) + "/" + to_string(nam) + " " + to_string(gio) + ":" + to_string(phut) + ":" + to_string(giay); } string getNgay(){ return to_string(ngay) + "/" + to_string(thang) + "/" + to_string(nam); } string hienThi(){ return to_string(ngay) + "/" + to_string(thang) + "/" + to_string(nam) + " " + to_string(gio) + ":" + to_string(phut) + ":" + to_string(giay); } };
true
cbe7d70e91308cda1eef5481518d47e9a55a49f9
C++
BoiseState/CS117-resources
/Chapter7_Objects_and_Classes/Student/Student.h
UTF-8
3,426
3.46875
3
[]
no_license
// // Created by DA on 12/31/2016. // #ifndef PERSON_STUDENT_H #define PERSON_STUDENT_H #include <iostream> using namespace std; class Student { public: /* Constructors... Note: There is no default constructor for Student, it wouldn't make sense in this implementation. */ Student(string fname, string lname, string major, double totalUnits); Student(string fname, string lname, double totalUnits); Student(string fname, string lname); /* Mutators... Update the sudent's total units with param 'units' and update student class standing accordingly (Freshman...Senior) */ void updateTotalUnits(double units); /* Update the sudent's semester units with param 'units' */ void updateSemesterUnits(double units); /* Complete the semester... Update the sudent's total units with student's semester units, clear out student's semester units, update student's class standing. */ void completeSemester(); /* Update the sudent's major with param 'newMajor' */ void updateMajor(string newMajor); /* Assessors... Returns the student's total units */ double getStudentTotalUnits() const; /* Returns the student's current units taken in the semester */ double getStudentCurrentUnits() const; /* Returns the student's name */ string getStudentName() const; /* Returns the student's major */ string getStudentMajor() const; /* Returns the student's class standing */ string getStudentClass() const; /* Returns the student's ID */ int getStudentID() const; // {return (int)this->totalUnits; }; /* Prints out the student's record */ void printStudent() const; /* destructor... destructors are used to 'clean up' memory when we are done using the 'Student' object; when the object goes 'out of scope'. We do not be concerned with destructors in this class. They are used for more complicated class. If you do include a destructor in your class code it as in this example */ ~Student(); private: int studentId; string major; string fname; string lname; string whatClass; double unitsThisSemester; double totalUnits; static int lastID; // this is the last ID in use. This variable is 'shared' between all objects; i.e., there // is only 1 copy of lastID for all students; /* Private mutators only for execution WITHIN THE CLASS; i.e., these are NOT visible to the outside, nor are they 'callable'... Returns the next available student ID that isn't being used. NOTE: this mutator is in the 'private' section as no one should be calling this routine from the outside. */ int getID(); /* Returns the students class level: Freshman, Sophomore, Junior, Senior depending on a 30 credit class level; i.e., 0-29 is a Freshman, 30-59 is a Sophomore, 60-89 is a Junior, and > 90 is a Senior. Note:this routine is called whenever the student's totalUnits are updated. */ string setClass(double units); }; int Student::getID() { int id = lastID; lastID++; return id; } int Student::lastID = 1; // set the 'shared' variable to 1 to begin with #endif //PERSON_STUDENT_H
true
1e2d79d86ec22b50c9ae51710d7a7e62246bbddd
C++
iskorotkov/kitchenware
/src/kitchen/electric_stove.h
UTF-8
435
2.78125
3
[]
no_license
#pragma once #include "stove.h" namespace kitchen { class electric_stove : public stove { public: using power_t = double; electric_stove() = default; void power(power_t p); [[nodiscard]] power_t power() const; void print(std::ostream& out, bool full_output = true) const override; ~electric_stove() override = default; private: power_t power_ = 0; }; }
true
4061d173edb0d8c0eca21b1bf62204120e84bd67
C++
anboqing/design_patter_practice
/Proxy/Test/Base.hpp
UTF-8
534
3.046875
3
[]
no_license
#include <iostream> using namespace std; class Base{ public: Base(){ cout << "Base constructor"<<endl; } virtual void func(){ cout << "Base virtual function"<<endl; } void function(){ cout << "Base common function " << endl; } }; class Extend:public Base{ public: Extend(){ cout << "Extend constructor" << endl; } void func(){ cout << "Extend virtual function"<<endl; } void function(){ cout << "Extend common function " << endl; } };
true
1c44bf91616ce0a8206fd3f21b91bbc3cd9e6076
C++
nickredmond/CSC190Nick_Redmond
/GameSkeleton/GameSolution/Engine/Debug.h
UTF-8
1,886
3.15625
3
[]
no_license
#ifndef DEBUG_H #define DEBUG_H #include "Core.h" #include "Matrix3.h" #include <sstream> using std::stringstream; using std::ceil; using std::floor; namespace Debug{ float Debug_RoundValue(float val){ int normalized = (int)(val * 1000.0f); return normalized / 1000.0f; } void DrawValue( Core::Graphics& graphics, int x, int y, float num ) { stringstream ss; ss << num; graphics.DrawString( x, y, ss.str().c_str()); } void DrawValue( Core::Graphics& graphics, int x, int y, int num ) { stringstream ss; ss << num; graphics.DrawString( x, y, ss.str().c_str()); } void DrawValue( Core::Graphics& graphics, int x, int y, size_t num ) { stringstream ss; ss << num; graphics.DrawString( x, y, ss.str().c_str()); } void DrawMatrix(int xPos, int yPos, Core::Graphics& graphics, Matrix3 matrix){ int perRowPixels = 15; int perColPixels = 50; for (int i = 0; i < sizeof(matrix.data) / sizeof(*matrix.data); i++){ int rowNumber = i / 3; int colNumber = 0; if (i == 1 || i == 4 || i == 7){ colNumber = 1; } else if (i == 2 || i == 5 || i == 8){ colNumber = 2; } float roundedVal = Debug_RoundValue(matrix.data[i]); int x = xPos + (colNumber * perColPixels); int y = yPos + (rowNumber * perRowPixels); DrawValue(graphics, x, y, roundedVal); } } void DrawMemoryState(Core::Graphics& graphics, int screenHeight){ _CrtMemState state = _CrtMemState(); _CrtMemCheckpoint(&state); graphics.DrawString(20, screenHeight - 60, "COUNTS:"); DrawValue(graphics, 140, screenHeight - 60, state.lCounts[_CLIENT_BLOCK]); graphics.DrawString(20, screenHeight - 40, "SIZES:"); DrawValue(graphics, 140, screenHeight - 40, state.lSizes[_CLIENT_BLOCK]); graphics.DrawString(20, screenHeight - 20, "MOST MEM ALLOC:"); DrawValue(graphics, 140, screenHeight - 20, state.lHighWaterCount); } } #endif
true
ead912d45776aeea4b8b603858ecef1ec40a9279
C++
brandonleitch/sudoku
/lib/Grid.h
UTF-8
375
2.5625
3
[]
no_license
#ifndef GRID_H #define GRID_H #include <string> class Grid { private: std::string puzzle; std::string solution; char grid[9][9]; bool check_cell(int row, int col); public: Grid(std::string p, std::string s); void init(); void set(int row, int col, char num); int get(int row, int col); bool is_puzzle_cell(int row, int col); bool check(); }; #endif
true
97c25398904e1aca6c73d8eaf9e7aea01b54a630
C++
wusiyan11/CC3K
/a5/game.h
UTF-8
691
2.609375
3
[]
no_license
#ifndef __GAME_H__ #define __GAME_H__ #include <iostream> #include <string> class Cell; class TextDisplay; class Chamber; class GameObject; using namespace std; class Game { int player_count; int stair_count[5],potion_count[5],gold_count[5],enemy_count[5]; Cell*** grid; int floorlevel; TextDisplay* display; // Chamber* rooms; char initialized_player; public: int player_x,player_y; Game(string filename, char chosen_player); ~Game(); void levelup(); GameObject* get_object(int x, int y); string get_type(int x, int y); void spawnPlayer(); void spawnStair(); void spawnObjects(); void setItem(); void change(); void updatedisplay(); void print(); }; #endif
true
373fb63dcba93af1c53ea9ee8610ab68c7343d0c
C++
lingqtan/myLeetcode
/1Array/283. Move Zeroes.cpp
UTF-8
1,408
2.71875
3
[ "Apache-2.0" ]
permissive
class Solution { public: void moveZeroes(vector<int>& nums) { // // slow version (16ms, 12.13%) // int cur_pos = 0, i = 0; // while (cur_pos < nums.size() && i < nums.size()) { // while (nums[cur_pos] != 0 && cur_pos < nums.size()) cur_pos++; // i = cur_pos; // while (nums[i] == 0 && i < nums.size()) i++; // if (cur_pos < nums.size() && i < nums.size()) { // int k = nums[cur_pos]; // nums[cur_pos] = nums[i]; // nums[i] = k; // } // } // faster version (12ms, 36.57%) // int i = 0, j = 1; // while (i < nums.size() && j < nums.size()) { // if (nums[i] == 0 && nums[j] != 0 && j > i) { // int k = nums[i]; // nums[i] = nums[j]; // nums[j] = k; // i++; j++; // } // if (i < nums.size() && nums[i] != 0) i++; // if (nums[i] == 0) { // j = i+1; // while (j < nums.size() && nums[j] == 0) j++; // } // } // fast version (8 ms, 100.00%) int i = 0, j = 0; for (i = 0; i < nums.size(); i++) if (nums[i] != 0) nums[j++] = nums[i]; if (j < nums.size()) for (i = j; i < nums.size(); i++) nums[i] = 0; } };
true
925bae6e3e5a29a92008e9f36d320e22b544bc37
C++
andylinpersonal/OpenCG3
/src/main.cpp
UTF-8
1,040
2.8125
3
[]
no_license
#include "main.hpp" using namespace std; using namespace OpenCG3; int main(int argc, char** argv) { // parse some args... int arg; string icon_filename; while ((arg = getopt(argc, argv, "h")) != -1) { switch (arg) { case 'h': puts("\nSimple 3D Viewer\nMade by KVD the PIG and ADL the sweet potato in 2017\n\n"); printf("%s -[opt]\n\n", argv[0]); puts("\t-h\thelp: print this message.\n"); puts("\t-i\ticon: custom icon.\n"); return EXIT_SUCCESS; case 'i': icon_filename = string(optarg); break; case '?': puts("*spew* : some rot foods ..."); puts(optarg); puts("Don\'t input strange things into me. Ahhhhhhhhh~~~"); return EXIT_FAILURE; } } // Start background stdin recepter... (non-blocking) thread Thread_stdin_handler = thread(&Input::stdin_handle_worker, std::ref(Input::CommandQueue)); OpenCG3::App = Gtk::Application::create(argc, argv); OpenCG3::MainWindow root_win(icon_filename); int ret = OpenCG3::App->run(root_win); Thread_stdin_handler.join(); return ret; }
true
0785ab7c378e6cf7176ead78fff462a3b6170d39
C++
vinith-123/datastructures
/stacks/reverse with recur.cpp
UTF-8
1,200
3.53125
4
[]
no_license
#include<iostream> using namespace std; struct stack{ int size; int top; int elements[50]; }; bool isfull(stack &s) { if(s.top==s.size-1) return true; else return false; } bool isempty(stack &s) { if(s.top==-1) return true; else return false; } void push(stack &s,int x) { if(isfull(s)) cout<<"error stack is full\n"; else s.elements[++s.top]=x; } int pop(stack &s) { if(isempty(s)) return 0; else return s.elements[s.top--]; } void recur(stack &s,stack &temp) { if(s.top==-1) { s=temp; return ; } else { temp.elements[++temp.top]=s.elements[s.top--]; recur(s,temp); } } int main(){ int n,ele; stack *s1,*s2,*temp; s1=new(stack); s2=new(stack); temp=new(stack); s1->size=50;s1->top=-1; s2->size=50;s2->top=-1; temp->size=50;temp->top=-1; cout<<"enter no of elements\n"; cin>>n; for(int i=0;i<n;i++) { cin>>ele; push(*s1,ele); push(*s2,ele); } cout<<"original stack\n"; for(int i=0;i<n;i++) { cout<<pop(*s2)<<" "; } cout<<endl; recur(*s1,*temp); s1=temp; cout<<"reversed stack\n"; for(int i=0;i<n;i++) { cout<<pop(*s1)<<" "; } cout<<endl; return 0; }
true
9636fb405e16d59c1c8ab72b1fb88778d67cf367
C++
enzohorquin/SAT
/FormulaProposicional.h
UTF-8
925
2.65625
3
[]
no_license
#ifndef FORMULAPROPOSICIONAL_H #define FORMULAPROPOSICIONAL_H #include "Clausula.h" class FormulaProposicional { public: FormulaProposicional(); FormulaProposicional(const FormulaProposicional & c); void operator= (const FormulaProposicional & c); void agregarClausula(const Clausula & c); Clausula devolverUnitaria() const; Literal devolverPuro() const; void eliminacionUnitaria(const Clausula & c); void eliminacionPuro(const Literal & l); set<Clausula> obtenerFormulaProposicional() const; bool vacio() const; bool existeClausulaVacia() const; Literal tope() const; void vaciarFormulaProposicional(); void eliminarClausula(const Clausula & c); set<QString> get_Variables(); int cantClausulas(); virtual ~FormulaProposicional(); set<Literal> get_Literales() const; protected: private: set<Clausula> Formula; }; #endif // FORMULAPROPOSICIONAL_H
true
b8ab16c9a0618afa7dcc07c037694938c2fb7be3
C++
Raghav-Bajaj/HacktoberFest-2
/cpp/circular_linked_list.cpp
UTF-8
2,503
3.828125
4
[]
no_license
#include <stdio.h> #include <stdlib.h> struct node { int num; struct node * nextptr; }*stnode; void ClListcreation(int n); void ClLinsertNodeAtBeginning(int num); void displayClList(int a); int main() { int n,num1,a; stnode = NULL; printf("\n\n Circular Linked List : Insert a node at the beginning of a circular linked list :\n"); printf("--------------------------------------------------------------------------------------\n"); printf(" Input the number of nodes : "); scanf("%d", &n); ClListcreation(n); a=1; displayClList(a); printf(" Input data to be inserted at the beginning : "); scanf("%d", &num1); ClLinsertNodeAtBeginning(num1); a=2; displayClList(a); return 0; } void ClListcreation(int n) { int i, num; struct node *preptr, *newnode; if(n >= 1) { stnode = (struct node *)malloc(sizeof(struct node)); printf(" Input data for node 1 : "); scanf("%d", &num); stnode->num = num; stnode->nextptr = NULL; preptr = stnode; for(i=2; i<=n; i++) { newnode = (struct node *)malloc(sizeof(struct node)); printf(" Input data for node %d : ", i); scanf("%d", &num); newnode->num = num; newnode->nextptr = NULL; // next address of new node set as NULL preptr->nextptr = newnode; // previous node is linking with new node preptr = newnode; // previous node is advanced } preptr->nextptr = stnode; //last node is linking with first node } } void ClLinsertNodeAtBeginning(int num) { struct node *newnode, *curNode; if(stnode == NULL) { printf(" No data found in the List yet."); } else { newnode = (struct node *)malloc(sizeof(struct node)); newnode->num = num; newnode->nextptr = stnode; curNode = stnode; while(curNode->nextptr != stnode) { curNode = curNode->nextptr; } curNode->nextptr = newnode; stnode = newnode; } } void displayClList(int m) { struct node *tmp; int n = 1; if(stnode == NULL) { printf(" No data found in the List yet."); } else { tmp = stnode; if (m==1) { printf("\n Data entered in the list are :\n"); } else { printf("\n After insertion the new list are :\n"); } do { printf(" Data %d = %d\n", n, tmp->num); tmp = tmp->nextptr; n++; }while(tmp != stnode); } }
true
60c979556b2a15d1e33a134cb23d919ec356bd77
C++
LaVestima/tcs-oop-ex2a
/mainwindow.cpp
UTF-8
4,122
2.875
3
[]
no_license
#include "mainwindow.h" #include "student.h" #include "studentlist.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); student = new Student; studentList = new StudentList; } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_addItemButton_clicked() { Student *newStudent = new Student; QString newName = ui->nameLineEdit->text(); QString newAddress = ui->addressLineEdit->text(); QString newAge = ui->ageLineEdit->text(); if (newName == "" || newAddress == "" || newAge == "") { ui->errorLabel->setText("All of the field must be filled!"); } else { newStudent->setName(newName); newStudent->setAddress(newAddress); newStudent->setAge(newAge); studentList->addItem(newStudent); ui->listWidget->insertItem(0, new QListWidgetItem(newName + " " + newAddress + " " + newAge)); ui->errorLabel->setText(""); ui->nameLineEdit->setText(""); ui->addressLineEdit->setText(""); ui->ageLineEdit->setText(""); } delete newStudent; } void MainWindow::on_appendItemButton_clicked() { Student *newStudent = new Student; QString newName = ui->nameLineEdit->text(); QString newAddress = ui->addressLineEdit->text(); QString newAge = ui->ageLineEdit->text(); if (newName == "" || newAddress == "" || newAge == "") { ui->errorLabel->setText("All of the field must be filled!"); } else { newStudent->setName(newName); newStudent->setAddress(newAddress); newStudent->setAge(newAge); studentList->appendItem(newStudent); ui->listWidget->addItem(new QListWidgetItem(newName + " " + newAddress + " " + newAge)); ui->errorLabel->setText(""); ui->nameLineEdit->setText(""); ui->addressLineEdit->setText(""); ui->ageLineEdit->setText(""); } delete newStudent; } void MainWindow::on_findItemButton_clicked() { QString findWord = ui->findItemLineEdit->text(); int rowNumber = ui->listWidget->currentRow(); int findRowNumber = studentList->findItem(rowNumber, findWord); if (findWord == "") { ui->errorLabel->setText("No word entered!"); } else { ui->createListButton->setText(QString::number(findRowNumber)); ui->listWidget->setCurrentRow(findRowNumber); } } void MainWindow::on_deleteItemButton_clicked() { int rowNumber = ui->listWidget->currentRow(); if (rowNumber == -1) { ui->errorLabel->setText("No item selected!"); } else { studentList->deleteItem(rowNumber); ui->listWidget->takeItem(rowNumber); ui->listWidget->setCurrentRow(-1); } } void MainWindow::on_deleteAllButton_clicked() { int i = 0; studentList->deleteList(); while (ui->listWidget->item(i)) { delete ui->listWidget->takeItem(i); } } void MainWindow::on_editItemButton_clicked() { int rowNumber = ui->listWidget->currentRow(); if (rowNumber == -1) { ui->errorLabel->setText("No item selected!"); } else { Student *newStudent = new Student; QString newName = ui->nameLineEdit->text(); QString newAddress = ui->addressLineEdit->text(); QString newAge = ui->ageLineEdit->text(); if (newName == "" || newAddress == "" || newAge == "") { ui->errorLabel->setText("All of the field must be filled!"); } else { newStudent->setName(newName); newStudent->setAddress(newAddress); newStudent->setAge(newAge); studentList->editItem(rowNumber, newStudent); ui->listWidget->takeItem(rowNumber); ui->listWidget->insertItem(rowNumber, new QListWidgetItem(newName + " " + newAddress + " " + newAge)); ui->listWidget->setCurrentRow(-1); ui->errorLabel->setText(""); ui->nameLineEdit->setText(""); ui->addressLineEdit->setText(""); ui->ageLineEdit->setText(""); } } }
true
ec02e083cdd1e34c050e9c838ee65c8004fbf04a
C++
Linzecong/My-ACM-Code
/HDU/1864/10395699_AC_421ms_13280kB.cpp
UTF-8
1,464
2.53125
3
[]
no_license
#include <stdio.h> #include <algorithm> #include <string.h> using namespace std; int dp[3000050];//由于每张发票不超过1000,最多30张,扩大100倍数后开这么大即可 int main() { char ch; double x,y; int sum,a,b,c,money[35],v; int t,i,j,k; while(~scanf("%lf%d",&x,&t),t) { sum = (int)(x*100);//将小数化作整数处理 memset(money,0,sizeof(money)); memset(dp,0,sizeof(dp)); int l = 0; for(i = 0; i<t; i++) { scanf("%d",&k); a = b = c = 0; int flag = 1; while(k--) { scanf(" %c:%lf",&ch,&y); v = (int)(y*100); if(ch == 'A' && a+v<=60000) a+=v; else if(ch == 'B' && b+v<=60000) b+=v; else if(ch == 'C' && c+v<=60000) c+=v; else flag = 0; } if(a+b+c<=100000 && a<=60000 && b<=60000 && c<=60000 && flag)//按题意所说,必须满足这些条件 money[l++] = a+b+c; } for(i = 0; i<=l; i++) { for(j = sum; j>=money[i]; j--) dp[j] = max(dp[j],dp[j-money[i]]+money[i]); } printf("%.2lf\n",dp[sum]/100.0); } return 0; }
true
c8010d2a6f03c5983c6e0cad3bf80115f958043e
C++
shreysingla11/ssl-project
/Backend/Parser/submissions/Assignment 6/12.cpp
UTF-8
433
2.671875
3
[]
no_license
#include<iostream> #include<string> using namespace std; int main() { string A; int Count=0; cin>>A; int n=A.length(); double l; for(l=1;l<n;l++) { for(double i=0.0;i<((n*1.0)/l);i++) { if(A.substr(i,l)==A.substr(i+l,l)) { Count=Count+1; cout<<l<<" "<<i<<endl; break; } } } //cout<<Count<<endl; if(Count==0){cout<<"0 0";} return 0; }
true
926b1aaae7b67c6beed0a652b12f4e1eb57cb2da
C++
alextac98/RBE-2001
/Robot/Arm.h
UTF-8
651
2.59375
3
[]
no_license
// Arm.h #ifndef _ARM_h #define _ARM_h #include "Servo.h" typedef enum { down, mid, up } armPos; class Arm { public: Arm(); void armSetup(); void setArmPosition(armPos); bool isArmPosition(armPos); bool closeGripper(); bool openGripper(); int getArmPosition(); private: Servo jxServo; Servo gripper; long lastClosedTime; long lastOpenTime; const int gripperDelay = 500; //in millis const int gripperClosed = 180; const int gripperOpen = 0; const int armUp = 176; const int armMid = 114; const int armDown = 0; const int threshold = 10; const int isUp = 915; const int isMid = 728; const int isDown = 262; }; #endif
true
b20930db7e7d8286b69e8e1c5d55d617e4b9d105
C++
torresmateo/vector-racer
/source/draw/pathSection.hpp
UTF-8
4,226
3.484375
3
[]
no_license
#ifndef PATH_SECTION_H #define PATH_SECTION_H //clase que reprsenta una sección del túnel class PathSection { //radio de la sección float radius; //número de segmentos que componen la sección int numberOfSegments; //posición inicial del centro de la sección Vector3D positionIni; //normal inicial, perpendicular a un corte transversal al inicio de la sección //indica la orientación del corte transversal Vector3D normalIni; //los vectores End asumen que el origen esta centrado en positionIni //y son análogos a los vectores Ini Vector3D positionEnd; Vector3D normalEnd; //vector de obstáculos de la sección vector<Obstacle*> obstacles; //vector de esferas azules de la sección vector<BlueSphere*> blueSpheres; //vector de esferas blancas de la sección vector<WhiteSphere*> whiteSpheres; //vector de esferas fucsias de la sección vector<FuchsiaSphere*> fuchsiaSpheres; //borrar obstáculos y esferas de la sección void deleteItems(); //generar obstáculos y esferas de la sección void createItems(); //generar obstáculos y esferas de la sección ignorando los primeros "segmentsLeftOut" segments void createItems( int segmentsLeftOut ); public: //constructors PathSection() { radius = 1.0f; numberOfSegments = 1; positionIni = Vector3D(0.0f,0.0f,0.0f); normalIni = Vector3D(0.0f,0.0f,1.0f); positionEnd = Vector3D(0.0f,0.0f,1.0f); normalEnd = Vector3D(0.0f,0.0f,1.0f); for(int i = 0; i<84; i++){ obstacles.push_back(NULL); blueSpheres.push_back(NULL); whiteSpheres.push_back(NULL); fuchsiaSpheres.push_back(NULL); } createItems(); } PathSection( int segmentsLeftOut ) { radius = 1.0f; numberOfSegments = 1; positionIni = Vector3D(0.0f,0.0f,0.0f); normalIni = Vector3D(0.0f,0.0f,1.0f); positionEnd = Vector3D(0.0f,0.0f,1.0f); normalEnd = Vector3D(0.0f,0.0f,1.0f); for(int i = 0; i<84; i++){ obstacles.push_back(NULL); blueSpheres.push_back(NULL); whiteSpheres.push_back(NULL); fuchsiaSpheres.push_back(NULL); } createItems( segmentsLeftOut ); } PathSection(float radius, Vector3D positionIni, Vector3D normalIni, Vector3D positionEnd, Vector3D normalEnd, int numberOfSegments ) { this->radius = radius; this->positionIni = positionIni; this->normalIni = normalIni; this->positionEnd = positionEnd; this->normalEnd = normalEnd; this->numberOfSegments = numberOfSegments; for(int i = 0; i<100; i++){ obstacles.push_back(NULL); blueSpheres.push_back(NULL); whiteSpheres.push_back(NULL); fuchsiaSpheres.push_back(NULL); } createItems(); } //seters void setRadius(float newRadius); void setNumberOfSegments(int newNumberOfSegments); void setPositionIni( Vector3D newPosition ); void setNormalIni( Vector3D newOrientation ); void setPositionEnd( Vector3D newPosition ); void setNormalEnd( Vector3D newOrientation ); //geters float getRadius(); int getNumberOfSegments(); Vector3D getPositionIni(); Vector3D getNormalIni(); Vector3D getPositionEnd(); Vector3D getNormalEnd(); //utils //regenerar los obstáculos y esferas de la sección void resetItems(); //regenerar los obstáculos y esferas de la sección ignorando los primeros "segmentsLeftOut" segmentos void resetItems(int segmentsLeftOut); //retorna true si hay un obstáculo en el segmento i bool thereIsObstacle(int i); //retorna true si hay una esfera azúl en el segmento i bool thereIsBlueSphere(int i); //retorna true si hay una esfera blanca en el segmento i bool thereIsWhiteSphere(int i); //retorna true si hay una esfera fucsia en el segmento i bool thereIsFuchsiaSphere(int i); //retorna el obtáculo del segmento i Obstacle* getObstacle(int i); //retorna la esfera azúl del segmento i BlueSphere* getBlueSphere(int i); //retorna la esfera blanca del segmento i WhiteSphere* getWhiteSphere(int i); //retorna la esfera fucsia del segmento i FuchsiaSphere* getFuchsiaSphere(int i); }; #endif
true
17913c9ee867e034396b56dc705c4da578eb669b
C++
harshbhandari7/CPP
/Basic/stringReverse1.cpp
UTF-8
236
2.9375
3
[]
no_license
#include<iostream> int main(){ int n; std::cin>>n; char str[n]; gets(str); std::cout<<"\n"; int i=sizeof(str)/sizeof(char); std::cout<<i; for(i-1;i>-1;i--){ std::cout<<str[i]; } }
true
a1e66a63d7a729c2738005458671d54d66f39016
C++
linsallyzhao/earlyobjects-exercises
/2015/chapter_13/examples/13_5.cpp
UTF-8
403
2.859375
3
[]
no_license
#include <iostream> #include <string> #include <fstream> int main() { std::fstream file; std::string input; file.open("murphy.txt", std::ios::in); if (!file) { std::cout << "File open error! " << std::endl; return 0; } file >> input; while (!file.fail()) { std::cout << input; file >> input; } file.close(); return 0; }
true
3b3b585fd56e2707916bcb0bb475cc11a55d00ec
C++
keitaroooo/atcoder-studying
/atcoder-regular-contest/114/A.cpp
UTF-8
2,274
3.078125
3
[]
no_license
#include <algorithm> #include <cmath> #include <iomanip> #include <iostream> #include <set> #include <string> #include <vector> using namespace std; const vector<int> PRIME = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47}; const int PRIME_SIZE = PRIME.size(); vector<int> integerToVector(int bit, int m) { vector<int> S; for(int i = 0; i < m; ++i) { if(bit & (1 << i)) { S.push_back(i); } } return S; } // 最大公約数を求める long long caliculateGcd(long long a, long long b) { if(b == 0) { return a; } else { return caliculateGcd(b, a % b); } } int main() { int N; cin >> N; vector<int> X(N); for(int i = 0; i < N; ++i) cin >> X[i]; long long min = 1; for(int x : PRIME) min *= x; for(int i = 1; i < (1 << PRIME_SIZE); ++i) { vector<int> binary = integerToVector(i, PRIME_SIZE); long long subset = 1; for(int x : binary) subset *= PRIME[x]; bool flag = false; for(int j = 0; j < N; ++j) { if(caliculateGcd(subset, X[j]) == 1) { flag = true; break; } } if(flag == false) min = std::min(min,subset); } cout << min << endl; } // int main() { // int N; // cin >> N; // vector<int> X(N); // for(int i = 0; i < N; ++i) cin >> X[i]; // int min = caliculateGcd(X[0], X[1]); // if(min == 1) { // int a = 2; // while(true) { // if(X[0] % a == 0) { // min *= a; // break; // } // a++; // } // a = 2; // while(true) { // if(X[1] % a == 0) { // min *= a; // break; // } // a++; // } // } // for(int i = 1; i < N; ++i) { // int gcd = caliculateGcd(min, X[i]); // if(gcd == 1) min *= X[i]; // } // cout << min << endl; // return 0; // } // int main() { // int N; // cin >> N; // vector<int> X(N); // for(int i = 0; i < N; ++i) cin >> X[i]; // int min = 2; // for(;; ++min) { // int i = 0; // for(; i < N; ++i) { // int gcd = caliculateGcd(X[i], min); // if(gcd == 1) break; // } // if(i == N) break; // } // cout << min << endl; // return 0; // }
true
4ed98b60198e27e2438926ad4973a3f23bdc27a2
C++
opendarkeden/server
/src/server/gameserver/skill/Concealment.h
UTF-8
1,036
2.65625
3
[]
no_license
////////////////////////////////////////////////////////////////////////////// // Filename : Concealment.h // Written By : // Description : ////////////////////////////////////////////////////////////////////////////// #ifndef __SKILL_CONCEALMENT_HANDLER_H__ #define __SKILL_CONCEALMENT_HANDLER_H__ #include "SkillHandler.h" ////////////////////////////////////////////////////////////////////////////// // class Concealment; ////////////////////////////////////////////////////////////////////////////// class Concealment : public SkillHandler { public: Concealment() throw() {} ~Concealment() throw() {} public: string getSkillHandlerName() const throw() { return "Concealment"; } SkillType_t getSkillType() const throw() { return SKILL_CONCEALMENT; } void execute(Slayer* pSlayer, SkillSlot* pSkillSlot, CEffectID_t CEffectID) ; void computeOutput(const SkillInput& input, SkillOutput& output); }; // global variable declaration extern Concealment g_Concealment; #endif // __SKILL_CONCEALMENT_HANDLER_H__
true
a817ab4bcefd0ad6fb53c6b4d9686c6bd0665c3d
C++
atmikajoy/CodingPractice
/CodingPractice/main.cpp
UTF-8
562
2.71875
3
[]
no_license
#include<iostream> #include"leastLetterCount.h" #include"arrEqual.h" #include"eggDrop.h" #include"wavesort.h" int main() { std::cout<<"letter with least frequency = " << llc::low_letter_freq("geeksforgeeks")<<'\n'; std::cout << "The arrays are equal : " << std::boolalpha << arreq::are_arrays_equal({ 1,2,3,4,5 }, { 2,1,3,5,4 }); std::cout << "\nEgg-Floor problem solution thingy : " << eggdrop::eggDrop(2, 36); std::cout << "\nWave sort = "; for(auto& i : ws::wavesort({ 1,2,3,4,5,6,7,8,9 })) std::cout<<i<<' '; }
true
970b226e55ae2625e0ae7d55f1527b65d063d20d
C++
icushman/tsp-heuristics
/heur2.cc
UTF-8
2,303
2.5625
3
[]
no_license
#include <config.h> #include "heur2.h" // class header file #include <util/nainf.h> // provides na and inf functions #include <cmath> // basic math operations #include <iostream> #include <typeinfo> #include <algorithm> #include <util/dim.h> #include <util/logical.h> using std::vector; // vector is used in the code using std::string; // string is used in the code #define step (*args[0]) // time step in problem #define npoints (*args[1]) // number of points in problem #define coords (args[2]) // ordered points array as (x, y) tuples namespace jags { namespace TSPHeuristics { heur2::heur2() :ArrayFunction ("heuristic2", 3) {} void heur2::evaluate(double *value, std::vector<double const *> const &args, std::vector<std::vector<unsigned int> > const &dims) const { int step_num = int (step) - 1; double coordPair [2]; float currentX = coords[step_num*2]; float currentY = coords[step_num*2+1]; float targetX; float targetY; for (unsigned int i = 0; i <= step_num; i++) { value[i] = 0; // value[i] = coords[i]; } for (unsigned int i = step_num + 1; i < npoints; i++) { targetX = coords[i*2]; targetY = coords[i*2+1]; value[i] = sqrt(pow((currentY - targetY),2) + pow((currentX - targetX),2)); // value[i] = currentX == targetX; } } unsigned int heur2::length (vector<unsigned int> const &parlengths, vector<double const *> const &parvalues) const { return (parvalues[1][0]); } bool heur2::checkParameterDim(std::vector<std::vector<unsigned int> > const &dims) const { return true; } std::vector<unsigned int> heur2::dim(std::vector <std::vector<unsigned int> > const &dims, std::vector <double const *> const &values) const { std::vector<unsigned int> v(1); v[0] = dims[2][0]/2; //v[1] = 3; return v; } }} //Because theJAGSprogramming structure inC++does not handle matrices, the covariance matrixshould be returned in a (1×n2)-dimensional vector //http://www.est.ufmg.br/~posgrad/mestrado/dissertacao_Magno_Severino.pdf
true
0a85d3946e51dddc1d80a1261cd11d8c8e6ea3e0
C++
AYOKINYA/CPP_MODULE
/CPP_MODULE_05/ex03/PresidentialPardonForm.cpp
UTF-8
1,731
2.546875
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* PresidentialPardonForm.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jkang <jkang@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/08/14 19:43:33 by jkang #+# #+# */ /* Updated: 2020/08/14 19:44:14 by jkang ### ########.fr */ /* */ /* ************************************************************************** */ #include "PresidentialPardonForm.hpp" PresidentialPardonForm::PresidentialPardonForm() {} PresidentialPardonForm::~PresidentialPardonForm() { } PresidentialPardonForm::PresidentialPardonForm(std::string const &target) : Form("tmp", 25, 5, 0), target(target) {} PresidentialPardonForm::PresidentialPardonForm(PresidentialPardonForm const &copy) : Form("tmp", 25, 5, 0), target("") { *this = copy; } PresidentialPardonForm& PresidentialPardonForm::operator=(PresidentialPardonForm const & PresidentialPardonForm) { if (this == &PresidentialPardonForm) return (*this); Form::operator=(PresidentialPardonForm); return (*this); } void PresidentialPardonForm::execute(Bureaucrat const & executor) const { Form::check(executor); std::cout << "<" << this->target << "> pardoned by Zafod Beeblebrox." << std::endl; }
true
fde77ac22fbdc04113becac905c4a71c66837e08
C++
PierrickLP/ObEngine
/src/Core/Script/ViliLuaBridge.cpp
UTF-8
3,917
2.625
3
[ "MIT", "BSD-2-Clause", "Zlib" ]
permissive
#include <Script/ViliLuaBridge.hpp> #include <Utils/StringUtils.hpp> #include <Utils/VectorUtils.hpp> #include <sol/sol.hpp> namespace obe::Script::ViliLuaBridge { sol::lua_value viliToLua(vili::node& convert) { if (convert.is<vili::array>()) { return viliArrayToLuaTable(convert); } else if (convert.is<vili::object>()) { return viliObjectToLuaTable(convert); } else if (convert.is_primitive()) { return viliPrimitiveToLuaValue(convert); } } vili::node luaToVili(sol::object convert) { if (convert.is<sol::table>()) { vili::integer expect = 1; for (auto& [k, _] : convert.as<sol::table>()) { if (!k.is<vili::integer>() || k.as<vili::integer>() != expect++) { return luaTableToViliObject(convert); } } return luaTableToViliArray(convert); } else { return luaValueToViliPrimitive(convert); } } sol::lua_value viliObjectToLuaTable(vili::node& convert) { std::unordered_map<std::string, sol::lua_value> result; for (auto [key, value] : convert.items()) { if (value.is_primitive()) { result.emplace(key, viliPrimitiveToLuaValue(value)); } else if (value.is<vili::object>()) { result.emplace(key, viliObjectToLuaTable(value)); } else if (value.is<vili::array>()) { result.emplace(key, viliArrayToLuaTable(value)); } } return sol::as_table(result); } sol::lua_value viliPrimitiveToLuaValue(vili::node& convert) { if (convert.is<vili::integer>()) return convert.as<vili::integer>(); else if (convert.is<vili::string>()) return convert.as<vili::string>(); else if (convert.is<vili::boolean>()) return convert.as<vili::boolean>(); else if (convert.is<vili::number>()) return convert.as<vili::number>(); } sol::lua_value viliArrayToLuaTable(vili::node& convert) { std::vector<sol::lua_value> result; std::size_t index = 0; for (vili::node& value : convert) { if (value.is_primitive()) result.push_back(viliPrimitiveToLuaValue(value)); else if (value.is<vili::array>()) result.push_back(viliArrayToLuaTable(value)); else if (value.is<vili::object>()) result.push_back(viliObjectToLuaTable(value)); } return sol::as_table(result); } vili::node luaTableToViliObject(sol::table convert) { vili::node result = vili::object {}; for (auto& [key, value] : convert) { result.insert(key.as<std::string>(), luaToVili(value)); } return result; } vili::node luaValueToViliPrimitive(sol::lua_value convert) { vili::node result; if (convert.is<vili::integer>()) { result = convert.as<vili::integer>(); } else if (convert.is<vili::number>()) { result = convert.as<vili::number>(); } else if (convert.is<vili::boolean>()) { result = convert.as<vili::boolean>(); } else if (convert.is<vili::string>()) { result = convert.as<vili::string>(); } return result; } vili::node luaTableToViliArray(sol::table convert) { vili::node result = vili::array {}; for (auto& [_, value] : convert) { result.push(luaToVili(value)); } return result; } } // namespace obe::Script::DataBridge
true
00240883fbbee4570c904ff995aaf32a7aec937f
C++
Dreamgoing/MySTL
/Iterator.hpp
UTF-8
1,584
2.953125
3
[]
no_license
// // Created by 王若璇 on 17/5/7. // #ifndef MYSTL_ITERATOR_HPP #define MYSTL_ITERATOR_HPP #include <stddef.h> ///设计迭代器模式 ///@brief 迭代器的设计与萃取实践 ///@note namespace MySTL{ ///@brief iterator_category 根据移动特性与施行操作,迭代器被分为五类: struct input_iterator_tag{}; struct output_iterator_tag{}; struct forward_iterator_tag:public input_iterator_tag{}; struct bidirectional_iterator_tag:public forward_iterator_tag{}; struct random_access_iterator_tag:public bidirectional_iterator_tag{}; template <class T,class Distance> struct input_iterator{ typedef input_iterator_tag iterator_category; typedef T value_type; typedef Distance difference_type; typedef T* pointer; typedef T& reference; }; template <class Category,class T,class Distance=ptrdiff_t , class Pointer = T*,class Reference = T&> struct iterator{ typedef Category iterator_category; typedef T value_type; typedef Distance difference_type; typedef Pointer pointer; typedef Reference reference; }; template <class Iterator> struct iterator_traits { typedef typename Iterator::iterator_category iterator_category; typedef typename Iterator::value_type value_type; typedef typename Iterator::difference_type difference_type; typedef typename Iterator::pointer pointer; typedef typename Iterator::reference reference; }; } #endif //MYSTL_ITERATOR_HPP
true
64c856c23acd8f3097ebf0c531bfd5aa3fcc4c5c
C++
SausageTaste/VulkanPractice
/apps/semaphore.h
UTF-8
1,961
2.59375
3
[ "MIT" ]
permissive
#pragma once #include <array> #include <vector> #include <utility> #include <vulkan/vulkan.h> #include "konst.h" namespace dal { class Semaphore { private: VkSemaphore m_handle = VK_NULL_HANDLE; public: void init(VkDevice device); void destroy(VkDevice device); auto get(void) const { return this->m_handle; } }; class Fence { private: VkFence m_handle = VK_NULL_HANDLE; public: void init(VkDevice device); void destroy(VkDevice device); auto& get(void) { return this->m_handle; } auto& get(void) const { return this->m_handle; } bool isReady(void) const { return VK_NULL_HANDLE != this->m_handle; } void wait(VkDevice device) const; void reset(VkDevice device) const; }; class SyncMaster { private: std::array<Semaphore, MAX_FRAMES_IN_FLIGHT> m_imageAvailable, m_renderFinished; std::array<Fence, MAX_FRAMES_IN_FLIGHT> m_inFlightFences; std::vector<VkFence> m_imageInFlight; public: void init(VkDevice device, const unsigned swapChainImgCount); void destroy(VkDevice device); auto& semaphImageAvailable(const unsigned index) const { return this->m_imageAvailable[index]; } auto& semaphRenderFinished(const unsigned index) const { return this->m_renderFinished[index]; } auto& fenceInFlight(const unsigned index) const { return this->m_inFlightFences[index]; } auto& fencesImageInFlight(void) { return this->m_imageInFlight; } auto& fencesImageInFlight(void) const { return this->m_imageInFlight; } std::pair<uint32_t, VkResult> acquireGetNextImgIndex(const unsigned index, VkDevice device, VkSwapchainKHR swapChain); }; }
true
9877f437aa84208c9d537812de63d9cc200dd467
C++
gbarne2/catanbaton
/Project2/player.h
UTF-8
2,410
2.625
3
[]
no_license
#pragma once #include <vector> #include <algorithm> #include <string> #include <iostream> #include <WinSock2.h> #include <WS2tcpip.h> #ifndef START_CARD_VALUES #define START_CARD_VALUES #define START_ORE 50 #define START_SHEEP 50 #define START_BRICK 50 #define START_WHEAT 50 #define START_WOOD 50 #define START_SETTLEMENTS 50 #define START_ROADS 150 #define START_CITIES 4 #endif using namespace std; /* struct trade_cards { unsigned int qty_wood_to_trade; unsigned int qty_wood_to_receive; unsigned int qty_ore_to_trade; unsigned int qty_ore_to_receive; unsigned int qty_brick_to_trade; unsigned int qty_brick_to_receive; unsigned int qty_wheat_to_trade; unsigned int qty_wheat_to_receive; unsigned int qty_sheep_to_trade; unsigned int qty_sheep_to_receive; }; */ struct dev_cards { int qty_knights; //1 int qty_victory_points; //2 int qty_year_of_plenty; //3 int qty_monopoly; //4 int qty_build_roads; //5 }; class player { sockaddr client_address; SOCKET ClientSocket; vector<unsigned int> docks; int player_ID; std::string Player_name; int qty_wood; int qty_ore; int qty_brick; int qty_wheat; int qty_sheep; int roads_to_place; int settlements_to_build; int cities_to_build; dev_cards DC; int calculate_victory_points(int); long int numRXbytes; long int numTXbytes; int execute_dock_trade(int type, int qty, int requested_card, int dock); public: player(void); player(int, std::string); player(int, std::string, SOCKET); void set_client_address(sockaddr, SOCKET); SOCKET get_client_socket(void); int get_number_of_docks(); int check_if_dock_available(int type); //returns > 1 if the dock of type is owned by player. int use_dock_to_trade(int type, int qty, int requested_card); int add_dock_to_player(int type); int get_dock_by_index(int index); int update_resources(int type, int amount); int check_resource_amount(int type); int roads_left(void); int settlements_left(void); int cities_left(void); int update_roads(int); int update_settlements(int); int update_cities(int); int check_qty_devcard(int); int purchase_dev_card(int); int use_dev_card(int); //if retval >= 0, then it was deducted/valid. if -52, not enough of selected card. if -51, invalid card. int get_victory_points(int); ~player(void); void add_RX_bytes(int); void add_TX_bytes(int); long int check_num_rx_bytes(); long int check_num_tx_bytes(); };
true
03540d771918e7e17ec3d9ffaf3dcf34a4e3f75f
C++
PercentEquals/CLL
/CLL/include/utils/search.hpp
UTF-8
470
3.171875
3
[ "MIT" ]
permissive
#pragma once #include <string> #include <vector> namespace cll { template<typename T> size_t search(const std::vector<T>& vec, const std::string& name, const size_t& l, const size_t& r) { if (r >= l) { size_t mid = l + (r - l) / 2; if (mid >= vec.size()) return vec.size(); if (vec[mid].name == name) return mid; if (vec[mid].name > name) return search(vec, name, l, mid - 1); return search(vec, name, mid + 1, r); } return vec.size(); } }
true
bbd80eec43db74ef759f5336f0596dce7fcc6a28
C++
SachiSakurane/owle
/test/range/mock.hpp
UTF-8
291
2.609375
3
[ "BSL-1.0" ]
permissive
#pragma once #include <owle/utility/convertible_to.hpp> template <class From, class To> requires owle::convertible_to<From, To> struct Connection { To apply(From v) { return static_cast<To>(v); } }; template <class Type, Type Value> struct Applier { Type apply() { return Value; } };
true
85210030d56b60e914d2e7b0793c40be5e2b6456
C++
lighttransport/nanosnap
/tests/test_convolve.cc
UTF-8
1,406
2.671875
3
[ "BSD-3-Clause", "MIT", "LicenseRef-scancode-public-domain" ]
permissive
#include "doctest/doctest.h" #include "nanosnap/nanosnap.h" #include <complex> #include <iostream> using namespace doctest; TEST_CASE("convolve1d_full") { #include "testvector/convolve_full.inc" std::vector<float> result(k_outnum); bool ret = nanosnap::convolve(g_a, k_n, g_v, k_m, &result, /* mode 0 = full */0); CHECK(ret == true); std::cout << "convolve(full): len = " << sizeof(g_reference) / sizeof(g_reference[0]) << std::endl; for (size_t i = 0; i < k_outnum; i++) { CHECK(g_reference[i] == Approx(result[i])); } } TEST_CASE("convolve1d_same") { #include "testvector/convolve_same.inc" std::vector<float> result(k_outnum); bool ret = nanosnap::convolve(g_a, k_n, g_v, k_m, &result, /* mode 1 = same */1); CHECK(ret == true); std::cout << "convolve(same): len = " << sizeof(g_reference) / sizeof(g_reference[0]) << std::endl; for (size_t i = 0; i < k_outnum; i++) { CHECK(g_reference[i] == Approx(result[i])); } } TEST_CASE("convolve1d_valid") { #include "testvector/convolve_valid.inc" std::vector<float> result(k_outnum); bool ret = nanosnap::convolve(g_a, k_n, g_v, k_m, &result, /* mode 2 = valid */2); CHECK(ret == true); std::cout << "convolve(valid): len = " << sizeof(g_reference) / sizeof(g_reference[0]) << std::endl; for (size_t i = 0; i < k_outnum; i++) { CHECK(g_reference[i] == Approx(result[i])); } }
true
f89eabc77585db8ca56f11ce3372601e75c82507
C++
vtrej003/cs100Fall19
/src/command.cpp
UTF-8
805
2.875
3
[]
no_license
#include "../header/command.h" bool Command::mExToken = true; bool Command::mParenToken = false; std::string Command::mConnector = "NULL"; int Command::mExitStatus = 255; Command::Command(){} void Command::execute(){} void Command::setToken(bool token){ mExToken = token; // std::cout<<"Executable token had been called and set to: " << mExToken<<std::endl; } void Command::setParenToken(bool token){ mParenToken = token; } void Command::setConnector(std::string connector){ mConnector = connector; } bool Command::getToken(){ // std::cout<<"Executable token had been called and is returning: " << mExToken<<std::endl; return mExToken; } bool Command::getParenToken(){ return mParenToken; } std::string Command::getConnector(){ return mConnector; } //std::string Command::print(){}
true
2975d29fbf14bea2d3c378350f83d994c64b67af
C++
nishantkj911/codes
/knapsack01.cpp
UTF-8
1,098
3.0625
3
[]
no_license
#include <iostream> #include <bits/stdc++.h> using namespace std; int knapsackValue(vector<pair<int, int>> items, int W) { vector<vector<int>> m(items.size() + 1, vector<int>(W + 1, 0)); for (int i = 1; i <= items.size(); i++) { for (int j = 1; j <= W; j++) { m[i][j] = m[i-1][j]; if (j-items[i-1].first >= 0) m[i][j] = max(m[i][j], m[i-1][j - items[i-1].first] + items[i-1].second); } } /*for (auto i : m) { for (auto j : i) cout<<j<<" "; cout<<endl; }*/ return m[items.size()][W]; } int main() { //code int t; cin>>t; while(t--) { int n, W, temp; cin>>n>>W; vector<pair<int, int>> items; // first = weight, second = value for (int i = 0; i < n; i++) { cin>>temp; items.push_back(make_pair(0, temp)); } for (int i = 0; i < n; i++) { cin>>items[i].first; } cout<<knapsackValue(items, W)<<endl; } return 0; }
true
ec82317028422f4b4c7ee5452f0ad52493c1e561
C++
demian2435/42-CPP_Module_05
/CPP_Module_05/ex02/main.cpp
UTF-8
2,534
2.703125
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dmalori <dmalori@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/05/15 10:33:12 by dmalori #+# #+# */ /* Updated: 2021/05/15 10:33:33 by dmalori ### ########.fr */ /* */ /* ************************************************************************** */ #include "Bureaucrat.hpp" #include "Form.hpp" #include "PresidentialPardonForm.hpp" #include "ShrubberyCreationForm.hpp" #include "RobotomyRequestForm.hpp" #include <string> #include <iostream> #define RED "\033[0;31m" #define OFF "\033[0m" int main (void) { std::cout << RED << "**Form PresidentialPardonForm, B1-1, B2-67" << OFF << std::endl; try { PresidentialPardonForm f = PresidentialPardonForm("MARIO"); std::cout << f; Bureaucrat b1 = Bureaucrat("Pippo", 1); b1.signForm(f); f.execute(b1); b1.executeForm(f); Bureaucrat b2 = Bureaucrat("Gino", 67); b2.executeForm(f); f.execute(b2); } catch(std::exception& e) { std::cout << e.what() << std::endl; } std::cout << RED << "**Form RobotomyRequestForm, B1-5, B2-100" << OFF << std::endl; try { RobotomyRequestForm f = RobotomyRequestForm("MARIO"); std::cout << f; Bureaucrat b1 = Bureaucrat("Pippo", 5); f.execute(b1); b1.executeForm(f); b1.signForm(f); f.execute(b1); b1.executeForm(f); Bureaucrat b2 = Bureaucrat("Gino", 100); b2.executeForm(f); f.execute(b2); } catch(std::exception& e) { std::cout << e.what() << std::endl; } std::cout << RED << "**Form ShrubberyCreationForm, B1-50, B2-105" << OFF << std::endl; try { ShrubberyCreationForm f = ShrubberyCreationForm("MARIO"); std::cout << f; Bureaucrat b1 = Bureaucrat("Pippo", 50); b1.signForm(f); f.execute(b1); ShrubberyCreationForm f2 = ShrubberyCreationForm("PEPPE"); Bureaucrat b2 = Bureaucrat("Gino", 105); b2.executeForm(f2); b1.signForm(f2); b2.executeForm(f2); } catch(std::exception& e) { std::cout << e.what() << std::endl; } return (0); }
true
e1c3a22a00a33c7e42a346160abd38ef59d6f5aa
C++
su6i/master-imagina
/S3/HMIN322 - Codage et compression multimedia/TDs-TPs/lib/test/old/static_multidim.hpp
UTF-8
5,557
3.296875
3
[ "MIT" ]
permissive
#ifndef __STATIC_MULTIDIM_ARRAY__ #define __STATIC_MULTIDIM_ARRAY__ #include <array> #include <vector> #include <utility> #include <iostream> /* template<typename T, size_t dim> struct getTypeAtDim { using type = T; }; template<typename T, size_t N> struct getTypeAtDim<T[N], 1> { using type = T; }; template<typename T, size_t dim, size_t N> struct getTypeAtDim<T[N], dim> : getTypeAtDim<T, dim-1> {}; template<typename T, size_t dim> using typeAtDim = typename getTypeAtDim<T, dim>::type; template<typename T> typeAtDim<T, 1>& indexed(T& arr, const int& first) { return arr[first]; } template<typename T, typename... Args> typeAtDim<T, sizeof...(Args) + 1>& indexed(T& arr, const int& first, const Args& ...rest) { return indexed(arr[first], rest...); } template <typename T, size_t PrimaryDimension, size_t... Dimensions> struct MultiDim_impl { using Nested = typename MultiDim_impl<T, Dimensions...>::type; using type = Nested[PrimaryDimension]; }; template <typename T, size_t PrimaryDimension> struct MultiDim_impl<T, PrimaryDimension> { using type = T[PrimaryDimension]; }; template<typename T, size_t PrimaryDimension, size_t... Dimensions> using MultiDimArray = typename MultiDim_impl<T, PrimaryDimension, Dimensions...>::type; template<typename T, size_t PrimaryDimension, size_t... Dimensions> class Multidim_array { public: using type = MultiDimArray<T, PrimaryDimension, Dimensions...>; using value_type = T; using size_type = decltype(PrimaryDimension); using difference_type = std::ptrdiff_t; using reference = value_type&; using const_reference = const value_type&; using pointer = value_type*; using const_pointer = const value_type*; using iterator = pointer; using const_iterator = const_pointer; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; // STL INTERFACE // Accessors // reference at(size_t pos) { return this->m_data.at(pos); } // const_reference at(size_t pos) const { return this->m_data.at(pos); } reference operator[](size_t pos) { return this->m_data + pos; } const_reference operator[](size_t pos) const { return this->m_data + pos; } //reference front() { return this->m_data; } //const_reference front() const { return this->m_data; } //reference back() { return this->m_data + (PrimaryDimension * ... * Dimensions) - 1; } //const_reference back() const { return this->m_data + (PrimaryDimension * ... * Dimensions) - 1; } pointer data() { return this->m_data; } const_pointer data() const { return this->m_data; } // Iterators iterator begin() { return this->data(); } const_iterator begin() const { return this->data(); } iterator end() { return this->data() + (PrimaryDimension * ... * Dimensions); } const_iterator end() const { return this->data() + (PrimaryDimension * ... * Dimensions); } //Capacity constexpr bool empty() const { return begin() == end(); } constexpr size_type size() const { return std::distance(begin(), end()); } constexpr size_type max_size() const { return std::distance(begin(), end()); } // MULTIDIM_ARRAY INTERFACE typeAtDim<T, 1>& indexed(const int& first) { return this->m_data[first]; } template<typename... Args> typeAtDim<T, sizeof...(Args) + 1>& indexed(const int& first, const Args& ...rest) { return indexed(this->m_data[first], rest...); } template<typename... Args> typeAtDim<T, sizeof...(Args) + 1>& operator()(const int& first, const Args& ...rest) { return indexed(this->m_data[first], rest...); } private: MultiDimArray<T, PrimaryDimension, Dimensions...> m_data; }; */ template <typename T, size_t PrimaryDimension, size_t... Dimensions> struct Multidim_array_t_impl { using Nested = typename Multidim_array_t_impl<T, Dimensions...>::type; using type = std::array<Nested, PrimaryDimension>; }; template <typename T, size_t PrimaryDimension> struct Multidim_array_t_impl<T, PrimaryDimension> { using type = std::array<T, PrimaryDimension>; }; template <typename T, size_t PrimaryDimension, size_t... Dimensions> using Multidim_array_t = typename Multidim_array_t_impl<T, PrimaryDimension, Dimensions...>::type; template<typename T, size_t PrimaryDimension, size_t... Dimensions> struct Multidim_array : Multidim_array_t<T, PrimaryDimension, Dimensions...> {}; /* z * height + y * width + x // STL INTERFACE // Accessors reference at(size_t pos) { return this->m_data.at(pos); } const_reference at(size_t pos) const { return this->m_data.at(pos); } reference operator[](size_t pos) { return this->m_data[pos]; } const_reference operator[](size_t pos) const { return this->m_data[pos]; } reference front() { return this->m_data.front(); } const_reference front() const { return this->m_data.front(); } reference back() { return this->m_data.back(); } const_reference back() const { return this->m_data.back(); } pointer data() { return this->m_data.data(); } const_pointer data() const { return this->m_data.data(); } // Iterators iterator begin() { return this->data(); } const_iterator begin() const { return this->data(); } iterator end() { return this->data() + this->size(); } const_iterator end() const { return this->data() + this->size(); } //Capacity constexpr bool empty() const { return this->m_data.empty(); } constexpr size_type size() const { return this->m_data.size(); } constexpr size_type max_size() const { return this->m_data.max_size(); } */ #endif
true
d29bdcd55f135d3b29a437315dbadde4a9053af1
C++
ths-rwth/carl
/src/carl-common/datastructures/carlTree.h
UTF-8
31,757
3.171875
3
[ "MIT" ]
permissive
/** * @file carlTree.h * @author Gereon Kremer <gereon.kremer@cs.rwth-aachen.de> */ #pragma once #include <cassert> #include <iterator> #include <list> #include <limits> #include <stack> #include <type_traits> #include <vector> #include <carl-common/util/streamingOperators.h> namespace carl { template<typename T> class tree; namespace tree_detail { constexpr std::size_t MAXINT = std::numeric_limits<std::size_t>::max(); template<typename T> struct Node { std::size_t id; mutable T data; std::size_t parent; std::size_t previousSibling = MAXINT; std::size_t nextSibling = MAXINT; std::size_t firstChild = MAXINT; std::size_t lastChild = MAXINT; std::size_t depth = MAXINT; Node(std::size_t _id, T&& _data, std::size_t _parent, std::size_t _depth): id(_id), data(std::move(_data)), parent(_parent), depth(_depth) {} }; template<typename T> bool operator==(const Node<T>& lhs, const Node<T>& rhs) { return &lhs == &rhs; } template<typename T> std::ostream& operator<<(std::ostream& os, const Node<T>& n) { int id = (int)n.id; int parent = (n.parent == MAXINT ? -1 : (int)n.parent); int firstChild = (n.firstChild == MAXINT ? -1 : (int)n.firstChild); int lastChild = (n.lastChild == MAXINT ? -1 : (int)n.lastChild); int previousSibling = (n.previousSibling == MAXINT ? -1 : (int)n.previousSibling); int nextSibling = (n.nextSibling == MAXINT ? -1 : (int)n.nextSibling); os << "(" << n.data << " @ " << id << ", " << parent << ", " << firstChild << ":" << lastChild << ", " << previousSibling << " <-> " << nextSibling << ")\n"; return os; } /** * This is the base class for all iterators. * It takes care of correct implementation of all operators and reversion. * * An actual iterator `T<reverse>` only has to * - inherit from `BaseIterator<T, reverse>`, * - provide appropriate constructors, * - implement `next()` and `previous()`. * If the iterator supports only forward iteration, it omits the template * argument, inherits from `BaseIterator<T, false>` and does not implement * `previous()`. */ template<typename T, typename Iterator, bool reverse> struct BaseIterator { template<typename TT, typename It, bool rev> friend struct BaseIterator; protected: const tree<T>* mTree; BaseIterator(const tree<T>* t, std::size_t root): mTree(t), current(root) {} public: const auto& nodes() const { return mTree->nodes; } const auto& node(std::size_t id) const { assert(id != MAXINT); return nodes()[id]; } const auto& curnode() const { return node(current); } std::size_t current; BaseIterator(const BaseIterator& ii) = default; BaseIterator(BaseIterator&& ii) noexcept = default; template<typename It, bool r> BaseIterator(const BaseIterator<T,It,r>& ii): mTree(ii.mTree), current(ii.current) {} BaseIterator& operator=(const BaseIterator& ii) = default; BaseIterator& operator=(BaseIterator&& ii) noexcept = default; std::size_t depth() const { return node(current).depth; } std::size_t id() const { assert(current != MAXINT); return current; } bool isRoot() const { return current == 0; } bool isValid() const { return (mTree != nullptr) && mTree->is_valid(*this); } T* operator->() { return &(curnode().data); } T const * operator->() const { return &(curnode().data); } }; template<typename T, typename I, bool r> T& operator*(BaseIterator<T,I,r>& bi) { return bi.curnode().data; } template<typename T, typename I, bool r> const T& operator*(const BaseIterator<T,I,r>& bi) { return bi.curnode().data; } template<typename T, typename I, bool reverse> typename std::enable_if<!reverse,I>::type& operator++(BaseIterator<T,I,reverse>& it) { return static_cast<I*>(&it)->next(); } template<typename T, typename I, bool reverse> typename std::enable_if<reverse,I>::type& operator++(BaseIterator<T,I,reverse>& it) { return static_cast<I*>(&it)->previous(); } template<typename T, typename I, bool reverse> typename std::enable_if<!reverse,I>::type operator++(BaseIterator<T,I,reverse>& it, int) { return static_cast<I*>(&it)->next(); } template<typename T, typename I, bool reverse> typename std::enable_if<reverse,I>::type operator++(BaseIterator<T,I,reverse>& it, int) { return static_cast<I*>(&it)->previous(); } template<typename T, typename I, bool reverse> typename std::enable_if<!reverse,I>::type& operator--(BaseIterator<T,I,reverse>& it) { return static_cast<I*>(&it)->previous(); } template<typename T, typename I, bool reverse> typename std::enable_if<reverse,I>::type& operator--(BaseIterator<T,I,reverse>& it) { return static_cast<I*>(&it)->next(); } template<typename T, typename I, bool reverse> typename std::enable_if<!reverse,I>::type operator--(BaseIterator<T,I,reverse>& it, int) { return static_cast<I*>(&it)->previous(); } template<typename T, typename I, bool reverse> typename std::enable_if<reverse,I>::type operator--(BaseIterator<T,I,reverse>& it, int) { return static_cast<I*>(&it)->next(); } template<typename T, typename I, bool r> bool operator==(const BaseIterator<T,I,r>& i1, const BaseIterator<T,I,r>& i2) { return i1.current == i2.current; } template<typename T, typename I, bool r> bool operator!=(const BaseIterator<T,I,r>& i1, const BaseIterator<T,I,r>& i2) { return i1.current != i2.current; } template<typename T, typename I, bool r> bool operator<(const BaseIterator<T,I,r>& i1, const BaseIterator<T,I,r>& i2) { return i1.current < i2.current; } /** * Iterator class for pre-order iterations over all elements. */ template<typename T, bool reverse = false> struct PreorderIterator: BaseIterator<T,PreorderIterator<T,reverse>, reverse>, std::iterator<std::bidirectional_iterator_tag, T, std::size_t, T*, T&> { using Base = BaseIterator<T,PreorderIterator<T,reverse>, reverse>; PreorderIterator(const tree<T>* t): Base(t, MAXINT) {} PreorderIterator(const tree<T>* t, std::size_t root): Base(t, root) {} PreorderIterator& next() { if (this->current == MAXINT) { this->current = this->mTree->begin_preorder().current; } else if (this->curnode().firstChild == MAXINT) { while (this->curnode().nextSibling == MAXINT) { this->current = this->curnode().parent; if (this->current == MAXINT) return *this; } this->current = this->curnode().nextSibling; } else { this->current = this->curnode().firstChild; } return *this; } PreorderIterator& previous() { if (this->current == MAXINT) { this->current = this->mTree->rbegin_preorder().current; } else if (this->curnode().previousSibling == MAXINT) { this->current = this->curnode().parent; } else { this->current = this->curnode().previousSibling; while (this->curnode().firstChild != MAXINT) { this->current = this->curnode().lastChild; } } return *this; } template<typename It,bool rev> PreorderIterator(const BaseIterator<T,It,rev>& ii): Base(ii) {} PreorderIterator(const PreorderIterator& ii): Base(ii) {} PreorderIterator(PreorderIterator&& ii): Base(ii) {} PreorderIterator& operator=(const PreorderIterator& it) { Base::operator=(it); return *this; } PreorderIterator& operator=(PreorderIterator&& it) { Base::operator=(it); return *this; } virtual ~PreorderIterator() noexcept = default; PreorderIterator& skipChildren() { assert(this->current != MAXINT); while (this->curnode().nextSibling == MAXINT) { this->current = this->curnode().parent; if (this->current == MAXINT) return *this; } this->current = this->curnode().nextSibling; return *this; } }; static_assert(std::is_copy_constructible<PreorderIterator<int,false>>::value, ""); static_assert(std::is_move_constructible<PreorderIterator<int,false>>::value, ""); static_assert(std::is_destructible<PreorderIterator<int,false>>::value, ""); static_assert(std::is_copy_constructible<PreorderIterator<int,true>>::value, ""); static_assert(std::is_move_constructible<PreorderIterator<int,true>>::value, ""); static_assert(std::is_destructible<PreorderIterator<int,true>>::value, ""); /** * Iterator class for post-order iterations over all elements. */ template<typename T, bool reverse = false> struct PostorderIterator: BaseIterator<T, PostorderIterator<T, reverse>,reverse>, std::iterator<std::bidirectional_iterator_tag, T, std::size_t, T*, T&> { using Base = BaseIterator<T, PostorderIterator<T, reverse>,reverse>; PostorderIterator(const tree<T>* t): Base(t, MAXINT) {} PostorderIterator(const tree<T>* t, std::size_t root): Base(t, root) {} PostorderIterator& next() { if (this->current == MAXINT) { this->current = this->mTree->begin_postorder().current; } else if (this->curnode().nextSibling == MAXINT) { this->current = this->curnode().parent; } else { this->current = this->curnode().nextSibling; while (this->curnode().firstChild != MAXINT) { this->current = this->curnode().firstChild; } } return *this; } PostorderIterator& previous() { if (this->current == MAXINT) { this->current = this->mTree->rbegin_postorder().current; } else if (this->curnode().firstChild == MAXINT) { if (this->curnode().previousSibling != MAXINT) { this->current = this->curnode().previousSibling; } else { while (this->curnode().previousSibling == MAXINT) { this->current = this->curnode().parent; if (this->current == MAXINT) return *this; } this->current = this->curnode().previousSibling; } } else { this->current = this->curnode().lastChild; } return *this; } template<typename It> PostorderIterator(const BaseIterator<T,It,reverse>& ii): Base(ii) {} PostorderIterator(const PostorderIterator& ii): Base(ii) {} PostorderIterator(PostorderIterator&& ii): Base(ii) {} PostorderIterator& operator=(const PostorderIterator& it) { Base::operator=(it); return *this; } PostorderIterator& operator=(PostorderIterator&& it) { Base::operator=(it); return *this; } virtual ~PostorderIterator() noexcept = default; }; static_assert(std::is_copy_constructible<PostorderIterator<int,false>>::value, ""); static_assert(std::is_move_constructible<PostorderIterator<int,false>>::value, ""); static_assert(std::is_destructible<PostorderIterator<int,false>>::value, ""); static_assert(std::is_copy_constructible<PostorderIterator<int,true>>::value, ""); static_assert(std::is_move_constructible<PostorderIterator<int,true>>::value, ""); static_assert(std::is_destructible<PostorderIterator<int,true>>::value, ""); /** * Iterator class for iterations over all leaf elements. */ template<typename T, bool reverse = false> struct LeafIterator: BaseIterator<T,LeafIterator<T,reverse>, reverse>, std::iterator<std::bidirectional_iterator_tag, T, std::size_t, T*, T&> { using Base = BaseIterator<T,LeafIterator<T,reverse>,reverse>; LeafIterator(const tree<T>* t): Base(t, MAXINT) {} LeafIterator(const tree<T>* t, std::size_t root): Base(t, root) {} LeafIterator& next() { if (this->current == MAXINT) { this->current = this->mTree->begin_leaf().current; } else { PreorderIterator<T,false> it(*this); do { ++it; if (it.current == MAXINT) break; } while (this->nodes()[it.current].firstChild != MAXINT); this->current = it.current; } return *this; } LeafIterator& previous() { if (this->current == MAXINT) { this->current = this->mTree->rbegin_leaf().current; } else { PreorderIterator<T,false> it(*this); do { --it; if (it.current == MAXINT) break; } while (this->nodes()[it.current].firstChild != MAXINT); this->current = it.current; } return *this; } template<typename It> LeafIterator(const BaseIterator<T,It,reverse>& ii): Base(ii) {} LeafIterator(const LeafIterator& ii): Base(ii) {} LeafIterator(LeafIterator&& ii): Base(ii) {} LeafIterator& operator=(const LeafIterator& it) { Base::operator=(it); return *this; } LeafIterator& operator=(LeafIterator&& it) { Base::operator=(it); return *this; } virtual ~LeafIterator() noexcept = default; }; static_assert(std::is_copy_constructible<LeafIterator<int,false>>::value, ""); static_assert(std::is_move_constructible<LeafIterator<int,false>>::value, ""); static_assert(std::is_destructible<LeafIterator<int,false>>::value, ""); static_assert(std::is_copy_constructible<LeafIterator<int,true>>::value, ""); static_assert(std::is_move_constructible<LeafIterator<int,true>>::value, ""); static_assert(std::is_destructible<LeafIterator<int,true>>::value, ""); /** * Iterator class for iterations over all elements of a certain depth. */ template<typename T, bool reverse = false> struct DepthIterator: BaseIterator<T,DepthIterator<T,reverse>,reverse>, std::iterator<std::bidirectional_iterator_tag, T, std::size_t, T*, T&> { using Base = BaseIterator<T,DepthIterator<T,reverse>,reverse>; std::size_t depth; DepthIterator(const tree<T>* t): Base(t, MAXINT), depth(0) {} DepthIterator(const tree<T>* t, std::size_t root, std::size_t _depth): Base(t, root), depth(_depth) { assert(!this->nodes().empty()); if (reverse) { PostorderIterator<T,reverse> it(*this); while (it.current != MAXINT && it.depth() != _depth) ++it; this->current = it.current; } else { PreorderIterator<T,reverse> it(*this); while (it.current != MAXINT && it.depth() != _depth) ++it; this->current = it.current; } } DepthIterator& next() { if (this->current == MAXINT) { this->current = this->mTree->begin_depth(depth).current; } else if (this->curnode().nextSibling == MAXINT) { std::size_t target = this->curnode().depth; while (this->curnode().nextSibling == MAXINT) { this->current = this->curnode().parent; if (this->current == MAXINT) return *this; } PreorderIterator<T,reverse> it(this->mTree, this->curnode().nextSibling); for (; it.current != MAXINT; ++it) { if (it.depth() == target) break; } this->current = it.current; } else { this->current = this->curnode().nextSibling; } return *this; } DepthIterator& previous() { if (this->current == MAXINT) { this->current = this->mTree->rbegin_depth(depth).current; } else if (this->curnode().previousSibling == MAXINT) { std::size_t target = this->curnode().depth; while (this->curnode().previousSibling == MAXINT) { this->current = this->curnode().parent; if (this->current == MAXINT) return *this; } PostorderIterator<T,reverse> it(this->mTree, this->curnode().previousSibling); for (; it.current != MAXINT; ++it) { if (it.depth() == target) break; } this->current = it.current; } else { this->current = this->curnode().previousSibling; } return *this; } template<typename It> DepthIterator(const BaseIterator<T,It,reverse>& ii): Base(ii), depth(this->nodes()[ii.current].depth) {} DepthIterator(const DepthIterator& ii): Base(ii), depth(ii.depth) {} DepthIterator(DepthIterator&& ii): Base(ii), depth(ii.depth) {} DepthIterator& operator=(const DepthIterator& it) { Base::operator=(it); depth = it.depth; return *this; } DepthIterator& operator=(DepthIterator&& it) { Base::operator=(it); depth = it.depth; return *this; } virtual ~DepthIterator() noexcept = default; }; static_assert(std::is_copy_constructible<DepthIterator<int,false>>::value, ""); static_assert(std::is_move_constructible<DepthIterator<int,false>>::value, ""); static_assert(std::is_destructible<DepthIterator<int,false>>::value, ""); static_assert(std::is_copy_constructible<DepthIterator<int,true>>::value, ""); static_assert(std::is_move_constructible<DepthIterator<int,true>>::value, ""); static_assert(std::is_destructible<DepthIterator<int,true>>::value, ""); /** * Iterator class for iterations over all children of a given element. */ template<typename T, bool reverse = false> struct ChildrenIterator: BaseIterator<T,ChildrenIterator<T,reverse>,reverse>, std::iterator<std::bidirectional_iterator_tag, T, std::size_t, T*, T&> { using Base = BaseIterator<T,ChildrenIterator<T,reverse>,reverse>; std::size_t parent; ChildrenIterator(const tree<T>* t, std::size_t base, bool end = false): Base(t, base) { parent = base; assert(base != MAXINT); if (end) this->current = MAXINT; else if (this->curnode().firstChild == MAXINT) this->current = MAXINT; else { if (reverse) { this->current = this->curnode().lastChild; } else { this->current = this->curnode().firstChild; } } } ChildrenIterator& next() { if (this->current == MAXINT) { this->current = this->mTree->begin_children(PreorderIterator<T,false>(this->mTree, parent)).current; } else { this->current = this->curnode().nextSibling; } return *this; } ChildrenIterator& previous() { if (this->current == MAXINT) { this->current = this->mTree->rbegin_children(PreorderIterator<T,false>(this->mTree, parent)).current; } else { this->current = this->curnode().previousSibling; } return *this; } template<typename It> ChildrenIterator(const BaseIterator<T,It,reverse>& ii): Base(ii), parent(MAXINT) { if (this->mTree->is_valid(ii)) parent = this->nodes()[ii.current].parent; } ChildrenIterator(const ChildrenIterator& ii): Base(ii), parent(ii.parent) {} ChildrenIterator(ChildrenIterator&& ii): Base(ii), parent(ii.parent) {} ChildrenIterator& operator=(const ChildrenIterator& it) { Base::operator=(it); parent = it.parent; return *this; } ChildrenIterator& operator=(ChildrenIterator&& it) noexcept { Base::operator=(it); parent = it.parent; return *this; } virtual ~ChildrenIterator() noexcept = default; }; static_assert(std::is_copy_constructible<ChildrenIterator<int,false>>::value, ""); static_assert(std::is_move_constructible<ChildrenIterator<int,false>>::value, ""); static_assert(std::is_destructible<ChildrenIterator<int,false>>::value, ""); static_assert(std::is_copy_constructible<ChildrenIterator<int,true>>::value, ""); static_assert(std::is_move_constructible<ChildrenIterator<int,true>>::value, ""); static_assert(std::is_destructible<ChildrenIterator<int,true>>::value, ""); /** * Iterator class for iterations from a given element to the root. */ template<typename T> struct PathIterator: BaseIterator<T, PathIterator<T>,false>, std::iterator<std::forward_iterator_tag, T, std::size_t, T*, T&> { using Base = BaseIterator<T, PathIterator<T>,false>; PathIterator(const tree<T>* t, std::size_t root): Base(t, root) {} PathIterator& next() { if (this->current != MAXINT) { this->current = this->curnode().parent; } return *this; } template<typename It> PathIterator(const BaseIterator<T,It,false>& ii): Base(ii) {} PathIterator(const PathIterator& ii): Base(ii) {} PathIterator(PathIterator&& ii): Base(ii) {} PathIterator& operator=(const PathIterator& it) { Base::operator=(it); return *this; } PathIterator& operator=(PathIterator&& it) noexcept { Base::operator=(it); return *this; } virtual ~PathIterator() noexcept = default; }; static_assert(std::is_copy_constructible<PathIterator<int>>::value, ""); static_assert(std::is_move_constructible<PathIterator<int>>::value, ""); static_assert(std::is_destructible<PathIterator<int>>::value, ""); } /** * This class represents a tree. * * It tries to stick to the STL style as close as possible. */ template<typename T> class tree { public: using value_type = T; using Node = tree_detail::Node<T>; template<bool reverse> using PreorderIterator = tree_detail::PreorderIterator<T,reverse>; template<bool reverse> using PostorderIterator = tree_detail::PostorderIterator<T,reverse>; template<bool reverse> using LeafIterator = tree_detail::LeafIterator<T,reverse>; template<bool reverse> using DepthIterator = tree_detail::DepthIterator<T,reverse>; template<bool reverse> using ChildrenIterator = tree_detail::ChildrenIterator<T,reverse>; using PathIterator = tree_detail::PathIterator<T>; private: template<typename TT, typename Iterator, bool reverse> friend struct tree_detail::BaseIterator; static constexpr std::size_t MAXINT = tree_detail::MAXINT; std::vector<Node> nodes; std::size_t emptyNodes = MAXINT; public: using iterator = PreorderIterator<false>; tree() = default; tree(const tree& t) = default; tree(tree&& t) noexcept = default; tree& operator=(const tree& t) = default; tree& operator=(tree&& t) noexcept = default; void debug() const { std::cout << "emptyNodes: " << emptyNodes << std::endl; std::cout << this->nodes << std::endl; } iterator begin() const { return begin_preorder(); } iterator end() const { return end_preorder(); } iterator rbegin() const { return rbegin_preorder(); } iterator rend() const { return rend_preorder(); } PreorderIterator<false> begin_preorder() const { return PreorderIterator<false>(this, 0); } PreorderIterator<false> end_preorder() const { return PreorderIterator<false>(this); } PreorderIterator<true> rbegin_preorder() const { std::size_t cur = 0; while (nodes[cur].lastChild != MAXINT) cur = nodes[cur].lastChild; return PreorderIterator<true>(this, cur); } PreorderIterator<true> rend_preorder() const { return PreorderIterator<true>(this); } PostorderIterator<false> begin_postorder() const { std::size_t cur = 0; while (nodes[cur].firstChild != MAXINT) cur = nodes[cur].firstChild; return PostorderIterator<false>(this, cur); } PostorderIterator<false> end_postorder() const { return PostorderIterator<false>(this); } PostorderIterator<true> rbegin_postorder() const { return PostorderIterator<true>(this, 0); } PostorderIterator<true> rend_postorder() const { return PostorderIterator<true>(this); } LeafIterator<false> begin_leaf() const { std::size_t cur = 0; while (nodes[cur].firstChild != MAXINT) cur = nodes[cur].firstChild; return LeafIterator<false>(this, cur); } LeafIterator<false> end_leaf() const { return LeafIterator<false>(this); } LeafIterator<true> rbegin_leaf() const { std::size_t cur = 0; while (nodes[cur].lastChild != MAXINT) cur = nodes[cur].lastChild; return LeafIterator<true>(this, cur); } LeafIterator<true> rend_leaf() const { return LeafIterator<true>(this); } DepthIterator<false> begin_depth(std::size_t depth) const { return DepthIterator<false>(this, 0, depth); } DepthIterator<false> end_depth() const { return DepthIterator<false>(this); } DepthIterator<true> rbegin_depth(std::size_t depth) const { return DepthIterator<true>(this, 0, depth); } DepthIterator<true> rend_depth() const { return DepthIterator<true>(this); } template<typename Iterator> ChildrenIterator<false> begin_children(const Iterator& it) const { return ChildrenIterator<false>(this, it.current, false); } template<typename Iterator> ChildrenIterator<false> end_children(const Iterator& it) const { return ChildrenIterator<false>(this, it.current, true); } template<typename Iterator> ChildrenIterator<true> rbegin_children(const Iterator& it) const { return ChildrenIterator<true>(this, it.current, false); } template<typename Iterator> ChildrenIterator<true> rend_children(const Iterator& it) const { return ChildrenIterator<true>(this, it.current, true); } template<typename Iterator> PathIterator begin_path(const Iterator& it) const { return PathIterator(this, it.current); } PathIterator end_path() const { return PathIterator(this, MAXINT); } /** * Retrieves the maximum depth of all elements. * @return Maximum depth. */ std::size_t max_depth() const { std::size_t max = 0; for (auto it = begin_leaf(); it != end_leaf(); ++it) { if (it.depth() > max) max = it.depth(); } return max; } template<typename Iterator> std::size_t max_depth(const Iterator& it) const { std::size_t max = 0; for (auto i = begin_children(it); i != end_children(it); ++i) { std::size_t d = max_depth(i); if (d + 1 > max) max = d + 1; } return max; } /** * Check if the given element is a leaf. * @param it Iterator. * @return If `it` is a leaf. */ template<typename Iterator> bool is_leaf(const Iterator& it) const { return nodes[it.current].firstChild == MAXINT; } /** * Check if the given element is a leftmost child. * @param it Iterator. * @return If `it` is a leftmost child. */ template<typename Iterator> bool is_leftmost(const Iterator& it) const { return nodes[it.current].previousSibling == MAXINT; } /** * Check if the given element is a rightmost child. * @param it Iterator. * @return If `it` is a rightmost child. */ template<typename Iterator> bool is_rightmost(const Iterator& it) const { return nodes[it.current].nextSibling == MAXINT; } template<typename Iterator> bool is_valid(const Iterator& it) const { if (it.current >= nodes.size()) return false; return nodes[it.current].depth < MAXINT; } /** * Retrieves the parent of an element. * @param it Iterator. * @return Parent of `it`. */ template<typename Iterator> Iterator get_parent(const Iterator& it) const { return Iterator(this, nodes[it.current].parent); } template<typename Iterator> Iterator left_sibling(const Iterator& it) const { assert(!is_leftmost(it)); auto res = it; res.current = nodes[it.current].previousSibling; return res; } /** * Sets the value of the root element. * @param data Data. * @return Iterator to the root. */ iterator setRoot(const T& data) { return setRoot(T(data)); } iterator setRoot(T&& data) { if (nodes.empty()) nodes.emplace_back(0, std::move(data), MAXINT, 0); else nodes[0].data = data; return iterator(this, 0); } /** * Clears the tree. */ void clear() { nodes.clear(); emptyNodes = MAXINT; } /** * Add the given data as last child of the root element. * @param data Data. * @return Iterator to inserted element. */ iterator append(const T& data) { if (nodes.empty()) setRoot(T()); return append(iterator(this, 0), data); } /** * Add the given data as last child of the given element. * @param parent Parent element. * @param data Data. * @return Iterator to inserted element. */ template<typename Iterator> Iterator append(Iterator parent, const T& data) { std::size_t id = createNode(data, parent.current, nodes[parent.current].depth + 1); assert(is_consistent()); return Iterator(this, id); } /** * Insert element before the given position. * @param position Position to insert before. * @param data Element to insert. * @return PreorderIterator to inserted element. */ template<typename Iterator> Iterator insert(Iterator position, const T& data) { std::size_t parent = nodes[position.current].parent; std::size_t newID = newNode(T(data), parent, nodes[position.current].depth); std::size_t prev = nodes[position.current].previousSibling; std::size_t next = position.current; nodes[newID].previousSibling = prev; nodes[newID].nextSibling = next; if (next != MAXINT) { nodes[next].previousSibling = newID; } else { nodes[parent].lastChild = newID; } if (prev != MAXINT) { nodes[prev].nextSibling = newID; } else { nodes[parent].firstChild = newID; } assert(is_consistent()); return PreorderIterator<false>(this, newID); } /** * Append another tree as last child of the root element. * @param tree Tree. * @return Iterator to root of inserted subtree. */ iterator append(tree&& tree) { if (nodes.empty()) std::swap(nodes, tree.nodes); return append(iterator(0), std::move(tree)); } /** * Append another tree as last child of the given element. * @param position Element. * @param tree Tree. * @return Iterator to root of inserted subtree. */ template<typename Iterator> Iterator append(Iterator position, tree&& data) { Node* r = data.root; r->depth = position.depth() + 1; data.root = nullptr; r->parent = position.current; std::size_t id = position.current->children.size(); if (id > 0) r->previousSibling = &(position.current->children.back()); position.current->children.push_back(*r); if (id > 0) r->previousSibling->nextSibling = &(position.current->children.back()); assert(is_consistent()); return Iterator(&(position.current->children.back())); } template<typename Iterator> const Iterator& replace(const Iterator& position, const T& data) { nodes[position.current].data = data; return position; } /** * Erase the element at the given position. * Returns an iterator to the next position. * @param position Element. * @return Next element. */ template<typename Iterator> Iterator erase(Iterator position) { assert(this->is_consistent()); std::size_t id = position.current; if (id == 0) { clear(); ++position; return position; } ++position; if (nodes[id].nextSibling != MAXINT) { nodes[nodes[id].nextSibling].previousSibling = nodes[id].previousSibling; } else { nodes[nodes[id].parent].lastChild = nodes[id].previousSibling; } if (nodes[id].previousSibling != MAXINT) { nodes[nodes[id].previousSibling].nextSibling = nodes[id].nextSibling; } else { nodes[nodes[id].parent].firstChild = nodes[id].nextSibling; } eraseNode(id); assert(this->is_consistent()); return position; } /** * Erase all children of the given element. * @param position Element. */ template<typename Iterator> void eraseChildren(const Iterator& position) { eraseChildren(position.current); } private: std::size_t newNode(T&& data, std::size_t parent, std::size_t depth) { std::size_t newID = 0; if (emptyNodes == MAXINT) { nodes.emplace_back(nodes.size(), std::move(data), parent, depth); newID = nodes.size() - 1; } else { newID = emptyNodes; emptyNodes = nodes[emptyNodes].nextSibling; nodes[newID].data = data; nodes[newID].parent = parent; nodes[newID].depth = depth; } return newID; } std::size_t createNode(const T& data, std::size_t parent, std::size_t depth) { std::size_t res = newNode(T(data), parent, depth); nodes[res].nextSibling = MAXINT; if (parent != MAXINT) { if (nodes[parent].lastChild != MAXINT) { nodes[nodes[parent].lastChild].nextSibling = res; nodes[res].previousSibling = nodes[parent].lastChild; nodes[parent].lastChild = res; } else { nodes[parent].firstChild = res; nodes[parent].lastChild = res; } } return res; } void eraseChildren(std::size_t id) { if (nodes[id].firstChild == MAXINT) return; std::size_t cur = nodes[id].firstChild; while (cur != MAXINT) { std::size_t tmp = cur; cur = nodes[cur].nextSibling; eraseNode(tmp); } nodes[id].firstChild = MAXINT; nodes[id].lastChild = MAXINT; } void eraseNode(std::size_t id) { eraseChildren(id); nodes[id].nextSibling = emptyNodes; nodes[id].previousSibling = MAXINT; nodes[id].depth = MAXINT; emptyNodes = id; } public: bool is_consistent() const { for (auto it = this->begin(); it != this->end(); ++it) { assert(is_consistent(it.current)); } return true; } bool is_consistent(std::size_t node) const { assert(node != MAXINT); assert(node < nodes.size()); if (nodes[node].firstChild != MAXINT) { std::size_t child = nodes[node].firstChild; while (nodes[child].nextSibling != MAXINT) { assert(nodes[child].parent == node); assert(nodes[nodes[child].nextSibling].previousSibling == child); child = nodes[child].nextSibling; } assert(child == nodes[node].lastChild); child = nodes[node].lastChild; while (nodes[child].previousSibling != MAXINT) { assert(nodes[child].parent == node); assert(nodes[nodes[child].previousSibling].nextSibling == child); child = nodes[child].previousSibling; } assert(child == nodes[node].firstChild); } return true; } }; template<typename TT> std::ostream& operator<<(std::ostream& os, const tree<TT>& tree) { for (auto it = tree.begin_preorder(); it != tree.end_preorder(); ++it) { os << std::string(it.depth(), '\t') << *it << std::endl; } return os; } template<typename T> const std::size_t tree<T>::MAXINT; }
true
41ac1d1282edda14a86684a9e424dac70fa765d0
C++
ablondal/comp-prog
/Practice/Club_Prac_3/a.cpp
UTF-8
394
2.578125
3
[]
no_license
#include <vector> #include <queue> #include <iostream> #include <utility> #include <algorithm> using namespace std; #define max(a,b) ((a>b)?a:b) #define min(a,b) ((a<b)?a:b) #define inf 1e9 typedef pair <int, int> pt; typedef long long ll; int main(){ string s; cin >> s; string S; for(auto ss: s){ if (ss >= 'A' && ss <= 'Z'){ S = S + ss; } } cout << S << endl; }
true
9b02db6925550350f0f4f9d7c18da5fd52267520
C++
beyzaerdogaan/huffman-algorithm
/BinaryTree.h
UTF-8
904
2.6875
3
[]
no_license
// // Created by Beyza on 23.12.2020. // #ifndef ASSIGNMENT_4_LAST_BINARYTREE_H #define ASSIGNMENT_4_LAST_BINARYTREE_H #include <string> #include <iostream> #include <unordered_map> #include <map> #include <vector> #include <fstream> class BinaryTree { private: struct TreeNode { char item; TreeNode* left; TreeNode* right; int frequency; }; TreeNode* root; public: BinaryTree(); BinaryTree(char value); ~BinaryTree(); std::map<std::string, std::string> encodingMap; // mapten unordered mape cevrildi char getRootItem(); TreeNode* getRoot(); void setFrequency(int frequency); void insertLeftNode(BinaryTree* binaryTree); void insertRightNode(BinaryTree* binaryTree); void encodeChars(const std::string& code, TreeNode* treeNode); }; #endif //ASSIGNMENT_4_LAST_BINARYTREE_H
true
bb6da6f8bcb9231baed87cd2256fdc0fd85654e7
C++
Curpiq/ood_labs
/lab1/CRectangle.h
UTF-8
468
3.171875
3
[]
no_license
#pragma once #include "IShape.h" class CRectange : public IShape { private: RectangleShape m_rectangle; public: CRectange(RectangleShape&& rectangle) : m_rectangle(std::move(rectangle)) { } double GetPerimeter()const override { return (static_cast<double>(m_rectangle.getSize().x) + m_rectangle.getSize().y) * 2; } double GetArea()const override { return (static_cast<double>(m_rectangle.getSize().x) * m_rectangle.getSize().y); } };
true