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
d0f59dfd4a3093d3d008c8f4c626f18200bad289
C++
hardcookies/dsaalgs
/binary_tree/traversal_BFS.cpp
UTF-8
2,755
4.375
4
[]
no_license
/******************************************************************* Copyright(c) 2018, James Fan All rights reserved. *******************************************************************/ // 二叉树的遍历算法 // C++实现二叉树广度优先遍历(BFS)又称层遍历 // 分别使用两种方法实现:1.使用输出某层的函数 2.使用队列 // 参考代码:https://www.geeksforgeeks.org/level-order-tree-traversal/ #include <iostream> #include <queue> using namespace std; /* 二叉树节点的定义 */ struct TreeNode { int val; TreeNode *left, *right; }; /* 方法一函数声明 */ void printGivenLevel(TreeNode *node, int level); int height(TreeNode *node); TreeNode* newNode(int value); /* 逐层遍历树:方法一 */ void printLevelOrder1(TreeNode *root) { int h = height(root); for (int i = 0; i < h; ++i) printGivenLevel(root, i); } /* 打印指定层 */ void printGivenLevel(TreeNode *root, int level) { if (root == nullptr) return; if (level == 0) cout << root->val << " "; else if (level > 0) { printGivenLevel(root->left, level-1); printGivenLevel(root->right, level-1); } } /* 计算树的高度 */ int height(TreeNode *root) { if (root == nullptr) return 0; else { /* 计算左右子树的高度 */ int lheight = height(root->left); int rheight = height(root->right); /* 返回较大者 */ if (lheight > rheight) return lheight + 1; else return rheight + 1; } } /* 创建新的节点并返回指针 */ TreeNode* newNode(int value) { TreeNode *temp = new TreeNode; temp->val = value; temp->left = temp->right = nullptr; return temp; } /* 层序遍历树:方法二 */ void printLevelOrder2(TreeNode *root) { if (root == nullptr) return; // 创建空队列实现层序遍历 queue<TreeNode *> q; // 根节点入队 q.push(root); while (!q.empty()) { // 打印队首节点并出队 TreeNode *node = q.front(); cout << node->val << " "; q.pop(); // 左子节点入队 if (node->left != nullptr) q.push(node->left); // 右子节点入队 if (node->right != nullptr) q.push(node->right); } } // 测试代码 int main(int argc, char const *argv[]) { /* 遍历如下二叉树: 1 / \ 2 3 / \ 4 5 */ TreeNode *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); // 树高 cout << "The height of tree is " << height(root) << endl; // 层序遍历:方法一 cout << "Method 1:" << endl; cout << "Level order traversal: "; printLevelOrder1(root); cout << endl; // 层序遍历:方法二 cout << "Method 2:" << endl; cout << "Level order traversal: "; printLevelOrder2(root); cout <<endl; return 0; }
true
8d2eb963ec99064741b6bc17cf9494f8c2b77764
C++
Abhishek2401/data-structures
/stack.cpp
UTF-8
2,374
3.09375
3
[]
no_license
// Copyright 2019 Souvik Biswas // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #include <iostream> using namespace std; int stack[100], n=100, top=-1; void push(int val) { if(top>=n-1) cout<<"Stack Overflow"<<endl; else { top++; stack[top]=val; } } void pop() { if(top<=-1) cout<<"Stack Underflow"<<endl; else { cout<<"The popped element is "<< stack[top] <<endl; top--; } } void display() { if(top>=0) { cout<<"Stack elements are:"; for(int i=top; i>=0; i--) cout<<stack[i]<<" "; cout<<endl; } else cout<<"Stack is empty"; } int main() { int ch, val; cout<<"1) Push in stack"<<endl; cout<<"2) Pop from stack"<<endl; cout<<"3) Display stack"<<endl; cout<<"4) Exit"<<endl; do { cout<<"Enter choice: "<<endl; cin>>ch; switch(ch) { case 1: { cout<<"Enter value to be pushed:"<<endl; cin>>val; push(val); break; } case 2: { pop(); break; } case 3: { display(); break; } case 4: { cout<<"Exit"<<endl; break; } default: { cout<<"Invalid Choice"<<endl; } } }while(ch!=4); return 0; }
true
9864ddfaa5aebb34c6b6884a587c285288841f54
C++
AstyCo/eqmpi
/iterations.cpp
UTF-8
19,059
2.515625
3
[]
no_license
#include "iterations.hpp" #include <algorithm> #include <string.h> //#include <mem.h> void Iterations::Requests::append(Iterations::Requests::Info info, uint sz) { iv.push_back(info); v.push_back(MPI_REQUEST_NULL); buffs.push_back(RealVector()); buffs.back().resize(sz); statuses.push_back(MPI_Status()); } Iterations::Iterations(uint N_) : N(N_), next_step(0) { fill(cnode); } void Iterations::prepare() { step0(); // printDeviationsPrivate(arrayPP, 0); step1(); // printDeviationsPrivate(arrayP, 1); } void Iterations::run() { MY_ASSERT(next_step == 2); // STEPS for (; next_step < clargs.K + 1; ++next_step) { profiler.step(); cnode.print(SSTR("ITER " << next_step << ',' << profiler.time())); async_recv_all(); async_send_all(); #ifdef WITH_OMP # pragma omp parallel for // parallel slices #endif for (int i = 1; i < ic - 1; ++i) { for (uint j = 1; j < jc - 1; ++j) { for (uint k = 1; k < kc - 1; ++k) { calculate(i, j, k); } } } // sync recv prev { int request_index; MPI_Status status; for(;;) { MPI_Waitany(recv_requests.v.size(), recv_requests.v.data(), &request_index, &status); if (request_index == MPI_UNDEFINED) { break; } CHECK_INDEX(request_index, 0, recv_requests.iv.size()); const Iterations::Requests::Info &info = recv_requests.iv[request_index]; copy_data(recv_requests, request_index, MPI_OP_RECV); calculate(info.dir); } } calculate_edge_values(); if (clargs.deviation) { prepareSolution(next_step); printDeviations(next_step); } if (next_step < clargs.K) shift_arrays(); // update arrays } // ENDS STEPS } void Iterations::async_send_all() { MPI_Waitall(send_requests.v.size(), send_requests.v.data(), send_requests.statuses.data()); // wait for every asynchronous send (so we can use send buffers again) // asynchronous send to every neighbor processor for (int i = 0; i < send_requests.size(); ++i) { copy_data(send_requests, i, MPI_OP_SEND); MPI_Isend(send_requests.buffs[i].data(), send_requests.buffs[i].size(), MPI_TYPE_REAL, cnode.neighbor(send_requests.iv[i].dir), send_requests.iv[i].dir, MPI_COMM_WORLD, &send_requests.v[i]); } } void Iterations::async_recv_all() { // asynchronous recv from every neighbor processor for (uint i = 0; i < recv_requests.size(); ++i) { MPI_Irecv(recv_requests.buffs[i].data(), recv_requests.buffs[i].size(), MPI_TYPE_REAL, cnode.neighbor(recv_requests.iv[i].dir), CDPair(recv_requests.iv[i].dir), MPI_COMM_WORLD, &recv_requests.v[i]); } } void Iterations::prepareSolution(uint n) { #ifdef WITH_OMP # pragma omp parallel for #endif for (int i = 0; i < ic; ++i) { for (uint j = 0; j < jc; ++j) { for (uint k = 0; k < kc; ++k) { long id = get_index(i, j, k); analyticalSolution[id] = u(x(i), y(j), z(k), time(n)); } } } } real Iterations::getDeviation(const Iterations::RealVector &arr, uint i, uint j, uint k, uint n) const { long long id = get_index(i, j, k); real correctAnswer = analyticalSolution[id]; real approxAnswer = arr[id]; return ABS(correctAnswer - approxAnswer); } void Iterations::printDeviations(uint n) { printDeviationsPrivate(array, n); } void Iterations::printDeviationsPrivate(const Iterations::RealVector &arr, uint n) { prepareSolution(n); real avgDeviation = 0; real corr = 0, appr = 0; #ifdef WITH_OMP # pragma omp parallel for #endif for (int i = 0; i < ic; ++i) { for (uint j = 0; j < jc; ++j) { for (uint k = 0; k < kc; ++k) { long long id = get_index(i, j, k); real correctAnswer = analyticalSolution[id]; real approxAnswer = arr[id]; corr += correctAnswer; appr += approxAnswer; avgDeviation += getDeviation(arr, i, j, k, n); } } } real globalDeviation=0; MPI_Reduce(&avgDeviation, &globalDeviation, 1, MPI_TYPE_REAL, MPI_SUM, 0, MPI_COMM_WORLD); globalDeviation /= N*N*N; // long size = ic * jc * kc; // avgDeviation /= size; // if (avgDeviation > 0.01) { // cnode.print(SSTR("local delta for step " << n << " equals " // << avgDeviation << " app " << appr << " corr " << corr)); // } if (cnode.mpi.rank == 0) { std::cout << SSTR("%%%," << cnode.scTag() << ',' << cnode.mpi.procCount << ',' << N << ',' << next_step << ',' << globalDeviation) << std::endl; } } uint Iterations::dir_size(ConnectionDirection cdir) { switch (cdir) { case DIR_X: case DIR_MINUS_X: return jc * kc; case DIR_Y: case DIR_MINUS_Y: case DIR_Y_PERIOD_FIRST: case DIR_Y_PERIOD_LAST: return ic * kc; case DIR_Z: case DIR_MINUS_Z: return ic * jc; default: MY_ASSERT(false); return 0; } } void Iterations::fill(const ComputeNode &n) { MY_ASSERT(0 == n.mpi.procCount % n.gridDimensions.x); MY_ASSERT(0 == n.mpi.procCount % n.gridDimensions.y); MY_ASSERT(0 == n.mpi.procCount % n.gridDimensions.z); ic = N / n.gridDimensions.x; jc = N / n.gridDimensions.y; kc = N / n.gridDimensions.z; int iMissedItemCount = N % n.gridDimensions.x; int jMissedItemCount = N % n.gridDimensions.y; int kMissedItemCount = N % n.gridDimensions.z; i0 = MIN(n.x, iMissedItemCount) * (ic + 1) + MAX(n.x - iMissedItemCount, 0) * ic; j0 = MIN(n.y, jMissedItemCount) * (jc + 1) + MAX(n.y - jMissedItemCount, 0) * jc; k0 = MIN(n.z, kMissedItemCount) * (kc + 1) + MAX(n.z - kMissedItemCount, 0) * kc; if (cnode.x < iMissedItemCount) ++ic; if (cnode.y < jMissedItemCount) ++jc; if (cnode.z < kMissedItemCount) ++kc; hx = VAL_LX / ic; hy = VAL_LY / jc; hz = VAL_LZ / kc; ht = VAL_T / clargs.K; bigsize = (ic + 2) * (jc + 2) * (kc + 2); // optimization (allocations may throw std::bad_alloc if no enough memory) try { prepareEdgeIndices(); array.resize(bigsize); arrayP.resize(bigsize); arrayPP.resize(bigsize); if (clargs.deviation) analyticalSolution.resize(bigsize); for (int i = 0; i < DIR_SIZE; ++i) { ConnectionDirection cdir = toCD(i); if (n.hasNeighbor(cdir)) { Requests::Info info; info.dir = cdir; send_requests.append(info, dir_size(cdir)); recv_requests.append(info, dir_size(cdir)); } } } catch(...) { MY_ASSERT(false); } } void Iterations::copy_recv(RealVector &v, RealVector &a, int i, int j, int k, uint offset) { CHECK_INDEX(offset, 0, v.size()); CHECK_INDEX(get_index(i, j, k), 0, a.size()); a[get_index(i, j, k)] = v[offset]; } void Iterations::copy_send(RealVector &v, RealVector &a, int i, int j, int k, uint offset) { CHECK_INDEX(offset, 0, v.size()); CHECK_INDEX(get_index(i, j, k), 0, a.size()); v[offset] = a[get_index(i, j, k)]; // cnode.print(SSTR("copy_send " << offset // << '=' << i << ',' << j << ',' << k // << '(' << get_p_index(i, j, k) << ')')); } void Iterations::copy_data(Requests &requests, uint id, MPI_OP type) { CHECK_INDEX(id, 0, requests.iv.size()); CopyMFuncPtr copy_func = ((type == MPI_OP_SEND) ? &Iterations::copy_send : &Iterations::copy_recv); ConnectionDirection cdir= requests.iv[id].dir; RealVector &v = requests.buffs[id]; uint offset = 0; switch (cdir) { case DIR_X: case DIR_MINUS_X: { int i = edgeId(cdir, type); for (uint j = 0; j < jc; ++j) { for (uint k = 0; k < kc; ++k) { (this->*copy_func)(v, arrayP, i, j, k, offset++); } } break; } case DIR_Y: case DIR_MINUS_Y: case DIR_Y_PERIOD_FIRST: case DIR_Y_PERIOD_LAST: { RealVector &a = (((cdir == DIR_Y_PERIOD_LAST) && (type == MPI_OP_RECV)) ? array : arrayP); int j = edgeId(cdir, type); for (uint i = 0; i < ic; ++i) { for (uint k = 0; k < kc; ++k) { (this->*copy_func)(v, a, i, j, k, offset++); } } break; } case DIR_Z: case DIR_MINUS_Z: { int k = edgeId(cdir, type); for (uint i = 0; i < ic; ++i) { for (uint j = 0; j < jc; ++j) { (this->*copy_func)(v, arrayP, i, j, k, offset++); } } break; } default: MY_ASSERT(false); } } void Iterations::calculate(ConnectionDirection cdir) { switch (cdir) { case DIR_X: case DIR_MINUS_X: { uint i = sendEdgeId(cdir); for (uint j = 1; j < jc - 1; ++j) { for (uint k = 1; k < kc - 1; ++k) calculate(i, j, k); } break; } case DIR_Y: case DIR_MINUS_Y: { uint j = sendEdgeId(cdir); for (uint i = 1; i < ic - 1; ++i) { for (uint k = 1; k < kc - 1; ++k) calculate(i, j, k); } break; } case DIR_Z: case DIR_MINUS_Z: { uint k = sendEdgeId(cdir); for (uint i = 1; i < ic - 1; ++i) { for (uint j = 1; j < jc - 1; ++j) calculate(i, j, k); } break; } case DIR_Y_PERIOD_FIRST: { uint j = recvEdgeId(cdir); for (uint i = 1; i < ic - 1; ++i) { for (uint k = 1; k < kc - 1; ++k) calculate(i, j, k); } break; } case DIR_Y_PERIOD_LAST: // just copy break; default: MY_ASSERT(false); } } void Iterations::calculate_edge_values() { for (long i = 0; i < edgeIndeces.size(); ++i) { const Indice &ind = edgeIndeces[i]; calculate(ind.i, ind.j, ind.k); } } void Iterations::calculate(uint i, uint j, uint k) { long index = get_index(i, j, k); // array[index]++; // cnode.print(SSTR("calculate " << i << ',' << j << ',' << k)); // return; CHECK_INDEX(index, 0, array.size()); CHECK_INDEX(index, 0, array.size()); CHECK_INDEX(get_index(i-1,j,k), 0, array.size()); CHECK_INDEX(get_index(i+1,j,k), 0, array.size()); CHECK_INDEX(get_index(i,j-1,k), 0, array.size()); CHECK_INDEX(get_index(i,j+1,k), 0, array.size()); CHECK_INDEX(get_index(i,j,k-1), 0, array.size()); CHECK_INDEX(get_index(i,j,k+1), 0, array.size()); array[index] = 2 * arrayP[index] - arrayPP[index] + ht * ht * ( (arrayP[get_index(i-1,j,k)] - 2 * arrayP[index] + arrayP[get_index(i+1,j,k)]) / hx / hx + (arrayP[get_index(i,j-1,k)] - 2 * arrayP[index] + arrayP[get_index(i,j+1,k)]) / hy / hy + (arrayP[get_index(i,j,k-1)] - 2 * arrayP[index] + arrayP[get_index(i,j,k+1)]) / hz / hz ); } void Iterations::it_for_each(IndexesMFuncPtr func) { #ifdef WITH_OMP # pragma omp parallel for #endif for (int i = 0; i < ic; ++i) { for (int j = 0; j < jc; ++j) { for (int k = 0; k < kc; ++k) { (this->*func)(i, j, k); } } } } void Iterations::shift_arrays() { uint byteSize = bigsize * sizeof(real); // // array -> arrayP, arrayP -> arrayPP memcpy(arrayPP.data(), arrayP.data(), byteSize); memcpy(arrayP.data(), array.data(), byteSize); } void Iterations::prepareEdgeIndices() { std::vector<int> tmp; tmp.resize(ic * jc * kc); for (long i = 0; i < tmp.size(); ++i) tmp[i] = 0; for (uint i = 0; i < ic; ++i) { tmp[get_exact_index(i, 0, 0)] = 1; tmp[get_exact_index(i, 0, kc - 1)] = 1; tmp[get_exact_index(i, jc - 1, 0)] = 1; tmp[get_exact_index(i, jc - 1, kc - 1)] = 1; } for (uint j = 0; j < jc; ++j) { tmp[get_exact_index(0, j, 0)] = 1; tmp[get_exact_index(0, j, kc - 1)] = 1; tmp[get_exact_index(ic - 1, j, 0)] = 1; tmp[get_exact_index(ic - 1, j, kc - 1)] = 1; } for (uint k = 0; k < kc; ++k) { tmp[get_exact_index(0, 0, k)] = 1; tmp[get_exact_index(0, jc - 1, k)] = 1; tmp[get_exact_index(ic - 1, 0, k)] = 1; tmp[get_exact_index(ic - 1, jc - 1, k)] = 1; } for (uint i = 0; i < DIR_Y_PERIOD_FIRST; ++i) { ConnectionDirection cdir = static_cast<ConnectionDirection>(i); if (cnode.hasNeighbor(cdir)) continue; switch (cdir) { case DIR_X: for (uint j = 0; j < jc; ++j) { tmp[get_exact_index(ic - 1, j, 0)] = 0; tmp[get_exact_index(ic - 1, j, kc - 1)] = 0; } for (uint k = 0; k < kc; ++k) { tmp[get_exact_index(ic - 1, 0, k)] = 0; tmp[get_exact_index(ic - 1, jc - 1, k)] = 0; } break; case DIR_MINUS_X: for (uint j = 0; j < jc; ++j) { tmp[get_exact_index(0, j, 0)] = 0; tmp[get_exact_index(0, j, kc - 1)] = 0; } for (uint k = 0; k < kc; ++k) { tmp[get_exact_index(0, 0, k)] = 0; tmp[get_exact_index(0, jc - 1, k)] = 0; } break; case DIR_Y: if (cnode.hasNeighbor(DIR_Y_PERIOD_FIRST)) continue; for (uint i = 0; i < ic; ++i) { tmp[get_exact_index(i, jc - 1, 0)] = 0; tmp[get_exact_index(i, jc - 1, kc - 1)] = 0; } for (uint k = 0; k < kc; ++k) { tmp[get_exact_index(0, jc - 1, k)] = 0; tmp[get_exact_index(ic - 1, jc - 1, k)] = 0; } break; case DIR_MINUS_Y: for (uint i = 0; i < ic; ++i) { tmp[get_exact_index(i, 0, 0)] = 0; tmp[get_exact_index(i, 0, kc - 1)] = 0; } for (uint k = 0; k < kc; ++k) { tmp[get_exact_index(0, 0, k)] = 0; tmp[get_exact_index(ic - 1, 0, k)] = 0; } break; case DIR_Z: for (uint i = 0; i < ic; ++i) { tmp[get_exact_index(i, 0, kc - 1)] = 0; tmp[get_exact_index(i, jc - 1, kc - 1)] = 0; } for (uint j = 0; j < jc; ++j) { tmp[get_exact_index(0, j, kc - 1)] = 0; tmp[get_exact_index(ic - 1, j, kc - 1)] = 0; } break; case DIR_MINUS_Z: for (uint i = 0; i < ic; ++i) { tmp[get_exact_index(i, 0, 0)] = 0; tmp[get_exact_index(i, jc - 1, 0)] = 0; } for (uint j = 0; j < jc; ++j) { tmp[get_exact_index(0, j, 0)] = 0; tmp[get_exact_index(ic - 1, j, 0)] = 0; } break; default: MY_ASSERT(false); break; } } for (long i = 0; i < tmp.size(); ++i) { if (!tmp[i]) continue; long vz = i % kc; long vxy = i / kc; long vy = vxy % jc; long vx = vxy / jc; edgeIndeces.push_back(Indice(vx, vy, vz)); } } long Iterations::get_index(uint i, uint j, uint k) const { return (long(i + 1) * (jc + 2) + (j + 1)) * (kc + 2) + (k + 1); } long Iterations::get_exact_index(uint i, uint j, uint k) const { return (long(i)*jc + j) * kc + k; } void Iterations::set_0th(uint i, uint j, uint k) { long index = get_index(i, j, k); CHECK_INDEX(index, 0, arrayPP.size()); arrayPP[index] = phi(x(i), y(j), z(k)); } void Iterations::step0() { MY_ASSERT(next_step == 0); it_for_each(&Iterations::set_0th); memcpy(array.data(), arrayPP.data(), bigsize * sizeof(real)); next_step = 1; } void Iterations::set_1th(uint i, uint j, uint k) { long index = get_index(i, j, k); CHECK_INDEX(index, 0, arrayP.size()); arrayP[index] = arrayPP[index] + ht * ht / 2 * div_grad_phi(x(i), y(j), z(k)); } void Iterations::step1() { MY_ASSERT(next_step == 1); it_for_each(&Iterations::set_1th); next_step = 2; } int Iterations::edgeId(ConnectionDirection cdir, Iterations::MPI_OP op_type) { if (op_type == MPI_OP_RECV) return recvEdgeId(cdir); else return sendEdgeId(cdir); } int Iterations::sendEdgeId(ConnectionDirection cdir) const { switch (cdir) { case DIR_Y_PERIOD_FIRST: return jc - 1; case DIR_Y_PERIOD_LAST: return 1; case DIR_X: return ic - 1; case DIR_MINUS_X: return 0; case DIR_Y: return jc - 1; case DIR_MINUS_Y:return 0; case DIR_Z: return kc - 1; case DIR_MINUS_Z: return 0; default: MY_ASSERT(false); return 0; } } int Iterations::recvEdgeId(ConnectionDirection cdir) const { switch (cdir) { case DIR_Y_PERIOD_FIRST: return jc; case DIR_Y_PERIOD_LAST: return 0; case DIR_X: case DIR_Y: case DIR_Z: return sendEdgeId(cdir) + 1; case DIR_MINUS_X: case DIR_MINUS_Y: case DIR_MINUS_Z: return sendEdgeId(cdir) - 1; default: MY_ASSERT(false); return 0; } } int Iterations::sendrecvEdgeId(ConnectionDirection cdir) const { switch (cdir) { case DIR_X: return ic - 1; case DIR_MINUS_X: return 0; case DIR_Y: return jc - 1; case DIR_MINUS_Y:return 0; case DIR_Z: return kc - 1; case DIR_MINUS_Z: return 0; default: MY_ASSERT(false); return 0; } } void Iterations::printArrayDebug() { if (cnode.mpi.rank != cnode.mpi.procCount - 1) return; cnode.print(SSTR("STEP " << next_step)); for (uint i = ic - 4; i < ic; ++i) { for (uint j = jc - 4; j < jc; ++j) { for (uint k = kc - 4; k < kc; ++k) { cnode.print(SSTR('(' << i << ',' << j << ',' << k << ')' << ' ' << array[get_index(i,j,k)])); } } } }
true
fea94db31b2d6bd043f60611f16e9776945f3272
C++
asd-g11-2019/LAB4
/stack.h
UTF-8
647
3.03125
3
[]
no_license
#include <cstddef> // serve per il NULL #include <iostream> #include <stdexcept> #include "token.h" using namespace std; // Implementa STACK namespace stack{ struct stackCell { token token; stackCell* next; }; typedef stackCell* Stack; const token EMPTY_ELEM = { "", VUOTO }; const token ERROR = { "", ERRORE }; const Stack EMPTY_STACK = nullptr; bool isEmpty(const Stack&); void push(const token, Stack&); /* aggiunge elem in cima (operazione safe, si può sempre fare) */ token pop(Stack&); /* toglie dallo stack l'ultimo elemento e lo restituisce; se lo stack è vuoto viene sollevata un'eccezione) */ }
true
63789f82cee51377a4142282ffdab897713ae374
C++
CJRMoore/CS246A5
/basement.cc
UTF-8
1,344
2.71875
3
[]
no_license
#include "basement.h" #include "subscriptions.h" #include "buildingtypes.h" #include "info.h" #include "residence.h" #include "builder.h" #include <memory> using namespace std; #include <iostream> Basement::Basement(shared_ptr<AbstractAddress> aa) : Residence(aa) { shared_ptr<Basement> tmp{this}; aa->attach(tmp); } Info Basement::getInfo() const { Info info{BuildingType::Address, owner, index, triggeredResource}; return info; } void Basement::notify(Subject &whoNotified){ Info info = whoNotified.getInfo(); if (info.buildingType==BuildingType::Path) { notifyObservers(SubscriptionType::Path); } else if (info.buildingType==BuildingType::Tile){ triggeredResource = whoNotified.getInfo().resource; notifyObservers(SubscriptionType::Address); notifyObservers(SubscriptionType::Tile); } } vector<int> Basement::upgradeRequirements(Builder &b){ vector<int> theRequirements(5,0); if (owner!=b.getColour()) { cout << "Address " << getIndex() << " already owned." << endl; return theRequirements; } theRequirements[2] = 2; // 2 glass theRequirements[3] = 3; // 3 heat if (theRequirements.size()>0) {//attach(make_shared<Builder>(b)); shared_ptr<Builder> pb{&b}; attach(pb); } return theRequirements; }
true
ae28694e02b31f4d5ecad23da6ab39492dd75bb3
C++
hustaoyang/algorithm
/greedy_algorithm/longest_palin_substr.cpp
UTF-8
796
3.265625
3
[]
no_license
#include<iostream> #include<string> #include<algorithm> using namespace std; class Solution { public: string longestPalindrome(string s) { size_t len = s.size(); string result; int max_len = 0; int max_left = 0 , max_right = 0; for(int i = 0; i < len; i++) { int left = i -1; int right = i + 1; int max = 1; while(left >= 0 && right < len && s[left] == s[right]) { max += 2; --left; ++right; } if(max > max_len) { max_len = max; max_left = left - 1; max_right = right - 1; } } for(int i = max_left; i <= max_right; i++) result.insert(result.end(), s[i]); return result; } }; int main() { Solution S; string s("7892kdedk2"); cout<<S.longestPalindrome(s)<<endl; return 0; }
true
42c6fc52ac2f71543e8185a2b4eac4d337d3d6e9
C++
shakhub/Interview
/Interview/sorting.cpp
UTF-8
4,012
3.25
3
[]
no_license
#include<iostream> #include<time.h> #include"sorting.hpp" #define __SORT #define SIZE 40000 template <class T> inline void swapSort(T *a,T *b) { /* *a = *a ^ *b; *b = *a ^ *b; *a = *a ^ *b; */ T temp; temp = *a; *a = *b; *b = temp; } template <class T> T binarySearch(T *a,const int size, const T data) { /* The input array must be sorted O(log n) */ int l = 0,r = size-1; while(l<=r) { int mid = l+((r - l)>>1); if ( a[mid] == data ) return mid+1; if ( data < a[mid]) r = mid - 1; else l = mid + 1; } return -1; // if data not found } template <class T> T search(T *a, const int size, const T data) { //O(n) int i=0; for(i=0;i<size;i++) { if(a[i] == data) return i+1; } return -1; } template <class T> void selectionSort(T *a, const int size) { //O(n*n) int min_loc = 0; while(min_loc < size) { int i = min_loc+1; while(i<size) { if(a[i] < a[min_loc]) { swapSort ( &a[i],&a[min_loc]); } i++; } min_loc++; } } template <class T> void bubbleSort(T *a, const int size) { /* Modified bubble sort : If the array is already sorted then Time Complexity is O(n) O(n^2) */ int swapCount = 1; while(swapCount) { int i = 0; swapCount = 0; while (i<(size-1)) { if(a[i]>a[i+1]) { swapSort(&a[i],&a[i+1]); swapCount++; } i++; } } } template <class T> void insertionSort(T *a, const int size) { //O(n*n) int i=1; while(i<size) { int key = i; while(key) { if(a[key]<a[key-1]){ swapSort(&a[key],&a[key-1]); key--; } else { key = 0; break; } } i++; } } template <class T> void merge(T *a, int left,const int mid,const int right) { int i=0,j=0,k=0; const int leftSize = mid-left+1; const int rightSize = right - mid; T *leftArray; T *rightArray; leftArray = new T[leftSize]; rightArray = new T[rightSize]; //copy data to the temp arrays for(int i=0;i<leftSize;i++) leftArray[i] = a[left+i]; for(int i=0;i<rightSize;i++) rightArray[i] = a[mid+1+i]; i=0; j=0; k=left; while(i<leftSize && j<rightSize) { if(leftArray[i] <=rightArray[j]) { a[k] = leftArray[i]; i++; } else { a[k] = rightArray[j]; j++; } k++; } //Copy the remaining elements of the left array while(i<leftSize) { a[k] = leftArray[i]; i++; k++; } //Copy the remaining elements of the right array while(j<rightSize) { a[k] = rightArray[j]; j++; k++; } delete[] leftArray; delete[] rightArray; } template <class T> void mergeSort(T *a,int left, int right) { //O(nlog n) int mid = left+((right-left)>>1);//same as (left+right)>>1 , but avoids overflow for large left values if(left<right) { mergeSort(a,left,mid); mergeSort(a,mid+1,right); merge(a,left,mid,right); } } template <class T> void printArray(T *a,const int size) { int i=0; std::cout<<std::endl; for(i=0;i<size;i++) std::cout<<a[i]<<" "; std::cout<<std::endl; std::cout<<std::endl; } void runSorting() { long a[SIZE] = {0},b[SIZE]={0},c[SIZE]={0}; clock_t startSort; int i = 0; for(i=SIZE-1;i--;) a[i] = rand()&16383; memcpy(b,a,SIZE*sizeof(int)); memcpy(c,a,SIZE*sizeof(int)); startSort = clock(); selectionSort(a,SIZE); printf("Time for selection sort : %3.4fs\n",(double)(clock()-startSort)/CLOCKS_PER_SEC); startSort = clock(); bubbleSort(b,SIZE); printf("Time for bubble sort : %3.4fs\n",(double)(clock()-startSort)/CLOCKS_PER_SEC); startSort = clock(); mergeSort(c,0,SIZE-1); printf("Time for merge sort : %3.4fs\n",(double)(clock()-startSort)/CLOCKS_PER_SEC); /* while(1) { int data; std::cout<<"Enter Item to Search: "; std::cin>>data; clock_t start = clock(); std::cout<<"Location : "<<binarySearch(a,SIZE,data)<<std::endl; printf("Time BS: %.8fs\n",(double)(clock()-start)/CLOCKS_PER_SEC); start = clock(); std::cout<<"Location : "<<search(a,SIZE,data)<<std::endl; printf("Time S: %.8fs\n",(double)(clock()-start)/CLOCKS_PER_SEC); } */ }
true
03d9ea8450fc6a1534b197665f2e104d82306d4e
C++
miuhui/LeetCode
/easy/344.cpp
UTF-8
571
3.28125
3
[]
no_license
// leetcode.cpp : Defines the entry point for the console application. // #include <vector> #include <iostream> #include <string> using namespace std; class Solution { public: static string reverseString(string s) { int len = s.length(); if (len <= 1) { return s; } auto swapCount = len / 2; auto front = 0; auto tail = len - 1; while (swapCount--) { auto temp = s[front]; s[front] = s[tail]; s[tail] = temp; front++; tail--; } return s; } }; int main() { Solution s; cout << s.reverseString(""); getchar(); return 0; }
true
569a20fbb2220763f84538554934443e05c3fd35
C++
alexshen/raytracinginoneweekend
/dielectric.h
UTF-8
358
2.546875
3
[]
no_license
#ifndef DIELECTRIC_H #define DIELECTRIC_H #include "material.h" class dielectric : public material { public: dielectric(float index = 1.0f) : index(index) {} bool scatter(const ray3& r_in, const hit_record& rec, vec3& attenuation, ray3& scattered) const override; float index; }; #endif /* ifndef DIELECTRIC_H */
true
5fdb14fd747c2d80cc0f47829db1c9ee106bd6fe
C++
nachogoro/simple-chess-games
/src/details/moves/RookMove.cpp
UTF-8
1,428
2.796875
3
[ "MIT" ]
permissive
#include "RookMove.h" #include <details/BoardAnalyzer.h> using namespace simplechess; using namespace simplechess::details; std::set<PieceMove> simplechess::details::rookMovesUnfiltered( const Board& board, const Color color, const Square& square) { const Piece rook = {PieceType::Rook, color}; std::set<Square> possibleSquares; { const std::set<Square> horizontalKingSide = BoardAnalyzer::reachableSquaresInDirection( board, square, color, 0, 1); possibleSquares.insert( horizontalKingSide.begin(), horizontalKingSide.end()); } { const std::set<Square> horizontalQueenSide = BoardAnalyzer::reachableSquaresInDirection( board, square, color, 0, -1); possibleSquares.insert( horizontalQueenSide.begin(), horizontalQueenSide.end()); } { const std::set<Square> verticalTowardsBlack = BoardAnalyzer::reachableSquaresInDirection( board, square, color, 1, 0); possibleSquares.insert( verticalTowardsBlack.begin(), verticalTowardsBlack.end()); } { const std::set<Square> verticalTowardsWhite = BoardAnalyzer::reachableSquaresInDirection( board, square, color, -1, 0); possibleSquares.insert( verticalTowardsWhite.begin(), verticalTowardsWhite.end()); } std::set<PieceMove> result; for (const Square& dst : possibleSquares) { result.insert(PieceMove::regularMove( rook, square, dst)); } return result; }
true
244a9ed898f144d748d8edbd1760197982f82e44
C++
MisakaGeek/c-cpp-projects
/数据结构/冒泡排序/main.cpp
GB18030
787
3.25
3
[ "Apache-2.0" ]
permissive
#include <iostream> using namespace std; int main() { int *R, n; cout << "Ԫظ:"; cin >> n; R = new int[n]; for(int i = 0; i < n; i++) cin >> R[i]; int Bound=n-1;//޶ȼѭ while(Bound!=0) { int t=0;//t¼ÿѭĽλ,˺ֻҪСtIJ򼴿,t=0ʾ޽ for(int i=0;i<Bound;i++) { if(R[i]>R[i+1]) { int temp=R[i+1]; R[i+1]=R[i]; R[i]=temp; t=i; } } Bound=t; } for(int i=0;i<n;i++) cout<<R[i]<<" "; delete[] R; return 0; }
true
7b60385c002a1903fadcd581d795561cb2765ad1
C++
goncasmage1/OpenGL
/CGJProject/CGJProject/src/PPFilterMesh.cpp
UTF-8
1,518
2.78125
3
[ "MIT" ]
permissive
#include "PPFilterMesh.h" PPFilterMesh::PPFilterMesh(GLuint v_coord_id) : v_coord(v_coord_id) { } void PPFilterMesh::CreateBufferObjects() { GLfloat fbo_vertices[] = { -1, -1, 1, -1, -1, 1, 1, 1, }; glGenVertexArrays(1, &VAO); glBindVertexArray(VAO); { glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); { glBufferData(GL_ARRAY_BUFFER, sizeof(fbo_vertices) * 8, fbo_vertices, GL_STATIC_DRAW); glEnableVertexAttribArray(v_coord); glVertexAttribPointer( v_coord, // attribute 2, // number of elements per vertex, here (x,y) GL_FLOAT, // the type of each element GL_FALSE, // take our values as-is 0, // no extra data between each position 0 ); } } glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } void PPFilterMesh::DestroyBufferObjects() { glDisableVertexAttribArray(v_coord); glDeleteVertexArrays(1, &VAO); glBindVertexArray(0); } void PPFilterMesh::Draw() { //glEnableVertexAttribArray(v_coord); glBindVertexArray(VAO); //glVertexAttribPointer( // v_coord, // attribute // 2, // number of elements per vertex, here (x,y) // GL_FLOAT, // the type of each element // GL_FALSE, // take our values as-is // 0, // no extra data between each position // 0 // offset of first element //); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); //glDisableVertexAttribArray(v_coord); glBindVertexArray(0); }
true
ffdd3fe6d1f653a2a4af5fb369aef21b725bddca
C++
ZhuYuJin/ros_code
/src/car_move/RobotBasicController.h
UTF-8
2,138
3.109375
3
[]
no_license
#include <stdio.h> #include <wiringPi.h> #include <softPwm.h> #define uchar unsigned char #define HIGH 1 #define LOW 0 #define LEFT_IN_PIN 7 #define LEFT_OUT_PIN 0 #define RIGHT_IN_PIN 2 #define RIGHT_OUT_PIN 3 #define LEFT_EN_PWM 1 #define RIGHT_EN_PWM 4 using namespace std; class RaspiRobot { private: static RaspiRobot *instance; int direction; RaspiRobot(); void setMotors(uchar leftIn, uchar leftOut, uchar rightIn, uchar rightOut, uchar leftEn, uchar rightEn); public: static bool init(); static RaspiRobot *getInstance(); void stop(); void forwardBySpeed(int speed); void forwardByTimeAndSpeed(float sec, int speed); void reverseBySpeed(int speed); void reverseByTimeAndSpeed(float sec, int speed); }; RaspiRobot *RaspiRobot::getInstance() { if(instance==NULL) instance=new RaspiRobot(); return instance; } RaspiRobot::RaspiRobot() { } RaspiRobot *RaspiRobot::instance=NULL; bool RaspiRobot::init() { if(wiringPiSetup() < 0){ printf("setup wiringPi failed !"); return false; } pinMode(LEFT_IN_PIN, OUTPUT); pinMode(LEFT_OUT_PIN, OUTPUT); pinMode(RIGHT_IN_PIN, OUTPUT); pinMode(RIGHT_OUT_PIN, OUTPUT); softPwmCreate(LEFT_EN_PWM, 0, 255); softPwmCreate(RIGHT_EN_PWM, 0, 255); return true; } void RaspiRobot::setMotors(uchar leftIn, uchar leftOut, uchar rightIn, uchar rightOut, uchar leftEn, uchar rightEn) { digitalWrite(LEFT_IN_PIN, leftIn); digitalWrite(LEFT_OUT_PIN, leftOut); digitalWrite(RIGHT_IN_PIN, rightIn); digitalWrite(RIGHT_OUT_PIN, rightOut); softPwmWrite(LEFT_EN_PWM, leftEn); softPwmWrite(RIGHT_EN_PWM, rightEn); } void RaspiRobot::stop() { setMotors(0,0,0,0,0,0); } void RaspiRobot::forwardBySpeed(int speed) { setMotors(1,0,1,0,speed,speed); } void RaspiRobot::forwardByTimeAndSpeed(float sec, int speed = 100) { setMotors(1,0,1,0,speed,speed); if(sec>0) { delay((int)(sec*1000)); stop(); } } void RaspiRobot::reverseBySpeed(int speed) { setMotors(0,1,0,1,speed,speed); } void RaspiRobot::reverseByTimeAndSpeed(float sec, int speed = 100) { setMotors(0,1,0,1,speed,speed); if(sec>0) { delay((int)(sec*1000)); stop(); } }
true
af918f07bbaf0cc0618c680c31fb8ed82a038af0
C++
zmillard/385-Algorithms
/PrimesSieve/sieve.cpp
UTF-8
4,171
3.375
3
[]
no_license
/* * sieve.cpp * * Created on: May 23, 2016 * Author: O236 */ /******************************************************************************* * Name : sieve.cpp * Author : Zoe Millard * Date : 5/25/16 * Description : Sieve of Eratosthenes * Pledge : "I pledge my honor that I have abided by the Stevens Honor System" -ZM ******************************************************************************/ #include <cmath> #include <iomanip> #include <iostream> #include <sstream> #include <math.h> using namespace std; class PrimesSieve { public: PrimesSieve(int limit) : is_prime_(new bool[limit + 1]), limit_(limit){ sieve(); } ~PrimesSieve() { delete [] is_prime_; } inline int num_primes() const { return count_num_primes(); } void display_primes() const { // TODO: write code to display the primes in the format specified in the // requirements document. int max_prime_width = num_digits(max_prime_); //given formula for columns length int primes_per_row = 80 / (max_prime_width + 1); int line_count = 0; //counts lines to catch a spacing error for(int i = 0; i <= limit_; i++){ if(is_prime_[i]){ if(line_count % primes_per_row > 0 || num_digits(limit_) <= 2){ //spacing for items with 1-2 digits as max if(i != 2 && num_digits(limit_) <= 2){ cout << " "; }else if(num_digits(limit_) > 2){ //calculates spacing of digits to keep table for(int j=0; num_digits(limit_)-num_digits(i) >= j; j++){ cout << " "; } } } if(line_count % primes_per_row == 0 && num_digits(limit_) > 2){ //moves to new line if needed based on given formula if (line_count > 0){ cout<<endl; } for(int j=0; num_digits(limit_)-num_digits(i) > j; j++){ //spacing for new line elements cout << " "; } } line_count++; cout << i; } } } private: bool * const is_prime_; const int limit_; int prime_count; int num_primes_, max_prime_; int count_num_primes() const { // TODO: write code to count the number of primes found int x = 0; for(int i = 0; i <= limit_; i++){ //counts true values. I did it this way to combat an error I found if(is_prime_[i]){ x++; } } return x; } int num_digits(int num) const { // TODO: write code to determine how many digits are in an integer // Hint: No strings are needed. Keep dividing by 10. int count = 0; for(int i = num; i >= 1; ){ //calculates the number of places in a number i/=10; count++; } return count; } void sieve() { // TODO: write sieve algorithm max_prime_ = limit_; //given sieve algorithm prime_count = 0; int n = limit_; for(int k = 2; k <= n; k++){ is_prime_[k] = true; } for(int i = 2; i < sqrt(n); i++){ if (is_prime_[i] == true){ for(int j = pow(i, 2); j <= n; j+=i){ is_prime_[j] = false; } } } } }; int main(void) { cout << "**************************** " << "Sieve of Eratosthenes" << " ****************************" << endl; cout << "Search for primes up to: "; string limit_str; cin >> limit_str; int limit; // Use stringstream for conversion. Don't forget to #include <sstream> istringstream iss(limit_str); // Check for error. if ( !(iss >> limit) ) { cerr << "Error: Input is not an integer." << endl; return 1; } if (limit < 2) { cerr << "Error: Input must be an integer >= 2." << endl; return 1; } cout << "" << endl; PrimesSieve prime (limit); cout << "Number of primes found: " << prime.num_primes() << endl; cout << "Primes up to " << limit << ":" << endl; prime.display_primes(); // TODO: write code that uses your class to produce the desired output. return 0; }
true
20ecc17e62b9d656362e75e53bb08ae724a0d6c6
C++
zzz0906/LeetCode
/Scripts/9.cpp
UTF-8
486
2.84375
3
[ "MIT" ]
permissive
#include<bits/stdc++.h> using namespace std; int answer[10000]; class Solution { public: static bool isPalindrome(int x) { if (x<0) return false; memset(answer,0,sizeof(answer)); int mid = x; int w = 0; int remainder; while (mid != 0){ remainder = mid % 10; mid = mid / 10; answer[w++] = remainder; } for (int i = 0;i<w/2;i++) if (answer[i] != answer[w-1-i]) return false; return true; } };
true
fa964746a153097b246dc7e8a85f329a6f05df5e
C++
renair/BankServer
/Protocol/Packets/UserLogoutPacket.cpp
UTF-8
1,378
2.515625
3
[]
no_license
#include "UserLogoutPacket.h" #include "ErrorPacket.h" #include "SuccessPacket.h" #include "DataBase/Access/session_table.h" #include <iostream> using namespace std; UserLogoutPacket::UserLogoutPacket(quint64 token, quint32 machineId): _token(token), _machineId(machineId) {} UserLogoutPacket::~UserLogoutPacket() {} char UserLogoutPacket::specificGetID() const { return 6; } PacketHolder UserLogoutPacket::specificClone() const { return PacketHolder(new UserLogoutPacket(*this)); } QByteArray UserLogoutPacket::specificDump() const { QByteArray res; res.append((char*)&_token, sizeof(_token)); res.append((char*)&_machineId, sizeof(_machineId)); return res; } void UserLogoutPacket::specificLoad(QBuffer& buff) { buff.read((char*)&_token, sizeof(_token)); buff.read((char*)&_machineId, sizeof(_machineId)); } PacketHolder UserLogoutPacket::specificHandle() const { cout<< "logout" <<endl; SessionTable sessionTable; Session session = sessionTable.getBySignature(token()); if(session.atmId()!=machineId()) { return PacketHolder(new ErrorPacket("Unexpected error in relation to session ID and machine ID.")); } quint64 time = QDateTime::currentDateTime().toTime_t(); session.renewValidTime(time); sessionTable.update(session); return PacketHolder(new SuccessPacket("Loged out.")); }
true
e3575884f64cfa5a42792bf7a95d1c8cfd4763fc
C++
hjain5164/Competitive-Programming-Concepts-and-Algorithms
/String Matching Algorithms/KMP String Matching Algorithm.cpp
UTF-8
841
3.078125
3
[]
no_license
#include <iostream> #define MAX_N 100005 int reset[MAX_N]; using namespace std; void KMPpreprocess(string pat) { int i = 0, j = -1; reset[0] = -1; while (i < pat.size()) { //Check for resetting while (j >= 0 && pat[i] != pat[j]) j = reset[j]; i++; j++; reset[i] = j; } } void KMPsearch(string str, string pat) { KMPpreprocess(pat); int i = 0, j = 0; while (i < str.size()) { while (j >= 0 && str[i] != pat[j]) j = reset[j]; i++; j++; if (j == pat.size()) { cout << "Found at " << (i - j) << endl; j = reset[j]; } } } int main() { for (int i = 0; i < MAX_N; i++) reset[i] = -1; string str, pat; cin >> str >> pat; KMPsearch(str, pat); }
true
777e5ee7318c15fb3ab13b2dc82a04bd387943d0
C++
HanmingZhang/ray-tracer
/basecode/src/scene/geometry/square.cpp
UTF-8
3,906
2.671875
3
[]
no_license
#include <scene/geometry/square.h> Intersection SquarePlane::GetIntersection(Ray r) { //TODO //Transform Ray to objecet space glm::mat4 inverse_modelMatrix = this->transform.invT(); Ray objSpace_Ray = r.GetTransformedCopy(inverse_modelMatrix); glm::vec3 origin = objSpace_Ray.origin; glm::vec3 direction = objSpace_Ray.direction; glm::vec3 planeNormal = glm::vec3(0.0f, 0.0f, 1.0f); float t = glm::dot(planeNormal, -origin) / glm::dot(planeNormal, direction); //First we check whether is intersection on plane if(t < 0.0f){ return Intersection(); } else{ glm::vec3 pointOnPlane = origin + t * direction; Intersection result; //Then we check whether this point is within the suqare if((pointOnPlane.x < 0.5f && pointOnPlane.x > -0.5f) && (pointOnPlane.y < 0.5f && pointOnPlane.y > -0.5f)) { result.t = t; result.object_hit = this; result.point = glm::vec3(this->transform.T() * glm::vec4(pointOnPlane, 1.0f)); result.normal = glm::vec3(this->transform.invTransT() * glm::vec4(planeNormal, 0.0f)); } //---------------------------------------------- //-------------- normal map -------------------- //---------------------------------------------- QImage* image = material->normal_map; if(image != nullptr){ glm::vec2 uv_coord = GetUVCoordinates(result.point); int X = glm::min(image->width() * uv_coord.x, image->width() - 1.0f); int Y = glm::min(image->height() * (1.0f - uv_coord.y), image->height() - 1.0f); QColor normal_from_texture = image->pixel(X, Y); glm::vec3 temp = glm::vec3((2.0 / 255.0) * normal_from_texture.red() - 1.0, (2.0 / 255.0) * normal_from_texture.green() - 1.0, (2.0 / 255.0) * normal_from_texture.blue() - 1.0); //glm::mat3 m = GetNormalMatrix(pointOnCube); glm::vec3 result_normal = temp; result_normal = glm::normalize(result_normal); result.normal = result_normal; } //---------------------------------------------- return result; } } void SquarePlane::create() { GLuint cub_idx[6]; glm::vec3 cub_vert_pos[4]; glm::vec3 cub_vert_nor[4]; glm::vec3 cub_vert_col[4]; cub_vert_pos[0] = glm::vec3(-0.5f, 0.5f, 0); cub_vert_nor[0] = glm::vec3(0, 0, 1); cub_vert_col[0] = material->base_color; cub_vert_pos[1] = glm::vec3(-0.5f, -0.5f, 0); cub_vert_nor[1] = glm::vec3(0, 0, 1); cub_vert_col[1] = material->base_color; cub_vert_pos[2] = glm::vec3(0.5f, -0.5f, 0); cub_vert_nor[2] = glm::vec3(0, 0, 1); cub_vert_col[2] = material->base_color; cub_vert_pos[3] = glm::vec3(0.5f, 0.5f, 0); cub_vert_nor[3] = glm::vec3(0, 0, 1); cub_vert_col[3] = material->base_color; cub_idx[0] = 0; cub_idx[1] = 1; cub_idx[2] = 2; cub_idx[3] = 0; cub_idx[4] = 2; cub_idx[5] = 3; count = 6; bufIdx.create(); bufIdx.bind(); bufIdx.setUsagePattern(QOpenGLBuffer::StaticDraw); bufIdx.allocate(cub_idx, 6 * sizeof(GLuint)); bufPos.create(); bufPos.bind(); bufPos.setUsagePattern(QOpenGLBuffer::StaticDraw); bufPos.allocate(cub_vert_pos, 4 * sizeof(glm::vec3)); bufNor.create(); bufNor.bind(); bufNor.setUsagePattern(QOpenGLBuffer::StaticDraw); bufNor.allocate(cub_vert_nor, 4 * sizeof(glm::vec3)); bufCol.create(); bufCol.bind(); bufCol.setUsagePattern(QOpenGLBuffer::StaticDraw); bufCol.allocate(cub_vert_col, 4 * sizeof(glm::vec3)); } glm::vec2 SquarePlane::GetUVCoordinates(const glm::vec3 &point){ glm::vec3 localPosition = glm::vec3(transform.invT() * glm::vec4(point, 1.0f)); return(glm::vec2(localPosition.x + 0.5, 0.5 - localPosition.y)); }
true
180ca1aa5a7f93875890aec2f38ccafd0d09831d
C++
CsacsoBacsi/VS2019
/Tutorial/Console/Btree/Btree.cpp
UTF-8
5,656
3.40625
3
[]
no_license
// Btree.cpp : Defines the entry point for the console application. // #include <iostream> //#include <iomanip> #define MAX_ELEMS 10 using std::cout; using std::cin; using std::endl; struct bst // Each node's structure. { int key ; // Key value from the table. Serves a base for sorting int rownum ; // Pointer to the row number holding this key int lindex ; // Pointer to a node with a key value that is less than this node's key value int rindex ; // Pointer to a node with a key value that is greater than this node's key value } ; struct dbtable // Simulate a database table with two columns: key + attribute { int UID ; // A unique identifier char Name [50] ; // Arbitrary name } ; int treeIndex ; int steps = 0 ; // Counts the number of recursive steps to locate a given key and return the row number void Insert (struct bst *, int, dbtable) ; void MakeNode (struct bst *, dbtable) ; void Intrav (struct bst *, int) ; void Pretrav (struct bst *, int) ; int FindRow (struct bst * tree, int index, int uid) ; int BinSearch (struct bst * tree, int index, int uid) ; int main () { struct bst tree [MAX_ELEMS] ; // The Binary tree struct dbtable mytbl [MAX_ELEMS] = {{50, "First" }, // Table with 10 rows {10, "Second" }, {60, "Third" }, {25, "Fourth" }, {30, "Fifth" }, {92, "Sixth" }, {15, "Seventh"}, {67, "Eighth" }, {100, "Ninth" }, {5, "Tenth" }} ; memset (tree, 0, sizeof (tree)) ; // Set all values to zero for (treeIndex = 0 ; treeIndex < MAX_ELEMS ; treeIndex ++) // For each table row { if (treeIndex == 0) MakeNode (&tree [treeIndex], mytbl [treeIndex]) ; // Create the first node else Insert (tree, treeIndex, mytbl [treeIndex]) ; // Add the subsequent nodes and link them up too to each other } int rownum = FindRow (tree, 0, 67) ; // Full traverse from left to right cout << "Steps taken: " << steps << endl ; steps = 0 ; rownum = BinSearch (tree, 0, 67) ; // Traverse in order cout << "Steps taken: " << steps << endl ; // Intrav (tree, 0) ; // Pretrav (tree,0) ; return 0 ; } void Insert (struct bst * tree, int treeIndex, dbtable mytbl) { int baseIndex = 0 ; while (baseIndex <= treeIndex) // Check every existing node where to link the new node { if (mytbl.UID <= tree[baseIndex].key) // Inserted key is less than this node's key value { if (tree[baseIndex].lindex == -1) // If leaf node, then make it a parent node { tree[baseIndex].lindex = treeIndex ; // Create the link to the left MakeNode (&tree[treeIndex], mytbl) ; // Init new node return ; } else { baseIndex = tree[baseIndex].lindex ; // Take the next node to the left continue ; } } else // data is > tree[baseIndex].data { if (tree[baseIndex].rindex == -1) { tree[baseIndex].rindex = treeIndex ; // Create the link to the right MakeNode (&tree[treeIndex], mytbl) ; // Init new node return ; } else { baseIndex = tree[baseIndex].rindex ; // Take the next node to the right continue ; } } } } void MakeNode (struct bst * tree, dbtable mytbl) { tree->key = mytbl.UID ; tree->rownum = treeIndex + 1 ; // Store the row number of the row in the table tree->lindex = tree->rindex = -1 ; // New node, not linked to any other node just yet } void Intrav (struct bst * tree, int index) { if (tree[index].lindex != -1) Intrav (tree, tree[index].lindex) ; cout << "DataIn =" << tree[index].key <<endl ; if (tree[index].rindex != -1) Intrav (tree, tree[index].rindex) ; } void Pretrav (struct bst * tree, int index) { cout << "DataPre =" << tree[index].key << endl ; if (tree[index].lindex != -1) Pretrav (tree, tree[index].lindex) ; if (tree[index].rindex != -1) Pretrav (tree, tree[index].rindex) ; } int FindRow (struct bst * tree, int index, int uid) // Traverse from left to right and stop when found { static bool found = false ; static int rn = -1 ; // Returns -1 if not found steps ++ ; // Count the number of recursive calls if (tree[index].key == uid) { // If the searched value is found rn = tree[index].rownum ; // Get the row number found = true ; // Set the found flag return rn ; } if (tree[index].lindex != -1) // Go left if possible FindRow (tree, tree[index].lindex, uid) ; if (found) return rn ; if (tree[index].rindex != -1) // Go right if possible FindRow (tree, tree[index].rindex, uid) ; if (found) return rn ; return rn ; } int BinSearch (struct bst * tree, int index, int uid) // Traverse based on comparison result { static bool found = false ; static int rn = -1 ; // Returns -1 if not found steps ++ ; // Count the number of recursive calls if (tree[index].key == uid) { // If the searched value is found rn = tree[index].rownum ; // Get the row number found = true ; // Set the found flag return rn ; } if (tree[index].key > uid && tree[index].lindex != -1) // Go left if possible and if the searched value is less than this node's value BinSearch (tree, tree[index].lindex, uid) ; if (found) return rn ; if (tree[index].key < uid && tree[index].rindex != -1) // Go right if possible and if the searched value is greater than this node's value BinSearch (tree, tree[index].rindex, uid) ; if (found) return rn ; return rn ; }
true
da63cbbf7102e861a6ea2744ae1b1df931790ff9
C++
avcopan/cpppractice
/accelerated_cpp/08algorithms/03rbegin.cpp
UTF-8
922
3.71875
4
[]
no_license
#include <string> #include <algorithm> #include <iostream> bool is_palindrome(const std::string& s) { return std::equal(s.begin(), s.end(), s.rbegin()); } int main() { std::cout << "Is it a palindrome?" << std::endl; std::string s1("madam"); std::string s2("rotor"); std::string s3("bilbo"); std::string s4("bobbo"); std::cout << s1 << ": " << (is_palindrome(s1) ? "yes" : "no") << std::endl; std::cout << s2 << ": " << (is_palindrome(s2) ? "yes" : "no") << std::endl; std::cout << s3 << ": " << (is_palindrome(s3) ? "yes" : "no") << std::endl; std::cout << s4 << ": " << (is_palindrome(s4) ? "yes" : "no") << std::endl; std::string s = "The quick brown fox jumps over the lazy dog"; for(std::string::reverse_iterator it = s.rbegin(); it != s.rend(); ++it) std::cout << *it; std::cout << std::endl; std::copy(s.rbegin(), s.rend(), std::back_inserter(s)); std::cout << s << std::endl; }
true
1c110368a6d5e5ceb00fcdb4a5d94dbf5b5c9cd9
C++
Himanshu-Negi8/Data-Structure-and-Algorithms
/Leetcode/Array/cords.cpp
UTF-8
701
3.109375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; bool isReachable(int x, int y,long long dy, long long dx) { if (x > dx || y > dy) return false; if (x == dx && y == dy) return true; return (isReachable(x + y, y, dy, dx) || isReachable(x, y + x, dy, dx)); } string solve(long long y, long long x){ if(isReachable(1,1,y,x)){ return "Yes"; }else{ return "No"; } } int main() { int t; cin>>t; while(t){ int x =1,y=1; int dest_x,dest_y; cin>>dest_x>>dest_y; if (isReachable(x, y, dest_x, dest_y)) cout << "Yes\n"; else cout << "No\n"; t--; } return 0; }
true
b1211c7223705f3b6367eca584ca421602ee3f3e
C++
DjPasco/Mag
/Detours/XFileMonitor/XFileMonitor.Hook/XFileMonitor.Hook.cpp
UTF-8
11,780
2.5625
3
[]
no_license
#include "stdafx.h" #include "XFileMonitor.Hook.h" #include "..\detours\detours.h" // Detours header #include <map> // std::map #include <atlstr.h> // for CString using namespace std; // Just a way for us to track what the client did, eg open/close/write to a file enum FileAction { File_Unknown = 0, File_CreateAlways, File_CreateNew, File_OpenAlways, File_OpenExisting, File_TruncateExisting, File_Write, File_Read, File_Close }; // Just a way for us to track which API was called.. enum Win32API { API_CreateFile = 1, API_WriteFile, API_ReadFile, API_CloseHandle }; // This is the structure we'll send over to the GUI via WM_COPYDATA struct FILECONTEXT { HANDLE File; __int32 OriginalAPI; }; map<HANDLE, CString> g_openFiles; CRITICAL_SECTION g_CritSec; // Guards access to the collection (thread synch) HINSTANCE g_hInstance = NULL; // This instance // Function pointer to the original (undetoured) WriteFile API. HANDLE (WINAPI * Real_CreateFile) (LPCWSTR lpFileName,DWORD dwDesiredAcces, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes,DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes,HANDLE hTemplateFile) = CreateFileW; // Function pointer to the original (undetoured) WriteFile API. BOOL (WINAPI * Real_WriteFile) (HANDLE hFile,LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite, LPDWORD lpNumberOfBytesWritten,LPOVERLAPPED lpOverlapped) = WriteFile; // Function pointer to the original (undetoured) ReadFile API. BOOL (WINAPI *Real_ReadFile) (HANDLE hFile,LPVOID lpBuffer,DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead,LPOVERLAPPED lpOverlapped) = ReadFile; // Function pointer to the original (undetoured) CloseHandle API. BOOL (WINAPI * Real_CloseHandle)(HANDLE hObject) = CloseHandle; // Transfer some textual data over to the GUI void Transmit(FileAction action, Win32API sourceAPI, HANDLE hFile, LPCWSTR text) { HWND hWnd = ::FindWindow(NULL, L"Coding the Wheel - XFileMonitor v1.0"); if (!hWnd) return; COPYDATASTRUCT cds; ::ZeroMemory(&cds, sizeof(COPYDATASTRUCT)); cds.dwData = action; cds.cbData = sizeof(FILECONTEXT) + ((wcslen(text)+1) * 2); // Allocate the outgoing array LPBYTE pOutData = new BYTE[cds.cbData]; // Place a HANDLEANDTEXT structure at the front of the array FILECONTEXT ht; ht.File = hFile; ht.OriginalAPI = sourceAPI; memcpy(pOutData, &ht, sizeof(FILECONTEXT)); // Place the text immediately following the structure wcscpy((LPWSTR)(pOutData + sizeof(FILECONTEXT)), text); // Send it off cds.lpData = pOutData; ::SendMessage(hWnd, WM_COPYDATA, (WPARAM)::GetDesktopWindow(), (LPARAM)&cds); delete [] pOutData; } // Check the first N bytes of data to see if they fall within printable ranges // for Unicode character data. Quick and dirty and needs work. bool IsUnicodeText(LPCWSTR buffer, int testLength) { int validChars = 0; for (int index = 0; index < testLength; index++) { wchar_t c = buffer[index]; if (c < 0 || !(iswprint(c) || iswspace(c))) return false; } return true; } // Check the first N bytes of data to see if they fall within printable ranges // for ASCII/MBCS character data. Quick and dirty. bool IsAsciiText(LPCSTR buffer, int testLength) { int validChars = 0; for (int index = 0; index < testLength; index++) { char c = buffer[index]; if (c < 0 || !(isprint(c) || isspace(c))) return false; } return true; } // Figure out if this is a binary file based on some common binary file extensions // Quick and dirty. bool IsBinaryFile(CString& file) { int indexOfExtension = file.ReverseFind(L'.'); if (indexOfExtension > -1) { CString sExt = file.Mid(indexOfExtension); return (sExt == L".dll" || sExt == L".exe" || sExt == L".bmp" || sExt == L".png" || sExt == L".gif" || sExt == L".ico" || sExt == L".jpg" || sExt == L".jpeg" || sExt == L".mp3" || sExt == L".drv" || sExt == L".wmp" || sExt == L".ra"); } return false; } // Our custom version of the CreateFile Windows API. // http://msdn.microsoft.com/en-us/library/aa363858.aspx HANDLE WINAPI Mine_CreateFile(LPCWSTR lpFileName,DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecAttr, DWORD dwCreateDisp, DWORD dwFlagsAttr,HANDLE hTemplate) { // First, all the original CreateFile provided by the operating system. HANDLE hFile = Real_CreateFile(lpFileName,dwDesiredAccess,dwShareMode,lpSecAttr, dwCreateDisp,dwFlagsAttr,hTemplate); if (lpFileName && hFile) { CString sFileName = lpFileName; if (!sFileName.IsEmpty()) { // Store the handle/filename... ::EnterCriticalSection(&g_CritSec); g_openFiles.insert(pair<HANDLE, CString>(hFile, sFileName)); ::LeaveCriticalSection(&g_CritSec); // Convert from creation disposition to our enumeration vals FileAction fa; switch(dwCreateDisp) { case CREATE_ALWAYS: fa = File_CreateAlways; break; case CREATE_NEW: fa = File_CreateNew; break; case OPEN_ALWAYS: fa = File_OpenAlways; break; case OPEN_EXISTING: fa = File_OpenExisting; break; case TRUNCATE_EXISTING: fa = File_TruncateExisting; break; default: fa = File_Unknown; break; } // Send a notification off to the GUI Transmit(fa, API_CreateFile, hFile, lpFileName); } } return hFile; } // Our ReadFile and WriteFile detours both call this function to handle the buffer data // and transmit it off to the GUI. void ReadOrWriteFile(HANDLE hFile, LPCVOID lpBuffer, DWORD nNumberOfBytes, bool isRead) { if (!hFile || !lpBuffer || !nNumberOfBytes) return; ::EnterCriticalSection(&g_CritSec); // Does the file being written to/read from exist in our map? map<HANDLE, CString>::const_iterator iter = g_openFiles.find(hFile); if (iter != g_openFiles.end()) { CString msg, strFileName; strFileName = (*iter).second; strFileName.MakeLower(); // Check the file extension if (IsBinaryFile(strFileName)) { msg.Format(L"Target %s %d bytes %s '%s'\nBINARY\n\n", isRead ? L"read" : L"wrote", nNumberOfBytes, isRead ? L"from" : L"to", (*iter).second); } // Check for ASCII text first.. else if (IsAsciiText((LPSTR)lpBuffer, min(100, nNumberOfBytes))) { // Convert from ASCII to Unicode text LPWSTR lpTempBuffer = new WCHAR[nNumberOfBytes+1]; ::ZeroMemory(lpTempBuffer, (nNumberOfBytes+1) * 2); MultiByteToWideChar(CP_ACP, 0, (LPCSTR)lpBuffer, nNumberOfBytes, lpTempBuffer, nNumberOfBytes+1); msg.Format(L"Target %s %d bytes %s '%s'\n%s\n\n", isRead ? L"read" : L"wrote", nNumberOfBytes, isRead ? L"from" : L"to", (*iter).second, lpTempBuffer); delete [] lpTempBuffer; } // If not ASCII, maybe it's Unicode? else if (IsUnicodeText((LPWSTR)lpBuffer, min(100, nNumberOfBytes / 2))) { msg.Format(L"Target %s %d bytes %s '%s'\n", isRead ? L"read" : L"wrote", nNumberOfBytes, isRead ? L"from" : L"to", (*iter).second); msg.Append((LPWSTR)lpBuffer, nNumberOfBytes/2); msg.Append(L"\n\n"); } // Nope. Binary. else { msg.Format(L"Target %s %d bytes %s '%s'\nBINARY\n\n", isRead ? L"read" : L"wrote", nNumberOfBytes, isRead ? L"from" : L"to", (*iter).second); } // Notify the GUI. Transmit(isRead ? File_Read : File_Write, isRead ? API_ReadFile : API_WriteFile, hFile, msg); } ::LeaveCriticalSection(&g_CritSec); } // Our custom version of the WriteFile Windows API. // http://msdn.microsoft.com/en-us/library/aa365747(VS.85).aspx BOOL WINAPI Mine_WriteFile(HANDLE hFile,LPCVOID lpBuffer,DWORD nNumberOfBytesToWrite,LPDWORD lpNumberOfBytesWritten,LPOVERLAPPED lpOverlapped) { BOOL bSuccess = Real_WriteFile( hFile, lpBuffer, nNumberOfBytesToWrite, lpNumberOfBytesWritten, lpOverlapped); ReadOrWriteFile(hFile, lpBuffer, nNumberOfBytesToWrite, false); return bSuccess; } // Our custom version of the WriteFile Windows API. // http://msdn.microsoft.com/en-us/library/aa365747(VS.85).aspx BOOL WINAPI Mine_ReadFile(HANDLE hFile,LPVOID lpBuffer,DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped) { BOOL bSuccess = Real_ReadFile(hFile, lpBuffer, nNumberOfBytesToRead,lpNumberOfBytesRead, lpOverlapped); ReadOrWriteFile(hFile, lpBuffer, *lpNumberOfBytesRead, true); return bSuccess; } // Our custom version of the CloseHandle Windows API. // http://msdn.microsoft.com/en-us/library/ms724211(VS.85).aspx BOOL WINAPI Mine_CloseHandle(HANDLE hObject) { BOOL bSuccess = Real_CloseHandle(hObject); ::EnterCriticalSection(&g_CritSec); map<HANDLE, CString>::iterator iter = g_openFiles.find(hObject); if (iter != g_openFiles.end()) { Transmit(File_Close, API_CloseHandle, hObject, L""); g_openFiles.erase(iter); } ::LeaveCriticalSection(&g_CritSec); return bSuccess; } // DLL Entry Point. This DLL will be loaded in two places on any given run: // in the XFileMonitor.Gui.EXE application, and in the target application's // address space. BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: if (::GetModuleHandle(L"XFILEMONITOR.GUI.EXE") == NULL) { InitializeCriticalSection(&g_CritSec); DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); DetourAttach(&(PVOID&)Real_CreateFile, Mine_CreateFile); DetourAttach(&(PVOID&)Real_CloseHandle, Mine_CloseHandle); DetourAttach(&(PVOID&)Real_WriteFile, Mine_WriteFile); DetourAttach(&(PVOID&)Real_ReadFile, Mine_ReadFile); DetourTransactionCommit(); } break; case DLL_THREAD_ATTACH: break; case DLL_THREAD_DETACH: break; case DLL_PROCESS_DETACH: if (::GetModuleHandle(L"XFILEMONITOR.GUI.EXE") == NULL) { DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); DetourDetach(&(PVOID&)Real_CreateFile, Mine_CreateFile); DetourDetach(&(PVOID&)Real_CloseHandle, Mine_CloseHandle); DetourDetach(&(PVOID&)Real_WriteFile, Mine_WriteFile); DetourDetach(&(PVOID&)Real_ReadFile, Mine_ReadFile); DetourTransactionCommit(); } break; } return TRUE; } // Install the global window procedure hook, causing this DLL to be mapped // into the address space of every process on the machine. bool XFILEMONITORHOOK_API InstallHook(LPCWSTR targetExePath) { // Initialize some data structures... STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(si)); ZeroMemory(&pi, sizeof(pi)); si.cb = sizeof(si); // The following call loads the target executable with our DLL attached BOOL bSuccess = DetourCreateProcessWithDll( targetExePath, NULL, NULL, NULL, TRUE, CREATE_DEFAULT_ERROR_MODE | CREATE_SUSPENDED, NULL, NULL, &si, &pi, "detoured.dll", "XFileMonitor.Hook.dll", NULL); if (bSuccess) ResumeThread(pi.hThread); return TRUE == bSuccess; }
true
49a34690dd8803aa7d35d5661591b2e5439f9ac1
C++
dishbreak/wende-project
/Laser/source/Laser_control.ino
UTF-8
2,918
3.078125
3
[]
no_license
#include <SPI.h> #include <Servo.h> #define ON 1 #define OFF 0 #define MIN_SERVO 544 #define MAX_SERVO 2400 // Control pins #define LASER_PIN 2 #define AZ_SERVO_PIN 5 #define EL_SERVO_PIN 6 // Communication pins #define SS_PIN 10 #define MOSI_PIN 11 #define MISO_PIN 12 #define SCK_PIN 13 // Manual mode pins #define LEFT_PIN 3 #define RIGHT_PIN 4 #define UP_PIN 7 #define DOWN_PIN 8 #define MANUAL_PIN 9 #define MANUAL_DELAY 250 Servo el_servo; Servo az_servo; // Manual mode, used to set the initial calibration void manual_mode() { boolean in_manual_mode = true; int x_coord = az_servo.readMicroseconds(); int y_coord = el_servo.readMicroseconds(); while( in_manual_mode ) { // Get direction or mode change if( digitalRead( LEFT_PIN ) == HIGH ) x_coord = x_coord - 1; else if( digitalRead( RIGHT_PIN ) == HIGH ) x_coord = x_coord + 1; else if( digitalRead( UP_PIN ) == HIGH ) y_coord = y_coord + 1; else if( digitalRead( DOWN_PIN ) == HIGH ) y_coord = y_coord - 1; else if( digitalRead( MANUAL_PIN ) == HIGH ) in_manual_mode = false; // Make sure position is within limits if( x_coord < MIN_SERVO ) x_coord = MIN_SERVO; if( x_coord > MAX_SERVO ) x_coord = MAX_SERVO; if( y_coord < MIN_SERVO ) y_coord = MIN_SERVO; if( y_coord > MAX_SERVO ) y_coord = MAX_SERVO; // Set position set_position( x_coord, y_coord ); // Wait to prevent constant reading delay( MANUAL_DELAY ); } } // Move to the specified position void set_position( int x, int y) { // Set x coordinate az_servo.writeMicroseconds( x ); // Set y coordinate el_servo.writeMicroseconds( y ); } // Turn laser on or off void set_laser( int on_off ) { if (on_off == ON) digitalWrite( LASER_PIN, HIGH); else digitalWrite( LASER_PIN, LOW); } // Get data from wireless byte get_data() { byte return_value; // Enable reading digitalWrite( SS_PIN, LOW ); // Send nothing, return with the value read return_value = SPI.transfer( NULL ); // Disable reading digitalWrite( SS_PIN, HIGH ); return return_value; } // Send data over wireless void send_data( byte value ) { // Enable writing digitalWrite( SS_PIN, LOW ); // Send value SPI.transfer( value ); // Disable writing digitalWrite( SS_PIN, HIGH ); } // This is the initialization void setup() { // Set outputs pinMode( LASER_PIN, OUTPUT ); pinMode( AZ_SERVO_PIN, OUTPUT ); pinMode( EL_SERVO_PIN, OUTPUT ); // Initialize SPI // Sets SCK, MOSI, and SS to outputs // Pulls SCK and MOSI low, SS high SPI.begin(); // Initialize servos el_servo.attach( EL_SERVO_PIN ); az_servo.attach( AZ_SERVO_PIN ); } // This runs the program void loop() { boolean in_manual_mode; while(1) { in_manual_mode = analogRead( MANUAL_PIN ); if( in_manual_mode ) manual_mode(); } }
true
cf9d61ff3410f349c008721080e31e45bfcbb324
C++
916-Maria-Popescu/Data-Structures-and-Algorithms
/ADT FixedCapBiMap/ExtendedTest.cpp
UTF-8
7,936
3.125
3
[ "MIT" ]
permissive
#include "ExtendedTest.h" #include "FixedCapBiMap.h" #include "FixedCapBiMapIterator.h" #include <cassert> #include <iostream> using namespace std; void testIteratorSteps(FixedCapBiMap& m) { FixedCapBiMapIterator mi = m.iterator(); int count = 0; while (mi.valid()) { count++; mi.next(); } assert(count == m.size()); } void testCreate() { cout << "Test create" << endl; FixedCapBiMap m(10); assert(m.size() == 0); assert(m.isEmpty() == true); ValuePair empty = std::pair<TValue, TValue>(NULL_TVALUE, NULL_TVALUE); for (int i = -10; i < 10; i++) { assert(m.search(i) == empty); } for (int i = -10; i < 10; i++) { assert(m.search(i) == empty); } FixedCapBiMapIterator it = m.iterator(); assert(it.valid() == false); try { it.next(); assert(false); } catch (exception&) { assert(true); } try { it.getCurrent(); assert(false); } catch (exception&) { assert(true); } } void testAdd() { cout << "Test add" << endl; FixedCapBiMap m(50); for (int i = 0; i < 10; i++) { assert(m.add(i, i) == true); } assert(m.isEmpty() == false); assert(m.size() == 10); for (int i = -10; i < 0; i++) { assert(m.add(i, i) == true); } for (int i = 0; i < 10; i++) { assert(m.add(i, i) == true); } for (int i = 10; i < 20; i++) { assert(m.add(i, i) == true); } assert(m.isEmpty() == false); assert(m.size() == 40); FixedCapBiMap m2(21000); for (int i = -100; i < 100; i++) { m2.add(i, i); } assert(m2.isEmpty() == false); assert(m2.size() == 200); ValuePair empty = std::pair<TValue, TValue>(NULL_TVALUE, NULL_TVALUE); for (int i = -200; i < 200; i++) { if (i < -100) { assert(m2.search(i) == empty); } else if (i < 0) { ValuePair one = std::pair<TValue, TValue>(i, NULL_TVALUE); assert(m2.search(i) == one); } else if (i < 100) { ValuePair one = std::pair<TValue, TValue>(i, NULL_TVALUE); assert(m2.search(i) == one); } else { assert(m2.search(i) == empty); } } for (int i = 10000; i > -10000; i--) { m2.add(i, i); } testIteratorSteps(m2); assert(m2.size() == 20200); for (int i = -100; i < 100; i++) { assert(m2.add(i, i) == false); } assert(m2.size() == 20200); } void testRemove() { cout << "Test remove" << endl; FixedCapBiMap m(1000); for (int i = -100; i < 100; i++) { assert(m.remove(i, i) == false); } assert(m.size() == 0); for (int i = -100; i < 100; i = i + 2) { assert(m.add(i, i) == true); } for (int i = -100; i < 100; i++) { if (i % 2 == 0) { assert(m.remove(i, i) == true); } else { assert(m.remove(i, i) == false); } } assert(m.size() == 0); for (int i = -100; i <= 100; i = i + 2) { assert(m.add(i, i) == true); } testIteratorSteps(m); for (int i = 100; i > -100; i--) { if (i % 2 == 0) { assert(m.remove(i, i) == true); } else { assert(m.remove(i, i) == false); } testIteratorSteps(m); } assert(m.size() == 1); m.remove(-100, -100); assert(m.size() == 0); for (int i = -100; i < 100; i++) { assert(m.add(i, 0) == true); assert(m.add(i, 1) == true); assert(m.add(i, 2) == false); assert(m.add(i, 3) == false); assert(m.add(i, 4) == false); } assert(m.size() == 400); for (int i = -200; i < 200; i++) { if (i < -100 || i >= 100) { assert(m.remove(i, 0) == false); } else { assert(m.remove(i, 0) == true); assert(m.remove(i, 1) == true); } } assert(m.size() == 0); } void testRemoveKey(){ cout << "Test remove key" << endl; FixedCapBiMap m(1000); m.add(10, 14); m.add(10, 6); ValuePair aux = m.removeKey(10); assert(aux.first == 14); assert(aux.second == 6); m.add(7, 9); aux = m.removeKey(7); assert(aux.first==9); assert(aux.second==NULL_TVALUE); aux = m.removeKey(16); assert(aux.first == NULL_TVALUE); assert(aux.second == NULL_TVALUE); } void testIterator() { cout << "Test iterator" << endl; FixedCapBiMap m(100); FixedCapBiMapIterator it = m.iterator(); assert(it.valid() == false); for (int i = 0; i < 100; i++) { m.add(33, 33); } FixedCapBiMapIterator it2 = m.iterator(); assert(it2.valid() == true); TElem el = it2.getCurrent(); assert(el.first == 33); assert(el.second == 33); it2.next(); el = it2.getCurrent(); assert(el.first == 33); assert(el.second == 33); it2.next(); assert(it2.valid() == false); try { it2.next(); assert(false); } catch (exception&) { assert(true); } try { it2.getCurrent(); assert(false); } catch (exception&) { assert(true); } it2.first(); assert(it2.valid() == true); FixedCapBiMap m2(500); for (int i = -100; i < 100; i++) { assert(m2.add(i, i) == true); assert(m2.add(i, i) == true); assert(m2.add(i, i) == false); } FixedCapBiMapIterator it3 = m2.iterator(); assert(it3.valid() == true); for (int i = 0; i < 400; i++) { it3.next(); } assert(it3.valid() == false); it3.first(); assert(it3.valid() == true); FixedCapBiMap m3(300); for (int i = 0; i < 200; i = i + 4) { m3.add(i, i); } FixedCapBiMapIterator it4 = m3.iterator(); assert(it4.valid() == true); int count = 0; while (it4.valid()) { TElem e = it4.getCurrent(); assert(e.first % 4 == 0); it4.next(); count++; } assert(count == 50); } void testQuantity() { FixedCapBiMap m(61000); cout << "Test quantity" << endl; for (int j = 0; j < 30000; j = j + 1) { assert(m.add(j, j) == true); } for (int i = 10; i >= 1; i--) { for (int j = 0; j < 30000; j = j + 1) { if (i == 10) { assert(m.add(j, j) == true); } else { assert(m.add(j, j) == false); } } } assert(m.size() == 60000); FixedCapBiMapIterator it = m.iterator(); assert(it.valid() == true); for (int i = 0; i < m.size(); i++) { it.next(); } it.first(); while (it.valid()) { TElem e = it.getCurrent(); ValuePair val = std::pair<TValue, TValue>(e.first, e.first); assert(m.search(e.first) == val); it.next(); } assert(it.valid() == false); for (int j = 30000 - 1; j >= 0; j--) { assert(m.remove(j, j) == true); assert(m.remove(j, j) == true); } for (int i = 0; i < 10; i++) { for (int j = 40000; j >= -4000; j--) { assert(m.remove(j, j) == false); } } assert(m.size() == 0); } void testCapacity() { cout << "Test capacity" << endl; FixedCapBiMap m(10); for (int i = 0; i < 10; i++) { assert(m.add(i, i) == true); } assert(m.isFull() == true); try { m.add(11, 11); assert(false); } catch (exception&) { assert(true); } for (int i = 0; i < 2; i++) { assert(m.remove(i, i) == true); } assert(m.isFull() == false); assert(m.add(2, 2) == true); assert(m.add(2, 2) == false); assert(m.add(1, 1) == true); assert(m.isFull() == true); for (int i = 0; i < 10; i++) { try { m.add(10, 10); assert(false); } catch (exception&) { assert(true); } assert(m.isFull() == true); } } void testSearch() { cout << "Test search" << endl; FixedCapBiMap m(100); ValuePair empty = std::pair<TValue, TValue>(NULL_TVALUE, NULL_TVALUE); for (int i = 0; i < 100; i++) { assert(m.search(i) == empty); } for (int i = 0; i < 50; i++) { m.add(i, i); } for (int i = 0; i < 50; i++) { ValuePair one = std::pair<TValue, TValue>(i, NULL_TVALUE); assert(m.search(i) == one); } for (int i = 0; i < 50; i++) { m.add(i, i + 2); } for (int i = 0; i < 50; i++) { ValuePair one = std::pair<TValue, TValue>(i, i + 2); ValuePair two = std::pair<TValue, TValue>(i + 2, i); assert(m.search(i) == one || m.search(i) == two); } for (int i = 0; i < 50; i++) { assert(m.remove(i, i) == true); } for (int i = 0; i < 50; i++) { ValuePair one = std::pair<TValue, TValue>(i + 2, NULL_TVALUE); assert(m.search(i) == one); } for (int i = 0; i < 50; i++) { assert(m.remove(i, i + 2) == true); } for (int i = 0; i < 50; i++) { assert(m.search(i) == empty); } } void testAllExtended() { testCreate(); testAdd(); testRemove(); testIterator(); testSearch(); testCapacity(); testRemoveKey(); //testQuantity(); }
true
3fed0a6d545497913844a9bfe09a7e1a9ada97b0
C++
echolite1/ESP32-CrawlerRobot-FH-Dortmund
/src/motorDriver.cpp
UTF-8
2,468
2.953125
3
[ "Apache-2.0" ]
permissive
/** * ESP32 Motor Library * * Functions to set motor speed * * Authors: Vipul Deshpande, Jaime Burbano */ #include "Arduino.h" #include "motorDriver.h" static uint8_t inA1 = 16; /* Pin for Motor 0 */ static uint8_t inA2 = 17; /* Pin for Motor 0 */ static uint8_t inB1 = 19; /* Pin for Motor 1 */ static uint8_t inB2 = 33; /* Pin for Motor 1 */ static int freq = 20000; static uint8_t Channel1 = 0; static uint8_t Channel2 = 1; static uint8_t motorChannel1 = 5; /* PWM Pin for Motor 0 */ static uint8_t motorChannel2 = 18; /* PWM Pin for Motor 0 */ static uint8_t resolution = 8; mclass::mclass() { } void mclass::SETUP() { pinMode(inA1, OUTPUT); /* Initializing pins as Outputs */ pinMode(inA2, OUTPUT); /* Initializing pins as Outputs */ pinMode(inB1, OUTPUT); /* Initializing pins as Outputs */ pinMode(inB2, OUTPUT); /* Initializing pins as Outputs */ ledcSetup(Channel1, freq, resolution); ledcAttachPin(motorChannel1, Channel1); ledcSetup(Channel2, freq, resolution); ledcAttachPin(motorChannel2, Channel2); } void mclass::SPEED(int motor_speed) { } void mclass::motor_direction(Motors motor_ch, Direction dir) { if (motor_ch == 0) { if (dir == Forward) { digitalWrite(inA1,HIGH); //uncomment to use ESP custom digitalWrite(inA2,LOW); //uncomment to use ESP custom } else { digitalWrite(inA1,LOW); //uncomment to use ESP custom digitalWrite(inA2,HIGH); //uncomment to use ESP custom } } else { if (dir == Forward) { digitalWrite(inB1,LOW); //uncomment to use ESP custom digitalWrite(inB2,HIGH); //uncomment to use ESP custom } else { digitalWrite(inB1,HIGH); //uncomment to use ESP custom digitalWrite(inB2,LOW); //uncomment to use ESP custom } } } void mclass::set_speed(Motors motor_ch, Direction dir, int new_speed) { motor_direction(motor_ch, dir); /* polarize the motors before setting the speed */ if (new_speed < 0) { new_speed = 0; } else if (new_speed > 255) { new_speed = 255; } else if (new_speed >= 0 && new_speed <= 255) { new_speed = new_speed; } else { /* Do nothing */ } if (motor_ch == 0) { ledcWrite(Channel1, new_speed); } else { ledcWrite(Channel2, new_speed); } } mclass motorobject = mclass(); /* creating an object of class motor */
true
5e38054f5f5c0dd9573b67c8e8678220cadb4d2f
C++
Chrivent/Yechan-Ha
/해전 게임/Shell.cpp
UTF-8
674
2.96875
3
[]
no_license
#include "Shell.h" Shell::Shell() { target = NULL; breakaway = false; } void Shell::SetColor(COLORREF color) { this->color = color; } void Shell::SetTarget(Unit* target) { this->target = target; } COLORREF Shell::GetColor() { return color; } string Shell::GetType() { return type; } int Shell::GetDamage() { return damage; } Unit* Shell::GetTarget() { return target; } void Shell::DeleteTarget() { target = NULL; } bool Shell::CheckBreakAway() { int x = transform.position.x; int y = transform.position.y; if (x < 0 || x > 1280 || y < 0 || y > 540 || breakaway == true) return true; return false; }
true
a0c54c8168c922ee824759eee125606ec39be95c
C++
nanWarez/BTC_Xpert
/BTC_Xpert_test.cpp
UTF-8
1,948
3.03125
3
[]
no_license
//created by Cr4shOv3rrid3 under the https://github.com/Cr4shOv3rrid3/1337_General_Public_BTC_Banking_license // feel free to copy, hack, destroy or create new things with it // P.S. if you don't like i created that for you. just replace first line with your own cool stylish hacker name ;) #include <iostream> #include <stdio.h> using namespace std; struct test { double beginning; string material; int quantity; float price; double extended; }; struct test2 { string material; int quantity; float price; double extended; }; struct test3 { string material; int quantity; float price; double extended; string shitsgotreal; }; struct toshi { static char const ett = '@'; string username; string displayname; string address; float amount; }; test var0; test var1; test2 var2; test3 var3; float s0 = 0.0; float s1 = 5.5; float s2 = 2.6; float s3 = 1.9; //amount of BTC in sum and cost price of roundabout a local banking license: (100k$) string m0 = "stone"; string m1 = "gold"; string m2 = "silver"; string m3 = "iron"; //string sneakshit = "shitcollectors"; string unit = "BTC"; void settings(void) { var0.price = s0; var1.price = s1; var2.price = s2; var3.price = s3; var0.material = m0; var1.material = m1; var2.material = m2; var3.material = m3; //var3.shitsgotreal = sneakshit; } void testprint(void) { cout << "Bitcoin Generator Test Programm: \n"; cout << var1.price << " " << unit << " " << var1.material << "\n" << var2.price << " " << unit << " " << var2.material << "\n" << var3.price << " " << unit << " " << var3.material << "\n"; // << var0.price << " " << unit << " " << var0.material << "\n"; } int main() { settings(); testprint(); int count = 10; char ch; while(cin.get(ch) != ".") count++; cout << "Numbers of characters read: \n" << count; cout << "Test print!!!"; return 0; } //Basic Beginners Bitcoin generator Test Programmm in 100 Lines of code
true
13b2e634f97c2ae23124ac293250b55f16c5eaf4
C++
Magiczne/MidiCreator
/MidiCreator/Util/Util.cpp
UTF-8
5,224
3.046875
3
[]
no_license
#include "Util.h" using namespace UI; using namespace std; ConsoleSize Util::getConsoleSize() { ConsoleSize size; CONSOLE_SCREEN_BUFFER_INFO csbi; GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi); size.cols = csbi.srWindow.Right - csbi.srWindow.Left + 1; size.rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1; return size; } void Util::setConsoleSize(SHORT x, SHORT y) { //http://www.cplusplus.com/forum/windows/121444/#msg661553 HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE); if (h == INVALID_HANDLE_VALUE) { throw std::runtime_error("Unable to get stdout handle."); } // If either dimension is greater than the largest console window we can have, // there is no point in attempting the change. { COORD largestSize = GetLargestConsoleWindowSize(h); if (x > largestSize.X) { throw std::invalid_argument("The x dimension is too large."); } if (y > largestSize.Y) { throw std::invalid_argument("The y dimension is too large."); } } CONSOLE_SCREEN_BUFFER_INFO bufferInfo; if (!GetConsoleScreenBufferInfo(h, &bufferInfo)) { throw std::runtime_error("Unable to retrieve screen buffer info."); } SMALL_RECT& winInfo = bufferInfo.srWindow; COORD windowSize = { winInfo.Right - winInfo.Left + 1, winInfo.Bottom - winInfo.Top + 1 }; if (windowSize.X > x || windowSize.Y > y) { // window size needs to be adjusted before the buffer size can be reduced. SMALL_RECT info = { 0, 0, x < windowSize.X ? x - 1 : windowSize.X - 1, y < windowSize.Y ? y - 1 : windowSize.Y - 1 }; if (!SetConsoleWindowInfo(h, TRUE, &info)) { throw std::runtime_error("Unable to resize window before resizing buffer."); } } COORD size = { x, y }; if (!SetConsoleScreenBufferSize(h, size)) { throw std::runtime_error("Unable to resize screen buffer."); } SMALL_RECT info = { 0, 0, x - 1, y - 1 }; if (!SetConsoleWindowInfo(h, TRUE, &info)) { throw std::runtime_error("Unable to resize window after resizing buffer."); } } void Util::setColor(uint8_t combinedColor) { HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); if (hConsole == INVALID_HANDLE_VALUE) { throw std::runtime_error("Unable to get stdout handle."); } SetConsoleTextAttribute(hConsole, combinedColor); } void Util::setColor(Color text, Color background) { HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); if (hConsole == INVALID_HANDLE_VALUE) { throw std::runtime_error("Unable to get stdout handle."); } SetConsoleTextAttribute(hConsole, Util::createColor(text, background)); } uint8_t Util::createColor(Color text, Color background) { return (static_cast<uint8_t>(background) << 4) + static_cast<uint8_t>(text); } void Util::clearConsole() { Util::writtenLines = 0; system("cls"); } void Util::setCursorPos(SHORT x, SHORT y) { COORD pos = { x, y }; Util::setCursorPos(pos); } void Util::setCursorPos(COORD coord) { HANDLE output = GetStdHandle(STD_OUTPUT_HANDLE); if (output == INVALID_HANDLE_VALUE) { throw std::runtime_error("Unable to get stdout handle."); } SetConsoleCursorPosition(output, coord); } void Util::writeLeft(string msg) { Util::writtenLines++; cout << msg << endl; } void Util::writeCentered(string msg) { Util::writtenLines++; ConsoleSize size = Util::getConsoleSize(); int width = (size.cols + msg.size()) / 2; cout << setw(width) << msg << endl; } void Util::writeRight(string msg) { Util::writtenLines++; ConsoleSize size = Util::getConsoleSize(); cout << setw(size.cols) << msg << endl; } void Util::writeMulti(string left, string right, int8_t rightColor) { Util::writtenLines++; ConsoleSize size = Util::getConsoleSize(); cout << left; if (rightColor != -1) { Util::setColor(rightColor); } cout << setw(size.cols - left.size()) << right << endl; } void Util::makeLine(int width, int8_t color) { Util::writtenLines++; if (color != -1) { Util::setColor(color); } for (int i = 0; i < width; i++) { cout << '-'; } cout << endl; } void Util::newLine(int num) { Util::writtenLines += num; for (int i = 0; i < num; i++) { cout << endl; } } char Util::getUnbufferedKey() { DWORD events; INPUT_RECORD buffer; HANDLE handle = GetStdHandle(STD_INPUT_HANDLE); if (handle == INVALID_HANDLE_VALUE) { throw std::runtime_error("Unable to get stdout handle."); } PeekConsoleInput(handle, &buffer, 1, &events); if (events > 0) { ReadConsoleInput(handle, &buffer, 1, &events); if (buffer.Event.KeyEvent.bKeyDown) { return static_cast<char>(buffer.Event.KeyEvent.wVirtualKeyCode); } return 0; } return 0; } unsigned short Util::getNumberOfDigits(unsigned i) { int digits = 0; while (i != 0) { i /= 10; digits++; } return digits; } void Util::showLastSystemError() { LPSTR messageBuffer; FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, nullptr, // source GetLastError(), 0, // lang reinterpret_cast<LPSTR>(&messageBuffer), 0, nullptr); cerr << messageBuffer << '\n'; LocalFree(messageBuffer); } #ifdef DEBUG_MSG void Util::debug(std::string c) { OutputDebugStringA(c.c_str()); } void Util::debug(int msg) { string m = to_string(msg); Util::debug(m); } #endif
true
86ef2d7c8497406ae17af4d9fa963fa24676a7e0
C++
smiljanaspasic/Algorithms-and-data-structures
/Hashing/Hesfunkcija.cpp
UTF-8
7,583
2.765625
3
[]
no_license
#include <iostream> #include <string> #include <math.h> #include <fstream> #define MAX 700000 #define c 2 using namespace std; int konverzijaosnove(string s,int n) { int q=13; int mul = 0; int num = 0; int sum = 0; for (int i = s.length()-1; i>=0 ; i--) { sum=sum + pow(q, num) * (int)s[i]; num++; } sum=sum % n; if (sum < 0) sum = 0 - sum; return sum; } class Info { private: string orglang, orgtitle, release, revenue, runtime; public: Info(string o=" ", string o2="", string r="", string r2="", string runt="") { orglang = o;orgtitle=o2; release = r; revenue = r2; runtime = runt; } string dohvatikey() const { return orgtitle; } void setkey(string m) { orgtitle = m; } string dohvatisadrzaj() const { return orglang + " " + release + " " + revenue + " " + runtime; } }; class AddressFunction { virtual int getAddress(string key, int matadr, int pokusaj, int n) = 0; }; class QuadriaticHashing : public AddressFunction { public: int getAddress(string key, int matadr, int pokusaj, int n) override { return (matadr + c * pokusaj*pokusaj) % n; } }; class HashTable { private: Info** niz; int n; QuadriaticHashing a; int pristupusp, pristupne; int numofkeysnotfound; int x, last; public: HashTable(int nn, QuadriaticHashing ff) { niz = new Info*[n = nn]; for (int i = 0; i < n; i++) { niz[i] = 0; } a = ff; resetStatistics(); } string findKey(string key) { int tryy = 1; bool flag = false; x = konverzijaosnove(key, n); last = x; if (niz[x] == 0) { pristupne++; last = x; numofkeysnotfound++; return "0"; } else if (niz[x]->dohvatikey() == key) { pristupusp++; return niz[x]->dohvatisadrzaj(); } else { if (niz[x]->dohvatikey() == "DELETED") last = x; pristupne++; pristupusp++; int j = a.getAddress(key, x, tryy, n); if (niz[last]->dohvatikey() != "DELETED") { last = j; } while (j !=x) { if (niz[j] == 0 ) { if (last != j) { if (niz[last]->dohvatikey() != "DELETED") last = j; } break; } else { if (niz[j]->dohvatikey() == key) { flag = true; x = j; break; } else { pristupusp++; pristupne++; tryy++; j = a.getAddress(key, j, tryy, n); if (niz[last]->dohvatikey() != "DELETED") { last = j; } } } } if (flag == false) { pristupusp = pristupusp - tryy; pristupne++; numofkeysnotfound++; return "0"; } else { pristupne = pristupne - tryy; pristupusp++; return niz[x]->dohvatisadrzaj(); } } } bool insertKey(string key, Info* in) { if (findKey(key) != "0") return false; else { if (niz[last] == 0) { niz[last] = in; return true; } else { if (niz[last]->dohvatikey() == "DELETED") { niz[last] = in; return true; } else return false; } } } bool deleteKey(string key) { if (findKey(key) == "0") return false; else { niz[x]->setkey("DELETED"); return true; } } void clear() { for (int i = 0; i < n; i++) { niz[i] = 0; } } ~HashTable() { clear(); delete[] niz; } int keycount() { int cnt = 0; for (int i = 0; i < n; i++) { if (niz[i] != 0) { if (niz[i]->dohvatikey() != "DELETED") { cnt++; } } } return cnt; } int tableSize() const { return n; } double fillRatio() { return (double)keycount() /(double)tableSize(); } void resetStatistics() { pristupusp = 0; pristupne = 0; numofkeysnotfound = 0; } int avgAccessSuccess() { return pristupusp /keycount(); } int avgAccessUnsuccess() { return pristupne /numofkeysnotfound; } double avgUnsuccessEst() { double p; if (fillRatio() != 1) { p = 1.00 - fillRatio(); p = 1.00 / p; } else p = 0; return p; } friend ostream& operator<<(ostream& os, const HashTable& h) { for (int i = 0; i < h.n; i++) { if (h.niz[i] == 0) os << "EMPTY" << endl; else { if (h.niz[i]->dohvatikey() == "DELETED") os << h.niz[i]->dohvatikey() << endl; else os << h.niz[i]->dohvatikey() << " " << h.niz[i]->dohvatisadrzaj() << endl; } } return os; } }; void funkcijazatestiranje(HashTable& h,string* ispniz,Info* nizo,int size1,int size2) { for (int i = 0; i < size1; i++) { h.insertKey(nizo[i].dohvatikey(),&nizo[i]); } h.resetStatistics(); for (int i = 0; i < size2; i++) { h.findKey(ispniz[i]); } cout << h.avgAccessSuccess() << endl; cout << h.avgAccessUnsuccess() << endl; cout << h.avgUnsuccessEst() << endl; } int main() { string* ispitniniz = new string[MAX]; Info* nizic = new Info[MAX]; Info* noviniz = new Info[MAX]; int n = -1; int n2 = 0; int vel; string jezik; string naslov; string godina; string prihod; string vremetrajanja; QuadriaticHashing d; cout << "Unesite velicinu tabele" << endl; cin >> vel; HashTable tabela(vel, d); int radi = 1; int izbor; while (radi) { cout << "Izbor?\n" "2. Ucitavanje podataka za test i pozivanje funkcije testiranja\n" "3. Trazi kljuc\n" "4. Dodaj kljuc\n" "5. Izbrisi kljuc\n" "6. Prosecan uspesni broj pristupa\n" "7. Prosecan neuspesni broj pristupa\n" "8. Prosecan neuspesni procenjeni broj pristupa\n" "9. Resetuj statistiku\n" "10. Isprazni tabelu\n" "11. Broj umetnutih kljuceva u tabeli\n" "12. Velicina tabele\n" "13. Ispis tabele\n" "14. Stepen popunjenosti\n" "15. Prekid programa\n" << endl; cin >> izbor; switch (izbor) { case 2: { ifstream dat; dat.open("tmdb_movies.csv"); if (!dat.is_open()) cout << "Greska"; else { while (!dat.eof()) { getline(dat, jezik, ','); getline(dat, naslov, ','); getline(dat, godina, ','); getline(dat, prihod, ','); getline(dat, vremetrajanja, '\n'); if (n >= 0) { nizic[n] = Info(jezik, naslov, godina, prihod, vremetrajanja); } n++; } ifstream dat2; dat2.open("movies_search_1.txt"); if (!dat.is_open()) cout << "Greska"; else { while (!dat2.eof()) { getline(dat2, naslov, '\n'); ispitniniz[n2++] = naslov; } } } funkcijazatestiranje(tabela, ispitniniz, nizic, n, n2); break; } case 3: { cout << "Napisi naslov filma koji zelis da nadjes" << endl; cin.get(); getline(cin, naslov); cout << tabela.findKey(naslov) << endl; break; } case 4: { ifstream dato; cout << "Unesi ime datoteke" << endl; string ime; cin >> ime; n = 0; dato.open(ime); if (!dato.is_open()) cout << "Greska"; else { while (!dato.eof()) { getline(dato, jezik, ','); getline(dato, naslov, ','); getline(dato, godina, ','); getline(dato, prihod, ','); getline(dato, vremetrajanja, '\n'); noviniz[n] = Info(jezik, naslov, godina, prihod, vremetrajanja); n++; } for (int i = 0; i < n; i++) { tabela.insertKey(noviniz[i].dohvatikey(), &noviniz[i]); } break; } } case 5: { cout << "Unesi naslov filma koji zelis da izbrises" << endl; cin.get(); getline(cin, naslov); tabela.deleteKey(naslov); break; } case 6: { cout << tabela.avgAccessSuccess() << endl; break; } case 7: { cout << tabela.avgAccessUnsuccess() << endl; break; } case 8: { cout << tabela.avgUnsuccessEst() << endl; break; } case 9: { tabela.resetStatistics(); break; } case 10: { tabela.clear(); break; } case 11: { cout << tabela.keycount() << endl; break; } case 12: { cout << tabela.tableSize() << endl; break; } case 13: { cout << tabela; break; } case 14: { cout << tabela.fillRatio() << endl; break; } case 15: { radi = 0; break; } } } }
true
ee5d03996d1b82ce95fa3e2369e32169c81092ca
C++
ashanka234/interviewPrep
/revision/arrays/removeAdjDuplicates.cpp
UTF-8
564
3.1875
3
[]
no_license
#include<iostream> using namespace std; void removeAdjDuplicates(char *str) { if(str[0] == '\0') return; if(str[0] == str[1]) { //adj duplicate found //shift left int i=0; while(str[i] != '\0') { str[i] = str[i+1]; i++; } removeAdjDuplicates(str); } //if adj duplicate not found removeAdjDuplicates(str+1); } int main() { char str[] = "aabccd"; int n = sizeof(str)/sizeof(str[0]); removeAdjDuplicates(str); cout << str << endl; return (0); }
true
a16006b74189bc9259341d324d6ae272bd4b9427
C++
SimonBFrank/TGA_Picture_Editor
/Pixel.cpp
UTF-8
412
2.96875
3
[]
no_license
#include "Pixel.h" Pixel::Pixel(unsigned char redIN, unsigned char blueIN, unsigned char greenIN) { this->redAmount = redIN; this->blueAmount = blueIN; this->greenAmount = greenIN; } unsigned char Pixel::getBlueAmount() { return this->blueAmount; } unsigned char Pixel::getRedAmount() { return this->redAmount; } unsigned char Pixel::getGreenAmount() { return this->greenAmount; }
true
4030ca1fa8680f709c812efd7b3ca769efe8acf8
C++
Matheus7OP/sudokuSolver
/sudoku_solver.cpp
UTF-8
4,675
3.078125
3
[]
no_license
#include <iostream> #include <cstring> #include <ctime> #include <set> using namespace std; bool isUnknown(int value) { return (value == 0); } void initialize(set<int> &possibilities) { for(int i = 1; i <= 9; i++) possibilities.insert(i); } void removeInconsistenciesFromLine(int line, set<int> &possibilities, int matrix[][11]) { for(int j = 0; j < 9; j++) possibilities.erase(matrix[line][j]); } void removeInconsistenciesFromColumn(int column, set<int> &possibilities, int matrix[][11]) { for(int i = 0; i < 9; i++) possibilities.erase(matrix[i][column]); } void removeInconsistenciesFromSubregion(int line, int column, set<int> &possibilities, int matrix[][11]) { int initialLine, initialColumn; initialLine = 3 * (line / 3); initialColumn = 3 * (column / 3); for(int i = initialLine; i < initialLine + 3; i++) { for(int j = initialColumn; j < initialColumn + 3; j++) possibilities.erase(matrix[i][j]); } } void showResultingMatrix(int matrix[][11]) { cout << "Resulting matrix is: " << endl; for(int i = 0; i < 9; i++) { for(int j = 0; j < 9; j++) { if(j != 0) cout << " "; cout << matrix[i][j]; } cout << endl; } } void answerNotFound() { cout << "You know when sometimes we just can't find an answer?" << endl; cout << "Well, this is one of those times. Couldn't find the resulting matrix for that." << endl; cout << "Remember: I'm only able to calculate results for valid matrices with difficulty level up to hard" << endl; cout << "Finishing execution..." << endl; } void removeAllInconsistencies(int line, int column, set<int> &possibilities, int matrix[][11]) { removeInconsistenciesFromLine(line, possibilities, matrix); removeInconsistenciesFromColumn(column, possibilities, matrix); removeInconsistenciesFromSubregion(line, column, possibilities, matrix); } void tryMethod1(int matrix[][11], int line, int column) { set<int> possibilities; initialize(possibilities); removeAllInconsistencies(line, column, possibilities, matrix); if( possibilities.size() == 1 ) { matrix[line][column] = *possibilities.begin(); } } void tryMethod2(int matrix[][11], int line, int column) { if( isUnknown(matrix[line][column]) ) { int frequencyColumn[10], frequencyLine[10]; set<int> possLine, possColumn, possibilities; memset(frequencyLine, 0, sizeof frequencyLine); memset(frequencyColumn, 0, sizeof frequencyColumn); for(int j = 0; j < 9; j++) { if( isUnknown( matrix[line][j] ) ) { possLine.clear(); initialize(possLine); removeAllInconsistencies(line, j, possLine, matrix); for(int e : possLine) frequencyLine[e]++; } } for(int i = 0; i < 9; i++) { if( isUnknown( matrix[i][column] ) ) { possColumn.clear(); initialize(possColumn); removeAllInconsistencies(i, column, possColumn, matrix); for(int e : possColumn) frequencyColumn[e]++; } } initialize(possibilities); removeAllInconsistencies(line, column, possibilities, matrix); for(int e : possibilities) { if(frequencyColumn[e] == 1 or frequencyLine[e] == 1) { matrix[line][column] = e; break; } } } } void tryMethod3(int matrix[][11], int line, int column) { if( isUnknown( matrix[line][column] ) ) { set<int> possSubregion, possibilities; int initialLine, initialColumn, frequency[10]; memset(frequency, 0, sizeof frequency); initialLine = 3 * (line / 3); initialColumn = 3 * (column / 3); for(int i = initialLine; i < initialLine + 3; i++) { for(int j = initialColumn; j < initialColumn + 3; j++) { if(isUnknown( matrix[i][j] )) { possSubregion.clear(); initialize(possSubregion); removeAllInconsistencies(i, j, possSubregion, matrix); for(int e : possSubregion) frequency[e]++; } } } initialize(possibilities); removeAllInconsistencies(line, column, possibilities, matrix); for(int e : possibilities) { if(frequency[e] == 1) { matrix[line][column] = e; break; } } } } bool timeUp(clock_t startTime) { double executionTime = ((double)(clock() - startTime/CLOCKS_PER_SEC)) / 1000000.0; return (executionTime >= 30.0); } int main() { clock_t startTime = clock(); int matrix[11][11]; bool endFilling; for(int i = 0; i < 9; i++) { for(int j = 0; j < 9; j++) cin >> matrix[i][j]; } while( !endFilling and !timeUp(startTime) ) { endFilling = true; for(int i = 0; i < 9; i++) { for(int j = 0; j < 9; j++) { if( isUnknown(matrix[i][j]) ) { endFilling = false; tryMethod1(matrix, i, j); tryMethod2(matrix, i, j); tryMethod3(matrix, i, j); } } } } if(endFilling) showResultingMatrix(matrix); else answerNotFound(); return 0; }
true
69a6d451cd895dbbc81dbda30511d8032780c58b
C++
anhero/BaconBox
/BaconBox/Helper/Timer.cpp
UTF-8
878
2.859375
3
[]
no_license
#include "BaconBox/Helper/Timer.h" #include "BaconBox/Core/Engine.h" #include "BaconBox/Helper/TimerManager.h" using namespace BaconBox; Timer::Timer() : started(false), interval(0.0), timeCounter(0.0) { TimerManager::addTimer(this); } Timer::Timer(double newInterval) : started(false), interval(newInterval), timeCounter(0.0) { TimerManager::addTimer(this); } Timer::~Timer() { TimerManager::removeTimer(this); } void Timer::start() { started = true; timeCounter = 0.0; } void Timer::stop() { started = false; } bool Timer::isStarted() const { return started; } void Timer::setInterval(double newInterval) { interval = newInterval; } double Timer::getInterval() const { return interval; } void Timer::update() { if(started) { timeCounter += Engine::getSinceLastUpdate(); while(timeCounter > interval) { timeCounter -= interval; tick(); } } }
true
fe8a90dacc1f3948a20e29eecbd612413d15fec5
C++
cmguo/just-just-export
/Error.h
UTF-8
3,890
2.5625
3
[]
no_license
// Error.h #ifndef _JUST_EXPORT_ERROR_H_ #define _JUST_EXPORT_ERROR_H_ namespace just { namespace error { enum errors { success = 0, not_start, already_start, not_open, already_open, operation_canceled, would_block, stream_end, logic_error, network_error, demux_error, certify_error, download_error, other_error = 1024, }; namespace detail { class category : public boost::system::error_category { public: const char* name() const BOOST_SYSTEM_NOEXCEPT { return "just/export"; } std::string message(int value) const { if (value == success) return "Everything is ok"; if (value == not_start) return "JUST has not started"; if (value == already_start) return "JUST has already started"; if (value == not_open) return "JUST has not opened"; if (value == already_open) return "JUST has already opened"; if (value == operation_canceled) return "JUST operation canceled"; if (value == would_block) return "JUST stream would block"; if (value == stream_end) return "JUST stream end"; if (value == logic_error) return "JUST logic error"; if (value == network_error) return "JUST network error"; if (value == demux_error) return "JUST demux error"; if (value == certify_error) return "JUST certify error"; if (value == download_error) return "JUST download error"; return "JUST error"; } }; } // namespace detail inline const boost::system::error_category & get_category() { static detail::category instance; return instance; } static boost::system::error_category const & just_category = get_category(); inline boost::system::error_code make_error_code( errors e) { return boost::system::error_code( static_cast<int>(e), get_category()); } inline boost::system::error_code & __last_error() { static boost::system::error_code ec; return ec; } inline boost::system::error_code const & last_error() { return __last_error(); } inline void last_error( boost::system::error_code const & ec) { __last_error() = ec; } error::errors last_error_enum( boost::system::error_code const & ec); inline error::errors last_error_enum() { return last_error_enum(last_error()); } } // namespace error } // namespace just namespace boost { namespace system { template<> struct is_error_code_enum<just::error::errors> { BOOST_STATIC_CONSTANT(bool, value = true); }; #ifdef BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP using just::error::make_error_code; #endif } } #endif // _JUST_EXPORT_ERROR_H_
true
61be4a90173b358b9ffbed1e7e28537960896e80
C++
yazici/minecraft-texture-viewer
/src/render/renderable.h
UTF-8
601
2.84375
3
[]
no_license
#ifndef RENDERABLE_H #define RENDERABLE_H #include <memory> #include "glad.h" #include "material.h" #include <glm\glm.hpp> struct vertex { glm::vec3 position; glm::vec3 normal; glm::vec3 tangent; glm::vec2 uv; vertex(glm::vec3 position, glm::vec3 normal, glm::vec3 tangent, glm::vec2 uv); }; /*! * \brief Something that can be rendered * * While I normally don't like OOP renderers, this is easy to write */ class renderable { public: void render(); void set_vertex_data(std::vector<vertex> vertices, std::vector<int> indices); private: int num_indices; GLuint vao = -1; }; #endif
true
116123ce8db9c3456eb3ab7b47abd5e62573c8c5
C++
arelli/bosch-BME280-lib
/bme280_register_read.ino
UTF-8
4,398
2.515625
3
[]
no_license
#include <Wire.h> // this sketch polls data out of the pressure/barometer sensor GY-BME280 // the direct register polling method was chosen to remove the need of external // libraries(like adafruit) that will potentially slow down the execution of the // integrated program. Refer to the bst-bme280-ds002.pdf datasheet to // understand the use of the registers! // Wiring: wire the SCL/SDA pins to the respective pins in arduino board // wire the vcc to 3.3V(NOT 5!) and the gnd to the respective gnd // optionally, pull-up the lines of SDA,SCL and the pin of CSB with 10K resistors. // Leave SDO unwired(needed only for SPI interfacing) // Raf //8-bit registers of the BME280 #define humidity_lsb 0xfe #define humidity_msb 0xFD #define temperature_xlsb 0xFC // the xlsb is used only for extra accuracy(and not needed in our case) #define temperature_lsb 0xFB #define temperature_msb 0xFA #define pressure_xlsb 0xF9 // the xlsb is used only for extra accuracy as above #define pressure_lsb 0xF8 #define pressure_msb 0xf7 #define config_register 0xF5 #define ctrl_meas 0xf4 #define status_register 0xf3 #define ctrl_humidity 0xf2 #define reset_register 0xe0 #define chip_id 0xD0 // the hardcoded i2c address of the sensor(found with arduino 12c scanner sketch) int BME280adress = 0x76; void setup() { Serial.begin(115200); Wire.begin(); //initiate the wire library(needed!) set_register(BME280adress,reset_register,B10110110); // B10110110 is the required sequence to reset the device set_register(BME280adress,config_register,B01001000); // configure the oversampling and IIR filter set_register(BME280adress,ctrl_humidity ,0x01); set_register(BME280adress,ctrl_meas, B01101101); // do one forced measurement cycle } byte temp1,temp2,temp3; byte pres1,pres2,pres3; byte hum1, hum2; void loop() { set_register(BME280adress,ctrl_meas, B01101101); // do one forced measurement cycle //initiate a transmission and ask for the data from the following registers read_register(BME280adress,ctrl_meas); read_register(BME280adress,status_register); read_register(BME280adress,ctrl_humidity); // r e a d t e m p e r a t u r e temp1 = read_register(BME280adress,temperature_msb); temp2 = read_register(BME280adress,temperature_lsb); temp3 = read_register(BME280adress,temperature_xlsb); temp3 = temp3 & 11110000; // only the 4 first bits are used unsigned long int temperature = temp1; // long to fit the 16+4 bit number we shove into temperature temperature = (temperature << 8) | temp2; // shift bits to make place for the next 8 bits to be included with logical OR ("|") float temperature_float = (float(temperature)+ (float(temp3)/16))/1000; Serial.print("Temperature: "); Serial.print(temperature_float,5); Serial.print(" °C, "); // r e a d p r e s s u r e pres1 = read_register(BME280adress,pressure_msb); pres2 = read_register(BME280adress,pressure_lsb); pres3 = read_register(BME280adress,pressure_xlsb); pres3 = pres3 & 11110000; // keep only the first 4 digits of the register(see datasheet) unsigned long int pressure = pres1; // 32 bit capacity pressure = (pressure<<8) | pres2; pressure = (pressure<<4) | pres3; float pressure_float = float(pressure)/256; Serial.print("Pres.: "); Serial.print(pressure_float,5);Serial.print(" hPa/mBar, "); // // r e a d h u m i d i t y // hum1 = read_register(BME280adress,humidity_msb); // hum2 = read_register(BME280adress,humidity_lsb); // unsigned int humidity = hum1 * 256 + hum2; // Serial.print("Humidity: "); // Serial.print(humidity); // Serial.println( " % RH \n"); Serial.println( "\n"); delay(250); Serial.write(12); } byte read_register(int ic_address,int reg_address){ Wire.beginTransmission(ic_address); Wire.write(reg_address); Wire.endTransmission(); byte returned_value; Wire.requestFrom(ic_address,byte(1)); if( Wire.available() == 1){ // check if there are 2 available bytes returned_value = Wire.read(); return returned_value; } else return -1; } void set_register(int ic_address, int reg_address, byte bytes_to_write){ Wire.beginTransmission(ic_address); Wire.write(reg_address); Wire.write(bytes_to_write); Wire.endTransmission(); }
true
1ff48e0b2ad59dfd6634d984319db26b20f72469
C++
kochol/kge
/Include/math/Frustum.h
UTF-8
2,239
2.6875
3
[ "MIT" ]
permissive
// File name: Frustum.h // Des: This class is for calculate frustum views. // Date: 16/11/1386 // Programmer: Ali Akbar Mohamadi(Kochol) #ifndef FRUSTUM_H #define FRUSTUM_H #include "Plane.h" namespace kge { namespace math { enum FrustumSide { //! The RIGHT side of the frustum EFS_Right = 0, //! The LEFT side of the frustum EFS_Left = 1, //! The BOTTOM side of the frustum EFS_Bottom = 2, //! The TOP side of the frustum EFS_Top = 3, //! The far side of the frustum EFS_Far = 4, //! The near side of the frustum EFS_Near = 5 }; // FrustumSide class KGE_API Frustum { public: //! Constructor Frustum(); //! Destructor ~Frustum(); //! Checks the frustum collision with sphere and returns ECT_In or ECT_Out CollisionType Collision(const Sphere* pSphere) const; //! Checks the frustum collision with sphere bool TestSphere(const Sphere* pSphere) const; //! Checks the frustum collision with AABB and returns ECT_In or ECT_Out CollisionType Collision(const AABB* pBox) const; /*! Create the frustum culling with camera matrices. \param pMatrixView The camera's view matrix. \param pMatrixProjection The camera's projection matrix. */ virtual void Init(const Matrix* pMatrixView, const Matrix* pMatrixProjection); //! Returns the point which is on the far left upper corner inside the the view frustum. Vector GetFarLeftUpPoint(); //! Returns the point which is on the far left bottom corner inside the the view frustum. Vector GetFarLeftDownPoint(); //! Returns the point which is on the far Right upper corner inside the the view frustum. Vector GetFarRightUpPoint(); //! Returns the point which is on the far Right bottom corner inside the the view frustum. Vector GetFarRightDownPoint(); //! Returns the bounding box AABB* GetBoundingBox(); //! Returns the center of the frustum Vector* GetCenter(); //! Returns the 8 frustum corners Vector* GetCorners(); //! TestSweptSphere bool TestSweptSphere(Sphere& sphere, Vector& sweepDir) const; Vector* m_pCameraPosition; protected: Plane * m_pSides; AABB * m_pAABB; bool m_bCalcAABB; Matrix m_mViewProj; Vector m_vCorners[8], m_vCenter; }; // Frustum } // math } // kge #endif // FRUSTUM_H
true
f1b99412da0fa56247e11efb9f7294775f6703f5
C++
linuxemb/datastructure
/Chapter02/SearchAndSortAdvanced/Main.cpp
UTF-8
14,926
3.140625
3
[ "MIT" ]
permissive
#include <IOStream> #include <CStdLib> #include <CAssert> using namespace std; #include "ArrayList.h" #include "..\\ListAdvanced\\List.h" #include "Search.h" #include "Sort.h" void linkedList(); void main() { linkedList(); } void linkedList() { LinkedList<double> list; cin >> list; for (LinkedList<double>::Iterator iterator = list.begin(); iterator != list.end(); ++iterator) { cout << *iterator << " "; } cout << endl; for (LinkedList<double>::ReverseIterator iterator = list.rbegin(); iterator != list.rend(); ++iterator) { cout << *iterator << " "; } cout << endl; for (LinkedList<double>::Iterator iterator = list.begin(); iterator != list.end(); iterator++) { cout << *iterator << " "; } cout << endl; for (LinkedList<double>::ReverseIterator iterator = list.rbegin(); iterator != list.rend(); iterator++) { cout << *iterator << " "; } cout << endl; for (const double value : list) { cout << value << " "; } cout << endl; for (const double& value : list) { cout << value << " "; } cout << endl; for (double value : list) { cout << value << " "; } cout << endl; for (double& value : list) { cout << value << " "; } cout << endl; mergeSort<LinkedList<double>, double>(list); cout << "Merge Sort " << list << endl; quickSort<LinkedList<double>, double>(list); cout << "Quick Sort " << list << endl; for (double value : list) { cout << "<" << value << "," << binarySearch<LinkedList<double>, double>(value, list) << "> "; } cout << "<0," << binarySearch<LinkedList<double>, double>(0, list) << "> "; cout << "<6," << binarySearch<LinkedList<double>, double>(6, list) << "> "; cout << "<10," << binarySearch<LinkedList<double>, double>(10, list) << ">" << endl; const LinkedList<double> list2(list); for (LinkedList<double>::Iterator iterator = list2.begin(); iterator != list2.end(); ++iterator) { cout << *iterator << " "; } cout << endl; for (LinkedList<double>::ReverseIterator iterator = list2.rbegin(); iterator != list2.rend(); ++iterator) { cout << *iterator << " "; } cout << endl; for (LinkedList<double>::Iterator iterator = list2.begin(); iterator != list2.end(); iterator++) { cout << *iterator << " "; } cout << endl; for (LinkedList<double>::ReverseIterator iterator = list2.rbegin(); iterator != list2.rend(); iterator++) { cout << *iterator << " "; } cout << endl; for (const double value : list2) { cout << value << " "; } cout << endl; for (const double& value : list2) { cout << value << " "; } cout << endl; for (double value : list2) { cout << value << " "; } cout << endl; for (double& value : list2) { cout << value << " "; } cout << endl; } #if 0 void arrayList() { cout << "ArrayList" << endl; ArrayList list; list.add(9); list.add(7); list.add(5); list.add(3); list.add(1); for (ArrayList::Iterator position = list.begin(); position.hasNext(); position.next()) { cout << "<" << *position << "," << linarySearch<ArrayList, double>(*position, list) << "> "; } cout << "<0," << linarySearch<ArrayList,double>(0, list) << "> "; cout << "<6," << linarySearch<ArrayList, double>(6, list) << "> "; cout << "<10," << linarySearch<ArrayList, double>(10, list) << ">" << endl; selectSort<ArrayList, double>(list); cout << "Select " << list << endl; for (ArrayList::Iterator position = list.begin(); position.hasNext(); position.next()) { cout << "<" << *position << "," << binarySearch<ArrayList, double>(*position, list) << "> "; } cout << "<0," << binarySearch<ArrayList, double>(0, list) << "> "; cout << "<6," << binarySearch<ArrayList, double>(6, list) << "> "; cout << "<10," << binarySearch<ArrayList, double>(10, list) << ">" << endl; insertSort<ArrayList,double>(list); cout << "Insert " << list << endl; bubbleSort<ArrayList, double>(list); cout << "Bubble " << list << endl; mergeSort<ArrayList, double>(list); cout << "Merge " << list << endl; quickSort<ArrayList,double>(list); cout << "Quick " << list << endl; } #endif #if 0 #include <IOStream> #include <CStdLib> #include <CAssert> using namespace std; #include "..\\ArrayList\\ArrayList.h" #include "..\\ListBasic\\List.h" #include "Search.h" #include "Sort.h" void linkedList(); void arrayList(); void main() { linkedList(); arrayList(); } void linkedList() { cout << "LinkedList" << endl; { LinkedList list; list.add(9); list.add(7); list.add(5); list.add(3); list.add(1); for (LinkedList::Iterator pos = list.begin(); pos.hasNext(); pos.next()) { cout << "<" << *pos << "," << linarySearch<LinkedList, double>(*pos, list) << "> "; } /* for (int index = 0; index < list.size(); ++index) { cout << "<" << list[index] << "," << linarySearch<LinkedList,double>(list[index], list) << "> "; }*/ cout << "<0," << linarySearch<LinkedList,double>(0, list) << "> "; cout << "<6," << linarySearch<LinkedList, double>(6, list) << "> "; cout << "<10," << linarySearch<LinkedList, double>(10, list) << ">" << endl; selectSort<LinkedList,double>(list); for (LinkedList::Iterator pos = list.begin(); pos.hasNext(); pos.next()) { cout << "<" << *pos << "," << linarySearch<LinkedList, double>(*pos, list) << "> "; } /* for (int index = 0; index < list.size(); ++index) { cout << "<" << list[index] << "," << binarySearch<LinkedList,double>(list[index], list) << "> "; }*/ cout << "<0," << binarySearch<LinkedList, double>(0, list) << "> "; cout << "<6," << binarySearch<LinkedList, double>(6, list) << "> "; cout << "<10," << binarySearch<LinkedList, double>(10, list) << ">" << endl; } { LinkedList list; list.add(9); list.add(7); list.add(5); list.add(3); list.add(1); cout << "Select " << list; selectSort<LinkedList,double>(list); cout << " " << list << " "; selectSort<LinkedList, double>(list); cout << " " << list << endl; } { LinkedList list; list.add(9); list.add(7); list.add(5); list.add(3); list.add(1); cout << "Insert " << list; insertSort<LinkedList,double>(list); cout << " " << list << " "; insertSort<LinkedList, double>(list); cout << " " << list << endl; } { LinkedList list; list.add(9); list.add(7); list.add(5); list.add(3); list.add(1); cout << "Bubble " << list; bubbleSort<LinkedList, double>(list); cout << " " << list << " "; bubbleSort<LinkedList, double>(list); cout << " " << list << endl; } { LinkedList list; list.add(9); list.add(7); list.add(5); list.add(3); list.add(1); cout << "Merge " << list; mergeSort<LinkedList,double>(list); cout << " " << list << " "; mergeSort<LinkedList, double>(list); cout << " " << list << endl; } { LinkedList list; list.add(9); list.add(7); list.add(5); list.add(3); list.add(1); cout << "Quick " << list; quickSort<LinkedList,double>(list); cout << " " << list << " "; quickSort<LinkedList, double>(list); cout << " " << list << endl; } } void arrayList() { cout << "ArrayList" << endl; { ArrayList list; list.add(9); list.add(7); list.add(5); list.add(3); list.add(1); for (ArrayList::Iterator pos = list.begin(); pos.hasNext(); pos.next()) { cout << "<" << *pos << "," << linarySearch<ArrayList, double>(*pos, list) << "> "; } /* for (int index = 0; index < list.size(); ++index) { cout << "<" << list[index] << "," << linarySearch<ArrayList,double>(list[index], list) << "> "; }*/ cout << "<0," << linarySearch<ArrayList,double>(0, list) << "> "; cout << "<6," << linarySearch<ArrayList, double>(6, list) << "> "; cout << "<10," << linarySearch<ArrayList, double>(10, list) << ">" << endl; selectSort<ArrayList,double>(list); for (ArrayList::Iterator pos = list.begin(); pos.hasNext(); pos.next()) { cout << "<" << *pos << "," << linarySearch<ArrayList, double>(*pos, list) << "> "; } /* for (int index = 0; index < list.size(); ++index) { cout << "<" << list[index] << "," << binarySearch<ArrayList,double>(list[index], list) << "> "; }*/ cout << "<0," << binarySearch<ArrayList, double>(0, list) << "> "; cout << "<6," << binarySearch<ArrayList, double>(6, list) << "> "; cout << "<10," << binarySearch<ArrayList, double>(10, list) << ">" << endl; } { ArrayList list; list.add(9); list.add(7); list.add(5); list.add(3); list.add(1); cout << "Select " << list; selectSort<ArrayList,double>(list); cout << " " << list << " "; selectSort<ArrayList, double>(list); cout << " " << list << endl; } { ArrayList list; list.add(9); list.add(7); list.add(5); list.add(3); list.add(1); cout << "Insert " << list; insertSort<ArrayList,double>(list); cout << " " << list << " "; insertSort<ArrayList, double>(list); cout << " " << list << endl; } { ArrayList list; list.add(9); list.add(7); list.add(5); list.add(3); list.add(1); cout << "Bubble " << list; bubbleSort<ArrayList, double>(list); cout << " " << list << " "; bubbleSort<ArrayList, double>(list); cout << " " << list << endl; } { ArrayList list; list.add(9); list.add(7); list.add(5); list.add(3); list.add(1); cout << "Merge " << list; mergeSort<ArrayList,double>(list); cout << " " << list << " "; mergeSort<ArrayList, double>(list); cout << " " << list << endl; } { ArrayList list; list.add(9); list.add(7); list.add(5); list.add(3); list.add(1); cout << "Quick " << list; quickSort<ArrayList,double>(list); cout << " " << list << " "; quickSort<ArrayList, double>(list); cout << " " << list << endl; } } /* void linkedList() { cout << "LinkedList" << endl; { LinkedList list; list.add(9); list.add(7); list.add(5); list.add(3); list.add(1); for (int index = 0; index < list.size(); ++index) { cout << "<" << list[index] << "," << linarySearch<LinkedList,double>(list[index], list) << "> "; } cout << "<0," << linarySearch<LinkedList,double>(0, list) << "> "; cout << "<6," << linarySearch<LinkedList, double>(6, list) << "> "; cout << "<10," << linarySearch<LinkedList, double>(10, list) << ">" << endl; selectSort<LinkedList,double>(list); for (int index = 0; index < list.size(); ++index) { cout << "<" << list[index] << "," << binarySearch<LinkedList,double>(list[index], list) << "> "; } cout << "<0," << binarySearch<LinkedList, double>(0, list) << "> "; cout << "<6," << binarySearch<LinkedList, double>(6, list) << "> "; cout << "<10," << binarySearch<LinkedList, double>(10, list) << ">" << endl; } { LinkedList list; list.add(9); list.add(7); list.add(5); list.add(3); list.add(1); cout << "Select " << list; selectSort<LinkedList,double>(list); cout << " " << list << " "; selectSort<LinkedList, double>(list); cout << " " << list << endl; } { LinkedList list; list.add(9); list.add(7); list.add(5); list.add(3); list.add(1); cout << "Insert " << list; insertSort<LinkedList,double>(list); cout << " " << list << " "; insertSort<LinkedList, double>(list); cout << " " << list << endl; } { LinkedList list; list.add(9); list.add(7); list.add(5); list.add(3); list.add(1); cout << "Bubble " << list; bubbleSort<LinkedList, double>(list); cout << " " << list << " "; bubbleSort<LinkedList, double>(list); cout << " " << list << endl; } { LinkedList list; list.add(9); list.add(7); list.add(5); list.add(3); list.add(1); cout << "Merge " << list; mergeSort<LinkedList,double>(list); cout << " " << list << " "; mergeSort<LinkedList, double>(list); cout << " " << list << endl; } { LinkedList list; list.add(9); list.add(7); list.add(5); list.add(3); list.add(1); cout << "Quick " << list; quickSort<LinkedList,double>(list); cout << " " << list << " "; quickSort<LinkedList, double>(list); cout << " " << list << endl; } } void arrayList() { cout << "ArrayList" << endl; { ArrayList list; list.add(9); list.add(7); list.add(5); list.add(3); list.add(1); for (int index = 0; index < list.size(); ++index) { cout << "<" << list[index] << "," << linarySearch<ArrayList,double>(list[index], list) << "> "; } cout << "<0," << linarySearch<ArrayList,double>(0, list) << "> "; cout << "<6," << linarySearch<ArrayList, double>(6, list) << "> "; cout << "<10," << linarySearch<ArrayList, double>(10, list) << ">" << endl; selectSort<ArrayList,double>(list); for (int index = 0; index < list.size(); ++index) { cout << "<" << list[index] << "," << binarySearch<ArrayList,double>(list[index], list) << "> "; } cout << "<0," << binarySearch<ArrayList, double>(0, list) << "> "; cout << "<6," << binarySearch<ArrayList, double>(6, list) << "> "; cout << "<10," << binarySearch<ArrayList, double>(10, list) << ">" << endl; } { ArrayList list; list.add(9); list.add(7); list.add(5); list.add(3); list.add(1); cout << "Select " << list; selectSort<ArrayList,double>(list); cout << " " << list << " "; selectSort<ArrayList, double>(list); cout << " " << list << endl; } { ArrayList list; list.add(9); list.add(7); list.add(5); list.add(3); list.add(1); cout << "Insert " << list; insertSort<ArrayList,double>(list); cout << " " << list << " "; insertSort<ArrayList, double>(list); cout << " " << list << endl; } { ArrayList list; list.add(9); list.add(7); list.add(5); list.add(3); list.add(1); cout << "Bubble " << list; bubbleSort<ArrayList, double>(list); cout << " " << list << " "; bubbleSort<ArrayList, double>(list); cout << " " << list << endl; } { ArrayList list; list.add(9); list.add(7); list.add(5); list.add(3); list.add(1); cout << "Merge " << list; mergeSort<ArrayList,double>(list); cout << " " << list << " "; mergeSort<ArrayList, double>(list); cout << " " << list << endl; } { ArrayList list; list.add(9); list.add(7); list.add(5); list.add(3); list.add(1); cout << "Quick " << list; quickSort<ArrayList,double>(list); cout << " " << list << " "; quickSort<ArrayList, double>(list); cout << " " << list << endl; } } */ #endif
true
618eea2ffe1ecebb2c957ab2d5ac4ea4dc6c010d
C++
wangzhezhe/Gorilla
/blockManager/rawmemobj/rawmemobj.h
UTF-8
1,403
2.609375
3
[]
no_license
#ifndef RAWMEMOBJ_H #define RAWMEMOBJ_H #include <blockManager/blockManager.h> #include <iostream> namespace GORILLA { struct RawMemObj : public DataBlockInterface { RawMemObj(const char* blockid) : DataBlockInterface(blockid){ // std::cout << "RawMemObj is initialised" << std::endl; }; BlockSummary getData(void*& dataContainer); // put data into coresponding data structure for specific implementation int putData(void* dataSourcePtr); int eraseData(); BlockSummary getDataSubregion(size_t dims, std::array<int, 3> subregionlb, std::array<int, 3> subregionub, void*& dataContainer); void* getrawMemPtr() { return this->m_rawMemPtr; }; int putArray(ArraySummary& as, void* dataSourcePtr) { throw std::runtime_error("unsupported yet for RawMemObj"); } int getArray(ArraySummary& as, void*& dataContainer) { throw std::runtime_error("unsupported yet for RawMemObj"); } // we use the new delete instead of malloc and free // since we want it more general // it can not only contain the void array // but can also conatain the particular class // if there is not constructor // we just use the operator new // or maybe use template here to represnet different type in future void* m_rawMemPtr = NULL; virtual ~RawMemObj() { if (m_rawMemPtr != NULL) { ::operator delete(m_rawMemPtr); } }; }; } #endif
true
a733867299a26a1cb4024fe45c6beb86b846a141
C++
tnordenmark/UU
/00.Kompendium_C++/Exempel/v3.0/kap6ex/power3.cc
UTF-8
437
3.453125
3
[]
no_license
// Filnamn: .../power3.cc #include <iostream> using namespace std; double power( double x, int n=2 ); // default here!! int main() { cout << "Call 1 : " << power( 3.5 , 3 ) << endl; cout << "Call 2 : " << power( 3.5 , 2 ) << endl; cout << "Call 3 : " << power( 3.5 ) << endl; return 0; } double power( double x, int n) // no default here !! { double p = 1.0; for (int i=1; i<=n; i++) { p *=x; } return p; }
true
f17d1fa8e981f909d47f1d1b74c75592ada6f72a
C++
whigg/point-and-surface-registration
/research-computing-with-cpp-demo/Code/SurfaceBasedRegistration/pointbasedregistration.tpp
UTF-8
5,738
3
3
[]
no_license
/** * @brief Implementation of the templated class PointBasedRegistration. Note that this tenmplate * file is included in the header file. * * @author Luis Carlos Garcia-Peraza Herrera (luis.herrera.14@ucl.ac.uk). * @date 14 Mar 2015. */ // My includes // #include "pointbasedregistration.h" #include <iostream> #include <Eigen/SVD> #include <cmath> // My includes #include "exception.h" template <typename PointFixed, typename PointMoving, typename Scalar> PointBasedRegistration<PointFixed, PointMoving, Scalar>::PointBasedRegistration() { } template <typename PointFixed, typename PointMoving, typename Scalar> PointBasedRegistration<PointFixed, PointMoving, Scalar>::~PointBasedRegistration() { } template <typename PointFixed, typename PointMoving, typename Scalar> void PointBasedRegistration<PointFixed, PointMoving, Scalar>::setFixedCloud(const PointCloud<PointFixed> &cloud) { m_fixed = cloud; } template <typename PointFixed, typename PointMoving, typename Scalar> void PointBasedRegistration<PointFixed, PointMoving, Scalar>::setMovingCloud(const PointCloud<PointMoving> &cloud) { m_moving = cloud; } template <typename PointFixed, typename PointMoving, typename Scalar> void PointBasedRegistration<PointFixed, PointMoving, Scalar>::align() { // Sanity check paranoia if (m_fixed.empty()) throw FixedSetIsEmpty(); if (m_moving.empty()) throw MovingSetIsEmpty(); if (m_fixed.size() < (*(m_fixed.begin())).size()) throw NotEnoughDataInFixedSet(); if (m_moving.size() < (*(m_moving.begin())).size()) throw NotEnoughDataInMovingSet(); if (m_fixed.size() != m_moving.size()) throw UnequalNumberOfPoints(); // Calculate centroid (p) of the source points typename PointCloud<PointFixed>::iterator itFixed = m_fixed.begin(); PointFixed p(*itFixed); p /= m_fixed.size(); itFixed++; while (itFixed != m_fixed.end()) { p += (*itFixed) / m_fixed.size(); ++itFixed; } // Calculate the centroid (p_) of the target points typename PointCloud<PointMoving>::iterator itMov = m_moving.begin(); PointMoving p_(*itMov); p_ /= m_moving.size(); itMov++; while (itMov != m_moving.end()) { p_ += (*itMov) / m_moving.size(); ++itMov; } // Calculate the [source points minus their centroid (p)] => qi PointCloud<PointFixed> qi(m_fixed); for (typename PointCloud<PointFixed>::iterator it = qi.begin(); it != qi.end(); ++it) { (*it) -= p; } // Calculate the [target points minus their centroid (p_)] => qi_ PointCloud<PointFixed> qi_(m_moving); for (typename PointCloud<PointMoving>::iterator it = qi_.begin(); it != qi_.end(); ++it) { (*it) -= p_; } // Calculate H Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> H = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>::Zero(p.size(), p.size()); typename PointCloud<PointFixed>::iterator it_qi = qi.begin(); typename PointCloud<PointMoving>::iterator it_qi_ = qi_.begin(); while (it_qi != qi.end() && it_qi_ != qi_.end()) { H += (*it_qi_).matrix() * (*it_qi).matrix().transpose(); it_qi++; it_qi_++; } // Calculate X Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> X = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>::Zero(p.size(), p.size()); Eigen::JacobiSVD<Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> > svdOfH(H, Eigen::ComputeFullU | Eigen::ComputeFullV); X = svdOfH.matrixV() * svdOfH.matrixU().transpose(); // Calculate R Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> R = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>::Zero(p.size(), p.size()); if (X.determinant() > 0) { // If determinan is +1, used > 0 to avoid numerical problems R = X; } else { // If this code was reached then we are mathematically sure that the determinant is -1 // If the dimension is 3 and H has at least a singular value equal to zero, then we can solve it by doing X' = V' * Ut, V' = [ v1, v2, -v3 ] if (p.size() == 3 && svdOfH.singularValues().nonZeros() < 3) { Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> V_ = svdOfH.matrixV(); V_.row(2) *= -1; R = V_ * svdOfH.matrixU().transpose(); } else { throw AlgorithmFailed(); } } // Calculate T Eigen::Matrix<Scalar, Eigen::Dynamic, 1> T; T = p - R * p_; // Build homogeneous matrix for the N-dimensional case // Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> hom = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>::Zero(p.size() + 1, p.size() + 1); m_hom.resize(p.size() + 1, p.size() + 1); m_hom.setZero(); m_hom.col(p.size()).setOnes(); m_hom.block(0, 0, p.size(), p.size()) = R; m_hom.block(0, p.size(), p.size(), 1) = T; // Calculate fiducial registration error (RMS error) m_fre = 0; itMov = m_moving.begin(); itFixed = m_fixed.begin(); // Eigen::Matrix<Scalar, Eigen::Dynamic, 1> pHom; // Eigen::Matrix<Scalar, Eigen::Dynamic, 1> p_Hom; // pHom.resize(p.size() + 1); // p_Hom.resize(p_.size() + 1); // pHom(p.size()) = 1; // p_Hom(p_.size()) = 1; while (itMov != m_moving.end() && itFixed != m_fixed.end()) { // pHom.block(0, 0, p.size(), 1) = (*itFixed); // p_Hom.block(0, 0, p_.size(), 1) = (*itMov); // m_fre += ((pHom - m_hom * p_Hom).array().pow(2) / m_moving.size()).sum(); m_fre += (((*itFixed).homogeneous() - m_hom * (*itMov).homogeneous()).array().pow(2) / m_moving.size()).sum(); itMov++; itFixed++; } m_fre = sqrt(m_fre); } template <typename PointFixed, typename PointMoving, typename Scalar> Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> PointBasedRegistration<PointFixed, PointMoving, Scalar>::getHomogeneousMatrix() const { return m_hom; } template <typename PointFixed, typename PointMoving, typename Scalar> Scalar PointBasedRegistration<PointFixed, PointMoving, Scalar>::getFiducialRegistrationError() const { return m_fre; }
true
7ff77b75483bbe5d89fdd1e67b79faad365d7a8b
C++
charlenemariscal/UVA_Judge
/11764 Jumping Mario.cpp
UTF-8
619
2.9375
3
[]
no_license
#include <iostream> using namespace std; int main(){ int t,n, low, high; cin>> t; for (int i =1; i<=t; i++){ cin >>n; int height[n]; for (int j=0;j< n; j++){ cin >>height[j]; } high =0; low = 0; for (int j=0;j< n-1; j++){ if (height[j]<height[j+1]){ high +=1; low =low; } else if (height[j+1]<height[j]){ low +=1; high = high; } else if(height[j]==height[j+1]){ high = high; low = low; } else{ high =0; low =0; } } cout<<"Case "<<i<<": "<<high<<" "<<low<<endl; } return 0; }
true
26f637036b9965cf33f80d84bfbd28d5bdf982c7
C++
Jerry-Terrasse/Programming
/比赛/清北学堂/入学测试0715/2018715/2018715/src/泰安二中袁傲慕飞/count.cpp
UTF-8
2,854
2.515625
3
[]
no_license
#include<iostream> #include<cstdio> #include<cstring> using namespace std; char ru[3][3], temp[3]; bool peo[27], grp[27][27]; int ans1, ans2; int main() { freopen("count.in", "r", stdin); freopen("count.out", "w", stdout); for(int i = 0; i <= 2; i++) { cin>>ru[i]; } for(int i = 0; i <= 2; i++) { int tp = 0; memset(temp, 0, sizeof(temp)); for(int j = 0; j <= 2; j++) { bool flag1 = 0; for(int t = 0; t <= 2; t++) { if(ru[i][j] == temp[t]) { flag1 = 1; } } if(flag1 == 0) { temp[tp] = ru[i][j]; tp++; } } if(tp == 1) { if(peo[temp[0] - 'A' + 1] == 0) { peo[temp[0] - 'A' + 1] = 1; ans1++; } } if(tp == 2) { if(grp[temp[1] - 'A' + 1][temp[0] - 'A' + 1] == 0) { grp[temp[0] - 'A' + 1][temp[1] - 'A' + 1] = 1; grp[temp[1] - 'A' + 1][temp[0] - 'A' + 1] = 1; ans2++; } } } for(int i = 0; i <= 2; i++) { int tp = 0; memset(temp, 0, sizeof(temp)); for(int j = 0; j <= 2; j++) { bool flag1 = 0; for(int t = 0; t <= 2; t++) { if(ru[j][i] == temp[t]) { flag1 = 1; } } if(flag1 == 0) { temp[tp] = ru[j][i]; tp++; } } if(tp == 1) { if(peo[temp[0] - 'A' + 1] == 0) { peo[temp[0] - 'A' + 1] = 1; ans1++; } } if(tp == 2) { if(grp[temp[1] - 'A' + 1][temp[0] - 'A' + 1] == 0) { grp[temp[0] - 'A' + 1][temp[1] - 'A' + 1] = 1; grp[temp[1] - 'A' + 1][temp[0] - 'A' + 1] = 1; ans2++; } } } int tp = 0; memset(temp, 0, sizeof(temp)); for(int j = 0; j <= 2; j++) { bool flag1 = 0; for(int t = 0; t <= 2; t++) { if(ru[j][j] == temp[t]) { flag1 = 1; } } if(flag1 == 0) { temp[tp] = ru[j][j]; tp++; } } if(tp == 1) { if(peo[temp[0] - 'A' + 1] == 0) { peo[temp[0] - 'A' + 1] = 1; ans1++; } } if(tp == 2) { if(grp[temp[1] - 'A' + 1][temp[0] - 'A' + 1] == 0) { grp[temp[0] - 'A' + 1][temp[1] - 'A' + 1] = 1; grp[temp[1] - 'A' + 1][temp[0] - 'A' + 1] = 1; ans2++; } } tp = 0; memset(temp, 0, sizeof(temp)); for(int j = 0; j <= 2; j++) { bool flag1 = 0; for(int t = 0; t <= 2; t++) { if(ru[j][2 - j] == temp[t]) { flag1 = 1; } } if(flag1 == 0) { temp[tp] = ru[j][2 - j]; tp++; } } if(tp == 1) { if(peo[temp[0] - 'A' + 1] == 0) { peo[temp[0] - 'A' + 1] = 1; ans1++; } } if(tp == 2) { if(grp[temp[1] - 'A' + 1][temp[0] - 'A' + 1] == 0) { grp[temp[0] - 'A' + 1][temp[1] - 'A' + 1] = 1; grp[temp[1] - 'A' + 1][temp[0] - 'A' + 1] = 1; ans2++; } } cout<<ans1<<endl<<ans2; return 0; }
true
b19f5b7c6de1e6aaef5a114154e211098f3243e6
C++
dementrock/acm
/poj/Archives/1679/7091111_WA.cpp
UTF-8
2,846
2.84375
3
[]
no_license
#include<stdio.h> #include<algorithm> #include<math.h> using namespace std; const int MAXV=105; const int MAXE=5465; const int INF=0x7fffffff; int set[MAXV]; int rank[MAXV]; int num;//记录最小生成树边的个数 int st,ed; typedef struct Edge { int st; int ed; int distance; }Edge; Edge edge[MAXE]; Edge edge1[MAXE]; /*下面三个函数是求并查集的函数!*/ //第一函数是初始化 void Make_Set(int x) { set[x]=x; rank[x]=0; } //返回包含x的集合中的一个代表元素 int Find_Set(int x) { if(x!=set[x]) set[x]=Find_Set(set[x]); return set[x]; } //实现树与树的合并 void Union(int x,int y) { x=Find_Set(x); y=Find_Set(y); if(rank[x]>rank[y]) set[y]=x; else { set[x]=y; if(rank[x]==rank[y]) rank[y]++; } } bool cmp(Edge a,Edge b) { return a.distance<b.distance; } /*关键函数-Kruskal算法的实现!*/ int Kruskal(int v,int e) { int i; int sum=0; for(i=1;i<=v;i++) Make_Set(i);//每个点构成一个树也即一个集合 sort(edge+1,edge+e+1,cmp);//将边按照权值非降序排序 for(i=1;i<=e;i++) if(Find_Set(edge[i].st)!=Find_Set(edge[i].ed)) {//如果是安全边就加sum中去 sum+=edge[i].distance; //并将包含这两棵树的集合合并 Union(edge[i].st,edge[i].ed); edge1[++num]=edge[i]; } return sum; } int Kruskal1(int v,int e) { int i; int sum=0; for(i=1;i<=v;i++) Make_Set(i);//每个点构成一个树也即一个集合 sort(edge+1,edge+e+1,cmp);//将边按照权值非降序排序 for(i=1;i<=e;i++) if(Find_Set(edge[i].st)!=Find_Set(edge[i].ed)) {//如果是安全边就加sum中去 if(edge[i].st==st&&edge[i].ed==ed) {continue;} if(edge[i].st==ed&&edge[i].ed==st) {continue;} sum+=edge[i].distance; //并将包含这两棵树的集合合并 Union(edge[i].st,edge[i].ed); } return sum; } bool Judge(int V) { int i; for(i=1;i<=V-1;i++) if(Find_Set(i)!=Find_Set(i+1)) return false; return true; } int main() { int i,V,E,T,min,sum; scanf("%d",&T); while(T--) { scanf("%d%d",&V,&E); for(i=1;i<=E;i++) scanf("%d%d%d",&edge[i].st,&edge[i].ed,&edge[i].distance); num=0; min=INF; sum=Kruskal(V,E); //printf("num=%d\n",num); for(i=1;i<=num;i++) { st=edge1[i].st; ed=edge1[i].ed; int temp=Kruskal1(V,E); if(min>temp&&Judge(V))//一定要加一个判断!看看是不是所有的点都联通! min=temp; if(Judge(V))printf("%d\n",temp); } printf("%d %d\n",min,sum); if(min==sum) printf("Not Unique!\n"); else printf("%d\n",sum); } return 0; }
true
120e0107d03f51ff2ec7bff3c2e6a7513f69e688
C++
wangsiyao1009/BIDE
/BIDE.cpp
UTF-8
2,032
2.84375
3
[]
no_license
#include "BIDE.h" size_t hashCode(const Sequence &sequence) { size_t h = 17; for (const auto &str : sequence.sequence) { for (const auto &c : str) { h = 37 * h + c; } } return h; } BIDE::BIDE(Database &database) : database(database), frequentOneItemsCount(database.frequentOneCount()), maxLength(database.getMaxLength()), minSupport(database.getMinSupport()), result(10, hashCode) { } /** * 从currentSequence开始深度优先搜索 */ void BIDE::dfs(IntSequence &currentSequence, const std::unordered_set<int> &supports) { if (currentSequence.size() == maxLength) { if (!database.bideCloseCheck(currentSequence, supports)) { return; } result[database.stringSequence(currentSequence)] = supports.size(); return; } std::unordered_map<int, std::unordered_set<int> > map1 = database.nextInsertItems(currentSequence, supports); for (auto &item : map1) { currentSequence.pushBackItem(item.first); if (database.isBackPatching(currentSequence, item.second)) { currentSequence.erase(currentSequence.size() - 1); continue; } dfs(currentSequence, item.second); currentSequence.erase(currentSequence.size() - 1); } if (!database.bideCloseCheck(currentSequence, supports)) { return; } result[database.stringSequence(currentSequence)] = supports.size(); } std::unordered_map<Sequence, size_t, size_t (*)(const Sequence &)> &BIDE::run() { for (int i = 0; i < database.frequentOneCount(); ++i) { currentSequence.pushBackItem(i); std::unordered_set<int> supports = database.intSequenceSupport(currentSequence); if (database.isBackPatching(currentSequence, supports)) { currentSequence.erase(0); continue; } dfs(currentSequence, supports); currentSequence.erase(0); } return this->result; }
true
a6f32394a9722cf9be2f1fc2b95034cc43ae3329
C++
clovervnd/Learning
/C++_LEARNING/access.cpp
UTF-8
553
3.75
4
[]
no_license
#include <iostream> // access modifier using namespace std; struct student{ private: int id; char *name; float percentage; public: void Show(); void SetInfo (int _id, char* _name, float _percentage); }; void student::Show(){ cout<<"아이디: " <<id<<endl; cout<<"이름: " <<name<<endl; cout<<"백분율: " <<percentage<<endl; } void student::SetInfo(int _id, char* _name, float _percentage){ id = _id; name = _name; percentage = _percentage; } int main (){ student s; s.SetInfo(1, "김철수", 90.5); s.Show(); return 0; }
true
1dbc423c1e3fd26b2b42c060b79e021fadbb1343
C++
Benner727/RPG-Graphics
/Alpha/ItemBonusDefinition.h
UTF-8
954
3.1875
3
[]
no_license
#ifndef ITEMBONUSDEFINITION_H #define ITEMBONUSDEFINITION_H class ItemBonusDefinition { public: ItemBonusDefinition() {}; ItemBonusDefinition(int _id, int _meleeatt, int _magicatt, int _rangeatt, int _meleedef, int _magicdef, int _rangedef, int _str, int _prayer) { id = _id; bonus[0] = _meleeatt; bonus[1] = _magicatt; bonus[2] = _rangeatt; bonus[3] = _meleedef; bonus[4] = _magicdef; bonus[5] = _rangedef; bonus[6] = _str; bonus[7] = _prayer; }; ~ItemBonusDefinition() {}; private: int id; int bonus[8]; public: int getId() const { return id; } int getMeleeAtt() const { return bonus[0]; } int getMagicAtt() const { return bonus[1]; } int getRangeAtt() const { return bonus[2]; } int getMeleeDef() const { return bonus[3]; } int getMagicDef() const { return bonus[4]; } int getRangeDef() const { return bonus[5]; } int getStrength() const { return bonus[6]; } int getPrayer() const { return bonus[7]; } }; #endif
true
a1a23674b7a406ba0db4d2c789355ba3a187a108
C++
Freebee2day/myTextBox
/cmake_modules/myBase.cpp
UTF-8
500
2.640625
3
[]
no_license
// // Created by 16262 on 4/1/2021. // #include "myBase.h" myBase::myBase(char s, float xPos){ font.loadFromFile("../cmake_modules/OpenSans-Bold.ttf"); msg.setFont(font); msg.setFillColor(sf::Color::White); msg.setCharacterSize(50); msg.setPosition(xPos,300); msg.setString(s); } void myBase::draw(sf::RenderTarget &target, sf::RenderStates states) const { target.draw(msg,states); } float myBase::getXpos()const{ return msg.getPosition().x; }
true
e2791e5451132319347f8361144fa67d2a4dc5e9
C++
avast/retdec
/tests/serdes/class_tests.cpp
UTF-8
1,995
2.703125
3
[ "MIT", "Zlib", "JSON", "LicenseRef-scancode-unknown-license-reference", "MPL-2.0", "BSD-3-Clause", "GPL-2.0-only", "NCSA", "WTFPL", "BSL-1.0", "LicenseRef-scancode-proprietary-license", "Apache-2.0" ]
permissive
/** * @file tests/serdes/classe_tests.cpp * @brief Tests for the class module. * @copyright (c) 2019 Avast Software, licensed under the MIT license */ #include <gtest/gtest.h> #include <rapidjson/error/en.h> #include <rapidjson/document.h> #include <rapidjson/prettywriter.h> #include <rapidjson/stringbuffer.h> #include "retdec/common/class.h" #include "retdec/serdes/class.h" using namespace ::testing; namespace retdec { namespace serdes { namespace tests { class ClassTests : public Test { protected: common::Class cl; }; TEST_F(ClassTests, ClassIsParsedCorrectlyFromJSONWhenClassIsFullySpecified) { std::string input(R"({ "name" : "A", "constructors" : [ "Actor" ], "destructors" : [ "Adtor" ], "methods" : [ "Amethod" ], "superClasses" : [ "Asuper" ], "virtualMethods" : [ "Avirtual" ], "virtualTables" : [ "Avtable" ] })"); rapidjson::Document root; rapidjson::ParseResult ok = root.Parse(input); ASSERT_TRUE(ok); deserialize(root, cl); EXPECT_EQ("A", cl.getName()); EXPECT_EQ(std::set<std::string>({"Actor"}), cl.constructors); EXPECT_EQ(std::set<std::string>({"Adtor"}), cl.destructors); EXPECT_EQ(std::set<std::string>({"Amethod"}), cl.methods); EXPECT_EQ(std::vector<std::string>({"Asuper"}), cl.getSuperClasses()); EXPECT_EQ(std::set<std::string>({"Avirtual"}), cl.virtualMethods); EXPECT_EQ(std::set<std::string>({"Avtable"}), cl.virtualTables); } TEST_F(ClassTests, ClassIsParsedCorrectlyFromJSONWhenClassHasOnlyNameSpecified) { std::string input(R"({ "name" : "A" })"); rapidjson::Document root; rapidjson::ParseResult ok = root.Parse(input); ASSERT_TRUE(ok); deserialize(root, cl); EXPECT_EQ("A", cl.getName()); EXPECT_TRUE(cl.constructors.empty()); EXPECT_TRUE(cl.destructors.empty()); EXPECT_TRUE(cl.methods.empty()); EXPECT_TRUE(cl.getSuperClasses().empty()); EXPECT_TRUE(cl.virtualMethods.empty()); EXPECT_TRUE(cl.virtualTables.empty()); } } // namespace tests } // namespace serdes } // namespace retdec
true
bd3582297ee85a9b6390d571dcf8e7d6648bbd31
C++
LayerXcom/libSTARK
/libstark/src/common/Utils/specsPrint.cpp
UTF-8
1,303
3.09375
3
[ "MIT" ]
permissive
#include "specsPrint.hpp" #include <iostream> #include <iomanip> #include<algorithm> namespace libstark{ using std::vector; using std::string; using std::pair; using std::max; specsPrinter::specsPrinter(const string title):title_(title),data_(0){}; void specsPrinter::addLine(const string name, const string val){ data_.push_back(pair<string,string>(name,val)); } void specsPrinter::print()const{ using std::cout; using std::endl; using std::setw; using std::setfill; int namesLen=0, valsLen = 0; for (const auto& p : data_){ namesLen = max(namesLen,int(p.first.length())); valsLen = max(valsLen,int(p.second.length())); } const int len = max(int(title_.length()), namesLen + valsLen + 3); valsLen = len - namesLen - 3; cout<<setfill('-')<<setw(4+len)<<"-"<<setfill(' ')<<endl; cout<<"| "<<std::left<<setw(len)<<title_<<" |"<<std::endl; cout<<setfill('-')<<setw(4+len)<<"-"<<setfill(' ')<<endl; for(const auto& p : data_){ cout<<"| "<<setw(namesLen)<<p.first<<" = "<<setw(valsLen)<<p.second<<" |"<<std::endl; } cout<<setfill('-')<<setw(4+len)<<"-"<<setfill(' ')<<endl; } } // namespace libstark
true
2dfe927e8b76ce74f70946999212da3b16245d08
C++
Blue-Xin/CPP
/CPP类/重载类型转换运算符.cpp
UTF-8
496
3.484375
3
[]
no_license
#include<iostream> using namespace std; class change { private: double real; double imag; public: change(double r,double i):real(r),imag(i) // 初始化列表 { } operator int () //不需要写返回值类型 将double类型的转换为int类型 { return real; } }; int main() { change c(1.2,1.3); cout << (int)c << endl; int a=2+c; //因为 c 经过了转换所以 a=2+c 是成立的 cout << a << endl; }
true
5f6cc8b38750b7768e264dff5dd455492112716e
C++
ye-luo/openmp-target
/tests/target_task/omp-task-bug.cpp
UTF-8
2,635
3.078125
3
[ "BSD-3-Clause" ]
permissive
#include <iostream> #include <memory> #include <numeric> #include <vector> #ifdef _OPENMP #include <omp.h> #else int omp_get_thread_num() { return 0; } int omp_get_num_threads() { return 1; } int omp_get_max_threads() { return 1; } #endif template<typename T> struct MyProblem { int M = 16; int N = 16; int K = 32; int Size = 0; int IP = 0; T* V = nullptr; T* W = nullptr; explicit MyProblem(int np) : Size(M * N * K / np) { M = M / np; size_t bytes = Size * sizeof(T); auto* v_ptr = (T*)aligned_alloc(64, bytes); auto* w_ptr = (T*)aligned_alloc(64, bytes); #pragma omp target enter data map(alloc : v_ptr [0:Size], w_ptr [0:Size]) V = v_ptr; W = w_ptr; #pragma omp target enter data map(to : this [0:1]) } ~MyProblem() { auto* v_ptr = V; auto* w_ptr = W; #pragma omp target exit data map(delete : this [0:1]) #pragma omp target exit data map(delete : v_ptr[:Size], w_ptr[:Size]) free(W); free(V); } void setV(int ip) { IP = ip; std::iota(V, V + Size, T(ip * Size)); } void update() { // v_ptr and w_ptr are shared as a task is created auto* v_ptr = V; auto* w_ptr = W; #pragma omp target teams distribute collapse(2) map(always, to : v_ptr[:Size]) nowait depend(out : w_ptr[:Size]) for (int i = 0; i < M; ++i) for (int j = 0; j < N; ++j) { #pragma omp parallel for for (int k = 0; k < K; ++k) { int ijk = i * N * K + j * K + k; w_ptr[ijk] = 0.1f + v_ptr[ijk]; } } #pragma omp target update nowait depend(inout : w_ptr[:Size]) from(w_ptr[:Size]) #if defined(INPLACE_TASKWAIT) #pragma omp taskwait #endif } void write() const { std::cout << "result: " << IP << std::endl; std::cout << "V[" << 0 << "] = " << V[0] << " " << W[0] << std::endl; std::cout << "V[" << Size / 2 << "] = " << V[Size / 2] << " " << W[Size / 2] << std::endl; std::cout << "V[" << Size - 1 << "] = " << V[Size - 1] << " " << W[Size - 1] << std::endl; } }; int main(int argc, char** argv) { const int np = omp_get_max_threads(); std::vector<std::unique_ptr<MyProblem<float>>> problems(np * 4); #pragma omp parallel { int ip = omp_get_thread_num(); for (int iw = 0; iw < 4; iw++) { int I = ip * 4 + iw; problems[I] = std::make_unique<MyProblem<float>>(np * 4); problems[I]->setV(I); } for (int iw = 0; iw < 4; iw++) { int I = ip * 4 + iw; problems[I]->update(); } } /* for(int ip=0; ip<np*4; ++ip) { problems[ip]->write(); } */ }
true
da375bced7f6d110a3fb49cda7a340b48949524c
C++
ajl2612/GarageDoorSimulator
/GarageDoorSimulator/thread.h
UTF-8
1,829
3.3125
3
[]
no_license
#ifndef THREAD_H #define THREAD_H #include <string> #include <pthread.h> #include "mutex.h" /** * pthread wrapper classes. * Provides a set of wrapper classes around various pthread constructs. * These allow proper object oriented programming when working with pthreads. */ namespace PThreads { /** * Abstract thread class. * Wrapper around a pthread_t primitive which hides away the gory details of * creating a thread. Subclasses need to override the run method. * The thread will not begin execution until the start method is called. */ class Thread { public: /** * Begin thread execution. * Create the pthread primitive and make it begin execution. */ virtual void start(); /** * Calling thread will block until this thread exits. * When called from a particular thread, this method will force the * calling thread to block until the thread that this object * encapsulates completes its execution and calls pthread_exit. */ virtual void join(); /** * Retrieve the thread's pthread handle. */ pthread_t getHandle(); protected: /** * Run the thread. * Pure virtual method which is where the thread's work should * be performed. * @warning Must be implemented in a subclass! */ virtual void run() = 0; /** * A Mutex for the thread instance. * This mutex is provided for protecting critical sections within the * thread itself from being modified by other threads.. */ PThreads::Mutex _mutex; private: static void* _run( void* ); pthread_t _handle; }; } #endif
true
e22fdf27ecee58fe883e6d48dcbdd3b300f775a6
C++
LeeNJU/LeetCode
/LeetCode/convertToTitle.cpp
GB18030
357
3.375
3
[]
no_license
#include <string> #include <algorithm> std::string convertToTitle(int n)//ʮת26 Ҫת { int Base = 26; std::string result = ""; while (n) { if (n % Base) { result += n % Base - 1 + 'A'; n /= Base; } else { result += 'Z'; n = n / Base - 1; } } reverse(result.begin(), result.end()); return result; }
true
949139fdfcdb0d5e300ae46a3375199546e9fa33
C++
frobro98/School-Projects
/RAD Engine/Game/RAD/Visualizer.cpp
UTF-8
2,200
2.84375
3
[]
no_license
#include "Visualizer.h" #include "AssetManager.h" #include "Azul.h" Visualizer& Visualizer::instance() { static Visualizer vis; return vis; } void Visualizer::initialize() { instance().unitBox = new GraphicsObjectWireFrame(AssetManager::retrieveModel("box")); instance().unitSphere = new GraphicsObjectWireFrame(AssetManager::retrieveModel("sphere")); } void Visualizer::showSphere(const Vect& center, const float& radius, const Vect& color) { VisualData* data; if(!instance().recyclying.empty()) { data = instance().recyclying.top(); instance().recyclying.pop(); } else { data = new VisualData(); } Matrix scale(SCALE, radius, radius, radius); Matrix trans(TRANS, center[x], center[y], center[z]); Matrix world = scale * trans; data->color = color; data->visModel = instance().unitSphere; data->world = world; instance().willRender.push(data); } void Visualizer::showAABB(const Vect& min, const Vect& max, const Vect& color) { VisualData* data; if(!instance().recyclying.empty()) { data = instance().recyclying.top(); instance().recyclying.pop(); } else { data = new VisualData; } Matrix scale(SCALE, max - min); Matrix trans(TRANS, (max+min)*.5); Matrix world = scale * trans; data->color = color; data->visModel = instance().unitBox; data->world = world; instance().willRender.push(data); } void Visualizer::showMarker(const Vect& pos, const Vect& color, const float& radius) { VisualData* data; if(!instance().recyclying.empty()) { data = instance().recyclying.top(); instance().recyclying.pop(); } else { data = new VisualData; } Matrix scale(SCALE, radius, radius, radius); Matrix trans(TRANS, pos); data->world = scale * trans; data->visModel = instance().unitSphere; data->color = color; instance().willRender.push(data); } void Visualizer::recycleData(VisualData* const rData) { recyclying.push(rData); } void Visualizer::render() { while(!instance().willRender.empty()) { VisualData* renderData = instance().willRender.front(); renderData->visModel->color = renderData->color; renderData->visModel->setWorld(renderData->world); renderData->visModel->Render(); instance().willRender.pop(); } }
true
bb4a19eced3d963bdf9d8dde17311af2e17dd5d2
C++
Yuessiah/Destiny_Record
/UVa_Online_Judge/908_Re-connecting_Computer_Sites.cpp
UTF-8
1,176
2.96875
3
[]
no_license
#include<cstdio> #include<cstring> #include<queue> #include<algorithm> using namespace std; const int maxn = 1e4 + 10, INF = 0x3f3f3f3f; struct node { int n, w; bool operator<(const node &lhs) const { return w > lhs.w; // min heap } }; int N, K, M; bool vis[maxn]; int main() { bool nl = false; while(~scanf("%d", &N)) { if(nl) putchar('\n'); else nl = true; vector<node> E[maxn]; int sum = 0, u, v, w; for(int i = 0; i < N-1; i++) { scanf("%d%d%d", &u, &v, &w); sum += w; } printf("%d\n", sum); scanf("%d", &K); for(int i = 0; i < K; i++) { scanf("%d%d%d", &u, &v, &w); E[u].push_back((node){v, w}); E[v].push_back((node){u, w}); } scanf("%d", &M); for(int i = 0; i < M; i++) { scanf("%d%d%d", &u, &v, &w); E[u].push_back((node){v, w}); E[v].push_back((node){u, w}); } /* minimun spanning tree */ memset(vis, false, sizeof(vis)); sum = 0; priority_queue<node> Q; Q.push((node){1, 0}); // root while(!Q.empty()) { node u = Q.top(); Q.pop(); if(!vis[u.n]) { sum += u.w; for(auto v: E[u.n]) if(!vis[v.n]) Q.push(v); } vis[u.n] = true; } printf("%d\n", sum); } return 0; }
true
4078b13f3dd47349f2041dcae8cc34cf382ea57a
C++
ericlin1001/offlineJudge
/hws/problem2/16308110/main.cpp
UTF-8
501
3.0625
3
[]
no_license
// 19.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include<iostream> #include<cmath> #include<iomanip> using namespace std; int main(int argc, char* argv[]) { int a,b,c,d; float x,y; cout<<"Please input 4 integer:"; cin>>a>>b>>c>>d; x=(a+b+c+d)/4.0; y=sqrt((a-x)*(a-x)+(b-x)*(b-x)+(c-x)*(c-x)+(d-x)*(d-x))/2.0; cout<<fixed<<setprecision(3); cout<<"The mean is:"<<x<<endl; cout<<"The standard deviation is:"<<y<<endl; return 0; }
true
a4ec41c7e8cff4d97c65c52a41cd9c7582cea5c1
C++
amedlin/AlgoLab
/AlgoLabCore/cast.h
UTF-8
554
2.8125
3
[]
no_license
#pragma once #include <cassert> namespace algolab { // Assert cast on pointers template<typename T, typename U> inline T* assert_cast(U* obj) { #ifdef NDEBUG return static_cast<T*>(obj); #else T* result = dynamic_cast<T*>(obj); assert(result != nullptr); return result; #endif } // Assert cast on references template<typename T, typename U> inline T& assert_cast(U& obj) { #ifdef NDEBUG return static_cast<T&>(obj); #else // This cast can throw exception. T& result = dynamic_cast<T&>(obj); return result; #endif } }
true
385f50115a8f277d46a1173202b6ca364ea01414
C++
Themandunord/TD_Dictionnary
/src/DictionaryException.cpp
UTF-8
280
2.640625
3
[]
no_license
#include "../include/DictionaryException.h" DictionaryException::DictionaryException(const std::string& _message) : m_message(_message) {} DictionaryException::~DictionaryException() throw() {} std::string DictionaryException::message() const throw() { return m_message; }
true
bd2af912fddb1f76895685f9a04965cc3ae74a8e
C++
macoro/CG_projects
/Deforming/src/mesh.cpp
UTF-8
9,405
2.546875
3
[]
no_license
#include "mesh.h" #include <iostream> Mesh::Mesh(const std::vector<Point3D>& verts, const std::vector< std::vector<int> >& faces) : m_verts(verts), m_faces(faces) { m_bbox= bounding_box(); m_chainmail = new DeformObject; m_chainmail->objSize = 0; m_chainmail->maxDeform = 1.5; m_chainmail->minDeform = 1.0; m_chainmail->maxDeformShear = 1.0; m_selectedpoint = false; } std::ostream& operator<<(std::ostream& out, const Mesh& mesh) { std::cerr << "mesh({"; for (std::vector<Point3D>::const_iterator I = mesh.m_verts.begin(); I != mesh.m_verts.end(); ++I) { if (I != mesh.m_verts.begin()) std::cerr << ",\n "; std::cerr << *I; } std::cerr << "},\n\n {"; for (std::vector<Mesh::Face>::const_iterator I = mesh.m_faces.begin(); I != mesh.m_faces.end(); ++I) { if (I != mesh.m_faces.begin()) std::cerr << ",\n "; std::cerr << "["; for (Mesh::Face::const_iterator J = I->begin(); J != I->end(); ++J) { if (J != I->begin()) std::cerr << ", "; std::cerr << *J; } std::cerr << "]"; } std::cerr << "});" << std::endl; return out; } void Mesh::walk_gl(bool picking){ glBegin(GL_TRIANGLES); for (std::vector<Mesh::Face>::const_iterator I = m_faces.begin(); I != m_faces.end(); ++I) { for(size_t v=1;v< (*I).size()-1;v++){ Vector3D ab = m_verts[(*I)[v]] - m_verts[(*I)[0]]; Vector3D ac = m_verts[(*I)[v+1]] - m_verts[(*I)[0]]; Vector3D n = ab.cross(ac); n.normalize(); // Vertex one glNormal3d(n[0],n[1],n[2]); glVertex3d(m_verts[(*I)[0]][0],m_verts[(*I)[0]][1],m_verts[(*I)[0]][2]); // Vertex two glNormal3d(n[0],n[1],n[2]); glVertex3d(m_verts[(*I)[v]][0],m_verts[(*I)[v]][1],m_verts[(*I)[v]][2]); // Vertex three glNormal3d(n[0],n[1],n[2]); glVertex3d(m_verts[(*I)[v+1]][0],m_verts[(*I)[v+1]][1],m_verts[(*I)[v+1]][2]); } } glEnd(); //draw bounding box m_bbox->walk_gl(picking); gen_controlpoints(5,5,5); } BBox* Mesh::bounding_box(){ double minx, miny, minz, maxx, maxy, maxz; Point3D p0(m_verts[0][0],m_verts[0][1],m_verts[0][2]); minx = maxx = p0[0]; miny = maxy = p0[1]; minz = maxz = p0[2]; for(size_t vert = 1; vert < m_verts.size(); vert++){ Point3D p(m_verts[vert][0],m_verts[vert][1],m_verts[vert][2]); //x if(p[0] < minx) minx = p[0]; else if(p[0] > maxx) maxx = p[0]; //y if(p[1] < miny) miny = p[1]; else if(p[1] > maxy) maxy = p[1]; //z if(p[2] < minz) minz = p[2]; else if(p[2] > maxz) maxz = p[2]; } Vector3D size( (maxx - minx),(maxy - miny),(maxz - minz) ); Point3D pos(minx,miny,minz); m_Po = pos; m_S = Vector3D(size[0],0,0); m_T = Vector3D(0,size[1],0); m_U = Vector3D(0,0,size[2]); global2local(); return new BBox(pos,size); } void Mesh::gen_controlpoints(int cpx, int cpy, int cpz, bool picking) { //allocate memory for control points if(m_chainmail->objSize == 0){ m_chainmail->object = new DeformElement[cpx*cpy*cpz]; } // center of points double step_x = m_bbox->m_size[0]/(cpx - 1); double step_y = m_bbox->m_size[1]/(cpy - 1); double step_z = m_bbox->m_size[2]/(cpz - 1); double radius = std::min(step_x, std::min( step_y, step_z) ); radius = radius/6.0; int cx= cpx/2; int cy = cpy/2; int cz = cpz/2; int index = 0; for(int i= 0; i < cpx; i++) for(int j= 0; j< cpy; j++) for(int k=0; k< cpz; k++){ //translate the point Matrix4x4 m_trans; if(m_chainmail->objSize == 0 || m_chainmail->objSize <= index){ m_trans[0][3] = m_bbox->m_pos[0] + i*step_x; m_trans[1][3] = m_bbox->m_pos[1] + j*step_y; m_trans[2][3] = m_bbox->m_pos[2] + k*step_z; //insert the point m_chainmail->object[index].x = m_trans[0][3]; m_chainmail->object[index].y = m_trans[1][3]; m_chainmail->object[index].z = m_trans[2][3]; DeformElement* link = &m_chainmail->object[index]; //if point is'nt on left face add left neightbor if(i>0){ link->left = &m_chainmail->object[index - cpy*cpz]; m_chainmail->object[index - cpy*cpz].right = link; } else{ link->left = NULL; } //if point is'nt on bottom face add bottom meightbor if(j>0){ link->bottom = &m_chainmail->object[index - cpz]; m_chainmail->object[index - cpz].top = link; } else{ link->bottom = NULL; } //if point is'nt on back face add back meightbor if(k>0){ link->back = &m_chainmail->object[index - 1]; m_chainmail->object[index - 1].front = link; } else{ link->back = NULL; } if(k == cpz-1){ link->front = NULL; } if(j == cpy -1){ link->top = NULL; } if(i == cpx - 1){ link->right = NULL; } if(i==cx && j == cy && k == cz) m_chainmail->centre = link; m_chainmail->objSize++; } else{ m_trans[0][3] = m_chainmail->object[index].x; m_trans[1][3] = m_chainmail->object[index].y; m_trans[2][3] = m_chainmail->object[index].z; } GLint mm; glGetIntegerv( GL_MATRIX_MODE, &mm); glMatrixMode(GL_MODELVIEW); glPushMatrix(); GLdouble t[16]; int z=0; for( int i=0; i < 4; i++ ){ for( int j=0; j < 4; j++ ){ t[z] = m_trans[j][i]; z++; } } glMultMatrixd(t); Sphere cpoint; cpoint.walk_gl(radius, picking); glPopMatrix(); glMatrixMode(mm); index++; } } bool Mesh::select_controlpoint(int index){ if(index < m_chainmail->objSize){ m_chainmail->selectedElementPtr = &m_chainmail->object[index]; m_selectedpoint = true; return true; } m_selectedpoint = false; return false; } void Mesh::move_controlpoint(float dx, float dy, float dz){ if(m_selectedpoint){ TestMove(m_chainmail,&dx,&dy,&dz,0); center_cm2bb(); deform_verts(5,5,5); } } void Mesh::global2local(){ for(size_t vert = 0; vert < m_verts.size(); vert++){ Vector3D tmp = m_verts[vert] - m_Po; Point3D lv; lv[0] = (m_T.cross(m_U)).dot(tmp)/((m_T.cross(m_U)).dot(m_S)); lv[1] = (m_U.cross(m_S)).dot(tmp)/((m_U.cross(m_S)).dot(m_T)); lv[2] = (m_S.cross(m_T)).dot(tmp)/((m_S.cross(m_T)).dot(m_U)); m_localverts.push_back(lv); } } void Mesh::deform_verts(int cpx,int cpy, int cpz) { for(size_t vert = 0; vert < m_localverts.size(); vert++){ Vector3D gvert; boost::math::binomial_distribution<double> x_dist = boost::math::binomial_distribution<double>((cpx - 1),m_localverts[vert][0]); for(int i= 0; i<cpx; i++){ Vector3D gvert_j; boost::math::binomial_distribution<double> y_dist = boost::math::binomial_distribution<double>((cpy - 1),m_localverts[vert][1]); for(int j=0; j<cpy; j++){ Vector3D gvert_k; boost::math::binomial_distribution<double> z_dist = boost::math::binomial_distribution<double>((cpz - 1),m_localverts[vert][2]); for(int k=0; k<cpz; k++){ int index = i*cpy*cpz + j*cpz + k; Vector3D Pijk(m_chainmail->object[index].x, m_chainmail->object[index].y, m_chainmail->object[index].z); gvert_k = gvert_k + boost::math::pdf(z_dist,k)*Pijk; } gvert_j = gvert_j + boost::math::pdf(y_dist,j)*gvert_k; } gvert = gvert + boost::math::pdf(x_dist,i)*gvert_j; } //deforming vertice m_verts[vert][0] = gvert[0]; m_verts[vert][1] = gvert[1]; m_verts[vert][2] = gvert[2]; } } void Mesh::center_cm2bb(){ float dx = m_bbox->centre[0] - m_chainmail->centre->x; float dy = m_bbox->centre[1] - m_chainmail->centre->y; float dz = m_bbox->centre[2] - m_chainmail->centre->z; Vector3D trsl(dx,dy,dz); if(trsl.length2() > M_EPS) TestMove(m_chainmail, &dx, &dy, &dz, 1); }
true
a9a3a131463a4e742a051751d56a9ba5ade364fe
C++
Enginek29/Study
/DZ1-1/DZ1-1.cpp
UTF-8
820
2.796875
3
[]
no_license
// DZ1-1.cpp набрать программу #include <stdio.h> int main (void) { int a,b = 5, c; double x, y = -5, z; printf("a="); scanf("%d", &a); x = c = a; printf("a=%d, c=%d, x=%f\n", a, c, x); a += b; printf("a=%d\n", a); x += b+a; printf("x=%f\n", x); b += a--; printf("b=%d\n", b); x -= ++c; printf("x=%f\n", x); c = a / b; printf("c=%4d\n",c); c = a % b; printf("c=%d\n",c); x = 5.3; y += ((--x - 1) / x++); printf("x=%f\ty = % 2f\n\n x= %.0f\ty = %.0f\n", x - 1, y, x, y - 1); z = a / 2; printf("z= %f\n", z); z = (float)a / 2; printf("z= %f\n", z); y = x / 2; printf("y=%f\n", y); y = (int)x/2; printf("y=%f\n", y); z = a % 2 - (x + b) / c + (x - y) / (a - 1) + 1 / 4 * a - y++ + ++b / 3; printf("a=%d b= %d c= %d x=%f y=%f z=%f\n", a, b, c, x, y, z); return{}; }
true
3c6368e39637003a2b9566a50a2e33c4212f1ccd
C++
alexandraback/datacollection
/solutions_5648941810974720_1/C++/boqun/a.cc
UTF-8
2,197
3.0625
3
[]
no_license
#include <iostream> #include <string> using namespace std; int T; string tmp; int S[256]; int n[10]; void count(int S[], const char *s) { char c; while (c = *s++) S[c]++; } int zero(int *S) { int result = S['Z']; if (result != 0) { S['Z'] -= result; S['E'] -= result; S['R'] -= result; S['O'] -= result; } return result; } int six(int *S) { int result = S['X']; if (result != 0) { S['S'] -= result; S['I'] -= result; S['X'] -= result; } return result; } int seven(int *S) { int result = S['S']; if (result != 0) { S['S'] -= result; S['E'] -= result * 2; S['V'] -= result; S['N'] -= result; } return result; } int nine(int *S) { int result = S['I']; if (result != 0) { S['N'] -= result * 2; S['E'] -= result; S['I'] -= result; } return result; } int eight(int *S) { int result = S['G']; if (result != 0) { S['E'] -= result; S['I'] -= result; S['G'] -= result; S['H'] -= result; S['T'] -= result; } return result; } int three(int *S) { int result = S['H']; if (result != 0) { S['E'] -= result * 2; S['H'] -= result; S['T'] -= result; S['R'] -= result; } return result; } int two(int *S) { int result = S['W']; if (result != 0) { S['T'] -= result; S['W'] -= result; S['O'] -= result; } return result; } int five(int *S) { int result = S['V']; if (result != 0) { S['F'] -= result; S['I'] -= result; S['V'] -= result; S['E'] -= result; } return result; } int one(int *S) { int result = S['N']; if (result != 0) { S['O'] -= result; S['N'] -= result; S['E'] -= result; } return result; } int four(int *S) { int result = S['F']; return result; } int main() { cin >> T; for (int i = 1; i <= T; i++) { cin >> tmp; for (int j = 0; j < 256; j++) S[j] = 0; for (int j = 0; j < 10; j++) n[j] = 0; count(S, tmp.c_str()); n[0] = zero(S); n[2] = two(S); n[6] = six(S); n[7] = seven(S); n[5] = five(S); n[8] = eight(S); n[9] = nine(S); n[3] = three(S); n[1] = one(S); n[4] = four(S); cout << "Case #" << i << ": "; for (int j = 0; j < 10; j++) for (int k = 0; k < n[j]; k++) cout << j; cout << endl; } }
true
14ecf237d3011a9e75830558d3da04d05a9c0879
C++
dh434/leetcode
/hot100/538. 把二叉搜索树转换为累加树.cpp
UTF-8
1,072
3.921875
4
[]
no_license
/* 给定一个二叉搜索树(Binary Search Tree),把它转换成为累加树(Greater Tree), 使得每个节点的值是原来的节点值加上所有大于它的节点值之和。 例如: 输入: 二叉搜索树: 5 / \ 2 13 输出: 转换为累加树: 18 / \ 20 13 */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* convertBST(TreeNode* root) { int temp = 0; return convertBSTCore(root,temp); } TreeNode* convertBSTCore(TreeNode* root, int& cumSum){ if(root == NULL) return root; root->right = convertBSTCore(root->right, cumSum); root->val += cumSum; cumSum = root->val; root->left = convertBSTCore(root->left, cumSum); return root; } };
true
2e53abd932045b1af819f2cf2366f947ac97a0ef
C++
jxzhsiwuxie/cppPrimer
/chap18/exercises/ex_18.1.cpp
UTF-8
449
3.25
3
[]
no_license
//练习 18.1:在下列 throw 语句中异常对象的类型是什么? // (a) range_error r("error"); (b) exception *p = &r; // throw r; throw *p //如果将 (b) 中的 throw 语句写成 throw p 将发生什么情况? /* * (a) range_error * (b) exception * 如果将 throw 语句写成 throw p,则泡泡出异常后 r 的析构函数被调用,在 catch 语句中不能再访问异常对象。 */
true
f587f6005927aaac108d7f438b02283c70d17dc9
C++
mt2522577/TranMelvin_CSC5_40717
/Hmwk/Assignment3/Gaddis_8thEd_Ch4_Q6/main.cpp
UTF-8
885
3.390625
3
[]
no_license
/* * File: main.cpp * Author: Melvin Tran * Created on January 19, 2015, 10:06 PM */ //System Libraries #include <cstdlib> //Randon srand(), rand() #include <iostream> //Keyboard/Monitor I/O #include <cmath> //Math Function Libraries #include <iomanip> using namespace std; //User Libraries //Global Constants //Function Prototype //Execution Begins Here! int main(int argc, char** argv) { //Declare Variables float weight,mass; cout<<"Please enter a mass of an object in kilograms."<<endl; cin>>mass; cout<<fixed<<setprecision(2)<<showpoint; weight=mass*9.8; if (weight>1000){ cout<<"The weight of Newtons is too heavy."<<endl; } else if (weight<10){ cout<<"The weight of Newtons is too light."<<endl; } else if (weight>10||weight<1000){ cout<<"The weight of Newtons is "<<weight<<endl; } return 0; }
true
6cb8cebe8b598309f995bab7c164f9ba458609f7
C++
MariaCholakova/Ecosystem
/Object.h
UTF-8
618
3.234375
3
[]
no_license
#ifndef OBJECT_H #define OBJECT_H class Object { public: static int rows; static int cols; private: struct Coordinate { int x; int y; Coordinate(int a, int b); Coordinate(); bool operator == (const Coordinate& c) const; }; protected: Coordinate c; Object(int x, int y); // to not create objects of this class, but of his children Object(); public: Coordinate GetCoordinate() const; void SetX(const int x); void SetY(const int y); int GetX() const; int GetY() const; }; #endif // OBJECT_H
true
ead2813f614b51af706d857ad315e5874c950c6e
C++
BRAINIAC2677/Lightoj-Solutions
/1053 - Higher Math.cpp
UTF-8
493
2.875
3
[ "MIT" ]
permissive
/*BISMILLAH THE WHITE WOLF NO DREAM IS TOO BIG AND NO DREAMER IS TOO SMALL*/ #include<bits/stdc++.h> using namespace std; int main() { int t; cin >> t; for (int i= 1;i <= t;i++) { int arr[3]; cin >> arr[0] >> arr[1] >> arr[2]; sort(arr, arr+3); int dif = arr[2] * arr[2] - arr[1]*arr[1] - arr[0] *arr[0]; if (dif == 0) printf("Case %d: yes\n",i); else printf("Case %d: no\n",i); } return 0; }
true
02feffa184b7f655626dbad2a951358d3d49d5bd
C++
IrishCoffee/AlgorithmCode
/ACM/LeetCode/addTwoNumbers.cpp
UTF-8
1,515
3.46875
3
[]
no_license
#include <iostream> #include <cstdio> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x): val(x),next(NULL){} }; class Solution { public: ListNode *addTwoNumbers(ListNode *L1, ListNode *L2) { ListNode *L = new ListNode((L1->val + L2->val) % 10); ListNode *head = L; int tmp = (L1->val + L2->val) / 10; while(L1->next != NULL && L2->next != NULL) { L1 = L1->next; L2 = L2->next; L->next = new ListNode((L1->val + L2->val + tmp) % 10); L = L->next; tmp = (L1->val + L2->val + tmp)/10; } while(L1->next != NULL) { L1 = L1->next; L->next = new ListNode((L1->val + tmp) % 10); L = L->next; tmp = (L1->val + tmp) / 10; } while(L2->next != NULL) { L2= L2->next; L->next = new ListNode((L2->val + tmp) % 10); L = L->next; tmp = (L2->val + tmp) / 10; } if(tmp != 0) L->next = new ListNode(tmp); return head; } }; int main() { Solution sol; ListNode *l1 = new ListNode(2),*l2 = new ListNode(8); ListNode *h1 = l1, *h2 = l2; /* int n1[2] = {4,3}; for(int i = 0; i < 2; ++i) { l1->next = new ListNode(n1[i]); l1 = l1->next; }*/ ListNode *t1 = h1, *t2 = h2; while(t1 != NULL) { printf("%d ",t1->val); t1 = t1->next; } cout << endl; while(t2 != NULL) { printf("%d ",t2->val); t2 = t2->next; } cout << endl; ListNode *ans = sol.addTwoNumbers(h1,h2); while(ans != NULL) { cout << ans->val << " "; ans = ans->next; } cout << endl; return 0; }
true
8ba6fbd3b81d267cc53aea1d27d304b0a64819c8
C++
BenGamliel/wet1ShayBen
/HoursAndCounters.h
UTF-8
1,327
3.40625
3
[]
no_license
// // Created by Ben on 4/25/2019. // #ifndef DSWET1SHAY_HOURSANDCOUNTERS_H #define DSWET1SHAY_HOURSANDCOUNTERS_H class HoursAndCounters { int _hours; unsigned int* _hoursCounters; unsigned int _totalSum; public: //HoursAndCounter Counstractor input: a given value to init the array // O(n) as n is hours value explicit HoursAndCounters(int hours) :_hours(hours),_totalSum(0){ try { _hoursCounters = new unsigned int[hours]; // _hoursCounters={0};//init new array with the 0 value in all the array for (int i = 0; i < hours; i++) { _hoursCounters[i] = 0; } } catch(std::bad_alloc&) { if(_hoursCounters){ delete [] _hoursCounters; } } } //Destractor free array ~HoursAndCounters(){ delete[]_hoursCounters;//verify this is the way to free a full array } void addLectureInHour(int hour){ if(_hoursCounters[hour]==0){ _totalSum++; } _hoursCounters[hour]++; } void removeLuctureInHour(int hour){ _hoursCounters[hour]--; if(_hoursCounters[hour]==0){ _totalSum--; } } unsigned int getTotalSum(){ return _totalSum; } }; #endif //DSWET1SHAY_HOURSANDCOUNTERS_H
true
11816a8a05b35938d24f670ef3fee5c88b146b95
C++
AzamAzam/PfLabsAssignments
/assing5/bcsf15m024(assig5)/Q4.cpp
UTF-8
361
2.671875
3
[]
no_license
//#include <iostream> //#include <string> //using namespace std; //int main() //{ // string s; // // getline(cin,s); // // int count=0; // // for(int i=0 ; i<=s.length(); i++) // // { // // if(s[i]==' ' || s[i]=='\n' || s[i]=='\t' || s[i]=='\0') // count++; // // // } // cout <<"\n "<< count; // // return 0; // //}
true
cf084a914bc06f4ec496cc333f592d6bbf8c55bb
C++
Ukio-G/study_cpp
/stepik_cpp/First_Course/strstr/main.cpp
UTF-8
6,709
2.75
3
[]
no_license
#include <iostream> using namespace std; int strstr(const char *text, const char *pattern); void test() { (0 == strstr("","")) ? cout<<"OK : 1"<< " (" << 0 << " : " << (0 == strstr("","")) << " )" << endl : cout<< "Failed : 1"<< " (" << 0 << " : " << (0 == strstr("","")) << " )" << endl ; (0 == strstr("a", "")) ? cout<<"OK : 2"<< " (" << 0 << " : " << (0 == strstr("a", "")) << " )" << endl : cout<< "Failed : 2"<< " (" << 0 << " : " << (0 == strstr("a", "")) << " )" << endl ; (0 == strstr("a", "a")) ? cout<<"OK : 3"<< " (" << 0 << " : " << (0 == strstr("a", "a")) << " )" << endl : cout<< "Failed : 3"<< " (" << 0 << " : " << (0 == strstr("a", "a")) << " )" << endl ; (-1 == strstr("a", "b")) ? cout<<"OK : 4"<< " (" << -1 << " : " << (-1 == strstr("a", "b")) << " )" << endl : cout<< "Failed : 4"<< " (" << -1 << " : " << (-1 == strstr("a", "b")) << " )" << endl ; (0 == strstr("aa", "")) ? cout<<"OK : 5"<< " (" << 0 << " : " << (0 == strstr("aa", "")) << " )" << endl : cout<< "Failed : 5"<< " (" << 0 << " : " << (0 == strstr("aa", "")) << " )" << endl ; (0 == strstr("aa", "a")) ? cout<<"OK : 6"<< " (" << 0 << " : " << (0 == strstr("aa", "a")) << " )" << endl : cout<< "Failed : 6"<< " (" << 0 << " : " << (0 == strstr("aa", "a")) << " )" << endl ; (0 == strstr("ab", "a")) ? cout<<"OK : 7"<< " (" << 0 << " : " << (0 == strstr("ab", "a")) << " )" << endl : cout<< "Failed : 7"<< " (" << 0 << " : " << (0 == strstr("ab", "a")) << " )" << endl ; (1 == strstr("ba", "a")) ? cout<<"OK : 8"<< " (" << 1 << " : " << (1 == strstr("ba", "a")) << " )" << endl : cout<< "Failed : 8"<< " (" << 1 << " : " << (1 == strstr("ba", "a")) << " )" << endl ; (-1 == strstr("bb", "a")) ? cout<<"OK : 9"<< " (" << -1 << " : " << (-1 == strstr("bb", "a")) << " )" << endl : cout<< "Failed : 9"<< " (" << -1 << " : " << (-1 == strstr("bb", "a")) << " )" << endl ; (0 == strstr("aaa", "")) ? cout<<"OK : 10"<< " (" << 0 << " : " << (0 == strstr("aaa", "")) << " )" << endl : cout<< "Failed : 10"<< " (" << 0 << " : " << (0 == strstr("aaa", "")) << " )" << endl ; (0 == strstr("aaa", "a")) ? cout<<"OK : 11"<< " (" << 0 << " : " << (0 == strstr("aaa", "a")) << " )" << endl : cout<< "Failed : 11"<< " (" << 0 << " : " << (0 == strstr("aaa", "a")) << " )" << endl ; (1 == strstr("abc", "b")) ? cout<<"OK : 12"<< " (" << 1 << " : " << (1 == strstr("abc", "b")) << " )" << endl : cout<< "Failed : 12"<< " (" << 1 << " : " << (1 == strstr("abc", "b")) << " )" << endl ; (2 == strstr("abc", "c")) ? cout<<"OK : 13"<< " (" << 2 << " : " << (2 == strstr("abc", "c")) << " )" << endl : cout<< "Failed : 13"<< " (" << 2 << " : " << (2 == strstr("abc", "c")) << " )" << endl ; (-1 == strstr("abc", "d")) ? cout<<"OK : 14"<< " (" << -1 << " : " << (-1 == strstr("abc", "d")) << " )" << endl : cout<< "Failed : 14"<< " (" << -1 << " : " << (-1 == strstr("abc", "d")) << " )" << endl ; (-1 == strstr("a", "aa")) ? cout<<"OK : 15"<< " (" << -1 << " : " << (-1 == strstr("a", "aa")) << " )" << endl : cout<< "Failed : 15"<< " (" << -1 << " : " << (-1 == strstr("a", "aa")) << " )" << endl ; (-1 == strstr("a", "ba")) ? cout<<"OK : 16"<< " (" << -1 << " : " << (-1 == strstr("a", "ba")) << " )" << endl : cout<< "Failed : 16"<< " (" << -1 << " : " << (-1 == strstr("a", "ba")) << " )" << endl ; (-1 == strstr("a", "ab")) ? cout<<"OK : 17"<< " (" << -1 << " : " << (-1 == strstr("a", "ab")) << " )" << endl : cout<< "Failed : 17"<< " (" << -1 << " : " << (-1 == strstr("a", "ab")) << " )" << endl ; (-1 == strstr("a", "bb")) ? cout<<"OK : 18"<< " (" << -1 << " : " << (-1 == strstr("a", "bb")) << " )" << endl : cout<< "Failed : 18"<< " (" << -1 << " : " << (-1 == strstr("a", "bb")) << " )" << endl ; (-1 == strstr("a", "aaa")) ? cout<<"OK : 19"<< " (" << -1 << " : " << (-1 == strstr("a", "aaa")) << " )" << endl : cout<< "Failed : 19"<< " (" << -1 << " : " << (-1 == strstr("a", "aaa")) << " )" << endl ; (-1 == strstr("aa", "aaa")) ? cout<<"OK : 20"<< " (" << -1 << " : " << (-1 == strstr("aa", "aaa")) << " )" << endl : cout<< "Failed : 20"<< " (" << -1 << " : " << (-1 == strstr("aa", "aaa")) << " )" << endl ; (0 == strstr("aaa", "aaa")) ? cout<<"OK : 21"<< " (" << 0 << " : " << (0 == strstr("aaa", "aaa")) << " )" << endl : cout<< "Failed : 21"<< " (" << 0 << " : " << (0 == strstr("aaa", "aaa")) << " )" << endl ; (0 == strstr("aaab", "aaa")) ? cout<<"OK : 22"<< " (" << 0 << " : " << (0 == strstr("aaab", "aaa")) << " )" << endl : cout<< "Failed : 22"<< " (" << 0 << " : " << (0 == strstr("aaab", "aaa")) << " )" << endl ; (1 == strstr("baaa", "aaa")) ? cout<<"OK : 23"<< " (" << 1 << " : " << (1 == strstr("baaa", "aaa")) << " )" << endl : cout<< "Failed : 23"<< " (" << 1 << " : " << (1 == strstr("baaa", "aaa")) << " )" << endl ; (1 == strstr("baaaa", "aaa")) ? cout<<"OK : 24"<< " (" << 1 << " : " << (1 == strstr("baaaa", "aaa")) << " )" << endl : cout<< "Failed : 24"<< " (" << 1 << " : " << (1 == strstr("baaaa", "aaa")) << " )" << endl ; (1 == strstr("baaab", "aaa")) ? cout<<"OK : 25"<< " (" << 1 << " : " << (1 == strstr("baaab", "aaa")) << " )" << endl : cout<< "Failed : 25"<< " (" << 1 << " : " << (1 == strstr("baaab", "aaa")) << " )" << endl ; (-1 == strstr("abd", "abc")) ? cout<<"OK : 26"<< " (" << -1 << " : " << (-1 == strstr("abd", "abc")) << " )" << endl : cout<< "Failed : 26"<< " (" << -1 << " : " << (-1 == strstr("abd", "abc")) << " )" << endl ; (2 == strstr("ababc", "abc")) ? cout<<"OK : 27"<< " (" << 2 << " : " << (2 == strstr("ababc", "abc")) << " )" << endl : cout<< "Failed : 27"<< " (" << 2 << " : " << (2 == strstr("ababc", "abc")) << " )" << endl ; (3 == strstr("abdabc", "abc")) ? cout<<"OK : 28"<< " (" << 3 << " : " << (3 == strstr("abdabc", "abc")) << " )" << endl : cout<< "Failed : 28"<< " (" << 3 << " : " << (3 == strstr("abdabc", "abc")) << " )" << endl ; } int strstr(const char *text, const char *pattern) { if(*pattern == '\0') return 0; for(int i = 0; *(text+i) != '\0' ;i++) for(int j = 0; *(pattern+j) == *(text+(i+j));j++) { if(*(pattern+j+1)=='\0') return i; if(*(text+(i+j)) == '\0') return -1; } return -1; } int main(int argc, const char *argv[]) { test(); // cout << strstr("","") << endl; //cout << strstr("a","") << endl; cout << strstr("aaaaa","a") << endl; // cout << strstr("a","ab") << endl; // cout << strstr("a","ba") << endl; // cout << strstr("a","bba") << endl; return 0; }
true
41690c1abb29ae903457a68d9640c4b1adb94a6e
C++
ATinyBanana233/HashTable
/linkedlist.cpp
UTF-8
3,337
3.578125
4
[]
no_license
//CMPT 225 assignment 5 //Author: Bei Bei Li //implementation for linkedlist.h #pragma once #include <cstdlib> #include <string> #include <vector> #include "linkedlist.h" using namespace std; // helper method for deep copy void LinkedList::CopyList(const LinkedList& ll) { if (size){ //if exsit, clear RemoveAll(); } if (ll.size && ll.head){ //if ll exist Node* L = ll.head; head = new Node(L->data, L->next); //creating deep copy L = L->next; Node* current = head; while (L != NULL){ current->next = new Node(L->data, L->next); L = L->next; //move L to copy current = current->next; //move current } } size = ll.size; } // default constructor LinkedList::LinkedList() { head = NULL; size = 0; } // copy constructor // deep copies source list LinkedList::LinkedList(const LinkedList& ll) { head = NULL; size = 0; CopyList(ll); } // destructor LinkedList::~LinkedList() { RemoveAll(); } // overloaded assignment operator // deep copies source list after deallocating existing memory (if necessary) LinkedList& LinkedList::operator=(const LinkedList& ll) { if (this != &ll) { // if not equal then change //RemoveAll(); CopyList(ll); } return *this; } // Inserts an item at the front of the list void LinkedList::Insert(string s) { //Node* oldhead = head; Node* ins = new Node(s, head); //create, oldhead becomes ptr next if (ins != NULL){ head = ins; //set head size++; } } // Removes an item from the list. // Returns true if item successfully removed // False if item is not found bool LinkedList::Remove(string s) { if (head == NULL){ return false; } if (head->data == s){ //if head is to be removed, ptr next becomes head Node* oldhead = head; head = head->next; delete oldhead; size--; return true; } Node* current = head->next; //if in the linked list, set prev node's next ptr to current's next Node* prev = head; while (current != NULL){ if (current->data == s){ prev->next = current->next; delete current; size--; return true; } current = current->next; prev = prev->next; } return false; } // Removes all items from the list, calls helper function void LinkedList::RemoveAll() { Node* current = head; while (current != NULL){ //traverse to remove head = head->next; delete current; current = head; } head = NULL; size = 0; } // Checks if an item exists in the list bool LinkedList::Contains(string s) const { if (head != NULL){ Node* current = head; while (current != NULL){ if (current->data == s){ return true; } current = current->next; } } return false; } // Return the number of items in the list unsigned int LinkedList::Size() const { return size; } // Returns a vector containing the list contents using push_back vector<string> LinkedList::Dump() const { vector<string> result; Node* current = head; while (current != NULL){ result.push_back(current->data); //using vector method to push_back current = current->next; //traverse to push_back next } return result; }
true
b055083f3aa4720f3b513c3f986576751c01b061
C++
jjjasperd/Cpp-Primer-Exercise
/Exercise5.14.cpp
UTF-8
1,471
3.21875
3
[]
no_license
// // main.cpp // Statement // // Created by DuanYujia on 1/9/15. // Copyright (c) 2015 DuanYujia. All rights reserved. // #include <iostream> #include <string> #include <vector> using std::cout; using std::cin; using std::string; using std::vector; using std::endl; int main(int argc, const char * argv[]) { vector<string> v; string str; //get input while ( cin >> str ) { v.push_back(str); } int max_dup = 1; // to keep the max duplicate times int count = 1; // to keep the duplicate times of current word auto beg = v.begin(); string max_str; while (beg != v.end()) { // if there exist duplication, count add 1 if(*beg ==*(beg - 1)){ ++count; } //else give the max_dup and max_str the current max value, and recount count else{ //to check if count is bigger than max_dup if (count > max_dup) { max_dup = count; max_str = *(beg -1); } count = 1; } ++beg; } //check again out side the loop to catch the last set of replicated word, if any if (count > max_dup) { max_dup = count; max_str = *(beg -1); } if (count != 1) { cout << " the most duplicated word is " << max_str << " for " << max_dup << " times"<< endl; } else{ cout << " there was no word been repeated"<<endl; } return 0; }
true
d99480ebd2f63b304401db00bb2148e6be148ea8
C++
rm3028/Monster-Killer
/Monster-Killer/Vector.h
UTF-8
1,407
3.203125
3
[]
no_license
/* * Vector.h: Basic vector class * Author: Wei-Yun * Email: rm3028@hotmail.com.tw * Copyright © 2021 Wei-Yun. * All rights reserved. */ #pragma once #include <GL\glut.h> class CVector { public: CVector(GLvoid); //Construct a vector CVector(GLfloat vVector_x, GLfloat vVector_y, GLfloat vVector_z); //Construct a vector with data CVector(const CVector &vVector); //Construct a vector by a vector ~CVector(GLvoid); //Deconstruct a vector GLfloat x, y, z; //Vector data public: CVector operator+(CVector vVector); //Addition operator of vector CVector operator-(CVector vVector); //Minus operator of vector CVector operator*(GLfloat num); //Multiply operator of vector CVector operator/(GLfloat num); //Division operator of vector GLvoid SetVector(GLfloat vVector_x, GLfloat vVector_y, GLfloat vVector_z); //Set the vector data friend GLfloat Magnitude(CVector vVector); //Return the Magnitude of a vector friend CVector Normalize(CVector vVector); //Return the normalized vector of a vector friend CVector Cross(CVector vVector1, CVector vVector2); //Return the cross vector of two vectors friend GLfloat Dot(CVector vVector1, CVector vVector2); //Return the dot value of two vectors friend GLfloat Distance(CVector vVector1, CVector vVector2); //Return the distance between two vectors friend GLfloat Angle(CVector vVector1, CVector vVector2); //Return the angle between two vectors };
true
d165f75a95970824e33734fc9cc1d6bcc841a178
C++
SayaUrobuchi/uvachan
/UVa/11926.cpp
UTF-8
1,274
2.5625
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #define M 1000000 int st[256], ed[256], inv[256], idx[256]; int comp(const void *p, const void *q) { return inv[*(int*)p] > inv[*(int*)q] ? 1 : -1; } int main() { int n, m, i, j, k, p, q, r, a, over; while (scanf("%d%d", &n, &m) == 2) { if (!n && !m) { break; } over = 0; for (i=0; i<n; i++) { scanf("%d%d", &st[i], &ed[i]); inv[i] = 1048576; idx[i] = i; } m += n; for (; i<m; i++) { scanf("%d%d%d", &st[i], &ed[i], &inv[i]); if (inv[i]+st[i] < ed[i]) { over = 1; } idx[i] = i; } if (!over) { qsort(idx, m, sizeof(int), comp); for (i=1; i<m; i++) { p = idx[i]; for (j=0; j<i; j++) { q = idx[j]; for (k=0; k+st[p]<=M; k+=inv[p]) { r = k + st[p]; /* inv[q]*a + ed[q] > r */ if (ed[q] > r) { a = 0; } else { a = (r-ed[q])/inv[q] + 1; } if (inv[q]*a+st[q] <= M && inv[q]*a + ed[q] > k+st[p] && k+ed[p] > inv[q]*a + st[q]) { break; } } if (k+st[p] <= M) { break; } } if (j < i) { break; } } } if (!over && i >= m) { puts("NO CONFLICT"); } else { puts("CONFLICT"); } } return 0; }
true
f75443e79019e00794af03b782b40c4c902c6fc5
C++
ajmarin/coding
/uva/Volume CXII/11227.cpp
UTF-8
1,049
2.609375
3
[]
no_license
#include <algorithm> #include <cmath> #include <cstdio> using namespace std; int x[128], y[128]; double s[128]; int main(void){ int dset = 1, lx, ly, n, rx, ry, t; for(scanf("%d", &t); t--; dset++){ scanf("%d", &n); for(int i = 0; i < n; ++i){ scanf("%d.%d %d.%d", &lx, &rx, &ly, &ry); x[i] = 100 * lx + rx; y[i] = 100 * ly + ry; for(int j = 0; j < i; ++j) if(x[j] == x[i] && y[j] == y[i]){ i--; n--; break; } } int maxaligned = 0; for(int i = 0; i < n; ++i){ int c = 0, sc = 0; for(int j = i + 1; j < n; ++j){ if(x[j] - x[i]) s[sc++] = (y[j] - y[i])/(double)(x[j] - x[i]); else c++; } sort(s, s + sc); for(int j = 0, k = 0; j < sc && k < sc; ){ while(k < sc && fabs(s[k] - s[j]) < 1e-9) k++; if(k - j > maxaligned) maxaligned = k - j; j = k; } if(c > maxaligned) maxaligned = c; } printf("Data set #%d contains ", dset); if(n == 1) printf("a single gnu.\n", dset); else printf("%d gnus, out of which a maximum of %d are aligned.\n", n, maxaligned + 1); } return 0; }
true
042c6867035aeb2b31a4801d12f637baa6dbd7db
C++
doggydigit/miniprojet1
/mini-projet1-empty/src/signal.hpp
UTF-8
650
3.0625
3
[]
no_license
#ifndef SIGNAL_H #define SIGNAL_H #include "types.hpp" using namespace std; class Signal { public: Signal(bool presence); ~Signal(); bool presence(); // une méthode getSignal() qui retournera un référence constante sur le signal courant (*this). impl::signal_t getSignal(); protected: private: //un booléen objectPresent permettant de connaître l'information initialement détenue par le signal (présence ou absence d'objet dans le champ visuel); bool objectPresent; //une séquence de vingt bits de type impl::signal_t modélisant le signal; impl::signal_t input_sequence; }; #endif
true
1133954a5fd54f82a84ade6f1fffbce58889e784
C++
ssprl/Direction-of-arrival-estimation-using-deep-neural-network
/DOA_DNN_Android_app/app/src/main/cpp/Transforms.cpp
UTF-8
5,432
2.875
3
[ "MIT" ]
permissive
#include "Transforms.h" //#include "stdafx.h" void FFT(Transform* fft, float* input); void IFFT(Transform* fft, float* inputreal, float* inputimaginary); Transform* newTransform(int points) { Transform* newTransform = (Transform*)malloc(sizeof(Transform)); newTransform->points = points; newTransform->real = (float*)malloc(points * sizeof(float)); newTransform->imaginary = (float*)malloc(points * sizeof(float)); newTransform->sine = NULL; newTransform->cosine = NULL; newTransform->doTransform = FFT; newTransform->invTransform = IFFT; newTransform->sine = (float*)malloc((points / 2) * sizeof(float)); newTransform->cosine = (float*)malloc((points / 2) * sizeof(float)); //precompute twiddle factors double arg; int i; for (i = 0; i<points / 2; i++) { arg = -2 * M_PI*i / points; newTransform->cosine[i] = cos(arg); newTransform->sine[i] = sin(arg); } return newTransform; } void FFT(Transform* fft, float* input) { int i, j, k, L, m, n, o, p, q; double tempReal, tempImaginary, cos, sin, xt, yt; k = fft->points; for (i = 0; i<k; i++) { fft->real[i] = input[i]; fft->imaginary[i] = 0; } j = 0; m = k / 2; //bit reversal for (i = 1; i<(k - 1); i++) { L = m; while (j >= L) { j = j - L; L = L / 2; } j = j + L; if (i<j) { tempReal = fft->real[i]; tempImaginary = fft->imaginary[i]; fft->real[i] = fft->real[j]; fft->imaginary[i] = fft->imaginary[j]; fft->real[j] = tempReal; fft->imaginary[j] = tempImaginary; } } L = 0; m = 1; n = k / 2; //computation for (i = k; i>1; i = (i >> 1)) { L = m; m = 2 * m; o = 0; for (j = 0; j<L; j++) { cos = fft->cosine[o]; sin = fft->sine[o]; o = o + n; for (p = j; p<k; p = p + m) { q = p + L; xt = cos*fft->real[q] - sin*fft->imaginary[q]; yt = sin*fft->real[q] + cos*fft->imaginary[q]; fft->real[q] = (fft->real[p] - xt); fft->imaginary[q] = (fft->imaginary[p] - yt); fft->real[p] = (fft->real[p] + xt); fft->imaginary[p] = (fft->imaginary[p] + yt); } } n = n >> 1; } } void IFFT(Transform* fft, float* inputreal, float* inputimaginary) { int i, j, k, L, m, n, o, p, q; float tempReal, tempImaginary, cos, sin, xt, yt; k = fft->points; for (i = 0; i<k; i++) { fft->real[i] = inputreal[i]; fft->imaginary[i] = (-1)*inputimaginary[i]; } j = 0; m = k / 2; //bit reversal for (i = 1; i<(k - 1); i++) { L = m; while (j >= L) { j = j - L; L = L / 2; } j = j + L; if (i<j) { tempReal = fft->real[i]; tempImaginary = fft->imaginary[i]; fft->real[i] = fft->real[j]; fft->imaginary[i] = fft->imaginary[j]; fft->real[j] = tempReal; fft->imaginary[j] = tempImaginary; } } L = 0; m = 1; n = k / 2; //computation for (i = k; i>1; i = (i >> 1)) { L = m; m = 2 * m; o = 0; for (j = 0; j<L; j++) { cos = fft->cosine[o]; sin = fft->sine[o]; o = o + n; for (p = j; p<k; p = p + m) { q = p + L; xt = cos*fft->real[q] - sin*fft->imaginary[q]; yt = sin*fft->real[q] + cos*fft->imaginary[q]; fft->real[q] = (fft->real[p] - xt); fft->imaginary[q] = (fft->imaginary[p] - yt); fft->real[p] = (fft->real[p] + xt); fft->imaginary[p] = (fft->imaginary[p] + yt); } } n = n >> 1; } for (i = 0; i<k; i++) { fft->real[i] = fft->real[i] / k; fft->imaginary[i] = fft->imaginary[i] / k; } } void transformMagnitude(Transform* transform, double* output) { int n; for (n = 0; n<transform->points; n++) { output[n] = sqrt(transform->real[n] * transform->real[n] + transform->imaginary[n] * transform->imaginary[n]); } } void invtranMagnitude(Transform* transform, double* output) { int n; float a; a = 1.0 / transform->points; for (n = 0; n < transform->points; n++) { output[n] = a * sqrt(transform->real[n] * transform->real[n] + transform->imaginary[n] * transform->imaginary[n]); } } void destroyTransform(Transform** transform) { if (*transform != NULL) { if ((*transform)->cosine != NULL) { free((*transform)->cosine); (*transform)->cosine = NULL; } if ((*transform)->sine != NULL) { free((*transform)->sine); (*transform)->sine = NULL; } if ((*transform)->real != NULL) { free((*transform)->real); (*transform)->real = NULL; } if ((*transform)->imaginary != NULL) { free((*transform)->imaginary); (*transform)->imaginary = NULL; } free(*transform); *transform = NULL; } }
true
fa3a42b3bc6471f0ffe1d5523bf617ff70bf3264
C++
Swizzman/Project_Zumo
/CodePC/MainProgram/Logo.cpp
UTF-8
651
2.96875
3
[]
no_license
#include "Logo.h" Logo::Logo() { this->texture.loadFromFile("../images/logo.png"); intRect = sf::IntRect(0, 0, this->texture.getSize().x / 30, this->texture.getSize().y); this->sprite.setTexture(texture); this->sprite.setTextureRect(this->intRect); } void Logo::setPosition(int x, int y) { this->sprite.setPosition(x, y); } Logo::~Logo() { } void Logo::nextFrame() { this->intRect.left = (this->intRect.left + this->intRect.width) % this->texture.getSize().x; this->sprite.setTextureRect(this->intRect); } void Logo::draw(sf::RenderTarget& target, sf::RenderStates states) const { target.draw(this->sprite, sf::RenderStates::Default); }
true
73a933f9986bfbf6aa235b21797d91c24891daa4
C++
eralmual/AirWar-
/Game/GameManager.cpp
UTF-8
28,555
2.90625
3
[]
no_license
// // Created by erick on 26/03/17. // #include "GameManager.h" GameManager::GameManager(GLshort width, GLshort height){ this->Width = width; this->Height = height; //Player setUp w/2 - playerSize.x/2 h - playerSize.y Player = new GameObject( glm::vec2( width / 2 - 100.0f / 2, height - 100.0f), //Player position glm::vec2(100.0f, 100.f), //Player size ResourceManager::GetTexture("ship")); //Player texture Player->life = 500; Player->tag = 1; Player->Color = glm::vec3(0.0f , 1.0f , 0.0); } /// Colision detection and position calculation \\\* void GameManager::CheckPlayerCollision() { // AABB - AABB collision GameObject *iterator = nullptr; //Colision detection for player and enemy shots if(!this->Player->hasShield){ for (int i = 0; i < this->enemyShots.sizeOf(); i++) { iterator = this->enemyShots.get(i); // Calls tha auxilary function tho check the axis collision if (this->CheckPlayerCollisionAux(iterator)) { Player->life -= iterator->tag * (9 + this->level); Texture2D auxText; if (Player->life <= 0) { auxText = ResourceManager::GetTexture("death"); playerLifes -= 1; //Dormir el tread un tiempo } else { auxText = ResourceManager::GetTexture("hit"); } iterator->tag = 0; this->animations.push(*new GameObject(iterator->Position, glm::vec2(50.0f, 50.f), auxText)); } } } PowerUp *PUiterator = nullptr; //Colision detection for player powerUps for (int i = 0; i < this->fieldPowerUps.sizeOf(); i++) { //Iterator gets the value of the enemy shot PUiterator = this->fieldPowerUps.get(i); // Collision only if on both axes if ( this->CheckPlayerCollisionAux( PUiterator ) ) { this->playerPowerUps.push_back( *PUiterator ); this->fieldPowerUps.remove(i); } } } bool GameManager::CheckPlayerCollisionAux(GameObject* iterator){ // Collision x-axis? bool collisionX = Player->Position.x + Player->Size.x >= iterator->Position.x && iterator->Position.x + iterator->Size.x >= Player->Position.x; // Collision y-axis? bool collisionY = Player->Position.y + Player->Size.y >= iterator->Position.y && iterator->Position.y + iterator->Size.y >= Player->Position.y; return collisionX && collisionY; } void GameManager::CheckEnemiesCollisions() { // AABB - AABB collision GameObject *iterator = nullptr; GameObject *auxIterator = nullptr; //Colision detection for enemies and player bullets for (int i = 0; i < this->Enemies.sizeOf(); i++) { //Iterator takes the value of the limits of the enemy iterator = this->Enemies.get(i); if(iterator->tag !=7) { glm::vec4 enemyPosition = getTruePosition(iterator); for (int j = 0; j < this->playerShots.sizeOf(); j++) { //AuxIterator takes the value of a shot auxIterator = this->playerShots.get(j); // Calls tha auxilary function tho check the axis collision if (CheckEnemiesCollisionsAux(auxIterator, enemyPosition)) { iterator->life -= auxIterator->tag * (29 + this->level); Texture2D auxText; if (iterator->life <= 0) { this->points += iterator->tag; short powerUpProb = rand() % 12; PowerUp *power = nullptr; switch (powerUpProb) { case 12: { // 12 represents a laser power = new PowerUp(3, glm::vec3(1.0f), 30.f, glm::vec2(iterator->Position.x, iterator->Position.y), ResourceManager::GetTexture("laserPU")); break; } case 11: { // 11 represents missiles power = new PowerUp(2, glm::vec3(1.0f), 30.f, glm::vec2(iterator->Position.x, iterator->Position.y), ResourceManager::GetTexture("missilePU")); break; } case 10: { // 10 represents the shield power = new PowerUp(1, glm::vec3(1.0f), 30.f, glm::vec2(iterator->Position.x, iterator->Position.y), ResourceManager::GetTexture("shield")); break; } default: break; } if (power != nullptr) { this->fieldPowerUps.addLast(*power); } auxText = ResourceManager::GetTexture("death"); } else { auxText = ResourceManager::GetTexture("hit"); } auxIterator->tag = 0; this->animations.push(*new GameObject(auxIterator->Position, glm::vec2(50.0f, 50.f), auxText)); } } } } //Colision detection for player crashing with enemies if(!this->Player->hasShield) { for (int i = 0; i < this->Enemies.sizeOf(); i++) { if (this->Enemies.get(i)->tag != 7) { glm::vec4 enemyPosition = getTruePosition(this->Enemies.get(i)); if (CheckEnemiesCollisionsAux(this->Player, enemyPosition)) { Texture2D auxText; auxText = ResourceManager::GetTexture("death"); Player->life = 0; playerLifes -= 1; this->Enemies.get(i)->life = 0; //Dormir el tread un tiempo this->animations.push(*new GameObject(glm::vec2(enemyPosition.x, enemyPosition.z), glm::vec2(enemyPosition.x - enemyPosition.y, enemyPosition.z - enemyPosition.w), auxText)); this->animations.push(*new GameObject(Player->Position, Player->Size, auxText)); } } } } } bool GameManager::CheckEnemiesCollisionsAux(GameObject* auxIterator, glm::vec4 enemyPosition ){ // Collision x-axis? bool collisionX = auxIterator->Position.x + auxIterator->Size.x >= enemyPosition.x && enemyPosition.y >= auxIterator->Position.x; // Collision y-axis? bool collisionY = auxIterator->Position.y + auxIterator->Size.y >= enemyPosition.z && enemyPosition.w >= auxIterator->Position.y; return collisionX && collisionY; } glm::vec4 GameManager::getTruePosition(GameObject* enemy){ glm::vec4 position; switch(enemy->tag) { //Format: //position = (Xmin, Xmax, Ymin, Ymax) case 1: { //The enemy is a jet position = glm::vec4(enemy->Position.x + 125, enemy->Position.x + 162, enemy->Position.y + 15, enemy->Position.y + 70); break; } case 2: { //The enemy is a bomber position = glm::vec4(enemy->Position.x + 125, enemy->Position.x + 162, enemy->Position.y + 15, enemy->Position.y + 73); break; } case 3: { //The enemy is a tower position = glm::vec4(enemy->Position.x + 20, enemy->Position.x + 80, enemy->Position.y, enemy->Position.y + 160); break; } case 4: { //The enemy is a missile tower position = glm::vec4(enemy->Position.x + 10, enemy->Position.x + 90, enemy->Position.y, enemy->Position.y + 165); break; } case 5: { //The enemy is a kamikaze position = glm::vec4(enemy->Position.x + 275, enemy->Position.x + 310, enemy->Position.y + 110, enemy->Position.y + 175); break; } case 6: { //The enemy is a tank position = glm::vec4(enemy->Position.x + 130, enemy->Position.x + 265, enemy->Position.y + 90, enemy->Position.y + 210); break; } case 8: { //The enemy is the boss position = glm::vec4(enemy->Position.x + 250, enemy->Position.x + 450, enemy->Position.y + 50, enemy->Position.y + 430); break; } } return position; } void GameManager::Draw(SpriteRenderer &renderer) { //Dibujar primero disparos, luego animaciones y finalmente naves para evitar //inconsistencias en la vista del juego GameObject* iterator; for (int i = 0; i < this->playerShots.sizeOf() ; i++) { iterator = this->playerShots.get(i); if((iterator->Position.y < 0.0f) || (iterator->tag == 0)){ this->playerShots.remove(i); } else{ iterator->Draw(renderer); } } for (int i = 0; i < this->enemyShots.sizeOf() ; i++) { iterator = this->enemyShots.get(i); if((iterator->Position.y > this->Height) || (iterator->tag == 0)){ this->enemyShots.remove(i); } else{ iterator->Draw(renderer); } } for (int i = 0; i < this->Enemies.sizeOf() ; i++) { iterator = this->Enemies.get(i); if(iterator->life <= 0){ this->Enemies.remove(i); } else{ iterator->Draw(renderer); } } if(this->Player->life <= 0) { Player->Position = glm::vec2(this->Width / 2 - 100.0f / 2, this->Height - 100.0f); Player->life = 475 + 25*this->level; // Player looses the PU for (int i = 0; i < this->playerPowerUps.sizeOf(); i++){ this->playerPowerUps.pop_back(); } } this->Player->Draw(renderer); for (int i = 0; i < this->animations.sizeOf() ; i++) { this->animations.get()->Draw(renderer); animations.dequeue(); } for (int i = 0; i < this->fieldPowerUps.sizeOf() ; i++) { this->fieldPowerUps.get(i)->Draw(renderer); } } /// Updates and movements \\\* void GameManager::updateShots(GLfloat dt) { GameObject* iterator = nullptr; for (int i = 0; i < this->playerShots.sizeOf(); ++i) { iterator = this->playerShots.get(i); iterator->Position += iterator->Velocity * dt; } for (int i = 0; i < enemyShots.sizeOf(); i++) { iterator = enemyShots.get(i); iterator->Position -= iterator->Velocity * dt; } } void GameManager::updatePowerUps(GLfloat dt) { if(this->playerPowerUps.sizeOf() > 0) { PowerUp *actual = this->playerPowerUps.peek(); if (actual->Activated) { if (actual->Duration <= 0) { Player->tag = 1; Player->hasShield = GL_FALSE; Player->Color = glm::vec3(0.0f, 1.0f, 0.0f); this->playerPowerUps.pop_back(); } else { actual->Duration -= dt; if (Player->hasShield) { Player->Color = glm::vec3(1.0f, 1.0f, 1.0f); } } } } } /// Enemy-related \\\* void GameManager::ControlEnemies(GLfloat dt, GLushort enemyPos) { GameObject* enemy = this->Enemies.get(enemyPos); switch(enemy->tag){ case 1:{ //The enemy is a jet so it should behave like one //Shoot the player if it is on range if( (enemy->Position.x + 163 >= Player->Position.x) && (this->Player->Position.x + 100 >= enemy->Position.x + 125) && ((dt - enemy->dt) >= 0.3f)){ GameObject* shot = new GameObject(glm::vec2(enemy->Position.x + 125, enemy->Position.y + 70) , glm::vec2(SHOT_RADIUS * 2, SHOT_RADIUS * 2), ResourceManager::GetTexture("face"), glm::vec3(1.0f), glm::vec2(0.0f, -400.0f)); shot->tag = 1; enemyShots.addLast(*shot); shot = new GameObject(glm::vec2(enemy->Position.x + 162,enemy->Position.y + 70), glm::vec2(SHOT_RADIUS * 2, SHOT_RADIUS * 2), ResourceManager::GetTexture("face"), glm::vec3(1.0f), glm::vec2(0.0f, -400.0f)); shot->tag = 1; enemyShots.addLast(*shot); enemy->dt = dt; } else { if (this->Player->Position.x - 100 < enemy->Position.x) { enemy->Position.x -= enemy->Velocity.x * dt; } else if (this->Player->Position.x - 100 > enemy->Position.x) { enemy->Position.x += enemy->Velocity.x * dt; } if (this->Player->Position.y - enemy->Position.y > 300) { enemy->Position.y += enemy->Velocity.y * dt; } else if ((this->Player->Position.y - enemy->Position.y < 600) && (enemy->Position.y > 0)) { enemy->Position.y -= enemy->Velocity.y * dt; } enemy->dt -= dt; } break;} case 2:{ //The enemy behaves as a bomber if( (enemy->Position.x + 163 >= Player->Position.x) && (this->Player->Position.x + 100 >= enemy->Position.x + 125) && ((dt - enemy->dt) >= 5)){ GameObject* shot = new GameObject(glm::vec2(enemy->Position.x + 90, enemy->Position.y + 70) , glm::vec2(40 * 2, 20 * 2), ResourceManager::GetTexture("missile"), glm::vec3(1.0f), glm::vec2(0.0f, -200.0f)); shot->tag = 4; shot->Rotation = 3.14; enemyShots.addLast(*shot); shot = new GameObject(glm::vec2(enemy->Position.x + 132, enemy->Position.y + 70), glm::vec2(40 * 2, 20 * 2), ResourceManager::GetTexture("missile"), glm::vec3(1.0f), glm::vec2(0.0f, -200.0f)); shot->tag = 4; shot->Rotation = 3.14; enemyShots.addLast(*shot); enemy->dt = dt; } else { if (this->Player->Position.x - 100 < enemy->Position.x) { enemy->Position.x -= enemy->Velocity.x * dt; } else if (this->Player->Position.x - 100 > enemy->Position.x) { enemy->Position.x += enemy->Velocity.x * dt; } if (this->Player->Position.y > enemy->Position.y) { enemy->Position.y += enemy->Velocity.y * dt; } else if ((this->Player->Position.y < enemy->Position.y) && (enemy->Position.y > 0)) { enemy->Position.y -= enemy->Velocity.y * dt; } enemy->dt -= dt; } break;} case 3:{ //The enemy behaves as a tower if((dt - enemy->dt) >= 0.7f){ GLfloat xVelocity, yVelocity, velocity; velocity = sqrtf(this->Player->Position.x*this->Player->Position.x + this->Player->Position.y*this->Player->Position.y); if (this->Player->Position.x > enemy->Position.x) xVelocity = this->Player->Position.x/velocity * -100 - 300; else xVelocity = this->Player->Position.x/velocity * +100 +300; if (this->Player->Position.y > enemy->Position.y) yVelocity = this->Player->Position.y/velocity * -100 -300; else yVelocity = this->Player->Position.y/velocity * 100 +300; GameObject* shot = new GameObject(glm::vec2(enemy->Position.x + 50, enemy->Position.y + 65) , glm::vec2(5.5f * 2, 5.5f * 2), ResourceManager::GetTexture("face"), glm::vec3(1.0f), glm::vec2( xVelocity, yVelocity)); shot->tag = 3; enemyShots.addLast(*shot); enemy->dt = dt; } else{ enemy->dt -= dt; } break;} case 4:{ //The enemy behaves as a missile tower if((dt - enemy->dt) >= 0.7f) { GLfloat xVelocity, yVelocity, velocity, rotationAngle; velocity = sqrtf(this->Player->Position.x * this->Player->Position.x + this->Player->Position.y * this->Player->Position.y); if (this->Player->Position.x > enemy->Position.x) { xVelocity = this->Player->Position.x / velocity * -100 - 300; rotationAngle = 3.14 / 2; } else { xVelocity = this->Player->Position.x / velocity * +100 + 300; rotationAngle = -3.14 / 2; } if (this->Player->Position.y > enemy->Position.y){ yVelocity = this->Player->Position.y / velocity * -100 - 300; if (rotationAngle > 0) rotationAngle += 3.14 / 4; else rotationAngle -= 3.14 / 4; } else { yVelocity = this->Player->Position.y / velocity * 100 + 300; if (rotationAngle > 0) rotationAngle -= 3.14 / 4; else rotationAngle = 3.14 / 4; } GameObject* shot = new GameObject(glm::vec2(enemy->Position.x + 50, enemy->Position.y + 65) , glm::vec2(40 * 2, 20 * 2), ResourceManager::GetTexture("missile"), glm::vec3(1.0f), glm::vec2( xVelocity, yVelocity)); shot->tag = 4; shot->Rotation = rotationAngle; enemyShots.addLast(*shot); enemy->dt = dt; } else{ enemy->dt -= dt; } break;} case 5:{ //The enemy behaves as a kamikaze glm::vec4 kamikazePos = getTruePosition(enemy); if(this->Player->Position.x < kamikazePos.x){ enemy->Position.x -= enemy->Velocity.x * dt; } else if(this->Player->Position.x > kamikazePos.y){ enemy->Position.x += enemy->Velocity.x * dt; } if(this->Player->Position.y > kamikazePos.z){ enemy->Position.y += enemy->Velocity.y * dt; } else if(( this->Player->Position.y < kamikazePos.w) && (kamikazePos.z > 0)) { enemy->Position.y -= enemy->Velocity.y * dt; } break;} case 6:{ //The enemy behaves as a tank if( (enemy->Position.x + 220 >= Player->Position.x) && (this->Player->Position.x + 100 >= enemy->Position.x + 170) && ((dt - enemy->dt) >= 0.3f)){ GameObject* shot = new GameObject(glm::vec2(enemy->Position.x + 125, enemy->Position.y + 70) , glm::vec2(10 * 2, 10 * 2), ResourceManager::GetTexture("laser"), glm::vec3(1.0f), glm::vec2(0.0f, -400.0f)); shot->tag = 6; enemyShots.addLast(*shot); shot = new GameObject(glm::vec2(enemy->Position.x + 162, enemy->Position.y + 70), glm::vec2(10 * 2, 10 * 2), ResourceManager::GetTexture("laser"), glm::vec3(1.0f), glm::vec2(0.0f, -400.0f)); shot->tag = 6; enemyShots.addLast(*shot); enemy->dt = dt; } else { if (this->Player->Position.x - 100 < enemy->Position.x) { enemy->Position.x -= enemy->Velocity.x * dt; } else if (this->Player->Position.x - 100 > enemy->Position.x) { enemy->Position.x += enemy->Velocity.x * dt; } if (this->Player->Position.y - enemy->Position.y > 600) { enemy->Position.y += enemy->Velocity.y * dt; } else if ((this->Player->Position.y - enemy->Position.y < 600) && (enemy->Position.y > 0)) { enemy->Position.y -= enemy->Velocity.y * dt; } enemy->dt -= dt; } break;} case 7:{ //The enemy behaves as an ally GameObject* realEnemy = this->Enemies.get(0); if( (enemy->Position.x + 220 >= realEnemy->Position.x) && (realEnemy->Position.x + 100 >= enemy->Position.x + 170) && ((dt - enemy->dt) >= 0.3f)){ GameObject shot = *new GameObject(glm::vec2(enemy->Position.x + 4 , enemy->Position.y + 30), glm::vec2(SHOT_RADIUS * 2, SHOT_RADIUS * 2), ResourceManager::GetTexture("face"), glm::vec3(1.0f), INITIAL_SHOT_VELOCITY); shot.tag = Player->tag;// Texture , color velocity this->playerShots.addLast(shot); shot = *new GameObject( glm::vec2(enemy->Position.x + 84.5 , enemy->Position.y + 30), glm::vec2(SHOT_RADIUS * 2, SHOT_RADIUS * 2), ResourceManager::GetTexture("face"), glm::vec3(1.0f), INITIAL_SHOT_VELOCITY); shot.tag = Player->tag; this->playerShots.addLast(shot); enemy->dt = dt; enemy->life -=1; } else { if (realEnemy->Position.x - 100 < enemy->Position.x) { enemy->Position.x -= enemy->Velocity.x * dt; } else if (realEnemy->Position.x - 100 > enemy->Position.x) { enemy->Position.x += enemy->Velocity.x * dt; } enemy->dt -= dt; if (realEnemy->Position.y - enemy->Position.y > 600) { enemy->Position.y += enemy->Velocity.y * dt; } else if ((realEnemy->Position.y - enemy->Position.y < 600) && (enemy->Position.y > 0)) { enemy->Position.y -= enemy->Velocity.y * dt; } } if (enemy->life ==0){ Texture2D auxText; auxText = ResourceManager::GetTexture("death"); animations.push(*new GameObject(enemy->Position, enemy->Size, auxText)); } break; } case 8:{ //The enemy behaves as boss if( (enemy->Position.x + 220 >= Player->Position.x) && (this->Player->Position.x + 100 >= enemy->Position.x + 170) && ((dt - enemy->dt) >= 0.3f)){ GameObject* shot = new GameObject(glm::vec2(enemy->Position.x + 300, this->Enemies.get(0)->Position.y + 380) , glm::vec2(10 * 2, 10 * 2), ResourceManager::GetTexture("laser"), glm::vec3(1.0f), glm::vec2(0.0f, -300.0f)); shot->tag = 8; this->enemyShots.addLast(*shot); shot = new GameObject(glm::vec2(enemy->Position.x + 390, this->Enemies.get(0)->Position.y + 380), glm::vec2(10 * 2, 10 * 2), ResourceManager::GetTexture("laser"), glm::vec3(1.0f), glm::vec2(0.0f, -300.0f)); shot->tag = 8; this->enemyShots.addLast(*shot); enemy->dt = dt; } else{ if(this->Player->Position.x - 100 < enemy->Position.x){ enemy->Position.x -= enemy->Velocity.x * dt; } if(this->Player->Position.x - 100 > enemy->Position.x){ enemy->Position.x += enemy->Velocity.x * dt; } enemy->dt -= dt; } if(this->Player->Position.y - enemy->Position.y > 600){ enemy->Position.y += enemy->Velocity.y * dt; } else if(( this->Player->Position.y - enemy->Position.y < 600) && (enemy->Position.y > 0)){ enemy->Position.y -= enemy->Velocity.y * dt; } break;} default:{ enemy = nullptr; break; } } } void GameManager::generateEnemies() { for (int i = 0; i < 100; ++i) { if((i == 25) || (i == 50) || (i == 75)) { enemySpawn.push(7); i += 1; } enemySpawn.push((rand() % 5) + 1); } enemySpawn.push(8); } void GameManager::spawnEnemy() { GameObject *enemy; switch (*this->enemySpawn.get()){ case 1:{ //A jet is generated enemy = new GameObject (glm::vec2(700 % 1100, 50), glm::vec2(300, 100), ResourceManager::GetTexture("jet"), glm::vec3(1.0f), glm::vec2(125.0f + this->level*25)); enemy->tag = 1; enemy->life = 50 + this->level*25; break;} case 2:{ //A bomber is generated enemy = new GameObject (glm::vec2(rand() % 1100, 50), glm::vec2(300, 100), ResourceManager::GetTexture("bomber"), glm::vec3(1.0f), glm::vec2(50.0f + this->level*25)); enemy->tag = 2; enemy->life = 200 + this->level*25; break;} case 3:{ //A tower is generated enemy = new GameObject (glm::vec2(rand() % 1100, 50), glm::vec2(100, 150), ResourceManager::GetTexture("tower"), glm::vec3(1.0f), glm::vec2(0.0f)); enemy->tag = 3; enemy->life = 250 + this->level*25; break;} case 4:{ //A missile tower is generated enemy = new GameObject (glm::vec2(rand() % 1100, 50), glm::vec2(100, 175), ResourceManager::GetTexture("missileTower"), glm::vec3(1.0f), glm::vec2(0.0f)); enemy->tag = 4; enemy->life = 250 + this->level*25; break;} case 5:{ //A kamikaze is generated enemy = new GameObject (glm::vec2(rand() % 1100, 2), glm::vec2(600, 300), ResourceManager::GetTexture("kamikaze"), glm::vec3(1.0f), glm::vec2(150.0f + this->level*25)); enemy->tag = 5; enemy->life = 50 + this->level*25; break;} case 6:{ //A tank is generated enemy = new GameObject (glm::vec2(rand() % 1100, 2), glm::vec2(400, 300), ResourceManager::GetTexture("tank"), glm::vec3(1.0f), glm::vec2(25.0f + this->level*25 )); enemy->tag = 6; enemy->life = 300 + this->level*25; break;} case 7:{ //A ally is generated enemy = new GameObject (glm::vec2(rand() % 1100, 2), glm::vec2(100, 100), ResourceManager::GetTexture("ally"), glm::vec3(1.0f), glm::vec2(400.0f - this->level*5)); enemy->tag = 7; break;} case 8:{ //A boss is generated enemy = new GameObject (glm::vec2(rand() % 1100, 2), glm::vec2(700, 500), ResourceManager::GetTexture("boss"), glm::vec3(1.0f), glm::vec2(200.0f + this->level*25)); enemy->tag = 8; enemy->life = 500 + this->level*100; break;} default:{ enemy = nullptr; break;} } if(enemy != nullptr){ this->Enemies.addLast(*enemy); } else{ std::cout << "ERROR: Se esta intentando agregar un enemigo que no existe. GameManager::LoadEnemies"; exit(EXIT_FAILURE); } this->enemySpawn.dequeue(); } /// Player Actions \\\* void GameManager::PressTheTrigger(GLfloat dt) { if((dt - this->Player->dt) >= 0.2f) { switch(this->Player->tag) { case 2: { // Position , size GameObject shot = *new GameObject(glm::vec2(Player->Position.x + 25, Player->Position.y ), glm::vec2(40 * 2, 20 * 2), ResourceManager::GetTexture("missile"), glm::vec3(1.0f), INITIAL_SHOT_VELOCITY); shot.tag = Player->tag;// Texture , color velocity this->playerShots.addLast(shot); shot = *new GameObject(glm::vec2(Player->Position.x - 5, Player->Position.y), glm::vec2(40 * 2, 20 * 2), ResourceManager::GetTexture("missile"), glm::vec3(1.0f), INITIAL_SHOT_VELOCITY); shot.tag = Player->tag; this->playerShots.addLast(shot); break; } case 3: { // Position , size GameObject shot = *new GameObject(glm::vec2(Player->Position.x + 30, Player->Position.y + 30), glm::vec2(10 * 2, 10 * 2), ResourceManager::GetTexture("laser"), glm::vec3(1.0f), INITIAL_SHOT_VELOCITY); shot.tag = Player->tag;// Texture , color velocity this->playerShots.addLast(shot); shot = *new GameObject(glm::vec2(Player->Position.x + 60, Player->Position.y + 30), glm::vec2(10 * 2, 10 * 2), ResourceManager::GetTexture("laser"), glm::vec3(1.0f), INITIAL_SHOT_VELOCITY); shot.tag = Player->tag; this->playerShots.addLast(shot); break; } default: { // Position , size GameObject shot = *new GameObject(glm::vec2(Player->Position.x + 30, Player->Position.y + 30), glm::vec2(SHOT_RADIUS * 2, SHOT_RADIUS * 2), ResourceManager::GetTexture("face"), glm::vec3(1.0f), INITIAL_SHOT_VELOCITY); shot.tag = Player->tag;// Texture , color velocity this->playerShots.addLast(shot); shot = *new GameObject(glm::vec2(Player->Position.x + 60, Player->Position.y + 30), glm::vec2(SHOT_RADIUS * 2, SHOT_RADIUS * 2), ResourceManager::GetTexture("face"), glm::vec3(1.0f), INITIAL_SHOT_VELOCITY); shot.tag = Player->tag; this->playerShots.addLast(shot); break; } } this->Player->dt = dt; } else{ this->Player->dt -= dt; } } void GameManager::ActivatePowerUp() { PowerUp* actual = this->playerPowerUps.peek(); if(actual->Type == 3){ Player->tag = 3; } else if(actual->Type == 2){ Player->tag = 2; } else{ Player->hasShield = GL_TRUE; } actual->Activated = GL_TRUE; } DoublyLinkedList<GameObject> &GameManager::getEnemies() { return Enemies; } DoublyLinkedList<GameObject> &GameManager::getEnemyShots() { return enemyShots; } GameObject *GameManager::getPlayer() { return Player; } DoublyLinkedList<GameObject> &GameManager::getPlayerShots() { return playerShots; } GLshort GameManager::getPlayerLifes() const { return playerLifes; } Queue<GLushort> &GameManager::getEnemySpawn() { return enemySpawn; } GLushort GameManager::getPoints() const { return points; } GLushort GameManager::getPlayerPowerUp() { if (this->playerPowerUps.sizeOf() < 0) { return playerPowerUps.peek()->Type; } else{ return 0; } }
true
57efe8ba7febe8388da6d19cceedec03d095b6c5
C++
zmbilx/cxxPrimerPlus6th
/05第五章/5-04-formore.cpp
UTF-8
517
3.28125
3
[]
no_license
#include <iostream> const int ArSize = 16; int main(){ long long factorials[ArSize]; factorials[1] = factorials[0] = 1LL; for (int i=2; i<ArSize; i++){ factorials[i] = i * factorials[i-1]; } for (int i=0; i< ArSize; i++){ std::cout<< i << "! = "<<factorials[i]<<std::endl; } return 0; } /* out: 0! = 1 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = 5040 8! = 40320 9! = 362880 10! = 3628800 11! = 39916800 12! = 479001600 13! = 6227020800 14! = 87178291200 15! = 1307674368000 */
true
acd94b65004b78f675b911cd3493bc69bf1cd6d7
C++
zh593245631/Cpp
/HashTable/hash.h
GB18030
5,973
3.09375
3
[]
no_license
#pragma once //ɢ #include<vector> #include<iostream> using namespace std; namespace CLOSE { enum STATA { EMPTY, DELETE, EXIST }; template<class K, class V> struct HashNode { pair<K, V> _kv; STATA _stata = EMPTY; }; template<class K, class V> class HashTable { public: typedef HashNode<K, V> Node; typedef Node* pNode; public: HashTable(size_t size = 5) { _table.resize(size); _size = 0; } bool insert(const pair<K, V>& kv) { CheckCapcity(); //λӳ size_t index = kv.first % _table.size(); //Ҹط while (_table[index]._stata != EMPTY) { //keyظ if (_table[index]._kv.first == kv.first) return false; ++index; if (index == _table.size()) index = 0; } _table[index]._kv = kv; _table[index]._stata = EXIST; ++_size; return true; } pNode Find(const K & k) { size_t index = k % _table.size(); while (_table[index]._stata != EMPTY) { if (_table[index]._stata == EXIST && _table[index]._kv.first == k) return &_table[index]; ++index; if (index == _table.size()) index = 0; } return nullptr; } bool Erase(const K & k) { pNode ret = Find(k); if (ret) { ret->_stata = DELETE; --_size; return true; } return false; } private: void CheckCapcity() { if (_table.size() == 0 || _size * 10 / _table.size() >= 7) { size_t newS = _table.size() == 0 ? 10 : 2 * _table.size(); HashTable newT(newS); for (int i = 0; i < _table.size(); ++i) { if (_table[i]._stata == EXIST) { newT.insert(_table[i]._kv); } } _table.swap(newT._table); } } private: vector<Node> _table; size_t _size; }; } //----------------------------------------------------------------------------------------- //ɢ template<class V> struct HashNode { HashNode<V>* _next; V _data; HashNode(const V& data) :_next(nullptr) ,_data(data) {} }; //ǰ template <class K, class V, class KeyOfValue, class HashFun> class HashTable; template<class K, class V,class KeyOfValue, class HashFun> struct HIterator { typedef HashNode<V> Node; typedef Node* pNode; typedef HIterator<K, V, KeyOfValue, HashFun> Self; typedef HashTable<K, V, KeyOfValue, HashFun> HT; pNode _node; HT* _ht; HIterator(pNode node,HT* ht) :_node(node) ,_ht(ht) {} V& operator*() { return _node->_data; } V* operator->() { return &_node->_data; } bool operator!=(const Self& it) { return _node != it._node; } //ǰ++ Self& operator++() { if (_node->_next) { _node = _node->_next; } else { KeyOfValue kov; size_t index = _ht->HashIndex(kov(_node->_data), (_ht->_table.size())); ++index; while (index < (_ht->_table.size())) { if (_ht->_table[index]) { _node = _ht->_table[index]; break; } ++index; } if (index == _ht->_table.size()) _node = nullptr; } return *this; } }; template<class K, class V,class KeyOfValue, class HashFun> class HashTable { public: //ԪҪʹϣ˽гԱ template <class K, class V, class KeyOfValue, class HashFun> friend struct HIterator; public: typedef HashNode<V> Node; typedef Node* pNode; typedef HIterator<K, V, KeyOfValue, HashFun> iterator; public: iterator begin() { for (size_t i = 0; i < _table.size(); ++i) { if (_table[i]) return iterator(_table[i],this); } return iterator(nullptr,this); } iterator end() { return iterator(nullptr,this); } pair<iterator,bool> insert(const V& data) { CheckCapacity(); KeyOfValue kov; size_t index = HashIndex(kov(data), _table.size()); pNode cur = _table[index]; while (cur) { if(kov(cur->_data) == kov(data)) return make_pair(iterator(cur,this),false); cur = cur->_next; } cur = new Node(data); //ͷ cur->_next = _table[index]; _table[index] = cur; ++_size; return make_pair(iterator(cur,this),true); } iterator Find(const K& k) { size_t index = HashIndex(k , _table.size()); pNode cur = _table[index]; KeyOfValue kov; while (cur) { if (kov(cur->_data) == k) return iterator(cur,this); cur = cur->_next; } return iterator(nullptr,this); } bool Erase(const K& k) { size_t index = k % _table.size(); pNode cur = _table[index]; KeyOfValue kov; pNode prev = nullptr; while (cur) { if (kov(cur->_data) == k) { if (prev) prev->_next = cur->_next; else _table[index] = cur->_next; --_size; delete cur; return true; } prev = cur; cur = cur->_next; } return false; } private: void CheckCapacity() { if (_size >= _table.size()*3) { //size_t newS = _table.size() == 0 ? 4 : _table.size() * 2; size_t newS = getNextPrime(_table.size()); vector<pNode> newV; newV.resize(newS); KeyOfValue kov; //ɱ for (size_t i = 0; i < _table.size(); ++i) { pNode cur = _table[i]; while (cur) { pNode next = cur->_next; size_t index = HashIndex(kov(cur->_data), newS); cur->_next = newV[index]; newV[index] = cur; cur = next; } _table[i] = nullptr; } _table.swap(newV); } } size_t HashIndex(const K& key, size_t sz) { HashFun hfun; return hfun(key) % sz; } size_t getNextPrime(const size_t prime) { static const int PRIMECOUNT = 28; static const size_t primeList[PRIMECOUNT] = { 53ul, 97ul, 193ul, 389ul, 769ul, 1543ul, 3079ul, 6151ul, 12289ul, 24593ul, 49157ul, 98317ul, 196613ul, 393241ul, 786433ul, 1572869ul, 3145739ul, 6291469ul, 12582917ul, 25165843ul, 50331653ul, 100663319ul, 201326611ul, 402653189ul, 805306457ul, 1610612741ul, 3221225473ul, 4294967291ul }; for (size_t i = 0; i < PRIMECOUNT; ++i) { if (primeList[i] > prime) return primeList[i]; } return primeList[PRIMECOUNT - 1]; } private: vector<pNode> _table; size_t _size = 0; };
true
fad55b3d3d9dc1e7f3a633c62336b582e02caaa9
C++
lcj2393/taller2-apuntadores_y_estructuras
/6-PUNTERO_NNUMEROS_BUSQUEDA.cpp
ISO-8859-10
1,032
3.40625
3
[]
no_license
//EJERCICIO TERMINADO, FUNCIONA CORRECTAMENTE #include <stdio.h> #include <stdlib.h> #include <iostream> using namespace std; void llenar_arreglo(int *,int); void busqueda(int *, int); using namespace std; int main() { int nnum; printf("\nDigite tamao del vector: "); cin>>nnum; int arreglo[nnum],*parreglo=arreglo; llenar_arreglo(parreglo,nnum); busqueda(parreglo,nnum); printf("\n\n"); system("pause"); return 0; } void llenar_arreglo(int *p,int nnum){ for(int i=0;i<nnum;i++){ printf("Ingrese valor %d: ",i+1); scanf("%d",&(*(p+i))); } } void busqueda(int *p, int nnum){ int nbusq; int n=0; do{ printf("\nDigite Valor a Colsultar: "); cin>>nbusq; for(int i=0;i<nnum;i++){ if(*(p+i)==nbusq){ printf("\nEl Valor buscado %d esta en la pocision %p\n",*(p+i),(p+i));n++; } } if(n==0){ printf("\nEl valor ingresado no esta en el Vector\n"); }else{ n=1; } }while(n!=1); }
true
868cff8f9da15012733c74fad8c60190c9f35cb1
C++
salva00/ProgrammiCeck_P1
/EserciziClasse/BMI Calculator/main.cpp
UTF-8
790
3.828125
4
[]
no_license
#include <iostream> //allows program to perform input and output using std::cin; //program uses names from the std namespace using std::cout; using std::endl; int main() { //variables to store weight and height int weight{ 0 }; float height{ 0 }; //prompt the user for their weight and height and read them in cout << "Enter weight (Kgs): "; cin >> weight; cout << "Enter height (m): "; cin >> height; //calculate bmi; float bmi{ weight / (height * height) }; cout << "\nYour BMI is: " << bmi << "\n\n"; //display user's BMI //display BMI information table cout << "BMI VALUES \n"; cout << "Underweight: less than 18.5 \n"; cout << "Normal: between 18.5 and 24.9\n"; cout << "Overweight: between 25 and 29.9 \n"; cout << "Normal: 30 or greater \n"; }
true
93fe5168ad25352e76d1a4109e7b3e337e7faf73
C++
supreme19981021/labworks
/chapt5/5_13/main.cpp
GB18030
1,092
3.703125
4
[]
no_license
//example5_13.cpp:ֵݹʾ #include<iostream> using namespace std; class Base { int b; public: Base(int x) :b(x) {} int getb() { return b; } }; class Derived :public Base { int d; public: Derived(int x, int y) :Base(x), d(y) {} int getd() { return d; } }; int main() { Base b1(11); Derived d1(22, 33); b1 = d1; //1ֵָ cout << "b1.getb() = " << b1.getb() << endl; //cout<<"b1.getd() = "<<b1.getd()<<endl; //ܷеԱ Base *pb1 = &d1; //2ֵָ cout << "pb1->getb() = " << pb1->getb() << endl; //cout<<"pb1->getd() = "<<pb1->getd()<<endl; //ܷеԱ Derived *pd = &d1; Base *pb2 = pd; //3ֵָ cout << "pb2->getb() = " << pb2->getb() << endl; //cout << "pb2->getd() = " << pb2->getd() << endl; //ܷеԱ Base &rb = d1; //4ֵָ cout << "rb.getb() = " << rb.getb() << endl; //cout << "rb.getd() = " << rb.getd() << endl; //ܷеԱ system("pause"); return 0; }
true
706eab7b5cd3208227dcb4a0a357f48f2f46f72d
C++
abc80486/codeBus
/OnlineJudge/PAT/PAT_B_20/1027**.cpp
UTF-8
603
2.90625
3
[]
no_license
//打印沙漏 #include<iostream> using namespace std; int main(){ int N,row=0; char c; cin>>N>>c; for(int i=0;i<N;i++){ if((2*i*(i+2)+1)>N){ row=i-1;break; } } for(int i=row;i>=1;i--){ for(int k=row-i;k>=1;k--) cout<<" "; for(int j=i*2+1;j>=1;j--) cout<<c; cout<<endl; } for(int i=0;i<row;i++) cout<<" "; cout<<c<<endl; for(int i=1;i<=row;i++) { for(int k=row-i;k>=1;k--) cout<<" "; for(int j=i*2+1;j>=1;j--) cout<<c; cout<<endl; } cout<<(N-(2*row*(row+2)+1)); return 0; }
true
7a6d3a25127da8ce7420c804e3d185f97e19f4e2
C++
lonelam/SolveSet
/poj2932.cpp
UTF-8
1,501
2.8125
3
[]
no_license
#include<iostream> #include<vector> #include<iterator> #include<algorithm> #include<cstdio> #include<set> using namespace std; int n; const int maxn = 45000; double x[maxn], y[maxn], r[maxn]; bool inside(int i, int j) { double dx = x[i] - x[j], dy = y[i] - y[j]; return dx * dx + dy * dy <= r[j] * r[j]; } void solve() { vector<pair<double,int> > events; for (int i = 0; i < n; i++) { events.push_back({x[i] - r[i], i}); events.push_back({x[i] + r[i], i + n}); } sort(events.begin(), events.end()); set<pair<double, int> > outers; vector<int> res; for (int i = 0; i < events.size(); i++) { int id = events[i].second % n; if (events[i].second < n) { set<pair<double,int> >::iterator it = outers.lower_bound({y[id], id}); if (it != outers.end() && inside(id, it->second)) continue; if (it != outers.begin() && inside(id, (--it)->second)) continue; res.push_back(id); outers.insert({y[id], id}); } else { outers.erase({y[id], id}); } } sort(res.begin(), res.end()); printf("%d\n", res.size()); for (int i = 0; i < res.size(); i++) { printf("%d%c", res[i] + 1, i + 1 == res.size() ? '\n' : ' '); } } int main() { while(scanf("%d",&n)!=EOF) { for(int i = 0; i < n; i++) { scanf("%lf%lf%lf",r + i, x + i, y + i); } solve(); } }
true
86b84f419c89175ed27d1018b82512496a584022
C++
basanets/SoftwareDesignPatterns
/structural/decorator/Decorator/encryptiondecorator.cpp
UTF-8
484
2.796875
3
[]
no_license
#include "encryptiondecorator.h" EncryptionDecorator::EncryptionDecorator(DataStream *dataStream) : DataStreamDecorator(dataStream) { } std::string EncryptionDecorator::read(uint32_t bytes) { std::string readData = m_dataStream->read(bytes); // decode readData += " decoded"; return readData; } uint32_t EncryptionDecorator::write(const std::string &str) { // encode std::string newData = str + " encoded"; return m_dataStream->write(newData); }
true
abf234ab3ddb8715d3286347ceff0b3c4e3ab842
C++
Zeratul31/leetcode
/261-Graph_Valid_Tree.cpp
UTF-8
2,694
3.203125
3
[]
no_license
class Solution { public: /** * @param n: An integer * @param edges: a list of undirected edges * @return: true if it's a valid tree, or false */ bool validTree(int n, vector<vector> &edges) { // write your code here //条件一:n个node, n-1个edge if( static_cast<int>(edges.size()) != n - 1) { return false; } //convert 成 adjecent list 形式 graph a std::unordered_map<int,std::unordered_set<int>> Graph_In {toGraph(n,edges)}; // Record 已经connected 的 vertex std::unordered_set<int> recorded_node; // iterator std::unordered_map<int,std::unordered_set<int>>::const_iterator it; //Check graph /*for (auto& i : Graph_In) { std::cout << i.first <<" 111111"<<std::endl; for (auto &j : i.second) { std::cout << j << std::endl; } }*/ // Bfs queue 去iterate 每一个 node 和 他的 connection std::queue<int> current_levelNode; // Push root current_levelNode.push(0); // BFS while while(!current_levelNode.empty()){ int current_vertex {current_levelNode.front()}; current_levelNode.pop(); // Record 有了就不加入 if(recorded_node.find(current_vertex) == recorded_node.end()){ recorded_node.emplace(current_vertex); } //找到 graph(adjacent list的 node hash set) it = Graph_In.find(current_vertex); for (auto &i : it->second) { //对于这个 vertex 的 hashset 来说, 如果record 里面没有, 把新的connected vertex 加入 if(recorded_node.find(i) == recorded_node.end()){ recorded_node.emplace(i); //把没有iterate through 的vertex加入 queue ,拓展新vertex里面的connection current_levelNode.push(i); } } } if( static_cast<int>(recorded_node.size()) == n){ return true; } return false; } std::unordered_map<int,std::unordered_set<int>> toGraph(int n,std::vector<std::vector<int>> &edges){ std::unordered_map<int,std::unordered_set<int>> result_graph; for(int i = 0; i < n; i++) { std::unordered_set<int> current_vertex_connection; for(int j = 0; j < edges.size(); j++) { if(edges[j][0] == i){ current_vertex_connection.emplace(edges[j][1]); } else if(edges[j][1] == i){ current_vertex_connection.emplace(edges[j][0]); } } result_graph.emplace(i,current_vertex_connection); } return result_graph; } };
true
0f6f2a1a4a5abbf63a5245ac5db460f30eb5a5f1
C++
FuzeT/LeetCode
/Algorithm/121-180/134_Gas_Station.cpp
UTF-8
1,345
2.78125
3
[]
no_license
#include <iostream> #include <string> #include <sstream> #include <vector> #include <algorithm> #include <map> #include <stack> #include <queue> #include <unordered_map> #include <set> #include <math.h> #include <unordered_set> using namespace std; class Solution { public: int canCompleteCircuit(vector<int>& gas, vector<int>& cost) { if (gas.size() == 0) return -1; if (gas.size() == 1) return gas[0] >= cost[0] ? 0 : -1; int index = 0; int phase = gas.size(); while (index < gas.size() && gas[index] < cost[index]) index++; if (index == gas.size()) return -1; long long contain = gas[index] - cost[index]; int start = getNext(index, phase); while (start != index){ if (contain + gas[start] - cost[start] < 0){ if (index >= getNext(start, phase)) return -1; else { index = getNext(start, phase); while (index<phase && gas[index] < cost[index]) index++; if (index == phase) return -1; start = getNext(index, phase); contain = gas[index] - cost[index]; } } else{ contain = contain + gas[start] - cost[start]; start = getNext(start, phase); } } return index; } int getNext(int start, int phase){ if (start + 1 == phase) return 0; else return start + 1; } int getPre(int start, int phase){ if (start == 0) return phase - 1; else return start - 1; } };
true
2e43333b9752c04dd5073d8ac148f7c8258cda9b
C++
r00tman/f-plotter
/widget.cpp
UTF-8
4,192
2.5625
3
[]
no_license
#include "widget.h" #include <functional> #include <QApplication> #include <QMessageBox> #include <QHBoxLayout> #include <QVBoxLayout> #include <QPushButton> #include <QPen> #include "parser.h" /*---------------------------------------------------------------------*/ /*- Из задачи -*/ /*---------------------------------------------------------------------*/ ld a = 0, b = 0.99, eps1 = 1e-12, eps2 = 1e-6; expr_t expr = parse("x^3+2*x-x+1"); ld f(ld x) { return evaluate(expr, x); } ld fd(ld x) { return (f(x+eps1)-f(x))/eps1; } /*---------------------------------------------------------------------*/ // Newton's method ld auto_solve(func_type fun, func_type fund, ld x0) { const size_t MAXITCOUNT = 1000000; ld xc = x0; for (size_t itcount = 0; itcount < MAXITCOUNT; ++itcount) { ld xn = xc-fun(xc)/fund(xc); if (std::abs(xc - xn) < eps2) { xc = xn; break; } xc = xn; } return xc; } Widget::Widget(QWidget *parent) : QWidget(parent) { QVBoxLayout *lay = new QVBoxLayout; QHBoxLayout *setlay = new QHBoxLayout; QPushButton *setxy = new QPushButton("Set range"); QPushButton *setf = new QPushButton("Set f(x)"); QPushButton *nextit = new QPushButton("Next iteration"); QPushButton *autosolve = new QPushButton("Auto solve"); const double INF = 1e12; setxy->setDefault(true); ltext = new QDoubleSpinBox(); ltext->setMinimum(-INF); ltext->setMaximum(INF); ltext->setValue(-5); rtext = new QDoubleSpinBox(); rtext->setMinimum(-INF); rtext->setMaximum(INF); rtext->setValue(5); ltext->setMaximumWidth(100); rtext->setMaximumWidth(100); setlay->addWidget(ltext); setlay->addWidget(rtext); setlay->addWidget(setxy); m_fun_text = new QLineEdit(); m_fun_text->setMinimumWidth(100); setlay->addWidget(m_fun_text); setlay->addWidget(setf); setlay->addWidget(nextit); setlay->addWidget(autosolve); setlay->addStretch(); lay->addLayout(setlay); m_plot_widget = new PlotWidget(); m_plot_widget->m_function = f; lay->addWidget(m_plot_widget); this->setLayout(lay); connect(setxy, SIGNAL(clicked()), this, SLOT(setLR())); connect(setf, SIGNAL(clicked()), this, SLOT(setF())); connect(nextit, SIGNAL(clicked()), this, SLOT(nextIt())); connect(autosolve, SIGNAL(clicked()), this, SLOT(autoSolve())); setMinimumHeight(100); // just something reasonable not crushing all of the resizing thing (preventing division by zero) started = false; } Widget::~Widget() { } void Widget::setLR() { m_plot_widget->setLRrange(this->ltext->value(), this->rtext->value()); m_plot_widget->autoFitY(); started = false; m_plot_widget->m_opt_elements.clear(); repaint(); } void Widget::setF() { expr = parse(m_fun_text->text().toStdString()); setLR(); } void Widget::nextIt() { if (!started) { // set a starting point for the Newton's method (middle of the screen) xc = (m_plot_widget->m_cs.invX(0)+m_plot_widget->m_cs.invX(m_plot_widget->width()))/2; started = true; } ld xn = xc-f(xc)/fd(xc); // Tangent QLineF line(QPointF(xc, f(xc)), QPointF(xc+1, f(xc)+fd(xc)*1)); QPen pen(Qt::red); // Paint old lines in gray if (m_plot_widget->m_opt_elements.size() > 0) { m_plot_widget->m_opt_elements[m_plot_widget->m_opt_elements.size()-1].second = QPen(Qt::darkGray); } // Add a new one m_plot_widget->m_opt_elements.push_back(PlotWidget::line_type(line, pen)); xc = xn; repaint(); } void Widget::autoSolve() { ld x0 = (m_plot_widget->m_cs.invX(0)+m_plot_widget->m_cs.invX(m_plot_widget->width()))/2; QString str; for (eps2 = 0.1; eps2 > 1e-12; eps2 /= 10) { ld x = auto_solve(f, fd, x0); str += "x=" + QString::number((double)x, '.', 12) + " f(x)=" + QString::number((double)f(x)) + " eps2=" + QString::number((double)eps2) + "\n"; } QMessageBox::information(this, "Solution", str); }
true
e5954e70dff72d9d7e61ddfe77d786cc38dfd9dd
C++
niceSimon7/ObserveDesign2
/ConcreteSubject.cpp
UTF-8
412
2.578125
3
[]
no_license
#include "ConcreateSubject.h" void ConcreteSubject::Attach(Observer *pObserver) { m_ObserverList.push_back(pObserver); } void ConcreteSubject::Detach(Observer *pObserver) { m_ObserverList.remove(pObserver); } void ConcreteSubject::Notify() { list<Observer* >::iterator it = m_ObserverList.begin(); while(it != m_ObserverList.end()) { (*it)->Update(m_iState); ++it; } }
true
6f994e56b0070c675032bb51de6a71e008c726d0
C++
ZoranPandovski/al-go-rithms
/data_structures/Graphs/graphsearch/transitive_closure_graph/cpp/transitive_closure_graph_floyd_warshall.cpp
UTF-8
1,860
3.640625
4
[ "CC0-1.0" ]
permissive
#include <iostream> #include <vector> #include <bitset> // Floyd-Warshall algorithm. Time complexity: O(n ^ 3) void transitive_closure_graph(std::vector<std::vector<int>> &graph) { int n = (int) graph.size(); for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { graph[i][j] |= (graph[i][k] & graph[k][j]); } } } } const int MAX_N = 2000; // maximum possible number of vertixes (only for bitset version) // Floyd-Warshall algorithm with bitset. // Time complexity: O(n ^ 3), but with 1/bitset constant. (~32 or ~64 times faster than naive) void transitive_closure_graph_bitset(std::vector<std::vector<int>> &graph) { int n = (int) graph.size(); std::vector<std::bitset<MAX_N>> d(n); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { d[i][j] = graph[i][j]; } } for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) { if (d[i][k]) { d[i] |= d[k]; } } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { graph[i][j] = d[i][j]; } } } int main() { std::cout << "Enter the number of vertexes:" << std::endl; int n; std::cin >> n; std::cout << "Enter the adjacency matrix (consisting from 0 and 1):" << std::endl; std::vector<std::vector<int>> graph(n, std::vector<int>(n)); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { std::cin >> graph[i][j]; } } transitive_closure_graph_bitset(graph); std::cout << "Result:\n"; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { std::cout << graph[i][j] << " "; } std::cout << "\n"; } return 0; }
true
6474138e2f5f573964dea6c6b99bcfd2b6865319
C++
aLagoG/kygerand-notebook
/data_structures/suffix_array/test.cpp
UTF-8
461
2.59375
3
[]
no_license
#include "catch.hpp" #include "nLog2n.h" using Catch::Matchers::Equals; TEST_CASE("banana", "[SuffixArray]") { vector<int> v{1, 0, 13, 0, 13, 0}; vector<int> ans{5, 3, 1, 0, 4, 2}; REQUIRE_THAT(buildSuffixArray(v), Equals(ans)); } TEST_CASE("yabbadabbado", "[SuffixArray]") { vector<int> v{24, 0, 1, 1, 0, 3, 0, 1, 1, 0, 3, 14}; vector<int> ans{1, 6, 4, 9, 3, 8, 2, 7, 5, 10, 11, 0}; REQUIRE_THAT(buildSuffixArray(v), Equals(ans)); }
true
acfb4e2cd6660902cad60a1f5c21c3489055428c
C++
rahat664/online-judge-solved
/Codechef/Decimal to binary.cpp
UTF-8
380
2.65625
3
[]
no_license
#include<stdio.h> int main() { int Test,num,i,j,binary[10]; scanf("%d",&Test); for(i = 0; i < Test; i++) { scanf("%d",&num); for(j = 0; num > 0 ; j++) { binary[j] = num % 2; num = num/2; } for(j = j-1;j >=0; j--) { printf("%d",binary[j]); } printf("\n"); } }
true
57a0caa0970d6fcabbc659b75a940460669b9aba
C++
tricktreat/oj-program
/zju_septembertest/euleriancircuit.cpp
UTF-8
1,180
2.65625
3
[]
no_license
#include<iostream> #include<cstring> #include<algorithm> #define MAXN 1010 using namespace std; int n,m; int fa[MAXN]; int height[MAXN]; int degree[MAXN]; void init(){ for (int i = 0; i < n; ++i) { fa[i]=i; height[i]=0; } } int find(int x){ if(fa[x]==x){ return x; } return fa[x]=find(fa[x]); } void merge(int x,int y){ x=fa[x]; y=fa[y]; if(x==y){ return; } if(height[x]>height[y]){ fa[y]=x; }else{ fa[x]=y; if(height[x]==height[y]){ height[y]++; } } } int main(){ while(cin>>n&&n!=0&&cin>>m&&m!=0 ){ init(); memset(degree,0, sizeof(degree)); for (int i = 0; i < m; ++i) { int f,t; cin>>f>>t; degree[f]++; degree[t]++; merge(f,t); } int flag=0,cnt=0; for (int i = 0; i < n; ++i) { if(fa[i]==i){ cnt++; } if(degree[i]%2!=0) { flag = 1; } } if(cnt==1&&flag==0){ cout<<"1\n"; }else{ cout<<"0\n"; } } }
true
f65a211289b9b96f67f05c631bd2fe4e63aa0c74
C++
KGoinger/coj
/oj练习六_1(拆礼物,我怎么想的这么复杂).cpp
UTF-8
728
3.109375
3
[]
no_license
#include<iostream> #include<cstring> using namespace std; int main() { char s[60]; int count=0; cin>>s; for(int i=0;i<strlen(s);i++) { if(s[i]=='('&&s[i+1]!=')'&&s[i+1]!='p') { count++; continue; } if(s[i]=='('&&s[i+1]==')') { i=i+2; continue; } if(s[i]==')'&&s[i+1]=='(')i=i+2; if(s[i]=='p') { cout<<count; return 0; } if(s[i]=='('&&s[i+1]=='p') { cout<<(count+1); return 0; } } } /*#include<iostream> #include<string> using namespace std; int main(void) { string s; while (cin >> s) { int n = 0; for (int i=0;i<s.size();++i) { if (s[i] == '(') ++n; else if (s[i] == ')') --n; else { cout << n << endl; break; } } } return 0; }*/
true
7399a7775f3084c19a651181161c9de4d91d716b
C++
BOJ-expedition/Challenges-of-the-week
/2021W01/hyeseong/자유/Programmers/12940 최대공약수와 최소공배수 (Lv.1).cpp
UTF-8
604
3.25
3
[]
no_license
// https://programmers.co.kr/learn/courses/30/lessons/12940 #include <string> #include <vector> using namespace std; vector<int> solution(int n, int m) { vector<int> answer; int x = n < m ? n : m; int y = n < m ? m : n; for (int i = x; i >= 1; --i) { if ((x % i == 0) && (y % i == 0)) { answer.emplace_back(i); break; } } for (int i = y; i <= x*y; ++i) { if ((i % x == 0) && (i % y == 0)) { answer.emplace_back(i); break; } } return answer; }
true
a18d83b3c8420eac0377014e20df11201468b02c
C++
Bampereza/Algoritmos
/Ejemplo If else.cpp
UTF-8
541
3.390625
3
[]
no_license
/* SENTENCIA IF */ /* if (condicion) { Instrucciones "SI se cumple la condicion" ; } else{ Instrucciones "si NO se cumple la condicion"; } */ #include<iostream> using namespace std; int main (){ int numero = 2021; int dato; cout << "BIENVENIDO, ALGORITMO CON ESTRUCTURA SI" << "\n"; cout << "INGRESE UN NUMERO:" << "\n"; cin >> dato; if ( dato < numero ){ // CONDICION cout << "EL NUMERO ES MENOR A 2021" << "\n" ; } else { cout << "EL NUMERO ES MAYOR A 2021" << "\n"; } return 0; }
true
86bd653d940830a620690184f244e8b5739b10b2
C++
tapeshpuhan/ApplicationSourceCode
/stl_algorithm/copy/copy.cpp
UTF-8
439
3.21875
3
[]
no_license
#include <iostream> #include <algorithm> #include <vector> #include <set> template<typename T> void print(T&& var) { for(auto& at : var) { std::cout<<at<<std::endl; } } int main() { std::set<int> v_ = {1,2,3,4,5,7,8,9,3,7,8,}; std::vector<int> s_; std::move(v_.begin(),v_.end(),std::back_inserter(s_)); //std::copy(v_.cbegin(),v_.cend(),s_.begin()); print(s_); print(v_); return 0; }
true