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
e0395865f2c35c1fc0d695e1f6e7f3bcdaa6abee
C++
kks227/BOJ
/5500/5555.cpp
UTF-8
409
2.53125
3
[]
no_license
#include <cstdio> using namespace std; int main(){ char W[11]; int N, result = 0; scanf("%s %d", W, &N); for(int i=0; i<N; i++){ bool found = false; char R[11]; scanf("%s", R); for(int i=0; i<10; i++){ found = true; for(int j=0; W[j]; j++){ if(R[(i+j)%10] != W[j]){ found = false; break; } } if(found){ result++; break; } } } printf("%d\n", result); }
true
5c38485ea8934b14e53b1603462f80aa3d70bcde
C++
muhammet-mucahit/My-C-Studies
/Others/char 4.cpp
UTF-8
645
3.078125
3
[]
no_license
#include<stdio.h> #define SIZE 20 int boyut(char a[]) { int i; for(i=0;a[i]!='\0';i++) { } return i; } int main() { char string1[SIZE]; char string2[SIZE]; printf("Karakter giriniz : ");scanf("%s",&string1); printf("Karakter giriniz : ");scanf("%s",&string2); int b1=boyut(string1); int b2=boyut(string2); int i,j,b,c=0; for(i=0;i<b2;i++) { for(j=0;j<b1;j++) { if(string2[i]==string1[j]) { b=j; c++; for(int k=1;k<=b2;k++) { if(string2[i+k]==string1[j+k]) { c++; } } if(c==b2) { printf("%d",b); } } c=0; } } }
true
b64c2867a91d3d4650f9873cd529a3b32d54c860
C++
ccccqyc/Books
/WD_Alg/5th/5_3_3_12.cpp
UTF-8
844
3.578125
4
[]
no_license
// 第五章 树与二叉树 // 5.3.3 二 12 // 打印值为x结点祖先 #include <malloc.h> #include <cstdio> typedef int ElemType; // 二叉树 typedef struct BitNode { ElemType data; BitNode *lchild, *rchild; } BitNode, *BitTree; // 思路后续遍历,查询到x值的结点,终止遍历,输出队列中祖先 void search(BitTree T, ElemType x) { Queue Q; initQueue(Q); //初始化遍历队列. BitNode *p = T; if (T == NULL) return; if (isEmpty(Q) || p != NULL) { while (p != NULL && p->data != x) { EnQueue(Q, p); p = p->lchild; } //找到结点 if (p->data == x && !isEmpty(Q)) { do { DeQueue(Q, p); //出队 printf("%d", p->data); } while (!isEmpty(Q)); exit(1); } } }
true
b9e6cca42e9746435890771626c674775a8ed9b8
C++
q545244819/leetcode
/week/202/5490.cpp
UTF-8
779
3.265625
3
[]
no_license
class Solution { public: unordered_map<int, int> memo; int minDays(int n) { return dfs(n); } int dfs (int n) { if (n == 0) return memo[0] = 0; if (n == 1) return memo[1] = 1; if (n == 2) return memo[2] = 2; if (memo.find(n) != memo.end()) return memo[n]; // 假设橘子数量是 n // 若橘子数量不是 2 的倍数的话,那么先需要吃掉 n % 2 个橘子/天(同时吃一个需要一天) // 若橘子数量不是 3 的倍数的话,同理 // m = 取整(n / 2) // dfs(n / 2): 吃掉 n / 2 个橘子需要的最小天数 // n % 2: 将 n 吃到偶数的 m 需要多少天 return memo[n] = 1 + min(dfs(n / 2) + n % 2, dfs(n / 3) + n % 3); } };
true
fa9e7affc7d76ed0702a7fff9e02fa7b43a3da6c
C++
Ch3shireDev/WIT-Zajecia
/semestr-3/Programowanie obiektowe 1/rozwiazania/06-bottle.cpp
UTF-8
2,159
3.984375
4
[]
no_license
class Bottle { double max_amount; double current_amount = 0; public: // 4.2.3 Bottle: Butelka o ograniczonej pojemnosci - bitcoin // Napisz klase Bottle reprezentujaca butelke. Zaimplementuj: //  Konstruktor przyjmujacy pojemnosc butelki. Bottle(double amount) { max_amount = amount; } //  Stała bezargumentowa metode volume, która zwraca objetosc płynu w butelce. double volume() const{ return current_amount; } //  Metode fill, która przyjmuje objetosc płynu, jaki chcemy wlac do butelki, zmienia odpowiednio objetosc płynu w butelce i zwraca objetosc płynu, który rzeczywiscie udało sie wlac. double fill(double amount) { if (current_amount + amount <= max_amount) { current_amount += amount; return amount; } amount = max_amount - current_amount; current_amount = max_amount; return amount; } //  Metode pour, która przyjmuje objetosc płynu, jaki chcemy wylac z butelki, zmienia odpowiednio objetosc płynu w butelce i zwraca objetosc płynu, który rzeczywiscie udało sie wylac. double pour(double amount) { if(amount <= current_amount){ current_amount -= amount; return amount; } amount = current_amount; current_amount = 0; return amount; } // Nowoutworzona butelka jest pusta. Klasa powinna byc przystosowana do uzycia w przykładowym programie // ponizej. Klasa nie korzysta z zadnych plików nagłówkowych. }; #include <iostream> using namespace std; // Przykładowy program int main() { const Bottle bottle(4.5); std::cout << bottle.volume() << "\n"; std::cout << bottle.fill(3.5) << "\n"; std::cout << bottle.volume() << "\n"; cout<<"Dolewamy 5 litrow"<<endl; std::cout << bottle.fill(5) << "\n"; std::cout << bottle.volume() << "\n"; std::cout << bottle.pour(5.5) << "\n"; std::cout << bottle.volume() << std::endl; double volume = bottle.volume(); } // Wykonanie // Out: 0 3.5 3.5 3.5 0
true
83d404bba55e3f573ea5d60aef589cf7988584ef
C++
reagler/general
/cpp/test/initlist.cpp
UTF-8
741
3.375
3
[]
no_license
#include <iostream> using namespace std; class Abc { public: Abc(){ a = 0; cout << "Abc::default constructor\n"; } Abc(int a){ this->a = a; cout << "a = " << a << endl; cout << "Abc::a constructor\n"; } ~Abc() { cout << "~Abc" << endl; } private: int a; }; class BB{ public: BB(){ abc = Abc(3); x = 0; cout << "BB: default constructor\n"; } BB(int x, int a): x(x),abc(a){ cout << this->x << endl; cout << "BB: initlist constructor\n"; } /*BB(int x, int a){ this->x = x; abc=Abc(a); cout << "BB: initlist constructor2\n"; }*/ ~BB() { cout << "~BB" << endl; } private: Abc abc; int x; }; int maiddn() { BB b = BB(2,33); return 0; }
true
9c96eec70dec4f951b376a1d65d64fd18e1213e2
C++
skndi/OnlineShop
/OnlineShop/ItemOrganizer.cpp
UTF-8
1,735
3.34375
3
[]
no_license
#include "Inventory.h" Message ItemOrganizer::addItem(const Item& item, const int& quantity) { Message msg; if (checkItemExistance(item)) return msg.error("Item already exists!"); if(!checkQuantity(quantity)) return msg.error("Invalid quantity!"); items.insert(std::make_pair(item, quantity)); return msg.success(); } bool ItemOrganizer::checkItemExistance(const Item& item) { if (items.find(item) == items.end()) return 0; return 1; } Message ItemOrganizer::removeItem(const Item& item) { Message msg; auto iter = items.find(item); if (iter == items.end()) { return msg.error("Item doesn't exist!"); } items.erase(iter); return msg.success(); } Message ItemOrganizer::takeOut(const Item& item, const int& quantity) { Message msg; auto iter = items.find(item); if (iter == items.end()) return msg.error("Item doesn't exist!"); if (!checkQuantity(quantity, iter->second)) { return msg.error("Invalid quantity!"); } iter->second -= quantity; return msg.success(); } std::unordered_map<Item, int, HashFunc>& ItemOrganizer::getItems(){ return items; } const std::unordered_map<Item, int, HashFunc>& ItemOrganizer::getItems() const{ return items; } std::unordered_map<Item, int>::iterator ItemOrganizer::getItem(const Item& name){ return items.find(name); } int ItemOrganizer::getStock(const Item& item) const{ return items.at(item); } std::unordered_map<Item, int>::iterator ItemOrganizer::search(const std::string& name) { for (std::unordered_map<Item, int>::iterator iter = items.begin(); iter != items.end(); iter++) { if (iter->first.getName() == name) return iter; } return items.end(); }
true
8eafdd78d3815f178c5ed70e38fac041a121310e
C++
BehaviorTree/BehaviorTree.CPP
/src/loggers/bt_sqlite_logger.cpp
UTF-8
3,836
2.578125
3
[ "MIT" ]
permissive
#include "behaviortree_cpp/loggers/bt_sqlite_logger.h" #include "behaviortree_cpp/xml_parsing.h" #include "cpp-sqlite/sqlite.hpp" namespace BT { SqliteLogger::SqliteLogger(const Tree &tree, std::filesystem::path const& filepath, bool append): StatusChangeLogger(tree.rootNode()) { const auto extension = filepath.filename().extension(); if( extension!= ".db3" && extension != ".btdb") { throw RuntimeError("SqliteLogger: the file extension must be [.db3] or [.btdb]"); } enableTransitionToIdle(true); db_ = std::make_unique<sqlite::Connection>(filepath.string()); sqlite::Statement(*db_, "CREATE TABLE IF NOT EXISTS Transitions (" "timestamp INTEGER PRIMARY KEY NOT NULL, " "session_id INTEGER NOT NULL, " "uid INTEGER NOT NULL, " "duration INTEGER, " "state INTEGER NOT NULL);"); sqlite::Statement(*db_, "CREATE TABLE IF NOT EXISTS Definitions (" "session_id INTEGER PRIMARY KEY AUTOINCREMENT, " "date TEXT NOT NULL," "xml_tree TEXT NOT NULL);"); if( !append ) { sqlite::Statement(*db_, "DELETE from Transitions;"); sqlite::Statement(*db_, "DELETE from Definitions;"); } auto tree_xml = WriteTreeToXML(tree, true, true); sqlite::Statement(*db_, "INSERT into Definitions (date, xml_tree) " "VALUES (datetime('now','localtime'),?);", tree_xml); auto res = sqlite::Query(*db_, "SELECT MAX(session_id) FROM Definitions LIMIT 1;"); while(res.Next()) { session_id_ = res.Get(0); } writer_thread_ = std::thread(&SqliteLogger::writerLoop, this); } SqliteLogger::~SqliteLogger() { loop_ = false; queue_cv_.notify_one(); writer_thread_.join(); flush(); sqlite::Statement(*db_, "PRAGMA optimize;"); } void SqliteLogger::callback(Duration timestamp, const TreeNode &node, NodeStatus prev_status, NodeStatus status) { using namespace std::chrono; int64_t tm_usec = int64_t(duration_cast<microseconds>(timestamp).count()); monotonic_timestamp_ = std::max( monotonic_timestamp_ + 1, tm_usec); long elapsed_time = 0; if( prev_status == NodeStatus::IDLE && status == NodeStatus::RUNNING ) { starting_time_[&node] = monotonic_timestamp_; } if( prev_status == NodeStatus::RUNNING && status != NodeStatus::RUNNING ) { elapsed_time = monotonic_timestamp_; auto it = starting_time_.find(&node); if( it != starting_time_.end() ) { elapsed_time -= it->second; } } Transition trans; trans.timestamp = monotonic_timestamp_; trans.duration = elapsed_time; trans.node_uid = node.UID(); trans.status = status; { std::scoped_lock lk(queue_mutex_); transitions_queue_.push_back(trans); } queue_cv_.notify_one(); } void SqliteLogger::writerLoop() { std::deque<Transition> transitions; while(loop_) { transitions.clear(); { std::unique_lock lk(queue_mutex_); queue_cv_.wait(lk, [this]() { return !transitions_queue_.empty() || !loop_; }); std::swap(transitions, transitions_queue_); } while(!transitions.empty()) { auto const trans = transitions.front(); transitions.pop_front(); sqlite::Statement( *db_, "INSERT INTO Transitions VALUES (?, ?, ?, ?, ?)", trans.timestamp, session_id_, trans.node_uid, trans.duration, static_cast<int>(trans.status)); } } } void BT::SqliteLogger::flush() { sqlite3_db_cacheflush(db_->GetPtr()); } }
true
ea84d055519180299d1e9ca7fe949d94c72bf8fe
C++
kwan0xfff/fmtk
/src/math/interpbilinear.cc
UTF-8
556
3.0625
3
[ "Apache-2.0" ]
permissive
// binear interpolation // // Implementation loosely based on the algorithm at: // http://en.wikipedia.org/wiki/Bilinear_interpolation // #include "interpbilinear.h" float interpbilinear(const float v[], const float xb[], const float yb[], float x, float y) { float weights = v[vx00] * (xb[1]-x) * (yb[1]-y) + v[vx01] * (xb[1]-x) * (y-yb[0]) + v[vx10] * (x-xb[0]) * (yb[1]-y) + v[vx11] * (x-xb[0]) * (y-yb[0]); float area = (xb[1]-xb[0]) * (yb[1]-yb[0]); float value = weights / area; return value; }
true
22c431eeeb97f0c411b0ebb92b501377fb8b3cad
C++
fmi-lab/up-gr8-seminars
/week5/problem0.cpp
UTF-8
826
3.390625
3
[]
no_license
#include <iostream> #include <cstring> using namespace std; /* * Задача 0. Напишете програма, която сравнява лексикографски два въведени низа. * (без да използвате вградените функции) */ int main() { char s1[40], s2[40]; cout << "Enter the two strings on separate lines:" << endl; cin.getline(s1, 40); cin.getline(s2, 40); int idx = 0; while(s1[idx] != 0 && s2[idx] != 0 && s1[idx] == s2[idx]) { idx++; } int result = s1[idx] - s2[idx]; if (result < 0) { cout << s1 << " comes before " << s2 << endl; } else if (result > 0) { cout << s1 << " comes after " << s2 << endl; } else { cout << s1 << " is the same as " << s2 << endl; } return 0; }
true
07c793bb49f45e5fff621239814862b933eb3d75
C++
darennet/CrackingTheCodingInterview
/ChapterThree/StackWithMin.cpp
UTF-8
755
2.96875
3
[]
no_license
/* * StackWithMin.cpp * * Created on: Nov 24, 2014 * Author: ubuntu */ #include "StackWithMin.h" #include "RuntimeException.h" #include <iostream> #include <limits> #include <memory> using namespace std; namespace chapterThree { StackWithMin::StackWithMin() : _stack() { } StackWithMin::~StackWithMin() { } int StackWithMin::pop() { StackNode top = _stack.top(); _stack.pop(); return top.value; } void StackWithMin::push(int value) { if (_stack.size() == 0) { _stack.emplace(value, value); } else { _stack.emplace(value, min(value, _stack.top().localMin)); } } int StackWithMin::getMin() { if (_stack.size() == 0) throw RuntimeException(); StackNode top = _stack.top(); return top.localMin; } } /* namespace twotwo */
true
6b34f956d125f258fbd03909f97b9d12eab44193
C++
TobbyT/example
/example_algo/TwoPointer/608.cpp
UTF-8
496
3.109375
3
[]
no_license
#include "general.h" int main() { vector<int> nums = {2, 7, 11, 15}; int target = 9; int left = 0, right = nums.size() - 1; vector<int> res; while (left < right){ int sum = nums[left] + nums[right]; if(sum == target){ res.push_back(left + 1); res.push_back(right + 1); break; } else if(sum < target){ left++; } else{ right--; } } PrintVector(res); }
true
19037fe9e22f27ba4dfdfaa5cef322b4fdde0374
C++
andr2000/avic900-vncviewer
/server/jni/libvncnative/AndroidGraphicBuffer.h
UTF-8
2,878
3.09375
3
[]
no_license
#ifndef ANDROIDGRAPHICBBUFFER_H_ #define ANDROIDGRAPHICBBUFFER_H_ #include <EGL/eglext.h> #include <stdint.h> /** * This class allows access to Android's direct texturing mechanism. Locking * the buffer gives you a pointer you can read/write to directly. It is fully * threadsafe, but you probably really want to use the AndroidDirectTexture * class which will handle double buffering. * * In order to use the buffer in OpenGL, just call Bind() and it will attach * to whatever texture is bound to GL_TEXTURE_2D. */ class AndroidGraphicBuffer { public: enum { /* buffer is never read in software */ GRALLOC_USAGE_SW_READ_NEVER = 0x00000000, /* buffer is rarely read in software */ GRALLOC_USAGE_SW_READ_RARELY = 0x00000002, /* buffer is often read in software */ GRALLOC_USAGE_SW_READ_OFTEN = 0x00000003, /* mask for the software read values */ GRALLOC_USAGE_SW_READ_MASK = 0x0000000F, /* buffer is never written in software */ GRALLOC_USAGE_SW_WRITE_NEVER = 0x00000000, /* buffer is never written in software */ GRALLOC_USAGE_SW_WRITE_RARELY = 0x00000020, /* buffer is never written in software */ GRALLOC_USAGE_SW_WRITE_OFTEN = 0x00000030, /* mask for the software write values */ GRALLOC_USAGE_SW_WRITE_MASK = 0x000000F0, /* buffer will be used as an OpenGL ES texture */ GRALLOC_USAGE_HW_TEXTURE = 0x00000100, /* buffer will be used as an OpenGL ES render target */ GRALLOC_USAGE_HW_RENDER = 0x00000200, /* buffer will be used by the 2D hardware blitter */ GRALLOC_USAGE_HW_2D = 0x00000400, /* buffer will be used with the framebuffer device */ GRALLOC_USAGE_HW_FB = 0x00001000, /* mask for the software usage bit-mask */ GRALLOC_USAGE_HW_MASK = 0x00001F00, }; enum { HAL_PIXEL_FORMAT_RGBA_8888 = 1, HAL_PIXEL_FORMAT_RGBX_8888 = 2, HAL_PIXEL_FORMAT_RGB_888 = 3, HAL_PIXEL_FORMAT_RGB_565 = 4, HAL_PIXEL_FORMAT_BGRA_8888 = 5, HAL_PIXEL_FORMAT_RGBA_5551 = 6, HAL_PIXEL_FORMAT_RGBA_4444 = 7, }; struct rect { int x; int y; int width; int height; }; AndroidGraphicBuffer(int width, int height, uint32_t format); virtual ~AndroidGraphicBuffer(); int lock(unsigned char **bits); int lock(const rect &rect, unsigned char **bits); int unlock(); bool allocate(); bool reallocate(int aWidth, int aHeight, uint32_t aFormat); int getWidth() { return m_Width; } int getHeight() { return m_Height; } int getStride() { return m_Stride; } bool bind(); private: uint32_t m_Width; uint32_t m_Height; uint32_t m_Usage; uint32_t m_Format; uint32_t m_Stride; bool ensureInitialized(); bool ensureEGLImage(); void destroyBuffer(); bool ensureBufferCreated(); void *m_Handle; EGLImageKHR m_EGLImage; }; #endif /* ANDROIDGRAPHICBBUFFER_H_ */
true
fd4dcfb5db887887321405f10df4eb81c7682d5c
C++
josyulakrishna/motion-toolkit
/jointlimits/EllipsoidJointLimits.cpp
UTF-8
1,721
2.828125
3
[ "MIT" ]
permissive
/* IK - Sample Code for Rotational Joint Limits in Quaternion Space Copyright (c) 2016 Gino van den Bergen, DTECTA Source published under the terms of the MIT License. For details please see COPYING file or visit http://opensource.org/licenses/MIT */ #include "EllipsoidJointLimits.hpp" namespace ik { EllipsoidJointLimits::EllipsoidJointLimits(Scalar maxRx, Scalar maxRy, Scalar maxRz) { setLocalJointLimits(maxRx, maxRy, maxRz); } void EllipsoidJointLimits::setLocalJointLimits(Scalar maxRx, Scalar maxRy, Scalar maxRz) { ASSERT(0 < maxRx && maxRx <= ScalarTraits::pi()); ASSERT(0 < maxRy && maxRy <= ScalarTraits::pi()); ASSERT(0 < maxRz && maxRz <= ScalarTraits::pi()); mEllipsoid.setBounds(mt::sin(maxRx * Scalar(0.5)), mt::sin(maxRy * Scalar(0.5)), mt::sin(maxRz * Scalar(0.5))); } void EllipsoidJointLimits::bound(DualQuaternion& relPose) const { Quaternion q = rotation(relPose); Vector3 p = translation(relPose); // Make sure the scalar part is positive. Since quaternions have a double covering, q and -q represent the same orientation. if (mt::isnegative(q.w)) { q = -q; // Negate the quaternion. Still represents the same orientation. } mEllipsoid.clamp(q.x, q.y, q.z); // We clamp the vector part, and recompute the scalar part (w). The scalar part is known up to a sign, but since we made sure that w was positive, and clamping does not switch the sign, // we can return a positive scalar part here. q.w = mt::sqrt(mt::max<Scalar>(0, 1 - (q.x * q.x + q.y * q.y + q.z * q.z))); relPose = rigid(q, p); } }
true
ed33312fdeeb116f7a1f0527810a1a4e52784af9
C++
lvtx/gamekernel
/kcore/base/Result.h
UTF-8
252
2.640625
3
[]
no_license
#pragma once namespace gk { struct Result { enum { SUCCESS, FAIL }; int code; Result( int code = SUCCESS ) { this->code = code; } operator bool () const { return code == SUCCESS; } }; } // namespace gk
true
7c83245a53ac73980b39c1d4dbea198a834ae0d7
C++
alexandraback/datacollection
/solutions_5670465267826688_1/C++/ptrj/Dijkstra.cpp
UTF-8
2,405
2.984375
3
[]
no_license
//============================================================================== // Qualification Round 2015 // Problem C. Dijkstra // //============================================================================== #include <iostream> #include <string> #include <cmath> #include <vector> #include <array> #include <algorithm> using namespace std; using sol_type = bool; void read_data(); sol_type find_solution(); long long L, X; vector<int> S; int get(const vector<int> & vi, const int x, const int y); constexpr array<array<int,8>,8> mult = { array<int,8> {0,1,2,3,4,5,6,7}, // 1,i,j,k,-1,-i,-j,-k array<int,8> {1,4,3,6,5,0,7,2}, array<int,8> {2,7,4,1,6,3,0,5}, array<int,8> {3,2,5,4,7,6,1,0}, array<int,8> {4,5,6,7,0,1,2,3}, array<int,8> {5,0,7,2,1,4,3,6}, array<int,8> {6,3,0,5,2,7,4,1}, array<int,8> {7,6,1,0,3,2,5,4}, }; int main() { int cases; int case_num =0; cin >> cases; while (cases--) { ++case_num; read_data(); auto solution = find_solution(); cout << "Case #" << case_num << ": "; cout << (solution ? "YES" : "NO") << endl; } return 0; } void read_data(){ cin >> L >> X; string t; cin >> t; S.resize(L); transform(t.begin(), t.end(), S.begin(), [](const char c){return c-'i'+1;}); } sol_type find_solution(){ long long ipos = -1, kpos = -1; int c = 0; for(auto i=0ll; i <= min(4ll,X)*L; ++i) { c = mult[c][S[i%L]]; if(c == 1) { // i found ipos = i; break; } } if(ipos == -1) return false; c = 0; for(auto i=0ll; i <= min(4ll,X)*L; ++i) { c = mult[S[L-1-i%L]][c]; if(c == 3) { // k found kpos = X*L -1 - i; break; } } if(kpos == -1 || kpos <= ipos + 1) return false; c = 0; if(ipos%L < L-1) c = get(S, ipos%L+1, min(kpos,L)); if(kpos/L > ipos/L +1) { auto full = get(S,0,L); for(int i=0; i< (kpos/L-ipos/L-1)%4; ++i) c = mult[c][full]; } if(kpos >= L) c = mult[c][get(S,0,kpos%L)]; if(c == 2) // j return true; return false; } int get(const vector<int> & vi, const int x, const int y) { return accumulate(vi.begin()+x, vi.begin()+y, 0, [](const int a, const int b){return mult[a][b];}); }
true
fd27614c250f760aa906f447f5579218c8954860
C++
omarKaushru/Numb-UV-Life-activites
/CSE/u/Recovered data 05-03-2015 at 01_14_01/NTFS/My pc/programing fun/chapter wise program/chapter-9/sum of n numbers .cpp
UTF-8
286
2.5625
3
[]
no_license
#include<stdio.h> #include<conio.h> int add(int n); main(){ int n; printf("enter n="); scanf("%d",&n); printf("sum=%d",add(n)); getch(); } int add(int n){ if(n!=0) return n+add(n-1); }
true
b9069a8ea103a8dd7310bf5963e51cbe6469917c
C++
saniahamid/AlgorithmicToolbox
/week3_greedy_algorithms/1_money_change/change.cpp
UTF-8
474
3.15625
3
[]
no_license
#include <iostream> int get_change(int m) { //write your code here int x[3] = { 1, 5, 10 }; int change_count = 0; int current_change = 0; while (m > 0) { for (int i = 0; i <= 2; i++) { if (m >= x[i]) { current_change = x[i]; } } //std::cout << "Current change is: " << current_change << std::endl; m = m - current_change; ++change_count; } return change_count; } int main() { int m; std::cin >> m; std::cout << get_change(m) << '\n'; }
true
8664b2de2cfb041e94119155474a15ccaf0e21e1
C++
Xuming8812/LeetcodeSolution
/LeetCodeSolution/Easy/292 Nim Game.cpp
UTF-8
661
3.21875
3
[]
no_license
#include<vector> #include<map> #include<string> #include<queue> #include<sstream> #include<stack> #include<set> #include<bitset> using namespace std; /* You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones. Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap. */ bool canWinNim(int n) { if (n % 4 == 0) return false; return true; }
true
aa96b64b54aceef8000b0ea2d742fa4acd28a948
C++
Robotics-Zhikai/Computational-Geometry
/ConvexHull/TestConvexHull.cpp
GB18030
8,088
3.015625
3
[ "MIT" ]
permissive
#include "ConvexHull.h" #include "Visualization.h" #include <time.h> #include <math.h> vector<Point> GenerateRandomPoint(int pointsNum, float RangeXmin, float RangeXmax, float RangeYmin, float RangeYmax) //generate pointsNum random points in [RangeXmin,RangeXmax,RangeYmin,RangeYmax] { vector<Point> Points; srand((int)time(0)); // 0NULLҲ for (int i = 0; i < pointsNum; i++) { Point Pointtemp; float a = RangeXmin; float b = RangeXmax; Pointtemp.Point_X = a + (rand() / double(RAND_MAX))*(b - a); a = RangeYmin; b = RangeYmax; Pointtemp.Point_Y = a + (rand() / double(RAND_MAX))*(b - a); Pointtemp.Point_Z = 0; Points.push_back(Pointtemp); } return Points; } void Test_ToLeftTest() { Point PointA(30,30,0); Point PointB(30, 30, 0); /*Point PointC(5, 10, 0);*/ Point PointC(30, 40.00000000000001, 0); //initgraph(200, 200); // TC //line(PointA.Point_X, PointA.Point_Y, PointB.Point_X, PointB.Point_Y); //putpixel(PointC.Point_X, PointC.Point_Y, 0); //circle(200, 200, 100); // ԲԲ(200, 200)뾶 100 int num = ToLeftTest(PointA, PointB, PointC); } void Test_InTriangle() { Point PointA(0, 0, 0); Point PointB(10, 0, 0); /*Point PointC(5, 10, 0);*/ Point PointC(0, 10, 0); Point PointD(-1, 6, 0); cout << InTriangle(PointA,PointB,PointC,PointD); } void Test_GetConvexHull_EP() { vector <Point> Points; Points = GenerateRandomPoint(100, 0, 10, 0, 10); //vector <Point> Points2; //Points2 = GenerateRandomPoint(0, 11, 11, 11, 11); //for (int i = 0; i < Points2.size(); i++) //{ // Points.push_back(Points2[i]); //} OpenGLplot(); AddBufferPoints(Points, 2.0f); Points = GetConvexHull_EP(Points); AddBufferPoints(Points, 5.0f); vector <Point> temp = Points; temp.push_back(Points[0]); //AddBufferLines(temp, 1.0f); Points = BubbleSortPoints(Points); temp = Points; temp.push_back(Points[0]); AddBufferLines(temp, 1.0f); CloseGLplot(); } void Test_GetConvexHull_EE() { vector <Point> Points; Points = GenerateRandomPoint(2500, 0, 10, 0, 10); vector <Point> Points2; Points2 = GenerateRandomPoint(500, 10, 10, 5, 5); for (int i = 0; i < Points2.size(); i++) { Points.push_back(Points2[i]); } OpenGLplot(); AddBufferPoints(Points, 2.0f); Points = GetConvexHull_EE(Points); AddBufferPoints(Points, 5.0f); vector <Point> temp = Points; //temp.push_back(Points[0]); Points = BubbleSortPoints(Points); temp = Points; temp.push_back(Points[0]); AddBufferLines(temp, 1.0f); CloseGLplot(); } void Test_GetConvexHull_IC()//͹ { //ڵ⣺żvectorĴ //ͬʱֱˮƽĺܶ㣬ͻҵüеִ󣬿ֵй vector <Point> Points; Points = GenerateRandomPoint(13000, 0, 10, 0, 10); //ڿɽܵʱҵ73000ĵ ǻvector //vector <Point> Points2; //Points2 = GenerateRandomPoint(500, 9.99, 9.99, 0, 10); //for (int i = 0; i < Points2.size(); i++) //{ // Points.push_back(Points2[i]); //} //Points2 = GenerateRandomPoint(500, 0, 9.99, 10, 10); //for (int i = 0; i < Points2.size(); i++) //{ // Points.push_back(Points2[i]); //} OpenGLplot(); AddBufferPoints(Points, 2.0f); Points = GetCHIncrementalConstruction(Points); AddBufferPoints(Points, 5.0f); vector <Point> temp = Points; //temp.push_back(Points[0]); Points = BubbleSortPoints(Points); temp = Points; temp.push_back(Points[0]); AddBufferLines(temp, 1.0f); CloseGLplot(); } void Test_ICPT() { vector <Point> Points; Points.push_back(Point(0, 0, 0)); Points.push_back(Point(5, 0, 0)); Points.push_back(Point(0, 5, 0)); Points.push_back(Point(5, 5, 0)); vector <Point> Points2; Points2.push_back(Point(0, 4, 0)); cout<< InConvexPolygonTest(Points, Points2[0]); //for (int i = 0; i < Points2.size(); i++) //{ // int result = InConvexPolygonTest(Points, Points2[i]); // if (result == 0|| result==1) // cout<<"e"; //} system("pause"); } void Test_GetConvexHull_JM()//jarvis march㷨 { vector <Point> Points; Points = GenerateRandomPoint(280000, 0, 10, 1, 10); //Points.push_back(Point(11, 5, 0)); //Points.push_back(Point(10, 0.5, 0)); // /*Points.push_back(Point(0.1, 0.5, 0)); Points.push_back(Point(0.2, 0.5, 0)); Points.push_back(Point(0.3, 0.5, 0)); Points.push_back(Point(0.3, 0.5, 0)); Points.push_back(Point(0.2, 0.5, 0)); Points.push_back(Point(0.1, 0.5, 0));*/ /*for (double i = 0; i < 10; i=i+0.1) { Points.push_back(Point(i, 0.5, 0)); } for (double i = 10; i > 0; i = i - 0.1) { Points.push_back(Point(i, 0.5, 0)); } */ vector <Point> Points2; Points2 = GenerateRandomPoint(1335,0, 9.99, 0.5, 0.5); for (int i = 0; i < Points2.size(); i++) { Points.push_back(Points2[i]); } //Points.push_back(Point(-1, 0.5, 0)); Points2 = GenerateRandomPoint(1500, 11,11, 1, 10); for (int i = 0; i < Points2.size(); i++) { Points.push_back(Points2[i]); } OpenGLplot(); AddBufferPoints(Points, 2.0f); Points = GetCHJarvisMarch(Points); AddBufferPoints(Points, 5.0f); vector <Point> temp = Points; //temp.push_back(Points[0]); //Points = BubbleSortPoints(Points); temp = Points; temp.push_back(Points[0]); AddBufferLines(temp, 1.0f); cout << Points.size() - 1 << endl; CloseGLplot(); } void Test_GetConvexHull_GS()//GrahamScan㷨 { clock_t start, end; vector <Point> Points; Points = GenerateRandomPoint(550000, 0, 10, 1, 10); vector <Point> Points2; Points2 = GenerateRandomPoint(850, 0, 9.99, 0.5, 0.5); for (int i = 0; i < Points2.size(); i++) { Points.push_back(Points2[i]); } //Points.push_back(Point(-1, 0.5, 0)); Points2 = GenerateRandomPoint(850, 9, 9, 0.5, 10); for (int i = 0; i < Points2.size(); i++) { Points.push_back(Points2[i]); } OpenGLplot(); AddBufferPoints(Points, 2.0f); start = clock(); cout << "" << Points.size() << "͹" << endl; Points = GetCHGrahamScan(Points); end = clock(); double endtime = (double)(end - start) / CLOCKS_PER_SEC; cout << "GrahamScan㷨ʱ" << endtime << "s" << endl; AddBufferPoints(Points, 5.0f); vector <Point> temp = Points; //temp.push_back(Points[0]); //Points = BubbleSortPoints(Points); temp = Points; temp.push_back(Points[0]); AddBufferLines(temp, 1.0f); cout <<"͹Ķ"<< Points.size() - 1 << endl; CloseGLplot(); } void Test_GetCHDivideMerge() { clock_t start, end; vector <Point> Points; Points = GenerateRandomPoint(500000, 0, 10, 1, 10); //Points.push_back(Point(1, 2, 0)); //Points.push_back(Point(2, 3, 0)); //Points.push_back(Point(3, 4, 0)); //Points.push_back(Point(4, 5, 0)); //Points.push_back(Point(5, 6, 0)); //Points.push_back(Point(6, 7, 0)); //Points.push_back(Point(4, 8, 0)); //Points.push_back(Point(3, 9, 0)); //Points.push_back(Point(2, 10, 0)); vector <Point> Points2; Points2 = GenerateRandomPoint(850, 0, 9.99, 0.5, 0.5); for (int i = 0; i < Points2.size(); i++) { Points.push_back(Points2[i]); } //Points.push_back(Point(-1, 0.5, 0)); Points2 = GenerateRandomPoint(850, 9, 9, 0.5, 10); for (int i = 0; i < Points2.size(); i++) { Points.push_back(Points2[i]); } OpenGLplot(); AddBufferPoints(Points, 2.0f); start = clock(); cout << "" << Points.size() << "͹" << endl; Points = GetCHDivideMerge(Points); end = clock(); double endtime = (double)(end - start) / CLOCKS_PER_SEC; cout << "GetCHDivideMerge㷨ʱ" << endtime << "s" << endl; AddBufferPoints(Points, 5.0f); vector <Point> temp = Points; //temp.push_back(Points[0]); //Points = BubbleSortPoints(Points); temp = Points; temp.push_back(Points[0]); AddBufferLines(temp, 1.0f); cout << "͹Ķ" << Points.size() - 1 << endl; CloseGLplot(); } void main() { //cout << sqrt(3.777); //Test_ToLeftTest(); //Test_InTriangle(); //Test_GetConvexHull_EP(); //Test_GetConvexHull_EE(); //Test_GetConvexHull_IC(); //Test_ICPT(); //Test_GetConvexHull_JM(); //Test_GetConvexHull_GS(); Test_GetCHDivideMerge(); }
true
f51b5cc8745ce4b8c7b9baf07787fe8b416d1787
C++
UNIVERSAL-IT-SYSTEMS/SOMO14D
/SOMO14D.cpp
UTF-8
2,389
2.625
3
[ "MIT" ]
permissive
/* Arduino Library for 4D Systems SOMO-14D Embedded Audio-Sound Module go to http://www.4dsystems.com.au/product/10/117/Development/SOMO_14D/ for more information License: CC BY-SA 3.0: Creative Commons Share-alike 3.0. Feel free to use and abuse this code however you'd like. If you find it useful please attribute, and SHARE-ALIKE! Created July 2013 by Jonathan Ruiz de Garibay */ #include "Arduino.h" #include "SOMO14D.h" // // begin // // Init inputs and outputs. boolean SOMO14D::begin(uint8_t clkPin, uint8_t dataPin, uint8_t busyPin){ _clkPin = clkPin; pinMode(_clkPin, OUTPUT); _dataPin = dataPin; pinMode(_dataPin, OUTPUT); _busyPin = busyPin; pinMode(_busyPin, INPUT); _volume = SOMO14D_MAX_VOLUME; delay(200); } // // play // // Play an specific song/audio boolean SOMO14D::play(unsigned int song){ _sendCommand(song); delay(1); return (digitalRead(_busyPin) == HIGH); } // // stop // // Stop present song/audio boolean SOMO14D::stop(){ _sendCommand(SOMO14D_STOP); delay(1); return (digitalRead(_busyPin) == HIGH); } // // pause // // Pause or resume present song/audio boolean SOMO14D::pause(){ _sendCommand(SOMO14D_PAUSE); delay(1); return (digitalRead(_busyPin) == HIGH); } // // getState // // return if player is running (TRUE) or not (FALSE) boolean SOMO14D::getState(){ return (digitalRead(_busyPin) == HIGH); } // // getVolume // // Get present volume for SOMO-14D uint8_t SOMO14D::getVolume(){ return _volume - SOMO14D_MIN_VOLUME; } // // setVolume // // set a specific volume for SOMO-14D void SOMO14D::setVolume(uint8_t volume){ if (volume > 7) volume = 7; _volume = volume + SOMO14D_MIN_VOLUME; _sendCommand(_volume); } // // sendCommand // // Send a command to SOMO-14D void SOMO14D::_sendCommand(unsigned int command){ uint8_t dataCounter = 0; digitalWrite(_clkPin, LOW); //Hold for 2msec to signal data start delay(2); while(dataCounter < 16){ digitalWrite(_clkPin, LOW); if (command & 0x8000) digitalWrite(_dataPin, HIGH); else digitalWrite(_dataPin, LOW); command = command << 1; delayMicroseconds(120); //Clock cycle period is 100 uSec - LOW digitalWrite(_clkPin, HIGH); dataCounter++; delayMicroseconds(120); //Clock cycle period is 100 uSec - HIGH } digitalWrite(_dataPin, LOW); digitalWrite(_clkPin, HIGH); // Place clock high to signal end of data }
true
17e0cd87c2ba43930a571e1e3563d89b028ea276
C++
oldtree/TestHash
/HashTableProbed.h
UTF-8
12,251
3.34375
3
[]
no_license
/*===================================================================== HashTableProbed.h - Probing hash table template class Author: Per Nilsson Freeware and no copyright on my behalf. However, if you use the code in some manner I'd appreciate a notification about it perfnurt@hotmail.com Classes: // The hash table template <class Key, class Value, class MyHasher = Hasher<Key>, class MyGrower = DefaultGrower, > class HashTableProbed { class iterator class const_iterator // Used as a proxy when operator[] is called class Access } Requirements: A Hasher must be implemented if the generic ones isn't applicable. Caller needs to #inlude default Grower/Hasher if they are to be used. Dependencies: To std::map if the default value_type is used =====================================================================*/ #if !defined(HASHTABLEPROBED_H) #define HASHTABLEPROBED_H #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include <map> //------------------------------------------------------------------------ // HashTableProbed // A generic hash collection, requires that the Hasher // has been implemented somwehere for the apropriate Key type. // It will simply hold ann array of <Key, Value> pairs, and using probing // to handle collisions // class Key // The, well, key type // class Value: // The value type // class MyHasher: // A class (function object) that will be called when computing the...well...hash value. // Substitute with your own if the generic hashers aren't good enough/applicable // class MyGrower: // A class used to determine what size the array should grow to template <class Key, class Value, class MyHasher = Hasher<Key>, class MyGrower = DefaultGrower > class HashTableProbed { public: //------------------------------------------------------------------ // Public Type Definitions //------------------------------------------------------------------ typedef std::pair<Key, Value> value_type; //------------------------------------------------------------------ // Public Classes //------------------------------------------------------------------ // class iterator class iterator { public: iterator(HashTableProbed& ht, size_t index):mHT(ht), mIndex(index) { if (index<mHT.getAllocated() && mHT.getElement(index)==0) { ++(*this); } } bool operator == (const iterator& src) const { return mHT == src.mHT && mIndex == src.mIndex; } bool operator != (const iterator& src) const { return !(*this == src); } value_type& operator*() { return *mHT.getElement(mIndex); } size_t getIndex() const { return mIndex; } iterator& operator ++ () { mIndex++; while (mIndex<mHT.getAllocated() && mHT.getElement(mIndex)==0) { mIndex++; } return (*this); } private: HashTableProbed& mHT; size_t mIndex; }; // class const_iterator class const_iterator { public: const_iterator(const HashTableProbed& ht, size_t index):mHT(ht), mIndex(index) { if (index<mHT.getAllocated() && mHT.getElement(index)==0) { ++(*this); } } bool operator == (const const_iterator& src) const { return mHT == src.mHT && mIndex == src.mIndex; } bool operator != (const const_iterator& src) const { return !(*this == src); } const value_type& operator*() const { return *mHT.getElement(mIndex); } size_t getIndex() const { return mIndex; } const_iterator& operator ++ () { mIndex++; while (mIndex<mHT.getAllocated() && mHT.getElement(mIndex)==0) { mIndex++; } return (*this); } private: const HashTableProbed& mHT; size_t mIndex; }; // Used as a proxy when operator[] is called // Handles theHash["foo"] = 42 and i = theHash["Foo"] differently. class Access { public: Access(HashTableProbed& ht, const Key& key):mHash(ht),mKey(key){} // Assignment operator. Handles the myHash["Foo"] = 32; situation operator=(const Value& value) { // Just use the Set method, it handles already exist/not exist situation mHash.set(mKey,value); } // ValueType operator operator Value() { HashTableProbed::iterator i = mHash.find(mKey); // Not found if (i==mHash.end()) { throw "Item not found"; } return (*i).second; } private: //------------------------------ // Disabled Methods //------------------------------ // Default constructor Access(); //------------------------------ // Private Members //------------------------------ HashTableProbed& mHash; const Key& mKey; }; // Access //------------------------------------------------------------------ // Public Construction //------------------------------------------------------------------ // Default constructor explicit HashTableProbed(size_t initialSize=1000) // Might be adjusted upwards { size_t newAlloc = mGrower.getPrimeGreaterThan(initialSize); mAllocated = newAlloc; mFreeSlots = mAllocated; mArray = new value_type*[mAllocated+1]; memset(mArray, 0, sizeof(mArray[0])*(mAllocated+1)); mSize=0; } // Destructor virtual ~HashTableProbed() { clear(); } //------------------------------------------------------------------ // Public Queries //------------------------------------------------------------------ // Find a non-const iterator, returns end() if not found. const_iterator find(const Key& key) const { size_t hashValue = hash(key, mAllocated); size_t index = hashValue; const value_type* element = mArray[index]; const Value* v=0; bool searchedAll = false; while (!searchedAll) { if (element!=0 && element->first == key) { v = &element->second; break; } index = (index + cIncBy) % mAllocated; searchedAll = index==hashValue; element = mArray[index]; } if(v == 0) return end(); else return const_iterator(*this,index); } // Find a non-const iterator, returns end() if not found. iterator find(const Key& key) { size_t hashValue = hash(key, mAllocated); size_t index = hashValue; value_type* element = mArray[index]; Value* v=0; bool searchedAll = false; while (!searchedAll) { if (element!=0 && element->first == key) { v = &element->second; break; } index = (index + cIncBy) % mAllocated; searchedAll = index==hashValue; element = mArray[index]; } if(v == 0) return end(); else return iterator(*this,index); } size_t size() const { return mSize; } value_type* getElement(size_t index) { return mArray[index]; } const value_type* getElement(size_t index) const { return mArray[index]; } size_t getAllocated() const { return mAllocated; } //------------------------------------------------------------------ // Public Commands //------------------------------------------------------------------ void set(const Key& key, const Value& value) { iterator i = find(key); if (i == end()) { if (!insert(key, value)) throw "Failed to insert"; } else { (*i).second = value; } } // insert - returns false if no insertion took place // key already stored or no free slots bool insert(const value_type& vt) { return insert(vt.first, vt.second); } // insert - returns false if no insertion took place // key already stored or no free slots bool insert(const Key& key, const Value& value) { if (find(key) != end()) return false; size_t newAlloc = mGrower.getNewSize(mAllocated, mFreeSlots); bool allSearched=false; if (newAlloc > mAllocated) { rehash(newAlloc); } size_t hashValue = hash(key, mAllocated); size_t index = hashValue; value_type* element = mArray[hashValue]; while (element!=0 && !allSearched) { index = (index + cIncBy) % mAllocated; element = mArray[index]; allSearched = index == hashValue; } if (allSearched) return false; else { element= new value_type(key, value); mArray[index] = element; mFreeSlots--; mSize++; return true; }; } size_t erase(const Key& key) { iterator it = find(key); size_t erased=0; if (it != end()) { size_t index = it.getIndex(); delete mArray[index]; mArray[index] = 0; mFreeSlots++; mSize--; erased++; } return erased; } void clear() { if (mArray != 0) { for (size_t i=0;i<mAllocated;++i) { delete mArray[i]; mArray[i] = 0; } delete [] mArray; mArray = 0; } mAllocated=0; mFreeSlots=0; mSize=0; } //------------------------------------------------------------------ // Public Operators //------------------------------------------------------------------ Access operator[](const Key& key) { return Access(*this, key); } bool operator == (const HashTableProbed& src) const { return mArray == src.mArray; } //------------------------------------------------------------------ // Public Iterators //------------------------------------------------------------------ iterator begin() { return iterator(*this, 0); } const_iterator begin() const { return const_iterator(*this, 0); } iterator end() { return iterator(*this, mAllocated); } const_iterator end() const { return const_iterator(*this, mAllocated); } private: //------------------------------------------------------------------ // Disabled Methods //------------------------------------------------------------------ // Copy constructor explicit HashTableProbed(const HashTableProbed&); // Assignment operator HashTableProbed operator = (const HashTableProbed&); //------------------------------------------------------------------ // Private Type Definitions //------------------------------------------------------------------ typedef value_type** Array; // == array of value_type pointer //------------------------------------------------------------------ // Private Helper Methods //------------------------------------------------------------------ size_t hash(const Key& key, size_t allocated) const { MyHasher hasher; size_t size_t = hasher(key, allocated); return size_t; } static void deleteElement(value_type* m) { delete m; m = 0; } // Create a new, bigger, array void rehash(size_t newAlloc) { size_t oldAllocated = mAllocated; Array newArray = new value_type*[newAlloc+1]; memset(newArray, 0, sizeof(newArray[0])*(newAlloc+1)); size_t newFreeSlots = newAlloc; for (size_t i=0; i<oldAllocated; ++i) { value_type* element = mArray[i]; if(element) { size_t newHashValue = hash(element->first, newAlloc); size_t index = newHashValue; value_type* newElement = newArray[newHashValue]; while (newElement!=0) { index = (index + cIncBy) % newAlloc; newElement = newArray[index]; } // Simply move the element to the new array newArray[index] = element; newFreeSlots--; } } // Note: Dont delete the elements in the old array, they are moved // as-is to the new array. if (mArray!=0) delete [] mArray; mArray = newArray; mAllocated = newAlloc; mFreeSlots = newFreeSlots; } //------------------------------------------------------------------ // Private Constants //------------------------------------------------------------------ // Probing increment enum { cIncBy = 7 }; //------------------------------------------------------------------ // Members //------------------------------------------------------------------ // The hash table iteself Array mArray; size_t mAllocated; // The actual size of the array size_t mFreeSlots; // Number of free slots in the array size_t mSize; // Number of elements stored in the hash table (incl. sub collections) MyGrower mGrower; }; #endif // !defined(HASHTABLEPROBED_H)
true
3ceace4b88b52c03e0ea8ac8ffd0251c0f7f023f
C++
DIYEmbeddedSystems/ArduinoLogger
/examples/multipleLoggers/multipleLoggers.ino
UTF-8
2,346
2.8125
3
[ "MIT" ]
permissive
/** * This code shows how you can create and use multiple logger contexts. * */ #include <Arduino.h> #include <ArduinoLogger.h> // default logger (not instantiated here) uses Serial for output, and logs all messages // logger1 context, for main program, uses Serial for output, logs only messages above the WARNING level // logger2 context, for a specific function, uses Serial for output, logs only error and critical messages Logger loggerProg("PROG", Serial, LOG_WARNING); Logger loggerFunc("FUNC", Serial, LOG_ERROR); void setup() { Serial.begin(115200); delay(1000); LOG("Starting..."); // Trace execution with default logger, or with specific loggers. TRACE(); LOGGER_TRACE(loggerProg); LOGGER_TRACE(loggerFunc); // DEBUG-level messages DEBUG("This is a debug message"); loggerProg.debug("This is a debug message"); loggerFunc.debug("This is a debug message"); // INFO-level messages INFO("This is an information message"); loggerProg.info("This is an information message"); loggerFunc.info("This is an information message"); // WARNING-level messages WARN("This is a warning"); loggerProg.warn("This is a warning"); loggerFunc.warn("This is a warning"); // ERROR-level messages ERROR("This is an error message!"); loggerProg.error("This is an error message!"); loggerFunc.error("This is an error message!"); // CRITICAL-level messages CRITICAL("This is a critical error !!"); loggerProg.critical("This is a critical error !!"); loggerFunc.critical("This is a critical error !!"); } void loop() { loggerFunc.setLevel((enum e_log_level)(((int)loggerFunc.getLevel() + 1) % LOG_ALL)); INFO("loggerFunc logging level is now set to %d", loggerFunc.getLevel()); loggerProg.debug("This is a debug message"); loggerFunc.debug("This is a debug message"); loggerProg.info("This is an information message"); loggerFunc.info("This is an information message"); loggerProg.warn("This is a warning"); loggerFunc.warn("This is a warning"); loggerProg.error("This is an error message!"); loggerFunc.error("This is an error message!"); loggerProg.critical("This is a critical error !!"); loggerFunc.critical("This is a critical error !!"); INFO("\n\n\n"); delay(1000); }
true
5ae9f26b9aeb078e0ecec2595d651fab369f426c
C++
Vishalshelke7558/OOP_using_CPP
/22_multilevel_inheritance.cpp
UTF-8
1,255
3.78125
4
[]
no_license
#include <iostream> using namespace std; class student { protected: int roll_no; public: void set_number(int); void get_number(); }; void student ::set_number(int r) { roll_no = r; } void student ::get_number() { cout << "the roll number is " << roll_no << endl; } class exam : public student { protected: int math; int physics; public: void set_marks(int, int); void get_marks(); }; void exam ::set_marks(int a, int b) { math = a; physics = b; } void exam ::get_marks() { cout << "the marks obtained in the physics are " << physics << endl; cout << "the marks obtained in the physics are " << math << endl; } class result : public exam { int percent; public: void display_result() { cout << "your percentage is " << (math + physics) / 2 << "%" << endl; } }; int main() { /* if we are inheriting B from A and C from B A ---> B ---> C A is the base class for B and B is base class for C A B C is called inheritance path */ result vishal; vishal.set_number(420); vishal.set_marks(98, 98); vishal.display_result(); return 0; }
true
80e6725c731e1dfa9e21b8bf092a0b01ea238507
C++
matthew99carroll/OpenGLGraphics
/OpenGLCourseApp/main.cpp
UTF-8
4,885
3
3
[]
no_license
#include <stdio.h> #include <string.h> #include <cmath> #include <vector> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include "Window.h" #include "Mesh.h" #include "Shader.h" #include "Camera.h" // OpenGL rotations use radians, using this allows for working in degrees and easy conversion const float toRadians = 3.14159265f / 180.0f; // Create an object for the main window Window mainWindow; // List of meshes and shaders std::vector<Mesh*> meshList; std::vector<Shader> shaderList; Camera camera; GLfloat deltaTime = 0.0f; GLfloat lastTime = 0.0f; // Location of Vertex Shader static const char* vShader = "Shaders/shader.vert"; // Location of Fragment Shader static const char* fShader = "Shaders/shader.frag"; /* CreateObjects is where the creation of meshes is handled. Indices and vertices are passed through to a mesh creation method and added to the mesh object list. */ void CreateObjects() { // Indices for 3D triangle mesh, 2 sides, front and base i.e. 12 indices unsigned int indices[] = { 0, 3, 1, 1, 3, 2, 2, 3, 0, 0, 1, 2 }; // Vertices for the 3D triangle mesh, 12 vertices total GLfloat vertices[] = { -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f }; // Create object meshes Mesh* obj1 = new Mesh(); obj1->CreateMesh(vertices, indices, 12, 12); meshList.push_back(obj1); Mesh* obj2 = new Mesh(); obj2->CreateMesh(vertices, indices, 12, 12); meshList.push_back(obj2); } /* CreateShaders is where the creation of shaders is handled. */ void CreateShaders() { // Create object shader Shader* shader1 = new Shader(); // Go to directory and read vertex and fragment shader shader1->CreateFromFiles(vShader, fShader); shaderList.push_back(*shader1); } /* Main rendering loop */ int main() { // Draw a window of dimensions 800x600 mainWindow = Window(800, 600); // Runs OpenGL methods to initialize the window mainWindow.Initialise(); // Creates meshes and shaders CreateObjects(); CreateShaders(); // Initialise camera constructor camera = Camera(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f), -90.0f, 0.0f, 5.0f, 0.001f); // Uniform variables to be passed to vertex shader. Initialised to 0 by default to prevent weird stuff happening GLuint uniformProjection = 0, uniformModel = 0, uniformView = 0; // Create projection matrix. perspective(vertical FOV, Aspect Ratiom, Near clip plane, Far clip Plane) glm::mat4 projection = glm::perspective(glm::radians(45.0f), mainWindow.getBufferWidth() /mainWindow.getBufferHeight(), 0.1f, 100.0f); // Loop until window closed while (!mainWindow.getShouldClose()) { GLfloat now = glfwGetTime(); deltaTime = now - lastTime; lastTime = now; // Get and handle user input events glfwPollEvents(); // Check if keys are being pressed in main window to move camera camera.keyControl(mainWindow.getsKeys(), deltaTime); camera.mouseControl(mainWindow.getXChange(), mainWindow.getYChange()); // Clear window glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Bitwise operators to handle what buffers to clear. In this case both Color and Depth buffers are cleared glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Applies the shader to an OpenGL shader program shaderList[0].UseShader(); // Getters for uniform vars model, projection and view uniformModel = shaderList[0].GetModelLocation(); uniformProjection = shaderList[0].GetProjectionLocation(); uniformView = shaderList[0].GetViewLocation(); // Create a 4x4 identity matrix as a starting point for transforms glm::mat4 model = glm::mat4(1.0f); // Apply translation and scaling model = glm::translate(model, glm::vec3(0.0f, 0.0f, -2.5f)); model = glm::scale(model, glm::vec3(0.4f, 0.4f, 1.0f)); // Pass model and projection to uniform variable counterparts by pointer glUniformMatrix4fv(uniformModel, 1, GL_FALSE, glm::value_ptr(model)); glUniformMatrix4fv(uniformProjection, 1, GL_FALSE, glm::value_ptr(projection)); glUniformMatrix4fv(uniformView, 1, GL_FALSE, glm::value_ptr(camera.calculateViewMatrix())); // Render mesh to screen meshList[0]->RenderMesh(); // Create a 4x4 identity matrix as a starting point for transforms model = glm::mat4(1.0f); // Apply translation and scaling model = glm::translate(model, glm::vec3(0.0f, 1.0f, -2.5f)); model = glm::scale(model, glm::vec3(0.4f, 0.4f, 1.0f)); // Pass model to uniform variable counterpart by pointer (NB: don't need to do this for projection again) glUniformMatrix4fv(uniformModel, 1, GL_FALSE, glm::value_ptr(model)); // Render Mesh to Screen meshList[1]->RenderMesh(); // Set shader program to 0 at end of frame glUseProgram(0); // Swap buffer to blank empty shader program mainWindow.swapBuffers(); } return 0; }
true
57fb832f6c52685bd32f44ad786e98ac4d611e79
C++
xsaiter/exts
/main.cpp
UTF-8
4,873
2.828125
3
[]
no_license
#include <algorithm> #include <cerrno> #include <cstdio> #include <cstring> #include <ctime> #include <memory> #include <queue> #include <string> #include <vector> #define PRINT(...) \ std::printf(__VA_ARGS__); \ std::fflush(stdout); #define DIE(...) \ std::fprintf(stderr, __VA_ARGS__); \ std::perror("reason"); \ exit(EXIT_FAILURE) static const size_t num_size = sizeof(int); using size_u = std::size_t; struct file_deleter_s { void operator()(FILE *fp) { if (fp) { fclose(fp); } } }; using file_ptr_u = std::unique_ptr<FILE, file_deleter_s>; using files_ptr_u = std::vector<file_ptr_u>; file_ptr_u open_or_die_file(const std::string &name, const std::string &modes) { FILE *fp = std::fopen(name.c_str(), modes.c_str()); if (!fp) { DIE("failed to open file: %s\n", name.c_str()); } return file_ptr_u(fp); } inline file_ptr_u create_or_die_file(const std::string &name) { return open_or_die_file(name, "w+"); } size_u size_of_file(FILE *fp) { std::fseek(fp, 0L, SEEK_END); auto res = static_cast<size_u>(std::ftell(fp)); std::fseek(fp, 0L, SEEK_SET); return res; } void create_src_file(const std::string &name, size_u size, int max_value) { std::time_t t; std::srand(static_cast<unsigned>(std::time(&t))); size_u nnums = size / num_size; auto fp = create_or_die_file(name); for (size_u i = 0; i < nnums; ++i) { auto num = rand() % max_value; std::fwrite(&num, num_size, 1, fp.get()); } } void print_file(const std::string &name) { auto fp = open_or_die_file(name, "rb"); auto fsize = size_of_file(fp.get()); auto nnums = fsize / num_size; for (size_u i = 0; i < nnums; ++i) { int num; std::fread(&num, num_size, 1, fp.get()); printf("\n%d", num); } } struct entry_s { FILE *fp; int num; bool has_num; }; using entry_ptr_u = std::shared_ptr<entry_s>; struct entry_cmp_s { bool operator()(const entry_ptr_u &x, const entry_ptr_u y) const { return x->num > y->num; } }; void merge_files(const files_ptr_u &files, const std::string &out_file) { std::priority_queue<entry_ptr_u, std::vector<entry_ptr_u>, entry_cmp_s> pq; const size_u nfiles = files.size(); for (size_u i = 0; i < nfiles; ++i) { auto e = std::make_shared<entry_s>(); e->fp = files[i].get(); auto ret = std::fread(&(e->num), num_size, 1, files[i].get()); if (ret != 0) { e->has_num = true; } else { e->has_num = false; } if (e->has_num) { pq.push(e); } } auto out_fp = create_or_die_file(out_file); while (!pq.empty()) { auto x = pq.top(); if (x) { pq.pop(); std::fwrite(&(x->num), num_size, 1, out_fp.get()); auto ret = fread(&(x->num), num_size, 1, x->fp); if (ret != 0) { x->has_num = true; pq.push(x); } else { x->has_num = false; } } } } files_ptr_u split_file(const std::string &name, size_u mem_size, const std::string &tmp_dir) { auto fp = open_or_die_file(name, "rb+"); auto fsize = size_of_file(fp.get()); auto len = fsize / mem_size; if (fsize % mem_size > 0) { ++len; } files_ptr_u res(len); auto buf_size = mem_size - mem_size % num_size; auto buf_len = buf_size / num_size; std::vector<int> buf(buf_len); size_u n = 0; size_u i = 0; while ((n = std::fread(&buf[0], num_size, buf_len, fp.get())) > 0) { std::sort(std::begin(buf), std::next(std::begin(buf), static_cast<int>(n))); std::string s(tmp_dir); s.append("/" + std::to_string(i) + "_"); s.append(name); auto tmp_fp = create_or_die_file(s); std::fwrite(&buf[0], num_size, n, tmp_fp.get()); std::fseek(tmp_fp.get(), 0L, SEEK_SET); res[i++] = std::move(tmp_fp); std::fill(std::begin(buf), std::end(buf), 0); } return res; } void sort_file(size_u mem_size, const std::string &file, const std::string &out_file, const std::string &tmp_dir) { auto files = split_file(file, mem_size, tmp_dir); merge_files(files, out_file); } int main(int argc, char **argv) { PRINT("DATA\n"); print_file("data2.dat"); PRINT("DATA END\n"); // create_src_file("data3.dat", 20, 20); sort_file(8, "data2.dat", "res.dat", "tmp"); // size_t nfiles; // split_src_file("data.dat", 256, "tmp", &nfiles); PRINT("\nOUT_0\n"); print_file("tmp/0_data2.dat"); PRINT("\nOUT_1\n"); print_file("tmp/1_data2.dat"); PRINT("\nOUT_2\n"); print_file("tmp/2_data2.dat"); PRINT("\nRESULT\n"); print_file("res.dat"); PRINT("\nEND"); sort_file(256, "data.dat", "out.dat", "tmp"); return EXIT_SUCCESS; }
true
aa8f5d5343ac76fe47d269d5b172bedf6e19f422
C++
valdersoul/CGProject3-4
/src/librt/Camera.cpp
UTF-8
4,791
2.859375
3
[]
no_license
//------------------------------------------------------------------------------ // Copyright 2015 Corey Toler-Franklin, University of Florida // Camera.cpp // Camera Object - position, up and lookat //------------------------------------------------------------------------------ #include "Camera.h" #include <assert.h> #include <stdio.h> #include <string> #include "STMatrix4.h" #include "utilities.h" #include "defs.h" // TO DO: Proj3_4 OpenGL //----------------------------------- // Adjust this camera implementation // to support the camera rotation and translation modes // Make sure that the camera viewing and projection // matrices are updated in the scene graph //----------------------------------- // construct the camera Camera::Camera(void) : m_trackballsize (0.8f) { Reset(); m_rotationMode = ORBIT; } Camera::~Camera() { } // reset the camera basis so camera is up right void Camera::SetUpAndRight(void) { m_Right = STVector3::Cross(m_LookAt - m_Position, m_Up); m_Right.Normalize(); m_Up = STVector3::Cross(m_Right, m_LookAt - m_Position); m_Up.Normalize(); } // reset the camera position to (0,0,0) looking down negative z void Camera::Reset(void) { m_LookAt=STVector3(0.f,0.f,0.f); m_Position=STVector3(0.f,0.f,0.f); m_Up=STVector3(0.f,1.f,-1.f); SetUpAndRight(); } // resets the camera up vector void Camera::ResetUp(void) { m_Up = STVector3(0.f,1.f,0.f); m_Right = STVector3::Cross(m_LookAt - m_Position, m_Up); m_Right.Normalize(); m_Up = STVector3::Cross(m_Right, m_LookAt - m_Position); m_Up.Normalize(); } // TO DO: Proj3_4 OpenGL // Complete this function // rotates about the center of an object // axis - axis of rotation, // p1x, p1y - coordinates of mouse START position in screen coords // p2x, p2y - coordinates of mouse END position in screen coords void Camera::Orbit(float axis[4], float p1x, float p1y, float p2x, float p2y) { // TO DO: Proj3_4 OpenGL // Orbit - rotates about an object // This is a analogous to a virtual trackball // your job is to update camera view matrix and projection matrix // this will then effect the camer node in the scene //----------------------------------------------------- //----------------------------------------------------- } void Camera::Rotate(float delta_x, float delta_y) { // TO DO: Proj3_4 OpenGL // 1. Alter this code so that there are two camera rotation options // 2. Fly - rotates around a viewpoint // Orbit - rotates about an object (see Camera::Orbit) // 3. All rotations are about the origin in world space // 4. Compute the coordinates of the world origin in camera space // 5. Contruct your rotation about this computed point //------------------------------------------------------------------------------- //------------------------------------------------------------------------------- } void Camera::Zoom(float delta_y) { STVector3 direction = m_LookAt - m_Position; float magnitude = direction.Length(); direction.Normalize(); float zoom_rate = 0.1f*magnitude < 0.5f ? .1f*magnitude : .5f; if(delta_y * zoom_rate + magnitude > 0) { m_Position += (delta_y * zoom_rate) * direction; } } void Camera::Strafe(float delta_x, float delta_y) { float strafe_rate = 0.05f; m_Position -= strafe_rate * delta_x * m_Right; m_LookAt -= strafe_rate * delta_x * m_Right; m_Position += strafe_rate * delta_y * m_Up; m_LookAt += strafe_rate * delta_y * m_Up; } STVector3 Camera::Position (void) { return(m_Position); } STVector3 Camera::LookAt (void) { return(m_LookAt); } STVector3 Camera::Up (void) { return(m_Up); } //------------------------------------------------------------------------------------ // TO DO: Proj3_4 OpenGL // These are all of the new members added to the Camera class for this assignment //------------------------------------------------------------------------------------ STVector3 Camera::Right (void) { return(m_Right); } STMatrix4 Camera::GetProjectionMatrix (void) { return(m_MP); } STMatrix4 Camera::GetViewMatrix (void) { return(m_MV); } void Camera::SetProjectionMatrix (STMatrix4 m) { m_MP = m; } void Camera::SetViewMatrix (STMatrix4 m) { m_MV = m; } void Camera::ToggleRotationMode (void) { if(m_rotationMode == ORBIT) m_rotationMode = FLY; else if(m_rotationMode == FLY) m_rotationMode = ORBIT; } void Camera::SetLookAt(STVector3 lookat) { m_LookAt = lookat; } void Camera::SetPosition(STVector3 position) { m_Position = position; } void Camera::SetUp(STVector3 up) { m_Up = up; } //-----------------------------------------------------------------------------------------
true
dc424a17145cf3c9b4f6e4b1a071b1758c7e8291
C++
rizky-bagus/Tsunemori-Akane
/CQU/Winter Training 6 - Test/E.cpp
UTF-8
949
2.65625
3
[]
no_license
#include <queue> #include <cstdio> #include <cstring> #include <cstdlib> #include <algorithm> using namespace std; int N, K; bool visited[200010]; int main() { freopen("in", "r", stdin); while (~scanf("%d%d", &N, &K)) { memset(visited, false, sizeof visited); queue<pair<int, int> > q; q.push(make_pair(N, 0)); visited[N] = true; int upper = max(2 * K, N); while (!q.empty()) { pair<int, int> now = q.front(); q.pop(); if (now.first == K) { printf("%d\n", now.second); break; } int x = now.first, s = now.second; if (0 <= x - 1 && x - 1 <= upper && !visited[x - 1]) { visited[x - 1] = true; q.push(make_pair(x - 1, s + 1)); } if (0 <= x + 1 && x + 1 <= upper && !visited[x + 1]) { visited[x + 1] = true; q.push(make_pair(x + 1, s + 1)); } if (0 <= x * 2 && x * 2 <= upper && !visited[x * 2]) { visited[x * 2] = true; q.push(make_pair(x * 2, s + 1)); } } } return 0; }
true
edebb19a84deb5676b3a469049110d0365142a43
C++
IcedLeon/Introduction-to-3D-with-OpenGL
/src/ParticlesUpdaters.h
UTF-8
2,143
2.6875
3
[ "MIT" ]
permissive
#ifndef _PARTICLESUPDATERS_H_ #define _PARTICLESUPDATERS_H_ //Lib #include "ParticleUpdater.h" #include "ParticleData.h" #include <vector> using std::vector; class EulerUpdater : public ParticleUpdater { public: vec4 m_vGlobalAcceleration; EulerUpdater() : m_vGlobalAcceleration(vec4(0.0f)) { } ~EulerUpdater() { } virtual void Update(double a_dDeltaTime, ParticleData* a_oParticle); }; class FloorUpdater : public ParticleUpdater { public: float m_fFloorY; float m_fBounceFactor; FloorUpdater() : m_fFloorY(0.0f), m_fBounceFactor(0.0f) { } ~FloorUpdater() { } virtual void Update(double a_dDeltaTime, ParticleData* a_oParticle); }; class AttractorUpdater : public ParticleUpdater { protected: vector<vec4> m_vAttractors; //.w is the force. public: AttractorUpdater() { } ~AttractorUpdater() { } virtual void Update(double a_dDeltaTime, ParticleData* a_oParticle); size_t CollectionSize() const { return m_vAttractors.size(); } void Attractor(const vec4& a_oAttractor) { m_vAttractors.push_back(a_oAttractor); } vec4& GetAttractor(size_t a_ID) { return m_vAttractors[a_ID]; } }; class BasicColourtUpdater : public ParticleUpdater { public: BasicColourtUpdater() { } ~BasicColourtUpdater() { } virtual void Update(double a_dDeltaTime, ParticleData* a_oParticle) override; }; class PosColourUpdater : public ParticleUpdater { public: vec4 m_vMinPosition; vec4 m_vMaxPosition; PosColourUpdater() : m_vMinPosition(vec4(0.0f)), m_vMaxPosition(vec4(0.0f)) { } ~PosColourUpdater() { } virtual void Update(double a_dDeltaTime, ParticleData* a_oParticle) override; }; class VelColourUpdater : public ParticleUpdater { public: vec4 m_vMinVelocity; vec4 m_vMaxVelocity; VelColourUpdater() : m_vMinVelocity(vec4(0.0f)), m_vMaxVelocity(vec4(0.0f)) { } ~VelColourUpdater() { } virtual void Update(double a_dDeltaTime, ParticleData* a_oParticle) override; }; class BasicTimeUpdater : public ParticleUpdater { public: BasicTimeUpdater() { } ~BasicTimeUpdater() { } virtual void Update(double a_dDeltaTime, ParticleData* a_oParticle) override; }; #endif //!_PARTICLESUPDATERS_H_
true
eb2f356ad27bbab21c9d07b854f9a8b18aaac14c
C++
cckroets/platformer
/level.h
UTF-8
3,656
3.140625
3
[]
no_license
#include <vector> #include "window.h" #include "stickman.h" #ifndef LEVEL_H #define LEVEL_H class HUD; // A Tile (Space) in the level. class Tile : public Picture { private: // Height of the tile. Zero means there is no tile. int height; // Position of the tile relative to the screen (Not constant!) int x_pos; int y_pos; public: // Default Tile Tile(); // Construct a regular tile with a certain height Tile(int height); // Some tiles may have an effect when landing on them, this one does not virtual void effect(HUD& d);// { }; // Corners of the bounding box int min_x() const; int min_y() const; int max_x() const; int max_y() const; // Change the position of the tile void setPos(int x, int y) { x_pos = x; y_pos = y; } // Paint a tile a certain way virtual void paint(GameWindow& GW); // Return the height of the tile int getHeight(); }; // A special tile that has a coin on it class CoinTile: public Tile { private: bool coin_taken; public: CoinTile() : coin_taken(false) { }; CoinTile(int height) : Tile(height), coin_taken(false) { }; void effect(HUD&); void paint(GameWindow& GW); }; // A special tile that is made of lava class LavaTile : public Tile { protected: Color color; public: static int damage; LavaTile() { }; LavaTile(int); void effect(HUD&); void paint(GameWindow& GW); }; class FlagTile : public Tile { public: FlagTile() { }; FlagTile(int h) : Tile(h) { }; void effect(HUD&); void paint(GameWindow& GW); }; class GunTile : public LavaTile { private: int bullet_y; public: static int speed; GunTile() { }; GunTile(int h) : LavaTile(h), bullet_y(0) { color=Black; }; void effect(HUD&); void paint(GameWindow& GW); }; class HUD : public Picture { private: bool finished; int hp; int coins; public: void addCoin() { coins++; }; void takeDamage(int dmg) { hp -= std::min(hp,dmg); }; void finish() { finished = true; }; bool died(); bool won() { return finished; }; void paint(GameWindow& GW); HUD() : hp(100), coins(0), finished(false) { }; }; /* A randomly generated level given a length and max height a tile can be. Each tile to the right */ class Level : public Picture { private: // Vector of spaces, representing the level from left to right. // Each uint represents the height of that space. Spaces increase // in height by at most one, but may decrease to zero. std::vector<Tile*> spaces; HUD hud; // Moving speeds int run_speed; int jump_speed; int jump_peak; // True if jumping or blocked bool jumping; bool block; void start_jump(); public: static long y_offset; static long x_offset; // Empty construction does nothing; Level() { }; ~Level(); // Create a random level of a specified length and height Level(int length, int rs, int js); // Return the index of the first and last blocks on the screen // (The ones that need to be redrawn) uint first_block(); uint last_block(); // Returns the index of the first active block, // the next one may also be active simultaneously uint active_block(); // Returns a const ref to the ith tile const Tile& getTile(size_t i); // Paint the world onto the screen void paint(GameWindow& GW); bool damaging(); bool gameOver(); void jump(bool high); void nextFrame(); void move(Key); bool floating(); bool blocked(); }; // The always-moving sun. class Sun : public Picture { private: int x_pos; // X Position int speed; public: Sun() { }; // Create an instance of a sun with a specified speed Sun(int s); // Move the sun for the next frame void nextFrame(); // Draw the sun void paint(GameWindow& GW); }; #endif
true
28fff320fd67ce685b74e949534c38905e40fe0c
C++
kylehug/COCC_Cplusplus_Programming
/Assignment3b/Assignment3b.cpp
UTF-8
2,298
3.96875
4
[]
no_license
// COCC C++ - Kyle Hug - Assignment 3b // // [x] Draw out a 2D Array of periods // [x] Change a point to be an asterisk // [x] Draw a horizontal line // [ ] Draw a vertical line ( WORK IN PROGRESS ) // [ ] Draw a diagonal line // [x] Using Loops show the array on screen // // [ ] Clean up warnings // #include <iostream> #include <string> #include <time.h> using namespace std; // Get a unique random integer int GetRandInt(int max, int seedOffset) { int randInt; srand((unsigned)time(NULL) + seedOffset); randInt = rand() % max; return randInt; } int main() { // Initialize the 2D Array, "image" const int X_SIZE = 70; const int Y_SIZE = 20; char image[X_SIZE][Y_SIZE]; int x; int y; // Initialize asterisk variables int asterRandX; int asterRandY; // Initialize horizontal line variables const int H_LINE_WIDTH = 10; int hLineRandStart; int hLineRandYPos; string userInput = "y"; // Pause at the end while (userInput == "y") { // Clear user input userInput = ""; // This is an ugly way to clear the screen, but at least it's OS independent... cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"; // Set up population of the asterisk asterRandX = GetRandInt(X_SIZE, 999); asterRandY = GetRandInt(Y_SIZE, -69); // Set up population of the horizontal line hLineRandStart = GetRandInt(X_SIZE, 42); hLineRandYPos = GetRandInt(Y_SIZE, 13); // Populate image for (x = 0; x < X_SIZE; x++) { for (y = 0; y < Y_SIZE; y++) { // Populate a random asterisk if ((x == asterRandX) && y == (asterRandY)) { image[x][y] = '*'; } // Populate the horizontal line else if ((x >= hLineRandStart) && (x <= (hLineRandStart + H_LINE_WIDTH)) && (y == hLineRandYPos)) { image[x][y] = '-'; } // Populate with a period else { image[x][y] = '.'; } } } // Print out the image for (y = 0; y < Y_SIZE; y++) { // Offset image position on screen cout << '\t'; for (x = 0; x < X_SIZE; x++) { cout << image[x][y]; } cout << endl; } // Spacer cout << "\n\n"; // Ask to quit or start over while ((userInput != "y") && (userInput != "n")) { cout << "Draw Again? [y/n]: "; getline(cin, userInput); } } return 0; }
true
5e63ddef8988d1afeec574b02335a626a2cc533d
C++
TDarkx13/Chapter_5
/Excercise5.2.cpp
UTF-8
257
3.015625
3
[]
no_license
#include<stdio.h> int main() { int r; float volume_sphere; printf("Enter radius : "); scanf("%d",&r); volume_sphere = (4/3.0)*3.14*r*r*r; printf("\nVolume of sphere = %f",volume_sphere); return 0; }
true
b34cc6cce9da4c0ee39ed3e179f4703be3b27a23
C++
nashdingsheng/spii
/include/spii/dynamic_auto_diff_term.h
UTF-8
15,644
2.8125
3
[ "BSD-2-Clause" ]
permissive
// Petter Strandmark 2013. #ifndef SPII_DYNAMIC_AUTO_DIFF_TERM_H #define SPII_DYNAMIC_AUTO_DIFF_TERM_H // // This header specialized dynamic versions of AutoDiffTerm, // allowing the sizes of the variables to be specified at // runtime. // // AutoDiffTerm<Functor, 2, 3, 5> my_term(arg); // // is equivalent to // // AutoDiffTerm<Functor, Dynamic, Dynamic, Dynamic> my_term(2, 3, 5, arg); // // Note that the dynamic versions of AutoDiffTerm are slower // than the equivalent static ones. // // The make_differentiable function also supports dynamic // differentiation. // // Examples // -------- // // class Functor1_2 // { // template<typename R> // R operator()(const T* x, const T* y) // { // return x[0]*x[0] + y[0] + y[1]; // } // }; // // auto term_1_2 = make_differentiable<Dynamic, Dynamic>(Functor{}, 1, 2); // #include <type_traits> #include <typeinfo> #include <spii-thirdparty/badiff.h> #include <spii-thirdparty/fadiff.h> #include <spii/auto_diff_term.h> namespace spii { static const int Dynamic = -1; // // 1-variable specialization // // Function differentiating a functor taking D variables. template<typename Functor, typename T> T dynamic_differentiate_functor( const Functor& functor, int d, const T* x_in, T* df) { using namespace fadbad; typedef fadbad::F<T> Dual; std::vector<Dual> x(d); for (int i = 0; i < d; ++i) { x[i] = x_in[i]; x[i].diff(i, d); } Dual f{functor(x.data())}; for (int i = 0; i < d; ++i) { df[i] = f.d(i); } return f.x(); } template<typename Functor> class AutoDiffTerm<Functor, Dynamic> : public Term { public: template<typename... Args> AutoDiffTerm(int d0_, Args&&... args) : d0(d0_), functor(std::forward<Args>(args)...) { } virtual int number_of_variables() const override { return 1; } virtual int variable_dimension(int var) const override { return d0; } virtual void read(std::istream& in) override { call_read_if_exists(in, functor); } virtual void write(std::ostream& out) const override { call_write_if_exists(out, functor); } virtual double evaluate(double * const * const variables) const override { return functor(variables[0]); } virtual double evaluate(double * const * const variables, std::vector<Eigen::VectorXd>* gradient) const override { typedef fadbad::F<double> Dual; std::vector<Dual> vars(d0); for (int i = 0; i < d0; ++i) { vars[i] = variables[0][i]; vars[i].diff(i, d0); } Dual f{functor(vars.data())}; for (int i = 0; i < d0; ++i) { (*gradient)[0](i) = f.d(i); } return f.x(); } virtual double evaluate(double * const * const variables, std::vector<Eigen::VectorXd>* gradient, std::vector< std::vector<Eigen::MatrixXd> >* hessian) const override { typedef fadbad::F<double> Dual; std::vector<Dual> vars(d0); for (int i = 0; i < d0; ++i) { vars[i] = variables[0][i]; vars[i].diff(i, d0); } std::vector<Dual> df(d0); Dual f = dynamic_differentiate_functor<Functor, Dual>( functor, d0, vars.data(), df.data()); for (int i = 0; i < d0; ++i) { (*gradient)[0](i) = df[i].x(); for (int j = 0; j < d0; ++j) { (*hessian)[0][0](i, j) = df[i].d(j); } } return f.x(); } protected: const int d0; Functor functor; }; // // 2-variable specialization // template<typename Functor> class AutoDiffTerm<Functor, Dynamic, Dynamic> : public Term { public: template<typename... Args> AutoDiffTerm(int d0_, int d1_, Args&&... args) : d0{d0_}, d1{d1_}, functor(std::forward<Args>(args)...) { } virtual int number_of_variables() const override { return 2; } virtual int variable_dimension(int var) const override { switch (var) { default: case 0: return d0; case 1: return d1; } } virtual void read(std::istream& in) { call_read_if_exists(in, functor); } virtual void write(std::ostream& out) const { call_write_if_exists(out, functor); } virtual double evaluate(double * const * const variables) const override { return functor(variables[0], variables[1]); } virtual double evaluate(double * const * const variables, std::vector<Eigen::VectorXd>* gradient) const override { typedef fadbad::F<double> Dual; std::vector<Dual> vars0(d0); for (int i = 0; i < d0; ++i) { vars0[i] = variables[0][i]; vars0[i].diff(i, d0 + d1); } std::vector<Dual> vars1(d1); int offset1 = d0; for (int i = 0; i < d1; ++i) { vars1[i] = variables[1][i]; vars1[i].diff(i + offset1, d0 + d1); } Dual f{functor(vars0.data(), vars1.data())}; for (int i = 0; i < d0; ++i) { (*gradient)[0](i) = f.d(i); } for (int i = 0; i < d1; ++i) { (*gradient)[1](i) = f.d(i + offset1); } return f.x(); } virtual double evaluate(double * const * const variables, std::vector<Eigen::VectorXd>* gradient, std::vector< std::vector<Eigen::MatrixXd> >* hessian) const override { typedef fadbad::B<fadbad::F<double>> BF; std::vector<BF> vars0(d0); for (int i = 0; i < d0; ++i) { vars0[i] = variables[0][i]; vars0[i].x().diff(i, d0 + d1); } std::vector<BF> vars1(d1); int offset1 = d0; for (int i = 0; i < d1; ++i) { vars1[i] = variables[1][i]; vars1[i].x().diff(offset1 + i, d0 + d1); } BF f = functor(vars0.data(), vars1.data()); f.diff(0, 1); for (int i = 0; i < d0; ++i) { (*gradient)[0](i) = vars0[i].d(0).x(); // D0 and D0 for (int j = 0; j < d0; ++j) { (*hessian)[0][0](i, j) = vars0[i].d(0).d(j); } // D0 and D1 for (int j = 0; j < d1; ++j) { (*hessian)[0][1](i, j) = vars0[i].d(0).d(offset1 + j); } } for (int i = 0; i < d1; ++i) { (*gradient)[1](i) = vars1[i].d(0).x(); // D1 and Ds0 for (int j = 0; j < d0; ++j) { (*hessian)[1][0](i, j) = vars1[i].d(0).d(j); } // D1 and D1 for (int j = 0; j < d1; ++j) { (*hessian)[1][1](i, j) = vars1[i].d(0).d(offset1 + j); } } return f.x().x(); } protected: const int d0, d1; Functor functor; }; // // 3-variable specialization // template<typename Functor> class AutoDiffTerm<Functor, Dynamic, Dynamic, Dynamic> : public Term { public: template<typename... Args> AutoDiffTerm(int d0_, int d1_, int d2_, Args&&... args) : d0{d0_}, d1{d1_}, d2{d2_}, functor(std::forward<Args>(args)...) { } virtual int number_of_variables() const override { return 3; } virtual int variable_dimension(int var) const override { switch (var) { default: case 0: return d0; case 1: return d1; case 2: return d2; } } virtual void read(std::istream& in) override { call_read_if_exists(in, this->functor); } virtual void write(std::ostream& out) const override { call_write_if_exists(out, this->functor); } virtual double evaluate(double * const * const variables) const override { return functor(variables[0], variables[1], variables[2]); } virtual double evaluate(double * const * const variables, std::vector<Eigen::VectorXd>* gradient) const override { typedef fadbad::F<double> Dual; const int number_of_vars = d0 + d1 + d2; std::vector<Dual> vars0(d0); for (int i = 0; i < d0; ++i) { vars0[i] = variables[0][i]; vars0[i].diff(i, number_of_vars); } std::vector<Dual> vars1(d1); int offset1 = d0; for (int i = 0; i < d1; ++i) { vars1[i] = variables[1][i]; vars1[i].diff(i + offset1, number_of_vars); } std::vector<Dual> vars2(d2); int offset2 = d0 + d1; for (int i = 0; i < d2; ++i) { vars2[i] = variables[2][i]; vars2[i].diff(i + offset2, number_of_vars); } Dual f(functor(vars0.data(), vars1.data(), vars2.data())); for (int i = 0; i < d0; ++i) { (*gradient)[0](i) = f.d(i); } for (int i = 0; i < d1; ++i) { (*gradient)[1](i) = f.d(i + offset1); } for (int i = 0; i < d2; ++i) { (*gradient)[2](i) = f.d(i + offset2); } return f.x(); } virtual double evaluate(double * const * const variables, std::vector<Eigen::VectorXd>* gradient, std::vector< std::vector<Eigen::MatrixXd> >* hessian) const override { typedef fadbad::B<fadbad::F<double>> BF; const int number_of_vars = d0 + d1 + d2; std::vector<BF> vars0(d0); for (int i = 0; i < d0; ++i) { vars0[i] = variables[0][i]; vars0[i].x().diff(i, number_of_vars); } std::vector<BF> vars1(d1); int offset1 = d0; for (int i = 0; i < d1; ++i) { vars1[i] = variables[1][i]; vars1[i].x().diff(offset1 + i, number_of_vars); } std::vector<BF> vars2(d2); int offset2 = d0 + d1; for (int i = 0; i < d2; ++i) { vars2[i] = variables[2][i]; vars2[i].x().diff(offset2 + i, number_of_vars); } BF f = functor(vars0.data(), vars1.data(), vars2.data()); f.diff(0, 1); for (int i = 0; i < d0; ++i) { (*gradient)[0](i) = vars0[i].d(0).x(); // D0 and D0 for (int j = 0; j < d0; ++j) { (*hessian)[0][0](i, j) = vars0[i].d(0).d(j); } // D0 and D1 for (int j = 0; j < d1; ++j) { (*hessian)[0][1](i, j) = vars0[i].d(0).d(offset1 + j); } // D0 and D2 for (int j = 0; j < d2; ++j) { (*hessian)[0][2](i, j) = vars0[i].d(0).d(offset2 + j); } } for (int i = 0; i < d1; ++i) { (*gradient)[1](i) = vars1[i].d(0).x(); // D1 and D0 for (int j = 0; j < d0; ++j) { (*hessian)[1][0](i, j) = vars1[i].d(0).d(j); } // D1 and D1 for (int j = 0; j < d1; ++j) { (*hessian)[1][1](i, j) = vars1[i].d(0).d(offset1 + j); } // D1 and D2 for (int j = 0; j < d2; ++j) { (*hessian)[1][2](i, j) = vars1[i].d(0).d(offset2 + j); } } for (int i = 0; i < d2; ++i) { (*gradient)[2](i) = vars2[i].d(0).x(); // D2 and D0 for (int j = 0; j < d0; ++j) { (*hessian)[2][0](i, j) = vars2[i].d(0).d(j); } // D2 and D1 for (int j = 0; j < d1; ++j) { (*hessian)[2][1](i, j) = vars2[i].d(0).d(offset1 + j); } // D2 and D2 for (int j = 0; j < d2; ++j) { (*hessian)[2][2](i, j) = vars2[i].d(0).d(offset2 + j); } } return f.x().x(); } protected: const int d0, d1, d2; Functor functor; }; // // 4-variable specialization // template<typename Functor> class AutoDiffTerm<Functor, Dynamic, Dynamic, Dynamic, Dynamic> : public Term { public: template<typename... Args> AutoDiffTerm(int d0_, int d1_, int d2_, int d3_, Args&&... args) : d0{d0_}, d1{d1_}, d2{d2_}, d3{d3_}, functor(std::forward<Args>(args)...) { } virtual int number_of_variables() const override { return 4; } virtual int variable_dimension(int var) const override { switch (var) { default: case 0: return d0; case 1: return d1; case 2: return d2; case 3: return d3; } } virtual void read(std::istream& in) override { call_read_if_exists(in, this->functor); } virtual void write(std::ostream& out) const override { call_write_if_exists(out, this->functor); } virtual double evaluate(double * const * const variables) const override { return functor(variables[0], variables[1], variables[2], variables[3]); } virtual double evaluate(double * const * const variables, std::vector<Eigen::VectorXd>* gradient) const override { typedef fadbad::F<double> Dual; const int number_of_vars = d0 + d1 + d2 + d3; std::vector<Dual> vars0(d0); for (int i = 0; i < d0; ++i) { vars0[i] = variables[0][i]; vars0[i].diff(i, number_of_vars); } std::vector<Dual> vars1(d1); int offset1 = d0; for (int i = 0; i < d1; ++i) { vars1[i] = variables[1][i]; vars1[i].diff(i + offset1, number_of_vars); } std::vector<Dual> vars2(d2); int offset2 = d0 + d1; for (int i = 0; i < d2; ++i) { vars2[i] = variables[2][i]; vars2[i].diff(i + offset2, number_of_vars); } std::vector<Dual> vars3(d3); int offset3 = d0 + d1 + d2; for (int i = 0; i < d3; ++i) { vars3[i] = variables[3][i]; vars3[i].diff(i + offset3, number_of_vars); } Dual f(functor(vars0.data(), vars1.data(), vars2.data(), vars3.data())); for (int i = 0; i < d0; ++i) { (*gradient)[0](i) = f.d(i); } for (int i = 0; i < d1; ++i) { (*gradient)[1](i) = f.d(i + offset1); } for (int i = 0; i < d2; ++i) { (*gradient)[2](i) = f.d(i + offset2); } for (int i = 0; i < d3; ++i) { (*gradient)[3](i) = f.d(i + offset3); } return f.x(); } virtual double evaluate(double * const * const variables, std::vector<Eigen::VectorXd>* gradient, std::vector< std::vector<Eigen::MatrixXd> >* hessian) const override { typedef fadbad::B<fadbad::F<double>> BF; const int number_of_vars = d0 + d1 + d2 + d3; std::vector<BF> vars0(d0); for (int i = 0; i < d0; ++i) { vars0[i] = variables[0][i]; vars0[i].x().diff(i, number_of_vars); } std::vector<BF> vars1(d1); const int offset1 = d0; for (int i = 0; i < d1; ++i) { vars1[i] = variables[1][i]; vars1[i].x().diff(offset1 + i, number_of_vars); } std::vector<BF> vars2(d2); const int offset2 = d0 + d1; for (int i = 0; i < d2; ++i) { vars2[i] = variables[2][i]; vars2[i].x().diff(offset2 + i, number_of_vars); } std::vector<BF> vars3(d3); const int offset3 = d0 + d1 + d2; for (int i = 0; i < d3; ++i) { vars3[i] = variables[3][i]; vars3[i].x().diff(offset3 + i, number_of_vars); } BF f = functor(vars0.data(), vars1.data(), vars2.data(), vars3.data()); f.diff(0, 1); for (int i = 0; i < d0; ++i) { (*gradient)[0](i) = vars0[i].d(0).x(); // D0 and D0 for (int j = 0; j < d0; ++j) { (*hessian)[0][0](i, j) = vars0[i].d(0).d(j); } // D0 and D1 for (int j = 0; j < d1; ++j) { (*hessian)[0][1](i, j) = vars0[i].d(0).d(offset1 + j); } // D0 and D2 for (int j = 0; j < d2; ++j) { (*hessian)[0][2](i, j) = vars0[i].d(0).d(offset2 + j); } // D0 and D3 for (int j = 0; j < d3; ++j) { (*hessian)[0][3](i, j) = vars0[i].d(0).d(offset3 + j); } } for (int i = 0; i < d1; ++i) { (*gradient)[1](i) = vars1[i].d(0).x(); // D1 and D0 for (int j = 0; j < d0; ++j) { (*hessian)[1][0](i, j) = vars1[i].d(0).d(j); } // D1 and D1 for (int j = 0; j < d1; ++j) { (*hessian)[1][1](i, j) = vars1[i].d(0).d(offset1 + j); } // D1 and D2 for (int j = 0; j < d2; ++j) { (*hessian)[1][2](i, j) = vars1[i].d(0).d(offset2 + j); } // D1 and D2 for (int j = 0; j < d3; ++j) { (*hessian)[1][3](i, j) = vars1[i].d(0).d(offset3 + j); } } for (int i = 0; i < d2; ++i) { (*gradient)[2](i) = vars2[i].d(0).x(); // D2 and D0 for (int j = 0; j < d0; ++j) { (*hessian)[2][0](i, j) = vars2[i].d(0).d(j); } // D2 and D1 for (int j = 0; j < d1; ++j) { (*hessian)[2][1](i, j) = vars2[i].d(0).d(offset1 + j); } // D2 and D2 for (int j = 0; j < d2; ++j) { (*hessian)[2][2](i, j) = vars2[i].d(0).d(offset2 + j); } // D2 and D3 for (int j = 0; j < d3; ++j) { (*hessian)[2][3](i, j) = vars2[i].d(0).d(offset3 + j); } } for (int i = 0; i < d3; ++i) { (*gradient)[3](i) = vars3[i].d(0).x(); // D3 and D0 for (int j = 0; j < d0; ++j) { (*hessian)[3][0](i, j) = vars3[i].d(0).d(j); } // D3 and D1 for (int j = 0; j < d1; ++j) { (*hessian)[3][1](i, j) = vars3[i].d(0).d(offset1 + j); } // D3 and D2 for (int j = 0; j < d2; ++j) { (*hessian)[3][2](i, j) = vars3[i].d(0).d(offset2 + j); } // D3 and D3 for (int j = 0; j < d3; ++j) { (*hessian)[3][3](i, j) = vars3[i].d(0).d(offset3 + j); } } return f.x().x(); } protected: const int d0, d1, d2, d3; Functor functor; }; } // namespace spii #endif
true
d6225d9a353a787eb207a1690e3314e8dbdac074
C++
dilsekhpatnaik7/cbcplusplus
/Pointers&Functions/etc.cpp
UTF-8
477
3.53125
4
[]
no_license
#include <iostream> using namespace std; int main() { int a = 10; int *ptr = &a; int *ptr2 = ptr; cout << *ptr << endl; cout << *ptr2 << endl; int b = 20; *ptr2 = b; // was pointing to the same location ad ptr and this changes what // was in that location // hence it is changed for both. if i had done ptr2 = &b, then ptr2 will point // to b but no change in ptr. cout << *ptr << endl; // 20 cout << *ptr2 << endl; // 20 return 0; }
true
332a3b2da30a89cc1fcd2d187382b793776ddd28
C++
dustinslade/Sector_TD
/Position.h
UTF-8
1,271
3.296875
3
[]
no_license
#ifndef POSITION_H #define POSITION_H class Position { public: //Pre-condition:none //Post-condition: none //Parameters: none //Return Values: none Position(); //Pre-condition:none //Post-condition: a new postion is created //Parameters: integer x and y //Return Values: none Position(int x, int y); //Pre-condition:none //Post-condition: none //Parameters: none //Return Values: none virtual ~Position(); //Pre-condition:something needs a position //Post-condition: position is set //Parameters: integer x and y //Return Values: none void setPosition(int x, int y); //Pre-condition:have object that user need X for //Post-condition: user gets x of selected object //Parameters: none //Return Values: integer representing X int getX(); //Pre-condition:have object that user need y for //Post-condition: user gets Y of selected object //Parameters: none //Return Values: integer representing Y int getY(); protected: private: int X; //This is in pixels int Y; //Also in pixels }; #endif // POSITION_H
true
4987ab494753e81979b3589bfe50547a44a5a27e
C++
alyapunov/banlog
/IndexedBitsetUnitTest.cpp
UTF-8
1,250
3.140625
3
[ "BSD-2-Clause" ]
permissive
#include <IndexedBitset.hpp> #include <iostream> #include <set> void check(bool aExpession, const char* aMessage) { if (!aExpession) { //assert(false); throw std::runtime_error(aMessage); } } void test(size_t aBitCount) { size_t sRuns = 1000 + aBitCount * 10; IndexedBitset b(aBitCount); std::set<size_t> c; for (size_t i = 0; i < sRuns; i++) { bool sIns = rand() & 1; size_t sPos = rand() % aBitCount; if (sIns) { b.set(sPos); c.insert(sPos); } else { b.clear(sPos); c.erase(sPos); } check(b.empty() == c.empty(), "empty check failed"); if (!b.empty()) check(b.lowest() == *c.begin(), "lowest check failed"); } } int main() { try { IndexedBitset b; check(b.empty(), "why no empty"); b.create(10); check(b.empty(), "why no empty"); b.create(0); check(b.empty(), "why no empty"); test(1); test(2); test(64); test(65); test(1000); } catch (const std::exception& e) { std::cerr << e.what() << std::endl; return EXIT_FAILURE; } }
true
ea0f8c96cf1513830b5dcd85449a9439ec71354c
C++
tomomii0806/Banking
/BSTree.cpp
UTF-8
4,047
3.46875
3
[]
no_license
/* * Tomomi Nakamura * Banking * file @ BSTree.cpp */ #include "BSTree.h" #include "Account.h" //default constructo BSTree::BSTree() { root = NULL; size = 0; } //destructor BSTree::~BSTree() { Empty(); } //inserting new account into BST bool BSTree::insert(Account * account) { if (isEmpty()) { root = new Node(account, NULL, NULL); size++; return true; } else { return insert(account, root); } } //private method for insert bool BSTree::insert(Account *account, BSTree::Node* curr) { if (account->GetClientId() == curr->pAccount->GetClientId()) { cout << "ERROR: Account " << account->GetClientId() << " is already open. Transaction refused." << endl; cout << endl; return false; } else if (account->GetClientId() < curr->pAccount->GetClientId()) { if (curr->left == NULL) { curr->left = new Node(account, NULL, NULL); size++; return true; } else { return insert(account, curr->left); } } else if (account->GetClientId() > curr->pAccount->GetClientId()) { if (curr->right == NULL) { curr->right = new Node(account, NULL, NULL); size++; return true; } else { return insert(account, curr->right); } } } // retrieve object, first parameter is the ID of the account // second parameter holds pointer to found object, NULL if not found bool BSTree::Retrive(const int &clientId, Account *&account) const { if (isEmpty()) { return false; } else { return Retrive(clientId, account, root); } } //private method for retrive bool BSTree::Retrive(const int &clientId, Account *&account, BSTree::Node *curr) const { if (curr == NULL) { cout << "ERROR: Account " << clientId << " not found. Transferal refused."; cout << endl; return false; } else if (clientId == curr->pAccount->GetClientId()) { account = curr->pAccount; return true; } else if (clientId < curr->pAccount->GetClientId()) { return Retrive(clientId, account, curr->left); } else { return Retrive(clientId, account, curr->right); } } //Displaying all account in BST void BSTree::Display() const { cout << "Displaying BST" << endl; if (!isEmpty()) { Display(root); } cout << endl; } //private method for display void BSTree::Display(BSTree::Node *curr) const { if (curr == NULL) { return; } Display(curr->left); cout << curr->pAccount->GetClientId() << ", " << curr->pAccount->GetFirstName() << endl; Display(curr->right); } //Checking is BST is empty bool BSTree::isEmpty() const { return root == NULL; } //Emptying BST void BSTree::Empty() { if (!isEmpty()) { Empty(root); //delete root; root = NULL; size = 0; } } //private method for empty() void BSTree::Empty(BSTree::Node *curr) { if (curr == NULL) { return; } Empty(curr->left); Empty(curr->right); delete curr; //delete curr->right; //delete curr->left; //curr->pAccount = NULL; //curr->right = NULL; //curr->left = NULL; curr = NULL; } //Returning vector which contains all accounts in BST vector<Account> BSTree::GetAllAccount() { if (!isEmpty()) { vector<Account> v; GetAllAccount(root, v); return v; } } //private method for getAllAccount() void BSTree::GetAllAccount(BSTree::Node *curr, vector<Account>& v) { if (curr == NULL) { return; } GetAllAccount(curr->left, v); v.push_back(*(curr->pAccount)); GetAllAccount(curr->right, v); } //constructor for Node BSTree::Node::Node(Account *account, BSTree::Node *right, BSTree::Node *left) : pAccount{account}, right{right}, left{left} { } //destructor for Node BSTree::Node::~Node() { delete pAccount; pAccount = NULL; }
true
166968139a77c15bc85208cb6e626b67e32f0461
C++
kobe24o/LeetCode
/algorithm/leetcode5713.cpp
UTF-8
608
2.84375
3
[]
no_license
class Solution { public: int numDifferentIntegers(string word) { word.push_back('a'); unordered_set<string> s; string num; for(auto c : word) { if(isalpha(c)) { if(!num.empty()) { while(num.size()>1 && *num.begin()=='0') num.erase(num.begin()); s.insert(num); num = ""; } } else//数字 { num.push_back(c); } } return s.size(); } };
true
b9fe77d57fdc00e7866df871e7bca8c353c7064d
C++
yetanotherbot/leetcode
/289. Game of Life/solution.cpp
UTF-8
934
3.015625
3
[]
no_license
class Solution { private: int neighbors(vector<vector<int>> &board, int i, int j) { int n = 0; int row = board.size(), col = board[0].size(); for (int r = max(0, i-1); r < min(i+2, row); r++) for (int c = max(0, j-1); c < min(j+2, col); c++) n += board[r][c] & 1; n -= board[i][j] & 1; return n; } public: void gameOfLife(vector<vector<int>>& board) { int row = board.size(); if (!row) return; int col = board[0].size(); if (!col) return; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { int n = neighbors(board, i, j); if (n >= 2 && n <= 3 && board[i][j] & 1 || n == 3 && !(board[i][j] & 1)) board[i][j] |= 2; } } for (auto &v: board) for (auto &e: v) e >>= 1; } };
true
9faf64082f832f7f1c94c5e6d2c92146bb13c3b1
C++
VipinPatel1305/mean_stack
/arduino/uv_tmp_big_attiny/uv_tmp_big_attiny.ino
UTF-8
1,353
2.84375
3
[]
no_license
#include "ssd1306.h" #include "DHT.h" #include <avr/pgmspace.h> SSD1306 oled; #define UV_PIN A3 #define DHTPIN A2 #define DHTTYPE DHT11 DHT dht(DHTPIN, DHTTYPE); void setup(void) { pinMode(UV_PIN, INPUT); pinMode(DHTPIN, INPUT); delay(3000); dht.begin(); delay(2000); TinyWireM.begin(); oled.begin(); oled.fill(0x00); // clear in black oled.print_digits(0, 0, 1, 10, 97, false); oled.print_digits(0, 1, 1, 10, 98, false); oled.print_digits(0, 2, 1, 10, 99, false); delay(3000); } void displayUV() { uint16_t uv = analogRead(UV_PIN); uv = 0; for(int i = 0; i < 10; i++) { uv += analogRead(UV_PIN); delay(40); } uv = uv/10; oled.print_digits(0, 0, 1, 10, uv, false); } void displayTemp() { /* float temp; //dicard first value int reading = analogRead(LM_PREC); reading = 0; for(int i = 0; i < 10; i++) { reading += analogRead(LM_PREC); delay(40); } reading = reading/10; float mv = (reading / 1024.0) * 5000; int imv = mv/10; */ float t = dht.readTemperature(); int imv = t; oled.print_digits(0, 1, 1, 10, imv, false); float h = dht.readHumidity(); int iHumidity = h; oled.print_digits(0, 2, 1, 10, iHumidity, false); } void loop() { displayUV(); displayTemp(); delay(5000); }
true
1ef15263689db1bb23a275da12c0a0518fe92017
C++
AutumnKite/Codes
/POJ/1737 Connected Graph/DP,组合数学/std.cpp
UTF-8
2,494
2.6875
3
[]
no_license
#include <cstdio> #include <cstring> #include <algorithm> #include <vector> struct BigInt{ const static long long P = 1000000000; std :: vector<long long> a; BigInt operator = (int x){ while (x) a.push_back(x % P), x /= P; return *this; } BigInt operator + (const BigInt &b) const { BigInt c; c.a.resize(std :: max(a.size(), b.a.size()) + 1); for (register int i = 0; i < a.size(); ++i) c.a[i] += a[i]; for (register int i = 0; i < b.a.size(); ++i) c.a[i] += b.a[i]; for (register int i = 0; i < c.a.size() - 1; ++i) c.a[i + 1] += c.a[i] / P, c.a[i] %= P; while (c.a.size() && !c.a[c.a.size() - 1]) c.a.pop_back(); return c; } BigInt operator += (const BigInt &b){ return *this = *this + b; } BigInt operator - (const BigInt &b) const { BigInt c; c.a.resize(a.size() + 1); for (register int i = 0; i < c.a.size() - 1; ++i){ c.a[i] += a[i] - (i < b.a.size() ? b.a[i] : 0); if (c.a[i] < 0) --c.a[i + 1], c.a[i] += P; } while (c.a.size() && !c.a[c.a.size() - 1]) c.a.pop_back(); return c; } BigInt operator -= (const BigInt &b){ return *this = *this - b; } BigInt operator * (const BigInt &b) const { BigInt c; c.a.resize(a.size() + b.a.size()); for (register int i = 0; i < a.size(); ++i) for (register int j = 0; j < b.a.size(); ++j) c.a[i + j] += a[i] * b.a[j], c.a[i + j + 1] += c.a[i + j] / P, c.a[i + j] %= P; while (c.a.size() && !c.a[c.a.size() - 1]) c.a.pop_back(); return c; } void print(){ if (!a.size()) return putchar('0'), void(0); printf("%lld", a[a.size() - 1]); for (register int i = a.size() - 2; ~i; --i){ int x = a[i], cnt = 0, num[10]; memset(num, 0, sizeof num); while (x) num[++cnt] = x % 10, x /= 10; for (register int j = 9; j; --j) putchar(num[j] + '0'); } } }; BigInt C[51][51], pow[1230], f[51]; int n; int main(){ C[0][0] = 1; for (register int i = 1; i <= 50; ++i){ C[i][0] = C[i][i] = 1; for (register int j = 1; j < i; ++j) C[i][j] = C[i - 1][j] + C[i - 1][j - 1]; } pow[0] = 1; for (register int i = 1; i <= 1225; ++i) pow[i] = pow[i - 1] + pow[i - 1]; for (register int i = 1; i <= 50; ++i){ f[i] = pow[i * (i - 1) >> 1]; // printf("%d ", i), f[i].print(), putchar(' '); for (register int j = 1; j < i; ++j) f[i] -= C[i - 1][j - 1] * f[j] * pow[(i - j) * (i - j - 1) >> 1]; // f[i].print(), putchar('\n'); } while (scanf("%d", &n), n) f[n].print(), putchar('\n'); }
true
0c47a61fedd89b377ad5bdf9cdb8b13162a26e60
C++
engichang1467/3D-Game-Simulator
/Vector3.h
UTF-8
700
2.78125
3
[]
no_license
#ifndef VECTOR3_H #define VECTOR3_H #include <iostream> #include <GLFW/glfw3.h> #include "Matrix3.h" typedef struct { GLfloat x, y, z; } Vector3; Vector3 makeVector3( GLfloat x, GLfloat y, GLfloat z ); Vector3 addVector3(Vector3 vectorA, Vector3 vectorB); Vector3 subtractVector3(Vector3 vectorA, Vector3 vectorB); // Convert the length of our vector into 1 Vector3 normalizeVector3(Vector3 vector); Vector3 scalerMultiplyVector3(Vector3 vectorToMultiply, GLfloat scalerValue); Vector3 crossProductVector3(Vector3 vectorA, Vector3 vectorB); GLfloat dotProductVector3( Vector3 vectorA, Vector3 vectorB); Vector3 transformVector3(Vector3 vector, Matrix3 transformMatrix); #endif // VECTOR3_H
true
5958cc58eb47a7eef6f0b5e2b25d4acdfec99429
C++
ksolo/cppnd-system-monitor
/src/linux_parser.cpp
UTF-8
8,915
2.890625
3
[ "MIT" ]
permissive
#include "linux_parser.h" #include <dirent.h> #include <unistd.h> #include <string> #include <vector> // debugging #include <cassert> #include <iostream> using std::stof; using std::string; using std::to_string; using std::vector; // DONE: An example of how to read data from the filesystem string LinuxParser::OperatingSystem() { string line; string key; string value; std::ifstream filestream(kOSPath); if (filestream.is_open()) { while (std::getline(filestream, line)) { std::replace(line.begin(), line.end(), ' ', '_'); std::replace(line.begin(), line.end(), '=', ' '); std::replace(line.begin(), line.end(), '"', ' '); std::istringstream linestream(line); while (linestream >> key >> value) { if (key == "PRETTY_NAME") { std::replace(value.begin(), value.end(), '_', ' '); return value; } } } } return value; } // DONE: An example of how to read data from the filesystem string LinuxParser::Kernel() { string os, kernel; string line; std::ifstream stream(kProcDirectory + kVersionFilename); if (stream.is_open()) { std::getline(stream, line); std::istringstream linestream(line); linestream >> os >> kernel; } return kernel; } // BONUS: Update this to use std::filesystem vector<int> LinuxParser::Pids() { vector<int> pids; DIR* directory = opendir(kProcDirectory.c_str()); struct dirent* file; while ((file = readdir(directory)) != nullptr) { // Is this a directory? if (file->d_type == DT_DIR) { // Is every character of the name a digit? string filename(file->d_name); if (std::all_of(filename.begin(), filename.end(), isdigit)) { int pid = stoi(filename); pids.push_back(pid); } } } closedir(directory); return pids; } // TODO: Read and return the system memory utilization float LinuxParser::MemoryUtilization() { std::ifstream mem_info_file(kProcDirectory + kMeminfoFilename); if (mem_info_file) { float mem_total{0.0}, mem_free{0.0}; while(mem_info_file.is_open()) { string mem_line; getline(mem_info_file, mem_line); std::istringstream mem_stream(mem_line); string key, value; mem_stream >> key >> value; if (key == "MemTotal:") { mem_total = std::stof(value); } if (key == "MemFree:") { mem_free = std::stof(value); } if (mem_total && mem_free) { mem_info_file.close(); return (mem_total - mem_free) / mem_total; } } mem_info_file.close(); } return float{0}; } // TODO: Read and return the system uptime long LinuxParser::UpTime() { std::ifstream uptime_file(kProcDirectory + kUptimeFilename); if (uptime_file) { string uptime_line; getline(uptime_file, uptime_line); uptime_file.close(); long uptime; std::istringstream uptime_stream(uptime_line); uptime_stream >> uptime; return uptime; } return long{0}; } // TODO: Read and return the number of jiffies for the system long LinuxParser::Jiffies() { return ActiveJiffies() + IdleJiffies(); } // TODO: Read and return the number of active jiffies for a PID // REMOVE: [[maybe_unused]] once you define the function long LinuxParser::ActiveJiffies(int pid) { vector<string> pid_stats = CpuUtilization(pid); return std::stol(pid_stats[13]) + std::stol(pid_stats[14]) + std::stol(pid_stats[15]) + std::stol(pid_stats[16]); } vector<string> LinuxParser::CpuUtilization(int pid) { std::ifstream pid_stat_file(kProcDirectory + std::to_string(pid) + kStatFilename); if (pid_stat_file) { string stat_line; getline(pid_stat_file, stat_line); pid_stat_file.close(); std::istringstream stat_stream(stat_line); std::vector<string> tokens; string token; while(stat_stream >> token) { tokens.push_back(token); } return tokens; } return {}; } // TODO: Read and return the number of active jiffies for the system long LinuxParser::ActiveJiffies() { std::vector<std::string> cpu_stats = CpuUtilization(); return std::stol(cpu_stats[kUser_]) + std::stol(cpu_stats[kNice_]) + std::stol(cpu_stats[kSystem_]) + std::stol(cpu_stats[kIRQ_]) + std::stol(cpu_stats[kSoftIRQ_]) + std::stol(cpu_stats[kSteal_]); } // TODO: Read and return the number of idle jiffies for the system long LinuxParser::IdleJiffies() { std::vector<std::string> cpu_stats = CpuUtilization(); return std::stol(cpu_stats[kIdle_]) + std::stol(cpu_stats[kIOwait_]); } // TODO: Read and return CPU utilization vector<string> LinuxParser::CpuUtilization() { vector<string> results; std::ifstream proc_stat(kProcDirectory + kStatFilename); if (proc_stat) { string cpu_line; getline(proc_stat, cpu_line); proc_stat.close(); string token; std::istringstream cpu_stats(cpu_line); while (cpu_stats >> token) { if (token == "cpu") { continue; } results.push_back(token); } } return results; } // TODO: Read and return the total number of processes int LinuxParser::TotalProcesses() { std::ifstream proc_stat_file(kProcDirectory + kStatFilename); if (proc_stat_file) { while(proc_stat_file.is_open()) { string stat_line; getline(proc_stat_file, stat_line); string key, value; std::istringstream stat_line_stream(stat_line); stat_line_stream >> key >> value; if (key == "processes") { proc_stat_file.close(); return std::stoi(value); } } } return 0; } // TODO: Read and return the number of running processes int LinuxParser::RunningProcesses() { std::ifstream proc_stat_file(kProcDirectory + kStatFilename); if (proc_stat_file) { while(proc_stat_file.is_open()) { string stat_line; getline(proc_stat_file, stat_line); string key, value; std::istringstream stat_line_stream(stat_line); stat_line_stream >> key >> value; if (key == "procs_running") { proc_stat_file.close(); return std::stoi(value); } } } return 0; } // TODO: Read and return the command associated with a process // REMOVE: [[maybe_unused]] once you define the function string LinuxParser::Command(int pid) { std::ifstream command_stream(kProcDirectory + std::to_string(pid) + kCmdlineFilename); if (command_stream) { string command_line; getline(command_stream, command_line); command_stream.close(); return command_line; } return string(); } // TODO: Read and return the memory used by a process // REMOVE: [[maybe_unused]] once you define the function string LinuxParser::Ram(int pid) { std::ifstream proc_status_file(kProcDirectory + std::to_string(pid) + kStatusFilename); if (proc_status_file) { while (proc_status_file.is_open()) { string proc_line; getline(proc_status_file, proc_line); std::istringstream proc_stream(proc_line); string key, value; proc_stream >> key >> value; if (key == "VmSize:") { proc_status_file.close(); long mem = std::stol(value); return std::to_string(mem / 1024); } } } return string(); } // TODO: Read and return the user ID associated with a process // REMOVE: [[maybe_unused]] once you define the function string LinuxParser::Uid(int pid) { std::ifstream status_file(kProcDirectory + std::to_string(pid) + kStatusFilename); string uid; if (status_file) { while(status_file.is_open()) { string status_line; getline(status_file, status_line); std::istringstream status_stream(status_line); string key, value; status_stream >> key >> value; if (key == "Uid:") { uid = value; status_file.close(); } } } return uid; } // TODO: Read and return the user associated with a process // REMOVE: [[maybe_unused]] once you define the function string LinuxParser::User(int pid) { string uid = Uid(pid); std::ifstream etc_password(kPasswordPath); if (etc_password) { while(etc_password.is_open()) { string line; getline(etc_password, line); std::istringstream line_stream(line); string user, mode, matching_uid; getline(line_stream, user, ':'); getline(line_stream, mode, ':'); getline(line_stream, matching_uid, ':'); if (matching_uid == uid) { etc_password.close(); return user; } } etc_password.close(); } return string(); } // TODO: Read and return the uptime of a process // REMOVE: [[maybe_unused]] once you define the function long LinuxParser::UpTime(int pid) { std::vector<std::string> pid_stat = CpuUtilization(pid); return UpTime() - (std::stol(pid_stat[21]) / sysconf(_SC_CLK_TCK)) ; }
true
c1aae9e5116b73a8201f2e32534452d7511c8d2e
C++
stqp/algorithm
/other/stl/17.set.cpp
UTF-8
481
2.78125
3
[]
no_license
#include <iostream> #include <cmath> #include <algorithm> #include <ctime> #include <functional> #include <vector> #include <stack> #include <queue> #include <map> #include <set> using namespace std; int main(){ set<int> s; s.insert(10); s.insert(20); s.insert(30); cout << "lower bound: " << (*s.lower_bound(15)) << endl; s.erase(20); auto itr = s.begin(); while(itr != s.end()) { cout << (*itr) << endl; itr++; } }
true
300d35444bc0524a4a5e051fed6f166c6c938537
C++
Holy-YxY/Algorithms-Dstructure
/Algorithms(算法)/Sorting_algorithm(排序算法)/Insertion.h
IBM852
285
2.9375
3
[]
no_license
#pragma once /* //Insertion_sort */ template <class T> void insertion(T* arr, int n) { for (int i = 0; i < n; i++) { int p = i - 1; T temp = arr[i]; while (arr[p] > temp && p >= 0 ) { arr[p + 1] = arr[p]; p--; } arr[p + 1] = temp; } }
true
274e0643313e9a6800f8b369d610afc081ab414e
C++
gusugusu1018/rclcpp_websocket
/include/rclcpp_websocket/rclcpp_websocket.hpp
UTF-8
3,637
2.515625
3
[]
no_license
#ifndef RCLCPP_WEBSOCKET_HPP #define RCLCPP_WEBSOCKET_HPP #include <cstdio> #include <cstdint> #include <memory> #include <string> #include <rclcpp/rclcpp.hpp> #include <std_msgs/msg/string.hpp> #include <websocketpp/config/asio_no_tls.hpp> #include <websocketpp/server.hpp> #include <functional> #include <boost/thread.hpp> namespace rclcpp_websocket { using namespace std::chrono_literals; typedef websocketpp::server<websocketpp::config::asio> server; class RclcppWebsocket : public rclcpp::Node { public: explicit RclcppWebsocket(const std::string & sub_topic_name, std::uint16_t port) : Node("rclcpp_websocket") { RCLCPP_INFO(this->get_logger(), "subscribe topic : %s\nserver port: %d", sub_topic_name.c_str(), port); // Set logging settings (/usr/local/includewebsocketpp/logger/levels.hpp) endpoint_.set_error_channels(websocketpp::log::elevel::warn); endpoint_.set_access_channels(websocketpp::log::alevel::all ^ websocketpp::log::alevel::frame_payload); // Initialize Asio endpoint_.init_asio(); // Set websocket handlers endpoint_.set_open_handler(websocketpp::lib::bind(&RclcppWebsocket::on_open,this,std::placeholders::_1)); endpoint_.set_close_handler(websocketpp::lib::bind(&RclcppWebsocket::on_close,this,std::placeholders::_1)); // Set the default message handler to the echo handler endpoint_.set_message_handler(std::bind( &RclcppWebsocket::echo_handler, this, std::placeholders::_1, std::placeholders::_2 )); // Create a callback function to subscribe auto callback = [this](const std_msgs::msg::String::UniquePtr msg) -> void { RCLCPP_INFO(this->get_logger(), "%s",msg->data.c_str()); // Broadcast count to all connections con_list::iterator it; for (it = connections_.begin(); it != connections_.end(); ++it) { endpoint_.send(*it,msg->data.c_str(),websocketpp::frame::opcode::text); } }; // Topic setting for subscribe rclcpp::QoS qos(rclcpp::KeepLast(10)); // Create subscriber sub_ = create_subscription<std_msgs::msg::String>(sub_topic_name, qos, callback); // Websocket server run RclcppWebsocket::ws_run(port); } void ws_run(std::uint16_t port){ // Listen on port 9002 endpoint_.listen(port); // Queues a connection accept operation endpoint_.start_accept(); // Start the ASIO io_service run loop boost::thread run_thread(boost::bind(&server::run, boost::ref(endpoint_))); } void echo_handler(websocketpp::connection_hdl hdl, server::message_ptr msg) { // Write a new message endpoint_.send(hdl, msg->get_payload(), msg->get_opcode()); } void on_open(websocketpp::connection_hdl hdl) { connections_.insert(hdl); } void on_close(websocketpp::connection_hdl hdl) { connections_.erase(hdl); } private: server endpoint_; typedef std::set<websocketpp::connection_hdl,std::owner_less<websocketpp::connection_hdl>> con_list; con_list connections_; rclcpp::Subscription<std_msgs::msg::String>::SharedPtr sub_; }; } // namespace rclcpp_websocket #endif // RCLCPP_WEBSOCKET_HPP
true
7e28370ee49c4d2cc3c5e80876fad6cbaee4d6c0
C++
PrachiSinghal86/Leetcode
/Graph/Evaluate Division.cpp
UTF-8
1,945
2.640625
3
[]
no_license
class Solution { public: bool p(map<string,vector<pair<string,double>>>m,string a,string b,double d,vector<double>&ot,map<string,bool>&vis) { for(int i=0;i<m[a].size();i++) { if(m[a][i].first==b) { ot.push_back(d*m[a][i].second); return true; } if(vis[m[a][i].first]==true) continue; vis[m[a][i].first]=true; bool c=p(m,m[a][i].first,b,d*m[a][i].second,ot,vis); vis[m[a][i].first]=false; if(c) return c; } return false; } vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) { map<string,vector<pair<string,double>>>m; map<string,bool>vis; for(int i=0;i<values.size();i++) { m[equations[i][0]].push_back(make_pair(equations[i][1],values[i])); vis[equations[i][0]]=false; m[equations[i][1]].push_back(make_pair(equations[i][0],1/values[i])); vis[equations[i][1]]=false; //cout<<m[equations[i][0]].back(); } vector<double>ot; for(int i=0;i<queries.size();i++) { if(m.find(queries[i][0])==m.end()||m.find(queries[i][1])==m.end()) { ot.push_back(-1.00000); } else if(queries[i][0]==queries[i][1]) ot.push_back(1.00000); else{ double d=1.00000; vis[queries[i][0]]=true; p(m,queries[i][0],queries[i][1],d,ot,vis); vis[queries[i][0]]=false; } if(ot.size()<i+1) ot.push_back(-1.00000); } return ot; } };
true
92115773e68f5324a9374b417bd289ad9c99df84
C++
pavelsimo/ProgrammingContest
/leetcode/46_permutations.cpp
UTF-8
1,226
3.21875
3
[]
no_license
/* ======================================================================== $File: $Date: $Creator: Pavel Simo ======================================================================== */ #include <iostream> #include <vector> using namespace std; class Solution { public: void perm(int lo, vector<int> &nums, vector<vector<int> > &res) { if (lo >= nums.size() - 1) { res.push_back(nums); return; } for(int k = lo; k <= nums.size() - 1; ++k) { swap(nums[lo], nums[k]); perm(lo + 1, nums, res); swap(nums[lo], nums[k]); } } vector<vector<int> > permute(vector<int>& nums) { vector<vector<int> > res; perm(0, nums, res); return res; } }; int main() { Solution s; vector<int> nums = {1, 2, 3}; auto res = s.permute(nums); cout << res.size() << endl; for (int i = 0; i < res.size(); ++i) { vector<int> elems = res[i]; for (int j = 0; j < elems.size(); ++j) { if (j > 0) cout << " "; cout << elems[j]; } cout << endl; } return 0; }
true
39fd1e59a187d920664340787924c4a91a373eff
C++
gemperline/Employee-File-I.O---Vector-Storage
/pay.cpp
UTF-8
4,212
3.46875
3
[]
no_license
// Adam Gemperline // CPSC 301-03 #include <iostream> #include <string> #include <fstream> #include <iomanip> #include <vector> using namespace std; #include "person.cpp" void readData(vector<Person> &P, string fileName, int &numPeople) { string fName; string lName; int empID; string company; float hours; float pay; // create a person object to set read data to class memebers Person p; ifstream inFile; inFile.open("input.txt"); if (inFile.is_open()) { cout << "File opened successfully ..." << endl; cout << "Reading from input file ...\n" << endl; while(inFile >> fName) { inFile >> lName >> empID >> company >> hours >> pay; p.setFirstName(fName); p.setLastName(lName); p.setEmployeeId(empID); p.setCompanyName(company); p.setHoursWorked(hours); p.setPayRate(pay); //push this object to the end of the vector P.push_back(p); // count the number of people in input file numPeople++; } cout << endl; inFile.close(); } else cout << "ERROR: could not open file ..." << endl; } void writeData(vector<Person> &P, string fileName) { ofstream outFile; outFile.open(fileName); cout << "Writing to output file ..." << endl; cout << "Array size is " << P.size() << endl; // loop to write data to output file for(int i = 0; i < P.size(); i++) { outFile << left << setw(8) << P[i].getFirstName() << " " << left << setw(9) << P[i].getLastName() << " " << right << setw(3) << P[i].getEmployeeId() << " " << left << setw(10) << P[i].getCompanyName() << " " << left << setw(4) << fixed << setprecision(2) << P[i].getHoursWorked() << " " << left << setw(4) << P[i].getPayRate() << " " << endl; } outFile.close(); cout << "Output file complete ..." << endl; } void getCompanies(vector<Person> &P, vector<string> &C) { string company; string s; for(int i = 0; i < P.size(); i++) { company = P[i].getCompanyName(); C.push_back(company); } } void printHighestPaid(vector<Person> &P) { double totalPay; int highesPaid; /* while(i < P.size() && j < P.size()) { if((P[i].getPayRate() * P[i].getHoursWorked()) > (P[j].getPayRate() * P[j].getHoursWorked())) { highestPaid = i; j++; } else if((P[i].getPayRate() * P[i].getHoursWorked()) < (P[j].getPayRate() * (P[j].getHoursWorked())) { i = j; highestPaid = j; j++; } else cout << "There are two people with the same total pay." << endl; } totalPay = P[highestPaid].getPayRate() * P[highestPaid].getHoursWorked(); cout << "Total pay: " << totalPay << endl; */ for(int i = 0, j = 1; j <= P.size(); j++) { double totalPay_i = P[i].getPayRate() * P[i].getHoursWorked(); double totalPay_j = P[j].getPayRate() * P[j].getHoursWorked(); if(totalPay_i < totalPay_j) { // move i cursor to j i = j; highestPaid = j; totalPay = totalPay_j; } else if(totalPay_i > totalPay_j) { highestPaid = i; totalPay = totalPay_i; } else cout << "There are two people with the same total pay." << endl; } cout << "Highest Paid: " << P[highesPaid].getFirstName() << " " << P[highestPaid].getLastName() << endl; cout << "Employee ID: " << P[highesPaid].getEmployeeId() << endl; cout << "Employer: " << P[highesPaid].getCompanyName() << endl; cout << "Total Pay: " << totalPay; } int main() { int numPeople = 0; // create a dynamic vector of type Person to store employee data (can grow in size b/c its a vector) vector<Person> employees; // create a dynamic vector to hold string names vector<string> companyNames; // read the data from input file into the array readData(employees, "input.txt", numPeople); cout << "Number of people from read : " << numPeople << endl; // write data to an output file writeData(employees, "output.txt"); // retrieve company names from employees vector and store in company names vector getCompanies(employees, companyNames); // find and print the highest paid employee printHighestPaid(employees); cout << "Exiting ..." << endl; return 0; }
true
846bb54dae01bffb2f1e1e6f3897ec0034bb22ad
C++
beeguy74/cpp_modules
/mod_01/ex01/main.cpp
UTF-8
463
3.203125
3
[]
no_license
#include "Zombie.hpp" #include <iostream> Zombie *zombieHorde(int N, std::string name); void hordeAnnounce(int N, Zombie *arr){ for (int i = 0; i < N; i++){ arr->announce(); } return ; } int main(void) { Zombie *arr; int N; N = 3; arr = zombieHorde(N, "Bill Murray"); hordeAnnounce(N, arr); delete [] arr; N = 5; arr = zombieHorde(N, "Shon"); hordeAnnounce(N, arr); delete [] arr; return 0; }
true
6d233233380ecf06a920395c26d5986c7a54467f
C++
xyuan/cosmopp
/source/test_kd_tree.cpp
UTF-8
9,277
2.90625
3
[]
no_license
#include <utility> #include <algorithm> #include <macros.hpp> #include <random.hpp> #include <timer.hpp> #include <numerics.hpp> #include <kd_tree.hpp> #include <test_kd_tree.hpp> std::string TestKDTree::name() const { return std::string("KD TREE TESTER"); } unsigned int TestKDTree::numberOfSubtests() const { return 9; } void TestKDTree::runSubTest(unsigned int i, double& res, double& expected, std::string& subTestName) { check(i >= 0 && i < numberOfSubtests(), "invalid index " << i); int dim, k, seed; unsigned long nPoints; bool testRes; switch(i) { case 0: runSubTest0(res, expected, subTestName); return; case 1: runSubTest1(res, expected, subTestName); return; case 2: runSubTest2(res, expected, subTestName); return; case 3: runSubTest3(res, expected, subTestName); return; case 4: runSubTest4(res, expected, subTestName); return; case 5: dim = 1; k = 2; nPoints = 1000; seed = 0; subTestName = "1_2_1000"; break; case 6: dim = 3; k = 2; nPoints = 10000; seed = 0; subTestName = "3_2_10000"; break; case 7: dim = 5; k = 10; nPoints = 1000000; seed = 0; subTestName = "5_10_1000000"; break; case 8: dim = 10; k = 20; nPoints = 1000000; seed = 0; subTestName = "10_20_1000000"; break; default: check(false, ""); break; } testRes = test(dim, nPoints, k, seed); expected = 1; res = (testRes ? 1 : 0); } void TestKDTree::runSubTest0(double& res, double& expected, std::string& subTestName) { Math::UniformRealGenerator gen(std::time(0), -1, 1); int size = 1000; int dim = 5; std::vector<std::vector<double> > points(size); for(int i = 0; i < size; ++i) { points[i].resize(dim); for(int j = 0; j < dim; ++j) points[i][j] = gen.generate(); } KDTree kdTree(dim, points); res = 10; expected = kdTree.depth(); subTestName = "depth"; } void TestKDTree::runSubTest1(double& res, double& expected, std::string& subTestName) { std::vector<std::vector<double> > points(3); for(int i = 0; i < 3; ++i) points[i].resize(1, 0); points[1][0] = -1; points[2][0] = 1; KDTree kdTree(1, points); std::vector<double> p(1, 0.2); std::vector<std::vector<double> > neighbors; kdTree.findNearestNeighbors(p, 2, &neighbors); res = 1; expected = 1; subTestName = "simple_1_d"; if(neighbors[0][0] != 0) { output_screen("FAIL! The first neighbor is wrong!"); res = 0; } if(neighbors[1][0] != 1) { output_screen("FAIL! The second neighbor is wrong!"); res = 0; } } void TestKDTree::runSubTest2(double& res, double& expected, std::string& subTestName) { std::vector<std::vector<double> > points(3); for(int i = 0; i < 3; ++i) points[i].resize(1, i); KDTree kdTree(1, points); std::vector<double> p(1, -1); kdTree.insert(p); p[0] = -2; kdTree.insert(p); p[0] = -5; std::vector<std::vector<double> > neighbors; kdTree.findNearestNeighbors(p, 4, &neighbors); res = 1; expected = 1; subTestName = "simple_1_d_insert"; if(neighbors[0][0] != -2) { output_screen("FAIL! The first neighbor is wrong!"); res = 0; } if(neighbors[1][0] != -1) { output_screen("FAIL! The second neighbor is wrong!"); res = 0; } if(neighbors[2][0] != 0) { output_screen("FAIL! The third neighbor is wrong!"); res = 0; } if(neighbors[3][0] != 1) { output_screen("FAIL! The fourth neighbor is wrong!"); res = 0; } } void TestKDTree::runSubTest3(double& res, double& expected, std::string& subTestName) { std::vector<std::vector<double> > points; for(int i = -100; i < 100; ++i) { for(int j = -100; j < 100; ++j) { int n = points.size(); points.resize(n + 1); points[n].resize(2); points[n][0] = double(i); points[n][1] = double(j); } } KDTree kdTree(2, points); std::vector<double> q(2); q[0] = 50.1; q[1] = 20.2; std::vector<unsigned long> indices; std::vector<double> distances; kdTree.findNearestNeighbors(q, 3, &indices, &distances); res = 1; expected = 1; subTestName = "2d_grid"; if(points[indices[0]][0] != 50 || points[indices[0]][1] != 20) { output_screen("FAIL: First neighbor should be (50, 20) but it is (" << points[indices[0]][0] << ", " << points[indices[0]][1] << ")." << std::endl); res = 0; } if(points[indices[1]][0] != 50 || points[indices[1]][1] != 21) { output_screen("FAIL: Second neighbor should be (50, 21) but it is (" << points[indices[1]][0] << ", " << points[indices[1]][1] << ")." << std::endl); res = 0; } if(points[indices[2]][0] != 51 || points[indices[2]][1] != 20) { output_screen("FAIL: Third neighbor should be (51, 20) but it is (" << points[indices[2]][0] << ", " << points[indices[2]][1] << ")." << std::endl); res = 0; } if(!Math::areEqual(distances[0], 0.05, 1e-7)) { output_screen("FAIL: Distance squared to the first neighbor should be " << 0.05 << " but it is " << distances[0] << "." << std::endl); res = 0; } } void TestKDTree::runSubTest4(double& res, double& expected, std::string& subTestName) { std::vector<std::vector<double> > points; for(int i = -50; i < 50; ++i) { for(int j = -50; j < 50; ++j) { for(int k = -50; k < 50; ++k) { int n = points.size(); points.resize(n + 1); points[n].resize(3); points[n][0] = double(i); points[n][1] = double(j); points[n][2] = double(k); } } } res = 1; expected = 1; subTestName = "timer"; Timer t1("KD TREE CONSTRUCTION"); t1.start(); KDTree kdTree(3, points); const unsigned long timeConstr = t1.end(); if(timeConstr > 60000000) { output_screen("FAIL! KD tree construction should take only a few seconds, 1 minute max. It took " << timeConstr / 1000000 << " seconds!"); res = 0; } std::vector<double> q(3, 0); std::vector<std::vector<double> > neighbors; std::vector<double> distances; Timer t2("KD TREE FIND NEAREST NEIGHBORS"); t2.start(); kdTree.findNearestNeighbors(q, 8, &neighbors, &distances); const unsigned long timeSearch = t2.end(); if(timeSearch > 1000) { output_screen("FAIL! nearest neighbor search should take about 100 microseconds, 1000 max. It took " << timeSearch << " microseconds!"); res = 0; } if(neighbors[0][0] != 0 || neighbors[0][1] != 0 || neighbors[0][2] != 0) { output_screen("FAIL: First neighbor should be (0, 0, 0) but it is (" << neighbors[0][0] << ", " << neighbors[0][1] << ", " << neighbors[0][2] << ")." << std::endl); res = 0; } for(int i = 1; i <= 6; ++i) { if(!Math::areEqual(distances[i], 1.0, 1e-7)) { output_screen("FAIL! Neighbor " << i << " should be distance 1 away but it is " << distances[i] << "." << std::endl); res = 0; } } if(!Math::areEqual(distances[7], 2.0, 1e-7)) { output_screen("FAIL! Neighbor 7 should be distance 2 away but it is " << distances[7] << "." << std::endl); res = 0; } } bool TestKDTree::test(int dim, unsigned long nPoints, int k, int seed) { check(dim > 0, ""); check(k > 0, ""); check(nPoints > 0, ""); check(k <= nPoints, ""); if(!seed) seed = std::time(0); Math::UniformRealGenerator gen(seed, -1, 1); std::vector<std::vector<double> > points(nPoints); for(unsigned long i = 0; i < nPoints; ++i) { points[i].resize(dim); for(int j = 0; j < dim; ++j) points[i][j] = gen.generate(); } Timer t0("KD TREE CONSTRUCTION"); t0.start(); KDTree kdTree(dim, points); t0.end(); std::vector<double> p(dim); for(int i = 0; i < dim; ++i) p[i] = gen.generate(); Timer t1("KD TREE FIND NEAREST NEIGHBORS"); t1.start(); std::vector<unsigned long> indices; kdTree.findNearestNeighbors(p, k, &indices); t1.end(); Timer t2("NEAREST NEIGHBORS BY SORT"); std::vector<std::pair<double, unsigned long> > v(nPoints); for(unsigned long i = 0; i < nPoints; ++i) { double d = 0; for(int j = 0; j < dim; ++j) { const double x = p[j] - points[i][j]; d += x * x; v[i].first = d; v[i].second = i; } } t2.start(); std::sort(v.begin(), v.end()); t2.end(); check(indices.size() == k, ""); for(int i = 0; i < k; ++i) { if(indices[i] != v[i].second) return false; } return true; }
true
0cb288aa93d4dc09953665b86f17140e07f9138d
C++
beingbing/pppucpp
/ch-05/drill.cpp
UTF-8
271
2.84375
3
[]
no_license
#include "std_lib_facilities.h" using namespace std; int main () { try { cout<<"Success!\n"; return 0; } catch (exception& e) { cerr<<"error for samar: "<<e.what()<<'\n'; return 1; } catch (...) { cerr<<"Oops samar: unknown exception!\n"; return 2; } }
true
13faf3bb0fe7d753ec1152d0640c194463259efc
C++
MarkusFischer/hpc-class
/exercise_5/task4/driver.cpp
UTF-8
777
2.9375
3
[]
no_license
#include <cstdint> #include <iostream> extern "C" { void gemm_asm_gp( uint32_t const * i_a, uint32_t const * i_b, uint32_t * io_c ); } int main() { uint32_t a[8] = {1, 2, 3, 5, 7, 11, 13, 17}; uint32_t b[4] = {1, 2, 3, 4}; uint32_t c[8] = {1, 2, 3, 4, 5, 6, 7, 8}; //NOTE more unit tests would be better but ... better than nothing uint32_t c_res[8] = {16, 26, 32, 43, 36, 56, 68, 91}; gemm_asm_gp(a, b, c); std::cout << "Comparing results... " << std::endl; for (int i = 0; i < 8; ++i) { if (c[i] != c_res[i]) { std::cout << "Found mismatch at index " << i << " c:" << c[i] << " != c_res:" << c_res[i] << std::endl; } } return 0; }
true
2cd997df23ed305925373faa06a10725eedcb203
C++
alexElArte/Crypto_2.0
/Crypto/examples/example/example.ino
UTF-8
4,879
2.9375
3
[]
no_license
#include <new_crypto.h> // You can change the value to have a powerful key // I usually use 32 or 64 const uint8_t length_array = 16; // The max value depends on the context const uint8_t max_value = 32; Crypto cryp(max_value, length_array); uint8_t keyA[max_value]; uint8_t keyM[length_array]; uint8_t msg[length_array] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; void setup() { Serial.begin(115200); Serial.println("Example to show you the functions\n"); cryp.init(analogRead(A0)); /***********************KEYM***********************/ // Create a key cryp.createMoveKey(keyM); Serial.println("Move function:"); Serial.print("keyM: "); for (uint8_t index = 0; index < length_array; index++) { if (keyM[index] < 0x10) Serial.write('0'); Serial.print(keyM[index], HEX); Serial.write(' '); } Serial.println(); Serial.print("nocode: "); for (uint8_t index = 0; index < length_array; index++) { if (msg[index] < 0x10) Serial.write('0'); Serial.print(msg[index], HEX); Serial.write(' '); } Serial.println(); // Encode cryp.encodeMove(msg, keyM); Serial.print("encode: "); for (uint8_t index = 0; index < length_array; index++) { if (msg[index] < 0x10) Serial.write('0'); Serial.print(msg[index], HEX); Serial.write(' '); } Serial.println(); // Decode cryp.decodeMove(msg, keyM); Serial.print("decode: "); for (uint8_t index = 0; index < length_array; index++) { if (msg[index] < 0x10) Serial.write('0'); Serial.print(msg[index], HEX); Serial.write(' '); } Serial.println('\n'); /***********************KEYC***********************/ // Create a key cryp.createArrayKey(keyA); Serial.println("Value change function:"); Serial.print("keyA: "); for (uint8_t index = 0; index < length_array; index++) { if (keyA[index] < 0x10) Serial.write('0'); Serial.print(keyA[index], HEX); Serial.write(' '); } Serial.println(); Serial.print("nocode: "); for (uint8_t index = 0; index < length_array; index++) { if (msg[index] < 0x10) Serial.write('0'); Serial.print(msg[index], HEX); Serial.write(' '); } Serial.println(); // Encode cryp.encodeArray(msg, keyA); Serial.print("encode: "); for (uint8_t index = 0; index < length_array; index++) { if (msg[index] < 0x10) Serial.write('0'); Serial.print(msg[index], HEX); Serial.write(' '); } Serial.println(); // Decode cryp.decodeArray(msg, keyA); Serial.print("decode: "); for (uint8_t index = 0; index < length_array; index++) { if (msg[index] < 0x10) Serial.write('0'); Serial.print(msg[index], HEX); Serial.print(' '); } Serial.println("\nIf you look at the first byte, the value is different(it's normal)"); Serial.println("because 0 is a null value and change by a random value."); Serial.println("So in this example the number are encoded from 1 to maxValue (here 16) include."); Serial.println("So be carefull !!!\n"); /*********************NOKEY***********************/ Serial.println("This function doesn't need any key"); Serial.println("Mask (auto):"); Serial.print("nocode: "); for (uint8_t index = 0; index < length_array; index++) { if (msg[index] < 0x10) Serial.write('0'); Serial.print(msg[index], HEX); Serial.write(' '); } Serial.println(); // Encode cryp.encodeBit(msg); Serial.print("encode: "); for (uint8_t index = 0; index < length_array; index++) { if (msg[index] < 0x10) Serial.write('0'); Serial.print(msg[index], HEX); Serial.write(' '); } Serial.println(); // Decode cryp.decodeBit(msg); Serial.print("decode: "); for (uint8_t index = 0; index < length_array; index++) { if (msg[index] < 0x10) Serial.write('0'); Serial.print(msg[index], HEX); Serial.write(' '); } Serial.println('\n'); /***************************************/ Serial.println("Mask (manual) 0x37:"); Serial.print("nocode: "); for (uint8_t index = 0; index < length_array; index++) { if (msg[index] < 0x10) Serial.write('0'); Serial.print(msg[index], HEX); Serial.write(' '); } Serial.println(); // Encode cryp.mask(msg, 0x37); Serial.print("first time: "); for (uint8_t index = 0; index < length_array; index++) { if (msg[index] < 0x10) Serial.write('0'); Serial.print(msg[index], HEX); Serial.write(' '); } Serial.println(); // Decode cryp.mask(msg, 0x37); Serial.print("second time: "); for (uint8_t index = 0; index < length_array; index++) { if (msg[index] < 0x10) Serial.write('0'); Serial.print(msg[index], HEX); Serial.write(' '); } Serial.println('\n'); } void loop() { // }
true
ec3be118024583f878bfadea216de8f0764505d7
C++
VasilescuAndreea/POO-Tema2
/Abonat.cpp
UTF-8
264
2.640625
3
[]
no_license
#include "Abonat.h" Abonat :: Abonat() = default; Abonat :: Abonat(std::string nr) { this->nr_telefon = nr; } void Abonat :: set_nr_telefon(std::string newNr){ this->nr_telefon = newNr; } std::string Abonat :: get_nr_telefon(){ return nr_telefon; }
true
86c4e358b77e29a1cb56b4e184b586661d634eea
C++
jonasla/icpc
/simulacros/TC2017 - Prueba 5/i.cpp
UTF-8
2,866
2.703125
3
[]
no_license
#include <iostream> #include <vector> #include <set> #include <queue> using namespace std; typedef long long tint; typedef pair<tint, tint> ii; typedef vector<ii> vii; typedef vector<tint> vi; typedef set<tint> si; #define forsn(i,s,n) for(int i=(tint)s; i<(tint)n; i++) #define forn(i,n) forsn(i,0,n) const tint INFINITO = 1e15; void dijkstra (tint comienzo, vector<vector<pair<tint,tint> > > &ladj, vector<tint> &distance, vector<set<tint> > &parent) { priority_queue <pair<tint,tint> > q; // {-peso,indice} tint n = distance.size(); forn(i,n) distance[i] = (i != comienzo)*INFINITO; vector<tint> procesado (n,0); q.push({0,comienzo}); while (!q.empty()) { tint actual = q.top().second; q.pop(); //~ cout << "sacoo " << actual << endl; if (!procesado[actual]) { procesado[actual] = 1; for (auto vecino : ladj[actual]) { //~ cout << "vecinoo " << vecino.first << endl; if (distance[actual] - vecino.first < distance[vecino.second]) { distance[vecino.second] = distance[actual] - vecino.first; q.push({-distance[vecino.second], vecino.second}); parent[vecino.second] = {actual}; } else if (distance[actual] - vecino.first == distance[vecino.second]) parent[vecino.second].insert(actual); } } } } int main() { ios_base::sync_with_stdio(0); cin.tie(NULL); tint N, M; while(cin >> N >> M && N != 0) { tint S, E; cin >> S >> E; vector<vii> graf(N, vii()); vector<vi> matGraf(N, vi(N, INFINITO)); forn(i,M) { tint u, v, w; cin >> u >> v >> w; graf[u].push_back({-w, v}); matGraf[u][v] = w; } //~ continue; // vi dist(N, 0); vector<si> parent(N, si()); dijkstra(S, graf, dist, parent); //~ forn(i,N) { //~ cout << "parent " << i << endl; //~ for (auto p : parent[i]) cout << p << endl; //~ cout << endl; //~ } //~ continue; // vi visit(N, 0); queue<tint> Q; Q.push(E); while(!Q.empty()) { tint act = Q.front(); Q.pop(); //~ cout << "mirando " << act << endl; if (visit[act]) continue; visit[act] = true; forn(i,N) { if (matGraf[i][act] < INFINITO) { //~ cout << "con " << i << endl; if (parent[act].find(i) != parent[act].end()) { Q.push(i); //~ cout << "agrego ars " << i << " " << act << " " << matGraf[i][act] << endl; matGraf[i][act] = INFINITO; } } } } vector<vii> nuevoGraf(N, vii()); forn(i,N) { forn(j,N) { if (matGraf[i][j] < INFINITO) { //~ if (parent[j].find(i) == parent[j].end()) { //~ cout << "agrego ars " << i << " " << j << " " << matGraf[i][j] << endl; nuevoGraf[i].push_back({-matGraf[i][j], j}); } } } // dist = vi(N, 0); parent = vector<si>(N, si()); dijkstra(S, nuevoGraf, dist, parent); if (dist[E] == INFINITO) cout << -1; else cout << dist[E]; cout << "\n"; } return 0; }
true
f10f4739b96bfa2ad739b8eb4aff53e918e7c4bf
C++
calm11/TP2
/datagrump/debug_printf.hh
UTF-8
1,996
2.96875
3
[]
no_license
#ifndef DEBUG_PRINTF_HH #define DEBUG_PRINTF_HH #include <cstdarg> // Debug logging definitions. const int ERROR = 0; const int WARN = 1; const int INFO = 2; const int VERBOSE = 3; const int EXTRA_VERBOSE = 4; //const int DEBUG_LEVEL = 0; // 0 means only output upto Error Level. const int DEBUG_LEVEL = 2; // 2 means only output upto Info Level. // TODO(): Remember to disable this after development completed so that // no debug output is printed for submission. static const bool LOGGING_ENABLED = true; //static const bool LOGGING_ENABLED = false; inline void debug_printf(int level, const char* format_template, ...) { if (level < 0) { return; } bool should_log = level <= DEBUG_LEVEL; if (!should_log || !LOGGING_ENABLED) { return; } // We color our debug prefix messages. // See https://en.wikipedia.org/wiki/ANSI_escape_code#Colors for ANSI color codes. if (level == ERROR) { fprintf(stderr, "\x1b[31m"); // Begin Red Color fprintf(stderr, "[ERROR] "); fprintf(stderr, "\x1b[0m"); // End Color } else if (level == WARN) { fprintf(stderr, "\x1b[33m"); // Begin Yellow Color fprintf(stderr, "[WARNING] "); fprintf(stderr, "\x1b[0m"); // End Color } else if (level == INFO) { fprintf(stderr, "\x1b[32m"); // Begin Green Color fprintf(stderr, "[LOG INFO] "); fprintf(stderr, "\x1b[0m"); // End Color } else if (level == VERBOSE) { fprintf(stderr, "\x1b[34m"); // Begin Blue Color fprintf(stderr, "[VERBOSE] "); fprintf(stderr, "\x1b[0m"); // End Color } else if (level == EXTRA_VERBOSE) { fprintf(stderr, "\x1b[35m"); // Begin Magneta Color fprintf(stderr, "[EXTRA VERBOSE] "); fprintf(stderr, "\x1b[0m"); // End Color } va_list argument_list; va_start(argument_list, format_template); vfprintf(stderr, format_template, argument_list); va_end(argument_list); // Output a new line so that boundary between messages is clear. fprintf(stderr, "\n"); return; } #endif
true
9c59596fd6ec79e04212da18b1e1ea8c00fa0299
C++
debapratimsaha/wiiglove-codebase
/stretch_grid_with_processing/stretch_grid_with_processing/stretch_grid_with_processing.ino
UTF-8
2,335
3.3125
3
[]
no_license
// two variables for each input pin to read and store the values int inPin0 = 0; //right int inPin1 = 1; //down int inPin2 = 2; //left int inPin3 = 3; //up int meanPos[4]; // an identifier for each value int id_1 = 'A'; int id_2 = 'B'; int id_3 = 'C'; int id_4 = 'D'; void setup() { // declaration of pins modes pinMode(inPin0, INPUT); pinMode(inPin1, INPUT); pinMode(inPin2, INPUT); pinMode(inPin3, INPUT); // set up the mean position meanPos[0]= analogRead(inPin0); meanPos[1]= analogRead(inPin1); meanPos[2]= analogRead(inPin2); meanPos[3]= analogRead(inPin3); // begin sending over serial port Serial.begin(9600); } void loop() { int i,val_read[4][2],relative_movement[4],abs_movement[4]; // read the values of the analog pins and store them in variables val_read[0][0] = analogRead(inPin0); val_read[1][0] = analogRead(inPin1); val_read[2][0] = analogRead(inPin2); val_read[3][0] = analogRead(inPin3); // read the 2nd set of values of the analog pins and store them in variables val_read[0][1] = analogRead(inPin0); val_read[1][1] = analogRead(inPin1); val_read[2][1] = analogRead(inPin2); val_read[3][1] = analogRead(inPin3); for(i=0;i<4;i++) relative_movement[i] = val_read[i][1]-val_read[i][0]; for(i=0;i<4;i++) abs_movement[i] = val_read[i][1] - meanPos[i]; // print out the variables preceeded by their IDs and followed by a carriage return if (abs(relative_movement[0]) > 2 || abs(abs_movement[0])>20) { Serial.write(id_1); Serial.write(constrain(abs_movement[0],0,255)/*map(abs_movement[0],1900,2300,0,255)*/); Serial.write(10);} if (abs(relative_movement[1]) > 2 || abs(abs_movement[1])>20) { Serial.write(id_2); Serial.write(constrain(abs_movement[1],0,255)/*map(abs_movement[1],1900,2300,0,255)*/); Serial.write(10);} if (abs(relative_movement[2]) > 2 || abs(abs_movement[2])>20) { Serial.write(id_3); Serial.write(constrain(abs_movement[2],0,255)/*map(abs_movement[2],1900,2300,0,255)*/); Serial.write(10);} if (abs(relative_movement[3]) > 2 || abs(abs_movement[3])>20) { Serial.write(id_4); Serial.write(constrain(abs_movement[3],0,255)/*map(abs_movement[3],1900,2300,0,255)*/); Serial.write(10);} }
true
ac03959c44e19fcb5277df8f84dc0ae4e2b394fd
C++
evlinsky/cpp
/ta/huletski/HSE_S20/02-200123/03-gtest-extra.cpp
UTF-8
725
2.53125
3
[]
no_license
#include <gtest/gtest.h> #include <vector> #include <cassert> #include <sstream> void always_die() { assert(0); } // checks if process dies TEST(MyDeathTest, TestAlwaysDie) { std::vector<int> vi; ASSERT_DEATH(always_die(), ".*? Assertion .*? failed"); } TEST(MyDeathTest, ExceptionThrow) { std::vector<int> vi; ASSERT_DEATH(vi.at(0), ""); } TEST(StringStreamTest, ExceptionOnFailThrow) { std::stringstream ss(""); ss.exceptions(ss.exceptions() | ss.failbit); char c; ASSERT_THROW(ss >> c, std::iostream::failure); ss.exceptions(ss.exceptions() & ~ss.failbit); ASSERT_NO_THROW(ss >> c); } // g++ 03-gtest-extra.cpp -Wall -lgtest -lgtest_main -lpthread && ./a.out --gtest_death_test_style=threadsafe
true
c7d4964cf7f6c5245650d2dce17e0d6162dab279
C++
loganjensen/Harry-Potter-Command-line-Game
/Game Files/ron.hpp
UTF-8
895
3.015625
3
[]
no_license
/************************************************* Author: Logan Jensen Assignment: Final Project Date: 11 JUN 2019 Description: This is the ron.hpp file. It contains the Ron class definition. *************************************************/ #include "space.hpp" #ifndef RON_HPP #define RON_HPP /************************************************* Ron Class This class inherits from the Space class. This class represents Ron Weasley on the Hogwarts Express. It contains a bool to track if Ron is sleeping in the game, as well as a constructor, and the look, talk, and castSpell functions to interact with a Ron object. *************************************************/ class Ron : public Space { private: bool asleep; public: Ron(); void look(); void talk(); void castSpell(); void setAsleep(bool); bool getAsleep(); }; #endif /* RON_HPP */
true
a025846b6d7875c7c7406a82a328b82323b5333e
C++
quangtruong4297/LTM_TUNGBT_20172
/Sources/Server/Client/Client.cpp
UTF-8
4,837
2.5625
3
[]
no_license
#define _WINSOCK_DEPRECATED_NO_WARNINGS #include<stdio.h> #include<conio.h> #include<stdlib.h> #include<string.h> #include<winsock2.h> #include<WS2tcpip.h> #pragma comment(lib,"Ws2_32.lib") #define BUFF_SIZE 2048 #define USER 1 #define PASS 2 #define LOUT 3 #define ADDP 4 #define LIST 5 #define LIFR 6 #define TAGF 7 #define NOTI 8 #define UNKN 9 int sessionStatus; //0-UNIDENT, 1-UNAUTH, 2-AUTH //construct message struct message { int msgType; int length; char data[BUFF_SIZE]; }msg; //wrapper function send() int Send(SOCKET s, char *buff, int size, int flag) { int n; n = send(s, buff, size, flag); if (n == SOCKET_ERROR) { printf("Send message error: %d\n", WSAGetLastError()); } return n; } //wrapper function recv() int Receive(SOCKET s, char *buff, int size, int flag) { int n; n = recv(s, buff, size, flag); if (n == SOCKET_ERROR) { printf("Receive message error: %d\n", WSAGetLastError()); } return n; } // type data // return 1 if OK, 0 if have error int enterData() { printf("type: "); char word[BUFF_SIZE]; gets_s(word); if (word[0] == '\n') { return 0; } static char *data; strtok_s(word, " ",&data); static char *msgType = word; if (strcmp(msgType, "user") == 0) msg.msgType = USER; else if (strcmp(msgType, "pass") == 0) msg.msgType = PASS; else if (strcmp(msgType, "lout") == 0) msg.msgType = LOUT; else msg.msgType = UNKN; strcpy_s(msg.data, data); msg.length = strlen(data); return 1; //static char word[25]; //if (sessionStatus == 0) { //enter userID // printf("enter userID: "); // gets_s(word, 25); // strcpy_s(msg.data, word); // msg.msgType = USER; // //return 1; //} //else if (sessionStatus == 1) { //enter pass // printf("enter passWord: "); // gets_s(word, 25); // strcpy_s(msg.data, word); // msg.msgType = PASS; // //return 1; //} //else if (sessionStatus == 2) { //logout // printf("type \"yes\" to logout: "); // gets_s(word, 25); // _strlwr_s(word); // strcpy_s(msg.data, word); // msg.msgType = LOUT; //} //msg.length = strlen(word); } //check if have error or not //return 1 if have error, 0 if OK int isError(char *buff) { if (buff[0] == '+') { return 0; } else if (buff[0] == '-') { return 1; } } //show error details void errorDetail(char *buff) { if (strcmp(buff, "-10") == 0) { printf("wrong sequence\n"); } else if (strcmp(buff, "-11") == 0) { printf("user is blocked\n"); } else if (strcmp(buff, "-21") == 0) { printf("user is not avail\n"); } else if (strcmp(buff, "-31") == 0) { printf("user was already connected\n"); } else if (strcmp(buff, "-41") == 0) { printf("client connected before\n"); } else if (strcmp(buff, "-12") == 0) { printf("password is wrong\n"); } else if (strcmp(buff, "-22") == 0) { printf("enter password fail more than 3 times, user will be blocked\n"); } else if (strcmp(buff, "-13") == 0) { printf("type again\n"); } else if (strcmp(buff, "-14") == 0) { printf("message type can not identified\n"); } else { printf("Error\n"); } } void changeStatusSession(int num) { sessionStatus = num % 3; } int main(int argc, char **argv) { unsigned short port_number; /* Port number to use */ //step 1: Initiate Winsock WSADATA wsaData; WORD wVersion = MAKEWORD(2, 2); if (WSAStartup(wVersion, &wsaData)) { printf("Version is not supported\n"); } //step 2: Construct socket SOCKET client; client = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); // (optional) Set time-out for receiving int tv = 10000; //Time-out interval: 10000ms setsockopt(client, SOL_SOCKET, SO_RCVTIMEO, (const char*)(&tv), sizeof(int)); //step 3: Specify server address port_number = atoi(argv[2]); sockaddr_in serverAddr; serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(port_number); serverAddr.sin_addr.s_addr = inet_addr(argv[1]); //step 4: Request to connect server if (connect(client, (sockaddr *)&serverAddr, sizeof(serverAddr))) { printf("Error! Cannot connect server. %d\n", WSAGetLastError()); _getch(); return 0; } printf("Connected server! \n"); //connect to server int ret; char buff[BUFF_SIZE]; char *data; //intit msg_type sessionStatus = 0; //loop while (true) { data = (char*)malloc(sizeof(message)); enterData(); //convert data type memcpy(data, &msg, sizeof(message)); printf("message\t %d %d %s\n", msg.msgType, msg.length, msg.data); //send messagee ret = Send(client, data, sizeof(message), 0); if (ret < 0) { return 0; } //release memory free(data); //printf("buff %s ", buff); //receive message ret = Receive(client, buff, BUFF_SIZE, 0); if (ret < 0) { return 0; } printf("buff %s ", buff); buff[0] = '\0'; } //step 6: Close socket closesocket(client); //step 7: Terminate Winsock WSACleanup(); return 0; }
true
5f1bdd6dc706196e6aff744ce50f36c27ead351a
C++
Tangjiahui26/CrackingCode
/Hard/ContinuousMedian/main.cpp
UTF-8
1,825
4.0625
4
[]
no_license
#include <iostream> #include <queue> using namespace std; // Given that integers are being read from a data stream, // Find median of all the elements read so far start from the first // integer till the last integer. // solution: Using max heap + min heap to store the elements // of higher half and lower half. void printMedians(double arr[], int n){ // max heap to store the smaller half elements priority_queue<double> s; // min heap to store the greater half elements priority_queue<double, vector<double>, greater<double>> g; double med = arr[0]; s.push(arr[0]); cout << med << endl; for (int i = 1; i < n; i++){ double x = arr[i]; // if left side heap has more element if (s.size() > g.size()){ if (x < med){ // pop the top of max heap and insert into min heap g.push(s.top()); s.pop(); // insert the new to max heap s.push(x); } else { g.push(x); } med = (s.top() + g.top()) / 2.0; } // both are balanced else if (s.size() == g.size()){ if (x < med){ s.push(x); med = (double)s.top(); } else { g.push(x); med = (double)g.top(); } } // right side heap has more elements else { if (x > med){ s.push(g.top()); g.pop(); g.push(x); } else { s.push(x); } med = (s.top() + g.top()) / 2.0; } cout << med << endl; } } int main() { double arr[] = {5, 15, 10, 20, 3}; int n = sizeof(arr)/sizeof(arr[0]); printMedians(arr, n); return 0; }
true
7d44f6452d0a769189d30bb5f2695cbadfd26d72
C++
JetAr/ZNginx
/ZGame/DX11/directx-sdk-samples/OIT11/OIT.h
UTF-8
4,524
2.796875
3
[ "MIT" ]
permissive
//----------------------------------------------------------------------------- // File: OIT.h // // Desc: Description for a class that handles Order Independent Transparency. // The algorithm uses a series of passes: // // 1. Determine the number of transparent fragments in each pixel by drawing // each of the transparent primitives into an overdraw accumlation buffer // // 2. Create a prefix sum for each pixel location. This holds the sum of all // the fragments in each of the preceding pixels. The last pixel will hold // a count of all fragments in the scene. // // 3. Render the fragments to a deep frame buffer that holds both depth and color // for each of the fragments. The prefix sum buffer is used to determine // the placement of each fragment in the deep buffer. // // 4. Sort the fragments and render to the final frame buffer. The prefix // sum is used to locate fragments in the deep frame buffer. // // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #pragma once #include "Scene.h" class OIT { public: OIT(); HRESULT CALLBACK OnD3D11CreateDevice( ID3D11Device* pDevice ); HRESULT OnD3D11ResizedSwapChain( const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, ID3D11Device* pDevice ); void OnD3D11ReleasingSwapChain(); void OnD3D11DestroyDevice(); void Render( ID3D11DeviceContext* pD3DContext, ID3D11Device* pDevice, CScene* pScene, DirectX::CXMMATRIX mWVP, ID3D11RenderTargetView* pRTV, ID3D11DepthStencilView* pDSV); private: void CreateFragmentCount( ID3D11DeviceContext* pD3DContext, CScene* pScene, DirectX::CXMMATRIX mWVP, ID3D11RenderTargetView* pRTV, ID3D11DepthStencilView* pDSV ); void CreatePrefixSum( ID3D11DeviceContext* pD3DContext ); void FillDeepBuffer( ID3D11DeviceContext* pD3DContext, ID3D11RenderTargetView* pRTV, ID3D11DepthStencilView* pDSV, CScene* pScene, DirectX::CXMMATRIX mWVP ); void SortAndRenderFragments( ID3D11DeviceContext* pD3DContext, ID3D11Device* pDevice, ID3D11RenderTargetView* pRTV ); protected: struct CS_CB { UINT nFrameWidth; UINT nFrameHeight; UINT nPassSize; UINT nReserved; }; struct PS_CB { UINT nFrameWidth; UINT nFrameHeight; UINT nReserved0; UINT nReserved1; }; UINT m_nFrameHeight; UINT m_nFrameWidth; // Shaders ID3D11PixelShader* m_pFragmentCountPS; // Counts the number of fragments in each pixel ID3D11ComputeShader* m_pCreatePrefixSum_Pass0_CS; // Creates the prefix sum in two passes, converting the ID3D11ComputeShader* m_pCreatePrefixSum_Pass1_CS; // two dimensional frame buffer to a 1D prefix sum ID3D11PixelShader* m_pFillDeepBufferPS; // Fills the deep frame buffer with depth and color values ID3D11ComputeShader* m_pSortAndRenderCS; // Sorts and renders the fragments to the final frame buffer // States ID3D11DepthStencilState* m_pDepthStencilState; // Constant Buffers ID3D11Buffer* m_pCS_CB; // Compute shader constant buffer ID3D11Buffer* m_pPS_CB; // Pixel shader constant buffer ID3D11Texture2D* m_pFragmentCountBuffer; // Keeps a count of the number of fragments rendered to each pixel ID3D11Buffer* m_pPrefixSum; // Count of total fragments in the frame buffer preceding each pixel ID3D11Buffer* m_pDeepBuffer; // Buffer that holds the depth of each fragment ID3D11Buffer* m_pDeepBufferColor; // Buffer that holds the color of each fragment // Debug Buffers used to copy resources to main memory to view more easily ID3D11Buffer* m_pPrefixSumDebug; ID3D11Buffer* m_pDeepBufferDebug; ID3D11Buffer* m_pDeepBufferColorDebug; // Unordered Access views of the buffers ID3D11UnorderedAccessView* m_pFragmentCountUAV; ID3D11UnorderedAccessView* m_pPrefixSumUAV; ID3D11UnorderedAccessView* m_pDeepBufferUAV; ID3D11UnorderedAccessView* m_pDeepBufferColorUAV; ID3D11UnorderedAccessView* m_pDeepBufferColorUAV_UINT; // Used to veiw the color buffer as a single UINT instead of 4 bytes // Shader Resource Views ID3D11ShaderResourceView* m_pFragmentCountRV; };
true
b96d310f82aac792c38a69237f7b44fed03973d2
C++
caokeai/NowCoderOffer66
/13.奇数位于偶数前面.cpp
UTF-8
717
3.84375
4
[]
no_license
/* 题目: 输入一个整数数组,实现一个函数来调整该数组中数字的顺序, 使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。 解析: 同样使用辅助存储空间来实现。 */ class Solution { public: void reOrderArray(vector<int> &array) { vector<int> res; for(int i=0;i<array.size();i++) if(array[i]%2!=0) res.push_back(array[i]); for(int i=0;i<array.size();i++) if(array[i]%2==0) res.push_back(array[i]); for(int i=0;i<array.size();i++) array[i]=res[i]; } };
true
2dfa7108550970bfa861ccabecb8e639b96dcda0
C++
Arelaxe/practicasED
/Práctica_5/letras/src/cantidad_letras.cpp
UTF-8
1,608
3.171875
3
[]
no_license
#include <iostream> #include <fstream> #include <cctype> #include "Diccionario.h" #include "Bolsa_Letras.h" using namespace std; int main (int argc, char *argv[]){ if(argc!=4){ cerr << "Número de argumentos incorrecto." << endl; cerr << "Uso: <" << argv[0] << "> <fichero diccionario> <fichero letras> <fichero salida>" << endl; exit(1); } ifstream f1(argv[1]), f2(argv[2]); //Abrimos el fichero diccionario y el fichero letras if(!f1){ cout << "No puedo abrir el fichero " << argv[1] << endl; exit(2); } if(!f2){ cout << "No puedo abrir el fichero " << argv[2] << endl; exit(3); } Diccionario d; Conjunto_Letras c; f1 >> d; f2 >> c; ofstream f3(argv[3]); //Abrimos el fichero de salida if(!f3){ cout << "No puedo abrir el fichero " << argv[3] << endl; exit(4); } f3 << "#Letra FAbs Frel" << endl; //Imprime la cabecera del fichero Diccionario::iterator it_diccionario; Conjunto_Letras::iterator it_conjunto; for (it_conjunto=c.begin(); it_conjunto!=c.end(); it_conjunto++){ //Busca cuántas veces aparece cada letra int f_absoluta = 0; int total_letras = 0; for (it_diccionario=d.begin(); it_diccionario!=d.end(); it_diccionario++){ for (int i=0; i<(*it_diccionario).size(); i++){ total_letras++; if(toupper((*it_diccionario)[i])==(*it_conjunto).GetCaracter()) f_absoluta++; } } double f_relativa = ((double)f_absoluta/(double)total_letras) * 100; //Calcula la frecuencia relativa de la letra f3 << (*it_conjunto).GetCaracter() << "\t" << f_absoluta << "\t" << f_relativa << endl; //Imprime los resultados } return(0); }
true
5d4a310f5fff960fb7e69176b75aefc684e9ffa7
C++
hunubul/tpg
/src/logging.cpp
UTF-8
2,773
2.828125
3
[ "Apache-2.0" ]
permissive
#include <string> #include <fstream> #include <time.h> #include "logging.h" #include "globals.h" #include "openGL/initOpenGL.h" using namespace globals; bool loggedSomething = false; // Get current date/time, format is YYYY-MM-DD.HH:mm:ss const std::string getCurrentDateTime() { time_t now = time(0); struct tm tstruct; char buf[80]; localtime_s(&tstruct, &now); // Visit http://en.cppreference.com/w/cpp/chrono/c/strftime // for more information about date/time format strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct); return buf; } void FatalError(const std::string& ErrorText) { loggedSomething = true; std::ofstream out(ERR_LOG_PATH.c_str(),std::ofstream::out|std::ofstream::app); std::string PrintText="["; PrintText.append(getCurrentDateTime()); PrintText.append("] A fatal error occured! - "); PrintText.append(ErrorText); PrintText.append("\nExitting..."); out << PrintText << std::endl; out.close(); Exitting(); #ifdef DEBUG std::cout << PrintText << std::endl; std::cout << "Press enter to exit..."; std::cin.ignore(); // Wait for keypress #endif } void ErrorOccured(const std::string& ErrorText) { loggedSomething = true; std::ofstream out(ERR_LOG_PATH.c_str(),std::ofstream::out|std::ofstream::app); std::string PrintText="["; PrintText.append(getCurrentDateTime()); PrintText.append("] An error occured! - "); PrintText.append(ErrorText); out << PrintText << std::endl; out.close(); #ifdef DEBUG std::cout << PrintText << std::endl; #endif } void DebugLog(const std::string& DebugText) { #ifdef DEBUG std::string PrintText = "["; PrintText.append(getCurrentDateTime()); PrintText.append("] DEBUG INFO - "); PrintText.append(DebugText); std::cout << PrintText << std::endl; #endif } void Exitting() { if (loggedSomething) { std::ofstream out(ERR_LOG_PATH.c_str(), std::ofstream::out | std::ofstream::app); std::string PrintText = "*******************************************************************"; out << PrintText << std::endl; out.close(); } // Properly de-allocate all resources once they've outlived their purpose if (initialisedGL) { glDeleteFramebuffers(1, &frameBuffer); glDeleteVertexArrays(1, &VAO_FrameBuff); glDeleteBuffers(1, &VBO_FrameBuff); glDeleteVertexArrays(1, &VAOfront); glDeleteBuffers(1, &VBOfront); glDeleteVertexArrays(1, &VAOleft); glDeleteBuffers(1, &VBOleft); glDeleteVertexArrays(1, &VAOright); glDeleteBuffers(1, &VBOright); glDeleteVertexArrays(1, &VAOfloor); glDeleteBuffers(1, &VBOfloor); glDeleteVertexArrays(1, &VAOceiling); glDeleteBuffers(1, &VBOceiling); } //Destroy window SDL_DestroyWindow(window); window = NULL; //Quit SDL subsystems SDL_Quit(); }
true
f83461714e09ae7adc2342cc89b3b32280e5cb79
C++
geekypandey/cc_solutions
/cses/introductory_problems/palindrome_reorder.cpp
UTF-8
1,420
2.71875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; using ll = long long; using vi = vector<int>; using vl = vector<ll>; using pi = pair<int, int>; using pl = pair<ll, ll>; #define all(x) begin(x), end(x) #define rall(x) rbegin(x), rend(x) #define PB push_back #define MP make_pair #define F first #define S second #define endl '\n' #define forn(i, n) for(ll i = 0; i < n; i++) #define readi(e) int e; cin >> e #define readl(e) ll e; cin >> e #define reads(e) string e; cin >> e #define T int tt; cin >> tt; while(tt--) template<typename U> void print(U arr) { for(auto element: arr) { cout << element << " "; } cout << endl; } // read and write into files, rather than standard i/o void setup(string s) { freopen((s+".in").c_str(), "r", stdin); freopen((s+".out").c_str(), "w", stdout); } int main(void) { ios::sync_with_stdio(false); cin.tie(0); int ch[26] = {0}; string s; cin >> s; for(auto& c: s) { ch[c-'A']++; } vector<char> ans; int odd_count = 0; int odd_pos; forn(i, 26) { if(ch[i]%2 != 0) { odd_count++; odd_pos = i; continue; } for(int j = 0; j < ch[i]/2; j++) { ans.PB('A'+i); } } if(odd_count > 1) cout << "NO SOLUTION" << endl; else { for(auto& c: ans) cout << c; if(odd_count == 1) { for(int i = 0; i < ch[odd_pos]; i++) cout << (char)('A' + odd_pos); } for(int i = ans.size()-1; i >=0; i--) cout << ans[i]; cout << endl; } return 0; }
true
71c6215e0802b260aec34650f8f7a0e529a71a7f
C++
RalfHendriks/Machiavelli
/Machiavelli/Condottiere.h
UTF-8
300
2.65625
3
[]
no_license
#pragma once #include "Character.h" class Condottiere : public CharacterCard { public: Condottiere(int id,CharacterType type); Condottiere(); ~Condottiere(); void Execute(GameController & game_controller) override; private: void PrintCharacterCards(GameController & game_controller) const; };
true
8e0bd514fc3cdf27a594959d6f3b95e48a6e23bd
C++
zanariah8/MyRepo
/C++ (Object Oriented Programming)/Workshops/AbstractBaseClasses-Workshop/AbstractBaseClasses-Workshop/w5.cpp
UTF-8
664
3.078125
3
[]
no_license
#ifdef _MSC_VER #define _CRT_SECURE_NO_WARNINGS #endif #include <iostream> using namespace std; #include "Polygon.h" int main() { // added some nice welcoming to the program cout << "\n Workshop#5 OOP344A(Winter2014)\n" << endl; cout << "------------OUTPUT------------" << endl; Polygon rect("Rectangle", 4); rect(0) = Point(1, 1); rect(1) = Point(2, 1); rect(2) = Point(2, 4); rect(3) = Point(1, 4); cout << ' ' << rect << endl; // added a nice footer to the program cout << "------------------------------" << endl; cout << endl; cout << ' ' << (char)0xA9 << "Jorgedeveloper.com, 2014\n" << endl; cout << endl; system("pause"); return 0; }
true
019cf35dc39bd4ecb7ac8db88fd88fc4270e056e
C++
1214wuai/public_code1
/C++/10_27类和对象/test1.cpp
UTF-8
449
3.46875
3
[]
no_license
#include<iostream> using namespace std; class Date { public: //Date(int year,int month, int day) //{ // _year = year; // _month = month; // _day = day; //} Date(int year,int month,int day) :_year(year) ,_month(month) ,_day(day) {} void Print() { cout<<_year<<"-"<<_month<<"-"<<_day<<endl; } private: int _year; int _month; int _day; }; int main() { Date d1(2018,8,29); d1.Print(); return 0; }
true
ecd771b6465f9aab0726c9cb3df8bb3d0b4d3e53
C++
bananaXu/algorithm
/算法题解/素数伴侣(二分图最大匹配).cpp
GB18030
2,586
2.96875
3
[]
no_license
#include <iostream> #include <algorithm> #include <cstdio> #include <cstring> #include <cstdlib> #include <stack> #include <cmath> #include <vector> #include <queue> #include <set> #include <ctype.h> #include <map> #include <cfloat> #include <string> using namespace std; #define M 105 struct EDGE { int r, next; }edge[M*M]; bool a[60005], used[M]; int b[M], head[M], match[M]; int Index; void insert(int l, int r) { edge[Index].r = r; edge[Index].next = head[l]; head[l] = Index ++; } bool Dfs_Match(int x) // dfsƥ { int i; for (i = head[x]; i != -1; i = edge[i].next) { int r = edge[i].r; if (!used[r]) // ڽ· { used[r] = 1; if (match[r] == -1 || Dfs_Match(match[r])) // ҵδƥ㣬· { match[r] = x; return true; } } } return false; } int main() { for(int i = 4; i < 60000; i += 2) a[i] = true; for(int i = 3; i*i < 60000; i += 2) { if(!a[i]) { for(int j = i*i; j < 60000; j += 2*i) a[j] = true; } } int n; while (cin >> n) { memset(head, -1, sizeof(head)); memset(match, -1, sizeof(match)); Index = 0; for (int i = 1; i <= n; i ++) cin >> b[i]; for (int i = 1; i <= n; i ++) { for (int j = i+1; j <= n; j ++) { if (!a[b[i]+b[j]]) { if (b[i]&1) insert(i, j); else insert(j, i); } } } int sum = 0; for (int i = 1; i <= n; i ++) { memset(used, false, sizeof(used)); if (Dfs_Match(i)) sum ++; } cout << sum << endl; } return 0; } /* Ŀ Ŀ ĺΪ֮Ϊ¡25613Ӧͨżܡѧһ򣬴еNNΪżѡɶɡ¡ѡֶ42561356Ϊһֻܵõһ顰¡25613齫õ顰¡ɡ¡ķΪѷȻѧϣѰҳѷ : һżNN100ʾѡȻĸ֣ΧΪ[2,30000] : һKʾõġѷɡ¡Ķ : ˵ 1 һżn 2 n : õġѷɡ¡Ķ ʾ1 4 2 5 6 13 2 */
true
6886ad2493d23b6f29a461aa11152a0bfc10aa29
C++
aryandosaj/CompetetiveProgramming
/best_worst_first.cpp
UTF-8
6,232
2.515625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { int mem[]={9500,7000,4500,8500,3000,9000,1000,5500,1500,500}; int pro[]={5760,4190,3290,2030,2550,6990,8940,740,3930,6890,6580,3820,9140,420,220}; cout<<"--------------------BEST FIT --------------------\n"; { map<int,int>asinged; map<int,int>mp; vector<int>v; int ifg=0,ef=0,a=0; for(int i=0;i<10;i++)a+=mem[i]; string e="No"; for(int i=0;i<15;i++) { int m=1000000; int p=-1; for(int j=0;j<10;j++) { if((mp[j]==0)&&(mem[j]>=pro[i])){ if(m>(mem[j]-pro[i])) { m = mem[j]-pro[i];p=j; } } } if(p==-1){ if(a>pro[i]) ef+=pro[i],e="Yes"; v.push_back(i); } else{ mp[p] = 1; ifg+=mem[p]-pro[i]; a-=pro[i]; asinged[p]=i+1; //cout<<"Process Allocated : "<<i+1<<"\nMemory block : "<<p+1<<"\nInternal Fragmentation : "<<ifg<<"\n\n"; } } cout<<"Internal Fragmentation : "<<ifg<<"\nExternal Fragmentation : "<<e<<"\nProcess Unallocated : "; for(int i=0;i<v.size();i++)cout<<v[i]+1<<" "; cout<<"\nMemory\tProcess\tFree\n"; for(int i=0;i<10;i++) { if(asinged[i]!=0) cout<<mem[i]<<"\t"<<pro[asinged[i]-1]<<"\t"<<mem[i]-pro[asinged[i]-1]<<"\n"; else cout<<mem[i]<<"\t"<<"Free"<<"\t"<<mem[i]-pro[asinged[i]-1]<<"\n"; } } cout<<"\n\n---------------------------FIRST FIT------------------------\n"; { map<int,int>asinged; map<int,int>mp; vector<int>v; int ifg=0,ef=0,a=0; for(int i=0;i<10;i++)a+=mem[i]; string e="No"; for(int i=0;i<15;i++) { int m=1000000; int p=-1; for(int j=0;j<10;j++) { if((mp[j]==0)&&(mem[j]>=pro[i])) { p=j;break; } } if(p==-1){ if(a>pro[i]) ef+=pro[i],e="Yes"; v.push_back(i); } else{ mp[p] = 1; ifg+=mem[p]-pro[i]; a-=pro[i]; asinged[p]=i+1; //cout<<"Process Allocated : "<<pro[i]<<"\nMemory block : "<<mem[p]<<"\nInternal Fragmentation : "<<ifg<<"\n\n"; } } cout<<"Internal Fragmentation : "<<ifg<<"\nExternal Fragmentation : "<<e<<"\nProcess Unallocated : "; for(int i=0;i<v.size();i++)cout<<v[i]+1<<" "; cout<<"\nMemory\tProcess\tFree\n"; for(int i=0;i<10;i++) { if(asinged[i]!=0) cout<<mem[i]<<"\t"<<pro[asinged[i]-1]<<"\t"<<mem[i]-pro[asinged[i]-1]<<"\n"; else cout<<mem[i]<<"\t"<<"Free"<<"\t"<<mem[i]-pro[asinged[i]-1]<<"\n"; } } cout<<"\n\n-----------------------WORST FIT--------------------\n"; { map<int,int>asinged; map<int,int>mp; vector<int>v; int ifg=0,ef=0,a=0; for(int i=0;i<10;i++)a+=mem[i]; string e="No"; for(int i=0;i<15;i++) { int m=0; int p=-1; for(int j=0;j<10;j++) { if((mp[j]==0)&&(mem[j]>=pro[i])){ if(m<(mem[j]-pro[i])) { m = mem[j]-pro[i];p=j; } } } if(p==-1){ if(a>pro[i]) ef+=pro[i],e="Yes"; v.push_back(i); } else{ mp[p] = 1; ifg+=mem[p]-pro[i]; a-=pro[i]; asinged[p]=i+1; //cout<<"Process Allocated : "<<i+1<<"\nMemory block : "<<p+1<<"\nInternal Fragmentation : "<<ifg<<"\n\n"; } } cout<<"Internal Fragmentation : "<<ifg<<"\nExternal Fragmentation : "<<e<<"\nProcess Unallocated : "; for(int i=0;i<v.size();i++)cout<<v[i]+1<<" "; cout<<"\nMemory\tProcess\tFree\n"; for(int i=0;i<10;i++) { if(asinged[i]!=0) cout<<mem[i]<<"\t"<<pro[asinged[i]-1]<<"\t"<<mem[i]-pro[asinged[i]-1]<<"\n"; else cout<<mem[i]<<"\t"<<"Free"<<"\t"<<mem[i]-pro[asinged[i]-1]<<"\n"; } } cout<<"\n\n---------------------------NEXT FIT------------------------\n"; { map<int,int>asinged; map<int,int>mp; vector<int>v; int ifg=0,ef=0,a=0; for(int i=0;i<10;i++)a+=mem[i]; string e="No"; int jj=0; for(int i=0;i<15;i++) { int p=-1; for(int k=0;k<10;k++) { int j = (k+jj)%10; if((mp[j]==0)&&(mem[j]>=pro[i])) { jj = j+1; p=j; break; } } if(p==-1){ if(a>pro[i]) ef+=pro[i],e="Yes"; v.push_back(i); } else{ mp[p] = 1; ifg+=mem[p]-pro[i]; a-=pro[i]; asinged[p]=i+1; //cout<<"Process Allocated : "<<pro[i]<<"\nMemory block : "<<mem[p]<<"\nInternal Fragmentation : "<<ifg<<"\n\n"; } } cout<<"Internal Fragmentation : "<<ifg<<"\nExternal Fragmentation : "<<e<<"\nProcess Unallocated : "; for(int i=0;i<v.size();i++)cout<<v[i]+1<<" "; cout<<"\nMemory\tProcess\tFree\n"; for(int i=0;i<10;i++) { if(asinged[i]!=0) cout<<mem[i]<<"\t"<<pro[asinged[i]-1]<<"\t"<<mem[i]-pro[asinged[i]-1]<<"\n"; else cout<<mem[i]<<"\t"<<"Free"<<"\t"<<mem[i]-pro[asinged[i]-1]<<"\n"; } } }
true
bcf8065e7ff5e8bfca35b4a491555ac0599be310
C++
chaabaj/BricksVM
/device/SimpleCPU/include/SimpleCPU/MathUnit.hpp
UTF-8
3,305
2.84375
3
[]
no_license
#ifndef __BRICKSVM_DEVICE_MATHUNIT_HPP__ # define __BRICKSVM_DEVICE_MATHUNIT_HPP__ # include <functional> # include "interpreter/Value.hpp" # include "device/Memory.hpp" namespace bricksvm { namespace device { class MathUnit { public: interpreter::Value sqrt(interpreter::Value const &val1) const; interpreter::Value pow(interpreter::Value const &val1, interpreter::Value const &val2) const; interpreter::Value log(interpreter::Value const &val1) const; interpreter::Value sin(interpreter::Value const &val1) const; interpreter::Value cos(interpreter::Value const &val1) const; interpreter::Value tan(interpreter::Value const &val1) const; void addVector(Memory &memory, std::string const &progId, uint64_t vecAddr1, uint64_t vecAddr2, uint64_t destAddr, uint8_t vecSize) const; void mulVector(Memory &memory, std::string const &progId, uint64_t vecAddr1, uint64_t vecAddr2, uint8_t vecSize, uint64_t destAddr) const; void subVector(Memory &memory, std::string const &progId, uint64_t vecAddr1, uint64_t vecAddr2, uint8_t vecSize, uint64_t destAddr) const; void divVector(Memory &memory, std::string const &progId, uint64_t vecAddr1, uint64_t vecAddr2, uint8_t vecSize, uint64_t destAddr) const; private: template<typename Operation> void vecOperation(Memory &memory, std::string const &progId, uint64_t vecAddr1, uint64_t vecAddr2, uint8_t vecSize, uint64_t destAddr) const { std::vector<double> result; std::vector<double> vec1; std::vector<double> vec2; result.resize(vecSize); vec1.resize(vecSize); vec2.resize(vecSize); memory.read(progId, vecAddr1, &vec1[0], vecSize); memory.read(progId, vecAddr2, &vec2[0], vecSize); for (uint8_t i = 0; i < vecSize; ++i) { result[i] = Operation::compute(vec1[i], vec2[i]); } memory.write(progId, destAddr, &result[0], vecSize); } }; } } #endif
true
1f3300c6fee85779a70ff5c228b926d7388338ad
C++
Beryl2208/CI-2
/Coding Club India/Interview Questions/MinimizeMaxDifferenceInsertK.cpp
UTF-8
854
3.171875
3
[ "MIT" ]
permissive
#include <bits/stdc++.h> using namespace std; int minimizedMaxDiff(int arr[], int n, int k){ int maxx = INT_MIN; for (int i = 0; i < n - 1; i++) maxx = max(maxx, abs(arr[i] - arr[i + 1])); if (maxx == 0) return 0; int low = 1; int high = maxx; int mid, temp; while (low < high){ mid = (low + high) / 2; temp = 0; for (int i = 0; i < n - 1; i++){ temp += (abs(arr[i] - arr[i + 1])- 1) / mid; } if (temp > k) low = mid + 1; else high = mid; } return high; } int main(){ int arr[] = {66, 31, 99, 76, 38, 76}; int res = minimizedMaxDiff(arr, 6, 5); cout << res << endl; return 0; }
true
14060463a6672f132d610c2feb18f2efed8abd15
C++
jonongjs/auv-vision-system
/src/PropertyAdaptor.h
UTF-8
579
2.703125
3
[]
no_license
// Helper class to connect between property widget and the filter #ifndef PROPERTYADAPTOR_H #define PROPERTYADAPTOR_H #include <QObject> #include <string> #include "ImageFilterBase.h" class PropertyAdaptor : public QObject { Q_OBJECT public: PropertyAdaptor(ImageFilterBase *_filter, const std::string& _property) : filter(_filter), property(_property) { } public slots: void valueChanged(const QString& text) { filter->setProperty(property, text.toStdString()); } private: ImageFilterBase *filter; std::string property; }; #endif//PROPERTYADAPTOR_H
true
a57d788383a7ae44db276e5b2ddf125a8c956f3a
C++
HachimineDaiki/KBC4U-22-
/2021summer_GAME/Time.cpp
UTF-8
352
2.5625
3
[]
no_license
#include "Time.h" void InitTime() { effect_time.count = 0; effect_time.time = 0; effect_exit_time.count = 0; effect_exit_time.time = 0; } int EffectExitTime() { effect_exit_time.count++; return effect_exit_time.time = effect_exit_time.count / 60; } int EffectTime() { effect_time.count++; return effect_time.time = effect_time.count / 60; }
true
a8c7a3fdb67361fff532b9b1659e663bd8612af4
C++
esix/competitive-programming
/e-olymp/~contest-8903/A/main.cpp
UTF-8
2,843
2.828125
3
[]
no_license
#include <iostream> #include <utility> #include <vector> #include <string> #include <sstream> #include <algorithm> #include <map> #include <math.h> using namespace std; template <typename INT> INT gcd(INT m, INT n) { if (m == 0) return n; if (n == 0) return m; if (m == n) return m; if (m == 1) return (INT)1; if (n == 1) return (INT)1; bool m_even = ((m & 1) == 0); bool n_even = ((n & 1) == 0); if (m_even) { return n_even ? 2 * gcd(m >> 1, n >> 1) : gcd(m >> 1, n); } // ! m_even if (n_even) { return gcd(m, n >> 1); } // !n_even && !m_even return (n > m) ? gcd(m, (n - m) >> 1) : gcd((m - n) >> 1, n); } long get_lower_bound(long h, long t) { return floor(double(t) / double(h)) * h; } long get_higher_bound(long h, long t) { return ceil(double(t) / double(h)) * h; } int main() { cin.tie(0); ios::sync_with_stdio(false); while (true) { int n, t; cin >> n >> t; if (n == 0 && t == 0) break; vector<int> ms(n); for (int i = 0; i < n; i++) cin >> ms[i]; vector<int> ts(t); for (int i = 0; i < t; i++) cin >> ts[i]; const int msLength = ms.size(); vector<long> lower(t); vector<long> higher(t); for (int i1 = 0; i1 < msLength - 3; i1++) { for (int i2 = i1 + 1; i2 < msLength - 2; i2++) { long lcm2 = ms[i1] * ms[i2] / gcd<long>(ms[i1], ms[i2]); for (int i3 = i2 + 1; i3 < msLength - 1; i3++) { long lcm3 = lcm2 * ms[i3] / gcd<long>(lcm2, ms[i3]); for (int i4 = i3 + 1; i4 < msLength - 0; i4++) { long h = lcm3 * ms[i4] / gcd<long>(lcm3, ms[i4]); // lcm for all numbers = minimal height of table with such if (i1 == 0 && i2 == 1 && i3 == 2 && i4 == 3) { // initial value for (int i = 0; i < t; i++) { lower[i] = get_lower_bound(h, ts[i]); higher[i] = get_higher_bound(h, ts[i]); } // cout << "initial value; h=" << h << endl; // for (int i = 0; i < t; i++) { // cout << '(' << ts[i] << ": " << lower[i] << ',' << higher[i] << ')' << ' '; // } // cout << endl; } else { for (int i = 0; i < t; i++) { lower[i] = max(lower[i], get_lower_bound(h, ts[i])); higher[i] = min(higher[i], get_higher_bound(h, ts[i])); } // cout << "contimue; h=" << h << endl; // for (int i = 0; i < t; i++) { // cout << '(' << ts[i] << ": " << lower[i] << ',' << higher[i] << ')' << ' '; // } // cout << endl; } } } } } for (int i = 0; i < t; i++) { cout << lower[i] << ' ' << higher[i] << '\n'; } } return 0; }
true
af99061e8e5ed33522991d18a2b55a4aa9fa3abc
C++
alexandraback/datacollection
/solutions_2692487_1/C++/Jonick/a.cpp
UTF-8
891
2.65625
3
[]
no_license
#include <vector> #include <iostream> #include <stdlib.h> #include <string> #include <map> #include <algorithm> using namespace std; void solveTest() { int A, N; cin >> A >> N; vector<int> a(N); for( int i = 0; i < N; i++ ) { cin >> a[i]; } sort(a.begin(),a.end()); int best = a.size(); int cur = A; int ind = 0; int cP = 0; if( cur == 1 ) { cout << a.size() << endl; return; } while( ind < a.size() ) { if( cur > a[ind] ) { cur += a[ind]; ind++; } else { cP++; cur += cur - 1; } int tmp = cP + a.size() - ind; best = min(best, tmp); } cout << best << endl; } void run() { int tn; cin >> tn; for( int i = 0; i < tn; i++ ) { cout << "Case #" << (i+1) << ": "; solveTest(); } } int main() { freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); run(); return 0; }
true
5b8719a5d9c359215eb7038762f79ef75180fe43
C++
xzrunner/sop
/include/sop/ParmList.h
UTF-8
2,985
2.8125
3
[ "MIT" ]
permissive
#pragma once #include "sop/ParmType.h" #include "sop/GeoAttrDefine.h" #include <SM_Vector.h> #include <vector> #include <memory> namespace sop { class ParmList { public: ParmList() {} ParmList(const ParmList& p); ParmList(GeoAttr attr); ParmList(const std::string& name, ParmType type); ParmList& operator = (const ParmList& list); virtual std::shared_ptr<ParmList> Clone(bool clone_items = true) const = 0; virtual void CopyFrom(size_t dst_idx, const ParmList& src, size_t src_idx) = 0; virtual void Append(const ParmList& list) = 0; virtual void Clear() = 0; virtual void Resize(size_t num) = 0; virtual size_t Size() const = 0; auto& GetAttr() const { return m_attr; } auto& GetName() const { return m_name; } auto& GetType() const { return m_type; } protected: GeoAttr m_attr = GEO_ATTR_UNKNOWN; std::string m_name; ParmType m_type = ParmType::Boolean; }; // ParmList template <typename T> class ParmListImpl : public ParmList { public: ParmListImpl(GeoAttr attr, std::vector<T> items) : ParmList(attr) , m_items(items) { } ParmListImpl(const std::string& name, ParmType type, std::vector<T> items) : ParmList(name, type) , m_items(items) { } virtual std::shared_ptr<ParmList> Clone(bool clone_items = true) const override { if (clone_items) { return std::make_shared<ParmListImpl<T>>(m_name, m_type, m_items); } else { return std::make_shared<ParmListImpl<T>>(m_name, m_type, std::vector<T>()); } } virtual void CopyFrom(size_t dst_idx, const ParmList& src, size_t src_idx) override { if (GetType() == src.GetType()) { m_items[dst_idx] = static_cast<const ParmListImpl<T>&>(src).m_items[src_idx]; } } virtual void Append(const ParmList& list) override { if (GetType() == list.GetType()) { auto& src = static_cast<const ParmListImpl<T>&>(list).m_items; std::copy(src.begin(), src.end(), std::back_inserter(m_items)); } else { m_items.resize(m_items.size() + list.Size()); } } virtual void Clear() override { m_items.clear(); } virtual void Resize(size_t num) override { m_items.resize(num); } virtual size_t Size() const override { return m_items.size(); } auto& GetAllItems() const { return m_items; } private: std::vector<T> m_items; }; // ParmListImpl typedef ParmListImpl<bool> ParmBoolList; typedef ParmListImpl<int> ParmIntList; typedef ParmListImpl<sm::ivec2> ParmInt2List; typedef ParmListImpl<sm::ivec3> ParmInt3List; typedef ParmListImpl<sm::ivec4> ParmInt4List; typedef ParmListImpl<float> ParmFltList; typedef ParmListImpl<sm::vec2> ParmFlt2List; typedef ParmListImpl<sm::vec3> ParmFlt3List; typedef ParmListImpl<sm::vec4> ParmFlt4List; typedef ParmListImpl<std::string> ParmStrList; }
true
193347780af6da270cd4dc2f16e12f9abc32e222
C++
Jerryh001/UVa
/318.cpp
UTF-8
2,146
2.75
3
[]
no_license
#include<iostream> #include<climits> #include<cstdio> #include<algorithm> using namespace std; struct domi { int dis; bool checked; }; struct edge { int a; int b; int dis; float time; }; int map[501][501]; domi v[501]; edge e[124751]; int main() { int n, m; for (int time = 1;; time++) { cin >> n >> m; if (!(n | m)) return 0; if (m == 0) { printf("System #%d\nThe last domino falls after 0.0 seconds, at key domino 1.\n", time); cout << endl; continue; } for (int i = 0; i <= n; i++) { v[i].dis = -1; v[i].checked = true; for (int j = 0; j <= n; j++) { map[i][j] = -1; } } int next = 1; for (int i = 0; i < m; i++) { cin >> e[i].a >> e[i].b >> e[i].dis; map[e[i].a][e[i].b] = map[e[i].b][e[i].a] = e[i].dis; v[e[i].a].checked = false; v[e[i].b].checked = false; } v[1].dis = 0; while (next != -1) { v[next].checked = true; for (int i = 0; i <= n; i++) { if (v[i].checked==false&&map[next][i]>0 && (v[i].dis<0||v[next].dis + map[next][i] < v[i].dis)) { v[i].dis = v[next].dis + map[next][i]; } } next = -1; for (int i = 0; i <= n; i++) { if (v[i].checked == false&&v[i].dis>0 && (next == -1 || v[i].dis < v[next].dis)) { next = i; } } } int maxedge = 0; for (int i = 0; i < m; i++) { int a = min(v[e[i].a].dis, v[e[i].b].dis); int b = max(v[e[i].a].dis, v[e[i].b].dis); if (b - a >= e[i].dis) { e[i].time = b; } else { e[i].time = (e[i].dis + v[e[i].a].dis + v[e[i].b].dis) / 2.0f; } if (e[i].time > e[maxedge].time) { maxedge = i; } } int maxv = 1; for (int i = 0; i <= n; i++) { if (v[i].dis>0&&v[i].dis > v[maxv].dis) { maxv = i; } } cout << "System #" << time << endl << "The last domino falls after "; if(e[maxedge].time>v[maxv].dis) { printf("%.1f", e[maxedge].time); cout << " seconds, between key dominoes " << e[maxedge].a << " and " << e[maxedge].b << "." << endl; } else { printf("%.1f", v[maxv].dis + 0.0); cout << " seconds, at key domino " << maxv << "." << endl; } cout << endl; } }
true
350e1bbf097dab7dea6660cee48bee31a9d35185
C++
Knabin/TBCppStudy
/Chapter3/Chapter3_01/main_chapter31.cpp
UTF-8
413
3.828125
4
[]
no_license
#include <iostream> #include <cmath> int main() { using namespace std; // 수식이 들어오면 어느 쪽을 먼저 계산할지 결정한다. // 필요한 경우 괄호를 사용해서 우선순위를 명확하게 남기자. int x = 4 + 2 * 3; // * 먼저 int y = 3 * 4 / 2; // *와 /는 우선순위가 같음, Associativity int z = std::pow(2, 3); // 2의 세제곱 cout << z << endl; return 0; }
true
a0ebcc8e92bea685302e4764118afc8a2709e4bf
C++
rizwankadhar/OOP
/Delivery/FuelTank.h
UTF-8
398
3.421875
3
[]
no_license
#pragma once class FuelTank { public: FuelTank(double petrol,double capac): fuel(petrol), capacity(capac) {} double getFuel() const {return fuel;} double getCapacity() const {return capacity;} void addFuel(double amount) {fuel += amount;} void consumeFuel(double amount) {fuel -= amount;} private: double fuel; double capacity; };
true
118d0569fcc7f0c7dfe70d38e94b58301b1ee464
C++
bluemix/Online-Judge
/CodeForce/444A DZY Loves Physics.cpp
UTF-8
2,460
3.40625
3
[]
no_license
/* 7038615 2014-07-07 11:27:32 Shark A - DZY Loves Physics GNU C++ Accepted 46 ms 0 KB */ #include<cstdio> #define MAX(x,y) ( (x) >= (y) ? (x) : (y) ) int main(){ int n, m; while (scanf("%d%d", &n, &m) == 2){ int S[501]; double ans = 0; for (int i = 1; i <= n; i++) scanf("%d", S + i); for (int i = 0; i < m; i++){ int a, b, c; scanf("%d%d%d", &a, &b, &c); ans = MAX(ans, 1.0 * (S[a] + S[b]) / c); } printf("%.15lf\n", ans); } return 0; } /* A. DZY Loves Physics time limit per test1 second memory limit per test256 megabytes inputstandard input outputstandard output DZY loves Physics, and he enjoys calculating density. Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges. Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible. An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. Input The first line contains two space-separated integers n (1 ≤ n ≤ 500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. Output Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9. Sample test(s) input 1 0 1 output 0.000000000000000 input 2 1 1 2 1 2 1 output 3.000000000000000 input 5 6 13 56 73 98 17 1 2 56 1 3 29 1 4 42 2 3 95 2 4 88 3 4 63 output 2.965517241379311 Note In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1. In the second sample, choosing the whole graph is optimal. */
true
06afd173e67785561e052656a8db1133a1a96ce1
C++
Brigapes/LivingExpenses
/LifeInUK/Life.cpp
UTF-8
1,796
3.640625
4
[]
no_license
#include "Life.h" #include <iostream> void Life::SetRent(int input) { Rent = input;} void Life::SetHourRate(double input) { HourRate = input;} void Life::SetWorkDays(int input) { WorkDays = input;} void Life::SetWorkHours(int input) { WorkHours = input;} void Life::SetExpenses(double input) { Expenses = input;} void Life::PrintAll() { std::cout << "You work for " << GetHourRate() << " per hour, "<<GetWorkHours()<<" hours across "<< GetWorkDays()<< " days in a week." << std::endl; std::cout << "You will have " << 24 - (GetWorkHours() / GetWorkDays() + 8) << " free hours in a day. Spending " << GetWorkHours() / GetWorkDays() << " work hours + 8 hours of sleep" << std::endl; std::cout << "You will earn " << GetMonthWage() << " a month, working "<< GetWorkHours()*4<< " hours a month." << std::endl; std::cout << "Which makes " << GetYearWage() << " a year without expenses and paying a tax income." << std::endl; std::cout << "Your tax rate per income will be " << GetTaxRate() << "%. \n" << std::endl; std::cout << "Final leftover money will be " << FinalLeftover() << " in a year, which is "<< FinalLeftover()/12 <<" a month. \n \n" << std::endl; } void Life::SetTaxRate() { double wage = GetYearWage(); if (wage<11500) {TaxRate = 0;} else if (wage > 11500 && wage < 45000) {TaxRate= 20;} else if (wage > 45000 && wage < 150000) { TaxRate = 40; } else { TaxRate = 45; } } Life::Life() { SetTaxRate(); double HourRate = 8; double MonthWage = WorkDays*WorkHours; double YearWage = MonthWage * 12; int WorkDays = 6; int Rent = 450; int WorkHours = 35; double Expenses = 200; } double Life::FinalLeftover() { return ((GetYearWage() - (GetYearWage() / 100 - GetTaxRate())) - Rent*12 - Expenses*12); }
true
4dfe36253f54ce1a8db4ab8394d7b760db6e1caf
C++
coollama11/cpp
/tests/person/testing-class-person.cpp
UTF-8
7,113
3.46875
3
[]
no_license
#include <iostream> using std::cin; using std::cout; using std::endl; #include "person.h" //<-usually, the class uses the include to import //the implementation //for some freaking reason, the body of member functions pertaining to a class //usually appear in the .cpp file instead of the .h file //#programmer logic void person::setFirstName(string fname) { first_name = fname; } void person::setLastName(string lname) { last_name = lname; } void person::setAge(int age) { this->age = age; } void person::setGrades(int grades) { this->grades = grades; } void person::setIq(int iq) { this->iq = iq; } void person::setMajor(string major) { this->major = major; } void person::addFamilyMember(string name, string relation) { family_members[relation] = name; } void person::addInterest(string interest) { interests.insert(interest); } void person::addClass(string className) { classes.push_back(className); } /* string first_name; string last_name; int age; int grades; int iq; string major; map <string,string> family_members ; set <string> interests; vector <string> classes; */ string person::getName()const { return first_name + " " + last_name; } void person::printStats() //srew it, we'll print them isntead { cout << "Age: " << age << endl << "Grades: " << grades << "/100\nIQ: " << iq << "\nMajor: " << major << endl; } string person::getFamilyMember(string relation) { return family_members[relation]; } void person::printListOfFamilyMembers() { for(map<string, string>::iterator i = family_members.begin(); i != family_members.end(); i++) { cout << (*i).first << ": " << (*i).second << endl; } } void person::printListOfInterests() { for(set<string>::iterator i = interests.begin(); i != interests.end(); i++) { cout << *i << ", "; } cout << endl; } bool person::isTakingClass(string className) { for(size_t c = 0; c < classes.size(); c++) { if(classes[c] == className) return true; } return false; } void person::printListOfClasses() { cout << "Classes: "; for(size_t c = 0; c < classes.size(); c++) { cout << classes[c] << ", "; } cout << endl; } void person::printEVERYTHING() { cout << "Full name: " << getName() << endl; printStats(); printListOfFamilyMembers(); printListOfInterests(); printListOfClasses(); } //dumb but i guess important: activating a member function of a class //object_name.memberFunction(parameter1, parameter2); parameters are also //called arguments of the member function /* ic: void setFirstName(string fname); void setLastName(string lname); void setAge(int age); void setGrades (int grades); void setIq(int iq); void setMajor(string major); void addFamilyMember(string name, string relation); void addInterest (string interest); void addClass (string className); string getName(); void printStats(); string getFamilyMember(string relation); void printListOfInterests(); void printListOfFamilyMembers(); void printListOfClasses(); void printEVERYTHING(); bool isTakingClass(string className); */ //two ways of overloading an operator (non member functions) //method1 /* person operator+(const person& p1, const person& p2) { person p3; p3.setFirstName(p1.getName() + " and"); p3.setLastName(p2.getName()); return p3; } */ //method 2 (after the end of this comment) /* - Variables declared in ( int main() { ... } ) are considered to be local - Variables declared outside of (int main () { ... }), usually before it, considered to be global - For ex: int i = 1; //global int main() { int i = 6; //local cout << i << endl; } */ person person::operator+(const person& p1) const { person p2; p2.first_name = this->first_name; p2.last_name = p1.last_name; p2.age = p1.age + this->age; p2.grades = p1.grades + this->grades; p2.iq = p1.iq + this->iq; p2.major = p1.major + " and " + this->major; return p2; } bool person::operator==(const person& p1) const { if(this->first_name == p1.first_name) { if(this->last_name == p1.last_name) { return true; } } return false; } //overloaded operators, like member functions, can utilize previosly //implemented overloaded operators bool person::operator!=(const person& p1) const { if(*this == p1) { return false; } return true; } //Kinda important: (this) is a pointer //IMPORTANT AF: when using constant parameters, the functions called must //ALSO be const (for person, getName() had to be const for the const //parameter p1 object to use the getName() function) //ex: can be found in the method1 operator+ //ALSO IMPORTANT AF: const functions are not allowed to make modificiations //to the object they are being called on int main() { person idol; idol.setFirstName("Super"); idol.setLastName("Guy"); idol.setAge(69); idol.setGrades(100); idol.setIq(100000); idol.setMajor("Computer Science"); idol.addClass("Intro to Russian Hacking"); idol.addClass("Discrete Fapping"); idol.addClass("Brute Force Programming"); idol.addClass("Watching Mr.Robot"); idol.addFamilyMember("Marie Estime", "Mum"); idol.addFamilyMember("Douchy Fuckface", "Dad"); idol.addFamilyMember("Lord Dork", "Little Brother"); idol.addFamilyMember("Karnovsky", "Older Brother"); idol.addInterest("Figure Skating"); idol.addInterest("Scuba Diving"); idol.addInterest("Being an absolute legend"); idol.printEVERYTHING(); //person(string fname, string lname, int age, int grades, int iq, string major) person peasant("Common", "Begger", 20, 6, 20, "Homelessness"); cout << endl << "Full Name: " << peasant.getName() << endl; peasant.printStats(); person noone("No", "One"); cout << endl << "Full Name: " << noone.getName() << endl; noone.printStats(); //when activating default constructor, DO NOT INCLUDE PARENTHESES, like the //nobody object below person nobody; nobody.setFirstName("Nobody"); cout << endl << "Full Name: " << nobody.getName() << endl; nobody.printStats(); person mystery = noone + nobody; cout << endl << "Full Name: " << mystery.getName() << endl; mystery.printStats(); person newPerson = idol + peasant; cout << endl << newPerson.getName() << endl; newPerson.printStats(); cout << endl << "Is idol equal to idol + peasant?"<< endl; if(peasant == (idol + peasant)) { cout << "Yep :)" << endl; } else { cout << "Nope :(" << endl; } cout << endl << "Is idol NOT equal to idol + peasant?" << endl; if(idol != idol + peasant) { cout << "Yep :)" << endl; } else { cout << "Nope :(" << endl; } //idol and peasant are objects of the person class (should be obv at this //point) }
true
d647c3f4eddbd75b0434f29b1cf7f8a3a794eed0
C++
OmarAhmedSaleh/competitive-programming
/UVA/537 - Artificial Intelligence?.cpp
UTF-8
3,502
2.53125
3
[]
no_license
#include <cstring> #include <vector> #include <list> #include <map> #include <set> #include <deque> #include <queue> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> #include <memory.h> #include <cassert> #include <complex> using namespace std; int dx[8]={1,-1,0,0,1,-1,1,-1}; int dy[8]={0,0,-1,1,1,-1,-1,1}; /* -- Valid -- const (10^9>sz) -- array index -- less or more , check if -- even or odd -- inequality */ int t; string s; // p=u*i; double p , I, u; int main(){ //freopen("in.txt","r",stdin); //freopen("out.txt","w",stdout); cin>>t; cin.ignore(); for(int tt=1;tt<=t;tt++){ getline(cin,s); int sz=s.size(); bool ok[3]={0,0,0}; for(int i=0;i<sz;i++){ if(s[i-1]=='U'&&s[i]=='='){ ok[1]=1; i++; int j=i; string temp=""; int mm=0,Mm=0,K=0; for(j=i;j<sz;j++){ if(s[j]=='V'){break;} if(s[j]=='='){continue;} if(s[j]=='m'){ mm=1; continue; } if(s[j]=='M'){ Mm=1; continue; } if(s[j]=='k'){ K=1; continue; } temp+=s[j]; } i=j; u=0; int d=1; bool dot=0; for(int j=0;j<temp.size();j++){ if(temp[j]=='.'){dot=1; continue;} int aa=temp[j]-'0'; if(dot){ d*=10; } u*=10; u+=aa; } u/=d; if(mm){ u/=1000; } if(K){ u*=1000; } if(Mm){ u*=1000; u*=1000; } } if(s[i-1]=='P'&&s[i]=='='){ ok[0]=1; int j=i; string temp=""; int mm=0,Mm=0,K=0; for(j=i;j<sz;j++){ if(s[j]=='='){continue;} if(s[j]=='W'){break;} if(s[j]=='m'){ mm=1; continue; } if(s[j]=='M'){ Mm=1; continue; } if(s[j]=='k'){ K=1; continue; } temp+=s[j]; } i=j; p=0; int d=1; bool dot=0; for(int j=0;j<temp.size();j++){ if(temp[j]=='.'){dot=1; continue;} int aa=temp[j]-'0'; if(dot){ d*=10; } p*=10; p+=aa; } p/=d; if(mm){ p/=1000; } if(K){ p*=1000; } if(Mm){ p*=1000; p*=1000; } } if(s[i-1]=='I'&&s[i]=='='){ ok[2]=1; int jj=i; string temp=""; int mm=0,Mm=0,K=0; for(jj=i;jj<sz;jj++){ if(s[jj]=='='){continue;} if(s[jj]=='A'){break;} if(s[jj]=='m'){ mm=1; continue; } if(s[jj]=='M'){ Mm=1; continue; } if(s[jj]=='k'){ K=1; continue; } temp+=s[jj]; } i=jj; I=0; int d=1; bool dot=0; for(int j=0;j<temp.size();j++){ if(temp[j]=='.'){dot=1; continue;} int aa=temp[j]-'0'; if(dot){ d*=10; } I*=10; I+=aa; } I/=d; if(mm){ I/=1000; } if(K){ I*=1000; } if(Mm){ I*=1000; I*=1000; } } } double ans=0; printf("Problem #%d\n",tt); if(!ok[0]){ ans=I*u; printf("P=%.2lf%c\n",ans,'W'); } if(!ok[1]){ ans=p/I; printf("U=%.2lf%c\n",ans,'V'); } if(!ok[2]){ ans=p/u; printf("I=%.2lf%c\n",ans,'A'); } printf("\n"); } return 0; }
true
c95ae1ea3b91cc73a2ae87bb454271cd1dc9e579
C++
Steelbadger/OpenGLThreading
/Windows Framework/Lab6c/myvector3.cpp
UTF-8
726
3.328125
3
[ "MIT" ]
permissive
#include "myvector3.h" #include "myvector4.h" Vector3::Vector3(void): x(0),y(0),z(0) { } Vector3::Vector3(const float _x, const float _y, const float _z) :x(_x),y(_y),z(_z) { } Vector3::Vector3(const Vector3 &rhs): x(rhs.x), y(rhs.y), z(rhs.z) { } Vector3::Vector3(const Vector4 &rhs): x(rhs.x/rhs.w), y(rhs.y/rhs.w), z(rhs.z/rhs.w) { } bool Vector3::operator ==(const Vector3 & rhs) const { return ((x == rhs.x) && (y == rhs.y) && (z == rhs.z)); } Vector3 & Vector3::operator +=(const Vector3 &rhs) { x += rhs.x; y += rhs.y; z += rhs.z; return *this; } Vector3::~Vector3(void) { } float Vector3::Length() { return sqrt(x * x + y * y + z * z); } Vector3 Vector3::Normalize() { return (*this/Length()); }
true
30f7d1cd6927fd27b2d54b769615b8bb668ac0cc
C++
sumeetgajjar/CS7610-F20
/lab2/src/utils.h
UTF-8
1,364
2.53125
3
[]
no_license
// // Created by sumeet on 9/30/20. // #ifndef LAB2_UTILS_H #define LAB2_UTILS_H #include <string> #include <vector> #include <unordered_map> #include "message.h" namespace lab2 { class Utils { public: static std::vector<std::string> readHostFile(const std::string &hostFilePath); static std::vector<std::string> getPeerContainerHostnames(const std::vector<std::string> &allHostnames, const std::string &currentHostname); static uint32_t getProcessIdentifier(const std::string &hostname, const std::vector<std::string> &allHostnames); static double getRandomNumber(double min = 0, double max = 1); }; class PeerInfo { static PeerId myPeerId; static std::vector<std::string> allPeerHostnames; static std::unordered_map<std::string, PeerId> hostnameToPeerIdMap; static std::unordered_map<PeerId, std::string> peerIdToHostnameMap; public: static void initialize(const std::string &myHostname, std::vector<std::string> allPeerHostnames_); static PeerId getMyPeerId(); static std::string getHostname(PeerId peerId); static PeerId getPeerId(const std::string &hostname); static const std::vector<std::string> &getAllPeerHostnames(); }; } #endif //LAB2_UTILS_H
true
6d186fe2acb36eb74e333ce2ad5d951bab5ef77d
C++
wallstead/school
/2016/Spring 2016/cs202/project4/project4.cpp
UTF-8
4,513
3.671875
4
[]
no_license
#include <iostream> #include <fstream> using namespace std; struct Pieces { char *word; int jump; }; void readFile(ifstream *fin, Pieces *pptr, int *kptr, int pieceCount, int keyCount); void decrypt(char *decrypted, Pieces *pptr, int *kptr, int pieceCount, int keyCount); int stringLength(char *str); void strConcat(char *str1, char *str2); void stringCopy(char *str1, char *str2); int main() { char *ifileName = new char[20]; cout << "Please enter file name: "; cin >> ifileName; ifstream fin; fin.open(ifileName); // open the file delete []ifileName; // Done with file ifileName = NULL; int pieceCount, keyCount; if(fin.good()) { cout << "File opened. Decoding..." << endl; /* Get pieceCount and keyCount */ fin >> pieceCount >> keyCount; } else { cout << "Error opening file." << endl; } /* Allocate arrays */ Pieces *pptr = new Pieces[pieceCount]; Pieces *pptrHome = pptr; // Don't move this! int *kptr = new int[keyCount]; char *decrypted = new char[100]; // temporarily allocate room for 100 chars /* Read in data */ readFile(&fin, pptr, kptr, pieceCount, keyCount); /* Decrypt data */ decrypt(decrypted, pptr, kptr, pieceCount, keyCount); /* delete allocated memory for each word in pieces */ for (int i = 0; i < pieceCount; i++) { delete [](*pptr).word; (*pptr).word = NULL; pptr++; } /* delete allocated memory for pieces */ pptr = pptrHome; delete []pptr; pptr = NULL; /* delete allocated memory for keys */ delete []kptr; kptr = NULL; /* resize decrypted string */ char *decrypted_final = new char[stringLength(decrypted)+1]; // Create exact amount of memory needed for word. stringCopy(decrypted_final, decrypted); delete []decrypted; decrypted = NULL; cout << "FINISHED: " << decrypted_final << endl; /* delete allocated memory for decrypted string. */ delete []decrypted_final; decrypted_final = NULL; return 0; } void readFile(ifstream *fin, Pieces *pptr, int *kptr, int pieceCount, int keyCount) { Pieces *pptrHome = pptr; // Don't move this home pointer int *kptrHome = kptr; // Don't move this home pointer for (int i = 0; i < pieceCount; i++) { char *tempWord = new char[20]; // create pointer to first char in char array. *fin >> tempWord >> (*pptr).jump; // Get the word and the jump (*pptr).word = new char[stringLength(tempWord)+1]; // Create exact amount of memory needed for word. stringCopy((*pptr).word, tempWord); delete []tempWord; // Done with tempWord tempWord = NULL; pptr++; } for (int j = 0; j < keyCount; j++) { *fin >> *kptr; // get the key kptr++; } pptr = pptrHome; // reset to home kptr = kptrHome; // reset to home (*fin).close(); } void decrypt(char *decrypted, Pieces *pptr, int *kptr, int pieceCount, int keyCount) { Pieces *pptrHome = pptr; int *kptrHome = kptr; int pieceIndex; // to keep track of current position for (int i = 0; i < keyCount; i++) { //For each key pptr += *kptr; // set the pointer to the key count pieceIndex = *kptr; // keep track with index while((*pptr).jump != 0) { // stop only if jump is 0 if ((pieceIndex + (*pptr).jump) < pieceCount) { // if it doesnt wrap pptr += (*pptr).jump; // jump the needed length pieceIndex += (*pptr).jump; // keep track } else { //wrap /* Calulate the new Index for the pptr */ int difference = pieceCount - pieceIndex; int newIndex = difference - (*pptr).jump; pptr = pptrHome + newIndex; pieceIndex = newIndex; } } strConcat(decrypted, (*pptr).word); kptr++; pptr = pptrHome; //reset to home } } void strConcat(char *str1, char *str2) { /* Add str2 to the end of str1 */ while(*str1 != '\0') { str1++; } while(*str2 != '\0') { *str1 = *str2; str1++; str2++; } *str1 = ' '; } int stringLength(char *str) { int length = 0; while (*str != '\0') { str++; length++; } return length; } void stringCopy(char *str1, char *str2) { while (*str2 != '\0') { *str1 = *str2; str1++; str2++; } *str1 = '\0'; }
true
575406ee3be6fa75daa4f6df312b5b2654e91be4
C++
Aiorosu-cn/Learning
/C++/c_plus_Neworigin/this指针/Circle2.cpp
UTF-8
390
3.375
3
[]
no_license
#include "Circle.h" Circle::Circle( float _r, float _x ,float _y ) { radius = _r; x = _x; y = _y; } Circle& Circle::setRadius( float r ) { radius = r ; return *this; } Circle& Circle::setX (float x ) { this->x = x ; return *this; } Circle& Circle::setY( float x ) { this->y = y ; return *this; } void Circle::print()const { cout << x << " " << y << " " << radius << endl; }
true
6d8d7695598e68aff287534efc73ed3edafbb5a1
C++
mcolula/CaribbeanOnlineJudge-Solutions
/frankzappa-p1690-Accepted-s809290.cpp
UTF-8
1,606
3.1875
3
[]
no_license
#include <iostream> #include <vector> #include <queue> using namespace std; typedef struct { int * sz; int * id; int count; } UnionFind; UnionFind create(int n) { UnionFind u; u.sz = new int[n]; u.id = new int[n]; for (int i = 0; i < n; i++) { u.id[i] = i; u.sz[i] = 1; } u.count = n; return u; } int find(UnionFind * u, int p) { int q = p; while (q != u->id[q]) q = u->id[q]; return q; } bool connected(UnionFind * u, int p, int q) { return find(u, p) == find(u, q); } void connect(UnionFind * u, int p, int q) { int rootP = find(u, p); int rootQ = find(u, q); if (rootQ == rootP) return; if (u->sz[rootP] < u->sz[rootQ]) { u->id[rootP] = rootQ; u->sz[rootQ] += u->sz[rootP]; u->count--; } else { u->id[rootQ] = rootP; u->sz[rootP] += u->sz[rootQ]; u->count--; } } typedef struct { int u; int v; int w; } edge; edge init(int u, int v, int w) { edge e; e.u = u; e.v = v; e.w = w; return e; } bool operator <(const edge & e, const edge & f) { return e.w < f.w; } int cost(priority_queue<edge> pq, int n) { UnionFind u = create(n); int mst = 0; int cst = 0; edge e; while(!pq.empty() && mst < n - 1) { e = pq.top(); pq.pop(); if(!connected(&u, e.u - 1, e.v - 1)) { mst += 1; cst += e.w; connect(&u, e.u - 1, e.v - 1); } } return u.count == 1 ? cst : - 1; } int main() { int n, t; int u, v, w; cin >> n >> t; priority_queue<edge> pq; while (t--) { cin >> u >> v >> w; pq.push(init(u, v, w)); } cout << cost(pq, n) << endl; return 0; }
true
7ae1a2916ca2db7429447fc37a07539807d7ff38
C++
kbinani/WaveFile
/format.hpp
UTF-8
846
2.859375
3
[ "MIT" ]
permissive
#pragma once #include <cstddef> namespace WaveFile { class Format { public: enum class Type { PCM, FLOAT, }; public: explicit Format(unsigned int channels = 2, Type type = Type::PCM, int sample_rate = 44100) : channels_(channels) , type_(type) , sample_rate_(sample_rate) , bit_per_sample_(16) {} std::size_t channels() const { return channels_; } Type type() const { return type_; } unsigned int sample_rate() const { return sample_rate_; } unsigned int bit_per_sample() const { return bit_per_sample_; } unsigned int data_rate() const { return channels_ * sample_rate_ * bit_per_sample_ / 8; } unsigned int block_size() const { return channels_ * bit_per_sample_ / 8; } private: unsigned int channels_; Type type_; int sample_rate_; int bit_per_sample_; }; } // namespace WaveFile
true
a854c5857aba67b78d3437133d588e08d617c1ee
C++
warmshowers1/cse_100-labs
/12Lab/awoersching.cpp
UTF-8
1,926
3.25
3
[]
no_license
#include<iostream> #include<vector> // The implementation of this algorithm was made possible // through the use of the textbook: ISBN: 978-0-262-03384-8 // on pages 651 - 653 using namespace std; void bell(vector<int> vert[], int **weight); int v, e; int main(){ int i, j, u, V, w; cin >> v >> e; int **weight = (int**)malloc(v * sizeof(int*)); for(i = 0; i < v; i++){ weight[i] = (int*)malloc(v * sizeof(int)); for(j = 0; j < v; j++) weight[i][j] = INT32_MAX; // Closest number to infinity } vector<int> vert[v]; for(i = 0; i < e; i++){ cin >> u >> V >> w; weight[u][V] = w; vert[u].push_back(V); } bell(vert, weight); return 0; } void bell(vector<int> vert[], int **weight){ int i, j, k, dist[v]; // Initializes distances of bool noCycle = true; long V, UW; for(i = 0; i < v; i++) // each vertex from source dist[i] = INT32_MAX; dist[0] = 0; for(i = 0; i < (v-1); i++){ for(j = 0; j < v; j++){ // for each edge for(k = 0; k < vert[j].size(); k++){ V = dist[vert[j][k]]; UW = (long)dist[j] + (long)weight[j][vert[j][k]]; if(V > UW) // Relax dist[vert[j][k]] = dist[j] + weight[j][vert[j][k]]; } } } for(i = 0; i < v; i++){ for(j = 0; j < vert[i].size(); j++){ V = dist[vert[i][j]]; UW = (long)dist[i] + (long)weight[i][vert[i][j]]; if(V > UW){ noCycle = false; break; } } if(!noCycle) break; } if(!noCycle) cout << "FALSE" << endl; else{ cout << "TRUE" << endl; for(i = 0; i < v; i++){ if(dist[i] == INT32_MAX) cout << "INFINITY" << endl; else cout << dist[i] << endl; } } }
true
df6ff031eb1d33a378abb25c1d94a0b25bd2a749
C++
xuanjianwu/KAVI
/KAVI/utils/GraphClass.cpp
UTF-8
9,304
2.546875
3
[]
no_license
#include "GraphClass.h" #include "XMLUtils.h" #include "EdgeStructure.h" using namespace XMLUtils; using namespace KAVIGraph; GraphClass::GraphClass(QDomElement diagram) { graphData = diagram; igraph_empty(graph, 0, false); } GraphClass::~GraphClass() { igraph_destroy(graph); } bool GraphClass::init(char nodeMask, char edgeMask, bool directed) { QList<EdgeDefinition> edgeList = selectEdges(graphData, edgeMask); int edgeCnt = edgeList.size(); if (edgeCnt == 0) qDebug() << "$GraphClass::init : no edges in diagram"; igraph_vector_t edgeVect; igraph_vector_init(edgeVect, edgeCnt * 2); QList<int> nodes = selectNodeIDList(graphData, nodeMask); if ( nodes.count() == 0 ) { qDebug() << "$GraphClass::init : no nodes in diagram"; return false; } igraph_destroy(graph); igraph_empty(graph, nodes.count(), directed); for (int i = 0; i < nodes.count(); ++i) { // vertex's ID in graph start from 0 idMap.insert(nodes.at(i), i); } for (int i = 0; i < edgeCnt; ++i) { edgeVect[2*i] = idMap.value(edgeList.at(i).first); edgeVect[2*i+1] = idMap.value(edgeList.at(i).second); } igraph_add_edges(graph, edgeVect, 0); igraph_vector_destroy(edgeVect); directedHasCycle = false; return true; } bool GraphClass::containsCycle() { selectComponentRootNodes(); return directedHasCycle; } int GraphClass::edgeCnt(int nodeID, igraph_neimode_t mode) { igraph_vector_t res; igraph_vector_init(res, 1); igraph_degree(graph, res, igraph_vss_1(graph, (igraph_integer_t)idMap.value(nodeID)), mode, IGRAPH_NO_LOOPS); return (int)res[0]; } QString GraphClass::nodeLabel(int nodeID) const { QDomElement node = findSubelementAttr(graphData, "node", "id", QString().setNum(nodeID)); //Q_ASSERT(!node.isNull()); if (!node.isNull()) { return subelementTagValue(node, "label"); } else { return QString(); } } int GraphClass::nodeParentID(int nodeID) const { igraph_integer_t vertID = idMap.value(nodeID, INVALID_ID); Q_ASSERT(vertID != INVALID_ID); igraph_vector_ptr_t res; igraph_vector_ptr_init(res, 1); igraph_neighborhood(graph, res, igraph_vss_1(graph, vertID), 1, IGRAPH_IN); //igraph_vector_t * parentVect = (igraph_vector_t*) igraph_vector_ptr_e(&res, 0); igraph_vector_t parentVect = (igraph_vector_t) igraph_vector_ptr_e(res, 0); if ( igraph_vector_size(parentVect) > 2) qWarning() << "$GraphClass::nodeParentID : current node has more than one parent node"; if (igraph_vector_size(parentVect) < 2 ) { qDebug() << "$GraphClass::nodeParentID : current node has no parent"; igraph_vector_destroy(parentVect); igraph_vector_ptr_destroy(res); return INVALID_ID; } // the first item in parentVect is the current node itself, get the second item for parent node igraph_integer_t parentID = parentVect[1]; igraph_vector_destroy(parentVect); igraph_vector_ptr_destroy(res); return idMap.key((int)parentID); } void GraphClass::addEdge(int startID, int endID) { igraph_integer_t startVertex = idMap.value(startID, INVALID_ID); igraph_integer_t endVertex = idMap.value(endID, INVALID_ID); Q_ASSERT( (startVertex != INVALID_ID) && (endVertex != INVALID_ID) ); igraph_add_edge(graph, startVertex, endVertex); } void GraphClass::removeEdge(int startID, int endID) { igraph_integer_t startVertex = idMap.value(startID, INVALID_ID); igraph_integer_t endVertex = idMap.value(endID, INVALID_ID); Q_ASSERT( (startVertex != INVALID_ID) && (endVertex != INVALID_ID) ); igraph_delete_edges(graph, startVertex, endVertex); } QStringList GraphClass::pathToRoot(int pathStart) const { Q_ASSERT(pathStart != INVALID_ID); QStringList result; while ( pathStart != INVALID_ID ) { result.append(nodeLabel(pathStart)); pathStart = nodeParentID(pathStart); } return result; } QList<int> GraphClass::childrenNodes(int parent) { // if parent <= 0, get the root vertices'ID with zero in-degree in all graph's connected components if (parent <= 0) { return selectComponentRootNodes(); } // if parent > 0, select children neighbors else { return selectNeighbours(parent); } } QSet<int> GraphClass::getDescendants(int parent) { QSet<int> result; QList<int> queue = childrenNodes(parent); // Breadth-First-Search while( !queue.isEmpty() ) { int descID = queue.takeFirst(); result << descID; queue << childrenNodes(descID); } return result; } void GraphClass::print() { qDebug() << "@GraphClass::print : node cnt:" << (int)igraph_vcount(graph) << "edge cnt:" << (int)igraph_ecount(graph) << '\n'; } QList<int> GraphClass::selectComponentRootNodes() { QList<int> result; directedHasCycle = false; igraph_integer_t vertexCnt = igraph_vcount(graph); igraph_vector_t list; // contains the vertices' ID QStack<igraph_integer_t> vertices; igraph_integer_t i; for (i = 0; i < vertexCnt; ++i) vertices.push(i); if ( igraph_is_directed(graph) ) { qDebug() << "$GraphClass::selectComponentRootNodes : select the " "root vertices'ID with zero in-degree of all graph's " "connected components for directed graph"; // contains the in-degree of vertices igraph_vector_t degrees; igraph_vector_init(degrees, vertexCnt); igraph_degree(graph, degrees, igraph_vss_all(graph), IGRAPH_IN, IGRAPH_NO_LOOPS); /* QMap<int, int>::iterator a; for(a = idMap.begin(); a != idMap.end(); a++) { QVector<int> temp, temp2; temp2.push_back(a.value()); igraph_degree(graph, temp, temp2, IGRAPH_IN, IGRAPH_NO_LOOPS); qWarning() << "nodeID: " << a.key() << " vertexID: " << a.value() << " label: " << nodeLabel(a.key()) << " in degree: " << temp[0]; } foreach (int temp, vertices) { qWarning() << temp; } foreach (int temp, degrees) { qWarning() << temp; } */ igraph_integer_t rootVertex; // the minimum in-degree of current component igraph_integer_t minimum; while (!vertices.isEmpty()) { rootVertex = vertices.pop(); minimum = igraph_vector_e(degrees, rootVertex); igraph_vector_init(list, 0); igraph_subcomponent(graph, list, rootVertex, IGRAPH_ALL); igraph_integer_t listLength = igraph_vector_size(list); for (i = 0; i < listLength; ++i) { igraph_integer_t actID = igraph_vector_e(list, i); if (actID == rootVertex) continue; igraph_integer_t inputDeg = igraph_vector_e(degrees, actID); // remove the vertex in the same component with rootVertex vertices.remove(vertices.indexOf(actID)); // update the minimum in-degree in current component if (inputDeg < minimum) { minimum = inputDeg; rootVertex = actID; } } if (minimum == 0) { qDebug() << "$The root vertex with zero in-degree of current component"; result.append(idMap.key(rootVertex)); } else { qWarning() << "$GraphClass::selectComponentRootNodes : graph contains a cycle"; directedHasCycle = true; } igraph_vector_destroy(list); } igraph_vector_destroy(degrees); } else { qDebug() << "$GraphClass::selectComponentRootNodes : select the random" "root vertices'ID of all graph's connected components for " "undirected graph"; while (!vertices.isEmpty()) { igraph_integer_t someVertex = vertices.pop(); result.append(idMap.key(someVertex)); igraph_vector_init(list, 0); igraph_subcomponent(graph, list, someVertex, IGRAPH_ALL); for (i = 0; i < igraph_vector_size(list); ++i) { igraph_integer_t actID = igraph_vector_e(list, i); if (actID == someVertex) continue; vertices.remove(vertices.indexOf(actID)); } igraph_vector_destroy(list); } } return result; } QList<int> GraphClass::selectNeighbours(int parent) { QList<int> result; igraph_integer_t i; igraph_integer_t parentVertex = idMap.value(parent); igraph_vector_t neighbours; igraph_vector_init(neighbours, 0); igraph_neighbors(graph, neighbours, parentVertex, IGRAPH_OUT); for (i = 0; i < igraph_vector_size(neighbours); ++i) { igraph_integer_t actID = igraph_vector_e(neighbours, i); result.append(idMap.key(actID)); } igraph_vector_destroy(neighbours); return result; }
true
56b57596c775ff6035b3e1acfdc618988e7f2f72
C++
Imammulh/Belajara-bahasa-C
/itung2an.cpp
UTF-8
95
2.515625
3
[]
no_license
#include <iostream> using namespace std; int main() {int A,B,T; A=6; B=8; T=A*B; cout << T; }
true
dd1d3f5f725e7551964072dfe162d54557670b49
C++
rafy13/Competitive-Programming
/UVa/uva-12468 - Zapping.cpp
UTF-8
367
2.640625
3
[]
no_license
#include<stdio.h> #include<algorithm> using namespace std; int main() { int a,b,t1,t2; while(scanf("%d%d",&a,&b)==2) { if(a==-1) break; if(a>b) swap(a,b); t1=b-a; t2=99-b+a+1; if(t1<t2) printf("%d\n",t1); else printf("%d\n",t2); } return 0; }
true
dde8a390259c80d4be859c10b523ce72858f23cf
C++
WhiZTiM/coliru
/Archive2/8b/e78a8962c2deaa/main.cpp
UTF-8
1,432
3.078125
3
[]
no_license
#include <fstream> #include <iostream> #include <memory> #include <chrono> int main() { const char TAB = '\t' ; // values to be written into one line in the file // in the actual program, these would be the calculated values // volatile, because we do not want any super-smart optimization volatile double x[] = { 1.2345, 1.2345, 1.2345, 1.2345, 1.2345, 1.2345, 1.2345 }; using clock = std::chrono::steady_clock ; using msecs = std::chrono::milliseconds ; using std::chrono::duration_cast ; // for the actual tests, make this larger, say 1024*1024 const int NLINES = 1024 * 64 ; std::size_t sz = 1024 ; for( int i = 0 ; i < 10 ; ++i, sz *= 2 ) { // allocate memory for the stream buffer std::unique_ptr< char[] > buf( new char[sz] ) ; std::cout << "buffer size: " << sz ; std::ofstream file ; file.rdbuf()->pubsetbuf( buf.get(), sz ) ; // set the buffer file.open( "test.txt" ) ; // and then open the file auto start = clock::now() ; for( int i = 0 ; i < NLINES ; ++i ) { for( auto d : x ) file << d << TAB ; file << '\n' ; } file << std::flush ; auto end = clock::now() ; std::cout << " elapsed: " << duration_cast<msecs>(end-start).count() << " milliseconds.\n" ; } }
true
8e203d406ab9a67d0680079d90f2f215937ce1de
C++
anhvvcs/corana
/libs/z3/src/smt/old_interval.h
UTF-8
7,510
2.625
3
[ "MIT" ]
permissive
/*++ Copyright (c) 2006 Microsoft Corporation Module Name: old_interval.h Abstract: Old interval class. It is still used in some modules. Author: Leonardo de Moura (leonardo) 2008-12-09. Revision History: --*/ #ifndef OLD_INTERVAL_H_ #define OLD_INTERVAL_H_ #include "util/rational.h" #include "util/dependency.h" class ext_numeral { public: enum kind { MINUS_INFINITY, FINITE, PLUS_INFINITY }; private: kind m_kind; rational m_value; explicit ext_numeral(kind k):m_kind(k) {} public: ext_numeral():m_kind(FINITE) {} /* zero */ explicit ext_numeral(bool plus_infinity):m_kind(plus_infinity ? PLUS_INFINITY : MINUS_INFINITY) {} explicit ext_numeral(rational const & val):m_kind(FINITE), m_value(val) {} explicit ext_numeral(int i):m_kind(FINITE), m_value(i) {} ext_numeral(ext_numeral const & other):m_kind(other.m_kind), m_value(other.m_value) {} bool is_infinite() const { return m_kind != FINITE; } bool sign() const { return m_kind == MINUS_INFINITY || (m_kind == FINITE && m_value.is_neg()); } void neg(); bool is_zero() const { return m_kind == FINITE && m_value.is_zero(); } bool is_neg() const { return sign(); } bool is_pos() const { return !is_neg() && !is_zero(); } rational const & to_rational() const { SASSERT(!is_infinite()); return m_value; } ext_numeral & operator+=(ext_numeral const & other); ext_numeral & operator-=(ext_numeral const & other); ext_numeral & operator*=(ext_numeral const & other); void inv(); void expt(unsigned n); void display(std::ostream & out) const; friend bool operator==(ext_numeral const & n1, ext_numeral const & n2); friend bool operator<(ext_numeral const & n1, ext_numeral const & n2); }; bool operator==(ext_numeral const & n1, ext_numeral const & n2); bool operator<(ext_numeral const & n1, ext_numeral const & n2); inline bool operator!=(ext_numeral const & n1, ext_numeral const & n2) { return !operator==(n1,n2); } inline bool operator>(ext_numeral const & n1, ext_numeral const & n2) { return operator<(n2, n1); } inline bool operator<=(ext_numeral const & n1, ext_numeral const & n2) { return !operator>(n1, n2); } inline bool operator>=(ext_numeral const & n1, ext_numeral const & n2) { return !operator<(n1, n2); } inline ext_numeral operator+(ext_numeral const & n1, ext_numeral const & n2) { return ext_numeral(n1) += n2; } inline ext_numeral operator-(ext_numeral const & n1, ext_numeral const & n2) { return ext_numeral(n1) -= n2; } inline ext_numeral operator*(ext_numeral const & n1, ext_numeral const & n2) { return ext_numeral(n1) *= n2; } inline std::ostream & operator<<(std::ostream & out, ext_numeral const & n) { n.display(out); return out; } class old_interval { v_dependency_manager & m_manager; ext_numeral m_lower; ext_numeral m_upper; bool m_lower_open; bool m_upper_open; v_dependency * m_lower_dep; // justification for the lower bound v_dependency * m_upper_dep; // justification for the upper bound v_dependency * join(v_dependency * d1, v_dependency * d2) { return m_manager.mk_join(d1, d2); } v_dependency * join(v_dependency * d1, v_dependency * d2, v_dependency * d3) { return m_manager.mk_join(m_manager.mk_join(d1, d2), d3); } v_dependency * join(v_dependency * d1, v_dependency * d2, v_dependency * d3, v_dependency * d4); v_dependency * join_opt(v_dependency * d1, v_dependency * d2, v_dependency * opt1, v_dependency * opt2); public: explicit old_interval(v_dependency_manager & m); explicit old_interval(v_dependency_manager & m, rational const & lower, bool l_open, v_dependency * l_dep, rational const & upper, bool u_open, v_dependency * u_dep); explicit old_interval(v_dependency_manager & m, rational const & val, v_dependency * l_dep = nullptr, v_dependency * u_dep = nullptr); explicit old_interval(v_dependency_manager & m, rational const & val, bool open, bool lower, v_dependency * d); explicit old_interval(v_dependency_manager & m, ext_numeral const& lower, bool l_open, v_dependency * l_dep, ext_numeral const & upper, bool u_open, v_dependency * u_dep); old_interval(old_interval const & other); bool minus_infinity() const { return m_lower.is_infinite(); } bool plus_infinity() const { return m_upper.is_infinite(); } bool is_lower_open() const { return m_lower_open; } bool is_upper_open() const { return m_upper_open; } v_dependency * get_lower_dependencies() const { return m_lower_dep; } v_dependency * get_upper_dependencies() const { return m_upper_dep; } rational const & get_lower_value() const { SASSERT(!minus_infinity()); return m_lower.to_rational(); } rational const & get_upper_value() const { SASSERT(!plus_infinity()); return m_upper.to_rational(); } old_interval & operator=(old_interval const & other); old_interval & operator+=(old_interval const & other); old_interval & operator-=(old_interval const & other); old_interval & operator*=(old_interval const & other); old_interval & operator*=(rational const & value); old_interval & operator/=(old_interval const & other); bool operator==(old_interval const & other) const { return m_lower == other.m_lower && m_upper == other.m_upper && m_lower_open == other.m_lower_open && m_upper_open == other.m_upper_open; } bool contains_zero() const; bool contains(rational const& v) const; old_interval & inv(); void expt(unsigned n); void neg(); void display(std::ostream & out) const; void display_with_dependencies(std::ostream & out) const; bool is_P() const { return m_lower.is_pos() || m_lower.is_zero(); } bool is_P0() const { return m_lower.is_zero() && !m_lower_open; } bool is_P1() const { return m_lower.is_pos() || (m_lower.is_zero() && m_lower_open); } bool is_N() const { return m_upper.is_neg() || m_upper.is_zero(); } bool is_N0() const { return m_upper.is_zero() && !m_upper_open; } bool is_N1() const { return m_upper.is_neg() || (m_upper.is_zero() && m_upper_open); } bool is_M() const { return m_lower.is_neg() && m_upper.is_pos(); } bool is_zero() const { return m_lower.is_zero() && m_upper.is_zero(); } ext_numeral const& inf() const { return m_lower; } ext_numeral const& sup() const { return m_upper; } }; inline old_interval operator+(old_interval const & i1, old_interval const & i2) { return old_interval(i1) += i2; } inline old_interval operator-(old_interval const & i1, old_interval const & i2) { return old_interval(i1) -= i2; } inline old_interval operator*(old_interval const & i1, old_interval const & i2) { return old_interval(i1) *= i2; } inline old_interval operator/(old_interval const & i1, old_interval const & i2) { return old_interval(i1) /= i2; } inline old_interval expt(old_interval const & i, unsigned n) { old_interval tmp(i); tmp.expt(n); return tmp; } inline std::ostream & operator<<(std::ostream & out, old_interval const & i) { i.display(out); return out; } struct interval_detail{}; inline std::pair<old_interval, interval_detail> wd(old_interval const & i) { interval_detail d; return std::make_pair(i, d); } inline std::ostream & operator<<(std::ostream & out, std::pair<old_interval, interval_detail> const & p) { p.first.display_with_dependencies(out); return out; } // allow "customers" of this file to keep using interval #define interval old_interval #endif /* OLD_INTERVAL_H_ */
true
7a8eb2e703d2fe44870257bc7d2b936c66f62e55
C++
WeiyiGeek/Study-Promgram
/C++/第六节/classdemo.cpp
GB18030
530
4.1875
4
[]
no_license
#include <iostream> /** Class Objectʼ֤ **/ // class Person{ public: // std::string name; //ԭ void cook(void); }; //ж巽 void Person::cook(void){ std::cout << "Һܺóԣ" << std::endl; } int main(void){ //ʵ -> Person girl; //Ըֵ girl.name = "С"; std::cout << "Name : " << girl.name << std::endl; //󷽷 girl.cook(); return 0; }
true
12a96767c26fc234f570366dd8b16906075e8d1a
C++
toth7667/h5cpp
/examples/reference/reference.cpp
UTF-8
2,060
2.703125
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "NCSA", "LicenseRef-scancode-hdf5", "LicenseRef-scancode-llnl", "LicenseRef-scancode-hdf4" ]
permissive
#include <armadillo> #include <vector> #include <h5cpp/all> int main(){ h5::fd_t fd = h5::create("ref.h5", H5F_ACC_TRUNC); { h5::ds_t ds = h5::create<float>(fd,"01", h5::current_dims{10,20}, h5::chunk{2,2} | h5::fill_value<float>{1} ); h5::reference_t ref = h5::reference(fd, "01", h5::offset{2,2}, h5::count{4,4}); h5::write(fd, "single reference", ref); /* you can factor out `count` this way : h5::count count{2,2}; */ std::vector<h5::reference_t> idx { // The HDF5 CAPI reqires fd + dataset name, instead of hid_t to ds: wishy-washy h5::reference(fd, "01", h5::offset{2,2}, h5::count{4,4}), h5::reference(fd, "01", h5::offset{4,8}, h5::count{1,1}), h5::reference(fd, "01", h5::offset{6,12}, h5::count{3,3}), h5::reference(fd, "01", h5::offset{8,16}, h5::count{2,1}) }; // datset shape can be controlled with dimensions, in this case is 2x2 // and is not related to the selected regions!!! // data type is H5R_DATASET_REGION when dataspace is provided, otherwise OBJECT h5::write(fd, "index", idx, h5::current_dims{2,2}, h5::max_dims{H5S_UNLIMITED, 2}); } { // we going to update the regions referenced by the set of region-references // stored in "index" h5::ds_t ds = h5::open(fd, "index"); std::vector color(50, 9); // this is to read from selection for(auto& ref: h5::read<std::vector<h5::reference_t>>(ds)) h5::exp::write(ds, ref, color.data()); } { // we are reading back data from the regions, now they all must be 'color' value '9' h5::ds_t ds = h5::open(fd, "index"); // this is to read from selection for(auto& ref: h5::read<std::vector<h5::reference_t>>(ds)){ arma::fmat mat = h5::exp::read<arma::fmat>(ds, ref); std::cout << mat << "\n"; } } { // for verification std::cout << h5::read<arma::fmat>(fd, "01") << "\n\n"; } }
true