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
fbd8c5b350f9003e0cdf365d7af31cc0b974a85f
C++
648664838/simpleproject
/mysqldbserver/mysqldbserver/clog.h
UTF-8
850
2.53125
3
[]
no_license
#pragma once #include<stdarg.h> #include<stdio.h> #include<time.h> #include<stdlib.h> #include <cstring> using namespace std; #define MAX_LOG_BUFF_LENGTH 86400 namespace af { void InitLogCategory(); void ShutDownCategory(); void LogInfo(const char* vLogName, const char* vFmt, ...); void LogError(const char* vLogName, const char* vFmt, ...); void LogDebug(const char* vLogName, const char* vFmt, ...); void LogWarn(const char* vLogName, const char* vFmt, ...); /*class CVaListBuff { public: CVaListBuff() { memset(mBuff, 0, sizeof(mBuff)); } char * GetBuffByFormat(const char** vFmt,...) { memset(mBuff, 0, sizeof(mBuff)); if (vFmt && *vFmt) { va_list ap; va_start(ap, *vFmt); vsprintf(mBuff, *vFmt, ap); va_end(ap); } return mBuff; } public: char mBuff[MAX_LOG_BUFF_LENGTH]; }; static CVaListBuff VaListBuff;*/ };
true
4bdd8986944d758b70412581ae1ee46b088ea5bc
C++
AJIOB/GraphProcessing
/Holt Model/Graph.h
UTF-8
2,753
3.328125
3
[]
no_license
#pragma once #include <map> #include <set> #include "Namespace.h" #include "Node.h" NAMESPACE_BEGIN template <typename T> class Graph { std::set<Node<T>*> nodes; Node<T>* findOrCreateNode(const T& nodeID); public: /** * Build the non-oriented graph with edges. * Key in multimap - starting node. * Value in multimap - ending node. */ explicit Graph(const std::multimap<T, T>& edges = std::multimap<T, T>()); Graph(const Graph& other); ~Graph(); Graph& operator=(const Graph& other); bool isHaveCycles() const; void addEdge(const T& begin, const T& end); void removeEdge(const T& begin, const T& end); }; template <typename T> Node<T>* Graph<T>::findOrCreateNode(const T& nodeID) { auto it = std::find_if(nodes.begin(), nodes.end(), [&nodeID](Node<T>* elem) { return (nodeID == elem->getId()); }); if (it != nodes.end()) { return *it; } Node<T>* res = new Node<T>(nodeID); nodes.insert(res); return res; } template <typename T> Graph<T>::Graph(const std::multimap<T, T>& edges) { for (auto it = edges.begin(); it != edges.end(); ++it) { findOrCreateNode(it->first)->addConnection(findOrCreateNode(it->second)); } } template <typename T> Graph<T>::Graph(const Graph& other) { for (auto node : other.nodes) { auto connectedNodeIDs = node->getConnectedIDs(); for (auto rightNodeID : connectedNodeIDs) { findOrCreateNode(node.getID())->addConnection(findOrCreateNode(rightNodeID)); } } } template <typename T> Graph<T>::~Graph() { for (auto it = nodes.begin(); it != nodes.end(); ++it) { delete *it; } } template <typename T> Graph<T>& Graph<T>::operator=(const Graph& other) { if (&other == this) { return *this; } for (auto node : nodes) { delete node; } for (auto node : other.nodes) { auto connectedNodeIDs = node->getConnectedIDs(); for (auto rightNodeID : connectedNodeIDs) { findOrCreateNode(node.getID())->addConnection(findOrCreateNode(rightNodeID)); } } return *this; } template <typename T> bool Graph<T>::isHaveCycles() const { std::set<Node<T>*> nodesToCheck = nodes; while (!nodesToCheck.empty()) { std::set<Node<T>*> noCycleElements; if ((*nodesToCheck.begin())->isInCycle(std::set<Node<T>*>(), noCycleElements)) { return true; } //remove all elements, that not in cycles for (auto it = noCycleElements.begin(); it != noCycleElements.end(); ++it) { nodesToCheck.erase(*it); } } return false; } template <typename T> void Graph<T>::addEdge(const T& begin, const T& end) { findOrCreateNode(begin)->addConnection(findOrCreateNode(end)); } template <typename T> void Graph<T>::removeEdge(const T& begin, const T& end) { findOrCreateNode(begin)->removeConnection(findOrCreateNode(end)); } NAMESPACE_END
true
94f5874108beba09aa4ec6a338d291bbae2a14a5
C++
bg1bgst333/Sample
/com/OleInitialize/OleInitialize/src/OleInitialize/OleInitialize/OleInitialize.cpp
SHIFT_JIS
1,358
2.921875
3
[ "MIT" ]
permissive
// wb_t@C̃CN[h #include <windows.h> // WWindowsAPI #include <tchar.h> // TCHAR^ // _tWinMain֐̒` int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nShowCmd){ // ϐ̐錾 HRESULT hr; // COM̏̌ʂi[hr. TCHAR tszText[256] = {0}; // \eLXgtszText(256){0}ŏ. // OLȄ hr = OleInitialize(NULL); // OleInitializeNULLnď. if (hr == S_OK){ // S_OKȂ珉. _stprintf(tszText, _T("OleInitialize success!\n")); // "OleInitialize success!"tszTextɃZbg. OutputDebugString(tszText); // OutputDebugStringtszTexto. } else if (hr == S_FALSE){ // S_FALSEȂ炷łɏĂ. _stprintf(tszText, _T("Already initialized!\n")); // "Already initialized!"tszTextɃZbg. OutputDebugString(tszText); // OutputDebugStringtszTexto. } else{ // ȊO. _stprintf(tszText, _T("Failed!\n")); // "Failed!"tszTextɃZbg. OutputDebugString(tszText); // OutputDebugStringtszTexto. return -1; // -1ԂĈُI. } // OLȄI. OleUninitialize(); // OleUninitializeŏI. // vȌI. return 0; // 0ԂďI. }
true
52d4156be7cae4564b22e415353ac621db0ab13c
C++
msamual/CPP_Piscine
/module00/ex01/includes/Contact.hpp
UTF-8
1,357
2.953125
3
[]
no_license
#ifndef CONTACT_H # define CONTACT_H # include <iostream> # include <string.h> # include <iomanip> class Contact { public: Contact(); ~Contact(); std::string getFirstName(); std::string getLastName(); std::string getNickName(); std::string getLogin(); std::string getPostalAddress(); std::string getEmailAddress(); std::string getPhoneNumber(); std::string getBirthDate(); std::string getFavoriteMeal(); std::string getUnderwearColor(); std::string getDarkestSecret(); void setFirstName(); void setLastName(); void setNickName(); void setLogin(); void setPostalAddress(); void setEmailAddress(); void setPhoneNumber(); void setBirthDate(); void setFavoriteMeal(); void setUnderwearColor(); void setDarkestSecret(); void displayInfo(); private: std::string firstName; std::string lastName; std::string nickName; std::string login; std::string postalAddress; std::string emailAddress; std::string phoneNumber; std::string birthDate; std::string favoriteMeal; std::string underwearColor; std::string darkestSecret; }; #endif
true
e13ef07a6bf874c71a7f0313b7b69678d47fd8f3
C++
AliOsm/CompetitiveProgramming
/CodeForces/961D. Pair Of Lines.cpp
UTF-8
1,240
2.65625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int const N = 1e5 + 1; int n, a[N], b[N]; bool vis[N]; bool solve(int i1, int i2) { memset(vis, false, sizeof vis); long long s1, s2; int v1 = -1, v2 = -1; s1 = b[i2] - b[i1]; s2 = a[i2] - a[i1]; vis[i1] = vis[i2] = true; int cnt = 2; for(int i = 0; i < n; ++i) { if(vis[i]) continue; long long ss1, ss2; ss1 = b[i] - b[i1]; ss2 = a[i] - a[i1]; if(s2 * ss1 == s1 * ss2) { vis[i] = true; ++cnt; } else { if(v1 == -1) v1 = i; else if(v2 == -1) v2 = i; } } if(n - cnt <= 2) { return true; } long long e1, e2; e1 = b[v2] - b[v1]; e2 = a[v2] - a[v1]; vis[v1] = vis[v2] = true; cnt += 2; for(int i = 0; i < n; ++i) { if(vis[i]) continue; long long ss1, ss2; ss1 = b[i] - b[v1]; ss2 = a[i] - a[v1]; if(e2 * ss1 == e1 * ss2) { vis[i] = true; ++cnt; } } if(cnt == n) { return true; } return false; } int main() { cin >> n; for(int i = 0; i < n; ++i) cin >> a[i] >> b[i]; if(n <= 2) { cout << "YES" << endl; return 0; } if(solve(0, 1) || solve(0, 2) || solve(1, 2)) cout << "YES" << endl; else cout << "NO" << endl; return 0; }
true
8001fe384ceaba69dab9a1be549ea6b3ddd691c4
C++
Girl-Code-It/Beginner-CPP-Submissions
/Megha/Milestone-19(sorting)/insertion sort/Insertion sort.cp
UTF-8
505
3.53125
4
[]
no_license
//insertion sort #include <iostream> using namespace std; void insertionSort(int arr[],int n){ for(int i=1;i<n;i++){ int value=arr[i]; int hole = i; while(hole>0 && arr[hole-1]>value){ arr[hole]=arr[hole-1]; hole=hole-1; } arr[hole]=value; } } int main() { int n; cin>>n; int arr[n+1]; for(int i=0;i<n;i++){ cin>>arr[i]; } insertionSort(arr,n); for(int i=0;i<n;i++){ cout<<arr[i]<<" "; } }
true
b3712b26b3699d57e2ba4cc3d1e6d2cccfd7a704
C++
shvedovskiy/huffman
/main.cpp
UTF-8
3,494
3.25
3
[]
no_license
#include <iostream> #include <fstream> #include <string> #include <vector> #include <list> #include <map> class Node { public: int _number; char _symbol; Node *_left, *_right; Node() { } Node(Node* l, Node* r) : _left(l), _right(r) { // from sons _number = l->_number + r->_number; } friend std::less<Node>; }; class CompareSons { public: bool operator() (const Node* left, const Node* right) const { return left->_number < right->_number; } }; void printTree(Node* root, size_t k = 1) { if (root != nullptr) { printTree(root->_left, k+3); for (size_t i = 0; i != k; ++i) std::cout << " "; if (root->_symbol) std::cout << root->_number << " (" << root->_symbol << ")" << std::endl; else std::cout << root->_number << std::endl; printTree(root->_right, k+3); } } std::map<char, std::vector<bool>> buildTable(Node* root) { std::vector<bool> code; std::map<char, std::vector<bool> > table; if (root->_left != nullptr) { code.push_back(0); buildTable(root->_left); } if (root->_right != nullptr) { code.push_back(1); buildTable(root->_right); } if (root->_left == nullptr && root->_right == nullptr) table[root->_symbol] = code; code.pop_back(); return table; } std::map<char, std::vector<bool>> encode(char* filename) { std::map<char, int> map_cnt; std::list<Node*> list_of_pairs; std::ifstream infile(filename); while(!infile.eof()) { char ch = infile.get(); map_cnt[ch]++; } for (std::map<char, int>::iterator it = map_cnt.begin(); it != map_cnt.end(); ++it) { Node* pNode = new Node(); pNode->_symbol = it->first; pNode->_number = it->second; list_of_pairs.push_back(pNode); } while (list_of_pairs.size() != 1) { list_of_pairs.sort(CompareSons()); Node* sonleft = list_of_pairs.front(); list_of_pairs.pop_front(); Node* sonright = list_of_pairs.front(); list_of_pairs.pop_front(); Node* parent = new Node(sonleft, sonright); list_of_pairs.push_back(parent); } Node* root = list_of_pairs.front(); std::map<char, std::vector<bool>> table = buildTable(root); for (auto it = table.begin(); it != table.end(); ++it) { std::cout << it->first << ": "; std::vector<bool>& vec = it->second; for (std::vector<bool>::iterator itt = vec.begin(); itt != vec.end(); ++itt) std::cout << *itt << " "; std::cout << std::endl; } infile.close(); return table; } void decode(std::map<char, std::vector<bool>> table, char* inputfilename, char* outputfilename) { std::ifstream infile(inputfilename); std::ofstream outfile(outputfilename); int cnt = 0; char buf = 0; // 8 zeros while (!infile.eof()) { char ch = infile.get(); std::vector<bool> bites = table[ch]; for (int j = 0; j != bites.size(); ++j) { buf = buf | bites[j] << (7 - cnt); cnt++; if (cnt == 8) { cnt = 0; outfile << buf; buf = 0; } } } infile.close(); outfile.close(); } int main() { std::map<char, std::vector<bool>> table = encode("1.txt"); decode(table, "1.txt", "output.bin"); }
true
9034c35108c466062b92cf895f1864df6e3775a8
C++
adrianrodriguesm/Ray-Tracer
/src/Math/BoundingBox.cpp
UTF-8
3,674
3.015625
3
[ "Apache-2.0" ]
permissive
#include "pch.h" #include "BoundingBox.h" #include "Core/Constant.h" namespace rayTracer { //-------------------------------------------------------------------- - default constructor AABB::AABB() { Min = Vec3(-1.0f, -1.0f, -1.0f); Max = Vec3(1.0f, 1.0f, 1.0f); } // --------------------------------------------------------------------- assignment operator AABB AABB::operator= (const AABB& rhs) { if (this == &rhs) return (*this); Min = rhs.Min; Max = rhs.Max; return (*this); } // --------------------------------------------------------------------- inside // used to test if a ray starts inside a grid bool AABB::IsInside(const Vec3& p) { return ((p.x > Min.x && p.x < Max.x) && (p.y > Min.y && p.y < Max.y) && (p.z > Min.z && p.z < Max.z)); } // --------------------------------------------------------------------- compute centroid Vec3 AABB::Centroid() { return (Min + Max) / 2; } // --------------------------------------------------------------------- extend AABB void AABB::Extend(AABB box) { if (Min.x > box.Min.x) Min.x = box.Min.x; if (Min.y > box.Min.y) Min.y = box.Min.y; if (Min.z > box.Min.z) Min.z = box.Min.z; if (Max.x < box.Max.x) Max.x = box.Max.x; if (Max.y < box.Max.y) Max.y = box.Max.y; if (Max.z < box.Max.z) Max.z = box.Max.z; } // --------------------------------------------------------------------- AABB intersection bool AABB::Intercepts(const Ray& ray, float& t) { /**/ Vec3 dirfrac; // r.dir is unit direction vector of ray dirfrac.x = 1.0f / ray.Direction.x; dirfrac.y = 1.0f / ray.Direction.y; dirfrac.z = 1.0f / ray.Direction.z; // lb is the corner of AABB with minimal coordinates - left bottom, rt is maximal corner // r.org is origin of ray const Vec3& lb = Min; const Vec3& rt = Max; float t1 = (lb.x - ray.Origin.x) * dirfrac.x; float t2 = (rt.x - ray.Origin.x) * dirfrac.x; float t3 = (lb.y - ray.Origin.y) * dirfrac.y; float t4 = (rt.y - ray.Origin.y) * dirfrac.y; float t5 = (lb.z - ray.Origin.z) * dirfrac.z; float t6 = (rt.z - ray.Origin.z) * dirfrac.z; // find largest entering t value float tmin = std::max({ std::min(t1, t2), std::min(t3, t4), std::min(t5, t6) }); // find smallest exiting t value float tmax = std::min({ std::max(t1, t2), std::max(t3, t4), std::max(t5, t6) }); // Condition for a hit // if tmax < 0, ray (line) is intersecting AABB, but the whole AABB is behind us if (tmax < EPSILON) return false; // if tmin > tmax, ray doesn't intersect AABB if (tmin > tmax) return false; t = tmin; return true; /** / double t0, t1; float ox = ray .Origin.x; float oy = ray.Origin.y; float oz = ray.Origin.z; float dx = ray.Direction.x; float dy = ray.Direction.y; float dz = ray.Direction.z; float x0 = Min.x; float y0 = Min.y; float z0 = Min.z; float x1 = Max.x; float y1 = Max.y; float z1 = Max.z; float tx_Min, ty_Min, tz_Min; float tx_Max, ty_Max, tz_Max; float a = 1.0 / dx; if (a >= 0) { tx_Min = (x0 - ox) * a; tx_Max = (x1 - ox) * a; } else { tx_Min = (x1 - ox) * a; tx_Max = (x0 - ox) * a; } float b = 1.0 / dy; if (b >= 0) { ty_Min = (y0 - oy) * b; ty_Max = (y1 - oy) * b; } else { ty_Min = (y1 - oy) * b; ty_Max = (y0 - oy) * b; } float c = 1.0 / dz; if (c >= 0) { tz_Min = (z0 - oz) * c; tz_Max = (z1 - oz) * c; } else { tz_Min = (z1 - oz) * c; tz_Max = (z0 - oz) * c; } //largest entering t value t0 = MAX3(tx_Min, ty_Min, tz_Min); //smallest exiting t value t1 = MIN3(tx_Max, ty_Max, tz_Max); t = (t0 < 0) ? t1 : t0; return (t0 < t1&& t1 > 0); /**/ } }
true
dacc39c0fdc8428a0e932ae117a296d2c899811c
C++
Mishiev711/Code-Samples
/Collision/CollisionLibrary/CollisionLib.cpp
UTF-8
29,590
2.921875
3
[]
no_license
#include "../../PreCompiled.h" #include "CollisionLib.h" #include <math.h> /************************************************ * Filename: CollisionLib.cpp * Date: 06/08/2015 * Mod. Date: 07/10/2015 * Mod. Initials: MM * Author: Mitchel Mishiev * Purpose: To hold all collisions functions *************************************************/ /******************************************** * CalculatePlane(): Creates a plane and offset out of three points * * Ins: _tpointA, _tpointB, _tpointC * * Outs: _tplane * * Returns: None * * Mod. Date 06/19/2015 * Mod. Initials: MM ********************************************/ void CalculatePlane(tPlane &_tplane, const XMFLOAT3& _tpointA, const XMFLOAT3& _tpointB, const XMFLOAT3& _tpointC) { XMFLOAT3 tPointA = XMFLOAT3( (_tpointB.x - _tpointA.x), (_tpointB.y - _tpointA.y), (_tpointB.z - _tpointA.z) ); XMFLOAT3 tPointB = XMFLOAT3( (_tpointC.x - _tpointB.x), (_tpointC.y - _tpointB.y), (_tpointC.z - _tpointB.z) ); FXMVECTOR tVectorA = DirectX::XMLoadFloat3(&tPointA); FXMVECTOR tVectorB = DirectX::XMLoadFloat3(&tPointB); XMVECTOR tNormal = DirectX::XMLoadFloat3(&_tplane.m_tNormal); XMVECTOR tNormalResults = DirectX::XMVector3Cross(tVectorA, tVectorB); DirectX::XMStoreFloat3(&_tplane.m_tNormal, tNormalResults); tNormal = DirectX::XMLoadFloat3(&_tplane.m_tNormal); tNormalResults = DirectX::XMVector3Normalize(tNormal); DirectX::XMStoreFloat3(&_tplane.m_tNormal, tNormalResults); tNormal = DirectX::XMLoadFloat3(&_tplane.m_tNormal); FXMVECTOR tVectorPoint = DirectX::XMLoadFloat3(&tPointA); XMVECTOR tOffsetResults = DirectX::XMVector3Dot(tNormal, tVectorPoint); DirectX::XMStoreFloat3(&_tplane.m_tNormal, tOffsetResults); } /******************************************** * IdentifyPointToPlane(): Perform a half-space test. * Returns 1 if the point is on or in front of the plane. * Returns 2 if the point is behind the plane. * * Ins: _tplane, _tpoint * * Outs: None * * Returns: int * * Mod. Date 06/19/2015 * Mod. Initials: MM ********************************************/ int IdentifyPointToPlane(const tPlane& _tplane, const XMFLOAT3& _tpoint) { XMVECTOR tNormal = DirectX::XMLoadFloat3(&_tplane.m_tNormal); XMVECTOR tPoint = DirectX::XMLoadFloat3(&_tpoint); XMVECTOR tNormalResults = DirectX::XMVector3Dot(tNormal, tPoint); XMFLOAT3 tPlaneNormal; DirectX::XMStoreFloat3(&tPlaneNormal, tNormalResults); if (tPlaneNormal.x - _tplane.m_fOffset > 0) return 1; else return 2; } /******************************************** * IdentifySphereToPlane(): Perform a sphere to point test. * Returns 1 if the sphere is in front of the plane. * Returns 2 if the sphere is behind the plane. * Returns 3 if the sphere is in the middle the plane. * * Ins: _tplane, _tsphere * * Outs: None * * Returns: int * * Mod. Date 06/19/2015 * Mod. Initials: MM ********************************************/ int IdentifySphereToPlane(const tPlane& _tplane, const tSphere& _tsphere) { XMVECTOR tNormal = DirectX::XMLoadFloat3(&_tplane.m_tNormal); XMVECTOR tCenter = DirectX::XMLoadFloat3(&_tsphere.m_tCenter); XMVECTOR tNormalResults = DirectX::XMVector3Dot(tNormal, tCenter); XMFLOAT3 tPlaneNormal; DirectX::XMStoreFloat3(&tPlaneNormal, tNormalResults); if (tPlaneNormal.x - _tplane.m_fOffset > _tsphere.m_fRadius) return 1; else if (tPlaneNormal.x - _tplane.m_fOffset > -_tsphere.m_fRadius) return 2; else return 3; } /******************************************** * IdentifyAABBToPlane(): Performs a AABB-to-plane test. * Returns 1 if the aabb is in front of the plane. * Returns 2 if the aabb is behind the plane. * Returns 3 if the aabb straddles the plane. * * Ins: _tplane, _tsphere * * Outs: None * * Returns: int * * Mod. Date 06/19/2015 * Mod. Initials: MM ********************************************/ int IdentifyAABBtoPlane(const tPlane& _tplane, const tAABB& _taabb) { XMVECTOR tMin = XMLoadFloat3(&_taabb.m_tMin); XMVECTOR tMax = XMLoadFloat3(&_taabb.m_tMax); XMFLOAT3 tCenterPoint; DirectX::XMStoreFloat3(&tCenterPoint, (tMin + tMax ) * 0.5f); XMVECTOR tCenter = XMLoadFloat3(&tCenterPoint); XMFLOAT3 tExtent; DirectX::XMStoreFloat3(&tExtent, ( tMax - tCenter )); float fRadius = (tExtent.x * abs(_tplane.m_tNormal.x)) + (tExtent.y * abs(_tplane.m_tNormal.y)) + (tExtent.z * abs(_tplane.m_tNormal.z)); tSphere tSphere; tSphere.m_tCenter = tCenterPoint; tSphere.m_fRadius = fRadius; return IdentifySphereToPlane(_tplane, tSphere); } /******************************************** * BuildFrustum(): Calculates the corner points and planes of the frustum based upon input values. * Should call ComputePlane. * * Ins: _fFov, _fNearDist, _fFarDist, _fRatio, _tcamXform * * Outs: _tfrustum * * Returns: None * * Mod. Date 06/16/2015 * Mod. Initials: MM ********************************************/ void BuildFrustum(tFrustum& _tfrustum, float _fFov, float _fNearDist, float _fFarDist, float _fRatio, const XMFLOAT4X4& _tcamXform) { } /******************************************** * FrustumToSphere(): Perform a Sphere-to-Frustum check. * Returns true if the sphere is inside. * False if not. * * Ins: _tfrustum, _tsphere * * Outs: None * * Returns: bool * * Mod. Date 06/16/2015 * Mod. Initials: MM ********************************************/ bool FrustumToSphere(const tFrustum& _tfrustum, const tSphere& _tsphere) { return false; } /******************************************** * FrustumToAABB(): Perform a AABB-to-Frustum check. * Returns true if the AABB is inside. * False if not. * * Ins: _tfrustum, _taabb * * Outs: None * * Returns: bool * * Mod. Date 06/16/2015 * Mod. Initials: MM ********************************************/ bool FrustumToAABB(const tFrustum& _tfrustum, const tAABB& _taabb) { return false; } /******************************************** * AABBtoAABB(): Returns true if the AABBs collide. * False if not. * * Ins: _taabbA, _taabbB * * Outs: None * * Returns: bool * * Mod. Date 06/16/2015 * Mod. Initials: MM ********************************************/ bool AABBtoAABB(const tAABB& _taabbA, const tAABB& _taabbB) { if (_taabbA.m_tMax.x < _taabbB.m_tMin.x || _taabbA.m_tMin.x > _taabbB.m_tMax.x) { return false; } else if (_taabbA.m_tMax.y < _taabbB.m_tMin.y || _taabbA.m_tMin.y > _taabbB.m_tMax.y) { return false; } else if (_taabbA.m_tMax.z < _taabbB.m_tMin.z || _taabbA.m_tMin.z > _taabbB.m_tMax.z) { return false; } else return true; } /******************************************** * SphereToSphere(): Returns true if the Spheres collide. * False if not. * * Ins: _tsphereA, _tsphereB * * Outs: None * * Returns: bool * * Mod. Date 06/20/2015 * Mod. Initials: MM ********************************************/ bool SphereToSphere(const tSphere& _tsphereA, const tSphere& _tsphereB) { //Get the combined radius of both sphere's center float fCombinedRadius = _tsphereA.m_fRadius + _tsphereB.m_fRadius; //Get the distance between both sphere's center XMVECTOR tCenterA = XMLoadFloat3(&_tsphereA.m_tCenter); XMVECTOR tCenterB = XMLoadFloat3(&_tsphereB.m_tCenter); XMFLOAT3 tDistance; DirectX::XMStoreFloat3(&tDistance, tCenterA - tCenterB); //Get the distance magnitude XMVECTOR tDist = XMLoadFloat3(&tDistance); XMVECTOR tLength = XMVector3Length(tDist); XMFLOAT3 tMagnitude; DirectX::XMStoreFloat3(&tMagnitude, tLength); //Check to see if the distance's magnitude is less than the combined radius //If it is, return true. Else return false. if (tMagnitude.x < fCombinedRadius) { return true; } else { return false; } } /******************************************** * SphereToAABB(): Returns true if the sphere collides with the AABB. * False if not. * * Ins: _tsphere, _taabb * * Outs: None * * Returns: bool * * Mod. Date 06/20/2015 * Mod. Initials: MM ********************************************/ bool SphereToAABB(const tSphere& _tsphere, const tAABB& _taabb) { //Get the closestpoint of the aabb from the sphere's center XMFLOAT3 tClosestPoint = XMFLOAT3(0, 0, 0); ClosestPointOnAABB(tClosestPoint, _tsphere.m_tCenter, _taabb); //Find the distance from the closest point to the sphere center XMVECTOR tAABBClosest = XMLoadFloat3(&tClosestPoint); XMVECTOR tCenter = XMLoadFloat3(&_tsphere.m_tCenter); XMFLOAT3 tDistance; DirectX::XMStoreFloat3(&tDistance, tAABBClosest - tCenter); //Get the magnitude of the distance XMVECTOR tDistanceResults = XMLoadFloat3(&tDistance); XMVECTOR tLength = XMVector3Length(tDistanceResults); XMFLOAT3 tMagnitude; DirectX::XMStoreFloat3(&tMagnitude, tLength); //Check to see if the distance's magnitude is less than the radius //If it is, return true. Else return false. if (tMagnitude.x <= _tsphere.m_fRadius) { return true; } else return false; } /******************************************** * CapsuleToSphere(): Returns true if the Capsule collides with the Sphere. * False if not. * * Ins: _tcapsule, _tsphere * * Outs: None * * Returns: bool * * Mod. Date 07/03/2015 * Mod. Initials: MM ********************************************/ bool CapsuleToSphere(const tCapsule& _tcapsule, const tSphere& _tsphere) { //Find the Closest Point of Capsule A using the Sphere's Center. XMFLOAT3 tTestPoint = ClosestPointLineSegment(_tcapsule.m_tsegment, _tsphere.m_tCenter); //Get the combined radius of the capsule and the sphere float fCombinedRadius = _tcapsule.m_fRadius + _tsphere.m_fRadius; //Get the distance from the test point to the sphere center XMVECTOR tCenterA = XMLoadFloat3(&tTestPoint); XMVECTOR tCenterB = XMLoadFloat3(&_tsphere.m_tCenter); XMFLOAT3 tDistance; DirectX::XMStoreFloat3(&tDistance, tCenterA - tCenterB); //Find the magnitude of the distance XMVECTOR tDist = XMLoadFloat3(&tDistance); XMVECTOR tLength = XMVector3Length(tDist); XMFLOAT3 tMagnitude; DirectX::XMStoreFloat3(&tMagnitude, tLength); //Check to see if the distance's magnitude is less than the combined radius //If it is, return true. Else return false. if (tMagnitude.x < fCombinedRadius) { return true; } else { return false; } } /******************************************** * CapsuleToAABB(): Returns true if the Capsule collides with the AABB. * False if not. * * Ins: _tcapsule, _taabb * * Outs: None * * Returns: bool * * Mod. Date 06/21/2015 * Mod. Initials: MM ********************************************/ bool CapsuleToAABB(const tCapsule& _tcapsule, const tAABB& _taabb) { //Get AABB CenterPoint XMVECTOR tMin = XMLoadFloat3(&_taabb.m_tMin); XMVECTOR tMax = XMLoadFloat3(&_taabb.m_tMax); XMFLOAT3 tAABBCenterPoint; DirectX::XMStoreFloat3(&tAABBCenterPoint, (tMin + tMax) * 0.5f); //Get the AABB Half-Extents XMVECTOR tAABBCenter = XMLoadFloat3(&tAABBCenterPoint); XMFLOAT3 tAABBHalfExtent; DirectX::XMStoreFloat3(&tAABBHalfExtent, tMax - tAABBCenter); //Get segment midpoint XMVECTOR tStartPoint = XMLoadFloat3(&_tcapsule.m_tsegment.m_tStart); XMVECTOR tEndPoint = XMLoadFloat3(&_tcapsule.m_tsegment.m_tEnd); XMFLOAT3 tMidPoint; DirectX::XMStoreFloat3(&tMidPoint, (tStartPoint + tEndPoint) * 0.5f); //Get HalfLength XMVECTOR tMid = XMLoadFloat3(&tMidPoint); XMFLOAT3 tHalfLength; DirectX::XMStoreFloat3(&tHalfLength, tEndPoint - tMid); //Midpoint = midpoint - center DirectX::XMStoreFloat3(&tMidPoint, tMid - tAABBCenter); //Try world coordinates axes as separating axes float adx = abs(tHalfLength.x); if (abs(tMidPoint.x) > tAABBHalfExtent.x + adx + _tcapsule.m_fRadius) { return false; } float ady = abs(tHalfLength.y); if (abs(tMidPoint.y) > tAABBHalfExtent.y + ady + _tcapsule.m_fRadius) { return false; } float adz = abs(tHalfLength.z); if (abs(tMidPoint.z) > tAABBHalfExtent.z + adz + _tcapsule.m_fRadius) { return false; } //Add in an Epsilon term to counteract arithmetic errors when segment is (near) parallel to a coordinate axis adx += FLT_EPSILON; ady += FLT_EPSILON; adz += FLT_EPSILON; //Try cross products of segment direction vector with coordinate axes if (abs(tMidPoint.y * tHalfLength.z - tMidPoint.z * tHalfLength.y) > tAABBHalfExtent.y * adz + tAABBHalfExtent.z * ady + _tcapsule.m_fRadius) { return false; } if (abs(tMidPoint.z * tHalfLength.x - tMidPoint.x * tHalfLength.z) > tAABBHalfExtent.x * adz + tAABBHalfExtent.z * adx + _tcapsule.m_fRadius) { return false; } if (abs(tMidPoint.x * tHalfLength.y - tMidPoint.y * tHalfLength.x) > tAABBHalfExtent.x * ady + tAABBHalfExtent.y * adx + _tcapsule.m_fRadius) { return false; } //No separating axis found, segment must be overlapping AABB return true; } /******************************************** * CapsuleToCapsule(): Returns true if the Capsule collides with another Capsule. * False if not. * * Ins: _tcapsuleA, _tcapsuleB * * Outs: None * * Returns: bool * * Mod. Date 06/20/2015 * Mod. Initials: MM ********************************************/ bool CapsuleToCapsule(const tCapsule& _tcapsuleA, const tCapsule& _tcapsuleB) { float fDistanceA, fDistanceB; XMFLOAT3 tClosestPointA, tClosestPointB; float fDistanceTo = ClosestPointSegmentSegment(_tcapsuleA.m_tsegment, _tcapsuleB.m_tsegment, fDistanceA, fDistanceB, tClosestPointA, tClosestPointB); float fCombinedRadius = _tcapsuleA.m_fRadius + _tcapsuleB.m_fRadius; float tSquaredRadius = fCombinedRadius * fCombinedRadius; if (fDistanceTo <= tSquaredRadius) { return true; } else { return false; } } /******************************************** * RayToSphere(): Returns true if a Ray has collided with a Sphere. * False if not. * * Ins: _tray, _tsphere * * Outs: None * * Returns: bool * * Mod. Date 07/10/2015 * Mod. Initials: MM ********************************************/ bool RayToSphere(const tRay& _tray, const tSphere& _tsphere) { //Find the distance between the closest point and the sphere's center XMVECTOR tRayStartPoint = XMLoadFloat3(&_tray.m_tStartPoint); XMVECTOR tSphereCenter = XMLoadFloat3(&_tsphere.m_tCenter); XMFLOAT3 tLengthVector; DirectX::XMStoreFloat3(&tLengthVector, tSphereCenter - tRayStartPoint); //Now calculate the dot between the distance and the direction XMVECTOR tDirection = XMLoadFloat3(&_tray.m_tRayDirection); XMVECTOR tDistance = XMLoadFloat3(&tLengthVector); XMVECTOR tDirectDot = XMVector3Dot(tDistance, tDirection); XMFLOAT3 tDirectDotResult; DirectX::XMStoreFloat3(&tDirectDotResult, tDirectDot); //Now calculate the dot of the distance by itself XMVECTOR tDistDot = XMVector3Dot(tDistance, tDistance); XMFLOAT3 tDistDotResult; DirectX::XMStoreFloat3(&tDistDotResult, tDistDot); //Now find 'c' by using the distance dot result - the squared radius float fSquaredRadius = _tsphere.m_fRadius * _tsphere.m_fRadius; float c = tDistDotResult.x - fSquaredRadius; //If the the ray's startpoint is outside of the sphere AND if the ray is pointing away from the sphere, return false if (c > 0.0f && tDirectDotResult.x > 0.0f) { return false; } //Now calculate the discriminant, and see if its negative, if so return false float fDiscriminant = tDirectDotResult.x * tDirectDotResult.x - c; if (fDiscriminant < 0.0f) { return false; } //If you made it to this point, your intersecting with the sphere return true; } /******************************************** * RayToAABB(): Returns true if a Ray has collided with an AABB. * False if not. * * Ins: _tray, _tsphere * * Outs: None * * Returns: bool * * Mod. Date 07/13/2015 * Mod. Initials: MM ********************************************/ bool RayToAABB(const tRay& _tray, const tAABB& _taabb) { //Setup the functions min and max float fmin = 0.0f; float fmax = FLT_MAX; //Store all variables passed in into float arrays for the for loop float fMax[3], fMin[3], fDirection[3], fStartPoint[3]; //Max setup fMax[0] = _taabb.m_tMax.x; fMax[1] = _taabb.m_tMax.y; fMax[2] = _taabb.m_tMax.z; //Min setup fMin[0] = _taabb.m_tMin.x; fMin[1] = _taabb.m_tMin.y; fMin[2] = _taabb.m_tMin.z; //Direction setup fDirection[0] = _tray.m_tRayDirection.x; fDirection[1] = _tray.m_tRayDirection.y; fDirection[2] = _tray.m_tRayDirection.z; //Startpoint setup fStartPoint[0] = _tray.m_tStartPoint.x; fStartPoint[1] = _tray.m_tStartPoint.y; fStartPoint[2] = _tray.m_tStartPoint.z; //Now check on all 3 axises for collision for (unsigned int i = 0; i < 3; i++) { //if the absolute value of a direction is less than the float_epsilon, if (abs(fDirection[i]) < FLT_EPSILON) { //the ray is parallel to the axis, return false if (fStartPoint[i] < fMin[i] || fStartPoint[i] > fMax[i]) { return false; } } else { //Compute intersection of the ray with the near and far plane of the axis float fObjectOrientedDirection = 1.0f / fDirection[i]; float fNear = (fMin[i] - fStartPoint[i]) * fObjectOrientedDirection; float fFar = (fMax[i] - fStartPoint[i]) * fObjectOrientedDirection; //Make fNear be intersecting with fFar if (fNear > fFar) { swap(fNear, fFar); } //Compute the intersection of axis intersection intervals fmin = max(fmin, fNear); fmax = min(fmax, fFar); //If fmin is greater than fmax, return false if (fmin > fmax) { return false; } } } //If it made it to this point, the Ray has collided on all Axises, return true return true; } /******************************************** * ClosestPointOnAABB(): Finds the closest point on an aabb from a given point * * Ins: _tPointA, _taabb * * Outs: _tClosestPoint * * Returns: None * * Mod. Date 06/19/2015 * Mod. Initials: MM ********************************************/ void ClosestPointOnAABB(XMFLOAT3& _tClosestPoint, const XMFLOAT3& _tPointA, const tAABB& _taabb) { //Use the pointA passed in to check against the min and max of the aabb XMVECTOR tPoint = XMLoadFloat3(&_tPointA); XMFLOAT3 tTempPoint; DirectX::XMStoreFloat3(&tTempPoint, tPoint); //On each axis, see if the point is either greater than the man or less than the min //If its greater than the max, set the point's axis to the max. //If its less than the min, set the point's axis to the min. //X Axis if (tTempPoint.x < _taabb.m_tMin.x) { tTempPoint.x = _taabb.m_tMin.x; } if (tTempPoint.x > _taabb.m_tMax.x) { tTempPoint.x = _taabb.m_tMax.x; } //Y Axis if (tTempPoint.y < _taabb.m_tMin.y) { tTempPoint.y = _taabb.m_tMin.y; } if (tTempPoint.y > _taabb.m_tMax.y) { tTempPoint.y = _taabb.m_tMax.y; } //Z Axis if (tTempPoint.z < _taabb.m_tMin.z) { tTempPoint.z = _taabb.m_tMin.z; } if (tTempPoint.z > _taabb.m_tMax.z) { tTempPoint.z = _taabb.m_tMax.z; } //Store the point into the closestpoint variable and send it back. XMVECTOR tClosestPoint = XMLoadFloat3(&tTempPoint); DirectX::XMStoreFloat3(&_tClosestPoint, tClosestPoint); } /******************************************** * ClosestPointLineSegment(): Finds the closest point on an capsule from a given point * * Ins: _tcapsule, _tTestPoint * * Outs: None * * Returns: XMFLOAT3 * * Mod. Date 06/21/2015 * Mod. Initials: MM ********************************************/ XMFLOAT3 ClosestPointLineSegment(tSegment _tsegment, XMFLOAT3 _tTestPoint) { //Calculate a vector from the start point to the end point XMVECTOR tStartPoint = XMLoadFloat3(&_tsegment.m_tStart); XMVECTOR tEndPoint = XMLoadFloat3(&_tsegment.m_tEnd); XMFLOAT3 tLengthVector; DirectX::XMStoreFloat3(&tLengthVector, tEndPoint - tStartPoint); //Normalize the LengthVector to find the Normal XMVECTOR tLengVector = XMLoadFloat3(&tLengthVector); XMVECTOR tNormal = DirectX::XMVector3Normalize(tLengVector); //Calculate the vector from the start point to the test point XMVECTOR tTestVector = XMLoadFloat3(&_tTestPoint); XMFLOAT3 tVector; DirectX::XMStoreFloat3(&tVector, tTestVector - tStartPoint); //Calculate the dot product of the normal and the vector XMVECTOR tVec = XMLoadFloat3(&tVector); XMVECTOR tDotProduct = XMVector3Dot(tNormal, tVec); XMFLOAT3 tDot; XMFLOAT3 tClosestPoint; DirectX::XMStoreFloat3(&tDot, tDotProduct); //Check to see if the Dot Product of Normal and Vector is less than zero if so //The Closest Point is the Start Point if (tDot.x < 0.0f) { tClosestPoint = _tsegment.m_tStart; return tClosestPoint; } //Check to see if the Dot Product of Normal and Vector is greater than length of the line segment. If so //The Closest Point is the End Point XMVECTOR tLeng = XMVector3Length(tLengVector); XMFLOAT3 tLength; DirectX::XMStoreFloat3(&tLength, tLeng); if (tDot.x > tLength.x) { tClosestPoint = _tsegment.m_tEnd; return tClosestPoint; } //Scale the normal to get Normal's Prime XMFLOAT3 tNormalPrime; DirectX::XMStoreFloat3(&tNormalPrime, tNormal * tDotProduct); //Add Normal Prime with the start point to get the closest point XMVECTOR tNPrime = XMLoadFloat3(&tNormalPrime); DirectX::XMStoreFloat3(&tClosestPoint, tStartPoint + tNPrime); //Return the ClosestPoint return tClosestPoint; } /******************************************** * ClosestPointOnRay(): Finds the closest point on a Ray from a given point * * Ins: _tray, _tTestPoint * * Outs: None * * Returns: XMFLOAT3 * * Mod. Date 07/10/2015 * Mod. Initials: MM ********************************************/ XMFLOAT3 ClosestPointOnRay(tRay _tray, XMFLOAT3 _tTestPoint) { //Calculate a vector from the start point to the end point XMVECTOR tStartPoint = XMLoadFloat3(&_tray.m_tStartPoint); XMVECTOR tTestPoint = XMLoadFloat3(&_tTestPoint); XMFLOAT3 tLengthVector; DirectX::XMStoreFloat3(&tLengthVector, tTestPoint - tStartPoint); //Now Calculate the Dot Product of the Normal and the LenghVector XMVECTOR tLengVector = XMLoadFloat3(&tLengthVector); XMVECTOR tNormal = XMLoadFloat3(&_tray.m_tRayDirection); XMVECTOR tDot = XMVector3Dot(tNormal, tLengVector); XMFLOAT3 tDotResults; DirectX::XMStoreFloat3(&tDotResults, tDot); //Now check to see if the DotResults is less than Zero. //If so then the ClosetPoint is the StartPoint of the Ray. XMFLOAT3 tClosestPoint; if (tDotResults.x < 0.0f) { tClosestPoint = _tray.m_tStartPoint; return tClosestPoint; } // If it's not, than find the normal's prime XMFLOAT3 tNormalPrime; DirectX::XMStoreFloat3(&tNormalPrime, tNormal * tDot); //Add Normal Prime with the start point to get the closest point XMVECTOR tNPrime = XMLoadFloat3(&tNormalPrime); DirectX::XMStoreFloat3(&tClosestPoint, tStartPoint + tNPrime); //Return the ClosestPoint return tClosestPoint; } /******************************************** * ClosestPointSegmentSegment(): Finds the closestpoint between two segments. * It also return the distance between both segments * * Ins: _tSegmentA, _tSegmentB, _fDistanceA, _fDistanceB, _tClosestPointA, _tClosestPointB * * Outs: None * * Returns: float * * Mod. Date 07/10/2015 * Mod. Initials: MM ********************************************/ float ClosestPointSegmentSegment(tSegment _tSegmentA, tSegment _tSegmentB, float& _fDistanceA, float& _fDistanceB, XMFLOAT3& _tClosestPointA, XMFLOAT3& _tClosestPointB) { //Find the direction of Segment A XMVECTOR tStartPointA = XMLoadFloat3(&_tSegmentA.m_tStart); XMVECTOR tEndPointA = XMLoadFloat3(&_tSegmentA.m_tEnd); XMFLOAT3 tDirectionA; DirectX::XMStoreFloat3(&tDirectionA, tEndPointA - tStartPointA); //Find the direction of Segment B XMVECTOR tStartPointB = XMLoadFloat3(&_tSegmentB.m_tStart); XMVECTOR tEndPointB = XMLoadFloat3(&_tSegmentB.m_tEnd); XMFLOAT3 tDirectionB; DirectX::XMStoreFloat3(&tDirectionB, tEndPointB - tStartPointB); //Find the range between both segment's startpoints XMFLOAT3 tRange; DirectX::XMStoreFloat3(&tRange, tStartPointA - tStartPointB); //Find the Squared Length of Segment A XMVECTOR tDirectA = XMLoadFloat3(&tDirectionA); XMVECTOR tDotA = XMVector3Dot(tDirectA, tDirectA); XMFLOAT3 tSquaredLengthA; DirectX::XMStoreFloat3(&tSquaredLengthA, tDotA); //Find the Squared Length of Segment B XMVECTOR tDirectB = XMLoadFloat3(&tDirectionB); XMVECTOR tDotB = XMVector3Dot(tDirectB, tDirectB); XMFLOAT3 tSquaredLengthB; DirectX::XMStoreFloat3(&tSquaredLengthB, tDotB); //Find f XMVECTOR tRanged = XMLoadFloat3(&tRange); XMVECTOR tDotF = XMVector3Dot(tDirectB, tRanged); XMFLOAT3 tF; DirectX::XMStoreFloat3(&tF, tDotF); //Check if both segments degenerate into points if (tSquaredLengthA.x <= FLT_EPSILON && tSquaredLengthB.x <= FLT_EPSILON) { //Since both points degenerate, set both distances to 0.0f. _fDistanceA = _fDistanceB = 0.0f; //Then set both closestpoints to the startpoint of each segment _tClosestPointA = _tSegmentA.m_tStart; _tClosestPointB = _tSegmentB.m_tStart; //Find the dot between both closestpoints and return the results XMVECTOR tClosestPointA = XMLoadFloat3(&_tClosestPointA); XMVECTOR tClosestPointB = XMLoadFloat3(&_tClosestPointB); XMVECTOR tDotResults = XMVector3Dot(tClosestPointA - tClosestPointB, tClosestPointA - tClosestPointB); XMFLOAT3 tResults; DirectX::XMStoreFloat3(&tResults, tDotResults); return tResults.x; } //If the first segments degenerates into a point ... if (tSquaredLengthA.x <= FLT_EPSILON) { _fDistanceA = 0.0f; _fDistanceB = tF.x / tSquaredLengthB.x; _fDistanceB = Clamp(_fDistanceB, 0.0f, 1.0f); } else { //Find C XMVECTOR tDotC = XMVector3Dot(tDirectA, tRanged); XMFLOAT3 tC; DirectX::XMStoreFloat3(&tF, tDotC); //If the second segments degenerates into a point ... if (tSquaredLengthB.x < FLT_EPSILON) { _fDistanceA = -tC.x / tSquaredLengthA.x; _fDistanceB = 0.0f; _fDistanceA = Clamp(_fDistanceA, 0.0f, 1.0f); } else { //The General nondegenerate case starts here //Find L XMVECTOR tDotL = XMVector3Dot(tDirectA, tDirectB); XMFLOAT3 tL; DirectX::XMStoreFloat3(&tL, tDotL); //Get the Denom float fDenom = (tSquaredLengthA.x * tSquaredLengthB.x) - (tL.x * tL.x); //If segments are not parallel, compute the closestpoint on L1 and L2 //and Clamp to segment S1. Else, make Distance A equal Zero. if (fDenom != 0.0f) { _fDistanceA = Clamp(((tL.x * tF.x) - (tC.x * tSquaredLengthB.x)) / fDenom, 0.0f, 1.0f); } else { _fDistanceA = 0.0f; } //Compute point on L2 closest to S1 _fDistanceB = (tL.x * _fDistanceA + tF.x) / tSquaredLengthB.x; //If _fDistanceB less than Zero, Clamp _fDistanceA, else if _fDistanceB is greater than One, Clamp _fDistanceB if (_fDistanceB < 0.0f) { _fDistanceA = -tC.x / tSquaredLengthA.x; _fDistanceB = 0.0f; _fDistanceA = Clamp(_fDistanceA, 0.0f, 1.0f); } else if (_fDistanceB > 1.0f) { _fDistanceA = tL.x - tC.x; _fDistanceB = 1.0f; _fDistanceA = Clamp(_fDistanceA, 0.0f, 1.0f); } } } //Find the _tClosestPointA DirectX::XMStoreFloat3(&_tClosestPointA, tStartPointA + tDirectA * _fDistanceA); DirectX::XMStoreFloat3(&_tClosestPointB, tStartPointB + tDirectB * _fDistanceB); //Find the dot between both closestpoints and return the results XMVECTOR tClosestPointA = XMLoadFloat3(&_tClosestPointA); XMVECTOR tClosestPointB = XMLoadFloat3(&_tClosestPointB); XMVECTOR tDotResults = XMVector3Dot(tClosestPointA - tClosestPointB, tClosestPointA - tClosestPointB); XMFLOAT3 tResults; DirectX::XMStoreFloat3(&tResults, tDotResults); return tResults.x; } /******************************************** * Clamp(): Clamps N to lie within the range [Min, Max] * * Ins: _fN, _fMin, _fMax * * Outs: None * * Returns: float * * Mod. Date 07/10/2015 * Mod. Initials: MM ********************************************/ float Clamp(float _fN, float _fMin, float _fMax) { if (_fN < _fMin) { return _fMin; } if (_fN > _fMax) { return _fMax; } return _fN; } bool RayPlaneIntersect(float _fPlaneMin, float _fPlaneMax, float _fStart, float _fEnd, float& tbenter, float& tbexit) { float raydir = _fEnd - _fStart; // ray parallel to the planes if (fabs(raydir) < 0.000000001f) { // ray parallel to the planes, but ray not inside the planes if (_fStart < _fPlaneMin || _fStart > _fPlaneMax) { return false; } // ray parallel to the planes, but ray inside the planes else { return true; } } // plane's enter and exit parameters float tsenter = (_fPlaneMin - _fStart) / raydir; float tsexit = (_fPlaneMax - _fStart) / raydir; // order the enter / exit values. if (tsenter > tsexit) { swap(tsenter, tsexit); } // make sure the plane interval and the current box intersection interval overlap if (tbenter > tsexit || tsenter > tbexit) { // nope. Ray missed the box. return false; } // the plane and current intersection interval overlap else { // update the intersection interval tbenter = max(tbenter, tsenter); tbexit = min(tbexit, tsexit); return true; } } bool SegmentToAABB(const tAABB& _tAABB, const XMFLOAT3& _xmStart, const XMFLOAT3& _xmEnd, float& _fThisDist, float _fPriorDist) { // initialise to the segment's boundaries. float tenter = 0.0f, texit = 1.0f; // test X planes if (!RayPlaneIntersect(_tAABB.m_tMin.x, _tAABB.m_tMax.x, _xmStart.x, _xmEnd.x, tenter, texit)) { return false; } // test Y planes if (!RayPlaneIntersect(_tAABB.m_tMin.y, _tAABB.m_tMax.y, _xmStart.y, _xmEnd.y, tenter, texit)) { return false; } // test Z planes if (!RayPlaneIntersect(_tAABB.m_tMin.z, _tAABB.m_tMax.z, _xmStart.z, _xmEnd.z, tenter, texit)) { return false; } // all intersections in the green. Return the first time of intersection, tenter. if (tenter > 0 && tenter < _fPriorDist) { _fThisDist = tenter; return true; } else return false; }
true
6650c67c8bb91b534e67900704cbc63587674d33
C++
wsavoie/SmarticleSim
/matlabScripts/newSimScripts/codegen/lib/generatePackingFromSimDatPLANE/projPointOnPlane.cpp
UTF-8
6,171
2.53125
3
[]
no_license
// // Academic License - for use in teaching, academic research, and meeting // course requirements at degree granting institutions only. Not for // government, commercial, or other organizational use. // File: projPointOnPlane.cpp // // MATLAB Coder version : 4.0 // C/C++ source code generated on : 20-Dec-2018 12:28:38 // // Include Files #include <string.h> #include "rt_nonfinite.h" #include "generatePackingFromSimDatPLANE.h" #include "projPointOnPlane.h" #include "bsxfun.h" #include "sum.h" #include "crossProduct3d.h" // Function Definitions // // PROJPOINTONPLANE Return the orthogonal projection of a point on a plane // // PT2 = projPointOnPlane(PT1, PLANE); // Compute the (orthogonal) projection of point PT1 onto the plane PLANE, // given as [X0 Y0 Z0 VX1 VY1 VZ1 VX2 VY2 VZ2] (origin point, first // direction vector, second directionvector). // // The function is fully vectorized, in that multiple points may be // projected onto multiple planes in a single call, returning multiple // points. With the exception of the second dimension (where // SIZE(PT1,2)==3, and SIZE(PLANE,2)==9), each dimension of PT1 and PLANE // must either be equal or one, similar to the requirements of BSXFUN. In // basic usage, point PT1 is a [N*3] array, and PLANE is a [N*9] array // (see createPlane for details). Result PT2 is a [N*3] array, containing // coordinates of orthogonal projections of PT1 onto planes PLANE. In // vectorised usage, PT1 is an [N*3*M*P...] matrix, and PLANE is an // [X*9*Y...] matrix, where (N,X), (M,Y), etc, are either equal pairs, or // one of the two is one. // // See also: // planes3d, points3d, planePosition, intersectLinePlane // Arguments : double point[9] // const double plane[9] // Return Type : void // void b_projPointOnPlane(double point[9], const double plane[9]) { double normals[3]; int k; double y; double z1[3]; double c[9]; double dv6[9]; double t[3]; double b_point[9]; int b_k; // --------- // author : David Legland // INRA - TPV URPOI - BIA IMASTE // created the 18/02/2005. // // HISTORY // 21/08/2006: debug support for multiple points or planes // 22/04/2013: uses bsxfun for mult. pts/planes in all dimensions (Sven H) // Unpack the planes into origins and normals, keeping original shape crossProduct3d(*(double (*)[3])&plane[3], *(double (*)[3])&plane[6], normals); // difference between origins of plane and point // relative position of point on normal's line for (k = 0; k < 3; k++) { z1[k] = normals[k] * normals[k]; } y = z1[0]; for (k = 0; k < 2; k++) { y += z1[k + 1]; } bsxfun(*(double (*)[3])&plane[0], point, c); b_bsxfun(normals, c, dv6); sum(dv6, z1); for (k = 0; k < 3; k++) { t[k] = z1[k] / y; } // add relative difference to project point back to plane for (k = 0; k < 3; k++) { for (b_k = 0; b_k < 3; b_k++) { c[b_k + 3 * k] = t[b_k] * normals[k]; } } memcpy(&b_point[0], &point[0], 9U * sizeof(double)); d_bsxfun(b_point, c, point); } // // PROJPOINTONPLANE Return the orthogonal projection of a point on a plane // // PT2 = projPointOnPlane(PT1, PLANE); // Compute the (orthogonal) projection of point PT1 onto the plane PLANE, // given as [X0 Y0 Z0 VX1 VY1 VZ1 VX2 VY2 VZ2] (origin point, first // direction vector, second directionvector). // // The function is fully vectorized, in that multiple points may be // projected onto multiple planes in a single call, returning multiple // points. With the exception of the second dimension (where // SIZE(PT1,2)==3, and SIZE(PLANE,2)==9), each dimension of PT1 and PLANE // must either be equal or one, similar to the requirements of BSXFUN. In // basic usage, point PT1 is a [N*3] array, and PLANE is a [N*9] array // (see createPlane for details). Result PT2 is a [N*3] array, containing // coordinates of orthogonal projections of PT1 onto planes PLANE. In // vectorised usage, PT1 is an [N*3*M*P...] matrix, and PLANE is an // [X*9*Y...] matrix, where (N,X), (M,Y), etc, are either equal pairs, or // one of the two is one. // // See also: // planes3d, points3d, planePosition, intersectLinePlane // Arguments : double point[12] // const double plane[9] // Return Type : void // void projPointOnPlane(double point[12], const double plane[9]) { double normals[3]; int k; int b_k; double y[4]; double c[12]; double dp[12]; int xoffset; double b_y; double z1[3]; double t[4]; // --------- // author : David Legland // INRA - TPV URPOI - BIA IMASTE // created the 18/02/2005. // // HISTORY // 21/08/2006: debug support for multiple points or planes // 22/04/2013: uses bsxfun for mult. pts/planes in all dimensions (Sven H) // Unpack the planes into origins and normals, keeping original shape crossProduct3d(*(double (*)[3])&plane[3], *(double (*)[3])&plane[6], normals); // difference between origins of plane and point // relative position of point on normal's line for (k = 0; k < 3; k++) { for (b_k = 0; b_k < 4; b_k++) { dp[b_k + (k << 2)] = plane[k] - point[b_k + (k << 2)]; c[b_k + (k << 2)] = normals[k] * dp[b_k + (k << 2)]; } } for (b_k = 0; b_k < 4; b_k++) { y[b_k] = c[b_k]; } for (k = 0; k < 2; k++) { xoffset = (k + 1) << 2; for (b_k = 0; b_k < 4; b_k++) { y[b_k] += c[xoffset + b_k]; } } for (k = 0; k < 3; k++) { z1[k] = normals[k] * normals[k]; } b_y = z1[0]; for (k = 0; k < 2; k++) { b_y += z1[k + 1]; } for (k = 0; k < 4; k++) { t[k] = y[k] / b_y; } // add relative difference to project point back to plane for (k = 0; k < 3; k++) { for (b_k = 0; b_k < 4; b_k++) { c[b_k + (k << 2)] = t[b_k] * normals[k]; } } memcpy(&dp[0], &point[0], 12U * sizeof(double)); for (k = 0; k < 3; k++) { for (b_k = 0; b_k < 4; b_k++) { point[b_k + (k << 2)] = dp[b_k + (k << 2)] + c[b_k + (k << 2)]; } } } // // File trailer for projPointOnPlane.cpp // // [EOF] //
true
b001be4158095780186cdb37c5ef69a6a2a4fe90
C++
senseiakhanye/cppmyunisa
/activity11/activity11a.cpp
UTF-8
288
3.375
3
[]
no_license
#include <iostream> using namespace std; int main() { int num; cout << "Enter a number between 10 and 20 : "; cin >> num; while (num < 10 || num > 20) { cout << "Enter a number between 10 and 20 : "; cin >> num; } return 0; }
true
3174fbc770a471be6f874ca5f5602d34748245ca
C++
olihewi/ASGEground
/src/game/GameObjects/Core/TextObject.cpp
UTF-8
1,139
2.984375
3
[]
no_license
// // Created by hewis on 19/03/2021. // #include "TextObject.h" TextObject::TextObject( ASGE::Renderer* renderer, std::string contents, ASGE::Point2D position, int font_index, ASGE::Colour colour, float scale, short z_order) { text.setString(contents); text.setFont(renderer->getFont(font_index)); text.setPosition(position); text.setColour(colour); text.setScale(scale); text.setZOrder(z_order); } std::string TextObject::contents() { return text.getString(); } void TextObject::contents(std::string _contents) { text.setString(_contents); } ASGE::Point2D TextObject::position() { return text.getPosition(); } void TextObject::position(ASGE::Point2D _position) { text.setPosition(_position); } void TextObject::translate(ASGE::Point2D _translation) { text.setPosition(ASGE::Point2D(text.getPosition().x + _translation.x, text.getPosition().y + _translation.y)); } ASGE::Colour TextObject::colour() { return text.getColour(); } void TextObject::colour(ASGE::Colour _colour) { text.setColour(_colour); } void TextObject::zOrder(short _z_order) { text.setZOrder(_z_order); }
true
eda23241ff4de14fecf137659de6723d0274cb1e
C++
wangsiping97/My-LeetCode-Solutions
/78.cpp
UTF-8
701
3.109375
3
[]
no_license
// Given a set of distinct integers, nums, return all possible subsets (the power set). // Note: The solution set must not contain duplicate subsets. #include <vector> using namespace std; class Solution { public: vector< vector<int> > ans; vector<int> tempans; void dfs(int index, vector<int>& nums) { int n = nums.size(); if (index > n) { return; } for (int i = index; i < n; ++i) { tempans.push_back(nums[i]); dfs(i + 1, nums); tempans.pop_back(); } ans.push_back(tempans); } vector< vector<int> > subsets(vector<int>& nums) { dfs(0, nums); return ans; } };
true
84fc55aff6555db6456663e28ccc3a31ceccaee3
C++
Ansou1/CPP
/Pisicne/Day_10/ex02/AssaultTerminator.cpp
UTF-8
1,030
2.609375
3
[]
no_license
// // AssaultTerminator.cpp for assault terminator in /home/daguen_s/rendu/piscine_cpp_d10/ex02 // // Made by daguen_s // Login <daguen_s@epitech.net> // // Started on Fri Jan 17 12:03:59 2014 daguen_s // Last update Fri Jan 17 16:09:16 2014 daguen_s // #include "AssaultTerminator.hh" AssaultTerminator::AssaultTerminator() { std::cout << "* teleports from space *" << std::endl; } AssaultTerminator::AssaultTerminator(AssaultTerminator const & marine) { (void) marine; std::cout << "* teleports from space *" << std::endl; } AssaultTerminator::~AssaultTerminator() { std::cout << "I'll be back ..." << std::endl; } ISpaceMarine * AssaultTerminator::clone() const { return new AssaultTerminator(*this); } void AssaultTerminator::battleCry() const { std::cout << "This code is unclean. PURIFY IT !" << std::endl; } void AssaultTerminator::rangedAttack() const { std::cout << "* does nothing *" << std::endl; } void AssaultTerminator::meleeAttack() const { std::cout << "* attacks with chainfists *" << std::endl; }
true
b14613dd92578aadece7bba7bc583093156e5b7d
C++
H-Shen/Collection_of_my_coding_practice
/Kattis/raggedright.cpp
UTF-8
586
2.890625
3
[]
no_license
// https://open.kattis.com/problems/raggedright // #include <bits/extc++.h> using namespace std; int main() { vector<string> A; string s; int maxLength = -1; while (getline(cin, s)) { A.emplace_back(s); maxLength = max(maxLength, static_cast<int>(s.size())); } int raggedness = 0; for (size_t i = 0; i != A.size(); ++i) { if (i == A.size() - 1) { break; } int temp = maxLength - static_cast<int>(A.at(i).size()); raggedness += temp * temp; } cout << raggedness << endl; return 0; }
true
63f70eaec88b3a65a1351051361c64e64ddfa4f6
C++
JIANSHULI/HERA_MapMaking_VisibilitySimulation
/src/_Bulm/include/wignerSymbols/wignerSymbols-fortran.h
UTF-8
2,437
2.6875
3
[]
no_license
/*******************************************************-/ * This source code is subject to the terms of the GNU -/ * Lesser Public License. If a copy of the LGPL was not -/ * distributed with this file, you can obtain one at -/ * https://www.gnu.org/licenses/lgpl.html. -/ ********************************************************/ #ifndef WIGNER_SYMBOLS_FORTRAN_H #define WIGNER_SYMBOLS_FORTRAN_H /** \file wignerSymbols-fortran.h * * \author Joey Dumont <joey.dumont@gmail.com> * * \since 2013-08-16 * * \brief Defines utility functions for the evaluation of Wigner-3j and -6j symbols. * * We use modified SLATEC (http://netlib.org/slatec) Fortran subroutines to compute * Wigner-3j and -6j symbols. We modified the subroutines so that they do not depend * d1mach, r1mach or i1mach as these are obsolete routines. They have been replaced * by intrinsics such as huge(), tiny(), epsilon() and spacing(), which are guaranteed * to work. The file wignerSymbols.f contain the subroutines and their * dependencies. * * We rely on the ISO C Binding to bind the Fortran subroutines to C++. This method * of working insures that proper type casts are performed, among other things. We * then use the same method as we did before (extern "C"). * */ #include <cmath> #include <limits> #include <algorithm> #include <vector> #include <iostream> namespace WignerSymbols { extern "C" { extern void drc3jj_wrap(double,double,double,double,double*,double*,double*,int,int*); extern void drc6j_wrap(double,double,double,double,double,double*,double*,double*,int,int*); } /*! Computes the Wigner-3j symbol for given l1,l2,l3,m1,m2,m3. We * explicitly enforce the selection rules. */ double wigner3j_f(double l1, double l2, double l3, double m1, double m2, double m3); /*! Computes the Clebsch-Gordan coefficient by relating it to the * Wigner 3j symbol. It sometimes eases the notation to use the * Clebsch-Gordan coefficients directly. */ inline double clebschGordan_f(double l1, double l2, double l3, double m1, double m2, double m3) { // We simply compute it via the 3j symbol. return (pow(-1.0,l1-l2+m3)*sqrt(2.0*l3+1.0)*wigner3j_f(l1,l2,l3,m1,m2,-m3)); } /*! Computes the Wigner-6j symbol for given, l1, l2, l3, l4, l5, l6. * We explicitly enforce the selection rules. */ double wigner6j_f(double l1, double l2, double l3, double l4, double l5, double l6); } #endif // WIGNER_SYMBOLS_FORTRAN_H
true
0e8267a6506c222797edc33aac6ce4e7a0eaca34
C++
khayamgondal/827
/patterns/singleton/gof/symbolTable.cpp
UTF-8
353
2.75
3
[]
no_license
#include "symbolTable.h" SymbolTable* SymbolTable::getInstance() { if ( !instance ) instance = new SymbolTable; return instance; } int SymbolTable::getValue(const std::string& name) const { std::map<std::string, int>::const_iterator it = table.find(name); if ( it == table.end() ) throw name+std::string(" not found"); return it->second; }
true
8d4fd3f3b22b09dd0773c9c170cced4d12f041f9
C++
alexcam96/progetto_Oggetti
/CuboRubik/CuboRubik/opengl-rubix-cube/src/game/MeshEntity.h
UTF-8
985
2.6875
3
[]
no_license
#ifndef MESHENTITY_H_ #define MESHENTITY_H_ #include "Entity.h" namespace game { class MeshEntity : public Entity { Mesh *mesh_; Material *mtl_; public: MeshEntity(Mesh *m = NULL) : Entity() { mesh_ = m, mtl_ = NULL; }; ~MeshEntity() {}; Mesh* mesh() { return mesh_; } void set_mesh(Mesh *m) { mesh_ = m; } Material* mtl() { return mtl_; } void set_mtl(Material *mtl) { mtl_ = mtl; } virtual void render() { // render self if (mtl_) mtlSet(mtl_); if (mesh_) mesh_->render(transform()); // super implementation Entity::render(); } //******************************* MODIFICA ********************** /* virtual std::vector<Face> getFaces() { std::vector<Face *> ptrFaces = mesh_->getFaces(); std::vector<Face> Faces; for (Face *f : ptrFaces) { Faces.push_back(*f); } return Faces; }*/ //*************************************************************** }; } #endif
true
bcf354917a67466b717282fa70977e415ca1eeab
C++
anujpathania/HotSniper
/common/misc/stable_iterator.h
UTF-8
683
3.1875
3
[ "MIT" ]
permissive
#ifndef STABLE_ITERATOR_H #define STABLE_ITERATOR_H #include <vector> template <class T> class StableIterator { public: StableIterator(const StableIterator<T> &s) : _vec(s._vec), _offset(s._offset) {} StableIterator(std::vector<T> &vec, unsigned int offset) : _vec(vec), _offset(offset) {} T* getPtr() { return &(_vec[_offset]); } T* operator->() { return getPtr(); } T& operator*() { return *getPtr(); } StableIterator<T> operator=(const StableIterator<T>&src) { return StableIterator<T>(src._vec, src._offset); } private: std::vector<T> & _vec; unsigned int _offset; }; #endif
true
55ac83f5b5ba9c937b775340c8760288113bfca4
C++
CyanoFresh/KPI-Labs
/OOP/s3/5_1/main.cpp
UTF-8
532
2.875
3
[]
no_license
#include "Adam.h" #include "Eva.h" #include "Array.h" using namespace std; int main() { Adam adam(180, "light", 7); Rib specialRib = adam[2]; Eva eva(160, "dark", specialRib); Eva eva2(150, "light", Rib(23)); // adam.show(); // eva.show(); Array arr(specialRib); arr.add(eva); arr.add(eva2); arr[10].show(); arr[11].show(); arr.remove(11); eva2 = arr[0]; eva2.show(); God *gods[3] = {&adam, &eva, &eva2}; for (auto &god : gods) { god->show(); } }
true
067f397087e2dfbb7f5b668abf91066765a6db20
C++
cracer/offer
/牛客网刷题/翻转单词顺序列.cpp
UTF-8
383
3.0625
3
[]
no_license
#include <string> using namespace std; class Solution { public: string ReverseSentence(string str) { int len = str.size(); if (len < 2) return str; string res = "", tmp = ""; for(int i=0;i<len;i++) { if (str[i] == ' ') { res = " " + tmp + res; tmp = ""; } else { tmp += str[i]; } } if (tmp != "") res = tmp + res; return res; } };
true
4b89be45ea9adacb1cc32935ae80c9b106f21896
C++
kohyatoh/contests
/pku/3193/3193.cpp
UTF-8
941
2.765625
3
[]
no_license
#include <stdio.h> #include <vector> #define rep(i, n) for(int i=0; i<(int)(n); i++) struct node { char ch; std::vector<node*> v; node(char ch) : ch(ch) {} ~node() { rep(i, v.size()) delete v[i]; } node *get(char ch) { rep(i, v.size()) if(v[i]->ch==ch) return v[i]; return (node*)0; } node *add(char ch) { v.push_back(new node(ch)); return v.back(); } }; char buf[128]; int main() { gets(buf); int n, m; sscanf(buf, "%d%d", &n, &m); node root(0); rep(i, n) { gets(buf); node *p=&root, *nx; for(char *s=buf; *s; s++) { if((nx=p->get((char)*s))==0) nx=p->add(*s); p = nx; } } int ans=0; rep(i, m) { char ch; node *p=&root; while((ch=getchar())!='\n') { if(p) p=p->get(ch); } if(p) ans++; } printf("%d\n", ans); return 0; }
true
6e3422289481b0d82d00fd7316da93fd696d48f2
C++
yangyueren/CppConcurrencyInAction
/quicksort_using_chunk.h
UTF-8
3,422
3.109375
3
[ "MIT" ]
permissive
// // Created by yryang on 2021/10/21. // #ifndef CPPTEST_QUICKSORT_USING_CHUNK_H #define CPPTEST_QUICKSORT_USING_CHUNK_H #include <algorithm> #include <atomic> #include <future> #include <iostream> #include <list> #include <thread> #include <vector> #include <string> #include "threadsafe_stack.h" #include "threadsafe_queue.h" namespace quicksort{ template <typename T> class sorter{ private: struct chunk{ std::list<T> data; std::promise<std::list<T> > promise; }; const int max_threads_num; std::vector<std::thread> threads; threadsafe_stack::threadsafe_stack<std::shared_ptr<chunk> > stack; std::atomic_bool done; std::mutex mtx; public: sorter(): max_threads_num(std::thread::hardware_concurrency()-1), done(false){} ~sorter(){ done = true; for (int i = 0; i < threads.size(); ++i) { threads[i].join(); } } void sort_chunk(std::shared_ptr<chunk> const &p){ if (p->data.empty()){ p->promise.set_value(std::list<T>()); return; } p->promise.set_value(do_sort(p->data)); } void try_sort_chunk(){ std::shared_ptr<chunk> chunk_p; if (stack.pop(chunk_p)){ sort_chunk(chunk_p); } } void sort_thread(){ while (!done){ try_sort_chunk(); std::this_thread::yield(); } } void debug(std::list<T> data, std::string des=""){ std::lock_guard<std::mutex> lockGuard(mtx); std::cout << des << std::endl; for(auto i: data){ std::cout << i << " "; } std::cout << '\n'; } std::list<T> do_sort(std::list<T> &chunk_data){ if (chunk_data.empty()){ return chunk_data; } std::list<T> result; result.splice(result.begin(), chunk_data, chunk_data.begin()); T const &pivot = *result.begin(); auto divide_point = std::partition(chunk_data.begin(), chunk_data.end(), [&](T const &t){return t < pivot;}); std::shared_ptr<chunk> lower_part = std::make_shared<chunk>(); lower_part->data.splice(lower_part->data.end(), chunk_data, chunk_data.begin(), divide_point); std::future<std::list<T> > new_lower = lower_part->promise.get_future(); stack.push(lower_part); if (threads.size() < max_threads_num){ std::lock_guard<std::mutex> lockGuard(mtx); threads.emplace_back(&sorter<T>::sort_thread, this); } std::list<T> new_higher(do_sort(chunk_data)); result.splice(result.end(), new_higher); while(new_lower.wait_for(std::chrono::seconds(0)) != std::future_status::ready) { try_sort_chunk(); } result.splice(result.begin(), new_lower.get()); return result; } }; template <typename T> std::list<T> quicksort_using_chunk(std::list<T> input){ if (input.empty()){ return input; } sorter<T> s; return s.do_sort(input); } } #endif //CPPTEST_QUICKSORT_USING_CHUNK_H
true
53c436d9931d26625f606a367e49d22f62bed7f8
C++
LuciusKyle/LeetCode
/0228_Summary_Ranges/0228.cc
UTF-8
1,191
3.046875
3
[ "Apache-2.0" ]
permissive
#include <limits.h> #include <string> #include <vector> using std::string; using std::vector; class Solution { public: vector<string> summaryRanges(const vector<int>& nums) { vector<string> rtn; if (nums.empty()) return rtn; rtn.push_back(std::to_string(nums.front())); int64_t pre_num = nums.front(); int64_t range_start = pre_num; bool continuous = true; for (int i = 1 /*start from 1 not 0*/; i < nums.size(); ++i) { if (continuous) if (nums[i] - pre_num == 1) { pre_num = nums[i]; continue; } else { continuous = false; if (nums[i - 1] != range_start) rtn.back().append("->" + std::to_string(nums[i - 1])); } rtn.push_back(std::to_string(nums[i])); pre_num = nums[i]; range_start = nums[i]; continuous = true; } if (continuous && nums.back() != range_start) rtn.back().append("->" + std::to_string(nums.back())); return rtn; } }; int main(void) { Solution sln; auto rtn = sln.summaryRanges({0, 1, 2, 4, 5, 7}); rtn = sln.summaryRanges({0, 2, 3, 4, 6, 8, 9}); rtn = sln.summaryRanges({-2147483648,-2147483647,2147483647}); return 0; }
true
500bc8da9c6e74614cbfa90dd831f49d68989685
C++
zhan92/osal_stm_w
/McuMonitor/comm/commtxthread.cpp
UTF-8
712
2.546875
3
[]
no_license
#include "commtxthread.h" #include "bdcomm.h" CommTxThread::CommTxThread() { m_bThreadRun = FALSE; } CommTxThread::~CommTxThread() { stop(); terminate(); wait(); } void CommTxThread::setThreadRunFlag(void) { m_bThreadRun = TRUE; } BOOL CommTxThread::getIsThreadRun(void) { return m_bThreadRun; } void CommTxThread::stop() { m_bThreadRun = FALSE; } /** * @brief COMM数据发送线程 */ void CommTxThread::run() { while (m_bThreadRun) { msleep(100);//100ms sleep if (BDComm::getInstance()->readTxFIFO(&BDComm::getInstance()->m_txMessage)) { BDComm::getInstance()->transmit(&BDComm::getInstance()->m_txMessage); } } }
true
4020f9766643b7ad548fe49a42ec8e148bdd2dcc
C++
adrs0049/FastVector
/linearAlgebra/VectorReduction.h
UTF-8
9,477
3.203125
3
[ "MIT" ]
permissive
//////////////////////////////////////////////////////////////////////////////// // // // File Name: CSVector.h // // // // Author: Andreas Buttenschoen <andreas@buttenschoen.ca> // // Created: 2018-03-30 12:22:20 // // // //////////////////////////////////////////////////////////////////////////////// #ifndef CS_VECTOR_REDUCTION_H #define CS_VECTOR_REDUCTION_H #include <iostream> #include <cmath> using std::abs; using std::max; template <typename T> T zero(T value) { return T(0); } struct one_norm_functor { template <typename Value> static inline void init(Value& value) { value = zero(value); } template <typename Value, typename Element> static inline void update(Value& value, const Element& x) { value += abs(x); } template <typename Value> static inline void finish(Value& value, const Value& value2) { value += value2; } template <typename Value> static inline Value post_reduction(const Value& value) { return value; } }; struct sum_functor { template <typename Value> static inline void init(Value& value) { value = zero(value); } template <typename Value, typename Element> static inline void update(Value& value, const Element& x) { value += x; } template <typename Value> static inline void finish(Value& value, const Value& value2) { value += value2; } template <typename Value> static inline Value post_reduction(const Value& value) { return value; } }; struct product_functor { template <typename Value> static inline void init(Value& value) { value = zero(value); } template <typename Value, typename Element> static inline void update(Value& value, const Element& x) { value *= x; } template <typename Value> static inline void finish(Value& value, const Value& value2) { value *= value2; } template <typename Value> static inline Value post_reduction(const Value& value) { return value; } }; struct two_norm_functor { template <typename Value> static inline void init(Value& value) { value = zero(value); } template <typename Value, typename Element> static inline void update(Value& value, const Element& x) { value += x * x; } template <typename Value> static inline void finish(Value& value, const Value& value2) { value += value2; } template <typename Value> static inline Value post_reduction(const Value& value) { Value (*sqrt) (const Value) = std::sqrt; return sqrt(value); } }; struct unary_dot : two_norm_functor { template <typename Value> static inline Value post_reduction(const Value& value) { return value; } }; struct infinity_norm_functor { template <typename Value> static inline void init(Value& value) { value = zero(value); } template <typename Value, typename Element> static inline void update(Value& value, const Element& x) { value = max(value, abs(x)); } template <typename Value> static inline void finish(Value& value, const Value& value2) { value = max(value, abs(value2)); } template <typename Value> static inline Value post_reduction(const Value& value) { return value; } }; namespace impl { template <unsigned long Index0, unsigned long Max0, typename Functor> struct reduction { using next = reduction<Index0 + 1, Max0, Functor>; template <typename Value> static inline void init(Value& tmp00, Value& tmp01, Value& tmp02, Value& tmp03, Value& tmp04, Value& tmp05, Value& tmp06, Value& tmp07) { Functor::init(tmp00); next::init(tmp01, tmp02, tmp03, tmp04, tmp05, tmp06, tmp07, tmp00); } template <typename Value, typename Vector, typename Size> static inline void update(Value& tmp00, Value& tmp01, Value& tmp02, Value& tmp03, Value& tmp04, Value& tmp05, Value& tmp06, Value& tmp07, const Vector& v, Size i) { Functor::update(tmp00, v[i + Index0]); next::update(tmp01, tmp02, tmp03, tmp04, tmp05, tmp06, tmp07, tmp00, v, i); } template <typename Value> static inline void finish(Value& tmp00, Value& tmp01, Value& tmp02, Value& tmp03, Value& tmp04, Value& tmp05, Value& tmp06, Value& tmp07) { next::finish(tmp01, tmp02, tmp03, tmp04, tmp05, tmp06, tmp07, tmp00); Functor::finish(tmp00, tmp01); } }; template <unsigned long Max0, typename Functor> struct reduction<Max0, Max0, Functor> { template <typename Value> static inline void init(Value& tmp00, Value&, Value&, Value&, Value&, Value&, Value&, Value&) { Functor::init(tmp00); } template <typename Value, typename Vector, typename Size> static inline void update(Value& tmp00, Value&, Value&, Value&, Value&, Value&, Value&, Value&, const Vector& v, Size i) { Functor::update(tmp00, v[i + Max0]); } template <typename Value> static inline void finish(Value&, Value&, Value&, Value&, Value&, Value&, Value&, Value&) {} }; } // end namespace template <unsigned long Unroll, typename Functor, typename Result> struct reduction { template <typename Vector> static inline Result apply(const Vector& v) { //using value_type = typename Vector::value_type; using size_type = typename Vector::size_type; Result result; Result tmp00, tmp01, tmp02, tmp03, tmp04, tmp05, tmp06, tmp07; constexpr size_type UNROLL = std::min(Unroll, size_type(8)); auto s = size(v); auto sb = s / UNROLL * UNROLL; Functor::init(result); //#pragma omp parallel { impl::reduction<0, UNROLL-1, Functor>::init(tmp00, tmp01, tmp02, tmp03, tmp04, tmp05, tmp06, tmp07); //#pragma omp for for (size_t i = 0; i < sb; i+=UNROLL) impl::reduction<0, UNROLL-1, Functor>::update(tmp00, tmp01, tmp02, tmp03, tmp04, tmp05, tmp06, tmp07, v, i); impl::reduction<0, UNROLL-1, Functor>::finish(tmp00, tmp01, tmp02, tmp03, tmp04, tmp05, tmp06, tmp07); //#pragma omp critical Functor::finish(result, tmp00); } for (size_t i = sb; i < s; i++) Functor::update(result, v[i]); return Functor::post_reduction(result); } }; namespace impl { template <unsigned long Index0, unsigned long Max0> struct dot_aux { using next = dot_aux<Index0 + 1, Max0>; template <typename Value, typename Vector1, typename Vector2, typename Size> static inline void apply(Value& tmp00, Value& tmp01, Value& tmp02, Value& tmp03, Value& tmp04, Value& tmp05, Value& tmp06, Value& tmp07, const Vector1& v1, const Vector2& v2, Size i) { tmp00 = std::fma(v1[i + Index0], v2[i + Index0], tmp00); next::apply(tmp01, tmp02, tmp03, tmp04, tmp05, tmp06, tmp07, tmp00, v1, v2, i); } }; template <unsigned long Max0> struct dot_aux<Max0, Max0> { template <typename Value, typename Vector1, typename Vector2, typename Size> static inline void apply(Value& tmp00, Value&, Value&, Value&, Value&, Value&, Value&, Value&, const Vector1& v1, const Vector2& v2, Size i) { tmp00 = std::fma(v1[i + Max0], v2[i + Max0], tmp00); } }; template <unsigned long Unroll> struct dot { template <typename Vector1, typename Vector2> static inline auto apply(const Vector1& v1, const Vector2& v2) { using value_type = typename Vector1::value_type; using size_type = typename Vector1::size_type; value_type z = value_type(0); value_type result = z; constexpr size_type UNROLL = std::min(Unroll, size_type(8)); const size_type N = size(v1); const size_type no_loops = N / UNROLL; //#pragma omp parallel { value_type tmp00 = z, tmp01 = z, tmp02 = z, tmp03 = z, tmp04 = z, tmp05 = z, tmp06 = z, tmp07 = z; //#pragma omp for for (size_type i = 0; i < no_loops; i+=UNROLL) dot_aux<0, UNROLL-1>::apply(tmp00, tmp01, tmp02, tmp03, tmp04, tmp05, tmp06, tmp07, v1, v2, i); //#pragma omp critical result += ((tmp00 + tmp01) + (tmp02 + tmp03)) + ((tmp04 + tmp05) + (tmp06 + tmp07)); } for (size_type i = UNROLL * no_loops; i < N; i++) result = std::fma(v1[i], v2[i], result); return result; } }; } // end namespace template <unsigned long Unroll, typename Vector1, typename Vector2> inline auto dot(const Vector1& v1, const Vector2& v2) { return impl::dot<Unroll>::apply(v1, v2); } #endif
true
4d82b4c5a104512f74722be83df288b7c7ec4b0d
C++
DemonQAQ/C_Study
/文件操作.cpp
GB18030
981
3.1875
3
[]
no_license
#include<stdio.h> #include<stdlib.h> #include<fcntl.h>//ļͷļ int main() { char str[128] = {0}; int i = 0; for (i = 0; str[i] != '!'; i++)//ַ!(Ӣ) { str[i] = getchar(); if (str[i] == '!') break; } str[i] = getchar();//뻻зˢ! i = 0;//iֵ while (str[i]!='\0')//תСд { if (str[i] >= 'a' && str[i] <= 'z') { str[i] = str[i] - 32; } i = i + 1; } FILE* fh;//ļָ fh = fopen("test.txt","w+");//ڵǰĿĿ¼´test.txtļû򴴽һ if (fh == NULL) printf("ʧ \n"); else { fprintf(fh, "%s", str);//strڵַļ fclose(fh);//رļ } fh = fopen("test.txt", "r+");//ļûиļʧ if (fh == NULL) { printf("ʧ \n"); exit(0); } fscanf(fh, str);//ļڵַstr printf("%s", str); return 0; }
true
218fc51e1f1949ddda7a88f0d2a08f84a71c2998
C++
Jballard419/lab11
/main.cpp
UTF-8
698
2.90625
3
[]
no_license
#include "Kruskal.cpp" #include <fstream> int main(int argc, char const *argv[]) { /* code */ if (argc != 2) { std::cout << "file didn't load use like this " << '\n'; std::cout << "./Skew_Heap data.txt" << '\n'; } std::ifstream in(argv[1]); int value; in>>value; // cause I don't need the first value int** array; int num= 1; while(in>>value) { const int dummy = value; array = new int*[dummy]; for (int i = 0; i < value; i++) { array[i]= new int[value]; for (int j = 0; j < value; j++) { in>>array[i][j]; } } std::cout << "Graph" <<num<< ":\n"; Kruskal(array, value); Prim(array, value); num++; } }
true
088d895df8c7cc02526411acdce04758dc948892
C++
ZhuBicen/ling-repeater
/UnitTest/PlayerStub.cpp
UTF-8
1,639
2.6875
3
[]
no_license
#include <cassert> #include <iostream> #include "Player_impl.h" Player_impl::Player_impl() { } Player_impl::~Player_impl() { } void Player_impl::Init(HWND hwnd, HINSTANCE hInst) { } bool Player_impl::OpenFile(const std::wstring& file_name) { return true; } bool Player_impl::CloseFile() { return true; } bool Player_impl::PlayFile() { state_.length = 100; state_.current_state = PlayerState::play; //state_.file_name = file_name; return true; } std::wstring Player_impl::GetFileName() { return state_.file_name; } long Player_impl::GetFileLength() { return state_.length; } bool Player_impl::Repeat() { state_.current_state = PlayerState::repeate; //state_.end_pos = MCIWndGetPosition(playerWnd_); return true;//MCIWndPlayFromTo(playerWnd_, state_.start_pos, state_.end_pos) == 0; } const PlayerState& Player_impl::GetState() { state_.curent_pos = 0;//MCIWndGetPosition(playerWnd_); return state_; } bool Player_impl::SetStartPos() { state_.start_pos = 0;//MCIWndGetPosition(playerWnd_); std::cout << "Setting started position: " << state_.start_pos << std::endl; return true; } bool Player_impl::PlayFrom(long pos) { if(state_.current_state == PlayerState::repeate){ assert(false); } if(state_.current_state == PlayerState::play){ state_.end_pos = pos; } return true; } bool Player_impl::ContinuePlay() { state_.current_state = PlayerState::play; return true; } bool Player_impl::Pause() { return true; } bool Player_impl::Stop() { return true; }
true
0bb48d37b6cb9eb25038cc56a6fbf58ccb182f32
C++
ViMaSter/arduinowrapper
/ArduinoMock.h
UTF-8
1,287
3.0625
3
[]
no_license
#pragma once #include <string> #include <iostream> #include <chrono> class _Serial { public: // ready check for the serial port operator bool() const { return true; // always ready when mocking }; void begin(int port) { return; // intentionally void } void println(std::string s) { this->print(s); std::cout << "\r\n"; } void print(std::string s) { std::cout << s; } void println(int s) { this->print(std::to_string(s)); std::cout << "\r\n"; } void print(int s) { std::cout << std::to_string(s); } }; _Serial Serial; int digitalRead(int slotIndex) { return 1; // intentionally void } void delay(int milliseconds) { std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds)); } int digitalPinToInterrupt(int pin) { return pin; } enum PinMode { INPUT, OUTPUT, INPUT_PULLUP }; void pinMode(int pin, PinMode mode) { return; // intentionally void } void digitalWrite(int pin, int value) { return; } enum SignalDirection { LOW, CHANGE, RISING, FALLING }; typedef void(*voidFunction)(); void attachInterrupt(int interruptIndex, voidFunction function, SignalDirection direction) { }
true
a462615b5da086473580f3ffa3c5df9ab397b5e6
C++
ClementPhan/ENPCInfo
/Info/TP8/utils.h
UTF-8
989
2.859375
3
[]
no_license
#ifndef UTILS_H #define UTILS_H #include <Imagine/Graphics.h> using namespace Imagine; //====================================== // Structure point struct point { int x; int y; point operator+(const point &p) const{ point q; q.x=x+p.x; q.y=y+p.y; return q; } point operator-(const point &p) const{ point q; q.x=x-p.x; q.y=y-p.y; return q; } point operator*(int lambda) const{ point q; q.x=x*lambda; q.y=y*lambda; return q; } bool operator==(point p) const{ return ((x==p.x)&&(y==p.y)); } int normeInf(){ return std::max(abs(x),abs(y)); } }; const int droite = 0; const int bas = 1; const int gauche = 2; const int haut = 3; const point dir[4] = {{1,0},{0,1},{-1,0},{0,-1}}; //====================================== // Gestion du clavier int Clavier(); #endif // UTILS_H
true
fc2cfabe3b93efc8d9f1374daed7532bd9457517
C++
emmacneil/checkers
/include/board_scene.hpp
UTF-8
503
2.78125
3
[]
no_license
/* board_scene.hpp * * This scene carries an instance of the game state, and is in charge of rendering the game state, * getting user input, and updating the game state based on that input. */ #ifndef BOARD_SCENE_HPP #define BOARD_SCENE_HPP #include "scene.hpp" #include "board_state.hpp" class board_scene : public scene { public : void init(game * g); void quit(); void render(); void update(); void handle_input(); private : board_state * m_board_state; }; #endif
true
8ac8e3079efa9e35bb49d5a5a7668b1624c97407
C++
vikrantgupta95/Alcohol-Detector-
/alcohol.ino
UTF-8
1,177
2.625
3
[]
no_license
// include the library code: #include <LiquidCrystal.h> // initialize the library with the numbers of the interface pins LiquidCrystal lcd(7, 8, 9, 10, 11, 12); void setup() { // put your setup code here, to run once: Serial.begin(9600); lcd.begin(16, 2); lcd.setCursor(0, 0); lcd.print("No drunk drive"); delay(2000); lcd.clear(); lcd.setCursor(0, 0); lcd.print("Aaditya sharma"); lcd.setCursor(0, 1); lcd.print("Gaurav chamoli"); delay(2000); lcd.clear(); lcd.setCursor(0, 0); lcd.print("Alcohol:"); delay(2000); pinMode(4, OUTPUT); pinMode(3, OUTPUT); digitalWrite(4, HIGH); //ignition digitalWrite(3, LOW); //buzzer } void loop() { // put your main code here, to run repeatedly: Serial.println(analogRead(A0)); lcd.setCursor(10, 0); lcd.print(analogRead(A0)); if(analogRead(A0) > 500) { lcd.setCursor(0, 1); lcd.print("Ignition Off"); digitalWrite(4, LOW); //ignition off led digitalWrite(3, HIGH); //buzzer delay(1000); } if(analogRead(A0) < 500) { lcd.setCursor(0, 1); lcd.print("Ignition On "); digitalWrite(4, HIGH); //ignition on led digitalWrite(3, LOW); //buzzer delay(1000); } }
true
4f4f8d02916a93587bf0c2568f713e5626dc7e3a
C++
YuukiReiya/My-DirectX-Template
/Direct3D11/Direct3D11/Source/Mesh/Mesh.cpp
SHIFT_JIS
2,853
2.609375
3
[]
no_license
#include "Mesh.h" #include "../Direct3D11/Direct3D11.h" #include "../Camera/Camera.h" #include "../MyGame.h" #include "../MemoryLeaks.h" Mesh::Mesh() { m_szShaderDataUsage = ShaderManager::c_MeshDefault; } Mesh::~Mesh() { } HRESULT Mesh::Initialize() { return E_NOTIMPL; } HRESULT Mesh::Render() { HRESULT hr; /*! g|W[Zbg */ Direct3D11::GetInstance().GetDeviceContext()->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP ); auto shaderData = ShaderManager::GetInstance().GetShaderData(m_szShaderDataUsage); /*! _CvbgCAEgZbg */ Direct3D11::GetInstance().GetDeviceContext()->IASetInputLayout(shaderData->m_pVertexLayout); /*! VF[_[̓o^ */ Direct3D11::GetInstance().GetDeviceContext()->VSSetShader(shaderData->m_pVertexShader, NULL, NULL); Direct3D11::GetInstance().GetDeviceContext()->PSSetShader(shaderData->m_pPixelShader, NULL, NULL); /*! RX^gobt@̓o^ */ Direct3D11::GetInstance().GetDeviceContext()->VSSetConstantBuffers(0, 1, &shaderData->m_pConstantBuffer); Direct3D11::GetInstance().GetDeviceContext()->PSSetConstantBuffers(0, 1, &shaderData->m_pConstantBuffer); DirectX::XMMATRIX mWorld, mTran, mRot, mScale; mWorld = DirectX::XMMatrixIdentity();/*!< Pʍs */ mTran = DirectX::XMMatrixTranslation(m_Pos.x, m_Pos.y, m_Pos.z); mRot = DirectX::XMMatrixRotationRollPitchYaw(m_Rot.x, m_Rot.y, m_Rot.z); mScale = DirectX::XMMatrixScaling(m_Scale.x, m_Scale.y, m_Scale.z); mWorld = mScale*mRot*mTran; /*! }bsOpϐ` */ D3D11_MAPPED_SUBRESOURCE pData; SecureZeroMemory(&pData, sizeof(pData)); MeshShaderBuffer cb; SecureZeroMemory(&cb, sizeof(cb)); /*! obt@ւ̃ANZX() */ hr = Direct3D11::GetInstance().GetDeviceContext()->Map( shaderData->m_pConstantBuffer, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &pData ); if (FAILED(hr)) { std::string error = "Texture mapping is failed!"; ErrorLog(error); Direct3D11::GetInstance().GetDeviceContext()->Unmap(shaderData->m_pConstantBuffer, NULL);/*!< ANZX‚Ĕ */ return E_FAIL; } /*! RX^gobt@Ƀf[^𑗂 */ auto camera = &Camera::GetInstance(); DirectX::XMMATRIX m = mWorld*camera->GetViewMatrix()*camera->GetProjMatrix(); m = DirectX::XMMatrixTranspose(m);/*!< s]usɂ */ cb.m_WVP = m;/*!< [hs */ /*! Rs[ */ memcpy_s(pData.pData, pData.RowPitch, (void*)(&cb), sizeof(cb)); /*! ANZXI */ Direct3D11::GetInstance().GetDeviceContext()->Unmap(shaderData->m_pConstantBuffer, NULL); /*! ` */ Direct3D11::GetInstance().GetDeviceContext()->Draw( 3, /*!< _(ƒ|SȂ̂Œ_4) */ NULL ); return S_OK; }
true
cff44effec27a631b693a78e1c81fe4c3ec4d007
C++
seannash/logprocessor
/src/monitor_stringlogger.h
UTF-8
422
2.515625
3
[ "MIT" ]
permissive
#pragma once #include <mutex> #include <sstream> #include <string_view> #include <monitor_logger.h> namespace monitor { // Logs the records to a string. Useful for testing. class StringLogger: public Logger { public: StringLogger(); void log(unsigned long tp, std::string_view msg) override; std::string getLog(); private: std::mutex d_mutex; std::stringstream d_buffer; }; } // namespace monitor
true
060c8cad6acc3c9b4542275482a862af3c56b4a6
C++
nokia/CPU-Pooler
/test/thread_busyloop.cpp
UTF-8
3,687
2.921875
3
[ "BSD-3-Clause" ]
permissive
#include <unistd.h> #include <thread> #include <string.h> #include <iostream> #include <vector> #include <sstream> std::string process_name; void printAffinity() { cpu_set_t mask; CPU_ZERO(&mask); int ret = pthread_getaffinity_np(pthread_self(), sizeof(cpu_set_t), &mask); if (ret != 0) { std::cout << "Error getting thread affinity" << ret << std::endl; } int cpu; std::stringstream output; output << " thread(s) running in cpu(s) "; for (cpu=0; cpu < CPU_SETSIZE;cpu++) { if (CPU_ISSET(cpu,&mask)) output << cpu << ","; } output.seekp(-1,output.cur); output << std::endl; std::cout << output.str(); fflush(stdout); } void thread_func (void) { printAffinity(); while(true); } int read_cores(int cores[],char *arg) { int i = 0; arg = strtok(arg,","); while (arg != NULL) { cores[i++]=atoi(arg); arg = strtok(NULL,","); } return i; } int main(int argc, char* argv[]) { for (int i=0; i<argc; i++) { std::cout << argv[i] << " "; } std::cout << std::endl; int opt,exclusive_cores[10],num_excl_cores=0,i,shared_cores[10],num_shared_cores=0; while ((opt = getopt (argc, argv, "c:s:n:")) != -1) { switch (opt) { case 'c': { num_excl_cores = read_cores(exclusive_cores,optarg); break; } case 'n': { process_name = static_cast<char *>(optarg); break; } case 's': { num_shared_cores = read_cores(shared_cores,optarg); break; } default: std::cout << "Illegal option: " << char(opt) << std::endl; return(1); } } std::vector<std::thread> threads; if (num_shared_cores) { int ret; cpu_set_t mask; CPU_ZERO(&mask); for (i=0; i<num_shared_cores; i++) { CPU_SET(shared_cores[i],&mask); } ret = pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &mask); if (ret != 0) { std::cerr << "Err::pthread_setaffinity_np(): " << ret << ":" << num_shared_cores << ":" << shared_cores[0] << std::endl; } } if (num_excl_cores) { for (i=0; i<num_excl_cores; i++) { int ret; cpu_set_t mask; CPU_ZERO(&mask); CPU_SET(exclusive_cores[i],&mask); std::thread thr{thread_func}; ret = pthread_setaffinity_np(thr.native_handle(), sizeof(cpu_set_t), &mask); if (ret != 0) { std::cerr << "Err::pthread_setaffinity_np(): " << ret << "\n"; } threads.push_back(std::move(thr)); } } else { threads.push_back(std::thread{thread_func}); std::this_thread::sleep_for (std::chrono::seconds(1)); } std::this_thread::sleep_for (std::chrono::milliseconds(1)); std::cout << "Main thread :"; printAffinity(); std::cout << std::endl; for (auto &t : threads) t.join(); }
true
f6c83f30e4f85d79965af53b1ce25029e200a292
C++
nihalchari/cpp-quickies
/src/threads/pthreads.cpp
UTF-8
1,013
3.109375
3
[]
no_license
#include <iostream> #include <pthread.h> #include <sys/types.h> #include <unistd.h> using namespace std; void* threadProc(void* param) { for (int count = 0; count < 1000; ++count) { // These are thread IDs assigned by pthread library // This will be different compared to OS thread ID // How to get OS thread id ? // ps -A | grep <app-name> -> This returns process ID // ps -T -p <process-id> OR // top -H -p <process-id> // pthread_id_np_t tid; // pthread_getthreadid_np(); cout << "Message " << count << " from " << pthread_self() << " : " << endl; sleep(1); } pthread_exit(0); } int main() { pthread_t thread1, thread2, thread3; pthread_create(&thread1, NULL, threadProc, NULL); pthread_create(&thread2, NULL, threadProc, NULL); pthread_create(&thread3, NULL, threadProc, NULL); pthread_join(thread1, NULL); pthread_join(thread2, NULL); pthread_join(thread3, NULL); return 0; }
true
723fe5e5ec6cd0f12fd085ff90a909f944e59569
C++
hchs910739/zerojudge_c
/d057.cpp
UTF-8
478
3.078125
3
[]
no_license
#include<iostream> using namespace std; main(){ int x,y,z; while(cin>>x>>y>>z) { if((x*x+y*y==z*z)||(x*x+z*z==y*y)||(y*y+z*z==x*x)) { cout<<"right triangle"<<endl; } else if((x*x+y*y>z*z)||(x*x+z*z>y*y)||(y*y+z*z>x*x)||(y*y+x*x>z*z)||(z*z+x*x>y*y)||(z*z+y*y>x*x)) { cout<<"acute triangle"<<endl; } else { cout<<"obtuse triangle"<<endl; } } system("pause"); return 0; }
true
041ab8e7cb4f82c6d198de2be3496fd1d0942969
C++
lehuubao1810/fstream2
/bai1.cpp
UTF-8
7,856
3.484375
3
[]
no_license
#include <iostream> using namespace std; // CÂY AVL struct Node{ int key; int bal; // 0: can bang // -1: lech trai // 1:lech phai Node *left; Node *right; Node *parent; }; struct Tree{ Node *root; int NumberNode; int NumeberLeaf; int Hight; }; Node* createNode(int k); void InitTree(Tree &T); int Put(Node *&root, Node* x, Node* parent); int PutNodeTree(Tree &tree, int x); void Rotate_LL(Node *&T); void Rotate_LR(Node *&T); void Rotate_RR(Node *&T); void Rotate_RL(Node *&T); Node* createNode(int k){ Node *n=new Node; n->key=k; n->bal=0; n->left=NULL; n->right=NULL; n->parent=NULL; return n; } void InitTree(Tree &T){ T.root=NULL; T.NumberNode=0; T.NumeberLeaf=0; T.Hight=0; } int Put(Node* &root, Node * x, Node* parent) { // return 0 neu khong lm thay doi chieu cao // return 1 chieu cao thay doi // return -1 khong chen int res=0; if(root!=NULL) { if(root->key == x->key) return -1; if(root->key>x->key){ res=Put(root->left, x,root); //chen vao trai if(res<1) return res; // khong lm thay doi chieu cao switch(root->bal){ case -1: if(root->left->bal==-1) { // LL Rotate_LL(root); } else { if(root->left->bal==1) { // LR Rotate_LR(root); } // return 0; } return 0; case 0: root->bal=-1; return 1; case 1: root->bal=0 ; return 0; } } else { res=Put(root->right, x,root); if(res<1) return res; // khong lm thay doi chieu cao switch(root->bal){ case -1: root->bal=0; return 0; case 0: root->bal=1; return 1; case 1: { if(root->right->bal==1) { // RR Rotate_RR(root); } else { if(root->right->bal==-1) { // RL Rotate_RL(root); } } return 0; } } } } //Node *tmp = createNode(x); x->parent=parent; root=x; return 1; } int PutNodeTree(Tree &tree, int x){ //insert node into tree // Node *p=tree.root; Node *X = createNode(x); if(Put(tree.root,X,NULL)!=-1){ if(tree.root==NULL) { tree.root=X; } tree.NumberNode++; } } bool search(Node *&root,int x,int &count) { if(root!=NULL){ if(root->key==x) { count+=1; return true; //Tim dc nut p co khoa x } if(root->key<x) { count+=1; return search(root->right,x,count); //Tim tiep o ben trai } if(root->key>x) { count+=1; return search(root->left,x,count); } } return false; } void Rotate_LL (Node *&T) { Node *T1 = T->left; T->left = T1->right; T1->right=T; switch(T1->bal) { case 0: T->bal =0; T1->bal=1; break; case -1: T->bal=0; T1->bal=0; break; } // T1->bal=0; T=T1; } void Rotate_LR(Node *&T) { Node *T1=T->left, *T2=T1->right; T->left=T2->right; T2->right=T; T1->right= T2->left; T2->left = T1; switch(T2->bal) { case -1: // T->bal = 0; T->bal = 1; T1->bal= 0; break; case 0: T->bal = 0; T1->bal= 0; break; case 1: T->bal = 0; // T1->bal= 0; T1->bal=-1; break; } T2->bal =0; T=T2; //cout<<T->key; } void Rotate_RR(Node *&T){ Node *T1 = T->right; T->right = T1->left; T1->left=T; switch(T1->bal) { case 1: T->bal =0; T1->bal=0; break; case 0: T->bal=0; T1->bal=-1; break; } T=T1; } void Rotate_RL(Node *&T){ Node *T1= T->right, *T2=T1->left; T->right = T2->left; T2->left = T; T1->left = T2->right; T2->right = T1; switch(T2-> bal) { case 1: T-> bal = -1; T1-> bal = 0; break; case 0: T-> bal = 0; T1-> bal = 0; break; case -1: T-> bal = 0; T1-> bal = 1; break; } T2-> bal =0; T=T2; } void printTree(Node *T){ if (T != NULL){ printTree(T->left); cout << T->key << " "; if (T->left != NULL) cout <<T->left->key << " "; if (T->right != NULL) cout << T->right->key << " "; cout << endl; printTree(T->right); } } // CÂY NHỊ PHÂN struct Node_NP{ int key; Node *left; Node *right; Node *parent; }; struct Tree_NP{ Node * root; int NumberNode; }; Node* CreateNode_NP(int k){ Node *n=new Node; n->key=k; n->left=NULL; n->right=NULL; n->parent=NULL; return n; } void InitTree_NP(Tree &T){ T.root=NULL; T.NumberNode=0; } bool Put_NP(Node*n,Tree &T){ Node *p=T.root; if(T.root==NULL){ T.root=n; return true; } while((n->key>p->key&&p->right!=NULL)||(n->key<p->key&&p->left!=NULL)){ if(n->key==p->key) return false; else{ if(n->key>p->key) p=p->right; else p=p->left;} } if(n->key>p->key) p->right=n; else p->left=n; n->parent=p; return true; } int PutDQ_NP(Node *root, int x) { if(root!=NULL) { if(root->key == x)return 0; if(root->key>x)return PutDQ_NP(root->left, x); else return PutDQ_NP(root->right, x); } root = CreateNode_NP(x); return 1; } // void print(Node *p) { if(p!=NULL) { print(p->left); print(p->right); cout<<p->key<<"\n"; } } int main() { Tree AVL; InitTree(AVL); // int n; // cout<<"Nhap n : "; // cin>>n; // for(int i=0;i<n;i++){ // int k; // cout<<"Nhap so thu "<<i+1<<" : "; // cin>>k; // PutNodeTree(AVL,k); // } //1 3 5 7 9 12 15 17 21 23 25 27 // a // cout<<"<a>"<<endl; // PutNodeTree(AVL,1); // PutNodeTree(AVL,3); // PutNodeTree(AVL,5); // PutNodeTree(AVL,7); // PutNodeTree(AVL,9); // PutNodeTree(AVL,12); // PutNodeTree(AVL,15); // PutNodeTree(AVL,17); // PutNodeTree(AVL,21); // PutNodeTree(AVL,23); // PutNodeTree(AVL,25); // PutNodeTree(AVL,27); // print(AVL.root); // cout<<"-----------------------"<<endl; // int count=0; // search(AVL.root,21,count); // cout<<count; // cout<<endl; cout<<"-----------------------"<<endl; // b cout<<"<b>"<<endl; Tree_NP NP; InitTree_NP(NP); Put_NP(CreateNode_NP(1),NP); Put_NP(CreateNode_NP(3),NP); Put_NP(CreateNode_NP(5),NP); Put_NP(CreateNode_NP(7),NP); Put_NP(CreateNode_NP(9),NP); Put_NP(CreateNode_NP(12),NP); Put_NP(CreateNode_NP(15),NP); Put_NP(CreateNode_NP(17),NP); Put_NP(CreateNode_NP(21),NP); Put_NP(CreateNode_NP(23),NP); Put_NP(CreateNode_NP(25),NP); Put_NP(CreateNode_NP(27),NP); print(NP.root); // if(search(AVL.root,2)) cout<<"Tim thay"<<endl; // else cout<<"Khong tim thay"<<endl; return 0; }
true
14be39631a0271626d4a392f9e322daf1064eec6
C++
vsamy/labyfou
/include/State.h
UTF-8
1,858
3
3
[ "CC0-1.0" ]
permissive
#pragma once #include <memory> #include <map> #include <vector> #include <functional> #include "SFML/System/NonCopyable.hpp" #include "SFML/Window/Event.hpp" #include "utils.h" #include "Player.h" class StateStack; class State { public: typedef std::unique_ptr<State> uPtr; struct Context { Context(sf::RenderWindow& win, TextureHolder& tex, FontHolder& fon, Player& play); sf::RenderWindow* window; TextureHolder* textures; FontHolder* fonts; Player* player; }; public: State(StateStack& stack, Context context); virtual ~State() {} virtual void draw() = 0; virtual bool update(sf::Time dt) = 0; virtual bool handleEvent(const sf::Event& event) = 0; protected: void requestStackPush(StatesID stateID); void requestStackPop(); void requestStateClear(); Context context() const; private: StateStack* stack_; Context context_; }; class StateStack : private sf::NonCopyable { public: enum Action { Push, Pop, Clear, }; public: explicit StateStack(State::Context context); template <typename T> void registerState(StatesID stateID) { factories_[stateID] = [this]() { return State::uPtr(new T(*this, context_)); }; } void update(sf::Time dt); void draw(); void handleEvent(const sf::Event& event); void pushState(StatesID stateID); void popState(); void clearStates(); bool isEmpty() const; private: State::uPtr createState(StatesID stateID); void applyPendingChanges(); private: struct PendingChange { PendingChange(Action act, StatesID sID = StatesID::None); Action action; StatesID stateID; }; private: std::vector<State::uPtr> stack_; std::vector<PendingChange> pendingList_; State::Context context_; std::map<StatesID, std::function<State::uPtr()> > factories_; };
true
21d30952c88867d959727aa4b4bb17a96032b9b9
C++
Moreno-Yassine/Analyseur-LTN
/LTN/src/symboles/Programme.cpp
UTF-8
1,006
2.609375
3
[ "Apache-2.0" ]
permissive
#include "../../include/symboles/Programme.h" Programme::Programme() : Symbole(I_P, "I_P") { } Programme::~Programme() { } bool Programme::setParam(Symbole* symbole, int placeSymbole) { if(placeSymbole==1) ptLd = (Ld*)symbole; else if(placeSymbole==2) ptLi = (Li*)symbole; else return false; return true; } bool Programme::executer() { if(!ptLd->executer()) return false; if(!ptLi->executer()) return false; return true; } bool Programme::display() { if(ptLd==NULL) cout << "Attention : AUCUNE DECLARATION" << endl; if(ptLi==NULL) cout << "Attention : AUCUNE INSTRUCTION" << endl; if(!ptLd->display()) return false; if(!ptLi->display()) return false; return true; } bool Programme::checkModifiedConst() { if(ptLi!=NULL) { return ptLi->checkModifiedConst(); } return false; } bool Programme::checkVarPasAffectees() { vector<Variable*> variables = ptLd->getVariables(); if(ptLi!=NULL) { return ptLi->checkVarPasAffectees(variables); } return false; }
true
f046ebb5cd748c309bdc20f4fef9907a12bf82dd
C++
aryan09/DSA
/Strings/strngPalindrome.cpp
UTF-8
605
2.84375
3
[]
no_license
#include<iostream> using namespace std; int main() { char ch[100],flag; int strt=0,end=0,size,i; flag=cin.get(); for(i=0;flag!='\n';i++) { ch[i]=flag; flag=cin.get(); } i=0; end=size-1; while(i<=size) { if(ch[strt]==ch[end]) { strt++; end--; } else { cout<<"Not palindrome"; break; } if(strt>=end) { cout<<"Palindrome"; break; } i++; } return 0; }
true
65203a1ecbc16df022cef0d3df87abece32e9377
C++
hobby16/code
/ThermK à supprimer/ThermK.ino
UTF-8
6,438
2.796875
3
[]
no_license
/* HMC : routines pour Thermocouple K, testé et validées Mesure avec compensation soudure froide: 1) mesurer R ctn (cold junction) 2) R ctn -> Température, routine R2DegC() 3) T ctn -> mV coldjunction =V0, routine DegC2mV_PQ 4) mesurer mV thermocouple = V1 5) mV compensé V = V0+V1 6 V -> température pour thermocouple K, routine mV2DegC_PQ */ //Sample using LiquidCrystal library #include <LiquidCrystal.h> //------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------ /* Thermistance NTC_MF52AT 10K, Cold junction for Thermocouple K linear interpolation using only int calculations error = 0.1°C max T=Tn + 5*(Rn-R)/(Rn-Rn+1) size table+routine = 180 bytes attention, ne pas mettre table en Flash avec Progmem car size = 210 bytes ! T (°C) R 0 , 28017 5 , 22660 10 , 18560 15 , 16280 20 , 12690 25 , 10000 30 , 8160 35 , 6813 40 , 5734 45 , 4829 50 4065 */ uint16_t NTC0to50[] ={ 28017 , 22660 , 18560 , 16280 , 12690 , 10000 , 8160 , 6813 , 5734 , 4829 , 4065 }; unsigned int R2DegC(unsigned int R) //retourner en dixième°C , par exemple 201 => 20.1°C { unsigned long w; unsigned int t, v, *pt; for (t=0, pt=NTC0to50; t<=450; t+=50) { v=*pt; pt++; if (R> *pt) { w= v-R; //attention, calculs en int => garder l'ordre pour éviter troncature w *=50; w /=v-*pt; return t+(unsigned int)w; } } return 0; //erreur, ne devrait jamais passer si T entre 0 et 50°C } //------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------ /* source = http://aviatechno.net/thermo/thermo04.php précision de l'ordre de 1°C => préférer interpolation par fraction P/Q */ float K_poly[]= { 0.000000E+00 , 2.508355E+01 , 7.860106E-02 , -2.503131E-01 , 8.315270E-02 , -1.228034E-02 , 9.804036E-04 , -4.413030E-05 , 1.057734E-06 , -1.052755E-08 }; float mV2DegC(float mV) //result in degC { float v; v=K_poly[9]; for (int8_t b=8; b>0; b--) //polynomial calc by Horner method { v=mV*(v+K_poly[b]); } return v; } //------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------ /* Thermocouple K, T(°C)->voltage(mV) in -20-70°C interval, for cold junction compensation source = http://www.mosaic-industries.com/embedded-systems/microcontroller-projects/temperature-measurement/thermocouple/calibration-table#computing-cold-junction-voltages To= 2.5000000E+01 Vo= 1.0003453E+00 p1= 4.0514854E-02 p2= -3.8789638E-05 p3= -2.8608478E-06 p4= -9.5367041E-10 q1= -1.3948675E-03 q2= -6.7976627E-05 */ float DegC2mV_PQ(float x) //result in mV { float p,q; x=x-2.5000000E+01; p=x*(4.0514854E-02+x*(-3.8789638E-05+x*(-2.8608478E-06+x*-9.5367041E-10))); q=1+x*(-1.3948675E-03+x*-6.7976627E-05); return 1.0003453E+00+p/q; } //------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------ /* Thermocouple K, voltage(mV) -> T(°C), calc by fraction, bien plus précis qu'avec polynôme deg 9, source = http://www.mosaic-industries.com/embedded-systems/microcontroller-projects/temperature-measurement/thermocouple/calibration-table#computing-cold-junction-voltages coef pour deux intervalles -100 à 100 et 100 à 400°C , précis à 0.01°C près !!! (pour gagner 50 octets, on peut ne garder que code pour 100 à 400°C, reste précis à 1°C près pour 20-100°C => parfait pour heatgun avec thermocouple K ) Vmin= -3.554 4.096 Vmax= 4.096 16.397 Tmin= -100 100 Tmax= 100 400 To= -8.7935962E+00 3.1018976E+02 Vo= -3.4489914E-01 1.2631386E+01 p1= 2.5678719E+01 2.4061949E+01 p2= -4.9887904E-01 4.0158622E+00 p3= -4.4705222E-01 2.6853917E-01 p4= -4.4869203E-02 -9.7188544E-03 q1= 2.3893439E-04 1.6995872E-01 q2= -2.0397750E-02 1.1413069E-02 q3= -1.8424107E-03 -3.9275155E-04 */ float mV2DegC_PQ(float x) //result in degC { // each interval uses 50 bytes flashrom float p,q; if (x<4.096) //intervalle -100 à 100°C { x=x+3.4489914E-01; p=x*(2.5678719E+01+x*(-4.9887904E-01+x*(-4.4705222E-01+x*-4.4869203E-02))); q=1+x*(2.3893439E-04+x*(-2.0397750E-02+x*-1.8424107E-03)); return -8.7935962E+00+p/q; } else //intervalle 100°C à 400°C { x=x-1.2631386E+01; p=x*(2.4061949E+01+x*(4.0158622E+00+x*(2.6853917E-01+x*-9.7188544E-03))); q=1+x*(1.6995872E-01+x*(1.1413069E-02+x*-3.9275155E-04)); return 3.1018976E+02+p/q; } } //------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------------------ // select the pins used on the LCD panel LiquidCrystal lcd(8, 9, 4, 5, 6, 7); unsigned int t0; void setup() { t0=millis(); lcd.begin(16, 2); // start the library } //---------------------------- void loop() { if (((unsigned int)millis() -t0) > 1000) { t0+=1000; lcd.setCursor(0,1); // move to the begining of the second line // lcd.print(R2DegC(4354)); // lcd.print(mV2DegC(4.096),3); // lcd.print(mV2DegC_PQ(0.397),3); lcd.print(DegC2mV_PQ(25),3); lcd.print(" "); } }
true
65c54fbc27383a6f738020ad664a709a9b3d3c92
C++
hayate242/lecture2019_applied_system_analysis
/kadaiB/systemA/MM3.cpp
UTF-8
4,579
2.796875
3
[]
no_license
#include "MM3.hpp" #include <algorithm> #include <random> #define SERVICE_NUM 3 std::tuple<double, double> MM3::simulation(double lambda, double mu, double startTime, double endTime) { // 初期化 vector<double> service; // 窓口 queue<double> systems[SERVICE_NUM]; //待ち行列 Random random; // ランダムクラスの宣言 SimStat simStat = StandBy; // 過渡状態、過渡状態以降を定義 double service_interval; // サービス間隔 double arrive; // 到着間隔 currentTime = 0.0; simEndJobs = 0.0; stayTime = 0.0; visitors = 0.0; // 処理開始(最初のイベントをイベントキューに登録) event.selectedLine = random.genRand(0, 2); event.time = currentTime + random.expDistribution(lambda); event.eventState = ARRIVE; eventQueue.push(event); // 窓口初期化 for (int i = 0; i < SERVICE_NUM; i++){ service.push_back(-1.0); } int cnt_selectedLines[3] = {0,0,0}; // 終了時間まで繰り返す while (currentTime < endTime) { // 最初のイベントを取り出す event = eventQueue.top(); eventQueue.pop(); // 現在時刻をイベント発生時刻まですすめる currentTime = event.time; switch (event.eventState) { // 到着イベントの場合 case ARRIVE: // 待ち行列への登録 systems[event.selectedLine].push(event.time); // イベントキューへのサービス到着イベントの登録 event.selectedLine = random.genRand(0, 2); event.time = currentTime + random.expDistribution(lambda); event.eventState = ARRIVE; eventQueue.push(event); break; // サービス終了イベントの場合 case FINISH: // 過渡状態中の統計値はリセットする if (currentTime > startTime && simStat == StandBy) { simStat = Execution; stayTime = 0.0; visitors = 0.0; simEndJobs = 0.0; } // 統計処理(待ち時間,客数等のカウント) int cnt_in_service = 0; for (int i = 0; i < SERVICE_NUM; i++) { if(service[i] != -1.0 ){ cnt_in_service++; } } cnt_selectedLines[event.selectedLine]++; visitors += cnt_in_service + systems[0].size() + systems[1].size() + systems[2].size(); //自分のサービス分,1引く // printf("visitors = %f\n", visitors); // printf("%f - %f ,staytime = %f\n", currentTime, service[event.selectedLine], currentTime - service[event.selectedLine]); stayTime += (currentTime - service[event.selectedLine]); // printf("currentTime= %f, service[%d] = %f, stayTime = %f\n", currentTime, event.selectedLine, service[event.selectedLine], currentTime - service[event.selectedLine]); simEndJobs++; // 窓口のクリア(先頭の要素だけ削除) if(service.size() > 0){ // service.erase(service.begin() + selectedLine); service[event.selectedLine] = -1.0; } break; } // 3つの列の窓口で,並んでる列の窓口に人がいなくて,待ち行列に人がいる場合 for (int i = 0; i < SERVICE_NUM; i++){ if (service[i] == -1.0 && systems[i].empty() == false) { // 待ち行列の先頭から窓口への移動 service[i] = systems[i].front(); systems[i].pop(); // debug // {for(int i=0;i<service.size();i++) printf("%f,",service[i]);} // printf("size = %lu\n", service.size()); // イベントキューへのサービス到着イベントの登録 event.selectedLine = i; event.time = currentTime + random.expDistribution(mu); event.eventState = FINISH; eventQueue.push(event); break; } } } for (int i = 0; i < SERVICE_NUM; i++){ printf("%d, ", cnt_selectedLines[i]); } printf("\n"); // 結果の返却 // return std::forward_as_tuple(システム内客数, システム内時間); return std::forward_as_tuple(visitors / simEndJobs, stayTime / simEndJobs); }
true
173acefc633845618520aa6f596a6f63a159f798
C++
iguessthislldo/georgios_computer
/vm/src/main.cpp
UTF-8
950
2.921875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string> #include "System.hpp" void print_help() { fprintf(stderr, "usage: georgios [-v|-h] FILEPATH MEMORY_SIZE\n"); } int main(int argc, char * argv[]) { if (argc == 1 || argc >= 5) { print_help(); return 100; } bool verbose = false; char * file; int size; if (argc == 2) { print_help(); if (argv[1][0] == '-' && argv[1][1] == 'h') return 0; return 100; } else if (argc == 3) { file = argv[1]; size = atoi(argv[2]); } else if (argc == 4) { if (argv[1][0] == '-' && argv[1][1] == 'v') verbose = true; else { print_help(); return 100; } file = argv[2]; size = atoi(argv[3]); } if (verbose) fprintf(stderr, "Verbose Mode\n"); System system(file, size, verbose); return system.run(); }
true
2a1471535afce42115c092e23c4dc5d87c8e3053
C++
stanleeyY/CS3391-Assignments
/192.cpp
UTF-8
577
2.9375
3
[]
no_license
#include <iostream> #include <string> using namespace std; int check(); int main() { int T; cin >> T; int ctr = 0; while (ctr<T) { if (check() == 0) cout << "NO" << endl; else cout << "YES" << endl; if (ctr != T - 1) cout << endl; ctr++; } return 0; } int check() { int wL, dL, wR, dR; int sum = 0; cin >> wL >> dL >> wR >> dR; //cout << wL << " " << dL << " " << wR << " " << dR << " " << endl; if (wL < 1) wL = check(); if (wR < 1) wR = check(); if (wL*dL == wR * dR) sum = wL+wR; return sum; }
true
d95489a44e30e724d57148f5b8d9903aa6ce034b
C++
wraithtc/timertask
/helloworld.cpp
UTF-8
684
2.546875
3
[]
no_license
#include <iostream> #include "timertask.h" using namespace std; map<int, string> g_testMap; void wifi_handler(int isIn) { if (isIn) cout << "wifi down" << endl; else { cout << "wifi up" << endl; } } int main() { timertask t; TASK_DURATION_INFO di = {TASK_DURATION (TIME_INFO (22,23), TIME_INFO (4, 22)),1, 0,0}; TASK_DURATION_INFO di2 = {TASK_DURATION (TIME_INFO (11,22), TIME_INFO (22, 33)),1, 0,0}; t.AddTask(1 << 2 | 1 << 3 | 1 << 4, di, "wifi", wifi_handler); t.AddTask(1 << 0 | 1 << 3 | 1 << 5, di2, "wifi", wifi_handler); t.printTask(); t.taskRun(); system("pause"); return 0; }
true
5e3691fcbf16cbb76cee4ddb974bb0fee67afce9
C++
19127618student/oop
/w5/19127618_NguyenThanhTung/Project4/Header.h
UTF-8
3,525
2.6875
3
[]
no_license
#ifndef _HEADER_H_ #define _HEADER_H_ #include <iostream> #include <vector> #include <string> using namespace std; class interface { public: virtual void getName() {}; virtual double getSize() = 0 {}; virtual int SoLuong() = 0 {}; }; class TapTin : public interface { protected: string Ten; double KichThuoc; public: TapTin() {} TapTin(const string& t, const double& kt) { Ten = t; KichThuoc = kt; } void setTen(const string& t) { Ten = t; } void setKT(const double& kt) { KichThuoc = kt; } void getName() override { cout << "\t\t" << Ten << "\t " << KichThuoc << " B\n"; } double getSize() override { return KichThuoc; } string getT() { return Ten; } void disIF() { cout << getT() << "" << KichThuoc << " B" << endl; } int SoLuong() override { return 1; } }; class ThuMuc : public TapTin, public interface { protected: string Name; double Size; vector<TapTin*> TT; vector<ThuMuc*> TM; int SL; public: static int k; ThuMuc() { TT.resize(0); Size = 0; SL = 0; } ThuMuc(const string& n) { TT.resize(0); Name = n; SL = 0; } void setName(const string& n) { Name = n; } void setSize(const double& s) { Size = s; } void disIF() { cout << "[" << Name << "]" << endl; } void getName() override { for (int j = 0; j < k - 1; j++) { cout << "\t "; } cout << "[" << Name << "]" << endl; for (int j = 0; j < k - 2; j++) { cout << "\t "; } if (!TT.empty()) { for (auto i = TT.begin(); i != TT.end(); i++) if (*i) { (*i)->getName(); k++; } } //for (int j = 0; j < k; j++) { cout << "\t"; } if (!TM.empty()) for (auto i = TM.begin(); i != TM.end(); i++) if (*i) { k++; (*i)->getName(); } } double getSize() override { if (!TT.empty()) for (auto i = TT.begin(); i != TT.end(); i++) if (*i) Size += (*i)->getSize(); if (!TM.empty()) for (auto i = TM.begin(); i != TM.end(); i++) if (*i) Size += (*i)->getSize(); return Size; } void addFile(TapTin* tt) { TT.push_back(tt); SL++; } void addFolder(ThuMuc* tm) { TM.push_back(tm); SL++; } int SoLuong() { return SL; } }; class QLTM : public interface { protected: vector<ThuMuc*>TM; vector<QLTM*>QL; string name; double SiZe; int SL; public: static int kk; QLTM() { QL.resize(0); TM.resize(0); SiZe = 0; SL = 0; } QLTM(const string& n) { name = n; SiZe = 0; SL = 0; QL.resize(0); TM.resize(0); } void addTM(ThuMuc* tm) { TM.push_back(tm); SL++; } void addQLTM(QLTM* ql) { QL.push_back(ql); SL++; } void getName() override { cout << "[" << name << "]\n"; if (!TM.empty()) for (auto i = TM.begin(); i != TM.end(); i++) if (*i) { ThuMuc::k = kk; cout << "\t"; (*i)->getName(); } if (!QL.empty()) for (auto i = QL.begin(); i != QL.end(); i++) if (*i) { ThuMuc::k = kk; kk++; (*i)->getName(); } } double getSize() override { if (!TM.empty()) for (auto i = TM.begin(); i != TM.end(); i++) if (*i) { SiZe += (*i)->getSize(); } if (!QL.empty()) for (auto i = QL.begin(); i != QL.end(); i++) if (*i) { SiZe += (*i)->getSize(); } return SiZe; }; int SoLuong() { return SL; } ~QLTM() { if (!QL.empty()) for (auto i = QL.begin(); i != QL.end(); i++) if (*i) delete* i; if (!TM.empty()) for (auto i = TM.begin(); i != TM.end(); i++) if (*i) delete* i; } }; void menu(QLTM& Q, ThuMuc& bt, ThuMuc& lt, ThuMuc& btc); #endif
true
56f5d8fbb78bbd59c0675fc174ae521909e8b043
C++
arnaudgelas/Examples
/c++/Broken/Iterator/Iterators.cpp
UTF-8
1,100
3.328125
3
[]
no_license
#include <iostream> #include <vector> #include <map> void Input(); void Output(); void AllMapElements(); int main(int argc, char *argv[]) { //Input(); //Output(); AllMapElements(); return 0; } void Input() { std::vector<double> a; a.push_back(1.2); a.push_back(1.3); a.push_back(1.4); a.push_back(1.5); a.push_back(1.6); std::vector<double>::iterator i; i = a.begin(); while( i != a.end() ) { std::cout << *i << std::endl; i++; } } void Output() { std::vector<double> a(5); std::vector<double>::iterator i; i = a.begin(); int counter = 0; while( i != a.end() ) { *i = counter; counter++; i++; } i = a.begin(); while( i != a.end() ) { std::cout << *i << std::endl; i++; } } void AllMapElements() { std::map <double, int> MyMap; MyMap[56.7] = 5; MyMap[99.3] = 9; MyMap[12.9] = 1; std::map <double, int>::iterator i; i = MyMap.begin(); while( i != MyMap.end() ) { std::cout << i->first << std::endl; std::cout << i->second << std::endl; std::cout << std::endl; i++; } }
true
62e628fbe26aa1368733c39426cbd2c43b9a4dc8
C++
Noor1504/Stack-Application
/stackXML.cpp
UTF-8
14,059
3.25
3
[]
no_license
#include "stackXML.h" tT Node<T>::Node() {} tT Node<T>::Node(const T val) { this->data=val; } tT Stack<T>::Stack() { top=nullptr; } tT bool Stack<T>::IsEmpty() { if(!top) return true; return false; } tT bool Stack<T>::pop(T &val) { if(!IsEmpty()) { val=top->data; Node<T>* aux = top; top=top->next; aux->next=nullptr; aux=nullptr; return true; } return false; } tT bool Stack<T>::push(const T &val) { Node<T>* aux=new Node<T>(val); aux->next=top; top=aux; return true; } tT void Stack<T>::print() { Node<T>* aux=top; while(aux!=nullptr) { cout<<aux->data<<"\t"; if(aux->next==nullptr) break; aux=aux->next; } } tT T Stack<T>::Top() { return top->data; } tT Stack<T>::~Stack() { } XMLData::XMLData() { lineNumber=0; StartOrEnd=0; } void XMLData::printXML() { cout<<"Tag name = "<<tagText<<", Line Number = "<<lineNumber<<", "; if(!StartOrEnd) cout<<"Starting tag\n"; else cout<<"Ending tag\n"; } void checkXML(string filename) { Stack<XMLData> St; int lineCounter = 1; bool foundError = false; bool attributeError = false; ifstream fin; fin.open(filename); while(!fin.eof()) { XMLData xml; string line; getline(fin, line, '\n');//reads whole line so that line number can be tracked int CurrentLineLength=line.length(); while( CurrentLineLength>0 ) { int OpeningAngularBracketIndex = line.find('<'); int ClosingAngularBracketIndex = line.find('>'); if(OpeningAngularBracketIndex == -1 && ClosingAngularBracketIndex == -1)//if true, it means the current line contain no tag CurrentLineLength = 0; //NOTE: XML prolog is optional. If it exists, it must come first in the document. if(line[OpeningAngularBracketIndex+1] == '?')//if true, it's a prolog { if(lineCounter==1) { line = line.substr(OpeningAngularBracketIndex+2, line.size());//ignore s[0]='<' and s[1]='?' CurrentLineLength=line.length(); int endOfProlog = line.find("?>"); if(endOfProlog==-1)//if false, it means prolog is complete { cout<<"---- ERROR ---- \tThe prolog is not complete.\n"; foundError = true; break; } else//if prolog is complete, then check if there is another tag { int secondAngularBracketIndex = line.find('<'); if (secondAngularBracketIndex==-1)//if there is no other tag besides prolog, then clear the current line { CurrentLineLength=0; } else//else, delete the contents of line before another tag (i.e., tag after prolog in the current line) { line = line.substr(secondAngularBracketIndex, line.size()); CurrentLineLength=line.length(); } } } else//if prolog is not in the first line; show error { cout<<"---- ERROR ---- \tProlog must be at the start of xml file.\n"; foundError = true; break; } } //check if there's a proper end of prolog else if( (OpeningAngularBracketIndex==-1 || OpeningAngularBracketIndex>ClosingAngularBracketIndex) && line[ClosingAngularBracketIndex-1]=='?' ) { if(lineCounter==1) { cout<<"---- ERROR ---- \tThere's no start of prolog but its end exists.\n"; foundError = true; break; } else { cout<<"---- ERROR ---- \tThere's no start of prolog but its end exists. It's at line "<<lineCounter<<" (prolog must be at line 1)\n"; foundError = true; break; } } //check if it's end of a comment else if( (line[ClosingAngularBracketIndex-1] == '-') && (line[ClosingAngularBracketIndex-2] == '-') && (line.find("-->")==line.find("--")) ) { xml=St.Top(); if(xml.tagText == "Comment") { St.pop(xml); //cout<<"Popped: "; xml.printXML(); } else { cout<<"---- ERROR ---- \tfound closing tag of Comment at line "<<lineCounter<<", but there's no starting tag for it."; foundError = true; break; } line = line.substr(ClosingAngularBracketIndex+1, line.size()); CurrentLineLength=line.length(); } //check if it's start of a simple tag with or without attribute. else if( (line[OpeningAngularBracketIndex]=='<') && ((line[OpeningAngularBracketIndex+1] >= 65 && line[OpeningAngularBracketIndex+1] <= 90) || (line[OpeningAngularBracketIndex+1] >=97 && line[OpeningAngularBracketIndex+1] <= 122)) /*&& (OpeningAngularBracketIndex < ClosingAngularBracketIndex)*/ ) { xml.lineNumber=lineCounter; xml.StartOrEnd=0; string Tag; int FirstSpaceAfterTag = line.find(' '); //check if there's an attribute if(FirstSpaceAfterTag != -1 && (FirstSpaceAfterTag < ClosingAngularBracketIndex || ClosingAngularBracketIndex==-1)) { Tag = line.substr(1, FirstSpaceAfterTag-1); line = line.substr(FirstSpaceAfterTag+1, line.size());//delete tag name from current line int firstQuoteS = line.find("'");//find first single quote int firstQuoteD = line.find('"');//find first double quote //if first "double quote" exists and there's a charachter after that double quote (i.e., name of attribute) if(firstQuoteD<firstQuoteS && firstQuoteD!=-1 && ((line[firstQuoteD+1] >= 65 && line[firstQuoteD+1] <= 90) || (line[firstQuoteD+1] >=97 && line[firstQuoteD+1] <= 122))) { line=line.substr(firstQuoteD+1, line.size());//delete line from start upto first double quote(icluding) int secondQuoteD = line.find('"');//find second double quote ClosingAngularBracketIndex = line.find('>');//update index of '>' //checking if current tag is properly closed; both when there's only one tag or multiple tags in a single line. if( (ClosingAngularBracketIndex==-1 || (secondQuoteD!=-1 && secondQuoteD<ClosingAngularBracketIndex)) && ( (line.find("\">")==-1) || (line.find("\">")!=-1 && secondQuoteD<line.find("\">")) ) ) { cout<<"---- ERROR ---- \tNo proper closing of tag: <"<<Tag<<"> at line "<<lineCounter; foundError = true; break; } //checking if current attribute is quoted; both when there's only one attribute or multiple attributes in a single line. else if(ClosingAngularBracketIndex!=-1 && (secondQuoteD>ClosingAngularBracketIndex || secondQuoteD==-1)) { cout<<"---- ERROR ---- \tThe attribute is not properly quoted at line "<<lineCounter; attributeError = true; break; } } //if first 'single quote' exists and there's a charachter after that single quote (i.e., name of attribute) else if(firstQuoteS!=-1 && ((line[firstQuoteS+1] >= 65 && line[firstQuoteS+1] <= 90) || (line[firstQuoteS+1] >=97 && line[firstQuoteS+1] <= 122))) { line=line.substr(firstQuoteS+1, line.size());//delete line from start upto first single quote(icluding) int secondQuoteS = line.find("'");//find second 'single quote' ClosingAngularBracketIndex = line.find('>');//update index of '>' //checking if current tag is properly closed; both when there's only one tag or multiple tags in a single line. if( (ClosingAngularBracketIndex==-1 || (secondQuoteS!=-1 && secondQuoteS<ClosingAngularBracketIndex)) && ( (line.find("'>")==-1) || (line.find("'>")!=-1 && secondQuoteS<line.find("'>")) ) ) { cout<<"---- ERROR ---- \tNo proper closing of tag: <"<<Tag<<"> at line "<<lineCounter; foundError = true; break; } //checking if current attribute is quoted; both when there's only one attribute or multiple attributes in a single line. else if(ClosingAngularBracketIndex!=-1 && (secondQuoteS>ClosingAngularBracketIndex || secondQuoteS==-1)) { cout<<"---- ERROR ---- \tThe attribute is not properly quoted at line "<<lineCounter; attributeError = true; break; } } } else//if there's no attribute Tag = line.substr(1, ClosingAngularBracketIndex-1); xml.tagText=Tag; St.push(xml); //cout<<"Pushed: "; xml.printXML(); ClosingAngularBracketIndex=line.find('>'); line = line.substr( ClosingAngularBracketIndex+1, line.size()); CurrentLineLength=line.length(); } //icheck if it's end of a simple tag with or without attribute. else if( (line[OpeningAngularBracketIndex]=='<') && (line[OpeningAngularBracketIndex+1]=='/') && ((line[OpeningAngularBracketIndex+2] >= 65 && line[OpeningAngularBracketIndex+2] <= 90) || (line[OpeningAngularBracketIndex+2] >=97 && line[OpeningAngularBracketIndex+2] <= 122)) ) { line = line.substr(OpeningAngularBracketIndex+2, line.size()); int TagLength = line.find('>'); string Tag = line.substr(0, TagLength); if(!St.IsEmpty())//check if there's a starting tag against incoming ending tag xml = St.Top(); else { cout<<"---- ERROR ---- \tfound closing tag: </"<<Tag<<"> at line "<<lineCounter<<", but there's no starting tag for it."; foundError = true; break; } int x=xml.tagText.compare(Tag); if(x==0) { St.pop(xml); //cout<<"Popped: "; xml.printXML(); } else { cout<<"---- ERROR ---- \tThere MUST be a closing tag: </"<<xml.tagText<<"> before encountered closing tag i.e., </"<<Tag<<"> at line "<<lineCounter; foundError = true; break; } line = line.substr(TagLength+1, line.size()); CurrentLineLength=line.length(); } //check if it's start of a comment else if(line[OpeningAngularBracketIndex+1] == '!' && line[OpeningAngularBracketIndex+2] == '-' && line[OpeningAngularBracketIndex+3] == '-') { line = line.substr(OpeningAngularBracketIndex+4, line.size());// <!-- these 4 charachters are deleted from string CurrentLineLength=line.length(); xml.lineNumber=lineCounter; xml.StartOrEnd=0; xml.tagText="Comment"; St.push(xml); //cout<<"Pushed: "; xml.printXML(); } //check if there are double dashes in the comment else if( line.find("--") != line.find("-->") ) { if(OpeningAngularBracketIndex==-1 && ClosingAngularBracketIndex==-1) { CurrentLineLength=0; } else { cout<<"---- ERROR ---- \tAt line "<<lineCounter<<", Two dashes in the middle of a comment are not allowed."; foundError = true; break; } } } if(foundError || attributeError) break; lineCounter++; } //show error if stack is not empty if(!St.IsEmpty() && !attributeError && !foundError) { cout<<"---- ERROR ---- \tFound "; if(St.Top().StartOrEnd==0) cout<<"Starting"; else cout<<"Ending"; cout<<" tag \""<<St.Top().tagText<<"\" at line "<<St.Top().lineNumber<<" but it has no "; if(St.Top().StartOrEnd==0) cout<<"Ending"; else cout<<"Starting"; cout<<" tag\n"; } else if(!foundError && !attributeError) cout<<"No Error found in this xml file.\n"; fin.close(); } int main() { checkXML("xml.txt"); return 0; }
true
60c97ae2c7b44124c5465576fcd1e32db44ddf95
C++
YujinHa/Baekjoon
/5032.cpp
UTF-8
265
3.015625
3
[]
no_license
#include<iostream> using namespace std; int main() { int e, f, c, bottle, result = 0; cin >> e >> f >> c; bottle = e + f; while ((bottle / c) != 0) { result += bottle / c; bottle = (bottle / c) + (bottle % c); } cout << result << endl; return 0; }
true
d847c67196c81a2b78a7cadf44f722148994b194
C++
meihao1203/learning
/03202018/priority_queue.cpp
UTF-8
566
3.3125
3
[]
no_license
/// /// @file priority_queue.cpp /// @author meihao1203(meihao19931203@outlook.com) /// @date 2018-03-20 15:06:09 /// #include<iostream> #include<queue> using namespace std; int main() { int arr[] = {0, 1, 3, 2, 5, 6, 9, 8, 7, 4}; priority_queue<int> ob1; // 优先队列,默认从大到小 for(int i=0;i!=sizeof(arr)/sizeof(int);++i) ob1.push(arr[i]); cout<<"priority size="<<ob1.size()<<endl; for(int i=0;i!=sizeof(arr)/sizeof(int);++i) { cout<<ob1.top()<<" "; ob1.pop(); } cout<<endl; return 0; } //priority size=10 //9 8 7 6 5 4 3 2 1 0
true
6b8c392f51baa199c1f72c575deac3d3a9ae163e
C++
QuantumBird/ACM_Team
/gjz/Codeforces/Problem/1204A.cpp
UTF-8
291
2.671875
3
[]
no_license
#include <iostream> #include <string> using namespace std; int main(){ string s; cin>>s; int cnt = 0; for(int i = 0; i < s.length(); i ++) if(s[i] == '1') cnt ++; int ans = (s.length() - 1) / 2 + (cnt > 1? 1: 0); cout<<ans<<endl; return 0; }
true
b9e2039ffc0eba0a95252483486175ff9611da3d
C++
Alex-Sol/LeetCode-Notes
/Ceetcode/二叉树/MirrorBTree.cpp
UTF-8
949
3.84375
4
[]
no_license
/* 使用栈完成中序遍历 */ void MirroInBFS(TreeNode* root) { if(root==nullptr) return; stack<TreeNode *> nstack; TreeNode *node = root; while(node!=nullptr ||!nstack.empty()) { while(node!=nullptr) { nstack.push(node); node=node->left; } if(!nstack.empty()) { node = nstack.top(); if(node->left!=nullptr || node->right!=nullptr) std::swap(node->left,node->right); nstack.pop(); node=node->left; // 本来是 right,但是发生了交换 } } } /* 使用队列完成层序遍历 */ void MirroLayerBFS(TreeNode* root) { if(root==nullptr) return; queue<TreeNode *> nqueue; nqueue.push(root); TreeNode *node =root; while(!nqueue.empty()) { node = nqueue.front(); nqueue.pop(); if(node->left!=nullptr || node->right!=nullptr) std::swap(node->left,node->right); if(node->left!=nullptr) nqueue.push(node->left); if(node->right!=nullptr) nqueue.push(node->right); } }
true
ff09e41b258d114b0678033638586b7c1d968a8a
C++
uthnp/HW04_uthnp
/include/uthnpStarbucks.h
UTF-8
1,592
3.265625
3
[]
no_license
/* * @Author Nicholas Uth * October 29, 2012 -- CSE 274 * * @Sources: Child class to Starbucks class by Bo Brinkman. * * Class is intended to work as a KD tree. It handles the coordinates and description of a starbucks and the paths to it's subtrees. * */ #pragma once #include <string> #include "Starbucks.h" using namespace std; class uthnpStarbucks : Starbucks { public: uthnpStarbucks* left; uthnpStarbucks* right; Entry* entry; Entry* candidate; static const int threshold = 0.00001; //int numIter; /* * Creates a null node. Can be used as a root or just a basic null tester. */ uthnpStarbucks(); /* * Creates a new node with the given Entry data (x,y coords and description) */ uthnpStarbucks(Entry* data); /* * Deletes the contents of the node and the node itself. */ ~uthnpStarbucks(); /* * Recursively adds a node to the KD tree. Alternatingly sorts the levels based on X or Y coordinate. */ //void add(Entry* data, bool isX); uthnpStarbucks* add(Entry* data, bool isX); /* * Builds an entire tree from an array containing Entry objects. */ virtual void build(Entry* c, int n); /* * Randomizes the order of an array's contents. * NOTE: obsolete. Replaced by a 1 line call to the std algorithm method random_shuffle */ Entry* randomizeArray (Entry* input, int len); /* * Recursively (alternating X and Y) searches the tree for the node containing the closest Starbucks location. */ virtual Entry* getNearest(double x, double y); /* * Helps the getNearest function with the recursive search. */ Entry* searchMatch(double x, double y, bool isX); };
true
0074d7f12c459fa704d893a307e935a8d6a9f2d7
C++
shenzhu/Quokka
/util/StringView.cc
UTF-8
2,149
3.265625
3
[]
no_license
#include <algorithm> #include <cassert> #include <cstring> #include "StringView.h" namespace Quokka { StringView::StringView() : data_(nullptr), len_(0) { } StringView::StringView(const char* p) : data_(p), len_(strlen(p)) { } StringView::StringView(const std::string& str) : data_(str.data()), len_(str.size()) { } StringView::StringView(const char* p, size_t size) : data_(p), len_(1) { } const char& StringView::operator[](size_t index) const { assert(index >= 0 && index < len_); return data_[index]; } const char* StringView::data() const { return data_; } const char& StringView::front() const { assert(len_ > 0); return data_[0]; } const char& StringView::back() const { assert(len_ > 0); return data_[len_ - 1]; } const char* StringView::begin() const { return data_; } const char* StringView::end() const { return data_ + len_; } size_t StringView::size() const { return len_; } bool StringView::empty() const { return len_ == 0; } void StringView::removePrefix(size_t n) { data_ += n; len_ -= n; } void StringView::removeSuffix(size_t n) { len_ -= n; } void StringView::swap(StringView& other) { if (this != &other) { std::swap(this->data_, other.data_); std::swap(this->len_, other.len_); } } StringView StringView::substr(size_t pos, size_t length) const { assert(length < len_); return StringView(data_ + pos, length); } std::string StringView::toString() const { return std::string(data_, len_); } bool operator==(const StringView& a, const StringView& b) { return a.size() == b.size() && strncmp(a.data(), b.data(), a.size()) == 0; } bool operator!=(const StringView& a, const StringView& b) { return !(a == b); } bool operator<(const StringView& a, const StringView& b) { int result = strncmp(a.data(), b.data(), a.size()); if (result != 0) { return result < 0; } return a.size() < b.size(); } bool operator>(const StringView& a, const StringView& b) { return !(a < b || a == b); } bool operator<=(const StringView& a, const StringView& b) { return !(a > b); } bool operator>=(const StringView& a, const StringView& b) { return !(a < b); } } // namespace Quokka
true
fbdcab9f37f9ed8748fb32a7db3486e03c6fce88
C++
wbach/GameEngine
/Resources/Models/Mesh.cpp
UTF-8
5,558
2.625
3
[]
no_license
#include "Mesh.h" #include "../../Utils/GLM/GLMUtils.h" #include "../../Utils/OpenGL/OpenGLUtils.h" CMesh::CMesh() { } CMesh::CMesh( std::vector<float>& positions, std::vector<float>& text_coords, std::vector<float>& normals, std::vector<float>& tangents, std::vector<unsigned short>& indices, SMaterial & material, std::vector<SVertexBoneData>& bones) { m_Positions = std::move(positions); m_TextCoords = std::move(text_coords); m_Normals = std::move(normals); m_Tangents = std::move(tangents); m_Indices = std::move(indices); m_Tangents = std::move(tangents); m_Bones = std::move(bones); m_Material = material; m_VertexCount = m_Indices.size() > 0 ? m_Indices.size() : m_Positions.size() / 3; if (!m_Positions.empty()) m_Attributes.push_back(0); if (!m_TextCoords.empty()) m_Attributes.push_back(1); if (!m_Normals.empty()) m_Attributes.push_back(2); if (!m_Tangents.empty()) m_Attributes.push_back(3); CalculateBoudnigBox(m_Positions); } CMesh::~CMesh() { if (!m_IsInit) return; for(auto& vbo : m_Vbos) { if(vbo != 0) glDeleteBuffers(1, &vbo); } glDeleteVertexArrays(1, &m_Vao); m_IsInit = false; } void CMesh::CalculateBoudnigBox(const std::vector<float>& positions) { Utils::CalculateBoudnigBox(positions, m_BoundingBox.m_BoundingBoxMin, m_BoundingBox.m_BoundingBoxMax, m_BoundingBox.m_BoundingSize, m_BoundingBox.m_BoundingCenter); } void CMesh::UpdateVertexPosition(const std::vector<float>& vertices) const { glBindBuffer(GL_ARRAY_BUFFER, m_Vbos[VertexBufferObjects::POSITION]); glBufferSubData(GL_ARRAY_BUFFER, 0, vertices.size() * sizeof(float), &vertices[0]); } void CMesh::CreateVaoMesh() { m_Vao = Utils::CreateVao(); if (m_Indices.size() > 0) { GLuint vboId = Utils::BindIndicesBuffer(m_Indices); m_Vbos[VertexBufferObjects::INDICES] = vboId; } if (m_Positions.size() > 0) { GLuint vboId = Utils::StoreDataInAttributesList(0, 3, m_Positions); m_Vbos[VertexBufferObjects::POSITION] = vboId; } if (m_TextCoords.size() > 0) { GLuint vboId = Utils::StoreDataInAttributesList(1, 2, m_TextCoords); m_Vbos[VertexBufferObjects::TEXT_COORD] = vboId; } if (m_Normals.size() > 0) { GLuint vboId = Utils::StoreDataInAttributesList(2, 3, m_Normals); m_Vbos[VertexBufferObjects::NORMAL] = vboId; } if (m_Tangents.size() > 0) { GLuint vboId = Utils::StoreDataInAttributesList(3, 3, m_Tangents); m_Vbos[VertexBufferObjects::TANGENT] = vboId; } Utils::UnbindVao(); m_IsInit = true; } void CMesh::CreateTransformsVbo(std::vector<glm::mat4>& m) { glBindVertexArray(m_Vao); glGenBuffers(1, &m_Vbos[VertexBufferObjects::TRANSFORM_MATRIX]); glBindBuffer(GL_ARRAY_BUFFER, m_Vbos[VertexBufferObjects::TRANSFORM_MATRIX]); for (uint i = 0; i < 4; i++) { glEnableVertexAttribArray(4 + i); glVertexAttribPointer(4 + i, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4), (const GLvoid*)(sizeof(GLfloat) * i * 4)); glVertexAttribDivisor(4 + i, 1); } glBufferData(GL_ARRAY_BUFFER, sizeof(glm::mat4) * m.size(), &m[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); m_TransformVboCreated = true; } void CMesh::UpdateTransformVbo(std::vector<glm::mat4>& m) { glDeleteBuffers(1, &m_Vbos[VertexBufferObjects::TRANSFORM_MATRIX]); glBindVertexArray(m_Vao); glGenBuffers(1, &m_Vbos[VertexBufferObjects::TRANSFORM_MATRIX]); glBindBuffer(GL_ARRAY_BUFFER, m_Vbos[VertexBufferObjects::TRANSFORM_MATRIX]); for (uint i = 0; i < 4; i++) { glEnableVertexAttribArray(4 + i); glVertexAttribPointer(4 + i, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4), (const GLvoid*)(sizeof(GLfloat) * i * 4)); glVertexAttribDivisor(4 + i, 1); } glBufferData(GL_ARRAY_BUFFER, sizeof(glm::mat4) * m.size(), &m[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } void CMesh::CreateBoneVbo(const std::vector<SVertexBoneData>& bones) { glBindVertexArray(m_Vao); glGenBuffers(1, &m_Vbos[VertexBufferObjects::BONES]); glBindBuffer(GL_ARRAY_BUFFER, m_Vbos[VertexBufferObjects::BONES]); glBufferData(GL_ARRAY_BUFFER, sizeof(bones[0]) * bones.size(), &bones[0], GL_STATIC_DRAW); glEnableVertexAttribArray(8); glVertexAttribIPointer(8, 4, GL_INT, sizeof(SVertexBoneData), (const GLvoid*)0); glEnableVertexAttribArray(9); glVertexAttribPointer(9, 4, GL_FLOAT, GL_FALSE, sizeof(SVertexBoneData), (const GLvoid*)16); glBindVertexArray(0); m_BonesInShader = true; } void CMesh::SetInstancedMatrixes(const std::vector<glm::mat4>& m) { m_InstancedMatrixes = m; } void CMesh::OpenGLLoadingPass() { CreateVaoMesh(); if (!m_Bones.empty()) { CreateBoneVbo(m_Bones); } ClearData(); } void CMesh::OpenGLPostLoadingPass() { CreateTransformsVbo(m_InstancedMatrixes); } const GLuint& CMesh::GetVao() const { return m_Vao; } const GLuint & CMesh::GetVbo(VertexBufferObjects::Type type) const { return m_Vbos[type]; } const SMaterial & CMesh::GetMaterial() const { return m_Material; } void CMesh::ClearData() { m_Positions.clear(); m_TextCoords.clear(); m_Normals.clear(); m_Tangents.clear(); m_Indices.clear(); m_Bones.clear(); m_InstancedMatrixes.clear(); } const glm::vec3 & CMesh::GetBoundingSize() { return m_BoundingBox.m_BoundingSize; } const glm::vec3 & CMesh::GetBoundingMin() { return m_BoundingBox.m_BoundingBoxMin; } const glm::vec3 & CMesh::GetBoundingMax() { return m_BoundingBox.m_BoundingBoxMax; } const glm::vec3 & CMesh::GetBoundingCenter() { return m_BoundingBox.m_BoundingCenter; } const GLuint& CMesh::GetVertexCount() const { return m_VertexCount; }
true
4b6c87534cd4ae20534ccc0f6968422c022acafd
C++
Cholla-CAAR/cholla
/src/ppmp.cpp
UTF-8
16,995
2.578125
3
[ "MIT" ]
permissive
/*! \file ppmp.cpp * \brief Definitions of the PPM reconstruction functions, written following Fryxell et al., 2000 */ #ifndef CUDA #ifdef PPMP #include<stdlib.h> #include<stdio.h> #include<math.h> #include"ppmp.h" #include"global.h" #define STEEPENING #define FLATTENING /*! \fn void ppmp(Real stencil[], Real bounds[], Real dx, Real dt) * \brief When passed a stencil of conserved variables, returns the left and right boundary values for the interface calculated using ppm. */ void ppmp(Real stencil[], Real bounds[], Real dx, Real dt, Real gamma) { // retrieve the values from the stencil Real d_i = stencil[0]; Real vx_i = stencil[1] / d_i; Real vy_i = stencil[2] / d_i; Real vz_i = stencil[3] / d_i; Real p_i = (stencil[4] - 0.5*d_i*(vx_i*vx_i + vy_i*vy_i + vz_i*vz_i)) * (gamma-1.0); p_i = fmax(p_i, TINY_NUMBER); Real d_imo = stencil[5]; Real vx_imo = stencil[6] / d_imo; Real vy_imo = stencil[7] / d_imo; Real vz_imo = stencil[8] / d_imo; Real p_imo = (stencil[9] - 0.5*d_imo*(vx_imo*vx_imo + vy_imo*vy_imo + vz_imo*vz_imo)) * (gamma-1.0); p_imo = fmax(p_imo, TINY_NUMBER); Real d_ipo = stencil[10]; Real vx_ipo = stencil[11] / d_ipo; Real vy_ipo = stencil[12] / d_ipo; Real vz_ipo = stencil[13] / d_ipo; Real p_ipo = (stencil[14] - 0.5*d_ipo*(vx_ipo*vx_ipo + vy_ipo*vy_ipo + vz_ipo*vz_ipo)) * (gamma-1.0); p_ipo = fmax(p_ipo, TINY_NUMBER); Real d_imt = stencil[15]; Real vx_imt = stencil[16] / d_imt; Real vy_imt = stencil[17] / d_imt; Real vz_imt = stencil[18] / d_imt; Real p_imt = (stencil[19] - 0.5*d_imt*(vx_imt*vx_imt + vy_imt*vy_imt + vz_imt*vz_imt)) * (gamma-1.0); p_imt = fmax(p_imt, TINY_NUMBER); Real d_ipt = stencil[20]; Real vx_ipt = stencil[21] / d_ipt; Real vy_ipt = stencil[22] / d_ipt; Real vz_ipt = stencil[23] / d_ipt; Real p_ipt = (stencil[24] - 0.5*d_ipt*(vx_ipt*vx_ipt + vy_ipt*vy_ipt + vz_ipt*vz_ipt)) * (gamma-1.0); p_ipt = fmax(p_ipt, TINY_NUMBER); Real p_imth = (stencil[29] - 0.5*(stencil[26]*stencil[26] + stencil[27]*stencil[27] + stencil[28]*stencil[28])/stencil[25]) * (gamma-1.0); p_imth = fmax(p_imth, TINY_NUMBER); Real p_ipth = (stencil[34] - 0.5*(stencil[31]*stencil[31] + stencil[32]*stencil[32] + stencil[33]*stencil[33])/stencil[30]) * (gamma-1.0); p_ipth = fmax(p_ipth, TINY_NUMBER); Real dx_i, dx_imo, dx_ipo, dx_imt, dx_ipt; dx_i = dx_imo = dx_ipo = dx_imt = dx_ipt = dx; // declare the primative variables we are calculating // note: dl & dr refer to the left and right boundary values of cell i Real dl, dr, vxl, vxr, vyl, vyr, vzl, vzr, pl, pr; //define constants to use in contact discontinuity detection Real d2_rho_imo, d2_rho_ipo; //second derivative of rho Real eta_i; //steepening coefficient derived from a dimensionless quantity relating //the first and third derivatives of the density (Fryxell Eqns 36 & 40) Real delta_m_imo, delta_m_ipo; //monotonized slopes (Fryxell Eqn 26) //define constants to use in shock flattening Real F_imo, F_i, F_ipo; //flattening coefficients (Fryxell Eqn 48) // define other constants Real cs, cl, cr; // sound speed in cell i, and at left and right boundaries Real del_d, del_vx, del_vy, del_vz, del_p; // "slope" accross cell i Real d_6, vx_6, vy_6, vz_6, p_6; Real beta_m, beta_0, beta_p; Real alpha_m, alpha_0, alpha_p; Real lambda_m, lambda_0, lambda_p; // speed of characteristics Real dL_m, dL_0; Real vxL_m, vyL_0, vzL_0, vxL_p; Real pL_m, pL_0, pL_p; Real dR_0, dR_p; Real vxR_m, vyR_0, vzR_0, vxR_p; Real pR_m, pR_0, pR_p; Real chi_L_m, chi_L_0, chi_L_p; Real chi_R_m, chi_R_0, chi_R_p; // use ppm routines to set cell boundary values (see Fryxell Sec. 3.1.1) // left dl = interface_value(d_imt, d_imo, d_i, d_ipo, dx_imt, dx_imo, dx_i, dx_ipo); vxl = interface_value(vx_imt, vx_imo, vx_i, vx_ipo, dx_imt, dx_imo, dx_i, dx_ipo); vyl = interface_value(vy_imt, vy_imo, vy_i, vy_ipo, dx_imt, dx_imo, dx_i, dx_ipo); vzl = interface_value(vz_imt, vz_imo, vz_i, vz_ipo, dx_imt, dx_imo, dx_i, dx_ipo); pl = interface_value(p_imt, p_imo, p_i, p_ipo, dx_imt, dx_imo, dx_i, dx_ipo); // right dr = interface_value(d_imo, d_i, d_ipo, d_ipt, dx_imo, dx_i, dx_ipo, dx_ipt); vxr = interface_value(vx_imo, vx_i, vx_ipo, vx_ipt, dx_imo, dx_i, dx_ipo, dx_ipt); vyr = interface_value(vy_imo, vy_i, vy_ipo, vy_ipt, dx_imo, dx_i, dx_ipo, dx_ipt); vzr = interface_value(vz_imo, vz_i, vz_ipo, vz_ipt, dx_imo, dx_i, dx_ipo, dx_ipt); pr = interface_value(p_imo, p_i, p_ipo, p_ipt, dx_imo, dx_i, dx_ipo, dx_ipt); #ifdef STEEPENING //check for contact discontinuities & steepen if necessary (see Fryxell Sec 3.1.2) //if condition 4 (Fryxell Eqn 37) is true, check further conditions, otherwise do nothing if ((fabs(d_ipo - d_imo) / fmin(d_ipo, d_imo)) > 0.01) { //calculate the second derivative of the density in the imo and ipo cells d2_rho_imo = calc_d2_rho(d_imt, d_imo, d_i, dx, dx, dx); d2_rho_ipo = calc_d2_rho(d_i, d_ipo, d_ipt, dx, dx, dx); //if condition 1 (Fryxell Eqn 38) is true, check further conditions, otherwise do nothing if ((d2_rho_imo * d2_rho_ipo) < 0) { //calculate condition 5, pressure vs density jumps (Fryxell Eqn 39) //if c5 is true, set value of eta for discontinuity steepening if ((fabs(p_ipo - p_imo) / fmin(p_ipo, p_imo)) < 0.1 * gamma * (fabs(d_ipo - d_imo) / fmin(d_ipo, d_imo))) { //calculate first eta value (Fryxell Eqn 36) eta_i = calc_eta(d2_rho_imo, d2_rho_ipo, dx, dx, dx, d_imo, d_ipo); //calculate steepening coefficient (Fryxell Eqn 40) eta_i = fmax(0, fmin(20*(eta_i-0.05), 1) ); //calculate new left and right interface variables using monotonized slopes delta_m_imo = calc_delta_q(d_imt, d_imo, d_i, dx, dx, dx); delta_m_imo = limit_delta_q(delta_m_imo, d_imt, d_imo, d_i); delta_m_ipo = calc_delta_q(d_i, d_ipo, d_ipt, dx, dx, dx); delta_m_ipo = limit_delta_q(delta_m_ipo, d_i, d_ipo, d_ipt); //replace left and right interface values of density dl = dl*(1-eta_i) + (d_imo + 0.5 * delta_m_imo) * eta_i; dr = dr*(1-eta_i) + (d_ipo - 0.5 * delta_m_ipo) * eta_i; } } } #endif #ifdef FLATTENING //flatten shock fronts that are too narrow (see Fryxell Sec 3.1.3) //calculate the shock steepness parameters (Fryxell Eqn 43) //calculate the dimensionless flattening coefficients (Fryxell Eqn 45) F_imo = fmax( 0, fmin(1, 10*(((p_i - p_imt) / (p_ipo - p_imth))-0.75)) ); F_i = fmax( 0, fmin(1, 10*(((p_ipo - p_imo) / (p_ipt - p_imt))-0.75)) ); F_ipo = fmax( 0, fmin(1, 10*(((p_ipt - p_i) / (p_ipth - p_imo))-0.75)) ); //ensure that we are encountering a shock (Fryxell Eqns 46 & 47) if (fabs(p_i - p_imt) / fmin(p_i, p_imt) < 1./3.) {F_imo = 0;} if (fabs(p_ipo - p_imo) / fmin(p_ipo, p_imo) < 1./3.) {F_i = 0;} if (fabs(p_ipt - p_i) / fmin(p_ipt, p_i) < 1./3.) {F_ipo = 0;} if (vx_i - vx_imt > 0) {F_imo = 0;} if (vx_ipo - vx_imo > 0) {F_i = 0;} if (vx_ipt - vx_i > 0) {F_ipo = 0;} //set the flattening coefficient (Fryxell Eqn 48) if (p_ipo - p_imo < 0) {F_i = fmax(F_i, F_ipo);} else {F_i = fmax(F_i, F_imo);} //modify the interface values dl = F_i * d_i + (1 - F_i) * dl; vxl = F_i * vx_i + (1 - F_i) * vxl; vyl = F_i * vy_i + (1 - F_i) * vyl; vzl = F_i * vz_i + (1 - F_i) * vzl; pl = F_i * p_i + (1 - F_i) * pl; dr = F_i * d_i + (1 - F_i) * dr; vxr = F_i * vx_i + (1 - F_i) * vxr; vyr = F_i * vy_i + (1 - F_i) * vyr; vzr = F_i * vz_i + (1 - F_i) * vzr; pr = F_i * p_i + (1 - F_i) * pr; #endif //ensure that the parabolic distribution of each of the primative variables is monotonic //local maximum or minimum criterion (Fryxell Eqn 52, Fig 11) if ( (dr - d_i) * (d_i - dl) <= 0) { dl = dr = d_i; } if ( (vxr - vx_i) * (vx_i - vxl) <= 0) { vxl = vxr = vx_i; } if ( (vyr - vy_i) * (vy_i - vyl) <= 0) { vyl = vyr = vy_i; } if ( (vzr - vz_i) * (vz_i - vzl) <= 0) { vzl = vzr = vz_i; } if ( (pr - p_i) * (p_i - pl) <= 0) { pl = pr = p_i; } //steep gradient criterion (Fryxell Eqn 53, Fig 12) if ( (dr - dl) * (dl - (3*d_i - 2*dr)) < 0) { dl = 3*d_i - 2*dr; } if ( (vxr - vxl) * (vxl - (3*vx_i - 2*vxr)) < 0) { vxl = 3*vx_i - 2*vxr; } if ( (vyr - vyl) * (vyl - (3*vy_i - 2*vyr)) < 0) { vyl = 3*vy_i - 2*vyr; } if ( (vzr - vzl) * (vzl - (3*vz_i - 2*vzr)) < 0) { vzl = 3*vz_i - 2*vzr; } if ( (pr - pl) * (pl - (3*p_i - 2*pr)) < 0) { pl = 3*p_i - 2*pr; } if ( (dr - dl) * ((3*d_i - 2*dl) - dr) < 0) { dr = 3*d_i - 2*dl; } if ( (vxr - vxl) * ((3*vx_i - 2*vxl) - vxr) < 0) { vxr = 3*vx_i - 2*vxl; } if ( (vyr - vyl) * ((3*vy_i - 2*vyl) - vyr) < 0) { vyr = 3*vy_i - 2*vyl; } if ( (vzr - vzl) * ((3*vz_i - 2*vzl) - vzr) < 0) { vzr = 3*vz_i - 2*vzl; } if ( (pr - pl) * ((3*p_i - 2*pl) - pr) < 0) { pr = 3*p_i - 2*pl; } // compute sound speed in cell i cs = sqrt(gamma * p_i / d_i); // compute a first guess at the left and right states by taking the average // under the characteristic on each side that has the largest speed // compute deltas and 'sixes' (Fryxell Eqns 29 & 30) del_d = dr - dl; // Fryxell Eqn 29 del_vx = vxr - vxl; // Fryxell Eqn 29 del_vy = vyr - vyl; // Fryxell Eqn 29 del_vz = vzr - vzl; // Fryxell Eqn 29 del_p = pr - pl; // Fryxell Eqn 29 d_6 = 6.0 * (d_i - 0.5*(dl + dr)); // Fryxell Eqn 30 vx_6 = 6.0 * (vx_i - 0.5*(vxl + vxr)); // Fryxell Eqn 30 vy_6 = 6.0 * (vy_i - 0.5*(vyl + vyr)); // Fryxell Eqn 30 vz_6 = 6.0 * (vz_i - 0.5*(vzl + vzr)); // Fryxell Eqn 30 p_6 = 6.0 * (p_i - 0.5*(pl + pr)); // Fryxell Eqn 30 // set speed of characteristics (v-c, v, v+c) using average values of v and c lambda_m = vx_i - cs; lambda_0 = vx_i; lambda_p = vx_i + cs; // calculate betas (for right interface guesses) beta_m = fmax( (lambda_m * dt / dx_i) , 0 ); // Fryxell Eqn 59 beta_0 = fmax( (lambda_0 * dt / dx_i) , 0 ); // Fryxell Eqn 59 beta_p = fmax( (lambda_p * dt / dx_i) , 0 ); // Fryxell Eqn 59 // calculate alphas (for left interface guesses) alpha_m = fmax( (-lambda_m * dt / dx_i), 0); // Fryxell Eqn 61 alpha_0 = fmax( (-lambda_0 * dt / dx_i), 0); // Fryxell Eqn 61 alpha_p = fmax( (-lambda_p * dt / dx_i), 0); // Fryxell Eqn 61 // average values under characteristics for left interface (Fryxell Eqn 60) dL_m = dl + 0.5 * alpha_m * (del_d + d_6 * (1 - (2./3.) * alpha_m)); vxL_m = vxl + 0.5 * alpha_m * (del_vx + vx_6 * (1 - (2./3.) * alpha_m)); pL_m = pl + 0.5 * alpha_m * (del_p + p_6 * (1 - (2./3.) * alpha_m)); dL_0 = dl + 0.5 * alpha_0 * (del_d + d_6 * (1 - (2./3.) * alpha_0)); vyL_0 = vyl + 0.5 * alpha_0 * (del_vy + vy_6 * (1 - (2./3.) * alpha_0)); vzL_0 = vzl + 0.5 * alpha_0 * (del_vz + vz_6 * (1 - (2./3.) * alpha_0)); pL_0 = pl + 0.5 * alpha_0 * (del_p + p_6 * (1 - (2./3.) * alpha_0)); vxL_p = vxl + 0.5 * alpha_p * (del_vx + vx_6 * (1 - (2./3.) * alpha_p)); pL_p = pl + 0.5 * alpha_p * (del_p + p_6 * (1 - (2./3.) * alpha_p)); // average values under characteristics for right interface (Fryxell Eqn 58) vxR_m = vxr - 0.5 * beta_m * (del_vx - vx_6 * (1 - (2./3.) * beta_m)); pR_m = pr - 0.5 * beta_m * (del_p - p_6 * (1 - (2./3.) * beta_m)); dR_0 = dr - 0.5 * beta_0 * (del_d - d_6 * (1 - (2./3.) * beta_0)); vyR_0 = vyr - 0.5 * beta_0 * (del_vy - vy_6 * (1 - (2./3.) * beta_0)); vzR_0 = vzr - 0.5 * beta_0 * (del_vz - vz_6 * (1 - (2./3.) * beta_0)); pR_0 = pr - 0.5 * beta_0 * (del_p - p_6 * (1 - (2./3.) * beta_0)); dR_p = dr - 0.5 * beta_p * (del_d - d_6 * (1 - (2./3.) * beta_p)); vxR_p = vxr - 0.5 * beta_p * (del_vx - vx_6 * (1 - (2./3.) * beta_p)); pR_p = pr - 0.5 * beta_p * (del_p - p_6 * (1 - (2./3.) * beta_p)); // as a first guess, use characteristics with the largest speeds // for transverse velocities, use the 0 characteristic // left dl = dL_m; vxl = vxL_m; vyl = vyL_0; vzl = vzL_0; pl = pL_m; // right dr = dR_p; vxr = vxR_p; vyr = vyR_0; vzr = vzR_0; pr = pR_p; // correct these initial guesses by taking into account the number of // characteristics on each side of the interface // calculate the 'guess' sound speeds cl = sqrt(gamma * pl / dl); cr = sqrt(gamma * pr / dr); // calculate the chi values (Fryxell Eqns 62 & 63) chi_L_m = 1./(2*dl*cl) * (vxl - vxL_m - (pl - pL_m)/(dl*cl)); chi_L_p = -1./(2*dl*cl) * (vxl - vxL_p + (pl - pL_p)/(dl*cl)); chi_L_0 = (pl - pL_0)/(dl*dl*cl*cl) + 1./dl - 1./dL_0; chi_R_m = 1./(2*dr*cr) * (vxr - vxR_m - (pr - pR_m)/(dr*cr)); chi_R_p = -1./(2*dr*cr) * (vxr - vxR_p + (pr - pR_p)/(dr*cr)); chi_R_0 = (pr - pR_0)/(dr*dr*cr*cr) + 1./dr - 1./dR_0; // set chi to 0 if characteristic velocity has the wrong sign (Fryxell Eqn 64) if (lambda_m >= 0) { chi_L_m = 0; } if (lambda_0 >= 0) { chi_L_0 = 0; } if (lambda_p >= 0) { chi_L_p = 0; } if (lambda_m <= 0) { chi_R_m = 0; } if (lambda_0 <= 0) { chi_R_0 = 0; } if (lambda_p <= 0) { chi_R_p = 0; } // use the chi values to correct the initial guesses and calculate final input states pl = pl + (dl*dl * cl*cl) * (chi_L_p + chi_L_m); vxl = vxl + dl * cl * (chi_L_p - chi_L_m); dl = pow( ((1.0/dl) - (chi_L_m + chi_L_0 + chi_L_p)) , -1); pr = pr + (dr*dr * cr*cr) * (chi_R_p + chi_R_m); vxr = vxr + dr * cr * (chi_R_p - chi_R_m); dr = pow( ((1.0/dr) - (chi_R_m + chi_R_0 + chi_R_p)) , -1); // send final values back (conserved variables) bounds[0] = dl; bounds[1] = dl*vxl; bounds[2] = dl*vyl; bounds[3] = dl*vzl; bounds[4] = (pl/(gamma-1.0)) + 0.5*dl*(vxl*vxl + vyl*vyl + vzl*vzl); bounds[5] = dr; bounds[6] = dr*vxr; bounds[7] = dr*vyr; bounds[8] = dr*vzr; bounds[9] = (pr/(gamma-1.0)) + 0.5*dr*(vxr*vxr + vyr*vyr + vzr*vzr); } /*! \fn interface_value * \brief Returns the interpolated value at the right hand interface of cell i.*/ Real interface_value(Real q_imo, Real q_i, Real q_ipo, Real q_ipt, Real dx_imo, Real dx_i, Real dx_ipo, Real dx_ipt) { Real Z_1; Real Z_2; Real X; Real dq_i; Real dq_ipo; Real q_R; Z_1 = (dx_imo + dx_i) / (2*dx_i + dx_ipo); Z_2 = (dx_ipt + dx_ipo) / (2*dx_ipo + dx_i); X = dx_imo + dx_i + dx_ipo + dx_ipt; dq_i = calc_delta_q(q_imo, q_i, q_ipo, dx_imo, dx_i, dx_ipo); dq_ipo = calc_delta_q(q_i, q_ipo, q_ipt, dx_i, dx_ipo, dx_ipt); dq_i = limit_delta_q(dq_i, q_imo, q_i, q_ipo); dq_ipo = limit_delta_q(dq_ipo, q_i, q_ipo, q_ipt); q_R = q_i + (dx_i / (dx_i + dx_ipo))*(q_ipo - q_i) + (1 / X)*( ((2*dx_ipo*dx_i)/(dx_ipo+dx_i)) * (Z_1 - Z_2) * (q_ipo - q_i) - dx_i*Z_1*dq_ipo + dx_ipo*Z_2*dq_i ); return q_R; } /*! \fn calc_delta_q * \brief Returns the average slope in zone i of the parabola with zone averages of imo, i, and ipo. See Fryxell Eqn 24. */ Real calc_delta_q(Real q_imo, Real q_i, Real q_ipo, Real dx_imo, Real dx_i, Real dx_ipo) { Real A; Real B; Real C; Real D; Real E; A = dx_i / (dx_imo + dx_i + dx_ipo); B = (2*dx_imo + dx_i) / (dx_ipo + dx_i); C = q_ipo - q_i; D = (dx_i + 2*dx_ipo) / (dx_imo + dx_i); E = q_i - q_imo; return A * (B*C + D*E); } /*! \fn limit_delta_q * \brief Limits the value of delta_rho according to Fryxell Eqn 26 to ensure monotonic interface values. */ Real limit_delta_q(Real del_in, Real q_imo, Real q_i, Real q_ipo) { Real dq; if ( (q_ipo-q_i)*(q_i-q_imo) > 0) { dq = fmin(2.0*fabs(q_i-q_imo), 2.0*fabs(q_i - q_ipo)); dq = fmin(dq, fabs(del_in)); return sgn(del_in)*dq; } else return 0; } /*! \fn test_interface_value * \brief Returns the right hand interpolated value at imo | i cell interface, assuming equal cell widths. */ Real test_interface_value(Real q_imo, Real q_i, Real q_ipo, Real q_ipt) { return (1./12.)*(-q_ipt + 7*q_ipo + 7*q_i - q_imo); } /*! \fn calc_d2_rho * \brief Returns the second derivative of rho across zone i. (Fryxell Eqn 35) */ Real calc_d2_rho(Real rho_imo, Real rho_i, Real rho_ipo, Real dx_imo, Real dx_i, Real dx_ipo) { Real A; Real B; Real C; A = 1 / (dx_imo + dx_i + dx_ipo); B = (rho_ipo - rho_i) / (dx_ipo + dx_i); C = (rho_i - rho_imo) / (dx_i + dx_imo); return A*(B - C); } /*! \fn calc_eta * \brief Returns a dimensionless quantity relating the 1st and 3rd derivatives See Fryxell Eqn 36. */ Real calc_eta(Real d2rho_imo, Real d2rho_ipo, Real dx_imo, Real dx_i, Real dx_ipo, Real rho_imo, Real rho_ipo) { Real x_imo = 0.5*dx_imo; Real x_i = x_imo + 0.5*dx_imo + 0.5*dx_i; Real x_ipo = x_i + 0.5*dx_i + 0.5*dx_ipo; Real A; Real B; A = (d2rho_ipo - d2rho_imo) / (x_ipo - x_imo); B = (pow((x_i - x_imo),3) + pow((x_ipo - x_i),3)) / (rho_ipo - rho_imo); return -A * B; } #endif //PPMP #endif //CUDA
true
4034a66835ec66390d4d5f74bdf442758870e2d7
C++
saga92/leetcode
/letter_combinations_of_phone_number.cpp
UTF-8
1,119
3.4375
3
[]
no_license
#include<string> #include<vector> #include<unordered_map> using namespace std; class Solution { public: vector<string> letterCombinations(string digits) { vector<string> res; unordered_map<int,string> map={{2,"abc"},{3,"def"},{4,"ghi"},{5,"jkl"},{6,"mno"},{7,"pqrs"},{8,"tuv"},{9,"wxyz"}}; letterCombinationsRecursive(res,map,"",digits); return res; } void letterCombinationsRecursive(vector<string>& res, unordered_map<int,string> map, string s, string digits){ if(digits.size()==0){ if(!s.empty()) res.push_back(s); return; } int idx=digits.at(0)-'0'; for(int i=0;i<map[idx].size();i++){ s+=map[idx].at(i); if(digits.size()!=1){ letterCombinationsRecursive(res,map,s,digits.substr(1,digits.size()-1)); }else{ letterCombinationsRecursive(res,map,s,""); } s=s.substr(0,s.size()-1); } } }; int main(){ Solution solution; vector<string> res=solution.letterCombinations("2"); return 0; }
true
48a2dd3bee68f33508697341fc83318704f4093c
C++
TabithaRoemish/CSS343_Assignment4.cpp
/store.cpp
UTF-8
4,524
3.046875
3
[]
no_license
// File Name: store.cpp // Programmer: Tabitha Roemish & Prathyusha Pillari // Date: March 2, 2018 // File contains: store class definitions // The Store class also contains a HashTable for all the Store’s Customers. // Manager for all of the Store’s database which includes all // the Movies sorted by their types, as well as all the Customers // of the Store. // It is assumed that all input is correctly formatted according to the // homework specification file. #include "store.h" #include <fstream> #include <iostream> #include <sstream> #include "binarysearchtree.h" #include "movie.h" #include "comedy.h" #include "classic.h" #include "drama.h" //initialize static variables in store std::set<std::string> Store::commandCodes = { "B", "R", "I", "H" }; std::set<std::string> Store::mediaCodes = { "D" }; std::set<std::string> Store::movieCodes = { "C", "D", "F" }; std::queue<Command*> Store::commandPtrs; HashMap Store::customerList; std::map< std::string, std::map<std::string, BinarySearchTree<Movie*>>> Store::collection; //store destructor Store::~Store() { // hashmap customerList releases space made for hash elements // and Customers // BST releses Movie space // release commands while (!commandPtrs.empty()) { delete commandPtrs.front(); commandPtrs.pop(); } } // reads DVDs specifically because it adds all files to collection["D"] // reads input string and sends it to movie create function void Store::readDVDMovies(std::string filename) { /*F, 10, Nora Ephron, You've Got Mail, 1998 D, 10, Steven Spielberg, Schindler's List, 1993 C, 10, George Cukor, Holiday, Katherine Hepburn 9 1938 C, 10, George Cukor, Holiday, Cary Grant 9 1938 Z, 10, Hal Ashby, Harold and Maude, Ruth Gordon 2 1971 D, 10, Phillippe De Broca, King of Hearts, 1967*/ std::ifstream toRead(filename); std::string input = ""; if (toRead.is_open()) { while (std::getline(toRead, input)) { // calls the Movie class's create to // create the correct movie obbject and // stores it into a pointer Movie * mvPtr = Movie::create(input); if (mvPtr != nullptr) { // add's the movie obbject to the // appropriate BST std::string code = input.substr(0, 1); collection["D"][code].add(mvPtr); } input = ""; } } else std::cerr << "Could not open file: " << filename; toRead.close(); } // reads customers from file, adds customers to hashtable void Store::readCustomers(std::string filename) { //1111 Mouse Mickey //1000 Mouse Minnie std::ifstream toRead(filename); std::string input; std::stringstream ss; int custId = 0; std::string custName = ""; if (toRead.is_open()) { while (std::getline(toRead, input)) { // gets the custormer ID ss << input; ss >> custId; ss.get(); // get space before name std::getline(ss,custName); //check if customer is in list, if not (nullptr returned) // then add if (customerList.search(custId) == nullptr) { Customer * cust = nullptr; cust = new Customer(custId, custName); customerList.insert(custId, cust); input = ""; custId = 0; custName = ""; ss.clear(); } // else continue without comment } } else std::cerr << "Could not open file: " << filename; toRead.close(); } // reads input string and sends it to command.create to make specific commands void Store::readCommands(std::string filename) { std::ifstream toRead(filename); std::string input; if (toRead.is_open()) { while (std::getline(toRead, input)) { Command * cmd = Command::create(input); if(cmd != nullptr) commandPtrs.push(cmd); } input = ""; } else std::cerr << "Could not open file: " << filename; toRead.close(); } //iterates through collection //prints string value for mediaType, then string value for Genre type //then prints contents of BST //ex // D: // C: // Title Year // Title Year void Store::printInventory() { std::cout << "Inventory: " << std::endl; for (std::map<std::string, std::map<std::string, BinarySearchTree<Movie*>>> ::iterator mediaTypeIt = collection.begin(); mediaTypeIt != collection.end(); mediaTypeIt++) { // prints the string vlaue for media type std::cout << mediaTypeIt->first << ": " << endl; for (auto genreIt = mediaTypeIt->second.begin(); genreIt != mediaTypeIt->second.end(); genreIt++) { // prints the genre type std::cout << " " << genreIt->first << ": " << endl; genreIt->second.print(); // prints the contents of BST's } } std::cout << endl; }
true
37e727546d9c80d3e82218108ebbbca30cd9bc9b
C++
rathyon/pbr
/src/Lights/Light.cpp
UTF-8
837
2.59375
3
[]
no_license
#include <Light.h> using namespace pbr; Light::Light() : SceneObject(), _on(true), _intensity(1.0f), _emission(1.0f) { } Light::Light(const Color& emission, float intensity) : SceneObject(), _emission(emission), _intensity(intensity) { } Light::Light(const Vec3& position, const Color& emission, float intensity) : SceneObject(position), _emission(emission), _intensity(intensity) { } Light::Light(const Mat4& lightToWorld, const Color& emission, float intensity) : SceneObject(lightToWorld), _emission(emission), _intensity(intensity) { } bool Light::isOn() const { return _on; } bool Light::castShadows() const { return _shadows; } float Light::intensity() const { return _intensity; } Color Light::emission() const { return _emission; } sref<Shape> Light::shape() const { return nullptr; }
true
deb00e47e9009426951148834c9289cdddc5881c
C++
delefme/jutge-informatica
/08. Consolidation I/P11916-Approximation_of_e.cc
UTF-8
681
3.328125
3
[]
no_license
#include <iostream> using namespace std; int factorial(double n) { int i = 0; int j = 1; while (i < n) { i = i+1; j = j*i; } return j; } int main() { cout.setf(ios::fixed); cout.precision(10); double n; while (cin >> n) { double suma = 0.000000000; double fact = factorial(n-1); double prod = 1.0000000000; for (double i = 1.0000000000; i <= n - 1; i++) { prod *= i; suma += fact/prod; } double e = 1.00000000000 + double(suma)/double(fact); if (n == 0) e = 0; cout << "With " << (int)n << " term(s) we get " << e << "." << endl; } }
true
6f47c885c751488fc3772659fd96c91f0be5d47d
C++
rithikb2/PolyRoute
/routes_analysis.cpp
UTF-8
1,626
3.015625
3
[]
no_license
#include <iostream> #include <string> #include <fstream> #include <sstream> using namespace std; int main() { ifstream in("/home/adammn2/final_project/routes.dat.txt"); string line; int count = 0; while(getline(in, line) && count < 4) { stringstream linestream(line); string airline, airline_id, source_airport, source_airport_id, dest_airport, dest_airport_id, codeshare, stops, equipment; getline(linestream, airline, ','); getline(linestream, airline_id, ','); getline(linestream, source_airport, ','); getline(linestream, source_airport_id, ','); getline(linestream, dest_airport, ','); getline(linestream, dest_airport_id, ','); getline(linestream, codeshare, ','); getline(linestream, stops, ','); getline(linestream, equipment, ','); /* if (codeshare.empty()) { cout << "Codeshare is NULL" << endl; } else { cout << "Codeshare : " << codeshare << endl; } */ //Print routes with more than 0 stops /* stringstream convert_int(stops); int stops_int = 0; convert_int >> stops_int; if (stops_int != 0) { cout << "Source Airport: " << source_airport << endl << "Destination Airport: " << dest_airport << endl << "Stops: " << stops << endl; count++; } */ //Prints basic info cout << "Source Airport: " << source_airport << endl << "Destination Airport: " << dest_airport << endl << "Stops: " << stops << endl; count++; } }
true
8c685171367580df95196eee2d8416337ff0f7bf
C++
jetp250/JRSC-Compiler
/src/parsing/Parser.cpp
UTF-8
42,543
2.828125
3
[]
no_license
#include "Parser.hpp" #include "misc/Logging.hpp" #include <algorithm> using namespace Lexer; // Brings in LexResult, TokenType, TokenData using namespace Parser; static bool strequals(const char* a, const char* b) noexcept { while(*a && *b) { if (*a != *b) return false; a++; b++; } return true; } static int scope = 0; static char _scope_buf[128]{}; template<typename ... Args> static void log(std::string_view format, Args&&... args) { std::memset(_scope_buf, ' ', 4 * scope); _scope_buf[4 * scope] = 0; printf(_scope_buf); fmt::print(format, std::forward<Args>(args)...); fflush(stdout); } template<typename ... Args> static void start_scope(std::string_view format, Args&&... args) { log(format, std::forward<Args>(args)...); scope += 1; } template<typename ... Args> static void end_scope(std::string_view format, Args&&... args) { scope -= 1; log(format, std::forward<Args>(args)...); } static std::string to_string(Parser::BinaryOp op) { switch(op) { case BinaryOp::ADD: return "+"; case BinaryOp::SUB: return "-"; case BinaryOp::MUL: return "*"; case BinaryOp::DIV: return "/"; case BinaryOp::MOD: return "%"; case BinaryOp::AND: return "&&"; case BinaryOp::OR: return "||"; case BinaryOp::RSHIFT: return ">>"; case BinaryOp::LSHIFT: return "<<"; case BinaryOp::BIT_AND: return "&"; case BinaryOp::BIT_OR: return "|"; case BinaryOp::BIT_XOR: return "^"; case BinaryOp::LTHAN: return "<"; case BinaryOp::LEQUAL_TO: return "<="; case BinaryOp::EQUAL_TO: return "=="; case BinaryOp::NEQUAL_TO: return "!="; case BinaryOp::GEQUAL_TO: return ">="; case BinaryOp::GTHAN: return ">"; } return "<invalid op>"; } static std::string to_string(const Parser::Expression& expression) { fflush(stdout); switch(expression.type) { case Expression::Type::EMPTY: return "()"; case Expression::Type::LITERAL: switch(expression.literal.type) { case Literal::Type::STRING: return "\"" + std::string(expression.literal.string_literal) + "\""; case Literal::Type::CHAR: return "'" + std::string(1, expression.literal.char_literal) + "'"; case Literal::Type::UINT: return std::to_string(expression.literal.uint_literal) + "u"; case Literal::Type::INT: return std::to_string(expression.literal.int_literal); case Literal::Type::FLOAT: return std::to_string(expression.literal.float_literal) + "f"; } return "<invalid literal>"; case Expression::Type::VAR_REF: return std::string(expression.var_ref.str_view()); case Expression::Type::MEMBER_VAR_REF: return to_string(*expression.member_var_ref.variable) + "->" + std::string(expression.member_var_ref.member_name.str_view()); case Expression::Type::FUNC_CALL: { std::string fcres = std::string(expression.func_call.fn_name.str_view()); fcres += "("; for (size_t i = 0; i < expression.func_call.num_params; ++i) { fcres += to_string(expression.func_call.array_of_params[i]); if (i != expression.func_call.num_params - 1) fcres += ", "; } fcres += ")"; return fcres; } case Expression::Type::MEMBER_FUNC_CALL: { std::string mfcres = to_string(*expression.member_func_call.variable) + "->"; mfcres += std::string(expression.member_func_call.fn_name.str_view()); mfcres += "("; for (size_t i = 0; i < expression.member_func_call.num_params; ++i) { mfcres += to_string(expression.member_func_call.array_of_params[i]); if (i != expression.member_func_call.num_params - 1) mfcres += ", "; } mfcres += ")"; return mfcres; } case Expression::Type::BINARY_OP: { std::string bopres; if (expression.binary_op.lhs->type == Expression::Type::BINARY_OP) { bopres += "(" + to_string(*expression.binary_op.lhs) + ")"; } else bopres += to_string(*expression.binary_op.lhs); bopres += " "; bopres += to_string(expression.binary_op.op); bopres += " "; if (expression.binary_op.rhs->type == Expression::Type::BINARY_OP) { bopres += "(" + to_string(*expression.binary_op.rhs) + ")"; } else bopres += to_string(*expression.binary_op.rhs); return bopres; } case Expression::Type::UNARY_OP: { UnaryOp op = expression.unary_op.op; return (op == UnaryOp::NOT ? "!" : op == UnaryOp::NEGATE ? "-" : "~") + to_string(*expression.unary_op.value); } } return "<invalid expression>"; } static std::string to_string(const Parser::CodeBlock& code); static std::string to_string(const Parser::Statement& stmt) { switch(stmt.type) { case Statement::Type::IF_STATEMENT: { std::string ires = "if "; ires += to_string(*stmt.if_statement.condition); ires += " "; if (stmt.if_statement.code->type != Statement::Type::CODE_BLOCK) ires += "{ "; ires += to_string(*stmt.if_statement.code); if (stmt.if_statement.code->type != Statement::Type::CODE_BLOCK) ires += " }"; if (stmt.if_statement.else_statement_code != nullptr) { ires += " else "; if (stmt.if_statement.else_statement_code->type != Statement::Type::CODE_BLOCK) ires += "{ "; ires += to_string(*stmt.if_statement.else_statement_code); if (stmt.if_statement.else_statement_code->type != Statement::Type::CODE_BLOCK) ires += " }"; } return ires; } case Statement::Type::VAR_DECL: { std::string vdres = "let "; vdres += stmt.var_decl.name.str_view(); if (!stmt.var_decl.value) return vdres + ";"; vdres += " = "; vdres += to_string(*stmt.var_decl.value); vdres += ";"; return vdres; } case Statement::Type::ASSIGNMENT: { std::string ares = to_string(*stmt.assignment.variable); ares += " = "; ares += to_string(*stmt.assignment.value); ares += ";"; return ares; } case Statement::Type::FUNC_CALL: return to_string(*stmt.func_call) + ";"; case Statement::Type::RETURN: { std::string retres = "return"; if (stmt.return_statement != nullptr) retres += " " + to_string(*stmt.return_statement); return retres + ";"; } case Statement::Type::LOOP: { return "loop " + to_string(stmt.loop); } case Statement::Type::CODE_BLOCK: return to_string(stmt.code_block); } return "<invalid statement>"; } static std::string to_string(const Parser::CodeBlock& code) { std::string result; result += "{\n"; for (size_t i = 0; i < code.num_statements; ++i) { Statement& stmt = code.statements[i]; result += " "; result += to_string(stmt); result += "\n"; } result += "}\n"; return result; } static std::string to_string(const Parser::FuncDecl& fn) { std::string result = "fn " + std::string(fn.name.str_view()) + "("; for (size_t i = 0; i < fn.params.size(); ++i) { result += fn.params[i].name.str_view(); result += ": "; result += fn.params[i].type_name.str_view(); if (i != fn.params.size()-1) result += ", "; } result += ") "; if (fn.return_type_name.length != 0) { result += "-> "; result += fn.return_type_name.str_view(); result += " "; } result += to_string(fn.code_block); return result; } static int get_precedence(BinaryOp op) noexcept { switch(op) { case BinaryOp::MUL: case BinaryOp::DIV: case BinaryOp::MOD: return 9; case BinaryOp::ADD: case BinaryOp::SUB: return 8; case BinaryOp::RSHIFT: case BinaryOp::LSHIFT: return 7; case BinaryOp::LTHAN: case BinaryOp::LEQUAL_TO: case BinaryOp::GEQUAL_TO: case BinaryOp::GTHAN: return 6; case BinaryOp::EQUAL_TO: case BinaryOp::NEQUAL_TO: return 5; case BinaryOp::BIT_AND: return 4; case BinaryOp::BIT_XOR: return 3; case BinaryOp::BIT_OR: return 2; case BinaryOp::AND: return 1; case BinaryOp::OR: return 0; } ice_abort(1, "get_precedence(BinaryOp): invalid operator"); } // Represents one active parsing process (for a single file). // Multiple may be running in parallel. // A parser simply takes in a token stream and // converts it to an AST. AST->IR conversion // is done elsewhere. class ParserUnit final { public: ParserUnit(const SourceFile& src, LexResult& lex) noexcept : index(0), num_tokens(lex.token_types.size()), tokens(lex.token_types.data()), datas(lex.token_datas.data()), source_refs(lex.source_refs.data()), src(src), current_function_name(Identifier{}) { expressions.reserve(num_tokens); // a single token is enough for an expression: `1` statements.reserve(num_tokens / 3) ;// 3 is the minimum number of tokens needed for a statement: `x = 5` } std::optional<AST> parse() { //fmt::print("sizeof(Expression) = {}. sizeof(Statement) = {}\n", sizeof(Parser::Expression), sizeof(Parser::Statement)); start_scope("parse_imports start\n"); parse_imports(); // Kicks off lexing & parsing of found imports in parallel end_scope("parse_imports end\n"); log("Next token: {}\n", TokenTypes::stringify(peek_token())); while(true) { if (consume_identifier("fn")) { parse_function(); } else if (consume_identifier("struct")) { parse_struct(); } else { break; } } if (!issues.empty()) { log_issues(issues, src); return {}; } AST ast; ast.storage.expressions = std::move(expressions); ast.storage.statements = std::move(statements); ast.functions = std::move(functions); ast.structs = std::move(structs); printf("Done parsing\n"); return ast; } private: void parse_function() noexcept { start_scope("Parsing function\n"); FuncDecl fn; expect_identifier(fn.name); log("Expecting ("); expect(TokenType::PAREN_OPEN); log("Found )"); // Even if the user forgets the whole parameter pack and the return value (which isn't always there though) // (e.g. 'fn func { println("hi"); }') // try to recover by looking for next expected tokens start_scope("Parsing parameters\n"); while (!consume_token(TokenType::PAREN_CLOSE) && !consume_token(TokenType::RIGHT_ARROW) && !consume_token(TokenType::BRACE_OPEN)) { start_scope("Parsing parameter\n"); Identifier param_name{}; expect_identifier(param_name); expect(TokenType::COLON); Identifier type_name{}; expect_identifier(type_name); fn.params.push_back(FuncDecl::Param{param_name, type_name}); consume_token(TokenType::COMMA); end_scope("Done parsing parameter\n"); } end_scope("Done parsing parameters\n"); if (consume_token(TokenType::RIGHT_ARROW)) { // Optional expect_identifier(fn.return_type_name); } fn.code_block = parse_code_block(); functions.insert({ fn.name, fn }); log("Function parsed\n"); fflush(stdout); current_function_name = Identifier{}; end_scope("Done parsing function: \n\n{}\n", to_string(fn)); } CodeBlock parse_code_block() noexcept { start_scope("Parsing code block\n"); std::vector<Statement> statements; statements.reserve(8); // Totally arbitrary. Should be over the 256 byte allocation threshold though expect(TokenType::BRACE_OPEN); while(!consume_token(TokenType::BRACE_CLOSE)) { statements.push_back(parse_statement()); } CodeBlock code_block{}; code_block.statements = &(this->statements.back()) + 1; code_block.num_statements = statements.size(); for (Statement& statement : statements) { push_statement(statement); } end_scope("Done parsing code block\n"); return code_block; } Statement parse_statement() noexcept { start_scope("Parsing statement. Next token: {}\n", TokenTypes::stringify(peek_token())); Statement statement{}; if (peek_token() == TokenType::BRACE_OPEN) { statement.type = Statement::Type::CODE_BLOCK; statement.code_block = parse_code_block(); } if (consume_identifier("let")) { statement.type = Statement::Type::VAR_DECL; statement.var_decl = parse_var_decl(); } else if (consume_identifier("if")) { statement.type = Statement::Type::IF_STATEMENT; statement.if_statement.condition = push_expression(parse_expression()); statement.if_statement.code = push_statement(parse_statement()); statement.if_statement.else_statement_code = nullptr; if (consume_identifier("else")) { statement.if_statement.else_statement_code = push_statement(parse_statement()); } } else if (consume_identifier("loop")) { statement.type = Statement::Type::LOOP; statement.loop = parse_code_block(); } else if (consume_identifier("return")) { statement.type = Statement::Type::RETURN; statement.return_statement = nullptr; if (!consume_token(TokenType::SEMICOLON)) { statement.return_statement = push_expression(parse_expression()); expect(TokenType::SEMICOLON); } } else { // If nothing else matches, try an expression. // Could be `x = ..`, `foo->bar = baz`, `foo(bar, baz)`, ... Expression left = parse_expression(); // 'left' as in left hand side if (left.type == Expression::Type::VAR_REF || left.type == Expression::Type::MEMBER_VAR_REF) { statement.type = Statement::Type::ASSIGNMENT; statement.assignment.variable = push_expression(left); if (consume_token(TokenType::ASSIGN)) { statement.assignment.value = push_expression(parse_expression()); } else if (BinaryOp op; consume_any_assignment_bin_op(op)) { // Convert `x += 5` to `x = x + 5` Expression rhs{}; rhs.type = Expression::Type::BINARY_OP; rhs.binary_op.lhs = statement.assignment.variable; rhs.binary_op.rhs = push_expression(parse_expression()); rhs.binary_op.op = op; statement.assignment.value = push_expression(rhs); } } else if (left.type == Expression::Type::FUNC_CALL || left.type == Expression::Type::MEMBER_FUNC_CALL) { statement.type = Statement::Type::FUNC_CALL; statement.func_call = push_expression(left); } expect(TokenType::SEMICOLON); } end_scope("Done parsing statement: '{}'\n", to_string(statement)); return statement; } // Variable declarations are statements starting with "let". VarDecl parse_var_decl() noexcept { start_scope("Parsing variable declaration\n"); VarDecl var_decl{}; expect_identifier(var_decl.name); log("Variable name: {}\n", var_decl.name.str_view()); if (consume_token(TokenType::SEMICOLON)) { var_decl.value = nullptr; end_scope("Done parsing variable declaration (empty)\n"); return var_decl; } expect(TokenType::ASSIGN); var_decl.value = push_expression(parse_expression()); expect(TokenType::SEMICOLON); Statement temp = {}; temp.type = Statement::Type::VAR_DECL; temp.var_decl = var_decl; end_scope("Done parsing variable declaration: '{}'\n", to_string(temp)); return var_decl; } // Parses and performs constant folding where trivial Expression parse_expression() noexcept { start_scope("Parsing expression\n"); Expression lhs = {}; lhs.type = Expression::Type::EMPTY; // Expression can start with a literal: `1 + 2`.. if (consume_token(TokenType::LITERAL)) { log("Parsed literal. Next token: '{}'\n", TokenTypes::stringify(peek_token())); // Strings are literals too, but no need to make a distinction lhs.type = Expression::Type::LITERAL; lhs.literal = get_literal(); } // .. or an identifier: `x + 5`, `func()`.. else if (consume_token(TokenType::IDENTIFIER)) { Identifier identifier = get_identifier(); if (consume_token(TokenType::PAREN_OPEN)) { // Function call lhs.type = Expression::Type::FUNC_CALL; lhs.func_call.fn_name = identifier; // The expressions vector is always bigger than the maximum number of expressions, // so pushing will never allocate and thereby never invalidate pointers lhs.func_call.num_params = 0; if(!consume_token(TokenType::PAREN_CLOSE)) { int param_count = recursive_parse_func_params(); auto start = expressions.end() - param_count; auto end = expressions.end(); std::reverse(start, end); lhs.func_call.num_params = param_count; lhs.func_call.array_of_params = start.base(); expect(TokenType::PAREN_CLOSE); } } else { lhs.type = Expression::Type::VAR_REF; lhs.var_ref = identifier; } } // .. or an open paren, aka sub-expression: `(x-3)`.. else if (consume_token(TokenType::PAREN_OPEN)) { lhs = parse_expression(); expect(TokenType::PAREN_CLOSE); } // .. or an unary operator: `-x`, `~x` else if (UnaryOp op; consume_any_unary_op(op)) { lhs.type = Expression::Type::UNARY_OP; lhs.unary_op.op = op; lhs.unary_op.value = push_expression(parse_expression()); } else { // Syntax error error("Unexpected token. Expected one of: -, ~, (, literal or identifier"); // Unless the token is a semicolon... if (consume_token(TokenType::SEMICOLON)) { // if this wasn't a non-recursive call to parse_expression(), // this is an ICE (because the semicolon should've been detected). // Either way, the returned expression shouldn't be needed, // because compilation will abort as errors were found end_scope("Done parsing expression, error: '{}'\n", to_string(lhs)); return lhs; } // Attempt recovery by starting over from the next token skip_token(); end_scope("Done parsing expression, recovering from error by starting over\n"); Expression expr = parse_expression(); return expr; } // Quick exit if ) is found. Not strictly necessary if (peek_token() == TokenType::PAREN_CLOSE) { end_scope("Done parsing expression (')' found): '{}'\n", to_string(lhs)); return lhs; } log("First half of expression parsing done, found '{}'\n", to_string(lhs)); // See if there's an operator used on the left hand side expression if (consume_token(TokenType::RIGHT_ARROW)) { // explicitly disallow `(` here because otherwise // syntax like `foo->(bar)` would work if (consume_token(TokenType::PAREN_OPEN)) { error("Unexpected token. Expected variable name or function call after ->"); Expression exp = parse_expression(); // Try to parse the rest still to see if there are more errors end_scope("Done parsing expression (error): '{}'\n", to_string(exp)); return exp; } Expression rhs = parse_expression(); if (rhs.type == Expression::Type::VAR_REF) { Expression* variable = push_expression(lhs); lhs.type = Expression::Type::MEMBER_VAR_REF; lhs.member_var_ref.member_name = rhs.var_ref; lhs.member_var_ref.variable = variable; end_scope("Done parsing expression, #1: '{}'\n", to_string(lhs)); return lhs; } else if (rhs.type == Expression::Type::FUNC_CALL) { log("Rhs was FUNC_CALL. Name length: {}\n", rhs.func_call.fn_name.length); Expression* variable = push_expression(lhs); lhs.type = Expression::Type::MEMBER_FUNC_CALL; lhs.member_func_call.variable = variable; lhs.member_func_call.fn_name = rhs.func_call.fn_name; lhs.member_func_call.array_of_params = rhs.func_call.array_of_params; lhs.member_func_call.num_params = rhs.func_call.num_params; end_scope("Done parsing expression, #2: '{}'\n", to_string(lhs)); return lhs; } // Complex cases else if (rhs.type == Expression::Type::MEMBER_FUNC_CALL) { // This could mean either `foo->bar->baz()` or `foo->bar()->baz()`. // However, right now it's constructed as // `foo->(bar->baz())` or `foo->(bar()->baz())`, both of which // are wrong, should be like `(foo->bar)->baz()` or `(foo->bar())->baz()` // NOTE: `foo` in any of these examples can be `foo` or `foo()`!! // (or any more complex expression!) // First store 'foo' persistently. // Note that any modifications to 'lhs' after this // won't change the value in 'expressions' Expression* foo = push_expression(lhs); // This is the function we're actually calling on lhs: Expression* rhs_var = rhs.member_func_call.variable; if (rhs_var->type == Expression::Type::VAR_REF) { // `foo->bar->baz()` // 'rhs_var' is `bar` here, *not* `bar->baz()`. lhs.type = Expression::Type::MEMBER_VAR_REF; lhs.member_var_ref.variable = foo; lhs.member_var_ref.member_name = rhs_var->var_ref; // Store `(foo->bar)` and rewrite so that result is `(foo->bar)->baz()` rhs.member_func_call.variable = push_expression(lhs); end_scope("Done parsing expression, #3: '{}'\n", to_string(rhs)); return rhs; } else if (rhs_var->type == Expression::Type::FUNC_CALL) { // `foo->bar()->baz()` // 'rhs_var' is `bar()` here, *not* `bar()->baz()`. lhs.type = Expression::Type::MEMBER_FUNC_CALL; lhs.member_func_call.variable = foo; lhs.member_func_call.num_params = rhs_var->func_call.num_params; lhs.member_func_call.array_of_params = rhs_var->func_call.array_of_params; lhs.member_func_call.fn_name = rhs_var->func_call.fn_name; // Store `(foo->bar())` and rewrite so that result is `(foo->bar())->baz()` rhs.member_func_call.variable = push_expression(lhs); end_scope("Done parsing expression, #4: '{}'\n", to_string(rhs)); return rhs; } else { // Syntax error. Something like `x->(y+5)->z()`? error( "Unexpected token. Expected variable name or function call after ->"); } } else if (rhs.type == Expression::Type::MEMBER_VAR_REF) { // `foo->bar->baz` or `foo->bar()->baz`. See handling of member_func_call above. Expression* variable = push_expression(lhs); Expression* rhs_var = lhs.member_var_ref.variable; if (rhs_var->type == Expression::Type::VAR_REF) { // `foo->bar->baz` lhs.type = Expression::Type::MEMBER_VAR_REF; lhs.member_var_ref.member_name = rhs_var->var_ref; lhs.member_var_ref.variable = variable; rhs.member_var_ref.variable = push_expression(lhs); end_scope("Done parsing expression, #5: '{}'\n", to_string(rhs)); return rhs; } else if (rhs_var->type == Expression::Type::FUNC_CALL) { lhs.type = Expression::Type::MEMBER_FUNC_CALL; lhs.member_func_call.variable = variable; lhs.member_func_call.fn_name = rhs_var->func_call.fn_name; lhs.member_func_call.array_of_params = rhs_var->func_call.array_of_params; lhs.member_func_call.num_params = rhs_var->func_call.num_params; rhs.member_var_ref.variable = push_expression(lhs); end_scope("Done parsing expression, #6: '{}'\n", to_string(rhs)); return rhs; } else { error("Unexpected token. Expected variable name or function call after ->"); } } } // end of `if (consume_token(TokenType::RIGHT_ARROW))` if (BinaryOp op; consume_any_binary_op(op)) { Expression* left = push_expression(lhs); lhs.type = Expression::Type::BINARY_OP; lhs.binary_op.lhs = left; lhs.binary_op.op = op; // Binary operators woo! Expression rhs = parse_expression(); if (rhs.type == Expression::Type::BINARY_OP) { if (get_precedence(op) > get_precedence(rhs.binary_op.op)) { // Convert `x OP (y OP z)` to `(x OP y) OP z` lhs.binary_op.rhs = rhs.binary_op.lhs; rhs.binary_op.lhs = push_expression(lhs); end_scope("Done parsing expression (binary op; swapped order): '{}'\n", to_string(rhs)); return rhs; } } lhs.binary_op.rhs = push_expression(rhs); end_scope("Done parsing expression (binary op): '{}'\n", to_string(lhs)); return lhs; } end_scope("Done parsing expression: '{}'\n", to_string(lhs)); return lhs; } // Tolerates push_expressions while parsing parameters, // and builds a contiguous array of parameters at the end of the 'expressions' vector. // Kind of relies on there not being enough function parameters to overflow stack? int recursive_parse_func_params(int D = 0) noexcept { Expression expression = parse_expression(); // 48 bytes on stack start_scope("Starting D={}, parsed '{}'\n", D, to_string(expression)); bool more = consume_token(TokenType::COMMA); int count = 1; // .. 52 bytes on stack per recursion, approximately if (more) { count += recursive_parse_func_params(D+1); } // Note that since this is pushed last, the parameters are pushed in reverse order. // This is why we're reversing the array after pushing the last one push_expression(expression); end_scope("Ending D={}. Count: {}\n", D, count); return count; } void parse_struct() noexcept { log("Parsing struct -- done, not implemented\n"); } void parse_imports() noexcept { std::unordered_map<std::string, SourceRef> paths; while(consume_identifier("import")) { const SourceRef& source_pos = source_refs[index].whole_line(); //token(); data(); // advance both std::string path; TokenType expected = TokenType::IDENTIFIER; while(!consume_token(TokenType::SEMICOLON)) { if (!expect(expected)) token(); // consume either way to not get stuck if (expected == TokenType::IDENTIFIER) { expected = TokenType::DOUBLE_COLON; path += data().identifier; } else { // Found :: expected = TokenType::IDENTIFIER; path += '/'; } } path += ".rsc"; if (auto it = paths.find(path); it != paths.end()) { warn("Duplicate import '{}'", path) .at(source_pos) .with_caret(false); note( "first occurrence here:") .at(it->second) .with_caret(false) .with_underline(false); } else { paths.insert({ std::move(path), source_pos }); } } for (auto& [path, src_ref] : paths) { log("Import statement found! Path: \"{}\"\n", path); } } private: // Conversion methods Literal get_literal() noexcept { // Assumes token() == TokenType::LITERAL. Check first! Literal literal{}; // This is stupid TokenData token_data = data(); switch(token_data.type) { case TokenData::Type::UINT: literal.type = Literal::Type::UINT; literal.uint_literal = token_data.uint_literal; break; case TokenData::Type::INT: literal.type = Literal::Type::INT; literal.int_literal = token_data.int_literal; break; case TokenData::Type::FLOAT: literal.type = Literal::Type::FLOAT; literal.float_literal = token_data.float_literal; break; case TokenData::Type::STRING: literal.type = Literal::Type::STRING; literal.string_literal = token_data.string_literal; break; case TokenData::Type::CHAR: literal.type = Literal::Type::CHAR; literal.char_literal = token_data.char_literal; break; default: ice_abort(1, "get_literal: invalid token data"); } return literal; } Identifier get_identifier() noexcept { // Assumes token() == TokenType::IDENTIFIER. Check first! Identifier identifier{}; TokenData token_data = data(); // Safety check even though this should never be true if (token_data.type != TokenData::Type::IDENTIFIER) { ice_abort(1, "get_identifier: invalid token data"); } identifier.string = token_data.identifier; identifier.length = source_refs[index-1].length; // Hack return identifier; } bool consume_any_assignment_bin_op(BinaryOp& out) noexcept { switch(peek_token()) { case TokenType::SET_ADD: out = BinaryOp::ADD; break; // += case TokenType::SET_SUB: out = BinaryOp::SUB; break; // -= case TokenType::SET_MUL: out = BinaryOp::MUL; break; // *= case TokenType::SET_DIV: out = BinaryOp::DIV; break; // /= case TokenType::SET_MOD: out = BinaryOp::MOD; break; // %= case TokenType::SET_OR: out = BinaryOp::BIT_OR; break; // |= case TokenType::SET_AND: out = BinaryOp::BIT_AND; break; // &= case TokenType::SET_XOR: out = BinaryOp::BIT_XOR; break; // ^= case TokenType::SET_LSHIFT: out = BinaryOp::LSHIFT; break; // <<= case TokenType::SET_RSHIFT: out = BinaryOp::RSHIFT; break; // >>= default: return false; } token(); // Consume the token return true; } bool consume_any_binary_op(BinaryOp& out) noexcept { switch(peek_token()) { case TokenType::PLUS_SIGN: out = BinaryOp::ADD; break; // + case TokenType::MINUS_SIGN: out = BinaryOp::SUB; break; // - case TokenType::ASTERISK: out = BinaryOp::MUL; break; // * case TokenType::FORWARD_SLASH: out = BinaryOp::DIV; break; // / case TokenType::MODULUS: out = BinaryOp::MOD; break; // % case TokenType::BITWISE_OR: out = BinaryOp::BIT_OR; break; // | case TokenType::BITWISE_AND: out = BinaryOp::BIT_AND; break; // & case TokenType::BITWISE_XOR: out = BinaryOp::BIT_XOR; break; // ^ case TokenType::LSHIFT: out = BinaryOp::LSHIFT; break; // << case TokenType::RSHIFT: out = BinaryOp::RSHIFT; break; // >> case TokenType::LOGICAL_AND: out = BinaryOp::AND; break; // && case TokenType::LOGICAL_OR: out = BinaryOp::OR; break; // || case TokenType::LESS_THAN: out = BinaryOp::LTHAN; break; // < case TokenType::LEQUAL_TO: out = BinaryOp::LEQUAL_TO; break; // <= case TokenType::EQUAL_TO: out = BinaryOp::EQUAL_TO; break; // == case TokenType::NEQUAL_TO: out = BinaryOp::NEQUAL_TO; break; // != case TokenType::GEQUAL_TO: out = BinaryOp::GEQUAL_TO; break; // >= case TokenType::GREATER_THAN: out = BinaryOp::GTHAN; break; // > default: return false; } token(); // Consume the token return true; } bool consume_any_unary_op(UnaryOp& out) noexcept { switch(peek_token()) { case TokenType::BITWISE_NOT: out = UnaryOp::BIT_NOT; break; // ~x case TokenType::MINUS_SIGN: out = UnaryOp::NEGATE; break; // -x case TokenType::EXCLAMATION: out = UnaryOp::NOT; break; // !x default: return false; } token(); // Consume the token return true; } private: // Methods for consuming and checking tokens void skip_token() noexcept { // Some tokens have data associated, and that needs to be consumed too. switch(token()) { case TokenType::LITERAL: case TokenType::IDENTIFIER: data(); break; default: break; } } void skip_until(TokenType type) noexcept { while(!consume_token(type)) { skip_token(); } } bool consume_identifier(const char* name) noexcept { if (peek_token() == TokenType::IDENTIFIER && strequals(peek_data().identifier, name)) { token(); data(); // Consume found token and its data return true; } return false; } bool consume_token(TokenType type) noexcept { if (peek_token() == type) { token(); // Consume return true; } return false; } bool expect_identifier(Identifier& out) noexcept { if (!consume_token(TokenType::IDENTIFIER)) { std::string_view found = src.get_token_at(source_refs[index]); std::string_view expected = TokenTypes::stringify(TokenType::IDENTIFIER); error("Unexpected token '{}', expected '{}'", found, expected) .with_caret(false); return false; } // TODO Use get_identifier()? out.string = data().identifier; out.length = source_refs[index-1].length; // bit of a hack. -2 because "" are included return true; } bool expect(TokenType type) noexcept { if (!consume_token(type)) { std::string_view found = src.get_token_at(source_refs[index]); std::string_view expected = TokenTypes::stringify(type); log("Logging issue\n"); error( "Unexpected token '{}', expected '{}'", found, expected) .with_caret(false); log("issue logged\n"); return false; } return true; } TokenType token() noexcept { return tokens[index++]; } TokenData data() noexcept { return *datas++; } [[nodiscard]] TokenType peek_token() const noexcept { return tokens[index]; } [[nodiscard]] TokenData peek_data() const noexcept { return *datas;} ErrorInfo error_info_here() const noexcept { ErrorInfo info; info.file = &src; info.where = source_refs[index]; if (info.where.length == 1) info.show_caret = true; return info; } private: Expression* push_expression(const Expression& expression) noexcept { if (expressions.size() == expressions.capacity()) { fmt::print("WELP: {}/{}\n", expressions.size(), num_tokens); return nullptr; } expressions.push_back(expression); return &expressions.back(); } Statement* push_statement(const Statement& statement) noexcept { if (expressions.size() == expressions.capacity()) { fmt::print("WELP: {}/{}\n", expressions.size(), num_tokens); return nullptr; } statements.push_back(statement); return &statements.back(); } private: // Logging template<typename ... Args> Issue& warn(std::string_view format, Args&&... args) noexcept { Issue issue; issue.where = source_refs[index]; issue.message = fmt::format(format, std::forward<Args>(args)...); issue.type = Issue::Type::WARNING; issue.underline = true; issue.show_caret = false; if (current_function_name.length != 0) { issue.function_name = current_function_name.str_view(); } if (issue.where.length == 1) issue.show_caret = true; issues.push_back(std::move(issue)); return issues.back(); } template<typename ... Args> Issue& error(std::string_view format, Args&&... args) noexcept { Issue issue; issue.where = source_refs[index]; issue.message = fmt::format(format, std::forward<Args>(args)...); issue.type = Issue::Type::ERROR; issue.underline = true; issue.show_caret = false; log("issue created\n"); if (current_function_name.length != 0) { issue.function_name = current_function_name.str_view(); } if (issue.where.length == 1) issue.show_caret = true; log("Pushing issue\n"); issues.push_back(std::move(issue)); log("Pushed, returning\n"); return issues.back(); } template<typename ... Args> Issue& note(std::string_view format, Args&&... args) noexcept { Issue issue; issue.where = source_refs[index]; issue.message = fmt::format(format, std::forward<Args>(args)...); issue.type = Issue::Type::INFO; issues.push_back(std::move(issue)); return issues.back(); } private: size_t index; size_t num_tokens; TokenType* tokens; TokenData* datas; SourceRef* source_refs; const SourceFile& src; // Neither of these are ever reallocated so pointers are stable std::vector<Expression> expressions; std::vector<Statement> statements; std::vector<Issue> issues; Identifier current_function_name; tsl::sparse_map<Identifier, FuncDecl> functions; tsl::sparse_map<Identifier, StructDecl> structs; }; std::optional<AST> Parser::parse(const SourceFile& src, LexResult& lex) { if (lex.token_types.empty()) return std::nullopt; printf("Tokens (%lld) {\n", lex.token_types.size()); int data_pos = 0; for (TokenType token : lex.token_types) { if (token == TokenType::LITERAL) { fmt::print(" literal "); switch(lex.token_datas[data_pos].type) { case TokenData::Type::STRING: fmt::print("(string): \"{}\"\n", lex.token_datas[data_pos++].string_literal); break; case TokenData::Type::CHAR: fmt::print("(char): '{}'\n", lex.token_datas[data_pos++].char_literal); break; case TokenData::Type::INT: fmt::print("(int): {}\n", lex.token_datas[data_pos++].int_literal); break; case TokenData::Type::UINT: fmt::print("(uint): {}\n", lex.token_datas[data_pos++].uint_literal); break; case TokenData::Type::FLOAT: fmt::print("(float): {}\n", lex.token_datas[data_pos++].float_literal); break; case TokenData::Type::IDENTIFIER: fmt::print("(identifier): \"{}\"\n", lex.token_datas[data_pos++].identifier); break; } } else if (token == TokenType::IDENTIFIER) { fmt::print(" identifier: \"{}\"\n", lex.token_datas[data_pos++].identifier); } else fmt::print(" '{}'\n", TokenTypes::stringify(token)); } printf("}\n"); std::optional<AST> ast = ParserUnit(src, lex).parse(); return ast; }
true
2d3097d6e93f53014f7d61c201ab71e2490e6ceb
C++
MFarradji/inf3105
/labs/lab10/lab10a.cpp
UTF-8
404
3.1875
3
[ "MIT" ]
permissive
#include <iostream> #include <string> #include <vector> using namespace std; int main() { vector<string> tab; tab.push_back("un"); // tab.ajouter("un"); tab.push_back("deux"); tab.push_back("trois"); tab.push_back("quatre"); tab.push_back("cinq"); vector<string> tab2 = tab; for (vector<string>::iterator iter = tab2.begin(); iter != tab2.end(); ++iter) cout << *iter << endl; }
true
bfada6ac28009bb9291d23a2648f699f1d51c652
C++
soneoed/cycloid
/main.cpp
UTF-8
1,846
2.90625
3
[]
no_license
/* */ #include "main.h" #include "locomotion/cmotion.h" #include "control/controlthread.h" // Thread scheduling variables (semaphores, mutexes, etc) sem_t NewSensorDataSemaphore; sem_t ControlReadySemaphore; void createThreadScheduling(); void createControlThread(CMotion* motion); int main() { createThreadScheduling(); CMotion* Motion = new CMotion(); createControlThread(Motion); return 0; } void createThreadScheduling() { // create and initialise thread scheduling tools int result = 0; result = sem_init(&NewSensorDataSemaphore, 0, 0); if (result == -1) { cout << "MAIN: Failed to initialise NewSensorDataSemaphore. Error code: " << errno << endl; return; } result = sem_init(&ControlReadySemaphore, 0, 1); if (result == -1) { cout << "MAIN: Failed to initialise ControlReadySemaphore. Error code: " << errno << endl; return; } } void createControlThread(CMotion* motion) { // create control thread cout << "MAIN: Creating controlthread as realtime, with priority " << CONTROLTHREAD_PRIORITY << endl; int err; pthread_t controlthread; err = pthread_create(&controlthread, NULL, runControlThread, motion); // the control thread needs the motion if (err > 0) { cout << "MAIN: Failed to create controlthread. Error code: " << err << endl; return; } sched_param param; param.sched_priority = CONTROLTHREAD_PRIORITY; pthread_setschedparam(controlthread, SCHED_FIFO, &param); // double check int actualpolicy; sched_param actualparam; pthread_getschedparam(controlthread, &actualpolicy, &actualparam); cout << "MAIN: Actual settings for controlthread; Policy: " << actualpolicy << " Priority: " << actualparam.sched_priority << endl; pthread_join(controlthread, NULL); }
true
b04f6d73854723dc598aef77561cf9b320ac9dde
C++
RashikAnsar/everyday_coding
/problems/arrays/sunny_buildings.cpp
UTF-8
673
3.28125
3
[]
no_license
/** * The heights of certain Buildings which lie adjacent to each other are given. *Light starts falling from left side of the buildings. If there is a building *of certain Height, all the buildings to the right side of it having lesser *heights cannot see the sun . The task is to find the total number of such *buildings that receive light. ***/ #include <climits> #include <iostream> using namespace std; int main() { int n, ans = 0, left_max_height = INT_MIN; cin >> n; for (int i = 0; i < n; i++) { int num; cin >> num; if (num >= left_max_height) { ans++; left_max_height = num; } } cout << ans << endl; return 0; }
true
b54c720d107046131df74ab4ab41a8d172a1900f
C++
panu2306/Data-Structure-Programs
/stack_array_implementation.cpp
UTF-8
1,190
3.828125
4
[]
no_license
#include <bits/stdc++.h> using namespace std; #define MAX_SIZE 100 void push(int ele); int pop(); int size(); bool isEmpty(); int returnTop(); int arr[MAX_SIZE]; int top = -1; int main(){ int op = -1; int ele; cout << "choose the operation - 1. Push 2.Pop 3.Return Top 4. Return if stack empty 5. size of stack " << endl; while(op != 0){ cin >> op; switch(op){ case 1:{ cout << "Enter ele to insert into stack: "; cin >> ele; push(ele); break; } case 2:{ int e = pop(); cout << e << " is popped!" << endl; break; } case 3:{ cout << "Top is: " << returnTop() << endl; break; } case 4:{ isEmpty() ? cout << "True" << endl : cout << "False" << endl; break;} case 5:{ cout << "Size of stack" << size() << endl; break;} default:{ cout << "Enter Valid Operation" << endl; break; } }} return 0; } void push(int ele){ top += 1; arr[top] = ele; } int returnTop(){ return arr[top]; } bool isEmpty(){ if(top == -1){ return true; }else{ return false; } } int pop(){ if(top == -1){ cout << "No element in stack" << endl; } top -= 1; return arr[top+1]; } int size(){ return top+1; }
true
c604bc8e3536b0450bc7fd3e1fc2cd6dbda3aebe
C++
dshin21/RPNCalculator
/subtraction_operation.hpp
UTF-8
469
3.078125
3
[]
no_license
#pragma once #include <iostream> #include "abstract_operation.hpp" class subtraction_operation : public abstract_operation { public: static const char operation_CODE = '-'; subtraction_operation() : abstract_operation(operation_CODE) {}; ~subtraction_operation(); int perform(int, int) override; }; inline subtraction_operation::~subtraction_operation() {}; int subtraction_operation::perform(int first, int second) { return first - second; }
true
27cb378001b4252ebee124981797bedb61100aa3
C++
liuning587/D6k2.0master
/d6k/trunk/src/mail/queue_impl.h
GB18030
2,356
2.765625
3
[]
no_license
/*! @file queue_impl.h <PRE> ******************************************************************************** ģ : ļ : queue_impl.h ļʵֹ : ̶еĴ : LiJin 汾 : V1.00 -------------------------------------------------------------------------------- ע : Ϊǵƽ̨ļδȷԣʲpimplģʽ -------------------------------------------------------------------------------- ޸ļ¼ : 汾 ޸ ޸ ******************************************************************************** </PRE> * @brief ̶еĴ * @author LiJin * @version 1.0 * @date 2016.09.15 *******************************************************************************/ #ifndef QUEUE_IMPL_H #define QUEUE_IMPL_H #include <boost/interprocess/ipc/message_queue.hpp> #include <memory> class CQueue { public: CQueue(); explicit CQueue(int nID) :m_nQueueID(nID), m_nOpenCount(0), m_nSentMailID(0) { m_bIsOpened = false; } ~CQueue(); public: bool Create(const char *pszName,size_t nNum,size_t nSize); void Destroy(); bool Open(const char *pszName); void Close( ); bool Send(const unsigned char *pData, size_t nSize, unsigned int nPriority); bool TrySend(const unsigned char *pData, size_t nSize, unsigned int nPriority); bool Send(const unsigned char *pData, size_t nSize, unsigned int nPriority,unsigned int nTimeOut); bool Receive(unsigned char * pBuff, size_t nBuffSize, size_t & nRecvdSize, unsigned int & nPriority); bool TryReceive(unsigned char * pBuff, size_t nBuffSize, size_t & nRecvdSize, unsigned int & nPriority); bool Receive(unsigned char * pBuff, size_t nBuffSize, size_t & nRecvdSize, unsigned int & nPriority, unsigned int nTimeOut); std::string &GetName() { return m_szName; } int GetQueueID()const { return m_nQueueID; } unsigned int GetMailID() { m_nSentMailID++; return m_nSentMailID; } bool IsOpened() { return m_bIsOpened; } private: //! Ƿ򿪹 bool m_bIsOpened; std::shared_ptr<boost::interprocess::message_queue> m_pQue; std::string m_szName; size_t m_nOpenCount; int m_nQueueID; //! еıʶ unsigned int m_nSentMailID; //! ʼıʶ }; #endif // QUEUE_IMPL_H /** @}*/
true
e0c3de83122490fe070080d24fdb73da8a44c91f
C++
meskandari/Power-Grid
/Cpp files/Picture.cpp
UTF-8
2,142
3.03125
3
[]
no_license
#include <string> #include <allegro5/allegro.h> #include <allegro5/allegro_image.h> #include "Picture.h" #include <iostream> // Default constructor. Doesn't build the picture yet. Picture::Picture(): Graphic() { file = ""; bitmap = nullptr; resize = 1; } // Sets the picture name and file name. Picture::Picture(std::string _name, std::string _file): Graphic(_name) { file = _file; bitmap = al_load_bitmap(file.c_str()); resize = 1; } // Sets the picture name and file name, as well as its coordinates. Picture::Picture(std::string _name, std::string _file, int _x, int _y): Graphic(_name, _x, _y) { file = _file; bitmap = al_load_bitmap(file.c_str()); resize = 1; } // Full constructor. Sets picture name, file name, coordinates, and resize value. Picture::Picture(std::string _name, std::string _file, int _x, int _y, float _resize) : Graphic(_name, _x, _y) { file = _file; bitmap = al_load_bitmap(file.c_str()); resize = _resize; } Picture::~Picture() { al_destroy_bitmap(bitmap); bitmap = nullptr; } // Draws the picture onto the screen. void Picture::draw() { if (!hidden && bitmap != nullptr) { al_draw_scaled_bitmap(bitmap, 0, 0, al_get_bitmap_width(bitmap), al_get_bitmap_height(bitmap), x, y, al_get_bitmap_width(bitmap)*resize, al_get_bitmap_height(bitmap)*resize, 0); } } // Returns true if the given Click coordinates collide with the picture. bool Picture::wasClicked(int _x, int _y) { if (hidden) { return false; } int width = al_get_bitmap_width(bitmap) * resize; int height = al_get_bitmap_height(bitmap) * resize; return (_x >= x && _x <= x + width && _y >= y && _y <= y + height); } // Changes the picture to the given file name. void Picture::changePicture(std::string _file) { if (file == _file) { return; } file = _file; bitmap = al_load_bitmap(file.c_str()); } // Sets the resize of the picture. 1 = default scale (100%) void Picture::set_resize(float _resize) { resize = _resize; } // Returns the current resize percentage of the picture. float Picture::get_resize() const { return resize; }
true
9becc919a6217b96aaa635fa2454847251398f05
C++
stefanalex99/algorithm-design
/CPP/data-structures/Circular_Queue.cpp
UTF-8
3,692
4.21875
4
[ "MIT" ]
permissive
/** Circular Queue */ #define DEFAULT_SIZE 100 #include <iostream> #include <climits> template <typename T> class Queue { private: T *container; int numElems; int size; int head, tail; public: /** Constructor */ Queue() { container = new T[DEFAULT_SIZE]; numElems = 0; this->size = DEFAULT_SIZE; head = tail = 0; } /** 2nd Constructor */ Queue(int size) { container = new T[size]; numElems = 0; this->size = size; head = tail = 0; } /** Destructor */ ~Queue() { delete[] container; } /** Assignment operator */ Queue &operator=(const Queue &copy) { this->container = new T[copy.size]; for (int i = 0; i < copy.size; i++) { this->container[i] = copy.container[i]; } this->size = copy.size; this->numElems = copy.numElems; this->head = copy.head; this->tail = copy.tail; return *this; } /** Copy Constructor */ Queue(const Queue &copy) { this->container = new T[copy.size]; for (int i = 0; i < copy.size; i++) { this->container[i] = copy.container[i]; } this->size = copy.size; this->numElems = copy.numElems; this->head = copy.head; this->tail = copy.tail; } /** Insert an element into the circular queue */ void enQueue(T x) { if (isFull()) { std::cout << "Can't enqueue, queue is full!\n"; return; } container[tail] = x; tail = (tail + 1) % size; numElems++; } /** Delete an element from the circular queue */ void deQueue() { if (isEmpty()) { std::cout << "Can't dequeue, queue is empty!\n"; return; } numElems--; head = (head + 1) % size; } /** Get the front item from the queue */ int front() { if (isEmpty()) { return INT_MIN; } return container[head]; } /** Checks whether the circular queue is empty or not */ bool isEmpty() { return !numElems; } /** Checks whether the circular queue is full or not */ bool isFull() { return numElems == size; } /** Overloading << operator */ template <typename U> friend std::ostream& operator<< (std::ostream& stream, Queue<U> &obj); }; template <typename T> std::ostream& operator<< (std::ostream& stream, Queue<T> &obj) { for (int i = 0; i < obj.numElems; i++) { T front = obj.front(); stream << front << " "; obj.deQueue(); obj.enQueue(front); } stream << std::endl; return stream; } int main() { /** Checking functionality of Circular Queue */ Queue<int> q(4); /** Checking isEmpty */ if (q.isEmpty()) { std::cout << "Queue is empty\n"; } /** Checking deQueue for empty queue */ q.deQueue(); /** Checking enQueue */ q.enQueue(2); q.enQueue(3); q.enQueue(-4); q.enQueue(23); /** Checking operator<< overloading */ std::cout << q; /** Checking enQueue for full queue */ q.enQueue(2); /** Checking isFull */ if (q.isFull()) { std::cout << "Queue is full\n"; } /** Checking deQueue */ q.deQueue(); std::cout << q; /** Checking front */ std::cout << q.front() << std::endl; /** Checking Copy Constructor */ Queue<int> p = q; std::cout << p; /** Checking operator= overloading */ Queue<int> r; r = p; std::cout << r; q.enQueue(2); r = q; std::cout << r; return 0; }
true
154085666915166418517b74db95f055045e2b4d
C++
antoinechalifour/Cpp_TP4
/CTableGType.h
UTF-8
1,416
3.28125
3
[]
no_license
#ifndef _CTableGTypeT_H #define _CTableGTypeT_H template<class T, int N=10> class CTableGType{ private: T tab[N]; int lastIndex; public: CTableGType(); CTableGType(const CTableGType<T, N>&); ~CTableGType(); CTableGType& operator=(const CTableGType<T, N>&); T operator[](int i) const; T& operator[](int i); int getSize(); void pushElement(T i); T popElement(); }; template<class T, int N> CTableGType<T, N>::CTableGType(){ lastIndex=-1;} template <class T, int N>CTableGType<T, N>::CTableGType(const CTableGType<T, N>& ct): lastIndex(ct.lastIndex) { for(int i=0 ; i<=lastIndex ; i++) tab[i]=ct[i]; } template<class T, int N> T CTableGType<T, N>::operator[](int i) const{ if(i<0) throw -1; if(i>lastIndex) throw -2; return tab[i]; } template<class T, int N> T& CTableGType<T, N>::operator[](int i){ if(i<0) throw -1; if(i>lastIndex) throw -2; return tab[i]; } template<class T, int N> CTableGType<T, N>& CTableGType<T, N>::operator=(const CTableGType<T, N>& ct){ lastIndex=ct.lastIndex; for(int i=0 ; i<=lastIndex ; i++) tab[i]=ct[i]; return *this; } template<class T, int N> int CTableGType<T, N>::getSize(){ return lastIndex+1; } template<class T, int N> void CTableGType<T, N>::pushElement(T i){ tab[++lastIndex]=i; } template<class T, int N> T CTableGType<T, N>::popElement(){ return tab[lastIndex--]; } template<class T, int N> CTableGType<T, N>::~CTableGType(){} #endif
true
ed1c2873fdb6812df3e8c2a35db1720b08a586e3
C++
leonardovallem/grafos-implementation
/dp/main.cpp
UTF-8
614
3.140625
3
[]
no_license
#include <iostream> #include "Matrix.h" int main() { Matrix grafo; grafo.add("1"); grafo.add("2"); grafo.add("3"); grafo.add("4"); grafo.addRelation("1", "2", 2); grafo.addRelation("3", "1", 5); grafo.addRelation("3", "4", 3); grafo.addRelation("4", "3", 9); grafo.addRelation("1", "4", 6); grafo.addRelation("2", "4", 1); grafo.addRelation("2", "3", 4); grafo.addRelation("4", "2", 7); grafo.addRelation("4", "4", 3); std::cout << grafo.toString() << std::endl; grafo.remove("2"); std::cout << grafo.toString() << std::endl; return 0; }
true
fd6814752bae9105a8e2f1f42b23ded99d944ffd
C++
amj311/cs142-lab8-shopping-cart
/ItemToPurchase.h
UTF-8
702
3.078125
3
[]
no_license
#ifndef ITEMTOPURCHASE_H #define ITEMTOPURCHASE_H #include <string> using namespace std; class ItemToPurchase { public: //Default constructor ItemToPurchase(string itemName = "none", string itemDescription = "none", double itemPrice = 0.0, int itemQuantity = 0); void SetName(string nameToSet); string GetName(); void SetDescription(string descriptionToSet); string GetDescription(); void SetPrice(double priceToSet); double GetPrice(); void SetQuantity(int quantityToSet); int GetQuantity(); string PrintCost(); string PrintDescription(); private: string itemName; string itemDescription; double itemPrice; int itemQuantity; }; #endif
true
c384d3f4401444ad5f8a10aef04534c1bb4b6b21
C++
rohitbhatghare/c-c-
/Sept-08-20/assignment23.cpp
UTF-8
993
3.359375
3
[]
no_license
#include<iostream> #include<conio.h> using namespace std; int main(int x,int y) { int x,y; cout<<"\n Enter Value of "<<endl; cout<<"x="<<endl; cin>>x; cout<<endl; cout<<"\n Enter Value of "<<endl; cout<< "y="<<endl; cin>>y; if((x>0)&&(y>0)) { cout<<"The input belongs to Quadrant-1 :"<<endl; cout<<"(where all values are in positive manner)"<<endl; } else if((x<0)&&(y>0)) { cout<<"The input belongs to Quadrant-2 :"<<endl; cout<<"(where X is Negative and Y is positive manner)"<<endl; } else if((x<0)&&(y<0)) { cout<<"The input belongs to Quadrant-3 :"<<endl; cout<<"(where all values are in negative manner)"<<endl; } else if((x>0)&&(y<0)) { cout<<"The input belongs to Quadrant-3 :"<<endl; cout<<"(where X is positive and Y is negative manner)"<<endl; } } int fun() { return (x,y); }
true
0c9cb323a386f9efe7c5a51c90bf26951ee4a77e
C++
phoenix76/teach_projects
/Prata_S/Prata_S/pr56.cpp
UTF-8
808
3.4375
3
[]
no_license
#include <iostream> #include <array> int main() { const char *months[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; int price[3][13] = { 0 }; int all = 0; int year = 2012; for(int i = 0; i < 3; i++) { for(int k = 0; k < 12; k++) { std::cout << "Enter the price for " << months[k] << " month of " << year << " year: "; std::cin >> price[i][k]; price[i][12] += price[i][k]; } year++; all += price[i][12]; } year = 2012; for(int i = 0; i < 3; i++, year++) std::cout << "Sell books of " << year << " year is: " << price[i][12] << " exmp." << std::endl; std::cout << "Count of books for the all time is " << all << " exmp." << std::endl; system("pause"); return 0; }
true
04c371c1456a1f17b3a352ec35ae01ee89c19f97
C++
vinothcse123/Miscellaneous
/PHN-CodeUpload/user_defined_key_for_map.cpp
UTF-8
548
3.1875
3
[]
no_license
#include<iostream> #include <algorithm> #include <map> template<typename T1,typename T2> class KeyPair { public: T1 key1; T2 key2; KeyPair(T1 a,T2 b): key1(a),key2(b) {} bool operator<(const KeyPair<T1,T2> &obj)const { if(key1 < obj.key1) { return true; } return false; } }; int main() { std::map<KeyPair<int,int>,int> l_timePeriodMap; l_timePeriodMap.insert( std::make_pair<KeyPair<int,int>,int>(KeyPair<int,int>(5,20),100) ); return 0; }
true
27f246e64e5072b2a011e97500c0b210b501f2a6
C++
zlumer/eos-london-poker
/contracts/notechain/notechain.cpp
UTF-8
22,097
2.59375
3
[]
no_license
#include <eosiolib/eosio.hpp> #include <eosiolib/print.hpp> #include <eosiolib/asset.hpp> #include <eosiolib/currency.hpp> #include <eosiolib/singleton.hpp> #include <eosiolib/time.hpp> #include <eosiolib/system.h> #include <eosio.token/eosio.token.hpp> using namespace eosio; struct playerpair { uint64_t alice; uint64_t bob; }; class poker : public eosio::contract { private: public: using contract::contract; enum roundstatename { NOT_STARTED, WAITING_FOR_PLAYERS, TABLE_READY, SHUFFLE, RECRYPT, DEAL_POCKET, BET_ROUND, DEAL_TABLE, SHOWDOWN, END }; /// @abi table rounddatas struct rounddata { uint64_t table_id; // current state of the game roundstatename state; // target player (behavior depends on current state) account_name target; // first player account_name alice; // second player account_name bob; // bankroll (total available money) eosio::asset alice_bankroll; eosio::asset bob_bankroll; // current round bets eosio::asset alice_bet; eosio::asset bob_bet; // amount of money needed to enter this table eosio::asset buy_in; // table cards vector<checksum256> table_cards; // amount of cards that came into play uint8_t cards_dealt; // array of encrypted cards in a deck vector<checksum256> encrypted_cards; // player private keys (PK_0, PK_1-PK_52) vector<checksum256> alice_keys; vector<checksum256> bob_keys; // whether the players are ready to play bool alice_ready; bool bob_ready; auto primary_key() const { return table_id; } }; typedef eosio::multi_index< N(rounddata), rounddata // indexed_by< N(getbyuser), const_mem_fun<notestruct, account_name, &notestruct::get_by_user> > > rounddatas; // we need this struct and table to access eosio.token balances struct account { asset balance; uint64_t primary_key()const { return balance.symbol.name(); } }; typedef eosio::multi_index<N(accounts), account> accounts; //////////// GAME SEARCH SIMPLIFIED FOR HACKATHON //////////// /// @abi action void search_game( /* asset min_stake, asset max_stake */ ) // only one bet possible for hackathon { /* player searches a suitable table (for hackathon any table is suitable) */ rounddatas datas(_self, _self); for (auto table_it = datas.begin(); table_it != datas.end(); ++table_it) { if (table_it->state != WAITING_FOR_PLAYERS) { // skip already playing tables continue; } if (table_it->alice == _self) { // can't play with myself continue; } if (table_it->bob == account_name()) { // found suitable table, let's join it datas.modify(table_it, _self, [&]( auto& table ) { table.bob = _self; table.state = TABLE_READY; }); return; } } // couldn't find suitable table, let's create a new one datas.emplace(_self, [&]( auto& table ) { table.table_id = datas.available_primary_key(); table.alice = _self; table.state = WAITING_FOR_PLAYERS; // table buy-in is hardcoded for the duration of hackathon table.buy_in = asset(1000, CORE_SYMBOL); }); } /// @abi action void cancel_game(uint64_t table_id) { /* cancel game before the start */ rounddatas datas(_self, _self); auto table_it = datas.find(table_id); assert(table_it != datas.end()); assert((table_it->state == WAITING_FOR_PLAYERS) || (table_it->state == TABLE_READY)); assert((_self == table_it->alice) || (_self == table_it->bob)); if (_self == table_it->alice) { // this is the user that created table (alice) datas.modify(table_it, _self, [&](auto& table) { // make other player (bob) the creator table.alice = table.bob; table.bob = account_name(); table.state = WAITING_FOR_PLAYERS; table.alice_ready = false; table.bob_ready = false; }); } else { // just remove the player from table datas.modify(table_it, _self, [&](auto& table) { table.bob = account_name(); table.state = WAITING_FOR_PLAYERS; table.alice_ready = false; table.bob_ready = false; }); } } /// @abi action void start_game(uint64_t table_id) { rounddatas datas(_self, _self); auto table_it = datas.find(table_id); assert(table_it != datas.end()); assert(table_it->state == TABLE_READY); assert((_self == table_it->alice) || (_self == table_it->bob)); // check if other player is ready bool ready = (_self == table_it->alice) ? table_it->bob_ready : table_it->alice_ready; if (!ready) { // other player is not ready, wait for them datas.modify(table_it, _self, [&](auto& table) { if (_self == table.alice) { table.alice_ready = true; } else { table.bob_ready = true; } }); } else { // both players are ready, we can start the game and shuffle cards datas.modify(table_it, _self, [&](auto& table) { table.state = SHUFFLE; table.target = table.alice; table.cards_dealt = 0; table.alice_keys = vector<checksum256>(53); table.bob_keys = vector<checksum256>(53); }); } // now we should hold the bankroll amount of money on user account (hard-coded for now) // FIXME: this stake is lost if game is cancelled, but game cancellation is not handled under hackathon time pressure asset newBalance(table_it->buy_in.amount * 2, table_it->buy_in.symbol); action( permission_level{ _self, N(active) }, N(eosio.token), N(transfer), std::make_tuple(_self, N(notechainacc), newBalance, std::to_string(table_it->table_id)) ).send(); } bool enoughMoney(account_name opener, asset quantity) { return getUserBalance(opener, quantity).amount >= quantity.amount; } asset getUserBalance(account_name opener, asset quantity) { accounts acc( N(eosio.token), opener ); auto balance = acc.get(quantity.symbol.name()); return balance.balance; } /////////////////////////////////////////////////////////// // SIMPLIFIED FOR HACKATHON (only needed to finalize on-chain cheating detection, trivial to implement) checksum256 encrypt(checksum256 card, checksum256 pk) { /* encrypts card with commutative cryptography algorithm */ /* XOR is not secure and is only used for illustration purposes. ElGamal/SRA are okay with certain params. */ // xor card with pk return card; } // SIMPLIFIED FOR HACKATHON (only needed to finalize on-chain cheating detection, trivial to implement) checksum256 decrypt(checksum256 card, checksum256 pk) { /* decrypts card with commutative cryptography algorithm */ /* XOR is not secure and is only used for illustration purposes. ElGamal/SRA are okay with certain params. */ // xor card with pk return card; } ///////////////////////// SHUFFLING METHODS //////////////////////////// /// @abi action void deck_shuffled(uint64_t table_id, vector<checksum256> encrypted_cards) { /* player pushes shuffled & encrypted deck */ rounddatas datas(_self, _self); auto table_it = datas.find(table_id); assert(table_it != datas.end()); assert(table_it->state == SHUFFLE); assert(_self == table_it->target); if (_self == table_it->alice) { // first player has shuffled the cards, we need to give cards to another player datas.modify(table_it, _self, [&](auto& table) { // table.state = SHUFFLE; // state doesn't change table.target = table.bob; table.encrypted_cards = encrypted_cards; }); } else { // both players have shuffled the cards, we can proceed with re-encryprion datas.modify(table_it, _self, [&](auto& table) { table.state = RECRYPT; table.target = table.alice; table.encrypted_cards = encrypted_cards; }); } } /// @abi action void deck_recrypted(uint64_t table_id, vector<checksum256> encrypted_cards) { /* player pushes re-encrypted deck */ rounddatas datas(_self, _self); auto table_it = datas.find(table_id); assert(table_it != datas.end()); assert(table_it->state == RECRYPT); assert(_self == table_it->target); if (_self == table_it->alice) { // first player has re-encrypted the cards, we need to give cards to another player datas.modify(table_it, _self, [&](auto& table) { // table.state = SHUFFLE; // state doesn't change table.target = table.bob; table.encrypted_cards = encrypted_cards; }); } else { // both players have re-encrypted the cards, we can proceed to game datas.modify(table_it, _self, [&](auto& table) { table.state = DEAL_POCKET; table.target = table.alice; table.cards_dealt = 0; table.encrypted_cards = encrypted_cards; }); } } /// @abi action void card_key(uint64_t table_id, checksum256 key) { /* receive next card private key from player */ rounddatas datas(_self, _self); auto table_it = datas.find(table_id); assert(table_it != datas.end()); assert((table_it->state == DEAL_TABLE) || (table_it->state == DEAL_POCKET)); assert((_self == table_it->alice) || (_self == table_it->bob)); if (table_it->state == DEAL_POCKET) { // we're dealing pocket cards assert(_self != table_it->target); // we should not send encryption keys for our own cards if (_self == table_it->alice) { datas.modify(table_it, _self, [&](auto& table) { // save the key for later use in decryption table.alice_keys[table.cards_dealt + 1] = key; table.cards_dealt = table.cards_dealt + 1; table.target = table.bob; }); } else { datas.modify(table_it, _self, [&](auto& table) { // save the key for later use in decryption table.bob_keys[table.cards_dealt + 1] = key; table.cards_dealt = table.cards_dealt + 1; table.target = table.alice; if (table.cards_dealt == 4) // hardcoded pocket cards count (2 players with 2 pocket cards each) { // we dealt 2 cards to each player, starting betting round table.state = BET_ROUND; } }); } } else { // we're dealing table cards auto opponent_keys = (_self == table_it->alice) ? table_it->bob_keys : table_it->alice_keys; // check if the opponent has already sent their keys if (opponent_keys[table_it->cards_dealt + 1] == checksum256()) { // opponent is not ready yet datas.modify(table_it, _self, [&](auto& table) { // save the card key for later use if (_self == table.alice) { table.alice_keys[table_it->cards_dealt + 1] = key; } else { table.bob_keys[table_it->cards_dealt + 1] = key; } }); } else { // opponent has already given their key datas.modify(table_it, _self, [&](auto& table) { // save the card key for later use if (_self == table.alice) { table.alice_keys[table_it->cards_dealt + 1] = key; } else { table.bob_keys[table_it->cards_dealt + 1] = key; } // one more card is marked as dealt table.cards_dealt = table.cards_dealt + 1; if (table.cards_dealt < 7) // magic number 7 is `2(alice cards) + 2(bob cards) + 3 (flop cards)` { // flop was not fully dealt yet, waiting for more keys return; } else { // it's either flop, turn, or river // we don't burn card like they do in casinos, it has no effect on randomness // but we can burn it if we decide to table.state = BET_ROUND; table.target = table.target; // there's a little mess with turn order, but we have no more hackathon time to fix it } }); } } } //////////////////////// POKER GAME LOGIC METHODS //////////////////////////// /// @abi action void check(uint64_t table_id) { /* `check` (do not raise bet, do not fold cards) */ rounddatas datas(_self, _self); auto table_it = datas.find(table_id); assert(table_it != datas.end()); assert(table_it->state == BET_ROUND); assert(_self == table_it->target); // we can check only if bets are equal assert(table_it->alice_bet == table_it->bob_bet); if (_self == table_it->alice) { // first action, let the other one decide datas.modify(table_it, _self, [&](auto& table) { table.target = table.bob; }); } else { datas.modify(table_it, _self, [&](auto& table) { if (table.cards_dealt < 9) // magic number 9 is `2(alice cards) + 2(bob cards) + 3 (flop cards) + 1 (turn card) + 1 (river card)` { table.state = DEAL_TABLE; } else { // calculate winner! table.state = SHOWDOWN; } }); } } /// @abi action void call(uint64_t table_id) { /* `call` (raise bet to match opponent raised bet) */ rounddatas datas(_self, _self); auto table_it = datas.find(table_id); assert(table_it != datas.end()); assert(table_it->state == BET_ROUND); assert(_self == table_it->target); } /// @abi action void raise(uint64_t table_id, eosio::asset amount) { /* `raise` bet (no more than current player bankroll) */ rounddatas datas(_self, _self); auto table_it = datas.find(table_id); assert(table_it != datas.end()); assert(table_it->state == BET_ROUND); assert(_self == table_it->target); } /// @abi action void fold(uint64_t table_id) { /* `fold` (drop cards, stop playing current round) */ rounddatas datas(_self, _self); auto table_it = datas.find(table_id); assert(table_it != datas.end()); assert(table_it->state == BET_ROUND); assert(_self == table_it->target); } ///////////////////// DISPUTES & CHEATING DETECTION //////////////////// /// @abi action void dispute(uint64_t table_id) { /* Open cheating dispute. The disputing player has to stake total value of all bankrolls on the table. */ } /// @abi action void card_keys(uint64_t table_id, vector<checksum256> private_keys) { /* Receives all card encryption private keys from the player to check for cheating. */ } /// @abi action void dispute_step(uint64_t table_id, uint8_t step_idx) { /* Dispute a specific encryption step. For optimization only (players can do their calculation off-chain and then check just one). */ } ///////////////////// POKER HANDS EVALUATOR /////////////////////// bool hasFlag(int b1, int b2) { // should be bitwise operation return (b1 / b2) % 2 == 1; } int getSuit(int card) { // 0 = spades // 1 = clubs // 2 = hearts // 3 = diamonds return card / 13; } int getValue(int card) { // 0 = 2 // 1 = 3 // ... // 8 = 10 // 9 = J // 10 = Q // 11 = K // 12 = A return card % 13; } vector<int> selectCombination(int c0, int c1, int c2, int c3, int c4, int c5, int c6, int comb) { vector<int> select = vector<int>(); if (hasFlag(comb, 1)) select.push_back(c0); if (hasFlag(comb, 2)) select.push_back(c1); if (hasFlag(comb, 4)) select.push_back(c2); if (hasFlag(comb, 8)) select.push_back(c3); if (hasFlag(comb, 16)) select.push_back(c4); if (hasFlag(comb, 32)) select.push_back(c5); if (hasFlag(comb, 64)) select.push_back(c6); return select; } int getHighestCombination(int c0, int c1, int c2, int c3, int c4, int c5, int c6) { vector<int> cardCombinations = vector<int>{ 31, 47, 79, 55, 87, 103, 59, 91, 107, 115, 61, 93, 109, 117, 121, 62, 94, 110, 118, 122, 124 // magic numbers! (different permutations of a 7-card array on a 5-card hand) }; int max = 0; for (int i = 0; i < 21; i++) { auto combination = selectCombination(c0, c1, c2, c3, c4, c5, c6, cardCombinations[i]); int cc0 = combination[0]; int cc1 = combination[1]; int cc2 = combination[2]; int cc3 = combination[3]; int cc4 = combination[4]; int val = getCombinationValue(cc0, cc1, cc2, cc3, cc4); if (val > max) max = val; } return max; } int getCombinationValue(int c0, int c1, int c2, int c3, int c4) { int cv0 = getValue(c0); int cv1 = getValue(c1); int cv2 = getValue(c2); int cv3 = getValue(c3); int cv4 = getValue(c4); // Straight flushes if (isStraightFlush(c0, c1, c2, c3, c4, cv0, cv1, cv2, cv3, cv4)) return 1000000 + cv0 // orders straight flushes on highest card value (2,J,Q,K,A loses to 2,3,4,5,6) ; // Four of a kind // 5,A,A,A,A // K,A,A,A,A // 6,6,6,6,Q // 6,6,6,6,A if (isFourOfAKind(cv0, cv1, cv2, cv3, cv4)) return 900000 + 1000 * (cv2 + 1) // get one middle card (there's four of them) + (cv0 + cv4 - cv2) // kicker ; // Full Houses if (isFullHouse(cv0, cv1, cv2, cv3, cv4)) return 800000 + 1000 * (cv2 + 1) // get one middle card (it will always be the one we have 3 of) + (cv0 + cv4 - cv2) // this will be the one we have only 2 of ; // Flushes if (isFlush(c0, c1, c2, c3, c4)) return 700000 + 5 * cv4 // kickers + 4 * cv3 + 3 * cv2 + 2 * cv1 + 1 * cv0 ; // Straights if (isStraight(cv0, cv1, cv2, cv3, cv4)) return 600000 + cv4 // highest card ; // Three of a kind if (isThreeOfAKind(cv0, cv1, cv2, cv3, cv4)) return 500000 + 1000 * (cv2 + 1) // get one middle card (it will always be the one we have 3 of) + 5 * cv4 // kickers (their score will always be lower than main card, but will still help decide) + 4 * cv3 + 3 * cv2 + 2 * cv1 + 1 * cv0 ; // Two pair if (isTwoPairs(cv0, cv1, cv2, cv3, cv4)) return 400000 + 1000 * (cv3 + 1) // highest pair + 50 * (cv1 + 1) // lowest pair + (cv0 + cv2 + cv4 - cv1 - cv3) // voodoo magic! (calculating the kicker) ; // Pairs if (isPair(cv0, cv1, cv2, cv3, cv4)) return 300000 + getPairCoef(cv0, cv1, cv2, cv3, cv4) ; // High cards by rank return 5 * cv4 + 4 * cv3 + 3 * cv2 + 2 * cv1 + cv0; } int getPairCoef(int c0, int c1, int c2, int c3, int c4) { if (c0 == c1) return 1000 * (c0 + 1) + 5 * c4 + 4 * c3 + 3 * c2; if (c1 == c2) return 1000 * (c1 + 1) + 5 * c4 + 4 * c3 + 1 * c0; if (c2 == c3) return 1000 * (c2 + 1) + 5 * c4 + 2 * c1 + 1 * c0; if (c3 == c4) return 1000 * (c4 + 1) + 3 * c2 + 2 * c1 + 1 * c0; return 0; } bool isFourOfAKind(int c0, int c1, int c2, int c3, int c4) { // optimized version (cards are sorted by value already) if ((c0 == c1) && (c0 == c2) && (c0 == c3)) return true; if ((c4 == c1) && (c4 == c2) && (c4 == c3)) return true; return false; } bool isFullHouse(int c0, int c1, int c2, int c3, int c4) { // 5,5,9,9,9 if ((c0 == c1) // 2 of a kind && (c2 == c3) && (c2 == c4)) // 3 of a kind return true; // 6,6,6,K,K if ((c0 == c1) && (c0 == c2) // 3 of a kind && (c3 == c4)) // 2 of a kind return true; return false; } bool isFlush(int c0, int c1, int c2, int c3, int c4) { int suit = getSuit(c0); return (suit == getSuit(c1)) && (suit == getSuit(c2)) && (suit == getSuit(c3)) && (suit == getSuit(c4)) ; } bool isStraightSimple(int c0, int c1, int c2, int c3, int c4) { if (c0 != (c1 - 1)) return false; if (c0 != (c2 - 2)) return false; if (c0 != (c3 - 3)) return false; if (c0 != (c4 - 4)) return false; return true; } bool isStraight(int c0, int c1, int c2, int c3, int c4) { // 5,6,7,8,9 // 2,3,4,5,A // 10,J,Q,K,A // straights can't wrap around (2,3,4,K,A is not a straight) if (isStraightSimple(c0, c1, c2, c3, c4)) return true; if (c0 != 0) return false; if (c4 != 12) return false; if ((c1 == (c0 + 1)) && (c2 == (c0 + 2)) && (c3 == (c0 + 3))) return true; if ((c4 == (c3 + 1)) && (c4 == (c2 + 2)) && (c4 == (c1 + 3))) return true; return false; } bool isStraightFlush(int c0, int c1, int c2, int c3, int c4, int cv0, int cv1, int cv2, int cv3, int cv4) { return isFlush(c0, c1, c2, c3, c4) && isStraight(cv0, cv1, cv2, cv3, cv4); } // Three of a kind bool isThreeOfAKind(int c0, int c1, int c2, int c3, int c4) { if ((c0 == c1) && (c0 == c2)) return true; if ((c1 == c2) && (c1 == c3)) return true; if ((c2 == c3) && (c2 == c4)) return true; return false; } // Two pair bool isTwoPairs(int c0, int c1, int c2, int c3, int c4) { if (c0 == c1) // 2,2,3,3,4 or 2,2,3,4,4 return ((c2 == c3) || (c3 == c4)); if (c1 == c2) // 2,3,3,4,4 return (c3 == c4); return false; } // Pairs bool isPair(int c0, int c1, int c2, int c3, int c4) { return (c0 == c1) || (c1 == c2) || (c2 == c3) || (c3 == c4); } }; EOSIO_ABI( poker, (search_game)(cancel_game)(start_game)(deck_shuffled)(deck_recrypted)(card_key)(check)(call)(raise)(fold)(dispute)(card_keys)(dispute_step) )
true
6f1270f670d995a514630d412ce4be48f34067ae
C++
RanaRanvijaySingh/my_doc_exp
/ranvijay/c++/assign.cpp
UTF-8
8,756
3.046875
3
[]
no_license
#include <stdio.h> #include <string> #include <fstream> #include <iostream> using namespace std; int check_file_type(string name); void identify_class(string file); void find_methods(string file, int type); void correct_indentation(string filename,int type); int main() { int type=0; string filename; cout<<"Enter the file name :"; getline(cin,filename); type=check_file_type(filename); identify_class(filename); find_methods(filename,type); correct_indentation(filename,3); /* fp = fopen("read","r"); c = getc(fp) ; while (c!= EOF) { putchar(c); c = getc(fp); } fclose(fp); */ return 0; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~` //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~CORRECT INDENTATION OF THE PROGRAMMING FILES~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~` //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~` void correct_indentation(string filename,int type) { string line,word,word2; char c; fstream file(filename.c_str()); if(!file) { cout<<"file not found \n";return; } else { string s="__"; for(int i=0;file>>word;i++) { if((word.compare("class")==0)||(word.compare("def")==0)||(word.compare("if")==0)) { getline(file,line);s=s+s; file<<s;//INCOMPLETE AT THIS PART .. } if(word.compare("end")==0) { getline(file,line); s=s.length()-2; file<<s; } } } file.close(); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~` //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~IDENTIFY THE METHODS AND THE VARIABLES TYPE PRESENT~~~~~~~~~~~~~~~~~~~~~~~~~~~` //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~` void find_methods(string filename, int type) { string spec,dtype,fname; string word; char c;string next1; fstream file(filename.c_str()); if(!file) { cout<<"file not found \n";return; } else { switch(type) { //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~` //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~FOR THE JAVA FILES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~` //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~` case 1: cout<<"\n\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~properties~~~~~~~~~~~~~~~~~~~~~~\n"; for(int i=0;file>>spec;i++) { if((spec.compare("public")==0)||(spec.compare("private")==0)||(spec.compare("protected")==0)) { file>>dtype; if((dtype.compare("String")==0)||(dtype.compare("int")==0)||(dtype.compare("float")==0)||(dtype.compare("Long")==0)||(dtype.compare("void")==0)||(dtype.compare("Double")==0)) { file>>fname; string temp=fname; int flag=0,flag1=0; for(int j=0;j<temp.length();j++) { if(temp[j]=='(') flag=1; } if(flag==0){cout<<"variable :"<<fname<<"\t\tdate type :"<<dtype<<"\t\tspecifer :"<<spec<<endl;} else { string temp1=fname;string next; for(int j=0;j<temp1.length();j++) { if((temp1[j]=='(')&&(temp1[j+1]!=')')) flag1=1; } if(flag1==1) { file>>next;cout<<"\n\nthe function is : "<<fname<<" "<<next<<endl; } else cout<<"\n\nthe function is : "<<fname<<endl; } } } } file.close(); break; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~` //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~FOR THE PHP FILES~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~` //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~` case 2: for(int i=0;file>>word;i++) { if(word.compare("function")==0) { file>>fname; cout<<"\n\nthe function is : "<<fname<<endl; } if((word.compare("public")==0)||(word.compare("private")==0)||(word.compare("protected")==0)||(word.compare("var")==0)) { file>>next1; if(next1.compare("function")==0) { file>>fname;int flag1=0; string temp1=fname;string next; for(int j=0;j<temp1.length();j++) { if((temp1[j]=='(')&&(temp1[j+1]!=')')) flag1=1; } if(flag1==1) { file>>next;cout<<"\n\nthe function is : "<<fname<<" "<<next<<endl; } else cout<<"\n\nthe function is : "<<fname<<endl; } if(next1[0]=='$'&&next1[1]!='t') { cout<<"\nvariable : "<<next1<<endl; } } } file.close(); break; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~` //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~FOR THE RUBY FILES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~` //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~` case 3:for(int i=0;file>>word;i++) { if(word[0]=='@') { cout<<"\nvariable :"<<word<<endl; } if(word.compare("def")==0) { file>>fname; cout<<"\nfunction is : "<<fname<<endl; } } file.close(); break; } } } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~` //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~IDENTIFY THE CLASSES IN THE CALSS~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~` //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~` void identify_class(string filename) { string line; char c; fstream file(filename.c_str()); if(!file) { cout<<"file not found \n";return; } else { cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"; cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"; //cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"; string line,classname; for(int i=0;file>>line;i++) { if(line.compare("class")==0) { file>>classname; cout<<"the class name is : "<<classname<<"\n\n"<<endl; //cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"; } } } file.close(); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~` //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~IDENTIFY THE FILE TYPE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~` //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~` int check_file_type(string name) { string file_type;int c=0,flag=0; int size; fstream file(name.c_str()); if(!file) { cout<<"file not found \n";return 0; } else { for(int i=0;i<name.length();i++) { if(name[i]=='.') { flag=1; for(int j=i+1;j<name.length();j++) file_type=file_type+name[j]; size=file_type.length(); } if(flag==1)break; } if(file_type.compare("java")==0) { cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"; cout<<"IT'S A JAVA FILE\n"; cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"; return 1; } else if(file_type.compare("php")==0) { cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"; cout<<"IT'S A PHP FILE\n"; cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"; return 2; } else if(file_type.compare("cpp")==0) { cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"; cout<<"IT'S A c++ FILE\n"; cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"; return 4; } else if(file_type.compare("rb")==0) { cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"; cout<<"IT'S A RUBY FILE\n"; cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"; return 3; } else if(file_type[size-1]=='p') { cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"; cout<<"IT'S A PHP FILE\n"; cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"; return 2; } else { cout<<"file not identified it does not have any extension.\n"; return 0; } } }
true
9f2c1c3ce4113369eb0367d9d8769b8af562cfe1
C++
fish-ball/acm.zju.edu.cn
/17XX/zoj.1766.src.1.cpp
GB18030
1,176
2.921875
3
[]
no_license
// 1788059 2009-03-13 22:51:21 Accepted 1766 C++ 0 184 ͵ // 򵥵ַע⣺Words consist of the characters {a-z,A-Z,0-9}. Words are separated by whitespace, end-of-line, and punctuation. #include <iostream> #include <string> #include <algorithm> #include <map> #include <vector> using namespace std; map<string, int> MP; int cnt = 0; vector<string> V; int main() { string s; while(cin >> s) { while(ispunct(s[s.size()-1])) s.erase(s.size()-1); while(ispunct(s[0])) s.erase(0, 1); for(int i = 0; i < s.size(); ++i) s[i] = tolower(s[i]); for(int i = 0; i < s.size(); ++i) { if(ispunct(s[i])) { MP[s.substr(0, i)]++; s.erase(0, i + 1); } } MP[s]++; } for(map<string, int>::iterator it = MP.begin(); it != MP.end(); ++it) { if(it->second < cnt) continue; if(it->second > cnt) V.clear(); cnt = it->second; V.push_back(it->first); } sort(V.begin(), V.end()); cout << cnt << " occurrences" << endl; for(int i = 0; i < V.size(); ++i) cout << V[i] << endl; }
true
51eeb02aa661c62844d3efffca55b8285ceadd71
C++
jobhope/TechnicalNote
/code/FactoryMethod.cpp
UTF-8
2,059
3.515625
4
[ "MIT" ]
permissive
#include<iostream> #include<memory> #include<string> class Drink { public: virtual ~Drink() = default; virtual std::string getName() const = 0; }; class Coffee : public Drink { std::string getName() const override { return "커피"; } }; class Coke : public Drink { std::string getName() const override { return "콜라"; } }; class Cocoa : public Drink { std::string getName() const override { return "코코아"; } }; enum class DrinkType { Coffee, Coke, Cocoa }; class DrinkFactory { public: virtual ~DrinkFactory() = default; virtual std::unique_ptr<Drink> Create() const = 0; }; class CoffeeFactory : public DrinkFactory { public: std::unique_ptr<Drink> Create() const override { return std::make_unique<Coffee>(); } }; class CokeFactory : public DrinkFactory { public: std::unique_ptr<Drink> Create() const override { return std::make_unique<Coke>(); } }; class CocoaFactory : public DrinkFactory { public: std::unique_ptr<Drink> Create() const override { return std::make_unique<Cocoa>(); } }; class VendingMachine final { public: VendingMachine(std::unique_ptr<DrinkFactory>&& drinkFactory) : drinkFactory_(std::move(drinkFactory)) {} void Create(std::unique_ptr<DrinkFactory>&& creator) { drinkFactory_ = std::move(creator); } void PrintDrinkName() const { std::cout << "Maked drink's name : " << drinkFactory_->Create()->getName() << std::endl; std::cout << std::endl; } private: std::unique_ptr<DrinkFactory> drinkFactory_; }; int main() { VendingMachine vendingMachine(std::make_unique<CoffeeFactory>()); std::cout << "==== Vending Machine Factory ====" << std::endl; vendingMachine.PrintDrinkName(); vendingMachine.Create(std::make_unique<CokeFactory>()); vendingMachine.PrintDrinkName(); vendingMachine.Create(std::make_unique<CocoaFactory>()); vendingMachine.PrintDrinkName(); return 0; }
true
bfbfa05f26ab60b8967eba2c3b2123a72cd0ef6e
C++
Alpha0531/Peliculas
/Serie.cpp
UTF-8
653
3.046875
3
[]
no_license
#include "Serie.h" //Constructores Serie::Serie(){ int id = 0; string Nombre = ""; int numCap=0; } Serie::Serie(int id,string Nombre, string genero, int numCap){ this->id = id; this->Nombre=Nombre; this->numCap=numCap; } //Getter int Serie::getIdS(){ return id; } string Serie::getNombre(){ return Nombre; } int Serie::getNumCap(){ return numCap; } string Serie::getGenero(){ return genero; } //Setters void Serie::setIdS(int id){ this -> id = id; } void Serie::setEp(Episodio ep, int h){ listE[h]=ep; } //Virtual void Serie::mostrarId(){ cout<<"El id de la serie es: "<<getIdS()<<endl; }
true
01912fe295b9b2300103f4a6a26d043fcec2e7cb
C++
p15-git-acc/code
/semaphores/sem_make.cpp
UTF-8
514
2.90625
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <fcntl.h> #include <semaphore.h> int main(int argc, char **argv) { if(argc!=3) { printf("Usage:- sem_make <sem_name> <no_resources>\n"); exit(1); } sem_t *this_sem=sem_open(argv[1],O_CREAT,S_IRUSR|S_IWUSR,atoi(argv[2])); if(this_sem==SEM_FAILED) { printf("Failed to create semaphore %s with %d resources.\n",argv[1],atoi(argv[2])); perror("Error reported was: "); exit(1); } exit(0); }
true
fb3bb7c4f8579c309aef593d2062d1e49e7b4ecc
C++
njumathdy/code-practice
/Leetcode/746_Min Cost Climbing Stairs/c++/solution.cpp
UTF-8
1,074
3.5
4
[]
no_license
/******************* On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed). Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1. *******************/ #include <cstdlib> #include <cstdio> #include <exception> #include <vector> #include <algorithm> #include <string> #include <iostream> using namespace std; class Solution { public: int minCostClimbingStairs(vector<int>& cost) { if(cost.empty()) return 0; if(cost.size() == 1) return cost[0]; if(cost.size() == 2) return min(cost[1], cost[2]); int n = cost.size(); vector<int> dp(n, 0); dp[n-1] = cost[n-1]; dp[n-2] = cost[n-2]; for(int i = n-3; i >= 0; --i) { dp[i] = cost[i] + min(dp[i+1], dp[i+2]); } return min(dp[0], dp[1]); } }; int main() { return 0; }
true
23f76a7ac5003dbb962f648ca9915e2864c2c06d
C++
BinyuHuang-nju/leetcode-implement
/all123/all123/main.cpp
UTF-8
3,246
3.109375
3
[]
no_license
#include <iostream> using namespace std; #include <vector> class Solution1 //190/120 { public: int maxProfit(vector<int>& prices) { if (prices.size() < 2) return 0; int i = 0, j; vector<int> choose; while (i < prices.size() - 1) { j = i; while (j < prices.size() - 1 && prices[j + 1] >= prices[j]) j++; if (i < j) { choose.push_back(prices[j] - prices[i]); } i = j + 1; } if (choose.size() == 0) return 0; if (choose.size() == 1) return choose[0]; if (choose.size() == 2) return choose[0] + choose[1]; int max = 0; for (i = 0; i < 2; i++) { max = i; for (j = i + 1; j < choose.size(); j++) { if (choose[j] > choose[max]) max = j; } if (max != i) { int temp = choose[i]; choose[i] = choose[max]; choose[max] = temp; } } return choose[0] + choose[1]; } }; class Solution1 //pass { private: int max(int x, int y) { return x > y ? x : y; } int min(int x, int y) { return x < y ? x : y; } public: int maxProfit(vector<int>& prices) { if (prices.size() < 2) return 0; vector<int> dp1(prices.size(), 0); vector<int> dp2(prices.size(), 0); int minval = prices[0], maxval = prices[prices.size() - 1]; for (int i = 1; i < prices.size(); i++) { dp1[i] = max(dp1[i - 1], prices[i] - minval); minval = min(minval, prices[i]); } for (int i = prices.size() - 2; i >= 0; i--) { dp2[i] = max(dp2[i + 1], maxval - prices[i]); maxval = max(maxval, prices[i]); } int max = dp1[0] + dp2[0]; for (int i = 1; i < prices.size(); i++) if (max < dp1[i] + dp2[i]) max = dp1[i] + dp2[i]; return max; } }; class Solution { //pass private: int max(int x, int y) { return x > y ? x : y; } int max(int x, int y, int z) { int m = x > y ? x : y; return m > z ? m : z; } public: int maxProfit(vector<int>& prices) { if (prices.size() < 2) return 0; vector<vector<vector<int>>> dp\ (prices.size(), vector<vector<int>>(3, vector<int>(2, 0))); int i, j, k; for (i = 0; i < 3; i++) { dp[0][i][0] = 0; dp[0][i][1] = -prices[0]; } for (i = 1; i < prices.size(); i++) { for (j = 0; j < 3; j++) { if (j == 0) dp[i][j][0] = dp[i - 1][j][0]; else dp[i][j][0] = max(dp[i - 1][j][0], dp[i - 1][j - 1][1] + prices[i]); dp[i][j][1] = max(dp[i - 1][j][1], dp[i - 1][j][0] - prices[i]); } } return max(dp[prices.size() - 1][0][0], dp[prices.size() - 1][1][0], dp[prices.size() - 1][2][0]); } }; int main() { vector<int> a = { 1,2,4,2,5,7,2,4,9,0 }; Solution sol; cout << sol.maxProfit(a); return 0; }
true
5c180b198219e3b46fda8f5c5bb76c55085c791e
C++
Suryavf/CameraCalibration
/Patron/structures.cpp
UTF-8
1,269
3.078125
3
[]
no_license
#include "structures.h" /* * Class Vect * ================================================= */ void Vect::module(float &m){ m = x*x + y*y; } T Vect::module(){ return x*x + y*y; } void Vect::norm(T &m){ m = std::sqrt(x*x + y*y); } T Vect::norm(){ return std::sqrt(x*x + y*y); } void Vect::dot(const Vect& p, T &prod){ prod = this->x*p.x + this->y*p.y; } T Vect::dot(const Vect& p){ return this->x*p.x + this->y*p.y; } /* * Class Point * ================================================= */ void Pt::distance(const Pt& p, T &d){ T a = this->x - p.x; T b = this->y - p.y; d = std::sqrt( a*a + b*b ); } T Pt::distance(const Pt& p){ T a = this->x - p.x; T b = this->y - p.y; return std::sqrt( a*a + b*b ); } /* * Class Line * ================================================= */ void Line::eval(const Pt &p, T &v){ v = p.x*x_coef + p.y*y_coef + bias; } T Line::eval(const Pt &p){ return p.x*x_coef + p.y*y_coef + bias; } /* * Distance Line to Point * ---------------------- * |L(p)| * d(L,p) = ------ * ||w|| */ void distance(Pt &p, Line &l, T &d){ if (p.check) d = abs( l.eval(p) ); // w = 1 else d = std::numeric_limits<T>::max(); }
true
b8ddf7b8aae2287ba4f339c57bfddf21f0e43510
C++
hldnwrght/Calculator_1_Using_Design_Patterns
/Evaluate_Postfix.cpp
UTF-8
355
2.640625
3
[]
no_license
//This holds the code for evaluate postix #include <iostream> #include "Evaluate_Postfix.h" //Function that iterates over the given array until empty and executes the command bool Evaluate_Postfix::evaluate_postfix(Array_Iterator<Expr_Command*> & iter) { for (; !iter.is_done(); iter.advance()) { (*iter)->execute(); } return true; }
true
fabd685d14c4c3c4dd218308c84a858c146385aa
C++
Rabbidon/project-euler
/euler013/largeSum.cpp
UTF-8
977
3.703125
4
[]
no_license
#include <iostream> #include <cmath> using namespace std; //We are given a sum of 100 50-digit numbers and are asked to calculate the first 10 digits. //This solution represents each number as digit arrays and adds each place in the number separately //It first adds on the 10 entries of least value, and then works its way up, adding the next solution //and dividing by 10 (place shifting) until it runs out of input. The first 10 digits can easily be read from the output. int main(int argc, char** argv){ string str(argv[1]); int sumArray [50] = {}; for (int i = 0; i < 100; i++){ for (int j = 0; j < 50; j++){ sumArray [j] += str[j+i*50] - '0'; cout << str[j+i*50] - '0' << endl; } } int digits = 10; long result = 0; for (int a = 0; a < digits; a++){ result += sumArray[49 - a]*pow(10,a); } cout << result << endl; for (int b = digits; b < 50 ; b++){ result += sumArray[49 - b]*pow(10,digits); result = result/10; } cout << result << endl; }
true
5eb062acf0c607de280d3d1af2731f76d7106350
C++
Adriments/Relearning-CppBasics
/Relearning CppBasics/Episode2.cpp
UTF-8
167
2.515625
3
[]
no_license
/* #include <iostream> using namespace std; int main() { //Every Cpp program needs a main function. Compiler looks for it. cout << "Hello World!"; return 0; } */
true
bba071f02c6f04df51afeab0fa594b0b18e44cd2
C++
preetisoni123/Tree
/bottomView.cpp
UTF-8
2,265
3.828125
4
[]
no_license
/* We need to do level order traversal starting root. Then keep putting node values in the vector based on its horizontal distance from root. 20 / \ 8 22 / \ \ 5 3 25 / \ 10 14 For the above tree, the bottom view is 5 10 3 14 25. */ #include <iostream> #include <vector> #include <queue> #include <tuple> using namespace std; class Node { public: int data; Node* left; Node* right; Node(int val): data(val), left(NULL), right(NULL) {} }; void getWidth(Node* n, int& wl, int& wr, int curr) { if(!n) return; if(wl > curr) { wl = curr; //cout << wl << "wl" << curr << " "; } if(wr < curr) { wr = curr; //cout << wr << "wr" << curr << " "; } if(n->left) { //curr--; getWidth(n->left, wl, wr, curr - 1); } //curr++; if(n->right) { //curr++; getWidth(n->right, wl, wr, curr + 1); } } void getBottomView(Node* node, vector<int>& v, int wl, int wr, int w) { vector<int>::iterator it = v.begin(); queue<pair<Node*, int>> q; if(!node) return; q.push(make_pair(node, 0)); while(!q.empty()) { Node* n; int wd; tie(n, wd) = q.front(); q.pop(); v[wd-wl] = n->data; if(n->left) q.push(make_pair(n->left, wd - 1)); if(n->right) q.push(make_pair(n->right, wd + 1)); } return; } vector<int> bottomView(Node* root) { vector<int> v; if(!root) return v; int wl = 0, wr = 0; getWidth(root, wl, wr, 0); //cout << wl << ":" << wr << "=" << wr - wl << endl; v.insert(v.begin(), wr- wl + 1, 0); getBottomView(root, v, wl, wr, 0); return v; } int main() { //Node *root = NULL; Node* root = new Node(20); root->left = new Node(10); root->right = new Node(30); root->left->right = new Node(15); root->left->right->right = new Node(25); root->right->right = new Node(5); vector<int> v = bottomView(root); for(int i: v) cout << i << " "; cout << endl; }
true
4c838f5d65b39421f56e79b9b235f6491b63d732
C++
levicode/mystl
/SqStack.h
GB18030
632
3.65625
4
[]
no_license
#pragma once typedef int ElemType; //˳ջԪ class SqStack { public: SqStack(int size); //캯 ~SqStack(); // int Length(); //ȡ˳ջij bool Empty(); //ж˳ջǷΪ bool Push(ElemType element); //ջѹһԪelement bool Pop(ElemType &element); //ջȡһԪطظelement bool GetTop(ElemType &element); //ȡջԪطظelement void Clear(); //ջ bool Traversal(); //ջ private: ElemType *sqstack; //˳ջԪ int top; //ջָ int SIZE; //˳ջ };
true
2918494336831d0c6085816c6ca3ec154310d50d
C++
maxschau/IINI4003-CPP-for-programmerere
/Oving3/Circle.h
UTF-8
389
2.90625
3
[]
no_license
// // Created by Max Torre Schau on 26/08/2020. // #ifndef OVING3_CIRCLE_H #define OVING3_CIRCLE_H const double pi = 3.141592; class Circle { public: Circle(double radius_); //Changed from lower-case to Upper-case C double get_area() const; double get_circumference() const; private: //Moved private to its own line double radius; }; #endif //OVING3_CIRCLE_H
true
cb1fc7ce76f0fd130b72b4e9f761d48c9e5055ef
C++
isaigm/leetcode
/missing-number/Accepted/3-3-2021, 3_37_44 PM/Solution.cpp
UTF-8
306
3.15625
3
[]
no_license
// https://leetcode.com/problems/missing-number class Solution { public: int missingNumber(vector<int>& nums) { int n = nums.size(); int s1 = n * (n + 1) / 2; int s2 = 0; for(const auto &j: nums) { s2 += j; } return s1 - s2; } };
true
1779a282914d5a616fe964612faa5f53a04d0bfb
C++
JaeJang/COMP_3512_Lab5
/RPNCalculator/RPNCalculator/RPNCalculator.cpp
UTF-8
1,369
3.640625
4
[]
no_license
#include "RPNCalculator.hpp" #include <iostream> #include <string> #include <sstream> //Decide operation type //PRE : parameter should be one of +,-,* and / //RETURN: matched class Operation * RPNCalculator::operation_type(char operation) { if (operation == AdditionOperation::OPERATION_CODE) return new AdditionOperation; else if (operation == SubstractionOperation::OPERATION_CODE) return new SubstractionOperation; else if (operation == MultiplicationOperation::OPERATION_CODE) return new MultiplicationOperation; else return new DivisionOperation(); } //Perform main feature //PRE : one of 4classes need to be passed //POST : take top 2elements out // push calculated result into the stack void RPNCalculator::perform(Operation * operation) { int top1 = stack.top(); stack.pop(); int top2 = stack.top(); stack.pop(); stack.push(operation->perform(top2, top1)); } //Process passed formula //PRE : well formatted formula is needed //POST : tokenize the formula and push them into stack and calculate //RETURE: final value int RPNCalculator::process_formula(std::string formula) { std::istringstream iss(formula); std::string operand; while (iss >> operand) { std::istringstream iss2(operand); int temp; if (iss2 >> temp) { stack.push(temp); } else { perform(operation_type(operand[0])); } } return stack.top(); }
true
473665f70d80adc72e2ec01673dfe69e33b4d78e
C++
tiggersworth/huffman_coding
/encode.hpp
UTF-8
1,284
2.859375
3
[]
no_license
/*** * File: encode.hpp * Author: Tammy Chang */ #ifndef ENCODE_HPP #define ENCODE_HPP #include "a6.hpp" #include <string> // IMPLEMENT FUNCTION ENCODE BELOW // THIS FUNCTION IS USED BY EXTRA CHALLENGE PROGRAM a6e // ONLY IF YOU GET 100 FOR a6 YOU WILL BE TESTED ON a6e struct value_count{ char value; std::string count; }; void dfs ( bnode<symbol>* root, std::string seq, std::vector<value_count>& vc){ if (root->left == nullptr && root->right == nullptr){ //os << root->value.value << " " << seq ; value_count thing; thing.value = root->value.value; thing.count = seq; vc.push_back(thing); return; // print entire value } std::string temp = seq; seq = seq + "0"; dfs( root->left, seq, vc); seq = temp; seq = seq + "1"; dfs( root->right, seq, vc); } std::string encode(const std::string& M, bnode<symbol>* root){ std::vector<value_count> vc; std::string str1; std::string ans; dfs (root, str1, vc); for(int i =0; i < M.size(); i++){ // through string for(int a = 0; a < vc.size(); a++){ //through vector if( M[i] == vc[a].value) { ans =ans + vc[a].count; } //std::cout << ans <<std::endl; } // std::cout << ans << std::endl; } return ans; std::cout << ans << std::endl; //return ans; } #endif // ENCODE_HPP
true
db0f0b8558fe4cf7d995d100d7b2bac4574059a4
C++
aernesto/moodbox_aka_risovaska
/velasquez/mousedrawingelement.h
UTF-8
1,511
2.75
3
[ "CC-BY-4.0", "MIT" ]
permissive
#ifndef MOUSEDRAWINGELEMENT_H #define MOUSEDRAWINGELEMENT_H #include "drawingelement.h" namespace Velasquez { // Basic mouse drawing element class class MouseDrawingElement : public DrawingElement { public: enum Settings {PenColor, PenTransparency, PenWidth}; public: MouseDrawingElement(QGraphicsItem *parent = 0); virtual QRectF boundingRect() const; virtual void setSetting(qint32 id, const QVariant &value); virtual QVariant getSetting(qint32 id) const; virtual QList <qint32> getSettingsList() const; virtual bool isSettingReversible(qint32 id) const; // Drawing process virtual void startDrawing(); virtual void addPoint(const QPointF &point) = 0; virtual void finishDrawing(); protected: // Current color QColor currentColor; // Current alpha qreal currentAlpha; // Current width qreal currentWidth; // Bounding rect QRectF rect; // Update total rect after adding of new point virtual void updateRect(const QRectF &pointRect); // Mouse drawing element settings virtual void setColor(const QColor &color); inline virtual bool hasColor() const { return true; }; virtual void setAlpha(qreal alpha); inline virtual bool hasAlpha() const { return true; }; virtual void setWidth(qreal width); inline virtual bool hasWidth() const { return true; }; // Drawing process control inline bool isDrawingNow() const { return drawingNow; }; private: bool drawingNow; }; } #endif // MOUSEDRAWINGELEMENT_H
true
187dc8541423f2f1e2a24676f17362bafb850307
C++
myuaggie/myuaggie1
/practice5.8(有注释.cpp
UTF-8
1,550
3.09375
3
[]
no_license
#include <iostream> #include <string> #include <fstream> #include <vector> #include <map> using namespace std; int main() { string fileName; fstream f; cout << "Input file name?"; //open file cin >> fileName; f.open(fileName); while (!f.is_open()) { cout << "Unable to open that file.Try again." << endl; cout << "Input file name? "; cin >> fileName; f.open(fileName); } int n; //get n-letter cout << "Number of letters of suffix?"; cin >> n; map<string, int> m; //get map like <suffix,count> string line; while (f >> line) { if (line.size() < n) continue; m[line.substr(line.size() - n, n)]++; } vector<string> member; vector<int> value; for (map<string, int>::iterator k = m.begin(); k != m.end(); k++) { member.push_back((*k).first); value.push_back((*k).second); } string temp1; int temp2; for (int idx = 0; idx < member.size() - 1; idx++) { //bubble sort for (int idx2 = 0; idx2 < member.size() - 1 - idx; idx2++) { if (value[idx2] > value[idx2 + 1]) { temp1 = member[idx2]; member[idx2] = member[idx2 + 1]; member[idx2 + 1] = temp1; temp2 = value[idx2]; value[idx2] = value[idx2 + 1]; value[idx2 + 1] = temp2; } } } for (int i = member.size() - 1; i > member.size() - 11; i--) { //print top 10 cout << member[i] << ":" << m[member[i]] << endl; } string suffix: cout << "input the suffix:"; cin >> suffix; while (cin) { cout << m[suffix] << endl; cout << "input the suffix:"; cin >> suffix; } cin.get(); cin.get(); return 0; }
true
2c9dfa30928fb3b58533fd7036f1983fde73b06a
C++
TrungKenbi/BaiTap-CSLT
/34.cpp
UTF-8
319
3
3
[]
no_license
#include<iostream> #include<cmath> using namespace std; int main() { int i, n; float S; do { cout<<"\nNhap n(n >= 1): "; cin>>n; if(n < 1) { cout<<"\nn phai >= 1. Xin nhap lai !"; } }while(n < 1); i = 1; S = 0; while(i <= n) { S = sqrt(i + S); i++; } cout<<"\nTong S = %f"<<S; return 0; }
true
6857cd5b05953581232b02dbcacbc359362b7855
C++
ggyool/study-alone
/ps/boj_cpp/1212.cpp
UTF-8
626
3.03125
3
[]
no_license
#include <iostream> #include <string> using namespace std; string s; const string arr[8] = { "000", "001", "010", "011", "100", "101", "110", "111" }; int main(void){ ios_base::sync_with_stdio(false); cin.tie(0); cin >> s; int slen = s.size(); int i=0; if(s[0] == '0') { cout << 0 ; return 0; } else if('1' <= s[0] && s[0] <='3'){ if(s[0] == '1') cout << "1"; if(s[0] == '2') cout << "10"; if(s[0] == '3') cout << "11"; i = 1; } for(; i<slen; ++i){ cout << arr[s[i] - '0']; } return 0; }
true