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
8f5ab95e617b6fcffd86a7abcf27fd48750e4328
C++
louisfghbvc/Leetcode
/Two Pointers/777. [Like] Swap Adjacent in LR String.cpp
UTF-8
1,017
3.25
3
[]
no_license
// record index, and is easy to calculate the L must can be sliding // also R // O(N) class Solution { public: // start = {(R, 0), (L, 3), (R, 4), (R, 6), (L, 8) } // end = {(R, 1), (L, 2), (R, 5), (R, 6), (L, 7) } vector<pair<char, int>> filterLR(string &s){ vector<pair<char, int>> res; for(int i = 0; i < s.size(); ++i){ if(s[i] == 'L' || s[i] == 'R') res.push_back({s[i], i}); } return res; } bool canTransform(string start, string end) { auto a = filterLR(start); auto b = filterLR(end); if(a.size() != b.size()) return false; for(int i = 0; i < a.size(); ++i){ if(b[i].first != a[i].first) return false; if(b[i].first == 'R'){ if(a[i].second > b[i].second) return false; } else{ if(a[i].second < b[i].second) return false; } } return true; } };
true
449d434faa80ad33a0b1cd2a6e6cc4632897d045
C++
michaelcullimore/CS1410Lab1
/Project1/roots.cpp
UTF-8
1,113
3.53125
4
[]
no_license
//Michael Cullimore //CS1410 - Brinkerhoff //Lab1 - Roots #include <cmath> #include <conio.h> #include <iostream> using namespace std; int main () { double a, b, c, d, x1, x2; cout << "===***===*** Lab 1 - Roots ***===***===\n"; cout << "A quadratic equation is given as ax^2 + bx + c = 0.\nThis program gives roots for quadratics.\n"; cout << "Enter a number for a: "; cin >> a; cout << "\n"; cout << "Enter a number for b: "; cin >> b; cout << "\n"; cout << "Enter a number for c: "; cin >> c; cout << "\n"; d = (b*b) - (4 * a*c); if (d >= 0) { x1 = (-b + sqrt (d)) / (2 * a); x2 = (-b - sqrt (d)) / (2 * a); cout << "(" << a << ")x^2+(" << b << ")x+(" << c << ")\n"; cout << "The roots of the quadratic equation are x1 = " << x1 << " and x2 = " << x2 <<"\n"; } else { d = d * (-1); cout << "(" << a << ")x^2+(" << b << ")x+(" << c << ")\n"; cout << "These roots are imaginary!\n"; cout << "The roots of the quadratic equation are x1 = " << (-b / (2 * a)) << " + " << (sqrt (d) / (2 * a)) << "i and x2 = " << (-b / (2 * a)) << " - " << (sqrt (d) / (2 * a)) << "\n"; } return 0; }
true
378f2e5db8fe996206285be42e53dcf954eb678b
C++
EinsVision/ModernCpp
/m11_2.cpp
UHC
658
3.125
3
[]
no_license
#include "projects.h" #include "m11_2_Teacher.h" #include "m11_2_Student.h" void Projects_11::m11_2() { // 11.2 ⺻ (2) is-a relationship Teacher t1("Prof. J"); t1.setName("Prof. H"); std::cout << t1.getName() << std::endl; t1.printStatus(); // ü ϴ //Ǽ ߰ ϸ ڽ class ִ. t1.teach(); std::cout << std::endl; Student s1("Jack Jack"); s1.setName("Doljabi"); std::cout << s1.getName() << std::endl; s1.printStatus(); // ü ϴ //Ǽ ߰ ϸ ڽ class ִ. s1.study(); }
true
4e017bcc20291fee54d0e58af9e1b6e6b46e1de3
C++
yvesbou/cpp_course_code
/Exercise05/Task01/Source.cpp
UTF-8
2,507
3.734375
4
[]
no_license
// // Created by Yves Boutellier on 20.11.20. // #include <iostream> #include <string> #include <sstream> #include <regex> #include "pset.h" using namespace std; int main(int argc, char* argv[]) { string dictfile; string textfile; string word; string str; int pos; smatch matches; //match_results for string objects char command; // user defines it string text = ""; regex r; // for words to be replaced regex reg("\\w+"); // for parsing in full words (omitting punctuation) string new_word; ostringstream str_stream; if (argc == 3) { textfile = argv[1]; // the filename of the file containing the text to check dictfile = argv[2]; // the filename of the file containing the dictionary } else if (argc == 2) { textfile = argv[1]; // the filename of the file containing the text to check dictfile = "dict.txt"; } ifstream text_ifs(textfile); str_stream << text_ifs.rdbuf(); //read the file text = str_stream.str(); // text as one string, words get exchanged text_ifs.close(); ifstream ifs(textfile); // for reading words pset<string> dict(dictfile); // creating pset instance for(;;) { ifs >> word; cout << word << endl; if (!ifs.good()) break; // this is to exclude other characters form words. regex_search(word, matches, reg); word = matches[0]; // we check if this word is in the dictionary if (dict.find(word) == dict.end()) { // user decides what to do with this new/misspelled word cout << word << endl; cout << "(a)dd (r)eplace (i)gnore?" << endl; cin >> command; switch (command) { case 'a': dict.insert(word); break; case 'r': cin >> new_word; //pos = text.find(word); //will fail with Kangaroo meat str = word+ "([^\\w+])"; r.assign(str); regex_search(text, matches, r); //check for the first identical occurrence // replace based on position pos = matches.position(); text.replace(pos, word.length(), new_word); break; case 'i': break; } } } ifs.close(); ofstream ofs(textfile); ofs << text; ofs.close(); }
true
d8e1d6953d73bd015016e99ae82e1bef3546f09c
C++
mat-kalinowski/Sorting-Algorithms
/Select/main.cpp
UTF-8
2,388
3.34375
3
[]
no_license
#include <iostream> #include <string.h> #include <string> #include <math.h> #include <stdlib.h> #include "Select.h" #include "RandomSelect.h" #include "MedianSelect.h" using namespace std; void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } void printUsage(){ cout << endl; cout << " USAGE: " << endl; cout << " flag `-p` random permutation of n size set" << endl; cout << " flag `-r` randomized set of n size" << endl; } void print(int *A, int size) { for (int i = 0; i <size; i++){ cerr << A[i] << " "; } cout << endl; } int main(int argc, char *argv[]){ srand (time(NULL)); int size; int stat; int testArray[size]; if(argc == 2){ if(strcmp(argv[1],"-r") == 0){ for(int i = 0; i < size; i ++){ testArray[i] = random()%1000; } } else if(strcmp(argv[1],"-p") == 0){ for(int i =0; i < size; i++){ testArray[i] = i; } for(int i =0; i < size; i++){ swap(testArray[i],testArray[random()%size]); } } else{ printUsage(); return 1; } } else{ printUsage(); return 1; } cin >> size; cin >> stat; print(testArray,size); Select* randomSelect = new RandomSelect(); Select* medianSelect = new MedianSelect(); int arrayCopy1[size]; int arrayCopy2[size]; memcpy(arrayCopy1,testArray,size*sizeof(int)); memcpy(arrayCopy2,testArray,size*sizeof(int)); cout << "(random select) :" << endl; randomSelect->start = clock(); int rsResult = randomSelect->select(arrayCopy1,0,size-1,stat); randomSelect->end = clock(); cout << endl; cout << " K-ta liczba w tablicy to :" << rsResult << endl; cout << " Całkowity czas : " << randomSelect->getTotalTime() << endl; cout << " Liczba porównań : " << randomSelect->getComparisions() << endl; cout << " Liczba przestawień : " << randomSelect->getSwaps() << endl; cout << endl; cout << "(median select) :" << endl; medianSelect->start = clock(); int msResult = medianSelect->select(arrayCopy1,0,size-1,stat); medianSelect->end = clock(); cout << " K-ta liczba w tablicy to :" << msResult << endl; cout << " Całkowity czas : " << medianSelect->getTotalTime() << endl; cout << " Liczba porównań : " << medianSelect->getComparisions() << endl; cout << " Liczba przestawień : " << medianSelect->getSwaps() << endl; }
true
e5ea1eb88f923263a43c5786ea8870ab8fc3802b
C++
intrepid249/Bootstrap-ShooterGame
/ShooterGame/include/Components/AIController.h
UTF-8
842
2.96875
3
[ "MIT" ]
permissive
#pragma once #include <Components\CComponent.h> #include <map> #include <Nodes\Node.h> #include <memory> class IAIState; /** State machine component for the AI controlling mechanics. This is the "brain" behind the AI*/ class AIController : public Node, public CComponent { public: AIController(); ~AIController(); /** Process the current active state*/ void update(float dt); /** Register a new state*/ void addState(const char *name, std::shared_ptr<IAIState> state); /** Set the currently active state*/ void setState(const char *name); /** Function returns a pointer to the matching value mapped to the given index (if found) if no match is found, returns nullptr*/ IAIState *getRegisteredState(const char * name) const; private: std::map<const char *, std::shared_ptr<IAIState>> m_states; IAIState *m_activeState; };
true
f191939f0b1f6158df58f2b04de1ffca5915258b
C++
iwtbam/leetcode
/code/lt1201.cpp
UTF-8
1,073
3.296875
3
[]
no_license
// https://leetcode-cn.com/problems/ugly-number-iii/ // ugly number iii class Solution { public: int nthUglyNumber(int n, int a, int b, int c) { long long lcm_ab = lcm(a, b); long long lcm_bc = lcm(b, c); long long lcm_ac = lcm(a, c); long long lcm_abc = lcm(lcm_ab, c); long long lo = 1; long long hi = 2 * pow(10, 9); // cout << lcm_ab << " " << lcm_bc << " " << lcm_ac << " " << lcm_abc << endl; while(lo <= hi){ long long mid = (lo + hi) >> 1; long long ugly_number = mid / a + mid / b + mid / c - mid / lcm_ab - mid / lcm_bc - mid / lcm_ac + mid / lcm_abc; // if(ugly_number == n) // return mid; if(ugly_number < n) lo = mid + 1; else hi = mid - 1; } return lo; } long long gcd(long long a, long long b){ return a%b == 0 ? b : gcd(b, a%b); } long long lcm(long long a, long long b){ return a * b / gcd(a, b); } };
true
beb8c75cadc07b3cdae01837e0761ed00809d7ec
C++
IvoWams/Engine
/global/Camera.cpp
UTF-8
291
2.71875
3
[]
no_license
#include <global/Camera.h> Camera::Camera(){ position = new Vector(0,0,0); target = new Vector(1,0,0); // just look somewhere } Camera::~Camera(){ delete position; delete target; } Vector* Camera::getPosition(){ return position; } Vector* Camera::getTarget(){ return target; }
true
b0ae93a37b8ce0c204ae2b9829acebc1088f73e6
C++
yzq986/cntt2016-hw1
/TC-SRM-586-div1-250/immortalCO/PiecewiseLinearFunction.cpp
UTF-8
805
2.90625
3
[]
no_license
#include <vector> using namespace std; #define check(a) (tmp = (a)) > ans ? ans = tmp : 0 int n, v[60]; int count(int x) { int ret = 0; for(int i = 1; i <= n - 1; ++i) if((v[i - 1] <= x && x <= v[i]) || (v[i] <= x && x <= v[i - 1])) ++ret; for(int i = 1; i <= n - 2; ++i) if(v[i] == x) --ret; return ret; } class PiecewiseLinearFunction { public: int maximumSolutions(vector<int> _v) { n = _v.size(); for(int i = 0; i != n; ++i) ::v[i] = _v[i] * 2; for(int i = 1; i != n; ++i) if(v[i - 1] == v[i]) return -1; int ans = 0, tmp; for(int i = 0; i != n; ++i) { check(count(v[i])); check(count(v[i] + 1)); check(count(v[i] - 1)); } return ans; } } user;
true
42d2bb2ee4e91cd585242bc005ecba8f94faa408
C++
hehichens/Mini-PhotoShop
/change_background.cpp
UTF-8
5,040
2.515625
3
[ "Apache-2.0" ]
permissive
#include <opencv2/opencv.hpp> //#include <opencv2/xfeatures2d.hpp> //#include<opencv2/face.hpp> #include<iostream> #include<math.h> #include <string> #include<fstream> #include "big_eye.h" // using namespace cv::face; using namespace cv; using namespace std; //using namespace cv::xfeatures2d; /* * Implementation Note: changeBackground * ------------------------- * this method take the image as the input and the chosen color_flag from the user * and then it will change the background of this identification photo to the corresponding * color user choose. * */ Mat changeBackground(Mat image,int color_flag) { Mat src = image; //初始化图片背景的长度与宽度 int width = src.cols; int height = src.rows; int samplecount = width * height; int dims = src.channels(); //行数为src的像素点数,列数为通道数,每列数据分别为src的bgr,从上到下 从左到右顺序读数据,把数据读取后传递给“points” Mat points(samplecount, dims, CV_32F, Scalar(10)); int ind = 0; for (int row = 0; row < height; row++) { for (int col = 0; col < width; col++) { ind = row * width + col; Vec3b bgr = src.at<Vec3b>(row, col); points.at<float>(ind, 0) = static_cast<int>(bgr[0]); points.at<float>(ind, 1) = static_cast<int>(bgr[1]); points.at<float>(ind, 2) = static_cast<int>(bgr[2]); } } //运行kmeans 算法 int numCluster = 5; Mat labels; Mat centers; //最多迭代10次 TermCriteria criteria = TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 10, 0.1); kmeans(points, numCluster, labels, criteria, 3, KMEANS_PP_CENTERS, centers); //去背景+遮罩生成 Mat mask = Mat::zeros(src.size(), CV_8UC1); int index = src.rows * 2 + 2;//不取边缘的左上点,往里靠2个位置 int cindex = labels.at<int>(index, 0); int height1 = src.rows; int width1 = src.cols; Mat dst;//人的轮廓周围会有一些杂点,所以需要腐蚀和高斯模糊取干扰 //原始图像拷贝给dst src.copyTo(dst); for (int row = 0; row < height1; row++) { for (int col = 0; col < width1; col++) { index = row * width1 + col; int label = labels.at<int>(index, 0); if (label == cindex) { dst.at<Vec3b>(row, col)[0] = 0; dst.at<Vec3b>(row, col)[1] = 0; dst.at<Vec3b>(row, col)[2] = 0; mask.at<uchar>(row, col) = 0; } else { dst.at<Vec3b>(row, col) = src.at<Vec3b>(row, col); mask.at<uchar>(row, col) = 255;//人脸部分设为白色,以便于下面的腐蚀与高斯模糊 } } } //腐蚀+高斯模糊 Mat k = getStructuringElement(MORPH_RECT, Size(3, 3)); erode(mask, mask, k); GaussianBlur(mask, mask, Size(3, 3), 0, 0); //通道混合 RNG rng(12345); //调整这个来改变颜色 Vec3b color; //填充进背景的颜色 默认白色 调三通道配比改变颜色 if(color_flag == 0){ color[0] = 255;//rng.uniform(0, 255); color[1] = 255;//rng.uniform(0, 255); color[2] = 255;//rng.uniform(0, 255); }else if (color_flag == 1 ) { color[0] = 33;//rng.uniform(0, 255); color[1] = 40;//rng.uniform(0, 255); color[2] = 193;//rng.uniform(0, 255); }else if(color_flag == 2 ){ color[0] = 227;//rng.uniform(0, 255); color[1] = 160;//rng.uniform(0, 255); color[2] = 66;//rng.uniform(0, 255); } Mat result(src.size(), src.type()); double w = 0.0; int b = 0, g = 0, r = 0; int b1 = 0, g1 = 0, r1 = 0; int b2 = 0, g2 = 0, r2 = 0; double time = getTickCount(); for (int row = 0; row < height1; row++) { for (int col = 0; col < width; col++) { int m = mask.at<uchar>(row, col); if (m == 255) { result.at<Vec3b>(row, col) = src.at<Vec3b>(row, col);//前景 } else if (m == 0) { result.at<Vec3b>(row, col) = color; // 背景 } else {//因为高斯模糊的关系,所以mask元素的颜色除了黑白色还有黑白边缘经过模糊后的非黑白值 w = m / 255.0; b1 = src.at<Vec3b>(row, col)[0]; g1 = src.at<Vec3b>(row, col)[1]; r1 = src.at<Vec3b>(row, col)[2]; b2 = color[0]; g2 = color[0]; r2 = color[0]; b = b1 * w + b2 * (1.0 - w); g = g1 * w + g2 * (1.0 - w); r = r1 * w + r2 * (1.0 - w); result.at<Vec3b>(row, col)[0] = b;//最终边缘颜色值 result.at<Vec3b>(row, col)[1] = g; result.at<Vec3b>(row, col)[2] = r; } } } cout << "time=" << (getTickCount() - time) / getTickFrequency() << endl; return result; }
true
576497f4770cef3675bbfdb951ca6e16c1321f06
C++
offscale/liboffkv
/tests/unit_tests.cpp
UTF-8
13,559
2.828125
3
[ "CC0-1.0", "MIT", "Apache-2.0" ]
permissive
#include "test_client_fixture.hpp" #include <liboffkv/liboffkv.hpp> #include <chrono> #include <mutex> #include <thread> #include <iostream> TEST_F(ClientFixture, key_validation_test) { const auto check_key = [](const std::string &path) { liboffkv::Key{path}; }; ASSERT_THROW(check_key(""), liboffkv::InvalidKey); ASSERT_THROW(check_key("/"), liboffkv::InvalidKey); ASSERT_THROW(check_key("mykey"), liboffkv::InvalidKey); ASSERT_NO_THROW(check_key("/mykey")); ASSERT_NO_THROW(check_key("/mykey/child")); ASSERT_THROW(check_key("/каша"), liboffkv::InvalidKey); ASSERT_THROW(check_key("/test\xFF"), liboffkv::InvalidKey); ASSERT_THROW(check_key(std::string("/test\0", 6)), liboffkv::InvalidKey); ASSERT_THROW(check_key(std::string("/test\x01", 6)), liboffkv::InvalidKey); ASSERT_THROW(check_key(std::string("/test\t", 6)), liboffkv::InvalidKey); ASSERT_THROW(check_key(std::string("/test\n", 6)), liboffkv::InvalidKey); ASSERT_THROW(check_key(std::string("/test\x1F", 6)), liboffkv::InvalidKey); ASSERT_THROW(check_key(std::string("/test\x7F", 6)), liboffkv::InvalidKey); ASSERT_THROW(check_key("/zookeeper"), liboffkv::InvalidKey); ASSERT_THROW(check_key("/zookeeper/child"), liboffkv::InvalidKey); ASSERT_THROW(check_key("/zookeeper/.."), liboffkv::InvalidKey); ASSERT_THROW(check_key("/one/two//three"), liboffkv::InvalidKey); ASSERT_THROW(check_key("/one/two/three/"), liboffkv::InvalidKey); ASSERT_THROW(check_key("/one/two/three/."), liboffkv::InvalidKey); ASSERT_THROW(check_key("/one/two/three/.."), liboffkv::InvalidKey); ASSERT_THROW(check_key("/one/./three"), liboffkv::InvalidKey); ASSERT_THROW(check_key("/one/../three"), liboffkv::InvalidKey); ASSERT_THROW(check_key("/one/zookeeper"), liboffkv::InvalidKey); ASSERT_NO_THROW(check_key("/.../.../zookeper")); } TEST_F(ClientFixture, create_large_test) { auto holder = hold_keys("/key"); std::string value(65'000, '\1'); ASSERT_NO_THROW(client->create("/key", value)); ASSERT_THROW(client->create("/key", value), liboffkv::EntryExists); ASSERT_THROW(client->create("/key/child/grandchild", value), liboffkv::NoEntry); ASSERT_NO_THROW(client->create("/key/child", value)); } TEST_F(ClientFixture, create_test) { auto holder = hold_keys("/key"); ASSERT_NO_THROW(client->create("/key", "value")); ASSERT_THROW(client->create("/key", "value"), liboffkv::EntryExists); ASSERT_THROW(client->create("/key/child/grandchild", "value"), liboffkv::NoEntry); ASSERT_NO_THROW(client->create("/key/child", "value")); } TEST_F(ClientFixture, exists_test) { auto holder = hold_keys("/key"); auto result = client->exists("/key"); ASSERT_FALSE(result); client->create("/key", "value"); result = client->exists("/key"); ASSERT_TRUE(result); } TEST_F(ClientFixture, erase_test) { auto holder = hold_keys("/key"); ASSERT_THROW(client->erase("/key"), liboffkv::NoEntry); client->create("/key", "value"); client->create("/key/child", "value"); ASSERT_NO_THROW(client->erase("/key")); ASSERT_FALSE(client->exists("/key")); ASSERT_FALSE(client->exists("/key/child")); } TEST_F(ClientFixture, versioned_erase_test) { auto holder = hold_keys("/key"); int64_t version = client->create("/key", "value"); client->create("/key/child", "value"); ASSERT_NO_THROW(client->erase("/key", version + 1)); ASSERT_TRUE(client->exists("/key")); ASSERT_TRUE(client->exists("/key/child")); ASSERT_NO_THROW(client->erase("/key", version)); ASSERT_FALSE(client->exists("/key")); ASSERT_FALSE(client->exists("/key/child")); } TEST_F(ClientFixture, exists_with_watch_test) { auto holder = hold_keys("/key"); client->create("/key", "value"); std::mutex my_lock; my_lock.lock(); auto thread = std::thread([&my_lock]() mutable { std::lock_guard<std::mutex> lock_guard(my_lock); client->erase("/key"); }); auto result = client->exists("/key", true); my_lock.unlock(); ASSERT_TRUE(result); thread.join(); result.watch->wait(); ASSERT_FALSE(client->exists("/key")); } TEST_F(ClientFixture, create_with_lease_test) { auto holder = hold_keys("/key"); using namespace std::chrono_literals; { auto local_client = liboffkv::open(SERVICE_ADDRESS, "/unitTests"); ASSERT_NO_THROW(local_client->create("/key", "value", true)); std::this_thread::sleep_for(25s); ASSERT_TRUE(client->exists("/key")); } std::this_thread::sleep_for(25s); { auto local_client = liboffkv::open(SERVICE_ADDRESS, "/unitTests"); ASSERT_FALSE(client->exists("/key")); } } TEST_F(ClientFixture, get_test) { auto holder = hold_keys("/key"); ASSERT_THROW(client->get("/key"), liboffkv::NoEntry); int64_t initialVersion = client->create("/key", "value"); liboffkv::GetResult result; ASSERT_NO_THROW(result = client->get("/key")); ASSERT_EQ(result.value, "value"); ASSERT_EQ(result.version, initialVersion); } TEST_F(ClientFixture, set_test) { auto holder = hold_keys("/key"); int64_t initialVersion = client->create("/key", "value"); int64_t version = client->set("/key", "newValue"); client->set("/another", "anything"); auto result = client->get("/key"); ASSERT_GT(version, initialVersion); ASSERT_EQ(result.value, "newValue"); ASSERT_EQ(result.version, version); ASSERT_THROW(client->set("/key/child/grandchild", "value"), liboffkv::NoEntry); ASSERT_NO_THROW(client->set("/key/child", "value")); ASSERT_EQ(client->get("/key/child").value, "value"); } TEST_F(ClientFixture, get_with_watch_test) { auto holder = hold_keys("/key"); client->create("/key", "value"); std::mutex my_lock; my_lock.lock(); auto thread = std::thread([&my_lock]() mutable { std::lock_guard<std::mutex> lock_guard(my_lock); client->set("/key", "newValue"); }); auto result = client->get("/key", true); my_lock.unlock(); ASSERT_EQ(result.value, "value"); result.watch->wait(); thread.join(); ASSERT_EQ(client->get("/key").value, "newValue"); } TEST_F(ClientFixture, cas_test) { auto holder = hold_keys("/key"); ASSERT_THROW(client->cas("/key", "value", 42), liboffkv::NoEntry); auto version = client->create("/key", "value"); liboffkv::CasResult cas_result; liboffkv::GetResult get_result; ASSERT_NO_THROW(cas_result = client->cas("/key", "new_value", version + 1)); ASSERT_FALSE(cas_result); get_result = client->get("/key"); ASSERT_EQ(get_result.version, version); ASSERT_EQ(get_result.value, "value"); ASSERT_NO_THROW(cas_result = client->cas("/key", "new_value", version)); ASSERT_TRUE(cas_result); get_result = client->get("/key"); ASSERT_EQ(get_result.version, cas_result.version); ASSERT_GT(cas_result.version, version); ASSERT_EQ(get_result.value, "new_value"); } TEST_F(ClientFixture, cas_zero_version_test) { auto holder = hold_keys("/key"); liboffkv::CasResult cas_result; liboffkv::GetResult get_result; ASSERT_NO_THROW(cas_result = client->cas("/key", "value")); ASSERT_TRUE(cas_result); ASSERT_NO_THROW(get_result = client->get("/key")); ASSERT_EQ(get_result.value, "value"); ASSERT_EQ(get_result.version, cas_result.version); int64_t version = cas_result.version; ASSERT_NO_THROW(cas_result = client->cas("/key", "new_value")); ASSERT_FALSE(cas_result); ASSERT_NO_THROW(get_result = client->get("/key")); ASSERT_EQ(get_result.value, "value"); ASSERT_EQ(get_result.version, version); } TEST_F(ClientFixture, get_children_test) { auto holder = hold_keys("/key"); ASSERT_THROW(client->get_children("/key"), liboffkv::NoEntry); client->create("/key", "/value"); client->create("/key/child", "/value"); client->create("/key/child/grandchild", "/value"); client->create("/key/hackerivan", "/value"); liboffkv::ChildrenResult result; ASSERT_NO_THROW(result = client->get_children("/key")); ASSERT_TRUE(liboffkv::detail::equal_as_unordered( result.children, {"/key/child", "/key/hackerivan"} )); ASSERT_NO_THROW(result = client->get_children("/key/child")); ASSERT_TRUE(liboffkv::detail::equal_as_unordered( result.children, {"/key/child/grandchild"} )); } TEST_F(ClientFixture, get_children_with_watch_test) { auto holder = hold_keys("/key"); client->create("/key", "value"); client->create("/key/child", "value"); client->create("/key/child/grandchild", "value"); client->create("/key/dimak24", "value"); std::mutex my_lock; my_lock.lock(); auto thread = std::thread([&my_lock]() mutable { std::lock_guard<std::mutex> lock_guard(my_lock); client->erase("/key/dimak24"); }); auto result = client->get_children("/key", true); my_lock.unlock(); ASSERT_TRUE(liboffkv::detail::equal_as_unordered( result.children, {"/key/child", "/key/dimak24"} )); result.watch->wait(); thread.join(); ASSERT_TRUE(liboffkv::detail::equal_as_unordered( client->get_children("/key").children, {"/key/child"} )); } TEST_F(ClientFixture, commit_test) { auto holder = hold_keys("/key", "/foo"); auto key_version = client->create("/key", "value"); auto foo_version = client->create("/foo", "value"); auto bar_version = client->create("/foo/bar", "value"); client->create("/foo/bar/subbar", "value"); // check fails try { client->commit( { { liboffkv::TxnCheck("/key", key_version), liboffkv::TxnCheck("/foo", foo_version + 1), liboffkv::TxnCheck("/foo/bar", bar_version), }, { liboffkv::TxnOpCreate("/key/child", "value"), liboffkv::TxnOpSet("/key", "new_value"), liboffkv::TxnOpErase("/foo"), } } ); FAIL() << "Expected commit to throw TxnFailed, but it threw nothing"; } catch (liboffkv::TxnFailed &e) { ASSERT_EQ(e.failed_op(), 1); } catch (std::exception &e) { FAIL() << "Expected commit to throw TxnFailed, " "but it threw different exception:\n" << e.what(); } ASSERT_FALSE(client->exists("/key/child")); ASSERT_EQ(client->get("/key").value, "value"); ASSERT_TRUE(client->exists("/foo")); // op fails try { client->commit( { { liboffkv::TxnCheck("/key", key_version), liboffkv::TxnCheck("/foo", foo_version), liboffkv::TxnCheck("/foo/bar", bar_version), }, { liboffkv::TxnOpCreate("/key/child", "value"), liboffkv::TxnOpCreate("/key/hackerivan", "new_value"), liboffkv::TxnOpErase("/foo"), // this fails because /key/child/grandchild does not exist liboffkv::TxnOpSet("/key/child/grandchild", "new_value"), liboffkv::TxnOpErase("/asfdsfasdfa"), } } ); FAIL() << "Expected commit to throw TxnFailed, but it threw nothing"; } catch (liboffkv::TxnFailed &e) { ASSERT_EQ(e.failed_op(), 6); } catch (std::exception &e) { FAIL() << "Expected commit to throw TxnFailed, but it threw different exception:\n" << e.what(); } ASSERT_FALSE(client->exists("/key/child")); ASSERT_TRUE(client->exists("/foo")); // everything is OK liboffkv::TransactionResult result; ASSERT_NO_THROW(result = client->commit( { { liboffkv::TxnCheck("/key", key_version), liboffkv::TxnCheck("/foo", foo_version), liboffkv::TxnCheck("/foo/bar", bar_version), }, { liboffkv::TxnOpCreate("/key/child", "value"), liboffkv::TxnOpSet("/key", "new_value"), liboffkv::TxnOpErase("/foo"), } } )); ASSERT_TRUE(client->exists("/key/child")); ASSERT_EQ(client->get("/key").value, "new_value"); ASSERT_FALSE(client->exists("/foo")); ASSERT_FALSE(client->exists("/foo/bar")); ASSERT_FALSE(client->exists("/foo/bar/subbar")); ASSERT_GT(result.at(1).version, key_version); } TEST_F(ClientFixture, erase_prefix_test) { auto holder = hold_keys("/ichi", "/ichinichi"); ASSERT_NO_THROW(client->create("/ichi", "one")); ASSERT_NO_THROW(client->create("/ichinichi", "two")); ASSERT_NO_THROW(client->erase("/ichi")); ASSERT_TRUE(client->exists("/ichinichi")); } TEST_F(ClientFixture, get_prefix_test) { auto holder = hold_keys("/sore", "/sorewanan"); ASSERT_NO_THROW(client->create("/sore", "1")); ASSERT_NO_THROW(client->create("/sore/ga", "2")); ASSERT_NO_THROW(client->create("/sorewanan", "3")); liboffkv::ChildrenResult result; ASSERT_NO_THROW(result = client->get_children("/sore")); ASSERT_TRUE(liboffkv::detail::equal_as_unordered( client->get_children("/sore").children, {"/sore/ga"} )); }
true
b3b43c7aca3e38828802261938b216dc6b3a5b56
C++
yukina0102/Aigis_IR
/src/SqlData.h
UTF-8
3,393
2.84375
3
[]
no_license
#ifndef SQLDATA_H #define SQLDATA_H #include "common.h" typedef class CSqlData * SqlData; typedef class CSqlRecord * SqlRecord; //DB側で指定される型名をプログラム内の型に変換 typedef const int INTEGER; typedef const _TCHAR * TEXT; class CSqlData { public: typedef enum { TYPE_INTEGER = 0, TYPE_TEXT, }ColumnType; private: //CulumnTypeとvariantの中身は一致させておく typedef boost::variant< int, tstring > SqlVar; typedef struct ColumnData { tstring name; ColumnType type; int maxLength; }ColumnData; private: std::vector< ColumnData > Column; std::map< tstring, uint > CIndex; //std::vector< tstring > Data; std::vector< std::vector< SqlVar > > Data; //レコード一時保管用 std::vector< SqlVar > Tmp; public: CSqlData(){} uint ColumnSize(void); uint RecordSize(void); void Show(void); void Clear(void); //カラム、レコードの追加 void AddColumn(LPCTSTR cname, ColumnType ctype); void AddColumn(LPCTSTR cname, LPCTSTR ctype ); void CheckLength(void); //void AddRecord(const SqlRecord record); //レコード一時保管関係 void Begin() { Tmp.clear(); } void Begin( uint num ) { Tmp.clear(); Tmp.resize( num ); } void AddData( boost::variant< int, tstring > data ) { Tmp.push_back( data ); } void Commit() { //レコードデータ数がカラム数と違う場合はデータを追加しない if ( Tmp.size() != Column.size()) return; Data.push_back( Tmp ); //各カラムの最大文字数を保存 CheckLength(); } ColumnType GetColumnType(unsigned int num) { return Column[num].type; } ColumnType GetColumnType(LPCTSTR column) { GetColumnType(CIndex[column]); } tstring getColumnName(uint num) { return Column[num].name; } //データ抽出 template<typename result_t> inline result_t Extract( uint record, LPCTSTR column); template<typename result_t> inline result_t Extract(uint record, uint cnum ); }; template<> inline INTEGER CSqlData::Extract<INTEGER>(unsigned int record, LPCTSTR column) { //指定したカラム if (record >= Data.size() || CIndex.find(column) == CIndex.end()) { return -1; } if (Column[CIndex[column]].type != TYPE_INTEGER ) { return -1; } return boost::get<int>( Data[record][CIndex[column]] ); } template<> inline TEXT CSqlData::Extract<TEXT>(unsigned int record, LPCTSTR column) { //指定したカラム if (record >= Data.size() || CIndex.find(column) == CIndex.end()) { return _T("Data Error"); } if (Column[CIndex[column]].type != TYPE_TEXT) { return _T("Data Error"); } return boost::get<tstring>(Data[record][CIndex[column]]).c_str(); } template<> inline INTEGER CSqlData::Extract<INTEGER>( uint record, uint cnum ) { //指定したカラム if (record >= Data.size() || cnum >= ColumnSize() ) { return -1; } if (Column[cnum].type != TYPE_INTEGER) { return -1; } return boost::get<int>(Data[record][cnum]); } template<> inline TEXT CSqlData::Extract<TEXT>( uint record, uint cnum ) { //指定したカラム if (record >= Data.size() || cnum >= ColumnSize() ) { return _T("Data Error"); } if (Column[cnum].type != TYPE_TEXT) { return _T("Data Error"); } return boost::get<tstring>(Data[record][cnum]).c_str(); } #endif/*SQLDATA_H*/
true
ca20118fbba473669f73cf6ac7b40374222ed293
C++
lydrainbowcat/tedukuri
/配套光盘/例题/0x10 基本数据结构/0x17 二叉堆/数据备份/CTSC2007/BZOJ1150 数据备份.cpp
UTF-8
1,639
2.8125
3
[]
no_license
//Author:XuHt #include <cstdio> #include <iostream> #include <algorithm> using namespace std; const int N = 100006; struct L { int d, prv, nxt, th; } p[N]; struct H { int D, tp; } h[N]; int tot = 0; void up(int i) { while (i > 1) { if (h[i].D < h[i>>1].D) { swap(h[i], h[i>>1]); swap(p[h[i].tp].th, p[h[i>>1].tp].th); i >>= 1; } else return; } } void down(int i) { int ii = i << 1; while (ii <= tot) { if (ii < tot && h[ii].D > h[ii+1].D) ++ii; if (h[ii].D < h[i].D) { swap(h[ii], h[i]); swap(p[h[ii].tp].th, p[h[i].tp].th); i = ii; ii = i << 1; } else return; } } void DeL(int i) { p[p[i].prv].nxt = p[i].nxt; p[p[i].nxt].prv = p[i].prv; } void DeH(int i) { if (i == --tot + 1) return; swap(h[i], h[tot+1]); swap(p[h[i].tp].th, p[h[tot+1].tp].th); up(i); down(i); } int main() { int n, k, pre; cin >> n >> k >> pre; for (int i = 1; i < n; i++) { int w; scanf("%d", &w); p[i].d = w - pre; p[i].prv = i - 1; p[i].nxt = i + 1; p[i].th = ++tot; pre = w; h[tot].D = p[i].d; h[tot].tp = i; up(tot); } int ans = 0; for (int i = 1; i <= k; i++) { ans += h[1].D; if (!p[h[1].tp].prv || p[h[1].tp].nxt == n) { if (!p[h[1].tp].prv) { DeH(p[p[h[1].tp].nxt].th); DeL(p[h[1].tp].nxt); } else { DeH(p[p[h[1].tp].prv].th); DeL(p[h[1].tp].prv); } DeL(h[1].tp); DeH(1); } else { int tp0 = h[1].tp; h[1].D = p[p[h[1].tp].prv].d + p[p[h[1].tp].nxt].d - p[h[1].tp].d; p[h[1].tp].d = h[1].D; down(1); DeH(p[p[tp0].prv].th); DeH(p[p[tp0].nxt].th); DeL(p[tp0].prv); DeL(p[tp0].nxt); } } cout << ans << endl; return 0; }
true
7d51839268f1f69ca3f01ba37cb52851e4d7e24b
C++
Marcotte07/Scrabble
/Scrabble/computer_player.cpp
UTF-8
18,462
3.015625
3
[]
no_license
#include "computer_player.h" #include "exceptions.h" #include "formatting.h" #include "move.h" #include "place_result.h" #include "rang.h" #include "tile_kind.h" #include <algorithm> #include <fstream> #include <iomanip> #include <iostream> #include <map> #include <memory> #include <sstream> #include <stdexcept> #include <string> #include <vector> using namespace std; void ComputerPlayer::left_part( Board::Position anchor_pos, std::string partial_word, Move partial_move, std::shared_ptr<Dictionary::TrieNode> node, size_t limit, TileCollection& remaining_tiles, std::vector<Move>& legal_moves, const Board& board) const { // This function finds all possible starting prefixes for an anchor of size less than or equal to the anchor’s // limit. It does this by searching through the dictionary trie, building possible prefixes based on the tiles still // available. For every prefix that can be made, it should call extend_right with that prefix. Starting at node // root, build all possible combination of prefixes and extend right start at node, for each and every tile in hand // add check if from node there is a path to the next letter, // For all members of the node map, recurse if and only if remaining tiles has that letter // Base case when limit is 0 if (limit == 0) { return; } // Iterate through all members of the map in node std::map<char, std::shared_ptr<Dictionary::TrieNode>>::iterator letterIterator; for (letterIterator = node->nexts.begin(); letterIterator != node->nexts.end(); letterIterator++) { // Add character to partial_word, tile to partial_move if tile is in hand try { TileKind tileInHand = remaining_tiles.lookup_tile(letterIterator->first); // Move needs to be updated to start from where first tile is placed partial_move.tiles.push_back(tileInHand); if (partial_move.direction == Direction::DOWN) { partial_move.row--; } else { partial_move.column--; } partial_word += letterIterator->first; // Remove tile from hand remaining_tiles.remove_tile(tileInHand); // call extend_right for new prefix extend_right( anchor_pos, anchor_pos, partial_word, partial_move, letterIterator->second, remaining_tiles, legal_moves, board); // then recurse to get new prefix, with new node, new limit left_part( anchor_pos, partial_word, partial_move, letterIterator->second, limit - 1, remaining_tiles, legal_moves, board); // Now done with all those prefixes, add tile back to hand and go to next iteration remaining_tiles.add_tile(tileInHand); partial_move.tiles.pop_back(); if (partial_move.direction == Direction::DOWN) { partial_move.row++; } else { partial_move.column++; } partial_word.pop_back(); } catch (std::exception& e) { // Go to next letter in map, only if no blank tiles in hand, if blank tile, then use that as the letter and // do same as above try { TileKind blankInHand = remaining_tiles.lookup_tile('?'); TileKind newTile(letterIterator->first, blankInHand.points); partial_move.tiles.push_back(newTile); if (partial_move.direction == Direction::DOWN) { partial_move.row--; } else { partial_move.column--; } partial_word += letterIterator->first; // Remove tile from hand remaining_tiles.remove_tile(blankInHand); // call extend_right for new prefix extend_right( anchor_pos, anchor_pos, partial_word, partial_move, letterIterator->second, remaining_tiles, legal_moves, board); // then recurse to get new prefix, with new node, new limit left_part( anchor_pos, partial_word, partial_move, letterIterator->second, limit - 1, remaining_tiles, legal_moves, board); // Now done with all those prefixes, add tile back to hand and go to next iteration remaining_tiles.add_tile(blankInHand); partial_move.tiles.pop_back(); if (partial_move.direction == Direction::DOWN) { partial_move.row++; } else { partial_move.column++; } partial_word.pop_back(); } catch (std::exception& e) { } } } } void ComputerPlayer::extend_right( Board::Position square, Board::Position anchor_pos, std::string partial_word, Move partial_move, std::shared_ptr<Dictionary::TrieNode> node, TileCollection& remaining_tiles, std::vector<Move>& legal_moves, const Board& board) const { // Words need to make it back to the anchor position at least, and be final if (node->is_final) { if (partial_move.direction == Direction::ACROSS) { if (partial_move.column + partial_word.size() > anchor_pos.column) { legal_moves.push_back(partial_move); } } else { if (partial_move.row + partial_word.size() > anchor_pos.row) { legal_moves.push_back(partial_move); } } } // BASE CASE if map is empty or if position is out of bounds if (node->nexts.empty() || !board.is_in_bounds(square)) { return; } // TILE ON BOARD IN THAT POSITION if (board.in_bounds_and_has_tile(square)) { // Already a tile on board in that position, if that letter is not in the node->map, then return char c = board.letter_at(square); if (node->nexts.find(c) == node->nexts.end()) { // Not a valid word return; } else { // Add tile and letter to move and word respectively, because it is a valid tile, could be words after partial_word += c; // Recurse again but with new node // Direction is down if (partial_move.direction == Direction::DOWN) { Board::Position newPos(square.row + 1, square.column); extend_right( newPos, anchor_pos, partial_word, partial_move, node->nexts.find(c)->second, remaining_tiles, legal_moves, board); } // Direction is across else { Board::Position newPos(square.row, square.column + 1); extend_right( newPos, anchor_pos, partial_word, partial_move, node->nexts.find(c)->second, remaining_tiles, legal_moves, board); } } } // NO TILE ON BOARD IN THAT POSITION else { std::map<char, std::shared_ptr<Dictionary::TrieNode>>::iterator letterIterator; for (letterIterator = node->nexts.begin(); letterIterator != node->nexts.end(); letterIterator++) { // iterate through map, recurse for each tile just like in left side try { TileKind tileInHand = remaining_tiles.lookup_tile(letterIterator->first); partial_move.tiles.push_back(tileInHand); partial_word += letterIterator->first; // Remove tile from hand remaining_tiles.remove_tile(tileInHand); // call extend_right for new prefix if (partial_move.direction == Direction::DOWN) { Board::Position newPos(square.row + 1, square.column); extend_right( newPos, anchor_pos, partial_word, partial_move, letterIterator->second, remaining_tiles, legal_moves, board); } else { Board::Position newPos(square.row, square.column + 1); extend_right( newPos, anchor_pos, partial_word, partial_move, letterIterator->second, remaining_tiles, legal_moves, board); } // Now done with recursive calls, add tile just removed back to hand and move to next letter in nexts // map remaining_tiles.add_tile(tileInHand); partial_move.tiles.pop_back(); partial_word.pop_back(); } catch (std::exception& e) { // The letter not found in hand, see if blank tile try { TileKind blankInHand = remaining_tiles.lookup_tile('?'); TileKind newTile(letterIterator->first, blankInHand.points); partial_move.tiles.push_back(newTile); partial_word += letterIterator->first; // Remove tile from hand remaining_tiles.remove_tile(blankInHand); // call extend_right for new prefix if (partial_move.direction == Direction::DOWN) { Board::Position newPos(square.row + 1, square.column); extend_right( newPos, anchor_pos, partial_word, partial_move, letterIterator->second, remaining_tiles, legal_moves, board); } else { Board::Position newPos(square.row, square.column + 1); extend_right( newPos, anchor_pos, partial_word, partial_move, letterIterator->second, remaining_tiles, legal_moves, board); } // Now done with recursive calls, add tile just removed back to hand and move to next letter in // nexts map remaining_tiles.add_tile(blankInHand); partial_move.tiles.pop_back(); partial_word.pop_back(); } catch (std::exception& e) { } } } } } Move ComputerPlayer::get_move(const Board& board, const Dictionary& dictionary) const { std::vector<Move> legal_moves; std::vector<Board::Anchor> anchors = board.get_anchors(); board.print(std::cout); print_hand(std::cout); for (size_t i = 0; i < anchors.size(); i++) { // Call left part on each and every anchor, need to initialize a move std::vector<TileKind> tiles; size_t row = anchors[i].position.row; size_t column = anchors[i].position.column; Move buildMove(tiles, row, column, anchors[i].direction); // First move, limit is hand size - 1 if (row == board.start.row && column == board.start.column) { anchors[i].limit = get_hand_size() - 1; } TileCollection copyTiles = this->tiles; // Limit is 0, no call to left_part, find if tiles to left or up (depending on direction) and call extend_right // on that if (anchors[i].limit == 0) { // Build move from tiles already on board std::string partial_word = ""; if (anchors[i].direction == Direction::DOWN) { Board::Position up(row - 1, column); while (board.in_bounds_and_has_tile(up)) { up.row--; } // Now at last position with tile, need to get full string and pass to extend_right up.row++; while (board.in_bounds_and_has_tile(up)) { partial_word = partial_word + board.letter_at(up); up.row++; } } // Direction Across else { Board::Position left(row, column - 1); while (board.in_bounds_and_has_tile(left)) { left.column--; } // Now at last position with tile, need to get full string and pass to extend_right left.column++; while (board.in_bounds_and_has_tile(left)) { partial_word = partial_word + board.letter_at(left); left.column++; } } // Now have prefix in partial_word, need to make sure its valid in trie before passing to extend_right if (dictionary.find_prefix(partial_word) != nullptr) { extend_right( anchors[i].position, anchors[i].position, partial_word, buildMove, dictionary.find_prefix(partial_word), copyTiles, legal_moves, board); } } // Limit is not 0, need to get all valid prefixes before extending right else { left_part( anchors[i].position, "", buildMove, dictionary.find_prefix(""), anchors[i].limit, copyTiles, legal_moves, board); } } return get_best_move(legal_moves, board, dictionary); } Move ComputerPlayer::get_best_move( std::vector<Move> legal_moves, const Board& board, const Dictionary& dictionary) const { Move best_move = Move(); // Pass if no move found size_t mostPoints = 0; for (size_t i = 0; i < legal_moves.size(); i++) { // test place all moves on board to find which has most points PlaceResult testPlace = board.test_place(legal_moves[i]); // Need to check if all words formed in testPlace are valid, if so then valid move bool validPlace = true; for (size_t j = 0; j < testPlace.words.size(); j++) { if (!dictionary.is_word(testPlace.words[j])) { validPlace = false; } } if (testPlace.points > mostPoints && validPlace && legal_moves[i].tiles.size() >= 2) { mostPoints = testPlace.points; best_move = legal_moves[i]; } // First move, make it start at center if (!board.in_bounds_and_has_tile(board.start)) { best_move.row = board.start.row; best_move.column = board.start.column; best_move.direction = Direction::ACROSS; } } return best_move; } void ComputerPlayer::print_hand(std::ostream& out) const { const size_t tile_count = tiles.count_tiles(); const size_t empty_tile_count = this->get_hand_size() - tile_count; const size_t empty_tile_width = empty_tile_count * (SQUARE_OUTER_WIDTH - 1); for (size_t i = 0; i < HAND_TOP_MARGIN - 2; ++i) { out << endl; } out << repeat(SPACE, HAND_LEFT_MARGIN) << FG_COLOR_HEADING << "Your Hand: " << endl << endl; // Draw top line out << repeat(SPACE, HAND_LEFT_MARGIN) << FG_COLOR_LINE << BG_COLOR_NORMAL_SQUARE; print_horizontal(tile_count, L_TOP_LEFT, T_DOWN, L_TOP_RIGHT, out); out << repeat(SPACE, empty_tile_width) << BG_COLOR_OUTSIDE_BOARD << endl; // Draw middle 3 lines for (size_t line = 0; line < SQUARE_INNER_HEIGHT; ++line) { out << FG_COLOR_LABEL << BG_COLOR_OUTSIDE_BOARD << repeat(SPACE, HAND_LEFT_MARGIN); for (auto it = tiles.cbegin(); it != tiles.cend(); ++it) { out << FG_COLOR_LINE << BG_COLOR_NORMAL_SQUARE << I_VERTICAL << BG_COLOR_PLAYER_HAND; // Print letter if (line == 1) { out << repeat(SPACE, 2) << FG_COLOR_LETTER << (char)toupper(it->letter) << repeat(SPACE, 2); // Print score in bottom right } else if (line == SQUARE_INNER_HEIGHT - 1) { out << FG_COLOR_SCORE << repeat(SPACE, SQUARE_INNER_WIDTH - 2) << setw(2) << it->points; } else { out << repeat(SPACE, SQUARE_INNER_WIDTH); } } if (tiles.count_tiles() > 0) { out << FG_COLOR_LINE << BG_COLOR_NORMAL_SQUARE << I_VERTICAL; out << repeat(SPACE, empty_tile_width) << BG_COLOR_OUTSIDE_BOARD << endl; } } // Draw bottom line out << repeat(SPACE, HAND_LEFT_MARGIN) << FG_COLOR_LINE << BG_COLOR_NORMAL_SQUARE; print_horizontal(tile_count, L_BOTTOM_LEFT, T_UP, L_BOTTOM_RIGHT, out); out << repeat(SPACE, empty_tile_width) << rang::style::reset << endl; }
true
4b7a57042e2dec2a4e2d5c20e3e94acc10b9f68b
C++
dannosliwcd/PointQuery
/src/CountyRecord.h
UTF-8
590
2.875
3
[ "MIT" ]
permissive
#ifndef COUNTYRECORD_H #define COUNTYRECORD_H #include <string> #include <iosfwd> struct CountyRecord { std::string m_state; std::string m_county; float m_latitude; float m_longitude; static CountyRecord FromString(const std::string& countyRecordString); static void CheckValidHeader(const std::string& countyRecordString); }; bool operator==(const CountyRecord& lhs, const CountyRecord& rhs); bool operator!=(const CountyRecord& lhs, const CountyRecord& rhs); std::ostream& operator<<(std::ostream& os, const CountyRecord& record); #endif //COUNTYRECORD_H
true
7b2e4c692d8b9dec179e0661b79eec34d5a097eb
C++
alexandraback/datacollection
/solutions_5756407898963968_0/C++/beerscout/A.cpp
UTF-8
1,071
3.296875
3
[]
no_license
#include <array> #include <iostream> #include <algorithm> typedef std::array<int, 4> Guess; Guess read_guess() { int row; std::cin >> row; for ( int i = 1; i < row; ++i ) for ( int j = 1; j <= 4; ++j ) { int dummy; std::cin >> dummy; } Guess r; for ( int i = 0; i != 4; ++i ) std::cin >> r[i]; for ( int i = row + 1; i <= 4; ++i ) for ( int j = 1; j <= 4; ++j ) { int dummy; std::cin >> dummy; } return r; } void run_case(int case_no) { Guess g1 = read_guess(); std::sort(g1.begin(), g1.end()); Guess g2 = read_guess(); std::sort(g2.begin(), g2.end()); Guess cand; auto e = std::set_intersection(g1.begin(), g1.end(), g2.begin(), g2.end(), cand.begin()); std::cout << "Case #" << case_no << ": "; if ( e == cand.begin() ) std::cout << "Volunteer cheated!\n"; else if ( e != cand.begin() + 1 ) std::cout << "Bad magician!\n"; else std::cout << cand[0] << '\n'; } int main() { int T; std::cin >> T; for ( int i = 1; i <= T; ++i ) run_case(i); return 0; }
true
682216f9e9d4d1b0ebce9a995f87fabdae443666
C++
doitliao/algorithms
/notebook/geometry_2d.cc
UTF-8
4,338
3.546875
4
[]
no_license
#include <cmath> #include <vector> #include <iostream> using namespace std; namespace geometry{ template < typename T> class Point{ public: T x,y; Point():x(0), y(0){} Point(T x, T y):x(x), y(y){} Point operator+(const Point& rhs){ return Point(x + rhs.x, y + rhs.y); } Point operator-(const Point& rhs){ return Point(x - rhs.x, y - rhs.y); } T operator*(const Point& rhs){ return x * rhs.x + y * rhs.y; } T operator^(const Point& rhs){ return x * rhs.y - y * rhs.x; } }; //Compute the dot product AB * BC template<typename T> T dot(Point<T>& A, Point<T>& B, Point<T>& C){ return (B - A) * (C - B); } //Compute the cross product AB x AC template<typename T> T cross(Point<T>& A, Point<T>& B, Point<T>& C){ return (B - A) ^ (C - A); } //Compute the distance from A to B template<typename T> double distance(Point<T>& A, Point<T>& B){ int dx = B.x - A.x; int dy = B.y - A.y; return sqrt(dx * dx + dy * dy); } //Compute the distance from C to AB //if isSegment is true, AB is a segment, not a line. template<typename T> double linePointDistance(Point<T>& A, Point<T>& B, Point<T>& C, bool isSegment = false){ double dist = cross(A, B, C) / distance(A, B); if(!isSegment)return dist; //isSegment is true. if(0 < dot(A, B, C)) return distance(B, C); if(0 < dot(B, A, C)) return distance(A, C); return dist; } //Compute the area of th ploygon. template<typename T> double polygon(std::vector<Point<T> >& p){ int area = 0; const int N = p.size(); //We will triangulate the polygon //into triangles with points p[0], p[i], p[i+1] for(int i = 1; i + 1 < N; i++){ area += cross(p[0], p[i], p[i + 1]); } return std::abs(area / 2.0); } template <typename T> class Line{ public: Line(T A, T B, T C):A(A), B(B), C(C){} Line(const Point<T> & X, const Point<T> & Y){ A = Y.y - X.y; B = X.x - Y.x; C = A * X.x + B * X.y; } //Find the prependicular bisector of XY static Line perpendicularBisector(const Point<T> & X, const Point<T> & Y){ T a = Y.y - X.y; T b = X.x - Y.x; T c = -1 * b * X.x + a * X.y; return Line(-1 * b, a, c); } public: T A, B, C; }; //Compute the intersection point of line X and Y template <typename T> bool lineIntersection(const Line<T> & X, const Line<T> & Y, Point<double>& P){ double det = X.A * Y.B - Y.A * X.B; if(det == 0)return false; // Lines are parallel P.x = (Y.B * X.C - X.B * Y.C) / det; P.y = (X.A * Y.C - Y.A * X.C) / det; return true; } //Compute intersection of line AB and CD template <typename T> bool lineIntersection(const Point<T>& A, const Point<T>& B, const Point<T>& C, const Point<T>& D, Point<double>& P, bool isSegment){ Line<T> X(A, B); Line<T> Y(C, D); if(false == lineIntersection(X, Y, P))return false; if(!isSegment) return true; if(isSegment){ if( P.x < min(A.x, B.x) || P.x > max(A.x, B.x))return false; if( P.x < min(C.x, D.x) || P.x > max(C.x, D.x))return false; if( P.y < min(A.y, B.y) || P.y > max(A.y, B.y))return false; if( P.y < min(C.y, D.y) || P.y > max(C.y, D.y))return false; } return true; } template <typename T> class Circle{ public: Circle(){} Circle(const Point<T>& C, T r){ center.x = C.x; center.y = C.y; radius = r; } public: Point<T> center; T radius; }; //Finding a Circle From 3 Points template <typename T> bool findCircle(const Point<T> & X, const Point<T>& Y, const Point<T> & Z, Circle<T>& C){ Line<T> a = Line<T>::perpendicularBisector(X, Y); Line<T> b = Line<T>::perpendicularBisector(Y, Z); Point<T> center; if(false == lineIntersection(a, b, center))return false; double radius = distance(center, X); } }; using namespace geometry; int main(){ std::vector<geometry::Point<int> > p; p.push_back(geometry::Point<int> (0, 0)); p.push_back(geometry::Point<int> (2, 0)); p.push_back(geometry::Point<int> (2, 3)); //p.push_back(geometry::Point(0, 3)); std::cout<<geometry::polygon(p)<<std::endl; Point<int> A(0, 0); Point<int> B(3, 3); Point<int> C(6, 2); Point<int> D(5, 0); Point<double> P; cout<<lineIntersection(A, B, C, D, P, true)<<endl; cout<<"P: "<<P.x<<" "<<P.y<<endl; cout<<linePointDistance(A, C, B)<<endl; cout<<linePointDistance(A, C, D)<<endl; }
true
15a16f8c4ea196a05046801ff10edd7b7b713bcd
C++
dmitry64/evolution-system
/simulationsystem.cxx
UTF-8
2,160
2.796875
3
[]
no_license
#include "simulationsystem.hpp" SimulationSystem::SimulationSystem() {} SimulationSystem::~SimulationSystem() { waitForSimulation(); } void SimulationSystem::init() {} void SimulationSystem::runSimulation() { std::cout << "Simulation start..." << std::endl; _hasWork.store(true); _actorsAccessMutex.unlock(); _actors.push(std::make_shared<Actor>()); _actors.push(std::make_shared<Actor>()); _actors.push(std::make_shared<Actor>()); _actors.push(std::make_shared<Actor>()); _actors.push(std::make_shared<Actor>()); _actors.push(std::make_shared<Actor>()); _actors.push(std::make_shared<Actor>()); for (int i = 0; i < 666; ++i) { std::shared_ptr<Actor> actor(new Actor()); _actors.push(actor); } _threads.emplace_back([this]() { this->simulationWorker(); }); _threads.emplace_back([this]() { this->simulationWorker(); }); _threads.emplace_back([this]() { this->simulationWorker(); }); _threads.emplace_back([this]() { this->simulationWorker(); }); _threads.emplace_back([this]() { this->simulationWorker(); }); _threads.emplace_back([this]() { this->simulationWorker(); }); _threads.emplace_back([this]() { this->simulationWorker(); }); //_threads.emplace_back([this]() { simulationWorker(); }); std::cout << "Threads created..." << std::endl; } void SimulationSystem::simulationWorker() { Simulator sim; std::cout << "Thread..." << std::endl; while (_hasWork.load()) { _actorsAccessMutex.lock(); std::cout << "Size: " << _actors.size() << std::endl; if (_actors.empty()) { _hasWork.store(false); _actorsAccessMutex.unlock(); break; } auto actor = _actors.top(); _actors.pop(); _actorsAccessMutex.unlock(); sim.testActor(actor); } std::cout << "Thread ready" << std::endl; } void SimulationSystem::waitForSimulation() { std::cout << "Waiting for simulation to finish..." << std::endl; for (auto& thread : _threads) { thread.join(); } _threads.clear(); std::cout << "Simulation finished" << std::endl; }
true
9a1c5b7dceb58b4edffaee09028479ad92a052c5
C++
ej2xu/LeetCode
/105construct-binary-tree-from-preorder.cc
UTF-8
1,847
2.96875
3
[]
no_license
class Solution { public: TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { for (int &x: inorder) inorderm[x] = &x; return gentree(&preorder[0], &*preorder.end(), &inorder[0], &*inorder.end()); } private: unordered_map<int, int*> inorderm; TreeNode* gentree(int *pl, int *ph, int *il, int *ih) { if (pl == ph) return nullptr; TreeNode* root = new TreeNode(*pl); int *mid = inorderm[root->val]; root->left = gentree(pl+1, pl+1+(mid-il), il, mid); root->right = gentree(pl+1+(mid-il), ph, mid+1, ih); return root; } }; class Solution { public: TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { ipos = 0, ppos = 0; return gentree(inorder, preorder, NULL); } private: int ppos, ipos; TreeNode* gentree(vector<int>& inorder, vector<int>& preorder, TreeNode *end) { if (ppos == preorder.size()) return NULL; TreeNode *root = new TreeNode(preorder[ppos++]); if (inorder[ipos] != root->val) root->left = gentree(inorder, preorder, root); ipos++; if (!end || inorder[ipos] != end->val) root->right = gentree(inorder, preorder, end); return root; } }; // iterative class Solution { public: TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { if (preorder.empty()) return nullptr; auto i = preorder.begin(), j = inorder.begin(); auto root = new TreeNode(*i++); stack<TreeNode *> s; s.push(root); while (i != preorder.end()) { auto x = s.top(); if (x->val != *j) { x->left = new TreeNode(*i++); x = x->left; s.push(x); } else { s.pop(); ++j; if (s.empty() || s.top()->val != *j) { x->right = new TreeNode(*i++); x = x->right; s.push(x); } } } return root; } };
true
043cdea8b356627b1e03fb4625b3f1e26e7ca32d
C++
xiaoxi-s/STL
/test/correctness/algorithm_binary_search_test.cpp
UTF-8
2,517
2.9375
3
[]
no_license
#include <gtest/gtest.h> #include <stdlib.h> #include "../../src/algorithms/sstl_binary_operations.hpp" namespace algorithm_binary_search_test { TEST(binary_search_int_test, return_value_test) { int n = 10; int array[] = {0, 1, 2, 3, 4, 15, 17, 20, 24, 30}; int query_val[] = {-5, -4, -2, -1, 10, 16, 23, 27, 40, 50}; for (int i = 0; i < n; ++i) { EXPECT_TRUE(sup::binary_search(array, array + 10, array[i])); } for (int i = 0; i < n; ++i) { EXPECT_FALSE(sup::binary_search(array, array + 10, query_val[i])); } } TEST(lower_bound_int_test, return_value_test) { int n = 10; int array[] = {0, 1, 2, 3, 4, 15, 17, 20, 24, 30}; // values in array for (int i = 0; i < n; ++i) { EXPECT_TRUE(sup::lower_bound(array, array + 10, array[i]) == array+i); } EXPECT_TRUE(sup::lower_bound(array, array+10, -1) == array); EXPECT_TRUE(sup::lower_bound(array, array+10, 10) == array + 5); EXPECT_TRUE(sup::lower_bound(array, array+10, 15) == array + 5); EXPECT_TRUE(sup::lower_bound(array, array+10, 60) == array + 10); } TEST(upper_bound_int_test, return_value_test) { int n = 10; int array[] = {0, 1, 2, 3, 4, 15, 17, 20, 24, 30}; // values in array for (int i = 0; i < n; ++i) { EXPECT_TRUE(sup::upper_bound(array, array + 10, array[i]) == array+i+1); } EXPECT_TRUE(sup::upper_bound(array, array+10, -1) == array); EXPECT_TRUE(sup::upper_bound(array, array+10, 10) == array + 5); EXPECT_TRUE(sup::upper_bound(array, array+10, 15) == array + 6); EXPECT_TRUE(sup::upper_bound(array, array+10, 60) == array + 10); } TEST(equal_range_int_test, return_value_test) { int n = 10; int array[] = {0, 1, 2, 3, 4, 15, 17, 20, 24, 30}; int query_val[] = {-5, -4, -2, -1, 10, 16, 23, 27, 40, 50}; std::pair<int*, int*> pp; // values in array for (int i = 0; i < n; ++i) { pp = sup::equal_range(array, array+10, array[i]); EXPECT_TRUE(pp.first == array + i); EXPECT_TRUE(pp.second == array + i + 1); } pp = sup::equal_range(array, array + 10, -1); EXPECT_TRUE(pp.first == array); EXPECT_TRUE(pp.second == array); pp = sup::equal_range(array, array+10, 10); EXPECT_TRUE(pp.first == array + 5); EXPECT_TRUE(pp.second == array + 5); pp = sup::equal_range(array, array+10, 15); EXPECT_TRUE(pp.first == array + 5); EXPECT_TRUE(pp.second == array + 6); pp = sup::equal_range(array, array+10, 60); EXPECT_TRUE(pp.first == array + 10); EXPECT_TRUE(pp.second == array + 10); } } // namespace algorithm_binary_search_test
true
b0f131748cd4ddfeacd5f9cd893b3de704e5ad5c
C++
chenjianlong/books-code
/head-first-design-pattern/cpp/templatemethod/barista/tea_with_hook.cpp
UTF-8
747
3.046875
3
[]
no_license
/* $Id$ */ #include <iostream> #include <string> #include <cctype> #include "tea_with_hook.h" using std::cin; using std::cout; using std::endl; using std::string; Tea_With_Hook::Tea_With_Hook() { } Tea_With_Hook::~Tea_With_Hook() { } void Tea_With_Hook::brew() { cout << "Steeping the tea" << endl; } void Tea_With_Hook::add_condiments() { cout << "Adding Lemon" << endl; } bool Tea_With_Hook::customer_wants_condiments() { std::string answer = get_user_input(); if (tolower(answer[0]) == 'y') { return true; } else { return false; } } string Tea_With_Hook::get_user_input() { string answer; cout << "Would you linke lemon with your tea (y/n)? "; cin >> answer; if (answer.empty()) { return "no"; } return answer; }
true
d0cb480cf97c58332b73928d0ca59cab429ec569
C++
YuxingLiu/CarND-Kidnapped-Vehicle-Project
/src/particle_filter.cpp
UTF-8
8,468
2.5625
3
[]
no_license
/* * particle_filter.cpp * * Created on: Dec 12, 2016 * Author: Tiffany Huang */ #include <random> #include <algorithm> #include <iostream> #include <numeric> #include <math.h> #include <iostream> #include <sstream> #include <string> #include <iterator> #include "particle_filter.h" using namespace std; void ParticleFilter::init(double x, double y, double theta, double std[]) { // TODO: Set the number of particles. Initialize all particles to first position (based on estimates of // x, y, theta and their uncertainties from GPS) and all weights to 1. // Add random Gaussian noise to each particle. // NOTE: Consult particle_filter.h for more information about this method (and others in this file). default_random_engine gen; // Create normal distributions for x, y and theta normal_distribution<double> dist_x(x, std[0]); normal_distribution<double> dist_y(y, std[1]); normal_distribution<double> dist_theta(theta, std[2]); // Set the number of particles num_particles = 100; // Initialize particles for(int i = 0; i < num_particles; ++i) { Particle particle; particle.x = dist_x(gen); particle.y = dist_y(gen); particle.theta = dist_theta(gen); particle.id = i; particle.weight = 1.0; particles.push_back(particle); weights.push_back(1.0); } is_initialized = true; } void ParticleFilter::prediction(double delta_t, double std_pos[], double velocity, double yaw_rate) { // TODO: Add measurements to each particle and add random Gaussian noise. // NOTE: When adding noise you may find std::normal_distribution and std::default_random_engine useful. // http://en.cppreference.com/w/cpp/numeric/random/normal_distribution // http://www.cplusplus.com/reference/random/default_random_engine/ default_random_engine gen; // Create normal distributions for x, y and theta normal_distribution<double> dist_x(0, std_pos[0]); normal_distribution<double> dist_y(0, std_pos[1]); normal_distribution<double> dist_theta(0, std_pos[2]); // Predict each particle by motion models for(int i = 0; i < num_particles; ++i) { double x = particles[i].x; double y = particles[i].y; double theta = particles[i].theta; if(yaw_rate) { // yaw rate is non-zero double theta_f = theta + yaw_rate * delta_t; particles[i].x = x + velocity / yaw_rate * ( sin(theta_f) - sin(theta) ) + dist_x(gen); particles[i].y = y + velocity / yaw_rate * ( cos(theta) - cos(theta_f) ) + dist_y(gen); particles[i].theta = theta_f + dist_theta(gen); } else { // yaw rate is zero particles[i].x = x + velocity * cos(theta) * delta_t + dist_x(gen); particles[i].y = y + velocity * sin(theta) * delta_t + dist_y(gen); particles[i].theta = theta + dist_theta(gen); } } } void ParticleFilter::dataAssociation(std::vector<LandmarkObs> predicted, std::vector<LandmarkObs>& observations) { // TODO: Find the predicted measurement that is closest to each observed measurement and assign the // observed measurement to this particular landmark. // NOTE: this method will NOT be called by the grading code. But you will probably find it useful to // implement this method and use it as a helper during the updateWeights phase. } void ParticleFilter::updateWeights(double sensor_range, double std_landmark[], const std::vector<LandmarkObs> &observations, const Map &map_landmarks) { // TODO: Update the weights of each particle using a mult-variate Gaussian distribution. You can read // more about this distribution here: https://en.wikipedia.org/wiki/Multivariate_normal_distribution // NOTE: The observations are given in the VEHICLE'S coordinate system. Your particles are located // according to the MAP'S coordinate system. You will need to transform between the two systems. // Keep in mind that this transformation requires both rotation AND translation (but no scaling). // The following is a good resource for the theory: // https://www.willamette.edu/~gorr/classes/GeneralGraphics/Transforms/transforms2d.htm // and the following is a good resource for the actual equation to implement (look at equation // 3.33 // http://planning.cs.uiuc.edu/node99.html double k_std_xy = 1 / (2 * M_PI * std_landmark[0] * std_landmark[1]); double k_std_xx = 1 / (2 * std_landmark[0] * std_landmark[0]); double k_std_yy = 1 / (2 * std_landmark[1] * std_landmark[1]); double weight_sum = 0; for(int i = 0; i < num_particles; ++i) { double xp = particles[i].x; double yp = particles[i].y; double theta = particles[i].theta; std::vector<int> associations; std::vector<double> sense_x; std::vector<double> sense_y; double prob = 1; // Transformation, data association, and weight update for each particle and each observation for(int n = 0; n < observations.size(); ++n) { // Transform landmark observations from the car coordinate to the map coordinate LandmarkObs obs_t; double xc = observations[n].x; double yc = observations[n].y; obs_t.x = cos(theta) * xc - sin(theta) * yc + xp; obs_t.y = sin(theta) * xc + cos(theta) * yc + yp; // Associate transformed landmark observations to landmark IDs double dist_min = 500; for(int m = 0; m < map_landmarks.landmark_list.size(); ++m){ double xm = map_landmarks.landmark_list[m].x_f; double ym = map_landmarks.landmark_list[m].y_f; double dist_obs = dist(obs_t.x, obs_t.y, xm, ym); if(dist_min > dist_obs) { dist_min = dist_obs; obs_t.id = map_landmarks.landmark_list[m].id_i; } } // Save associations associations.push_back(obs_t.id); sense_x.push_back(obs_t.x); sense_y.push_back(obs_t.y); // Update weight int index = associations[n] - 1; // landmark IDs start from 1 double mu_x = map_landmarks.landmark_list[index].x_f; double mu_y = map_landmarks.landmark_list[index].y_f; double dx = sense_x[n] - mu_x; double dy = sense_y[n] - mu_y; prob *= k_std_xy * exp(-k_std_xx * dx * dx - k_std_yy * dy * dy); } // Add associations to particle when a landmark is found if(observations.size()) { particles[i].associations = associations; particles[i].sense_x = sense_x; particles[i].sense_y = sense_y; } particles[i].weight = prob; weight_sum += prob; } // Normalize weight for(int i = 0; i < num_particles; ++i) { particles[i].weight *= 1.0/weight_sum; weights[i] = particles[i].weight; } } void ParticleFilter::resample() { // TODO: Resample particles with replacement with probability proportional to their weight. // NOTE: You may find std::discrete_distribution helpful here. // http://en.cppreference.com/w/cpp/numeric/random/discrete_distribution default_random_engine gen; // Create discrete distribution with weights discrete_distribution<> d(weights.begin(), weights.end()); // Resample std::vector<Particle> particles_new; for(int i = 0; i < num_particles; ++i) { particles_new.push_back(particles[d(gen)]); } particles = particles_new; } Particle ParticleFilter::SetAssociations(Particle& particle, const std::vector<int>& associations, const std::vector<double>& sense_x, const std::vector<double>& sense_y) { //particle: the particle to assign each listed association, and association's (x,y) world coordinates mapping to // associations: The landmark id that goes along with each listed association // sense_x: the associations x mapping already converted to world coordinates // sense_y: the associations y mapping already converted to world coordinates particle.associations= associations; particle.sense_x = sense_x; particle.sense_y = sense_y; } string ParticleFilter::getAssociations(Particle best) { vector<int> v = best.associations; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<int>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; } string ParticleFilter::getSenseX(Particle best) { vector<double> v = best.sense_x; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<float>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; } string ParticleFilter::getSenseY(Particle best) { vector<double> v = best.sense_y; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<float>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; }
true
9bdb7ebf5ac99d5939804c452bef3621b1317754
C++
uchihaitachi08/daily_code
/c++/array_rotation.cpp
UTF-8
625
3.453125
3
[]
no_license
#include<iostream> #include<string> #include<vector> using namespace std; void rotate_array_temp(vector<int>*arr,int n,int d){ int* temp; temp = new int[d]; for(int i=0;i<d;i++){ temp[i] = (*arr)[i]; } for(int i=d;i<n;i++){ (*arr)[i-d] = (*arr)[i]; } int j = 0; for(int i=n-d;i<n;i++){ (*arr)[i] = temp[j]; j++; } } int main(){ static const int t[] = {12,31,3,4,56,76}; vector<int>arr (t,t+sizeof(t)/sizeof(t[0])); for(int i = 0;i<=arr.size()-1;i++){ cout<<arr[i]<<" "; } cout<<endl; rotate_array_temp(&arr,arr.size(),2); for (int i = 0; i < arr.size() ; ++i) { cout<<arr[i]<<" "; } return 0; }
true
e39e19cbe550a60ef76beef79b7c56f24d0f766a
C++
AntiqueTraider/special-for-alick
/laba_sort1/laba_sort1/Source.cpp
UTF-8
2,622
3.34375
3
[]
no_license
#include<iostream> #include <string> #include<conio.h> #include<fstream> #include<stack> using namespace std; struct Somebody { string name; int nomber; }; struct List { Somebody man; List *next; }; void FirstBuf(Somebody *arr, int i, List *head, List *other); void SecondBuf(Somebody *arr, int i, List *head, List *other); void JustAnotheSort(Somebody *arr) { List *head1 = new List; List *head2 = NULL; head1->man.nomber = arr[0].nomber; head1->man.name = arr[0].name.substr(0, arr[0].name.length()); head1->next = NULL; FirstBuf(arr,1,head1,head2); for (int i = 0; i < 5; i++) { if (head1->man.nomber < head2->man.nomber) { arr[i].name = head1->man.name.substr(0, head1->man.name.length()); arr[i].nomber = head1->man.nomber; head1 = head1->next; } else { arr[i].name = head2->man.name.substr(0, head2->man.name.length()); arr[i].nomber = head2->man.nomber; head2 = head2->next; } } } void main() { Somebody *they=new Somebody[5]; ifstream in("input.txt"); for (int i = 0; i < 5; i++) { in >> they[i].name; in >> they[i].nomber; } for (int i = 0; i < 5; i++) cout << they[i].nomber << endl; JustAnotheSort(they); for (int i = 0; i < 5; i++) cout << they[5].nomber << endl; system("pause"); } void FirstBuf(Somebody *arr, int i, List *head, List *other) { while (arr[i].nomber > head->man.nomber) { head->next = new List; head = head->next; head->next = NULL; head->man.nomber = arr[i].nomber; head->man.name = arr[i].name.substr(0, arr[i].name.length()); i++; } if (i < 5) { if (other != NULL) { other->next = new List; other = other->next; other->next = NULL; other->man.nomber = arr[i].nomber; other->man.name = arr[i].name.substr(0, arr[i].name.length()); } else { List *buf = new List; buf->next = NULL; buf->man.nomber = arr[i].nomber; buf->man.name = arr[i].name.substr(0, arr[i].name.length()); other = buf; } SecondBuf(arr, i, other, head); } } void SecondBuf(Somebody *arr, int i, List *head, List *other) { while (arr[i].nomber > head->man.nomber) { head->next = new List; head = head->next; head->next = NULL; head->man.nomber = arr[i].nomber; head->man.name = arr[i].name.substr(0, arr[i].name.length()); i++; } if (i < 5) { other->next = new List; other = other->next; other->next = NULL; other->man.nomber = arr[i].nomber; other->man.name = arr[i].name.substr(0, arr[i].name.length()); FirstBuf(arr, i, other, head); } }
true
143635d6ec94be74707372a03422925340496120
C++
squirrelClare/algorithm_cplusplus
/excise/TestDemo21/main.cpp
UTF-8
1,058
2.71875
3
[]
no_license
#include <QCoreApplication> #include<QFile> #include<QDebug> #include<QDir> static bool copyFileToPath(QString sourceDir,QString toDir, bool coverFileIfExist) { toDir.replace('\\','/'); if (sourceDir==toDir){ return true; } if (!QFile::exists(sourceDir)){ return false; } QDir *createfile = new QDir; bool exist = createfile->exists(toDir); if (exist){ if(coverFileIfExist){ createfile->remove(toDir); } }//end if if(!QFile::copy(sourceDir,toDir)) { return false; } return true; } int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QDir dir; QString strDir1("C:/Users/lenovo/Desktop/OldFile/1.txt"); QString strDir2("C:/Users/lenovo/Desktop/NewFile/2.txt"); qDebug()<< dir.exists(strDir1); qDebug()<< dir.exists(strDir2); // bool suc=copyFileToPath(strDir1,strDir2,true); bool suc=QFile::copy(strDir1,strDir2); if(suc) qDebug()<<"YES"; else qDebug()<<"NO"; return a.exec(); }
true
02809d484480b938cf9b22e04e30d88a6d9fe75e
C++
chunchou/ACM
/数据结构/splay/SGU 187 Twist and whirl - want to cheat.cpp
GB18030
3,716
2.6875
3
[]
no_license
/* ĿУm䷭ת֮ splay򵥲 */ #include <set> #include <map> #include <cmath> #include <queue> #include <stack> #include <string> #include <vector> #include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; typedef long long ll; typedef unsigned long long ull; #define debug puts("here") #define rep(i,n) for(int i=0;i<n;i++) #define foreach(i,vec) for(unsigned i=0;i<vec.size();i++) #define pb push_back #define RD(n) scanf("%d",&n) namespace Splay{ #define lx ch[x][0] #define rx ch[x][1] #define px pre[x] #define ly ch[y][0] #define ry ch[y][1] #define py pre[y] #define lz ch[z][0] #define rt ch[root][1] #define lrt ch[rt][0] const int MAXN = 130015; int ch[MAXN][2],pre[MAXN],val[MAXN],sz[MAXN]; bool rev[MAXN]; int root,tot; int ary[MAXN]; bool ok; inline void update(int x){ // ok sz[x] = sz[lx]+sz[rx]+1; } inline void new_node(int &x,int y,int v){ // ok x = ++tot; px = y; rev[x] = 0; lx = rx = 0; val[x] = v; } inline void build(int &x,int y,int l,int r){ // ok if(l>r) return; int mid = (l+r)>>1; new_node(x,y,ary[mid]); build(lx,x,l,mid-1); build(rx,x,mid+1,r); update(x); } inline void push_down(int x){ // ok if(rev[x]==0) return; swap(lx,rx); rev[x] = 0; rev[lx] ^= 1; rev[rx] ^= 1; } inline int sgn(int x){ // ok return ch[px][1]==x; } inline void setc(int y,int d,int x){ // ok ch[y][d] = x; px = y; } inline void rot(int x,int d){ // ok int y = px; int z = py; push_down(y); push_down(x); setc(y,!d,ch[x][d]); if(z) setc(z,sgn(y),x); pre[x] = z; setc(x,d,y); update(y); } inline void splay(int x,int goal=0){ // ok push_down(x); while(px!=goal){ int y = px; int z = py; if(z==goal){ rot(x,!sgn(x)); break; } if(lz==y){ if(ly==x) rot(y,1),rot(x,1); else rot(x,0),rot(x,1); } else{ if(ry==x) rot(y,0),rot(x,0); else rot(x,1),rot(x,0); } } update(x); if(goal==0) root = x; } inline int get_Kth(int x,int k){ // ok push_down(x); int tmp = sz[lx]+1; if(tmp==k) return x; if(k<tmp) return get_Kth(lx,k); else return get_Kth(rx,k-tmp); } inline void dfs(int x){ if(x==0) return; push_down(x); dfs(lx); if(val[x]){ ok?printf(" "):ok = 1; printf("%d",val[x]); } dfs(rx); } inline void solve(){ ok = 0; int n,m; scanf("%d%d",&n,&m); int x,y; root = tot = 0; ch[0][0] = ch[0][1] = pre[0] = rev[0] = 0; ary[0] = 0; for(int i=1;i<=n;i++) ary[i] = i; new_node(root,0,0); new_node(rt,root,0); build(lrt,rt,1,n); while(m--){ scanf("%d%d",&x,&y); x = get_Kth(root,x); splay(x); y = get_Kth(root,y+2); splay(y,root); rev[lrt] ^= 1; } dfs(root); puts(""); } }using namespace Splay; int main(){ #ifndef ONLINE_JUDGE freopen("sum.in","r",stdin); #endif solve(); return 0; }
true
b626ef324d7767368a3ce8829b4fcbe430a6d007
C++
caidongyun/tray
/commons/include/MRE_Windows.h
UTF-8
1,670
2.671875
3
[ "Apache-2.0" ]
permissive
#ifndef MRE_WINDOWS_H #define MRE_WINDOWS_H #include <Windows.h> #include "InternalCriticalSection.h" #include <string> class CGuidCreator { public: #ifdef UNICODE static std::wstring CreateGuidString(void) { GUID guid; CoCreateGuid(&guid); RPC_WSTR rpcStr; UuidToStringW( &guid, &rpcStr ); wchar_t* pwStr = reinterpret_cast<wchar_t*>( rpcStr ); std::wstring result(pwStr); RpcStringFreeW( &rpcStr ); return result; } #else static std::string CreateGuidString(void) { GUID guid; CoCreateGuid(&guid); RPC_CSTR rpcStr; UuidToStringA( &guid, &rpcStr ); char* pStr = reinterpret_cast<char*>( rpcStr ); std::string result(pwStr); RpcStringFreeA( &rpcStr ); return result; } #endif }; namespace SynchroPrimitives { class CWindowsManualResetEvent { private: HANDLE m_mre; CWindowsManualResetEvent(const CWindowsManualResetEvent&); void operator=(const CWindowsManualResetEvent&); public: CWindowsManualResetEvent(void){} ~CWindowsManualResetEvent(void){} static int MRE_Init(CWindowsManualResetEvent* lpMre) { lpMre->m_mre = CreateEvent(NULL, TRUE, FALSE, CGuidCreator::CreateGuidString().c_str()) ; return 0; } static int MRE_Wait(CWindowsManualResetEvent* lpMre, int timeInMs) { return WaitForSingleObject (lpMre->m_mre, timeInMs) ;} static int MRE_Set(CWindowsManualResetEvent* lpMre) {return SetEvent(lpMre->m_mre);} static int MRE_Reset(CWindowsManualResetEvent* lpMre) {return ResetEvent(lpMre->m_mre);} static int MRE_Destroy(CWindowsManualResetEvent* lpMre) {return CloseHandle(lpMre->m_mre);} }; } #endif // MRE_WINDOWS_H
true
10e5d5ef8fe773c1728cb5719217a061e9bf9961
C++
eotkd4791/Algorithms
/SW Academy/BFS&DFS/SW1868.cpp
UTF-8
2,091
2.5625
3
[]
no_license
#include <iostream> #include <queue> #include <utility> #include <cstring> using namespace std; int dx[] = {0,0,-1,1,1,1,-1,-1}; int dy[] = {1,-1,0,0,1,-1,1,-1}; char field[303][303]; bool check[303][303]; queue<pair<int,int> > q; int T,n; inline bool OOB(int xx, int yy) { return 0 <= xx && xx < n && n > yy && yy >= 0; } void bfs(int x, int y) { check[x][y] = true; q.push(make_pair(x,y)); while(!q.empty()) { pair<int,int> oq = q.front(); q.pop(); for(int dir=0; dir<8; dir++) { int nx = oq.first + dx[dir]; int ny = oq.second + dy[dir]; if(OOB(nx,ny) && !check[nx][ny] && field[nx][ny] !='*') { check[nx][ny] = true; int around = 0; for(int ddir=0; ddir<8; ddir++) { int nnx = nx + dx[ddir]; int nny = ny + dy[ddir]; if(OOB(nnx,nny) && field[nnx][nny] == '*') around++; } if(around==0) q.push(make_pair(nx,ny)); } } } } int main() { ios::sync_with_stdio(0); cin.tie(0); cin >> T; for(int t=1; t<=T; t++) { cin >> n; int cnt=0; memset(check,false, sizeof(check)); for(int i=0; i<n; i++) for(int j=0; j<n; j++) cin >> field[i][j]; for(int i=0; i<n; i++) { for(int j=0; j<n; j++) { if(field[i][j]=='.') { int around = 0; for(int dir=0; dir<8; dir++) { int nx = i + dx[dir]; int ny = j + dy[dir]; if(OOB(nx, ny) && field[nx][ny] =='*') around++; } if(around == 0 && !check[i][j]) { bfs(i,j); cnt++; } } } } for(int i=0; i<n; i++) for(int j=0; j<n; j++) if(!check[i][j] && field[i][j] != '*') cnt++; cout << '#' << t << ' ' << cnt << '\n'; } return 0; }
true
a41de6e0ee7b383ad2dcc7c8ed1cac3d47a976bb
C++
TheBaxes/medellin-covid-simulation
/src/common.h
UTF-8
1,958
2.6875
3
[ "Apache-2.0" ]
permissive
#ifndef __CS267_COMMON_H__ #define __CS267_COMMON_H__ #include <vector> #include <tuple> inline int min( int a, int b ) { return a < b ? a : b; } inline int max( int a, int b ) { return a > b ? a : b; } // // saving parameters // const float VEL_HUMAN = 1.39; // 1.38 m/s const float MOVEMENT_DELTA = 80; //80 Meters -> the length of a block const int SAVEFREQ = 5; const double PARAM_RATE_INIT_INFECT = 0.05; // ratio between infected and not infected in the beginning of the simulation const double PARAM_GOING_OUT = 0.4; // prob a given particle is going out const double PARAM_PROB_INFECTION = 0.01; // prob of infection in a interaction // // Solution of floyd algorithm // typedef struct { float **cost; int **path; } floydSolution; // // particle data structure: a person // typedef struct { // Moving related vars int id_present_node; int id_initial_node; int id_object_node; double meters_to_move; // Virus related vars bool infected; bool goingout; double socialDiscipline; } particle_t; // // timing routines // double read_timer( ); float** createArray(int m, int n); // // simulation routines // void init_particles( int n, particle_t *p, floydSolution &solution, std::vector<int> &interesNodes ); void apply_interaction( particle_t &p_a, particle_t &p_b); void move( particle_t &p, floydSolution &floyd, std::vector<int> &interesNodes ); // graph stuff void floydWarshell(int graph); float** init_graph(); std::vector<int> getPath(float **path, int v, int u); std::tuple<std::vector<int>, std::vector<int> > init_nodes(); void printPath(int** path, int v, int u); // // argument processing routines // int find_option( int argc, char **argv, const char *option ); int read_int( int argc, char **argv, const char *option, int default_value ); char *read_string( int argc, char **argv, const char *option, char *default_value ); #endif
true
f50355a74988670466f5adf0bc00a17848916257
C++
MatTerra/simuladorCamadaFisica
/src/CamadaFisica.cpp
UTF-8
3,404
2.5625
3
[]
no_license
#include "CamadaFisica.hpp" #include "CamadaEnlace.hpp" void CamadaFisicaReceptora(bitStream fluxoBrutoDeBits) { int tipoDeDecodificacao = CODIFICAO_ESCOLHIDA; std::string mensagemDecodificada; mostrarProcessamentoCamadaFisicaReceptora(fluxoBrutoDeBits); switch (tipoDeDecodificacao) { case CODIFICACAO_BINARIA: std::cout << "Utilizando decodificação binária!" << std::endl; mensagemDecodificada = CamadaFisicaReceptoraDecodificacaoBinaria( fluxoBrutoDeBits); break; case CODIFICACAO_MANCHESTER: std::cout << "Utilizando decodificação manchester!" << std::endl; mensagemDecodificada = CamadaFisicaReceptoraDecodificacaoManchester( fluxoBrutoDeBits); break; case CODIFICACAO_BIPOLAR: std::cout << "Utilizando decodificação bipolar!" << std::endl; mensagemDecodificada = CamadaFisicaReceptoraDecodificacaoBipolar( fluxoBrutoDeBits); break; } CamadaEnlaceDadosReceptora(mensagemDecodificada); } void transmit(bitStream &fluxoBrutoDeBitsPontoA, bitStream &fluxoBrutoDeBitsPontoB) { for (int j=0; j<fluxoBrutoDeBitsPontoA.size(); j++){ fluxoBrutoDeBitsPontoB.insert(fluxoBrutoDeBitsPontoB.begin()+j, std::bitset<8>()); for (int i=0; i<8; i++){ if((rand()%100) < PORCENTAGEM_ERRO) { fluxoBrutoDeBitsPontoB.at(j)[i] = !fluxoBrutoDeBitsPontoA.at(j)[i]; } else fluxoBrutoDeBitsPontoB.at(j)[i] = fluxoBrutoDeBitsPontoA.at(j)[i]; } } } void MeioDeComunicacao(bitStream bits) { bitStream fluxoBrutoDeBitsPontoB; transmit(bits, fluxoBrutoDeBitsPontoB); CamadaFisicaReceptora(fluxoBrutoDeBitsPontoB); } void CamadaFisicaTransmissora(const std::string& quadro) { int tipoDeCodificacao = CODIFICAO_ESCOLHIDA; bitStream fluxoBrutoDeBits; switch (tipoDeCodificacao) { case CODIFICACAO_BINARIA: std::cout << "Utilizando codificação binária!" << std::endl; fluxoBrutoDeBits = CamadaFisicaTransmissoraCodificacaoBinaria(quadro); break; case CODIFICACAO_MANCHESTER: std::cout << "Utilizando codificação manchester!" << std::endl; fluxoBrutoDeBits = CamadaFisicaTransmissoraCodificacaoManchester(quadro); break; case CODIFICACAO_BIPOLAR: std::cout << "Utilizando codificação bipolar!" << std::endl; fluxoBrutoDeBits = CamadaFisicaTransmissoraCodificacaoBipolar(quadro); break; } mostrarProcessamentoCamadaFisicaTransmissora(fluxoBrutoDeBits); MeioDeComunicacao(fluxoBrutoDeBits); } void mostrarFluxoBrutoDeBits(bitStream &fluxoBrutoDeBits) { for (auto &byte : fluxoBrutoDeBits) std::cout << byte << " "; std::cout << std::endl; } void mostrarProcessamentoCamadaFisicaTransmissora(bitStream &fluxoBrutoDeBits) { std::cout << "Camada física transmitindo o seguinte fluxo de bits: "; mostrarFluxoBrutoDeBits(fluxoBrutoDeBits); } void mostrarProcessamentoCamadaFisicaReceptora(bitStream &fluxoBrutoDeBits) { std::cout << "Camada física receptora recebeu o seguinte fluxo de bits: "; mostrarFluxoBrutoDeBits(fluxoBrutoDeBits); }
true
07c5bcdbbb06b86bb33cf7b77befd5ac988a4b77
C++
mamacker/DogDoor
/DogDoor.ino
UTF-8
2,979
2.625
3
[]
no_license
#include <Arduino.h> #include <ESP8266WiFi.h> #include "fauxmoESP.h" #define WIFI_SSID "*****" #define WIFI_PASS "*****" #define SERIAL_BAUDRATE 115200 #define DEBUG_FAUXMO_VERBOSE true #define ON_PIN 12 #define OPEN_PIN 13 fauxmoESP fauxmo; int doorOpen; #define REBOOT_TIME 345600000 // 1000 * 60 * 60 * 24 * 4 : 4 days // Matt's Notes!!! // Requires ESP8266 Board Library version: 2.3.0 // Requires single-word device name. // Requires FauxmoESP 2.3.0 // These things are all outside the control of this code. (: // ----------------------------------------------------------------------------- // Wifi // ----------------------------------------------------------------------------- void wifiSetup() { // Set WIFI module to STA mode WiFi.mode(WIFI_STA); // Connect Serial.printf("[WIFI] Connecting to %s ", WIFI_SSID); WiFi.begin(WIFI_SSID, WIFI_PASS); // Wait while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(100); } Serial.println(); // Connected! Serial.printf("[WIFI] STATION Mode, SSID: %s, IP address: %s\n", WiFi.SSID().c_str(), WiFi.localIP().toString().c_str()); } void setup() { // put your setup code here, to run once: pinMode(ON_PIN, OUTPUT); pinMode(OPEN_PIN, OUTPUT); digitalWrite(ON_PIN, HIGH); digitalWrite(OPEN_PIN, HIGH); doorOpen = -1; // Init serial port and clean garbage Serial.begin(SERIAL_BAUDRATE); Serial.println(); Serial.println(); // Wifi wifiSetup(); // Fauxmo v2.0 //fauxmo.addDevice("dog door"); //Doesn't work due to space. fauxmo.addDevice("dog"); fauxmo.enable(true); fauxmo.onSetState([](unsigned char device_id, const char * device_name, bool state) { Serial.printf("[MAIN] Device #%d (%s) state: %s\n", device_id, device_name, state ? "ON" : "OFF"); if (state) { doorOpen = 1; } else { doorOpen = 0; } }); } void forceClose() { digitalWrite(ON_PIN, HIGH); digitalWrite(OPEN_PIN, LOW); delay(300); digitalWrite(OPEN_PIN, HIGH); delay(300); digitalWrite(OPEN_PIN, LOW); delay(100); digitalWrite(OPEN_PIN, HIGH); } void loop() { fauxmo.handle(); static int lastDoorState = doorOpen; if (doorOpen != lastDoorState) { if (lastDoorState == -1) { // Force the door to reset state. forceClose(); if (doorOpen == 0) { lastDoorState = 0; return; } delay(9000); } if (doorOpen == 1) { digitalWrite(ON_PIN, LOW); delay(100); digitalWrite(OPEN_PIN, LOW); delay(300); digitalWrite(ON_PIN, HIGH); digitalWrite(OPEN_PIN, HIGH); } else if (doorOpen == 0) { forceClose(); if (millis() > REBOOT_TIME ) { ESP.restart(); } } lastDoorState = doorOpen; } static unsigned long last = millis(); if (millis() - last > 5000) { last = millis(); Serial.printf("[MAIN] Free heap: %d bytes\n", ESP.getFreeHeap()); } }
true
d5428296fe39e50172005607a65a057191c9e115
C++
DragonJoker/StarMap
/StarMapTestApp/StarMapTestApp.NativeActivity/Engine.h
UTF-8
2,251
2.65625
3
[]
no_license
#pragma once #include <StarMapLib/ScreenEvents.h> #include <StarMapLib/StarMap.h> #include <AndroidUtils/AndroidWindow.h> class Window : public utils::AndroidWindow { public: Window( utils::AndroidApp const & parent , ANativeWindow * window , render::ByteArray const & state ); ~Window(); private: /** *\brief * Création de la fenêtre. */ void onCreate()override; /** *\brief * Destruction de la fenêtre. */ void onDestroy()override; /** *\brief * Met à jour les données de frame et dessine une frame. */ void onDraw()override; /** *\return * Sauvegarde les données de l'application. */ void onSave( render::ByteArray & state )override; /** *\return * Restaure les données de l'application. */ void onRestore( render::ByteArray const & state )override; /** *\brief * Gestion d'un évènement de type tap. */ void onSingleTap( gl::IVec2 const & position )override; /** *\brief * Gestion d'un évènement de type double tap. */ void onDoubleTap( gl::IVec2 const & position )override; /** *\brief * Gestion d'un évènement de type déplacement avec un pointeur. */ void onSingleMove( gl::IVec2 const & position )override; /** *\brief * Gestion d'un évènement de type déplacement avec deux pointeur. */ void onDoubleMove( gl::IVec2 const & posDiff, int distDiff )override; private: //! Le signal émis lorsque l'on "clique" sur l'écran. starmap::OnScreenTap m_onScreenTap; //! Le signal émis lorsque l'on "double clique" sur l'écran. starmap::OnScreenDoubleTap m_onScreenDoubleTap; //! Le signal émis lorsque l'on effectue un déplacement avec un doigt sur l'écran. starmap::OnScreenSingleMove m_onScreenSingleMove; //! Le signal émis lorsque l'on effectue un déplacement avec deux doigts sur l'écran. starmap::OnScreenDoubleMove m_onScreenDoubleMove; //! Les évènements écran. starmap::ScreenEvents m_events; //! La carte des étoiles. starmap::StarMap m_starmap; }; class Engine { public: /** *\brief * Traitement de l'évènement d'entrée suivant. */ static int32_t handleInput( android_app * app, AInputEvent * event ); /** *\brief * Traitement de la commande principale suivante. */ static void handleCommand( android_app * app, int32_t cmd ); };
true
4968f95ff75cf7edee9ad25b064d9929c8615a3c
C++
swayamxd/noobmaster69
/SPOJ/AGGRCOW/Swayamdeepta/aggressive_cows.cpp
UTF-8
1,911
3.375
3
[]
no_license
/*We can use binary search in the function . We first of all sort the stalls. Then we always keep cow 1 in stall 1 and then proceed by finding the lower_bound in array of stalls for last_stall+dist. If the lower_bound doesn't point to the end then we can accomodate one more cow.And then check how many cows can we accomodate with minimum distance dist and if it's greater than or equal to the cows present c then it would return true but if noot return false In step 1- we place 1st cow in stall 1 and last cow in stall n(last stall). then to put one more cow , find the middle positiion as this will be farthest from the two other cows. now check if we keep distance of x(middle) between the cows, is it possible to accomodate all the cows? if yes then this is the final answer else we further divide middle position( similar divide and conquer concept) and continue the steps... */ #include <bits/stdc++.h> #include<iostream> #include<vector> #include<algorithm> #include<cmath> using namespace std; int n,c; int func(int num,int array[]) { int cows=1,pos=array[0]; for (int i=1; i<n; i++) { if (array[i]-pos>=num) { pos=array[i]; cows++; if (cows==c) return 1; } } return 0; } int bs(int array[]) { int ini=0,last=array[n-1],max=-1; while (last>ini) { //cout<<last<<" "<<ini<<endl; int mid=(ini+last)/2; if (func(mid,array)==1) { //cout<<mid<<endl; if (mid>max) max=mid; ini=mid+1; } else last=mid; } return max; } int main() { int t; cin>>t while (t--) { cin>>n>>c; int array[n]; for (int i=0; i<n; i++) cin>>array[i]; sort(array,array+n); int k=bs(array); cout<<k; } return 0; }
true
31a092a7df6f2f425635c99d79c8e1e47a7dad1e
C++
sykim9587/Linux_src
/cpp_accel/ch11_vector_all/allocator.cpp
UTF-8
1,238
3.65625
4
[]
no_license
#include <iostream> #include <string> #include <memory> //allocator using std::allocator; using std::cout; using std::endl; using std::string; int main () { /* origianl method using new and delete string *pArr = new string[5]; //not really necessary, since constructor is called later. //that's why we want to have empty space. pArr[0] = string("AAA"); pArr[1] = string("BBB"); pArr[2] = string("CCC"); pArr[3] = string("DDD"); pArr[4] = string("FFF"); for (int i = 0; i!=5; ++i) cout << pArr[i] << endl; delete [] pArr; */ allocator<string> alloc; string *pArr = alloc.allocate(5); //uninitialized_fill(pArr,pArr+5,string("hello")); alloc.construct(pArr,"AAA"); alloc.construct(pArr+1,"BBB"); alloc.construct(pArr+2,"CCC"); alloc.construct(pArr+3,"DDD"); alloc.construct(pArr+4,"EEE"); // string *pArr2 = alloc.allocate(5); //uninitialized_copy(pArr,pArr+5,pArr2); for (int i = 0; i!=5; ++i) cout << pArr[i] << endl; for (int i = 0; i!=5; ++i){ alloc.destroy(pArr + i); //alloc.destroy(pArr2 + i); } alloc.deallocate(pArr, 5); //alloc.deallocate(pArr2, 5); return 0; }
true
024b12e84182a39381eb7afd2b01ba4099521d1d
C++
davorzdralo/math_wars
/GreenEnemy.cpp
UTF-8
1,421
2.703125
3
[]
no_license
#include "GreenEnemy.h" #include "GameWindow.h" #include "Explosion.h" #include "Point.h" GreenEnemy::GreenEnemy(GameWindow* parent, const Point& location) : Enemy(parent, location, "resources/green.png", 1.0f, 0.0f, 0.13, (double) rand() / RAND_MAX * 90, 0.6f) { rotationPerUpdate = 5; this->parent = parent; } GreenEnemy::~GreenEnemy() { Explosion e = Explosion(parent, location, "resources/greenParticle.png"); parent->addToHighScore(50); } void GreenEnemy::update() { angle += rotationPerUpdate; // krecemo se direktno prema igracu direction = Vector(location, parent->getPlayerLocation()); if(direction.getX() || direction.getY()) direction = direction.normalized(); location.x += direction.getX() * speed; location.y += direction.getY() * speed; // sprecavamo izlazak van "terena" if(location.x < -Globals::worldWidth/2 + boundingCircle.getRadius()) location.x = -Globals::worldWidth/2 + boundingCircle.getRadius(); if(location.x > Globals::worldWidth/2 - boundingCircle.getRadius()) location.x = Globals::worldWidth/2 - boundingCircle.getRadius(); if(location.y < -Globals::worldHeight/2 + boundingCircle.getRadius()) location.y = -Globals::worldHeight/2 + boundingCircle.getRadius(); if(location.y > Globals::worldHeight/2 - boundingCircle.getRadius()) location.y = Globals::worldHeight/2 - boundingCircle.getRadius(); boundingCircle.setCenter(location); }
true
fb988b78687df3b3336e2fb2abf2776c1e6b1e23
C++
RaBarBarS/wyszukiwanieMotywowWSekwencjach
/Źródło.cpp
WINDOWS-1250
25,567
2.875
3
[]
no_license
#include "pch.h" #include "header.h" #include <string> #include <fstream> #include <iostream> vector <vertex> vertexesList; vector <vector <int>> nextList; vector <string> seqList; vector <int> maxMotyw; //prawo,lewo,wierzchoki ktre nale int window; int deletion; int vertexID = 0; int seqNumber; int minimumSekwencji = 4; int dlsekw = 100; //int skadnumerki = 0; void setWindow(int a) { window = a; } void setDeletion(int a) { deletion = a; } void read() { ifstream test, test2; string seq, numbers; //string helpLine; test.open("plik5-1.txt", ios::in); if (test.good() == false) cout << "Blad otwierania pliku" << endl; else { test2.open("plik5-2.txt", ios::in); if (test2.good() == false) cout << "Blad otwierania pliku" << endl; else { while (getline(test, seq) && getline(test2, numbers)) { if (seq == "\n") { getline(test, seq); getline(test2, numbers); } if (seq[0] == '>') { //wczytanie kolejnej linii, bo kolejna to to co potrzebne getline(test, seq); getline(test2, numbers); seqList.push_back(seq); addingSequence(seq, numbers); seqNumber++; } } } } } void addingSequence(string sequence, string numbers) { int skadnumerki = 0; for (int i = 0; i < dlsekw - window + 1; i++) { //domylnie <100!!! vertex*object = new vertex; object->sequence.insert(0, sequence, i, window);//sprawdz co robi ktry parametr, zeby nei wywalio bdu object->id = vertexID++; object->sequenceNumer = seqNumber; object->sequencePosition = i; int pos = skadnumerki; string halp; for (int j = i; j < i + window; j++) { int found = numbers.find(' ', pos);//bd moe by z '/" halp.insert(0, numbers, pos, found - pos);//(nie wiem, skd, pozycja startu, ile skopiowa) pos = found + 1; object->tab.push_back(atoi(halp.c_str()));//kolejne wartoi wiarygodnoci w wektorze halp.clear(); if (j == i) { skadnumerki = found + 1; } object->tab2.push_back(true);//eby nei pisa kolejnego fora } vertexesList.push_back(*object); } } void buildGraph() { for (int i = 0; i < vertexesList.size(); i++) { vector<int>container; for (int j = 0; j < vertexesList.size(); j++) { if (vertexesList[i].sequenceNumer == vertexesList[j].sequenceNumer) { continue; } else if (vertexesList[i].sequence == vertexesList[j].sequence) { container.push_back(j); } } nextList.push_back(container); } } void addDeletions() { int howMuch = 0; int max = 0; if (window == 4 || window == 5)max = 1; else max = 2; for (int i = 0; i < vertexesList.size(); i++) { for (int j = 0; j < vertexesList[i].sequence.length(); j++) { if (vertexesList[i].tab[j] <= deletion) { vertexesList[i].sequence.erase(vertexesList[i].sequence.begin() + j); vertexesList[i].tab2[j + howMuch] = false; howMuch++; j--; if (howMuch == max)break; } } howMuch = 0; } } void buildGraph2() {//z uwzgldnieniem delecji (dopisuje krawdzie tylko miedzy podobnymi wierzchokami) addDeletions(); for (int i = 0; i < vertexesList.size(); i++) { for (int j = i; j < vertexesList.size(); j++) {//bo po co sprawdza te same wierzchoki dwa razy if (vertexesList[i].sequence.length() == window && vertexesList[j].sequence.length()== window) { continue;//bo jeli ma byc midzy nimi kraw to ju zostaa dodana } else if ((vertexesList[i].sequence.find(vertexesList[j].sequence) != string::npos || vertexesList[j].sequence.find(vertexesList[i].sequence) != string::npos)&&vertexesList[i].sequenceNumer!=vertexesList[j].sequenceNumer) { //jeli jeden wierzchoek zawiera sie w drugim i s z rnych sekwencji vector<int>::iterator it; it = find(nextList[i].begin(), nextList[i].end(), j); if (it == nextList[i].end()) { //spr czy ten byo dodane czy nie nextList[i].push_back(j); nextList[j].push_back(i); } } } } } /* void makeItBigger() { for (int i = 0; i < nextList.size(); i++) { if (nextList[i].size() >= minimumSekwencji) {//ponad poowa sekwencji int liczbaSekwencji = 0; int*sekwencje = new int[seqNumber]; vector<int>klika; for (int j = 0; j < seqNumber; j++) { sekwencje[j] = 0; } for (int j = 0; j < nextList[i].size(); j++) { vector<int>::iterator it; it = find(klika.begin(), klika.end(), nextList[i][j]); if (it != klika.end()) { //spr czy ten byo dodane czy nie continue; //jak tak to } else { klika.push_back(nextList[i][j]); sekwencje[vertexesList[nextList[i][j]].sequenceNumer]++; //zwiksza ilo wystpie motywu w sekwencji o danym indeksie if (sekwencje[vertexesList[nextList[i][j]].sequenceNumer] == 1) //jeli pierwszy raz wystpi ta sekwencja to zwiksz ilo sekwencji branych pod uwag liczbaSekwencji++; } } for (int j = 0; j < nextList[nextList[i][0]].size(); j++) { vector<int>::iterator it; it = find(klika.begin(), klika.end(), nextList[nextList[i][0]][j]); if (it != klika.end()) { //spr czy ten byo dodane czy nie continue; //jak tak to } else { klika.push_back(nextList[nextList[i][0]][j]); sekwencje[vertexesList[nextList[nextList[i][0]][j]].sequenceNumer]++; //zwiksza ilo wystpie motywu w sekwencji o danym indeksie if (sekwencje[vertexesList[nextList[nextList[i][0]][j]].sequenceNumer] == 1) //jeli pierwszy raz wystpi ta sekwencja to zwiksz ilo sekwencji branych pod uwag liczbaSekwencji++; } } if (liczbaSekwencji < minimumSekwencji)//ponad polowa sekwecji continue; if (maxMotyw.size() == 0) { maxMotyw.push_back(0); maxMotyw.push_back(0); for (int c = 0; c < klika.size(); c++) { maxMotyw.push_back(klika[c]); } } /////////////////////struktury przygotowan, teraz rozszerzanko/////////////////// bool mogeRozszerzac = true, rozpraw = true; int prawo = 0, lewo = 0; //przechowuj wartoci o ile zostaa rozszerzony motyw w ktr stron //rozszerza patrzc nie czy nukleotydy s takiem same tylko czy nale do jakiej wsplnej kliki while (mogeRozszerzac) { if (i + prawo + 1 < vertexID && vertexesList[i + prawo + 1].sequenceNumer == vertexesList[i].sequenceNumer && vertexesList[i + prawo + 1].tab2[vertexesList[i + prawo + 1].tab2.size() - 1] == true && rozpraw) { //jeli kolejny wierzchoek nalezy wci do tej samej sekwencji i istnieje wgl taki wierzchoek oraz element ktry chcemy rozpatrywa nie uleg delecji char znak = vertexesList[i + prawo + 1].sequence[vertexesList[i + prawo + 1].sequence.size() - 1]; //zawsze bierzemy ostatni znak kolejnego okna eby nie walczy z ostatnim oknem for (int j = 0; j < klika.size(); j++) { if (klika[j] + prawo + 1 < vertexID && vertexesList[klika[j] + prawo + 1].sequenceNumer == vertexesList[klika[j]].sequenceNumer && vertexesList[klika[j] + prawo + 1].tab2[vertexesList[klika[j] + prawo + 1].tab2.size() - 1] == true) { if (vertexesList[klika[j] + prawo + 1].sequence[vertexesList[klika[j] + prawo + 1].sequence.size() - 1] != znak) { if (sekwencje[vertexesList[klika[j] + prawo + 1].sequenceNumer] - 1 <= 0 && liczbaSekwencji - 1 < minimumSekwencji) {//jeli zmniejszenie kliki o kolejn sekwencj zniszczyby zaoenia rozszerzaj w lewo rozpraw = false; prawo--; break; } else { if (sekwencje[vertexesList[klika[j] + prawo + 1].sequenceNumer] == 1) { liczbaSekwencji--; } sekwencje[vertexesList[klika[j] + prawo + 1].sequenceNumer]--; klika.erase(klika.begin() + j); j--; //bo przesunicie indeksw w vectorze } } } else if (klika[j] + prawo + 1 < vertexID && vertexesList[klika[j] + prawo + 1].sequenceNumer == vertexesList[klika[j]].sequenceNumer && vertexesList[klika[j] + prawo + 1].tab2[vertexesList[klika[j] + prawo + 1].tab2.size() - 1] == false) { continue;//jak warunki spenion to fajno } else {//nie mona ju dalej rozszerza rozpraw = false; prawo--; break; } } prawo++; } else if (i + prawo + 1 < vertexID && vertexesList[i + prawo + 1].sequenceNumer == vertexesList[i].sequenceNumer && vertexesList[i + prawo + 1].tab2[vertexesList[i + prawo + 1].tab2.size() - 1] == false && rozpraw) { for (int j = 0; j < klika.size(); j++) { if (klika[j] + prawo + 1 > vertexID) { if (klika[j] + prawo + 1 < vertexID && sekwencje[vertexesList[klika[j] + prawo].sequenceNumer] - 1 <= 0 && liczbaSekwencji - 1 < minimumSekwencji) {//jeli zmniejszenie kliki o kolejn sekwencj zniszczyby zaoenia rozszerzaj w lewo rozpraw = false; prawo--; break; } else { if (sekwencje[vertexesList[klika[j]].sequenceNumer] == 1) { liczbaSekwencji--; } sekwencje[vertexesList[klika[j]].sequenceNumer]--; klika.erase(klika.begin() + j); j--; //bo przesunicie indeksw w vectorze } } else if (klika[j] + prawo + 1 < vertexID && vertexesList[klika[j] + prawo + 1].sequenceNumer != vertexesList[klika[j]].sequenceNumer) { if (sekwencje[vertexesList[klika[j] + prawo + 1].sequenceNumer] - 1 <= 0 && liczbaSekwencji - 1 < minimumSekwencji) {//jeli zmniejszenie kliki o kolejn sekwencj zniszczyby zaoenia rozszerzaj w lewo rozpraw = false; prawo--; break; } else { if (sekwencje[vertexesList[klika[j] + prawo + 1].sequenceNumer] == 1) { liczbaSekwencji--; } sekwencje[vertexesList[klika[j] + prawo + 1].sequenceNumer]--; klika.erase(klika.begin() + j); j--; //bo przesunicie indeksw w vectorze } } } prawo++; } else { //bool rozszerzanie = true; //rozszerzanko w lewo if (i - lewo - 1 >= 0 && vertexesList[i - lewo - 1].sequenceNumer == vertexesList[i].sequenceNumer && vertexesList[i - lewo - 1].tab2[0] == true) { //jeli kolejny wierzchoek nalezy wci do tej samej sekwencji i istnieje wgl taki wierzchoek oraz element ktry chcemy rozpatrywa nie uleg delecji char znak = vertexesList[i - lewo - 1].sequence[0]; //zawsze bierzemy ostatni znak kolejnego okna eby nie walczy z ostatnim oknem for (int j = 0; j < klika.size(); j++) { if (klika[j] - lewo - 1 >= 0 && vertexesList[klika[j] - lewo - 1].sequenceNumer == vertexesList[klika[j]].sequenceNumer && vertexesList[klika[j] - lewo - 1].tab2[0] == true) { if (vertexesList[klika[j] - lewo - 1].sequence[0] != znak) {//WYWALA BD NIE WIEM CZEMU if (sekwencje[vertexesList[klika[j] - lewo - 1].sequenceNumer] - 1 <= 0 && liczbaSekwencji - 1 < minimumSekwencji) {//jeli zmniejszenie kliki o kolejn sekwencj zniszczyby zaoenia rozszerzaj w lewo mogeRozszerzac = false; lewo--; break; } else { if (sekwencje[vertexesList[klika[j] - lewo - 1].sequenceNumer] == 1) { liczbaSekwencji--; } sekwencje[vertexesList[klika[j] - lewo - 1].sequenceNumer]--; klika.erase(klika.begin() + j); j--; //bo przesunicie indeksw w vectorze } } } else if (klika[j] - lewo - 1 >= 0 && vertexesList[klika[j] - lewo - 1].sequenceNumer == vertexesList[klika[j]].sequenceNumer && vertexesList[klika[j] - lewo - 1].tab2[0] == false) { continue;//jak warunki spenion to fajno } else {//nie mona ju dalej rozszerza mogeRozszerzac = false; lewo--; break; } } lewo++; } else if (i - lewo - 1 >= 0 && vertexesList[i - lewo - 1].sequenceNumer == vertexesList[i].sequenceNumer && vertexesList[i - lewo - 1].tab2[0] == false) { for (int j = 0; j < klika.size(); j++) { if (klika[j] - lewo - 1 < 0) { if (sekwencje[vertexesList[klika[j] - lewo].sequenceNumer] - 1 <= 0 && liczbaSekwencji - 1 < minimumSekwencji) {//jeli zmniejszenie kliki o kolejn sekwencj zniszczyby zaoenia rozszerzaj w lewo mogeRozszerzac = false; lewo--; break; } else { if (sekwencje[vertexesList[klika[j] - lewo].sequenceNumer] == 1) { liczbaSekwencji--; } sekwencje[vertexesList[klika[j] - lewo].sequenceNumer]--; klika.erase(klika.begin() + j); j--; //bo przesunicie indeksw w vectorze } } else if (vertexesList[klika[j] - lewo - 1].sequenceNumer != vertexesList[klika[j]].sequenceNumer) { if (sekwencje[vertexesList[klika[j] - lewo - 1].sequenceNumer] - 1 <= 0 && liczbaSekwencji - 1 < minimumSekwencji) {//jeli zmniejszenie kliki o kolejn sekwencj zniszczyby zaoenia rozszerzaj w lewo mogeRozszerzac = false; lewo--; break; } else { if (sekwencje[vertexesList[klika[j] - lewo - 1].sequenceNumer] == 1) { liczbaSekwencji--; } sekwencje[vertexesList[klika[j] - lewo - 1].sequenceNumer]--; klika.erase(klika.begin() + j); j--; //bo przesunicie indeksw w vectorze } } } lewo++; } else mogeRozszerzac = false; } } //porwnaie z maksymaln jak dotd if (maxMotyw.size() == 0) { maxMotyw.push_back(prawo); maxMotyw.push_back(lewo); for (int j = 0; j < klika.size(); j++) { maxMotyw.push_back(klika[j]);//wpisanie w vector wierzchokw z naszej super dugiego motywu } } else if (maxMotyw[0] + maxMotyw[1] < lewo + prawo) { maxMotyw.clear(); maxMotyw.push_back(prawo); maxMotyw.push_back(lewo); for (int j = 0; j < klika.size(); j++) { maxMotyw.push_back(klika[j]);//wpisanie w vector wierzchokw z naszej super dugiego motywu } } } } } */ void makeItBiggerBetter() { for (int i = 0; i < nextList.size(); i++) { int lewo = 0, prawo = 0; bool rozpraw = true, mogeRozszerzac = true; if (nextList[i].size() >= minimumSekwencji) {//ponad poowa sekwencji int liczbaSekwencji = 0; int*sekwencje = new int[seqNumber]; vector<int>klika; for (int j = 0; j < seqNumber; j++) { sekwencje[j] = 0; } for (int j = 0; j < nextList[i].size(); j++) { vector<int>::iterator it; it = find(klika.begin(), klika.end(), nextList[i][j]); if (it != klika.end()) { //spr czy ten byo dodane czy nie continue; //jak tak to } else { klika.push_back(nextList[i][j]); sekwencje[vertexesList[nextList[i][j]].sequenceNumer]++; //zwiksza ilo wystpie motywu w sekwencji o danym indeksie if (sekwencje[vertexesList[nextList[i][j]].sequenceNumer] == 1) //jeli pierwszy raz wystpi ta sekwencja to zwiksz ilo sekwencji branych pod uwag liczbaSekwencji++; } } for (int j = 0; j < nextList[nextList[i][0]].size(); j++) { vector<int>::iterator it; it = find(klika.begin(), klika.end(), nextList[nextList[i][0]][j]); if (it != klika.end()) { //spr czy ten byo dodane czy nie continue; //jak tak to } else { klika.push_back(nextList[nextList[i][0]][j]); sekwencje[vertexesList[nextList[nextList[i][0]][j]].sequenceNumer]++; //zwiksza ilo wystpie motywu w sekwencji o danym indeksie if (sekwencje[vertexesList[nextList[nextList[i][0]][j]].sequenceNumer] == 1) //jeli pierwszy raz wystpi ta sekwencja to zwiksz ilo sekwencji branych pod uwag liczbaSekwencji++; } } if (liczbaSekwencji < minimumSekwencji)//ponad polowa sekwecji continue; if (maxMotyw.size() == 0) { maxMotyw.push_back(0); maxMotyw.push_back(0); for (int c = 0; c < klika.size(); c++) { //c++ mieszne maxMotyw.push_back(klika[c]); } } /////strukturki zrobion////rozszerzanie waciwe while (mogeRozszerzac) { if (i + prawo + 1 < vertexID && vertexesList[i].sequenceNumer == vertexesList[i + prawo + 1].sequenceNumer && rozpraw) { vector<int>klikaHalp; if (nextList[i + prawo + 1].size() >= minimumSekwencji - 1) { //czyli naley do jakiej kilki i to moliwe e obejmujcej potzrebne rzeczy for (int j = 0; j < nextList[i + prawo + 1].size(); j++) { vector<int>::iterator it; it = find(klikaHalp.begin(), klikaHalp.end(), nextList[i + prawo + 1][j]); if (it != klikaHalp.end()) { //spr czy ten byo dodane czy nie continue; //jak tak to } else { klikaHalp.push_back(nextList[i + prawo + 1][j]); } } for (int j = 0; j < nextList[nextList[i + prawo + 1][0]].size(); j++) { vector<int>::iterator it; it = find(klikaHalp.begin(), klikaHalp.end(), nextList[nextList[i + prawo + 1][0]][j]); if (it != klikaHalp.end()) { //spr czy ten byo dodane czy nie continue; //jak tak to } else { klikaHalp.push_back(nextList[nextList[i + prawo + 1][0]][j]); } } //klika pomocnicza zrobion } else {//skoro nie naley do aadnej kliki to nie bdzie nalea do wsplnej z innymi rozpraw = false; prawo--; } if (rozpraw) { for (int j = 0; j < klika.size(); j++) { if (klika[j] != i && vertexesList[klika[j]].id + prawo + 1 < vertexID && vertexesList[klika[j] + prawo + 1].sequenceNumer == vertexesList[klika[j]].sequenceNumer) { vector<int>::iterator it; it = find(klikaHalp.begin(), klikaHalp.end(), vertexesList[klika[j] + prawo + 1].id); if (it != klikaHalp.end()) { //spr czy naley do kliki continue; //jak tak to sprawd kolejny } else { if (sekwencje[vertexesList[klika[j] + prawo].sequenceNumer] - 1 <= 0 && liczbaSekwencji - 1 < minimumSekwencji) {//jeli zmniejszenie kliki o kolejn sekwencj zniszczyby zaoenia rozszerzaj w lewo rozpraw = false; prawo--; //bo nie moe by rozszerzone o t pozycj break; } else { if (sekwencje[vertexesList[klika[j]].sequenceNumer] == 1) { liczbaSekwencji--; } sekwencje[vertexesList[klika[j]].sequenceNumer]--; klika.erase(klika.begin() + j); j--; //bo przesunicie indeksw w vectorze } } } else if(klika[j] != i || (klika[j] == i && (vertexesList[klika[j]].id + prawo + 1 >= vertexID || vertexesList[klika[j] + prawo + 1].sequenceNumer != vertexesList[klika[j]].sequenceNumer))){ //gdy wychodzimy poza sekwencj lub zakres indeksw if (sekwencje[vertexesList[klika[j] + prawo].sequenceNumer] - 1 <= 0 && liczbaSekwencji - 1 < minimumSekwencji) {//jeli zmniejszenie kliki o kolejn sekwencj zniszczyby zaoenia rozszerzaj w lewo rozpraw = false; prawo--; //bo nie moe by rozszerzone o t pozycj break; } else { if (sekwencje[vertexesList[klika[j]].sequenceNumer] == 1) { liczbaSekwencji--; } sekwencje[vertexesList[klika[j]].sequenceNumer]--; klika.erase(klika.begin() + j); j--; //bo przesunicie indeksw w vectorze } } } prawo++; } } else { //rozszerzanko w lewo if (i - lewo - 1 > 0 && vertexesList[i].sequenceNumer == vertexesList[i - lewo - 1].sequenceNumer) { vector<int>klikaHalp; if (nextList[i - lewo - 1].size() >= minimumSekwencji - 1) { //czyli naley do jakiej kilki i to moliwe e obejmujcej potzrebne rzeczy for (int j = 0; j < nextList[i - lewo - 1].size(); j++) { vector<int>::iterator it; it = find(klikaHalp.begin(), klikaHalp.end(), nextList[i - lewo - 1][j]); if (it != klikaHalp.end()) { //spr czy ten byo dodane czy nie continue; //jak tak to } else { klikaHalp.push_back(nextList[i - lewo - 1][j]); } } for (int j = 0; j < nextList[nextList[i - lewo - 1][0]].size(); j++) { vector<int>::iterator it; it = find(klikaHalp.begin(), klikaHalp.end(), nextList[nextList[i - lewo - 1][0]][j]); if (it != klikaHalp.end()) { //spr czy ten byo dodane czy nie continue; //jak tak to } else { klikaHalp.push_back(nextList[nextList[i - lewo - 1][0]][j]); } } //klika pomocnicza zrobion } else {//skoro nie naley do aadnej kliki to nie bdzie nalea do wsplnej z innymi break; } for (int j = 0; j < klika.size(); j++) { if (klika[j] != i && vertexesList[klika[j]].id - lewo - 1 > 0 && vertexesList[klika[j] - lewo - 1].sequenceNumer == vertexesList[klika[j]].sequenceNumer) { vector<int>::iterator it; it = find(klikaHalp.begin(), klikaHalp.end(), vertexesList[klika[j] - lewo - 1].id); if (it != klikaHalp.end()) { //spr czy naley do kliki continue; //jak tak to sprawd kolejny } else { if (sekwencje[vertexesList[klika[j] - lewo].sequenceNumer] - 1 <= 0 && liczbaSekwencji - 1 < minimumSekwencji) {//jeli zmniejszenie kliki o kolejn sekwencj zniszczyby zaoenia rozszerzaj w lewo mogeRozszerzac = false; lewo--; //bo nie moe by rozszerzone o t pozycj break; } else { if (sekwencje[vertexesList[klika[j]].sequenceNumer] == 1) { liczbaSekwencji--; } sekwencje[vertexesList[klika[j]].sequenceNumer]--; klika.erase(klika.begin() + j); j--; //bo przesunicie indeksw w vectorze } } } else { if (sekwencje[vertexesList[klika[j] - lewo].sequenceNumer] - 1 <= 0 && liczbaSekwencji - 1 < minimumSekwencji) {//jeli zmniejszenie kliki o kolejn sekwencj zniszczyby zaoenia rozszerzaj w lewo mogeRozszerzac = false; lewo--; //bo nie moe by rozszerzone o t pozycj break; } else { if (sekwencje[vertexesList[klika[j]].sequenceNumer] == 1) { liczbaSekwencji--; } sekwencje[vertexesList[klika[j]].sequenceNumer]--; klika.erase(klika.begin() + j); j--; //bo przesunicie indeksw w vectorze } } } lewo++; } else { mogeRozszerzac = false; } } } //porwnaie z maksymaln jak dotd if (maxMotyw[0] + maxMotyw[1] < lewo + prawo) { maxMotyw.clear(); maxMotyw.push_back(prawo); maxMotyw.push_back(lewo); for (int j = 0; j < klika.size(); j++) { maxMotyw.push_back(klika[j]);//wpisanie w vector wierzchokw z naszej super dugiego motywu } } } } } void outputResults() { if (maxMotyw.size() == 0) { cout << "UPS! COS POSZLO NIE TAK, ZADNA KLIKA NIE ZOSTALA ZNALEZIONA" << endl; } else { vector<vector<int>>sekwencje; for (int j = 0; j < seqNumber; j++) { vector<int>nieWazne; sekwencje.push_back(nieWazne); } for (int i = 2; i < maxMotyw.size(); i++) { //i=2 bo dwie pierwsze liczby to prawo/lewo sekwencje[vertexesList[maxMotyw[i]].sequenceNumer].push_back(maxMotyw[i]); } /*for (int i = 0; i < maxMotyw.size(); i++) { cout << maxMotyw[i] << " "; }*/ cout << endl; for (int i = 0; i < seqNumber; i++) { if (sekwencje[i].size() > 0) { cout << "SEKWENCJA " << i << ":" << endl; for (int j = 0; j < sekwencje[i].size(); j++) { int prawo = 0; int lewo = maxMotyw[1]; int okno = 0; cout << "\tPOZYCJA " << (vertexesList[sekwencje[i][j]].sequencePosition - lewo) << ":"; while (lewo > 0) { cout << seqList[vertexesList[sekwencje[i][j]].sequenceNumer][vertexesList[sekwencje[i][j] - lewo].sequencePosition]; lewo--; } while (okno < window) { cout << seqList[vertexesList[sekwencje[i][j]].sequenceNumer][vertexesList[sekwencje[i][j]].sequencePosition + okno]; okno++; } while (prawo < maxMotyw[0]) { cout << seqList[vertexesList[sekwencje[i][j]].sequenceNumer][vertexesList[sekwencje[i][j] + prawo].sequencePosition + window]; prawo++; } cout << endl; } } } /*for (int i = 2; i < maxMotyw.size(); i++) { int prawo = 0; int lewo = maxMotyw[1]; int okno = 0; cout << maxMotyw[i] << ": "; while (lewo > 0) { cout << vertexesList[maxMotyw[i] - lewo].sequence[0]; lewo--; } while (okno < window) { cout << seqList[vertexesList[maxMotyw[i]].sequenceNumer][vertexesList[maxMotyw[i]].sequencePosition + okno]; okno++; } while (prawo < maxMotyw[0]) { cout << vertexesList[maxMotyw[i] + prawo].sequence[0]; prawo++; } cout << endl; }*/ //wypisz wszystkie kombinacje } }
true
255301e1d88cfa435d35445cc572513ab6b86e70
C++
NPIPHI/v8Inspector
/src/SafeQueue.h
UTF-8
1,278
3.25
3
[]
no_license
// // Created by 16182 on 12/14/2020. // #ifndef V8DEBUGGER_SAFEQUEUE_H #define V8DEBUGGER_SAFEQUEUE_H #include <queue> #include <mutex> #include <condition_variable> #include <optional> // A threadsafe-queue. template <class T> class SafeQueue { public: SafeQueue(): q(), m(), c(){} // Add an element to the queue. inline void enqueue(T t) { std::lock_guard<std::mutex> lock(m); q.push(t); c.notify_one(); } // Get the "front"-element. inline std::optional<T> dequeue() { std::unique_lock<std::mutex> lock(m); if(q.empty()){ return std::nullopt; } else { T val = q.front(); q.pop(); return std::move(val); } } T blocking_dequeue() { std::unique_lock<std::mutex> lock(m); while(q.empty()) { // release lock as long as the wait and reaquire it afterwards. c.wait(lock); } T val = q.front(); q.pop(); return std::move(val); } inline size_t size(){ std::unique_lock<std::mutex> lock(m); return q.size(); } private: std::queue<T> q; mutable std::mutex m; std::condition_variable c; }; #endif //V8DEBUGGER_SAFEQUEUE_H
true
96797fd9ce7e772d11e704460a5f4f5419754489
C++
swd543/projects
/Codes/poly.cpp
UTF-8
1,575
3.140625
3
[]
no_license
#include "libs/bugabox.cpp" #define max 10 #define end 999999 struct polynomial { struct node { int x_degree,y_degree,z_degree,coeff; node *next; }; node *head,*p; void traverseTo(int a) { p=head; for(int i=0;i<a;i++) if(p->next!=NULL) p=p->next; else break; } bool isXYZ() { return true; } bool isNum() { return true; } bool isOp() { return true; } public: void init() { head=new node,p=new node; head=p; p->x_degree=0,p->y_degree=0,p->z_degree=0,p->coeff=0; } /* void insert(int e) { if(p->next!=NULL)traverseTo(end); p->next=new node; p=p->next; p->data=e; } void del(int l) { traverseTo(l-1); if((p->next)!=NULL) { if((p->next)->next!=NULL) p->next=(p->next)->next; else p->next=NULL; } }*/ void display() { p=head; cout<<"\n\n"; while(p->next!=NULL) { p=p->next; cout<<" + "<<p->coeff<<"x"<<p->x_degree<<"y"<<p->y_degree<<"z"<<p->z_degree; } } void getPoly() { int t=0; cout<<"\n\nEnter a polynomial in x, y and z...\n"; do{ p->next=new node; p=p->next; cout<<"\n\nTerm "<<++t<<":\nCoefficient::X_Degree::Y_Degree::Z_Degree ? "; cin>>p->coeff>>p->x_degree>>p->y_degree>>p->z_degree; cout<<"\nAnother polynominal? (y/n) : "; getch(); }while(getch()!='n'); } }; polynomial operator + (polynomial a, polynomial b) { polynomial c; a.traverseTo(0); b.traverseTo(0); cout<<"\n\n"; return c; } int main() { polynomial p,q; p.init(); p.getPoly(); p.display(); q.init(); q.getPoly(); p.display(); p+q.display(); }
true
e42df72443428a88b0ba9f63c6e12cbd95699a64
C++
littesss/test_code
/Test/project_sync_22/ut/utfopen.cpp
UTF-8
741
2.546875
3
[]
no_license
/************************************************************************* > File Name: utfopen.cpp > Created Time: Sun 27 Aug 2017 17:23:23 PDT ************************************************************************/ #include <iostream> using namespace std; #include <stdio.h> int main() { FILE * fp = NULL; fp = fopen("/etc/exports", "r"); char line[1024]; int count = 0; while(NULL != fgets(line, 1024, fp)) { cout << "line " << ++count << ":" << line ;//fgets() STOP after a newline/EOF } /* size_t nread; char buff[10240]; nread = fread(buff,1 , 10240, fp);// 读的每个数据项1个大小,读10240个 cout << buff; */ fclose(fp); return 0; }
true
f5a7c52e52967d258000d87a3c8b09ce2a89c7e7
C++
sillyatom/OpenGL
/OpenGL/Base/Primitives/Cube.cpp
UTF-8
1,021
2.640625
3
[]
no_license
// // Cube.cpp // OpenGL_1 // // Created by Sillyatom on 23/09/17. // Copyright © 2017 SillyatomGames. All rights reserved. // #include <GL/glew.h> #include "Cube.h" unsigned int Cube::_VAO = -1; unsigned int Cube::_VBO = -1; size_t Cube::_size = 0; Cube::Cube(const float *vertices, size_t size) { _size = (size / sizeof(float)) / 8; glGenVertexArrays(1, &_VAO); glGenBuffers(1, &_VBO); glBindVertexArray(_VAO); glBindBuffer(GL_ARRAY_BUFFER, _VBO); glBufferData(GL_ARRAY_BUFFER, size, vertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float))); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float))); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); }
true
34f2820b836cd4fc0d07909daa6c126ef6c25e2c
C++
Sorades/DataStructure
/DataStructure/ex8/AdjGraph.cpp
GB18030
2,072
3.015625
3
[]
no_license
#include <iostream> #define maxV 5 #define INF 0x3f3f3f3f using namespace std; typedef char infoType; int a[maxV][maxV] = {0, 8, INF, 5, INF, INF, 0, 3, INF, INF, INF, INF, 0, INF, 6, INF, INF, 9, 0, INF, INF, INF, INF, INF, 0}; typedef struct ANode { int adjvex;//ñߵڽӵ struct ANode *nextArc;//ñߵڽӵ int weight; //߽ } ArcNode; typedef struct VNode { infoType info; ArcNode *firstArc; } VerNode; typedef struct { VNode adjList[maxV]; int n, e; } AdjGraph; AdjGraph *creatAdj(int a[maxV][maxV], int n, int e); void disAdj(AdjGraph *G); void destroyAdj(AdjGraph *&G); AdjGraph *creatAdj(int a[maxV][maxV], int n, int e) { AdjGraph *G = (AdjGraph *)malloc(sizeof(AdjGraph)); for (int i = 0; i < n; i++) G->adjList[i].firstArc = NULL; ArcNode *node; for (int i = 0; i < n; i++) for (int j = n - 1; j >= 0; j--) if (a[i][j] != INF && a[i][j] != 0) { node = (ArcNode *)malloc(sizeof(ArcNode)); node->adjvex = j; node->nextArc = G->adjList[i].firstArc; node->weight = a[i][j]; G->adjList[i].firstArc = node; } G->n = n, G->e = e; return G; } void disAdj(AdjGraph *G) { ArcNode *node; for (int i = 0; i < G->n; i++) { node = G->adjList[i].firstArc; cout << i << ":"; while (node != NULL) { cout << node->adjvex << "[" << node->weight << "]"; node = node->nextArc; } cout << endl; } } void destroyAdj(AdjGraph *&G) { ArcNode *pre, *p; for (int i = 0; i < G->n; i++) { pre = G->adjList[i].firstArc; if(pre!=NULL){ p = pre->nextArc; while (p!=NULL) { free(pre); pre = p; p = pre->nextArc; } free(pre); } } free(G); }
true
7d9062e0c52933a2d8b632bf266cef90b6255787
C++
Roooooobin/Leetcode-Problems
/meituan-sort strings/main.cpp
UTF-8
1,070
2.875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; vector<string> a; bool cmp(string a, string b){ if(a == "") return true; if(b.find(a) == 0 && a != b) return true; if(a.find(b) == 0 && a != b) return false; return a > b; } void qsort(int l, int r){ if(l >= r) return; int i = l, j = r; string x = a[i]; while(i != j){ while(i < j && !cmp(x, a[j])){ j--; } swap(a[i], a[j]); while(i < j && cmp(x, a[i])){ i++; } swap(a[i], a[j]); } qsort(l, i-1); qsort(i+1, r); } int main(){ string s; cin >> s; int len = s.size(); int index = 0; string str; a.clear(); while(index <= len){ if(s[index] == ',' || index == len){ a.push_back(str); str.clear(); index++; } else{ str += s[index]; index++; } } qsort(0, a.size()-1); for(int i=a.size()-1; i>0; --i){ cout << a[i] << ","; } cout << a[0] << endl; return 0; }
true
6650081b92bb985596500cd9a861dc851c96b852
C++
robinlzw/GameEngine2
/src/lights/spotlight.cpp
UTF-8
3,566
2.578125
3
[]
no_license
#pragma once #include <GLFW/glfw3.h> #include <glad/glad.h> #include <iostream> #include <glm/glm.hpp> #include "../engine/logger.h" #include "../engine/context.h" #include "../engine/renderObject.cpp" #include "../engine/shader.cpp" #include "../shape/cube.cpp" class Spotlight : public RenderObject { public: bool showCube = true; glm::vec3 lightColor = glm::vec3(0.2f, 0.3f, 0.6f); glm::vec3 lightPos = glm::vec3(1.2f, 1.0f, 2.0f); // Shader *shaderProgram; float translationX; float translationY; float translationZ; ShapeCube cube; void init() { // shaderProgram = context->resourceManager->loadShader("light"); // shaderProgram->use(); if (showCube) { cube = ShapeCube(); cube.loadTexture = false; cube.addChild(&cube, scene); } } void draw(float delta) { std::cout << "draw light" << std::endl; // float speed = 2.1f; // translationX = 12.0f * cos(0.0f + speed * (float)glfwGetTime()); // translationY = 1.0f; // // translationY = 2.0f * sin(0.0f + 1.0f * (float)glfwGetTime()); // translationZ = 14.0f * sin(0.0f + speed * (float)glfwGetTime()); // // glm::vec3 translation = glm::vec3(2.0f); // glm::vec3 translation = glm::vec3(translationX, translationY, translationZ); // glm::vec3 lightColor; // lightColor.x = sin(glfwGetTime() * 2.0f); // lightColor.y = sin(glfwGetTime() * 0.7f); // lightColor.z = sin(glfwGetTime() * 1.3f); // glm::vec3 diffuseColor = lightColor * glm::vec3(0.5f); // glm::vec3 ambientColor = diffuseColor * glm::vec3(0.2f); // if (showCube) // { // cube.position = translation; // cube.color = diffuseColor; // cube.draw(delta); // } // shaderProgram->use(); // // shaderProgram->setVec3("light.color", lightColor); // shaderProgram->setVec3("light.position", translation); // shaderProgram->setVec3("light.ambient", ambientColor); // // shaderProgram->setVec3("light.ambient", 0.2f, 0.2f, 0.2f); // shaderProgram->setVec3("light.diffuse", diffuseColor); // darken diffuse light a bit // // shaderProgram->setVec3("light.diffuse", 0.5f, 0.5f, 0.5f); // darken diffuse light a bit // shaderProgram->setVec3("light.specular", 1.0f, 1.0f, 1.0f); } void renderScene(float delta, Shader *shader, bool isShadowRender) { std::cout << "Render light" << std::endl; float speed = 2.1f; translationX = 12.0f * cos(0.0f + speed * (float)glfwGetTime()); translationY = 1.0f; // translationY = 2.0f * sin(0.0f + 1.0f * (float)glfwGetTime()); translationZ = 14.0f * sin(0.0f + speed * (float)glfwGetTime()); // glm::vec3 translation = glm::vec3(2.0f); glm::vec3 translation = glm::vec3(translationX, translationY, translationZ); glm::vec3 lightColor; lightColor.x = sin(glfwGetTime() * 2.0f); lightColor.y = sin(glfwGetTime() * 0.7f); lightColor.z = sin(glfwGetTime() * 1.3f); glm::vec3 diffuseColor = lightColor * glm::vec3(0.5f); glm::vec3 ambientColor = diffuseColor * glm::vec3(0.2f); if (showCube) { // cube.position = translation; // cube.color = diffuseColor; // cube.renderScene(delta, shader, isShadowRender); } shader->use(); // shaderProgram->setVec3("light.color", lightColor); shader->setVec3("lightPosition", translation); shader->setVec3("light.ambient", ambientColor); // shaderProgram->setVec3("light.ambient", 0.2f, 0.2f, 0.2f); shader->setVec3("light.diffuse", diffuseColor); // darken diffuse light a bit // shaderProgram->setVec3("light.diffuse", 0.5f, 0.5f, 0.5f); // darken diffuse light a bit shader->setVec3("light.specular", 1.0f, 1.0f, 1.0f); } };
true
96e83802fdaff9b9cecfea78e59258cacb22382c
C++
Pangeamt/nectm
/tools/mosesdecoder-master/phrase-extract/filter-rule-table/ForestTsgFilter.h
UTF-8
1,887
2.515625
3
[ "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "LGPL-2.0-or-later", "GPL-1.0-or-later", "LGPL-2.1-or-later", "LicenseRef-scancode-other-copyleft", "GPL-2.0-only", "Apache-2.0" ]
permissive
#pragma once #include <istream> #include <ostream> #include <string> #include <vector> #include <boost/shared_ptr.hpp> #include <boost/unordered_map.hpp> #include <boost/unordered_set.hpp> #include "syntax-common/numbered_set.h" #include "syntax-common/tree.h" #include "syntax-common/tree_fragment_tokenizer.h" #include "Forest.h" #include "StringForest.h" #include "TsgFilter.h" namespace MosesTraining { namespace Syntax { namespace FilterRuleTable { // Filters a rule table, discarding rules that cannot be applied to a given // test set. The rule table must have a TSG source-side and the test sentences // must be parse forests. class ForestTsgFilter : public TsgFilter { public: // Initialize the filter for a given set of test forests. ForestTsgFilter(const std::vector<boost::shared_ptr<StringForest> > &); private: struct IdForestValue { Vocabulary::IdType id; std::size_t start; std::size_t end; }; static const std::size_t kMatchLimit; // Represents a forest using integer vocabulary values. typedef Forest<IdForestValue> IdForest; typedef boost::unordered_map<std::size_t, std::vector<const IdForest::Vertex*> > InnerMap; typedef std::vector<InnerMap> IdToSentenceMap; // Forest-specific implementation of virtual function. bool MatchFragment(const IdTree &, const std::vector<IdTree *> &); // Try to match a fragment against a specific vertex of a test forest. bool MatchFragment(const IdTree &, const IdForest::Vertex &); // Convert a StringForest to an IdForest (wrt m_testVocab). Inserts symbols // into m_testVocab. boost::shared_ptr<IdForest> StringForestToIdForest(const StringForest &); std::vector<boost::shared_ptr<IdForest> > m_sentences; IdToSentenceMap m_idToSentence; std::size_t m_matchCount; }; } // namespace FilterRuleTable } // namespace Syntax } // namespace MosesTraining
true
81b426fd5781e58d2e5bc344821244ae0d462eac
C++
David-Whiteford/Tofu-Of-Doom
/Tofu-of-Doom/ProjectileEnemy.h
UTF-8
985
2.53125
3
[]
no_license
#pragma once #include <SFML/Graphics.hpp> #include <SFML/OpenGL.hpp> #include "DisplayScale.h" #include <stdlib.h> #include "Globals.h" class ProjectileEnemy : public GameObject { public: ProjectileEnemy(sf::RenderWindow& t_window); ~ProjectileEnemy(); void init(sf::Vector2f startPosition, sf::Vector2f moveDirection); void setDamageAmount(int t_damage); int getDamageAmount(); void update(sf::Time t_deltaTime); //void draw(); float getRadius(); sf::CircleShape getSprite(); sf::Vector2f getPosition(); void setAlive(bool t_alive); void draw(); bool isAlive(); bool canRender = true; GameObject* myGameObject; private: bool m_alive; float m_speed = 10.0f; int damageAmount = 10; sf::Time m_time; sf::CircleShape m_bulletShape; sf::RenderWindow& m_window; float m_radius = 23; int m_aliveAt = 0; float m_timeToLive = 400; sf::Vector2f m_direction = sf::Vector2f(0, 0); sf::Vector2f m_position = sf::Vector2f(0, 0); };
true
66177831405d3c959ac801224c9b7963018668b1
C++
RajB07/DS-Algo-Problem-Solving
/Code Forces/1560/B.cpp
UTF-8
444
2.875
3
[]
no_license
// https://codeforces.com/contest/1560/problem/B #include <iostream> using namespace std; int main() { int t; int a, b, c, half_n, n; cin >> t; while (t--) { cin >> a >> b >> c; half_n = abs(a - b); n = 2 * half_n; if (a > n || b > n || c > n) cout << -1 << endl; else { cout << (c + half_n <= n ? c + half_n : c - half_n) << endl; } } }
true
12be7ad1fd6d9ac4063c5b989665319f95232e47
C++
AntoniaShalamanova/Programming-Basic-With-C-Plus-Plus
/MyExam.05.11.2017/WireNet.cpp
UTF-8
728
2.90625
3
[]
no_license
// WireNet.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <iomanip> using namespace std; int main() { int place_length, place_width; double net_height, net_price, net_weight; cin >> place_length >> place_width >> net_height >> net_price >> net_weight; int net_length = place_length * 2 + place_width * 2; double net_area = net_length*net_height; double all_net_price = net_length*net_price; double all_net_weight = net_area*net_weight; cout << fixed << setprecision(2) << net_length << endl; cout << fixed << setprecision(2) << all_net_price << endl; cout << fixed << setprecision(3) << all_net_weight << endl; return 0; }
true
0cef67754211c51a60cab61d739288cf352d5879
C++
xueqing/CodeForces
/A-level/A59-Word.cpp
UTF-8
440
2.796875
3
[]
no_license
#include <iostream> #include <stdio.h> #include <string.h> #include <ctype.h> //islower,toupper,tolower func using namespace std; int main() { int i, len, nl=0, nu=0; char u[101]={}, l[101]={}; scanf("%s", l); len = strlen(l); memcpy(u, l, len+1); for(i=0; i<len; i++) { if(islower(l[i])) { nl++; u[i] = toupper(l[i]); } else { nu++; l[i] = tolower(l[i]); } } printf("%s\n", (nl < nu ? u : l)); return 0; }
true
fa6174de7d84e2de48edfd6befe49bc009aed78e
C++
khuevu/battlecity-online
/server/src/bt_server.h
UTF-8
1,037
2.796875
3
[]
no_license
#ifndef INCLUDED_BATTLETANK_SERVER #define INCLUDED_BATTLETANK_SERVER #include <string> #include <vector> #include <bt_socket.h> #include <bt_player.h> namespace bt { class Server { public: /** * @brief: Start game server at the specified port */ Server(int port); /** * @brief: Wait for enough players to join the game */ void waitForPlayersToJoin(); /** * @brief: Start Game */ void startGame(); private: // socket to handle send and recv data ListenSocket d_listenSocket; // number of supported players const size_t d_supported_players; // connected players std::vector<Player> d_players; // cycle through the sockets, receive data from client and save to player // buffer void receiveDataFromPlayers(); // wait for all players to ready for new level void waitForPlayersReadyForNewLevel(); /** * @brief: play Level * @return: true if player won */ bool runLevel(int levelNumber); }; } #endif
true
b948669f125fbb3033fa202ca7e6dcb9ec379751
C++
1119-2916/vim-snippet
/dinic.cpp
UTF-8
2,504
2.65625
3
[]
no_license
/* * 有効辺を貼る * 辺の重みが最大流量になる */ struct Dinic { int n, s, t; vector<int> level, prog, que; vector< vector< Flow > > cap, flow; vector< vector < int > > g; Flow inf; Dinic(const Graph &graph) : n(graph.size()), cap(n, vector<Flow>(n)), flow(n, vector<Flow>(n)), g(n, vector<int>()), inf(numeric_limits<Flow>::max() / 8) { for (int i = 0; i < n; i++) { for (int j = 0; j < graph[i].size(); j++) { Edge e = graph[i][j]; int u = e.s, v = e.d; Flow c = e.c; cap[u][v] += c; cap[v][u] += c; flow[v][u] += c; g[u].push_back(v); g[v].push_back(u); } } } inline Flow residue(int u, int v) { return cap[u][v] - flow[u][v]; } Flow solve(int s_, int t_) { this->t = t_, this->s = s_; que.resize(n + 1); Flow res = 0; while (levelize()) { prog.assign(n, 0); res += augment(s, inf); } return res; } bool levelize() { int l = 0, r = 0; level.assign(n, -1); level[s] = 0; que[r++] = s; while (l != r) { int v = que[l++]; if (v == t) break; for (int i = 0; i < g[v].size(); i++) { int d = g[v][i]; if (level[d] == -1 && residue(v, d) != 0) { level[d] = level[v] + 1; que[r++] = d; } } } return level[t] != -1; } Flow augment(int v, Flow lim) { Flow res = 0; if (v == t) return lim; for (int &i = prog[v]; i < (int)g[v].size(); i++) { const int &d = g[v][i]; if (residue(v, d) == 0 || level[v] >= level[d]) continue; const Flow aug = augment(d, min(lim, residue(v, d))); flow[v][d] += aug; flow[d][v] -= aug; res += aug; lim -= aug; if (lim == 0) break; } return res; } };
true
ad118109d5e9a04f2989b023b7517d314465694a
C++
42kevinzheng/Cpp-11
/CSCE240/hw6/src/median.cc
UTF-8
560
2.640625
3
[]
no_license
/* Copyright 2019 Kevin Zheng hw6*/ #include <median.h> namespace csce240 { Median::Median() {} void Median::Collect(double datum) { ok.push_back(datum); } double Median::Calculate() const { std::vector<double> vec; int n = ok.size(); for (int i = 0; i < n; ++i) { vec.push_back(ok[i]); } if (vec.empty()) { return 0; } else { std::sort(vec.begin(), vec.end()); if (vec.size() % 2 == 0) return (vec[vec.size()/2 - 1] + vec[vec.size()/2]) / 2; else return vec[vec.size()/2]; } } } // namespace csce240
true
3ba1828569de1d387dbcef6d009cdabf3ed42dbc
C++
joshpersaud/RSA-encryption-algorithm
/RSA.cpp
UTF-8
5,050
3.34375
3
[]
no_license
#include<iostream> #include<stdlib.h> #include<stdio.h> #include<math.h> #include<string.h> using namespace std; int primeFirstElement, primeSecondElement; int dp, e, rf, objectFlag; // Encrypt and decrypt number with temporary long int encryptValue[50], decryptValue[50], temporaryValue[50], j; // Encrypt and decrypt message char encryptedMessage[50], decryptedMessage[50]; char messageOriginalContent[100]; // Code snippet to check prime number int primeCheckMethod(long int num) { for (int w = 2; w <= sqrt(num); w++) { // Checks if the number is divisible by loop variable if (num % w == 0) // Return 0 for not prime return 0; } // Returns 1 for prime return 1; } long int cd(long int data) { long int v = 1; while (1) { // Here we will Increase the v value by e v = v + e; // here we will Checks if the v value is divisible by data if (v % data == 0) // Returns the quotient return(v / data); } } // code snippet to generate encryption key void encryptionKey() { // Initialize v to zero int v = 0; for (rf = 2; rf < e; rf++) { // Checks if e is divisible by loop value rf if (e % rf == 0) // Continue the loop continue; // Otherwise call he function to check rf is prime or not // set the objectFlag to function return value 0 or 1 objectFlag = primeCheckMethod(rf); // Checks if the objectFlag value is 1 and // loop variable rf is not equals to first and second prime number entered by the user if (objectFlag == 1 && rf != primeFirstElement && rf != primeSecondElement) { // Assigns the loop variable rf value to encryptValue of v index position encryptValue[v] = rf; // Calls the function CD with encryptValue v index position value // Stores the return value in objectFlag objectFlag = cd(encryptValue[v]); // Checks if objectFlag value is greater than 0 if (objectFlag > 0) { // Stores objectFlag value in decryptValue array's v index position decryptValue[v] = objectFlag; // Increase the v value by one v++; }// End of inner if condition // Checks if the v value is 99 then come out of the loop if (v == 99) break; } }// End of for loop } // Function to encrypt the message void encrypt() { long int hp, ju, key = encryptValue[0], v, objectLength; rf = 0; objectLength = strlen(messageOriginalContent); while (rf != objectLength) { // Stores the decrypt message array rf index position data in hp hp = decryptedMessage[rf]; // Subtract 96 from hp and stores it in hp hp = hp - 96; // Initialize v to one v = 1; // Loops till key value for (j = 0; j < key; j++) { // Multiplies v with hp and stores the result in v v = v * hp; // Divides v with dp and stores the remainder in v v = v % dp; } temporaryValue[rf] = v; // Updates ju by assigning v added to 96 ju = v + 96; // Stores the ju value at rf index position of encrypted message array encryptedMessage[rf] = ju; // Increase the counter by one rf++; } encryptedMessage[rf] = -1; cout << "\n\nTHE ENCRYPTED MESSAGE IS\n"; // Loops till -1 for (rf = 0; encryptedMessage[rf] != -1; rf++) cout << encryptedMessage[rf]; } void decrypt() { long int hp, ju, key = decryptValue[0], v; rf = 0; // Loops till -1 while (encryptedMessage[rf] != -1) { ju = temporaryValue[rf]; // initialize v to 1 v = 1; for (j = 0; j < key; j++) { // Multiplies v with ju and stores the result in v v = v * ju; // Divides v with dp and stores the remainder in v v = v % dp; } // Updates hp by assigning v added to 96 hp = v + 96; decryptedMessage[rf] = hp; // Increase the counter by one rf++; } decryptedMessage[rf] = -1; cout << "\n\nTHE DECRYPTED MESSAGE IS\n"; // Loops till -1 for (rf = 0; decryptedMessage[rf] != -1; rf++) // Displays the decrypted message cout << decryptedMessage[rf]; cout << endl; }// End of function // main function definition int main() { primeFirstElement = 17; cout << "Num 1 : " << primeFirstElement; primeSecondElement = 13; cout << "\nNum 2: " <<primeSecondElement; // Checks if objectFlag is zero or first prime number is equals to second prime number then error message and stop fflush(stdin); cout << "\nEnter original message to encrypt: "; cin.getline(messageOriginalContent, 100); for (rf = 0; messageOriginalContent[rf] != '\0'; rf++) // Assigns message decryptedMessage[rf] = messageOriginalContent[rf]; // Multiplies first and second prime number and stores it in dp dp = primeFirstElement * primeSecondElement; // Multiplies first and second prime number minus one and stores it in e e = (primeFirstElement - 1) * (primeSecondElement - 1); // Calls the function to generate encryption key encryptionKey(); cout << "\nPossible values of e and d are: \n"; // Loops till j minus one times for (rf = 0; rf < j - 1; rf++) cout << "\n" << encryptValue[rf] << "\e" << decryptValue[rf]; encrypt(); // Calls the function to decrypt decrypt(); system("pause"); //return 0; }
true
f046697a8398d16f62906ad2773ca0f7280a5cd9
C++
bayertom/detectproj
/libalgo/source/structures/line/PolyLine.hpp
UTF-8
4,788
2.71875
3
[]
no_license
// Description: Polyline definition // Copyright (c) 2010 - 2013 // Tomas Bayer // Charles University in Prague, Faculty of Science // bayertom@natur.cuni.cz // This library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this library. If not, see <http://www.gnu.org/licenses/>. #ifndef PolyLine_HPP #define PolyLine_HPP #include "libalgo/source/structures/line/HalfEdge.h" template <typename T> PolyLine <T> :: PolyLine ( const Container <Node3DCartesian <T> *> *nl ) { //Create polyline from the list of nodes this->vertices_count = nl->size(); //Create half edges and set previous edges HalfEdge <T> *h = NULL, * h_old = NULL, *h_start = NULL; for ( unsigned int i = 0; i < this->vertices_count; i++ ) { if ( h != NULL ) { h = new HalfEdge <T> ( ( *nl ) [i], h_old, NULL, NULL ); } //Create first edge else { h = new HalfEdge <T> ( ( *nl ) [i], NULL, NULL, NULL ); h_start = h; } //Assign edge h_old = h; } //Set next edge for other half edges while ( h_old != h_start ) { //Get previous half edge HalfEdge <T> *h_prev = h_old->getPreviousEdge(); //Set next edge for previous edge h_prev->setNextEdge ( h_old ); //Decrement edge h_old = h_old->getPreviousEdge(); } //Set start edge of the Face this->edge = h_start; //Set Face for all half edges h = h_start; for ( unsigned int i = 0; i < vertices_count; i++, h = h->getNextEdge() ) { //Set Face h->setFace ( NULL ); } } template <typename T> PolyLine <T> ::~PolyLine() { //Get half edge if ( edge != NULL ) { //Get next edge in cell HalfEdge <T> *e = edge; HalfEdge <T> *e_prev = NULL; //Proces all edges of the Face for ( unsigned int i = 0; i < vertices_count ; i++ ) { //Get edge of the polyline e_prev = e; //First increment edge e = e->getNextEdge(); //Then delete edge delete e_prev; //Set edge to NULL e_prev = NULL; } } } template <typename T> void PolyLine <T> ::printPolyLine ( std::ofstream & file ) const { //Print polyline if ( edge != NULL ) { //Get next edge in cell HalfEdge <T> *e = edge; //Proces all edges of the Face for ( unsigned int i = 0; i < vertices_count; i++, e = e->getNextEdge() ) { //Print half edge e->printHalfEdge ( file ); } } } template <typename T> void PolyLine <T> ::toPoints3DCartesianList ( Container <Point3DCartesian<T> >&pl ) const { //Convert polyline to list if ( edge != NULL ) { //Get next edge in cell HalfEdge <T> *e = edge; //Proces all edges of the Face for ( unsigned int i = 0; i < vertices_count; i++, e = e->getNextEdge() ) { //Add point to the list pl.push_back ( * ( e->getPoint() ) ); } } } template <typename T> void PolyLine <T> ::toNodes3DCartesianList ( Container <Node3DCartesian <T> *> *nl ) const { //Convert polyline to nodes list if ( edge != NULL ) { //Get next edge in cell HalfEdge <T> *e = edge; for ( unsigned int i = 0; i < vertices_count; i++, e = e->getNextEdge() ) { //Add node to the list nl->push_back ( new Node3DCartesian <T> ( e->getPoint() ) ); } } } #endif
true
7c7ce5b41f5fea6bafd16f41a33e9b5940e87f1f
C++
junaidnz97/Competitive-Programming
/HACKEREARTH/Practice/Aryas_Stunts.cpp
UTF-8
1,103
2.734375
3
[]
no_license
#include<bits/stdc++.h> using namespace std; vector<int>warriors(10001); int maxs=0,sums=0,id=0; int dfs(vector<vector<int> >&g,vector<int>&visited,int i) { visited[i]=1; sums=sums+warriors[i]; //cout<<i<<endl; if(maxs<warriors[i]) { maxs=warriors[i]; id=i; } else if(maxs==warriors[i]) { id=min(id,i); } int j; for(j=0;j<g[i].size();j++) { if(visited[g[i][j]]==0) { dfs(g,visited,g[i][j]); } } } int main() { int n,m; cin>>n>>m; int i; vector<int>visited(n+1,0); for(i=1;i<=n;i++) { cin>>warriors[i]; } vector<vector<int> >g(n+1); int temp1,temp2; for(i=0;i<m;i++) { cin>>temp1>>temp2; g[temp1].push_back(temp2); g[temp2].push_back(temp1); } int died=0,injured=0; vector<int>burnedid; for(i=1;i<=n;i++) { if(visited[i]==0) { maxs=0,sums=0,id=0; dfs(g,visited,i); //cout<<maxs<<" "<<id<<endl; died+=maxs; injured+=sums-maxs; burnedid.push_back(id); } } cout<<died<<" "<<injured<<endl; sort(burnedid.begin(),burnedid.end()); for(i=0;i<burnedid.size();i++) { cout<<burnedid[i]<<" "; } cout<<endl; }
true
9ed620ccb3de6c7a0027d8e92b25522d17546ce2
C++
GaryOu101/CS100_FALL2020
/lab-07---factory-pattern-mogr002-gou004-lab7/mult.hpp
UTF-8
546
3.078125
3
[]
no_license
#ifndef __MULT_HPP__ #define __MULT_HPP__ #include "op.hpp" using namespace std; class Mult: public Base { public: Mult(Base* leftOp, Base* rightOp):Base(){ leftNum = leftOp -> evaluate(); rightNum = rightOp -> evaluate(); leftStr = leftOp -> stringify(); rightStr = rightOp -> stringify(); } virtual double evaluate(){ return (leftNum * rightNum); } virtual string stringify(){ return (leftStr + " * " + rightStr); } private: string leftStr; string rightStr; double leftNum; double rightNum; }; #endif
true
6a69bcfee2d780c646468d4c0ffe4e3fbda3339d
C++
JiangKevin/FishEngine
/Engine/Source/FishEngine/Asset/Resources.cpp
UTF-8
901
2.515625
3
[ "MIT" ]
permissive
#include <FishEngine/Resources.hpp> #include <boost/algorithm/string.hpp> namespace FishEngine { AssetType Resources::GetAssetType(Path const & extension) { auto ext = boost::to_lower_copy(extension.string()); //auto ext = path.extension(); if (ext == ".jpg" || ext == ".png" || ext == ".jpeg" || ext == ".tga" || ext == ".dds" || ext == ".psd") { return AssetType::Texture; } else if (ext == ".obj" || ext == ".fbx") { return AssetType::Model; } else if (ext == ".shader" || ext == ".surf") { return AssetType::Shader; } else if (ext == ".mat") { return AssetType::Material; } else if (ext == ".hpp" || ext == ".cpp") { return AssetType::Script; } else if (ext == ".prefab") { return AssetType::Prefab; } else if (ext == ".mp3" || ext == ".ogg" || ext == ".wav") { return AssetType::AudioClip; } return AssetType::Unknown; } }
true
f8ff8b642533326d50939a12e212e2635df0dbcc
C++
markwhittyunsw/MTRN2500-T3-2019-Week-10-Lectures
/stack.h
UTF-8
2,178
3.84375
4
[ "MIT" ]
permissive
#ifndef STACK_H #define STACK_H #include <iostream> using namespace std; #define MEMORY_ALLOCATION_FAILED -1 // Class template template <class T> class Stack { private: int Size; T* StackPointer; int Top; int ErrorCode; public: Stack(); Stack(int size); ~Stack(); bool Push(const T& obj); bool Pop(T& obj); bool Empty(); bool Full(); int GetSize(); int GetErrorCode(); T* GetStackPointer(); }; //Class member function templates - does not generate code template <class T> Stack<T>::Stack() { Top = 0; StackPointer = NULL; Size = 10; StackPointer = new T[Size]; if (StackPointer == NULL) ErrorCode = MEMORY_ALLOCATION_FAILED; } template <class T> Stack<T>::Stack(int size) { Top = 0; StackPointer = NULL; Size = size; StackPointer = new T[Size]; if (StackPointer == NULL) ErrorCode = MEMORY_ALLOCATION_FAILED; } template <class T> Stack<T>::~Stack() { if(StackPointer != NULL) delete [] StackPointer; } template <class T> bool Stack<T>::Push(const T& obj) { if(!Full()) { *(StackPointer + Top++) = obj; return true; } else return false; } template <class T> bool Stack<T>::Pop(T& obj) { if(!Empty()) { obj = *(StackPointer + Top--); return true; } else return false; } template <class T> bool Stack<T>::Empty() { if(Top < 0) return true; else return false; } template <class T> bool Stack<T>::Full() { if(Top >= Size) return true; else return false; } template <class T> int Stack<T>::GetSize() { return Size; } template <class T> T* Stack<T>::GetStackPointer() { return StackPointer; } template <class T> int Stack<T>::GetErrorCode() { return ErrorCode; } // Function Templates template<class T> void PrintArray(T* ptr, int n) { for(int i = 0; i < n; i++) cout << setw(10) << setprecision(3) << fixed << *(ptr+i) << endl; cout << endl; } template<class T> void PrintArray(T* ptr, int start, int end) { for(int i = start; i < end; i++) cout << setw(10) << setprecision(3) << fixed << *(ptr+i) << endl; cout << endl; } #endif // STACK_H
true
dbbdc9fffc827390bcdf5f6adde48eb185472bd5
C++
Taurus-Chao/TreeIncpp
/Tree_c++/source.cpp
UTF-8
883
2.875
3
[]
no_license
#include"MytreeFun.h" #include<iostream> #include<list> using namespace std; int main() { MytreeFun t1; t1.insertIterative(6); t1.insertIterative(4); t1.insertIterative(8); t1.insertIterative(3); t1.insertIterative(5); t1.insertIterative(7); t1.insert(9); //t1.insert(11); //cout << endl; //t1.printLevelOrderZigzag(); /*int pre[] = { 4,1,3,5,2,8,6,7,9 }; int in[] = {4,3,2,5,8,1,7,9,6 }; t1.buildTreeBy_PreIn(pre, in,9); t1.printPostorderIterative();*/ /*int array[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; t1.sortedArray2BST(array, 8); t1.printLevelOrder();*/ //list<int> l; //l.push_back(1); //l.push_back(2); //l.push_back(3); //l.push_back(4); //t1.sortedList2BST(l); //t1.printLevelOrder(); //cout<<t1.findPaths(16); Node* n1 = t1.find(3); Node* n2 = t1.find(8); Node *res = t1.lowestCommonAncestor(n1, n2); cout << res->element; system("pause"); }
true
0b010aa086b79f09186eade985382903f3b6da93
C++
Zedidle/myDataStructures
/Tree/AVL/AVLTreeNode.cpp
UTF-8
1,363
3.34375
3
[]
no_license
// Created by Kadir Emre Oto on 06.08.2018. #include "AVLTreeNode.h" template <class T> AVLTreeNode<T>::AVLTreeNode(T value) : value(value) { count = 1; height = 1; left = nullptr; right = nullptr; } template <class T> void AVLTreeNode<T>::updateValues() { // count 等于 两个子节点的count相加 + 加上根结点自己; count = (left != nullptr ? left->count : 0) + (right != nullptr ? right->count : 0) + 1; // height 等于两个子节点里最高的 + 自身结点的1个高度; height = std::max(left != nullptr ? left->height : 0, right != nullptr ? right->height : 0) + 1; } template <class T> int AVLTreeNode<T>::balanceFactor() { // 计算平衡因子:左子树高度 - 右子树高度 return (left != nullptr ? left->height : 0) - (right != nullptr ? right->height : 0); } template <class T> AVLTreeNode<T>* AVLTreeNode<T>::left_rotate() { AVLTreeNode<T>* R = right; right = R->left; R->left = this; this->updateValues(); R->updateValues(); return R; } template <class T> AVLTreeNode<T>* AVLTreeNode<T>::right_rotate() { AVLTreeNode<T>* L = left; left = L->right; L->right = this; this->updateValues(); L->updateValues(); return L; } template class AVLTreeNode<int>; template class AVLTreeNode<short>; template class AVLTreeNode<long>; template class AVLTreeNode<long long>; template class AVLTreeNode<std::string>;
true
632eda9d0912995f6d7994a1c1b018e30ec9534e
C++
yury-dymov/legacy_l2auth
/catx/catxfunc.cpp
UTF-8
2,242
2.65625
3
[]
no_license
#include "catxfunc.h" namespace CatX { bool Func::mycmp (const CatX::String & str1, const CatX::String & str2, const unsigned int segm) { if (str2.length () <= str1.length () - segm) { for (unsigned int i = 0; i < str2.length (); ++i) { if (str1[segm + i] != str2[i]) { return true; } } return false; } else { return true; } } bool Func::mycmp_to_lower (const CatX::String & str1, const CatX::String & str2, const unsigned int segm) { if (str2.length () <= str1.length () - segm) { for (unsigned int i = 0; i < str2.length (); ++i) { if (std::tolower (str1[segm + i]) != std::tolower (str2[i])) { return true; } } return false; } else { return true; } } unsigned int Func::skipComment (const CatX::String & str, const unsigned int i) { unsigned int j = i; for (; j < str.length (); ++j) { if (!mycmp (str, "*/", j)) { j += 2; break; } } return j; } void Func::cx_write (FILE *f, const CatX::String & str, int encode) { if (encode == ANSI) { fprintf (f,"%s\r\n", str.c_str ()); } else if (encode == UTF) { if (ftell (f) == 0) { fprintf (f, "%c%c", -1, -2); } CatX::String out; for (unsigned int i = 0; i < str.length (); ++i) { out += str[i]; out += (char)0; } out += '\r'; out += (char)0; out += '\n'; out += (char)0; fwrite (out.c_str (), sizeof (char), out.length (), f); } } CatX::String Func::trim (const CatX::String & str) { unsigned int first = 0; unsigned int last = str.length (); if (last) { for (unsigned int i = 0; i < str.length (); ++i) { if (!isspace (str[i])) { first = i; break; } } for (unsigned int i = last - 1; i > 0; --i) { if (!isspace (str[i])) { last = i; break; } } if (last != str.length ()) { CatX::String ret = str; if (isspace (ret[ret.length () - 1])) { return ret; } else { return ret; } } else { return str; } } else { return ""; } } }
true
9c228d7182b4ac6a80332a4fe39b7a944b17637f
C++
PMRocha/Laig
/segunda entrega/LAIGvs10/src/Node.h
UTF-8
1,323
2.609375
3
[]
no_license
#ifndef NODE_H #define NODE_H #include "Appearance.h" #include "Transformation.h" #include "SceneObject.h" #include "Animation.h" #include <iostream> class Node { string id; pair<string,Appearance*> nodeAppearance; vector<Transformation* > transformations; vector<SceneObject*> objects; vector<string> childNodeIds; float textT,textS; bool DisplayList; GLuint displayListId; Animation* animation; public: Node(string id, bool displaylist=false); Node(void); ~Node(void); string getId(); void addTransformation(Transformation* transformation); void addObject(SceneObject* object); void addchildId(string id); vector<string> getChildNodeIds() const; pair<string, Appearance*> getNodeAppearance() const; void setNodeAppearance(pair<string, Appearance*> nodeAppearance); vector<Transformation*> getTransformations() const; void setTransformations(vector<Transformation*> transformations); void setTransMatrix(float a[16]); vector<SceneObject*> getObjects() const; void setObjects(vector<SceneObject*> objects); float transMatrix[16]; void setTextT(float t); void setTextS(float s); float getTextT(); float getTextS(); bool getDisplayList(); void setDisplayList(bool displayList); void createDisplayList(GLuint ID); GLuint getDisplayListId(); void setAnimation(Animation* animation); }; #endif
true
b842e57f01f829aa92efae3e1f3fdb7f66dacf46
C++
desy-cms/analysis
/Analysis/MssmHbb/src/Measurement.cpp
UTF-8
1,597
2.703125
3
[]
no_license
#include "Analysis/MssmHbb/interface/Measurement.h" Measurement::Measurement() : median_(0), plus1G_(0), minus1G_(0), plus2G_(0), minus2G_(0){}; Measurement::Measurement(const double& median) : median_(median), plus1G_(0), minus1G_(0), plus2G_(0), minus2G_(0) {}; Measurement::Measurement(const double& median, const double& err) : median_(median), plus1G_(median+err), minus1G_(median-err), plus2G_(median+2*err), minus2G_(median-2*err) {}; Measurement::Measurement(const double& median, const double& plus1G, const double& minus1G, const double& plus2G, const double& minus2G) : median_(median), plus1G_(plus1G), minus1G_(minus1G), plus2G_(plus2G), minus2G_(minus2G) {}; Measurement::Measurement(const double& median, const double& plus1G, const double& minus1G) : median_(median), plus1G_(plus1G), minus1G_(minus1G){ plus2G_ = median + (plus1G - median)*2; minus2G_ = median + (minus1G - median)*2; }; double Measurement::getMedian() const { return median_; } void Measurement::setMedian(const double& median) { median_ = median; } double Measurement::getMinus1G() const { return minus1G_; } void Measurement::setMinus1G(const double& minus1G) { minus1G_ = minus1G; } double Measurement::getMinus2G() const { return minus2G_; } void Measurement::setMinus2G(const double& minus2G) { minus2G_ = minus2G; } double Measurement::getPlus1G() const { return plus1G_; } void Measurement::setPlus1G(const double& plus1G) { plus1G_ = plus1G; } double Measurement::getPlus2G() const { return plus2G_; } void Measurement::setPlus2G(const double& plus2G) { plus2G_ = plus2G; }
true
bab0ce23d77420562ea38f537ebc1d99190c2b17
C++
justAburger/week10ex1
/Item.h
UTF-8
813
3.453125
3
[]
no_license
#pragma once #include<iostream> #include<string> #include<algorithm> class Item { public: Item(std::string, std::string, double); ~Item(); double totalPrice() const; //returns _count*_unitPrice bool operator <(const Item& other) const; //compares the _serialNumber of those items. bool operator >(const Item& other) const; //compares the _serialNumber of those items. bool operator ==(const Item& other) const; //compares the _serialNumber of those items. //get and set functions std::string getSerial() const; double getPrice() const; std::string getName() const; int getCount() const; void setCount(int count); private: std::string _name; std::string _serialNumber; //consists of 5 numbers int _count; //default is 1, can never be less than 1! double _unitPrice; //always bigger than 0! };
true
e94d63eecd8c16f72074a4668bef43d4b69afd68
C++
hyperrhelen/ECS40
/Project5/appointment.cpp
UTF-8
2,044
3.453125
3
[]
no_license
// Helen Chac && Gabriel Chan #include <cstring> #include <iostream> #include <iomanip> #include "appointment.h" using namespace std; Appointment::Appointment() : subject(NULL) , location(NULL) { } // Appointment() Appointment::Appointment(const char* s) : location(NULL) { subject = new char[strlen(s) + 1]; strcpy(subject, s); } // Appointment() Appointment::~Appointment() { if(subject) delete [] subject; if(location) delete [] location; } // ~Appointment() bool Appointment::operator==(const Appointment &appt) const { return strcmp(subject, appt.subject) == 0; } // operator==() ostream& operator<< (ostream &os, const Appointment &a) { os << a.startTime; os << a.endTime; os << setw(15) << left << a.subject << " " << a.location << endl; return os; } // operator<<() Appointment& Appointment::operator= (const Appointment &a) { if(this == &a) return *this; if(subject) delete [] subject; if(location) delete [] location; startTime = a.startTime; endTime = a.endTime; subject = new char[strlen(a.subject) + 1]; strcpy(subject, a.subject); location = new char[strlen(a.location) + 1]; strcpy(location, a.location); return *this; } // operator= istream& operator>> (istream & is, Appointment &a) { char s[80]; cout << "Subject >> "; is.getline(s,80); a.subject = new char[strlen(s) + 1]; strcpy(a.subject, s); cout << "Location >> "; is.getline(s,80); a.location = new char[strlen(s) + 1]; strcpy(a.location, s); do { cout << "Start time >> "; is >> a.startTime; cout << "End time >> "; is >> a.endTime; if(a.endTime < a.startTime) cout << "Start time is later than end time!\n"; } while (a.endTime < a.startTime); return is; } // operator>> void Appointment::read() { char *ptr; ptr = strtok(NULL, ","); subject = new char[strlen(ptr) + 1]; strcpy(subject, ptr); startTime.read(); endTime.read(); ptr = strtok(NULL, ","); location = new char[strlen(ptr) + 1]; strcpy(location, ptr); } // read()
true
badbc555940faf5d14a01e4c3bb1f47dc89e1c2d
C++
AlexAlestra100/Alexander-College-Projects
/Data Structures & Algorithms/InsertSearch/InsertSearch.cpp
UTF-8
2,638
3.71875
4
[]
no_license
/* Alexander Alestra Prof. Sabzevary CISP 430 03-29-2020 */ #include <iostream> #include <string> #include <fstream> using namespace std; string names[10]; struct node { string name; node* next; }; void AddN(node* head, string val) { node* nn = new node; nn->name = val; nn->next = head; head = nn; } void ReadFile() { int i = 0; string in; ifstream inF; inF.open("input.txt"); while(!inF.eof()) { inF >> in; names[i] = in; i++; } inF.close(); } struct TreeNode { string name; node* head; TreeNode* left; TreeNode* right; }; void AddT(TreeNode *&leaf, string name) { leaf = new TreeNode; leaf->name = name; leaf->left = NULL; leaf->right = NULL; } void Insert(TreeNode *&root, string name) { bool done = false; TreeNode *leaf = root; if(!root) { AddT(root, name); } else { while(!done) { if(name == leaf->name) { AddN(leaf->head, name); done = true; } else if(name > leaf->name) { if(leaf->left != NULL) { leaf = leaf->left; } else { AddT(leaf->left, name); done = true; } } else { if(leaf->right != NULL) { leaf = leaf->right; } else { AddT(leaf->right, name); done = true; } } } } } bool searchR(TreeNode* leaf, string name) { bool found = false; if(leaf) { if(name == leaf->name) { int c = 0; found = true; cout << "Found: " << name << " "; if(leaf->head) { c++; } cout << "Count: " << c << endl; } else if(name > leaf->name) { found = searchR(leaf->left, name); cout << "Left side: " << name << endl; } else { found = searchR(leaf->right, name); cout << "Right side: " << name << endl; } } } int main() { ReadFile(); TreeNode* root = NULL; string name; for(int i = 0; i < 10; i++) { Insert(root, names[i]); } cout << "Insert a string name to search: "; cin >> name; cout << endl; searchR(root, name); return 0; }
true
5b2be7e302aaae51f398b0527e2f925cdde9e09f
C++
wired7/COMP477
/NoiseTexture.h
UTF-8
3,481
3.25
3
[]
no_license
#pragma once // Std. Includes #include <string> #include <fstream> #include <sstream> #include <iostream> #include <vector> #include "glm.hpp" enum noiseType{ STATIC , WOOD , RANDOM ,CLOUDS , MARBLE}; using namespace std; class NoiseTexture{ public: float **noise; glm::vec3 **colors; NoiseTexture(int col , int row ){ this->col = col; this->row = row; this->width = col; this->height = row; noise = new float*[row]; colors = new glm::vec3*[row]; for(int i = 0 ; i< row ; i++){ noise[i] = new float[col]; colors[i] = new glm::vec3[col]; } } void createHeightMap(int layerCount , noiseType type){ for (int i = 0; i < row ; i++){ for (int j = 0; j < col; j++) { noise[i][j] = (rand() % 32768) / 32768.0; } } switch(type){ case STATIC : { createStatic(layerCount); break; } case CLOUDS: { createClouds(layerCount); break; } } } void cleanUp(){ // clean up for(int i = 0 ; i < row ; i++){ delete [] noise[i]; delete [] colors[i]; } delete [] noise; delete [] colors; } private: int width , height; int row , col; float layeringTexture(int x, int y, float zoomFactor) { float value = 0.0, initialZoom = zoomFactor; while(zoomFactor >= 1) { value += smoothMagnification(x / zoomFactor, y / zoomFactor) * zoomFactor; zoomFactor /= 2.0f; } return ((128 * value) / initialZoom); } double smoothMagnification(float x, float y) { float xFraction = x - int(x); float yFraction = y - int(y); // we get the indices of the noise array based on the zoom // to insure the indices wrap around, incase out of bound int x1 = (int(x) + width) % width; int y1 = (int(y) + height) % height; int x2 = (int(x)-1 + width) % width; int y2 = (int(y)-1 + height) % height; //smooth the noise with bilinear interpolation float bilinearInterpolatedVal = 0.0f; bilinearInterpolatedVal += xFraction * yFraction * noise[y1][x1] ; bilinearInterpolatedVal += (1 - xFraction) * yFraction * noise[y1][x2] ; bilinearInterpolatedVal += xFraction * (1 - yFraction) * noise[y2][x1] ; bilinearInterpolatedVal += (1 - xFraction) * (1 - yFraction) * noise[y2][x2] ; return bilinearInterpolatedVal; } void createStatic(int layerCount){ for (int i = 0; i < row ; i++){ for (int j = 0; j < col; j++) { colors[i][j] = glm::vec3(layeringTexture(i, j, layerCount)); } } } void createClouds(int layerCount){ int colorZ; for(int i = 0 ; i < row ; i++){ for(int j = 0; j<col ; j++){ colorZ = (20 + int(layeringTexture(i,j,layerCount))+255)%255; colors[i][j] = glm::vec3(100,100,colorZ); } } } };
true
5688b4c9dd98f0f2e16c22a51cd0a3dc38ad29d7
C++
Lumpros/Zombie-Survival
/GameActor.cpp
UTF-8
1,027
3.078125
3
[]
no_license
#include "GameActor.h" bool PZS::GameActor::HandleCollisionWithBarrier(SDL_Rect rect) noexcept { if (abs(hitbox.x - rect.x) > 200) return false; SDL_Rect intersection; if (SDL_IntersectRect(&hitbox, &rect, &intersection)) { if (intersection.w <= intersection.h) { if (hitbox.x < rect.x) hitbox.x -= intersection.w; else hitbox.x += intersection.w; } else { if (hitbox.y < rect.y) hitbox.y -= intersection.h; else hitbox.y += intersection.h; } return true; } return false; } double PZS::GameActor::CalculateRotationAngle(SDL_Point point1, SDL_Point point2) noexcept { double angle = 0.0; if (point1.x == point2.x) { if (point1.y > point2.y) angle = 90.0; else angle = 270.0; } else { double dir_factor = (static_cast<double>(point2.y) - point1.y) / (static_cast<double>(point2.x) - point1.x); angle = atan(dir_factor) * 180 / M_PI; if (point2.x > point1.x) angle += 180; } return angle; }
true
b9e8a9c3989129c251dfeb1ba4e3fbcfc5d64632
C++
vinnilla/USC_IntroToCplusplus_Work
/monopolyConsole/Monopoly/action.cpp
UTF-8
320
2.765625
3
[]
no_license
//action.cpp #include "action.h" #include <string> using namespace std; void Action::populate(string text1, string text2, string text3) { text[0] = text1; text[1] = text2; text[2] = text3; return; } void Action::retrieve(string Array[]) { Array[0] = text[0]; Array[1] = text[1]; Array[2] = text[2]; return; }
true
c57e91ddaea0020966041161cbe8b70216547d05
C++
Outerskyb/baekjoon
/7226/main.cpp
UHC
1,914
3.046875
3
[]
no_license
#include <iostream> #include <queue> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); priority_queue<int> q1; priority_queue<int, vector<int>, greater<int>> q2; int ac = 0, dc = 0, in = 0; int T; cin >> T; while (T--) { int k; cin >> k; ac = dc = in = 0; for (int i = 0; i < k; i++) { char c; int n; cin >> c >> n; if (c == 'I') { if (q1.size() > q2.size() && n < q1.top()) { q1 = priority_queue<int>(); auto temp = q2; for (int i = 0; i < q2.size(); i++) q1.push(temp.top()), temp.pop(); } q1.push(n); if (q2.size() > q1.size() && n > q2.top()) { q2 = priority_queue<int, vector<int>, greater<int>>(); auto temp = q1; for (int i = 0; i < q1.size(); i++) q2.push(temp.top()), temp.pop(); } q2.push(n); ++in; } else if (n == 1 && ac + dc < in) { q1.pop(); ++ac; } else if (ac + dc < in) { q2.pop(); ++dc; } if (in != 0 && ac + dc == in) { q1 = priority_queue<int>(); q2 = priority_queue<int, vector<int>, greater<int>>(); in = ac = dc = 0; } } // // 1 q1.top == q2.top if (ac + dc < in) { cout << q1.top() << ' ' << q2.top() << '\n'; } //ac+dc == in̸ Ƽ else { cout << "EMPTY\n"; } } }
true
81f8aef2657519fb19a3a711607375bf9bf477fc
C++
thanhchinguyenpk/mario_scene
/05-ScenceManager/GameObject.h
UTF-8
3,260
2.625
3
[]
no_license
#pragma once #include <Windows.h> #include <d3dx9.h> #include <vector> #include "Sprites.h" #include "Animations.h" using namespace std; #define ID_TEX_BBOX -100 // special texture to draw object bounding box class CGameObject; typedef CGameObject * LPGAMEOBJECT; struct CCollisionEvent; typedef CCollisionEvent * LPCOLLISIONEVENT; struct CCollisionEvent { LPGAMEOBJECT obj; float t, nx, ny; float dx, dy; // *RELATIVE* movement distance between this object and obj CCollisionEvent(float t, float nx, float ny, float dx = 0, float dy = 0, LPGAMEOBJECT obj = NULL) { this->t = t; this->nx = nx; this->ny = ny; this->dx = dx; this->dy = dy; this->obj = obj; } static bool compare(const LPCOLLISIONEVENT &a, LPCOLLISIONEVENT &b) { return a->t < b->t; } }; class CGameObject { public: int type; int w; int h; int id_grid; int id; bool is_appeared = false; bool is_cam_coming = false; float x; float y; float dx; // dx = vx*dt float dy; // dy = vy*dt float vx; float vy; int nx = 1; int ny = 1; int state; bool used = false; DWORD dt; LPANIMATION_SET animation_set; /*thay vì chứa nguyên một cái vector gồm danh sách các animation mình set ngay lúc đầu thì đơn giản mình chỉ chứa con trỏ đến nguyên một cái animationset như thế nào là một animationset? animation set là bao gồm hết tất cả các animation của nhân vật đó luôn .Chẳng hạn như đối với mario thì bao gồm cả animation đi qua bên trái, đi qua bên phải, lên trên rồi nhảy,...nhỏ lớn gì là phải có hết nó sẽ giúp tiết kiệm, thay vì phải lưu một vector trong một object, nó giúp mình khởi tạo tốt hơn, nhanh hơn. khuyết: nhiều đối tượng chia sẽ một animationset, thì các con đó giống như là đồng bộ với nhau. */ public: void DeleteWhenOutOfCam(); bool CheckOverLap(float l_a, float t_a, float r_a, float b_a, float l_b, float t_b, float r_b, float b_b) { return (l_a < r_b && r_a > l_b && t_a < b_b && b_a > t_b); } float GetX() { return this->x; } float GetY() { return this->y; } int GetNX() { return this->nx; } void SetPosition(float x, float y) { this->x = x, this->y = y; } void SetSpeed(float vx, float vy) { this->vx = vx, this->vy = vy; } void GetPosition(float &x, float &y) { x = this->x; y = this->y; } void GetSpeed(float &vx, float &vy) { vx = this->vx; vy = this->vy; } int GetState() { return this->state; } void RenderBoundingBox(); void SetAnimationSet(LPANIMATION_SET ani_set) { animation_set = ani_set; } LPCOLLISIONEVENT SweptAABBEx(LPGAMEOBJECT coO); void CalcPotentialCollisions(vector<LPGAMEOBJECT> *coObjects, vector<LPCOLLISIONEVENT> &coEvents); void FilterCollision( vector<LPCOLLISIONEVENT> &coEvents, vector<LPCOLLISIONEVENT> &coEventsResult, float &min_tx, float &min_ty, float &nx, float &ny); //&rdx; //&rdy; CGameObject(); virtual void GetBoundingBox(float &left, float &top, float &right, float &bottom) = 0; virtual void Update(DWORD dt, vector<LPGAMEOBJECT> *coObjects = NULL); virtual void Render() = 0; virtual void SetState(int state) { this->state = state; } ~CGameObject(); };
true
41eab5bda81b19a30cca113058861f13e28013f1
C++
Devang-25/100DaysOfCode
/nandini3698/Day15/activityselc.cpp
UTF-8
1,633
3.078125
3
[]
no_license
// Geeksforgeeks\Must_do_questions\Greedy Problem-Activity Selection /*Given N activities with their start and finish times. Select the maximum number of activities that can be performed by a single person, assuming that a person can only work on a single activity at a time. Note : The start time and end time of two activities may coincide. Input: The first line contains T denoting the number of testcases. Then follows description of testcases. First line is N number of activities then second line contains N numbers which are starting time of activies.Third line contains N finishing time of activities. Output: For each test case, output a single number denoting maximum activites which can be performed in new line. Constraints: 1<=T<=50 1<=N<=1000 1<=A[i]<=100*/ #include <bits/stdc++.h> using namespace std; #define ll long long #define test ll t;cin>>t;while(t--) bool sortpair(const pair<ll,ll>&a,const pair<ll,ll>&b){ return (a.second<b.second); } int main() { test{ ll n,maxv=1; cin>>n; ll a[n],b[n]; for(ll i=0;i<n;i++) cin>>a[i]; for(ll i=0;i<n;i++) cin>>b[i]; vector<pair<ll,ll>>v; for(ll i=0;i<n;i++) v.push_back(make_pair(a[i],b[i])); sort(v.begin(),v.end(),sortpair); ll dp[n]; for(ll i=0;i<n;i++) dp[i]=1; for(ll i=1;i<n;i++){ for(ll j=0;j<i;j++){ if(v[i].first>=v[j].second && dp[i]<dp[j]+1) dp[i]=dp[j]+1; } maxv=max(maxv,dp[i]); } //cout<<dp[0]<<dp[1]<<dp[2]<<dp[3]; cout<<maxv<<endl; } return 0; }
true
100b2109605239aba1099f20e5bca7c8420b34ce
C++
zois-tasoulas/algoExpert
/medium/minNumberOfCoinsForChange.cpp
UTF-8
901
3.296875
3
[]
no_license
#include <iostream> #include <vector> int minNumberOfCoinsForChange(std::vector<int> denominations, int n); int main() { int n{78}; std::vector<int> denominations{5, 1, 10, 50, 25}; std::cout << minNumberOfCoinsForChange(denominations, n) << std::endl; return 0; } int minNumberOfCoinsForChange(std::vector<int> denominations, int n) { std::vector<int> amounts(n + 1, -1); amounts[0] = 0; for (int coin : denominations) { for (int amount{1}; amount < static_cast<int>(amounts.size()); ++amount) { if (amount < coin) { continue; } if (amounts[amount - coin] != -1 && (amounts[amount] == -1 || (amounts[amount] > amounts[amount - coin] + 1))) { amounts[amount] = amounts[amount - coin] + 1; } } } return amounts[n]; }
true
120a90cbaf75e4501af109db3a5af1b6b27b4fc1
C++
earljohn004/phonenumber_cpp_exercise
/test/phonedata_model_unit_test.cpp
UTF-8
12,167
2.921875
3
[]
no_license
/** * phonedata_model unit test source - version 1.00 * -------------------------------------------------------- * Created June 2021, * @author Earl John Abaquita (earl.abaquita@outlook.com) * * Description: * contains the unit tests for phonedata_model cpp * **/ #include "common_debug.h" #include "common_defines.h" #include "phonedata_model.h" #include "utility.h" #ifdef TEST_MODE #include "unit_test_framework.h" #endif #include <iostream> #include <string> #include <tuple> #ifdef TEST_MODE /** Test Description * Test the function to increase the phonenumber_send count of each * phone numbers receive with the same format */ TEST( phonenumber_send_increase ){ std::unique_ptr<phonedata_model> phonedata { std::make_unique<phonedata_model>() }; phonedata->increment_phonenumber_send("1234567890"); phonedata->increment_phonenumber_send("1234567890"); phonedata->increment_phonenumber_send("1234567890"); phonedata->increment_phonenumber_send("1234567890"); phonedata->increment_phonenumber_send("1234567890"); phonedata->increment_phonenumber_send("1234567890"); phonedata->increment_phonenumber_send("1234567890"); phonedata->increment_phonenumber_send("1234567890"); phonedata->increment_phonenumber_send("1234567890"); phonedata->increment_phonenumber_send("1234567890"); auto total = phonedata->get_total_send("1234567890"); VAR_LOG(total); ASSERT_EQUAL(10, total); } /** Test Description * Test the function to increase the phonenumber_send count of each * phone numbers receive with different formats */ TEST( phonenumber_send_increase_diff_format ){ std::unique_ptr<phonedata_model> phonedata { std::make_unique<phonedata_model>() }; std::unique_ptr<utility> util { std::make_unique<utility>() }; std::string test_output {}; retcode ret { retcode::ret_ng }; // ------- Begin of format 1 --------- ret = util->extract_phonenumber("+1 234 5678 900",test_output); ASSERT_EQUAL( "12345678900", test_output ); ASSERT_EQUAL( retcode::ret_ok, ret ); if(ret == retcode::ret_ok){ phonedata->increment_phonenumber_send( test_output ); }else {/* Do nothing */} // ------- End of format 1 ---------- // ------- Begin of format 2 --------- ret = util->extract_phonenumber("+(1) 234 5678 900",test_output); ASSERT_EQUAL( "12345678900", test_output ); ASSERT_EQUAL( retcode::ret_ok, ret ); if(ret == retcode::ret_ok){ phonedata->increment_phonenumber_send( test_output ); }else {/* Do nothing */} // ------- End of format 2---------- // ------- Begin of format 3 --------- ret = util->extract_phonenumber("+(1) 234-567-8900",test_output); ASSERT_EQUAL( "12345678900", test_output ); ASSERT_EQUAL( retcode::ret_ok, ret ); if(ret == retcode::ret_ok){ phonedata->increment_phonenumber_send( test_output ); }else {/* Do nothing */} // ------- End of format 3---------- // ------- Begin of format 4 --------- ret = util->extract_phonenumber("12345678900",test_output); ASSERT_EQUAL( "12345678900", test_output ); ASSERT_EQUAL( retcode::ret_ok, ret ); if(ret == retcode::ret_ok){ phonedata->increment_phonenumber_send( test_output ); }else {/* Do nothing */} // ------- End of format 4---------- auto total = phonedata->get_total_send("12345678900"); VAR_LOG(total); ASSERT_EQUAL(4, total); } /** Test Description * Test the function to increase the phonenumber_receive count of each * phone numbers receive with same format */ TEST( phonenumber_receive_increase ){ std::unique_ptr<phonedata_model> phonedata { std::make_unique<phonedata_model>() }; std::string test_output {}; phonedata->increment_phonenumber_receive("1234567890"); phonedata->increment_phonenumber_receive("1234567890"); phonedata->increment_phonenumber_receive("1234567890"); phonedata->increment_phonenumber_receive("1234567890"); phonedata->increment_phonenumber_receive("1234567890"); phonedata->increment_phonenumber_receive("1234567890"); phonedata->increment_phonenumber_receive("1234567890"); phonedata->increment_phonenumber_receive("1234567890"); phonedata->increment_phonenumber_receive("1234567890"); phonedata->increment_phonenumber_receive("1234567890"); auto total = phonedata->get_total_receive("1234567890"); VAR_LOG(total); ASSERT_EQUAL(10, total); } /** Test Description * Test the function to increase the phonenumber_receive count of each * phone numbers receive with different formats */ TEST( phonenumber_receive_increase_diff_format ){ std::unique_ptr<phonedata_model> phonedata { std::make_unique<phonedata_model>() }; std::unique_ptr<utility> util { std::make_unique<utility>() }; std::string test_output {}; retcode ret { retcode::ret_ng }; // ------- Begin of format 1 --------- ret = util->extract_phonenumber("+1 234 5678 900",test_output); ASSERT_EQUAL( "12345678900", test_output ); ASSERT_EQUAL( retcode::ret_ok, ret ); if(ret == retcode::ret_ok){ phonedata->increment_phonenumber_receive( test_output ); }else {/* Do nothing */} // ------- End of format 1 ---------- // ------- Begin of format 2 --------- ret = util->extract_phonenumber("+(1) 234 5678 900",test_output); ASSERT_EQUAL( "12345678900", test_output ); ASSERT_EQUAL( retcode::ret_ok, ret ); if(ret == retcode::ret_ok){ phonedata->increment_phonenumber_receive( test_output ); }else {/* Do nothing */} // ------- End of format 2---------- // ------- Begin of format 3 --------- ret = util->extract_phonenumber("+(1) 234-567-8900",test_output); ASSERT_EQUAL( "12345678900", test_output ); ASSERT_EQUAL( retcode::ret_ok, ret ); if(ret == retcode::ret_ok){ phonedata->increment_phonenumber_receive( test_output ); }else {/* Do nothing */} // ------- End of format 3---------- // ------- Begin of format 4 --------- ret = util->extract_phonenumber("12345678900",test_output); ASSERT_EQUAL( "12345678900", test_output ); ASSERT_EQUAL( retcode::ret_ok, ret ); if(ret == retcode::ret_ok){ phonedata->increment_phonenumber_receive( test_output ); }else {/* Do nothing */} // ------- End of format 4---------- auto total = phonedata->get_total_receive("12345678900"); VAR_LOG(total); ASSERT_EQUAL(4, total); } /** Test Description * Test the function to increase the phonenumber_send count of each * phone numbers send with different numbers */ TEST( phonenumber_multiple_send_increase ){ std::unique_ptr<phonedata_model> phonedata { std::make_unique<phonedata_model>() }; phonedata->increment_phonenumber_send("1234567890"); phonedata->increment_phonenumber_send("1234567890"); phonedata->increment_phonenumber_send("1234567890"); phonedata->increment_phonenumber_send("1234567890"); auto total = phonedata->get_total_send("1234567890"); ASSERT_EQUAL(4, total); phonedata->increment_phonenumber_send("0987654321"); phonedata->increment_phonenumber_send("0987654321"); phonedata->increment_phonenumber_send("0987654321"); phonedata->increment_phonenumber_send("0987654321"); total = phonedata->get_total_send("0987654321"); ASSERT_EQUAL(4, total); total = phonedata->get_total_send("111111111"); ASSERT_EQUAL(0, total); } /** Test Description * Test the function to increase the phonenumber_receive count of each * phone numbers receive with different numbers */ TEST( phonenumber_multiple_receive_increase ){ std::unique_ptr<phonedata_model> phonedata { std::make_unique<phonedata_model>() }; phonedata->increment_phonenumber_receive("1234567890"); phonedata->increment_phonenumber_receive("1234567890"); phonedata->increment_phonenumber_receive("1234567890"); phonedata->increment_phonenumber_receive("1234567890"); auto total = phonedata->get_total_receive("1234567890"); ASSERT_EQUAL(4, total); phonedata->increment_phonenumber_receive("0987654321"); phonedata->increment_phonenumber_receive("0987654321"); phonedata->increment_phonenumber_receive("0987654321"); phonedata->increment_phonenumber_receive("0987654321"); total = phonedata->get_total_receive("0987654321"); ASSERT_EQUAL(4, total); total = phonedata->get_total_receive("111111111"); ASSERT_EQUAL(0, total); } /** Test Description * Test the function to get the correct information of the phone number * with the highest recorded date and highest recorded recipient numbers * with a single phone number */ TEST( phonenumber_date_send_countqueue_test ){ std::unique_ptr<phonedata_model> phonedata { std::make_unique<phonedata_model>() }; std::string phonenumber {"12345678900"}; phonedata->add_date_information( phonenumber, "06-04-1993", "3830656" ); phonedata->add_date_information( phonenumber, "06-04-1993", "3830656" ); phonedata->add_date_information( phonenumber, "06-04-1993", "3844724" ); phonedata->add_date_information( phonenumber, "08-08-1996", "3844724" ); phonedata->add_date_information( phonenumber, "08-08-1996", "3830656" ); phonedata->add_date_information( phonenumber, "12-12-1996", "3830656" ); phonedata->add_date_information( phonenumber, "12-12-1996", "3830656" ); ASSERT_EQUAL(7, phonedata->get_total_send(phonenumber)); auto [getdate, gettotal, recepient] = phonedata->get_phone_max_date(phonenumber); ASSERT_EQUAL("06-04-1993", getdate); VAR_LOG(getdate); ASSERT_EQUAL(3, gettotal ); VAR_LOG(gettotal); ASSERT_EQUAL("3830656", recepient); VAR_LOG(recepient); } /** Test Description * Test the function to get the correct information of the phone number * with the highest recorded date and highest recorded recipient numbers * with multiple phonenumbers and varying dates */ TEST( phonenumber_date_send_countqueue_multiple_test ){ std::unique_ptr<phonedata_model> phonedata { std::make_unique<phonedata_model>() }; std::string phonenumber {"12345678900"}; phonedata->add_date_information( phonenumber, "06-04-1993", "3844724" ); phonedata->add_date_information( phonenumber, "06-04-1993", "3830656" ); phonedata->add_date_information( phonenumber, "06-04-1993", "3844724" ); phonedata->add_date_information( phonenumber, "06-04-1993", "3844724" ); phonedata->add_date_information( phonenumber, "08-08-1996", "3844724" ); phonedata->add_date_information( phonenumber, "08-08-1996", "3830656" ); phonedata->add_date_information( phonenumber, "12-12-1996", "3830656" ); phonedata->add_date_information( phonenumber, "12-12-1996", "3830656" ); ASSERT_EQUAL(8, phonedata->get_total_send(phonenumber)); { auto [getdate, gettotal, recepient] = phonedata->get_phone_max_date(phonenumber); ASSERT_EQUAL("06-04-1993", getdate); VAR_LOG(getdate); ASSERT_EQUAL(4, gettotal ); VAR_LOG(gettotal); ASSERT_EQUAL("3844724", recepient); VAR_LOG(recepient); } phonenumber = "12222333300"; phonedata->add_date_information( phonenumber, "01-01-2002", "3830656" ); phonedata->add_date_information( phonenumber, "03-14-2002", "3830656" ); phonedata->add_date_information( phonenumber, "03-14-2002", "3844724" ); phonedata->add_date_information( phonenumber, "08-01-2003", "3844724" ); phonedata->add_date_information( phonenumber, "08-01-2003", "3844724" ); phonedata->add_date_information( phonenumber, "08-01-2003", "3830656" ); phonedata->add_date_information( phonenumber, "02-28-2000", "3844724" ); phonedata->add_date_information( phonenumber, "02-28-2000", "3844724" ); phonedata->add_date_information( phonenumber, "02-28-2000", "3830656" ); phonedata->add_date_information( phonenumber, "02-28-2000", "3844724" ); ASSERT_EQUAL(10, phonedata->get_total_send(phonenumber)); { auto [getdate, gettotal, recepient] = phonedata->get_phone_max_date(phonenumber); ASSERT_EQUAL("02-28-2000", getdate); VAR_LOG(getdate); ASSERT_EQUAL(4, gettotal ); VAR_LOG(gettotal); ASSERT_EQUAL("3844724", recepient); VAR_LOG(recepient); } } /** Test Description * Test the function to get the correct information of the phone number * with the highest recorded recipient number */ TEST( phonenumber_vector_highest_element_check ){ std::unique_ptr<phonedata_model> phonedata { std::make_unique<phonedata_model>() }; std::vector<std::string> test_vector {"123", "456", "123", "456", "123", "789"}; std::string output; phonedata->get_largest_element(test_vector, output); ASSERT_EQUAL( "123", output ); } TEST_MAIN() #endif
true
eb6819eb7c1c779fea079049fc7b93ac47236927
C++
tommitah/cpp_mini_projects
/optimizations/opttest.cpp
UTF-8
171
3.03125
3
[]
no_license
#include <iostream> int main() { double value = 1; while(value < 1000000000000000000) { value += value / (1 / value); } std::cout << value; return 0; }
true
e2a112c2f5f60d6d060646ade01943e3438419bd
C++
tejasborkar74/ProblemSolvingIB-
/Backtracking/Generate_all_Parentheses_II.cpp
UTF-8
401
2.921875
3
[]
no_license
vector<string> ans; void solve(int open,int close,string temp,int n) { if(open>n)return; if(open==n && close==n) { ans.push_back(temp); } if(close>open) { return; } solve(open+1,close,temp + "(",n); solve(open,close+1,temp+")",n); } vector<string> Solution::generateParenthesis(int A) { ans.clear(); solve(0,0,"",A); return ans; }
true
85f3ff74e7198edcd6d462b119cd7c4be2e747e8
C++
MFC1989/acm
/1166/1166.cpp
UTF-8
1,428
2.75
3
[]
no_license
// 1166.cpp : Defines the entry point for the console application. // //#include "stdafx.h" #include <iostream> #include <cassert> #include <algorithm> #include <map> #include <vector> using namespace std; inline unsigned int factors(unsigned int n) { unsigned int i = 2, k = 0, m = n, count = 1; while (m != 1) { for (; i <= m; i++) { if (m % i == 0) { k = 1; while (m % i == 0) { k++; m /= i; } count *= k; } } } return count; } multimap<int ,int> m1; //int res; // //inline int factors(int tmp) //{ // res=0; // for (register int i=1;i<=(tmp>>1);i++) // { // if (tmp%i==0) // { // res++; // } // } // return (res+1); //} int main() { //m1.insert( make_pair(0,0)); int n; cin>>n; if (n<0||n>500000) { exit(0); } for (register int i=n;i>=1;i-- ) { m1.insert(make_pair(factors(i), i)); } pair<int,int> maxValuePair= *m1.rbegin(); //vector<pair<int, int>> vec; //for (multimap<int,int>::iterator it1=m1.begin();it1!=m1.end();it1++) //{ // pair<int,int> resultPair=* it1; // if (resultPair.first==maxValuePair.first) // { // cout<<resultPair.second<<" "<<resultPair.first/*<<endl*/; // //vec.push_back(make_pair(resultPair.second, resultPair.first)); // break; // } //} //multimap<int, int>::iterator itres =m1.find(maxValuePair.first); cout << maxValuePair.second << " " << maxValuePair.first << endl; return 0; }
true
db248698391cfca2d285e5159be593d7bbd96cdd
C++
czchen/programming-exercise
/LeetCode/rotate-array/rotate-array-0.cpp
UTF-8
756
2.953125
3
[]
no_license
class Solution { public: int get_gcd(int x, int y) { int z = y % x; if (z == 0) { return x; } return get_gcd(z, x); } void rotate(vector<int>& nums, int k) { if (k == 0) return; int pos = 0; int tmp = nums[pos]; int gcd = get_gcd(k, nums.size()); int loop = nums.size() / gcd; for (int i = 0; i < gcd; ++i) { int pos = i; int tmp = nums[pos]; for (int j = 0; j < loop; ++j) { int new_pos = (pos + k) % nums.size(); int new_tmp = nums[new_pos]; nums[new_pos] = tmp; pos = new_pos; tmp = new_tmp; } } } };
true
a761128ba8ae04f2e9d9b16b3e690d24d699fb36
C++
rayburgemeestre/processfighter
/src/states/challenged.cpp
UTF-8
1,457
2.640625
3
[]
no_license
#include "states/challenged.h" #include "states/countdown.h" #include <iostream> #include <SFML/Graphics.hpp> #include <sstream> #include "utils/menu.h" #include "states.h" #include "messages.h" #include "global_game_state.h" extern int window_width; extern int window_height; challenged::challenged(global_game_state &gs) : state_interface(gs, game_state::state_type::challenged), menu_(window_width, window_height) { } void challenged::initialize() { menu_.add_item(std::string("Fight this guy"), [&](){ game_state state(state_); auto new_state = states::factory(state.transition(game_state::transition_type::accept), global_game_state_); auto countdown_state = dynamic_cast<countdown *>(new_state.get()); if (countdown_state) { countdown_state->set_opponent(opponent_); countdown_state->set_challenger(false); next_state_ = std::move(new_state); } }); menu_.add_item("Run away like a coward", [&](){ game_state state(state_); next_state_ = std::move(states::factory(state.transition(game_state::transition_type::bail), global_game_state_)); }); menu_.add_item("Exit", [](){ std::exit(0); }); } void challenged::set_opponent(probed_opponent_type opp) { opponent_ = opp; } void challenged::handle(std::vector<std::unique_ptr<messages::message_interface>> msgs) { } void challenged::tick() { } void challenged::draw(sf::RenderTarget &renderTarget) { menu_.render(renderTarget); }
true
d6742e01bbeea0b5472c853306397257019761a8
C++
julienmcollins/DTD
/QuiteGoodMachine/Source/GameManager/Public/Timers/SecondsTimer.cpp
UTF-8
1,651
2.875
3
[]
no_license
#include "QuiteGoodMachine/Source/GameManager/Private/Timers/SecondsTimer.h" #include <stdio.h> #include <SDL2/SDL.h> // Initialize timer SecondsTimer::SecondsTimer() : delta_(0), is_paused_(false), is_started_(false) {} // Start timer function void SecondsTimer::Start() { if (is_started_) { return; } is_started_ = true; is_paused_ = false; start_ticks_ = steady_clock::now(); } // Stop timer function void SecondsTimer::Stop() { is_started_ = false; } // Pause timer void SecondsTimer::Pause() { if (is_paused_ || !is_started_) { return; } is_paused_ = true; paused_ticks_ = steady_clock::now(); } // Unpause timer void SecondsTimer::Unpause() { if (!is_paused_) { return; } is_paused_ = false; start_ticks_ += steady_clock::now() - paused_ticks_; } void SecondsTimer::Reset() { is_paused_ = false; start_ticks_ = steady_clock::now(); } // Get tick functions double SecondsTimer::GetTime() { if (!is_started_) { return 0; } if (is_paused_) { return duration_cast<seconds>(paused_ticks_ - start_ticks_).count(); } return duration_cast<seconds>(steady_clock::now() - start_ticks_).count(); } // Get delta time function double SecondsTimer::GetDeltaTime() { curr_tick_ = steady_clock::now(); delta_ = duration_cast<seconds>(curr_tick_ - last_tick_).count(); last_tick_ = curr_tick_; return delta_; } // Check states bool SecondsTimer::IsStarted() { // SecondsTimer is running and paused or unpaused return is_started_; } bool SecondsTimer::IsPaused() { // SecondsTimer is running and paused return is_paused_; }
true
d00b4e70db2a97c5fb5d58e40ad80beac9d3dbb5
C++
project-arcana/arcana-samples
/tests/pm/topo-fuzzer.cc
UTF-8
5,392
2.546875
3
[ "MIT" ]
permissive
#include <nexus/monte_carlo_test.hh> #include <iostream> #include <polymesh/Mesh.hh> #include <polymesh/debug.hh> #include <polymesh/objects.hh> #include <polymesh/properties.hh> #include <typed-geometry/tg-std.hh> namespace { struct Mesh3D { pm::unique_ptr<pm::Mesh> mesh; pm::vertex_attribute<tg::pos3> pos; static Mesh3D create() { Mesh3D m; m.mesh = pm::Mesh::create(); m.pos = {*m.mesh}; return m; } Mesh3D copy() const { Mesh3D m; m.mesh = mesh->copy(); m.pos = pos.copy_to(*m.mesh); return m; } void copy_from(Mesh3D const& m) { mesh->copy_from(*m.mesh); pos.copy_from(m.pos); } private: Mesh3D() = default; }; } // TODO: fix this test! MONTE_CARLO_TEST("pm::Mesh topology mct", disabled) { auto const get_vertex = [](Mesh3D const& m, unsigned idx) -> pm::vertex_handle { if (m.mesh->vertices().empty()) return pm::vertex_handle::invalid; tg::rng rng; rng.seed(idx); return m.mesh->vertices().random(rng); }; auto const get_halfedge = [](Mesh3D const& m, unsigned idx) -> pm::halfedge_handle { if (m.mesh->halfedges().empty()) return pm::halfedge_handle::invalid; tg::rng rng; rng.seed(idx); return m.mesh->halfedges().random(rng); }; auto const is_vertex_collapsible = [&](Mesh3D const& m, unsigned idx) { auto v = get_vertex(m, idx); return v.is_valid() && (v.is_isolated() || !v.is_boundary()); }; // auto const is_vertex_valid = [&](Mesh3D const& m, unsigned idx) { // auto v = get_vertex(m, idx); // return v.is_valid() && !v.is_removed(); // }; auto const can_add_or_get_edge_vv = [&](Mesh3D const& m, unsigned ia, unsigned ib) { auto va = get_vertex(m, ia); auto vb = get_vertex(m, ib); return va.is_valid() && vb.is_valid() && pm::can_add_or_get_edge(va, vb); }; auto const can_add_or_get_edge_hh = [&](Mesh3D const& m, unsigned ia, unsigned ib) { auto ha = get_halfedge(m, ia); auto hb = get_halfedge(m, ib); return ha.is_valid() && hb.is_valid() && pm::can_add_or_get_edge(ha, hb); }; auto const has_vertices_rng = [&](Mesh3D const& m, tg::rng&) { return !m.mesh->vertices().empty(); }; auto const has_edges_rng = [&](Mesh3D const& m, tg::rng&) { return !m.mesh->edges().empty(); }; auto const random_permutation = [&](tg::rng& rng, int size) { std::vector<int> p; p.resize(size); for (auto i = 0; i < size; ++i) p[i] = i; std::shuffle(p.begin(), p.end(), rng); return p; }; auto const add_triangle = [](Mesh3D& m) { auto v0 = m.mesh->vertices().add(); auto v1 = m.mesh->vertices().add(); auto v2 = m.mesh->vertices().add(); m.mesh->faces().add(v0, v1, v2); m.pos[v0] = {1, 0, 0}; m.pos[v1] = {0, 1, 0}; m.pos[v2] = {0, 0, 1}; }; auto const split_edge = [&](Mesh3D& m, tg::rng& rng) { auto e = m.mesh->edges().random(rng); auto np = mix(m.pos[e.vertexA()], m.pos[e.vertexB()], .5f); auto nv = m.mesh->edges().split(m.mesh->edges().random(rng)); m.pos[nv] = np; }; // random unsigned addOp("gen uint", [](tg::rng& rng) { return unsigned(rng()); }); // create and copy addOp("make mesh", [] { return Mesh3D::create(); }).execute_at_least(5); addOp("copy", [](Mesh3D const& m) { return m.copy(); }); addOp("copy_from", [](Mesh3D& lhs, Mesh3D const& rhs) { lhs.copy_from(rhs); }); // general addOp("clear", [](Mesh3D& m) { m.mesh->clear(); }); addOp("shrink_to_fit", [](Mesh3D& m) { m.mesh->shrink_to_fit(); }); addOp("reset", [](Mesh3D& m) { m.mesh->reset(); }); addOp("compactify", [](Mesh3D& m) { m.mesh->compactify(); }); // objects addOp("add cube", [](Mesh3D& m) { pm::objects::add_cube(*m.mesh, m.pos); }); addOp("add triangle", add_triangle); // vertices addOp("add vertex", [](Mesh3D& m) { m.mesh->vertices().add(); }); addOp("collapse vertex", [&](Mesh3D& m, unsigned idx) { m.mesh->vertices().collapse(get_vertex(m, idx)); }).when(is_vertex_collapsible); addOp("remove vertex", [&](Mesh3D& m, tg::rng& rng) { m.mesh->vertices().remove(m.mesh->vertices().random(rng)); }).when(has_vertices_rng); addOp("permute vertices", [&](Mesh3D& m, tg::rng& rng) { m.mesh->vertices().permute(random_permutation(rng, m.mesh->all_vertices().size())); }); // edges addOp("add_or_get edge vv", [&](Mesh3D& m, unsigned va, unsigned vb) { m.mesh->edges().add_or_get(get_vertex(m, va), get_vertex(m, vb)); }).when(can_add_or_get_edge_vv); addOp("add_or_get edge hh", [&](Mesh3D& m, unsigned ha, unsigned hb) { m.mesh->edges().add_or_get(get_halfedge(m, ha), get_halfedge(m, hb)); }).when(can_add_or_get_edge_hh); addOp("split edge", split_edge).when(has_edges_rng); // faces // TODO // halfedges // TODO // "pseudo invariants" addOp("edge exists", [](Mesh3D const& m, tg::rng& rng) { auto e = m.mesh->edges().random(rng); CHECK(pm::are_adjacent(e.vertexA(), e.vertexB())); }).when(has_edges_rng); // invariants addInvariant("consistent", [](Mesh3D const& m) { m.mesh->assert_consistency(); }); }
true
bd66ca934e9ab96a456e1f996adb8e46f1288041
C++
perfumez/BusReminder
/ReminderScreen/Settings.cpp
UTF-8
2,789
2.59375
3
[]
no_license
#include "Settings.h" #include <codecvt> #include <boost/locale/encoding_utf.hpp> using namespace kudd; namespace { #if 0 // convert UTF-8 string to wstring std::wstring utf8_to_wstring(const std::string& str) { std::wstring_convert<std::codecvt_utf8<wchar_t>> myconv; return myconv.from_bytes(str); } // convert wstring to UTF-8 string std::string wstring_to_utf8(const std::wstring& str) { std::wstring_convert<std::codecvt_utf8<wchar_t>> myconv; return myconv.to_bytes(str); } #else // GCC 에서는 wstring_convert 를 못쓰는듯 하다.. // https://stackoverflow.com/questions/15615136/is-codecvt-not-a-std-header std::wstring utf8_to_wstring(const std::string& str) { return boost::locale::conv::utf_to_utf<wchar_t>(str.c_str(), str.c_str() + str.size()); } std::string wstring_to_utf8(const std::wstring& str) { return boost::locale::conv::utf_to_utf<char>(str.c_str(), str.c_str() + str.size()); } #endif SubscribeInfo createSubcription(SubscribeInfo::Direction dir, const std::wstring& stopName, const std::wstring& stopId, std::pair<uint16_t, uint16_t>&& time) { SubscribeInfo si; si.setDirection(dir); si.setStopName(stopName); si.setStopId(stopId); si.setTime(std::move(time)); //si.setBusLines(std::move(lines)); return si; } const std::wstring GUPABAL(utf8_to_wstring("\xea\xb5\xac\xed\x8c\x8c\xeb\xb0\x9c")); const std::wstring GUPABAL_ID_TO_GOYANG(L"BS14360"); const std::wstring GUPABAL_ID_TO_SEOUL(L"BS14359"); } Configuration& Configuration::get() { static Configuration __instance__; return __instance__; } Configuration::Configuration() { makeDefault(); } bool Configuration::loadFrom(const std::wstring& filename) { return true; } bool Configuration::saveTo(const std::wstring& filename) const { return false; } void Configuration::makeDefault() { _subscriptions.clear(); // 구파발 -> 고양방향. _subscriptions[GUPABAL_ID_TO_GOYANG] = createSubcription(SubscribeInfo::WEST, GUPABAL, GUPABAL_ID_TO_GOYANG, { 450, 480 }); auto& stop1 = _subscriptions[GUPABAL_ID_TO_GOYANG]; stop1.addBusLine(L"9703", BusDisplayOption(L"ff0000", L"ffffff")); stop1.addBusLine(L"773", BusDisplayOption(L"0000ff", L"ffffff")); // 구파발 -> 서울방향. _subscriptions[GUPABAL_ID_TO_SEOUL] = createSubcription(SubscribeInfo::EAST, GUPABAL, GUPABAL_ID_TO_SEOUL, { 450, 480 }); auto& stop2 = _subscriptions[GUPABAL_ID_TO_SEOUL]; stop2.addBusLine(L"9703", BusDisplayOption(L"ff0000", L"ffffff")); stop2.addBusLine(L"773", BusDisplayOption(L"0000ff", L"ffffff")); } // 끝.
true
6f1fdd9d69094e253e32d95fbafaabf768b74a35
C++
domenipavec/Coursera-DiscreteOptimization
/coloring/lsSolver-unfeasible.cpp
UTF-8
6,085
2.78125
3
[ "MIT" ]
permissive
/* * lsSolver-unfeasible.cpp * * Copyright 2014 Domen <domen.ipavec@z-v.si> * * See LICENSE. * */ #include "lsSolver.hpp" #include <algorithm> #include <iostream> #include <stdlib.h> typedef std::pair<uint16_t, uint16_t> colorPair; typedef std::vector<colorPair> pairList; bool sortFunctionDesc(colorPair p1, colorPair p2) { return p1.second > p2.second; } bool sortFunctionAsc(colorPair p1, colorPair p2) { return (p1.second < p2.second || (p1.second == p2.second && (rand() %2 == 0))); } bool sortFunctionAscRand(colorPair p1, colorPair p2) { return (p1.second < p2.second ||(rand() %2 == 0)); } uint16_t getLowestUsedColor(const LSState & state) { // init color count pairList colorCount(state.nColors, colorPair(0,0)); for (uint16_t i = 0; i < state.nColors; i++) { colorCount[i].first = i; } // count colors for (intList::const_iterator it = state.verticesColors.cbegin(); it != state.verticesColors.cend(); ++it) { colorCount[*it].second++; } return std::min_element(colorCount.begin(), colorCount.end(), sortFunctionAsc)->first; } void removeColor(LSState & state, uint16_t color) { // one color less state.nColors--; // change all color numbers after this one (inclusive) for (uint16_t i = 0; i < state.nVertices; i++) { if (state.verticesColors[i] == color) { state.verticesColors[i] = rand() % state.nColors; state.infeasible.insert(i); } else if (state.verticesColors[i] > color) { state.verticesColors[i]--; } } } uint16_t getCollisionsVertex(const LSState & state, uint16_t vertex) { uint16_t c = 0; for (intList::const_iterator it = state.graph->neighbours[vertex].cbegin(); it != state.graph->neighbours[vertex].cend(); ++it) { if (state.verticesColors[vertex] == state.verticesColors[*it]) { c++; } } return c; } uint16_t getCollisions(const LSState & state) { uint16_t c = 0; for (intSet::const_iterator it = state.infeasible.cbegin(); it != state.infeasible.cend(); ++it) { c += getCollisionsVertex(state, *it); } return c; } uint16_t getBestColor(LSState & state, uint16_t vertex, uint16_t & bestColor) { // init color count pairList colorCount(state.nColors, colorPair(0,0)); for (uint16_t i = 0; i < state.nColors; i++) { colorCount[i].first = i; } // count neighbours per color for (intList::const_iterator it = state.graph->neighbours[vertex].cbegin(); it != state.graph->neighbours[vertex].cend(); ++it) { colorCount[state.verticesColors[*it]].second++; } // select best uint16_t currentColls = colorCount[state.verticesColors[vertex]].second; pairList::iterator min = std::min_element(colorCount.begin(), colorCount.end(), sortFunctionAsc); uint16_t bestColls = min->second; bestColor = min->first; return currentColls - bestColls; } void LSSolver::solve() { // reset the problem after timesMAX times LSState oldState = state; const uint16_t timesMAX = 100; uint16_t times = 0; // select how many colors we want while (state.nColors > 99) { uint16_t color = getLowestUsedColor(state); removeColor(state, color); times = 0; std::cerr << "Inf: " << state.infeasible.size() << " Colls: " << getCollisions(state) << std::endl; std::cerr << "Color " << color << " removed. nColors: " << state.nColors << std::endl; while (state.infeasible.size() > 0) { uint16_t bestVertex = 0xffff; uint16_t bestColor = 0xffff; uint16_t bestImprovement = 0; // iterate over infeasible list for (intSet::iterator it = state.infeasible.begin(); it != state.infeasible.end(); ++it) { // change this vertex uint16_t color; uint16_t improvement = getBestColor(state, *it, color); if (improvement > bestImprovement || (improvement == bestImprovement && (rand() % 2 == 0))) { bestColor = color; bestImprovement = improvement; bestVertex = *it; } // change all neighbours for (intList::iterator neighbour = state.graph->neighbours[*it].begin(); neighbour != state.graph->neighbours[*it].end(); ++neighbour) { // select how often to choose non faulty vertex // should be low enough to work well, but not too slow if (state.verticesColors[*it] == state.verticesColors[*neighbour] || rand() % 50 == 0) { improvement = getBestColor(state, *neighbour, color); if (improvement > bestImprovement || (improvement == bestImprovement && (rand() % 2 == 0))) { bestColor = color; bestImprovement = improvement; bestVertex = *neighbour; } } } } // change chosen vertex or terminate if (bestVertex != 0xffff) { state.verticesColors[bestVertex] = bestColor; if (getCollisionsVertex(state, bestVertex) != 0) { state.infeasible.insert(bestVertex); } else { state.infeasible.erase(bestVertex); } } else { if (times < timesMAX) { times++; if (times % 10 == 0) { std::cerr << "Times: " << times << std::endl; } continue; } else { std::cerr << "Reset" << std::endl; break; } } } if (times == timesMAX) { state = oldState; times = 0; } } }
true
dabef9016469d7340dabc02968c87168faaf9b39
C++
nileshkadam222/C-AND-CPP
/c++/clasnobjects/PH2.CPP
UTF-8
540
3.53125
4
[]
no_license
#include<iostream.h> #include<conio.h> class math { private: float a,b,c; public: void getdata() { cout<<"Enter two numbers: "; cin>>a>>b; } int sum() { c=a+b; return(c); } int sub() { c=a-b; return(c); } float div() { c=a/b; return(c); } int mul() { c=a*b; return(c); } }; void main() { math r; float a,b,c,d; clrscr(); r.getdata(); a=r.sum(); b=r.sub(); c=r.mul(); d=r.div(); cout<<"Add: "<<a<<endl<<"Sub: "<<b<<endl<<"Mul: "<<c<<endl<<"Div: "<<d<<endl; getch(); }
true
da66fae4ee38530912db2cba8e9b2f9079f8b4a1
C++
yutatanaka/TestProgram
/コンスト.cpp
SHIFT_JIS
618
3.109375
3
[]
no_license
// RXg #include <stdio.h> // NX class Hoge { const int* const func(const int a)const; // constɏĂ΁As\ // constɏĂ΁Aւs\ // const̒ŏĂ΁AȂ // consťɏĂ΁AoϐȂ }; Hoge h; void main() { int a = 10; int b = 20; const int max = 200;// 萔 int* const pa = &a; // AhX̍Đݒ肪oȂ const int* pb = &b; // gȂ getchar(); }
true
2944668abd22c2786771143d9d8a10d7b4855d36
C++
rodrigobmg/Cloudberry-Kingdom-Port
/Core/src/Content/FilesystemPc.cpp
UTF-8
1,694
3.03125
3
[]
no_license
#include <Content/FilesystemPc.h> #include <Content/File.h> #include <fstream> /** * File implementation for Pc. */ class FilePc : public File { std::fstream fs_; unsigned int size_; private: /// No copying. FilePc( const FilePc & ) { } /// No assignment. FilePc &operator = ( const FilePc & ) { return *this; } public: FilePc( const std::string &path, bool write ) : fs_( path, std::ios_base::in | std::ios_base::binary | ( write ? std::ios_base::out | std::ios_base::trunc : 0 ) ) { fs_.seekg( 0, std::ios_base::end ); size_ = static_cast< unsigned int >( fs_.tellg() ); fs_.seekg( 0 ); } /** * @see File::Read() */ size_t Read( char *buffer, size_t length ) { std::streamoff start = fs_.tellg(); fs_.read( buffer, length ); return static_cast< size_t >( fs_.tellg() - start ); } /** * @see File::Write() */ size_t Write( const char *buffer, size_t length ) { std::streamoff start = fs_.tellp(); fs_.write( buffer, length ); return static_cast< size_t >( fs_.tellp() - start ); } /** * @see File::ReadLine() */ std::string ReadLine() { std::string buffer; std::getline( fs_, buffer ); return buffer; } /** * @see File::Peek() */ int Peek() { return fs_.peek(); } /** * @see File::IsOpen() */ bool IsOpen() { return fs_.is_open(); } /** * @see File::EOF() */ bool IsEOF() { return fs_.eof(); } /** * @see File::Size() */ unsigned int Size() { return size_; } }; FilesystemPc::FilesystemPc() { } boost::shared_ptr<File> FilesystemPc::Open( const std::string &path, bool write ) { return boost::static_pointer_cast<File>( boost::make_shared<FilePc>( path, write ) ); }
true
3b2cde4e56b7af64c32dd6ce7159f6b1d4979ce4
C++
vineetsinghrana/gfg_dsa_selfplaced
/Searching/problems/__sqrtOfNo.cpp
UTF-8
1,497
3.546875
4
[]
no_license
// { Driver Code Starts //Initial Template for C #include<stdio.h> // } Driver Code Ends //User function Template for C long long int floorSqrt(long long int x) { // Your code goes here // Base cases if (x == 0 || x == 1) return x; // Do Binary Search for floor(sqrt(x)) int start = 1, end = x, ans; while (start <= end) { int mid = (start + end) / 2; // If x is a perfect square if (mid * mid == x) return mid; // Since we need floor, we update answer when // mid*mid is smaller than x, and move closer to // sqrt(x) /* if(mid*mid<=x) { start = mid+1; ans = mid; } Here basically if we multiply mid with itself so there will be integer overflow which will throw tle for larger input so to overcome this situation we can use long or we can just divide the number by mid which is same as checking mid*mid < x */ if (mid <= x / mid) { start = mid + 1; ans = mid; } else // If mid*mid is greater than x end = mid - 1; } return ans; } // { Driver Code Starts. int main() { int t; scanf("%d", &t); while(t--) { long long n; scanf("%ld", &n); printf("%ld\n", floorSqrt(n)); } return 0; } // } Driver Code Ends
true
68bc954eb1a2a276fc9071924360782b45945fc4
C++
Mo-Dabao/mooc_cpp_bupt
/unit02/oj1/main.cpp
UTF-8
143
2.609375
3
[]
no_license
#include <iostream> #include <string> int main() { int n; std::cin >> n; for (int x = 1; x <= n; x++) { std::cout << x; } return 0; }
true
d08647459a054c485fe12827ec0265913a9e3cfd
C++
SPReddy224/C-Advance
/submission-c++-arif/20th.cpp
UTF-8
408
3.125
3
[]
no_license
#include<stdio.h> /*#include<iostream> using namespace std; int main() { int a, b, c; cout << "enter the value of a" << endl; cin >> a; cout << "enter the value of b" << endl; cin >> b; cout << "enter the value of c" << endl; cin >> c; if (a < b) { cout << " the value of A is less than B " << endl; } else if (c < b) { cout << " HELLO WORLD" << endl; } system("pause"); return 0; }*/
true
172d54717b14d1c2b646fe253a4a936dd63a3662
C++
BagasMuharom/FantasyWorld
/Util/Util.cpp
UTF-8
20,338
3.375
3
[]
no_license
#include "Util.h" #include "GL/glut.h" #include <math.h> #include <vector> #include <iostream> #include <array> using namespace std; Vector3::Vector3(){} Vector3::Vector3(float x, float y, float z) { this->x = x; this->y = y; this->z = z; } float Vertex::globalScaleX = -1; float Vertex::globalScaleY = -1; float Vertex::globalScaleZ = -1; bool Vertex::useGlobalTranslate = false; float Vertex::globalTranslateX = 0; float Vertex::globalTranslateY = 0; float Vertex::globalTranslateZ = 0; vector<array<float, 3>> Vertex::stackScale(1, {1, 1, 1}); vector<array<float, 3>> Vertex::stackTranslate(1, {0, 0, 0}); Vertex::Vertex() {} Vertex::Vertex(float x, float y, float z) : Vector3(x, y, z){ this->realX = x; this->realY = y; this->realZ = z; } Vertex::Vertex(Vector3 &vector) { this->x = vector.x; this->y = vector.y; this->z = vector.z; } Vertex* Vertex::translate(float x, float y, float z) { this->x += x; this->y += y; this->z += z; return this; } Vertex* Vertex::scale(float scaleX, float scaleY, float scaleZ) { this->x *= scaleX; this->y *= scaleY; this->z *= scaleZ; } Vertex* Vertex::rotate(float degree, bool x, bool y, bool z, float a, float b, float c) { if(x) this->rotateX(degree, a, b, c); if(y) this->rotateY(degree, a, b, c); if(z) this->rotateZ(degree, a, b, c); return this; } void Vertex::rotateX(float degree, float a, float b, float c) { float tempX = 0, tempY = 0, tempZ = 0; tempX = this->x + a; tempY = this->y * cos(toRad(degree)) + (-1 * this->z * sin(toRad(degree))) + b; tempZ = this->y * sin(toRad(degree)) + this->z * cos(toRad(degree)) + c; this->x = tempX; this->y = tempY; this->z = tempZ; } void Vertex::rotateY(float degree, float a, float b, float c) { float tempX = 0, tempY = 0, tempZ = 0; tempX = this->x * cos(toRad(degree)) + this->z * sin(toRad(degree)) + a; tempY = this->y + b; tempZ = this->x * -1 * sin(toRad(degree)) + this->z * cos(toRad(degree)) + c; this->x = tempX; this->y = tempY; this->z = tempZ; } void Vertex::rotateZ(float degree, float a, float b, float c) { float tempX = 0, tempY = 0, tempZ = 0; tempX = this->x * cos(toRad(degree)) + (-1 * this->y * sin(toRad(degree))) + a; tempY = this->x * sin(toRad(degree)) + this->y * cos(toRad(degree)) + b; tempZ = this->z + c; this->x = tempX; this->y = tempY; this->z = tempZ; } Vertex* Vertex::reset() { this->x = this->realX; this->y = this->realY; this->z = this->realZ; return this; } Vertex* Vertex::flip(bool horizontal, bool vertical) { if(horizontal) this->x = - this->x; if(vertical) this->y = - this->y; return this; } Vertex* Vertex::flip(bool xy, bool xz, bool yz) { if(xy) { this->z = -this->z; } if(xz) { this->y = -this->y; } if(yz) { this->x = -this->x; } return this; } void Vertex::pushGlobalScale(float x, float y, float z) { Vertex::stackScale.push_back({x, y, z}); } void Vertex::popGlobalScale() { Vertex::stackScale.pop_back(); } void Vertex::pushGlobalTranslate(float x, float y, float z) { Vertex::stackTranslate.push_back({x, y, z}); } void Vertex::popGlobalTranslate() { Vertex::stackTranslate.pop_back(); } Vertex* Vertex::clone() { return new Vertex(this->x, this->y, this->z); } void Vertex::drawNormalVertex() { glNormal3f(this->x, this->y, this->z); glVertex3f(this->x, this->y, this->z); } void Vertex::drawVertex() { if(Vertex::stackScale.size() > 0) { for(auto &vertex : Vertex::stackScale) { this->scale(vertex[0], vertex[1], vertex[2]); } } if(Vertex::stackTranslate.size() > 0) { for(auto &vertex : Vertex::stackTranslate) { this->translate(vertex[0], vertex[1], vertex[2]); } } glVertex3f(this->x, this->y, this->z); } Vertex::~Vertex() { // cout << "Vertex deleted" << endl; } /** * Face Class */ Face::Face() { } Face::Face(std::vector<Vertex> vertices) { for(int i = 0; i < vertices.size(); i++) this->vertices.push_back(vertices[i]); } Face* Face::addVertex(Vertex vertex) { this->vertices.push_back(vertex); return this; } Face* Face::addVertex(float x, float y, float z) { this->addVertex(Vertex(x, y, z)); return this; } Face* Face::addVertex(Vertex* vertex) { this->addVertex( vertex->x, vertex->y, vertex->z ); delete vertex; return this; } Face* Face::addVertex(float *vertex) { this->addVertex(Vertex(*vertex, *(vertex + 1), *(vertex + 2))); return this; } Face* Face::flip(bool horizontal, bool vertical) { for(int i = 0; i < this->vertices.size(); i++) this->vertices[i].flip(horizontal, vertical); return this; } Face* Face::flip(bool xy, bool xz, bool yz) { for(int i = 0; i < this->vertices.size(); i++) this->vertices[i].flip(xy, xz, yz); return this; } Face* Face::translate(float x, float y, float z) { for(int i = 0; i < this->vertices.size(); i++) this->vertices[i].translate(x, y, z); return this; } Face* Face::setColor(Color* color) { this->color = color; return this; } Color* Face::getColor() { return this->color; } const void Face::drawFace() { if(this->color != nullptr) this->color->set(); glBegin(GL_POLYGON); for(int i = 0; i < this->vertices.size(); i++) this->vertices[i].drawVertex(); glEnd(); } const void Face::drawNormal() { if(this->color != nullptr) this->color->set(false); glBegin(GL_POLYGON); if(this->vertices.size() >= 3) { float a[] = {this->vertices[0].x, this->vertices[0].y, this->vertices[0].z}; float b[] = {this->vertices[1].x, this->vertices[1].y, this->vertices[1].z}; float c[] = {this->vertices[2].x, this->vertices[2].y, this->vertices[2].z}; float* calc = calculate_normal(a, b, c); glNormal3fv(calc); delete calc; } for(int i = 0; i < this->vertices.size(); i++) { this->vertices[i].drawVertex(); } glEnd(); } Face* Face::clone() { Face* temp = new Face(); for(int i = 0; i < this->vertices.size(); i++) temp->addVertex(Vertex(this->vertices[i].x, this->vertices[i].y, this->vertices[i].z)); if(this->color != nullptr) temp->setColor(this->color); return temp; } Face* Face::reset() { for(int i = 1; i <= this->vertices.size(); i++) this->vertices[i].reset(); return this; } Face* Face::rotate(float degree, bool x, bool y, bool z) { for(int i = 0; i < this->vertices.size(); i++) this->vertices[i].rotate(degree, x, y, z); return this; } Face* Face::scale(float scaleX, float scaleY, float scaleZ) { for(int i = 0; i < this->vertices.size(); i++) this->vertices[i].scale(scaleX, scaleY, scaleZ); return this; } std::vector<Vertex> Face::getVertices() { return this->vertices; } Face::~Face() { if(this->color != nullptr) delete this->color; this->vertices.clear(); // cout << "Face deleted" << endl; } Objek::Objek() { } Objek* Objek::addFace(Face* face) { this->faces.push_back(face); return this; } Objek* Objek::deleteFace(int index) { Face* face = this->faces[index]; this->faces.erase(this->faces.begin() + index); delete face; } Objek* Objek::combine(Objek* objek, bool autoDelete) { vector<Face*> daftarFaces = objek->getFaces(); for(int i = 0; i < daftarFaces.size(); i++) { this->addFace(daftarFaces[i]->clone()); } if(autoDelete) delete objek; return this; } void Objek::draw(bool autoDelete) { for(int i = 0; i < this->faces.size(); i++) this->faces[i]->drawNormal(); if(autoDelete) delete this; } Objek* Objek::translate(float x, float y, float z) { for(int i = 0; i < this->faces.size(); i++) this->faces[i]->translate(x, y, z); return this; } Objek* Objek::clone() { Objek* objek = new Objek(); for(int i = 0; i < this->faces.size(); i++) objek->addFace(this->faces[i]->clone()); return objek; } Objek* Objek::flip(bool horizontal, bool vertical) { for(unsigned int i = 0; i < this->faces.size(); i++) this->faces[i]->flip(horizontal, vertical); return this; } Objek* Objek::flip(bool xy, bool xz, bool yz) { for(int i = 0; i < this->faces.size(); i++) this->faces[i]->flip(xy, xz, yz); return this; } Objek* Objek::rotate(float degree, bool x, bool y, bool z) { for(unsigned int i = 0; i < this->faces.size(); i++) this->faces[i]->rotate(degree, x, y, z); return this; } Objek* Objek::scale(float scaleX, float scaleY, float scaleZ) { for(unsigned int i = 0; i < this->faces.size(); i++) this->faces[i]->scale(scaleX, scaleY, scaleZ); return this; } Objek* Objek::setColor(Color* color) { this->faces[0]->setColor(color); return this; } Objek* Objek::reset() { for(unsigned int i = 0; i < this->faces.size(); i++) this->faces[i]->reset(); return this; } vector<Face*> Objek::getFaces() { return this->faces; } void Objek::printFacesMemory() { for(int i = 0; i < this->faces.size(); i++) cout << "Face " << i << " : " << this->faces[i] << endl; } Objek::~Objek() { for(int i = this->faces.size() - 1; i >= 0; i--) { Face* temp = this->faces[i]; this->faces.pop_back(); delete temp; } } ///////////////////// // GrupObjek ///////////////////// GrupObjek::GrupObjek() {} GrupObjek* GrupObjek::addObjek(Objek* objek) { this->daftarObjek.push_back(objek); } GrupObjek* GrupObjek::translate(float x, float y, float z) { for(unsigned int i = 0; i < this->daftarObjek.size(); i++) this->daftarObjek[i]->translate(x, y, z); return this; } GrupObjek* GrupObjek::flip(bool horizontal, bool vertical) { for(unsigned int i = 0; i < this->daftarObjek.size(); i++) this->daftarObjek[i]->flip(horizontal, vertical); return this; } GrupObjek* GrupObjek::flip(bool xy, bool xz, bool yz) { for(int i = 0; i < this->daftarObjek.size(); i++) this->daftarObjek[i]->flip(xy, xz, yz); return this; } GrupObjek* GrupObjek::rotate(float degree, bool x, bool y, bool z) { for(unsigned int i = 0; i < this->daftarObjek.size(); i++) this->daftarObjek[i]->rotate(degree, x, y, z); return this; } GrupObjek* GrupObjek::scale(float scaleX, float scaleY, float scaleZ) { for(unsigned int i = 0; i < this->daftarObjek.size(); i++) this->daftarObjek[i]->scale(scaleX, scaleY, scaleZ); return this; } GrupObjek* GrupObjek::clone() { GrupObjek* cloning = new GrupObjek(); for(unsigned int i = 0; i < this->daftarObjek.size(); i++) cloning->addObjek(this->daftarObjek[i]->clone()); return cloning; } GrupObjek* GrupObjek::reset() { for(unsigned int i = 0; i < this->daftarObjek.size(); i++) this->daftarObjek[i]->reset(); return this; } GrupObjek* GrupObjek::addGrupObjek(GrupObjek* grupObjek) { vector<Objek*> daftarObjek = grupObjek->getObjek(); for(unsigned int i = 0; i < daftarObjek.size(); i++) this->addObjek(daftarObjek[i]->clone()); return this; } vector<Objek*> GrupObjek::getObjek() { return this->daftarObjek; } void GrupObjek::draw(bool autoDelete) { for(unsigned int i = 0; i < this->daftarObjek.size(); i++) this->daftarObjek[i]->draw(false); if(autoDelete) delete this; } GrupObjek::~GrupObjek() { for(int i = this->daftarObjek.size() - 1; i >= 0; i--) { Objek* objek = this->daftarObjek[i]; // cout << "Alamat faces : " << endl; // for(int j = 0; j < this->daftarObjek[i]->getFaces().size(); j ++) { // cout << this->daftarObjek[i]->getFaces()[j] << endl; // } // cout << " end Alamat faces" << endl; this->daftarObjek.pop_back(); // cout << objek << endl; delete objek; } } //////////// // Function //////////// Face* persegi(float sisi) { float vertices[][3] = { {0, 0, 0}, {0, 0, sisi}, {sisi, 0, sisi}, {sisi, 0, 0} }; Face* persegi = new Face(); for(auto &vertex : vertices) { persegi->addVertex(vertex); } return persegi; } Objek* kubus(float sisi, bool atas, bool bawah, bool depan, bool belakang, bool kanan, bool kiri) { return balok(sisi, sisi, sisi, atas, bawah, depan, belakang, kanan, kiri); } Objek* balok(float panjang, float lebar, float tinggi, bool atas, bool bawah, bool depan, bool belakang, bool kanan, bool kiri) { float vertices[][3] = { // 0 {0, 0, 0}, // 1 {panjang, 0, 0}, // 2 {panjang, 0, lebar}, // 3 {0, 0, lebar}, // 4 {0, tinggi, 0}, // 5 {panjang, tinggi, 0}, // 6 {panjang, tinggi, lebar}, // 7 {0, tinggi, lebar} }; vector<array<int, 4>> indexVertices; if(atas) indexVertices.push_back({4, 5, 6, 7}); if(bawah) indexVertices.push_back({0, 1, 2, 3}); if(kanan) indexVertices.push_back({5, 1, 2, 6}); if(kiri) indexVertices.push_back({0, 4, 7, 3}); if(depan) indexVertices.push_back({0, 4, 5, 1}); if(belakang) indexVertices.push_back({3, 2, 6, 7}); Objek* objek = new Objek(); for(auto &a : indexVertices) { Face* face = new Face(); for(auto &b : a) { face->addVertex(vertices[b]); } objek->addFace(face); } return objek; } Objek* trapesiumSiku(float panjangBawah, float lebarBawah, float panjangAtas, float lebarAtas, float tinggi, bool atas, bool bawah, bool depan, bool belakang, bool kanan, bool kiri) { float selisihPanjang = 0; float selisihLebar = 0; float vertices[][3] = { // 0 {0, 0, 0}, // 1 {panjangBawah, 0, 0}, // 2 {panjangBawah, 0, lebarBawah}, // 3 {0, 0, lebarBawah}, // 4 {selisihPanjang, tinggi, selisihLebar}, // 5 {panjangAtas + selisihPanjang, tinggi, selisihLebar}, // 6 {panjangAtas + selisihPanjang, tinggi, lebarAtas + selisihLebar}, // 7 {selisihPanjang, tinggi, lebarAtas + selisihLebar}, }; vector<array<int, 4>> indexVertices; if(atas) indexVertices.push_back({4, 5, 6, 7}); if(bawah) indexVertices.push_back({0, 1, 2, 3}); if(kanan) indexVertices.push_back({6, 2, 1, 5}); if(kiri) indexVertices.push_back({0, 4, 7, 3}); if(depan) indexVertices.push_back({0, 1, 5, 4}); if(belakang) indexVertices.push_back({7, 6, 2, 3}); Objek* objek = new Objek(); for(auto &a : indexVertices) { Face* face = new Face(); for(auto &b : a) { face->addVertex(vertices[b]); } objek->addFace(face); } return objek; } Objek* trapesiumSamaSisi(float panjangBawah, float lebarBawah, float panjangAtas, float lebarAtas, float tinggi, bool atas, bool bawah, bool depan, bool belakang, bool kanan, bool kiri) { float selisihPanjang = (panjangBawah - panjangAtas) / 2; float selisihLebar = (lebarBawah - lebarAtas) / 2; float vertices[][3] = { // 0 {0, 0, 0}, // 1 {panjangBawah, 0, 0}, // 2 {panjangBawah, 0, lebarBawah}, // 3 {0, 0, lebarBawah}, // 4 {selisihPanjang, tinggi, selisihLebar}, // 5 {panjangAtas + selisihPanjang, tinggi, selisihLebar}, // 6 {panjangAtas + selisihPanjang, tinggi, lebarAtas + selisihLebar}, // 7 {selisihPanjang, tinggi, lebarAtas + selisihLebar}, }; vector<array<int, 4>> indexVertices; if(atas) indexVertices.push_back({4, 5, 6, 7}); if(bawah) indexVertices.push_back({0, 1, 2, 3}); if(kanan) indexVertices.push_back({6, 2, 1, 5}); if(kiri) indexVertices.push_back({0, 4, 7, 3}); if(depan) indexVertices.push_back({0, 1, 5, 4}); if(belakang) indexVertices.push_back({7, 6, 2, 3}); Objek* objek = new Objek(); for(auto &a : indexVertices) { Face* face = new Face(); for(auto &b : a) { face->addVertex(vertices[b]); } objek->addFace(face); } return objek; } Objek* tabung(float radiusBawah, float radiusAtas, float tinggi, int slices, bool atas, bool bawah) { Objek* objek = new Objek(); Face* faceBawah = new Face(); Face* faceAtas = new Face(); // tidak perlu inisialisasi vertex dan indexnya for(float sudut = 0; sudut <= 360; sudut += (360 / slices)) { Face* face = new Face(); Vertex* awalBawah = Vertex(radiusBawah, 0, 0).rotate(sudut, 0, 1, 0); faceBawah->addVertex(awalBawah); face->addVertex(awalBawah); face->addVertex(Vertex(radiusBawah, 0, 0).rotate(sudut + (360 / slices), 0, 1, 0)); face->addVertex(Vertex(radiusAtas, tinggi, 0).rotate(sudut + (360 / slices), 0, 1, 0)); Vertex* awalAtas = Vertex(radiusAtas, tinggi, 0).rotate(sudut, 0, 1, 0); face->addVertex(awalAtas); faceAtas->addVertex(awalAtas); objek->addFace(face); } if(bawah) objek->addFace(faceBawah); else delete faceBawah; if(atas) objek->addFace(faceAtas); else delete faceAtas; return objek; } Objek* from2Dto3D(Face* face, float scale) { float xScale = 0; float yScale = 0; float zScale = 0; vector<Vertex> vertices = face->getVertices(); for(int i = 0; i < vertices.size(); i++) { xScale += vertices[i].x; yScale += vertices[i].y; zScale += vertices[i].z; } xScale = vertices[0].x == (xScale / vertices.size()) ? 1 : -1; yScale = vertices[0].y == (yScale / vertices.size()) ? 1 : -1; zScale = vertices[0].z == (zScale / vertices.size()) ? 1 : -1; if(xScale == -1 && yScale == -1 && zScale == -1) return (new Objek())->addFace(face); Objek* objek = new Objek(); Face* scaled = new Face(); for(int i = 0; i < vertices.size(); i++) { Face* face = new Face(); face->addVertex(vertices[i]); int indexFinish = (i == vertices.size() - 1) ? 0 : i + 1; face->addVertex(vertices[indexFinish]); Vertex* scaledVertex = new Vertex(); Vertex* scaledVertexFinish = new Vertex(); if(xScale == 1) { scaledVertex = vertices[i].clone()->translate(-scale, 0, 0); scaledVertexFinish = vertices[indexFinish].clone()->translate(-scale, 0, 0); } else if(yScale == 1) { scaledVertex = vertices[i].clone()->translate(0, -scale, 0); scaledVertexFinish = vertices[indexFinish].clone()->translate(0, -scale, 0); } else { scaledVertex = vertices[i].clone()->translate(0, 0, -scale); scaledVertexFinish = vertices[indexFinish].clone()->translate(0, 0, -scale); } face->addVertex(scaledVertexFinish); face->addVertex(scaledVertex); scaled->addVertex(scaledVertexFinish); scaled->addVertex(scaledVertex); objek->addFace(face); } objek->addFace(face); objek->addFace(scaled); return objek; } float toRad(float degree) { return degree * M_PI / 180; } void normalize(float *v) { float length = sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]); for (int i = 0; i < 3; i++) { v[i] = v[i] / length; } } float *cross_product(float *a, float *b) { float* result = new float[3]; result[0] = a[1] * b[2] - a[2] * b[1]; result[1] = -(a[0] * b[2] - a[2] * b[0]); result[2] = a[0] * b[1] - a[1] * b[0]; normalize(result); return result; } float *calculate_normal(float *a, float *b, float *c) { float x[] = {b[0] - a[0], b[1] - a[1], b[2] - a[2]}; float y[] = {c[0] - a[0], c[1] - a[1], c[2] - a[2]}; float *result = cross_product(x, y); return result; }
true
bc31da4567ea5d0c305d37035ee8a5a296dd72b4
C++
nongeneric/tinytasks
/tests.cpp
UTF-8
4,285
2.9375
3
[]
no_license
#include <catch2/catch.hpp> #include "task/Task.h" #include "task/Scheduler.h" #include <numeric> #include <random> using namespace task; TEST_CASE("simple_tasks") { Scheduler::init(); auto addInts = [](int a, int b) { return a + b; }; auto getInt = []{ return 10; }; auto getIntTask1 = make_task(getInt); auto getIntTask2 = make_task(getInt); auto addIntsTask = make_task(addInts, getIntTask1, getIntTask2); auto res = addIntsTask->result(); REQUIRE( res == 20 ); Scheduler::shutdown(); } TEST_CASE("combine_type_erased_tasks") { Scheduler::init(); auto addInts = [](int a, int b) { return a + b; }; auto getInt = []{ return 10; }; SPTask<int> getIntTask1 = make_task(getInt); SPTask<int> getIntTask2 = make_task(getInt); auto addIntsTask = make_task(addInts, getIntTask1, getIntTask2); auto res = addIntsTask->result(); REQUIRE( res == 20 ); Scheduler::shutdown(); } TEST_CASE("when_all_vector") { Scheduler::init(); std::vector<SPTask<int>> tasks; for (int i = 0; i < 5; ++i) { tasks.push_back(make_task([=] { return i * i; })); } auto root = make_task([=](auto vec) { return std::accumulate(begin(vec), end(vec), 0); }, when_all(tasks)); REQUIRE(root->result() == 1 + 2 * 2 + 3 * 3 + 4 * 4); Scheduler::shutdown(); } TEST_CASE("dynamic_task_creation") { Scheduler::init(); auto getIntTask1 = make_task([]{return 0;}); auto getIntTask2 = make_task([]{return 5;}); auto task = make_task([](int x, int y) { std::vector<SPTask<int>> tasks; for (int i = x; i < y; ++i) { tasks.push_back(make_task([=]{ return i * 2; })); } return when_all(tasks); }, getIntTask1, getIntTask2); auto sumTask = make_task([](auto vec) { return std::accumulate(begin(vec), end(vec), 0); }, task); REQUIRE(sumTask->result() == 2 + 2 * 2 + 3 * 2 + 4 * 2); Scheduler::shutdown(); } template <class Iter> Iter qsPartition(Iter begin, Iter end) { auto i = begin, p = end - 1; for (auto j = begin; j < p; ++j) { if (*j <= *p) { std::iter_swap(i, j); ++i; } } std::iter_swap(p, i); return i; } template <class Iter> void quickSortSeq(Iter begin, Iter end) { if (begin >= end) return; auto p = qsPartition(begin, end); quickSortSeq(begin, p), quickSortSeq(p + 1, end); } template <class Iter> SPTask<int> quickSort(Iter begin, Iter end) { if (begin >= end) return make_task([] { return 0; }); if (std::distance(begin, end) < 1000) { quickSortSeq(begin, end); return make_task([] { return 0; }); } auto partition = make_task([=] { return qsPartition(begin, end); }); auto recurse = make_task([=] (auto p) { return when_all(std::vector{ quickSort(begin, p), quickSort(p + 1, end)}); }, partition); return make_task([] (auto) { return 0; }, recurse); } TEST_CASE("quick_sort") { Scheduler::init(); std::default_random_engine g; std::uniform_int_distribution<int> d(0, 10000); std::vector<int> vec; for (int i = 0; i < 10000; ++i) { vec.push_back(d(g)); } quickSort(begin(vec), end(vec))->result(); REQUIRE(std::is_sorted(begin(vec), end(vec))); Scheduler::shutdown(); } TEST_CASE("continuation_transfer") { Scheduler::init(); auto sleep = [] { std::this_thread::sleep_for(std::chrono::milliseconds(400)); }; auto t1 = make_task([&] { sleep(); int a = 10; return make_task([&, a] { sleep(); int b = a + 10; return make_task([&, b] { return b + 10; }); }); }); auto t2 = make_task([&] { sleep(); int a = 1; return make_task([&, a] { sleep(); int b = a + 1; return make_task([&, b] { return b + 1; }); }); }); auto t3 = make_task([] (auto vec) { return vec[0] + vec[1]; }, when_all(std::vector{t1, t2})); REQUIRE(t3->result() == 33); Scheduler::shutdown(); }
true
05ea4655cd380a960289620b4d7c6fa55d73ea72
C++
y42sora/soraSRM
/00001-00500/SRM494/Div2/PaintingTest.cpp
UTF-8
3,036
3.234375
3
[]
no_license
#include "Painting.h" #include <iostream> #include <vector> using std::cerr; using std::cout; using std::endl; using std::vector; class PaintingTest { static void assertEquals(int testCase, const int& expected, const int& actual) { if (expected == actual) { cout << "Test case " << testCase << " PASSED!" << endl; } else { cout << "Test case " << testCase << " FAILED! Expected: <" << expected << "> but was: <" << actual << '>' << endl; } } Painting solution; void testCase0() { string picture_[] = {"BBBB", "BBBB", "BBBB", "BBBB"}; vector<string> picture(picture_, picture_ + (sizeof(picture_) / sizeof(picture_[0]))); int expected_ = 4; assertEquals(0, expected_, solution.largestBrush(picture)); } void testCase1() { string picture_[] = {"BBBB", "BWWB", "BWWB", "BBBB"}; vector<string> picture(picture_, picture_ + (sizeof(picture_) / sizeof(picture_[0]))); int expected_ = 1; assertEquals(1, expected_, solution.largestBrush(picture)); } void testCase2() { string picture_[] = {"WBBBBB", "BBBBBB", "BBBBBB", "BBBBBB"}; vector<string> picture(picture_, picture_ + (sizeof(picture_) / sizeof(picture_[0]))); int expected_ = 3; assertEquals(2, expected_, solution.largestBrush(picture)); } void testCase3() { string picture_[] = {"BBBB", "BBBB", "WBBB", "BBBB", "BBBB", "BBBB"}; vector<string> picture(picture_, picture_ + (sizeof(picture_) / sizeof(picture_[0]))); int expected_ = 2; assertEquals(3, expected_, solution.largestBrush(picture)); } void testCase4() { string picture_[] = {"WBBBBBWWWWWWWWW", "WBBBBBBWWWWWWWW", "WBBBBBBBBBBBWWW", "WBBBBBBBBBBBWWW", "BBBBBBBBBBBBBBB", "BBBBBBBBBBBBBBB", "BBBBBBBBBBBBBBB", "BBBBBBBBWWBBBBB", "BBBBBBBBWBBBBBB", "WBBBBBBBWBBBBBW", "BBBBBBBWWBBBBBW", "BBBBBBBWWBBBBBW", "BBBBBBWWWBBBBBW", "BBBBBWWWWWWWWWW", "BBBBBWWWWWWWWWW"}; vector<string> picture(picture_, picture_ + (sizeof(picture_) / sizeof(picture_[0]))); int expected_ = 5; assertEquals(4, expected_, solution.largestBrush(picture)); } void testCase5() { string picture_[] = {"BBWBBBBBBBBBBBBBBBBBBBBBBBBBBBBBWBBBBB", "BBBBBBBBBBBBWWBBBWBBBBBBBBBWBBBBBBWBBB"}; vector<string> picture(picture_, picture_ + (sizeof(picture_) / sizeof(picture_[0]))); int expected_ = 1; assertEquals(5, expected_, solution.largestBrush(picture)); } public: void runTest(int testCase) { switch (testCase) { case (0): testCase0(); break; case (1): testCase1(); break; case (2): testCase2(); break; case (3): testCase3(); break; case (4): testCase4(); break; case (5): testCase5(); break; default: cerr << "No such test case: " << testCase << endl; break; } } }; int main() { for (int i = 0; i < 6; i++) { PaintingTest test; test.runTest(i); } }
true
296198d6cb7b0794e43bc3fc47923cfc06567793
C++
erdincay/MyRobot
/Manager.cc
UTF-8
1,888
2.953125
3
[]
no_license
#include "Manager.h" const int defaultListenPort = 9002; const int defautBroadCastPort = 9000; using namespace std; Manager::Manager(boost::asio::io_service & io_service) :CommPoint(io_service, defaultListenPort), curPt_(boost::posix_time::microsec_clock::local_time()) { } Manager::~Manager() { } int Manager::AddWayPoint(double x, double y) { return AddWayPoint(Coordinate(x,y)); } int Manager::AddWayPoint(Coordinate waypoint) { string newCmd = ""; if (waypoints_.empty()) { newCmd = lineMsg; } else { if(waypoints_.back().formationType_.compare(lineMsg) == 0) { newCmd = diamondMsg; } else { newCmd = lineMsg; } } stSection newWaypoint(newCmd, waypoint); waypoints_.push(newWaypoint); } void Manager::SendCmd() { ostringstream msg; if (waypoints_.empty()) { msg << stopMsg; } else { curSec_ = waypoints_.front(); waypoints_.pop(); msg <<curSec_.formationType_<<" "<< curSec_.waypoint_.getX() <<" "<< curSec_.waypoint_.getY(); } TalkToAll(msg.str(), defautBroadCastPort); cout<<"Send Cmd : \""<<msg.str()<<"\""<<endl; RecordTime(); } void Manager::ParseRead(unsigned char * buf, size_t bytes_transferred) { if(bytes_transferred > 0) { string msg(buf, buf + bytes_transferred); //cout <<"Manager Receive msg: "<< msg << endl; if (msg.compare(finishMsg) == 0) { Report(); SendCmd(); } } } void Manager::RecordTime() { curPt_ = boost::posix_time::microsec_clock::local_time(); } void Manager::Report() { boost::posix_time::time_duration msdiff = boost::posix_time::microsec_clock::local_time() - curPt_; cout<<"Mission \""<<curSec_.formationType_<<" to ("<<curSec_.waypoint_.getX()<<", "<<curSec_.waypoint_.getY()<<")\"" <<" accomplished in "<<msdiff.total_milliseconds()<<" milliseconds"<<endl; } void Manager::Run() { cout << "Manager is running" << endl; ListenFromAll(); SendCmd(); }
true
e7e8067b78707220ef6d04c5a4063d7661e59ad8
C++
Derecho-Project/derecho
/src/core/notification.cpp
UTF-8
5,612
2.75
3
[ "BSD-3-Clause" ]
permissive
#include "derecho/core/notification.hpp" #include <cstring> #include <memory> namespace derecho { NotificationMessage::NotificationMessage( uint64_t type, uint8_t* const buffer, std::size_t size, bool owns_buffer) : message_type(type), size(size), body(buffer), owns_body(owns_buffer) { if(size > 0 && owns_buffer) { body = new uint8_t[size]; if(buffer != nullptr) { memcpy(body, buffer, size); } else { memset(body, 0, size); } } // In case of illegal argument combination: non-null buffer, size = 0, owns = false if(size == 0) { body = nullptr; } } NotificationMessage::NotificationMessage( uint64_t type, const uint8_t* const buffer, std::size_t size) : message_type(type), size(size), body(new uint8_t[size]), owns_body(true) { if(size > 0) { if(buffer != nullptr) { memcpy(body, buffer, size); } else { memset(body, 0, size); } } } NotificationMessage::NotificationMessage(uint64_t type, std::size_t size) : NotificationMessage(type, nullptr, size) {} NotificationMessage::NotificationMessage(const NotificationMessage& other) : message_type(other.message_type), size(other.size), body(new uint8_t[size]), owns_body(true) { if(size > 0) { if(other.body != nullptr) { memcpy(body, other.body, size); } else { memset(body, 0, size); } } } NotificationMessage::NotificationMessage(NotificationMessage&& other) : message_type(other.message_type), size(other.size), body(other.body), owns_body(other.owns_body) { //This ensures other won't delete the body buffer on destruction other.body = nullptr; other.size = 0; } NotificationMessage::~NotificationMessage() { if(body != nullptr && owns_body) { delete[] body; } } NotificationMessage& NotificationMessage::operator=(const NotificationMessage& other) { if(body != nullptr && owns_body) { delete[] body; } message_type = other.message_type; size = other.size; owns_body = true; if(size > 0) { body = new uint8_t[size]; memcpy(body, other.body, size); } else { body = nullptr; } return *this; } NotificationMessage& NotificationMessage::operator=(NotificationMessage&& other) { if(body != nullptr && owns_body) { delete[] body; } message_type = other.message_type; size = other.size; owns_body = other.owns_body; body = other.body; other.body = nullptr; other.size = 0; return *this; } std::size_t NotificationMessage::bytes_size() const { return sizeof(message_type) + sizeof(size) + size; } std::size_t NotificationMessage::to_bytes(uint8_t* buffer) const { std::size_t offset = 0; memcpy(buffer + offset, &message_type, sizeof(message_type)); offset += sizeof(message_type); memcpy(buffer + offset, &size, sizeof(size)); offset += sizeof(size); if(size > 0) { memcpy(buffer + offset, body, size); } return offset + size; } void NotificationMessage::post_object(const std::function<void(uint8_t const* const, std::size_t)>& post_func) const { post_func(reinterpret_cast<const uint8_t*>(&message_type), sizeof(message_type)); post_func(reinterpret_cast<const uint8_t*>(&size), sizeof(size)); post_func(body, size); } std::unique_ptr<NotificationMessage> NotificationMessage::from_bytes( mutils::DeserializationManager*, const uint8_t* const buffer) { std::size_t offset = 0; uint64_t message_type; memcpy(&message_type, buffer + offset, sizeof(message_type)); offset += sizeof(message_type); std::size_t size; memcpy(&size, buffer + offset, sizeof(size)); offset += sizeof(size); return std::make_unique<NotificationMessage>(message_type, buffer + offset, size); } mutils::context_ptr<NotificationMessage> NotificationMessage::from_bytes_noalloc( mutils::DeserializationManager*, const uint8_t* const buffer) { std::size_t offset = 0; uint64_t message_type; memcpy(&message_type, buffer + offset, sizeof(message_type)); offset += sizeof(message_type); std::size_t size; memcpy(&size, buffer + offset, sizeof(size)); offset += sizeof(size); //This is dangerous, because we store the const buffer pointer in the non-const body pointer, //but from_bytes_noalloc *should* only be used to make a read-only temporary return mutils::context_ptr<NotificationMessage>{ new NotificationMessage(message_type, const_cast<uint8_t*>(buffer + offset), size, false)}; } mutils::context_ptr<const NotificationMessage> NotificationMessage::from_bytes_noalloc_const( mutils::DeserializationManager*, const uint8_t* const buffer) { std::size_t offset = 0; uint64_t message_type; memcpy(&message_type, buffer + offset, sizeof(message_type)); offset += sizeof(message_type); std::size_t size; memcpy(&size, buffer + offset, sizeof(size)); offset += sizeof(size); //We shouldn't need const_cast to create a const NotificationMessage, but we do return mutils::context_ptr<const NotificationMessage>{ new NotificationMessage(message_type, const_cast<uint8_t*>(buffer + offset), size, false)}; } } // namespace derecho
true
acb18418e7c8c8eb9ee25550bffcb5f037a4f771
C++
piyushnbali/competitive-coding
/Siddhesh/Leetcode/LinkedListCycleII.cpp
UTF-8
1,051
3.140625
3
[]
no_license
// FLOYD'S ALGORITHM // LINK:: https://youtu.be/9YTjXqqJEFE /* APPROACH:: FIRST FIND OUT IF THERE IS A CYCLE ... REFER TO LINKED LIST CYCLE SOLUTION IF THERE IS A CYCLE :: MOVE FIRST PTR TO START AND KEEP SCND PTR WHERE IT IS NOW KEEP MOVING FORWARD EACH PTR... THE POINT WHERE THEY MEET WILL BE THE POINT WHERE THE CYCLE STARTS.. WHICH IS ASKED IN THE SOLUTION */ class Solution { public: ListNode *detectCycle(ListNode *head) { if(head==nullptr) return head; ListNode *f=head,*s=head; bool found=0,first=1; while(true){ if(s->next==nullptr || s->next->next==nullptr){ break; } if(s==f && !first){ found=1; break; } first=0; f=f->next; s=s->next->next; } if(found){ f=head; while(f!=s){ f=f->next; s=s->next; } return f; } return nullptr; } };
true
bf2ccc084d96aac99c876e4e47e2e9a626c54012
C++
SimonvBez/MRB_Due
/MRB_Due/servo-driver-pca9685.hpp
UTF-8
3,477
3.234375
3
[]
no_license
/// @file #ifndef SERVO_DRIVER_PCA9685_HPP #define SERVO_DRIVER_PCA9685_HPP #include "hwlib.hpp" /// \brief /// PCA9685 16 Channel Servo Driver /// \details /// This class implements an interface to a 16 Channel Servo Driver. /// The interface is I²C. /// The driver chip is PCA9685. /// /// The Vcc pin is used to power the chip, and has a voltage range of 2.3 V to 5.5V. /// The V+ pin is used to power the servos. If you are controlling a lot of servos, /// use an external power supply to prevent damage to the Arduino. /// /// The Vcc and V+ pin have a common GND. /// /// The OE (=Output Enable) pin is active LOW and should be connected to ground. /// If you set the OE pin to HIGH, all outputs will be programmed to the value defined /// in the OUTNE[1:0] in the MODE 2 register. (The default of OUTNE[1:0] will be to disable all outputs) class pca9685 { private: hwlib::i2c_bus & bus; uint_fast8_t address; // PCA9685 registers static constexpr const uint8_t MODE1 = 0x00; static constexpr const uint8_t MODE2 = 0x01; static constexpr const uint8_t SUB_ADR1 = 0x02; static constexpr const uint8_t SUB_ADR2 = 0x03; static constexpr const uint8_t SUB_ADR3 = 0x04; static constexpr const uint8_t ALL_CALL_ADR = 0x05; static constexpr const uint8_t LED0_ON_L = 0x06; static constexpr const uint8_t ALL_LED_ON_L = 0xFA; static constexpr const uint8_t PRESCALE = 0xFE; // PCA9685 software reset address static constexpr const uint8_t SW_RESET = 0x06; uint8_t read_reg(uint8_t reg_addr); void write_reg(uint8_t reg_addr, uint8_t data); public: /// \brief /// Create a servo driver /// \details /// This constructor creates a servo driver from the I²C bus and makes it ready for use. pca9685(hwlib::i2c_bus & bus, const uint_fast8_t address = 0x40 ): bus(bus), address(address) { reset(); // Resets the PCA9685 and makes it ready for use. setPWMfreq(62.5); // Sets the default PWM frequency to 62.5Hz. (This could be anywhere between 100 to 50Hz) } /// \brief /// Set the PWM frequency /// \details /// This function sets the PCA9685's PWM to the given frequency (in Hz). /// The PCA9685 outputs operated from 24Hz to 1526Hz. /// /// Because the frequency is stored in only one register byte (also known as the PRESCALE), /// the real frequency can be a few Hz of the one that is set. void setPWMfreq(float freq); /// \brief /// Set the PWM duty cycle /// \details /// This function sets a servo pin to a given duty cycle. /// 'servo_num' is the pin number you want to set (0 to 15). /// 'start_time' is the step when the output pin is set to HIGH (0 to 4096). /// 'stop_time' is the step when the outpit pin is set to LOW again (0 to 4096). /// /// Example: setPWM(3, 0, 2048) will give pin 3 a duty cycle of 50%. /// /// /// Remember the angle of a servo motor is controlled by the *time* a PWM pulse /// is HIGH, and not just the duty cycle percentage. void setPWM(const uint8_t servo_num, const uint16_t start_time, const uint16_t stop_time); /// \brief /// Resets the PCA9685 /// \details /// This function will reset the PCA9685. /// This means all registers will turn to their defaults. /// /// Default PWM frequency: ~200Hz /// Default duty cycle: 0% void reset(); /// \brief /// Resets all PCA9685's /// \details /// This function will reset all PCA9685's on the I²C bus /// and set their registers to their defaults. void reset_all_devices(); }; #endif
true
2d5c30250b946317f209fcd176e2ce1c289d09bd
C++
Niraka/ThirdYearProject
/Source/CollisionsSystem/Vector2D.cpp
UTF-8
6,185
3.875
4
[]
no_license
#include "Vector2D.h" /** Constructs a new Vector2D and sets both the X and Y components to a default of 0. */ Vector2D::Vector2D() { m_fX = 0; m_fY = 0; } /** Constructs a new Vector2D and sets both the X and Y components to the given value. @param fBoth The value. */ Vector2D::Vector2D(float fBoth) { m_fX = fBoth; m_fY = fBoth; } /** Constructs a new Vector2D and sets the X and Y components to their respective parameters. @param fX The X component value. @param fY The Y component value. */ Vector2D::Vector2D(float fX, float fY) { m_fX = fX; m_fY = fY; } /** Set the X component to the given value. @param fX The value. */ void Vector2D::setX(float fX) { m_fX = fX; } /** Set the Y component to the given value. @param fY The value. */ void Vector2D::setY(float fY) { m_fY = fY; } /** Sets the X and Y components to the given value. @param The value. */ void Vector2D::setBoth(float fBoth) { m_fX = fBoth; m_fY = fBoth; } /** Sets the X and Y components to their respective values. @param fX The X component. @param fY The Y component. */ void Vector2D::setBoth(float fX, float fY) { m_fX = fX; m_fY = fY; } /** Returns the X component. @return The X component. */ float Vector2D::x() { return m_fX; } /** Returns the Y component. @preturn The Y component. */ float Vector2D::y() { return m_fY; } /** Returns the magnitude of the vector. @return The magnitude of the vector. */ float Vector2D::magnitude() { return sqrt(magnitudeSquared()); } /** Returns the magnitude prior to square-rooting it. @return The magnitude prior to square-rooting it. */ float Vector2D::magnitudeSquared() { return (m_fX * m_fX) + (m_fY * m_fY); } /** Returns the dot product of the vector and the given vector. @param other The other vector. @return The dot product of the two vectors. */ float Vector2D::dotProduct(Vector2D& other) { return (m_fX * other.x()) + (m_fY * other.y()); } /** Normalises the vector. */ void Vector2D::normalise() { float mag = magnitude(); m_fX = m_fX / mag; m_fY = m_fY / mag; } /** Inverts the sign of both the X and Y components. */ void Vector2D::invert() { m_fX *= -1; m_fY *= -1; } /** Returns true if the X and Y components of the two vectors are equal. @param vOther The other vector. @return True if the X and Y components of the two vectors are equal. */ bool Vector2D::operator==(Vector2D& vOther) { if (m_fX == vOther.x() && m_fY == vOther.y()) { return true; } else { return false; } } /** Sets the X and Y components of this vector to be equal to the X and Y components of the given vector. @param vOther The other vector. */ void Vector2D::operator=(Vector2D& vOther) { m_fX = vOther.x(); m_fY = vOther.y(); } /** Returns a new Vector2D whose X and Y components are the sum of this vector and the given vectors X and Y components. @param vOther The other vector. @return A new vector. */ Vector2D Vector2D::operator+(Vector2D& vOther) { return Vector2D(m_fX + vOther.x(), m_fY + vOther.y()); } /** Adds the X and Y components of the other vector to this vector. @param vOther The other vector. */ void Vector2D::operator+=(Vector2D& vOther) { m_fX = m_fX + vOther.x(); m_fY = m_fY + vOther.y(); } /** Returns a new Vector2D whose X and Y components are equal to this vector minus theother vectors X and Y components. @param vOther The other vector. @return The new vector. */ Vector2D Vector2D::operator-(Vector2D& vOther) { return Vector2D(m_fX - vOther.x(), m_fY - vOther.y()); } /** Takes away the X and Y components of the other vector from this vector. @param vOther The other vector. */ void Vector2D::operator-=(Vector2D& vOther) { m_fX = m_fX - vOther.x(); m_fY = m_fY - vOther.y(); } /** Returns a new Vector2D that is the result of this vector multiplied by the given scalar value. @param fVal The scalar value. @result The new Vector2D. */ Vector2D Vector2D::operator*(float fVal) { return Vector2D(m_fX * fVal, m_fY * fVal); } /** Multiplies the X and Y components of this vector by the given scalar value. @param fVal The scalar value. */ void Vector2D::operator*=(float fVal) { m_fX = m_fX * fVal; m_fY = m_fY * fVal; } /** Returns a new Vector2D that is the result of this vector divided by the given scalar value. @param fVal The scalar value. @return The new Vector2D. */ Vector2D Vector2D::operator/(float fVal) { return Vector2D(m_fX / fVal, m_fY / fVal); } /** Divides the X and Y components of the vector by the given scalar value. @param fVal The scalar value. */ void Vector2D::operator/=(float fVal) { m_fX = m_fX / fVal; m_fY = m_fY / fVal; } /** Returns the cross product of the vector and the other given vector. @param vOther The other vector. @return The cross product of the two vectors. */ float Vector2D::crossProduct(Vector2D& vOther) { return (m_fX * vOther.y()) - (m_fY - vOther.x()); } /** Returns a new Vector2D that is the cross product of the given scalar and vector. @param fScalar The scalar. @param vVector The vector. @return A new Vector2D that is the cross product of the given scalar and vector. */ Vector2D Vector2D::crossProduct(float fScalar, Vector2D& vVector) { return Vector2D(fScalar * vVector.y(), -fScalar * vVector.x()); } /** Returns a new Vector2D that is the cross product of the given vector and scalar. @param vVector The vector. @param fScalar The scalar. @return A new Vector2D that is the cross product of the given vector and scalar. */ Vector2D Vector2D::crossProduct(Vector2D& vVector, float fScalar) { return Vector2D(-fScalar * vVector.y(), fScalar * vVector.x()); } /** Rotates the point formed by this vectors X and Y components around the given point by the given numver of degrees. @param fRotation The amount to rotate, in degrees. @param vPoint The point to rotate about. */ void Vector2D::rotateAboutPoint(float fRotation, Vector2D vPoint) { float fRadians = fRotation * (3.14159265 / 180); Vector2D tmpPos(m_fX, m_fY); tmpPos -= vPoint; float fX = tmpPos.x(); float fY = tmpPos.y(); tmpPos.setX((cos(fRadians) * fX) + (-sin(fRadians) * fY)); tmpPos.setY((sin(fRadians) * fX) + (cos(fRadians) * fY)); tmpPos += vPoint; m_fX = tmpPos.x(); m_fY = tmpPos.y(); }
true
64a766435c13598c5d7a9d05696883234671b3f1
C++
Niadus/cst211-data-structures
/DataStructures/array2d_p.hpp
UTF-8
881
2.671875
3
[]
no_license
#ifndef ARRAY2D_P_HPP #define ARRAY2D_P_HPP #include "adt_exception.hpp" #include "i_array2d.hpp" template<class T> class array2d_p : public i_array2d<T> { public: T select(int row, int column) const override; T& select(int row, int column) override; //row<T> operator[](int row) const override; //row<T> operator[](int row) override; operator bool() override; size_t get_rows() override; size_t get_columns() override; void set_rows(size_t rows) override; void set_columns(size_t columns) override; explicit array2d_p(const size_t rows, const size_t columns); ~array2d_p(); array2d_p(const array2d_p& copy); array2d_p(array2d_p<T>&& copy); array2d_p<T>& operator=(const array2d_p& rhs); array2d_p<T>& operator=(array2d_p<T>&& rhs); private: T** storage_ = nullptr; size_t rows_ = 0; size_t columns_ = 0; }; #endif
true
96457b6e77758abff84d1178b284eb159d1d80ff
C++
sirAdarsh/CP-files
/PRACTICE/489-C.cpp
UTF-8
1,294
2.765625
3
[]
no_license
/*----- || Hare Krishna || -----*/ /* "WHY DO WE FALL, BRUCE?" */ #include<bits/stdc++.h> #define ll long long #define endl '\n' #define elif else if #define PI 3.1415926535897932384 #define MOD 1000000007 using namespace std; string s; int t; int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); //freopen("input.txt","r",stdin); //freopen("output.txt","w",stdout); int m,s; cin >> m >> s; int secondry_digs = m-1; int minSum=1; int maxSum = 9*m; if(m==1 && s<9){ if(s<9){ cout << s << ' ' << s << endl; } else{ cout << -1 << ' ' << -1 << endl; } return 0; } if(s<minSum || s>maxSum){ cout << -1 << ' ' << -1 << endl; return 0; } // MINIMUM int maxSumSecondry = secondry_digs*9; int firstDig = max( 1, s-maxSumSecondry ); int rem = s-firstDig; vector<int> places(m); for(int i=m-1; i>0; i--){ places[i] = min( 9, max(0, rem) ) ; rem -= places[i]; } places[0] = firstDig; for(int i=0; i<m; i++){ cout << places[i]; } cout << ' '; // MAXIMUM firstDig = min(9, s); places[0] = firstDig; rem = s-firstDig; for(int i=1; i<m; i++){ places[i] = min( 9, max(0,rem) ); rem -= places[i]; } for(int i=0; i<m; i++){ cout << places[i]; } }
true
6a4f3a0b62ebd76f1378af5a684c584e62bed95c
C++
RodrigoNazar/SEP_2018-2
/Lab_7/AVR/USART_3/USART_3.ino
UTF-8
1,594
3.03125
3
[]
no_license
/*************************************************** * This is an example program to demonstrate the * successful implementation of the USART's * receive functions. * * Connect your developer board to a PC and configure * a terminal emulator with the appropriate baud rate * in order to see the test message below. * * Hint: You can not connect your terminal to this board * and avrdude at the same time. Disconnect your terminal * software when loading a new program into the flash! * * This code is in the public domain. * ****************************************************/ #include <avr/io.h> #include "USART_implement_me.h" int main(void) { // Initialize the serial communication interface struct USART_configuration config_9600_8N1 = {9600, 8, 0, 1}; Error_checking(USART_Init(config_9600_8N1)); node_t *head = linked_list_init(); while(1) { USART_Transmit_String("\r\n\r\n"); // Print a welcome message int a = 3; USART_Transmit_String("Welcome to the first test. Please send a single character from your terminal.\r\n"); USART_Transmit_char("%d"); // Show the received character char c = USART_Receive_char(); USART_Transmit_String("I received an "); USART_Transmit_char(c); USART_Transmit_String(".\r\n\r\n"); // Print a welcome message USART_Transmit_String("Welcome to the Second test. Please send a properly terminated string.\r\n\r\n"); USART_Receive_String(head); USART_Transmit_String("I received this line:"); // Show the received string print_list(head); USART_Transmit_String("\r\n\r\n"); } }
true
e63e0bef0f463e5c8aaa7c92ff118e906936b49c
C++
drheli/hal
/src/netlist/netlist_factory.cpp
UTF-8
3,037
2.5625
3
[ "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
#include "netlist/netlist_factory.h" #include "core/log.h" #include "core/program_arguments.h" #include "netlist/event_system/event_controls.h" #include "netlist/gate_library/gate_library_manager.h" #include "netlist/hdl_parser/hdl_parser_dispatcher.h" #include "netlist/netlist.h" #include "netlist/persistent/netlist_serializer.h" #include <fstream> #include <iostream> #include <unistd.h> namespace hal { namespace netlist_factory { std::shared_ptr<Netlist> create_netlist(const std::shared_ptr<GateLibrary>& gate_library) { if (gate_library == nullptr) { log_critical("netlist", "nullptr given as gate library."); return nullptr; } return std::make_shared<Netlist>(gate_library); } std::shared_ptr<Netlist> load_netlist(const std::filesystem::path& hdl_file, const std::string& language, const std::filesystem::path& gate_library_file) { if (access(hdl_file.c_str(), F_OK | R_OK) == -1) { log_critical("netlist", "cannot access file '{}'.", hdl_file.string()); return nullptr; } auto lib = gate_library_manager::load_file(gate_library_file); if (!lib) { log_critical("netlist", "cannot read netlist without gate library."); return nullptr; } std::shared_ptr<Netlist> nl = HDLParserDispatcher::parse(lib, language, hdl_file); return nl; } std::shared_ptr<Netlist> load_netlist(const std::filesystem::path& hal_file) { if (access(hal_file.c_str(), F_OK | R_OK) == -1) { log_critical("netlist", "cannot access file '{}'.", hal_file.string()); return nullptr; } std::shared_ptr<Netlist> nl = netlist_serializer::deserialize_from_file(hal_file); return nl; } std::shared_ptr<Netlist> load_netlist(const ProgramArguments& args) { if (!args.is_option_set("--input-file")) { log_critical("netlist", "no file to process specified."); return nullptr; } std::filesystem::path file_name = std::filesystem::path(args.get_parameter("--input-file")); if (access(file_name.c_str(), F_OK | R_OK) == -1) { log_critical("netlist", "cannot access file '{}'.", file_name.string()); return nullptr; } auto extension = file_name.extension(); std::shared_ptr<Netlist> nl = nullptr; if (extension == ".hal") { nl = netlist_serializer::deserialize_from_file(file_name); } else { nl = HDLParserDispatcher::parse(file_name, args); } return nl; } } // namespace netlist_factory } // namespace hal
true