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
80a3438c0fd77ed4ddbff8030ba7f4ff554e7450
C++
yuktajuneja/Data-Structure-Coding-ninjas
/Graphs/Get_DFS.cpp
UTF-8
1,086
3.03125
3
[]
no_license
#include<iostream> #include<vector> using namespace std; bool GetPathDFS(int** edges,int n,int a,int b,bool* visited,vector<int> &v){ if(a==b){ v.push_back(a); visited[a]=true; return true; } visited[a]=true; for(int i=0;i<n;i++){ if(i==a){ continue; } if(edges[a][i]==1&&!visited[i]){ bool find=GetPathDFS(edges,n,i,b,visited,v); if(find){ v.push_back(a); return true; } } } return false; } int main(int argc, char const *argv[]) { int n,e; cin>>n>>e; int** edges=new int*[n]; for(int i=0;i<n;i++){ edges[i]=new int [n]; for(int j=0;j<n;j++){ edges[i][j]=0; } } for(int i=0;i<e;i++){ int f,s; cin>>f>>s; edges[s][f]=1; edges[f][s]=1; } bool* visited=new bool[n]; for(int i=0;i<n;i++){ visited[i]=false; } int a,b; cin>>a>>b; vector<int> v; if(GetPathDFS(edges,n,a,b,visited,v)){ for(auto it: v){ cout<<it<<" "; } } delete []visited; for(int i=0;i<n;i++){ delete [] edges[i]; } delete [] edges; return 0; }
true
bead2c59e43f4f6a416e8c63aafe8adce9b85b0b
C++
ssynn/PAT_advanced
/1070. Mooncake.cpp
UTF-8
818
2.859375
3
[]
no_license
#include"stdafx.h" #include<iostream> #include<vector> #include<string> #include<iomanip> #include<algorithm> using namespace std; struct good { double stock; double total; double price; }; bool cmp(good &a,good &b) { return a.price > b.price; } int main() { int n, sum, k = 0, haha = 0, yu = 0, yu2 = 0, yu1 = 0; double profit = 0; good temp; cin >> n >> sum; vector<good>a(n); for (int i = 0; i < n; i++)//input stock cin >> a[i].stock; for (int i = 0; i < n; i++)//input total { cin >> a[i].total; a[i].price = a[i].total / a[i].stock; } sort(a.begin(), a.end(), cmp); while (sum > a[k].stock&&k<n) { sum = sum - a[k].stock; profit = profit + a[k].total; k++; } if (k<n) profit = profit + (sum)*a[k].price; cout << fixed << setprecision(2) << profit; system("pause"); return 0; }
true
ce4eb6c3957fe38d72d25e6fa76362e28d188469
C++
keewon/winter-source-beta-3
/card.cpp
UTF-8
2,651
2.984375
3
[]
no_license
#include "card.h" #include "random.h" #include <fstream> Card::Card(int no) { set(no); } Card:: Card() { num=0; atr=0; mon=0; rmn=4; } void Card::set(int no) { if(no >0 && no <= 50) { num=no; mon=(num-1)/4+1; //고유 번호로 달을 정한다. rmn=num%4; // atr //NULL:0 광:1 비광:2 //열(일반):3 열(쌍피):4 열(고도리):5 //홍단:6 청단:7 구사:8 //쌍피:9 피:10 //비구사:11 if(mon==13) { rmn=4; //rmn은 조커에서는 필요없음. atr=9; //조커의 속성은 쌍피 } switch(rmn) { case 1: if(mon==1 || mon==3 || mon==8 || mon==11) atr=1; if(mon==12) atr=2; if(mon==7 || mon==10) atr=3; // mon==9일 때에만 그림쌍피인 것이 맞는 것 아닌가? //if(mon==5 || mon==6 || mon==9) // atr=4; if (mon==5 || mon==6) atr=3; if (mon==9) atr=4; if(mon==2 || mon==4) atr=5; break; case 2: if(mon==12) atr=3; if(mon==8) atr=5; if(mon==1 || mon==2 || mon==3) atr=6; if(mon==6 || mon==9 || mon==10) atr=7; if(mon==4 || mon==5 || mon==7) atr=8; if(mon==11) atr=9; break; case 3: if(mon==12) atr=8;//atr=11; //비초단 else atr=10; break; case 0: if(mon==12) atr=9; else atr=10; break; } //고유번호에 의한 패의 특성 } else if (no == 51) { // 얼음패 선언 num=51; mon=-1; rmn=4; atr=-1; } else { // NULL Card 선언, // 1에서 51을 벗어나는 숫자를 입력한 경우는 모두 NULL num=0; mon=-1; rmn=4; atr=-1; } } Cardset::Cardset() { int i; randomize(); for(i=1;i<=50;i++) Hwatoo[i]=1; // 모든 카드의 존재여부가 1 nSet=50; //카드의 수 50 } Cardpair::Cardpair() { } Cardpair::Cardpair(int Card1, int Card2) { Pair[0].set(Card1); Pair[1].set(Card2); row[0]=8;row[1]=9;col[0]=2;col[1]=2; } Cardpair Cardset::decard() { // std::ofstream ofs("log.txt", std::ios::app); if(nSet<2) return Cardpair(0,0); int selected[2]; selected[0] = -1; selected[1] = -1; for (int j=0; j<2; j++) { int start=random(nSet)+1; for (int i=1; i<=50; i++) { if (Hwatoo[i] == 1) { start--; } if (start == 0) { selected[j] = i; break; } } Hwatoo[selected[j]] = 0; nSet-=1; } return Cardpair(selected[0], selected[1]); } void Cardset::incard(int inc) { if (inc >= 1 && inc <= 50) { if (Hwatoo[inc] != 1) { Hwatoo[inc]=1; nSet++; } } } int Cardset::number() { return nSet; }
true
22bc0e9436dc883eb5925c62dee649bb6c5127f6
C++
denocris/Object-Oriented-Programming
/D2/Vect2D_class/vect2D.hh
UTF-8
930
3.046875
3
[]
no_license
#include <iostream> #include <cmath> class Vec_2D{ private: double x_; double y_; double r_; double phi_; public: Vec_2D(); Vec_2D(double x1, double y1 ); double length() const; double r() const {return r_;}; double phi() const {return phi_;}; int x() const {return x_; }; int y() const {return y_; }; Vec_2D & operator+=(const Vec_2D &); Vec_2D & operator*=(const double); }; struct DataLine{ Vec_2D a; Vec_2D b; }; Vec_2D operator+(const Vec_2D & a, const Vec_2D & b); Vec_2D operator-(const Vec_2D & a, const Vec_2D & b); Vec_2D operator*(double c, const Vec_2D & a); Vec_2D operator/(double c, const Vec_2D & a); std::istream & operator>>(std::istream & is, Vec_2D & v); std::ostream & operator<<(std::ostream & os, const Vec_2D & v); double operator*(const Vec_2D & a, const Vec_2D & b); double length(const Vec_2D & a); double distance(const Vec_2D & a, const Vec_2D & b);
true
6585ab68a04c26c53031375dbf65c916e2b6fcc5
C++
MultivacX/leetcode2020
/algorithms/medium/0640. Solve the Equation.h
UTF-8
1,629
3.390625
3
[ "MIT" ]
permissive
// 640. Solve the Equation // Runtime: 0 ms, faster than 100.00% of C++ online submissions for Solve the Equation. // Memory Usage: 6.1 MB, less than 100.00% of C++ online submissions for Solve the Equation. class Solution { public: string solveEquation(string equation) { const int N = equation.length(); int n = 0; int x = 0; int i = 0; while (i < N && equation[i] != '=') { bool positive = true; if (equation[i] == '+') ++i; else if (equation[i] == '-') positive = false, ++i; int v = 0; if (equation[i] == 'x') v = 1; else while (i < N && isdigit(equation[i])) v = v * 10 + (equation[i++] - '0'); if (!positive) v *= -1; if (i < N && equation[i] == 'x') x += v, ++i; else n += v; // printf("%d, x * %d + %d\n", v, x, n); } ++i; while (i < N) { bool positive = false; if (equation[i] == '+') ++i; else if (equation[i] == '-') positive = true, ++i; int v = 0; if (equation[i] == 'x') v = 1; else while (i < N && isdigit(equation[i])) v = v * 10 + (equation[i++] - '0'); if (!positive) v *= -1; if (i < N && equation[i] == 'x') x += v, ++i; else n += v; // printf("x * %d + %d\n", x, n); } if (x == 0) return n == 0 ? "Infinite solutions" : "No solution"; return "x=" + to_string(-n / x); } };
true
81302b7f3b0c1b259c408151242555a0fb32c5f5
C++
naturalatlas/node-gdal
/src/gdal_point.cpp
UTF-8
4,772
2.65625
3
[ "Apache-2.0" ]
permissive
#include "gdal_common.hpp" #include "gdal_geometry.hpp" #include "gdal_point.hpp" #include <stdlib.h> namespace node_gdal { Nan::Persistent<FunctionTemplate> Point::constructor; void Point::Initialize(Local<Object> target) { Nan::HandleScope scope; Local<FunctionTemplate> lcons = Nan::New<FunctionTemplate>(Point::New); lcons->Inherit(Nan::New(Geometry::constructor)); lcons->InstanceTemplate()->SetInternalFieldCount(1); lcons->SetClassName(Nan::New("Point").ToLocalChecked()); Nan::SetPrototypeMethod(lcons, "toString", toString); // properties ATTR(lcons, "x", xGetter, xSetter); ATTR(lcons, "y", yGetter, ySetter); ATTR(lcons, "z", zGetter, zSetter); Nan::Set(target, Nan::New("Point").ToLocalChecked(), Nan::GetFunction(lcons).ToLocalChecked()); constructor.Reset(lcons); } Point::Point(OGRPoint *geom) : Nan::ObjectWrap(), this_(geom), owned_(true), size_(0) { LOG("Created Point [%p]", geom); } Point::Point() : Nan::ObjectWrap(), this_(NULL), owned_(true), size_(0) { } Point::~Point() { if(this_) { LOG("Disposing Point [%p] (%s)", this_, owned_ ? "owned" : "unowned"); if (owned_) { OGRGeometryFactory::destroyGeometry(this_); Nan::AdjustExternalMemory(-size_); } LOG("Disposed Point [%p]", this_); this_ = NULL; } } /** * Point class. * * @constructor * @class gdal.Point * @extends gdal.Geometry * @param {Number} x * @param {Number} y * @param {Number} [z] */ NAN_METHOD(Point::New) { Nan::HandleScope scope; Point *f; OGRPoint *geom; double x = 0, y = 0, z = 0; if (!info.IsConstructCall()) { Nan::ThrowError("Cannot call constructor as function, you need to use 'new' keyword"); return; } if (info[0]->IsExternal()) { Local<External> ext = info[0].As<External>(); void* ptr = ext->Value(); f = static_cast<Point *>(ptr); } else { NODE_ARG_DOUBLE_OPT(0, "x", x); NODE_ARG_DOUBLE_OPT(1, "y", y); NODE_ARG_DOUBLE_OPT(2, "z", z); if (info.Length() == 1) { Nan::ThrowError("Point constructor must be given 0, 2, or 3 arguments"); return; } if (info.Length() == 3) { geom = new OGRPoint(x, y, z); } else { geom = new OGRPoint(x, y); } f = new Point(geom); } f->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } Local<Value> Point::New(OGRPoint *geom) { Nan::EscapableHandleScope scope; return scope.Escape(Point::New(geom, true)); } Local<Value> Point::New(OGRPoint *geom, bool owned) { Nan::EscapableHandleScope scope; if (!geom) { return scope.Escape(Nan::Null()); } //make a copy of geometry owned by a feature // + no need to track when a feature is destroyed // + no need to throw errors when a method trys to modify an owned read-only geometry // - is slower if (!owned) { geom = static_cast<OGRPoint*>(geom->clone()); } Point *wrapped = new Point(geom); wrapped->owned_ = true; UPDATE_AMOUNT_OF_GEOMETRY_MEMORY(wrapped); Local<Value> ext = Nan::New<External>(wrapped); Local<Object> obj = Nan::NewInstance(Nan::GetFunction(Nan::New(Point::constructor)).ToLocalChecked(), 1, &ext).ToLocalChecked(); return scope.Escape(obj); } NAN_METHOD(Point::toString) { Nan::HandleScope scope; info.GetReturnValue().Set(Nan::New("Point").ToLocalChecked()); } /** * @attribute x * @type Number */ NAN_GETTER(Point::xGetter) { Nan::HandleScope scope; Point *geom = Nan::ObjectWrap::Unwrap<Point>(info.This()); info.GetReturnValue().Set(Nan::New<Number>((geom->this_)->getX())); } NAN_SETTER(Point::xSetter) { Nan::HandleScope scope; Point *geom = Nan::ObjectWrap::Unwrap<Point>(info.This()); if (!value->IsNumber()) { Nan::ThrowError("y must be a number"); return; } double x = Nan::To<double>(value).ToChecked(); ((OGRPoint* )geom->this_)->setX(x); } /** * @attribute y * @type Number */ NAN_GETTER(Point::yGetter) { Nan::HandleScope scope; Point *geom = Nan::ObjectWrap::Unwrap<Point>(info.This()); info.GetReturnValue().Set(Nan::New<Number>((geom->this_)->getY())); } NAN_SETTER(Point::ySetter) { Nan::HandleScope scope; Point *geom = Nan::ObjectWrap::Unwrap<Point>(info.This()); if (!value->IsNumber()) { Nan::ThrowError("y must be a number"); return; } double y = Nan::To<double>(value).ToChecked(); ((OGRPoint* )geom->this_)->setY(y); } /** * @attribute z * @type Number */ NAN_GETTER(Point::zGetter) { Nan::HandleScope scope; Point *geom = Nan::ObjectWrap::Unwrap<Point>(info.This()); info.GetReturnValue().Set(Nan::New<Number>((geom->this_)->getZ())); } NAN_SETTER(Point::zSetter) { Point *geom = Nan::ObjectWrap::Unwrap<Point>(info.This()); if (!value->IsNumber()) { Nan::ThrowError("z must be a number"); return; } double z = Nan::To<double>(value).ToChecked(); ((OGRPoint* )geom->this_)->setZ(z); } } // namespace node_gdal
true
1306c8808bbd697c4146479b48d5d010fb1aa88a
C++
Redleaf23477/ojcodes
/codejam/2008-1A-C.cpp
UTF-8
1,300
2.671875
3
[]
no_license
// #include <bits/stdc++.h> #define endl '\n' #define int ll using namespace std; typedef long long ll; typedef vector<vector<ll>> Mat; ll n; void init(); void process(); int32_t main() { ios::sync_with_stdio(false); cin.tie(0); int T, caseN = 0; cin >> T; while(T--) { cout << "Case #" << ++caseN << ": "; init(); process(); } cout.flush(); return 0; } void init() { cin >> n; } Mat mul(Mat lhs, Mat rhs) { Mat res(lhs.size()); for(auto &x : res) x.resize(rhs[0].size(), 0); for(int i = 0; i < res.size(); i++) for(int j = 0; j < res[i].size(); j++) for(int k = 0; k < rhs.size(); k++) res[i][j] = (res[i][j] + lhs[i][k] * rhs[k][j])%1000; return res; } Mat fpw(Mat m, ll p) { if(p == 0) { Mat res = m; for(auto &x : res) for(auto &y : x) y = 0; for(size_t i = 0; i < res.size(); i++) res[i][i] = 1; return res; } else { if(p%2 == 1) return mul(m, fpw(mul(m, m), p>>1)); else return fpw(mul(m, m), p>>1); } } void process() { Mat a = {{3, 5}, {1, 3}}; a = fpw(a, n-1); Mat x = {{3}, {1}}; Mat b = mul(a, x); cout << setw(3) << setfill('0') << (b[0][0]*2+999)%1000 << endl; }
true
5432c997c4d1387efdea5043631689133431d41e
C++
winlp4ever/cpp_exs
/codejam/roundingerr/main.cpp
UTF-8
2,150
3.140625
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> #include <math.h> typedef std::pair<int, double> p; class Solution { public: int largest_possible(const int &N, const int &L, const std::vector<int> &vec) const{ std::vector<p> residuals; double coef = 100.0 / N; double rd = coef - (int) coef; int U = 0; for (int i = 0; i < L; i++) { double res = vec[i] * coef; residuals.push_back(p(i, res - (int) res)); U += (rd >= 0.5)? (int) std::ceil(res): (int) res; } sort(residuals.begin(), residuals.end(), [] (const p &a, const p &b) { return a.second >= b.second; }); int s = N; // sum of vec std::for_each(vec.begin(), vec.end(), [&] (int n) { s -= n; }); if (100 % N == 0) { // check if coef - (int) coef == 0. return 100; } if (coef - (int) coef >= 0.5) { U += s * std::ceil(coef); return U; } for (auto& x: residuals) { if (x.second < 0.5) { double r = (0.5 - x.second) / rd; int need_p = (int) std::ceil(r); if (s >= need_p) { s -= need_p; U += 1 + need_p * (int) coef; } else break; } } if (s > 0) { double rd = coef - (int) coef; int times = (int) std::ceil(0.5 / rd); int t = s / times; U += t * times + s * (int) coef; } return U; } }; int main(int argc, char** argv) { int T; Solution sol; std::cin >> T; std::cin.ignore(); for (int i = 1; i <= T; ++i) { int N, L; std::cin >> N >> L; std::cin.ignore(); std::vector<int> v; for (int j = 0; j < L; j++) { int c; std::cin >> c; v.push_back(c); } int result = sol.largest_possible(N, L, v); std::cout << "Case #" << i << ": " << result << std::endl; } return 0; }
true
69ffc2f373b9b3a63d9e43c221cdfc15eb51b092
C++
madhav-bits/Coding_Practice
/leetDiagTraverseII.cpp
UTF-8
3,646
3.484375
3
[]
no_license
/* * //******************************************************1424. Diagonal Traverse II.*********************************************** https://leetcode.com/problems/diagonal-traverse-ii/description/ Given a list of lists of integers, nums, return all elements of nums in diagonal order as shown in the below images. Example 1: Input: nums = [[1,2,3],[4,5,6],[7,8,9]] Output: [1,4,2,7,5,3,8,6,9] Example 2: Input: nums = [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]] Output: [1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16] Example 3: Input: nums = [[1,2,3],[4],[5,6,7],[8],[9,10,11]] Output: [1,4,2,5,3,8,6,9,7,10,11] Example 4: Input: nums = [[1,2,3,4,5,6]] Output: [1,2,3,4,5,6] Constraints: 1 <= nums.length <= 10^5 1 <= nums[i].length <= 10^5 1 <= nums[i][j] <= 10^9 There at most 10^5 elements in nums. ***************************************************************TEST CASES:******************************************************** //These are the examples I had tweaked and worked on. [[1,2,3],[4,5,6],[7,8,9]] [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]] [[1,2,3,4,5,6]] [[1,2,3],[4],[5,6,7],[8],[9,10,11]] // Time Complexity: O(n*m). // n- rows, m-avg. col size in matrix. // Space Complexity: O(n*m). //********************************************************THIS IS LEET ACCEPTED CODE.*************************************************** */ //************************************************************Solution 1:************************************************************ //*****************************************************THIS IS LEET ACCEPTED CODE.*********************************************** // Time Complexity: O(n*m). // n- rows, m-avg. col size in matrix. // Space Complexity: O(n*m). // This algorithm is observation based. Here, as the #cols in each row differs, most of the cols are of smaller lengths when compared // to other cols making it Sparse Matrix. So, instead of iteating over diagonals and pushing the values to result array, we iter. over // matrix and temp. push into dp array, we utilize an observation that all the indices belonging to same diagonal have their row+col // to be same value, so we use this total as index in dp array and push the values into dp array. Now, we iter. over dp array and push // the values the values diagonal wise into the final result array. class Solution { public: vector<int> findDiagonalOrder(vector<vector<int>>& v) { vector<int>res; // Final result array. if(v.size()==0) return res; // Base Case. int maxCol=0; for(int i=0;i<v.size();i++){ // Calc. maxCol size, useful in deciding dp array size. maxCol=max(maxCol, (int)v[i].size()); } // for(int a=0;a<v.size()+maxCol-1;a++){ // int x=min((int)v.size()-1, a), y=(a-x); // while(x>=0 && y<maxCol){ // if(y<v[x].size()) res.push_back(v[x][y]); // x--;y++; // } // } // return res; vector<vector<int>>dp((int)v.size()+maxCol-1); // Init. DP array. for(int i=v.size()-1;i>=0;i--){ // Iter. matrix and pushing into DP array. for(int j=0;j<v[i].size();j++) dp[i+j].push_back(v[i][j]); } for(int i=0;i<dp.size();i++){ // Iter. over DP array. for(int j=0;j<dp[i].size();j++) // Pushing vals from each DP row into result array. res.push_back(dp[i][j]); } return res; // Returning the result array. } };
true
c6c5c747c517a67a81ae47907e45ee8b6dbe1ff8
C++
matthewlouis/OneHorseTown
/OdinEngine/includes/Odin/PhysicalComponent.hpp
UTF-8
4,911
2.78125
3
[]
no_license
#pragma once #include <Box2D/Box2D.h> #include "Math.hpp" namespace odin { inline b2Vec2 getShapePosition( const b2Shape* shape ) { if ( shape->m_type == b2Shape::e_circle ) { return static_cast< const b2CircleShape* >( shape )->m_p; } else if ( shape->m_type == b2Shape::e_polygon ) { return static_cast< const b2PolygonShape* >( shape )->m_centroid; } return b2Vec2_zero; } inline b2Vec2 getFixturePosition( const b2Fixture* fixture ) { return getShapePosition( fixture->GetShape() ); } inline b2Vec2 getFixtureWorldPosition( const b2Fixture* fixture ) { return fixture->GetBody()->GetPosition() + getShapePosition( fixture->GetShape() ); } struct PhysicalComponent { b2Body* pBody = nullptr; static constexpr float DEFAULT_FRICTION = 0.2f; PhysicalComponent() = default; PhysicalComponent( b2Body* body ) : pBody( body ) { } PhysicalComponent( PhysicalComponent&& move ) : pBody( move.pBody ) { move.pBody = nullptr; } ~PhysicalComponent() { if ( pBody != nullptr ) pBody->GetWorld()->DestroyBody( pBody ); } PhysicalComponent& operator =( PhysicalComponent&& move ) { std::swap( pBody, move.pBody ); return *this; } Vec2 position() const { return pBody->GetPosition(); } float rotation() const { return pBody->GetAngle(); } b2Body* operator ->() const { return pBody; } static PhysicalComponent makeRect( float width, float height, b2World& world, b2BodyDef bodyDef = {}, float density = 1, uint16 type = 1, uint16 collidesWith = 0x0000) { b2PolygonShape boxShape; boxShape.SetAsBox( width / 2, height / 2 ); b2FixtureDef fxtDef; fxtDef.shape = &boxShape; fxtDef.friction = DEFAULT_FRICTION; fxtDef.density = density; // Collision detection fxtDef.filter.categoryBits = type; fxtDef.filter.maskBits = collidesWith; b2Body* pBody = world.CreateBody( &bodyDef ); pBody->CreateFixture( &fxtDef ); return PhysicalComponent( pBody ); } static PhysicalComponent makeCircle( float radius, b2World& world, b2BodyDef bodyDef = {}, float density = 1, uint16 type = 1, uint16 collidesWith = 0xFFFF) { b2CircleShape circleShape; circleShape.m_radius = radius; b2FixtureDef fxtDef; fxtDef.shape = &circleShape; fxtDef.friction = DEFAULT_FRICTION; fxtDef.density = density; fxtDef.filter.categoryBits = type; fxtDef.filter.maskBits = collidesWith; b2Body* pBody = world.CreateBody( &bodyDef ); pBody->CreateFixture( &fxtDef ); return PhysicalComponent( pBody ); } static PhysicalComponent makeRightTri( float width, float height, b2World& world, b2BodyDef bodyDef = {}, float density = 1 ) { b2Vec2 vertices[] = { { -width / 2, -height / 2 }, { -width / 2, +height / 2 }, { +width / 2, -height / 2 }, }; b2PolygonShape triShape; triShape.Set( vertices, 3 ); b2FixtureDef fxtDef; fxtDef.shape = &triShape; fxtDef.friction = DEFAULT_FRICTION; fxtDef.density = density; b2Body* pBody = world.CreateBody( &bodyDef ); pBody->CreateFixture( &fxtDef ); return PhysicalComponent( pBody ); } static PhysicalComponent makeEqTri( float length, b2World& world, b2BodyDef bodyDef = {}, float density = 1 ) { float h = 0.86602540378f * length; // ?3 / 2 * a b2Vec2 vertices[] = { { 0, 2 * h / 3 }, { +length / 2, -h / 3 }, { -length / 2, -h / 3 }, }; b2PolygonShape triShape; triShape.Set( vertices, 3 ); b2FixtureDef fxtDef; fxtDef.shape = &triShape; fxtDef.friction = DEFAULT_FRICTION; fxtDef.density = density; b2Body* pBody = world.CreateBody( &bodyDef ); pBody->CreateFixture( &fxtDef ); return PhysicalComponent( pBody ); } }; } // namespace odin
true
5ec1c513f9b1f34c1832416a64f0d1a870d1f5d0
C++
gybing/RobertC
/Temporary_File/Temporary_File/Temporary_File.cpp
UTF-8
1,577
2.71875
3
[]
no_license
// Temporary_File.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include "pch.h" #include <Windows.h> #include <iostream> #define BUFFSIZE 1024 int main() { TCHAR wPath[MAX_PATH]; LPWSTR fullName = new TCHAR[MAX_PATH]; TCHAR buf[BUFFSIZE]; DWORD dwAlreadySize = 0; BOOL bRes; DWORD pathLength = GetTempPath(MAX_PATH, wPath); // 创建临时文件并打开 if (pathLength > MAX_PATH || (pathLength < 0)) { return -1; } UINT uUnique = GetTempFileName(wPath, L"tempFile", 0, fullName); if (uUnique == 0) { return -2; } HANDLE hTempFile = CreateFile(fullName, GENERIC_ALL, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hTempFile == INVALID_HANDLE_VALUE) { return -3; } // 读取本地文件 HANDLE hLocalFile = CreateFile(L"D:/a/local.txt", GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); do { bRes = ReadFile(hLocalFile, buf, BUFFSIZE, &dwAlreadySize, NULL); if (!bRes) { std::cout << "Error = " << GetLastError() << "\n"; return -4; } bRes = WriteFile(hTempFile, buf, dwAlreadySize, NULL, NULL); if (!bRes) { std::cout << "Error = " << GetLastError() << "\n"; return -5; } } while (dwAlreadySize != 0); CloseHandle(hTempFile); CloseHandle(hLocalFile); // 将临时文件移动到新的文件里 bRes = MoveFileEx(fullName, L"D:/a/moveex.txt", MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED); if (!bRes) { std::cout << "Error = " << GetLastError() << "\n"; return -6; } return 0; }
true
349ff8c5786affe1cb0d34742729564c3bcc755c
C++
jebreimo/DemReader
/extras/deminfo/src/deminfo.cpp
UTF-8
1,949
2.765625
3
[ "BSD-2-Clause" ]
permissive
//**************************************************************************** // Copyright © 2020 Jan Erik Breimo. All rights reserved. // Created by Jan Erik Breimo on 2020-09-18. // // This file is distributed under the BSD License. // License text is included with the source distribution. //**************************************************************************** #include <iostream> #include <fstream> #include <Argos/Argos.hpp> #include <DemReader/DemReader.hpp> struct RecordBStats { unsigned count = 0; unsigned max_row = 0; unsigned max_column = 0; unsigned missing = 0; }; int main(int argc, char* argv[]) { using namespace Argos; auto args = ArgumentParser(argv[0], true) .add(Argument("FILE")) .parse(argc, argv); std::ifstream file(args.value("FILE").asString()); if (!file) args.value("FILE").error("no such file!"); std::ios::sync_with_stdio(false); try { Dem::DemReader reader(file); const auto& a = reader.record_a(); print(a, std::cout); RecordBStats stats; for (auto b = reader.next_record_b(); b; b = reader.next_record_b()) { stats.count++; stats.max_row = std::max(stats.max_row, unsigned(b->row + b->rows - 1)); stats.max_column = std::max(stats.max_column, unsigned(b->column + b->columns - 1)); stats.missing = std::count(b->elevations.begin(), b->elevations.end(), -32767); std::cout << "\r" << stats.count << std::flush; } std::cout << '\r' << "instances of record B: " << stats.count << '\n' << "rowCount: " << stats.max_row << '\n' << "columnCount: " << stats.max_column << '\n' << "number of missing elevations: " << stats.missing << '\n'; } catch (std::exception& ex) { std::cout << "Exception: " << ex.what() << "\n"; } return 0; }
true
9481f4acaf434e1e298329c6f15e37e7821f2093
C++
64octets/rfirstraytracer
/src/Trimesh.cpp
UTF-8
1,131
2.8125
3
[]
no_license
#include "trimesh.h" Trimesh::Trimesh(const std::vector<vec3> &verts) : verts(verts) { calcBounds(); } void Trimesh::calcBounds() { bounds_min = vec3(FLT_MAX, FLT_MAX, FLT_MAX); bounds_max = vec3(FLT_MIN, FLT_MIN, FLT_MIN); for (size_t i=0; i<verts.size(); i++){ const vec3 &v = verts[i]; bounds_min = min(bounds_min, v); bounds_max = max(bounds_max, v); } } bool Trimesh::intersect(const ray_t &ray, Intersection_t &hit) { float boxnear, boxfar; if ( !ray.CheckBoxIntersection(bounds_min, bounds_max, boxnear, boxfar ) ) { return false; } const size_t numVerts = verts.size(); int num_tris_hit = 0; for ( size_t i=0; i<numVerts; i+=3 ) { const vec3 &a = verts[i+0]; const vec3 &b = verts[i+1]; const vec3 &c = verts[i+2]; vec3 geometric_normal; const float t_triangle = ray.intersectTriangle( a,b,c, geometric_normal ); if ( t_triangle < FLT_MAX ) { num_tris_hit++; hit.t = t_triangle; const vec3 hitPoint = ray.origin + hit.t * ray.dir; hit.normal = geometric_normal; // TODO, interpolate normals with barycentric coords (uvw) hit.mat = mat; } } return num_tris_hit > 0; }
true
065dccbe92437204c6924813c8fa54b714d733bf
C++
kyduke/Coding
/LeetCode/739_DailyTemperatures.cpp
UTF-8
1,161
3.109375
3
[]
no_license
// https://leetcode.com/problems/daily-temperatures/description/ class Solution { public: vector<int> dailyTemperatures(vector<int>& temperatures) { map<int, vector<int>> history; map<int, vector<int>>::iterator it; vector<int> arr; vector<int> ans; int i, j; ans.assign(temperatures.size(), 0); for (i = 0; i < temperatures.size(); i++) { while (true) { it = history.begin(); if (it == history.end() || it->first >= temperatures[i]) break; for (j = 0; j < it->second.size(); j++) { ans[ it->second[j] ] = i - it->second[j]; } history.erase(it); } it = history.find(temperatures[i]); if (it == history.end()) { arr.clear(); arr.push_back(i); history.insert(make_pair(temperatures[i], arr)); } else { it->second.push_back(i); } } return ans; } }; /* [73, 74, 75, 71, 69, 72, 76, 73] ===== [1, 1, 4, 2, 1, 1, 0, 0] */
true
a6fbf9e36008bfd0bd54e9efd28fe02c3cc82fc6
C++
Alex-Shahane/stepik-cpp-basic
/module-3/step-3-10.cpp
UTF-8
868
3.5625
4
[]
no_license
#include <iostream> #include <cstddef> // size_t #include <cstring> // strlen, strcpy #include <algorithm> // std::swap struct String { String(const char* str = "") : size(strlen(str)) , str(new char [size + 1]) { strcpy(this->str, str); } String(size_t n, char c) : size(n) , str(new char [size + 1]) { memset(str, c, size); } ~String() { delete [] str; str = nullptr; } void swap(String& other) { std::swap(this->str, other.str); std::swap(this->size, other.size); } void append(String& other) { String new_string(size + other.size, '\0'); strcpy(new_string.str, str); strcpy(new_string.str + size, other.str); swap(new_string); } size_t size; char* str; }; int main() { return 0; }
true
6fbb26193c087972acfc736c48fd23c5dd69693f
C++
fpdjsns/Algorithm
/programmers/Dev-matching/다단계 칫솔 판매.cpp
UTF-8
1,300
3.375
3
[ "MIT" ]
permissive
/** * problem : https://programmers.co.kr/learn/courses/30/lessons/77486 * time complexity : O(N + M) // N = |enroll|, M = |seller| */ #include <string> #include <vector> #include <unordered_map> using namespace std; /** * enroll : 판매원 이름 * referral : 다단계 조직에 참여시킨 판매원 이름 * seller : 판매원 이름 * amount : 판매량 집계 데이터의 판매 수량 * 칫솔가격 : 100 */ vector<int> solution(vector<string> enroll, vector<string> referral, vector<string> seller, vector<int> amount) { const int PRICE = 100; unordered_map<string, string> parentMap; for(int i=0; i<enroll.size(); i++) parentMap[enroll[i]] = referral[i]; unordered_map<string, int> priceMap; for(int i=0; i<seller.size(); i++) { string people = seller[i]; int price = amount[i] * PRICE; while(parentMap[people] != "-") { // 90% priceMap[people] += price - (int)(price * 0.1); price *= 0.1; people = parentMap[people]; if(price == 0) break; } priceMap[people] += price - (int)(price * 0.1); } vector<int> answer(enroll.size()); for(int i=0; i<enroll.size(); i++) answer[i] = priceMap[enroll[i]]; return answer; }
true
83caa94ec6f42b2a4f0dcbca7c2fbd95a183a97d
C++
ljt12138/Hyper-OS
/src/syscall/syscalls/sys_parent.cpp
UTF-8
453
2.59375
3
[]
no_license
/** * syscall/syscalls/sys_parent.cpp * get process id of parent */ #include "sys_parent.h" #include "../../process/process.h" #include "../../logging/logging.h" #include "../../status/status.h" #include "../../core/core.h" sys_parent::sys_parent() :syscall_t(syscall_id_t::PARENT) { } int sys_parent::process() { int res = status.get_core()->get_current()->get_par(); logging::debug << "get pid : " << res << logging::log_endl; return res; }
true
04290fe2a258fb91022a38ebe20baf076eb2ff2c
C++
kkubunge/Common
/CTC_PE_ALD/Function/Function_Maint_Run/Source/TransferArea.cpp
UTF-8
7,842
2.765625
3
[]
no_license
// TransferArea.cpp: implementation of the CTransferArea class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "TransferArea.h" #include "Area.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CTransferArea::CTransferArea() { m_psAreaList = NULL; m_psCurrentList = NULL; m_psStartList = NULL; m_psCurrentClear= NULL; } CTransferArea::~CTransferArea() { sArea* psArea = NULL; sArea* psNext = NULL; sArea* psTemp = NULL; psArea = m_psStartList; psNext = m_psStartList->pNext; do { if (NULL == psNext) { //delete current & break; if (NULL != psArea) { if (NULL != psArea->pArea) delete psArea->pArea; delete psArea; } break; } else { psTemp = psNext; if (NULL != psArea) { if (NULL != psArea->pArea) delete psArea->pArea; delete psArea; } psArea = psTemp; psNext = psTemp->pNext; } } while (1); } ////////////////////////////////////////////////////////////////////////////////////////////////////// //Function : IsValidArea() //Date : 2007.06.25 //Description : //Arguments : //Return Value : BOOL ////////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CTransferArea::IsValidArea (char* szAreaName , int nSWEnum) { BOOL bRet = TRUE; sArea* psArea = NULL; psArea = m_psStartList; //Not Yet created any area if (NULL == psArea) return TRUE; while (NULL != psArea) { if (0 == strcmp(psArea->szAreaName , szAreaName)) {bRet = FALSE; break;} if (nSWEnum == psArea->nSWEnum) {bRet = FALSE; break;} psArea = psArea->pNext; } return bRet; } ////////////////////////////////////////////////////////////////////////////////////////////////////// //Function : AddArea() //Date : 2007.06.25 //Description : //Arguments : //Return Value : BOOL ////////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CTransferArea::AddArea(char* szAreaName , int nMaxSlot , int nCapacity , int nSWEnum) { BOOL bRet = TRUE; do { if (FALSE == IsValidArea(szAreaName , nSWEnum)) {bRet = FALSE; break;} if (NULL == m_psCurrentList) { //Initial Create m_psAreaList = new sArea; strcpy(m_psAreaList->szAreaName , szAreaName); m_psAreaList->nMaxSlot = nMaxSlot; m_psAreaList->nCapacity = nCapacity; m_psAreaList->nSWEnum = nSWEnum; m_psCurrentList = m_psAreaList; m_psStartList = m_psAreaList; } else { m_psCurrentList->pNext = new sArea; strcpy(m_psCurrentList->pNext->szAreaName , szAreaName); m_psCurrentList->pNext->nMaxSlot = nMaxSlot; m_psCurrentList->pNext->nCapacity = nCapacity; m_psCurrentList->pNext->nSWEnum = nSWEnum; m_psCurrentList->pPrev = m_psCurrentList; m_psCurrentList = m_psCurrentList->pNext; } } while (0); return bRet; } ////////////////////////////////////////////////////////////////////////////////////////////////////// //Function : GetFirstArea() //Date : 2007.06.25 //Description : //Arguments : //Return Value : sArea* ////////////////////////////////////////////////////////////////////////////////////////////////////// sArea* CTransferArea::GetFirstArea() { m_psCurrentList = m_psStartList; return m_psCurrentList; } ////////////////////////////////////////////////////////////////////////////////////////////////////// //Function : GetNextArea() //Date : 2007.06.25 //Description : //Arguments : //Return Value : sArea* ////////////////////////////////////////////////////////////////////////////////////////////////////// sArea* CTransferArea::GetNextArea () { m_psCurrentList = m_psCurrentList->pNext; return m_psCurrentList; } ////////////////////////////////////////////////////////////////////////////////////////////////////// //Function : GetFirstClear() //Date : 2007.06.25 //Description : //Arguments : //Return Value : sArea* ////////////////////////////////////////////////////////////////////////////////////////////////////// sArea* CTransferArea::GetFirstClear() { m_psCurrentClear = m_psStartList; return m_psCurrentClear; } ////////////////////////////////////////////////////////////////////////////////////////////////////// //Function : GetNextClear() //Date : 2007.06.25 //Description : //Arguments : //Return Value : sArea* ////////////////////////////////////////////////////////////////////////////////////////////////////// sArea* CTransferArea::GetNextClear () { m_psCurrentClear = m_psCurrentClear->pNext; return m_psCurrentClear; } ////////////////////////////////////////////////////////////////////////////////////////////////////// //Function : GetAreaCount() //Date : 2007.06.25 //Description : //Arguments : //Return Value : int ////////////////////////////////////////////////////////////////////////////////////////////////////// int CTransferArea::GetAreaCount() { int nCount = 0; if (NULL != m_psStartList) nCount++; else return 0; sArea* psArea = NULL; psArea = m_psStartList; while (NULL != psArea) { if (NULL == psArea->pNext) break; else nCount++; psArea = psArea->pNext; } return nCount; } ////////////////////////////////////////////////////////////////////////////////////////////////////// //Function : GetArea() //Date : 2007.06.25 //Description : //Arguments : //Return Value : CArea* ////////////////////////////////////////////////////////////////////////////////////////////////////// CArea* CTransferArea::GetArea(char* szAreaName) { CArea* pArea = NULL; m_psCurrentList = m_psStartList; while (NULL != m_psCurrentList) { if (0 == strcmp(m_psCurrentList->szAreaName , szAreaName)) { pArea = m_psCurrentList->pArea; break; } m_psCurrentList = m_psCurrentList->pNext; } return pArea; } ////////////////////////////////////////////////////////////////////////////////////////////////////// //Function : GetArea() //Date : 2007.06.25 //Description : //Arguments : //Return Value : CArea* ////////////////////////////////////////////////////////////////////////////////////////////////////// CArea* CTransferArea::GetArea(int nSWEnum) { CArea* pArea = NULL; m_psCurrentList = m_psStartList; while (NULL != m_psCurrentList) { if (nSWEnum == m_psCurrentList->nSWEnum) { pArea = m_psCurrentList->pArea; break; } m_psCurrentList = m_psCurrentList->pNext; } return pArea; } ////////////////////////////////////////////////////////////////////////////////////////////////////// //Function : GetSArea() //Date : 2007.06.25 //Description : //Arguments : //Return Value : sArea* ////////////////////////////////////////////////////////////////////////////////////////////////////// sArea* CTransferArea::GetSArea(char* szAreaName) { sArea* psArea = NULL; m_psCurrentList = m_psStartList; while (NULL != m_psCurrentList) { if (0 == strcmp(m_psCurrentList->szAreaName , szAreaName)) { return m_psCurrentList; break; } m_psCurrentList = m_psCurrentList->pNext; } return psArea; } ////////////////////////////////////////////////////////////////////////////////////////////////////// //Function : GetSArea() //Date : 2007.06.25 //Description : //Arguments : //Return Value : sArea* ////////////////////////////////////////////////////////////////////////////////////////////////////// sArea* CTransferArea::GetSArea(int nSWEnum) { sArea* psArea = NULL; m_psCurrentList = m_psStartList; while (NULL != m_psCurrentList) { if (nSWEnum == m_psCurrentList->nSWEnum) { return m_psCurrentList; break; } m_psCurrentList = m_psCurrentList->pNext; } return psArea; }
true
2e6165e20464ff2b6045bc4ec71533f44aff56c5
C++
wadong100/System-Software-Experiment-3
/lab3/Space.cpp
UTF-8
2,029
2.875
3
[]
no_license
#include "Space.h" using namespace std; Space::Space(){ int i; state = 'N'; for(i=0;i<4;i++){ emptytime[i] = 0; returntime[i] = 0; } } string Space::getusername(){ return username; } char Space::getstate(){ return state; } void Space::setuserborrow(string mem_name, int* nowd, int rsvtime){ int i; username = mem_name; state = 'B'; for(i=0;i<4;i++) returntime[i] = nowd[i]; returntime[3] += 3; if(returntime[3] >= 24){ returntime[3] -= 24; returntime[2]++; } if(returntime[2] > 30){ returntime[2] -= 30; returntime[1]++; } if(returntime[1] > 12){ returntime[1] -= 12; returntime[0]++; } } void Space::setuserreturn(){ int i; for(i=0;i<4;i++) returntime[i] = 0; state = 'N'; } void Space::setempty(int* d){ int i; state = 'E'; for(i=0;i<4;i++) emptytime[i] = d[i]; emptytime[3] += 1; if(emptytime[3] >= 24){ emptytime[3] -= 24; emptytime[2]++; } if(emptytime[2] > 30){ emptytime[2] -= 30; emptytime[1]++; } if(emptytime[1] > 12){ emptytime[1] -= 12; emptytime[0]++; } } void Space::setstate(){ int i; state = 'B'; for(i=0;i<4;i++) emptytime[i] = 0; } int Space::isavailable(int* nowd){ int i; if(state == 'B'){ for(i=0;i<3;i++){ if(nowd[i] != returntime[i]){ state = 'N'; return 1; } } if(nowd[3] < returntime[3]) return 0; state = 'N'; return 1; }else if(state == 'E'){ for(i=0;i<3;i++){ if(nowd[i] != emptytime[i]){ state = 'N'; return 1; } } if(nowd[3] < emptytime[3]) return 0; state = 'N'; return 1; }else return 1; } int Space::getremaintime(int* d){ return returntime[3] - d[3]; } Study_Room::Study_Room():Space(){ } Seat::Seat():Space(){ }
true
9001fefccb7f86ece147c807d5bc3705ec7b1338
C++
bence7999/InterQiew
/Tests/Excercise_19.cpp
ISO-8859-2
6,649
3.625
4
[]
no_license
#include "Excercices.h" #include <functional> #include <vector> #include <algorithm> #include <string> #include <cassert> namespace Ex19 { class A { public: A() : m_size(sizeof(A)) { // 8 byte -> virtual table (4), variable (4) std::cout << "A: " << m_size << std::endl; } public: virtual void f() const { std::cout << 1; } virtual ~A() { } public: static bool compare(const A *a, const A *b) { assert(a != nullptr); assert(b != nullptr); return a->m_size < b->m_size; } protected: size_t m_size; }; class B : public A { public: B() : m_b(nullptr) { m_size = sizeof(B); // 12 byte -> A (8), +1 char* param(4) std::cout << "B: " << m_size << std::endl; } public: virtual void f() const { std::cout << 2; } private: char *m_b; }; class C : public A { public: C() { m_size = sizeof(C); // 8 byte -> A (8), static int* nem nveli a mrett std::cout << "C: " << m_size << std::endl; } public: virtual void f() const { std::cout << 3; } private: static int *m_c; }; int *C::m_c = nullptr; void Excercise_19() { std::vector<A*> v({ new C, new B, new A }); std::stable_sort(v.begin(), v.end(), A::compare); std::for_each(v.begin(), v.end(), std::mem_fn(&A::f)); std::cout << std::endl; std::for_each(v.begin(), v.end(), std::default_delete<A>()); } void Extra05() { A *a = new A(); // m_a = 8 -> maga a class 4b + virtual table 4b B *b = new B(); // m_b = 12 -> maga b class 4b + a class 4b + virtual table 4b C *c = new C(); // m_c = 8 -> maga c class 1b (static miatt) + a class 4b + virtual table 4b } // std::mem_fn struct int_holder { int value; int triple() { return value * 3; } }; void Extra01() { int_holder five{ 5 }; std::cout << five.triple() << '\n'; auto triple = std::mem_fn(&int_holder::triple); std::cout << triple(five) << '\n'; } struct Foo { void display_greeting() { std::cout << "Hello, world.\n"; } void display_number(int i) { std::cout << "number: " << i << '\n'; } int data = 7; }; void Extra02(){ Foo f; auto greet = std::mem_fn(&Foo::display_greeting); greet(f); auto print_num = std::mem_fn(&Foo::display_number); print_num(f, 42); auto access_data = std::mem_fn(&Foo::data); std::cout << "data: " << access_data(f) << '\n'; } // std::stable_sort struct Employee { int age; std::string name; // Does not participate in comparisons }; bool operator<(const Employee &lhs, const Employee &rhs) { return lhs.age < rhs.age; } void Extra03() { std::vector<Employee> v = { {108, "Zaphod"}, {32, "Arthur"}, {108, "Ford"}, }; std::stable_sort(v.begin(), v.end()); for (const Employee &e : v) { std::cout << e.age << ", " << e.name << '\n'; } } bool compare_as_ints(double i, double j) { return (int(i) < int(j)); } void Extra04() { double mydoubles[] = { 3.14, 1.41, 2.72, 4.67, 1.73, 1.32, 1.62, 2.58 }; std::vector<double> myvector; myvector.assign(mydoubles, mydoubles + 8); std::cout << "using default comparison:"; std::stable_sort(myvector.begin(), myvector.end()); for (std::vector<double>::iterator it = myvector.begin(); it != myvector.end(); ++it) std::cout << ' ' << *it; std::cout << '\n'; myvector.assign(mydoubles, mydoubles + 8); std::cout << "using 'compare_as_ints' :"; std::stable_sort(myvector.begin(), myvector.end(), compare_as_ints); for (std::vector<double>::iterator it = myvector.begin(); it != myvector.end(); ++it) std::cout << ' ' << *it; std::cout << '\n'; } // class sizes class SizeA { }; class SizeB { public: SizeB() = default; }; class SizeC { private: int m_n; }; class SizeD { public: SizeD(int n = 1) : m_n(n) { } private: int m_n; }; class SizeE { public: void print() { } }; class SizeF { public: virtual void print() { } }; class SizeG { public: SizeG(int n = 1) : m_n(n) { } virtual void print() {} private: int m_n; }; void Extra06() { SizeA a; std::cout << "A: " << sizeof(SizeA) << std::endl; // 1 std::cout << "a: " << sizeof(a) << std::endl; // 1 SizeB b; std::cout << "B: " << sizeof(SizeB) << std::endl; // 1 std::cout << "b: " << sizeof(b) << std::endl; // 1 SizeC c; std::cout << "C: " << sizeof(SizeC) << std::endl; // 4 std::cout << "c: " << sizeof(c) << std::endl; // 4 SizeD d(0); std::cout << "D: " << sizeof(SizeD) << std::endl; // 4 std::cout << "d: " << sizeof(d) << std::endl; // 4 SizeE e; std::cout << "E: " << sizeof(SizeE) << std::endl; // 1 std::cout << "e: " << sizeof(e) << std::endl; // 1 SizeF f; std::cout << "F: " << sizeof(SizeF) << std::endl; // 4 std::cout << "f: " << sizeof(f) << std::endl; // 4 SizeG g(0); std::cout << "G: " << sizeof(SizeG) << std::endl; // 8 std::cout << "g: " << sizeof(g) << std::endl; // 8 } class DerivedA : public SizeA { }; class DerivedVA : virtual public SizeA { }; class DerivedC : public SizeC { }; class DerivedVC : virtual public SizeC { }; class DerivedF : public SizeF { }; class DerivedVF : virtual public SizeF { }; class DerivedG : public SizeG { }; class DerivedVG : virtual public SizeG { }; void Extra07() { DerivedA da; std::cout << "DerivedA: " << sizeof(DerivedA) << std::endl; // 1 DerivedVA dva; std::cout << "DerivedVA: " << sizeof(DerivedVA) << std::endl; // 4 DerivedC dc(); std::cout << "DerivedC: " << sizeof(DerivedC) << std::endl; // 4 DerivedVC dvc(); std::cout << "DerivedVC: " << sizeof(DerivedVC) << std::endl; // 8 DerivedF df; std::cout << "DerivedF: " << sizeof(DerivedF) << std::endl; // 4 DerivedVF dvf; std::cout << "DerivedVF: " << sizeof(DerivedVF) << std::endl; // 8 DerivedG dg; std::cout << "DerivedG: " << sizeof(DerivedG) << std::endl; // 8 DerivedVG dvg; std::cout << "DerivedVG: " << sizeof(DerivedVG) << std::endl; // 12 } class DerivedEA : public SizeA { // paremter nlkl: 1 char *m_b; // 1 paramterrel: 4 int m_n; // 2 paramterrel: 8 // plusz 2 param + 8 byte // char *m_c; // int m_m; // static static int s_n; // nem nveli DerivedEA mrett static int *sp_n; // nem nveli DerivedEA mrett }; int DerivedEA::s_n = 0; int* DerivedEA::sp_n = new int(0); class DerivedEB : public SizeB { }; class DerivedEC : public SizeC { }; class DerivedED : public SizeD { }; class DerivedEE : public SizeE { }; class DerivedEF : public SizeF { }; class DerivedEG : public SizeG { }; void Extra08() { DerivedEA dea; std::cout << "DerivedEA: " << sizeof(DerivedEA) << std::endl; // 8 } }
true
d10534ace2f7665c428899ac7a186184fc5b81e6
C++
longxiangbaby/FlagGame
/Classes/control/GameControl.cpp
UTF-8
1,393
2.921875
3
[]
no_license
#include "GameControl.h" #include "global.h" static GameControl* p_gameControl=nullptr; GameControl::GameControl(void): player(nullptr), isPause(true) { } GameControl::~GameControl(void) { CC_SAFE_DELETE(player); CCLOG("GameControl is destroy!"); m_camps.clear(); } GameControl* GameControl::getInstance() { if (p_gameControl==nullptr) { p_gameControl=new GameControl(); } return p_gameControl; } bool GameControl::init() { player=Player::createPlayer(); //addCamp(player); addCamp(Camp::createCamp()); return true; } Player* GameControl::getPlayer() { return player; } Camp* GameControl::getCamp(int flag) { return m_camps.at(flag); } void GameControl::destroy() { CC_SAFE_DELETE(p_gameControl); p_gameControl=nullptr; } void GameControl::addCamp(Camp* camp) { if (camp->getFlag()==CampFlag::PLAYER) { player=static_cast<Player*>(camp); } m_camps.insert(camp->getFlag(),camp); } void GameControl::update(float delta) { if (isPause)return; for (auto iter : m_camps) { Camp* camp=iter.second; camp->update(delta); } for (auto it : m_citys) { City* city=it.second; city->update(delta); } } void GameControl::pause() { isPause=true; } void GameControl::start() { isPause=false; } void GameControl::addCity(City* city) { m_citys.insert(city->getCityVO()->getID(),city); } City* GameControl::getCity(int id) { return m_citys.at(id); }
true
d4e7a53b975382c8ac1c9fcb53375e357881ec9f
C++
almoreir/algorithm
/cd4/PDS/soop/HANOITOW.CPP
UTF-8
225
2.640625
3
[]
no_license
#include<stdio.h> #include<conio.h> void hanoi(int n,char a,char b,char c) { if(n>0) { hanoi(n-1,a,c,b); printf("%dth plate %c to %c\n",n,a,b); hanoi(n-1,c,b,a); } } void main() { clrscr(); hanoi(4,'a','b','c'); }
true
11b461f9db22b5d8e463ebd680f02772308d6728
C++
overnew/CodeSaving
/블랙잭.cpp
UTF-8
872
3.234375
3
[]
no_license
// 쉬운 부스트포스트 // https://www.acmicpc.net/problem/2798 #include <iostream> #include <algorithm> using namespace std; int N; //카드개수 int M; int number[100]; int BlackJack(){ int sum=0; int answer=0; int answer_temp=0; for(int i=0; i<(N-2) ;++i){ sum += number[i]; for(int j= i+1 ; j<(N-1) ;++j){ sum += number[j]; for(int k=j+1; k<N ; ++k){ sum+= number[k]; answer_temp = sum; if( M>=answer_temp && (M - answer > M-answer_temp) ){ answer = answer_temp; } // >=에서 =를 안붙여서 해맴.. sum -= number[k]; } sum -= number[j]; } sum =0; } return answer; } int main() { int temp; cin>>N; cin>>M; for(int i=0; i<N ; ++i){ cin>>number[i]; } sort(number, number+N); cout<< BlackJack()<<endl; return 0; }
true
ecbe0de52a9410bbb5153beaf91a260f8c823fe0
C++
ananda1066/ECS60Programs
/BTreeImplementation/LeafNode.h
UTF-8
533
2.828125
3
[]
no_license
#ifndef LeafNodeH #define LeafNodeH #include "BTreeNode.h" class LeafNode:public BTreeNode { int *values; int leafSize; public: LeafNode(int LSize, InternalNode *p, BTreeNode *left, BTreeNode *right); int getMinimum() const; LeafNode* insert(int value); // returns pointer to new Leaf if splits // else NULL void print(Queue <BTreeNode*> &queue); void sortValues(int value); LeafNode* leafNotFull(int value); LeafNode* splitLeaf(int value); LeafNode* checkSiblings(int value); }; //LeafNode class #endif
true
79881a4c2758e845d2486c47aaec3e3ec55f43fe
C++
sagar-viradiya/DS-Algo-C
/Leetcode/MostFrequentElements.cpp
UTF-8
1,045
3.453125
3
[]
no_license
#include<iostream> #include<queue> #include<vector> #include<unordered_map> using namespace std; // Inputs vector<int> nums {1, 1, 2, 2, 2, 3, 3, 3, 3, 3}; int k = 2; unordered_map<int, int> freq; auto compare = [](int a, int b) { return freq[a] < freq[b]; }; int main(int argc, char const *argv[]) { // PQ with custom comparator for frequency comparison. priority_queue<int, vector<int>, decltype(compare)> pq(compare); // Calculate the frequency of each number. for (int num : nums) { if (freq.find(num) == freq.end()) { freq[num] = 0; } freq[num]++; } // Construct priority queue of number based on frequency calculated above. for (unordered_map<int, int>::iterator it = freq.begin(); it != freq.end(); ++it) { pq.push(it->first); } // Pop K elements from PQ which will return number having highest frequency for each pop. for (int i = k - 1; i >= 0; --i) { cout << pq.top() << endl; pq.pop(); } return 0; }
true
31a1de72adb7af1ce1028b43a47f6266a24f3f84
C++
Efore/BaldLionEngine
/BaldLionEngine/src/BaldLion/SceneManagement/SceneManager.cpp
UTF-8
2,255
2.671875
3
[ "Apache-2.0" ]
permissive
#include "blpch.h" #include "SceneManager.h" #include "Serialization/SceneSerializer.h" namespace BaldLion { namespace SceneManagement { HashMap<StringId, Scene*> SceneManager::m_activeScenes; Scene* SceneManager::m_mainScene; void SceneManager::Init() { m_activeScenes = HashMap<StringId, Scene*>(AllocationType::FreeList_ECS, 10); } void SceneManager::FrameStart() { if (m_mainScene != nullptr) { m_mainScene->FrameStart(); } } void SceneManager::Update() { BL_PROFILE_FUNCTION(); if (m_mainScene != nullptr) { m_mainScene->Update(); } } void SceneManager::FrameEnd() { if (m_mainScene != nullptr) { m_mainScene->FrameEnd(); } } void SceneManager::Stop() { m_activeScenes.Delete(); } void SceneManager::SetMainScene(StringId sceneID) { Scene* result = nullptr; if (m_activeScenes.TryGet(sceneID, result)) { m_mainScene = result; } } Scene* SceneManager::GetMainScene() { return m_mainScene; } ECS::ECSManager* SceneManager::GetECSManager() { return m_mainScene->GetECSManager(); } void SceneManager::OpenScene(const char* filepath) { SceneSerializer::DeserializeScene(filepath); } void SceneManager::SaveScene(const char* filepath) { SceneSerializer::SerializeScene(m_mainScene, filepath); } void SceneManager::AddScene(const char* sceneID, bool openAdditive, bool setAsMainScene) { AddScene(sceneID, nullptr, openAdditive, setAsMainScene); } void SceneManager::AddScene(const char* sceneID, ECS::ECSManager* ecsManager, bool openAdditive, bool setAsMainScene) { StringId sceneid = BL_STRING_TO_STRINGID(sceneID); Scene* newScene = MemoryManager::New<Scene>(sceneID, AllocationType::FreeList_Main, sceneID, ecsManager); newScene->Init(); if (openAdditive) { if (!m_activeScenes.Contains(sceneid)) { m_activeScenes.Emplace(sceneid, newScene); } if (setAsMainScene) { m_mainScene = newScene; } } else { if (m_mainScene) { MemoryManager::Delete(m_mainScene); } m_mainScene = newScene; } } void SceneManager::RemoveActiveScene(StringId sceneID) { m_activeScenes.Remove(sceneID); } } }
true
c060fd05312f825dbf64f49e251d6a1cf0943b91
C++
rodrigobedoya/vli2_modelo_contagio_enfermedades
/cell_grid.cpp
UTF-8
3,269
3.25
3
[]
no_license
#include "cell_grid.h" #include <iostream> #include <stdlib.h> CellGrid::CellGrid(float numberX, float numberY): number_of_cellsX(numberX), number_of_cellsY(numberY), dead(false), death_count(0) { grid.reserve(number_of_cellsY); for(int i = 0;i < number_of_cellsX;i++) { std::vector<Cell*> newV; newV.clear(); newV.reserve(number_of_cellsX); for(int j = 0; j < number_of_cellsY;j++) { Cell *newCell = new Cell; newV.push_back(newCell); } grid.push_back(newV); } } CellGrid::~CellGrid() { for(int i = 0;i < number_of_cellsX;i++) { for(int j = 0; j < number_of_cellsY;j++) { delete grid[i][j]; } } } Cell* CellGrid::at(int posX, int posY) { return grid[posX][posY]; } void CellGrid::draw() { for(int i = 0;i < number_of_cellsY;i++) { for(int j = 0; j < number_of_cellsX;j++) { grid[i][j]->draw(); } std::cout << std::endl; } } int CellGrid::getDeathCount() { return death_count; } std::vector<Cell*> CellGrid::surroundingCells(int posX,int posY) { bool left_side = true, right_side = true, upper_side = true, down_side = true; std::vector<Cell*> environment; if (posY != 0) //left { if(grid[posX][posY-1]->getState() == 0) environment.push_back(grid[posX][posY-1]); left_side = false; } if (posY != number_of_cellsY-1) //right { if(grid[posX][posY+1]->getState() == 0) environment.push_back(grid[posX][posY+1]); right_side = false; } if (posX != 0) //above { if(grid[posX-1][posY]->getState() == 0) environment.push_back(grid[posX-1][posY]); upper_side = false; } if (posX != number_of_cellsX-1) //below { if(grid[posX+1][posY]->getState() == 0) environment.push_back(grid[posX+1][posY]); down_side = false; } return environment; } bool CellGrid::isDead() { return dead; } void CellGrid::run() { bool change = false; for(int i = 0; i < number_of_cellsX;i++) { for(int j = 0; j < number_of_cellsY;j++) { grid[i][j]->evaluate(death_count,change); if(grid[i][j]->getState() == 1) { //CURE INFECETD CELLS int cured = rand()%100; if(cured+1 < grid[i][j]->getCureChance()) { grid[i][j]->setState(0); grid[i][j]->setDaysInfected(0); change = true; continue; } //INFECT SURROUNDING CELLS std::vector<Cell*> possibleInfections = surroundingCells(i,j); for(std::vector<Cell*>::iterator it=possibleInfections.begin(); it!=possibleInfections.end(); ++it) { int infected = rand()%100; if(infected+1 < grid[i][j]->getInfectChance()) { (*it)->setState(3); change = true; } } } } } /* draw(); std::cout << "=============================================================" << std::endl; //*/ if(death_count == number_of_cellsX*number_of_cellsY || !change) dead = true; } void CellGrid::summary(std::vector<int> &dead, std::vector<int> &alive) { int alive_count = number_of_cellsX*number_of_cellsY - death_count; /*std::cout << "Alive: "<< alive_count << std::endl; std::cout << "Dead: "<< death_count << std::endl;*/ dead.push_back(death_count); alive.push_back(alive_count); }
true
6ac12f5a2441e4b200c1e6bd3a13712272688815
C++
thrs79136/CPP-Templates
/hashtable.hpp
UTF-8
1,151
3.5625
4
[]
no_license
#include <iostream> #include <vector> using namespace std; template<class K> using hashfunc = long(*)(K); template<class T, class K> using getKey = K(*)(T); template<class T, class K> class HashTable{ public: HashTable(long size, hashfunc<K> pf, getKey<T,K> gK); void addEntry(T data); T getEntry(K key); template <class U, class L> friend ostream& operator<<(ostream &OS, HashTable<U,L> ht); private: long size; vector<T> *table; hashfunc<K> pf; getKey<T,K> gK; }; template<class T, class K> HashTable<T,K>::HashTable(long size, hashfunc<K> pf, getKey<T,K> gK){ this->size = size; table = new vector<T>[size]; this->pf = pf; this->gK = gK; } template<class T, class K> void HashTable<T,K>::addEntry(T data){ table[(*pf)((*gK)(data))%size].push_back(data); } template<class T, class K> T HashTable<T,K>::getEntry(K key){ for (T t: table[(*pf)(key)%size]){ if (key == (*gK)(t)) return t; } throw new string("Element not found."); } template <class U, class L> ostream& operator<<(ostream &OS, HashTable<U,L> ht){ for (int i =0; i<ht.size;i++){ for (auto t: ht.table[i]) OS << t << '\t'; OS << '\n'; } return OS; }
true
0d9e628e13ac32e9624553c674cd93c953d3125a
C++
whitychen/myPT
/include/camera.hpp
UTF-8
2,583
3.171875
3
[]
no_license
#ifndef CAMERA_H #define CAMERA_H #include "ray.hpp" #include <vecmath.h> #include <float.h> #include <cmath> class Camera { public: Camera(const Vector3f &center, const Vector3f &direction, const Vector3f &up, int imgW, int imgH) { this->center = center; this->direction = direction.normalized(); this->horizontal = Vector3f::cross(this->direction, up); this->horizontal.normalize(); this->up = Vector3f::cross(this->horizontal, this->direction); this->width = imgW; this->height = imgH; } // Generate rays for each screen-space coordinate virtual Ray generateRay(const Vector2f &point) = 0; virtual ~Camera() = default; int getWidth() const { return width; } int getHeight() const { return height; } // Extrinsic parameters Vector3f center; Vector3f direction; Vector3f up; Vector3f horizontal; // Intrinsic parameters int width; int height; float fx, fy; }; // TODO: Implement Perspective camera // You can add new functions or variables whenever needed. class PerspectiveCamera : public Camera { double aperture = 0.08; //光圈大小,由于无法做到完美小孔,使得相机光线出现一定波动 double focus; //焦距,使得相机射线法相出现波动 public: PerspectiveCamera(const Vector3f &center, const Vector3f &direction, const Vector3f &up, int imgW, int imgH, float angle) : Camera(center, direction, up, imgW, imgH) { // angle is in radian. fx = (width / 2) / tan(angle / 2); //单位坐标表示的像素大小 fy = (height / 2) / tan(angle / 2); //单位坐标表示的像素大小 focus = (center - Vector3f(-0.5, 0, 1.0)).length(); } Ray generateRay(const Vector2f &point) override { unsigned short random[3] = {0, 0, point.x() * point.x()}; unsigned short random2[3] = {0, 0, point.y() * point.y()}; double dx = erand48(random) * aperture; double dy = erand48(random2) * aperture; float u = point.x(); float v = point.y(); float x = (u - width / 2) / fx; float y = (height / 2 - v) / fy; Vector3f drc = Vector3f(focus * x - dx, focus * y - dy, focus).normalized(); // Vector3f drc = Vector3f(x, y, 1).normalized(); Matrix3f R(horizontal, -up, direction); auto dRW = R * drc; return Ray(center, dRW.normalized()); } }; #endif //CAMERA_H
true
8a03f87ff771442ca1cbbf92be7617314336512c
C++
shadmansaleh/CharScreen
/src/charScreen/CharScreen.cpp
UTF-8
3,904
3.609375
4
[]
no_license
#include "CharScreen.h" #include <cstdlib> //initiates screan by allocating requiared mwmory and cleaning terminal void CharScreen::init(int W,int H) { if( H > 0 && W > 0 ) { height = H; width = W; scr = (char*)std::malloc(H * W * sizeof(char)); if(scr){ std::memset(scr,' ',height*width); oldScr = (char*)std::malloc(H * W * sizeof(char)); if (oldScr){ std::memset(oldScr,0,height*width); clearTerminal(); refreash(); }else setDefault(); }else setDefault(); }else setDefault(); } //returns the value of a char in x,y location of screen char CharScreen::getVal(char *sc,int x,int y) { //check if input is valid if( sc && x <= width && y <= height && x >= 0 && y >= 0 ) { //width+1 is requiared to make the last char of line and the first char of line differ return *( sc + ( ((width +1) * y) + x )); } else return 0; } //oposit of getVal it change a char in a location inline int CharScreen::setVal(char *sc,int x,int y,char ch) { if( sc && x <= width && y <= height && x >= 0 && y >= 0 ) {//same as getVal *( sc + ( ((width+1) * y) + x )) = ch; return 1; } else return -1; } //it is used to reset the screen or to dustruct it . It sets default vslues void CharScreen::setDefault() { if(scr) free(scr); if(oldScr) free(oldScr); scr=NULL; oldScr=NULL; height=0; width=0; } //draws one char at a time on the screen using ansi excape sequence void CharScreen::draw(int x,int y) { if( x <= width && y <= height && x >= 0 && y >= 0 ) {//\x1b[b;aH sends sursor to (a,b) location std::cout << "\x1b[" << y+ofsetY << ";" << x+ofsetX << "H" << getVal(scr,x,y) << std::flush; } } //clears the terminal below screen void CharScreen::clearBottom() { if( height > 0 && width > 0 ) { std::cout << "\x1b[" << height+1 << "B" << "\x1b[J" << "\x1b[" << height+1 << ";0H"<<std::flush ; } } //Constuctor just cslls init CharScreen::CharScreen(int W,int H) { // if(maxHeight <= 0 || maxWidth <= 0) getMaxHW(); init(W,H); } CharScreen::CharScreen() { // if(maxHeight <= 0 || maxWidth <= 0) getMaxHW(); init(maxHeight,maxWidth); // setDefault(); } //destructor just calls setDefault CharScreen::~CharScreen() { setDefault(); } //resets screen void CharScreen::getNewScreen(int W,int H) { setDefault(); init(W,H); } //clears the screen . just puts spaces everywhere . int CharScreen::clear() { if(scr){ memset(scr,' ', height * width ); return 1; } else return -1; } //fills the screen with one char int CharScreen::fillScreen(char ch) { if(scr){ memset(scr,ch, height * width ); refreash(); return 1; } else return -1; } //clears terminal with escape sequence void CharScreen::clearTerminal() { std::cout << "\x1b[H\x1b[J" << std::flush; } //updates a single location with a char int CharScreen::update( int x , int y , char ch) { return setVal(scr,x,y,ch); } //adds a string to certain position in screen int CharScreen::update(int x,int y,char *ch) { int len = std::strlen(ch); if(width >= (x + len)) { for(int i=0; i <= len ; ++i,ch++) setVal(scr, x+i , y,*ch); return 1; }else return -1; } //adds a string at certain line int CharScreen::update(int y,char *ch) { return update(0,y,ch); } //refreashes the screen void CharScreen::refreash(int keepOld) { for (int i = 0 ; i <= height ; ++i ) for( int j = 0 ; j <= width ; ++j ) { if( getVal(scr,j,i) != getVal(oldScr,j,i)) { draw(j,i); setVal(oldScr,j,i,getVal(scr,j,i)); } } if(!keepOld) clear(); clearBottom(); } //get max height and max width void CharScreen::getMaxHW() { struct winsize size; ioctl(STDOUT_FILENO, TIOCGWINSZ, &size); maxHeight=size.ws_col; maxWidth=size.ws_row; /* size.ws_row is the number of rows, size.ws_col is the number of columns. */ }
true
092c0b48db962c5015695c12e4a94cd178773a0d
C++
Majroch/cppev3dev-code-examples
/menu.cpp
UTF-8
1,811
3.421875
3
[]
no_license
#include <iostream> #include "ev3dev.h" #include <unistd.h> /** * Returns: * U - Up * D - Down * L - Left * R - Right * B - Back * E - Enter */ char getch() { ev3dev::button up(ev3dev::button::up); ev3dev::button down(ev3dev::button::down); ev3dev::button left(ev3dev::button::left); ev3dev::button right(ev3dev::button::right); ev3dev::button back(ev3dev::button::back); ev3dev::button enter(ev3dev::button::enter); while(true) { if(up.pressed()) return 'U'; if(down.pressed()) return 'D'; if(left.pressed()) return 'L'; if(right.pressed()) return 'R'; if(back.pressed()) return 'B'; if(enter.pressed()) return 'E'; } } void clear() { system("clear"); } int main(void) { int selected = 0; while(true) { std::cout << "-----------------------------" << std::endl; std::cout << "| MENU |" << std::endl; std::cout << "-----------------------------" << std::endl; if(selected == 0) std::cout << "Option 0" << " <<" << std::endl; else std::cout << "Option 0" << std::endl; if(selected == 1) std::cout << "Option 1" << " <<" << std::endl; else std::cout << "Option 1" << std::endl; if(selected == 2) std::cout << "Option 2" << " <<" << std::endl; else std::cout << "Option 2" << std::endl; // LOGIC switch(getch()) { case 'U': if(selected <= 0) selected = 2; else selected--; break; case 'D': if(selected >= 2) selected = 0; else selected++; break; case 'B': return 0; break; } sleep(1); clear(); } }
true
40e4b4583c588d65945db87007f93d5a678b37f9
C++
dot-Sean/src
/cc/impsep/impsep.cpp
UTF-8
1,278
3.09375
3
[]
no_license
#include "impsep.h" // ------------------------------------------------------------------- #undef i #define i(member) pimp->member class ImpSepImp { public: ImpSepImp(float, float); float fReal; float fImag; }; ImpSepImp::ImpSepImp ( float fRealArg, float fImagArg ) : fReal(fRealArg), fImag(fImagArg) { ; } ImpSep::ImpSep ( float fRealArg, float fImagArg ) : pimp(new struct ImpSepImp(fRealArg, fImagArg)) { ; } ImpSep::~ImpSep () { delete this->pimp; } std::ostream & operator<< (std::ostream & out, const ImpSep & impsep) { out << impsep.i(fReal) << " + " << impsep.i(fImag) << " i"; return (out); } // ------------------------------------------------------------------- #undef i #define i(member) member Imp::Imp ( float fRealArg, float fImagArg ) : i(fReal)(fRealArg), i(fImag)(fImagArg) { ; } std::ostream & operator<< (std::ostream & out, const Imp & imp) { out << imp.i(fReal) << " + " << imp.i(fImag) << " i"; return (out); } // ------------------------------------------------------------------- #include <iostream> int main ( int argc, char * * argv ) { ImpSep impsep(7.3, 9.8); Imp imp(2.3, 3.5); std::cout << impsep << std::endl; std::cout << imp << std::endl; return (0); }
true
40ae290045537f8b8839b034bcd20456c531b7ef
C++
lemonacy/QtPractice
/FileDialog/mainwindow.cpp
UTF-8
1,989
2.8125
3
[]
no_license
#include <QTextEdit> #include <QFileDialog> #include <QFile> #include <QMessageBox> #include <QTextStream> #include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); ui->actionOpen->setShortcut(QKeySequence::Open); ui->actionOpen->setStatusTip(tr("Open an existing file")); ui->actionSave->setShortcut(QKeySequence::Save); ui->actionSave->setStatusTip(tr("Save a new file")); m_textEdit = new QTextEdit(this); setCentralWidget(m_textEdit); connect(ui->actionOpen, &QAction::triggered, this, &MainWindow::openFile); connect(ui->actionSave, &QAction::triggered, this, &MainWindow::saveFile); } MainWindow::~MainWindow() { delete ui; } void MainWindow::openFile() { QString path = QFileDialog::getOpenFileName(this, tr("Open file"), ".", tr("Text files(*.txt);;Header files(*.h)")); if (path.isEmpty()) { QMessageBox::warning(this, tr("Path"), tr("You did not select any file")); return; } QFile file(path); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { QMessageBox::warning(this, tr("Read File"), tr("Can't open file:\n%1").arg(path)); return; } QTextStream in(&file); m_textEdit->setText(in.readAll()); file.close(); } void MainWindow::saveFile() { QString path = QFileDialog::getSaveFileName(this, tr("Open file"), ".", tr("Text files(*.txt)")); if (path.isEmpty()) { QMessageBox::warning(this, tr("Path"), tr("Please choose a location to save file")); return; } QFile file(path); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { QMessageBox::warning(this, tr("Save File"), tr("Can't write to file:\n%1").arg(path)); return; } QTextStream out(&file); out << m_textEdit->toPlainText(); file.close(); }
true
b0cc39f8b4cc4e9594e1ddc1e4d47948e87dd361
C++
mohamedsamir1495/Duck-Duck-Go-Tested-Version
/Duck Duck Go Tested Version/app/src/main/cpp/third-party/bloom_cpp/src/BloomFilter.cpp
UTF-8
6,548
2.765625
3
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2018 DuckDuckGo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cstdio> #include <fstream> #include <cmath> #include <assert.h> #include "BloomFilter.hpp" // Forward declarations static size_t calculateHashRounds(size_t size, size_t maxItems); static unsigned int djb2Hash(string text); static unsigned int sdbmHash(string text); static unsigned int doubleHash(unsigned int hash1, unsigned int hash2, unsigned int round); static void writeVectorToStream(vector<bool> &bloomVector, BinaryOutputStream &out); static BlockType pack(const vector<bool> &filter, size_t block, size_t bits); static vector<bool> readVectorFromFile(const string &path); static vector<bool> readVectorFromStream(BinaryInputStream &in); static void unpackIntoVector(vector<bool> &bloomVector, size_t offset, size_t bitsInThisBlock, BinaryInputStream &in); // Implementation BloomFilter::BloomFilter(size_t maxItems, double targetProbability) { auto size = (size_t) ceil((maxItems * log(targetProbability)) / log(1.0 / (pow(2.0, log(2.0))))); bloomVector = vector<bool>(size); hashRounds = calculateHashRounds(size, maxItems); } BloomFilter::BloomFilter(string importFilePath, size_t maxItems) { bloomVector = readVectorFromFile(importFilePath); hashRounds = calculateHashRounds(bloomVector.size(), maxItems); } BloomFilter::BloomFilter(BinaryInputStream &in, size_t maxItems) { bloomVector = readVectorFromStream(in); hashRounds = calculateHashRounds(bloomVector.size(), maxItems); } static size_t calculateHashRounds(size_t size, size_t maxItems) { return (size_t) round(log(2.0) * size / maxItems); } void BloomFilter::add(string element) { unsigned int hash1 = djb2Hash(element); unsigned int hash2 = sdbmHash(element); for (int i = 0; i < hashRounds; i++) { unsigned int hash = doubleHash(hash1, hash2, i); size_t index = hash % bloomVector.size(); bloomVector[index] = true; } } bool BloomFilter::contains(string element) { unsigned int hash1 = djb2Hash(element); unsigned int hash2 = sdbmHash(element); for (int i = 0; i < hashRounds; i++) { unsigned int hash = doubleHash(hash1, hash2, i); size_t index = hash % bloomVector.size(); if (!bloomVector[index]) { return false; } } return true; } static unsigned int djb2Hash(string text) { unsigned int hash = 5381; for (char &iterator : text) { hash = ((hash << 5) + hash) + iterator; } return hash; } static unsigned int sdbmHash(string text) { unsigned int hash = 0; for (char &iterator : text) { hash = iterator + ((hash << 6) + (hash << 16) - hash); } return hash; } static unsigned int doubleHash(unsigned int hash1, unsigned int hash2, unsigned int round) { switch (round) { case 0: return hash1; case 1: return hash2; default: return (hash1 + (round * hash2) + (round ^ 2)); } } void BloomFilter::writeToFile(string path) { basic_ofstream<BlockType> out(path.c_str(), ofstream::binary); writeVectorToStream(bloomVector, out); } void BloomFilter::writeToStream(BinaryOutputStream &out) { writeVectorToStream(bloomVector, out); } static void writeVectorToStream(vector<bool> &bloomVector, BinaryOutputStream &out) { const size_t elements = bloomVector.size(); out.put(((elements & 0x000000ff) >> 0)); out.put(((elements & 0x0000ff00) >> 8)); out.put(((elements & 0x00ff0000) >> 16)); out.put(((elements & 0xff000000) >> 24)); const size_t bitsPerBlock = sizeof(BlockType) * 8; for (size_t i = 0; i < elements / bitsPerBlock; i++) { const BlockType buffer = pack(bloomVector, i, bitsPerBlock); out.put(buffer); } const size_t bitsInLastBlock = elements % bitsPerBlock; if (bitsInLastBlock > 0) { const size_t lastBlock = elements / bitsPerBlock; const BlockType buffer = pack(bloomVector, lastBlock, bitsInLastBlock); out.put(buffer); } } static BlockType pack(const vector<bool> &filter, size_t block, size_t bits) { const size_t sizeOfTInBits = sizeof(BlockType) * 8; assert(bits <= sizeOfTInBits); BlockType buffer = 0; for (int j = 0; j < bits; ++j) { const size_t offset = (block * sizeOfTInBits) + j; const BlockType bit = filter[offset] << j; buffer |= bit; } return buffer; } static vector<bool> readVectorFromFile(const string &path) { basic_ifstream<BlockType> inFile(path, ifstream::binary); return readVectorFromStream(inFile); } static vector<bool> readVectorFromStream(BinaryInputStream &in) { const size_t component1 = in.get() << 0; const size_t component2 = in.get() << 8; const size_t component3 = in.get() << 16; const size_t component4 = in.get() << 24; const size_t elementCount = component1 + component2 + component3 + component4; vector<bool> bloomVector(elementCount); const size_t bitsPerBlock = sizeof(BlockType) * 8; const size_t fullBlocks = elementCount / bitsPerBlock; for (int i = 0; i < fullBlocks; ++i) { const size_t offset = i * bitsPerBlock; unpackIntoVector(bloomVector, offset, bitsPerBlock, in); } const size_t bitsInLastBlock = elementCount % bitsPerBlock; if (bitsInLastBlock > 0) { const size_t offset = bitsPerBlock * fullBlocks; unpackIntoVector(bloomVector, offset, bitsInLastBlock, in); } return bloomVector; } static void unpackIntoVector(vector<bool> &bloomVector, size_t offset, size_t bitsInThisBlock, BinaryInputStream &in) { const BlockType block = in.get(); for (int j = 0; j < bitsInThisBlock; j++) { const BlockType mask = 1 << j; bloomVector[offset + j] = (block & mask) != 0; } }
true
3d454bda7766b9afb9679e3d3799c800ab4c8aaf
C++
jacobfrank96/muffinman
/lab3/FiveCardDraw.cpp
UTF-8
1,942
2.859375
3
[]
no_license
#include "stdafx.h" #include "deck.h" #include "functions.h" #include "game.h" #include "FiveCardDraw.h" #include <string> #include <vector> #include <fstream> #include <sstream> #include <iostream> #include <algorithm> #include <random> #include <chrono> #include <memory> #include "stdafx.h" #include "deck.h" #include "functions.h" #include "game.h" #include "FiveCardDraw.h" #include <string> #include <vector> #include <fstream> #include <sstream> #include <iostream> #include <algorithm> #include <random> #include <chrono> #include <memory> using namespace std; FiveCardDraw::FiveCardDraw() : dealer(0){ for (int i = 2; i <= 14; i++) { //variable not accessible HELP CUCKIER for (int j = 0; j < 4; j++) { Deck d; card_rank c_rank = getRank(i); card_suit c_suit = getSuit(j); Card c = Card(c_suit, c_rank); d.add_card(c); } } } int FiveCardDraw::before_turn(Player & p) { //add implementation int cardsToDiscard = 0; cout << "player: " << p.name << "wins: " << p.handsWon << "losses: " << p.handsLost << endl; cout <<p.hand << endl; bool validResponse = false; while (!validResponse) { cout << "How many cards would you like to discard?" << endl; string input; cin >> input; if (0 <= stoi(input) && stoi(input)< 5) { validResponse= true; cardsToDiscard = stoi(input); } else { cout << "enter a number from 0 to 5" << endl; } } while (cardsToDiscard > 0) { cout << "Which card index would you like to discard?" << endl; cout << p.hand << endl; string discard; cin >> discard; try { Card toDiscard = p.hand[stoi(discard)]; discardDeck.add_card(toDiscard); p.hand.remove_card(stoi(discard)); cardsToDiscard--; } catch (int e) { switch (e) { case out_of_bounds: std::cout << "out of bounds!" << std::endl; break; default: std::cout << "try again" << std::endl; } } catch (...) { cout << "try again" << endl; } } }
true
4df1e106abb81268592fae23dd01a7c2aee25513
C++
tgibbons95/Source
/DataStructure/test/test_Stack.cpp
UTF-8
423
3.265625
3
[]
no_license
#include "gtest/gtest.h" #include "DataStructure/Stack.h" TEST(Stack, PushPop) { const int TEST_ARRAY_LENGTH = 20; int testArray[TEST_ARRAY_LENGTH] = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20 }; DataStructureT::Stack<int> stack; for (int i = 0; i < TEST_ARRAY_LENGTH; i++) { stack.Push(testArray[i]); } for(int i = TEST_ARRAY_LENGTH - 1; i >= 0; i--) { EXPECT_EQ(testArray[i], stack.Pop()); } }
true
445eee847946d6b0cc3eecae0de88e135ac5fb08
C++
wangyunfeifeifei/AlgorithmNote
/ch3/pat_b1006.cpp
UTF-8
267
2.546875
3
[]
no_license
#include<stdio.h> int main() { int n; scanf("%d", &n); int b=n/100; int s=(n/10)%10; int x=n%10; for(int i=0;i<b;i++)printf("B"); for(int i=0;i<s;i++)printf("S"); for(int i=1;i<=x;i++)printf("%d",i); printf("\n"); return 0; }
true
4f719937070f8e4a74a08b65f11cd741c571e0e4
C++
AyushP90/dalhurst_valley
/Dalhurst Valley/Dalhurst Valley/Menu2.cpp
UTF-8
2,986
2.890625
3
[]
no_license
#include "Menu2.h" Menu2::Menu2(float x, float y, float height, char *menu1, char *menu2) { soundBufferSwing.loadFromFile("assets/sounds/sword_swing.wav"); soundSwing.setBuffer(soundBufferSwing); soundBufferHit.loadFromFile("assets/sounds/sword_metal_hit.wav"); soundHit.setBuffer(soundBufferHit); soundSwing.setVolume(3); soundHit.setVolume(3); texSelect.loadFromFile("assets/images/select.png"); sprSelect.setTexture(texSelect); fontSelected.loadFromFile("assets/fonts/Sansation_Bold_Italic.ttf"); font.loadFromFile("assets/fonts/Sansation_Bold.ttf"); txtList[0].setFont(fontSelected); txtList[0].setString(menu1); txtList[0].setCharacterSize(40); txtList[0].setColor(sf::Color(210, 210, 210)); txtList[0].setPosition(sf::Vector2f(x, y + height / (MAX_NUM_OF_ITEMS + 1) * 1)); txtList[1].setFont(font); txtList[1].setString(menu2); txtList[1].setCharacterSize(70); txtList[1].setColor(sf::Color::White); txtList[1].setPosition(sf::Vector2f(x, y + height / (MAX_NUM_OF_ITEMS + 1) * 2 - 20)); sprSelect.setPosition(sf::Vector2f(x - 35, y + height / (MAX_NUM_OF_ITEMS + 1) * 2 - 12)); selectedItemIndex = 1; } void Menu2::draw(sf::RenderWindow &window) { window.draw(sprSelect); for (int i = 0; i < MAX_NUM_OF_ITEMS; i++) { window.draw(txtList[i]); } } void Menu2::MoveUp() { if (selectedItemIndex - 1 >= 0) { soundSwing.play(); sf::Vector2f tempLocation; tempLocation = txtList[selectedItemIndex].getPosition(); txtList[selectedItemIndex].setPosition(tempLocation.x, tempLocation.y + 20); txtList[selectedItemIndex].setColor(sf::Color(210, 210, 210)); txtList[selectedItemIndex].setFont(font); txtList[selectedItemIndex].setCharacterSize(40); selectedItemIndex--; txtList[selectedItemIndex].setColor(sf::Color::White); txtList[selectedItemIndex].setCharacterSize(70); txtList[selectedItemIndex].setFont(fontSelected); tempLocation = txtList[selectedItemIndex].getPosition(); txtList[selectedItemIndex].setPosition(tempLocation.x, tempLocation.y - 20); sprSelect.setPosition(tempLocation.x - 35, tempLocation.y - 12); } } void Menu2::MoveDown() { if (selectedItemIndex + 1 < MAX_NUM_OF_ITEMS) { soundSwing.play(); sf::Vector2f tempLocation; tempLocation = txtList[selectedItemIndex].getPosition(); txtList[selectedItemIndex].setPosition(tempLocation.x, tempLocation.y + 20); txtList[selectedItemIndex].setColor(sf::Color(210, 210, 210)); txtList[selectedItemIndex].setFont(font); txtList[selectedItemIndex].setCharacterSize(40); selectedItemIndex++; txtList[selectedItemIndex].setColor(sf::Color::White); txtList[selectedItemIndex].setCharacterSize(70); txtList[selectedItemIndex].setFont(fontSelected); tempLocation = txtList[selectedItemIndex].getPosition(); txtList[selectedItemIndex].setPosition(tempLocation.x, tempLocation.y - 20); sprSelect.setPosition(tempLocation.x - 35, tempLocation.y - 12); } } int Menu2::getPressedItem() { soundHit.play(); return selectedItemIndex; }
true
a38eb5b211207e2abd6ccc11704206b96ba5494c
C++
atrimuhammad/Assignment
/CSE 102/loop assignment 12.cpp
UTF-8
729
2.796875
3
[]
no_license
/** Tanvir Hasan Uap, 31st Batch email: tanvir002700@gmail.com **/ #include<stdio.h> int main() { printf("enter the line num that contain maximum blanks:"); int b; scanf("%d",&b); int a=b-1; for(int t=1;t<=(b*2-1);t++) { printf("*"); } printf("\n"); for(int i=1;i<=a;i++) { for(int j=1;j<=(a+1)-i;j++) { printf("*"); } for(int k=1;k<=i*2-1;k++) { printf(" "); } for(int l=1;l<=(a+1)-i;l++) { printf("*"); } printf("\n"); } for(int m=1;m<=(a-1);m++) { for(int n=1;n<=m+1;n++) { printf("*"); } for(int p=1;p<=(a*2-1)-2*m;p++) { printf(" "); } for(int q=1;q<=m+1;q++) { printf("*"); } printf("\n"); } for(int r=1;r<=(b*2-1);r++) { printf("*"); } return 0; }
true
d722b257f21476ae723b98d6f4ce864b1e1e37d6
C++
olnayoung/coding
/2751.cpp
UTF-8
896
3.125
3
[]
no_license
#include<cstdio> int N; int map[1000000], ans[1000000]; int merge(int left, int mid, int right) { int i, j, k; i = left; j = mid + 1; k = left; while ((i <= mid) && (j <= right)) { if (map[i] <= map[j]) { ans[k++] = map[i++]; } else { ans[k++] = map[j++]; } } if (i > mid) { for (int t = j; t <= right; t++) { ans[k++] = map[t]; } } else { for (int t = i; t <= mid; t++) { ans[k++] = map[t]; } } for (int t = left; t <= right; t++) { map[t] = ans[t]; } return 0; } int MergeSort(int left, int right) { int mid; if (left < right) { mid = (left + right) / 2; MergeSort(left, mid); MergeSort(mid + 1, right); merge(left, mid, right); } return 0; } int main() { scanf("%d", &N); for (int n = 0; n < N; n++) { scanf("%d", &map[n]); } MergeSort(0, N - 1); for (int n = 0; n < N; n++) { printf("%d\n", map[n]); } return 0; }
true
fb14128fc6e896433cabee4efffe1bb2ce3826f8
C++
melival/cppjun
/cpp/test_task_cpp/TZinfo.cpp
UTF-8
535
2.65625
3
[]
no_license
#include "TZinfo.hpp" int TZinfo::load_base(std::string fname){ std::string tzname; int tzhours = 0; int tzmins = 0; std::ifstream tz_file(fname); if (!tz_file.is_open()){ return -1; }else { while (!tz_file.eof()){ tz_file >> tzname >> tzhours >> tzmins; if ((tzname == "")||(tzname == "\n")) continue; tzmins = tzhours * 60 + tzmins * ((tzhours < 0)?-1:1); time_zones[tzname] = tzmins * 60; //in seconds offset count++; } tz_file.close(); } return count; }
true
c6f2e705bf5692246749d9b18e6ac84fea2bec68
C++
arangodb/arangodb
/3rdParty/boost/1.78.0/boost/dll/detail/demangling/demangle_symbol.hpp
UTF-8
2,222
2.703125
3
[ "BSL-1.0", "Apache-2.0", "BSD-3-Clause", "ICU", "Zlib", "GPL-1.0-or-later", "OpenSSL", "ISC", "LicenseRef-scancode-gutenberg-2020", "MIT", "GPL-2.0-only", "CC0-1.0", "LicenseRef-scancode-autoconf-simple-exception", "LicenseRef-scancode-pcre", "Bison-exception-2.2", "LicenseRef-scancode...
permissive
// Copyright 2015 Klemens Morgenstern // // This file provides a demangling for function names, i.e. entry points of a dll. // // Distributed under the Boost Software License, Version 1.0. // See http://www.boost.org/LICENSE_1_0.txt #ifndef BOOST_DLL_DEMANGLE_SYMBOL_HPP_ #define BOOST_DLL_DEMANGLE_SYMBOL_HPP_ #include <boost/dll/config.hpp> #include <string> #include <algorithm> #include <memory> #if defined(_MSC_VER) // MSVC, Clang-cl, and ICC on Windows namespace boost { namespace dll { namespace detail { typedef void * (__cdecl * allocation_function)(std::size_t); typedef void (__cdecl * free_function)(void *); extern "C" char* __unDName( char* outputString, const char* name, int maxStringLength, // Note, COMMA is leading following optional arguments allocation_function pAlloc, free_function pFree, unsigned short disableFlags ); inline std::string demangle_symbol(const char *mangled_name) { allocation_function alloc = [](std::size_t size){return static_cast<void*>(new char[size]);}; free_function free_f = [](void* p){delete [] static_cast<char*>(p);}; std::unique_ptr<char> name { __unDName( nullptr, mangled_name, 0, alloc, free_f, static_cast<unsigned short>(0))}; return std::string(name.get()); } inline std::string demangle_symbol(const std::string& mangled_name) { return demangle_symbol(mangled_name.c_str()); } }}} #else #include <boost/core/demangle.hpp> namespace boost { namespace dll { namespace detail { inline std::string demangle_symbol(const char *mangled_name) { if (*mangled_name == '_') { //because it start's with an underline _ auto dm = boost::core::demangle(mangled_name); if (!dm.empty()) return dm; else return (mangled_name); } //could not demangled return ""; } //for my personal convenience inline std::string demangle_symbol(const std::string& mangled_name) { return demangle_symbol(mangled_name.c_str()); } } namespace experimental { using ::boost::dll::detail::demangle_symbol; } }} #endif #endif /* BOOST_DEMANGLE_HPP_ */
true
a52a2485e209faced7fbb0c713e072a66eeb4e4d
C++
thejosess/Informatica-UGR
/1º AÑO/1ºCuatrimestre/FP/Practicas/Practica 5 Matrices/ejercicio 2.cpp
UTF-8
1,000
3.15625
3
[]
no_license
#include <iostream> using namespace std ; int main (){ const int MAX_FIL = 100, MAX_COL = 100; bool colrep , colunica; int i, j, k , cu , FilEncontrado, ColEncontrado; double m[MAX_FIL][MAX_COL]; int f, c; cu=0; do{ cout << "Introducir el numero de filas: "; cin >> f; }while ( (f<1) || (f>MAX_FIL) ); do{ cout << "Introducir el numero de columnas: "; cin >>c; }while ( (c<1) || (c>MAX_COL) ); for(i=0;i<f;i++){ for(j=0;j<c;j++){ cout<<"Introduce el "<<j+1<<" valor de la "<<i+1<<" fila: "; cin>>m[i][j]; } } for(j=0;j<c;j++) { colunica=true; for(k=0;k<c;k++) { colrep=true; for(i=0;i<f;i++) { if(m[i][j]!=m[i][k]) { colrep=false; } if(colrep==true&&j!=k){ colunica=false; } } } if(colunica==true){ cu++; } } cout<<"El numero de columnas unicas es: "<<cu; }
true
95b5197cef478761a74f423407f0446c94ba56ac
C++
ShahidAkhtar777/HACKTOBERFEST2020
/C++/NewtonRapshon/newtonRaphson.cpp
UTF-8
833
2.96875
3
[]
no_license
#include <stdio.h> #include <conio.h> #include <math.h> #define f(x) (5*x*x*x*x*x-3*x*x-100) #define g(x) (25*x*x*x*x-6*x) #define E 0.00001 int main() { float ecal,xi,x0,count; printf("\n************************Newton Raphson Method**********************************\n"); printf("\n Enter initial value x0 = "); scanf("%f",&x0); if(g(x0)==0) { printf("\n Sorry the first derivative is zero, enter another initial value. \n"); } else { do{ xi = x0 -(f(x0)/g(x0)); ecal = fabs((xi-x0)/xi); x0 = xi; printf("\n x0=%f \t f(x0)=%f \t g(x0)=%f \t xi=%f \t ecal=%f \n",x0,f(x0),g(x0),xi,ecal); count += 1; }while(E<ecal && count<=12); if(count > 12) { printf("\n iterative more than 12. There is no solution. \n"); } printf("\n Root is %f",x0); } return 0; }
true
0dd3a897fcc592fb2b43b6b281cbf63c31b6042c
C++
bkmiecik12/List1
/OtherNumber.h
UTF-8
444
2.609375
3
[]
no_license
#include <iostream> #include "RealNumber.h" using namespace std; class OtherNumber { public: RealNumber number1; // OtherNumber(RealNumber); ~OtherNumber(); OtherNumber add1(OtherNumber&);//dodawanie OtherNumber multiply1(OtherNumber&);//mnozenie //void separate(); //kropka [.] oddziela void display1(); //wyswietl liczbe //void alignNumbers(RealNumber&); //wyrownanie dlugosci //void alignNumbers1(int,int); void reverse(); };
true
d1f8988124b07be350e5770d56e8aaefde9ebe2b
C++
misakamijou/AirCombatGameDemo
/huge_plane/huge_plane/diablo.cpp
GB18030
9,233
2.515625
3
[]
no_license
#include"definition.h" #include<math.h> #include<cmath> #define pi 3.14159265358979323846 Boss1::Boss1() { int hitbox_[2] = { 360,360 }; x = 1800; y = 360; hitbox[0] = hitbox_[0]; hitbox[1] = hitbox_[1]; hp = 0; speed = 5; //лٶ loadimage(&img, _T("IMAGE2"), _T("Boss1"), 480, 480, true); loadimage(&maskbitmap, _T("IMAGE2"), _T("Mask_Boss1"), 480, 480, true); loadimage(&BoomImg, _T("IMAGE"), _T("Boom"), 240, 240, true); loadimage(&Mask_BoomImg, _T("IMAGE"), _T("Mask_Boom"), 240, 240, true); loadimage(&Atkedimg, _T("IMAGE2"), _T("Boss1Atked"), 480, 480, true); loadimage(&boom1, _T("IMAGE2"), _T("BossBoom"), 720, 720, true); loadimage(&boom2, _T("IMAGE2"), _T("BossBoom2"), 720, 720, true); loadimage(&mask_boom1, _T("IMAGE2"), _T("Mask_BossBoom"), 720, 720, true); loadimage(&mask_boom2, _T("IMAGE2"), _T("Mask_BossBoom2"), 720, 720, true); } void Boss1::draw(MyPlane& target) { if (hp > 0) { DWORD now = GetTickCount() - show_time; //жڵstate if (now < 5000) state = 0; else if (now < 6000 && now > 5000) state = 3; else if (now < 12000 && now > 6000) state = 4; else if (now < 16000 && now > 12000) state = 2; else if (now < 23000 && now > 16000) state = 1; else if (now < 24000 && now > 23000) state = 5; else if (now < 25000 && now > 24000) state = 6; //ʵʲ switch(state) {case 0: //ҡīdz move(); putimage(x - 270, y - 200, &maskbitmap, SRCAND);//bossĿ putimage(x - 270, y - 200, &img, SRCPAINT); i++; break; case 1: //ǹޱ shoot_six_direction(); putimage(x - 270, y - 200, &maskbitmap, SRCAND);//bossĿ putimage(x - 270, y - 200, &img, SRCPAINT); for (int j = 0; j < MAX_BOSS_BULLET_1; j++) //ӵ1 { if (bul1[j].hp > 0) { bul1[j].draw(); bul1[j].col_det(target); } } for (int j = 0; j < MAX_BOSS_BULLET_3; j++) //ӵ3 { if (bul3[j].hp > 0) { bul3[j].draw(); bul3[j].col_det(target); } } i++; break; case 2: //׼ơ˫ǹ̫ shoot_to_where_you_are(target); putimage(x - 270, y - 200, &maskbitmap, SRCAND);//bossĿ putimage(x - 270, y - 200, &img, SRCPAINT); for (int j = 0; j < MAX_BOSS_BULLET_1; j++) //ӵ1 { if (bul1[j].hp > 0) { bul1[j].draw(); bul1[j].col_det(target); } } for (int j = 0; j < MAX_BOSS_BULLET_3; j++) //ӵ3 { if (bul3[j].hp > 0) { bul3[j].draw(); bul3[j].col_det(target); } } i++; break; case 3: //ȫ⡢û˺ putimage(x - 270, y - 200, &maskbitmap, SRCAND);//bossĿ putimage(x - 270, y - 200, &img, SRCPAINT); pre_shoot_focking_lazer(target); i++; break; case 4: //ȫ⡢ת putimage(x - 270, y - 200, &maskbitmap, SRCAND);//bossĿ putimage(x - 270, y - 200, &img, SRCPAINT); shoot_focking_lazer(target); i++; break; case 5: //һѭ putimage(x - 270, y - 200, &maskbitmap, SRCAND);//bossĿ putimage(x - 270, y - 200, &img, SRCPAINT); for (int j = 0; j < MAX_BOSS_BULLET_1; j++) //ӵ1 { if (bul1[j].hp > 0) { bul1[j].draw(); bul1[j].col_det(target); } } for (int j = 0; j < MAX_BOSS_BULLET_3; j++) //ӵ3 { if (bul3[j].hp > 0) { bul3[j].draw(); bul3[j].col_det(target); } } break; case 6: //λӵ putimage(x - 270, y - 200, &maskbitmap, SRCAND);//bossĿ putimage(x - 270, y - 200, &img, SRCPAINT); for (int j = 0; j < MAX_BOSS_BULLET_1; j++) //ӵ1 { bul1[j].hp = 0; } for (int j = 0; j < MAX_BOSS_BULLET_3; j++) //ӵ3 { bul3[j].hp = 0; } show_time = GetTickCount() - 5000; break; } } else if (hp <= 0 && i != 0) { DWORD now = GetTickCount() - dead_time; if (now < 1500) state = 1; else if (now < 3000) state = 2; else state = 3; switch (state) { case 1://ը putimage(x - 405, y - 300, &mask_boom1, SRCAND); putimage(x - 405, y - 300, &boom1, SRCPAINT); break; case 2://Сը putimage(x - 405, y - 300, &mask_boom2, SRCAND); putimage(x - 405, y - 300, &boom2, SRCPAINT); break; } } } void Boss1::move() { if (hp > 0 && x >= 910) x -= speed; } void Boss1::move_to_left() { if (hp > 0 && x >= 683) x -= speed; } void Boss1::move_to_right() { if (x <= 910) x += speed; } void Boss1::shoot_six_direction() { if (hp > 0) { if (i % 20 == 0) { for (int p = 0; p < 6; p++) { for (int j = 0; j < MAX_BOSS_BULLET_1; j++) { if (bul1[j].hp == 0) { bul1[j].hp = 1; //ӵ bul1[j].x = x; bul1[j].y = y; bul1[j].direction[0] = sin(pi / 3 * (i / 20 + p + i / 20 / 10.0)); bul1[j].direction[1] = cos(pi / 3 * (i / 20 + p + i / 20 / 10.0)); break; } } } } } } void Boss1::shoot_to_where_you_are(MyPlane& target) { if (i % 10 == 0) { for (int p = 0; p < 2; p++) { for (int k = 0; k < MAX_BOSS_BULLET_3; k++) { if (bul3[k].hp == 0) { bul3[k].hp = 1; bul3[k].x = x; bul3[k].y = y - 50 + p * 100; bul3[k].direction[0] = target.x - bul3[k].x; bul3[k].direction[1] = target.y - bul3[k].y; double bili = bul3[k].speed / sqrt(pow(bul3[k].direction[0] - x, 2) + pow(bul3[k].direction[1] - y, 2)); bul3[k].direction[0] *= bili; bul3[k].direction[1] *= bili; break; } } } } } void Boss1::pre_shoot_focking_lazer(MyPlane& target) { for (int j = 0; j < MAX_BOSS_LAZER; j++) { lazer[j].x = x; lazer[j].y = y; lazer[j].direction = (2 * pi / MAX_BOSS_LAZER * j) + i / 50.0; lazer[j].draw(); } } void Boss1::shoot_focking_lazer(MyPlane& target) { { for (int j = 0; j < MAX_BOSS_LAZER; j++) { lazer[j].x = x; lazer[j].y = y; lazer[j].direction = (2 * pi / MAX_BOSS_LAZER * j) + i / 50.0; lazer[j].draw2(); lazer[j].col_det(target); } } } void InitBoss1(Boss1& boss) { if (boss.i == 0 && boss.hp == 0 ) { boss.hp = BOSS_LIVE; //boss boss.show_time = GetTickCount(); boss.state = 0; } } void Boss1::col_det(MyBullet1* bul) { if (hp > 0) for (int i = 0; i < MAXBULLET; i++) { if (hitbox[0] / 2 + bul[i].hitbox[0] / 2 > abs(x - bul[i].x) && hitbox[1] / 2 + bul[i].hitbox[1] / 2 > abs(y - bul[i].y) && bul[i].hp > 0) { hp--; putimage(x - 270, y - 200, &maskbitmap, SRCAND); putimage(x - 270, y - 200, &Atkedimg, SRCPAINT); if (hp <= 0) dead_time = GetTickCount(); bul[i].hp = 0; } } } //bossӵ1 BossBullet1::BossBullet1() { x = 0; y = 0; hp = 0; hitbox[0] = 10; hitbox[1] = 10; speed = 6; //ӵٶ loadimage(&img, _T("IMAGE2"), _T("BossBullet3"), 200, 200); loadimage(&maskbitmap, _T("IMAGE2"), _T("Mask_BossBullet3"),200, 200); } void BossBullet1::draw() { move(); fillcircle(x, y, 5); //ӵһ putimage(x - 110, y - 90, &maskbitmap, SRCAND); putimage(x - 110, y - 90, &img, SRCPAINT); } void BossBullet1::move() { x += int(speed * direction[0]); y += int(speed * direction[1]); } void BossBullet1::col_det(MyPlane& target) { if (target.hp > 0 && target.hitted_time == 0 && hitbox[0] / 2 + target.hitbox[0] / 2 > abs(x - target.x) && hitbox[1] / 2 + target.hitbox[1] / 2 > abs(y - target.y)) { target.hp -= 2; target.hitted_time = GetTickCount(); } } //bossӵ2 BossBullet2::BossBullet2() { x = 0; y = 0; hp = 0; hitbox[0] = 10; hitbox[1] = 10; speed = 5; //ӵٶ } void BossBullet2::draw() { fillcircle(x, y, 5); } //Bossӵ3 BossBullet3::BossBullet3() { x = 0; y = 0; hp = 0; hitbox[0] = 10; hitbox[1] = 10; speed = 6; //ӵٶ loadimage(&img, _T("IMAGE2"), _T("BossBullet2"), 200, 200); loadimage(&maskbitmap, _T("IMAGE2"), _T("Mask_BossBullet2"), 200, 200); } void BossBullet3::move() { x += int(speed * direction[0]); y += int(speed * direction[1]); } void BossBullet3::draw() { if (hp > 0) { move(); fillrectangle(x - hitbox[0] / 2, y - hitbox[1] / 2, x + hitbox[0] / 2, y + hitbox[1] / 2); putimage(x - 110, y - 100, &maskbitmap, SRCAND); putimage(x - 100, y - 100, &img, SRCPAINT); } } void BossBullet3::col_det(MyPlane& target) { if (target.hp > 0 && target.hitted_time == 0 && hitbox[0] / 2 + target.hitbox[0] / 2 > abs(x - target.x) && hitbox[1] / 2 + target.hitbox[1] / 2 > abs(y - target.y)) { target.hp--; target.hitted_time = GetTickCount(); } } // void Lazer::draw() { setlinecolor(RED); line(x, y, int(x + 2000 * cos(direction)), int(y + 2000 * sin(direction))); setlinecolor(WHITE); } void Lazer::draw2() //˺ļdraw@ { setlinecolor(YELLOW); line(x, y, int(x + 2000 * cos(direction)), int(y + 2000 * sin(direction))); setlinecolor(WHITE); } void Lazer::col_det(MyPlane& target) { double l = sqrt(pow(target.x - x, 2) + pow(target.y - y, 2)); double theta = direction - atan(double(target.y - y) / double(target.x - x)); if (target.hp > 0 && target.hitted_time == 0 && abs(l * sin(theta)) < hit_distance) { target.hp--; target.hitted_time = GetTickCount(); } }
true
2ca899512d78706106b648d915c4a86333b43506
C++
gagan86nagpal/SPOJ-200
/CATM/main.cpp
UTF-8
2,018
2.671875
3
[]
no_license
#include <iostream> #include <cmath> #include <queue> using namespace std; int mouse[101][101],cat1[101][101],cat2[101][101]; int vis[101][101]; queue < pair <int, pair <int,int > > > q; void bfs(int x[101][101],int sx,int sy,int n,int m) { int i,j; for(i=1;i<=n;i++) for(j=1;j<=m;j++) vis[i][j]=0; while(!q.empty()) q.pop(); vis[sx][sy]=1; q.push({0,{sx,sy}}); x[sx][sy]=0; while(!q.empty()) { pair <int,pair <int,int> > p= q.front(); q.pop(); int px = p.second.first; int py =p.second.second; int t = p.first; for(i=-1;i<=1;i++) { for(j=-1;j<=1;j++) { if( px+i<1 || px+i>n || py+j<1 || py+j>m || abs(i) +abs(j)!=1 || vis[px+i][py+j]==1 ) continue; x[px+i][py+j]=t+1; vis[px+i][py+j]=1; q.push({t+1,{px+i,py+j}}); } } } } void print(int x[101][101],int n,int m) { int i,j; for(i=1;i<=n;i++) { for(j=1;j<=m;j++) cout<<x[i][j]<<" "; cout<<"\n"; } cout<<"\n"; } bool check(int n,int m) { int i; for(i=1;i<=m;i++) if(mouse[1][i]<min(cat1[1][i],cat2[1][i])) return true; for(i=1;i<=m;i++) if(mouse[n][i]<min(cat1[n][i],cat2[n][i])) return true; for(i=1;i<=n;i++) if(mouse[i][1]<min(cat1[i][1],cat2[i][1])) return true; for(i=1;i<=n;i++) if(mouse[i][m]<min(cat1[i][m],cat2[i][m])) return true; return false; } int main() { int n,m; cin>>n>>m; int t; cin>>t; while(t--) { int ax,ay,bx,by,cx,cy; cin>>ax>>ay>>bx>>by>>cx>>cy; bfs(mouse,ax,ay,n,m); bfs(cat1,bx,by,n,m); bfs(cat2,cx,cy,n,m); bool ans = check(n,m); cout<<(ans?"YES":"NO")<<"\n"; // print(mouse,n,m); // print(cat1,n,m); // print(cat2,n,m); } return 0; }
true
87b88f4871a7e8bc0dc56c3d772bafc1a5c12f4d
C++
truong02bp/C-
/ctdl/bai52.cpp
UTF-8
731
2.71875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; string s; vector<int> cnt; int temp; bool result() { int size = s.length(); if (size%2==0) { if (temp > size/2) return false; return true; } else if (temp > size/2+1) return false; return true; } int main() { int t; cin >> t; while(t--) { cnt.assign(100,0); temp=0; cin >> s; for (int i=0;i<s.length();i++) cnt[s[i]-'0']++; for (int i=0;i<s.length();i++) temp = max(temp,cnt[s[i]-'0']); if (result()) cout << 1 << endl; else cout << -1 << endl; } return 0; }
true
93451c969e330be8905f6f01ad9b2fbc56047ae2
C++
AlMamun-CSE/competitive_programming
/Codeforces/1579C - Ticks/c.cpp
UTF-8
2,794
2.65625
3
[]
no_license
#include <algorithm> #include <iostream> #include <iterator> #include <numeric> #include <sstream> #include <fstream> #include <cassert> #include <climits> #include <cstdlib> #include <cstring> #include <bitset> #include <string> #include <cstdio> #include <vector> #include <cmath> #include <queue> #include <deque> #include <stack> #include <list> #include <map> #include <set> using namespace std; ////////////// Prewritten code follows. Look down for solution. //////////////// #define foreach(x, v) for (typeof (v).begin() x=(v).begin(); x !=(v).end(); ++x) #define For(i, a, b) for (int i=(a); i<(b); ++i) #define D(x) cerr << #x " is " << (x) << endl const double EPS = 1e-9; int cmp(double x, double y = 0, double tol = EPS) { return (x <= y + tol) ? (x + tol < y) ? -1 : 0 : 1; } ////////////////////////// Solution starts below. ////////////////////////////// bool black[25][25]; char board[25][25]; int rows, cols; bool inside(int r, int c) { return 0 <= r and r < rows and 0 <= c and c < cols; } int max_length(int r, int c) { assert(board[r][c] == '*'); int length = 0; int c1, c2; c1 = c; c2 = c; while (true) { r--; c1--; c2++; if (!inside(r, c1) or !inside(r, c2)) break; if (board[r][c1] != '*' or board[r][c2] != '*') break; length++; } return length; } void paint(int r, int c) { assert(board[r][c] == '*'); black[r][c] = true; int c1, c2; c1 = c; c2 = c; while (true) { r--; c1--; c2++; if (!inside(r, c1) or !inside(r, c2)) break; if (board[r][c1] != '*' or board[r][c2] != '*') break; black[r][c1] = true; black[r][c2] = true; } } void solve() { int k; cin >> rows >> cols >> k; for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { cin >> board[r][c]; black[r][c] = false; //cout << board[r][c]; } //cout << endl; } for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { if (board[r][c] == '.') continue; int d = max_length(r, c); if (d >= k) { //printf("painting at (%d, %d) length=%d\n", r, c, d); paint(r, c); } } } bool good = true; for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { if (board[r][c] == '*' and !black[r][c]) { good = false; break; } } } cout << (good ? "YES" : "NO") << endl; } int main(){ #ifndef LOCAL ios::sync_with_stdio(false); cin.tie(nullptr); #endif int t; cin >> t; while (t--) { solve(); } return 0; }
true
5093324209fd0b7a3ccf06fcadae520eb1d92ca1
C++
PSDent/DX11_2D-Game-Engine
/DX2DGame/Timer.cpp
UTF-8
1,266
2.78125
3
[]
no_license
#include "Timer.h" #include <Windows.h> Timer::Timer() { } Timer::~Timer() { } void Timer::Initialize() { QueryPerformanceFrequency((LARGE_INTEGER*)&m_frequency); if (m_frequency == 0) return; m_ticksPerMs = (float)(m_frequency / 1000); QueryPerformanceCounter((LARGE_INTEGER*)&m_startTime); m_timeStoragy = new std::map<int, float>(); } void Timer::Frame() { INT64 currentTime; float timeDiffrence; QueryPerformanceCounter((LARGE_INTEGER*)&currentTime); timeDiffrence = (float)(currentTime - m_startTime); m_frameTime = timeDiffrence / m_ticksPerMs; m_startTime = currentTime; //AddFrameTime(); } void Timer::AddFrameTime() { std::map<int, float>::iterator iter = m_timeStoragy->begin(); for (; iter != m_timeStoragy->end(); ++iter) iter->second -= m_frameTime; return; } float Timer::GetTime() { return m_frameTime; } bool Timer::SearchTimer(int timerNum) { std::map<std::string, float>::iterator iter; // iter = m_timeStoragy->find(timerNum); //if(*iter != NULL ) return true; } bool Timer::CheckTime(int timerNum) { return true; } int Timer::GetEmptySlot() { for (int i = 0; ; i++) { if (SearchTimer(i) == false) return i; } } bool Timer::WaitForSec(float sec, int timeNum, bool isBegin) { return true; }
true
5bf3275d95c4a4f4da7c364b1a5e577a7ecfed14
C++
3l-d1abl0/DS-Algo
/cpp/practise/max_build_speed_prac.cpp
UTF-8
387
2.546875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int main(){ int N; cin>>N; int arr[2*N]; for(int i=0; i<2*N; i++) cin>>arr[i]; sort(arr, arr+2*N); long long int sum=0; for(int i=0; i<2*N;i++) cout<<arr[i]; cout<<endl; for(int i=0; i<2*N; i+=2) sum+=arr[i]; cout<<sum; return 0; }
true
f72a1e8152bf24e1302e10f1fec9c52a87eb559f
C++
cjhgo/leetcode
/518_Coin_Change_2.cpp
UTF-8
1,853
2.6875
3
[]
no_license
#include"struct_define.h" #include<iostream> #include<vector> #include<string> #include<map> using namespace std; static const auto x=[](){ std::ios::sync_with_stdio(false); std:cin.tie(nullptr); return nullptr; }(); class Solution { public: int change(int amount, vector<int>& coins) { int n = coins.size(); int dp[n+1][amount+1]; vector<int> k_i(n); for(int i = 0; i <=n; i++) dp[i][0] = 1; for(int i = 0; i <= amount; i++) dp[0][i] = 0; dp[0][0]=1; for(int i = 1; i <= n; i++) for(int j = 1; j <= amount; j++) { int temp = 0; for(int k = 0; k <= j/coins[i-1];k++) { int temp2 = j - k*coins[i-1]; temp += dp[i-1][temp2]; } dp[i][j] = temp; } return dp[n][amount]; }//160ms int change2(int amount, vector<int>& coins) { int n = coins.size(); int dp[n+1][amount+1]; vector<int> k_i(n); for(int i = 0; i <=n; i++) dp[i][0] = 1; for(int i = 0; i <= amount; i++) dp[0][i] = 0; dp[0][0]=1; for(int i = 1; i <= n; i++) for(int j = 1; j <= amount; j++) { dp[i][j] = dp[i-1][j]; if( j - coins[i-1] >= 0) dp[i][j] += dp[i][j-coins[i-1]]; } return dp[n][amount]; }//28ms int change3(int amount, vector<int>& coins) { vector<int>dp(amount+1,0); dp[0]=1; for(auto coin : coins) for(int j = coin; j <= amount; j++) { dp[j]+=dp[j-coin]; } return dp[amount]; }//8ms }; int main(int argc, char const *argv[]) { Solution sol; vector<int> coins = {1,5,10,25}; cout<<sol.change(6,coins)<<endl; cout<<sol.change(35837,coins)%1000000007; return 0; }
true
c4718fad256c9466f9b95dbf009f1e830c70fecb
C++
andalevor/resampline
/src/main.cpp
UTF-8
6,792
2.8125
3
[ "MIT" ]
permissive
#include <iostream> #include <fstream> #include <vector> #include <string> #include <cmath> #include <iomanip> #include <cassert> #include "params.hpp" #include "error.hpp" using namespace std; vector<pair<double, double>> get_data(params &p); vector<pair<double, double>> parse_input(istream &input); vector<pair<double, double>> resample(vector<pair<double, double>> &pairs, params &p); void data_output(vector<pair<double, double>> &result, params &p); void print_result(vector<pair<double, double>> &result, params &p, ostream &out); int main(int argc, char **argv) { try { if (argc < 2) throw error(string("Not enouth parameters.") + "\n\nUsage: " + argv[0] + " if=\"inputfile\" " "of=\"output_file\" step=\"number\" [OPTIONAL]" "\n\nIf either or both input and output files are not set," "\nSTDIN or STDOUT respectively will be used." "\nEach input line should consist of X and Y pairs " "with witespace delimiter." "\n\nOptional parameters:" "\n\tstart=\tValue in units(meters or feet). " "Could be used to set start point" "\n\t\tif first point in input file is not the start. " "\n\t\tIt is assumed that first point in input is 0." "\n\t\tSo everything before first point should be set " "as negative value." "\n\tend=\tValue in units(meters or feet). " "Could be used to set end point" "\n\t\tif last point in input is not the end." "\n\t\tIt is recommended to always set the \"end=\" value."); params par = parse_params(argc, argv); auto pairs = get_data(par); if (pairs.size() < 2) throw error("Not enouth data"); auto result = resample(pairs, par); data_output(result, par); } catch (exception &e) { cerr << "Error occurred:\n" << e.what() << endl; return 1; } } vector<pair<double, double>> get_data(params &p) { vector<pair<double, double>> pairs; if (p.in_file.empty()) { pairs = parse_input(cin); } else { ifstream in_file(p.in_file); if (in_file) pairs = parse_input(in_file); } return pairs; } vector<pair<double, double>> parse_input(istream &input) { vector<pair<double, double>> vec; input.exceptions(istream::badbit | istream::failbit); try { double first, second; char ch; while (true) { input >> first >> second; vec.push_back(make_pair(first, second)); input.get(ch); if (ch != '\n' && ch != '\r') throw error("More then two numbers in row"); } } catch (ifstream::failure &e) { if (!input.eof()) throw ifstream::failure("No such file of wrong data format"); } return vec; } vector<pair<double, double>> resample(vector<pair<double, double>> &pairs, params &p) { vector<pair<double, double>> result; double first_x, first_y, second_x, second_y, azimuth, length = 0, dx, dy, x, y, third_x, third_y, alpha, beta, gamma, a, b, c, total = 0; int steps; decltype(pairs.size()) counter = 0; //if start is far from first point we need find line with start point do { p.start -= length; first_x = pairs[counter].first; first_y = pairs[counter].second; ++counter; second_x = pairs[counter].first; second_y = pairs[counter].second; length = sqrt(pow(first_x - second_x, 2) + pow(first_y - second_y, 2)); } while (length - p.start <= 0 && counter + 1 < pairs.size()); length -= p.start; x = first_x; y = first_y; //find azimuth for first line azimuth = atan2(second_y - first_y, second_x - first_x); if (p.start) { x += cos(azimuth) * p.start; y += sin(azimuth) * p.start; } result.push_back(make_pair(x, y)); steps = length / p.step; dx = cos(azimuth) * p.step; dy = sin(azimuth) * p.step; for (int i = 0; i < steps; ++i) { x += dx; y += dy; result.push_back(make_pair(x, y)); total += p.step; } for (decltype(pairs.size()) i = counter + 1; i < pairs.size(); ++i) { third_x = pairs[i].first; third_y = pairs[i].second; //consider a triangle with sides a, b, c and angles alpha, beta, gamma //b is what left on first line, a -- step //we need to find c -- part of second line from begining //where we need to place next point a = p.step; b = length - steps * p.step; assert(b < a); //b should be never more then a //find angle between lines as difference of their angles //which we can find from their slopes alpha = fabs(atan2(first_y - second_y, first_x - second_x) - atan2(third_y - second_y, third_x - second_x)); //alpha could be more than 180 degrees if (alpha > M_PI) alpha = 2 * M_PI - alpha; //from sines theorem beta = asin(b / a * sin(alpha)); //sum of triangles angles is 180 gamma = M_PI - alpha - beta; //from sines theorem c = a * sin(gamma) / sin(alpha); //find dx and dy for first point azimuth = atan2(third_y - second_y, third_x - second_x); dx = cos(azimuth) * c; dy = sin(azimuth) * c; x = second_x + dx; y = second_y + dy; result.push_back(make_pair(x, y)); total += p.step; length = sqrt(pow(third_x - second_x, 2) + pow(third_y - second_y, 2)) - c; if (p.end && i == pairs.size() - 1) length = p.end - p.start - total; steps = length / p.step; dx = cos(azimuth) * p.step; dy = sin(azimuth) * p.step; for (int i = 0; i < steps; ++i) { x += dx; y += dy; result.push_back(make_pair(x, y)); total += p.step; } first_x = second_x; first_y = second_y; second_x = third_x; second_y = third_y; } if (p.end) { while (total < p.end - p.start) { x += dx; y += dy; result.push_back(make_pair(x, y)); total += p.step; } } return result; } void data_output(vector<pair<double, double>> &result, params &p) { if (p.out_file.empty()) { print_result(result, p, cout); } else { ofstream out_file(p.out_file); if (out_file) print_result(result, p, out_file); } } void print_result(vector<pair<double, double>> &result, params &p, ostream &out) { vector<int> field_length; field_length.push_back(to_string(result.size()).length()); field_length.push_back(to_string(static_cast<long>((result.size() - 1) * p.step)).length() + 2); field_length.push_back(to_string(static_cast<long>(result[0].first)).length() + 2); field_length.push_back(to_string(static_cast<long>(result[0].second)).length() + 2); out.exceptions(istream::badbit | istream::failbit); decltype(result.size()) counter = 0; decltype(p.start) curr = p.start; for (const auto &v : result) { out << setprecision(1) << fixed << " " << setw(field_length[0]) << ++counter << " " << setw(field_length[1]) << curr << " " << setw(field_length[2]) << v.first << " " << setw(field_length[3]) << v.second << endl; curr += p.step; } }
true
d27fe9d604ab12b6bba9b06c49edac8a6cb428b6
C++
ChristianReifberger/skip-set
/main.cpp
UTF-8
1,846
3.296875
3
[]
no_license
#include "skip_set.h" #include <iostream> #include <string> #define RUN(X) std::cout << "================================" << std::endl \ << "---- " << (#X) << " ----" << std::endl; \ (X); \ std::cout << "================================" << std::endl << std::endl #define LOG(X) std::cout << (#X) << std::endl; (X) #define DEBUG(X) std::cout << (#X) << " -> " << (X) << std::endl using namespace std; void test_string_set() { skip_set<string> s("a", "z"); LOG(s.insert("b")); LOG(s.insert("g")); LOG(s.insert("e")); LOG(s.insert("u")); cout << endl; DEBUG(s.size()); cout << endl; DEBUG(s.erase("g")); DEBUG(s.erase("x")); DEBUG(s.size()); cout << endl; DEBUG(s.find_bool("g")); DEBUG(s.find_bool("x")); DEBUG(s.find_bool("b")); } void test_int_set() { skip_set<int> s(0, 100); LOG(s.insert(5)); LOG(s.insert(10)); LOG(s.insert(8)); LOG(s.insert(3)); LOG(s.insert(20)); cout << endl; DEBUG(s.size()); cout << endl; DEBUG(s.erase(5)); DEBUG(s.erase(60)); DEBUG(s.size()); cout << endl; DEBUG(s.find_bool(5)); DEBUG(s.find_bool(60)); DEBUG(s.find_bool(20)); } void test_forward_iterator() { skip_set<int> s(0, 100); LOG(s.insert(5)); LOG(s.insert(10)); LOG(s.insert(8)); LOG(s.insert(3)); LOG(s.insert(20)); for (skip_set<int>::iterator it = s.begin(); it != s.end(); ++it) { DEBUG(it->value); } } void test_bidirectional_iterator() { skip_set<int> s(0, 100); LOG(s.insert(1)); LOG(s.insert(10)); LOG(s.insert(3)); LOG(s.insert(50)); LOG(s.insert(7)); for (skip_set<int>::iterator it = s.end(); it != s.begin(); --it) { DEBUG(it->value); } } int main() { cout << std::boolalpha; RUN(test_int_set()); RUN(test_string_set()); RUN(test_forward_iterator()); RUN(test_bidirectional_iterator()); return 0; }
true
9201d7fb74a8c313425e08adea9b39a526897e93
C++
Wahabmughal077/OOP-lab-1
/7.cpp
UTF-8
197
2.9375
3
[]
no_license
#include<iostream> using namespace std; int main() { char c; cout<<"Enter character for which you wants to find the ascci code "; cin>>c; cout<<"Assci code of "<<c<<" is "<<int(c); }
true
d9d03361c9de6807913a02155065f95b8880191c
C++
Hopson97/SFML-Imgui-OpenGL-Example
/src/Maths.cpp
UTF-8
1,666
3.09375
3
[]
no_license
#include "Maths.h" glm::mat4 createModelMatrix(const Transform& transform) { glm::mat4 matrix{1.0f}; matrix = glm::translate(matrix, transform.position); matrix = glm::rotate(matrix, glm::radians(transform.rotation.x), {1, 0, 0}); matrix = glm::rotate(matrix, glm::radians(transform.rotation.y), {0, 1, 0}); matrix = glm::rotate(matrix, glm::radians(transform.rotation.z), {0, 0, 1}); return matrix; } glm::mat4 createViewMartix(const Transform& transform, const glm::vec3& up) { glm::vec3 center{0.0f}; glm::vec3 front{0.0f}; front.x = cos(glm::radians(transform.rotation.y)) * cos(glm::radians(transform.rotation.x)); front.y = sin(glm::radians(transform.rotation.x)); front.z = sin(glm::radians(transform.rotation.y)) * cos(glm::radians(transform.rotation.x)); front = glm::normalize(front); center = transform.position + front; return glm::lookAt(transform.position, center, up); } glm::mat4 createProjectionMatrix(float aspectRatio, float fov) { return glm::perspective(glm::radians(fov), aspectRatio, 0.1f, 10000.0f); } glm::vec3 forwardsVector(const glm::vec3& rotation) { float yaw = glm::radians(rotation.y); float pitch = glm::radians(rotation.x); return {glm::cos(yaw) * glm::cos(pitch), glm::sin(pitch), glm::cos(pitch) * glm::sin(yaw)}; } glm::vec3 backwardsVector(const glm::vec3& rotation) { return -forwardsVector(rotation); } glm::vec3 leftVector(const glm::vec3& rotation) { float yaw = glm::radians(rotation.y + 90); return {-glm::cos(yaw), 0, -glm::sin(yaw)}; } glm::vec3 rightVector(const glm::vec3& rotation) { return -leftVector(rotation); }
true
c1a72b97abcbab07dc4209158ab5b9a73ba56860
C++
ChrisKru/bOS
/Memory/PageTable.h
WINDOWS-1250
942
3.171875
3
[]
no_license
#pragma once #include <vector> #include <iostream> class PageTable { private: int ID; // ID przechwyconego procesu do tablicy stronic int pages; // ilo stronic zalena od rozmiaru procesu public: std::vector<int> FrameNumber; // tablica, zawierajca w sobie numer ramki dla kadej ze stronic std::vector<bool> VIBit; // bit, mwicy czy dana stronica jest w pamici PageTable(int PID, int ProcessSize); // konstruktor przechwytuje ID procesu, tworzy dla niego tablic stronic, // oblicza ile potrzeba stronic dla procesu, ustawia domylne wartoci // tablicom FrameNumber oraz VIBit int getPageNumber(int LogicalAddress); // zwraca stronic, w ktrej powinien znajdowa si wskazany adres int getPages(); // zwraca ilo stronic int getID(); // zwraca ID procesu, do ktrego naley tablica stronic void show(); // wyswietla zawartosc tablicy stronic };
true
9542a01e0f16e794ee74c4271925d243aac48c79
C++
InsaDams/Qualite_Logicielle
/Qualite_Logicielle/CCompas.cpp
ISO-8859-1
825
3.109375
3
[]
no_license
#include "CCompas.h" //Affecte les positions de dparts x et y void CCompas::SetStart(Pos start) { pos_x = start.x; pos_y = start.y; } //Dplace le robot d'une case vers la droite void CCompas::MoveRight() { pos_x = pos_x + 1; } //Dplace le robot d'une case vers la gauche void CCompas::MoveLeft() { pos_x = pos_x - 1; } //Dplace le robot d'une case vers le haut void CCompas::MoveUp() { pos_y = pos_y -1; } //Dplace le robot d'une case vers le bas void CCompas::MoveDown() { pos_y = pos_y + 1; } //Retourne la position du robot travers un point de coordonns {x,y} CCompas::Pos CCompas::GetPosition() { CCompas::Pos point = {pos_x,pos_y}; return point; } CCompas::CCompas() { pos_x = 0; pos_y = 0; } //Metrique : Comment Only : lignes 13.0 % // Caractres :41.6 %
true
fbbe55b344f262fbef3518a7e3306fc09d00bea2
C++
hmnt007/CPP-Pogramming
/Leetcode/Leetcode Daily/May/19thMay21.cpp
UTF-8
953
3.375
3
[]
no_license
// https://leetcode.com/explore/challenge/card/may-leetcoding-challenge-2021/600/week-3-may-15th-may-21st/3748/ /** Minimum Moves to Equal Array Elements II Solution Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal. In one move, you can increment or decrement an element of the array by 1. Example 1: Input: nums = [1,2,3] Output: 2 Explanation: Only two moves are needed (remember each move increments or decrements one element): [1,2,3] => [2,2,3] => [2,2,2] Example 2: Input: nums = [1,10,2,9] Output: 16 Constraints: n == nums.length 1 <= nums.length <= 105 -109 <= nums[i] <= 109 **/ // CODE class Solution { public: int minMoves2(vector<int>& nums) { int n = nums.size(), sum = 0; sort(nums.begin(), nums.end()); sum = nums[0.5*n]; int res =0; for ( auto x : nums) res += abs(x-sum); return res; } };
true
f314f79ed4425d2f4d2f0ad2d708a01a117ff17f
C++
Jay-Ppark/Algorithm
/10828_스택.cpp
UTF-8
938
3.421875
3
[]
no_license
#include<iostream> #include<vector> #include<string> using namespace std; vector <int> v; string command; void push(int num){ v.push_back(num); } int pop(){ if (v.empty()) { return -1; } else { int temp = v.at(v.size() - 1); v.pop_back(); return temp; } } int size(){ return v.size(); } bool empty(){ if (v.empty()){ return true; } else{ return false; } } int top(){ if (v.empty()){ return -1; } else{ return v.at(v.size() - 1); } } int main(void){ int N; cin >> N; for (int i = 0; i < N; i++){ cin >> command; if (command.compare("push") == 0){ int temp; cin >> temp; push(temp); } else if (command.compare("pop") == 0){ cout << pop() << '\n'; } else if (command.compare("size") == 0){ cout << size() << '\n'; } else if (command.compare("empty") == 0){ cout << empty() << '\n'; } else if (command.compare("top") == 0){ cout << top() << '\n'; } } return 0; }
true
4a51522ae17adeb4d5d4018aad4179198750beb5
C++
srandonova18/deistviq-s-mnojestva
/deistviq-s-mnojestva/Presentation.cpp
UTF-8
8,015
3.375
3
[]
no_license
#include <iostream> #include "Data.h" #include "Presentation.h" using namespace std; //function that graphically displays the union of two sets void unionGraphic() { cout << endl; cout << " * * * * * *" << endl; cout << " ********** **********" << endl; cout << " *********** ** ***********" << endl; cout << "*********** **** ***********" << endl; cout << "*********** **** ***********" << endl; cout << "*********** **** ***********" << endl; cout << " *********** ** ***********" << endl; cout << " ********** **********" << endl; cout << " * * * * * * " << endl; cout << endl; } //function that graphically displays the intersection of two sets void intersectionGraphic() { cout << endl; cout << " * * * * * *" << endl; cout << " * ** *" << endl; cout << " * **** *" << endl; cout << "* ****** *" << endl; cout << "* ****** *" << endl; cout << "* ****** *" << endl; cout << " * **** *" << endl; cout << " * ** *" << endl; cout << " * * * * * * " << endl; cout << endl; } //function that graphically displays the subtraction of the first set void subtractionOfAGraphic() { cout << endl; cout << " * * * * * *" << endl; cout << " ************ *" << endl; cout << " ************ * *" << endl; cout << "************ * *" << endl; cout << "************ * *" << endl; cout << "************ * *" << endl; cout << " ************ * *" << endl; cout << " ************ *" << endl; cout << " * * * * * * " << endl; cout << endl; } //function that graphically displays the subtraction of the second set void subtractionOfBGraphic() { cout << endl; cout << " * * * * * *" << endl; cout << " * ************" << endl; cout << " * * ************" << endl; cout << "* * ************" << endl; cout << "* * ************" << endl; cout << "* * ************" << endl; cout << " * * ************" << endl; cout << " * ************" << endl; cout << " * * * * * * " << endl; cout << endl; } //function that graphically displays the symmetrical subtraction of two sets void symmetricalSubtractionGraphic() { cout << endl; cout << " * * * * * *" << endl; cout << " **********************" << endl; cout << " ************ ************" << endl; cout << "************ ************" << endl; cout << "************ ************" << endl; cout << "************ ************" << endl; cout << " ************ ************" << endl; cout << " **********************" << endl; cout << " * * * * * * " << endl; cout << endl; } //function that graphically displays a set and a subset within it void subsetGraphic() { cout << endl; cout << " * * *" << endl; cout << " * *" << endl; cout << " * * *" << endl; cout << "* ******* *" << endl; cout << "* ********* *" << endl; cout << "* ******* *" << endl; cout << " * * *" << endl; cout << " * *" << endl; cout << " * * *" << endl; cout << endl; } /* function that returns the user's choice (1 is for the first array and 2 is for the second array) */ int whichArray() { int choice; cout << "Enter an option: "; choice = readInt(); while (choice < 1 or choice > 2) { cout << "\nYour input has to be either 1 or 2! Try again: "; choice = readInt(); } return choice; } /* function that prompts the user to input a size number and elements for each of the two arrays */ void enterArrayElements(int array[], int& size, string number) { cout << "Enter the size of the " << number << " array: "; size = readInt(); while (size < 1) { cout << "\nYour input has to be a whole positive number! Try again: "; size = readInt(); } cout << endl; cout << "Enter the elements of the " << number << " array: "; for (int i = 0; i < size; i++) { array[i] = readInt(); } cout << endl << endl; } /* function that finds the substraction of the first and second array or vice versa */ void subtractionOfSets(int a[], int n, int b[], int m) { int* c = new int[(double)n + m]; int k = 0; cout << "Which array do you want to subtract from?" << endl; cout << endl; cout << "1. The first one (A) - A \\ B" << endl; cout << "2. The second one (B) - B \\ A" << endl; cout << endl; if (whichArray() == 1) { subtractionOfAGraphic(); cout << "- - - - - The subtraction of the sets (A \\ B) is: "; comparison(a, n, b, m, "==", c, k); } else { subtractionOfBGraphic(); cout << "- - - - - The subtraction of the sets (B \\ A) is: "; comparison(b, m, a, n, "==", c, k); } sort(c, k); for (int i = 0; i < k; i++) cout << c[i] << " "; cout << "- - - - -"; delete[]c; } /* function that finds if the first array is a subset of the second or vice versa */ void isSubset(int a[], int n, int b[], int m) { int count = 0; cout << "Which set do you want to check if it is a subset of the other set?" << endl; cout << endl; cout << "1. The first one (A)" << endl; cout << "2. The second one (B)" << endl; cout << endl; if (whichArray() == 1) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (a[i] == b[j]) { count++; } } } cout << endl; if (count == n) { subsetGraphic(); cout << "- - - - - A is a subset of B - - - - -" << endl; } else { cout << "- - - - - A is not a subset of B - - - - -" << endl; } } else { for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (b[i] == a[j]) { count++; } } } cout << endl; if (count == m) { subsetGraphic(); cout << "- - - - - B is a subset of A - - - - -" << endl; } else { cout << "- - - - - B is not a subset of A - - - - -" << endl; } } } //function that prints a welcoming message void showWelcome() { cout << "WELCOME TO OUR PROGRAM!" << endl; cout << "To try it, you'll have to enter two sets of whole numbers" << endl << endl; } //function that prints the menu void showMenu() { cout << "+---------------------------+" << endl; cout << "| |" << endl; cout << "| MENU |" << endl; cout << "| |" << endl; cout << "+---------------------------+" << endl; cout << endl; cout << "1. Union" << endl; cout << "2. Intersection" << endl; cout << "3. Subtraction (difference)" << endl; cout << "4. Symmetrical subtraction" << endl; cout << "5. Subset" << endl; cout << "6. Quit " << endl << endl; cout << "Please enter an option: "; } //function that displays the menu options, prompts the user to input data and prints the result void mainMenu() { showWelcome(); int a[100], b[100], n, m; enterArrayElements(a, n, "first"); enterArrayElements(b, m, "second"); int choice; do { showMenu(); choice = readInt(); while ((choice < 1) or (choice > 6)) { cout << "\nYour input has to be a whole number between 1 and 6! Try again: "; choice = readInt(); } cout << endl; switch (choice) { case 1: unionGraphic(); cout << "- - - - - The union of the sets (A U B) is: "; unionOfSets(a, n, b, m); cout << "- - - - -"; break; case 2: intersectionGraphic(); cout << "- - - - - The intersection of the sets (A " << u8"\u2229" << " B) is: "; intersectionOfSets(a, n, b, m); cout << "- - - - -"; break; case 3: subtractionOfSets(a, n, b, m); break; case 4: symmetricalSubtractionGraphic(); cout << "- - - - - The symmetrical subtraction of the sets is: "; symmetricalSubtractionOfSets(a, n, b, m); cout << "- - - - -"; break; case 5: isSubset(a, n, b, m); break; case 6: cout << "Exiting....\n"; exit(0); break; } cout << endl << endl << endl; } while (choice != 6); }
true
d64ea0de5c22af94c22fffe6892f67173508cb4f
C++
sperrys/comp117_rpc
/tcp.cpp
UTF-8
2,036
2.984375
3
[]
no_license
#include "tcp.h" using namespace std; using namespace C150NETWORK; size_t read_message_size(C150StreamSocket *socket) { char buffer[30]; char *buff_ptr = buffer; // next char to read ssize_t readlen; // amount of data read from socket for (unsigned int i = 0; i < sizeof(buffer); i++) { readlen = socket->read(buff_ptr, 1); // read a byte if (*buff_ptr == '{') { return stoi(string(buffer)); } buff_ptr++; // error handling if (readlen == 0) { c150debug->printf(C150RPCDEBUG, "Read zero length message, checking EOF"); if (socket-> eof()) { c150debug->printf(C150RPCDEBUG, "EOF signaled on input"); } else { throw C150Exception("Unexpected zero length read without EOF"); } } } // catchall error handling if (readlen == 0) { return 0; } else { throw C150Exception("Finding JSON size failed."); } } string read_message(C150StreamSocket *socket, size_t message_size) { char buffer[message_size]; char *buff_ptr = buffer; // next char to read ssize_t readlen; // amount of data read from socket bool read_null; for (unsigned int i = 0; i < sizeof(buffer); i++) { readlen = socket->read(buff_ptr, 1); // read a byte if (readlen == 0) { break; } else if (*buff_ptr++ == '\0') { read_null = true; break; } } // error handling if (readlen == 0) { c150debug->printf(C150RPCDEBUG,"Read zero length message, checking EOF"); if (socket-> eof()) { return ""; c150debug->printf(C150RPCDEBUG,"EOF signaled on input"); } else { throw C150Exception("Unexpected zero length read without EOF"); } } else if (!read_null) { // If we didn't get a null, input message was poorly formatted throw C150Exception("Method name not null terminated or too long"); } // buffer to string string message(buffer); cout << message << endl; message = to_string(message_size) + "{" + message; // manually reformat message return message; }
true
0fac656c3a0edda60b43a89973cf25d297262c8e
C++
NLGRF/Workshop-Arduino-SUT
/Code/EXERCISES/Interruptor_Ex1/Interruptor_Ex1.ino
UTF-8
285
2.71875
3
[]
no_license
// Interrupter Test by polling int pin_Counter = 3; int counter = 0; void setup() { pinMode(pin_Counter,INPUT); Serial.begin(9600); } void loop() { int isCount = digitalRead(pin_Counter); if (isCount == 1) { counter++; Serial.println(counter); delay(500); } }
true
d563bc1a33ec0f0556b3e8c4015a5360d5490962
C++
ForPertP/HackerRank-in-a-String-
/HackerRank-in-a-String-.cpp
UTF-8
340
2.703125
3
[]
no_license
string hackerrankInString(string s) { std::deque<char> dq = {'h', 'a', 'c', 'k', 'e', 'r', 'r', 'a', 'n', 'k'}; for (const auto & c : s) { if (c == dq[0]) { dq.pop_front(); if (dq.empty()) { return "YES"; } } } return "NO"; }
true
b2bfd163a2cb4304d62f3d9042fc72c3ab30c770
C++
mosemb/C-
/MyCodeSchool/LinkedList/main.cpp
UTF-8
316
3.015625
3
[]
no_license
#include <iostream> #include "Link.h" using namespace std; int main() { Link *temp ; std::cout << "How many numbers " << std::endl; int n , x; cin>> n; for(int i = 0; i<n; i++){ cout << "Enter number "; cin>> x; temp->insert(x); } temp->print(); return 0; }
true
f6c37fec502698ab5deee43bebc4d85e4cd3671c
C++
kedebug/AlgoTraining
/poj/1178/10931454_AC_47MS_416K.cc
UTF-8
2,526
2.96875
3
[]
no_license
// // http://blog.csdn.net/lijiecsu/article/details/7579855 // #include <cstdio> #include <cstdlib> #include <cstring> const int INF = 0x7FFF; int king_move[8][2] = {{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}}; int knight_move[8][2] = {{-2,-1},{-2,1},{-1,-2},{-1,2},{1,-2},{1,2},{2,-1},{2,1}}; int king_map[65][65], knight_map[65][65]; bool judge(int x, int y) { if(x >= 0 && x < 8 && y >= 0 && y < 8) return true; else return false; } void init() { int i, j; int x, y, tx, ty; for (i = 0; i < 64; ++i) { for (j = 0; j < 64; ++j) knight_map[i][j] = INF, king_map[i][j] = INF; knight_map[i][i] = 0; king_map[i][i] = 0; x = i % 8; y = i / 8; for (j = 0; j < 8; ++j) { tx = x + king_move[j][0]; ty = y + king_move[j][1]; if (judge(tx, ty)) king_map[i][tx+ty*8] = 1; tx = x + knight_move[j][0]; ty = y + knight_move[j][1]; if (judge(tx, ty)) knight_map[i][tx+ty*8] = 1; } } } void floyd() { int i, j, k; for (k = 0; k < 64; ++k) { for (i = 0; i < 64; ++i) { for (j = 0; j < 64; ++j) { if (king_map[i][j] > king_map[i][k] + king_map[k][j]) king_map[i][j] = king_map[i][k] + king_map[k][j]; if (knight_map[i][j] > knight_map[i][k] + knight_map[k][j]) knight_map[i][j] = knight_map[i][k] + knight_map[k][j]; } } } } int main() { char s[256]; int pos[65]; int i, j, num; memset(s, 0, sizeof(s)); init(); floyd(); scanf("%s", s); for (i = 0, num = 0; i < strlen(s); i += 2) pos[num++] = s[i] - 'A' + (s[i+1] - '1') * 8; int min_move = INF; int dst, met, k, sum; // the position is range from 0 to 63 for (dst = 0; dst < 64; ++dst) { for (met = 0; met < 64; ++met) { for (k = 1; k < num; ++k) { sum = 0; for (i = 1; i < num; ++i) sum += knight_map[pos[i]][dst]; sum += king_map[pos[0]][met]; sum += knight_map[pos[k]][met] + knight_map[met][dst]; sum -= knight_map[pos[k]][dst]; if (sum < min_move) min_move = sum; } } } printf("%d\n", min_move); return 0; }
true
b34f3fb15c839ab57878ed366f820b2c3fc54375
C++
timruning/leecode
/IntersectionofTwoLinkedLists1/IntersectionofTwoLinkedLists1/IntersectionofTwoLinkedLists1.cpp
GB18030
1,625
3.546875
4
[]
no_license
// IntersectionofTwoLinkedLists1.cpp : ̨Ӧóڵ㡣 // #include "stdafx.h" #include<iostream> #include<vector> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { vector<int> vecA; vector<int> vecB; ListNode* p = headA; ListNode* q = headB; if (p == NULL || q == NULL){ return NULL; } while (p != NULL){ vecA.push_back(p->val); p = p->next; } while (q!=NULL) { vecB.push_back(q->val); q = q->next; } int count = 0; // bool have = false; for (int i = vecA.size() - 1, j = vecB.size() - 1; i >= 0, j >= 0; i--, j--){ if (vecA[i] == vecB[j]){ count++; } else{ // have = true; break; } } p = headA; for (int i = 0; i < vecA.size() - count; i++){ p = p->next; } return p; } }; ListNode* turnToList(int a[], int n){ ListNode* head = NULL; if (n == 0){ return head; } head = new ListNode(a[0]); ListNode *p = head; for (int i = 1; i < n; i++){ ListNode *t = new ListNode(a[i]); p->next = t; p = p->next; } return head; } int _tmain(int argc, _TCHAR* argv[]) { int a[] = { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21 }; int b[] = {2}; ListNode* head1 = turnToList(a, sizeof(a)/sizeof(a[0])); // ListNode* head2 = turnToList(b, sizeof(b)/sizeof(b[0])); ListNode* head2=NULL; Solution sol; ListNode* p = sol.getIntersectionNode(head1, head2); if (p != NULL){ cout << p->val << endl; } else{ cout << "null" << endl; } return 0; }
true
2972de5b2f9c97b769b26628050656247cadb197
C++
jayirum/ChartProjSvr
/Source/FBI/HashMap/SimpleMapSKey.h
UHC
1,157
2.515625
3
[]
no_license
#pragma once #include "MapClassSimpleBase.h" class CSimpleMapSKey { public: CSimpleMapSKey(); ~CSimpleMapSKey(); bool Initialize(VAL_TYPE valType); void DeInitialize(); bool AddValue(char* key, char* val, int nValLen, bool bUpdate = true); bool AddValue(char* key, long* val, int nValLen, bool bUpdate = true); bool AddValue(char* key, double* val, int nValLen, bool bUpdate = true); bool AddValue(char* key, RECORD_VAL* val, int nValLen, bool bUpdate = true); bool IsExists(char* key ); bool GetValue(char* key, _Out_ char* pVal, int nValSize=0); // nValSize ʿ bool GetValue(char* key, _Out_ long* pVal, int nValSize=0); // nValSize ʿ bool GetValue(char* key, _Out_ double* pVal, int nValSize=0); // nValSize ʿ bool GetValue(char* key, _Out_ RECORD_VAL* pVal, int nValSize=0); // nValSize ݵʿ void Del(char* key); int GetLastErr() { return m_nLastErr; } private: CSimpleMapBase<string, string> *m_mapS; CSimpleMapBase<string, long> *m_mapL; CSimpleMapBase<string, double> *m_mapD; CSimpleMapBase<string, RECORD_VAL> *m_mapR; VAL_TYPE m_tpVal; int m_nLastErr; };
true
7d4625e190a1a85a44fb6fe18e400a57db2b0700
C++
rahulsa123/Programming
/Sorting/insertionSort.cpp
UTF-8
473
2.890625
3
[]
no_license
#include<iostream> #include<bits/stdc++.h> using namespace std; vector<int> InsertionSort(vector<int> a){ for(int i=1;i<a.size();i++){ for(int j=i;j>-1 && a[j-1]>a[j];j--){ int temp =a[j-1]; a[j-1]=a[j]; a[j]=temp; } } return a; } int main(){ ios_base::sync_with_stdio(false); vector<int> a ={2,34,5,6567,667,778,3564,34,23,32,43,54,45,54232,898}; a=InsertionSort(a); for(int i :a) cout<<i<<" "; return 0; }
true
c19614fa57b7583dc08757905d07615112917222
C++
1124418652/data_structure_and_algrithom
/SVD/main.cpp
UTF-8
438
3.078125
3
[]
no_license
#include <iostream> using namespace std; int **createArray(); void main() { int **b = createArray(); for (int i=0; i<5; i++) { // for (int j=0; j<5; j++) //cout<<b[i][j]<<endl; } string a="adfagargha"; cout<<a.length()<<int(1.2)<<endl; } int **createArray() { int **a; a = new int*[5]; for (int i=0; i<5; i++) { a[i] = new int[5]; } for (i=0; i<5; i++) { for (int j=0; j<5; j++) a[i][j] = i+j; } return a; }
true
bc26e1cd7b9a28740eda308922849d27dd0e877c
C++
thorout/ConsoleApplication4
/ConsolePatterns/Proxy.cpp
UTF-8
1,504
3.28125
3
[]
no_license
#include "Proxy.h" class Subject { public: virtual ~Subject() { } virtual void RequestComplexData() = 0; virtual void RequestSimpleData() = 0; }; class RealSubject : public Subject { public: void RequestComplexData() override { std::cout << "Real object with big comlex data!" << std::endl; } void RequestSimpleData() override { std::cout << "Real object simple data." << std::endl; } }; class ProxyClass : public Subject { public: ~ProxyClass() { delete pointerToRealObject; } void RequestComplexData() override { std::cout << std::endl << "Proxy object trapping real method and redirect to real object!" << std::endl; if (pointerToRealObject == nullptr) pointerToRealObject = new RealSubject(); // delayed creation of real object pointerToRealObject->RequestComplexData(); } void RequestSimpleData() override { std::cout << std::endl << "Proxy object trapping real method and check is real obect creted or not!" << std::endl; if (pointerToRealObject == nullptr) std::cout << "Proxy object is executing internal method" << std::endl; else pointerToRealObject->RequestSimpleData(); // if no real object created yet do proxy method } private: Subject* pointerToRealObject = nullptr; }; Proxy::Proxy() { std::cout << "Pattern \"Proxy\"\n"; } Proxy::~Proxy() { } void Proxy::run() { Subject& subject = ProxyClass(); subject.RequestSimpleData(); subject.RequestComplexData(); subject.RequestSimpleData(); std::cout << ">>> Whole Pattern was terminated...\n"; }
true
03958fcf7fee3f38e338a23b9cc3ab5f7bb16350
C++
HaikuArchives/DockBert
/source/OffscreenView.h
UTF-8
1,316
2.71875
3
[ "MIT", "BSD-3-Clause", "BSD-2-Clause" ]
permissive
#ifndef OFFSCREEN_VIEW_H #define OFFSCREEN_VIEW_H #include <View.h> #include <Bitmap.h> #include <Locker.h> class TOffscreenView : public BView { public: TOffscreenView( BRect rect ) : BView( rect, "TOffscreenView", B_FOLLOW_ALL, B_WILL_DRAW ) { fBitmapBuffer = new BBitmap( rect, B_RGBA32, true ); fBitmapBuffer->AddChild( this ); } virtual ~TOffscreenView() { fBitmapBuffer->RemoveChild(this); delete fBitmapBuffer; } void SetBackBufferSize( float width, float height ) { fLock.Lock(); fBitmapBuffer->Lock(); ResizeTo( width, height ); fBitmapBuffer->Unlock(); BRect r = fBitmapBuffer->Bounds(); if ( width > r.Width() ) r.right *= 2; if ( height > r.Height() ) r.bottom *= 2; if ( r != fBitmapBuffer->Bounds() ) { BBitmap *tmp = new BBitmap( r, B_RGBA32, true ); fBitmapBuffer->RemoveChild( this ); tmp->AddChild( this ); tmp->Lock(); DrawBitmap( fBitmapBuffer ); tmp->Unlock(); delete fBitmapBuffer; fBitmapBuffer = tmp; } fLock.Unlock(); } inline void Lock() { fLock.Lock(); fBitmapBuffer->Lock(); } inline void Unlock() { Sync(); // Flush(); fBitmapBuffer->Unlock(); fLock.Unlock(); } BBitmap *OffscreenBuffer() const { return fBitmapBuffer; } protected: BBitmap *fBitmapBuffer; BLocker fLock; }; #endif
true
d7c5aa85b2d9fa3e2f79af8162476f02b4109a75
C++
tkemmer/badhron
/src/cpp/reports.cpp
UTF-8
2,013
2.875
3
[ "MIT" ]
permissive
#include "reports.h" #include <iomanip> #include <string> namespace badhron { using std::ostream; using std::string; // ================================================================================================================ // report::impl class report::impl { public: explicit impl( string function, string subgroup, string message, data_t expected, data_t observed ) : function_{move(function)}, subgroup_{move(subgroup)}, message_ {move(message)}, expected_{expected}, observed_{observed} { } friend ostream& operator<<(ostream& os, const impl& report) { using namespace std::string_literals; if(std::holds_alternative<bool>(report.expected_)) os << std::boolalpha; else if(std::holds_alternative<double>(report.expected_)) os << std::setprecision(15); os << " # "s << report.function_; if(report.subgroup_ != ""s) os << " (in subgroup "s << report.subgroup_ << ")"s; os << '\n' << " \033[1mAssertion failed: "s << report.message_ << "\033[0m\n"s << " Expected: "s; visit([&os](auto&& arg){ os << arg; }, report.expected_); os << '\n' << " Observed: "s; visit([&os](auto&& arg){ os << arg; }, report.observed_); os << '\n'; return os; } private: string function_; string subgroup_; string message_; data_t expected_; data_t observed_; }; // ================================================================================================================ // report report::report( string function, string subgroup, string message, data_t expected, data_t observed ) : impl_{std::make_unique<report::impl>(move(function), move(subgroup), move(message), expected, observed)} { } report::report(report&&) noexcept = default; report::~report() noexcept = default; report& report::operator=(badhron::report&&) noexcept = default; ostream& operator<<(ostream& os, const report& report) { if(report.impl_) os << *report.impl_; return os; } }
true
c94692eef5c298602b8c7e02c1008240bbb201dd
C++
DustinCraggs/SpaceBoat
/Physics/Particles/Graphics.cpp
UTF-8
2,237
2.578125
3
[]
no_license
#include "Graphics.hpp" #include <iostream> #include <unistd.h> #include <math.h> #include "shader.hpp" Graphics::Graphics() : physics(1, 300){ initWindow(); particleShader = compileShader("particle"); particleRenderer.initialise(1000); // TESTING prev = std::chrono::high_resolution_clock::now(); } unsigned int Graphics::compileShader(std::string name){ unsigned int PID = LoadShaders((name + ".vert").c_str(), (name + ".frag").c_str()); if( PID == 0 ){ exit(1); } return PID; } void Graphics::nextFrame(){ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(particleShader); std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); float delta = std::chrono::duration_cast<std::chrono::nanoseconds>(now - prev).count()/pow(10,9); prev = now; std::cout << delta << std::endl; physics.nextFrame(delta, 300); particleRenderer.render(physics.particleData(), physics.colourData(), physics.nParticles(), particleShader); glFlush(); glfwSwapBuffers(window); glfwWaitEvents(); } bool Graphics::shouldClose(){ return glfwWindowShouldClose(window); } void Graphics::errCallback(int error, const char *description){ fputs(description, stderr); fputs("\n", stderr); } void Graphics::initWindow(){ std::cout << "initialisation" << std::endl; glfwSetErrorCallback(errCallback); if( !glfwInit() ){ exit(1); } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_SAMPLES, 4); std::cout << "Window creation" << std::endl; window = glfwCreateWindow(1000, 800, "Particle sim", NULL, NULL); std::cout << "Window created" << std::endl; if( !window ){ glfwTerminate(); exit(0); } glfwMakeContextCurrent(window); glfwSwapInterval(1); glewExperimental = true; if( glewInit() != GLEW_OK ){ fprintf(stderr, "GLEW initialisation failed\n"); exit(1); } glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // glEnable(GL_DEPTH_TEST); glEnable(GL_PROGRAM_POINT_SIZE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE); // glEnable(GL_MULTISAMPLE); glFrontFace(GL_CCW); }
true
fa270d971e752ca492ec0e0292fbb852f0ace5d2
C++
reclaimingmytime/lillabeler
/Lillabeler.cpp
UTF-8
848
2.765625
3
[ "MIT" ]
permissive
/* Lillabeler.cpp Dependency: OpenCV 4.5.2 A piece of software which can automagicly label your pictures via the use of a digital twin. */ #include "Import.hpp" #include "BBFinder.hpp" #include "Formatter.hpp" #include "Export.hpp" #include <filesystem> Import Im; BBFinder Find; Formatter Format; Export Ex; std::vector<std::string> *textFile; int main() { // Setup filesystem Im.Setup(); Ex.Setup(Im.ClassPoint()); while (true) { // Find BBoxes in a single image bool returnVal = Find.Draw(Im.ClassPoint(), Im.ColourPoint()); // Check if we procesed all the files if (returnVal == false) { textFile = Format.FormatData(Find.BBoxesPoint(), Find.ImgWidthPoint(), Find.ImgHeightPoint()); Ex.WriteBBox(textFile, Find.FileNamePoint()); } else { break; } } // Create the train.txt file Ex.WriteTrain(); }
true
ae0f7a70bed0de075e6d7863836f642ade92fde9
C++
kushalarora/codes
/codesprint/isFibbo.cpp
UTF-8
442
2.78125
3
[]
no_license
#include<iostream> #include<set> const long long MAX = 10000000000; using namespace std; int main() { long long T, n1 = 0, n2 = 1, n; cin >> T; set<long long> s; s.insert(n1); //init while (n2 <= MAX) { s.insert(n2); long long tmp = n2; n2 = n1 + n2; n1 = tmp; } while(T--) { cin >> n; cout << (s.find(n) == s.end() ? "IsNotFibo" : "IsFibo") << endl; } }
true
a55361c352f93948c9c228697d09f068b5b3b16c
C++
Aestheticism1/Leetcode-PAT-CCF
/PAT/Advanced/A081_gcd.cpp
UTF-8
643
2.5625
3
[]
no_license
#include <iostream> using namespace std; typedef long long ll; ll gcd(ll a, ll b){ return b==0 ? a : gcd(b, a%b); } int main() { int N; cin >> N; ll rn, rd; scanf("%lld/%lld", &rn, &rd); for(int i = 0; i < N-1; ++i){ int n, d; scanf("%d/%d", &n, &d); rn = rn * d + n * rd; rd *= d; } if(rn == 0){ printf("%lld", rn); }else if(rn % rd == 0){ printf("%lld", rn/rd); }else{ if(rn > rd){ printf("%lld ", rn/rd); rn %= rd; } ll a = gcd(rn, rd); printf("%lld/%lld", rn/a, rd/a); } return 0; }
true
94945301502b85b1ea362b54b474f2f509948834
C++
luisa-maria1111/Hacker_Blocks_CPP
/count_digits_decimal.cpp
UTF-8
1,003
3.890625
4
[]
no_license
/* HACKER BLOCKS : COUNT DIGITS (accepts decimal numbers) @author: Luísa Maria Mesquita */ #include <iostream> #include <string> using namespace std; int countDigit(const string &num, const string &digit) { int count = 0, remainder; string testingDigit; for(int i = 0; i <= num.length(); i++) { testingDigit = num.substr(i, 1); if(testingDigit == "0" || testingDigit == "1" || testingDigit == "2" || testingDigit == "3" || testingDigit == "4" || testingDigit == "5" || testingDigit == "6" || testingDigit == "7" || testingDigit == "8" || testingDigit == "9") if(testingDigit == digit) count = count + 1; } return count; } int main() { string num, digit; cin >> num >> digit; if(stoi(num) < 0 || stoi(num) > 1000000000 || stoi(digit) < 0 || stoi(digit) > 9) { cout << "Outside valid range!" << endl; exit(1); } else { cout << countDigit(num, digit) << endl; } return 0;
true
74a7b3c89a7738287faaa7df548694cdd3ec7adc
C++
MatMarkiewicz/University
/Term 6/SK (Computer networks)/P1/mateusz_markiewicz/main.cpp
UTF-8
1,995
2.6875
3
[]
no_license
// autor: Mateusz Markiewicz 298653 #include "sender.h" #include "receive.h" bool isIpAddr(char *str) { struct sockaddr_in sai; int res = inet_pton(AF_INET, str, &(sai.sin_addr)); return res != 0; } int main(int argc, char *argv[]) { if (argc != 2){ fprintf(stderr,"Wrong number of arguments\n"); return EXIT_FAILURE; } else if (!isIpAddr(argv[1])){ fprintf(stderr,"Invalid Ip Addres: %s\n",argv[1]); return EXIT_FAILURE; } int sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); sendPacket sender = sendPacket(sockfd, argv[1]); fd_set descriptors; receivePacket receiver = receivePacket(sockfd, &descriptors); for (int ttl=1; ttl<=30; ttl++){ std::chrono::high_resolution_clock::time_point sendtime = std::chrono::high_resolution_clock::now(); int pid = -1; try{ pid = sender.sendMulti(ttl); } catch(const char * c){ fprintf(stderr,"%s\n",c); return EXIT_FAILURE; } array<packet,3> packets; try{ packets = receiver.reciveMulti(pid,ttl-1); } catch (const char * c){ fprintf(stderr,"%s\n",c); return EXIT_FAILURE; } if (packets[0].id == -1){ printf("*\n"); }else { unsigned int whole_time = 0; set<char*> S; for (int i=0;i<3;i++){ packet p = packets[i]; if (p.id != -1){ S.insert(p.ip_str); whole_time += std::chrono::duration_cast<std::chrono::milliseconds>(p.time - sendtime).count(); } } for (char * const& ipstr : S) printf("%s ",ipstr); if (packets[2].id != -1){ printf("%ums\n",whole_time/3); }else{ printf("???\n"); } if (packets[0].type == ICMP_ECHOREPLY){ break; } } } return EXIT_SUCCESS; }
true
982b8520dc8df5830abf2528b654125e34c8c713
C++
Art17/Kpi-1
/courses/prog_base/labs/lab2/arrays/main.cpp
UTF-8
3,193
3.265625
3
[]
no_license
#include <stdio.h> #include <math.h> #include <stdlib.h> #include <time.h> const int n0 = 4; const int n1 = 1; const int nMax = 511; int counts[nMax]; int max (int x, int y) { return (x > y) ? x : y; } int min (int x, int y) { return x < y ? x : y; } void fillRand2 (int arr[], int size) { for (int i = 0; i < size; i++) arr[i] = (rand () % 511) - 255; } int checkRand2 (int arr[], int size) { for (int i = 0; i < size; i++) if (arr[i] > 255 && arr[i] < -255) return 0; return 1; } int maxValue (int arr[], int size) { int m = arr[0]; for (int i = 0; i < size; i++) m = max (m, arr[i]); return m; } int minIndex (int arr[], int size) { int m = arr[0], index = -1; for (int i = 0; i < size; i++) m = min (m, arr[i]); for (int i = 0; i < size; i++) if (arr[i] == m) { index = i; break; } return index; } int maxOccurance (int arr[], int size) { int m = 0; for (int i = 0; i < size; i++) m = max (m, ++counts[arr[i] + 255]); for (int i = nMax - 1; i >= 0; i--) if ( counts[i] == m ) return i - 255; } int diff (int arr1[], int arr2[], int res[], int size) { int bZero = 1; for (int i = 0; i < size; i++) { res[i] = arr1[i] - arr2[i]; if (res[i] != 0) bZero = 0; } } void add (int arr1[], int arr2[], int res[], int size) { for (int i = 0; i < size; i++) res[i] = arr1[i] + arr2[i]; } int gteq (int arr1[], int arr2[], int size) { for (int i = 0; i < size; i++) if (arr1[i] < arr2[i]) return 0; return 1; } void lor (int arr1[], int arr2[], int res[], int size) { for (int i = 0; i < size; i++) res[i] = arr1[i] || arr2[i]; } void printArr (int arr[], int size) { for (int i = 0; i < size; i++) printf ("%d ", arr[i]); printf ("\n\n"); } int main () { srand (time (NULL)); const int size = 20; int arr1[size]; int arr2[size]; int res[size]; fillRand2 (arr1, size); fillRand2 (arr2, size); printf ("First array: \n"); printArr (arr1, size); printf ("check interval: %d\n\n", checkRand2 (arr1, size)); printf ("Max element: %d\n\n", maxValue (arr1, size)); printf ("Min index: %d\n\n", minIndex (arr1, size)); printf ("Max occurance: %d\n\n", maxOccurance (arr1, size)); printf ("First array: \n"); printArr (arr1, size); printf ("Second array: \n"); printArr (arr2, size); printf ("diff result: %d\n\n", diff (arr1, arr2, res, size)); printf ("res array: \n"); printArr (res, size); add (arr1, arr2, res, size); printf ("Add res: \n"); printArr (res, size); printf ("Greater than or equals: %d\n\n", gteq (arr1, arr2, size)); for (int i = 0; i < size; i++) { arr1[i] = (arr1[i] + 255) % 2; arr2[i] = (arr2[i] + 255) % 2; } printf ("First array: \n"); printArr (arr1, size); printf ("Second array: \n"); printArr (arr2, size); lor (arr1, arr2, res, size); printf ("Lor res: \n"); printArr (res, size); return 0; }
true
fbea2d9fc31133ca9b80bdeca5b63b5ecc22ebad
C++
derlistigelurch/RobotCommander
/MapDisplay/src/MapDisplay.cpp
UTF-8
2,666
2.71875
3
[]
no_license
#include <iostream> #include <fstream> #include "../include/TileTypes.h" #include "../include/Colors.h" #include "../../MessageManager/include/ConfigManager.h" int main() { while(true) { std::string line; std::ifstream pipe(ConfigManager().mapPipe); std::cout << CLEAR; if(!pipe.is_open()) { std::cerr << "ERROR: Unable to read from pipe" << std::endl << std::flush; std::exit(EXIT_FAILURE); } while(getline(pipe, line)) { line = ConfigManager::RemoveNewLine(line); if(line == "shutdown") { pipe.close(); return EXIT_SUCCESS; } for(char &c : line) { switch(c) { case (char) TileTypes::SPAWN: std::cout << ESCAPE << BG_LIGHT_GREEN << SEPARATOR << FG_BLACK << END_ESCAPE << 'G' << RESET; break; case (char) TileTypes::PLAYER: std::cout << ESCAPE << BG_BLACK << SEPARATOR << FG_LIGHT_GREY << END_ESCAPE << c << RESET; break; case (char) TileTypes::ENEMY: std::cout << ESCAPE << BG_RED << SEPARATOR << FG_BLACK << END_ESCAPE << c << RESET; break; case (char) TileTypes::MOUNTAIN: std::cout << ESCAPE << BG_YELLOW << SEPARATOR << FG_BLACK << END_ESCAPE << c << RESET; break; case (char) TileTypes::WATER: std::cout << ESCAPE << BG_BLUE << SEPARATOR << FG_BLACK << END_ESCAPE << c << RESET; break; case (char) TileTypes::GRASS: std::cout << ESCAPE << BG_LIGHT_GREEN << SEPARATOR << FG_BLACK << END_ESCAPE << c << RESET; break; case (char) TileTypes::BUILDING: std::cout << ESCAPE << BG_GREY << SEPARATOR << FG_BLACK << END_ESCAPE << c << RESET; break; case (char) TileTypes::FOREST: std::cout << ESCAPE << BG_GREEN << SEPARATOR << FG_BLACK << END_ESCAPE << c << RESET; break; default: std::cerr << "ERROR: Unrecognised character" << std::endl; exit(EXIT_FAILURE); } } std::cout << std::endl << std::flush; } pipe.close(); } return EXIT_SUCCESS; }
true
798f0c316cc8d9958de1038f78a7540bf07ac2f2
C++
manalikale/Linked-List
/IterativeReversal.cpp
UTF-8
2,047
4.34375
4
[]
no_license
/*Iterative reversal of a linked list Time comlexity:O(n) where n is th enumber of elements in the linked list eg: 1-2-3-4-5->NULL current=1 next=current->next i.e. next=2 current->next=prev i.e. current->next=NULL; prev=current i.e. prev=1 current=next i.e. current=2 Lastly after all the elements are reversed change the head element to prev. */ #include<iostream> using namespace std; /* Link list node */ struct node { int data; struct node* next; }; /* The function removes duplicates from a sorted list */ void reverse(struct node **head) { node *prev=NULL; node *current=*head; node *next=NULL; while(current!=NULL) { next=current->next; current->next=prev; prev=current; current=next; } *head=prev; } /* UTILITY FUNCTIONS */ /* Function to insert a node at the beginging of the linked list */ void push(struct node ** head_ref, int new_data) { /* allocate node */ node* new_node = new node(); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } /* Function to print nodes in a given linked list */ void printList(struct node *node) { while(node!=NULL) { cout <<node->data; node = node->next; } } /* Drier program to test above functions*/ int main() { /* Start with the empty list */ struct node* head = NULL; /* Let us create a sorted linked list to test the functions Created linked list will be 11->11->11->13->13->20 */ push(&head, 2); push(&head, 3); push(&head, 1); push(&head, 4); push(&head, 5); push(&head, 6); printf("Linked list before reversal"); cout<<endl; printList(head); cout<<endl; /* Remove duplicates from linked list */ reverse(&head); printf("Linked list after reversal "); printList(head); cout<<endl; }
true
346ede55236d179d37c84ac00839e7fae2731127
C++
0ashu0/CProgramming
/IMPORTANT PROGRAM/CWP117.CPP
UTF-8
537
3.25
3
[]
no_license
#include<iostream.h> #include<conio.h> void main() { int a[100]; int i,j,n,x,count=0; clrscr(); cout<<"How many elements(not more than 100)="; cin>>n; cout<<"Enter elements="; for(i=0;i<n;i++) cin>>a[i]; cout<<"Enter the elemnt to be deleted="; cin>>x; i=0; while(i<n) { while(i<n&&a[i]!=x) i++; if(i<n) { for(j=i+1;j<n;j++) a[j-1]=a[j]; n--; count++; } } if(count==0) cout<<"Element to be deleted is not present\n"; cout<<"Array contents\n"; for(i=0;i<n;i++) cout<<a[i]<<' '; getch(); }
true
a3e54cc5a5f57fecb15803d5bc1e0c9e0c81635d
C++
JoeriR/comboboy
/src/hitbox.cpp
UTF-8
1,543
3.15625
3
[]
no_license
#ifndef HITBOX_CPP #define HITBOX_CPP #include "hitbox.h" // Doesn't detect collision between attacks and the dummy when the dummy is in the left corner bool collisionUsingOverlap(Hitbox *hitbox1, Hitbox *hitbox2) { bool doesWidthOverlap = (hitbox1->x <= (hitbox2->x + hitbox2->width)) && ((hitbox1->x + hitbox1->width) >= hitbox2->x); bool doesHeightOverlap = (hitbox1->y <= (hitbox2->y + hitbox2->height)) && ((hitbox1->y + hitbox1->height) >= hitbox2->y); return doesWidthOverlap && doesHeightOverlap; } // Doesn't detect collision when the dummy is in the middle huge hitbox that is bigger than the dummy itself bool collisionWithCornersOnly(Hitbox *hitbox1, Hitbox *hitbox2) { bool result = isPointInBox(hitbox1->x, hitbox1->y, hitbox2) || isPointInBox(hitbox1->x + hitbox1->width, hitbox1->y, hitbox2) || isPointInBox(hitbox1->x, hitbox1->y + hitbox1->height, hitbox2) || isPointInBox(hitbox1->x + hitbox1->width, hitbox1->y + hitbox1->height, hitbox2); return result; } bool isPointInBox(uint8_t x, uint8_t y, Hitbox *hitbox) { if (x >= hitbox->x && x <= hitbox->x + hitbox->width) if (y >= hitbox->y && y <= hitbox->y + hitbox->height) return true; return false; } // Both collision fuctions have quirks, so call them both to get working collisions in any situation bool collision(Hitbox *hitbox1, Hitbox *hitbox2) { return collisionWithCornersOnly(hitbox1, hitbox2) || collisionUsingOverlap(hitbox1, hitbox2); } #endif
true
5d8dfab0f61822842a7fa3a42ec6ca7530c943ac
C++
Westblat/Settlers
/src/gamewindow.h
UTF-8
2,341
2.578125
3
[]
no_license
#ifndef GAMEWINDOW_H #define GAMEWINDOW_H #include <QWidget> #include <QPushButton> #include <QtWidgets> #include <QGraphicsScene> #include <QGraphicsView> #include <QTimer> #include <QLabel> #include <QString> #include <QGraphicsPixmapItem> #include <QMouseEvent> #include "game.h" #include "map.h" #include "terrainitem.h" #include "buildingitem.h" #include "settleritem.h" #include "buildmenuicon.h" #include "cmdmenuicon.h" /* Imagefiles taken from kenney.nl and other "free use"-places! Most are slightly modified. */ class Map; //window showing the actual game //opens when new game is started from main menu class GameWindow : public QWidget { Q_OBJECT public: explicit GameWindow(QWidget *parent = 0); void draw_terrain(QGraphicsScene* scene); void draw_buildings(QGraphicsScene* scene); void draw_settlers(QGraphicsScene* scene); QGraphicsScene *scene; QGraphicsView *view; QGraphicsScene *buildscene; QGraphicsView *buildview; QGraphicsScene *commandscene; QGraphicsView *commandview; bool buildmode; int newBuildingType = -1; bool commandmode; int selectedSettler = -1; private: Game game; // creates the game Map map = game.getMap(); int width = map.get_width(); int height = map.get_height(); std::vector<std::vector<Terrain*>> terrain_map = map.get_map(); std::vector<Building*> buildings; std::vector<BuildingItem*> buildingitems; std::vector<Settler*> settlers; std::vector<SettlerItem*> settleritems; std::vector<TerrainItem*> terrainitems; int tilesize = 64; // images used are 64x64 pixels int refresh_time = 400; // milliseconds, after how much time locations update on screen, 100 ms = 10 fps QPushButton *menu_button; public slots: void ShowMainMenu(); void refresh(); // refreshes building- and settlervectors void moveSettlers(); // moves the settlers void refreshBuildings(); // checks readiness of buildings and changes image accordingly void selectBuildingType(int type); // sets buildmode to true, selects the type of building void getSiteLocation(int x, int y); // builds a new building in the left-clicked location void cancel(); // sets both modes to false void giveCommand(int n); // selects a settler void selectCommand(int cmd); // selects the command and gives this command to the selected settler }; #endif
true
b539d3ec08f7fbb4e805a0ba890e71024dace28c
C++
sfox33/ITCS-6114---Algorithms-and-Data-Structures
/Prime Factorizer/PrimeFactorizer.h
UTF-8
328
2.703125
3
[]
no_license
#ifndef PRIMEFACTORIZER_H #define PRIMEFACTORIZER_H #include <vector> class PrimeFactorizer { public: PrimeFactorizer(); virtual ~PrimeFactorizer(); void factorize(int num); bool isPrime(int num); protected: private: std::vector<int> primes; }; #endif // PRIMEFACTORIZER_H
true
2fe7f2e58f4d4604630ba819b9f23f5a1bc9aa60
C++
skiry/Highschool
/latime-liste/main.cpp
UTF-8
841
2.578125
3
[]
no_license
#include <fstream> using namespace std; ifstream f("date.in"); ofstream g("date.out"); struct nod{int nr; nod *urm;}; int c[100],n,i,j,viz[100],u,p1,prim; nod *l[100]; void parc() { nod *p; if(prim<=u) { g<<prim<<" "<<u<<endl; p=l[c[prim]]; while(p) { if(!viz[p->nr]) u++, c[u]=p->nr, viz[p->nr]++; p=p->urm; } prim++; parc(); } } int main() { nod *p=0,*q=0; f>>n; while(f>>i>>j) { p=new nod; p->nr=j; p->urm=l[i]; l[i]=p; q=new nod; q->nr=i; q->urm=l[j]; l[j]=p; } f>>p1; c[1]=p1; viz[p1]=1; u=1; prim=1; parc(); for(i=1;i<=u;i++) g<<c[i]<<" "; return 0; }
true
46e28936135f64d6c467c403f6b24f56f73579c8
C++
Knothe/DungeonTextGame
/ProyectoFinal/DungeonGame/PlayerSaver.h
UTF-8
629
2.953125
3
[]
no_license
#pragma once #include <vector> #include <array> using std::vector; using std::array; struct PlayerSaver { int room_id; int sword; int shield; vector<int> key_list; int life; int rooms_passed; int mana; short bosses_defeated; array<short, 4> loot_list; void operator=(PlayerSaver other){ room_id = other.room_id; sword = other.sword; shield = other.shield; key_list = other.key_list; life = other.life; rooms_passed = other.rooms_passed; mana = other.mana; bosses_defeated = other.bosses_defeated; for (int i = 0; i < 4; i++) loot_list[i] = other.loot_list[i]; } };
true
5d64c49f8a3bd528cabfe21828431090fd1169ad
C++
ThatBeanBag/Slimfish
/Robotron/Source/DirectX9Framework/Events/EventData_Collision.h
UTF-8
1,455
2.6875
3
[ "Apache-2.0" ]
permissive
// // Bachelor of Software Engineering // Media Design School // Auckland // New Zealand // // (c) 2005 - 2015 Media Design School // // File Name : EventData_Collision.h // Description : CEventData_Collision declaration file. // Author : Hayden Asplet. // Mail : hayden.asplet@mediadesignschool.com // #pragma once #ifndef __EVENTDATA_COLLISION_H__ #define __EVENTDATA_COLLISION_H__ // Library Includes // Local Includes #include "EventData.h" class CEventData_Collision : public IEventData { // Member Functions public: CEventData_Collision(); CEventData_Collision(TActorID _actorID1, TActorID _actorID2, const CVec3& _krvec3SumForceNormal, const CVec3& _krvec3SumFrictionForce, const std::vector<CVec3>& _krvecCollisionPoints); virtual ~CEventData_Collision(); TActorID GetActorID1() const; TActorID GetActorID2() const; const CVec3 GetSumForceNormal() const; const CVec3 GetSumFrictionForce() const; const std::vector<CVec3> GetCollisionPoints() const; virtual void VSerialise(std::ostringstream& outStream) override; virtual void VDeserialise(std::istringstream& inStream) override; virtual TEventTypeID VGetEventTypeID() const override; protected: private: // Member Variables public: static const TEventTypeID s_kEVENT_TYPE_ID; protected: private: TActorID m_actorID1; TActorID m_actorID2; CVec3 m_vec3SumForceNormal; CVec3 m_vec3SumFrictionForce; std::vector<CVec3> m_vecCollisionPoints; }; #endif // __EVENTDATA_COLLISION_H__
true
832c8ece90b5a1eccb00fe9e873416fcccd104f6
C++
aayn/myNEAT
/crossover_test.cpp
UTF-8
1,687
2.6875
3
[]
no_license
#include <iostream> #include <vector> #include <ctime> #include <cstdlib> #include <cstdio> #include "genome.h" #include "organism.h" #include "innovation.h" using namespace std; int MAX_NEURONS, INIT_NEURONS; int main() { srand(static_cast<unsigned> (time(0))); MAX_NEURONS = 100; INIT_NEURONS = 5; Organism dog; dog.init_pop(2); dog.genomes[0].add_init_neuron(0, 0.0f, 0.0f); dog.genomes[0].add_init_neuron(0, 1.0f, 0.0f); dog.genomes[0].add_init_neuron(1, 0.0f, 1.0f); dog.genomes[0].add_init_neuron(1, 0.0f, 1.0f); dog.genomes[0].add_init_neuron(1, 0.0f, 1.0f); dog.genomes[1].add_init_neuron(0, 0.0f, 0.0f); dog.genomes[1].add_init_neuron(0, 1.0f, 0.0f); dog.genomes[1].add_init_neuron(1, 0.0f, 1.0f); dog.genomes[1].add_init_neuron(1, 0.0f, 1.0f); dog.genomes[1].add_init_neuron(1, 0.0f, 1.0f); for(int i = 0; i < 40; ++i) { dog.genomes[0].mutate_add_axon(); dog.genomes[0].mutate_add_axon(); dog.genomes[0].mutate_add_axon(); dog.genomes[0].mutate_add_neuron(); dog.genomes[1].mutate_add_axon(); dog.genomes[1].mutate_add_axon(); dog.genomes[1].mutate_add_axon(); dog.genomes[1].mutate_add_neuron(); } dog.genomes[0].print_genome(); cout << "--------------------------------------------------------------\n\n"; dog.genomes[1].print_genome(); cout << "--------------------------------------------------------------\n\n"; printf("Mom fitness = %lf ; Dad fitness = %lf\n", dog.genomes[0].get_fitness(), dog.genomes[1].get_fitness()); cout << "--------------------------------------------------------------\n\n"; crossover(dog.genomes[0], dog.genomes[1]).print_genome(); return 0; }
true
1d11f829ea35650168f1c28cea264271edc0cab4
C++
Kamil96/ProjektSokoban
/Sokoban2/Sokoban2/Sokoban2/Licznik.h
UTF-8
679
3
3
[]
no_license
#pragma once #include <SFML/Graphics.hpp> class Licznik : public sf::Drawable { public: Licznik(const std::string& prefixText, const sf::Vector2f& position, const sf::Font& font); Licznik operator++(int); Licznik operator--(int); void reset(); std::string toString() { return std::to_string(liczba); } private: int liczba; sf::Text text; std::string prefixText; void update() { text.setString(prefixText + std::to_string(liczba)); //update wartosci w wyswietlanym w grze tekscie } virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const { //dziedziczenie metody draw() po klasie sf::Rendertarget target.draw(text); } };
true
f6f8a64047e5b7ec876ce29a6c305b26121f43f9
C++
morell5/HSE-Course
/seminars/seminar12/3.cpp
UTF-8
214
2.546875
3
[]
no_license
#include <iostream> #include <vector> namespace std { template<typename T, typename Arg> unique_ptr<T> make_unique(Arg&& arg) { return unique_ptr<T>(new T(std::forward<Arg>(arg))); } } int main() { }
true
ef02d170a5ec8f5c158c21e0b40ce2821cd300f9
C++
karikera/ken
/KR3/util/serializer.h
UTF-8
6,931
2.734375
3
[]
no_license
#pragma once #include <KR3/main.h> #include <KR3/math/coord.h> #include <vector> namespace kr { template <typename OS> class Serializer; template <typename IS> class Deserializer; namespace _pri_ { template <typename T, bool is_class> struct BaseSerialize; template <typename T> struct BaseSerialize<T, true> { template <typename S> inline static void serialize(T& dest, S & serializer) { dest.serialize(serializer); } }; template <typename T> struct BaseSerialize<T, false> { template <typename S> inline static void serialize(T& dest, S & serializer) { serializer.raw(dest); } }; } template <typename T> struct Serialize : _pri_::BaseSerialize<T, std::is_class<T>::value> { }; template <typename C> struct Serialize<Array<C>> { template <typename S> inline static void serialize(Array<C>& dest, S & s) { s.serializeSize(&dest); for (C & c : dest) s & c; } }; template <typename C> struct Serialize<View<C>> { template <typename S> inline static void serialize(View<C>& dest, S & s) { s.reference(dest); } }; template <typename C> struct Serialize<std::vector<C>> { template <typename S> inline static void serialize(std::vector<C>& dest, S & s) { s.serializeSize(&dest); for (C & c: dest) s & c; } }; template <typename C, size_t count, bool aligned, typename order> struct Serialize<math::vector<C, count, aligned, order>> { template <typename S> inline static void serialize(math::vector<C, count, aligned, order>& dest, S & s) { s.raw(dest); } }; template <typename C> struct Serialize<std::basic_string<C>> { template <typename S> inline static void serialize(std::basic_string<C>& dest, S & s) { s.serializeSize(&dest); for (C & c : dest) s & c; } }; template <typename C, size_t size> struct Serialize<C[size]> { template <typename S> inline static void serialize(C(&dest)[size], S & serializer) { for (C & c : dest) { serializer & dest; } } }; class SerializedSizer { private: size_t m_size; public: static constexpr bool read = true; static constexpr bool write = false; inline SerializedSizer() noexcept { m_size = 0; } template <typename T> inline void raw(T &) noexcept { m_size += sizeof(T); } template <typename T> inline void serializeSize(T * buffer) { size_t sz = buffer->size(); if(sz == 0) m_size ++; else m_size += math::plog2(sz) / 7 + 1; } template <typename T> inline SerializedSizer& operator &(T & t) { Serialize<T>::serialize(t, *this); return *this; } template <typename T> inline SerializedSizer& operator <<(T & t) { Serialize<T>::serialize(t, *this); return *this; } template <typename T> inline SerializedSizer& operator >>(T & t) { Serialize<T>::serialize(t, *this); return *this; } size_t size() const noexcept { return m_size; } template <typename T> static size_t getSize(const T & value) { SerializedSizer sizer; sizer & const_cast<T&>(value); return sizer.m_size; } }; template <class OS> class Serializer { using Component = typename OS::Component; static_assert(sizeof(typename OS::InternalComponent) == 1, "sizeof Component != 1"); private: OS * const m_os; public: static constexpr bool read = false; static constexpr bool write = true; inline Serializer(OS * os) noexcept :m_os(os) { } OS * stream() const noexcept { return m_os; } template <typename T> inline void raw(T & t) { m_os->write((Component*)&t, sizeof(T)); } inline void leb128(dword value) { m_os->writeLeb128(value); } inline void leb128(qword value) { m_os->writeLeb128(value); } inline void kr_leb128(dword value) { byte out; while (value >= 0x80) { out = (byte)(value & 0x7f); m_os->write((Component*)&out, 1); value >>= 7; } out = (byte)(value | 0x80); m_os->write((Component*)&out, 1); } inline void kr_leb128(qword value) { byte out; while (value >= 0x80) { out = (byte)(value) & 0x7f; m_os->write((Component*)&out, 1); value >>= 7; } out = (byte)(value) | 0x80; m_os->write((Component*)&out, 1); } template <typename C> inline void reference(const C* ref, size_t sz) { copy(ref, sz); } template <typename C> inline void copy(const C* p, size_t sz) { sz *= sizeof(C); if (m_os->write((Component*)p, sz) != sz) throw NotEnoughSpaceException(); } template <typename C> inline void reference(View<C> &ref) { size_t sz = ref.size(); kr_leb128(sz); reference(ref, sz); } template <typename C> inline void reference(View<C> &ref, size_t sz) { copy(ref.data(), sz); } template <typename T> inline void serializeSize(T * buffer) { kr_leb128(buffer->size()); } template <typename T> inline Serializer& operator &(const T & t) { Serialize<T>::serialize((T&)t, *this); return *this; } template <typename T> inline Serializer& operator <<(const T & t) { Serialize<T>::serialize((T&)t, *this); return *this; } }; template <class IS> class Deserializer { using Component = typename IS::Component; static_assert(sizeof(typename IS::InternalComponent) == 1, "sizeof Component != 1"); private: IS * const m_is; public: static constexpr bool read = true; static constexpr bool write = false; inline Deserializer(IS * is) noexcept : m_is(is) { } IS * stream() const noexcept { return m_is; } template <typename T> inline void raw(T & t) { m_is->read((Component*)&t, sizeof(T)); } inline void leb128(dword &value) { value = m_is->readLeb128(); } inline void leb128(qword &value) { value = m_is->readLeb128_64(); } inline void kr_leb128(dword & value) { value = m_is->readLeb128_kr(); } inline void kr_leb128(qword & value) { value = m_is->readLeb128_kr64(); } template <typename C> inline void reference(const C* &ref, size_t sz) { ref = (C*)m_is->begin(); m_is->addBegin(sz * sizeof(C)); } template <typename C> inline void copy(C* p, size_t sz) { sz *= sizeof(C); if (m_is->read((Component*)p, sz) != sz) throw EofException(); } template <typename C> inline void reference(View<C> &ref) { size_t sz; kr_leb128(sz); reference(ref, sz); } template <typename C> inline void reference(View<C> &ref, size_t sz) { const C * beg; reference(beg, sz); ref = View<C>(beg, sz); } template <typename T> inline void serializeSize(T * buffer) { size_t sz; kr_leb128(sz); buffer->resize(sz); } template <typename T> inline Deserializer& operator &(T & t) { Serialize<T>::serialize(t, *this); return *this; } template <typename T> inline Deserializer& operator >>(T & t) { Serialize<T>::serialize(t, *this); return *this; } }; }
true
f6ce40bd5ce1ea3c42a6544efe23f22ea07d3236
C++
jaumeMA/CommAlg
/YTL/types/smartPtr/reference_counter.h
UTF-8
3,799
2.765625
3
[]
no_license
#pragma once #include "Utils/cMacroHelper.h" #include <atomic> #include <cstddef> #ifdef _DEBUG #define LENT_WITH_LOGIC #endif namespace yame { namespace ytl { enum class Policy { Shared, Unique }; class lent_reference_counter { #ifdef LENT_WITH_LOGIC public: lent_reference_counter() : m_numWeakReferences(0) { } lent_reference_counter(const lent_reference_counter& other) : m_numWeakReferences(other.m_numWeakReferences.load()) { } size_t incrementWeakReference() { size_t currNumReferences = 0; do { currNumReferences = m_numWeakReferences.load(); } while(m_numWeakReferences.compare_exchange_weak(currNumReferences,currNumReferences+1) == false); return currNumReferences+1; } size_t decrementWeakReference() { size_t currNumReferences = 0; do { currNumReferences = m_numWeakReferences.load(); } while(m_numWeakReferences.compare_exchange_weak(currNumReferences,currNumReferences-1) == false); return currNumReferences-1; } size_t getNumWeakReferences() const { return m_numWeakReferences.load(); } bool hasWeakReferences() const { return m_numWeakReferences.load() > 0; } private: std::atomic<size_t> m_numWeakReferences; #endif }; template<Policy> class reference_counter; //reference counting for shared references template<> class reference_counter<Policy::Shared> : public lent_reference_counter { public: reference_counter() : m_numReferences(0) { } reference_counter(const reference_counter& other) : m_numReferences(other.m_numReferences.load()) { } ~reference_counter() { } size_t incrementReference() { size_t currNumReferences = 0; do { currNumReferences = m_numReferences.load(); } while(m_numReferences.compare_exchange_weak(currNumReferences,currNumReferences+1) == false); return currNumReferences+1; } size_t decrementReference() { size_t currNumReferences = 0; do { currNumReferences = m_numReferences.load(); } while(m_numReferences.compare_exchange_weak(currNumReferences,currNumReferences-1) == false); return currNumReferences-1; } size_t getNumReferences() const { return m_numReferences.load(); } bool hasReferences() const { return m_numReferences.load() > 0; } private: std::atomic<size_t> m_numReferences; }; //reference counting for unique references template<> class reference_counter<Policy::Unique> : public lent_reference_counter { public: reference_counter() : m_numStrongReferences(0) { } reference_counter(const reference_counter& other) : m_numStrongReferences(other.m_numStrongReferences.load()) { } ~reference_counter() { } size_t incrementStrongReference() { size_t currNumReferences = 0; do { currNumReferences = m_numStrongReferences.load(); } while(m_numStrongReferences.compare_exchange_weak(currNumReferences,currNumReferences+1) == false); return currNumReferences+1; } size_t decrementStrongReference() { size_t currNumReferences = 0; do { currNumReferences = m_numStrongReferences.load(); } while(m_numStrongReferences.compare_exchange_weak(currNumReferences,currNumReferences-1) == false); return currNumReferences-1; } size_t getNumStrongReferences() const { return m_numStrongReferences.load(); } bool hasStrongReferences() const { return m_numStrongReferences.load() > 0; } private: std::atomic<size_t> m_numStrongReferences; }; typedef reference_counter<Policy::Shared> shared_reference_counter; typedef reference_counter<Policy::Unique> unique_reference_counter; } }
true
1a851afd6b67c1e4fc12f4f83fea20718c031c35
C++
sergiodrm/Trabajo-Informatica
/nave.cpp
UTF-8
1,469
3.34375
3
[]
no_license
#include "nave.h" Nave::nave() { vida = 50; escudo = 20; ataque = 4; ataque_especial = 4; pos.first = 0; pos.second = 0; } Nave::Nave(int vid, int esc, int ataq, int ataq_es, pair<int, int> pos ){ vida = vid; escudo = esc; ataque = ataq; ataque_especial = ataq_es; this->pos.first = pos.first; this->pos.second = pos.second; } // Metodos GET int Nave::getVida(){ return vida; } int Nave::getAtaque(){ return ataque; } int Nave::getAtaque_especial(){ return ataque_especial; } int Nave::getEscudo(){ return escudo; } pair <int,int> getPos(){ return std::make_pair(pos.first, pos.second); } // Metodos SET void Nave::setVida(int value){ this->vida = value; } void Nave::setAtaque(int value){ this->ataque = value; } void Nave::setAtaque_especial(int value){ this->ataque_especial = value; } void Nave::setEscudo(int value){ this->escudo = value; } void Nave::setPos(pair<int, int> value){ this->pos = make_pair(value.first,value.second); } void Nave::mover(char mov){ //Según el string, se modifica la posición de la nave en una de las 4 posibles direcciones if (mov == "w" || mov == "W"); this->pos.second++; if ((mov == "s" || mov == "S")); this->pos.second--; if ((mov == "d" || mov == "D")); this->pos.first++; if (mov == "a" || mov == "A"); this->pos.second--; }
true
0a2f58e2c9fe7655fefa7d5505f2b5f56e620961
C++
qannoufoualid/HapticGolf
/wall.cpp
UTF-8
344
2.90625
3
[]
no_license
#include "wall.h" Wall::Wall(Point firstPt, Point secondPt, WallType type) : m_firstPt(firstPt), m_secondPt(secondPt), m_wallType(type) { } Wall::~Wall() { } Point Wall::getFirstPoint() { return m_firstPt; } Point Wall::getSecondPoint() { return m_secondPt; } WallType Wall::getWallType() { return m_wallType; }
true
db8b0c37be67abff89027a7a68aa1bf1d45ce57f
C++
gerald-guiony/ESPCoreExtension
/src/Tools/Delegate.h
UTF-8
1,944
2.875
3
[ "MIT" ]
permissive
//************************************************************************************************************************ // Delegate.h // Version 1.0 April, 2019 // Author Gerald Guiony //************************************************************************************************************************ #pragma once #include <functional> //#include <mutex> #include <memory> #include <map> using namespace std::placeholders; using FunctionId = size_t; template <typename ...Args> class Delegate { protected: using fn_t = std::function <void(Args ...args)>; // std::shared_ptr<std::recursive_mutex> _m; =========> Useless mutex (No thread) FunctionId _guid{ 0 }; std::map <FunctionId, fn_t> _delegates; public: Delegate () {} Delegate (const Delegate &d) { _delegates = d._delegates; } Delegate& operator = (const Delegate &d) { _delegates = d._delegates; return *this; } ~Delegate () { clear(); } void operator() (Args ...args) { notify(args...); } operator bool() { return _delegates.size() != 0; } Delegate& operator = (fn_t fn) { clear(); push_back(fn); return *this; } FunctionId push_back (fn_t fn) { _delegates.insert(std::make_pair(++_guid, fn)); return _guid; } FunctionId operator+= (fn_t fn) { return push_back(fn); } Delegate& operator-= (FunctionId id) { remove(id); return *this; } void remove (FunctionId ind) { _delegates.erase(ind); } void clear () { _delegates.clear(); } inline void notify (Args ...args) { if (!_delegates.size()) return; auto it = _delegates.begin(); while (it != _delegates.end()) { auto curr = it++; curr->second(args...); } } };
true
9d1621bf61e4ac1bd16a2eb275eea7fff4620b99
C++
luckylove/first
/icpc5.cpp
UTF-8
1,659
2.6875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int main() { int test,a,b,c,i,j,k,n,m; cin>>test; while(test--) { cin>>n>>k; int arr[n]; for(i=0;i<n;i++) { cin>>arr[i]; } sort(arr,arr+n); int start=0; int endd=0; for(i=0;i<n-1;i++) { if(arr[i]>k) { start=i; break; } } if(start!=n-1) { // then we need to find out the endd int diff=0; endd=n-2; // endd is the n-2 elements accordingly for it //cout<<"start"<<start<<endl; //cout<<"endd"<<endd<<endl; while(start!=endd) { if(arr[start]-k<=arr[endd]-k) { diff=arr[start]-k; arr[start]-=diff; arr[endd]-=diff; start++; } else { diff=arr[endd]-k; arr[start]-=diff; arr[endd]-=diff; endd--; } // cout<<"start here is "<<start<<"arr[starti s]"<<arr[start]<<endl; // cout<<"endd here is "<<endd<<"arr[endds] sis "<<arr[endd]<<endl; } // means here the start is equal to endd diff=arr[start]-k; arr[n-1]-=diff; arr[start]-=diff; cout<<accumulate(arr,arr+n,0)<<endl; } else { cout<<accumulate(arr,arr+n,0)<<endl; } } }
true
61167b957772a7b83d4c5a511f6457d526cd4049
C++
michaeljrosa/stewart-platform
/src/StewartPlatform/StewartPlatform.ino
UTF-8
3,023
2.828125
3
[]
no_license
/** * stewart-platform * * Authors: Leroy Sibanda, Michael Rosa * Date: August 2018 * * Program to test and calibrate an Stewart platform based on an Arduino Mega and motor drivers */ #include "configuration.h" #include "Actuator.h" #include "Platform.h" #include "eeprom.h" int count2 = 0; #if DEMO > 0 float positions[][6] = { {0,0,0,0,0,0}, {0,0,15,0,0,0}, {0,-5,5,0,0,0}, {0,5 ,5,0,0,0}, {-5,0,5,0,0,0}, {5,0,5,0,0,0}, {0,0,10,-1,0,0}, {0,0,10,1,0,0}, {0,0,5,0,-1,0}, {0,0,5,0,1,0}, {0,0,10,0,0,-1}, {0,0,10,0,0,1}, }; #else #define POINTS 20 #endif // ------ main program ------ // Platform platform; void setup() { Serial.begin(9600); // set the analog ref (5V regulator) analogReference(EXTERNAL); pinMode(SHDN_BTN, INPUT_PULLUP); platform.setup(); #if VERBOSE > 0 Serial.println("Actuator info"); for (int i = 0; i < NUM_ACTUATORS; i++) { Serial.print("Actuator "); Serial.print(i); Serial.print(" position: "); Serial.println(platform.getActuatorPosition(i)); Serial.print("min: "); Serial.println(platform.getActuatorMinPosition(i)); Serial.print("max: "); Serial.println(platform.getActuatorMaxPosition(i)); Serial.print("target: "); Serial.println(platform.getActuatorTarget(i)); Serial.print("ready: "); Serial.println(platform.isActuatorReady(i)); Serial.println(); } #endif #if GRAPH > 0 // print the min and max positions of each actuator for (int i = 0; i < NUM_ACTUATORS; i++) { Serial.print(platform.getActuatorMaxPosition(i)); Serial.print(','); } Serial.println(); for (int i = 0; i < NUM_ACTUATORS; i++) { Serial.print(platform.getActuatorMinPosition(i)); Serial.print(','); } Serial.println(); Serial.println(); #endif } void loop() { if(digitalRead(SHDN_BTN) == LOW) { platform.retract(); } else { #if DEMO > 0 if (platform.isPlatformReady()) { platform.setPlatformPosition(positions[count2]); count2++; if (count2 >= sizeof(positions) / NUM_ACTUATORS / sizeof(int)) { count2 = 0; } } #else if (platform.isPlatformReady()) { float ratio = (float)count2 / POINTS; float p[] = {5*cos(TWO_PI * ratio), 5*sin(TWO_PI * ratio), 5*sin(TWO_PI * ratio * 3)+6, 0.5*sin(TWO_PI * ratio),0.5*cos(TWO_PI * ratio),0.33*sin(TWO_PI * ratio)}; platform.setPlatformPosition(p); count2++; if (count2 > POINTS) { count2 = 0; } } #endif } platform.loop(); #if GRAPH > 0 // print the current raw and filtered positions of each actuator for (int i = 0; i < NUM_ACTUATORS; i++) { Serial.print(platform.getActuatorPosition(i)); Serial.print(','); Serial.print(platform.getActuatorRawPosition(i)); Serial.print(','); } Serial.println(); #endif }
true
3dd3d3d6d026dbc70bc0f240ff8119b5449ef57c
C++
RangooDu/LeetCode
/WordSearch.cpp
UTF-8
1,483
2.75
3
[ "MIT" ]
permissive
class Solution { public: bool inBoard(const vector<vector<char>> &board, int x, int y) { return x >= 0 && x < board.size() && y >= 0 && y < board[0].size(); } bool search(const vector<vector<char>> &board, int x, int y, int now, const string &word, vector<vector<bool>> &used) { if (now == word.length()) return true; for (int i = 0; i < dirs.size(); i++) { int nx = x + dirs[i][0]; int ny = y + dirs[i][1]; if (!inBoard(board, nx, ny)) continue; if (used[nx][ny] || word[now] != board[nx][ny]) continue; used[nx][ny] = true; if (search(board, nx, ny, now + 1, word, used)) return true; used[nx][ny] = false; } return false; } bool exist(vector<vector<char>>& board, string word) { if (word.length() == 0) return true; int n = board.size(); if (n == 0) return false; int m = board[0].size(); vector<vector<bool>> used(n, vector<bool>(m, false)); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (board[i][j] != word[0]) continue; used[i][j] = true; if (search(board, i, j, 1, word, used)) return true; used[i][j] = false; } } return false; } private: static vector<vector<int>> dirs; }; vector<vector<int>> Solution::dirs{{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
true