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
6b00d62b38615d2474b97d225710f3362b56b222
C++
SeanCarlson91/Portfolio
/C++ Examples/Paycheck Calculator/Paycheck Calculator/Paycheck Calculator.cpp
UTF-8
6,450
3.59375
4
[]
no_license
/* This program is meant give me a rough estimate of what my monthly income will be after taxes and pre-tax deductions for a range of potential salaries. */ #include "pch.h" #include <iostream> #include <string> #include <cstdlib> //Containers #include <list> //Just in case there's a use for multithreading here. #include <thread> using namespace std; //Checks Income and sets the appropriate tax bracket. //Currently has 2019 single filer numbers since they're most relevant to me. float FedTaxBrackets(float m_Income, float m_fedTaxTotal); int main() { list<float> annualSalary; list<float>::iterator iter; int Limit = 20; float Income = 30000.0; float StateIncTaxRate = 0.051f; //Massachusetts income tax rate. cout << "Input low-range annual salary: "; cin >> Income; cout << endl; cout << "Salaries will be counted in units of 1000.\nInput how many salaries to calculate:"; cin >> Limit; cout << endl; //Pretax Deductions float MedicalIns, DentalIns, VisionIns, F01k, LongTermDisability, LifeIns, CommuterPlan, FSA, HSA = 0; cout << "Input any pre-tax deductions as an exact value: " << endl; cout << "Medical Insurance: "; cin >> MedicalIns; cout << endl; cout << "Dental Insurance: "; cin >> DentalIns; cout << endl; cout << "Vision Insurance: "; cin >> VisionIns; cout << endl; cout << "401k: "; cin >> F01k; cout << endl; cout << "Long Term Disability: "; cin >> LongTermDisability; cout << endl; cout << "Life Insurance: "; cin >> LifeIns; cout << endl; cout << "Commuter Plan: "; cin >> CommuterPlan; cout << endl; cout << "FSA: "; cin >> FSA; cout << endl; cout << "HSA: "; cin >> HSA; cout << endl; /** * Fills a list with the pre-deduction salaries and output what will be calculated. */ for (int i = 0; i < Limit; i++) { float Incriment = 1000.0; Income = Income + Incriment; annualSalary.push_back(Income); } cout << "Calculating monthly income for the following salaries: \n"; for (iter = annualSalary.begin(); iter != annualSalary.end(); iter++) { cout << *iter << endl; } //Pretax deductions. Calculates amount to deduct and inserts the result into a new list. list<float> annualIncomeAfterPreTax; cout << "Calculating pre-tax deductions\n"; for (iter = annualSalary.begin(); iter != annualSalary.end(); iter++) { float result = 0; result = *iter - MedicalIns - DentalIns - VisionIns - F01k - LongTermDisability - LifeIns - CommuterPlan - FSA - HSA; annualIncomeAfterPreTax.push_back(result); } for (iter = annualIncomeAfterPreTax.begin(); iter != annualIncomeAfterPreTax.end(); iter++) { cout << *iter << endl; } //Now that pre-tax deductions have been subtracted from the salaries it's time to calculate the taxes. list<float>annualIncomeAfterTaxes; for (iter = annualIncomeAfterPreTax.begin(); iter != annualIncomeAfterPreTax.end(); iter++) { float fedTaxTotal = 0; fedTaxTotal = FedTaxBrackets(*iter, fedTaxTotal); float stateTaxTotal = *iter * StateIncTaxRate; float result = 0; result = *iter - fedTaxTotal - stateTaxTotal; annualIncomeAfterTaxes.push_back(result); } cout << "Annual Income after taxes\n\n"; for (iter = annualIncomeAfterTaxes.begin(); iter != annualIncomeAfterTaxes.end(); iter++) { cout << *iter << endl; } /* Takes the final annual income values and divides by 12 to give a rough approximation of the monthly income. */ list<float>MonthlyIncome; for (iter = annualIncomeAfterTaxes.begin(); iter != annualIncomeAfterTaxes.end(); iter++) { float result = 0; result = *iter / 12; MonthlyIncome.push_back(result); } for (iter = MonthlyIncome.begin(); iter != MonthlyIncome.end(); iter++) { cout << "Monthly income after taxes: " << *iter << endl; } } /* Checks Income and calculates total federal taxes for the appropriate tax bracket range. Currently has 2019 tax bracket numbers. Future goal: make it possible to input, save and loan tax bracket numbers instead of hard coding the tax brackets. */ float FedTaxBrackets(float m_Income, float m_fedTaxTotal) { float firstBracket = 0; const float Bracket1_Range1 = 0, Bracket1_Range2 = 9700; if (m_Income > Bracket1_Range1 && m_Income <= Bracket1_Range2) { firstBracket = (m_Income * 0.10f); } if (m_Income >= Bracket1_Range2) { firstBracket = (Bracket1_Range2 * 0.10f); } float secondBracket=0; const float Bracket2_Range1 = 9701, Bracket2_Range2 = 39475; if (m_Income >= Bracket2_Range1 && m_Income <= Bracket2_Range2) { float localHolder = m_Income - Bracket2_Range1; secondBracket = (localHolder *= 0.12f); } if (m_Income > Bracket2_Range2) { secondBracket = (Bracket2_Range2 - Bracket2_Range1) * 0.12f; } ; float thirdBracket=0; const float Bracket3_Range1 = 39476, Bracket3_Range2 = 84200; if (m_Income >= Bracket3_Range1 && m_Income <= Bracket3_Range2) { float localHolder = m_Income - Bracket3_Range1; thirdBracket = localHolder *= 0.22f; } if (m_Income > Bracket3_Range2) { thirdBracket = ((Bracket3_Range2 - Bracket3_Range1)*0.22f); } float fourthBracket = 0; const float Bracket4_Range1 = 84201, Bracket4_Range2 = 160725; if (m_Income >= Bracket4_Range1 && m_Income <= Bracket4_Range2) { float localHolder = m_Income - Bracket4_Range1; fourthBracket = (localHolder *= 0.24f); } if (m_Income > Bracket4_Range2) { fourthBracket = ((Bracket4_Range2 - Bracket4_Range1)*0.24f); } float fifthBracket = 0; const float Bracket5_Range1 = 160726, Bracket5_Range2 = 204100; if (m_Income >= Bracket5_Range1 && m_Income <= Bracket5_Range2) { float localHolder = m_Income - Bracket5_Range1; fifthBracket = (localHolder *= 0.32f); } if (m_Income > Bracket5_Range2) { fifthBracket = ((Bracket5_Range2 - Bracket5_Range1)*0.32f); } float sixthBracket = 0; const float Bracket6_Range1 = 204401, Bracket6_Range2 = 510300; if (m_Income >= Bracket6_Range1 && m_Income <= Bracket6_Range2) { float localHolder = m_Income - Bracket6_Range1; sixthBracket = (localHolder *= 0.35f); } if (m_Income > Bracket6_Range2) { sixthBracket = ((Bracket6_Range2 - Bracket6_Range1)*0.35f); } float seventhBracket = 0; const float Bracket7_Range1 = 501301; if (m_Income >= Bracket7_Range1) { float localHolder = m_Income - Bracket7_Range1; seventhBracket = (localHolder *= 0.37f); } m_fedTaxTotal = firstBracket + secondBracket + thirdBracket + fourthBracket + fifthBracket + sixthBracket + seventhBracket; return m_fedTaxTotal; }
true
0507215298f73e4775614eef639a3bbdf8dcec49
C++
B4c0nStr1ps/error-handling
/main.cpp
UTF-8
2,725
4
4
[ "MIT" ]
permissive
#include <iostream> #include <string> #include "result.h" /* * When a function needs to return a value or an error you can use the * bs::Result<T, E> type. Interally Result<T, E> use as storage a * std::variant<Ok<T>, Err<E>>. Ok<T> and Err<E> are two wrapper objects used to * mock rust Ok, Err syntax and to simpy handle the case for Ok<void>. The usage * of this two wrapper has the cost of one additional move constructor call. * To check if Result has a value T or an error E you can use methods is_ok() or * is_err(). Result also implements explicit bool operator() that works as a * is_ok() call. To get the value if available use the unwrap() function. If * called when Result is an error it will assert and terminate the program. * Use unwrap_or(T default_value) to get the value or in case Result is an error * to get default_value. * Use unwrap_err() to ghe the error. If Result is a valid value will assert and * terminate the program. * Is also possible to use the match_result function to imitate the pattern * matching syntax available in rust. */ auto divide(int a, int b) -> bs::Result<int, std::string> { if (b == 0) { return bs::Err(std::string("Division by 0 is not defined.")); } else { return bs::Ok((a / b)); } } int main() { std::cout << "Error handling demo.\n"; // Valid division operation. { auto res = divide(8, 4); assert(res.is_ok() == true); } // Invalid division by 0. { auto res = divide(8, 0); assert(res.is_err() == true); } // Unwrap value. { auto res = divide(8, 4); int value = res.unwrap(); assert(value == 2); } // Unwrap error. { auto res = divide(8, 0); std::string error_message = res.unwrap_err(); } // Unwrap_or invalid result. { auto res = divide(8, 0); int value = res.unwrap_or(-1); assert(value == -1); } // Pattern match a valid result. { auto res = divide(8, 4); bs::match_result(res /***PADDING***/, [](const bs::Ok<int>& val) { std::cout << "result = " << val.value << "\n"; }, [](const bs::Err<std::string>& err) { std::cout << "Division error: " << err.value << "\n"; }); } // Pattern match an invalid result. { auto res = divide(8, 0); bs::match_result(res /***PADDING***/, [](const bs::Ok<int>& val) { std::cout << "result = " << val.value << "\n"; }, [](const bs::Err<std::string>& err) { std::cout << "Division error: " << err.value << "\n"; }); } return 0; }
true
d8791cbbf6e4f42b5b5f6b8492ae4a595b98c36b
C++
peterzcc/PGE
/pge/source/pge/constructs/Quaternion.h
UTF-8
3,657
3.25
3
[ "Zlib" ]
permissive
#pragma once #include <pge/constructs/Vec3f.h> #include <pge/constructs/Vec4f.h> #include <pge/constructs/Matrix3x3f.h> #include <pge/constructs/Matrix4x4f.h> namespace pge { class Quaternion { public: static const float _quaternionNormalizationTolerance; static const float _quaternionDotTolerance; float w, x, y, z; Quaternion() {} Quaternion(float W, float X, float Y, float Z) : w(W), x(X), y(Y), z(Z) {} Quaternion(const Vec3f &eulerAngles) { setFromEulerAngles(eulerAngles); } Quaternion(const Matrix3x3f &mat) { setFromRotationMatrix3x3f(mat); } Quaternion(float angle, const Vec3f &axis); float magnitude() const { return sqrtf(x * x + y * y + z * z + w * w); } float magnitudeSquared() const { return x * x + y * y + z * z + w * w; } Quaternion normalized() const; void normalize(); float getAngle() const { return 2.0f * acosf(w); } Vec3f getAxis() const; Vec4f getVec4f() const { return Vec4f(x, y, z, w); } float dot(const Quaternion &other) const { return x * other.x + y * other.y + z * other.z + w * other.w; } Quaternion operator+(const Quaternion &other) const { return Quaternion(w + other.w, x + other.x, y + other.y, z + other.z); } Quaternion operator-(const Quaternion &other) const { return Quaternion(w - other.w, x - other.x, y - other.y, z - other.z); } Quaternion operator-() const { return Quaternion(-w, -x, -y, -z); } Quaternion operator*(float scale) const { return Quaternion(w * scale, x * scale, y * scale, z * scale); } Quaternion operator/(float scale) const { float scaleInv = 1.0f / scale; return Quaternion(w * scaleInv, x * scaleInv, y * scaleInv, z * scaleInv); } Quaternion operator*(const Quaternion &other) const; const Quaternion &operator*=(const Quaternion &other) { return *this = *this * other; } const Quaternion &operator*=(float scale) { return *this = *this * scale; } const Quaternion &operator/=(float scale) { return *this = *this / scale; } bool operator==(const Quaternion &other) const { return w == other.w && x == other.x && y == other.y && z == other.z; } bool operator!=(const Quaternion &other) const { return w != other.w || x != other.x || y != other.y || z != other.z; } Vec3f operator*(const Vec3f &vec); void rotate(float angle, const Vec3f &axis); void setFromRotateDifference(const Vec3f &v1, const Vec3f &v2); void setFromMatrix(const Matrix4x4f &mat); static Quaternion getRotated(float angle, const Vec3f &axis); static Quaternion getRotateDifference(const Vec3f &v1, const Vec3f &v2); static Quaternion getFromMatrix(const Matrix4x4f &mat); Quaternion conjugate() const { return Quaternion(w, -x, -y, -z); } Quaternion inverse() const { return conjugate() / magnitudeSquared(); } void setIdentityMult(); void setIdentityAdd(); static Quaternion identityMult() { return Quaternion(1.0f, 0.0f, 0.0f, 0.0f); } static Quaternion identityAdd() { return Quaternion(0.0f, 0.0f, 0.0f, 0.0f); } Matrix4x4f getMatrix() const; void setFromEulerAngles(const Vec3f &eulerAngles); void setFromRotationMatrix3x3f(const Matrix3x3f &mat); Vec3f getEulerAngles() const; void calculateWFromXYZ(); static Quaternion lerp(const Quaternion &first, const Quaternion &second, float interpolationCoefficient); static Quaternion slerp(const Quaternion &first, const Quaternion &second, float interpolationCoefficient); }; Vec3f operator*(const Vec3f &vec, const Quaternion &quat); std::ostream &operator<<(std::ostream &output, const Quaternion &quat); }
true
99ce38d20e1f5625a9df2730f2be898168b38be2
C++
z397318716/C-Plus-Plus
/10_10_class_practice/10_10_class_practice/review_c.cpp
GB18030
974
2.9375
3
[]
no_license
//#define _CRT_SECURE_NO_WARNINGS //#include <stdio.h> //#include <stdlib.h> //#include <string.h> // // //int check_sys1() //{ // int i = 1; // char *tmp = (char *)&i; // return *tmp; //} // //int check_sys2() //{ // union // { // int i; // char c; // }un; // un.i = 1; // // return un.c; //} // //void GetMemory(char *p) //{ // p = (char *)malloc(100); //} //void Test(void) //{ // char *str = NULL; // GetMemory(str); // strcpy(str, "hello world"); // printf(str); //} // //void test1() //{ // char* pstr = "hello bit.";//ǰһַŵpstrָ // printf("%s\n", pstr); //} // //int main() //{ // Test(); // // /*int tmp = check_sys1(); // if (tmp == 1) // { // printf("С\n"); // } // else // { // printf("\n"); // } // // union Un // { // int i; // char c[5]; // // }; // union Un1 // { // short c[7]; // int i; // }; // // // printf("%d\n", sizeof(union Un1)); // printf("%d\n", sizeof(Un));*/ // return 0; //}
true
4b469b2d3a2258b37c5860f228db5f41e83fe151
C++
CodeInSleep/Autonomous_Watering_System
/ButtonPair.h
UTF-8
537
2.734375
3
[]
no_license
#ifndef BUTTONPAIR_H #define BUTTONPAIR_H #include "Arduino.h" #include "Button.h" class ButtonPair { public: ButtonPair(int p1, int p2, String b1Name, String b2Name, String buttonPairName); int button_pressed(bool op); void setVals(const int val, const int minVal, const int maxVal); int getVal(); private: int increment(); int decrement(); bool check_lower_bound(); bool check_upper_bound(); int _val; int _p1; int _p2; int _maxVal; int _minVal; String _buttonPairName; Button _incButton; Button _decButton; }; #endif
true
e5d4fa32f3649886f3bdd006ccf7463a762cfe5d
C++
koryakinp/AutoYahtzee.Arduino
/StateManager.cpp
UTF-8
663
2.640625
3
[]
no_license
#include "StateManager.h" #include "States.h" StateManager::StateManager() { _currentState = 0; _states[0] = States::THROW; _states[1] = States::PRE_LOWER; _states[2] = States::LOWER; _states[3] = States::PRE_UNLOAD; _states[4] = States::UNLOAD; _states[5] = States::PRE_LIFT; _states[6] = States::LIFT; _states[7] = States::SHUTDOWN; } void StateManager::StepForward() { if(_currentState == 7) { return; } _currentState++; if(_currentState == 7) { _currentState = 0; } } String StateManager::GetCurrentState() { return _states[_currentState]; } void StateManager::ForceShutDownState() { _currentState = 7; }
true
16b7b95141c3c500ba3ed1bd7594ce0d4cfd36fd
C++
lyr19950720/data-structure
/assignment5/1144Tree Recovery/main.cpp
GB18030
722
3.03125
3
[]
no_license
#include<iostream> #include<string> #include<cstdio> using namespace std; char post[30]; // int t = 0; void solve(string pre, string in) { if (pre.length() == 0) return; else if (pre.length() == 1) { post[t++] = pre[0]; return; } else { int tt = in.find(pre[0]);//еλ solve(pre.substr(1, tt), in.substr(0, tt)); //ĺ solve(pre.substr(tt + 1, pre.length() - tt - 1), in.substr(tt + 1, in.length() - tt - 1)); //ĺ post[t++] = pre[0]; } } int main() { string pre, in; while (cin >> pre >> in) { int len = pre.length(); t = 0; solve(pre, in); post[len] = '\0'; cout << post << endl; } return 0; }
true
25da659912d2261b8bad22f7ccfd8b6c7e3d2f6f
C++
Timoniche/Graphics
/Delaunay/main.cpp
UTF-8
35,411
2.875
3
[]
no_license
/**#include <SFML/Graphics.hpp>*/ #include <SFML/Graphics.hpp> #include <iostream> #include <cassert> #include <unordered_map> #include <set> #include <iomanip> #include <vector> #include <float.h> #include <cmath> #include <algorithm> #include <functional> #include <random> using namespace std; typedef pair<long double, long double> pdd; typedef pair<int, int> pii; struct Edge; struct Vector2; #define FOR(i, n) for (int i = 0; i < n; i++) struct Vector2 { Vector2() = default; Vector2(const Vector2 &v) = default; Vector2(Vector2 &&) = default; Vector2(const long double vx, const long double vy); long double dist2(const Vector2 &v) const; long double dist(const Vector2 &v) const; long double norm2() const; Vector2 &operator=(const Vector2 &) = default; Vector2 &operator=(Vector2 &&) = default; bool operator==(const Vector2 &v) const; friend std::ostream &operator<<(std::ostream &str, const Vector2 &v); long double x; long double y; }; Vector2::Vector2(const long double vx, const long double vy) : x(vx), y(vy) {} long double Vector2::dist2(const Vector2 &v) const { const long double dx = x - v.x; const long double dy = y - v.y; return dx * dx + dy * dy; } long double Vector2::dist(const Vector2 &v) const { return hypot(x - v.x, y - v.y); } long double Vector2::norm2() const { return x * x + y * y; } bool Vector2::operator==(const Vector2 &v) const { return (this->x == v.x) && (this->y == v.y); } std::ostream & operator<<(std::ostream &str, const Vector2 &v) { return str << "Point x: " << v.x << " y: " << v.y; } bool almost_equal(const long double x, const long double y, int ulp) { return std::abs(x - y) <= std::numeric_limits<long double>::epsilon() * std::abs(x + y) * static_cast<long double>(ulp) || std::abs(x - y) < std::numeric_limits<long double>::min(); } bool almost_equal(const Vector2 &v1, const Vector2 &v2, int ulp) { return almost_equal(v1.x, v2.x, ulp) && almost_equal(v1.y, v2.y, ulp); } bool almost_equal(const Vector2 &v1, const Vector2 &v2, int ulp = 2); long double half(const long double x) { return 0.5 * x; } void lineFromPoints(pdd P, pdd Q, long double &a, long double &b, long double &c) { a = Q.second - P.second; b = P.first - Q.first; c = a * (P.first) + b * (P.second); } void perpendicularBisectorFromLine(pdd P, pdd Q, long double &a, long double &b, long double &c) { pdd mid_point = make_pair((P.first + Q.first) / 2, (P.second + Q.second) / 2); // c = -bx + ay c = -b * (mid_point.first) + a * (mid_point.second); long double temp = a; a = -b; b = temp; } pdd lineLineIntersection(long double a1, long double b1, long double c1, long double a2, long double b2, long double c2) { long double determinant = a1 * b2 - a2 * b1; if (determinant == 0) { // The lines are parallel. This is simplified // by returning a pair of FLT_MAX return make_pair(FLT_MAX, FLT_MAX); } else { long double x = (b2 * c1 - b1 * c2) / determinant; long double y = (a1 * c2 - a2 * c1) / determinant; return make_pair(x, y); } } pdd findCircumCenter(pdd P, pdd Q, pdd R) { // Line PQ is represented as ax + by = c long double a, b, c; lineFromPoints(P, Q, a, b, c); // Line QR is represented as ex + fy = g long double e, f, g; lineFromPoints(Q, R, e, f, g); // Converting lines PQ and QR to perpendicular // vbisectors. After this, L = ax + by = c // M = ex + fy = g perpendicularBisectorFromLine(P, Q, a, b, c); perpendicularBisectorFromLine(Q, R, e, f, g); // The point of intersection of L and M gives // the circumcenter pdd circumcenter = lineLineIntersection(a, b, c, e, f, g); return {circumcenter.first, circumcenter.second}; } struct Triangle { using EdgeType = Edge; using VertexType = Vector2; Triangle() = default; Triangle(const Triangle &) = default; Triangle(Triangle &&) = default; Triangle(const VertexType &v1, const VertexType &v2, const VertexType &v3); bool containsVertex(const VertexType &v) const; bool circumCircleContains(const VertexType &v) const; Triangle &operator=(const Triangle &) = default; Triangle &operator=(Triangle &&) = default; bool operator==(const Triangle &t) const; friend std::ostream &operator<<(std::ostream &str, const Triangle &t); const VertexType *a; const VertexType *b; const VertexType *c; bool isBad = false; }; Triangle::Triangle(const VertexType &v1, const VertexType &v2, const VertexType &v3) : a(&v1), b(&v2), c(&v3), isBad(false) {} bool Triangle::containsVertex(const VertexType &v) const { // return p1 == v || p2 == v || p3 == v; return almost_equal(*a, v) || almost_equal(*b, v) || almost_equal(*c, v); } bool Triangle::circumCircleContains(const VertexType &v) const { const long double ab = a->norm2(); const long double cd = b->norm2(); const long double ef = c->norm2(); const long double ax = a->x; const long double ay = a->y; const long double bx = b->x; const long double by = b->y; const long double cx = c->x; const long double cy = c->y; const long double circum_x = (ab * (cy - by) + cd * (ay - cy) + ef * (by - ay)) / (ax * (cy - by) + bx * (ay - cy) + cx * (by - ay)); const long double circum_y = (ab * (cx - bx) + cd * (ax - cx) + ef * (bx - ax)) / (ay * (cx - bx) + by * (ax - cx) + cy * (bx - ax)); const VertexType circum(half(circum_x), half(circum_y)); const long double circum_radius = a->dist2(circum); const long double dist = v.dist2(circum); return dist <= circum_radius; } bool Triangle::operator==(const Triangle &t) const { return (*this->a == *t.a || *this->a == *t.b || *this->a == *t.c) && (*this->b == *t.a || *this->b == *t.b || *this->b == *t.c) && (*this->c == *t.a || *this->c == *t.b || *this->c == *t.c); } std::ostream & operator<<(std::ostream &str, const Triangle &t) { return str << "Triangle:" << "\n\t" << *t.a << "\n\t" << *t.b << "\n\t" << *t.c << '\n'; } bool almost_equal(const Triangle &t1, const Triangle &t2) { return (almost_equal(*t1.a, *t2.a) || almost_equal(*t1.a, *t2.b) || almost_equal(*t1.a, *t2.c)) && (almost_equal(*t1.b, *t2.a) || almost_equal(*t1.b, *t2.b) || almost_equal(*t1.b, *t2.c)) && (almost_equal(*t1.c, *t2.a) || almost_equal(*t1.c, *t2.b) || almost_equal(*t1.c, *t2.c)); } bool almost_equal(const Triangle &t1, const Triangle &t2); struct Edge { using VertexType = Vector2; Edge() = default; Edge(const Edge &) = default; Edge(Edge &&) = default; Edge(const VertexType &v1, const VertexType &v2); Edge &operator=(const Edge &) = default; Edge &operator=(Edge &&) = default; bool operator==(const Edge &e) const; friend std::ostream &operator<<(std::ostream &str, const Edge &e); const VertexType *v; const VertexType *w; bool isBad = false; }; Edge::Edge(const VertexType &v1, const VertexType &v2) : v(&v1), w(&v2) {} bool Edge::operator==(const Edge &e) const { return (*(this->v) == *e.v && *(this->w) == *e.w) || (*(this->v) == *e.w && *(this->w) == *e.v); } std::ostream & operator<<(std::ostream &str, const Edge &e) { return str << "Edge " << *e.v << ", " << *e.w; } bool almost_equal(const Edge &e1, const Edge &e2) { return (almost_equal(*e1.v, *e2.v) && almost_equal(*e1.w, *e2.w)) || (almost_equal(*e1.v, *e2.w) && almost_equal(*e1.w, *e2.v)); } bool almost_equal(const Edge &e1, const Edge &e2); class Delaunay { public: using TriangleType = Triangle; using EdgeType = Edge; using VertexType = Vector2; Delaunay() = default; Delaunay(const Delaunay &) = delete; Delaunay(Delaunay &&) = delete; const std::vector<TriangleType> &triangulate(std::vector<VertexType> &vertices); const std::vector<TriangleType> &getTriangles() const; const std::vector<EdgeType> &getEdges() const; const std::vector<VertexType> &getVertices() const; Delaunay &operator=(const Delaunay &) = delete; Delaunay &operator=(Delaunay &&) = delete; private: std::vector<TriangleType> _triangles; std::vector<EdgeType> _edges; std::vector<VertexType> _vertices; }; const std::vector<Delaunay::TriangleType> & Delaunay::triangulate(std::vector<VertexType> &vertices) { _vertices = vertices; long double minX = vertices[0].x; long double minY = vertices[0].y; long double maxX = minX; long double maxY = minY; for (std::size_t i = 0; i < vertices.size(); ++i) { if (vertices[i].x < minX) minX = vertices[i].x; if (vertices[i].y < minY) minY = vertices[i].y; if (vertices[i].x > maxX) maxX = vertices[i].x; if (vertices[i].y > maxY) maxY = vertices[i].y; } const long double dx = maxX - minX; const long double dy = maxY - minY; const long double deltaMax = std::max(dx, dy); const long double midx = half(minX + maxX); const long double midy = half(minY + maxY); const VertexType p1(midx - 20 * deltaMax, midy - deltaMax); const VertexType p2(midx, midy + 20 * deltaMax); const VertexType p3(midx + 20 * deltaMax, midy - deltaMax); // Create a list of triangles, and add the supertriangle in it _triangles.push_back(TriangleType(p1, p2, p3)); for (auto p = begin(vertices); p != end(vertices); p++) { std::vector<EdgeType> polygon; for (auto &t : _triangles) { if (t.circumCircleContains(*p)) { t.isBad = true; polygon.push_back(Edge{*t.a, *t.b}); polygon.push_back(Edge{*t.b, *t.c}); polygon.push_back(Edge{*t.c, *t.a}); } } _triangles.erase(std::remove_if(begin(_triangles), end(_triangles), [](TriangleType &t) { return t.isBad; }), end(_triangles)); for (auto e1 = begin(polygon); e1 != end(polygon); ++e1) { for (auto e2 = e1 + 1; e2 != end(polygon); ++e2) { if (almost_equal(*e1, *e2)) { e1->isBad = true; e2->isBad = true; } } } polygon.erase(std::remove_if(begin(polygon), end(polygon), [](EdgeType &e) { return e.isBad; }), end(polygon)); for (const auto e : polygon) _triangles.push_back(TriangleType(*e.v, *e.w, *p)); } _triangles.erase(std::remove_if(begin(_triangles), end(_triangles), [p1, p2, p3](TriangleType &t) { return t.containsVertex(p1) || t.containsVertex(p2) || t.containsVertex(p3); }), end(_triangles)); for (const auto t : _triangles) { _edges.push_back(Edge{*t.a, *t.b}); _edges.push_back(Edge{*t.b, *t.c}); _edges.push_back(Edge{*t.c, *t.a}); } return _triangles; } const std::vector<Delaunay::TriangleType> & Delaunay::getTriangles() const { return _triangles; } const std::vector<Delaunay::EdgeType> & Delaunay::getEdges() const { return _edges; } const std::vector<Delaunay::VertexType> & Delaunay::getVertices() const { return _vertices; } struct Point; typedef std::vector<Point> vector_of_points; struct StackExtended { public: void push(size_t x); int top(); int top_next(); int pop(); public: std::vector<size_t> _data; }; struct Point { long double x = -1; long double y = -1; Point(); Point(long double x, long double y); Point(Point const &p); Point(Point &&p); Point &operator=(Point const &p); Point &operator=(Point &&p); void swap(Point &p); friend std::ostream &operator<<(std::ostream &os, const Point &dt); friend bool operator==(Point const &lhs, Point const &rhs); friend bool operator!=(Point const &lhs, Point const &rhs); friend bool operator<(Point const &lhs, Point const &rhs); }; Point::Point() = default; Point::Point(long double x, long double y) : x(x), y(y) {} void Point::swap(Point &p) { Point tmp(std::move(p)); p = std::move(*this); *this = std::move(tmp); } Point &Point::operator=(Point const &p) { x = p.x; y = p.y; return *this; } Point &Point::operator=(Point &&p) { x = p.x; y = p.y; return *this; } Point::Point(Point const &p) { x = p.x; y = p.y; } Point::Point(Point &&p) { x = p.x; y = p.y; } std::ostream &operator<<(std::ostream &os, const Point &dt) { os << dt.x << ' ' << dt.y; return os; } bool operator==(Point const &lhs, Point const &rhs) { return lhs.x == rhs.x && lhs.y == rhs.y; } bool operator!=(Point const &lhs, Point const &rhs) { return !(lhs == rhs); } bool operator<(Point const &lhs, Point const &rhs) { if (lhs.x == rhs.x) return lhs.y < rhs.y; return lhs.x < rhs.x; } void StackExtended::push(size_t x) { _data.push_back(x); } int StackExtended::top() { if (_data.empty()) { return -1; } return int(_data[_data.size() - 1]); } int StackExtended::top_next() { if (_data.size() < 2) { return -1; } return int(_data[_data.size() - 2]); } int StackExtended::pop() { if (_data.empty()) { return -1; } int tmp = top(); _data.pop_back(); return tmp; } long double distance_pow2(long double x1, long double y1, long double x2, long double y2) { return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); } bool left_directed(size_t next_to_top, size_t top, size_t pi, vector_of_points const &data) { Point u = {data[top].x - data[next_to_top].x, data[top].y - data[next_to_top].y}; Point v = {data[pi].x - data[top].x, data[pi].y - data[top].y}; long double cross = u.x * v.y - u.y * v.x; return cross < 0; } StackExtended _stack; vector_of_points const &graham(vector_of_points const &points) { auto *ret = new vector_of_points(); switch (points.size()) { case 0: case 1: return *ret; case 2: ret->emplace_back(points[0].x, points[0].y); ret->emplace_back(points[1].x, points[1].y); return *ret; default: break; } vector_of_points data_counter_clock_from_p0 = points; auto it_to_min_y_element = std::min_element(data_counter_clock_from_p0.begin(), data_counter_clock_from_p0.end(), [](const Point &a, const Point &b) { if (a.y == b.y) return a.x < b.x; return a.y < b.y; }); auto it_to_max_y_element = std::min_element(data_counter_clock_from_p0.begin(), data_counter_clock_from_p0.end(), [](const Point &a, const Point &b) { return a.y > b.y; }); data_counter_clock_from_p0.begin()->swap(*it_to_min_y_element); long double x0 = data_counter_clock_from_p0[0].x; long double y0 = data_counter_clock_from_p0[0].y; long double maxx = (*it_to_max_y_element).x; long double maxy = (*it_to_max_y_element).y; Point tomax{maxx - x0, maxy - y0}; std::sort(data_counter_clock_from_p0.begin() + 1, data_counter_clock_from_p0.end(), [x0, y0, tomax](const Point &a, const Point &b) { Point at{a.x - x0, a.y - y0}; Point bt{b.x - x0, b.y - y0}; long double cross = at.x * bt.y - at.y * bt.x; if (cross == 0) { long double cross_with_max = at.x * tomax.y - at.y * tomax.x; long double dis_a_p0 = distance_pow2(a.x, a.y, x0, y0); long double dis_b_p0 = distance_pow2(b.x, b.y, x0, y0); return cross_with_max >= 0 ? dis_a_p0 < dis_b_p0 : dis_a_p0 > dis_b_p0; } else { return cross > 0; } }); _stack.push(0); _stack.push(1); for (size_t pi = 2; pi < data_counter_clock_from_p0.size(); pi++) { int _next_to_top = _stack.top_next(); assert(_next_to_top != -1); int _top = _stack.top(); assert(_top != -1); while (left_directed(size_t(_next_to_top), size_t(_top), pi, data_counter_clock_from_p0)) { _stack.pop(); if (_stack._data.size() == 1) break; _next_to_top = _stack.top_next(); assert(_next_to_top != -1); _top = _stack.top(); assert(_top != -1); } _stack.push(pi); } for (size_t i = 0; i < _stack._data.size(); i++) { ret->push_back(data_counter_clock_from_p0[_stack._data[i]]); } _stack._data.clear(); return *ret; } struct hash_pair { template<class T1, class T2> size_t operator()(const pair<T1, T2> &p) const { auto hash1 = hash<T1>{}(p.first); auto hash2 = hash<T2>{}(p.second); return hash1 ^ hash2; } }; long double cross(const pdd &p1, const pdd &p2, const pdd &q) { pdd u = {p2.first - p1.first, p2.second - p1.second}; pdd v = {q.first - p2.first, q.second - p2.second}; return u.first * v.second - u.second * v.first; } bool is_left(const pdd &p1, const pdd &p2, const pdd &q) { pdd u = {p2.first - p1.first, p2.second - p1.second}; pdd v = {q.first - p2.first, q.second - p2.second}; return cross(p1, p2, q) > 0; } bool belongs(const pdd &ebeg, const pdd &eend, const pdd &q) { long double rot = cross(ebeg, eend, q); long double eps = 1e-7; //long double eps = numeric_limits<long double>::epsilon(); //if (rot <= eps && rot >= -eps) { long double low = min(ebeg.second, eend.second); long double high = max(ebeg.second, eend.second); long double left = min(ebeg.first, eend.first); long double right = max(ebeg.first, eend.first); return q.first >= left - eps && q.first <= right + eps && q.second >= low - eps && q.second <= high + eps; } return false; } int max_x, max_y; set<Point> clip_hull(vector_of_points _hull, int MAXX, int MAXY, int deltaX, int deltaY) { set<Point> ret; long double alow, blow, clow; long double ahigh, bhigh, chigh; long double aleft, bleft, cleft; long double aright, bright, cright; lineFromPoints({0, 0}, {MAXX, 0}, alow, blow, clow); lineFromPoints({0, MAXY}, {MAXX, MAXY}, ahigh, bhigh, chigh); lineFromPoints({0, 0}, {0, MAXY}, aleft, bleft, cleft); lineFromPoints({MAXX, 0}, {MAXX, MAXY}, aright, bright, cright); int k = int(_hull.size()); for (int i = 0; i < k; ++i) { _hull[i].x -= deltaX; _hull[i].y -= deltaY; } for (int i = 0; i < k; ++i) { pdd now = {_hull[i].x, _hull[i].y}; if (now.first >= 0 && now.first <= MAXX && now.second >= 0 && now.second <= MAXY) { ret.emplace(now.first, now.second); } pdd after = {_hull[(i + 1) % k].x, _hull[(i + 1) % k].y}; long double a, b, c; lineFromPoints(now, after, a, b, c); pdd withLow = lineLineIntersection(a, b, c, alow, blow, clow); if (belongs({0, 0}, {MAXX, 0}, withLow) && belongs(now, after, withLow)) ret.emplace(withLow.first, withLow.second); pdd withHigh = lineLineIntersection(a, b, c, ahigh, bhigh, chigh); if (belongs({0, MAXY}, {MAXX, MAXY}, withHigh) && belongs(now, after, withHigh)) ret.emplace(withHigh.first, withHigh.second); pdd withLeft = lineLineIntersection(a, b, c, aleft, bleft, cleft); if (belongs({0, 0}, {0, MAXY}, withLeft) && belongs(now, after, withLeft)) ret.emplace(withLeft.first, withLeft.second); pdd withRight = lineLineIntersection(a, b, c, aright, bright, cright); if (belongs({MAXX, 0}, {MAXX, MAXY}, withRight) && belongs(now, after, withRight)) ret.emplace(withRight.first, withRight.second); } return ret; } bool tryEmplace(pdd const &v, std::set<pdd> *const &hulls, int index, pdd before, pdd now) { if (v.first < 0 || v.first > max_x || v.second < 0 || v.second > max_y) return false; if (v.first != FLT_MAX && !is_left(before, now, v)) { hulls[index].emplace(v); return true; } return false; } int main() { int n; int MAXX, MAXY, deltaX, deltaY; //cin >> MAXX >> MAXY >> n; n = 1000; MAXX = 100000; MAXY = 100000; vector_of_points input; std::default_random_engine eng(std::random_device{}()); std::uniform_real_distribution<long double> dist_w(0, MAXX); std::uniform_real_distribution<long double> dist_h(0, MAXY); max_x = 1000 * MAXX; max_y = 1000 * MAXY; // max_x = 100000 * 1000; // max_y = 100000 * 1000; deltaX = max_x / 2; deltaY = max_y / 2; /** sf::RenderWindow window(sf::VideoMode(800, 600), "Voronoi"); window.setFramerateLimit(1); */ sf::RenderWindow window(sf::VideoMode(800, 600), "Voronoi"); window.setFramerateLimit(1); //long double scaleX = 800 / max_x; //long double scaleY = 600 / max_y; long double scaleX = 800.0 / MAXX; long double scaleY = 600.0 / MAXY; // points: {0, 0}, {0, max_y}, {max_x, 0}, {max_x, max_y} //borders: long double alow, blow, clow; long double ahigh, bhigh, chigh; long double aleft, bleft, cleft; long double aright, bright, cright; lineFromPoints({0, 0}, {max_x, 0}, alow, blow, clow); lineFromPoints({0, max_y}, {max_x, max_y}, ahigh, bhigh, chigh); lineFromPoints({0, 0}, {0, max_y}, aleft, bleft, cleft); lineFromPoints({max_x, 0}, {max_x, max_y}, aright, bright, cright); unordered_map<pii, int, hash_pair> point_index_map; std::set<pdd> hulls[n]; std::vector<Vector2> points; std::vector<pdd> pointsPddView; vector_of_points pointsView; set<Point> allpoints; FOR(i, n) { int x, y; //cin >> x >> y; x = int(dist_w(eng)); y = int(dist_h(eng)); while (allpoints.find(Point{double(x), double(y)}) != allpoints.end()) { x = int(dist_w(eng)); y = int(dist_h(eng)); } allpoints.emplace(x, y); cout << "xy: " << x << " " << y << endl; /** sf::RectangleShape s{sf::Vector2f(4, 4)}; s.setPosition(static_cast<float>(x * scaleX), static_cast<float>((MAXY - y) * scaleY)); window.draw(s); */ sf::RectangleShape s{sf::Vector2f(2, 2)}; s.setPosition(static_cast<float>(x * scaleX), static_cast<float>((MAXY - y) * scaleY)); window.draw(s); // x += deltaX; y += deltaY; // points.emplace_back(x, y); pointsView.emplace_back(x, y); pointsPddView.emplace_back(x, y); point_index_map[{x, y}] = i; // sf::RectangleShape s{sf::Vector2f(4, 4)}; // s.setPosition(static_cast<float>(x * scaleX), // static_cast<float>((max_y - y) * scaleY)); // window.draw(s); } Delaunay triangulation; const std::vector<Triangle> triangles = triangulation.triangulate(points); const std::vector<Edge> edges = triangulation.getEdges(); vector_of_points hull = graham(pointsView); int sz = int(hull.size()); //hull is a line if (triangles.empty()) { for (int i = sz - 1 - 1; i >= 0 + 1; i--) { hull.push_back(hull[i]); } } sz = int(hull.size()); for (int i = 1; i <= hull.size(); i++) { Point nowP = hull[i % sz]; Point beforeP; beforeP = hull[i - 1]; Point afterP; afterP = hull[(i + 1) % sz]; pdd now = {nowP.x, nowP.y}; pdd before = {beforeP.x, beforeP.y}; pdd after = {afterP.x, afterP.y}; long double a1, b1, c1; long double a2, b2, c2; lineFromPoints(before, now, a1, b1, c1); lineFromPoints(now, after, a2, b2, c2); // c = -bx + ay perpendicularBisectorFromLine(before, now, a1, b1, c1); perpendicularBisectorFromLine(now, after, a2, b2, c2); int index = i % sz; index = point_index_map[{hull[index].x, hull[index].y}]; pdd predWithLow = lineLineIntersection(a1, b1, c1, alow, blow, clow); pdd predWithHigh = lineLineIntersection(a1, b1, c1, ahigh, bhigh, chigh); pdd predWithLeft = lineLineIntersection(a1, b1, c1, aleft, bleft, cleft); pdd predWithRight = lineLineIntersection(a1, b1, c1, aright, bright, cright); if (tryEmplace(predWithLow, hulls, index, before, now)) /**fromPred = LOW*/; if (tryEmplace(predWithHigh, hulls, index, before, now)) /**fromPred = HIGH*/; if (tryEmplace(predWithLeft, hulls, index, before, now)) /**fromPred = LEFT*/; if (tryEmplace(predWithRight, hulls, index, before, now)) /**fromPred = RIGHT*/; pdd nextWithLow = lineLineIntersection(a2, b2, c2, alow, blow, clow); pdd nextWithHigh = lineLineIntersection(a2, b2, c2, ahigh, bhigh, chigh); pdd nextWithLeft = lineLineIntersection(a2, b2, c2, aleft, bleft, cleft); pdd nextWithRight = lineLineIntersection(a2, b2, c2, aright, bright, cright); if (tryEmplace(nextWithLow, hulls, index, now, after)) /**fromNext = LOW*/; if (tryEmplace(nextWithHigh, hulls, index, now, after)) /**fromNext = HIGH*/; if (tryEmplace(nextWithLeft, hulls, index, now, after)) /**fromNext = LEFT*/; if (tryEmplace(nextWithRight, hulls, index, now, after)) /**fromNext = RIGHT*/; } auto it_leftlow = std::min_element(pointsPddView.begin(), pointsPddView.end(), [](const pdd &a, const pdd &b) { return distance_pow2(a.first, a.second, 0, 0) < distance_pow2(b.first, b.second, 0, 0); }); auto it_lefthigh = std::min_element(pointsPddView.begin(), pointsPddView.end(), [](const pdd &a, const pdd &b) { return distance_pow2(a.first, a.second, 0, max_y) < distance_pow2(b.first, b.second, 0, max_y); }); auto it_rightlow = std::min_element(pointsPddView.begin(), pointsPddView.end(), [](const pdd &a, const pdd &b) { return distance_pow2(a.first, a.second, max_x, 0) < distance_pow2(b.first, b.second, max_x, 0); }); auto it_righthigh = std::min_element(pointsPddView.begin(), pointsPddView.end(), [](const pdd &a, const pdd &b) { return distance_pow2(a.first, a.second, max_x, max_y) < distance_pow2(b.first, b.second, max_x, max_y); }); std::vector<pdd> voronoi_vertices; for (auto &t : triangles) { pdd center = findCircumCenter({t.a->x, t.a->y}, {t.b->x, t.b->y}, {t.c->x, t.c->y}); if (center.first == FLT_MAX || center.second == FLT_MAX) continue; voronoi_vertices.push_back(center); hulls[point_index_map[{int(t.a->x), int(t.a->y)}]].emplace(center); hulls[point_index_map[{int(t.b->x), int(t.b->y)}]].emplace(center); hulls[point_index_map[{int(t.c->x), int(t.c->y)}]].emplace(center); } //______________________________________________________________________________________________________________________ /**std::vector<std::array<sf::Vertex, 2> > lines;*/ std::vector<std::array<sf::Vertex, 2> > lines; auto leftlow = std::min_element(pointsPddView.begin(), pointsPddView.end(), [MAXX, MAXY, deltaX, deltaY](const pdd &a, const pdd &b) { return distance_pow2(a.first - deltaX, a.second - deltaY, 0, 0) < distance_pow2(b.first - deltaX, b.second - deltaY, 0, 0); }); auto lefthigh = std::min_element(pointsPddView.begin(), pointsPddView.end(), [MAXX, MAXY, deltaX, deltaY](const pdd &a, const pdd &b) { return distance_pow2(a.first - deltaX, a.second - deltaY, 0, MAXY) < distance_pow2(b.first - deltaX, b.second - deltaY, 0, MAXY); }); auto rightlow = std::min_element(pointsPddView.begin(), pointsPddView.end(), [MAXX, MAXY, deltaX, deltaY](const pdd &a, const pdd &b) { return distance_pow2(a.first - deltaX, a.second - deltaY, MAXX, 0) < distance_pow2(b.first - deltaX, b.second - deltaY, MAXX, 0); }); auto righthigh = std::min_element(pointsPddView.begin(), pointsPddView.end(), [MAXX, MAXY, deltaX, deltaY](const pdd &a, const pdd &b) { return distance_pow2(a.first - deltaX, a.second - deltaY, MAXX, MAXY) < distance_pow2(b.first - deltaX, b.second - deltaY, MAXX, MAXY); }); FOR(i, n) { if (pointsPddView[i] == *it_leftlow) hulls[i].emplace(0, 0); if (pointsPddView[i] == *it_lefthigh) hulls[i].emplace(0, max_y); if (pointsPddView[i] == *it_rightlow) hulls[i].emplace(max_x, 0); if (pointsPddView[i] == *it_righthigh) hulls[i].emplace(max_x, max_y); vector<pdd> hullV(hulls[i].begin(), hulls[i].end()); /**assert(!hullV.empty());*/ assert(!hullV.empty()); if (hullV.empty()) { cout << "xyempty: " << pointsPddView[i].first - deltaX << " " << pointsPddView[i].second - deltaY << endl; continue; } vector_of_points hulltmp; for (auto &e : hullV) hulltmp.push_back({e.first, e.second}); vector_of_points _hull = graham(hulltmp); //______________________________________________________________________________________________________________ set<Point> _hullSet = clip_hull(_hull, MAXX, MAXY, deltaX, deltaY); if (pointsPddView[i] == *leftlow) _hullSet.emplace(0, 0); if (pointsPddView[i] == *lefthigh) _hullSet.emplace(0, MAXY); if (pointsPddView[i] == *rightlow) _hullSet.emplace(MAXX, 0); if (pointsPddView[i] == *righthigh) _hullSet.emplace(MAXX, MAXY); _hull = vector_of_points(_hullSet.begin(), _hullSet.end()); _hull = graham(_hull); //______________________________________________________________________________________________________________ int k = int(_hull.size()); cout.precision(std::numeric_limits<long double>::max_digits10); cout << k << endl; FOR(j, k) { auto v = _hull[j]; auto w = _hull[(j + 1) % k]; cout << _hull[j].x << " " << _hull[j].y << endl; // const std::array<sf::Vertex, 2> line{{sf::Vertex(sf::Vector2f( // static_cast<float>(scaleX * v.x + 2.), // static_cast<float>(scaleY * (max_y - v.y) + 2.))), sf::Vertex(sf::Vector2f( // static_cast<float>(scaleX * w.x + 2.), // static_cast<float>(scaleY * (max_y - w.y) + 2.))), // }}; // window.draw(std::data(line), 2, sf::Lines); scaleX = 800.0 / MAXX; scaleY = 600.0 / MAXY; /** const std::array<sf::Vertex, 2> line{{sf::Vertex(sf::Vector2f( static_cast<float>(scaleX * v.x + 2.), static_cast<float>(scaleY * (MAXY - v.y) + 2.))), sf::Vertex(sf::Vector2f( static_cast<float>(scaleX * w.x + 2.), static_cast<float>(scaleY * (MAXY - w.y) + 2.))), }}; window.draw(std::data(line), 2, sf::Lines); */ const std::array<sf::Vertex, 2> line{{sf::Vertex(sf::Vector2f( static_cast<float>(scaleX * v.x + 2.), static_cast<float>(scaleY * (MAXY - v.y) + 2.))), sf::Vertex(sf::Vector2f( static_cast<float>(scaleX * w.x + 2.), static_cast<float>(scaleY * (MAXY - w.y) + 2.))), }}; window.draw(std::data(line), 2, sf::Lines); } } //______________________________________________________________________________________________________________________ /** window.display(); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); } } */ window.display(); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); } } return 0; } //tests: //6 5 5 2 1 2 2 2 3 1 4 3 4 //6 5 5 3 1 3 2 3 3 2 4 4 4 //10 10 5 4 1 4 2 4 3 3 4 5 4 //6 5 4 2 1 2 2 2 3 3 4 //no triangles tests: //6 5 5 1 1 1 2 1 3 1 4 1 5 //10 10 5 1 1 2 2 3 3 4 4 5 5
true
78fc576d8a67f274d2e432129e1b63a8562530d5
C++
zhouchao0924/RTX_Render
/Source/ajdr/Cabinet/base/common.cpp
UTF-8
10,014
2.53125
3
[]
no_license
#include "common.h" #include "../Building/BuildingSystem.h" #include "../CabinetGlobal.h" float Point2LineSeg(const FVector2D& point_A, const FVector2D& point_B, const FVector2D& point_P, float &fDot, FVector2D &point_C) { FVector2D AP = point_P - point_A; FVector2D AB = point_B - point_A; fDot = (AP | AB) / (AB | AB); FVector2D AC = AB * fDot; point_C = AC + point_A; if (fDot >= 1) { FVector2D BP = point_P - point_B; point_C = point_B; return BP.Size(); } else if (fDot <= 0) { point_C = point_A; return AP.Size(); } else { FVector2D PC = point_P - point_C; return PC.Size(); } }; float Point2LineSegVer(const FVector2D& point_A, const FVector2D& point_B, const FVector2D& point_P, float &fDot, FVector2D &point_C) { FVector2D AP = point_P - point_A; FVector2D AB = point_B - point_A; fDot = (AP | AB) / (AB | AB); FVector2D AC = AB * fDot; point_C = AC + point_A; FVector2D PC = point_P - point_C; if (fDot >= 1) { point_C = point_B; } else if (fDot <= 0) { point_C = point_A; } return PC.Size(); }; float AreaPoly(TArray<FVector2D> &poly) { int size = (int)poly.Num(); if (size < 3) return 0; double a = 0; for (int i = 0, j = size - 1; i < size; ++i) { a += ((double)poly[j].X + poly[i].X) * ((double)poly[j].Y - poly[i].Y); j = i; } return -a * 0.5; } bool IsPointOnLine(FVector2D PosStart,FVector2D PosEnd, FVector2D point_P) { if (FMath::Abs(((PosStart.X - point_P.Y)*(PosEnd.Y - point_P.Y) - (PosStart.Y - point_P.Y)*(PosEnd.X - point_P.X))) <= 0.00001f) { if (FMath::Min(PosStart.X, PosEnd.X) <= point_P.X && point_P.X <= FMath::Max(PosStart.X, PosEnd.X) && FMath::Min(PosStart.Y, PosEnd.Y) <= point_P.Y && point_P.Y <= FMath::Max(PosStart.Y, PosEnd.Y)) return true; } return false; } FVector2D CeilVector(FVector2D Size) { return FVector2D(FMath::CeilToInt(Size.X), FMath::CeilToInt(Size.Y)); } int64 Pos2Id(float _x, float _y) { INT32 x = INT32((_x + (_x > 0 ? .5f : -.5f))); INT32 y = INT32((_y + (_y > 0 ? .5f : -.5f))); return (INT64(x) << 32) + y; } int64 Pos2Id(FVector2D Pos) { return Pos2Id(Pos.X, Pos.Y); } FString IdId2Str(INT64 IdStart, INT64 IdEnd) { if (IdStart > IdEnd) return FString::Printf(TEXT("%llx_%llx"), IdStart, IdEnd); else return FString::Printf(TEXT("%llx_%llx"), IdEnd, IdStart); } FVector2D Local2World(FVector2D& Anchor, FVector2D& Dir, FVector2D& Scale, FVector2D& LocalPos) { FVector2D Pos = LocalPos * Scale; Pos = Anchor + Pos.X*Dir + Pos.Y* FVector2D(-Dir.Y, Dir.X); return Pos; } FVector GetResSize(FString ResID) { FVector Size; IBuildingSDK *SDK = UBuildingSystem::GetBuildingSDK(); if ( SDK==nullptr) { return Size; } const char *AnsiResID = TCHAR_TO_ANSI(*ResID); IObject *pObj = SDK->GetResourceMgr()->GetResource(AnsiResID, false); if (pObj == nullptr) { return Size; } IGeometry* pGeometry = SDK->GetGeometryLibrary(); if (pGeometry == nullptr) { return Size; } IMeshObject* pMeshObj = pObj->GetMeshObject(0); if (pMeshObj == nullptr) { return Size; } kBox3D box = pMeshObj->GetBounds(); Size.X = box.MaxEdge.x - box.MinEdge.x; Size.Y = /*box.MaxEdge.y*/ - box.MinEdge.y*2; Size.Z = box.MaxEdge.z - box.MinEdge.z; return Size; } bool LoadStrim(FString ResID, TArray<FVector2D>& OutLine, int IgnoreXYZ, char* sMeshName, float& Z) { OutLine.Empty(); Z = 0; OutLine.Empty(); IBuildingSDK *SDK = UBuildingSystem::GetBuildingSDK(); CHECK_ERROR(SDK); const char *AnsiResID = TCHAR_TO_ANSI(*ResID); IObject *pObj = SDK->GetResourceMgr()->GetResource(AnsiResID, false,true,false/*,true*/); CHECK_ERROR(pObj); IGeometry* pGeometry = SDK->GetGeometryLibrary(); CHECK_ERROR(pGeometry); IMeshObject* pMeshObj = pObj->GetMeshObject(sMeshName); CHECK_ERROR(pMeshObj); kBox3D box = pMeshObj->GetBounds(); Z = box.MaxEdge.z*10; kArray<kPoint>* OutBoundarys = nullptr;; unsigned char* OutCloseFlags = nullptr;; int OutBoundaryCount; bool bSucess= pGeometry->GetMesh2DBoundary(pMeshObj, OutBoundarys, OutCloseFlags, OutBoundaryCount, IgnoreXYZ); CHECK_ERROR(bSucess); kArray<kPoint>& OutBound = OutBoundarys[0]; OutLine.SetNum(OutBound.size()); for (int i = 0; i < OutBound.size(); ++i) { FVector2D a = FVector2D(OutBound[i].x * 10, OutBound[i].y * 10); OutLine[i] = FVector2D(OutBound[i].x * 10, OutBound[i].y * 10); } return true; } bool GetMeshSize(FString ResID, char* sMeshName, FVector& Size, FVector& Pos) { IBuildingSDK *SDK = UBuildingSystem::GetBuildingSDK(); CHECK_ERROR(SDK); const char *AnsiResID = TCHAR_TO_ANSI(*ResID); IObject *pObj = SDK->GetResourceMgr()->GetResource(AnsiResID, false); CHECK_ERROR(pObj); IGeometry* pGeometry = SDK->GetGeometryLibrary(); CHECK_ERROR(pGeometry); IMeshObject* pMeshObj = pObj->GetMeshObject(sMeshName); CHECK_ERROR(pMeshObj); kBox3D box = pMeshObj->GetBounds(); kVector3D kSize = box.GetExtent()*0.5f; Size.Set(kSize.x, kSize.y, kSize.z); kVector3D kPos = box.GetCenter()*10; kPos.z = kPos.z -= kSize.z*0.5f; Pos.Set(kPos.x, kPos.y, kPos.z); return true; } eAutoSetType CategoryId2SetType(int32 categoryId, bool bFloor /*= false*/) { switch (categoryId) { case 200028: { if (bFloor) return eAutoSetFloor; return eAutoSetHang; } case 200051: { if (bFloor == false) return eAutoSetToiletHang; return eAutoSetToilet; } case 200076: { return eAutoSetTatami; } case 200015: { if (bFloor == false) return eAutoSetWardorbeHang; return eAutoSetWardrobe; } case 200116: { return eAutoSetSideboardCabinet; } case 200115: { return eAutoSetTelevision; } case 200063: { return eAutoSetBookcase; } case 200008: { return eAutoSetPorchArk; } case 200101: { return eAutoSetWashCabinet; } case 200109: { return eAutoSetStoreCabinet; } case 200119: { return eAutoSetBedCabinet; } case 200073: { return eAutoSetDesk; } case 200106: { return eAutoSetHangBedCabinet; } case 200082: { if (bFloor == false) return eAutoSetCoatroomHang; return eAutoSetCoatroom; } case 200124: { return eAutoSetBayWindowCabinet; } case 200128: { return eAutoSetTakeInCabinet; } case 200123: { return eAutoSetLaminate; } case 200129: { return eAutoSetBedside; } default: return eAutoSetNull; break; } } int32 SetType2CategoryId(eAutoSetType eSetType) { switch (eSetType) { case eAutoSetFloor: { return 200028; } break; case eAutoSetHang: { return 200028; } break; case eAutoSetToiletHang: case eAutoSetToilet: { return 200051; } break; case eAutoSetTatami: { return 200076; } break; case eAutoSetWardorbeHang: case eAutoSetWardrobe: { return 200015; } break; case eAutoSetSideboardCabinet: { return 200116; } break; case eAutoSetTelevision: { return 200115; } break; case eAutoSetBookcase: { return 200063; } break; case eAutoSetPorchArk: { return 200008; } break; case eAutoSetWashCabinet: { return 200101; } break; case eAutoSetStoreCabinet: { return 200109; } break; case eAutoSetBedCabinet: { return 200119; } break; case eAutoSetDesk: { return 200073; } break; case eAutoSetHangBedCabinet: { return 200106; } break; case eAutoSetCoatroomHang: case eAutoSetCoatroom: { return 200082; } break; case eAutoSetBayWindowCabinet: { return 200124; } break; case eAutoSetTakeInCabinet: { return 200128; } break; case eAutoSetLaminate: { return 200123; } break; case eAutoSetBedside: { return 200129; } break; default: return eAutoSetNull; break; } } int GetTurnSize(int TemplateId) { if (TemplateId == 200036) { return 562; } else if (TemplateId == 200090) { return 512; } else if (TemplateId == 200086) { return 512; } else if (TemplateId == 200098) { return 530; } else if (TemplateId == 200094) { return 530; } return 0; } bool IsTurnCabinet(int TemplateId) { if (TemplateId == 200036) { return true; } else if (TemplateId == 200090) { return true; } else if (TemplateId == 200086) { return true; } else if (TemplateId == 200098) { return true; } else if (TemplateId == 200094) { return true; } return false; } TRectBase::TRectBase(FVector2D Pos, FVector2D Size, FVector2D Dir, FVector2D Scale, FVector2D Anchor) { mScale = Scale; mDir = Dir; mSize = FVector2D(Size.X*0.5f, Size.Y*0.5f); mPos = FVector2D(Pos.X, Pos.Y) - mSize.X*Anchor.X*mDir - mSize.Y*Anchor.Y*FVector2D(-mDir.Y, mDir.X); } bool TRectBase::Collision(TLine2d & Line2d, float fOffset) { FVector2D PosStart = Line2d.mStart-mPos; PosStart = FVector2D(PosStart | mDir, PosStart | FVector2D(-mDir.Y, mDir.X) ); FVector2D PosEnd = Line2d.mEnd-mPos; PosEnd = FVector2D(PosEnd | mDir, PosEnd | FVector2D(-mDir.Y, mDir.X) ); FVector2D SegPos = (PosStart + PosEnd)*0.5f; FVector2D HalfD = PosEnd - SegPos; float adx = FMath::Abs(HalfD.X); if (FMath::Abs(SegPos.X) > mSize.X + 20 + adx) return false; float ady = FMath::Abs(HalfD.Y); if (FMath::Abs(SegPos.Y) > mSize.Y + fOffset + ady) return false; if (FMath::Abs(SegPos^HalfD) > (mSize.X + 20)*ady + (mSize.Y + fOffset)*adx) return false; return true; } float TSkuInstance::LoadSku() { static char* StrimName[3] = { "aux_trim_1","aux_trim_0","aux_trim_2" }; for (int i = 0; i < 3; ++i) { LoadStrim(mSku.mMxFileMD5, mHoles[i], 2, StrimName[i], mAnchor[i]); } return gCabinetGlobal.mFloorHeight -mAnchor[0]+ gCabinetGlobal.mTableThickness; } bool FCabinetRes::InitSinkSku(FVector2D mScale) { FVector2D Size = mScale * mTableSize; for (int i = 0; i < mSkuDatas.Num(); ++i) { if (mSkuDatas[i].mCategoryId == 726 || mSkuDatas[i].mCategoryId == 721) { TSkuData* pData = gCabinetGlobal.GetSku(Size, mSkuDatas[i].mCategoryId, mSkuDatas[i].mSkuId); if (pData == nullptr || pData->mSize.X>Size.X || pData->mSize.Y>Size.Y ) { pData = gCabinetGlobal.GetSku(Size, 726, 162860); } if( pData ) { mSkuDatas[i] = *pData; mCategoryIds[i] = pData->mSkuId; mHardSkuMd5[i] = pData->mMxFileMD5; return true; } } } return true; }
true
04ba6b83c9805c7af32d8d1e2db45bfbe986e056
C++
foiki/spbu-Homeworks
/sem1/homework2/task3/main.cpp
UTF-8
902
3.828125
4
[]
no_license
#include <iostream> using namespace std; void fareyAlorithm(int number) { int nominatorFirst = 0; int denominatorFirst = 1; int nominatorSecond = 1; int denominatorSecond = number; cout << nominatorFirst << "/" << denominatorFirst << endl; while (nominatorSecond <= number) { int k = (number + denominatorFirst) / denominatorSecond; int oldNominator = nominatorFirst; int oldDenominator = denominatorFirst; nominatorFirst = nominatorSecond; denominatorFirst = denominatorSecond; nominatorSecond = (k * nominatorSecond) - oldNominator; denominatorSecond = (k * denominatorSecond) - oldDenominator; cout << nominatorFirst << "/" << denominatorFirst << endl; } } int main() { int number = 0; cout << "Enter the maximinum denominator: "; cin >> number; fareyAlorithm(number); return 0; }
true
86e191c82d346d9f277265dbfd245b60ae25efed
C++
young1928/Cpp
/下降路径最小和.cpp
GB18030
1,355
3.265625
3
[]
no_license
һ?AҪõͨ A ½·С͡ ½·ԴӵһеκԪؿʼÿһѡһԪءһѡԪغ͵ǰѡԪһС ? ʾ 룺[[1,2,3],[4,5,6],[7,8,9]] 12 ͣ ܵ½·У [1,4,7], [1,4,8], [1,5,7], [1,5,8], [1,5,9] [2,4,7], [2,4,8], [2,5,7], [2,5,8], [2,5,9], [2,6,8], [2,6,9] [3,5,7], [3,5,8], [3,5,9], [3,6,8], [3,6,9] С½·?[1,4,7]Դ?12 ? ʾ 1 <= A.length == A[0].length <= 100 -100 <= A[i][j] <= 100 class Solution { public: int minFallingPathSum(vector<vector<int>>& A) { int n = A.size(); int m = A[0].size(); vector<vector<int> > dp = A; for(int i = 1; i < n; i++) for(int j = 0; j < m; j++) { int num = INT_MAX; for(int k = -1; k <= 1; k++) { int y = k + j; if(y < 0 || y >= m) continue; num = min(num,dp[i-1][y] + A[i][j]); } dp[i][j] = num; } int ans = INT_MAX; for(int j = 0; j < m; j++) ans = min(dp[n-1][j],ans); return ans; } };
true
76e6fe4cf48125fa3c35dca090f71af8104af4e8
C++
NikitaKhlopin/laboratory-work-2-semester
/lab18_8/person.cpp
UTF-8
821
4
4
[]
no_license
#include <iostream> #include "person.h" Person::Person() { name = ""; age = 0; } Person::Person(std::string n, int a) { name = n; age = a; } Person::~Person(){} void Person::show() { std::cout << "Имя: " << name << std::endl << "Возраст: " << age << std::endl; } void Person::input() { std::cout << "Введите имя: "; std::cin >> name; std::cout << "Введите возраст: "; std::cin >> age; } std::string Person::getName() { return name; } int Person::getAge() { return age; } void Person::setName(std::string n) { name = n; } void Person::setAge(int a) { age = a; } Person &Person::operator=(const Person &temp) { name = temp.name; age = temp.age; return *this; }
true
9419b910fab5f70901cb76c61bc41faebce78c3c
C++
ronenabr/backstage
/inwords_model/inwords_model_light/inwords_model_light.ino
UTF-8
5,212
3.078125
3
[]
no_license
//use version 3001000 of `FastLed` librery. #include "FastLED.h" #include "math.h" #include "led_setup.h" //This is a crappy program that fades an array of led from a given color to a different color // in given number of steps and given delay. //I'm using crappy static varibles for the program. Deal with it. // Will probably be good only for small led array. #define NUM_LEDS 14 CRGB leds[NUM_LEDS]; led_prog program[NUM_LEDS]; //Data line connected to pin#6 in Arduino. #define PIN 6 //Set the color of led `i` to `r`,`g`,`b`. void setled(uint8_t i, uint8_t r, uint8_t g, uint8_t b) { leds[i].r = r; leds[i].g = g; leds[i].b = b; } //Interpolate all leds using start-position // and end-position set on `program` array. // In `count` steps with delay `sleep` between steps. void run_program(int count, int sleep) { double inverse_count = 1/count; for (int idx = 0; idx < (count+1); idx++) { for (int led = 0; led < NUM_LEDS; led++) { if (!program[led].stat) { uint8_t cur_r = ((program[led].r_end * idx + program[led].r_start * (count - idx)) /count ); uint8_t cur_g = ((program[led].g_end * idx + program[led].g_start * (count - idx)) /count ); uint8_t cur_b = ((program[led].b_end * idx + program[led].b_start * (count - idx)) /count ); setled(led, cur_r, cur_g, cur_b); } } FastLED.show(); delay(sleep); } } //Set all leds in `program` to have start=end // e.g. in the next run_program will do nothing. void set_static() { for (int led = 0; led < NUM_LEDS; led++) { program[led].r_start = program[led].r_end; program[led].g_start = program[led].g_end; program[led].b_start = program[led].b_end; program[led].stat = true; } } void setup() { Serial.begin(115200); FastLED.addLeds<WS2812B, PIN, RGB>(leds, NUM_LEDS); } ////////////////////////////////// // INWORDS model led array // ////////////////////////////////// // Entrence // /----------@@@@---------\ // | 4+5 6+7+8 9,10 | // | | // | (12) | // | | // | 13 ^ 11 | // | /_\ | // | 3+2 0+1 | // \_______________________/ void parameter(uint8_t front_r ,uint8_t front_g, uint8_t front_b ) { int inter_fraction = 3; //Initilize the gate-leds in 100 steps. program[7] = led_prog(0, 0, 0, front_r/inter_fraction, front_g/inter_fraction, front_b/inter_fraction); run_program(100, 10); //Leave the gate leds as is //Initilize the gate-leds in 100 steps. program[6] = led_prog(0, 0, 0, front_r, front_g, front_b); program[7] = led_prog(front_r/inter_fraction, front_g/inter_fraction, front_b/inter_fraction, front_r, front_g, front_b); program[8] = led_prog(0, 0, 0, front_r, front_g, front_b); run_program(300, 10); //Leave the gate leds as is set_static(); program[9] = led_prog(0, 0, 0, front_r/inter_fraction, front_g/inter_fraction, front_b/inter_fraction); program[5] = led_prog(0, 0, 0, front_r/inter_fraction, front_g/inter_fraction, front_b/inter_fraction); run_program(100, 10); set_static(); program[9] = led_prog(front_r/inter_fraction, front_g/inter_fraction, front_b/inter_fraction, front_r, front_g, front_b); program[9] = led_prog(front_r/inter_fraction, front_g/inter_fraction, front_b/inter_fraction, front_r, front_g, front_b); program[4] = led_prog(0, 0, 0, 30, 10, 100); program[10] = led_prog(0, 0, 0, 30, 10, 100); run_program(300, 10); set_static(); program[0] = led_prog(0, 0, 0, front_r/inter_fraction, front_g/inter_fraction, front_b/inter_fraction); program[3] = led_prog(0, 0, 0, front_r/inter_fraction, front_g/inter_fraction, front_b/inter_fraction); run_program(100, 10); set_static(); program[0] = led_prog(front_r/inter_fraction, front_g/inter_fraction, front_b/inter_fraction, front_r, front_g, front_b); program[3] = led_prog(front_r/inter_fraction, front_g/inter_fraction, front_b/inter_fraction, front_r, front_g, front_b); program[1] = led_prog(0, 0, 0, 30, 10, 100); program[2] = led_prog(0, 0, 0, 30, 10, 100); run_program(300, 10); } void tower(unsigned char t_r, unsigned char t_g, unsigned char t_b) { //Turn on the tower leds. set_static(); program[11] = led_prog(0, 0, 0, t_r, t_g, t_b); program[12] = led_prog(0, 0, 0, t_r, t_g, t_b); program[13] = led_prog(0, 0, 0, t_r, t_g, t_b); run_program(300, 10); } void final() { delay(10000); set_static(); //for (int led = 0; led < NUM_LEDS; led++) // program[led].set_end(0, 0, 0); //run_program(200, 15); //delay(2000); } void init_state() { for (int led=0; led<NUM_LEDS; led++) { leds[led].r = 0; leds[led].g = 0; leds[led].b = 0; program[led] = led_prog(); } FastLED.show(); } void loop() { // put your main code here, to run repeatedly: init_state(); parameter(60,0,180); tower(30, 100, 0); final(); init_state(); delay(3000); parameter(180,0,60); tower(0, 100, 30); final(); init_state(); delay(3000); parameter(60,180,0); tower(0, 30, 100); final(); init_state(); delay(3000); }
true
d7ea8c3ce2a2cd17ee9425771eae1506833e1db6
C++
rafapaz/megamanportal
/src/scenarium.cpp
UTF-8
2,866
2.765625
3
[]
no_license
#include <allegro5/allegro5.h> #include <vector> #include <sstream> #include <fstream> #include <stdio.h> #include <math.h> #include "commom.h" #include "scenarium.h" Scenarium::Scenarium(Player *p) { player = p; level = 1; cameraPos[0] = cameraPos[1] = 0; } Scenarium::~Scenarium() { cleanLevel(); plats.~vector(); } void Scenarium::moveCamera() { cameraPos[0] = - (SCREENWIDTH/2) + (player->getPosX() + player->getWidth()); //cameraPos[1] = - (SCREENHEIGHT/2) + (player->getPosY() + player->getHeight()); if (cameraPos[0] < 0) cameraPos[0] = 0; if (cameraPos[1] < 0) cameraPos[1] = 0; al_identity_transform(&camera); al_translate_transform(&camera, -cameraPos[0], -cameraPos[1]); al_use_transform(&camera); } void Scenarium::Update() { int i; if (player->getPosX() > mapSizeX*BLOCK_SIZE) next_level = true; for (i=0; i < plats.size();i++) plats[i]->Update(); } void Scenarium::cleanLevel() { int i; for (i=0; i < plats.size();i++) { delete plats[i]; } plats.clear(); } bool Scenarium::startLevel(int l) { int i, j; Limits laux; std::vector<Limits> lim; if (l > LEVELS) { printf("You Win!\n"); return false; } level = l; cleanLevel(); loadLevel(); for (i=0;i < mapSizeX; i++) { for (j=0;j < mapSizeY; j++) { if (map[i][j] == 1) plats.push_back(new Platform(i * BLOCK_SIZE, j * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE, al_map_rgb(0, 255, 0))); } } // Fill collision limits to the player for (i=0; i < plats.size();i++) { laux.x0 = plats[i]->getPosX(); laux.y0 = plats[i]->getPosY(); laux.x1 = plats[i]->getPosX() + plats[i]->getWidth(); laux.y1 = plats[i]->getPosY() + plats[i]->getHeight(); lim.push_back(laux); } player->setLimits(lim); next_level = false; player->startLevel(); return true; } void Scenarium::loadLevel() { int i,j,k; std::stringstream map_str; std::string line; map_str << "../maps/L" << level << ".txt"; std::ifstream openfile(map_str.str().c_str()); map_str.str(""); if (openfile.is_open()) { std::getline(openfile, line); mapSizeX = ceil(((float)line.length())/2); openfile.seekg(0, std::ios::beg); j=k=0; while (!openfile.eof()) { openfile >> map[j++][k]; if (j >= mapSizeX) { j=0; k++; } } mapSizeY = k; } else { printf("Error on loading map %d \n", level); exit(1); } openfile.close(); /* printf("Printing map: \n"); for (i=0;i<mapSizeY;i++) { for (j=0;j<mapSizeX;j++) { printf("%d ", map[j][i]); } printf("\n"); } */ } bool Scenarium::nextLevel() { return next_level; }
true
a684c0c8e4eadfab8ead7bea5bc186b99d9e06e5
C++
flanggut/smvs
/tests/gtest_matrix_vector.cc
UTF-8
8,181
2.640625
3
[ "BSD-3-Clause" ]
permissive
/* * Copyright (C) 2016, Fabian Langguth * TU Darmstadt - Graphics, Capture and Massively Parallel Computing * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD 3-Clause license. See the LICENSE.txt file for details. */ #include <gtest/gtest.h> #include "sse_vector.h" #include "block_sparse_matrix.h" #include "ldl_decomposition.h" TEST(LDLDecompositionTest, inverse) { double A[9] {2, -1, 0, -1, 2, -1, 0 , -1, 1}; smvs::ldl_inverse(A, 3); double const epsilon = 1e-15; EXPECT_NEAR(1, A[0], epsilon); EXPECT_NEAR(1, A[1], epsilon); EXPECT_NEAR(1, A[2], epsilon); EXPECT_NEAR(1, A[3], epsilon); EXPECT_NEAR(2, A[4], epsilon); EXPECT_NEAR(2, A[5], epsilon); EXPECT_NEAR(1, A[6], epsilon); EXPECT_NEAR(2, A[7], epsilon); EXPECT_NEAR(3, A[8], epsilon); } TEST(SSEVectorTest, dot) { smvs::SSEVector a(5); smvs::SSEVector b(5); a[0] = 1.0; a[1] = 2.0; a[2] = 3.0; a[3] = 1.0; a[4] = 2.0; b[0] = 1.0; b[1] = 2.0; b[2] = 3.0; b[3] = 1.0; b[4] = 2.0; double d = a.dot(b); EXPECT_DOUBLE_EQ(19.0, d); } TEST(SSEVectorTest, add) { smvs::SSEVector a(5); smvs::SSEVector b(5); a[0] = 4.0; a[1] = 2.0; a[2] = 3.0; a[3] = 1.0; a[4] = 2.0; b[0] = 1.0; b[1] = 7.0; b[2] = 3.0; b[3] = 8.0; b[4] = 2.0; smvs::SSEVector c = a.add(b); for (int i = 0; i < 5; ++i) EXPECT_DOUBLE_EQ(a[i] + b[i], c[i]); } TEST(SSEVectorTest, subtract) { smvs::SSEVector a(5); smvs::SSEVector b(5); a[0] = 1.0; a[1] = 2.0; a[2] = 3.0; a[3] = 10.0; a[4] = 2.0; b[0] = 11.0; b[1] = 2.0; b[2] = 30.0; b[3] = 1.0; b[4] = 29.0; smvs::SSEVector c = a.subtract(b); for (int i = 0; i < 5; ++i) EXPECT_DOUBLE_EQ(a[i] - b[i], c[i]); } TEST(SSEVectorTest, multiply) { smvs::SSEVector a(5); a[0] = 12.0; a[1] = 2.0; a[2] = 3.0; a[3] = 10.0; a[4] = 2.0; double rhs = 4.3; smvs::SSEVector c = a.multiply(rhs); for (int i = 0; i < 5; ++i) EXPECT_DOUBLE_EQ(a[i] * rhs, c[i]); } TEST(SSEVectorTest, multiply_add) { smvs::SSEVector a(5); a[0] = 12.0; a[1] = 2.0; a[2] = 3.0; a[3] = 10.0; a[4] = 2.0; smvs::SSEVector b(5); b[0] = 11.0; b[1] = 2.0; b[2] = 30.0; b[3] = 1.0; b[4] = 29.0; double factor = 4.3; smvs::SSEVector c = a.multiply_add(b, factor); for (int i = 0; i < 5; ++i) EXPECT_DOUBLE_EQ(a[i] + b[i] * factor, c[i]); } TEST(SSEVectorTest, multiply_sub) { smvs::SSEVector a(5); a[0] = 12.0; a[1] = 2.0; a[2] = 3.0; a[3] = 10.0; a[4] = 2.0; smvs::SSEVector b(5); b[0] = 11.0; b[1] = 2.0; b[2] = 30.0; b[3] = 1.0; b[4] = 29.0; double factor = 4.3; smvs::SSEVector c = a.multiply_sub(b, factor); for (int i = 0; i < 5; ++i) EXPECT_DOUBLE_EQ(a[i] - b[i] * factor, c[i]); } TEST(SSEVectorTest, multiply_add_large) { int const dim = 1000000; smvs::SSEVector a(dim); smvs::SSEVector b(dim); for (int i = 0; i < dim; ++i) { a[i] = i % 3; b[i] = i % 7; } double factor = 0.3; smvs::SSEVector c = a.multiply_add(b, factor); for (int i = 0; i < dim; ++i) EXPECT_DOUBLE_EQ(a[i] + b[i] * factor, c[i]); } TEST(SSEVectorTest, multiply_sub_large) { int const dim = 1000000; smvs::SSEVector a(dim); smvs::SSEVector b(dim); for (int i = 0; i < dim; ++i) { a[i] = i % 7; b[i] = i % 3; } double factor = 0.3; smvs::SSEVector c = a.multiply_sub(b, factor); for (int i = 0; i < dim; ++i) EXPECT_DOUBLE_EQ(a[i] - b[i] * factor, c[i]); } TEST (BlockSparseMatrixTest, Create) { smvs::BlockSparseMatrix<4> bs_matrix; smvs::BlockSparseMatrix<4> bs_matrix2(100,100); } TEST (BlockSparseMatrixTest, SetFromBlocks) { typedef smvs::BlockSparseMatrix<2> BSMatrix; BSMatrix bs_matrix(4, 4); double values1[4] = {1, 2, 3, 4}; double values2[4] = {4, 3, 2, 1}; BSMatrix::Blocks blocks; blocks.emplace_back(0, 0, values1); blocks.emplace_back(2, 2, values2); bs_matrix.set_from_blocks(blocks); EXPECT_EQ(2, bs_matrix.num_non_zero()); BSMatrix::Blocks blocks2; blocks2.emplace_back(2, 2, values2); blocks2.emplace_back(0, 0, values1); bs_matrix.set_from_blocks(blocks2); EXPECT_EQ(2, bs_matrix.num_non_zero()); } TEST (BlockSparseMatrixTest, SetFromTriplets) { typedef smvs::BlockSparseMatrix<2> BSMatrix; BSMatrix::Triplets triplets; triplets.emplace_back(0, 0, 11); triplets.emplace_back(0, 1, 12); triplets.emplace_back(0, 2, 13); triplets.emplace_back(0, 3, 14); triplets.emplace_back(1, 1, 22); triplets.emplace_back(1, 2, 23); triplets.emplace_back(2, 2, 33); triplets.emplace_back(2, 3, 34); triplets.emplace_back(2, 4, 35); triplets.emplace_back(2, 5, 36); triplets.emplace_back(3, 3, 44); triplets.emplace_back(3, 4, 45); triplets.emplace_back(4, 5, 56); triplets.emplace_back(5, 5, 66); BSMatrix bs_matrix(6, 6); bs_matrix.set_from_triplets(triplets); EXPECT_EQ(5, bs_matrix.num_non_zero()); } TEST (BlockSparseMatrixTest, Multiply) { typedef smvs::BlockSparseMatrix<2> BSMatrix; BSMatrix bs_matrix(4, 4); double values1[4] = {1, 2, 3, 4}; double values2[4] = {5, 3, 2, 0}; BSMatrix::Blocks blocks; blocks.emplace_back(0, 0, values1); blocks.emplace_back(2, 2, values2); bs_matrix.set_from_blocks(blocks); smvs::SSEVector x(4, 1); smvs::SSEVector rhs; rhs = bs_matrix.multiply(x); EXPECT_EQ(3, rhs[0]); EXPECT_EQ(7, rhs[1]); EXPECT_EQ(8, rhs[2]); EXPECT_EQ(2, rhs[3]); BSMatrix::Blocks blocks2; blocks2.emplace_back(2, 2, values2); blocks2.emplace_back(0, 0, values1); bs_matrix.set_from_blocks(blocks2); rhs = bs_matrix.multiply(x); EXPECT_EQ(3, rhs[0]); EXPECT_EQ(7, rhs[1]); EXPECT_EQ(8, rhs[2]); EXPECT_EQ(2, rhs[3]); BSMatrix::Blocks blocks3; blocks3.emplace_back(2, 2, values2); blocks3.emplace_back(0, 2, values1); blocks3.emplace_back(0, 0, values1); bs_matrix.set_from_blocks(blocks3); rhs = bs_matrix.multiply(x); EXPECT_EQ(6, rhs[0]); EXPECT_EQ(14, rhs[1]); EXPECT_EQ(8, rhs[2]); EXPECT_EQ(2, rhs[3]); } TEST (BlockSparseMatrixTest, SetFromTripletsMultiply) { typedef smvs::BlockSparseMatrix<2> BSMatrix; BSMatrix::Triplets triplets; triplets.emplace_back(0, 0, 1); triplets.emplace_back(0, 1, 2); triplets.emplace_back(1, 0, 3); triplets.emplace_back(1, 1, 4); triplets.emplace_back(2, 2, 5); triplets.emplace_back(2, 3, 3); triplets.emplace_back(3, 2, 2); triplets.emplace_back(3, 3, 0); BSMatrix bs_matrix(4, 4); bs_matrix.set_from_triplets(triplets); smvs::SSEVector x(4, 1); smvs::SSEVector rhs; rhs = bs_matrix.multiply(x); EXPECT_EQ(3, rhs[0]); EXPECT_EQ(7, rhs[1]); EXPECT_EQ(8, rhs[2]); EXPECT_EQ(2, rhs[3]); triplets.emplace_back(2, 0, 2); triplets.emplace_back(2, 1, 7); triplets.emplace_back(3, 0, 4); triplets.emplace_back(3, 1, 1); BSMatrix bs_matrix2(4, 4); bs_matrix2.set_from_triplets(triplets); rhs = bs_matrix2.multiply(x); smvs::SSEVector rhs2; rhs2 = bs_matrix2.multiply(x); EXPECT_EQ(rhs2[0], rhs[0]); EXPECT_EQ(rhs2[1], rhs[1]); EXPECT_EQ(rhs2[2], rhs[2]); EXPECT_EQ(rhs2[3], rhs[3]); } TEST (BlockSparseMatrixTest, BlockInvert) { typedef smvs::BlockSparseMatrix<2> BSMatrix; BSMatrix bs_matrix(4, 4); double values1[4] = {2, 0, 0, 2}; BSMatrix::Blocks blocks; blocks.emplace_back(0, 0, values1); blocks.emplace_back(2, 2, values1); bs_matrix.set_from_blocks(blocks); bs_matrix.invert_blocks_inplace(); smvs::SSEVector x(4, 1); smvs::SSEVector rhs; rhs = bs_matrix.multiply(x); EXPECT_NEAR(0.5, rhs[0], 1e-10); EXPECT_NEAR(0.5, rhs[1], 1e-10); EXPECT_NEAR(0.5, rhs[2], 1e-10); EXPECT_NEAR(0.5, rhs[3], 1e-10); }
true
272732f9d6f1b6affdac5dc772fa9c0a205d64ed
C++
AStoimenovGit/Median
/Demo/Demo/Map.h
UTF-8
2,185
3.375
3
[]
no_license
#ifndef _Map_h_ #define _Map_h_ #include <map> #include "Median.h" /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Map of values and number of their occurances */ template <class T, class Compare = std::less<T>> class Map : public Median<T, Compare> { using BaseClass = Median<T, Compare>; public: Map(); virtual void Clear(); virtual void Insert(const T& value); virtual bool GetMedian(T& median) const; private: std::map<T, int, Compare> m_values; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <class T, class Compare> Map<T, Compare>::Map() : m_values() { } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <class T, class Compare> /*virtual*/ void Map<T, Compare>::Clear() { BaseClass::Clear(); m_values.clear(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <class T, class Compare> /*virtual*/ void Map<T, Compare>::Insert(const T& value) { BaseClass::Insert(value); ++m_values[value]; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <class T, class Compare> /*virtual*/ bool Map<T, Compare>::GetMedian(T& median) const { if (!BaseClass::m_size) return false; int steps = BaseClass::m_size / 2; for (const auto& val : m_values) { if (steps >= val.second) { steps -= val.second; continue; } if(BaseClass::m_size % 2) { median = val.first; } else if (steps) { median = val.first; } else { auto prev = m_values.find(val.first); assert(prev != m_values.end()); assert(prev != m_values.begin()); --prev; median = (val.first + prev->first) / static_cast<T>(2); } break; } return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #endif // _Map_h_
true
38fafd4969b9324f5d830d5d4851457266ec9a69
C++
ebagli/ECHARM_CXX
/phi/src/ECHARM_lattice.cpp
UTF-8
8,091
2.765625
3
[]
no_license
// // ECHARM_lattice.cpp // // // Created by Enrico Bagli on 04/06/12. // Copyright 2012 Enrico Bagli. All rights reserved. // ECHARM_lattice::ECHARM_lattice() { InitializePointersLattice(); } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... ECHARM_lattice::ECHARM_lattice(std::string LatticeType) { InitializePointersLattice(); fLatticeType = LatticeType; FindLatticePoints(); } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... ECHARM_lattice::~ECHARM_lattice() { if (&fLatticeType) { delete &fLatticeType; } } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... const ECHARM_lattice& ECHARM_lattice::operator=(const ECHARM_lattice& right) { if (this != &right) { InitializePointersLattice(); fLatticeType = right.fLatticeType; fLatticeCoordinates = right.fLatticeCoordinates; for(unsigned int i = 0;i<right.fLatticeCoordinates.size();i++) fLatticeCoordinates.push_back(right.fLatticeCoordinates.at(i)); } return *this; } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... void ECHARM_lattice::InitializePointersLattice() { fLatticeType.clear(); fLatticeCoordinates.clear(); } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... void ECHARM_lattice::PrintLatticeCoordinates() { std::cout << "ECHARM_lattice - Print Lattice " << fLatticeType << " Coordinates" << std::endl; std::cout << "Point X/X_0 Y/Y_0 Z/Z_0" << std::endl; for(unsigned int i = 0;i<fLatticeCoordinates.size();i++) fLatticeCoordinates.at(i)->PrintThreeVector(); } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... void ECHARM_lattice::PrintLatticeCoordinates(std::string Axis) { std::cout << "ECHARM_lattice - Print Lattice " << fLatticeType << " Coordinates" << std::endl; } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... void ECHARM_lattice::AddThreeVector(double X,double Y,double Z) { ECHARM_threevector *vector = new ECHARM_threevector(X,Y,Z); fLatticeCoordinates.push_back(vector); } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... void ECHARM_lattice::DeleteThreeVector(unsigned int vIndex) { fLatticeCoordinates.erase(fLatticeCoordinates.begin()+vIndex); } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... void ECHARM_lattice::FindLatticePoints() { if(fLatticeType == "cubic") { // std::cout << "ECHARM_lattice - Face Centered Cubic Lattice Created" << std::endl; AddThreeVector(0.0,0.0,0.0); } else if(fLatticeType == "cubicc") { // std::cout << "ECHARM_lattice - Face Centered Cubic Lattice Created" << std::endl; AddThreeVector(0.5,0.5,0.5); } else if(fLatticeType == "bcc") { // std::cout << "ECHARM_lattice - Face Centered Cubic Lattice Created" << std::endl; AddThreeVector(0.0,0.0,0.0); AddThreeVector(0.5,0.5,0.5); } else if(fLatticeType == "fcc") { // std::cout << "ECHARM_lattice - Face Centered Cubic Lattice Created" << std::endl; AddThreeVector(0.0,0.0,0.0); AddThreeVector(0.5,0.5,0.0); AddThreeVector(0.0,0.5,0.5); AddThreeVector(0.5,0.0,0.5); } else if(fLatticeType == "diamond") { // std::cout << "ECHARM_lattice - Diamond Lattice Created" << std::endl; for(unsigned int i=0;i<2;i++) { AddThreeVector(0.0+0.25*i,0.0+0.25*i,0.0+0.25*i); AddThreeVector(0.5+0.25*i,0.5+0.25*i,0.0+0.25*i); AddThreeVector(0.0+0.25*i,0.5+0.25*i,0.5+0.25*i); AddThreeVector(0.5+0.25*i,0.0+0.25*i,0.5+0.25*i); } } else { ReadCoordinatesFromFile(fLatticeType); } } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... void ECHARM_lattice::ReadCoordinatesFromFile(std::string vFileName) { std::ifstream File_LatticeIn; ECHARM_threevector *vector_old = new ECHARM_threevector(); File_LatticeIn.open(vFileName.c_str()); if(File_LatticeIn) { int nlines = 0; double temp_x,temp_y,temp_z; temp_x = temp_y = temp_z = 0.0; do { vector_old->Set(temp_x,temp_y,temp_z); if(!File_LatticeIn.eof()) File_LatticeIn >> temp_x; if(!File_LatticeIn.eof()) File_LatticeIn >> temp_y; if(!File_LatticeIn.eof()) File_LatticeIn >> temp_z; if(nlines == 0) AddThreeVector(temp_x,temp_y,temp_z); else if(!( (temp_x == vector_old->GetX()) && (temp_y == vector_old->GetY()) && (temp_z == vector_old->GetZ()))) { AddThreeVector(temp_x,temp_y,temp_z); } nlines++; } while (!File_LatticeIn.eof()); std::cout << "ECHARM_lattice - " << nlines << " lines have been read" << std::endl; } else std::cout << "ECHARM_lattice ERROR - lattice & lattice file do not exist" << std::endl; File_LatticeIn.close(); } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... void ECHARM_lattice::ReadCoordinatesNotNormalizedFromFile(std::string vFileName, ECHARM_threevector *vSize) { std::ifstream File_LatticeIn; ECHARM_threevector *vector_old = new ECHARM_threevector(); File_LatticeIn.open(vFileName.c_str()); if(File_LatticeIn) { int nlines = 0; double temp_x,temp_y,temp_z; temp_x = temp_y = temp_z = 0.0; do { vector_old->Set(temp_x,temp_y,temp_z); if(!File_LatticeIn.eof()) File_LatticeIn >> temp_x; if(!File_LatticeIn.eof()) File_LatticeIn >> temp_y; if(!File_LatticeIn.eof()) File_LatticeIn >> temp_z; if(nlines == 0) AddThreeVector(temp_x/vSize->GetX(),temp_y/vSize->GetY(),temp_z/vSize->GetZ()); else if(!( (temp_x == vector_old->GetX()) && (temp_y == vector_old->GetY()) && (temp_z == vector_old->GetZ()))) { AddThreeVector(temp_x/vSize->GetX(),temp_y/vSize->GetY(),temp_z/vSize->GetZ()); } nlines++; } while (!File_LatticeIn.eof()); std::cout << "ECHARM_lattice - " << nlines << " lines have been read" << std::endl; } else std::cout << "ECHARM_lattice ERROR - lattice & lattice file do not exist" << std::endl; File_LatticeIn.close(); //delete &vector_old; } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... int ECHARM_lattice::operator==(const ECHARM_lattice& right) const { return (this == (ECHARM_lattice*) &right); } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... int ECHARM_lattice::operator!=(const ECHARM_lattice& right) const { return (this != (ECHARM_lattice*) &right); } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... std::vector<double> ECHARM_lattice::FindStructureFactor(int vIndex[3]) { std::vector<double> vSF; double vTempDouble = 0.0; vSF.push_back(0.0); vSF.push_back(0.0); for(unsigned int i=0;i<fLatticeCoordinates.size();i++) { vTempDouble = 0.0; for(unsigned int k=0;k<3;k++) vTempDouble += double(vIndex[k]) * fLatticeCoordinates.at(i)->GetComponent(k); vSF.at(0) += cos(2 * M_PI * vTempDouble); vSF.at(1) += sin(2 * M_PI * vTempDouble); } return vSF; } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... std::vector<double> ECHARM_lattice::FindStructureFactor(int vIndex00,int vIndex01,int vIndex02) { int vIndex[3]; vIndex[0]=vIndex00; vIndex[1]=vIndex01; vIndex[2]=vIndex02; std::vector<double> vSF = FindStructureFactor(vIndex); return vSF; } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
true
b019dbeb52d73d1f009ef704b2d8e880cb26f0c4
C++
RyanFluck/ECE0302
/limited_size_bag_tests.cpp
UTF-8
774
3.125
3
[]
no_license
#define CATCH_CONFIG_MAIN #include "catch.hpp" #include "limited_size_bag.tpp" // force template expansion for ints template class LimitedSizeBag<int>; TEST_CASE("Test 1", "[LimitedSizeBag]") { LimitedSizeBag<int> limitbag; REQUIRE(limitbag.getCurrentSize() == 10); REQUIRE(limitbag.fillNum() == 0); //placing in value 15 int a = 15; int & input = a; REQUIRE(true == limitbag.add(input)); }; TEST_CASE("Test 2", "[LimitedSizeBag]") { LimitedSizeBag<int> bag; int a = 1; int b = 2; int c = 3; int d = 4; int & fill1 = a; int & fill2 = b; int & fill3 = c; int & fill4 = d; bag.add(fill1); bag.add(fill2); bag.add(fill3); REQUIRE(bag.remove(fill4) == false); REQUIRE(bag.remove(fill3) == true); REQUIRE(bag.getCurrentSize() == 10); REQUIRE(bag.isEmpty() == false); }
true
02461d62dc630ce14c95a3ccb65a9a99c3fad5e7
C++
DoobleD/Air
/Air/include/FingersListener.hpp
UTF-8
4,157
2.65625
3
[]
no_license
#ifndef _FINGERS_LISTENER_HPP_ #define _FINGERS_LISTENER_HPP_ #include "XnFingersGenerator.hpp" #include "MouseControl.hpp" #include "OS/Screen.hpp" namespace air { /** * Handle the fingers related callbacks, which are called by xn::FingersGenerator. * Transmitt fingers data to a MouseControl object, since fingers are * controlling mouse. If no mouse action is recognized, simply display fingers * positions above screen. * * @author Pierre Alletru */ class FingersListener { private: // A screen object used to draw fingers on screen. static os::Screen m_screen; // The MouseControl object recognizing fingers gestures and perform mouse actions. static MouseControl m_mouseControl; /** * Called only if DEBUG_MOD is defined. Draw circles on debug screen where * detected finger tips are located, and where the hand palm is located. * * @param fingersData A pointer to a structure containing fingers * information. */ static void showDebug(xn::FingersData * fingersData); /** * Draw rectangles above OS screen where detected finger tips are located, * and where the hand palm is located. * * @param fingersData A pointer to a structure containing fingers * information. */ static void drawHandToScreen(xn::FingersData * fingersData); /** * Converts real world finger coordinates in the given FingersData structure, to * their corresponding coordinates on OS screen. * * @param fingersData A pointer to a structure containing fingers * information. */ static void toScreenCoord(xn::FingersData * fingersData); public: /** * xn::FingersGenerator callback called when a hand and its fingers has been * detected for the first time in the session. Does no action. * * @param gen A reference to the FingersGenerator object * which has detected the hand and generated * the given data. * @param id The hand id. * @param fingersData A pointer to a structure containing hand and * fingers information. * @param time A timestamp, in seconds. * @param userData A pointer to some undefined data. * Not used here (is equal to NULL). */ static void XN_CALLBACK_TYPE FingersCreate(xn::FingersGenerator & gen, XnUserID id, xn::FingersData * fingersData, XnFloat time, void * userData); /** * xn::FingersGenerator callback called every frame while a hand and its fingers * are still detected, indicating hand and fingers positions and * related information. * Essentially transmitt data to the MouseControl object member, and * draw fingers on OS screen if MouseControl doesn't recognize any fingers gesture. * * @param gen A reference to the FingersGenerator object * which has detected the hand and generated * the given data. * @param id The hand id. * @param fingersData A pointer to a structure containing hand and * fingers information. * @param time A timestamp, in seconds. * @param userData A pointer to some undefined data. * Not used here (is equal to NULL). */ static void XN_CALLBACK_TYPE FingersUpdate(xn::FingersGenerator & gen, XnUserID id, xn::FingersData * fingersData, XnFloat time, void * userData); /** * xn::FingersGenerator callback called when a hand is lost * (is no longer detected). * * @param gen A reference to the FingersGenerator object * which has pereviously detected the hand. * @param id The hand id. * @param time A timestamp, in seconds. * @param userData A pointer to some undefined data. * Not used here (is equal to NULL). */ static void XN_CALLBACK_TYPE FingersDestroy(xn::FingersGenerator & gen, XnUserID id, XnFloat time, void * userData); }; } #endif //_FINGERS_LISTENER_HPP_
true
1876a1f5ff08ec8cc107798b2634daf906668d12
C++
ArfreeX/TravelingSalesmanProblem-PEA_1
/tests/DataGenerator.h
UTF-8
907
2.953125
3
[]
no_license
#ifndef DATAGENERATOR_H #define DATAGENERATOR_H #include <limits.h> #include "helpers/FileStream.h" #include "helpers/RandomNumberGenerator.h" namespace tests { class DataGenerator { public: static std::vector<std::vector<int>> drawData(unsigned dataSize, unsigned dataRange) { helpers::FileStream file; helpers::RandomNumberGenerator numberGen(dataRange); std::vector<std::vector<int>> dataSet(dataSize); for (unsigned i = 0; i < dataSize; i++) { for(unsigned j = 0; j < dataSize; j++) { if(i == j) { dataSet[i].emplace_back(0); } else { dataSet[i].emplace_back(numberGen.drawNumber()); } } } return dataSet; } }; } // namespace tests #endif // DATAGENERATOR_H
true
823c08b737042d6b92388fe5c85420d9639234d0
C++
tccmobile/Fall2017
/PersonData.cpp
UTF-8
762
3.484375
3
[]
no_license
// // Created by Will Smith on 11/9/17. // #include "PersonData.h" #include <iostream> using namespace std; void PersonData::SetAge(int ageYears) { PersonData::ageYears = ageYears; } void PersonData::SetName(const string &lastName) { PersonData::lastName = lastName; } void PersonData::PrintAll(){ cout << "Name: " << lastName; cout << ", Age: " << ageYears; } PersonData::PersonData() { cout<<"PersonData default constructor called!"<<endl; } PersonData::PersonData(int ageYears, const string &lastName) : ageYears(ageYears), lastName(lastName) { cout<<"PersonData parameterized constructor called"<<endl; } int PersonData::GetAge() const { return ageYears; } const string &PersonData::GetName() const { return lastName; }
true
6d1e34d8e5bdbc90a1330d71ebaedcaa10456e14
C++
sialiuk/TaskDispatcher
/TestSingleton/TestSingleton.cpp
UTF-8
2,301
2.859375
3
[]
no_license
// TestSingleton.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <WinBase.h> using namespace mtd; namespace { struct Count { Count() { ++m_count; } ~Count() { } static size_t m_count; }; size_t Count::m_count = 0; typedef SingletonHolder<Count, CreateStaticVariable, MultiThreadedMutexLock> SingletonStaticMutex; typedef SingletonHolder<Count, CreateWithNew, MultiThreadedMutexLock> SingletonNewMutex; typedef SingletonHolder<Count, CreateStaticVariable, MultiThreadedLockFree> SingletonStaticLockFree; typedef SingletonHolder<Count, CreateWithNew, MultiThreadedLockFree> SingletonNewLockFree; } BOOST_AUTO_TEST_CASE(TestSingletonHolderDefault) { typedef SingletonHolder<int> Singleton; int& result1 = Singleton::Instance(); int& result2 = Singleton::Instance(); BOOST_CHECK(&result1 == &result2); } BOOST_AUTO_TEST_CASE(TestSingletonSingleThreadingUseStaticVariable) { typedef SingletonHolder<int, CreateStaticVariable> Singleton; int& result1 = Singleton::Instance(); int& result2 = Singleton::Instance(); BOOST_CHECK(&result1 == &result2); } BOOST_AUTO_TEST_CASE(TestSingletonMultiThreadingUseStaticVariable) { boost::thread_group pool; for(int i = 0; i != 20; ++i) { pool.create_thread([](){ SingletonStaticMutex::Instance(); }); } pool.join_all(); BOOST_CHECK(Count::m_count == 1); Count::m_count = 0; } BOOST_AUTO_TEST_CASE(TestSingletonMultiThreadingUseNew) { boost::thread_group pool; for(int i = 0; i != 20; ++i) { pool.create_thread([](){ SingletonNewMutex::Instance(); }); } pool.join_all(); BOOST_CHECK(Count::m_count == 1); Count::m_count = 0; } BOOST_AUTO_TEST_CASE(TestSingletonMultiThreadingLockFreeUseStaticVariable) { boost::thread_group pool; for(int i = 0; i != 20; ++i) { pool.create_thread([](){ SingletonStaticLockFree::Instance(); }); } pool.join_all(); BOOST_CHECK(Count::m_count == 0); } BOOST_AUTO_TEST_CASE(TestSingletonMultiThreadingLockFreeUseNew) { boost::thread_group pool; for(int i = 0; i != 20; ++i) { pool.create_thread([](){ SingletonNewLockFree::Instance(); }); } pool.join_all(); BOOST_CHECK(Count::m_count == 1); Count::m_count = 0; }
true
d5846c91599c8861187460c6af53151daada3d0a
C++
MeeSong/hvpp
/src/hvpp/hvpp/lib/mp.h
UTF-8
1,414
2.984375
3
[ "MIT", "LicenseRef-scancode-free-unknown", "BSD-2-Clause" ]
permissive
#pragma once #include <cstdint> // // Multi-Processor functions. // namespace mp { namespace detail { uint32_t cpu_count() noexcept; uint32_t cpu_index() noexcept; void sleep(uint32_t milliseconds) noexcept; void ipi_call(void(*callback)(void*), void* context) noexcept; } inline uint32_t cpu_count() noexcept { return detail::cpu_count(); } inline uint32_t cpu_index() noexcept { return detail::cpu_index(); } inline void sleep(uint32_t milliseconds) noexcept { detail::sleep(milliseconds); } inline void ipi_call(void(*callback)(void*), void* context) noexcept { detail::ipi_call(callback, context); } inline void ipi_call(void(*callback)()) noexcept { detail::ipi_call([](void* context) { ((void(*)())context)(); }, callback); } template < typename T > inline void ipi_call(T* instance, void (T::*member_function)()) noexcept { // // Inter-Processor Interrupt - runs specified method on all logical CPUs. // struct ipi_ctx { T* instance; void (T::*member_function)(); } ipi_context { instance, member_function }; ipi_call([](void* context) noexcept { auto ipi_context = reinterpret_cast<ipi_ctx*>(context); auto instance = ipi_context->instance; auto member_function = ipi_context->member_function; (instance->*member_function)(); }, &ipi_context); } }
true
30a3e97bf83913c424822bfa8a62058739adf65d
C++
raynardbrown/graphics
/inc/graphics/Point2D.h
UTF-8
2,412
3.3125
3
[]
no_license
//////////////////////////////////////////////////////////////////////////////// // // File: Point2D.h // // Author: Raynard Brown // // Copyright (c) 2020 Raynard Brown // // All rights reserved. // //////////////////////////////////////////////////////////////////////////////// #ifndef GRAPHICS_POINT_H_ #define GRAPHICS_POINT_H_ /** * Point in a two-dimensional coordinate system. */ class Point2D { public: /** * Create a new <code>Point2D</code> with the x and y coordinates set to 0. */ Point2D(); /** * Create a new <code>Point2D</code> with the specified coordinates. * * @param[in] x the x coordinate of this <code>Point2D</code>. * * @param[in] y the y coordinate of this <code>Point2D</code>. */ Point2D(int x, int y); /** * Create a new <code>Point2D</code> by copying the coordinates from the * specified point. If the specified <code>Point2D</code> is * <code>nullptr</code> then this <code>Point2D</code> will have its x and y * coordinates set to 0. * * @param[in] p the <code>Point2D</code> that this <code>Point</code> will * copy from. */ Point2D(const Point2D * p); /** * Destructor */ ~Point2D(); /** * Returns the x coordinate of this <code>Point2D</code>. * * @return the x coordinate of this <code>Point2D</code>. */ int getX() const; /** * Returns the y coordinate of this <code>Point2D</code>. * * @return the y coordinate of this <code>Point2D</code>. */ int getY() const; /** * Changes the location of this <code>Point2D</code> to the specified * location. * * @param[in] x the new x coordinate of this <code>Point2D</code>. * * @param[in] y the new y coordinate of this <code>Point2D</code>. */ void setLocation(int x, int y); /** * Changes the location of this <code>Point2D</code> to the specified * location. If the specified <code>Point2D</code> is <code>nullptr</code> * then this <code>Point2D</code> will have its x and y coordinates set to * 0. * * @param[in] p the new location of this <code>Point2D</code>. */ void setLocation(const Point2D * p); private: int x; int y; }; #endif /* GRAPHICS_POINT_H_ */
true
c336f6367cddbdf473f2c0131923ce8a8cd14717
C++
xxxFilosoFxxx/TIMP
/task2_2/task2-2_main.cpp
UTF-8
2,045
2.640625
3
[]
no_license
#include <iostream> #include <time.h> #include "vector" #include <algorithm> #include "sstream" #include "../DDZ/OstTree.h" using namespace std; int main() { /* int **mas = new int*[20]; for(int i = 0; i < 20; i++) { mas[i] = new int(i); cout << mas[i] << ' '; } for (int i = 0; i < 20; i++) { delete mas[i]; } delete [] mas; */ //TODO переделка для неор графа std::string str = "a,b,c,d,e,f,g,h,ab10,ff20,dl30,qm40"; std::string str1 = str; std::vector<int> vect_versh; std::vector<int> vect_edge; vector<int> vect_diiich; int mas[26]; for (int i = 0; i < 26; i++) { mas[i] = i; } std::stringstream ss(str); char i; int r; int count = 0, k = 0; while (ss >> i) { if (ss.peek() == ',') { k++; ss.ignore(); } if (count > k - 1) break; count++; for (int j = 0; j < 26; j++) { if (mas[j] == ((int)i - 97)) vect_versh.push_back(j); } } str1.erase(str1.begin(), str1.end() - (str1.size() - 2*count)); std::stringstream ss1(str1); while (ss1 >> i) { if (ss1.peek() == ',') { ss1.ignore(); } for (int j = 0; j < 26; j++) { if (mas[j] == ((int)i - 97)) { vect_edge.push_back(j); str1.erase(str1.find(i), 1); } } } std::stringstream ss2(str1); while (ss2 >> r) { if (ss2.peek() == ',') { ss2.ignore(); } vect_diiich.push_back(r); } for (i=0; i< vect_versh.size(); i++) std::cout << vect_versh.at(i)<<" "; cout<<endl; for (i=0; i< vect_edge.size(); i++) std::cout << vect_edge.at(i)<< " "; cout << endl; for (i=0; i< vect_diiich.size(); i++) std::cout << vect_diiich.at(i)<< " "; cout<<endl; return 0; }
true
197517934a59f055e68eec1df0256d1ab4fc00a9
C++
PersonalPete/MicroscopeController
/AutoFocus/afCentroidImages.cpp
UTF-8
4,457
2.546875
3
[]
no_license
/* afCentroidImages.cpp * * RETURNS double imageCentroid * * ARGS INT hCam, INT mPtr, * INT roiHMin, INT roiHMax, * INT roiVMin, INT roiVMax, * INT nFrames < 1000 * * Computes the centroid within the ROI of the last nFrames images acquired */ #include "mex.h" #include <iostream> #include "uc480.h" #include "afconstants.h" bool isScalarArray(const mxArray* pArg) { return (mxIsNumeric(pArg) && mxGetN(pArg) == 1 && mxGetM(pArg) == 1); } bool isFramesArray(const mxArray* pArg) { return (mxIsNumeric(pArg) && mxGetN(pArg) == 1 && mxGetM(pArg) == N_FRAMES); } void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[]) { // CHECK ARGS if (nrhs != 7) { mexErrMsgIdAndTxt( "Mscope:afGetLastImage:invalidNumInputs", "Seven or eight input arguments required (camH, mId, mPtr)."); } if (nlhs > 1) { mexErrMsgIdAndTxt( "Mscope:afGetLastImage:maxlhs", "Too many output arguments."); } if (!isScalarArray(prhs[0])) { mexErrMsgIdAndTxt( "Mscope:afGetLastImage:invalidArg", "Camera handle is an integer"); } if (!isFramesArray(prhs[1])) { mexErrMsgIdAndTxt( "Mscope:afGetLastImage:invalidArg", "Memory Ptr is an array of length equal to the number of frames"); } if ((!isScalarArray(prhs[2])) | (!isScalarArray(prhs[3])) | (!isScalarArray(prhs[4])) | (!isScalarArray(prhs[5]))){ mexErrMsgIdAndTxt( "Mscope:afGetLastImage:invalidArg", "Roi defined by 4 scalars"); } if (!isScalarArray(prhs[6])) { mexErrMsgIdAndTxt( "Mscope:afGetLastImage:invalidArg", "NFrames is an integer"); } // EXTRACT PARAMETERS int hCam = (int) mxGetScalar(prhs[0]); // Pointer to the pointers to the 8-bit camera data UINT8_T** mPtrsPtr = (UINT8_T**) mxGetData(prhs[1]); // ROI to centroid within int hRoiMin = (int) mxGetScalar(prhs[2]); int hRoiMax = (int) mxGetScalar(prhs[3]); int vRoiMin = (int) mxGetScalar(prhs[4]); int vRoiMax = (int) mxGetScalar(prhs[5]); // Number of recent frames to consider int nFrames = (int) mxGetScalar(prhs[6]); //std::printf("\nInput Parameters: ROI %i %i %i %i; Frames %i\n",hRoiMin, hRoiMax, vRoiMin, vRoiMax, nFrames); // WORK OUT WHICH MEMORY IN SEQUENCE IS MOST RECENT int mostRecentBuffer; VOID *pcImgMem; is_GetImageMem(hCam, &pcImgMem); UINT8_T* pcImgMemInt = (UINT8_T*) pcImgMem; for (int ii = 0; ii < N_FRAMES; ii++) { // loop over allocated frame pointers, if it matches then use the corresponding ID if (mPtrsPtr[ii] == pcImgMemInt) { mostRecentBuffer = ii; break; } } //std::printf("\nMost Recent Buffer: %i\n",mostRecentBuffer); // LOOP OVER FRAMES int actualFrame; double weightedMeanPosSum = 0; double normalisationSum = 0; for (int frame = mostRecentBuffer - nFrames; frame < mostRecentBuffer; frame++) { // Calculate which frame buffer to use, putting negatives in range // cyclically if (frame < 0) { actualFrame = frame + N_FRAMES; } else { actualFrame = frame; } //std::printf("\nLooking at buffer %i\n",actualFrame); // LOOP OVER ROWS for (int row = vRoiMin; row < vRoiMax; row++) { //std::printf("\nLooping over vertical row %i\n",row); // LOOP OVER COLUMNS for (int column = hRoiMin; column < hRoiMax; column++) { //std::printf("\nColumn %i; Value %u\n",column,mPtrsPtr[actualFrame][column + row*H_PIX]); weightedMeanPosSum += (double) column * (double) mPtrsPtr[actualFrame][column + row*H_PIX]; normalisationSum += (double) mPtrsPtr[actualFrame][column + row*H_PIX]; } } } // COMPUTE THE CENTROID double centroidPos = weightedMeanPosSum/normalisationSum; //std::printf("\nCentroid: %.2f\n",centroidPos); // RETURN THE ANSWER TO MATLAB mwSignedIndex scalarDims[2] = {1,1}; // elements in image plhs[0] = mxCreateNumericArray(2, scalarDims, mxDOUBLE_CLASS, mxREAL); double * centroidPtr = mxGetPr(plhs[0]); memcpy(centroidPtr, &centroidPos, sizeof(centroidPos)); return; }
true
160da17d1b061ee964c0689d4a14a83267bb251c
C++
takikhasan/codebase
/Number Theory/nCr without mod (n is fixed).cpp
UTF-8
711
2.8125
3
[]
no_license
///*... nCr without mod ...*/ class nCrCalc { /// Time & space complexity: O(k), where k is /// the maximum value of r in all nCr queries private: ULL n; ULL* C; int last; gen(int st, int en) { for (int i = st; i <= en; i++) { C[i] = C[i-1] * (n - i + 1); C[i] /= i; } last = en; } public: nCrCalc(ULL n, int MAX_K = -1) { this->n = n; if (MAX_K == -1) MAX_K = n; C = new ULL[MAX_K+1]; C[0] = 1; last = 0; } ULL nCr(int k) { if (k > n - k) k = n - k; if (k > last) gen(last + 1, k); return C[k]; } }; ///*... nCr without mod ...*/
true
ea335d39998f90cf5a6006cd548583f8628ac7ed
C++
tanvieer/ProblemSolving
/URI PROBS/1174.cpp
UTF-8
242
2.53125
3
[]
no_license
#include<iostream> using namespace std; int main(){ int n = -1; float i; while (1){ n++; if(n>99) break; cin>>i; if(i<=10){ cout<<"A["<<n<<"] = " <<i<<endl; } } }
true
ec4c998dfab513cca8af67059392ede65e53b16b
C++
BipinKalra/CPP_Basics_2
/textfiles/all codes.cpp
UTF-8
4,513
3.1875
3
[]
no_license
#include<iostream> #include<conio.h> #include<fstream> #include<ctype.h> #include<string.h> using namespace std; void para() { ofstream fout; fout.open("writing.txt",ios::app); char para[100]; cout<<"ENTER CONTENT:"; cin.getline(para,100,'$'); fout<<para; fout.close(); } void line() { ofstream fout; fout.open("writing.txt",ios::app); char line[50],ans; do { cout<<"ENTER LINE CONTENT:"; cin.ignore(); cin.getline(line,100); fout<<line<<endl; cout<<"DO YOU WANT TO ADD MORE:"; cin>>ans; }while((ans=='y')||(ans=='Y')); fout.close(); } void character() { ofstream fout; fout.open("writing.txt",ios::app); char ch,ans; do { cout<<"ENTER CONTENT:"; cin.ignore(); cin.get(ch); fout<<ch<<" "; cout<<"DO YOU WANT TO ADD MORE:"; cin>>ans; }while((ans=='y')||(ans=='Y')); fout.close(); } void writingmenu() { char ans; int ch; do { system("cls"); cout<<"SUB MENU:"; cout<<"\n1.PARA WISE."; cout<<"\n2.LINE BY LINE."; cout<<"\n3.CHARCTER BY CHARACTER."; cout<<"\nENTER YOUR CHOICE:"; cin>>ch; switch(ch) { case 1:para(); break; case 2:line(); break; case 3:character(); break; default:cout<<"WRONG CHOICE.."; } cout<<"DO YOU WANT TO REVISIT WRITING MENU.."; cin>>ans; }while(ans=='y'); } /*********************************************/ void read() { ifstream fin("writing.txt"); char c; while(fin.get(c)) cout<<c; fin.close(); } void count() { ifstream fin("writing.txt"); char ch; int a=0,l=0,s=0,t=0,v=0,c=0; while(fin.get(ch)) { if(isalpha(ch)) { a++; switch(ch) { case 'a': case 'A': case 'e': case 'E': case 'i': case 'I': case 'o': case 'O': case 'u': case 'U':v++; break; default:c++; } } else if(ch==' ') s++; else if(ch=='\t') t++; else if(ch=='\n') l++; } cout<<"\nNO OF ALPHABETS:"<<a; cout<<"\nNO OF VOWELS:"<<v; cout<<"\nNO OF CONSONANTS:"<<c; cout<<"\nNO OF SPACES:"<<s; cout<<"\nNO OF TABS:"<<t; cout<<"\nNO OF LINES:"<<l; fin.close(); } void toggle() { ifstream fin("writing.txt"); char c; while(fin.get(c)) { if(islower(c)) c=toupper(c); else if(isupper(c)) c=tolower(c); cout<<c; } fin.close(); } void searchword(char word[]) { ifstream fin("writing.txt"); char w[20]; int cnt=0; while(fin>>w) { if(strcmpi(w,word)==0) cnt++; } cout<<"NO OF OCCURENCE OF THE WORD "<<word<<"is/are "<<cnt<<" times."; fin.close(); } void searchletter(char l) { ifstream fin("writing.txt"); char w[20]; int cnt=0; while(fin>>w) { if(w[0]==l) cnt++; } cout<<"NO OF WORDs STARTING WITH "<<l<<" are "<<cnt; fin.close(); } void countword(int len) { ifstream fin("writing.txt"); char w[20]; int cnt=0; while(fin>>w) { if(strlen(w)==len) cnt++; } cout<<"NO OF "<<len<<" LETTER WORDS"<<" are "<<cnt; fin.close(); } void readingmenu() { char ans; int ch; do { system("cls"); cout<<"SUB MENU:"; cout<<"\n1.READ."; cout<<"\n2.FILE STATISTICS."; cout<<"\n3.TOGGLE CASE."; cout<<"\n4.OCCURENCE OF A WORD."; cout<<"\n5.WORDS STARTING FROM A LETTER."; cout<<"\n6.NO OF WORDS."; cout<<"\nENTER YOUR CHOICE:"; cin>>ch; switch(ch) { case 1:read(); break; case 2:count(); break; case 3:toggle(); break; case 4: char word[15]; cout<<"\nENTER WORD TO FIND:"; cin>>word; searchword(word); break; case 5:char l; cout<<"ENTER STARTING LETTER:"; cin>>l; searchletter(l) ; break; case 6:int len; cout<<"ENTER LENGTH OF WORD:"; cin>>len; countword(len); break; default:cout<<"WRONG CHOICE.."; } cout<<"\nDO YOU WANT TO REVISIT READING MENU.."; cin>>ans; }while(ans=='y'); } /*********************************************/ void mainmenu() { int choice; char ans; do { system("cls"); cout<<"MAIN MENU:"; cout<<"\n1.WRITING."; cout<<"\n2.READING."; cout<<"\nENTER YOUR CHOICE:"; cin>>choice; switch(choice) { case 1:writingmenu(); break; case 2: readingmenu(); break; default:cout<<"INVALID CHOICE.."; } cout<<"\nDO YOU WANT TO REVISIT MAIN MENU:"; cin>>ans; }while(ans=='y'); } int main() { mainmenu(); getch(); return 0; }
true
dcad07d13d02581bcb487af1d53f30d5dfba7dbb
C++
plaice/Williams
/07/lf_stack.h
UTF-8
2,188
3.46875
3
[ "BSL-1.0" ]
permissive
// Listings 7.3-5, pp.187-190, Williams. // Lock-free stack. #include <atomic> #include <memory> template<typename T> class lock_free_stack { private: struct node { std::shared_ptr<T> data; node* next; node(T const& data_): data(std::make_shared<T>(data_)) {} }; std::atomic<node*> head; std::atomic<unsigned> threads_in_pop; std::atomic<node*> to_be_deleted; static void delete_nodes(node* nodes) { while(nodes) { node* next=nodes->next; delete nodes; nodes=next; } } void try_reclaim(node* old_head) { if(threads_in_pop==1) { node* nodes_to_delete=to_be_deleted.exchange(nullptr); if(!--threads_in_pop) { delete_nodes(nodes_to_delete); } else if(nodes_to_delete) { chain_pending_nodes(nodes_to_delete); } delete old_head; } else { chain_pending_node(old_head); --threads_in_pop; } } void chain_pending_nodes(node* nodes) { node* last=nodes; while(node* const next=last->next) { last=next; } chain_pending_nodes(nodes,last); } void chain_pending_nodes(node* first,node* last) { last->next=to_be_deleted; while(!to_be_deleted.compare_exchange_weak( last->next,first)); } void chain_pending_node(node* n) { chain_pending_nodes(n,n); } public: void push(T const& data) { node* const new_node=new node(data); new_node->next=head.load(); while(!head.compare_exchange_weak(new_node->next,new_node)); } std::shared_ptr<T> pop() { ++threads_in_pop; node* old_head=head.load(); while(old_head && !head.compare_exchange_weak(old_head,old_head->next)); std::shared_ptr<T> res; if(old_head) { res.swap(old_head->data); } try_reclaim(old_head); return res; } };
true
51de31a9918d9348b769d3ed7fdd9932dfaa352a
C++
raviswan/Elixir
/MiscProjects/Blackjack/dealer.h
UTF-8
1,083
2.796875
3
[]
no_license
#ifndef _DEALER_H_ #define _DEALER_H_ #include <iostream> #include <array> #include <vector> #include <map> #include "player.h" using namespace std; using uint = unsigned int; class Player; enum class PlayerAction: int{ No_op =0, Hit = 1, Stand }; class Dealer{ public: Dealer(); ~Dealer(); void initializePlayers(); uint drawCard(); void drawDealerHand(); const vector<uint>& showDealerHand(); void drawPlayerHands(); void setDealerBet(uint); uint getDealerBet() const; void setPlayerBets(uint); void createPlayingDeck(); void shuffleDeck(); void playGame(); void printDeck(); void printSortedDeck(); void putBackPlayedCards(); void actOnPlayerRequest(uint, PlayerAction); void dealerAction(uint); void cleanup(); void checkDealerSoftHand(uint, uint); private: vector<uint> mDealerHand; uint mDealerCard; uint mHandValue; //Player index will identify the player,and get access to their info map<uint,Player* > mPlayers; uint mDealerBet; vector<uint> mDeck; vector<uint> mDrawnCards; bool mSoftHand; static int randomSeed; }; #endif
true
4ec61301df4eb355c8cbb1c9c4beb30e13d8a99d
C++
gered/MonsterDefense
/src/framework/graphics/sprite3dshader.h
UTF-8
612
2.578125
3
[]
no_license
#ifndef __FRAMEWORK_GRAPHICS_SPRITE3DSHADER_H_INCLUDED__ #define __FRAMEWORK_GRAPHICS_SPRITE3DSHADER_H_INCLUDED__ #include "spriteshader.h" /** * Shader for rendering 3D billboard sprites with vertex color modulation. * Includes special support for color modulation using RGB, RGBA, and * alpha-only texture formats. Also performs alpha testing (fragments with * alpha == 0.0f are discarded). */ class Sprite3DShader : public SpriteShader { public: Sprite3DShader(); virtual ~Sprite3DShader(); private: static const char *m_vertexShaderSource; static const char *m_fragmentShaderSource; }; #endif
true
acf9c9e28838bcc1d92377539ad97d718fa663db
C++
ziegfeld/leetcode
/LinkedListCycle/LinkedListCycle.cpp
UTF-8
998
3.6875
4
[]
no_license
//============================================================================ // Linked List Cycle // Given a linked list, determine if it has a cycle in it. // // Follow up: // Can you solve it without using extra space? // // Complexity // O(n) //============================================================================ #include <iostream> using namespace std; /** * Definition for singly-linked list. */ struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: bool hasCycle(ListNode *head) { ListNode * runner1 = head; ListNode * runner2 = head; while (runner2 != NULL){ runner1 = runner1 -> next; runner2 = runner2 -> next; if (runner2 == NULL || (runner2 = runner2 -> next) == NULL) return false; else if (runner1 == runner2) return true; } return false; } }; int main() { return 0; }
true
2e130bd8f3c844472de716fcf6d5fdd584e1b189
C++
Pojemnik/game-of-life
/JJK/src/cell.cpp
UTF-8
1,450
3.0625
3
[]
no_license
#include "cell.h" const std::array<sf::Color, 12> Cell::colors = { sf::Color(255,0,0,255), sf::Color(255,128,0,255), sf::Color(255,255,0,255), sf::Color(128,255,0,255), sf::Color(0,255,0,255), sf::Color(0, 255, 128,255), sf::Color(0,255,255,255), sf::Color(0, 128, 255,255), sf::Color(0, 0, 255,255), sf::Color(128, 0, 255,255), sf::Color(255, 0, 255,255), sf::Color(255, 0, 128,255) }; Cell::Cell(sf::Vector2f pos) { rect.setPosition(pos); rect.setSize(sf::Vector2f(10, 10)); rect.setFillColor(sf::Color::White); rect.setOutlineThickness(-1); rect.setOutlineColor(sf::Color::Black); current_color = colors.begin(); } void Cell::change_state() { state = !state; if (state) { rect.setFillColor(sf::Color::Black); } else { rect.setFillColor(sf::Color::White); rect.setOutlineThickness(-1); rect.setOutlineColor(sf::Color::Black); } } void Cell::next_color() { if (++current_color == colors.end()) { current_color = colors.begin(); } rect.setFillColor(*current_color); } sf::FloatRect Cell::get_rect() const { return rect.getGlobalBounds(); } void Cell::reset_color() { current_color = colors.begin(); rect.setFillColor(sf::Color::Black); } bool Cell::get_state() const { return state; } void Cell::draw(sf::RenderTarget& target, sf::RenderStates states) const { target.draw(rect, states); } bool operator ==(const Cell& a, const Cell& b) { if (b.get_state() == a.get_state()) return true; return false; }
true
8e141b9ad049d3ac9ea00754d39e8bf4ba38359c
C++
FinancialEngineerLab/Financial_Computing-cpp
/cfl/Function.hpp
UTF-8
16,571
3.1875
3
[]
no_license
//Copyright (c) Dmitry Kramkov, 2000-2006. All rights reserved. #ifndef __cflFunction_hpp__ #define __cflFunction_hpp__ #include <functional> #include <limits> #include <memory> #include <valarray> #include "cfl/Macros.hpp" /** * \file Function.hpp * \author Dmitry Kramkov * \date 2000-2006 * * \brief One-dimensional function object in cfl library. * * This file contains classes and functions related to * one-dimensional function object. */ namespace cfl { /** * \defgroup cflFunctionObjects Function objects. * * This module contains implementations of one and multi dimensional * function objects. */ /** * \ingroup cflFunctionObjects * \defgroup cflFunction One-dimensional function object. * * This module deals with a one-dimensional function object. */ //@{ //! Interface for a one-dimensional function. /** * The abstract class for a one-dimensional function. Its * implementation on a free store is used to construct the concrete * class Function. \see Function, MultiFunction, IMultiFunction */ class IFunction { public: /** * Virtual destructor. */ virtual ~IFunction(){} /** * Standard functional operator. * \param dX The argument. * \return The value of the function at \a dX. */ virtual double operator()(double dX) const = 0; /** * Tests whether an argument belongs to the domain of the function. * \param dX The argument. * \return The function returns \p true if the argument \a dX belongs to the domain * of the function. Returns \p false otherwise. */ virtual bool belongs(double dX) const = 0; }; //! Concrete class for a one-dimensional function. /** * The standard class for a one-dimensional function. * It is implemented by a dynamically allocated object derived * from the interface class IFunction. * \see IFunction, MultiFunction, IMultiFunction */ class Function: public std::function<double(double)> { public: /** * Constructs constant function with the value * \a dV on the interval [\a dLeft, \a dRight]. * * \param dV The value of the function. * \param dLeft The left point of the domain. * \param dRight The right point of the domain. */ explicit Function(double dV=0., double dLeft=-std::numeric_limits<double>::max(), double dRight=std::numeric_limits<double>::max()); /** * Constructs \p *this from a dynamically allocated implementation * of IFunction. * * \param pNewP The pointer to a dynamically allocated * implementation of IFunction. */ explicit Function(IFunction * pNewP); /** * Assigns to \p *this the constant function with the value \a dV. * The domain becomes equal the real line. * * \param dV The value of the function. * \return Reference to \p *this. */ Function & operator=(double dV); /** * Standard functional operator. * * \param dX The argument. * \return The value of the function at \a dX. */ double operator()(double dX) const; /** * \copydoc IFunction::belongs */ bool belongs(double dX) const; /** * Replaces \p *this with the sum of \p *this and \a rF. The new * domain of \p *this equals the intersection of its old domain * with the domain of \a rF. A deep copy of \a rF is created * inside of \p *this. * * \param rF Constant reference to the function that will be added. * \return Reference to \p *this. */ Function & operator+=(const Function & rF); /** * Replaces \p *this with the product of \p *this and \a rF. The * new domain of \p *this equals the intersection of its old * domain with the domain of \a rF. A deep copy of \a rF is * created inside of \p *this. * * \param rF Constant reference to the multiplier. * \return Reference to \p *this. */ Function & operator*=(const Function & rF); /** * Replaces \p *this with the difference between \p *this and \a * rF. The new domain of \p *this equals the intersection of its * old domain with the domain of \a rF. A deep copy of \a rF is * created inside of \p *this. * * \param rF Constant reference to the function that will be subtracted. * \return Reference to \p *this. */ Function & operator-=(const Function & rF); /** * Replaces \p *this with the ratio between \p *this and \a rF. * The new domain of \p *this equals the intersection of its old * domain with the domain of \a rF. A deep copy of \a rF is * created inside of \p *this. * * \param rF The divisor function. * * \return Reference to \p *this. */ Function & operator/=(const Function & rF); /** * Replaces \p *this with the sum of \p *this and \a dV. * * \param dV The number to be added to the function. * * \return Reference to \p *this. */ Function & operator+=(double dV); /** * Replaces \p *this with the difference between \p *this and \a * dV. * * \param dV The number to be subtracted from the function. * * \return Reference to \p *this. */ Function & operator-=(double dV); /** * Replaces \p *this with the product of \p *this and \a dV. * * \param dV The number to be multiplied by the function. * * \return Reference to \p *this. */ Function & operator*=(double dV); /** * Replaces \p *this with the ratio of \p *this and \a dV. * * \param dV The divisor number. * * \return Reference to \p *this. */ Function & operator/=(double dV); private: /** * The \p shared_ptr to an implementation of IFunction */ std::shared_ptr<IFunction> m_pF; }; /** * Returns minus \a rF. The result contains a deep copy of \a rF. * The domain of the result equals the domain of \a rF. * * \param rF A function object which minus is computed. * * \return The function given by <code>-rF</code> */ Function operator-(const Function & rF); /** * Returns the product of \a rF and \a rG. The result contains * deep copies of \a rF and \a rG. The domain of the result equals * the intersection of the domains of \a rF and \a rG. * * \param rF First function multiplier. * \param rG Second function multiplier. * * \return The function given by <code>rF*rG</code> */ Function operator*(const Function & rF, const Function & rG); /** * Returns the sum of \a rF and \a rG. The result contains * deep copies of \a rF and \a rG. The domain of the result equals * the intersection of the domains of \a rF and \a rG. * * \param rF First element of the sum. * \param rG Second element of the sum. * * \return The function given by <code>rF+rG</code> */ Function operator+(const Function & rF, const Function & rG); /** * Returns the difference between \a rF and \a rG. The result * contains deep copies of \a rF and \a rG. The domain of the * result equals the intersection of the domains of \a rF and \a rG. * * \param rF The function from which we subtract. * \param rG The function which is subtracted. * * \return The function given by <code>rF-rG</code> */ Function operator-(const Function & rF, const Function & rG); /** * Returns the ratio of \a rF and \a rG. The result contains deep * copies of \a rF and \a rG. The domain of the result equals the * intersection of the domains of \a rF and \a rG. * * \param rF The function which is divided. * \param rG The divisor function. * * \return The function given by <code>rF/rG</code> */ Function operator/(const Function & rF, const Function & rG); /** * Returns the product of \a dV and \a rF. The result * contains a deep copy of \a rF. The domain of the * result equals that of \a rF. * * \param dV The multiplier number. * \param rF The multiplier function. * * \return The function given by <code>dV*rF</code> */ Function operator*(double dV, const Function & rF); /** * Returns the difference between \a dV and \a rF. The result * contains a deep copy of \a rF. The domain of the * result equals that of \a rF. * * \param dV The number from which we subtract. * \param rF The function which is subtracted. * * \return The function given by <code>dV-rF</code> */ Function operator-(double dV, const Function & rF); /** * Returns the ratio of \a dV and \a rF. The result * contains a deep copy of \a rF. The domain of the * result equals that of \a rF. * * \param dV The number which is divided. * \param rF The divisor function. * * \return The function given by <code>dV/rF</code> */ Function operator/(double dV, const Function & rF); /** * Returns the sum of \a dV and \a rF. The result * contains a deep copy of \a rF. The domain of the * result equals that of \a rF. * * \param dV The number-term of the sum. * \param rF The function-term of the sum. * * \return The function given by <code>dV+rF</code> */ Function operator+(double dV, const Function & rF); /** * Returns the ratio of \a rF and \a dV. The result * contains a deep copy of \a rF. The domain of the * result equals that of \a rF. * * \param rF The function which is divided. * \param dV The divisor number. * * \return The function given by <code>rF/dV</code> */ Function operator/(const Function & rF, double dV); /** * Returns the sum of \a rF and \a dV. The result * contains a deep copy of \a rF. The domain of the * result equals that of \a rF. * * \param rF The function-term of the sum. * \param dV The number-term of the sum. * * \return The function given by <code>rF+dV</code> */ Function operator+(const Function & rF,double dV); /** * Returns the product of \a rF and \a dV. The result * contains a deep copy of \a rF. The domain of the * result equals that of \a rF. * * \param rF The function multiplier. * \param dV The number multiplier. * * \return The function given by <code>rF*dV</code> */ Function operator*(const Function & rF, double dV); /** * Returns the difference between \a rF and \a dV. The result * contains a deep copy of \a rF. The domain of the result equals * that of \a rF. * * \param rF The function from which we subtract. * \param dV The number which is subtracted. * * \return The function given by <code>rF-dV</code> */ Function operator-(const Function & rF, double dV); /** * Returns the maximum \a rF and \a rG. The result contains deep * copies of \a rF and \a rG. The domain of the result equals the * intersection of the domains of \a rF and \a rG. * * \param rF First function in the maximum. * \param rG Second function in the maximum. * * \return The function given by <code>max(rF,rG)</code> */ Function max(const Function & rF, const Function & rG); /** * Returns the maximum of \a dV and \a rF. The result * contains a deep copy of \a rF. The domain of the result equals * that of \a rF. * * \param dV The number-term of the maximum. * \param rF The function-term of the maximum. * * \return The function given by <code>max(dV,rF)</code> */ Function max(double dV, const Function & rF); /** * Returns the maximum of \a rF and \a dV. The result * contains a deep copy of \a rF. The domain of the result equals * that of \a rF. * * \param rF The function-term of the maximum. * \param dV The number-term of the maximum. * * \return The function given by <code>max(rF,dV)</code> */ Function max(const Function & rF, double dV); /** * Returns the minimum of \a rF and \a rG. The result contains deep * copies of \a rF and \a rG. The domain of the result equals the * intersection of the domains of \a rF and \a rG. * * \param rF The first function in the minimum. * \param rG The second term in the minimum. * * \return The function given by <code>min(rF,rG)</code> */ Function min(const Function & rF, const Function & rG); /** * Returns the minimum of \a dV and \a rF. The result contains a * deep copy of \a rF. The domain of the result equals that of \a * rF. * * \param dV The number-term of the minimum. * \param rF The function-term of the minimum. * * \return The function given by <code>min(dV,rF)</code> */ Function min(double dV, const Function & rF); /** * Returns the minimum of \a rF and \a dV. The result contains a * deep copy of \a rF. The domain of the result equals that of \a * rF. * * \param rF The function-term of the maximum. * \param dV The number-term of the maximum. * * \return The function given by <code>min(rF,dV)</code> */ Function min(const Function & rF, double dV); /** * Returns \a rF in the power \a dV. The result contains a deep copy * of \a rF. The domain of the result equals that of \a rF. * * \param rF The function-base. * \param dV The number-exponent. * * \return The function \a rF in the power \a dV. */ Function pow(const Function & rF, double dV); /** * Returns the absolute value of \a rF. The result contains a deep * copy of \a rF. The domain of the result equals the domain of \a * rF. * * \param rF The function which absolute value is computed. * * \return The absolute value of \a rF. */ Function abs(const Function & rF); /** * Returns the exponent of \a rF. The result contains a deep * copy of \a rF. The domain of the result equals the domain of \a * rF. * * \param rF The function which exponent is computed. * * \return The exponent of \a rF. */ Function exp(const Function & rF); /** * Returns the logarithm of \a rF. * The result contains a deep copy of \a rF. * The domain of the result equals the domain of \a rF. * * \param rF The function which logarithm is computed. * * \return The logarithm of \a rF. */ Function log(const Function & rF); /** * Returns the squire root of \a rF. * The result contains the a deep copy of \a rF. * The domain of the result equals the domain of \a rF. * * \param rF The function which square root is computed. * * \return The square root of \a rF. */ Function sqrt(const Function & rF); /** * Constructs \p *this from a unary function object of STL * library. The types of argument and value of the unary function * should allow implicit conversion to \p double. A deep copy of \a * rF is created in the result. * * \param rF A unary function object from STL library. * \param dLeft The left point of the domain of the function. * \param dRight The right point of the domain of the function. * * \return A standard one-dimensional function object in the library * which represents the function \a rF. */ template <class F> Function toFunction(const F & rF, double dLeft=-std::numeric_limits<double>::infinity(), double dRight=std::numeric_limits<double>::infinity()); class MultiFunction; /** * Returns the restriction of the multi-dimensional function \a rF * to the one-dimensional region defined as the intersection of the * domain of \a rF with the line where the coordinate with index \a * iArg is flexible and all other coordinates equal \a rOtherArg . * * \param rF Constant reference to a multi-dimensional function object. * \param iArg The index of flexible coordinate. * \param rOtherArg The values of fixed coordinates. * * \return A standard one-dimensional function object in the library * which represents the restriction of the multi-dimensional * function \a rF to a one-dimensional domain. */ Function toFunction(const MultiFunction & rF, unsigned iArg=0, const std::valarray<double> & rOtherArg = std::valarray<double>()); //@} } #include "cfl/Inline/iFunction.hpp" #endif // of __cflFunction_hpp__
true
857ff9b04b9c008453f4eb7242e1a2cec9301186
C++
ricetuan/Tetrominos
/Classes/Tetromino.cpp
UTF-8
4,210
2.796875
3
[]
no_license
// // Tetromino.cpp // Tetrominos // // Created by Liang Fan on 7/2/15. // // #include "Tetromino.h" #include "JSONPacker.h" #include <unordered_set> using namespace cocos2d; Tetromino* Tetromino::createWithType(TetrominoType type) { Tetromino* tetromino = new (std::nothrow) Tetromino(); if (tetromino && tetromino->initWithType(type)) { tetromino->autorelease(); return tetromino; } else { CC_SAFE_DELETE(tetromino); return nullptr; } } bool Tetromino::initWithType(TetrominoType type) { if (! Node::init()) { return false; } this->type = type; rotations = std::vector<std::vector<Coordinate>>(); std::string jsonStr = FileUtils::getInstance()->getStringFromFile("tetrominos.json"); JSONPacker::TetrominoState tetrominoState = JSONPacker::unpackTetrominoJSON(jsonStr, type); this->color = tetrominoState.color; this->rotations = tetrominoState.rotations; this->blocks = std::vector<Sprite*>(); this->blocks.reserve(4); this->rotationIndex = 0; Sprite* dummyBlock = Sprite::create("block.png"); Size dummySize = dummyBlock->getContentSize(); float gridSizeF = float(GRID_SIZE); this->setContentSize(Size(dummySize.width * gridSizeF, dummySize.height * gridSizeF)); auto coordinates = this->getCurrentRotations(); for (Coordinate coordinate : coordinates) { Sprite* block = Sprite::create("block.png"); block->setColor(this->color); block->setAnchorPoint(Vec2(0.0f, 0.0f)); block->setPosition(Vec2(coordinate.x * dummySize.width, coordinate.y * dummySize.height)); this->addChild(block); this->blocks.push_back(block); } return true; } #pragma mark - #pragma mark Public Methods void Tetromino::rotate(bool right) { if (right) { rotationIndex++; } else { rotationIndex--; } if (rotationIndex >= (int) rotations.size()) { rotationIndex = 0; } else if (rotationIndex < 0) { rotationIndex = (int) rotations.size() - 1; } auto coordinates = this->getCurrentRotations(); for (int index =0;index < GRID_SIZE;++index) { Sprite* block = blocks[index]; Coordinate coordinate = coordinates[index]; Size blockSize = block->getContentSize(); block->setPosition(Vec2(coordinate.x * blockSize.width, coordinate.y * blockSize.height)); } } int Tetromino::getHighestYCoordinate() { auto coordinates = this->getCurrentRotations(); int highestYCoordinate = 0; for (Coordinate coordinate : coordinates) { highestYCoordinate = highestYCoordinate >= coordinate.y ? highestYCoordinate : coordinate.y; } return highestYCoordinate; } int Tetromino::getWidthInBlocks() { auto coordinates = this->getCurrentRotations(); std::unordered_set<int> widthPoint; for (Coordinate coordinate : coordinates) { widthPoint.insert(coordinate.x); } return widthPoint.size(); } int Tetromino::getMinimumXCoordinate() { auto coordinates = this->getCurrentRotations(); int mininumXCoordinate = GRID_SIZE; for (Coordinate coordinate : coordinates) { mininumXCoordinate = coordinate.x < mininumXCoordinate ? coordinate.x : mininumXCoordinate; } return mininumXCoordinate; } std::vector<int> Tetromino::getSkirt() { int width = this->getWidthInBlocks(); int skirtStart = this->getMinimumXCoordinate(); std::vector<int> skirt = std::vector<int>(width,GRID_SIZE -1); auto coordinates = this->getCurrentRotations(); for (Coordinate coordinate : coordinates) { int x = coordinate.x - skirtStart; int skirtY = skirt[x]; if (coordinate.y < skirtY) { skirt[x] = coordinate.y; } } return skirt; } std::vector<Sprite*> Tetromino::getBlocks() { return blocks; } std::vector<Coordinate> Tetromino::getCurrentRotations() { return rotations[rotationIndex]; } TetrominoType Tetromino::getTetrominoType() { return this->type; } Color3B Tetromino::getTetrominoColor() { return this->color; }
true
d43c99f28937d1b478fc9dd4244d9b004243a9d9
C++
respu/ice
/include/ice/error.h
UTF-8
2,271
3
3
[ "LicenseRef-scancode-gary-s-brown", "BSD-3-Clause", "MIT", "Zlib", "BSL-1.0", "BSD-2-Clause" ]
permissive
#pragma once #include <ice/exception.h> #include <ice/optional.h> #include <ostream> #include <sstream> #include <stdexcept> #include <string> #include <system_error> #include <utility> namespace ice { template <typename T> class error : public exception, public T { public: using manipulator = std::ostream& (*)(std::ostream&); template <typename... Args> explicit error(Args&&... args) : T(std::forward<Args>(args)...) {} error(error&& other) = default; error(const error& other) = default; error& operator=(error&& other) = default; error& operator=(const error& other) = default; template <typename V> error& operator<<(V&& v) { std::ostringstream oss; oss.flags(flags_); oss << std::forward<V>(v); flags_ = oss.flags(); if (info_) { info_->append(oss.str()); } else { info_.emplace(oss.str()); } return *this; } error& operator<<(manipulator manipulator) { std::ostringstream oss; oss.flags(flags_); manipulator(oss); flags_ = oss.flags(); if (info_) { info_->append(oss.str()); } else { info_.emplace(oss.str()); } return *this; } const char* what() const noexcept override { return T::what(); } const char* info() const noexcept override { if (!info_) { return nullptr; } return info_->c_str(); } private: static std::ios_base::fmtflags default_flags() { static const std::ios_base::fmtflags flags = std::ostringstream().flags(); return flags; } ice::optional<std::string> info_; std::ios_base::fmtflags flags_ = default_flags(); }; using logic_error = ice::error<std::logic_error>; using invalid_argument = ice::error<std::invalid_argument>; using domain_error = ice::error<std::domain_error>; using length_error = ice::error<std::length_error>; using out_of_range = ice::error<std::out_of_range>; using runtime_error = ice::error<std::runtime_error>; using range_error = ice::error<std::range_error>; using overflow_error = ice::error<std::overflow_error>; using underflow_error = ice::error<std::underflow_error>; using system_error = ice::error<std::system_error>; } // namespace ice
true
46df2d81ad3746c8ceb752ac40f986b3542831fd
C++
sidorovis/cpp_craft_1013
/solutions/ivan_sidarau/trade_processor_project/sources/market_data_receiver/main.cpp
UTF-8
642
2.640625
3
[]
no_license
#include <config_reader.h> #include <mediator.h> boost::mutex wait_ctrl_c_protector; boost::condition_variable pressed; void ctrl_c_handler( int ) { boost::mutex::scoped_lock lock( wait_ctrl_c_protector ); pressed.notify_one(); } int main() { try { multicast_communication::mediator m( "." ); boost::mutex::scoped_lock lock( wait_ctrl_c_protector ); signal(SIGINT, ctrl_c_handler); pressed.wait( lock ); } catch( const std::exception& ex ) { std::cerr << "Exception: " << ex.what() << std::endl; } catch( ... ) { std::cerr << "Unknown exception throwed" << std::endl; } std::cout << "Finished" << std::endl; }
true
9f749548deef9d14f486a41058c01d43caa9413d
C++
rjzupkoii/PSU-CIDD-Malaria-Simulation
/src/Reporters/Specialist/MovementReporter.cpp
UTF-8
5,225
2.8125
3
[]
no_license
/* * MovementReporter.cpp * * Implementation of the MovementReporter class. * * NOTE Since we assume this class will mostly be used for testing purposes, there * is an assumed dependency on DbReporter having already initialized the database. * * NOTE This code could be significantly optimized; however, since it is only used * for the initial model validation it hasn't been tuned that much. */ #include "MovementReporter.h" #include "Core/Config/Config.h" #include "Core/Random.h" #include "easylogging++.h" #include "Model.h" #define COUNT_LIMIT 100 // Add a reported move to the update void MovementReporter::add_fine_move(int individual, int source, int destination) { // Append the move fine_update_query.append(fmt::format(INSERT_FINE_MOVE, replicate, Model::SCHEDULER->current_time(), individual, source, destination)); // Check to see if we should report count++; if (count >= COUNT_LIMIT) { fine_report(); } } // Add a move between districts void MovementReporter::add_coarse_move(int individual, int source, int destination) { movement_counts[source][destination]++; } // Prepare and perform a bulk insert of the aggregated movements (can be cell-to-cell or district-to-district) // // NOTE This is slowed down a lot by sending the query to the DB for each source-destination. For district movements // this isn't too bad, but for cellular it can be painfully slow. void MovementReporter::coarse_report() { // If we are at the zero time point, just return since we don't anticipate anything to do auto timestep = Model::SCHEDULER->current_time(); if (timestep == 0) { return; } // Open the transaction pqxx::work db(*conn); // Send the inserts as we read the table, note that we assume that the division count is correct prepared // with padding as needed if it is coming from one-index ArcGIS std::string query; for (auto source = 0; source < division_count; source++) { for (auto destination = 0; destination < division_count; destination++) { if (movement_counts[source][destination] == 0) { continue; } query = fmt::format(INSERT_COARSE_MOVE, replicate, timestep, movement_counts[source][destination], source, destination); movement_counts[source][destination] = 0; db.exec(query); } } if (query.empty()) { // Issue a warning if there were no movements since zeroed data is not recorded LOG(WARNING) << "No movement between districts recorded."; db.abort(); return; } // Commit the data db.commit(); } // Open a connection to the database void MovementReporter::initialize(int job_number, std::string path) { // Connect to the database conn = new pqxx::connection(Model::CONFIG->connection_string()); // Since we are dependent upon DbReporter, the replicate should already be set replicate = Model::MODEL->replicate(); if (replicate == 0) { LOG(ERROR) << "Replicate value of zero, expected one or higher. Was DbReporter loaded?"; throw std::runtime_error("Invalid replicate value"); } if (Model::MODEL->district_movement()) { // Get the district count, prepare the memory. Note that we are assuming that the count // is coming from ArcGis which will use one-based indexing. Therefore, we need some extra // padding on the area to prevent errors. Since we are only inserting actual movement // (i.e., district A to district B) cells with zero are not as big of a concern (baring // any memory considerations). division_count = SpatialData::get_instance().get_district_count(); if (division_count == -1) { VLOG(1) << "District not loaded"; return; } // Pad the count division_count++; VLOG(1) << "Real District Count: " << division_count - 1; VLOG(1) << "Adjusted District Count: " << division_count; } else { // Assume we are tracking cells division_count = static_cast<int>(Model::CONFIG->number_of_locations()); VLOG(1) << "Cell count: " << division_count; } // Prepare the memory, assume that padding is in place movement_counts = new int*[division_count]; for (auto ndx = 0; ndx < division_count; ndx++) { movement_counts[ndx] = new int[division_count]; for (auto ndy = 0; ndy < division_count; ndy++) { movement_counts[ndx][ndy] = 0; } } // Inform the user that we are running LOG(INFO) << fmt::format("MovementReporter loaded, using replicate {}", replicate); } // Call the relevant sub reports void MovementReporter::monthly_report() { if (movement_counts != nullptr) { coarse_report(); } if (count > 0) { fine_report(); } } // Insert the buffered moves into the database void MovementReporter::fine_report() { // Insert the fine movement data pqxx::work db(*conn); db.exec(fine_update_query); db.commit(); // Reset the query and counter fine_update_query = ""; count = 0; } // Close the connection void MovementReporter::after_run() { conn->close(); }
true
af602b307c25624284304c21dfb4cdcb471bebaa
C++
Songsonge/First
/10.쿠키_작년문제비슷_더어려움.cpp
UHC
3,843
3.171875
3
[]
no_license
#include <iostream> #include <iomanip> #include <random> #include <string> #include <fstream> #include <algorithm> using namespace std; enum Tier { common, rare, epic, legend }; string NameofTier[4]{ "Ŀ", "", "","" }; //3. ߰ uniform_int_distribution<> nameuid(30, 80); uniform_int_distribution<> hpuid(-50, 200); uniform_int_distribution<> tieruid(common, epic); uniform_int_distribution<> charuid('a', 'z'); default_random_engine dre; class Cookie { string name; int hp; bool isdie = false; Tier tier; public: Cookie() { for (int i = 0; i < nameuid(dre); ++i) { name += charuid(dre); } hp = hpuid(dre); tier = Tier(tieruid(dre)); // ʷϻ Ÿ ϰ . } void show() { if (!isdie) { cout<<left << setw(80) << name << " " << setw(4) << hp << " "; showtier(); return; } cout << " Ű ׾ϴ." << endl; } void showtier() { cout << NameofTier[tier] << endl; } void setTier(int n) { tier = Tier(n); } string getName() const { return name; } int getHp() const { return hp; } int getTier() const { return tier; } void setName(string s) { name = s; } void setHp(int n) { hp = n; } void setDie(bool b) { isdie = b; } }; int main() { Cookie* data = new Cookie[1'0000]; //Ű ofstream out("Ű 30000.data"); for (int i = 0; i < 10000; ++i) { out << data[i].getName() << " " << data[i].getHp() << " " << data[i].getTier() << endl; } Cookie *data2 = new Cookie[10000]; ifstream in("Ű 30000.data"); for (int i = 0; i < 10000; ++i) //3. ->ѱ { string s; int a; int b; in >> s; in >> a; in >> b; data2[i].setName(s); data2[i].setHp(a); data2[i].setTier(b); } sort(&data2[0], &data2[1'0000], [](Cookie a, Cookie b) { //4. return a.getHp() < b.getHp(); }); for (int i = 0; i < 10000; ++i) //5. Ű ̱ { if (data2[i].getHp() <= 0) { data2[i].setDie(true); } //data2[i].show(); } short arr[26] = {}; //6. Ծ //for (int i= 0; i < 10000; ++i) //{ // ++alpha[data2[i].getName()[0]-'a']; //} //for (int i = 0; i < 26; ++i) //{ // cout<<(char)(i+'a')<<" " << alpha[i] << endl; //} for (int i = 0; i < 10000; ++i) { string s = data2[i].getName(); auto p = s.begin(); int q = *p - 'a'; ++arr[q]; } for (int i = 0; i < 10000; ++i) { string s = data2[i].getName(); auto p = s.rbegin(); if (*p == 'z') { data2[i].setTier(3); } data2[i].show(); } // ذϴµ ʿ ڵ带 ߰ؾѴٸ ߰ѵ ּ ߰ ڵ忡 ٿ Ѵ. // 1. Ű  Cookie.data Ͽ ϶ // 2. Cookie.data о ڷᱸ ϶. // 3. showtier() ̿ؼ ߴ ʴ´. tier µȴ. tier ѱ۷ // common̸ Ŀ, rare , epic̸ , legend // ǹ ʴ´. // 4. qsort Լ ̿ ü ϶. // 5. ü 0 Ű ׿. // 6. 迭 ̿Ͽ ̸ ܾ ϴ ̸ ϰ ϶. // a -  // b -  // ... // abcdef ̸̶ a ϹǷ a ϴ ̸ ϳ ߰ȴ. // 5 ذϴµ 60Ʈ ̻ ؼ ȵȴ. // 7. name ޱڰ Z Ű ٲ۴. }
true
ab74c1eda0d97463cd57b99daf29c81843f7e2d4
C++
goodgodgd/DesignPatternCpp
/강사/20160330/6_일반적프로그래밍.cpp
UHC
1,717
3.796875
4
[]
no_license
#include <iostream> using namespace std; // Ϲ α׷ // C++ ̺귯 ϱ ؼ Ϲȭ ؾ մϴ. // C++ - OOP + Ϲȭ(Generic) // C ڿ Լ char* xstrchr(char *s, char c) { while (*s != '\0' && *s != c) ++s; return *s == c ? s : NULL; } // 1. ˻ Ϲȭ : κ ڿ ˻ ϰ . // [first, last) - ݰ char* xstrchr(char* first, char* last, char value) { while (first != last && *first != value) ++first; return first; } // 2. ˻ Ÿ Ϲȭ - template // 1) // - Ÿ԰ ã Ÿ Ǿ ִ. // template <typename T> // T* xfind(T* first, T* last, T value) // 2) // - T* ϸ ¥ ͸ ִ. // Ʈ ͸ . template <typename T1, typename T2> T1 xfind(T1 first, T1 last, T2 value) { while (first != last && *first != value) ++first; return first; } #include <vector> #include <algorithm> // find int main() { int x[] = { 1, 2, 3 }; cout << *xfind(x, x + 3, 3) << endl; vector<int> v; v.push_back(10); v.push_back(20); v.push_back(30); cout << *xfind(v.begin(), v.end(), 30) << endl; } #if 0 int main() { int x[] = { 1, 2, 3, 4, 5 }; int* p = xfind(x, x + 5, 3.0); if (p != x + 5) cout << *p << endl; } #endif #if 0 int main() { char s[] = "abcdefg"; char* p = xfind(s + 3, s + 7, 'c'); if (p != s + 7) cout << *p << endl; } #endif #if 0 int main() { char s[] = "abcdefg"; char* p = xstrchr(s, 'c'); if (p != NULL) cout << *p << endl; } #endif
true
d8dd3a4c861ecef1b73e5a085078d0680a0b1d7f
C++
noahmasur/CPSC350_Assignment4
/Window.cpp
UTF-8
552
3.03125
3
[]
no_license
#include "Window.h" //default Window::Window(){ m_timeFree = 0; m_timeArrived = 0; } //destructor Window::~Window(){ } //function to get the free times of the window int Window::getTimeFree(){ return m_timeFree; } //set free time void Window::setTimeFree(int timeFree){ m_timeFree = timeFree; } //get the time that the student arrived to the window int Window::getTimeArrived(){ return m_timeArrived; } //set the arrived time so we can keep track of the metrics void Window::setTimeArrived(int timeArrived){ m_timeArrived = timeArrived; }
true
d1a6a411ed16e3905abb20a9e71ce80441326be3
C++
MarcoBetance0327/C_plus_plus
/2. Expresiones/Ejercicio3.cpp
UTF-8
424
3.296875
3
[]
no_license
#include <iostream> using namespace std; int main() { float a, b, c, d, resul; cout << "Ingrese el valor de a: "; cin >> a; cout << "Ingrese el valor de b: "; cin >> b; cout << "Ingrese el valor de c: "; cin >> c; cout << "Ingrese el valor de d: "; cin >> d; resul = a + (b / (c - d)); cout.precision(2); cout << "\nEl valor de la expresion es: " << resul << endl; }
true
3433bcf0ef037a59127eb2d7a3a44c84d279d4a4
C++
Manhisme09/OOP
/kethuab2.cpp
UTF-8
1,290
3.046875
3
[]
no_license
#include<iostream> #include<iomanip> using namespace std; class vehicle{ private: string nhanHieu; int namsx; string hang; public: void nhap(); void xuat(); }; class oto : public vehicle{ private: int soChoNgoi; double dungTich; public: void nhap(); void xuat(); void sua(); }; class moto : public vehicle{ private: int phanKhoi; public: void nhap(); void xuat(); }; void vehicle::nhap(){ cout<<"Nhap nhan hieu:"; fflush(stdin); getline(cin,this->nhanHieu); cout<<"Nhap nam sx:"; cin>>this->namsx; cout<<"Nhap hang:"; fflush(stdin); getline(cin,this->hang); } void vehicle::xuat(){ cout<<setw(10)<<this->nhanHieu<<setw(10)<<this->namsx<<setw(10)<<this->hang; } void oto::nhap(){ vehicle::nhap(); cout<<"Nhap so cho ngoi:"; cin>>this->soChoNgoi; cout<<"Nhap dung tich:"; cin>>this->dungTich; } void oto::xuat(){ vehicle::xuat(); cout<<setw(10)<<this->soChoNgoi<<setw(10)<<this->dungTich<<endl; } void moto::nhap(){ vehicle::nhap(); cout<<"Nhap phan khoi:"; cin>>this->phanKhoi; } void moto::xuat(){ vehicle::xuat(); cout<<setw(10)<<this->phanKhoi<<endl; } void oto::sua(){ this->dungTich=3.0; } int main(){ oto o1; moto m1; o1.nhap(); m1.nhap(); o1.xuat(); m1.xuat(); cout<<"sua:"; o1.sua(); o1.xuat(); return 0; }
true
a60e9c56401a0074feb0a2e788d412a0fa81b59c
C++
leonefrain86/AyEdeD
/src/Lección 1/Leccion 112/ejercicio_1128/ejercicio1128.cpp
UTF-8
1,757
3.15625
3
[]
no_license
#include <iostream> using namespace std; int main() { int d = 1, dMyr, p, contP = 0, contPersonas, contTP; double i, sumP = 0, sumTP = 0, sumPMyr = 0; char continuar; while(d != 0) { cout << "Ingrese DNI: "; cin >> d; if(d != 0) { continuar = 'S'; sumP = 0; contP = 0; while (continuar == 'S') { cout << "Ingrese la fecha de pago: "; cin >> p; cout << "Ingrese importe: $"; cin >> i; if (i > 0) { sumP+=i; contP++; contTP++; sumTP+=i; } else { cout << "ERROR, el pago no se realizo correctamente" << endl; } cout << "Desea continuar? Si es asi ingrese | S |: "; cin >> continuar; } if (sumP > 0) { contPersonas++; } if (sumP > sumPMyr) { sumPMyr = sumP; dMyr = d; } cout << "Cantidad de pagos efectuados: " << contP << endl; cout << "Importe promedio de los pagos: " << sumP / contP << endl; cout << "Cantidad total abonada: " << sumP << endl; } } cout << "Cuantas personas efectuaron al menos un pago: " << contPersonas << endl; cout << "Promedio de los importes pagados: " << sumTP / contTP << endl; cout << "DNI de la persona que, en total, abonó la mayor cantidad de dinero: " << dMyr << endl; return 0; }
true
3f063d238b53dfc849bdb8dac6248d97b9650049
C++
jasminedayinta/cplusplus2
/Assignment 3/a3p5/WindGauge.h
UTF-8
483
2.640625
3
[]
no_license
// // WindGauge.hpp // a3p5 // // Created by Jasmine Juwono on 08.04.18. // Copyright © 2018 Jasmine Juwono. All rights reserved. // /*CH08-320143 a3_p5.cpp Jasmine Dayinta j.dayinta@jacobs-university.de*/ #include <stdio.h> #include <deque> using namespace std; class WindGauge{ public: WindGauge(int period = 10); void currentWindSpeed(int speed); int highest() const; int lowest() const; int average() const; void print(); private: int speed; int period; deque<int> deq; };
true
e74a2edb22dc27cc0b9e80ddd294bb5ee0105b8a
C++
nathanaelFixx/Array-List-and-Sorting
/List and Sorting/arrayList.cpp
UTF-8
3,620
3.71875
4
[]
no_license
#include "arrayList.h" using namespace std; template <class TYPE> ArrayList<TYPE>::ArrayList(int initialSize) { maxLength = initialSize; currentLength = 0; items = new TYPE[initialSize]; originalLength = initialSize; } template<class TYPE> ArrayList<TYPE>::ArrayList(const ArrayList & rhs) { items = NULL; *this = rhs; } template<class TYPE> ArrayList<TYPE>& ArrayList<TYPE>::operator=(const ArrayList<TYPE>& rhs) { if (this != &rhs) { if (items != NULL){ delete[] items; } currentLength = rhs.currentLength; items = new TYPE[rhs.maxLength]; for (int i = 0; i < rhs.getSize(); i++) { items[i] = rhs.items[i]; } } maxLength = rhs.maxLength; return *this; } template<class TYPE> void ArrayList<TYPE>::growArray() { int newSize = maxLength * 2; TYPE * tempArray = new TYPE[newSize]; for (int i = 0; i < currentLength; i++) { tempArray[i] = items[i]; } maxLength = newSize; delete[] items; items = tempArray; } template<class TYPE> bool ArrayList<TYPE>::isEmpty() const { if (currentLength == 0) return true; else return false; } template<class TYPE> void ArrayList<TYPE>::append(const TYPE & app) { if (currentLength == maxLength - 1) { growArray(); } items[currentLength] = app; currentLength++; appendCount++; } template<class TYPE> TYPE & ArrayList<TYPE>::operator[](int index) throw (std::out_of_range) { if (index >= currentLength || index < 0) { throw std::out_of_range("Invalid index on operator []"); } accessCount++; return items[index]; } template<class TYPE> int ArrayList<TYPE>::getSize() const { return currentLength; } template<class TYPE> void ArrayList<TYPE>::insertAt(int index, const TYPE & newEntry) throw(std::out_of_range) { if (index > currentLength || index < 0) { throw std::out_of_range("Invalid Index"); } if (currentLength == maxLength) { growArray(); } for (int i = currentLength - 1; i >= index; i--) { items[i + 1] = items[i]; } items[index] = newEntry; currentLength++; insertCount++; } template<class TYPE> void ArrayList<TYPE>::removeAt(int index) throw(std::out_of_range) { if (index >= currentLength || index < 0) { throw std::out_of_range("Invalid index on remove"); } for (int i = index; i <= currentLength; i++) { items[i] = items[i + 1]; } currentLength--; removeCount++; } template<class TYPE> TYPE & ArrayList<TYPE>::getAt(int index) throw(std::out_of_range) { if (index >= currentLength || index < 0) { throw std::out_of_range("Invalid index on Get"); } accessCount++; return items[index]; } template<class TYPE> void ArrayList<TYPE>::swap(int from, int to) throw(std::out_of_range) { TYPE temp; if (from >= currentLength || from < 0 || to >= currentLength || to < 0) { throw std::out_of_range("Invalid index on Get"); } temp = items[to]; items[to] = items[from]; items[from] = temp; swapCount++; } template<class TYPE> void ArrayList<TYPE>::clearAll() { delete[] items; } template <class TYPE> ArrayList<TYPE>::~ArrayList() { delete[] items; } template<class TYPE> void ArrayList<TYPE>::clearStatistics() { accessCount = 0; swapCount = 0; removeCount = 0; insertCount = 0; appendCount = 0; } template<class TYPE> int ArrayList<TYPE>::getNumAccess() const { return accessCount; } template<class TYPE> int ArrayList<TYPE>::getNumSwap() const { return swapCount; } template<class TYPE> int ArrayList<TYPE>::getNumRemove() const { return removeCount; } template<class TYPE> int ArrayList<TYPE>::getNumInsertAt() const { return insertCount; } template<class TYPE> int ArrayList<TYPE>::getNumAppends() const { return appendCount; }
true
bd559f9ba3951ba710b5f1e53739fce5ab6d8e3f
C++
Sharayu1071/Daily-Coding-DS-ALGO-Practice
/Codeforces/C++/Q1_Lucky_sum_of_digits.cpp
UTF-8
1,563
3.71875
4
[ "MIT" ]
permissive
//------Lucky Sum of Digits Explanation------// // Problem link is: // https://codeforces.com/contest/110/problem/C /* Problem Statement: Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya wonders eagerly what minimum lucky number has the sum of digits equal to n. Help him cope with the task. */ /* Solution: In this problem you just need to find a number of lucky digits in n and output YES if it number is equal to 4 or 7, NO otherwise. Here in solution, we will first find the number of 4's that can come in lucky number such that remaining part of number can be filled by 7 and also sum of digits of number become equal to n. */ #include <iostream> using namespace std; int main(){ int n; cin>>n; //inputs the sum of digits n int i,flag=0; /* i represents the number of 4 to be added in required number flag checks whether such a lucky number exists for given n */ for( i=0;4*i<=n;i++) { int z=n-i*4; if(z%7==0){ flag=1;// flag=1 says that a lucky number exist for break ;// a given n and break the loop } } if(flag==0) // if no such number is there for given n cout<<-1<<"\n"; else { string s; //required number will be in string s for(int j=1;j<=i;j++) s+='4'; for(int j=1;j<=n-i*4;j+=7) s+='7'; cout<<s<<"\n"; } }
true
7060ed4fe8da135ed0f8ce7454e8d8c6895f45ed
C++
adiravishankara/arduino_tutorials
/Code/tutorial5/motor_drive_us/rc_control.ino
UTF-8
909
2.53125
3
[]
no_license
void remote_vals(decode_results *results){ if(results->value == 0xFF629D){ Serial.print("VOL + PRESSED, motor speed: "); motor_speed += 20; motor_speed = constrain(motor_speed,100,255); Serial.println(motor_speed); } else if (results->value == 0xFFA857){ Serial.print("VOL - PRESSED, motor speed: "); motor_speed -= 20; motor_speed = constrain(motor_speed,100,255); Serial.println(motor_speed); } else if (results->value == 0xFF906F){ Serial.print("Up Arrow Pressed, motor speed: "); Serial.println(motor_speed); direc = 0; Serial.println("Direction = Forward"); } else if (results->value == 0xFFE01F){ Serial.print("Down Arrow Pressed, motor speed: "); Serial.println(motor_speed); direc = 1; Serial.print("Direction = Reverse"); } else{ Serial.print("WRONG INPUT, motor speed: "); Serial.println(motor_speed); } }
true
3b0b8c0eeb114b02e7e55873de59c3e38123ad32
C++
abhisheksaxena1998/SortingAlgorithms.cpp
/insertion-sort.cpp
UTF-8
2,033
4.1875
4
[ "MIT" ]
permissive
# include "includeAll.h" using namespace std; // "Insertion Sort" Sorting Algorithm Time Complexity O(N^2). void sort (int *listOfElements, int size) { // This sorting method works by doing inplace comparison between it's // elements, basically the algorithm Assumes that from index 0 to the hole // all elements are sorted, after making this assumption the algorithm // compares all the elements from the unsorted subarray to all the elements // in the sorted subarray. If the element is found greater than the element // in sorted subarray. Insert this element in the sorted subarray and // shift all the elements accordingly int value = 0, hole = 0; for (int i = 1; i < size; ++i) { value = listOfElements[i]; hole = i; while (hole > 0 && listOfElements[hole-1] > value) { listOfElements[hole] = listOfElements[hole-1]; hole = hole - 1; } listOfElements[hole] = value; // Print the list with the state of each iteration to simulate the Insertion sort // for the user cout << "Iteration #" << i+1 << ":" ; for (int k = 0; k < size; ++k) cout << listOfElements[k]; cout << endl; } } int main () { // Read and declare size of desired list by user int sizeOfList, *listOfElements; cout << "Enter Size: " << endl; cin >> sizeOfList; // Declare vector to save list of elements listOfElements = (int *)malloc(sizeOfList * sizeof(int)); // Receive list elements from the user and save them in the vector cout << endl << "Enter elements: " << endl; for (int i = 0; i < sizeOfList; ++i) cin >> listOfElements[i]; // Print the list before sorting for the user cout << endl << "Array before sorting: " << endl; for (int i = 0; i < sizeOfList; ++i) cout << listOfElements[i]; cout << endl << endl; // Sort the elements in the list sort (listOfElements, sizeOfList); // Print the list after the list has been sorted cout << endl << "Array after sorting: " << endl; for (int i = 0; i < sizeOfList; ++i) cout << listOfElements[i]; return 0; }
true
d4d5b3b3c6bd25cbd6fa4d7a4e3d61d9bcbf53b1
C++
micro-pi/MaixduinoAutonomousDriveESP32
/src/modules/Module.cpp
UTF-8
358
2.578125
3
[]
no_license
#include "Module.h" Module::Module(const char *name) : moduleName(name) { this->errorCode = E_NOK; } ErrorCode Module::init(void) { this->errorCode = initModule(); return this->errorCode; } const char *Module::getName(void) { return this->moduleName; } ErrorCode Module::getErrorCode(void) { return this->errorCode; } Module::~Module(void) { }
true
f7e2b965a775b7ce355ccdc11602ad824f26a4f4
C++
Xzzzh/cpplearn
/20170413/src/String.cc
UTF-8
1,079
3.265625
3
[]
no_license
/// /// @file String.cc /// @author lemon(haohb13@gmail.com) /// @date 2017-04-13 09:44:53 /// #include <stdio.h> #include <string.h> #include <iostream> using std::cout; using std::endl; class String { public: String() : _pstr(new char[1]) { } String(const char* pstr) : _pstr(new char[strlen(pstr) + 1]) { cout << "String(const char *)" << endl; strcpy(_pstr, pstr); } String(const String& rhs) : _pstr(new char[strlen(rhs._pstr) + 1]) { cout << "String(const String &rhs)" << endl; strcpy(_pstr, rhs._pstr); } String & operator=(const String& rhs) { if(&rhs == this) return *this; delete [] _pstr; _pstr = new char[strlen(rhs._pstr) + 1]; strcpy(_pstr, rhs._pstr); return *this; } ~String() { cout << "~String()" << endl; delete [] _pstr; } void print(); private: char * _pstr; }; void String::print(){ if(_pstr) cout << _pstr << endl; } int main(void) { String str; str.print(); cout << "---" << endl; String str2("hello,world"); String str3 = "wangdao"; str2.print(); str3.print(); return 0; }
true
645ea65bfe56226a282d0f7dbfb4cf5c70090963
C++
lonteray/tetris
/gamefield.cpp
UTF-8
3,165
3.03125
3
[]
no_license
#include "gamefield.h" #include "tile.h" #include "drawingsystem.h" #include <iostream> GameField::GameField(int w, int h) : width(w), height(h) { field = new FieldCell*[height]; for (int row = 0; row < height; row++) field[row] = new FieldCell[width]; fieldBorder = sf::RectangleShape(sf::Vector2f(width * 18.f - BORDER_THICKNESS, height * 18.f)); fieldBorder.setOutlineThickness(BORDER_THICKNESS); fieldBorder.setOutlineColor(sf::Color::Black); fieldBorder.setFillColor(sf::Color(0, 0, 0, 0)); fieldBorder.move(BORDER_THICKNESS, 0); highestTileLevel = height - 1; } GameField::~GameField() { for (int row = 0; row < height; row++) delete field[row]; delete field; } bool GameField::isInField(const sf::Vector2f &pos) const { //std::cout << "Cell position(" << pos.x << ", " << pos.y << ")\n"; if ((pos.x >= 0) && (pos.y >= 0) && (pos.x < width) && (pos.y < height)) return true; return false; } bool GameField::isCellEmpty(const sf::Vector2f &coords) const { return field[static_cast<int>(coords.y)][static_cast<int>(coords.x)].sign == FieldSign::EMPTY; } void GameField::fillCell(sf::Vector2f coords, Tile &tile) { int row = static_cast<int>(coords.y); int clmn = static_cast<int>(coords.x); field[row][clmn].sign = FieldSign::BUSY; field[row][clmn].tilePtr = &tile; if (row < highestTileLevel) highestTileLevel = row; } int GameField::getHighestLevel() { return highestTileLevel; } void GameField::checkRowsFilling(DrawingSystem &ds) { std::cout << "Checking\n"; int sourceRow = height - 1; for (int row = height - 1; row > 0; row--) { int tilesCount = 0; for (int clmn = 0; clmn < width; clmn++) { if (field[row][clmn].sign == FieldSign::BUSY) tilesCount++; // tiles reassignement //std::cout << "Assignment\n"; if (sourceRow != row) { if (field[sourceRow][clmn].sign == FieldSign::BUSY) ds.delItemByRef(*field[sourceRow][clmn].tilePtr); field[sourceRow][clmn] = field[row][clmn]; if (field[sourceRow][clmn].sign == FieldSign::BUSY) { sf::Vector2f newTileCoords(clmn * Tile::TEXTURE_WIDTH, sourceRow * Tile::TEXTURE_HEIGHT); field[sourceRow][clmn].tilePtr->setPosition(newTileCoords); } } } if (tilesCount < width) sourceRow--; } } const sf::RectangleShape &GameField::getBorderShape() const { return fieldBorder; } GameField::FieldCell &GameField::FieldCell::operator=(GameField::FieldCell &other) { if (this == &other) return *this; if (this->tilePtr) { delete this->tilePtr; std::cout << "DELETED\n"; this->tilePtr = nullptr; } this->sign = other.sign; this->tilePtr = other.tilePtr; // clear other other.sign = FieldSign::EMPTY; other.tilePtr = nullptr; return *this; }
true
8435f923a2de1fb8064b66286b6a293de505050e
C++
dinesh5583/Data-Structure-and-Algorithm-using-c-
/Data Structure and algorithm/Queue/dynamic_queue_array.cpp
UTF-8
2,458
3.609375
4
[]
no_license
#include<iostream> #include<conio.h> #include<stdlib.h> using namespace std; class dyqueue { public: int capacity; int front,rear; int *array; }; class queue{ public: dyqueue *q=new dyqueue; queue() { q->front=q->rear=-1; q->capacity=1; q->array=new int[q->capacity]; } void enqueue(int x) { if(isfull(q)) { resizequeue(q); } q->rear=(q->rear+1)%q->capacity; q->array[q->rear]=x; cout<<"inserted"<<x; if(q->front==-1) { q->front=q->rear; } } void resizequeue(dyqueue *q) { int size=q->capacity; q->capacity=q->capacity*2; q->array=(int*) realloc(q->array,q->capacity * sizeof(int)); if(q->front>q->rear) { for(int i=0;i<q->front;i++) //when the size of array is full so we insert all the previos elemrnt from front to the new block after the rear { q->array[i+size]=q->array[i]; } q->rear=q->rear+size; } } void peek() { cout<<q->array[q->front]; } void capacity() { cout<<q->capacity; } void dequeue() { int x; if(isempty(q)) { cout<<"queue is empty"; } else if(q->rear==q->front) { q->front=q->rear=-1; } else { x=q->array[q->front]; q->front=(q->front+1)%q->capacity; } } int isfull(dyqueue *q) { return (q->rear+1)%q->capacity==q->front; } int isempty(dyqueue *q) { return q->front==-1; } void display() { if(isempty(q)) { cout<<"queue is empty"; return; } if(q->rear>=q->front) { for(int i=q->front;i<=q->rear;i++) { cout<<q->array[i]<<" "; } } else { int i; for(i=q->front;i<q->capacity;i++) { cout<<q->array[i]; } for(i=0;i<=q->rear;i++) { cout<<q->array[i]; } } } }; int main() { int ch; queue st; while(1) { cout <<"\n1.enqueue 2.dequeue 3.display 4.peek or top 5.exit 6.show capacity\nEnter ur choice"; cin >> ch; switch(ch) { case 1: cout <<"enter the element"; cin >> ch; st.enqueue(ch); break; case 2: st.dequeue(); break; case 3: st.display();break; case 4: st.peek(); break; case 5: exit(0); case 6: st.capacity(); break; } } }
true
8c14a8d4b49ccb7958e81de6dc48e708c702e8e7
C++
paksas/Tamy
/Code/Include/core/FilesystemSection.h
UTF-8
3,161
2.84375
3
[]
no_license
/// @file core/FilesystemSection.h /// @brief a section of the filesystem that filters out all directories except for the selected few #pragma once #include <vector> #include "core\Filesystem.h" #include "core\MemoryRouter.h" /////////////////////////////////////////////////////////////////////////////// class FilePath; /////////////////////////////////////////////////////////////////////////////// /** * A section of the filesystem that filters out all directories except for the selected few. */ class FilesystemSection : public FilesystemListener { DECLARE_ALLOCATOR( FilesystemSection, AM_DEFAULT ); private: Filesystem& m_filesystem; std::vector< FilePath > m_allowedDirs; std::vector< FilesystemListener* > m_listeners; public: /** * Constructor. * * @param filesystem host filesystem */ FilesystemSection( Filesystem& filesystem ); ~FilesystemSection(); /** * Tells whether the node at the specified path can be modified. */ bool isMember( const FilePath& path ) const; /** * Adds a new directory to the section filter. * * @param path */ void addDirectory( const FilePath& path ); /** * Removes a directory from the section filter. If it's a parent directory * to several defined section directories, it will cause all of them to be removed. * * @param path */ void removeDirectory( const FilePath& path ); /** * Returns a list of section directories. */ inline const std::vector< FilePath >& getSectionDirectories() const { return m_allowedDirs; } // ------------------------------------------------------------------------- // Listeners management // ------------------------------------------------------------------------- /** * Attaches a filesystem listener to the section. * * @param listener */ void attach( FilesystemListener& listener ); /** * Detaches a filesystem listener from the section. * * @param listener */ void detach( FilesystemListener& listener ); /** * Pulls the current structure of the filesystem. * * @param listener * @param root the root directory the structure of which we want pulled */ void pullStructure( FilesystemListener& listener, FilePath& root ) const; // ------------------------------------------------------------------------- // FilesystemListener implementation // ------------------------------------------------------------------------- void onFileAdded( const FilePath& path ) override; void onFileEdited( const FilePath& path ) override; void onFileRemoved( const FilePath& path ) override; void onFileRenamed( const FilePath& oldPath, const FilePath& newPath ) override; void onDirAdded( const FilePath& dir ) override; void onDirRemoved( const FilePath& dir ) override; void onDirRenamed( const FilePath& oldPath, const FilePath& newPath ) override; void onFilesystemDeleted( Filesystem& filesystem ) override; }; ///////////////////////////////////////////////////////////////////////////////
true
73f3a1a11749a4ea61517a6e91fa89de6e6550dc
C++
nagyist/ParaView
/Examples/Catalyst/TemporalCacheExample/FEDataStructures.h
UTF-8
1,620
2.734375
3
[ "BSD-3-Clause" ]
permissive
// SPDX-FileCopyrightText: Copyright (c) Kitware Inc. // SPDX-License-Identifier: BSD-3-Clause /** The code for the toy simulation itself is here. In this example we make a configurable number of random sized spheres, and make them bounce around in a cube. At each timestep we move the spheres, and then sample them onto a configurable sized volume. The points and the volume are available to Catalyst pipelines, but in this example only the volume is temporally cached. Note: Interaction between spheres is left as an exercise to the reader. */ #ifndef FEDATASTRUCTURES_HEADER #define FEDATASTRUCTURES_HEADER #include <cstddef> #include <vector> class particle; class region; class Grid { // computational domain public: ~Grid(); Grid(); void Initialize(const unsigned int numPoints[3], const double spacing[3]); unsigned int GetNumberOfLocalPoints(); unsigned int GetNumberOfLocalCells(); void GetLocalPoint(unsigned int pointId, double* point); unsigned int* GetNumPoints(); unsigned int* GetExtent(); double* GetSpacing(); region* GetMyRegion() { return MyRegion; }; private: unsigned int NumPoints[3]; unsigned int Extent[6]; double Spacing[3]; region* MyRegion; }; class Attributes { // array of results, updated every timestep public: ~Attributes(); Attributes(int numParticles); void Initialize(Grid* grid); void UpdateFields(double time); double* GetOccupancyArray(); const std::vector<double>& GetParticles(); private: std::vector<double> Occupancy; std::vector<double> Particles; Grid* GridPtr; particle** MyParticles; int NumParticles; }; #endif
true
cfb27cb3e3ecb3348206345fbf1b9921267b5119
C++
sam-slate/day-in-the-life
/event.cpp
UTF-8
3,038
3.109375
3
[ "MIT" ]
permissive
#include <iostream> using namespace std; #include <string> #include <stdlib.h> #include <time.h> #include "event.h" #include "game.h" #include <unistd.h> Event :: Event(){ } Event :: Event(int id, bool random, string name, string message){ this->id = id; this->random = random; this->name = name; this->message = message; this->total_num_options = 0; } void Event :: initialize_event(int id, bool random, string name, string message){ this->id = id; this->random = random; this->name = name; this->message = message; this->total_num_options = 0; } void Event :: add_option(string name, string description, int change_pain, int change_spoons, int change_money, bool random, int random_percentage, int next_id){ options[total_num_options].set_all(name, description, change_pain, change_spoons, change_money, random, random_percentage, next_id); total_num_options++; } int Event :: run_event(Scores &s){ int choice = -1; int next_event = -1; if (SLEEP){sleep(2);} print_message(); if (SLEEP){sleep(2);} if (random){ next_event = process_random(s); } else { print_options(); choice = get_choice(); next_event = process_choice(choice, s); } return next_event; } void Event :: print_message(){ if (message != "" and message != " "){ cout << message << endl; } } void Event :: print_options(){ cout << "Your options: " << endl; for (int i = 0; i < total_num_options; i++){ cout << i + 1 << ") " << options[i].get_name() << endl; } } int Event :: get_choice(){ int choice = -1; cout << "Type the number of your choice: "; cin >> choice; return choice - 1; } int Event :: process_choice(int choice, Scores &s){ cout << options[choice].get_description() << endl << endl; if (SLEEP){sleep(2);} int change_pain = options[choice].get_change_pain(); int change_spoons = options[choice].get_change_spoons(); int change_money = options[choice].get_change_money(); if (change_pain != 0){ cout << "The change in pain tolerance is: " << change_pain << endl; } if (change_spoons != 0){ cout << "The change in spoons is: " << change_spoons << endl; } if (change_money != 0){ cout << "The change in money is: " << change_money << endl; } cout << endl; s.add_pain(change_pain); s.add_spoons(change_spoons); s.add_money(change_money); if (SLEEP){sleep(2);} s.print_scores(); cout << endl; if (s.check_lost()){ return LOST; } return options[choice].get_next_id(); } int Event :: process_random(Scores &s){ string trash; cout << "Type anything: "; cin >> trash; if (SLEEP){sleep(2);} srand(time(NULL)); int rand_num = rand() % 100; int range = 0; for (int i = 0; i < total_num_options; i++){ if (rand_num >= range and rand_num <= range + options[i].get_random_percentage()){ cout << options[i].get_name() << endl; return process_choice(i, s); } else { range += options[i].get_random_percentage(); } } cout << rand_num << endl; return 0; } int Event :: get_id(){ return id; }
true
39235b615c1c5dba4cbfb87f3d014f4e8acbaec9
C++
nschantz21/Accelerated_C-
/chap14/grading.cpp
UTF-8
1,565
3.53125
4
[]
no_license
#include<vector> #include<algorithm> #include<iostream> #include<string> #include"Handle.h" #include"Core.h" #include<iomanip> #include<stdexcept> using namespace std; // exercise 14-1 bool compare_Core_pointers(const Ptr<Core>& hc1, const Ptr<Core>& hc2){ return hc1->name() < hc2->name(); } int main(){ vector< Ptr<Core> > students; // changed type Ptr<Core> record; char ch; string::size_type maxlen = 0; // read and store the data while (cin>>ch) { if (ch == 'U') record = new Core; // allocated a Core object else record = new Grad; // allocate Grad object record->read(cin); // Handle<T>::->, then virtual call to read maxlen = max(maxlen, record->name().size()); students.push_back(record); } // compare must be rewritten to work on const Handle<Core>& sort(students.begin(), students.end(),compare_Core_pointers); // write names and grades for (vector<Ptr<Core> >::size_type i = 0; i != students.size(); ++i){ //students[i] is a Handle, which we dereference to call the functions cout << students[i]->name() << string(maxlen + 1 - students[i]->name().size(), ' '); try{ double final_grade = students[i]->grade(); streamsize prec = cout.precision(); cout << std::setprecision(3) << final_grade << std::setprecision(prec) << endl; } catch (domain_error e) { cout<<e.what()<<endl; } // no delete statement } return 0; }
true
3d3580664831820c183165fde8232599f3f6cd0d
C++
tetat/Codeforces-Problems-Sol
/Difficulty800/1077A.cpp
UTF-8
565
2.984375
3
[]
no_license
/// Problem Name: Frog Jumping /// Problem Link: https://codeforces.com/problemset/problem/1077/A #include <iostream> #include <cstdio> using namespace std; #define lol long long int int main() { int t;scanf("%d", &t); while (t--){ lol a, b, k; cin >> a >> b >> k; if (k==1){cout << a << endl;continue;} lol l, r; if (!(k%2))l = r = k/2; else { l = k/2+1; r = k/2; } lol res = (a*l)-(b*r); cout << res << endl; } return 0; }
true
422e4f4e00d2cf0be4650ecfb2bd9214aae68ee9
C++
Wahed08/ACM-Problem-Solving
/Getting An A.cpp
UTF-8
990
2.6875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int myf(int a,int b) { return a>b; } int main() { ios_base::sync_with_stdio(false); cin.tie(0),cout.tie(0); int n,sum=0,cnt=0; cin>>n; int arr[n]; for(int i=0; i<n; i++) { cin>>arr[i]; sum+=arr[i]; } sort(arr,arr+n); double val=0; val=1.0*sum/n; if(val>=4.5) { cout<<0<<endl; return 0; } else { for(int i=0; i<n; i++) { if(arr[i]<5) { int a=5-arr[i]; arr[i]+=a; cnt++; } sum=0,val=0; for(int j=0; j<n; j++) { sum+=arr[j]; } val=1.0*sum/n; // cout<<val<<" "; if(val>=4.5) { cout<<cnt<<endl; return 0; //break; } } } // cout<<cnt<<endl; return 0; }
true
dedbcf92340ed69111ba173565c75785c12f6c63
C++
EricDDK/leetcode_brush
/algorithms/047_PermutationsII/main_set_2000+ms.cpp
UTF-8
1,321
3.265625
3
[]
no_license
//Given a collection of numbers that might contain duplicates, return all possible unique permutations. #include<sstream> #include "iostream" #include <cstdint> #include <vector> #include <unordered_map> #include <map> #include <set> #include "algorithm" #include <stack> #include <string> #include <queue> using namespace std; class Solution { public: vector<vector<int>> permuteUnique(vector<int>& nums) { vector<vector<int>> res{{}}; for (auto &num : nums) { for (int k = res.size(); k > 0; --k) { vector<int> tmp = res.front(); res.erase(res.begin()); for (int i = 0; i <= tmp.size(); ++i) { vector<int> one = tmp; one.insert(one.begin() + i, num); res.push_back(one); } } } set<vector<int>> result; for (auto &r : res){ result.insert(result.begin(), r); } return vector<vector<int>> (result.begin(), result.end()); } }; int main() { Solution* solution = new Solution; vector<int> input = {1,1,2}; auto result = solution->permuteUnique(input); delete solution; //cout << result << endl; system( "read -n 1 -s -p \"Press any key to continue...\"" ); return 0; }
true
00042a92bf7ab25a3301a1b251acd486940ec26a
C++
alinaseri25/Qt_jalalidate
/qdatejalali.cpp
UTF-8
6,752
2.734375
3
[]
no_license
#include "qdatejalali.h" QDATEJALALI::QDATEJALALI(QObject *parent) : QObject(parent) { this->setParent(parent); shmdate.day = shmdate.month = 0; shmdate.year = 0 - 1300; mildate.day = mildate.month = 0;mildate.year = 0 - 2000; } bool QDATEJALALI::SetMiladiDate(int _year, int _month, int _day, int _dayOfWeek) { mildate.day = _day; mildate.month = _month; mildate.year = _year - 2000; dayOfWeek = _dayOfWeek; miltoshmcv(mildate.year,mildate.month,mildate.day); return true; } bool QDATEJALALI::SetMiladiDate(QString Date) { QStringList DatePart = Date.split("/"); if(DatePart.count() == 3) { mildate.year = QString(DatePart[0]).toInt() - 2000; mildate.month = QString(DatePart[1]).toInt(); mildate.day = QString(DatePart[2]).toInt(); miltoshmcv(mildate.year,mildate.month,mildate.day); return true; } else { mildate.day = mildate.month = 0;mildate.year = 0 - 2000; miltoshmcv(mildate.year,mildate.month,mildate.day); return false; } } bool QDATEJALALI::SetShamsiDate(int _year, int _month, int _day, int _dayOfWeek) { shmdate.day = _day; shmdate.month = _month; shmdate.year = _year - 1300; dayOfWeek = _dayOfWeek; shmtomilcv(shmdate.year,shmdate.month,shmdate.day); return true; } bool QDATEJALALI::SetShamsiDate(QString Date) { QStringList DatePart = Date.split("/"); if(DatePart.count() == 3) { shmdate.year = QString(DatePart[0].toInt() - 1300).toInt(); shmdate.month = QString(DatePart[1]).toInt(); shmdate.day = QString(DatePart[2]).toInt(); shmtomilcv(shmdate.year,shmdate.month,shmdate.day); return true; } else { shmdate.day = shmdate.month = 0; shmdate.year = 0 - 1300; shmtomilcv(shmdate.year,shmdate.month,shmdate.day); return false; } } bool QDATEJALALI::ProcNow() { QDateTime Now = QDateTime::currentDateTime(); SetMiladiDate(Now.date().year(),Now.date().month(),Now.date().day(),Now.date().dayOfWeek()); return true; } int QDATEJALALI::getdaymi() { return mildate.day; } int QDATEJALALI::getmonthmi() { return mildate.month; } QString QDATEJALALI::getmonthmistring() { switch (mildate.month) { case 1: return QString("January"); break; case 2: return QString("February"); break; case 3: return QString("March"); break; case 4: return QString("April"); break; case 5: return QString("May"); break; case 6: return QString("June"); break; case 7: return QString("July"); break; case 8: return QString("August"); break; case 9: return QString("September"); break; case 10: return QString("October"); break; case 11: return QString("November"); break; case 12: return QString("December"); break; default: return QString("Not in month range"); break; } } int QDATEJALALI::getyearmi() { return mildate.year + 2000; } QString QDATEJALALI::getdayofweekmi() { switch (dayOfWeek) { case 0: return QString("sunday"); break; case 1: return QString("monday"); break; case 2: return QString("tuesday"); break; case 3: return QString("wednesday"); break; case 4: return QString("thursday"); break; case 5: return QString("friday"); break; case 6: return QString("saturday"); break; default: return QString("Error"); break; } } int QDATEJALALI::getdaysh() { return shmdate.day; } int QDATEJALALI::getmonthsh() { return shmdate.month; } QString QDATEJALALI::getmonthshstring() { switch (shmdate.month) { case 1: return QString("فروردین"); break; case 2: return QString("اردیبهشت"); break; case 3: return QString("خرداد"); break; case 4: return QString("تیر"); break; case 5: return QString("مرداد"); break; case 6: return QString("شهریور"); break; case 7: return QString("مهر"); break; case 8: return QString("آبان"); break; case 9: return QString("آذر"); break; case 10: return QString("دی"); break; case 11: return QString("بهمن"); break; case 12: return QString("اسفند"); break; default: return QString("خارج از بازه ی ماه ها"); break; } } int QDATEJALALI::getyearsh() { return shmdate.year + 1300; } QString QDATEJALALI::getdayofweeksh() { switch (dayOfWeek) { case 0: return QString("یکشنبه"); break; case 1: return QString("دوشنبه"); break; case 2: return QString("سشنبه"); break; case 3: return QString("چهارشنبه"); break; case 4: return QString("پنجشنبه"); break; case 5: return QString("جمعه"); break; case 6: return QString("شنبه"); break; default: return QString("Error"); break; } } /*************************************************************************/ void QDATEJALALI::miltoshmcv(unsigned char ym,unsigned char mm,unsigned char dm) { //ym -= 2000; unsigned char k,t1,t2; k=ym%4; if(k==3) k=2; k*=2; t1=miltable[k][mm-1]; t2=miltable[k+1][mm-1]; if(mm<3 || (mm==3 && dm<=miltable[k][mm-1])) shmdate.year = ym + 78; else shmdate.year = ym + 79; if(dm<=t1) { shmdate.day=dm+t2; shmdate.month=(mm+8)%12+1; } else { shmdate.day=dm-t1; shmdate.month=(mm+9)%12+1; } } /**********************************************************************/ void QDATEJALALI::shmtomilcv(unsigned char ys ,unsigned char ms,unsigned char ds) { //ys -= 1300; unsigned char k,t1,t2; k = ys%4; if( k == 0) k = 2; else k = k + k; t1 =shmtable[k - 2][ms-1]; t2 = shmtable[k-1][ms-1]; if(ms<10 || (ms==10 && ds <= shmtable[k-2][ms-1])) mildate.year = ys - 79; else mildate.year = ys - 78; //mildate.year += 2000; if(ds <= t1) { mildate.day = ds + t2; mildate.month = (ms + 1)%12 + 1; } else { mildate.day= ds - t1; mildate.month= (ms + 2)%12 + 1; } }
true
9d84d0b9ad966186cfc8c3fdd5f6386b782ef3a1
C++
maxrake/CppCourse
/Instructor Solutions/TypeExamplesAndHelloWorld!/constexpr/Source.cpp
UTF-8
1,192
3.421875
3
[]
no_license
#include <iostream> #include <limits> namespace cppcourse //needed as the global namespace gets poluted when limits includes cmath which includes math.h { constexpr int square(int x) { return x*x; } constexpr long long_max() { return std::numeric_limits<long>::max(); } //This function is not constexpr in math.h and there is a collision if not in namespace. //boo constexpr int abs(int x) { return x < 0 ? -x : x; } /* constexpr void f(int x) { //can't have a void constexpr function... this is an error. //yes it compiles but just try to use it. The compiler just ignores this unless it is used. } */ constexpr int prev(int x) { //return x - 1; return --x; //constexpr function return is non-constant } constexpr int g(int x, int n) //not allowed by microsofts C++14 implementation. Use clang to make it work. { int r = 1; while (--n > 0) r *= x; return r; } } int main() { using namespace cppcourse; int x[square(3)]; int y[prev(5)]; return 0; }
true
1c9e6df9e4c79c165236ebc1f5a81c451f4fc07b
C++
kylchien/Prac
/Bit/PowerSet.h
UTF-8
1,022
3.46875
3
[]
no_license
#pragma once #include <iostream> #include <string> #include <vector> #include <math.h> #include <map> using namespace std; /* given {x, y ,z} return {} {x} {y} {z} {xy} {xz} {yz} {xyz} For the whole power set of S we get: { } = 000 (Binary) = 0 (Decimal) {x} = 100 = 4 {y} = 010 = 2 {z} = 001 = 1 {x, y } = 110 = 6 {x, z } = 101 = 5 {y, z } = 011 = 3 {x, y, z } = 111 = 7 map lg(n) for 2^n * lg (n) so overall still O(2^n lg (n)) can use & 1<<bitpos to do the same trick */ void powerSet(vector<char>& vec) { int exp = vec.size(); int len = pow(2, exp); map<int, char> map; for (int i = 0; i < exp; ++i) { map[i + 1] = vec[i]; } string output = ""; for (int i = 0; i < len; ++i) { string s = "{"; int copy = i; int bitpos = 1; //from low pos to high pos (right to left) while (copy > 0) { if (copy & 1) { char c = map[bitpos]; s += c; } copy >>= 1; bitpos++; } s += "} "; output += s; } cout << output << endl; }
true
7419c29c490797df6f38cf3261f1b96b8a8807ba
C++
alexandraback/datacollection
/solutions_5766201229705216_0/C++/entri/main.cpp
UTF-8
1,980
2.84375
3
[]
no_license
#include <iostream> #include <string> #include <vector> #include <algorithm> #include <stdlib.h> #include <string.h> using namespace std; int T; const int maxN = 1005; const int INF = 1000000; //bool mark[maxN][maxN]; int N; vector<pair<int,int> > Edge; vector<int> AdjOf[maxN]; int DegreeOf[maxN]; int countFrom(int u){ int res = 0; if (DegreeOf[u] == 1) return 1; vector<int> Q; Q.push_back(u); res++; bool visited[maxN]; memset(visited,false,sizeof(visited)); visited[u] = true; int dq = 0, cq = 0; while(dq <= cq){ int u = Q[dq]; visited[u] = true; dq++; for(int i = 0; i<AdjOf[u].size(); i++){ int v = AdjOf[u][i]; if (visited[v]) continue; if (DegreeOf[v] == 2){ if (DegreeOf[u] == 2) res++; continue; } Q.push_back(v); res++; cq++; }; }; return res; } void solveIt(){ int res = 0; for(int i = 1; i<=N; i++){ int cnt = countFrom(i); //cout <<" from "<<i<<" : "<<cnt<<endl; res = max(res,cnt); }; res = N - res; cout <<res<<endl; } void input(){ cin >>T; for(int i = 1; i<=T;i++){ cin >>N; Edge.clear(); //memset(mark, false, sizeof(mark)); memset(AdjOf, 0,sizeof(AdjOf)); memset(DegreeOf, 0, sizeof(DegreeOf)); for(int j = 1; j<N; j++){ int x,y; cin >>x>>y; Edge.push_back(make_pair(x,y)); AdjOf[x].push_back(y); DegreeOf[x]++; AdjOf[y].push_back(x); DegreeOf[y]++; //mark[x][y] = true; //mark[y][x] = true; } cout<<"Case #"<<i<<": "; solveIt(); } }; int main() { input(); //cout << "Hello world!" << endl; return 0; }
true
8c0d4ed73c1c1dfafa6e8ad84c60e6e6908a1276
C++
kevinMkY/CPP_ALGO
/testC++++/题库14合并k个已升序链表.cpp
UTF-8
1,429
3.03125
3
[]
no_license
// // 题库14合并k个已升序链表.cpp // testC++++ // // Created by yekaihua on 2021/3/7. // #include "题库14合并k个已升序链表.hpp" #include "common.h" ListNode *_tk_14_test_merge2Lists(ListNode *l1,ListNode *l2){ if(!l1)return l2; if(!l2)return l1; if(l1->val <= l2->val){ l1->next = _tk_14_test_merge2Lists(l1->next,l2); return l1; }else{ l2->next = _tk_14_test_merge2Lists(l1,l2->next); return l2; } return nullptr; } ListNode *_tk_14_test_mergeKLists(vector<ListNode *> &lists,int l ,int r) { if (l>r) return nullptr; int mid = l; while (l<r) { mid = l+((r-l)>>1); if (l==r) { return lists[l]; }else if (l==r-1) { ListNode *left = lists[l]; ListNode *right = lists[r]; return _tk_14_test_merge2Lists(left,right); }else{ ListNode *left = _tk_14_test_mergeKLists(lists,l,mid); ListNode *right = _tk_14_test_mergeKLists(lists,mid+1,r); return _tk_14_test_merge2Lists(left,right); } } return lists[l]; } ListNode *_tk_14_test_mergeKLists(vector<ListNode *> &lists) { int n = lists.size(); return _tk_14_test_mergeKLists(lists,0,n-1); } void _tk_14_test() { vector<ListNode *>list = {}; ListNode *res= _tk_14_test_mergeKLists(list); //小顶堆,升序队列 }
true
7c28a474dce86555952fc920cad8f38bb358f039
C++
kks227/BOJ
/3400/3473.cpp
UTF-8
2,038
3.078125
3
[]
no_license
#include <iostream> #include <string> #include <stack> #include <vector> #include <utility> #include <cctype> using namespace std; typedef pair<char, string> Node; int main(){ int T; cin >> T; for(int t = 0; t < T; ++t){ string E; cin >> E; stack<char> S1; vector<char> P; for(char c: E){ if(c == '('){ S1.push('('); } else if(c == ')'){ while(S1.top() != '('){ P.push_back(S1.top()); S1.pop(); } S1.pop(); } else if(c == '+'){ while(!S1.empty() && S1.top() != '('){ P.push_back(S1.top()); S1.pop(); } S1.push('+'); } else if(c == '-'){ while(!S1.empty() && S1.top() != '('){ P.push_back(S1.top()); S1.pop(); } S1.push('-'); } else if(c == '*'){ while(!S1.empty() && (S1.top() == '*' || S1.top() == '/')){ P.push_back(S1.top()); S1.pop(); } S1.push('*'); } else if(c == '/'){ while(!S1.empty() && (S1.top() == '*' || S1.top() == '/')){ P.push_back(S1.top()); S1.pop(); } S1.push('/'); } else{ P.push_back(c); } } while(!S1.empty()){ P.push_back(S1.top()); S1.pop(); } stack<Node> S2; for(char c: P){ if(islower(c)){ S2.push(Node(' ', string(1, c))); } else{ Node A[2]; A[1] = S2.top(); S2.pop(); A[0] = S2.top(); S2.pop(); bool pflag[2] = {false,}; if(c == '+'){ } else if(c == '-'){ if(A[1].first == '+' || A[1].first == '-') pflag[1] = true; } else if(c == '*'){ for(int k = 0; k < 2; ++k) if(A[k].first == '+' || A[k].first == '-') pflag[k] = true; } else{ for(int k = 0; k < 2; ++k) if(A[k].first == '+' || A[k].first == '-') pflag[k] = true; if(A[1].first == '*' || A[1].first == '/') pflag[1] = true; } string temp[2] = {A[0].second, A[1].second}; for(int k = 0; k < 2; ++k) if(pflag[k]) temp[k] = "(" + temp[k] + ")"; Node C(c, temp[0] + string(1, c) + temp[1]); S2.push(C); } } cout << S2.top().second << '\n'; } }
true
03b71c3b2a5d0ea06cfe9461531d1bb085497b4b
C++
mtoutai/fastq_index
/fastq_index.cpp
UTF-8
5,079
2.5625
3
[ "LicenseRef-scancode-public-domain", "CC0-1.0" ]
permissive
// fastq_index.c // // THIS SOFTWARE IS DISTRIBUTED UNDER // CC0 1.0 Universal // Public Domain Dedication // http://creativecommons.org/publicdomain/zero/1.0/ // // Developed by: // TOTAI MITSUYAMA, PhD. // Biotechnology Research Institute for Drug Discovery // National Institute of Advanced Industrial Science and Technology (AIST) // // Version; 0.1 // August 3. 2015. // #include <iostream> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #define max(x,y) (x>y)?x:y #ifdef DEBUG_BUILD #define DEBUG(x) do { std::cerr << "Debug: " << __FILE__ << ": " << __LINE__ << ": " << x << std::endl; } while(0) #else #define DEBUG(x) #endif /* DEBUG_BUILD */ #define DEFAULT_STEP 1000000 #define BLOCK_SIZE 4096 #define LINE_BUFFER_SIZE 10240 int count_lines (FILE *fp) { rewind (fp); char buff[LINE_BUFFER_SIZE]; int lines = 0; for ( ; fgets(buff, LINE_BUFFER_SIZE, fp) != NULL && buff[0]!='\0'; ++lines); rewind (fp); return lines; } int estimate_seq_len (FILE *fp, size_t *head1_len, size_t *seq_len, size_t *head2_len, size_t *qual_len) { rewind (fp); int c=0; for (c=fgetc (fp); !feof (fp) & c!='\n'; c=fgetc (fp), ++(*head1_len)); for (c=fgetc (fp); !feof (fp) & c!='\n'; c=fgetc (fp), ++(*seq_len)); for (c=fgetc (fp); !feof (fp) & c!='\n'; c=fgetc (fp), ++(*head2_len)); for (c=fgetc (fp); !feof (fp) & c!='\n'; c=fgetc (fp), ++(*qual_len)); rewind (fp); ++(*head1_len); // counting '\n' ++(*seq_len); // counting '\n' ++(*head2_len); // counting '\n' ++(*qual_len); // counting '\n' return (*seq_len); } void usage(FILE *fp) { fprintf (fp, "Create the index file for a given FASTQ file.\n"); fprintf (fp, "Usage: fastq_index [-i <fastq index file>] [-s <number of items per block> (default: 1000000)] <fastq_file>\n"); } int main (int argc, char **argv) { if (argc==1) { usage (stdout); return (0); } char index_file[4096] = { '\0' }; char step_str[256] = { '\0' }; int arg_opt; while ((arg_opt=getopt(argc, argv, "i:s:"))!=-1) { switch(arg_opt) { case 'i': strncpy(index_file, optarg, sizeof(index_file)-1); break; case 's': strncpy(step_str, optarg, sizeof(step_str)-1); break; default: fprintf(stderr, "Error: main: Unknown option speficied.\n"); usage(stderr); return(1); } } FILE *fp=NULL; fp=fopen (argv[optind], "r"); if (fp==NULL) { fprintf (stderr, "Error: main: \"%s\" is not found.\n", argv[optind]); return (1); } int step=DEFAULT_STEP; if (step_str[0] != '\0') { if (sscanf(step_str, "%d", &step) != 1) { fprintf (stderr, "Error: main: \"-s %s\" has invalid argument.\n", step_str); return(1); } } int step_lines=step * 4; struct stat file_stat; stat (argv[optind], &file_stat); size_t head1_len=0; size_t seq_len=0; size_t head2_len=0; size_t qual_len=0; float estimated_lines=0; if (file_stat.st_size < 1048576) estimated_lines = count_lines (fp); else { estimate_seq_len (fp, &head1_len, &seq_len, &head2_len, &qual_len); DEBUG("header_length(1)=" << head1_len << " sequence_length=" << seq_len << " header_length(2)=" << head2_len << " quality_length=" << qual_len); estimated_lines = file_stat.st_size / (head1_len + seq_len + head2_len + qual_len); } DEBUG("estimated_lines=" << estimated_lines); if (estimated_lines < step_lines) { fprintf (stderr, "Error: main: \"-s %s\" specifies too larger value than estimated number of lines (%.1f).\n", step_str, estimated_lines); return (1); } int buffer_size=(max (head1_len, seq_len))*2; char *buffer=NULL; buffer=(char *)calloc (buffer_size, sizeof (char)); if (buffer==NULL) { fprintf (stderr, "Error: main: memory allocation error.\n"); return (1); } DEBUG("buffer_size=" << buffer_size); long int *index=NULL; // why "long int" because ftell returns a "long int" value. size_t index_lines=BLOCK_SIZE/sizeof (long int); index=(long int*)calloc (index_lines, sizeof (long int)); if (index==NULL) { fprintf (stderr, "Error: main: memory allocation error.\n"); return (1); } DEBUG("index_lines=" << index_lines); if (index_file[0] == '\0') { sprintf (index_file, "%s.index", argv[optind]); } DEBUG("index_file_name=" << index_file); FILE *outfp=NULL; outfp=fopen (index_file, "wb"); size_t line_no=0; size_t ii=0; for ( ; fgets (buffer, buffer_size, fp) != NULL; ) { ++line_no; if (buffer[buffer_size-1] != 0 & buffer[buffer_size-1] != '\n') { fprintf (stderr, "Error: main: the line no. %d is longer than the buffer size (%d).\n", line_no, buffer_size); return (1); } if (line_no % step_lines==0) { if (ii>=index_lines) { fprintf (stderr, "Error: main: ii=%d >= index_lines=%d\n", ii, index_lines); return (-1); } index[ii++] = ftell (fp); if (ii==index_lines) { ii=0; fwrite (index, sizeof (long int), index_lines, outfp); memset (index, index_lines, sizeof (long int)); } } DEBUG ("line_no=" << line_no); } fclose (fp); if (ii>0) { fwrite (index, sizeof (long int), index_lines, outfp); } fclose (outfp); return (0); }
true
e09b1b1503e6b4ed3ca89586ca8eb17e21295867
C++
gverhelp/19_CPP
/cpp07/ex02/Array.hpp
UTF-8
1,837
3.625
4
[]
no_license
#ifndef ARRAY_HPP # define ARRAY_HPP # include <iostream> template<typename T> class Array { public: Array(); Array(unsigned int n); Array(const Array &copy); Array& operator=(const Array &copy); T& operator[](unsigned int const a); ~Array(); unsigned int size(void) const; class ArrayExceptions : public std::exception { const char *what() const throw(); }; private: T* _array; unsigned int _len; }; template<typename T> Array<T>::Array(): _len(0) { std::cout << "Constructor has been called" << std::endl; _array = new T[0]; } template<typename T> Array<T>::Array(unsigned int len): _len(len) { std::cout << "Overloaded constructor has been called" << std::endl; _array = new T[_len]; for (unsigned int a = 0; a < len; a++) _array[a] = 0; } template<typename T> Array<T>::Array(const Array &copy) { *this = copy; } template<typename T> Array<T>& Array<T>::operator=(const Array &copy) { if (this != &copy) { _len = copy._len; if (_array) delete [] _array; _array = new T[copy._len]; for (unsigned int a = 0; a < _len; a++) _array[a] = copy._array[a]; } return (*this); } template<typename T> T& Array<T>::operator[](unsigned int const a) { if (a >= _len) throw ArrayExceptions(); return (_array[a]); } template<typename T> Array<T>::~Array() { std::cout << "Destructor has been called" << std::endl; if (_array) delete [] _array; } template<typename T> unsigned int Array<T>::size() const { return (_len); } template<typename T> const char* Array<T>::ArrayExceptions::what() const throw() { return ("This element is out of the limits"); } #endif
true
1cac3bdd724a4456ec27ac830ed34666b7dc8f57
C++
grimtraveller/voice2midi
/source/voice2midi/fft.cpp
UTF-8
3,881
2.515625
3
[]
no_license
// fft.cpp : Defines the entry point for the console application. // #include "math.h" #define DDC_PI 3.1415926; int IsPowerOfTwo ( int x ) { if ( x < 2 ) return 0; if ( x & (x-1) ) // Thanks to 'byang' for this cute trick! return 0; return 1; } int NumberOfBitsNeeded ( int PowerOfTwo ) { int i; if ( PowerOfTwo < 2 ) { /* fprintf ( stderr, ">>> Error in fftmisc.c: argument %d to NumberOfBitsNeeded is too small.\n", PowerOfTwo ); */ return 0; } for ( i=0; ; i++ ) { if ( PowerOfTwo & (1 << i) ) return i; } } int ReverseBits ( int index, int NumBits ) { int i, rev; for ( i=rev=0; i < NumBits; i++ ) { rev = (rev << 1) | (index & 1); index >>= 1; } return rev; } double Index_to_frequency ( int NumSamples, int Index ) { if ( Index >= NumSamples ) return 0.0; else if ( Index <= NumSamples/2 ) return (double)Index / (double)NumSamples; return -(double)(NumSamples-Index) / (double)NumSamples; } void fft_float ( int NumSamples, int InverseTransform, float *RealIn, float *ImagIn, float *RealOut, float *ImagOut ) { int NumBits; /* Number of bits needed to store indices */ int i, j, k, n; int BlockSize, BlockEnd; double angle_numerator = 2.0 * DDC_PI; double tr, ti; /* temp real, temp imaginary */ if ( !IsPowerOfTwo(NumSamples) ) { /* fprintf ( stderr, "Error in fft(): NumSamples=%u is not power of two\n", NumSamples ); */ return; } if ( InverseTransform ) angle_numerator = -angle_numerator; //CHECKPOINTER ( RealIn ); //CHECKPOINTER ( RealOut ); //CHECKPOINTER ( ImagOut ); NumBits = NumberOfBitsNeeded ( NumSamples ); /* ** Do simultaneous data copy and bit-reversal ordering into outputs... */ for ( i=0; i < NumSamples; i++ ) { j = ReverseBits ( i, NumBits ); RealOut[j] = RealIn[i]; ImagOut[j] = (ImagIn == 0) ? 0.0 : ImagIn[i]; } /* ** Do the FFT itself... */ BlockEnd = 1; for ( BlockSize = 2; BlockSize <= NumSamples; BlockSize <<= 1 ) { double delta_angle = angle_numerator / (double)BlockSize; double sm2 = sin ( -2 * delta_angle ); double sm1 = sin ( -delta_angle ); double cm2 = cos ( -2 * delta_angle ); double cm1 = cos ( -delta_angle ); double w = 2 * cm1; double ar[3], ai[3]; double temp; for ( i=0; i < NumSamples; i += BlockSize ) { ar[2] = cm2; ar[1] = cm1; ai[2] = sm2; ai[1] = sm1; for ( j=i, n=0; n < BlockEnd; j++, n++ ) { ar[0] = w*ar[1] - ar[2]; ar[2] = ar[1]; ar[1] = ar[0]; ai[0] = w*ai[1] - ai[2]; ai[2] = ai[1]; ai[1] = ai[0]; k = j + BlockEnd; tr = ar[0]*RealOut[k] - ai[0]*ImagOut[k]; ti = ar[0]*ImagOut[k] + ai[0]*RealOut[k]; RealOut[k] = RealOut[j] - tr; ImagOut[k] = ImagOut[j] - ti; RealOut[j] += tr; ImagOut[j] += ti; } } BlockEnd = BlockSize; } /* ** Need to normalize if inverse transform... */ if ( InverseTransform ) { float denom = (float)NumSamples; for ( i=0; i < NumSamples; i++ ) { RealOut[i] /= denom; ImagOut[i] /= denom; } } }
true
12cddd29350cd3fe906b1856c95924680e7cd377
C++
wangxianghust/leetcode
/52NQueens.cpp
UTF-8
1,447
3.640625
4
[ "MIT" ]
permissive
/*求出NQueens的解 * 经典的回溯法就可以解决,稍微tricky的地方是,matrix不是用二维矩阵保存的,一维就可以 */ #include <vector> #include <string> #include <iostream> using namespace std; class Solution { public: int totalNQueens(int n) { vector<int> matrix(n, -1);//every row have one queen, the value is the column index. int ret = 0; solveNQueens(ret, matrix, 0); return ret; } private: void solveNQueens(int &ret, vector<int> &matrix, int row){ int size = matrix.size(); if(row == size){ ++ret; return; } for(int column=0; column<size; ++column){ if(isValid(matrix, row, column)){ matrix[row] = column; solveNQueens(ret, matrix, row+1); matrix[row] = -1; } } } bool isValid(vector<int> &matrix, int row, int column){ for(int i=0; i<row; ++i){ int j = matrix[i]; //get the column of row i if(abs(row-i) == abs(column-j) || column == j) return false; } return true; } }; int main(){ freopen("52test.txt", "r", stdin); int total; cin >> total; //cout << total << endl; Solution Sol; for(int i=0; i<total; ++i){ int n; cin >> n; //cout << n << endl; auto ret = Sol.totalNQueens(n); cout << ret << endl; } }
true
817205cd46f3dfd704d5c03ada53b9357f8e30f5
C++
jDellsperger/tafl
/src/Board.h
UTF-8
1,791
2.921875
3
[ "BSD-2-Clause-Views" ]
permissive
#ifndef BOARD_H const uint8_t DIM = 7; const Vector2 DIRECTIONS[4] = { {0, 1}, {0, -1}, {1, 0}, {-1, 0} }; #include "Gamestate.h" class ZobristNode { public: ZobristNode* next = nullptr; GameState state; }; class ZobristEntryNode { public: ZobristNode* firstNode = nullptr; }; class Board { private: static Vector2 thronePos; Board(); GameState* getGameState(GameState* s); GameState* addGameState(GameState* s); public: GameState* state; // TODO(jan): is this the best place for this? // how large should the hash table be? ZobristEntryNode zobristHashTable[UINT16_MAX + 1]; uint16_t zobristValues[DIM][DIM][3]; int roundCount = 0; static Board* getInstance(); static bool isFieldPosTarget(Vector2 pos); static bool isFieldPosThrone(Vector2 pos); static bool isFieldPosValid(Vector2 pos); uint16_t getZobristValue(Vector2 pos, uint8_t s); GameState* getZobristAddress(GameState* s); }; inline bool Board::isFieldPosValid(Vector2 pos) { bool result = (pos.x >= 0) && (pos.y >= 0) && (pos.x < DIM) && (pos.y < DIM); return result; } inline bool Board::isFieldPosTarget(Vector2 pos) { bool result = false; // TODO(jan): extract target vectors into array in board class if (pos.x == 0) { if (pos.y == 0 || pos.y == DIM - 1) { result = true; } } else if (pos.x == DIM - 1) { if (pos.y == 0 || pos.y == DIM - 1) { result = true; } } return result; } inline bool Board::isFieldPosThrone(Vector2 pos) { bool result = Board::thronePos.equals(pos); return result; } #define BOARD_H #endif
true
b9497da6de94dbbe5f8760272394206060d11799
C++
Taekleee/Algoritmos-num-ricos
/Lab2/Integracion/test/escribir.h
UTF-8
2,709
3.0625
3
[]
no_license
#include <fstream> #include <iostream> #include <vector> using namespace std; void escribirErrores(long double ); void escribirIntegrales(long double ec1Trapecio, long double ec2Trapecio); void escribirErrores(long double errores[24]){ ofstream archivo("errores.txt"); if(archivo.is_open()){ archivo <<"DifD_A1_E1_10: "<< errores[0] << "\n"; archivo <<"DifD_A2_E2_10: "<< errores[1] << "\n"; archivo <<"DifD_A3_E1_5: "<< errores[2] << "\n"; archivo <<"DifD_A4_E2_5: "<< errores[3] << "\n"; archivo <<"DifD_A5_E1_1: "<< errores[4] << "\n"; archivo <<"DifD_A6_E2_1: "<< errores[5] << "\n"; archivo <<"DifD_A7_E1_05: "<< "errores[6]" << "\n"; archivo <<"DifD_A8_E2_05: "<< "errores[7]" << "\n"; archivo <<"DifF_A9_E1_10: "<< errores[8] << "\n"; archivo <<"DifF_A10_E2_10: "<< errores[9] << "\n"; archivo <<"DifF_A11_E1_5: "<< errores[10] << "\n"; archivo <<"DifF_A12_E2_5: "<< errores[11] << "\n"; archivo <<"DifF_A13_E1_1: "<< errores[12] << "\n"; archivo <<"DifF_A14_E2_1: "<< errores[13] << "\n"; archivo <<"DifF_A15_E1_05: "<< "errores[14]" << "\n"; archivo <<"DifF_A16_E2_05: "<< "errores[15]" << "\n"; archivo << "Min_A17_E1_10: " <<errores[16] << "\n"; archivo << "Min_A18_E2_10: " <<errores[17] << "\n"; archivo << "Min_A19_E1_5: " <<errores[18] << "\n"; archivo << "Min_A20_E2_5: " <<errores[19] << "\n"; archivo << "Min_A21_E1_1: " <<errores[20] << "\n"; archivo << "Min_A22_E2_1: " <<errores[21] << "\n"; archivo << "Min_A23_E1_05: " <<errores[22] << "\n"; archivo << "Min_A24_E2_05: " <<errores[23] << "\n"; archivo << "sp_A25_E1_10: " << errores[24] << "\n"; archivo << "sp_A26_E2_10: " << errores[25] << "\n"; archivo << "sp_A27_E1_5: " << errores[26] << "\n"; archivo << "sp_A28_E2_5: " << errores[27] << "\n"; archivo << "sp_A29_E1_1: " << errores[28] << "\n"; archivo << "sp_A30_E2_1: " << errores[29] << "\n"; archivo << "sp_A31_E1_05: " << errores[30] << "\n"; archivo << "sp_A32_E2_05: " << errores[31] << "\n"; } archivo.close(); } void escribirIntegrales(long double ec1Trapecio, long double ec2Trapecio, long double simpson, long double simpson2){ ofstream archivo("Trapecio.txt"); if(archivo.is_open()){ archivo << "Calculo exponencial mediante trapecio: " << ec1Trapecio << "\n"; archivo << "Calculo polinomio mediante trapecio: " << ec2Trapecio << "\n"; archivo << "Calculo exponencial mediante simpson: " << simpson << "\n"; archivo << "Calculo polinomio mediante simpson: " << simpson2 << "\n"; } archivo.close(); }
true
8265b7b6ff9f1ce95a7f981f1c221faeb14d4744
C++
alexandraback/datacollection
/solutions_2449486_1/C++/paladin8/B.cc
UTF-8
709
2.546875
3
[]
no_license
#include <iostream> #include <memory.h> using namespace std; int a[110][110], maxr[110], maxc[110]; int main() { int t; cin >> t; for (int c = 1; c <= t; c++) { int n, m; cin >> n >> m; memset(maxr, 0, sizeof(maxr)); memset(maxc, 0, sizeof(maxc)); for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { cin >> a[i][j]; maxr[i] = max(maxr[i], a[i][j]); maxc[j] = max(maxc[j], a[i][j]); } bool ok = true; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) ok = ok && (a[i][j] == maxr[i] || a[i][j] == maxc[j]); cout << "Case #" << c << ": " << (ok ? "YES" : "NO") << endl; } return 0; }
true
fe03e946cf87fdf4f2df763cff7e216bf53f5bd9
C++
jpaterso/fire-engine
/src/FPSCalculator.cpp
UTF-8
1,025
2.78125
3
[]
no_license
/** * FILE: FPSCalculator.cpp * AUTHOR: Joseph Paterson ( joseph dot paterson at gmail dot com ) * RCS ID: $Id: FPSCalculator.cpp 110 2007-09-23 15:57:55Z jpaterso $ * PURPOSE: A simple class to calculate the number of frames per second. **/ #include "FPSCalculator.h" #include "Timer.h" namespace fire_engine { FPSCalculator::FPSCalculator() : mFPS(0.0), mAverageFPS(0.0), mFramesDrawn(0), mLastFramePolyCount(0) { mTimer.start(); mInitialTime = mTimer.getElapsedTimeSeconds(); mLastCalculated = mInitialTime; } void FPSCalculator::registerFrameDrawn(s32 polys) { mTimeNow = mTimer.getElapsedTimeSeconds(); mFramesDrawn++; mFPS = 1.0/(mTimeNow-mLastCalculated); mLastCalculated = mTimeNow; mAverageFPS = mFramesDrawn/(mTimeNow-mInitialTime); mLastFramePolyCount = polys; } f64 FPSCalculator::getFPS() const { return mFPS; } f64 FPSCalculator::getAverageFPS() const { return mAverageFPS; } s32 FPSCalculator::getFramesDrawn() const { return mFramesDrawn; } s32 FPSCalculator::getLastPolyCount() const { return mLastFramePolyCount; } }
true
5ac6730615b252d511ae6250c9dd0d2a35d40f1e
C++
RTCSD2016/notes
/grp_cpp/PWM3/PWMTASK2.CPP
UTF-8
1,035
2.78125
3
[]
no_license
// Inherited classes for PWM -- the only substantive // material here is the PWMOn and PWMOff functions // File: pwmtask2.cpp // created 12/25/95, DM Auslander #include <iostream.h> #include <string.h> #include "tasks.hpp" PWMTask2::PWMTask2(char *aName) : PWMBaseTask (aName) { // Nothing to initialize here -- its all done in the // base class constructor. Any initializations unique // to the inherited class would be done here. } PWMTask2::~PWMTask2(void) { }; // PWMOn() and PWMOff are defined here and are unique to this // class. Although they are really the same in the case of // this example, in a real example they would have differen // code to access different I/O devices. void PWMTask2::PWMOn(void) { PWMOutput = 1; PWMRecord->AddData(PWMOutput,END_OF_ARGS); CriticalSectionBegin(); xPWMOutput = PWMOutput; CriticalSectionEnd(); } void PWMTask2::PWMOff(void) { PWMOutput = 0; PWMRecord->AddData(PWMOutput,END_OF_ARGS); CriticalSectionBegin(); xPWMOutput = PWMOutput; CriticalSectionEnd(); }
true
dee48e70dfa20db8e1d817c704284bc2ebc770b1
C++
bldbld/cpp-common
/poj.cpp/prob1003.cpp
UTF-8
1,878
3.40625
3
[]
no_license
// POJ 1003 Hangover // // Description // How far can you make a stack of cards overhang a table? If you have one card, you can create a maximum overhang of half a card length. (We're assuming that the cards must be perpendicular to the table.) With two cards you can make the top card overhang the bottom one by half a card length, and the bottom one overhang the table by a third of a card length, for a total maximum overhang of 1/2 + 1/3 = 5/6 card lengths. In general you can make n cards overhang by 1/2 + 1/3 + 1/4 + ... + 1/(n + 1) card lengths, where the top card overhangs the second by 1/2, the second overhangs tha third by 1/3, the third overhangs the fourth by 1/4, etc., and the bottom card overhangs the table by 1/(n + 1). This is illustrated in the figure below. // IMG:http://poj.org/images/1003/hangover.jpg // // Input // The input consists of one or more test cases, followed by a line containing the number 0.00 that signals the end of the input. Each test case is a single line containing a positive floating-point number c whose value is at least 0.01 and at most 5.20; c will contain exactly three digits. // // Output // For each test case, output the minimum number of cards necessary to achieve an overhang of at least c card lengths. Use the exact output format shown in the examples. // // Sample Input // 1.00 // 3.71 // 0.04 // 5.19 // 0.00 // // Sample Output // 3 card(s) // 61 card(s) // 1 card(s) // 273 card(s) // // 4333024_AC_16MS_292K // // Author: Ballad // Date: 2008-11-06 #include <iostream> #include <math.h> using namespace std; int main () { float t; int a[100]; int i=0; float total=0.5; cin>>t; while(fabs(t-0.00)>0.000001){ a[i]=1; while(t-total>0.000001){ a[i]++; total+=(1.0/(a[i]+1)); } i++; total=0.5; t=0.0; cin>>t; } for(int j=0;j<i;j++) cout<<a[j]<<" card(s)"<<endl; return 0; }
true
254c11edcbdf6effd438c1fba68b8ea5d0b3993f
C++
mtriston/ft_containers
/list.hpp
UTF-8
15,117
3.234375
3
[]
no_license
// // Created by mtriston on 09.02.2021. // #ifndef FT_CONTAINERS_LIST_HPP #define FT_CONTAINERS_LIST_HPP #include "utils.hpp" namespace ft { template<typename T> struct ListNode; template<typename T> class list_iterator { private: typedef list_iterator<T> Self; typedef ListNode<T> Node; Node *_node; public: typedef std::ptrdiff_t difference_type; typedef T value_type; typedef T *pointer; typedef T &reference; typedef ft::bidirectional_iterator_tag iterator_category; explicit list_iterator(Node *node = 0) : _node(node) {} ~list_iterator() {} list_iterator(list_iterator const &other) : _node(other._node) {} list_iterator &operator=(list_iterator const &other) { if (this != &other) _node = other._node; return (*this); } Node *getNode() { return _node; } reference operator*() const { return _node->data; } pointer operator->() const { return &(_node->data); } bool operator==(list_iterator const &rhs) const { return this->_node == rhs._node; } bool operator!=(list_iterator const &rhs) const { return this->_node != rhs._node; } Self operator++(int) { Self tmp = *this; this->operator++(); return tmp; } Self &operator++() { _node = _node->next; return *this; } Self operator--(int) { Self tmp = *this; this->operator--(); return tmp; } Self &operator--() { _node = _node->prev; return *this; } }; template<typename T> class list_const_iterator { private: typedef list_const_iterator<T> Self; typedef ListNode<T> Node; typedef list_iterator<T> iterator; Node *_node; public: typedef std::ptrdiff_t difference_type; typedef const T value_type; typedef const T *pointer; typedef const T &reference; typedef ft::bidirectional_iterator_tag iterator_category; explicit list_const_iterator(Node *node = 0) : _node(node) {} ~list_const_iterator() {} list_const_iterator(iterator const &other) : _node(other._node) {} list_const_iterator &operator=(list_const_iterator const &other) { _node(other._node); return (*this); } Node getNode() { return _node; } reference operator*() const { return _node->data; } pointer operator->() const { return &(_node->data); } bool operator==(list_const_iterator const &rhs) { return this->_node == rhs._node; } bool operator!=(list_const_iterator const &rhs) { return this->_node != rhs._node; } Self operator++(int) { Self tmp = *this; this->operator++(); return tmp; } Self &operator++() { _node = _node->next; return *this; } Self operator--(int) { Self tmp = *this; this->operator--(); return tmp; } Self &operator--() { _node = _node->prev; return *this; } }; template<typename T> struct ListNode { typedef T value_type; ListNode() : data(0), next(0), prev(0) {} explicit ListNode(T const &a, ListNode<T> *next = 0, ListNode<T> *prev = 0) : data(a), next(next), prev(prev) {} ListNode(const ListNode<T> &other) : data(other.data), next(other.next), prev(other.prev) {} ListNode<T> &operator=(const ListNode<T> &other) { if (this != &other) { data = other.data; next = other.next; prev = other.prev; } return *this; } ~ListNode() {} value_type data; ListNode<T> *next; ListNode<T> *prev; }; template<typename T, typename Allocator = ft::allocator<T> > class list { public: typedef T value_type; typedef Allocator allocator_type; typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; typedef typename allocator_type::reference reference; typedef typename allocator_type::const_reference const_reference; typedef typename allocator_type::pointer pointer; typedef typename allocator_type::const_pointer const_pointer; typedef ft::list_iterator<T> iterator; typedef ft::list_const_iterator<T> const_iterator; typedef ft::reverse_iterator<iterator> reverse_iterator; typedef ft::reverse_iterator<const_iterator> const_reverse_iterator; explicit list(const allocator_type &alloc = allocator_type()) { (void) alloc; initBlankList_(); } explicit list(size_type n, const value_type &val = value_type(), const allocator_type &alloc = allocator_type()) { (void) alloc; initBlankList_(); insert(end(), n, val); } template<class InputIterator> list(InputIterator first, InputIterator last, const allocator_type &alloc = allocator_type()) { initBlankList_(alloc); insert(end(), first, last); } list(list const &x) { initBlankList_(); insert(end(), x.begin(), x.end()); } ~list() { clear(); deleteNode_(_root_node); } list &operator=(list const &x) { if (this != &x) { list(x).swap(*this); } return *this; } /* Iterators */ iterator begin() { return iterator(_root_node->next); } const_iterator begin() const { return const_iterator(_root_node->next); } iterator end() { return iterator(_root_node); } const_iterator end() const { return const_iterator(_root_node); } reverse_iterator rbegin() { return reverse_iterator(end()); } const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } reverse_iterator rend() { return reverse_iterator(begin()); } const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } /* Capacity */ bool empty() const { return _root_node == _root_node->next; } size_type size() const { node_pointer ptr = _root_node->next; size_type i = 0; while (ptr != _root_node) { ++i; ptr = ptr->next; } return i; } size_type max_size() const { return allocator_.max_size(); } /* Element access */ reference front() { return _root_node->next->data; } const_reference front() const { return _root_node->next->data; } reference back() { return _root_node->prev->data; } const_reference back() const { return _root_node->prev->data; } /* Modifiers */ template<class InputIterator> void assign(InputIterator first, InputIterator last) { clear(); insert(end(), first, last); } void assign(size_type n, const value_type &val) { clear(); insert(end(), n, val); } void push_front(const_reference val) { insert(begin(), val); } void pop_front() { erase(begin()); } void push_back(const_reference val) { insert(end(), val); } void pop_back() { erase(--end()); } iterator insert(iterator position, const value_type &val) { node_pointer pos = position.getNode(); node_pointer newNode = createNode_(val, pos->prev, pos); pos->prev->next = newNode; pos->prev = newNode; return iterator(newNode); } void insert(iterator position, size_type n, const value_type &val) { for (size_type i = 0; i < n; ++i) { insert(position, val); } } template<class InputIterator> void insert(iterator position, InputIterator first, InputIterator last) { for (; first != last; ++first) { insert(position, *first); } } iterator erase(iterator pos) { if (pos == end()) return (pos); node_pointer node = pos.getNode(); ++pos; node->prev->next = node->next; node->next->prev = node->prev; deleteNode_(node); return pos; } iterator erase(iterator first, iterator last) { while (first != last) { iterator tmp = first++; erase(tmp); } return first; } void swap(list &x) { node_pointer tmp_node = _root_node; node_allocator tmp_allocator = allocator_; _root_node = x._root_node; allocator_ = x.allocator_; x._root_node = tmp_node; x.allocator_ = tmp_allocator; } void resize(size_type n, value_type val = value_type()) { if (n < size()) { iterator itBegin = begin(); ft::advance(itBegin, n); erase(itBegin, end()); } else { insert(end(), n - size(), val); } } void clear() { erase(begin(), end()); } /* Operations */ void splice(iterator position, list &x) { splice(position, x, x.begin(), x.end()); } void splice(iterator position, list &x, iterator i) { splice(position, x, i, ++i); } void splice(iterator position, list &x, iterator first, iterator last) { if (first == x.end()) return; node_pointer pos = position.getNode(); node_pointer first_node = first.getNode(); node_pointer last_node = last.getNode()->prev; x.detachNodes_(first, last); pos->prev->next = first_node; first_node->prev = pos->prev; pos->prev = last_node; last_node->next = pos; } void remove(const value_type &val) { iterator itBegin = begin(); iterator itEnd = end(); while (itBegin != itEnd) { if (val == *itBegin) { iterator tmp = itBegin++; erase(tmp); } else { ++itBegin; } } } template<class Predicate> void remove_if(Predicate pred) { iterator itBegin = begin(); iterator itEnd = end(); while (itBegin != itEnd) { if (pred(*itBegin)) { iterator tmp = itBegin++; erase(tmp); } else { ++itBegin; } } } template<class BinaryPredicate> void unique(BinaryPredicate binary_pred) { iterator itBegin = begin(); iterator itEnd = end(); while (itBegin != itEnd) { iterator tmp = itBegin; ++itBegin; if (binary_pred(*tmp, *itBegin)) erase(tmp); } } void unique() { unique(ft::equal_to<T>()); } void merge(list &x) { merge(x, ft::less<T>()); } template<class Compare> void merge(list &x, Compare comp) { if (x.empty()) return; iterator it1 = begin(); iterator it2 = x.begin(); iterator mergedList(this->end()); x.detachNodes_(x.begin(), x.end()); while (it1 != this->end() && it2 != x.end()) { if (comp(*it1, *it2)) { insertAfter_(mergedList, it1); ++it1; } else { insertAfter_(mergedList, it2); ++it2; } ++mergedList; } while (it1 != this->end()) { insertAfter_(mergedList, it1); ++it1; ++mergedList; } while (it2 != x.end()) { insertAfter_(mergedList, it2); ++it2; ++mergedList; } insertAfter_(mergedList, end()); } template<class Compare> void sort(Compare comp) { _root_node->next = sortList_(_root_node->next, comp); node_pointer begin = _root_node->next; node_pointer prev; while (begin != _root_node) { prev = begin; begin = begin->next; } _root_node->prev = prev; } void sort() { sort(ft::less<T>()); } void reverse() { node_pointer prev = _root_node; node_pointer curr = _root_node->next; node_pointer next = curr->next; while (next != _root_node) { curr->next = prev; prev->prev = curr; prev = curr; curr = next; next = curr->next; } curr->next = prev; prev->prev = curr; _root_node->next = curr; curr->prev = _root_node; } private: typedef ListNode<value_type> node_type; typedef typename allocator_type::template rebind<node_type>::other node_allocator; typedef node_type *node_pointer; template<class Compare> node_pointer sortList_(node_pointer head, Compare comp) { if (head == _root_node || head->next == _root_node) { return head; } node_pointer second = halveList_(head); head = sortList_(head, comp); second = sortList_(second, comp); return mergeLists_(head, second, comp); } template<class Compare> node_pointer mergeLists_(node_pointer a, node_pointer b, Compare comp) { if (a == _root_node) return b; if (b == _root_node) return a; if (comp(a->data, b->data)) { a->next = mergeLists_(a->next, b, comp); a->next->prev = a; a->prev = _root_node; return a; } else { b->next = mergeLists_(a, b->next, comp); b->next->prev = b; b->prev = _root_node; return b; } } node_pointer halveList_(node_pointer list) { node_pointer first = list; node_pointer second = list; while (first->next != _root_node && second->next->next != _root_node) { first = first->next->next; second = second->next; } node_pointer result = second->next; second->next = _root_node; return result; } node_pointer createNode_(const_reference data, node_pointer prev = 0, node_pointer next = 0) { node_pointer newNode = allocator_.allocate(1); allocator_.construct(newNode, node_type(data)); newNode->prev = prev; newNode->next = next; return newNode; } void deleteNode_(node_pointer node) { allocator_.destroy(node); allocator_.deallocate(node, 1); } void detachNodes_(iterator first, iterator last) { node_pointer first_node = first.getNode(); node_pointer last_node = last.getNode(); last_node->prev = first_node->prev; first_node->prev->next = last_node; } bool _isEqual(iterator x, iterator y) { return x == y; } /** * @brief Initialization blank list container. Needed to avoid duplication */ void initBlankList_() { _root_node = createNode_(0); _root_node->next = _root_node; _root_node->prev = _root_node; } void insertAfter_(iterator pos, iterator val) { node_pointer posNode = pos.getNode(); node_pointer valNode = val.getNode(); posNode->next = valNode; valNode->prev = posNode; } node_pointer _root_node; node_allocator allocator_; }; template<class T, class Alloc> bool operator==(const ft::list<T, Alloc> &lhs, const ft::list<T, Alloc> &rhs) { typename ft::list<T>::const_iterator lBegin = lhs.begin(); typename ft::list<T>::const_iterator lEnd = lhs.end(); typename ft::list<T>::const_iterator rBegin = rhs.begin(); typename ft::list<T>::const_iterator rEnd = rhs.end(); while (lBegin != lEnd && rBegin != rEnd) { if (*lBegin != *rBegin) return false; ++lBegin; ++rBegin; } return (lBegin == lEnd && rBegin == rEnd); } template<class T, class Alloc> bool operator!=(const ft::list<T, Alloc> &lhs, const ft::list<T, Alloc> &rhs) { return !(lhs == rhs); } template<class T, class Alloc> bool operator<(const ft::list<T, Alloc> &lhs, const ft::list<T, Alloc> &rhs) { typename ft::list<T>::const_iterator lBegin = lhs.begin(); typename ft::list<T>::const_iterator lEnd = lhs.end(); typename ft::list<T>::const_iterator rBegin = rhs.begin(); typename ft::list<T>::const_iterator rEnd = rhs.end(); while (lBegin != lEnd && rBegin != rEnd) { if (*lBegin < *rBegin) return true; ++lBegin; ++rBegin; } return (lBegin == lEnd && rBegin != rEnd); } template<class T, class Alloc> bool operator<=(const ft::list<T, Alloc> &lhs, const ft::list<T, Alloc> &rhs) { return (lhs < rhs || lhs == rhs); } template<class T, class Alloc> bool operator>(const ft::list<T, Alloc> &lhs, const ft::list<T, Alloc> &rhs) { return !(lhs <= rhs); } template<class T, class Alloc> bool operator>=(const ft::list<T, Alloc> &lhs, const ft::list<T, Alloc> &rhs) { return !(lhs < rhs); } } #endif //FT_CONTAINERS_LIST_HPP
true
692ff60dfe608a57a1ccba0b989a0f8045fd6790
C++
codeserfer/2-term
/forum4/forum4/TheMatrix.h
UTF-8
424
2.796875
3
[]
no_license
#pragma once class TheMatrix { int** array; int N, M; public: TheMatrix(void); TheMatrix(int N, int M); ~TheMatrix(void); void show(); void fillMatrix(); void getMemory(int, int); TheMatrix& operator*(const int num); friend TheMatrix& operator*(const TheMatrix& A, const TheMatrix& B); friend TheMatrix& operator+(const TheMatrix& A, const TheMatrix& B); TheMatrix& operator=(const TheMatrix&); };
true
0a70ac56403176a1e750382c13899f98dcccc789
C++
marco-c/gecko-dev-comments-removed
/gfx/harfbuzz/src/hb-object.hh
UTF-8
6,867
2.75
3
[ "LicenseRef-scancode-other-permissive", "MIT-Modern-Variant", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#ifndef HB_OBJECT_HH #define HB_OBJECT_HH #include "hb.hh" #include "hb-atomic.hh" #include "hb-mutex.hh" #include "hb-vector.hh" template <typename item_t, typename lock_t> struct hb_lockable_set_t { hb_vector_t<item_t> items; void init () { items.init (); } template <typename T> item_t *replace_or_insert (T v, lock_t &l, bool replace) { l.lock (); item_t *item = items.lsearch (v); if (item) { if (replace) { item_t old = *item; *item = v; l.unlock (); old.fini (); } else { item = nullptr; l.unlock (); } } else { item = items.push (v); l.unlock (); } return items.in_error () ? nullptr : item; } template <typename T> void remove (T v, lock_t &l) { l.lock (); item_t *item = items.lsearch (v); if (item) { item_t old = *item; *item = std::move (items.tail ()); items.pop (); l.unlock (); old.fini (); } else { l.unlock (); } } template <typename T> bool find (T v, item_t *i, lock_t &l) { l.lock (); item_t *item = items.lsearch (v); if (item) *i = *item; l.unlock (); return !!item; } template <typename T> item_t *find_or_insert (T v, lock_t &l) { l.lock (); item_t *item = items.find (v); if (!item) { item = items.push (v); } l.unlock (); return item; } void fini (lock_t &l) { if (!items.length) { items.fini (); return; } l.lock (); while (items.length) { item_t old = items.tail (); items.pop (); l.unlock (); old.fini (); l.lock (); } items.fini (); l.unlock (); } }; struct hb_reference_count_t { mutable hb_atomic_int_t ref_count; void init (int v = 1) { ref_count = v; } int get_relaxed () const { return ref_count; } int inc () const { return ref_count.inc (); } int dec () const { return ref_count.dec (); } void fini () { ref_count = -0x0000DEAD; } bool is_inert () const { return !ref_count; } bool is_valid () const { return ref_count > 0; } }; struct hb_user_data_array_t { struct hb_user_data_item_t { hb_user_data_key_t *key; void *data; hb_destroy_func_t destroy; bool operator == (const hb_user_data_key_t *other_key) const { return key == other_key; } bool operator == (const hb_user_data_item_t &other) const { return key == other.key; } void fini () { if (destroy) destroy (data); } }; hb_mutex_t lock; hb_lockable_set_t<hb_user_data_item_t, hb_mutex_t> items; void init () { lock.init (); items.init (); } void fini () { items.fini (lock); lock.fini (); } bool set (hb_user_data_key_t *key, void * data, hb_destroy_func_t destroy, hb_bool_t replace) { if (!key) return false; if (replace) { if (!data && !destroy) { items.remove (key, lock); return true; } } hb_user_data_item_t item = {key, data, destroy}; bool ret = !!items.replace_or_insert (item, lock, (bool) replace); return ret; } void *get (hb_user_data_key_t *key) { hb_user_data_item_t item = {nullptr, nullptr, nullptr}; return items.find (key, &item, lock) ? item.data : nullptr; } }; struct hb_object_header_t { hb_reference_count_t ref_count; mutable hb_atomic_int_t writable = 0; hb_atomic_ptr_t<hb_user_data_array_t> user_data; bool is_inert () const { return !ref_count.get_relaxed (); } }; #define HB_OBJECT_HEADER_STATIC {} template <typename Type> static inline void hb_object_trace (const Type *obj, const char *function) { DEBUG_MSG (OBJECT, (void *) obj, "%s refcount=%d", function, obj ? obj->header.ref_count.get_relaxed () : 0); } template <typename Type, typename ...Ts> static inline Type *hb_object_create (Ts... ds) { Type *obj = (Type *) hb_calloc (1, sizeof (Type)); if (unlikely (!obj)) return obj; new (obj) Type (std::forward<Ts> (ds)...); hb_object_init (obj); hb_object_trace (obj, HB_FUNC); return obj; } template <typename Type> static inline void hb_object_init (Type *obj) { obj->header.ref_count.init (); obj->header.writable = true; obj->header.user_data.init (); } template <typename Type> static inline bool hb_object_is_valid (const Type *obj) { return likely (obj->header.ref_count.is_valid ()); } template <typename Type> static inline bool hb_object_is_immutable (const Type *obj) { return !obj->header.writable; } template <typename Type> static inline void hb_object_make_immutable (const Type *obj) { obj->header.writable = false; } template <typename Type> static inline Type *hb_object_reference (Type *obj) { hb_object_trace (obj, HB_FUNC); if (unlikely (!obj || obj->header.is_inert ())) return obj; assert (hb_object_is_valid (obj)); obj->header.ref_count.inc (); return obj; } template <typename Type> static inline bool hb_object_destroy (Type *obj) { hb_object_trace (obj, HB_FUNC); if (unlikely (!obj || obj->header.is_inert ())) return false; assert (hb_object_is_valid (obj)); if (obj->header.ref_count.dec () != 1) return false; hb_object_fini (obj); if (!std::is_trivially_destructible<Type>::value) obj->~Type (); return true; } template <typename Type> static inline void hb_object_fini (Type *obj) { obj->header.ref_count.fini (); hb_user_data_array_t *user_data = obj->header.user_data.get_acquire (); if (user_data) { user_data->fini (); hb_free (user_data); obj->header.user_data.set_relaxed (nullptr); } } template <typename Type> static inline bool hb_object_set_user_data (Type *obj, hb_user_data_key_t *key, void * data, hb_destroy_func_t destroy, hb_bool_t replace) { if (unlikely (!obj || obj->header.is_inert ())) return false; assert (hb_object_is_valid (obj)); retry: hb_user_data_array_t *user_data = obj->header.user_data.get_acquire (); if (unlikely (!user_data)) { user_data = (hb_user_data_array_t *) hb_calloc (sizeof (hb_user_data_array_t), 1); if (unlikely (!user_data)) return false; user_data->init (); if (unlikely (!obj->header.user_data.cmpexch (nullptr, user_data))) { user_data->fini (); hb_free (user_data); goto retry; } } return user_data->set (key, data, destroy, replace); } template <typename Type> static inline void *hb_object_get_user_data (Type *obj, hb_user_data_key_t *key) { if (unlikely (!obj || obj->header.is_inert ())) return nullptr; assert (hb_object_is_valid (obj)); hb_user_data_array_t *user_data = obj->header.user_data.get_acquire (); if (!user_data) return nullptr; return user_data->get (key); } #endif
true
fec68c1afe09f7b2b1aa433e4a297ef250211dc5
C++
fenix0111/Algorithm
/Leetcode/646. Maximum Length of Pair Chain/maximum_length_of_pair_chain_dp.cpp
UTF-8
832
3.15625
3
[]
no_license
// Leetcode 646. Maximum Length of Pair Chain // https://leetcode.com/problems/maximum-length-of-pair-chain/ // time complexity: O(N^2) // space complexity: O(N) class Solution { public: int findLongestChain(vector<vector<int>>& pairs) { sort(pairs.begin(), pairs.end(), [](vector<int>& x, vector<int>& y) { return x[0] < y[0]; }); int sz = pairs.size(); vector<int> dp(sz, 1); int result = 1; for (int i = sz - 1; i >= 0; i--) { for (int j = i + 1; j < sz; j++) { if (pairs[i][1] < pairs[j][0]) { dp[i] = max(dp[i], dp[j] + 1); result = max(dp[i], result); } } } return result; } };
true
e3e5faeb7c0680353856775a79a5864fbd3f805a
C++
namanworld/Codechef-Solutions-Competitive-Programming
/Penalty Shoot-Out || (PSHOT).cpp
UTF-8
697
2.625
3
[]
no_license
#include <bits/stdc++.h> #define int long long #define MOD 1000000007 #define INF 100000000000000 using namespace std; int time(string s, int n){ int A_goals = 0, B_goals = 0; int rem_A = n/2, rem_B = n/2; for(int i=0; i<n; i++){ if((i&1) == 0) { A_goals+=s[i]-'0'; rem_A--; } else { B_goals+=s[i]-'0'; rem_B--; } if ((A_goals-B_goals>rem_B) || (B_goals-A_goals>rem_A)) return i+1; } return n; } signed main() { int t; cin>>t; while(t--){ int n; cin>>n; string s; cin>>s; cout<<time(s,2*n)<<endl; } return 0; }
true
32e39095db4f3da8c233d40f81f50cea25a82d85
C++
overnew/CodeSaving
/Dynamic Programming(동적 계획법)/[BaekJoon]_2494_숫자 맞추기.cpp
UTF-8
1,801
3.171875
3
[]
no_license
//https://www.acmicpc.net/problem/2494 #include<iostream> #include<string.h> #include<string> using namespace std; typedef struct state { int total_turn = -1; //전체 회전횟수 int turn = 0; //이번 나사에서의 회전 }State; State dp[10000][10]; //[숫자나사][현재의 수] char init[10000], dest[10000]; int screw_num; const int MOD = 10; int TurnScrew(int left_turned, int idx) { if (idx == screw_num) return 0; int num = init[idx] + left_turned; num %= MOD; int& ret = dp[idx][num].total_turn; if (ret != -1) return ret; int right; //오른쪽으로 돌려야하는 횟수 if (dest[idx] > num) right = num + 10 - dest[idx]; else right = num - dest[idx]; int left; //왼쪽으로 돌려야하는 횟수 if (dest[idx] >= num) left = dest[idx] - num; else left = dest[idx] + 10 - num; int left_num = TurnScrew((left_turned + left) % MOD, idx + 1) + left; int right_num = TurnScrew(left_turned, idx + 1) + right; if (left_num < right_num) { //더 조금 돌려도 되는 것이 최적해가 된다. ret = left_num; dp[idx][num].turn = left; } else { ret = right_num; dp[idx][num].turn = -right; } return ret; } int main() { ios_base::sync_with_stdio(0); cin >> screw_num; string init_state, dest_state; cin >> init_state >> dest_state; for (int i = 0; i < screw_num; ++i) { init[i] = init_state[i] - '0'; dest[i] = dest_state[i] - '0'; } cout << TurnScrew(0, 0) << '\n'; int idx = 0, num = init[0], total_left = 0; while (1) { //저장된 최적해를 역추적하자. cout << idx + 1 << ' ' << dp[idx][num].turn << '\n'; if (dp[idx][num].turn > 0) { total_left += dp[idx][num].turn; total_left %= MOD; } idx++; if (idx == screw_num) break; num = (init[idx] + total_left) % MOD; } return 0; }
true
8bf8bb62fa451e232b94e22bfd89178eb997e288
C++
denis-gubar/Leetcode
/Array/2552. Count Increasing Quadruplets.cpp
UTF-8
826
2.609375
3
[]
no_license
class Solution { public: long long countQuadruplets(vector<int>& nums) { long long result = 0; for (int& x : nums) --x; int N = nums.size(); vector<vector<int>> A(N + 1, vector<int>(N + 1)); vector<vector<int>> B(N + 1, vector<int>(N + 1)); for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) A[i][j] = (i > 0 ? A[i - 1][j] : 0) + (nums[i] <= j); for (int i = N - 1; i >= 0; --i) for (int j = 0; j < N; ++j) B[i][j] = (i < N - 1 ? B[i + 1][j] : 0) + (nums[i] >= j); for (int j = 1; j + 2 < N; ++j) for (int k = j + 1; k + 1 < N; ++k) if (nums[j] > nums[k]) result += A[j - 1][nums[k]] * B[k + 1][nums[j]]; return result; } };
true
cfb312332e846b1b6f83709e604aacfb19c11896
C++
Woooosz/AlgorithmTrainSet
/PAT-Advanced/1051. Pop Sequence (25).cpp
UTF-8
682
2.53125
3
[]
no_license
#include <iostream> #include <vector> #include <stack> using namespace std; int main() { int n, m, k; scanf("%d %d %d", &m, &n, &k); for(int i = 0; i < k; ++i) { stack<int> s; vector<int> d(n); for(int j = 0; j < n; ++j) scanf("%d", &d[j]); bool ans = false; int current = 0; for(int j = 1; j <= n; ++j) { s.push(j); if(s.size() > m) break; while(!s.empty() && d[current] == s.top()) { s.pop(); ++current; } } if(current == n) ans = true; if(ans) printf("YES\n"); else printf("NO\n"); } }
true
fee4d9014facf7a76c94d1b7920ce47795241198
C++
rohitopal23/SDE-sheet
/Heap/Reorganize String.cpp
UTF-8
1,366
2.8125
3
[]
no_license
class Solution { public: string reorganizeString(string S) { string ans; priority_queue<pair<int,int>> pq; map<char,int>mp; for(char ch:S){ mp[ch]++; } for(char ch='a'; ch<='z'; ch++){ if(mp[ch]>0){ pq.push(make_pair(mp[ch], ch)); } } while(!pq.empty()){ char last = (ans.empty())?' ':ans.back(); if(pq.top().second == last){ pair<int,int>tmp = pq.top(); pq.pop(); if(pq.empty()){ return ""; }else{ pair<int,int>p = pq.top(); pq.pop(); ans.push_back(p.second); if(p.first != 1){ p.first--; pq.push(p); } } pq.push(tmp); }else{ pair<int,int>p = pq.top(); pq.pop(); ans.push_back(p.second); if(p.first != 1){ p.first--; pq.push(p); } } } return ans; } };
true
1ec41b9c8384e4322b67ef4d26ad6086f3a34392
C++
wonny-Jo/algorithm
/알고리즘 정리/그래프/문제풀이/가장 먼 노드.cpp
UTF-8
1,200
2.71875
3
[]
no_license
#include<iostream> #include <string> #include <vector> #include <queue> using namespace std; int maxNum = 0; int dist_num[20001] = { 0 }; bool visited[20001] = { 0 }; void bfs(vector<int> vertex[20001]) { queue<pair<int,int>> q; q.push({ 1,0 }); while(!q.empty()) { int x = q.front().first; int dist = q.front().second; q.pop(); dist_num[dist]++; for (int i = 0; i < vertex[x].size(); i++) { int y = vertex[x][i]; if (y != 1 && !visited[y]) { visited[y] = true; q.push({ y,dist + 1 }); } } maxNum = dist; } } int solution(int n, vector<vector<int>> edge) { vector<int> vertex[20001]; for (int i = 0; i < edge.size(); i++) { vertex[edge[i][0]].push_back(edge[i][1]); vertex[edge[i][1]].push_back(edge[i][0]); } bfs(vertex); return dist_num[maxNum]; } int main() { cin.sync_with_stdio(0); cin.tie(0); cout.tie(0); cout << solution(6, { {3, 6},{4, 3},{3, 2},{1, 3},{1, 2},{2, 4},{5, 2} }); return 0; }
true
f78bb57e3d9b3d1e23d50fa11749674a3e884b94
C++
DSPNerd/m-nebula
/code/src/misc/noctree_collect.cc
UTF-8
19,021
2.515625
3
[]
no_license
#define N_IMPLEMENTS nOctree //------------------------------------------------------------------- // noctree_collect.cc // (C) 1999 A.Weissflog //------------------------------------------------------------------- #include "kernel/nkernelserver.h" #include "kernel/nenv.h" #include "misc/noctree.h" #include "gfx/ngfxserver.h" //------------------------------------------------------------------- /** Determines the view volume clip status for the bounding box: Return: - <0 -> entirely out - ==0 -> partly in/out - >0 -> entirely in this->vp_matrix must be up-to-date... - 02-Jun-99 floh created */ //------------------------------------------------------------------- int nOctree::box_clip_viewvol(vector3& p0, vector3& p1) { int i, and_flags, or_flags; vector4 v0,v1; // for each of the 8 bounding box corners... and_flags = 0xffff; or_flags = 0; for (i=0; i<8; i++) { int clip = 0; v0.w = 1.0; if (i & 1) v0.x = p0.x; else v0.x = p1.x; if (i & 2) v0.y = p0.y; else v0.y = p1.y; if (i & 4) v0.z = p0.z; else v0.z = p1.z; // transform current corner to clip coordinate v1 = this->vp_matrix * v0; // Get clip flags... if (v1.x < -v1.w) clip |= N_OCT_CLIPX0; else if (v1.x > v1.w) clip |= N_OCT_CLIPX1; if (v1.y < -v1.w) clip |= N_OCT_CLIPY0; else if (v1.y > v1.w) clip |= N_OCT_CLIPY1; if (v1.z < -v1.w) clip |= N_OCT_CLIPZ0; else if (v1.z > v1.w) clip |= N_OCT_CLIPZ1; and_flags &= clip; or_flags |= clip; } if (0 == or_flags) return +1; // ENTIRELY IN else if (0 != and_flags) return -1; // ENTIRELY OUT else return 0; // PARTLY IN/OUT } //------------------------------------------------------------------- /** Get clipping status of node bounding box against global collection bounding box. Return: - +1 - node box completely containd in collection box - -1 - node box completely outside of collection box - 0 - node box partially inside collection box, or collection box is contained in node box - 02-Jun-00 floh created */ //------------------------------------------------------------------- int nOctree::box_clip_box(vector3& p0, vector3& p1) { bbox3 b(p0,p1); int res = b.intersect(this->collect_bbox); if (bbox3::OUTSIDE == res) { return -1; } else if (bbox3::ISCONTAINED == res) { return +1; } else { return 0; } } //------------------------------------------------------------------- /** Collects an element and ensures that collect_array doesn't overflow. - 02-Jun-99 floh created */ //------------------------------------------------------------------- void nOctree::collect(nOctElement *oe) { if (this->num_collected < this->ext_array_size) { this->ext_collect_array[this->num_collected++] = oe; } else { n_printf("nOctree::collect(): Overflow in collect array!\n"); } } //------------------------------------------------------------------- /** Trivially collects all elements of the specified node and recursively searches its child nodes. - 02-Jun-99 floh created */ //------------------------------------------------------------------- void nOctree::recurse_collect_nodes_with_flags(nOctNode *on, int c_flags) { nOctElement *oe; for (oe = (nOctElement *) on->elm_list.GetHead(); oe; oe = (nOctElement *) oe->GetSucc()) { oe->SetCollectFlags(c_flags); this->collect(oe); } if (on->c[0]) { int i; for (i=0; i<8; i++) this->recurse_collect_nodes_with_flags(on->c[i],c_flags); } } //------------------------------------------------------------------- /** Does a visibility test on each element in the node and collects it if it is visible. To check visibility, this->vp_matrix must be up-to-date! - 02-Jun-99 floh created */ //------------------------------------------------------------------- void nOctree::collect_nodes_in_viewvol(nOctNode *on) { nOctElement *oe; for (oe = (nOctElement *) on->elm_list.GetHead(); oe; oe = (nOctElement *) oe->GetSucc()) { int c = this->box_clip_viewvol(oe->p0,oe->p1); if (c >= 0) { oe->SetCollectFlags(nOctElement::N_COLLECT_VIEWVOL); this->collect(oe); } } } //------------------------------------------------------------------- /** Low level version of CollectByViewvol(), recurses as far into the tree as needed. - 02-Jun-99 floh created */ //------------------------------------------------------------------- void nOctree::recurse_collect_by_viewvol(nOctNode *on) { // Clip status of the current node... int c = this->box_clip_viewvol(on->p0,on->p1); if (c > 0) { // Node is entirely contained, all elements of // the node and all of its children can be // trivially collected... this->recurse_collect_nodes_with_flags(on,nOctElement::N_COLLECT_VIEWVOL); } else if (c == 0) { // Node is partly inside the view volume. A bounding box // check is done on all elements of the node before they // get collected. recurse_collectbyview() is applied to // all child nodes. this->collect_nodes_in_viewvol(on); if (on->c[0]) { int i; for (i=0; i<8; i++) this->recurse_collect_by_viewvol(on->c[i]); } } } //------------------------------------------------------------------- /** - 30-May-00 floh created */ //------------------------------------------------------------------- void nOctree::collect_nodes_in_viewvol_or_bbox(nOctNode *on) { nOctElement *oe; for (oe = (nOctElement *) on->elm_list.GetHead(); oe; oe = (nOctElement *) oe->GetSucc()) { int vvol_c = this->box_clip_viewvol(oe->p0,oe->p1); int bbox_c = this->box_clip_box(oe->p0,oe->p1); int c_flags = 0; if (vvol_c >= 0) c_flags |= nOctElement::N_COLLECT_VIEWVOL; if (bbox_c >= 0) c_flags |= nOctElement::N_COLLECT_BBOX; if (c_flags != 0) { oe->SetCollectFlags(c_flags); this->collect(oe); } } } //------------------------------------------------------------------- /** - 30-May-00 floh created */ //------------------------------------------------------------------- void nOctree::recurse_collect_by_viewvol_or_bbox(nOctNode *on) { // clip status of current node int vvol_c = this->box_clip_viewvol(on->p0,on->p1); int bbox_c = this->box_clip_box(on->p0,on->p1); if ((vvol_c > 0) && (bbox_c > 0)) { // node is contained both in view volume and in bounding // box, trivially accept all sub-nodes this->recurse_collect_nodes_with_flags(on,(nOctElement::N_COLLECT_VIEWVOL|nOctElement::N_COLLECT_BBOX)); } else if ((vvol_c > 0) && (bbox_c < 0)) { // node is contained in view volume and completely outside // bounding box, trivially accept all view volume sub nodes this->recurse_collect_nodes_with_flags(on,nOctElement::N_COLLECT_VIEWVOL); } else if ((vvol_c < 0) && (bbox_c > 0)) { // node is contained in bounding box and completely outside // view volume, trivially accept all bounding box sub nodes this->recurse_collect_nodes_with_flags(on,nOctElement::N_COLLECT_BBOX); } else if ((vvol_c < 0) && (bbox_c < 0)) { // node is outside of both volumes } else { // look at each element and recurse down further... this->collect_nodes_in_viewvol_or_bbox(on); if (on->c[0]) { int i; for (i=0; i<8; i++) this->recurse_collect_by_viewvol_or_bbox(on->c[i]); } } } //------------------------------------------------------------------- /** - 17-Aug-00 floh created */ //------------------------------------------------------------------- void nOctree::collect_nodes_in_bbox(nOctNode *on) { nOctElement *oe; for (oe = (nOctElement *) on->elm_list.GetHead(); oe; oe = (nOctElement *) oe->GetSucc()) { int c = this->box_clip_box(oe->p0,oe->p1); if (c >= 0) { oe->SetCollectFlags(nOctElement::N_COLLECT_BBOX); this->collect(oe); } } } //------------------------------------------------------------------- /** - 17-Aug-00 floh created */ //------------------------------------------------------------------- void nOctree::recurse_collect_by_bbox(nOctNode *on) { // clip status of current node int bbox_c = this->box_clip_box(on->p0,on->p1); if (bbox_c > 0) { // node is contained completely inside the // collection box, trivially accept all child nodes this->recurse_collect_nodes_with_flags(on,nOctElement::N_COLLECT_BBOX); } else if (bbox_c == 0) { // node is partly contained in box, all elements in // the node need to be checked further, and recurse // to children this->collect_nodes_in_bbox(on); if (on->c[0]) { int i; for (i=0; i<8; i++) this->recurse_collect_by_bbox(on->c[i]); } } } //------------------------------------------------------------------- /** @brief Collect the nodes that are within the view volume. Collects the elements contained in the current view volume. Requires the current modelview matrix as well as the current projection matrix. Global coordinates in the octree are passed through the modelview and projection matrices, resulting in 4D clip coordinates. The clip volume is defined by - -w <= x <= w - -w <= y <= w - -w <= z <= w Note that it may be preferable to use the newer methods that use clipping planes, such as CollectByFrustum(), as performance should be improved. - 02-Jun-99 floh created - 18-Aug-00 floh now fills externally provided element array */ //------------------------------------------------------------------- int nOctree::CollectByViewvol(matrix44& mv, matrix44& p, nOctElement **ext_array, int size) { n_assert(ext_array); n_assert(NULL == ext_collect_array); this->vp_matrix = mv * p; this->num_collected = 0; this->ext_collect_array = ext_array; this->ext_array_size = size; this->recurse_collect_by_viewvol(this->tree_root); this->ext_collect_array = 0; this->ext_array_size = 0; return this->num_collected; } //------------------------------------------------------------------- /** @brief Collect all nodes that are either in the view volume and/or a bounding bbox. - 30-May-00 floh created */ //------------------------------------------------------------------- int nOctree::CollectByViewvolOrBBox(matrix44& mv, matrix44& p, bbox3& bbox, nOctElement **ext_array, int size) { n_assert(ext_array); n_assert(NULL == ext_collect_array); this->vp_matrix = mv * p; this->collect_bbox = bbox; this->num_collected = 0; this->ext_collect_array = ext_array; this->ext_array_size = size; this->recurse_collect_by_viewvol_or_bbox(this->tree_root); this->ext_collect_array = 0; this->ext_array_size = 0; return this->num_collected; } //------------------------------------------------------------------- /** @brief Collect all nodes touching given bounding box. - 17-Aug-00 floh created */ //------------------------------------------------------------------- int nOctree::CollectByBBox(bbox3& bbox, nOctElement **ext_array, int size) { n_assert(ext_array); n_assert(NULL == ext_collect_array); this->collect_bbox = bbox; this->num_collected = 0; this->ext_collect_array = ext_array; this->ext_array_size = size; this->recurse_collect_by_bbox(this->tree_root); this->ext_collect_array = 0; this->ext_array_size = 0; return this->num_collected; } /** @brief Collect all nodes bounded by view frustum Assume symmetrical frustum. Uses a clip mask to minimize checks. Hardcoded to only derive clip planes from frustum but no reason why it cannot be extended to use additional clip planes, up to a total max of 32. */ int nOctree::CollectByFrustum(nGfxServer* gfx_server, nOctElement** ext_array, int size) { n_assert(ext_array); n_assert(NULL == ext_collect_array); init_clip_planes_for_frustum(gfx_server); this->num_collected = 0; this->ext_collect_array = ext_array; this->ext_array_size = size; unsigned int active_clips = 0x003F; recurse_collect_within_clip_planes(this->tree_root, active_clips); this->ext_collect_array = 0; this->ext_array_size = 0; return num_collected; } /** Initialize the clip planes for view frustum collection. */ void nOctree::init_clip_planes_for_frustum(nGfxServer* gfx_server) { float minx, maxx, miny, maxy, minz, maxz; gfx_server->GetViewVolume(minx, maxx, miny, maxy, minz, maxz); // The setup of the planes here are a bit mucky: // 0 - front // 1 - back // 2 - left // 3 - right // 4 - top // 5 - bottom float angle_h = n_atan(maxx / minz); float cos_h = n_cos(angle_h); float sin_h = n_sin(angle_h); float angle_v = n_atan(maxy / minz); float cos_v = n_cos(angle_v); float sin_v = n_sin(angle_v); // D = - dot(p.normal, point_in_plane) clipPlanes[0].set(0.0f, 0.0f, -1.0f, 0.0f); clipPlanes[0].w = -( -1.0f * -minz); clipPlanes[1].set(0.0f, 0.0f, 1.0f, 0.0f); clipPlanes[1].w = -( 1.0f * -maxz); clipPlanes[2].set(cos_h, 0.0f, -sin_h, 0.0f); clipPlanes[3].set(-cos_h, 0.0f, -sin_h, 0.0f); clipPlanes[4].set(0.0f, -cos_v, -sin_v, 0.0f); clipPlanes[5].set(0.0f, cos_v, -sin_v, 0.0f); // Transform clip planes by current camera angle // Plane normals are transformed by the transpose of the inverse // matrix for transforming points. Just transpose since mv is // already inverted matrix44 inv_viewer; gfx_server->GetMatrix(N_MXM_INVVIEWER, inv_viewer); inv_viewer.transpose(); // Would have used plane but vector4 can be transformed for (int i = 0; i < 6; ++i) clipPlanes[i] = inv_viewer * clipPlanes[i]; } /** @brief Recursively collect within the clip planes. */ void nOctree::recurse_collect_within_clip_planes(nOctNode* on, unsigned int clip_mask) { unsigned int out_clip_mask; // Clip-Status der aktuellen Node... if (false == box_clip_against_clip_planes(on->p0, on->p1, clipPlanes, out_clip_mask, clip_mask)) return; // Node completely contained, gotta catch them all! if (0 == out_clip_mask) { recurse_collect_nodes_with_flags(on, nOctElement::N_COLLECT_CLIP_PLANES); } // Partially clipped by clip planes, future doodah could do // with passing in clip mask to reduce number of checks recursively else { this->collect_nodes_within_clip_planes(on, out_clip_mask); if (on->c[0]) { for (int i = 0; i < 8; ++i) this->recurse_collect_within_clip_planes(on->c[i], out_clip_mask); } } } /** @brief Collect nodes in this node only. */ void nOctree::collect_nodes_within_clip_planes(nOctNode* on, unsigned int clip_mask) { nOctElement *oe; for (oe = (nOctElement *) on->elm_list.GetHead(); oe; oe = (nOctElement *) oe->GetSucc()) { unsigned int out_clip_mask = 0; if (true == box_clip_against_clip_planes(oe->p0,oe->p1, clipPlanes, out_clip_mask, clip_mask)) { oe->SetCollectFlags(nOctElement::N_COLLECT_CLIP_PLANES); this->collect(oe); } } } /** Clip AABB defined by p0, p1 to supplied planes. This code is derived from code provided by Ville Miettinen of Hybrid.fi on the Algorithms mailing list. It is similar to the code that Hybrid uses in their product dPVS (http://www.hybrid.fi/dpvs.html). @param p0 Lower corner of AABB @param p1 Upper corner of AABB @param planes the array of planes to clip against (up to 32) @param out_clip_mask returned clip plane overlap @param in_clip_mask planes to clip against @return true if the AABB is at least partially inside clip */ bool nOctree::box_clip_against_clip_planes(vector3& p0, vector3& p1, vector4* planes, unsigned int& out_clip_mask, unsigned int in_clip_mask) { // Figure out centre and half diagonal of AABB vector3 centre = (p0 + p1) / 2.0f; vector3 half_diagonal = p1 - centre; unsigned int mk = 1; out_clip_mask = 0; // loop while there are active planes.. while (mk <= in_clip_mask) { if (in_clip_mask & mk) { float NP = float(half_diagonal.x * n_abs(planes->x) + half_diagonal.y * n_abs(planes->y) + half_diagonal.z * n_abs(planes->z)); float MP = centre.x * planes->x + centre.y * planes->y + centre.z * planes->z + planes->w; // Behind clip plane if ((MP + NP) < 0.0f) return false; // Cross this plane if ((MP - NP) < 0.0f) out_clip_mask |= mk; } mk <<= 1; ++planes; } // Contained in some way return true; } //------------------------------------------------------------------- // EOF //-------------------------------------------------------------------
true
963bb62e9b0188f3e6d9e26f60649f69742ad8d3
C++
jasonrohrer/Transcend
/game/MusicPart.h
UTF-8
2,844
2.6875
3
[]
no_license
/* * Modification History * * 2004-August-22 Jason Rohrer * Created. * * 2004-August-26 Jason Rohrer * Added parameter to control character of part. */ #ifndef MUSIC_PART_INCLUDED #define MUSIC_PART_INCLUDED #include "MusicNoteWaveTable.h" #include "minorGems/util/SimpleVector.h" #include "minorGems/util/random/RandomSource.h" /** * A sequence of music notes. * * @author Jason Rohrer */ class MusicPart { public: /** * Constructs a randomized part. * Reads configuration using the LevelDirectoryManager. * * @param inWaveTable the wave table to pick random notes from. * Must be destroyed by caller after this class is destroyed. * @param inRandSource the source for random numbers. * Must be destroyed by caller (can be destroyed after * this constructor returns). * @param inParameter parameter in the range [0,1] that controls * the character of this music part. */ MusicPart( MusicNoteWaveTable *inWaveTable, RandomSource *inRandSource, double inParameter ); ~MusicPart(); /** * Gets this part's length. * * @return the length in seconds. */ double getPartLengthInSeconds(); /** * Gets the notes that should start playing in a given time interval. * * Note that only notes that *start* in the interval are returned. * Notes that are playing during the interval, but that start before * the interval, are ignored. * * @param inStartTimeInSeconds the start of the interval * Must be in the range [ 0, getPartLengthInSeconds() ]. * @param inLengthInSeconds the length of the interval. * @param outNotes pointer to where an array of notes * should be returned. * The returned array and the notes must be destroyed by caller. * @param outNoteStartOffsetsInSeconds pointer to where an array of * note start offsets should be returned. * Offsets are in seconds beyond inStartTimeInSeconds. * The returned array must be destroyed by caller. * * @return the number of notes that start in the interval * (in other words, the length of the returned arrays). */ int getNotesStartingInInterval( double inStartTimeInSeconds, double inLengthInSeconds, MusicNote ***outNotes, double **outNoteStartOffsetsInSeconds ); protected: MusicNoteWaveTable *mWaveTable; SimpleVector<MusicNote *> *mNotes; double mPartLengthInSeconds; }; #endif
true
a02514c31b59a82628b48fdcf4dcd3bef327a1ce
C++
ahmedelsaie/AlgorithmsProblems
/UVA/825 - Walking on the Safe Side.cpp
UTF-8
2,525
2.984375
3
[]
no_license
#include <iostream> #include <cctype> #include <cstdlib> #include <sstream> #include <string> using namespace std; bool check(string in); void reset(); long long min(int row, int col); long long ways(int row, int col); string str; long long dp[105][105]; int map[105][105]; int main_row; int main_col; int main() { int cases; cin >> cases; for(int counter2 = 0; counter2 < cases; counter2++) { cin >> main_row >> main_col; reset(); for(int counter = 1; counter <= main_row;) { getline(cin, str, '\n'); if(check(str) == true) counter++; } if(min(1, 1) >= 100000000) cout << "0" << endl; else cout << ways(1, 1) << endl; if(counter2 < cases - 1) cout << endl; } return 0; } bool check(string in) { int flag = 0; stringstream stream_str(in); int main; int i; while(stream_str >> i) { if(flag == 0) main = i; else { map[main][i] = 1; } flag++; } if(flag == 0) return false; else return true; } long long ways(int row, int col) { if(dp[row][col] == 100000000) return 0; if(row == main_row && col == main_col) return 1; if(row == main_row) return ways(row, col + 1); if(col == main_col) return ways(row + 1, col); if(dp[row + 1][col] == dp[row][col + 1]) { return ways(row + 1, col) + ways(row, col + 1); } long long m1, m2; m1 = dp[row + 1][col]; m2 = dp[row][col + 1]; if(m1 < m2) return ways(row + 1, col); else return ways(row, col + 1); } long long min(int row, int col) { if(row > main_row || col > main_col) return 100000000; if(map[row][col] == 1) { dp[row][col] = 100000000; return 100000000; } if(dp[row][col] != -1) return dp[row][col]; if(row == main_row && col == main_col) { return 0; } long long r, d, max; r = min(row, col + 1); d = min(row + 1, col); max = r; if(d < max) max = d; dp[row][col] = max + 1; return max + 1; } void reset() { for(int counter = 0; counter < main_row + 5; counter++) { for(int counter2 = 0; counter2 < main_col + 5; counter2++) { map[counter][counter2] = -1; dp[counter][counter2] = -1; } } }
true
463e32d05335c59e3cbce500cbf03dccb37d59d4
C++
kamaroyl/data-structures-2421
/final-project/test/PictureComparatorTest.cpp
UTF-8
2,804
3.59375
4
[]
no_license
#include "../src/Data/Comparators/PictureComparator.hpp" #include "../src/Data/Picture.hpp" #include <iostream> #include <string> std::string humanReadableResult(char value) { if(value < 0) return "less than"; if(value > 0) return "greater than"; return "equal to"; } void testPictureComparatorConstructor() { std::cout << "testPictureComparatorConstructor()" << std::endl; PictureComparator pc; } void testPictureCompareNoFields() { std::cout << "testPictureCompareNoFields()" << std::endl; Picture *one = new Picture(1, "one", "1111", "1", "11.11", "111", "Adventure", "Action", "January", "11", "AAAAAAAA"); Picture *two = new Picture(2, "two", "2222", "2", "22.22", "222", "Biography", "Comedy", "February", "22", "BBBBBBBBB"); PictureComparator pc; char result = pc(one, two); std::cout << "One is: " << humanReadableResult(result) << " Two" << std::endl; } void testPictureCompareOneField() { std::cout << "testPictureCompareOneField()" << std::endl; Picture *one = new Picture(1, "one", "1111", "1", "11.11", "111", "adventure", "action", "january", "11", "aaaaaaaa"); Picture *two = new Picture(2, "two", "2222", "2", "22.22", "222", "biography", "comedy", "february", "22", "bbbbbbbbb"); PictureComparator pc; pc.setYear(1); char result = pc(one, two); std::cout << "One is: " << humanReadableResult(result) << " Two" << std::endl; } void testPictureCompareOneFieldReverse() { std::cout << "testPictureCompareOneFieldReverse()" << std::endl; Picture *one = new Picture(1, "one", "1111", "1", "11.11", "111", "adventure", "action", "january", "11", "aaaaaaaa"); Picture *two = new Picture(2, "two", "2222", "2", "22.22", "222", "biography", "comedy", "february", "22", "bbbbbbbbb"); PictureComparator pc; pc.setYear(-1); char result = pc(one, two); std::cout << "One is: " << humanReadableResult(result) << " Two" << std::endl; } void testPictureCompareTwoFields() { std::cout << "testPictureCompareTwoFields()" << std::endl; Picture *one = new Picture(1, "one", "1111", "1", "11.11", "111", "adventure", "action", "january", "11", "aaaaaaaa"); Picture *two = new Picture(2, "two", "1111", "2", "22.22", "222", "biography", "comedy", "february", "22", "bbbbbbbbb"); PictureComparator pc; pc.setYear(10); char result = pc(one, two); std::cout << "One is: " << humanReadableResult(result) << " Two" << std::endl; pc.setMetacritic(5); result = pc(one, two); std::cout << "One is: " << humanReadableResult(result) << " Two" << std::endl; } int main() { testPictureComparatorConstructor(); testPictureCompareNoFields(); testPictureCompareOneField(); testPictureCompareOneFieldReverse(); testPictureCompareTwoFields(); return 0; }
true
66d3dcee0619ec0eadf1941b112a15f5e9cdac4f
C++
sivm205/cpp-development
/function/f16.cpp
UTF-8
776
3.515625
4
[]
no_license
// greatest tof three number using pointer #include<iostream> using namespace std; int find_max(int *x,int *y,int *z) { if(*x >*y && *x>*z) { return *x; } else if(*y>*x && *y>*z) { return *y; } else { return *z; } } int find_fact(int *num) { if(*num==0 || *num==1) { return 1; } else { int res = 1; for(int *i= num; *i>1; i--) { cout<<i<<" " ; } return res; } } int main() { int num1 , num2, num3; cout<<"ENTER THE NUMBERS="<<endl; // cin>>num1>>num2>>num3; // cout<<"THE GREATEST OF THREE NUMBER IS = "<<find_max(&num1,&num2,&num3); cin>>num1; cout<<find_fact(&num1); return 0; }
true
94366d922e6a1fcb719fec3a14839876a674a345
C++
vsignor/CandiVal
/progettoP2 /ProgettoPasticceria/Modello/user.cpp
UTF-8
1,438
2.953125
3
[]
no_license
//user.cpp #include "user.h" User::User(const QString &name, const QString &pw) : username(name), password(pw){ setNomeDb("User"); } // costruttore bool User::isConnected() const { return !(username.isEmpty() && password.isEmpty()); } QString User::getUsername() const { return username; } QString User::getPassword() const { return password; } QString User::getNome() const { return nome; } QString User::getCognome() const { return cognome; } QString User::getFoto() const { return foto; } User *User::clone() const { return new User(*this); } void User::setUsername(const QString &u) { username = u; } void User::setPassword(const QString &p) { password = p; } void User::setNome(const QString &n) { nome = n; } void User::setCognome(const QString &c) { cognome = c; } void User::setFoto(const QString &f) { foto = f; } QString User::toString() const { return "("+username+") "+cognome+" "+nome; } void User::completeInJson(QJsonObject &json) const { json["username"] = username; json["password"] = password; json["nome"] = nome; json["cognome"] = cognome; json["foto"] = foto; } void User::completeFromJson(const QJsonObject &json) { username = json["username"].toString(); password = json["password"].toString(); nome = json["nome"].toString(); cognome = json["cognome"].toString(); foto = json["foto"].toString(); }
true
c7f7a9dbe1ffda0cd158619745c720bae537c10a
C++
bdumitriu/playground
/university-work/before/c/backtrak/1_uri.cpp
UTF-8
1,176
2.703125
3
[]
no_license
#include <stdio.h> #include <conio.h> int a[101][101], m, n, k; int x[5]= {0, -1, 0, 1, 0}; int y[5]= {0, 0, -1, 0, 1}; Back(int i, int ii, int jj) { int j, iii, jjj; for (j= 1; j <= 4; j++) { iii= ii+x[j]; jjj= jj+y[j]; if ((i >= 1) || (i <= m) || (j >= 1) || (j <= n)) if (a[iii][jjj] == 1) { a[iii][jjj]= k; back(i+1, iii, jjj); } } return 0; } Afisare() { int i, j; for (i= 1; i <= m; i++) { for (j= 1; j <= n; j++) printf("%i ", a[i][j]); printf("\n"); } return 0; } CitireDate() { int i, j; printf(" Numarul de linii : "); scanf("%i", &m); printf(" Numarul de coloane : "); scanf("%i", &n); for (i= 1; i <= m; i++) for (j= 1; j <= n; j++) { printf(" - elementul [%i,%i] : ", i, j); scanf("%i", &a[i][j]); } return 0; } main() { int i, j; clrscr(); printf("\n"); CitireDate(); k= 1; for (i= 1; i <= m; i++) for (j= 1; j <= n; j++) if (a[i][j] == 1) { k++; a[i][j]= k; Back(2, i, j); } Afisare(); return 0; }
true
c5b3a71a2affbf0ffbdf42eeb3b4c53b0dcd93d7
C++
breno550/Competitive-Programming
/Contest/contest/cf round #470 div.2/sheep.cpp
UTF-8
996
3
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main(){ int r, c; bool flag=false; cin >> r >> c; vector<vector <char>> board(r); for(int i = 0; i < r; i++){ char ent[505]; cin >> ent; for(int j = 0; j < c; j++){ board[i].push_back(ent[j]); } } for(int i = 0; i < r; i++){ for(int j = 0; j < c; j++){ if(board[i][j] == 'S'){ //cima if(i-1 >= 0){ if(board[i-1][j] == 'W') flag = true; } //baixo if(i+1 < r){ if(board[i+1][j] == 'W') flag = true; } //direita if(j+1 < c){ if(board[i][j+1] == 'W') flag = true; } //esquerda if(j-1 >= 0){ if(board[i][j-1] == 'W') flag = true; } } else { continue; } } } if(flag) cout << "No" << endl; else { cout << "Yes" << endl; for(int i = 0; i < r; i++){ for(int j = 0; j < c; j++){ if(board[i][j] == '.') cout << 'D'; else cout << board[i][j]; } cout << endl; } } return 0; }
true
f9aa11152b770fec00e1b9442340b08f921d2ca7
C++
hyh2010/reverseParentheses
/reverseParentheses.cpp
UTF-8
2,239
3.40625
3
[]
no_license
#include "reverseParentheses.h" #include <utility> #include <string> #include <stack> #include "OutputStrategyInterface.hpp" #include "topDownParser.hpp" class ReverseParenthesesStrategy : public OutputStrategyInterface { public: virtual ~ReverseParenthesesStrategy() = default; ReverseParenthesesStrategy(): _outputString(), _bufferStack(), _reverse(false) { } ReverseParenthesesStrategy(const ReverseParenthesesStrategy &) = default; ReverseParenthesesStrategy & operator = (const ReverseParenthesesStrategy &) = default; ReverseParenthesesStrategy(ReverseParenthesesStrategy &&) = default; ReverseParenthesesStrategy & operator = (ReverseParenthesesStrategy &&) = default; std::string outputString() const { return _outputString; } virtual void left_parenthesis() override { push_output_string(); _reverse = !_reverse; } virtual void right_parenthesis() override { _reverse = !_reverse; pop_output_string(); } virtual void character(const char c) override { write_to_outputString(std::string(1, c)); } private: void push_output_string() { _bufferStack.push(_outputString); _outputString.clear(); } void pop_output_string() { std::string tempBuffer = std::move(_outputString); _outputString = _bufferStack.top(); write_to_outputString(tempBuffer); _bufferStack.pop(); } void write_to_outputString (const std::string & buffer) { // prepend to output string in reverse mode, append in forward mode if (_reverse) { _outputString = buffer + _outputString; } else { _outputString += buffer; } } std::string _outputString; std::stack<std::string> _bufferStack; bool _reverse; }; std::string reverseParentheses(const std::string & s) { ReverseParenthesesStrategy strategy; auto it = s.begin(); try { topDownParser(strategy, it, s.end()); } catch (const syntaxErrorExcpetion &) { print_syntax_error(it, s); return std::string(); } return strategy.outputString(); }
true
a053f2362028b6c3a80d36ec7a01cb97082c5347
C++
masa-k0101/Self-Study_Cpp
/Cp1/1-6-1_overload.cpp
UTF-8
850
3.828125
4
[]
no_license
// Ovload1.cpp #include <iostream> // 絶対値を求める int Abs(int a) { return a < 0 ? -a : a; } double Abs(double a) { return a < 0 ? -a : a; } // 入力 int Input(int& nInt, double& nDouble) { std::cout << "Please imput by integer > " << std::flush; std::cin >> nInt; if(nInt == 1) return 0; std::cout << "Please imput by double > " << std::flush; std::cin >> nDouble; return 1; } // 絶対値の表示 void DispAbs(int nInt, double nDouble) { std::cout << nInt << " の絶対値は " << Abs(nInt) << "で、" << std::endl << nDouble << " の絶対値は " << Abs(nDouble) << "です。" << std::endl; } int main() { int nInt; double nDouble; while(Input(nInt, nDouble)) DispAbs(nInt, nDouble); return 0; }
true
2bd044fd9a8aae432b66252aa25c0657ce6595e3
C++
knetikmedia/knetikcloud-cpprest-client
/model/PasswordResetRequest.h
UTF-8
2,414
2.53125
3
[]
no_license
/** * Knetik Platform API Documentation latest * This is the spec for the Knetik API. Use this in conjunction with the documentation found at https://knetikcloud.com. * * OpenAPI spec version: latest * Contact: support@knetik.com * * NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ /* * PasswordResetRequest.h * * A request to reset a user&#39;s password by using a known user property */ #ifndef PasswordResetRequest_H_ #define PasswordResetRequest_H_ #include "ModelBase.h" #include <cpprest/details/basic_types.h> namespace com { namespace knetikcloud { namespace client { namespace model { /// <summary> /// A request to reset a user&#39;s password by using a known user property /// </summary> class PasswordResetRequest : public ModelBase { public: PasswordResetRequest(); virtual ~PasswordResetRequest(); ///////////////////////////////////////////// /// ModelBase overrides void validate() override; web::json::value toJson() const override; void fromJson(web::json::value& json) override; void toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& namePrefix) const override; void fromMultiPart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& namePrefix) override; ///////////////////////////////////////////// /// PasswordResetRequest members /// <summary> /// The user&#39;s email address /// </summary> utility::string_t getEmail() const; bool emailIsSet() const; void unsetEmail(); void setEmail(utility::string_t value); /// <summary> /// The user&#39;s mobile phone number /// </summary> utility::string_t getMobileNumber() const; bool mobileNumberIsSet() const; void unsetMobile_number(); void setMobileNumber(utility::string_t value); /// <summary> /// The user&#39;s username /// </summary> utility::string_t getUsername() const; bool usernameIsSet() const; void unsetUsername(); void setUsername(utility::string_t value); protected: utility::string_t m_Email; bool m_EmailIsSet; utility::string_t m_Mobile_number; bool m_Mobile_numberIsSet; utility::string_t m_Username; bool m_UsernameIsSet; }; } } } } #endif /* PasswordResetRequest_H_ */
true
8a3243075b93310603fe3d319b62ef84a70a6b58
C++
yvomenezes/cpp_polytech
/td6/piletableau/rectangle.hpp
UTF-8
437
3.265625
3
[]
no_license
#ifndef _PILE_HPP_ #define _PILE_HPP_ #include <iostream> class Rectangle { private: double largeur; double longuer; public: Rectangle(double largeur = 1, double longuer = 1) : largeur(largeur), longuer(longuer){} double surface() const; bool operator<(const Rectangle &r) const{ return this->surface() < r.surface() ? true : false; } friend std::ostream& operator << (std::ostream &out, const Rectangle &r); }; #endif
true
d37a5fa857f8cac367c98a09872de010ec27e235
C++
luis-3000/OnlineStore
/mainmenu.cpp
UTF-8
1,866
3.046875
3
[]
no_license
// // mainmenu.cpp // eBookStore // // Created by Jose Luis Castillo on 10/7/15. // Copyright © 2015 Jose Luis Castillo. All rights reserved. // #include <stdio.h> #include "cashier.cpp" #include "bookinfo.cpp" #include "invmenu.cpp" #include "reports.cpp" #include <iostream> using namespace std; int main(int argc, const char * argv[]) { int choice = 0; cout << "\n OnlineStore\n"; cout << " Main Menu\n\n"; cout << "1. Cashier Module.\n"; cout << "2. Inventory Database Module.\n"; cout << "3. Report Module.\n"; cout << "4. Exit.\n\n"; cout << "Enter Your Choice: "; cin >> choice; //Take appropriate actions switch(choice) { case 1: cashier(); //cout << "You selected item 1.\n"; break; case 2: invmenu(); //cout << "You selected item 2.\n"; break; case 3: reports(); //cout << "You selected item 3.\n"; break; case 4: cout << "Exiting now ... "; //"You selected item 4.\n"; break; default: cout << "\nPlease enter a number in the range 1-4.\n\n"; break; } do { cout << " OnlineStore\n"; cout << " Main Menu\n\n"; cout << "1. Cashier Module.\n"; cout << "2. Inventory Database Module.\n"; cout << "3. Report Module.\n"; cout << "4. Exit.\n\n"; cout << "Enter Your Choice: "; cin >> choice; //Take appropriate actions switch(choice) { case 1: cout << "You selected item 1.\n"; break; case 2: cout << "You selected item 2.\n"; break; case 3: cout << "You selected item 3.\n"; break; case 4: cout << "You selected item 4.\n"; break; default: cout << "\nPlease enter a number in the range 1-4.\n\n"; break; } } while (choice != 4); return 0; }
true