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
b6d101cd2a55b1cb4615f47386b841dbc511d411
C++
W00fdev/smart_math
/smart_rational/smart_rational.cpp
UTF-8
5,481
3.3125
3
[]
no_license
#include "smart_rational.h" /* Реализация методов класса Rational. Дополнительные методы: ... */ /* [XQ - 1] Куликов Дмитрий Дополнительный метод, переворачивающий дробь. */ Rational& Rational::INVERT_Q() { bool final_minus = numerator.getMinus(); *this = Rational( Integral(denominator.getRawOdds(), denominator.getRawDeg(), final_minus), numerator.ABS_Z_N() ); return *this; } /* [XQ - 2] Куликов Дмитрий Дополнительный метод, переворачивающий дробь. */ Rational& Rational::MUL_ZM_Q() { numerator.MUL_ZM_Z(); return *this; } /* [Q - 1] Ковтун Александр Сокращаем дробь. Поделим обе части дроби на НОД. */ Rational& Rational::RED_Q_Q() { // НОД через натуральные. if (numerator == Integral{0}) { MakeNull(); return *this; } Integral NOD = Integral(Natural(denominator).GCF_NN_N(numerator.ABS_Z_N())); numerator.DIV_ZZ_Z(NOD); denominator.DIV_NN_N(NOD.ABS_Z_N()); return *this; // Изменили исходный объект } /* [Q - 2] Ковтун Александр Проверка на целое. Число целое? Тогда true Ссылки на документацию, использованную при разработке. */ // опять же, оператор= к рациональному. bool Rational::INT_Q_B() const { Rational reduced_copy(*this); reduced_copy.RED_Q_Q(); return reduced_copy.getDenominator() == Natural{"1"} != 0; } /* [Q - 3] Бабкин Иван Преобразование целого в рациональное. Значение сохраняем в числителе, а знаменатель = 1 */ Rational Rational::TRANS_Z_Q(const Integral& i) const { return Rational(i, Natural{1}); } /* [Q - 4] Бабкин Иван Преобразование Рационального в целое с округлением деления */ Integral Rational::TRANS_Q_Z() { RED_Q_Q(); if (INT_Q_B()) return numerator; Integral i_numerator(numerator); Integral i_denominator(denominator); return i_numerator.DIV_ZZ_Z(i_denominator); } /* [Q - 5] Ширнин Кирилл Сложение двух рациональных чисел Ссылки на документацию, использованную при разработке. */ Rational& Rational::ADD_QQ_Q(const Rational& r) { Integral copy_numerator = numerator; Natural lcm_denoms = LCM_NN_N(denominator, r.getDenominator()); // НОК дробей Integral left_koeff_num = Integral(DIV_NN_N(lcm_denoms, denominator)); // домножение левого числителя на коэффициент Integral right_koeff_num = Integral(DIV_NN_N(lcm_denoms, r.getDenominator())); // домножение правого числителя на коэффициент numerator = ADD_ZZ_Z(MUL_ZZ_Z(numerator, left_koeff_num), MUL_ZZ_Z(r.getNumerator(), right_koeff_num)); denominator = lcm_denoms; RED_Q_Q(); // сократим результат return *this; } /* [Q - 6] Ширнин Кирилл Вычитание дробей реализуем как сложение двух дробей, где у второй изменён знак */ // Изменили знак у второй дроби Rational& Rational::SUB_QQ_Q(const Rational& r) { return ADD_QQ_Q(Rational(r.getNumerator().MUL_ZM_Z(), r.getDenominator())); } /* [Q - 7] Ширнин Кирилл Умножение дробей. Умножим числители, знаменатели, сократим. */ Rational& Rational::MUL_QQ_Q(const Rational& r) { // проверка на ноль numerator.MUL_ZZ_Z(r.getNumerator()); denominator.MUL_NN_N(r.getDenominator()); RED_Q_Q(); return *this; } /* [Q - 8] Ширнир Кирилл Деление дробей. Умножим, перевернув правую дробь. Для этого создана специальная функция Invert_Q(). */ Rational& Rational::DIV_QQ_Q(const Rational& r) { return MUL_QQ_Q(Rational(r).INVERT_Q()); } // <! ---------- Friend функционал ---------- !> // Rational INVERT_Q(const Rational& r) { Rational const_disqualification(r); return const_disqualification.INVERT_Q(); } Rational RED_Q_Q(const Rational& r) { Rational const_disqualification(r); return const_disqualification.RED_Q_Q(); } bool INT_Q_B(const Rational& r) { return r.INT_Q_B(); } Rational TRANS_Z_Q(const Integral& i) { Rational r; return r.TRANS_Z_Q(i); } Integral TRANS_Q_Z(const Rational& n) { Rational const_disqualification(n); return const_disqualification.TRANS_Q_Z(); } Rational ADD_QQ_Q(const Rational& r1, const Rational& r2) { Rational const_disqualification(r1); return const_disqualification.ADD_QQ_Q(r2); } Rational SUB_QQ_Q(const Rational& r1, const Rational& r2) { Rational const_disqualification(r1); return const_disqualification.SUB_QQ_Q(r2); } Rational MUL_QQ_Q(const Rational& r1, const Rational& r2) { Rational const_disqualification(r1); return const_disqualification.MUL_QQ_Q(r2); } Rational DIV_QQ_Q(const Rational& r1, const Rational& r2) { Rational const_disqualification(r1); return const_disqualification.DIV_QQ_Q(r2); }
true
83af25abb8b0640387c46c31d11d9e3687dbbf87
C++
igrek51/adb-sync
/src/diffs/Diff.cpp
UTF-8
1,396
3.078125
3
[]
no_license
// // Created by igrek on 04/02/17. // #include "Diff.h" Diff::Diff(string localFile, string remoteFile, DiffType type) { this->localFile = localFile; this->remoteFile = remoteFile; this->type = type; this->inverted = false; } string Diff::typeName() { if (!inverted) { // synchronize from local to remote switch (type) { case DiffType::NO_DIRECTORY: return "not existing directory"; case DiffType::NO_REGULAR_FILE: return "not existing file"; case DiffType::DIFFERENT_CONTENT: return "different content"; case DiffType::DIFFERENT_SIZE: return "different size"; case DiffType::REDUNDANT_DIRECTORY: return "reduntant directory"; case DiffType::REDUNDANT_REGULAR_FILE: return "redundant file"; } } else { // inverted synchronization direction: from remote to local switch (type) { case DiffType::NO_DIRECTORY: // no remote directory return "redundant directory"; case DiffType::NO_REGULAR_FILE: // no remote file return "redundant file"; case DiffType::DIFFERENT_CONTENT: // different checksums return "different content"; case DiffType::DIFFERENT_SIZE: // different file sizes return "different size"; case DiffType::REDUNDANT_DIRECTORY: // no local directory return "not existing directory"; case DiffType::REDUNDANT_REGULAR_FILE: // no local file return "not existing file"; } } return ""; }
true
44a2687d18e8c019a9419305dddbdd2c8e45b0ba
C++
yosh1/sfc-graphics-programming
/final/src/particle.cpp
UTF-8
898
2.890625
3
[]
no_license
// // particle.cpp // emptyExample // // Created by Yoshihisa Kaino on 2020/07/11. // #include "particle.h" // constructor particle::particle() { setup(); } // ----------------------- void particle::setup() { pos.set(ofRandom(ofGetWidth()), ofRandom(ofGetHeight())); vel.set(ofRandom(-5, 5), ofRandom(-5, 0)); color = ofColor(255); speed = 1.0; size = 10; }; // ----------------------- void particle::update() { pos += vel; // bound condition if (pos.x < 0 || pos.x > ofGetWidth()) vel.x *= speed; if (pos.y < 0 || pos.y > ofGetHeight()) vel.y *= speed; }; // ----------------------- void particle::draw() { ofSetColor(color); ofDrawCircle(pos.x, pos.y, size); } void particle::setColor(ofColor col) { color = col; } void particle::setSpeed(float spd) { speed = spd; } void particle::setSize(float siz) { size = siz; }
true
587a77975571fe1236b0046e25c277c49bcc12e3
C++
jeffgojeff/messAround
/playingWithFunctions.cpp
UTF-8
448
3.578125
4
[]
no_license
#include <iostream> using namespace std; void getInfo(int&, int&); int sum(int, int); int main() { int var1, var2, tot1; getInfo(var1, var2); tot1 = sum(var1, var2); cout << tot1 << endl; return 0; } void getInfo(int& var1, int& var2) { cout << "Enter in a number: " << endl; cin >> var1; cout << "Enter in a second number: " << endl; cin >> var2; } int sum(int A, int B) { int total = 0; total = A + B; return total; }
true
329016c58953cfcce78e38573788fbbfc76fcbe1
C++
himdhiman/Launchpad-May
/Lecture-3/operator.cpp
UTF-8
334
2.625
3
[]
no_license
#include<iostream> using namespace std; int main(){ /* int i = 1; cout<<i++<<endl; cout<<++i<<endl; cout<<--i<<" "<<i--<<endl; */ //cout<<(~(-5))<<endl; //cout<< (5^7)<<endl; /* int x = 7; cout<< (x<<1)<<endl; cout<< (x<<2)<<endl; x = -5; cout<< (x>>1)<<endl; //cout<< (x>>2)<<endl; */ int i=5; i<<=3; cout<<i<<endl; }
true
90c0c52090459e3faab077d30d2dbec3342a6832
C++
MrPeanutButta/cx
/cx/tknnum.cpp
UTF-8
6,700
2.703125
3
[ "MIT" ]
permissive
/* The MIT License (MIT) Copyright (c) 2015 Aaron Hebert <aaron.hebert@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <cstring> #include <cstdio> #include <cmath> #include <sstream> #include <climits> #include <cfloat> #include <cctype> #include "token.h" namespace cx{ /// radix number bases enum cx_radix_base { rb_DECIMAL = 10, rb_BINARY = 2, rb_HEXADECIMAL = 16, rb_OCTAL = 8 }; /******************* * * * Number Tokens * * * *******************/ /** get Extract a number token from the source and set * its value. * * @param buffer : ptr to text input buffer. */ void number_token::get(text_in_buffer &buffer) { cx_real number_value = 0.0; /* value of number ignoring * the decimal point */ int whole_places = 0; // no. digits before the decimal point int decimal_places = 0; // no. digits after the decimal point wchar_t exponent_sign = L'+'; cx_real e_value = 0.0; // value of number after 'E' int exponent = 0; // final value of exponent bool saw_dot_dot_Flag = false; // true if encountered '..', ch = buffer.current_char(); ps = string; digit_count = 0; count_error_flag = false; code__ = TC_ERROR; type__ = T_INT; /* we don't know what it is yet, but * assume it'll be an integer */ // assume base 10 radix radix = rb_DECIMAL; // octal base if (ch == L'0') { radix = rb_OCTAL; ch = buffer.get_char(); switch (ch) { case L'x': radix = rb_HEXADECIMAL; ch = buffer.get_char(); break; case L'b': radix = rb_BINARY; ch = buffer.get_char(); break; case L'.': radix = rb_DECIMAL; ch = buffer.put_back_char(); break; default: ch = buffer.put_back_char(); break; } } /* get the whole part of the number by accumulating * the values of its digits into number_value. whole_places keeps * track of the number of digits in this part. */ if (!accumulate_value(buffer, number_value, ERR_INVALID_NUMBER)) return; whole_places = digit_count; /* If the current character is a dot, then either we have a * fraction part or we are seeing the first character of a '..' * token. To find out, we must fetch the next__ character. */ if (ch == '.') { ch = buffer.get_char(); if (ch == '.') { /* We have a .. token. Back up bufferp so that the * token can be extracted next__. */ saw_dot_dot_Flag = true; buffer.put_back_char(); } else { type__ = T_DOUBLE; *ps++ = '.'; // We have a fraction part. Accumulate it into number_value. if (!accumulate_value(buffer, number_value, ERR_INVALID_FRACTION)) return; decimal_places = digit_count - whole_places; } } /* get the exponent part, if any. There cannot be an * exponent part if we already saw the '..' token. */ if (!saw_dot_dot_Flag && ((ch == 'E') || (ch == 'e'))) { type__ = T_DOUBLE; *ps++ = ch; ch = buffer.get_char(); // Fetch the exponent's sign, if any. if ((ch == '+') || (ch == '-')) { *ps++ = exponent_sign = ch; ch = buffer.get_char(); } // Accumulate the value of the number after 'E' into e_value. digit_count = 0; if (!accumulate_value(buffer, e_value, ERR_INVALID_EXPONENT)) return; if (exponent_sign == '-') e_value = -e_value; } // Were there too many digits? if (count_error_flag) { cx_error(ERR_TOO_MANY_DIGITS); return; } /* Calculate and check the final exponent value, * and then use it to adjust the number's value. */ exponent = int(e_value) - decimal_places; if ((exponent + whole_places < DBL_MIN_10_EXP) || (exponent + whole_places > DBL_MAX_10_EXP)) { cx_error(ERR_REAL_OUT_OF_RANGE); return; } if (exponent != 0) number_value *= pow(10.0L, exponent); // Check and set the numeric value. if (type__ == T_INT) { if ((number_value < LLONG_MIN) || (number_value > LLONG_MAX)){ cx_error(ERR_INTEGER_OUT_OF_RANGE); return; } value__.i_ = static_cast<cx_int>(number_value); } else { // TODO Range check for max double if ((number_value < -DBL_MAX) || (number_value > DBL_MAX)){ cx_error(ERR_REAL_OUT_OF_RANGE); return; } value__.d_ = number_value; } *ps = '\0'; code__ = TC_NUMBER; } /** accumulate_value Extract a number part from the source * and set its value. * * @param buffer : ptr to text input buffer. * @param value : accumulated value (from one or more calls). * @param ec : error code if failure. * @return true if success false if failure. */ int number_token::accumulate_value(text_in_buffer &buffer, cx_real &value, error_code ec) { const int max_digit_count = 20; /* cx_error if the first character is not a digit * and radix base is not hex */ if ((char_map[ch] != CC_DIGIT) && (!isxdigit(static_cast<int>(ch)))) { cx_error(ec); return false; // failure } /* Accumulate the value as long as the total allowable * number of digits has not been exceeded. */ do { *ps++ = ch; if (++digit_count <= max_digit_count) { value = radix * value + char_value(ch); // shift left__ and add } else count_error_flag = true; // too many digits ch = buffer.get_char(); } while ((char_map[ch] == CC_DIGIT) || isxdigit(ch)); return true; // success } int number_token::char_value(const wchar_t &c) { if (isxdigit(c)) { switch (c) { case L'A': case L'a': return 10; case L'B': case L'b': return 11; case L'C': case L'c': return 12; case L'D': case L'd': return 13; case L'E': case L'e': return 14; case L'F': case L'f': return 15; } } return (c - L'0'); } }
true
fb761976fa7b2d1194b4fce66a311cb32c798c07
C++
icoty/LeetCode
/Algorithms/861.Score_After_Flipping_Matrix.cpp
UTF-8
1,131
2.65625
3
[]
no_license
#include "AllInclude.h" class Solution { public: // https://leetcode.com/problems/score-after-flipping-matrix/discuss/144125/c%2B%2B-easy-understand-Greedy-method-with-explanation int matrixScore(vector<vector<int>>& A) { int r = A.size(); int c = A[0].size(); for(int i = 0; i < r; ++i){ if(A[i][0] == 0){ for(int j = 0; j < c; ++j) A[i][j] ^= 1; } } for(int i = 1; i < c; ++i){ int cnt = 0; for(int j = 0; j < r; ++j){ cnt += A[j][i]; } if(cnt <= (r >> 1)){ // 列中1的个数小于等于r/2 for(int j = 0; j < r; ++j) A[j][i] ^= 1; } } int ret = 0; int bin = 1; for(int i = c - 1; i >= 0; --i){ for(int j = 0; j < r; ++j){ ret += A[j][i] * bin; } bin <<= 1; } return ret; } };
true
1cb475a341ffaba5afb6f7c814a5fd8cffb6cee8
C++
Vokhmintseva/arkanoid2
/00/game.h
UTF-8
31,608
2.515625
3
[]
no_license
#include <cstdlib> #include <ctime> #include <map> #include <vector> #include <algorithm> #include <cmath> #include "calculations.cpp" #include "scores.cpp" #include "levels.cpp" using namespace std; const sf::Vector2f gameFieldPosition = sf::Vector2f(50, 50); const float GAME_FIELD_WIDTH = 300; const float GAME_FIELD_HEIGHT = 300; const float LEFT_EDGE = gameFieldPosition.x; const float RIGHT_EDGE = LEFT_EDGE + GAME_FIELD_WIDTH; const float TOP = gameFieldPosition.y; const float BOTTOM = TOP + GAME_FIELD_HEIGHT; const float PLATFORM_WIDTH = 50; const float PLATFORM_HEIGHT = 13; const float INITIAL_PLATFORM_X = LEFT_EDGE + (GAME_FIELD_WIDTH - PLATFORM_WIDTH) / 2; const float INITIAL_PLATFORM_Y = 325; const float BALL_SIZE = 10; const float INITIAL_BALL_X = LEFT_EDGE + (GAME_FIELD_WIDTH - BALL_SIZE) / 2; //195 const float INITIAL_BALL_Y = INITIAL_PLATFORM_Y - BALL_SIZE; //315 const float gameFieldOutlineThickness = 5; const float regularBallSpeed = 100.0f; const sf::Vector2f DOOR_POSITION = {RIGHT_EDGE, TOP + GAME_FIELD_HEIGHT / 4}; const float DOOR_WIDTH = 5; const float DOOR_HEIGHT = GAME_FIELD_HEIGHT / 2; const float regularTimeOfPrizeEffect = 40; sf::Sprite livesDesignation; sf::Sprite ball; sf::Sprite highScoresSprite; sf::Sprite background; sf::Sprite scoresSprite; sf::Text levelLostMsgTextModal; sf::Text okTextModal; sf::Text cancelTextModal; sf::Text playerText; sf::Text scoresText; sf::Text highScoresText; sf::RectangleShape levelLostModal; sf::Sprite platform; sf::Sprite expandPlatformSprite; sf::Sprite twoBallsSprite; sf::Sprite slowBallDownSprite; sf::Sprite accelerateBallSprite; sf::Sprite extraLifeSprite; sf::Sprite portalDoorSprite; sf::Sprite stickyBallSprite; void resetPlatform() { platform.setPosition(INITIAL_PLATFORM_X, INITIAL_PLATFORM_Y); } void setPlatformSize() { sf::Vector2f platformSize(PLATFORM_WIDTH, PLATFORM_HEIGHT); platform.setScale( platformSize.x / platform.getLocalBounds().width, platformSize.y / platform.getLocalBounds().height); } void resetBall() { ball.setPosition(INITIAL_BALL_X, INITIAL_BALL_Y); } void handlePrize(sf::FloatRect brickBounds, PrizeType prizeType, std::vector<sf::Sprite *> &activePrizes) { sf::Sprite *spritePtr = new sf::Sprite(); spritePtr->setTexture(getPrizeSpriteTexture(prizeType)); spritePtr->setPosition(brickBounds.left, brickBounds.top); activePrizes.push_back(spritePtr); } void handleBallCollisionWithBrick(sf::FloatRect brickBounds, sf::FloatRect ballBounds, Brick brick, int &ballXdir, int &ballYdir, std::vector<sf::Sprite *> &activePrizes) { scores = scores + 50; scoresText.setString(std::to_string(scores)); const float ballCenter = ballBounds.left + BALL_SIZE / 2; if ( (brickBounds.left <= ballCenter) && (ballCenter <= (brickBounds.left + brickBounds.width))) { ballYdir = -1 * ballYdir; } else if ( (brickBounds.left > ballCenter) || (ballCenter > (brickBounds.left + brickBounds.width))) { ballXdir = -1 * ballXdir; } if (brick.prize.prizeType != none && !brick.isBrokenWithDoubleHit) { handlePrize(brickBounds, brick.prize.prizeType, activePrizes); } } bool isStickyBallActive(std::vector<PrizeEffect> prizeEffects) { for (int i = 0; i < prizeEffects.size(); i++) { if (prizeEffects[i].prizeEffectType == sticky_ball) { return true; } } } void handleBallCollisionWithPlatform(sf::FloatRect platformBounds, sf::FloatRect ballBounds, float &ballAngle, bool &isBallStuck, int &ballXdir, int &ballYdir, std::vector<PrizeEffect> &prizeEffects) { if ((ballBounds.top + ballBounds.height) >= (platformBounds.top + 3)) { return; } if (isStickyBallActive(prizeEffects)) { isBallStuck = true; } const float ballCenter = ballBounds.left + BALL_SIZE / 2; const float point1 = platformBounds.left + PLATFORM_WIDTH / 4; const float point2 = platformBounds.left + PLATFORM_WIDTH / 2; const float point3 = platformBounds.left + PLATFORM_WIDTH / 4 * 3; if (ballCenter <= point1) { ballAngle = 45; ballYdir = -1 * abs(ballYdir); ballXdir = -1 * abs(ballXdir); return; } if (ballCenter <= point2 && ballCenter > point1) { ballAngle = 20; ballYdir = -1 * abs(ballYdir); ballXdir = -1 * abs(ballXdir); return; } if (ballCenter > point2 && ballCenter <= point3) { ballAngle = 20; ballYdir = -1 * abs(ballYdir); ballXdir = 1 * abs(ballXdir); return; } if (ballCenter > point3) { ballAngle = 45; ballYdir = -1 * abs(ballYdir); ballXdir = 1 * abs(ballXdir); return; } } void handleBallMiss(int &lives, int &ballXdir, int &ballYdir, float &ballSpeed, bool &isPaused, std::vector<PrizeEffect> &prizeEffects, std::vector<sf::Sprite *> &activePrizes) { decreaseScores(); prizeEffects.clear(); activePrizes.clear(); lives--; if (lives < 1) { gameState = level_lost_modal; handleScores(); } else { resetPlatform(); setPlatformSize(); resetBall(); isPaused = true; ballXdir = 1; ballYdir = -1; ballSpeed = 100; } } void checkBallCollisionWithBrick(const sf::FloatRect &ballBounds, std::vector<Brick> &bricks, std::vector<float> *timeFromCollisionWithCrackedBrick, float &timeToShowLevelPassedMsg, int &ballXdir, int &ballYdir, std::vector<sf::Sprite *> &activePrizes) { for (int i = 0; i < bricks.size(); i++) { sf::Sprite brick = bricks[i].brickSprite; const sf::FloatRect brickBounds = brick.getGlobalBounds(); if (ballBounds.intersects(brickBounds)) { if (bricks[i].isBrokenWithDoubleHit) { bricks[i].brickSprite.setTexture(getStoneCrackedTexture()); } if ((*timeFromCollisionWithCrackedBrick)[i] <= 0.0f) { handleBallCollisionWithBrick(brickBounds, ballBounds, bricks[i], ballXdir, ballYdir, activePrizes); if (!bricks[i].isBrokenWithDoubleHit) bricks.erase(bricks.begin() + i); } if (bricks[i].isBrokenWithDoubleHit) { bricks[i].isBrokenWithDoubleHit = false; timeFromCollisionWithCrackedBrick->insert(timeFromCollisionWithCrackedBrick->begin() + i, 0.15f); } if (bricks.empty()) { level += 1; timeToShowLevelPassedMsg = 3.0f; gameState = level_passed; } } } } void checkBallCollisionWithPlatform(const sf::FloatRect &ballBounds, float &ballAngle, bool &isBallStuck, int &ballXdir, int &ballYdir, std::vector<PrizeEffect> &prizeEffects) { const sf::FloatRect platformBounds = platform.getGlobalBounds(); if (ballBounds.intersects(platformBounds)) { handleBallCollisionWithPlatform(platformBounds, ballBounds, ballAngle, isBallStuck, ballXdir, ballYdir, prizeEffects); } } bool isPortalDoorActive(std::vector<PrizeEffect> &prizeEffects) { for (int i = 0; i < prizeEffects.size(); i++) { if (prizeEffects[i].prizeEffectType == portal_door) { return true; } } } void checkBallCollisionWithEdges(const sf::FloatRect &ballBounds, sf::Vector2f &newGlobalCoords, int &lives, float &timeToShowLevelPassedMsg, int &ballXdir, int &ballYdir, std::vector<PrizeEffect> &prizeEffects) { if (newGlobalCoords.x >= RIGHT_EDGE - BALL_SIZE) { if (isPortalDoorActive(prizeEffects) && ballBounds.top >= DOOR_POSITION.y && (ballBounds.top + ballBounds.height <= DOOR_POSITION.y + DOOR_HEIGHT)) { level++; gameState = level_passed; timeToShowLevelPassedMsg = 3.0f; return; } else { ballXdir = -1 * abs(ballXdir); } } if (newGlobalCoords.x <= LEFT_EDGE) { ballXdir = 1 * abs(ballXdir); } if (newGlobalCoords.y <= TOP) { ballYdir = 1 * abs(ballYdir); } } void checkBallMiss(sf::Vector2f &newGlobalCoords, int &lives, int &ballXdir, int &ballYdir, float &ballSpeed, bool &isPaused, std::vector<PrizeEffect> &prizeEffects, std::vector<sf::Sprite *> &activePrizes) { if (newGlobalCoords.y >= BOTTOM) { handleBallMiss(lives, ballXdir, ballYdir, ballSpeed, isPaused, prizeEffects, activePrizes); } } void updateBall(float &ballSpeed, float &dt, std::vector<Brick> &bricks, std::vector<float> *timeFromCollisionWithCrackedBrick, int &lives, float &timeToShowLevelPassedMsg, float &ballAngle, bool &isBallStuck, int &ballXdir, int &ballYdir, bool &isPaused, std::vector<PrizeEffect> &prizeEffects, std::vector<sf::Sprite *> &activePrizes) { if (isPaused || gameState != playing) return; const sf::FloatRect ballBounds = ball.getGlobalBounds(); const sf::FloatRect platformBounds = platform.getGlobalBounds(); checkBallCollisionWithPlatform(ballBounds, ballAngle, isBallStuck, ballXdir, ballYdir, prizeEffects); sf::Vector2f newGlobalCoords; if (isBallStuck) { const float ballCenter = ballBounds.left + BALL_SIZE / 2; const float platformCenter = platformBounds.left + PLATFORM_WIDTH / 2; newGlobalCoords = {platformCenter, platformBounds.top - BALL_SIZE}; } else { checkBallCollisionWithBrick(ballBounds, bricks, timeFromCollisionWithCrackedBrick, timeToShowLevelPassedMsg, ballXdir, ballYdir, activePrizes); const sf::Vector2f currentBallPos = ball.getPosition(); const float S = ballSpeed * dt; sf::Vector2f newLocalCoords = toEuclidean(S, ballAngle); newLocalCoords.x = ballXdir * newLocalCoords.x; newLocalCoords.y = ballYdir * newLocalCoords.y; newGlobalCoords = currentBallPos + newLocalCoords; checkBallCollisionWithEdges(ballBounds, newGlobalCoords, lives, timeToShowLevelPassedMsg, ballXdir, ballYdir, prizeEffects); } ball.setPosition(newGlobalCoords); checkBallMiss(newGlobalCoords, lives, ballXdir, ballYdir, ballSpeed, isPaused, prizeEffects, activePrizes); } void updatePlatform(sf::Keyboard::Key &key, float &dt) { const float speed = 1500; sf::Vector2f platformPosition = platform.getPosition(); if (key == sf::Keyboard::Left) { if (platformPosition.x > gameFieldPosition.x) platform.move(-1 * speed * dt, 0); } if (key == sf::Keyboard::Right) { if (platformPosition.x < gameFieldPosition.x + GAME_FIELD_WIDTH - PLATFORM_WIDTH) platform.move(speed * dt, 0); } } void handleLeftKeyPressed(sf::Keyboard::Key &key, float &dt, bool &isPaused, int &selectedModalItem) { if (gameState == playing && !isPaused) { updatePlatform(key, dt); } else { if (gameState == level_lost_modal) { selectedModalItem = 1; okTextModal.setStyle(sf::Text::Bold | sf::Text::Underlined); cancelTextModal.setStyle(sf::Text::Regular); } } } void handleRightKeyPressed(sf::Keyboard::Key &key, float &dt, bool &isPaused, int &selectedModalItem) { if (gameState == playing && !isPaused) { updatePlatform(key, dt); } else { if (gameState == level_lost_modal) { selectedModalItem = 2; okTextModal.setStyle(sf::Text::Regular); cancelTextModal.setStyle(sf::Text::Bold | sf::Text::Underlined); } } } void handleReturnKeyReleased(int selectedModalItem) { scores = 0; if (gameState == level_lost_modal) { switch (selectedModalItem) { case 1: gameState = start_game; break; case 2: gameState = menu_screen; break; } } } void onKeyReleased(sf::Event::KeyEvent &key, float &dt, bool &isBallStuck, bool &isPaused, int selectedModalItem) { switch (key.code) { case sf::Keyboard::Space: isBallStuck ? isBallStuck = false : isPaused = !isPaused; break; case sf::Keyboard::Return: handleReturnKeyReleased(selectedModalItem); return; default: break; } } void onKeyPressed(sf::Event::KeyEvent &key, float &dt, bool &isPaused, int &selectedModalItem) { switch (key.code) { case sf::Keyboard::Left: handleLeftKeyPressed(key.code, dt, isPaused, selectedModalItem); break; case sf::Keyboard::Right: handleRightKeyPressed(key.code, dt, isPaused, selectedModalItem); break; default: break; } } //опрашивает и обрабатывает доступные события в цикле void pollEvents(sf::RenderWindow &window, float &dt, bool &isBallStuck, bool &isPaused, int &selectedModalItem) { sf::Event event; while (window.pollEvent(event)) { switch (event.type) { case sf::Event::Closed: handleScores(); gameState = quit; return; case sf::Event::KeyReleased: onKeyReleased(event.key, dt, isBallStuck, isPaused, selectedModalItem); break; case sf::Event::KeyPressed: onKeyPressed(event.key, dt, isPaused, selectedModalItem); break; default: break; } } } void drawBricks(sf::RenderWindow &window, std::vector<Brick> &bricks) { for (std::vector<int>::size_type i = 0; i != bricks.size(); i++) { window.draw(bricks[i].brickSprite); } } void drawLevelLostModal(sf::RenderWindow &window) { window.draw(levelLostModal); window.draw(levelLostMsgTextModal); window.draw(okTextModal); window.draw(cancelTextModal); } bool isExtraLifePrizeActive(std::vector<PrizeEffect> prizeEffects) { for (int i = 0; i < prizeEffects.size(); i++) { if (prizeEffects[i].prizeEffectType == extra_life) { return true; } } } void drawSidebar(sf::RenderWindow &window, int &lives, sf::Sprite playerSprite, sf::RectangleShape livesDesignationBackgr, std::vector<PrizeEffect> &prizeEffects) { window.draw(playerText); window.draw(playerSprite); window.draw(scoresText); window.draw(scoresSprite); sf::Vector2f initPos = {x : 370, y : 310}; livesDesignationBackgr.setPosition(362, 310 + 22 * (lives - 1)); if (isExtraLifePrizeActive(prizeEffects)) { window.draw(livesDesignationBackgr); } for (int i = 0; i < lives; i++) { livesDesignation.setPosition(initPos); window.draw(livesDesignation); initPos.y = initPos.y + 22; } window.draw(highScoresSprite); window.draw(highScoresText); } void drawPrizes(sf::RenderWindow &window, std::vector<sf::Sprite *> &activePrizes) { for (sf::Sprite *prizeSprite : activePrizes) { window.draw(*prizeSprite); } } void drawLevelPassedModal(sf::RenderWindow &window, sf::Text *levelPassedText) { window.draw(levelLostModal); window.draw(*levelPassedText); } void redrawFrame(sf::RenderWindow &window, std::vector<Brick> bricks, sf::RectangleShape field, sf::RectangleShape door, int &lives, sf::Sprite playerSprite, sf::RectangleShape livesDesignationBackgr, sf::Text *levelPassedText, std::vector<PrizeEffect> &prizeEffects, std::vector<sf::Sprite *> &activePrizes) { window.clear(sf::Color::White); window.draw(background); window.draw(field); drawBricks(window, bricks); drawSidebar(window, lives, playerSprite, livesDesignationBackgr, prizeEffects); window.draw(platform); window.draw(ball); drawPrizes(window, activePrizes); if (gameState == level_lost_modal) { drawLevelLostModal(window); } if (isPortalDoorActive(prizeEffects)) { window.draw(door); } if (gameState == level_passed) { drawLevelPassedModal(window, levelPassedText); } window.display(); } sf::RectangleShape createGameField() { sf::RectangleShape gameField; gameField.setSize({x : GAME_FIELD_WIDTH, y : GAME_FIELD_HEIGHT}); gameField.setOutlineColor(sf::Color(76, 5, 73)); gameField.setOutlineThickness(gameFieldOutlineThickness); gameField.setPosition(gameFieldPosition); gameField.setFillColor(sf::Color(50, 25, 100, 180)); return gameField; } sf::RectangleShape createDoor() { sf::RectangleShape door; door.setSize({x : DOOR_WIDTH, y : DOOR_HEIGHT}); door.setOutlineColor(sf::Color(197, 21, 21)); door.setPosition(DOOR_POSITION); door.setFillColor(sf::Color(197, 21, 21)); return door; } void recalcTimeToShowLevelPassedMsg(float &dt, float &timeToShowLevelPassedMsg, sf::Text *textPtr) { if (gameState == level_passed) { timeToShowLevelPassedMsg -= dt; if (timeToShowLevelPassedMsg <= 0) { gameState = start_game; delete textPtr; } } } void adjustPlatform() { platform.setTexture(getPlatformTexture()); setPlatformSize(); resetPlatform(); } void adjustBall(int &ballXdir, int &ballYdir, float &ballSpeed) { ball.setTexture(getBallTexture()); ball.setScale( BALL_SIZE / ball.getLocalBounds().width, BALL_SIZE / ball.getLocalBounds().height); ballXdir = 1; ballYdir = -1; ballSpeed = 100.0f; resetBall(); } sf::RectangleShape setLivesDesignationBackgr() { sf::RectangleShape livesDesignationBackgr; livesDesignationBackgr.setSize({x : 56, y : 20}); livesDesignationBackgr.setOutlineColor(sf::Color(197, 21, 21)); livesDesignationBackgr.setFillColor(sf::Color(197, 21, 21)); livesDesignationBackgr.setRotation(-20); return livesDesignationBackgr; } sf::Sprite adjustPlayer() { sf::Sprite playerSprite; playerSprite.setTexture(getPlayerTexture()); playerSprite.setPosition(370, 50); return playerSprite; } void adjustSidebar() { playerText = sf::Text(); playerText.setFillColor(sf::Color(232, 6, 107)); playerText.setFont(getFont()); playerText.setCharacterSize(30); playerText.setString(playerName); playerText.setPosition({x : 440, y : 80}); scoresSprite.setTexture(getScoresTexture()); scoresSprite.setPosition(370, 190); scoresText = sf::Text(); scoresText.setFillColor(sf::Color::Red); scoresText.setFont(getFont()); scoresText.setCharacterSize(50); scoresText.setString(std::to_string(scores)); scoresText.setPosition({x : 450, y : 192}); livesDesignation.setTexture(getPlatformTexture()); sf::Vector2f livesDesignationSize(40, 15); livesDesignation.setScale( livesDesignationSize.x / livesDesignation.getLocalBounds().width, livesDesignationSize.y / livesDesignation.getLocalBounds().height); livesDesignation.setRotation(-20); highScoresSprite.setTexture(getHighScoresTexture()); highScoresSprite.setPosition(370, 430); highScoresText = sf::Text(); highScoresText.setFillColor(sf::Color::Yellow); highScoresText.setFont(getFont()); highScoresText.setCharacterSize(50); highScoresText.setString(highScoresStr); highScoresText.setPosition({x : 450, y : 440}); } void adjustGameLostModal() { levelLostModal.setSize(sf::Vector2f(WINDOW_WIDTH, WINDOW_HEIGHT)); levelLostModal.setPosition(0, 0); levelLostModal.setFillColor(sf::Color(0, 0, 0, 200)); levelLostMsgTextModal = sf::Text(); levelLostMsgTextModal.setFillColor(sf::Color::Red); levelLostMsgTextModal.setStyle(sf::Text::Bold); levelLostMsgTextModal.setCharacterSize(25); levelLostMsgTextModal.setString("YOU HAVE LOST THE LEVEL.\nWOULD YOU LIKE TO REPEAT ONE?"); levelLostMsgTextModal.setPosition({x : WINDOW_WIDTH / 4, y : WINDOW_HEIGHT / 3}); okTextModal = sf::Text(); okTextModal.setFillColor(sf::Color::Red); okTextModal.setStyle(sf::Text::Bold | sf::Text::Underlined); okTextModal.setCharacterSize(25); okTextModal.setString("OK"); okTextModal.setPosition({x : WINDOW_WIDTH * 1 / 3, y : WINDOW_HEIGHT / 2}); cancelTextModal = sf::Text(); cancelTextModal.setFillColor(sf::Color::Red); cancelTextModal.setStyle(sf::Text::Regular); cancelTextModal.setCharacterSize(25); cancelTextModal.setString("CANCEL"); cancelTextModal.setPosition({x : WINDOW_WIDTH * 2 / 3, y : WINDOW_HEIGHT / 2}); levelLostMsgTextModal.setFont(getFont()); okTextModal.setFont(getFont()); cancelTextModal.setFont(getFont()); } sf::Text *getLevelPassedText() { sf::Text *textPtr = new sf::Text(); textPtr->setFillColor(sf::Color::Red); textPtr->setStyle(sf::Text::Bold); textPtr->setCharacterSize(35); textPtr->setString("YOU HAVE PASSED THE LEVEL!"); textPtr->setPosition({x : WINDOW_WIDTH / 8, y : WINDOW_HEIGHT / 2}); textPtr->setFont(getFont()); return textPtr; } void resetVars(bool &isPaused, std::vector<PrizeEffect> &prizeEffects, std::vector<sf::Sprite *> &activePrizes) { isPaused = true; int selectedModalItem = 1; gameState = playing; highScoresStr = ""; prizeEffects.clear(); activePrizes.clear(); } void loadPrizesTextures() { expandPlatformSprite.setTexture(getExpandPlatformTexture()); twoBallsSprite.setTexture(getTwoBallsTexture()); slowBallDownSprite.setTexture(getSlowBallDownTexture()); accelerateBallSprite.setTexture(getAccelerateBallTexture()); extraLifeSprite.setTexture(getExtraLifeTexture()); portalDoorSprite.setTexture(getPortalDoorTexture()); stickyBallSprite.setTexture(getStickyBallTexture()); } void changePlatformSize(float &koeffOfPlatformExpansion) { sf::Vector2f platformSize(PLATFORM_WIDTH * koeffOfPlatformExpansion, PLATFORM_HEIGHT); platform.setScale( platformSize.x / platform.getLocalBounds().width, platformSize.y / platform.getLocalBounds().height); } void changeBallSpeed(float &ballSpeed, float &koeffOfBallSpeed) { ballSpeed = regularBallSpeed * koeffOfBallSpeed; } void twoBalls() { } void applyPrizeEffect(PrizeType prizeType, int &lives, float &koeffOfPlatformExpansion, float &koeffOfBallSpeed, float &ballSpeed) { switch (prizeType) { case expand_platform: koeffOfPlatformExpansion += 0.35; if (koeffOfPlatformExpansion < 2) changePlatformSize(koeffOfPlatformExpansion); break; case accelerate_ball: koeffOfBallSpeed += 0.35; if (koeffOfBallSpeed < 2) changeBallSpeed(ballSpeed, koeffOfBallSpeed); break; case slow_ball_down: koeffOfBallSpeed -= 0.35; if (koeffOfBallSpeed > 0) changeBallSpeed(ballSpeed, koeffOfBallSpeed); break; case two_balls: twoBalls(); break; case extra_life: lives++; break; } } PrizeType getPrizeType(sf::Sprite *prizeSprite) { const sf::Texture *prizeTexture = prizeSprite->getTexture(); return getPrizeType(prizeTexture); } void deletePtr(sf::Sprite *prizeSprite) { prizeSprite = NULL; delete prizeSprite; } void deletePrizeFromActivePrizes(sf::Sprite *prizeSprite, std::vector<sf::Sprite *> &activePrizes) { activePrizes.erase(std::remove(activePrizes.begin(), activePrizes.end(), prizeSprite), activePrizes.end()); deletePtr(prizeSprite); } void handlePrizeCollisionWithPlatform(sf::Sprite *prizeSprite, float &dt, int &lives, float &prizeStartTime, float &koeffOfPlatformExpansion, float &koeffOfBallSpeed, float &ballSpeed, std::vector<PrizeEffect> &prizeEffects, std::vector<sf::Sprite *> &activePrizes) { prizeStartTime = dt; PrizeType prizeType = getPrizeType(prizeSprite); applyPrizeEffect(prizeType, lives, koeffOfPlatformExpansion, koeffOfBallSpeed, ballSpeed); deletePrizeFromActivePrizes(prizeSprite, activePrizes); PrizeEffect effect; effect.prizeEffectType = getPrizeType(prizeSprite); effect.timeOfEffectApplying = 0; prizeEffects.push_back(effect); } void checkPrizeCollisionWithPlatform(float &dt, int &lives, float &prizeStartTime, float &koeffOfPlatformExpansion, float &koeffOfBallSpeed, float &ballSpeed, std::vector<PrizeEffect> &prizeEffects, std::vector<sf::Sprite *> &activePrizes) { const sf::FloatRect platformBounds = platform.getGlobalBounds(); for (sf::Sprite *prizeSprite : activePrizes) { const sf::FloatRect prizeBounds = prizeSprite->getGlobalBounds(); if (prizeBounds.intersects(platformBounds)) { handlePrizeCollisionWithPlatform(prizeSprite, dt, lives, prizeStartTime, koeffOfPlatformExpansion, koeffOfBallSpeed, ballSpeed, prizeEffects, activePrizes); } } } void checkPrizeMiss(std::vector<sf::Sprite *> &activePrizes) { for (sf::Sprite *prizeSprite : activePrizes) { const sf::FloatRect prizeBounds = prizeSprite->getGlobalBounds(); const sf::Vector2f currPrizeSpritePos = prizeSprite->getPosition(); if (currPrizeSpritePos.y + prizeBounds.height > BOTTOM) deletePrizeFromActivePrizes(prizeSprite, activePrizes); } } void updateFallingPrizes(float &dt, int &lives, float &prizeStartTime, float &koeffOfPlatformExpansion, float &koeffOfBallSpeed, float &ballSpeed, bool isPaused, std::vector<PrizeEffect> &prizeEffects, std::vector<sf::Sprite *> &activePrizes) { if (isPaused || gameState != playing) return; const float prizeSpeed = 40; for (sf::Sprite *prizeSprite : activePrizes) { sf::Vector2f currPos = prizeSprite->getPosition(); const float newYpos = currPos.y + dt * prizeSpeed; prizeSprite->setPosition(currPos.x, newYpos); } checkPrizeCollisionWithPlatform(dt, lives, prizeStartTime, koeffOfPlatformExpansion, koeffOfBallSpeed, ballSpeed, prizeEffects, activePrizes); checkPrizeMiss(activePrizes); } void undoEffect(PrizeType prizeType, float &koeffOfPlatformExpansion, float &koeffOfBallSpeed, float &ballSpeed) { switch (prizeType) { case expand_platform: koeffOfPlatformExpansion -= 0.35; if (koeffOfPlatformExpansion > 0) changePlatformSize(koeffOfPlatformExpansion); break; case accelerate_ball: koeffOfBallSpeed -= 0.35; if (koeffOfBallSpeed > 0) changeBallSpeed(ballSpeed, koeffOfBallSpeed); break; case slow_ball_down: koeffOfBallSpeed += 0.35; if (koeffOfBallSpeed < 2) changeBallSpeed(ballSpeed, koeffOfBallSpeed); break; } } void updatePrizeEffects(float &dt, float &koeffOfPlatformExpansion, float &koeffOfBallSpeed, float &ballSpeed, bool isPaused, std::vector<PrizeEffect> &prizeEffects) { if (isPaused || gameState != playing) return; for (int i = 0; i < prizeEffects.size(); i++) { const float effectTime = prizeEffects[i].timeOfEffectApplying; const float newEffectTime = effectTime + dt; prizeEffects[i].timeOfEffectApplying = newEffectTime; if (prizeEffects[i].timeOfEffectApplying > regularTimeOfPrizeEffect) { undoEffect(prizeEffects[i].prizeEffectType, koeffOfPlatformExpansion, koeffOfBallSpeed, ballSpeed); prizeEffects.erase(prizeEffects.begin() + i); } } } bool shouldLeaveGame() { return (gameState == quit || gameState == menu_screen || gameState == start_game); } updateArrOfTimeFromCollision(std::vector<float> *timeFromCollisionWithCrackedBrick, float dt) { for (auto it = timeFromCollisionWithCrackedBrick->begin(); it != timeFromCollisionWithCrackedBrick->end(); ++it) { if (*it == 0) { continue; } *it -= dt; if (*it <= 0) { (*it = 0); } } } void playGame(sf::RenderWindow &window) { sf::Sprite brick; std::vector<sf::Sprite *> activePrizes; std::map<PrizeType, sf::Sprite *> prizesSprites = { {expand_platform, &expandPlatformSprite}, {two_balls, &twoBallsSprite}, {slow_ball_down, &slowBallDownSprite}, {accelerate_ball, &accelerateBallSprite}, {extra_life, &extraLifeSprite}, {portal_door, &portalDoorSprite}, {sticky_ball, &stickyBallSprite}}; std::vector<PrizeEffect> prizeEffects; bool isPaused; int ballXdir; int ballYdir; float ballSpeed; int selectedModalItem = 1; resetVars(isPaused, prizeEffects, activePrizes); float prizeStartTime; float koeffOfPlatformExpansion = 1.0f; float koeffOfBallSpeed = 1.0f; sf::Sprite playerSprite = adjustPlayer(); sf::Text *levelPassedText = getLevelPassedText(); sf::RectangleShape livesDesignationBackgr = setLivesDesignationBackgr(); getBestScores(); background.setTexture(getBackgroundMainTexture()); adjustPlatform(); adjustBall(ballXdir, ballYdir, ballSpeed); adjustGameLostModal(); adjustSidebar(); loadPrizesTextures(); std::vector<Brick> bricks; float timeToShowLevelPassedMsg = 0; std::vector<float> timeFromCollisionWithCrackedBrick; sf::RectangleShape door = createDoor(); bool isBallStuck = false; float ballAngle = 45; int lives = 3; switch (level) { case 1: bricks = createBricksVector_1level({x : 70, y : 60}, &timeFromCollisionWithCrackedBrick, &brick, &prizesSprites); break; case 2: bricks = createBricksVector_2level({x : 65, y : 60}, &timeFromCollisionWithCrackedBrick, &brick, &prizesSprites); break; case 3: bricks = createBricksVector_3level({x : 65, y : 60}, &timeFromCollisionWithCrackedBrick, &brick, &prizesSprites); break; default: gameState = menu_screen; } sf::RectangleShape gameField = createGameField(); sf::Clock clock; while (window.isOpen()) { float dt = clock.restart().asSeconds(); pollEvents(window, dt, isBallStuck, isPaused, selectedModalItem); updateBall(ballSpeed, dt, bricks, &timeFromCollisionWithCrackedBrick, lives, timeToShowLevelPassedMsg, ballAngle, isBallStuck, ballXdir, ballYdir, isPaused, prizeEffects, activePrizes); updateFallingPrizes(dt, lives, prizeStartTime, koeffOfPlatformExpansion, koeffOfBallSpeed, ballSpeed, isPaused, prizeEffects, activePrizes); updateArrOfTimeFromCollision(&timeFromCollisionWithCrackedBrick, dt); updatePrizeEffects(dt, koeffOfPlatformExpansion, koeffOfBallSpeed, ballSpeed, isPaused, prizeEffects); //обновить время действия эффектов от призов recalcTimeToShowLevelPassedMsg(dt, timeToShowLevelPassedMsg, levelPassedText); redrawFrame(window, bricks, gameField, door, lives, playerSprite, livesDesignationBackgr, levelPassedText, prizeEffects, activePrizes); if (shouldLeaveGame()) { cout << "return" << endl; cout << gameState << endl; return; } } } //sf::Keyboard::isKeyPressed(sf::Keyboard::Space) : isGameStarted = true;
true
9bea3b64007c78a409412fba2d2b2e60451f3bc0
C++
i-love-falcom/ModelViewer
/Framework/FwCore/include/container/fw_array.h
UTF-8
5,430
3.0625
3
[ "MIT" ]
permissive
/** * @file fw_array.h * @author Kamai Masayoshi */ #ifndef FW_ARRAY_H_ #define FW_ARRAY_H_ #include "debug/fw_assert.h" BEGIN_NAMESPACE_FW template<typename _Ty, size_t _Num> class array { public: typedef array<_Ty, _Num> _My; typedef _Ty value_type; typedef size_t size_type; typedef ptrdiff_t defference_type; typedef value_type * pointer; typedef const value_type * const_pointer; typedef value_type & reference; typedef const value_type & const_reference; typedef pointer iterator; array() { } array(const _My & ref) { copy(*this, ref); } size_type size() const { return _Num; } size_type capacity() const { return _Num; } bool empty() const { return (_Num == 0); } void clear() { memset(buffer, 0, sizeof(buffer)); } reference at(size_type idx) { FwAssert(check_range(idx)); return buffer[idx]; } const_reference at(size_type idx) const { FwAssert(check_range(idx)); return buffer[idx]; } iterator begin() { return &buffer[0]; } iterator end() { return &buffer[size()]; } reference front() { return at(0); } const_reference front() const { return at(0); } reference back() { return at(size() - 1); } const_reference back() const { return at(size() - 1); } pointer data() { return buffer; } const_pointer data() const { return buffer; } void fill(const _Ty & value) { for (size_type i = 0; i < size(); ++i) { buffer[i] = value; } } void swap(const _My & other) { _Ty tmp; for (size_type i = 0; i < size(); ++i) { tmp = buffer[i]; buffer[i] = other.buffer[i]; other.buffer[i] = tmp; } } _Ty ** operator &() { return &buffer; } reference operator [](size_type idx) { return at(idx); } const_reference operator [](size_type idx) const { return at(idx); } const array<_Ty, _Num> & operator =(const array<_Ty, _Num> & ref) { copy(*this, ref); return *this; } private: bool check_range(size_type idx) { return (0 <= idx && idx < _Num); } void copy(const _My & dst, const _My & src) { for (size_type i = 0; i < size(); ++i) { dst[i] = src[i]; } } _Ty buffer[_Num == 0 ? 1 : _Num]; }; template<typename _Ty, size_t _Num, size_t _Align> class block_array { public: typedef block_array<_Ty, _Num, _Align> _My; typedef _Ty value_type; typedef size_t size_type; typedef ptrdiff_t defference_type; typedef value_type * pointer; typedef const value_type * const_pointer; typedef value_type & reference; typedef const value_type & const_reference; block_array() { } block_array(const _My & ref) { copy(*this, ref); } size_type size() const { return _Num; } size_type max_size() const { return _Num; } bool empty() const { return (_Num == 0); } void clear() { memset(buffer, 0, sizeof(buffer)); } reference at(size_type idx) { FwAssert(check_range(idx)); return ref(idx); } const_reference at(size_type idx) const { FwAssert(check_range(idx)); return ref(idx); } reference front() { return ref(0); } const_reference front() const { return ref(0); } reference back() { return ref(size() - 1); } const_reference back() const { return ref(size() - 1); } pointer data() { return buffer; } const_pointer data() const { return buffer; } void fill(const _Ty & value) { for (size_type i = 0; i < size(); ++i) { ref(i) = value; } } void swap(const _My & other) { _Ty tmp; for (size_type i = 0; i < size(); ++i) { tmp = ref(i); ref(i) = other.ref(i); other.ref(i) = tmp; } } _Ty ** operator &() { return &buffer; } reference operator [](size_type idx) { return at(idx); } const_reference operator [](size_type idx) const { return at(idx); } const array<_Ty, _Num> & operator =(const array<_Ty, _Num> & ref) { copy(*this, ref); return *this; } private: bool check_range(size_type idx) { return (0 <= idx && idx < _Num); } void copy(const _My & dst, const _My & src) { for (size_type i = 0; i < size(); ++i) { dst[i] = src[i]; } } reference ref(size_type idx) { return buffer[((sizeof(_Ty) + (_Align - 1)) & ~(_Align - 1)) * idx]; } const_reference ref(size_type idx) const { return buffer[((sizeof(_Ty) + (_Align - 1)) & ~(_Align - 1)) * idx]; } unsigned char buffer[((sizeof(_Ty) + (_Align - 1)) & ~(_Align - 1)) * (_Num == 0 ? 1 : _Num)]; }; END_NAMESPACE_FW #endif // FW_ARRAY_H_
true
3045299d26c6cfe7345af343d69a7d9de41af7c0
C++
scpp/metafactor
/variadic_typelist.h
UTF-8
2,259
2.953125
3
[ "MIT" ]
permissive
/*************************************************************************** * Copyright (C) 2015 by Vladimir Mirnyy, blog.scpp.eu * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the MIT License * ***************************************************************************/ #ifndef __variadic_typelist_h #define __variadic_typelist_h /** \file \brief compile-time list of types based on variadic templates from C++11 */ #include <type_traits> // A class template that just a list of types: template <class... T> struct typelist { }; template <typename TList> struct get_first; template <typename T, typename ...List> struct get_first<typelist<T,List...>> { typedef T type; }; template <typename T> struct get_first<typelist<T>> { typedef T type; }; template <> struct get_first<typelist<>> { typedef typelist<> type; }; template <typename List1, typename List2> struct typelist_cat; template <typename ...List1, typename ...List2> struct typelist_cat<typelist<List1...>, typelist<List2...>> { using type = typelist<List1..., List2...>; }; template <typename T, typename ...List2> struct typelist_cat<T, typelist<List2...>> { using type = typelist<T, List2...>; }; template <typename T, typename ...List1> struct typelist_cat<typelist<List1...>,T> { using type = typelist<List1... ,T>; }; template<typename List> struct typelist_out; template<typename T, typename ...Args> struct typelist_out<typelist<T, Args...> > { static void print(std::ostream& os = std::cout, const char sep = '\t') { os << T::value << sep; typelist_out<typelist<Args...>>::print(os, sep); } }; template<typename T1, typename T2, typename ...Args> struct typelist_out<typelist<pair_<T1,T2>, Args...> > { static void print(std::ostream& os = std::cout, const char sep = '\t') { os << T1::value << "^" << T2::value << sep; typelist_out<typelist<Args...>>::print(os, sep); } }; template<> struct typelist_out<typelist<>> { static void print(std::ostream& os = std::cout, const char sep = '\t') { os << std::endl; } }; #endif
true
51a30b420dc0ca516cf0f5f9924e596f7fe6641f
C++
Omegastick/bots
/src/networking/server_communicator.h
UTF-8
465
2.515625
3
[]
no_license
#pragma once #include <memory> #include <string> #include "third_party/zmq.hpp" #include "third_party/zmq_addon.hpp" namespace ai { struct MessageWithId { std::string id; std::string message; }; class ServerCommunicator { private: std::unique_ptr<zmq::socket_t> socket; public: ServerCommunicator(std::unique_ptr<zmq::socket_t> socket); MessageWithId get(); void send(const std::string &client_id, const std::string &message); }; }
true
0e19ed7f0c8229b88595e054606284c1fb0739ba
C++
hrisbh10/Array-Class-Cpp
/Array.cpp
UTF-8
520
3.578125
4
[]
no_license
//Program demonstrating Array class #include "Array.h" #include <iostream> using namespace std; int main(){ Array<int> a; //empty array for(int i=0;i<7;++i) a.push_back(i+1); //O(1) for(int i=0;i<7;++i) cout<<a[i]<<" "; //accessing time O(log(i)) cout<<'\n'; a.pop_back(); //O(1) cout<<a.back()<<"\n"; //O(1) a.push_back(8); //O(1) or O(2*prev) for(int i=0;i<7;++i) cout<<a[i]<<" "; Array<int> b(7); cout<<'\n'; for(int i=0;i<7;++i){ b[i] = 2*i+1; } for(int i=0;i<7;++i) cout<<b[i]<<" "; }
true
a4ca76633367337750ede187af9f8388293f08fe
C++
chamow97/Interview-Prep
/leetcode/1410. HTML Entity Parser.cpp
UTF-8
1,041
2.875
3
[ "MIT" ]
permissive
class Solution { public: string getString(string str) { if(str == "&quot;") { return "\""; } else if(str == "&apos;") { return "'"; } else if(str == "&amp;") { return "&"; } else if(str == "&gt;") { return ">"; } else if(str == "&lt;") { return "<"; } else if(str == "&frasl;") { return "/"; } else { return str; } } string entityParser(string str) { string ans = ""; int i = 0; int n = str.length(); while(i < n) { while(i < n && str[i] != '&') { ans += (str[i]); i++; } string curr = ""; while(i < n && str[i] != ';' && str[i] != ' ') { curr += str[i]; i++; } if(i < n) { curr += str[i]; } ans += getString(curr); i++; } return ans; } };
true
f151edb6e14f7ef212dcb001c003bf269e4382f3
C++
stefan2904/sweb
/common/include/mm/PageManager.h
UTF-8
2,524
3.28125
3
[]
no_license
/** * @file PageManger.h */ #ifndef PAGEMANAGER_H__ #define PAGEMANAGER_H__ #include "types.h" #include "paging-definitions.h" #include "new.h" #include "kernel/Mutex.h" typedef uint8 puttype; #define PAGE_RESERVED static_cast<puttype>(1<<0) #define PAGE_KERNEL static_cast<puttype>(1<<1) #define PAGE_USERSPACE static_cast<puttype>(1<<2) #define PAGE_4_PAGES_16K_ALIGNED static_cast<puttype>(1<<3) #define PAGE_FREE static_cast<puttype>(0) /** * @class PageManager is in issence a BitMap managing free or used pages of size PAGE_SIZE only */ class PageManager { public: /** * Creates a new instance (and THE ONLY ONE) of our page manager * This one will also automagically initialise itself accordingly * i.e. mark pages used by the kernel already as used * @param next_usable_address Pointer to memory the page manager can use * @return 0 on failure, otherwise a pointer to the next free memory location */ static void createPageManager (); /** * the access method to the singleton instance * @return the instance */ static PageManager *instance() {return instance_;} /** * returns the number of 4k Pages avaible to sweb. * ((size of the first usable memory region or max 1Gb) / PAGESIZE) * @return number of avilable pages */ uint32 getTotalNumPages() const; /** * returns the number of the next free Physical Page * and marks that Page as used. * @param type can be either PAGE_USERSPACE (default) or PAGE_KERNEL * (passing PAGE_RESERVED or PAGE_FREE would obviously not make much sense, * since the page then either can neve be free'd again or will be given out * again) */ uint32 getFreePhysicalPage ( uint32 type = PAGE_USERSPACE ); //also marks page as used /** * marks physical page <page_number> as free, if it was used in * user or kernel space. * @param page_number Physcial Page to mark as unused */ void freePage ( uint32 page_number ); private: /** * the singleton constructor * @param start_of_structure the start address of the memory after the page manager */ PageManager (); /** * Copy Constructor * must not be implemented */ PageManager ( PageManager const& ); //PageManager &operator=(PageManager const&){}; static PageManager* instance_; puttype *page_usage_table_; uint32 number_of_pages_; uint32 lowest_unreserved_page_; Mutex lock_; }; #endif
true
f0e4f9adfd7776cbf7a36a8deef3cc03547257e6
C++
vivekmaurya1505/CPP
/CPP/Codes/Day7/35. Template for Function swap.cpp
UTF-8
3,247
3.96875
4
[]
no_license
#include<iostream> #include<cstring> // or #include<string.h> using namespace std; namespace NTemplate { template <class Type> void swap(Type &n1, Type &n2) { Type temp; temp=n1; n1=n2; n2=temp; } class Complex { private: int real; int imag; public: //void AcceptInputFromConsole(Complex * const this) // c1.AcceptInputFromConsole(); this=&c1; // c2.AcceptInputFromConsole(); this=&c2; //1.1 input void AcceptInputFromConsole() { cout<<"Enter Real :: "; cin>>this->real; cout<<"Enter Imag :: "; cin>>this->imag; } //void PrintOutputOnConsole(className * const this) //void PrintOutputOnConsole(Complex * const this) //c1.PrintOutputOnConsole(); this=&c1; //c2.PrintOutputOnConsole(); this=&c2; // 1.2 output void PrintOutputOnConsole() { cout<<"Real ::"<<this->real<<" [ "<< &this->real<<" ] "<<endl; cout<<"Imag ::"<<this->imag<<" [ "<< &this->imag<<" ] "<<endl; } //void SetReal(Complex * const this,int real) //2.0 mutator methods --> setter method they modify state of object void SetReal(int real) { this->real=real; } //void SetImag(Complex * const this,int imag) void SetImag(int imag) { this->imag=imag; } //3.0 Inspectors -> getter methods // dont modify state of object //int GetReal(Complex * const this) int GetReal() { return this->real; } //int GetImag(Complex * const this) int GetImag() { return this->imag; } //4.1 parameter less ctor Complex() { this->real=10; this->imag=20; //cout<<"inside parameterless ctor of Complex class"<<endl; } //4.2 parameterized less ctor with 2 arguments Complex(int real, int imag) { this->real=real; this->imag=imag; //cout<<"inside parameterized ctor of Complex class"<<endl; } // dtor ~Complex() { this->real=0; this->imag=0; //cout<<"Inside dtor of Complex class"<<endl; } };// end class complex } using namespace NTemplate; int main() { { int no1=10, no2=20; cout<<"data type :: int"<<endl; cout<<"before swap no1="<<no1<<" no2="<<no2<<endl; NTemplate::swap(no1, no2); cout<<"after swap no1="<<no1<<" no2="<<no2<<endl; } cout<<"================================"<<endl; { float no1=10.2, no2=20.1; cout<<"data type :: float"<<endl; cout<<"before swap no1="<<no1<<" no2="<<no2<<endl; NTemplate::swap(no1, no2); cout<<"after swap no1="<<no1<<" no2="<<no2<<endl; } cout<<"================================"<<endl; { char no1='A', no2='B'; cout<<"data type :: char"<<endl; cout<<"before swap no1="<<no1<<" no2="<<no2<<endl; NTemplate::swap(no1, no2); cout<<"after swap no1="<<no1<<" no2="<<no2<<endl; } cout<<"================================"<<endl; { Complex c1(11,22), c2(33,44); cout<<"data type :: Complex"<<endl; cout<<"before swap :: "<<endl; cout<<"c1 ::"<<endl; c1.PrintOutputOnConsole(); cout<<"c2 ::"<<endl; c2.PrintOutputOnConsole(); NTemplate::swap(c1, c2); cout<<"After swap :: "<<endl; cout<<"c1 ::"<<endl; c1.PrintOutputOnConsole(); cout<<"c2 ::"<<endl; c2.PrintOutputOnConsole(); } cout<<"================================"<<endl; return 0; }
true
5af59fd6797cc7f6e5474e7becaa655e9f11ce54
C++
munish-b/IA-Hardware-Composer
/tests/hwc-val/tests/hwc/hwcharness/HwchReplayRunner.h
UTF-8
2,150
2.5625
3
[]
no_license
/* // Copyright (c) 2018 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. */ #ifndef __HwchReplayRunner_h__ #define __HwchReplayRunner_h__ #include "HwchInterface.h" #include "HwchTest.h" #include "HwchReplayLayer.h" #include "HwchReplayParser.h" namespace Hwch { class ReplayRunner : public Test { protected: /** The base class owns the parser instance. */ std::unique_ptr<ReplayParser> mParser; /** Reference to the HWC interface. */ Hwch::Interface& mInterface; /** RAII file handle. */ std::ifstream mFile; /** * Set to true if the replay file has been opened and the regex * compilation has been successful. */ bool mReplayReady = false; public: /** * @name ReplayRunner * @brief Base class constructor. * * @param interface Reference to the Hardware Composer interface. * @param filename File to replay (typically from command line). * * @details Handles file opening and dynamically allocates an instance * of the parser. */ ReplayRunner(Hwch::Interface& interface, const char* filename); /** Returns whether the replay file was opened successfully. */ bool IsReady() { return mReplayReady; } /** Virtual function to print individual 'runner' statistics. */ virtual void PrintStatistics(void) { std::printf("No replay statistics implemented for this runner\n"); } /** Empty virtual destructor. */ virtual ~ReplayRunner() = default; /** Runs the regular expression unit tests for the parser. */ bool RunParserUnitTests(void) { return mParser->RunParserUnitTests(); } }; } #endif // __HwchReplayRunner_h__
true
cce86e1ebf3c14ef924763506c0a8070c1e83ee9
C++
rcsunanda/cpp_learn
/segfault.cpp
UTF-8
190
2.75
3
[]
no_license
//g++ -g segfault.cpp -o segfault #include <stdio.h> int main() { char* temp = "Paras"; int i; i=0; temp[3]='F'; for (i =0 ; i < 5 ; i++ ) printf("%c\n", temp[i]); return 0; }
true
98e4ef10495c1144c4ca32efde21ee214f67179f
C++
BruceLuuc/CS-Basic
/LeetCode/15. 3Sum.cpp
GB18030
2,321
3.15625
3
[]
no_license
#include"x.h" //ύĴ //жnums.size()С //vectorȥerase //map[gap]Ҫj class Solution_3_1 { public: vector<vector<int>> threeSum(vector<int>& nums) { vector<vector<int>>result; if (nums.size() < 3) return result; unordered_map<int, int>_map; sort(nums.begin(), nums.end()); for (int i=0;i!=nums.size();++i) { _map[nums[i]] = i; } for (int i = 0; i != nums.size()-1; ++i) { if (i > 0 && nums[i - 1] == nums[i]) continue; for (int j = i+1 ; j != nums.size()-1; ++j) { const int gap = 0 - nums[i] - nums[j]; if (_map.find(gap) != _map.end()&&_map[gap]>j)//map[gap]Ҫj>= { result.push_back({ nums[i], nums[j], gap}); } } } result.erase(unique(result.begin(), result.end()), result.end()); return result; } }; //ȻҼб class Solution_3_2 { public: vector<vector<int>> threeSum(vector<int>& nums) { vector<vector<int>> result; if (nums.size() < 3) return result; sort(nums.begin(), nums.end()); const int target = 0; auto last = nums.end(); /* ''' X Y Z ''' i j k '''last-3 last-2 last-1 last(β) */ for (auto i = nums.begin(); i < last - 2; ++i) { //֮󣬱ųȵ //ȣֱųtargetж if (i > nums.begin() && *i == *(i - 1)) continue;//һѭһȣ auto k = last - 1; auto j = i + 1; while (j < k) { if (*i + *j + *k < target) { ++j; while (*j == *(j - 1) && j < k) ++j;//һǰһ֮ǰֵ֮䣬*i + *j + *kֵҲ䣬ҪһСΧjǰ++j } else if (*i + *j + *k > target) { --k; while (*k == *(k + 1) && j < k) --k; } else { result.push_back({ *i, *j, *k }); ++j; --k; while (*j == *(j - 1) && *k == *(k + 1) && j < k) ++j; } } } return result; } }; int main_15() { Solution_3_1 A; vector<int>a = { 1,2,-2,-1 ,5,1,1,-1,-2,3,-4};//{ 0,0,0 }; auto result = A.threeSum(a); for (auto i : result) { print_vector(i); } system("pause"); return 0; }
true
52deaa169f803a4a51beeddf05a05bb3e9bd968f
C++
danwahl/solar-fan
/solar-fan/solar-fan.ino
UTF-8
4,653
2.828125
3
[]
no_license
#include <avr/sleep.h> #include <avr/wdt.h> #include <avr/power.h> // hardware definitions #define VBAT_PIN A0 // also reset pin #define VBAT_SLOPE 3.24889 // x/1e3 = (y - x)/2.2e3 + (5 - x)/45e3 #define VBAT_OFFSET -0.244444 #define VBAT_MIN 10.8f #define VBAT_NOM 11.8f // should be greater than VBAT_MIN #define FAN_IN_PIN A3 #define FAN_OUT_PIN 0 #define LED_IN_PIN A2 #define LED_OUT_PIN 1 #define USB_OUT_PIN 2 // system states enum {RUN, LOWBAT}; // global vars float vbat; unsigned fan_in, led_in, fan_out, led_out, usb_out, state; /*************************************************************************** * watchdog timer isr **************************************************************************/ ISR(WDT_vect) { } /*************************************************************************** * setup **************************************************************************/ void setup() { // set tmr0 pwm frequency to 8e6/2^8/psc TCCR0B &= ~(_BV(CS01) | _BV(CS02)); TCCR0B |= _BV(CS00); // disable tim0 interrupts TIMSK &= ~(_BV(OCIE0A) | _BV(OCIE0B) | _BV(TOIE0)); // usb out pin setup pinMode(USB_OUT_PIN, OUTPUT); // disable outputs analogWrite(FAN_OUT_PIN, 0); analogWrite(LED_OUT_PIN, 0); digitalWrite(USB_OUT_PIN, LOW); // go to run state = RUN; } /***************************************************************************u * loop **************************************************************************/ void loop() { // read inputs vbat = ((float)analogRead(VBAT_PIN)*5.0f/1023.0f)*VBAT_SLOPE + VBAT_OFFSET; fan_in = analogRead(FAN_IN_PIN); led_in = analogRead(LED_IN_PIN); /*// map inputs to outputs fan_out = map(fan_in, 0, 1023, 0, 255); led_out = map(led_in, 0, 1023, 0, 255); usb_out = HIGH; // write outputs analogWrite(FAN_OUT_PIN, fan_out); analogWrite(LED_OUT_PIN, led_out); digitalWrite(USB_OUT_PIN, usb_out); // idle for a bit sleep_system(SLEEP_MODE_IDLE, WDTO_1S); //delay(1000);*/ switch (state) { case (RUN): // check if vbat below min voltage threshold if (vbat < VBAT_MIN) { // set outputs fan_out = led_out = 0; usb_out = LOW; // disable outputs analogWrite(FAN_OUT_PIN, fan_out); analogWrite(LED_OUT_PIN, led_out); digitalWrite(USB_OUT_PIN, usb_out); // set state state = LOWBAT; // sleep for a while sleep_system(SLEEP_MODE_PWR_DOWN, WDTO_8S); } else { // map inputs to outputs fan_out = map(fan_in, 0, 1023, 0, 255); led_out = map(led_in, 0, 1023, 0, 255); usb_out = HIGH; // write outputs analogWrite(FAN_OUT_PIN, fan_out); analogWrite(LED_OUT_PIN, led_out); digitalWrite(USB_OUT_PIN, usb_out); // idle for a bit //delay(100); sleep_system(SLEEP_MODE_IDLE, WDTO_1S); } break; case (LOWBAT): // back to run if vbat nominal if (vbat >= VBAT_NOM) { state = RUN; // idle for a bit //delay(100); sleep_system(SLEEP_MODE_IDLE, WDTO_1S); } // otherwise sleep again else sleep_system(SLEEP_MODE_PWR_DOWN, WDTO_8S); break; default: state = RUN; break; } } /*************************************************************************** * sleep system **************************************************************************/ void sleep_system(unsigned mode, unsigned wdto) { // disable peripherals power_timer1_disable(); power_adc_disable(); // set sleep mode set_sleep_mode(mode); sleep_enable(); // set watchdog and sleep setup_watchdog(wdto); sleep_mode(); // zzzzz... (sleeping here) // disable sleep sleep_disable(); // enable peripherals power_adc_enable(); power_timer1_enable(); } /*************************************************************************** * watchdog setup **************************************************************************/ void setup_watchdog(unsigned wdto) { // Limit incoming amount to legal settings if (wdto > WDTO_8S) wdto = WDTO_8S; // Set the special 5th bit if necessary byte bb = wdto & 0x07; if (wdto > 7) bb |= (1 << 5); MCUSR &= ~(1 << WDRF); // Clear the watchdog reset WDTCR |= (1 << WDCE) | (1 << WDE); // Set WD_change enable, set WD enable WDTCR = bb; // Set new watchdog timeout value WDTCR |= _BV(WDIE); // Set the interrupt enable, this will keep unit from resetting after each int }
true
379ffdb6d96a08ea95e793d4af2fb66ca8d190ac
C++
zlewisdigipen/physicsengine
/3Dphysics/PhysicsEngine/PhysicsEngine/mesh.h
UTF-8
804
2.9375
3
[]
no_license
#pragma once #ifndef MESH_H #define MESH_H #include <glm/glm.hpp> #include <GL/glew.h> #include <vector> class Vertex { public: Vertex() { pos = glm::vec3(0.0f, 0.0f, 0.0f); } Vertex(const glm::vec3 & pos) { this->pos = pos; } glm::vec3* GetPos() { return &pos; } void SetPos(const glm::vec3 vec) { pos = vec; } private: glm::vec3 pos; }; class Mesh { public: Mesh() { draw_count = 0; } Mesh(Vertex* verts, unsigned int num_verts, unsigned int* indices, unsigned int num_indices); ~Mesh(); void Draw(); std::vector<glm::vec3> GetShape() { return shape_points; } private: enum { POSITION_VB, INDEX_VB, NUM_BUFFERS }; std::vector<glm::vec3> shape_points; GLuint vertex_objs; GLuint vertex_buff[NUM_BUFFERS]; unsigned int draw_count; }; #endif // !MESH_H
true
07a500227bad697dcfb5e5cb0bf74214eec18d77
C++
Duonghailee/Cpp-Programming-
/week6/4.cpp
UTF-8
374
3.21875
3
[]
no_license
#include <iostream> #include <fstream> using namespace std; int main() { char c; ifstream fromfile("A.txt"); ofstream tofile("B.txt"); if (fromfile.is_open()) { while (fromfile.get(c)) { tofile << c; } tofile.close(); fromfile.close(); } cout << "Copying successfully" << endl; return 0; }
true
1b883d3605b990bf2b4577e5553fd6d3094dd5b5
C++
mhuisi/lean4
/src/library/abstract_type_context.h
UTF-8
1,638
2.734375
3
[ "Apache-2.0" ]
permissive
/* Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #pragma once #include "kernel/expr.h" namespace lean { class abstract_type_context { public: virtual ~abstract_type_context() {} virtual environment const & env() const = 0; virtual expr whnf(expr const & e) = 0; virtual name next_name() = 0; virtual expr relaxed_whnf(expr const & e) { return whnf(e); } virtual bool is_def_eq(expr const & e1, expr const & e2) = 0; virtual bool relaxed_is_def_eq(expr const & e1, expr const & e2) { return is_def_eq(e1, e2); } virtual expr infer(expr const & e) = 0; /** \brief Simular to \c infer, but also performs type checking. \remark Default implementation just invokes \c infer. */ virtual expr check(expr const & e) { return infer(e); } virtual optional<expr> is_stuck(expr const &) { return none_expr(); } virtual optional<name> get_local_pp_name(expr const & e) = 0; virtual expr push_local(name const & pp_name, expr const & type, binder_info bi = mk_binder_info()); virtual void pop_local(); expr check(expr const & e, bool infer_only) { return infer_only ? infer(e) : check(e); } }; class push_local_fn { abstract_type_context & m_ctx; unsigned m_counter; public: push_local_fn(abstract_type_context & ctx):m_ctx(ctx), m_counter(0) {} ~push_local_fn(); expr operator()(name const & pp_name, expr const & type, binder_info bi = mk_binder_info()) { m_counter++; return m_ctx.push_local(pp_name, type, bi); } }; }
true
d5ef229dd17de35d8c8cf94b7100fa19af209f57
C++
dasguptar/pytorch
/aten/src/ATen/native/LinearAlgebra.cpp
UTF-8
6,933
2.71875
3
[ "BSD-2-Clause" ]
permissive
#include "ATen/ATen.h" #include "ATen/ExpandUtils.h" #include "ATen/NativeFunctions.h" #include <functional> #include <numeric> #include <vector> namespace at { namespace native { // For backward, we save svd. // http://www.ics.forth.gr/cvrl/publications/conferences/2000_eccv_SVD_jacobian.pdf // But instead of gesvd SVD A = U(A) Sig(A) V(A)^T, which doesn't specify signs // of determinants of U and V, we consider det(A) = \prod Sig_(A), where // 1. A = U_(A) Sig_(A) V(A)^T // 2. Sig_(A) and U_(A) can be different in signs in first row/col from // their counterparts so that U_(A) * V_(A) have +1 determinant std::tuple<Tensor, Tensor, Tensor, Tensor> _det_with_svd(const Tensor& self) { if (!at::isFloatingType(self.type().scalarType()) || self.dim() != 2 || self.size(0) != self.size(1)) { std::ostringstream ss; ss << "det(" << self.type() << "{" << self.sizes() << "}): expected a 2D " << "square tensor of floating types"; throw std::runtime_error(ss.str()); } // check symmetric bool symmetric = self.equal(self.transpose(0, 1)); auto svd = self.svd(true); auto sigma = std::get<1>(svd); auto u = std::get<0>(svd); auto v = std::get<2>(svd); auto det = sigma.prod(); if (!symmetric) { auto qr = self.geqrf(); auto a = std::get<0>(qr); auto tau = std::get<1>(qr); // non-zero values in tau represent Householder reflectors, which has -1 det int64_t num_reflectors = tau.nonzero().size(0); auto qr_det = a.diag().prod(); if (num_reflectors % 2 == 1) { qr_det = -qr_det; } det = qr_det; // QR is more stable than svd, so use it anyways if ((qr_det < 0).any() ^ (det < 0).any()) { // if different sign u.narrow(1, 0, 1).mul_(-1); sigma.narrow(0, 0, 1).mul_(-1); } } return std::make_tuple(det, u, sigma, v); } Tensor det(const Tensor& self) { return std::get<0>(self._det_with_svd()); } static Tensor maybeSqueeze(const Tensor & tensor, int64_t dim_tensor1, int64_t dim_tensor2) { if (dim_tensor1 == 1) { return tensor.squeeze(-2); } else if (dim_tensor2 == 1) { return tensor.squeeze(-1); } else { return tensor; } } /* Matrix product of two Tensors. The behavior depends on the dimensionality of the Tensors as follows: - If both Tensors are 1-dimensional, the dot product (scalar) is returned. - If both arguments are 2-dimensional, the matrix-matrix product is returned. - If the first argument is 1-dimensional and the second argument is 2-dimensional, a 1 is prepended to its dimension for the purpose of the matrix multiply. After the matrix multiply, the prepended dimension is removed. - If the first argument is 2-dimensional and the second argument is 1-dimensional, the matrix-vector product is returned. - If both arguments are at least 1-dimensional and at least one argument is N-dimensional (where N > 2), then a batched matrix multiply is returned. If the first argument is 1-dimensional, a 1 is prepended to its dimension for the purpose of the batched matrix multiply and removed after. If the second argument is 1-dimensional, a 1 is appended to its dimension for the purpose of the batched matrix multiple and removed after. The non-matrix (i.e. batch) dimensions are broadcasted (and thus must be broadcastable). For example, if tensor1 is a (j x 1 x n x m) Tensor and tensor2 is a (k x m x p) Tensor, the returned tensor will be an (j x k x n x p) Tensor. */ Tensor matmul(const Tensor & tensor1, const Tensor & tensor2) { auto dim_tensor1 = tensor1.dim(); auto dim_tensor2 = tensor2.dim(); if (dim_tensor1 == 1 && dim_tensor2 == 1) { return tensor1.dot(tensor2); } else if (dim_tensor1 == 2 && dim_tensor2 == 1) { return tensor1.mv(tensor2); } else if (dim_tensor1 == 1 && dim_tensor2 == 2) { return tensor1.unsqueeze(0).mm(tensor2).squeeze_(0); } else if (dim_tensor1 == 2 && dim_tensor2 == 2) { return tensor1.mm(tensor2); } else if (dim_tensor1 >= 3 && (dim_tensor2 == 1 || dim_tensor2 == 2)) { // optimization: use mm instead of bmm by folding tensor1's batch into // its leading matrix dimension. Tensor t2 = dim_tensor2 == 1 ? tensor2.unsqueeze(-1) : tensor2; auto size1 = tensor1.sizes(); auto size2 = t2.sizes(); std::vector<int64_t> output_size; output_size.insert(output_size.end(), size1.begin(), size1.end() - 1); output_size.insert(output_size.end(), size2.end() - 1, size2.end()); // fold the batch into the first dimension Tensor t1 = tensor1.contiguous().view({-1, size1[size1.size() - 1]}); auto output = t1.mm(t2).view(output_size); if (dim_tensor2 == 1) { output = output.squeeze(-1); } return output; } else if ((dim_tensor1 >= 1 && dim_tensor2 >= 1) && (dim_tensor1 >= 3 || dim_tensor2 >= 3)) { // We are multiplying b1 x n x m1 by x2 x m2 x p (where b1 can be a list); // we track m1 vs m2 separately even though they must match for nicer error messages int64_t n = dim_tensor1 > 1 ? tensor1.size(-2) : 1; int64_t m1 = tensor1.size(-1); IntList batch_tensor1(tensor1.sizes().data(), std::max<int64_t>(dim_tensor1 - 2, 0)); int64_t m2 = dim_tensor2 > 1 ? tensor2.size(-2) : 1; int64_t p = tensor2.size(-1); IntList batch_tensor2(tensor2.sizes().data(), std::max<int64_t>(dim_tensor2 - 2, 0)); // expand the batch portion (i.e. cut off matrix dimensions and expand rest) std::vector<int64_t> expand_batch_portion = infer_size(batch_tensor1, batch_tensor2); std::vector<int64_t> tensor1_expand_size(expand_batch_portion); tensor1_expand_size.insert(tensor1_expand_size.end(), {n, m1}); std::vector<int64_t> tensor2_expand_size(expand_batch_portion); tensor2_expand_size.insert(tensor2_expand_size.end(), {m2, p}); int expand_batch_product = std::accumulate(expand_batch_portion.begin(), expand_batch_portion.end(), 1, std::multiplies<int64_t>()); std::vector<int64_t> tensor1_bmm_view({expand_batch_product}); tensor1_bmm_view.insert(tensor1_bmm_view.end(), {n, m1}); std::vector<int64_t> tensor2_bmm_view({expand_batch_product}); tensor2_bmm_view.insert(tensor2_bmm_view.end(), {m2, p}); // flatten expanded batches Tensor tensor1_expanded = tensor1.expand(tensor1_expand_size).contiguous().view(tensor1_bmm_view); Tensor tensor2_expanded = tensor2.expand(tensor2_expand_size).contiguous().view(tensor2_bmm_view); Tensor output = tensor1_expanded.bmm(tensor2_expanded); // reshape batches back into result std::vector<int64_t> total_expansion(expand_batch_portion); total_expansion.insert(total_expansion.end(), {n, p}); return maybeSqueeze(output.view(total_expansion), dim_tensor1, dim_tensor2); } runtime_error("both arguments to matmul need to be at least 1D, but they are %dD and %dD", dim_tensor1, dim_tensor2); } } }
true
34225198b8e1c9250704d8aced8399f29b5f8914
C++
achallion/cpptopics
/hashing/longestsubarrwithsumk.cpp
UTF-8
659
2.828125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int longestsubsumk(int *arr, int n, int k) { int pre = 0; int maxl = 0; unordered_map<int, int> fi; for (int i = 0; i < n; i++) { pre += arr[i]; if (arr[i] == k) maxl = max(maxl, 1); if (pre == k) maxl = max(maxl, i + 1); if (fi.count(pre) == 0) { fi[pre] = i; } if (fi.count(pre - k) != 0) { maxl = max(maxl, i - fi[pre - k]); } } return maxl; } int main() { int a[] = {6, -1, 0, 2, -1}; int n = 5; cout << longestsubsumk(a, n, 0); return 0; }
true
13cccedcfe382dc9da3e05c0ddb7f7dd85c46a52
C++
FluffyDou/HangDou
/ToyRayTracer/Core/Camera.h
UTF-8
1,916
3.078125
3
[]
no_license
/******************************************************************/ /* Camera.h */ /* ------------- */ /* */ /* The file defines the camera class for the ray tracer. The */ /* Important functions are the constructor, and the */ /* GenerateRay() method. GenerateRay() takes pixel coords */ /* (either integer or pixel) and returns a vector from the */ /* eye (at the point 'eye') through that pixel in the image. */ /* Camera() takes in the eye point, look at point, an up */ /* vector, field of view, and the image resolution. */ /* */ /* Chris Wyman (10/26/2006) */ /******************************************************************/ #ifndef CAMERA_H #define CAMERA_H #include "DataTypes/datatypes.h" #include "Core/Ray.h" #include "DataTypes/MathDefs.h" #include <iostream> #include <math.h> class Scene; class Camera { // Store the camera a way we like to think about it (and OpenGL does) vec3 eye, at, up; float fovy; // Store the screen size int screenWidth, screenHeight; // Store the camera in an easy-to-use format for ray tracing vec3 U, V, W; public: // sets up a camera Camera( const vec3 &eye, const vec3 &at, const vec3 &up, float fovy, int screenWidth, int screenHeight ); // generate a ray based on previous set camera parameters vec3 GenerateRay( float x, float y ); // accessor functions inline vec3 GetEye( void ) const { return eye; } inline int GetScreenWidth( void ) const { return screenWidth; } inline int GetScreenHeight( void ) const { return screenHeight; } void SetScreenRatio(int w, int h); }; #endif
true
ad0074c145fca6a97bf977b7ee62f7724b8e6377
C++
Jeffrey-P-McAteer/ros_object_recognition
/src/shape_detector/include/shape_detector/normal_estimation_groupbox.h
UTF-8
1,669
2.875
3
[ "MIT" ]
permissive
/** \file * \brief Definition of the NormalEstimationGroupBox class. */ #ifndef SHAPE_DETECTOR_NORMAL_ESTIMATION_GROUPBOX_H #define SHAPE_DETECTOR_NORMAL_ESTIMATION_GROUPBOX_H // Qt. #include <QGroupBox> class QWidget; class QLabel; class QSpinBox; class QHBoxLayout; namespace shape_detector { class ObservedParameterManager; /** \brief QGroupBox for accessing the parameters of a ShapeDetector that are * related to the estimation of normals. */ class NormalEstimationGroupBox : public QGroupBox { Q_OBJECT public: /** \brief Creates and initializes the GroupBox. * * \param[in] parent Pointer to QWidget that serves as a parent of the * GroupBox. */ explicit NormalEstimationGroupBox(QWidget* parent = nullptr); /** \brief Updates the view of the GroupBox so that it displays the current * values of the parameters. */ void update() const; /** \brief Sets the parameter-manager of the ShapeDetector. * * The ObservedParameterManager manages the parameters of a ShapeDetector * object. * The manager represents the Model of the MVC-pattern, while the GroupBox * represents the View and the Controller. */ void setParameterManager(ObservedParameterManager* detector); private slots: void requestNumNearestNeighborsChange(int val) const; private: void createNearestNeighborsLabel(); void createNearestNeighborsSpinBox(); QHBoxLayout* createMainLayout() const; // Data members. ObservedParameterManager* param_manager_ {nullptr}; QLabel* nearest_neighbors_label_; QSpinBox* nearest_neighbors_spinbox_; }; } // shape_detector #endif // SHAPE_DETECTOR_NORMAL_ESTIMATION_GROUPBOX_H
true
53bb8565ae40c61eb524305f2279c336205cc8c0
C++
qiqzhang/CPP-Data-Structures-and-Algorithms
/Chapter02/Doubly_Linked_List/include/DoublyLinkedList.h
UTF-8
7,875
3.890625
4
[ "MIT" ]
permissive
// Project: Doubly_Linked_List.cbp // File : DoublyLinkedList.h 双向链表 有双向节点构成的 双向索引链条 在插入/删除节点时需要考虑 设置前继和后继节点的指针 #ifndef DOUBLYLINKEDLIST_H #define DOUBLYLINKEDLIST_H #include <iostream> #include "DoublyNode.h" template <typename T> class DoublyLinkedList { private: // 私有数据 int m_count;// 双向节点 数量记录 public: // 双向链表头 DoublyNode<T> * Head; // 双向链表尾 DoublyNode<T> * Tail; // 构造函数=========== DoublyLinkedList(); // 获取指定索引上的双向节点 Get() operation DoublyNode<T> * Get(int index); // 双向链表插入操作 Insert() operation void InsertHead(T val);// 表头插入 void InsertTail(T val);// 表尾插入 void Insert(int index, T val);// 普通插入函数 //查找数据信息 Search() operation int Search(T val); // 双向链表删除节点操作 Remove() operation void RemoveHead(); void RemoveTail(); void Remove(int index); // 附加操作 Additional operation int Count(); // 计数 void PrintList(); // 正向打印 双向链表 void PrintListBackward();// 反向打印 双向链表 // 从尾节点 依次找 前继节点 反向遍历链表== }; // 构造函数=========== DoublyLinkedList<T>:: 前置 所有关系 template <typename T> DoublyLinkedList<T>::DoublyLinkedList() : m_count(0), Head(NULL), Tail(NULL) {} template <typename T> DoublyNode<T> * DoublyLinkedList<T>::Get(int index) { // 指定位置索引 范围检查 if(index < 0 || index > m_count) return NULL; // 从头结点开始遍历 DoublyNode<T> * node = Head; // 遍历到指定 index处 for(int i = 0; i < index; ++i) { node = node->Next; // 0,...,index-1 } // Simply return the node result return node; } // 表头插入节点================================== template <typename T> void DoublyLinkedList<T>::InsertHead(T val) { // 新建节点 DoublyNode<T> * node = new DoublyNode<T>(val); // 连接处 互相指向===========each other====== // 新节点的后继 指向原 链表表头 node->Next = Head; // 如果原 头结点存在,则原头结点的 前继 需要指向 新节点(作为新表头) if(Head != NULL) Head->Previous = node; // 新节点 重置为 链表表头 Head = node; // 如果链表中只有一个节点,那么 表尾 == 表头 if(m_count == 0) Tail = Head; // One element is added m_count++; } // 表尾插入节点============================= template <typename T> void DoublyLinkedList<T>::InsertTail(T val) { // 链表为空时,和表头插入一致 if(m_count == 0) { InsertHead(val); return; } // 新建一个节点 DoublyNode<T> * node = new DoublyNode<T>(val); // 原尾节点 的 后继 设置为 新节点 // 注意需要双向关联 Tail->Next = node; // 新节点的 前继 设置为 原尾节点 node->Previous = Tail; // 新节点 重置为 链表的 尾节点 Tail = node; // 数量++ m_count++; } template <typename T> void DoublyLinkedList<T>::Insert(int index, T val) { // 插入位置 范围检查 if(index < 0 || index > m_count) return; // 在头部插入==== if(index == 0) { InsertHead(val); return; } // 在尾部插入===== else if(index == m_count) { InsertTail(val); return; } // 目标位置的 前置节点 DoublyNode<T> * prevNode = Head; // 遍历到 前置节点 for(int i = 0; i < index - 1; ++i) { prevNode = prevNode->Next; // 0,...,index-2 } // 后置节点 DoublyNode<T> * nextNode = prevNode->Next;//0,...,index-1 // 创建一个新的节点 DoublyNode<T> * node = new DoublyNode<T>(val); // 需要重新设置4个指向====== // prevNode----> node ------>nextNode // prevNode<---- node <----- nextNode node->Next = nextNode; // 1. node ------>nextNode node->Previous = prevNode; // 2. prevNode<---- node prevNode->Next = node; // 3. prevNode----> node nextNode->Previous = node; // 4. node <----- nextNode // One element is added m_count++; } template <typename T> int DoublyLinkedList<T>::Search(T val) { // 链表为空 if(m_count == 0) return -1; // 找到的位置 int index = 0; // 从头结点开始遍历 DoublyNode<T> * node = Head; // 找到指定值 while(node->Value != val) { index++; node = node->Next; // 直到找到 链表尾部 if(node == NULL) { return -1; } } return index; } template <typename T> void DoublyLinkedList<T>::RemoveHead() { // Do nothing if list is empty if(m_count == 0) return; // 原 链表头 DoublyNode<T> * node = Head; // 原 链表头后继 设置为 新链表头 Head = Head->Next; // 删除原链表头 delete node; // 设置 表头前置 节点为 NULL if(Head != NULL) Head->Previous = NULL; // 数量-- m_count--; } template <typename T> void DoublyLinkedList<T>::RemoveTail() { // Do nothing if list is empty if(m_count == 0) return; // If List element is only one // just simply call RemoveHead() if(m_count == 1) { RemoveHead(); return; } // 原表尾节点 DoublyNode<T> * node = Tail; // 可以反向遍历 找到 原表尾节点的 前置节点,并设置为 新的表尾节点 Tail = Tail->Previous; // 表尾节点的后继设置为 NULL Tail->Next = NULL; // 删除原 链表表尾节点 delete node; // 数量-- m_count--; } template <typename T> void DoublyLinkedList<T>::Remove(int index) { // Do nothing if list is empty if(m_count == 0) return; // Do nothing if index is out of bound if(index < 0 || index >= m_count) return; // If removing the current Head if(index == 0) { RemoveHead(); return; } // If removing the current Tail else if(index == m_count - 1) { RemoveTail(); return; } // 指定位置 的 前置节点 DoublyNode<T> * prevNode = Head; for(int i = 0; i < index - 1; ++i) { prevNode = prevNode->Next; // 0,...,index-2 } // 需要删除的 目标节点 DoublyNode<T> * node = prevNode->Next; // 0,...,index-1 // 目标节点 后 的 后置节点 DoublyNode<T> * nextNode = node->Next; // 0,...,index // 新增两个指向 前置节点 ----> 后置节点 // 前置节点 <---- 后置节点 prevNode->Next = nextNode; // 前置节点 ----> 后置节点 nextNode->Previous = prevNode; // 前置节点 <---- 后置节点 // 删除目标节点 delete node; // 数量-- m_count--; } template <typename T> int DoublyLinkedList<T>::Count() { return m_count; } template <typename T> void DoublyLinkedList<T>::PrintList() { DoublyNode<T> * node = Head; while(node != NULL) { std::cout << node->Value << " -> "; node = node->Next; } std::cout << "NULL" << std::endl; } template <typename T> void DoublyLinkedList<T>::PrintListBackward() { // 从尾节点 依次找 前继节点 反向遍历链表== DoublyNode<T> * node = Tail; while(node != NULL) { std::cout << node->Value << " -> "; node = node->Previous; } std::cout << "NULL" << std::endl; } #endif // DOUBLYLINKEDLIST_H
true
67939b0de5e03b1124074794a3ab2e06d9d24479
C++
vivekpisal/450-problem-solving
/11th.cpp
UTF-8
499
3.203125
3
[]
no_license
#include<iostream> #include<algorithm> using namespace std; bool bsearch(int a[],int start,int end,int ser) { int mid=(start+end)/2; while(start>end) { if(a[mid]==ser) { return true; } else if(a[mid]>ser) { end=start-1; mid=(start+end)/2; } else if(a[mid]<ser) { start=end+1; mid=(start+end)/2; } } return false; } int main() { int nums[]={1,3,4,2,2}; for(int i=0;i<5;i++) { if(bsearch(nums,i+1,4,nums[i])) { cout<<nums[i]<<" "; } } return 0; }
true
063939a69190aa6a82d89ca254918837a0939876
C++
lxq2537664558/Leetcode-1
/122. Best Time to Buy and Sell Stock II.cpp
UTF-8
817
3.578125
4
[]
no_license
//Say you have an array for which the ith element is the price of a given stock on day i. // //Design an algorithm to find the maximum profit.You may complete as many transactions as you like(ie, buy one and sell one share of the stock multiple times).However, you may not engage in multiple transactions at the same time(ie, you must sell the stock before you buy again). #include <iostream> #include <vector> #include <algorithm> #include <string> #include <unordered_set> #include <unordered_map> #include <numeric> #include <stack> #include <map> #include <list> using namespace std; int maxProfit(vector<int>& prices) { int result = 0; for (int i = 1; i < prices.size(); ++i) result += max(prices[i] - prices[i - 1], 0); return result; } void main() { vector<int> test{ 1, 2, 3 }; maxProfit(test); }
true
3ef523d15330ba3a0815ab20d89af33c8dc19679
C++
a62625536/ACM
/zhedamuke/树的同构.cpp
UTF-8
1,560
2.765625
3
[]
no_license
#include<iostream> #include<map> #include<cstdio> #include<string> using namespace std; struct node { char left,right; friend bool operator==(node &x,node &y) { return x.left==y.left&&x.right==y.right || x.left==y.right&&x.right==y.left; } }; map<char,node> mp1,mp2; char a1[10] = {0},a2[10] = {0}; int has[128] = {0}; int main() { int n,m; char str[10]; scanf("%d",&n); getchar(); for(int i = 0;i < n;i++) { gets(str); mp1[str[0]].left = str[2]; mp1[str[0]].right = str[4]; a1[i] = str[0]; has[str[0]] = 1; } scanf("%d",&m); getchar(); for(int i = 0;i < m;i++) { gets(str); mp2[str[0]].left = str[2]; mp2[str[0]].right = str[4]; a2[i] = str[0]; has[str[0]] = 1; } if(m != n) cout << "No" << endl; else if(m == 0 || n == 0) cout << "Yes" << endl; else { int flag = 1; for(char i = 'A';i <= 'Z';i++) { if(!has[i]) continue; if(mp1[i].left!= '-') mp1[i].left = a1[mp1[i].left-'0']; if(mp1[i].right!= '-') mp1[i].right = a1[mp1[i].right-'0']; if(mp2[i].left!= '-') mp2[i].left = a2[mp2[i].left-'0']; if(mp2[i].right!= '-') mp2[i].right = a2[mp2[i].right-'0']; if(mp1[i] == mp2[i]) continue; else { flag = 0; break; } } if(flag) cout << "Yes" << endl; else cout << "No" << endl; } return 0; }
true
8cf434cbd329a8975b9990dca051bcc4ca69dcba
C++
namyoungu/baekjoon
/백준 2675번 문자열 반복.cpp
UTF-8
396
2.765625
3
[]
no_license
#include<stdio.h> int main(void){ int n, c, cnt; char arr[1001]; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &c); scanf("%s", arr); cnt = 0; while (1) { if (arr[cnt] == '\0') { break; } cnt += 1; } for (int j = 0; j < cnt; j++) { for (int k = 0; k < c; k++) { printf("%c", arr[j]); } } puts(""); } return 0; }
true
01cb45f4b0936439f7ae240a1c5e059180c16e87
C++
hoangpq/Evolving-Snakes
/sources/ctrRandomEvolving.cpp
UTF-8
1,383
2.84375
3
[ "MIT" ]
permissive
#include "../headers/ctrRandomEvolving.h" #include "../headers/decision.h" #include "../headers/randomisation.h" #include<stdlib.h> std::string ctrRandomEvolving::getType() { return "randomEvolving"; } std::vector<double> ctrRandomEvolving::getValues() { return {turn_left_probability,turn_right_probability,split_probability}; } void ctrRandomEvolving::setValues(std::vector<double>& values) { turn_left_probability=values[0]; turn_right_probability=values[1]; split_probability=values[2]; } ctrRandomEvolving* ctrRandomEvolving::clone() { return new ctrRandomEvolving(*this); } void ctrRandomEvolving::randomise() { randomiseVariable(turn_left_probability,0,1); randomiseVariable(turn_right_probability,0,1); randomiseVariable(split_probability,0,1); } void ctrRandomEvolving::mutate() { mutateVariable(turn_left_probability,0,1); mutateVariable(turn_right_probability,0,1); mutateVariable(split_probability,0,1); } decision ctrRandomEvolving::think() { decision decision; decision.turn_right=(rand()%1000)/1000.0<turn_left_probability; decision.turn_left=(rand()%1000)/1000.0<turn_right_probability; if (body_length>0) { decision.split=(rand()%1000)/1000.0<split_probability; decision.split_length=rand()%body_length; } else { decision.split=0; } return decision; }
true
997ec96b757fae6da6a801dc6cb80ad7f09313e0
C++
Stonerdk/onlinejudge
/p17471.cpp
UTF-8
3,319
2.765625
3
[]
no_license
#include <iostream> #include <string> #include <queue> #include <map> #include <cstring> using namespace std; int N, row, col; const int MAX = 102; char** board; bool visited[MAX][MAX]; int treasure = 0; void bfs(int i, int j); bool isValid(int i, int j); bool key[26]; class Door { private: map<char, vector<pair<int, int>>> data; public: void add(char c, int i, int j); void open(char c); void clear(); }; void Door::add(char c, int i, int j) { if (data.find(c) == data.end()) { vector<pair<int, int>> temp; temp.push_back(make_pair(i, j)); data.insert(make_pair(c, temp)); } else { data[c].push_back(make_pair(i, j)); } }; void Door::open(char c) { if (data.find(c) != data.end()) { for (auto p : data[c]) { board[p.first][p.second] = '.'; } } } void Door::clear() { data.clear(); } Door door; void bfs(int i, int j) { queue<pair<int, int>> q; q.push(pair<int, int>(i, j)); while (!q.empty()) { int x = q.front().first; int y = q.front().second; q.pop(); if (!isValid(x, y)) continue; char& c = board[x][y]; if (visited[x][y] || c == '*') continue; if (c >= 'A' && c <= 'Z') continue; if (c >= 'a' && c <= 'z') { if (key[c - 'a'] == false) { key[c - 'a'] = true; door.open(c + 'A' - 'a'); c = '.'; memset(visited, false, sizeof(visited)); /*for (; !q.empty(); q.pop()); q.push(make_pair(i, j)); continue;*/ } } else if (c == '$') { treasure += 1; c = '.'; } visited[x][y] = true; q.push(pair<int, int>(x + 1, y)); q.push(pair<int, int>(x - 1, y)); q.push(pair<int, int>(x, y + 1)); q.push(pair<int, int>(x, y - 1)); } } bool isValid(int i, int j) { return i >= 0 && i < row + 2 && j >= 0 && j < col + 2; } int main() { cin >> N; vector<int> answer; string currentkey; for (int i = 0; i < N; i++) { cin >> row >> col; board = new char* [row + 2]; for (int j = 0; j < row + 2; j++) { board[j] = new char[col + 2]; board[j][0] = '.'; if (j == 0 || j == row + 1) { for (int k = 1; k <= col; k++) { board[j][k] = '.'; } } else { for (int k = 1; k <= col; k++) { cin >> board[j][k]; if (board[j][k] >= 'A' && board[j][k] <= 'Z') door.add(board[j][k], j, k); } } board[j][col + 1] = '.'; } memset(key, false, sizeof(key)); memset(visited, false, sizeof(visited)); cin >> currentkey; for (char c : currentkey) { door.open(c + 'A' - 'a'); } bfs(0, 0); for (int j = 0; j < row + 2; j++) delete[] board[j]; delete[] board; currentkey = ""; answer.push_back(treasure); treasure = 0; door.clear(); } for (int a : answer) { cout << a << endl; } }
true
5d65bbf1d3ce3bef12a6212c38ce61b60b0087d8
C++
ThePhysicsGuys/Physics3D
/tests/testsMain.h
UTF-8
7,198
2.703125
3
[ "MIT" ]
permissive
#pragma once #include "compare.h" #include <Physics3D/misc/toString.h> #include <sstream> class TestInterface { size_t assertCount = 0; public: bool debugOnFailure; TestInterface() : debugOnFailure(false) {} TestInterface(bool debugOnFailure) : debugOnFailure(debugOnFailure) {} inline void markAssert() { assertCount++; } inline size_t getAssertCount() const { return assertCount; } }; enum class TestType { NORMAL, SLOW }; #define __JOIN2(a,b) a##b #define __JOIN(a,b) __JOIN2(a,b) #define TEST_CASE(func) void func(); static TestAdder __JOIN(tAdder, __LINE__)(__FILE__, #func, func, TestType::NORMAL); void func() #define TEST_CASE_SLOW(func) void func(); static TestAdder __JOIN(tAdder, __LINE__)(__FILE__, #func, func, TestType::SLOW); void func() struct TestAdder { TestAdder(const char* filePath, const char* nameName, void(*testFunc)(), TestType isSlow); }; class AssertionError { const char* info; public: int line; AssertionError(int line, const char* info); const char* what() const noexcept; }; void logf(const char* format, ...); extern std::stringstream logStream; extern thread_local TestInterface __testInterface; extern const bool reffableTrue; // Testing utils: template<typename R, typename P> const char* errMsg(const R& first, const P& second, const char* sep) { std::stringstream s; s << first; s << ' '; s << sep; s << '\n'; s << second; std::string msg = s.str(); const char* data = msg.c_str(); char* dataBuf = new char[msg.size() + 1]; for(int i = 0; i < msg.size() + 1; i++) dataBuf[i] = data[i]; return dataBuf; } template<typename R> const char* errMsg(const R& first) { std::stringstream s; s << "("; s << first; s << ")"; std::string msg = s.str(); const char* data = msg.c_str(); char* dataBuf = new char[msg.size() + 1]; for(int i = 0; i < msg.size() + 1; i++) dataBuf[i] = data[i]; return dataBuf; } #ifdef _MSC_VER #define __DEBUG_BREAK __debugbreak(); #else #define __DEBUG_BREAK #endif #define __ASSERT_FAILURE(line, printText) if(__testInterface.debugOnFailure) {__DEBUG_BREAK} throw AssertionError(line, printText) template<typename T> class AssertComparer { public: const int line; const T& arg; AssertComparer(int line, const T& arg) : line(line), arg(arg) {} template<typename P> AssertComparer<bool> operator<(const P& other) const { if(!(arg < other)) { __ASSERT_FAILURE(line, errMsg(arg, other, "<")); }; return AssertComparer<bool>(this->line, reffableTrue); } template<typename P> AssertComparer<bool> operator>(const P& other) const { if(!(arg > other)) { __ASSERT_FAILURE(line, errMsg(arg, other, ">")); }; return AssertComparer<bool>(this->line, reffableTrue); } template<typename P> AssertComparer<bool> operator<=(const P& other) const { if(!(arg <= other)) { __ASSERT_FAILURE(line, errMsg(arg, other, "<=")); }; return AssertComparer<bool>(this->line, reffableTrue); } template<typename P> AssertComparer<bool> operator>=(const P& other) const { if(!(arg >= other)) { __ASSERT_FAILURE(line, errMsg(arg, other, ">=")); }; return AssertComparer<bool>(this->line, reffableTrue); } template<typename P> AssertComparer<bool> operator==(const P& other) const { if(!(arg == other)) { __ASSERT_FAILURE(line, errMsg(arg, other, "==")); }; return AssertComparer<bool>(this->line, reffableTrue); } template<typename P> AssertComparer<bool> operator!=(const P& other) const { if(!(arg != other)) { __ASSERT_FAILURE(line, errMsg(arg, other, "!=")); }; return AssertComparer<bool>(this->line, reffableTrue); } }; template<typename T, typename Tol> class TolerantAssertComparer { public: const int line; const T& arg; const Tol tolerance; TolerantAssertComparer(int line, const T& arg, Tol tolerance) : line(line), arg(arg), tolerance(tolerance) {} template<typename T2> TolerantAssertComparer<bool, Tol> operator<(const T2& other) const { if(!tolerantLessThan(arg, other, tolerance)) { __ASSERT_FAILURE(line, errMsg(arg, other, "<")); }; return TolerantAssertComparer<bool, Tol>(this->line, reffableTrue, this->tolerance); } template<typename T2> TolerantAssertComparer<bool, Tol> operator>(const T2& other) const { if(!tolerantGreaterThan(arg, other, tolerance)) { __ASSERT_FAILURE(line, errMsg(arg, other, ">")); }; return TolerantAssertComparer<bool, Tol>(this->line, reffableTrue, this->tolerance); } template<typename T2> TolerantAssertComparer<bool, Tol> operator<=(const T2& other) const { if(!tolerantLessOrEqual(arg, other, tolerance)) { __ASSERT_FAILURE(line, errMsg(arg, other, "<=")); }; return TolerantAssertComparer<bool, Tol>(this->line, reffableTrue, this->tolerance); } template<typename T2> TolerantAssertComparer<bool, Tol> operator>=(const T2& other) const { if(!tolerantGreaterOrEqual(arg, other, tolerance)) { __ASSERT_FAILURE(line, errMsg(arg, other, ">=")); }; return TolerantAssertComparer<bool, Tol>(this->line, reffableTrue, this->tolerance); } template<typename T2> TolerantAssertComparer<bool, Tol> operator==(const T2& other) const { if(!tolerantEquals(arg, other, tolerance)) { __ASSERT_FAILURE(line, errMsg(arg, other, "==")); }; return TolerantAssertComparer<bool, Tol>(this->line, reffableTrue, this->tolerance); } template<typename T2> TolerantAssertComparer<bool, Tol> operator!=(const T2& other) const { if(!tolerantNotEquals(arg, other, tolerance)) { __ASSERT_FAILURE(line, errMsg(arg, other, "!=")); }; return TolerantAssertComparer<bool, Tol>(this->line, reffableTrue, this->tolerance); } }; struct AssertBuilder { int line; AssertBuilder(int line) : line(line) {}; template<typename T> AssertComparer<T> operator<(const T& other) const { return AssertComparer<T>(line, other); } }; template<typename Tol> struct TolerantAssertBuilder { int line; Tol tolerance; TolerantAssertBuilder(int line, Tol tolerance) : line(line), tolerance(tolerance) {}; template<typename T> TolerantAssertComparer<T, Tol> operator<(const T& other) const { return TolerantAssertComparer<T, Tol>(line, other, tolerance); } }; #define ASSERT_STRICT(condition) do {if(!(AssertBuilder(__LINE__) < condition).arg) {__ASSERT_FAILURE(__LINE__, "false");}__testInterface.markAssert(); }while(false) #define ASSERT_TOLERANT(condition, tolerance) do {if(!(TolerantAssertBuilder<decltype(tolerance)>(__LINE__, tolerance) < condition).arg) {__ASSERT_FAILURE(__LINE__, "false");} __testInterface.markAssert(); }while(false) #define ASSERT_TRUE(condition) do {if(!(condition)) {__ASSERT_FAILURE(__LINE__, "false");}__testInterface.markAssert(); }while(false) #define ASSERT_FALSE(condition) do {if(condition) {__ASSERT_FAILURE(__LINE__, "true");}__testInterface.markAssert(); }while(false) #define PREV_VAL_NAME __JOIN(____previousValue, __LINE__) #define ISFILLED_NAME __JOIN(____isFilled, __LINE__) #define REMAINS_CONSTANT_STRICT(value) do{\ static bool ISFILLED_NAME = false;\ static auto PREV_VAL_NAME = value;\ if(ISFILLED_NAME) ASSERT_STRICT(PREV_VAL_NAME == (value));\ ISFILLED_NAME = true;\ }while(false) #define REMAINS_CONSTANT_TOLERANT(value, tolerance) do{\ static bool ISFILLED_NAME = false;\ static auto PREV_VAL_NAME = value;\ if(ISFILLED_NAME) ASSERT_TOLERANT(PREV_VAL_NAME == (value), tolerance);\ ISFILLED_NAME = true;\ }while(false)
true
f237239fbd1e7fc42dbf299ceb2e85e091b3b093
C++
Juantamayo26/Train
/ICPC/ukiepc2020problems/kleptocrat/submissions/accepted/ragnar-no-erase.cpp
UTF-8
1,428
2.5625
3
[]
no_license
#include <cassert> #include <iostream> #include <vector> using namespace std; int main() { int n, m, q; cin >> n >> m >> q; vector<vector<pair<int, long long>>> g(n); while(m--) { int u, v; long long w; cin >> u >> v >> w; --u, --v; g[u].push_back({v, w}); g[v].push_back({u, w}); } // -1 if not visited yet; xor of path from root to here otherwise. vector<vector<long long>> done(64, vector<long long>(n, -1)); vector<bool> bip(64, false); for(int i = 63; i >= 0; --i) { auto b = 1ll << i; auto& d = done[i]; // Check whether the graph of edges containing b is bipartite. auto dfs = [&](int u, const auto& dfs) -> bool { assert(d[u] != -1); for(auto [v, w] : g[u]) { auto dv = d[u] ^ w; if(d[v] == -1) { d[v] = dv; if(not dfs(v, dfs)) return false; } else if(auto wc = d[v] ^ dv; wc & b) { // Found a cycle! // g[u].erase(v); // g[v].erase(u); // all edges containing b are xor'ed with wc. for(auto& s : g) for(auto& [v2, w2] : s) if(w2 & b) w2 ^= wc; return false; } } return true; }; d[0] = 0; bip[i] = dfs(0, dfs); } while(q--) { int x, y; cin >> x >> y; --x, --y; long long w = 0; for(int i = 63; i >= 0; --i) { if(not bip[i]) continue; auto xc = done[i][x]; auto yc = done[i][y]; assert(xc != -1 and yc != -1); w += (xc ^ yc) & (1ll << i); } cout << w << endl; } }
true
db88a5f99a296967f14ecca71dec765f1e47d4f9
C++
Uiroon/Uir
/2019-2020 C++课设/源代码/Keshe/Function4.h
GB18030
3,223
3.609375
4
[]
no_license
#pragma once class Function4 { public: int find(vector<int> vec, int target) { int low = 0, high = vec.size() - 1; while (low < high) { int mid = (high + low) / 2; if (target < vec[mid]) { high = mid - 1; } else if (target > vec[mid]) { low = mid + 1; } else { return mid; } } return -1; } static bool comp(const int& c1, const int& c2) { return c1 < c2; } Function4() { //==================˳=================== vector<int> oderList; int oderListLength; int oderListInputtmp; system("cls"); cout << "==================˳==================" << endl ; do { cout << "ijȣ"; cin >> oderListLength; } while (oderListLength <= 0); for (int i = 0; i < oderListLength; i++) { cout << "" << i + 1 << "Ԫأ"; cin >> oderListInputtmp; oderList.push_back(oderListInputtmp); } sort(oderList.begin(), oderList.end(), comp); cout << "------------------------------------------" << endl; cout << "˳еΪ" << endl; for (vector<int>::iterator it = oderList.begin(); it < oderList.end(); it++) { cout << *it << " "; } cout << endl; random_shuffle(oderList.begin(), oderList.end()); cout << "------------------------------------------" << endl; cout << "ҺеΪ" << endl; for (vector<int>::iterator it = oderList.begin(); it < oderList.end(); it++) { cout << *it << " "; } cout << endl; BTree<int> bt = BTree<int>(); for (vector<int>::iterator it = oderList.begin(); it < oderList.end(); it++) { bt.Insert(bt.getRoot(), *it); } cout << "------------------------------------------" << endl; cout << "ǰΪ"; bt.PreOrder(bt.getRoot()); cout << endl<<"Ϊ"; bt.InOrder(bt.getRoot()); cout << endl<<"պΪ"; bt.PostOrder(bt.getRoot()); cout << endl; cout << "------------------------------------------" << endl; cout << "ҪɾԪأ"; cin >> oderListInputtmp; bt.Delete(bt.getRoot(), oderListInputtmp); cout << "------------------------------------------" << endl; cout << "ɾǰΪ"; bt.PreOrder(bt.getRoot()); cout << endl<<"ɾΪ"; bt.InOrder(bt.getRoot()); cout << endl<<"ɾպΪ"; bt.PostOrder(bt.getRoot()); cout << endl; sort(oderList.begin(), oderList.end(), comp); cout << "------------------------------------------" << endl; cout << "˳еΪ" << endl; for (vector<int>::iterator it = oderList.begin(); it < oderList.end(); it++) { cout << *it << " "; } cout << endl; cout << "------------------------------------------" << endl; cout << "Ҫҵݣ"; cin >> oderListInputtmp; int loc; loc = find(oderList, oderListInputtmp); cout << "" << oderListInputtmp << "ڵǰ˳ĵ" << loc + 1 << "λ" << endl; system("pause"); } };
true
b29d388b3243d39ac3bb4efd8d3ad6224393b990
C++
talentlyb/Leetcode
/c++/135.cpp
UTF-8
631
3.140625
3
[]
no_license
/** First time. 4/28/2015 * * Two passes. */ class Solution { public: int candy(vector<int>& ratings) { vector<int> number (ratings.size(), 1); int result = 0; for (int i = 1; i < number.size(); ++i) { if (ratings[i-1] < ratings[i]) { number[i] = number[i-1] + 1; } } for (int i = number.size()-1; i > 0; --i) { if (ratings[i-1] > ratings[i]) { number[i-1] = max(number[i-1], number[i]+1); } } for (int i = 0; i < number.size(); ++i) { result += number[i]; } return result; } };
true
67a77022c4f973ed3717731e90f884c235ab2a89
C++
VFVrPQ/2017ACM
/codeforces/cf849/B.cpp
UTF-8
1,670
2.921875
3
[]
no_license
/* author : VFVrPQ problem : cf849-B , 判断所有的(i,a[i])能否被两条平行线覆盖,其中每条线至少要覆盖一个点。 solve : 1.第一个点要么是单独的一个点,要么是在一条线上,依此搞一搞;2.考虑前三个点,三者情况分别考虑O(n) time : 2017-09-03-17.31.51 */ #include<bits/stdc++.h> using namespace std; typedef long long LL; const int M = 1e9+7; const int N = 1e4+10; struct Node{ int x,y; Node(){} Node(int x,int y):x(x),y(y){} friend Node operator - (const Node&a,const Node&b){ return Node(a.x-b.x,a.y-b.y); } }; vector<Node> a; LL cj(Node i,Node j){ return (LL)i.x*j.y-(LL)i.y*j.x; } int main(){ int n;scanf("%d",&n); for (int i=0;i<n;i++){ int x;scanf("%d",&x); a.emplace_back(i,x); } vector<int> V1; for (int my=0;my<2;my++){ for (int i=0;i<n;i++)if (i!=my){ V1.clear(); int flag=1; for (int j=0;j<n;j++)if(i!=j && my!=j){ if (cj(a[i]-a[my],a[j]-a[my])!=0){ if (V1.size()<2) { V1.push_back(j); if (V1.size()==2){ if (cj(a[i]-a[my],a[V1[1]]-a[V1[0]])!=0){ flag=0;break; } } } else { if (cj(a[V1[1]]-a[V1[0]],a[j]-a[V1[0]])!=0){ flag=0;break; } } } } //printf("%d\n",i); if (flag && V1.size()>0){puts("YES");return 0;} } } puts("NO"); return 0; }
true
1cfb98fdaa038d7aa780356915c76534a7b149b5
C++
tyagiakash926/level-up-jun
/lectur_01/l003.cpp
UTF-8
12,669
2.875
3
[]
no_license
#include <iostream> #include <vector> using namespace std; int permutationINFI(vector<int> &arr,int idx,int tar,string ans) { if(tar==0) { cout<<ans<<endl; return 1; } int count =0; for(int i=idx;i<arr.size();i++) { if(tar-arr[i]>=0) count+=permutationINFI(arr,0,tar-arr[i],ans+to_string(arr[i])+" "); } return count; } int combinationINFI(vector<int> &arr,int idx,int tar,string ans) { if(tar==0) { cout<<ans<<endl; return 1; } int count =0; for(int i=idx;i<arr.size();i++) { if(tar-arr[i]>=0) count+=combinationINFI(arr,i,tar-arr[i],ans+to_string(arr[i])+" "); } return count; } int combinationSingle(vector<int> &arr,int idx,int tar,string ans) { if(tar==0) { cout<<ans<<endl; return 1; } int count =0; for(int i=idx;i<arr.size();i++) { if(tar-arr[i]>=0) count+=combinationSingle(arr,i+1,tar-arr[i],ans+to_string(arr[i])+" "); } return count; } int permutationSingle(vector<int> &arr,int idx,int tar,string ans) { if(tar==0) { cout<<ans<<endl; return 1; } int count =0; for(int i=idx;i<arr.size();i++) { if(arr[i]>0 && tar-arr[i]>=0) { int temp = arr[i]; arr[i]=-arr[i]; count+=permutationSingle(arr,0,tar-temp,ans+to_string(temp)+" "); arr[i]=-arr[i]; } } return count; } //=======================================================================================> int combinationSingle_sub(vector<int> &arr,int idx,int tar,string ans) { if(tar==0 || idx==arr.size()) { if(tar==0) { cout<<ans<<endl; return 1; } return 0; } int count =0; if(tar-arr[idx]>=0) count+=combinationSingle_sub(arr,idx+1,tar-arr[idx],ans+to_string(arr[idx])+" "); count+=combinationSingle_sub(arr,idx+1,tar,ans); return count; } int combinationINFI_subseq(vector<int> &arr, int idx, int tar, string ans) { if (tar == 0 || idx == arr.size()) { if (tar == 0) { cout << ans << endl; return 1; } return 0; } int count = 0; if (tar - arr[idx] >= 0) count += combinationINFI_subseq(arr,idx , tar - arr[idx], ans + to_string(arr[idx]) + " "); count += combinationINFI_subseq(arr,idx+1, tar, ans); return count; } int permutationINFI_subseq(vector<int> &arr, int idx, int tar, string ans) { if (tar == 0 || idx == arr.size()) { if (tar == 0) { cout << ans << endl; return 1; } return 0; } int count = 0; if (tar - arr[idx] >= 0) count += permutationINFI_subseq(arr,0 , tar - arr[idx], ans + to_string(arr[idx]) + " "); count += permutationINFI_subseq(arr, idx + 1, tar, ans); return count; } int permutationSingleCoin_subseq(vector<int> &arr, int idx, int tar, string ans) { if (tar == 0 || idx == arr.size()) { if (tar == 0) { cout << ans << endl; return 1; } return 0; } int count = 0; if (arr[idx] >= 0 && tar - arr[idx] >= 0) { int temp = arr[idx]; arr[idx] = -arr[idx]; count += permutationSingleCoin_subseq(arr,0 , tar - temp, ans + to_string(temp) + " "); arr[idx] = -arr[idx]; } count += permutationSingleCoin_subseq(arr, idx + 1, tar, ans); return count; } //================================================================================================> int queenCombination_1D(vector<bool> &boxes,int tnq,int idx,int qpsf,string ans) { if(tnq == qpsf) { cout<<ans<<endl; return 1; } int count=0; for(int i=idx;i<boxes.size();i++) { count+=queenCombination_1D(boxes,tnq,i+1,qpsf+1,ans+"("+"b"+to_string(i)+" "+"q"+to_string(qpsf)+")"); } return count; } int queenCombination_1D_subseq(vector<bool> &boxes,int tnq,int idx,int qpsf,string ans) { if(tnq==qpsf || idx==boxes.size()) { if(tnq==qpsf) { cout<<ans<<endl; return 1; } return 0; } int count = 0; count+=queenCombination_1D_subseq(boxes,tnq,idx+1,qpsf+1,ans+"("+"b"+to_string(idx)+" "+"q"+to_string(qpsf)+")"); count+=queenCombination_1D_subseq(boxes,tnq,idx+1,qpsf,ans); return count; } int queenPermutation_1D(vector<bool> &boxes,int tnq,int idx,int qpsf,string ans) { if(tnq == qpsf) { cout<<ans<<endl; return 1; } int count =0; for(int i=idx;i<boxes.size();i++) { if(!boxes[i]) { boxes[i]=true; count+=queenPermutation_1D(boxes,tnq,0,qpsf+1,ans + "b" + to_string(i) + "q" + to_string(qpsf) + " "); boxes[i]=false; } } return count; } int queenPermutation_1D_subseq(vector<bool> &boxes,int tnq,int idx,int qpsf,string ans) { if (tnq == qpsf || idx == boxes.size()) { if (tnq == qpsf) { cout << ans << endl; return 1; } return 0; } int count = 0; if (!boxes[idx]) { boxes[idx]=true; count += queenPermutation_1D_subseq(boxes,tnq,0,qpsf+1,ans + "b" + to_string(idx) + "q" + to_string(qpsf) + " "); boxes[idx]=false; } count += queenPermutation_1D_subseq(boxes,tnq,idx+1,qpsf, ans); return count; } //==================================================================================== int queen_Combination_2D(vector<vector<bool>> &boxes,int tnq, int idx, int qpsf, string ans) { if(tnq==qpsf) { cout<<ans<<endl; return 1; } int count=0; for(int i=idx;i<boxes.size()*boxes.size();i++) { int r = i/boxes[0].size(); int c = i%boxes[0].size(); count+=queen_Combination_2D(boxes,tnq,i+1,qpsf+1, ans + "(" + to_string(r) + "," + to_string(c) + ")"); } return count; } int queenPermutation_2D(vector<vector<bool>> &boxes, int tnq, int idx, int qpsf, string ans) // tnq is equal to target. { if (qpsf == tnq) { cout << ans << endl; return 1; } int count = 0; for (int i = idx; i < boxes.size() * boxes[0].size(); i++) { int r = i / boxes[0].size(); int c = i % boxes[0].size(); if (!boxes[r][c]) { boxes[r][c] = true; count += queenPermutation_2D(boxes, tnq, 0, qpsf + 1, ans + "b" + to_string(i) + "q" + to_string(qpsf) + " "); boxes[r][c] = false; } } return count; } //================================================================================================ bool isSafeToPlaceQueen(vector<vector<bool>> &boxes,int r,int c) { // vector<vector<int>> dir{{0,-1},{-1,-1},{-1,0},{-1,1}}; //for combination vector<vector<int>> dir{{0,-1},{-1,-1},{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1}}; for(int d=0;d<dir.size();d++) { for(int radius=1;radius<=boxes.size();radius++) { int x = r + radius*dir[d][0]; int y = c + radius*dir[d][1]; if(x>=0 && y>=0 && x<boxes.size() && y<boxes[0].size()) { if(boxes[x][y]) return false; } } } return true; } int Nqueen_01(vector<vector<bool>> &boxes,int tnq, int idx, string ans) { if(tnq==0) { cout<<ans<<endl; return 1; } int count=0; for(int i=idx;i<boxes.size()*boxes[0].size();i++) { int r = i/boxes[0].size(); int c = i%boxes[0].size(); if(isSafeToPlaceQueen(boxes,r,c)) { boxes[r][c]=true; count+=Nqueen_01(boxes,tnq-1,i+1, ans + "(" + to_string(r) + "," + to_string(c) + ") "); boxes[r][c]=false; } } return count; } int Nqueen_02(vector<vector<bool>> &boxes, int tnq, int idx, string ans) // tnq is equal to target. { if (tnq==0) { cout << ans << endl; return 1; } int count = 0; for (int i = idx; i < boxes.size() * boxes[0].size(); i++) { int r = i / boxes[0].size(); int c = i % boxes[0].size(); if (!boxes[r][c] && isSafeToPlaceQueen(boxes,r,c)) { boxes[r][c] = true; count += Nqueen_02(boxes, tnq-1, 0, ans + "(" + to_string(r) + "," + to_string(c) + ") "); boxes[r][c] = false; } } return count; } vector<bool> rowA; vector<bool> colA; vector<bool> diagA; vector<bool> adiagA; int Nqueen_03(vector<vector<bool>> &boxes,int tnq, int idx, string ans) { if(tnq==0) { cout<<ans<<endl; return 1; } int count=0; int n = boxes.size(); int m = boxes[0].size(); for(int i=idx;i<boxes.size()*boxes[0].size();i++) { int r = i/boxes[0].size(); int c = i%boxes[0].size(); if(!rowA[r] && !colA[c] && !diagA[r+c] && !adiagA[r-c+m-1]) { rowA[r]=true; colA[c]=true; diagA[r+c]=true; adiagA[r-c+m-1]=true; count+=Nqueen_03(boxes,tnq-1,i+1, ans + "(" + to_string(r) + "," + to_string(c) + ") "); rowA[r]=false; colA[c]=false; diagA[r+c]=false; adiagA[r-c+m-1]=false; } } return count; } int calls=0; int Nqueen_04(int n,int m,int tnq, int r, string ans) { if(tnq==0) { cout<<ans<<endl; return 1; } int count=0; calls++; for(int c=0;c<m;c++) { if(!rowA[r] && !colA[c] && !diagA[r+c] && !adiagA[r-c+m-1]) { rowA[r]=true; colA[c]=true; diagA[r+c]=true; adiagA[r-c+m-1]=true; count+=Nqueen_04(n,m,tnq-1,r+1, ans + "(" + to_string(r) + "," + to_string(c) + ") "); rowA[r]=false; colA[c]=false; diagA[r+c]=false; adiagA[r-c+m-1]=false; } } return count; } int row = 0; int col = 0; int diag = 0; int adiag = 0; int Nqueen_05(int n, int m, int tnq, int r, string ans) // tnq is equal to target. { if (tnq == 0) { cout << ans << endl; return 1; } int count = 0; calls++; for (int c = 0; c < m; c++) { if ((row & (1 << r)) == 0 && (col & (1 << c)) == 0 && (diag & (1 << (r + c))) == 0 && (adiag & (1 << (r - c + m - 1))) == 0) { row ^= (1 << r); col ^= (1 << c); diag ^= (1 << (r + c)); adiag ^= (1 << (r - c + m - 1)); count += Nqueen_05(n, m, tnq - 1, r + 1, ans + "(" + to_string(r) + "," + to_string(c) + ") "); row ^= (1 << r); col ^= (1 << c); diag ^= (1 << (r + c)); adiag ^= (1 << (r - c + m - 1)); } } return count; } //===================================================================================== void Nqueen() { int n = 4; int m = 4; vector<vector<bool>> boxes(n, vector<bool>(m, 0)); int tnq = n; //cout<<Nqueen_01(boxes,tnq,0,"")<<endl; //cout<<Nqueen_02(boxes,tnq,0,"")<<endl; rowA.resize(n,false); colA.resize(m,false); diagA.resize(m+n-1,false); adiagA.resize(m+n-1,false); //cout<<Nqueen_03(boxes,tnq,0,"")<<endl; cout<<Nqueen_04(n,m,tnq,0,"")<<endl; cout<<calls<<endl; } void queen_Permutation_Combination() { //vector<bool> boxes(5, false); //int tnq = 3; //cout << queenCombination_1D(boxes, tnq, 0, 0, "") << endl; //cout << queenCombination_1D_subseq(boxes, tnq, 0, 0, "") << endl; // cout << queenPermutation_1D(boxes, tnq, 0, 0, "") << endl; // cout << queenPermutation_1D_subseq(boxes, tnq, 0, 0, "") << endl; //vector<vector<bool>> boxes(4, vector<bool>(4, false)); //int tnq = 4; //cout<<queen_Combination_2D(boxes,tnq,0,0,"")<<endl; //cout << queenPermutation_2D(boxes, tnq, 0, 0, "") << endl; } void coin_Permutation_Combination() { vector<int> arr{1,1,1,1,1,-1,-1,-1,-1,-1}; int tar =3; //cout<<permutationINFI(arr,0,tar,"")<<endl; //cout<<combinationINFI(arr,0,tar,"")<<endl; cout<<combinationSingle(arr,0,tar,"")<<endl; // cout<<permutationSingle(arr,0,tar,"")<<endl; //cout<<combinationSingle_sub(arr,0,tar,"")<<endl; //cout<<combinationINFI_subseq(arr,0,tar,"")<<endl; } void solve() { coin_Permutation_Combination(); // queen_Permutation_Combination(); //Nqueen(); } int main() { solve(); return 0; }
true
ad59a17505a3b0478918c766bbf15707a3cee1c6
C++
flomar/CrypTool-VS2015
/trunk/CrypTool/SquareMatrixModN.h
UTF-8
6,151
2.515625
3
[ "Apache-2.0" ]
permissive
/************************************************************************** Copyright [2009] [CrypTool Team] This file is part of CrypTool. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. **************************************************************************/ ////////////////////////////////////////////////////////////////// // Copyright 1998-2000 Deutsche Bank AG, Frankfurt am Main ////////////////////////////////////////////////////////////////// // Klasse SQUARE_MATRIX ////////////////////////////////////////////////////////////////// // Klasse fuer eine quadratische Matrix mit invertiermoeglichleit // modulo einer Zahl // // Deklaration der Klasse ////////////////////////////////////////////////////////////////// // Autor: Jens Liebehenschel ////////////////////////////////////////////////////////////////// #ifndef SQUARE_MATRIX_INCLUDED #define SQUARE_MATRIX_INCLUDED #if !defined(_MSC_VER) || _MSC_VER <= 1200 #include <iostream.h> #else #include <iostream> using namespace std; #endif #include <stdlib.h> // fuer srand, rand #include <time.h> // fuer time #define BOOL int #define TRUE 1 #define FALSE 0 // Werte fuer Feld laPositionVektor #define SQ_MAT_LIN_KOMB_INIT -1 #define SQ_MAT_LIN_KOMB_NEU -2 // Klasse fuer quadratische Matrix // mit Invertiermoeglichkeit modulo einer natuerlichen Zahl class CSquareMatrixModN { private: // Daten long **mat; // Dimension der Matrix int dim; // Modul = Maechtigkeit des Alphabeths int modul; // Maximale Laenge einer Zahl mod modul fuer Breite des Ausgabefeldes int feldbreite; // Inverse Elemente von 0 bis modul-1 int *inverse_elemente; // Determinante berechnen long determinante (int*, int*, int) const; // Konvertierung eines Eintrages long convert_long (long) const; // Felder fuer die Invertierung einer Matrix mittels Gauss-Jordan Verfahren // Diese Felder haben alle die Laenge modul; der Speicher wird im Konstruktor // angefordert und im Destruktor wieder freigegeben. // Sie werden nur benoetigt, wenn bei Gauss-Jordan Verfahren kein invertierbares // Element mehr fuer die aktuelle Position auf der Hauptdiagonalen verfuegbar // ist, so dass das Verfahren nicht fortgresetzt werden kann, da die "1" auf der // Hauptdiagonalen nicht erzeugt werden kann. int *iaZeileVektor; // An der Stelle i steht anfangs SQ_MAT_LIN_KOMB_INIT. // Falls beim Invertieren erstmalig der Wert i // an der entsprechenden Stelle auf der Hauptdiagonalen // auftritt, wird die Zeile des Vektors in der Matrix // in diesem Feld gespeichert. // Kann dieser Wert i durch eine Linearkombination // gebildet werden, so wird SQ_MAT_LIN_KOMB_NEU an der // Stelle i eingetragen. i ergibt sich aus der Summe von // den beiden in iaLinearKombination1 und // iaLinearKombination2 eingetragenen Werten; die Vektoren // fuer diese beiden Werte koennen mittels dieser Variablen // laPositionVektor ermittelt werden. int *iaLinearKombination1; // siehe Erklaerung zu laPositionVektor. int *iaLinearKombination2; // siehe Erklaerung zu laPositionVektor. int *iaFaktoren; // Dieses Feld enthaelt die Faktoren, mit denen die // Vektoren der Linearkombination multipliziert werden // muessen, damit an der entsprechenden Stelle auf der // Hauptdiagonalen ein invertierbares Elemnent steht. // Hilfsvariablen zum Bilden der Linearkombination bei Invertierung der Matrix // mittels Gauss-Jordan Verfahren. Die beiden Zeilenvektoren werden nachher // in der Matrix eingefuegt. Sie ersetzen eine Zeile, die in die // Linaerkombination eingegangen ist. // Diese Felder haben alle die Laenge dim; der Speicher wird im Konstruktor // angefordert und im Destruktor wieder freigegeben. int *iaHilfsfeld_hilfsmat, // Zeilenvektor linke Seite *iaHilfsfeld_mat1; // Zeilenvektor rechte Seite // Hilfsfunktion fuer die Invertierung mittels Gauss-Jordan Verfahren // zum Berechnen der Faktoren fuer die Linearkombination void BerechneFaktoren(int) const; void destroy(); public: // Konstruktor mit Parameter: Dimension, Modul CSquareMatrixModN(int, int); ~CSquareMatrixModN(); // Zugriffsfunktion: Operator, der ein Element der Matrix liefert long& operator() (int, int); long operator() (int, int) const; // Konvertierung der Eintraege nach [0:modul-1] void convert_mod (); // Ein- und Ausgabe friend ostream& operator<< (ostream & os, const CSquareMatrixModN &); friend istream& operator>> (istream & is, CSquareMatrixModN &); // Zuweisung CSquareMatrixModN& operator= (const CSquareMatrixModN &); // Rueckgabe der Dimension int get_dim (void) const; // Rueckgabe des Moduls int get_mod (void) const; // Rueckgabe des Feldbreite fuer die Ausgabe der Matrix int get_feldbreite (void) const; // Ausgabe des inversen Elements einer Zahl // Falls es nicht existiert, wird 0 zurueckgegeben int get_inverses_element (int) const; // Invertieren modulo einer Zahl // Es sollte immer die Funktion invert aufgerufen werden. // Diese ruft - in Anhaengigkeit von der entprechenden Matrix - // entweder invert_adjunkten_verfahren oder invert_gauss_jordan auf. BOOL invert(CSquareMatrixModN *) const; BOOL invert_adjunkten_verfahren(CSquareMatrixModN *) const; BOOL invert_gauss_jordan(CSquareMatrixModN *) const; // Berechnung einer zufaelligen invertierbaren Matrix der entsprechenden Dimension // Rueckgabewert: TRUE, falls eine invertirbare Matrix existiert. BOOL zufaellige_invertierbare_matrix (void); BOOL initialize( int, int ); BOOL is_initialized() { return (dim > 0); } }; #endif
true
3953605016cca8e0df826c6e4b37370b084855fb
C++
kuonanhong/Exercise
/Hihocoder 1181 欧拉路二.cpp
UTF-8
1,855
3.234375
3
[]
no_license
/* 输入 第1行:2个正整数,N,M。分别表示骨牌上出现的最大数字和骨牌数量。1≤N≤1,000,1≤M≤5,000 第2..M+1行:每行2个整数,u,v。第i+1行表示第i块骨牌两端的数字(u,v),1≤u,v≤N 输出 第1行:m+1个数字,表示骨牌首尾相连后的数字 比如骨牌连接的状态为(1,5)(5,3)(3,2)(2,4)(4,3),则输出"1 5 3 2 4 3" 你可以输出任意一组合法的解。 样例输入 5 5 3 5 3 2 4 2 3 4 5 1 样例输出 1 5 3 4 2 3 */ #include <iostream> #include <vector> #include <stack> #include <unordered_set> #include <unordered_map> #include <set> using namespace std; int main(){ int n, m, s, t; while(cin >> n >> m){ unordered_map<int, multiset<int>> udmp(n + 1); // 可能有重复边 vector<int> indegree(n + 1, 0); for(int i = 0;i < m; ++ i){ cin >> s >> t; udmp[s].insert(t); udmp[t].insert(s); indegree[s] ++; indegree[t] ++; } int start = 1; for(int i = 1; i <= n; ++ i){ if(indegree[i] & 1){ start = i; break; } } stack<int> stk; stk.push(start); vector<int> res; while(!stk.empty()){ s = stk.top(); if(!udmp[s].empty()){ stk.push(*(udmp[s].begin())); int b = *(udmp[s].begin()); udmp[s].erase(udmp[s].begin()); udmp[b].erase(udmp[b].find(s)); // 需要把反向边也删掉 } else{ res.push_back(stk.top()); stk.pop(); } } int i = (int)res.size() - 1; cout << res[i --]; for(; i >= 0; -- i) cout << " " << res[i]; cout << endl; } return 0; }
true
5abafe5a0ea05c9c11d3d49d6bd76bd86b003e20
C++
amlopez9173/menu
/menu.cpp
UTF-8
2,393
3.546875
4
[]
no_license
#include <stdlib.h> #include <stdio.h> #include <iostream> #include <conio.h> using namespace std; struct Nodo{ int num; Nodo *Siguiente; }; void init_pila(); void vacia_pila_bool(Nodo *&, int); void ins_pila(Nodo *&, int); void retirar_pila(Nodo *&, int &); Nodo *pila; int main() { int n,opc,menu=1; do{ printf("MENU\n"); printf("1. Inicializar Pila\n"); printf("2. Verificar estado de Pila\n"); printf("3. Insertar elementos de Pila\n"); printf("4. Retirar elementos de Pila\n"); printf("0. Salir\n"); printf("Opcion: ");scanf("%d",&opc); switch(opc) { case 0: menu=0; break; case 1: init_pila(); break; case 2: vacia_pila_bool(pila,n); break; case 3: printf("Presiones (0) cuando termine el ingreso de numeros"); do{ printf("\nIngrese un numero: "); scanf("%d",&n); ins_pila(pila, n); }while(n!=0); break; case 4: while(pila!=NULL) { retirar_pila(pila,n); if(pila!=NULL) { printf("%d -> ",n); }else { printf("%d -> FIN",n); } } break; } getch(); }while(menu !=0); return 0; } void init_pila() { Nodo *pila =NULL; printf("Inicializacion realizada correctamente\n"); } void vacia_pila_bool(Nodo *&pila, int n) { bool validador; if(pila==NULL) { validador=true; }else { validador=false; } if(validador==true) { printf("\nLa Pila esta Vacia.\n"); }else { printf("\nLa Pila no esta Vacia.\n"); } } void ins_pila(Nodo *&pila, int n) { Nodo *nuevo_nodo=(Nodo*)malloc(sizeof(Nodo)); nuevo_nodo->num=n; nuevo_nodo->Siguiente=pila; pila= nuevo_nodo; } void retirar_pila(Nodo *&pila, int &n) { Nodo *aux=pila; n=aux->num; pila=aux->Siguiente; free(aux); }
true
47bb402a2dc4368bbab0a95c1d1ad31a862070bf
C++
AppledoreM/OI
/PastFiles/Codeforces/Contest2019/Codeforces572_Div12/C.cpp
UTF-8
1,290
2.59375
3
[]
no_license
#include <iostream> #include <stdio.h> #include <cstring> #include <math.h> #include <algorithm> #include <vector> using namespace std; #define FAST_IO ios::sync_with_stdio(false) int n; typedef pair<int,int> pii; vector<pii> lev[20]; int main() { FAST_IO; cin.tie(nullptr); cout.tie(nullptr); cin>>n; for(int i = 1; i <= n; i++){ int x; cin>>x; lev[1].emplace_back(pii(x,0)); } int cur = 1; for(int i = 2; (1 << (i - 1)) <= n; i++){ cur *= 2; for(int j = 0; j + cur / 2< (int) lev[i - 1].size(); j++){ int candie1 = lev[i - 1][j].second; int candie2 = lev[i - 1][j + cur / 2].second; int dig1 = lev[i - 1][j].first; int dig2 = lev[i - 1][j + cur / 2].first; int new_candie = candie1 + candie2 + (int)(dig1 + dig2 >= 10); int new_dig = (dig1 + dig2) % 10; lev[i].emplace_back(pii(new_dig,new_candie)); } } int q; cin>>q; for(int i = 1; i <= q; i++){ int l,r; cin>>l>>r; int len = r - l + 1; int dep = 1; while(len / 2){ len /= 2; dep++; } cout<<lev[dep][l - 1].second<<endl; } return 0; }
true
b7d74a7b23e08982429ebec692caed3cdec91408
C++
TomasKimer/gles3mark
/jni/jnilink.h
UTF-8
1,351
2.703125
3
[]
no_license
/** * gles3mark v1.0 * * \date 2014-05-28 * \author Tomas Kimer <xkimer00@stud.fit.vutbr.cz> */ #pragma once #include <jni.h> #include <stdexcept> const std::string JNI_STRING_SIGNATURE("(Ljava/lang/String;)V"); /** * \brief Interface to Dalvik via JNI. */ class JNILink { JNIEnv *env; // game thread env (vs main thread env: state->activity->env) jobject thiz; jclass clazz; const android_app* refState; public: JNILink(android_app* state) : refState(state) { if (refState->activity->vm->AttachCurrentThread(&env, nullptr) == 0) { thiz = refState->activity->clazz; clazz = env->GetObjectClass(thiz); } else { throw std::runtime_error("AttachCurrentThread Failed"); } } ~JNILink() { refState->activity->vm->DetachCurrentThread(); } jmethodID GetMethodID(const std::string& name, const std::string& sig) { return env->GetMethodID(clazz, name.c_str(), sig.c_str()); } template<typename ...Args> void CallVoidMethod(jmethodID& methodID, Args &&...args) { env->CallVoidMethod(thiz, methodID, std::forward<Args>(args)...); } jstring NewStringUTF(const std::string& str) { return env->NewStringUTF(str.c_str()); } void DeleteLocalRef(jobject localRef) { env->DeleteLocalRef(localRef); } JNIEnv* GetEnv() { return env; } jobject& GetObject() { return thiz; } jclass& GetClass() { return clazz; } };
true
4cfac7ca1393ac2e9ccfcea536cdeee80a05a729
C++
vfcastro/dropbox-sisop2
/src/client/ClientProcessor.cpp
UTF-8
3,308
2.796875
3
[]
no_license
#include <iostream> #include <fcntl.h> #include <unistd.h> #include "../../include/client/ClientProcessor.h" #include "../../include/common/FileManager.h" // Avalia qual o tipo de mensagem recebida e encaminha pra funcao adequada void ClientProcessor_dispatch(ClientCommunicator *cc, Message *msg) { // std::cout << "ClientProcessor_dispatch(): START\n"; switch(msg->type) { case FILE_CLOSE_WRITE: // std::cout << "ClientProcessor_dispatch(): recv FILE_CLOSE_WRITE from user " << msg->username << "\n"; ClientProcessor_onCloseWrite(cc,msg); break; case DELETE_FILE: // std::cout << "ClientProcessor_dispatch(): recv DELETE_FILE from user " << msg->username << "\n"; ClientProcessor_receiveDelete(cc, msg); break; case S2C_PROPAGATE: // std::cout << "SOU UM CLIENTE E RECEBI MENSAGEM" << msg->username << "\n"; ClientProcessor_receivePropagate(cc, msg); break; } // std::cout << "ClientProcessor_dispatch(): END\n"; } void ClientProcessor_onCloseWrite(ClientCommunicator *cc, Message *msg) { // std::cout << "ClientProcessor_onCloseWrite(): recv FILE_CLOSE_WRITE from server " << msg->username << "\n"; //primeira msg contem o nome do arquivo, cria caso necessario std::string path("./sync_dir_"); path.append(msg->username).append("/"); path.append(msg->payload); int f = open((char*)path.c_str(),O_CREAT|O_WRONLY,0600); if(f == -1){ std::cerr << "ClientProcessor_onCloseWrite(): ERROR creating file " << path << "\n"; return; } //msg->type = OK; //Message_send(msg,sockfd); //Preenche o arquivo conforme recebimento das mensagens while(Message_recv(msg,ClientCommunicator_getRecvSocket(cc)) != -1) { // Verifica se tipo = OK, se sim, para de escrever if(msg->type == END){ break; } // std::cout << "ClientProcessor_onCloseWrite(): recv payload with " << msg->seqn << " bytes\n"; if(write(f,(const void *)msg->payload, msg->seqn) == -1){ exit(6); } } } void ClientProcessor_receivePropagate(ClientCommunicator *cc, Message *msg) { // std::cout << "ClientProcessor_receivePropagate(): recv FILE_CLOSE_WRITE from client " << msg->username << "\n"; std::string path("./sync_dir_"); path.append(cc->username).append("/"); path.append(msg->payload); std::cout << "Recebendo arquivo: " << path << "\n"; pthread_mutex_lock(&cc->syncFilesLock); //Adiciona filename na lista de sicronizacao cc->syncFiles.insert(msg->payload); // Começa o recebimento do arquivo if(FileManager_receiveFile(path, msg, ClientCommunicator_getRecvSocket(cc)) == -1){ std::cerr<<"ClientProcessor_receivePropagate(): Error Receive File\n"; } //Remove filename na lista de sync cc->syncFiles.erase(msg->payload); pthread_mutex_unlock(&cc->syncFilesLock); } void ClientProcessor_receiveDelete(ClientCommunicator *cc, Message *msg){ std::string path("./sync_dir_"); path.append(cc->username).append("/"); path.append(msg->payload); pthread_mutex_lock(&cc->syncFilesLock); cc->syncFiles.insert(msg->payload); // cout << path << "\n"; int Removed = std::remove(path.c_str()); cc->syncFiles.erase(msg->payload); pthread_mutex_unlock(&cc->syncFilesLock); }
true
2ef3cb7ac1e473af9aabb4cffe03dfbfbd344382
C++
WhiZTiM/coliru
/Archive2/18/9c75cb32ed7b58/main.cpp
UTF-8
501
3.4375
3
[]
no_license
#include <iostream> #include <string> using std::cout; using std::string; template<class C> C min(C a,C b) { return a<b?a:b; } int main() { string a="first string"; string b="second string"; cout<<"minimum string is: "<<min(a,b)<<'\n'; int c=3,d=5; cout<<"minimum number is: "<<min(c,d)<<'\n'; double e{3.3},f{6.6}; cout<<"minimum number is: "<<min(e,f)<<'\n'; char g{'a'},h{'b'}; cout<<"minimum number is: "<<min(g,h)<<'\n'; return 0; }
true
c9e1b2502ce76928dcb0c06cb2278c4fc842e605
C++
seungmin97/Algorithm
/Programmers/2020_카카오_인턴십/jewerly_shopping.cpp
UTF-8
6,748
3.1875
3
[]
no_license
// // Created by 이승민 on 2020-07-27. // #include <iostream> /* #include <string> #include <vector> #include <algorithm> using namespace std; struct jewerly{ string name; vector<int> index; }; bool cmp(const jewerly &j1, const jewerly &j2 ){ if(j1.index.size() < j2.index.size()){ return true; } return false; } bool cmp2(const pair<int, int> &p1, const pair<int, int> &p2){ if((p1.second - p1.first) < (p2.second - p2.first)){ return true; } return false; } vector<jewerly> find_jewerly(string temp, int index, vector<jewerly> jewer){ vector<jewerly> je = jewer; for (int i = 0; i < jewer.size(); ++i) { if(je[i].name == temp){ je[i].index.push_back(index); return je; } } jewerly j; j.name = temp; j.index.push_back(index); je.push_back(j); return je; } vector<int> solution(vector<string> gems) { vector<int> answer; vector<jewerly> jewer; vector<pair<int, int>> temp; for (int i = 0; i < gems.size(); ++i) { jewer = find_jewerly(gems[i], i, jewer); } sort(jewer.begin(), jewer.end(), cmp); if(jewer.size() == 1){ answer.push_back(1); answer.push_back(1); return answer; } for (int i = 0; i < jewer.size(); ++i) { if(i == 0){ if(jewer[i].index.size() == 1){ temp.push_back(make_pair(jewer[i].index[0], jewer[i].index[0])); } else{ for (int j = 0; j < jewer[i].index.size(); ++j) { temp.push_back(make_pair(jewer[i].index[j], jewer[i].index[j])); } } } else{ if(jewer[i].index.size() == 1){ for (int j = 0; j < temp.size(); ++j) { if(jewer[i].index[0] < temp[j].first){ temp[j].first = jewer[i].index[0]; } else{ temp[j].second = jewer[i].index[0]; } } } else{ for (int j = 0; j < temp.size(); ++j) { int left = -1; int checkcheck = 0; int right = -1; for (int k = 0; k < jewer[i].index.size(); ++k) { if(jewer[i].index[k] > temp[j].first && jewer[i].index[k] < temp[j].second){ checkcheck = 1; break; } else if(jewer[i].index[k] < temp[j].first){ if(left == -1){ left = jewer[i].index[k]; } else if(left < jewer[i].index[k]){ left = jewer[i].index[k]; } else{ continue; } } else{ if(right == -1){ right = jewer[i].index[k]; } else if(right > jewer[i].index[k]){ right = jewer[i].index[k]; } else{ continue; } } } if(checkcheck == 0){ if(left == -1){ temp[j].second = right; } else if(right == -1){ temp[j].first = left; } else if(abs(left - temp[j].first) <= abs(right - temp[j].second)){ temp[j].first = left; } else{ temp[j].second = right; } } } } } } sort(temp.begin(), temp.end(), cmp2); answer.push_back(temp[0].first + 1); answer.push_back(temp[0].second + 1); return answer; }*/ #include <string> #include <vector> #include <unordered_map> #include <unordered_set> #include <iostream> using namespace std; vector<int> solution(vector<string> gems) { vector<int> answer; answer.push_back(0); answer.push_back(0); // 정답 리턴을 위한 초기화 // set을 사용하여 보석의 종류수를 센다. unordered_set<string> s; for (auto tmp : gems) { s.insert(tmp); } int kind = s.size(); // map을 사용하여 구간내 보석의 빈도수를 센다. unordered_map<string, int> m; int start = 0, end = 0; int minDist = 0x7fffffff; // 투포인터 기법을 사용해 연속된 구간들을 탐색해본다. while (1) { if (m.size() >= kind) { // 현재 구간이 조건에 맞는다면(모든 종류의 보석을 포함한다면) m[gems[start]]--; // 구간을 줄여본다.(맨 앞의 보석을 제거한다.) if (m[gems[start]] == 0) m.erase(gems[start]); start++; } else if (end == gems.size()) // 현재 구간이 조건에 맞지않고, 마지막 포인터가 범위를 초과하면 break; // 구간 탐색을 중지한다. else { // 현재 구간이 조건에 맞지 않는다면, 마지막 포인터를 증가시켜본다.(맨 뒤에 보석을 추가한다.) m[gems[end]]++; end++; } if (m.size() == kind) { // 현재 구간이 조건에 맞는지 확인한다.(모든 종류 보석 포함여부) if (abs(end - start) < minDist) { // 조건을 만족하는 최소 구간을 구한다. minDist = abs(end - start); answer[0] = start + 1; answer[1] = end; } } } return answer; } int main(){ vector <int> answer; answer = solution({"DIA", "RUBY", "RUBY", "DIA", "DIA", "EMERALD", "SAPPHIRE", "DIA"}); cout << answer[0] << " " << answer[1] << endl; answer.erase(answer.begin(), answer.end()); answer = solution({"AA", "AB", "AC", "AA", "AC"}); cout << answer[0] << " " << answer[1] << endl; answer.erase(answer.begin(), answer.end()); answer = solution({"XYZ", "XYZ", "XYZ"}); cout << answer[0] << " " << answer[1] << endl; answer.erase(answer.begin(), answer.end()); answer = solution({"ZZZ", "YYY", "NNNN", "YYY", "BBB"}); cout << answer[0] << " " << answer[1] << endl; return 0; }
true
74f0f2ee1a376ab750d3de34be58a96484518cbf
C++
kl4kennylee81/Canon
/source/PulseParticleGenerator.cpp
UTF-8
4,956
2.515625
3
[]
no_license
// // PulseParticleGenerator.cpp // // Created by Hong Jeon on 5/4/17. // Copyright © 2017 Game Design Initiative at Cornell. All rights reserved. // #include "PulseParticleGenerator.hpp" #include <map> #include <math.h> // how many frames to wait until the next pulse #define TIMEOUT_FRAMES 100 // how many pulses to generate per second #define PULSE_RATE 3 #define NUM_PARTICLES 1 // max number of pulse particles #define MAX_PARTICLES 120*PULSE_RATE*NUM_PARTICLES #define MAX_GROUPS 1000 #define BLUER 49 #define BLUEG 185 #define BLUEB 255 #define GOLDR 235 #define GOLDG 235 #define GOLDB 56 bool PulseParticleGenerator::init(std::shared_ptr<GameState> state, std::unordered_map<std::string, ParticleData>* particle_map) { _particle_map = particle_map; _active = false; // initialize partnode _ringpd = _particle_map->at("pulse_ring"); _pulsepartnode = ParticleNode::allocWithTexture(_ringpd.texture); _pulsepartnode->setBlendFunc(GL_SRC_ALPHA, GL_ONE); _pulsepartnode->setBlendEquation(GL_FUNC_ADD); _pulsepartnode->setPosition(Vec2::ZERO); _pulsepartnode->setAnchor(Vec2::ANCHOR_MIDDLE); // important steps _groups = GroupContainer::alloc(MAX_GROUPS); _pulsepartnode->init_memory(MAX_PARTICLES); _pulsepartnode->_groups = _groups; state->getWorldNode()->addChild(_pulsepartnode); // initialize instance variables. _timeout = TIMEOUT_FRAMES; return true; } ParticleData PulseParticleGenerator::randomizeAngle(ParticleData pd) { float rand = getRandomFloat(0,1); auto angle = rand*2.0f*M_PI; pd.current_angle = angle; return pd; } /** * Generates a pulse at world_pos and assigns a new group to that pulse. */ void PulseParticleGenerator::createPulseParticles(Vec2 world_pos, int group_num, ElementType element) { ParticleData pd = _ringpd; // don't taint the template // how much scale each pulse is separated by float scale_rate = ((float)(pd.end_scale - pd.start_scale)/(PULSE_RATE-1)); // how much ttl each pulse is separated by float ttl_rate = ceil(((float)pd.ttl)/(PULSE_RATE-1)); pd.current_scale = pd.start_scale; if (element == ElementType::BLUE) { pd.color_fade = true; pd.start_color = normalizedRGB(BLUER,BLUEG,BLUEB,1); pd.end_color = normalizedRGB(BLUER,BLUEG,BLUEB,1); pd.color_duration = -1; // infinite } else { pd.color_fade = true; pd.start_color = normalizedRGB(GOLDR,GOLDG,GOLDB,1); pd.end_color = normalizedRGB(GOLDR,GOLDG,GOLDB,1); pd.color_duration = -1; // infinite } // pd is the original starting particle ParticleData original = pd; // create the particles that are spaced out by a constant amount for (int ii = 0; ii < PULSE_RATE; ii++) { _pulsepartnode->addParticle(randomizeAngle(pd), group_num, original); _pulsepartnode->_original = original; pd.current_scale += scale_rate; // ones in the outer ring are bigger pd.ttl -= ttl_rate; // ones in the outer ring die sooner } } void PulseParticleGenerator::add_mapping(GameObject* obj) { // don't add pulses on players or zones or bullets if (obj->type != GameObject::ObjectType::CHARACTER || obj->getIsPlayer()) return; // this might be the source of the gravity bug? Vec2 world_pos = obj->getPosition()*Util::getGamePhysicsScale(); bool repeat = true; // finds the next available group num int group_num = _groups->makeNewGroup(world_pos, repeat); ElementType element = obj->getPhysicsComponent()->getElementType(); // create the wrapper for (int i = 0; i < NUM_PARTICLES; i++) { createPulseParticles(world_pos, group_num, element); } // insert wrapper to object -> wrapper map _obj_to_group_num.insert(std::make_pair(obj, group_num)); } void PulseParticleGenerator::remove_mapping(GameObject* obj) { if (obj->type != GameObject::ObjectType::CHARACTER || obj->getIsPlayer()) return; // find out what group the object belongs to auto group_num = _obj_to_group_num.at(obj); // mark this one as done. very important. _groups->group_array[group_num].alive = false; // remove object from the mapping _obj_to_group_num.erase(obj); } /** * Goes through all of the ParticleWrapper we have, and calls update on each one of them */ void PulseParticleGenerator::generate() { if (!_active) return; for (auto it = _obj_to_group_num.begin(); it != _obj_to_group_num.end(); it++) { GameObject* obj = it->first; int group_num = it->second; // sync the position of the group to the character Vec2 world_pos = obj->getPosition()*Util::getGamePhysicsScale(); _groups->group_array[group_num].global_position = world_pos; } // update every particle in this node _pulsepartnode->update(); }
true
fc641aa0d6f0534d12478a6201d358d01d456a1e
C++
ppmht/gporca
/libgpos/include/gpos/common/CSyncHashtableAccessorBase.h
UTF-8
4,512
2.546875
3
[ "Apache-2.0" ]
permissive
//--------------------------------------------------------------------------- // Greenplum Database // Copyright (C) 2011 EMC Corp. // // @filename: // CSyncHashtableAccessorBase.h // // @doc: // Base hashtable accessor class; provides primitives to operate // on a target bucket in the hashtable. // // Throughout its life time, the accessor holds the spinlock on a // target bucket; this allows clients to implement more complex // functionality than simple test-and-insert/remove functions. // //--------------------------------------------------------------------------- #ifndef GPOS_CSyncHashtableAccessorBase_H_ #define GPOS_CSyncHashtableAccessorBase_H_ #include "gpos/base.h" #include "gpos/common/CSyncHashtable.h" #include "gpos/common/CSyncHashtableIter.h" namespace gpos { //--------------------------------------------------------------------------- // @class: // CSyncHashtableAccessorBase<T, K, S> // // @doc: // Accessor class to encapsulate locking of a hashtable bucket; // has to know all template parameters of the hashtable class in order // to link to the target hashtable; see file doc for more details on the // rationale behind this class // //--------------------------------------------------------------------------- template <class T, class K, class S> class CSyncHashtableAccessorBase : public CStackObject { private: // shorthand for buckets typedef struct CSyncHashtable<T, K, S>::SBucket SBucket; // target hashtable CSyncHashtable<T, K, S> &m_ht; // bucket to operate on SBucket &m_bucket; // no copy ctor CSyncHashtableAccessorBase<T, K, S> (const CSyncHashtableAccessorBase<T, K, S>&); protected: // ctor - protected to restrict instantiation to children CSyncHashtableAccessorBase<T, K, S> ( CSyncHashtable<T, K, S> &ht, ULONG ulBucketIndex ) : m_ht(ht), m_bucket(m_ht.Bucket(ulBucketIndex)) { // acquire spin lock on bucket m_bucket.m_slock.Lock(); } // dtor virtual ~CSyncHashtableAccessorBase<T, K, S>() { // unlock bucket m_bucket.m_slock.Unlock(); } // accessor to hashtable CSyncHashtable<T, K, S>& Sht() const { return m_ht; } // accessor to maintained bucket SBucket& Bucket() const { return m_bucket; } // returns the first element in the hash chain T *PtFirst() const { return m_bucket.m_list.PtFirst(); } // finds the element next to the given one T *PtNext(T *pt) const { GPOS_ASSERT(NULL != pt); // make sure element is in this hash chain GPOS_ASSERT(GPOS_OK == m_bucket.m_list.EresFind(pt)); return m_bucket.m_list.PtNext(pt); } // inserts element at the head of hash chain void Prepend(T *pt) { GPOS_ASSERT(NULL != pt); m_bucket.m_list.Prepend(pt); // increase number of entries (void) UlpExchangeAdd(&(m_ht.m_ulpEntries), 1); } // adds first element before second element void Prepend(T *pt, T *ptNext) { GPOS_ASSERT(NULL != pt); // make sure element is in this hash chain GPOS_ASSERT(GPOS_OK == m_bucket.m_list.EresFind(ptNext)); m_bucket.m_list.Prepend(pt, ptNext); // increase number of entries (void) UlpExchangeAdd(&(m_ht.m_ulpEntries), 1); } // adds first element after second element void Append(T *pt, T *ptPrev) { GPOS_ASSERT(NULL != pt); // make sure element is in this hash chain GPOS_ASSERT(GPOS_OK == m_bucket.m_list.EresFind(ptPrev)); m_bucket.m_list.Append(pt, ptPrev); // increase number of entries (void) UlpExchangeAdd(&(m_ht.m_ulpEntries), 1); } public: // unlinks element void Remove(T *pt) { // not NULL and is-list-member checks are done in CList m_bucket.m_list.Remove(pt); // decrease number of entries (void) UlpExchangeAdd(&(m_ht.m_ulpEntries), -1); } }; // class CSyncHashtableAccessorBase } #endif // GPOS_CSyncHashtableAccessorBase_H_ // EOF
true
fd003995ce096e7a9b5b5b0127f5fe79ce77c704
C++
Anshumankumar/Apollo
/include/shaderHandler.hpp
UTF-8
2,641
3.1875
3
[]
no_license
#ifndef SHADER_HANDLER_HPP #define SHADER_HANDLER_HPP #include <iostream> #include <fstream> #include <cstdlib> #include <vector> #include <string> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <utility> namespace apollo { class ShaderHandler { GLuint shader; GLenum shaderType; char *buffer; public: ShaderHandler(std::string filename, GLenum shaderType) { this->shaderType = shaderType; std::ifstream stream(filename,std::ifstream::in); if (stream.is_open()) { stream.seekg(0,stream.end); int len = stream.tellg(); stream.seekg(0,stream.beg); buffer = new char[len]; stream.read(buffer,len); buffer[len-1]='\0'; stream.close(); } else { std::cerr << "Error in reading file " << filename<<"\n"; exit(2); } shader = glCreateShader(shaderType); } GLuint compileShader() { glShaderSource(shader, 1, (const char **)&buffer, NULL); glCompileShader(shader); GLint status; glGetShaderiv(shader, GL_COMPILE_STATUS, &status); if (status == GL_FALSE) { GLchar infoLog[2048]; glGetShaderInfoLog(shader, sizeof(infoLog), NULL, infoLog); std::cerr << shaderType << " " << infoLog << std::endl; exit(2); } return shader; } }; class ShaderUtil { std::vector<GLuint> shaderList; public: using sprop = std::pair<std::string,GLenum>; ShaderUtil(std::vector<sprop> pairs) { for(auto pair:pairs) { ShaderHandler shader(pair.first,pair.second); shaderList.push_back(shader.compileShader()); } } GLuint getProgram() { GLuint program = glCreateProgram(); for(auto &shader:shaderList) { glAttachShader(program, shader); } glLinkProgram(program); GLint status; glGetProgramiv (program, GL_LINK_STATUS, &status); if (status == GL_FALSE) { GLint infoLogLength; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLogLength); GLchar *strInfoLog = new GLchar[infoLogLength + 1]; glGetProgramInfoLog(program, infoLogLength, NULL, strInfoLog); std::cerr<<"GLSL Linker failure: "<<strInfoLog<<std::endl; delete[] strInfoLog; } for(auto &shader:shaderList) glDetachShader(program, shader); return program; } }; } #endif //SHADER_HANDLER_HPP
true
12e4b1726170dca8b313df644b2c76219c8c0ffd
C++
nspope/inlassle
/src/Null.cpp
UTF-8
1,116
2.734375
3
[ "MIT" ]
permissive
#include "Null.hpp" namespace Covariance { mat Null::covariance (void) { mat d = arma::eye<mat>(dim, dim) * std::pow(nugget,2); return d; } mat Null::differential (void) { mat d (dim * dim, npars+1, arma::fill::zeros); return d; } cube Null::differential_dist (void) { cube d (dim, dim, npars, arma::fill::zeros); return d; } vec Null::parameters (void) { arma::vec out = {stddev}; return arma::join_vert(out, weight); } } /* namespace Covariance */ //------------------------------------------- tests // [[Rcpp::export("inlassle_test_Null_C")]] arma::mat test_Null_C (arma::cube D, double nu, double delta, arma::vec pars) { Covariance::Null cov (D, nu, delta, pars); return cov.C; } // [[Rcpp::export("inlassle_test_Null_dC_dt")]] arma::mat test_Null_dC_dt (arma::cube D, double nu, double delta, arma::vec pars) { Covariance::Null cov (D, nu, delta, pars); return cov.dC_dt; } // [[Rcpp::export("inlassle_test_Null_dC_dD")]] arma::cube test_Null_dC_dD (arma::cube D, double nu, double delta, arma::vec pars) { Covariance::Null cov (D, nu, delta, pars); return cov.dC_dD; }
true
c0bb703823bf44f12abc7b6b064a97792c39bd3a
C++
Nihal-Priyadarshi/Hacktoberfest2021
/scripts/print_name_pattern.cpp
UTF-8
1,796
3.703125
4
[]
no_license
#include <iostream> using namespace std; // Below height and width variable can be used // to create a user-defined sized alphabet's pattern // Number of lines for the alphabet's pattern int height = 5; // Number of character width in each line int width = (2 * height) - 1; // Function to find the absolute value // of a number D int abs(int d) { return d < 0 ? -1 * d : d; } // Function to print the pattern of 'A' void printA() { int n = width / 2, i, j; for (i = 0; i < height; i++) { for (j = 0; j <= width; j++) { if (j == n || j == (width - n) || (i == height / 2 && j > n && j < (width - n))) cout <<"*"; else cout <<" "; } cout <<"\n"; n--; } } // Function to print the pattern of 'N' void printN() { int i, j, counter = 0; for (i = 0; i < height; i++) { cout <<"*"; for (j = 0; j <= height; j++) { if (j == height) cout <<"*"; else if (j == counter) cout <<"*"; else cout <<" "; } counter++; cout <<"\n"; } } // Function to print the pattern of 'Y' void printY() { int i, j, counter = 0; for (i = 0; i < height; i++) { for (j = 0; j <= height; j++) { if (j == counter || j == height - counter && i <= height / 2) cout <<"*"; else cout <<" "; } cout <<"\n"; if (i < height / 2) counter++; } } int main() { printA(); cout<<endl; printN(); cout<<endl; printA(); cout<<endl; printN(); cout<<endl; printY(); cout<<endl; printA(); return 0; }
true
04233597a44c049a05f7d080b8b7d66e1fc36c0c
C++
yashwanth2804/EosSmartconstracts
/smartContracts/zombieFactory.hpp
UTF-8
1,799
2.6875
3
[]
no_license
// // Created by Ludvig Kratz on 2018-01-14. // //#include <stdio.h> //#include <math.h> #include <eoslib/eos.hpp> #include <eoslib/db.hpp> #include <eoslib/string.hpp> using namespace eosio; namespace zombieFactory { struct zombie { zombie() {}; zombie(account_name owner, eosio::string name, uint64_t dna):owner(owner), name(name), dna(dna) {}; uint64_t dna; // DNA of zombie will be the key (since this is the first uint64_t in the struct) account_name owner; // Owner of the zombie eosio::string name; }; struct zombie_owner { zombie_owner() {}; zombie_owner(account_name owner):owner(owner) { counter = 0; }; account_name owner; //Database table key uint8_t max_zombies = 10; // Maximum 10 zombies per account, make vector? uint64_t zombies[10]; //List of zombie DNA this user owns, TODO: maybe make it Zombie object uint64_t counter; // i.e length of zombies array }; // Defines a action used when calling the smart contract struct create { account_name owner; eosio::string name; }; // Define database table on blockchain using Zombies = eosio::table<N(zombiefac), // default scope N(zombiefac), // Defines account that has write access N(zombies), // Name of the table zombie, // Structure of table (c++ struct) uint64_t>; // Data type of table's key (first uint64_t that's defined in struct // will be the key // Mapping of a users' zombies using Owners = eosio::table<N(zombiefac), N(zombiefac), N(owners), zombie_owner, uint64_t>; }
true
777d74b5dcd217c0e74032b7448a29151be9f012
C++
Kalyan-Sunkara/Data-Structures-And-Algorithms
/AVLTree/Node.cpp
UTF-8
1,108
3.203125
3
[]
no_license
#include "Node.h" Node::Node() { counter = 0; data = ""; height = 0; right = nullptr; left = nullptr; balanceFactor = 0; } Node::Node(int c, string d, int e):counter(c), data(d), height(e) { right = nullptr; left = nullptr; balanceFactor = 0; } int Node::setNodeCounter(int num) { counter = num; return counter; } Node* Node::getRight() { return right; } Node* Node::getLeft() { return left; } string Node::getNodeData() { return data; } void Node::setRight(Node* temp) { right = temp; } void Node::setLeft(Node* temp) { left = temp; } int Node::getNodeCounter() { return counter; } void Node::setNodeData(string temp) { data = temp; } void Node::updateNodeCounter() { counter = 1 + counter; } void Node::decrementNodeCounter() { counter = counter - 1; } int Node::getHeight() { return height; } void Node::updateHeight() { height = height + 1; } Node::~Node() { } void Node::setParent(Node* temp) { parent = temp; } Node* Node::getParent() { return parent; } int Node::getBalanceFactor() { return balanceFactor; } void Node::setBalanceFactor(int num) { balanceFactor = num; }
true
c2a8937fbaacb3cb3a598a89055d26ce7dad695e
C++
pranjaltimsina/DSA-Assignments
/Assignment 2/eval_infix.cpp
UTF-8
5,646
3.9375
4
[]
no_license
// Exp 2D: Program to evaluate infix expressions // Author: Pranjal Timsina; 20BDS0392 #include <iostream> #include <ctype.h> #include <cmath> #include <string> // Initializing a stack #define MAX 500 std::string stack[MAX]; int top = -1; // functions to check if stack is empty or full bool is_empty() { return (top == -1); } bool is_full() { return (top == MAX-1); } // returns the top element of stack without removing std::string peek() { if (is_empty()) { throw "Stack underflow!";} return stack[top]; } // pops the top most element of the stack and decrements top std::string pop() { if (is_empty()) { throw "Stack underflow!";} return stack[top--]; } // pushes data to the stack and increments top void push(std::string data) { if (is_full()) {throw "Stack Overflow!";} stack[++top] = data; } // returns precedence of an operator int operator_precedence(char a) { switch (a) { case '+': case '-': return 1; case '*': case '/': case '%': return 2; case '^': return 3; default: return 0; } } // -1 for left, 1 for right parantheses int parentheses(char a) { switch (a) { case '{': case '(': case '[': return -1; case '}': case ']': case ')': return 1; default: return 0; } } // function to convert infix to postfix std::string infix_to_postfix(std::string infix) { std::string postfix{""}, temp; // initialize variables infix = '(' + infix + ')'; // surround the expressions // variables for processing the infix expression char current; int number; // loop to traverse the characters in infix expresison for (int i = 0; infix[i] != '\0'; i++){ current = infix[i]; // storing in variable for ease // continues if the current character is whitespace if (current == ' ') { continue; } else if (isdigit(current)) { // checks adjacent characters for digits number = (int) (current - '0'); while (i+1 < MAX && infix[i+1] != '\0' && isdigit(infix[i+1])) { i = i+1; current = infix[i]; number = number*10 + (int) current - '0'; } // adds the full number to the postfix expression postfix = postfix + std::to_string(number) + " "; } else { // storing the value of char current to a string // to make it a uniform data type for pushing to stack temp = current; // if the current character is a left parentheses // pushes it to the stack if (parentheses(current) == -1) push(temp); // if the current character is a right parentheses // pops everything in the stack and adds it to the postfix expr // until a left parentheses is found else if (parentheses(current) == 1) { while (peek()[0] != '('){ postfix += pop() + " "; } pop(); // popping the left parentheses } // if the stack is empty pushes the operator to stack // or the precedence of current operator is greater that the precedence of the stack top else if (is_empty() || operator_precedence(current) > operator_precedence(peek()[0])) push(temp); else { // pops all operators which have lower precedence than the current operator // then pushes the current operator to the stack while(!is_empty() && (operator_precedence(current) <= operator_precedence(peek()[0]))) { postfix += pop() + " "; } push(temp); } } } return postfix; } // initialize stack for operators int int_stack[500]; int int_top = -1; void int_push(int data) { if(int_top != 499) int_stack[++int_top] = data; } int int_pop() { if (int_top != -1) return int_stack[int_top--]; else return 1; } // takes operators, operators and applies it int apply_operator(int a, int b, char op) { switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': return a / b; case '^': return pow(a,b); default: return 0; } } int main() { std::string infix; std::cin >> infix; std::string postfix = infix_to_postfix(infix); char current; int number; // traverses the postfix expression for (int i = 0; i < MAX && postfix[i] != '\0'; i++) { current = postfix[i]; if (current == ' ') { continue; } if (isdigit(current)) { number = (int) current - '0'; // if the current char is an number, // it checks adjacent chars to find out the complete number while (i+1 < MAX && postfix[i+1] != '\0' && isdigit(postfix[i+1])){ current = postfix[++i]; number = number*10 + ((int)current - '0'); } int_push(number); // pushing number to the stack } else if (operator_precedence(current)) { // pops two numbers and applies the operator // then pushes back the result to the stack int_push(apply_operator(int_pop(), int_pop(), current)); } } std::cout << "ans = " << int_pop() << std::endl; return 0; }
true
7ecf27cc4b336bb789b5281bdddf47609bf8b349
C++
droneRL2020/DS_Algorithms
/backtracking_recursion/79. Word Search/79. Word Search/79. Word Search.cpp
UTF-8
1,601
3.390625
3
[]
no_license
//5:30pm start // #include <iostream> #include <vector> using namespace std; class Solution { public: bool exist(vector<vector<char>>& board, string word) { bool res; for (int i = 0; i < board.size(); ++i) { for (int j = 0; j < board[0].size(); ++j) { res = rec(board, word, i, j); if (res == true) { return res; } } }return res; } bool rec(vector<vector<char>>& board, const string& word, int i = 0, int j = 0, int flag = 0) { char temp; bool res; if (flag == word.size()) { return true; } else { if (((i > -1) and (j > -1) and (i < board.size()) and (j < board[0].size())) == false) { return false; } else { if ((board[i][j] != word[flag])) { return false; } else { flag += 1; temp = board[i][j]; // why not string temp board[i][j] = '-'; res = rec(board, word, i, j + 1, flag) or rec(board, word, i + 1, j, flag) or rec(board, word, i, j - 1, flag) or rec(board, word, i - 1, j, flag); board[i][j] = temp; return res; } } } } }; int main() { Solution solution; vector<vector<char>> board{ {'A','B','C','E'},{'S','F','C','S'},{'A','D','E','E'} }; string word = "ABCB"; cout<< solution.exist(board, word); return 0; }
true
0e39f1e01ff0e1c625d54fbaeb6045d9b6d179cf
C++
pathfinder-for-autonomous-navigation/FlightSoftware
/test/test_fsw_fault_handler/test_super_simple_fault_handler.cpp
UTF-8
4,858
2.96875
3
[ "MIT" ]
permissive
#include "test_fault_handlers.hpp" #include <fsw/FCCode/SimpleFaultHandler.hpp> class TestFixtureSuperSimpleFH { protected: StateFieldRegistryMock registry; public: std::shared_ptr<WritableStateField<unsigned char>> mission_state_fp; std::shared_ptr<Fault> fault_fp; std::unique_ptr<SuperSimpleFaultHandler> fault_handler; const std::vector<mission_state_t> active_states {mission_state_t::follower}; TestFixtureSuperSimpleFH(mission_state_t recommended_state) : registry() { TimedControlTaskBase::control_cycle_count = 0; Fault::cc = &TimedControlTaskBase::control_cycle_count; mission_state_fp = registry.create_writable_field<unsigned char>("pan.state", 12); fault_fp = registry.create_fault("fault", 1); fault_handler = std::make_unique<SuperSimpleFaultHandler>( registry, fault_fp.get(), active_states, recommended_state); set(mission_state_t::follower); // Start in an active state for the fault handler. } void set(mission_state_t state) { mission_state_fp->set(static_cast<unsigned char>(state)); } fault_response_t step(bool signal_fault) { if (signal_fault) fault_fp->signal(); else fault_fp->unsignal(); fault_response_t ret = fault_handler->execute(); TimedControlTaskBase::control_cycle_count++; return ret; } }; /** * @brief Test a simple fault handler that recommends the safehold * state when its underlying fault is faulted. */ void test_super_simple_fh_safehold() { TestFixtureSuperSimpleFH tf(mission_state_t::safehold); fault_response_t response = tf.step(false); // When fault is unsignaled, the recommended fault response should be ignorable. TEST_ASSERT_EQUAL(fault_response_t::none, response); // Signal the fault. Now, the recommended fault response should be to go to safehold. tf.step(true); response = tf.step(true); TEST_ASSERT_EQUAL(fault_response_t::safehold, response); // Unsignal the fault. The fault response should be ignorable again. response = tf.step(false); TEST_ASSERT_EQUAL(fault_response_t::none, response); } /** * @brief Test a simple fault handler that recommends the standby * state when its underlying fault is faulted. */ void test_super_simple_fh_standby() { TestFixtureSuperSimpleFH tf(mission_state_t::standby); fault_response_t response = tf.step(false); // When fault is unsignaled, the recommended fault response should be ignorable. TEST_ASSERT_EQUAL(fault_response_t::none, response); // Signal the fault. Now, the recommended fault response should be to go to standby. tf.step(true); response = tf.step(true); TEST_ASSERT_EQUAL(fault_response_t::standby, response); // Unsignal the fault. The fault response should be ignorable again. response = tf.step(false); TEST_ASSERT_EQUAL(fault_response_t::none, response); } /** * @brief Test that a simple fault handler does not recommend any * fault response when it is in a non-active mission state. */ void test_super_simple_fh_active_states() { // The test begins in an active state for the fault handler. TestFixtureSuperSimpleFH tf(mission_state_t::standby); // Get the fault to be signaled. The recommended fault response should be to go to standby. tf.step(true); fault_response_t response = tf.step(true); TEST_ASSERT_EQUAL(fault_response_t::standby, response); // Move the mission state into a non-active state. The recommended fault response should // become "no response" even though the fault has remained signaled. tf.set(mission_state_t::startup); response = tf.step(true); TEST_ASSERT_EQUAL(fault_response_t::none, response); // If we enter a non-active state with the fault being unsignaled, and then signal the // fault, the fault handler still suggests no response. tf.step(false); tf.step(true); response = tf.step(true); TEST_ASSERT_EQUAL(fault_response_t::none, response); // Going back into an active state with the fault triggered causes the fault handler // to suggest the "go to standby" response. tf.set(mission_state_t::follower); response = tf.step(true); TEST_ASSERT_EQUAL(fault_response_t::standby, response); // Suppose we start in a non-active state, and the fault is just about to be signaled. // If we transition to an active state, the fault will be triggered. tf.set(mission_state_t::startup); tf.step(false); tf.step(true); tf.set(mission_state_t::follower); response = tf.step(true); TEST_ASSERT_EQUAL(fault_response_t::standby, response); } void test_super_simple_fault_handlers() { RUN_TEST(test_super_simple_fh_safehold); RUN_TEST(test_super_simple_fh_standby); RUN_TEST(test_super_simple_fh_active_states); }
true
ac3ca27338bc28b6f608818ccbc5ffd166b62646
C++
Debopriyasaha/lab9
/lab9_q12.cpp
UTF-8
451
3.203125
3
[]
no_license
#include<iostream> using namespace std; int main(){ int a=2, b=3, c=b; //declare variable int *ptr = &a; //point to a c = *ptr; //printing value a, b and *ptr cout << "variable 1= " << a <<endl; cout << "variable 2 = " << c << endl; cout << "pointer " << *ptr <<endl; ptr = &b; //printing value a, b and *ptr cout << "variable 1" << a <<endl; cout << "variable 2" << b << endl; cout << "pointer " << *ptr <<endl; return 0; }
true
9c628ba7649a03a0ddd968b52af48d146b621a38
C++
rituraj2847/spoj
/PRIME1/PRIME1.cpp
UTF-8
993
2.84375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; #define MAXN 1000000020 int main() { int maxa = sqrt(MAXN), maxb = sqrt(maxa) + 1; vector<bool> prime(maxa, 1); for(int i = 2; i <= maxb; i++) { if (prime[i]) for(int j = i*i; j < maxa; j += i) prime[j] = 0; } int primes[3410], p = 0; for(int j = 2; j < maxa; j++) { if (prime[j]) primes[p++] = j; } int t, a, b; scanf("%i", &t); while(t--) { scanf("%i %i", &a, &b); int n = b - a + 1; vector<bool> isprime(n, 1); if (a == 1) isprime[0] = 0; for(int i = 0; i < p; i++) { int pr = primes[i]; int x = (a%pr)?a/pr+1:a/pr, y = b/pr; for(int j = x; j <= y; j++) { int m = pr * j; if (m >= a && m <= b && j != 1) isprime[m-a] = 0; } } for(int i = 0; i < n; i++) if (isprime[i]) printf("%i\n", i+a); printf("\n"); } return 0; } /** * Find all primes till sqrt(1000000000) using * simple sieve. Then sieve again in the range * [m, n] using these primes. Ta da! */
true
cd14885de3e969388f4dda4f7d0c99f71543a83b
C++
victorsenam/treinos-old
/na2th/codeforces/308-div2/A/table.cpp
UTF-8
537
2.515625
3
[]
no_license
#include<cstdio> #define MAX 102 using namespace std; typedef int num; num grid[MAX][MAX]; num n, x1, y1, x2, y2; int main() { scanf("%d", &n); for( int i = 0; i < MAX*MAX; i++ ) grid[i/MAX][i%MAX] = 0; while( n-- > 0 ) { scanf("%d %d %d %d", &x1, &y1, &x2, &y2); for( num x = x1; x <= x2; x++ ) for( num y = y1; y <= y2; y++ ) grid[x][y]++; } num ans = 0; for( int i = 0; i < MAX*MAX; i++ ) ans += grid[i/MAX][i%MAX]; printf("%d\n", ans); }
true
f46b557d9f9b981798656b4531930cfa8b53c93b
C++
yliu-cs/ACM
/PTA/团体程序设计天梯赛-练习集-L1-048.cpp
UTF-8
1,902
2.53125
3
[]
no_license
#include <stdio.h> #include <iostream> #include <string> #include <cstring> #include <algorithm> #include <iomanip> #include <cctype> #include <cmath> #include <stack> #include <queue> #include <vector> #include <cstdlib> #include <sstream> using namespace std; #define mem(a,b) memset(a,b,sizeof(a)) typedef long long ll; int main() { ios::sync_with_stdio(0); cin.tie(0); int r1, c1; cin >> r1 >> c1; int **num1; num1 = new int*[r1]; for (int i = 0; i < r1; ++i) { num1[i] = new int[c1]; } for (int i = 0; i < r1; ++i) { for (int j = 0; j < c1; ++j) { cin >> num1[i][j]; } } int r2, c2; cin >> r2 >> c2; int **num2; num2 = new int*[r2]; for (int i = 0; i < r2; ++i) { num2[i] = new int[c2]; } for (int i = 0; i < r2; ++i) { for (int j = 0; j < c2; ++j) { cin >> num2[i][j]; } } if (c1 != r2) { cout << "Error: " << c1 << " != " << r2; } else { int **res; res = new int*[r1]; for (int i = 0; i < r1; ++i) { res[i] = new int[c2]; } for (int i = 0; i < r1; ++i) { for (int j = 0; j < c2; ++j) { res[i][j] = 0; } } for (int i = 0; i < r1; ++i) { for (int j = 0; j < c2; ++j) { for (int k = 0; k < c1; ++k) { res[i][j] += num1[i][k] * num2[k][j]; } } } cout << r1 << " " << c2 << endl; for (int i = 0; i < r1; ++i) { for (int j = 0; j < c2; ++j) { cout << res[i][j]; if (j != c2 - 1) { cout << " "; } } cout << endl; } } return 0; }
true
a6b5987e31f0624e1e16d24e31b58896141d08b6
C++
nitish166/Interview-Prepration
/LeetCodeJune/UniquePaths.cpp
UTF-8
528
2.828125
3
[]
no_license
class Solution { public: int uniquePaths(int m, int n) { vector<vector<int>> paths(n, vector<int>(m)); for(int c=0; c<m; c++) { paths[n-1][c]=1; } for(int r=0; r<n; r++) { paths[r][m-1]=1; } for(int r=n-2; r>=0; r--) { for(int c=m-2; c>=0; c--) { paths[r][c] = paths[r][c+1] + paths[r+1][c]; } } return paths[0][0]; } };
true
c28a0dbe41188c5eada771571b85ba3e65332d01
C++
mark-smits/CSD2
/csd2d/Juce Plugin/Source/Phasor.cpp
UTF-8
831
2.5625
3
[]
no_license
/* ============================================================================== Phasor.cpp Created: 30 May 2021 4:59:32pm Author: marks ============================================================================== */ #include "../JuceLibraryCode/JuceHeader.h" #include "Phasor.h" Phasor::Phasor() { this->samplerate = 44100; } Phasor::Phasor(double samplerate) : samplerate(samplerate) { phase_increment = frequency / samplerate; } Phasor::~Phasor() { } double Phasor::getVal() { return phase; } void Phasor::setFrequency(double freq) { frequency = freq; phase_increment = frequency / samplerate; } void Phasor::setSamplerate(double sr_in) { samplerate = sr_in; } void Phasor::tick() { phase += phase_increment; while (phase > 1.0) { phase -= 1.0; } }
true
5b983bebb55a7726ce4ef1a7a65dd81869036bc6
C++
sergeyborov8/lab11
/hunter/_Base/c712822/e1266bb/83da1ac/Install/include/print.hpp
UTF-8
1,189
3.15625
3
[]
no_license
#include <string> #include <fstream> #include <iostream> /*! \brief Функция копирования \param[in] text Копирование текстовой строки \param[out] out Вывод текстовой строки на экран Данная функция копирует текстовую строку и выводит её на экран для контроля. Код функции выглядит следующим образом: \code void print(const std::string& text, std::ostream& out = std::cout); \endcode */ void print(const std::string& text, std::ostream& out = std::cout); /*! \brief Функция копирования \param[in] text Копирование текстовой строки \param[out] out Вывод текстовой строки на экран Данная функция копирует текстовую строку и выводит её на экран для контроля. Код функции выглядит следующим образом: \code void print(const std::string& text, std::ofstream& out); \endcode */ void print(const std::string& text, std::ofstream& out);
true
ad3db45e36de53c478e64836785259ed84854646
C++
torgiren/szkola
/semestr_5/numerki/9/main.cpp
UTF-8
1,423
2.640625
3
[]
no_license
#include <iostream> #include <math.h> #include <nrutil.h> #include <nrutil.c> #include <sinft.c> #include <realft.c> #include <four1.c> #include <time.h> using namespace std; float omega; long n; float y(float i); int main(int argc, char* argv[]) { srand(time(NULL)); if(argc<2) { cerr<<"Usage: "<<argv[0]<<" <k>"<<endl; return -1; }; int k=atoi(argv[1]); n=pow(2,k); omega=4*M_PI/(n); long x; float *data=new float[n]; FILE *plik=fopen("f.dat","w+"); FILE *plik2=fopen("f3.dat","w"); if(!plik) { cerr<<"File error"<<endl; return -2; }; for(x=0;x<n;x++) { data[x]=y(x); fprintf(plik2,"%d %f\n",x,data[x]); float r=rand(); float szum=r/(RAND_MAX+1.0); if(((float)rand()/(RAND_MAX+1.0)<0.5)) szum*=-1; data[x]+=szum; // cout<<x<<" "<<data[x]<<endl; fprintf(plik,"%d %f\n",x,data[x]); }; fclose(plik); // cout<<endl; sinft(data,n); plik=fopen("f2.dat","w+"); for(x=0;x<n;x++) { fprintf(plik,"%d %f\n",x,data[x]); // cout<<x<<" "<<data[x]<<endl; }; float max=0; for(x=0;x<n;x++) { if(data[x]>max) max=data[x]; }; for(x=0;x<n;x++) { if(data[x]<0.25*max) data[x]=0; }; sinft(data,n); fclose(plik); plik=fopen("f4.dat","w+"); for(x=0;x<n;x++) { data[x]*=2.0/n; fprintf(plik,"%d %f\n",x,data[x]); // cout<<x<<" "<<data[x]<<endl; }; fclose(plik); fclose(plik2); return 0; }; float y(float i) { return sin(omega*i)+sin(2*omega*i)+sin(3*omega*i); };
true
2929f2a8a7b84643e6b1841fe09b9c2f35841b5f
C++
michaeldoylecs/RocketAnalytics
/RocketAnalyticsLib/include/Keyframe.hpp
UTF-8
777
2.640625
3
[ "MIT" ]
permissive
/****************************************************************************** * Author: Michael Doyle * Date: 2/19/18 * File: Keyframe.hpp * Description: * Represents a Keyframe. *****************************************************************************/ #ifndef KEYFRAME_HPP #define KEYFRAME_HPP #include <cstdint> namespace rocketanalytics { class Keyframe { public: Keyframe(float time, std::uint32_t frame, std::uint32_t filePos); float time() const; std::uint32_t frame() const; std::uint32_t filePos() const; bool operator==(const Keyframe &k1) const; bool operator!=(const Keyframe &k1) const; private: float k_time; std::uint32_t k_frame; std::uint32_t k_filePos; }; } // namespace rocketanalytics #endif
true
3373fee4a49f2da6f3a5904d6f70cf047bcf3db4
C++
georgerapeanu/c-sources
/C - Train Ticket/main.cpp
UTF-8
565
2.59375
3
[]
no_license
#include <iostream> #include <cstdlib> using namespace std; string rez; int V[5]; char C[10]; void btr(int pas,int sum) { if(pas>4) { if(sum==7) { rez+="=7"; cout<<rez; exit(0); } return ; } rez+="+";rez+=(V[pas]+'0'); btr(pas+1,sum+V[pas]); rez[rez.size()-2]='-'; btr(pas+1,sum-V[pas]); rez.pop_back(); rez.pop_back(); } int main() { cin.getline(C+1,5); for(int i=1;i<5;i++) V[i]=C[i]-'0'; rez+=(V[1]+'0'); btr(2,V[1]); return 0; }
true
2c358de8912c9336ab8f7dd05e7f4a1b6c66780a
C++
veksku/R210_Algorithm_Construction_and_Analysis
/3_cas/kodovi/1.cpp
UTF-8
908
3.546875
4
[]
no_license
#include <iostream> #include <vector> #include <cmath> using namespace std; void build_segment_tree(vector<int> &array, vector<int> &segment_tree, int k, int x, int y){ if(x == y){ segment_tree[k] = array[x]; return; } int middle = (x + y) / 2; build_segment_tree(array, segment_tree, 2*k + 1, x, middle); build_segment_tree(array, segment_tree, 2*k + 2, middle + 1 , y); segment_tree[k] = segment_tree[2*k + 1] + segment_tree[2*k + 2]; //za k=0 je ovo dodela vrednosti korenu } int main(){ vector<int> array = { 1, 2, 3, 4, 5, 6, 7, 8 }; int n = array.size(); int height = ceil(log2(n)); int size = 2 * pow(2, height) - 1; vector<int> segment_tree(size); build_segment_tree(array, segment_tree, 0, 0, n-1); for(int x : segment_tree) cout << x << " "; cout << endl; return 0; }
true
2d6df6d1391a014b4172335e604229dcdf257364
C++
dhnesh12/codechef-solutions
/03-CodeChef-Medium/23--Jumping Fever.cpp
UTF-8
6,185
2.53125
3
[]
no_license
#include "bits/stdc++.h" using namespace std; #ifndef LOCAL #define endl '\n' #endif #define fr(i, a, b) for(int i = a; i <= b; i++) #define rf(i, a, b) for(int i = a; i >= b; i--) #define pf push_front #define pb push_back #define fi first #define se second #define all(x) x.begin(), x.end() #define rall(x) x.rbegin(), x.rend() #define sz(x) (int)x.size() #define rsz resize() #define lb lower_bound #define ub upper_bound #define br cout << endl typedef long long ll; typedef long double f80; typedef pair<int,int> pii; typedef pair<ll,ll> pll; int pct(int x) { return __builtin_popcount(x); } int pct(ll x) { return __builtin_popcountll(x); } int bit(int x) { return 31 - __builtin_clz(x); } // floor(log2(x)) int bit(ll x) { return 63 - __builtin_clzll(x); } // floor(log2(x)) int cdiv(int a, int b) { return a / b + !(a < 0 || a % b == 0); } ll cdiv(ll a, ll b) { return a / b + !(a < 0 || a % b == 0); } template<typename T> void leftShift(vector<T> &v, ll k) { k %= sz(v); if(k < 0) k += sz(v); rotate(v.begin(), v.begin() + k, v.end()); } template<typename T> void rightSift(vector<T> &v, ll k) { leftShift(v, sz(v) - k); } mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count()); ll rand(ll l, ll r){ uniform_int_distribution<ll> uid(l, r); return uid(rng); } inline int nxt() { int x; cin >> x; return x; } inline ll nxtll() { ll x; cin >> x; return x; } void pr() {} void sc() {} template <typename Head, typename... Tail> void pr(Head H, Tail... T) { cout << H << " "; pr(T...); } template <typename Head, typename... Tail> void sc(Head &H, Tail &... T) { cin >> H; sc(T...); } #ifdef LOCAL #define debug(...) cerr << "[L:" << __LINE__ << "][" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__) #else #define debug(...) 42 #endif #ifndef LOCAL string to_string(__int128 x) { string s = ""; bool neg = 0; if(x < 0) { s += "-"; neg = 1; x = -x; } if(!x) s += '0'; while(x) { int rem = x % 10; s += to_string(rem); x /= 10; } reverse(s.begin() + neg, s.end()); return s; } #endif const int mod = 1e9 + 7; // 998244353; int pwr(int a,int b) { int ans = 1; while(b) { if(b & 1) ans = (ans * 1LL * a) % mod; a = (a * 1LL * a) % mod; b >>= 1; } return ans; } /* Lookout for overflows!! Check array sizes!! Clear before test cases!! Use the correct modulo!! Check for corner cases!! Are you forgetting something?! Read problem statement carefully!!! */ /** * Author: Simon Lindholm * Date: 2017-04-20 * License: CC0 * Source: own work * Description: Container where you can add lines of the form kx+m, and query maximum values at points x. * Useful for dynamic programming (``convex hull trick''). * Time: O(\log N) * Status: stress-tested */ struct Line { mutable ll k, m, p; bool operator<(const Line& o) const { return k < o.k; } bool operator<(ll x) const { return p < x; } }; struct LineContainer : multiset<Line, less<>> { // (for doubles, use inf = 1/.0, div(a,b) = a/b) const ll inf = LLONG_MAX; ll div(ll a, ll b) { // floored division return a / b - ((a ^ b) < 0 && a % b); } bool isect(iterator x, iterator y) { if (y == end()) { x->p = inf; return false; } if (x->k == y->k) x->p = x->m > y->m ? inf : -inf; else x->p = div(y->m - x->m, x->k - y->k); return x->p >= y->p; } void add(ll k, ll m) { auto z = insert({k, m, 0}), y = z++, x = y; while (isect(y, z)) z = erase(z); if (x != begin() && isect(--x, y)) isect(x, y = erase(y)); while ((y = x) != begin() && (--x)->p >= y->p) isect(x, erase(y)); } ll query(ll x) { if(empty()) return -1e18; auto l = *lower_bound(x); return l.k * x + l.m; } }; const int N = 3e5 + 5; ll a[N], depth[N], sz[N], s[N], p[N], r[N], dp[N], dp1[N]; ll ans = -1e18; vector<int> g[N]; LineContainer ch[N], ch1[N]; int lol[N]; void pre_dfs(int u,int pp) { depth[u] = depth[pp] + 1; sz[u] = 1; s[u] = s[pp] + a[u]; r[u] = r[pp] + s[u]; p[u] = p[pp] + depth[u] * 1LL * a[u]; for(int v : g[u]) { if(v != pp) { pre_dfs(v, u); sz[u] += sz[v]; } } } void _add(int ss,int u) { ch[ss].add(s[u], p[u] + dp[u]); } ll _query(int ss, int u2, int u) { int l2 = depth[u2] - depth[u] - 1; ll x = l2 + 2 - depth[u]; ll c = dp1[u2] - p[u] + depth[u] * s[u] - (l2 + 2) * s[u] + a[u] * (l2 + 2) + (r[u2] - r[u]) - (l2 + 1) * s[u]; return ch[ss].query(x) + c; } void _add1(int ss,int u) { ch1[ss].add(depth[u], r[u] + dp1[u]); } ll _query1(int ss, int u2, int u) { int l2 = depth[u2] - depth[u] - 1; ll x = -2 * s[u] + a[u] + s[u2]; ll c = dp[u2] + p[u2] - p[u] + 2 * depth[u] * s[u] - depth[u] * s[u2] + (-depth[u] + 1) * (s[u2] - s[u]) - r[u] - depth[u] * a[u] + a[u]; return ch1[ss].query(x) + c; } void dfs2(int u2, int p, int u, bool add) { if(!add) { ans = max(ans, _query(lol[u], u2, u)); ans = max(ans, _query1(lol[u], u2, u)); } else { _add(lol[u], u2); _add1(lol[u], u2); } for(int v : g[u2]) { if(v != p) { dfs2(v, u2, u, add); } } } void dfs(int u,int p) { int hc = -1, S = -1; for(int v : g[u]) { if(v != p) { dfs(v, u); if(sz[v] > S) { S = sz[v], hc = v; } } } if(hc == -1) { lol[u] = u; } else { lol[u] = lol[hc]; } for(int v : g[u]) { if(v != p && v != hc) { dfs2(v, u, u, 0); dfs2(v, u, u, 1); } } ll q = _query(lol[u], u, u); ll q1 = _query1(lol[u], u, u); dp[u] = max(q, 0LL); dp1[u] = max(q1, 0LL); ans = max(ans, q); ans = max(ans, q1); _add(lol[u], u); _add1(lol[u], u); } void solve() { ans = -1e18; int n; sc(n); fr(i, 1, n) { ch[i].clear(); ch1[i].clear(); dp[i] = dp1[i] = 0; r[i] = p[i] = s[i] = 0; g[i].clear(); sc(a[i]); } fr(i, 1, n - 1) { int u, v; sc(u, v); g[u].pb(v); g[v].pb(u); } int r = 1; pre_dfs(r, 0); dfs(r, 0); pr(ans); br; } signed main() { ios :: sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin >> t; // t = 1; for(int tt = 1; tt <= t; tt++) { solve(); } return 0; }
true
f76580ba165dc75baa6e6c38b4780a8227d0db91
C++
thejustinwalsh/libbulletml
/include/bulletmltree.h
UTF-8
2,614
2.828125
3
[ "BSD-3-Clause", "MIT" ]
permissive
/// BulletMLツリー。 /// BulletML Tree. /** * BulletML に特化していて非常にいんちきくさいのが特徴。 * Specialized in BulletML, characterized by being extremely cheap. */ #ifndef BULLETMLTREE_H_ #define BULLETMLTREE_H_ #include <algorithm> #include <memory> #include <string> #include <vector> #include "bulletmlcommon.h" #include "formula.h" #include "tree.h" class BULLETML_API BulletMLNode : public TreeNode<BulletMLNode> { public: typedef Formula<double> Number; typedef enum { none, aim, absolute, relative, sequence, typeSize } Type; typedef enum { bullet, action, fire, changeDirection, changeSpeed, accel, wait, repeat, bulletRef, actionRef, fireRef, vanish, horizontal, vertical, term, times, direction, speed, param, bulletml, nameSize } Name; private: static Type string2type(const std::string &str); static Name string2name(const std::string &str); static std::string name2string[nameSize]; public: typedef TreeNode<BulletMLNode>::Children Children; typedef TreeNode<BulletMLNode>::ChildIterator ChildIterator; public: explicit BulletMLNode(const std::string &name); virtual ~BulletMLNode(); Name getName() const { return m_name; } void setValue(const std::string &val); double getValue() const { return m_val->value(); } void setType(const std::string &type) { m_type = string2type(type); } Type getType() const { return m_type; } void setRefID(int id) { m_refID = id; } int getRefID() const { return m_refID; } BulletMLNode *getChild(Name name); /* template <class TOutIter> void getAllChildren(Name name, TOutIter outIter); */ void getAllChildrenVec(Name name, std::vector<BulletMLNode *> &outvec); /// 子孫の中に指定した名前に一致するものがあるかどうか /// Whether there is any match in the descendants with the specified name bool findNode(Name name) const; BulletMLNode *next(); virtual void dump(); protected: Name m_name; Type m_type; int m_refID; std::unique_ptr<Number> m_val; }; /* template <class TOutIter> void BulletMLNode::getAllChildren(Name name, TOutIter outIter) { ChildIterator it; for (it = childBegin(); it != childEnd(); it++) { if ((*it)->getName() == name) *outIter = *it; outIte++; } } */ #endif // ! BULLETMLTREE_H_
true
538a889f362548d263a331134283cfe2fd39410d
C++
GMohn/proj5
/src/testcsv.cpp
UTF-8
664
3.1875
3
[]
no_license
#include <gtest/gtest.h> #include "CSVReader.h" #include <sstream> TEST(CSVReader,EmptyTest){ std::stringstream Input; CCSVReader Reader(Input); EXPECT_TRUE(Reader.End()); } TEST(CSVReader,SingleLineTest){ std::stringstream Input(" 1,2 , 3 ,4,5\x0d\x0a"); CCSVReader Reader(Input); std::vector<std::string> Row; EXPECT_TRUE(Reader.ReadRow(Row)); EXPECT_EQ(Row.size(), 5); if(5<= Row.size()){ EXPECT_EQ(Row[0],"1"); EXPECT_EQ(Row[1],"2"); EXPECT_EQ(Row[2],"3"); EXPECT_EQ(Row[3],"4"); EXPECT_EQ(Row[4],"5"); } EXPECT_TRUE(Reader.End()); }
true
822631d0820ad4421343df3bea5314e2bdf271d8
C++
kitakou0313/-
/aoj150king.cpp
UTF-8
771
2.609375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; #include <iostream> int main(){ int n; string st = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; cin >>n; while(n!=0){ string s; vector<int>key; string ans = ""; for(int i = 0; i<n;i++){ int x; cin >>x; key.push_back(x); } cin >>s; int ind = 0; for (int i = 0; i<(int)s.size(); i++){ char c; for (int j = 0; j < (int)st.size();j++){ if(s[i] == st[j]){ if(j - key[ind] < 0)c = st[j - key[ind] + 52]; else c = st[j - key[ind]]; } } ans = ans + c; ind++; if(ind >= (int)key.size()){ ind = 0; } } cout <<ans<<endl; key.clear(); cin >>n; } return 0; }
true
e3d90cba9e348e6176c317ae90ac2f4a284b14b3
C++
Kipsora/KitJudge
/tools/server/judger/comparator/spjByte.cpp
UTF-8
1,685
2.671875
3
[ "MIT" ]
permissive
#include <cstdio> #include <cstring> #include <algorithm> #include "spjbase.hpp" int main(int argc, char *argv[]) { try{ FILE *indat = fopen(argv[1], "r"); FILE *instd = fopen(argv[2], "r"); FILE *insrc = fopen(argv[3], "r"); if (indat == NULL) { throw SPJException("Cannot open the input data.", SPJ_SRC_IO_ERROR); } if (instd == NULL) { throw SPJException("Cannot open the stdfile.", SPJ_STD_IO_ERROR); } if (insrc == NULL) { throw SPJException("Cannot open the srcfile.", SPJ_SRC_IO_ERROR); } int size = 0; while (true) { char stdans = fgetc(instd); char srcans = fgetc(insrc); if ((stdans == EOF) ^ (srcans == EOF)) { printf("The stdfile's size differs from srcfile."); fclose(instd); fclose(insrc); return SPJ_WA; } if (stdans == EOF && srcans == EOF) { break; } if (stdans == '\r') stdans = '\n'; if (srcans == '\r') srcans = '\n'; size++; if (stdans != srcans) { if (size % 20 == 1) { printf("Read \"%c\", but expects \"%c\" at the %d-st token.\n", srcans, stdans, size); } else if (size % 20 == 2) { printf("Read \"%c\", but expects \"%c\" at the %d-nd token.\n", srcans, stdans, size); } else { printf("Read \"%c\", but expects \"%c\" at the %d-th token.\n", srcans, stdans, size); } fclose(instd); fclose(insrc); putScore(argc, argv, 0.0, SPJ_SCR_IO_ERROR); return SPJ_WA; } } printf("OK, %d tokens.\n", size); fclose(instd); fclose(insrc); fclose(indat); putScore(argc, argv, getScore(argc, argv, SPJ_SCR_IO_ERROR), SPJ_SCR_IO_ERROR); return SPJ_OK; } catch(SPJException e) { e.print(); return e.exitcode; } return 0; }
true
7094559ea743b2d16db2276b419045a915e33931
C++
zcaisse9876/caisse
/zmc/define/pair.cpp
UTF-8
884
3.40625
3
[]
no_license
template <typename T1, typename T2> pair<T1, T2>::pair(T1 first, T2 second) : first{first}, second{second} { } template <typename T1, typename T2> pair<T1, T2>::pair() { } template <typename T1, typename T2> bool pair<T1, T2>::operator==(pair<T1, T2> &src) { return this->first == src.first && this->second == src.second; } template <typename T1, typename T2> bool pair<T1, T2>::operator!=(pair<T1, T2> &src) { return !(this->first == src.first && this->second == src.second); } template <typename T1, typename T2> void pair<T1, T2>::swap(pair<T1, T2> &src) { T1 a = std::move(src.first); T2 b = std::move(src.second); src.first = std::move(this->first); src.second = std::move(this->second); this->first = std::move(a); this->second = std::move(b); } template <typename T1, typename T2> pair<T1, T2> make_pair(T1 first, T2 second) { return {first, second}; }
true
a66113887584c390dca330584f212d5ad8e47cfb
C++
357272055/Sorting-Algprithm
/mySort/mergeSort.h
UTF-8
1,162
3.140625
3
[]
no_license
#ifndef MERGESORT_H #define MERGESORT_H #include "dataList.h" template<class T> void Merge(dataList<T>& L1, dataList<T>& L2, const int left, const int middle, const int right, int& swapTime){ for(int k = left;k <= right;++k) L2[k] = L1[k]; int point1 = left, point2 = middle + 1, t = left; while(point1 <= middle && point2 <= right){ if(L2[point1] > L2[point2]){ L1[t++] = L2[point2++]; ++swapTime; } else{ L1[t++] = L2[point1++]; ++swapTime; } } while(point1 <= middle){ L1[t++] = L2[point1++]; ++swapTime; } while(point2 <= right){ L1[t++] = L2[point2++]; ++swapTime; } } template<class T> void MergeSort(dataList<T>& L, dataList<T>& L2, const int left, const int right, int& swapTime){ if(left >= right)return; int middle = (left + right) / 2; MergeSort(L, L2, left, middle, swapTime); MergeSort(L, L2, middle + 1, right, swapTime); Merge(L, L2, left, middle, right, swapTime); } template<class T> void MergeSort(dataList<T>& L, int left, int right, int& swapTime){ if(right == -1) right = L.currentSize - 1; swapTime = 0; dataList<T> L2(right - left); MergeSort(L, L2, left, right, swapTime); } #endif
true
e4dfa137a4c8a892dfb54a550dd22cb0a3ac4baf
C++
antonpriyma/BMSTU
/ Languages ​​and methods of programming/C++/Lab12/main.cpp
UTF-8
796
3.0625
3
[]
no_license
#include <iostream> #include <vector> #include <string> #include "OwnIterator.h" #include "Number.h" #include "PrefixIterator.h" using namespace std; typedef PrefixIterator iter; int main() { /* std:string in; cin>>in; String s(in); PrefixIterator iter=s.begin(); *iter='{'; *iter++; *iter='{'; for (iter=s.begin();!iter.is_end();iter++) { cout << *iter; }*/ vector<string> sample(3); for(int i=0;i<3;i++){ string s; cin>>s; sample[i]=s; } StringSeq seq(sample); PrefixIterator prefixIterator=seq.begin(); // cout << *prefixIterator; *prefixIterator="Jo"а; for(prefixIterator=seq.begin();!prefixIterator.is_end();prefixIterator++){ cout<<*prefixIterator; } return 0; }
true
43b45805dd9e366590151194c5082e6fa87518ce
C++
duwenjie/asio.demo
/echo_server/echo_server.cpp
GB18030
2,625
2.609375
3
[]
no_license
// echo_server.cpp : ̨Ӧóڵ㡣 // #include "stdafx.h" #include <iostream> #include <boost/asio.hpp> #include <boost/bind.hpp> #include <boost/shared_ptr.hpp> #include <boost/enable_shared_from_this.hpp> #include <string> using namespace boost::asio; struct TcpSession; typedef boost::shared_ptr<ip::tcp::socket> sock_ptr; typedef boost::shared_ptr<TcpSession> tcpSess_ptr; typedef buffers_iterator<streambuf::const_buffers_type> iterator; struct TcpSession : public boost::enable_shared_from_this<TcpSession> { TcpSession(io_service& service) : sock_(service) { } void start() { sock_.async_read_some(buffer(read_, 1024), boost::bind(&TcpSession::read_handler, shared_from_this(), _1, _2)); } void close() { if(sock_.is_open()) { sock_.close(); } } ip::tcp::socket& get_socket() { return sock_; } void read_handler(const boost::system::error_code& ec, size_t length) { if(ec) { std::cout << ec.message() << std::endl; } else { std::cout << "received: " << std::string(read_, length) << std::endl; sock_.async_write_some(buffer(read_, length), boost::bind(&TcpSession::write_handler, shared_from_this(), _1, _2)); } } void write_handler(const boost::system::error_code& ec, size_t length) { if(ec) { std::cout << ec.message() << std::endl; } else { std::cout << "send: " << std::string(read_, length) << std::endl; sock_.async_read_some(buffer(read_, 1024), boost::bind(&TcpSession::read_handler, shared_from_this(), _1, _2)); } } public: ip::tcp::socket sock_; char read_[1024]; }; struct Server { Server(io_service& service, ip::tcp::endpoint& ep) : service_(service), accept_(service_, ep) { tcpSess_ptr session = boost::shared_ptr<TcpSession>(new TcpSession(service_)); accept_.async_accept(session->get_socket(), boost::bind(&Server::accept_handler, this, session, _1)); } void accept_handler(tcpSess_ptr ptr, const boost::system::error_code& ec) { if(ec) { std::cout << ec.message() << std::endl; // } else { ptr->start(); std::cout << "ip: " << ptr->get_socket().remote_endpoint().address() << " port: " << ptr->get_socket().remote_endpoint().port() << std::endl; } ptr.reset(new TcpSession(service_)); accept_.async_accept(ptr->get_socket(), boost::bind(&Server::accept_handler, this, ptr, _1)); } private: io_service& service_; ip::tcp::acceptor accept_; }; int _tmain(int argc, _TCHAR* argv[]) { io_service service; ip::tcp::endpoint ep(ip::address_v4::any(), 12345); Server server(service, ep); service.run(); return 0; }
true
f424f26c3bb0279d1cd994292feda92922d6e99a
C++
JSarasua/Guildhall
/ThesisSubmission/Engine/Code/Engine/Math/MathUtils.cpp
UTF-8
25,721
2.984375
3
[]
no_license
#include "Engine/Math/MathUtils.hpp" #include <math.h> #include "Engine/Math/FloatRange.hpp" #include "Engine/Math/Vec2.hpp" #include "Engine/Math/Vec3.hpp" #include "Engine/Math/AABB2.hpp" #include "Engine/Math/IntVec2.hpp" #include "Engine/Math/OBB2.hpp" #include "Engine/Math/Capsule2.hpp" #include "Engine/Math/LineSegment2.hpp" #include "Engine/Math/Polygon2D.hpp" #include "Engine/Core/ErrorWarningAssert.hpp" #include "Engine/Core/EngineCommon.hpp" int absInt( int initialValue ) { return abs( initialValue ); } float absFloat( float initialValue ) { return fabsf( initialValue ); } float SignFloat( float val ) { return ( val >= 0.f ) ? 1.f : -1.f; } bool AlmostEqualsFloat( float a, float b, float epsilon /*= 0.01f*/ ) { float bMin = b - epsilon; float bMax = b + epsilon; if( a >= bMin && a <= bMax ) { return true; } return false; } float NaturalLog( float val ) { return logf( val ); } float SquareRootFloat( float value ) { return sqrtf( value ); } float ConvertDegreesToRadians( float orientationDegrees ) { float degreesToRadiansScale = 3.14159265f / 180.f; return orientationDegrees * degreesToRadiansScale; } float ConvertRadiansToDegrees( float orientationRadians ) { float RadiansToDegreesScale = 180.f /3.14159265f; return orientationRadians * RadiansToDegreesScale; } float CosDegrees( float orientationDegrees ) { return cosf( ConvertDegreesToRadians( orientationDegrees ) ); } float SinDegrees( float orientationDegrees ) { return sinf( ConvertDegreesToRadians( orientationDegrees ) ); } float TanDegrees( float orientationDegrees ) { return tanf( ConvertDegreesToRadians( orientationDegrees ) ); } float Atan2Degrees( float y, float x ) { return ConvertRadiansToDegrees( atan2f( y, x ) ); } float GetDistance2D( const Vec2& vectorA, const Vec2& vectorB ) { float diffX = vectorB.x - vectorA.x; float diffY = vectorB.y - vectorA.y; return sqrtf( (diffX*diffX) + (diffY*diffY) ); } float GetDistanceSquared2D( const Vec2& vectorA, const Vec2& vectorB ) { float diffX = vectorB.x - vectorA.x; float diffY = vectorB.y - vectorA.y; return (diffX*diffX) + (diffY*diffY); } int GetTaxicabDistance2D( const IntVec2& vectorA, const IntVec2& vectorB ) { IntVec2 displacementVec = vectorA - vectorB; return displacementVec.GetTaxicabLength(); } float GetDistance3D( const Vec3& vectorA, const Vec3& vectorB ) { float diffX = vectorB.x - vectorA.x; float diffY = vectorB.y - vectorA.y; float diffZ = vectorB.z - vectorA.z; return sqrtf( (diffX*diffX) + (diffY*diffY) + (diffZ*diffZ) ); } float GetDistanceXY3D( const Vec3& vectorA, const Vec3& vectorB ) { float diffX = vectorB.x - vectorA.x; float diffY = vectorB.y - vectorA.y; return sqrtf( (diffX*diffX) + (diffY*diffY) ); } float GetDistanceSquared3D( const Vec3& vectorA, const Vec3& vectorB ) { float diffX = vectorB.x - vectorA.x; float diffY = vectorB.y - vectorA.y; float diffZ = vectorB.z - vectorA.z; return (diffX*diffX) + (diffY*diffY) + (diffZ*diffZ); } float GetDistanceXYSquared3D( const Vec3& vectorA, const Vec3& vectorB ) { float diffX = vectorB.x - vectorA.x; float diffY = vectorB.y - vectorA.y; return (diffX*diffX) + (diffY*diffY); } float GetProjectedLength2D( const Vec2& sourceVector, const Vec2& ontoVector ) { Vec2 normalizedOntoVector = ontoVector.GetNormalized(); float projectedLength = sourceVector.x*normalizedOntoVector.x + sourceVector.y*normalizedOntoVector.y; return projectedLength; } const Vec2 GetProjectedOnto2D( const Vec2& sourceVector, const Vec2& ontoVector ) { Vec2 projectedVector = ontoVector.GetNormalized(); projectedVector *= GetProjectedLength2D( sourceVector, ontoVector ); return projectedVector; } float GetAngleDegreesBetweenVectors2D( const Vec2& vectorA, const Vec2& vectorB ) { float vecAOrientationDegrees = vectorA.GetAngleDegrees(); float vecBOrientationDegrees = vectorB.GetAngleDegrees(); float angleBetweenVectorsDegrees = vecAOrientationDegrees - vecBOrientationDegrees; angleBetweenVectorsDegrees = absFloat( angleBetweenVectorsDegrees ); return angleBetweenVectorsDegrees; } bool DoDiscsOverlap( const Vec2& vectorA, float radiusA, const Vec2& vectorB, float radiusB ) { float distanceBetweenVectors = GetDistance2D( vectorA, vectorB ); if( distanceBetweenVectors < (radiusA+radiusB) ) { return true; } return false; } bool DoSpheresOverlap( const Vec3& vectorA, float radiusA, const Vec3& vectorB, float radiusB ) { float distanceBetweenVectors = GetDistance3D( vectorA, vectorB ); if( distanceBetweenVectors < (radiusA+radiusB) ) { return true; } return false; } const Vec2 TransformPosition2D( const Vec2& position, float uniformScale, float rotationDegrees, const Vec2& translation ) { Vec2 transformedVec; transformedVec.x = position.x; transformedVec.y = position.y; transformedVec.x *= uniformScale; transformedVec.y *= uniformScale; transformedVec.RotateDegrees( rotationDegrees ); transformedVec.x += translation.x; transformedVec.y += translation.y; return transformedVec; } const Vec2 TransformPosition2D( const Vec2& position, const Vec2& iBasis, const Vec2& jBasis, const Vec2& translation ) { float newX = position.x*iBasis.x + position.y*jBasis.x; float newY = position.x*iBasis.y + position.y*jBasis.y; Vec2 transformedVec( newX, newY ); transformedVec += translation; return transformedVec; } const Vec3 TransformPosition3DXY( const Vec3& position, float scaleXY, float RotationDegrees, const Vec2& translationXY ) { Vec3 transformedVec = position.GetRotatedAboutZDegrees( RotationDegrees ); transformedVec.z = position.z; transformedVec.x *= scaleXY; transformedVec.y *= scaleXY; transformedVec.x += translationXY.x; transformedVec.y += translationXY.y; return transformedVec; } const Vec3 TransformPosition3DXY( const Vec3& position, const Vec2& iBasisXY, const Vec2& jBasisXY, const Vec2& translationXY ) { float newX = position.x*iBasisXY.x + position.y*jBasisXY.x; float newY = position.x*iBasisXY.y + position.y*jBasisXY.y; Vec3 transformedVec( newX, newY, position.z ); transformedVec += translationXY; return transformedVec; } float RangeMap( float InputMin, float InputMax, float outputMin, float outputMax, float inputScale ) { float displacement = inputScale - InputMin; float inputRange = InputMax - InputMin; float fraction = displacement/inputRange; float outputRange = outputMax - outputMin; float outputDisplacement = fraction * outputRange; float outputValue = outputDisplacement + outputMin; return outputValue; } Vec2 RangeMap( float inputMin, float inputMax, Vec2 outputMin, Vec2 outputMax, float inputScale ) { float scale = (inputScale - inputMin) / ( inputMax - inputMin ); Vec2 output = outputMin + scale * (outputMax - outputMin); return output; } float Interpolate( float rangeMin, float rangeMax, float rangeScale ) { float displacement = rangeMax - rangeMin; float outputValue = displacement * rangeScale; outputValue += rangeMin; return outputValue; } float Clampf( float rawValue, float inputMin, float inputMax ) { if( rawValue < inputMin ) { return inputMin; } else if( rawValue > inputMax ) { return inputMax; } return rawValue; } int ClampInt( int rawValue, int inputMin, int inputMax ) { if( rawValue < inputMin ) { return inputMin; } else if( rawValue > inputMax ) { return inputMax; } return rawValue; } double ClampDouble( double rawValue, double inputMin, double inputMax ) { if( rawValue < inputMin ) { return inputMin; } else if( rawValue > inputMax ) { return inputMax; } return rawValue; } float ClampZeroToOne( float rawValue ) { return Clampf( rawValue, 0.f, 1.f ); } int RoundDownToInt( float rawValue ) { int tempInt = static_cast<int>(floorf( rawValue )); return tempInt; } const Vec2 GetNearestPointOnDisc2D( const Vec2& point, const Vec2& discPosition, float radius ) { Vec2 nearestPoint = Vec2( point.x - discPosition.x, point.y - discPosition.y ); nearestPoint.ClampLength( radius ); nearestPoint += discPosition; return nearestPoint; } const Vec2 GetNearestPointOnAABB2D( const AABB2& aabb2, const Vec2& point ) { float nearestX = Clampf( point.x, aabb2.mins.x, aabb2.maxs.x ); float nearestY = Clampf( point.y, aabb2.mins.y, aabb2.maxs.y ); return Vec2( nearestX, nearestY ); } const Vec2 GetNearestPointOnInfiniteLine2D( const Vec2& refPos, const Vec2& somePointOnLine, const Vec2& anotherPointOnLine ) { Vec2 infiniteLineDirectionVector = anotherPointOnLine - somePointOnLine; Vec2 somePointToRefPos = refPos - somePointOnLine; Vec2 refPosProjectedOntoLine = GetProjectedOnto2D( somePointToRefPos, infiniteLineDirectionVector ); refPosProjectedOntoLine+= somePointOnLine; return refPosProjectedOntoLine; } const Vec2 GetNearestPointOnLineSegment2D( const Vec2& refPos, const Vec2& start, const Vec2& end ) { return GetNearestPointOnCapsule2D( refPos, start, end, 0.f ); } const Vec2 GetNearestPointOnCapsule2D( const Vec2& refPos, const Vec2& capsuleMidStart, const Vec2& capsuleMidEnd, float capsuleRadius ) { Vec2 startToRefPos = refPos - capsuleMidStart; Vec2 endToRefPos = refPos - capsuleMidEnd; Vec2 startToEnd = capsuleMidEnd - capsuleMidStart; Vec2 endToStart = capsuleMidStart- capsuleMidEnd; float startToRefPosOntoEndToStartProjectedLength = GetProjectedLength2D( startToRefPos, endToStart ); float endToRefPosOntoStartToEndProjectedLength = GetProjectedLength2D( endToRefPos, startToEnd ); Vec2 startToRefPosProjectedOntoStartToEnd = GetProjectedOnto2D( startToRefPos, startToEnd ); if( startToRefPosOntoEndToStartProjectedLength > 0.f ) { //Do disc check from startPos return GetNearestPointOnDisc2D( refPos, capsuleMidStart, capsuleRadius ); } else if( endToRefPosOntoStartToEndProjectedLength > 0.f ) { //Do disc check from endPos return GetNearestPointOnDisc2D( refPos, capsuleMidEnd, capsuleRadius ); } else { Capsule2 capsule = Capsule2( capsuleMidStart, capsuleMidEnd, capsuleRadius ); Vec2 center = capsule.GetCenter(); Vec2 fullDimensions = Vec2( capsule.GetBoneLength(), capsule.radius * 2.f ); Vec2 capsuleIBasis = startToEnd; capsuleIBasis.Normalize(); OBB2 capsuleOBB2 = OBB2( center, fullDimensions, capsuleIBasis ); return GetNearestPointOnOBB2D( refPos, capsuleOBB2 ); } } const Vec2 GetNearestPointOnOBB2D( const Vec2& refPos, const OBB2& box ) { return box.GetNearestPoint( refPos ); } // Vec3 const GetNearestPointOnLineSegment3D( Vec3 const& refPos, Vec3 const& start, Vec3 const& end ) // { // // } float Max( float a, float b ) { return (a>b) ? a : b; } float Min( float a, float b ) { return (a<b) ? a : b; } int MaxInt( int a, int b ) { return (a>b) ? a : b; } int MinInt( int a, int b ) { return (a<b) ? a : b; } int PositiveMod( int valueToMod, int modBy ) { int moddedValue = 0; int modFraction = valueToMod/modBy; moddedValue = absInt( valueToMod - modFraction*modBy ); return moddedValue; } bool DoAABBsOverlap2D( const AABB2& aabbA, const AABB2& aabbB ) //Slower than checking each case of no overlap, should be 4 if statements { //X float maxOfMinsX = Max( aabbA.mins.x, aabbB.mins.x ); float minOfMaxsX = Min( aabbA.maxs.x, aabbB.maxs.x ); //Y float maxOfMinsY = Max( aabbA.mins.y, aabbB.mins.y ); float minOfMaxsY = Min( aabbA.maxs.y, aabbB.maxs.y ); if( aabbA.IsPointInside( aabbB.mins ) || aabbB.IsPointInside( aabbA.mins ) ) { return true; } if( maxOfMinsX < minOfMaxsX && maxOfMinsY < minOfMaxsY ) { return true; } else { return false; } } bool DoDiscAndAABBOverlap2D( const Vec2& discPosition, float discRadius, const AABB2& aabb ) { Vec2 nearestPoint = GetNearestPointOnAABB2D( aabb, discPosition ); if( GetDistance2D( discPosition, nearestPoint ) < discRadius ) { return true; } return false; } bool DoDiscAndLineSegmentOverlap2D( Vec2 const& discPosition, float discRadius, LineSegment2 const& line ) { Vec2 nearestPoint = GetNearestPointOnLineSegment2D( discPosition, line.startPosition, line.endPosition ); return IsPointInsideDisc2D( nearestPoint, discPosition, discRadius ); } bool DoLineSegmentsOverlap2D( LineSegment2 const& lineA, LineSegment2 const& lineB ) { Vec2 lineAStartAndEndPositions[2]; Vec2 lineBStartAndEndPositions[2]; //obb.GetCornerPositions( OBBCornerPositions ); lineAStartAndEndPositions[0] = lineA.startPosition; lineAStartAndEndPositions[1] = lineA.endPosition; lineBStartAndEndPositions[0] = lineB.startPosition; lineBStartAndEndPositions[1] = lineB.endPosition; float lineAHalfLength = lineA.GetLength()*0.5f; FloatRange lineAIBasisRange = FloatRange( -lineAHalfLength, lineAHalfLength ); FloatRange lineBOnLineAIRange = GetRangeOnProjectedAxis( 2, lineBStartAndEndPositions, lineA.GetCenter(), lineA.GetIBasisNormal() ); if( !lineAIBasisRange.DoesOverlap( lineBOnLineAIRange ) ) { return false; } FloatRange lineAJBasisRange = FloatRange( 0.f, 0.f ); FloatRange LineBOnLineAJRange = GetRangeOnProjectedAxis( 2, lineBStartAndEndPositions, lineA.GetCenter(), lineA.GetJBasisNormal() ); if( !lineAJBasisRange.DoesOverlap( LineBOnLineAJRange ) ) { return false; } float lineBHalfLength = lineB.GetLength()*0.5f; FloatRange lineBIBasisRange = FloatRange( -lineBHalfLength, lineBHalfLength ); FloatRange lineAOnLineBIRange = GetRangeOnProjectedAxis( 2, lineAStartAndEndPositions, lineB.GetCenter(), lineB.GetIBasisNormal() ); if( !lineBIBasisRange.DoesOverlap( lineAOnLineBIRange ) ) { return false; } FloatRange lineBJBasisRange = FloatRange( 0.f, 0.f ); FloatRange lineAOnLineBJRange = GetRangeOnProjectedAxis( 2, lineAStartAndEndPositions, lineB.GetCenter(), lineB.GetJBasisNormal() ); if( !lineBJBasisRange.DoesOverlap( lineAOnLineBJRange ) ) { return false; } return true; } FloatRange GetRangeOnProjectedAxis( int numPoints, const Vec2* points, const Vec2& relativeToPos, const Vec2& axisNormal ) { FloatRange rangeOnProjectedAxis( 0.f, 0.f ); Vec2 pointToRelativePosFirst = points[0] - relativeToPos; float projectedValueFirst = GetProjectedLength2D( pointToRelativePosFirst, axisNormal ); rangeOnProjectedAxis.minimum = projectedValueFirst; rangeOnProjectedAxis.maximum = projectedValueFirst; for( int pointIndex = 1; pointIndex < numPoints; pointIndex++ ) { Vec2 pointToRelativePos = points[pointIndex] - relativeToPos; float projectedValue = GetProjectedLength2D( pointToRelativePos, axisNormal ); rangeOnProjectedAxis.minimum = Min( projectedValue, rangeOnProjectedAxis.minimum ); rangeOnProjectedAxis.maximum = Max( projectedValue, rangeOnProjectedAxis.maximum ); } return rangeOnProjectedAxis; } bool DoOBBAndOBBOverlap2D( const OBB2& boxA, const OBB2& boxB ) { Vec2 boxACornerPositions[4]; Vec2 boxBCornerPositions[4]; boxA.GetCornerPositions( boxACornerPositions ); boxB.GetCornerPositions( boxBCornerPositions ); FloatRange boxAOnAIRange; boxAOnAIRange.minimum = -boxA.m_halfDimensions.x; boxAOnAIRange.maximum = boxA.m_halfDimensions.x; FloatRange boxBOnAIRange = GetRangeOnProjectedAxis( 4, boxBCornerPositions, boxA.GetCenter(), boxA.GetIBasisNormal() ); if( !boxBOnAIRange.DoesOverlap( boxAOnAIRange ) ) { return false; } FloatRange boxAOnAJRange; boxAOnAJRange.minimum = -boxA.m_halfDimensions.y; boxAOnAJRange.maximum = boxA.m_halfDimensions.y; FloatRange boxBOnAJRange = GetRangeOnProjectedAxis( 4, boxBCornerPositions, boxA.GetCenter(), boxA.GetJBasisNormal() ); if( !boxBOnAJRange.DoesOverlap( boxAOnAJRange ) ) { return false; } FloatRange boxBOnBIRange; boxBOnBIRange.minimum = -boxB.m_halfDimensions.x; boxBOnBIRange.maximum = boxB.m_halfDimensions.x; FloatRange boxAOnBIRange = GetRangeOnProjectedAxis( 4, boxACornerPositions, boxB.GetCenter(), boxB.GetIBasisNormal() ); if( !boxAOnBIRange.DoesOverlap( boxBOnBIRange ) ) { return false; } FloatRange boxBOnBJRange; boxBOnBJRange.minimum = -boxB.m_halfDimensions.y; boxBOnBJRange.maximum = boxB.m_halfDimensions.y; FloatRange boxAOnBJRange = GetRangeOnProjectedAxis( 4, boxACornerPositions, boxB.GetCenter(), boxB.GetJBasisNormal() ); if( !boxAOnBJRange.DoesOverlap( boxBOnBJRange ) ) { return false; } return true; } bool DoOBBAndAABBOverlap2D( const OBB2& boxA, const AABB2& boxB ) { OBB2 boxBOBB2 = OBB2( boxB, 0.f ); return DoOBBAndOBBOverlap2D( boxA, boxBOBB2 ); } bool DoOBBAndLineSegmentOverlap2D( const OBB2& obb, const LineSegment2& line ) { Vec2 OBBCornerPositions[4]; Vec2 lineStartAndEndPositions[2]; obb.GetCornerPositions( OBBCornerPositions ); lineStartAndEndPositions[0] = line.startPosition; lineStartAndEndPositions[1] = line.endPosition; float lineHalfLength = line.GetLength()*0.5f; FloatRange lineIBasisRange = FloatRange( -lineHalfLength, lineHalfLength ); FloatRange obbOnLineIRange = GetRangeOnProjectedAxis( 4, OBBCornerPositions, line.GetCenter(), line.GetIBasisNormal() ); if( !lineIBasisRange.DoesOverlap( obbOnLineIRange ) ) { return false; } FloatRange lineJBasisRange = FloatRange( 0.f, 0.f ); FloatRange obbOnLineJRange = GetRangeOnProjectedAxis( 4, OBBCornerPositions, line.GetCenter(), line.GetJBasisNormal() ); if( !lineJBasisRange.DoesOverlap( obbOnLineJRange ) ) { return false; } FloatRange obbOnObbIRange; obbOnObbIRange.minimum = -obb.m_halfDimensions.x; obbOnObbIRange.maximum = obb.m_halfDimensions.x; FloatRange lineOnObbIRange = GetRangeOnProjectedAxis( 2, lineStartAndEndPositions, obb.GetCenter(), obb.GetIBasisNormal() ); if( !obbOnObbIRange.DoesOverlap( lineOnObbIRange ) ) { return false; } FloatRange obbOnObbJRange; obbOnObbJRange.minimum = -obb.m_halfDimensions.y; obbOnObbJRange.maximum = obb.m_halfDimensions.y; FloatRange lineOnObbJRange = GetRangeOnProjectedAxis( 2, lineStartAndEndPositions, obb.GetCenter(), obb.GetJBasisNormal() ); if( !obbOnObbJRange.DoesOverlap( lineOnObbJRange ) ) { return false; } return true; } bool DoOBBAndCapsuleOverlap2D( const OBB2& obb, const Capsule2& capsule ) { if( DoOBBAndOBBOverlap2D( obb, capsule.GetInnerBox() ) ) { return true; } else if( DoOBBAndDiscOverlap2D( obb, capsule.startPosition, capsule.radius ) ) { return true; } else if( DoOBBAndDiscOverlap2D( obb, capsule.endPosition, capsule.radius ) ) { return true; } else { return false; } } bool DoOBBAndDiscOverlap2D( const OBB2& obb, const Vec2& discCenter, float discRadius ) { Vec2 nearestPointOnOBB2 = obb.GetNearestPoint( discCenter ); if( GetDistance2D( nearestPointOnOBB2, discCenter ) < discRadius ) { return true; } return false; } bool DoPolygonAndDiscOverlap2D( const Polygon2D& poly, const Vec2& discCenter, float discRadius ) { Vec2 polyClosestPoint = poly.GetClosestPoint( discCenter ); return IsPointInsideDisc2D(polyClosestPoint, discCenter, discRadius ); } bool DoPolygonAndLineSegementOverlap2D( const Polygon2D& poly, const LineSegment2& line ) { size_t polyEdgeCount = poly.GetEdgeCount(); for( size_t polyEdgeIndex = 0; polyEdgeIndex < polyEdgeCount; polyEdgeIndex++ ) { LineSegment2 edgeLine; poly.GetEdge( &edgeLine.startPosition, &edgeLine.endPosition, polyEdgeIndex ); if( DoLineSegmentsOverlap2D( edgeLine, line ) ) { return true; } } if( poly.Contains( line.startPosition ) ) { return true; } return false; UNUSED( poly ); UNUSED( line ); } bool IsPointInsideDisc2D( const Vec2& point, const Vec2& discCenter, float discRadius ) { return DoDiscsOverlap( point, 0.f, discCenter, discRadius ); } bool IsPointInsideAABB2D( const Vec2& point, const AABB2& box ) { return box.IsPointInside( point ); } bool IsPointInsideCapsule2D( const Vec2& point, const Vec2& capsuleMidStart, const Vec2& capsuleMidEnd, float capsuleRadius ) { if( IsPointInsideDisc2D( point, capsuleMidStart, capsuleRadius ) ) { return true; } if( IsPointInsideDisc2D( point, capsuleMidEnd, capsuleRadius ) ) { return true; } Vec2 nearestPointOnCapsule = GetNearestPointOnLineSegment2D( point, capsuleMidStart, capsuleMidEnd ); float distanceToPoint = GetDistance2D( point, nearestPointOnCapsule ); if( distanceToPoint < capsuleRadius ) { return true; } return false; } bool IsPointInsideCapsule2D( const Vec2& point, const Capsule2& capsule ) { return IsPointInsideCapsule2D(point, capsule.startPosition, capsule.endPosition, capsule.radius ); } bool IsPointInsideOBB2D( const Vec2& point, const OBB2& box ) { return box.IsPointInside( point ); } bool IsPointInForwardSector2D( const Vec2& point, const Vec2& observerPos, float observerForwardDegrees, float apertureDegrees, float maxDist ) { Vec2 displacementVec = point - observerPos; float distanceBetweenPoints = displacementVec.GetLength(); if( distanceBetweenPoints > maxDist ) { return false; } float angularDisplacementDegrees = GetShortestAngularDisplacement( observerForwardDegrees, displacementVec.GetAngleDegrees() ); angularDisplacementDegrees = absFloat( angularDisplacementDegrees ); if( angularDisplacementDegrees < apertureDegrees*0.5f ) { return true; } return false; } void PushDiscsOutOfEachOther2D( Vec2& discA, float discARadius, Vec2& discB, float discBRadius ) { if( !DoDiscsOverlap( discA, discARadius, discB, discBRadius ) ) { return; } float overlap = (discARadius+discBRadius) - GetDistance2D( discA, discB ); overlap /= 2.f; Vec2 pushDiscs( discA - discB ); pushDiscs.ClampLength( overlap ); discA += pushDiscs; discB -= pushDiscs; } void PushDiscOutOfDisc2D( Vec2& discA, float discARadius, const Vec2& discB, float discBRadius ) { if( !DoDiscsOverlap( discA, discARadius, discB, discBRadius ) ) { return; } float overlap = (discARadius+discBRadius) - GetDistance2D( discA, discB ); Vec2 pushDiscs( discA - discB ); pushDiscs.ClampLength( overlap ); discA += pushDiscs; } void PushDiscOutOfPoint2D( Vec2& disc, float discRadius, const Vec2& point ) { //Get how far past radius point is. //Move disc that far back if( !DoDiscsOverlap( disc, discRadius, point, 0.f ) ) { return; } float overlap = discRadius - GetDistance2D( disc, point ); Vec2 pushDisc( disc - point ); pushDisc.ClampLength( overlap ); disc += pushDisc; } void PushDiscOutOfAABB2D( Vec2& disc, float discRadius, const AABB2& aabb ) { if( !DoDiscAndAABBOverlap2D( disc, discRadius, aabb ) || GetNearestPointOnAABB2D( aabb, disc ) == disc ) { return; } Vec2 nearestPoint( GetNearestPointOnAABB2D( aabb, disc ) ); PushDiscOutOfPoint2D( disc, discRadius, nearestPoint ); } float GetShortestAngularDisplacement( float oldOrientationDegrees, float newOrientationDegrees ) { float displacement = newOrientationDegrees - oldOrientationDegrees; while( displacement > 360.f || displacement < -360.f ) { if( displacement > 360.f ) { displacement -= 360.f; } else { displacement += 360.f; } } //float negativeDisplacement = oldOrientationDegrees - newOrientationDegrees; if( displacement < 180.f && displacement > 0.f ) { return displacement; } else if( displacement > 180.f ) { return displacement - 360.f; } else if( displacement > -180.f && displacement < 0.f ) { return displacement; } else if( displacement <= -180.f ) { return 360.f + displacement; } else if( displacement == 180.f ) { return 180.f; } else { return 0.f; } } float GetShortestAngularDistance( float oldOrientationDegrees, float newOrientationDegrees ) { float angularDistance = GetShortestAngularDisplacement( oldOrientationDegrees, newOrientationDegrees ); angularDistance = absFloat( angularDistance ); return angularDistance; } float GetTurnedToward( float oldOrientationDegrees, float newOrientationDegrees, float rotateSpeed ) { float displacement = newOrientationDegrees - oldOrientationDegrees; while( displacement > 360.f || displacement < -360.f ) { if( displacement > 360.f ) { displacement -= 360.f; } else { displacement += 360.f; } } if( absFloat( displacement ) < rotateSpeed || 360.f - absFloat( displacement ) < rotateSpeed ) { return newOrientationDegrees; } else if( GetShortestAngularDisplacement( oldOrientationDegrees, newOrientationDegrees ) >= 0.f ) { return oldOrientationDegrees + rotateSpeed; } else { return oldOrientationDegrees - rotateSpeed; } } float GetAngleBetweenMinus180And180Degrees( float currentAngleDegrees ) { while( currentAngleDegrees > 180.f ) { currentAngleDegrees -= 360.f; } while( currentAngleDegrees <= -180.f ) { currentAngleDegrees += 360.f; } return currentAngleDegrees; } float DotProduct2D( const Vec2& vecA, const Vec2& vecB ) { return vecA.x*vecB.x + vecA.y*vecB.y; } float DotProduct3D( Vec3 const& vecA, Vec3 const& vecB ) { return vecA.x*vecB.x + vecA.y*vecB.y + vecA.z*vecB.z; } Vec3 CrossProduct( Vec3 const& a, Vec3 const& b ) { float x = a.y*b.z - a.z*b.y; float y = a.z*b.x - a.x*b.z; float z = a.x*b.y - a.y*b.x; Vec3 c = Vec3( x, y, z ); return c; } float SmoothStart2( float t ) { float smoothStart2 = t*t; return smoothStart2; } float SmoothStart3( float t ) { float smoothStart3 = t*t*t; return smoothStart3; } float SmoothStart4( float t ) { float smoothStart4 = t*t*t*t; return smoothStart4; } float SmoothStart5( float t ) { float smoothStart5 = t*t*t*t*t; return smoothStart5; } float SmoothStop2( float t ) { float scale = 1-t; float smoothStop2 = 1 - scale*scale; return smoothStop2; } float SmoothStop3( float t ) { float scale = 1-t; float smoothStop3 = 1 - scale*scale*scale; return smoothStop3; } float SmoothStop4( float t ) { float scale = 1-t; float smoothStop4 = 1 - scale*scale*scale*scale; return smoothStop4; } float SmoothStop5( float t ) { float scale = 1-t; float smoothStop5 = 1 - scale*scale*scale*scale*scale; return smoothStop5; } float SmoothStep3( float t ) { float smoothStep3 = 2*(t*t*t) - 3*(t*t); return smoothStep3; }
true
5d2c7a7509a7436e41a21d9b091a4965cb7f64f2
C++
FuangCao/cavan
/mfc/include/JwpCore.h
UTF-8
2,800
2.515625
3
[]
no_license
#pragma once #include "jwp-win32.h" class JwpCore : public jwp_desc { private: jwp_bool mInitiated; jwp_bool mRunning; protected: int mLogIndex; CFile mFileLog; JwpCore(void); virtual ~JwpCore(void); private: static jwp_size_t HwReadHandler(struct jwp_desc *jwp, void *buff, jwp_size_t size); static jwp_size_t HwWriteHandler(struct jwp_desc *jwp, const void *buff, jwp_size_t size); static void OnSendCompleteHandler(struct jwp_desc *jwp); static void OnDataReceivedHandler(struct jwp_desc *jwp, const void *buff, jwp_size_t size); static void OnCommandReceivedHandler(struct jwp_desc *jwp, const void *command, jwp_size_t size); static void OnPackageReceivedHandler(struct jwp_desc *jwp, const struct jwp_header *hdr); static void OnLogReceivedHandler(struct jwp_desc *jwp, jwp_device_t device, const char *log, jwp_size_t size); static void OnRemoteNotResponseHandler(struct jwp_desc *jwp); static void TxThreadHandler(void *data); static void RxThreadHandler(void *data); static void RxPackageThreadHandler(void *data); static void TxDataThreadHandler(void *data); protected: virtual jwp_bool JwpInit(void); virtual jwp_bool JwpStart(jwp_bool useRxThread = true); virtual void JwpStop(void); virtual int HwRead(void *buff, jwp_size_t size); virtual int HwWrite(const void *buff, jwp_size_t size) = 0; virtual void OnLogReceived(jwp_device_t device, const char *log, jwp_size_t size); virtual void OnSendComplete(void) { println("OnSendComplete"); } virtual void OnDataReceived(const void *buff, jwp_size_t size) { println("OnDataReceived: size = %d", size); } virtual void OnCommandReceived(const void *command, jwp_size_t size) { println("OnCommandReceived: size = %d", size); } virtual void OnPackageReceived(const struct jwp_header *hdr) { println("OnPackageReceived: index = %d, type = %d, length = %d", hdr->index, hdr->type, hdr->length); } virtual void OnRemoteNotResponse(void) { println("OnRemoteNotResponse"); } public: void puts(const char *text, jwp_size_t size) { mFileLog.Write(text, size); } void puts(const char *text) { puts(text, strlen(text)); } void println(const char *fmt, ...); void WriteRxData(const void *buff, jwp_size_t size); jwp_size_t SendData(const void *buff, jwp_size_t size) { return jwp_send_data(this, buff, size); } jwp_size_t RecvData(void *buff, jwp_size_t size) { return jwp_recv_data(this, buff, size); } jwp_bool SendCommand(const void *command, jwp_size_t size) { return jwp_send_command(this, command, size); } void SendLog(const char *log, jwp_size_t size) { jwp_send_log(this, log, size); } void JwpSync(void) { jwp_send_sync(this); } };
true
326bfc9b5936e14bf3621731b8db72321f8ac71e
C++
mar10930/CSC240-C-Basics
/ReverseNum.cpp
UTF-8
176
2.90625
3
[]
no_license
#include <iostream> using namespace std; int main() { int num = 123; int ans = 0; while(num != 0) { ans = ans*10 + num%10; num /=10; } cout<<ans; }
true
8dc1757164378dffda3d46049a2051e4d56c9dff
C++
leafyoung88/Virtual-Engine
/virtual_engine_origin/LogicComponent/DirectionalLight.h
UTF-8
1,305
2.546875
3
[]
no_license
#pragma once #include "Component.h" class Transform; class RenderTexture; class DirectionalLight final : public Component { public: static const uint CascadeLevel = 4; private: static ObjectPtr<DirectionalLight> current; uint shadowmapResolution[CascadeLevel]; ObjectPtr<RenderTexture> shadowmaps[CascadeLevel]; DirectionalLight( const ObjectPtr<Transform>& trans, ObjectPtr<Component>& ptr); ~DirectionalLight(); public: static void DestroyLight() { if (current) { delete current; } current = nullptr; } static DirectionalLight* GetInstance( const ObjectPtr<Transform>& trans, uint* shadowmapResolution, ID3D12Device* device); static DirectionalLight* GetInstance() { return current; } float intensity = 1; float3 color = { 1,1,1}; float shadowDistance[CascadeLevel] = { 7,20,45,80 }; float shadowSoftValue[CascadeLevel] = { 2.0f,1.3f,1.0f,0.5f }; float shadowBias[CascadeLevel] = { 0.05f,0.1f, 0.15f,0.3f }; constexpr uint GetShadowmapResolution(uint level) const { #ifndef NDEBUG if (level >= CascadeLevel) throw "Out of Range Exception"; #endif return shadowmapResolution[level]; } ObjectPtr<RenderTexture>& GetShadowmap(uint level) { #ifndef NDEBUG if (level >= CascadeLevel) throw "Out of Range Exception"; #endif return shadowmaps[level]; } };
true
aef32ae5bf85072ba5086e36df01699d1839c660
C++
ohaluminum/COSC1430_Exercise2
/Shape2D.cpp
UTF-8
419
2.953125
3
[]
no_license
#include "Shape2D.h" Shape2D::Shape2D(float cx = 0, float cy = 0) : center_x(cx), center_y(cy), area(0.0) { } float Shape2D::getCenter_x() { return center_x; } float Shape2D::getCenter_y() { return center_y; } float Shape2D::getArea() { return area; } void Shape2D::setCenter(float cx = 0, float cy = 0) { center_x = cx; center_y = cy; } void Shape2D::setArea(float a) { area = a; }
true
a80ce85b39e6c24470c12be9af67c8d20d3897ba
C++
DoanTran2001/C-
/OOP/Nap chong toan tu/6.1-Vector.cpp
UTF-8
904
3.703125
4
[]
no_license
#include <iostream> #include <iomanip> using namespace std; class Vector{ private: int x,y; public: void Nhap(); void Xuat(); Vector operator+(Vector a); Vector operator-(Vector a); }; void Vector::Nhap(){ cout <<"Nhap hoanh do: "; cin >>x; cout <<"Nhap tung do: "; cin >>y; } void Vector::Xuat(){ cout <<"( "<<x<<", "<<y<<")"; } Vector Vector:: operator+(Vector a){ Vector tong; tong.x = this->x + a.x; tong.y = this->y +a.y; return tong; } Vector Vector:: operator-(Vector a){ Vector hieu; hieu.x = this->x - a.x; hieu.y = this->y - a.y; return hieu; } int main(){ Vector A,B; cout <<"\n\t\tNhap vector A"<<endl; A.Nhap(); cout <<"\n\tVecto A: "; A.Xuat(); cout <<"\n\t\tNhap vector B"<<endl; B.Nhap(); cout <<"\n\tVecto B: "; B.Xuat(); Vector C = A + B; cout <<"\n\n\tVector tong"; C.Xuat(); Vector D = A - B; cout <<"\n\n\tVector hieu"; D.Xuat(); return 0; }
true
1fd1b2896edbe62ccf420d3411a3f5eb249c4ce5
C++
tttakano/Competitive-programming
/template/約数列挙.cpp
UTF-8
196
3.046875
3
[]
no_license
vector<int> enumdiv(int n){ vector<int> s; for(int i=1;i*i<=n;i++){ if(n%i==0){ s.push_back(i); if(i*i!=n)s.push_back(n/i); } } sort(s.begin(),s.end()); return s; }
true
1514b27d0c723766ab95da232e154eb8029b9798
C++
tamadate/MD_Collision_Transportation
/interface_flex_rigid.cpp
UTF-8
3,708
2.515625
3
[]
no_license
//------------------------------------------------------------------------ #include "md.hpp" #include <random> #include <algorithm> //------------------------------------------------------------------------ ///////////////////////////////////////////////////////////////////// /* Interface from rigid(CG) MD to all-atom MD */ ///////////////////////////////////////////////////////////////////// void MD::rigid_to_flex(MD *md2, MD *Md1, MD *Md2) { // take over positions/velocities of ion/gas (Md -> md) int gs=vars->gases.size(); int is=vars->ions.size(); for(int i=0;i<gs;i++){vars->gases[i]=Md1->vars->gases[i];} for(int i=0;i<is;i++){vars->ions[i]=Md1->vars->ions[i];} gs=md2->vars->gases.size(); is=md2->vars->ions.size(); for(int i=0;i<gs;i++){md2->vars->gases[i]=Md2->vars->gases[i];} for(int i=0;i<is;i++){md2->vars->ions[i]=Md2->vars->ions[i];} // set initial positions/velocities r=(0,0,0), vtrans=(0,0,0) for (auto &a : vars->ions) a.qx-=Md1->ion_r[0], a.qy-=Md1->ion_r[1], a.qz-=Md1->ion_r[2]; for (auto &a : vars->gases) a.qx-=Md1->ion_r[0], a.qy-=Md1->ion_r[1], a.qz-=Md1->ion_r[2]; for (auto &a : md2->vars->ions) a.qx-=Md2->ion_r[0], a.qy-=Md2->ion_r[1], a.qz-=Md2->ion_r[2]; for (auto &a : md2->vars->gases) a.qx-=Md2->ion_r[0], a.qy-=Md2->ion_r[1], a.qz-=Md2->ion_r[2]; Md1->analysis_ion(); Md2->analysis_ion(); for (auto &a : vars->ions) a.px-=Md1->ion_v[0], a.py-=Md1->ion_v[1], a.pz-=Md1->ion_v[2]; for (auto &a : md2->vars->ions) a.px-=Md2->ion_v[0], a.py-=Md2->ion_v[1], a.pz-=Md2->ion_v[2]; // Randomly rotating ions and change the center of domain 2 to (0,delta,0) random_device seed; double A,B,C,x,y,z; A=seed(),B=seed(),C=seed(); for(auto &a : vars->ions) { x=a.qx,y=a.qy,z=a.qz; vars->ROTATION(a.qx,a.qy,a.qz,A,B,C,x,y,z); x=a.px,y=a.py,z=a.pz; vars->ROTATION(a.px,a.py,a.pz,A,B,C,x,y,z); a.qx+=ion_r[0]; a.qy+=ion_r[1]; a.qz+=ion_r[2]; } for(auto &a : vars->gases) { x=a.qx,y=a.qy,z=a.qz; vars->ROTATION(a.qx,a.qy,a.qz,A,B,C,x,y,z); x=a.px,y=a.py,z=a.pz; vars->ROTATION(a.px,a.py,a.pz,A,B,C,x,y,z); a.qx+=ion_r[0]; a.qy+=ion_r[1]; a.qz+=ion_r[2]; } A=seed(),B=seed(),C=seed(); for(auto &a : md2->vars->ions) { x=a.qx,y=a.qy,z=a.qz; vars->ROTATION(a.qx,a.qy,a.qz,A,B,C,x,y,z); x=a.px,y=a.py,z=a.pz; vars->ROTATION(a.px,a.py,a.pz,A,B,C,x,y,z); a.qx+=md2->ion_r[0]; a.qy+=md2->ion_r[1]; a.qz+=md2->ion_r[2]; } for(auto &a : md2->vars->gases) { x=a.qx,y=a.qy,z=a.qz; vars->ROTATION(a.qx,a.qy,a.qz,A,B,C,x,y,z); x=a.px,y=a.py,z=a.pz; vars->ROTATION(a.px,a.py,a.pz,A,B,C,x,y,z); a.qx+=md2->ion_r[0]; a.qy+=md2->ion_r[1]; a.qz+=md2->ion_r[2]; } // add the thermal velocity as a transtrational velocity from MB distribution // add electrical velocity for(auto &a : vars->ions) a.px+=ion_v[0], a.py+=ion_v[1], a.pz+=ion_v[2]; for(auto &a : md2->vars->ions) a.px+=md2->ion_v[0], a.py+=md2->ion_v[1], a.pz+=md2->ion_v[2]; make_pair(); if(flags->force_sw==1) sw->make_pair(vars); if(flags->force_ters==1) ters->make_pair(vars); md2->make_pair(); if(md2->flags->force_sw==1) md2->sw->make_pair(vars); if(md2->flags->force_ters==1) md2->ters->make_pair(vars); margin_length = MARGIN; compute_intra(); md2->compute_intra(); compute_inter(); md2->compute_inter(); int judge=compute_domdom(md2); } ///////////////////////////////////////////////////////////////////// /* Interface from all-atom MD to rigid(CG) MD */ ///////////////////////////////////////////////////////////////////// void MD::flex_to_rigid(MD *md2, MD *Md1, MD *Md2) { ion_f[0]=ion_f[1]=ion_f[2]=0.0; md2->ion_f[0]=md2->ion_f[1]=md2->ion_f[2]=0.0; int dammy=compute_domdom_rigid(md2); }
true
99b60ce15cbe0ffcb5b5022f4514de8e6be56056
C++
AndreiMihalea/a-problem-a-day
/2-products-array/products_array.cpp
UTF-8
1,124
3.859375
4
[]
no_license
#include <fstream> #include <iostream> #include <math.h> using namespace std; #define EPS 1e-9 void product_array(int n, int array[]) { int left[n], right[n]; left[0] = 1; right[n - 1] = 1; for (int i = 1; i < n; i++) { left[i] = array[i - 1] * left[i - 1]; } for (int i = n - 2; i >= 0; i--) { right[i] = right[i + 1] * array[i + 1]; } for (int i = 0; i < n; i++) { cout << left[i] * right[i] << " "; } cout << endl; return; } /* * O(1) space solution * Using sum of logarithms instead of prodcut */ void product_array_log(int n, int array[]) { float sum = 0; for (int i = 0; i < n; i++) { sum += (float)log10(array[i]); } for (int i = 0; i < n; i++) { cout << pow((float)10, sum - log10(array[i])) << " "; } cout << endl; return; } int main() { ifstream inFile; inFile.open("test.txt"); int n, x; inFile >> n; int array[n]; for (int i = 0; i < n; i++) { inFile >> x; array[i] = x; } product_array(n, array); product_array_log(n, array); }
true
ba801b0d50f2393046611a948ff788db6304ed6d
C++
sontallive/PAT_Basic_Practice
/1013/main.cpp
UTF-8
628
3.15625
3
[]
no_license
#include <iostream> using namespace std; bool isPrime(int n){ if(n == 2) return true; if(n % 2 == 0) return false; for(int i = 3;i * i <= n;i += 2){ if(n % i == 0) return false; } return true; } int main(int argc, char **argv) { int count = 0; int a,b; cin >> a >> b; int i = 2; while(count < b){ if(isPrime(i)){ count++; if(count >= a){ if((count - a) % 10 == 0) cout << i; else cout << " " << i; if((count - a) % 10 == 9) cout << endl; } } i += 1; } return 0; }
true
0076fe499dabbea2a3db177ab4d32dc27057a703
C++
ChanhuiSeok/Basic_problem_solving
/[1]DP/2225-합분해.cpp
UHC
514
2.578125
3
[]
no_license
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <cstdio> #include <vector> #include <algorithm> int dp[201][201]; int main() { int N, K; scanf("%d %d", &N, &K); //1 N Ǵ 1̴. for (int i = 0; i <= N; i++) { dp[1][i] = 1; } for (int k = 2; k <= K; k++) { for (int n = 0; n <= N; n++) { for (int i = 0; i <= n; i++) { dp[k][n] = (dp[k][n] + dp[k - 1][i]) % 1000000000; } } } printf("%d", dp[K][N]); }
true
31e5d886e69ce778e9c6e74cebee782998c41811
C++
EvgeniyMakhmudov/Arduino
/meteo_bmp180/app.ino
UTF-8
924
2.859375
3
[]
no_license
#include <Wire.h> #include <Adafruit_BMP085.h> Adafruit_BMP085 bmp180; void setup() { Serial.begin(115200); if (!bmp180.begin()) { Serial.println("Could not find a valid BMP180 sensor, check wiring!"); while (true) delay(100); } } void loop() { Serial.print("Temperature = "); Serial.print(bmp180.readTemperature()); Serial.println(" *C"); Serial.print("Pressure = "); Serial.print(int(bmp180.readPressure() / 133.3224)); Serial.println(" mm Hg"); Serial.print("Altitude = "); Serial.print(bmp180.readAltitude()); Serial.println(" meters"); Serial.print("Pressure at sealevel (calculated) = "); Serial.print(int(bmp180.readSealevelPressure() / 133.3224)); Serial.println(" mm Hg"); Serial.print("Real altitude = "); Serial.print(bmp180.readAltitude(101500)); Serial.println(" meters"); Serial.println(); delay(1000); }
true
45fb223bc8230d9e946e8f391d9ffae83c213561
C++
aheyeant/poker_game
/poker_sem/cards/cardCombinationsEngine/CombinationsEngineFor5cards.h
UTF-8
1,159
2.515625
3
[]
no_license
#ifndef SEM_ALI_COMBINATIONSENGINEFOR5CARDS_H #define SEM_ALI_COMBINATIONSENGINEFOR5CARDS_H #include "CombinationsEngineAbstract.h" class CombinationsEngineFor5Cards : public CombinationsEngineAbstract { public: explicit CombinationsEngineFor5Cards(const Card * cards); double getSumChance() override; double getBestChance() override; ECombinations getBestAchievedCombinations() override; std::map<ECombinations, bool> getAchievedCombinationsMap() override; std::map<ECombinations, double> getPotentialCombinationChance() override; void recalculate() override; protected: void calculateChanceHighCard() override; void calculateChanceOnePair() override; void calculateChanceTwoPair() override; void calculateChanceTreeOfAKind() override; void calculateChanceStraight() override; void calculateChanceFlush() override; void calculateChanceFullHouse() override; void calculateChanceFourOfAKind() override; void calculateChanceStraightFlush() override; void calculateChanceRoyalFlush() override; private: int cardsCount; }; #endif //SEM_ALI_COMBINATIONSENGINEFOR5CARDS_H
true
b931bf7c661d1787114411c9c5982da278834a61
C++
DevCodeOne/lp
/include/bcm_host_wrapper.h
UTF-8
610
2.703125
3
[]
no_license
#pragma once #include <mutex> #include "bcm_host.h" /** \brief This class will initialize the bcm_host library. */ class bcm_host { public: /** \brief Intialize the library. * It will only be initialized when the method is called first. * Further calls will be ignored */ static void initialize(); private: /** \brief Variable which contains if the library is initialized or not. */ static inline bool _is_initialized = false; /** \brief Mutex to exclude simulatenous access to the is_initialized variable. */ static inline std::mutex _bcm_mutex; };
true
1f7656c31b031cb20dfaa4096aa8ec63e5e112d8
C++
LSaber36/IEEE_UCF_Hardware_Competition_MotherShip
/Arduino Files/MotherShip_V2/MotherShip_V2.ino
UTF-8
15,351
2.59375
3
[]
no_license
/* The purpose of this file is to make controlling the GBE as easy as possible Functions for controlling the motor: void pulseMotor(int dir) void moveGEBDist(int dir, float dist, float scale) void moveGEBSteps(int dir, float steps, float scale) void homeGBE(float scale, int *z) void setDir(int dir) void setScale(int scale) void enableMotor(void) void disableMotor(void) void pushServo(void) void pushServoSlow(void) All of these functions can be rewritten or appended to make their use easier */ #include <Servo.h> String textIn, textOut; #define M1A 33 // motor 1 logic pin a #define M1B 31 // motor 1 logic pin b #define M1E 6 // motor 1 enable pin #define M1_HALL1 A10 // motor 1 sensor 1 pin #define M1_HALL2 A11 // motor 1 sensor 2 pin int m1[3] = {M1A, M1B, M1E}; // holds pins for set functions #define M2A 30 // motor 2 logic pin a #define M2B 32 // motor 2 logic pin b #define M2E 3 // motor 2 enable pin #define M2_HALL1 A6 // motor 2 sensor 1 pin #define M2_HALL2 A7 // motor 2 sensor 2 pin int m2[3] = {M2A, M2B, M2E}; // holds pins for set functions #define M3A 25 // motor 3 logic pin a #define M3B 27 // motor 3 logic pin b #define M3E 5 // motor 3 enable pin #define M3_HALL1 A8 // motor 3 sensor 1 pin #define M3_HALL2 A9 // motor 3 sensor 2 pin int m3[3] = {M3A, M3B, M3E}; // holds pins for set functions #define M4A 26 // motor 4 logic pin a #define M4B 24 // motor 4 logic pin b #define M4E 4 // motor 4 enable pin #define M4_HALL1 A4 // motor 4 sensor 1 pin #define M4_HALL2 A5 // motor 4 sensor 2 pin int m4[3] = {M4A, M4B, M4E}; // holds pins for set functions // lazy susan bracket #define M5A 36 // motor 4 logic pin a #define M5B 38 // motor 4 logic pin b #define M5E 9 // motor 4 enable pin #define M5_HALL1 44 // motor 4 sensor 1 pin #define M5_HALL2 46 // motor 4 sensor 2 pin int m5[3] = {M5A, M5B, M5E}; // holds pins for set functions //line sensors #define LINE1 A12 #define LINE2 A13 #define LINE3 A14 #define LINE4 A15 int line1 = 0; int line2 = 0; int line3 = 0; int line4 = 0; int motorSpeed = 255; Servo servo; String text; int z = 0; // height of the GBE int dir = 0, sc = 1; int stepsPerCenti = 250; int stepsPerRev = 200; #define STEP_PIN 8 #define DIR_PIN 50 #define MS1 43 #define MS2 45 #define RST 49 #define SLEEP 41 #define ENABLE 47 #define SERVO_PIN 2 #define UPPER_STOP A0 #define LOWER_STOP A1 #define LEFT_STOP A2 #define RIGHT_STOP A3 int lowerStopVal = 0; int upperStopVal = 0; int leftStopVal = 0; int rightStopVal = 0; void setCW(int *motor) { digitalWrite(motor[0], LOW); digitalWrite(motor[1], HIGH); Serial.println("motor set CW"); } void setCCW(int *motor) { digitalWrite(motor[0], HIGH); digitalWrite(motor[1], LOW); Serial.println("motor set CCW"); } void setAllCW() { setCW(m1); setCW(m2); setCW(m3); setCW(m4); } void setAllCCW() { setCCW(m1); setCCW(m2); setCCW(m3); setCCW(m4); } void startAllMotors() { startMotor(m1); startMotor(m2); startMotor(m3); startMotor(m4); } void startMotor(int *motor) { analogWrite(motor[2], motorSpeed); } void startAllMotorsDelay() { startMotor(m1); delay(1000); startMotor(m2); delay(1000); startMotor(m3); delay(1000); startMotor(m4); } void stopAllMotors() { stopMotor(m1); stopMotor(m2); stopMotor(m3); stopMotor(m4); } void stopMotor(int *motor) { digitalWrite(motor[2], LOW); } void moveForward() { setCW(m1); setCW(m2); setCCW(m3); setCCW(m4); startAllMotors(); } void moveBackward() { setCCW(m1); setCCW(m2); setCW(m3); setCW(m4); startAllMotors(); } void moveLeft() { setCCW(m1); setCW(m2); setCCW(m3); setCW(m4); startAllMotors(); } void moveRight() { setCW(m1); setCCW(m2); setCW(m3); setCCW(m4); startAllMotors(); } void rotateCW() { setAllCW(); startAllMotors(); } void rotateCCW() { setAllCCW(); startAllMotors(); } // stepper motor functions void pulseMotor(int dir) { enableMotor(); digitalWrite(STEP_PIN, HIGH); delayMicroseconds(1100); digitalWrite(STEP_PIN, LOW); delayMicroseconds(1100); } void moveGEBDist(int dir, float dist, float scale) { // centi: 1 step(1), 1/2 step(2), 1/4 step(4), 1/8 step(8) int i = 0; //how many steps to 1 centimeter float stepsPerCenti = 250; // 250 steps/cm float numSteps = dist * stepsPerCenti * scale; enableMotor(); digitalWrite(STEP_PIN, LOW); setDir(dir); setScale(scale); for (i = 0; i < numSteps; i++) { // upperStopVal = digitalRead(UPPER_STOP); // lowerStopVal = digitalRead(LOWER_STOP); // // if (upperStopVal == 1 || lowerStopVal == 1) // { // return; // } pulseMotor(dir); } } void moveGEBSteps(int dir, float steps, float scale) { int i; enableMotor(); for (i = 0; i < steps; i++) { if (UPPER_STOP == 1 || LOWER_STOP == 1) { return; } pulseMotor(dir); } } void homeGBE(float scale, int *z) { enableMotor(); Serial.println("Homing GBE"); while (lowerStopVal == 0) // LOWER_STOP is not pressed { lowerStopVal = digitalRead(LOWER_STOP); pulseMotor(0); } *z = 0; // dereference z and set it equal to 0 Serial.println("Done"); } void setDir(int dir) { if (dir == 0) // down { digitalWrite(DIR_PIN, LOW); //set direction ccw } else if (dir == 1) // up { digitalWrite(DIR_PIN, HIGH); //set direction cw } } void setScale(int scale) { if (scale == 1) // whole steps { digitalWrite(MS1, LOW); digitalWrite(MS2, LOW); } else if (scale == 2) // 1/2 steps { digitalWrite(MS1, HIGH); digitalWrite(MS2, LOW); } else if (scale == 4) // 1/4 steps { digitalWrite(MS1, LOW); digitalWrite(MS2, HIGH); } else if (scale == 8) // 1/8 steps { digitalWrite(MS1, HIGH); digitalWrite(MS2, HIGH); } } void enableMotor(void) { //Serial.println("Motor Enabled"); digitalWrite(RST, HIGH); //digitalWrite(ENABLE, LOW); //digitalWrite(SLEEP, HIGH); } void disableMotor(void) { //Serial.println("Motor Disabled"); digitalWrite(RST, LOW); //digitalWrite(ENABLE, HIGH); //digitalWrite(SLEEP, LOW); } void pushServo(void) { servo.write(120); delay(1000); servo.write(75); } void pushServoSlow(void) { int i; int delayTime = 10; for (i = 75; i < 120; i++) { servo.write(i); delay(delayTime); } delay(1000); for (i = 120; i > 75; i--) { servo.write(i); delay(delayTime); } } void eject1(void) { Serial.println("Ejecting block"); moveGEBDist(1, .85, 2); pushServoSlow(); } void eject2(void) { Serial.println("Ejecting block"); } void pushServoOut(void) { servo.write(120); } void pushServoIn(void) { servo.write(75); } void getSerialInput(void) { // computer serial if (Serial.available()) { textOut = Serial.readString(); // not auto new line sent in textOut //Serial.println(textOut); Serial1.println(textOut); } // bluetooth serial if (Serial1.available()) { textIn = Serial1.readString(); // auto new line sent in textIn //Serial.print(textIn); //Serial1.print(textIn); // main motor commands if (textIn == "forward\n") { Serial.println("Testing forward"); Serial1.println("Testing forward"); moveForward(); Serial.println("Proceed"); Serial1.println("Proceed"); } else if (textIn == "backward\n") { Serial.println("Testing backward"); Serial1.println("Testing backward"); moveBackward(); Serial.println("Proceed"); Serial1.println("Proceed"); } else if (textIn == "left\n") { Serial.println("Testing left"); Serial1.println("Testing left"); moveLeft(); Serial.println("Proceed"); Serial1.println("Proceed"); } else if (textIn == "right\n") { Serial.println("Testing right"); Serial1.println("Testing right"); moveRight(); Serial.println("Proceed"); Serial1.println("Proceed"); } else if (textIn == "rotateCW\n") { Serial.println("Testing rotateCW"); Serial1.println("Testing rotateCW"); rotateCW(); Serial.println("Proceed"); Serial1.println("Proceed"); } else if (textIn == "rotateCCW\n") { Serial.println("Testing rotateCCW"); Serial1.println("Testing rotateCCW"); rotateCCW(); Serial.println("Proceed"); Serial1.println("Proceed"); } else if (textIn == "setDist\n") { Serial.println("Testing setDist"); Serial1.println("Testing setDist"); Serial.println("Proceed"); Serial1.println("Proceed"); } else if (textIn == "stopAllMotors\n") { Serial.println("Testing stopAllMotors"); Serial1.println("Testing stopAllMotors"); stopAllMotors(); Serial.println("Proceed"); Serial1.println("Proceed"); } else if (textIn == "CWdelay\n") { Serial.println("Testing CWdelay"); Serial1.println("Testing CWdelay"); stopAllMotors(); setAllCW(); startAllMotorsDelay(); Serial.println("Proceed"); Serial1.println("Proceed"); } else if (textIn == "CCWdelay\n") { Serial.println("Testing CCWdelay"); Serial1.println("Testing CCWdelay"); stopAllMotors(); setAllCCW(); startAllMotorsDelay(); Serial.println("Proceed"); Serial1.println("Proceed"); } // GBE commands else if (textIn == "whole\n") { Serial.println("step set to whole"); Serial1.println("step set to whole"); sc = 1; setScale(1); Serial.println("Proceed"); Serial1.println("Proceed"); } else if (textIn == "half\n") { Serial.println("step set to half"); Serial1.println("step set to half"); sc = 2; setScale(2); Serial.println("Proceed"); Serial1.println("Proceed"); } else if (textIn == "quarter\n") { Serial.println("step set to quarter"); Serial1.println("step set to quarter"); sc = 4; setScale(4); Serial.println("Proceed"); Serial1.println("Proceed"); } else if (textIn == "eighth\n") { Serial.println("step set to eighth"); Serial1.println("step set to eighth"); sc = 8; setScale(8); Serial.println("Proceed"); Serial1.println("Proceed"); } else if (textIn == "enable\n") { Serial.println("GBE enabled"); Serial1.println("GBE enabled"); enableMotor(); Serial.println("Proceed"); Serial1.println("Proceed"); } else if (textIn == "disable\n") { Serial.println("GBE disabled"); Serial1.println("GBE disabled"); disableMotor(); Serial.println("Proceed"); Serial1.println("Proceed"); } else if (textIn == "up\n") { Serial.println("direction set to up"); Serial1.println("direction set to up"); dir = 1; setDir(1); Serial.println("Proceed"); Serial1.println("Proceed"); } else if (textIn == "down\n") { Serial.println("direction set to down"); Serial1.println("direction set to down"); dir = 0; setDir(0); Serial.println("Proceed"); Serial1.println("Proceed"); } else if (textIn == "push\n") { Serial.println("pushing"); Serial1.println("pushing"); pushServo(); Serial.println("Proceed"); Serial1.println("Proceed"); } else if (textIn == "pushSlow\n") { Serial.println("pushing slow"); Serial1.println("pushing slow"); pushServoSlow(); Serial.println("Proceed"); Serial1.println("Proceed"); } else if (textIn == "moveDist\n") { Serial.println("moving set dist"); Serial1.println("moving set dist"); moveGEBDist(dir, 1, sc); Serial.println("Proceed"); Serial1.println("Proceed"); } else if (textIn == "step\n") { Serial.println("direction set to down"); Serial1.println("direction set to down"); dir = 0; setDir(0); Serial.println("Proceed"); Serial1.println("Proceed"); } else if (textIn == "fast\n") { motorSpeed = 255; Serial.print("motorSpeed: "); Serial.println(motorSpeed); Serial1.println("motorSpeed: "); Serial1.println(motorSpeed); Serial.println("Proceed"); Serial1.println("Proceed"); } else if (textIn == "slow\n") { motorSpeed = 125; Serial.print("motorSpeed: "); Serial.println(motorSpeed); Serial1.println("motorSpeed: "); Serial1.println(motorSpeed); motorSpeed = 125; Serial.println("Proceed"); Serial1.println("Proceed"); } else if (textIn == "getSensorData\n") { Serial1.print(line1); Serial1.print(" : "); Serial1.print(line2); Serial1.print(" : "); Serial1.print(line3); Serial1.print(" : "); Serial1.println(line4); Serial.print(line1); Serial.print(" : "); Serial.print(line2); Serial.print(" : "); Serial.print(line3); Serial.print(" : "); Serial.println(line4); } else if (textIn == "turnTable\n") { Serial.println("testing turnTable"); Serial1.println("testing turnTable"); setCW(m5); startMotor(m5); delay(250); stopMotor(m5); Serial.println("Proceed"); Serial1.println("Proceed"); } } } void setup() { pinMode(M1A, OUTPUT); pinMode(M1B, OUTPUT); pinMode(M1E, OUTPUT); pinMode(M1_HALL1, INPUT); pinMode(M1_HALL2, INPUT); pinMode(M2A, OUTPUT); pinMode(M2B, OUTPUT); pinMode(M2E, OUTPUT); pinMode(M2_HALL1, INPUT); pinMode(M2_HALL2, INPUT); pinMode(M3A, OUTPUT); pinMode(M3B, OUTPUT); pinMode(M3E, OUTPUT); pinMode(M3_HALL1, INPUT); pinMode(M3_HALL2, INPUT); pinMode(M4A, OUTPUT); pinMode(M4B, OUTPUT); pinMode(M4E, OUTPUT); pinMode(M4_HALL1, INPUT); pinMode(M4_HALL2, INPUT); pinMode(STEP_PIN, OUTPUT); pinMode(DIR_PIN, OUTPUT); pinMode(MS1, OUTPUT); pinMode(MS2, OUTPUT); pinMode(RST, OUTPUT); pinMode(SLEEP, OUTPUT); pinMode(ENABLE, OUTPUT); pinMode(SERVO_PIN, OUTPUT); pinMode(UPPER_STOP, INPUT); pinMode(LOWER_STOP, INPUT); pinMode(LINE1, INPUT); pinMode(LINE2, INPUT); pinMode(LINE3, INPUT); pinMode(LINE4, INPUT); Serial.begin(9600); Serial1.begin(38400); Serial.setTimeout(10); Serial1.setTimeout(10); Serial.println("Begining Program..."); Serial.println(""); servo.attach(SERVO_PIN); digitalWrite(STEP_PIN, LOW); digitalWrite(DIR_PIN, LOW); digitalWrite(ENABLE, LOW); digitalWrite(SLEEP, HIGH); servo.write(90); servo.write(75); setScale(1); setDir(0); stopAllMotors(); } void loop() { upperStopVal = digitalRead(UPPER_STOP); lowerStopVal = digitalRead(LOWER_STOP); leftStopVal = digitalRead(LEFT_STOP); rightStopVal = digitalRead(RIGHT_STOP); line1 = digitalRead(LINE1); line2 = digitalRead(LINE2); line3 = digitalRead(LINE3); line4 = digitalRead(LINE4); getSerialInput(); // Serial.print(line1); // Serial.print(" : "); // Serial.print(line2); // Serial.print(" : "); // Serial.print(line3); // Serial.print(" : "); // Serial.println(line4); }
true
224bf5e268dbbb3e4abd2d4cc56ae36d6494bef1
C++
watashi/AlgoSolution
/zoj/20/2011.cpp
UTF-8
4,227
2.78125
3
[]
no_license
/* #include <cmath> #include <cstdio> #include <utility> using namespace std; typedef pair<long long, long long> Complex; const int MAXN = 100; const double eps = 1e-8; const Complex ZERO = Complex(0, 0); long long a[MAXN + 1], nx, nb, nbb[MAXN + 1]; Complex x, b, bb[MAXN + 1]; long long norm(const Complex& c) { return c.first * c.first + c.second * c.second; } Complex mul(const Complex& lhs, const Complex& rhs) { return make_pair(lhs.first * rhs.first - lhs.second * rhs.second, lhs.first * rhs.second + lhs.second * rhs.first); } bool flag; int n; void gao(Complex c, int i) { if (!flag) { if (i < 0) { if (c == ZERO) { flag = true; i = n; while (i > 0 && a[i] == 0) { --i; } for (; i >= 0; --i) { printf("%lld%c", a[i], (i == 0) ? '\n' : ','); } } } else { a[i] = (long long)(sqrt((double)(norm(c) / nbb[i])) + eps); c.first -= a[i] * bb[i].first; c.second -= a[i] * bb[i].second; if (a[i] > 0 && (a[i] - 1) * (a[i] - 1) < nb) { --a[i]; gao(Complex(c.first + bb[i].first, c.second + bb[i].second), i - 1); ++a[i]; } if (a[i] >= 2 && (a[i] - 2) * (a[i] - 2) < nb) { a[i] -= 2; gao(Complex(c.first + 2 * bb[i].first, c.second + 2 * bb[i].second), i - 1); a[i] += 2; } if (a[i] * a[i] < nb) { gao(c, i - 1); ++a[i]; if (a[i] * a[i] < nb) { c.first -= bb[i].first; c.second -= bb[i].second; gao(c, i - 1); } ++a[i]; if (a[i] * a[i] < nb) { c.first -= bb[i].first; c.second -= bb[i].second; gao(c, i - 1); } } } } } int main() { int re; long long xr, xi, br, bi; scanf("%d", &re); while (re--) { scanf("%lld%lld%lld%lld", &xr, &xi, &br, &bi); x = Complex(xr, xi); nx = norm(x); b = Complex(br, bi); nb = norm(b); bb[0] = Complex(1, 0); nbb[0] = norm(bb[0]); for (n = 1; ; n++) { bb[n] = mul(bb[n - 1], b); nbb[n] = norm(bb[n]); if (nbb[n] > nx * 100) { break; } } flag = false; gao(x, n); if (!flag) { puts("The code cannot be decrypted."); } } return 0; } //1647852 2008-09-19 21:05:22 Accepted 2011 C++ 510 260 watashi */ #include <cmath> #include <stack> #include <cstdio> using namespace std; int main() { int re; int r, i, xr, xi, br, bi, bb, b, a; scanf("%d", &re); while (re--) { scanf("%d%d%d%d", &xr, &xi, &br, &bi); bb = br * br + bi * bi; b = (int)(sqrt((double)bb) - 1e-6); stack<int> ans; do { for (a = 0; a <= b; a++) { r = (xr - a) * br - xi * (-bi); i = (xr - a) * (-bi) + xi * br; if (r % bb == 0 && i % bb == 0) { xr = r / bb; xi = i / bb; ans.push(a); break; } } if (a > b || ans.size() > 100) { break; } } while (xr != 0 || xi != 0); if (xr != 0 || xi != 0) { puts("The code cannot be decrypted."); } else { while(!ans.empty()) { printf("%d", ans.top()); ans.pop(); putchar(ans.empty() ? '\n' : ','); } } } return 0; } //Run ID Submit Time Judge Status Problem ID Language Run Time(ms) Run Memory(KB) User Name //1647951 2008-09-19 22:12:10 Accepted 2011 C++ 220 260 watashi // 2012-09-07 01:10:08 | Accepted | 2011 | C++ | 200 | 180 | watashi | Source
true
bbfb5449dc5a6d3308afc64350d9a128439e3c16
C++
fspirit/kf
/src/main.cpp
UTF-8
3,887
2.671875
3
[]
no_license
#include <uWS/uWS.h> #include <iostream> #include "json.hpp" #include <math.h> #include "RMSECalculator.hpp" #include "ExtendedKalmanFilter.hpp" #include "UnscentedKalmanFilter.hpp" #include "MeasurementPackageFactory.hpp" #include "WebSocketMessageHandler.hpp" #include "RadarMeasurementModel.hpp" #include "LaserMeasurementModel.hpp" using std::string; using std::cout; using std::endl; using std::cerr; const double RadarRoNoiseVar = 0.9; const double RadarPhiNoiseVar = 0.009; const double RadarRoDotNoiseVar = 0.9; const double LaserXNoiseVar = 0.0225; const double LaserYNoiseVar = 0.0225; const double ProcessANoiseVar = 0.325; const double ProcessYawDDNoiseVar = 0.325; const double ProcessAXNoiseVar = 9; const double ProcessAYNoiseVar = 9; const int ExtendedKalmanFilterMode = 0; const int UnscentedKalmanFilterMode = 1; static void printUsage(std::string name) { cerr << "Usage: " << name << " <mode>" << endl << "Modes:" << endl << "\t 0\t Use extended kalman filter" << endl << "\t 1\t Use unscented kalman filter" << endl; } static void start(int mode) { uWS::Hub h; shared_ptr<KalmanFilterBase> kalmanFilter; if (mode == ExtendedKalmanFilterMode) kalmanFilter = std::make_shared<ExtendedKalmanFilter>(ProcessAXNoiseVar, ProcessAYNoiseVar); else kalmanFilter = std::make_shared<UnscentedKalmanFilter>(ProcessANoiseVar, ProcessYawDDNoiseVar); auto rmseCalculator = std::make_shared<RMSECalculator>(); auto radarMeasurementModel = std::make_shared<RadarMeasurementModel>(RadarRoNoiseVar, RadarPhiNoiseVar, RadarRoDotNoiseVar); auto laserMeasurementModel = std::make_shared<LaserMeasurementModel>(LaserXNoiseVar, LaserYNoiseVar); auto measurementPackageFactory = std::make_shared<MeasurementPackageFactory>(radarMeasurementModel, laserMeasurementModel); WebSocketMessageHandler handler(kalmanFilter, rmseCalculator, measurementPackageFactory); h.onMessage([&handler](uWS::WebSocket<uWS::SERVER> ws, char * data, size_t length, uWS::OpCode opCode) { if (length == 0) return; string message (data, length); handler.HandleMessage(message, ws); }); h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req) { cout << "Connected" << endl; }); h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code, char *message, size_t length) { ws.close(); cout << "Disconnected" << endl; }); const int port = 4567; if (h.listen(port)) { cout << "Listening to port " << port << endl; h.run(); } else { cerr << "Failed to listen to port" << endl; } } int main(int argc, char * argv[]) { if (argc < 2) { printUsage(argv[0]); return 1; } int mode = std::stoi(std::string(argv[1])); if (mode != ExtendedKalmanFilterMode && mode != UnscentedKalmanFilterMode) { printUsage(argv[0]); return 1; } start(mode); }
true
d00581de5f1ece5fc2a8e47ca468c6b9a383bf53
C++
Sendhuraan/CPP_solutions
/src/collection/test-solution/index.cpp
UTF-8
184
2.6875
3
[ "MIT-0" ]
permissive
#include "math-functions/functions.h" #include <iostream> int main(void) { start(); int number = 5; printf("The Square of the number %d", square(number)); end(); }
true
d6eef06eb2feec789f0f286b41c51f555d9bdd8f
C++
cybo-neutron/DS-and-Algo
/Graph/Bishu_and_his_girlfriend.cpp
UTF-8
2,102
2.65625
3
[]
no_license
//Hackerearth Bishu and his girlfriend #include<bits/stdc++.h> using namespace std; #define ll long long #define mod 1000000007 #define eb emplace_back #define pii pair<int,int> #define pll pair<ll,ll> #define fo(i,n) for(i=0;i<n;i++) #define fok(i,k,n) for(i=k;i<n;i++) #define dbg(x) printf("%d %d\n",#x,x) #define sci(x) scanf("%d",&x) #define scd(x) scanf("%lf",&x) #define scl(x) scanf("%lld",&x) #define pfi(x) printf("%d",x) #define pfd(x) printf("%lf",x) #define pfl(x) printf("%lld",x) class graph{ unordered_map<int,vector<int>> adjList; int v,e; unordered_set<int> visited; public: unordered_map<int,pair<bool,int>> girls; graph(int v,int e) { this->v=v; this->e=e; for(int i=1;i<=v;i++) { adjList[i]={}; girls[i]={false,100000}; } } void addEdge(int from,int to) { adjList[from].emplace_back(to); adjList[to].emplace_back(from); } void dfs(int from,int dist) { if(visited.find(from)!=visited.end()) return; cout<<from<<": "<<girls[from].first<<" "<<(girls[from].second>dist)<<" "<<girls[from].second<<" "<<dist<<endl; visited.insert(from); if(girls[from].first) { if(girls[from].second>dist) girls[from].second=dist; } for(auto i:adjList[from]) { dfs(i,dist+1); } } int findGirl() { dfs(1,0); int g=-1; int maxDist=1000000; for(auto girl:girls) { if(girl.second.first) { if(girl.second.second<maxDist) g=girl.first; else if(girl.second.second==maxDist) g=girl.first<g?girl.first:g; } } return g; } }; int main() { int v,e; cin>>v; e=v-1; graph g(v,e); int from,to; for(int i=0;i<e;i++) { cin>>from>>to; g.addEdge(from,to); } int q; cin>>q; for(int i=0;i<q;i++) { int x; cin>>x; g.girls[x].first=true; } for(auto i:g.girls) { cout<<i.first<<" "<<i.second.first<<" "<<i.second.second<<endl; } cout<<g.findGirl(); return 0; }
true
4784f4573d7c1bfbd049ab3ffaa5d26ece634097
C++
pikipupiba/RGB_Empire_Rewrite_July_2019
/Meteor.cpp
UTF-8
1,097
2.65625
3
[]
no_license
#include "Meteor.h" Meteor::Meteor(LED_Fixture* new_fixture, LED_Group* new_group) :Animation(new_fixture, new_group) { START; vars(position, a_value)->eor = _eor_Loop; vars(position, a_speed)->value = float(random8(100,255)) / 200.0; vars(fade, a_value)->value = 2; vars(hue, a_speed)->value = 0; END; } void Meteor::erase_previous_frame() { for (auto& pixel : *led_set) { if (random8(100) > 90) { pixel.fadeToBlackBy(vars(fade) * 30 * speed_scale_factor); } else { pixel.fadeToBlackBy(vars(fade) * speed_scale_factor); } } } void Meteor::calculate_frame() { if (vars(position) == 0) { vars(hue, a_value)->value = random8(); vars(position, a_speed)->value = float(random8(100,255)) / 200.0; } if (vars(position) < num_leds + vars(size)) { leds[(int)vars(position)] = CHSV(vars(hue), 255, vars(brightness) * ((vars(position) - (int)vars(position)))); for (int i = 1; i < vars(size); i++) { if (vars(position) - i > 0 && vars(position) - i < num_leds) { leds[(int)vars(position) - i] = CHSV(vars(hue), 255, vars(brightness)); } } } }
true
1651067ff758b576dbee0231601e4935a6615e57
C++
vishalbelsare/DMGameBasic
/src/Tools.h
UTF-8
1,329
2.59375
3
[ "MIT" ]
permissive
/* * Tools.h * * Created on: Apr 22, 2014 * Author: wilfeli */ #ifndef TOOLS_H_ #define TOOLS_H_ #include <Eigen/Dense> namespace Tools{ extern void mgrid(Eigen::MatrixXd, Eigen::MatrixXd*); extern void mgrid_test(Eigen::MatrixXd, Eigen::MatrixXd*); extern void print_vector(std::vector<double>); extern void print_vector(std::vector<std::vector<double>>); class MyRNG{ public: MyRNG(double); double GetUniform(); uint64_t GetUint(); double state = 2013; bool hasSpare = false; double rn1 = 0.0; double rn2 = 0.0; uint64_t m_w = 521288629; uint64_t m_z = 362436069; }; extern double get_normal(double, double, MyRNG&); extern int get_int(int, int, MyRNG&); template <class _RandomAccessIterator> void random_shuffle(_RandomAccessIterator __first, _RandomAccessIterator __last, MyRNG& rng){ typedef typename std::iterator_traits<_RandomAccessIterator>::difference_type difference_type; difference_type __d = __last - __first; if (__d > 1){ for (--__last, --__d; __first < __last; ++__first, --__d){ //get random number from 0 to __d difference_type __i = get_int(0, __d, rng); if (__i != difference_type(0)) swap(*__first, *(__first + __i)); }; }; }; }; #endif /* TOOLS_H_ */
true
3957ddaa09dbc5f6241f6ee67dace10eb8d9c97f
C++
InflamedBanana/FileChecker
/FileChecker/src/fileChecks.cpp
UTF-8
4,094
2.609375
3
[]
no_license
#include <iostream> #include "fileChecks.h" #include "fileManipulator.h" #include <vector> #include "UString.h" #include <algorithm> typedef Settings::DirectoryConfig::DirectoryFlags DirectoryFlags; using namespace std; bool AnyOf( const vector<string>& _strVector, const string& _str ) { return any_of( _strVector.begin(), _strVector.end(), [&_str]( const string& _s ) { return ( _s.compare( _str ) == 0 ); } ); } void RemoveAssociatedFiles( fs::path _file, unordered_set<string>& _badFiles, const vector<string>& _associatedFiles ) { for( const auto& associatedFileExtension : _associatedFiles ) { _file.replace_extension( associatedFileExtension ); _badFiles.insert( _file.string() ); } } namespace Nomenclature { namespace { bool CompareNomenclature( const fs::path& _file, const Settings::NomenclatureConfig& _nomenclatureConfig, const vector<string>& _associatedFiles ) { if( _associatedFiles.size() > 0 && AnyOf( _associatedFiles, _file.extension().string() ) ) return true; vector<string> fileName( uString::split( _file.filename().string(), _nomenclatureConfig.separator ) ); if( _nomenclatureConfig.definitions.size() > fileName.size() ) return false; for( int i = 0; i < _nomenclatureConfig.definitions.size(); ++i ) { if( _nomenclatureConfig.definitions[ i ].size() == 0 ) continue; if( !any_of( _nomenclatureConfig.definitions[ i ].begin(), _nomenclatureConfig.definitions[ i ].end(), [&i, &fileName]( const string _definition ) { return ( _definition.compare( fileName[ i ] ) == 0 ); } ) ) return false; } return true; } } void CheckNomenclature( const string& _path, const Settings::NomenclatureConfig& _nomenclatureConfig, unordered_set<string>& _badFiles, const vector<string>& _associatedFiles ) { for( auto& file : FileManipulator::GetFilesInDirectory( _path ) ) { if( !CompareNomenclature( file, _nomenclatureConfig, _associatedFiles ) ) { _badFiles.insert( file ); if( _associatedFiles.size() > 0 ) { RemoveAssociatedFiles( file, _badFiles, _associatedFiles ); } } } } } namespace Arborescence { void CheckArborescence( const string& _path, const Settings::DirectoryConfig& _directory, unordered_set<string>& _badFiles, const vector<string>& _associatedFiles, const std::vector<std::string>& _exceptions ) { vector<string> explorerSubDirs = FileManipulator::GetDirectoriesAtPath( _path ); for( const auto& exception : _exceptions ) { vector<string>::iterator pos = find( explorerSubDirs.begin(), explorerSubDirs.end(), exception ); if(pos != explorerSubDirs.end() ) explorerSubDirs.erase( pos ); } for( const auto& arboSubDir : _directory.subDirectories ) { if( !FileManipulator::DirectoryContainsFile( _path, _path + arboSubDir.name ) ) FileManipulator::CreateDirectory( _path + arboSubDir.name ); else explorerSubDirs.erase( find( explorerSubDirs.begin(), explorerSubDirs.end(), _path + arboSubDir.name ) ); } for( const auto& explorerSubDir : explorerSubDirs ) { _badFiles.insert( explorerSubDir ); if( _associatedFiles.size() > 0 ) RemoveAssociatedFiles( _path, _badFiles, _associatedFiles ); } explorerSubDirs.clear(); } } namespace Extension { namespace { bool CheckFileExtension( const fs::path _file, const vector<string>& _extensions ) { if( !_file.has_extension() ) return false; if( _extensions.size() == 0 ) return false; return AnyOf( _extensions, _file.extension().string() ); } } void CheckFilesExtensions( const string & _path, const Settings::DirectoryConfig & _dirConfig, unordered_set<string>& _badFiles, const vector<string>& _associatedFiles ) { if( _dirConfig.extensionRestricts.size() == 0 ) return; for( const auto& file : FileManipulator::GetFilesInDirectory( _path ) ) { if( !CheckFileExtension( file, _dirConfig.extensionRestricts ) ) { _badFiles.insert( file ); if( _associatedFiles.size() > 0 ) RemoveAssociatedFiles( file, _badFiles, _associatedFiles ); } } } }
true
1a609183a7bd3fbd604fcb95e92fa26066000e05
C++
KevinUTAT/Cplusplus
/ECE244/Lab5/Lab5/TreeNode.h
UTF-8
1,323
2.765625
3
[]
no_license
#ifndef TREENODE_H #define TREENODE_H #include <string> #include "DBentry.h" //#include "TreeDB.h" using namespace std; class TreeDB; class TreeNode { private: DBentry* entry; TreeNode* left; TreeNode* right; public: TreeNode(); TreeNode(DBentry* entry_, TreeNode* left_, TreeNode* right_); TreeNode(string name_, unsigned int IP_, bool active_); ~TreeNode(); string getName(); unsigned int getIP(); bool getActive(); //insert a node with name_ IP_ and active IN ORDER //return false if the name already exsit bool insert(string name_, unsigned int IP_, bool active_); //search node by name //return a pointer to the data object //return NULL if name DNE DBentry* find(string name_); //return number of active node //as this node is the root int countActive(); //print all node in ascending order //as if this object is the root void printAll(); //search sub tree and print //return false if name_ DNE bool print(string name_); //return pointer pointing to the node have max key TreeNode* max(); bool remove(string name_, TreeNode*& pp); void removeAll(); //count number of probe wlked thourgh //NOTE!!! //this assume name_ exist int probeCount(string name_, int probes); friend TreeDB; friend ostream& operator<<(ostream& out, TreeNode const & node); }; #endif
true