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
3c694295e007135b653e8f8472fd8ede0acd0290
C++
yuhc/LeetCode
/src/lc140.cpp
UTF-8
2,316
3.078125
3
[]
no_license
/* LC ID : #140 * Type : String + DFS * Author: Hangchen Yu * Date : 09/14/2015 */ #include <iostream> #include <cstdio> #include <cstring> #include <cctype> #include <algorithm> #include <vector> #include <queue> #include <list> #include <map> #include <stack> #include <unordered_set> #include <utility> #include <cmath> using namespace std; //copy the Solution class here class Solution { public: void dfs(int k, string& s, vector<string>& tmp, vector<string>& ans, unordered_set<string>& wordDict, bool canBreak[]) { if (k == s.length()) { string t = tmp[0]; for (int i = 1; i < tmp.size(); i++) t += " " + tmp[i]; ans.push_back(t); return; } for (int i = k; i < s.length(); i++) { if (!canBreak[i+1]) continue; string subs = s.substr(k,i-k+1); if (wordDict.count(subs)) { tmp.push_back(s.substr(k,i-k+1)); dfs(i+1, s, tmp, ans, wordDict, canBreak); tmp.pop_back(); } } } vector<string> wordBreak(string s, unordered_set<string>& wordDict) { int n = s.length(); bool canBreak[n]; //right-side memset(canBreak, false, sizeof(canBreak)); canBreak[n] = true; for (int i = n-1; i >= 0; i--) for (int j = 1; j <= n-i; j++) if (canBreak[i+j] && wordDict.count(s.substr(i,j))) { canBreak[i] = true; break; } vector<string> tmp; vector<string> ans; dfs(0, s, tmp, ans, wordDict, canBreak); return ans; } }; int main() { Solution sol; string s; //s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab"; //unordered_set<string> wordDict = {"a","aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa","aaaaaaaaaa"}; s = "abcd"; unordered_set<string> wordDict = {"a","abc","b","cd"}; vector<string> ans = sol.wordBreak(s, wordDict); for (int i = 0; i < ans.size(); i++) { cout << ans[i] << "\n"; } return 0; }
true
ece52720e23449860ea91680123eabc6f8d2ea8f
C++
JoshChubi/Academic
/Spring2018/Adv Data Structure/Traversals/Graph.h
UTF-8
453
3.140625
3
[]
no_license
#include<list> #include"Edge.h" using namespace std; class Graph { public: Graph(int numVertices, bool directed, bool weighted); int getNumVertices() const; int getNumEdges() const; bool isDirected() const; bool isWeighted() const; void addEdge(Edge e); list<Edge> getAdjacentList(int v) const; Edge getEdge(int v1, int v2) const; private: int numVertices; int numEdges = 0; bool directed; bool weighted; list<Edge> * edgeList; };
true
32f33832759c269d7ae8883ca375fc332ca5f8f6
C++
kimgr/bandit
/specs/fakes/logging_fake.h
UTF-8
958
3.015625
3
[]
no_license
#ifndef BANDIT_SPECS_LOGGING_FAKE_H #define BANDIT_SPECS_LOGGING_FAKE_H #include <sstream> namespace bandit { namespace specs { struct logging_fake { template <typename T> void log(T val, bool add_newline = true) { logstm_ << val; if(add_newline) { logstm_ << "\n"; } } void log(const char* val, bool add_newline = true) { std::string no_newline = val; std::transform(no_newline.begin(), no_newline.end(), no_newline.begin(), [](const char& c) { return (c == '\n' || c == '\r') ? ' ' : c; }); logstm_ << no_newline; if(add_newline) { logstm_ << "\n"; } } template <typename First, typename... Args> void log(First first, Args... args) { log(first, false); log(args...); } std::string call_log() { return logstm_.str(); } private: std::stringstream logstm_; }; }} #endif
true
e54745f46ea3b94f3267acc45b13d2881ce41ba5
C++
ciwomuli/NOIP2017exercise
/2019-2-3/A.cpp
UTF-8
1,045
2.65625
3
[]
no_license
#include <algorithm> #include <cctype> #include <climits> #include <cmath> #include <cstdio> #include <cstring> #include <iostream> #include <queue> #include <stack> #include <vector> #include <string> #define LL long long #define P pair<int,int> using namespace std; template <typename T> inline void read(T &t) { int f = 0, c = getchar(); t = 0; while (!isdigit(c)) f |= c == '-', c = getchar(); while (isdigit(c)) t = t * 10 + c - 48, c = getchar(); if (f) t = -t; } template <typename T, typename... Args> inline void read(T &t, Args &... args) { read(t); read(args...); } bool isv(char ch){ return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u'; } int main(){ bool ok=true; string str1,str2; cin>>str1>>str2; if(str1.size()!=str2.size()){ puts("No"); return 0; } for (int i = 0; i < str1.size();i++){ if(isv(str1[i]) != isv(str2[i]) ) ok = false; } if(ok) puts("Yes"); else puts("No"); }
true
a51983a3e18bcc78946a117fe364528cfa5fe5da
C++
pcasamiquela/IA_PracticaFinal
/source/HC_DecisionTreeBoid.cpp
UTF-8
2,582
2.53125
3
[]
no_license
/* ======================================================================== File: HC_DecisionTreeBoid.cpp Revision: 0.1 Creator: David Collado Ochoa Notice: (C) Copyright 2016 by David Collado Ochoa. All Rights Reserved. ======================================================================== */ #include "HC_DecisionTreeBoid.h" #include "GameController.h" void HC_DecisionTreeBoid::Update(float deltaTime) { // Update Boid health if (Vector2D::Distance(position, GameController::Instance().healthArea->center) > GameController::Instance().healthArea->radius) { if (Vector2D::Distance(position, GameController::Instance().coverArea->center) > GameController::Instance().coverArea->radius) { // Decrease health if not in Health Area and not inside Cover Area timeHealth += deltaTime; if (timeHealth > K_HEALTH_DECREASE_TIME) { health -= 1; timeHealth = 0.0f; } } } else { // Set health if inside Health Area health = 10; } // Run Tree RunDecisionTree(); // Call Base Update AnimatedBoid::Update(deltaTime); } void HC_DecisionTreeBoid::Render() { // Render nearby boid area filledCircleColor(Game::Instance().renderer, position.x, position.y, K_NEARBY_THRESHOLD, Colors::SetAlpha(Colors::ASBESTOS, 128)); AnimatedBoid::Render(); } void HC_DecisionTreeBoid::Clean() { AnimatedBoid::Clean(); } void HC_DecisionTreeBoid::RunDecisionTree() { // Run Hard-Coded Decision Tree if (DecisionHealthOk()) { if (DecisionEnemyNearby()) { if (DecisionEnemyDangerous()) { ActionCover(); } else { ActionAttackEnemy(); } } else { ActionCover(); } } else { ActionSeekHealth(); } } // Decision methods bool HC_DecisionTreeBoid::DecisionEnemyNearby() { return (Vector2D::Distance(GameController::Instance().player->position, position) < K_NEARBY_THRESHOLD); } #define K_HEALTH_OK 3 bool HC_DecisionTreeBoid::DecisionHealthOk() { return (health > K_HEALTH_OK); } bool HC_DecisionTreeBoid::DecisionEnemyDangerous() { return GameController::Instance().player->isDangerous; } // Action methods void HC_DecisionTreeBoid::ActionSeekHealth() { SetBehavior(Behavior::ARRIVE); targetPosition = &GameController::Instance().healthArea->center; } void HC_DecisionTreeBoid::ActionAttackEnemy() { SetBehavior(Behavior::PURSUE); targetPosition = &GameController::Instance().player->position; targetSpeed = &GameController::Instance().player->speed; } void HC_DecisionTreeBoid::ActionCover() { SetBehavior(Behavior::ARRIVE); targetPosition = &GameController::Instance().coverArea->center; }
true
b728b0fbd988f48596db2bd0d1d0fdeaeb438416
C++
alvls/mp1-2021-1
/Yunin_DD/task6/MySnake.cpp
UTF-8
1,706
3.234375
3
[]
no_license
#include "MySnake.h" const char SNAKE_TAIL = 'o'; const char SNAKE_HEAD = 'O'; void MySnake::RestartSnake(MyCoordXY star_pos) { snake.clear(); snake.reserve(1000); for (int i = 0; i < 5; i++) { snake.push_back(star_pos); } for (int i = 1; i < 5; i++) { snake[i].x++; } } void MySnake::DrawSnake(MyDisplay& console) { console.SetColor(9, 0); console.GoAndDrawSymbol(snake[0].x, snake[0].y, SNAKE_HEAD); console.SetColor(6, 0); for (int i = 1; i < snake.size(); i++) { console.GoAndDrawSymbol(snake[i].x, snake[i].y, SNAKE_TAIL); } drawn = snake.size(); } void MySnake::GrowSnake(int growsize) { MyCoordXY temp = LastElement(); for (int i = 0; i < growsize; i++) { snake.push_back(temp); } } MyCoordXY MySnake::LastElement() { int size = snake.size(); size--; return snake[size]; } bool MySnake::IntoSnake(MyCoordXY& pos) { for (unsigned int i = 0; i < snake.size(); i++) { if (snake[i].x == pos.x && snake[i].y == pos.y) { return true; } } return false; } void MySnake::MoveSnake(MyCoordXY& delta, MyDisplay& console) { typedef vector<MyCoordXY> CoordVectortemp; CoordVectortemp tmpvector; int size = snake.size(); tmpvector.reserve(size); for (int i = 0; i < size; i++) { tmpvector.push_back(snake[i]); } if (drawn == snake.size()) { console.GoAndDrawSymbol(snake[size - 1].x, snake[size - 1].y, ' '); } else { drawn++; } snake[0] += delta; for (int i = 1; i < size; i++) { snake[i] = tmpvector[i - 1]; } console.SetColor(9, 0); console.GoAndDrawSymbol(snake[0].x, snake[0].y, SNAKE_HEAD); console.SetColor(6, 0); console.GoAndDrawSymbol(snake[1].x, snake[1].y, SNAKE_TAIL); } MyCoordXY MySnake::Head() { return snake[0]; }
true
ea8c0fe3925e663f3702cc6a7511d3b00eaa9f15
C++
luyanfei/algorithm016
/Week_04/55.jump-game.cpp
UTF-8
1,266
3.625
4
[]
no_license
/* * @lc app=leetcode.cn id=55 lang=cpp * * [55] 跳跃游戏 * * https://leetcode-cn.com/problems/jump-game/description/ * * algorithms * Medium (41.09%) * Total Accepted: 157.7K * Total Submissions: 383.6K * Testcase Example: '[2,3,1,1,4]' * * 给定一个非负整数数组,你最初位于数组的第一个位置。 * * 数组中的每个元素代表你在该位置可以跳跃的最大长度。 * * 判断你是否能够到达最后一个位置。 * * 示例 1: * * 输入: [2,3,1,1,4] * 输出: true * 解释: 我们可以先跳 1 步,从位置 0 到达 位置 1, 然后再从位置 1 跳 3 步到达最后一个位置。 * * * 示例 2: * * 输入: [3,2,1,0,4] * 输出: false * 解释: 无论怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 , 所以你永远不可能到达最后一个位置。 * * */ class Solution { public: bool canJump(vector<int>& nums) { if (nums.size() == 0) { return false; } int reachable = nums.size() - 1; for (int i = nums.size() - 1; i >= 0; i--) { if (i + nums[i] >= reachable) { reachable = i; } } return reachable == 0; } };
true
f32e54b90363def29fbf31fc036374090867d3ae
C++
ecsanchesjr/GPX2
/sources/main.cpp
UTF-8
4,926
2.84375
3
[ "MIT" ]
permissive
#include <algorithm> #include <cmath> #include <cstdlib> #include <ctime> #include <fstream> #include <iostream> #include <chrono> #include "Config.hpp" #include "Population.hpp" #include "Utils.hpp" #include "GAUtils.hpp" #include "Arg.hpp" using std::cout; using std::endl; using std::invalid_argument; using std::srand; using std::stof; using std::stoi; using std::ofstream; // inicia o algoritmo genético void GA(); //1 -n argumento tour_name REQUIRED //2 -lib caminho para o .tsp //3 -s tamanho da pop REQUIRED //4 -id ID da run(usado para log //5 -lk porcentagem de população inicial gerado pelo LK //6 -np tipo de geração da nova poop //7 -nb n best para serem salvos para a proxima geração //8 -bf best fitness conhecida // ex: GA -n berlin52 -lib lib/ -s 100 -id 3 -lk 0.1 -np 1 -nb 4 -bf 255 // ex: GA -n berlin52 -s 100 int main(int argc, char *argv[]) { srand(time(NULL)); Arg arg(argc,argv); if(arg.getOption("n").empty()){ cout<<"name of the tour is required"<<endl; return(0); } if(arg.getOption("s").empty()){ cout<<"size of the population is required"<<endl; return(0); }else{ try { Config::NAME = arg.getOption("n"); Config::POP_SIZE = stoi(arg.getOption("s")); string tmp{""},cmd{"lib"}; if(arg.isSet(cmd)){ tmp = arg.getOption(cmd); if(tmp == ""){ cout<<"command "<<cmd<<" needs an argument"<<endl; return(0); }else{ Config::LIB_PATH = tmp; } } cmd = "id"; if(arg.isSet(cmd)){ tmp = arg.getOption(cmd); if(tmp == ""){ cout<<"command "<<cmd<<" needs an argument"<<endl; return(0); }else{ Config::ID = stoi(tmp); } } cmd = "lk"; if(arg.isSet(cmd)){ tmp = arg.getOption(cmd); if(tmp == ""){ cout<<"command "<<cmd<<" needs an argument"<<endl; return(0); }else{ Config::LK_PERCENTAGE = stof(tmp); } } cmd = "np"; if(arg.isSet(cmd)){ tmp = arg.getOption(cmd); if(tmp == ""){ cout<<"command "<<cmd<<" needs an argument"<<endl; return(0); }else{ Config::NEW_POP_TYPE = stoi(tmp); } } cmd = "nb"; if(arg.isSet(cmd)){ tmp = arg.getOption(cmd); if(tmp == ""){ cout<<"command "<<cmd<<" needs an argument"<<endl; return(0); }else{ Config::N_BEST = stoi(tmp); } } cmd = "bf"; if(arg.isSet(cmd)){ tmp = arg.getOption(cmd); if(tmp == ""){ cout<<"command "<<cmd<<" needs an argument"<<endl; return(0); }else{ Config::BEST_FITNESS = stoi(tmp); } } } catch (invalid_argument &i_a) { cout << "Invalid argument!" << i_a.what() << endl; return (0); } } GA(); return 0; } void GA() { Population pop; ofstream *logFile{GAUtils::initLogFile()}; GAUtils::printHeader(*logFile); auto start = std::chrono::high_resolution_clock::now(); GAUtils::init(pop); auto finishInitPop = std::chrono::high_resolution_clock::now(); GAUtils::printTime(*logFile,"Population created in:",std::chrono::duration<double,std::milli> (finishInitPop - start).count(),std::chrono::duration<double> (finishInitPop - start).count()); auto startGA = std::chrono::high_resolution_clock::now(); int i{1}, firstBestFitness{pop.bestFitness()}; *logFile << "\nFirst fitness " << firstBestFitness << endl; do { pop = GAUtils::generateNewPopulation(pop); *logFile << "gen " << i << " best fitness " << pop.bestFitness() << endl; i++; } while (GAUtils::stop(pop)); auto finishGA = std::chrono::high_resolution_clock::now(); GAUtils::printTime(*logFile,"GA execution time:",std::chrono::duration<double,std::milli> (finishGA - startGA).count(),std::chrono::duration<double> (finishGA - startGA).count()); auto finish = std::chrono::high_resolution_clock::now(); GAUtils::printTime(*logFile,"Total execution time:",std::chrono::duration<double,std::milli> (finish - start).count(),std::chrono::duration<double> (finish - start).count()); GAUtils::printFooter(*logFile,pop,i,firstBestFitness); (*logFile).close(); delete logFile; }
true
6aa2f3de1c6f38725c8a5f8221ed0bee38b2364c
C++
michivo/osd
/ue3/ConstConstConst/ConstConstConst/Dummy.cpp
UTF-8
567
3.03125
3
[ "MIT" ]
permissive
#include "stdafx.h" #include "Dummy.h" Dummy::Dummy() : od_{ 0 } { } Dummy::Dummy(OtherDummy od) : od_{ od } { } const OtherDummy & Dummy::get_other_ref() const { return od_; } OtherDummy Dummy::get_other_val() const { return od_; } OtherDummy& Dummy::get_other_nc_ref() { return od_; } void Dummy::set_other(const OtherDummy & od) { od_ = od; } void Dummy::change_dummy(int new_x) { od_.set_x(new_x); } void Dummy::const_change_dummy(int new_x) const { // od_.set_x(new_x); // compiler says no. cannot call non-const method on member in const method }
true
c0b98d0f93ca80515d561918ef8d499322672ff7
C++
Conglang/MyLeetCode
/src/Reverse_Nodes_in_k-Group.cpp
UTF-8
2,692
3.71875
4
[]
no_license
////////////////////////////////////////////////////// // Project: MyLeetCode // // Author: YanShicong // Date: 2014/11/17 ////////////////////////////////////////////////////// /*-------------------------------------------------------------------------------------------------------------- * Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. * * If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. * * You may not alter the values in the nodes, only nodes itself may be changed. * * Only constant memory is allowed. * * For example, * Given this linked list: 1->2->3->4->5 * * For k = 2, you should return: 2->1->4->3->5 * * For k = 3, you should return: 3->2->1->4->5 //--------------------------------------------------------------------------------------------------------------*/ #include "../include/include.h" // 时间复杂度O(n),空间复杂度O(1)。 // fast先走到k的倍数处等着,slow一个个跟上,同时反转next指向。此段的首尾更改一下next。 // 然后修改指针,进入下一个k倍数段。 class Solution { public: ListNode *reverseKGroup(ListNode *head, int k) { if (!head || !head->next || k < 2) {return head;} ListNode dummy(-1); dummy.next = head; int count(0); ListNode* fast = head; ListNode* slow = head->next; ListNode* period_start = &dummy; ListNode* prev = head; while(fast) { ++count; ListNode* next_fast = fast->next; if ((count % k) == 0) { for(int i = 1; i < k; ++i) { ListNode* behind = slow->next; slow->next = prev; prev = slow; slow = behind; } ListNode* next_period_start = period_start->next; period_start->next->next = next_fast; period_start->next = prev; period_start = next_period_start; prev = next_fast; slow = next_fast ? next_fast->next : NULL; } fast = next_fast; } return dummy.next; } }; //-------------------------------------------------------------------------------------------------------------- TEST_CASE("Reverse_Nodes_in_k-Group", "[Linked Lists]"){ Solution sln; SECTION("Empty Input"){ REQUIRE(sln.reverseKGroup(NULL,0) == NULL); } ListNode a1(1); ListNode a2(2); ListNode a3(3); ListNode a4(4); ListNode a5(5); a1.next = &a2; a2.next = &a3; a3.next = &a4; a4.next = &a5; SECTION("Normal Input1"){ int temp[5] = {2,1,4,3,5}; vector<int> res(temp, temp+5); REQUIRE(get_nodes_val(sln.reverseKGroup(&a1,2)) == res); } SECTION("Normal Input2"){ int temp[5] = {3,2,1,4,5}; vector<int> res(temp, temp+5); REQUIRE(get_nodes_val(sln.reverseKGroup(&a1,3)) == res); } }
true
6139e52b86ae8bf143009ccd7df41a34fe093dd6
C++
TaranSinghania/sherpa_41
/src/dom.cpp
UTF-8
4,743
2.84375
3
[ "MIT" ]
permissive
// sherpa_41's DOM module, licensed under MIT. (c) hafiz, 2018 #ifndef DOM_CPP #define DOM_CPP #include "dom.h" #include <iterator> #include <sstream> #include "visitor/visitor.h" /** * Inserts an attribute * @param attribute attribute to add * @param value value of attribute */ void DOM::AttributeMap::insert(const std::string& attribute, const std::string& value) { if (find(attribute) == end()) { (*this)[attribute] = value; order.push_back(attribute); } } auto DOM::AttributeMap::print() const -> std::string { if (empty()) { return ""; } auto assign = [this](const auto& attr) { return attr + "=\"" + const_cast<AttributeMap&>(*this)[attr] + "\""; }; auto start = order.begin(); std::string first = order.front(); return std::accumulate( std::next(start), order.end(), assign(first), [&assign](auto acc, auto attr) { return acc + " " + assign(attr); }); } /** * Creates a DOM Node * @param tag node tag name */ DOM::Node::Node(std::string tag) : tag(std::move(tag)) {} /** * Pure virtual destructor prevents unanticipated instantiation */ DOM::Node::~Node() = default; /** * Determines whether the Node is of specified type * @param cand tag to match * @return whether Node is of `cand` type */ auto DOM::Node::is(const std::string& cand) const -> bool { return tagName() == cand; } /** * Returns the tag name of the Node * @return Node tag */ auto DOM::Node::tagName() const -> std::string { return tag; } /** * Creates a Text Node * @param tag node tag name * @param text node content */ DOM::TextNode::TextNode(std::string text) : Node("TEXT NODE"), text(std::move(text)) {} /** * Returns text * @return text */ auto DOM::TextNode::getText() const -> std::string { return text; } /** * Accepts a visitor to the node * @param visitor accepted visitor */ void DOM::TextNode::acceptVisitor(Visitor& visitor) const { visitor.visit(*this); } /** * Clone the Text Node to a unique pointer * @return cloned Node */ auto DOM::TextNode::clone() -> DOM::NodePtr { return NodePtr(new TextNode(text)); } /** * Creates a Comment Node * @param comment node content */ DOM::CommentNode::CommentNode(std::string comment) : Node("COMMENT NODE"), comment(std::move(comment)) {} /** * Returns comment * @return comment */ auto DOM::CommentNode::getComment() const -> std::string { return comment; } /** * Accepts a visitor to the node * @param visitor accepted visitor */ void DOM::CommentNode::acceptVisitor(Visitor& visitor) const { visitor.visit(*this); } /** * Clone the Comment Node to a unique pointer * @return cloned Node */ auto DOM::CommentNode::clone() -> DOM::NodePtr { return NodePtr(new CommentNode(comment)); } /** * Creates an Element Node * @param tag node tag name * @param attributes node attributes * @param children children nodes */ DOM::ElementNode::ElementNode(std::string tag, AttributeMap attributes, const NodeVector& children) : Node(std::move(tag)), attributes(std::move(attributes)), children() { this->children.reserve(children.size()); std::for_each(children.begin(), children.end(), [this](const auto& child) { this->children.push_back(child->clone()); }); } /** * Returns pointers to children nodes * @return children nodes */ auto DOM::ElementNode::getChildren() const -> DOM::NodeVector { NodeVector nodes; std::transform(children.begin(), children.end(), std::back_inserter(nodes), [](const auto& child) { return child->clone(); }); return nodes; } /** * Returns pretty-printed attributes * @return attributes */ auto DOM::ElementNode::getAttributes() const -> std::string { return attributes.print(); } /** * Returns id of element * @return id */ auto DOM::ElementNode::getId() const -> std::string { auto id = attributes.find("id"); return id != attributes.end() ? id->second : ""; } /** * Returns classes of element * @return classes */ auto DOM::ElementNode::getClasses() const -> std::vector<std::string> { auto classes = attributes.find("class"); if (classes == attributes.end()) { return {}; } std::istringstream iss(classes->second); return {std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}}; // split classes by space } /** * Accepts a visitor to the node * @param visitor accepted visitor */ void DOM::ElementNode::acceptVisitor(Visitor& visitor) const { visitor.visit(*this); } /** * Clone the Element Node to a unique pointer * @return cloned Node */ auto DOM::ElementNode::clone() -> DOM::NodePtr { return NodePtr(new ElementNode(tagName(), attributes, children)); } #endif
true
60e6ecfa2f78ea53527ac088efc3bae059207f6f
C++
kurocha/buffers
/source/Buffers/Buffer.cpp
UTF-8
3,619
2.828125
3
[ "MIT" ]
permissive
// // Buffer.cpp // This file is part of the "Buffers" project and released under the MIT License. // // Created by Samuel Williams on 17/7/2016. // Copyright, 2016, by Samuel Williams. All rights reserved. // #include "Buffer.hpp" #include "File.hpp" #include <stdexcept> #include <system_error> #include <cassert> #include <cstring> #include <sstream> #include <sys/types.h> #include <unistd.h> namespace Buffers { Buffer::~Buffer() { } const Byte Buffer::at (std::size_t offset) const { if (offset > size()) throw std::out_of_range(__func__); return begin()[offset]; } void Buffer::read (std::size_t offset, std::size_t size, Byte * value) const { assert(offset+size <= this->size()); std::memcpy(value, begin() + offset, size); } const Byte & Buffer::operator[] (std::size_t offset) const { assert(offset <= size()); return begin()[offset]; } const Byte * Buffer::end () const { return begin() + size(); } bool Buffer::operator== (const Buffer & other) const { return compare(other) == 0; } bool Buffer::operator!= (const Buffer & other) const { return compare(other) != 0; } int Buffer::compare(const Buffer & other) const { // If buffers are not the same size, they can't possibly be the same: if (size() < other.size()) return -1; if (size() > other.size()) return 1; // If buffers both point to the same block of data (and are the same size) they are the same: if (begin() == other.begin()) return 0; if (size() == 0) return 0; return std::memcmp(begin(), other.begin(), size()); } /// Dump the buffer as hex to the given stream. void Buffer::hexdump (std::ostream & out) const { // http://stahlforce.com/dev/index.php?tool=csc01 const Byte * current = begin(); std::size_t remaining = size(); while (true) { std::stringstream buffer; buffer << "0x"; buffer.fill('0'); buffer.width(sizeof(long) * 2); buffer.setf(std::ios::hex, std::ios::basefield); buffer << (current - begin()) << " >"; std::size_t count = std::min(remaining, (std::size_t)4*4); for (std::size_t i = 0; i < (4*4); i += 1) { if (i > 0 && i % 4 == 0) buffer << ' '; if (i < count) { buffer.width(2); buffer << (int)(*(current + i)); } else buffer << " "; } buffer << "< "; out << buffer.str(); for (std::size_t i = 0; i < count; i += 1) { Byte character = *(current + i); if (character >= 32 && character <= 128) out << character; else out << "."; } out << std::endl; remaining -= count; if (remaining == 0) break; current += count; } } uint32_t Buffer::checksum () const { uint32_t sum = 0; uint32_t r = 55665; const uint32_t C1 = 52845; const uint32_t C2 = 22719; std::size_t s = size(); const Byte * b = begin(); for (unsigned i = 0; i < s; i += 1) { Byte cipher = (b[i] ^ (r >> 8)); r = (cipher + r) * C1 + C2; sum += cipher; } return sum; } void Buffer::write_to_file (const std::string & path) const { File file(path, O_CREAT|O_RDWR); file.write(*this); } void Buffer::write_to_stream (FileDescriptor file_descriptor) const { std::size_t sent = 0; while (sent < size()) { auto result = ::write(file_descriptor, begin() + sent, size() - sent); if (result < 0) { throw std::system_error(errno, std::system_category(), "write"); } sent += result; } } std::ostream & operator<< (std::ostream & out, const Buffer & buffer) { out.write(reinterpret_cast<const std::ostream::char_type *>(buffer.begin()), buffer.size()); return out; } }
true
27c0c5c6f891520069dad426e0f84171fd5104fc
C++
hnlylmlzh/cs
/array/char_array/main.cpp
UTF-8
880
3.453125
3
[]
no_license
#include <iostream> #include <string> // pointer array const char * p[] = { "wang zong", "sun zong", "china" }; const char * q[] = { "wang zong", "sun zong", "china" , 0 }; char * pp[] = { "wang zong", "sun zong", "china" }; char * qq[] = { "wang zong", "sun zong", "china" , 0 }; char * a = "hello world"; const char * b = "hello world again"; int main() { // p is a array of pointer, there are three pointers in array p // one pointer is 8 bytes, so the sizeof array p is 24 bytes std::cout << sizeof(p) << std::endl; std::cout << sizeof(q) << std::endl; std::cout << sizeof(pp) << std::endl; std::cout << sizeof(qq) << std::endl; std::cout << sizeof(a) << std::endl; for (int i = 0; NULL != q[i]; i++) { std::cout << q[i] << std::endl; } for (int i = 0; NULL != p[i]; i++) { std::cout << p[i] << std::endl; } return 0; }
true
32bc5f7ca30246d2ada0e16bd160ac99f780c39a
C++
RedwanNewaz/tase_exp
/include/TrajPlanner.h
UTF-8
1,901
2.703125
3
[]
no_license
// // Created by redwan on 5/3/19. // #ifndef TASE_EXP_TRAJPLANNER_H #define TASE_EXP_TRAJPLANNER_H #include <iostream> #include <QtCore> #include <QPointF> #include <QThread> #include <queue> #include "MotionPrimitives.h" #include "VizTraj.h" class TrajPlanner:public QThread{ public: TrajPlanner(MotionPrimitives *move):move_(move){ }; virtual ~TrajPlanner() { delete move_; } virtual bool generate()=0; bool hasNext() { return !trajectory_.empty(); }; QPointF next() { QPointF point = trajectory_.front(); trajectory_.pop(); return point; } void write_traj(QString &log){ QString filename ="/home/redwan/catkin_ws/src/tase_exp/result/log.csv"; QFile file(filename); if (file.open(QIODevice::ReadWrite)) { QTextStream stream(&file); stream <<log; } } void run(){ bool status = generate(); if(!status) { std::cerr<<"no trajectory found"<<std::endl; exit(-1); } //TODO - create visulization class for showing gloabl trajectory // TODO - show robot tracking trajectory disp.setTrajectory(trajectory_); while (hasNext()&& ros::ok()){ QPointF point = next(); disp.publish(); //FIXME - get tracking error and write log with tracking error //FIXME - get execution time auto start = ros::Time::now(); move_->goTo(point.x(),point.y()); auto end = ros::Time::now(); auto duration = end - start; qDebug()<<point <<" | "<<trajectory_.size()<<" | "<<duration.sec<<" s"; } qDebug()<<"Planner thread terminated"; } protected: std::queue<QPointF> trajectory_; MotionPrimitives *move_; VizTraj disp; }; #endif //TASE_EXP_TRAJPLANNER_H
true
9f94a95cd8c77f249bb7eb6aed8bd7e823c5c706
C++
guankang/NaviPackDebugTools
/commonSrc/tools/Matrix.h
UTF-8
3,667
2.75
3
[]
no_license
#pragma once #include <stdio.h> #include <stdlib.h> #include <math.h> #include "windowsdef.h" #include <iostream> using namespace std; #define USINGFLOAT //#define USINGDOUBLE #ifdef USINGFLOAT typedef float REAL; #define MATDATATYPE CV_32F #define READTYEP "%f" #endif #ifdef USINGDOUBLE typedef double REAL; #define MATDATATYPE CV_64F #define READTYPE "%lf" #endif #include <vector> #include <string> #include <fstream> using namespace std; class Matrix_{ private: public: int rows; int cols; vector< vector<REAL> > data; Matrix_(){ rows = 0; cols = 0; } Matrix_(int r, int c){ rows = r; cols = c; data.assign(rows, vector<REAL>(cols, 0)); } Matrix_(int r, int c, REAL* p){ rows = r; cols = c; data.assign(rows, vector<REAL>(cols, 0)); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { data[i][j] = p[i*cols + j]; } } } Matrix_(int r, int c, unsigned short* p) { rows = r; cols = c; data.assign(rows, vector<REAL>(cols, 0)); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { data[i][j] = (REAL)p[i*cols + j]; } } } Matrix_(int r, int c, unsigned char* p) { rows = r; cols = c; data.assign(rows, vector<REAL>(cols, 0)); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { data[i][j] = (REAL)p[i*cols + j]; } } } //Matrix(int r, int c, REAL arr){ // rows = r; // cols = c; // data.assign(rows, vector<REAL>(cols, 0)); // for (int i = 0; i < rows; i++) // { // for (int j = 0; j < cols; j++) // { // data[i][j] = arr[i*cols + j]; // } // } //} void ReadFile(string fname); void Init(string filename); void WriteFile(string fname); void PrintMat(); void SetMatrix(int r, int c, REAL* p); Matrix_ operator*(Matrix_ &mul) const; Matrix_ operator*(const REAL &mul) const; Matrix_ operator+(Matrix_ &ad) const; Matrix_ operator-(Matrix_ &su) const; Matrix_ operator/(const REAL &div) const; Matrix_ trans(); Matrix_ m_sqrt(); vector<REAL> mean(int option); Matrix_ sort(vector<int>& id, int option); Matrix_ trunc(int num, int option); Matrix_ invert(); Matrix_ copy(){ Matrix_ res(rows, cols); res.setdata(data); return res; } Matrix_ ROI(int x, int y, int w, int h) { Matrix_ ROI(h, w); for (int i = y; i < y + h; i++) { for (int j = x; j < x + w; j++) { ROI.data[i - y][j - x] = data[i][j]; } } return(ROI); } REAL &operator()(int x, int y){ return data[x][y]; } const REAL &operator()(int x, int y) const{ return data[x][y]; } int Getrows() const{ return this->rows; } int Getcols() const{ return this->cols; } void setdata(vector< vector<REAL> > d){ if (data.size() != d.size()){ cout << "Matrix dimensions must agree." << endl; exit(-1); } data.assign(d.begin(), d.end()); } }; inline Matrix_ zeros(int r, int c){ Matrix_ res(r, c); return res; } inline Matrix_ ones(int r, int c){ Matrix_ res(r, c); vector< vector<REAL> > data_t(r, vector<REAL>(c, 1)); res.setdata(data_t); return res; } inline Matrix_ diag(vector<REAL> d){ int n = d.size(); Matrix_ res(n, n); vector< vector<REAL> > data_t(n, vector<REAL>(n, 0)); for (int i = 0; i<n; i++) data_t[i][i] = d[i]; res.setdata(data_t); return res; } void MatMul(Matrix_ *A, Matrix_ *B, Matrix_ *C); //void MatMul(Matrix *A, Matrix *B, Matrix *C, int thread_num); void MatDiff(Matrix_ *A, Matrix_ *B, Matrix_ *C); void MatDiv(Matrix_ *A, float B, Matrix_ *C); void MatNumMul(Matrix_ *A, float B, Matrix_ *C); unsigned short Convolution(Matrix_ *A, Matrix_ *B, Matrix_ *C, Matrix_ *D); void ROI55(Matrix_ *A, Matrix_ *B, int x, int y, int w, int h);
true
36d5853d39475b8d4a832fcfc00a3e4c52101fa8
C++
Hooje/Introduction_to_algorithm
/997.cpp
UTF-8
967
2.75
3
[]
no_license
#include<iostream> #include<memory.h> #include<math.h> using namespace std; int n; int sum=0, middle; int A[1000]={0}; int value[1000]={0}; int solve(int k); int dp[10000000]; int main() { cin>>n; for (int i = 0; i < n; ++i) { int x; cin>>x; A[i]=x; value[x]++; sum+=x; } middle=sum/2; for (int i = 0; i <=middle; ++i) { if (solve(middle+i)==1) { cout<<abs(sum-2*(middle+i))<<endl; return 0; } if (solve(middle-i)==1) { cout<<abs(sum-2*(middle-i))<<endl; return 0; } } return 0; } int solve(int k) { memset(dp, -1, sizeof(dp)); dp[0]=0; for (int i = 0; i <= 500 ; ++i) { if(value[i]!=0) { for (int j = 0; j <= k; ++j) { if (dp[j]>=0) { dp[j]=value[i]; } else if (j<i || dp[j-i]<=0) { dp[j]=-1; } else dp[j]=dp[j-i]-1; } } } if (dp[k]>=0) { return 1; } return 0; }
true
a1da0b02caa877cc7ddf29770b3553af8e2b9e92
C++
siliconx/cpp
/cpp_primer_plus/16/rangefor.cpp
UTF-8
404
2.625
3
[]
no_license
// @siliconx // 2017-08-27 10:59:31 #include <iostream> #include <vector> int test(int); int main() { std::vector<int> v; for (int i = 0; i < 10; ++i) { v.push_back(i); } for (auto& e : v) { ++e; } for (auto& e : v) { std::cout << e << std::endl; } std::cout << '\n' << test(10) << std::endl; return 0; } int test(int) { return 0; }
true
c4a2d7d6f9244da83e6e79901a3e665c4084765f
C++
KangyinYu/yuk3
/newhw4/new hw4.cpp
UTF-8
784
3.78125
4
[]
no_license
#include <iostream> using namespace std; int binarySearch(int array[], int size, int searchValue) { int low= 0; int high= size - 1; int mid; while(low<=high) { mid = (low+high)/2; if(searchValue==array[mid]) { return mid; } else if(searchValue>array[mid]) { low=mid+1; } else { high=mid-1; } } return -1; } int main() { int a[]= {4, 9, 16, 25, 36, 49, 64, 81}; int userValue; cout << "Enter an integer:" <<endl; cin>> userValue; int result = binarySearch(a, 8, userValue); if(result>=0) { cout<, "The number" << a[result] << "was found at the" " element with index " << result << endl; } else { cout<<"The number " << userValue << " was not found. " <<endl; } }
true
d49d3e40da424931c21c3114e6e61ea1e2a8eaa8
C++
Adinda18/sistemperlombaan2
/main.cpp
UTF-8
10,539
3.015625
3
[]
no_license
#include <iostream> #include <string> #include "list_lomba.h" #include "list_peserta.h" #include "relasi.h" #include <conio.h> using namespace std; int main() { List_peserta L1; List_lomba L2; List_relasi L3; createList(L1); createLomba(L2); createRelasi(L3); int pilih = 0; string nama,nim; int angkatan; char jawab; string lomba; while (pilih==0) { cout<<"=================================================================="<<endl; cout<<" Daftar Kejuaraan Mahasiswa "<<endl; cout<<"=================================================================="<<endl; cout<<"========================== OFFERED MENU =========================="<<endl; cout<<"1. Tambah Mahasiswa."<<endl; cout<<"2. Tambah Kejuaraan."<<endl; cout<<"3. Menambahkan Peserta pada Kejuaraan."<<endl; cout<<"4. Hapus Peserta."<<endl; cout<<"5. Hapus Kejuaraan."<<endl; cout<<"6. Tampil Data."<<endl; cout<<"7. Tampil Data Kejuaraan Tertentu"<<endl; cout<<"8. Kejuaraan Tertentu."<<endl; cout<<"9. Data Kejuaraan Terpopuler dan paling sedikit."<<endl; cout<<endl; cout<<"Silahkan pilih: "; cin>>pilih; system("CLS"); switch (pilih) { case 1: cout<<"Anda akan memasukkan mahasiswa ke sistem [Y/y]"<<endl; cin>>jawab; cout<<endl; while ((jawab=='y') || (jawab=='Y')) { system("CLS"); cout<<"NIM: "; cin>>nim; cout<<"Nama: "; cin>>nama; cout<<"Angkatan: "; cin>>angkatan; system("CLS"); address_peserta p; p=findElm(L1,nim); if(p==NULL) { tambahurut(L1,nama,nim,angkatan); cout<<"Siswa berhasil ditambahkan."<<endl; printInfo(L1); } else { cout<<"Siswa sudah terdaftar."<<endl; } cout<<endl; cout<<"Apakah anda ingin memasukan data peserta lagi? [y/Y]"<<endl; cin>>jawab; cout<<endl; } if ((jawab!='Y') || (jawab!='y')) { system("CLS"); pilih=0; } break; case 2: cout<<"Anda akan menambahkan perlombaan ke sistem [Y/y]"<<endl; cin>>jawab; cout<<endl; while ((jawab=='y') || (jawab=='Y')) { system("CLS"); cout<<"Nama Perlombaan: "; cin>>lomba; system("CLS"); address_lomba p = findElem(L2,lomba); if(p==NULL) { insertLomba(L2,lomba); cout<<"Perlombaan berhasil ditambahkan."<<endl; viewLomba(L2); } else { cout<<"Perlombaan sudah terdaftar "<<endl; } cout<<endl; cout<<"apakah anda ingin memasukan data perlombaan lagi ? [y/Y] "<<endl; cin>>jawab; cout<<endl; } system("CLS"); pilih=0; break; case 3: if ((first(L1)!= NULL)&&(first2(L2)!= NULL)) { cout<<"Apakah anda ingin memasukan peserta ke perlombaan?[y/Y]"<<endl; cin>>jawab; system("CLS"); while ((jawab=='y')||(jawab=='Y')) { cout<<"========== NAMA - NAMA PENDAFTAR LOMBA =========="<<endl; printInfo(L1); cout<<endl; cout<<"===== DAFTAR KEJUARAAN YANG DISELENGGARAKAN ====="<<endl; viewLomba(L2); cout<<endl; cout<<"================================================"<<endl; cout<<"Pilih nim yang akan mengikuti lomba :"<<endl; cin>>nim; cout<<"Pilih perlombaan yang anda inginkan:"<<endl; cin>>lomba; address_peserta a=findElm(L1,nim); address_lomba b=findElem(L2,lomba); if (a==NULL) { cout<<"NIM tersebut tidak ada dalam data."<<endl<<endl; } if (b==NULL) { cout<<"Lomba tersebut tidak ada dalam data."<<endl<<endl; } if ((a!=NULL)&&(b!=NULL)) { address_relasi C = findElmn(L3, a, b); if (C!=NULL) { cout <<"Peserta dengan nim tersebut sudah didaftarkan pada lomba ini."<<endl; } else { address_relasi D = alloRelasi(a,b); insertAkhir(L3,D); cout<<"Proses berhasil."<<endl; cout<<endl; cout<<"=============================================================="<<endl; system("CLS"); } showRelasiParentToChild(L3); } cout<<"apakah anda ingin memasukan lagi peserta ke perlombaan?[Y/y]"<<endl; cin>>jawab; system("CLS"); } pilih=0; } else { pilih=0; cout<<"silahkan isi peserta atau perlombaan terlebih dahulu."<<endl; } break; case 4: cout<<"apakah anda ingin menghapus data peserta"<<endl; cin>>jawab; while((jawab=='y')||(jawab=='Y')) { cout<<"====================================================="<<endl; cout<<" Data Keseluruhan Peserta & Perlombaan yang Diikuti "<<endl; showRelasiParentToChild(L3); cout<<"Masukkan nim peserta yang akan dihapus data-datanya: "<<endl; cin>>nim; address_peserta p = findElm(L1,nim); if (p!=NULL) { deleteRelasiPeserta(L3,p); deletePeserta(L1,p); cout<<"penghapusan data berhasil"<<endl; if(first(L1) != NULL) { showRelasiParentToChild(L3); } else { pilih=0; } } else { cout<<"data kosong"<<endl; } cout<<"apakah anda ingin menghapus peserta lain ?"<<endl; cin>>jawab; } pilih=0; break; case 5: while((jawab=='y')||(jawab=='Y')) { cout<<"====================================================="<<endl; cout<<" Data Keseluruhan Peserta & Perlombaan yang Diikuti "<<endl; showRelasiParentToChild(L3); cout<<"Masukkan nama perlombaan yang akan dihapus datanya: "<<endl; cin>>lomba; address_lomba q; q=findElem(L2,lomba); if (q!=NULL) { deleteRelasiLomba(L3,q); deleteLomba(L2,q); cout<<"penghapusan data berhasil"<<endl; if (first2(L2)!=NULL) { showRelasiParentToChild(L3); } else { cout<<"data kosong"<<endl; } cout<<"apakah anda ingin menghapus peserta lain ?"<<endl; cin>>jawab; } pilih=0; break; case 6: cout<<"====================================================="<<endl; cout<<" Data Keseluruhan Peserta & Perlombaan yang Diikuti "<<endl; showRelasiParentToChild(L3); break; case 7: cout<<"==========================================================="<<endl; cout<<"====== Data Orang yang Mengikuti Perlombaan Tertentu ======"<<endl; cout<<endl; cout<<endl; cout<<"Masukkan kejuaraan yang akan ditampilkan para pesertanya: "<<endl; cin>>lomba; PesertaLombaTertentu(L3, lomba); break; case 8: cout<<"==========================================================="<<endl; cout<<"======= Data Perlombaan yang Diikuti Orang Tertentu ======="<<endl; cout<<endl; cout<<endl; cout<<"Masukkan NIM peserta yang akan ditampilkan perlombaannya : "<<endl; cin>>nim; LombaPesertaTertentu(L3, nim); break; case 9: cout<<"==========================================================="<<endl; cout<<"============= Kejuaraan yang Paling Diminati ============="<<endl; cout<<endl; cout<<endl; string m=kejuaraan_popular(L1,L2,L3); cout<<endl; cout<<endl; cout<<"==========================================================="<<endl; cout<<"============= Kejuaraan yang Paling Sedikit Diminati ============="<<endl; string n=Peserta_DikitLomba(L1,L2,L3); break; } } return 0; } }
true
14d2286dd7974d6261c26ce98ff95b9076fa3ba9
C++
grossora/ConeProject
/ConeProject/conicalprojection.cxx
UTF-8
4,264
2.53125
3
[]
no_license
#ifndef RECOTOOL_CONICALPROJECTION_CXX #define RECOTOOL_CONICALPROJECTION_CXX #include "conicalprojection.h" namespace larlite { //----------------------------------------------------------------------------------------------------------------- // This is the pxpoint for the vertex? std::vector<larutil::PxPoint> conicalprojection::vertexproj(TLorentzVector& pos){ // Has to have good inputs... or put up a flag auto geom = larutil::GeometryUtilities::GetME(); std::vector<larutil::PxPoint> vertex; auto p0 =geom->Get2DPointProjectionCM(&pos,0); vertex.push_back(p0); auto p1 =geom->Get2DPointProjectionCM(&pos,1); vertex.push_back(p1); auto p2 =geom->Get2DPointProjectionCM(&pos,2); vertex.push_back(p2); return vertex; } //----------------------------------------------------------------------------------------------------------------- // This is a pair of PxPoints for the start and end point? std::vector<std::pair<larutil::PxPoint,larutil::PxPoint>> conicalprojection::startendpt(TLorentzVector& pos,TLorentzVector& dir, double Length){ // Has to have good inputs... or put up a flag auto geom = larutil::GeometryUtilities::GetME(); std::vector<std::pair<larutil::PxPoint,larutil::PxPoint>> Vsep; auto p0 =geom->Get2DPointProjectionCM(&pos,0); auto p1 =geom->Get2DPointProjectionCM(&pos,1); auto p2 =geom->Get2DPointProjectionCM(&pos,2); double mag = sqrt(dir.Px()* dir.Px()+dir.Py()* dir.Py()+dir.Pz()* dir.Pz()); double vsx = dir.Px()/mag; double vsy = dir.Py()/mag; double vsz = dir.Pz()/mag; TLorentzVector vv; double xtpc = pos.X() + Length*vsx; vv.SetX(xtpc); double ytpc = pos.Y() + Length*vsy; vv.SetY(ytpc); double ztpc = pos.Z() + Length*vsz; vv.SetZ(ztpc); // Need to know that these are inside of the TPC auto e0 =geom->Get2DPointProjectionCM(&vv,0); auto e1 =geom->Get2DPointProjectionCM(&vv,1); auto e2 =geom->Get2DPointProjectionCM(&vv,2); // Make the pairs std::pair<larutil::PxPoint,larutil::PxPoint> se0(p0,e0); std::pair<larutil::PxPoint,larutil::PxPoint> se1(p1,e1); std::pair<larutil::PxPoint,larutil::PxPoint> se2(p2,e2); Vsep.push_back(se0); Vsep.push_back(se1); Vsep.push_back(se2); return Vsep; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------------------------------------------- // This is a pair that contains the slope and cept for the axis in cm space std::vector<std::pair<double,double>> conicalprojection::ConeAxisSC(TLorentzVector& pos, TLorentzVector& dir, double length){ std::vector<std::pair<double,double>> ret; auto geom = larutil::GeometryUtilities::GetME(); auto v0 =geom->Get2DPointProjectionCM(&pos,0); auto v1 =geom->Get2DPointProjectionCM(&pos,1); auto v2 =geom->Get2DPointProjectionCM(&pos,2); double mag = sqrt(dir.Px()* dir.Px()+dir.Py()* dir.Py()+dir.Pz()* dir.Pz()); double vsx = dir.Px()/mag; double vsy = dir.Py()/mag; double vsz = dir.Pz()/mag; TLorentzVector vv; // avoid infinities double xtpc = pos.X() + length*vsx; vv.SetX(xtpc); double ytpc = pos.Y() + length*vsy; vv.SetY(ytpc); double ztpc = pos.Z() + length*vsz; vv.SetZ(ztpc); auto vv0 =geom->Get2DPointProjectionCM(&vv,0); auto vv1 =geom->Get2DPointProjectionCM(&vv,1); auto vv2 =geom->Get2DPointProjectionCM(&vv,2); double slope0 = (v0.t -vv0.t)/(v0.w - vv0.w); double cept0 = v0.t - slope0 * v0.w ; // is there a time issue? std::pair<double,double> sc0(slope0,cept0); ret.push_back(sc0); double slope1 = (v1.t -vv1.t)/(v1.w - vv1.w); double cept1 = v1.t - slope1 * v1.w; // is there a time issue? std::pair<double,double> sc1(slope1,cept1); ret.push_back(sc1); double slope2 = (v2.t -vv2.t)/(v2.w - vv2.w); double cept2 = v2.t - slope2 * v2.w; // is there a time issue? std::pair<double,double> sc2(slope2,cept2); ret.push_back(sc2); return ret; } } #endif
true
cbd8754d5203f7c3e866e743021e439dc2cc1cb1
C++
marvinschmitt/ipi2017
/loesungen/zettel4/roots.cc
UTF-8
2,443
3.796875
4
[]
no_license
// Aufgabe 4.4 (a): f(x) = x² - c hat die positive Nullstelle Wurzel(c). #include <iostream> #include <cmath> // Nils (Tutor) hat gesagt, wir dürfen in Aufgabenteil d) die sqrt-Funktion nutzen um die Genauigkeit zu bestimmen. using namespace std; const double accuracy = 1.0e-12; // Globale Variable mit gewünschter Genauigkeit double f(double x, double c) // Gibt den Wert von f(x) = x² - c aus { return (x*x - c); } double newton_method(double c, double nullstelle) // Funktion zieht die Wurzel aus c, Startwert ist nullstelle { int k = 1; do { nullstelle = 0.5*(nullstelle + (c/nullstelle)); cout << "Iteration #" << k << ", Wert: " << nullstelle << endl; k++; } while (abs(nullstelle - sqrt(c)) > accuracy); // Genauigkeit wird als Betrag ausgewertet, weil man sich je nach Startwerten von links oder rechts nähern kann. return k-1; } double bisection_method(double c, double a, double b) // Nomenklatur nach Aufgabenblatt. { double m; int k = 1; do { if (f(a, c) < 0 && 0 < f(b, c)) // { m = (a+b) / 2; // hier könnte man auch überall m durch (a+b)/2 ersetzen und bräuchte die Variable m nicht, das würde aber ziemlich unübersichtlich.. if (f(m, c) > 0) b = m; else if (f(m, c ) < 0) a = m; else cout << "Maximale Genauigkeit erreicht." << endl; // Wenn sich die Werte nicht mehr ändern, ist die maximale Auflösung mit double erreicht oder die Wurzel ist als double darstellbar und genau berechnet. cout << "Iteration #" << k << ", Wert: " << m << endl; // m ist die aktuellste Intervallhalbierung und wird deshalb als Schätzer verwendet. } else cout << "Maximale Genauigkeit erreicht." << endl; // Wenn sich die Werte nicht mehr ändern, ist die maximale Auflösung mit double erreicht oder die Wurzel ist als double darstellbar und genau berechnet. k++; } while (abs(m - sqrt(c)) > accuracy); // Genauigkeit wird als Betrag ausgewertet, weil man sich je nach Startwerten von links oder rechts nähern kann. return k-1; } int main() { double c; cout << "Von welcher natürlichen Zahl soll die Quadratwurzel berechnet werden? "; cin >> c; cout << newton_method(c, 4) << " Iterationen bei Newtonverfahren nötig." << endl; cout << "---########################---------------------########################---" << endl << endl << endl; cout << bisection_method(c, 0, 4) << " Iterationen bei Intervallhalbierung nötig." << endl; return 0; }
true
19bc1a20c69ade4da56b540613297da36b91ec0b
C++
kobe24o/LeetCode
/algorithm/leetcode844_backspace-string-compare.cpp
UTF-8
1,552
3.53125
4
[]
no_license
#include <iostream> #include<string> using namespace std; class Solution { public: bool backspaceCompare(string S, string T) { process(S); process(T); int i, j; for(i = 0,j = 0; i < S.size() && j < T.size(); i++,j++) { while(i < S.size() && S[i] == '#') i++; while(j < T.size() && T[j] == '#') j++; if((i < S.size() && j < T.size() && S[i] != T[j]) || (i < S.size() && j >= T.size()) || (j < T.size() && i >= S.size())) return false; } while(i < S.size() && S[i] == '#') i++; while(j < T.size() && T[j] == '#') j++; return i>=S.size() && j>=T.size(); } void process(string &s) { int i, j; for(j = 0; j < s.size(); ++j) { i = j-1; while(j < s.size() && s[j] == '#') { while(i >= 0 && s[i] == '#') i--; if(i >= 0) s[i] = '#'; ++j; } } } }; int main() { Solution s; std::cout << s.backspaceCompare("isfcow#","isfco#w#"); } class Solution { public: bool backspaceCompare(string s, string t) { return process(s) == process(t); } string process(string &s) { vector<char> v; for(char c : s) { if(c == '#') { if (!v.empty()) v.pop_back(); } else v.push_back(c); } return string(v.begin(), v.end()); } };
true
bc733e31e94040a707ae987f7f62629a3d83f5a0
C++
TruVortex/Competitive-Programming
/ICPC/ecna16i.cpp
UTF-8
2,750
2.890625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; template <const int MAXN> struct Dinics { struct edge { int v, flow, cap, rev; }; int vis[MAXN], start[MAXN]; vector<edge> adj[MAXN]; bool BFS(int src, int fin) { memset(vis, -1, sizeof vis); vis[src] = 0; queue<int> buf; buf.push(src); while (!buf.empty()) { int u = buf.front(); buf.pop(); for (auto &x : adj[u]) if (vis[x.v] < 0 && x.flow < x.cap) vis[x.v] = vis[u]+1, buf.push(x.v); } return vis[fin] >= 0; } int add_flow(int u, int flow, int fin) { if (u == fin) return flow; for (; start[u] < adj[u].size(); start[u]++) { auto &x = adj[u][start[u]]; if (vis[x.v] == vis[u]+1 && x.flow < x.cap) { int tmp = add_flow(x.v, min(flow, x.cap-x.flow), fin); if (tmp > 0) { x.flow += tmp; adj[x.v][x.rev].flow -= tmp; return tmp; } } } return 0; } int max_flow(int src, int fin) { assert(src != fin); int ret = 0; while (BFS(src, fin)) { memset(start, 0, sizeof start); for (int f = add_flow(src, INT_MAX, fin); f; ret += f, f = add_flow(src, INT_MAX, fin)); } return ret; } void add_edge(int u, int v, int cap) { adj[u].push_back({v, 0, cap, adj[v].size()}); adj[v].push_back({u, 0, 0, adj[u].size()-1}); } }; // 1 - 100 child // 101 - 200 toy // 201 - 300 category // 301 category other // 303 source // 304 sink const int CHILD = 0; const int TOY = 100; const int CT = 200; const int CT_OTHER = 301; const int SOURCE = 303; const int SINK = 304; int main() { Dinics<350> d; int n, m, p; int k, a; scanf("%i%i%i", &n, &m, &p); const int MAXF = 10000; for (int x = 1; x <= n; x++) { d.add_edge(SOURCE, CHILD+x, 1); scanf("%i", &k); while (k--) { scanf("%i", &a); d.add_edge(CHILD+x, TOY+a, 1); } } vector<int> categories(m+1, CT_OTHER); for (int x = 1; x <= p; x++) { scanf("%i", &k); while (k--) { scanf("%i", &a); categories[a] = CT+x; } scanf("%i", &a); d.add_edge(CT+x, SINK, a); } d.add_edge(CT_OTHER, SINK, MAXF); for (int x = 1; x <= m; x++) d.add_edge(TOY+x, categories[x], 1); printf("%i\n", d.max_flow(SOURCE, SINK)); }
true
9107958a952dfe0a21cceb966f6eb5f009ea15a2
C++
hammad97/pos_system_cplusplus
/PrePackedFood.cpp
UTF-8
661
2.640625
3
[]
no_license
#include "PrePackedFood.h" #include "Product.h" #pragma once PrePackedFood::PrePackedFood(char pname[50],int aoQuantity,int noQuantity, int sQuantity,double pcode,double cp,double sp,double discount,int Quan) :Product(pname,pcode,cp,sp,discount,aoQuantity,noQuantity,sQuantity) { QuantityInUnit=Quan; } double PrePackedFood::CalculatePrice() { double dis; dis=getDiscount(); TotalPrice=TotalPrice-TotalPrice*(dis/100); return TotalPrice; } void PrePackedFood::setQuantityInUnit(int q) { QuantityInUnit=q; } int PrePackedFood::getQuantityInUnit() { return QuantityInUnit; } double PrePackedFood::getTotalPrice() { return TotalPrice; }
true
675ca37a43c23819afc301065ad6e758a8eae88b
C++
SergeyBrian/derivative_calculator
/src/math/Log.h
UTF-8
611
2.671875
3
[]
no_license
// // Created by sergio on 22.03.2021. // #ifndef DERIVATIVE_CALCULATOR_LOG_H #define DERIVATIVE_CALCULATOR_LOG_H #include "UnaryOperation.h" #include "Division.h" class Log : public UnaryOperation{ public: explicit Log(Operation *o) : UnaryOperation(o) {}; string getString() override { return "\\\\ln{(" + operation->getString() + ")}"; } double getNumber(double val) override { return log(operation->getNumber(val)); } Operation *getDerivative(); Operation *simplify() override{return new Log(operation->simplify());} }; #endif //DERIVATIVE_CALCULATOR_LOG_H
true
8f7ada4e72e0dbdbba6af5506b35a9570cc2a2d1
C++
geminoric/nativeRace
/src/sector.hpp
UTF-8
311
2.53125
3
[]
no_license
#ifndef SECTOR_HPP #define SECTOR_HPP #include "component.hpp" #include <vector> class sector : public component { public: int sectX, sectY; std::vector<gameObject *> objectsInSector; sector(int secX, int secY) : sectX(secX), sectY(secY) {} ~sector(); void addToSector(gameObject *obj); }; #endif
true
8f24e62c845670fa08d20ca079a8b71f1706b067
C++
vuslysty/piscineCPP
/rush00/Enemys/FireflyShip.cpp
UTF-8
598
2.6875
3
[]
no_license
// // Created by Vladyslav USLYSTYI on 2019-06-30. // #include <cstdlib> #include "FireflyShip.hpp" FireflyShip::FireflyShip() {} FireflyShip::FireflyShip(int x, int y) { _hp = 3; _damage = 1; _heading = -1; _speed = 2; _pos_y = y; _pos_x = x; _score = 30; pic[0] = 'K'; pic[1] = 'H'; pic[2] = '\0'; } FireflyShip::FireflyShip(FireflyShip const &src) { *this = src; } FireflyShip& FireflyShip::operator=(FireflyShip const &) { return *this; } FireflyShip::~FireflyShip() { } void FireflyShip::move() { count++; if (count % 5 == 0) changePosition(_heading, rand() % 2 == 0 ? 1 : -1); }
true
3b2941799b8eac2f83d430d39a08d72c5b33aeeb
C++
h4tr3d/IncludeOS
/mod/SQLite/sqlite.cpp
UTF-8
1,890
2.96875
3
[ "Apache-2.0" ]
permissive
#include <SQLite/sqlite.hpp> #include <stdio.h> namespace database { SQLite::SQLite() { this->status = sqlite3_open(":memory:", &this->database); printf("Database status: %d, db: %p\n", this->status, this->database); } SQLite::~SQLite() { if (this->database) sqlite3_close((sqlite3*) this->database); } int SQLite::exec(const std::string& command) { char* error = nullptr; int rc = sqlite3_exec(this->database, command.c_str(), 0, 0, &error); if (rc) { printf("SQLite error(%d): %s\n", rc, error); sqlite3_free(error); } return rc; } int SQLite::select(const std::string& query, select_t func) { sqlite3_stmt* stmt; int rc = sqlite3_prepare_v2(this->database, query.c_str(), -1, &stmt, nullptr); if (rc != SQLITE_OK) { printf("SQLite::select() failed: %s\n", sqlite3_errmsg(this->database)); return rc; } while (sqlite3_step(stmt) == SQLITE_ROW) { SQResult result(stmt); int columnCount = sqlite3_column_count(stmt); for (int index = 0; index < columnCount; index++) { std::string type = sqlite3_column_decltype(stmt, index); if (type == "INT") { result.row.emplace_back( SQResult::INTEGER, new int(sqlite3_column_int(stmt, index))); } else if (type == "FLOAT") { result.row.emplace_back( SQResult::FLOAT, new double(sqlite3_column_double(stmt, index))); } else if (type == "TEXT") { result.row.emplace_back( SQResult::TEXT, new std::string((char*) sqlite3_column_text(stmt, index))); } else { printf("SQLite::select(): Unknown column decltype: %s\n", type.c_str()); return SQLITE_IOERR_NOMEM; } } // column index // execute callback to user with result func(result); } // row index sqlite3_finalize(stmt); return SQLITE_OK; } // select() }
true
1d95ca897d0aa0fbe5ae87627b8683cf329ad0b8
C++
joshua-evins/capstone
/Code/Phi/Phi/Circle.h
UTF-8
306
2.671875
3
[]
no_license
#pragma once #include <glm\glm.hpp> class Circle { public: static float diameters[11]; static float radii[11]; Circle* left; Circle* right; Circle* top; Circle* bottom; float diameter; glm::vec2 center; Circle(float x, float y, int diameterIndex); Circle(float x, float y, float diameter); };
true
282aee03c62b6e979bd829b497f0e525a17f79f4
C++
vishalkumarsingh999/CPP_Practice
/Coding_From_School/School_Practice/QWERTYUI.CPP
UTF-8
271
3
3
[]
no_license
#include<iostream.h> #include<process.h> void main() { int num,i; cout<<"\n enter the number:"; cin>>num; for(i=2;i<=num/2 ; ++i) if(num % i==0) { cout<<"\n not a prime number !!!"; exit(0) ; } cout <<"\n it is a prime number."; }
true
27778fafc20fcb2e6ee1c346a6aa4b3f80c74780
C++
frc3512/AutonSelector
/test/src/Main.cpp
UTF-8
1,227
2.703125
3
[ "BSD-3-Clause" ]
permissive
// Copyright (c) 2020 FRC Team 3512. All Rights Reserved. #include <chrono> #include <iostream> #include <thread> #include "autonselector/AutonSelector.hpp" using namespace std::chrono_literals; class Robot { public: void initFunc1() { std::cout << "Auto Init 1" << std::endl; } void initFunc2() { std::cout << "Auto Init 2" << std::endl; } void initFunc3() { std::cout << "Auto Init 3" << std::endl; } void periodicFunc1() { std::cout << "Auto Periodic 1" << std::endl; } void periodicFunc2() { std::cout << "Auto Periodic 2" << std::endl; } void periodicFunc3() { std::cout << "Auto Periodic 3" << std::endl; } }; int main() { frc3512::AutonSelector autonSelector(5800); Robot robot; autonSelector.AddMode("Auto 1", std::bind(&Robot::initFunc1, &robot), std::bind(&Robot::periodicFunc1, &robot)); autonSelector.AddMode("Auto 2", std::bind(&Robot::initFunc2, &robot), std::bind(&Robot::periodicFunc2, &robot)); autonSelector.AddMode("Auto 3", std::bind(&Robot::initFunc3, &robot), std::bind(&Robot::periodicFunc3, &robot)); while (1) { std::this_thread::sleep_for(100ms); } }
true
7d196d84e5e92e7d0b9356027c812c2ac6a36eeb
C++
newkid004/portfolio_01_maple_2
/winDirect/winAPI/sceneTest2.cpp
UTF-8
1,351
2.53125
3
[]
no_license
#include "stdafx.h" #include "sceneTest2.h" HRESULT sceneTest2::init() { pos.x = 100; pos.y = 100; x = y = 0; return S_OK; } void sceneTest2::release() { } void sceneTest2::update() { if (KEYMANAGER->press(VK_LEFT)) { pos.x -= 10; x--; } if (KEYMANAGER->press(VK_RIGHT)) { pos.x += 10; x++; } if (KEYMANAGER->press(VK_UP)) { pos.y -= 10; y--; } if (KEYMANAGER->press(VK_DOWN)) { pos.y += 10; y++; } } void sceneTest2::render() { IMAGEMANAGER->statePos(0, 0); IMAGEMANAGER->find("henesys_background_1")->render(); IMAGEMANAGER->statePos(0, 130); IMAGEMANAGER->find("henesys_background_2")->render(); IMAGEMANAGER->statePos(0, 270); IMAGEMANAGER->find("henesys_background_3")->render(); IMAGEMANAGER->statePos(0, 320); IMAGEMANAGER->find("henesys_background_4")->render(); IMAGEMANAGER->statePos(0, 370); IMAGEMANAGER->find("henesys_background_5")->render(); IMAGEMANAGER->statePos(0, 400); IMAGEMANAGER->find("henesys_background_6")->render(); IMAGEMANAGER->statePos(-pos.x, -pos.y); if (KEYMANAGER->toggle(VK_F1)) { IMAGEMANAGER->find("henesys_pixel")->render(); } else { IMAGEMANAGER->find("henesys")->render(); } IMAGEMANAGER->statePos(pos); IMAGEMANAGER->find("start")->render(); IMAGEMANAGER->statePos(300, 500); IMAGEMANAGER->find("buttonTest")->frameRender(x, y, 1.0f); }
true
8806ea0e31e3cf4cfbd89e2855a0a645f38f2190
C++
EthanJamesLew/DataBass_Project3
/include/songlist.h
UTF-8
1,966
3.28125
3
[]
no_license
#ifndef SongList_H #define SongList_H #include "evector.h" #include "estring.h" #include "song.h" /* Library is an abstract class that define storage and searching of a library type */ template <class T> class Library { public: void addItem(T item){ items.push_back(item); } template <class V> T* searchIndex(unsigned idx, V val) { for (T* it = items.begin(); it != items.end(); ++it) { if ((*it)[idx] == val) return it; } return NULL; } template <class V> e::EVector<T> searchMultiIndex(unsigned idx, V val) { e::EVector<T> results; for (T* it = items.begin(); it != items.end(); ++it) { if ((*it)[idx] == val) results.push_back(*it); } return results; } T* searchOrder(unsigned idx) { return &items[idx]; } size_t getSize(){ return items.size(); } template <class V> bool deleteIndex(unsigned idx, V val) { for (T* it = items.begin(); it != items.end(); ++it) { if ((*it)[idx] == val) { std::swap(*it, items.back()); items.pop_back(); return true; } } return false; } bool deleteNumIndex(unsigned idx) { if (idx >= items.size() || idx < 0) return false; else { std::swap(items[idx], items.back()); items.pop_back(); return true; } } private: e::EVector<T> items; }; /* SongList is a library type that stores songs */ class SongList: public Library<Song> { public: Song* searchSong(int idx, e::EString val) { return searchIndex<e::EString>(idx, val); } Song* searchSong(int idx, char* val) { return searchIndex<e::EString>(idx, val); } e::EVector<Song> searchSongs(int idx, e::EString val) { return searchMultiIndex<e::EString>(idx, val); } e::EVector<Song> searchSongs(int idx, char* val) { return searchMultiIndex<char*>(idx, val); } bool deleteSong(int idx, e::EString val) { return deleteIndex<e::EString>(idx, val); } bool deleteSong(int idx, char* val) { return deleteIndex<char*>(idx, val); } }; #endif
true
cbb931b2f3e95c839516485d0f16df060e86ddcd
C++
shatorofusuki/CPP-STL-Huge-numbers-calculator
/src/CElement/COperator.cpp
UTF-8
993
3.875
4
[]
no_license
#include "COperator.h" COperator::COperator (const EOperation a) : m_Op(a) {} COperator::COperator (const char * op) { if (*op == '+') { m_Op = EOperation::addition; } else if ( *op == '*') { m_Op = EOperation::multiplication; } else if (*op == '-') { m_Op = EOperation::subtraction; } else { cout<<"Error : unknown operation"<<endl; } } EType COperator::getType () const { switch (m_Op) { case addition: return EType::add; break; case multiplication: return EType::mult; break; default: return EType::subtr; break; }; } void COperator::print(ostream & os) const { switch (m_Op) { case addition: os<<" + "; break; case multiplication: os<<" * "; break; case subtraction: os<<" - "; break; default: break; }; }
true
186d9e752a93048a087298ea9eb6ab3aca3bbba2
C++
descrip/competitive-programming
/uva/572.cpp
UTF-8
706
2.53125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int M, N, cnt; char A[101][101]; void recur(int x, int y) { if (!(0 <= y && y < N) || !(0 <= x && x < M) || A[y][x] != '@') return; A[y][x] = '*'; for (int cy = y-1; cy <= y+1; ++cy) for (int cx = x-1; cx <= x+1; ++cx) recur(cx, cy); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); while (cin >> N >> M) { if (M == 0) break; cnt = 0; for (int y = 0; y < N; ++y) for (int x = 0; x < M; ++x) cin >> A[y][x]; for (int y = 0; y < N; ++y) for (int x = 0; x < M; ++x) if (A[y][x] == '@') { recur(x, y); ++cnt; } cout << cnt << '\n'; } return 0;}
true
6c0d015849870e7fe953b86dc53cbdd4b8ea1bdf
C++
zshanahmed/Communication-Assistant-for-Hearing-Impaired
/Code/Normal_Person.cpp
UTF-8
4,361
2.625
3
[]
no_license
#include<stdio.h> #include<winsock2.h> #include <iostream> #include <string> #include "opencv2/highgui/highgui.hpp" #include <assert.h> #pragma comment(lib,"ws2_32.lib") //Winsock Library using namespace cv; using namespace std; int main(int argc , char *argv[]) { WSADATA wsa; printf("-------------------------------------------------------------------------------\n"); printf(" Establishing Connection \n"); printf("-------------------------------------------------------------------------------\n"); printf("Initialising Winsock...\n"); if (WSAStartup(MAKEWORD(2,2),&wsa) != 0) { printf("Failed. Error Code : %d\n",WSAGetLastError()); return 1; } printf("Initialised\n"); SOCKET s; s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(s==INVALID_SOCKET) { printf("Could not create socket: %d\n", WSAGetLastError()); } printf("Socket Created.\n"); struct sockaddr_in server; server.sin_addr.s_addr = inet_addr("127.0.0.1"); server.sin_family = AF_INET; server.sin_port = htons(8888); if( bind(s ,(struct sockaddr *)&server , sizeof(server)) == SOCKET_ERROR) { printf("Bind failed with error code : %d\n" , WSAGetLastError()); } printf("Bind done\n"); //Listen to incoming connections listen(s , 3); //Accept and incoming connection puts("Waiting for incoming connections..."); int c; SOCKET new_socket; struct sockaddr_in client; c = sizeof(struct sockaddr_in); //Initializing for the Text Send to Dumb person int total_Input_Words=0; int total_Vocab_Words=8; string input_line,str; string input_words[100]; string vocab_words[8] = {"YES","WAALAIKUM-US-SALAM","HOW-ARE-YOU","HOW-LONG","MEDICINE","TAKE","PRESCRIPTION","."}; //First of all we will have a receive flag. When it is 1 our socket will be in receive mode //else it will be in sending mode int Recv_Flag; //Firstly set Recv_Flag to 1 because we have assumed that it will receive first Recv_Flag=1; while((new_socket = accept(s , (struct sockaddr *)&client, &c))!=INVALID_SOCKET) { printf("\n-------------------------------------------------------------------------------\n"); printf(" Connection Established \n"); printf("-------------------------------------------------------------------------------\n"); while(1) { if(Recv_Flag==1) { printf("\n\n-------------------------------------------------------------------------------\n"); printf(" Normal Person Receiving Mode \n"); printf("-------------------------------------------------------------------------------\n"); const int buffSize=1000; char server_reply[buffSize]; int recv_size; printf("\nReceived Text: "); while((recv_size = recv(new_socket , server_reply , buffSize , 0)) != SOCKET_ERROR) { server_reply[recv_size] = '\0'; printf(server_reply); printf(" "); string reply=server_reply; if(strcmp(reply.c_str(),".")==0) { Recv_Flag=0; break; } } } if(Recv_Flag==0) { input_line = ""; total_Input_Words=0; printf("\n\n-------------------------------------------------------------------------------\n"); printf(" Normal Person Sending Mode \n"); printf("-------------------------------------------------------------------------------\n"); cout<<"\nPlease Enter Sentence (Terminated by a '.') :\n"<<endl; getline(cin,input_line); istringstream iss(input_line); while (getline(iss, str, ' ' )) { input_words[total_Input_Words] = str.c_str(); total_Input_Words++; } printf("\nWords Selected From Vocabulary Matching:\n"); for(int i=0;i<total_Input_Words;i++) { for(int j=0;j<total_Vocab_Words;j++) { if (input_words[i]==vocab_words[j]) { cout<<"\n"<<input_words[i].c_str(); if(send(new_socket , input_words[i].c_str(), strlen(input_words[i].c_str()) , 0) < 0) { puts("Send failed"); return 1; } Sleep(3000); break; } } } Recv_Flag=1; } } } closesocket(s); WSACleanup(); return 0; }
true
281e76affeac8f92a9f05ff36ef2f4cf34e4ee99
C++
alicezywang/cognition
/src/micros/resource_management/cognition/cognition_manager/core/model_recommend/include/model_recommend/recommend.h
UTF-8
1,458
2.53125
3
[]
no_license
#ifndef RECOMMEND_H #define RECOMMEND_H #include <vector> #include <string> #include <map> #include <ros/package.h> namespace cognition { struct task_info { std::string task_id; std::string task_type; std::string battle_field; std::string task_period; std::string target_category; std::string target_status; float target_pose; }; struct actor_info { std::string actor_id; std::string sensor_id; std::string sensor_type; std::string cpu_info; int memory_info; }; struct task_description { task_info task_inf; actor_info actor_inf; }; struct actor_who { std::string sensor_type; std::string cpu_info; int memory_info; }; struct task_what { std::string task_type; std::string target_category; std::string target_status; float target_pose; }; struct scene_where { std::string field; std::string period; }; struct model_description { std::string model_id; std::string train_framework; std::string developer; std::string root_path; float confidence; actor_who who_inf; task_what what_inf; scene_where where_inf; }; std::map<std::string, model_description> load_model_list(); std::vector<std::string> get_recommended_models(const task_description &task, const std::map<std::string, model_description> &model_list); }//namespace #endif // RECOMMEND_H_H
true
0381838bc7095074641966265ce5828c5c25bb26
C++
delyex/depthai-core
/examples/bootloader/bootloader_config.cpp
UTF-8
2,012
2.734375
3
[ "MIT" ]
permissive
#include "depthai/depthai.hpp" int main(int argc, char** argv) { // Options bool usage = false, read = true, clear = false; std::string path = ""; if(argc >= 2) { std::string op = argv[1]; if(op == "read") { read = true; } else if(op == "flash") { read = false; if(argc >= 3) { path = argv[2]; } } else if(op == "clear") { clear = true; read = false; } else if(op == "clear") { clear = true; read = false; } else { usage = true; } } else { usage = true; } if(usage) { std::cout << "Usage: " << argv[0] << " [read/flash/clear] [flash: path/to/config/json]" << std::endl; return -1; } // DeviceBootloader configuration bool res = false; dai::DeviceInfo info; std::tie(res, info) = dai::DeviceBootloader::getFirstAvailableDevice(); if(res) { std::cout << "Found device with name: " << info.desc.name << std::endl; dai::DeviceBootloader bl(info); if(read) { std::cout << "Current flashed configuration\n" << bl.readConfigData().dump(4) << std::endl; } else { bool success; std::string error; if(clear) { std::tie(success, error) = bl.flashConfigClear(); } else { if(path.empty()) { std::tie(success, error) = bl.flashConfig(dai::DeviceBootloader::Config{}); } else { std::tie(success, error) = bl.flashConfigFile(path); } } if(success) { std::cout << "Successfully flashed bootloader configuration\n"; } else { std::cout << "Error flashing bootloader configuration: " << error; } } } else { std::cout << "No devices found" << std::endl; } return 0; }
true
1e057caa4401cf861201d3289c153dce2799a0bf
C++
bayusamudra5502/PustakaCPP
/Pemrograman Kompetitif/Runtuh-Rev2.cpp
UTF-8
1,482
2.671875
3
[ "MIT" ]
permissive
#include <bits/stdc++.h> using namespace std; char matriks[25][10]; bool hapus(); int R,C; void runtuh(); void isi(); void cetak(); int maximum = -1; int main(){ for(int i = 0; i < 25; i++){ for(int j = 0; j < 10; j++){ matriks[i][j] = '0'; } } isi(); runtuh(); cetak(); return 0; } void isi(){ scanf("%d %d", &R, &C); for(int i = 0; i < R; i++){ scanf("%s",matriks[i]); } } void cetak(){ for(int i = 0; i < R; i++){ printf("%s\n",matriks[i]); } } bool hapus(){ bool hasil = false; for(int i = 0; i < R; i++){ bool hapuskan = true; for(int j = 0; j < C; j++){ if(matriks[i][j] == '0'){ hapuskan = false; } } if(hapuskan){ hasil = true; maximum = i; for(int j = 0; j< C; j++){ matriks[i][j] = '0'; } } } return hasil; } void runtuh(){ if(hapus()){ for(int j=0; j < C; j++){ for(int i=maximum; i >= 0; i--){ if(matriks[i][j] == '1'){ int tmp = i; while(matriks[tmp+1][j] != '1' && tmp < R-1){ swap(matriks[tmp+1][j],matriks[tmp][j]); tmp++; } } } } runtuh(); } }
true
6a07f585b736ef1010b4be77f4d9967b0290604f
C++
BuffBuff/GE-Architecture
/GEN/ResourceCache/Source/ResourceCache.cpp
UTF-8
8,421
2.765625
3
[]
no_license
#include "ResourceCache.h" #include "DefaultResourceLoader.h" #include <algorithm> #include <iomanip> #include <iostream> namespace GENA { std::shared_ptr<ResourceHandle> ResourceCache::find(ResId res) { std::unique_lock<std::recursive_mutex> lLock(leastRecentlyUsedLock, std::defer_lock); std::unique_lock<std::recursive_mutex> rLock(resourcesLock, std::defer_lock); std::lock(lLock, rLock); auto iter = resources.find(res); if (iter != resources.end()) { return iter->second; } auto weakIter = weakResources.find(res); if (weakIter != weakResources.end()) { std::shared_ptr<ResourceHandle> handle = weakIter->second.lock(); weakResources.erase(res); if (handle) { resources[res] = handle; leastRecentlyUsed.push_front(handle); return handle; } } return std::shared_ptr<ResourceHandle>(); } void ResourceCache::update(std::shared_ptr<ResourceHandle> handle) { std::lock_guard<std::recursive_mutex> lock(leastRecentlyUsedLock); leastRecentlyUsed.remove(handle); leastRecentlyUsed.push_front(handle); } std::shared_ptr<ResourceHandle> ResourceCache::load(ResId res) { std::shared_ptr<IResourceLoader> loader; std::shared_ptr<ResourceHandle> handle; for (auto testLoader : resourceLoaders) { if (testLoader->getPattern() == file->getResourceType(res)) { loader = testLoader; break; } } if (!loader && !resourceLoaders.empty()) { loader = resourceLoaders.back(); } if (!loader) { throw std::runtime_error("Default resource loader not found!"); } uint64_t rawSize = file->getRawResourceSize(res); char* rawCharBuffer = loader->useRawFile() ? allocate(rawSize) : new char[(size_t)rawSize]; if (rawCharBuffer == nullptr) { // Out of cache memory return std::shared_ptr<ResourceHandle>(); } Buffer rawBuffer(rawCharBuffer, (size_t)rawSize); file->getRawResource(res, rawBuffer.data()); uint64_t size = 0; if (loader->useRawFile()) { handle = std::shared_ptr<ResourceHandle>(new ResourceHandle(res, std::move(rawBuffer), this)); } else { size = loader->getLoadedResourceSize(rawBuffer); Buffer buffer(allocate(size), (size_t)size); if (rawBuffer.data() == nullptr || buffer.data() == nullptr) { // Out of cache memory return std::shared_ptr<ResourceHandle>(); } handle = std::shared_ptr<ResourceHandle>(new ResourceHandle(res, std::move(buffer), this)); if (!loader->loadResource(rawBuffer, handle)) { // Out of cache memory return std::shared_ptr<ResourceHandle>(); } } if (handle) { std::unique_lock<std::recursive_mutex> lLock(leastRecentlyUsedLock, std::defer_lock); std::unique_lock<std::recursive_mutex> rLock(resourcesLock, std::defer_lock); std::lock(lLock, rLock); leastRecentlyUsed.push_front(handle); resources[res] = handle; } return handle; } void ResourceCache::asyncLoad(ResId res, void (*completionCallback)(std::shared_ptr<ResourceHandle>, void*), void* userData) { std::shared_ptr<ResourceHandle> handle = load(res); if (handle) { completionCallback(handle, userData); } std::thread me; { std::lock_guard<std::recursive_mutex> rLock(workerLock); me = std::move(workers[res]); workers.erase(res); } std::lock_guard<std::mutex> lock(doneWorkersLock); doneWorkers.push_back(std::move(me)); } void ResourceCache::free(std::shared_ptr<ResourceHandle> gonner) { std::unique_lock<std::recursive_mutex> lLock(leastRecentlyUsedLock, std::defer_lock); std::unique_lock<std::recursive_mutex> rLock(resourcesLock, std::defer_lock); std::lock(lLock, rLock); resources.erase(gonner->resource); leastRecentlyUsed.remove(gonner); std::weak_ptr<ResourceHandle> weakGonner = gonner; gonner.reset(); gonner = weakGonner.lock(); if (gonner) { weakResources[gonner->resource] = gonner; } } void ResourceCache::makeRoom(uint64_t size) { if (size > cacheSize) { throw std::runtime_error("Object to large for cache"); } while (size > cacheSize - allocated) { if (leastRecentlyUsed.empty()) { std::streamsize oldWidth = std::cerr.width(); std::streamsize idWidth = std::numeric_limits<ResId>::digits10 + 1; std::streamsize sizeWidth = std::numeric_limits<size_t>::digits10 + 1; std::cerr << "Failed to make room for resource\n"; std::cerr << "\nResources currently loaded:\n"; for (const auto& res : weakResources) { std::shared_ptr<ResourceHandle> handle = res.second.lock(); if (handle) { std::cerr << std::setw(idWidth) << res.first << " " << std::setw(sizeWidth) << handle->getBuffer().size() << std::setw(oldWidth) << " B " << file->getResourceName(res.first) << "\n"; } } std::cerr << std::endl; break; } freeOneResource(); } } char* ResourceCache::allocate(uint64_t size) { std::unique_lock<std::recursive_mutex> lLock(leastRecentlyUsedLock, std::defer_lock); std::unique_lock<std::recursive_mutex> rLock(resourcesLock, std::defer_lock); std::lock(lLock, rLock); makeRoom(size); char* mem = new char[(size_t)size]; if (mem) { uint64_t alloced = allocated += size; if (alloced > maxAllocated) { maxAllocated = alloced; } } return mem; } void ResourceCache::freeOneResource() { std::shared_ptr<ResourceHandle> handle = leastRecentlyUsed.back(); leastRecentlyUsed.pop_back(); resources.erase(handle->resource); leastRecentlyUsed.remove(handle); std::weak_ptr<ResourceHandle> weakGonner = handle; handle.reset(); handle = weakGonner.lock(); if (handle) { weakResources[handle->resource] = handle; } } void ResourceCache::memoryHasBeenFreed(uint64_t size, ResId resId) { std::unique_lock<std::recursive_mutex> lLock(leastRecentlyUsedLock, std::defer_lock); std::unique_lock<std::recursive_mutex> rLock(resourcesLock, std::defer_lock); std::lock(lLock, rLock); allocated -= size; if (weakResources.count(resId) > 0) { weakResources.erase(resId); } } ResourceCache::ResourceCache(uint64_t sizeInMiB, std::unique_ptr<IResourceFile>&& resFile) : cacheSize(sizeInMiB * 1024 * 1024), allocated(0), maxAllocated(0), file(std::move(resFile)) { } ResourceCache::~ResourceCache() { for (auto& t : workers) { t.second.join(); } workers.clear(); for (auto& t : doneWorkers) { t.join(); } doneWorkers.clear(); while (!leastRecentlyUsed.empty()) { freeOneResource(); } } void ResourceCache::init() { file->open(); registerLoader(std::shared_ptr<IResourceLoader>(new DefaultResourceLoader())); } void ResourceCache::registerLoader(std::shared_ptr<IResourceLoader> loader) { resourceLoaders.push_front(loader); } std::shared_ptr<ResourceHandle> ResourceCache::getHandle(ResId res) { std::unique_lock<std::recursive_mutex> lock(workerLock); std::shared_ptr<ResourceHandle> handle(find(res)); if (!handle) { if (workers.count(res) == 0) { handle = load(res); } else { workers[res].join(); workers.erase(res); handle = find(res); } } else { update(handle); } return handle; } void ResourceCache::preload(ResId res, void (*completionCallback)(std::shared_ptr<ResourceHandle>, void*), void* userData) { std::shared_ptr<ResourceHandle> handle; { std::unique_lock<std::recursive_mutex> lock(workerLock); handle = find(res); if (!handle) { if (workers.count(res) == 0) { std::thread newWorker(&ResourceCache::asyncLoad, this, res, completionCallback, userData); workers.emplace(res, std::move(newWorker)); } return; } } completionCallback(handle, userData); std::lock_guard<std::mutex> lock(doneWorkersLock); for (auto& doneThread : doneWorkers) { doneThread.join(); } doneWorkers.clear(); } ResourceCache::ResId ResourceCache::findByPath(const std::string path) const { const uint32_t numRes = file->getNumResources(); for (uint32_t i = 0; i < numRes; ++i) { ResId resId = file->getResourceId(i); if (file->getResourceName(resId) == path) { return resId; } } throw std::runtime_error(path + " could not be mapped to a resource"); } std::string ResourceCache::findPath(ResId res) const { return file->getResourceName(res); } uint64_t ResourceCache::getMaxMemAllocated() const { return maxAllocated; } }
true
ec1fe452bdc6ab6e9cd176ab2aed25382f6ad4a6
C++
alejandro-g/Funciona
/VSArrayList.h
UTF-8
596
2.71875
3
[]
no_license
#ifndef VSARRAYLIST_H #define VSARRAYLIST_H #include "ADTList.h" class VSArrayList : public ADTList{ private: int current_capacity; int delta; void resize(); Object** array; public: VSArrayList(int); VSArrayList(int,int); virtual ~VSArrayList(); virtual bool insert(Object*, int); virtual Object* remove(int); virtual Object* first() const; virtual Object* last() const; virtual void clear(); virtual int indexOf(Object*) const; virtual Object* get(int) const; virtual int capacity() const; virtual bool isEmpty() const; virtual bool isFull() const; }; #endif
true
4cc79030c2371af81e2ab72f915891aa6ec74f9d
C++
skvl/TermOx
/include/termox/painter/detail/screen.hpp
UTF-8
742
2.53125
3
[ "MIT" ]
permissive
#ifndef TERMOX_PAINTER_DETAIL_SCREEN_HPP #define TERMOX_PAINTER_DETAIL_SCREEN_HPP #include <termox/painter/detail/staged_changes.hpp> namespace ox::detail { /// Writes uncommitted changes to the underlying paint engine. /** Also enable the cursor on the widget in focus. Implements optimizations * if the tile already exists onscreen. All coordinates are global. */ class Screen { public: Screen() = delete; public: /// Puts the state of \p changes onto the physical screen. static void flush(Staged_changes::Map_t const& changes); /// Moves the cursor to the currently focused widget, if cursor enabled. static void display_cursor(); }; } // namespace ox::detail #endif // TERMOX_PAINTER_DETAIL_SCREEN_HPP
true
22cf603b707a767b875403a22eeae95e52ab0629
C++
Huynh-Thanh-Tam/Lean
/B5.CPP
UTF-8
632
3.296875
3
[]
no_license
#include <iostream> #include <cmath> using namespace std; // Nhập va xuất mảng một chiều void input(int m[], int n) { for(int i = 0; i <= n; i++) { cout << "["<< i+1 << "] = "; cin >> m[i]; } } void output(int m[], int n) { for(int i = 0; i < n; i++) { cout << m[i] << " "; } } int main() { int n; int m[10]; cout << "\tnhap So luong mang \n\n"; do { cout << "input : "; cin >> n; }while(n <= 0 || n > 10); cout << "\t Nhap Gia Tri cho mang \n\n: "; input(m,n); cout << "\t Xuat ra cac phan tu mang \n"; output(m,n); return 0; }
true
b8ae1b6e77ac25d3adf9dde1963125e1f480e587
C++
xiaoyongaz/jslintcode
/7binaryTree/removeNode.cpp
UTF-8
2,412
3.953125
4
[]
no_license
class TreeNode { public: int val; TreeNode *left, *right; TreeNode(int val) { this->val = val; this->left = this->right = nullptr; } } class Solution { public: int removeLeftMax(TreeNode* pre, TreeNode* node){ //if right is nullptr, then itself is largest, remove itself if(node->right == nullptr){ pre->left = node->left; auto val = node->val; delete node; return val; } while(node->right != nullptr){ pre = node; node = node->right; } auto val = node->val; removeNodeHelper(pre, node, false); return val; } int removeRightMin(TreeNode* pre, TreeNode* node){ if(node->left == nullptr){ pre->right = node->right; auto val = node->val; delete node; return val; } while(node->left != nullptr){ pre = node; node = node->left; } auto val = node->val; removeNodeHelper(pre, node, true); return val; } void removeNodeHelper(TreeNode* pre, TreeNode* node, bool left){ if(node->left == nullptr && node->right == nullptr){ if(left) pre->left = nullptr; else pre->right = nullptr; delete node; return; } if(node->left != nullptr){ auto val = removeLeftMax(node, node->left); node->val = val; return; } auto val = removeRightMin(node, node->right); node->val = val; return; } void removeNodeP(TreeNode* pre, TreeNode * root, int value, bool left) { if(root == nullptr) return; if(root->val == value) { removeNodeHelper(pre, root, left); return; } pre = root; if(root->val > value){ root = root->left; removeNodeP(pre, root, value, true); return; } root = root->right; removeNodeP(pre, root, value, false); return; } TreeNode * removeNode(TreeNode * root, int value) { auto dummyNode = new TreeNode(0); dummyNode->left = root; removeNodeP(dummyNode, root, value, true); return dummyNode->left; } };
true
e614458f4b9dbab0f7b6ce10623aff909f349bfa
C++
mohitsh/cpp
/binaryTree/generalTreeAlgo/tree.cpp
UTF-8
2,320
3.859375
4
[]
no_license
#include<iostream> using namespace std; struct node { int data; node* left; node* right; }; node *newNode(int key) { node *new_node = new node; new_node->data = key; new_node->left = nullptr; new_node->right = nullptr; return new_node; } void printInOrder(node *root) { if (root == nullptr) return; printInOrder(root->left); cout << root->data << endl; printInOrder(root->right); } void printArr(int paths[], int pathLen) { for (int i = 0; i<pathLen; ++i) cout << paths[i] << " "; cout << endl; } void root2leaf(node *head, int paths[], int pathLen) { if (head == nullptr) return; paths[pathLen] = head->data; pathLen++; if (head->left == nullptr && head->right == nullptr) printArr(paths, pathLen); else { root2leaf(head->left, paths, pathLen); root2leaf(head->right, paths, pathLen); } } void printAllPaths(node *head) { /* driver function to print all paths */ int paths[1000]; root2leaf(head, paths, 0); } int hasPathSum(node *head, int sum) { if (head == nullptr) return (sum == 0); else { int new_sum = sum - head->data; return (hasPathSum(head->left, new_sum) || hasPathSum(head->right, new_sum)); } } int maxDepth(node *head) { if (head == nullptr) return 0; int lefth = maxDepth(head->left); int righth = maxDepth(head->right); if (lefth>righth) return 1+lefth; else return 1+righth; } int treeSize(node *head) { if (head == nullptr) return 0; return (1+treeSize(head->left) + treeSize(head->right)); } int main() { node *root = newNode(10); root->left = newNode(5); root->right = newNode(15); root->left->left = newNode(2); root->left->right = newNode(6); root->right->left = newNode(12); root->right->right = newNode(16); root->left->left->left = newNode(1); root->left->left->right = newNode(3); root->right->left->left = newNode(11); root->right->left->right = newNode(14); root->right->left->right->left = newNode(13); root->right->left->right->right = newNode(16); //printInOrder(root); printAllPaths(root); cout << hasPathSum(root,18) << endl; cout << hasPathSum(root,0) << endl; cout << hasPathSum(root,20) << endl; cout << maxDepth(root) << endl; cout << "tree size: " << treeSize(root) << endl; return 0; }
true
1865b1e0d064c998d74d6baab30f7a4cf795cc18
C++
LeeSangYun92/Algorithm
/백준 - 14502.연구소.cpp
UTF-8
1,835
2.765625
3
[]
no_license
//#include <iostream> //#include <vector> //#include <queue> // //using namespace std; // //int N, M; //int **board; //int Max = 0; // //vector<pair<int, int>> v; // //void BFS() //{ // queue<pair<int, int>> q; // bool **visit = new bool*[N]; // for (int i = 0; i < N; i++) // { // visit[i] = new bool[M]; // for (int j = 0; j < M; j++) // { // visit[i][j] = false; // } // } // for (int i = 0; i < v.size(); i++) // { // q.push(make_pair(v[i].first, v[i].second)); // } // // int dx[4] = { 0,0,1,-1 }; // int dy[4] = { 1,-1,0,0 }; // // while (!q.empty()) // { // int x = q.front().first; // int y = q.front().second; // q.pop(); // // for (int i = 0; i < 4; i++) // { // int newX = x + dx[i]; // int newY = y + dy[i]; // // if (newX >= 0 && newX < N &&newY >= 0 && newY < M && // board[newX][newY] == 0 && visit[newX][newY] == false) // { // visit[newX][newY] = true; // q.push(make_pair(newX, newY)); // } // } // } // int count = 0; // for (int i = 0; i < N; i++) // { // for (int j = 0; j < M; j++) // { // if (board[i][j] == 0 && visit[i][j] == false) // count++; // } // } // if (count > Max) // Max = count; // // for (int i = 0; i < N; i++) // { // delete[] visit[i]; // } // delete[] visit; //} //void DFS(int n) //{ // if (n == 3) // { // BFS(); // return; // } // // for (int i = 0; i < N; i++) // { // for (int j = 0; j < M; j++) // { // if (board[i][j] == 0) // { // board[i][j] = 1; // DFS(n + 1); // board[i][j] = 0; // } // } // } //} //int main() //{ // cin >> N >> M; // // board = new int*[N]; // for (int i = 0; i < N; i++) // { // board[i] = new int[M]; // for (int j = 0; j < M; j++) // { // cin >> board[i][j]; // if (board[i][j] == 2) // v.push_back(make_pair(i, j)); // } // } // DFS(0); // // cout << Max << endl; // // return 0; //}
true
71159c42abfe86c3368802c8c5d2ec5d997eb5f6
C++
JanaSabuj/Leetcode-solutions
/797/797.cpp
UTF-8
645
3
3
[ "MIT" ]
permissive
class Solution { public: vector<vector<int>> dfs(vector<vector<int>>& adj, int x, int n) { // base if (x == n - 1) { return {{x}}; } // main vector<vector<int>> ans; for (auto v : adj[x]) { // x -> v vector<vector<int>> paths = dfs(adj, v, n); for (auto subpath : paths) { subpath.push_back(x); ans.push_back(subpath); } } return ans; } vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) { int n = graph.size(); vector<vector<int>> paths = dfs(graph, 0, n); for(auto& path: paths){ reverse(path.begin(), path.end()); } return paths; } };
true
278fb24323aa0e167b66ce5b290a0d7e49c46621
C++
ZhaCong2017/USACO
/1.4.2Mother'sMilk.cpp
UTF-8
3,039
2.6875
3
[]
no_license
/* ID:chac161 TASK:milk3 LANG:C++ */ #include<iostream> #include<stdio.h> #include<fstream> #include<queue> #include<vector> #include<algorithm> #include<set> using namespace std; inline int hashed(int a, int b, int c) { return a * 10000 + b * 100 + c; } int main() { ifstream fin("milk3.in"); ofstream fout("milk3.out"); int a, b, c; vector<int> start; fin >> a >> b >> c; start.push_back(0); start.push_back(0); start.push_back(c); queue<vector<int> > status; set<int> have; set<int> result; status.push(start); have.insert(hashed(0, 0, c)); while (!status.empty()) { vector<int> now = status.front(); vector<int> tmp(3); status.pop(); int h; int count; if (now[0] > 0 && b - now[1] > 0) { count = min(now[0], b - now[1]); h = hashed(now[0] - count, now[1] + count, now[2]); if (have.find(h) == have.end()) { have.insert(h); tmp[0] = now[0] - count; tmp[1] = now[1] + count; tmp[2] = now[2]; status.push(tmp); } if (now[0] - count == 0) result.insert(now[2]); } if (now[0] > 0 && c - now[2] > 0) { count = min(now[0], c - now[2]); h = hashed(now[0] - count, now[1], now[2] + count); if (have.find(h) == have.end()) { have.insert(h); tmp[0] = now[0] - count; tmp[1] = now[1]; tmp[2] = now[2] + count; status.push(tmp); } if (now[0] - count == 0) result.insert(now[2] + count); } if (now[1] > 0 && c - now[2] > 0) { count = min(now[1], c - now[2]); h = hashed(now[0], now[1] - count, now[2] + count); if (have.find(h) == have.end()) { have.insert(h); tmp[0] = now[0]; tmp[1] = now[1] - count; tmp[2] = now[2] + count; status.push(tmp); } if (now[0] == 0) result.insert(now[2] + count); } if (now[1] > 0 && a - now[0] > 0) { count = min(now[1], a - now[0]); h = hashed(now[0] + count, now[1] - count, now[2]); if (have.find(h) == have.end()) { have.insert(h); tmp[0] = now[0] + count; tmp[1] = now[1] - count; tmp[2] = now[2]; status.push(tmp); } if (now[0] + count == 0) result.insert(now[2]); } if (now[2] > 0 && a - now[0] > 0) { count = min(now[2], a - now[0]); h = hashed(now[0] + count, now[1], now[2] - count); if (have.find(h) == have.end()) { have.insert(h); tmp[0] = now[0] + count; tmp[1] = now[1]; tmp[2] = now[2] - count; status.push(tmp); } if (now[0] + count == 0) result.insert(now[2] - count); } if (now[2] > 0 && b - now[1] > 0) { count = min(now[2], b - now[1]); h = hashed(now[0], now[1] + count, now[2] - count); if (have.find(h) == have.end()) { have.insert(h); tmp[0] = now[0]; tmp[1] = now[1] + count; tmp[2] = now[2] - count; status.push(tmp); } if (now[0] == 0) result.insert(now[2] - count); } } vector<int> r; for (set<int> ::iterator iter = result.begin(); iter != result.end(); iter++) r.push_back(*iter); fout << r[0]; for (int i = 1; i < r.size(); i++) fout << ' ' << r[i]; fout << endl; //system("pause"); return 0; }
true
d1af4f8ea7f745ab1c5705299306645883b25100
C++
bbqchickenrobot/RPG-1
/src/Sprite.cpp
UTF-8
1,477
2.765625
3
[]
no_license
#include "Sprite.hpp" CSprite::CSprite() { screen = g_pFramework->GetScreen(); renderer = g_pFramework->GetRenderer(); } CSprite::~CSprite() { SDL_FreeSurface(m_pImage); } void CSprite::Load(const string sFilename) { m_pImage = SDL_LoadBMP(sFilename.c_str()); if (m_pImage == NULL) { cout << "Error while loading: " << sFilename.c_str() << endl; cout << "Error: " << SDL_GetError() << endl; g_pFramework->Quit(); exit(1); } m_Rect.x = 0; m_Rect.y = 0; m_Rect.w = m_pImage->w; m_Rect.h = m_pImage->h; } void CSprite::Load(const string sFilename, int NumFrames, int FrameWidth, int FrameHeight) { Load(sFilename); m_NumFrames = NumFrames; m_FrameWidth = FrameWidth; m_FrameHeight = FrameHeight; m_FrameRect.w = FrameWidth; m_FrameRect.h = FrameHeight; m_NumFramesX = m_pImage->w / m_FrameWidth; } void CSprite::SetColorKey(int R, int G, int B) { SDL_SetColorKey(m_pImage, SDL_SRCCOLORKEY, SDL_MapRGB(m_pImage->format, R, G, B)); } void CSprite::SetPos(float fXPos, float fYPos) { m_Rect.x = static_cast<int>(fXPos); m_Rect.y = static_cast<int>(fYPos); } void CSprite::Render() { SDL_BlitSurface(m_pImage, NULL, screen, &m_Rect); } void CSprite::Render(float fFrameNumber) { int Column = static_cast<int>(fFrameNumber) % m_NumFramesX; int Row = static_cast<int>(fFrameNumber) / m_NumFramesX; m_FrameRect.x = Column * m_FrameWidth; m_FrameRect.y = Row * m_FrameHeight; SDL_BlitSurface(m_pImage, &m_FrameRect, screen, &m_Rect); }
true
4cbcbc272526a90ab459753a2e862569d4b7105a
C++
jjzhang166/Geant4
/SimpleSimClean/include/CIScintiHit.h
UTF-8
3,145
2.796875
3
[]
no_license
/*************************************************************************** * Copyright (C) Minister of Natural Resources Canada 2008. * * hseywerd@nrcan.gc.ca * * * ***************************************************************************/ /** * @file CIScintiHit.h * @brief Represent hits in scintillators. * @author Henry Seywerd hseywerd@nrcan.gc.ca **/ #ifndef CIScintiHit_h #define CIScintiHit_h #include "CIGenericHit.h" /** * @class CIScintiHit * @brief Represent hits in scintillators. * * @author Henry Seywerd <hseywerd@nrcan.gc.ca> */ class CIScintiHit: public CIGenericHit { public: /** * Constructor */ CIScintiHit(); /** * Copy constructor * @param hit object to copy */ CIScintiHit(const CIScintiHit& hit); /** * Assignment * @param hits object to copy */ const CIScintiHit& operator=(const CIScintiHit& hits); /** * Assignment * @param hit object to copy */ G4int operator==(const CIScintiHit& hit) const; /** * allocater method to override memory allocation with Geant's own * @param size the size to allocate */ inline void* operator new(size_t size); /** * deletetion method to override memory deletion with Geant's own */ inline void operator delete(void*); /** * Override for drawing a hit */ void Draw(); /** * Override for printing a hit */ void Print(); /** * Deletion */ ~CIScintiHit(); /** * @return Reference to the name of the incoming particle */ inline G4String& ThePartName() { return m_strPartName; } ; /** * @return Reference to the name of the process involved in the hit interaction */ inline G4String& TheInteractionProcessName() {return m_strInteractionProcessName; } /** * Energy * @return reference to the energy deposited by this track */ inline G4double& TheEnergyDep() { return m_dEnergyDep;} private: /// The name of the particle initiating the hit G4String m_strPartName; /// The process whereby ther particle is interactng G4String m_strInteractionProcessName; G4double m_dEnergyDep; }; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- /** * @class CIScintiHitsCollection * @brief Collection of scintillator hits (CIScintiHits) * * Use G4Allocator to allocate the object * * @author Henry Seywerd <hseywerd@nrcan.gc.ca> */ typedef G4THitsCollection<CIScintiHit> CIScintiHitsCollection; extern G4Allocator<CIScintiHit> CIScintiHitsAllocator; /** * Allocate a new CIScintiHit, using the CIScintiHitsAllocator * @param size its size (not used) * @return a pointer to the new CIScintiHit */ inline void* CIScintiHit::operator new(size_t size) { void *aHit; aHit = (void *) CIScintiHitsAllocator.MallocSingle(); return aHit; } /** * Delete the CIScintiHit, using the CIScintiHitsAllocator * @param aHit pointer to the CIScintiHit to be deleted */ inline void CIScintiHit::operator delete(void *aHit) { CIScintiHitsAllocator.FreeSingle((CIScintiHit*) aHit); } #endif
true
dab08395161fde9d7ce98c93c54c4f54b07652f7
C++
Guima01/trabalhoED2-parte2
/AVLtree.h
UTF-8
1,334
2.734375
3
[]
no_license
#include <fstream> #include "NoAVL.h" #include "HashTable.h" using namespace std; class AVLtree { public: AVLtree(HashTable *tabela); // CONSTRUTOR ~AVLtree(); // DESTRUTOR bool vazia(); // VERIFICA SE A ÁRVORE ESTÁ VAZIA void busca(string code,int &totalCasos, int &comparacoes); // BUSCA void insere(int val); // INSERÇÃO void imprime(HashTable *registros); // IMPRESSÃO NO TERMINAL void saidaArqv(ofstream &saida, HashTable *registros); // IMPRESSÃO POR ARQUIVO int altura (NoAVL* raiz); // CALCULA A ALTURA DE UM NÓ bool menorElemento(Registro *candidatoInicio, Registro *candidatoFim); int retornaMaior(int a, int b); private: NoAVL* raiz; // PONTEIRO PARA A RAIZ DA ÁRVORE HashTable *registros; // FUNÇÕES AUX void auxBusca(NoAVL *p, string code, int &totalCasos, int &comparacoes); // BUSCA NoAVL* auxInsere(NoAVL *p, int val); // INSERÇÃO void auxSaidaArqv(NoAVL *p, int nivel, ofstream &saida, HashTable *registros); // IMPRESSÃO POR ARQUIVO void imprimePorNivel(NoAVL* p, int nivel, HashTable *registros); // IMPRESSÃO NO TERMINAL NoAVL* libera(NoAVL *p); // AUXILIAR DO DESTRUTOR int calculaFB(NoAVL* no); // ROTAÇÕES NoAVL* rotacaoEsquerda(NoAVL* no); NoAVL* rotacaoDireita(NoAVL* no); };
true
21e84d6e9f5ba9924d0d8f7a3a4b885a779c635e
C++
bolvarak/GeneticAlgorithm
/C++/main.cpp
UTF-8
1,266
2.90625
3
[]
no_license
// Application Headers #include <stdlib.h> #include <time.h> #include "GeneticAlgorithm.h" #include "Definitions.h" // Namespace definition using namespace std; // global definitions GeneticAlgorithm* cGeneticAlgorithm; // Main() int main () { // Setup our stop boolean bool bDone = false; // Instantiate the algorithm cGeneticAlgorithm = new GeneticAlgorithm(CROSSOVER_RATE, MUTATION_RATE, POPULATION_SIZE, CHROMOSOME_LENGTH, GENE_LENGTH); // Execute the algorithm cGeneticAlgorithm->Execute(); // Loop until done while (!bDone) { // Check to see if the algorithm has started if (cGeneticAlgorithm->Started()) { // Epoch cGeneticAlgorithm->Epoch(); } else { // Render a clean line cout << "----------------------------------------------------------------------------------" << endl; // Render the Generation count cout << "Generations:\t" << cGeneticAlgorithm->Generation() << endl; // Render the fittest genome cout << "Fittest Genome:\t" << cGeneticAlgorithm->GetFittest() << endl; // Render a clean line cout << "----------------------------------------------------------------------------------" << endl; // Set the done boolean bDone = true; } } // Return return 0; }
true
c5e8f973de2e0293ac38af81d6b86153c0b2a77d
C++
LectureswithAkhil/Implementation-of-stack-using-Array
/Stack.cpp
UTF-8
1,195
3.75
4
[]
no_license
#include<iostream> using namespace std; int top=-1; int a[5]; bool isempty() { if (top==-1) return true; else return false; } void push(int value) { if (top==4) { cout<<"stack is full \n"; } else{ top++; a[top]=value; } } void pop() { if(isempty()) cout<<"The stack is empty \n"; else top--; } void top_show() { if (isempty()) cout<<"stack is empty \n"; else cout<<"The top most element is:"<<a[top]<<"\n"; } void display() { if (isempty()) { cout<<"stack is empty \n"; } else { for(int i=0;i<=top;i++) cout<<a[i]<<" "; cout<<"\n"; } } void isfull() { if(top==4) { cout<<"The stack is full \n"; } else { cout<<"The stack is not full"; } } int main() { int choice,flag=1,value; while(flag==1) { cout<<"\n 1.push 2.pop 3.top 4.display 5.EXIT \n"; cin>>choice; switch(choice) { case 1:cout<<"enter value to be inserted : \n"; cin>>value; push(value); break; case 2:pop(); break; case 3:top_show(); break; case 4:display(); break; case 5:flag=0; break; } } return 0; }
true
789e50e19bd0cccd673f7a180504225281d96f2e
C++
brucechin/Leetcode
/141-Linked List Cycle.cpp
UTF-8
683
3.65625
4
[]
no_license
/* Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it without using extra space? */ /* 一个每次前进两格,一个每次前进一格,如果有环,迟早会重合。不能一个移动,一个停着等相遇,可能停着的那个不在环里 */ class Solution { public: bool hasCycle(ListNode *head) { if(head==NULL) return false; ListNode* walker = head; ListNode* runner = head; while(runner->next!=NULL && runner->next->next!=NULL) { walker = walker->next; runner = runner->next->next; if(walker==runner) return true; } return false; } };
true
cec9f8e01c7c226180fb5b87e212c8971f4246eb
C++
henrybear327/Sandbox
/LeetCode/old/PrepForGoogleInterview2018/C++/first/10_recursive.cpp
UTF-8
4,240
2.84375
3
[]
no_license
#ifdef LOCAL #include <bits/stdc++.h> using namespace std; // tree node stuff here... #endif static int __initialSetup = []() { std::ios::sync_with_stdio(false); cin.tie(NULL); return 0; } (); // code using look-ahead logic -> life is a lot more easier class Solution { private: string conv(int a, int b) { return to_string(a) + to_string(b); } unordered_map<string, bool> dp; bool match(string s, string p, int ps, int pp) { if (dp.find(conv(ps, pp)) != dp.end()) return dp[conv(ps, pp)]; if ((int)p.length() == pp) { // no more pattern to match bool ret = (int)s.length() == ps; // empty string or not dp[conv(ps, pp)] = ret; return ret; } if ((int)s.length() == ps) { // run down the regex :) while (pp < (int)p.length()) { if (pp + 1 < (int)p.length() && p[pp + 1] == '*') // skip match all cases pp += 2; else { // others: failing... dp[conv(ps, pp)] = false; return false; } } dp[conv(ps, pp)] = true; return true; } if (pp + 1 < (int)p.length() && p[pp + 1] == '*') { // a * term // match 0 or match 1+ // case char or . bool ret = match(s, p, ps, pp + 2) || (p[pp] == '.' ? match(s, p, ps + 1, pp) : (p[pp] == s[ps] ? match(s, p, ps + 1, pp) : false)); dp[conv(ps, pp)] = ret; return ret; } else { // a normal term // case char or . bool ret = p[pp] == '.' ? match(s, p, ps + 1, pp + 1) : (p[pp] == s[ps] ? match(s, p, ps + 1, pp + 1) : false); dp[conv(ps, pp)] = ret; return ret; } } public: bool isMatch(string s, string p) { // return regex_match(s, regex(p)); return match(s, p, 0, 0); } }; // // code using look-ahead logic -> life is a lot more easier // class Solution // { // private: // bool match(string s, string p, int ps, int pp) // { // if ((int)p.length() == pp) { // no more pattern to match // return (int)s.length() == ps; // empty string or not // } // if ((int)s.length() == ps) { // run down the regex :) // while (pp < (int)p.length()) { // if (pp + 1 < (int)p.length() && p[pp + 1] == '*') // pp += 2; // else // return false; // } // return true; // } // if (pp + 1 < (int)p.length() && p[pp + 1] == '*') { // a * term // // match 0 or match 1+ // // case char or . // return match(s, p, ps, pp + 2) || // (p[pp] == '.' // ? match(s, p, ps + 1, pp) // : (p[pp] == s[ps] ? match(s, p, ps + 1, pp) : false)); // } else { // a normal term // // case char or . // return p[pp] == '.' // ? match(s, p, ps + 1, pp + 1) // : (p[pp] == s[ps] ? match(s, p, ps + 1, pp + 1) : false); // } // } // public: // bool isMatch(string s, string p) // { // // return regex_match(s, regex(p)); // return match(s, p, 0, 0); // } // }; #ifdef LOCAL int main() { { string s = ""; string p = ""; cout << Solution().isMatch(s, p) << endl; } { string s = "aa"; string p = "a*"; cout << Solution().isMatch(s, p) << endl; } { string s = "cabc"; string p = "c.*c"; cout << Solution().isMatch(s, p) << endl; } { string s = "cab"; string p = "c.*c"; cout << Solution().isMatch(s, p) << endl; } { string s = "aab"; string p = "c*a*b*"; cout << Solution().isMatch(s, p) << endl; } { string s = "a"; string p = "ab*"; cout << Solution().isMatch(s, p) << endl; } return 0; } #endif
true
5507eaecd3cb981988569229d93391b2d28674d9
C++
alexandraback/datacollection
/solutions_1485490_0/C++/dstabosz/toys.cpp
UTF-8
2,590
2.6875
3
[]
no_license
#include <stdio.h> #include <assert.h> #include <cstring> #include <vector> #include <set> #include <list> #include <algorithm> using namespace std; int debug = 0; int N, M; int toyType[100]; long long toyCount[100]; int boxType[100]; long long boxCount[100]; long long Solve(int toyIdx, int boxIdx, int tType, long long toys, int bType, long long boxes, long long total, int level); int main(int argc, char *argv[]) { int T; assert(scanf("%d", &T) == 1); for (int t = 1; t <= T; t++) { assert(scanf("%d %d", &N, &M) == 2); // assert(N <= 1000); for(int i = 0; i < N; i++) { long long a; int b; assert(scanf("%lld %d", &a, &b) == 2); boxCount[i] = a; boxType[i] = b; } for(int i = 0; i < M; i++) { long long a; int b; assert(scanf("%lld %d", &a, &b) == 2); toyCount[i] = a; toyType[i] = b; } long long val = Solve(0, 0, 0, 0, 0, 0, 0, 0); printf ("Case #%d: %lld\n", t, val); fflush(stdout); } } void Indent(int lvl) { for (int l = 0; l < lvl; l++) { printf(" "); } } long long Solve(int toyIdx, int boxIdx, int tType, long long toys, int bType, long long boxes, long long total, int level) { long long count; if (debug) { Indent(level); printf("toys %d/%d/%lld boxes %d/%d/%lld\n", toyIdx, tType, toys, boxIdx, bType, boxes); } while(1) { if (toys == 0) { if (debug) { Indent(level); printf("Get toys, toyIdx %d M %d\n", toyIdx, M); } if (toyIdx == M) break; tType = toyType[toyIdx]; toys = toyCount[toyIdx]; if (debug) { Indent(level); printf("Getting toys idx %d toyType %d count %lld\n", toyIdx, tType, toys); } toyIdx++; } if (boxes == 0) { if (boxIdx == N) break; bType = boxType[boxIdx]; boxes = boxCount[boxIdx]; if (debug) { Indent(level); printf("Getting boxes idx %d toyType %d count %lld\n", toyIdx, tType, toys); } boxIdx++; } if (tType == bType) { count = min(toys, boxes); total += count; toys -= count; boxes -= count; if (debug) printf("Boxed %lld toys type %d\n", count, tType); continue; } long long t1, t2; t1 = Solve(toyIdx, boxIdx, tType, 0, bType, boxes, total, level + 1); t2 = Solve(toyIdx, boxIdx, tType, toys, bType, 0, total, level + 1); return max(t1, t2); } return total; }
true
5d51c234a86fc9416d0b6e73711935a8bafc0a0b
C++
vchahalBMS/CCP
/Lab 1/Count positive,negative,zeros.CPP
UTF-8
531
3.421875
3
[]
no_license
#include<stdio.h> int main() { int limit,num,positive=0,negative=0,zero=0; printf("Enter the limit\n"); scanf("%d",&limit); printf("Enter %d numbers\n",limit); while(limit) { scanf("%d",&num); if(num>0) { positive++; } else if(num<0) { negative++; } else { zero++; } limit--; } printf("\nPositive Numbers: %d\n",positive); printf("\nNegative Numbers: %d\n",negative); printf("\nNumber of zero: %d\n",zero); return 0; }
true
0ef29f191cef6e6e9f1d7f34f7c996173cd283c7
C++
DieterJoubert/CSE100
/pa4-rcaldero-djoubert/boggleutil.cpp
UTF-8
1,057
3.09375
3
[]
no_license
#include "boggleutil.h" //see whether dice has been used in forming word bool BoardNode::getVisited() { return visited; } //sets whether dice has been visited, used by finding word path void BoardNode::setVisited(bool newState) { visited = newState; } //returns the string representing the face of this dice const std::string& BoardNode::getFace() const { return face; } //------------------------------------------------------------ //constructor for MWTNode used by boggleplayer to represent multiwaytrie nodes MWTNode::MWTNode() { //create child for every letter of alphabet children = new MWTNode*[26]; for (int i = 0; i<26; i++) { children[i] = 0; } exists = false; parent = 0; } //destructor for MWTNode MWTNode::~MWTNode(){ for(int i = 0; i<26; i++){ delete children[i]; } delete[] children; } //returns bool exists, used to see if this is end-path of valid word bool MWTNode::getExists() { return exists; } //sets exist, used when creating the trie void MWTNode::setExists(bool state) { exists = state; }
true
a13dd7d1601a2f6fcad3fa100b2254f1d769d065
C++
user160244980349/course-work-footballstars
/sources/Physics.cpp
UTF-8
8,777
2.6875
3
[]
no_license
#include "../include/Physics.h" Physics::Physics (Model* objectPtr, Collider* collider, Vector s, Vector a, Vector g, double bouncy, Collider** otherColliders, int collidresNum, Collider** otherTriggers, int triggersNum) { this -> ThisAttributes.objectPtr = objectPtr; this -> ThisAttributes.collider = collider; this -> Env.otherColliders = otherColliders; this -> Env.otherTriggers = otherTriggers; this -> Env.collidresNum = collidresNum; this -> Env.triggersNum = triggersNum; this -> PhysicalAttributes.maxSpeed = 20; this -> PhysicalAttributes.bouncy = bouncy; this -> Vectors.s = s; this -> Vectors.a = a; this -> Vectors.g = g; this -> Triggers.collision = false; this -> Triggers.bounce = false; this -> Triggers.sleep = true; Vectors.additionalS.x = 0; Vectors.additionalS.y = 0; Vectors.additionalA.x = 0; Vectors.additionalA.y = 0; this -> Triggers.collisions = new bool[collidresNum]; for (int i = 0; i < collidresNum; i++) this -> Triggers.collisions[i] = false; this -> Triggers.onTriggerEnter = new bool[triggersNum]; for (int i = 0; i < triggersNum; i++) this -> Triggers.onTriggerEnter[i] = false; }; void Physics::ApplyForce (Vector s, Vector a) { Vectors.additionalS.x += s.x; Vectors.additionalS.y += s.y; Vectors.additionalA.x += a.x; Vectors.additionalA.y += a.y; }; void Physics::Update () { if (Triggers.sleep) return; Vectors.s.x += Vectors.g.x + Vectors.additionalS.x + Vectors.additionalA.x; Vectors.s.y += Vectors.g.y + Vectors.additionalS.y + Vectors.additionalA.y; Rect newPos; newPos.x = ThisAttributes.objectPtr -> GetPos ().x + Vectors.s.x; newPos.y = ThisAttributes.objectPtr -> GetPos ().y + Vectors.s.y; newPos.w = ThisAttributes.objectPtr -> GetPos ().w; newPos.h = ThisAttributes.objectPtr -> GetPos ().h; if (Vectors.s.x > PhysicalAttributes.maxSpeed) Vectors.s.x = PhysicalAttributes.maxSpeed; if (Vectors.s.x < -PhysicalAttributes.maxSpeed) Vectors.s.x = -PhysicalAttributes.maxSpeed; if (Vectors.s.y > PhysicalAttributes.maxSpeed) Vectors.s.y = PhysicalAttributes.maxSpeed; if (Vectors.s.y < -PhysicalAttributes.maxSpeed) Vectors.s.y = -PhysicalAttributes.maxSpeed; ThisAttributes.objectPtr -> SetPos (newPos); Collide (); if (Triggers.collision) { Triggers.bounce = true; ThisAttributes.objectPtr -> SetPos (PhysicalAttributes.oldPos); } else { PhysicalAttributes.oldPos.x = ThisAttributes.objectPtr -> GetPos ().x - Vectors.s.x; PhysicalAttributes.oldPos.y = ThisAttributes.objectPtr -> GetPos ().y - Vectors.s.y; PhysicalAttributes.oldPos.w = ThisAttributes.objectPtr -> GetPos ().w; PhysicalAttributes.oldPos.h = ThisAttributes.objectPtr -> GetPos ().h; } if (!Triggers.collision && Triggers.bounce) { Vectors.s.x *= PhysicalAttributes.bouncy; Vectors.s.y *= PhysicalAttributes.bouncy; Triggers.bounce = false; } Vectors.additionalS.x = 0; Vectors.additionalS.y = 0; }; void Physics::Sleep() { Triggers.sleep = true; }; void Physics::Awake() { Triggers.sleep = false; }; void Physics::Collide () { double x1 = ThisAttributes.objectPtr -> GetPos().x; // Левая граница тела. double x2 = ThisAttributes.objectPtr -> GetPos().x + ThisAttributes.objectPtr -> GetPos().w; // Правая граница тела. double y1 = ThisAttributes.objectPtr -> GetPos().y; // Верхняя граница тела. double y2 = ThisAttributes.objectPtr -> GetPos().y + ThisAttributes.objectPtr -> GetPos().h; // Нижняя граница тела. int collisionCounter = 0; // Колличество столкновений. double step = 1; // Величина шага проверки на столкновение. for (int collidersCount = 0; collidersCount < Env.collidresNum; collidersCount++) { if (Env.otherColliders[collidersCount] == this -> ThisAttributes.collider) continue; double left = Env.otherColliders[collidersCount] -> GetPos ().x; // Левая граница другого тела. double right = Env.otherColliders[collidersCount] -> GetPos ().x + Env.otherColliders[collidersCount] -> GetPos ().w; // Левая граница другого тела. double top = Env.otherColliders[collidersCount] -> GetPos ().y; // Левая граница другого тела. double bottom = Env.otherColliders[collidersCount] -> GetPos ().y + Env.otherColliders[collidersCount] -> GetPos ().h; // Левая граница другого тела. for (double x = ThisAttributes.objectPtr -> GetPos ().x; x < ThisAttributes.objectPtr -> GetPos ().x + ThisAttributes.objectPtr -> GetPos ().w; x += step) { if (Triggers.collisions[collidersCount]) break; for (double y = ThisAttributes.objectPtr -> GetPos ().y; y < ThisAttributes.objectPtr -> GetPos ().y + ThisAttributes.objectPtr -> GetPos ().h; y += step) { if (Triggers.collisions[collidersCount]) break; if (x > left && x < right && y > top && y < bottom) { Triggers.collision = true; Triggers.collisions[collidersCount] = true; collisionCounter++; if ((abs(y2 - top) >= abs(x2 - left) && abs(y1 - bottom) > abs(x2 - left)) || (abs(y1 - bottom) >= abs(x1 - right) && abs(y2 - top) > abs(x1 - right))) { PhysicalAttributes.moduleX = -1; } else PhysicalAttributes.moduleX = 1; if ((abs(y2 - top) < abs(x2 - left) && abs(y2 - top) <= abs(x1 - right)) || (abs(y1 - bottom) < abs(x1 - right) && abs(y1 - bottom) <= abs(x2 - left))) { PhysicalAttributes.moduleY = -1; } else PhysicalAttributes.moduleY = 1; Vectors.s.x = PhysicalAttributes.previousSpeedX * PhysicalAttributes.moduleX; Vectors.s.y = PhysicalAttributes.previousSpeedY * PhysicalAttributes.moduleY; } } } if (collisionCounter == 0) { Triggers.collision = false; Triggers.collisions[collidersCount] = false; } } if (!Triggers.collision) { PhysicalAttributes.previousSpeedX = Vectors.s.x; PhysicalAttributes.previousSpeedY = Vectors.s.y; } }; bool Physics::OnTriggerStay (Collider* trigger) { double x1 = ThisAttributes.collider -> GetPos().x; double x2 = ThisAttributes.collider -> GetPos().x + ThisAttributes.collider -> GetPos().w; double y1 = ThisAttributes.collider -> GetPos().y; double y2 = ThisAttributes.collider -> GetPos().y + ThisAttributes.collider -> GetPos().h; double left = trigger -> GetPos ().x; double right = trigger -> GetPos ().x + trigger -> GetPos ().w; double top = trigger -> GetPos ().y; double bottom = trigger -> GetPos ().y + trigger -> GetPos ().h; if (x2 > left && x1 < right && y2 > top && y1 < bottom) { return true; } else return false; }; bool Physics::OnTriggerEnter (Collider* trigger) { for (int i = 0; i < Env.triggersNum; i++) { if (trigger != Env.otherTriggers[i]) continue; if (OnTriggerStay (trigger)) { if (!Triggers.onTriggerEnter[i]) { Triggers.onTriggerEnter[i] = true; return true; } else return false; } Triggers.onTriggerEnter[i] = false; return false; } return false; }; Physics::~Physics () { delete this -> Triggers.onTriggerEnter; delete this -> Triggers.collisions; };
true
f9c217fd176f85c830dc1b9a619a581acff6e50e
C++
astronautas/tanks
/Messenger/messenger_client.cpp
UTF-8
2,984
2.65625
3
[]
no_license
#include "Messenger_Client.h" // Explain each #ifdef _WIN32 #include <WinSock2.h> #include <WS2tcpip.h> #include <Windows.h> #else #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <arpa/inet.h> #endif using namespace std; Messenger_Client::Messenger_Client() { } Messenger_Client::~Messenger_Client() { } bool Messenger_Client::Connect(string ip_address, unsigned short port) { if ((port < 1) || (port > 65535)) { throw SocketErrorException("The Port value is not in the range of 0-65535!"); } curr_socket = socket(AF_INET, SOCK_STREAM, 0); // Unless socket is succesfully created, return false if (curr_socket < 0) { int error = errno; // TODO: Throw exception throw SocketErrorException("Cannot create socket with specified data."); } const char *ip_chars = ip_address.c_str(); server_struct.sin_family = AF_INET; // The protocol is IP server_struct.sin_port = htons(port); // u_short -> tcp/ip network byte order inet_pton(AF_INET, ip_chars, &server_struct.sin_addr.s_addr); // Need to cast server_struct to sockaddr from sockaddr_in int connected = connect(curr_socket, (const sockaddr*) &server_struct, sizeof(server_struct)); if (connected < 0) { int error = errno; // TODO: Throw exception throw SocketErrorException("Cannot connect to specified remote (offline)."); } is_connected = true; return true; } void Messenger_Client::Disconnect() { if (is_connected) { is_connected = false; Close_socket(curr_socket); } } bool Messenger_Client::Send(string text) { return Send(curr_socket, text); } bool Messenger_Client::Send(int socket, string text) { return super::Send(socket, text); } void Messenger_Client::WaitForData() { int fdmax = curr_socket; fd_set readfds = {}; fd_set masterfds = {}; FD_SET(curr_socket, &masterfds); while (true) { if (!is_connected) return; //clear the socket set FD_ZERO(&readfds); readfds = masterfds; // Hangs until any of sockets are ready for reading (have new data) if (select(fdmax + 1, &readfds, NULL, NULL, NULL) == -1) { throw SocketErrorException("A select error has occured."); } // Check if server socket is ready for reading if (FD_ISSET(curr_socket, &readfds)) { // Reading client data int readbytes; // First 3 symbols indicate msg length char len_buff[4]; len_buff[3] = '\0'; recv(curr_socket, len_buff, 3, 0); int len = 0; sscanf_s(len_buff, "%d", &len); // len char array to integer char *msg_buffer = new char[len]; readbytes = recv(curr_socket, msg_buffer, len, 0); // Client sends 0 bytes on orderly disconnect if (readbytes <= 0) { Close_socket(curr_socket); FD_CLR(curr_socket, &masterfds); // remove from master set } else { on_message(curr_socket, string(msg_buffer, len)); } delete msg_buffer; } } }
true
274a256a4ba10985fe3afdc84f02bc166b954305
C++
nathaniel-mohr/undergrad_coursework
/CS162/labs/lab7/rectangle.h
UTF-8
307
2.796875
3
[]
no_license
#ifndef RECTANGLE_H #define RECTANGLE_H #include "shape.h" class Rectangle:public Shape{ private: float base; float height; public: float get_base() const; float get_height() const; void set_base(float); void set_height(float); virtual float calculate_area(); Rectangle(); }; #endif
true
b55f5e39718433e56ae12f3d7c697564adc21546
C++
DrSHW/syh-LuoGu
/P5736.cpp
UTF-8
479
2.703125
3
[]
no_license
#include<bits/stdc++.h> #define N 100000 using namespace std; int prime[N] = {0}; int main() { int i, j; prime[0] = 1; prime[1] = 1; for(i = 2; i < N; i++) { if(!prime[i]) { for(j = 2; i * j < N; j++) prime[i * j] = 1; } } // for(i = 2; i < N; i++) // { // cout << i << ' ' << prime[i] << endl; // } int n, a; cin >> n; for(i = 0; i < n; i++) { cin >> a; if(!prime[a]) cout << a << ' '; } return 0; }
true
60ea97ba5c2dcc57b42f6eb257d957e7515aeb67
C++
Treyhowell/csci325
/Vector_program/Vector.cpp
UTF-8
997
3.59375
4
[]
no_license
#include "Vector.h" #include <iostream> using namespace std; Vector::Vector(){ vec_ptr = NULL; vec_size = 0; vec_capacity = 0; } Vector::Vector(const Vector &other){ vec_ptr = other.vec_ptr; vec_size = other.vec_size; vec_capacity = other.vec_capacity; } Vector::~Vector(){ delete [] vec_ptr; vec_size = 0; vec_capacity = 0; } int capacity(){ return vec_capacity; } int Vector::size(){ return vec_size; } void Vector::push_back(int element){ if(vec_size < vec_capacity) vec_ptr[vec_size] = elemtent; else { resize(); vec_ptr[vec_size] = element; } } void Vector::resize(){ if(vec_capacity == 0) vec_capacity = 1; vec_capacity *= 2; } void &Vector::operator=(const Vector &other){ vec_ptr = new int other.vec_capacity; vec_size = other.vec_size; vec_capacity = other.vec_capacity; for(int i = 0; i < vec_size; i++){ vec_ptr[i] = other.vec_ptr[i]; } double &Vector::operator[](unsigned int index){ return vec_ptr[index]; }
true
975c3448478e091f48f07e4722547aebecff915a
C++
xtozero/Study
/SIMD/src/Ch.04/01_overview.cpp
UTF-8
2,828
2.640625
3
[]
no_license
/*-------------- SIMD 명령어를 이용한 구현은 어셈블리 언어 구조이므로 루프 문에 대한 구현, 레지스터 개수 제한, 디버깅의 어려움 등의 단점이 있다. 인텔에서는 이런 점을 보안하기 위해 intrinsic 함수를 제공한다. intrinsic 함수를 사용하면 C/C++환경에 익숙한 루프와, 조건문, 코드의 가독성, 보다 나은 디버깅 환경을 얻을 수 있다. 명명법 _mm_<intrin_op>_<suffix> _mm_ : SIMD의 intrinsic 함수를 의미한다. <intrin_op> : 실제로 동작할 연산자를 의미한다. <suffix> : 사용하게 될 인자의 데이터 타입과 사이즈, packed 혹은 scalar와 같은 정보가 들어가게 된다. 두 개의 문자가 포함되는데 첫 번째는 p(packed), ep(extended packed), s(scalar)가 들어간다. 두 번째 들어갈 문자는 데이터형의 크기로 결정되며 들어가는 문자는 다음과 같다. 문자 데이터 타입 s 32 bit 실수형 ( single-precision floating point ) d 64 bit 실수형 ( double-precision floating point ) i128 128bit signed 정수 ( signed 128-bit integer ) i64 64bit signed 정수 ( signed 64-bit integer ) u64 64bit unsigned 정수 ( unsigned 64-bit integer ) i32 32bit signed 정수 ( signed 32-bit integer ) u32 32bit unsigned 정수 ( unsigned 32-bit integer ) i16 16bit signed 정수 ( signed 16-bit integer ) u16 16bit unsigned 정수 ( unsigned 16-bit integer ) i8 8bit signed 정수 ( signed 8-bit integer ) u8 8bit unsigned 정수 ( unsigned 8-bit integer ) 128bit 정수형 데이터 타입 명명법 __m128i __m : intrinsic 데이터 타입임을 나타낸다. 128 : 데이터형의 사이즈이다. i : 정수형을 의미한다. intrinsic 함수를 사용하기 위해서는 다음과 같은 헤더 파일을 포함해야 한다. SSE2 : emmintrin.h SSE3 : pmmintrin.h SSE4 : smmintrin.h, nmmintrin.h --------------*/ #include <emmintrin.h> #include <iostream> int main( ) { __m128i _128_int_type; /* typedef union __declspec(intrin_type) __declspec(align(16)) __m128i { __int8 m128i_i8[16]; __int16 m128i_i16[8]; __int32 m128i_i32[4]; __int64 m128i_i64[2]; unsigned __int8 m128i_u8[16]; unsigned __int16 m128i_u16[8]; unsigned __int32 m128i_u32[4]; unsigned __int64 m128i_u64[2]; } __m128i; */ __m128 _128_bit_type; /* typedef union __declspec( intrin_type ) __declspec( align( 16 ) ) __m128 { float m128_f32[4]; unsigned __int64 m128_u64[2]; __int8 m128_i8[16]; __int16 m128_i16[8]; __int32 m128_i32[4]; __int64 m128_i64[2]; unsigned __int8 m128_u8[16]; unsigned __int16 m128_u16[8]; unsigned __int32 m128_u32[4]; } __m128; */ return 0; }
true
9240578e67edb062be5f03883a82ca11869bcb26
C++
TheiaRT/libpnmpp
/pixel.h
UTF-8
1,675
3.078125
3
[]
no_license
#ifndef PIXEL_H #define PIXEL_H #include <iostream> #include "dist/jsoncpp/json/json.h" #include "json_util.h" struct pixel_t { long r, g, b; pixel_t() { r = g = b = 0; } pixel_t(long r, long g, long b) : r(r), g(g), b(b) { } pixel_t operator+(const pixel_t &other) { return pixel_t(r + other.r, g + other.g, b + other.b); } pixel_t operator/(double scale) { return pixel_t(r / scale, g / scale, b / scale); } pixel_t operator/(int scale) { return *this / (double) scale; } pixel_t(Json::Value json_pixel) : r(json_pixel[0].asInt()), g(json_pixel[1].asInt()), b(json_pixel[2].asInt()) { } Json::Value to_json_value() { Json::Value json_pixel; json_pixel.append((int) r); json_pixel.append((int) g); json_pixel.append((int) b); return json_pixel; } std::string to_json() { return json_to_string(to_json_value()); } static bool from_json(std::string json, pixel_t &res) { Json::Value root; Json::Reader reader; if (reader.parse(json, root, false)) { res = pixel_t(root); return true; } return false; } static pixel_t *from_json_value(Json::Value pixels_json, int width, int height) { pixel_t *pixels = new pixel_t[width * height]; for (int i = 0; i < width * height; i++) { pixels[i] = pixel_t(pixels_json[i]); } return pixels; } }; #endif
true
2d99e55ac65a1c72bda8eb3f64b72887e5149dc9
C++
the-bad-cop/memmgmt_cpp
/raii/raii.cpp
UTF-8
702
3.765625
4
[]
no_license
#include <iostream> class raiClass { int *_ptr; public: raiClass(int *p = NULL) : _ptr(p) {} ~raiClass() { std::cout << "resource: " << *_ptr << " deallocated\n"; delete _ptr; } int &operator*() { return *_ptr; } }; int main() { int a[] = {1, 2, 3, 4, 5}; for (size_t i = 0; i < 5; i++) { // int *e = new int(i); raiClass e(new int(i)); //when e goes of of scope, it will be automatically deallocated //also here allocation is done within the main class and the pointer is copied to the class std::cout << "Dividing " << *e << " with " << a[i] << " = " << (float)*e / a[i] << std::endl; // delete e; } }
true
0ccc0c0e626e22f874759bdd333c663d098979a7
C++
dut-info/Gare-OpenGL
/BezierCurve.cpp
UTF-8
823
3.15625
3
[ "MIT" ]
permissive
#include "BezierCurve.h" #include "Point.h" #include <vector> #include <stdexcept> BezierCurve::BezierCurve(std::vector<Point> points) { this->points = std::vector<Point>(points); } Point BezierCurve::getTan(double t) { Point p = points[0] * (1 - t)*(1 - t) * (-3) + points[1]*(3*(1 - t)*(1 - t) - 6*(1 - t)*t) + points[2]*(6*(1 - t)*t - 3*t*t) + points[3]*3*t*t; return p; } Point BezierCurve::getPoint(double t) { std::vector<Point> tmp = std::vector<Point>(this->points); for (int i = tmp.size() - 1; i > 0; i--) { for (int k = 0; k < i; k++) tmp[k] = tmp[k] + ( tmp[k+1] - tmp[k] ) * t; } Point result = tmp[0]; //delete tmp; return result; } Point BezierCurve::getNextPoint() { Point p = this->getPoint(this->currentPoint); this->currentPoint += this->precision; return p; }
true
3591be0cd777912a16704549d6203504927c79c6
C++
iamsile/ACM
/Palindrome-2.cpp
UTF-8
1,008
3.546875
4
[]
no_license
#include <iostream> using namespace::std; int main() { char s[1001]; int i,j,m; cin >> m; while(m) { cin >> s; i=strlen(s); for(j=0;j<i/2;j++) { if(s[j]!=s[i-j-1]&&(char)(s[j]+32)!=s[i-j-1]&&s[j]!=(char)(s[i-j-1]+32) &&(char)(s[j]-32)!=s[i-j-1]&&s[j]!=(char)(s[i-j-1]-32)) { cout << "NO" << '\n'; break; } } if(j==i/2) cout << "YES" << '\n'; m--; } return 0; } /* Problem description A palindrome is a symmetrical string, that is, a string read the same from left to right as from right to left. You are asked to write a program which, given a string, determines whether it is a palindrome or not. Input The first line contain a single integer T, indicates the number of test cases. T lines follow, each line contain a string which you should judge. The length of the string is at most 1000. Output Print one line for each string, if it is a palindrome, output “YES”, else “NO”. Sample Input 2 aba ab Sample Output YES NO */
true
69fbb358a13ad4c78875baaecd75d627152e3f4f
C++
jubinsoni/100daysofcode
/day49/day_fourty_nine.cpp
UTF-8
564
3.328125
3
[]
no_license
# include <iostream> # include <queue> using namespace std; void almostSorted(int arr[],int n,int k) { // minheap priority_queue<int,vector<int>,greater<int> > pq; for(int i=0;i<k;i++) { pq.push(arr[i]); } for(int i=0;i<k-1;i++) { cout << "_" << " "; } cout << pq.top() << " "; pq.pop(); for(int i=k;i<n;i++) { pq.push(arr[i]); cout << pq.top() << " "; pq.pop(); } cout << endl; } int main() { int arr1[] = {10, 20, 11, 70, 50, 40, 100, 50}; int n = sizeof(arr1)/sizeof(arr1[0]); int k = 3; almostSorted(arr1,n,k); return 0; }
true
997c48e34a09839ad1ce84c2597c57739d218178
C++
barrmelissa/CS161
/library/book.cpp
UTF-8
1,756
3.140625
3
[]
no_license
/********************************************************************* ** Author: Melissa Barr ** Date: August 8th, 2016 ** Description: Assignment 10 This program uses 6 seperate files and a main file to run a library simulator. It uses the Book files to get the books information, the Patron files to get the Patrons information, and the Library files to run the simulator. *********************************************************************/ #include "Book.hpp" #include <vector> #include <iostream> #include <string> using namespace std; // Constructor Book::Book(string idc, string t, string a) { idCode = idc; title = t; author = a; location = ON_SHELF; } int Book::getCheckOutLength() { return CHECK_OUT_LENGTH; } // Returns the books ID Code string Book::getIdCode() { return idCode; } // Returns the books title string Book::getTitle() { return title; } // Returns the books author string Book::getAuthor() { return author; } // Returns the books location Locale Book::getLocation() { return location; } // Set the location for the book void Book::setLocation(Locale lo1) { location = lo1; } // Return who checked out the book Patron* Book::getCheckedOutBy() { return checkedOutBy; } // Set who checked out the book void Book::setCheckedOutBy(Patron* p1) { checkedOutBy = p1; } // Return who checked out the book Patron* Book::getRequestedBy() { return requestedBy; } // Set who checked out the book void Book::setRequestedBy(Patron* p1) { requestedBy = p1; } // Returns date the book was checked out int Book::getDateCheckedOut() { return dateCheckedOut; } // Sets date the book was checked out void Book::setDateCheckedOut(int d1) { dateCheckedOut = d1; }
true
25dc1c7be12f7d4a6aac595a30fb1d26b7a3d183
C++
ruanbo/Robert
/test_files/data/ThreadClass.cpp
UTF-8
1,398
2.875
3
[]
no_license
/* * ThreadClass.cpp * * Created on: Dec 27, 2013 * Author: root */ #include "ThreadClass.h" #include <pthread.h> ThreadClass::ThreadClass() { _is_running = false; _t_pid = 0; _thread_name = ""; } ThreadClass::ThreadClass(const string & class_name) { _is_running = false; _t_pid = 0; _thread_name = class_name; } ThreadClass::~ThreadClass() { } void ThreadClass::show_local_time() { // struct tm *local; time_t t; // t = time(NULL); time(&t); // local = localtime(&t); cout << _thread_name << ". time: " << endl; // cout << local->tm_year << "-" << local->tm_mon << "-" << local->tm_mday << " " // << local->tm_hour << ":" << local->tm_min << ":" << local->tm_sec << endl; // cout << ctime(&t); } void ThreadClass::timer_100ms() { // _timer_manager.update_now_ms(0); } void ThreadClass::run() { cout << "start this thread_t: " << _t_pid << endl; _is_running = true; while(_is_running == true) { cout << "this thread_t: " << _t_pid << ", name:" << _thread_name << endl; struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 100000; // 100000 select(0, NULL, NULL, NULL, &tv); // show_local_time(); } } void ThreadClass::start() { pthread_create(&_t_pid, NULL, thread_func<ThreadClass, &ThreadClass::run>, this); } void ThreadClass::stop() { _is_running = false; cout << "stop this thread_t:" << _t_pid << ", name:" << _thread_name << endl; }
true
1586776005d35683937477243d604015cf9a7821
C++
IntelLabs/SLIDE_opt_ia
/SLIDE/DensifiedWtaHash.h
UTF-8
760
2.59375
3
[ "MIT" ]
permissive
#pragma once #include <stdio.h> #include <stdlib.h> #include <chrono> #include <climits> #include <iostream> #include <random> #include <vector> #include <string.h> #include "MurmurHash.h" /* * Algorithm from the paper Densified Winner Take All (WTA) Hashing for Sparse Datasets. Beidi Chen, Anshumali Shrivastava */ using namespace std; class DensifiedWtaHash { private: int *_randHash, _randa, _numhashes, _rangePow,_lognumhash, *_indices, *_pos, _permute; public: DensifiedWtaHash(int numHashes, int noOfBitsToHash); template <class T> int * getHash(int* indices, T* data, int dataLen); int getRandDoubleHash(int binid, int count); template <class T> int * getHashEasy(T* data, int dataLen, int topK, int stride = 1); ~DensifiedWtaHash(); };
true
0671054ca87ece3cbe30ebf5d6cd36a177ee6f76
C++
lccl7/My-leetcode
/ReverseNodesink-Group.cpp
UTF-8
1,639
3.234375
3
[]
no_license
ListNode* reverseKGroup(ListNode* head, int k) { if(k <= 1 || !head || !head->next) return head; ListNode Dummy(-1); Dummy.next = head; ListNode *beginK = &Dummy, *endK = &Dummy; while(true) { for(int i = 0; i < k && endK; i++) endK = endK->next; if(!endK) break; ListNode *cur = beginK->next;//When started, beginK->next always points to the head of the k-group for(int i = 0; i < k-1; i++) // each time reverse one node, and do k-1 iterations { ListNode *tmp = cur->next;//tmp is a temporary point that next to the front,which we reverse to the front cur->next = tmp->next; tmp->next = beginK->next;//begink->next which now is the front becomes the second one beginK->next = tmp; // Then begink->next retrieve to the first one } beginK = cur; endK = cur; } return Dummy.next; } //A recursive way ListNode* reverseKGroup(ListNode* head, int k) { return reverseK(head, k, getlength(head)); } ListNode* reverseK(ListNode* head, int k, int len) { if(k == 1 || k > len || !head) return head; int i = 2; ListNode* cur = head->next; ListNode* pre = head; head->next = NULL; ListNode* Dummy = head; while(i <= k) { head = cur; cur = cur->next; head->next = pre; pre = head; head = cur; i++; } Dummy->next = reverseK(head, k, len-k); return pre; } int getlength(ListNode* head) { int len = 0; while(head) { len++; head = head->next; } return len; }
true
691b1b10bb5386becfb6c18e6a248d72ac90e35e
C++
tyadav4268/problem_solving
/dequeue.cpp
UTF-8
1,007
2.625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif int t; cin>>t; while(t--){ long long int m, n; cin>>n>>m; vector<long long int> q; for(long long int j = 0; j < m; j++){ int number; cin>>number; q.push_back(number); } long long int i = 0, j = q.size()-1, count = 0; while(i < j){ if(q[i] != q[i + 1]) while(q[i] != q[i + 1] && i+1 <= q.size() - 1){ count++; i++; } else if(q[j] != q[j - 1]) while(q[j] != q[j - 1] && j - 1 >= 0){ count++; j--; } else if(q[i] == q[i + 1] && q[j] == q[j - 1]){ i++; count++; swap(i, j); } } cout<<count<<endl; } return 0; }
true
c8d4dd7d14d11da4c6ef4d77754e2f0ab32fee62
C++
Kewth/OJStudy
/cf1444b.cpp
UTF-8
1,822
2.921875
3
[]
no_license
/* * Author: Kewth * Date: 2020.11.01 * Solution: * 贡献系数的还原 把序列排个序,容易想到每个数的贡献就是一个系数乘上该数,而该系数只与其所在的位置有关。 那么问题就是求出这个贡献系数,求出所有 01 序列的答案,就可以还原系数数组。 * Digression: * CopyRight: __ __ __ __ | |/ |.-----.--.--.--.| |_| |--. | < | -__| | | || _| | |__|\__||_____|________||____|__|__| */ #include <cstdio> #include <algorithm> #define debug(...) fprintf(stderr, __VA_ARGS__) typedef long long ll; static struct { inline operator int () { int x; return scanf("%d", &x), x; } template<class T> inline void operator () (T &x) { x = *this; } } read; const int maxn = 300005, mod = 998244353; int a[maxn]; ll fac[maxn], ifac[maxn]; ll inv[maxn]; inline ll power (ll x, int k) { if (k < 0) k += mod - 1; ll res = 1; while (k) { if (k & 1) (res *= x) %= mod; (x *= x) %= mod; k >>= 1; } return res; } inline ll C (int n, int m) { if (n < m) return 0; return fac[n] * ifac[m] % mod * ifac[n - m] % mod; } void combinator_init (int n) { fac[0] = 1; for (int i = 1; i <= n; i ++) fac[i] = fac[i - 1] * i % mod; ifac[n] = power(fac[n], -1); for (int i = n; i; i --) ifac[i - 1] = ifac[i] * i % mod; inv[1] = 1; for (int i = 2; i <= n; i ++) inv[i] = (mod - mod / i) * inv[mod % i] % mod; } int main () { int n = read; combinator_init(n << 1); for (int i = 1; i <= n * 2; i ++) read(a[i]); std::sort(a + 1, a + n * 2 + 1); ll las = 0, ans = 0, c = C(n << 1, n); for (int i = n * 2; i; i --) { ll now = (n - std::abs(n * 2 - i + 1 - n)) * c % mod; (ans += (now + mod - las) * a[i]) %= mod; las = now; /* debug("%lld\n", now); */ } printf("%lld\n", ans); }
true
42332ebb06570280f00e0b88b48557aa3188946b
C++
rmrychecky/CSCI1300
/Practice Practicum IV/q10.cpp
UTF-8
1,146
3.609375
4
[]
no_license
#include <iostream> using namespace std; class Probability { private: float prob_values[50]; string event[50]; public: //set each function with their perspective input types Probability(); void ReadFile(string filename); string getMostLikelyEvent(float value); }; Probability :: Probability() { for (int i = 0; i < 50; i++) { prob_values[i] = 0.0; event[i] = ""; } } void Probability :: ReadFile(string filename) { ifstream file; file.open(filename); string line; string array[2]; int i = 0; if (file.is_open()) { while (getline(file, line)) { split(line, ',', array, 2); prob_values[i] = stof(array[1]); event[i] = array[0]; i++; } } file.close(); } string Probability :: getMostLikelyEvent(float value) { float likely; string mostLikelyEvent; for (int i = 0; i < 50; i++) { if (prob_values[i] >= value) { mostLikelyEvent = event[i]; return mostLikelyEvent; } else { mostLikelyEvent = ""; } } return mostLikelyEvent; }
true
2eee1d30d70c298b289fd345e018dc1b9d4c7684
C++
vsdaniela/Daniela
/laboratorio 5/main_chrono.cpp
UTF-8
442
2.90625
3
[]
no_license
#include <iostream> #include "code_chono.h" using namespace std; int main(){ try{ Chrono::Date holiday(1978, Chrono::Date::jul,4); Chrono::Date d2=Chrono::day_next_sunday(holiday); Chrono::Date d = day_of_week(d2); cout<<"Feriado es "<<holiday<<" d2 es "<<d2<<endl; return holiday != d2; } catch(Chrono::Date::Invalid&) { cerr<<"error: Fecha invalida\n"; return 1; } }
true
d9acb3dbca2c0d0845e287643aa13299c131a028
C++
Darui99/ITMO-Algorithms-And-Data-Structures
/Laboratory work 5 - Search trees/Sum again.cpp
UTF-8
1,960
2.6875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; typedef long long ll; const ll mod = (ll)1e+9; struct Node { Node* left; Node* right; ll key, pr, sum; }; Node* Empty = new Node{ NULL, NULL, 0ll, 0ll, 0ll }; Node* root = Empty; void update(Node* v) { if (v == Empty) return; v->sum = v->left->sum + v->right->sum + v->key; } pair <Node*, Node*> split(Node* v, ll k) { if (v == Empty) return make_pair(Empty, Empty); if (v->key > k) { auto gets = split(v->left, k); Node* l = gets.first; Node* r = gets.second; v->left = r; update(l); update(v); return make_pair(l, v); } else { auto gets = split(v->right, k); Node* l = gets.first; Node* r = gets.second; v->right = l; update(v); update(r); return make_pair(v, r); } } Node* merge(Node* l, Node* r) { if (l == Empty) { update(r); return r; } if (r == Empty) { update(l); return l; } if (l->pr > r->pr) { l->right = merge(l->right, r); update(l); return l; } else { r->left = merge(l, r->left); update(r); return r; } } bool contains(Node* v, ll k) { if (v == Empty) return false; if (v->key == k) return true; if (v->key < k) { return contains(v->right, k); } else { return contains(v->left, k); } } void insert(ll k) { auto gets = split(root, k); Node* p = new Node{ Empty, Empty, k, rand(), k }; root = merge(merge(gets.first, p), gets.second); } ll get(ll l, ll r) { auto gets = split(root, l - 1ll); auto gets1 = split(gets.second, r); ll res = gets1.first->sum; root = merge(gets.first, merge(gets1.first, gets1.second)); return res; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); ll q, x, prev = 0ll, l, r; char c; cin >> q; while (q--) { cin >> c; if (c == '+') { cin >> x; x = (x + prev) % mod; if (!contains(root, x)) insert(x); prev = 0ll; } else { cin >> l >> r; x = get(l, r); cout << x << endl; prev = x; } } return 0; }
true
1515d9b5f64bae92f957421086cdf2d6319c7171
C++
jshou/cpp_exercises
/farm.cpp
UTF-8
821
3.765625
4
[]
no_license
#include <iostream> using namespace std; float sum(int horse, int pig, int rabbit); void print_answer(int horse, int pig, int rabbit); int main() { int horse = 100; while (horse > 0) { for (int i = 0; i < (100 - horse); i++) { int pig = i; int rabbit = 100 - horse - pig; if (sum(horse, pig, rabbit) == 100) { print_answer(horse, pig, rabbit); return 0; } } horse --; } cout << "can't find answer" << endl; return -1; } float sum(int horse, int pig, int rabbit) { return 10 * horse + 3 * pig + 0.5 * rabbit; } void print_answer(int horse, int pig, int rabbit) { cout << "horses: " << horse << endl; cout << "pigs: " << pig << endl; cout << "rabbits: " << rabbit << endl; }
true
ee987bc702917b8ce2e604ecad4d09d67fd46d1b
C++
MarshalBrain/C-projects
/KPoint(Ingeritance)/KPoint(Ingeritance)/KShape.cpp
WINDOWS-1251
1,669
3.171875
3
[]
no_license
#include "stdafx.h" #include "KShape.h" const double rad = 3.14159265358979323846 / 180; void KShape::Explode(double a) { if (a > 0) { high *= a; width *= a; Count(); } else if (a < 0) { high /= -a; width /= -a; Count(); } } //void KShape::Shift(double dx, double dy) //{ // Shift(dx, dy, centre); // Count(); //} void KShape::Shift(double dx, double dy, KPoint& A_) // dx, dy { A_.x += dx; A_.y += dy; } void KShape::MoveTo(KPoint& B_) { MoveTo(centre, B_); // Move centre to _B Count(); // } void KShape::MoveTo(KPoint& A_, KPoint& B_) // B { A_.x = B_.x; A_.y = B_.y; } void KShape::Rotate(KPoint& A_, KPoint const& centre_, double angle_) //rotate A_ about B_ by an angle = angle_ { double x = A_.x, y = A_.y, x0 = centre.x, y0 = centre.y; double sn, cs; if ((int)angle_ % 270 == 0) { sn = -1; cs = 0; } else if ((int)angle_ % 90 == 0 && (int)angle_ % 180 != 0) { sn = 1; cs = 0; } else if ((int)angle_ % 180 == 0 && (int)angle_ % 360 != 0) { sn = 0; cs = -1; } else if ((int)angle_ % 360 == 0) { sn = 0; cs = 1; } else if ((int)angle_ % 360 == 60) { sn = sqrt(3) / 2; cs = 0.5; } else if ((int)angle_ % 360 == 30) { cs = sqrt(3) / 2; sn = 0.5; } else { angle_ *= rad; sn = sin(angle_); cs = cos(angle_); } double out_x = x0 + ((x - x0) * cs - (y - y0) * sn); double out_y = y0 + ((x - x0) * sn + (y - y0) * cs); A_.x = out_x; A_.y = out_y; }
true
2cbe9b32a8e893c3511164efe4ccb7ee70766777
C++
summerHearts/AlgorithmPro
/算法时空/图论/Graph-Representation/Component.h
UTF-8
1,244
2.859375
3
[ "Apache-2.0" ]
permissive
// // Created by 佐毅 on 2018/3/18. // Copyright © 2018年 dfjr. All rights reserved. // #include <iostream> #include <cassert> using namespace std; template <typename Graph> class Component{ private: Graph &G; bool* visited; int ccount = 0; int *id; void dfs( int v ){ visited[v] = true; id[v] = ccount; typename Graph::adjIterator adj(G,v); for( int i = adj.begin() ; !adj.end() ; i = adj.next() ) if( !visited[i] ) dfs(i); } public: Component(Graph &graph):G(graph){ visited = new bool[G.V()]; id = new int[G.V()]; for( int i = 0 ; i < G.V() ; i ++ ){ visited[i] = false; id[i] = -1; } ccount = 0; for( int i = 0 ; i < G.V() ; i ++ ) if( !visited[i] ){ dfs(i); ccount += 1; } } ~Component(){ delete [] visited; delete [] id; } int count(){ return ccount; } bool isConnected( int v , int w ){ assert( v >= 0 && v < G.V() ); assert( w >= 0 && w < G.V() ); assert( id[v] != -1 && id[w] != -1 ); return id[v] == id[w]; } };
true
c5abf3686104d455b9cfbd6397980d9e77c8f908
C++
irisu-inwl/programming_contest
/POJ/poj_1979.cpp
UTF-8
1,213
2.5625
3
[]
no_license
#include <iostream> #include <cstdio> #include <string> #include <algorithm> #include <string.h> using namespace std; #define MAX_N 20 int W; int H; char field[MAX_N][MAX_N]; int dx[4] = {1, 0, -1, 0}; int dy[4] = {0, 1, 0, -1}; int res; void dfs(int x, int y){ field[y][x] = '#'; res++; // cout << x << "," << y << "," << res << endl; for(int delta = 0; delta < 4; delta++){ int nx = x+dx[delta], ny = y+dy[delta]; // cout << "debug: n" << nx << "," << ny << "," << endl; if(0 <= nx && nx < W && 0 <= ny && ny < H && field[ny][nx] == '.') dfs(nx, ny); } } int main(){ while(scanf("%d %d", &W, &H)){ if(W == 0 && H == 0) break; // cout << "width:" << W << ",height:" << H << ",field input" << endl; for(int inp = 0; inp < H; inp++){ scanf("%s", field[inp]); } res = 0; for(int i = 0; i < H; i++){ for(int j = 0; j < W; j++){ if(field[i][j] == '@'){ // printf("find.\n"); dfs(j, i); printf("%d\n", res); } } } } return 0; }
true
3d9d0c9368ae7ce5b5c0b55341371c9be92c275f
C++
alexandraback/datacollection
/solutions_5708921029263360_0/C++/angel8878/2-c.cpp
UTF-8
1,937
2.890625
3
[]
no_license
#include<string> #include<iostream> #include<fstream> #include<math.h> #include<stdlib.h> using namespace std; int main(void) { ifstream file; file.open("C-small-attempt2.in"); ofstream output; output.open("result.out"); int caseNo; file >> caseNo; for (int c = 1; c <= caseNo; c++) { int j, p, s, k; file >> j >> p >> s >> k; int cc, ccc, cccc; output << "Case #" << c << ": "; //int max = j * p * s; if (s <= k) { output << j*p*s << "\n"; for (cc = 1; cc <= j; cc++) { for (ccc = 1; ccc <= p; ccc++) { for (cccc = 1; cccc <= s; cccc++) { output << cc << " " << ccc << " " << cccc << "\n"; } } } } else if (p <= k) { output << j*p*k << "\n"; for (cc = 1; cc <= j; cc++) { for (ccc = 1; ccc <= p; ccc++) { for (cccc = 1; cccc <= k; cccc++) { output << cc << " " << ccc << " " << cccc << "\n"; } } } } else if (j <= k) { if ((p-k)*k > (p-k)*(s-k)) output << j*k*k + (p - k)*(s-k) << "\n"; else output << j*k*k + (p - k)*k << "\n"; for (cc = 1; cc <= j; cc++) { for (ccc = 1; ccc <= k; ccc++) { for (cccc = 1; cccc <= k; cccc++) { output << cc << " " << ccc << " " << cccc << "\n"; } } int count = 1; for (ccc = k + 1; ccc <= p; ccc++) { for (cccc = ccc; cccc <= s; cccc++) { output << cc << " " << ccc << " " << cccc << "\n"; count++; if (count > k) break; } } } } else { output << j*p << "\n"; int roll = 0; for (cc = 1; cc <= j; cc++) { for (ccc = 1; ccc <= p; ccc++) { if (roll + ccc <= s) output << cc << " " << ccc << " " << roll + ccc << "\n"; else output << cc << " " << ccc << " " << roll + ccc - s << "\n"; } roll++; } } } }
true
50fe4a5e67f2da6c8e389b0ac6ef0c1f8811a34b
C++
csalvaggio/rit
/imgs/apps/key_encrypt/key_encrypt.cpp
UTF-8
847
3
3
[]
no_license
#include <iostream> #include <string> #include "imgs/ipcv/key_encryption/KeyEncryption.h" using namespace std; int main() { string key = "buffalo"; string str = "This is a test of the key encryption system"; // string key = "imgs"; // string str = "Hello World!!!"; // string key = "Salvaggio"; // string str = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; auto encrypted_str = ipcv::KeyEncrypt(key, str); auto decrypted_str = ipcv::KeyDecrypt(key, encrypted_str); cout << "Encryption Key: " << endl << key << endl; cout << endl; cout << "Original String: " << endl << str << endl; cout << endl; cout << "Encrypted String: " << endl << encrypted_str << endl; cout << endl; cout << "Decrypted String: " << endl << decrypted_str << endl; cout << endl; }
true
d3da2a13c3938df38e5ad90df76da38903285162
C++
angstyloop/MyProjects
/CSCI382/c++/Random.cpp
UTF-8
1,730
4.09375
4
[]
no_license
/* Some practice with generating random numbers in c++ */ /* I added a function Shuffle() that randomizes a list by swapping each element an element at a random index. */ #include <iostream> #include <random> using namespace std; // we'll need a Swap() function template <class T> void Swap(vector<T> &A, int i, int j) { T c = A[i]; A[i] = A[j]; A[j] = c; } template <class T> void Shuffle(vector<T> &A) { // generate a distribution of random indices random_device seed; mt19937 generator(seed()); uniform_int_distribution<int> distribution(0,A.size()-1); // swap every element in the list with a randomly selected element for (int i=0; i<A.size(); i++) { Swap(A, i, distribution(generator)); } } // Shuffle some arguments around from the command line int main(int argc, char **argv) { // Get the arguments from the command line into an array of strings. vector<string> A(argv+1, argv+argc); // Shuffle and print the shuffled arguments. Shuffle(A); for (auto x: A) cout << x << " "; cout << endl; return 0; } // This is just an example I found online for how to generate random numbers in c++. // There are three components: the seed, the generator, and the distribution. // The generator takes a seed, and the distribution takes the generator. /* int main() { //Random seed random_device rd; //Initialize Mersenne Twister pseudo-random number generator mt19937 gen(rd()); // Generate pseudo-random numbers // uniformly distributed in range (1,100) uniform_int_distribution<int> dis(1,2); for (int i=0; i<10; i++) { //int randomX = dis(gen); cout << dis(gen) << endl; } } */
true
e9286871a62a60189ba3424c05f3a9c27ec423a3
C++
kyun1016/2019.04.30-
/Even Digits(string add, stirng min, string min).cpp
UHC
3,607
3.359375
3
[]
no_license
//////https://code.google.com/codejam/contest/9234486/dashboard(ڵ ó) // // // //#include<iostream> //#include<string> //#include<algorithm> // //using namespace std; // //string Min(string a, string b) { // if (a.size() < b.size()) // return a; // else if (b.size() < a.size()) // return b; // else // for (int i = 0; i < a.size(); i++) { // if (a[i] != b[i]) // return a[i] < b[i] ? a : b; // } // return a; //} // // // //string string_add(const string num1, const string num2) { // long long sum = 0; // //num copy Ͽ. // string copy1(num1), copy2(num2); // string ret; // // //copy1, copy2, sum Ѵ. // while (!copy1.empty() || !copy2.empty() || sum) { // if (!copy1.empty()) { // //copy1 ִ ڴ char· ǾǷ(ascii) '0' ־ ȭ ־. // sum += copy1.back() - '0'; // copy1.pop_back(); // } // if (!copy2.empty()) { // sum += copy2.back() - '0'; // copy2.pop_back(); // } // //sum ڸ ret ־.(̶, char Ƿ ٽ '0' ش) // ret.push_back((sum % 10) + '0'); // sum /= 10; // } // // ԷµǾǷ, reverseԼ Ȱ ڿ ´. // reverse(ret.begin(), ret.end()); // return ret; //} // ////num1 > num2 Է. //string string_sub(const string num1, const string num2) { // long long sum = 0; // //num copy Ͽ. // string copy1(num1), copy2(num2); // string ret; // int flag = 0; // // // num2 '0'̶ 0 Ų. // if (num2[0] == '0') { // copy2.erase(0, 1); // } // // //copy1, copy2, sum Ѵ. // while (!copy1.empty() || !copy2.empty() || sum) { // if (!copy1.empty()) { // //copy1 ִ ڴ char· ǾǷ(ascii) '0' ־ ȭ ־. // sum += copy1.back() - '0'; // if (flag) { // flag = 0; // sum -= 1; // } // copy1.pop_back(); // } // if (!copy2.empty()) { // sum -= copy2.back() - '0'; // copy2.pop_back(); // } // //sum ڸ ret ־.(̶, char Ƿ ٽ '0' ش) // if (sum < 0) { // sum += 10; // ret.push_back((sum % 10) + '0'); // sum /= 10; // // // flag = 1; // // } // else { // ret.push_back((sum % 10) + '0'); // sum /= 10; // } // // } // // ԷµǾǷ, reverseԼ Ȱ ڿ ´. // reverse(ret.begin(), ret.end()); // // while (ret[0] == '0') { // ret.erase(0, 1); // } // if (ret.size() == 0) { // ret.push_back('0'); // } // return ret; //} // //string calculator(string N) { // string up(N), down(N); // string ret1,ret2; // int size = N.length(); // for (int i = 0; i < size; i++) { // if (N[i] % 2 == 1) { // up[i] = N[i] + 1; // for (int j = i+1; j < size; j++) { // up[j] = '0'; // } // down[i] = N[i] - 1; // for (int j = i+1; j < size; j++) { // down[j] = '8'; // } // break; // } // } // // ret1 = string_sub(up, N); // ret2 = string_sub(N, down); // string MIN; // MIN = Min(ret1, ret2); // // return MIN; //} // //int main() { // int T; // string N; // cin >> T; // for (int i = 1; i <= T; i++) { // cin >> N; // cout << "Case #" << i << ": " << calculator(N) << endl; // } //}
true
832e4321158e2f7c59bb07f8419622e37f971851
C++
huangk4/web-security
/WebProtect/C_virus.cpp
GB18030
2,836
2.65625
3
[]
no_license
#include "stdafx.h" //洢ļ· vector<string> filepath; extern char g_virus_check_ip[MAX_PATH];//ƼIP extern int g_virus_check_port;//Ƽ˿ /*---------------------------- * : ݹļУҵаļ *---------------------------- * : find * : public * * : lpPath [in] ļĿ¼ * : fileList [in] ļƵʽ洢ļ */ void find(char* lpPath, std::vector<std::string> &fileList) { char szFind[MAX_PATH]; WIN32_FIND_DATAA FindFileData; strcpy(szFind, lpPath); strcat(szFind, "\\*.*"); HANDLE hFind = ::FindFirstFileA(szFind, &FindFileData); if (INVALID_HANDLE_VALUE == hFind) return; string path = lpPath;//ļ· while (true) { if (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if (FindFileData.cFileName[0] != '.') { char szFile[MAX_PATH]; strcpy(szFile, lpPath); strcat(szFile, "\\"); strcat(szFile, (char*)(FindFileData.cFileName)); find(szFile, fileList);//ݹ } } else { path = lpPath; path = path + "\\" + FindFileData.cFileName; fileList.push_back(FindFileData.cFileName); filepath.push_back(path); } if (!FindNextFileA(hFind, &FindFileData)) break; } FindClose(hFind); } C_Virus::C_Virus(string hashpath) { m_vhashpath = hashpath; } bool C_Virus::single_scan(char *file) { char sha[256]; FileSHA256(file, sha); fstream hashfile(m_vhashpath.c_str(), ios::in); if (!hashfile) return false; char viruhash[256]; while (!hashfile.eof()) { hashfile >> viruhash; if (strcmp(sha, viruhash) == 0)//ƥhashֵ { savelog(file); return true; } } return false; } bool *C_Virus::multi_scan(char *path,int &filenums) { vector<string> fileList;//һŽļƵ find(path, fileList); bool *check = new bool[filepath.size()];//洢 for (int i = 0; i < filepath.size(); i++) { char *temp_buf = new char[strlen(filepath[i].c_str()) + 1]; strcpy(temp_buf, filepath[i].c_str()); if (single_scan(temp_buf) == true) check[i] = true; else check[i] = false; } filenums = filepath.size(); return check; } bool C_Virus::cloud_scan(char *file) { CTCP client(2,2); SOCKET socket = client.InitSocket(SOCK_NOBIND,g_virus_check_ip ,g_virus_check_port ); if (socket == INVALID_SOCKET) { MessageBox(NULL, L"socketʼ", L"", MB_OK); exit(0); } char sha[256]; FileSHA256(file, sha); fstream hashfile(m_vhashpath.c_str(), ios::in); if (!hashfile) return false; char viruhash[256]; char result[4]; client.mysend(socket, sha, 256); client.myrecv(socket, result, 4, 0); if (strcmp(result, "yes") == 0) return true; return false; }
true
00a9da9064f81f8c1968a934a66ab2093f9b3b42
C++
denis9570/tsi_tasks
/fifth_task/countTriplets.cpp
UTF-8
786
3.34375
3
[]
no_license
#include <iostream> using namespace std; // this code is distributed under the GNU GPL license int main() { /* Вводится натуральное число. Определить количество цифр 3 в нем. Эта программа написана для Рижского института транспорта и связи студентом Денисом Орловом(А.К)*/ int a; cout << "Please enter random number" << endl; cin >> a; int count_of_three = 0; while(a > 0) { if (a % 10 == 3) { ++count_of_three; } a = a / 10; } cout << "This is the count of 3 in the number entered by you:" << count_of_three << endl; return 0; }
true
dfdde48d776b9054d62466d81ef19b995a3e097f
C++
MuhammadNajat/Sorting-Algorithms
/1727_SELECTION_SORT.cpp
UTF-8
613
2.53125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int a[1000000]; int main() { int i, j, n; //Read until the end of file reached while(scanf("%d", &n) != EOF) { for(i=0; i<n; i++) { scanf("%d", &a[i]); } for(i=0; i<n; i++) { int minInd = i; for(j=i; j<n; j++) { if(a[j] < a[minInd]) { minInd = j; } } swap(a[i], a[minInd]); } for(i=0; i<n; i++) { i < n-1 ? printf("%d ", a[i]) : printf("%d\n", a[i]); } } return 0; }
true
5a6c10b84d17f4eeddff3fa0efb1332664c67b68
C++
SweetySnail/Project_TREE
/Project_TREE/project2/AVLTree.cpp
UTF-8
5,985
3.28125
3
[]
no_license
#include "AVLTree.h" bool AVLTree::Insert(Gamedata* pGame) { // make new Node to insert and insert data AVLNode* New_Node = new AVLNode; New_Node->setGD(pGame); if (root == NULL) // if root has nothing { root = New_Node; // set New_Node to root return true; } else // if root has anything { AVLNode* a = root; // to change BF(change BF's position) AVLNode* pa = NULL; // a's parent Node AVLNode* p = root; // to move Node(insert Node's position) AVLNode* pp = NULL; // p's parent Node AVLNode* rootSub = NULL; // Subtree's root while (p != NULL) // move p to leaf Node { if (p->getBF() != 0) // if p is balanced tree { a = p; // set a pa = pp; // set pa } if (p->getGD()->getGameid() > pGame->getGameid()) // if p has to go left { pp = p; // set pp p = p->getLeft(); // move p } else if (p->getGD()->getGameid() < pGame->getGameid()) // if p has to go right { pp = p; // set pp p = p->getRight(); // move p } else // if p is duplication return false; } // set New_Node if (pp->getGD()->getGameid() > pGame->getGameid()) pp->setLeft(New_Node); else pp->setRight(New_Node); int d; // temporary Balance Factor AVLNode* b; // a's child Node AVLNode* c; // a's child Node if (a->getGD()->getGameid() > pGame->getGameid()) // if p has to go left { b = p = a->getLeft(); d = 1; } else // if p has to go right { b = p = a->getRight(); d = -1; } // set Balance Factor while (p != New_Node) { if (p->getGD()->getGameid() > pGame->getGameid()) // if p is bigger than pGame { p->setBF(1); p = p->getLeft(); } else // if p is smaller than pGame { p->setBF(-1); p = p->getRight(); } } if (a->getBF() == 0 || a->getBF() + d == 0) // if tree is balanced { a->setBF(a->getBF() + d); return true; } else // if tree is unbalanced { // if tree has left unbalanced if (d == 1) { if (b->getBF() == 1) // LL unbalanced { a->setLeft(b->getRight()); b->setRight(a); a->setBF(0); b->setBF(0); rootSub = b; } else // LR unbalanced { c = b->getRight(); b->setRight(c->getLeft()); a->setLeft(c->getRight()); c->setLeft(b); c->setRight(a); switch (c->getBF()) // set Balance Factor to use c's Balance Factor { case 0: // if it is balanced a->setBF(0); b->setBF(0); break; case 1: // if it is unbalanced a->setBF(-1); b->setBF(0); break; case -1: // if it is unbalanced a->setBF(0); b->setBF(1); break; } c->setBF(0); rootSub = c; } } else // if tree has right unbalanced { if (b->getBF() == -1) // RR unbalanced { a->setRight(b->getLeft()); b->setLeft(a); a->setBF(0); b->setBF(0); rootSub = b; } else // RL unbalanced { c = b->getLeft(); a->setRight(c->getLeft()); b->setLeft(c->getRight()); c->setLeft(a); c->setRight(b); switch (c->getBF()) // set Balance Factor to use c's Balance Factor { case 0: // if it is left unbalanced a->setBF(0); b->setBF(0); break; case 1: // if it is unbalanced a->setBF(0); b->setBF(-1); break; case -1: // if it is unbalanced a->setBF(1); b->setBF(0); break; } c->setBF(0); rootSub = c; } } } if (pa == NULL) // if a was root root = rootSub; else if (a == pa->getLeft()) // if a was pa's left child pa->setLeft(rootSub); else // if a was pa's right child pa->setRight(rootSub); return true; } return true; // no duplication } void AVLTree::Print() { // print Inorder traversal stack<AVLNode*> q; // make stack AVLNode* current_Node = root; ofstream write("log.txt", ios::app); while (1) { while (current_Node != NULL) // move most left child and push each nodes { q.push(current_Node); current_Node = current_Node->getLeft(); } if (q.empty()) // if stack is empty break; current_Node = q.top(); // set current_Node's position cout << current_Node->getGD()->getGameid() << " " << current_Node->getGD()->getDuration() << " " << current_Node->getGD()->getWinner() << " "; for (int i = 0; i < 5; i++) cout << current_Node->getGD()->getTeamA()[i] << " "; for (int i = 0; i < 4; i++) cout << current_Node->getGD()->getTeamB()[i] << " "; cout << current_Node->getGD()->getTeamB()[4] << endl; write << current_Node->getGD()->getGameid() << " " << current_Node->getGD()->getDuration() << " " << current_Node->getGD()->getWinner() << " "; for (int i = 0; i < 5; i++) write << current_Node->getGD()->getTeamA()[i] << " "; for (int i = 0; i < 4; i++) write << current_Node->getGD()->getTeamB()[i] << " "; write << current_Node->getGD()->getTeamB()[4] << endl; q.pop(); // after write output, pop that node current_Node = current_Node->getRight(); // if current_Node has right child, go to right child } write.close(); } Gamedata* AVLTree::Search(int id) { AVLNode* Search_Node = root; // move Search_Node to search id while (Search_Node != NULL) { if (Search_Node->getGD()->getGameid() > id) // if Search_Node has bigger than id Search_Node = Search_Node->getLeft(); else if (Search_Node->getGD()->getGameid() < id) // if Search_Node has smaller than id Search_Node = Search_Node->getRight(); else if (Search_Node->getGD()->getGameid() == id) // if Search_Node has same id return Search_Node->getGD(); } if (Search_Node == NULL) // if fail to search id return NULL; else // if success to search id return Search_Node->getGD(); }
true
f0fd8cfbfc8f9851ca3b69b6fbb1c17267d88713
C++
alexandraback/datacollection
/solutions_5766201229705216_0/C++/kokocrunch/tree.cpp
UTF-8
1,425
2.515625
3
[]
no_license
#include<iostream> #include<algorithm> #include<vector> #include<utility> using namespace std; typedef pair<int,int> ii; #define INF 1000000000 int p[1010]; vector<int> raw[1010]; vector<int> children[1010]; int ch[1010]; int states[1010]; int T,N; void root(int u){ for(int i = 0; i < raw[u].size(); i++){ int v = raw[u][i]; if(v != p[u]){ p[v] = u; children[u].push_back(v); root(v); ch[u] += ch[v]; } } //cout << "children of " << u <<": " << ch[u] << endl; } int dp(int u){ if(children[u].size() == 0 ) return 0; if(children[u].size() == 1) return ch[children[u][0]]; int low1 = INF, low2 = INF; for(int i = 0; i < children[u].size(); i++){ int v = children[u][i]; int cur = dp(v) - ch[v]; if(low1 > cur){ low2 = low1; low1 = cur; } else if(low2 > cur){ low2 = cur; } } return ch[u] + low1 + low2 - 1; } int main(){ int i,j,k,t; cin >> T; for(t = 1; t<=T;t++){ cout << "Case #" << t << ": "; cin >> N; //init for(i = 0; i < N + 1; i++ )raw[i].clear(); for(i = 0; i < N -1; i++ ){ int a,b; cin >> a >> b; raw[a].push_back(b); raw[b].push_back(a); } int best = INF; for(i = 1; i <= N; i++){ fill(p, p + N + 1, -1); fill(ch, ch + N + 1, 1); for(j = 0; j < N + 1; j++ )children[j].clear(); //cout<< "rooting " << i << endl; root(i); best = min(best, dp(i)); } cout << best <<endl; } }
true
361dee3427adcaa6d2a2ad7460fd56fc416c148e
C++
nickbiffis/test
/Test.cpp
UTF-8
15,322
3.03125
3
[]
no_license
#include <iostream> #include <cstring> #include <fstream> #include "InstructionMemory.h" #include "ProgramCounter.h" #include <string> #include <sstream> #include <map> #include "DataMemory.h" #include "ControlUnit.h" #include "ALU.h" #include "Multiplexor.h" #include "Instruction.h" using namespace std; class Tester{ public: Tester(){ } }; int main () { //writting code to read the configuration file //will read contents of the file and save information set up //to be used by the program. //This should be changed to take command line argument (I think?) string configFile = "input.config"; string programInputFile; string dataMemoryFile; string registerFile; string outputMode; string outputFile; bool debugMode; bool printMemoryContents; bool writeToFile; ifstream infile1; //opens file then make sure it was successful infile1.open(configFile); if (!infile1.is_open()) { cerr << "An error has occured when opening the file"; exit(1); } //loop to run once for each config for(int i = 0; i < 8; i++) { string configInput; infile1 >> configInput; string configResult; int pointerToEquals = 0; //loops through string until it finds equals //sets pointer to j for(int j = 0; j < configInput.length(); j++) { if(configInput.at(j) == '=') { pointerToEquals = j+1; break; } } //gets the part of the input after the equals sign configResult = configInput.substr(pointerToEquals); //this block of code adds the values from the config file to //the appropriate variable. switch(i) { case 0 : programInputFile = configResult; break; case 1 : dataMemoryFile = configResult; break; case 2 : registerFile = configResult; break; case 3 : outputMode = configResult; break; case 4 : if(configResult.at(0) == 'f') { debugMode = false; } else { debugMode = true; } break; case 5 : if(configResult.at(0) == 'f') { printMemoryContents = false; } else { printMemoryContents = true; } break; case 6 : outputFile = configResult; break; case 7 : if(configResult.at(0) == 'f') { writeToFile = false; } else { writeToFile = true; } break; } } infile1.close(); /// Writting code to read the Data memory file. // will read data and build a 2d vector that can be used // to construct memory contents. //int used to store # of instructions, must be <= 100 int numOfMemcells = 0; DataMemory* dm = new DataMemory (dataMemoryFile); string memdata = dm->getdata("10000000"); std::cout<<memdata<<std::endl; dm->dmemPrint(); //map<string,string>::iterator it = dm->mem.begin(); //it++; //while(it != dm->mem.end()) //{ // std::cout<< it->first << ":" << it->second <<endl; //it++; //} dm->dmemPrintFinal("output.mem"); // //builds array to store registers string arrayOfRegisters[32][2]; int numOfRegisters = 0; // ifstream infile3; infile3.open(registerFile); if (!infile3.is_open()) { cerr << "An error has occured when opening the file"; exit(1); } // Loop should run until eof(). while(infile3.good()) { //creates string and saves each line to input string input; infile3 >> input; int equalsPtr = 0; //gets location of the = for(int k = 0; k < input.length(); k++) { if(input.at(k) == '=') { equalsPtr = k; break; } } arrayOfRegisters[numOfRegisters][0] = input.substr(0,equalsPtr); //puts instruction in arrayOfRegisters[numOfRegisters][1] = input.substr(equalsPtr + 1,8); //increments number of instructions numOfRegisters++; } infile3.close(); // RegisterFile registerFile(); // //For loops runs so the values in arrayOfRegisters get // //stored into the Register file // for(int i = 0; i < numOfRegisters; i++) // { // registerFile.writeReg(arrayOfRegisters[i][0], arrayOfRegisters[i][1]) // } // } //------------------------------------------------------------------// //------------------------------------------------------------------// //------------------------------------------------------------------// //------------------------------------------------------------------// //------------------------------------------------------------------// //This is an example of how to get Instructions from the Instruction from the InstructionMemory //In this example I'm getting the in InstructionMemory* im = new InstructionMemory (programInputFile); Instruction i = im->getInstruction("4000008"); string s = i.getString(); cout<<s<<endl; // std::cout<<std::endl; /* @Won't be needing this Iterates through instructions, and sends them to the Instruction memory. The below code is from the lab4 parser class, and will find the encodings for a given programInputFile found above. Once the other files are added to the folder it should run and collect instructions in binary to be used in the program. */ // ASMParser *parser; // parser = new ASMParser(programInputFile); // if(parser->isFormatCorrect() == false){ // cerr << "Format of program input file is incorrect " << endl; // exit(1); // } // Instruction i; // i = parser->getNextInstruction(); // int instructionCounter = 0; // while( i.getOpcode() != UNDEFINED || instructionCounter <= 100){ // //Puts values into array, prints them for testing purposes. // cout << i.getString() << endl; // instructionArray[instructionCounter][1]; // //cout << i.getEncoding() << endl; // i = parser->getNextInstruction(); // } // delete parser; //Code below will begin using imput to simulate a processor. First all objects needed // for the execution will be created. //Sets first address at the start and creates Program Counter Object string firstAddress = "4000000"; ProgramCounter pc(firstAddress); //Creates IM using the array built above. // InstructionMemory im(instructionArray); //We don't create another InstructionMemory, I created it above and renamed it to be im to work with the rest of your code //Creates controlunit object. ControlUnit* control = new ControlUnit (); //build 5 Multiplexors Multiplexor* mux1 = new Multiplexor (); Multiplexor* mux2 = new Multiplexor (); Multiplexor* mux3 = new Multiplexor (); Multiplexor* mux4 = new Multiplexor (); Multiplexor* mux5 = new Multiplexor (); ALU* ALU1 = new ALU();// only ADD ALU* ALU2 = new ALU();// ADD and ALU Result ALU* ALU3 = new ALU();// ALU and ALU Result OpcodeTable opt = OpcodeTable(); // SignExtend signExtend(); // ShiftLeftTwo SL1(); // ShiftLeftTwo SL2(); // DataMem dataMemory(); // Loop should run until end of program //while(false) //{ //If the user chose to use single step mode, this code asks the user to //press y to continue, will continuously run until user enters y if(outputMode == "single_step"){ while(true) { string x; cout << "Please enter y to move to the next step in the Program!" << endl; cin >> x; if(x == "y") { break; } } } //FETCH //Retrives address from the instruction memory as a string of 1s/0s. string addr = pc.getCurrentAddress(); Instruction inst = im->getInstruction(addr); if(debugMode) { cout << "The address being run in this iteration: " << addr << endl; cout << "The instruction referenced by the above address: " << inst.getString() << endl; } //Adds 4 to current address and stores the result. ALU1->setInput_1("10"); ALU1->setInput_2("10"); ALU1->setOperation("add"); ALU1->performOperation(); string add4ToAddress = ALU1->getResult(); if(debugMode) { cout << "Result of adding 4 to the address: " << add4ToAddress << endl; } //retrives opcode from instruction Opcode op= opt.getOpcode(inst.getString()); //sets values to false to reset control unit, then calls method //to set control values with opcode. control->setToZero(); //resets values in control unit control->setValues(opt.getOpcodeField(op)); mux1->setFlow(control->getRegDest()); mux2->setFlow(control->getAluSrc()); mux3->setFlow(control->getmemToReg()); mux4->setFlow(control->getJump()); // mux 5 is set by a combination of branch and the result of ALU //always goes to read regester1 Register reg1 = inst.getRS(); //goes to read register 2 and mux1 Register reg2 = inst.getRT(); //goes to mux1 Register reg3 = inst.getRD(); //gets last15 didgets of instruction int immediate = inst.getImmediate(); //goes to ALU control // string functCode = instruction.substr(27, 5); // //gets what would be instruction for j types // string jInstruction = instruction.substr(6, 26); if(debugMode) { cout << "Printing: reg1, reg2, reg3, immediate, functCode, j addr" << endl; cout << reg1 << " " << reg2 << " " << reg3 << " " << immediate<<endl; // << " " << functCode << " " << jInstruction << endl; } //} // //Shifts the instruction to the left // string jInstSl2 = SL1.Shift(jInstruction); // mux4.setFirstInput(jInstSl2); // must wait for result of Mux5 // //gets values from reg1 and reg 2 // string valAtReg1 = readReg(reg1); // string valAtReg2 = readReg(reg2); // //Sends reg2 and reg3 to mux, based on control // mux1.setFirstInput(reg2); // mux1.setSecondInput(reg3); // //write register gets value from mux1 // string writeRegister = mux1.mux(); // //test for mux1 // if(debugMode) // { // cout << "Value in write register: " << writeRegister << endl; // } // string extended = signExtend.Extend(last15Digits); // mux2.setFirstInput(reg2); // mux2.setSecondInput(extended); // //calls second mux to determine second input for alu // string aluInput = mux2.mux(); // if(debugMode) // { // cout << "Second input for ALU3: " << aluInput << endl; // } // //The following code acts as the ALU control for ALU3 // string alu3Result; // if(control.getAluOp1() == 1 || control.getAluOp0() == 1) // { // if(control.getAluOp1() == 1) // { // //SLT, ADD, SUB, SLT // if(functCode == "100000") // { // //Add // ALU3.add(reg1, aluInput) // ALU3.preformOperation(); // alu3Result = ALU3.getResult(); // break; // } // if(functCode == "100010") // { // //Subtract // ALU3.sub(reg1, aluInput) // ALU3.preformOperation(); // alu3Result = ALU3.getResult(); // break; // } // if(functCode == "101010") // { // //SLT instruction, not yet implemented in ALU // } // //Result gets "equal" or "not equal" // if(control.getAluOp0() == 1) // { // ALU3.compare(reg1, aluInput); // ALU3.preformOperation(); // alu3Result = ALU3.getResult(); // } // } else { // //runs for lw and sw // ALU3.add(reg1, aluInput) // ALU3.preformOperation(); // alu3Result = ALU3.getResult(); // break; // } // if(debugMode) // { // cout << "Result from ALU3: " << alu3Result << endl; // } // if(controlunit.getBranch() == 1 && alu3Result == "equal") // { // // if this runs it is a branch instruction AND the branch // // condition passed. Basically the AND in the data path. // mux5.setFlow(control.getBranch()); // } // mux3.setFirstInput(alu3Result); // if(control.getMemRead() == 1) // { // bitset<32> resultInBits (alu3Result); // bitset<32> dataFromMem; // dataFromMem = dataMemory.readMem(); // mux3.setSecondInput(dataFromMem.to_string()); // if(debugMode) // { // cout << "Value read from memory: " << dataFromMem.to_string() << endl; // } // } // //checks to see if it is writting to a register from mux3. // if(control.getRegWrite()) // { // string writeData = mux3.mux(); // // remeber string writeRegister holds in the reg // // code below should write the given value to the register // if(debugMode) // { // cout << "Value being written to mem " << writeData << endl; // } // registerFile.writeReg(writeReg, writeData); // } // //Shifts the previously exstended address by 2 bits(needed for b and j) // string instructionShiftedLeft = sl2.Shift(extended); // //Add this value to current PC value(This doesnt make sense to me...) // ALU2.add(instructionShiftedLeft, add4ToAddress); // ALU2.preformOperation(); // resultOfAlu2 = ALU2.getResult(); // if(debugMode) // { // cout << "Result of ALU2: " << resultOfAlu2 << endl; // } // mux5.setFirstInput(add4ToAddress); // mux5.setSecondInput(resultOfAlu2); // string resultOfMux5 = mux5.mux(); // if(debugMode) // { // cout << "Result of Mux5: " << resultOfMux5 << endl; // } // mux4.setSecondInput(resultOfMux5); // string resultOfMux4 = mux4.mux(); // if(debugMode) // { // cout << "Address being sentt to PC: " << resultOfMux4 << endl; // } // //Updates program counter with correct address // programCounter.moveAddress(resultOfMux5); // } //////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////// //Testing stuff // stringstream ss (s4); // for(int i=0;i<10;i++){ // int x; // ss>>hex>>x; // ss<<hex<<x; // x=x+4; // string s5 =ss.str(); // std::cout<<hex<<x<<std::endl; // std::cout<<mem.at(s5)<<std::endl; // } // string s4 ="4000000"; // Tester t ; // for(int i=0;i<9;i++){ // int x = t.hextoint(s4); // x=x+4; // s4 =t.inttohex(x); // std::cout<<instructions.at(s4)<<endl; // } return 0; }
true
ab7c3a3b01103156fa79e33a17c30eaf2764bfd8
C++
diptadas/acm-resources
/uva-solutions/191.cpp
UTF-8
2,439
2.734375
3
[]
no_license
//Dipta Das CUET CSE-11 #include <cstdio> #include <cstring> #include <cmath> #include <iostream> #include <algorithm> #include <sstream> #include <string> #include <vector> #include <stack> #include <queue> #include <map> #define LL long long #define Pi acos(-1.0) #define EPS 1e-7 #define Mod 100000007 #define Inf 100000000 #define mset(a, s) memset(a, s, sizeof (a)) using namespace std; //vector templete struct p //point; { double x,y; p(double x=0,double y=0) { this->x=x; this->y=y; } }; p mv(p a,p b) //make vector { return p(b.x-a.x,b.y-a.y); } double dp(p a,p b) //dot product { return a.x*b.x+a.y*b.y; } double cp(p a,p b) //cross product { return a.x*b.y-a.y*b.x; } p vr(p v,double an) //vector rotation an radious angle { return p(v.x*cos(an)-v.y*sin(an),v.x*sin(an)+v.y*cos(an)); } p add(p a,p b) //two vector add { return p(a.x+b.x,a.y+b.y); } double value(p a) //value of a vector { return sqrt(dp(a,a)); } p lv(p a,double l) //l th time of a vector { double v=value(a); return p((a.x*l)/v,(a.y*l)/v); } p pointseg(p a,p b,p c) //min distance point of a,b segment from point c { if(dp(mv(a,b),mv(a,c))<0) return a; if(dp(mv(b,a),mv(b,c))<0) return b; double l=(dp(mv(a,b),mv(a,c)))/value(mv(a,b)); return add(a,lv(mv(a,b),l)); } double dis(p a,p b) //distance of two point { return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y)); } bool onseg(p a,p b,p c) //if a,b,c colinear check if c lies on a,b segment { return (c.x>=min(a.x,b.x) && c.x<=max(a.x,b.x) && c.y>=min(a.y,b.y) && c.y<=max(a.y,b.y)); } bool inseg(p a,p b,p c,p d) //check if a,b and c,d segment intersect { double d1,d2,d3,d4; d1=cp(mv(a,b),mv(a,c)); d2=cp(mv(a,b),mv(a,d)); d3=cp(mv(c,d),mv(c,a)); d4=cp(mv(c,d),mv(c,b)); if(d1*d2<0 && d3*d4<0) return true; if(d1==0 && onseg(a,b,c)) return true; if(d2==0 && onseg(a,b,d)) return true; if(d3==0 && onseg(c,d,a)) return true; if(d4==0 && onseg(c,d,b)) return true; return false; } //end of vector templete int main() { int tc; cin>>tc; while(tc--) { p a,b,c,d,e,f; cin>>e.x>>e.y>>f.x>>f.y>>a.x>>a.y>>c.x>>c.y; b.x=a.x,b.y=c.y,d.x=c.x,d.y=a.y; if(inseg(a,b,e,f) || inseg(b,c,e,f) || inseg(c,d,e,f) || inseg(d,a,e,f) || onseg(a,c,e)) cout<<"T"<<endl; else cout<<"F"<<endl; } return 0; }
true
4757a57d429575d285258ba59294068db5f76c50
C++
gabsn/competitive-programming
/td5/test.cpp
UTF-8
222
2.5625
3
[]
no_license
include <algorithm> #include <iostream> #include <string> int main() { std::string hw( "Hello World" ); std::cout << hw << std::endl; std::reverse( hw.begin(), hw.end() ); std::cout << hw << std::endl; }
true
f51940f806cf04d9bacdcc8943cc878041e41fb2
C++
trongthanht3/baitapkithuatlaptrinhMTA
/b4.cpp
UTF-8
432
3.21875
3
[]
no_license
#include <iostream> #include <conio.h> using namespace std; void find_USCLN(int a, int b) { char t; while (a != b) { if (a > b) a = a - b; else if (a < b) b = b - a; } cout << "uscln: " << a << endl; cout << "Press any key to continue. Esc to escape\n"; } int main() { int a, b; char t; cout << "input: "; do { cin >> a >> b; find_USCLN(a, b); } while((t = getch()) != 27); }
true
619698c0e798df04a06bb054a181a8e4dad4586a
C++
HaoYang0123/LeetCode
/Check_If_It_Is_A_Straight_Line.cpp
UTF-8
526
2.953125
3
[]
no_license
//Leetcode 1232 class Solution { public: bool checkStraightLine(vector<vector<int>>& coordinates) { if(coordinates.size()<3) return true; for(int i=2;i<coordinates.size();i++) { int dy1=coordinates[i][1]-coordinates[i-1][1]; int dy0=coordinates[i-1][1]-coordinates[i-2][1]; int dx1=coordinates[i][0]-coordinates[i-1][0]; int dx0=coordinates[i-1][0]-coordinates[i-2][0]; if(dy1*dx0!=dy0*dx1) return false; } return true; } };
true
e4de36ab5a8373804fd71718f7ad86109ad1974e
C++
kr-MATAGI/ELGO_Client_QT
/elgo_control/JSON/Schema/ContentServerSchema.h
UTF-8
1,922
2.546875
3
[]
no_license
#ifndef CONTENTSERVERSCHEMA_H #define CONTENTSERVERSCHEMA_H // QT #include <QString> #include <QDateTime> namespace ContentSchema { /** @brief Server -> elgo_control */ enum Event { NONE_EVENT = 0, READY = 1, ACCESS = 2, RENAME = 3, // payload type : once, request SINGLE_PLAY = 4, PLAY_SCHEDULE = 5, POWER_SCHEDULE = 6, DISPLAY_ON = 7, DISPLAY_OFF = 8, SCREEN_CAPTURE = 9, SYSTEM_REBOOT = 10, CLEAR_PLAY_SCHEDULE = 11, CLEAR_POWER_SCHEDULE = 12, ERROR = 255 }; /** @brief */ enum PayloadType { NONE_TYPE = 0, ONCE = 1, REQUEST = 2, RESPONSE = 3, PROGRESS = 4 }; /** @brief */ struct Payload { Payload() : type(PayloadType::NONE_TYPE) , displayPower(false) { } QString src; QString dest; QString message; QString deviceName; QString url; QString path; QString scheduleId; PayloadType type; bool displayPower; }; /** @brief */ struct Summary { Summary() : event(Event::NONE_EVENT) { } Event event; Payload payload; }; } namespace ResourceJson { // resource /** @brief */ enum ResourceType { NONE_RSRC = 0, JS = 1, ICON = 2, DATA = 3, PAGE = 4, IMAGE = 5, VIDEO = 6, OBJECT = 7 }; const static QString ResourceTypeEnumToStr[] = { "NONE", "js", "icon", "data", "page", "image", "video", "object" }; /** @brief */ struct Resource { ResourceType type; QString name; QString url; int size; // unit : byte }; } #endif // CONTENTSERVERSCHEMA_H
true
623fa22915286f1d99b076e06350f93172bcb92e
C++
jtristao/Project-Euler
/e_084.cpp
UTF-8
3,188
2.71875
3
[]
no_license
#include <bits/stdc++.h> // MArkov chain using namespace std; typedef struct{ long prob_board[40] = {0}; void print(int n){ for(int i = 0; i < 40; i++){ if(i %10 == 0) printf("\n"); printf("%ld ", prob_board[i]); } printf("\n"); } } Board; typedef struct { unordered_set<int> places = {7, 22, 36}; vector<int> cards = {0, 10, 11, 24, 39, 5, -1, -1, -2, -3, 50, 50, 50, 50, 50, 50}; bool shuffle = false; void prepare_cards(){ if(this->shuffle == false){ random_shuffle(cards.begin(), cards.end()); this->shuffle = true; } } int pick_card(){ this->prepare_cards(); int card = cards[0]; cards.erase(cards.begin()); cards.push_back(card); return card; } void print_cards(){ for(int i = 0; i < (int)cards.size(); i++){ printf("%d ", cards[i]); } printf("\n"); } } Chance; typedef struct { unordered_set<int> places = {2, 17, 33}; vector<int> cards = {0, 10, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50}; bool shuffle = false; void prepare_cards(){ if(this->shuffle == false){ random_shuffle(cards.begin(), cards.end()); this->shuffle = true; } } int pick_card(){ this->prepare_cards(); int card = cards[0]; cards.erase(cards.begin()); cards.push_back(card); return card; } void print_cards(){ for(int i = 0; i < (int)cards.size(); i++){ printf("%d ", cards[i]); } printf("\n"); } } ComunityChest; bool sortf(const pair<int,long> &a, const pair<int,long> &b){ return (a.second > b.second); } int main(int argc, char *argv[]){ srandom(time(NULL)); Board b; ComunityChest cc; Chance ch; int iter_limit = 10000000, pos = 0, equal_dice = 0; int d1, d2, card; for(int i = 0; i < iter_limit; i++){ d1 = random()%4+1; d2 = random()%4+1; // printf("%d (%d)\n", pos, d1+d2); if(d1 == d2){ equal_dice += 1; }else{ equal_dice = 0; } if(equal_dice == 3){ pos = 10; // equal_dice = 0; }else{ pos = (pos + d1 + d2)%40; if(pos == 30) pos = 10; else if(ch.places.find(pos) != ch.places.end()){ card = ch.pick_card(); // printf("Chance: "); if(card < 40){ // Railway company if(card == -1){ // printf("Railway\n"); if(pos == 7){ //CH1 pos = 15; }else if(pos == 22){ // CH2 pos = 25; }else if(pos == 36){ // CH3 pos = 5; } }else if(card == -2){ // Utility company // printf("Utility\n"); if(pos == 7 || pos == 36){ //CH1 || CH3 pos = 12; }else if(pos == 22){ // CH2 pos = 28; } }else if(card == -3){ // printf("Go back\n"); pos -= 3; }else { pos = card; } }else{ // printf("Nothing\n"); } }else if(cc.places.find(pos) != cc.places.end()){ // printf("ComunityChest\n"); card = cc.pick_card(); if(card < 40){ pos = card; } } } b.prob_board[pos] += 1; } vector<pair<int, long>> probs; for(int i = 0; i < 40; i++){ probs.push_back({i, b.prob_board[i]}); } sort(probs.begin(), probs.end(), sortf); printf("String: "); for(int i = 0; i < 3; i++){ printf("%d", probs[i].first); } printf("\n"); return 0; }
true
871cd7ccb74d2b2e4250a5c3db0a137e73f27e5e
C++
jingsia/three1
/C++Save/Tmp/ProjectA/Core/GObject/GLocalObjectManager.h
UTF-8
1,162
3.078125
3
[]
no_license
#ifndef _GLOCALOBJECTMANAGER_H_ #define _GLOCALOBJECTMANAGER_H_ #include "GObjectBase.h" #include "Common/Mutex.h" #include <list> #include <vector> namespace GObject { template<typename _V > class GLocalObjectManagerT { public: bool add(_V* val) { UInt32 slot = val->getSlot(); if(slot != static_cast<UInt32>(-1)) { return false; } if(_empty.empty()) { _objs.push_back(val); val->setSlot(static_cast<UInt32>(_objs.size() - 1)); } else { size_t id = _empty.front(); _objs[id] = val; val->setSlot(static_cast<UInt32>(id)); _empty.pop_front(); } return true; } void remove(_V* val) { UInt32 slot = val->getSlot(); if(_objs.size() > slot && _objs[slot] != NULL && _objs[slot] == val) { _objs[slot]->setSlot(static_cast<UInt32>(-1)); _objs[slot] = NULL; _empty.push_back(slot); } } void remove(UInt32 slot) { } _V * operator[] (const UInt32 slot) { if(_objs.size() > slot) { if(_objs[slot]->getSlot() == slot) return _objs[slot]; _objs[slot] = NULL; } return NULL; } protected: std::vector<_V *> _objs; std::list<size_t> _empty; }; } #endif // _GLOCALOBJECTMANAGER_H_
true
e48ca2363bbf8e264190862744143547e3075ff8
C++
UlianaKov-hab/IncreaseArr
/Project2/Source.cpp
UTF-8
1,057
3.40625
3
[]
no_license
#include<iostream> #include<time.h> using namespace std; void FillArr(int* arr, int size) { for (int i = 0; i < size; i++) { arr[i] = rand() % 20; } } void PrintArr(int* arr, int size) { for (int i = 0; i < size; i++) { cout << arr[i] << "\t"; } cout << endl; } void IncreaseArr(int*& arr, int &size) { //int* arr1 = new int[*size]; //FillArr(arr, size); int* arr1 = new int[size + 1]; for (int i = 0; i < size; i++) { arr1[i] = arr[i]; } cout << "Enter value arr[size] "; int c = 0; cin >> c; arr1[size] = c; delete[]arr; arr = arr1; size++; PrintArr(arr, size); } void main() { srand(time(0)); bool exit=true; int item = 0; int size = 0; int* arr=nullptr; while (exit == true) { cout << "- MENU -\n"; cout << "1.Add arrey\n2.Increase arrey\n3.Exit\n"; cin >> item; if (item == 1) { cout << "Enter size arrey\t"; cin >> size; arr= new int[size]; FillArr(arr, size); PrintArr(arr, size); } if (item == 2) { IncreaseArr(arr, size); } if (item == 3) { exit = false; } }
true