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
cc482e5e551a976a640497c040cf2a29cad12cc9
C++
Botelho31/trabalhos_IDJ
/170109071_T1/src/Sprite.cpp
UTF-8
1,277
3.0625
3
[]
no_license
#include "../include/Sprite.h" #include "../include/State.h" #include "../include/Game.h" Sprite::Sprite(){ texture = nullptr; } Sprite::Sprite(std::string file){ texture = nullptr; Open(file); } Sprite::~Sprite(){ if(texture){ SDL_DestroyTexture(texture); } } void Sprite::Open(std::string file){ if(texture){ SDL_DestroyTexture(texture); texture = nullptr; } texture = IMG_LoadTexture(Game::GetInstance().GetRenderer(), file.c_str()); if(texture == nullptr){ std::cout << "Error Loading Image: " << SDL_GetError() << std::endl; return; }else{ SDL_QueryTexture(texture,nullptr,nullptr, &width, &height); } } void Sprite::SetClip(int x,int y,int w,int h){ clip_rect.h = h; clip_rect.w = w; clip_rect.x = x; clip_rect.y = y; } void Sprite::Render(int x,int y){ SDL_Rect dst_rect; dst_rect.x = x; dst_rect.y = y; dst_rect.w = clip_rect.w; dst_rect.h = clip_rect.h; SDL_RenderCopy(Game::GetInstance().GetRenderer(),texture,&clip_rect,&dst_rect); } int Sprite::GetWidth(){ return width; } int Sprite::GetHeight(){ return height; } bool Sprite::IsOpen(){ if(texture){ return true; }else{ return false; } }
true
3f05d5352d4dd4aa718bc443b9d4646b4bc0be2f
C++
HelloSunyi/Elements-of-Programming-Interviews
/Chapter_16/c16_4.cpp
UTF-8
1,756
2.9375
3
[]
no_license
#include <iostream> #include <vector> #define WHITE 0 #define GRAY 1 #define BLACK 2 using namespace std; //directed graph bool dfs(vector<vector<int> >& v, vector<int>& b, int i) { b[i] = GRAY; for (int j = 0; j < v.size(); j++) { if (!v[i][j]) { continue; } if (b[j] == WHITE) { bool reg = dfs(v, b, j); if (reg) return true; } else if (b[j] == GRAY) { return true; } b[i] = BLACK; return false; } } //undirected graph bool dfs(vector<vector<int> >& v, vector<int>& b, int i, int parent) { b[i] = 1; for (int j = 0; j < v.size(); j++) { if (!v[i][j]) { continue; } if (b[j] == 0) { bool reg = dfs(v, b, j, i); if (reg) return true; } else if (b[j] == 1 && j != parent) { return true; } return false; } } bool checkConnecty(vector<int> b) { for (int i = 0; i < b.size(); i++) { if (b[i] == WHITE) return false; } return true; } bool twoE(vector<vector<int> > v) { vector<int> b(v.size(), 0); bool ret = dfs(v, b, 0); ret &= checkConnecty(b); return ret; } ///////////////////////////////////////////////////////////////////////////////////////////// int time = 0; bool dfs(vector<vector<int> > v, vector<int> d, vector<int> l, int i, int parent) { l[i] = d[i] = time++; for (int j = 0; j < v.size(); j++) { if (j == paretn || v[i][j] == -1) continue; if (d[j]) { l[i] = min(l[i], l[j]); } else if(!dfs(v, d, l, j, i)) { return false; } l[i] = min(l[i], l[j]); } return parent == -1 || l[i] < d[i]; } bool is_graph_2(vector<vector<int> > v) { vector<int> d(v.size(), -1); vector<int> l(v.size(), -1); return dfs(v, d, l, 0, -1); }
true
169b03540fd6075f4e7e328a78bdb14152358f45
C++
gzc/leetcode
/cpp/1001-10000/1171-1180/Dinner Plate Stacks.cpp
UTF-8
1,462
3.375
3
[ "MIT" ]
permissive
class DinnerPlates { vector<stack<int>> v; int capacity; int bestindex; public: DinnerPlates(int capacity) { this->capacity = capacity; bestindex = 0; } void push(int val) { for (int i = bestindex; i < v.size(); i++) { stack<int>& s = v[i]; if (s.size() < capacity) { s.push(val); bestindex = i; return; } } stack<int> ss; ss.push(val); v.emplace_back(ss); bestindex = v.size() - 1; } int pop() { for (int i = v.size() - 1; i >= 0; i--) { stack<int>& s = v[i]; if (!s.empty()) { int ret = s.top(); s.pop(); bestindex = min(bestindex, i); return ret; } v.pop_back(); bestindex = max(0, min(bestindex, (int)v.size()-1)); } return -1; } int popAtStack(int index) { stack<int>& s = v[index]; if (!s.empty()) { int ret = s.top(); s.pop(); bestindex = min(bestindex, index); return ret; } return -1; } }; /** * Your DinnerPlates object will be instantiated and called as such: * DinnerPlates* obj = new DinnerPlates(capacity); * obj->push(val); * int param_2 = obj->pop(); * int param_3 = obj->popAtStack(index); */
true
129f23158d006165f2f3ed25c53344413366b778
C++
Sakerini/BMSTU-4th-Sem
/Object-Oriented-Programming(C++)/lab_03/lab_03/lab_03/geometry/point.cpp
UTF-8
2,156
3.625
4
[]
no_license
#include <cmath> #include "point.h" Point::Point(double x_, double y_, double z_) : x(x_), y(y_), z(z_) { } Point::Point(const Point &point) : x(point.getX()), y(point.getY()), z(point.getZ()) { } Point::~Point() { } Point& Point::operator=(const Point& point) { if (this != &point) { x = point.getX(); y = point.getY(); z = point.getZ(); } return *this; } double Point::getX() const { return x; } void Point::setX(double x) { this->x = x; } double Point::getY() const { return y; } void Point::setY(double y) { this->y = y; } double Point::getZ() const { return z; } void Point::setZ(double z) { this->z = z; } void Point::rotate(const IPoint& center, double alpha, double beta, double gamma) { rotateX(center, alpha); rotateY(center, beta); rotateZ(center, gamma); } void Point::rotateX(const IPoint& center, double angle) { double newY = (this->y - center.getY()) * cos(angle) - (this->z - center.getZ()) * sin(angle) + center.getY(); double newZ = (this->y - center.getY()) * sin(angle) + (this->z - center.getZ()) * cos(angle) + center.getZ(); this->y = newY; this->z = newZ; } void Point::rotateY(const IPoint& center, double angle) { double newX = (this->x - center.getX()) * cos(angle) + (this->z - center.getZ()) * sin(angle) + center.getX(); double newZ = -(this->x - center.getX()) * sin(angle) + (this->z - center.getZ()) * cos(angle) + center.getZ(); this->x = newX; this->z = newZ; } void Point::rotateZ(const IPoint& center, double angle) { double newX = (this->x - center.getX()) * cos(angle) - (this->y - center.getY()) * sin(angle) + center.getX(); double newY = (this->x - center.getX()) * sin(angle) + (this->y - center.getY()) * cos(angle) + center.getY(); this->x = newX; this->y = newY; } void Point::transfer(double dx, double dy, double dz) { x += dx; y += dy; z += dz; } void Point::scale(const IPoint& center, double k) { x = (x - center.getX()) * k + center.getX(); y = (y - center.getY()) * k + center.getY(); z = (z - center.getZ()) * k + center.getZ(); }
true
9333d9367e8c29f8b53986f3a5262248b6f01ee7
C++
Samraksh/Tuscarora
/TuscaroraFW/Lib/Pattern/NeighborTable/PatternNeighborIterator.cpp
UTF-8
2,013
2.53125
3
[]
no_license
////////////////////////////////////////////////////////////////////////////////// // Tuscarora Software Suite. The Samraksh Company. All rights reserved. // Please see License.txt file in the software root directory for usage rights. // Please see developer's manual for implementation notes. ////////////////////////////////////////////////////////////////////////////////// #include "Lib/Pattern/NeighborTable/PatternNeighborTable.h" namespace Patterns{ PatternNeighborIterator::PatternNeighborIterator() { //nbrhood = new SortedListT<LinkMetrics*, false, QualityComparator>(); } PatternNeighborIterator::PatternNeighborIterator(PatternNeighborTable* tbl, uint16_t _curNodeIndex) { curNodeIndex = _curNodeIndex; myNbrTable = tbl; curNode = &(myNbrTable->nbrhood->GetItem(curNodeIndex)->link); } const Link* PatternNeighborIterator::operator -> (){ return curNode; } const Link& PatternNeighborIterator::operator * (){ return *curNode; } PatternNeighborIterator PatternNeighborIterator::operator ++ (){ curNode = &(myNbrTable->nbrhood->GetItem(++curNodeIndex)->link); return *this; } PatternNeighborIterator PatternNeighborIterator::operator -- (){ curNode = &(myNbrTable->nbrhood->GetItem(--curNodeIndex)->link); return *this; } PatternNeighborIterator PatternNeighborIterator::GetNext() { LinkMap* nextNode = myNbrTable->nbrhood->GetItem(++curNodeIndex); if(nextNode) { curNode= &(nextNode->link); } return *this; } /*bool PatternNeighborIterator::operator == (Link& _node) { return false; } bool PatternNeighborIterator::operator == (Link& _node) { return false; }*/ bool PatternNeighborIterator::operator == (PatternNeighborIterator _iter) { if(_iter.operator->() == curNode) { //printf("\n\nThe iterators point ot same node\n\n");fflush(stdout); return true; } return false; } bool PatternNeighborIterator::operator != (PatternNeighborIterator _iter) { return !(this->operator==(_iter)); } } //End namespace
true
9dd635917fb566119adb1fb438de0836527f25f5
C++
Doggzor/Alien-Search-and-Rescue
/Engine/Alien.h
UTF-8
702
2.625
3
[]
no_license
#pragma once #include "Graphics.h" #include "UFO.h" #include <random> class Alien { public: Alien(int start_x, int start_y); void Draw(Graphics& gfx); int count = 0; bool collected = false; int fadeout = 300; int fadein = 0; int x = 0; int y = 0; static constexpr int width = 18; static constexpr int height = 30; void DrawFade1(int x, int y, Graphics& gfx); void DrawFade2(int x, int y, Graphics& gfx); void DrawFade3(int x, int y, Graphics& gfx); void DrawFade4(int x, int y, Graphics& gfx); void DrawFade5(int x, int y, Graphics& gfx); private: std::random_device rd; std::mt19937 rng; std::uniform_int_distribution<int> xDist; std::uniform_int_distribution<int> yDist; };
true
e2cc1a0b5bfd6e3c9eba8d10236c438b871e58e4
C++
NamYoonJae/InhaGame
/win32_C++/ClassProject/ClassProject/rectangle.cpp
UHC
705
3.15625
3
[]
no_license
#include "stdafx.h" #include "rectangle.h" #include <iostream> using namespace std; rectangle::rectangle() { width = 0; height = 0; areaRsult = 0; circum = 0; } rectangle::~rectangle() { } void rectangle::setWidth(double w) { width = w; } void rectangle::setHeght(double h) { height = h; } double rectangle::getWidth() { cout << " : "<<width << endl; return width; } double rectangle::getHeight() { cout << " : "<<height << endl; return height; } // void rectangle::area() { areaRsult = width*height; cout << " : " << areaRsult <<endl; } //ѷ void rectangle::circumference() { circum = (width * 2) + (height * 2); cout << "ѷ : "<<circum << endl; }
true
eaa1e4dd394b482810598c5565d171c2b8c96fa1
C++
chenlei65368/algorithm004-05
/Week 3/id_425/LeetCode_860_425.cpp
UTF-8
3,026
3.734375
4
[]
permissive
/* * @lc app=leetcode.cn id=860 lang=cpp * * [860] 柠檬水找零 * * https://leetcode-cn.com/problems/lemonade-change/description/ * * algorithms * Easy (52.15%) * Likes: 81 * Dislikes: 0 * Total Accepted: 11.6K * Total Submissions: 22.1K * Testcase Example: '[5,5,5,10,20]' * * 在柠檬水摊上,每一杯柠檬水的售价为 5 美元。 * * 顾客排队购买你的产品,(按账单 bills 支付的顺序)一次购买一杯。 * * 每位顾客只买一杯柠檬水,然后向你付 5 美元、10 美元或 20 美元。你必须给每个顾客正确找零,也就是说净交易是每位顾客向你支付 5 美元。 * * 注意,一开始你手头没有任何零钱。 * * 如果你能给每位顾客正确找零,返回 true ,否则返回 false 。 * * 示例 1: * * 输入:[5,5,5,10,20] * 输出:true * 解释: * 前 3 位顾客那里,我们按顺序收取 3 张 5 美元的钞票。 * 第 4 位顾客那里,我们收取一张 10 美元的钞票,并返还 5 美元。 * 第 5 位顾客那里,我们找还一张 10 美元的钞票和一张 5 美元的钞票。 * 由于所有客户都得到了正确的找零,所以我们输出 true。 * * * 示例 2: * * 输入:[5,5,10] * 输出:true * * * 示例 3: * * 输入:[10,10] * 输出:false * * * 示例 4: * * 输入:[5,5,10,10,20] * 输出:false * 解释: * 前 2 位顾客那里,我们按顺序收取 2 张 5 美元的钞票。 * 对于接下来的 2 位顾客,我们收取一张 10 美元的钞票,然后返还 5 美元。 * 对于最后一位顾客,我们无法退回 15 美元,因为我们现在只有两张 10 美元的钞票。 * 由于不是每位顾客都得到了正确的找零,所以答案是 false。 * * * * * 提示: * * * 0 <= bills.length <= 10000 * bills[i] 不是 5 就是 10 或是 20  * * */ // @lc code=start class Solution { public: bool lemonadeChange(vector<int>& bills) { if(bills[0]!=5 || bills[1]==20) return false; int n=0; int m=0; for(int i=0;i<bills.size();i++) { if(bills[i]==5) { n++; } else if(bills[i]==10) { if(n) { n--; m++; } else return false; } else { if(m) { if(n) { m--; n--; continue; } } if(n>=3) { n-=3; } else return false; } } return true; } }; // @lc code=end
true
2d6fa516580983f75599005550bb93e9df4feb53
C++
Jbudone/noengine
/src/libutils/lib_containers.h
UTF-8
4,356
3.453125
3
[]
no_license
#ifndef __LIB_CONTAINERS_H__ #define __LIB_CONTAINERS_H__ /*** * Containers * * Various data structures * * TODO * - ... * **/ #include <stdlib.h> #define CHAR0 48 // ASCII dec code for 0 template<class T1, class T2, class T3> struct Triple { Triple() { } Triple(T1 t1, T2 t2, T3 t3) : t1(t1), t2(t2), t3(t3) { } T1 t1; T2 t2; T3 t3; }; /* Array_Resizable * * An array which is resized when an item is added or * removed. The array is an unordered set **/ template<class T> struct Array_Resizable { Array_Resizable() : elements(0), size(0) { } void add(T element) { T* new_elements = (T*)malloc( sizeof(T) * size+1 ); int i = 0; for ( ; i < size; ++i ) { new_elements[i] = elements[i]; } new_elements[i] = element; ++size; delete elements; elements = new_elements; } bool has(T element) { int i = 0; for ( ; i < size; ++i ) { if ( elements[i] == element ) return true; } return false; } void remove(T element) { if ( size == 0 ) return; T* new_elements = (T*)malloc( sizeof(T) * size-1 ); int j = 0, k = 0; for ( ; j < size, k < size-1; ++j ) { if ( elements[j] == element ) continue; new_elements[k] = elements[j]; ++k; } --size; delete elements; elements = new_elements; } T& operator[](size_t index) { return elements[index]; } T* elements; unsigned short size; }; /* ================================================= Bitfield An extremely flexible container for storing variable-length data structures and easily retrieving it later. The way this is built is very efficient for storing and reading back data later ================================================= */ template<unsigned char SIZE> struct Bitfield { Bitfield() { fields = new unsigned char[SIZE]; for ( unsigned char i = 0; i < size; ++i ) { fields[i] = 0; } } Bitfield(const char* message) { fields = new unsigned char[SIZE](); for ( unsigned char i = 0; i < size; ++i ) { fields[i] = (unsigned char)(message[i]); } } Bitfield(int num) { fields = new unsigned char[SIZE](); for ( unsigned char i = 0; i < size; ++i ) { fields[i] = 0; } fields[0] = (unsigned char)num; } Bitfield(const Bitfield<SIZE> &rhs) { fields = new unsigned char[SIZE](); for ( unsigned char i = 0; i < (rhs.size <= this->size ? rhs.size : this->size); ++i ) { fields[i] = rhs.fields[i]; } } ~Bitfield() { delete[] fields; } Bitfield<SIZE>& operator=(const Bitfield<SIZE> &rhs) { fields = new unsigned char[SIZE](); for ( unsigned char i = 0; i < (rhs.size <= this->size ? rhs.size : this->size); ++i ) { fields[i] = rhs.fields[i]; } return *this; } void copy(const Bitfield<SIZE> &rhs) { fields = new unsigned char[SIZE](); for ( unsigned char i = 0; i < (rhs.size <= this->size ? rhs.size : this->size); ++i ) { fields[i] = rhs.fields[i]; } } operator const char*() const { char *theseFields = new char[size+1]; for ( unsigned char i = 0; i < size; ++i ) { theseFields[i] = fields[i]; } theseFields[size] = '\0'; return theseFields; // return fields; } const char* getChar() { char *theseFields = new char[size+1]; for ( unsigned char i = 0; i < size; ++i ) { theseFields[i] = (char)(fields[i]+48); // NOTE: pretty-print to show ascii } theseFields[size] = '\0'; return theseFields; } template<class T> void set(T num, unsigned char position) { for ( unsigned char i = position; i < (position + sizeof(num)); ++i ) { fields[i] = (unsigned char)num; num >>= 8; } } template<class T> T fetch(unsigned char position) { T num = 0; unsigned char i = position; unsigned char offset = 0; for ( ; i < (position + sizeof(num)); ++i, offset++ ) { num += ( fields[i] << (offset * 8) ); } return num; } template<int argsize> unsigned char append(const Bitfield<argsize>* args, unsigned char offset) { for ( unsigned char i = offset, j = 0; j < args->size; ++i, ++j ) { this->fields[i] = (char)args->fields[j]; } return offset + args->size; } template<class T> unsigned char append(T args, unsigned char offset) { this->set<T>( args, offset ); return offset + sizeof(T); } const unsigned char size = SIZE; unsigned char *fields; }; typedef Bitfield<32> Bfield32_t ; typedef Bitfield<64> Bfield64_t ; typedef Bitfield<128> Bfield128_t; #endif
true
c01ccca03e03d6ed45824909ba48df3db87394a6
C++
milczarekIT/agila
/app/Report/Goods/EndingGoodsDialogView.cpp
UTF-8
1,819
2.546875
3
[]
no_license
#include "EndingGoodsDialogView.h" EndingGoodsDialogView::EndingGoodsDialogView(QWidget *parent, EndingGoodsDialogController *controller) : ReportDialogView(parent) { this->controller = controller; this->setWindowTitle("Kończące się towary"); this->addComponents(); connect(buttonBox, SIGNAL(accepted()), controller, SLOT(saveReport())); connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); } void EndingGoodsDialogView::addComponents() { tableView = new QTableView; tableView->setSelectionBehavior(QAbstractItemView::SelectRows); tableView->setSelectionMode(QAbstractItemView::SingleSelection); tableView->setFocusPolicy(Qt::NoFocus); tableView->verticalHeader()->setDefaultSectionSize(20); labelText = new QLabel("Ilość nie większa niż:"); spinBoxQuantity = new QDoubleSpinBox(); spinBoxQuantity->setMinimum(0.0); spinBoxQuantity->setDecimals(3); spinBoxQuantity->setValue(3.00); layout->setRowMinimumHeight(0, 20); layout->addWidget(labelText, 0, 1, 1, 1); layout->addWidget(spinBoxQuantity, 0, 2, 1, 1); layout->addWidget(tableView, 1, 1, 1, 6); layout->addWidget(buttonBox, 2, 1, 1, 6, Qt::AlignRight); connect(spinBoxQuantity, SIGNAL(valueChanged(double)), controller, SLOT(quantityChanged(double))); } void EndingGoodsDialogView::setTVModel(TVModel *model) { tableView->setModel(model); tableView->setColumnHidden(0, true); tableView->setColumnWidth(1, 170); tableView->setColumnWidth(2, 260); tableView->setColumnWidth(3, 80); tableView->setColumnWidth(4, 40); tableView->setColumnWidth(5, 120); tableView->setColumnWidth(6, 90); tableView->setColumnWidth(7, 90); } QDoubleSpinBox *EndingGoodsDialogView::getSpinBoxQuantity() { return spinBoxQuantity; }
true
ddf12b63f9137ac6864842e6f93223afd14a2cc6
C++
jsffeng/ShredderReconstruct
/common_classes.cpp
UTF-8
7,858
3.109375
3
[]
no_license
#include <fstream> #include <unordered_set> #include "common_classes.h" #include "singleton_random.h" using namespace std; // Common function for reading text lines from an input file, usually used read text page void TextFileOperation::ReadText(const string str_filename, vector<string> &vec_str_text_lines) { string str_line; ifstream f_infile; f_infile.open(str_filename); if (!f_infile) { throw runtime_error("File cannot open to read!"); } if (!vec_str_text_lines.empty()) vec_str_text_lines.clear(); unsigned int n_length; unsigned int n_max_length = 0; while (getline(f_infile, str_line)) { n_length = str_line.length(); if (n_length > n_max_length) n_max_length = n_length; vec_str_text_lines.emplace_back(str_line); } f_infile.close(); // Convert blank at end of each line to ascii space characters, and this is required by shredding process auto iter = vec_str_text_lines.begin(); unsigned int n_size; while (iter != vec_str_text_lines.end()) { n_size = iter->size(); while (n_size < n_max_length) { iter->append(" "); ++n_size; } ++iter; } } // Common function for reading text lines from an input file, usually used to store dictionary void TextFileOperation::ReadText(const string str_filename, unordered_set<string> &uset_str_text_lines) { string str_line; ifstream f_infile; f_infile.open(str_filename); if (!f_infile) { throw runtime_error("File cannot open to read!"); } if (!uset_str_text_lines.empty()) uset_str_text_lines.clear(); while (getline(f_infile, str_line)) { uset_str_text_lines.insert(str_line); } f_infile.close(); } // Common function for writing text strips to an output file void TextFileOperation::WriteText(const string str_filename, const vector<string> vec_str_text_lines) { ofstream f_outfile; f_outfile.open (str_filename); if (!f_outfile) { throw runtime_error("File cannot open to write!"); } for (int i = 0; i < vec_str_text_lines.size(); ++i) { f_outfile << vec_str_text_lines[i] << endl; } f_outfile.close(); } const int TextStripOperation::s_random_number_ = 40; // Re-order the vector component - each component contain a vector to store a text strip void TextStripOperation::Disorder(vector<vector<string>>& vec_str_input) { unsigned int n_temp = 0; if (vec_str_input.size() == 0) { throw runtime_error("Invalid input!"); } else { SingletonRandom::s_max_val_ = vec_str_input.size() - 1; SingletonRandom& random_instance = SingletonRandom::GetInstance(); for (int i = 0; i < s_random_number_; ++i) { n_temp = random_instance.GenerateRandom(); vec_str_input.emplace(vec_str_input.end(), vec_str_input[n_temp]); vec_str_input.erase(vec_str_input.begin() + n_temp); } } } // Transpose row and column(each column is for a text strip) void TextStripOperation::Transpose(vector<vector<string>>& vec_str_input, vector<vector<string>>& vec_str_input_trans) { vector<string> vec_temp; if (!vec_str_input_trans.empty()) vec_str_input_trans.clear(); if (vec_str_input.size() == 0) { throw runtime_error("Invalid input!"); } for (int i = 0; i < vec_str_input[0].size(); ++i) { for (int j = 0; j< vec_str_input.size(); ++j) { vec_temp.emplace_back(vec_str_input[j][i]); } vec_str_input_trans.emplace_back(vec_temp); vec_temp.clear(); } } // Merge multiple columns into one column void TextStripOperation::MergeText(vector<vector<string>> & vec_str_input, vector<string>& vec_str_text) { string str_temp; if (vec_str_input.empty()) { throw runtime_error("vec_str_input is empty, no text data to merge!"); } if (!vec_str_text.empty()) vec_str_text.clear(); for (int j = 0; j < vec_str_input.begin()->size() ; ++j) { for (int i = 0; i < vec_str_input.size(); ++i) { str_temp.append(vec_str_input[i][j]); } vec_str_text.emplace_back(str_temp); str_temp.clear(); } } // From left hand, identify the word used to lookup in the dictionary from a string containing many words. // Before calling this function, some delimiter such as "," or "." need to be transformed to blank // character ' '. // Below is the list of examples to show how this function works to extract a word (or word piece) // used for lookup: // a1a2a3|a4a5 |a7a8a9 --> a1a2a3a4a5 // a3|a4a5a6|a7 a9 --> a3a4a5a6a7 // |a4a5a6|a7a8a9 --> "" (empty string) // | a5a6|a7a8 --> "" (empty string) // a1 a3|a4 a6|a7a8a9 --> a3a4 // a1 a3| a5a6|a7a8 --> "" (empty string) void WordStringOperation::FindLookupWordLeft(string & str_line, string & str_key, int n_column_width) { string str_key_t; if (str_line.empty() || n_column_width <= 0 || str_line.size() <= n_column_width) throw runtime_error("Invalid input to function FindLookupWordLeft()!"); int n_boundary = n_column_width; for (int k = 0; k < str_line.size(); ++k) { if (' ' != str_line[k]) { if (str_key_t.empty() && k >= n_boundary) { break; } else { str_key_t = str_key_t + str_line[k]; } } else { if (k > n_boundary) { break; } else { if (!str_key_t.empty()) str_key_t.clear(); } } } str_key = str_key_t; } // From right hand, identify the word used to lookup in the dictionary from a string containing many words. // Before calling this function, some delimiter such as "," or "." need to be transformed to blank // character ' '. // Below is the list of examples to show how this function works to extract a word (or word piece) // used for lookup: // a1a2a3| a5a6|a7a8a9 --> a5a6a7a8a9 // a2a3|a4a5a6|a7 --> a2a3a4a5a6a7 // a2a3|a4a5a6| --> "" (empty string) // a1 a3|a4a5 | --> "" (empty string) // a1a2a3|a4 a6|a7 a9 --> a6a7 // a2a3|a4a5 |a7 a9 --> "" (empty string) void WordStringOperation::FindLookupWordRight(string & str_line, string & str_key, int n_column_width) { string str_key_t; if (str_line.size() == 0 || n_column_width <= 0 || str_line.size() <= n_column_width) throw runtime_error("Invalid input to function FindLookupWordRight()!"); int n_boundary = str_line.size() - n_column_width - 1; for (int k = str_line.size() - 1; k >= 0; --k) { if (' ' != str_line[k]) { if (str_key_t.empty() && k <= n_boundary) { break; } else { str_key_t = str_line[k] + str_key_t; } } else { if (k < n_boundary) { break; } else { if (!str_key_t.empty()) str_key_t.clear(); } } } str_key = str_key_t; } // Removing word suffix such as ed|ing|s|es, won't remove suffix if the number of remaining letters are // less than 2. This function is usually for dictionary lookup. bool WordStringOperation::RemoveWordSuffix(string &str_lookup_key) { vector<string> vec_suffix = {"ing", "ed", "es", "s"}; if (str_lookup_key.size() == 0) throw runtime_error("Invalid input to function RemoveWordSuffix()!"); int n_position = str_lookup_key.size(); int n_position_t, n_length_t; bool b_remove_suffix = false; auto iter = vec_suffix.begin(); while (iter != vec_suffix.end()) { n_length_t = iter->size(); n_position_t = n_position - n_length_t; // Need to ensure the number of remaining letters are equal or greater than 2 after removing suffix if (n_position_t >= 2) { if (str_lookup_key.compare(n_position_t,n_length_t,*iter) == 0) { str_lookup_key = str_lookup_key.substr(0, n_position_t); b_remove_suffix = true; break; } } ++iter; } return b_remove_suffix; }
true
7bc6a38f50ce8f49011fd9d5ec95b3bb95f1db96
C++
gingkg/happyleetcodeeveryday
/leetcode/leetcode_93/test.cpp
UTF-8
238
2.6875
3
[ "MIT" ]
permissive
#include <iostream> #include <vector> using namespace std; int test() { vector<string> vec; string s = "swsdfghjhk"; s.insert(2, "."); cout << s << endl; vec.push_back(s); vec.push_back(s); vec.push_back(s); return 0; }
true
cb619196875f8aba174668f9dcd3561c1e2ea79b
C++
emmmile/ibm-ponder-this
/2015/april/vect.hpp
UTF-8
530
3.265625
3
[]
no_license
#include <array> #include <ostream> using namespace std; // simple stack vector implementation typedef array<int, 3> vect; vect operator + ( const vect& a, const vect& b ) { vect c; for ( size_t i = 0; i < a.size(); ++i ) c[i] = a[i] + b[i]; return c; } vect operator - ( const vect& a, const vect& b ) { vect c; for ( size_t i = 0; i < a.size(); ++i ) c[i] = a[i] - b[i]; return c; } ostream& operator << ( ostream& stream, vect& c ) { for ( auto i : c ) stream << i << " "; return stream; }
true
5adb7a071351a7a0e6ca1aab54d99ec7ba90739b
C++
lazymonday/PS
/baekjoon/12015_lis/main.cpp
UTF-8
642
2.84375
3
[]
no_license
#include <iostream> #include <algorithm> using namespace std; const int MAX = 1e6 + 10; int n; int nums[MAX]; int lisArr[MAX]; bool comp(const int& a, const int& b) { return a > b;} int lis() { int len = 0; for (int i = 0; i < n; ++i) { auto pos = lower_bound(lisArr, lisArr + len, nums[i], comp); *pos = nums[i]; if (pos == lisArr + len) { len++; } } return len; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cin >> n; for (int i = 0; i < n; ++i) { cin >> nums[i]; } int len = lis(); cout << len << "\n"; return 0; }
true
5f1da366a0d413a9fccc49a483f8ce77e7897bbc
C++
iynaur/ChineseChesses
/chess_shi.cpp
WINDOWS-1252
1,378
2.59375
3
[ "MIT" ]
permissive
#include "chess_shi.h" chess_shi::chess_shi(int X,int Y,int PLAYER,bool ALIVE):chess(X,Y,PLAYER,ALIVE) { name=NAMESHI; } chess_shi::chess_shi(void):chess(-1,-1,NAMENONE,false) { name=NAMESHI; } chess_shi::chess_shi(chess_shi &obj) { x=obj.x; y=obj.y; name=obj.name; player=obj.player; alive=obj.alive; } int chess_shi::OutChessName() { return name; } BOARD_HIND chess_shi::hind(BOARD_CHESS BOARD,BOARD_CHESS CHESS) { BOARD_HIND *p=new BOARD_HIND; //ʱ int i,k; for(i=0;i<=9;i++) for(k=0;k<=8;k++) p->a[i][k]=false; if(player==PLAYERRED) switch(x) { case 7: if(BOARD.a[8][4]!=PLAYERRED) p->a[8][4]=true; break; case 8: if(BOARD.a[7][3]!=PLAYERRED) p->a[7][3]=true; if(BOARD.a[7][5]!=PLAYERRED) p->a[7][5]=true; if(BOARD.a[9][3]!=PLAYERRED) p->a[9][3]=true; if(BOARD.a[9][5]!=PLAYERRED) p->a[9][5]=true; break; case 9: if(BOARD.a[8][4]!=PLAYERRED) p->a[8][4]=true; break; } if(player==PLAYERBLACK) switch(x) { case 0: if(BOARD.a[1][4]!=PLAYERBLACK) p->a[1][4]=true; break; case 1: if(BOARD.a[0][3]!=PLAYERBLACK) p->a[0][3]=true; if(BOARD.a[0][5]!=PLAYERBLACK) p->a[0][5]=true; if(BOARD.a[2][3]!=PLAYERBLACK) p->a[2][3]=true; if(BOARD.a[2][5]!=PLAYERBLACK) p->a[2][5]=true; break; case 2: if(BOARD.a[1][4]!=PLAYERBLACK) p->a[1][4]=true; break; } return *p; }
true
11bc820f1f548e5f8ee68cbc28068f5859963b7f
C++
jerrywwl/gnm
/gnm/functions/func_quat.inl
UTF-8
4,353
2.671875
3
[]
no_license
#include "func_vector_relational.h" #include "func_trigonometric.h" GNM_NAMESPACE_BEGIN GNM_INLINE bvec4 Equal(const quat& x, const quat& y) { return bvec4((Abs(x.w - y.w) <= GNM_EPSILON), (Abs(x.x - y.x) <= GNM_EPSILON), (Abs(x.y - y.y) <= GNM_EPSILON), (Abs(x.z - y.z) <= GNM_EPSILON)); } GNM_INLINE float Dot(const quat& x, const quat& y) { #if (GNM_SIMD) return _mm_cvtss_f32(_mm_dp_ps(x._v, y._v, 0xff)); #else return (x.w * y.w + x.x * y.x + x.y * y.y + x.z * y.z); #endif } GNM_INLINE quat Cross(const quat& x, const quat& y) { return quat(x.w * y.z + x.z * y.w + x.x * y.y - x.y * y.x, x.w * y.w - x.x * y.x - x.y * y.y - x.z * y.z, x.w * y.x + x.x * y.w + x.y * y.z - x.z * y.y, x.w * y.y + x.y * y.w + x.z * y.x - x.x * y.z); } GNM_INLINE float Length(const quat& x) { return std::sqrt(x.w * x.w + x.x * x.x + x.y * x.y + x.z * x.z); } GNM_INLINE quat Normalize(const quat& x) { #if (GNM_SIMD) return vec4(_mm_mul_ps(x._v, _mm_rsqrt_ps(_mm_dp_ps(x._v, x._v, 0xFF)))); #else const float f = 1.0f / std::sqrt(x.x * x.x + x.y * x.y + x.z * x.z + x.w * x.w); return quat(x.w * f, x.x * f, x.y * f, x.z * f); #endif } GNM_INLINE quat Conjugate(const quat& x) { #if (GNM_SIMD) return quat(_mm_set_ps(x.w, -x.z, -x.y, -x.x)); #else return quat(x.w, -x.x, -x.y, -x.z); #endif } GNM_INLINE quat Inverse(const quat& x) { #if (GNM_SIMD) return quat(_mm_div_ps(_mm_set_ps(-x.z, -x.y, -x.x, x.w), _mm_dp_ps(x._v, x._v, 0xFF))); #else const float f = 1.0f / (x.x * x.x + x.y * x.y + x.z * x.z + x.w * x.w); return quat(x.w * f, -x.x * f, -x.y * f, -x.z * f); #endif } GNM_INLINE float Angle(const quat& x) { if (Abs(x.w) > 0.87758256f) { const float a = Asin(std::sqrt(x.x * x.x + x.y * x.y + x.z * x.z)) * 2.0f; if (x.w < 0.0f) { return GNM_PI * 2.0f - a; } return a; } return Acos(x.w) * 2.0f; } GNM_INLINE vec3 Axis(const quat& x) { const float tmp1 = 1.0f - x.w * x.w; if (tmp1 <= 0.0f) { return vec3(0, 0, 1); } const float tmp2 = 1.0f / std::sqrt(tmp1); return vec3(x.x * tmp2, x.y * tmp2, x.z * tmp2); } GNM_INLINE quat Rotate(const quat& x, const vec3& Axis, const float Angle) { vec3 tmp = Axis; // Axis of rotation must be normalised float len = Length(tmp); if (Abs(len - 1.0f) > 0.001f) { float oneOverLen = 1.0f / len; tmp.x *= oneOverLen; tmp.y *= oneOverLen; tmp.z *= oneOverLen; } const float f = Sin(Angle * 0.5f); return x * quat(Cos(Angle * 0.5f), tmp.x * f, tmp.y * f, tmp.z * f); } // http://lolengine.net/blog/2013/09/18/beautiful-maths-quaternion-from-vectors GNM_INLINE quat FromNormalizedAxis(const vec3& a, const vec3& b) { float norm_u_norm_v = std::sqrt(Dot(a, a) * Dot(b, b)); float real_part = norm_u_norm_v + Dot(a, b); vec3 t; if (real_part < static_cast<float>(1.e-6f) * norm_u_norm_v) { // If u and v are exactly opposite, rotate 180 degrees // around an arbitrary orthogonal axis. Axis normalisation // can happen later, when we normalise the quaternion. real_part = 0.0f; t = Abs(a.x) > Abs(a.z) ? vec3(-a.y, a.x, 0.0f) : vec3(0.0f, -a.z, a.y); } else { // Otherwise, build quaternion the standard way. t = Cross(a, b); } return Normalize(quat(real_part, t)); } GNM_INLINE float Roll(const quat& q) { const float y = 2.0f * (q.x * q.y + q.w * q.z); const float x = q.w * q.w + q.x * q.x - q.y * q.y - q.z * q.z; if (All(Equal(vec2(x, y), VEC2_ZERO, GNM_EPSILON))) return 0.0f; return Atan(y, x); } GNM_INLINE float Pitch(const quat& q) { const float y = 2.0f * (q.y * q.z + q.w * q.x); const float x = q.w * q.w - q.x * q.x - q.y * q.y + q.z * q.z; if (All(Equal(vec2(x, y), VEC2_ZERO, GNM_EPSILON))) return 2.0f * Atan(q.x, q.w); return Atan(y, x); } GNM_INLINE float Yaw(const quat& q) { return Asin(Clamp(-2.0f * (q.x * q.z - q.w * q.y), -1.0f, 1.0f)); } GNM_INLINE vec3 EulerAngles(const quat& q) { return vec3(Pitch(q), Yaw(q), Roll(q)); } GNM_INLINE quat QuatAxisAngle(const vec3& Axis, const float Angle) { return quat(Cos(Angle * 0.5f), Axis * (Sin(Angle) * 0.5f)); } GNM_INLINE quat QuatEulerAngles(const vec3& angles) { vec3 c = Cos(angles * 0.5f); vec3 s = Sin(angles * 0.5f); return quat(c.x * c.y * c.z + s.x * s.y * s.z, s.x * c.y * c.z - c.x * s.y * s.z, c.x * s.y * c.z + s.x * c.y * s.z, c.x * c.y * s.z - s.x * s.y * c.z); } GNM_NAMESPACE_END
true
7287166ab77534648f24e69ebbb01be6b67fe3df
C++
seal-git/atcoder
/2021-05-09-C/main.cpp
UTF-8
775
2.515625
3
[]
no_license
#include <iostream> #include <string> #include <stdio.h> #include <math.h> #include <queue> #include <algorithm> #include <utility> #include <vector> #include <tuple> #include <numeric> using namespace std; int main(int argc, char* argv[]){ int n; cin>>n; vector<int> sosu; int nums[10001]; for(int i=0;i<10000;i++){ nums[i] = i; } nums[1] = 0; for(int i=0;i<10000;i++){ if(nums[i]!=0){ sosu.push_back(nums[i]); int idx = i+i; while(idx<10000){ nums[idx] = 0; idx += i; } } } // for(int i=0;i<sosu.size();i++){ // cout<<sosu[i]<<endl; // } vector<long long>ans(n); for(int i=0;i<n;i++){ ans[i] = 1; for(int j=0;j<n;j++){ if(i!=j){ ans[i] *= sosu[j]; } } } for(int i=0;i<n;i++){ cout<<ans[i]<<" "; } cout<<endl; }
true
7824235d2195a3833b3df1ff73af77eb1fbf646f
C++
kushagraagrawal/codeforces-codechef
/Music/git_project2/codeforces/332ADiv2.cpp
UTF-8
358
2.53125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int main() { long long int d1,d2,d3,distance = 0; cin>>d1>>d2>>d3; if(d1<=d2) { distance+=d1; if(d1+d2<d3) distance+=d1+d2; else distance+=d3; distance+=d2; } else { distance+=d2; if(d1+d2 < d3) distance += d1 + d2; else distance += d3; distance += d1; } cout<<distance<<endl; }
true
98c6be64a683fa5931f7effb9270ce15b652e388
C++
sarim/Avrodroid
/jni/avrov8.cpp
UTF-8
4,199
2.609375
3
[]
no_license
#include <jni.h> #include <iostream> #include <v8.h> #include <string> #include <stdio.h> #include <android/log.h> #define LOGI(...) __android_log_print(ANDROID_LOG_INFO,"avro-ndk",__VA_ARGS__) #define LOGIJS(...) __android_log_print(ANDROID_LOG_INFO,"avro-js",__VA_ARGS__) using namespace v8; HandleScope handle_scope; std::string libdir; // Create a new context. Persistent<Context> context; Handle<String> ReadFile(const char* name) { FILE* file = fopen(name, "rb"); if (file == NULL) return Handle<String>(); fseek(file, 0, SEEK_END); int size = ftell(file); rewind(file); char* chars = new char[size + 1]; chars[size] = '\0'; for (int i = 0; i < size;) { int read = fread(&chars[i], 1, size - i, file); i += read; } fclose(file); Handle<String> result = String::New(chars, size); delete[] chars; return result; } const char* ToCString(const String::Utf8Value& value) { return *value ? *value : "<string conversion failed>"; } Handle<Value> Print(const Arguments& args) { bool first = true; for (int i = 0; i < args.Length(); i++) { HandleScope handle_scope; if (first) { first = false; } else { //printf(" "); } String::Utf8Value str(args[i]); const char* cstr = ToCString(str); LOGIJS("%s", cstr); } return Undefined(); } void loadfile(std::string filename){ Context::Scope context_scope(context); LOGI("Loading js file : %s",filename.c_str()); std::string filepath = libdir + filename; // Create a string containing the JavaScript source code. Handle<String> source = ReadFile(filepath.c_str()); // Compile the source code. Handle<Script> script = Script::Compile(source); script->Run(); LOGI("Finished Loding file."); } extern "C" { JNIEXPORT void JNICALL Java_com_omicronlab_avrokeyboard_PhoneticIM_setdir( JNIEnv* env,jobject thiz, jstring sk1); JNIEXPORT void JNICALL Java_com_omicronlab_avrokeyboard_PhoneticIM_loadjs( JNIEnv* env,jobject thiz, jstring sk1, jstring sk2); JNIEXPORT void JNICALL Java_com_omicronlab_avrokeyboard_PhoneticIM_killjs( JNIEnv* env,jobject thiz); JNIEXPORT jstring JNICALL Java_com_omicronlab_avrokeyboard_PhoneticIM_avroparse( JNIEnv* env,jobject thiz,jstring sk1); }; void GetJStringContent(JNIEnv *AEnv, jstring AStr, std::string &ARes) { if (!AStr) { ARes.clear(); return; } const char *s = AEnv->GetStringUTFChars(AStr,NULL); ARes=s; AEnv->ReleaseStringUTFChars(AStr,s); } void Java_com_omicronlab_avrokeyboard_PhoneticIM_loadjs(JNIEnv* env,jobject thiz,jstring sk1, jstring sk2){ std::string filepath1; std::string filepath2; //convert java String to Cpp String GetJStringContent(env,sk1,filepath1); GetJStringContent(env,sk2,filepath2); // Enter the created context for compiling and running script. Handle<ObjectTemplate> global = ObjectTemplate::New(); global->Set(String::New("print"), FunctionTemplate::New(Print)); context = Context::New(NULL, global); loadfile(filepath1); loadfile(filepath2); } void Java_com_omicronlab_avrokeyboard_PhoneticIM_killjs( JNIEnv* env,jobject thiz){ Context::Scope context_scope(context); context.Dispose(); } void Java_com_omicronlab_avrokeyboard_PhoneticIM_setdir( JNIEnv* env,jobject thiz, jstring sk1){ GetJStringContent(env,sk1,libdir); LOGI("Setting js files dir path : %s",libdir.c_str()); } jstring JNICALL Java_com_omicronlab_avrokeyboard_PhoneticIM_avroparse( JNIEnv* env,jobject thiz,jstring sk1) { std::string banglatxt; //convert java String to Cpp String GetJStringContent(env,sk1,banglatxt); Context::Scope context_scope(context); Handle<Object> global = context->Global(); Handle<Value> avro_parse = global->Get(String::New("avroparsefunc")); Handle<Function> avro_parse_func = Handle<Function>::Cast(avro_parse); Handle<Value> args[1]; Handle<Value> result; args[0] = v8::String::New(banglatxt.c_str()); result = avro_parse_func->Call(global, 1, args); // Convert the result to an ASCII string String::Utf8Value ascii(result); std::string bntext = std::string(*ascii); return env->NewStringUTF(bntext.c_str()); }
true
9af4341c5ae666f89da4fa64d3d00495c222dc98
C++
alexiskovi/renegade
/modules/common/serial/src/serial.cc
UTF-8
1,126
3.015625
3
[]
no_license
#include <stdio.h> #include "serial.h" namespace renegade { namespace common { SerialInterface::SerialInterface(const char *port) { serial_port.open(port); if(!serial_port.is_open()) { ROS_FATAL("Can't open serial port"); } else { ROS_INFO("Opened"); } } void SerialInterface::Write(std::string msg) { serial_port << msg << std::endl; } bool SerialInterface::Read(std::string *msg) { serial_port >> *msg; if(msg->empty()) return false; else return true; } std::vector<double> SerialInterface::Parse(std::string msg) { std::string delimeter = ";"; size_t start = 0U; size_t end; std::string token; std::vector <double> result; while ((end = msg.find(delimeter, start)) != std::string::npos) { token = msg.substr(start, end-start); double ttoken = std::stod(token); result.push_back(ttoken); start = end + delimeter.length(); } result.push_back(std::stod (msg.substr(start, msg.length()))); return result; } SerialInterface::~SerialInterface() { serial_port.close(); ROS_INFO("Closed port"); } } }
true
3d401b7fead2e9fd8a5adf0466ee507b8c0fff88
C++
MSallermann/spirit_toy_code
/include/implementation/Memory.hpp
UTF-8
8,487
2.78125
3
[]
no_license
#pragma once #ifndef MEMORY_HPP #define MEMORY_HPP #include "Definitions.hpp" #include <string> #include <vector> #ifdef BACKEND_CUDA #include "implementation/backend_cuda/cuda_helper_functions.hpp" #endif namespace Spirit { namespace Implementation { template<typename T> class device_type { private: T m_value; T * m_ptr = nullptr; public: device_type() { #ifdef BACKEND_CUDA CUDA_HELPER::malloc_n( m_ptr, 1 ); #endif } device_type( const T & value ) : device_type() { upload( value ); } HD_ATTRIBUTE T * data() { #ifdef BACKEND_CPU return &m_value; #else return m_ptr; #endif } H_ATTRIBUTE device_type & operator=( const device_type<T> & other ) { #ifdef BACKEND_CPU m_value = other.value; #else cudaMemcpy( m_ptr, other.m_ptr, sizeof( T ), cudaMemcpyDeviceToDevice ); return *this; #endif } H_ATTRIBUTE void upload( const T & value ) { #ifdef BACKEND_CPU m_value = value; #else CUDA_HELPER::copy_H2D( m_ptr, &value ); #endif } H_ATTRIBUTE T download() { #ifdef BACKEND_CPU return m_value; #else CUDA_HELPER::copy_D2H( &m_value, m_ptr ); return m_value; #endif } H_ATTRIBUTE ~device_type() { if( m_ptr != nullptr ) { #ifdef BACKEND_CPU delete m_ptr; #else CUDA_HELPER::free( m_ptr ); #endif } } }; template<typename T> class device_vector { protected: T * m_ptr = nullptr; size_t m_size = 0; public: H_ATTRIBUTE device_vector() : m_ptr( nullptr ), m_size( 0 ) {} H_ATTRIBUTE device_vector( size_t N ); H_ATTRIBUTE device_vector( size_t N, const T & value ); H_ATTRIBUTE device_vector( const device_vector<T> & old_vector ); H_ATTRIBUTE device_vector & operator=( const device_vector<T> & old_vector ); H_ATTRIBUTE void copy_to( std::vector<T> & host_vector ); H_ATTRIBUTE void copy_from( const std::vector<T> & host_vector ); H_ATTRIBUTE void copy_to( T * host_ptr ); H_ATTRIBUTE void copy_from( T * host_vector ); D_ATTRIBUTE T & operator[]( int N ); HD_ATTRIBUTE size_t size() const; H_ATTRIBUTE ~device_vector(); HD_ATTRIBUTE T * data() { return m_ptr; } }; #ifdef BACKEND_CPU template<typename T> H_ATTRIBUTE device_vector<T>::device_vector( size_t N ) { m_ptr = new T[N]; m_size = N; } template<typename T> H_ATTRIBUTE device_vector<T>::device_vector( size_t N, const T & value ) : device_vector<T>( N ) { #pragma omp parallel for for( int i = 0; i < int( m_size ); i++ ) { m_ptr[i] = value; } } template<typename T> H_ATTRIBUTE device_vector<T>::device_vector( const device_vector<T> & old_vector ) { m_size = old_vector.size(); m_ptr = new T[m_size]; #pragma omp parallel for for( int i = 0; i < int( m_size ); i++ ) { m_ptr[i] = old_vector.m_ptr[i]; } } template<typename T> H_ATTRIBUTE device_vector<T> & device_vector<T>::operator=( const device_vector<T> & old_vector ) { if( this->m_size != old_vector.size() ) { m_size = old_vector.size(); if( this->m_ptr != nullptr ) delete[] m_ptr; m_ptr = new T[m_size]; } #pragma omp parallel for for( int i = 0; i < int( m_size ); i++ ) { m_ptr[i] = old_vector.m_ptr[i]; } return *this; } template<typename T> H_ATTRIBUTE void device_vector<T>::copy_to( std::vector<T> & host_vector ) { if( host_vector.data() == this->m_ptr ) { return; } if( host_vector.size() == this->size() ) { #pragma omp parallel for for( int i = 0; i < int( this->size() ); i++ ) { host_vector[i] = ( this->m_ptr )[i]; } } else { std::string msg = "Trying to copy from device vector of size " + std::to_string( this->size() ) + " to host vector of size " + std::to_string( host_vector.size() ); throw std::runtime_error( msg ); } } template<typename T> H_ATTRIBUTE void device_vector<T>::copy_to( T * host_ptr ) { #pragma omp parallel for for( int i = 0; i < int( this->size() ); i++ ) { host_ptr[i] = ( this->m_ptr )[i]; } } template<typename T> H_ATTRIBUTE void device_vector<T>::copy_from( const std::vector<T> & host_vector ) { if( host_vector.data() == this->m_ptr ) { return; } if( host_vector.size() == this->size() ) { #pragma omp parallel for for( int i = 0; i < int( this->size() ); i++ ) { ( this->m_ptr )[i] = host_vector[i]; } } else { std::string msg = "Trying to copy to device vector of size " + std::to_string( this->size() ) + " from host vector of size " + std::to_string( host_vector.size() ); throw std::runtime_error( msg ); } } template<typename T> H_ATTRIBUTE void device_vector<T>::copy_from( T * host_ptr ) { #pragma omp parallel for for( int i = 0; i < int( this->size() ); i++ ) { ( this->m_ptr )[i] = host_ptr[i]; } } template<typename T> D_ATTRIBUTE T & device_vector<T>::operator[]( int N ) { return m_ptr[N]; } template<typename T> HD_ATTRIBUTE size_t device_vector<T>::size() const { return m_size; } template<typename T> H_ATTRIBUTE device_vector<T>::~device_vector() { if( m_ptr != nullptr ) { delete[] m_ptr; } } #else template<typename T> H_ATTRIBUTE device_vector<T>::device_vector( size_t N ) { CUDA_HELPER::malloc_n( m_ptr, N ); m_size = N; } template<typename T> __global__ void __cu_set( T * m_ptr, size_t N, T value ) { int idx = blockIdx.x * blockDim.x + threadIdx.x; if( idx < N ) m_ptr[idx] = value; } template<typename T> H_ATTRIBUTE device_vector<T>::device_vector( size_t N, const T & value ) : device_vector<T>( N ) { int blockSize = 1024; int numBlocks = ( N + blockSize - 1 ) / blockSize; __cu_set<<<blockSize, numBlocks>>>( m_ptr, N, value ); } template<typename T> H_ATTRIBUTE device_vector<T>::device_vector( const device_vector<T> & old_vector ) { m_size = old_vector.size(); CUDA_HELPER::malloc_n( m_ptr, m_size ); cudaMemcpy( m_ptr, old_vector.m_ptr, m_size * sizeof( T ), cudaMemcpyDeviceToDevice ); } template<typename T> H_ATTRIBUTE device_vector<T> & device_vector<T>::operator=( const device_vector<T> & old_vector ) { if( this->m_size != old_vector.size() ) { m_size = old_vector.size(); if( this->m_ptr != nullptr ) CUDA_HELPER::free( m_ptr ); CUDA_HELPER::malloc_n( m_ptr, m_size ); } cudaMemcpyAsync( m_ptr, old_vector.m_ptr, m_size * sizeof( T ), cudaMemcpyDeviceToDevice ); return *this; } template<typename T> H_ATTRIBUTE void device_vector<T>::copy_to( std::vector<T> & host_vector ) { if( this->size() == host_vector.size() ) CUDA_HELPER::copy_vector_D2H( host_vector, this->m_ptr ); else { std::string msg = "Trying to copy from device vector of size " + std::to_string( this->size() ) + " to host vector of size " + std::to_string( host_vector.size() ); throw std::runtime_error( msg ); } } template<typename T> H_ATTRIBUTE void device_vector<T>::copy_to( T * host_ptr ) { CUDA_HELPER::copy_n_D2H( host_ptr, this->m_ptr, this->size() ); } template<typename T> H_ATTRIBUTE void H_ATTRIBUTE device_vector<T>::copy_from( const std::vector<T> & host_vector ) { if( this->size() == host_vector.size() ) CUDA_HELPER::copy_vector_H2D( this->m_ptr, host_vector ); else { std::string msg = "Trying to copy to device vector of size " + std::to_string( this->size() ) + " from host vector of size " + std::to_string( host_vector.size() ); throw std::runtime_error( msg ); } } template<typename T> H_ATTRIBUTE void device_vector<T>::copy_from( T * host_ptr ) { CUDA_HELPER::copy_n_H2D( this->m_ptr, host_ptr, this->size() ); } template<typename T> D_ATTRIBUTE T & device_vector<T>::operator[]( int N ) { return m_ptr[N]; } template<typename T> HD_ATTRIBUTE size_t device_vector<T>::size() const { return m_size; } template<typename T> H_ATTRIBUTE device_vector<T>::~device_vector() { if( m_ptr != nullptr ) CUDA_HELPER::free( m_ptr ); } #endif } // namespace Implementation } // namespace Spirit #endif
true
60ede015ce0917cfdf36b70ae8d19261be85f6b5
C++
KishoreKaushal/cpp-routines
/stoppable-task/main.cpp
UTF-8
626
3.0625
3
[ "MIT" ]
permissive
#include "stoppable_task.hpp" #include <iostream> #include <memory> class Speak : public StoppableTask { int count; public: Speak() : count(0), StoppableTask() {} Speak(const Speak&) = delete; Speak& operator=(const Speak&) = delete; void run() override { std::cout << ++count << " -- speaking ... " << std::endl; } }; int main() { int i = 10; std::unique_ptr<Speak> spk = std::make_unique<Speak>(); // spk->request_stop(); do { (*spk)(); if (--i <= 0) { spk->request_stop(); } } while(not spk->is_stop_requested()); return 0; }
true
46f227f10907c62d9fd714bbe79a30bce0897a72
C++
nanenchanga53/BackJoonAlgorithems
/algorithms/algorithms2/1038_감소하는 수.cpp
UHC
2,132
3.515625
4
[]
no_license
#include<iostream> #include<algorithm> #include<cmath> using namespace std; int find_decrease_num, sum = 0; int isGetAnswer = 0, isEndCheck = 0; int num_arr[10][10] = { 0 }; long long answer = 0; // 迭 void make_arr() { // ù for (int j = 0; j < 10; j++) num_arr[0][j] = 1; // 迭 ä for (int i = 1; i < 10; i++) { for (int j = i; j < 10; j++) { if (j == i) num_arr[i][j] = 1; else for (int k = i - 1; k < j; k++) num_arr[i][j] += num_arr[i - 1][k]; } } } int dfs(long long start_num, long long digit, long long now_num) { if (isGetAnswer) return 0; // ڸ 1 ڸ ̸ sum ߰ (ó ڴ ) if (digit == 1) { if (!isEndCheck) isEndCheck = 1; else sum++; } else { // ڸ ڸ ۰ Ʒ ڸ ڸ dfs ϱ for (long long i = digit - 2; i < start_num; i++) dfs(i, digit - 1, now_num + (long long)(i * pow(10, digit - 2))); } // ϸ flag Ѵ. if ((sum == find_decrease_num) && !isGetAnswer) { answer = now_num; isGetAnswer = 1; } } int main() { make_arr(); cin >> find_decrease_num; if (find_decrease_num == 0) { cout << 0; return 0; } long long start_num; long long digit; int isFindRange = 0; // ãƳ. for (int i = 0; i < 10 && (!isFindRange); i++) { for (int j = i; j < 10 && (!isFindRange); j++) { if ((sum + num_arr[i][j]) > find_decrease_num) { isFindRange = 1; } else { digit = i + 1; start_num = j + 1; sum += num_arr[i][j]; } } } // long long now_num = (long long)(start_num * pow(10, digit - 1)); if (find_decrease_num == 1022) { now_num = 9876543210; } // ٷ ã ٷ if (sum == find_decrease_num) { if (sum == 1023) answer = -1; else answer = now_num; } else if (find_decrease_num > 1022) { answer = -1; } // ƴϸ dfs Ž else dfs(start_num, digit, now_num); cout << answer; system("pause"); return 0; }
true
3a3a8783d2d7bd93fd29bf0ab1442c31c8e34d95
C++
NathanWine/2048-AI-Solvers
/src/Main.cpp
UTF-8
5,555
3.390625
3
[]
no_license
#include <cctype> #include <chrono> #include <numeric> #include "Game.hpp" #include "MonteCarlo.hpp" #include "Minimax.hpp" #include "Expectimax.hpp" using namespace std::chrono; // Simple cmd line parsing function to determine if a string is representing a number bool isNumber(const std::string& str) { for (char const &c : str) { if (std::isdigit(c) == 0) { return false; } } return true; } // Simple function to convert a string to lowercase void lowercase(std::string &str) { std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c){ return std::tolower(c); }); } // Simple cmd parser from: https://stackoverflow.com/a/868894/9306928 class CmdParser { public: CmdParser (int &argc, char **argv) { for (int i = 1; i < argc; ++i) { cmds.push_back(std::string(argv[i])); } } const std::string& getCmdOption(const std::string &opt) const { std::vector<std::string>::const_iterator itr; itr = std::find(cmds.begin(), cmds.end(), opt); if (itr != cmds.end() && ++itr != cmds.end()){ return *itr; } static const std::string empty_string(""); return empty_string; } bool cmdOptionExists(const std::string &opt) const { return std::find(cmds.begin(), cmds.end(), opt) != cmds.end(); } private: std::vector<std::string> cmds; }; int main(int argc, char** argv) { enum ALGORITHMS {MONTECARLO, MINIMAX, EXPECTIMAX}; std::map<std::string, int> alg_map = {{"montecarlo", MONTECARLO}, {"minimax", MINIMAX}, {"expectimax", EXPECTIMAX}}; int alg_key = MINIMAX; int num_games = 1; int num_runs = 25; int depth = 1; int print_level = 2; // Parse command-line arguments CmdParser cmd_parser(argc, argv); if (cmd_parser.cmdOptionExists("-h") || cmd_parser.cmdOptionExists("--help") || cmd_parser.cmdOptionExists("help") || cmd_parser.cmdOptionExists("usage")) { std::string msg = "Usage:\ \n AISolver <flag> <flag_val> ...\ \n Flag list:\ \n -a: Integer/String value; Algorithm to run. 0=montecarlo, 1=minimax, 2=expectimax\ \n -n: Integer value; # times to run the algorithm. Stats displayed at program completion\ \n -r: Integer value; # runs MonteCarlo completes for each move. Higher=better but slower. Recommend 10-100\ \n -d: Integer value; # depth level for Minimax / Expectimax\ \n -p: Integer value; Print level. Higher=more display. 0=minimal, 1=medium, 2=high, 3=full\ \n Ex: AISolver -a minimax -n 1 -d 1 -p 3"; std::cout << msg << std::endl; return 0; } if (cmd_parser.cmdOptionExists("-a")) { std::string a_arg = cmd_parser.getCmdOption("-a"); if (isNumber(a_arg)) { alg_key = std::stoi(a_arg); } else { lowercase(a_arg); alg_key = alg_map[a_arg]; } } if (cmd_parser.cmdOptionExists("-n")) { std::string n_option = cmd_parser.getCmdOption("-n"); if (isNumber(n_option)) { num_games = std::stoi(n_option); } } if (cmd_parser.cmdOptionExists("-r")) { std::string r_option = cmd_parser.getCmdOption("-r"); if (isNumber(r_option)) { num_runs = std::stoi(r_option); } } if (cmd_parser.cmdOptionExists("-d")) { std::string d_option = cmd_parser.getCmdOption("-d"); if (isNumber(d_option)) { depth = std::stoi(d_option); } } if (cmd_parser.cmdOptionExists("-p")) { std::string p_option = cmd_parser.getCmdOption("-p"); if (isNumber(p_option)) { print_level = std::stoi(p_option); } } // Set up variables for statistics int successes = 0; std::vector<int> scores; std::vector<int> highest_tiles; high_resolution_clock::time_point t1 = high_resolution_clock::now(); switch (alg_key) { // Run chosen algorithm case MONTECARLO: successes = monteCarloSolve(num_games, num_runs, print_level, scores, highest_tiles); break; case MINIMAX: successes = minimaxSolve(num_games, depth, print_level, scores, highest_tiles); break; case EXPECTIMAX: successes = expectimaxSolve(num_games, depth, print_level, &scores, &highest_tiles); } high_resolution_clock::time_point t2 = high_resolution_clock::now(); duration<double> time_span = duration_cast<duration<double>>(t2 - t1); // Display statistics if (num_games > 1) { std::cout << "Success rate: " << (float) successes / num_games * 100 << "%" << std::endl; float average = std::accumulate(scores.begin(), scores.end(), 0.0) / num_games; std::cout << "Average score: " << average << std::endl; std::cout << "Highest tiles: "; for (int i = 0; i < (int) highest_tiles.size(); ++i) { std::cout << highest_tiles[i] << ", "; } std::cout << std::endl; } else { std::cout << (successes > 0 ? "Game won!" : "Game lost.") << std::endl; std::cout << "Final score: " << scores[0] << std::endl; std::cout << "Highest tile: " << highest_tiles[0] << std::endl; } std::cout << "Time elapsed: " << time_span.count() << " seconds" << std::endl; return 0; }
true
8ed310390a2091ae70467b653f85741ba21888be
C++
Edvvard92/remotesensor
/SA02/remotesenor/climate.hpp
UTF-8
6,965
2.84375
3
[]
no_license
// Developer note stack size needs to be increased to allow the allocation of memory for this double = 8 bytes // 8 * 24 * 60 * 60 * 2 arrays of doubles = 1382400 bytes base allocation is 1MB // In VS2017 go to project > properties > System > and set Stack Reserve Size and Stack Commit Size to 2000000 // This prevents a stack overflow #define maximum_readings 24 * 60 * 60 #define invalid_reading -1000.0 #include <vector>; #include <exception>; #define fakedata 1 // NOTE: Set to 1 use fake sensor values instead of the online values 0 #include <chrono> // System time #include <stdexcept> #if fakedata == 1 #include "fakesensor.hpp" #else #include "http.h" #endif using namespace std; using namespace chrono; class Climate { private: double temperature; double humidity; int samples; int totalSamples; #if fakedata == 1 FakeSensor sensorDevice; #else Http sensorDevice; #endif protected: float tempArray[maximum_readings]; float humArray[maximum_readings]; public: double getTemperature() { return temperature; } double getHumidity() { return humidity; } void setTemperature(double newTemperature) { temperature = newTemperature; } void setHumidity(double newHumidity) { humidity = newHumidity; } system_clock::time_point StartTime; // Constructors Climate(); // Utility void clearSamples(); long sampleCount(long); long sampleTotal(); // Sensor related long readSensor(); // Temperature double getTemperature(long); double averageTemperature(long); double maximumTemperature(long); double minimumTemperature(long); // Humidity double getHumidity(long); double averageHumidity(long); double maximumHumidity(long); double minimumHumidity(long); }; // Constructor Climate::Climate() { StartTime = std::chrono::system_clock::now(); } void Climate::clearSamples() { for (int i = 0; i < maximum_readings; i++) { tempArray[i] = 0; humArray[i] = 0; } } long Climate::readSensor() { sensorDevice.read_data(); system_clock::time_point EndTime = std::chrono::system_clock::now(); std::chrono::duration<double> Period = EndTime - StartTime; int currentSecond = (int)Period.count(); // This line is purely for your debugging and can be removes/commented out in the final code. cout << endl << "Debugging information : " << "Temperature is " << sensorDevice.get_temperature_in_c() << " in degrees C " << sensorDevice.get_humidity() << "% humidity" << endl; tempArray[currentSecond] = sensorDevice.get_temperature_in_c(); //Set setHumidity(sensorDevice.get_humidity()); setTemperature(sensorDevice.get_temperature_in_c()); //Get humArray[currentSecond] = getHumidity(); tempArray[currentSecond] = getTemperature(); if (currentSecond > maximum_readings) { throw out_of_range("Over 24 hour limit"); } if (currentSecond < 1) { throw underflow_error("Less than a 1 second from last sample "); } if (sensorDevice.get_temperature_in_c() == NULL || sensorDevice.get_humidity() == NULL) { throw runtime_error("A read attempt has failed"); } return currentSecond; } long Climate::sampleCount(long secs) { if (secs > maximum_readings || secs < 1) { throw out_of_range("Out of range"); } for (int n = (int)secs; n >= 1; n--) { if (tempArray[n] || humArray[n] != NULL) { samples++; } } return samples; } long Climate::sampleTotal() { for (auto it = begin(tempArray); it != end(tempArray); ++it) { totalSamples++; } return totalSamples; } double Climate::getTemperature(long number_of_seconds) { if (number_of_seconds > maximum_readings || number_of_seconds < 1) { throw out_of_range("Out of range"); } float value = tempArray[number_of_seconds]; if (value == NULL) { throw invalid_argument("No samples at specified time"); } return value; } double Climate::averageTemperature(long number_of_seconds) { if (number_of_seconds > maximum_readings || number_of_seconds < 1) { throw out_of_range("Out of range"); } double average; double sum = 0; for (int i = number_of_seconds; i >= 1; i--) { if (tempArray[i] == NULL) { throw invalid_argument("No samples at specified time"); } sum += tempArray[i]; } average = sum / number_of_seconds; return average; } double Climate::maximumTemperature(long number_of_seconds) { if (number_of_seconds > maximum_readings || number_of_seconds < 1) { throw out_of_range("Out of range"); } double max = tempArray[number_of_seconds]; for (int i = number_of_seconds; i >= 1; i--) { if (tempArray[i] == NULL) { throw invalid_argument("No samples at specified time"); } if (tempArray[i] > max) { max = tempArray[i]; } } return max; } double Climate::minimumTemperature(long number_of_seconds) { if (number_of_seconds > maximum_readings || number_of_seconds < 1) { throw out_of_range("Out of range"); } double min = tempArray[number_of_seconds]; for (int i = number_of_seconds; i >= 1; i--) { if (tempArray[i] == NULL) { throw invalid_argument("No samples at specified time"); } if (tempArray[i] < min) { min = tempArray[i]; } } return min; } double Climate::getHumidity(long number_of_seconds) { if (number_of_seconds > maximum_readings || number_of_seconds < 1) { throw out_of_range("Out of range"); } float value = humArray[number_of_seconds]; if (number_of_seconds == NULL) { throw invalid_argument("No samples at specified time"); } return value; } double Climate::averageHumidity(long number_of_seconds) { double average; double sum = 0; if (number_of_seconds > maximum_readings || number_of_seconds < 1) { throw out_of_range("Out of range"); } for (int i = number_of_seconds; i >= 1; i--) { if (humArray[i] == NULL) { throw invalid_argument("No samples at specified time"); } sum += humArray[i]; } average = sum / number_of_seconds; return average; } double Climate::maximumHumidity(long number_of_seconds) { if (number_of_seconds > maximum_readings || number_of_seconds < 1) { throw out_of_range("Out of range"); } double max = humArray[number_of_seconds]; for (int i = number_of_seconds; i >= 1; i--) { if (humArray[i] == NULL) { throw invalid_argument("No samples at specified time"); } if (humArray[i] > max) { max = humArray[i]; } } return max; } double Climate::minimumHumidity(long number_of_seconds) { if (number_of_seconds > maximum_readings || number_of_seconds < 1) { throw out_of_range("Out of range"); } double min = humArray[number_of_seconds]; for (int i = number_of_seconds; i >= 1; i--) { if (humArray[i] == NULL) { throw invalid_argument("No samples at specified time"); } if (humArray[i] < min) { min = humArray[i]; } } return min; }
true
1003c5ec6253de9d895491a15f4cc8cace69ee70
C++
HangHangbo/C_Plusplus
/test/test/test.cpp
GB18030
6,550
2.921875
3
[]
no_license
//#include <iostream> //#include <vector> //#include <algorithm> //using namespace std; ////int main() ////{ //// int num[4] = { 0 }; //// for (int i = 0; i < 4; i++) //// { //// cin >> num[i]; //// } //// int A, B, C; //// A = (num[0] + num[2]) / 2; //// B = (num[1] + num[3]) / 2; //// C = B - num[1]; //// if ((num[0]==A-B) && (num[1]==B-C) && (num[2]==A+B)&&(num[3]==B+C)) //// { //// cout << A << ' ' << B << ' ' << C << endl; //// } //// else //// { //// cout << "No" << endl; //// } //// system("pause"); //// return 0; ////} ////class A ////{ //// friend long fun(A s) //// { //// if (s.x < 3){ //// return 1; //// } //// return s.x + fun(A(s.x - 1)); //// } ////public: //// A(long a) //// { //// x = a--; //// cout << x << endl; //// } ////private: //// long x; ////}; ////int main() ////{ //// int sum = 0; //// for (int i = 0; i < 5; i++) //// { //// sum += fun(A(i)); //// } //// cout << sum; //// system("pause"); //// return 0; ////} ////int main() ////{ //// int i = 3; //// int a = i++; //// return 0; ////} ////int main() ////{ //// int i = 10; //// int j = 1; //// const int *p1;//(1) //// int const *p2 = &i; //(2) //// p2 = &j;//(3) //// int *const p3 = &i;//(4) //// *p3 = 20;//(5) //// *p2 = 30;//(6) //// p3 = &j;//(7) //// return 0; ////} // // // ////class A ////{ ////public: //// A() :m_iVal(0) //// { //// test(); //// } // 0 //// virtual void func() { //// std::cout << m_iVal; //// } //// void test(){ func(); } ////public: //// int m_iVal; ////}; ////class B : public A ////{ ////public: //// B(){ //// test(); //// } //// virtual void func() //// { //// ++m_iVal; //// std::cout << m_iVal; //1 //// } ////}; ////int main(int argc, char* argv[]) ////{ //// A*p = new B; //// p->test(); //// return 0; ////} ////typedef void (*fF)(); // ////int main() ////{ //// //// unsigned int n = 197; //// n = (n & 0x55555555) + ((n >> 1) & 0x55555555); //// n = (n & 0x33333333) + ((n >> 2) & 0x33333333); //// n = (n & 0x0f0f0f0f) + ((n >> 4) & 0x0f0f0f0f); //// n = (n & 0x00ff00ff) + ((n >> 8) & 0x00ff00ff); //// n = (n & 0x0000ffff) + ((n >> 16) & 0x0000ffff); //// system("pause"); //// return 0; ////} ////int BitCount4(unsigned int n) ////{ //// n = (n & 0x55555555) + ((n >> 1) & 0x55555555); //// n = (n & 0x33333333) + ((n >> 2) & 0x33333333); //// n = (n & 0x0f0f0f0f) + ((n >> 4) & 0x0f0f0f0f); //// n = (n & 0x00ff00ff) + ((n >> 8) & 0x00ff00ff); //// n = (n & 0x0000ffff) + ((n >> 16) & 0x0000ffff); //// //// return n; ////} //int main() //{ // char arr[] = "ABC"; // char arr1[] = { 'A', 'B', 'C' }; // int a[100][100] = {0}; // for (int i = 0; i < 100; j++) // { // for (int j = 0; j < 100; j++) // a[i][j] += a[j][i]; // } // return 0; //} #if 0 //һɶٸ1 #include <iostream> using namespace std; int main() { int n = 0; int count = 0; while (cin >> n) { while (n) { int num = n & 1; if (num == 1) { count++; } n = n >> 1; } cout << count << endl; } system("pause"); return 0; } #endif #if 0 class Gloves { public: int findMinimum(int n, vector<int> left, vector<int> right) { // write code here int sumL = 0, sumR = 0, min = 0; vector<int> arrL, arrR; for (int i = 0; i < n; i++) { if (left[i] == 0 || right[i] == 0) { min += left[i] + right[i]; continue; } sumL += left[i]; arrL.push_back(left[i]); sumR += right[i]; arrR.push_back(right[i]); } if (sumL < sumR) { sort(arrL.begin(), arrL.end()); for (int i = 1; i < arrL.size(); i++) min += arrL[i]; } else { sort(arrR.begin(), arrR.end()); for (int i = 1; i < arrR.size(); i++) min += arrR[i]; } return min + 2; } }; //class Gloves { //public: // int findMinimum(int n, vector<int> left, vector<int> right) { // int MIN = 0, lsum = 0, rsum = 0; // vector<int> tlef, trig; // for (int i = 0; i < n; i++) // { // if (left[i] == 0 || right[i] == 0) // { // MIN += right[i] + left[i]; // continue; // } // lsum += left[i], tlef.push_back(left[i]); // rsum += right[i], trig.push_back(right[i]); // } // if (lsum < rsum) // { // sort(tlef.begin(), tlef.end()); // for (int i = tlef.size() - 1; i > 0; i--) MIN += tlef[i]; // } // else // { // sort(trig.begin(), trig.end()); // for (int i = trig.size() - 1; i > 0; i--) MIN += trig[i]; // } // return MIN + 2; // } //}; int main() { int n = 4; vector<int> left; left.push_back(0); left.push_back(7); left.push_back(1); left.push_back(6); vector<int> right; right.push_back(1); right.push_back(5); right.push_back(0); right.push_back(6); Gloves s; int m = s.findMinimum(n, left, right); return 0; } #endif // //void pint(char *str) //{ // if (*str){ // pint(str++); // printf("%c", *str); // } //} // //int main() //{ // char str[] = "asdfgh"; // pint(str); // system("pause"); // return 0; //} // //#include <iostream> //using namespace std; //bool count(int num) //{ // if (num <= 1) // return false; // int sum=0; // for (int i = 1; i<num; ++i) // { // if (num%i == 0) // sum += i; // } // if (num != sum) // return false; // else // return true; //} //int main() //{ // int n; // while (cin >> n) // { // int g_count = 0; // for (int i = 0; i <= n; i++) // { // g_count += count(i); // } // cout << g_count << endl; // } // system("pause"); // return 0; //} //˿˱ȴС #include <iostream> #include <string> using namespace std; string poker = "345678910JQKA2"; #define printa {cout<<a<<endl; system("pause");return 0;} #define printb {cout<<b<<endl; system("pause");return 0;} int count(const string &a) { int num = 0; auto it = a.begin(); while (it != a.end()) { if (*it == ' ') num++; ++it; } return num; } int main() { string str; getline(cin, str); string a; string b; int len=str.find('-'); a = str.substr(0, len); b = str.substr(len+1); string Max = "joker JOKER"; if (a == Max) { printa; } else if (b == Max) { printb; } //ȡո int count_a = count(a); int count_b = count(b); //ͬ if (count_a == count_b) { string begin_a, begin_b; int pos_a = a.find(' '); begin_a = a.substr(0, pos_a); int pos_b = b.find(' '); begin_b = b.substr(0, pos_b); if (poker.find(begin_a) > poker.find(begin_b)) { printa; } else { printb; } } //һը if (count_a == 3 && count_b != 3) { printa; } else if (count_b == 3 && count_a != 3) { printb; } cout << "ERROR" << endl; system("pause"); return 0; }
true
0e2ef48694a92487e4c7b731c7d281074dd4a63d
C++
refkxh/AIZUOJ_Basic
/ALDS1_7_C.cpp
UTF-8
997
2.890625
3
[]
no_license
#include <cstdio> #include <cstring> using namespace std; int p[30],left[30],right[30]; void preParse (int cur) { printf (" %d",cur); if (left[cur]!=-1) preParse (left[cur]); if (right[cur]!=-1) preParse (right[cur]); } void inParse (int cur) { if (left[cur]!=-1) inParse (left[cur]); printf (" %d",cur); if (right[cur]!=-1) inParse (right[cur]); } void postParse (int cur) { if (left[cur]!=-1) postParse (left[cur]); if (right[cur]!=-1) postParse (right[cur]); printf (" %d",cur); } int main () { int n; scanf ("%d",&n); memset (p,-1,sizeof(p)); memset (left,-1,sizeof(left)); memset (right,-1,sizeof(right)); for (int i=0;i<n;i++) { int id,l,r; scanf ("%d%d%d",&id,&l,&r); left[id]=l; right[id]=r; if (l!=-1) p[l]=id; if (r!=-1) p[r]=id; } for (int i=0;i<n;i++) { if (p[i]==-1) { printf ("Preorder\n"); preParse (i); printf ("\nInorder\n"); inParse (i); printf ("\nPostorder\n"); postParse (i); printf ("\n"); break; } } return 0; }
true
568a7f448cf0fc5f8436f2d75375aa059eb85c5f
C++
JuneOne/Learn-in-C
/PAT/1055.cpp
UTF-8
1,003
2.828125
3
[]
no_license
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; struct node{ char name[10]; int age; int worth; }Peo[100000]; bool cmp( struct node a, struct node b ) { if( a.worth == b.worth ){ if( a.age == b.age ) return strcmp(a.name, b.name) < 0; else return a.age < b.age; } else return a.worth > b.worth; } int main() { int N, K; scanf("%d%d", &N, &K); getchar(); for( int i = 0; i < N; i++ ){ scanf("%s%d%d", Peo[i].name, &Peo[i].age, &Peo[i].worth); getchar(); } sort(Peo, Peo+N, cmp); for( int i = 0; i < K; i++ ){ int cnt, Amin, Amax; bool flag = false; scanf("%d%d%d", &cnt, &Amin, &Amax); printf("Case #%d:\n", i+1); for( int j = 0; j < N && cnt > 0 ; j++ ){ if( Peo[j].age >= Amin && Peo[j].age <= Amax ){ printf("%s %d %d\n", Peo[j].name, Peo[j].age, Peo[j].worth); cnt--; flag = true; } } if( flag == false ) printf("None\n"); } }
true
473a757eea5e97bb96721792268febb1074989dd
C++
yareCandy/Data-Structure
/1606_1.cpp
UTF-8
3,946
2.890625
3
[]
no_license
#include <iostream> using namespace std; const int N = 55; template<class T> class seqQueue { private: T *dt; int maxSize; int front, rear; void doubleSpace(); public: seqQueue(int initSize = 10); ~seqQueue(){delete [] dt;} bool isEmpty()const {return front == rear;} void enQueue(const T &d); T deQueue(); T getHead()const {return dt[(front + 1) % maxSize];} int size(){ if (front <= rear) return rear - front; else return rear + maxSize - front; } }; template<class T> void seqQueue<T>::doubleSpace() { T *tmp = dt; dt = new T [maxSize * 2]; for (int i = 1; i <= maxSize; i++) dt[i] = tmp[(front + i) % maxSize]; front = 0; rear = maxSize; maxSize *= 2; delete [] tmp; } template<class T> seqQueue<T>::seqQueue(int initSize) { dt = new T [initSize]; maxSize = initSize; front = rear = 0; } template<class T> void seqQueue<T>::enQueue(const T &d) { if ((rear+1)%maxSize == front) doubleSpace(); rear = (rear+1) % maxSize; dt[rear] = d; } template<class T> T seqQueue<T>::deQueue() { front = (front + 1) % maxSize; return dt[front]; } struct point { int x, y; point(int X = 0, int Y = 0):x(X), y(Y){} }; char s[N][N]; int n, m, **vis; int num = 0, tot = 0; int dx[] = {-1,1,0,0}; int dy[] = {0,0,-1,1}; seqQueue<point> a(55); void DFS(int x,int y) { vis[x][y] = 1;//标为已经访问 tot ++;//访问过的陆地数+1 if(s[x][y] == '?')//如果是未知那未知的数也要+1 num++; for(int i = 0;i < 4; i++) { int c = x + dx[i]; int d = y + dy[i]; if(c>=1 && c<=n && d>=1 && d<=m && (!vis[c][d]) && s[c][d] != '#') DFS(c,d); } } void find(int x,int y) { vis[x][y] = 1; s[x][y] = '#'; for(int i = 0; i < 4; i++) { int a = x + dx[i]; int b = y + dy[i]; if(a>=1 && a<=n && b>=1 && b<=m && (!vis[a][b]) && (s[a][b]=='?')) find(a,b); } } int check() { int cnt = 0; for (int i = 0; i < n+2; i++){ for (int j = 0; j < m+2; j++) vis[i][j] = 0; } for(int i = 1; i <= n; i++) for(int j = 1; j <= m; j++) if(s[i][j] != '#' && !vis[i][j]) DFS(i,j), cnt++; return cnt; } int main() { point cur; seqQueue<point> b(55);//备用 cin >> n >> m; vis = new int *[n+2]; for (int i = 0; i < n+2; i++) vis[i] = new int [m+2]; for(int i = 1;i <= n; i ++) { cin.get(); for(int j = 1; j <= m; j++) { s[i][j] = cin.get(); if(s[i][j] == '?')//把所有的'?'放在队列中3 a.enQueue(point(i,j)); } } if(check() > 1) { if (num == tot) {cout << "Ambiguous\n"; return 0;} while(!a.isEmpty()) { cur.x = a.getHead().x, cur.y = a.getHead().y; a.deQueue(); if(s[cur.x][cur.y] == '#') continue; num = tot = 0; for (int i = 0; i < n+2; i++) for (int j = 0; j < m+2; j++) vis[i][j] = 0; DFS(cur.x, cur.y); if(num == tot) { for (int i = 0; i < n+2; i++){ for (int j = 0; j < m+2; j++) vis[i][j] = 0; } find(cur.x, cur.y); } else { b.enQueue(cur);//不全是问号联通的区域 } } if(check()>1) { cout << "Impossible\n"; return 0; } } bool flag = true; while (!b.isEmpty()) { int x = b.getHead().x, y = b.getHead().y; b.deQueue(); if(s[x][y] == '#') continue; s[x][y] = '#'; int p = check(); if(p == 1 || p == 0) flag = false; s[x][y] = '.'; } while (!a.isEmpty()) { int x = a.getHead().x, y = a.getHead().y; a.deQueue(); if(s[x][y] == '#') continue; s[x][y] = '#'; int p = check(); if(p == 1 || p == 0) flag = false; s[x][y] = '.'; } if(!flag) cout << "Ambiguous\n"; else for(int i = 1; i <= n; i++){ for(int j = 1; j <= m; j++) cout << s[i][j]; cout << '\n'; } return 0; }
true
461ebf74df989a2103966beb72b39594cbecf69d
C++
dwaq/IR-Closet-Lights
/IR-Closet-Lights.ino
UTF-8
2,295
2.703125
3
[ "CC-BY-3.0" ]
permissive
//************************************************************************************************* // IR-Closet-Lights // // By: Dillon Nichols // https://tinkerer.us // // Created in Arduino v1.8.2 // // Description: // Using Arduino Leonardo to switch lights using IR with door as trigger // // This work is licensed under a Creative Commons Attribution 3.0 Unported License. // https://creativecommons.org/licenses/by/3.0/ //************************************************************************************************* // include IR libraries for using NEC protocol // https://github.com/cyborg5/IRLib2 #include <IRLibSendBase.h> #include <IRLib_P01_NEC.h> #include <IRLibCombo.h> // For debouncing the door switch // Search for "button tiny simple" in the Arduino Library Manager // to find the correct library by Michael Adams #include <Button.h> // switch attached to door on pin 12 Button door(12); // All on or off #define ON 0xFF00FF #define OFF 0xFF807F // Increase or decrease brightness by 10% #define INCR 0xFF40BF #define DECR 0xFFC03F // Set brightness to these percentages #define PCT_10 0xFF20DF #define PCT_40 0xFFA05F #define PCT_80 0xFF906F #define PCT_100 0xFFE01F // Set timer and turn off after this many minutes #define TIM_10 0xFF10EF #define TIM_30 0xFF609F #define TIM_60 0xFF50AF #define TIM_120 0xFFD02F // used to fade lights when switching #define DELAY_ON 200 #define DELAY_OFF 350 IRsend mySender; void setup() { // set door switch as input door.begin(); } void loop() { // When door opens, if (door.pressed()) { // Turn on lights // defaults to 80% on power on mySender.send(NEC, ON, 0); // increase to 100% delay(DELAY_ON); mySender.send(NEC, PCT_100, 0); // shut lights off after 10 minutes if door hasn't been closed delay(DELAY_ON); mySender.send(NEC, TIM_10, 0); } // When door closes if (door.released()) { // Turn off lights // slowly decrease to 10% mySender.send(NEC, PCT_80, 0); delay(DELAY_OFF); mySender.send(NEC, PCT_40, 0); delay(DELAY_OFF); mySender.send(NEC, PCT_10, 0); delay(DELAY_OFF); // then decrease once more to 5% mySender.send(NEC, DECR, 0); delay(DELAY_OFF); // then turn off mySender.send(NEC, OFF, 0); } }
true
c49d849e0568f548b00c44db15e8a0546cd8f739
C++
hannabizon/hannabizon
/zadania do wgrania c++/2V.cpp
UTF-8
611
3.890625
4
[]
no_license
//zdefiniuj tab 10-elementową typu całkowitego //wyświetl 1,4,osttani element //wyświetl wszystkie elementy na 2 sposoby: od 0-9 oraz od 9-0 #include <iostream> using namespace std; int main() { int tab[10] = {0,1,2,3,4,5,6,7,8,9}; cout << tab[0] << " " << tab[3] << " " << tab[9] << endl; // 1 el. tab = tab[0] cout << " " << endl; // separator for(int i=0; i<10; i++){ //wyświetlam od 0-9 cout << tab[i] << endl; } cout << " " << endl; // separator for(int i=9; i>=0; i--){ //wyświetlam od 9-0 cout << tab[i] << endl; } return 0; }
true
59a0555334664f6fd8b0918f2d229da7acd2c702
C++
chandankds/CPP
/Exception/Complex.cpp
UTF-8
804
2.765625
3
[]
no_license
#include"Complex.h" #include"IlligalValueException.h" using namespace pcomplex; complex::complex() : real(0), imag(0) { } complex::complex(int real, int imag)throw (nexception::IlligalException) { if(real < 0 || imag < 0) throw nexception::IlligalException("not good"); this->real = real; this->imag = imag; } void complex::setReal(int real) throw (nexception::IlligalException) { if(real < 0) throw nexception::IlligalException("not good"); this->real = real; } void complex::setImag(int imag) throw (nexception::IlligalException) { if(imag < 0) throw nexception::IlligalException("not good"); this->imag = imag; } int complex::getReal(void) const { return this->real; } int complex::getImag(void) const { return this->imag; }
true
20a3975922679889c8fa6dbcb5178f1d9fb93381
C++
rahulchhabra07/CompetitiveProgramming
/My Programs/simple equation.cpp
UTF-8
575
2.5625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int main() { int n; cin>>n; while(n--) { int sol=1; long a,b,c; cin>>a>>b>>c; for(int x=-100;x<=100&&sol;x++) { for(int y=x+1;y<=100&&sol;y++) { for(int z=y+1;z<=100&&sol;z++) { if(x+y+z==a&&x*y*z==b&&(x*x)+(y*y)+(z*z)==c&&sol) { cout<<x<<' '<<y<<' '<<z<<'\n'; sol=0; } } } } if(sol) { cout<<"No solution.\n"; } } return 0; }
true
8f3bf6fa18315b7ddde36869175c6f1362abe40a
C++
KaynRO/C-Cpp
/C++-20181025T075829Z-001/C++/ALGORITMI/rege2/main.cpp
UTF-8
1,725
2.671875
3
[]
no_license
#include <iostream> #include <vector> #include <fstream> using namespace std; const int maxn = 100005; const int inf = (1 << 30); vector <pair<int, int> > g[maxn]; int n, s, cnt, dp[maxn]; void dfs(int node, int father, int &energy) { dp[node] = -1; for(auto it : g[node]) { if(it.first == father) continue; dfs(it.first, node, energy); if(dp[it.first] - it.second < 0) { ++ cnt; dp[it.first] = energy; } if(dp[it.first] - it.second > dp[node]) dp[node] = dp[it.first] - it.second; } if(dp[node] == -1) { ++ cnt; dp[node] = energy; } } bool check(int energy) { cnt = 0; dfs(1, 0, energy); //cerr << energy << ' ' << cnt << '\n'; return cnt <= s; } int main() { freopen("rege.in", "r", stdin); freopen("rege.out", "w", stdout); int t; cin >> t; while(t --) { cin >> n >> s; int li = 0, ls = inf; for(int i = 1 ; i < n; ++ i) { int x, y, z; cin >> x >> y >> z; g[x].push_back(make_pair(y, z)); g[y].push_back(make_pair(x, z)); li = max(li, z); } int ans = -1; while(li <= ls) { int mid = li + (ls - li) / 2; if(check(mid)) { ans = mid; ls = mid - 1; } else li = mid + 1; } cout << ans << '\n'; for(int i = 1 ; i <= n ; ++ i) { vector <pair<int, int> > ().swap(g[i]); } } }
true
a6001388730ee39a2d8643f13e737a5286fceff0
C++
collisdecus/discover3d
/arcball.h
UTF-8
581
2.640625
3
[ "MIT" ]
permissive
#ifndef ARCBALL_H #define ARCBALL_H #include <QtCore/QPointF> #include <QtGui/QVector3D> #include <QtGui/QQuaternion> //! Arc ball rotation of the level class ArcBall { public: ArcBall(const QVector3D& axis); void push(const QPointF& point, const QQuaternion &transformation); void move(const QPointF& point, const QQuaternion &transformation); void release(const QPointF& point, const QQuaternion &transformation); QQuaternion getRotation() const; private: QQuaternion _rotation; QVector3D _axis; QPointF _lastPosition; bool _pressed; }; #endif // ARCBALL_H
true
2aafbbdc4eab98e3f4bc353270b1498658219c18
C++
shrumo/rbggamemanager
/tests/arimaa_test.cc
UTF-8
9,061
2.53125
3
[]
no_license
// // Created by shrum on 30.06.19. // #include <game_state/construction/game_state_creator.h> #include <utility/calculate_perft.h> #include <utility/printer.h> #include <iostream> namespace { using namespace rbg; using namespace std; const char *kArimaaGame = R"LIM( // Arimaa // -- The state after the move must be different. // -- No rule forbidding a state repeated three times. // -- Play is limited to 200 turns excluding initial setup. #turnlimit = 199 #colorPieces(color) = color~Elephant, color~Camel, color~Horse, color~Dog, color~Cat, color~Rabbit #players = gold(100), silver(100) #pieces = colorPieces(gold), colorPieces(silver), goldRabbitSecond, silverRabbitSecond, empty #variables = turn(turnlimit), steps(4), changed(1) #emptyLayer = [[empty , empty , empty , empty , empty , empty , empty , empty] [empty , empty , empty , empty , empty , empty , empty , empty ] [empty , empty , empty , empty , empty , empty , empty , empty ] [empty , empty , empty , empty , empty , empty , empty , empty ] [empty , empty , empty , empty , empty , empty , empty , empty ] [empty , empty , empty , empty , empty , empty , empty , empty ] [empty , empty , empty , empty , empty , empty , empty , empty ] [empty , empty , empty , empty , empty , empty , empty , empty ]] #board = cuboid(up,down,left,right,backLayer,frontLayer, emptyLayer emptyLayer) #anySquare = (left* + right*)(up* + down*) #anyNeighborSquare = (left + right + up + down) #setupPiece(color; piece; backward) = (anySquare {! backward^2} {empty} ->> [color~piece]) #setupPlayer(color; backward) = ( ({$ color~Elephant < 1} + {$ color~Camel < 1} + {$ color~Horse < 2} + {$ color~Dog < 2} + {$ color~Cat < 2} + {$ color~Rabbit < 8}) ->color ( {$ color~Elephant < 1} setupPiece(color; Elephant; backward) + {$ color~Camel < 1} setupPiece(color; Camel; backward) + {$ color~Horse < 2} setupPiece(color; Horse; backward) + {$ color~Dog < 2} setupPiece(color; Dog; backward) + {$ color~Cat < 2} setupPiece(color; Cat; backward) + {$ color~Rabbit < 8} setupPiece(color; Rabbit; backward) ) )* {$ color~Elephant == 1} {$ color~Camel == 1} {$ color~Horse == 2} {$ color~Dog == 2} {$ color~Cat == 2} {$ color~Rabbit == 8} #fireTrap = ( {colorPieces(gold)} ({? anyNeighborSquare {colorPieces(gold)}} + {! anyNeighborSquare {colorPieces(gold)}} [empty] [$ changed = 1]) + {colorPieces(silver)} ({? anyNeighborSquare {colorPieces(silver)}} + {! anyNeighborSquare {colorPieces(silver)}} [empty] [$ changed = 1]) + {empty} ) #fireTraps = ( anySquare left^7 up^7 right^2 down^2 fireTrap right^3 fireTrap down^3 fireTrap left^3 fireTrap ) #isFrozen(color; oppColor) = ( {! anyNeighborSquare {colorPieces(color)}} {? {color~Camel} anyNeighborSquare {oppColor~Elephant} + {color~Horse} anyNeighborSquare {oppColor~Elephant,oppColor~Camel} + {color~Dog} anyNeighborSquare {oppColor~Elephant,oppColor~Camel,oppColor~Horse} + {color~Cat} anyNeighborSquare {oppColor~Elephant,oppColor~Camel,oppColor~Horse,oppColor~Dog} + {color~Rabbit} anyNeighborSquare {oppColor~Elephant,oppColor~Camel,oppColor~Horse,oppColor~Dog,oppColor~Cat} } ) #basicMoveRabbit(color; oppColor; forward) = ( {color~Rabbit} [empty] ( left {empty} [color~Rabbit] + right {empty} [color~Rabbit] + forward {empty} [color~Rabbit] [$ changed = 1] ) ) #basicMovePiece(color; piece) = ( {color~piece} [empty] ( left {empty} [color~piece] + right {empty} [color~piece] + up {empty} [color~piece] + down {empty} [color~piece] ) ) #basicMove(color; oppColor; forward) = ( ( basicMovePiece(color; Elephant) + basicMovePiece(color; Camel) + basicMovePiece(color; Horse) + basicMovePiece(color; Dog) + basicMovePiece(color; Cat) + basicMoveRabbit(color; oppColor; forward) ) ) #displace(color; dir) = ( {color~Rabbit} [empty] dir {empty} [color~Rabbit] + {color~Cat} [empty] dir {empty} [color~Cat] + {color~Dog} [empty] dir {empty} [color~Dog] + {color~Horse} [empty] dir {empty} [color~Horse] + {color~Camel} [empty] dir {empty} [color~Camel] + {color~Elephant} [empty] dir {empty} [color~Elephant] ) #pushMovePiece(color; piece; weakerPieces; oppColor) = ( ( left weakerPieces (displace(oppColor; left) right + displace(oppColor; up) down + displace(oppColor; down) up) + right weakerPieces (displace(oppColor; right) left + displace(oppColor; up) down + displace(oppColor; down) up) + up weakerPieces (displace(oppColor; left) right + displace(oppColor; right) left + displace(oppColor; up) down) + down weakerPieces (displace(oppColor; left) right + displace(oppColor; right) left + displace(oppColor; down) up) ) [color~piece] ) #pullMovePiece(color; piece; weakerPieces; oppColor) = ( ( left {empty} [color~piece] right + right {empty} [color~piece] left + up {empty} [color~piece] down + down {empty} [color~piece] up ) ( left weakerPieces displace(oppColor; right) + right weakerPieces displace(oppColor; left) + up weakerPieces displace(oppColor; down) + down weakerPieces displace(oppColor; up) ) ) #pushOrPullMovePiece(color; piece; weakerPieces; oppColor) = ( {color~piece} [empty] ( pushMovePiece(color; piece; weakerPieces; oppColor) + pullMovePiece(color; piece; weakerPieces; oppColor) ) ) #pushOrPullMove(color; oppColor) = ( pushOrPullMovePiece(color; Elephant; {oppColor~Camel,oppColor~Horse,oppColor~Dog,oppColor~Cat,oppColor~Rabbit}; oppColor) + pushOrPullMovePiece(color; Camel; {oppColor~Horse,oppColor~Dog,oppColor~Cat,oppColor~Rabbit}; oppColor) + pushOrPullMovePiece(color; Horse; {oppColor~Dog,oppColor~Cat,oppColor~Rabbit}; oppColor) + pushOrPullMovePiece(color; Dog; {oppColor~Cat,oppColor~Rabbit}; oppColor) + pushOrPullMovePiece(color; Cat; {oppColor~Rabbit}; oppColor) ) #forEachPiece(actionBegin; actionEnd) = ( {empty} actionBegin empty actionEnd + {goldElephant} actionBegin goldElephant actionEnd + {goldCamel} actionBegin goldCamel actionEnd + {goldHorse} actionBegin goldHorse actionEnd + {goldDog} actionBegin goldDog actionEnd + {goldCat} actionBegin goldCat actionEnd + {goldRabbit} actionBegin goldRabbitSecond actionEnd + {silverElephant} actionBegin silverElephant actionEnd + {silverCamel} actionBegin silverCamel actionEnd + {silverHorse} actionBegin silverHorse actionEnd + {silverDog} actionBegin silverDog actionEnd + {silverCat} actionBegin silverCat actionEnd + {silverRabbit} actionBegin silverRabbitSecond actionEnd ) #isDifferentPieceInConfigurations = {! forEachPiece(backLayer {;})} #isConfigurationDifferent = {? anySquare isDifferentPieceInConfigurations} #isConfigurationSame = {! anySquare isDifferentPieceInConfigurations} #copyConfiguration = ( (anySquare {! forEachPiece(backLayer {;})} ->> forEachPiece(backLayer [;]) frontLayer)* isConfigurationSame ) #checkWin = ( {$ goldRabbit > 0} {$ silverRabbit > 0} {! anySquare {! down} {silverRabbit}} {! anySquare {! up} {goldRabbit}} + ({$ goldRabbit == 0} + {? anySquare {! down} {silverRabbit}}) [$ silver=100, gold=0] ->> {} + ({$ silverRabbit == 0} + {? anySquare {! up} {goldRabbit}}) [$ gold=100, silver=0] ->> {} ) #turn(color; oppColor; forward; backward) = ( copyConfiguration ->color [$ steps = 4] [$ changed = 0] ( {$ steps > 0} anySquare {colorPieces(color)} {! isFrozen(color; oppColor)} ( [$ steps = steps-1] basicMove(color; oppColor; forward) + [$ steps = steps-2] pushOrPullMove(color; oppColor) ) fireTraps checkWin )* ( {$ changed == 1} + {$ steps == 1} + {$ steps == 3} + {$ changed == 0} ({$ steps == 0} + {$ steps == 2}) isConfigurationDifferent ) ->> ( {$ turn < turnlimit} [$ color=100, oppColor=0] + {$ turn == turnlimit} [$ color=50, oppColor=50] ->> {} ) [$ turn = turn+1] ) #rules = setupPlayer(gold; down) setupPlayer(silver; up) ->> ( turn(gold; silver; up; down) turn(silver; gold; down; up) )* )LIM"; } // namespace int main() { auto game = CreateGameState(kArimaaGame); auto result = Perft(game, 2); assert(result.leaves_count == 8160); assert(result.nodes_count == 8257); game.Apply(game.Moves()[0]); std::cout << RectangularBoardDescription(game.board_content(), game.declarations()); }
true
1a75350403b056e48297612eff14599d233facea
C++
bayanbatn/fcam
/include/FCam/TSQueue.h
UTF-8
16,834
3.078125
3
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#ifndef FCAM_TSQUEUE_H #define FCAM_TSQUEUE_H #include <deque> #include <iterator> #include <semaphore.h> #include <pthread.h> #include <errno.h> #include <string.h> #include "Base.h" //#include "../../src/Debug.h" /** \file * A basic thread-safe queue using pthread mutexes to wrap a * C++ STL queue. Convenient to use for devices, etc, if they need a * background control thread. This could probably be done with no locks, * since it's just mostly used as a producer-consumer queue. But this way * we don't have to worry about it, and lock contention has not appeared * to be a problem yet. */ namespace FCam { /** Basic thread-safe consumer/producer queue. Safe for multiple * producers, but not for multiple consumers. The consumer will * typically call wait(), pop(), front(), and pull, while * producers mostly uses push(). */ template<typename T> class TSQueue { public: TSQueue(); ~TSQueue(); /** A thread-safe iterator to access the queue. Constructing * this locks the queue. Allows algorithms to be run on the queue atomically. */ class locking_iterator; /** Add a copy of item to the back of the queue. */ void push(const T& val); /** Remove the frontmost element from the queue. */ void pop(); /** Add a copy of item to the front of the queue. */ void pushFront(const T& val); /** Remove the backmost element from the queue. */ void popBack(); /** Return a reference to the frontmost element of the queue. * Behavior not defined if size() == 0 */ T& front(); const T& front() const; /** Return a reference to the backmost element of the queue. * Behavior not defined if size() == 0 */ T& back(); const T& back() const; /** Returns true if empty, false otherwise. */ bool empty() const; /** Returns the number of items in the queue */ size_t size() const; /** Waits until there are entries in the queue. * The optional timeout is in microseconds, zero means no timeout. */ bool wait(unsigned int timeout=0); /** Waits for the queue not to be empty, and then copies the * frontmost item, then pops it from the queue and returns the * element copy. A convenience function, which is somewhat * inefficient if T is a large class (so use it on * pointer-containing queues, mostly). This is the only safe * way for multiple consumers to use the queue. */ T pull(); /** Pulls the backmost element off the queue. */ T pullBack(); /** Atomically either dequeue an item, or fail to do so. Does * not block. Returns whether it succeeded. */ bool tryPull(T *); bool tryPullBack(T *); /** Create an iterator referring to the front of the queue and * locks the queue. Queue will remain locked until all the * locked_iterators referring to it are destroyed. */ locking_iterator begin(); /** Create an iterator referring to the end of the queue and * locks the queue. Queue will remain locked until all the * iterators referring to it are destroyed. */ locking_iterator end(); /** Deletes an entry referred to by a locking_iterator. Like a * standard deque, if the entry erased is at the start or end * of the queue, other iterators remain valid. Otherwise, all * iterators and references are invalidated. Returns true if * entry is successfully deleted. Failure can occur if some * other thread(s) successfully reserved a queue entry/entries * before the locking iterator claimed the queue.*/ bool erase(TSQueue<T>::locking_iterator); private: std::deque<T> q; mutable pthread_mutex_t mutex; sem_t *sem; friend class locking_iterator; }; template<typename T> class TSQueue<T>::locking_iterator: public std::iterator< std::random_access_iterator_tag, T> { public: locking_iterator(); locking_iterator(TSQueue<T> *, typename std::deque<T>::iterator i); locking_iterator(const TSQueue<T>::locking_iterator &); ~locking_iterator(); locking_iterator& operator=(const TSQueue<T>::locking_iterator &); locking_iterator& operator++(); locking_iterator operator++(int); locking_iterator& operator--(); locking_iterator operator--(int); locking_iterator operator+(int); locking_iterator operator-(int); locking_iterator& operator+=(int); locking_iterator& operator-=(int); int operator-(const TSQueue<T>::locking_iterator &); bool operator==(const TSQueue<T>::locking_iterator &other); bool operator!=(const TSQueue<T>::locking_iterator &other); bool operator<(const TSQueue<T>::locking_iterator &other); bool operator>(const TSQueue<T>::locking_iterator &other); bool operator<=(const TSQueue<T>::locking_iterator &other); bool operator>=(const TSQueue<T>::locking_iterator &other); T& operator*(); T* operator->(); private: TSQueue *parent; typename std::deque<T>::iterator qi; friend class TSQueue<T>; }; template<typename T> TSQueue<T>::TSQueue() { pthread_mutexattr_t mutexAttr; pthread_mutexattr_init(&mutexAttr); pthread_mutexattr_settype(&mutexAttr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&mutex, &mutexAttr); #ifdef FCAM_PLATFORM_OSX // unnamed semaphores not supported on OSX char semName[256]; // Create a unique semaphore name for this TSQueue using its pointer value snprintf(semName, 256, "FCam::TSQueue::sema::%llx", (long long unsigned)this); sem = sem_open(semName, O_CREAT, 0600, 0); if (sem == SEM_FAILED) { fcamPanic("TSQueue::TSQueue: Unable to initialize semaphore %s: %s", semName, strerror(errno)); } #else sem = new sem_t; int success = sem_init(sem, 0, 0); if (success == -1) { fcamPanic("TSQueue::TSQueue: Unable to initialize semaphore: %s", strerror(errno)); } #endif //dprintf(6,"TSQueue %llx initialized\n", (long long unsigned)this); } template<typename T> TSQueue<T>::~TSQueue() { pthread_mutex_destroy(&mutex); #ifdef FCAM_PLATFORM_OSX int success = sem_close(sem); char semName[256]; // Recreate the unique semaphore name for this TSQueue using its pointer value snprintf(semName, 256, "FCam::TSQueue::sema::%llx", (long long unsigned)this); if (success == 0) success = sem_unlink(semName); if (success == -1) { fcamPanic("TSQueue::~TSQueue: Unable to destroy semaphore %s: %s\n", semName, strerror(errno)); } #else int success = sem_destroy(sem); if (success == -1) { fcamPanic("TSQueue::~TSQueue: Unable to destroy semaphore: %s\n", strerror(errno)); } delete sem; #endif } template<typename T> void TSQueue<T>::push(const T& val) { //dprintf(6, "Pushing to queue %llx\n",(long long unsigned)this); pthread_mutex_lock(&mutex); q.push_back(val); pthread_mutex_unlock(&mutex); sem_post(sem); } template<typename T> void TSQueue<T>::pushFront(const T& val) { pthread_mutex_lock(&mutex); q.push_front(val); pthread_mutex_unlock(&mutex); sem_post(sem); } template<typename T> void TSQueue<T>::pop() { // Only safe for a single consumer!!! sem_wait(sem); pthread_mutex_lock(&mutex); q.pop_front(); pthread_mutex_unlock(&mutex); } template<typename T> void TSQueue<T>::popBack() { // Only safe for a single consumer!!! sem_wait(sem); pthread_mutex_lock(&mutex); q.pop_back(); pthread_mutex_unlock(&mutex); } template<typename T> T& TSQueue<T>::front() { pthread_mutex_lock(&mutex); T &val = q.front(); pthread_mutex_unlock(&mutex); return val; } template<typename T> const T& TSQueue<T>::front() const{ const T &val; pthread_mutex_lock(&mutex); val = q.front(); pthread_mutex_unlock(&mutex); return val; } template<typename T> T& TSQueue<T>::back() { pthread_mutex_lock(&mutex); T& val = q.back(); pthread_mutex_unlock(&mutex); return val; } template<typename T> const T& TSQueue<T>::back() const { const T &val; pthread_mutex_lock(&mutex); val = q.back(); pthread_mutex_unlock(&mutex); return val; } template<typename T> bool TSQueue<T>::empty() const { bool _empty; pthread_mutex_lock(&mutex); _empty = q.empty(); pthread_mutex_unlock(&mutex); return _empty; } template<typename T> size_t TSQueue<T>::size() const { size_t _size; pthread_mutex_lock(&mutex); _size = q.size(); pthread_mutex_unlock(&mutex); return _size; } template<typename T> bool TSQueue<T>::wait(unsigned int timeout) { bool res; int err; if (timeout == 0) { err=sem_wait(sem); } else { #ifndef FCAM_PLATFORM_OSX // No clock_gettime or sem_timedwait on OSX timespec tv; // This will overflow around 1 hour or so of timeout clock_gettime(CLOCK_REALTIME, &tv); tv.tv_nsec += timeout*1000; tv.tv_sec += tv.tv_nsec / 1000000000; tv.tv_nsec = tv.tv_nsec % 1000000000; err=sem_timedwait(sem, &tv); #else err=sem_trywait(sem); #endif } if (err == -1) { switch (errno) { case EINTR: case ETIMEDOUT: res = false; break; default: //error(Event::InternalError, "TSQueue::wait: Unexpected error from wait on semaphore: %s", strerror(errno)); res = false; break; } } else { res = true; sem_post(sem); // Put back the semaphore since we're not actually popping } return res; } template<typename T> T TSQueue<T>::pull() { //dprintf(6, "Pulling from queue %llx\n",(long long unsigned)this); sem_wait(sem); pthread_mutex_lock(&mutex); T copyVal = q.front(); q.pop_front(); pthread_mutex_unlock(&mutex); //dprintf(6, "Done pull from queue %llx\n",(long long unsigned)this); return copyVal; } template<typename T> T TSQueue<T>::pullBack() { sem_wait(sem); pthread_mutex_lock(&mutex); T copyVal = q.back(); q.pop_back(); pthread_mutex_unlock(&mutex); return copyVal; } template<typename T> bool TSQueue<T>::tryPull(T *ptr) { if (sem_trywait(sem)) return false; pthread_mutex_lock(&mutex); T copyVal = q.front(); q.pop_front(); pthread_mutex_unlock(&mutex); *ptr = copyVal; return true; } template<typename T> bool TSQueue<T>::tryPullBack(T *ptr) { if (sem_trywait(sem)) return false; pthread_mutex_lock(&mutex); T copyVal = q.back(); q.pop_back(); pthread_mutex_unlock(&mutex); *ptr = copyVal; return true; } template<typename T> typename TSQueue<T>::locking_iterator TSQueue<T>::begin() { return locking_iterator(this, q.begin()); } template<typename T> typename TSQueue<T>::locking_iterator TSQueue<T>::end() { return locking_iterator(this, q.end()); } template<typename T> bool TSQueue<T>::erase(TSQueue<T>::locking_iterator li) { /* Since we're erasing, decrement semaphore. */ if (sem_trywait(sem)) { return false; } q.erase(li.qi); return true; } template<typename T> TSQueue<T>::locking_iterator::locking_iterator() : parent(NULL), qi() {} template<typename T> TSQueue<T>::locking_iterator::locking_iterator(TSQueue<T> *p, typename std::deque<T>::iterator i) : parent(p), qi(i) { if (parent) { pthread_mutex_lock(&(parent->mutex)); } } template<typename T> TSQueue<T>::locking_iterator::locking_iterator(const TSQueue<T>::locking_iterator &other): parent(other.parent), qi(other.qi) { if (parent) { pthread_mutex_lock(&(parent->mutex)); } } template<typename T> TSQueue<T>::locking_iterator::~locking_iterator() { if (parent) { pthread_mutex_unlock(&(parent->mutex)); } } template<typename T> typename TSQueue<T>::locking_iterator &TSQueue<T>::locking_iterator::operator=(const TSQueue<T>::locking_iterator &other) { if (&other == this) return (*this); if (parent && other.qi == qi) return (*this); if (parent) pthread_mutex_unlock(&(parent->mutex)); parent = other.parent; qi = other.qi; if (parent) pthread_mutex_lock(&(parent->mutex)); } template<typename T> typename TSQueue<T>::locking_iterator &TSQueue<T>::locking_iterator::operator++() { qi++; return (*this); } template<typename T> typename TSQueue<T>::locking_iterator TSQueue<T>::locking_iterator::operator++(int) { typename TSQueue<T>::locking_iterator temp(*this); qi++; return temp; } template<typename T> typename TSQueue<T>::locking_iterator &TSQueue<T>::locking_iterator::operator--() { qi--; return (*this); } template<typename T> typename TSQueue<T>::locking_iterator TSQueue<T>::locking_iterator::operator--(int) { typename TSQueue<T>::locking_iterator temp(*this); qi--; return temp; } template<typename T> typename TSQueue<T>::locking_iterator TSQueue<T>::locking_iterator::operator+(int n) { typename TSQueue<T>::locking_iterator temp(*this); temp+=n; return temp; } template<typename T> typename TSQueue<T>::locking_iterator operator+(int n, typename TSQueue<T>::locking_iterator l) { return l+n; } template<typename T> typename TSQueue<T>::locking_iterator TSQueue<T>::locking_iterator::operator-(int n) { typename TSQueue<T>::locking_iterator temp(*this); temp-=n; return temp; } template<typename T> typename TSQueue<T>::locking_iterator &TSQueue<T>::locking_iterator::operator+=(int n) { qi += n; return *this; } template<typename T> typename TSQueue<T>::locking_iterator &TSQueue<T>::locking_iterator::operator-=(int n) { qi -= n; return *this; } template<typename T> int TSQueue<T>::locking_iterator::operator-(const TSQueue<T>::locking_iterator &other) { return qi - other.qi; } template<typename T> bool TSQueue<T>::locking_iterator::operator==(const TSQueue<T>::locking_iterator &other) { return qi == other.qi; } template<typename T> bool TSQueue<T>::locking_iterator::operator!=(const TSQueue<T>::locking_iterator &other) { return qi != other.qi; } template<typename T> bool TSQueue<T>::locking_iterator::operator<(const TSQueue<T>::locking_iterator &other) { return qi < other.qi; } template<typename T> bool TSQueue<T>::locking_iterator::operator>(const TSQueue<T>::locking_iterator &other) { return qi > other.qi; } template<typename T> bool TSQueue<T>::locking_iterator::operator<=(const TSQueue<T>::locking_iterator &other) { return qi <= other.qi; } template<typename T> bool TSQueue<T>::locking_iterator::operator>=(const TSQueue<T>::locking_iterator &other) { return qi >= other.qi; } template<typename T> T& TSQueue<T>::locking_iterator::operator*() { return *qi; } template<typename T> T* TSQueue<T>::locking_iterator::operator->() { return &(*qi); } } #endif
true
53347a3850667e8db53cb30c32a400b40ee48c40
C++
mnofresno/temperature_wifi_logger
/FirmwareUpdater.h
UTF-8
589
2.515625
3
[]
no_license
#ifndef __FIRMWARE_UPDATER_H__ #define __FIRMWARE_UPDATER_H__ #include <ESP8266WebServer.h> typedef std::function<void(void)> THandlerFunction; class FirmwareUpdater { public: void setup(const char* username, const char* password, ESP8266WebServer *server); void handle(); private: void setup_root_path(); void setup_update_path(); void authenticate_and_handle(THandlerFunction handler); void handle_update(); void finish_update(); ESP8266WebServer *_server; const char* _username; const char* _password; }; #endif //ESP8266WEBSERVER_H
true
4f4cd06a764a817ceeb688131429592f85a53bb1
C++
dimitarbez/JaniS
/Vezba 6/Buzzer-photoresistor_sensor/Buzzer-photoresistor_sensor.ino
UTF-8
1,017
2.8125
3
[]
no_license
int lightPin = 0; int led = 11; long previousMillis = 0; long interval = 100; int buzzer=8; // the setup routine runs once when you press reset: void setup() { // initialize the digital pin as an output. pinMode(lightPin, OUTPUT); pinMode(led, OUTPUT); // open the serial port at 9600 bps: Serial.begin(9600); } // the loop routine runs over and over again forever: void loop() { // using millis() instead of delay unsigned long currentMillis = millis(); if(currentMillis - previousMillis > interval) { // save the last time you checked the sensor previousMillis = currentMillis; // read value from sensor int reading = analogRead(lightPin); int ledvalue = reading / 2.67; //log values to Serial Monitor Serial.println("Light value / LED value"); Serial.print(reading); Serial.print(" / "); Serial.println(ledvalue); if (led==HIGH,buzzer, HIGH); //set the brigthness of LED analogWrite(led, ledvalue); } }
true
ad64818f13350a84fc578f251204fae422b0547e
C++
LeMinhTinh/Broblocks
/C++/Lambda/LambdaExpression.cpp
UTF-8
1,601
3.46875
3
[]
no_license
#include "stdafx.h" #include "iostream" #include "LambdaExpression.h" using namespace std; void LambdaExpression::InOutLambdaExpression() { auto l = [] { if (1) { std::cout << "hello lamb1" << std::endl; } else { std::cout << "hello lambda" << std::endl; } }; auto function = [](int a, int b)->int{ if (a > b) return a; else return b; }; l(); cout << "This is lambda: " << function(3, 4) << endl; int tmp; auto swap = [tmp](int a, int b){ a = a + b; b = a - b; a = a - b; cout << "after swap: " << a << endl; cout << "after swap: " << b << endl; }; swap(100, 200); } int LambdaExpression::TinhGiaiThua(int a) { if (a <=1 ) return 1; else { return a * TinhGiaiThua(a - 1); } } void LambdaExpression::AutoFunction() { /*int a = 10; double b = 20; auto b = a; cout << "Auto Function:"<< b;*/ } void LambdaExpression::swap(int *xp, int *yp) { int temp = *xp; *xp = *yp; *yp = temp; } void LambdaExpression::PrintArray(int arr[], int n) { for (int i = 0; i < n; i++) { cout << arr[i] << " "; } } void LambdaExpression::SelectionSort(int arr[], int n) { int _min_index; for (int i = 0; i < n -1; i++) { _min_index = i; for (int j = i + 1; j < n; j++) { if (arr[_min_index] > arr[j]) { _min_index = j; } } swap(&arr[_min_index], &arr[i]); } for (int i = 0; i < n; i++) { cout << arr[i] << " "; } } void LambdaExpression::BubleSort(int arr[], int n) { for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if (arr[i] > arr[j]) { swap(&arr[i], &arr[j]); } } } }
true
222a29206ee08014509f6717288f86a36348653e
C++
Sebastiaan-Alvarez-Rodriguez/Occulis
/src/Camera.cpp
UTF-8
2,034
3.0625
3
[]
no_license
#include "Camera.h" #include "error.hpp" Camera::Camera() { cam_update(); errCheck(); } void Camera::rotate(rotdir d, float amt) { switch (d) { case rotdir::LEFT: cam_phi -= amt; break; case rotdir::RIGHT: cam_phi += amt; break; case rotdir::UP: cam_theta -= amt; break; case rotdir::DOWN: cam_theta += amt; break; } cam_update(); } void Camera::move(movedir d, float amt) { switch (d) { case movedir::LEFT: cam_pos.x += std::sin(cam_phi) * amt; cam_pos.z -= std::cos(cam_phi) * amt; break; case movedir::RIGHT: cam_pos.x -= std::sin(cam_phi) * amt; cam_pos.z += std::cos(cam_phi) * amt; break; case movedir::UP: cam_pos.y += amt; break; case movedir::DOWN: cam_pos.y -= amt; break; case movedir::FORWARD: cam_pos.x += std::cos(cam_phi) * std::sin(cam_theta) * amt; cam_pos.y += std::cos(cam_theta) * amt; cam_pos.z += std::sin(cam_phi) * std::sin(cam_theta) * amt; break; case movedir::BACKWARD: cam_pos.x -= std::cos(cam_phi) * std::sin(cam_theta) * amt; cam_pos.y -= std::cos(cam_theta) * amt; cam_pos.z -= std::sin(cam_phi) * std::sin(cam_theta) * amt; break; } cam_update(); } glm::mat4 Camera::getView() const{ return view; } void Camera::cam_update() { if(cam_phi < -M_PI) cam_phi = M_PI; else if(cam_phi > M_PI) cam_phi = -M_PI; if(cam_theta < 0.001f) cam_theta = 0.001f; else if(cam_theta > M_PI - 0.001f) cam_theta = M_PI - 0.001f; view = glm::lookAt( cam_pos, cam_pos + glm::vec3(std::cos(cam_phi)*std::sin(cam_theta), std::cos(cam_theta), std::sin(cam_phi)*std::sin(cam_theta)), {0,1,0} ); }
true
c0cbc49d8f7fd5df691138edf5ef749638af87e1
C++
123pk/100DaysCoding-Part-3
/Day51/C - Reorder Cards.cpp
UTF-8
1,010
2.921875
3
[]
no_license
/* Platform :- Atcoder Contest :- Atcoder Beginner Contest 213 Approach :- sort A and B separately and for pair A[i] and B[i] and store the rank of A[i] and B[i] when you sort them and print the rank. */ #include<bits/stdc++.h> using namespace std; int main(){ long long h,w; int n; cin>>h>>w>>n; vector<long long>A(n),B(n); vector<pair<long long,long long>>z; for(int i=0;i<n;++i){ cin>>A[i]>>B[i]; z.push_back({A[i],B[i]}); } sort(A.begin(),A.end()); sort(B.begin(),B.end()); set<long long>unq_r,unq_c; for(auto &x:A)unq_r.insert(x); for(auto &x:B)unq_c.insert(x); int c=1; map<long long,int>P,Q; for(auto &x:unq_r){ P[x]=c; c++; } c=1; for(auto &x:unq_c){ Q[x]=c; c++; } for(int i=0;i<n;++i){ int r = P[z[i].first]; int c= Q[z[i].second]; cout<<(r)<<" "<<(c)<<"\n"; } }
true
a815f99fb7de6eb32848325325d88a653542c4d8
C++
Armstrm6/C-Semester-1
/Lab 6/tesla.cpp
UTF-8
6,885
3.046875
3
[]
no_license
#include <iostream> #include <vector> #include <stdlib.h> #include <time.h> #include <iomanip> using namespace std; void Start(); int Design(); int play(); char UMove(); int Emusk(); int bubble(); int Fail(); char Game[15][15]; char Obj[15][15]; int x=0; int y=0; int a1; int a2; int b1; int b2; int c1; int c2; int d1; int d2; int p1; int p2; int p3; int p4; int C=0; int F=0; int W=0; int L=0; int main() { cout<<"The rules of the game are simple\n1: Avoid Elon Musk he will only let you escape once\n2: Find the Roadster labeled by \'R\'\n3: If Elon Musk Captures you or you enter the wrong vehichle, YOU LOSE!"<<endl; Start(); } //intitializes all the functions and game board void Start(){ int p=0; char ans; while(p!=2){ Design(); play(); cout<<"Do you want to play again? [y/n] "<<endl; cin>>ans; if(ans=='y'||ans=='Y'){ p=0; } if(ans=='n'||ans=='N'){ p=2; cout<<"Wins: "<<W<<" \nTimes you became STARMAN: "<<L<<endl; } } } //Designs the Game board an initializes all the game pieces in a second array stored in (x,y) varaibles... All random int Design(){ C=0; srand(time(NULL)); int x=0; int y=0; for(x=0;x<15;x++){ for(y=0;y<15;y++){ Game[x][y]='*'; } } a1=rand()%15; a2=rand()%15; b1=rand()%15; b2=rand()%15; c1=rand()%15; c2=rand()%15; d1=rand()%15; d2=rand()%15; p1=rand()%15; p2=rand()%15; Obj[a1][a2]='R'; while(b1==a1&&b2==a2){ b1=rand()%15; b2=rand()%15; } while((c1==b1&&c2==b2)||(c1==a1&&c2==a2)){ c1=rand()%15; c2=rand()%15; } while((d1==b1&&d2==b2)||(d1==a1&&d2==a2)||(d1==c1&&d2==c2)){ d1=rand()%15; d2=rand()%15; } while((p1==b1&&p2==b2)||(p1==a1&&p2==a2)||(p1==c1&&p2==c2)||(p1==d1&&p2==d2)){ p1=rand()%15; p2=rand()%15; } Obj[b1][b2]='P'; Obj[c1][c2]='Y'; Obj[d1][d2]='E'; Game[p1][p2]='@'; return 0; } //Analysis the player's input to move the piece around the board, it also will alert the player if they are colder or warmer to the desiered end. char UMove(){ char M; cin>>M; p3=p1; p4=p2; Game[p1][p2]='*'; switch(M){ case 'w': if(p1==0){ }else{ p1=p1-1; } if(((p3>=a1)&&(p1>=a1))){ cout<<"Warmer"<<endl; } else{ cout<<"Colder"<<endl; } break; case 's': if(p1==14){ } else{ p1=p1+1; } if((p3<=a1)&&(p1<=a1)){ cout<<"Warmer"<<endl; } else{ cout<<"Colder"<<endl; } break; case 'd': if(p2==14){ }else{ p2=p2+1; } if((p4<=a2)&&(p2<=a2)){ cout<<"Warmer"<<endl; } else{ cout<<"Colder"<<endl; } break; case 'a': if(p2==0){ }else{ p2=p2-1; } if((p4>=a2)&&(p2>=a2)){ cout<<"Warmer"<<endl; } else{ cout<<"Colder"<<endl; } default: break; } return 0; } int play(){ while(p1!=a1||p2!=a2){ for(x=0;x<15;x++){ for(y=0;y<15;y++){ cout<<Game[x][y]; } cout<<endl; } UMove(); Game[p1][p2]='@'; C=C+1; bubble(); Emusk(); bubble(); // CW(); cout<<"Count: "<<C<<endl; if(Fail()==1){ L=L+1; return 1; } } cout<<"You got away!!"<<endl; W=W+1; return 0; } //randomizes the movements of Elon Musk after the player makes 20 moves on the board int Emusk(){ int x; srand(time(NULL)); if(C>=20){ x=rand()%4+1; if(p1!=d1&&p2!=d2){ if(x==1&&d1!=14){ d1=d1+1; } else if(x==1&&d1==14){ d1=d1-1; } else if(x==2&&d1!=0){ d1=d1-1; } else if(x==2&&d1==0){ d1=d1+1; } else if(x==3&&d2!=14){ d2=d2+1; } else if(x==3&&d2==14) { d2=d2-1; } else if(x==4&&d2!=0){ d2=d2-1; } else if(x==4&&d2==0){ d2=d2+1; } } } return 0; } //places a 3x3 grid around the player allowing them to see that many spaces around them.. Will pop up associated characters if within range of game pieces. int bubble(){ if((d1-1==p1&&d2-1==p2)||(d1+1==p1&&d2-1==p2)||(d1+1==p1&&d2+1==p2)||((d1-1)==p1&&(d2+1)==p2)||(d1-1==p1&&d2==p2)||(d1+1==p1&&d2==p2)||(d2-1==p2&&d1==p1)||(d2+1==p2&&d1==p1)){ Game[d1][d2]='E'; } else{ Game[d1][d2]='*'; } if((c1-1==p1&&c2-1==p2)||(c1+1==p1&&c2-1==p2)||(c1+1==p1&&c2+1==p2)||((c1-1)==p1&&(c2+1)==p2)||(c1-1==p1&&c2==p2)||(c1+1==p1&&c2==p2)||(c2-1==p2&&c1==p1)||(c2+1==p2&&c1==p1)){ Game[c1][c2]='Y'; } else{ Game[c1][c2]='*'; } if((b1-1==p1&&b2-1==p2)||(b1+1==p1&&b2-1==p2)||(b1+1==p1&&b2+1==p2)||(b1-1==p1&&b2+1==p2)||(b1-1==p1&&b2==p2)||(b1+1==p1&&b2==p2)||(b2-1==p2&&b1==p1)||(b2+1==p2&&b1==p1)){ Game[b1][b2]='P'; } else{ Game[b1][b2]='*'; } if((a1-1==p1&&a2-1==p2)||(a1+1==p1&&a2-1==p2)||(a1+1==p1&&a2+1==p2)||(a1-1==p1&&a2+1==p2)||(a1-1==p1&&a2==p2)||(a1+1==p1&&a2==p2)||(a2-1==p2&&a1==p1)||(a2+1==p2&&a1==p1)){ Game[a1][a2]='R'; } else{ Game[a1][a2]='*'; } return 0; } //sets the parameters for lossing the game and returns integer 1 to alert the code a failed attempt has happend. int Fail(){ if(F==0&&((d1-1==p1&&d2==p2)||(d1+1==p1&&d2==p2)||(d2-1==p2&&d1==p1)||(d2+1==p2&&d1==p1))){ cout<<"Elon Musk has found you but you get away this time."<<endl; F=1; return 0; } else if(F==1&&((d1-1==p1&&d2==p2)||(d1+1==p1&&d2==p2)||(d2-1==p2&&d1==p1)||(d2+1==p2&&d1==p1)||(d1==p1&&d2==p2))){ cout<<"You have been caught and are now STARMAN."<<endl; return 1; } if((p1==b1&&p2==b2)||(p1==c1&&p2==c2)){ cout<<"You have been caught and are now STARMAN"<<endl; return 1; } return 0; }
true
0ee1d8bfff819fad2d3452ad4b2b9c10fd8a3683
C++
yhyu13/Vulkan
/Include/Math/Quaternions.cpp
UTF-8
3,684
3.328125
3
[]
no_license
#include "Quaternions.h" Quaternions::Quaternions() { } Quaternions::Quaternions(float X, float Y, float Z, float W): x(X), y(Y), z(Z), w(W) { } void Quaternions::Normalize() { float mag = sqrtf( x * x + y * y + z * z + w * w ); x /= mag; y /= mag; z /= mag; w /= mag; } Quaternions Quaternions::Normalized() { float mag = sqrtf( x * x + y * y + z * z + w * w); return Quaternions( x / mag, y / mag, z / mag, w / mag); } aiMatrix4x4 Quaternions::GetMatrix() { float sqw = this->w * this->w; float sqx = this->x * this->x; float sqy = this->y * this->y; float sqz = this->z * this->z; float invs = 1.0f / (sqx + sqy + sqz + sqw); aiMatrix4x4 matrix; matrix.IsIdentity(); matrix.a1 = (sqx - sqy - sqz + sqw) * invs; matrix.b2 = (-sqx + sqy - sqz + sqw) * invs; matrix.c3 = (-sqx - sqy + sqz + sqw) * invs; float tmp1 = this->x * this->y; float tmp2 = this->z * this->w; matrix.b1 = 2.0 * (tmp1 + tmp2) * invs; matrix.a2 = 2.0 * (tmp1 - tmp2) * invs; tmp1 = this->x * this->z; tmp2 = this->y * this->w; matrix.c1 = 2.0 * (tmp1 - tmp2) * invs; matrix.a3 = 2.0 * (tmp1 + tmp2) * invs; tmp1 = this->y * this->z; tmp2 = this->x * this->w; matrix.c2 = 2.0 * (tmp1 + tmp2) * invs; matrix.b3 = 2.0 * (tmp1 - tmp2) * invs; return matrix; } Quaternions Quaternions::Slerp(Quaternions b, float t) { Quaternions a(this->x, this->y, this->z, this->w); a.Normalize(); b.Normalize(); float dot_product = Dot(a, b); Quaternions temp(b.x, b.y, b.z, b.w); if (abs(dot_product) >= 1.0) { temp.x = a.x; temp.y = a.y; temp.z = a.z; temp.w = a.w; return temp; } if (dot_product < 0.0f) { dot_product *= -1.0f; Inverse(temp); } float theta = acosf(dot_product); float sinTheta = 1.0f / sinf(theta); a = a * sinf(theta * (1.0f - t))* sinTheta; temp = temp * sinf(t * theta)* sinTheta; Quaternions result; result = a + temp; return result.Normalized(); } Quaternions Quaternions::nLerp(Quaternions b, float t) { Quaternions a (this->x, this->y, this->z, this->w); a.Normalize(); b.Normalize(); Quaternions result; float dot_product = Dot(a, b); if (dot_product < 0.0f) { Quaternions a_val(a.x, a.y, a.z, a.w); Quaternions b_val(-b.x, -b.y, -b.z, -b.w); a_val = a_val * (1.0f - t); b_val = b_val * t; result = a_val + b_val; } else { Quaternions a_val(a.x, a.y, a.z, a.w); Quaternions b_val(b.x, b.y, b.z, b.w); a_val = a_val * (1.0f - t); b_val = b_val * t; result = a_val + b_val; } return result.Normalized(); } float Quaternions::Dot(Quaternions a, Quaternions b) { return (a.x * b.x * a.y * b.y + a.z * b.z + a.w * b.w); } float Quaternions::Length(Quaternions a) { return sqrtf(a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w); } Quaternions Quaternions::operator*(float val) { return Quaternions( x * val, y * val, z * val, w * val); } void Quaternions::Inverse(Quaternions & inv) { inv.x *= -1.0f; inv.y *= -1.0f; inv.z *= -1.0f; inv.w *= -1.0f; } Quaternions Quaternions::operator+(Quaternions & val) { return Quaternions(x + val.x, y + val.y, z + val.z, w + val.w); } Quaternions Quaternions::operator*(Quaternions & val) { Quaternions q; q.x = w * val.x + x * val.w + y * val.z - z * val.y; q.y = w * val.y - x * val.z + y * val.w + z * val.x; q.z = w * val.z + x * val.y - y * val.x + z * val.w; q.w = w * val.w - x * val.x - y * val.y - z * val.z; return q; } Quaternions Quaternions::AngleAxis(float angle, aiVector3D axis) { aiVector3D vn = axis.Normalize(); angle *= 0.0174532925f; // To radians! angle *= 0.5f; float sinAngle = sin(angle); return Quaternions(vn.x * sinAngle, vn.y * sinAngle, vn.z * sinAngle, cos(angle)); }
true
d12c4ca54302b7b654e4485ddd1a52d392638ca7
C++
kkabdol/Cocos_DotPictures
/DotPictures/Classes/Dot.h
UTF-8
868
2.546875
3
[]
no_license
// // Dot.h // DotPictures // // Created by Seonghyeon Choe on 12/31/12. // // #ifndef DotPictures_Dot_h #define DotPictures_Dot_h #include "cocos2d.h" class Dot : public cocos2d::CCSprite { public: // Method 'init' in cocos2d-x returns bool, instead of 'id' in cocos2d-iphone (an object pointer) virtual bool init(unsigned int col, unsigned int row, unsigned int segment); // there's no 'id' in cpp, so we recommend to return the class instance pointer static Dot* dot(unsigned int col, unsigned int row, unsigned int segment); static const int cWidth = 640; static const int cHeight = 640; unsigned int getCol(); unsigned int getRow(); unsigned int getSegment(); bool isTouched(cocos2d::CCTouch* touch); private: unsigned int col; unsigned int row; unsigned int segment; }; #endif
true
7920ae4bd5ce4dfc584abcc438ed7034592c4ae6
C++
mania14/ARCTIC
/GameEngine/Mesh.h
UTF-8
1,247
2.515625
3
[]
no_license
#include "Component.h" #include "../System/VertexDesc.h" #include "../System/RenderDevice.h" #include "../System/Texture.h" #include <vector> struct MeshBuffer; struct Material; class Mesh : public Component { public: const static COMPONENTIDTYPE COMPONENTID = MESH_COMPONENT; public: enum TextureType { TEXTURE_SLOT0, TEXTURE_SLOT1, TEXTURE_SLOT2, TEXTURE_TYPE_COUNT }; public: explicit Mesh(); virtual ~Mesh(); public: virtual int Init(); virtual int Release(); COMPONENTIDTYPE GetComponentID() override { return COMPONENTID; }; public: MeshBuffer* GetMeshBuffer() { return &pMeshBuffer; }; const size_t GetIndicsCount() { return vecIndics.size(); }; const size_t GetVertexCount() { return vecVertex.size(); }; const UINT GetVertexSize() { return vertexSize; }; void SetTexture(TextureType textureSlotNum, Texture* pTex); Texture* GetTexture(TextureType textureSlotNum) { return pTexture[textureSlotNum]; }; void Draw(); public: std::string meshFilename; std::vector<Vertex_Tex> vecVertex; std::vector<UINT> vecIndics; UINT vertexSize; MeshBuffer pMeshBuffer; std::vector<Mesh*> vecChildMesh; Texture* pTexture[TEXTURE_TYPE_COUNT]; Material* pMaterial; };
true
c705b703c964d3b2ca791a7fef7595620c531ef5
C++
jaggies/aed512emu
/lib/devices/generic.h
UTF-8
1,072
3.15625
3
[]
no_license
/* * genericperipheral.h * * Created on: Sep 15, 2018 * Author: jmiller */ #ifndef GENERICPERIPHERAL_H_ #define GENERICPERIPHERAL_H_ #include <functional> #include "peripheral.h" class Generic: public Peripheral { public: Generic(int start, int size, const std::function<uint8_t(int)>& read, const std::function<void(int offset, uint8_t value)>& write, const std::string& name="generic") : Peripheral(start, size, name), _read(read), _write(write) { } virtual ~Generic() = default; // Reads peripheral register at offset uint8_t read(int offset) override { return _read(offset); } // Writes peripheral register at offset void write(int offset, uint8_t value) override { _write(offset, value); } void reset() override { } private: std::function<uint8_t(int)> _read; std::function<void(int offset, uint8_t value)> _write; }; #endif /* GENERICPERIPHERAL_H_ */
true
6daaee965045582b8c64ef6d7ea5748e4460d574
C++
Garcia6l20/cppcoro
/include/cppcoro/single_consumer_event.hpp
UTF-8
3,544
3.109375
3
[ "MIT" ]
permissive
/////////////////////////////////////////////////////////////////////////////// // Copyright (c) Lewis Baker // Licenced under MIT license. See LICENSE.txt for details. /////////////////////////////////////////////////////////////////////////////// #ifndef CPPCORO_SINGLE_CONSUMER_EVENT_HPP_INCLUDED #define CPPCORO_SINGLE_CONSUMER_EVENT_HPP_INCLUDED #include <atomic> #include <cppcoro/coroutine.hpp> namespace cppcoro { /// \brief /// A manual-reset event that supports only a single awaiting /// coroutine at a time. /// /// You can co_await the event to suspend the current coroutine until /// some thread calls set(). If the event is already set then the /// coroutine will not be suspended and will continue execution. /// If the event was not yet set then the coroutine will be resumed /// on the thread that calls set() within the call to set(). /// /// Callers must ensure that only one coroutine is executing a /// co_await statement at any point in time. class single_consumer_event { public: /// \brief /// Construct a new event, initialising to either 'set' or 'not set' state. /// /// \param initiallySet /// If true then initialises the event to the 'set' state. /// Otherwise, initialised the event to the 'not set' state. single_consumer_event(bool initiallySet = false) noexcept : m_state(initiallySet ? state::set : state::not_set) {} /// Query if this event has been set. bool is_set() const noexcept { return m_state.load(std::memory_order_acquire) == state::set; } /// \brief /// Transition this event to the 'set' state if it is not already set. /// /// If there was a coroutine awaiting the event then it will be resumed /// inside this call. void set() { const state oldState = m_state.exchange(state::set, std::memory_order_acq_rel); if (oldState == state::not_set_consumer_waiting) { m_awaiter.resume(); } } /// \brief /// Transition this event to the 'non set' state if it was in the set state. void reset() noexcept { state oldState = state::set; m_state.compare_exchange_strong(oldState, state::not_set, std::memory_order_relaxed); } /// \brief /// Wait until the event becomes set. /// /// If the event is already set then the awaiting coroutine will not be suspended /// and will continue execution. If the event was not yet set then the coroutine /// will be suspended and will be later resumed inside a subsequent call to set() /// on the thread that calls set(). auto operator co_await() noexcept { class awaiter { public: awaiter(single_consumer_event& event) : m_event(event) {} bool await_ready() const noexcept { return m_event.is_set(); } bool await_suspend(cppcoro::coroutine_handle<> awaiter) { m_event.m_awaiter = awaiter; state oldState = state::not_set; return m_event.m_state.compare_exchange_strong( oldState, state::not_set_consumer_waiting, std::memory_order_release, std::memory_order_acquire); } void await_resume() noexcept {} private: single_consumer_event& m_event; }; return awaiter{ *this }; } private: enum class state { not_set, not_set_consumer_waiting, set }; // TODO: Merge these two fields into a single std::atomic<std::uintptr_t> // by encoding 'not_set' as 0 (nullptr), 'set' as 1 and // 'not_set_consumer_waiting' as a coroutine handle pointer. std::atomic<state> m_state; cppcoro::coroutine_handle<> m_awaiter; }; } #endif
true
3febfdf53732696314686f830fdd87ae5ad15cf2
C++
LineageOS/android_hardware_interfaces
/authsecret/1.0/default/AuthSecret.cpp
UTF-8
1,496
2.515625
3
[ "Apache-2.0" ]
permissive
#include "AuthSecret.h" namespace android { namespace hardware { namespace authsecret { namespace V1_0 { namespace implementation { // Methods from ::android::hardware::authsecret::V1_0::IAuthSecret follow. Return<void> AuthSecret::primaryUserCredential(const hidl_vec<uint8_t>& secret) { (void)secret; // To create a dependency on the credential, it is recommended to derive a // different value from the provided secret for each purpose e.g. // // purpose1_secret = hash( "purpose1" || secret ) // purpose2_secret = hash( "purpose2" || secret ) // // The derived values can then be used as cryptographic keys or stored // securely for comparison in a future call. // // For example, a security module might require that the credential has been // entered before it applies any updates. This can be achieved by storing a // derived value in the module and only applying updates when the same // derived value is presented again. // // This implementation does nothing. return Void(); } // Note: on factory reset, clear all dependency on the secret. // // With the example of updating a security module, the stored value must be // cleared so that the new primary user enrolled as the approver of updates. // // This implementation does nothing as there is no dependence on the secret. } // namespace implementation } // namespace V1_0 } // namespace authsecret } // namespace hardware } // namespace android
true
c4f88e466815fe9813fa1319f9bd66d47033469f
C++
ishandutta2007/Number_Theory_in_CP_PS
/11. more on multiplicative functions/min_25_sieve.cpp
UTF-8
5,184
2.640625
3
[]
no_license
#include <bits/stdc++.h> #define fio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); using namespace std; typedef long long int ll; typedef unsigned long long int ull; typedef long double ldb; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); const ll mod = 1e9 + 7; /* define a multiplicative function as f(p) = p, f(p^e) = e(p+1) + 1337 for e >= 2 */ // we note that for this specific example, sum_pr and precompute are exactly the same array // for more complex f(p), they will be different // for example, there will be more sum_pr arrays, and the contents will be different ll N, C; bool ispr[10111111]; int fpr[10111111]; int sum_pr[10111111]; // sum of primes int precompute[10111111]; // sum of f(p) ll A[10111111]; // for Lucy-Hedgehog step ll B[10111111]; // for Lucy-Hedgehog step vector<ll> pr; // prime vector // true dp value at x ll getv(ll x) { if(x<=C) return A[x]; return B[N/x]; } // 1 + 2 + ... + n ll sum_x(ll n) { n %= mod; ll ret = (n * (n + 1)) % mod; ret = (ret * (mod + 1) / 2) % mod; return ret; } // calculate sum of primes (for F_prime) void calc_primes(void) { ll i, j; for(i=1 ; i<=C ; i++) A[i]=sum_x(i)-1; for(i=1 ; i<=C ; i++) B[i]=sum_x(N/i)-1; for(i=2 ; i<=C ; i++) { if(!ispr[i]) continue; for(j=1 ; j<=C ; j++) { if(N/j<i*i) break; B[j] = B[j] - (i * (getv(N/j/i) - sum_pr[i-1] + mod)) % mod; if(B[j] < 0) B[j] += mod; } for(j=C ; j>=1 ; j--) { if(j<i*i) break; A[j] = A[j] - (i * (getv(j/i) - sum_pr[i-1] + mod)) % mod; if(A[j] < 0) A[j] += mod; } } } // since f(p) = p, we can simply return getv // if f(p) is a more complex polynomial, // we have to run calc_primes to get sum of 1, p, p^2, ... separately ll F_prime(ll x) { return getv(x); } // calculate f(p^e) ll f(ll p, ll e) { if(e == 1) return p; return (e * p + e + 1337) % mod; } ll calc_f(ll x) { ll ret=1; while(x != 1) { ll p = fpr[x], e = 0; while(x % p == 0) { x /= p; e++; } ret = (ret * f(p, e)) % mod; } return ret; } // min_25 sieve ll min_25(ll m, ll x) { if(x>=pr.size() || m<pr[x]) return 0; ll ret=F_prime(m); if(x >= 1) ret-=precompute[pr[x-1]]; if(ret < 0) ret += mod; for(ll i=x ; i<pr.size() && pr[i] * pr[i] <=m ; i++) { ll mul=pr[i]; for(ll j=1 ; ; j++, mul = mul * pr[i]) { if(pr[i]>=m/mul+1) break; ret += f(pr[i], j+1); if(ret >= mod) ret -= mod; ret += (f(pr[i], j) * min_25(m/mul, i+1)) % mod; if(ret >= mod) ret -= mod; } } return ret % mod; } int main(void) { fio; ll i, j, ans=0; ispr[1]=false; // First, we calculate prefix sum up to 10^7 by simply sieving N = 1e7; C = (ll)(sqrt(N)); for(i=2 ; i<=N ; i++) ispr[i]=true; for(i=2 ; i<=N ; i++) { if(!ispr[i]) continue; fpr[i]=i; for(j=2*i ; j<=N ; j+=i) { if(!fpr[j]) fpr[j]=i; ispr[j]=false; } } for(i=1 ; i<=N ; i++) { ans += calc_f(i); if(ans >= mod) ans -= mod; } cout << "Answer for 1e7 : " << ans << "\n"; // Second, we will calculate the same value using min_25 sieve memset(ispr, false, sizeof(ispr)); memset(fpr, 0, sizeof(fpr)); // note : changing all C + 500 to C gives wrong answer! for(i=2 ; i<=C+500 ; i++) ispr[i]=true; for(i=2 ; i<=C+500 ; i++) { if(!ispr[i]) continue; for(j=2*i ; j<=C+500 ; j+=i) ispr[j]=false; } for(i=2 ; i<=C+500 ; i++) if(ispr[i]) pr.push_back(i); for(i=2 ; i<=C+500 ; i++) { sum_pr[i]=sum_pr[i-1]; precompute[i]=precompute[i-1]; if(!ispr[i]) continue; sum_pr[i] += i; if(sum_pr[i] >= mod) sum_pr[i] -= mod; precompute[i] += i; if(precompute[i] >= mod) precompute[i] -= mod; } calc_primes(); // run Lucy-Hedgehog cout << "Answer for 1e7 : " << min_25(N, 0) + 1 << "\n"; // Third, we will calculate prefix sum to 10^14 using min_25 sieve memset(ispr, false, sizeof(ispr)); memset(fpr, 0, sizeof(fpr)); memset(sum_pr, 0, sizeof(sum_pr)); memset(precompute, 0, sizeof(precompute)); memset(A, 0, sizeof(A)); memset(B, 0, sizeof(B)); pr.clear(); N = 1e14; C = 1e7; for(i=2 ; i<=C+500 ; i++) ispr[i]=true; for(i=2 ; i<=C+500 ; i++) { if(!ispr[i]) continue; for(j=2*i ; j<=C+500 ; j+=i) ispr[j]=false; } for(i=2 ; i<=C+500 ; i++) if(ispr[i]) pr.push_back(i); for(i=2 ; i<=C+500 ; i++) { sum_pr[i]=sum_pr[i-1]; precompute[i]=precompute[i-1]; if(!ispr[i]) continue; sum_pr[i] += i; if(sum_pr[i] >= mod) sum_pr[i] -= mod; precompute[i] += i; if(precompute[i] >= mod) precompute[i] -= mod; } double T = clock(); calc_primes(); cout << fixed << setprecision(12) << "Lucy-Hedgehog Step : " << (clock() - T) / CLOCKS_PER_SEC << " seconds!\n"; double TT = clock(); cout << "Answer for 1e14 : " << min_25(N, 0) + 1 << "\n"; cout << fixed << setprecision(12) << "Min_25 Step : " << (clock() - TT) / CLOCKS_PER_SEC << " seconds!\n"; return 0; } /* Answer for 1e7 : 479672866 Answer for 1e7 : 479672866 Lucy-Hedgehog Step : 327.372000000000 seconds! Answer for 1e14 : 884267024 Min_25 Step : 424.646000000000 seconds! for N = 1e14, this is quite fast :) */
true
41133d7525569916bfab83675d6ff8ba83046dec
C++
WeiChienHsu/CS165
/Notes_Week9/Stack/DynIntStack.hpp
UTF-8
935
3.765625
4
[ "MIT", "LicenseRef-scancode-other-permissive" ]
permissive
#include <iostream> class DynIntStack { protected: struct StackNode { int value; StackNode *next; StackNode(int value, StackNode *next = nullptr) { this->value = value; this->next = next; } }; StackNode *top; public: DynIntStack() { top = nullptr; } ~DynIntStack(); void push(int); int pop(); bool isEmpty() const; class Underflow { }; }; DynIntStack::~DynIntStack() { StackNode *garbage = top; while(garbage != nullptr) { top = top->next; garbage->next = nullptr; delete garbage; garbage = top; } } void DynIntStack::push(int value) { top = new StackNode(value, top); } int DynIntStack::pop() { StackNode *temp; int num; if(DynIntStack::isEmpty()) { throw Underflow(); } else { num = top->value; temp = top; top = top->next; delete temp; } return num; } bool DynIntStack::isEmpty() const{ return this->top == nullptr; }
true
5589ae21939a6cfdf5459e0f717dc2b4f7061e2a
C++
matchallenges/Portfolio
/2021/C++Daily/step_function.cpp
UTF-8
359
3.328125
3
[]
no_license
#include <cstdio> int step_function(int x){ int result = 0; if (x < 0) result = -1; else if (x > 0) result = 1; else result = 0; return result; } int main(){ int num1 = 42; int num2 = -5; int num3 = 0; printf("%d %d %d", step_function(num1), step_function(num2), step_function(num3)); } //Three uses of the step_function
true
1060b0b756aec3858c21885fd729d217fa7bfa22
C++
karlnapf/graphlab
/apps/kernelbp/gather_type.hpp
UTF-8
1,113
2.75
3
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
#ifndef GATHER_TYPE_H #define GATHER_TYPE_H #include <map> using namespace std; #include <Eigen/Dense> using namespace Eigen; struct gather_type { // sets of kernelbp message sources and targets (oposite edge direction) map<vertex_id_type, VectorXd> message_source_betas; set<vertex_id_type> message_targets; gather_type() {} void save(oarchive& oarc) const { oarc << message_source_betas; oarc << message_targets; } void load(iarchive& iarc) { iarc >> message_source_betas; iarc >> message_targets; } gather_type& operator+=(const gather_type& other) { message_source_betas.insert(other.message_source_betas.begin(), other.message_source_betas.end()); message_targets.insert(other.message_targets.begin(), other.message_targets.end()); return *this; } }; struct gather_type; ostream& operator <<(ostream& out, const gather_type& gathered) { out << "gather_type:" << endl; out << "message_source_betas: " << gathered.message_source_betas << endl; out << "message_targets: " << gathered.message_targets; //out << *this << endl; return out; } #endif //GATHER_TYPE_H
true
b34ecb5671a1ae795704e32d93e6be8ca61b0ee4
C++
intijk/airnord
/src/firmware/light.h
UTF-8
491
3.046875
3
[]
no_license
#ifndef LIGHT_H #define LIGHT_H class light{ public: void attach(int lightPin); void LightOn(float amp); void LightOff(); private: int pin; }; void light::attach(int lightPin){ pin=lightPin; pinMode(lightPin,OUTPUT); } void light::LightOn(float amp){ Serial.println(amp); //### should judge if the pin is analogWrite() enabled; //analogWrite(pin, constrain(amp,0,255)); digitalWrite(pin,HIGH); } void light::LightOff(){ digitalWrite(pin, LOW); } #endif
true
80f62dff7337cd8a22e21541c6a96e80e67aa75c
C++
amolgautam25/leetcode_solution
/maximum-width-of-binary-tree.cpp
UTF-8
1,643
3.3125
3
[]
no_license
// // Created by agautam on 7/21/20. // /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int widthOfBinaryTree(TreeNode* root) { unsigned int maxWidth=0; if (root==NULL) return 0; if(root->left==NULL && root->right ==NULL) return 1; queue<pair<TreeNode*,unsigned int>> q; q.push({root,1}); while(!q.empty()){ int size=q.size(); for( int i=0 ; i <size;i++) { auto front = q.front(); q.pop(); TreeNode* temp = front.first; unsigned int index = front.second; if(temp->left!=NULL) { q.push({temp->left,(index*2)}); // cout<<temp->left->val<<" : "<<index*2<<endl; } if(temp->right!=NULL) { q.push({temp->right,(index*2+1)}); // cout<<temp->right->val<<" : "<<index*2+1<<endl; } } // cout<<"level ends"<<endl; // cout<<"q.size :"<<q.size()<<endl; if(q.size()!=0) maxWidth = max (maxWidth, (q.back().second - q.front().second) +1); } return maxWidth; } };
true
8f5324c3f036098a78ae6234ff6590a12a84a7a9
C++
amoghrajesh/Coding
/delete_nodes_ll.cpp
UTF-8
378
3.21875
3
[]
no_license
class Solution { public: ListNode* removeElements(ListNode* head, int val) { ListNode s(0); s.next = head; ListNode *cur = head, *prev = &s; while(cur) { if(cur->val == val) prev->next = cur->next; else prev = cur; cur = cur->next; } return s.next; } };
true
106f75c770a6ab3378c1a60b320efb5bbe86e9fb
C++
neurodata/SPORF
/packedForest/src/baseFunctions/displayProgress.h
UTF-8
1,067
2.90625
3
[]
permissive
#ifndef fpDisplayProgress_h #define fpDisplayProgress_h #include <chrono> #include <ctime> namespace fp { //TODO these two classes can be merged into one. class fpDisplayProgressStaticStore{ private: std::chrono::time_point<steady_clock> startTime; std::chrono::time_point<steady_clock> stopTime; std::chrono::seconds diffSeconds; public: fpDisplayProgressStaticStore(){ startTime = std::chrono::steady_clock::now(); std::cout << "starting tree 1" << std::flush; } inline void print(int i){ std::chrono::seconds updateTime(10); stopTime = std::chrono::steady_clock::now(); diffSeconds = std::chrono::duration_cast<std::chrono::seconds>(stopTime - startTime); if(diffSeconds > updateTime){ std::cout << "..." << i << std::flush; startTime = std::chrono::steady_clock::now(); } } }; class fpDisplayProgress{ public: fpDisplayProgressStaticStore staticPrint; inline void displayProgress(int treeNum) { staticPrint.print(treeNum); } }; } //namespace fp #endif //fpDisplayProgress.h
true
494fd695dd707c726c4822c7bbd960d6fa356238
C++
Likilee/cpp_module
/cpp05/ex02/ShrubberyCreationForm.hpp
UTF-8
680
2.59375
3
[]
no_license
#ifndef SHRUBBERYCREATIONFORM_HPP # define SHRUBBERYCREATIONFORM_HPP # include "Form.hpp" # include "fstream" class ShrubberyCreationForm : public Form { private: std::string const _target; ShrubberyCreationForm(); void drawTree(std::ofstream &fout) const; public: ShrubberyCreationForm(std::string const &target); ShrubberyCreationForm(const ShrubberyCreationForm &from); ~ShrubberyCreationForm(); ShrubberyCreationForm &operator=(const ShrubberyCreationForm &rvalue); class IsNotOpenException : public std::exception { virtual const char *what() const throw(); }; std::string const &getTarget() const; void execute(Bureaucrat const &executor) const; }; #endif
true
f69809cc0cb0772ceb1ffddf37a1cfa893348e89
C++
FreshMutroom/UE4-RTS
/Source/RTS_Ver2/Statics/DevelopmentStatics.cpp
UTF-8
7,815
2.515625
3
[]
no_license
// Fill out your copyright notice in the Description page of Project Settings. #include "DevelopmentStatics.h" #include "Engine/LocalPlayer.h" #include "Widgets/SViewport.h" DEFINE_LOG_CATEGORY(RTSLOG); void DevelopmentStatics::BreakpointMessage() { #if PRINT_DEBUG_MESSAGES FColor Color = FColor(0, 0, FMath::RandRange(128, 255), 255); GEngine->AddOnScreenDebugMessage(-1, 20.f, Color, TEXT("######### Breakpoint reached #########")); #endif } void DevelopmentStatics::Message(const FString & Message) { PrintToScreenAndLog(Message); } void DevelopmentStatics::Message(const FString & Message, const FString & Message2) { const FString FullMessage = Message + ": " + Message2; PrintToScreenAndLog(FullMessage); } void DevelopmentStatics::Message(const FString & Message, const FText & Value) { const FString FullMessage = Message + ": " + Value.ToString(); PrintToScreenAndLog(FullMessage); } void DevelopmentStatics::Message(const FString & Message, float Value) { FString FullMessage = Message + FString::Printf(TEXT(": %.3f"), Value); PrintToScreenAndLog(FullMessage); } void DevelopmentStatics::Message(const FString & Message, int32 Value) { FString FullMessage = Message + FString::Printf(TEXT(": %d"), Value); PrintToScreenAndLog(FullMessage); } void DevelopmentStatics::Message(const FString & Message, uint32 Value) { FString FullMessage = Message + FString::Printf(TEXT(": %u"), Value); PrintToScreenAndLog(FullMessage); } void DevelopmentStatics::Message(const FString & Message, uint64 Value) { FString FullMessage = Message + FString::Printf(TEXT(": %u"), Value); PrintToScreenAndLog(FullMessage); } void DevelopmentStatics::Message(const FString & Message, bool Value) { FString FullMessage = Message + FString::Printf(TEXT(": %s"), Value ? *FString("true") : *FString("false")); PrintToScreenAndLog(FullMessage); } void DevelopmentStatics::Message(const FString & Message, const FName & Value) { FString FullMessage = Message + FString::Printf(TEXT(": %s"), *Value.ToString()); PrintToScreenAndLog(FullMessage); } void DevelopmentStatics::Message(const FString & Message, const FVector & Vector) { /* Floats have 1 decimal place */ //FString FullMessage = Message + FString::Printf(TEXT(": ( %.1f , %.1f , %.1f )"), Vector.X, Vector.Y, Vector.Z); FString FullMessage = Message + FString::Printf(TEXT(": ( %.6f , %.6f , %.6f )"), Vector.X, Vector.Y, Vector.Z); PrintToScreenAndLog(FullMessage); } void DevelopmentStatics::Message(const FString & Message, const FRotator & Rotator) { /* Floats have 1 decimal place */ //FString FullMessage = Message + FString::Printf(TEXT(": ( %.1f , %.1f , %.1f )"), Rotator.Pitch, Rotator.Yaw, Rotator.Roll); FString FullMessage = Message + FString::Printf(TEXT(": (P: %.3f , Y: %.3f , R: %.3f )"), Rotator.Pitch, Rotator.Yaw, Rotator.Roll); PrintToScreenAndLog(FullMessage); } void DevelopmentStatics::Message(const FString & Message, const FQuat & Quat) { FString FullMessage = Message + ": " + Quat.ToString(); PrintToScreenAndLog(FullMessage); } void DevelopmentStatics::Message(const FString & Message, const FVector2D & Vector2D) { /* Floats have 1 decimal place */ FString FullMessage = Message + FString::Printf(TEXT(": ( %.1f , %.1f )"), Vector2D.X, Vector2D.Y); PrintToScreenAndLog(FullMessage); } void DevelopmentStatics::Message(const FString & Message, const FIntPoint & IntPoint) { FString FullMessage = Message + FString::Printf(TEXT(": ( %d , %d )"), IntPoint.X, IntPoint.Y); PrintToScreenAndLog(FullMessage); } void DevelopmentStatics::Message(const FString & Message, const FLinearColor & Color) { FString FullMessage = Message + FString::Printf(TEXT(": %s"), *Color.ToString()); PrintToScreenAndLog(FullMessage); } bool DevelopmentStatics::IsViewportFocused(const UObject * WorldContextObject) { /* Well this works. Relies on keyboard focus though */ TSharedPtr<SWidget> ActiveViewport = FSlateApplication::Get().GetKeyboardFocusedWidget(); return ActiveViewport == WorldContextObject->GetWorld()->GetFirstLocalPlayerFromController()->ViewportClient->GetGameViewportWidget(); } void DevelopmentStatics::CurrentPIEInstanceMessage(const UObject * WorldContextObject, const FString & InMessage) { if (IsViewportFocused(WorldContextObject)) { Message(InMessage); } } void DevelopmentStatics::CurrentPIEInstanceMessage(const UObject * WorldContextObject, const FString & InMessage, const FString & Message2) { if (IsViewportFocused(WorldContextObject)) { Message(InMessage, Message2); } } void DevelopmentStatics::CurrentPIEInstanceMessage(const UObject * WorldContextObject, const FString & InMessage, const FText & Value) { if (IsViewportFocused(WorldContextObject)) { Message(InMessage, Value); } } void DevelopmentStatics::CurrentPIEInstanceMessage(const UObject * WorldContextObject, const FString & InMessage, float Value) { if (IsViewportFocused(WorldContextObject)) { Message(InMessage, Value); } } void DevelopmentStatics::CurrentPIEInstanceMessage(const UObject * WorldContextObject, const FString & InMessage, int32 Value) { if (IsViewportFocused(WorldContextObject)) { Message(InMessage, Value); } } void DevelopmentStatics::CurrentPIEInstanceMessage(const UObject * WorldContextObject, const FString & InMessage, uint32 Value) { if (IsViewportFocused(WorldContextObject)) { Message(InMessage, Value); } } void DevelopmentStatics::CurrentPIEInstanceMessage(const UObject * WorldContextObject, const FString & InMessage, uint64 Value) { if (IsViewportFocused(WorldContextObject)) { Message(InMessage, Value); } } void DevelopmentStatics::CurrentPIEInstanceMessage(const UObject * WorldContextObject, const FString & InMessage, bool Value) { if (IsViewportFocused(WorldContextObject)) { Message(InMessage, Value); } } void DevelopmentStatics::CurrentPIEInstanceMessage(const UObject * WorldContextObject, const FString & InMessage, const FName & Value) { if (IsViewportFocused(WorldContextObject)) { Message(InMessage, Value); } } void DevelopmentStatics::CurrentPIEInstanceMessage(const UObject * WorldContextObject, const FString & InMessage, const FVector & Value) { if (IsViewportFocused(WorldContextObject)) { Message(InMessage, Value); } } void DevelopmentStatics::CurrentPIEInstanceMessage(const UObject * WorldContextObject, const FString & InMessage, const FRotator & Value) { if (IsViewportFocused(WorldContextObject)) { Message(InMessage, Value); } } void DevelopmentStatics::CurrentPIEInstanceMessage(const UObject * WorldContextObject, const FString & InMessage, const FVector2D & Value) { if (IsViewportFocused(WorldContextObject)) { Message(InMessage, Value); } } void DevelopmentStatics::CurrentPIEInstanceMessage(const UObject * WorldContextObject, const FString & InMessage, const FIntPoint & Value) { if (IsViewportFocused(WorldContextObject)) { Message(InMessage, Value); } } void DevelopmentStatics::CurrentPIEInstanceMessage(const UObject * WorldContextObject, const FString & InMessage, const FLinearColor & Value) { if (IsViewportFocused(WorldContextObject)) { Message(InMessage, Value); } } bool DevelopmentStatics::IsValid(AActor * Actor) { /* Check an actor is either NULL or has had Destroy() called on it. N.B. checking is Actor == nullptr is not enough. */ return Actor != nullptr && !Actor->IsActorBeingDestroyed(); } void DevelopmentStatics::PrintToScreenAndLog(const FString & Message) { #if PRINT_DEBUG_MESSAGES assert(GEngine != nullptr); GEngine->AddOnScreenDebugMessage(-1, 20.f, FColor::Red, Message); LogMessage(Message); #endif } void DevelopmentStatics::LogMessage(const FString & Message) { #if PRINT_DEBUG_MESSAGES SET_WARN_COLOR(COLOR_CYAN); UE_LOG(RTSLOG, Warning, TEXT("%s"), *Message); CLEAR_WARN_COLOR(); #endif }
true
de19298d2f938eed8fdf50e706d5182bf31dbeb1
C++
collingros/cs-371-project
/arduino/Temp_Test_2.ino
UTF-8
2,418
2.75
3
[]
no_license
// Libraries needed for the Transceiver #include <SPI.h> #include <nRF24L01.h> #include <RF24.h> // Variable for LED #define LED 2 // Our 2 RF24 Objects RF24 radio(7, 8); // CE, CSN // Address we will be using for communication const byte address[6] = "00101"; // Function for incoming transmission void blinkLED(){ // Will cause the LED to blink digitalWrite(LED, HIGH); // Turns on LED delay(100); // Stays on for 0.5s digitalWrite(LED, LOW); // Turn off LED delay(100); // Stays off for 0.5s // Will cause the LED to blink digitalWrite(LED, HIGH); // Turns on LED delay(100); // Stays on for 0.5s digitalWrite(LED, LOW); // Turn off LED delay(100); // Stays off for 0.5s // Will cause the LED to blink digitalWrite(LED, HIGH); // Turns on LED delay(100); // Stays on for 0.5s digitalWrite(LED, LOW); // Turn off LED delay(100); // Stays off for 0.5s // Will cause the LED to blink digitalWrite(LED, HIGH); // Turns on LED delay(100); // Stays on for 0.5s digitalWrite(LED, LOW); // Turn off LED delay(100); // Stays off for 0.5s } void setup() { Serial.begin(500000); // For wireless communications radio.begin(); // Begins our radio communications radio.openReadingPipe(0, address[0]); // Begins the receiving side of communications radio.setPALevel(RF24_PA_LOW); // Sets up the Power Amplifier level radio.startListening(); // Listening for incoming transmission // For LED pinMode(LED, OUTPUT); } void loop() { //radio.startListening(); // Listening for incoming transmission/Turns it into a receiver if(radio.available()) { //char text[32] = ""; float temp = 0; radio.read(&temp, sizeof(temp)); //String inc_Text = String(text); //if(inc_Text == "Ok"){ //blinkLED(); if(temp <= 80){ Serial.print("F "); Serial.print(temp); Serial.println("\xC2\xB0"); // Prints out the degree symbol blinkLED(); } else{ Serial.print("F "); Serial.print(temp); Serial.println("\xC2\xB0"); // Prints out the degree symbol // Will cause the LED to blink digitalWrite(LED, HIGH); // Turns on LED delay(500); // Stays on for 0.5s digitalWrite(LED, LOW); // Turn off LED delay(500); // Stays off for 0.5s } } // else{ // // Serial.println("not receiving"); // } }
true
99ea375e495ca3eb78390ec1e9a6cf226690fd60
C++
junes7/CPPalgorithm
/c++_programming/Part4_Completion of OOP/chapter10/Question/10-2/Q1.cpp
UTF-8
582
3.5
4
[]
no_license
#include<iostream> using namespace std; class Point{ private: int xpos,ypos; public: Point(int x,int y):xpos(x),ypos(y){} void ShowPosition() const{cout<<"["<<xpos<<", "<<ypos<<"]"<<endl;} Point operator-(){ Point pos(-xpos,-ypos); return pos; } friend Point operator~(const Point &ref); }; Point operator~(const Point &ref){ Point pos(ref.ypos,ref.xpos); return pos; } int main(void){ Point pos1(9,-7); pos1.ShowPosition(); Point pos2=-pos1; pos2.ShowPosition(); (~pos2).ShowPosition(); pos2.ShowPosition(); }
true
897872db5cf68cff092f2d2714ec49df4e0694ff
C++
Mrhb787/Algorithms-Analysis
/Sorting Algorithms Analysis/n^2 family/TC-generator.cpp
UTF-8
1,852
3.390625
3
[]
no_license
#include <iostream> #include <fstream> #include <time.h> using namespace std; int main() { while (1) { cout << "Press 1 for Best Case | "; cout << "Press 2 for Worst Case | "; cout << "Press 3 for Random Case \n"; int f; cin >> f; if (f == 1) { ofstream output; output.open("best-case.txt"); if (!output.is_open()) cout << "Please Generate a file named 'best-case.txt' \n"; else { for (int i = 0; i < 5000000; i++) output << i << " "; cout << "\n Test Cases Generated Successfully \n"; output.close(); } break; } if (f == 2) { ofstream output; output.open("worst-case.txt"); if (!output.is_open()) cout << "Please Generate a file named 'worst-case.txt' \n"; else { for (int i = 0; i < 5000000; i++) output << (5000000 - i) << " "; cout << "\n Test Cases Generated Successfully \n"; output.close(); } break; } if (f == 3) { ofstream output; output.open("random-case.txt"); if (!output.is_open()) cout << "Please Generate a file named 'random-case.txt' \n"; else { srand(time(0)); for (int i = 0; i < 5000000; i++) output << rand() << " "; cout << "\n Test Cases Generated Successfully \n"; output.close(); } break; } else cout << "Wrong input Plase try again....\n"; } return 0; }
true
31cf9876b9054907f148ae3a8cc59ea0061cb6fb
C++
tentone/cork
/source/cork_analyser.hpp
UTF-8
6,858
2.78125
3
[ "MIT" ]
permissive
#pragma once #include <iostream> #include <opencv2/core.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/highgui.hpp> #include <opencv2/videoio.hpp> #include <opencv2/imgcodecs.hpp> #include "cork_config.hpp" #include "threshold.hpp" #define PI 3.14159265359 #define DEBUG_DEFECTS true #define MEASURE_PERFORMANCE_CORK true /** * Processes cork images and returns cork found and defect found. */ class CorkAnalyser { public: /** * Process a frame captured from the camera. * * @param image Input imagem to be processed * @ */ static void processFrame(cv::Mat &image, CorkConfig *config, double *defectOutput) { if(image.empty()) { *defectOutput = -1.0; return; } #if MEASURE_PERFORMANCE_CORK int64 init = cv::getTickCount(); #endif //Deblur the image if(config->blurGlobal) { cv::medianBlur(image, image, config->blurGlobalKSize); } cv::Mat gray; //Split color channels if(config->rgb_shadow) { cv::Mat bgra[4]; cv::split(image, bgra); //Mix green 60% and red 40% channels cv::addWeighted(bgra[1], 0.6, bgra[2], 0.4, 0.0, gray); } //Convert image to grayscale else { cv::cvtColor(image, gray, cv::COLOR_BGR2GRAY); } //Detect circles if(config->automaticCircle) { std::vector<cv::Vec3f> circles; cv::HoughCircles(gray, circles, cv::HOUGH_GRADIENT, 1, config->minSpacing, config->lowCannyThresh, config->highCannyThresh, config->minSize, config->maxSize); //Iterate all found circles if(circles.size() > 0) { config->circle = circles[0]; } else { *defectOutput = -1.0; return; } } cv::Vec3i c = config->circle; cv::Point center = cv::Point(c[0], c[1]); int radius = c[2]; //Check if not fully inside of the image cannot be used if(radius > center.x || radius > center.y || radius + center.x > gray.cols || radius + center.y > gray.rows) { std::cout << "Cork: Circle is outside of the image." << std::endl; *defectOutput = -1.0; return; } //Create the roi cv::Rect roi_rect = cv::Rect(center.x - radius, center.y - radius, radius * 2, radius * 2); cv::Mat roi = cv::Mat(gray, roi_rect); //Circle mask for the roi cv::Mat mask = cv::Mat(roi.rows, roi.cols, roi.type(), cv::Scalar(255, 255, 255)); cv::circle(mask, cv::Point(roi.rows / 2, roi.cols / 2), radius - config->outsizeSkirt, cv::Scalar(0, 0, 0), -1, 8, 0); //Binarize the roi cv::Mat roi_bin; if(config->blurMask) { cv::medianBlur(roi, roi, config->blurMaskKSize); } //Only calculate otsu if the tolerance is more than 0 if(config->tresholdTolerance > 0.0) { double thresh = Threshold::otsuMask(roi, mask); thresh = (thresh * config->tresholdTolerance) + (config->thresholdValue * (1 - config->tresholdTolerance)); cv::threshold(roi, roi_bin, thresh, 255, cv::THRESH_BINARY); //std::cout << "Semi Automatic threshold: " << thresh << std::endl; } else { cv::threshold(roi, roi_bin, config->thresholdValue, 255, cv::THRESH_BINARY); } //Mask outside of the cork in roi bin bitwise_or(mask, roi_bin, roi_bin); //Invert binary roi bitwise_not(roi_bin, roi_bin); //Measure defective area double count = 0.0; unsigned char *data = (unsigned char*)(roi_bin.data); for(int j = 0; j < roi_bin.rows; j++) { for(int i = 0; i < roi_bin.cols; i++) { if(data[roi_bin.step * j + i] > 0) { count++; } } } double radiusSkirt = (radius - config->outsizeSkirt); double area = PI * radiusSkirt * radiusSkirt; double defect = (count / area) * 100.0; //std::cout << "cv::Points: " << points << std::endl; //std::cout << "Resolution: " << (roi_bin.rows * roi_bin.cols) << std::endl; //std::cout << "Count: " << count << std::endl; //std::cout << "Area: " << area << std::endl; //std::cout << "Defect: " << defect << "%" << std::endl; //Draw debug information #if DEBUG_DEFECTS int channels = image.channels(); //Draw defect for(int i = 0; i < roi_bin.rows; i++) { for(int j = 0; j < roi_bin.cols; j++) { int t = (i * roi_bin.cols + j); if(roi_bin.data[t] > 0) { int k = ((i + roi_rect.y) * image.cols + (j + roi_rect.x)) * channels; image.data[k + 2] = (unsigned char) 255; } } } //Cicle position //cv::circle(image, center, 1, cv::Scalar(255, 0, 0), 2, cv::LINE_AA); cv::circle(image, center, radius, cv::Scalar(0, 255, 0), 1, cv::LINE_AA); //cv::putText(image, std::to_string(defect) + "%", center, cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 255, 255)); #endif if(config->checkIdentation) { std::vector<cv::Vec3f> inside; cv::HoughCircles(roi, inside, cv::HOUGH_GRADIENT, 1, config->minSpacing, config->lowCannyThresh, config->highCannyThresh, 0, static_cast<int>(radius * 0.9)); std::cout << roi.rows << std::endl; if(inside.size() > 0) { config->identation = inside[0]; #if DEBUG_DEFECTS //cv::Point(config->identation[0], config->identation[1]) cv::circle(image, center, config->identation[2], cv::Scalar(255, 0, 0), 1, cv::LINE_AA); #endif } } #if MEASURE_PERFORMANCE_CORK int64 end = cv::getTickCount(); double secs = (end - init) / cv::getTickFrequency(); std::cout << "Cork: Processing time was " << secs << " s." << std::endl; #endif *defectOutput = defect; } /** * Check if a value is in the neighborhood of another one. * * @param value * @param center * @param neighborhood */ static bool isNeighbor(int value, int center, int neighborhood) { return value > (center - neighborhood) && value < (center + neighborhood); } };
true
0c9b1d59a84aba6086b3a3c68c20d819f394e518
C++
Poirault/SpeedRunnerManager
/SpeedRunManager/joueur.cpp
UTF-8
1,453
2.796875
3
[]
no_license
/*! * \class Joueur joueur.h * \brief la class joueur est une liste des joueurs */ #include "joueur.h" /*! * \brief Joueur::Joueur constructeur de base */ Joueur::Joueur() { count = 0; } void Joueur::rename(QString name){ this->nom=name; } void Joueur::newfavorite(Jeu fav){ this->jeu_prefere=&fav; } void Joueur::rebirth(QDate birth){ int a,b,c; birth.getDate(&a,&b,&c); date_naissance.setDate(a,b,c); } /*! * \brief Joueur::rowCount * \return nombre de joueurs */ int Joueur::rowCount(const QModelIndex & /* parent */)const{return count;} /*! * \brief Joueur::data * \param index * \param role * \return */ QVariant Joueur::data(const QModelIndex &index, int role)const { if (!index.isValid()) return QVariant(); if (index.row() >= itemList.size() || index.row() < 0) return QVariant(); if (role == Qt::DisplayRole) { return itemList.at(index.row()); } else if (role == Qt::BackgroundRole) { int batch = (index.row() / 100) % 2; if (batch == 0) return qApp->palette().base(); else return qApp->palette().alternateBase(); } return QVariant(); } void Joueur::newPseudo(QString text){ if(text != "" && !itemList.contains(text)){ QAbstractListModel::beginInsertRows(QModelIndex(),count,count); itemList.append(text); count++; QAbstractListModel::endInsertRows(); }}
true
827a8829219e330dac5ceeb5bc00d8cfb0257cdc
C++
showmic96/Online-Judge-Solution
/LightOJ/1066/8719152_AC_12ms_1704kB.cpp
UTF-8
2,836
2.765625
3
[]
no_license
// In the name of Allah the Lord of the Worlds. #include<bits/stdc++.h> using namespace std; const int MAX = 13; char ar[MAX+9][MAX+9]; int level[MAX+9][MAX+9] , check; int c = 0; int n , counter = 0; bool isAlpha(char x) { //cout << "Char " << x << endl; if(x>='A'&&x<='Z'){return true;} return false; } void bfs(int i , int j , char s , char d) { queue<int>current; current.push(i); current.push(j); level[i][j] = 0; while(!current.empty()){ //cout << i << " " << j << endl; i = current.front();current.pop(); j = current.front();current.pop(); if(ar[i][j]=='#')continue; if(ar[i][j]==d){ c = min(c , level[i][j]); check = true; break; } if(isAlpha(ar[i][j])==true){ if(ar[i][j]!=s){continue;} ar[i][j]= '.'; } if(i+1<n){ if(level[i+1][j]>level[i][j]+1){ level[i+1][j] = level[i][j] + 1; current.push(i+1); current.push(j); } } if(j+1<n){ if(level[i][j+1]>level[i][j]+1){ level[i][j+1] = level[i][j] + 1; current.push(i); current.push(j+1); } } if(i-1>=0){ if(level[i-1][j]>level[i][j]+1){ level[i-1][j] = level[i][j] + 1; current.push(i-1); current.push(j); } } if(j-1>=0){ if(level[i][j-1]>level[i][j]+1){ level[i][j-1] = level[i][j] + 1; current.push(i); current.push(j-1); } } } } void setUp() { for(int i=0;i<MAX;i++){ for(int j=0;j<MAX;j++)level[i][j] = 1234567; } } int main(void) { int t; scanf("%d",&t); for(int i=0;i<t;i++){ counter = 0; scanf("%d",&n); map<char , pair<int , int> > mp; for(int j=0;j<n;j++)cin >> ar[j]; //for(int j=0;j<n;j++)cout << ar[j] << endl; for(int j=0;j<n;j++){ for(int k=0;k<n;k++){ if(isAlpha(ar[j][k])==true){ counter++; mp[ar[j][k]] = make_pair(j , k); } } } int ans = 0; for(int j=0;j<counter-1;j++){ check = false; setUp(); c = 123456; bfs(mp['A'+j].first , mp['A'+j].second , 'A'+j , 'A'+j+1); if(check==false)break; ans+=c; } if(counter==1){check=true;ans=0;} //for(int i=0;i<n;i++)cout << ar[i] << endl; if(check==false)printf("Case %d: Impossible\n",i+1); else printf("Case %d: %d\n",i+1 , ans); } return 0; }
true
1df4346ebef1445c4bd78a6a4f4deb3691f635da
C++
gabrielboroghina/BrickBreaker
/Source/BrickBreaker/Walls.h
UTF-8
412
2.96875
3
[]
no_license
#pragma once #include "Core/GPU/Mesh.h" namespace Object { /** * Object containing the three walls placed on the left, right and top of the game area. */ class Walls { public: static constexpr float thickness = 15; float verticalHeight, topWallWidth; Mesh *meshLeft, *meshRight, *meshTop; Walls(glm::vec2 viewportSize); ~Walls(); private: const glm::vec3 color = glm::vec3(0.48f, 0.08f, 0.23f); }; }
true
c3f25dcb15bf149211d0050570a6f557e7767afd
C++
joshuaanrico/Algoritma-Struktur-Data
/prak asd/[c]AntrianRibet.cpp
UTF-8
2,258
3.25
3
[]
no_license
#include <iostream> #include <stdlib.h> using namespace std; typedef int infotype; typedef struct Node* address; typedef struct Node { infotype x; address next; }List; typedef struct { address head; address tail; }Queue; void createempty(Queue *Q) { Q->head= NULL; Q->tail= NULL; } address alokasi (infotype x) { address P = address(malloc(sizeof(List))); if(P!=NULL) { P->x = x; P->next = NULL; } return P; } void dealokasi(address P) { P->next = NULL; free(P); } void Add(Queue *Q, infotype x) { address P = alokasi(x); if(P!=NULL) { if(Q->head==NULL && Q->tail==NULL) Q->head = P; else Q->tail->next=P; Q->tail = P; } } void Del(Queue *Q, infotype *x) { if(Q->head != NULL && Q->tail != NULL){ *x = Q->head->x; if(Q->head == Q->tail){ dealokasi(Q->head); createempty(Q); return; } address P = Q->head; Q->head = Q->head->next; dealokasi(P); } } void print(Queue Q) { address P = Q.head; cout << '['; if(P!=NULL) { while(P->next != NULL) { cout << P->x << ","; P = P->next; } cout << P->x; } cout <<"]"<<endl; } int main () { int A, B, C, D, ambil, j; Queue Q[3]; createempty(&Q[0]); createempty(&Q[1]); createempty(&Q[2]); cin >> A; for(int i=0; i<A; i++) { cin >> B; for(j=0; j<3; j++) { if(Q[j].tail==NULL) { Add(&Q[j], B); j=100; } else if(B>= Q[j].tail->x) { Add(&Q[j], B); j=100; } } if(j==3) { D = 0; C = Q[0].head->x; for(int i=0; i<3; i++) { if(C>Q[i].head->x) { D = i; C = Q[i].head->x; } } Del(&Q[D], &ambil); } } int sum = 0; while(sum < 3) { cout << "Antrian "<< sum+1 <<":"; print(Q[sum]); sum++; } }
true
08baed30930a22a8ffd2efb1be009b90d548598e
C++
liuzhengzhe/leetcode
/17.cpp
UTF-8
1,202
3.21875
3
[]
no_license
#include <iostream> #include <vector> using namespace std; class Solution { public: vector<string> ret; string convert(char c){ switch(c){ case '0': return " "; case '1': return ""; case '2': return "abc"; case '3': return "def"; case '4': return "ghi"; case '5': return "jkl"; case '6': return "mno"; case '7': return "pqrs"; case '8': return "tuv"; case '9': return "wxyz"; } } void dfs(string d,string have){ if(d.length()==0){ ret.push_back(have); return; } string s=convert(d[0]); for(int i=0;i<s.length();i++){ dfs(d.substr(1,d.length()-1),have+s[i]); } } vector<string> letterCombinations(string digits) { if(digits.length()==0){ return ret; } dfs(digits,""); return ret; } }; int main(){ Solution s; s.letterCombinations("2"); return 0; }
true
1cf79b0ad00199fd9ef5573f4199e494e350409c
C++
cvra/robot-software
/hitl/PhysicsRobot.cpp
UTF-8
2,006
2.796875
3
[ "MIT" ]
permissive
#include "PhysicsRobot.h" PhysicsRobot::PhysicsRobot(b2World& world, float size_x, float size_y, float mass, float pulse_per_mm, b2Vec2 initial_pos, float heading) : size_y(size_y) , pulse_per_mm(pulse_per_mm) , pos_left(0.f) , pos_right(0.f) { b2BodyDef robotDef; robotDef.type = b2_dynamicBody; robotDef.position = initial_pos; robotDef.angle = heading; robotBody = world.CreateBody(&robotDef); b2PolygonShape robotBox; robotBox.SetAsBox(size_x / 2, size_y / 2); robotBody->CreateFixture(&robotBox, mass / (size_x * size_y)); } void PhysicsRobot::ApplyWheelbaseForces(float left, float right) { auto left_wheel_pos = robotBody->GetWorldPoint({0., size_y / 2}); auto right_wheel_pos = robotBody->GetWorldPoint({0., -size_y / 2}); auto left_wheel_force = robotBody->GetWorldVector({left, 0.}); auto right_wheel_force = robotBody->GetWorldVector({right, 0.}); robotBody->ApplyForce(left_wheel_force, left_wheel_pos, true); robotBody->ApplyForce(right_wheel_force, right_wheel_pos, true); // Apply the tires sideways friction // https://www.iforce2d.net/b2dtut/top-down-car b2Vec2 rightNormal = robotBody->GetWorldVector({0, 1}); b2Vec2 lateralVelocity = b2Dot(rightNormal, robotBody->GetLinearVelocity()) * rightNormal; b2Vec2 impulse = robotBody->GetMass() * -lateralVelocity; robotBody->ApplyLinearImpulse(impulse, robotBody->GetWorldCenter(), true); } void PhysicsRobot::AccumulateWheelEncoders(float dt) { auto world_vel = robotBody->GetLinearVelocity(); auto local_vel = robotBody->GetLocalVector(world_vel); pos_left += local_vel.x * dt; pos_right += local_vel.x * dt; auto angle_vel = robotBody->GetAngularVelocity(); pos_left -= 0.5 * size_y * angle_vel * dt; pos_right += 0.5 * size_y * angle_vel * dt; } void PhysicsRobot::GetWheelEncoders(int& left, int& right) const { left = 1000 * pulse_per_mm * pos_left; right = 1000 * pulse_per_mm * pos_right; }
true
902ceec2b4e4d14513f8a38bd02a30f210eb20f0
C++
mgula/cisc361proj
/Node.cpp
UTF-8
2,110
3.640625
4
[]
no_license
/* * Marcus Gula * Thomas Nelson * CISC 361 * Project 1 * */ #include <iostream> #include <stdlib.h> #include "Node.h" using namespace std; /*Traverse the system node and print information*/ void printSystem(Node *list) { Node *temp = list; if (temp->next == NULL) { cout << "No jobs have arrived yet." << endl; } else { while (temp != NULL) { if (temp->head == false) { cout << "Job number: " << temp->jobNumber << " | Status: "; if (temp->status == "Completed") { cout << temp->status << " at time " << temp->completionTime << " | Turnaround Time: " << temp->turnaroundTime << " | Weighted Turnaround Time: "; std::printf("%.2f", temp->weightedTT); } else { cout << temp->status << " | Time Remaining: " << temp->remainingTime; } cout << endl; } temp = temp->next; } } } /*Traverse a list and print information about each node*/ void traverseAndPrint(Node *list) { Node *temp = list; if (temp->next == NULL) { cout << "This Queue is empty." << endl; } else { int i = 1; while (temp != NULL) { if (temp->head == false) { cout << "Place in queue: " << i << " | Job number: " << temp->jobNumber << " " << endl; i++; } temp = temp->next; } } } /*Add node to front of list*/ void addToFront(Node *head, Node *addition) { Node *temp = new Node; temp->next = head->next; head->next = addition; addition->next = temp->next; } /*Add node to end of list*/ void addToEnd(Node *head, Node *addition) { if (head->next == NULL) { head->next = addition; addition->next = NULL; } else { Node *temp = head; while (temp->next != NULL) { temp = temp->next; } temp->next = addition; addition->next = NULL; } } /*Remove a node from a list and return that node*/ Node *remove(Node *head, int target){ Node *temp = head; Node *tempPrev = NULL; //Keep track of previous node while(temp != NULL) { if (temp->jobNumber == target) { tempPrev->next = temp->next; //Remove selected node from queue temp->next = NULL; return temp; } tempPrev = temp; temp = temp->next; } return NULL; //Node not in list }
true
39eb16b2c1668b0f5ac42501a1c1a1e5d2d8528f
C++
desperadoray/POJ
/矩阵乘方和.cpp
WINDOWS-1252
1,899
3.125
3
[]
no_license
#include <iostream> using namespace std; int n, k, m; int matrix[31][31] = {0}; void Matrix_Add(int a[31][31], int b[31][31], int c[31][31]) { for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) c[i][j] = (a[i][j] + b[i][j]) % m; } void Matrix_Multiply(int a[31][31], int b[31][31], int c[31][31]) { for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { c[i][j] = 0; for (int k = 0; k < n; k++) c[i][j] = (c[i][j] + a[i][k] * b[k][j]) % m; } } void Matrix_Power(int a[31][31], int k, int b[31][31]) { memset(b, 0, sizeof(b)); if (k == 1) { for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) b[i][j] = a[i][j]; return; } int temp1[31][31] = {0}; int temp2[31][31] = {0}; Matrix_Power(a, k/2, temp1); Matrix_Multiply(temp1, temp1, temp2); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) b[i][j] = temp2[i][j]; if ((k & 1) == 1) Matrix_Multiply(a, temp2, b); return; } void f(int a[31][31], int k, int result[31][31]) { if (k == 1) { for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) result[i][j] = a[i][j]; return; } int temp1[31][31] = {0}; int temp2[31][31] = {0}; int temp3[31][31] = {0}; f(a, k/2, temp1);//A + A^2 + ... + A^(k/2) Matrix_Power(a, k/2, temp3);//A^(k/2) Matrix_Multiply(temp1, temp3, temp2); Matrix_Add(temp1, temp2, result);//temp1A+A^2+...A^(k/2*2) if ((k & 1) == 1) { Matrix_Power(temp3, 2, temp2);//A^(k/2*2) memset(temp3, 0, sizeof(temp3)); Matrix_Multiply(temp2, a, temp3); Matrix_Add(temp3, result, result); } } int main() { cin >> n >> k >> m; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) cin >> matrix[i][j]; int result[31][31] = {0}; f(matrix, k, result); for (int i = 0; i < n; i++) { for (int j = 0; j < n-1; j++) cout << result[i][j] << " "; cout << result[i][n-1] << endl; } system("pause"); return 0; }
true
1957b5d7b2da794014780115a2dbf8679d9b2af5
C++
RMariowski/Graphics-and-multimedia-laboratory
/11 - Morphing/Triangle.cpp
UTF-8
864
2.84375
3
[ "MIT" ]
permissive
#include "Triangle.h" #include <QColor> Triangle::Triangle() : _image(0) { } Triangle::Triangle(QImage* image, const QList<Marker>& markers) : _image(image) { for (int i = 0; i < 3; i++) _vertices[i] = QVector2D(markers[i].getX(), markers[i].getY()); } Triangle::Triangle(QVector2D v1, QVector2D v2, QVector2D v3) : _image(0) { _vertices[0] = v1; _vertices[1] = v2; _vertices[2] = v3; } void Triangle::createImage(int width, int height) { _image = new QImage(width, height, QImage::Format_ARGB32); resetImage(); } void Triangle::resetImage() { QRgb whiteColor = QColor(255, 0, 0, 0).rgba(); for (int y = 0; y < _image->height(); y++) { for (int x = 0; x < _image->width(); x++) _image->setPixel(QPoint(x, y), whiteColor); } } void Triangle::deleteImage() { delete _image; }
true
554082aabcc4cabad97207903830c606b545d516
C++
Dhurjati-Prasad-Das/Programs_basic_c-_visual-studio
/MISC_Class_iss.cpp
UTF-8
348
3.203125
3
[]
no_license
#include<iostream> using namespace std; class example{ private: int data; static int count; public: example(); void display() const; }; int example::count=10; example::example(){ data=0; } void example::display() const{ cout<<endl<<"count="<<data<<count; } int main(){ example d; d.display(); return 0; }
true
9a1c4140fabc763918ad284df2bbe63d553dc3f0
C++
Tonin386/MvisualizerPP
/classes/particlecluster.cpp
UTF-8
3,133
2.515625
3
[]
no_license
#include "particle.hpp" #include "particlecluster.hpp" #include "note.hpp" #include "../constants.hpp" #include <random> #include <cmath> #include <iostream> #include <stdio.h> #include <stdlib.h> using namespace sf; using namespace std; ParticleCluster::ParticleCluster(Note* parentNote, int protocol, Color color) : _parentNote(parentNote), _protocol(protocol), _color(color) { //Need to figure out how to create the particles of a cluster extern Clock PROCESS_TIME; default_random_engine gen; int n = 0; switch(_protocol) { default: case 0: //Not full circle { n = _parentNote->getVelocity()/4; break; } case 1: //Full circle { n = 900; break; } case 2: //Case 0 but random x { n = _parentNote->getVelocity()/8; break; } case 3: //Cool waves { n = _parentNote->getVelocity()/6; break; } } for(int i = 0; i < n; i++) { _origin.y = ((int)(_parentNote->getNote()*6845864)) % HEIGHT; double deg = 0; double acceleration = _parentNote->getVelocity()/20 + (double)(rand() % 6000)/(double)1000 - (double)(rand() % 6000)/(double)1000; double accelerationDecay = acceleration/1000;; switch(_protocol) { default: case 0: { deg = rand() % 360; _origin.x = (int)((_parentNote->getNote() - 21) * (WIDTH/87)); break; } case 1: { deg = (double)i * 0.4; acceleration = _parentNote->getVelocity() / 32; accelerationDecay = 0.005; _origin.x = (int)(_parentNote->getTimeOn() * 10000) % WIDTH; _origin.y = ((int)(_parentNote->getNote()*684864)) % HEIGHT; break; } case 2: { deg = rand() % 360; _origin.x = rand() % WIDTH; break; } case 3: { deg = (int)(PROCESS_TIME.getElapsedTime().asSeconds()*90) % 360; deg = (int)(deg + (180 * (rand() % 2))) % 360; _origin.x = (int)((_parentNote->getNote() - 21) * (WIDTH/87)); acceleration *= 4; break; } } if(acceleration < 1) acceleration = 1; Color pColor = _color; int intensity = 1 + rand() % 5; if(_protocol != 1) { pColor.r -= intensity*10; pColor.g -= intensity*10; pColor.b -= intensity*10; } if(_protocol != 1 || _parentNote->getChildCluster() == nullptr) { Particle *p = new Particle(this, acceleration, accelerationDecay, pColor, deg, _origin); _particles.push_back(p); } } _parentNote->setChild(this); } void ParticleCluster::moveParticles() { for(int i = 0; i < _particles.size(); i++) { if(_particles[i]->isActive()) { _particles[i]->move(); } else { Particle* particle = _particles[i]; _particles.erase(_particles.begin() + i); i--; delete particle; } } } void ParticleCluster::addParticle(Particle* p) { _particles.push_back(p); } Note* ParticleCluster::getParentNote() const { return _parentNote; } Vector2f ParticleCluster::getOrigin() const { return _origin; } vector<Particle*> ParticleCluster::getParticles() const { return _particles; } int ParticleCluster::getProtocol()const { return _protocol; } Color ParticleCluster::getColor() const { return _color; } ParticleCluster::~ParticleCluster() { }
true
37ec97af272eceb8ed9a64c6eacdb202a0d5ec45
C++
siddharthshenoy/LEET
/count-primes/count-primes.cpp
UTF-8
431
2.796875
3
[ "MIT" ]
permissive
class Solution { public: int countPrimes(int n) { vector<bool> sieve(n, true); for (int i = 2; i <= sqrt(n); ++i) { if (sieve[i]) { for (int ii = i*i; ii < n; ii += i) { sieve[ii] = false; } } } int ans = 0; for (int i = 2; i < n; ++i) if (sieve[i]) ++ans; return ans; } };
true
b0f3f0bba8918c9c2c50a54ece0a3d39ba73d800
C++
ElementAyush/Code
/OnlineJudges/Hackerrank/Lily's Homework/main.cpp
UTF-8
682
2.828125
3
[]
no_license
#include <bits/stdc++.h> using namespace std ; int solve(vector<int> vec) { int count = 0 ; map<long , long> keyPair ; for(int i = 0 ; i < vec.size() ; i++) keyPair[vec[i]] = i ; vector<int> sorted ; sorted = vec ; sort(sorted.begin() , sorted.end()) ; for(int i = 0 ; i < vec.size() ; i++) { if(vec[i] != sorted[i]) count++ ; int tempSwap = keyPair[sorted[i]] ; keyPair[vec[i]] = keyPair[sorted[i]] ; vec[i] = sorted[i] ; vec[tempSwap] = vec[i] ; } return count ; } int main() { int n = 4 ; vector<int> vec = {2,5,3,1} ; cout << solve(vec) << "\n" ; reverse(vec.begin() , vec.end()) ; cout << solve(vec) << "\n" ; }
true
851e93a4a08a4d27fbe913efe7ef09fb00c580a5
C++
o2themar/cse471Synthesizer
/Step5/Synthie/NoiseGate.h
UTF-8
340
2.59375
3
[]
no_license
#pragma once #include "audionode.h" class CNoiseGate : public CAudioNode { public: CNoiseGate(void); ~CNoiseGate(void); virtual void Start(); virtual bool Generate(); void SetNode(CAudioNode* node) { m_node = node; } void SetThreshold(short thresh) { m_threshold = thresh; } private: CAudioNode* m_node; short m_threshold; };
true
d22498e96321c3a6a445f91ccb72735c881e9403
C++
Eleveneat/myCpp
/Sicily/1034_Forest/1034.cpp
UTF-8
2,566
2.875
3
[]
no_license
/* * Filename: 1034.cpp * Description: NULL * Last modified: 2016-01-09 22:14 * * Created by Eleven on 2016-01-09 * Email: eleveneat@gmail.com * Copyright (C) 2015 Eleven. All rights reserved. */ #include <iostream> #include <cstring> #include <cstdio> #include <vector> #define MAX 110 using namespace std; int nodesNum, edgesNum; int in[MAX], tree[MAX][MAX], width[MAX]; bool isVisit[MAX]; vector<int> inIs0; // 入度为0的点的集合,即根节点的集合。 bool isValid; int maxHeight, maxWidth; void dfs(int node, int height) { if (height > maxHeight) maxHeight = height; for (int i = 1; i <= nodesNum; i++) { if (tree[node][i]) { if (isVisit[i]) { // 存在环的情况 isValid = false; return; } else { isVisit[i] = true; } width[height + 1]++; dfs(i, height + 1); if (!isValid) return; } } } int main() { while (scanf("%d%d", &nodesNum, &edgesNum) && nodesNum) { inIs0.clear(); memset(in, 0, MAX * sizeof(int) ); memset(width, 0, MAX * sizeof(int) ); memset(isVisit, false, MAX * sizeof(bool) ); memset(tree, 0, MAX * MAX * sizeof(int) ); isValid = true; for (int i = 0; i < edgesNum; i++) { int nodeA, nodeB; scanf("%d%d", &nodeA, &nodeB); tree[nodeA][nodeB] = 1; if (in[nodeB] == 1) // 判断入度是否会超过1 isValid = false; else in[nodeB] = 1; } if (!isValid) { // 存在入度大于1的情况 printf("INVALID\n"); continue; } for (int i = 1; i <= nodesNum; i++) if (in[i] == 0) inIs0.push_back(i); maxHeight = maxWidth = 0; for (int i = 0; i < inIs0.size(); i++) { int node = inIs0[i]; isVisit[node] = true; width[0]++; dfs(node, 0); if (!isValid) break; } for (int i = 1; i <= nodesNum; i++) // 除非存在环,不然已遍历所有节点 if (!isVisit[i]) isValid = false; if (!isValid) { printf("INVALID\n"); continue; } for (int i = 0; i <= maxHeight; i++) // 找出最大宽度 if (maxWidth < width[i]) maxWidth = width[i]; printf("%d %d\n", maxHeight, maxWidth); } return 0; }
true
a5485cb61beb041610b11a9b0b11e67bab3d13ae
C++
dvetutnev/boost-di-example
/di/test_group.cpp
UTF-8
2,073
2.546875
3
[ "MIT" ]
permissive
#include "group.h" #include "mocks.h" #include <gtest/gtest.h> using ::testing::Return; using ::testing::ReturnRef; using ::testing::ByMove; using ::testing::InSequence; namespace di = boost::di; namespace { const auto ssid = Ssid{"Casiopea"}; auto config = []() { return make_injector( di::bind<IFactoryExecuter>().to<MockFactoryExecuter>().in(di::singleton), di::bind<IGroup>().to<Group>(), di::bind<Ssid>().to(ssid), di::bind<GroupSize>().to(GroupSize{2}) ); }; } // Anonymous namespace TEST(Group, severalId) { auto injector = di::make_injector(config()); auto& mock = injector.create<MockFactoryExecuter&>(); { InSequence _; EXPECT_CALL(mock, create(Ssid{ssid}, Id{"0"})) .WillOnce(Return(ByMove(std::make_unique<MockExecuter>()))) ; EXPECT_CALL(mock, create(Ssid{ssid}, Id{"1"})) .WillOnce(Return(ByMove(std::make_unique<MockExecuter>()))) ; } auto group = injector.create<std::unique_ptr<IGroup>>(); IExecuter& executer1 = group->getExecuter(); IExecuter& executer2 = group->getExecuter(); } TEST(Group, ringId) { auto injector = di::make_injector(config()); auto& mock = injector.create<MockFactoryExecuter&>(); const Id id0{"0"}; auto executer0 = std::make_unique<MockExecuter>(); EXPECT_CALL(*executer0, getId) .WillRepeatedly(ReturnRef(id0)) ; EXPECT_CALL(mock, create(Ssid{ssid}, Id{id0})) .WillOnce(Return(ByMove(std::move(executer0)))) ; const Id id1{"1"}; auto executer1 = std::make_unique<MockExecuter>(); EXPECT_CALL(mock, create(Ssid{ssid}, Id{id1})) .WillOnce(Return(ByMove(std::move(executer1)))) ; auto group = injector.create<std::unique_ptr<IGroup>>(); IExecuter& _0 = group->getExecuter(); IExecuter& _1 = group->getExecuter(); IExecuter& executer = group->getExecuter(); EXPECT_EQ(&_0, &executer); EXPECT_EQ(executer.getId(), Id{"0"}); }
true
d168efb41d9610f5e0ff63931b9b192c4f90bbfa
C++
SimaoAraujo/ScopeMainProcess
/text.cpp
UTF-8
2,456
2.59375
3
[]
no_license
#include "text.h" CText* CText::instance = nullptr; CText* CText::getInstance() { if(!instance) instance = new CText(); return instance; } int CText::recordCount = 0; CText::CText() { } CText::~CText() { } int CText::getRecord() { string sLastRecordCount; int iLastRecordCount; ifstream lastRecord_in("/etc/SCOPE/lastRecord.txt"); if(lastRecord_in.is_open()) { getline(lastRecord_in, sLastRecordCount); lastRecord_in.close(); iLastRecordCount = stoi(sLastRecordCount); recordCount = iLastRecordCount; return recordCount; } else { cout << "Unable to open file"; } } void CText::createFile(string name, string text) { string create = "/etc/SCOPE/records/record" + to_string(recordCount) + "/" + name + ".txt"; ofstream outfile (create.c_str()); outfile << text << endl; outfile.close(); cout << "CText::createFile()" << endl; } void CText::assemble() { tesseract::TessBaseAPI *oTesseract = new tesseract::TessBaseAPI(); // Initialize tesseract-ocr with English, without specifying tessdata path if (oTesseract->Init(NULL, "eng", OEM_LSTM_ONLY)) { cout << "Could not initialize tesseract.\n" << endl; } oTesseract->SetPageSegMode(PSM_AUTO); getRecord(); // Open input image with opencv library Mat image = imread("/etc/SCOPE/records/record" + to_string(recordCount) + "/image.jpeg"); oTesseract->SetImage(image.data, image.cols, image.rows, 3, image.step); // Get OCR result char* outText = oTesseract->GetUTF8Text(); createFile("text", outText); // Destroy used object and release memory oTesseract->End(); delete oTesseract; delete [] outText; } void* CText::tAssembleText(void *ptr) { extern sem_t semAssembleText, semGenerateAudio; extern pthread_cond_t condAssembleText, condGenerateAudio; extern pthread_mutex_t mutexAssembleText, mutexGenerateAudio, mutexText; while(1) { pthread_mutex_lock(&mutexAssembleText); pthread_cond_wait(&condAssembleText, &mutexAssembleText); pthread_mutex_unlock(&mutexAssembleText); pthread_mutex_lock(&mutexText); CText::getInstance()->assemble(); pthread_mutex_unlock(&mutexText); pthread_mutex_lock(&mutexGenerateAudio); pthread_cond_signal(&condGenerateAudio); pthread_mutex_unlock(&mutexGenerateAudio); } }
true
4f04b9dd2b6c70b14fd15c00169a24b5b1949135
C++
hubartstephane/Code
/libraries/chaos/include/chaos/Gameplay/GameParticles.h
UTF-8
3,293
2.6875
3
[]
no_license
namespace chaos { #ifdef CHAOS_FORWARD_DECLARATION class ParticleBackground; class ParticleBackgroundLayerTrait; #elif !defined CHAOS_TEMPLATE_IMPLEMENTATION // =========================================================================== // Background particle system // =========================================================================== class CHAOS_API ParticleBackground { public: glm::vec4 color; }; CHAOS_REGISTER_CLASS(ParticleBackground); class CHAOS_API ParticleBackgroundLayerTrait : public ParticleLayerTrait<ParticleBackground, VertexDefault> { public: /** constructor */ ParticleBackgroundLayerTrait() { dynamic_particles = dynamic_vertices = false; } /** copy constructor */ ParticleBackgroundLayerTrait(ParticleBackgroundLayerTrait const& src) = default; }; /** output primitive */ template<typename VERTEX_TYPE> /*CHAOS_API*/ void ParticleToPrimitives(ParticleBackground const& particle, PrimitiveOutput<VERTEX_TYPE>& output); /** generates 1 quad from one particle */ template<typename VERTEX_TYPE> /*CHAOS_API*/ void ParticleToPrimitive(ParticleBackground const& particle, QuadPrimitive<VERTEX_TYPE>& primitive); /** generates 1 triangle pair from one particle */ template<typename VERTEX_TYPE> /*CHAOS_API*/ void ParticleToPrimitive(ParticleBackground const& particle, TrianglePairPrimitive<VERTEX_TYPE>& primitive); #else template<typename VERTEX_TYPE> void ParticleToPrimitives(ParticleBackground const& particle, PrimitiveOutput<VERTEX_TYPE>& output) { QuadPrimitive<VERTEX_TYPE> quad = output.AddQuads(); ParticleToPrimitive(particle, quad); } template<typename VERTEX_TYPE> void ParticleToPrimitive(ParticleBackground const& particle, QuadPrimitive<VERTEX_TYPE>& primitive) { primitive[0].position = glm::vec2(-1.0f, -1.0f); primitive[1].position = glm::vec2(+1.0f, -1.0f); primitive[2].position = glm::vec2(+1.0f, +1.0f); primitive[3].position = glm::vec2(-1.0f, +1.0f); for (VERTEX_TYPE& vertex : primitive) { glm::vec2 texcoord = vertex.position * 0.5f + glm::vec2(0.5f, 0.5f); vertex.texcoord.x = texcoord.x; vertex.texcoord.y = texcoord.y; vertex.texcoord.z = 0.0f; vertex.color = particle.color; } } template<typename VERTEX_TYPE> void ParticleToPrimitive(ParticleBackground const& particle, TrianglePairPrimitive<VERTEX_TYPE>& primitive) { primitive[0].position = glm::vec2(-1.0f, -1.0f); primitive[1].position = glm::vec2(+1.0f, -1.0f); primitive[2].position = glm::vec2(-1.0f, +1.0f); primitive[3].position = glm::vec2(-1.0f, +1.0f); primitive[4].position = glm::vec2(+1.0f, -1.0f); primitive[5].position = glm::vec2(+1.0f, +1.0f); for (VERTEX_TYPE& vertex : primitive) { glm::vec2 texcoord = vertex.position * 0.5f + glm::vec2(0.5f, 0.5f); vertex.texcoord.x = texcoord.x; vertex.texcoord.y = texcoord.y; vertex.texcoord.z = 0.0f; vertex.color = particle.color; } } #endif }; // namespace chaos
true
e1500ec917f9fa9ac2d7d5d288f20cbf5b2957d8
C++
ddeuber/RandAlign
/samfile.cpp
UTF-8
3,055
2.734375
3
[]
no_license
#include "samfile.h" #include <iostream> SAMFile::SAMFile(std::string const &fileName, std::string const &refSeqName, int refSeqLength){ file.open(fileName); file << "@HD\tN:1.4\tSO:unsorted"; for (int i=0; i<8; ++i) file << tab; file << endline; file << "@SQ\tSN:" << refSeqName << "\tLN:" << refSeqLength; for (int i=0; i<8; ++i) file << tab; file << endline; this->refSeqName = refSeqName; } void SAMFile::close(){ file.close(); } void SAMFile::add_paired_read_entry(std::string const &readName, std::string const &readSeq1, std::string const &qualSeq1, int pos1, std::string const &cigar1, std::string const &readSeq2, std::string const &qualSeq2, int pos2, std::string const &cigar2, bool read1Reversed, int mapQuality1, int mapQuality2){ int tempLen; if (read1Reversed) { tempLen = pos1 - pos2 + readSeq1.length(); add_single_entry(readName, true, readSeq1, qualSeq1, true, pos1, cigar1, pos2, -tempLen, mapQuality1); add_single_entry(readName, false, readSeq2, qualSeq2, false, pos2, cigar2, pos1, tempLen, mapQuality2); } else { tempLen = pos2 - pos1 + readSeq2.length(); add_single_entry(readName, true, readSeq1, qualSeq1, false, pos1, cigar1, pos2, tempLen, mapQuality1); add_single_entry(readName, false, readSeq2, qualSeq2, true, pos2, cigar2, pos1, -tempLen, mapQuality2); } } void SAMFile::add_single_entry(std::string const &readName, bool isRead1, std::string const &readSeq, std::string const &qualSeq, bool isReverse, int pos, std::string const &cigar, int posNext, int tempLen, int mapQuality){ file << readName << tab; file << generate_flag(pos, isReverse, isRead1, posNext) << tab; file << refSeqName << tab; file << pos << tab; file << mapQuality << tab; file << cigar << tab; file << "=" << tab; file << posNext << tab; file << tempLen << tab; file << readSeq << tab; file << qualSeq << endline; } int SAMFile::generate_flag(int pos, bool isReverse, bool isRead1, int posOtherRead){ int flag = 1; if (pos > 0 && posOtherRead > 0) flag |= 2; if (pos == 0) flag |= 4; if (posOtherRead == 0) flag |= 8; if (isReverse) flag |= 16; else flag |= 32; if (isRead1) flag |= 64; else flag |= 128; return flag; } std::string SAMFile::alignment_to_CIGAR(std::string const &dnaAligned, std::string const &readAligned){ std::string cifar = ""; char lastmode = '!'; //one of 'M' (match), 'I' (insert in reference), 'D' (deletion in reference), 'X' mismatch char mode; int count; char c1, c2; for (unsigned int i=0; i < dnaAligned.length(); ++i){ c1 = dnaAligned[i]; c2 = readAligned[i]; if (c1 == c2) mode = 'M'; else if (c1 == '-') mode = 'I'; else if (c2 == '-') mode = 'D'; else mode = 'X'; if (mode == lastmode) { ++count; } else if (lastmode == '!'){ lastmode = mode; count = 1; } else { cifar += std::to_string(count); cifar += lastmode; lastmode = mode; count = 1; } } cifar += std::to_string(count); cifar += lastmode; return cifar; }
true
ec5fd11f73aef1e58ae655145d00f47ab60475a2
C++
chenwei182729/code
/C/niu/剑指offer/二维数组中值得查找.cpp
GB18030
1,461
3.5
4
[]
no_license
#include<iostream> #include<vector> using namespace std; class Solution { public: bool Find(vector<vector<int> > array,int target) { bool found = false; if(array.size() > 0 && array[0].size() > 0) { int rows = array.size(),columns = array[0].size(),row = 0, column = columns - 1 ; while(row < rows && column >= 0) { int tmp = array[row][column]; if(tmp == target) { found = true; break; } else if(tmp > target) --column; else ++row; } } return found; } //lengthΪţϵͳ涨ַ󳤶ȣ̶Ϊһ void replaceSpace(char *str,int length) { if(str == NULL && length == 0) return ; int realLength = 0,numberOfBlank = 0; int idx = 0 ; while(str[idx]!='\0') { ++realLength; if(str[idx]==' ') ++numberOfBlank; ++idx; } int newLength = realLength + numberOfBlank * 2; if(newLength > length) return ; int indexOfOriginal = realLength; int indexOfNew = newLength; while(indexOfOriginal >= 0 && indexOfNew > indexOfOriginal) { if(str[indexOfOriginal] == ' ') { str[indexOfNew--] = '0'; str[indexOfNew--] = '2'; str[indexOfNew--] = '%'; } else { str[indexOfNew--] = str[indexOfOriginal]; } --indexOfOriginal; } } }; int main(void) { Solution solution; bool flag=solution.Find({{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,5}},7); cout << flag << endl; return 0; }
true
62867294c7cdd1cefe08a7bd30c7c7a3625f2e24
C++
rhayatin/C--
/DCEPC201.cpp
UTF-8
1,152
2.78125
3
[]
no_license
#include<iostream> #include<string.h> #include<stdio.h> using namespace std; char str[20],str1[20]; int ans=1000,cnt=1000,len,kill_task=0; int toggle(int a) { if(str[a]=='1') str[a]='0'; else str[a]='1'; } int swap_index(int a) { if(a!=0) toggle(a-1); toggle(a); if(a!=len-1) toggle(a+1); } int find_ans() { int flag=0; for(int i=0;i<len;i++) { if(str[i]=='1') { flag=1; break; } } if(flag==0) if(ans>cnt) { ans=cnt; kill_task=1; } } int main() { int t, num1; scanf("%d",&t); while ( t-- ) { ans=1000; cnt=1000; scanf("%s" ,&str); strcpy(str1,str); len=strlen(str); int num=0; //For storing number from input as a number /* for(int i=len-1;i>=0;i--) if(str[i]=='1') { int num2 = 1<<(len-1-i); num = num + num2; } */ num1=1<<len; num=num1-1; kill_task=0; while ( num >= 0 && kill_task==0) { strcpy(str,str1); num1=num; cnt=0; for(int i=0;num1!=0;i++) { if(num1&1==1) { cnt++; swap_index(i); } num1=num1>>1; } find_ans(); num--; } if(ans==1000) ans=-1; printf("%d\n",ans); } }
true
d9094f949207f2e372306d65ae49828302674166
C++
yuanyewa/learnsystemc
/basic/06_time/time.cpp
UTF-8
1,292
2.578125
3
[]
no_license
// Yuanye Wang, 2020, MIT license #include <systemc> using namespace sc_core; int sc_main(int, char*[]) { sc_core::sc_report_handler::set_actions( "/IEEE_Std_1666/deprecated", sc_core::SC_DO_NOTHING ); // suppress warning due to set_time_resolution sc_set_time_resolution(1, SC_FS); // deprecated function but still useful, default is 1 PS sc_set_default_time_unit(1, SC_SEC); // change time unit to 1 second std::cout << "1 SEC = " << sc_time(1, SC_SEC).to_default_time_units() << " SEC"<< std::endl; std::cout << "1 MS = " << sc_time(1, SC_MS).to_default_time_units() << " SEC"<< std::endl; std::cout << "1 US = " << sc_time(1, SC_US).to_default_time_units() << " SEC"<< std::endl; std::cout << "1 NS = " << sc_time(1, SC_NS).to_default_time_units() << " SEC"<< std::endl; std::cout << "1 PS = " << sc_time(1, SC_PS).to_default_time_units() << " SEC"<< std::endl; std::cout << "1 FS = " << sc_time(1, SC_FS).to_default_time_units() << " SEC"<< std::endl; sc_start(7261, SC_SEC); // run simulation for 7261 second double t = sc_time_stamp().to_seconds(); // get time in second std::cout << int(t) / 3600 << " hours, " << (int(t) % 3600) / 60 << " minutes, " << (int(t) % 60) << "seconds" << std::endl; return 0; }
true
c3b70f25ed6f797a1fd6eaa2e8ae30ff1e581616
C++
therocode/space
/src/tableutil.hpp
UTF-8
546
2.59375
3
[]
no_license
#pragma once #include <thero/optional.hpp> #include "insert.hpp" template <typename DataType> th::Optional<int32_t> tableEmplaceOptional(int32_t id, th::Optional<DataType> data, DataTable<DataType, true>& table) { if(data) return insert(id, std::move(*data), table).id; else return {}; } template <typename DataType> th::Optional<int32_t> tableEmplaceOptional(th::Optional<DataType> data, DataTable<DataType, false>& table) { if(data) return insert(std::move(*data), table).id; else return {}; }
true
ab0c720f56265444c6f4f9b4f5b8a3efcb04d3cd
C++
mrjai24/Code-Samples--C--
/SFML_Template/SFML_Template/SFML_Template/include/Bullet.h
UTF-8
529
2.640625
3
[]
no_license
#pragma once //Adding in additional libraries. #include <SFML/Graphics.hpp> #include <SFML/System.hpp> #include <SFML/Window.hpp> #include <iostream> using namespace std; using namespace sf; class Bullet { private: //Variables. Sprite sprite; Vector2f direction; float fBulletSpeed; public: //Constructor. Bullet(Texture* texture, float fPosX, float fPosY, float fDirX, float fDirY, float fSpeed); //Accessors. const FloatRect getBounds() const; //Functions. void update(); void render(RenderTarget* target); };
true
7ff24fac4171d1be48ae60588aab06ef73634e45
C++
ashwani65/Coding-Interview-Prepration
/3)-Recursion/A3firstoccur.cpp
UTF-8
433
2.875
3
[]
no_license
#include<iostream> using namespace std; #define rep(i,n) for(int i=0;i<(n);i++) int first(int a[], int n, int x) { if(n==0) return -1; if(a[0]==x) return 0; int ans= first(a+1,n-1,x); if(ans!=-1){ return ans+1; } else{ return ans; } } int main(){ int n; cin>>n; int arr[n]; rep(i,n){ cin>>arr[i]; } int k; cin>>k; cout<<first(arr,n,k); return 0; }
true
16971777a9541740c8343910f3c96d2e1405aa6c
C++
IHR57/Competitive-Programming
/CodeForces/573A-1.cpp
UTF-8
816
2.5625
3
[]
no_license
#include <bits/stdc++.h> #define MAX 100005 using namespace std; typedef long long ll; int main() { ios::sync_with_stdio(0), cin.tie(0), cout.tie(0); ll n, value, t; cin>>n; cin>>value; t = value; ll result = 1; while(value % 2 == 0){ value /= 2; result *= 2; } while(value % 3 == 0){ value /= 3; result *= 3; } result = t / result; for(int i = 1; i < n; i++){ cin>>value; t = value; ll temp = 1; while(value % 2 == 0){ value /= 2; temp *= 2; } while(value % 3 == 0){ value /= 3; temp *= 3; } //cout<<t/temp<<endl; if(t / temp != result){ cout<<"No"<<endl; return 0; } } cout<<"Yes"<<endl; return 0; }
true
56bdfab175133e01ef286bbdc108cf766202ab59
C++
esdream/AIEngineer
/julyDSA/STL/heap.cpp
UTF-8
2,130
3.890625
4
[]
no_license
#include <iostream> #include <vector> #include <algorithm> // 引入algorithm头文件才能使用heap相关操作 using namespace std; bool compareLess(int num1, int num2) { return num1 > num2; } int main() { vector<int> v{6, 1, 2, 5, 3, 4}; cout << "source vector: "; for (auto val : v) { cout << val << ","; } cout << endl; // make_heap:建堆,默认建立最大堆 make_heap(v.begin(), v.end()); cout << "heap vector: "; for(auto val: v) { cout << val << ","; } cout << endl; // push_heap: 当堆中增加一个元素至最末尾时,用来调整堆 v.push_back(8); push_heap(v.begin(), v.end()); cout << "push_heap:"; for (auto val : v) { cout << val << ","; } cout << endl; // pop_heap:将堆顶元素与最后一个叶子节点交换位置,并调整堆(不包括交换位置后的原堆顶元素),此时最后一个节点就是弹出的堆顶元素 pop_heap(v.begin(), v.end()); cout << "pop vector: "; for (auto val : v) { cout << val << ","; } cout << endl; // make_heap默认建立最大堆,可以通过辅助函数定义建堆规则,如这里变成建立最小堆 make_heap(v.begin(), v.end(), compareLess); cout << "min heap: "; for (auto val : v) { cout << val << ","; } cout << endl; // sort_heap:堆排序算法,通过每次弹出堆顶元素直至堆为空 // 排序结束后已经是一个有序列表,不再是堆了 sort_heap(v.begin(), v.end(), compareLess); cout << "sort heap: "; for (auto val : v) { cout << val << ","; } cout << endl; // is_heap:判断是否是堆 vector<int> v1{6, 1, 2, 5, 3, 4}; cout << is_heap(v1.begin(), v1.end()) << endl; make_heap(v1.begin(), v1.end()); cout << is_heap(v1.begin(), v1.end()) << endl; // is_heap_until:返回第一个不满足heap条件的元素 vector<int> v2{6, 1, 2, 5, 3, 4}; auto iter = is_heap_until(v2.begin(), v2.end()); cout << *iter << endl; return 0; }
true
84772ca67d8e09594cc794fc38e5591e7222a477
C++
AnupamDas054/competitve-programming
/codeforces/1130A.cpp
UTF-8
770
2.515625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int m=0,r=0; for(int i=0;i<n;i++) { int k; cin>>k; if(k==0) { } else if(k<0) { m++; } else { r++; } } // cout<<ceil((double)n/2)<<endl; if(r>=ceil((double)n/2)) { cout<<"1\n"; return 0; } if(m>r) { if(m>=ceil((double)n/2)) { cout<<"-1\n"; } else { cout<<"0\n"; } } else { if(r>=ceil((double)n/2)) { cout<<"1\n"; } else { cout<<"0\n"; } } }
true
289c48947da094a504ac6f93aca915715a8a2f35
C++
Orochisun/CattleCorn
/main.cpp
GB18030
7,867
2.640625
3
[]
no_license
#include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> using namespace std; #define MAX_CAILD_NODES 9 #define RED 0 #define BLUE 1 #define REDSTONE 0 #define BLUESTONE1 1 #define BLUESTONE2 2 #define MAXDEPTH 10 #define MAX 1 #define MIN -1 #define INV -1 int alpha, bate; int preTable[2][10][5]{ { //red { 2, 1, INV },{ 2, 3, 0, INV }, { 4, 3, 1, 0, INV },{ 5, 4, 2, 1, INV }, { 6, 5, 3, 2, INV },{ 7, 6, 4, 3, INV }, { 8, 7, 5, 4, INV },{ 9, 8, 6, 5, INV }, { 9, 7, 6, INV },{ 8, 7, INV } }, { //blue { INV },{ 0, INV }, { 3, 1, 0, INV },{ 2, 1, INV }, { 2, 3, 5, INV },{ 3, 4, INV }, { 4, 5, 7, INV },{ 5, 6, INV }, { 6, 7, 9, INV },{ 7, 8, INV }, } }; //ʼ int stoneIntersection[3] = { 0,8,9 }; //ŷб int moveList[1024]; //ŷ׵ַ int* pList[MAXDEPTH + 2]; //ǰ int maxDepth; //õ int bestRootMove; //˼ int boards_checked; void DrawBoard(); // int putCell(int from,int to,int wtm) { int i; int rVal = 1; if ((from < 0) || (from > 9)) return 1; if ((to < 0) || (to > 9)) return 1; if (RED == wtm && (from != stoneIntersection[REDSTONE] || to == stoneIntersection[BLUESTONE1] || to == stoneIntersection[BLUESTONE2])) return 1; else if (BLUE == wtm && ((from != stoneIntersection[BLUESTONE1] && from != stoneIntersection[BLUESTONE2]) || to == stoneIntersection[REDSTONE] || to == stoneIntersection[BLUESTONE1] || to == stoneIntersection[BLUESTONE2])) return 1; if (2 < abs(from - to)) return 1; for (i = 0; i < 3; ++i) { if (from == stoneIntersection[i]){ stoneIntersection[i] = to; rVal = -1; } } return rVal; } //ŷ int* getMove(int color, int *mList) { int i = 0; int from; int to; int count = 0; if (color == RED) { from = stoneIntersection[REDSTONE]; to = preTable[color][from][i]; while (to != INV) { if ((to != stoneIntersection[BLUESTONE1]) && (to != stoneIntersection[BLUESTONE2])) { mList[count++] = to; } to = preTable[color][from][++i]; } } else { from = stoneIntersection[BLUESTONE1]; to = preTable[color][from][i]; while (to != INV) { if ((to != stoneIntersection[REDSTONE]) && (to != stoneIntersection[BLUESTONE2])) { mList[count++] = to | 16; } to = preTable[color][from][++i]; } i = 0; from = stoneIntersection[BLUESTONE2]; to = preTable[color][from][i]; while (to != INV) { if ((to != stoneIntersection[REDSTONE]) && (to != stoneIntersection[BLUESTONE1])) { mList[count++] = to | 32; } to = preTable[color][from][++i]; } } return &mList[count]; } int checkIsWin(int wtm,int *si) { if ((si[RED] == 8) || (si[RED] == 9)) { return ((wtm == RED) ? 1 : -1); } else if ((si[RED] == 0) && ((si[BLUESTONE1] + si[BLUESTONE2]) == 3)){ return ((wtm == RED) ? -1 : 1); } return 0; } int Evaluation(int wtm, int *si) { int value = 0; if ((si[RED] > si[BLUESTONE1]) || (si[RED] > si[BLUESTONE2])){ value = ((wtm == RED) ? MAX : MIN); } else if ((wtm == RED) && ((stoneIntersection[BLUESTONE1] == si[RED] + 1) && (stoneIntersection[BLUESTONE2] == si[RED] + 2) || (stoneIntersection[BLUESTONE1] == si[RED] + 2) && (stoneIntersection[BLUESTONE2] == si[RED] + 1))) { value = MAX; } else if ((wtm == BLUE) &&((1 == si[REDSTONE] || 2 == si[REDSTONE] || 3 == si[REDSTONE]) &&((stoneIntersection[BLUESTONE1] == si[RED] + 1) &&(stoneIntersection[BLUESTONE2] == si[RED] + 2) ||(stoneIntersection[BLUESTONE1] == si[RED] + 2) &&(stoneIntersection[BLUESTONE2] == si[RED] + 1)))){ value = MAX; } return value; } int MakeMove(int piece, int to) { int tmp = stoneIntersection[piece]; stoneIntersection[piece] = to; return tmp; } void UnmakeMove(int piece, int from) { stoneIntersection[piece] = from; } void getHunamMove() { char selection[200]; while (1) { cin>>selection; printf("\n"); int piece, from, to; from = selection[0] - '0'; to = selection[1] - '0'; if (from <= 9 && from >= 0 && to <= 9 && to >= 0) if (putCell(from, to, RED) == -1) break; } } int evaluateComputerMove(int depth, int alpha, int bate); int evaluateHumanMove(int depth, int alpha, int bate); int evaluateHumanMove(int depth, int alpha, int bate) { int move; int piece; int from; int ply = maxDepth - depth; int *pMove = pList[ply]; int value; boards_checked++; short min = MAX + 1; pList[ply + 1] = getMove(RED, pList[ply]); if (checkIsWin(BLUE, stoneIntersection) == 1) { return MAX; } if (pList[ply] == pList[ply + 1] || depth == 0) { return Evaluation(BLUE, stoneIntersection); } for (; pMove<pList[ply + 1]; ++pMove) { move = *pMove; piece = move >> 4; from = MakeMove(piece, move & 15); value = evaluateComputerMove(depth - 1, alpha, bate); UnmakeMove(piece, from); if (value<min) { min = value; } if (value < bate) { bate = value; } if (bate <= alpha) { return bate; } } if (min == MAX + 1) { return 0; } return min; } int evaluateComputerMove(int depth, int alpha, int bate) { int move; int piece; int from; int ply = maxDepth - depth; int *pMove = pList[ply]; int value; boards_checked++; short max = MIN - 1; pList[ply + 1] = getMove(BLUE, pList[ply]); if (checkIsWin(RED, stoneIntersection) == 1) return MIN; if (pList[ply] == pList[ply + 1] || depth == 0){ return -Evaluation(RED, stoneIntersection); } for (; pMove<pList[ply + 1]; ++pMove){ move = *pMove; piece = move >> 4; from = MakeMove(piece, move & 15); value = evaluateHumanMove(depth - 1, alpha, bate); UnmakeMove(piece, from); if (value>max){ max = value; if (!ply){ bestRootMove = move; } } if (value>alpha) alpha = value; if (alpha >= bate) return alpha; } if (max == MIN - 1) { return 0; } return max; } void getComputerMove() { boards_checked = 0; evaluateComputerMove(maxDepth, -3, 3); int piece, from, to; piece = (bestRootMove & 48) >> 4; from = stoneIntersection[piece]; to = bestRootMove & 15; cout << from << to << endl; putCell(from, to, piece); return; } int main() { cout << "ţ壬ʼͼһRӣڶˣBӣڵ׶ˣߣÿ1ڿλӳɹߵ89λӻʤӰѺ0ӻʤǺӣԣPlayEggӡ01롰01+سʲôBUGʼ\n" << endl; bestRootMove = 1000; maxDepth = MAXDEPTH; pList[0] = moveList; int won = 0; DrawBoard(); while (!won) { getHunamMove(); won = checkIsWin(RED, stoneIntersection); if (!won){ won = 0; getComputerMove(); DrawBoard(); won = checkIsWin(BLUE, stoneIntersection); if (won){ printf("\nYou lose!\n"); } } else{ printf("\nYou win!\n"); } } system("pause"); return 0; } //껭 void DrawBoard() { char ch[10] = { '0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' }; ch[stoneIntersection[RED]] = 'R'; ch[stoneIntersection[BLUESTONE1]] = 'B'; ch[stoneIntersection[BLUESTONE2]] = 'B'; cout << ch[0] << "\n"; cout << "| \\\n"; cout << "| " << ch[1] << endl; cout << "| / \\\n"; cout << ch[2] << "-----" << ch[3] << endl; printf("O O\n"); printf("%c %c\n", ch[4], ch[5]); printf("O O\n"); printf("O O\n"); printf("%c %c\n", ch[6], ch[7]); printf("O O\n"); printf("O O\n"); printf("%c %c\n", ch[8], ch[9]); return; }
true
5bf473b9b99b63eaab923556f1dbbe5676f9c056
C++
fyang26/leetcode
/c++/product-of-array-except-self.cpp
UTF-8
374
2.625
3
[]
no_license
class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { int mul = 1; int n = nums.size(); vector<int> res(n, 1); for (int i=1; i<n; i++) res[i] = res[i-1] * nums[i-1]; for (int i=n-1; i>=0; i--) { res[i] = mul * res[i]; mul *= nums[i]; } return res; } };
true
007e0ff9aa5c2dd5e1a71c953efa2af7ee27cb96
C++
oahugrown/PlatEngine
/GameObject/GameObjectComponents/ComponentObject.h
UTF-8
1,562
2.984375
3
[]
no_license
// ComponentManager.h #ifndef COMPONENTMANAGER_H #define COMPONENTMANAGER_H #ifdef PLATENGINE_EXPORTS #define COMPONENTOBJECT_H __declspec(dllimport) #else #define COMPONENTOBJECT_H __declspec(dllexport) #endif #include"Component.h" #include <unordered_map> // List of all component types that PlatEngine currently supports enum class ComponentType { k_TransformComponent, k_RendererComponent, k_RigidBodyComponent }; class Component; // This class is responsible for managing all components to its owner. // It will create and store the components that its owner owns. // This is the base class to inherit to if you wish to create a base object // that supports components. class ComponentObject { private: std::unordered_map<ComponentType, Component*> m_pComponents; public: COMPONENTOBJECT_H ComponentObject(); COMPONENTOBJECT_H ~ComponentObject(); // Returns NULLPTR if the componentType does not exist on the gameObject Component* GetComponent(ComponentType componentType) { return m_pComponents[componentType]; }; // Attaches a new component to this object IF and ONLY IF that component doesn't already exist on the object. // PlatEngine currently doesn't support multiple components of the same type. void COMPONENTOBJECT_H AttachComponent(ComponentType componentType); // PlatEngine's process of removing a component attached to it. // It will delete the component, and unregister it from the map of components it references. void COMPONENTOBJECT_H RemoveComponent(ComponentType componentType); }; #endif // !COMPONENTMANAGER_H
true
68bda6ba3f928d0ac87055ca79876f5f09c9dff2
C++
gzc/leetcode
/cpp/431-440/Minimum Genetic Mutation.cpp
UTF-8
1,113
2.796875
3
[ "MIT" ]
permissive
class Solution { public: int minMutation(string start, string end, vector<string>& bank) { queue<string> toVisit; unordered_set<string> dict(bank.begin(), bank.end()); int dist = 0; if(!dict.count(end)) return -1; toVisit.push(start); dict.insert(start); dict.insert(end); while(!toVisit.empty()) { int n = toVisit.size(); for(int i=0; i<n; i++) { string str = toVisit.front(); toVisit.pop(); if(str==end) return dist; addWord(str, dict, toVisit); } dist++; } return -1; } void addWord(string word, unordered_set<string>& dict, queue<string>& toVisit) { for(int i=0; i<word.size(); i++) { char tmp = word[i]; for(char c:string("ACGT")) { word[i] = c; if(dict.count(word)) { toVisit.push(word); dict.erase(word); } } word[i] = tmp; } } };
true
93830907b22f18c29c6d931d98d6ae856d017bda
C++
neuronsimulator/nrn
/src/scopmath/revsawto.cpp
UTF-8
1,768
2.65625
3
[ "BSD-3-Clause" ]
permissive
#include <../../nrnconf.h> /****************************************************************************** * * File: revsawto.c * * Copyright (c) 1984-1991 * Duke University * ******************************************************************************/ #include "scoplib.h" #include <cmath> /****************************************************************/ /* */ /* Abstract: revsawtooth() */ /* */ /* Computes the value of a reverse sawtooth function (a */ /* periodic declining ramp) of specified amplitude and */ /* period */ /* */ /* Returns: Double precision value of the reverse sawtooth */ /* function */ /* */ /* Calling sequence: revsawtooth(t, period, amplitude) */ /* */ /* Arguments */ /* Input: t, double the independent variable, */ /* usually time */ /* */ /* period, double duration of the ramp decline */ /* for each cycle */ /* */ /* amplitude, double */ /* ramp height for each cycle */ /* */ /* Output: reset_integ, *int set to 1 if discontinuity is */ /* generated */ /* old_value, *double saved value from previous */ /* call */ /* */ /* Functions called: none */ /* */ /* Files accessed: none */ /* */ /****************************************************************/ double revsawtooth(int* reset_integ, double* old_value, double t, double period, double amplitude) { double value; value = amplitude * (1.0 - std::modf(t / period, &value)); if (value != *old_value) *reset_integ = 1; *old_value = value; return (value); }
true
ff0ab1994c852fcba751e40df783f9f6ed67411b
C++
suyuee/LC
/841.keys-and-rooms.cpp
UTF-8
1,949
3.421875
3
[]
no_license
/* * @lc app=leetcode id=841 lang=cpp * * [841] Keys and Rooms * * https://leetcode.com/problems/keys-and-rooms/description/ * * algorithms * Medium (60.61%) * Total Accepted: 39.4K * Total Submissions: 64.8K * Testcase Example: '[[1],[2],[3],[]]' * * There are N rooms and you start in room 0.  Each room has a distinct number * in 0, 1, 2, ..., N-1, and each room may have some keys to access the next * room.  * * Formally, each room i has a list of keys rooms[i], and each key rooms[i][j] * is an integer in [0, 1, ..., N-1] where N = rooms.length.  A key rooms[i][j] * = v opens the room with number v. * * Initially, all the rooms start locked (except for room 0).  * * You can walk back and forth between rooms freely. * * Return true if and only if you can enter every room. * * * * * Example 1: * * * Input: [[1],[2],[3],[]] * Output: true * Explanation: * We start in room 0, and pick up key 1. * We then go to room 1, and pick up key 2. * We then go to room 2, and pick up key 3. * We then go to room 3. Since we were able to go to every room, we return * true. * * * Example 2: * * * Input: [[1,3],[3,0,1],[2],[0]] * Output: false * Explanation: We can't enter the room with number 2. * * * Note: * * * 1 <= rooms.length <= 1000 * 0 <= rooms[i].length <= 1000 * The number of keys in all rooms combined is at most 3000. * * */ class Solution { public: bool canVisitAllRooms(vector<vector<int>>& rooms) { unordered_set<int> opened; queue<int> keys; keys.push(0); while (keys.empty() == false) { int room = keys.front(); keys.pop(); if (opened.find(room) == opened.end()) { opened.insert(room); for (int key : rooms[room]) keys.push(key); } } return opened.size() == rooms.size(); } };
true
3919250be9ce0de519f22cb752ae5fa0328703c4
C++
sdecoder/geeksforgeeks
/misc/petersons-algorithm-for-mutual-exclusion-set-1.cc
UTF-8
2,491
3.234375
3
[]
no_license
// Filename: peterson_spinlock.c // Use below command to compile: // gcc -pthread peterson_spinlock.c -o peterson_spinlock #include <stdio.h> #include <pthread.h> #include "mythreads.h" int flag[2]; int turn; const int MAX = 1e9; int ans = 0; void lock_init() { // Initialize lock by reseting the desire of // both the threads to acquire the locks. // And, giving turn to one of them. flag[0] = flag[1] = 0; turn = 0; } // Executed before entering critical section void lock(int self) { // Set flag[self] = 1 saying you want to acquire lock flag[self] = 1; // But, first give the other thread the chance to // acquire lock turn = 1 - self; // Wait until the other thread looses the desire // to acquire lock or it is your turn to get the lock. while (flag[1 - self] == 1 && turn == 1 - self) ; } // Executed after leaving critical section void unlock(int self) { // You do not desire to acquire lock in future. // This will allow the other thread to acquire // the lock. flag[self] = 0; } // A Sample function run by two threads created // in main() void* func(void* s) { int i = 0; int self = (int*)s; printf("Thread Entered: %d\n", self); lock(self); // Critical section (Only one thread // can enter here at a time) for (i = 0; i < MAX; i++) ans++; unlock(self); } // Driver code int main() { // Initialized the lock then fork 2 threads pthread_t p1, p2; lock_init(); // Create two threads (both run func) Pthread_create(&p1, NULL, func, (void*)0); Pthread_create(&p2, NULL, func, (void*)1); // Wait for the threads to end. Pthread_join(p1, NULL); Pthread_join(p2, NULL); printf("Actual Count: %d | Expected Count: %d\n", ans, MAX * 2); return 0; } Run on IDE // mythread.h (A wrapper header file with assert // statements) #ifndef __MYTHREADS_h__ #define __MYTHREADS_h__ #include <pthread.h> #include <assert.h> #include <sched.h> void Pthread_mutex_lock(pthread_mutex_t* m) { int rc = pthread_mutex_lock(m); assert(rc == 0); } void Pthread_mutex_unlock(pthread_mutex_t* m) { int rc = pthread_mutex_unlock(m); assert(rc == 0); } void Pthread_create(pthread_t* thread, const pthread_attr_t* attr, void* (*start_routine)(void*), void* arg) { int rc = pthread_create(thread, attr, start_routine, arg); assert(rc == 0); } void Pthread_join(pthread_t thread, void** value_ptr) { int rc = pthread_join(thread, value_ptr); assert(rc == 0); } #endif // __MYTHREADS_h__
true
a3131c74e3f63d775b53880f194edc48b900ab1f
C++
unmeshvrije/leetcode
/leetcode/UniqueBinarySearchTreesII.cpp
UTF-8
1,360
3.625
4
[]
no_license
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { private: vector<TreeNode*> all_trees(vector<int>& roots, int start, int end) { vector<TreeNode*> result; if (start > end) { result.push_back(NULL); return result; } for (int i = start; i <= end; ++i) { vector<TreeNode*> leftTrees = all_trees(roots, start, i-1); vector<TreeNode*> rightTrees = all_trees(roots, i+1, end); for (auto lt : leftTrees) { for (auto rt: rightTrees){ TreeNode * root = new TreeNode(roots[i]); root->left = lt; root->right = rt; result.push_back(root); } } } return result; } public: vector<TreeNode*> generateTrees(int n) { vector<int> roots(n); for (int i = 1; i <= n; ++i) { roots[i-1] = i; } if (n == 0) { return vector<TreeNode*>(); } return all_trees(roots, 0, n-1); } };
true
05a56437b08bdbff4dd721b4bdd09f99ce156d51
C++
JohanJacobs/Head_First_Design_Patterns
/Chapter6_Command_Pattern/src/Core/Base.h
UTF-8
290
2.875
3
[ "MIT" ]
permissive
#pragma once #include <memory> // template functions to help create Shared_ptr objects template<typename T> using Ref = std::shared_ptr<T>; template <typename T, typename ... Args> constexpr Ref<T> CreateRef(Args&& ... args) { return std::make_shared<T>(std::forward<Args>(args) ...); }
true