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
3f85b889a9eecf609392d46a81104384fdec88e0
C++
tilak30/babbar-450
/Arrays/neg_pos_rearrange.cpp
UTF-8
509
3.296875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; void neg_pos_rearrange(vector<int> v, int n){ //two pointer approach int x=0,y=n-1; while(x<y){ if(v[x]<0){ x++; } if(v[y]<0){ swap(v[x],v[y]); x++; } y--; } //PRINT ARRAY for(auto x: v){ cout<<x<<" "; } } int main() { int n; cin>>n; vector<int> v(n); for(int i=0;i<n;i++) cin>>v[i]; neg_pos_rearrange(v,n); return 0; }
true
9e3d802dab0a81eb84c819bf0f4ee58270080769
C++
leejaeseung/Algorithm
/BOJ/C++/15686_치킨 배달.cpp
UHC
5,045
3.453125
3
[]
no_license
/* ũⰡ NN ð ִ. ô 11ũ ĭ ִ. ĭ ĭ, ġŲ, ϳ̴. ĭ (r, c) · Ÿ, r c Ǵ r° ĭ, ʿ c° ĭ ǹѴ. r c 1 Ѵ. ÿ ġŲ ſ Ѵ. , "ġŲ Ÿ" ַ Ѵ. ġŲ Ÿ ġŲ Ÿ̴. , ġŲ Ÿ , ġŲ Ÿ ִ. ġŲ Ÿ ġŲ Ÿ ̴. ĭ (r1, c1) (r2, c2) Ÿ |r1-r2| + |c1-c2| Ѵ. , Ʒ ø 캸. 0 2 0 1 0 1 0 1 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 1 2 0 ĭ, 1 , 2 ġŲ̴. (2, 1) ִ (1, 2) ִ ġŲ Ÿ |2-1| + |1-2| = 2, (5, 5) ִ ġŲ Ÿ |2-5| + |1-5| = 7̴. , (2, 1) ִ ġŲ Ÿ 2̴. (5, 4) ִ (1, 2) ִ ġŲ Ÿ |5-1| + |4-2| = 6, (5, 5) ִ ġŲ Ÿ |5-5| + |4-5| = 1̴. , (5, 4) ִ ġŲ Ÿ 1̴. ÿ ִ ġŲ ̴. 翡 Ű Ϻ ġŲ Ű Ѵ. ÿ ִ ġŲ ִ M ˾Ƴ. ÿ ִ ġŲ ߿ ִ M , ġŲ Ѿ Ѵ.  , ġŲ Ÿ ۰ ϴ α׷ ۼϽÿ. Է ù° ٿ N(2 N 50) M(1 M 13) ־. ° ٺ N ٿ ־. 0, 1, 2 ̷ ְ, 0 ĭ, 1 , 2 ġŲ ǹѴ. 2N ,  1 Ѵ. ġŲ M ũų , 13 ۰ų . ù° ٿ Ű ġŲ ִ M , ġŲ Ÿ ּڰ Ѵ. Ǯ: ġŲ Ÿ մϴ(ִ 13 * 100) ġŲ ִ m ϴµ, ִ ġŲ ߿ m ˴ϴ. ʾ ð ! */ #include<iostream> #include<algorithm> #include<math.h> #include<string> #include<vector> #include<stack> #include<queue> #include<map> using namespace std; #define FIO ios_base::sync_with_stdio(false); cin.tie(NULL) #define pii pair<int, int> #define pdd pair<double, double> #define pic pair<int, char> #define ll long long #define vi vector<int> #define vl vector<long long> #define vc vector<char> #define vii vector<pii> #define IMAX 2000000001 #define LMAX 1000000000000000000 #define DMAX 0xFFFFFFFFFFFFF int mv1[4] = { 0, 1, 0, -1 }; int mv2[4] = { 1, 0, -1, 0 }; int n, m; int maps[51][51]; int ch_to_home[13][100]; vector<pair<pii, bool>> chicken; vector<pair<pii, int>> home; int minLeng = IMAX; int getDis(pii x1, pii x2) { return abs(x1.first - x2.first) + abs(x1.second - x2.second); } int getChicken() { int all_chicken = 0; for (int i = 0; i < chicken.size(); i++) { if (chicken[i].second) { for (int j = 0; j < home.size(); j++) { home[j].second = min(home[j].second, ch_to_home[i][j]); } } } for (int i = 0; i < home.size(); i++) { all_chicken += home[i].second; home[i].second = IMAX; } return all_chicken; } void recul(int idx, int cnt) { if (cnt == m) { int minAllChicken = getChicken(); if (minAllChicken < minLeng) { minLeng = minAllChicken; } return; } for (int i = idx + 1; i < chicken.size(); i++) // ʱ idx ϰ { chicken[i].second = true; recul(i, cnt + 1); chicken[i].second = false; } } int main(void) { FIO; cin >> n >> m; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { cin >> maps[i][j]; if (maps[i][j] == 2) chicken.push_back(make_pair(make_pair(i, j), false)); if (maps[i][j] == 1) home.push_back(make_pair(make_pair(i, j), IMAX)); } } for (int i = 0; i < chicken.size(); i++) { for (int j = 0; j < home.size(); j++) { ch_to_home[i][j] = getDis(make_pair(chicken[i].first.first, chicken[i].first.second), make_pair(home[j].first.first, home[j].first.second)); } } recul(-1, 0); cout << minLeng; }
true
5860175cc4a8ae9586aedad3f55bd80f06835d2c
C++
Arjunann/competitive-programming
/MinimumTimetoMeet.cpp
UTF-8
1,514
3.90625
4
[]
no_license
// Efficient C++ program to find minimum time // required to produce m items. #include<bits/stdc++.h> using namespace std; // Return the number of items can be // produced in temp sec. int findItems(int arr[], int n, int temp) { int ans = 0; for (int i = 0; i < n; i++) ans += (temp/arr[i]); return ans; } // Binary search to find minimum time required // to produce M items. int bs(int arr[], int n, int m, int high) { int low = 1; // Doing binary search to find minimum // time. while (low < high) { // Finding the middle value. int mid = (low+high)>>1; // Calculate number of items to // be produce in mid sec. int itm = findItems(arr, n, mid); // If items produce is less than // required, set low = mid + 1. if (itm < m) low = mid+1; // Else set high = mid. else high = mid; } return high; } // Return the minimum time required to // produce m items with given machine. int minTime(int arr[], int n, int m) { int maxval = INT_MIN; // Finding the maximum time in the array. for (int i = 0; i < n; i++) maxval = max(maxval, arr[i]); return bs(arr, n, m, maxval*m); } // Driven Program int main() { int arr[] = { 1, 2, 3 }; int n = sizeof(arr)/sizeof(arr[0]); int m = 11; cout << minTime(arr, n, m) << endl; return 0; }
true
f398da8f9ab021334de0f6cf230b3f33b08c315d
C++
ZeroZhong/ACM2-
/第07章_2010_Day1/7.1.xiaoqiao/xiaoqiao.cpp
GB18030
2,664
3.046875
3
[]
no_license
#include<algorithm> #include<iostream> #include<cstring> #include<cstdlib> #include<cstdio> using namespace std; const int COLOR = 3; const int RANK = 13; int cnt[COLOR][RANK]; int max_group[RANK]; char answer[1594324]; // 3 ^ 13 == 1594324 // a洢3ÿһλget_slotת inline int get_slot(int a[]) { int slot = 0; for (int i = 0; i < RANK; ++i) { slot = slot * 3 + a[i]; } return slot; } // ͨ仯жÿ״̬ǷԷֳڶ bool presolve(int a[]) { int slot = get_slot(a); if (answer[slot] != -1) { return answer[slot]; } answer[slot] = false; int x = 0; while (x < RANK && a[x] == 0) { ++x; } if (x + 1 >= RANK || a[x + 1] == 0) { return false; } int b[RANK]; memcpy(b, a, sizeof(b)); --b[x]; --b[x + 1]; for (int i = 2; x + i < RANK; ++i) { if (b[x + i] > 0) { --b[x + i]; if (presolve(b)) { answer[slot] = true; break; } } } return answer[slot]; } // ö void preprocess_dfs(int a[], int p) { if (p == RANK) { presolve(a); return; } for (int i = 0; i < 3; ++i) { a[p] = i; preprocess_dfs(a, p + 1); } } // Ԥпн void preprocess() { memset(answer, -1, sizeof(answer)); int a[RANK]; memset(a, 0, sizeof(a)); answer[get_slot(a)] = true; preprocess_dfs(a, 0); } void input() { memset(cnt, 0, sizeof(cnt)); int n; scanf("%d", &n); while (n--) { int color, rank; scanf("%d%d", &color, &rank); ++cnt[color - 1][rank - 1]; } } // ԤÿrankȡٶԵһgroup void pre_dfs() { for (int i = 0; i < RANK; ++i) { int min_value = cnt[0][i]; for (int j = 1; j < COLOR; ++j) { min_value = min(min_value, cnt[j][i]); } max_group[i] = min_value; } } // ÿɫԤanswerO(1)жʣµĿܷ񱻷ֳɵڶgroup inline bool check() { for (int i = 0; i < COLOR; ++i) { if (!answer[get_slot(cnt[i])]) { return false; } } return true; } // öһôȡ bool dfs(int r) { if (r == RANK) { return check(); } for (int i = 0; i <= max_group[r]; ++i) { for (int j = 0; j < COLOR; ++j) { cnt[j][r] -= i; } if (dfs(r + 1)) { return true; } for (int j = 0; j < COLOR; ++j) { cnt[j][r] += i; } } return false; } void solve() { pre_dfs(); if (dfs(0)) { puts("Yes"); } else { puts("No"); } } int main() { freopen("xiaoqiao.in", "r", stdin); freopen("xiaoqiao.out", "w", stdout); preprocess(); int T; scanf("%d", &T); while (T--) { input(); solve(); } return 0; }
true
e23000ecde7b0abc71c588098d6a0cb2142bf376
C++
krishna-NIT/100DaysCodingChallenege
/Day26/Number of students unable to eat lunch.cpp
UTF-8
941
2.8125
3
[]
no_license
/* Platform :- Leetcode Approach :- Bruteforce and eliminate the types and studets choice accordingly */ class Solution { public: int countStudents(vector<int>& t, vector<int>& q) { int c=0,d=0; for(auto x:t)if(x)c++; for(auto x:q)if(x)d++; if(c==d){return 0;} vector<int>s; vector<int>p; p=q; s=t; while(1){ int f=0; vector<int>z; int i=0,j=0; for(int i=0;i<s.size();++i){ if(s[i]==p[0]){ p.erase(p.begin()); f=1; if(p.size()==0)break; } else{ z.push_back(s[i]); } } if(f==0)break; s.clear(); s=z; } return s.size(); } };
true
e1cfd19f3af43f51f36876ddd794e42c3b71cacb
C++
MrClassic/patch-ware
/patch-ware/DynamicOutputDevice.cpp
UTF-8
3,839
3.375
3
[]
no_license
/* ********************************************************************** * File: DynamicOutputDevice.cpp * Author: Nate Gallegos * * Log: * 8/29/19 * File Created ********************************************************************** */ #include "DynamicOutputDevice.h" /* Default Constructor: Does nothing special. nothing to initialize. */ DynamicOutputDevice::DynamicOutputDevice() { } /* Initialization Constructor: Accepts a Patch to initialize as an ouput. */ DynamicOutputDevice::DynamicOutputDevice(Patch * const patch) { addOutput(patch); } /* Copy Constructor: Performs a shallow copy of the base OutputDevice's output Patches. */ DynamicOutputDevice::DynamicOutputDevice(const DynamicOutputDevice &base) { LinkedList<Patch> copy = base.outputs; while (!copy.isEmpty()) { addOutput(copy.pop_front()); } } /* Add Output: Attempts to add a patch to this output device's output channels. */ bool DynamicOutputDevice::addOutput(Patch * const patch) { if (patch != NULL) { outputs.push_back(patch); patch->setInput(this); } return patch != NULL; } /* Remove Output: Attempts to remove the specified Patch from this output device's output Patches. If the patch is removed, true is returned. If the patch was not in this output device's output channels, false is returned. */ bool DynamicOutputDevice::removeOutput(Patch * const patch) { //shallow copy outputs LinkedList<Patch> copy = outputs; //shallow clear outputs.clear(); //result to return bool result = false; while (!copy.isEmpty()) { //Attempt to pop fro copied list Patch* pop = copy.pop_front(); if (pop == NULL) { //if popped a NULL, don't re-insert... "how did that get there???" continue; } else if (pop != patch) { //if not the patch to remove, re-insert it outputs.push_back(pop); } else { //if pop == patch, don't add. return true result = true; pop->setInput(NULL); } } //return result return result; } /* Gets the count of output channels for this OutputDevice */ int DynamicOutputDevice::getOutputCount() const { return outputs.getSize(); } /* Check Outputs: Checks whether the output patches are ready to accept the next signal. If there are any output patches that are not ready, false is returned. If all output patches are ready, then true is returned. */ bool DynamicOutputDevice::checkOutputs() const { return outputs.apply(checkOutputsPrivate, NULL); } // protected /* Output: Sends the specified signal to the output patches. */ void DynamicOutputDevice::output(const double signal) const { double sig = signal; outputs.apply(outputToPatches, &sig); } /* Get Output Patches: Accessor for this Output Device's output Patches in the form of a LinkedList. Returns a shallow copy of the output patches linked list */ LinkedList<Patch> DynamicOutputDevice::getOutputPatches() { return outputs; } // Private /* Output To Patches: Private function to be sent to the LinkedList.apply() method. This function converts the void* to a double, and sends it to the patch parameter. The boolean returned is passed back to the LinkedList.apply() function to let it know if it should continue applying this function to the next Patch in the list. */ bool DynamicOutputDevice::outputToPatches(Patch* patch, void* arg) { double* signal = (double*)arg; if (!*patch) return patch->pushSignal(*signal); return false; } /* Check Outputs Private: Private function to be sent to the LinkedList.apply() method. This function just checks the current Patch to see if it is ready for its next signal. The boolean returned is passed back to the LinkedList.apply() function to let it know if it should continue applying this function to the next Patch in the list. */ bool DynamicOutputDevice::checkOutputsPrivate(Patch* patch, void* arg) { return !*patch; }
true
00f19711bc7bd2e88e616564b354746d75b44f2c
C++
hex0d/ADSL
/Newton-EulerConvergenceTransformation.cpp
UTF-8
642
3.109375
3
[]
no_license
#include <iostream> #include <limits> #include <cmath> #include "windows.h" #include <iomanip> unsigned long long fat(int n){ unsigned long long fat = 1; while (n) { fat *= n; n--; } return fat; } double newt_euler_pi(int termos){ double pi = 0.0; double aux = 0.0 ; for (int i = 0; i < termos; i++){ unsigned long long f = fat(i); unsigned long long g = fat(2*i+1); unsigned long long h = fat(g); aux += (double)f/h; std::cout << aux << '\n'; //else break; } return pi; } int main(int argc, char const *argv[]) { std::cout << std::setprecision(30)<< newt_euler_pi(100000) << '\n'; return 0; }
true
222073b6d10d88032a966d40a68a288bd145ee98
C++
RockyYHL/gocpp
/ch03/test2_1.cpp
UTF-8
8,011
3.609375
4
[]
no_license
#include <iostream> using namespace std; #include <vector> #include <algorithm> /* 2 STL初识 2.1 STL的诞生 - 长久以来,软件界一直希望建立一种可重复利用的东西 - C++的面向对象和泛型编程思想,目的就是复用性的提升 - 大多情况下,数据结构和算法一直都未能有一套标准,导致被迫从事大量重复工作 - 为了建立数据结构和算法的一套标准,诞生了STL 2.2 STL基本概念 - STL(Standard Template Library,标准模板库) - STL从广义上分为: 容器(container)、算法(algorithm)、迭代器(Iterator) - 容器和算法之间通过迭代器进行无缝连接 - STL几乎所有的代码都采用了模板类或者模板函数 2.3 STL六大组件 STL大体分为六大组件,分别是容器、算法、迭代器、仿函数、适配器(配接器)、空间配置 1. 容器:各种数据结构,如vector、list、deque、set、map等,用来存放数据 2. 算法:各种常用的算法,如sort、find、copy、for_each等 3. 迭代器:扮演了容器与算法之间的胶合剂 4. 仿函数:行为类似函数,可以作为算法的某种策略 5. 适配器:一种用力啊修饰容器或者仿函数或迭代器接口的东西 4. 空间配置器:负责空间的配置与管理 2.4 STL中容器、算法、迭代器 容器:置物之所也 STL容器就是将运用最广泛的一些数据结构实现出来 常用的数据结构:数组,链表,树,栈,队列,集合,映射表 等 这些容器分为序列式容器和关联式容器两种: 序列式容器:强调值的排序,序列式容器中的每个元素均有固定的位置 关联式容器:二叉树结构,各元素之间没有严格的物理上的顺序关系 算法:问题之解法也 有限的步骤,解决逻辑或数学上的问题,这一门学科我们叫做算法(algorithm) 算法分为质变算法和非质变算法 质变算法: 是指运算过程中会更改区间内的元素的内容,例如拷贝,替换,删除等等 非质变算法:是指运算过程中不会更改区间的元素内容,例如查找、计数、遍历、寻找极值等等 迭代器:容器和算法之间的粘合剂 提供一种方法: 是之能够依序寻访某个容器所含的各个元素,而又无需暴露该容器的内部表示方式 每个容器都有自己的迭代器 迭代器使用非常类似于指针,初学阶段我们可以先理解迭代器为指针 迭代器种类: 输入迭代器 | 对数据的只读访问 | 只读,支持 ++、==、!= 输出迭代器 | 对数据的只写访问 | 只写,支持 ++ 前向迭代器 | 读写操作,并能向前推进迭代器 | 读写,支持 ++、==、!= 双向迭代器 | 读写操作,并能向前和向后操作 | 读写,支持 ++、-- 随机访问迭代器 | 读写操作,可以跳跃的方式访问任意数据,功能是最强的迭代器 |读写,支持 ++、--、[n]、-n、<、<=、>、>= 常用的容器中迭代器种类分为双向迭代器,和随机访问迭代器 2.5 容器算法迭代器初识 了解STL中容器、算法、迭代器概念之后,我们利用代码感受STL的魅力 STL中最常用的容器为vector, 可以理解为数组,下面我们将学习如何向这个容器中插入数据,并遍历这个容器 2.5.1 vector存放内置数据类型 容器:vector 算法:for_each 迭代器:vector<int>::iterator 2.5.2 Vector存放自定义数据类型 学习目标: vector中存放自定义数据类型,并打印输出 2.5.3 Vector容器嵌套容器 学习目标:容器中嵌套容器,我们将所有数据进行遍历输出 */ void myPrint(int val) { cout << val << endl; } void test01() { // 创建一个vector容器,数组 vector<int> v; v.push_back(10); v.push_back(20); v.push_back(60); v.push_back(80); v.push_back(30); vector<int>::iterator itBegan = v.begin(); // 起始迭代器,指向容器中的第一个元素 vector<int>::iterator itEnd = v.end(); // 结束迭代器,指向容器中最后一个元素的下一个位置 // // 第一种遍历方式 // while (itBegan != itEnd) // { // cout << *itBegan << endl; // itBegan++; // } // // 第二种遍历方式 // for (vector<int>::iterator it = v.begin(); it != v.end(); it++) // { // cout << *it << endl; // } // 第三种遍历方式,利用STL中提供的遍历算法 for_each(v.begin(), v.end(), myPrint); } void printVector(vector<vector<float>> frame_info) { if (frame_info.empty()) { cout << "The vector is empty!" << endl; return; } int i, j; cout << "Use index : " << endl; for (i = 0; i < frame_info.size(); i++) { for (j = 0; j < frame_info[0].size(); j++) cout << "frame_info: " << frame_info[i][j] << " "; cout << "---------" << i << "---------" << endl; } cout << "**************************" << endl; } void testother() { static vector<vector<float>> frame_info; //初始化row*column二维动态数组,初始化值为0 vector<float> object_info; object_info.push_back(20 + 60); object_info.push_back(20 + 60); object_info.push_back(40 + 60); object_info.push_back(40 + 60); object_info.push_back(0); object_info.push_back(0); object_info.push_back(0); object_info.push_back(0); object_info.push_back(0); frame_info.push_back(object_info); printVector(frame_info); } class Person { public: Person(string name, int age) { this->m_age = age; this->m_name = name; } string m_name; int m_age; }; void test02() { vector<Person> v; Person p1("aaa", 10); Person p2("bbb", 20); Person p3("ccc", 30); Person p4("ddd", 40); Person p5("eee", 60); v.push_back(p1); v.push_back(p2); v.push_back(p3); v.push_back(p4); v.push_back(p5); for (vector<Person>::iterator it = v.begin(); it != v.end(); it++) { cout << "name: " << (*it).m_name << "\t" << "age: " << (*it).m_age << endl; } } // 存放自定义数据类型 指针 void test03() { vector<Person *> v; Person p1("aaa", 10); Person p2("bbb", 20); Person p3("ccc", 30); Person p4("ddd", 40); Person p5("eee", 60); v.push_back(&p1); v.push_back(&p2); v.push_back(&p3); v.push_back(&p4); v.push_back(&p5); for (vector<Person *>::iterator it = v.begin(); it != v.end(); it++) { cout << "name: " << (**it).m_name << '\t' << "age: " << (**it).m_age << endl; } } void test04() { vector<vector<int>> v; vector<int> v1; vector<int> v2; vector<int> v3; vector<int> v4; for (int i = 0; i < 4; i++) { v1.push_back(i + 1); v2.push_back(i + 2); v3.push_back(i + 3); v4.push_back(i + 4); } v.push_back(v1); v.push_back(v2); v.push_back(v3); v.push_back(v4); for(vector<vector<int>>::iterator it = v.begin(); it != v.end(); it++){ // cout << (*it) << endl; for(vector<int>::iterator it2 = (*it).begin(); it2 != (*it).end(); it2++){ cout << (*it2) << " "; } cout << endl; } } int main() { // test01(); // testother() // test02(); // test03(); test04(); return 0; }
true
ec38473e9a4c3690e3be3f60a7d64cd33e63f7ce
C++
liuyuwang2016/-C-
/Final/Final 2/Source.cpp
GB18030
786
3.203125
3
[ "MIT" ]
permissive
#include<iostream> using namespace std; int main() { int n; while (cin >> n) { if (n % 3 == 0) {//Ȱܱ3Ķֱ if (n % 5 == 0) { if (n % 7 == 0) cout << "3 5 7" << endl; else cout << "3 5" << endl; } if (n % 7 == 0 && n % 5 != 0) cout << "3 7" << endl; if (n % 7 != 0 && n % 5 != 0) cout << '3' << endl; } if (n % 5 == 0 && n % 3 != 0) {//Ϊܱ3Ѿ۹ˣֻܱ5ܱ3 if (n % 7 == 0) cout << "5 7" << endl; else cout << '5' << endl; } if (n % 7 == 0 && n % 3 != 0 && n % 5 != 0)//ͬ cout << '7' << endl; if (n % 7 != 0 && n % 3 != 0 && n % 5 != 0)//ɶҲܵ cout << 'n' << endl; } return 0; }
true
4ca3b8f16a6f431cf1363a5001c0f1e129711484
C++
Jamil132/DSA-COMPLETE-SERIES
/Practise Code 1/Friend function in cpp.cpp
UTF-8
541
3.1875
3
[]
no_license
#include <iostream> #include <bits/stdc++.h> using namespace std; class Y; class X { int data; public: void setValue(int value){ data = value; } friend void sumdata(X,Y); }; class Y { int num; public: friend void sumdata(X,Y); void setValue(int value){ num = value; } }; void sumdata(X b1, Y b2) { cout<<"The of sum of X and Y is "<<b1.data + b2.num<<endl; } int main() { X a; a.setValue(4); Y b; b.setValue(5); sumdata(a,b); return 0; }
true
14efb35ca7fff58d1b184af4e44952bbb35f6333
C++
semiessessi/jEngine
/jen/Source/pngtex.h
UTF-8
693
2.515625
3
[]
no_license
// .png texture loader by Semi Essessi // only supports loading 3/4 channel pngs to a rgba/rgb0 unsigned int bitmap // can be easily updated to support further types or perhaps ALL using the libpng functions #ifndef PNGTEX_H #define PNGTEX_H #pragma comment(lib, "libpng.lib") #pragma comment(lib, "zlib.lib") #include "libpng\png.h" #include <malloc.h> class png_tex { private: int width; int height; public: unsigned int* imagedata; png_tex() { imagedata = 0; } ~png_tex() { if(imagedata) free(imagedata); } bool LoadFromFile(char* filename); int GetWidth(); int GetHeight(); }; #endif
true
8ef23518e312e063bd8709f7a66e6e71e4130d56
C++
miguelcarvalhosa/CAV-20-21
/examples/classes/example.cpp
UTF-8
421
3
3
[]
no_license
// // Created by Antonio J. R. Neves on 16/10/2020. // #include "Img.h" #include <iostream> using namespace std; int main() { Img i1; Img i2(1024, 768); cout << i1.getNCols() << endl; try { i1.putPixel(10, 1, 255); } catch (std::out_of_range e){ std::cout << e.what() << std::endl; } i1.print(); string s = string("CAV"); cout << "ola" << s << std::endl; return 0; }
true
bb3d2cfe074460b3804cb7ef72b8f2d35b567065
C++
shuz/TinyGraphics
/project/016/src/TinyGraphics/TinyGraphics/Kernel/Primitive3D.h
UTF-8
2,762
3.359375
3
[]
no_license
#ifndef PRIMITIVE_3D_INCLUDED__ #define PRIMITIVE_3D_INCLUDED__ #include "Real.h" #include "Vector3D.h" #include "Matrix4D.h" #include <vector> namespace TinyGraphics { class Point3D { public: real x, y, z; Point3D() { assign(0, 0, 0); } Point3D(real x, real y, real z) { assign(x, y, z); } Point3D(const Vector3D& v) { from_vec3d(v); } void from_vec3d(const Vector3D& v) { assign(v(0), v(1), v(2)); } Vector3D to_vec3d() const { return Vector3D(x, y, z); } void assign(real x, real y, real z) { this->x = x; this->y = y; this->z = z; } bool operator==(const Point3D& rhs) const { return x == rhs.x && y == rhs.y && z == rhs.z; } bool operator!=(const Point3D& rhs) const { return x != rhs.x || y != rhs.y || z != rhs.z; } Vector3D operator-(const Point3D& rhs) const { return Vector3D(x - rhs.x, y - rhs.y, z - rhs.z); } Point3D& operator+=(const Vector3D& rhs) { x += rhs(0); y += rhs(1); z += rhs(2); return *this; } Point3D& operator+=(const Point3D& rhs) { x += rhs.x; y += rhs.y; z += rhs.z; return *this; } Point3D operator+(const Vector3D& rhs) const { return Point3D(*this) += rhs; } Point3D& operator*=(const Matrix4D& mat) { transform(mat); return *this; } Point3D operator*(const Matrix4D& mat) const { return Point3D(*this) *= mat; } void transform(const Matrix4D& mat) { Vector3D vec(x, y, z); vec *= mat; from_vec3d(vec); } static const Point3D ORIGIN; }; class TriangleSet { public: struct Triangle { Triangle() {} Triangle(int a, int b, int c) : a(a), b(b), c(c) {} int a, b, c; // indices of vertices in the triangle set void assign(int aa, int bb, int cc) { a = aa; b = bb; c = cc; } }; typedef std::vector<Point3D> VertexContainer; typedef std::vector<Vector3D> NormalContainer; typedef std::vector<Triangle> TriangleContainer; VertexContainer vertices; NormalContainer normals; TriangleContainer triangles; void transform(const Matrix4D& rhs) { VertexContainer::iterator itor1 = vertices.begin(), end1 = vertices.end(); for (; itor1 != end1; ++itor1) { (*itor1).transform(rhs); } NormalContainer::iterator itor2 = normals.begin(), end2 = normals.end(); for (; itor2 != end2; ++itor2) { (*itor2).transform(rhs); } } void clear() { vertices.clear(); normals.clear(); triangles.clear(); } }; } #endif
true
cabb273b4314a208421e1487c7f96a23fda46871
C++
jjzhang166/QT43
/patedit/patternEdit/pattimagemodel.cpp
UTF-8
2,509
2.5625
3
[]
no_license
#include <QtGui> #include <QtCore> #include "pattimagemodel.h" pattImageModel::pattImageModel(QObject *parent) : QAbstractTableModel(parent) { for (int i = 0; i < 16; i ++) { QString name; name.sprintf(":/colorImage/%d.bmp", i); itemDisplay[0][i].load(name); // 正色图片 name.sprintf(":/colorImage/%d.bmp", 100+i); itemDisplay[1][i].load(name); // 反色图片 } enableRevColor = false; itemRevColor = 0; memset(itemColorData, 0, sizeof(itemColorData)); } int pattImageModel::rowCount(const QModelIndex & /* parent */) const { return 25; } int pattImageModel::columnCount(const QModelIndex & /* parent */) const { return 50; } QVariant pattImageModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); if (role == Qt::EditRole) { return itemColorStr[index.row()][index.column()]; } uchar value = itemColorData[index.row()][index.column()]; if (role == Qt::DisplayRole) { return itemDisplay[0][value]; } else if (role == Qt::UserRole) { return itemDisplay[itemRevColor][value]; } return QVariant(); } QVariant pattImageModel::headerData(int /* section */, Qt::Orientation /* orientation */, int role) const { return QVariant(); } Qt::ItemFlags pattImageModel::flags( const QModelIndex &) const { return (Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsEnabled); } bool pattImageModel::setData(const QModelIndex &index, const QVariant &var, int role) { if (index.isValid() && role == Qt::EditRole) { QString input; uchar data; bool ok; input = var.toString(); data = input.toInt(&ok, 16); if (ok) { itemColorData[index.row()][index.column()] = data; itemColorStr[index.row()][index.column()] = input; emit dataChanged(index, index); return true; } } else if (index.isValid() && role == Qt::UserRole) { if (enableRevColor) { // 切换反色图片 itemRevColor = var.toInt(); emit dataChanged(index, index); enableRevColor = false; return true; } } else if (index.isValid() && role == Qt::UserRole + 1) { enableRevColor = var.toBool(); return true; } return false; }
true
50d5cb516f270872771884a13786d12f86e57338
C++
Mingchenchen/raptorx-zy
/contrib/BALL/include/BALL/MOLMEC/PARAMETER/quadraticBondStretch.h
UTF-8
2,410
2.59375
3
[]
no_license
// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: quadraticBondStretch.h,v 1.18 2005-12-23 17:01:54 amoll Exp $ // #ifndef BALL_MOLMEC_PARAMETER_QUADRATICBONDSTRETCH_H #define BALL_MOLMEC_PARAMETER_QUADRATICBONDSTRETCH_H #ifndef BALL_FORMAT_PARAMETERSECTION_H # include <BALL/FORMAT/parameterSection.h> #endif #ifndef BALL_MOLMEC_PARAMETER_ATOMTYPES_H # include <BALL/MOLMEC/PARAMETER/atomTypes.h> #endif namespace BALL { /** QuadraticBondStretch. Molecular Mechanics Parameter: class describing the parameters required for a harmonic stretch potential. \ingroup MolmecParameters */ class BALL_EXPORT QuadraticBondStretch : public ParameterSection { public: enum { UNKNOWN }; struct BALL_EXPORT Values { float r0; float k; }; struct BALL_EXPORT Data { Atom::StaticAtomAttributes* atom1; Atom::StaticAtomAttributes* atom2; Values values; }; /** Default constructor. */ QuadraticBondStretch(); /** Destructor. */ virtual ~QuadraticBondStretch() throw(); /** Clear method */ virtual void clear() throw(); /** Reads a parameter section from an INI file. This method reads the section given in section_name from ini_file, interprets (if given) a format line, reads the data from this section according to the format, and builds some datastructures for fast and easy acces this data. */ virtual bool extractSection(ForceFieldParameters& parameters, const String& section_name); /// virtual bool extractSection(Parameters& parameters, const String& section_name); /** Queries whether a parameter set is defined for the given atom types. */ bool hasParameters(Atom::Type I, Atom::Type J) const; /** Returns the parameters for a given atom type combination. */ QuadraticBondStretch::Values getParameters (Atom::Type I, Atom::Type J) const; /** Assign the parameters for a given atom type combination. If no parameters are defined for this combination, false is returned and nothing is changed. */ bool assignParameters (QuadraticBondStretch::Values& parameters, Atom::Type I, Atom::Type J) const; protected: Size number_of_atom_types_; float* k_; float* r0_; bool* is_defined_; String* names_; }; } // namespace BALL #endif // BALL_MOLMEC_PARAMETER_QUADRATICBONDSTRETCH_H
true
4038df33d70ca38c1ae2da2d716de5d4c1d6e906
C++
Deven-14/CPP_Lab
/asgn1/sqrt.cpp
UTF-8
206
3.15625
3
[]
no_license
#include <iostream> #include <cmath> using namespace std; int main() { double a; cout << "Enter a number : " << endl; cin >> a; cout << "Square root of " << a << " = " << sqrt(a) << endl; return 0; }
true
a5eef7027d7c1572984374603457de492ef2aa54
C++
zywww/regex_engine
/regex_engine/Lexer.h
UTF-8
313
2.578125
3
[]
no_license
#ifndef LEXER_H #define LEXER_H #include <fstream> #include <string> #include "Token.h" class Lexer { public: Lexer(const std::string &regex); Token GetNextToken(); private: void Error(char ch); std::string regex_; std::string::size_type index_ = 0; bool error_ = false; }; #endif
true
97d71bedcd527db1af65046bb10a66f86a3108e6
C++
SiggiSigmann/adventofcode2020
/04/_2/04.cpp
UTF-8
7,029
3.421875
3
[ "MIT" ]
permissive
#include <iostream> #include <fstream> #include <string> using namespace std; /*############################################################################## # depicts a database # byr (Birth Year) # iyr (Issue Year) # eyr (Expiration Year) # hgt (Height) # hcl (Hair Color) # ecl (Eye Color) # pid (Passport ID) # cid (Country ID) ##############################################################################*/ struct Passport { string byr; string iyr; string eyr; string hgt; string hcl; string ecl; string pid; string cid; } ; /*############################################################################## # counts number of entires in given file ##############################################################################*/ int numberOfEntries(string fileName){ int lineCount = 0; string inputLine; ifstream inputFile (fileName); if (inputFile.is_open()){ //count lines while (getline(inputFile, inputLine)){ if(inputLine.empty()) lineCount++; } inputFile.close(); lineCount++; } cout << "Number of Etries: " << lineCount << '\n'; return lineCount; } /*############################################################################## # loads each entry in the file in a Passport array # byr (Birth Year) # iyr (Issue Year) # eyr (Expiration Year) # hgt (Height) # hcl (Hair Color) # ecl (Eye Color) # pid (Passport ID) # cid (Country ID) ##############################################################################*/ int loadFileInArray(string fileName, Passport *passports, int length){ string inputLine; ifstream inputFile (fileName); if (inputFile.is_open()){ int passport = 0; //itereate over file and fille array while(passport<length && getline(inputFile, inputLine)){ if(inputLine.empty()){ passport++; continue; } //split string an fille Passport entry int endoffset = inputLine.find(":"); int start = 0; string key = "", value = ""; while(endoffset != string::npos){ key = inputLine.substr(start, endoffset-start); start = endoffset+1; endoffset = inputLine.find(" ", start); if(endoffset == string::npos) endoffset = inputLine.length(); value = inputLine.substr(start, endoffset-start); //write key value in Passport entry if(key == "byr"){ passports[passport].byr = value; }else if(key == "iyr"){ passports[passport].iyr = value; }else if(key == "eyr"){ passports[passport].eyr = value; }else if(key == "hgt"){ passports[passport].hgt = value; }else if(key == "hcl"){ passports[passport].hcl = value; }else if(key == "ecl"){ passports[passport].ecl = value; }else if(key == "pid"){ passports[passport].pid = value; }else if(key == "cid"){ passports[passport].cid = value; } start = endoffset+1; endoffset = inputLine.find(":", start-1); } } inputFile.close(); return 1; } return 0; } /*############################################################################## # The next seven methods are checks rules for each entry ##############################################################################*/ //byr (Birth Year) - four digits; at least 1920 and at most 2002. int byrCheck(string input){ if(input.empty()) return 0; try{ int i = std::stoi(input); if(!(1920 <= i && i <= 2002)) return 0; }catch (std::invalid_argument const &e){ return 0; } return 1; } //iyr (Issue Year) - four digits; at least 2010 and at most 2020. int iyrCheck(string input){ if(input.empty()) return 0; try{ int i = std::stoi(input); if(!(2010 <= i && i <= 2020)) return 0; }catch (std::invalid_argument const &e){ return 0; } return 1; } //eyr (Expiration Year) - four digits; at least 2020 and at most 2030. int eyrCheck(string input){ if(input.empty()) return 0; try{ int i = std::stoi(input); if(!(2020 <= i && i <= 2030)) return 0; }catch (std::invalid_argument const &e){ return 0; } return 1; } //hgt (Height) - a number followed by either cm or in: // - If cm, the number must be at least 150 and at most 193. // - If in, the number must be at least 59 and at most 76. int hgtCheck(string input){ if(input.empty()) return 0; int split = input.find("cm"); if(split == string::npos){ split = input.find("in"); if(split == string::npos) return 0; } string height = input.substr(0, split); string unit = input.substr(split, input.length()-(split)); try{ int i = std::stoi(height); if(unit == "cm"){ if(!(150 <= i && i <= 193)) return 0; }else{ if(!(59 <= i && i <= 76)) return 0; } }catch (std::invalid_argument const &e){ return 0; } return 1; } //(Hair Color) - a # followed by exactly six characters 0-9 or a-f // ASCII values => 48->57 (0-9) and 97->102 (a-f) int hclCheck(string input){ if(input.empty()) return 0; int split = input.find("#"); if(split == string::npos || split != 0) return 0; string color = input.substr(split+1, input.length()-(split+1)); for(int i = 0; i < color.length(); i++){ char c = color.at(i); if(!((48 <= c && c <=57) || (97 <= c && c <= 102))) return 0; } return 1; } //(Eye Color) - exactly one of: amb blu brn gry grn hzl oth. int eclCheck(string input){ if(input.empty()) return 0; if(!(input == "amb" || input == "blu" || input == "brn" || input == "gry" || input == "grn" || input == "hzl" || input == "oth")){ return 0; } return 1; } //(Passport ID) - a nine-digit number, including leading zeroes. int pidCheck(string input){ if(input.empty()) return 0; if(input.length() != 9) return 0; try{ int i = std::stoi(input); }catch (std::invalid_argument const &e){ return 0; } return 1; } /*############################################################################## # checks each entry in the Passport array against the rules defined above # byr (Birth Year) # iyr (Issue Year) # eyr (Expiration Year) # hgt (Height) # hcl (Hair Color) # ecl (Eye Color) # pid (Passport ID) # cid (Country ID) ##############################################################################*/ int processPassport(Passport *entries, int length){ int accepted = 0; for(int i = 0; i<length; i++){ if(!byrCheck(entries[i].byr)){ continue; } if(!iyrCheck(entries[i].iyr)){ continue; } if(!eyrCheck(entries[i].eyr)){ continue; } if(!hgtCheck(entries[i].hgt)){ continue; } if(!hclCheck(entries[i].hcl)){ continue; } if(!eclCheck(entries[i].ecl)){ continue; } if(!pidCheck(entries[i].pid)){ continue; } accepted++; } return accepted; } int main(){ string filename = "../input.txt"; //get numbers of enties int entrieNumber = numberOfEntries(filename); if(!entrieNumber) return 1; //get file as an array Passport *passports = new Passport[entrieNumber]; int res = loadFileInArray(filename, passports, entrieNumber); if(!res) return 1; //check entries res = processPassport(passports, entrieNumber); if(!res) return 1; cout << "Number of accepted: " << res <<"\n"; delete passport; return 0; }
true
e3eb37ce0f9b1e934af570aae12b2dd584f21a7a
C++
UNKJay/Data_Structure_Algorithm
/Data_Structures_ZJU/Chap9/Sort.cpp
UTF-8
4,677
3.078125
3
[]
no_license
#include<cstdio> #include<algorithm> using namespace std; const int MAXN = 100010; const int CUTOFF = 100; int N; long long int A[MAXN]; long long int TempA[MAXN]; void BubbleSort(); void InsertSort(int l, int r); void ShellSort(); void HeapSort(); void PercDown(int L , int R); void MergeSort(); void Merge(int L, int R, int rightEnd); void MSort(int l, int rightEnd); void MergePass(int length); void QuickSort(int l, int r); long long int Median3(int l, int r); int main() { scanf("%d",&N); for (int i = 0; i < N; i++) { scanf("%lld",&A[i]); } //BubbleSort(); //InsertSort(); // ShellSort(); // HeapSort(); //MergeSort(); QuickSort(0,N-1); for (int i = 0; i < N; i++) { printf("%lld",A[i]); if (i == N-1) printf("\n"); else printf(" "); } return 0; } void BubbleSort() { for (int p = N-1; p >= 0; --p) //p为元素放的位置 { bool flag = false; for (int i = 0; i < p; i++) { if (A[i] > A[i+1]) { long long int temp = A[i]; A[i] = A[i+1]; A[i+1] = temp; flag = true; } } if (!flag) break; } } void InsertSort(int l, int r) { for (int p = l+1; p <= r; p++) { int i; long long int temp = A[p]; for (i = p; i > 0 && A[i-1] > temp; --i) { A[i] = A[i-1]; } A[i] = temp; } } void ShellSort() { for (int D = N/2; D > 0; D /= 2){ for (int p = D; p < N; p += D) { int i; long long int temp = A[p]; for (i = p; i >= D && A[i-D] > temp; i -= D) { A[i] = A[i-D]; } A[i] = temp; } } } void HeapSort() { //构建最大堆,调整,0-N-1 for (int i = (N-1)/2; i >= 0; i--) { PercDown(i,N); // build heap } for (int i = N-1; i > 0; --i) { long long int temp = A[0]; A[0] = A[i]; A[i] = temp; PercDown(0,i); } } void PercDown(int L, int R) { // 树根不是堆 long long int temp = A[L]; int parent,child; for (parent = L; parent * 2 + 1 < R; parent = child) { child = parent * 2 + 1; if (child != R-1 && A[child] < A[child+1]) child++; if (temp < A[child]) { A[parent] = A[child]; } else { break; } } A[parent] = temp; } // L为左边开始位置,R为右边开始位置,rightEnd为右边结束位置 void Merge(int l, int r, int rightEnd) { int leftEnd = r - 1; int temp = l; int num = rightEnd - l + 1; while (l <= leftEnd && r <= rightEnd) { if (A[l] <= A[r]) TempA[temp++] = A[l++]; else TempA[temp++] = A[r++]; } while (l <= leftEnd) TempA[temp++] = A[l++]; while (r <= rightEnd) TempA[temp++] = A[r++]; for (int i = 0; i < num; i++, rightEnd--) { A[rightEnd] = TempA[rightEnd]; } } void MSort(int l, int rightEnd) { int center; if (l < rightEnd) { center = (l + rightEnd) / 2; MSort(l,center); MSort(center+1, rightEnd); Merge(l,center+1,rightEnd); } } void MergeSort() { // 递归版本 // MSort(0,N-1); // 非递归版本 int length = 1; while (length < N) { MergePass(length); length *= 2; MergePass(length); length *= 2; } } void MergePass( int length) { int i; for (i = 0; i <= N-2*length; i += 2*length) { Merge(i, i+length, i+length*2-1); } if (i + length < N) { Merge(i, i+length, N-1); } else { for (int j = i; j < N; j++) TempA[j] = A[j]; } } long long int Median3(int l, int r) { int center = (l+r)/2; if (A[center] < A[l]) { swap(A[l],A[center]); } if (A[r] < A[l]) { swap(A[l],A[r]); } if (A[r] < A[center]) { swap(A[center],A[r]); } swap(A[center],A[r-1]); //将主元藏起来 return A[r-1]; } // QuickSort(0,N-1) void QuickSort(int l, int r) { if (CUTOFF <= r-l) { //最好为100 long long int pivot = Median3(l,r); int i = l; int j = r-1; for (;;) { while (A[++i] < pivot) {} while (A[--j] > pivot) {} if (i < j) { swap(A[i],A[j]); } else break; } swap(A[i],A[r-1]); //确定主元位置 QuickSort(l,i-1); QuickSort(i+1,r); } else { InsertSort(l,r); } }
true
d630b692d2f1464b1901d69264e29d2c68a75c1b
C++
fantasydreams/usually-coding
/ACM/3n+1problem.cpp
UTF-8
602
3.40625
3
[]
no_license
#include <iostream> /* 3n+1 problem */ using namespace std; void calculate(int * a, const int number, int num); int main() { int size; cin >> size; int * p = new int[size]; for (int i = 0,temp; i < size; i++) { cin >> temp; calculate(p, temp, i); } for (int i = 0; i < size; i++) { cout << p[i]<<endl; } delete[] p; //free memory system("pause"); return 0; } void calculate(int * p, int number,int i) { int n = 0; while (number != 1) { if (number % 2) number = 3 * number + 1; else number /= 2; if (n > 1000) { p[i] = -1; break; } n++; } p[i] = n; }
true
839391cb865ad935fb0791c9a8291bfa219721bf
C++
wjslager/KO2
/teensy3.2/ldr_recorder/recording.ino
UTF-8
2,067
3.21875
3
[]
no_license
void recordMotion() { if (recording) { // Display the users actions using the led outputLight = light; // Record LDR values // One sample per 10ms if (millis() % 10 == 0) { // Take a sample recordedValues[playbackPos] = light; // Advance one step playbackPos++; Serial.print("Sampled LDR value at "); Serial.println(playbackPos++); } playbackPos = playbackPos % 1000; } else { // Display the recorded motion outputLight = recordedValues[playbackPos]; // Serial.println(recordedValues[playbackPos]); if (millis() % 10 == 0) { playbackPos++; playbackPos = playbackPos % 1000; Serial.print("Playing recorded value at "); Serial.println(playbackPos++); } } } void dynamicRecording() { // Automatically starts recording when a 'light on' is detected // Will stop recording ~1000ms after the last 'light off' switch (lightSwitch()) { case 1: // Light on if (!recording) { // Set recording to true and save the starttime playbackPos = 0; recording = true; timeStartRec = millis(); } case -1: // Light off timeSinceLastMotion = millis(); default: // No change // If the light is off, start a countdown of 1000ms to stop recording if (!light) { if ((millis() - timeSinceLastMotion) >= 1000) { // Stop recording, set playbackhead at 0 recording = false; } } } } int lightSwitch() { // Detects 'light on' and 'light off' if (ldrValue > ldrThreshold) { light = false; } else { light = true; } if (light != lastLight) { if (light) { // Light turned on lastLight = light; // Serial.println("1"); return 1; } else { // Light turned off lastLight = light; // Serial.println("2"); return -1; } } else { // No change lastLight = light; return 0; } }
true
ff764f420e86a750e7e89d1d9fdf6457b00810f8
C++
acc-cosc-1337-spring-2021/acc-cosc-1337-spring-2021-24SergioA
/src/classwork/03_assign/main.cpp
UTF-8
989
3.984375
4
[ "MIT" ]
permissive
#include "decision.h" #include <iostream> //Write the include statement for decisions.h here //Write namespace using statements for cout and cin //Prompt the user for a number and if the number is between 0 and 100 //call both get_letter_grade_using_if and get_letter_grade_using_switch //functions to display the letter grade to screen otherwise display number out of range. int main() { // Add space when starting std::cout<<"\n"; // If - else statament ---------------------------- int grade1; std::cout<<"What's the test grade? "; std::cin>>grade1; std::cout << "Grade of " << grade1 << " is: " << get_letter_grade_using_if(grade1) <<"\n"; //std::cout<<get_letter_grade_using_if(grade1); std::cout<<"\n"; // Switch - Statement ---------------------------- int grade2; std::cout<<"What's the test grade? "; std::cin>>grade2; std::cout << "Grade of " << grade2 << " is: " << get_letter_grade_using_switch (grade2) <<"\n"; std::cout<<"\n"; return 0; }
true
b04c64380d29433493189e2b04aad441e794a383
C++
IssaShane/upgraded-waffle
/src/Level.h
UTF-8
503
2.53125
3
[]
no_license
#ifndef LEVEL_H #define LEVEL_H #include <SDL.h> #include <SDL_image.h> #include <fstream> #include <vector> #include "Subject.h" class Level : public Subject { public: Level( const char *filename, int CollY ); Level(const Level&); void draw( SDL_Surface *Screen ); bool IsColliding(const SDL_Rect&) const; int findFloor(const SDL_Rect&) const; ~Level(); SDL_Surface *Img; int Colly; std::vector<SDL_Rect> floor; }; #endif
true
cdad99d37ae4554494523f932bec5b7b0b1dbb6c
C++
cnsuhao/myown
/FsGame/SystemFunctionModule/CoolDownModule.h
GB18030
2,992
2.515625
3
[]
no_license
//-------------------------------------------------------------------- // ļ: Server\FsGame\SkillModule\CoolDownModule.h // : ȴϵͳ // ˵ : // : 2008/01/28 // : // : //-------------------------------------------------------------------- #ifndef __CoolDownModule_h__ #define __CoolDownModule_h__ #include "Fsgame/Define/header.h" #include <vector> //ȴж enum CoolDownRecColIndex { COOLDOWN_REC_COL_ID, //ȴID COOLDOWN_REC_COL_BEGINTIME, //ȴʼʱ COOLDOWN_REC_COL_ENDTIME, //ȴʱ COOLDOWN_REC_COL_COUNT }; class CoolDownModule : public ILogicModule { public: //ʼ virtual bool Init(IKernel* pKernel); //ͷ virtual bool Shut(IKernel* pKernel); static CoolDownModule* Instance(); public: /** @brief ʼһȴȴ @param [IN]cooldowncategory:ȴ [IN]cooldowntime:ȴʱ䣬λms @remarks @return ɹʼȴtrue򣬷false */ bool BeginCoolDown(IKernel* pKernel, const PERSISTID& self, int cooldowncategory, int cooldowntime ); /** @brief һȴȴ @param [IN]cooldowncategory:ȴ @remarks @return ɹʼȴtrue򣬷false */ bool EndCoolDown(IKernel* pKernel, const PERSISTID& self, int cooldowncategory); /** @brief ָǷȴ @param [IN]cooldowncategory:ȴ @remarks @return ijȴУtrue򷵻false */ bool IsCoolDown(IKernel* pKernel, const PERSISTID& self, int cooldowncategory); // ȡȴʣ int64_t GetMillisecRemain(IKernel* pKernel, const PERSISTID& self, int cooldowncategory); //ȫCD void ClearAllCD(IKernel* pKernel, const PERSISTID& self); //CD void ClearPlayerNormalSkillCD(IKernel* pKernel, const PERSISTID& self); // ȡ bool LoadConfig(IKernel* pKernel); private: // static int OnPlayerStore(IKernel* pKernel, const PERSISTID& self, const PERSISTID& sender, const IVarList& args); //ȴϢȴ bool InnerBeginCoolDown(IRecord* pRecordCool, const int& cooldowncategory, const int64_t& begin_time, const int64_t& end_time); // Ƿȴȴкţȴ-1 int InnerIsCoolDown(IRecord* pRecordCool, const int cooldowncategory, const int64_t now); //ҳʱȴ bool ClearCoolDownRec(IRecord* pRecordCool); // ǷҪCD bool IsNeedSaveCategory(int nCategory); static void ReloadConfig(IKernel* pKernel); public: static CoolDownModule* m_pInstance; private: std::vector<int> m_vSavedCategoryIds; // ҪCD }; #endif
true
087736d1bf947fcbd2f9105cc2fb88e624bd6c1a
C++
proRamLOGO/high-school
/pnc.cpp
UTF-8
551
2.703125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; const long long MAX = 999999999; bool seen[10]; bool isRepFree(long long i) { if(i == 0) return false; memset(seen, false, sizeof(seen)); while(i) { if(i % 10 == 0 or seen[i % 10]) return false; seen[i % 10] = true; i /= 10; } return true; } int main(void) { int N; cin >> N; bool ans = false; for(int i = N + 1; i <= MAX; i++) { if(isRepFree(i)) { ans = true; cout << i << "\n"; break; } } if(!ans) cout << "0\n"; return 0; }
true
481afc24dfaa0b7af06e973ea1407535535eaabf
C++
fledmer/MushroomsGame
/hackgamewidget.cpp
UTF-8
8,158
2.609375
3
[]
no_license
#include "hackgamewidget.h" #include <random> #include <time.h> #include <QtCore> #include <QKeyEvent> #include <QGridLayout> CandyWorld::CandyWorld(int w_count, int h_count):candyEatCount(0) { srand(time(0)); this->w_count = w_count*2+1; this->h_count = h_count*2+1; playerPosition = new QPoint(1,1); candyPosition = new QPoint(1,0); world = GenerateMaze(h_count,w_count); for(int x = 0; x < h_count; x++) world->push_back(QVector<int>(w_count)); (*world)[1][1] = 1; //Player while(*playerPosition == *candyPosition || (*world)[candyPosition->y()][candyPosition->x()] == -1) { candyPosition->setX(rand()%w_count); candyPosition->setY(rand()%h_count); } (*world)[candyPosition->y()][candyPosition->x()] = 2; } void CandyWorld::Update(int direction) { auto candyEat = false; auto oldPlayerPosition = *playerPosition; (*world)[playerPosition->y()][playerPosition->x()] = 0; (*world)[candyPosition->y()][candyPosition->x()] = 0; if(direction == 0) playerPosition->setX(playerPosition->x()-1); else if(direction == 1) playerPosition->setX(playerPosition->x()+1); else if(direction == 2) playerPosition->setY(playerPosition->y()-1); else if(direction == 3) playerPosition->setY(playerPosition->y()+1); if((*world)[playerPosition->y()][playerPosition->x()] == -1){ *playerPosition = oldPlayerPosition; //qDebug() << "WALL"; } while(*playerPosition == *candyPosition || (*world)[candyPosition->y()][candyPosition->x()] == -1) { candyPosition->setX(rand()%w_count); candyPosition->setY(rand()%h_count); candyEat = true; } if(candyEat)candyEatCount++; (*world)[playerPosition->y()][playerPosition->x()] = 1; (*world)[candyPosition->y()][candyPosition->x()] = 2; } QVector<QVector<int>>* CandyWorld::GenerateMaze(int height, int width) { { int output_height = height*2+1; int output_width = width*2+1; auto maze = new QVector<QVector<int>>(); for (int i = 0; i < output_height; ++i) { QVector<int> row; row.reserve(output_width); for (int j = 0; j < output_width; ++j) if ((i % 2 == 1) && (j % 2 == 1)) row.push_back(0); else if (((i % 2 == 1) && (j % 2 == 0) && (j != 0) && (j != output_width - 1)) || ((j % 2 == 1) && (i % 2 == 0) && (i != 0) && (i != output_height - 1))) row.push_back(0); else row.push_back(-1); maze->push_back(std::move(row)); } QVector<int> row_set; for (int i = 0; i < width; ++i) row_set.push_back(0); unsigned set = 1; std::random_device rd; std::mt19937 mt(rd()); std::uniform_int_distribution<int> dist(0, 2); for (int i = 0; i < height; ++i) { for (int j = 0; j < width; ++j) if (row_set[j] == 0) row_set[j] = set++; for (int j = 0; j < width - 1; ++j) { const auto right_wall = dist(mt); if ((right_wall == 1) || (row_set[j] == row_set[j + 1])) (*maze)[i * 2 + 1][j * 2 + 2] = -1; else { const auto changing_set = row_set[j + 1]; for (int l = 0; l < width; ++l) if (row_set[l] == changing_set) row_set[l] = row_set[j]; } } for (int j = 0; j < width; ++j) { const auto bottom_wall = dist(mt); unsigned int count_current_set = 0; for (int l = 0; l < width; ++l) if (row_set[j] == row_set[l]) count_current_set++; if ((bottom_wall == 1) && (count_current_set != 1)) (*maze)[i * 2 + 2][j * 2 + 1] = -1; } if (i != height - 1) { for (int j = 0; j < width; ++j) { int count_hole = 0; for (int l = 0; l < width; ++l) if ((row_set[l] == row_set[j]) && (*maze)[i * 2 + 2][l * 2 + 1] == 0) count_hole++; if (count_hole == 0) (*maze)[i * 2 + 2][j * 2 + 1] = 0; } for (int j = 0; j < width; ++j) if ((*maze)[i * 2 + 2][j * 2 + 1] == -1) row_set[j] = 0; } } for (int j = 0; j < width - 1; ++j) { if (row_set[j] != row_set[j + 1]) (*maze)[output_height - 2][j * 2 + 2] = 0; } return maze; } } CandyWorld::~CandyWorld() { delete world; delete playerPosition; delete candyPosition; } HackGameWidget::HackGameWidget(int mazeSize, int candyCount): QWidget(), mazeSize(mazeSize), candyLvl(0), candyCount(candyCount) { setStyleSheet("background: black"); setWindowTitle("HACK.EXE"); setWindowFlags(Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint); setGeometry(1080,400,500,500); } HackGameWidget::~HackGameWidget() { } void HackGameWidget::StartGame() { QGridLayout *mainLayout = new QGridLayout(); mainLayout->setSpacing(0); candyWorld = new CandyWorld(mazeSize,mazeSize); worldMatrix = candyWorld->world; int _w_size = mazeSize*2+1; int _h_size = mazeSize*2+1; //такие размеры нужны для работы с матрицей graphicsMatrix = new QVector<QVector<QWidget*>>(); for(int y = 0; y < _h_size; y++){ graphicsMatrix->push_back(QVector<QWidget*>()); for(int x = 0; x < _w_size; x++){ ((*graphicsMatrix)[y]).push_back(new QWidget(this)); mainLayout->addWidget((*graphicsMatrix)[y][x],y,x,1,1); ((*graphicsMatrix)[y])[x]->show(); } } this->setLayout(mainLayout); Update(); } void HackGameWidget::keyPressSlot(QKeyEvent *event) { } void HackGameWidget::Update() { for(int y = 0; y < mazeSize*2+1; y++) { for(int x = 0; x < mazeSize*2+1; x++) { if((*worldMatrix)[y][x] == 1) { ((*graphicsMatrix)[y])[x]->setStyleSheet("background-color: white;"); ((*graphicsMatrix)[y])[x]->setAutoFillBackground(true); ((*graphicsMatrix)[y])[x]->show(); } else if((*worldMatrix)[y][x] == 2) { ((*graphicsMatrix)[y])[x]->setStyleSheet("background-color: yellow;"); ((*graphicsMatrix)[y])[x]->setAutoFillBackground(true); ((*graphicsMatrix)[y])[x]->show(); } else if((*worldMatrix)[y][x] == -1) { ((*graphicsMatrix)[y])[x]->setStyleSheet("background-color: green;"); ((*graphicsMatrix)[y])[x]->setAutoFillBackground(true); ((*graphicsMatrix)[y])[x]->show(); } else { ((*graphicsMatrix)[y])[x]->setStyleSheet("background-color: black;"); ((*graphicsMatrix)[y])[x]->setAutoFillBackground(true); ((*graphicsMatrix)[y])[x]->show(); } } } //candyEatLabel->setText("Свинья съела " //+ QString::number(candyWorld->candyEatCount) //+ " конфет"); if(candyWorld->candyEatCount == candyCount) { parentChannel->succesHack(); this->close(); } } void HackGameWidget::keyPressEvent(QKeyEvent *event) { //qDebug() << "KEY PRESS"; if(event->key() == Qt::Key_A) candyWorld->Update(0); else if(event->key() == Qt::Key_D) candyWorld->Update(1); else if(event->key() == Qt::Key_W) candyWorld->Update(2); else if(event->key() == Qt::Key_S) candyWorld->Update(3); Update(); }
true
bc83f4ba9c20cd622ba25e70f35d8a4b89c02806
C++
SelvaBalasubramanian/SPOJ-Submissions
/ADDREV - Adding Reversed Numbers.cpp
UTF-8
1,234
2.953125
3
[]
no_license
/* http://www.spoj.com/problems/ADDREV/ Author : Selva Balasubramanian */ #include<iostream> #include<vector> using namespace std; vector<int>add(vector<int>a , vector<int>b){ vector<int>::reverse_iterator ait , bit , cit; vector<int>::iterator rit; ait = a.rbegin(); bit = b.rbegin(); int carry = 0; for(; bit != b.rend() ; ait++,bit++){ *ait = *ait + carry + *bit; int temp = *ait % 10; carry = *ait / 10; *ait = temp; } while(carry != 0){ if(ait == a.rend()){ rit = a.begin(); a.insert(rit , carry); } else *ait = *ait + carry; carry = *ait / 10; *ait %= 10; ait++; } return a; } int main(){ int t; cin>>t; while(t--){ vector<int>aa , bb; vector<int>::reverse_iterator rit; string a , b; cin>>a>>b; long int alen = a.length(); long int blen = b.length(); for(long int i = alen-1; i>=0 ; i--){aa.push_back(int(a[i]-'0')); } for(long int i = blen-1; i>=0 ; i--){bb.push_back(int(b[i]-'0')); } vector<int>sum ; if(alen>blen) sum = add(aa, bb); else sum = add(bb,aa); bool found = false; for(rit = sum.rbegin() ;rit != sum.rend(); rit++){ if(*rit != 0){ found= true; } if(found) cout<<*rit; } cout<<endl; } return 0; }
true
074b52643a99ea4624bc459db05c5564853fcee0
C++
cash2one/mygametool
/Client/Common/engine.h
GB18030
1,576
2.578125
3
[]
no_license
//******************************************************************************* // Ȩ(C) 2012 All right reserved // ļ : engine.h // ǰ汾 : 1.0.0.1 // : fuzhun (339448261@qq.com) // : 20121212 // ˵ : //******************************************************************************* #pragma once #include <time.h> enum EngineLogLevel { LogLevelDebug, LogLevelTest, LogLevelRelease, }; inline void __Engine_WriteLog(const char* szString) { time_t ti = time(NULL); tm* t = localtime(&ti); char szTime[MAX_PATH] = {0}; strftime(szTime, MAX_PATH, "[%y-%m-%d %H:%m:%S]", t); #if defined _DEBUG std::cout<< szTime <<std::endl; #endif } inline void Engine_WriteLog(const char* szString, EngineLogLevel level = LogLevelDebug) { #ifdef _DEBUG __Engine_WriteLog(szString); #else if(level > LogLevelTest) __Engine_WriteLog(szString); #endif } inline void Engine_WriteLogV(const char* szFmt, va_list argptr, EngineLogLevel level = LogLevelDebug) { char szString[1024] = {0}; _vsnprintf(szString, 1024, szFmt, argptr); szString[1023] = 0; Engine_WriteLog(szString, level); } //debug inline void System_LogDebug(const char* szFmt, ...) { #ifdef _DEBUG va_list args; va_start( args, szFmt); Engine_WriteLogV(szFmt, args, LogLevelDebug); va_end(args); #endif } //release inline void System_LogRelease(const char* szFmt, ...) { va_list args; va_start( args, szFmt); Engine_WriteLogV(szFmt, args, LogLevelDebug); va_end(args); }
true
0dc9ab68785cb342d3b6fd046137eb9558ad86cb
C++
bolidezhang/socketlite
/include/SL_Utility_Memory.h
GB18030
3,510
2.75
3
[ "BSD-2-Clause" ]
permissive
#ifndef SOCKETLITE_UTILITY_MEMORY_H #define SOCKETLITE_UTILITY_MEMORY_H #include <cstring> #include "SL_Config.h" class SL_Utility_Memory { public: SL_Utility_Memory() { } ~SL_Utility_Memory() { } //ڴ濽 //: window7-32 vc2010 cpu: 4*i5-2310 memory: 4G: // 1)Сڴʱ, 8ֵֽ,; // 2)ڴʱ, 8ֵֽ,ܷ½;ڴ256ʱ,ֱӵ׼memcpy. // linux: // 1)ܿܺЩ,ҲܲЩ(ʹǰ,лϸ) // 2)centos6.3 x86-64 kernel:2.6.32 gcc:4.4.6 cpu:4*i5-2310 memory:4G 8ֵֽ // 3)centos7.0.1406 x86-64 kernel:3.10.0 gcc:4.8.2 cpu:4*i5-3330S memory:8G 8ֵֽ ׼memcpy Բ. static void* memcpy(void *dest, const void *src, size_t n); //ڴ static void memclear(void *dest, size_t n); //ڴȽ static inline int memcmp(const void *s1, const void *s2, size_t n) { return std::memcmp(s1, s2, n); } //ڴֵ //һʵַʽ: Ԥȼ 8ֵֽ(ÿֽڶcֵ) // 4ֵֽ(ÿֽڶcֵ) // 2ֵֽ(ÿֽڶcֵ) static inline void* memset(void *dest, int c, size_t n) { return std::memset(dest, c, n); } static inline void* memmove(void *dest, const void *src, size_t n) { return std::memmove(dest, src, n); } }; #ifdef SOCKETLITE_OS_WINDOWS #define SL_MEMCPY(dest, src, n) std::memcpy(dest, src, n) #define SL_MEMCLEAR(dest, n) std::memset(dest, 0, n) #define SL_MEMCMP(s1, s2, n) std::memcmp(s1, s2, n) #define SL_MEMSET(dest, c, n) std::memset(dest, c, n) #define SL_MEMMOVE(dest, src, n) std::memmove(dest, src, n) #define sl_memcpy(dest, src, n) SL_Utility_Memory::memcpy(dest, src, n) #define sl_memclear(dest, n) SL_Utility_Memory::memclear(dest, n) #define sl_memcmp(s1, s2, n) std::memcmp(s1, s2, n) #define sl_memset(dest, c, n) std::memset(dest, c, n) #define sl_memmove(dest, src, n) std::memmove(dest, src, n) #else #define SL_MEMCPY(dest, src, n) std::memcpy(dest, src, n) #define SL_MEMCLEAR(dest, n) std::memset(dest, 0, n) #define SL_MEMCMP(s1, s2, n) std::memcmp(s1, s2, n) #define SL_MEMSET(dest, c, n) std::memset(dest, c, n) #define SL_MEMMOVE(dest, src, n) std::memmove(dest, src, n) //SL_Utility_Memory::memcpyios¿ܻ, //ڷwindowsҪSOCKETLITE_USE_CUSTOM_MEMCPYsl_memcpyʵΪSL_Utility_Memory::memcpy #ifdef SOCKETLITE_USE_CUSTOM_MEMCPY #define sl_memcpy(dest, src, n) SL_Utility_Memory::memcpy(dest, src, n) #define sl_memclear(dest, n) SL_Utility_Memory::memclear(dest, n) #else #define sl_memcpy(dest, src, n) std::memcpy(dest, src, n) #define sl_memclear(dest, n) std::memset(dest, 0, n) #endif #define sl_memcmp(s1, s2, n) std::memcmp(s1, s2, n) #define sl_memset(dest, c, n) std::memset(dest, c, n) #define sl_memmove(dest, src, n) std::memmove(dest, src, n) #endif #endif
true
23629bf0cac831ed2abf34a03e9e8a50bc241ab7
C++
albertoavs06/SisOp-UFPB
/src/projeto1_CiceroMarcelo_11121217.cpp
UTF-8
7,769
2.640625
3
[]
no_license
// Tempo de retorno: tempo no qual o processo espera para ser finalizado (espera + execução) // Tempo de resposta: tempo esperando para iniciar execução; // Tempo de espera: tempo gasto na fila de prontos; // Para executar, fazer uso do CAT // EXEMPLO: cat entrada.txt | ./projeto2 // Espera e resposta so sao diferentes em algoritmos de uso compartilhado, nesse exemplo, apenas no RR // Nos demais, resposta e espera serao iguais // Cicero Marcelo Louro Leite // Matricula 11121217 // Universidade Federal da Paraiba // Ciencia da Computacao - Sistemas Operacionais - Trabalho 1 #include <iostream> #include <fstream> #include <unistd.h> #include <vector> #include <cstdlib> using namespace std; #define quantum 2 struct Process { double ent; double dur; bool done; double rt; int esp, ret; }; /* ORDENA POR CHEGADA*/ void selectionChegada(vector<Process>& procVec, int tam) { int pos_min,ent,dur,rt,esp,ret; int size=tam; for (int i=0; i < tam-1; i++) { pos_min = i; for (int j=i+1; j < tam; j++) { if (procVec[j].ent < procVec[pos_min].ent) pos_min=j; } if (pos_min != i) { ent = procVec[i].ent; dur = procVec[i].dur; rt = procVec[i].rt; esp = procVec[tam].esp; ret = procVec[tam].ret; procVec[i].ent = procVec[pos_min].ent; procVec[i].dur = procVec[pos_min].dur; procVec[i].rt = procVec[pos_min].rt; procVec[i].esp = procVec[pos_min].esp; procVec[i].ret = procVec[pos_min].ret; procVec[pos_min].ent = ent; procVec[pos_min].dur = dur; procVec[pos_min].rt = rt; procVec[pos_min].esp = esp; procVec[pos_min].ret = ret; } } }; // /* >>>>>> FUNCTION FCFS <<<<<<< */ // int fcfs (vector<Process>& procVec, int tam) { double rettot = 0, esptot = 0, reptot = 0; int tempo=0,espera=0,retorno=0; for (int i = 0; i<tam; i++) { if (procVec[i].ent<=tempo) { esptot = esptot + (tempo-procVec[i].ent); espera = tempo-procVec[i].ent; rettot += espera + procVec[i].dur; tempo += procVec[i].dur; } else { rettot += procVec[i].dur; tempo = procVec[i].ent+procVec[i].dur; } //std::cout << i << std::endl; //std::cout << "espera total " << esptot << std::endl; // CALCULAR MEDIA DA ESPERA //std::cout << "retorno total " << retorno << std::endl; // CALCULAR MEDIA DE RETORNO } std::cout.precision(5); std::cout << "FCFS " << rettot/tam << /*" Media espera*/" " << esptot/tam << " " << esptot/tam << std::endl; } // /* >>>>>> FUNCTION SJF <<<<<<< */ // int proximoPros(vector<Process>& procVec, int tam, int tempo) { int prox=-1, maxAtual=9999; for (int i=0; i<tam; i++) { if (procVec[i].ent <= tempo && procVec[i].done==false) // verifica se ja ta na fila e se ja foi executado { if (procVec[i].dur < maxAtual) { prox=i; maxAtual = procVec[i].dur; //std::cout << "proximo atual sera " << prox << " de duracao " << procVec[i].dur << std::endl; //std::cout << "tempo de execucao = " << tempo << std::endl; } } } return prox; } int sjf (vector<Process>& procVec, int tam) { double rettot = 0, esptot = 0, reptot = 0; int tempo=0,espera=0,retorno=0; int prox = -1; int tam2=tam; for (int i=0; i<tam2; i++) { prox = proximoPros(procVec, tam, tempo); if (prox >= 0) { //std::cout << prox << " executado" << std::endl; procVec[prox].done = true; procVec[prox].esp = tempo-procVec[prox].ent; esptot+=procVec[prox].esp; procVec[prox].ret=procVec[prox].esp+procVec[prox].dur; rettot = rettot + procVec[prox].ret; tempo = tempo + procVec[prox].dur; //rettot = rettot + procVec[prox].ent + procVec[prox].dur - tempo; prox = -1; } else { //std::cout << "nenhum entrou" << std::endl; tam2++; tempo+=1; } } std::cout.precision(5); std::cout << "SJF " << rettot/tam << /*" Media espera SJF*/" " << esptot/tam << " " << esptot/tam << std::endl; } // /* >>>>>> FUNCTION RR <<<<<<< */ // int rr (vector<Process>& procVec, int tam) { int restante = tam; double resposta=0, retorno=0, espera=0, tempo=0; int fg=0, i=0, laco=0; while(i<tam) { for (int j=0; j<tam;) { //verifica se o processo atual ja terminou a execucao if (procVec[j].done==true) { j++; } //verifica se o processo atual vai terminar a execucao agora else if(procVec[j].rt<=quantum && procVec[j].rt>0 && procVec[j].ent<=tempo) { if (procVec[j].rt==procVec[j].dur) { resposta=resposta+tempo-procVec[j].ent; } //std::cout << "***executou " << procVec[j].rt << " do processo " << j << std::endl; tempo+=procVec[j].rt; procVec[j].esp=tempo-procVec[j].ent-procVec[j].dur; procVec[j].ret=procVec[j].dur+procVec[j].esp; procVec[j].rt = procVec[j].rt - quantum; fg = 1; i++; procVec[j].done = true; //std::cout << "processo finalizado " << j << std::endl; //std::cout << "tempo executando " << tempo << std::endl; j++; } //verifica se o processo atual ainda nao terminou e nem vai terminar agora else if (procVec[j].rt > quantum && procVec[j].ent<=tempo) { if (procVec[j].rt==procVec[j].dur) { resposta=resposta+tempo-procVec[j].ent; } tempo+=quantum; //std::cout << "***executou q" << quantum << " do processo " << j << std::endl; //std::cout << "tempo executando " << tempo << std::endl; procVec[j].rt = procVec[j].rt - quantum; //std::cout << "falta " << procVec[j].rt << " do processo " << j << std::endl; j++; fg = 1; } //verifica se nesse tempo nao ha nenhum processo querendo executar else if (laco>0) { //std::cout << "entrou no break" << std::endl; break; } //verifica se o processo atual ja entra em execucao ou ainda nao else if (procVec[j].ent > tempo ) { //std::cout << "processo " << j << " ainda nao entra" << std::endl; j=0; laco++; } } //Verifica se nennum processo entrou, se nao, aumenta 1 no tempo e volta a verificar if (fg==0) { //std::cout << "nao entra ngm" << std::endl; tempo++; //std::cout << "tempo " << tempo << std::endl; } fg=0; laco=0; } //std::cout << tempo << std::endl; for (int aux=0; aux<tam; aux++) { //std::cout << aux << "espera " << procVec[aux].esp << " : retorno " << procVec[aux].ret << std::endl; retorno=retorno+procVec[aux].ret; espera=espera+procVec[aux].esp; } std::cout.precision(5); std::cout << "RR " << retorno/tam << /*" Media resposta RR*/" " << resposta/tam << /*" Media espera RR*/" " << espera/tam << std::endl; } // /* >>>>>>> MAIN <<<<<<< */ // int main() { std::vector<Process> procVec; // cria vector de processos double x, y; int tam=0; while(std::cin >> x >> y) // le do arquivo pelo cat cmd //while (tam<5) { procVec.push_back(Process()); procVec[tam].ent = x; procVec[tam].dur = y; procVec[tam].done = false; procVec[tam].esp = 0; procVec[tam].ret = 0; tam++; } for (int j=0; j<tam; j++) { // std::cout << procVec[j].ent << " e " << procVec[j].dur << std::endl; procVec[j].rt = procVec[j].dur; } selectionChegada(procVec, tam); // for (int j=0; j<tam; j++) // { // std::cout << procVec[j].ent << " " << procVec[j].dur << std::endl; // } fcfs(procVec, tam); sjf(procVec, tam); for (int aux=0; aux<tam; aux++) { procVec[aux].done = false; procVec[aux].ret = 0; procVec[aux].esp = 0; } rr(procVec, tam); }
true
14d172bedc03e3186c977a175f91758ce03d4cb0
C++
ShinBei/C_pratice
/buythings.cpp
BIG5
3,516
3.0625
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <conio.h> struct product { int id; char name[10]; int num; int sale; int cost; }; int cal(struct product *produce, int i) { int id, num; int money = 0; char keep = 'y'; do { printf("пJniXإ<1 2R>\n"); scanf("%d", &i); if (i == 1) { printf("пJnذӫ~id:\n"); scanf("%d", &id); printf("пJnhֶq:\n"); scanf("%d", &num); switch (id){ case 1: if (num > produce[0].num) { printf("\n"); printf("ƶq\n"); printf("\n"); } else { produce[0].num = produce[0].num - num; money += num*produce[0].sale; } break; case 2: if (num > produce[1].num) { printf("\n"); printf("ƶq\n"); printf("\n"); } else { produce[1].num = produce[1].num - num; money += num*produce[1].sale; } break; case 3: if (num > produce[2].num) { printf("\n"); printf("ƶq\n"); printf("\n"); } else { produce[2].num = produce[2].num - num; money += num*produce[2].sale; } break; } } else { printf("пJnRذӫ~id:\n"); scanf("%d", &id); printf("пJnRhֶq:\n"); scanf("%d", &num); if (money < num*produce[id - 1].cost) { printf("\n"); printf("========\n"); printf("\n"); } else { switch (id){ case 1: produce[0].num = produce[0].num + num; money -= num*produce[0].cost; break; case 2: produce[1].num = produce[1].num + num; money -= num*produce[1].cost; break; case 3: produce[2].num = produce[2].num + num; money -= num*produce[2].cost; break; } } } printf("====ثeӫ~ƶq====\n%d.%s:%d\n%d.%s:%d\n%d.%s:%d\n", produce[0].id, produce[0].name, produce[0].num, produce[1].id, produce[1].name, produce[1].num, produce[2].id, produce[2].name, produce[2].num); printf("====ثeӫ~/====\n%d.%s:%d/%d\n%d.%s:%d/%d\n%d.%s:%d/%d\n", produce[0].id, produce[0].name, produce[0].sale, produce[0].cost, produce[1].id, produce[1].name, produce[1].sale, produce[1].cost, produce[2].id, produce[2].name, produce[2].sale, produce[2].cost); printf("ثeJ:%d\n", money); printf("O_n~(y/n):\n"); keep = getch(); printf("%c\n", keep); } while (keep == 'y'); return 0; } int main(void) { product *produce; produce = (product*)malloc(sizeof(product)* 3); produce[0].num = 50; produce[1].num = 60; produce[2].num = 30; strcpy(produce[0].name, "milk"); strcpy(produce[1].name, "bread"); strcpy(produce[2].name, "egg"); produce[0].id = 1; produce[1].id = 2; produce[2].id = 3; printf("====ثeӫ~ƶq====\n%d.%s:%d\n%d.%s:%d\n%d.%s:%d\n", produce[0].id, produce[0].name, produce[0].num, produce[1].id, produce[1].name, produce[1].num, produce[2].id, produce[2].name, produce[2].num); produce[0].sale = 30; produce[1].sale = 70; produce[2].sale = 20; produce[0].cost = 20; produce[1].cost = 40; produce[2].cost = 10; printf("====ثeӫ~/====\n%d.%s:%d/%d\n%d.%s:%d/%d\n%d.%s:%d/%d\n", produce[0].id, produce[0].name, produce[0].sale, produce[0].cost, produce[1].id, produce[1].name, produce[1].sale, produce[1].cost, produce[2].id, produce[2].name, produce[2].sale, produce[2].cost); int i = 0; cal(produce, i); system("pause"); return 0; }
true
31e3b28ec106026dce66ecfb4e6000803d99977c
C++
ifkas/newsfeeder
/shareddblib/src/FeedController.cpp
UTF-8
10,648
2.984375
3
[]
no_license
#include "FeedController.h" #include <cppconn/prepared_statement.h> #include <sstream> using namespace std; using namespace sql; using namespace nfdb; /** * Initialising Constructor for FeedController, opens a database connection */ FeedController::FeedController() { dbc = new DatabaseController(); conn = dbc->Connect(); } /** * Deallocates any dynamic memory and closes the database connection */ FeedController::~FeedController() { delete dbc; } /** * Find the feed with that id */ Feed* FeedController::GetFeedById(int id) { PreparedStatement* stmt = conn->prepareStatement("SELECT * FROM feeds WHERE id = ?"); stmt->setInt(1, id); ResultSet* rs = stmt->executeQuery(); delete stmt; if(rs != NULL) { while(rs->next()) { //If there is a matching content placeholder return it Feed* f = GenerateFeed(*rs); delete rs; return f; } } else { return NULL; } return NULL; } /** * Find all feeds that are contained within that CPH */ vector<Feed*> FeedController::GetFeedsByCphId(int cphId) { PreparedStatement* stmt = conn->prepareStatement("SELECT feeds.id AS id, feeds.url AS url, feeds.name AS name, feeds.frequency AS frequency, feeds.lastupdate AS lastupdate, feeds.category AS category, feeds.type AS TYPE , feeds.favicon AS favicon FROM feeds INNER JOIN cph_feeds ON feeds.id = cph_feeds.feedid WHERE cph_feeds.cphid = ?"); stmt->setInt(1, cphId); //JOIN all relevant tables, find by cphId ResultSet* rs = stmt->executeQuery(); vector<Feed*> feeds; if(rs != NULL) { while(rs->next()) { //Add all results to a vector feeds.push_back(GenerateFeed(*rs)); } } delete stmt; delete rs; return feeds; } /** * Find all feeds that belong to the user of that username */ vector<Feed*> FeedController::GetFeedsByUsername(string username) { PreparedStatement* stmt = conn->prepareStatement("SELECT feeds.id AS id, feeds.url AS url, feeds.name AS name, feeds.frequency AS frequency, feeds.lastupdate AS lastupdate, feeds.category AS category, feeds.type AS TYPE , feeds.favicon AS favicon FROM feeds INNER JOIN userfeeds ON feeds.id = userfeeds.feedid WHERE userfeeds.username = ?"); //Join onto the user table stmt->setString(1, username); ResultSet* rs = stmt->executeQuery(); vector<Feed*> feeds; if(rs != NULL) { while(rs->next()) { //Add all results to a vector feeds.push_back(GenerateFeed(*rs)); } } delete stmt; delete rs; return feeds; } /** * Find all feeds */ vector<Feed*> FeedController::GetAllFeeds() { Statement* stmt = conn->createStatement(); ResultSet* rs = stmt->executeQuery("SELECT * FROM feeds"); vector<Feed*> feeds; if(rs != NULL) { while(rs->next()) { //Add all results to a vector feeds.push_back(GenerateFeed(*rs)); } } delete stmt; delete rs; return feeds; } /** * Get all of the feeds which are newer than the passed id */ vector<Feed*> FeedController::GetNewFeeds(int id) { PreparedStatement* stmt = conn->prepareStatement("SELECT * FROM feeds WHERE id > ?"); stmt->setInt(1, id); //Query for freshly added feeds (i.e. the ID is later than the current one) ResultSet* rs = stmt->executeQuery(); vector<Feed*> feeds; if(rs != NULL) { while(rs->next()) { feeds.push_back(GenerateFeed(*rs)); } } delete stmt; delete rs; return feeds; } /** * Find all feeds which are due to be crawled again */ vector<QueueItem*> FeedController::GetQueueFeeds() { Statement* stmt = conn->createStatement(); ResultSet* rs = stmt->executeQuery("SELECT id, frequency, type FROM feeds"); vector<QueueItem*> feeds; if(rs != NULL) { while(rs->next()) { //Get all feeds to populate the queue feeds.push_back(GenerateQueueItem(*rs)); } } delete stmt; delete rs; return feeds; } /** * Insert the feed into the database */ int FeedController::AddFeed(Feed& feed) { PreparedStatement* stmt = conn->prepareStatement("INSERT INTO feeds (url, name, frequency, lastupdate, category, type, favicon) VALUES (?,?,?,?,?,?,?)"); stmt->setString(1, feed.url); stmt->setString(2, feed.name); stmt->setInt(3, feed.frequency); //Allow for nullable values if(feed.lastUpdate != NULL) { stmt->setString(4, feed.lastUpdate->ExportToMySQL()); } else { stmt->setNull(4, 0); } if(feed.category != NULL) { stmt->setString(5, *feed.category); } else { stmt->setNull(5, 0); } if(feed.type != NULL) { stmt->setInt(6, *feed.type); } else { stmt->setNull(6, 0); } if(feed.favIcon != NULL) { istringstream tempBlob(string(feed.favIcon, feed.iconSize)); stmt->setBlob(7, &tempBlob); } else { stmt->setNull(7, 0); } //Insert stmt->executeUpdate(); delete stmt; //Perform another query to get the Id of the inserted row Statement* lastStmt = conn->createStatement(); ResultSet* rs = lastStmt->executeQuery("SELECT LAST_INSERT_ID()"); if(rs != NULL) { while(rs->next()) { int lastId = rs->getInt("LAST_INSERT_ID()"); delete rs; delete lastStmt; return lastId; } } else { delete lastStmt; return -1; } return -1; } /** * Update the relevant feed in the database */ void FeedController::UpdateFeed(Feed& feed) { PreparedStatement* stmt = conn->prepareStatement("UPDATE feeds SET url = ?, name = ?, frequency = ?, lastupdate = ?, category = ?, type = ?, favIcon = ? WHERE id = ?"); //Populate the query values based on input from the passed feed stmt->setString(1, feed.url); stmt->setString(2, feed.name); stmt->setInt(3, feed.frequency); //If the value is null, set it to the same value it is currently if(feed.lastUpdate != NULL) { stmt->setString(4, feed.lastUpdate->ExportToMySQL()); } else { stmt->setNull(4, 0); } if(feed.category != NULL) { stmt->setString(5, *feed.category); } else { stmt->setNull(5, 0); } if(feed.type != NULL) { stmt->setInt(6, *feed.type); } else { stmt->setNull(6, 0); } if(feed.favIcon != NULL) { istringstream tempBlob(string(feed.favIcon, feed.iconSize)); stmt->setBlob(7, &tempBlob); } else { stmt->setNull(7, 0); } stmt->setInt(8, feed.id); stmt->executeUpdate(); delete stmt; } /** * Update the relevant feed in the database, NULLs passed if that parameter is not to be updated */ void FeedController::UpdateFeed(int id, string* url, string* name, int* frequency, nfrd::misc::DateTime* lastUpdate, string* category, int* type, char* favIcon, int* iconSize) { //Generate the query based on the provided parameters string query = "UPDATE users SET"; if(url != NULL) { query += " url = ? "; } else { query += " url = url"; } if(name != NULL) { query += ", name = ?"; } else { query += ", name = name"; } if(frequency != NULL) { query += ", frequency = ?"; } else { query += ", frequency = frequency"; } if(lastUpdate != NULL) { query += ", lastupdate = ?"; } else { query += ", lastupdate = lastupdate"; } if(category != NULL) { query += ", category = ?"; } else { query += ", category = category"; } if(type != NULL) { query += ", type = ?"; } else { query += ", type = type"; } if(favIcon != NULL) { query += ", favIcon = ?"; } else { query += ", favIcon = favIcon"; } query += " WHERE id = ?"; PreparedStatement* stmt = conn->prepareStatement(query); int param = 1; //Populate the query values if(url != NULL) { stmt->setString(param, *url); param++; } if(name != NULL) { stmt->setString(param, *name); param++; } if(frequency != NULL) { stmt->setInt(param, *frequency); param++; } if(lastUpdate != NULL) { stmt->setString(param, lastUpdate->ExportToMySQL()); param++; } if(category != NULL) { stmt->setString(param, *category); param++; } if(type != NULL) { stmt->setInt(param, *type); param++; } if(favIcon != NULL) { istringstream tempBlob(string(favIcon, *iconSize)); stmt->setBlob(param, &tempBlob); param++; } stmt->setInt(param, id); stmt->executeUpdate(); delete stmt; } /** * Delete the feed from the database */ void FeedController::RemoveFeed(int id) { PreparedStatement* stmt = conn->prepareStatement("DELETE FROM feeds WHERE id = ?"); stmt->setInt(1, id); //Delete by ID stmt->executeUpdate(); delete stmt; } /** * Generate a feed based on the data in a result set row */ Feed* FeedController::GenerateFeed(ResultSet& rs) { Feed* f = new Feed(); //Populate the new feed based on the result set f->id = rs.getInt("id"); f->url = rs.getString("url"); f->name = rs.getString("name"); f->frequency = rs.getInt("frequency"); if(!rs.isNull("lastupdate")) { f->lastUpdate = new nfrd::misc::DateTime(); f->lastUpdate->ImportFromMySQL(rs.getString("lastupdate")); } if(!rs.isNull("category")) { f->category = new string(rs.getString("category")); } if(!rs.isNull("type")) { f->type = new int(rs.getInt("type")); } if(!rs.isNull("favicon")) { //Get blob and convert to char* istream* is = rs.getBlob("favicon"); is->seekg(0, ios::end); int length = (int)is->tellg(); is->seekg(0, ios::beg); char* buffer = new char[length]; is->read(buffer, length); f->favIcon = buffer; f->iconSize = length; delete is; } return f; } /** * Generate a queue item based on the data in a result set row */ QueueItem* FeedController::GenerateQueueItem(ResultSet& rs) { QueueItem* q = new QueueItem(); //Create new queue item based on result q->id = rs.getInt("id"); q->frequency = rs.getInt("frequency"); if(!rs.isNull("type")) { q->type = new int(rs.getInt("type")); } q->numUsers = GetNumberOfFeedUsers(q->id); return q; } /** * Get the number of users currently subscribed to that feed */ int FeedController::GetNumberOfFeedUsers(int id) { //JOIN to users table and query for count of distinct users using this feed PreparedStatement* stmt = conn->prepareStatement("SELECT COUNT(DISTINCT users.username) FROM feeds JOIN cph_feeds ON feeds.id = cph_feeds.feedid JOIN cph ON cph.id = cph_feeds.cphid JOIN sheets ON sheets.id = cph.sheetid JOIN users ON users.username = sheets.username WHERE feeds.id = ?"); stmt->setInt(1, id); ResultSet* rs = stmt->executeQuery(); delete stmt; if(rs != NULL) { while(rs->next()) { //Get count and return int num = rs->getInt("COUNT(DISTINCT users.username)"); delete rs; return num; } } else { return 0; } return 0; } /** * Touch the feed, setting lastupdate to now */ void FeedController::UpdateLastUpdateTime(int feedid) { PreparedStatement* stmt = conn->prepareStatement("UPDATE feeds SET lastupdate = now() WHERE id = ?"); //Update the lastupdate time to NOW stmt->setInt(1, feedid); stmt->executeUpdate(); delete stmt; }
true
f22bdc219699d65ced4feed34f2f2723e0ee71c6
C++
atemple84/DataStructureAlgorithms
/GraphLesson.cpp
UTF-8
2,285
3.3125
3
[]
no_license
#include <iostream> #include <queue> #include "GraphLesson.h" vector<vector<int> > adjacencyMatrix() { int n, e; cin >> n >> e; vector<vector<int> > matrix(n, vector<int>(n, 0)); for (int i = 1; i <= e; ++i) { int fv, sv; cin >> fv >> sv; matrix[fv][sv] = 1; matrix[sv][fv] = 1; } return matrix; } void printGraphDFS(vector<vector<int> > graph, int sv, vector<bool>& visited) { cout << sv << endl; visited[sv] = true; int n = graph.size(); for (int i = 0; i < n; ++i) { if (graph[sv][i] == 1 && visited[i] == false) { printGraphDFS(graph, i, visited); } } } void printGraphBFS(vector<vector<int> > graph, int sv, vector<bool>& visited) { queue<int> children; children.push(sv); visited[sv] = true; while (!children.empty()) { int front = children.front(); children.pop(); cout << front << endl; for (int i = 0; i < graph.size(); ++i) { if (graph[front][i] && !visited[i]) { children.push(i); visited[i] = true; } } } } void DFS(vector<vector<int> > matrix) { vector<bool> visited(matrix.size(), false); for (int i = 0; i < matrix.size(); ++i) { if (!visited[i]) { printGraphDFS(matrix, i, visited); } } } void BFS(vector<vector<int> > matrix) { vector<bool> visited(matrix.size(), false); for (int i = 0; i < matrix.size(); ++i) { if (!visited[i]) { printGraphBFS(matrix, i, visited); } } } int ComponentCountDFS(vector<vector<int>> matrix) { int count = 0; vector<bool> visited(matrix.size(), false); for (int i = 0; i < matrix.size(); ++i) { if (!visited[i]) { ++count; printGraphDFS(matrix, i, visited); } } return count; } int ComponentCountBFS(vector<vector<int>> matrix) { int count = 0; vector<bool> visited(matrix.size(), false); for (int i = 0; i < matrix.size(); ++i) { if (!visited[i]) { ++count; printGraphBFS(matrix, i, visited); } } return count; }
true
0c20c3b0e6033214c994300c3229278fcee795c9
C++
RebeccaCheng910/CHAMBER-CRAWLER
/include/player.h
UTF-8
733
2.84375
3
[]
no_license
#ifndef _PLAYER_H_ #define _PLAYER_H_ #include "character.h" #include <string> #include <memory> class Enemy; // abstract class class Player: public Character { int goldValue; std::string action; bool isDead = false; protected: int maxHP; public: Player(); // constructor // int getHP() override; // int getAtk() override; // int getDef() override; std::string getAction(); void setAction(std::string); void setHP(int n); virtual int getGold(); // goblin needs to overload virtual void setGold(int); virtual bool getStatus(); virtual void beAttackedBy(const std::shared_ptr<Enemy> &); virtual std::shared_ptr<Player> getBase() = 0; virtual ~Player() = 0; // to make Player abstract }; #endif
true
17af4849a49594de1a29a365f89ed7bf94052154
C++
RoboMark9/ocs2
/ocs2_thirdparty/include/cppad/cg/smart_containers.hpp
UTF-8
6,683
2.953125
3
[ "GPL-3.0-only", "EPL-1.0", "EPL-2.0", "GPL-2.0-only", "BSD-3-Clause" ]
permissive
#ifndef CPPAD_CG_SMART_CONTAINERS_INCLUDED #define CPPAD_CG_SMART_CONTAINERS_INCLUDED /* -------------------------------------------------------------------------- * CppADCodeGen: C++ Algorithmic Differentiation with Source Code Generation: * Copyright (C) 2014 Ciengis * * CppADCodeGen is distributed under multiple licenses: * * - Eclipse Public License Version 1.0 (EPL1), and * - GNU General Public License Version 3 (GPL3). * * EPL1 terms and conditions can be found in the file "epl-v10.txt", while * terms and conditions for the GPL3 can be found in the file "gpl3.txt". * ---------------------------------------------------------------------------- * Author: Joao Leal */ namespace CppAD { namespace cg { /** * Smart vector of pointers. * Deletes all vector values on destruction. */ template<class Base> class SmartVectorPointer { public: using iterator = typename std::vector<Base*>::iterator; using const_iterator = typename std::vector<Base*>::const_iterator; using reverse_iterator = typename std::vector<Base*>::reverse_iterator; using const_reverse_iterator = typename std::vector<Base*>::const_reverse_iterator; std::vector<Base*> v; inline SmartVectorPointer() { } inline SmartVectorPointer(size_t size) : v(size) { } inline SmartVectorPointer(std::vector<Base*>& v_) { v.swap(v_); } inline size_t size() const { return v.size(); } inline bool empty() const { return v.empty(); } inline void reserve(size_t n) { v.reserve(n); } inline void push_back(Base* x) { v.push_back(x); } inline Base* operator[](size_t n) const { return v[n]; } inline Base*& operator[](size_t n) { return v[n]; } inline iterator begin() { return v.begin(); } inline const_iterator begin() const { return v.begin(); } inline iterator end() { return v.end(); } inline const_iterator end() const { return v.end(); } inline reverse_iterator rbegin() { return v.rbegin(); } inline const_reverse_iterator rbegin() const { return v.rbegin(); } inline reverse_iterator rend() { return v.rend(); } inline const_reverse_iterator rend() const { return v.rend(); } inline std::vector<Base*> release() { std::vector<Base*> v2; v2.swap(v); return v2; } inline virtual ~SmartVectorPointer() { for (size_t i = 0; i < v.size(); i++) { delete v[i]; } } }; /** * Smart set of pointers. * Deletes all set values on destruction. */ template<class Base> class SmartSetPointer { public: using iterator = typename std::set<Base*>::iterator; std::set<Base*> s; inline SmartSetPointer() { } inline SmartSetPointer(std::set<Base*>& s_) { s.swap(s_); } inline size_t size() const { return s.size(); } inline bool empty() const { return s.empty(); } inline iterator begin() const { return s.begin(); } inline iterator end() const { return s.end(); } inline std::pair<iterator, bool> insert(Base* x) { return s.insert(x); } inline void erase(iterator pos) { s.erase(pos); } inline size_t erase(Base* x) { return s.erase(x); } inline std::set<Base*> release() { std::set<Base*> s2; s2.swap(s); return s2; } inline virtual ~SmartSetPointer() { typename std::set<Base*>::const_iterator it; for (it = s.begin(); it != s.end(); ++it) { delete *it; } } }; /** * Smart set of pointers. * Deletes all set values on destruction. */ template<class Base> class SmartListPointer { public: using iterator = typename std::list<Base*>::iterator; using const_iterator = typename std::list<Base*>::const_iterator; std::list<Base*> l; inline SmartListPointer() { } inline SmartListPointer(const std::set<Base*>& l_) { l.swap(l_); } inline size_t size() const { return l.size(); } inline bool empty() const { return l.empty(); } inline void push_front(Base* x) { l.push_front(x); } inline void pop_front() { l.pop_front(); } inline void push_back(Base* x) { l.push_back(x); } inline void pop_back() { l.pop_back(); } inline iterator begin() { return l.begin(); } inline const_iterator begin() const { return l.begin(); } inline iterator end() { return l.end(); } inline const_iterator end() const { return l.end(); } inline std::list<Base*> release() { std::list<Base*> l2; l2.swap(l); return l2; } inline virtual ~SmartListPointer() { typename std::list<Base*>::const_iterator it; for (it = l.begin(); it != l.end(); ++it) { delete *it; } } }; template<class Key, class Value> class SmartMapValuePointer { public: using iterator = typename std::map<Key, Value*>::iterator; using const_iterator = typename std::map<Key, Value*>::const_iterator; using reverse_iterator = typename std::map<Key, Value*>::reverse_iterator; using const_reverse_iterator = typename std::map<Key, Value*>::const_reverse_iterator; std::map<Key, Value*> m; inline size_t size() const { return m.size(); } inline bool empty() const { return m.empty(); } inline iterator begin() { return m.begin(); } inline const_iterator begin() const { return m.begin(); } inline iterator end() { return m.end(); } inline const_iterator end() const { return m.end(); } inline reverse_iterator rbegin() { return m.rbegin(); } inline const_reverse_iterator rbegin() const { return m.rbegin(); } inline reverse_iterator rend() { return m.rend(); } inline const_reverse_iterator rend() const { return m.rend(); } inline Value*& operator[](const Key& key) { return m[key]; } std::map<Key, Value*> release() { std::map<Key, Value*> m2; m2.swap(m); return m2; } inline virtual ~SmartMapValuePointer() { typename std::map<Key, Value*>::const_iterator it; for (it = m.begin(); it != m.end(); ++it) { delete it->second; } } }; } // END cg namespace } // END CppAD namespace #endif
true
9b34f88e1df784676571a4b8cb114c279d1730d0
C++
njoy/ACEtk
/src/ACEtk/block/AngularDistributionData/src/verifyIncidentEnergyIndex.hpp
UTF-8
483
2.765625
3
[ "BSD-2-Clause" ]
permissive
void verifyIncidentEnergyIndex( const std::size_t index ) const { if ( ( index < 1 ) || ( index > this->numberIncidentEnergies() ) ) { Log::error( "Illegal incident energy index argument into {} block", this->name() ); Log::info( "Index value: {}", index ); Log::info( "{} accepts an incident energy index between 1 and {} inclusively", this->name(), this->numberIncidentEnergies() ); throw std::out_of_range( this->name() ); } }
true
48b505bec0c840d40b10be6fda615719a4670ab5
C++
ysouyno/daobell
/src/bencode_list.cpp
UTF-8
606
2.703125
3
[]
no_license
#include "bencode_list.h" void bencode_list::print_member() { for (value_type::iterator it = value_.begin(); it != value_.end(); ++it) { (*it)->print_member(); } } void bencode_list::crawl(bencode_crawler *p) { p->crawl(this); } void bencode_list::insert_to_list(std::shared_ptr<bencode_value_base> value) { value_.push_back(value); } const bencode_list::value_type &bencode_list::get_value() const { return value_; } bencode_list::value_type::iterator bencode_list::begin() { return value_.begin(); } bencode_list::value_type::iterator bencode_list::end() { return value_.end(); }
true
7e1b43e12414db89173ae4d249b75c23d53e2c55
C++
s13shok/Labs_Cpp
/Lab_2/Lab_2/Matrix.cpp
UTF-8
2,319
3.203125
3
[ "MIT" ]
permissive
#include "Matrix.h" #include <iomanip> #include "Vector.h" Matrix::Matrix(int i, int j) { array_ = new int* [i]; i_ = i; j_ = j; for (size_t l = 0; l < i_; ++l) { array_[l] = new int[j_]; } for (size_t i = 0; i < i_; ++i) { for (size_t j = 0; j < j_; ++j) { array_[i][j] = 0; } } } Matrix::Matrix(const Matrix& m) { i_ = m.i_; j_ = m.j_; array_ = new int* [i_]; for (size_t k = 0; k < i_; ++k) { array_[k] = new int[j_]; } for (size_t i = 0; i < i_; ++i) { for (size_t j = 0; j < j_; ++j) { array_[i][j] = m.array_[i][j]; } } } Matrix::~Matrix() { for (size_t i = 0; i < i_; ++i) { delete[] * (array_ + i); } delete[] array_; } int Matrix::at(int i, int j) const { return array_[i][j]; } void Matrix::setAt(int i, int j, int value) { array_[i][j] = value; } Matrix& Matrix::operator++() { for (size_t i = 0; i < i_; ++i) { for (size_t j = 0; j < j_; ++j) { ++array_[i][j]; } } return *this; } Matrix& Matrix::operator--() { for (size_t i = 0; i < i_; ++i) { for (size_t j = 0; j < j_; ++j) { --array_[i][j]; } } return *this; } Matrix Matrix::operator++(int) { Matrix m(*this); for (size_t i = 0; i < i_; ++i) { for (size_t j = 0; j < j_; ++j) { array_[i][j]++; } } return m; } Matrix Matrix::operator--(int) { Matrix m(*this); for (size_t i = 0; i < i_; ++i) { for (size_t j = 0; j < j_; ++j) { array_[i][j]++; } } return m; } std::ostream& operator<<(std::ostream& out, const Matrix& m) { for (size_t i = 0; i < m.i_; ++i) { for (size_t j = 0; j < m.j_; ++j) { out << std::setw(8) << m.array_[i][j] << ' '; } if (i != m.i_ - 1) { out << std::endl; } } return out; } int factorial(int x) { if (x < 0 || x > 12) { return -1; } static const int table[] = { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600 }; return table[x]; } Matrix& Matrix::initializeMatrix() { for (size_t i = 0; i < i_; ++i) { for (size_t j = 0; j < j_; ++j) { array_[i][j] = factorial(i) + factorial(j); } } return *this; } Vector Matrix::transformMatrix() { Vector v = i_ / 2 * j_; int position = 0; for (size_t i = 0; i < i_; ++i) { if (i % 2 != 0) { for (size_t j = 0; j < j_; ++j) { v[position] = array_[i][j]; position++; } } } return v; }
true
297f457594fd52a2a8b45fd2f8f33054d969b74f
C++
debordem/arduino-basics
/_displays/LED_Matrix/MAX7219/MAX7219_Adafruit-Multiple-SPI-Graphics/MAX7219_Adafruit-Multiple-SPI-Graphics.ino
UTF-8
3,949
2.875
3
[]
no_license
// https://github.com/markruys/arduino-Max72xxPanel /* THis works with 1X4 Module * Download the library zip files and Add Zip file */ #include <SPI.h> #include <Adafruit_GFX.h> #include <Max72xxPanel.h> /* PIN Connections * _______|_______________|____ * | VCC | | +5V * | CLK | -CLOCK | 13 * | CE |- CE /CS | 10 * | MOSI | - Data Input | 11 * | GND | | GND */ int pinCS = 10; // Attach CS to this pin, DIN to MOSI and CLK to SCK (cf http://arduino.cc/en/Reference/SPI ) int numberOfHorizontalDisplays = 1; // Horizontal int numberOfVerticalDisplays = 1; // Vertical // Set up the panel Max72xxPanel matrix = Max72xxPanel(pinCS, numberOfHorizontalDisplays, numberOfVerticalDisplays); String tape = "DESIGN team"; // the string or message int wait = 100; // the Scrolling speed in milliseconds int spacer = 1; int width = 5 + spacer; // The font width is 5 pixels // can I draw a hearst with GFX? /*byte array for heart * */ static uint8_t heart[8] = {0x66, 0xFF, 0xFF, 0xFF, 0x7E, 0x3C, 0x18, 0x00}; /*byte array for face * */ static uint8_t face[8] = {0x3C, 0x7E, 0xFF, 0xFF, 0xFF, 0xFF, 0x7E, 0x3C}; void setup() { Serial.begin(9600); // for debugging matrix.setIntensity(1); // Use a value between 0 and 15 for brightness // Adjust to your own needs // matrix.setPosition(0, 0, 0); // The first display is at <0, 0> // matrix.setPosition(1, 1, 0); // The second display is at <1, 0> // matrix.setPosition(2, 2, 0); // The third display is at <2, 0> // matrix.setPosition(3, 3, 0); // And the last display is at <3, 0> // ... matrix.setRotation(0, 1); // The first display is position upside down matrix.setRotation(1, 1); // The same hold for the last display matrix.setRotation(2, 1); // The first display is position upside down matrix.setRotation(3, 1); // The same hold for the last display } void loop() { ticker(); drawHeart(); drawFace(); moveHeart(); } /* * Use http://www.binaryhexconverter.com/binary-to-hex-converter * to convert binary 0 and 1 to hex */ // draw symbol of heart wuth a byte array void drawHeart() { // methods from Adafruit_GFX matrix.drawBitmap(0, 0, heart, 8, 8, true); matrix.write(); // Send bitmap to display delay(2000); // turn all pixels off (takes effect after led->flush()) matrix.fillScreen(false); } // draw symbol of face with a byte array void drawFace() { // methods from Adafruit_GFX matrix.drawBitmap(0, 0, face, 8, 8, true); matrix.write(); // Send bitmap to display delay(2000); // turn all pixels off (takes effect after led->flush()) matrix.fillScreen(false); } /* To animate, draw the bitmap in the first position * draw another behind or following it offset to the width + a spacer * write to the screen */ void moveHeart(){ for(int x=0; x<=8; x++){ matrix.fillScreen(LOW); Serial.println(x); // for debugging position of x matrix.drawBitmap(x, 0, heart, 8, 8, true); // leading image matrix.drawBitmap(x-9, 0, heart, 8, 8, true); // trailing image matrix.write(); // Send bitmap to display delay(100); } } /*A ticker ot text across the display * */ void ticker(){ String tape = "The Message "; // the string or message for ( int i = 0 ; i < width * tape.length() + matrix.width() - 1 - spacer; i++ ) { matrix.fillScreen(LOW); int letter = i / width; int x = (matrix.width() - 1) - i % width; int y = (matrix.height() - 8) / 2; // center the text vertically while ( x + width - spacer >= 0 && letter >= 0 ) { if ( letter < tape.length() ) { matrix.drawChar(x, y, tape[letter], HIGH, LOW, 1); } letter--; x -= width; } matrix.write(); // Send bitmap to display delay(wait); } }
true
98da3131b73db395713f4b84e1140954a4de3470
C++
Bunty9/GSM_Home_Auto
/gsm-a2/gsm-a2.ino
UTF-8
4,465
2.734375
3
[]
no_license
#include <SoftwareSerial.h> //Create software serial object to communicate with SIM800L SoftwareSerial mySerial(3, 2); //SIM800L Tx & Rx is connected to Arduino #3 & #2 int temp=0,i=0; #define Fan 6 #define Light 4 #define TV 5 char str[25]; String msg; char ph[] = "+919420490305"; void setup() { //Begin serial communication with Arduino and Arduino IDE (Serial Monitor) Serial.begin(9600); //Begin serial communication with Arduino and SIM800L mySerial.begin(9600); pinMode(Fan, OUTPUT); pinMode(Light, OUTPUT); pinMode(TV, OUTPUT); digitalWrite(TV, HIGH); digitalWrite(Light, HIGH); digitalWrite(Fan, HIGH); Serial.println("Initializing..."); delay(1000); mySerial.println("AT"); //Once the handshake test is successful, it will back to OK updateSerial(); delay(500); mySerial.println("AT+CMGF=1"); // Configuring TEXT mode updateSerial(); delay(500); mySerial.println("AT+CNMI=1,2,0,0,0"); // Decides how newly arrived SMS messages should be handled updateSerial(); delay(500); delay(500); mySerial.print("AT+CMGS="); mySerial.print("\""); mySerial.print(ph); mySerial.println("\""); delay(1000); mySerial.println("System is ready to receive SMS commands."); delay(100); mySerial.println((char)26); } void loop() { updateSerial(); serialEvent(); if(temp==1) { check(); temp=0; i=0; } } void updateSerial() { delay(500); while (Serial.available()) { mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port } // while(mySerial.available()) // { // String msg = mySerial.readString(); // Serial.println(msg); //Forward what Software Serial received to Serial Port // } } void serialEvent() { while(mySerial.available()) { if(mySerial.find("#A.")) { Serial.println("cmd"); while (mySerial.available()) { char inChar=mySerial.read(); Serial.print(inChar); str[i++]=inChar; if(inChar=='*') { temp=1; return; } } } } } /////////////////////////////////////////////////////// void check() { if(!(strncmp(str,"tv on",5))) { digitalWrite(TV, LOW); delay(200); Serial.println("TV ON"); mySerial.print("AT+CMGS="); mySerial.print("\""); mySerial.print(ph); mySerial.println("\""); delay(200); mySerial.println("TV turned ON."); delay(200); mySerial.println((char)26); } else if(!(strncmp(str,"tv off",6))) { digitalWrite(TV, HIGH); Serial.println("TV OFF"); delay(200); mySerial.print("AT+CMGS="); mySerial.print("\""); mySerial.print(ph); mySerial.println("\""); delay(200); mySerial.println("TV turned OFF."); delay(200); mySerial.println((char)26); } else if(!(strncmp(str,"fan on",6))) { digitalWrite(Fan, LOW); delay(200); Serial.println("fan on"); mySerial.print("AT+CMGS="); mySerial.print("\""); mySerial.print(ph); mySerial.println("\""); delay(200); mySerial.println("FAN turned ON."); delay(200); mySerial.println((char)26); } else if(!(strncmp(str,"fan off",7))) { digitalWrite(Fan, HIGH); delay(200); Serial.println("fan off"); mySerial.print("AT+CMGS="); mySerial.print("\""); mySerial.print(ph); mySerial.println("\""); delay(200); mySerial.println("FAN turned OFF."); delay(200); mySerial.println((char)26); } else if(!(strncmp(str,"all on",6))) { digitalWrite(Fan, LOW); digitalWrite(TV, LOW); delay(200); mySerial.print("AT+CMGS="); mySerial.print("\""); mySerial.print(ph); mySerial.println("\""); delay(200); mySerial.println("ALL DEVICES turned ON."); delay(200); mySerial.println((char)26); } else if(!(strncmp(str,"all off",7))) { digitalWrite(Fan, HIGH); digitalWrite(TV, HIGH); delay(200); mySerial.print("AT+CMGS="); mySerial.print("\""); mySerial.print(ph); mySerial.println("\""); delay(200); mySerial.println("ALL DEVICES turned OFF."); delay(200); mySerial.println((char)26); } } /////////////////////////////////////////////////////////////////
true
a2a9010134d87bbc700ee1385601691877747e46
C++
tnie/see-the-world
/1.语言怎么用/pFunc_learn/lambda/for.cpp
UTF-8
760
3.53125
4
[]
no_license
#include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; // 依据参数 n,过滤集合中单词 int main(void) { const vector<string> words = {"niel", "has", "many", "books"}; cout << "-------------use for()" << endl; cout << "长度大于3的单词:"; for (auto citor = words.cbegin(); citor != words.cend(); ++citor) { if(citor->size() > 3) cout << *citor << " "; } cout << endl; cout << "长度大于4的单词:"; //for (auto citor = words.cbegin(); citor != words.cend(); ++citor) //{ //if(citor->size() > 4) //cout << *citor << " "; //} for ( auto word : words ) { if(word.size() > 4) cout << word << " "; } cout << endl; return 0; }
true
fca759551450eeefb91e569302317e077acf3b37
C++
PabloMessina/Competitive-Programming-Material
/Solved problems/others/HyperactiveGirl.cpp
UTF-8
1,740
2.609375
3
[]
no_license
#include <cstdio> #include <set> #include <algorithm> #include <cstring> #include <map> #include <stack> #include <string> #include <vector> using namespace std; #define MAXN 100 #define MOD 100000000 int M, N; struct Activity { int S; int F; }; Activity activities[MAXN]; int times[2 * MAXN]; map<int, int> time2IndexMap; int DP[MAXN][2 * MAXN][2 * MAXN]; bool compByS(const Activity& x, const Activity& y) { return x.S < y.S; } int solve(int i, int ti_1, int ti_2) { if (i == N) return 0; if (ti_2 != -1 && DP[i][ti_1][ti_2] != -1) return DP[i][ti_1][ti_2]; int ans = 0; Activity& act = activities[i]; bool parentCond = (act.S <= times[ti_1] && act.F > times[ti_1]); bool gparentCond = (ti_2 == -1) || (act.S > times[ti_2]); if (parentCond && gparentCond) { if (act.F == M) ans++; else { int next_ti = time2IndexMap[act.F]; ans += solve(i + 1, next_ti, ti_1); } } ans += solve(i + 1, ti_1, ti_2); ans %= MOD; if(ti_2 != -1) DP[i][ti_1][ti_2] = ans; return ans; } int main() { setvbuf(stdout, NULL, _IONBF, 0); mainloop: while (true) { int i; scanf("%d %d", &M, &N); if (M == 0 && N == 0) break; set<int> timesSet; for (i = 0; i < N; ++i) { int s, f; scanf("%d %d", &s, &f); activities[i].S = s; activities[i].F = f; timesSet.insert(s); timesSet.insert(f); } i = 0; time2IndexMap.clear(); for (set<int>::iterator it = timesSet.begin(); it != timesSet.end(); ++it) { int t = *it; time2IndexMap[t] = i; times[i] = t; ++i; } if (times[0] > 0 || times[timesSet.size() - 1] < M) { puts("0"); goto mainloop; } sort(activities, activities + N, compByS); memset(DP, -1, sizeof DP); printf("%d\n", solve(0, 0, -1)); } return 0; }
true
05fdfd8845468d01e2c28f207374a018de730f77
C++
askarakshabayev/PP1-2018
/week1/1/4.cpp
UTF-8
298
3.3125
3
[]
no_license
#include <iostream> using namespace std; int main() { // Example 1 string s1, s2; // s1 = "hello world" s2 = "abc" cin >> s1 >> s2; // s1 = "45" s2 = "5" cout << s1 + s2; // Example 2 // string s1; // cin >> s1; // char b = s1[3]; // cout << b; return 0; }
true
28570d58ca8f6953b09854a167c3e49d375a968b
C++
perutilli/project_euler
/prob3/prob3.cpp
UTF-8
703
3.140625
3
[]
no_license
#include <iostream> #include <bits/stdc++.h> #include <math.h> const long long NUM = 600851475143; using namespace std; bool multiple_of_factor(vector<int>, int); int main() { int max = 0; int max_fact = sqrt(NUM); vector<int> prime_factors; for (int i = 2; i <= max_fact; i++) { if ((NUM % i == 0) && !(multiple_of_factor(prime_factors, i))) { prime_factors.push_back(i); max = i; } } std::cout << max; return 0; } bool multiple_of_factor(vector<int> prime_factors, int num) { for (int f : prime_factors) { if ((num % f) == 0) { return true; } } return false; }
true
8a43dff705415bd4ac3052e7154bd31f685d666c
C++
laziestcoder/Problem-Solvings
/C++ C141018/Private_Shoab_Vai/PROG_102.CPP
UTF-8
243
3.046875
3
[]
no_license
//#include<cstdio> #include<iostream> using namespace std; int main() { int a; char ch; cin >> a; cout << a << endl; cin.get(ch); // it is taking the enter key('\n') as input cout << ch << endl; return 0; }
true
270227eb30ed540322adffbfd811df2ad3ffad45
C++
catunlock/Dementia
/Dementia/src/Camera.cpp
UTF-8
3,788
2.765625
3
[]
no_license
#include "Camera.h" #include "MathHelper.h" namespace Dementia{ Camera::Camera() : m_position(XMVectorSet(0.0f, 0.0f, -15.0f, 0.0f)), mRight(XMVectorSet(1.0f, 0.0f, 0.0f, 0.0f)), mUp(XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f)), mLook(XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f)) { SetLens(0.25f*MathHelper::Pi, 1.0f, 1.0f, 1000.0f); } Camera::~Camera() { } XMVECTOR Camera::GetPosition() const { return m_position; } void Camera::SetPosition(XMVECTOR position) { m_position = position; } XMVECTOR Camera::GetRight()const { return mRight; } XMVECTOR Camera::GetUp()const { return mUp; } XMVECTOR Camera::GetLook() const { return mLook; } float Camera::GetNearZ()const { return mNearZ; } float Camera::GetFarZ()const { return mFarZ; } float Camera::GetAspect()const { return mAspect; } float Camera::GetFovY()const { return mFovY; } float Camera::GetFovX()const { float halfWidth = 0.5f*GetNearWindowWidth(); return 2.0f*atan(halfWidth / mNearZ); } float Camera::GetNearWindowWidth()const { return mAspect * mNearWindowHeight; } float Camera::GetNearWindowHeight()const { return mNearWindowHeight; } float Camera::GetFarWindowWidth()const { return mAspect * mFarWindowHeight; } float Camera::GetFarWindowHeight()const { return mFarWindowHeight; } void Camera::SetLens(float fovY, float aspect, float zn, float zf) { // cache properties mFovY = fovY; mAspect = aspect; mNearZ = zn; mFarZ = zf; mNearWindowHeight = 2.0f * mNearZ * tanf( 0.5f*mFovY ); mFarWindowHeight = 2.0f * mFarZ * tanf( 0.5f*mFovY ); mProj = XMMatrixPerspectiveFovLH(mFovY, mAspect, mNearZ, mFarZ); } void Camera::LookAt(FXMVECTOR pos, FXMVECTOR target, FXMVECTOR worldUp) { m_position = pos; mLook = XMVector3Normalize(XMVectorSubtract(target, pos)); mRight = XMVector3Normalize(XMVector3Cross(worldUp, mLook)); mUp = XMVector3Cross(mLook, mRight); } XMMATRIX Camera::View()const { return mView; } XMMATRIX Camera::Proj()const { return mProj; } XMMATRIX Camera::ViewProj()const { return XMMatrixMultiply(View(), Proj()); } void Camera::Strafe(float d) { XMVECTOR s = XMVectorReplicate(d); m_position += s*mRight; } void Camera::Walk(float d) { XMVECTOR s = XMVectorReplicate(d); m_position += s*mLook; } void Camera::Pitch(float angle) { // Rotate up and look vector about the right vector. XMMATRIX R = XMMatrixRotationAxis(mRight, angle); mUp = XMVector3TransformNormal(mUp, R); mLook = XMVector3TransformNormal(mLook, R); } void Camera::RotateY(float angle) { // Rotate the basis vectors about the world y-axis. XMMATRIX R = XMMatrixRotationY(angle); mRight = XMVector3TransformNormal(mRight, R); mUp = XMVector3TransformNormal(mUp, R); mLook = XMVector3TransformNormal(mLook, R); } void Camera::UpdateViewMatrix() { XMVECTOR R = mRight; XMVECTOR U = mUp; XMVECTOR L = mLook; XMVECTOR P = m_position; // Keep camera's axes orthogonal to each other and of unit length. L = XMVector3Normalize(L); U = XMVector3Normalize(XMVector3Cross(L, R)); // U, L already ortho-normal, so no need to normalize cross product. R = XMVector3Cross(U, L); // Fill in the view matrix entries. float x = -XMVectorGetX(XMVector3Dot(P, R)); float y = -XMVectorGetX(XMVector3Dot(P, U)); float z = -XMVectorGetX(XMVector3Dot(P, L)); mRight = R; mUp = U; mLook = L; XMFLOAT4 right; XMFLOAT4 up; XMFLOAT4 look; XMStoreFloat4(&right, mRight); XMStoreFloat4(&up, mUp); XMStoreFloat4(&look, mLook); XMFLOAT4X4 view = { right.x, up.x, look.x, 0.0f, right.y, up.y, look.y, 0.0f, right.z, up.z, look.z, 0.0f, x, y, z, 1.0f }; mView = XMLoadFloat4x4(&view); } }
true
fcffcb915eb18b022a8d2f1327e1c6fd05271793
C++
illusivedmg/Dijkstra-Graph-Solver
/MinHeap.h
UTF-8
1,450
3.375
3
[]
no_license
#pragma once #include <string> #include <vector> #include <iostream> #include <cmath> struct Node { Node(int lab, int k) : mLabel(lab), mKey(k) {} int mLabel, mKey; }; class MinHeap { public: // init vectors as 1-indexed MinHeap(); // delete Nodes in both lists ~MinHeap(); // |i| int numElements() { return mHeap.size()-1; }; int top() { return mHeap[1]->mLabel; }; bool isEmpty() { return numElements() == 0; }; // i^-1(x) => get index in position vector of label int getPositionIndexOfLabel(int labeltofind); // swap and update in Pos vector void swapPositions(int indexL, int indexR); // prints contents of vectors void displayHeap(); void displayPositions(); // compare parent with child, swap if parent bigger void bubbleUp(int i); // same label as existing Node, new value for key void decreaseKey(int label, int key); // compare parent with children, swap with smaller void siftDown(int i); void insert(Node* x); void makeHeap(const std::vector<Node*> &S); // swaps and pops first/last in heap, swap/nullify in pos vector int deleteMin(); private: int Parent(int i) { return floor(i/2); }; int Left(int i) { return (2*i); }; int Right(int i) { return (2*i+1); }; // key = value to minimize std::vector<Node*> mHeap; // key = tree index/position std::vector<Node*> mPositions; };
true
93dd1bdd30128263a6606b7813cdc4c236a834fe
C++
tito-kimbo/Online-Judge-Solutions
/AceptaElReto/AceptaElReto_212/AceptaElReto_212/Source.cpp
WINDOWS-1250
792
3.265625
3
[]
no_license
#include <iostream> #include <vector> using namespace std; typedef vector<int> VI; //TEOREMA 1: Un multigrafo tiene un camino (=>No circular) euleriano sii //todos sus vrtices tienen orden par salvo 2 //TEOREMA 2: Un multigrafo tiene un circuito (ciclo) euleriano sii //todos sus vrtices tienen grado par bool resolver(int edges) { int from, to, nodes, odd; cin >> nodes; VI v(nodes); //Mantiene los grados de los vertices for (int i = 0; i < edges; ++i){ cin >> from; cin >> to; v[from-1]++; v[to-1]++; } odd = 0; for (int i = 0; i < nodes; ++i) { if (v[i] % 2 != 0) { odd++; } } return odd == 2 || odd == 0; } int main() { int n; cin >> n; while (n != 0) { if (resolver(n)) { cout << "SI\n"; } else { cout << "NO\n"; } cin >> n; } }
true
9fdad9a195fd6723642b4f37ee1c024e2bc78122
C++
MegaRizwan20/Programming-Assignments-4
/extension.cpp
UTF-8
4,782
3.25
3
[]
no_license
/* * Authors: Rizwan Khan, Yiming Cai * Date: 6/5/17 * * This is the main executable program that runs the code to make the graph * and obtain the information on the paths to the graph */ #include <fstream> #include <iostream> #include <string.h> #include <errno.h> #include <math.h> #include "ExtensionGraph.h" #include "ExtensionGraph.h" #include "ActorNode.h" #include "ActorEdge.h" #include "ActorPath.h" #include "MovieName.h" #define USAGE "Usage: ./extension 9_column_file.csv 2_column_file.csv output_file\n" using namespace std; int main (int argc, char* argv[]) { // Make sure to add all the user input error parsings here if (argc != 4) { std::cerr << "Incorrect number of inputs!" << std::endl; std::cerr << USAGE; return -1; } // Check input and output file validity errno = 0; ifstream inFile; inFile.open( argv[1] ); if (errno != 0 || !inFile.is_open()) { cerr << "Error: " << strerror(errno) << endl; cerr << USAGE; return -1; } inFile.close(); inFile.open(argv[2]); if (errno != 0 || !inFile.is_open()) { cerr << "Error: " << strerror(errno) << endl; cerr << USAGE; return -1; } inFile.close(); ofstream outFile; outFile.open( argv[3] ); if (errno != 0 ) { cerr << "Error: " << strerror(errno) << endl; cerr << USAGE; return -1; } // Finished checking if all input is correct // initiate graph ExtensionGraph graph; ActorPath* twoActors; // check weight input /*bool weight; if ( strcmp( argv[2], "u") == 0 ) { weight = false; } else if ( strcmp( argv[2], "w") == 0 ) { weight = true; } else { std::cerr << "Invalid flag input!" << std::endl; std::cerr << USAGE; return -1; }*/ // Load graph from the input file std::cout << "Loading from file, this might take a while..." << std::endl; if ( !graph.loadFromFile( argv[1]) ) { cerr << USAGE; return -1; } graph.printStats(cout); cout << "done!" << endl; // initialize pair input and output files ifstream infile(argv[2]); ofstream outfile(argv[3]); // WHERE TWO COLUMN READING bool header_check = false; // output file header; outfile << "anime1,anime2,average,standard deviation" << endl; // Read lines until we reach the end of the file while (infile) { string s; // Get the next lines in a file if (!getline(infile, s)) { break; } // Skip header part if (!header_check) { header_check = true; continue; } istringstream ss(s); vector<string> record; while(ss) { string next; // Get next string before hitting tab character and put it in next if (!getline(ss, next, ',')) { break; } record.push_back(next); } // Should have exactly 2 columns if (record.size() != 2) { continue; } // The names of the 2 actors string actor1(record[0]); string actor2(record[1]); // find the path and print it out twoActors = graph.findPath(actor1, actor2); if (twoActors == nullptr) { cerr << " Path is not found for the pair (" << actor1 << ") -> (" << actor2 << ")" <<endl; } else { cout<<"Computer average and SD for ("<<actor1<<") -> (" <<actor2<< ")" <<endl; vector<double> incomes; incomes.push_back( graph.findIncome( twoActors->getStartNode() ) ); vector<ActorEdge *> edges = twoActors->getEdges(); for (int i = 0; i < edges.size(); i++) { incomes.push_back( graph.findIncome( edges[i]->getNextNode() ) ); } double sum = 0; double average; double sd; for (int i = 0; i < incomes.size(); i++) { sum += incomes[i]; } average = sum/ ((double) incomes.size()); sum = 0; for (int i = 0; i < incomes.size(); i++) { sum += (pow( (average - incomes[i]), 2)) / ((double) incomes.size()); } sd = sqrt(sum); outfile << actor1 << "," << actor2 << "," << average << "," << sd << endl; delete twoActors; } // End of outer while loop } // if the loop is broken out before eof is reached, exit with failure if (!infile.eof()) { cerr << "Failed to read " << argv[3] << "!\n"; std::cerr << USAGE; return -1; } // Ended program successfully infile.close(); return 0; }
true
6975d3d5e79f5c24b78e3102c0969ff0531b0774
C++
xueliuxing28/Medusa
/Medusa/MedusaCore/Core/Action/IAction.h
UTF-8
1,959
2.515625
3
[ "MIT" ]
permissive
// Copyright (c) 2015 fjz13. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. #pragma once #include "Core/Pattern/Runnable/DefaultRunnable.h" #include "Core/Pattern/IClone.h" #include "Core/String/HeapString.h" MEDUSA_BEGIN; enum class ActionType { Instant, Finite, Infinite }; class IAction :public IClone<IAction>, public DefaultRunnable { public: IAction(const StringRef& name = StringRef::Empty) :mName(name) {} virtual ~IAction(void) {} virtual ActionType Type()const = 0; public: virtual bool Update(float dt, float blend = 1.f) { return true; //return true to continue next actions } bool ForceUpdate(float dt) { return Update(dt); } bool IsDead()const { return !mKeepAlive && IsDone(); } bool IsAlive()const { return mKeepAlive || !IsDone(); } bool IsKeepAlive()const {return mKeepAlive;} void KeepAlive(bool val = true) { mKeepAlive = val; } void* Target() const { return mTarget; } void SetTarget(void* val) { mTarget = val; } int Tag() const { return mTag; } void SetTag(int val) { mTag = val; } bool HasName()const { return !mName.IsEmpty(); } StringRef Name() const { return mName; } void SetName(const StringRef& val) { mName = val; } virtual IAction* FindActionByTagRecursively(int tag)const { return nullptr; } virtual IAction* FindActionByNameRecursively(const StringRef& name) const { return nullptr; } virtual bool Initialize(void* target) { mTarget = target; return true; } virtual IAction* Reverse()const { MEDUSA_ASSERT_NOT_IMPLEMENT(); return nullptr; } virtual float ElapsedExceed()const { return 0.f; } protected: virtual void BuildClone(IAction& obj) override { obj.mTarget = mTarget; obj.mTag = mTag; obj.mName = mName; obj.mKeepAlive = mKeepAlive; } protected: void* mTarget = nullptr; int mTag = 0; HeapString mName; bool mKeepAlive = false; //won't be deleted after done }; MEDUSA_END;
true
227cece31dbcbaf16c166d5b4ff1a105dc572bfc
C++
WFCSC112AlqahtaniFall2019/project6-Phaddi
/InsertionSort.cpp
UTF-8
1,537
3.484375
3
[]
no_license
//Ryan Phadnis #include <iostream> #include <vector> #include "BinaryInsertionSort.h" #include "Node.h" #include <cassert> #include <ctime> #include "LinkedList.h" using namespace std; int main() { cout << "Enter seed, length: " << endl; int seed, length; cin >> seed >> length; srand(seed); LinkedList list; vector<int> v(length); // generate vector of random integers for (int i = 0; i < v.size(); i++) { v[i] = rand() % 100; } //create the LinkedList for(int i = 0; i < v.size(); i++) { int a = v[i]; list.append(a); } cout << "Unsorted LinkedList: " << endl; list.printList(); clock_t begbinary = clock(); insertionSort(v, v.size()); clock_t endbinary = clock(); clock_t beginsertion = clock(); list.InsertionSort(); clock_t endinsertion = clock(); // check if sorted for (int i = 1; i < v.size(); i++) { assert(v[i-1] <= v[i]); } // print out sorted list (binary) cout << "Sorted with Binary: " << endl; for (int i = 0; i < v.size(); i++) { cout << v[i] << " "; } cout << endl; cout << "Sorted with Insertion" << endl; list.printList(); cout << endl; double totalbinary; totalbinary = double(endbinary - begbinary); double totalinsertion; totalinsertion = double(endinsertion - beginsertion); cout << "Time to Binary Sort: " << totalbinary << endl; cout << "Time to Insertion Sort: " << totalinsertion << endl; // FINISH ME }
true
8568032eea37eaf29600ca59ab8cd08c08f1e9f3
C++
yashkatta/search_algorithms
/src/LinearSearch.hpp
UTF-8
360
3.140625
3
[]
no_license
#pragma once class LinearSearch { public: LinearSearch() {} ~LinearSearch() {} template <typename T> int LinearSearchOnArray(T arr[], unsigned int size, T x); }; template <typename T> int inline LinearSearch::LinearSearchOnArray(T arr[], unsigned int size, T x) { for (int i = 0; i < size; i++) { if (arr[i] == x) return i; } return -1; }
true
8170056fcdb6730fc70d34d931c3c646e25ff329
C++
small-cat/myCode_repository
/language_implementation_pattern/sql_query/parser/sqlquery_parser.cpp
UTF-8
3,291
2.609375
3
[]
no_license
/** * @copyright (c) Copyright 2020 Secsmart. All Rights Reserved. * @license * @file : sqlquery_parser.cpp * @author: Jona * @email : wuzhenyu@secsmart.net * @date : 2020-08-11 * @brief : parser for iso/iec sql:1999 */ #include "sqlquery_parser.hpp" SqlQueryParser::SqlQueryParser(CommonTokenStream* tokens) : Parser(tokens) {} SqlQueryParser::~SqlQueryParser() {} void SqlQueryParser::Fill(int n) { for (int i = 0; i < n; i++) { Token* t = tokens_->NextToken(); while (t->GetType() == SPACE) { t = tokens_->NextToken(); } lookahead_.push_back(t); } } void SqlQueryParser::QuerySpecification() { Match(SELECT); if (LA(1) == ALL) { Match(ALL); } else if (LA(1) == DISTINCT) { Match(DISTINCT); } SelectList(); TableExpression(); } void SqlQueryParser::SelectList() { if (LA(1) == ASTERISK) { Match(ASTERISK); } else { SelectListElement(); while (LA(1) == COMMA) { Match(COMMA); SelectListElement(); } } } // select_list_element // : derived_column // | qualified_asterisk // ; // // derived_column // : identifier attrs* as_clause? // ; // // qualified_asterisk // : identifier attrs* PERIOD ASTERISK // ; void SqlQueryParser::SelectListElement() { if (SpeculateSelectListElement_Alt1()) { DerivedColumn(); } else if (SpeculateSelectListElement_Alt2()) { QualifiedAsterisk(); } else { std::cout << "no viable alt, expect SelectListElement, but found " << LT(1)->ToString() << std::endl; } } bool SqlQueryParser::SpeculateSelectListElement_Alt1() { bool success = true; Mark(); try { DerivedColumn(); } catch (RuntimeException& e) { std::cout << e.what() << std::endl; success = false; } Release(); return success; } bool SqlQueryParser::SpeculateSelectListElement_Alt2() { bool success = true; Mark(); try { QualifiedAsterisk(); } catch (RuntimeException& e) { std::cout << e.what() << std::endl; success = false; } Release(); return success; } void SqlQueryParser::QualifiedAsterisk() { Match(IDENTIFIER); while (LA(1) == PERIOD && LA(2) != ASTERISK) { Match(PERIOD); Match(IDENTIFIER); } if (LA(1) == PERIOD) { Match(PERIOD); Match(ASTERISK); } else { std::cout << "expect PERIOD found" << LT(1)->ToString() << std::endl; } } void SqlQueryParser::DerivedColumn() { ValueExpression(); if (LA(1) == AS || LA(1) == IDENTIFIER) { AsClause(); } } // IDENTIFIER ('.' IDENTIFIER)* void SqlQueryParser::Attrs() { while (LA(1) == PERIOD) { Match(PERIOD); Match(IDENTIFIER); } } void SqlQueryParser::AsClause() { if (LA(1) == AS) { Match(AS); } Match(IDENTIFIER); } void SqlQueryParser::ValueExpression() { // TODO throw RuntimeException("TODO: ValueExpression"); } void SqlQueryParser::TableExpression() { FromClause(); /* * WhereClause(); * GroupByClause(); * HavingClause(); */ } void SqlQueryParser::FromClause() { Match(FROM); TableRef(); while (LA(1) == COMMA) { Match(COMMA); TableRef(); } } void SqlQueryParser::TableRef() { TablePrimary(); } void SqlQueryParser::TablePrimary() { Match(IDENTIFIER); if (LA(1) == PERIOD) { Attrs(); } if (LA(1) == AS || LA(1) == IDENTIFIER) { AsClause(); } }
true
69967b80aaa60508642e360735acf9b32a33e80c
C++
tuyen-nnt/BigO
/Lesson9/Recursion04/main.cpp
UTF-8
273
3.015625
3
[]
no_license
#include <iostream> using namespace std; int findFirst(int n) { int mod = n % 10; if ((n / 10) == 0) { return abs(mod); } else { return findFirst(n/10); } } int main() { int n; cin >> n; cout << findFirst(n); return 0; }
true
ceeb3dda9ddbfcd28fe1f9ca444a1ae26f04a9e7
C++
tommyang/autoCompleter_GUI
/wordlist.h
UTF-8
955
2.640625
3
[]
no_license
/* * Author: Huayin Zhou * Description: WordList is a customized QListWidget to keep track of the text * changes in QLineEdit and print strings to the changes accordingly by * calling pa3 function: * vector<std::string> autocomplete(unsigned int num_words, std::string prefix). * Date: 01/28/2015 */ #ifndef WORDLIST_H #define WORDLIST_H #include <QListWidget> #include <QString> #include <QLineEdit> #include <string> #include <iostream> #include <fstream> #include <array> #include "dictionaryConst.h" #include "mylineedit.h" class MyLineEdit; class WordList : public QListWidget { Q_OBJECT public: WordList(QWidget *parent = 0); void selectNext(); void selectPrev(); ~WordList(); const static char * dictionary[]; public slots: void setItems(const QString &newString); private: MyLineEdit *lineEdit; std::vector<std::string> autocomplete(unsigned int num_words, std::string prefix); }; #endif // WORDLIST_H
true
fa42fd4f5bd996fe92effdffd97b44936f7a30fe
C++
imVPandey/codesnippet
/code.cpp
UTF-8
696
2.984375
3
[]
no_license
#include<bits/stdc++.h> using namespace std; bool isprime(int n){ int flag = 0; int sqr = sqrt(n); for (int i = 2; i <= sqr; ++i) { if(n%i==0){ flag++; break; } } if(flag == 0){ return true; }else{ return false; } } vector<int> find(int n){ vector<int>v; for (int i = 2; i <= n; ++i) { if(isprime(i)){ for(int j=2;j*i<=sqrt(n);j++){ v[i*j] == 0; } v.push_back(i); } } return v; } vector<int> fact(int n){ vector<int>v; for(int i = 1;i <= sqrt(n); i++){ if(n % i == 0){ v.push_back(i); v.push_back(n/i); } } sort(v.begin(),v.end()); return v; } int main(){ }
true
2a6d60b1729d67201107175334cd500c8c475000
C++
WolverinDEV/CXXTerminal
/include/CString.h
UTF-8
844
2.75
3
[]
no_license
#pragma once #include <string> #include <vector> #define STYLE_MAGIC 0 #define STYLE_BOLD 1 #define STYLE_ITALIC 2 #define STYLE_UNDERLINED 3 #define STYLE_CURSIVE 4 struct CChar { char _char = -1; uint16_t attributes = 17; int color(); CChar& color(int color); bool hasStyle(int type); CChar& setStyle(int type, bool active); void append(std::stringstream&,CChar*); }; class CString{ public: CString(const CString&); CString(); CString(std::string); CString(std::vector<CChar>&); //CString& operator+(const CString&); CString& operator+=(const CString&); CString& operator+=(const CChar); CString& operator+=(const char*); CChar&operator[](const int); std::string str(); //private: std::vector<CChar> chars; };
true
1a5c66ba1e5dfe1323e0bb71896ce5c72c771833
C++
Twinklebear/Charm-experiments
/pathtracer/pt/plane.cpp
UTF-8
1,452
2.6875
3
[ "MIT" ]
permissive
#include "plane.h" namespace pt { Plane::Plane(const glm::vec3 &center, const glm::vec3 &normal, float half_length, std::shared_ptr<BxDF> &brdf) : Geometry(brdf), center(center), normal(glm::normalize(normal)), half_length(half_length) {} bool Plane::intersect(Ray &ray) const { const float d = -glm::dot(center, normal); const float v = glm::dot(ray.dir, normal); if (std::abs(v) < 1e-6f){ return false; } const float t = -(glm::dot(ray.origin, normal) + d) / v; if (t > ray.t_min && t < ray.t_max){ const glm::vec3 pt = ray.origin + ray.dir * t; // Compute the tangent and bitangent glm::vec3 tan, bitan; coordinate_system(normal, tan, bitan); if (std::abs(glm::dot(pt - center, tan)) <= half_length && std::abs(glm::dot(pt - center, bitan)) <= half_length) { ray.t_max = t; return true; } else { return false; } } return false; } void Plane::get_shading_info(const Ray &ray, DifferentialGeometry &dg) const { dg.point = ray.origin + ray.dir * ray.t_max; dg.normal = normal; dg.brdf = brdf.get(); coordinate_system(normal, dg.tangent, dg.bitangent); } BBox Plane::bounds() const { glm::vec3 tan, bitan; coordinate_system(normal, tan, bitan); const glm::vec3 min_pt = center - half_length * tan - half_length * bitan - 0.001 * normal; const glm::vec3 max_pt = center + half_length * tan + half_length * bitan + 0.001 * normal; return BBox(glm::min(min_pt, max_pt), glm::max(min_pt, max_pt)); } }
true
476cbdcf4764184a06f9e59cb3bc1ec6bf6be151
C++
anirul/JavascriptIntegration
/javascript/duktape_impl.h
UTF-8
1,066
2.5625
3
[ "MIT" ]
permissive
#pragma once #include <memory> #include <string> #include <vector> #include <map> #include <any> #include <istream> #include "javascript.h" #include "duktape.h" namespace javascript { class DuktapeImpl : public Javascript { public: DuktapeImpl(); virtual ~DuktapeImpl(); void AddFromString(const std::string& source) override; void AddFromStream(std::istream& is) override; const std::size_t GetPrintLines() const override; const std::string GetPrintString() override; const std::any CallFunction( const std::string& func, const std::vector<std::any>& args = {}) override; const std::any CallMethod( const std::string& obj, const std::string& func, const std::vector<std::any>& args = {}) override; protected: const std::string GetTopType(int id = -1) const; const std::size_t SetArgs( const std::vector<std::any>& args) const; const std::any GetReturn() const; private: duk_context* p_duk_ctx_ = nullptr; static std::map<duk_context*, std::vector<std::string>> s_ctx_strings_; }; } // End namespace javascript.
true
540831ebde476b3b0a044732243caf684477e2d8
C++
jeffphi/advent-of-code-2018
/jeff/day-07/part-2.cpp
UTF-8
4,635
3.015625
3
[ "MIT" ]
permissive
#include <iostream> #include <vector> #include <string> #include "jefflib.h" #include <boost/tokenizer.hpp> #include <map> #include <set> #include <iomanip> #include <thread> #include <chrono> using namespace std; using namespace boost; struct stepInfo_t { set<char> prereqs; bool workerAssigned = false; int clock = 0; }; void ClearScreen() { cout << string( 100, '\n' ); } void printSteps(map<char, stepInfo_t > &steps){ ClearScreen(); for(const auto item : steps){ //cout << item.first << ": " << item.second.size() << endl; cout << item.first; if(item.second.workerAssigned){ cout << " w "; } else { cout << " . "; } cout << setfill('0') << setw(2) << item.second.clock; cout << " ["; for(auto prereq : item.second.prereqs){ cout << prereq; } cout << "]" << endl; } cout << endl; } int main() { vector<string> vect; if(GetStringInput(vect)){ cout << "Got data!" << endl; cout << endl; } else { cout << "Failed to read input :( " << endl; return -1; } map<char, stepInfo_t > steps; // .....5..............................36 // Step V must be finished before step M can begin. for (const string line : vect) { char c = line[36]; char p = line[5]; //cout << c << " deps " << p << endl; steps[c].prereqs.insert(p); // So, items without prereqs don't have dependencies, so make sure they get // have entries created as well... steps[p]; } string dummy; getline(cin, dummy); //cout << "Working..." << endl; int elapsedTime = 0; int workers = 5; while(!steps.empty()){ printSteps(steps); cout << "Elapsed time: " << elapsedTime << endl; this_thread::sleep_for (std::chrono::milliseconds(100)); // Find ready step char ready = ' '; // Assing workers to any ready steps //cout << "Assigning workers..." << endl; for(auto& item : steps){ if(item.second.prereqs.size() == 0 && !item.second.workerAssigned && workers > 0){ ready = item.first; item.second.workerAssigned = true; workers--; // ASCII A = 65, so always subtract 4 item.second. clock = int(item.first) - 4; } } // Decrement clocks //cout << "Decrementing clocks..." << endl; for(auto& item : steps){ if(item.second.clock > 0){ item.second. clock -= 1; } } // If any steps are done, remove them and free up workers! //cout << "Checking for completed steps, size = " << steps.size() << endl; for(auto& item : steps){ if(item.second.workerAssigned && item.second.clock == 0){ workers++; // Remove step from other step's dependendencies char ready = item.first; printSteps(steps); //cout << "Removing " << ready << " from deps" << endl; for(auto& item : steps){ auto it = item.second.prereqs.find(ready); if(it != item.second.prereqs.end()){ //cout << "Erasing " << ready << ", Num erased: " << item.second.erase(*it) << endl; item.second.prereqs.erase(*it); } } //Remove step from list of steps //cout << "Removing " << ready << " from steps" << endl; auto it = steps.find(ready); if(it != steps.end()){ //cout << "Erasing " << ready; steps.erase(it); //cout << "... Erased!" << endl; /* // HACKING if(ready == 'M'){ cout << "Removed M. A clock: " << steps['A'].clock << endl; cout << "Elapsed time: " << elapsedTime << endl; } */ } else { cout << "Hmm, couldn't remove " << ready << "??" << endl; } } //cout << "Continuing loop..." << endl; } // Increment overall elapsed time //cout << "Incrementing time from " << elapsedTime << endl; elapsedTime++; } cout << "Elapsed time: " << elapsedTime << endl; }
true
2848cc2a2068337f0cb74b4f5bb859b44505167b
C++
eefortunato/Cplusplus-Codes
/Project5/SAE.cpp
UTF-8
3,981
3.40625
3
[]
no_license
/** * @file * @author Eric Fortunato * @version 1.0 * * @section DESCRIPTION * * Source file for SAE class implementation. */ #include <sstream> #include <exception> #include <stdexcept> #include <cmath> #include "SAE.h" using namespace std; /** * Default constructor that initializes feet and dimension */ SAE::SAE():feet(0), dimension(1) { // TODO Auto-generated constructor stub } /** * Constructor that initializes feet and inches and dimension and converts everything to feet * @param feet double value for the feet * @param inches double value for the inches */ SAE::SAE(double feet, double inches): feet(0), dimension(1){ this->feet += feet + convertToFeet(inches); } /** * Operator overloading for addition * @param magnitudeB a SAE magnitude * @return result the result of the operation as a SAE object */ SAE SAE::operator+(const SAE &magnitudeB){ SAE result(*this); return result+=magnitudeB; } /** * Operator overloading for += * @param magnitudeB a SAE magnitude * @return *this the result of the operation as a SAE object */ SAE SAE::operator+=(const SAE &magnitudeB){ feet+=magnitudeB.getFeet(); return *this; } /** * Operator overloading for subtraction * @param magnitudeB a SAE magnitude * @return result the result of the operation as a SAE object */ SAE SAE::operator-(const SAE &magnitudeB){ SAE result(*this); return result-=magnitudeB; } /** * Operator overloading for -= * @param magnitudeB a SAE magnitude * @return *this the result of the operation as a SAE object */ SAE SAE::operator-=(const SAE &magnitudeB){ feet-=magnitudeB.getFeet(); return *this; } /** * Operator overloading for multiplication * @param magnitudeB a SAE magnitude * @return result the result of the operation as a SAE object */ SAE SAE::operator*(const SAE &magnitudeB){ SAE result(*this); return result*=magnitudeB; } /** * Operator overloading for *= * @param magnitudeB a SAE magnitude * @return *this the result of the operation as a SAE object */ SAE SAE::operator*=(const SAE &magnitudeB){ dimension+=magnitudeB.getDimension(); feet *= magnitudeB.getFeet(); return *this; } /** * Operator overloading for division * @param magnitudeB a SAE magnitude * @return result the result of the operation as a SAE object */ SAE SAE::operator/(const SAE &magnitudeB){ SAE result(*this); return result/=magnitudeB; } /** * Operator overloading for /= * @param magnitudeB a SAE magnitude * @return *this the result of the operation as a SAE object */ SAE SAE::operator/=(const SAE &magnitudeB){ if(dimension <= magnitudeB.getDimension()){ throw std::underflow_error("Not enough dimensions!"); } dimension-=magnitudeB.getDimension(); feet /= magnitudeB.getFeet(); return *this; } /** * Method for converting inches to feet * @param inches double value for the iches * @return inches/12 the value in feet */ double SAE::convertToFeet(double inches){ return inches/12; } /** * Getter method for feet * @return feet the value of feet */ double SAE::getFeet()const{ return feet; } /** * Getter method for dimension * @return dimension the value for dimension */ double SAE::getDimension()const{ return dimension; } /** * Operator overloading for << * @param os output source * @param magnitudeB a SAE magnitude * @return os the stream to print as an output stream */ ostream& operator<<(std::ostream& os, const SAE& sae ){ stringstream iss; if(sae.dimension==1){ int justFeet = (int)sae.feet; // Stores the integer part of the feet value double feetDecimal= sae.feet-justFeet; // Stores the decimal part of the feet value double justInches = feetDecimal*12; // Converts the decimal part of the feet value to inches iss << justFeet << " feet, " << justInches << " inches"; os << iss.str(); return os; } if(sae.feet > -1 && sae.feet < 1){ iss << sae.feet*12 << " inches^"; } else{ iss << sae.feet << " feet^"; iss << sae.dimension; } os << iss.str(); return os; }
true
235b7fbfe7321dfeb1974678e1e1a299cf41a811
C++
Murgowt/CodeBase
/Freelancing/cppAssignment.cpp
UTF-8
280
2.640625
3
[]
no_license
#include<iostream> using namespace std; int main(){ double dec1 = 2.5; double dec2 = 3.8; double *p, *q; p = &dec1; *p = dec2 - dec1; q = p; *q = 10.0; *p = 2 * dec1 + (*q); q = &dec2; dec1 = *p + *q; cout << dec1 << " " << dec2 << endl; cout << *p << " " << *q << endl; }
true
521fa437b27365e7a4758d6827f3cdbed643192e
C++
zee7985/LeetCode
/Random/Find Permutation-Arrays(I,D).cpp
UTF-8
1,355
3.578125
4
[]
no_license
Given a positive integer n and a string s consisting only of letters D or I, you have to find any permutation of first n positive integer that satisfy the given input string. D means the next number is smaller, while I means the next number is greater. Notes Length of given string s will always equal to n - 1 Your solution should run in linear time and space. Example : Input 1: n = 3 s = ID Return: [1, 3, 2] Two Solution:With different ordering //1. //n : 5 // s = DIDD // Return: [5, 1, 4, 3, 2] vector<int> Solution::findPerm(const string A, int B) { int l=1,r=B; vector<int> ans; for(int i=0;i<A.length();i++) { if(A[i]=='I' ) { ans.push_back(l); l++; } else { ans.push_back(r); r--; } } ans.push_back(l); return ans; } //2.Stack //n : 5 // s = DIDD // Return: [2,1,5,4,3] vector<int> Solution::findPerm(const string A, int B) { vector<int> ans; int n = A.size(); stack<int>s; for(int i=0;i<n;i++){ s.push(i+1); if(A[i]=='I'){ while(!s.empty()){ ans.push_back(s.top()); s.pop(); } } } s.push(n+1); while(!s.empty()){ ans.push_back(s.top()); s.pop(); } return ans; }
true
58f1c87e829453deeb8f107ed759e0accb793240
C++
etlapale/tencatl
/include/tencatl/lexer.h
UTF-8
2,136
3.203125
3
[]
no_license
#pragma once #include <memory> #include <queue> #include <stack> namespace tencatl { enum class Token { NoToken, Double, Long, Int, String, Variable, Symbol, Operator, EndOfExpression, BlockBegin, BlockEnd, EndOfFile }; std::ostream& operator<<(std::ostream& os, Token token); class Lexer { public: Lexer(); /** * Create a lexer for the given input file. */ Lexer(const std::string& path); void set_source(std::unique_ptr<std::istream> input); /// Read the next token from the input stream. Token read_token(); /// Return the last read token type. Token current_token() const { return last_token; } const std::string& variable_name() const { return last_var; } char symbol() const { return last_sym; } const std::string& oper() const { return last_oper; } long int_value() const { return last_int; } double float_value() const { return last_float; } const std::string& string() const { return last_string; } private: //// Input stream. std::unique_ptr<std::istream> is; /// Current input filename. std::string filename; /// Current character being read. char c; /// Whether we are at the beginning of a line. bool bol = true; /// Whether the end of file was read. bool eofed = false; /// Braces context. std::stack<char> braces; // Indentation stack. std::stack<std::size_t> indent; // Number of closing blocks to be generated std::size_t closing_blocks = 0; // Tokens to be emitted in the future. std::queue<Token> to_emit; bool maybe_expend = false; std::size_t skipped_blocks = 0; /// Last returned token. Token last_token = Token::NoToken; /// Name of the last variable token. std::string last_var; std::string last_oper; std::string last_string; /// Name of the last variable token. char last_sym; double last_float; long last_int; char opening_brace[128]; /** * Read one character from the input. * * The read character is stored into the private variable ‘c’ and * also returned by value. */ char get_char(); }; } // namespace tencatl
true
5c831a643bb512aa046f915e883f5a66b0f869f8
C++
kapyar/---
/KR2013/KR2013/Products.h
WINDOWS-1251
1,913
3.453125
3
[]
no_license
// Goods // Product. // . #ifndef _PRODUCTS_H #define _PRODUCTS_H class Products : public Goods { private: Date _exDate; virtual const Date& do_get_date_of_expiry()const{return _exDate;} virtual void do_set_date_of_expiry(const Date& d){_exDate = d;return;} virtual void do_get_spec()const { Goods::showBasic(); cout<<"Date of expiry: "<<_exDate<<endl; return; } public: class BadProducts; Products* clone(){return new Products(*this);}// explicit Products(size_t id = 0, const Date& d = Date(), const Money& p = Money(), string name="unknown", string other="unknown", Date exd = Date()) : Goods(id,d,p,name,other), _exDate(exd) { #ifndef NDEBUG cout<<"Constructor Products"<<endl; #endif } Products (const Products& g) :Goods((g.getCode()),(g.getDate()), (g.getPrice()),(g.getName()),(g.getOther())), _exDate(g.getDateOfExpiry()) { #ifndef NDEBUG cout<<"Copyconstructor Products"<<endl; #endif } virtual ~Products() { #ifndef NDEBUG cout<<"Destructor Goods"<<endl; #endif } const Date& getDateOfExpiry() const { return do_get_date_of_expiry(); } ostream& show (ostream & os) const { os<<"Code: "<<getCode()<<endl; os<<"Date of issue: "<<getDate()<<endl; os<<"Price: "<<getPrice()<<endl; os<<"Name: "; for(size_t i = 0;i<getName().length();++i) os<<getName()[i]; os<<endl; os<<"Other: "; for(size_t i = 0;i<getOther().length();++i) os<<getOther()[i]; os<<endl; os<<"Date of expiry: "<<getDateOfExpiry()<<endl; return os; } }; //inline ostream& operator<<(ostream& os, const Products& g) //{ // return g.show(os); //} #endif
true
81567b0533f6ef05c2eb3cdf44483e9b7dcf0cf0
C++
shrey/templates_cpp
/ConceptsAndQuestions/BinarySearch/binary_search_stl.cpp
UTF-8
1,311
2.84375
3
[]
no_license
//Shrey Dubey //Contact Me at wshrey09@gmail.com #include<iostream> #include<string> #include<algorithm> #include<map> #include<unordered_map> #include<vector> #include<set> #include<list> #include<iomanip> #include<queue> #include<stack> #define prDouble(x) cout<<fixed<<setprecision(10)<<x //to print decimal numbers #define pb push_back #define F first #define S second #define umap unordered_map #define fo(x,y) for(int i = x; i<y; i++) #define fo(n) for(int i = 0; i<n; i++) #define fnd(stl, data) find(stl.begin(), stl.end(), data) using namespace std; typedef long long ll; int modulo = 1e9 + 7; int main(){ int arr[] = {20,30,40,40,40,50,100,1100}; int n = sizeof(arr)/sizeof(int); int key; cin>>key; bool present = binary_search(arr,arr+n,key); if(present){ cout<<"Present"<<endl; } else{ cout<<"Not Present"<<endl; } //to find the pos of the occurance auto it = lower_bound(arr,arr+n,key); cout<<"Lower Bound: "<<(it-arr)<<endl; it = upper_bound(arr,arr+n,key); cout<<"Upper Bound: "<<(it-arr-1)<<endl; //returns occurance of first el greater than key, so do -1 //can also be used to calculate frequency but lower bound gives first el >= key and upper bound gives first el>key //use binary search to check if el is present }
true
37a9c267955335359fd4d61663552dc4aa7c0d89
C++
rajephon/programmers_training
/cpp/level3_longest_palindrome.cpp
UTF-8
1,047
3.140625
3
[ "MIT" ]
permissive
// // level3_longest_palindrome.cpp // programmers_training // // Created by Chanwoo Noh on 2018. 06. 24.. // Copyright © 2018년 Chanwoo Noh. All rights reserved. // #include <iostream> #include <string> using namespace std; int solution(string s) { int answer=1; if (s.length() <= 1) { return (int)s.length(); } for (int i = 0; i < s.length(); i++) { bool e1 = true; bool e2 = true; for (int j = i-1; j >= 0; j--) { int t1 = i + i - j; int t2 = t1 - 1; if ((t1 > s.length() - 1) || (s.at(j) != s.at(t1))) e1 = false; if ((t2 > s.length() - 1) || (s.at(j) != s.at(t2))) e2 = false; if (!e1 && !e2) break; int l1 = t1 - j + 1; int l2 = t2 - j + 1; if (e1 && l1 > answer) { answer = l1; } if (e2 && l2 > answer) { answer = l2; } } } return answer; }
true
5585a4b3ee7449bde077a0c02bab53212c892c99
C++
kamonson/BibleReaderCpp
/source_code/Books.cpp
UTF-8
8,719
3.1875
3
[]
no_license
#include <iostream> #include "Books.h" #include <string> #include <vector> #include <fstream> #include <sstream> Select_Book::Select_Book(){}; Bible::Bible(){}; void Bible::Bible_Select() { //Master Class-choose between saved data, Bibles, book system ("CLS");//for looking good int user_selection; v_verse.clear();//for each loop clear the stored data to reuse v_chapter.clear();//for each loop clear the stored data to reuse v_book.clear();//for each loop clear the stored data to reuse int s_born; cout << "Would you like to read from the Bible or Stored notes?\n" << endl ;//for cout << "1)Bible\n" << endl ; cout << "2)Stored Notes\n" << endl ; cout << "3)Books of the Bible List\n" << endl; cout << "0)Exit Program\n" << endl ; cin >> s_born; cin.clear ( ) ; //ignore junk input cin.ignore ( INT_MAX, '\n' ) ;//ignore junk system ( "cls" ) ; switch (s_born)//switch menue for selection { case 1: //select how you want to read the bible { cout << "Would you like to search by:?\n" << endl; cout << "1)Book\n" << endl; cout << "2)Chapter\n" << endl; cout << "3)Verse\n" << endl; cin >> user_selection; //if statements selection instead of an additional switch menu if (user_selection == 1) { cin.clear ( ) ; //ignore junk input cin.ignore ( INT_MAX, '\n' ) ;//ignore junk system ("CLS");//for looking good cout << "Which book would you like to read?\n"; cin >> s_book; Pcon();//run CHAPTER/PSALM search to create chapters in the vector read_book(); //read entire book function break; } if (user_selection == 2)//select chapters to read { cin.clear ( ) ; //ignore junk input cin.ignore ( INT_MAX, '\n' ) ;//ignore junk system ("CLS");//for looking good cout << "Which book would you like to read?\n"; cin >> s_book; Pcon();//run CHAPTER/PSALM search to create chapters in the vector cout << "Which chapter would you like to start with?\n"; cin >> i_chapter_b; cout << "Which chapter would you like to end with?\n"; cin >> i_chapter_e; read_chapter(); //read chapter function break; } if (user_selection == 3)//select chapter and verses to read { cin.clear ( ) ; //ignore junk input cin.ignore ( INT_MAX, '\n' ) ;//ignore junk system ("CLS");//for looking good cout << "Which book would you like to read?\n"; cin >> s_book; Pcon();//run CHAPTER/PSALM search to create chapters in the vector cout << "Which Chapter would you like to read?\n"; cin >> i_chapter; cout << "Which verse would you like to start at?\n"; cin >> i_verse_b; cout << "Which verse would you like to end at?\n"; cin >> i_verse_e; read_verses(); //read verse function break; } else { cin.clear ( ) ; //ignore junk input cin.ignore ( INT_MAX, '\n' ) ;//ignore junk system ("CLS");//for looking good cout << "Pelase make a valid selection\n"; Bible_Select(); //wrong selection takes you to the begining } return; break; } case 2: { Stored s1; s1.open(); return; break; } break; case 0: return; break; default: cout << "Please make a valid selection " ; Bible_Select(); break; } }; void Bible::Pcon()//changes if searches are for CHAPTER of VERSE depending on book { if (s_book == ("Psalms")) {c_or_p = "PSALM ";} else {c_or_p = "CHAPTER ";} }; void Bible::read_book()//read out entire book { cin.clear ( ) ; //ignore junk input cin.ignore ( INT_MAX, '\n' ) ;//ignore junk system ("CLS"); //formating, cosmetic only fstream file( "AV1611Text\\"+s_book+".txt", ios::in); //open book if (file.fail()) { cout << "Failed to open " << s_book << endl; Bible_Select(); } //something here to read out from chapter to chapter assign a variable, then push back into vector while (!file.eof()) //go till there's no more. { string verses; while (getline (file, verses)) //get the whole verse line from the file { v_book.push_back (verses); cout << verses <<endl; //cout the verse, end the line, restart the loop } } cout << endl << "That is the end of the book\n\nWould you like to go back to the menu (m) or exit (e)?\n"; //basic menu select char selection; cin >> selection; if (selection == 'm') //main menu { Bible_Select(); } else { } file.close(); //close for space }; void Bible::read_chapter()//need to close book still { system ("CLS"); //formating only string format_space = "\n"; //add to vector store for proper format string verses; //string to hold the entire collection of verses string chapter;//sring to hold the chapter fstream file( "AV1611Text\\"+s_book+".txt", ios::in);//open book if (file.fail())//if book does not open { cout << "Failed to open " << s_book << ".txt"<< endl; //if broke recycle Bible_Select(); } while (!file.eof())//search to end of file { while (getline(file, chapter))//add lines from book to chapter { if (chapter.find (c_or_p) != string::npos)//check to see if file contains CHAPTER of PSALM { v_chapter.push_back (verses);//When CHAPTER/PSALM found add string to chapter vector verses.clear();//Empty verses string for next element of vector break; } verses += (chapter + format_space);//Add line from book and a new line to verses to be stored in chapter vector when CHAPTER/PSALM found } } for (int i = i_chapter_b; i < i_chapter_e + 1; i++) //cout put the begining and end points for chapter { cout << v_chapter[i] << endl; } cout << endl << "Would you like to go back to the menu (m), save to notes (s) or exit (e)?\n"; //menu to save or restart char selection; cin >> selection; if (selection == 'm') //menu { Bible_Select(); } if (selection =='s') //save { cout << "Please assign a name for this file\n"; cin >> schapters; fstream bfile(schapters + ".txt", ios::app); //write to user named file if (bfile.fail()) { cout << "Error saving " << schapters << endl; //if broke return to main Bible_Select(); } for (int i = i_chapter_b; i < i_chapter_e + 1; i++) //cout put the begining and end points for chapter { bfile << v_chapter[i] << endl; } bfile.close(); cout << schapters << " saved to notes" << endl; } else { } file.close(); //close to save space }; void Bible::read_verses()//need to close book still { system ("CLS"); string format_space = "\n"; //add to vector store for proper format string verses; //string to hold the entire collection of verses string chapter;//sring to hold the chapter fstream file( "AV1611Text\\"+s_book+".txt", ios::in);//open book if (file.fail())//if book does not open { cout << "Failed to open " << s_book << ".txt"<< endl; //start over if wrong selection Bible_Select(); } while (!file.eof())//search to end of file { while (getline(file, chapter))//add lines from book to chapter { if (chapter.find (c_or_p) != string::npos)//check to see if file contains CHAPTER of PSALM { v_chapter.push_back (verses);//When CHAPTER/PSALM found add string to chapter vector verses.clear();//Empty verses string for next element of vector break; } verses += (chapter + format_space);//Add line from book and a new line to verses to be stored in chapter vector when CHAPTER/PSALM found } } system("CLS");//clear screen s_chapter = v_chapter [i_chapter]; //set s_chapter to be the user selected chapter from chapter vector stringstream vfile (s_chapter , ios::in); //like fstream but for strings while (getline(vfile, s_verse)) //get lines from string and output as s_verse to be stored in vector { v_verse.push_back (s_verse); //store verses in vector } for (int k = i_verse_b -=1; k < i_verse_e; k++){ cout << v_verse [k] << endl;//Output the verse (-1 to start in the correct location) from vector that the user searched for within the chapter } cout << endl << "Would you like to go back to the menu (m), save to notes (s) or exit (e)?\n"; char selection; cin >> selection; if (selection == 'm') //main menu { Bible_Select(); } if (selection =='s') //save selection to notes { cout << "Please assign a name for this file\n"; cin >> sverses; fstream bfile(sverses + ".txt", ios::app); //write to user named file without overwritng if (bfile.fail()) { cout << "Error saving " << sverses << endl; Bible_Select(); } for (int k =i_verse_b; k < i_verse_e; k++){ bfile << endl << v_verse [k] << endl;//save the verse (-1 to start in the correct location) from vector that the user searched for within the chapter to user named file } cout << sverses << " saved to notes" << endl; bfile.close(); } else { } file.close(); //restart };
true
f00fe5d69d75c576c86312b236b09938651dcfd3
C++
StewiiE/OpenGL_SDL-Dodgeball_Project
/OpenGL_SDL Dodgeball Project/object3DS.h
UTF-8
932
2.84375
3
[]
no_license
#pragma once #ifndef _OBJECT3DS_H_ #define _OBJECT3DS_H_ #include "Commons.h" #include <string> #include <SDL.h> using std::string; class Object3DS { public: Object3DS(Vector3D startPosition, string modelFileName, string texturePath); ~Object3DS() {} void Update(float deltaTime, SDL_Event e); void Render(); //Load 3ds file void LoadModel(); //Load texture for this model. void LoadTexture(string texturePath); private: Vector3D mPosition; float octopusRotation; char fileName[20]; char textureName[20]; obj_type object; Vector3D position = Vector3D(); Vector3D forward = Vector3D(); Vector3D up = Vector3D(); Vector3D right = Vector3D(); // horizontal angle : toward -Z float yaw = 3.14f; // vertical angle : 0, look at the horizon float pitch = 0.0f; bool movingRight = false; bool movingLeft = false; bool movingForward = false; bool movingBackward = false; }; #endif //_OBJECT3DS_H_
true
81914e27f27791da4c701c23461b0e866bd40ccc
C++
tsydd/missile-win32
/Controller.cpp
UTF-8
4,360
2.625
3
[]
no_license
#include "Controller.h" #include <windows.h> #define VK_C 0x43 // not defined in winuser.h enum class KeyEvent { UNKNOWN, EXIT, LEFT_PRESSED, LEFT_RELEASED, RIGHT_PRESSED, RIGHT_RELEASED, UP_PRESSED, UP_RELEASED, DOWN_PRESSED, DOWN_RELEASED, FIRE_PRESSED, FIRE_RELEASED }; enum class DeviceState { MOVE_LEFT, MOVE_RIGHT, MOVE_UP, MOVE_DOWN, STOP, START_FIRE, FIRE, STOP_FIRE, }; KeyEvent translateEvent(KEY_EVENT_RECORD& keyEvent) { switch (keyEvent.wVirtualKeyCode) { case VK_C: if (keyEvent.dwControlKeyState & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) return KeyEvent::EXIT; break; case VK_LEFT: return keyEvent.bKeyDown ? KeyEvent::LEFT_PRESSED : KeyEvent::LEFT_RELEASED; case VK_RIGHT: return keyEvent.bKeyDown ? KeyEvent::RIGHT_PRESSED : KeyEvent::RIGHT_RELEASED; case VK_UP: return keyEvent.bKeyDown ? KeyEvent::UP_PRESSED : KeyEvent::UP_RELEASED; case VK_DOWN: return keyEvent.bKeyDown ? KeyEvent::DOWN_PRESSED : KeyEvent::DOWN_RELEASED; case VK_SPACE: return keyEvent.bKeyDown ? KeyEvent::FIRE_PRESSED : KeyEvent::FIRE_RELEASED; default: break; } return KeyEvent::UNKNOWN; } DeviceState getNewDeviceState(DeviceState currentState, KeyEvent event) { switch (event) { case KeyEvent::LEFT_PRESSED: return DeviceState::MOVE_LEFT; case KeyEvent::LEFT_RELEASED: if (currentState == DeviceState::MOVE_LEFT) return DeviceState::STOP; break; case KeyEvent::RIGHT_PRESSED: return DeviceState::MOVE_RIGHT; case KeyEvent::RIGHT_RELEASED: if (currentState == DeviceState::MOVE_RIGHT) return DeviceState::STOP; break; case KeyEvent::UP_PRESSED: return DeviceState::MOVE_UP; case KeyEvent::UP_RELEASED: if (currentState == DeviceState::MOVE_UP) return DeviceState::STOP; break; case KeyEvent::DOWN_PRESSED: return DeviceState::MOVE_DOWN; case KeyEvent::DOWN_RELEASED: if (currentState == DeviceState::MOVE_DOWN) return DeviceState::STOP; break; case KeyEvent::FIRE_PRESSED: switch (currentState) { case DeviceState::FIRE: return DeviceState::STOP_FIRE; case DeviceState::START_FIRE: return currentState; default: return DeviceState::START_FIRE; } case KeyEvent::FIRE_RELEASED: if (currentState == DeviceState::START_FIRE) return DeviceState::FIRE; break; } return currentState; } void sendCommand(DeviceApi* device, DeviceState state) { switch (state) { case DeviceState::MOVE_LEFT: device->moveLeft(); break; case DeviceState::MOVE_RIGHT: device->moveRight(); break; case DeviceState::MOVE_UP: device->moveUp(); break; case DeviceState::MOVE_DOWN: device->moveDown(); break; case DeviceState::START_FIRE: device->fire(); break; case DeviceState::STOP: device->stop(); break; case DeviceState::STOP_FIRE: device->stopFire(); default: break; } } void handleInput(DeviceApi* device) { HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE); if (hStdin == INVALID_HANDLE_VALUE) ExitProcess(1); DWORD fdwSaveOldMode; if (!GetConsoleMode(hStdin, &fdwSaveOldMode)) ExitProcess(2); DWORD fdwMode; fdwMode = ENABLE_WINDOW_INPUT | ENABLE_MOUSE_INPUT; if (!SetConsoleMode(hStdin, fdwMode)) ExitProcess(3); bool exit = false; DeviceState state = DeviceState::STOP; while (!exit) { DWORD cNumRead; INPUT_RECORD irInBuf[128]; if (!ReadConsoleInput(hStdin, irInBuf, 128, &cNumRead)) ExitProcess(4); for (DWORD i = 0; i < cNumRead; i++) { if (irInBuf[i].EventType != KEY_EVENT) continue; KEY_EVENT_RECORD& nativeKeyEvent = irInBuf[i].Event.KeyEvent; KeyEvent keyEvent = translateEvent(nativeKeyEvent); if (keyEvent == KeyEvent::UNKNOWN) continue; if (keyEvent == KeyEvent::EXIT) { exit = true; break; } DeviceState newState = getNewDeviceState(state, keyEvent); if (newState == state) continue; state = newState; sendCommand(device, state); } } }
true
3494a10adabc3ebb66a7536202cd21412dd9bbe1
C++
Yamoneta/Stuff-for-class
/802b.cpp
UTF-8
382
3.5
4
[]
no_license
#include <iostream> using namespace std; int main() { int num1, num2, product, count; product = 0; count = 1; cout << "What is the first number: "; cin >> num1; cout << "What is the second number: "; cin >> num2; while (count <= num1) { product += num2; ++count; } cout << num1 << " times " << num2 << " = " << product << endl; return 0; }
true
12b57ff32bfbeb96a9ac5bd84a21d577fd68e025
C++
adityaiiitL/OOM-Project
/admin.cpp
UTF-8
82,782
3.234375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; #include "admin.h" void admin::lib_add_book() { string book_name; cout << "Enter the name of the book " << endl; cin >> book_name; int choice; cout << "1 for student book" << endl; cout << "2 for teacher book" << endl; cin >> choice; obj_library.add_book(book_name, choice); } void admin::get_id_book() { string book_name; cout << "Enter the name of the book " << endl; cin >> book_name; int choice; cout << "1 for student book" << endl; cout << "2 for teacher book" << endl; cin >> choice; if (choice == 1) { int ans = obj_library.get_id_student(book_name); } else if (choice == 2) { int ans = obj_library.get_id_teacher(book_name); } } int admin::get_school_balance() { int balance = obj_bank.get_school_balance(); return balance; } int admin::student_id = 1000; int admin::staff_id = 2000; void admin::admin_functions() { cout << "Welcome Admin here!! How can I help you " << endl; cout << "MENU" << endl; cout << "-----------------------" << endl; int choice; cout << "Press 1 to add student " << endl; cout << "Press 2 to add teacher " << endl; cout << "Press 3 to add staff " << endl; cout << "Press 4 to remove student " << endl; cout << "Press 5 to remove teacher " << endl; cout << "Press 6 to remove staff " << endl; cout << "Press 7 to add class monitor (student) " << endl; cout << "Press 8 to add class teacher (teacher) " << endl; cout << "Press 9 to add leader (student) " << endl; cout << "Press 10 to remove class monitor (student) " << endl; cout << "Press 11 to remove class teacher (teacher) " << endl; cout << "Press 12 to remove leader (student) " << endl; cout << "Press 13 to pay the staff" << endl; cout << "Press 14 to get the school balance" << endl; cout << "Press 15 to add book" << endl; cout << "Press 16 to check id of book" << endl; cout << "Press 17 to display student list " << endl; cout << "Press 18 to display class monitor list " << endl; cout << "Press 19 to display leader list" << endl; cout << "Press 20 to display staff list " << endl; cout << "Press 21 to display teacher list " << endl; cout << "Press 22 to display class teacher list " << endl; cout << "Press 23 to display library contents " << endl; cout << "Press 24 to exit" << endl; cout << "Enter your choice " << endl; cin >> choice; if (choice == 1) { add_student(); } else if (choice == 2) { add_teacher(); } else if (choice == 3) { add_staff(); } else if (choice == 4) { remove_student(); } else if (choice == 5) { remove_teacher(); } else if (choice == 6) { remove_staff(); } else if (choice == 7) { add_class_monitor(); } else if (choice == 8) { add_class_teacher(); } else if (choice == 9) { add_leader(); } else if (choice == 10) { remove_class_monitor(); } else if (choice == 11) { remove_class_teacher(); } else if (choice == 12) { remove_leader(); } else if (choice == 13) { pay_staff(); } else if (choice == 14) { int x = obj_bank.get_school_balance(); cout << x << endl; } else if (choice == 15) { lib_add_book(); } else if (choice == 16) { get_id_book(); } else if (choice == 17) { int size = student_list.size(); cout << "List size :- " << size << endl; for (int i = 0; i < size; i++) { cout << "Student number " << i + 1 << endl; student_list[i].display(); } } else if (choice == 18) { int size = class_monitor_list.size(); cout << "List size :- " << size << endl; for (int i = 0; i < size; i++) { cout << "Class monitor number " << i + 1 << endl; class_monitor_list[i].display(); } } else if (choice == 19) { int size = leader_list.size(); cout << "List size :- " << size << endl; for (int i = 0; i < size; i++) { cout << "Leader number " << i + 1 << endl; leader_list[i].display(); } } else if (choice == 20) { int size = staff_list.size(); cout << "List size :- " << size << endl; for (int i = 0; i < size; i++) { cout << "Staff number " << i + 1 << endl; staff_list[i].display(); } } else if (choice == 21) { int size = teacher_list.size(); cout << "List size :- " << size << endl; for (int i = 0; i < size; i++) { cout << "teacher number " << i + 1 << endl; teacher_list[i].display(); } } else if (choice == 22) { int size = class_teacher_list.size(); cout << "List size :- " << size << endl; for (int i = 0; i < size; i++) { cout << "class_teacher number " << i + 1 << endl; class_teacher_list[i].display(); } } else if (choice == 23) { obj_library.display(); } else if (choice == 24) { return; } cout << "Do you want to perform more functions < y/Y for yes > < n/N for no >"; char ch; cin >> ch; if (ch == 'y' || ch == 'Y') { admin_functions(); } else { return; } } void admin::pay_staff() { int id; cout << "Enter the id of the staff(staff/teacher/class-teacher) you want to make the payment" << endl; cin >> id; int check1 = 0; // staff int check2 = 0; // teacher int check3 = 0; // class-teacher int size = staff_list.size(); auto it = staff_list.begin(); staff *ptr; for (int i = 0; i < size; i++) { if (staff_list[i].get_staff_id() == id) { ptr = &staff_list[i]; check1 = 1; break; } it++; } int size2 = teacher_list.size(); auto it2 = teacher_list.begin(); teacher *ptr2; for (int i = 0; i < size2; i++) { if (teacher_list[i].get_staff_id() == id) { // staff_list.erase(it); ptr2 = &teacher_list[i]; check2 = 1; break; } it2++; } int size3 = class_teacher_list.size(); auto it3 = class_teacher_list.begin(); class_teacher *ptr3; for (int i = 0; i < size3; i++) { if (class_teacher_list[i].get_staff_id() == id) { ptr3 = &class_teacher_list[i]; check3 = 1; break; } it3++; } if (check1 == 1) { int amount = ptr->get_salary(); if (ptr->get_payment_done() == 1) { cout << "Payment is already done!!" << endl; } else { obj_bank.pay_payment_staff(id, amount); ptr->set_payment_done(1); } } else if (check2 == 1) { int amount = ptr2->get_salary(); // if already paid then do not pay if (ptr2->get_payment_done() == 1) { cout << "Payment is already done!!" << endl; } else { obj_bank.pay_payment_staff(id, amount); ptr2->set_payment_done(1); } } else if (check3 == 1) { int amount = ptr3->get_salary(); // if already paid then do not pay if (ptr3->get_payment_done() == 1) { cout << "Payment is already done!!" << endl; } else { obj_bank.pay_payment_staff(id, amount); ptr3->set_payment_done(1); } } else { cout << "No such staff exist " << endl; } } void admin::add_class_monitor() { class_monitor obj1; obj1.set_fee_paid(0); string str; cout << "Enter Student name :- "; cin >> str; obj1.set_name(str); string username; cout << "Enter Username :- "; cin >> username; obj1.set_username(username); student_id++; obj1.set_roll_no(student_id); string email; cout << "Enter Email :-"; cin >> email; obj1.set_email(email); string phone_no; cout << "Enter Phone No :-"; cin >> phone_no; obj1.set_phone_no(phone_no); string date_of_birth; cout << "Enter Date Of Birth :-"; cin >> date_of_birth; obj1.set_date_of_birth(date_of_birth); int standard; cout << "Enter Standard :-"; cin >> standard; obj1.set_standard(standard); class_monitor_list.push_back(obj1); } void admin ::add_leader() { leader obj1; obj1.set_fee_paid(0); string str; cout << "Enter Student name :- "; cin >> str; obj1.set_name(str); string username; cout << "Enter Username :- "; cin >> username; obj1.set_username(username); student_id++; obj1.set_roll_no(student_id); string email; cout << "Enter Email :-"; cin >> email; obj1.set_email(email); string phone_no; cout << "Enter Phone No :-"; cin >> phone_no; obj1.set_phone_no(phone_no); string date_of_birth; cout << "Enter Date Of Birth :-"; cin >> date_of_birth; obj1.set_date_of_birth(date_of_birth); int standard; cout << "Enter Standard :-"; cin >> standard; obj1.set_standard(standard); leader_list.push_back(obj1); } void admin::add_class_teacher() { class_teacher obj1; obj1.set_payment_done(0); // as soon as the object is created --> set the payment done to 0 string str; cout << "Enter name :- "; cin >> str; obj1.set_name(str); string username; cout << "Enter Username :- "; cin >> username; obj1.set_username(username); // used to set as well as upadte // therefore took sperately all staff_id++; obj1.set_staff_id(staff_id); // string designation; // cout<<"Enter designation "<<endl; // cin>>designation; // we have a teacher here obj1.set_designation("Class Teacher"); string email; cout << "Enter Email :-"; cin >> email; obj1.set_email(email); string phone_no; cout << "Enter Phone No :-"; cin >> phone_no; obj1.set_phone_no(phone_no); string address; cout << "Enter address :-"; cin >> address; obj1.set_address(address); string date_of_birth; cout << "Enter Date Of Birth :-"; cin >> date_of_birth; obj1.set_date_of_birth(date_of_birth); int salary; cout << "Enter salary :-"; cin >> salary; obj1.set_salary(salary); // unique s int x; cout << "Enter the standard you are the class teacher of " << endl; cin >> x; obj1.set_batch_no(x); class_teacher_list.push_back(obj1); } // no menu required here // you want to have these things // like they are mandatory void admin::add_student() { student obj1; // obj1.set_percentage(0); // done via setting name only obj1.set_fee_paid(0); // initalization string str; cout << "Enter Student name :- "; cin >> str; obj1.set_name(str); string username; cout << "Enter Username :- "; cin >> username; obj1.set_username(username); // used to set as well as upadte // therefore took sperately all // roll number or id we will give you this // int roll_no; // cout << "Enter Roll no :- "; // cin >> roll_no; student_id++; obj1.set_roll_no(student_id); string email; cout << "Enter Email :-"; cin >> email; obj1.set_email(email); string phone_no; cout << "Enter Phone No :-"; cin >> phone_no; obj1.set_phone_no(phone_no); string date_of_birth; cout << "Enter Date Of Birth :-"; cin >> date_of_birth; obj1.set_date_of_birth(date_of_birth); int standard; cout << "Enter Standard :-"; cin >> standard; obj1.set_standard(standard); // int status; // cout << "Enter Status :-"; // cin >> status; // obj1.update_standard(status); // 1 for pass 0 for fail // string date; int present; // cout << "Enter date :-"; // cin >> date; // cout << "Enter Present :-"; // cin >> present; // obj1.add_date_for_attandence(date, present); // date, 1 or 0 1 for present 0 for absent student_list.push_back(obj1); cout << "Student has been added successfully!" << endl; } void admin::add_staff() { staff obj1; obj1.set_payment_done(0); // as soon as the object is created --> set the payment done to 0 string str; cout << "Enter name :- "; cin >> str; obj1.set_name(str); string username; cout << "Enter Username :- "; cin >> username; obj1.set_username(username); // used to set as well as upadte // therefore took sperately all staff_id++; obj1.set_staff_id(staff_id); string designation; cout << "Enter designation " << endl; cin >> designation; obj1.set_designation(designation); string email; cout << "Enter Email :-"; cin >> email; obj1.set_email(email); string phone_no; cout << "Enter Phone No :-"; cin >> phone_no; obj1.set_phone_no(phone_no); string address; cout << "Enter address :-"; cin >> address; obj1.set_address(address); string date_of_birth; cout << "Enter Date Of Birth :-"; cin >> date_of_birth; obj1.set_date_of_birth(date_of_birth); int salary; cout << "Enter salary :-"; cin >> salary; obj1.set_salary(salary); staff_list.push_back(obj1); } void admin::add_teacher() { teacher obj1; obj1.set_payment_done(0); // as soon as the object is created --> set the payment done to 0 string str; cout << "Enter name :- "; cin >> str; obj1.set_name(str); string username; cout << "Enter Username :- "; cin >> username; obj1.set_username(username); // used to set as well as upadte // therefore took sperately all staff_id++; obj1.set_staff_id(staff_id); // string designation; // cout<<"Enter designation "<<endl; // cin>>designation; // we have a teacher here obj1.set_designation("Teacher"); string email; cout << "Enter Email :-"; cin >> email; obj1.set_email(email); string phone_no; cout << "Enter Phone No :-"; cin >> phone_no; obj1.set_phone_no(phone_no); string address; cout << "Enter address :-"; cin >> address; obj1.set_address(address); string date_of_birth; cout << "Enter Date Of Birth :-"; cin >> date_of_birth; obj1.set_date_of_birth(date_of_birth); int salary; cout << "Enter salary :-"; cin >> salary; obj1.set_salary(salary); teacher_list.push_back(obj1); } void admin::remove_student() { int id; cout << "Enter the roll number (student id) to be removed "; cin >> id; int check = 0; int size = student_list.size(); auto it = student_list.begin(); for (int i = 0; i < size; i++) { if (student_list[i].get_roll_no() == id) { student_list.erase(it); check = 1; break; } it++; } if (check) { cout << "The student with id " << id << " has been delted successfully " << endl; } else { cout << "No such student exist " << endl; } } void admin::remove_staff() { int id; cout << "Enter the staff id to be removed "; cin >> id; int check = 0; int size = staff_list.size(); auto it = staff_list.begin(); for (int i = 0; i < size; i++) { if (staff_list[i].get_staff_id() == id) { staff_list.erase(it); check = 1; break; } it++; } if (check) { cout << "The staff with id " << id << " has been delted successfully " << endl; } else { cout << "No such staff exist " << endl; } } void admin::remove_teacher() { int id; cout << "Enter the teacher id to be removed "; // staff id cin >> id; int check = 0; int size = teacher_list.size(); auto it = teacher_list.begin(); for (int i = 0; i < size; i++) { if (teacher_list[i].get_staff_id() == id) { teacher_list.erase(it); check = 1; break; } it++; } if (check) { cout << "The teacher with id " << id << " has been delted successfully " << endl; } else { cout << "No such teacher exist " << endl; } } void admin::remove_class_teacher() { int id; cout << "Enter the class teacher id to be removed "; // staff id cin >> id; int check = 0; int size = class_teacher_list.size(); auto it = class_teacher_list.begin(); for (int i = 0; i < size; i++) { if (class_teacher_list[i].get_staff_id() == id) { class_teacher_list.erase(it); check = 1; break; } it++; } if (check) { cout << "The class teacher with id " << id << " has been delted successfully " << endl; } else { cout << "No such class teacher exist " << endl; } } void admin::remove_class_monitor() { int id; cout << "Enter the roll number (student id monitor ) to be removed "; cin >> id; int check = 0; int size = class_monitor_list.size(); auto it = class_monitor_list.begin(); for (int i = 0; i < size; i++) { if (class_monitor_list[i].get_roll_no() == id) { class_monitor_list.erase(it); check = 1; break; } it++; } if (check) { cout << "The class monitor student with id " << id << " has been delted successfully " << endl; } else { cout << "No such student exist " << endl; } } void admin::remove_leader() { int id; cout << "Enter the roll number ( leade ) to be removed "; cin >> id; int check = 0; int size = leader_list.size(); auto it = leader_list.begin(); for (int i = 0; i < size; i++) { if (leader_list[i].get_roll_no() == id) { leader_list.erase(it); check = 1; break; } it++; } if (check) { cout << "The leader student with id " << id << " has been delted successfully " << endl; } else { cout << "No such student exist " << endl; } } void admin::staff_functions() { int id; cout << "Enter your staff id "; cin >> id; int check = 0; int size = staff_list.size(); staff *ptr; auto it = staff_list.begin(); for (int i = 0; i < size; i++) { if (staff_list[i].get_staff_id() == id) { ptr = &staff_list[i]; check = 1; break; } it++; } if (check == 0) { cout << "The staff with this id do not exist " << endl; } else { // designation change // address change // salary change while (1) { cout << "The staff with this " << id << " here " << endl; cout << "MENU " << endl; cout << "---------------------------------" << endl; cout << "Press 1 for change username " << endl; cout << "Press 2 for change name " << endl; cout << "Press 3 for change email " << endl; cout << "Press 4 for change phone_no " << endl; cout << "Press 5 for change date_of_birth " << endl; cout << "Press 6 for change designation " << endl; cout << "Press 7 for get username " << endl; cout << "Press 8 for get name " << endl; cout << "Press 9 for get email " << endl; cout << "Press 10 for get phone_no " << endl; cout << "Press 11 for get date_of_birth " << endl; cout << "Press 12 for get designation " << endl; cout << "Press 13 for get staff id " << endl; cout << "Press 14 for add date for attendance " << endl; cout << "Press 15 for marking todays attendance " << endl; cout << "Press 16 to set address" << endl; cout << "Press 17 to get address" << endl; cout << "Press 18 to set salary" << endl; cout << "Press 19 to get salary " << endl; cout << "Press 20 to get the attendance list " << endl; // cout<<"Press 19 to get the report-card "<<endl; // new cout << "Press 21 to check payment is done or not " << endl; cout << "Press 22 to display " << endl; cout << "Press 23 to exit " << endl; int choice; cout << "Enter your choice " << endl; cin >> choice; if (choice == 1) { string username; cout << "Enter Username :- "; cin >> username; ptr->set_username(username); } else if (choice == 2) { string str; cout << "Enter Staff name :- "; cin >> str; ptr->set_name(str); } else if (choice == 3) { string email; cout << "Enter Email :-"; cin >> email; ptr->set_email(email); } else if (choice == 4) { string phone_no; cout << "Enter Phone No :-"; cin >> phone_no; ptr->set_phone_no(phone_no); } else if (choice == 5) { string date_of_birth; cout << "Enter Date Of Birth :-"; cin >> date_of_birth; ptr->set_date_of_birth(date_of_birth); } else if (choice == 6) { string designation; cout << "Enter designation :-"; cin >> designation; ptr->set_designation(designation); } else if (choice == 7) { string str = ptr->get_username(); cout << "Username -" << str << endl; } else if (choice == 8) { string str = ptr->get_name(); cout << "Name -" << str << endl; } else if (choice == 9) { string str = ptr->get_email(); cout << "Email -" << str << endl; } else if (choice == 10) { string str = ptr->get_phone_no(); cout << "Phone number -" << str << endl; } else if (choice == 11) { string str = ptr->get_date_of_birth(); cout << "Date of birth -" << str << endl; } else if (choice == 12) { string str = ptr->get_designation(); cout << "Designation -" << str << endl; } else if (choice == 13) { int x = ptr->get_staff_id(); cout << "Staff id -" << x << endl; } else if (choice == 14) { string str; int x; cout << "Enter the date " << endl; cin >> str; cout << "Enter <1,0> ( 1 for present and 0 for absent ) " << endl; cin >> x; ptr->add_date_for_attandence(str, x); } // else if (choice==15){ // ptr->mark_todays_attandence(); // } else if (choice == 16) { string str; cout << "Enter Address " << endl; cin >> str; ptr->set_address(str); } else if (choice == 17) { string str = ptr->get_address(); cout << str << endl; } else if (choice == 18) { int x; cout << "Enter salary" << endl; cin >> x; ptr->set_salary(x); } else if (choice == 19) { int x = ptr->get_salary(); cout << "salary " << x << endl; } else if (choice == 20) { vector<pair<string, int>> v; v = ptr->get_attendance_list(); cout << "Date" << " " << "Status" << endl; for (auto x : v) { cout << x.first << " " << x.second << endl; } } // else if (choice==19) { // ptr->show_report(); // } else if (choice == 21) { int x = ptr->get_payment_done(); cout << x << endl; } else if (choice == 22) { ptr->display(); } else if (choice == 23) { return; } cout << "Do you want to perform more functions < y/Y for yes > < n/N for no >"; char ch; cin >> ch; if (ch == 'y' || ch == 'Y') { // teacher_functions(); continue; } else { // return; break; } } // while loop } // else condition } // complete function void admin::teacher_functions() { int id; cout << "Enter your staff id "; cin >> id; int check = 0; int size = teacher_list.size(); teacher *ptr; auto it = teacher_list.begin(); for (int i = 0; i < size; i++) { if (teacher_list[i].get_staff_id() == id) { ptr = &teacher_list[i]; check = 1; break; } it++; } if (check == 0) { cout << "The staff with this id do not exist " << endl; } else { // designation change // address change // salary change while (1) { cout << "The teacher with this id " << id << " here !!" << endl; cout << "MENU " << endl; cout << "---------------------------------" << endl; cout << "Press 1 for change username " << endl; cout << "Press 2 for change name " << endl; cout << "Press 3 for change email " << endl; cout << "Press 4 for change phone_no " << endl; cout << "Press 5 for change date_of_birth " << endl; cout << "Press 6 for change designation " << endl; cout << "Press 7 for get username " << endl; cout << "Press 8 for get name " << endl; cout << "Press 9 for get email " << endl; cout << "Press 10 for get phone_no " << endl; cout << "Press 11 for get date_of_birth " << endl; cout << "Press 12 for get designation " << endl; cout << "Press 13 for get staff id " << endl; cout << "Press 14 for add date for attendance " << endl; cout << "Press 15 for marking todays attendance " << endl; cout << "Press 16 to set address" << endl; cout << "Press 17 to get address" << endl; cout << "Press 18 to set salary" << endl; cout << "Press 19 to get salary " << endl; cout << "Press 20 to get the attendance list " << endl; // cout<<"Press 19 to get the report-card "<<endl; // unique cout << "Press 21 to add subject " << endl; cout << "Press 22 to get the subject list" << endl; cout << "Press 23 to conduct exam " << endl; cout << "Press 24 to check payment is done or not " << endl; cout << "Press 25 to display " << endl; cout << "Press 26 to exit " << endl; // // giving marks to student // cout<<"Press 25 to give marks to student "<<endl; int choice; cout << "Enter your choice " << endl; cin >> choice; if (choice == 1) { string username; cout << "Enter Username :- "; cin >> username; ptr->set_username(username); } else if (choice == 2) { string str; cout << "Enter Staff name :- "; cin >> str; ptr->set_name(str); } else if (choice == 3) { string email; cout << "Enter Email :-"; cin >> email; ptr->set_email(email); } else if (choice == 4) { string phone_no; cout << "Enter Phone No :-"; cin >> phone_no; ptr->set_phone_no(phone_no); } else if (choice == 5) { string date_of_birth; cout << "Enter Date Of Birth :-"; cin >> date_of_birth; ptr->set_date_of_birth(date_of_birth); } else if (choice == 6) { string designation; cout << "Enter designation :-"; cin >> designation; ptr->set_designation(designation); } else if (choice == 7) { string str = ptr->get_username(); cout << "Username -" << str << endl; } else if (choice == 8) { string str = ptr->get_name(); cout << "Name -" << str << endl; } else if (choice == 9) { string str = ptr->get_email(); cout << "Email -" << str << endl; } else if (choice == 10) { string str = ptr->get_phone_no(); cout << "Phone number -" << str << endl; } else if (choice == 11) { string str = ptr->get_date_of_birth(); cout << "Date of birth -" << str << endl; } else if (choice == 12) { string str = ptr->get_designation(); cout << "Designation -" << str << endl; } else if (choice == 13) { int x = ptr->get_staff_id(); cout << "Staff id -" << x << endl; } else if (choice == 14) { string str; int x; cout << "Enter the date " << endl; cin >> str; cout << "Enter <1,0> ( 1 for present and 0 for absent ) " << endl; cin >> x; ptr->add_date_for_attandence(str, x); } // else if (choice==15){ // ptr->mark_todays_attandence(); // } else if (choice == 16) { string str; cout << "Enter Address " << endl; cin >> str; ptr->set_address(str); } else if (choice == 17) { string str = ptr->get_address(); cout << str << endl; } else if (choice == 18) { int x; cout << "Enter salary" << endl; cin >> x; ptr->set_salary(x); } else if (choice == 19) { int x = ptr->get_salary(); cout << "salary " << x << endl; } else if (choice == 20) { vector<pair<string, int>> v; v = ptr->get_attendance_list(); cout << "Date" << " " << "Status" << endl; for (auto x : v) { cout << x.first << " " << x.second << endl; } } else if (choice == 21) { int x; string str; cout << "Enter the subject "; cin >> str; cout << "Enter the batch "; cin >> x; ptr->add_subject(x, str); } else if (choice == 22) { cout << "Subject list is as follows " << endl; ptr->get_subject(); } else if (choice == 23) { ptr->conduct_exam(); } // else if (choice==19) { // ptr->show_report(); // } else if (choice == 24) { int x = ptr->get_payment_done(); cout << x << endl; } else if (choice == 25) { ptr->display(); } else if (choice == 26) { return; } cout << "Do you want to perform more functions < y/Y for yes > < n/N for no >"; char ch; cin >> ch; if (ch == 'y' || ch == 'Y') { // teacher_functions(); continue; } else { // return; break; } } // while loop } // else condition } // complete function void admin::class_teacher_functions() { int id; cout << "Enter your staff id "; cin >> id; int check = 0; int size = class_teacher_list.size(); class_teacher *ptr; auto it = class_teacher_list.begin(); for (int i = 0; i < size; i++) { if (class_teacher_list[i].get_staff_id() == id) { ptr = &class_teacher_list[i]; check = 1; break; } it++; } if (check == 0) { cout << "The staff with this id do not exist " << endl; return; } else { // designation change // address change // salary change while (1) { cout << "MENU " << endl; cout << "class Teacher here id -> " << id << endl; cout << "---------------------------------" << endl; cout << "Press 1 for change username " << endl; cout << "Press 2 for change name " << endl; cout << "Press 3 for change email " << endl; cout << "Press 4 for change phone_no " << endl; cout << "Press 5 for change date_of_birth " << endl; cout << "Press 6 for change designation " << endl; cout << "Press 7 for get username " << endl; cout << "Press 8 for get name " << endl; cout << "Press 9 for get email " << endl; cout << "Press 10 for get phone_no " << endl; cout << "Press 11 for get date_of_birth " << endl; cout << "Press 12 for get designation " << endl; cout << "Press 13 for get staff id " << endl; cout << "Press 14 for add date for attendance " << endl; cout << "Press 15 for marking todays attendance " << endl; cout << "Press 16 to set address" << endl; cout << "Press 17 to get address" << endl; cout << "Press 18 to set salary" << endl; cout << "Press 19 to get salary " << endl; cout << "Press 20 to get the attendance list " << endl; // cout<<"Press 19 to get the report-card "<<endl; // unique cout << "Press 21 to add subject " << endl; cout << "Press 22 to get the subject list" << endl; cout << "Press 23 to conduct exam " << endl; cout << "Press 24 to change the branch " << endl; cout << "Press 25 to get the branch " << endl; cout << "Press 26 to check payment is done or not " << endl; // new // lib // check if you like want the lib infro in student class as well or not cout << "Press 27 to issue a book " << endl; cout << "Press 28 to submit a book" << endl; // giving marks to student --> check later cout << "Press 29 to give marks to student " << endl; // all the teachers gives the marks to the class teacher and class teacher gives them to student cout << "Press 30 to change student entries " << endl; // being the class teacher --> it can cout << "Press 31 to display " << endl; cout << "Press 32 to exit " << endl; int choice; cout << "Enter your choice " << endl; cin >> choice; if (choice == 1) { string username; cout << "Enter Username :- "; cin >> username; ptr->set_username(username); } else if (choice == 2) { string str; cout << "Enter Staff name :- "; cin >> str; ptr->set_name(str); } else if (choice == 3) { string email; cout << "Enter Email :-"; cin >> email; ptr->set_email(email); } else if (choice == 4) { string phone_no; cout << "Enter Phone No :-"; cin >> phone_no; ptr->set_phone_no(phone_no); } else if (choice == 5) { string date_of_birth; cout << "Enter Date Of Birth :-"; cin >> date_of_birth; ptr->set_date_of_birth(date_of_birth); } else if (choice == 6) { string designation; cout << "Enter designation :-"; cin >> designation; ptr->set_designation(designation); } else if (choice == 7) { string str = ptr->get_username(); cout << "Username -" << str << endl; } else if (choice == 8) { string str = ptr->get_name(); cout << "Name -" << str << endl; } else if (choice == 9) { string str = ptr->get_email(); cout << "Email -" << str << endl; } else if (choice == 10) { string str = ptr->get_phone_no(); cout << "Phone number -" << str << endl; } else if (choice == 11) { string str = ptr->get_date_of_birth(); cout << "Date of birth -" << str << endl; } else if (choice == 12) { string str = ptr->get_designation(); cout << "Designation -" << str << endl; } else if (choice == 13) { int x = ptr->get_staff_id(); cout << "Staff id -" << x << endl; } else if (choice == 14) { string str; int x; cout << "Enter the date " << endl; cin >> str; cout << "Enter <1,0> ( 1 for present and 0 for absent ) " << endl; cin >> x; ptr->add_date_for_attandence(str, x); } // else if (choice==15){ // ptr->mark_todays_attandence(); // } else if (choice == 16) { string str; cout << "Enter Address " << endl; cin >> str; ptr->set_address(str); } else if (choice == 17) { string str = ptr->get_address(); cout << str << endl; } else if (choice == 18) { int x; cout << "Enter salary" << endl; cin >> x; ptr->set_salary(x); } else if (choice == 19) { int x = ptr->get_salary(); cout << "salary " << x << endl; } else if (choice == 20) { vector<pair<string, int>> v; v = ptr->get_attendance_list(); cout << "Date" << " " << "Status" << endl; for (auto x : v) { cout << x.first << " " << x.second << endl; } } else if (choice == 21) { int x; string str; cout << "Enter the subject "; cin >> str; cout << "Enter the batch "; cin >> x; ptr->add_subject(x, str); } else if (choice == 22) { cout << "Subject list is as follows " << endl; ptr->get_subject(); } else if (choice == 23) { ptr->conduct_exam(); } else if (choice == 24) { int x; cout << "Enter the branch "; cin >> x; ptr->set_batch_no(x); } else if (choice == 25) { int x = ptr->get_batch_no(); cout << "Branch " << x << endl; } // else if (choice==19) { // ptr->show_report(); // } else if (choice == 26) { int x = ptr->get_payment_done(); cout << x << endl; } else if (choice == 27) { string book; cout << "Enter book name you want " << endl; cin >> book; string date; // input or use prabhav function to fetch todays date // now we are inputing cout << "Enter the todays date " << endl; cin >> date; obj_library.issue_teacher(book, date, id); } else if (choice == 28) { string book; cout << "Enter book name you want to return " << endl; cin >> book; string date; // input or use prabhav function to fetch todays date // now we are inputing cout << "Enter the todays date ( return date ) " << endl; cin >> date; obj_library.submit_teacher(id, book, date); } else if (choice == 29) { int id; cout << "Enter the roll no of the student you want " << endl; cin >> id; int check = 0; int size = student_list.size(); student *pointer; auto it = student_list.begin(); for (int i = 0; i < size; i++) { if (student_list[i].get_roll_no() == id) { pointer = &student_list[i]; check = 1; break; } it++; } if (check == 0) { cout << "The student with this id do not exist " << endl; } else { exam_marks m = ptr->give_marks(); // pointer->exam.push_back(m); // direct cannot give the marks // so make a function in student pointer->add_exam_marks(m); } } else if (choice == 31) { ptr->display(); } else if (choice == 32) { return; } else if (choice == 30) { int id; cout << "Enter your student id "; cin >> id; int check = 0; int size = student_list.size(); student *pointer; auto it = student_list.begin(); for (int i = 0; i < size; i++) { if (student_list[i].get_roll_no() == id) { pointer = &student_list[i]; check = 1; break; } it++; } if (check == 0) { cout << "The student with this id do not exist " << endl; } // check if the class teacher and student are of the same batch else if (pointer->get_standard() != ptr->get_batch_no()) { cout << "You are not the class teacher of this batch (student belongs) --> so you cannot .... " << endl; } else if (pointer->get_standard() == ptr->get_batch_no()) { // can change while (1) { cout << "MENU " << endl; cout << "---------------------------------" << endl; cout << "Press 1 for change username " << endl; cout << "Press 2 for change name " << endl; cout << "Press 3 for change email " << endl; cout << "Press 4 for change phone_no " << endl; cout << "Press 5 for change date_of_birth " << endl; // cout<<"Press 6 for change standard "<<endl; --> check you can update the standard from here cout << "Press 6 for get username " << endl; cout << "Press 7 for get name " << endl; cout << "Press 8 for get email " << endl; cout << "Press 9 for get phone_no " << endl; cout << "Press 10 for get date_of_birth " << endl; cout << "Press 11 for get standard " << endl; cout << "Press 12 for get roll no " << endl; // cout<<"Press 14 for add date for attendance "<<endl; // cout<<"Press 15 for marking todays attendance "<<endl; // cout<<"Press 16 to give exam"<<endl; cout << "Press 13 to get the percentage " << endl; cout << "Press 14 to get the attendance list " << endl; cout << "Press 15 to get the report-card " << endl; // new // bank // cout<<"Press 20 to pay the fees"<<endl; // cout<<"Press 21 to get fee paid or not"<<endl; // new // lib // check if you like want the lib infro in student class as well or not // cout<<"Press 22 to issue a book " <<endl; // cout<<"Press 23 to submit a book"<<endl; int choice1; cout << "Enter your choice " << endl; cin >> choice1; if (choice1 == 1) { string username; cout << "Enter Username :- "; cin >> username; pointer->set_username(username); } else if (choice1 == 2) { string str; cout << "Enter Student name :- "; cin >> str; pointer->set_name(str); } else if (choice1 == 3) { string email; cout << "Enter Email :-"; cin >> email; pointer->set_email(email); } else if (choice1 == 4) { string phone_no; cout << "Enter Phone No :-"; cin >> phone_no; pointer->set_phone_no(phone_no); } else if (choice1 == 5) { string date_of_birth; cout << "Enter Date Of Birth :-"; cin >> date_of_birth; pointer->set_date_of_birth(date_of_birth); } // else if (choice==6) { // int standard; // cout << "Enter Standard :-"; // cin >> standard; // ptr->set_standard(standard); // } else if (choice1 == 6) { string str = pointer->get_username(); cout << "Username -" << str << endl; } else if (choice1 == 7) { string str = pointer->get_name(); cout << "Name -" << str << endl; } else if (choice1 == 8) { string str = pointer->get_email(); cout << "Email -" << str << endl; } else if (choice1 == 9) { string str = pointer->get_phone_no(); cout << "Phone number -" << str << endl; } else if (choice1 == 10) { string str = pointer->get_date_of_birth(); cout << "Date of birth -" << str << endl; } else if (choice1 == 11) { int str = pointer->get_standard(); cout << "Standard -" << str << endl; } else if (choice1 == 12) { int str = pointer->get_roll_no(); cout << "Roll no -" << str << endl; } // else if (choice==13){ // string str; // int x; // cout<<"Enter the date "<<endl; // cin>>str; // cout<<"Enter <1,0> ( 1 for present and 0 for absent ) "<<endl; // cin>>x; // ptr->add_date_for_attandence(str,x); // } // else if (choice==15){ // ptr->mark_todays_attandence(); // } // else if (choice==16){ // ptr->give_exam(); // } else if (choice1 == 13) { float x = pointer->get_percentage(); cout << "Percentage - " << x << endl; } else if (choice1 == 14) { vector<pair<string, int>> v; v = pointer->get_attendance_list(); cout << "Date" << " " << "Status" << endl; for (auto x : v) { cout << x.first << " " << x.second << endl; } } else if (choice1 == 15) { pointer->show_report(); } // else if (choice==20) { // // fix this fees somehow say 1000 store it somewhere // obj_bank.perform_student_transaction(ptr->get_roll_no(),1000); // ptr->set_fee_paid(1); // } // else if (choice==21) { // int x=ptr->get_fee_paid(); // cout<<x<<endl; // } // else if (choice==22) { // string book; // cout<<"Enter book name you want "<<endl; // cin>>book; // string date; // // input or use prabhav function to fetch todays date // // now we are inputing // cout<<"Enter the todays date "<<endl; // cin>>date; // obj_library.issue_student(book,date,id); // } // else if (choice==23) { // string book; // cout<<"Enter book name you want to return "<<endl; // cin>>book; // string date; // // input or use prabhav function to fetch todays date // // now we are inputing // cout<<"Enter the todays date ( return date ) "<<endl; // cin>>date; // obj_library.issue_student(book,date,id); // /pointer cout << "Do you want to perform more functions < y/Y for yes > < n/N for no >"; char ch; cin >> ch; if (ch == 'y' || ch == 'Y') { // teacher_functions(); continue; } else { // return; break; } } // while loop } } cout << "Do you want to perform more functions < y/Y for yes > < n/N for no >"; char ch; cin >> ch; if (ch == 'y' || ch == 'Y') { // teacher_functions(); continue; } else { // return; break; } } // while loop } // else condition } // complete function // update status // check where to add --> while assigning percentage // teacher will assign marks --> then set percentage --> if percentage is greater than sth then // update status // choice 16 // give exam --> check // change to go via the teacher // int number_of_exams; --> use this void admin::student_functions() { int id; cout << "Enter your student id "; cin >> id; int check = 0; int size = student_list.size(); student *ptr; auto it = student_list.begin(); for (int i = 0; i < size; i++) { if (student_list[i].get_roll_no() == id) { ptr = &student_list[i]; check = 1; break; } it++; } if (check == 0) { cout << "The student with this id do not exist " << endl; } else { while (1) { cout << "Student with this id " << id << " here !!" << endl; cout << "MENU " << endl; cout << "---------------------------------" << endl; cout << "Press 1 for change username " << endl; cout << "Press 2 for change name " << endl; cout << "Press 3 for change email " << endl; cout << "Press 4 for change phone_no " << endl; cout << "Press 5 for change date_of_birth " << endl; cout << "Press 6 for change standard " << endl; cout << "Press 7 for get username " << endl; cout << "Press 8 for get name " << endl; cout << "Press 9 for get email " << endl; cout << "Press 10 for get phone_no " << endl; cout << "Press 11 for get date_of_birth " << endl; cout << "Press 12 for get standard " << endl; cout << "Press 13 for get roll no " << endl; cout << "Press 14 for add date for attendance " << endl; cout << "Press 15 for marking todays attendance " << endl; cout << "Press 16 to give exam" << endl; cout << "Press 17 to get the percentage " << endl; cout << "Press 18 to get the attendance list " << endl; cout << "Press 19 to get the report-card " << endl; // new // bank cout << "Press 20 to pay the fees" << endl; cout << "Press 21 to get fee paid or not" << endl; // new // lib // check if you like want the lib infro in student class as well or not cout << "Press 22 to issue a book " << endl; cout << "Press 23 to submit a book" << endl; cout << "Press 24 to display" << endl; cout << "Press 25 to give maths exam" << endl; cout << "Press 26 to exit" << endl; int choice; cout << "Enter your choice " << endl; cin >> choice; if (choice == 1) { string username; cout << "Enter Username :- "; cin >> username; ptr->set_username(username); } else if (choice == 2) { string str; cout << "Enter Student name :- "; cin >> str; ptr->set_name(str); } else if (choice == 3) { string email; cout << "Enter Email :-"; cin >> email; ptr->set_email(email); } else if (choice == 4) { string phone_no; cout << "Enter Phone No :-"; cin >> phone_no; ptr->set_phone_no(phone_no); } else if (choice == 5) { string date_of_birth; cout << "Enter Date Of Birth :-"; cin >> date_of_birth; ptr->set_date_of_birth(date_of_birth); } else if (choice == 6) { int standard; cout << "Enter Standard :-"; cin >> standard; ptr->set_standard(standard); } else if (choice == 7) { string str = ptr->get_username(); cout << "Username -" << str << endl; } else if (choice == 8) { string str = ptr->get_name(); cout << "Name -" << str << endl; } else if (choice == 9) { string str = ptr->get_email(); cout << "Email -" << str << endl; } else if (choice == 10) { string str = ptr->get_phone_no(); cout << "Phone number -" << str << endl; } else if (choice == 11) { string str = ptr->get_date_of_birth(); cout << "Date of birth -" << str << endl; } else if (choice == 12) { int str = ptr->get_standard(); cout << "Standard -" << str << endl; } else if (choice == 13) { int str = ptr->get_roll_no(); cout << "Roll no -" << str << endl; } else if (choice == 14) { string str; int x; cout << "Enter the date " << endl; cin >> str; cout << "Enter <1,0> ( 1 for present and 0 for absent ) " << endl; cin >> x; ptr->add_date_for_attandence(str, x); } // else if (choice==15){ // ptr->mark_todays_attandence(); // } else if (choice == 16) { ptr->give_exam(); } else if (choice == 17) { float x = ptr->get_percentage(); cout << "Percentage - " << x << endl; } else if (choice == 18) { vector<pair<string, int>> v; v = ptr->get_attendance_list(); cout << "Date" << " " << "Status" << endl; for (auto x : v) { cout << x.first << " " << x.second << endl; } } else if (choice == 19) { ptr->show_report(); } else if (choice == 20) { // fix this fees somehow say 1000 store it somewhere obj_bank.perform_student_transaction(ptr->get_roll_no(), 1000); ptr->set_fee_paid(1); } else if (choice == 21) { int x = ptr->get_fee_paid(); cout << x << endl; } else if (choice == 22) { string book; cout << "Enter book name you want " << endl; cin >> book; string date; // input or use prabhav function to fetch todays date // now we are inputing cout << "Enter the todays date " << endl; cin >> date; obj_library.issue_student(book, date, id); } else if (choice == 23) { string book; cout << "Enter book name you want to return " << endl; cin >> book; string date; // input or use prabhav function to fetch todays date // now we are inputing cout << "Enter the todays date ( return date ) " << endl; cin >> date; obj_library.submit_student(id, book, date); } else if (choice == 24) { ptr->display(); } else if (choice == 25) { ptr->give_maths_exam(); } else if (choice == 26) { return; } cout << "Do you want to perform more functions < y/Y for yes > < n/N for no >"; char ch; cin >> ch; if (ch == 'y' || ch == 'Y') { // teacher_functions(); continue; } else { // return; break; } } // while loop } // else condition } // complete function void admin::class_monitor_functions() { int id; cout << "Enter your student id "; cin >> id; int check = 0; int size = class_monitor_list.size(); class_monitor *ptr; auto it = class_monitor_list.begin(); for (int i = 0; i < size; i++) { if (class_monitor_list[i].get_roll_no() == id) { ptr = &class_monitor_list[i]; check = 1; break; } it++; } if (check == 0) { cout << "The student with this id do not exist " << endl; } else { while (1) { cout << "The class monitor (student) with this id" << id << " here" << endl; cout << "MENU " << endl; cout << "---------------------------------" << endl; cout << "Press 1 for change username " << endl; cout << "Press 2 for change name " << endl; cout << "Press 3 for change email " << endl; cout << "Press 4 for change phone_no " << endl; cout << "Press 5 for change date_of_birth " << endl; cout << "Press 6 for change standard " << endl; cout << "Press 7 for get username " << endl; cout << "Press 8 for get name " << endl; cout << "Press 9 for get email " << endl; cout << "Press 10 for get phone_no " << endl; cout << "Press 11 for get date_of_birth " << endl; cout << "Press 12 for get standard " << endl; cout << "Press 13 for get roll no " << endl; cout << "Press 14 for add date for attendance " << endl; cout << "Press 15 for marking todays attendance " << endl; cout << "Press 16 to give exam" << endl; cout << "Press 17 to get the percentage " << endl; cout << "Press 18 to get the attendance list " << endl; cout << "Press 19 to get the report-card " << endl; // unique here // cout<<"Press 20 to change standard you are monitoring"<<endl; // cout<<"Press 21 to get the standard you are monitoring"<<endl; cout << "Press 22 to maintain the class" << endl; // new cout << "Press 23 to pay the fees" << endl; cout << "Press 24 to get fee paid or not" << endl; // new // lib // check if you like want the lib infro in student class as well or not cout << "Press 25 to issue a book " << endl; cout << "Press 26 to submit a book" << endl; cout << "Press 27 to display" << endl; cout << "Press 28 to exit" << endl; int choice; cout << "Enter your choice " << endl; cin >> choice; if (choice == 1) { string username; cout << "Enter Username :- "; cin >> username; ptr->set_username(username); } else if (choice == 2) { string str; cout << "Enter Student name :- "; cin >> str; ptr->set_name(str); } else if (choice == 3) { string email; cout << "Enter Email :-"; cin >> email; ptr->set_email(email); } else if (choice == 4) { string phone_no; cout << "Enter Phone No :-"; cin >> phone_no; ptr->set_phone_no(phone_no); } else if (choice == 5) { string date_of_birth; cout << "Enter Date Of Birth :-"; cin >> date_of_birth; ptr->set_date_of_birth(date_of_birth); } else if (choice == 6) { int standard; cout << "Enter Standard :-"; cin >> standard; ptr->set_standard(standard); } else if (choice == 7) { string str = ptr->get_username(); cout << "Username -" << str << endl; } else if (choice == 8) { string str = ptr->get_name(); cout << "Name -" << str << endl; } else if (choice == 9) { string str = ptr->get_email(); cout << "Email -" << str << endl; } else if (choice == 10) { string str = ptr->get_phone_no(); cout << "Phone number -" << str << endl; } else if (choice == 11) { string str = ptr->get_date_of_birth(); cout << "Date of birth -" << str << endl; } else if (choice == 12) { int str = ptr->get_standard(); cout << "Standard -" << str << endl; } else if (choice == 13) { int str = ptr->get_roll_no(); cout << "Roll no -" << str << endl; } else if (choice == 14) { string str; int x; cout << "Enter the date " << endl; cin >> str; cout << "Enter <1,0> ( 1 for present and 0 for absent ) " << endl; cin >> x; ptr->add_date_for_attandence(str, x); } // else if (choice==15){ // ptr->mark_todays_attandence(); // } else if (choice == 16) { ptr->give_exam(); } else if (choice == 17) { float x = ptr->get_percentage(); cout << "Percentage - " << x << endl; } else if (choice == 18) { vector<pair<string, int>> v; v = ptr->get_attendance_list(); cout << "Date" << " " << "Status" << endl; for (auto x : v) { cout << x.first << " " << x.second << endl; } } else if (choice == 19) { ptr->show_report(); } // else if (choice==20) { // int x; // cout<<"Enter the standard you are monitoring"<<endl; // cin>>x; // ptr->set_standard(x); // } // else if (choice==21) { // int x=ptr->get_standard(); // cout<<"Standard you are monitoring "<<x<<endl; // } else if (choice == 22) { ptr->maintain_the_class(); } else if (choice == 23) { // fix this fees somehow say 1000 store it somewhere obj_bank.perform_student_transaction(ptr->get_roll_no(), 1000); ptr->set_fee_paid(1); } else if (choice == 24) { int x = ptr->get_fee_paid(); cout << x << endl; } else if (choice == 25) { string book; cout << "Enter book name you want " << endl; cin >> book; string date; // input or use prabhav function to fetch todays date // now we are inputing cout << "Enter the todays date " << endl; cin >> date; obj_library.issue_student(book, date, id); } else if (choice == 26) { string book; cout << "Enter book name you want to return " << endl; cin >> book; string date; // input or use prabhav function to fetch todays date // now we are inputing cout << "Enter the todays date ( return date ) " << endl; cin >> date; obj_library.issue_student(book, date, id); } else if (choice == 27) { ptr->display(); } else if (choice == 28) { return; } cout << "Do you want to perform more functions < y/Y for yes > < n/N for no >"; char ch; cin >> ch; if (ch == 'y' || ch == 'Y') { // teacher_functions(); continue; } else { // return; break; } } // while loop } // else condition } // complete function void admin::leader_functions() { int id; cout << "Enter your student id "; cin >> id; int check = 0; int size = leader_list.size(); leader *ptr; auto it = leader_list.begin(); for (int i = 0; i < size; i++) { if (leader_list[i].get_roll_no() == id) { ptr = &leader_list[i]; check = 1; break; } it++; } if (check == 0) { cout << "The student with this id do not exist " << endl; } else { while (1) { cout << "The leader student with this id " << id << " here" << endl; cout << "MENU " << endl; cout << "---------------------------------" << endl; cout << "Press 1 for change username " << endl; cout << "Press 2 for change name " << endl; cout << "Press 3 for change email " << endl; cout << "Press 4 for change phone_no " << endl; cout << "Press 5 for change date_of_birth " << endl; cout << "Press 6 for change standard " << endl; cout << "Press 7 for get username " << endl; cout << "Press 8 for get name " << endl; cout << "Press 9 for get email " << endl; cout << "Press 10 for get phone_no " << endl; cout << "Press 11 for get date_of_birth " << endl; cout << "Press 12 for get standard " << endl; cout << "Press 13 for get roll no " << endl; cout << "Press 14 for add date for attendance " << endl; cout << "Press 15 for marking todays attendance " << endl; cout << "Press 16 to give exam" << endl; cout << "Press 17 to get the percentage " << endl; cout << "Press 18 to get the attendance list " << endl; cout << "Press 19 to get the report-card " << endl; // unique here cout << "Press 20 to change standard you are monitoring" << endl; cout << "Press 21 to get the standard you are monitoring" << endl; cout << "Press 22 to maintain the class" << endl; cout << "Press 23 to maintain the monitors " << endl; // new cout << "Press 24 to pay the fees" << endl; cout << "Press 25 to get fee paid or not" << endl; // new // lib // check if you like want the lib infro in student class as well or not cout << "Press 26 to issue a book " << endl; cout << "Press 27 to submit a book" << endl; cout << "Press 28 to display" << endl; cout << "Press 29 to exit" << endl; int choice; cout << "Enter your choice " << endl; cin >> choice; if (choice == 1) { string username; cout << "Enter Username :- "; cin >> username; ptr->set_username(username); } else if (choice == 2) { string str; cout << "Enter Student name :- "; cin >> str; ptr->set_name(str); } else if (choice == 3) { string email; cout << "Enter Email :-"; cin >> email; ptr->set_email(email); } else if (choice == 4) { string phone_no; cout << "Enter Phone No :-"; cin >> phone_no; ptr->set_phone_no(phone_no); } else if (choice == 5) { string date_of_birth; cout << "Enter Date Of Birth :-"; cin >> date_of_birth; ptr->set_date_of_birth(date_of_birth); } else if (choice == 6) { int standard; cout << "Enter Standard :-"; cin >> standard; ptr->set_standard(standard); } else if (choice == 7) { string str = ptr->get_username(); cout << "Username -" << str << endl; } else if (choice == 8) { string str = ptr->get_name(); cout << "Name -" << str << endl; } else if (choice == 9) { string str = ptr->get_email(); cout << "Email -" << str << endl; } else if (choice == 10) { string str = ptr->get_phone_no(); cout << "Phone number -" << str << endl; } else if (choice == 11) { string str = ptr->get_date_of_birth(); cout << "Date of birth -" << str << endl; } else if (choice == 12) { int str = ptr->get_standard(); cout << "Standard -" << str << endl; } else if (choice == 13) { int str = ptr->get_roll_no(); cout << "Roll no -" << str << endl; } else if (choice == 14) { string str; int x; cout << "Enter the date " << endl; cin >> str; cout << "Enter <1,0> ( 1 for present and 0 for absent ) " << endl; cin >> x; ptr->add_date_for_attandence(str, x); } // else if (choice==15){ // ptr->mark_todays_attandence(); // } else if (choice == 16) { ptr->give_exam(); } else if (choice == 17) { float x = ptr->get_percentage(); cout << "Percentage - " << x << endl; } else if (choice == 18) { vector<pair<string, int>> v; v = ptr->get_attendance_list(); cout << "Date" << " " << "Status" << endl; for (auto x : v) { cout << x.first << " " << x.second << endl; } } else if (choice == 19) { ptr->show_report(); } else if (choice == 20) { int x; cout << "Enter the standard you are monitoring" << endl; cin >> x; ptr->set_standard(x); } else if (choice == 21) { int x = ptr->get_standard(); cout << "Standard you are monitoring " << x << endl; } else if (choice == 22) { ptr->maintain_the_class(); } // unique else if (choice == 23) { ptr->maintain_the_monitor(); } else if (choice == 24) { // fix this fees somehow say 1000 store it somewhere obj_bank.perform_student_transaction(ptr->get_roll_no(), 1000); ptr->set_fee_paid(1); } else if (choice == 25) { int x = ptr->get_fee_paid(); cout << x << endl; } else if (choice == 26) { string book; cout << "Enter book name you want " << endl; cin >> book; string date; // input or use prabhav function to fetch todays date // now we are inputing cout << "Enter the todays date " << endl; cin >> date; obj_library.issue_student(book, date, id); } else if (choice == 27) { string book; cout << "Enter book name you want to return " << endl; cin >> book; string date; // input or use prabhav function to fetch todays date // now we are inputing cout << "Enter the todays date ( return date ) " << endl; cin >> date; obj_library.issue_student(book, date, id); } else if (choice == 28) { ptr->display(); } else if (choice == 29) { return; } cout << "Do you want to perform more functions < y/Y for yes > < n/N for no >"; char ch; cin >> ch; if (ch == 'y' || ch == 'Y') { // teacher_functions(); continue; } else { // return; break; } } // while loop } // else condition } // complete function
true
81d60e266b4b8ceb26919b8f77134954fead66e7
C++
GabeOchieng/ggnn.tensorflow
/program_data/PKU_raw/43/825.c
UTF-8
262
2.796875
3
[]
no_license
int jud(int k) { int s=sqrt(k); for(int i=2;i<=s;i++) if(k%i==0) return 0; return 1; } int main() { int m, t, s; cin>>m; for(t=3;t<=m/2;t++) { s=m-t; if(jud(s)+jud(t)==2) cout<<t<<' '<<s<<endl; } return 0; }
true
89ce916e6ebfc0f4236d7eae52983941e9cdda40
C++
bsmith19/chip8-emu-sub
/cpu/include/instructions/InstDisp_DXYN.hpp
UTF-8
843
2.796875
3
[]
no_license
#ifndef __INSTDISP_DXYN_HPP__ #define __INSTDISP_DXYN_HPP__ #include "instructions/Inst.h" #include "cpu/CpuData.h" class InstDisp_DXYN : Inst { public: InstDisp_DXYN(unsigned short opcode) : Inst(opcode) {}; ~InstDisp_DXYN() {}; public: virtual bool Handle(std::shared_ptr<CpuData> systemData) { // Draws a sprite at coordinate (VX, VY) that has a width of 8 pixels and a height of N pixels. // Each row of 8 pixels is read as bit-coded starting from memory location I; I value doesn’t change after the execution of this instruction. // As described above, VF is set to 1 if any screen pixels are flipped from set to unset when the sprite is drawn, and to 0 if that doesn’t happen // TODO: Must implement this after I have a solution to drawing return true; } }; #endif
true
f6ba21383b0015c765f133e672ad49452b31ddf3
C++
haozha111/algo
/41.cpp
UTF-8
1,129
3.28125
3
[]
no_license
#include "leetcode.h" using namespace std; class Solution { public: int firstMissingPositive(vector<int>& nums) { return firstMissingPositive2(nums); } //similar to bucket sort, A[i] -> i + 1 int firstMissingPositive1(vector<int>& nums) { int n = nums.size(); int i = 0; while (i < n) { if (nums[i] > 0 and nums[i] < n and nums[i] != nums[nums[i] - 1]) { swap(nums[i], nums[nums[i] - 1]); }else { i++; } } for (i = 0; i < n; ++i) { if (nums[i] != i + 1) { return i + 1; } } return n + 1; } int firstMissingPositive2(vector<int>& nums) { int n = nums.size(); for (int i = 0; i < n; ++i) { while (nums[i] != i + 1) { if (nums[i] <= 0 or nums[i] > n or nums[i] == nums[nums[i] - 1]) { break; } swap(nums[i], nums[nums[i] - 1]); } } for (int i = 0; i < n; ++i) { if (nums[i] != i + 1) { return i + 1; } } return n + 1; } }; int main(){ Solution s; vector<int> nums = {3}; cout << s.firstMissingPositive(nums) << endl; return 0; }
true
3d5b707fa513b7c091a52adc4e725de33d9dafa0
C++
Jackwin/mipt-mips
/simulator/risc_v/riscv_register/t/unit_test.cpp
UTF-8
1,736
2.859375
3
[ "MIT" ]
permissive
/** * Unit tests for RISCV register * @author Alexander Misevich * Copyright 2018 MIPT-MIPS */ // generic C #include <cassert> #include <cstdlib> // Catch2 #include <catch.hpp> // MIPT-MIPS modules #include "../riscv_register.h" static_assert(RISCVRegister::MAX_REG == 32); // Testing methods of the class TEST_CASE( "RISCV_registers: Size_t_converters") { for ( size_t i = 0; i < 32; ++i) { CHECK( RISCVRegister::from_cpu_index( i).to_rf_index() == i); } } TEST_CASE( "RISCV_registers: Equal") { for ( size_t i = 0; i < 32; ++i) { CHECK( RISCVRegister::from_cpu_index( i) == RISCVRegister::from_cpu_index( i)); if (i > 0) { CHECK( RISCVRegister::from_cpu_index(i - 1) != RISCVRegister::from_cpu_index( i)); } } } TEST_CASE( "RISCV_registers: no_mips") { auto reg_hi = RISCVRegister::mips_hi; auto reg_lo = RISCVRegister::mips_lo; for( size_t i = 0; i < 32; ++i) { // Ensure that there are no mips regs CHECK( RISCVRegister::from_cpu_index( i).to_rf_index() != reg_hi.to_rf_index()); CHECK( RISCVRegister::from_cpu_index( i).to_rf_index() != reg_lo.to_rf_index()); CHECK_FALSE( RISCVRegister::from_cpu_index( i).is_mips_hi()); CHECK_FALSE( RISCVRegister::from_cpu_index( i).is_mips_lo()); } } TEST_CASE( "RISCV_registers: return_address") { auto reg = RISCVRegister::return_address; CHECK( reg.to_rf_index() == 1u); CHECK_FALSE( reg.is_zero()); CHECK_FALSE( reg.is_mips_hi()); CHECK_FALSE( reg.is_mips_lo()); } TEST_CASE( "RISCV_registers: Zero") { auto reg = RISCVRegister::zero; CHECK( reg.is_zero()); CHECK_FALSE( reg.is_mips_hi()); CHECK_FALSE( reg.is_mips_lo()); }
true
ad8e413868b3594599398a242f48f6029e351f13
C++
Busiu/ProblemSolving
/Project Euler/Project Euler #10/main.cpp
UTF-8
695
3.03125
3
[]
no_license
#include <iostream> #include <vector> using namespace std; bool czy_pierwsza(long long int n) { for(int i=2; i*i<=n; i++) { if(n%i==0) return false; } return true; } int main() { long long int t, n; vector <long long int> suma; suma.push_back(0); suma.push_back(0); suma.push_back(2); for(int i=3; i<=1000000; i++) { if(czy_pierwsza(i)) { suma.push_back(suma[suma.size()-1]+i); } else { suma.push_back(suma[suma.size()-1]); } } cin >> t; for(int x=0; x<t; x++) { cin >> n; cout << suma[n] << endl; } return 0; }
true
d5407a9506fdbd39c792f9c3abe0851403996062
C++
EishaMazhar/Semester2-Resources
/CP_LabTasks/lab 5/task 2.cpp
UTF-8
1,069
3.578125
4
[]
no_license
#include<iostream> #include<string.h> #include<iomanip> using namespace std; class Calculator{ private: float rentPerDay; string Customer_name; int NoOfdays; float CustomerRent; public: Calculator(){} Calculator(string s,int n) { Customer_name=s; NoOfdays=n; rentPerDay=1000.85; CustomerRent=(float)NoOfdays*rentPerDay; } float RentwithBonus() { if(NoOfdays>7){ CustomerRent=(float)CustomerRent-rentPerDay; return CustomerRent; } else if(NoOfdays<=7) { return CustomerRent; } } DisplayRent() { cout<<"\nCustomer Name : "<<Customer_name; cout<<"\nNo of Days : "<<NoOfdays; cout<<"\nTotal Rent After bonus(if applicable) : "<<fixed<<setprecision(2)<<RentwithBonus(); } }; main() { cout<<" ** Hotel Mercato **\n"; string n1,n2; int d1,d2; cout<<"Enter name : "; cin>>n1; cout<<"Days : "; cin>>d1; Calculator C1(n1,d1); cout<<"Enter name : "; cin>>n2; cout<<"Days : "; cin>>d2; Calculator C2(n2,d2); C1.DisplayRent(); cout<<endl; C2.DisplayRent(); }
true
b5695acb5ff3222e9de51c5fa441fe0ed4bc94ef
C++
eitama7/semestral_work_cpp_2020
/src/CInterface.h
UTF-8
5,373
3.046875
3
[]
no_license
#pragma once #include "CCharacter.h" #include "CPlayer.h" #include "constants.h" class CInterface { public: /** * Draws the start menu. */ void StartMenu (); /** * Choosing mode : [Pl. vs Pl.] or [Pl. vs PC] */ void ChooseMode (); /** * For CHelp call. Shows the rules of game. */ void ShowRules (); /** * Mode vs Player. * Check users answers. * * @param[in, out] vec Vector with 4 characters for choosing. * @param[in] number What characters is being choosing: first or second. * @param[in] announ String that will be written for user. * @param[in] prevChoice1 Comparing with previous choice for validate input. * @param[in] prevChoice2 Comparing with previous choice for validate input. * @param[in] prevChoice3 Comparing with previous choice for validate input. * * @return Made choice. */ int MakeChoicePC ( const std::vector < std::shared_ptr <CCharacter> > &, const std::string, const std::string, int, int, int ); /** * Mode vs PC. * Generate answers. * * @param[in, out] vec Vector with 4 characters for choosing. * @param[in] number What characters is being choosing: first or second. * @param[in] announ String that will be written for user. * @param[in] prevChoice1 Comparing with previous choice for validate input. * @param[in] prevChoice2 Comparing with previous choice for validate input. * @param[in] prevChoice3 Comparing with previous choice for validate input. * * @return Made choice. */ int MakeChoicePl ( const std::vector < std::shared_ptr <CCharacter> > &, const std::string, const std::string, int, int, int ); /** * Get chosen character for Player1 and Player2. * * @param[in, out] vec Vector with characters to choose. * @param[in] withPlayer Which mode we have. Depending on it it will (not) write in output instructions for user. * @param[in, out] player1char1 Loading number of choice. * @param[in, out] player2char1 Loading number of choice. * @param[in, out] player1char2 Loading number of choice. * @param[in, out] player2char2 Loading number of choice. */ void getCharacter ( const std::vector < std::shared_ptr <CCharacter> > &, bool, int &, int &, int &, int & ); /** * Drawing asking menu for user - choosing characters. * * @param[in] vec Has all names and hints of characters for choosing. * @param[in] str First or second character we choose. */ void ChooseCharacter ( const std::vector <std::shared_ptr <CCharacter> > &, const std::string str ); /** * Printing message. * * @param[in] str What message will be printed. */ void Announcement ( const std::string ); /** * Show cards of opponent in hidden mode. * * @param[in, out] pl Who owns cards. */ void ShowHiddenCards ( CPlayer & ); /** * Show cards that player owns in open mode. * * @param[in, out] pl Who owns cards. */ void ShowCards ( CPlayer & ); /** * Show cards that player has in a game - with long effect. * * @param[in, out] pl Who owns cards. */ void ShowCardsInGame ( CPlayer & ); /** * Choose active and passive characters. * * @param[in, out] vec Vector with characters to choose. * @param[in] idx1 Where is each character in vector vec * @param[in] idx2 Where is each character in vector vec * @param[in, out] active Here will be loaded active character. * @param[in, out] passive Here will be loaded active character. */ void ChooseActive ( std::vector <std::shared_ptr <CCharacter> > &, int, int, std::shared_ptr <CCharacter> &, std::shared_ptr <CCharacter> & ); /** * Method for discarding cards in mode vs PC when their number is bigger than current health. * * @param[in, out] pc Presents PC. * @param[in, out] pl Presents player. */ void DiscardCardsPC ( CPlayer &, CPlayer & ); /** * Method for discarding cards in mode vs Player when their number is bigger than current health. * * @param[in, out] pl1 Presents player1. * @param[in, out] pl2 Presents player2. */ void DiscardCards ( CPlayer &, CPlayer & ); /** * Checks users input and get number of chosen card. * * @param[in, out] pl1 Presents player1. * @param[in, out] pl2 Presents player2. * * @return Returns number of chosen card. */ int CardUse ( CPlayer &, CPlayer & ); /** * Comparing priority of cards and choose ine for playing. * * @param[in, out] pc Presents PC. * @param[in, out] pl Presents player. * * @return Returns number of chosen card. */ int CardUsePC ( CPlayer &, CPlayer & ); /** * Draws plaing zone. * * @param[in, out] pl1 Presents player1. * @param[in, out] pl2 Presents player2. * @param[in] str What message will be printed in a center of playing zone. * @param[in] turnPlayer Desides which player's cards will be shown. */ void DrawPlayZone ( CPlayer &, CPlayer &, const std::string, bool ); };
true
c615f940a4a8cc8d3e50906d799b6e962259f12d
C++
notozeki/ave637kbps-season1
/GL.cpp
UTF-8
4,228
2.53125
3
[]
no_license
#include <GL/glut.h> #include <GL/freeglut_ext.h> #include <stdio.h> #include "Map.hpp" #include "GL.hpp" #include "Vector.hpp" #include "StructureManager.hpp" #include "SimpleStructure.hpp" Map* GL::mMap = 0; StructureManager* GL::mStructureManager = 0; GL::MouseButton GL::mMouseButton; int GL::mMouseBuf[2]; int GL::mScreenX; int GL::mScreenY; Vector GL::mCameraDir; Vector GL::mViewpoint; double GL::mMagni; void drawSquare() // 妥協 { glColor3d(0.5, 1.0, 0.5); // みどり glBegin(GL_QUADS); glVertex3d(0.0, 0.0, 0.0); glVertex3d(1.0, 0.0, 0.0); glVertex3d(1.0, 1.0, 0.0); glVertex3d(0.0, 1.0, 0.0); glEnd(); glColor3d(0.0, 0.0, 0.0); // くろ glBegin(GL_LINE_LOOP); glVertex3d(0.0, 0.0, 0.0); glVertex3d(1.0, 0.0, 0.0); glVertex3d(1.0, 1.0, 0.0); glVertex3d(0.0, 1.0, 0.0); glEnd(); } void GL::drawMapCell(int x, int y, int z) { glLoadIdentity(); glTranslated(x, y, z); drawSquare(); } void GL::init(int* argcp, char** argv, const char* name, const char* init_data, const int screen_x, const int screen_y) { /* データ準備 */ // 基本となる正方形を初期化 glNewList(PRI_SQUARE, GL_COMPILE); glBegin(GL_QUADS); glVertex3d(0.0, 0.0, 0.0); glVertex3d(1.0, 0.0, 0.0); glVertex3d(1.0, 1.0, 0.0); glVertex3d(0.0, 1.0, 0.0); glEnd(); glEndList(); mMap = new Map(name, init_data); mStructureManager = new StructureManager(); Structure* t = new SimpleStructure(); t->setLocate(1, 1); mStructureManager->addStructure(t); mViewpoint.setComp(mMap->width() / 2.0, mMap->height() / 2.0, 0.0); mCameraDir.setComp(0.0, 1.0, 10.0); mCameraDir.normalize(); mMagni = 10.0; mScreenX = screen_x; mScreenY = screen_y; /* OpenGL, GLUTの設定 */ glutInitWindowSize(mScreenX, mScreenY); glutInit(argcp, argv); glutInitDisplayMode(GLUT_RGBA/* | GLUT_DEPTH*/); glutCreateWindow("My Sim"); glutDisplayFunc(GL::display); glutReshapeFunc(GL::resize); glutMouseFunc(GL::mouse); glutMotionFunc(GL::motion); glutKeyboardFunc(GL::keyboard); //glEnable(GL_DEPTH_TEST); glClearColor(1.0, 1.0, 1.0, 1.0); } void GL::display() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // glCallList(PRI_SQUARE);// ほんとはこれしたい mMap->draw(); mStructureManager->draw(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); //glOrtho(0.0, 10.0, 0.0, 10.0, -2.0, 2.0); gluPerspective(100.0, 1.0, 0.0, 100.0); //gluLookAt(3.0, -4.0, 5.0, 3.0, 3.0, 0.0, 0.0, 0.0, 1.0); Vector t = mViewpoint + mCameraDir * mMagni; gluLookAt(t.x(), t.y(), t.z(), mViewpoint.x(), mViewpoint.y(), mViewpoint.z(), 0.0, 0.0, 1.0); glMatrixMode(GL_MODELVIEW); glFlush(); } void GL::resize(int w, int h) { glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); //glOrtho(0.0, 10.0, 0.0, 10.0, -2.0, 2.0); gluPerspective(100.0, 1.0, 0.0, 100.0); //gluLookAt(3.0, -4.0, 5.0, 3.0, 3.0, 0.0, 0.0, 0.0, 1.0); Vector t = mViewpoint + mCameraDir * mMagni; gluLookAt(t.x(), t.y(), t.z(), mViewpoint.x(), mViewpoint.y(), mViewpoint.z(), 0.0, 0.0, 1.0); glMatrixMode(GL_MODELVIEW); } void GL::mouse(int button, int state, int x, int y) { switch (state) { case GLUT_DOWN: mMouseBuf[0] = x; mMouseBuf[1] = y; switch (button) { case GLUT_LEFT_BUTTON: mMouseButton = MB_LEFT; break; case GLUT_MIDDLE_BUTTON: mMouseButton = MB_MIDDLE; break; case GLUT_RIGHT_BUTTON: mMouseButton = MB_RIGHT; break; default: mMouseButton = MB_NOPUSH; break; } break; case GLUT_UP: mMouseButton = MB_NOPUSH; break; default: break; } } void GL::motion(int x, int y) { double drag_x = x - mMouseBuf[0]; double drag_y = y - mMouseBuf[1]; switch (mMouseButton) { case MB_LEFT: // 視点の移動 break; case MB_MIDDLE: // ズーム break; case MB_RIGHT: // カメラの移動 break; default: break; } mMouseBuf[0] = x; mMouseBuf[1] = y; } void GL::keyboard(unsigned char key, int x, int y) { switch (key) { case 'u': mMagni -= 1; if (mMagni < 5) mMagni = 5; break; case 'd': mMagni += 1; if (mMagni > 100) mMagni = 100; break; default: /* nothing to do */ break; } glutPostRedisplay(); } void GL::mainLoop() { glutMainLoop(); } /* void GL::idle() { }*/
true
b4b9ddd78998f1324f47f690a4b486e06fa50f04
C++
Psyc-d/C-
/Multiplication.cpp
UTF-8
218
2.671875
3
[]
no_license
#include<stdio.h> #include<math.h> int main() { int Num,It=10,A; printf("Enter The number \n"); scanf("%d",&Num); for(A=1;A<=10;A++) { printf("%d * %d = %d \n",Num,A,Num*A); } }
true
7a55314df30fd09f6afe9a73f459daffe71c6d97
C++
acyclics/ENGG1340_Group98
/main.cpp
UTF-8
6,801
3.515625
4
[]
no_license
/* File: main.cpp Purpose: Combine all modules to find optimal solution to problem */ #include <iostream> #include <string> #include <iomanip> #include <algorithm> #include "main.h" #include "testcase_generator.h" #include "simulator.h" /* Function: main Description: This function runs the program. Return: 0 */ int main() { using namespace std; using namespace testcase; /* Step 1: Goal: Generate testcases a. Let user define number of testcases and maximum number of cashiers b. Setup customer parameters: amount of items, payment methods c. Initialize and generate testcase matrix d. Ask user for extra details. These details DOES NOT affect simulation; rather, it changes the method for calculating optimal solution. e. If user has extra details, request input. Otherwise, go straight to Step 2. f. If the user has extra details, Step 3 will calculate optimal solution with METHOD 1. Else, Step 3 will calculate optimal solution with METHOD 2. */ int numberOfCustomers = 0, maxNumberOfCashiers = 0; cout << left << setw(25) << "Number of customers: "; cin >> numberOfCustomers; cout << setw(25) << "Number of cashiers: "; cin >> maxNumberOfCashiers; tcGenerator gen(numberOfCustomers, 2); /* Testcase description: We placed the testcases into a matrix. Each row corresponds to a customer and each column corresponds to a customer parameter. Customer parameter: ID:0 -- amount of goods ID:1 -- payment method -- 1: Octopus card 2: Cash 3: Credit card 4: Electronic payment */ gen.editConstraints(0, 0, 100, "int"); gen.editTimeConstants(0, 5); // Each grocery is assumed to take 5 seconds for checkout. gen.editConstraints(1, 1, 4, "int"); // Each payment method is given a multiplier according to the theoretical amount of time needed. For example, Cash is given gen.editTimeConstants(1, 3); // a multiplier of 2 whereas Octopus card is given a multiplier of 1 as customers generally need less time to pay by Octopus card. gen.generate(); string user_input; cout << "Do you know the average spending of each customer and cost of each cashier? (YES / NO): "; cin >> user_input; int customer_average_spending = 0, cost_of_cashier = 0; if (user_input == "YES") { // Ask for extra data cout << left << setw(35) << "Average spending of customers: "; cin >> customer_average_spending; cout << setw(35) << "Cost of each cashier: "; cin >> cost_of_cashier; } cout << "\n"; /* Step 2: Goal: Simulate! Simulation is done by the function "simulate". Details of implementation can be found in the file simulator.cpp. Below is a brief overview of the simulation process. Note that we are also gathering info during simulation for finding the optimal solution. a. Setup cashiers and start simulation. b. Customers will be uniformly distributed to the cashiers throughout the day. c. Once a customer has waited in queue for over 15 minutes, he / she will leave the queue. d. During the simulation, the number of customers served by each cashier is summed up. e. Simulation will continue until "one day" has passed. f. When simulation ends, it will return the total number of customers served. g. A for-loop will repeat the simulation from 1 to "maxNumberOfCashiers" which is specified by the user. The output from each simulation is stored into the array "increment". h. Note that during simulations, the minimum number of customers served is constantly updated. This variable is used for Step 3. */ int *increment = new int[maxNumberOfCashiers + 1]; increment[0] = 0; int minimum_customers_served = numeric_limits<int>::max(); cout << "********************* The following is the results of each simulation *********************\n\n"; for (int numberOfCashiers = 1; numberOfCashiers <= maxNumberOfCashiers; ++numberOfCashiers) { long long customers_served = simulate(numberOfCashiers, numberOfCustomers, gen); increment[numberOfCashiers] = customers_served; if (minimum_customers_served > customers_served) { minimum_customers_served = customers_served; } cout << left << fixed << setw(25) << "Number of cashiers:"; cout << setw(10) << numberOfCashiers; cout << setw(33) << "Number of served customers:"; cout << setw(10) << customers_served << "\n"; } cout << "\n"; /* Step 3: Goal: Find and output the optimal solution a. Iterate through the array "increment". b. If the user has provided extra data, use METHOD 1 to find optimal solution. Otherwise, use METHOD 2. c. Output the optimal solution. Method 1: - We have enough data to find an optimal solution that is tailored towards the user. - If "average customer spending" * "number of served customers" < "cost of each cashier" * "number of cashiers", then this "number of cashiers" and any larger number of cashiers is "not optimal". Method 2: - We do not have enough data to find an optimal solution that is tailored towards the user. So, we must base our decision on statistics alone. - If "number of customers served with (n) cashiers" - "number of customers served with (n - 1) cashiers" < "minimum number of customers served" * 0.5 then "n" cashiers and any larger number of cashiers is "not optimal". */ int bottle_neck = 1; int maximum = 0; for (int numberOfCashiers = 1; numberOfCashiers <= maxNumberOfCashiers; ++numberOfCashiers) { if (user_input == "YES") { // METHOD 1 if ( (customer_average_spending * increment[numberOfCashiers] < cost_of_cashier * numberOfCashiers) || increment[numberOfCashiers] <= maximum) { break; } } else { // METHOD 2 if (abs(increment[numberOfCashiers] - increment[numberOfCashiers - 1]) < minimum_customers_served * 0.5) { break; } } bottle_neck = numberOfCashiers; maximum = max(maximum, increment[numberOfCashiers]); } cout << "The recommended number of cashiers: " << bottle_neck << "\n"; // This is the optimal solution delete[] increment; return 0; }
true
256080ddfea09092bf956bb57c16455339c98d9b
C++
lsw9021/DexterousManipulation
/fem/Tensor3333.h
UTF-8
894
2.765625
3
[ "Apache-2.0" ]
permissive
#ifndef __FEM_TENSOR_3333_H__ #define __FEM_TENSOR_3333_H__ #include <iostream> #include <Eigen/Core> #include <Eigen/Sparse> #include <Eigen/Geometry> namespace FEM { class Tensor3333 { public: Tensor3333(); Tensor3333(const Tensor3333& other); Tensor3333& operator=(const Tensor3333& other); Tensor3333 operator+() const; Tensor3333 operator-() const; Tensor3333 operator+(const Tensor3333& B) const; Tensor3333 operator-(const Tensor3333& B) const; Tensor3333 operator*(const Eigen::Matrix3d& m) const; Tensor3333 operator*(double a) const; Eigen::Matrix3d& operator()(int i, int j); void SetIdentity(); void SetZero(); Tensor3333 Transpose(); public: Eigen::Matrix3d A[3][3]; }; Tensor3333 operator*(double a,const Tensor3333& B); Tensor3333 operator*(const Eigen::Matrix3d& m,const Tensor3333& B); std::ostream& operator<<(std::ostream& os,const Tensor3333& B); } #endif
true
0733519442211b4acddc9666cc533248746c459a
C++
nealwu/UVa
/volume131/13189 - Humbertov and the Triangular Spiral.cpp
UTF-8
788
2.703125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; pair<long long, long long> triangle_spiral(long long n) { if (n == 1) return make_pair(0, 0); long long bx = 0, by = 0, lv = 1; n--; long long k = sqrt(n/4); lv = k+1, bx += 2*k, by -= k, n -= 4*k*k; for (; n > (lv-1)*8+4; lv++) n -= (lv-1)*8+4, bx += 2, by--; bx--, n--; if (n < (lv-1)*4) { bx -= n; } else { bx -= (lv-1)*4, n -= (lv-1)*4; if (n < lv*2-1) { bx += n, by += n; } else { bx += lv*2-1, by += lv*2-1, n -= lv*2-1; bx += n, by -= n; } } return make_pair(bx, by); } int main() { int testcase; long long n; scanf("%d", &testcase); while (testcase--) { scanf("%lld", &n); pair<long long, long long> pos = triangle_spiral(n); printf("%lld %lld\n", pos.first, pos.second); } return 0; }
true
adc960ce7cb67802b6fd3c2404452cbb37506977
C++
Alexander-Saad/Newtech
/Операторы/Упражнение_14.cpp
UTF-8
415
2.625
3
[]
no_license
#include <clocale> #include <iostream> #include <Windows.h> #include <math.h> using namespace std; int main() { setlocale(LC_ALL, "Russian"); // Число человек между i-тым и k-тым членом очереди int i = 3, k = 10; cout << abs(i - k) - 1 << endl; //Только зачем в условии кол-во человек? system("pause"); return 0; }
true
519f4552dda427716b57790e337269010935a4e9
C++
Zilby/Graphics-Final
/monorepo-Zilby/Assignment4_NormalMappedModelParser/src/ObjParser.cpp
UTF-8
4,001
2.90625
3
[]
no_license
#include "ObjParser.h" ObjParser::ObjParser(std::string fileName) { // Get filepath of the object file's directory std::size_t endOfPath = fileName.find_last_of("/"); relFilePath = fileName.substr(0, endOfPath + 1); std::ifstream objFile; objFile.open(fileName); // Parse obj file if(objFile.is_open()) { std::string line; while(getline(objFile, line)) { parseObjLine(line); } } objFile.close(); std::ifstream mtlFile; mtlFile.open(relFilePath + mtlFileName); // Parse obj file's mtl file if(mtlFile.is_open()) { std::string line; while(getline(mtlFile, line)) { parseMtlLine(line); } } mtlFile.close(); } ObjParser::~ObjParser() { } void ObjParser::parseObjLine(std::string line) { if(line.length() > 1) { std::istringstream stream(line); std::string value; stream >> value; if(line[0] == 'v') { if (line[1] == 't') { ObjParser::Vec2<float> vec; for(int i = 0; i < 2; ++i) { stream >> value; vec[i] = std::stof(value); } vertTextures.push_back(vec); } else { ObjParser::Vec3<float> vec; for(int i = 0; i < 3; ++i) { stream >> value; vec[i] = std::stof(value); } if(line[1] == 'n') { normals.push_back(vec); } else { verts.push_back(vec); } } } else if(line[0] == 'f') { ObjParser::Vec3<unsigned int> verts; ObjParser::Vec3<unsigned int> vertTextures; ObjParser::Vec3<unsigned int> norms; for(int i = 0; i < 3; ++i) { stream >> value; std::size_t foundVert = value.find("/", 0); verts[i] = std::stoi(value.substr(0, foundVert)) - 1; std::size_t foundVertTexture = value.find("/", foundVert + 1); vertTextures[i] = std::stoi(value.substr(foundVert + 1, foundVertTexture)) - 1; std::size_t foundVertNorm = value.find("/", foundVertTexture + 1); norms[i] = std::stoi(value.substr(foundVertTexture + 1)) - 1; } ObjParser::Face f; f.verts = verts; f.vertTextures = vertTextures; f.norms = norms; faces.push_back(f); } else if(value == "mtllib") { stream >> value; mtlFileName = value; } } } void ObjParser::parseMtlLine(std::string line) { if(line.length() > 1) { std::istringstream stream(line); std::string value; stream >> value; if(value == "map_Kd") { stream >> value; diffuseMapName = value; } else if(value == "map_Bump") { stream >> value; normalMapName = value; } else if(value == "map_Ks") { stream >> value; spectralMapName = value; } } } std::vector<ObjParser::Vec3<float>> ObjParser::getVerts() { return verts; } std::vector<ObjParser::Vec3<float>> ObjParser::getNormals() { return normals; } std::vector<ObjParser::Vec2<float>> ObjParser::getVertTextures() { return vertTextures; } std::vector<ObjParser::Face> ObjParser::getFaces() { return faces; } std::string ObjParser::getDiffuseMap() { return relFilePath + diffuseMapName; } std::string ObjParser::getNormalMap() { return relFilePath + normalMapName; } std::string ObjParser::getSpectralMap() { return relFilePath + spectralMapName; } void ObjParser::debug() { for(int i = 0; i < verts.size(); ++i) { printf("v %f, %f, %f\n", verts[i].x, verts[i].y, verts[i].z); } for(int i = 0; i < normals.size(); ++i) { printf("vn %f, %f, %f\n", normals[i].x, normals[i].y, normals[i].z); } for(int i = 0; i < vertTextures.size(); ++i) { printf("vt %f, %f\n", vertTextures[i].x, vertTextures[i].y); } for(int i = 0; i < faces.size(); ++i) { printf("f %d/%d/%d, %d/%d/%d, %d/%d/%d\n", faces[i].verts.x, faces[i].vertTextures.x, faces[i].norms.x, faces[i].verts.y, faces[i].vertTextures.y, faces[i].norms.y, faces[i].verts.z, faces[i].vertTextures.z, faces[i].norms.z); } std::cout << "mtlFileName: " << mtlFileName << std::endl; std::cout << "diffuse map: " << diffuseMapName << std::endl; std::cout << "normal map: " << normalMapName << std::endl; std::cout << "spec map: " << spectralMapName << std::endl; }
true
fae60201a43dff832413a32a730307f5c4e5ae3e
C++
waxmar/PIC16C84
/PIC/ram.cpp
ISO-8859-1
3,566
2.71875
3
[]
no_license
#include "ram.h" #include <stdlib.h> #include "bitoperationen.h" #include "steuerwerk.h" #include "programmspeicher.h" #include "programmzaehler.h" #include <iostream> Ram::Ram(Steuerwerk* steuerwerk) { this->steuerwerk = steuerwerk; for (int i=0; i<0x50;i++) { // Alle Adressen zeigen auf Bank 0 adressen[0][i]=&bank0[i]; adressen[1][i]=&bank0[i]; bank0[i] = 0; bank1[i] = 0; } //Definition der Adressen auf Bank 1 S.6 adressen[1][0x01] = &bank1[0x01]; adressen[1][0x05] = &bank1[0x05]; adressen[1][0x06] = &bank1[0x06]; adressen[1][0x08] = &bank1[0x08]; adressen[1][0x09] = &bank1[0x09]; adressen[0][0x07] = NULL; adressen[1][0x07] = NULL; // Defaultwerte fr Speicher initialisieren! *adressen[1][OPTION] = 0xff; *adressen[0][STATUS] = 0x18; *adressen[1][TRISA] = 0xff; *adressen[1][TRISB] = 0xff; } //Auslesen des RAM-Inhaltes von einer bestimmten Bank int Ram::lesen(int adresse, int bank) { if (adressen[bank][adresse] == NULL) return 256; return *adressen[bank][adresse]; } //Auslesen des RAM-Inhaltes int Ram::lesen(int adresse) { int aktiveBank = getActiveBank(); if (adressen[aktiveBank][adresse] == NULL) return 256; return *adressen[aktiveBank][adresse]; } //Schreiben eines Wertes an eine bestimmte Adresse auf einer bestimmmten Bank void Ram::schreiben(int wert, int adresse, int bank) { if (adressen[bank][adresse] == NULL) return; *adressen[bank][adresse] = (wert & 0xff); } //Schreiben eines Wertes an eine bestimmte Adresse void Ram::schreiben(int wert, int adresse) { int aktiveBank = getActiveBank(); if (adressen[aktiveBank][adresse] == NULL) return; *adressen[aktiveBank][adresse] = (wert & 0xff); if(adresse == Ram::FSR) { if(Bitoperationen::pruefeBit(wert, 7)) adressen[1][0] = adressen[0][0] = adressen[1][wert & 0x7F]; else adressen[1][0] = adressen[0][0] = adressen[0][wert & 0x7F]; } if(adresse == Ram::PCLATH) { int pclath_wert = lesen(Ram::PCLATH, 0); int pc_wert = (pclath_wert << 8) + (wert & 0x00ff); if(pc_wert > steuerwerk->getProgrammspeicher()->getProgrammspeicherLaenge()) return; steuerwerk->getProgrammzaehler()->schreiben(pc_wert, Speicher::NOADDRESS); } } int* Ram::getReferenceOf(int adresse, int bank) { if(bank != 0 && bank != 1) return NULL; return adressen[bank][adresse]; } //Ermmitteln der zur Zeit aktiven Bank int Ram::getActiveBank() { return (bank0[0x03]&0x20>>5); } //setzt das Zero-Bit auf 1 void Ram::setzeZBit() { schreiben(Bitoperationen::setzeBit(lesen(STATUS), 2), STATUS, 0); } //setzt das Zero-Bit auf 0 void Ram::loescheZBit() { schreiben(Bitoperationen::loescheBit(lesen(STATUS), 2), STATUS, 0); } //setzt das Carry-Bit auf 1 void Ram::setzeCBit() { schreiben(Bitoperationen::setzeBit(lesen(STATUS),0), STATUS, 0); } //setzt das Carry-Bit auf 0 void Ram::loescheCBit() { schreiben(Bitoperationen::loescheBit(lesen(STATUS),0), STATUS, 0); } //setzt das DigitCarry-Bit auf 1 void Ram::setzeDCBit() { schreiben(Bitoperationen::setzeBit(lesen(STATUS),1), STATUS, 0); } //setzt das DigitCarry-Bit auf 0 void Ram::loescheDCBit() { schreiben(Bitoperationen::loescheBit(lesen(STATUS) ,1), STATUS, 0); }
true
d7711d5a37a068c63e1cce222948fda708dc7d78
C++
ifsmirnov/jngen
/printers.h
UTF-8
6,279
2.734375
3
[ "MIT" ]
permissive
#pragma once #include "repr.h" #include <iostream> #include <tuple> #include <type_traits> #include <typeinfo> #include <utility> #include <vector> namespace jngen { namespace detail { // TODO: maybe make it more clear SFINAE, like boost::has_left_shift<X,Y>? // TODO: make these defines namespace independent #define JNGEN_DEFINE_FUNCTION_CHECKER(name, expr)\ template<typename T, typename Enable = void>\ class Has ## name ## Helper: public std::false_type {};\ \ template<typename T>\ class Has ## name ## Helper<T,\ decltype(void(\ expr\ ))\ > : public std::true_type {};\ #define JNGEN_HAS_FUNCTION(name)\ ::jngen::detail::Has ## name ## Helper<T>::value JNGEN_DEFINE_FUNCTION_CHECKER( OstreamMethod, std::declval<std::ostream&>().operator<< (std::declval<T>()) ) JNGEN_DEFINE_FUNCTION_CHECKER( OstreamFreeFunction, std::operator<<(std::declval<std::ostream&>(), std::declval<T>()) ) JNGEN_DEFINE_FUNCTION_CHECKER( Plus, T(std::declval<T>() + 1) ) JNGEN_DEFINE_FUNCTION_CHECKER( Container, std::distance(std::declval<T>().begin(), std::declval<T>().end()) ) #define JNGEN_HAS_OSTREAM()\ (JNGEN_HAS_FUNCTION(OstreamMethod) ||\ JNGEN_HAS_FUNCTION(OstreamFreeFunction)) template<typename T> struct VectorDepth { constexpr static int value = 0; }; template<typename T, template <typename...> class C> struct VectorDepth<C<T>> { constexpr static int value = std::is_base_of< std::vector<T>, C<T> >::value ? VectorDepth<T>::value + 1 : 0; }; } // namespace detail #define JNGEN_DECLARE_PRINTER(constraint, priority)\ template<typename T>\ auto printValue(\ std::ostream& out, const T& t, const OutputModifier& mod, PTag<priority>)\ -> enable_if_t<constraint, void> #define JNGEN_DECLARE_SIMPLE_PRINTER(type, priority)\ inline void printValue(std::ostream& out, const type& t,\ const OutputModifier& mod, PTag<priority>) #define JNGEN_PRINT(value)\ printValue(out, value, mod, PTagMax{}) #define JNGEN_PRINT_NO_MOD(value)\ printValue(out, value, OutputModifier{}, PTagMax{}) JNGEN_DECLARE_PRINTER(!JNGEN_HAS_OSTREAM(), 0) { static bool locked = false; ensure( !locked, std::string{} + "You are trying to print a type for which " "operator<< is not defined: " + typeid(T).name()); locked = true; (void)mod; out << t; locked = false; } JNGEN_DECLARE_PRINTER(JNGEN_HAS_OSTREAM(), 10) { (void)mod; out << t; } JNGEN_DECLARE_PRINTER( JNGEN_HAS_OSTREAM() && JNGEN_HAS_FUNCTION(Plus), 11) { if (std::is_integral<T>::value) { out << T(t + mod.addition); } else { out << t; } } JNGEN_DECLARE_PRINTER(detail::VectorDepth<T>::value == 1, 3) { if (mod.printN) { out << t.size() << "\n"; } bool first = true; for (const auto& x: t) { if (first) { first = false; } else { out << mod.sep; } JNGEN_PRINT(x); } } JNGEN_DECLARE_PRINTER(detail::VectorDepth<T>::value == 1 && std::tuple_size<typename T::value_type>::value == 2, 4) { if (mod.printN) { out << t.size() << "\n"; } bool first = true; for (const auto& x: t) { if (first) { first = false; } else { out << "\n"; } JNGEN_PRINT(x); } } JNGEN_DECLARE_PRINTER(detail::VectorDepth<T>::value == 2, 4) { if (mod.printN) { out << t.size() << (mod.printM ? " " : ""); } if (mod.printM) { if (t.empty()) { out << 0; } else { auto size = t[0].size(); out << size; for (const auto& vec: t) { ensure(size == vec.size(), "Size of all matrix elements must " "be equal if printM is specified"); } } } if ((mod.printN || mod.printM) && !t.empty()) { out << "\n"; } auto tmp = mod; { auto mod = tmp; mod.printN = mod.printM = false; bool first = true; for (const auto& x: t) { if (first) { first = false; } else { out << '\n'; } JNGEN_PRINT(x); } } } JNGEN_DECLARE_PRINTER(JNGEN_HAS_FUNCTION(Container), 2) { if (mod.printN) { out << t.size() << "\n"; } bool first = true; for (const auto& x: t) { if (first) { first = false; } else { out << " "; } JNGEN_PRINT(x); } } JNGEN_DECLARE_PRINTER(JNGEN_HAS_FUNCTION(Container) && std::tuple_size<typename T::value_type>::value == 2, 3) { if (mod.printN) { out << t.size() << "\n"; } bool first = true; for (const auto& x: t) { if (first) { first = false; } else { out << "\n"; } JNGEN_PRINT(x); } } // http://stackoverflow.com/a/19841470/2159939 #define JNGEN_COMMA , template<typename Lhs, typename Rhs> JNGEN_DECLARE_SIMPLE_PRINTER(std::pair<Lhs JNGEN_COMMA Rhs>, 3) { JNGEN_PRINT(t.first); out << " "; JNGEN_PRINT(t.second); } #undef JNGEN_COMMA // Following snippet allows writing // cout << pair<int, int>(1, 2) << endl; // in user code. I have to put it into separate namespace because // 1) I don't want to 'use' all operator<< from jngen // 2) I cannot do it in global namespace because JNGEN_HAS_OSTREAM relies // on that it is in jngen. namespace namespace_for_fake_operator_ltlt { template<typename T> auto operator<<(std::ostream& out, const T& t) -> enable_if_t< !JNGEN_HAS_OSTREAM() && !std::is_base_of<BaseReprProxy, T>::value, std::ostream& > { // not jngen::printValue, because relying on ADL here for printers declared // later (see, e.g., http://stackoverflow.com/questions/42833134) printValue(out, t, jngen::defaultMod, jngen::PTagMax{}); return out; } } // namespace namespace_for_fake_operator_ltlt // Calling this operator inside jngen namespace doesn't work without this line. using namespace jngen::namespace_for_fake_operator_ltlt; } // namespace jngen using namespace jngen::namespace_for_fake_operator_ltlt;
true
9a25a0dc96e246905f99e3f96f1e38b00ec75dc4
C++
218478/PAMSI-SORT
/Lab5/MergeSortArray.cpp
UTF-8
384
2.828125
3
[]
no_license
#include "MergeSortArray.hh" #include <cstdlib> // to deal with pseudo-randomness bool MergeSortArray::Prepare(int size) { ExpandingType alloc_type = two_times; srand(time(NULL)); for (int i = 0; i < size; i++) // adding with doubling array size tablica.Add(alloc_type, static_cast<int>(rand())); return true; } bool MergeSortArray::Run() { tablica.MergeSort(); }
true
f2221cf5f67b77644867b41c0e67e38c43885790
C++
Manan007224/street-coding
/Leetcode/add_to_num.cpp
UTF-8
1,102
3.59375
4
[]
no_license
#include <iostream> using namespace std; struct ListNode { int val; ListNode *next; //ListNode(int x) : val(x), next(NULL) {} }; ListNode* new_node(int val){ ListNode *l1 = new ListNode; l1->val = val; l1->next = NULL; return l1; } class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode * current = new_node(0); int cr = 0; while(l1!=NULL || l2!=NULL) { int f = l1!=NULL ? l1->val : 0; int s = l2!=NULL ? l2->val : 0; int add = (f+s+cr); cr = add/10; cout << add%10 << endl; current->next = new_node(add%10); l1 = l1 ? l1->next : NULL; l2 = l2 ? l2->next : NULL; current = current->next; } if(cr>0) current->next = new_node(cr); return current->next; } }; int main(){ Solution sln; ListNode * l1 = new_node(1); l1->next = new_node(3); ListNode * l2 = new_node(2); l2->next = new_node(4); ListNode * l3 = sln.addTwoNumbers(l1,l2); ListNode * iter; for(iter=l3;iter!=NULL;iter=iter->next) cout << iter->val << endl; return 0; }
true
c0203744fbd539f1011c785940c52dfdf48060e8
C++
shaybarak/Tomasulo
/simulator/MIPS32/GPR.h
UTF-8
584
3.015625
3
[]
no_license
#pragma once #include "ISA.h" #include <ostream> /** * MIPS32 general purpose registers. */ class GPR { public: // Returns whether GPR index is valid static bool isValid(int index); // Initializes all registers to zero #pragma warning(disable:4351) // gpr array init to zero is the desired behavior GPR() : gpr(), zero(0) {} // Assumes index is in range int& operator[](int index); // Assumes index is in range const int& operator[](int index) const; // Dump to file, returns whether successful bool dump(ostream& out); private: int gpr[ISA::REG_COUNT]; int zero; };
true
728efa0dbd3df88818c36299d5b901ede24bc1e8
C++
dculp94/School-Assignments
/CULPDE/Radix.h
UTF-8
897
2.84375
3
[]
no_license
/******************************************** * Header file for Radix.h * * Richard Walker * 06/12/2014 * **/ #ifndef RADIX_H #define RADIX_H #include <vector> #include <string> #include "../../Utilities/Utils.h" #include "../../Utilities/Scanner.h" using namespace std; class Radix { public: Radix(); virtual ~Radix(); void runRadix(Scanner& inScanner, ofstream& outStream); void printVector(int radixnum, int n, vector<int> v); int createVector(int n, int radixnum, vector<int> & v); private: void add(int radixnum, int & l3, vector<int> & v3, int l1, vector<int> v1, int l2, vector<int> v2); void multiply(int radixnum, int & l3, vector<int> & v3, int l1, vector<int> v1, int l2, vector<int> v2); }; #endif // RADIX_H
true
823e4771dc37cafbad9111b1245ba72bdbb09c42
C++
ephi/GraphMaximalSimplePath
/task_3/Graph.cpp
UTF-8
746
2.75
3
[]
no_license
#include "Graph.h" #include "ListForEachGraphTranspose.h" #include "ListForEachGraphPrint.h" #include "ListForEachGraphResetForScan.h" Graph::Graph() { vertices = new ListVertices(); } void Graph::transpose() { ListForEachGraphTranspose * lfegt = new ListForEachGraphTranspose(); vertices->ForEach(lfegt); delete lfegt; } void Graph::addVertex(Vertex* v){ vertices->Add(v); } void Graph::printGraph(ostream & os){ ListForEachGraphPrint * lfegp = new ListForEachGraphPrint(os); vertices->ForEach(lfegp); delete lfegp; } void Graph::resetNodesForScan(){ ListForEachGraphResetForScan * lfe = new ListForEachGraphResetForScan(); vertices->ForEach(lfe); delete lfe; } Graph::~Graph(void) { delete vertices; }
true
b7bd56f3cc7b6d2d9377a82eec72ddbc1e9ed938
C++
saturn1mc/puls4r
/C++/src/Phong.h
UTF-8
1,829
2.8125
3
[]
no_license
/* * Phong.h * puls4r * * Created by Camille on 23/01/08. * Copyright 2008 __MyCompanyName__. All rights reserved. * */ #ifndef PHONG_H #define PHONG_H #include <list> #include "Enlightment.h" #include "Light.h" class Phong : public Enlightment{ private: Color* oa; //ambient color Color* od; //diffuse color Color* os; //specular color double ia; double ka; //ambient reflection constant double kd; //diffuse reflection constant double ks; //specular reflection constant int n; //rugosity constant public: Phong(Color* _od) : oa(new Color((*_od) * ia)), od(new Color(_od)), os(new Color(1.0, 1.0, 1.0)), ia(1.0), ka(1.0), kd(0.7), ks(0.3), n(10) {} Phong(Color* _oa, Color* _od, Color* _os, double _ia, double _ka, double _kd, double _ks, int _n) : oa(new Color(_oa)), od(new Color(_od)), os(new Color(_os)), ia(_ia), ka(_ka), kd(_kd), ks(_ks), n (_n) {} Phong(const Phong& phong) : oa(new Color(phong.oa)), od(new Color(phong.od)), os(new Color(phong.os)), ia(phong.ia), ka(phong.ka), kd(phong.kd), ks(phong.ks), n(phong.n) {} Phong(const Phong* phong) : oa(new Color(phong->oa)), od(new Color(phong->od)), os(new Color(phong->os)), ia(phong->ia), ka(phong->ka), kd(phong->kd), ks(phong->ks), n(phong->n) {} virtual ~Phong(void) { delete(oa); delete(od); delete(os); } virtual Color getColor(Point* point, Vector* norm, Ray* ray, std::list<Light* > lights) const; virtual Enlightment* clone() {return new Phong(*this);} Phong& operator=(const Phong& phong){ delete(oa); delete(od); delete(os); reflect = phong.reflect; kr = phong.kr; oa = new Color(phong.oa); od = new Color(phong.od); os = new Color(phong.os); ia = phong.ia; ka = phong.ka; kd = phong.kd; ks = phong.ks; n = phong.n; return *this; } }; #endif //PHONG_H
true
49f82949ba58d8f612db1fb9c2313c5aa77e7fbd
C++
SP0N9E/Study4Job
/LeetCode/494.目标和.cpp
UTF-8
2,981
3.0625
3
[]
no_license
/* * @Author: SP0N9E * @Description: Edit * @Date: 2020-08-01 17:44:02 * @LastEditors: SP0N9E * @LastEditTime: 2020-08-01 18:07:41 * @FilePath: \C++_Code\LeetCode\494.目标和.cpp */ /* * @lc app=leetcode.cn id=494 lang=cpp * * [494] 目标和 * * https://leetcode-cn.com/problems/target-sum/description/ * * algorithms * Medium (44.39%) * Likes: 340 * Dislikes: 0 * Total Accepted: 37.4K * Total Submissions: 84.3K * Testcase Example: '[1,1,1,1,1]\n3' * * 给定一个非负整数数组,a1, a2, ..., an, 和一个目标数,S。现在你有两个符号 + 和 -。对于数组中的任意一个整数,你都可以从 + 或 * -中选择一个符号添加在前面。 * * 返回可以使最终数组和为目标数 S 的所有添加符号的方法数。 * * * * 示例: * * 输入:nums: [1, 1, 1, 1, 1], S: 3 * 输出:5 * 解释: * * -1+1+1+1+1 = 3 * +1-1+1+1+1 = 3 * +1+1-1+1+1 = 3 * +1+1+1-1+1 = 3 * +1+1+1+1-1 = 3 * * 一共有5种方法让最终目标和为3。 * * * * * 提示: * * * 数组非空,且长度不会超过 20 。 * 初始的数组的和不会超过 1000 。 * 保证返回的最终结果能被 32 位整数存下。 * * */ #include <iostream> #include <vector> #include <map> #include <unordered_map> #include <algorithm> #include <queue> #include <set> #include <unordered_set> #include <stack> #include <assert.h> #include <string> #include <memory> using namespace std; // @lc code=start class Solution { public: // 回溯法 int result = 0; int findTargetSumWays_1(vector<int> &nums, int S) { if (nums.size() == 0) return 0; backtrack(nums, 0, S); return result; } void backtrack(vector<int> &nums, int i, int rest) { if (i == nums.size()) { if (rest == 0) result++; return; } rest += nums[i]; backtrack(nums, i + 1, rest); rest -= nums[i]; rest -= nums[i]; backtrack(nums, i + 1, rest); rest += nums[i]; } int findTargetSumWays(vector<int> &nums, int S) { int sum = 0; for (auto n : nums) sum += n; if (sum < S || (sum + S) % 2 == 1) { return 0; } return subsets(nums, (sum + S) / 2); } int subsets(vector<int> &nums, int sum) { int n = nums.size(); vector<vector<int>> dp(n + 1, vector<int>(sum + 1)); for (int i = 0; i <= n; i++) { dp[i][0] = 1; } for (int i = 1; i <= n; i++) { for (int j = 0; j <= sum; j++) { if (j >= nums[i - 1]) dp[i][j] = dp[i - 1][j] + dp[i - 1][j - nums[i - 1]]; else { dp[i][j] = dp[i - 1][j]; } } } return dp[n][sum]; } }; // @lc code=end
true
fd1432c2a25b79e21f476bcf36591edca0784b32
C++
Muikkunen/Lieburo
/src/BananaGun.cpp
UTF-8
931
2.75
3
[ "MIT" ]
permissive
#include "BananaGun.hpp" #include "Banana.hpp" #include <iostream> BananaGun::BananaGun(Game* game): Weapon(4, 0.5f, 5, 25.0f, "texture/bananagun.png", game){ ammo = clipSize; (void) game; } void BananaGun::shoot(float angle, b2Vec2 position, b2Vec2 preSpeed, Game* game){ (void) game; //Checking the fire rate if(fireClock.getElapsedTime().asSeconds() < fireRate) { return; } //Checking for empty clip. if(ammo == 0) { if(fireClock.getElapsedTime().asSeconds() > reloadTime) { ammo = clipSize; //reload time up -> load clip } else { return; } } std::shared_ptr<Banana> b = std::make_shared<Banana>(mGame); mGame->getSceneNode()->attachChild(std::dynamic_pointer_cast<SceneNode>(b)); b->getBody()->SetAngularVelocity(25);//Adding a nice spin launchProjectile(angle, position, preSpeed, b); fireClock.restart();//restarting the fire rate observing clock ammo--;//reducing ammo in the clip by 1. }
true
afd3f1de14777c72ba549219d3403993dcc97585
C++
jstty/OlderProjects
/Games/SuperShooter/SuperShooter_source/code/sprite.cpp
UTF-8
6,021
2.765625
3
[]
no_license
////////////////////////////////////////////////////////////////////////////// // Program Name: sprite.cpp // Programmer: Joseph E. Sutton // Description: Sprint // Course: cs371 // Start Date: 10/23/2004 // Last Updated: // Version: 1.00 ////////////////////////////////////////////////////////////////////////////// #include "sprite.h" SpriteData::SpriteData() { w = 0; h = 0; data = NULL; pts_num = NULL; pts_off[0] = NULL; pts_off[1] = NULL; } SpriteData::~SpriteData() { if(data != NULL) { for(i = 0; i < size; i++) { if(data[i] != NULL) { tsize = 2*pts_num[i]; for(k = 0; k < tsize; k++) { if(data[i][k] != NULL) delete [] data[i][k]; } delete [] data[i]; } } delete [] data; } if(pts_num != NULL) delete [] pts_num; if(pts_off[0] != NULL) delete [] pts_off[0]; if(pts_off[1] != NULL) delete [] pts_off[1]; } // copy data SpriteData::SpriteData(const SpriteData & src) { size = src.size; w = src.w; h = src.h; data = new void **[size]; pts_num = new uInt16[size]; pts_off[0] = new uInt16[size]; pts_off[1] = new uInt16[size]; memcpy(pts_num, src.pts_num, sizeof(uInt16)*size); memcpy(pts_off[0], src.pts_off[0], sizeof(uInt16)*size); memcpy(pts_off[1], src.pts_off[1], sizeof(uInt16)*size); for(i = 0; i < size; i++) { if(data[i] != NULL) { tpts_num = 2*pts_num[i]; data[i] = new void *[tpts_num]; for(k = 0; k < tpts_num; k++) { data[i][k] = new float[4]; memcpy(data[i][k], src.data[i][k], sizeof(float)*4 ); k++; data[i][k] = new uInt16[2]; memcpy(data[i][k], src.data[i][k], sizeof(uInt16)*2 ); } } } } // int SpriteData::LoadFile(char *file) { uInt16 j; char inChar, chpt[256]; int inInt; float inFloat; ifstream inFs(file, ios::in ); if( inFs.fail() ) { cerr << "File could not be opened\n"; return 100; } inFs.get(inChar); if( !inFs.fail() ) { inFs.putback(inChar); inFs >> size; inFs >> inInt; w = inInt; inFs >> inInt; h = inInt; data = new void **[size]; pts_num = new uInt16[size]; pts_off[0] = new uInt16[size]; pts_off[1] = new uInt16[size]; i = 0; while( !inFs.fail() ) { inFs.get(inChar); while(inChar == '#') { inFs.getline(chpt, 255); inFs.get(inChar); } if( (inChar != '\n') && (inChar != '\r') ) { inFs.putback(inChar); inFs >> inInt; pts_num[i] = inInt; inFs >> inInt; pts_off[0][i] = inInt; inFs >> inInt; pts_off[1][i] = inInt; tpts_num = 2*pts_num[i]; data[i] = new void *[tpts_num]; for(k = 0; k < tpts_num; k++) { data[i][k++] = new float[4]; data[i][k] = new uInt16[2]; } for(k = 0; k < tpts_num; k++) { for(j = 0; j < 4; j++) { inFs >> inFloat; ((float *)data[i][k])[j] = inFloat; } k++; for(j = 0; j < 2; j++) { inFs >> inInt; ((uInt16 *)data[i][k])[j] = inInt; } } i++; } } } inFs.close(); return 0; } void SpriteData::Draw(sInt16 x, sInt16 y) { if(data != NULL) { for(i = 0; i < size; i++) // group { if(data[i] != NULL) { tsize = 2*pts_num[i]; glBegin(GL_POLYGON); for(k = 0; k < tsize; k++) { if(data[i][k] != NULL) { // Set Color glColor4fv( (float *)data[i][k++] ); // Add Point tx = pts_off[0][i] + ((sInt16 *)data[i][k])[0] + x; ty = pts_off[1][i] + ((sInt16 *)data[i][k])[1] + y; glVertex2s(tx, ty); } } glEnd(); } } } } Sprite::Sprite() { current_anim = 0; num_anim = 0; anim = NULL; } Sprite::~Sprite() { if(anim != NULL) { for(i = 0; i < num_anim; i++) { if(anim[i] != NULL) delete anim[i]; } } } Sprite::Sprite(const Sprite & src) { copy(src); } void Sprite::Draw(uInt16 an) { if(anim != NULL) { if( an < num_anim) { current_anim = an; if(anim[current_anim] != NULL) { anim[current_anim]->Draw(x, y); } } } } int Sprite::Load(char **file, uInt16 num) { if(file != NULL) { num_anim = num; anim = new SpriteData *[num_anim]; for(i = 0; i < num_anim; i++) { if(file[i] != NULL) { anim[i] = new SpriteData(); anim[i]->LoadFile(file[i]); } } } return 1; } sInt32 * Sprite::Rect() { if(anim != NULL) { if(anim[current_anim] != NULL) { rect[0] = x; rect[1] = y; rect[2] = x + anim[current_anim]->GetWidth(); rect[3] = y + anim[current_anim]->GetHeight(); } } return rect; } void Sprite::copy(const Sprite & src) { num_anim = src.num_anim; anim = new SpriteData *[num_anim]; for(i = 0; i < num_anim; i++) { if(src.anim[i] != NULL) { anim[i] = new SpriteData(*src.anim[i]); } } }
true
8549426a406f5440fd40668dd9c7e1f869bba747
C++
ramandeepladda/pepcoding
/Lec31Aug/BTree.cpp
UTF-8
1,891
3.765625
4
[]
no_license
#include <iostream> #include <vector> #include <math.h> using namespace std; void swap(vector<int> &arr, int l, int r) { for (int i = l, j = r; i < j; i++, j--) { int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } } void reverseK(vector<int> &arr, int k) { k = k < 0 ? k + arr.size() + 1 : k % arr.size(); swap(arr, 0, k - 1); swap(arr, k, arr.size() - 1); swap(arr, 0, arr.size() - 1); } void fillLeftMax(vector<int> &arr, vector<int> &leftmax) { int max = arr[0]; leftmax[0] = 0; for (int i = 1, j = 1; j < arr.size(); i++, j++) { leftmax[j] = max; if (max > arr[i]) { max = arr[i]; } } } void fillRightMax(vector<int> &arr, vector<int> &rightmax) { int max = arr[arr.size() - 1]; rightmax[arr.size() - 1] = 0; for (int i = arr[arr.size() - 2], j = arr.size() - 2; j >= 0; i--, j--) { rightmax[j] = max; if (max > arr[i]) { max = arr[i]; } } cout << "rightmax" << endl; for (int x : rightmax) { cout << x << endl; } } int main() { vector<int> arr(3, 0); vector<int> leftmax(3, 0); vector<int> rightmax(3, 0); int sum = 0; for (int i = 0; i < arr.size(); i++) cin >> arr[i]; cout << endl << endl; fillLeftMax(arr, leftmax); for (int i = 0; i < arr.size(); i++) { int y = leftmax[i] - rightmax[i]; if (y > 0) sum += y - arr[i]; } cout << "the sum is :" << sum; /* cout<<"enter elements"<<endl; for(int i=0; i< arr.size() ;i++) cin>>arr[i]; fillLeftMax(arr ,leftmax); for(int x : arr) cout<<x<<" "; cout<<endl; reverseK(arr , -3); cout<<endl<<"after rotation"<<endl; for(int x : arr) cout<<x<<" "; cout<<endl;*/ return 0; }
true
c70cb555f419ccb275dd1fc95f063f1802c07245
C++
MicrosoftDocs/cpp-docs
/docs/mfc/reference/codesnippet/CPP/casyncsocket-class_3.cpp
UTF-8
1,034
2.578125
3
[ "CC-BY-4.0", "MIT" ]
permissive
// CMyAsyncSocket is derived from CAsyncSocket and defines the // following variables: // CString m_sendBuffer; //for async send // int m_nBytesSent; // int m_nBytesBufferSize; void CMyAsyncSocket::OnSend(int nErrorCode) { while (m_nBytesSent < m_nBytesBufferSize) { int dwBytes; if ((dwBytes = Send((LPCTSTR)m_sendBuffer + m_nBytesSent, m_nBytesBufferSize - m_nBytesSent)) == SOCKET_ERROR) { if (GetLastError() == WSAEWOULDBLOCK) { break; } else { TCHAR szError[256]; _stprintf_s(szError, _T("Server Socket failed to send: %d"), GetLastError()); Close(); AfxMessageBox(szError); } } else { m_nBytesSent += dwBytes; } } if (m_nBytesSent == m_nBytesBufferSize) { m_nBytesSent = m_nBytesBufferSize = 0; m_sendBuffer = _T(""); } CAsyncSocket::OnSend(nErrorCode); }
true
a8c46b2b6c429077d936702ac7dd92cc18839d49
C++
davidwang318/LeetCode
/Easy/155_MinStack.cpp
UTF-8
650
3.3125
3
[]
no_license
// First Attemp. Feels good to have think of using List. // Time: 91.94%, Memory: 100.00% class MinStack { public: /** initialize your data structure here. */ MinStack() { } void push(int x) { s.push(x); if(minList.empty() || x <= minList.front()) minList.push_front(x); return; } void pop() { if(s.top() == minList.front()) minList.pop_front(); s.pop(); return; } int top() { return s.top(); } int getMin() { return minList.front(); } private: stack<int> s; list<int> minList; };
true