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
f1eade793d4a25b1dd5119f01ba78ce1de4bdbdb
C++
dawidjk/naive_bayes
/Naive Bayes/Naive Bayes/ImageTesting.cpp
UTF-8
2,873
2.9375
3
[]
no_license
// // ImageTesting.cpp // Naive Bayes // // Created by David Kluszczynski on 3/26/19. // Copyright © 2019 David Kluszczynski. All rights reserved. // #include "Catch2.hpp" #include "Image.hpp" #include "ImageSet.hpp" #include "FileIO.hpp" #include <string> TEST_CASE( "Read Image Successfully", "[Image]" ) { FileIO file_io; file_io.OpenFileRead("/Users/dave07747/Documents/CS126/naivebayes-dawidjk/digitdata/trainingimages"); std::string image_arr[28]; for (int i = 0; i < IMAGE_SIZE; ++i) { image_arr[i] = file_io.ReadLine(); } Image image; image.LoadImage(image_arr, true); REQUIRE((char) image.GetValue(8, 11) == '#'); } TEST_CASE( "Load Set Successfully", "[Image]" ) { FileIO file_io; std::string file = "/Users/dave07747/Documents/CS126/naivebayes-dawidjk/digitdata/trainingimages"; file_io.OpenFileRead(file); std::string image_arr[28]; for (int i = 0; i < IMAGE_SIZE; ++i) { image_arr[i] = file_io.ReadLine(); } Image image; image.LoadImage(image_arr, true); ImageSet image_set; image_set.LoadSet(file, true); REQUIRE(image.GetValue(8, 11) == image_set.GetImageAt(0).GetValue(8, 11)); } TEST_CASE( "Load Descriptor Successfully", "[Image]" ) { FileIO file_io; std::string file = "/Users/dave07747/Documents/CS126/naivebayes-dawidjk/digitdata/traininglabels"; file_io.OpenFileRead(file); int descriptor = file_io.ReadInt(); ImageSet image_set; image_set.LoadDescriptors(file); REQUIRE(descriptor == image_set.GetDescriptorAt(0)); } TEST_CASE( "Check Set Size Correctly", "[Image]" ) { std::string file_path = "/Users/dave07747/Documents/CS126/naivebayes-dawidjk/digitdata/training"; ImageSet image_set; image_set.LoadSet(file_path + "images", true); image_set.LoadDescriptors(file_path + "labels"); REQUIRE(image_set.Size() == 5000); } TEST_CASE( "Check Image Size Correctly", "[Image]" ) { std::string file_path = "/Users/dave07747/Documents/CS126/naivebayes-dawidjk/digitdata/training"; ImageSet image_set; image_set.LoadSet(file_path + "images", true); REQUIRE(image_set.ImageSetSize() == 5000); } TEST_CASE( "Check Descriptor Size Correctly", "[Image]" ) { std::string file_path = "/Users/dave07747/Documents/CS126/naivebayes-dawidjk/digitdata/training"; ImageSet image_set; image_set.LoadDescriptors(file_path + "labels"); REQUIRE(image_set.DescriptorSize() == 5000); } TEST_CASE( "Check Dim Mismatched", "[Image]" ) { std::string file_path = "/Users/dave07747/Documents/CS126/naivebayes-dawidjk/digitdata/"; ImageSet image_set; image_set.LoadSet(file_path + "trainingimages", true); image_set.LoadDescriptors(file_path + "testlabels"); REQUIRE(image_set.Size() == MISMATCHED_DIM); }
true
cdfaa0e0b161542eb8313369ef49ea19af45bbc9
C++
LPD-EPFL/consensusinside
/protocols/tpc/T_Reply.h
UTF-8
4,352
2.6875
3
[ "MIT" ]
permissive
#ifndef _T_Reply_h #define _T_Reply_h 1 #include "types.h" #include "libbyz.h" #include "T_Message.h" #include "Digest.h" class T_Principal; class T_Rep_info; // // T_Reply messages have the following format. // struct T_Reply_rep : public T_Message_rep { View v; // current view Request_id rid; // unique request identifier //Digest rh_digest; // digest of reply. int replica; // id of replica sending the reply int reply_size; // if negative, reply is not full. int cid; // Followed by a reply that is "reply_size" bytes long and // a MAC authenticating the reply to the client. The MAC is computed // only over the Reply_rep. Replies can be empty or full. Full replies // contain the actual reply and have reply_size >= 0. Empty replies // do not contain the actual reply and have reply_size < 0. }; class T_Reply : public T_Message { // // T_Reply messages // public: T_Reply(); T_Reply(T_Reply_rep *r); T_Reply(View view, Request_id req, int replica, T_Principal *p, int cid); virtual ~T_Reply(); View view() const; // Effects: Fetches the view from the message Request_id request_id() const; // Effects: Fetches the request identifier from the message. int cid() const; // Effects: Fetches the identifier of the client who issued the request this message is in response to. //Digest &request_history_digest() const; // Effects : Fetches the request-history digest from the message int& reply_size(); // Return the reply size bool full() const; // Effects: Returns true iff "this" is a full reply. int id() const; // Effects: Fetches the reply identifier from the message. void set_id(int id); // Effects: Sets the reply identifier to id. bool verify(); // Effects: Verifies if the message is authenticated by rep().replica. bool match(T_Reply *r); // Effects: Returns true if the replies match. static bool convert(T_Message *m1, T_Reply *&m2); // Effects: If "m1" has the right size and tag of a "T_Reply", casts // "m1" to a "T_Reply" pointer, returns the pointer in "m2" and // returns true. Otherwise, it returns false. Convert also trims any // surplus storage from "m1" when the conversion is successfull. char *reply(int &len); char *store_reply(int &max_len); // Effects: Returns a pointer to the location within the message // where the reply should be stored and sets "max_len" to the number of // bytes available to store the reply. The caller can copy any reply // with length less than "max_len" into the returned buffer. private: T_Reply_rep &rep() const; // Effects: Casts "msg" to a T_Reply_rep& friend class T_Rep_info; //Added by Maysam Yabandeh //TODO: Clean this dirty imprivization //friend class T_Replica; }; inline T_Reply_rep& T_Reply::rep() const { th_assert(ALIGNED(msg), "Improperly aligned pointer"); return *((T_Reply_rep*)msg); } inline View T_Reply::view() const { return rep().v; } inline Request_id T_Reply::request_id() const { return rep().rid; } inline int T_Reply::id() const { return rep().replica; } inline void T_Reply::set_id(int id) { rep().replica = id; } inline int T_Reply::cid() const { return rep().cid; } //inline Digest& T_Reply::request_history_digest() const //{ //return rep().rh_digest; //} inline int& T_Reply::reply_size() { return rep().reply_size; } inline bool T_Reply::full() const { return rep().reply_size >= 0; } inline bool T_Reply::match(T_Reply *r) { if ((r->reply_size() < 0) || (reply_size() < 0)) { return true; } bool toRet = ( //(request_history_digest() == r->request_history_digest()) && (rep().v == r->rep().v) && (rep().cid == r->rep().cid) && (rep().rid == r->rep().rid) && ((r->reply_size() < 0) || (reply_size() < 0) )); //fprintf(stderr, "Reply::match [%u,%u,%u,%u]==[%u,%u,%u,%u] && [%u,%u,%u,%u]==[%u,%u,%u,%u]\n", d1.udigest()[0], d1.udigest()[1], d1.udigest()[2], d1.udigest()[3] //, d2.udigest()[0], d2.udigest()[1], d2.udigest()[2], d2.udigest()[3] //, d3.udigest()[0], d3.udigest()[1], d3.udigest()[2], d3.udigest()[3] //, d4.udigest()[0], d4.udigest()[1], d4.udigest()[2], d4.udigest()[3]); if (toRet) { // fprintf(stderr, "reply_match returning true\n"); return true; } // fprintf(stderr, "reply_match returning false\n"); return false; } #endif // _Reply_h
true
a4cd8778603458370c293139114c79851425867c
C++
yogeshg/small-projects
/lc/p131.cpp
UTF-8
1,935
3.375
3
[]
no_license
#include<iostream> #include<vector> #include<string> #include<cstring> class Solution { public: std::vector<std::vector<std::string>> partitionRec(const char* cstr, int len, std::vector<std::string>partSolution ) { std::vector<std::vector<std::string>> result; if( len<=0 ) { result.push_back( partSolution ); return result; } std::vector<int> palinCandidates ; int palinLen; for(palinLen=1; palinLen<=len; ++palinLen) { //std::cout<<"trying for len:"<<len<<" palinLen:"<<palinLen; bool isPalin = true; for( int i=0; i<palinLen/2 && isPalin; ++i ) { isPalin &= cstr[i]==cstr[palinLen-i-1]; } //std::cout<<" isPalin:"<<isPalin<<"\n"; if(isPalin){ palinCandidates.push_back(palinLen); } } for(auto c : palinCandidates) { char* buff = new char[c+1]; std::strncpy(buff, cstr, c); buff[c] = '\0'; partSolution.push_back( buff ); for(auto sol:partitionRec(cstr+c, len-c, partSolution)) { result.push_back(sol); } partSolution.pop_back(); } return result; } std::vector<std::vector<std::string>> partition(std::string s) { const int len = s.length(); std::vector<std::string> partSolution; return partitionRec(s.c_str(), len, partSolution); } }; int main(int argc, char** argv) { Solution s; for( std::vector<std::string> v : s.partition(argv[1]) ) { for(std::string st : v) { std::cout << st << " "; } std::cout << "\n"; } return 0; }
true
88fac527c478d0e25fd59c5a891d8b5b0e760eca
C++
ab-dragon/workshop_oct2018
/need_for_speed/need_for_speed/test_perf.cpp
UTF-8
1,103
3.234375
3
[]
no_license
#include <utility> #include <chrono> #include <iostream> #include <vector> struct Point { std::vector<double> v; double x; double y; }; Point go_left(const Point& p) { Point tmp; tmp.x = p.x + 1; tmp.y = p.y; tmp.v = p.v; return tmp; } Point go_up(const Point& p) { Point tmp; tmp.x = p.x; tmp.y = p.y + 1; tmp.v = p.v; return tmp; } //Point go_left(Point&& p) { // p.x++; // return std::move(p); //} //Point go_up(Point&& p) { // p.y++; // return std::move(p); //} using namespace std::chrono; int main() { auto ten_million = 100000000; high_resolution_clock::time_point t1 = high_resolution_clock::now(); Point P3; P3.x = 0; P3.y = 0; P3.v.resize(200); for (unsigned i = 0; i < ten_million; i++) { P3 = go_left(go_up(go_left(P3))); } high_resolution_clock::time_point t2 = high_resolution_clock::now(); auto duration = duration_cast<milliseconds>(t2 - t1).count(); std::cout << P3.x << std::endl; std::cout << duration << " ms" << std::endl; getchar(); }
true
f7ce5e96941ddb859636d398eccc39f4d9d0f832
C++
Sunshine334419520/gstl
/test/set/test.cc
UTF-8
1,443
3.015625
3
[]
no_license
/** * @Author: YangGuang <sunshine> * @Date: 2018-03-18T15:25:37+08:00 * @Email: guang334419520@126.com * @Filename: test.cc * @Last modified by: sunshine * @Last modified time: 2018-03-18T15:51:57+08:00 */ #include "Set.h" #include <iostream> using namespace std; int main(int argc, char const *argv[]) { int ia[5] = {0, 1, 2, 3, 4}; gstl::Set<int> iset(ia, ia + 5); cout << "size = " << iset.size() << endl; cout << "3 count = " << iset.count(3) << endl; iset.insert(3); cout << "size = " << iset.size() << endl; cout << "3 count = " << iset.count(3) << endl; iset.insert(5); cout << "size = " << iset.size() << endl; cout << "3 count = " << iset.count(3) << endl; iset.erase(1); cout << "size = " << iset.size() << endl; cout << "3 count = " << iset.count(3) << endl; gstl::Set<int>::iterator it1 = iset.begin(); gstl::Set<int>::iterator it2 = iset.end(); for ( ; it1 != it2; ++it1) cout << *it1 << '\t'; cout << endl; it1 = iset.find(3); if (it1 != iset.end()) { cout << "3 found" << endl; iset.insert(it1, 10); iset.erase(it1); } else { cout << "3 not found" << endl; } for (it1 = iset.begin(); it1 != it2; ++it1) cout << *it1 << '\t'; cout << endl; gstl::Set<int> iset2(iset); cout << "iset == iset2 : " <<(iset == iset2) << endl; cout << "iset < iset2 : " <<(iset < iset2) << endl; cout << "iset >= iset2 : " <<(iset >= iset2) << endl; return 0; }
true
fe64d48a248865d505ac94c1ed985eba3bd71271
C++
vyldr/potential-pancake
/src/uiDraw.cpp
UTF-8
6,386
2.796875
3
[]
no_license
// Functions for drawing on the screen. Also random functions because of reasons // TODO: Maybe find a better place for the random functions #define LINUX //#define MAC_XCODE //#define WIN_VISUAL_STUDIO #ifdef MAC_XCODE #include <openGL/gl.h> // Main OpenGL library #include <GLUT/glut.h> // Second OpenGL library #endif // MAC_XCODE #ifdef LINUX //#include <GL/gl.h> // Main OpenGL library #include <GL/glut.h> // Second OpenGL library #endif // LINUX #ifdef WIN_VISUAL_STUDIO #include <stdio.h> #include <stdlib.h> #include <glut.h> // OpenGL library we copied #define _USE_MATH_DEFINES #include <math.h> #endif // WIN_VISUAL_STUDIO #include <iostream> #include "include/definitions.h" #include "include/uiDraw.h" // RGB values for different items float colors[3][10] = { // Type 0 Type 1 Type 2 Type 3 Type 4 Type 5 Type 6 Type 7 Base 1 {0.1961, 0.6980, 0.6000, 0.5020, 0.4000, 0.2384, 0.5000, 0.7098, 0.0000, 0.2187}, // Red {0.1216, 0.4706, 0.4000, 0.3294, 0.2588, 0.1506, 0.5000, 0.8980, 0.5000, 0.8672}, // Green {0.0627, 0.2392, 0.2000, 0.1686, 0.1294, 0.0800, 0.5000, 0.2000, 0.8000, 0.3047}}; // Blue // 2D drawing // Draw a tile on the screen void drawTile(int xCoord, int yCoord, int xOffset, int yOffset, float scale, int type, int base) { drawRectangle( // Top left corner of tile (xCoord * TILE_SIZE - xOffset) * scale, (yCoord * TILE_SIZE - yOffset) * scale, // Bottom right corner of tile ((xCoord + 1) * TILE_SIZE - xOffset) * scale - 1, ((yCoord + 1) * TILE_SIZE - yOffset) * scale - 1, //Red Green Blue colors[0][type], colors[1][type], colors[2][type]); // Draw a blue square on base tiles if (base == 1) drawRectangle( // Top left corner of tile (xCoord * TILE_SIZE - xOffset + (TILE_SIZE / 4)) * scale, (yCoord * TILE_SIZE - yOffset + (TILE_SIZE / 4)) * scale, // Bottom right corner of tile ((xCoord + 1) * TILE_SIZE - xOffset - (TILE_SIZE / 4)) * scale - 1, ((yCoord + 1) * TILE_SIZE - yOffset - (TILE_SIZE / 4)) * scale - 1, //Red Green Blue colors[0][8], colors[1][8], colors[2][8]); } void drawCharacter(float xCoord, float yCoord, int xOffset, int yOffset, float scale) { drawRectangle( // Top left corner of tile (xCoord * TILE_SIZE - xOffset - CHARACTER_SIZE / 2) * scale, (yCoord * TILE_SIZE - yOffset - CHARACTER_SIZE / 2) * scale, // Bottom right corner of tile (xCoord * TILE_SIZE - xOffset + CHARACTER_SIZE / 2) * scale, (yCoord * TILE_SIZE - yOffset + CHARACTER_SIZE / 2) * scale, //Red Green Blue colors[0][8], colors[1][8], colors[2][8]); //std::cout << xCoord << '\n'; } // Draw the Items void drawItem(float xCoord, float yCoord, int type, int xOffset, int yOffset, float scale) { drawRectangle( // Top left corner of tile (xCoord * TILE_SIZE - xOffset - ITEM_SIZE / 2) * scale, (yCoord * TILE_SIZE - yOffset - ITEM_SIZE / 2) * scale, // Bottom right corner of tile (xCoord * TILE_SIZE - xOffset + ITEM_SIZE / 2) * scale, (yCoord * TILE_SIZE - yOffset + ITEM_SIZE / 2) * scale, //Red Green Blue colors[0][9], colors[1][9], colors[2][9]); } // Draw the yellow box in the center of the screen void drawCenterBox(float scale) { drawRectangleOutline( ( TILE_SIZE / 2 * scale), ( TILE_SIZE / 2 * scale - 1), (-TILE_SIZE / 2 * scale), (-TILE_SIZE / 2 * scale - 1), 1, 1, 0); } // 3D drawing void setup3DFrame(const float camera[6]) { // clear the drawing buffer. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); // Move the camera glRotatef(camera[4] * 180 / M_PI, 0, 1, 0); glTranslatef(camera[0] + 0.5,camera[1],camera[2] + 0.5); } void drawModel(std::vector<Model> models, int modelnum, int direction, int xCoord, int yCoord, int type) { // Set up the matrix glPushMatrix(); glTranslatef(xCoord, 0, yCoord); glRotatef(90 * direction, 0, 1, 0); // glTranslatef(-0.5, 0.0, -0.5); // Draw each triangle for (int i = 0; i < models[modelnum].triangles.size(); i++) { Triangle t = models[modelnum].triangles[i]; // Draw the triangle glBegin(GL_TRIANGLES); glColor3f(colors[0][type], colors[1][type], colors[2][type]); glVertex3f(models[modelnum].vertices[t.a].x,models[modelnum].vertices[t.a].y,models[modelnum].vertices[t.a].z); glVertex3f(models[modelnum].vertices[t.b].x,models[modelnum].vertices[t.b].y,models[modelnum].vertices[t.b].z); glVertex3f(models[modelnum].vertices[t.c].x,models[modelnum].vertices[t.c].y,models[modelnum].vertices[t.c].z); glEnd(); } glPopMatrix(); } void drawTile3D(int xCoord, int yCoord, int type, int base, int shape, int direction, std::vector<Model> models) { drawModel(models, shape, direction, xCoord, yCoord, type); if (base) { } } // Draw the crosshair for aiming void drawCrosshair() { drawRectangle(1, 0, 10, 10, 0.5, 1.0, 0.5); } // Draw text on the screen from specific coordinates void drawText(int x, int y, const char * text) { // Set color to white TODO: Add color input options glColor3f(1.0, 1.0, 1.0); // Top-left corner of the text glRasterPos2f(x, y); // Draw each character for (const char *p = text; *p; p++) glutBitmapCharacter(GLUT_BITMAP_HELVETICA_12, *p); } // Draw a rectangle based on two corners and the color void drawRectangle(int xBegin, int yBegin, int xEnd, int yEnd, float red, float green, float blue) { glColor3f(red, green, blue); // Set color glRectf(xBegin, yBegin, xEnd, yEnd); // Draw the thing! } void drawRectangleOutline(int xBegin, int yBegin, int xEnd, int yEnd, float red, float green, float blue) { glColor3f(red, green, blue); // Set color // Draw the thing! glBegin(GL_LINE_STRIP); glVertex2f(xBegin, yBegin); glVertex2f(xEnd - 1, yBegin); // Subtract 1 to fill in the corner glVertex2f(xEnd, yEnd); glVertex2f(xBegin, yEnd); glVertex2f(xBegin, yBegin); glEnd(); } // Generate a random number within a specified range int random(int min, int max) { if (min == max) return min; return ((rand() % (max - min)) + min); } double random(double min, double max) { if (min == max) return min; return (min + ((double)rand() / (double)RAND_MAX * (max - min))); }
true
be248f3d141e090f541ec1cf800a9036e65b6a82
C++
ivtipm/oop-lab5-Rosspal
/Gukov/Forgotten city/Item/item.cpp
UTF-8
1,637
3.03125
3
[]
no_license
#include "item.h" int Item::getStatus() const { return status; } void Item::setStatus(int value) { status = value; } void Item::addDurability(int a) { if((durability + a) >= 100){ durability = 100; }else{ if((durability + a) <= 0){ durability = 0; }else{ durability += a; } } } void Item::addQuantity(int a) { quantity += a; } ushort Item::getLevel() const { return level; } void Item::setLevel(const ushort &value) { level = value; } Item::Item(int _cost, int _value, int _type, int _durability, int _quantity) { cost = _cost; value = _value; type = _type; durability = _durability; quantity = _quantity; } void Item::setCost(int _cost) { cost = _cost; } int Item::getCost() { return cost; } Spells* Item::getEff() { return effect; } void Item::setValue(double _value) { value = _value; } void Item::setType(int _type) { type = _type; } int Item::getType() { return type; } void Item::setDurability(int _durability) { durability = _durability; } double Item::getValue() { return value; } double Item::getDurability() { return durability; } void Item::setName(QString _name) { name = _name; } QString Item::getName() { return name; } void Item::create(int c,int t ,int v, int d, int q, QString n,Spells* e,ushort l) { cost = c; type = t; value = v; durability = d; quantity = q; name = n; effect = e; level = l; } void Item::setQuantity(int _quantity) { quantity = _quantity; } int Item::getQuantity() { return quantity; }
true
d3eb724529a17783c45446e687f19bef1af4c143
C++
generation472/Rmstr
/indicator.h
UTF-8
1,279
2.828125
3
[]
no_license
//--------------------------------------------------------- #ifndef INDICATOR_H #define INDICATOR_H //--------------------------------------------------------- #include <QWidget> //--------------------------------------------------------- /** \class Indicator \brief Класс виджет круглого индикатора.<br> <h2>Виджет реализует отображение круглого индикатора, красного и целёного цвета.</h2><br> */ class Indicator : public QWidget { Q_OBJECT public: /// \brief Конструктор /// \param parent, указатель на виджет родитель explicit Indicator(QWidget *parent = nullptr); /// \brief Деструктор ~Indicator(); private: bool f_status; ///< Статус индикатора public slots: /// \brief Слот изменения статуса /// \param fl, статус void slot_changeStatus(bool fl); protected: /// \brief Событие рисования индикатора void paintEvent(QPaintEvent *event); }; //--------------------------------------------------------- #endif // INDICATOR_H //---------------------------------------------------------
true
45a2f19e12461bb2657b7c6cc8d2dbd2e84481a8
C++
mingkaic/travis-test
/jobs/scope_guard.hpp
UTF-8
903
3.140625
3
[ "MIT", "BSL-1.0" ]
permissive
/// /// scope_guard.hpp /// jobs /// /// Purpose: /// Simulate golang defer statement /// #ifndef PKG_JOBS_SCOPE_GUARD_HPP #define PKG_JOBS_SCOPE_GUARD_HPP #include <functional> namespace jobs { using GuardOpF = std::function<void(void)>; /// Invoke held function upon destruction /// Operates as C++ style of Golang's defer struct ScopeGuard // todo: replace with a better option { ScopeGuard (GuardOpF f) : term_(f) {} virtual ~ScopeGuard (void) { if (term_) { term_(); } } ScopeGuard (const ScopeGuard&) = delete; ScopeGuard (ScopeGuard&& other) : term_(std::move(other.term_)) {} ScopeGuard& operator = (const ScopeGuard&) = delete; ScopeGuard& operator = (ScopeGuard&& other) { if (this != &other) { if (term_) { term_(); } term_ = std::move(other.term_); } return *this; } private: GuardOpF term_; }; } #endif // PKG_JOBS_SCOPE_GUARD_HPP
true
51011de0cc52c9e829d73cd68e73d41837b74a00
C++
Angella3/Jutge.org-PRO1
/Jutge-P08/06 - P63414 CountingFrequences/main.cpp
UTF-8
317
2.640625
3
[]
no_license
#include <iostream> #include <vector> using namespace std; int main(){ unsigned long n; cin >> n; vector<int> v(1001); int a; for (int num = 0; num < n; num++){ cin >> a; v[a%10000]++; } for (int i = 0; i < 1001; i++){ if(v[i] != 0) cout << 1000000000+i << " : " << v[i] << endl; } }
true
f3defb67af070faa22d0b6f688b00d1893d88970
C++
ttalvitie/frivol
/frivol/fortune/algorithm.hpp
UTF-8
4,528
2.71875
3
[]
no_license
#ifndef FRIVOL_FORTUNE_ALGORITHM_HPP #define FRIVOL_FORTUNE_ALGORITHM_HPP #include <frivol/containers/priority_queue_concept.hpp> #include <frivol/fortune/beach_line.hpp> #include <frivol/policy.hpp> #include <frivol/voronoi_diagram.hpp> #include <frivol/geometry_traits.hpp> namespace frivol { namespace fortune { /// State of Fortune's algorithm. /// @tparam PolicyT The algorithm policy to use, instance of Policy template. template <typename PolicyT = DefaultPolicy> class Algorithm { public: typedef typename PolicyT::Coord CoordT; typedef Point<CoordT> PointT; typedef VoronoiDiagram<CoordT> VoronoiDiagramT; /// Constructs algorithm state. /// @param points Reference to the input set of sites. The object must /// exist throughout the existence of the Algorithm. Algorithm(const containers::Array<PointT>& sites); /// Runs the algorithm one event handling forward. void step(); /// Returns the sweepline Y coordinate of last step(). Undefined return /// value if step() has not been called yet. CoordT getSweeplineY() const; /// Returns true if the algorithm has finished. bool isFinished(); /// Steps the algorithm until the end. void finish(); /// Returns the number of Voronoi vertices met in the algorithm. int getVoronoiVertexCount() const; /// Returns the Voronoi diagram constructed in the algorithm. The diagram /// is complete if the algorithm is finished. const VoronoiDiagramT& getVoronoiDiagram() const; /// Moves the Voronoi diagram from the algorithm state. /// @param algorithm The algorithm state rvalue from which to move the /// Voronoi diagram. static VoronoiDiagramT extractVoronoiDiagram(Algorithm<PolicyT>&& algorithm); private: typedef BeachLine<PolicyT> BeachLineT; /// Priority of events in the event queue. struct EventPriority { /// In site events, the X coordinate of the site. In circle events does /// not matter. CoordT x; /// The sweepline Y coordinate at which the event happens. CoordT y; /// Ordering of events, primarily by y and secondarily by x to handle /// cases of sites on the same horizontal line correctly. bool operator<(const EventPriority& other) const; }; typedef typename PolicyT::template EventPriorityQueue<EventPriority> EventPriorityQueueT; BOOST_CONCEPT_ASSERT((containers::PriorityQueueConcept<EventPriorityQueueT, EventPriority>)); typedef GeometryTraits<CoordT> GeometryTraitsT; /// Returns the event queue key for circle event of given arc. /// @param arc_id The id of the arc. Idx getCircleEventKey_(Idx arc_id) const; /// Get the event queue key for site event. /// @param site The index of the site. Idx getSiteEventKey_(Idx site) const; /// Get the number of possible event keys. The event keys are in range /// 0, ..., getEventKeyCount_()-1. Idx getEventKeyCount_() const; /// Returns pair of: /// - boolean with value true if the event is a site event, false if /// the event is a circle event. /// - In case of site event, the index of the site. In case of circle /// event, the arc ID. /// @param event_key The key of the event. std::pair<bool, Idx> getEventInfo_(Idx event_key) const; /// Check whether the breakpoints around an arc converge, and if they do, /// add a circle event to the queue. /// @param arc_id The ID of the arc. void tryAddCircleEvent_(Idx arc_id); /// Handles site event. /// @param site The index of the site. void handleSiteEvent_(Idx site); /// Handles circle event. /// @param arc_id The ID of the disappearing arc. void handleCircleEvent_(Idx arc_id); /// Mark the consecutive edges to infinite edges in the Voronoi diagram. /// Should only be run when all events have been handled. void markConsecutiveInfiniteEdges_(); /// The input set of point sites. const containers::Array<PointT>& sites_; /// The beach line of arcs. BeachLineT beach_line_; /// The y coordinate of last step. Undefined value if step has not been /// called. CoordT sweepline_y_; /// The event queue of site events and circle events. The event keys /// can be translated with #getCircleEventKey_, #getSiteEventKey_ and /// #getEventInfo_. EventPriorityQueueT event_queue_; /// The output Voronoi diagram that is constructed by the algorithm. VoronoiDiagramT diagram_; /// Indexes of the half-edges the breakpoints are drawing, indexed by the /// arc IDs of the arcs left from the breakpoints. containers::Array<Idx> breakpoint_edge_index_; }; } } #include "algorithm_impl.hpp" #endif
true
9083746e82ebe66bc6725e3e0cbd678e1220ccd2
C++
Geeksongs/Traditional-code
/虚函数.cpp
GB18030
985
4.03125
4
[]
no_license
#include<iostream>//дһ麯Ӷĵ using namespace std; class A { public: void great() { cout<<"һʵ,BʵܹǴ˺Ϊָ"<<endl; }//һʵ virtual void great2() { cout<<"һ麯Dzܹõ"<<endl; }//һ麯 }; class B:public A { public: void great2() { cout<<"BеʵḲAе麯"<<endl; } void great() { cout<<"BеʵӦòḲAеʵ,˵ûõָ"<<endl; } }; int main() { A *a=new B; a->great(); a->great2(); cout<<"DzָBĺӦûȫĸ"<<endl; B b; b.great(); b.great2(); return 0; }
true
7509c98b32053c06b9a911cd96cc5b9885d07d3e
C++
Flostin1/temp
/Advanced Calculator/Math.cpp
UTF-8
1,698
3.53125
4
[]
no_license
#include "Math.h" #include <ctype.h> #include <regex> void removeWhiteSpace(std::string& str) { int i = str.length() - 1; while ((i--) > 0) { if (str.at(i) == ' ') { str.erase(i, 1); i++; } } } // Split Equation // 1. Find first operator (using PEMDAs + going left to right) // 2. Number to the left is the number of origin // 3. The operator and the number on the right are a term. // Iterating over regex matches - https://stackoverflow.com/a/39080627 void splitEquation(std::string equation) { std::smatch res; std::regex pemdas("([\+])"); //std::string copy = equation; /*std::regex_search(equation, res, pemdas); std::cout << res.size() << std::endl; for (unsigned i = 0; i < res.size(); i++) { std::cout << res[i] << " found at position: " << res.position(i) << std::endl; }*/ while (std::regex_search(equation, res, pemdas)) { for (auto match : res) { std::cout << match << std::endl; } equation = res.suffix().str(); } } std::vector<int> getNumbers(const std::string& str) { std::vector<int> numbers; std::string number = ""; int length = str.length(); for (int i = 0; i < length; i++) { char chr = str.at(i); if (isdigit(chr)) { number += chr; } if (!isdigit(chr) || i == length - 1) { if (number.length() > 0) { numbers.push_back(std::stoi(number)); number = ""; } } } return numbers; } void printNumbers(std::vector<int> numbers) { int length = numbers.size(); for (int i = 0; i < length; i++) { if (i < length - 1) { std::cout << numbers[i] << ", "; } else { std::cout << numbers[i]; } } std::cout << std::endl; }
true
5b8d5e3b520dc309d6c55a403e6ea2f8a82f4092
C++
CalebSarikey/cplusplus
/Calkin-Wilf-Enumeration.cpp
UTF-8
5,588
3.578125
4
[]
no_license
#include<iostream> #include<iomanip> #include<cmath> #include<string> #include<cstring> #include<cstdlib> using namespace std; struct Fraction { int num; int den; }; int bin_array[100]; //global array to hold binary numbers Fraction cwfrac(int p); //Returns the fraction in position p in the Calkin-Wilf enumeration. int cwpos(Fraction f); //Returns the position of the fraction f in the Calkin-Wilf enumeration. int main() { int position; //to hold position Fraction frac; //to hold fraction int decision; string repeat; bool valid = false; do { while (!valid) { cout << "Enter 1 to find the position of a fraction in the Calkin-Wilf Tree," << endl; cout << "or 2 to find the fraction in a given position in the Calkin-Wilf Tree: "; cin >> decision; if(cin.fail()){ cout << "Invalid entry. Try again." << endl; cin.clear(); cin.ignore(50, '\n'); valid = false; } else if (decision == 1 || decision == 2) valid = true; else { cout << "Invalid entry. Try again." << endl; valid = false; } } cout << endl; if (decision == 1) { cout << "Enter a positive fraction and I will find its position in the Calkin- Wilf Tree" << endl; do { cout << "Numerator: "; cin >> frac.num; if(cin.fail()){ cout << "Invalid entry. Try again." << endl; cin.clear(); cin.ignore(50, '\n'); } cout << "Denominator: "; cin >> frac.den; if(cin.fail()){ cout << "Invalid entry. Try again." << endl; cin.clear(); cin.ignore(50, '\n'); } else if (frac.num <= 0 || frac.den <= 0) cout << "Invalid Entry. Must be greater than 0." << endl; } while (frac.num <= 0 || frac.den <= 0); position = cwpos(frac); cout << endl; cout << frac.num << "/" << frac.den << " is located at position " << position << endl << endl; } else if (decision == 2) { do { cout << "Enter a position and I will find the fraction in the Calkin-Wilf Tree: " << endl; cin >> position; if(cin.fail()){ cout << "Invalid entry. Try again." << endl; cin.clear(); cin.ignore(50, '\n'); } else if (position <= 0) { cout << "Invalid Entry. Must be greater than 0." << endl; } } while (position <= 0); frac = cwfrac(position); cout << endl; cout << "The fraction at position " << position << " is " << frac.num << "/" << frac.den << endl << endl; } valid = false; cout << "Would you like to compute another? (Yes/No) "; cin >> repeat; cout << endl; } while (repeat == "yes" || repeat == "Yes"); cout << "You have chosen to exit." << endl << endl; return 0; } int cwpos(Fraction f) { int i = 0; //to hold index of bin_array bool root = false; //true when the root is reached //execute while loop until the root 1/1 is reached do { f.num = f.num; f.den = f.den; //if fraction > 1, it is a right child if (f.num > f.den) { //insert a 1 into the binary number bin_array[i++] = 1; //compute parent f.num = f.num - f.den; f.den = f.den; root = false; } //if fraction < 1, it is a left child else if (f.num < f.den) { //insert a 0 into the binary number bin_array[i++] = 0; //compute parent f.den = f.den - f.num; f.num = f.num; root = false; } else root = true; } while (!root); //insert 1 into binary number once you get to root bin_array[i] = 1; int p = 0; //to hold the position integer int exp = i; //used as exponent for powers of 2 throughout conversion //convert binary to decimal for (int c = i; c >= 0; c--) { p += (bin_array[c] * (pow(2, exp))); exp--; } return p; }; Fraction cwfrac(int p) { Fraction frac; //to hold fraction at position p int r; //to hold remainder and insert into array int i = 0; //to step through array //Convert p to binary and store binary digits into array while (p != 0){ r = p % 2; bin_array[i] = r; p /= 2; i++; } //Start at root node frac.num = 1; frac.den = 1; //Start at i-2 since leading '1' means start at root node //Cycle through digits in binary number and follow path for (int c = i - 2; c >= 0; c--) { //if digit is 1, move to the right child if (bin_array[c] == 1) { frac.num = frac.num + frac.den; frac.den = frac.den; } //if digit is 0, move to the left child else if (bin_array[c] == 0) { frac.num = frac.num; frac.den = frac.den + frac.num; } } return frac; };
true
60a4b2010c43ed729c63928cb6855c69751a6966
C++
PasserByJia/algorithm-train
/EC/PAT1027/src/PAT1027.cpp
UTF-8
522
2.671875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { int n,sf=1,be=1;char f; cin>>n>>f; while(sf<=n){ sf+=((be+=2)*2); } sf-=(be*2); be-=2; for(int i=be;i>1;i-=2){ for(int l=0;l<(be-i)/2;l++)cout<<" "; for(int j=1;j<=i;j++){ cout<<f; } cout<<endl; } for(int l=0;l<(be-1)/2;l++)cout<<" "; cout<<f<<endl; for(int i=3;i<=be;i+=2){ for(int l=0;l<(be-i)/2;l++)cout<<" "; for(int j=1;j<=i;j++){ cout<<f; } cout<<endl; } cout << n-sf << endl; // prints !!!Hello World!!! return 0; }
true
a402c1638c9487daf4b4cdb6aad388c7618f342c
C++
JeffreyC1998/CS115-Assignment-project-small-game
/ItemManager.cpp
UTF-8
4,825
2.96875
3
[]
no_license
#include "ItemManager.h" #include "Item.h" #include "Location.h" #include <cassert> const int NO_SUCH_ITEM = 999999999; ItemManager::ItemManager() { item_count = 0; my_item_array = new Item[item_count]; assert(invariant ()); } ItemManager::ItemManager(const string& game_name) { for(int i = 0;i< item_count;i++) { my_item_array = nullptr; } load(game_name); sort(); assert(invariant ()); } ItemManager::ItemManager(const ItemManager& to_copy) { assert(invariant ()); item_count = to_copy.item_count; my_item_array = new Item[item_count]; for(int i = 0;i<item_count;i++) { my_item_array[i] = to_copy.my_item_array[i]; } assert(invariant ()); assert(to_copy.invariant ()); } ItemManager::~ItemManager() { delete[] my_item_array; } ItemManager& ItemManager::operator=(const ItemManager& to_copy) { assert(invariant ()); assert(to_copy.invariant()); if (&to_copy != this) { delete [] my_item_array; item_count = to_copy.item_count; } return *this; assert(invariant ()); assert(to_copy.invariant()); } void ItemManager::load(const string& filename) { assert(my_item_array != nullptr); ifstream inf; inf.open(filename.c_str()); string tempid; char id; unsigned int start_location; int points; string world_description; string inventory_description; string line; if(!inf.fail()) { inf >> item_count; for(int i = 0;i<item_count;i++) { getline(inf,line); getline(inf,line); inf >> tempid >> start_location >> points; getline(inf,world_description); getline(inf,inventory_description); id = tempid.at(0); my_item_array[i].init(id,start_location,points,world_description,inventory_description); } } else { cout << "Can not open " << endl; } } int ItemManager::getScore() const { assert(invariant ()); int score = 0; for (int i = 0;i < item_count;i++) { if (my_item_array[i].isInInventory() == true) { score = score + my_item_array[i].getPlayerPoints(); } } return score; } void ItemManager::printAtLocation(const Location& location) const { assert(invariant ()); for(int i = 0;i < item_count;i++) { if(my_item_array[i].isAtLocation(location)) my_item_array[i].printDescription(); } } void ItemManager::printInventory () const { assert(invariant ()); for(int i = 0;i < item_count ; i++) { if(my_item_array[i].isInInventory() == true) my_item_array[i].printDescription(); } } void ItemManager::reset() { assert(invariant ()); for(int i = 0;i< item_count; i++) { my_item_array[i].reset(); } assert(invariant ()); } unsigned int ItemManager::find (char id) const { /*int i; for(i = 0;i < item_count;i++) { if(id == my_item_array[i].getId()) return i; } return NO_SUCH_ITEM; */ int low = 0; int high = item_count - 1; while(low <= high) { int mid = (low + high) / 2; if(id == my_item_array[mid].getId()) { return mid; } else if( id < my_item_array[mid].getId()) { high = mid - 1; } else if( id > my_item_array[mid].getId()) { low = mid + 1; } } return -1; } bool ItemManager::isInInventory (char id) const { assert(invariant ()); if(find(id) != NO_SUCH_ITEM) return true; else return false; } void ItemManager::take(char id, const Location& player_location) { assert(invariant ()); for (int i = 0;i < item_count;i++) { if (id == my_item_array[i].getId()) { if (my_item_array[i].isAtLocation(player_location) == true) my_item_array[i].moveToInventory(); } } assert(invariant ()); } void ItemManager::leave (char id, const Location& player_location) { assert(invariant ()); int i; for (i = 0;i < item_count;i++) { if (id == my_item_array[i].getId()) { if (my_item_array[i].isInInventory()) my_item_array[i].moveToLocation(player_location); } } if(i = 10) cout << "Invalid item" << endl; assert(invariant ()); } void ItemManager::sort() { int i,j,search_min; Item temp; for( i = 0;i<item_count;i++) { search_min = i; for(j = i + 1;j < item_count;j++) { if (my_item_array[j] < my_item_array[search_min]) { search_min = j; } } temp = my_item_array[i]; my_item_array[search_min] = my_item_array[i]; my_item_array[i] = temp; } } bool ItemManager::invariant() const { int i; for(i = 0;i<item_count;i++) { if(!my_item_array[i].isInitialized() || (my_item_array == nullptr)) return false; } for(i = 0;i < item_count - 1;i++) { if(my_item_array[i+1] < my_item_array[i]) return false; } return true; }
true
ab0069dfd7d524db6a4ae88c0aa59d7fc2a8a01a
C++
salvomob/Esercitazioni_Prog2
/2020/lezioni/algoritmi di sorting/selectionsort.cpp
UTF-8
1,111
3.40625
3
[]
no_license
#include<iostream> using namespace std; template <class T> void selectionsort(T *v, int n); template <class T> void r_1selectionsort(T *v, int n); template <class T> void r_2selectionsort(T *v, int n); template <class T> void scambia(T *v,int i, int j); template <class T> void stampa(T *v, int n); int main(){ int a[]={5,1,4,3,6,4,8,9,34,2}; stampa(a,10); bubblesort(a,10); stampa(a,10); } template <class T> void selectionsort(T *v,int n){ for(int i=0;i<n-1;i++){ int m=i; for(int j=i+1;j<n;j++) if(v[m]>v[j]) m=j; scambia (v,i,m); } } template <class T> void stampa(T *v,int n){ for(int i=0;i<n;i++){ cout<< v[i] << " "; } cout << endl; } template <class T> void scambia(T *v, int i, int j){ T tmp = v[j]; v[j]=v[i]; v[i]=tmp; } template <class T> void r_1selectionsort(T *v, int n){ if(n<=1) return; int m=0; for(int i=0;i<n;i++) if(v[m]>v[i]) m=i; scambia(v,0,m); r_1selectionsort(v+1,n-1); } template <class T> void r_2selectionsort(T *v, int n){ if(n<=1) return; int m=0; for(int i=0;i<n;i++) if(v[m]<v[i]) m=i; scambia(v,n-1,m); r_2selectionsort(v,n-1); }
true
0209cf3d3c2a11eee270c32902890a967bf8c5d5
C++
JPTIZ/libgba-cpp
/libgba-cpp/engine/graphics/maps.h
UTF-8
1,823
2.6875
3
[ "MIT" ]
permissive
#ifndef GBA_ENGINE_GRAPHICS_MAPS_H #define GBA_ENGINE_GRAPHICS_MAPS_H #include <array> #include <libgba-cpp/arch/display/tilemap.h> #include "geometry.h" namespace gba::engine::graphics { template <std::size_t TilesetLength> using TileSet = std::array<display::map::Tile, TilesetLength>; template <std::size_t MapLength> class TileMap { using contents_t = std::array<uint16_t, MapLength>; public: TileMap(contents_t& contents): contents{contents} {} auto& length() const { return MapLength; } const auto& operator[](int i) const { return contents[i]; } private: const contents_t& contents; }; class Map { public: virtual auto length() const -> std::size_t = 0; virtual auto operator()(int x, int y) -> int& = 0; virtual auto operator()(int x, int y) const -> const int& = 0; }; template <std::size_t TilesetLength, std::size_t MapLength> class BaseMap: Map { using tileset_t = TileSet<TilesetLength>; using tilemap_t = TileMap<MapLength>; public: BaseMap(tileset_t& tileset, tilemap_t& tilemap, geometry::Size size = {0, 0}): _tileset{tileset}, _tilemap{tilemap}, size{size} {} auto length() const override { return _tilemap.length(); } auto& tileset() { return _tileset; } const auto& tileset() const { return _tileset; } auto& tilemap() { return _tilemap; } const auto& tilemap() const { return _tilemap; } auto& operator()(int x, int y) override { return _tilemap[x + size.width * y]; } const auto& operator()(int x, int y) const override { return _tilemap[x + size.width * y]; } private: tileset_t& _tileset; tilemap_t& _tilemap; geometry::Size size; }; } #endif
true
a9b9ff2e323fc407b945a356a277342968e49281
C++
spatial-model-editor/spatial-model-editor
/core/mesh/src/boundary.cpp
UTF-8
1,115
2.625
3
[ "MIT", "Zlib", "LGPL-2.0-or-later", "LGPL-3.0-only", "BSD-3-Clause", "GPL-1.0-or-later", "GPL-2.0-only", "BSL-1.0", "Apache-2.0", "LicenseRef-scancode-other-copyleft", "GPL-3.0-only" ]
permissive
#include "boundary.hpp" #include "line_simplifier.hpp" #include <algorithm> #include <utility> namespace sme::mesh { bool Boundary::isLoop() const { return lineSimplifier.isLoop(); } bool Boundary::isValid() const { return lineSimplifier.isValid(); } const std::vector<QPoint> &Boundary::getPoints() const { return points; } const std::vector<QPoint> &Boundary::getAllPoints() const { return lineSimplifier.getAllVertices(); } std::size_t Boundary::getMaxPoints() const { return maxPoints; } void Boundary::setPoints(std::vector<QPoint> &&simplifiedPoints) { points = std::move(simplifiedPoints); } void Boundary::setMaxPoints(std::size_t nMaxPoints) { maxPoints = nMaxPoints; lineSimplifier.getSimplifiedLine(points, maxPoints); } std::size_t Boundary::setMaxPoints() { lineSimplifier.getSimplifiedLine(points); maxPoints = points.size(); return maxPoints; } Boundary::Boundary(const std::vector<QPoint> &boundaryPoints, bool isClosedLoop) : lineSimplifier(boundaryPoints, isClosedLoop) { if (!lineSimplifier.isValid()) { return; } setMaxPoints(); } } // namespace sme::mesh
true
dd51c535806fbd8eecbdc388b8fa9a806d205095
C++
pranaykrpiyush/Codeforces--solutions
/Print Name Initials.cpp
UTF-8
1,004
2.75
3
[]
no_license
#include <stdio.h> #include <string> using namespace std; int main(){ int space_count=0, space_index[2]={0,0}; char name[100]; fgets(name, sizeof(name), stdin); // read string printf("%s",name); for (int i=0; name[i]!='\0';i++){ if (name[i]==32){ space_index[space_count]=i; space_count++; // printf("%d",space_index[space_count]); } } // printf("%d",space_count); if (space_count==1){ printf("%c ", name[0]); for (int j=0; name[j]!='\0'; j++){ if(name[j]==32){ for (int k=j; name[k]!='\0';k++){ printf("%c", name[k]); } } } } else if(space_count==2){ printf("%c ",name[0]); //printf("%d %d",space_index[0],space_index[1]); printf("%c",name[(space_index[0]+1)]); for (int l=space_index[1]; name[l]!='\0'; l++ ){ printf("%c",name[l]); } } }
true
24815c936641e55906fffff8143c3bd4c4732b4f
C++
LasseD/uva
/P11455.cpp
UTF-8
517
3.078125
3
[]
no_license
#include <iostream> #include <algorithm> int main() { unsigned long N, a[4]; std::cin >> N; for(unsigned long cas = 0; cas < N; ++cas) { std::cin >> a[0] >> a[1] >> a[2] >> a[3]; std::sort(a, a+4); if(a[0] == 0 || a[3] >= (a[0]+a[1]+a[2])) std::cout << "banana" << std::endl; else if(a[0] == a[3]) std::cout << "square" << std::endl; else if(a[0] == a[1] && a[2] == a[3]) std::cout << "rectangle" << std::endl; else std::cout << "quadrangle" << std::endl; } }
true
dfdd94ad22175b982cc0fbefe521de2ae099a1a7
C++
wen-zhi/PAT-Advanced-Level
/C++/1061-dating.cc
UTF-8
1,654
3.484375
3
[]
no_license
#include <iostream> #include <string> #include <array> #include <cctype> #include <iomanip> const std::array<std::string, 7> kWeekName = { "MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN" }; int main() { std::string day; int hour, minute; std::string str1, str2; std::getline(std::cin, str1); std::getline(std::cin, str2); bool day_is_found = false; for (auto iter1 = str1.begin(), iter2 = str2.begin(); iter1 != str1.end() && iter2 != str2.end(); ++iter1, ++iter2) { if (*iter1 == *iter2) { if (!day_is_found) { if (*iter1 <= 'G' && *iter1 >= 'A') { day = kWeekName[*iter1 - 'A']; day_is_found = true; } } else { if (*iter1 <= 'N' && *iter1 >= 'A') { hour = *iter1 - 'A' + 10; break; } else if (std::isdigit(*iter1)) { hour = *iter1 - '0'; break; } } } } std::string str3, str4; std::getline(std::cin, str3); std::getline(std::cin, str4); for (auto iter1 = str3.begin(), iter2 = str4.begin(); iter1 != str3.end() && iter2 != str4.end(); ++iter1, ++iter2) { if (*iter1 == *iter2 && std::isalpha(*iter1)) { minute = std::distance(str3.begin(), iter1); } } std::cout << day << ' '; std::cout << std::setfill('0'); std::cout << std::setw(2) << hour << ':'; std::cout << std::setw(2) << minute << '\n'; std::cout << std::setfill(' '); return 0; }
true
7c9eb528a7dc4184bffe03039f650231f35331d3
C++
PriyanshBordia/CodeForces
/1426C.cpp
UTF-8
340
2.578125
3
[]
no_license
#include <iostream> #include <math.h> #include <algorithm> typedef long long ll; using namespace std; void solve() { int n; cin >> n; int ans(1e09); for (int i = 1; i * i <= n; i++) { ans = min(ans, i - 1 + (n - 1) / i); } cout << ans << endl; return; } int main() { int t; cin >> t; while (t--) solve(); return 0; }
true
6ebad9b5544d3375f1d6d04959db46350f30b182
C++
Hung150/Lab4
/task8.cpp
UTF-8
387
3.59375
4
[]
no_license
#include <iostream> using namespace std; void swap(int&, int&); int main() { int n1, n2; cout << "Enter 1-st number" << endl; cin >> n1; cout << "Enter 2-st number" << endl; cin >> n2; swap(n1, n2); cout << n1 << ' ' << n2 << endl; system ("pause"); return 0; } void swap(int& num1, int& num2) { int temp = num1; num1 = num2; num2 = temp; }
true
469502515834ea30b90cde6d06a30add18d46efc
C++
epain17/Lab2C
/LAB2C++EP/LAB2C++EP/Rational.h
UTF-8
2,132
3.1875
3
[]
no_license
#pragma once #include <iostream> #include "GCD.h" template<typename Tint> class Rational { public: Tint P, Q; //nom, denom friend std::ostream & operator<< (std::ostream & cout, Rational<Tint> R) { cout << R.P << '/' << R.Q; return cout; } friend std::istream & operator>> (std::istream & cin, Rational<Tint>& R) { cin >> R.P; char c; cin >> c; cin >> R.Q; return cin; } Rational() : P(0), Q(1) {}; Rational(Tint P):P(P), Q(1){} Rational(Tint P, Tint Q) :P(P), Q(Q) { Reduce(this->P, this->Q); } Rational(const Rational& r) { P = r.P; Q = r.Q; } operator int() { return P / Q; } template <typename T> Rational(Rational<T>& r) { P = r.P; Q = r.Q; } /*template <typename Other> std::ostream& operator << (std::ostream& s)const { return (s << P << '/' << Q); }*/ /*std::ostream& Rational::print(std::ostream &s)const { return (s << P << '/' << Q); }*/ template <typename Other> friend bool operator== (const Rational<Tint>& lhs, const Rational<Other>& rhs) { return lhs.P * rhs.Q == lhs.Q * rhs.P; } Rational operator= (const Rational<Tint>& rhs) { P = rhs.P; Q = rhs.Q; return *this; } template<typename Other> Rational operator+= (const Rational<Other>& rhs) { P = rhs.P * Q + rhs.Q * P; Q = rhs.Q*Q; Reduce(P, Q); return *this; } template<typename Other> Rational operator+= (const Other& rhs) { P = rhs * Q + P; Reduce(P, Q); return *this; } Rational operator-= (const Rational<Tint>& rhs) { P = P * rhs.Q + Q rhs.P; Q *= rhs.Q; return *this; } template <typename Other> Rational operator+ (const Other& rhs) { Rational temp(*this); return temp += rhs; } template <typename Other> Rational operator+ (const Rational<Other>& rhs) { Rational temp(*this); return temp += rhs; } Rational operator- (const Rational<Tint> rhs) { return Rational{ *this } -= rat; } Rational operator- () { this->P = (0 - P); return *this; } Rational operator ++() { return (*this) += 1; } Rational operator++(int) { Rational temp(*this ); ++*this; return temp; } };
true
996f4c0d1af74a9696f24ef5a7dd316c6abb5b95
C++
ParagSaini/Competitive-Practice
/Striver_Series/SDE Problems/String/LongestCommonPrefix.cpp
UTF-8
552
3.0625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; string findPrefix(string s1, string s2) { string result = ""; int i = 0, j = 0; while(i < s1.length() && j < s2.length() && s1[i] == s2[j] ) { result.push_back(s1[i]); i++; j++; } return result; } string longestCommonPrefix(vector<string>& strs) { if(strs.size() == 0) return ""; string result = strs[0]; for(int i=1; i<strs.size(); i++) { result = findPrefix(strs[i], result); if(result.empty()) return ""; } return result; }
true
600f2c7150da6fe821c7db37164e26b6f417f99a
C++
rlabrecque/RLEngine
/Core/src/CInput.cpp
UTF-8
4,454
2.84375
3
[]
no_license
#include "Core.hpp" #include "CInput.hpp" CInput::CInput() { m_directInput = nullptr; m_keyboard = nullptr; m_mouse = nullptr; } CInput::CInput(const CInput&) { } CInput::~CInput() { } bool CInput::Initialize(HINSTANCE hinstance, HWND hwnd, int screenWidth, int screenHeight) { HRESULT result; Console::Print("Initializing Input."); m_screenWidth = screenWidth; m_screenHeight = screenHeight; m_mouseX = 0; m_mouseY = 0; result = DirectInput8Create(hinstance, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&m_directInput, nullptr); if(FAILED(result)) { return false; } result = m_directInput->CreateDevice(GUID_SysKeyboard, &m_keyboard, nullptr); if(FAILED(result)) { return false; } result = m_keyboard->SetDataFormat(&c_dfDIKeyboard); if(FAILED(result)) { return false; } result = m_keyboard->SetCooperativeLevel(hwnd, DISCL_FOREGROUND | DISCL_EXCLUSIVE); if(FAILED(result)) { return false; } result = m_keyboard->Acquire(); if(FAILED(result)) { return false; } result = m_directInput->CreateDevice(GUID_SysMouse, &m_mouse, nullptr); if(FAILED(result)) { return false; } result = m_mouse->SetDataFormat(&c_dfDIMouse); if(FAILED(result)) { return false; } result = m_mouse->SetCooperativeLevel(hwnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE); if(FAILED(result)) { return false; } result = m_mouse->Acquire(); if(FAILED(result)) { return false; } return true; } void CInput::Shutdown() { if(m_mouse != nullptr) { m_mouse->Unacquire(); m_mouse->Release(); } if(m_keyboard != nullptr) { m_keyboard->Unacquire(); m_keyboard->Release(); } if(m_directInput != nullptr) { m_directInput->Release(); } return; } bool CInput::Frame() { bool result; result = ReadKeyboard(); if(!result) { return false; } result = ReadMouse(); if(!result) { return false; } ProcessInput(); return true; } bool CInput::ReadKeyboard() { HRESULT result; result = m_keyboard->GetDeviceState(sizeof(m_keyboardState), (LPVOID)&m_keyboardState); if(FAILED(result)) { if(result == DIERR_INPUTLOST || result == DIERR_NOTACQUIRED) { m_keyboard->Acquire(); } else { return false; } } return true; } bool CInput::ReadMouse() { HRESULT result; result = m_mouse->GetDeviceState(sizeof(DIMOUSESTATE), (LPVOID)&m_mouseState); if(FAILED(result)) { if(result == DIERR_INPUTLOST || result == DIERR_NOTACQUIRED) { m_mouse->Acquire(); } else { return false; } } return true; } void CInput::ProcessInput() { m_mouseX += m_mouseState.lX; m_mouseY += m_mouseState.lY; if(m_mouseX < 0) { m_mouseX = 0; } if(m_mouseY < 0) { m_mouseY = 0; } if(m_mouseX > m_screenWidth) { m_mouseX = m_screenWidth; } if(m_mouseY > m_screenHeight) { m_mouseY = m_screenHeight; } return; } void CInput::GetMouseLocation(int& mouseX, int& mouseY) { mouseX = m_mouseX; mouseY = m_mouseY; return; } bool CInput::IsEscapePressed() { if(m_keyboardState[DIK_ESCAPE] & 0x80) { return true; } return false; } bool CInput::IsLeftArrowPressed() { if(m_keyboardState[DIK_LEFT] & 0x80) { return true; } return false; } bool CInput::IsRightArrowPressed() { if(m_keyboardState[DIK_RIGHT] & 0x80) { return true; } return false; } bool CInput::IsUpArrowPressed() { if(m_keyboardState[DIK_UP] & 0x80) { return true; } return false; } bool CInput::IsDownArrowPressed() { if(m_keyboardState[DIK_DOWN] & 0x80) { return true; } return false; } bool CInput::IsPgUpPressed() { if(m_keyboardState[DIK_PGUP] & 0x80) { return true; } return false; } bool CInput::IsPgDownPressed() { if(m_keyboardState[DIK_PGDN] & 0x80) { return true; } return false; } bool CInput::IsWPressed() { if(m_keyboardState[DIK_W] & 0x80) { return true; } return false; } bool CInput::IsAPressed() { if(m_keyboardState[DIK_A] & 0x80) { return true; } return false; } bool CInput::IsSPressed() { if(m_keyboardState[DIK_S] & 0x80) { return true; } return false; } bool CInput::IsDPressed() { if(m_keyboardState[DIK_D] & 0x80) { return true; } return false; } bool CInput::IsZPressed() { if(m_keyboardState[DIK_Z] & 0x80) { return true; } return false; }
true
9df8f94872087f66b57baedaca1a42565fe7d1bb
C++
Rookie35/C-plus-plus-practice
/派生类赋值兼容.cpp
UTF-8
703
3.234375
3
[]
no_license
/* * @Author: ZKF * @Date: 2019-04-10 14:20:01 * @Last Modified by: ZKF * @Last Modified time: 2019-04-10 15:04:39 */ #include <iostream> using namespace std; class base { public: base(int a=0,int b=0) { x=a; y=b; } void show2() { cout<<"x="<<x<<endl; cout<<"y="<<y<<endl; } int x; int y; }; class child:public base { public: child(int a=0,int b=0, int c=0,int d=0):base(a,b) { z=c; w=d; } void show() { show2(); cout<<"z="<<z<<endl; cout<<"w="<<w<<endl; } int z; int w; }; int main() { child c(1,2,3,4); c.show(); cout<<endl; base b; b=c; b.show2(); cout<<endl; base *b1; b1=&c; b1->show2(); cout<<endl; base &b2=c; b2.show2(); return 0; }
true
3188f19bf2af3b25f1f2dc4386048d65773d6fdc
C++
philou/philou
/opengl/isiviewerCpp/my_scene.cpp
UTF-8
7,452
2.625
3
[]
no_license
#include "my_scene.h" #include <iostream> #include <math.h> #include <GL/gl.h> // OpenGL include file #include <boost/shared_ptr.hpp> using namespace std; /** * Constructor * * @param radius */ MyScene::MyScene(float radius) : _allObjects(NULL) { std::cout << "constructing : MyScene" << std::endl; _currentObject = MyScene::CUBE; _displayMode = MyScene::SMOOTHSHADED; _radius = radius; _radiusMin = 0.1; _radiusMax = 2.0; _radiusIncr = 0.1; _dayOfYear = 0; } /** * Destructor * */ MyScene::~MyScene() { std::cout<<"~MyScene"<<std::endl; delete _allObjects; } /** * Init the scene and OpenGL state * */ void MyScene::init() { _objects[CUBE].load("./data/cube.off"); _objects[PYRAMID].load("./data/pyramid.off"); _objects[DISK].load("./data/disk.off"); _objects[DISKHOLE].load("./data/diskhole.off"); _objects[CYLINDER].load("./data/cylinder.off"); _objects[CONE].load("./data/cone.off"); _objects[SPHERE].load("./data/sphere.off"); _objects[AIRCRAFT].load("./data/aircraft.off"); _objects[VENUS].load("./data/venus.off"); _objects[NEFERTITI].load("./data/nefertiti.off"); Mesh* cone = new Mesh(); cone->load("./data/cone.off"); cone->addTransformation(glTranslatef,0.0,0.0,_radius); cone->addTransformation(glScalef,0.1, 0.1, 0.5); Mesh* cylinder = new Mesh(); cylinder->load("./data/cylinder.off"); cylinder->addTransformation(glScalef,0.01, 0.01, 1.0); ObjectGroup* zArrow = new ObjectGroup(); zArrow->add(cone); zArrow->add(cylinder); //zArrow->addTransformation(glScalef, _radius/2, _radius/2, _radius/2); zArrow->addTransformation(glColor3f, 0, 0, 0.5); ObjectGroup* xArrow = zArrow->clone(); xArrow->addTransformation(glRotatef, 90, 0, 1, 0); xArrow->addTransformation(glColor3f, 0.5, 0, 0); ObjectGroup* yArrow = zArrow->clone(); yArrow->addTransformation(glRotatef, -90, 1, 0, 0); yArrow->addTransformation(glColor3f, 0, 0.5, 0); Mesh* centerSphere = new Mesh(); centerSphere->load("./data/sphere.off"); centerSphere->addTransformation(glScalef,0.05, 0.05, 0.05); centerSphere->addTransformation(glColor3f, 0.5, 0.5, 0.5); _allObjects = new ObjectGroup(); _allObjects->add(centerSphere); _allObjects->add(xArrow); _allObjects->add(yArrow); _allObjects->add(zArrow); Mesh* sun = new Mesh(); sun->load("./data/sphere.off"); sun->addTransformation(glScalef, 0.3, 0.3, 0.3); sun->addTransformation(glColor3f, 0.9, 0.2, 0.0); _allObjects->add(sun); ObjectGroup* earthAndMoon = new ObjectGroup(); _earthAndMoonRotator = new ParametrizedRotator(0,0,1); earthAndMoon->addTransformation(_earthAndMoonRotator); earthAndMoon->addTransformation(glTranslatef, 2, 0.0, 0.0); Mesh* earth = new Mesh(); earth->load("./data/sphere.off"); earth->addTransformation(glScalef, 0.1, 0.1, 0.1); earth->addTransformation(glColor3f, 0.0, 0.2, 0.9); earthAndMoon->add(earth); Mesh* moon = new Mesh(); moon->load("./data/sphere.off"); _moonRotator = new ParametrizedRotator(0,0,1); moon->addTransformation(_moonRotator); moon->addTransformation(glTranslatef, 0.5, 0.0, 0.0); moon->addTransformation(glScalef, 0.04, 0.04, 0.04); moon->addTransformation(glColor3f, 0.3, 0.3, 0.3); earthAndMoon->add(moon); _allObjects->add(earthAndMoon); setDayOfYear(0); // set antialiased lines //glEnable(GL_LINE_SMOOTH); // FIXME current MESA driver messes up with antialiasing ... glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); glLineWidth(1.5); } /** * Draw the scene * */ void MyScene::draw() { //glDisable(GL_LIGHT0); glScalef( _radius/2, _radius/2, _radius/2); _allObjects->draw(_displayMode == MyScene::SMOOTHSHADED); GLfloat light_position[] = { 1.0, 1.0, 1.0, 0.0 }; glLightfv(GL_LIGHT1, GL_POSITION, light_position); glEnable(GL_LIGHT1); } void MyScene::setDayOfYear(int dayOfYear) { _dayOfYear = dayOfYear; if( NULL != _earthAndMoonRotator) { _earthAndMoonRotator->setAngle( (GLfloat)(_dayOfYear % 365) / 365.0 * 360.0 ); } if( NULL != _moonRotator) { _moonRotator->setAngle( (GLfloat)(_dayOfYear % 21) / 21.0 * 360.0 ); } } /** * Slot set current object * * @param currentObject */ void MyScene::slotSetCurrentObject(int currentObject) { std::cout << "slotSetCurrentObject "<< currentObject << std::endl; _currentObject = currentObject % COUNT; //std::cout << _objects[_currentObject] << std::endl; emit sigCurrentObjectChanged(currentObject); } /** * Slot set display mode * * @param currentObject */ void MyScene::slotSetDisplayMode(int displayMode) { std::cout << "slotSetDisplayMode "<< displayMode%3 << std::endl; _displayMode = displayMode; switch (displayMode%3) { case MyScene::WIREFRAME: glDisable(GL_LIGHTING); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); break; case MyScene::FLATSHADED: glEnable(GL_LIGHTING); glShadeModel(GL_FLAT); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); break; case MyScene::SMOOTHSHADED: glEnable(GL_LIGHTING); glShadeModel(GL_SMOOTH); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); break; } emit sigDisplayModeChanged(displayMode); } /** * Slot set radius * * @param radius */ void MyScene::slotSetRadius(double radius) { if (fabs(_radius - float(radius))>1e-6) { //std::cout << "slotSetRadius "<< radius << std::endl; _radius = radius; emit sigRadiusChanged(radius); } } /** * Process keyboard events for QGLViewer widget * * @param e a keyboard event from QGLViewer * * @return true if the event has been handled */ bool MyScene::keyPressEvent(QKeyEvent *e) { const Qt::KeyboardModifiers modifiers = e->modifiers(); // A simple switch on e->key() is not sufficient if we want to take // state key into account. With a switch, it would have been // impossible to separate 'F' from 'CTRL+F'. That's why we use // imbricated if...else and a "handled" boolean. bool handled = false; float epsilon = 1e-5; // for float comparison // Increase radius with 'r' if ((e->key()==Qt::Key_R) && (modifiers==Qt::NoButton)) { if (_radius+_radiusIncr <= _radiusMax + epsilon) this->slotSetRadius(_radius+_radiusIncr); handled = true; } // Decrease radius with 'R' else if ((e->key()==Qt::Key_R) && (modifiers==Qt::SHIFT)) { if (_radius-_radiusIncr >= _radiusMin - epsilon) this->slotSetRadius(_radius-_radiusIncr); handled = true; } // Increase current displayed object with 'o' if ((e->key()==Qt::Key_O) && (modifiers==Qt::NoButton)) { this->slotSetCurrentObject(_currentObject+1); handled = true; } // Decrease current displayed object with 'O' else if ((e->key()==Qt::Key_O) && (modifiers==Qt::SHIFT)) { this->slotSetCurrentObject(_currentObject-1); handled = true; } // change displau mode with 's' else if ((e->key()==Qt::Key_S) && (modifiers==Qt::NoButton)) { this->slotSetDisplayMode(_displayMode+1); handled = true; } // increase day with 'd' else if ((e->key()==Qt::Key_D) && (modifiers==Qt::NoButton)) { this->setDayOfYear(_dayOfYear+1); handled = true; } // decrease day with 'd' else if ((e->key()==Qt::Key_D) && (modifiers==Qt::SHIFT)) { this->setDayOfYear(_dayOfYear-1); handled = true; } // ... and so on with other else/if blocks. return handled; }
true
2364a05ad442c19be349cc9c1da989337ab7ca55
C++
zleviz1/csi2372-project
/deck.cpp
UTF-8
1,528
3.140625
3
[]
no_license
#include "Deck.h" using std::istream; using std::cout; using std::endl; using std::string; using std::getline; Card* Deck::draw() { if (size() > 0) { Card* card = this.begin(); erase(begin()); return card; } else { return nullptr; } } void Deck::print() { for (auto& i : *this) { std::cout << *i; } } Deck::Deck(istream& a, CardFactory* f) { string card; while ((in >> card)) { if (card == "--") { break; } Card * add; if (cards == 'Hematite') { string name{"Hematite"}; add = f->getCard(Hematite); } if (cards == 'Amethyst') { string name{"Amethyst"}; add = f->getCard(Amethyst); } if (cards == 'Obsidian') { string name{"Obsidian"}; add = f->getCard(Obsidian); } if (cards == 'Malachite') { string name{"Malachite"}; add = f->getCard(Malachite); } if (cards == 'Turquoise') { string name{"Turquoise"}; add = f->getCard(Turquoise); } if (cards == 'Ruby') { string name{"Ruby"}; add = f->getCard(Ruby); } if (cards == 'Quartz') { string name{"Quartz"}; add = f->getCard(Quartz); } if (cards == 'Emerald') { string name{"Emerald"}; add = f->getCard(Emerald); } this->push_back(add); } }
true
a788f7847c2f0a52784d16611475d01c6737e14e
C++
jorgmo02/Problemas-resueltos-MARP
/32 - El alienígena infiltrado.cpp
ISO-8859-1
2,486
3.390625
3
[]
no_license
#include <iostream> #include <fstream> #include <queue> #include <string> struct Trabajo { int c, f; bool operator < (const Trabajo& other) const { return c > other.c || (c == other.c && f < other.f); } }; int resolver(std::priority_queue<Trabajo>& q, int C, int F) { // empezamos por C porque el resto nos da igual (no metemos trabajos que no nos interesan en resuelveCaso()) int cubierto = C; int nTareas = 0; // INVARIANTE: no puede haber huecos vacos entre C y F. // vamos cogiendo tareas mientras que no haya huecos vacos (q.top().c <= cubierto) // y no hayamos terminado (cubierto < F). while (!q.empty() && q.top().c <= cubierto && cubierto < F) { // vamos quitando elementos de la cola que solapen. Podemos coger el elemento // que empiece antes o en el mismo sitio que cubierto y que termine ms tarde. // Si no hemos cogido ningn elemento, significa que no podemos unir // trabajos, es decir, que va a haber un momento sin que se solape ningn trabajo. // En ese caso devolvemos -1. Si, por el contrario, hemos cambiado el valor de "max", // esto significa que hemos cogido un elemento de la cola (que llega hasta el instante // de tiempo max). int max = cubierto; // nueva variable para lo que hemos cubierto hasta el momento while (!q.empty() && q.top().c <= cubierto) { // vamos quitando elementos de la cola if (q.top().f > max) max = q.top().f; q.pop(); } if (max != cubierto) { cubierto = max; nTareas++; } else return -1; } return (cubierto < F) ? -1 : nTareas; } bool resuelveCaso() { int C, F, N; std::cin >> C >> F >> N; if (C == 0 && F == 0 && N == 0) return false; std::priority_queue<Trabajo> q; int c, f; for (int i = 0; i < N; i++) { std::cin >> c >> f; if(f >= C && c <= F) q.push({ c, f }); // no metemos trabajos que no nos interesan } int sol = resolver(q, C, F); std::cout << ((sol != -1) ? std::to_string(sol) : "Imposible") << "\n"; return true; } int main() { #ifndef DOMJUDGE std::ifstream in("casos.txt"); auto cinbuf = std::cin.rdbuf(in.rdbuf()); #endif while (resuelveCaso()); // para dejar todo como estaba al principio #ifndef DOMJUDGE std::cin.rdbuf(cinbuf); system("PAUSE"); #endif return 0; }
true
050505a233742ecf88f9a28ea84a6d808585b8b0
C++
lizlyon/CPSC350_SP21_ASSIGNMENT6_LYON
/main.cpp
UTF-8
7,488
3.765625
4
[]
no_license
#include <iostream> #include <string> #include "Database.h" #include "DbStack.h" //#include "Student.h" using namespace std; int main(){ bool loadMenu = true; string userChoice; int id, sid, fid = 0; Database db; DbStack stack; while(loadMenu){ //prompt user with menu options cout << "\nPlease type an integer from the menu below: " << endl; cout << "\n1.Print all students and their information (sorted by ascending id #)" << endl; cout << "2.Print all faculty and their information (sorted by ascending id #)" << endl; cout << "3.Find and display student information given the students id" << endl; cout << "4.Find and display faculty information given the faculty id" << endl; cout << "5.Given a student's id, print the name and info of their faculty advisor" << endl; cout << "6.Given a faculty id, print ALL the names and info of his/her advisees." << endl; cout << "7.Add a new student" << endl; cout << "8.Delete a student given the id" << endl; cout << "9.Add a new faculty member" << endl; cout << "10.Delete a faculty member given the id." << endl; cout << "11.Change a student's advisor given the student id and the new faculty id." << endl; cout << "12.Remove an advisee from a faculty member given the ids" << endl; cout << "13.Rollback" << endl; cout << "14.Exit" << endl; //read in user choice cout << "\nSelection: "; cin >> userChoice; while (userChoice != "1" && userChoice != "2" && userChoice != "3" && userChoice != "4" && userChoice != "5" && userChoice != "6" && userChoice != "7" && userChoice != "8" && userChoice != "9" && userChoice != "10" && userChoice != "11" && userChoice != "12" && userChoice != "13" && userChoice != "14") { cout << "Error. Please enter an integer from the list!" << endl; cout << "Selection: "; cin >> userChoice; } cout << "Thank you for choosing " << userChoice << endl; cin.ignore(); if (userChoice == "1"){ //call method to print ALL students and their info (sorted by ascending id #) cout << "All students:" << endl; db.printAllStudents(); } else if (userChoice == "2"){ //call method to print all faculty and their info (sorted by ascending id #) cout << "All faculty members:" << endl; db.printAllFaculty(); } else if (userChoice == "3"){ //call method to find and display student information given the students id cout << "Student information:" << endl; cout << "\nEnter student ID: "; cin >> id; //call method in Database to find the student db.findStudent(id); } else if (userChoice == "4"){ //call method to find and display faculty information given the faculty id cout << "Faculty information:" << endl; cout << "\nEnter faculty ID: "; cin >> id; //call method in Database to find the faculty member db.findFaculty(id); } else if (userChoice == "5"){ //call method given a student’s id, print the name and info of their faculty advisor cout << "A student's faculty advisor" << endl; cout << "\nEnter student ID: "; cin >> id; //method to print the students advisor db.printStudentsAdvisor(id); } else if (userChoice == "6"){ //call method given a faculty id, print ALL the names and info of his/her advisees cout << "A faculty member's advisees:" << endl; cout << "\nEnter faculty ID: "; cin >> id; //method that prints the advisors students db.printAdvisorsStudents(id); } else if (userChoice == "7"){ //call method to add a student cout << "Add a student:" << endl; int ID, advisorID; double gpa; string name, year, major; //prompt new student for their name, year, major, gpa, and advisor ID cout << "\nEnter student ID: "; cin >> ID; cin.ignore(); cout << "Enter name: "; getline(cin, name); cout << "Enter year: "; getline(cin, year); cout << "Enter major: "; getline(cin, major); cout << "Enter gpa: "; cin >> gpa; cout << "Enter advisor id: "; cin >> advisorID; cout << "New student " << name << " successfully added!" << endl; //create new student and insert into tree db.addStudent(Student(ID, name, year, major, gpa, advisorID)); stack.push(db); } else if (userChoice == "8"){ //call method that deletes a student given their id cout << "Delete a student:" << endl; cout << "\nEnter student ID: "; cin >> id; //method that deletes the student from tree db.deleteStudent(id); //push change to the stack stack.push(db); } else if (userChoice == "9"){ //call method to add a new faculty member cout << "Add a faculty member:" << endl; int ID; string name, level, dept; //list for students List<int> list; cout << "\nEnter faculty ID: "; cin >> ID; cin.ignore(); cout << "Enter name: "; getline(cin, name); cout << "Enter level: "; getline(cin, level); cout << "Enter department: "; getline(cin, dept); int studentID = 0; while (studentID != -1){ cout << "Enter advisee id(s) (enter -1 to quit entering id(s)): "; cin >> studentID; if (studentID == -1){ continue; } list.insertBack(studentID); } db.addFaculty(Faculty(ID, name, level, dept, list)); cout << "Successfully added " << name << " to the database!" << endl; //push changes to stack (error here) stack.push(db); } else if (userChoice == "10"){ //call method to delete a faculty member given their id cout << "Delete a faculty member:" << endl; cout << "\nEnter faculty ID: "; cin >> id; //method to delete faculty from the tree db.deleteFaculty(id); //push change on stack stack.push(db); } else if (userChoice == "11"){ //call method that changes a student’s advisor given the student id and the new faculty id cout << "Change a student's advisor:" << endl; cout << "\nEnter student ID: "; cin >> sid; cout << "Enter faculty ID: "; cin >> fid; //call method to change advisor db.changeAdvisor(sid,fid); //push change on stack stack.push(db); } else if (userChoice == "12"){ //call method that removes an advisee from a faculty member given the ids cout << "Remove an advisee from a faculty member's list:" << endl; cout << "\nEnter faculty ID: "; cin >> fid; cout << "\nEnter student ID you wish to remove from list: "; cin >> sid; //remove advisee from advisors list, not the tree db.removeAdvisee(sid, fid); //push change on stack stack.push(db); } else if (userChoice == "13"){ //call method to rollback to undo previous action cout << "Rollback:" << endl; //if the stack is not empty then get the top and pop max 5x if(!stack.empty()){ db = stack.top(); stack.pop(); } } else if (userChoice == "14"){ //call method to write the faculty and student tables back out to the //“facultyTable” and “studentTable” files, clean up, and quit cout << "\nWriting to facultyTable.txt" << endl; cout << "Writing to studentTable.txt" << endl; cout << "\nGoodbye!" << endl; db.exit(); return 0; } } //end of while loop return 0; }
true
23733941a2a4289932eb9f2daae8d25514fd7aaa
C++
deepakchinnadurai/SortVisualization
/main.cpp
UTF-8
16,031
2.984375
3
[ "MIT" ]
permissive
/** * main.cpp * @author: Kevin German **/ #include <SDL.h> #include <vector> #include <thread> #include <iostream> #include <fstream> #include "settings.h" #include "SortingData.h" #include "sort.h" //-------Prototypes------- void init_settings(const int argc, char** argv); void close_system(); void print_controls(); void init_data(std::vector<SortingData>& data); void keyboard_event(const SDL_KeyboardEvent* type, std::vector<SortingData>& data); void thread_drawing(std::vector<SortingData>* data); void thread_sorting(std::vector<SortingData>* data); int init_system(); //------Variables--------- auto assignmentDelay = defaultAssignmentDelay; auto compareDelay = defaultCompareDelay; auto numberOfElements = defaultNumberOfElements; auto currentSortingAlgorithm = sort::SortingAlgorithm::none; auto isRunning = true; bool sortingDisabled = false; //------SDL variables----- SDL_Window* window = nullptr; SDL_Renderer* renderer = nullptr; auto elementWidth = defaultScreenWidth / numberOfElements; auto screenWidth = defaultScreenWidth; auto screenHeight = defaultScreenHeight; auto maxThreads = defaultMaxThreads; int main(const int argc, char** argv) { init_settings(argc, argv); //init std::vector<SortingData> data(numberOfElements); init_data(data); if (init_system()) return -1; print_controls(); //threads std::thread drawingThread(thread_drawing, &data); std::thread sortingThread(thread_sorting, &data); //handle events while (isRunning) { SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYDOWN: keyboard_event(&event.key, data); break; case SDL_QUIT: sortingDisabled = true; isRunning = false; default: break; } } std::this_thread::sleep_for(std::chrono::milliseconds(50)); } //wait for threads sortingThread.join(); drawingThread.join(); //terminate sdl close_system(); return 1; } void thread_drawing(std::vector<SortingData>* data) { SDL_Rect rect; rect.y = screenHeight; rect.w = elementWidth; while (isRunning) { //clear screen SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE); SDL_RenderClear(renderer); //draw each element SDL_SetRenderDrawColor(renderer, 255, 255, 255, SDL_ALPHA_OPAQUE); auto elementPos = 0; for (auto& element : *data) { if (!element.verificationEnabled()) { if (element.compared()) SDL_SetRenderDrawColor(renderer, 194, 24, 7, SDL_ALPHA_OPAQUE); else if (element.assigned()) SDL_SetRenderDrawColor(renderer, 90, 24, 7, SDL_ALPHA_OPAQUE); else SDL_SetRenderDrawColor(renderer, 255, 255, 255, SDL_ALPHA_OPAQUE); } else { if (element.compared()) SDL_SetRenderDrawColor(renderer, 0, 160, 0, SDL_ALPHA_OPAQUE); else SDL_SetRenderDrawColor(renderer, 194, 24, 7, SDL_ALPHA_OPAQUE); } rect.h = -element.mKey; rect.x = (elementPos++) * elementWidth; SDL_RenderFillRect(renderer, &rect); } SDL_RenderPresent(renderer); std::this_thread::yield(); } } void thread_sorting(std::vector<SortingData>* data) { while (isRunning) { if (currentSortingAlgorithm != sort::SortingAlgorithm::none) { sortingDisabled = false; //start timer here for rough measurement const auto start = std::chrono::high_resolution_clock::now(); try { switch (currentSortingAlgorithm) { case sort::SortingAlgorithm::cyclesort: std::cout << "Cyclesort started...\n"; sort::cyclesort(data->begin(), data->end()); break; case sort::SortingAlgorithm::bubblesort: std::cout << "Bubblesort started...\n"; sort::bubblesort(data->begin(), data->end()); break; case sort::SortingAlgorithm::bubblesortrc: std::cout << "Bubblesort recursivly started...\n"; sort::bubblesort_rc(data->begin(), data->end()); break; case sort::SortingAlgorithm::stdsort: std::cout << "std::sort started...\n"; std::sort(data->begin(), data->end()); break; case sort::SortingAlgorithm::shellsort: std::cout << "Shellsort started...\n"; sort::shellsort(data->begin(), data->end()); break; case sort::SortingAlgorithm::combsort: std::cout << "Combsort started...\n"; sort::combsort(data->begin(), data->end()); break; case sort::SortingAlgorithm::gnomesort: std::cout << "Gnomesort started...\n"; sort::gnomesort(data->begin(), data->end()); break; case sort::SortingAlgorithm::gnomesort2: std::cout << "Gnomesort2 started...\n"; sort::gnomesort2(data->begin(), data->end()); break; case sort::SortingAlgorithm::radixsort: std::cout << "Radixsort started...\n"; sort::radixsort(data->begin(), data->end(), 13); break; case sort::SortingAlgorithm::radixsortslow: std::cout << "Slow radixsort started...\n"; sort::radixsort_slow(data->begin(), data->end(), 13); break; case sort::SortingAlgorithm::radixsortipis: std::cout << "Inplace Radixsort with insertionsort started...\n"; sort::radixsort_ip_is(data->begin(), data->end(), 13, std::less<>(), maxThreads); break; case sort::SortingAlgorithm::insertionsort: std::cout << "Insertionsort started...\n"; sort::insertionsort(data->begin(), data->end()); break; case sort::SortingAlgorithm::insertionsortbinsearch: std::cout << "Insertionsort with binary search started...\n"; sort::insertionsort_binsearch(data->begin(), data->end()); break; case sort::SortingAlgorithm::selectionsort: std::cout << "Selectionsort started...\n"; sort::selectionsort(data->begin(), data->end()); break; case sort::SortingAlgorithm::bogosort: std::cout << "Bogosort started...\n"; sort::bogosort(data->begin(), data->end()); break; case sort::SortingAlgorithm::bozosort: std::cout << "Bozosort started...\n"; sort::bozosort(data->begin(), data->end()); break; case sort::SortingAlgorithm::oddevensort: std::cout << "Odd-even-sort started...\n"; sort::odd_even_sort(data->begin(), data->end()); break; case sort::SortingAlgorithm::shakersort: std::cout << "Shakersort started...\n"; sort::shakersort(data->begin(), data->end()); break; case sort::SortingAlgorithm::quicksort: std::cout << "Quicksort started...\n"; sort::quicksort(data->begin(), data->end(), std::less<>(), maxThreads); break; case sort::SortingAlgorithm::mergesort: std::cout << "Mergesort started...\n"; sort::mergesort(data->begin(), data->end(), std::less<>(), maxThreads); break; case sort::SortingAlgorithm::heapsort: std::cout << "Heapsort started...\n"; sort::heapsort(data->begin(), data->end()); break; case sort::SortingAlgorithm::introsort: std::cout << "Introsort started...\n"; sort::introsort(data->begin(), data->end(), std::less<>(), maxThreads); break; case sort::SortingAlgorithm::stdstablesort: std::cout << "std::stablesort started...\n"; std::stable_sort(data->begin(), data->end()); break; default: break; } std::cout << "Sort finished. "; } catch (std::exception & e) { std::cout << e.what(); //user input will interrupt the sorting process } const std::chrono::duration<double> elapsed = std::chrono::high_resolution_clock::now() - start; currentSortingAlgorithm = sort::SortingAlgorithm::none; sortingDisabled = false; std::cout << "Elapsed Time:\t" << elapsed.count() << " s\n"; } std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } void init_data(std::vector<SortingData>& data) { //init seed & rng std::random_device seed; std::mt19937 gen(seed()); std::uniform_int_distribution<int> dist(0, screenHeight); //fill with random values for (auto& i : data) i.mKey = dist(gen); for (auto& i : data) { i.enableVerification(false); //disable slow comparison i.setDelay(compareDelay, assignmentDelay); } } void keyboard_event(const SDL_KeyboardEvent* type, std::vector<SortingData>& data) { sortingDisabled = true; switch ((*type).keysym.sym) { case SDLK_0: init_data(data); break; case SDLK_1: currentSortingAlgorithm = sort::SortingAlgorithm::stdsort; break; case SDLK_2: currentSortingAlgorithm = sort::SortingAlgorithm::bubblesort; break; case SDLK_3: currentSortingAlgorithm = sort::SortingAlgorithm::bubblesortrc; break; case SDLK_4: currentSortingAlgorithm = sort::SortingAlgorithm::insertionsort; break; case SDLK_5: currentSortingAlgorithm = sort::SortingAlgorithm::insertionsortbinsearch; break; case SDLK_6: currentSortingAlgorithm = sort::SortingAlgorithm::selectionsort; break; case SDLK_7: currentSortingAlgorithm = sort::SortingAlgorithm::gnomesort; break; case SDLK_8: currentSortingAlgorithm = sort::SortingAlgorithm::gnomesort2; break; case SDLK_9: currentSortingAlgorithm = sort::SortingAlgorithm::cyclesort; break; case SDLK_q: currentSortingAlgorithm = sort::SortingAlgorithm::shellsort; break; case SDLK_w: currentSortingAlgorithm = sort::SortingAlgorithm::combsort; break; case SDLK_e: currentSortingAlgorithm = sort::SortingAlgorithm::oddevensort; break; case SDLK_r: currentSortingAlgorithm = sort::SortingAlgorithm::shakersort; break; case SDLK_t: currentSortingAlgorithm = sort::SortingAlgorithm::radixsort; break; case SDLK_z: currentSortingAlgorithm = sort::SortingAlgorithm::radixsortslow; break; case SDLK_u: currentSortingAlgorithm = sort::SortingAlgorithm::radixsortipis; break; case SDLK_i: currentSortingAlgorithm = sort::SortingAlgorithm::bogosort; break; case SDLK_o: currentSortingAlgorithm = sort::SortingAlgorithm::bozosort; break; case SDLK_p: currentSortingAlgorithm = sort::SortingAlgorithm::quicksort; break; case SDLK_a: currentSortingAlgorithm = sort::SortingAlgorithm::mergesort; break; case SDLK_s: currentSortingAlgorithm = sort::SortingAlgorithm::heapsort; break; case SDLK_d: currentSortingAlgorithm = sort::SortingAlgorithm::introsort; break; case SDLK_f: currentSortingAlgorithm = sort::SortingAlgorithm::stdstablesort; break; case SDLK_x: //inverse order sort::inverse_order(data.begin(), data.end()); std::cout << "Order inversed!\n"; break; case SDLK_v: //verify order //enable verification mode, this is used for drawing correctly sorted values in green for (auto& i : data) i.enableVerification(true); if (sort::verifiy_sort_order(data.begin(), data.end())) std::cout << "Sorted!\n"; else std::cout << "Not sorted\n"; break; case SDLK_b: std::cout << "Max. threads increased: " << ++maxThreads << "\n"; break; case SDLK_n: if (maxThreads != 0) { --maxThreads; std::cout << "Max. threads decreased: " << maxThreads << "\n"; } else { std::cout << "Max. threads is already 0\n"; } break; default: break; } } int init_system() { //SDL System initialisieren if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) != 0) { std::cout << "Error SDL_Init: " << SDL_GetError(); return ERROR_SDL_INIT; } //fenster und renderer erstellen if (SDL_CreateWindowAndRenderer(screenWidth, screenHeight, 0, &window, &renderer) != 0) { std::cout << "Error SDL_CreateWindowAndRenderer: " << SDL_GetError(); return ERROR_SDL_INIT; } return 0; } void close_system() { SDL_DestroyWindow(window); window = nullptr; SDL_DestroyRenderer(renderer); renderer = nullptr; SDL_Quit(); } void init_settings(const int argc, char** argv) { std::cout << "SortVisualization by Kevin German\n\n"; auto loadFromFile = false; std::ifstream file; //try to load from specified file if (argc != 1) { file.open(argv[1]); if (!file) { std::cout << "Error: " << argv[1] << " not found!\n"; loadFromFile = false; } else { std::cout << "Loading config from: " << argv[1] << "\n"; loadFromFile = true; } } //try to load from default file if (!loadFromFile) { file.open(configFileName); //if no file was found, use user input if (!file) { std::cout << configFileName << " not found!\n"; loadFromFile = false; } else { std::cout << "Loading config from default file: " << configFileName << "\n"; loadFromFile = true; } } //----screenwidth---- std::cout << "Screenwidth (default " << defaultScreenWidth << " ): "; if (loadFromFile) { file >> screenWidth; std::cout << screenWidth << "\n"; } else { std::cin >> screenWidth; } if (screenWidth <= 0 || screenWidth >= 4096) { std::cout << "Invalid size. Default: " << defaultScreenWidth << " used\n"; screenWidth = defaultScreenWidth; } //----screenheight---- std::cout << "Screenheight (default " << defaultScreenHeight << " ): "; if (loadFromFile) { file >> screenHeight; std::cout << screenHeight << "\n"; } else { std::cin >> screenHeight; } if (screenWidth <= 0 || screenWidth >= 4096) { std::cout << "Invalid size. Default: " << defaultScreenHeight << " used\n"; screenHeight = defaultScreenHeight; } //----number of elements---- std::cout << "Number of elements (default " << defaultScreenWidth / 2 << " ): "; if (loadFromFile) { file >> numberOfElements; std::cout << numberOfElements << "\n"; } else { std::cin >> numberOfElements; } if (numberOfElements == 0 || numberOfElements > screenWidth) { std::cout << "Invalid size. Default: " << defaultScreenWidth / 2 << " used\n"; numberOfElements = defaultScreenWidth / 2; } elementWidth = screenWidth / numberOfElements; //----assignmentdelay---- std::cout << "Assignment delay (default " << defaultAssignmentDelay.count() << "ns ): "; auto delay = 0; if (loadFromFile) { file >> delay; std::cout << delay << "\n"; } else { std::cin >> delay; } if (delay >= 0) assignmentDelay = std::chrono::nanoseconds(delay); else std::cout << "Invalid delay. Default: " << defaultAssignmentDelay.count() << " used\n"; //-----comparedelay----- std::cout << "Comparison delay (default " << defaultCompareDelay.count() << "ns ): "; delay = 0; if (loadFromFile) { file >> delay; std::cout << delay << "\n"; } else { std::cin >> delay; } if (delay >= 0) compareDelay = std::chrono::nanoseconds(delay); else std::cout << "Invalid delay. Default: " << defaultCompareDelay.count() << " used\n"; } void print_controls() { std::cout << "\n---------CONTROLS---------\n" << "0|random init data\n" << "1|std::sort (unstoppable)\n" << "2|bubblesort\n" << "3|bubblesort recursivly\n" << "4|insertionsort\n" << "5|insertionsort with binary search\n" << "6|selectionsort\n" << "7|gnomesort\n" << "8|gnomesort with jump(insertionsort variation)\n" << "9|cyclesort\n" << "Q|shellsort\n" << "W|combsort\n" << "E|odd-even-sort (2 threads)\n" << "R|shakersort\n" << "T|radixsort\n" << "Z|radixsort slow (copy instead of move operations used)\n" << "U|radixsort in-place & insertionsort (optional parallel)\n" << "I|bogosort\n" << "O|bozosort\n" << "P|quicksort (optional parallel)\n" << "A|mergesort (optional parallel)\n" << "S|heapsort\n" << "D|introsort (optional parallel)\n" << "F|std::stablesort\n" << "X|reverse order\n" << "V|verify order\n" << "----Threads(default " << defaultMaxThreads << ")----\n" << "B|increase max. threads\n" << "N|decrease max. threads\n" << "--------------------------\n" << " Keypress stopps sort\n" << "--------------------------\n" << std::endl; }
true
23c6df1975469cf0c6c1cf804f91773d1e7c8f2b
C++
bpieszko/BoostTraining
/String_Handling/StringAlgorithms/to_upper_copy.cpp
UTF-8
217
2.875
3
[]
no_license
#include <iostream> #include <string> #include <boost/algorithm/string.hpp> using namespace boost::algorithm; int main () { std::string s{"hello world"}; std::cout << to_upper_copy(s) << std::endl; return 0; }
true
d604772017a0763ff0b17ce4ac6ec22dea41c36e
C++
xinyuang/9_chapter_cpp_algorithm
/1.Linked_List vector string stack/segmentTree/439. Segment Tree Build II.cpp
UTF-8
1,445
3.703125
4
[]
no_license
/** * Definition of SegmentTreeNode: * class SegmentTreeNode { * public: * int start, end, max; * SegmentTreeNode *left, *right; * SegmentTreeNode(int start, int end, int max) { * this->start = start; * this->end = end; * this->max = max; * this->left = this->right = NULL; * } * } */ // Build SegmentTree // Divide and Conquer //Input: [3, 2, 1, 4] // Explanation : // The segment tree will be // [0, 3](max = 4) // / \ // [0, 1][2, 3] // (max = 3) (max = 4) // / \ / \ // [0, 0][1, 1] [2, 2][3, 3] //(max = 3)(max = 2)(max = 1)(max = 4) class Solution { public: /** * @param A: a list of integer * @return: The root of Segment Tree */ SegmentTreeNode* build(vector<int>& A) { // write your code here int n = A.size(); if (n == 0) return nullptr; SegmentTreeNode* root = buildTree(A, 0, n - 1); return root; } SegmentTreeNode* buildTree(vector<int>& A, int start, int end) { if (start == end) { SegmentTreeNode* newNode = new SegmentTreeNode(start, end, A[start]); return newNode; } int mid = (end - start) / 2 + start; SegmentTreeNode* left = buildTree(A, start, mid); SegmentTreeNode* right = buildTree(A, mid + 1, end); int max_value = max(left->max, right->max); SegmentTreeNode* node = new SegmentTreeNode(start, end, max_value); node->left = left; node->right = right; return node; } };
true
f8f56cbeee014d793a6ab2bd634389dbd679ec00
C++
sonicaks/Cryptography
/lab-7/MD4.cpp
UTF-8
4,602
2.96875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; char hexa[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; string C[3] = {"00000000", "5A827999", "6ED9EBA1"}; int S[3][16] = { {3, 7, 11, 19, 3, 7, 11, 19, 3, 7, 11, 19, 3, 7, 11, 19}, {3, 5, 9, 13, 3, 5, 9, 13, 3, 5, 9, 13, 3, 5, 9, 13}, {3, 9, 11, 15, 3, 9, 11, 15, 3, 9, 11, 15, 3, 9, 11, 15} }; string generate(int cnt) { string msg = ""; for (int i = 0; i < cnt; i++) { msg += hexa[rand() % 16]; } return msg; } string toBinary(string s) { string ans = ""; for (int i = 0; i < (int)s.length(); i++) { int val = lower_bound(hexa, hexa + 16, s[i]) - hexa; string res = ""; for (int j = 0; j < 4; j++) { if (val % 2) res += '1'; else res += '0'; val /= 2; } reverse(res.begin(), res.end()); ans += res; } return ans; } string toHexa(string s) { string res = ""; for (int i = 0; i < (int)s.length(); i += 4) { int val = 0; for (int j = i; j < i + 4; j++) { val = val * 2 + (s[j] - '0'); } res += hexa[val]; } return res; } string ADD(string x, string y) { int carry = 0; reverse(x.begin(), x.end()); reverse(y.begin(), y.end()); string res = ""; for (int i = 0; i < (int)x.length(); i++) { int a = lower_bound(hexa, hexa + 16, x[i]) - hexa; int b = lower_bound(hexa, hexa + 16, y[i]) - hexa; int sum = a + b + carry; int carry = sum / 16; res += hexa[sum % 16]; } reverse(res.begin(), res.end()); return res; } string OR(string x, string y) { string res = ""; for (int i = 0; i < (int)x.length(); i++) { int a = lower_bound(hexa, hexa + 16, x[i]) - hexa; int b = lower_bound(hexa, hexa + 16, y[i]) - hexa; res += hexa[a | b]; } return res; } string AND(string x, string y) { string res = ""; for (int i = 0; i < (int)x.length(); i++) { int a = lower_bound(hexa, hexa + 16, x[i]) - hexa; int b = lower_bound(hexa, hexa + 16, y[i]) - hexa; res += hexa[a & b]; } return res; } string XOR(string x, string y) { string res = ""; for (int i = 0; i < (int)x.length(); i++) { int a = lower_bound(hexa, hexa + 16, x[i]) - hexa; int b = lower_bound(hexa, hexa + 16, y[i]) - hexa; res += hexa[a ^ b]; } return res; } string NOT(string s) { s = toBinary(s); string res = ""; for (int i = 0; i < (int)s.length(); i++) { if (s[i] == '1') res += '0'; else res += '1'; } res = toHexa(res); return res; } string XOR(string x, string y, string z) { return XOR(x, XOR(y, z)); } string MAJ(string x, string y, string z) { return XOR(AND(x, y), XOR(AND(x, z), AND(y, z))); } string IF(string x, string y, string z) { return OR(AND(x, y), AND(NOT(x), z)); } string F(int rnd, string x, string y, string z) { if (rnd == 1) return XOR(x, y, z); if (rnd == 2) return MAJ(x, y, z); if (rnd == 3) return IF(x, y, z); } string SHIFT(string x, int cnt) { string res = ""; x = toBinary(x); for (int i = 0; i < cnt; i++) { char t = x[0]; for (int i = 1; i < (int)x.length(); i++) { res += x[i]; } res += t; x = res; res = ""; } x = toHexa(x); return x; } string computeHash(string msg) { string hash = ""; string reg[4]; // 0 = a(i - 4), 1 = a(i - 1), 2 = a(i - 2), 3 = a(i - 3) reg[0] = "67452301"; reg[1] = "EFCDAB89"; reg[2] = "98BADCFE"; reg[3] = "10325476"; for (int rnd = 1; rnd <= 3; rnd++) { for (int m = 0, cnt = 0; m < 128; m += 8, cnt++) { string word = ""; for (int i = m; i < m + 8; i++) { word += msg[i]; } string nxtReg[4]; nxtReg[0] = reg[3]; nxtReg[1] = ADD(reg[0], F(rnd, reg[1], reg[2], reg[3])); nxtReg[1] = ADD(nxtReg[1], word); nxtReg[1] = ADD(nxtReg[1], C[rnd - 1]); nxtReg[1] = SHIFT(nxtReg[1], S[rnd - 1][cnt]); nxtReg[2] = reg[1]; nxtReg[3] = reg[2]; for (int i = 0; i < 4; i++) { reg[i] = nxtReg[i]; } } } for (int i = 0; i < 4; i++) { hash += reg[i]; } return hash; } int main() { string msg; // msg = "76931FAC9DAB2B36C248B87D6AE33F9A62D71B3A5D5789E4B2D6B441E2411DC709E111C7E1E7ACB6FBCAC0BB2FC4C8BC2AE3BAAAB9165CC458E199CB89F51B13"; cout << "Enter hexadecimal message: "; cin >> msg; msg = toBinary(msg); int len = msg.length(); msg += '1'; while ((int)msg.length() < 448) { msg += '0'; } string lenBinary = ""; for (int i = 0; i < 64; i++) { if (len % 2) lenBinary += '1'; else lenBinary += '0'; len /= 2; } reverse(lenBinary.begin(), lenBinary.end()); msg += lenBinary; msg = toHexa(msg); cout << "Message is: " << msg << "\n"; string hash = computeHash(msg); cout << "The computed hash is: " << hash << "\n"; return 0; } // acd18b60168c4a3478fe56517eb8070b
true
1297414a8f2235e068109a3af4be15fa03639e29
C++
rwgriffithv/IEEE-Advanced-Projects
/Motor-Control/motor_control.ino
UTF-8
267
2.5625
3
[]
no_license
#define MOTOR 10 void setup() { pinMode(MOTOR, OUTPUT); } void loop() { for (int i = 1; i <= 150; i++) { analogWrite(MOTOR, i); delay(50); } for (int i = 1; i <= 150; i++) { analogWrite(MOTOR, 150 - i); delay(50); } delay(1000); }
true
3a974dedbefacf52f7a48963458ca27ba0a40dd9
C++
vladyslavkazachenko/pdfio
/test/pdfio/pdf1_0/istream/pdf1_0_istream_array_testsuite.cpp
UTF-8
1,527
2.84375
3
[]
no_license
#include <sstream> #include "pdfio/pdf1_0/indirect_reference.h" #include "pdfio/pdf1_0/istream/read_hexstring.h" #include "pdfio/pdf1_0/istream/read_array.h" #include "gtest/gtest.h" namespace pdf1_0 = pdfio::pdf1_0; TEST(ArrayTestSuite, emptyStream) { pdf1_0::Array<pdf1_0::IndirectReference> array; std::istringstream istream; EXPECT_FALSE(istream >> array); } TEST(ArrayTestSuite, simpleArray) { pdf1_0::Array<pdf1_0::IndirectReference> array1; std::istringstream istream1("[ 234 3 R ]"); EXPECT_TRUE(istream1 >> array1); EXPECT_EQ(1, array1.size()); EXPECT_TRUE(array1[0].objectNumber() == 234); EXPECT_TRUE(array1[0].generationNumber() == 3); pdf1_0::Array<pdf1_0::IndirectReference> array2; std::istringstream istream2("[ 234 3 R 432 0 R ]"); EXPECT_TRUE(istream2 >> array2); EXPECT_EQ(2, array2.size()); EXPECT_TRUE(array2[0].objectNumber() == 234); EXPECT_TRUE(array2[0].generationNumber() == 3); EXPECT_TRUE(array2[1].objectNumber() == 432); EXPECT_TRUE(array2[1].generationNumber() == 0); pdf1_0::Array<pdf1_0::HexString> array3; std::istringstream istream3("[<B0DCFF11815D46D2A0723B8B6A07897C><CB01C436D5674A45A3942939551EB0ED>]"); EXPECT_TRUE(istream3 >> array3); EXPECT_EQ(2, array3.size()); EXPECT_EQ(array3[0], "B0DCFF11815D46D2A0723B8B6A07897C"); EXPECT_EQ(array3[1], "CB01C436D5674A45A3942939551EB0ED"); } TEST(ArrayTestSuite, wrongContent) { pdf1_0::Array<pdf1_0::IndirectReference> array; std::istringstream istream("[234 3 R 432 0 ]"); EXPECT_FALSE(istream >> array); }
true
8cf512d410e7dad9bbbe29425f8305b0496dafa8
C++
chrzhang/abc
/matrices/rotateSquare90Degs/main.cpp
UTF-8
1,601
4.0625
4
[]
no_license
#include <iostream> #define N 3 // Rotate a N x N matrix 90 degrees where each pixel is 4 bytes struct Pixel { int i; Pixel() { } Pixel(int val) { i = val; } }; void printMatrix(Pixel matrix[N][N]) { for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) { std::cout << matrix[i][j].i << " "; } std::cout << std::endl; } } void rotateMatrix(Pixel matrix[N][N]) { // Start off on the outmost layer and descend in for (int depth = 0; depth < (N + 1) / 2; ++depth) { Pixel * nw, * ne, * sw, * se; nw = &matrix[depth][depth]; ne = &matrix[depth][N - 1 - depth]; sw = &matrix[N - 1 - depth][depth]; se = &matrix[N - 1 - depth][N - 1 - depth]; int i = 0; // Keep count of how many 4-way swaps to do while (i < (N - 2 * depth) - 1) { // Swap Pixel temp = *nw; *nw = *sw; *sw = *se; *se = *ne; *ne = temp; // Shift 4 pointers nw = nw + 1; // right ne = ne + N; // down sw = sw - N; // up se = se - 1; // left ++i; // Counter for how many times the 4 pointers shift } } } int main() { Pixel matrix[N][N]; int val = 1; for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) { matrix[i][j] = Pixel(val++); } } printMatrix(matrix); std::cout << "Rotate 90 degrees clockwise." << std::endl; rotateMatrix(matrix); printMatrix(matrix); return 0; }
true
48fff44546ec33c70c75b70e97697877833cb7fd
C++
agrippa/chimes
/src/libchimes/set_of_aliases.h
UTF-8
874
3.046875
3
[]
no_license
#ifndef SET_OF_ALIASES_H #define SET_OF_ALIASES_H #include <set> #include <stdio.h> class set_of_aliases { public: set_of_aliases(unsigned set_capacity) { capacity = set_capacity; set = (unsigned char *)malloc(capacity * sizeof(unsigned char)); memset(set, 0x00, capacity * sizeof(unsigned char)); } ~set_of_aliases() { free(set); } void clear() { memset(set, 0x00, capacity * sizeof(unsigned char)); explicit_aliases.clear(); } void add_alias(size_t alias) { explicit_aliases.insert(alias); } void add_loc(unsigned id) { set[id] = 1; } // TODO Ugly to have these public unsigned char *set; unsigned capacity; std::set<size_t> explicit_aliases; }; #endif
true
7f55825c8567be897b632c1cab638afda5617e5e
C++
shawnmolga/CPP-rock-paper-scissors
/EX3/RPSFight.cpp
UTF-8
950
3.09375
3
[]
no_license
/* * RPSFight * * Created on: 24 ����� 2018 * Author: OR */ #include "RPSFight.h" //RPSFight::RPSFight(RPSpoint inputPosition,char inputOpponentPiece, int inputWinner): position(inputPosition),opponentPiece(inputOpponentPiece),winner(inputWinner) {} RPSFight::RPSFight() : position(RPSpoint(0, 0)),playerOnePiece('#') ,playerTwoPiece('#'), winner(0) {} const Point &RPSFight::getPosition() const { return position; } char RPSFight::getPiece(int player) const { if (player == 1) { return playerOnePiece; } else { return playerTwoPiece; } } void RPSFight::setPosition(RPSpoint pos) { position = pos; } void RPSFight::setWinner(int playerNum) { winner = playerNum; } void RPSFight::setPlayerOnePiece(char piece) { playerOnePiece = piece; } void RPSFight::setPlayerTwoPiece(char piece) { playerTwoPiece = piece; } int RPSFight::getWinner()const { return winner; }
true
3825d93098c346d471ac43dafca0c1a4e2f54904
C++
jmserrano-dev-university/Practica3Arquitectura
/main.cpp
UTF-8
5,730
3.25
3
[]
no_license
/* * File: main.cpp * Author: José Manuel Serrano Mármol * Author: Raúl Salazar de Torres * Date: 16 - 1 - 2012 */ #include <cstdlib> #include <stdio.h> #include <iostream> #include <vector> #include <math.h> #include "imgs.h" using namespace std; /** * Función que lee un núcleo desde fichero * @param ruta Ruta donde se encuentra el núcleo * @param nucleo Devuelve el núcleo leido en vector * @param tamaNucleo Devuelve el tamaño del núcleo leido */ void leerNucleo(char *ruta, vector<float> *nucleo, int *tamaNucleo) { FILE *file; float dato; file = fopen(ruta, "r"); if (file == NULL) { cout << "No se puede leer Nucleo de convolución"; exit(-1); } while (fscanf(file, "%f", &dato) != EOF) { nucleo->push_back(dato); } *tamaNucleo = (int) sqrt(nucleo->size()); if ((*tamaNucleo) % 2 != 1) { cout << "Nucleo incorrecto" << endl; exit(-1); } } int main(int argc, char** argv) { /************* DECLARACIÓN DE VARIABLES ***************/ unsigned char *imagen; // Imagen original unsigned char *imagenSalida; // Imagen de salida unsigned char *imagenC; // Imagen original unsigned char *imagenSalidaC; // Imagen de salida unsigned int h, w, M; // Alto, ancho e intersidad imgs gestorImagen; // Gestor de la imagen, carga y almacena imagenes /************** FORMA DE USO DE LA FUNCIÓN *************/ if (argc < 3) { cout << "USO: ejecutable rutaImagenOrigen rutaImagenDestino rutaNucleo"; exit(-1); } /************** DETECCIÓN DE IMAGEN EN ESCALA DE GRISES O RBG *************/ bool color; string ruta = argv[1]; ruta = ruta.substr(ruta.length() - 3, ruta.length()); if (ruta.compare("pgm") == 0) { color = false; } else { if (ruta.compare("ppm") == 0) { color = true; } else { cout << "ERROR: Extensión de la imagen incorrecta. (.pgm o .ppm)" << endl; exit(-1); } } /************** CARGAMOS NÚCLEO DE CONVOLUCIÓN *************/ int tamaNucleo, mitadTamano; vector<float> nucleo; leerNucleo(argv[3], &nucleo, &tamaNucleo); mitadTamano = tamaNucleo / 2; /************** CARGAMOS IMAGEN *************/ if (!color) { if (!gestorImagen.loadPgm(argv[1], &imagen, &w, &h, &M)) { cout << "ERROR: Cargar imagen en ESCALA DE GRISES" << endl; exit(-1); } } else { if (!gestorImagen.loadPpm(argv[1], &imagenC, &w, &h, &M)) { cout << "ERROR: Cargar imagen en COLOR" << endl; exit(-1); } } /************** REALIZAMOS CONVOLUCIÓN *************/ float acomulador, valorF; int fx, fy; if (!color) { //Imagen en ESCALA DE GRIS imagenSalida = (unsigned char *) malloc(w * h); //Resevamos memoria para la imagen de salida (ancho por alto) for (int x = 0; x < w; x++) { for (int y = 0; y < h; y++) { //Aplicamos convolución acomulador = 0; for (int s = (mitadTamano * -1); s <= mitadTamano; s++) { for (int t = (mitadTamano * -1); t <= mitadTamano; t++) { fx = x + s; fy = y + t; if (fx < 0 || fy < 0 || fx >= w || fy >= h) { valorF = 0; //Si nos salimos de los límites ponemos 0 } else { valorF = imagen[w * fx + fy]; //Recorremos la matriz con un solo indice } acomulador += valorF * nucleo[(s + mitadTamano) * tamaNucleo + (t + mitadTamano)]; } } //Guardamos el resultado en la imagen de salida imagenSalida[w * x + y] = (unsigned char) acomulador; } } } else { //Imagen en COLOR imagenSalidaC = (unsigned char *) malloc(w * h * 3); //Resevamos memoria para la imagen de salida (ancho por alto) for (int z = 0; z < 3; z++) { for (int x = 0; x < w; x++) { for (int y = 0; y < h; y++) { //Aplicamos convolución acomulador = 0; for (int s = (mitadTamano * -1); s <= mitadTamano; s++) { for (int t = (mitadTamano * -1); t <= mitadTamano; t++) { fx = x + s; fy = y + t; if (fx < 0 || fy < 0 || fx >= w || fy >= h) { valorF = 0; //Si nos salimos de los límites ponemos 0 } else { valorF = imagenC[w * fx + fy + z * w * h]; //Recorremos la matriz con un solo indice } acomulador += valorF * nucleo[(s + mitadTamano) * tamaNucleo + (t + mitadTamano)]; } } //Guardamos el resultado en la imagen de salida imagenSalidaC[w * x + y + z * w * h] = (unsigned char) acomulador; } } } } /************** GUARDAMOS IMAGEN *************/ if (!color) { if (!gestorImagen.savePgm(argv[2], imagenSalida, w, h, M)) { cout << "ERORR: Guardar imagen resultado en ESCALA DE GRISES" << endl; exit(-1); } } else { if (!gestorImagen.savePgm(argv[2], imagenSalidaC, w, h, M)) { cout << "ERORR: Guardar imagen resultado en COLOR" << endl; exit(-1); } } cout << "IMAGEN OBTENIDA..." << endl; return 0; }
true
54c398048ca9553e9cc14d1751f85ab37205e257
C++
pauldoo/scratch
/PolyRender/AutoTest.cpp
UTF-8
4,091
3.109375
3
[ "ISC" ]
permissive
#include "stdafx.h" #include "AutoTest.h" #include "Auto.h" #include "DestructionAsserter.h" std::string AutoTest::Name() const { return "Auto Test"; } namespace { class DestructorParent : public LinkCount { public: DestructorParent(bool& destroyed) : m_destructionAsserter(new DestructionAsserter(destroyed)) {} Auto<DestructionAsserter> m_destructionAsserter; }; } void AutoTest::Execute() { bool destroyed1 = false; bool destroyed2 = false; // Simple case { Auto<DestructionAsserter> a(new DestructionAsserter(destroyed1)); Assert("Heap object wasn't deleted: Simplest Case", !destroyed1); } Assert("Heap object was deleted: Simplest Case", destroyed1); // One Auto, multiple pointers case { Auto<DestructionAsserter> a = new DestructionAsserter(destroyed1); a = new DestructionAsserter(destroyed2); Assert("Old heap object was deleted : Assignment case", destroyed1); Assert("New heap object wasn't deleted : Assignment case", !destroyed2); } Assert("New heap object was deleted : Assignment case", destroyed2); // default constructor case { Auto<LinkCount> a; a = new DestructionAsserter(destroyed1); } Assert("New heap object was deleted : Default constructor case", destroyed1); // Multiple Auto, multiple pointers, out of order detruction case { DestructionAsserter* ptr = new DestructionAsserter(destroyed1); Auto<DestructionAsserter> a = new DestructionAsserter(destroyed2); { Auto<DestructionAsserter> b = ptr; Assert("First heap object wasn't deleted", !destroyed1); a = ptr; Assert("First heap object wasn't deleted", !destroyed1); } Assert("First heap object wasn't deleted", !destroyed1); } Assert("First heap object was deleted", destroyed1); // Copy constructor testing // Multiple Auto, multiple pointers, out of order destruction case { Auto<DestructionAsserter> a = new DestructionAsserter(destroyed1); { Auto<const DestructionAsserter> b = a; } Assert("Copy Constructor Case: First heap object wasn't deleted", !destroyed1); } Assert("Copy Constructor Case: First heap object was deleted", destroyed1); // Auto assignment testing // Multiple Auto, multiple pointers, out of order destruction case { Auto<DestructionAsserter> a = new DestructionAsserter(destroyed1); { Auto<const DestructionAsserter> b = new DestructionAsserter(destroyed2); b = a; Assert("Assignment Case: First heap object wasn't deleted", !destroyed1); } Assert("Assignment Case: First heap object wasn't deleted", !destroyed1); Assert("Assignment Case: Second heap object was deleted", destroyed2); } Assert("Assignment Case: First heap object was deleted", destroyed1); // Auto assignment to a pointer. { Auto<const DestructionAsserter> a = new DestructionAsserter(destroyed1); a = new DestructionAsserter(destroyed2); Assert("Assignment to Pointer Case: First heap object was deleted", destroyed1); } Assert("Assignment Case: First heap object was deleted", destroyed2); // Test Self assignment { DestructionAsserter* ptr = new DestructionAsserter(destroyed1); Auto<const DestructionAsserter> a = ptr; a = ptr; Assert("Heap object wasn't deleted: Self assignment case", !destroyed1); } // Downcasting of pointer works (compilation check) { Auto<const DestructionAsserter> a = new DestructionAsserter(destroyed1); Auto<const LinkCount> b = new DestructionAsserter(destroyed2); b = a; // pointer access works; a->IsDestroyed(); } // Putting into a vector case { std::vector<Auto<DestructionAsserter> > destructorList; destructorList.push_back(new DestructionAsserter(destroyed1)); destructorList.push_back(new DestructionAsserter(destroyed2)); Assert("Heap object wasn't deleted: vector case", !destroyed1); Assert("Heap object wasn't deleted: vector case", !destroyed2); } Assert("Heap object was deleted: vector case", destroyed1); Assert("Heap object was deleted: vector case", destroyed2); }
true
a4c7efc903f7c56c8c66599e335d860f5ce52528
C++
daodaokami/FeaturesAbout
/src/datas_map.cpp
UTF-8
4,842
2.65625
3
[]
no_license
// // Created by lut on 18-12-25. #include <iostream> #include "datas_map.h" KeyPoints_Map::KeyPoints_Map(int preSize){ this->pre_size = pre_size; this->unm_v_ikps.reserve(this->pre_size); } void KeyPoints_Map::CreateUnorder_Map_KpIndex_vecIndex_IndexKP(vector<cv::KeyPoint> &kps) { int count = 0; for(int i=0; i<kps.size(); i++) { kpIndex index = compress_func_1(kps[i].pt.x, kps[i].pt.y); //向unordermap中插入数据 if(this->unm_v_ikps.find(index) == this->unm_v_ikps.end()){ //是空的 vector<Index_Kp>v_ikps; v_ikps.reserve(3);//只是一个假设的空间大小 v_ikps.push_back(Index_Kp(i, &kps[i])); this->unm_v_ikps.insert(make_pair(index, v_ikps)); } else{ //因为可能有多层可能是不一样的点,所以存在一样的index的点 count ++; //std::cout<<this->unm_v_ikps[index].size()<<std::endl; //cout<<"cur_index "<< index <<endl; //到重复的点了就不可能是空 bool flag_insert = true; for(int j=0; j<this->unm_v_ikps[index].size(); j++){ //查看索引的大小,一般都是1 if(unm_v_ikps[index][j].ptr_kp->pt.x == kps[i].pt.x && unm_v_ikps[index][j].ptr_kp->pt.y == kps[i].pt.y && unm_v_ikps[index][j].ptr_kp->octave == kps[i].octave) { flag_insert = false; cout<<unm_v_ikps[index][j].ptr_kp->pt.x<<"-"<<kps[i].pt.x<<endl <<unm_v_ikps[index][j].ptr_kp->pt.y<<"-"<<kps[i].pt.y<<endl <<unm_v_ikps[index][j].ptr_kp->octave<<"-"<<kps[i].octave<<endl <<unm_v_ikps[index][j].ptr_kp->response<<"-"<<kps[i].response<<endl <<unm_v_ikps[index][j].ptr_kp->class_id<<"-"<<kps[i].class_id<<endl; cerr<<"the same !"<<endl; } } if(flag_insert) unm_v_ikps[index].push_back(Index_Kp(i, &kps[i])); //一些点的位置是一样的,但是因为octave不同,所以表示不同层之间的数据 } } cout<<"count size is "<<count<<endl; //48 次重复 } //返回的是在原始的kps_2中的序列号 KeyPoints_Map::vecIndex KeyPoints_Map::GetKeyPointsIndex(cv::KeyPoint& kp){ kpIndex kp_index = compress_func_1(kp.pt.x, kp.pt.y); if(this->unm_v_ikps.find(kp_index) != this->unm_v_ikps.end()) { for (int j = 0; j < this->unm_v_ikps[kp_index].size(); j++){ //查看索引的大小,一般都是1 if(unm_v_ikps[kp_index][j].ptr_kp->pt.x == kp.pt.x && unm_v_ikps[kp_index][j].ptr_kp->pt.y == kp.pt.y && unm_v_ikps[kp_index][j].ptr_kp->octave == kp.octave){ return unm_v_ikps[kp_index][j].vec_index; } } } return -1; } void KeyPoints_Map::CreateUnorder_Map_OuterIndex_InnerIndex(vector<cv::KeyPoint>& keyps){ for(int outerIndex=0; outerIndex<keyps.size(); outerIndex++){ kpIndex kp_index = compress_func_1(keyps[outerIndex].pt.x, keyps[outerIndex].pt.y); if(this->unm_v_ikps.find(kp_index) != this->unm_v_ikps.end()){ for(int vindex =0; vindex<this->unm_v_ikps[kp_index].size(); vindex++){ if(unm_v_ikps[kp_index][vindex].ptr_kp->pt.x == keyps[outerIndex].pt.x && unm_v_ikps[kp_index][vindex].ptr_kp->pt.y == keyps[outerIndex].pt.y && unm_v_ikps[kp_index][vindex].ptr_kp->octave == keyps[outerIndex].octave){ //这里存储的点与当前的一样 if(this->unm_v_outerIndex2innerIndex.find(outerIndex) == this->unm_v_outerIndex2innerIndex.end()) {//这里要是出现了重复的怎么办?不好,不如直接用map存储 this->unm_v_outerIndex2innerIndex.insert( //通过map,映射这两个空间 make_pair(outerIndex, unm_v_ikps[kp_index][vindex].vec_index));//表示的当前的pt 在kps中的索引序号 } else{ //是不可能出现的,outerIndex是不会重复的! } } } //判断v_ikps中是否存在一样的点,理论上都是存在的,要不然,就是keyps中的数据有误 } else{ cerr<<"can not find this kp index !!!"<<endl; } } } /* * * 当前的数据结构: unordered_map<KpIndex, vector<Index_Kp>> unm_v_ikps; * 通过点的位置信息得到索引 * 存储一个向量,1.vec_index 2.指向的特征点的值 * * */
true
1aaf0c82eb90af479b87686a01eece9e51f2b76e
C++
JasbirCodeSpace/Spider-Task-2
/Data Structures/Linear/Stack/question3.cpp
UTF-8
1,081
3.328125
3
[]
no_license
//Question: https://www.hackerearth.com/practice/data-structures/stacks/basics-of-stacks/practice-problems/algorithm/fun-game-91510e9f/ #include <bits/stdc++.h> using namespace std; void output(int *A, int *B, int n) { stack<int> a, b; for (int i = 0; i < n; i++) { a.push(A[i]); } for (int i = 0; i < n; i++) { b.push(B[i]); } while (!a.empty() && !b.empty()) { if (a.top() > b.top()) { cout << 1 << " "; b.pop(); } else if (a.top() < b.top()) { cout << 2 << " "; a.pop(); } else { cout << 0 << " "; a.pop(); b.pop(); } } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; int A[n], B[n]; for (int i = 0; i < n; i++) { int temp; cin >> temp; A[n - i - 1] = temp; B[i] = temp; } output(A, B, n); return 0; }
true
661b38544c53871e6cb196ce611f243db34aa528
C++
JonMuehlst/CPP2014
/mStack/mStack.h
UTF-8
402
2.921875
3
[ "MIT" ]
permissive
#ifndef MSTACK_H #define MSTACK_H #include <string> using std::string; struct Node { int value; Node * next; }; class MStack { public: MStack(); ~MStack(); void push(int value); int pop(); string toString(); bool isEmpty(); size_t size(); private: Node * head; size_t sSize; }; #endif
true
3a16932b75ee7afa214dd2f8afa1545e62c2d1bd
C++
oNddleo/AlgorithmDataStructure
/sudoku.cpp
UTF-8
1,841
3.25
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <iostream> //Array store value need to find int a[9][9]; int I, J; void process(){ for(int i = 0; i <= 8; i++){ for(int j = 0; j <= 8; j++){ printf("%d ", a[i][j]); } printf("\n"); } printf("---------------------\n"); return; } //Check number in square I, J bool checkSquare(int number){ for(int ii = 0; ii <= 2; ii++) for(int jj = 0; jj <= 2; jj++) if(a[3*I + ii][3*J + jj] == number) return false; return true; } //Chack value at col and row bool check(int number, int row, int col){ // Do number check exist in before row? for(int i = 0; i <= row - 1; i++) if(a[i][col] == number) return false; // Do number check exist in before column? for(int j = 0; j <= col - 1; j++) if(a[row][j] == number) return false; //Change big-sudoku to small-sudoku I = row/3; J = col/3; if(!checkSquare(number)) return false; // return true; } /* void readFile(char* fileName){ FILE* f = fopen(fileName, "r"); for(int i = 1; i <= 9; i++){ for (int j = 1; j <= 9; j++) { fscanf(f, "%d\n", &a[i][j]); } } }*/ void TRY(int row, int col){ if(row == 8 && col == 9){ process(); } else{ if(col == 9){ TRY(row + 1, 0); } else{ for(int v = 1; v <= 9; v++){ if(check(v, row, col)){ int old = a[row][col]; a[row][col] = v; TRY(row, col+1); a[row][col] = old; } } } } } int main(int argc, char** argv){ //n = atoi(argv[2]); //readFile(argv[3]); for (int i = 0; i <= 8; i++) { for(int j = 0; j <= 8; j++){ a[i][j] = 0; } } for (int i = 0; i <= 8; i++) { for(int j = 0; j <= 8; j++){ printf("%d", a[i][j]); } printf("\n"); } printf("Start! \n"); TRY(0, 0); }
true
957a472d9da860673edcd2604881f3e43403f843
C++
keithreynoldsworld/oysterman3
/oysterman3.ino
UTF-8
13,332
2.6875
3
[]
no_license
#include <Servo.h> #include <NewPing.h> #define TRIGGER_PIN 12 // Arduino pin tied to trigger pin on the ultrasonic sensor. #define ECHO_PIN 11 // Arduino pin tied to echo pin on the ultrasonic sensor. #define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm. NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance. /************************************************/ Servo myservo;//create servo object to control a servo /************************************************/ void setup() { Serial.begin(9600); myservo.attach(9);//attachs the servo on pin 9 to servo object myservo.write(0);//back to 0 degrees delay(10000);//wait for a second randomSeed(analogRead(A0)); } /*************************************************/ void loop() { delay(500); // Wait 500ms between pings (about 2 pings/sec). 29ms should be the shortest delay between pings. unsigned int uS = sonar.ping(); // Send ping, get ping time in microseconds (uS). Serial.print("Ping: "); Serial.print(uS / US_ROUNDTRIP_CM); // Convert ping time to distance and print result (0 = outside set distance range, no ping echo) Serial.println("cm"); if (uS / US_ROUNDTRIP_CM<15 && uS / US_ROUNDTRIP_CM != 0){ myservo.write(133);delay(300); myservo.write(130);delay(100); myservo.write(135);delay(100); myservo.write(130);delay(100); myservo.write(135);delay(100); myservo.write(130);delay(100); myservo.write(135);delay(100); myservo.write(130);delay(100); myservo.write(135);delay(100); myservo.write(130);delay(100); myservo.write(135);delay(100); myservo.write(130);delay(50); myservo.write(135);delay(50); myservo.write(130);delay(50); myservo.write(135);delay(50); myservo.write(130);delay(50); myservo.write(135);delay(50); myservo.write(130);delay(50); myservo.write(135);delay(50); myservo.write(130);delay(50); myservo.write(135);delay(50); myservo.write(130);delay(50); myservo.write(135);delay(50); myservo.write(133);delay(300); Spell("iloveyou"); } if (uS / US_ROUNDTRIP_CM>=80 && uS / US_ROUNDTRIP_CM<260){ myservo.write(uS / US_ROUNDTRIP_CM-80);delay(500);} if(uS / US_ROUNDTRIP_CM==263){myservo.write(135);delay(50); myservo.write(130);delay(50); myservo.write(135);delay(50); myservo.write(130);delay(50); myservo.write(135);delay(50); myservo.write(130);delay(50); myservo.write(135);delay(50); myservo.write(130);delay(50); myservo.write(135);delay(50);} if(uS / US_ROUNDTRIP_CM==260){Spell("samurainevermournminutely");} if(uS / US_ROUNDTRIP_CM==261){Spell("levitymournsoverstays");} if(uS / US_ROUNDTRIP_CM==262){Spell("itstaresalonelystareenonamee");Spell("itlivesaloneeyoumaysayiamittnoooyouare");} if(uS / US_ROUNDTRIP_CM>14 && uS / US_ROUNDTRIP_CM <80){ myservo.write(27);delay(500); myservo.write(24);delay(100); myservo.write(30);delay(100); myservo.write(24);delay(100); myservo.write(30);delay(100); myservo.write(24);delay(100); myservo.write(30);delay(100); myservo.write(24);delay(100); myservo.write(30);delay(100); myservo.write(24);delay(100); myservo.write(30);delay(100); myservo.write(24);delay(100); myservo.write(30);delay(100); myservo.write(24);delay(100); myservo.write(30);delay(100); myservo.write(24);delay(100); myservo.write(30);delay(100); myservo.write(24);delay(100); myservo.write(30);delay(100); myservo.write(24);delay(100); myservo.write(30);delay(100); myservo.write(24);delay(100); myservo.write(30);delay(100); myservo.write(24);delay(100); myservo.write(30);delay(100); myservo.write(27);delay(500); myservo.write(119);delay(500); myservo.write(122);delay(100); myservo.write(116);delay(100); myservo.write(122);delay(100); myservo.write(116);delay(100); myservo.write(122);delay(100); myservo.write(116);delay(100); myservo.write(122);delay(100); myservo.write(116);delay(100); myservo.write(122);delay(100); myservo.write(116);delay(100); myservo.write(122);delay(100); myservo.write(116);delay(100); myservo.write(122);delay(100); myservo.write(116);delay(100); myservo.write(122);delay(100); myservo.write(116);delay(100); myservo.write(122);delay(100); myservo.write(116);delay(100); myservo.write(119);delay(500); myservo.write(150);delay(500); myservo.write(153);delay(100); myservo.write(147);delay(100); myservo.write(153);delay(100); myservo.write(147);delay(100); myservo.write(153);delay(100); myservo.write(147);delay(100); myservo.write(153);delay(100); myservo.write(147);delay(100); myservo.write(153);delay(100); myservo.write(147);delay(100); myservo.write(153);delay(100); myservo.write(147);delay(100); myservo.write(153);delay(100); myservo.write(147);delay(100); myservo.write(153);delay(100); myservo.write(147);delay(100); myservo.write(153);delay(100); myservo.write(147);delay(100); myservo.write(153);delay(100); myservo.write(147);delay(100); myservo.write(153);delay(100); myservo.write(147);delay(100); myservo.write(153);delay(100); myservo.write(147);delay(100); myservo.write(153);delay(100); myservo.write(147);delay(100); myservo.write(153);delay(100); myservo.write(147);delay(100); myservo.write(150);delay(500); int ADJECTIVEnumber = random(1,88); int NOUNnumber = random(1,93); if (ADJECTIVEnumber==1){Spell("yeasty");} if (ADJECTIVEnumber==2){Spell("savory");} if (ADJECTIVEnumber==3){Spell("lonely");} if (ADJECTIVEnumber==4){Spell("lovely");} if (ADJECTIVEnumber==5){Spell("vain");} if (ADJECTIVEnumber==6){Spell("easy");} if (ADJECTIVEnumber==7){Spell("yummy");} if (ADJECTIVEnumber==8){Spell("enormous");} if (ADJECTIVEnumber==9){Spell("envious");} if (ADJECTIVEnumber==10){Spell("evil");} if (ADJECTIVEnumber==11){Spell("silver");} if (ADJECTIVEnumber==12){Spell("irate");} if (ADJECTIVEnumber==13){Spell("vomitous");} if (ADJECTIVEnumber==14){Spell("venomous");} if (ADJECTIVEnumber==15){Spell("vile");} if (ADJECTIVEnumber==16){Spell("stale");} if (ADJECTIVEnumber==17){Spell("lame");} if (ADJECTIVEnumber==18){Spell("sour");} if (ADJECTIVEnumber==19){Spell("satin");} if (ADJECTIVEnumber==20){Spell("leary");} if (ADJECTIVEnumber==21){Spell("lemony");} if (ADJECTIVEnumber==22){Spell("sly");} if (ADJECTIVEnumber==22){Spell("smiley");;} if (ADJECTIVEnumber==24){Spell("steamy");} if (ADJECTIVEnumber==25){Spell("verminous");} if (ADJECTIVEnumber==26){Spell("livery");} if (ADJECTIVEnumber==27){Spell("solitary");} if (ADJECTIVEnumber==28){Spell("solemn");} if (ADJECTIVEnumber==29){Spell("lost");} if (ADJECTIVEnumber==30){Spell("lousy");} if (ADJECTIVEnumber==31){Spell("lovey");} if (ADJECTIVEnumber==32){Spell("lunar");} if (ADJECTIVEnumber==33){Spell("stolen");} if (ADJECTIVEnumber==34){Spell("lusty");} if (ADJECTIVEnumber==35){Spell("malty");} if (ADJECTIVEnumber==36){Spell("manly");} if (ADJECTIVEnumber==37){Spell("stormy");} if (ADJECTIVEnumber==38){Spell("snarly");} if (ADJECTIVEnumber==39){Spell("suave");} if (ADJECTIVEnumber==40){Spell("veiny");} if (ADJECTIVEnumber==41){Spell("mean");} if (ADJECTIVEnumber==42){Spell("silent");} if (ADJECTIVEnumber==43){Spell("measly");} if (ADJECTIVEnumber==44){Spell("meaty");} if (ADJECTIVEnumber==45){Spell("menstrual");} if (ADJECTIVEnumber==46){Spell("saintly");} if (ADJECTIVEnumber==47){Spell("melty");} if (ADJECTIVEnumber==48){Spell("sultry");} if (ADJECTIVEnumber==49){Spell("minty");} if (ADJECTIVEnumber==50){Spell("miserly");} if (ADJECTIVEnumber==51){Spell("misty");} if (ADJECTIVEnumber==52){Spell("moist");} if (ADJECTIVEnumber==53){Spell("molten");} if (ADJECTIVEnumber==54){Spell("violent");} if (ADJECTIVEnumber==55){Spell("immoral");} if (ADJECTIVEnumber==56){Spell("tame");} if (ADJECTIVEnumber==57){Spell("mortal");} if (ADJECTIVEnumber==58){Spell("motley");} if (ADJECTIVEnumber==59){Spell("mousey");} if (ADJECTIVEnumber==60){Spell("musty");} if (ADJECTIVEnumber==61){Spell("violet");} if (ADJECTIVEnumber==62){Spell("snorty");} if (ADJECTIVEnumber==63){Spell("naive");} if (ADJECTIVEnumber==64){Spell("natural");} if (ADJECTIVEnumber==65){Spell("neat");;} if (ADJECTIVEnumber==66){Spell("nervous");} if (ADJECTIVEnumber==67){Spell("nervy");} if (ADJECTIVEnumber==68){Spell("salty");} if (ADJECTIVEnumber==69){Spell("rusty");} if (ADJECTIVEnumber==70){Spell("noisy");} if (ADJECTIVEnumber==71){Spell("normal");} if (ADJECTIVEnumber==72){Spell("nosey");} if (ADJECTIVEnumber==73){Spell("tiny");} if (ADJECTIVEnumber==74){Spell("oily");} if (ADJECTIVEnumber==75){Spell("olivey");} if (ADJECTIVEnumber==76){Spell("sumo");} if (ADJECTIVEnumber==77){Spell("ornate");} if (ADJECTIVEnumber==78){Spell("overlusty");} if (ADJECTIVEnumber==79){Spell("rainy");} if (ADJECTIVEnumber==80){Spell("slimy");} if (ADJECTIVEnumber==81){Spell("ravenous");} if (ADJECTIVEnumber==82){Spell("slanty");} if (ADJECTIVEnumber==83){Spell("rational");} if (ADJECTIVEnumber==84){Spell("vital");} if (ADJECTIVEnumber==85){Spell("smart");} if (ADJECTIVEnumber==86){Spell("uneasy");} if (ADJECTIVEnumber==87){Spell("rosey");} if (ADJECTIVEnumber==88){Spell("royal");} if (NOUNnumber==1){Spell("voyeur");} if (NOUNnumber==2){Spell("yeti");} if (NOUNnumber==3){Spell("snot");} if (NOUNnumber==4){Spell("alien");} if (NOUNnumber==5){Spell("snarl");} if (NOUNnumber==6){Spell("smartie");} if (NOUNnumber==7){Spell("ant");} if (NOUNnumber==8){Spell("snail");} if (NOUNnumber==9){Spell("salmon");} if (NOUNnumber==10){Spell("soul");} if (NOUNnumber==11){Spell("eel");} if (NOUNnumber==12){Spell("senorita");} if (NOUNnumber==13){Spell("emulation");} if (NOUNnumber==14){Spell("sternum");} if (NOUNnumber==15){Spell("satyr");} if (NOUNnumber==16){Spell("inmate");} if (NOUNnumber==17){Spell("investor");} if (NOUNnumber==18){Spell("liar");} if (NOUNnumber==19){Spell("laser");} if (NOUNnumber==20){Spell("savior");} if (NOUNnumber==21){Spell("lemon");} if (NOUNnumber==22){Spell("lemur");} if (NOUNnumber==23){Spell("lesion");} if (NOUNnumber==24){Spell("stain");} if (NOUNnumber==25){Spell("lion");} if (NOUNnumber==26){Spell("star");} if (NOUNnumber==27){Spell("loner");} if (NOUNnumber==28){Spell("tsunami");} if (NOUNnumber==29){Spell("lotus");} if (NOUNnumber==30){Spell("loser");} if (NOUNnumber==31){Spell("lover");} if (NOUNnumber==32){Spell("luminary");} if (NOUNnumber==33){Spell("user");} if (NOUNnumber==34){Spell("maestro");} if (NOUNnumber==35){Spell("varmint");} if (NOUNnumber==36){Spell("souvenir");} if (NOUNnumber==37){Spell("soulmate");} if (NOUNnumber==38){Spell("mason");} if (NOUNnumber==39){Spell("marvel");} if (NOUNnumber==40){Spell("urinal");} if (NOUNnumber==41){Spell("venom");} if (NOUNnumber==42){Spell("mayor");} if (NOUNnumber==43){Spell("sun");} if (NOUNnumber==44){Spell("sailor");} if (NOUNnumber==45){Spell("riot");} if (NOUNnumber==46){Spell("melon");} if (NOUNnumber==47){Spell("mentor");} if (NOUNnumber==48){Spell("venus");} if (NOUNnumber==49){Spell("melon");} if (NOUNnumber==50){Spell("rose");} if (NOUNnumber==51){Spell("utensil");} if (NOUNnumber==52){Spell("sultan");} if (NOUNnumber==53){Spell("minotaur");} if (NOUNnumber==54){Spell("toenail");} if (NOUNnumber==55){Spell("simulator");} if (NOUNnumber==56){Spell("mist");} if (NOUNnumber==57){Spell("minuet");} if (NOUNnumber==58){Spell("tease");} if (NOUNnumber==59){Spell("moaner");} if (NOUNnumber==60){Spell("mole");} if (NOUNnumber==61){Spell("monster");} if (NOUNnumber==62){Spell("toilet");} if (NOUNnumber==63){Spell("morsel");} if (NOUNnumber==64){Spell("mortal");} if (NOUNnumber==65){Spell("motel");} if (NOUNnumber==66){Spell("uniter");} if (NOUNnumber==67){Spell("mouse");} if (NOUNnumber==68){Spell("mover");} if (NOUNnumber==69){Spell("mule");} if (NOUNnumber==70){Spell("muse");} if (NOUNnumber==71){Spell("tourist");} if (NOUNnumber==72){Spell("navel");} if (NOUNnumber==73){Spell("nest");} if (NOUNnumber==74){Spell("servant");} if (NOUNnumber==75){Spell("toy");} if (NOUNnumber==76){Spell("novelty");} if (NOUNnumber==77){Spell("nurse");} if (NOUNnumber==78){Spell("novelist");} if (NOUNnumber==79){Spell("nut");} if (NOUNnumber==80){Spell("olive");} if (NOUNnumber==81){Spell("yam");} if (NOUNnumber==82){Spell("train");} if (NOUNnumber==83){Spell("virus");} if (NOUNnumber==84){Spell("ovary");} if (NOUNnumber==85){Spell("tumor");} if (NOUNnumber==86){Spell("nostril");} if (NOUNnumber==87){Spell("runt");} if (NOUNnumber==88){Spell("oysterman");} if (NOUNnumber==89){Spell("ram");} if (NOUNnumber==90){Spell("rat");} if (NOUNnumber==91){Spell("raven");} if (NOUNnumber==92){Spell("realist");} if (NOUNnumber==93){Spell("slayer");} } } void Spell(char WORD[]){ for (int i = 0; i < strlen(WORD); i++){ if(WORD[i]=='i'){myservo.write(7);delay(2000);} if(WORD[i]=='l'){myservo.write(17);delay(2000);} if(WORD[i]=='u'){myservo.write(27);delay(2000);} if(WORD[i]=='v'){myservo.write(38);delay(2000);} if(WORD[i]=='o'){myservo.write(50);delay(2000);} if(WORD[i]=='y'){myservo.write(62);delay(2000);} if(WORD[i]=='s'){myservo.write(74);delay(2000);} if(WORD[i]=='t'){myservo.write(89);delay(2000);} if(WORD[i]=='e'){myservo.write(100);delay(2000);} if(WORD[i]=='r'){myservo.write(119);delay(2000);} if(WORD[i]=='m'){myservo.write(133);delay(2000);} if(WORD[i]=='a'){myservo.write(150);delay(2000);} if(WORD[i]=='n'){myservo.write(170);delay(2000);} } } /**************************************************/
true
7108fc7c5f3bc49eb50bc13a4359beb4588862f9
C++
galoscar07/college2k16-2k19
/2nd Semester/Object Oriented Programming /Lecture/Code/Lecture5_demo/Lecture5_demo/Penguin.h
UTF-8
249
2.84375
3
[]
no_license
#pragma once #include "Animal.h" class Penguin: public Animal { private: std::string type; public: Penguin(std::string _colour, double _weight, std::string _type); ~Penguin(); std::string getType() const; std::string toString() const; };
true
50c1fe3c32cf73a1f0d745dd7d9e85ee0ad0b354
C++
fcvarela/glsg
/glsg/render/Camera.h
UTF-8
2,493
2.796875
3
[ "MIT" ]
permissive
#ifndef GLSG_CAMERA_H #define GLSG_CAMERA_H #include <string> #include <memory> #include <glmext/glmext.h> #include <render/Framebuffer.h> #include <scenegraph/SceneNode.h> #include <component/InputComponent.h> namespace glsg { class Camera { public: typedef std::shared_ptr<Camera> Ptr; typedef std::map<std::string, Ptr> Map; Camera(double vfov, double near, double far); virtual ~Camera(); /** * Set this camera's clear mode (before rendering). */ void setClearMode(GLenum clearMode); /** * Set this camera's clear color. */ void setClearColor(glm::vec4 clearColor); /** * Set this camera's viewport. */ void setViewport(uint32_t width, uint32_t height); /** * Set this camera's framebuffer. */ void setFramebuffer(Framebuffer::Ptr framebuffer); /** * Get this camera's framebuffer */ Framebuffer::Ptr getFramebuffer(); /** * Render this camera to an RTT target. */ void draw(SceneNode::Vec drawables); /** * Sets this camera's scene node. Useful for attaching to scenegraph. * @param scenenode the scene node to set. */ void setSceneNode(SceneNode::Ptr sceneNode); /** * Return this camera's scene node. Useful for attaching to scenegraph. */ SceneNode::Ptr getSceneNode(); /** * Returns this camera's projection matrix. */ glm::dmat4 getProjectionMatrix(); /** * Returns this camera's view matrix. */ glm::dmat4 getViewMatrix(); /** * Sets the camera's input component. */ void setInputComponent(InputComponent *inputComponent) { _sceneNode->setInputComponent(inputComponent); } private: /** * This camera's vertical field of view. */ double _vfov; /** * This camera's near plane distance. */ double _near; /** * This camera's far plane distance. */ double _far; /** * This camera's clearmode. */ GLenum _clearMode; /** * This camera's clear color. */ glm::vec4 _clearColor; /** * This camera's RTT width. */ uint32_t _width; /** * This camera's RTT height. */ uint32_t _height; /** * This camera's framebuffer. */ Framebuffer::Ptr _framebuffer; /** * This camera's scene node. */ SceneNode::Ptr _sceneNode; /** * This camera's projection matrix. */ glm::dmat4 _projectionMatrix; }; } #endif
true
a406da1618ebaf553a906ca3d3fb1d0f55513f72
C++
swethanandha/ok
/42.cpp
UTF-8
522
3.015625
3
[]
no_license
#include<iostream> #include<string> using namespace std; int main() { string str; string str1; int count=0,i,j; cin>>str; cin>>str1; //cout<<str<<endl; for(i=0;str[i]!='\0';i++) { for(j=0;str1[j]!='\0';j++) { if(str[i]==str1[j]) { count++; cout<<str[i]; if(str[i]>str1[j]) { cout<<str[i]; } } } } //cout<<" number of matching characters: "<<count; }
true
54d02f03fd6b6c94b05d8fdd7aa52be3e26c31cf
C++
oflucas/Leetcode-Cpp
/Design/p146_LRU_Cache.cpp
UTF-8
1,300
3.3125
3
[]
no_license
class LRUCache { typedef list<int> key_queue; typedef pair<int, key_queue::iterator> record; typedef unordered_map<int, record> hmap; int capacity; key_queue lru_q; hmap cache; public: LRUCache(int capacity) : capacity(capacity) { } int get(int key) { auto it = cache.find(key); if (it == cache.end()) return -1; refresh(it); return it->second.first; } void put(int key, int value) { auto it = cache.find(key); if (it == cache.end()) { if (cache.size() == capacity) { cache.erase(lru_q.back()); lru_q.pop_back(); } lru_q.push_front(key); cache.emplace(key, make_pair(value, lru_q.begin())); } else { refresh(it); it->second.first = value; } } void refresh(hmap::iterator it) { int key = it->first; record& r = it->second; lru_q.erase(r.second); lru_q.push_front(key); r.second = lru_q.begin(); } }; /** * * Your LRUCache object will be instantiated and called as such: * * LRUCache obj = new LRUCache(capacity); * * int param_1 = obj.get(key); * * obj.put(key,value); * */
true
c885d9688c300daaab2c09d8c301e3c0867eae78
C++
sunny-aguilar/matrix-calculator
/determinant.cpp
UTF-8
1,541
3.671875
4
[]
no_license
/********************************************************************* ** Author: Sandro Aguilar ** Date: Jan 2019 ** Description: A function that calculates the determinant of a ** 2x2 or 3x3 matrix calculator. Returns the ** calculated value. *********************************************************************/ #include "determinant.hpp" int determinant(int **matrixPtr, int size) { // variables to hold user entered values int determinant = 0, a, b, c, d, e, f, g, h, i; // calcualte values on 2 x 2 grid if (size == 2) { // formula values from array a = matrixPtr[0][0]; b = matrixPtr[0][1]; c = matrixPtr[1][0]; d = matrixPtr[1][1]; // calculate determinant for size 2 matrix // |A| = ad - bc determinant = (a*d) - (b*c); } // calculate determinant on a 3 x 3 grid else if (size == 3) { // formula values from array a = matrixPtr[0][0]; b = matrixPtr[0][1]; c = matrixPtr[0][2]; d = matrixPtr[1][0]; e = matrixPtr[1][1]; f = matrixPtr[1][2]; g = matrixPtr[2][0]; h = matrixPtr[2][1]; i = matrixPtr[2][2]; // calculate determinant for size 3 matrix // |A| = a(ei − fh) − b(di − fg) + c(dh − eg) determinant = a*((e*i) - (f*h)) - b*((d*i) - (f*g)) + c*((d*h) - (e*g)); } // return determinant value return determinant; }
true
c93ab29691949989d6d9967aea9d6f3ce79f1d09
C++
saching13/Coding-challenge
/Algoexpert/moveElementToEnd.cpp
UTF-8
421
3.296875
3
[]
no_license
#include <vector> using namespace std; vector<int> moveElementToEnd(vector<int> array, int toMove) { sort(array.begin(),array.end()); int left = 0; int right = array.size()-1; while(right > left){ if(array[left] == toMove){ int temp = array[left]; array[left] = array[right]; array[right] = temp; left++; right--; } else {//if(array(left != toMove)) left++; } } return array; }
true
03fd4f236c4cb44e3d7e03b7724168801fbcfff9
C++
gwanhyeon/algorithm_study
/beakjoon_algorithm/beakjoon_algorithm/CodingTestExam/selection_sort.cpp
UTF-8
1,641
3.625
4
[]
no_license
//#include <stdio.h> //#include <iostream> //using namespace std; //void selection_sort(int arr[],int size){ // int min = 0; // int temp = 0; // // for(int i=0; i<size; i++){ // // 맨처음값을 min으로 넣는다고 생각하면된다 // min = i; // for(int j=i+1; j<size; j++){ // // 최소값 변경 arr[min]보다 작으므로 // if(arr[j] < arr[min]){ // min = j; // } // } // // 정렬코드 // temp = arr[i]; // arr[i] = arr[min]; // arr[min] = temp; // // } //} //int main(void){ // // int arr[5] = {7,1,2,3,4}; // int size = sizeof(arr) / sizeof(int); // selection_sort(arr,size); // // for(int i=0; i<size; i++){ // cout << arr[i]; // } // //} // // 10 * (10 + 1) / 2 의 시간복잡도가 나온다 다시 말하면 n * ( n + 1 ) / 2 #include <stdio.h> #include <iostream> using namespace std; int main(void){ int index,min,size; int arr[5] = {6,1,4,7,2}; size = sizeof(arr) / sizeof(int); for(int i=0; i<size; i++){ // 중요 min값을 처음부터 init 하는것이 아니다. min = 99999; for(int j=i; j<size; j++){ // min보다 값이 작을경우 min값을 새로 저장시키고, 현재 j의 인덱스값을 index 변수에 저장한다 if(min > arr[j]){ min = arr[j]; index = j; } } // swap int temp = arr[i]; arr[i] = arr[index]; arr[index] = temp; } for(int i=0; i<size; i++){ cout << arr[i]; } }
true
c7b7c4d0eecf10fab9a9907501b8d4e3c2378d76
C++
MolinDeng/PAT
/1110.cpp
UTF-8
968
2.890625
3
[]
no_license
#include <cstdio> #include <iostream> #include <vector> #include <queue> #include <string> using namespace std; struct Node { int left; int right; }; int main() { int N, root = 0; scanf("%d", &N); vector<Node> Tree(N); vector<bool> isroot(N, true); for(int i = 0; i < N; i++) { char ls[5], rs[5]; scanf("%s %s", ls, rs); int li = ls[0] == '-' ? -1 : stoi(ls); int ri = rs[0] == '-' ? -1 : stoi(rs); Tree[i] = {li, ri}; if(li != -1) isroot[li] = false; if(ri != -1) isroot[ri] = false; } for(int i = 0; i < N; i++) { if(isroot[i]) { root = i; break; } } vector<int> res; res.push_back(root); int i = 0; for( ; res[i] != -1; i++) { res.push_back(Tree[res[i]].left); res.push_back(Tree[res[i]].right); } if(i != N) printf("NO %d", root); else printf("YES %d", res[N-1]); return 0; }
true
83391fc430f12597b91479902b42c534bae1d231
C++
Crawping/cDesktop
/Player.h
UTF-8
706
2.78125
3
[]
no_license
#pragma once #include "Object.h" #include "Events.h" class EventData; class TaskData; class Player : public Object { public: Player(std::string name, Position pos); ~Player(void); void onKeyboardKeyPress(const KeyPressEvent&, EventData*); // calls MoveEvent void onPlayerMove(const PlayerMoveEvent&, EventData*); // calls PlayerHurt, ApplyPoison void onPlayerHurt(const PlayerHurtEvent&, EventData*); // calls PlayerDie int getType() { return Object::TYPES::PLAYER; } int getHealth() { return health; } void lock(); void unlock(TaskData *); EventData *keyPressEvent; EventData *moveEvent; EventData *hurtEvent; EventData *poisonedEvent; private: int health; // 0-100 bool locked; };
true
55dc2a16e9d37b0d13c1b98f6d9374b93c1a3ad3
C++
The4Bros/Starcraft_AI
/Motor2D/UI_PositionManagement.cpp
UTF-8
1,533
2.828125
3
[]
no_license
/* void UIElement::Center(UIElement* element) { SDL_Rect elementRect = element->GetWorldRect(); int centerX = elementRect.x + elementRect.w / 2; int centerY = elementRect.y + elementRect.h / 2; SetGlobalPosition(centerX - collider.w / 2, centerY - collider.h / 2); } void UIElement::Center(iPoint point) { SetGlobalPosition(point.x - collider.w / 2, point.y - collider.h / 2); } void UIElement::Center_x(UIElement* element) { int centerX = element->GetWorldRect().x + element->collider.w / 2; int currentY = GetWorldRect().y; SetGlobalPosition(centerX - collider.w / 2, currentY); } void UIElement::Center_x(int x) { SDL_Rect rect = GetWorldRect(); SetGlobalPosition(x - collider.w / 2, rect.y); } void UIElement::Center_y(UIElement* element) { int centerY = element->GetWorldRect().y + element->collider.h / 2; int currentX = GetWorldRect().x; SetGlobalPosition(currentX, centerY - collider.h / 2); } void UIElement::Center_y(int y) { SDL_Rect rect = GetWorldRect(); SetGlobalPosition(rect.x, y - collider.h); } void UIElement::Align(UIElement* element) { SDL_Rect elementRect = element->GetWorldRect(); SetGlobalPosition(elementRect.x, elementRect.y); } void UIElement::Align_x(UIElement* element) { SDL_Rect elementRect = element->GetWorldRect(); int currentY = GetWorldRect().y; SetGlobalPosition(elementRect.x, currentY); } void UIElement::Align_y(UIElement* element) { SDL_Rect elementRect = element->GetWorldRect(); int currentX = GetWorldRect().x; SetGlobalPosition(currentX, elementRect.y); } */
true
e104d45c0884ddc3060c6021ce126ca8ae9909a7
C++
Valzur/Pinball
/Utility/PixelPerfectCollision.cpp
UTF-8
640
2.78125
3
[]
no_license
#include "PixelPerfectCollision.h" Vector2D PixelPerfectCollision::CheckCollision(Ball ball, Sprite sprite) { Vector2D Acc={0,0}; image =sprite.getTexture()->copyToImage(); size=image.getSize(); ballPosition=ball.getCenter(); for (int i = 0; i < size.x; i++) { for (int j = 0; j < size.y; j++) { if (pow((pow(i+size.x, 2) + pow(j+size.y, 2)), 0.5) <= ball.getRadius()) { Acc = {ballPosition.x - i, ballPosition.y - j}; break; } } if (Acc.x!=0 | Acc.y!=0) break; } Acc={-Acc.x,-Acc.y}; return Acc; }
true
f8d8d7556112423517be4e6331bb7e15b44a741d
C++
Nblhshda/ProgrammingAssignmentClassScheduling
/PRIORITY(NON-PREEMPTIVE).cpp
UTF-8
3,052
3.5
4
[]
no_license
/* MAISARAH BINTI HAMZAH 1810325 NUR MAISARA BINTI AHMAD RASID 1818356 NOR NABILAH SHUHADA BINTI MOHD KAMAL 1817510 SITI NUR AISHAH BINTI SULAIMAN 1816454 CSC3401 Operating System Section 5 */ // C++ implementation for non-preemptive Priority Scheduling #include <bits/stdc++.h> using namespace std; struct Course { int ccode; // course code int duration; // class duration int priority; //priority int arrival_time; //prefered arrival time }; bool comp(Course a, Course b) { if(a.priority == b.priority) return (a.arrival_time < b.arrival_time); else return (a.priority < b.priority); } void findWaitingTime(Course proc[], int wt[], int n) { // declaring service array that stores cumulative burst time int service[n]; // Initilising initial elements of the arrays service[0] = proc[0].arrival_time; wt[0]=0; for(int i = 1; i < n; i++) { service[i] = proc[i-1].duration + service[i-1]; wt[i] = service[i] - proc[i].arrival_time; // If waiting time is negative, change it into zero if(wt[i]<0) { wt[i]=0; } } } void findTurnAroundTime(Course proc[], int n, int tat[],int wt[]) { // Filling turnaroundtime array for(int i=0; i<n; i++) { tat[i]=proc[i].duration + wt[i]; } } void priorityScheduling(Course proc[], int n) { cout << "Output for Priority Non-Preemptive scheduling algorithm" << endl; sort(proc, proc + n, comp); cout<< "\nOrder of the course code: \n"; for (int i = 0 ; i < n; i++) cout << proc[i].ccode <<" " ; //Declare waiting time and turnaround time array int wt[n],tat[n]; double wavg=0,tavg=0; // Function call to find waiting time array findWaitingTime(proc, wt, n); //Function call to find turnaround time findTurnAroundTime(proc, n, tat, wt); int stime[n],ctime[n]; stime[0] = proc[0].arrival_time; ctime[0]=stime[0]+tat[0]; int j=1; // calculating starting and ending time for(int i = 1; i < n; i++) { stime[i]=ctime[i-1]; ctime[i]=stime[i]+tat[i]-wt[i]; } cout<<"\n\nCourse Code\tBurst time\tPriority\tArrival time\tWaiting Time\tTurn-Around Time\tCompletion time"<<endl; // display the process details for(int i=0; i<n; i++) { wavg += wt[i]; tavg += tat[i]; cout<<proc[i].ccode<<"\t\t"<<proc[i].duration<<"\t\t" <<proc[i].priority<<"\t\t\t"<<proc[i].arrival_time<<"\t\t" <<wt[i]<<"\t\t"<<tat[i]<<"\t\t\t"<<ctime[i]<<endl; } // display the average waiting time //and average turn around time cout<<"\nAverage waiting time is : "; cout<<wavg/(float)n<<endl; cout<<"average turnaround time : "; cout<<tavg/(float)n<<endl; } int main() { Course proc[] = {{2201,3,2,0}, {3401, 5, 6,2}, {1103,4,3,1}, {2302,2,5,4},{2602,9,7,6},{3102,4,4,5},{2011,10,10,7}}; int n = sizeof proc / sizeof proc[0]; priorityScheduling(proc, n); return 0; }
true
1d1faeac54fbd9b1a3c115ef4af655a20189bdbd
C++
vrcordoba/Klondike
/src/views/text/SaveTextView.cpp
UTF-8
874
2.53125
3
[]
no_license
#include "SaveTextView.hpp" #include "SaveController.hpp" #include "IO.hpp" #include "YesNoDialog.hpp" namespace Views { SaveTextView::SaveTextView() : saveFileNameM() { } SaveTextView::~SaveTextView() { } void SaveTextView::interact(Controllers::SaveController* saveController) { if (saveFileNameM.empty()) { askForName(saveController); } saveController->saveGame(saveFileNameM); } void SaveTextView::askForName(Controllers::SaveController* saveController) { bool askAgain; do { Utils::IO& io = Utils::IO::getInstance(); saveFileNameM = io.readString("Write now the name of the file you want to save"); if (saveController->fileAlreadyExists(saveFileNameM)) askAgain = not Utils::YesNoDialog("File already exist. Do you want to override").read(); else askAgain = false; } while (askAgain); } }
true
815a8399ad2f85f41ef189c2302563bfbf117bed
C++
xuxiandi/LiquidFL
/current/gameswf/lfl_TAG_PlaceObject2_impl.h
UTF-8
1,395
2.53125
3
[]
no_license
// lfl_TAG_PlaceObject2_impl.h - by Timur Losev 2010 // For embedding event handlers in place_object_2 #ifndef __lfl_TAG_PlaceObject2_impl_h__ #define __lfl_TAG_PlaceObject2_impl_h__ #include "lfl_execute_tag.h" namespace gameswf { class CTAGPlaceObject2: public execute_tag { private: int m_iTagType; lfl_string m_CharacterName; float m_fRatio; cxform m_ColorTransform; matrix m_Matrix; bool m_bHasMatrix; bool m_bHasCxform; int m_iDepth; Uint16 m_uCharacterId; Uint16 m_uClipDepth; Uint8 m_uBlendMode; enum E_PLACE_TYPE { EPT_PLACE = 0, EPT_MOVE, EPT_REPLACE }; E_PLACE_TYPE m_ePlaceType; array<swf_event*> m_EventHandlers; public: //ctor CTAGPlaceObject2(); //dtor ~CTAGPlaceObject2(); void read(player* pPlayer, lfl_stream* pInStream, int iTagType, int iMovieVersion); // Place/move/whatever our object in the given movie. void execute(character *pCharacter); void execute_state(character *pCharacter){ this->execute(pCharacter); } void execute_state_reverse(character *pCharacter, int iFrame); // "depth_id" is the 16-bit depth & id packed into one 32-bit int. virtual uint32 get_depth_id_of_replace_or_add_tag() const; }; //CTAGPlaceObject2 } //gameswf #endif //__lfl_TAG_PlaceObject2_impl_h__
true
a3696c56fb40e9549dfb4e6a73b672f39f777f10
C++
liuyaqiu/LeetCode-Solution
/48.cpp
UTF-8
1,106
3.421875
3
[]
no_license
#include <iostream> #include <string> #include <vector> #include <utility> using namespace std; void rotate(vector<vector<int>>& matrix) { int len = matrix.size(); vector<vector<int>> res; for(int j = 0; j < len; j += 1) { vector<int> row; for(int i = 0; i < len; i += 1) { row.push_back(matrix[len - 1 - i][j]); } res.push_back(row); } matrix = res; } void print(vector<int> res) { for(auto iter = res.begin(); iter != res.end(); iter += 1) { cout << *iter << " "; } cout << endl; } int main() { int n; cout << "Please input the number: "; cin >> n; vector<vector<int>> matrix; int val; for(int i = 0; i < n; i += 1) { vector<int> line; for(int j = 0; j < n; j += 1) { cin >> val; line.push_back(val); } matrix.push_back(line); } for(auto iter = matrix.begin(); iter != matrix.end(); iter += 1) print(*iter); rotate(matrix); for(auto iter = matrix.begin(); iter != matrix.end(); iter += 1) print(*iter); return 0; }
true
acfd962e5d5ff1a21814c968be76896f7f430a8f
C++
Naveen110501/Hackerrank
/lab ater vector.cpp
UTF-8
1,439
3.6875
4
[]
no_license
#include<iostream> #include<cstdio> #include<istream> using namespace std; class employee_data; class employee_data { int id; float salary; int acc_num,bal; string name; public: employee_data() { salary=0.00; } friend float pay_sal(employee_data&,int ); friend istream &operator >>(istream &in ,employee_data &obj); friend ostream &operator <<(ostream &out,employee_data &obj); }; istream& operator >>(istream &in ,employee_data &obj) { in>>obj.id>>obj.acc_num>>obj.name>>obj.bal; return in; } ostream &operator <<(ostream &out,employee_data &obj) { out<<"\nEMPLOYEE ID = "<<obj.id <<"\nACCOUNT NUMBER = "<<obj.acc_num <<"\nNAME = " <<obj.name <<"\nBALANCE = "<<obj.bal <<"\nSALARY = "<<obj.salary; return out; } float pay_sal(employee_data &s1,int sal) { s1.salary=sal*1.0; return s1.salary; } class company { int sala; public: company(int basic,int all) { sala=basic+all; } int get_sala() { return sala;} // friend float pay_sal(employee_data,int ,int ); }; int main() { employee_data obj; cout<<"ENTER EMPLOYEE ID , ACCOUNT NUMBER , NAME, BALANCE :\n"; cin>>obj; cout<<obj; cout<<"\nENTER THE BASIC PAY : "; int basic; cin>>basic; cout<<"ENTER THE OTHER ALLOWANCES: "; int all; cin>>all; company obj_com(basic,all); float salary=pay_sal(obj,obj_com.get_sala()); cout<<"CALCULATED SALARY : "<<salary<<endl; cout<<obj; return 0; }
true
9eca38d76600f967c17a36c2d96949f936c791fc
C++
mamepika426/Atcoder
/atcoder_problems/C_GetAC.cpp
UTF-8
1,053
2.703125
3
[]
no_license
#include <iostream> #include <bits/stdc++.h> #include <vector> using namespace std; vector<int> starting_indices_AC(int N, string S) { vector<int> indices; for(int index=0; index < N-1; index++) { if(S.substr(index, 2) == "AC"){ indices.push_back(index); } } return indices; } int main() { int N, Q; cin >> N >> Q; string S; cin >> S; vector<int> ok_indices = starting_indices_AC(N, S); for(int q=0; q<Q; q++) { // int ans = 0; int l, r; cin >> l >> r; // for(int index=l-1; index < r-1; index++) { // if(ok_indices.find(index) != ok_indices.end()) ans++; // } auto iter1 = lower_bound(ok_indices.begin(), ok_indices.end(), l-1); auto iter2 = upper_bound(ok_indices.begin(), ok_indices.end(), r-2); // auto val1 = iter1 - ok_indices.begin(); // auto val2 = iter2 - ok_indices.begin(); int ans = iter2 - iter1; cout << ans << endl; } return 0; }
true
f7cb8ee3967276184bf96fba6da5e4217d7e548f
C++
cuzdav/baneful
/src/levelgen/src/phase1/test/TestGraphCreator.cpp
UTF-8
11,531
2.5625
3
[]
no_license
#include "AdjacencyMatrix.hpp" #include "AdjacencyMatrixPrinter.hpp" #include "Color.hpp" #include "GraphCreator.hpp" #include "jsonlevelconfig.hpp" #include "jsonutil.hpp" #include "graph_utils.hpp" #include "color_constants.hpp" #include "boost/json.hpp" #include "gtest/gtest.h" #include <algorithm> namespace test { using namespace json; using namespace std::literals; using StrVec = std::vector<std::string>; StrVec vertex_names(boost::json::object lvl) { GraphCreator gc(lvl); Vertices const & vertices = gc.get_vertices(); std::vector<std::string> actual{vertices.names_begin(), vertices.names_end()}; std::sort(begin(actual), end(actual)); return actual; } StrVec expected(StrVec args) { std::sort(begin(args), end(args)); return args; } TEST(TestGraphCreator, simple_rule1) { auto lvl = level(rules(from("a") = to(""))); auto actual = vertex_names(lvl); EXPECT_EQ(expected({color::test::short_string::rect_fm + "a", color::test::short_string::noth_to + "!"}), actual); } TEST(TestGraphCreator, simple_rule2) { auto lvl = level(rules(from("abc") = to("bb"))); // "abc" is the id of the vertex starting at 'a' // "bc" is the id of the vertex starting at 'b' // "c" is the id of the vertex starting at 'c' auto actual = vertex_names(lvl); EXPECT_EQ(expected({color::test::short_string::rect_fm + "abc", color::test::short_string::rect_fm + "bc", color::test::short_string::rect_fm + "c", color::test::short_string::rect_to + "bb", color::test::short_string::rect_to + "b"}), actual); } TEST(TestGraphCreator, rule3_with_transform) { // clang-format off auto lvl = level( rules(from("a") = to("b")), type_overrides( std::pair("a", rotating_colors("cd")))); // clang-format on auto actual = vertex_names(lvl); EXPECT_EQ(expected({color::test::short_string::cust_fm + "a", color::test::short_string::rect_to + "b"}), actual); } TEST(TestGraphCreator, rule4_wc_backref_colors) { // clang-format off auto lvl = level( rules(from(".") = to("121"), from("a") = to(""))); // clang-format on using namespace color::test::short_string; auto actual = vertex_names(lvl); EXPECT_EQ(expected({ rect_fm + "a", noth_to + "!", wild_fm + ".", bref_to + "121", // id of the first 1 bref_to + "21", // id of the 2 bref_to + "1", // id of the 2nd 1 (in chain 121) }), actual); } TEST(TestGraphCreator, type_override_sets_up_custom_colors) { // clang-format off auto lvl = level(rules(from("a") = to("b")), type_overrides( std::pair("a", rotating_colors("cd")), std::pair("b", rotating_colors("cde")), std::pair("c", rotating_colors("abc")))); // clang-format on GraphCreator gc(lvl); Transforms const & transforms = gc.get_transforms(); StrVec xform_names(transforms.begin(), transforms.end()); std::sort(xform_names.begin(), xform_names.end()); EXPECT_EQ(StrVec({"RotCol:abc", "RotCol:cd", "RotCol:cde"}), xform_names); color::FinalColor fr_a_color = transforms.to_color('a', RuleSide::FROM); color::FinalColor to_a_color = transforms.to_color('a', RuleSide::TO); color::FinalColor fr_b_color = transforms.to_color('b', RuleSide::FROM); color::FinalColor to_b_color = transforms.to_color('b', RuleSide::TO); color::FinalColor fr_c_color = transforms.to_color('c', RuleSide::FROM); color::FinalColor to_c_color = transforms.to_color('c', RuleSide::TO); using namespace color::test::short_string; EXPECT_EQ(cust_fm, to_short_string(fr_a_color)); EXPECT_EQ(cust_to, to_short_string(to_a_color)); EXPECT_EQ(cust2_fm, to_short_string(fr_b_color)); EXPECT_EQ(cust2_to, to_short_string(to_b_color)); EXPECT_EQ(cust3_fm, to_short_string(fr_c_color)); EXPECT_EQ(cust3_to, to_short_string(to_c_color)); } TEST(TestGraphCreator, proper_edges) { // clang-format off auto lvl = level(rules(from("a") = to("b", "cc"), from("bb") = to(""), from("c") = to("bb") )); // clang-format on GraphCreator gc(lvl); Transforms const & transforms = gc.get_transforms(); Vertices const & verts = gc.get_vertices(); // jsonutil::pretty_print(std::cout, lvl); auto has_edge = [&](auto vert_name1, auto vert_name2) { int from_idx = verts.index_of_internal_name(vert_name1); int to_idx = verts.index_of_internal_name(vert_name2); return gc.has_edge(from_idx, to_idx); }; using namespace color::test::short_string; EXPECT_TRUE(has_edge(rect_fm + "a", rect_to + "b")); EXPECT_TRUE(has_edge(rect_fm + "a", rect_to + "cc")); EXPECT_TRUE(has_edge(rect_fm + "bb", rect_fm + "b")); EXPECT_TRUE(has_edge(rect_fm + "b", noth_to + "!")); EXPECT_TRUE(has_edge(rect_to + "cc", rect_to + "c")); EXPECT_TRUE(has_edge(rect_fm + "c", rect_to + "bb")); EXPECT_TRUE(has_edge(rect_to + "bb", rect_to + "b")); EXPECT_FALSE(has_edge(rect_fm + "a", rect_fm + "bb")); EXPECT_FALSE(has_edge(rect_fm + "a", rect_fm + "b")); EXPECT_FALSE(has_edge(rect_fm + "a", noth_to + "!")); EXPECT_FALSE(has_edge(rect_fm + "a", rect_to + "bb")); EXPECT_FALSE(has_edge(rect_fm + "a", rect_to + "c")); EXPECT_FALSE(has_edge(rect_fm + "bb", rect_fm + "bb")); EXPECT_FALSE(has_edge(rect_fm + "bb", rect_fm + "a")); EXPECT_FALSE(has_edge(rect_fm + "bb", rect_fm + "c")); EXPECT_FALSE(has_edge(rect_fm + "bb", rect_to + "b")); EXPECT_FALSE(has_edge(rect_fm + "bb", rect_to + "cc")); EXPECT_FALSE(has_edge(rect_fm + "bb", rect_to + "c")); EXPECT_FALSE(has_edge(rect_fm + "bb", rect_to + "bb")); EXPECT_FALSE(has_edge(rect_fm + "bb", rect_to + "b")); EXPECT_FALSE(has_edge(rect_fm + "bb", noth_to + "!")); EXPECT_FALSE(has_edge(rect_fm + "b", rect_fm + "bb")); EXPECT_FALSE(has_edge(rect_fm + "b", rect_fm + "a")); EXPECT_FALSE(has_edge(rect_fm + "b", rect_to + "b")); EXPECT_FALSE(has_edge(rect_fm + "b", rect_fm + "c")); EXPECT_FALSE(has_edge(rect_fm + "b", rect_to + "cc")); EXPECT_FALSE(has_edge(rect_fm + "b", rect_to + "c")); EXPECT_FALSE(has_edge(rect_fm + "b", rect_fm + "bb")); EXPECT_FALSE(has_edge(rect_fm + "b", rect_fm + "b")); EXPECT_FALSE(has_edge(rect_fm + "c", rect_fm + "bb")); EXPECT_FALSE(has_edge(rect_fm + "c", rect_fm + "a")); EXPECT_FALSE(has_edge(rect_fm + "c", rect_fm + "b")); EXPECT_FALSE(has_edge(rect_fm + "c", rect_fm + "c")); EXPECT_FALSE(has_edge(rect_fm + "c", rect_to + "cc")); EXPECT_FALSE(has_edge(rect_fm + "c", rect_to + "c")); EXPECT_FALSE(has_edge(rect_fm + "c", noth_to + "!")); EXPECT_FALSE(has_edge(rect_fm + "c", rect_fm + "b")); } TEST(TestGraphCreator, using_common_vertices) { // clang-format off auto lvl = level(rules(from("a") = to("bc"), from("b") = to("c") )); // clang-format on GraphCreator gc(lvl); Transforms const & transforms = gc.get_transforms(); Vertices const & verts = gc.get_vertices(); using namespace color::test::short_string; int frect_a = verts.index_of_internal_name(rect_fm + "a"); int frect_b = verts.index_of_internal_name(rect_fm + "b"); int trect_bc = verts.index_of_internal_name(rect_to + "bc"); int trect_c = verts.index_of_internal_name(rect_to + "c"); EXPECT_TRUE(gc.has_edge(frect_a, trect_bc)); EXPECT_TRUE(gc.has_edge(trect_bc, trect_c)); EXPECT_TRUE(gc.has_edge(frect_b, trect_c)); } TEST(TestGraphCreator, remove_vertex1) { auto lvl = level(rules(from("a") = to("bc"))); GraphCreator gc(lvl); Transforms const & transforms = gc.get_transforms(); matrix::AdjacencyMatrix const & adjmtx = gc.get_adjacency_matrix(); Vertices & verts = gc.get_vertices(); int a_idx = verts.index_of_internal_name("FRa"); int bc_idx = verts.index_of_internal_name("TRbc"); int c_idx = verts.index_of_internal_name("TRc"); int doomed_idx = bc_idx; ASSERT_NE(-1, a_idx); ASSERT_NE(-1, bc_idx); ASSERT_NE(-1, c_idx); vertex::Vertex orig_a = verts[a_idx]; vertex::Vertex orig_bc = verts[bc_idx]; vertex::Vertex orig_c = verts[c_idx]; EXPECT_EQ(1, size(orig_a)); // num_blocks EXPECT_EQ(1, size(orig_bc)); // num_blocks EXPECT_EQ(1, size(orig_c)); // num_blocks ASSERT_EQ(3, verts.names_size()); ASSERT_EQ(3, adjmtx.size()); EXPECT_TRUE(adjmtx.has_edge(a_idx, bc_idx)); EXPECT_TRUE(adjmtx.has_edge(bc_idx, c_idx)); EXPECT_FALSE(adjmtx.has_edge(a_idx, c_idx)); EXPECT_FALSE(adjmtx.has_edge(c_idx, bc_idx)); EXPECT_FALSE(adjmtx.has_edge(c_idx, a_idx)); EXPECT_FALSE(adjmtx.has_edge(bc_idx, a_idx)); gc.compress_vertices(); int a_idx_compressed = verts.index_of_internal_name("FRa"); // From Rect a int bc_idx_compressed = verts.index_of_internal_name("TRbc"); // To Rect bc int c_idx_compressed = verts.index_of_internal_name("TRc"); // To Rect c ASSERT_NE(-1, a_idx_compressed); ASSERT_NE(-1, bc_idx_compressed); vertex::Vertex a_compressed = verts[a_idx_compressed]; vertex::Vertex bc_compressed = verts[bc_idx_compressed]; EXPECT_EQ(2, verts.names_size()); EXPECT_EQ(2, adjmtx.size()); EXPECT_EQ(1, size(a_compressed)); // num_blocks EXPECT_EQ(2, size(bc_compressed)); // num_blocks // should be merged into bc EXPECT_EQ(-1, c_idx_compressed); vertex::Vertex expected_bc = add_block(orig_bc, get_block(orig_c, 0)); EXPECT_EQ(expected_bc, bc_compressed); EXPECT_TRUE(adjmtx.has_edge(a_idx_compressed, bc_idx_compressed)); EXPECT_FALSE(adjmtx.has_edge(bc_idx_compressed, a_idx_compressed)); } TEST(TestGraphCreator, remove_group_by_color) { // clang-format off auto lvl = level(rules(from("a") = to("bc"), from("b..") = to(""))); // clang-format on GraphCreator gc(lvl); matrix::AdjacencyMatrix const & adjmtx = gc.get_adjacency_matrix(); Vertices & verts = gc.get_vertices(); int w_idx = verts.index_of_internal_name("F.."); // from wild . int c_idx = verts.index_of_internal_name("TRc"); // to rect c EXPECT_NE(-1, w_idx); EXPECT_NE(-1, c_idx); gc.compress_vertices().group_by_colors(); int a_idx = verts.index_of_internal_name("FRa"); // from rect a int bc_idx = verts.index_of_internal_name("TRbc"); // to rect b, c follows int bww_idx = verts.index_of_internal_name("FRb.."); // from rect b, . follows int ww_idx = verts.index_of_internal_name("F..."); // from wild ., . follows int noth_idx = verts.index_of_internal_name("T!!"); // to nothing w_idx = verts.index_of_internal_name("F.."); // from wild . c_idx = verts.index_of_internal_name("TRc"); // to rect c // bww and ww - diff in color, can't compress EXPECT_NE(-1, a_idx); EXPECT_NE(-1, bc_idx); EXPECT_NE(-1, bww_idx); EXPECT_NE(-1, ww_idx); EXPECT_NE(-1, noth_idx); EXPECT_EQ(-1, c_idx); // c doesn't exist after compression EXPECT_EQ(-1, w_idx); // (last) . doesn't exist after compression EXPECT_TRUE(adjmtx.has_edge(a_idx, bc_idx)); EXPECT_TRUE(adjmtx.has_edge(bww_idx, ww_idx)); EXPECT_TRUE(adjmtx.has_edge(ww_idx, noth_idx)); } } // namespace test
true
d46f25bc91fb98a864a0d72371995db2bf503c79
C++
LeiShi1313/leetcode
/leetcode_cpp/49_group_anagrams.cpp
UTF-8
786
3.25
3
[]
no_license
// // Created by Dicky Shi on 6/13/17. // #include <iostream> #include <vector> #include <map> #include <unordered_map> #include <string> #include <ctime> #include "utils.h" using namespace std; class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { unordered_map<string, vector<string>> mem; for (auto& str: strs) { string s = str; sort(s.begin(), s.end()); mem[s].push_back(str); } vector<vector<string>> ret; for (auto &k: mem) { ret.push_back(k.second); } return ret; } }; int main() { vector<string> strs; strs = {"eat", "tea", "tan", "ate", "nat", "bat"}; cout << Solution().groupAnagrams(strs) << endl; return 0; }
true
73b7d2acb80c6983623c36499bff8935f4404f91
C++
jpoffline/pascal_shp
/PYRAMID.cpp
UTF-8
431
2.546875
3
[]
no_license
#include "PYRAMID.h" PYRAMID::PYRAMID(){ } PYRAMID::PYRAMID(int n){ _nrows = n; } void PYRAMID::create(){ int offset = 1; int nspaces = std::sqrt(3)/2 * _nrows * 3 + offset; nspaces = nspaces / 2; for(int r = 0; r < _nrows; r++){ for(int s = 0; s < nspaces;s++){ add_plaque(PLAQUE("--b")); } for(int e = 1; e < r; e++){ add_plaque( PLAQUE("Q") ); } add_plaque( PLAQUE("--n") ); nspaces--; } }
true
6f6e4c0876228b3e198dca48cf05fd0346571976
C++
rafern/multiplayer_roguelike
/src/client/MenuItem.cpp
UTF-8
2,106
3.359375
3
[]
no_license
#include "MenuItem.hpp" MenuItem::MenuItem(int key, std::string text, bool selectable, const Formating& formatting, const Formating& selectedFormatting) : key(key), text(text), formatting(formatting), selectedFormatting(selectedFormatting), selectable(selectable) {} int MenuItem::getKey() const { return key; } unsigned int MenuItem::getLength() const { return text.size(); } bool MenuItem::isSelectable() const { return selectable; } void MenuItem::drawAt(Renderer* renderer, int left, int right, int y, bool selected) const { // Clip y if(y < 0) return; const auto limitY = renderer->getHeight(); if(y >= limitY) return; // Get formatting bool useSelectedFormatting = selected && selectable; const Formating& thisFormatting = useSelectedFormatting ? selectedFormatting : formatting; // Handle overflowing items bool overflow = false; int width = right - left; int drawableLength = text.size(); if(drawableLength > width) { drawableLength = width - 3; if(drawableLength <= 0) drawableLength = 1; overflow = true; } // Draw item characters const auto limitX = renderer->getWidth(); for(auto c = 0; c < drawableLength; c++) { // Clip x auto charX = left + c; if(charX >= limitX) break; if(charX < 0) continue; // Draw renderer->draw_cell(charX, y, text[c], thisFormatting); } // Draw overflow and blank spaces if needed const auto itemEndX = left + drawableLength; const auto overflowX = itemEndX + 3; for(auto x = itemEndX; x < right; x++) { // Clip x if(x < 0) continue; if(x >= limitX) break; // Draw if(overflow && x < overflowX) renderer->draw_cell(x, y, '.', thisFormatting); else renderer->draw_cell(x, y, ' ', thisFormatting); } } bool MenuItem::onInput(char input) { (void)input; return false; }
true
1441d04ff3822839e7603dff307ae29b686525d9
C++
levey-lee/GraphicsEngine
/DiamondGraphicsEngine/inc/core/ComponentBase.h
UTF-8
8,823
2.90625
3
[]
no_license
#pragma once #include "core/Object.h" #include "core/ComponentPool.h" //flag for if a component needs acceess to graphics engine #define SHADED true //flag for if a component needs acceess to graphics engine #define UNSHADED false namespace Graphics { enum class ShaderType; class ShaderProgram; class GraphicsEngine; } /*********************************************************** * @brief exception class used for component errors ***********************************************************/ class ComponentErrorException : public std::exception { std::string m_msg; public: explicit ComponentErrorException(std::string msg) : m_msg(std::move(msg)) {} char const* what() const override { return m_msg.c_str(); } }; /******************************************************* * @brief This is a component editor interface. ComponenetBase * is derived from this class so that each component can access * and have its own place in the component editor. * For components that need to appear in the editor, their name must be * registered by calling REGISTER_EDITOR_COMPONENT(ClassType) *******************************************************/ class ComponentEditorInterface { public: virtual ~ComponentEditorInterface() = 0{} /******************************************************* * @brief Get component name, must be registered. Used by editor. * @return Registered component name. *******************************************************/ virtual std::string GetComponentTypeName() { Warning("Calling base function to get component name since component is not registered."); return { "Unknown Component" }; } /******************************************************* * @brief Implement this function if you wish the component * appear in Component Editor. *******************************************************/ virtual void Reflect(TwBar*, std::string const& /*barName*/, std::string const& /*groupName*/, Graphics::GraphicsEngine*) {} }; /*********************************************************** * @brief Common component interface. The very base level * of a component inheritance structure. * @remark All templated components can be cast to this type. **********************************************************/ class ComponentInterface { public: virtual ~ComponentInterface() = 0 {} virtual void Start() {} /******************************************************* * @brief Update function will be called each frame as long as * the component is enabled. * @param dt frametime in seconds *******************************************************/ virtual void Update(float dt) { UNUSED_VAR(dt) } /******************************************************* * @brief Set whatever needed to render this object * @remark This function will ONLY be called when ifShaded flag is set *******************************************************/ virtual void SetShaderParams(std::shared_ptr<Graphics::ShaderProgram>, Graphics::GraphicsEngine*) {} /******************************************************* * @brief Enable current component, call event callback *******************************************************/ virtual void Enable() { OnEnable(); } /******************************************************* * @brief Disable current component, call event callback *******************************************************/ virtual void Disable() { OnDisable(); } /******************************************************* * @brief Set if current component is enabled, * @remark will NOT call any callback functions *******************************************************/ virtual void SetEnabled(bool){} virtual bool IsEnabled() { return false; } protected: virtual void OnEnable() {} virtual void OnDisable() {} }; /************************************************************************** * @brief Component class base. Creates component pool automatically * @tparam TComp Type of derived component * @tparam ifShaded Specify if this component needs access to rendering engine. * If true, virtual function SetShaderParams will be called each frame. * @note Be aware of shader efficiency, some uniforms only need to be set once * per frame, such as Light attribute, camera view vector etc. * If it is shaded, SetShaderParams will be called each frame on every object. *************************************************************************/ template <typename TComp, bool ifShaded> class ComponentBase : public ComponentInterface , public ComponentEditorInterface { friend class Object; ///private constructor and friend class of T to prevent incorrect inheritance. friend TComp; explicit ComponentBase(bool defaultEnable, Graphics::ShaderType shaderType = Graphics::ShaderType::Null) : m_isEnabled(defaultEnable), m_shaderType(shaderType){} public: virtual ~ComponentBase() = 0 {} void Enable() override; void Disable() override; bool IsEnabled() override { return m_isEnabled; } void SetEnabled(bool ifEnabled) override { m_isEnabled = ifEnabled; } Object* GetOwner() const { return m_owner; } static constexpr bool IfShaded() { return ifShaded; } const Graphics::ShaderType& GetShaderType() const { return m_shaderType; } /******************************************************* * @brief Get update "frequency". * @return How many frames to update once. *******************************************************/ unsigned GetUpdateGap() const { return m_updateFrameGap; } /******************************************************* * @brief Set update "frequency". * @param value How many frames to update once. *******************************************************/ void SetUpdateGap(unsigned value) { m_updateFrameGap = value; } /******************************************************* * @brief This get the counter to update. Whenever the counter reaches * zero, update function will be called. * @return How many frames left to update. *******************************************************/ unsigned GetUpdateCounter()const { return m_updateCounter; } /******************************************************* * @brief Reset the counter to be the update "frequency" defined in the class *******************************************************/ virtual void ResetUpdateCounter() { m_updateCounter = m_updateFrameGap; } /******************************************************* * @brief Decrement the counter number. * Whenever the counter reaches zero, update function will be called. *******************************************************/ virtual void DecrementUpdateCounter() { if (m_updateCounter > 0)--m_updateCounter; } protected: Object* m_owner = nullptr; bool m_isEnabled = true; Graphics::ShaderType m_shaderType = Graphics::ShaderType::Null; //how many frame to update once. //i.e. if enabled, //0 means to update this component each frame, //1 means to update this component every other frame //2 means to update this component once per three frames unsigned m_updateFrameGap = 0; //update counter will be decreased by Update() by one whenver it gets called. //if the value reaches 0, it will be reset to m_updateFrameGap unsigned m_updateCounter = m_updateFrameGap; private: /******************************************************* * @brief This is the most interesting part of the architecture. * The compiler will generate a container specifically for this * component type. *******************************************************/ static ComponentPool<TComp> m_componentPool; void AssignOwner(Object* owner); }; //============================================================================= /////////////////////////////////////////////////////////////////////////////// // Implementation /////////////////////////////////////////////////////////////////////////////// //============================================================================= template <typename TComp, bool ifShaded> void ComponentBase<TComp, ifShaded>::Enable() { DEBUG_PRINT_DATA_FLOW m_isEnabled = true; OnEnable(); } template <typename TComp, bool ifShaded> void ComponentBase<TComp, ifShaded>::Disable() { DEBUG_PRINT_DATA_FLOW m_isEnabled = false; OnDisable(); } template <typename TComp, bool ifShaded> void ComponentBase<TComp, ifShaded>::AssignOwner(Object* owner) { Assert(owner!=nullptr, "Trying to assign an object to null."); DEBUG_PRINT_DATA_FLOW m_owner = owner; if (ifShaded) { m_owner->PushShadedComponent(this, m_shaderType); } }
true
f62b5a05eee0ee73d82941ec6dbe08ecad9e242a
C++
playfultechnology/arduino-wirebuzz
/arduino-wirebuzz.ino
UTF-8
1,716
3.34375
3
[ "Apache-2.0" ]
permissive
// CONSTANTS // The "start zone" which players must touch to start the game each time const byte startPin = 8; // Touching any part of the wire itself causes a failure const byte failPin = 9; // The "win zone" at the end of the wire const byte endPin = 10; // A piezo buzzer chirps to signify success/failure const byte buzzerPin = 6; // GLOBALS // Keep track of the current states of the game enum GameState {FAILED, IN_PROGRESS, SUCCESS}; GameState gameState = GameState::FAILED; void setup() { // Set the pins to the correct mode pinMode(startPin, INPUT_PULLUP); pinMode(failPin, INPUT_PULLUP); pinMode(endPin, INPUT_PULLUP); pinMode(buzzerPin, OUTPUT); // Begin a serial connection for debugging Serial.begin(9600); } void loop() { switch(gameState) { case GameState::IN_PROGRESS: if(!digitalRead(endPin)) { gameState = GameState::SUCCESS; Serial.println("Congratulations!"); tone(buzzerPin, 440, 50); delay(60); tone(buzzerPin, 587, 250); } else if(!digitalRead(failPin)) { gameState = GameState::FAILED; Serial.println("FAILED"); tone(buzzerPin, 440, 200); delay(200); tone(buzzerPin, 415, 200); delay(200); tone(buzzerPin, 392, 200); delay(200); tone(buzzerPin, 370, 400); } break; case GameState::FAILED: case GameState::SUCCESS: if(!digitalRead(startPin)) { gameState = GameState::IN_PROGRESS; Serial.println("New Game Started"); tone(buzzerPin, 440, 100); delay(120); tone(buzzerPin, 554, 100); delay(120); tone(buzzerPin, 659, 200); } break; } }
true
60ea7baf9d313f9017335bebad45a0afea66792e
C++
Jedibassist/CPlus-Valencia
/ArraysFunctions4/ArraysFunctions4/ArraysFunctions4.cpp
UTF-8
6,289
3.328125
3
[]
no_license
// ArraysFunctions4.cpp : Defines the entry point for the console application. /* Jed Gravelin, June 2013 * * Part 1 Answers: * 1 : If a variable is declared within the paramaters of a function, that variable is NOT available in main * 2 : If a variable is declared within a function itself, that variable is NOT available in main * 3 : If a variable is declared in main, that variable can be accessed by the function as long as the reference * to the function's memory location is passed in to the function. * 4 : If a global variable is defined, that can be used within any functions or main. If a variable is instantiated * within a class, that variable can be accessed by functions of that class if it is passed by reference. * */ // Test #include "stdafx.h" #include <iostream> using namespace std; // The number of items on the menu #define MENU_ITEMS 9 // Define an item typedef struct { char name[20]; double price; }item; // Prototype all the Functions double sum(int a, int b); double sum(double a, double b); double sum(int a, double b); void printMenu(); double swapMenuItems(char* oldItem, char* newItem); double superSize(double mealTotal); double addTaxes(double mealTotal); double bigMacMeal(); double fishFiletMeal(); double chickenNuggetsMeal(); double hamburgerMeal(); // Creating the 9 Menu items as structs and putting them into an array item menuitems[MENU_ITEMS] = {"BigMac", 3.49, "FishFilet", 3.89, "Hamburger", .79, "ChickenNuggets", 3.53, "Fries", 1.89, "SuperFries", 2.89, "Drink", 1.10, "SuperDrink", 2.52, "Tax", .065}; void main() { // Set precision of cout cout.precision(3); cout << "Testing..." << endl; cout << sum(5, 6) << endl; cout << sum(5.3, 6.4) << endl; cout << sum(5, 8.5) << endl << endl; int choice = 0; double mealTotal = 0; cout << "Welcome to McDonalds!" << endl; printMenu(); // Get input and validate. while(true) { cin >> choice; if((cin) && (choice > 0) && (choice < 5)) break; cin.clear(); cin.ignore( 1000, '\n' ); cout << "That is not a valid menu selection. Please choose again." << endl; } //while(!(cin >> choice)){ // cout << "That is not a valid menu selection. Please choose again." << endl; // cin >> choice; //} switch(choice){ case 1: mealTotal = bigMacMeal(); cout << "After Tax, your Big Mac Meal Comes to $"; if(int(mealTotal * 100) % 10 == 0){ cout << mealTotal << "0" << endl << endl; }else{ cout << mealTotal << endl << endl; } break; case 2: mealTotal = fishFiletMeal(); cout << "After Tax, your Fish o Filet Meal Comes to $"; if(int(mealTotal * 100) % 10 == 0){ cout << mealTotal << "0" << endl << endl; }else{ cout << mealTotal << endl << endl; } break; case 3: mealTotal = chickenNuggetsMeal(); cout << "After Tax, your Chicken Nuggets Meal Comes to $"; if(int(mealTotal * 100) % 10 == 0){ cout << mealTotal << "0" << endl << endl; }else{ cout << mealTotal << endl << endl; } break; case 4: mealTotal = hamburgerMeal(); cout << "After Tax, your Hamburger Meal Comes to $"; if(int(mealTotal * 100) % 10 == 0){ cout << mealTotal << "0" << endl << endl; }else{ cout << mealTotal << endl << endl; } break; default: break; } system("pause"); } // Sum test A double sum(int a, int b){ return ((double) a + b); } // Sum test B double sum(double a, double b){ return a + b; } // Sum test C double sum(int a, double b){ return ((double) a) + b; } // Prints the Menu and prompts for choice void printMenu(){ cout << "Please select a choice from the following Menu:" << endl; cout << "1. Big Mac Meal - $6.48" << endl; cout << "2. Fish o Filet Meal - $6.88" << endl; cout << "3. Chicken Nugget Meal - $6.52" << endl; cout << "4. Hamburger Meal - $3.78" << endl << endl; } // Will Swap Menu items in a Meal, and Update the total cost double swapMenuItems(char* oldItem, char* newItem){ double cost = 0; int i; for(i = 0;i < MENU_ITEMS;i++){ if(strcmp(oldItem, menuitems[i].name) == 0){ cost -= menuitems[i].price; } if(strcmp(newItem, menuitems[i].name) == 0){ cost += menuitems[i].price; } } return cost; } // Asks for Drink and Fries SuperSize upgrades // Takes in beginning total, Returns Modified total double superSize(double mealTotal){ double total = mealTotal; char choice; // SuperSize Drink ? cout << "Would you like to SuperSize your Drink? (y/n)"; cin >> choice; if(choice == 'y'){ total += swapMenuItems("Drink", "SuperDrink"); cout << "You have chosen to SuperSize your Drink." << endl; if(int(total * 100) % 10 == 0){ cout << "Your new total is $" << total << "0" << endl << endl; }else{ cout << "Your new total is $" << total << endl << endl; } }else{ cout << "You have chosen not to SuperSize." << endl << endl; } // SuperSize Fries ? cout << "Would you like to SuperSize your Fries? (y/n)"; cin >> choice; if(choice == 'y'){ total += swapMenuItems("Fries", "SuperFries"); cout << "You have chosen to SuperSize your Fries." << endl; if(int(total * 100) % 10 == 0){ cout << "Your new total is $" << total << "0" << endl << endl; }else{ cout << "Your new total is $" << total << endl << endl; } }else{ cout << "You have chosen not to SuperSize." << endl << endl; } return total; } // Will return the total plus 6.5% tax double addTaxes(double mealTotal){ return mealTotal + (mealTotal * menuitems[8].price); } // Will run the program for a Big Mac Meal double bigMacMeal(){ double mealTotal = 6.48; cout << "You have chosen the Big Mac Meal - $6.48" << endl; return addTaxes(superSize(mealTotal)); } // Will run the program for a Fish o Filet Meal double fishFiletMeal(){ double mealTotal = 6.88; cout << "You have chosen the Fish o Filet Meal - $6.88" << endl; return addTaxes(superSize(mealTotal)); } // Will run the program for a Chicken Nuggets Meal double chickenNuggetsMeal(){ double mealTotal = 6.52; cout << "You have chosen the Chicken Nuggets Meal - $6.52" << endl; return addTaxes(superSize(mealTotal)); } // Will run the program for a Hamburger Meal double hamburgerMeal(){ double mealTotal = 3.78; cout << "You have chosen the Hamburger Meal - $3.78" << endl; return addTaxes(superSize(mealTotal)); }
true
73d0108d99d805c094e5879d4932daee79bd6564
C++
piax93/CNodePP
/core/strutils.hpp
UTF-8
2,111
3.140625
3
[]
no_license
#ifndef UTILITIES_HPP_ #define UTILITIES_HPP_ #include <vector> #include <string> namespace util { /** * Split string into tokens * @param src String to split * @param delimiter Delimiter string * @return Vector of tokens */ std::vector<std::string> splitString(const std::string& src, const std::string& delimiter); /** * Split string into tokens * @param src Char array to split * @param delimiter Delimiter character * @return Array of tokens */ std::vector<std::string> splitString(char* src, char delimiter); /** * Check if string ends with a certain suffix * @param value String to check * @param ending Ending */ bool endsWith(const std::string& value, const std::string& ending); /** * Check if string starts with prefix * @param value String to check * @param prefix Prefix */ bool startsWith(const std::string& value, const std::string& prefix); /** * Check if string ends with a certain suffix * @param value Char array to check * @param ending Ending */ bool endsWith(const char* value, const char* ending); /** * Check if string starts with prefix * @param value Char array to check * @param prefix Prefix */ bool startsWith(const char* value, const char* prefix); /** * Remove extension from filename */ std::string removeExtension(const char* filename); /** * Remove extension from filename */ std::string removeExtension(const std::string& filename); /** * Encode string using URL notations */ std::string urlEncode(const std::string& toEncode); /** * Decode URL-Encoded string */ std::string urlDecode(const std::string &toDecode); /** * Store a complete text file in a string * @param filename File path * @return String containing file content */ std::string readFileToString(const std::string& filename); /** * Trim both ends of a string */ std::string trim(const std::string& s); /** * Transform explicit escape symbols into ASCII values */ std::string unescape(const std::string& s); /** * Convert newline chatacters to <br> tags */ std::string nl2br(const std::string& s); } /* namespace util */ #endif /* UTILITIES_HPP_ */
true
4c29c5f795b2013c46a14b7cc40b1a9f41962d03
C++
novo1985/Leetcode
/Easy/Remove duplicates from sorted array/RemoveDuplicatesFromSortedArray.cpp
UTF-8
555
3.546875
4
[]
no_license
#include <iostream> #include <vector> using namespace std; /* Remove the duplicated number in a sorted array and return the length * for example : [2,2,3,4] -> [2,3,4] return len = 3; * in-place, no extraspace */ class Solution{ public: int removeDuplicates(vector<int>& nums){ //double indice, one for old array, one for new array if(nums.size() < 2) { return nums.size(); } int i = 0; for(int j = 1; j < nums.size(); j++){ if(nums[i] != nums[j]){ i++; nums[i] = nums[j]; } } return i + 1; } };
true
ce6517f899cec27f09b6f507fc4bde3b2125863e
C++
M-o-C-u-i-s-h-l-e/GeeksforGeeks
/Basic/Binary Array Sorting.cpp
UTF-8
449
2.515625
3
[]
no_license
#include <iostream> using namespace std; int main(void) { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t; cin >> t; while (t--) { int n, Count = 0; cin >> n; for (int i = 0, temp; i < n; ++i) { cin >> temp; Count += (temp == 0); } for (int i = 0; i < n; ++i) cout << (i < Count ? 0 : 1) << ' '; cout << endl; } }
true
ea3d03e2bcecaf7feb6522b60067428b685f05ed
C++
woodbineZ/Cplusplus
/Projekt4autochess/Project1/Project1/Postac.cpp
UTF-8
1,442
3.125
3
[]
no_license
#include <iostream> #include "Postac.h" #include "Druzyna.h" using namespace std; Postac::Postac() { atakowal = false; zyje = true; } Postac::Postac(int _koszt, int _hp, int _dmg, string _nazwa, char _rodzaj) { hp = _hp; dmg = _dmg; koszt = _koszt; atakowal = false; zyje = true; dostepna = true; nazwa = _nazwa; rodzaj = _rodzaj; } void Postac::wyswietlInfo(int pozycjaWliscie, int _gold) { if (_gold >= koszt || _gold == -1) cout <<pozycjaWliscie<<" "<< rodzaj << " " << nazwa << " " << hp << " hp " << dmg << " dmg " << koszt << " zlota" << endl; } void Postac::getObrazenia(int damage) { hp -= damage; if (hp <= 0) zyje = false; } Postac* Postac::celuj(Druzyna& przeciwnik) { Postac* wrog = przeciwnik.dajPostac(0); return wrog; } Postac* Postac::przeszukajPozycje(Druzyna& przeciwnik, int _pozycja) { for (int i = 0; i < przeciwnik.zwrocLiczbePostaci(); i++) { Postac* temp = przeciwnik.dajPostac(i); if (temp->zwrocPozycje() == _pozycja && temp->czyZyje()) return temp; } throw 1; } void Postac::atak(Druzyna& przeciwnik) { Postac* wrog; try { wrog = celuj(przeciwnik); } catch (...) { return; } wrog->getObrazenia(dmg); cout << " postac: " << this->nazwa << " zaatakowal " << wrog->nazwa << " zadajac " << this->dmg << " obrazen, " << wrog->nazwa << " zostalo " << wrog->hp << " hp." << endl; atakowal = true; }
true
ad89d782eecedad306bfc01163b74a5fed547f26
C++
liuguolu/data_structure
/tree/binary/traversing_binary_tree/binary_tree_traversing.cpp
UTF-8
7,373
3.015625
3
[]
no_license
#include <stdio.h> #include <malloc.h> #include <conio.h> #include <queue> #include <stack> // 建立的二叉树模型 // // 1 // / \ // / \ // / \ // / \ // 2 3 // / \ / \ // / \ / \ // / \ / \ // 4 5 6 7 // / \ / \ / \ / \ // / \ / \ / \ / \ // 8 9 10 11 12 13 14 15 // / \ / \ / \ / \ / \ / \ / \ / \ // 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 typedef struct _BIN_TREE_NODE { int value; struct _BIN_TREE_NODE* left; struct _BIN_TREE_NODE* right; }BIN_TREE_NODE, BIN_TREE_ROOT,*PBIN_TREE_NODE,*PBIN_TREE_ROOT; // 创建节点 PBIN_TREE_NODE alloc_bin_tree_node(int _value, PBIN_TREE_NODE _left = NULL, PBIN_TREE_NODE _right = NULL) { PBIN_TREE_NODE node = (PBIN_TREE_NODE)calloc(1, sizeof(BIN_TREE_NODE)); if (NULL == node) return NULL; node->value = _value; node->left = _left; node->right = _right; return node; } // 释放节点 void free_bin_tree_node(PBIN_TREE_NODE* _node) { free(*_node); *_node = NULL; } // 建立完全二叉树 PBIN_TREE_ROOT build_complete_bin_tree(int _start,int _num) { PBIN_TREE_ROOT root = NULL; PBIN_TREE_NODE* nodes = (PBIN_TREE_ROOT*)calloc(_num, sizeof(PBIN_TREE_NODE)); if (NULL == nodes) return NULL; for (size_t i = 0; i < _num; i++) { nodes[i] = alloc_bin_tree_node(_start + i); } for (size_t i = 0; i < _num; i++) { int left_index = (i + 1) * 2 - 1; int right_index = (i + 1) * 2 + 1 -1; if (left_index < _num) { nodes[i]->left = nodes[left_index]; } if (right_index < _num) { nodes[i]->right = nodes[right_index]; } } root = nodes[0]; free(nodes); return root; } // 释放二叉树(基于非递归的先序遍历实现) void destroy_bin_tree(PBIN_TREE_ROOT* _root) { PBIN_TREE_NODE now_node = NULL; std::stack<PBIN_TREE_NODE> node_cache; node_cache.push(*_root); while (node_cache.empty() == false) { now_node = node_cache.top(); node_cache.pop(); if (now_node->right != NULL) { node_cache.push(now_node->right); } if (now_node->left != NULL) { node_cache.push(now_node->left); } free_bin_tree_node(&now_node); } *_root = NULL; } // 递归实现 先序遍历 void recursive_preorder_traversal_bin_tree(PBIN_TREE_NODE _node) { if (_node == NULL) return; printf("%d ", _node->value); recursive_preorder_traversal_bin_tree(_node->left); recursive_preorder_traversal_bin_tree(_node->right); } // 递归实现 中序遍历 void recursive_inorder_traversal_bin_tree(PBIN_TREE_NODE _node) { if (_node == NULL) return; recursive_inorder_traversal_bin_tree(_node->left); printf("%d ", _node->value); recursive_inorder_traversal_bin_tree(_node->right); } // 递归实现 后序遍历 void recursive_postorder_traversal_bin_tree(PBIN_TREE_NODE _node) { if (_node == NULL) return; recursive_postorder_traversal_bin_tree(_node->left); recursive_postorder_traversal_bin_tree(_node->right); printf("%d ", _node->value); } // 非递归实现 先序遍历 void nonrecursive_preorder_traversal_bin_tree(PBIN_TREE_NODE _node) { if (_node == NULL) return; PBIN_TREE_NODE now_node = NULL; std::stack<PBIN_TREE_NODE> node_cache; node_cache.push(_node); while (node_cache.empty() == false) { now_node = node_cache.top(); node_cache.pop(); printf("%d ", now_node->value); if (now_node->right != NULL) node_cache.push(now_node->right); if (now_node->left != NULL) node_cache.push(now_node->left); } } // 非递归实现 中序遍历 void nonrecursive_inorder_traversal_bin_tree(PBIN_TREE_NODE _node) { if (_node == NULL) return; PBIN_TREE_NODE now_node = NULL; std::stack<PBIN_TREE_NODE> node_cache; now_node = _node; while (node_cache.empty() == false || now_node != NULL) { if (now_node != NULL) { node_cache.push(now_node); now_node = now_node->left; } else { now_node = node_cache.top(); node_cache.pop(); printf("%d ", now_node->value); now_node = now_node->right; } } } // 非递归实现 后序遍历 void nonrecursive_postorder_traversal_bin_tree(PBIN_TREE_NODE _node) { if (_node == NULL) return; PBIN_TREE_NODE nnow = _node; PBIN_TREE_NODE nlast = NULL; std::stack<PBIN_TREE_NODE> node_cache; while (node_cache.empty() == false || nnow != NULL) { if (nnow != NULL) { node_cache.push(nnow); nnow = nnow->left; } else { nnow = node_cache.top(); if (nnow->right != NULL && nnow->right != nlast) nnow = nnow->right; else { node_cache.pop(); printf("%d ", nnow->value); nlast = nnow; nnow = NULL; } } } } void level_traversal_bin_tree(PBIN_TREE_NODE _node) { if (_node == NULL) return; PBIN_TREE_NODE now_node = NULL; std::queue<PBIN_TREE_NODE> node_cache; node_cache.push(_node); while (node_cache.empty() == false) { now_node = node_cache.front(); node_cache.pop(); printf("%d ", now_node->value); if (now_node->left != NULL) node_cache.push(now_node->left); if (now_node->right != NULL) node_cache.push(now_node->right); } } void print_traversal_bin_tree(void (*_fun)(PBIN_TREE_NODE), PBIN_TREE_ROOT _root, const char* _title) { printf("%16s:", _title); _fun(_root); printf("\n"); } int main(int argc, char* argv[]) { PBIN_TREE_ROOT root = build_complete_bin_tree(1, 31); print_traversal_bin_tree(recursive_preorder_traversal_bin_tree, root, "递归-前序遍历"); print_traversal_bin_tree(recursive_inorder_traversal_bin_tree, root, "递归-中序遍历"); print_traversal_bin_tree(recursive_postorder_traversal_bin_tree, root, "递归-后序遍历"); print_traversal_bin_tree(nonrecursive_preorder_traversal_bin_tree, root, "非递归-前序遍历"); print_traversal_bin_tree(nonrecursive_inorder_traversal_bin_tree, root, "非递归-中序遍历"); print_traversal_bin_tree(nonrecursive_postorder_traversal_bin_tree, root, "非递归-后序遍历"); print_traversal_bin_tree(level_traversal_bin_tree, root, "层级遍历"); destroy_bin_tree(&root); return 0; }
true
d59bd653b154351c4f1ef3f01e36a28f6f4bb827
C++
wduraes/curso-iot
/sample-code/local.ino
UTF-8
2,726
2.5625
3
[]
no_license
#include <ESP8266WiFi.h> #include <Adafruit_MQTT.h> #include <Adafruit_MQTT_Client.h> #include <Adafruit_Sensor.h> #include <DHT.h> #include <DHT_U.h> #include <SPI.h> #define DHTPIN 10 #define DHTTYPE DHT11 DHT_Unified dht(DHTPIN, DHTTYPE); #define WLAN_SSID "WI-FI" #define WLAN_PASS "SENHA" #define AIO_SERVER "IP" #define AIO_USERNAME "" #define AIO_KEY "" #define AIO_SERVERPORT 1883 WiFiClient client; Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY); Adafruit_MQTT_Publish TEMPO = Adafruit_MQTT_Publish(&mqtt,"TEMPO"); int ChipID = ESP.getChipId(); //variables to hold data char hum[5]; char temp[5]; char payload[51]; void setup() { Serial.begin(115200); delay(10); //pinMode(16,OUTPUT); // Connect to WiFi access point. Serial.println(); Serial.println(); Serial.print("Connecting to "); Serial.println(WLAN_SSID); WiFi.begin(WLAN_SSID, WLAN_PASS); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(); Serial.println("WiFi connected"); Serial.print("IP address: "); Serial.println(WiFi.localIP()); dht.begin(); } void loop() { MQTT_connect(); sensors_event_t event; //Cria o Payload combinando os dados de telemetria String Payload = "ID="; dht.temperature().getEvent(&event); float nn = event.temperature; dtostrf(nn, 2, 2, temp); Payload = Payload + ChipID + ";LOC=4;TEMP=" + temp + ";HUM="; dht.humidity().getEvent(&event); float no = event.relative_humidity; dtostrf(no, 2, 2, hum); Payload = Payload + hum; //convert String Payload to a char array int str_len = Payload.length() + 1; char char_array[str_len]; Payload.toCharArray(char_array, str_len); Serial.println(""); Serial.print("Payload: "); Serial.println(char_array); //Publish all value into a single Topic and wait 10 secondes Serial.println("Sending Payload data... "); TEMPO.publish(char_array); delay(30000); } // Function to connect and reconnect as necessary to the MQTT server. // Should be called in the loop function and it will take care if connecting. void MQTT_connect() { int8_t ret; if (mqtt.connected()) // Stop if already connected { return; } Serial.print("Connecting to MQTT... "); uint8_t retries = 3; while ((ret = mqtt.connect()) != 0) // connect will return 0 for connected { Serial.println(mqtt.connectErrorString(ret)); Serial.println("Retrying MQTT connection in 5 seconds..."); mqtt.disconnect(); delay(5000); // wait 5 seconds retries--; if (retries == 0) { while (1) ; } } Serial.println("MQTT Connected!"); }
true
ada3b74b4ffc23c7736a254956327650a2cf969f
C++
eriser/xh_jucemodules
/xh_Utilities/misc/ArrayDuplicateScanner.h
UTF-8
2,158
3.078125
3
[ "MIT" ]
permissive
#ifndef ARRAYDUPLICATESCANNER_H_INCLUDED #define ARRAYDUPLICATESCANNER_H_INCLUDED template <class ValueType> class ArrayDuplicateScanner { JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(ArrayDuplicateScanner); public: ArrayDuplicateScanner () { } ~ArrayDuplicateScanner () { } void reset () { checkBuffer.clear (); duplicateValues.clear (); duplicateCounts.clear (); } void prepare (int arraySize) { reset (); checkBuffer.ensureStorageAllocated (arraySize); duplicateCounts.ensureStorageAllocated (arraySize); duplicateValues.ensureStorageAllocated (arraySize); } void processElement (const ValueType& valueToCheck) { if (expectedSize >= 0) { jassert (checkBuffer.size () < expectedSize); } if (checkBuffer.contains (valueToCheck)) { int dupeIndex = duplicateValues.indexOf (valueToCheck); if (dupeIndex == -1) { duplicateValues.add (valueToCheck); duplicateCounts.add (1); // We've seen 2 instances now, but we'll only count dupes } else { duplicateCounts.getReference (dupeIndex)++; } checkBuffer.add (valueToCheck); } } template <class ArrayType> void processArray (const ArrayType& source) { int size = source.size (); prepare (size); for (int i=0; i<size; ++i) { processElement (source.getUnchecked (i)); } } bool anyFound () const { return getNumDifferentDuplicatesFound() > 0; } int getNumDifferentDuplicatesFound () const { return duplicateValues.size (); } ValueType getDuplicateValueAt (int index) const { return duplicateValues[index]; } int getNumDuplicatesOfValueAt (int index) const { return duplicateCounts[index]; } int getNumExtraValues () const { int totalDupes = 0; for (int i=0; i<duplicateCounts.size(); i++) { totalDupes += duplicateCounts.getUnchecked (i); } return totalDupes; } private: juce::Array< ValueType > checkBuffer; juce::Array< ValueType > duplicateValues; juce::Array< int > duplicateCounts; int expectedSize; }; #endif // ARRAYDUPLICATESCANNER_H_INCLUDED
true
40354085a18595f151846de63688cb9d767c9055
C++
alfmorente/aticaprojectsvn
/CITIUS/CITIUS_Control_Driving/include/RosNode_Driving.h
UTF-8
1,697
2.546875
3
[]
no_license
/** * @file RosNode_Driving.h * @brief Declara el tipo de la clase "RosNode_Driving" * - La clase implementa la gestión del nodo de conduccion (Driving) del * Subsistema de control de UGV * @author Carlos Amores * @date 2013, 2014 * @addtogroup DrivingRosNode * @{ */ #ifndef ROSNODE_DRIVING_H #define ROSNODE_DRIVING_H #include <time.h> #include "RosNode.h" #include "DrivingConnectionManager.h" #include "CITIUS_Control_Driving/msg_command.h" #include "CITIUS_Control_Driving/msg_switcher.h" #include "CITIUS_Control_Driving/msg_vehicleInfo.h" #include "CITIUS_Control_Driving/srv_vehicleStatus.h" #include "CITIUS_Control_Driving/srv_nodeStatus.h" #include "Timer.h" /** * \class RosNode_Driving * \brief Clase que representa al nodo ROS que gestiona la comunicación con el * módulo de conducción del vehículo */ class RosNode_Driving : public RosNode { private: ros::Publisher pubVehicleInfo; ros::Publisher pubSwitcher; ros::Subscriber subsCommand; ros::ServiceServer servNodeStatus; ros::ServiceClient clientStatus; DrivingConnectionManager *dVehicle; bool electricAlarms; void fcn_sub_command(CITIUS_Control_Driving::msg_command msg); bool fcv_serv_nodeStatus(CITIUS_Control_Driving::srv_nodeStatus::Request &rq, CITIUS_Control_Driving::srv_nodeStatus::Response &rsp); bool checkCommand(CITIUS_Control_Driving::msg_command msg); void setEmergecyCommands(); public: RosNode_Driving(); ~RosNode_Driving(); void initROS(); DrivingConnectionManager *getDriverMng(); void publishDrivingInfo(DrivingInfo); void publishSwitcherInfo(short position); void checkAlarms(); void checkSwitcher(); }; #endif /* ROSNODE_DRIVING_H */ /** * @} */
true
8d16f7c72139b0d6dad86872bd86a806838cf071
C++
Disbalance/cryptoadapter
/src/platform/websocket.cpp
UTF-8
11,951
2.53125
3
[]
no_license
/*************************************************** * websocket.cpp * Created on Fri, 28 Sep 2018 09:37:36 +0000 by vladimir * * $Author$ * $Rev$ * $Date$ ***************************************************/ #include <map> #include <iostream> #include <exception> #include <platform/log.h> #include "websocket.h" namespace platform { std::set<WebSocketClient*> WebSocketClient::s_instances; size_t WebSocketClient::s_numInstance = 0; WebSocketConnection::WebSocketConnection(WebSocketClient *client) : m_closing(false) , m_webSocket(NULL) , m_client(client) , m_wantWrite(false) { m_writeBuffer.resize(LWS_PRE); m_writtenBuffer.resize(LWS_PRE); } WebSocketConnection::~WebSocketConnection() { m_closing = true; if(m_client) { m_client->detach(this); } if(m_webSocket) { WebSocketConnection **wsc = (WebSocketConnection**)lws_wsi_user(m_webSocket); *wsc = NULL; } if(m_connectInfo.userdata) { delete (void**)m_connectInfo.userdata; } } void WebSocketConnection::setConnectionHandler(WebSocketConnectionHandler *handler) { m_handler = handler; } void WebSocketConnection::connect(std::string url) { const char *tmpProtocol; const char *tmpAddress; int port; const char *tmpPath; if(lws_parse_uri(&url[0], &tmpProtocol, &tmpAddress, &port, &tmpPath)) { throw std::invalid_argument("invalid url"); } auto protocol = std::string(tmpProtocol); auto address = std::string(tmpAddress); auto path = std::string("/").append(tmpPath); bool ssl = false; if(protocol == std::string("wss")) { ssl = true; } else if(protocol == std::string("ws")) { ssl = false; } else { throw std::invalid_argument("invalid protocol: '" + protocol + "'. Must be 'ws' or 'wss'."); } connect(std::move(address), port, std::move(path), ssl); } void WebSocketConnection::connect(std::string address, int port, std::string path, bool ssl) { static const char *origin = "fin"; if(m_webSocket) { return; } memset(&m_connectInfo, 0, sizeof(m_connectInfo)); m_address.swap(address); m_port = port; m_path.swap(path); m_ssl = ssl; m_connectInfo.address = m_address.c_str(); m_connectInfo.host = m_address.c_str(); m_connectInfo.port = m_port; m_connectInfo.path = m_path.c_str(); m_connectInfo.ssl_connection = ssl; m_connectInfo.ietf_version_or_minus_one = -1; m_connectInfo.origin = origin; WebSocketConnection **thisInfo = new (WebSocketConnection*); *thisInfo = this; m_connectInfo.userdata = (void*)thisInfo; if(m_client) { m_client->add(this); } } void WebSocketConnection::disconnect() { if(m_webSocket) { WebSocketConnection **wsc = (WebSocketConnection**)lws_wsi_user(m_webSocket); if(wsc) { *wsc = NULL; } memset(&m_connectInfo, 0, sizeof(m_connectInfo)); m_webSocket = NULL; } } void WebSocketConnection::reconnect() { connect(m_address, m_port, m_path, m_ssl); } bool WebSocketConnection::isConnected() { return m_webSocket != NULL; } int WebSocketConnection::write(const char *buffer, size_t size) { if(m_webSocket) { { std::lock_guard<std::mutex> lock(m_writeSync); m_writeBuffer.insert(m_writeBuffer.end(), buffer, buffer + size); m_writeBuffer.resize(m_writeBuffer.size() + LWS_PRE); m_writeMessageSizes.emplace_back(size); m_wantWrite = true; } lws_cancel_service_pt(m_webSocket); return size; } return -1; } int WebSocketConnection::onDataReady(char *data, size_t length) { if(m_closing) { return -1; } if(data) { m_readBuffer.insert(m_readBuffer.end(), data, data + length); const size_t remaining = lws_remaining_packet_payload(m_webSocket); if(remaining || !lws_is_final_fragment(m_webSocket)) { return 0; } } if(m_handler) { WSMessage msg; msg.type = data ? (lws_frame_is_binary(m_webSocket) ? BINARY : TEXT) : TEXT; if(m_readBuffer.size() == m_readBuffer.capacity()) { m_readBuffer.emplace_back(0); m_readBuffer.pop_back(); } msg.data = m_readBuffer.data(); msg.size = m_readBuffer.size(); struct timespec now; clock_gettime(CLOCK_REALTIME, &now); msg.timestamp = now.tv_sec * 1000000000 + now.tv_nsec; m_handler->onDataReady(this, msg); } m_readBuffer.resize(0); return 0; } void WebSocketConnection::checkTimers() { if(m_handler) { m_handler->checkTimers(); } } int WebSocketConnection::onConnectFailed() { if(m_handler) { return m_handler->onConnectFailed(this); } return 0; } int WebSocketConnection::onConnected() { if(m_handler) { m_handler->onConnected(this); } return 0; } int WebSocketConnection::onWrite() { if(m_closing) { return -1; } if(!m_wantWrite) { return 0; } { std::lock_guard<std::mutex> lock(m_writeSync); m_writeBuffer.swap(m_writtenBuffer); m_writeMessageSizes.swap(m_writtenMessageSizes); m_wantWrite = false; } if(m_writtenBuffer.size() <= LWS_PRE) { return 0; } size_t ptr = LWS_PRE, i = 0; WSMessage msg; msg.type = TEXT; while(ptr < m_writtenBuffer.size()) { if(m_readBuffer.size() == m_readBuffer.capacity()) { m_readBuffer.emplace_back(0); m_readBuffer.pop_back(); } msg.data = (char*)&m_writtenBuffer[ptr]; msg.size = m_writtenMessageSizes[i]; struct timespec now; clock_gettime(CLOCK_REALTIME, &now); msg.timestamp = now.tv_sec * 1000000000 + now.tv_nsec; if(m_handler) { m_handler->onMessageSent(this, msg); } lws_write(m_webSocket, (unsigned char*)msg.data, msg.size, LWS_WRITE_TEXT); ptr += m_writtenMessageSizes[i] + LWS_PRE; i ++; } m_writtenBuffer.resize(LWS_PRE); m_writtenMessageSizes.resize(0); return 0; } int WebSocketConnection::onClose() { if(m_client) { m_client->remove(this); } m_webSocket = NULL; if(m_handler) { m_handler->onClose(this); } return 0; } int WebSocketConnection::wsCallback(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len) { WebSocketConnection *wsc = NULL; if(user) { wsc = *(WebSocketConnection**)user; } switch(reason) { case LWS_CALLBACK_CLIENT_ESTABLISHED: if(wsc) { return wsc->onConnected(); } return -1; case LWS_CALLBACK_CLIENT_RECEIVE: if(wsc) { return wsc->onDataReady((char*)in, len); } return -1; case LWS_CALLBACK_CLIENT_WRITEABLE: if(wsc) { wsc->checkTimers(); if(wsc->m_wantWrite) { return wsc->onWrite(); } return 0; } return -1; case LWS_CALLBACK_CLOSED: { WebSocketClient *client = NULL; int result = 0; if(wsc) { client = wsc->m_client; result = wsc->onClose(); } else if(wsi) { client = (WebSocketClient*)lws_context_user(lws_get_context(wsi)); } if(client) { client->removeHandle(wsi); } return result; } case LWS_CALLBACK_CLIENT_CONNECTION_ERROR: if(wsc) { wsc->onConnectFailed(); } return -1; case LWS_CALLBACK_WSI_DESTROY: if(user) { delete (void**)user; } default: //if(wsc) { //wsc->onDataReady(NULL, 0); //} return 0; } return 0; } WebSocketClient::WebSocketClient(const std::string &outboundAddr, bool enableLWSLogging) : m_changed(false) , m_protocols({ { "default-protocol", &WebSocketConnection::wsCallback, sizeof(void*), 4096, 0, this }, { NULL, NULL, 0, 0 } /* terminator */ }) , m_outgoingInterface(outboundAddr) , m_numConnections(0) { if(!enableLWSLogging) { lws_set_log_level(LLL_DEBUG, &wsLog); lws_set_log_level(LLL_INFO, &wsLog); lws_set_log_level(LLL_NOTICE, &wsLog); lws_set_log_level(LLL_WARN, &wsLog); lws_set_log_level(LLL_ERR, &wsLog); } lws_context_creation_info info; memset(&info, 0, sizeof(info)); info.port = CONTEXT_PORT_NO_LISTEN; info.protocols = m_protocols.data(); info.gid = -1; info.uid = -1; if(!m_outgoingInterface.empty()) { info.iface = m_outgoingInterface.c_str(); } #if LWS_LIBRARY_VERSION_MAJOR >= 2 info.options = LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT; #endif m_context = lws_create_context(&info); m_running = true; m_thread = std::thread([this]() { run(); }); s_instances.insert(this); } void WebSocketClient::wsLog(int level, const char *line) { static std::map<int, Logger::Severity> logLevelMapping = { {LLL_ERR, Logger::Critical}, {LLL_WARN, Logger::Error}, {LLL_NOTICE, Logger::Warning}, {LLL_INFO, Logger::Info}, {LLL_DEBUG, Logger::Debug} }; auto i = logLevelMapping.find(level); if(i == logLevelMapping.end()) { return; } long len = strlen(line); if(line[len-1] == '\n') { len --; } LoggerMessage(i->second) << std::string(line, len); } WebSocketClient::~WebSocketClient() { s_instances.erase(this); m_running = false; lws_cancel_service(m_context); m_thread.join(); for(auto conn : m_boundConnections) { conn->m_webSocket = NULL; conn->m_client = NULL; } lws_context_destroy(m_context); } WebSocketConnection *WebSocketClient::createConnection() { WebSocketConnection *conn = new WebSocketConnection(this); m_boundConnections.insert(conn); return conn; } WebSocketClient &WebSocketClient::instance() { if(!s_instances.size()) { throw std::runtime_error("WebSocketClient instance does not exist!"); } size_t instance = s_numInstance ++; s_numInstance %= s_instances.size(); auto currentInstance = s_instances.begin(); while(instance -- && currentInstance != s_instances.end()) { currentInstance ++; } return **currentInstance; } void WebSocketClient::detach(WebSocketConnection *conn) { m_boundConnections.erase(conn); remove(conn); } void WebSocketClient::add(WebSocketConnection *conn) { std::lock_guard<std::mutex> lock(m_connectionsSync); m_addConnections.insert(conn); m_changed = true; lws_cancel_service(m_context); } void WebSocketClient::remove(WebSocketConnection *conn) { std::lock_guard<std::mutex> lock(m_connectionsSync); if(m_addConnections.find(conn) != m_addConnections.end()) { m_addConnections.erase(conn); } if(!conn->m_webSocket) { return; } m_removeConnections.insert(conn->m_webSocket); m_changed = true; lws_cancel_service(m_context); } void WebSocketClient::removeHandle(lws *handle) { m_connections.erase(handle); lws_cancel_service(m_context); } void WebSocketClient::run() { while(m_running) { if(m_changed) { std::lock_guard<std::mutex> lock(m_connectionsSync); for(auto &conn : m_addConnections) { if(conn->m_webSocket == NULL) { conn->m_connectInfo.context = m_context; conn->m_connectInfo.protocol = m_protocols[0].name; conn->m_webSocket = lws_client_connect_via_info(&conn->m_connectInfo); conn->m_connectInfo.userdata = NULL; if(conn->m_webSocket) { m_connections.insert(conn->m_webSocket); m_numConnections ++; } else { conn->onConnectFailed(); } } } m_addConnections.clear(); for(auto &conn : m_removeConnections) { m_connections.erase(conn); m_numConnections --; } m_removeConnections.clear(); m_changed = false; } if(!m_numConnections) { usleep(250000); continue; } int result = lws_service(m_context, 10); if(result) { std::cout << "LWS service return value: " << result << std::endl; } for(auto &conn : m_connections) { if(lws_callback_on_writable(conn) < 0) { std::lock_guard<std::mutex> lock(m_connectionsSync); m_removeConnections.insert(conn); m_changed = true; } } } } }
true
df03e3591780491c575305dfc2304ad4d004426e
C++
whileskies/curriculum_design
/SoftwareArchitecture/linux server/access/ClientAccessInfo.cpp
UTF-8
1,176
2.6875
3
[]
no_license
// // Created by whileskies on 19-6-13. // #include "ClientAccessInfo.h" namespace access { ClientAccessInfo::ClientAccessInfo() {} ClientAccessInfo::ClientAccessInfo(evutil_socket_t sockfd, struct sockaddr_in addr, struct bufferevent *client_bufferevent) : sockfd_(sockfd), addr_(addr), client_bufferevent_(client_bufferevent) { } ClientAccessInfo::~ClientAccessInfo() { bufferevent_free(client_bufferevent_); } struct sockaddr_in ClientAccessInfo::get_addr() const { return addr_; } void ClientAccessInfo::print() const { char buf[100]; inet_ntop(AF_INET, &addr_.sin_addr, buf, 16); std::cout << "addr: " << buf << " port:" << ntohs(addr_.sin_port) << std::endl; } void ClientAccessInfo::set_email(std::string email) { email_ = email; } std::string ClientAccessInfo::get_email() const { return email_; } evutil_socket_t ClientAccessInfo::get_sockfd() const { return sockfd_; } struct bufferevent *ClientAccessInfo::get_bufferevent() const { return client_bufferevent_; } }
true
ffa5dd45bdab1b48ca9f1931b01ab10a6e8c4ffe
C++
LinkItONEDevGroup/LASS
/SensingOfRiceFields/SensingOfRiceFields.ino
UTF-8
2,914
2.6875
3
[ "MIT" ]
permissive
#include <SoftwareSerial.h> #include <OneWire.h> #include <DallasTemperature.h> #include <Wire.h> #include <LiquidCrystal_I2C.h> #include <Stepper.h> #define DELAY 60000 #define WATER_WIRE_BUS 2 #define SOIL_WIRE_BUS 3 #define ETAPE_PIN A0 #define ETAPE_NUMSAMPLES 15 #define ETAPE_SERIESRESISTOR 560 #define ETAPE_FUDGE 0.3 int samples[ETAPE_NUMSAMPLES]; OneWire waterWire(WATER_WIRE_BUS); OneWire soilWire(SOIL_WIRE_BUS); DallasTemperature water_temp(&waterWire); DallasTemperature soil_temp(&soilWire); float etape_liquid_level = 0; float water_temperature = 0; float soil_temperature = 0; float waterlevel; LiquidCrystal_I2C lcd(0x27, 16, 2); SoftwareSerial mySerial(4, 5); // UNO (RX, TX) void read_water_temp() { water_temp.requestTemperatures(); water_temperature = water_temp.getTempCByIndex(0); if(water_temperature == -127) { water_temperature = 0; } Serial.print("Water Temperature: "); Serial.print(water_temperature); Serial.println(" *C "); } void read_soil_temp() { soil_temp.requestTemperatures(); soil_temperature = soil_temp.getTempCByIndex(0); if(soil_temperature == -127) { soil_temperature = 0; } Serial.print("Soil Temperature: "); Serial.print(soil_temperature); Serial.println(" *C "); } void read_etape() { uint8_t i; float average; float lastwaterlevel=0; // take N samples in a row, with a slight delay for (i=0; i< ETAPE_NUMSAMPLES; i++) { samples[i] = analogRead(ETAPE_PIN); delay(10); } // average all the samples out average = 0; for (i=0; i< ETAPE_NUMSAMPLES; i++) { average += samples[i]; } average /= ETAPE_NUMSAMPLES; //Serial.print("Average analog reading "); //Serial.println(average); // convert the value to resistance average = 1023 / average - 1; average = ETAPE_SERIESRESISTOR / average; //Serial.print("Sensor resistance "); //Serial.println(average); waterlevel = 0; waterlevel= -1 * 0.006958 * average + 11.506958 + ETAPE_FUDGE; etape_liquid_level = waterlevel; if(waterlevel < 0) { waterlevel = 0; } Serial.print("Water level (inches) "); Serial.print(waterlevel); Serial.print(", (cm) "); Serial.println(waterlevel * 2.54); } void setup() { Serial.begin(9600); mySerial.begin(9600); water_temp.begin(); soil_temp.begin(); lcd.begin(); lcd.backlight(); } void loop() { read_etape(); read_water_temp(); read_soil_temp(); mySerial.print(water_temperature); mySerial.print(","); mySerial.print(soil_temperature); mySerial.print(","); mySerial.println(waterlevel * 2.54); lcd.clear(); lcd.print(water_temperature); lcd.print(" C ,"); lcd.print(soil_temperature); lcd.print(" C ,"); lcd.setCursor(0, 1); lcd.print(waterlevel * 2.54); lcd.print(" cm, "); delay(DELAY); }
true
899aac849e37e4a6f75e34ab8d207d322b5efaed
C++
colmap/colmap
/src/colmap/math/math.h
UTF-8
8,425
2.53125
3
[ "BSD-3-Clause" ]
permissive
// Copyright (c) 2023, ETH Zurich and UNC Chapel Hill. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of ETH Zurich and UNC Chapel Hill nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Author: Johannes L. Schoenberger (jsch-at-demuc-dot-de) #pragma once #include "colmap/util/logging.h" #include <algorithm> #include <cmath> #include <complex> #include <limits> #include <list> #include <stdexcept> #include <vector> #ifndef M_PI #define M_PI 3.14159265358979323846264338327950288 #endif namespace colmap { // Return 1 if number is positive, -1 if negative, and 0 if the number is 0. template <typename T> int SignOfNumber(T val); // Clamp the given value to a low and maximum value. template <typename T> inline T Clamp(const T& value, const T& low, const T& high); // Convert angle in degree to radians. inline float DegToRad(float deg); inline double DegToRad(double deg); // Convert angle in radians to degree. inline float RadToDeg(float rad); inline double RadToDeg(double rad); // Determine median value in vector. Returns NaN for empty vectors. template <typename T> double Median(const std::vector<T>& elems); // Determine mean value in a vector. template <typename T> double Mean(const std::vector<T>& elems); // Determine sample variance in a vector. template <typename T> double Variance(const std::vector<T>& elems); // Determine sample standard deviation in a vector. template <typename T> double StdDev(const std::vector<T>& elems); // Generate N-choose-K combinations. // // Note that elements in range [first, last) must be in sorted order, // according to `std::less`. template <class Iterator> bool NextCombination(Iterator first, Iterator middle, Iterator last); // Sigmoid function. template <typename T> T Sigmoid(T x, T alpha = 1); // Scale values according to sigmoid transform. // // x \in [0, 1] -> x \in [-x0, x0] -> sigmoid(x, alpha) -> x \in [0, 1] // // @param x Value to be scaled in the range [0, 1]. // @param x0 Spread that determines the range x is scaled to. // @param alpha Exponential sigmoid factor. // // @return The scaled value in the range [0, 1]. template <typename T> T ScaleSigmoid(T x, T alpha = 1, T x0 = 10); // Binomial coefficient or all combinations, defined as n! / ((n - k)! k!). size_t NChooseK(size_t n, size_t k); // Cast value from one type to another and truncate instead of overflow, if the // input value is out of range of the output data type. template <typename T1, typename T2> T2 TruncateCast(T1 value); // Compute the n-th percentile in the given sequence. template <typename T> T Percentile(const std::vector<T>& elems, double p); //////////////////////////////////////////////////////////////////////////////// // Implementation //////////////////////////////////////////////////////////////////////////////// namespace internal { template <class Iterator> bool NextCombination(Iterator first1, Iterator last1, Iterator first2, Iterator last2) { if ((first1 == last1) || (first2 == last2)) { return false; } Iterator m1 = last1; Iterator m2 = last2; --m2; while (--m1 != first1 && *m1 >= *m2) { } bool result = (m1 == first1) && *first1 >= *m2; if (!result) { while (first2 != m2 && *m1 >= *first2) { ++first2; } first1 = m1; std::iter_swap(first1, first2); ++first1; ++first2; } if ((first1 != last1) && (first2 != last2)) { m1 = last1; m2 = first2; while ((m1 != first1) && (m2 != last2)) { std::iter_swap(--m1, m2); ++m2; } std::reverse(first1, m1); std::reverse(first1, last1); std::reverse(m2, last2); std::reverse(first2, last2); } return !result; } } // namespace internal template <typename T> int SignOfNumber(const T val) { return (T(0) < val) - (val < T(0)); } template <typename T> T Clamp(const T& value, const T& low, const T& high) { return std::max(low, std::min(value, high)); } float DegToRad(const float deg) { return deg * 0.0174532925199432954743716805978692718781530857086181640625f; } double DegToRad(const double deg) { return deg * 0.0174532925199432954743716805978692718781530857086181640625; } // Convert angle in radians to degree. float RadToDeg(const float rad) { return rad * 57.29577951308232286464772187173366546630859375f; } double RadToDeg(const double rad) { return rad * 57.29577951308232286464772187173366546630859375; } template <typename T> double Median(const std::vector<T>& elems) { CHECK(!elems.empty()); const size_t mid_idx = elems.size() / 2; std::vector<T> ordered_elems = elems; std::nth_element(ordered_elems.begin(), ordered_elems.begin() + mid_idx, ordered_elems.end()); if (elems.size() % 2 == 0) { const T mid_element1 = ordered_elems[mid_idx]; const T mid_element2 = *std::max_element(ordered_elems.begin(), ordered_elems.begin() + mid_idx); return 0.5 * mid_element1 + 0.5 * mid_element2; } else { return ordered_elems[mid_idx]; } } template <typename T> T Percentile(const std::vector<T>& elems, const double p) { CHECK(!elems.empty()); CHECK_GE(p, 0); CHECK_LE(p, 100); const int idx = static_cast<int>(std::round(p / 100 * (elems.size() - 1))); const size_t percentile_idx = std::max(0, std::min(static_cast<int>(elems.size() - 1), idx)); std::vector<T> ordered_elems = elems; std::nth_element(ordered_elems.begin(), ordered_elems.begin() + percentile_idx, ordered_elems.end()); return ordered_elems.at(percentile_idx); } template <typename T> double Mean(const std::vector<T>& elems) { CHECK(!elems.empty()); double sum = 0; for (const auto el : elems) { sum += static_cast<double>(el); } return sum / elems.size(); } template <typename T> double Variance(const std::vector<T>& elems) { const double mean = Mean(elems); double var = 0; for (const auto el : elems) { const double diff = el - mean; var += diff * diff; } return var / (elems.size() - 1); } template <typename T> double StdDev(const std::vector<T>& elems) { return std::sqrt(Variance(elems)); } template <class Iterator> bool NextCombination(Iterator first, Iterator middle, Iterator last) { return internal::NextCombination(first, middle, middle, last); } template <typename T> T Sigmoid(const T x, const T alpha) { return T(1) / (T(1) + std::exp(-x * alpha)); } template <typename T> T ScaleSigmoid(T x, const T alpha, const T x0) { const T t0 = Sigmoid(-x0, alpha); const T t1 = Sigmoid(x0, alpha); x = (Sigmoid(2 * x0 * x - x0, alpha) - t0) / (t1 - t0); return x; } template <typename T1, typename T2> T2 TruncateCast(const T1 value) { return static_cast<T2>(std::min( static_cast<T1>(std::numeric_limits<T2>::max()), std::max(static_cast<T1>(std::numeric_limits<T2>::min()), value))); } } // namespace colmap
true
0ce03433010f3bb87f7440e8b93cb182fbcf4ff5
C++
threeal/sunny-land
/Image.cpp
UTF-8
796
2.90625
3
[]
no_license
#include <stdio.h> #include "Game.h" #include "Resource.h" Image::Image(std::string name, std::string fileName) { this->name = name; texture = NULL; LoadImage(fileName); } Image::~Image() { if (texture != NULL) { SDL_DestroyTexture(texture); texture = NULL; } } void Image::LoadImage(std::string fileName) { SDL_Surface* surface = IMG_Load(fileName.c_str()); if (surface == NULL) { printf("%s Unable to load image\n", fileName.c_str()); return; } texture = SDL_CreateTextureFromSurface(Game.renderer, surface); width = surface->w; height = surface->h; SDL_FreeSurface(surface); if (texture == NULL) { printf("Unable to create texture\n"); return; } }
true
ad7d2c1b0963199fb033f9ca7d16f1a7c257d4f1
C++
chae-y/coding_test_practices
/map/1302.cpp
UTF-8
422
2.859375
3
[]
no_license
#include<iostream> #include<map> #include<iterator> using namespace std; int main() { int n; cin >> n; map<string, int> m; map<string, int> ::iterator it; for (int i = 0; i < n; i++) { string temp; cin >> temp; m[temp]++; } int maxx = 0; string m_book; for (it = m.begin(); it != m.end(); it++) { if (maxx < it->second) { maxx = it->second; m_book = it->first; } } cout << m_book; return 0; }
true
8145de709a0cd4584f8f40419e47fda6d6896229
C++
Chinmay-20/Generalized-Data-Structure
/GENERALIZEDDATASTRUCTURES.cpp
UTF-8
70,542
3.6875
4
[]
no_license
#include<iostream> using namespace std; template<class h> struct node { h slldata; struct node *next; }; template<class h> class SLL { private: struct node <h>* head; int isize; public: SLL() { head=NULL; isize=0; } ~SLL() { struct node <h>* temp=NULL; while(head!=NULL) { temp=head; head=head->next; delete temp; } cout<<"inside destructor"<<endl; } void insertfirst(h); void displayll(); void insertlast(h); void insertatpos(int,h); int countll(); h deletefirst(); h deletelast(); h deleteatpos(int); }; template<class h> void SLL<h>::insertfirst(h ino) { struct node <h>* newn=NULL; newn=new struct node <h>; newn->next=NULL; newn->slldata=ino; if(head==NULL) { head=newn; } else { newn->next=head; head=newn; } isize++; } template<class h> void SLL<h>::displayll() { struct node <h>* temp=NULL; temp=head; cout<<"the linked list is\n"; while(temp!=NULL) { cout<<"|"<<temp->slldata<<"|->"; temp=temp->next; } } template<class h> void SLL<h>::insertlast(h ino) { struct node <h>* newn=NULL; newn=new struct node<h>; newn->next=NULL; newn->slldata=ino; if(head==NULL) { head=newn; } else { struct node <h>* temp=NULL; temp=head; while(temp->next!=NULL) { temp=temp->next; } temp->next=newn; } isize++; } template<class h> void SLL<h>::insertatpos(int ipos,h ino) { if((ipos<=0)||(ipos>isize+1)) { return; } if(ipos==1) { insertfirst(ino); } else if(ipos==(isize+1)) { insertlast(ino); } else { struct node <h>* newn=NULL; struct node<h>* temp=head; newn=new struct node<h>; newn->next=NULL; newn->slldata=ino; for(int i=0;i<ipos-2;i++) { temp=temp->next; } newn->next=temp->next; temp->next=newn; isize++; } } template<class h> int SLL<h>::countll() { return isize; } template<class h> h SLL<h>::deletefirst() { h ret; struct node <h>* temp=head; if(head==NULL) { return -1; } else { head=temp->next; ret=temp->slldata; delete(temp); } isize--; return ret; } template<class h> h SLL<h>::deletelast() { h ret; struct node <h>* temp=head; if(head==NULL) { return -1; } else if(isize==1) { ret=temp->slldata; delete(temp); head=NULL; } else { while(temp->next->next!=NULL) { temp=temp->next; } ret=temp->next->slldata; delete(temp->next); temp->next=NULL; } isize--; return ret; } template<class h> h SLL<h>::deleteatpos(int ipos) { h ret; if((ipos<=0)||(ipos>isize)) { return -1; } if(ipos==1) { ret=deletefirst(); } else if(ipos==isize) { ret=deletelast(); } else { struct node <h>* temp1=NULL; struct node <h>* temp2=NULL; temp1=head; for(int i=1;i<ipos-1;i++) { temp1=temp1->next; } temp2=temp1->next; temp1->next=temp1->next->next; ret=temp2->slldata; delete(temp2); isize--; return ret; } } ///SINGLY CIRCULAR LINKED LIST template<class a> struct scllnode { a sclldata; struct scllnode *scllnext; }; template<class a> class SCLL { private: struct scllnode <a>* head; struct scllnode <a>* tail; int isize; public: SCLL() { head=NULL; tail=NULL; isize=0; } ~SCLL() { struct scllnode <a>* temp=NULL; while(isize!=0) { temp=head; head=head->scllnext; delete temp; isize--; } cout<<"inside destructor"<<endl; } void insertfirst(a); void display(); int countscll(); void insertlast(a); void insertatpos(int,a); a deletefirst(); a deletelast(); a deleteatpos(int); }; template<class a> void SCLL<a>::insertfirst(a ino) { struct scllnode <a>* newn=NULL; newn=new struct scllnode <a>; newn->scllnext=NULL; newn->sclldata=ino; if((head==NULL)&&(tail==NULL)) { head=newn; tail=newn; } else { newn->scllnext=head; head=newn; } tail->scllnext=head; isize++; } template<class a> void SCLL<a>::display() { struct scllnode <a>* temp=NULL; temp=head; cout<<"the linked list is\n"; do { cout<<"|"<<temp->sclldata<<"|->"; temp=temp->scllnext; }while(temp!=head); } template<class a> int SCLL<a>::countscll() { return isize; } template<class a> void SCLL<a>::insertlast(a ino) { struct scllnode <a>* newn=NULL; newn=new struct scllnode <a>; newn->scllnext=NULL; newn->sclldata=ino; if((head==NULL)&&(tail==NULL)) { head=newn; tail=newn; } else { tail->scllnext=newn; tail=newn; tail->scllnext=head; } isize++; } template<class a> void SCLL<a>::insertatpos(int ipos,a ino) { if((head==NULL)||(tail==NULL)||(ipos<=0)||(ipos>(isize+1))) { return; } else if(ipos==1) { insertfirst(ino); } else if(ipos==(isize+1)) { insertlast(ino); } else { struct scllnode <a>* newn=NULL; struct scllnode <a>* temp=head; newn=new struct scllnode <a>; newn->scllnext=NULL; newn->sclldata=ino; for(int i=1;i<ipos-1;i++) { temp=temp->scllnext; } newn->scllnext=temp->scllnext; temp->scllnext=newn; isize++; } } template<class a> a SCLL<a>::deletefirst() { a ret; struct scllnode <a>* temp=head; if((head==NULL)&&(tail==NULL)) { return -1; } if(head==tail) { delete head; head=NULL; tail=NULL; } else { head=temp->scllnext; tail->scllnext=head; ret=temp->sclldata; delete(temp); } isize--; ///return tail->scllnext->data;///we will get value of first node as we have lost address of first node return ret; } template<class a> a SCLL<a>::deletelast() { a ret; struct scllnode <a>* temp=NULL; struct scllnode <a>* temp2=NULL; if((head==NULL)&&(tail==NULL)) { return (int)-1; } if(head==tail) { temp2=tail; ret=temp->sclldata; delete temp2; head=NULL; tail=NULL; } else { temp=head; while(temp->scllnext->scllnext!=head) { temp=temp->scllnext; } temp2=temp->scllnext; temp->scllnext=head; tail=temp; ret=temp2->sclldata; delete(temp2); } isize--; return ret; } template<class a> a SCLL<a>::deleteatpos(int ipos) { a ret; struct scllnode <a>* temp=NULL; struct scllnode <a>*temp2=NULL; if((ipos<=0)||(ipos>isize)) { return (int)-1; } if(ipos==1) { ret=deletefirst(); } else if(ipos==isize) { ret=deletelast(); } else { temp=head; for(int i=1;i<ipos-1;i++) { temp=temp->scllnext; } temp2=temp->scllnext; temp->scllnext=temp->scllnext->scllnext; ret=temp->scllnext ->sclldata; delete(temp2); isize--; } return ret; } ///DOUBLY LINEAR LINKED LIST template<class n> struct dllnode { n dlldata; struct dllnode *dllnext; struct dllnode *dllprev; }; template<class n> class dll { private: struct dllnode <n>* head; struct dllnode <n>* tail; int isize; public: dll() { head=NULL; tail=NULL; isize=0; } ~dll() { struct dllnode <n>* temp=NULL; while(head!=NULL) { temp=head; head=head->dllnext; delete temp; } cout<<"inside destructor"<<endl; } void insertfirst(n); void displayf(); void displayr(); int countn(); void insertlast(n); void insertatpos(int,n); n deletefirst(); n deletelast(); n deleteatpos(int); }; template<class n> void dll<n>::insertfirst(n ino) { struct dllnode <n>* newn=NULL; newn=new struct dllnode<n>; newn->dllnext=NULL; newn->dllprev=NULL; newn->dlldata=ino; if((head==NULL)&&(tail==NULL)) { head=newn; tail=newn; } else { newn->dllnext=head; head->dllprev=newn; head=newn; } isize++; } template<class n> void dll<n>::displayf() { struct dllnode <n>* temp=NULL; temp=head; cout<<"the linked list in forward direction is\n"; while(temp!=NULL) { cout<<"|"<<temp->dlldata<<"|->"; temp=temp->dllnext; } } template<class n> void dll<n>::displayr() { struct dllnode <n>* temp=NULL; temp=tail; cout<<"the linked list in backward direction is\n"; while(temp!=NULL) { cout<<"|"<<temp->dlldata<<"|<-"; temp=temp->dllprev; } } template<class n> int dll<n>::countn() { return isize; } template<class n> void dll<n>::insertlast(n ino) { struct dllnode <n>* newn=NULL; newn=new struct dllnode<n>; newn->dllnext=NULL; newn->dllprev=NULL; newn->dlldata=ino; if((head==NULL)&&(tail==NULL)) { tail=newn; head=newn; } else { tail->dllnext=newn; newn->dllprev=tail; tail=newn; } isize++; } template<class n> void dll<n>::insertatpos(int ipos,n ino) { struct dllnode <n>* newn=NULL; newn=new struct dllnode<n>; newn->dllnext=NULL; newn->dllprev=NULL; newn->dlldata=ino; if((ipos>(isize+1))||(ipos<=0)) { return; } if(ipos==1) { insertfirst(ino); } else if(ipos==(isize+1)) { insertlast(ino); } else { struct dllnode <n>* temp=NULL; temp=head; for(int i=1;i<ipos-1;i++) { temp=temp->dllnext; } newn->dllnext=temp->dllnext; newn->dllnext->dllprev=newn; temp->dllnext=newn; newn->dllprev=temp; isize++; } } template<class n> n dll<n>::deletefirst() { n ret; if((head==NULL)&&(tail==NULL)) { return (int)-1; } else if(head==tail) { delete head; head=NULL; tail=NULL; } else { head=head->dllnext; ret=head->dllprev->dlldata; delete head->dllprev; head->dllprev=NULL; } isize--; return ret; } template<class n> n dll<n>::deletelast() { n ret; if((head==NULL)&&(tail==NULL)) { return (int)-1; } else if(head==tail) { ret=tail->dlldata; delete tail; head=NULL; tail=NULL; } else { tail=tail->dllprev; ret=tail->dllprev->dlldata; delete tail->dllnext; tail->dllnext=NULL; } isize--; return ret; } template<class n> n dll<n>::deleteatpos(int ipos) { n ret; if((ipos<=0)||(ipos>isize)) { return(int)-1; } if(ipos==1) { ret=deletefirst(); } else if(ipos==isize) { ret=deletelast(); } else { struct dllnode <n>* temp=head; for(int i=1;i<ipos;i++) { temp=temp->dllnext; } temp->dllprev->dllnext=temp->dllnext; temp->dllnext->dllprev=temp->dllprev; ret=temp->dlldata; delete temp; isize--; } return ret; } ///DOUBLY CIRCULAR LINKED LIST template<class c> struct dcllnode { c dclldata; struct dcllnode *dcllnext; struct dcllnode *dcllprev; }; template<class c> class dcll { private: struct dcllnode<c>* head; struct dcllnode<c>* tail; int isize; public: dcll() { head=NULL; tail=NULL; isize=0; } ~dcll() { struct dcllnode<c>* temp=NULL; while(isize!=0) { temp=head; head=head->dcllnext; delete temp; isize--; } cout<<"inside destructor"<<endl; } void insertfirst(c); void displayf(); void displayr(); int countn(); void insertlast(c); void insertatpos(int,c); c deleteatpos(int); c deletefirst(); c deletelast(); }; template<class c> void dcll<c>::insertfirst(c ino) { struct dcllnode<c>* newn=NULL; newn=new struct dcllnode<c>; newn->dcllnext=NULL; newn->dcllprev=NULL; newn->dclldata=ino; if((head==NULL)&&(tail==NULL)) { head=newn; tail=newn; } else { newn->dcllnext=head; head->dcllprev=newn; head=newn; } tail->dcllnext=head; head->dcllprev=tail; isize++; } template<class c> void dcll<c>::displayf() { struct dcllnode<c>* temp=head; cout<<"the linked list in forward direction is\n"; do { cout<<"|"<<temp->dclldata<<"|->"; temp=temp->dcllnext; }while(temp!=head); } template<class c> void dcll<c>::displayr() { struct dcllnode<c>* temp=tail; cout<<"the linked list in backward direction is\n"; do { cout<<"|"<<temp->dclldata<<"|<-"; temp=temp->dcllprev; }while(temp!=tail); } template<class c> int dcll<c>::countn() { return isize; } template<class c> void dcll<c>::insertlast(c ino) { struct dcllnode<c>* newn=NULL; newn=new struct dcllnode<c>; newn->dcllnext=NULL; newn->dcllprev=NULL; newn->dclldata=ino; if((head==NULL)&&(tail==NULL)) { tail=newn; head=newn; } else { tail->dcllnext=newn; newn->dcllprev=tail; tail=newn; } tail->dcllnext=head; head->dcllprev=tail; isize++; } template<class c> void dcll<c>::insertatpos(int ipos,c ino) { if((ipos<=0)||(ipos>=(isize+2))) { return; } else if(ipos==1) { insertfirst(ino); } else if(ipos==(isize+1)) { insertlast(ino); } else { struct dcllnode<c>* newn=NULL; struct dcllnode<c>* temp=head; newn=new struct dcllnode<c>; newn->dcllnext=NULL; newn->dcllprev=NULL; newn->dclldata=ino; for(int i=1;i<ipos-1;i++) { temp=temp->dcllnext; } newn->dcllnext=temp->dcllnext; temp->dcllnext->dcllprev=newn; temp->dcllnext=newn; newn->dcllprev=temp; isize++; } } template<class c> c dcll<c>::deleteatpos(int ipos) { c iret=0; if((ipos<=0)||(ipos>=(isize+1))) { return (int)-1; } if(ipos==1) { iret=deletefirst(); } else if(ipos==isize) { iret=deletelast(); } else { struct dcllnode<c>* temp=head; for(int i=1;i<ipos;i++) { temp=temp->dcllnext; } temp->dcllprev->dcllnext=temp->dcllnext; temp->dcllnext->dcllprev=temp->dcllprev; iret=temp->dclldata; delete temp; isize--; return iret; } } template<class c> c dcll<c>::deletefirst() { c iret=0; if((head==NULL)&&(tail==NULL)) { return -1; } else { head=head->dcllnext; iret=tail->dcllnext->dclldata; delete tail->dcllnext; } tail->dcllnext=head; head->dcllprev=tail; isize--; return iret; } template<class c> c dcll<c>::deletelast() { c iret=0; if((head==NULL)&&(tail==NULL)) { return -1; } else { tail=tail->dcllprev; iret=tail->dcllnext->dclldata; delete tail->dcllnext; } tail->dcllnext=head; head->dcllprev=tail; isize--; return iret; } ///stack using linked list template<class m> struct stllnode { m stlldata; struct stllnode *next; }; ///stack using linked list template<class m> class STLL { private: struct stllnode <m>* head; public: STLL() { head=NULL; } ~STLL() { struct stllnode <m>* temp=NULL; while(head!=NULL) { temp=head; head=head->next; delete temp; } cout<<"inside destructor"<<endl; } void insertfirst(m); void displayll(); m deletefirst(); }; template<class m> void STLL<m>::insertfirst(m ino) { struct stllnode <m>* newn=NULL; newn=new struct stllnode <m>; newn->next=NULL; newn->stlldata=ino; if(head==NULL) { head=newn; } else { newn->next=head; head=newn; } } template<class m> void STLL<m>::displayll() { struct stllnode <m>* temp=NULL; temp=head; cout<<"the stack is\n"; while(temp!=NULL) { cout<<temp->stlldata<<" "; temp=temp->next; } } template<class m> m STLL<m>::deletefirst() { m ret; struct stllnode <m>* temp=head; if(head==NULL) { return (int)-1; } else { head=temp->next; ret=temp->stlldata; delete(temp); } return ret; } ///stack using array template<class y> class arrstack { private: y *arr; int arrsize; int top; public: arrstack(int no) { this->arrsize=no; this->arr=new y[arrsize]; this->top=-1; } ~arrstack() { delete []arr; } void push(y); y pop(); void display(); }; template<class y> void arrstack<y>::push(y ino) { if(top==(arrsize-1)) { return; } top++; arr[top]=ino; } template<class y> void arrstack<y>::display() { cout<<"the stack is\n"; for(int i=(arrsize-1);i>-1;i--) { cout<<arr[i]<<" "; } } template<class y> y arrstack<y>::pop() { y i; if(top==-1) { return -2; } i=arr[top]; top--; return i; } ///queue using array template<class o> class arrqueue { o *arrq; int qfront; int qrear; int qsize; public: arrqueue(int no) { this->qsize=no; this->qfront=-1; this->qrear=-1; this->arrq=new o[qsize]; } ~arrqueue() { delete []arrq; } void enqueue(o); o dequeue(); void display(); }; template<class o> void arrqueue<o>::enqueue(o no) { if((qfront==0)&&(qrear==(qsize-1))||(qrear==(qfront-1))%(qsize-1)) { cout<<"queue is full"; return; } else if(qfront==-1) { qfront=0; qrear=0; arrq[qrear]=no; } else if((qrear==(qsize-1))&&(qfront!=0)) { qrear=0; arrq[qrear]=no; } else { qrear++; arrq[qrear]=no; } } template<class o> o arrqueue<o>::dequeue() { o temp; if(qfront==-1) { cout<<"queue is empty"; return -1; } temp=arrq[qfront]; if(qfront==qrear) { qfront=-1; qrear=-1; } else if(qfront==(qsize-1)) { qfront=0; } else { qfront++; } return temp; } template<class o> void arrqueue<o>::display() { int i=0; cout<<"the queue is\n"; for(i=qfront;i!=qrear;i=(i+1)%qsize) { cout<<arrq[i]; } cout<<arrq[i]; } int main() { int x; cout<<"what to perform \n1.doubly linear linked list.\n2.doubly circular linked list.\n3.singly linear linked list.\n4.singly circular linked list\n5.stack using linked list\n6.stack using array\n7.queue using array\n"<<endl; cin>>x; switch(x) { case 1: { int value=0; int y=0; cout<<"which datatype to perform:\n1.char\n2.int\n3.float\n4.double"; cin>>y; switch(y) { case 1: { dll<char> dllobj; char dlldata=0; int iret=0; cout<<"how many DLLNODEs to enter?"<<endl; cin>>value; cout<<"enter values"<<endl; for(int i=1;i<=value;i++) { cin>>dlldata; dllobj.insertfirst(dlldata); } dllobj.displayf(); cout<<endl; dllobj.displayr(); cout<<endl; iret=dllobj.countn(); cout<<"count of node is:"<<iret<<endl; cout<<"enter the element to be inserted at last"<<endl; cin>>dlldata; dllobj.insertlast(dlldata); dllobj.displayf(); cout<<endl; dllobj.displayr(); cout<<endl; iret=dllobj.countn(); cout<<"count of node is:"<<iret<<endl; cout<<"enter the position and dlldata to be inserted"<<endl; cin>>value>>dlldata; dllobj.insertatpos(value,dlldata); dllobj.displayf(); cout<<endl; dllobj.displayr(); cout<<endl; iret=dllobj.countn(); cout<<"count of node is:"<<iret<<endl; cout<<"after deleting first node"<<endl; cout<<dllobj.deletefirst(); dllobj.displayf(); cout<<endl; dllobj.displayr(); cout<<endl; iret=dllobj.countn(); cout<<"count of node is:"<<iret<<endl; cout<<"after deleting last node"<<endl; cout<<dllobj.deletelast(); dllobj.displayf(); cout<<endl; dllobj.displayr(); cout<<endl; iret=dllobj.countn(); cout<<"count of node is:"<<iret<<endl; cout<<"enter the position to be deleted:"<<endl; cin>>value; cout<<dllobj.deleteatpos(value); dllobj.displayf(); cout<<endl; dllobj.displayr(); cout<<endl; iret=dllobj.countn(); cout<<"count of node is:"<<iret<<endl; } break; case 2: { dll<int> dllobj; int dlldata=0; int iret=0; cout<<"how many DLLNODEs to enter?"<<endl; cin>>value; cout<<"enter values"<<endl; for(int i=1;i<=value;i++) { cin>>dlldata; dllobj.insertfirst(dlldata); } dllobj.displayf(); cout<<endl; dllobj.displayr(); cout<<endl; iret=dllobj.countn(); cout<<"count of node is:"<<iret<<endl; cout<<"enter the element to be inserted at last"<<endl; cin>>dlldata; dllobj.insertlast(dlldata); dllobj.displayf(); cout<<endl; dllobj.displayr(); cout<<endl; iret=dllobj.countn(); cout<<"count of node is:"<<iret<<endl; cout<<"enter the position and dlldata to be inserted"<<endl; cin>>value>>dlldata; dllobj.insertatpos(value,dlldata); dllobj.displayf(); cout<<endl; dllobj.displayr(); cout<<endl; iret=dllobj.countn(); cout<<"count of node is:"<<iret<<endl; cout<<"after deleting first node"<<endl; cout<<dllobj.deletefirst(); dllobj.displayf(); cout<<endl; dllobj.displayr(); cout<<endl; iret=dllobj.countn(); cout<<"count of node is:"<<iret<<endl; cout<<"after deleting last node"<<endl; cout<<dllobj.deletelast(); dllobj.displayf(); cout<<endl; dllobj.displayr(); cout<<endl; iret=dllobj.countn(); cout<<"count of node is:"<<iret<<endl; cout<<"enter the position to be deleted:"<<endl; cin>>value; cout<<dllobj.deleteatpos(value); dllobj.displayf(); cout<<endl; dllobj.displayr(); cout<<endl; iret=dllobj.countn(); cout<<"count of node is:"<<iret<<endl; } break; case 3: { dll<float> dllobj; float dlldata=0; int iret=0; cout<<"how many DLLNODEs to enter?"<<endl; cin>>value; cout<<"enter values"<<endl; for(int i=1;i<=value;i++) { cin>>dlldata; dllobj.insertfirst(dlldata); } dllobj.displayf(); cout<<endl; dllobj.displayr(); cout<<endl; iret=dllobj.countn(); cout<<"count of node is:"<<iret<<endl; cout<<"enter the element to be inserted at last"<<endl; cin>>dlldata; dllobj.insertlast(dlldata); dllobj.displayf(); cout<<endl; dllobj.displayr(); cout<<endl; iret=dllobj.countn(); cout<<"count of node is:"<<iret<<endl; cout<<"enter the position and dlldata to be inserted"<<endl; cin>>value>>dlldata; dllobj.insertatpos(value,dlldata); dllobj.displayf(); cout<<endl; dllobj.displayr(); cout<<endl; iret=dllobj.countn(); cout<<"count of node is:"<<iret<<endl; cout<<"after deleting first node"<<endl; cout<<dllobj.deletefirst(); dllobj.displayf(); cout<<endl; dllobj.displayr(); cout<<endl; iret=dllobj.countn(); cout<<"count of node is:"<<iret<<endl; cout<<"after deleting last node"<<endl; cout<<dllobj.deletelast(); dllobj.displayf(); cout<<endl; dllobj.displayr(); cout<<endl; iret=dllobj.countn(); cout<<"count of node is:"<<iret<<endl; cout<<"enter the position to be deleted:"<<endl; cin>>value; cout<<dllobj.deleteatpos(value); dllobj.displayf(); cout<<endl; dllobj.displayr(); cout<<endl; iret=dllobj.countn(); cout<<"count of node is:"<<iret<<endl; } break; case 4: { dll<double> dllobj; double dlldata=0; int iret=0; cout<<"how many DLLNODEs to enter?"<<endl; cin>>value; cout<<"enter values"<<endl; for(int i=1;i<=value;i++) { cin>>dlldata; dllobj.insertfirst(dlldata); } dllobj.displayf(); cout<<endl; dllobj.displayr(); cout<<endl; iret=dllobj.countn(); cout<<"count of node is:"<<iret<<endl; cout<<"enter the element to be inserted at last"<<endl; cin>>dlldata; dllobj.insertlast(dlldata); dllobj.displayf(); cout<<endl; dllobj.displayr(); cout<<endl; iret=dllobj.countn(); cout<<"count of node is:"<<iret<<endl; cout<<"enter the position and dlldata to be inserted"<<endl; cin>>value>>dlldata; dllobj.insertatpos(value,dlldata); dllobj.displayf(); cout<<endl; dllobj.displayr(); cout<<endl; iret=dllobj.countn(); cout<<"count of node is:"<<iret<<endl; cout<<"after deleting first node"<<endl; cout<<dllobj.deletefirst(); dllobj.displayf(); cout<<endl; dllobj.displayr(); cout<<endl; iret=dllobj.countn(); cout<<"count of node is:"<<iret<<endl; cout<<"after deleting last node"<<endl; cout<<dllobj.deletelast(); dllobj.displayf(); cout<<endl; dllobj.displayr(); cout<<endl; iret=dllobj.countn(); cout<<"count of node is:"<<iret<<endl; cout<<"enter the position to be deleted:"<<endl; cin>>value; cout<<dllobj.deleteatpos(value); dllobj.displayf(); cout<<endl; dllobj.displayr(); cout<<endl; iret=dllobj.countn(); cout<<"count of node is:"<<iret<<endl; } break; } } break; case 2: { int value=0; int x=0; cout<<"which datatype to use:\n1.char\n2.int\n3.float\n4.double\n"; cin>>x; switch(x) { case 1: {///char dcll<char> dcllobj; char data='\0'; cout<<"how many nodes?"<<endl; cin>>value; cout<<"enter values"<<endl; for(int i=1;i<=value;i++) { cin>>data; dcllobj.insertfirst(data); } dcllobj.displayf(); cout<<endl; dcllobj.displayr(); cout<<endl; int iret=0; iret=dcllobj.countn(); cout<<"count of nodes is:"<<iret; cout<<endl; cout<<"enter the element to insert last:"<<endl; cin>>data; dcllobj.insertlast(data); dcllobj.displayf(); cout<<endl; dcllobj.displayr(); cout<<endl; iret=dcllobj.countn(); cout<<"count of nodes is:"<<iret; cout<<endl; cout<<"enter position and data to be inserted"<<endl; cin>>value>>data; dcllobj.insertatpos(value,data); dcllobj.displayf(); cout<<endl; dcllobj.displayr(); cout<<endl; iret=dcllobj.countn(); cout<<"count of nodes is:"<<iret; cout<<endl; cout<<"after deleting first node"<<endl; cout<<"deleted data of first node is:"<<dcllobj.deletefirst(); cout<<endl; dcllobj.displayf(); cout<<endl; dcllobj.displayr(); cout<<endl; iret=dcllobj.countn(); cout<<"count of nodes is:"<<iret; cout<<endl; cout<<"after deleting last node"<<endl; cout<<"deleted data of last node is:"<<dcllobj.deletelast(); cout<<endl; dcllobj.displayf(); cout<<endl; dcllobj.displayr(); cout<<endl; iret=dcllobj.countn(); cout<<"count of nodes is:"<<iret; cout<<endl; cout<<"enter the position to delete"<<endl; cin>>value; iret=dcllobj.deleteatpos(value); cout<<"deleted data of node is"<<iret; cout<<endl; dcllobj.displayf(); cout<<endl; dcllobj.displayr(); cout<<endl; iret=dcllobj.countn(); cout<<"count of nodes is:"<<iret; cout<<endl; } break; case 2: {///int dcll<int> idcllobj; int data=0; cout<<"how many nodes?"<<endl; cin>>value; cout<<"enter values"<<endl; for(int i=1;i<=value;i++) { cin>>data; idcllobj.insertfirst(data); } idcllobj.displayf(); cout<<endl; idcllobj.displayr(); cout<<endl; int iret=0; iret=idcllobj.countn(); cout<<"count of nodes is:"<<iret; cout<<endl; cout<<"enter the element to insert last:"<<endl; cin>>data; idcllobj.insertlast(data); idcllobj.displayf(); cout<<endl; idcllobj.displayr(); cout<<endl; iret=idcllobj.countn(); cout<<"count of nodes is:"<<iret; cout<<endl; cout<<"enter position and data to be inserted"<<endl; cin>>value>>data; idcllobj.insertatpos(value,data); idcllobj.displayf(); cout<<endl; idcllobj.displayr(); cout<<endl; iret=idcllobj.countn(); cout<<"count of nodes is:"<<iret; cout<<endl; cout<<"after deleting first node"<<endl; cout<<"deleted data of first node is:"<<idcllobj.deletefirst(); cout<<endl; idcllobj.displayf(); cout<<endl; idcllobj.displayr(); cout<<endl; iret=idcllobj.countn(); cout<<"count of nodes is:"<<iret; cout<<endl; cout<<"after deleting last node"<<endl; cout<<"deleted data of last node is:"<<idcllobj.deletelast(); cout<<endl; idcllobj.displayf(); cout<<endl; idcllobj.displayr(); cout<<endl; iret=idcllobj.countn(); cout<<"count of nodes is:"<<iret; cout<<endl; cout<<"enter the position to delete"<<endl; cin>>value; iret=idcllobj.deleteatpos(value); cout<<"deleted data of node is"<<iret; cout<<endl; idcllobj.displayf(); cout<<endl; idcllobj.displayr(); cout<<endl; iret=idcllobj.countn(); cout<<"count of nodes is:"<<iret; cout<<endl; } break; case 3: { ///float dcll<float> dcllobj; float data=0.0; cout<<"how many nodes?"<<endl; cin>>value; cout<<"enter values"<<endl; for(int i=1;i<=value;i++) { cin>>data; dcllobj.insertfirst(data); } dcllobj.displayf(); cout<<endl; dcllobj.displayr(); cout<<endl; int iret=0; iret=dcllobj.countn(); cout<<"count of nodes is:"<<iret; cout<<endl; cout<<"enter the element to insert last:"<<endl; cin>>data; dcllobj.insertlast(data); dcllobj.displayf(); cout<<endl; dcllobj.displayr(); cout<<endl; iret=dcllobj.countn(); cout<<"count of nodes is:"<<iret; cout<<endl; cout<<"enter position and data to be inserted"<<endl; cin>>value>>data; dcllobj.insertatpos(value,data); dcllobj.displayf(); cout<<endl; dcllobj.displayr(); cout<<endl; iret=dcllobj.countn(); cout<<"count of nodes is:"<<iret; cout<<endl; cout<<"after deleting first node"<<endl; cout<<"deleted data of first node is:"<<dcllobj.deletefirst(); cout<<endl; dcllobj.displayf(); cout<<endl; dcllobj.displayr(); cout<<endl; iret=dcllobj.countn(); cout<<"count of nodes is:"<<iret; cout<<endl; cout<<"after deleting last node"<<endl; cout<<"deleted data of last node is:"<<dcllobj.deletelast(); cout<<endl; dcllobj.displayf(); cout<<endl; dcllobj.displayr(); cout<<endl; iret=dcllobj.countn(); cout<<"count of nodes is:"<<iret; cout<<endl; cout<<"enter the position to delete"<<endl; cin>>value; iret=dcllobj.deleteatpos(value); cout<<"deleted data of node is"<<iret; cout<<endl; dcllobj.displayf(); cout<<endl; dcllobj.displayr(); cout<<endl; iret=dcllobj.countn(); cout<<"count of nodes is:"<<iret; cout<<endl; } break; case 4: {///double dcll<double> dcllobj; double data=0.0; cout<<"how many nodes?"<<endl; cin>>value; cout<<"enter values"<<endl; for(int i=1;i<=value;i++) { cin>>data; dcllobj.insertfirst(data); } dcllobj.displayf(); cout<<endl; dcllobj.displayr(); cout<<endl; int iret=0; iret=dcllobj.countn(); cout<<"count of nodes is:"<<iret; cout<<endl; cout<<"enter the element to insert last:"<<endl; cin>>data; dcllobj.insertlast(data); dcllobj.displayf(); cout<<endl; dcllobj.displayr(); cout<<endl; iret=dcllobj.countn(); cout<<"count of nodes is:"<<iret; cout<<endl; cout<<"enter position and data to be inserted"<<endl; cin>>value>>data; dcllobj.insertatpos(value,data); dcllobj.displayf(); cout<<endl; dcllobj.displayr(); cout<<endl; iret=dcllobj.countn(); cout<<"count of nodes is:"<<iret; cout<<endl; cout<<"after deleting first node"<<endl; cout<<"deleted data of first node is:"<<dcllobj.deletefirst(); cout<<endl; dcllobj.displayf(); cout<<endl; dcllobj.displayr(); cout<<endl; iret=dcllobj.countn(); cout<<"count of nodes is:"<<iret; cout<<endl; cout<<"after deleting last node"<<endl; cout<<"deleted data of last node is:"<<dcllobj.deletelast(); cout<<endl; dcllobj.displayf(); cout<<endl; dcllobj.displayr(); cout<<endl; iret=dcllobj.countn(); cout<<"count of nodes is:"<<iret; cout<<endl; cout<<"enter the position to delete"<<endl; cin>>value; iret=dcllobj.deleteatpos(value); cout<<"deleted data of node is"<<iret; cout<<endl; dcllobj.displayf(); cout<<endl; dcllobj.displayr(); cout<<endl; iret=dcllobj.countn(); cout<<"count of nodes is:"<<iret; cout<<endl; } break; } break; } case 3: { int ivalue=0; int w=0; cout<<"which datatype to use:\n1.char\n2.int\n3.float\n4.double\n"; cin>>w; switch(w) { case 1: { SLL<char> sllobj; char idata=0; cout<<"how many nodes?"<<endl; cin>>ivalue; cout<<"enter value to be insert"<<endl; for(int i=1;i<=ivalue;i++) { cin>>idata; sllobj.insertfirst(idata); } sllobj.displayll(); cout<<endl; int iret=sllobj.countll(); cout<<"\ncount of node is :"<<iret; cout<<endl; cout<<"enter data to be inserted at last"<<endl; cin>>idata; cout<<endl; sllobj.insertlast(idata); sllobj.displayll(); cout<<endl; iret=sllobj.countll(); cout<<"\ncount of node is :"<<iret; cout<<endl; cout<<"enter the position & data"<<endl; cin>>ivalue>>idata; sllobj.insertatpos(ivalue,idata); sllobj.displayll(); cout<<endl; iret=sllobj.countll(); cout<<"\ncount of node is :"<<iret; cout<<endl; cout<<endl<<"after deleting first node"<<endl; cout<<"data of deleted node is :"<<sllobj.deletefirst(); cout<<endl; sllobj.displayll(); iret=sllobj.countll(); cout<<"\ncount of node is :"<<iret; cout<<endl; cout<<"after deleting last node"<<endl; cout<<"data of deleted node is :"<<sllobj.deletelast(); cout<<endl; sllobj.displayll(); iret=sllobj.countll(); cout<<"\ncount of node is :"<<iret; cout<<endl; cout<<"insert the position to delete node"<<endl; cin>>ivalue; cout<<"data of deleted node is:"<<sllobj.deleteatpos(ivalue); cout<<endl; sllobj.displayll(); iret=sllobj.countll(); cout<<"\ncount of node is :"<<iret; cout<<endl; } break; case 2: { SLL<int> sllobj; int idata=0; cout<<"how many nodes?"<<endl; cin>>ivalue; cout<<"enter value to be insert"<<endl; for(int i=1;i<=ivalue;i++) { cin>>idata; sllobj.insertfirst(idata); } sllobj.displayll(); cout<<endl; int iret=sllobj.countll(); cout<<"\ncount of node is :"<<iret; cout<<endl; cout<<"enter data to be inserted at last"<<endl; cin>>idata; cout<<endl; sllobj.insertlast(idata); sllobj.displayll(); cout<<endl; iret=sllobj.countll(); cout<<"\ncount of node is :"<<iret; cout<<endl; cout<<"enter the position & data"<<endl; cin>>ivalue>>idata; sllobj.insertatpos(ivalue,idata); sllobj.displayll(); cout<<endl; iret=sllobj.countll(); cout<<"\ncount of node is :"<<iret; cout<<endl; cout<<endl<<"after deleting first node"<<endl; cout<<"data of deleted node is :"<<sllobj.deletefirst(); cout<<endl; sllobj.displayll(); iret=sllobj.countll(); cout<<"\ncount of node is :"<<iret; cout<<endl; cout<<"after deleting last node"<<endl; cout<<"data of deleted node is :"<<sllobj.deletelast(); cout<<endl; sllobj.displayll(); iret=sllobj.countll(); cout<<"\ncount of node is :"<<iret; cout<<endl; cout<<"insert the position to delete node"<<endl; cin>>ivalue; cout<<"data of deleted node is:"<<sllobj.deleteatpos(ivalue); cout<<endl; sllobj.displayll(); iret=sllobj.countll(); cout<<"\ncount of node is :"<<iret; cout<<endl; } break; case 3: { SLL<float> sllobj; float idata=0; cout<<"how many nodes?"<<endl; cin>>ivalue; cout<<"enter value to be insert"<<endl; for(int i=1;i<=ivalue;i++) { cin>>idata; sllobj.insertfirst(idata); } sllobj.displayll(); cout<<endl; int iret=sllobj.countll(); cout<<"\ncount of node is :"<<iret; cout<<endl; cout<<"enter data to be inserted at last"<<endl; cin>>idata; cout<<endl; sllobj.insertlast(idata); sllobj.displayll(); cout<<endl; iret=sllobj.countll(); cout<<"\ncount of node is :"<<iret; cout<<endl; cout<<"enter the position & data"<<endl; cin>>ivalue>>idata; sllobj.insertatpos(ivalue,idata); sllobj.displayll(); cout<<endl; iret=sllobj.countll(); cout<<"\ncount of node is :"<<iret; cout<<endl; cout<<endl<<"after deleting first node"<<endl; cout<<"data of deleted node is :"<<sllobj.deletefirst(); cout<<endl; sllobj.displayll(); iret=sllobj.countll(); cout<<"\ncount of node is :"<<iret; cout<<endl; cout<<"after deleting last node"<<endl; cout<<"data of deleted node is :"<<sllobj.deletelast(); cout<<endl; sllobj.displayll(); iret=sllobj.countll(); cout<<"\ncount of node is :"<<iret; cout<<endl; cout<<"insert the position to delete node"<<endl; cin>>ivalue; cout<<"data of deleted node is:"<<sllobj.deleteatpos(ivalue); cout<<endl; sllobj.displayll(); iret=sllobj.countll(); cout<<"\ncount of node is :"<<iret; cout<<endl; } break; case 4: { SLL<double> sllobj; double idata=0; cout<<"how many nodes?"<<endl; cin>>ivalue; cout<<"enter value to be insert"<<endl; for(int i=1;i<=ivalue;i++) { cin>>idata; sllobj.insertfirst(idata); } sllobj.displayll(); cout<<endl; int iret=sllobj.countll(); cout<<"\ncount of node is :"<<iret; cout<<endl; cout<<"enter data to be inserted at last"<<endl; cin>>idata; cout<<endl; sllobj.insertlast(idata); sllobj.displayll(); cout<<endl; iret=sllobj.countll(); cout<<"\ncount of node is :"<<iret; cout<<endl; cout<<"enter the position & data"<<endl; cin>>ivalue>>idata; sllobj.insertatpos(ivalue,idata); sllobj.displayll(); cout<<endl; iret=sllobj.countll(); cout<<"\ncount of node is :"<<iret; cout<<endl; cout<<endl<<"after deleting first node"<<endl; cout<<"data of deleted node is :"<<sllobj.deletefirst(); cout<<endl; sllobj.displayll(); iret=sllobj.countll(); cout<<"\ncount of node is :"<<iret; cout<<endl; cout<<"after deleting last node"<<endl; cout<<"data of deleted node is :"<<sllobj.deletelast(); cout<<endl; sllobj.displayll(); iret=sllobj.countll(); cout<<"\ncount of node is :"<<iret; cout<<endl; cout<<"insert the position to delete node"<<endl; cin>>ivalue; cout<<"data of deleted node is:"<<sllobj.deleteatpos(ivalue); cout<<endl; sllobj.displayll(); iret=sllobj.countll(); cout<<"\ncount of node is :"<<iret; cout<<endl; } break; } break; } case 4: { int value=0; int z=0; cout<<"which datatype to use:\n1.char\n2.int\n3.float\n4.double\n"; cin>>z; switch(z) { case 1: { SCLL<char> scllobj; char ch; cout<<"how many node to enter?"<<endl; cin>>value; cout<<"enter values"<<endl; for(int i=1;i<=value;i++) { cin>>ch; scllobj.insertfirst(ch); } scllobj.display(); int iret=0; iret=scllobj.countscll(); cout<<endl<<"count of node is:"<<iret<<endl; cout<<"enter element to be inserted at end"<<endl; cin>>ch; scllobj.insertlast(ch); scllobj.display(); iret=scllobj.countscll(); cout<<endl<<"count of node is:"<<iret<<endl; int pos=0; cout<<"enter the position and data"<<endl; cin>>pos>>ch; scllobj.insertatpos(pos,ch); scllobj.display(); iret=scllobj.countscll(); cout<<endl<<"count of node is:"<<iret<<endl; cout<<"after deleting first node"<<endl; cout<<"deleted data of node is"<<scllobj.deletefirst()<<endl; scllobj.display(); iret=scllobj.countscll(); cout<<endl<<"count of node is:"<<iret<<endl; cout<<"after deleting last node"<<endl; cout<<"deleted data of node is:"<<scllobj.deletelast()<<endl; scllobj.display(); iret=scllobj.countscll(); cout<<endl<<"count of node is:"<<iret<<endl; cout<<"enter position to delete node:"<<endl; cin>>pos; cout<<"deleted data of node is:"<<scllobj.deleteatpos(pos)<<endl; scllobj.display(); iret=scllobj.countscll(); cout<<endl<<"count of node is:"<<iret<<endl; } break; case 2: { SCLL<int> scllobj; int ch; cout<<"how many node to enter?"<<endl; cin>>value; cout<<"enter values"<<endl; for(int i=1;i<=value;i++) { cin>>ch; scllobj.insertfirst(ch); } scllobj.display(); int iret=0; iret=scllobj.countscll(); cout<<endl<<"count of node is:"<<iret<<endl; cout<<"enter element to be inserted at end"<<endl; cin>>ch; scllobj.insertlast(ch); scllobj.display(); iret=scllobj.countscll(); cout<<endl<<"count of node is:"<<iret<<endl; int pos=0; cout<<"enter the position and data"<<endl; cin>>pos>>ch; scllobj.insertatpos(pos,ch); scllobj.display(); iret=scllobj.countscll(); cout<<endl<<"count of node is:"<<iret<<endl; cout<<"after deleting first node"<<endl; cout<<"deleted data of node is"<<scllobj.deletefirst()<<endl; scllobj.display(); iret=scllobj.countscll(); cout<<endl<<"count of node is:"<<iret<<endl; cout<<"after deleting last node"<<endl; cout<<"deleted data of node is:"<<scllobj.deletelast()<<endl; scllobj.display(); iret=scllobj.countscll(); cout<<endl<<"count of node is:"<<iret<<endl; cout<<"enter position to delete node:"<<endl; cin>>pos; cout<<"deleted data of node is:"<<scllobj.deleteatpos(pos)<<endl; scllobj.display(); iret=scllobj.countscll(); cout<<endl<<"count of node is:"<<iret<<endl; } break; case 3: { SCLL<float> scllobj; float ch; cout<<"how many node to enter?"<<endl; cin>>value; cout<<"enter values"<<endl; for(int i=1;i<=value;i++) { cin>>ch; scllobj.insertfirst(ch); } scllobj.display(); int iret=0; iret=scllobj.countscll(); cout<<endl<<"count of node is:"<<iret<<endl; cout<<"enter element to be inserted at end"<<endl; cin>>ch; scllobj.insertlast(ch); scllobj.display(); iret=scllobj.countscll(); cout<<endl<<"count of node is:"<<iret<<endl; int pos=0; cout<<"enter the position and data"<<endl; cin>>pos>>ch; scllobj.insertatpos(pos,ch); scllobj.display(); iret=scllobj.countscll(); cout<<endl<<"count of node is:"<<iret<<endl; cout<<"after deleting first node"<<endl; cout<<"deleted data of node is"<<scllobj.deletefirst()<<endl; scllobj.display(); iret=scllobj.countscll(); cout<<endl<<"count of node is:"<<iret<<endl; cout<<"after deleting last node"<<endl; cout<<"deleted data of node is:"<<scllobj.deletelast()<<endl; scllobj.display(); iret=scllobj.countscll(); cout<<endl<<"count of node is:"<<iret<<endl; cout<<"enter position to delete node:"<<endl; cin>>pos; cout<<"deleted data of node is:"<<scllobj.deleteatpos(pos)<<endl; scllobj.display(); iret=scllobj.countscll(); cout<<endl<<"count of node is:"<<iret<<endl; } break; case 4: { SCLL<double> scllobj; double ch; cout<<"how many node to enter?"<<endl; cin>>value; cout<<"enter values"<<endl; for(int i=1;i<=value;i++) { cin>>ch; scllobj.insertfirst(ch); } scllobj.display(); int iret=0; iret=scllobj.countscll(); cout<<endl<<"count of node is:"<<iret<<endl; cout<<"enter element to be inserted at end"<<endl; cin>>ch; scllobj.insertlast(ch); scllobj.display(); iret=scllobj.countscll(); cout<<endl<<"count of node is:"<<iret<<endl; int pos=0; cout<<"enter the position and data"<<endl; cin>>pos>>ch; scllobj.insertatpos(pos,ch); scllobj.display(); iret=scllobj.countscll(); cout<<endl<<"count of node is:"<<iret<<endl; cout<<"after deleting first node"<<endl; cout<<"deleted data of node is"<<scllobj.deletefirst()<<endl; scllobj.display(); iret=scllobj.countscll(); cout<<endl<<"count of node is:"<<iret<<endl; cout<<"after deleting last node"<<endl; cout<<"deleted data of node is:"<<scllobj.deletelast()<<endl; scllobj.display(); iret=scllobj.countscll(); cout<<endl<<"count of node is:"<<iret<<endl; cout<<"enter position to delete node:"<<endl; cin>>pos; cout<<"deleted data of node is:"<<scllobj.deleteatpos(pos)<<endl; scllobj.display(); iret=scllobj.countscll(); cout<<endl<<"count of node is:"<<iret<<endl; } break; } break; } case 5: { int ivalue=0; int e=0; cout<<"which datatype to use\n1.char\n2.int\n3.float\n4.double\n"; cin>>e; switch(e) { case 1: { STLL<char> sllobj; char idata='\0'; cout<<"how many nodes?"<<endl; cin>>ivalue; cout<<"enter value to be insert"<<endl; for(int i=1;i<=ivalue;i++) { cin>>idata; sllobj.insertfirst(idata); } sllobj.displayll(); cout<<endl; cout<<"how many nodes to delete?"<<endl; cin>>ivalue; for(int i=1;i<=ivalue;i++) { cout<<"data of deleted node is :"<<sllobj.deletefirst(); cout<<"\n"; } cout<<endl; sllobj.displayll(); cout<<endl; } break; case 2: { STLL<int> sllobj; int idata=0; cout<<"how many nodes?"<<endl; cin>>ivalue; cout<<"enter value to be insert"<<endl; for(int i=1;i<=ivalue;i++) { cin>>idata; sllobj.insertfirst(idata); } sllobj.displayll(); cout<<endl; cout<<"how many nodes to delete?"<<endl; cin>>ivalue; for(int i=1;i<=ivalue;i++) { cout<<"data of deleted node is :"<<sllobj.deletefirst(); cout<<"\n"; } cout<<endl; sllobj.displayll(); cout<<endl; } break; case 3: { STLL<float> sllobj; float idata=0.0; cout<<"how many nodes?"<<endl; cin>>ivalue; cout<<"enter value to be insert"<<endl; for(int i=1;i<=ivalue;i++) { cin>>idata; sllobj.insertfirst(idata); } sllobj.displayll(); cout<<endl; cout<<"how many nodes to delete?"<<endl; cin>>ivalue; for(int i=1;i<=ivalue;i++) { cout<<"data of deleted node is :"<<sllobj.deletefirst(); cout<<"\n"; } cout<<endl; sllobj.displayll(); cout<<endl; } break; case 4: { STLL<double> sllobj; double idata=0.0; cout<<"how many nodes?"<<endl; cin>>ivalue; cout<<"enter value to be insert"<<endl; for(int i=1;i<=ivalue;i++) { cin>>idata; sllobj.insertfirst(idata); } sllobj.displayll(); cout<<endl; cout<<"how many nodes to delete?"<<endl; cin>>ivalue; cout<<"enter value to be insert"<<endl; for(int i=1;i<=ivalue;i++) { cout<<"data of deleted node is :"<<sllobj.deletefirst(); cout<<"\n"; } cout<<endl; sllobj.displayll(); cout<<endl; } break; } break; } case 6: { int q=0,t=0; cout<<"which datatype to use:\n1.char\n2.int\n3.float\n4.double\n"; cin>>t; switch(t) { case 1: { char e=0; cout<<"how many elememts in stack?\n"; cin>>q; arrstack<char> saobj(q); cout<<"enter values\n"; for(int i=0;i<q;i++) { cin>>e; saobj.push(e); } saobj.display(); cout<<endl; cout<<"how many nodes to delete\n"; cin>>q; for(int i=0;i<q;i++) { cout<<"data is:"<<saobj.pop()<<"\n"; } cout<<"how many elememts in stack?\n"; cin>>q; cout<<"enter values\n"; for(int i=0;i<q;i++) { cin>>e; saobj.push(e); } saobj.display(); cout<<endl; } break; case 2: { int e=0; cout<<"how many elememts in stack?\n"; cin>>q; arrstack<int> saobj(q); cout<<"enter values\n"; for(int i=0;i<q;i++) { cin>>e; saobj.push(e); } saobj.display(); cout<<endl; cout<<"how many nodes to delete\n"; cin>>q; for(int i=0;i<q;i++) { cout<<"data is:"<<saobj.pop()<<"\n"; } cout<<"how many elememts in stack?\n"; cin>>q; cout<<"enter values\n"; for(int i=0;i<q;i++) { cin>>e; saobj.push(e); } saobj.display(); cout<<endl; } break; case 3: { float e=0; cout<<"how many elememts in stack?\n"; cin>>q; arrstack<float> saobj(q); cout<<"enter values\n"; for(int i=0;i<q;i++) { cin>>e; saobj.push(e); } saobj.display(); cout<<endl; cout<<"how many nodes to delete\n"; cin>>q; for(int i=0;i<q;i++) { cout<<"data is:"<<saobj.pop()<<"\n"; } cout<<"how many elememts in stack?\n"; cin>>q; cout<<"enter values\n"; for(int i=0;i<q;i++) { cin>>e; saobj.push(e); } saobj.display(); cout<<endl; } break; case 4: { double e=0; cout<<"how many elememts in stack?\n"; cin>>q; arrstack<double> saobj(q); cout<<"enter values\n"; for(int i=0;i<q;i++) { cin>>e; saobj.push(e); } saobj.display(); cout<<endl; cout<<"how many nodes to delete\n"; cin>>q; for(int i=0;i<q;i++) { cout<<"data is:"<<saobj.pop()<<"\n"; } cout<<"how many elements in stack?\n"; cin>>q; cout<<"enter values\n"; for(int i=0;i<q;i++) { cin>>e; saobj.push(e); } saobj.display(); cout<<endl; } break; } } break; case 7: { { int qsize; cout<<"size of arrray is?\n"; cin>>qsize; int t; cout<<"which datatype to use:\n1.char\n2.int\n3.float\n4.double\n"; cin>>t; switch(t) { case 1: { arrqueue<char> quobj(qsize); char ch='\0'; int value=0; cout<<"enter "<<qsize<<" elements\n"; for(int i=1;i<=qsize;i++) { cin>>ch; quobj.enqueue(ch); } quobj.display(); cout<<"\nhow many entries to delete?\n"; cin>>value; for(int i=1;i<=value;i++) { cout<<quobj.dequeue()<<"\n"; } quobj.display(); } break; case 2: { arrqueue<int> quobj(qsize); int ch=0; int value=0; cout<<"enter "<<qsize<<" elements\n"; for(int i=1;i<=qsize;i++) { cin>>ch; quobj.enqueue(ch); } quobj.display(); cout<<"\nhow many entries to delete?\n"; cin>>value; for(int i=1;i<=value;i++) { cout<<quobj.dequeue()<<"\n"; } quobj.display(); } break; case 3: { arrqueue<float> quobj(qsize); float ch=0; int value=0; cout<<"enter "<<qsize<<" elements\n"; for(int i=1;i<=qsize;i++) { cin>>ch; quobj.enqueue(ch); } quobj.display(); cout<<"\nhow many entries to delete?\n"; cin>>value; for(int i=1;i<=value;i++) { cout<<quobj.dequeue()<<"\n"; } quobj.display(); } break; case 4: { arrqueue<double> quobj(qsize); double ch=0; int value=0; cout<<"enter "<<qsize<<" elements\n"; for(int i=1;i<=qsize;i++) { cin>>ch; quobj.enqueue(ch); } quobj.display(); cout<<"\nhow many entries to delete?\n"; cin>>value; for(int i=1;i<=value;i++) { cout<<quobj.dequeue()<<"\n"; } quobj.display(); } break; } } return 0; } }}
true
f8daef2e18dc8fa1a6e9f3f4af384c7f826ef291
C++
shubhamgupta372/lockless_pubsub_framework
/subscriber.cpp
UTF-8
2,252
3.015625
3
[]
no_license
#include<iostream> #include"message.h" #include"pubsubservice.h" #include"subscriber.h" #include<chrono> #include<unistd.h> using namespace std; subscriber::subscriber() { subscriberMessages = new LocklessQueue; msgcount=0; size = 1024; } subscriber::subscriber(size_t size ) { subscriberMessages = new LocklessQueue(size); this->size=size; msgcount=0; } subscriber::~subscriber() { delete subscriberMessages; } LocklessQueue *subscriber::getSubscriberMessages() { return subscriberMessages; } void subscriber::setSubscriberMessages(LocklessQueue subscriberMessagesarg) { *subscriberMessages = subscriberMessagesarg; } void subscriber::addSubscription(string topic, pubsubservice &pubSubService) { pubSubService.addSubscriber(topic, this); } void subscriber::removeSubscription(string topic, pubsubservice &pubSubService) { pubSubService.removeSubscriber(topic, this); } void subscriber::printMessages() { LocklessQueue tempsubscriberMessages = *(getSubscriberMessages()); while(tempsubscriberMessages.get_filled_size()) { message * tempmessage=(tempsubscriberMessages.pop()); cout<<"Message Topic -> " + tempmessage->getTopic() + " : " + tempmessage->getPayload()<<endl; } } string subscriber::getname() { return name; } void subscriber::Run() { while(1){ while(subscriberMessages->get_filled_size()){ message * msg=subscriberMessages->pop(); msgcount++; cout<<"\n**************In Subscriber "<<this->GetThreadName()<<" Run method ***********\n"; cout<<"performing operation for message number " << msgcount<<"\n"; int fact=1,num=10; while(num>0){ fact *=num; num --; } auto end_time = chrono::steady_clock::now(); cout<<"factorial is : "<< fact<<endl; cout<< "************operation finished for " << msgcount <<" message***********\n"; cout << "***********Elapsed time in milliseconds : " << chrono::duration_cast<chrono::milliseconds>(end_time - start_time).count()<< " ms ***********" << endl; msg->finishCount.fetch_sub(1, std::memory_order_relaxed); cout<<"---------finiscount is : "<<msg->finishCount<<" ---------\n"; if(msg->finishCount == 0 && msg->isPublished == true){ //delete msg; cout<<"----------------delete msg----------- \n"; } } } }
true
8597bcea2040a755205fa7a3ec811ede9efcbe08
C++
tjakway/digital-ant-farm
/src/Util.cpp
UTF-8
1,004
2.5625
3
[ "MIT" ]
permissive
#include "Util.hpp" #include "Types.hpp" #include <random> #include <utility> namespace jakway_antf { namespace { //mersenne //see http://stackoverflow.com/questions/5008804/generating-random-integer-from-a-range std::random_device rd; std::mt19937 mersenne_rng(rd()); } template<typename T> T getRandInRangeInclusive(T lower, T upper) { std::uniform_int_distribution<T> distribution(lower, upper); return distribution(mersenne_rng); } //need type specializations because this is compiled into a library and linked //with the test code (to avoid compiling the main project code twice) //only template specializations can be included in library object code, not the templates themselves template POS_TYPE getRandInRangeInclusive<POS_TYPE>(POS_TYPE, POS_TYPE); template int getRandInRangeInclusive<int>(int, int); template<typename T, typename... Args> std::unique_ptr<T> make_unique(Args&&... args) { return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); } }
true
6961c80261606a74c0bec9381fcaf47a30373613
C++
pjt1988/project_euler
/7/main.cpp
UTF-8
1,273
3.578125
4
[]
no_license
#include <iostream> #include <vector> #include <time.h> using namespace std; int main(){ clock_t t0 = clock(); int num_primes=1; int max_prime=2; int iter=3; while(num_primes < 10001){ int check=0; for(int i=2;i<iter;i++){ if(iter % i == 0){ check=1; break; } } if(check==0){ num_primes++; max_prime=iter; } iter+=2; } cout << "And the " << num_primes << "st prime number = " << max_prime << endl; cout << "The slow way took " << ((double)clock() - t0)/CLOCKS_PER_SEC*1000 << " ms." << endl << endl; // //that was one way // //this is another! instead of running the inner loop over all numbers, just check for other prime divisors... clock_t t1 = clock(); vector<int> primes; primes.push_back(2); iter=3; while(primes.size() < 10001){ int check=0; for(int i=0;i<primes.size()-1;i++){ if(iter % primes[i] == 0){ check=1; break; } } if(check == 0) primes.push_back(iter); iter+=2; } cout << "And the " << primes.size() << "st/nd/rd/th prime = "; cout << primes[primes.size()-1] << endl; cout << "The smarter way took " << ((double) clock()-t1)/CLOCKS_PER_SEC*1000 << " ms " << endl; return 0; }
true
feb7e219d994cfb5edec04ac45e8f2b11d2219bd
C++
yejh123/cpp-repos
/练习/练习/文件复制.cpp
GB18030
1,539
3.140625
3
[]
no_license
#include <iostream> #include <fstream> #include <Windows.h> using namespace std; /** * ļ * @param src ԭļ * @param des Ŀļ * @return ture ɹ, false ʧ */ bool CopyFile(const char *src, const char *des) { FILE * fSrc; int err1 = fopen_s(&fSrc, src, "rb"); if (err1) { printf("ļ`%s`ʧ", src); return false; } FILE * fDes; int err2 = fopen_s(&fDes, des, "wb"); if (err2) { printf("ļ`%s`ʧ", des); return false; } unsigned char * buf; unsigned int length; fseek(fSrc, 0, SEEK_END); length = ftell(fSrc); buf = new unsigned char[length + 1]; memset(buf, 0, length + 1); fseek(fSrc, 0, SEEK_SET); fread(buf, length, 1, fSrc); fwrite(buf, length, 1, fDes); fclose(fSrc); fclose(fDes); delete[] buf; return true; } void CopyFile2(const char *src, const char *des) { ifstream in(src, ios::binary); ofstream out(des, ios::binary); if (!in) { cout << "ļʧ" << endl; return; } if (!out) { cout << "ļʧ" << endl; return; } //out << in.rdbuf(); char c[1024] = { 0 }; while (in.read(c, sizeof(char) * 1024)) { out.write(c, sizeof(char) * 1024); } out.write(c, in.gcount()); //Ҫһ,ļȱ1K in.close(); out.close(); cout << "Ƴɹ" << endl; } int main() { SYSTEMTIME sys; GetLocalTime(&sys); printf("%4d-%02d-%02d %02d:%02d:%02d %d", sys.wYear, sys.wMonth, sys.wDay, sys.wHour, sys.wMinute, sys.wSecond, sys.wDayOfWeek); }
true
d53d37aac16c5df675c8cd368d1362e78fa456ce
C++
ShreyashRoyzada/DSA-Practice-
/LeetCode/#413. Arithmetic Slices.cpp
UTF-8
628
2.671875
3
[]
no_license
class Solution { public: int numberOfArithmeticSlices(vector<int>& A) { if(A.size()<3) return 0; vector<int> res (A.size(),0); for(int i = 2;i<A.size();i++) { if(A[i]-A[i-1] == A[i-1]-A[i-2]) { if(res[i-1]>0) { res[i] = res[i-1]+1; } else { res[i]++; } } } int ans = 0; for(int i = 0;i<res.size();i++) { ans = ans+res[i]; } return ans; } };
true
5636b686fae0e4a70e1678e05b28de422cc81dae
C++
dany74q/sshpassten
/sshpassten.hpp
UTF-8
2,536
2.96875
3
[ "MIT" ]
permissive
#pragma once #include "pseudo_terminal_manager.hpp" #include <string> #include <vector> #include <memory> #include <unistd.h> namespace sshpassten { namespace detail { inline namespace v1 { /* SSHPassten is a C++14 mini-port of SSHPass (Not every feature was implemented). This utility provides the ability to pass SSH passwords via an argument, so you could automate password-based SSH session creation. How it works: 1. We create a valid PTY (Pseudo-Terminal) pair (Master & Slave) 2. We fork the process 3. The child is going to create a new Session (via setsid) and attach itself to the afforementioned PTY-slave 4. The parent is going to handle slave input and output via the master PTY A simple diagram showing the I/O flow: stdout stdin stdin ▲ | | | | | | | ◀- ------------ ----------- | ----------- ----------- | | | | | | | | | | Parent |<---------->| Master |<---------->| Slave |<---------->| Child | | | | PTY | | | PTY | | (SSH) | ------------ ----------- | ----------- ----------- -▶ | | | | | ▼ stdin stdout Support for handling the SSH prompt was added as well. */ struct SSHPassten { int run(int argc, char** argv); private: /* Usage: sshpassten -p password -- ssh -o StrictHostKeyChecking=no -o PubkeyAuthentication=no user@host */ void parseArgs(int argc, char** argv); /* We're going to fork, and the child handler will be execvp-ing itself to the passed SSH command. */ int childHandler() const; /* The parent handler will handle input from the created pseudo-terminal. */ int parentHandler() const; private: std::string password_; std::vector<std::string> command_; std::unique_ptr<PseudoTerminalManager> manager_; pid_t childPID_; }; } } }
true
d433a937338e54c711cc061fb7432b3046401c7f
C++
refinap/Pulse-Convertion-to-voltage
/Konversi_Pulsa_Jarak_Ke_tegangan.ino
UTF-8
1,256
2.765625
3
[ "CC0-1.0" ]
permissive
;/* =============================================================================== ;Program untuk konversi pulsa jarak ke tegangan ;------------------------------------------------------------------------------------ ; Komponen : ; Encoder ; Arduino Nano ; Resistor 1K ; Kapasitor 220uF ;------------------------------------------------------------------------------------*/ ;=== Deklarasi Variabel === #define CHB 2 ;pin 2 sebagai Channel B #define CHA 3 ;pin 3 sebagai Channel A #define arah 4 ;pin 4 sebagai keluaran digital untuk arah motor #define PWM 5 ;pin 5 sebagai output PWM #define PPR 500 ;deklarasi nilai PPR int distance, pulse, tegangan ; bool direction, ;=== Program === void setup() { pinMode (CHA, INPUT); pinMode (CHB, INPUT); pinMode (arah, 4); pinMode (PWM, 4); attachInterrupt(digitalPinToInterrupt(CHB), encoder, RISING); } void loop() { distance = (500/pulse)*250; tegangan = map (distane, 0,250,0,255); analogWrite (PWM, tegangan); digitalWrite (arah, direction); } void encoder1 () { if (digitalRead(CHA) == 0) { pulse --; direction = 0; // Putar maju } else { pulse ++; direction = 1; // Putar mundur } }
true
36eb667abce07503bfd4f08d357d8b1b7ba865df
C++
everpan/tidp
/include/TL_DictMap.h
UTF-8
2,629
2.890625
3
[]
no_license
/* * File: TL_DictMap.h * Author: everpan * * Created on 2011年6月22日, 下午3:41 */ #ifndef TL_DICTMAP_H #define TL_DICTMAP_H #include <map> #include <stdlib.h> #include "TL_Exp.h" namespace tidp { template <class T> class TL_DictMap { public: TL_DictMap() { _kv.clear(); _vk.clear(); _k = 0; _min_k = 0; } void erase(unsigned int k) { std::map<unsigned int, T>::iterator it = _kv.find(k); if (it != _kv.end()) { _kv.erase(it); _vk.erase(_kv[k]); } } T operator[](unsigned int k) { typename std::map<unsigned int, T>::iterator it = _kv.find(k); if (it == _kv.end()) { char c[100]; sprintf(c, "TL_DictMap::can't find key[%d].", k); throw TL_Exp(c); } return it->second; } unsigned int operator[](const T& v) { std::map<T, unsigned int>::iterator it = _vk.find(v); if (it == _vk.end()) { char c[100]; sprintf(c, "TL_DictMap::can't find value"); //todo throw TL_Exp(c); } return 0; } void add(unsigned k, const T& v) { if(k==(unsigned int)(-1)){ throw TL_Exp("TL_DictMap::add the key is invaild.k=unsigned int)(-1)"); } typename std::map<unsigned int, T>::iterator it = _kv.find(k); if (it != _kv.end() && it->second != v) { _vk.erase(_kv[k]); } _kv[k] = v; _vk[v] = k; } unsigned int add(const T& v) { typename std::map<T, unsigned int>::iterator it = _vk.find(v); if (it == _vk.end()) { ++_k; while (_kv.find(_k) != _kv.end()) { ++_k; } _kv[_k] = v; _vk[v] = _k; return _k; } return it->second; } unsigned int findk(const T& v) { typename std::map<T, unsigned int>::iterator it = _vk.find(v); if (it == _vk.end()) { return (unsigned int)(-1); } return it->second; } /* T findV(unsigned int k){ }*/ private: std::map<unsigned int, T> _kv; std::map<T, unsigned int> _vk; unsigned int _k; unsigned int _min_k; }; } #endif /* TL_DICTMAP_H */
true
5c6bf7c6cd4c1814d54afbedc1dfb50df8d4aa31
C++
hemanth5585/LintCode
/Others/574.Build-Post-Office/574.Build-Post-Office.cpp
UTF-8
1,612
3.125
3
[]
no_license
class Solution { public: /** * @param grid: a 2D grid * @return: An integer */ int shortestDistance(vector<vector<int>> &grid) { int m = grid.size(); int n = grid[0].size(); vector<int>countX(n); for (int j=0; j<n; j++) for (int i=0; i<m; i++) { if (grid[i][j]==1) countX[j]+=1; } vector<int>countY(m); for (int i=0; i<m; i++) for (int j=0; j<n; j++) { if (grid[i][j]==1) countY[i]+=1; } vector<int>sumDist2x = helper(countX); vector<int>sumDist2y = helper(countY); int ret = INT_MAX; for (int i=0; i<m; i++) for (int j=0; j<n; j++) { if (grid[i][j]==0) { ret = min(ret, sumDist2x[j]+sumDist2y[i]); } } if (ret==INT_MAX) return -1; else return ret; } vector<int>helper(vector<int>& count) { int n = count.size(); vector<int>ret(n); int sum = 0; for (int i=0; i<n; i++) sum += i*count[i]; int total = accumulate(count.begin(), count.end(), 0); int precount = count[0]; ret[0] = sum; for (int i=1; i<n; i++) { ret[i] = ret[i-1] + precount - (total - precount); precount += count[i]; } return ret; } };
true
808d45ec06d0136c7dd7a6b686adae0039dccb0d
C++
muripic/tp_algoritmos2
/src/Registro.h
UTF-8
589
2.59375
3
[]
no_license
#ifndef __REGISTRO_H__ #define __REGISTRO_H__ #include <string> #include "Tipos.h" #include "modulos_basicos/string_map.h" using namespace std; class Registro { public: Registro(); void definir(const NombreCampo& campo, const Valor& valor); const linear_set<NombreCampo>& campos() const; Valor& operator[](const NombreCampo& campo); const Valor& operator[](const NombreCampo& campo) const; bool operator==(const Registro& registro) const; void borrarCampo(const NombreCampo &campo); private: string_map<Valor> _registro; }; #endif /*__REGISTRO_H__*/
true
5f209f73c4d4bbd2cef1b96cb2379037176ce2cd
C++
luyiming112233/PatCodeRepo
/PatCodeRepo/PatBasic/Basic1027.cpp
GB18030
776
2.84375
3
[]
no_license
#include<cstdio> int main() { int a[100] = { 0,1 }, num, l, k, i, j; char c; scanf("%d %c", &num, &c); for (i = 2; i < 100; i++) { a[i] = a[i - 1] + 2 * (2 * i - 1); } for (i = 1; i < 100; i++) { if (a[i] > num) { l = num - a[i - 1]; k = i - 1; break; } } for (i = 0; i < k - 1; i++) { //ӡո for (j = 0; j < i; j++) printf(" "); //ӡ for (j = 0; j < (k - 1 - i) * 2 + 1; j++) printf("%c", c); printf("\n"); } //ӡмո for (j = 0; j < k - 1; j++) printf(" "); printf("%c\n", c); for (i = 0; i < k - 1; i++) { //ӡո for (j = 0; j < k - 2 - i; j++) printf(" "); //ӡ for (j = 0; j < i * 2 + 3; j++) printf("%c", c); printf("\n"); } printf("%d\n", l); return 0; }
true
d2c58186bac19fbe10cff3280b91dc2a0715ed37
C++
sanchitgoel10/365_of_code
/MMASS SOPJ.cpp
UTF-8
1,049
2.921875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main(){ string s; while(cin >> s){ int n = s.size(); stack <int> Stack; for(int i = 0; i < n; i++){ if(s.at(i) == '('){ Stack.push(-1); } else if(s.at(i) == ')'){ int x = 0; while(Stack.top() != -1&&!Stack.empty()){ x += Stack.top(); Stack.pop(); } Stack.pop(); Stack.push(x); } else if(isdigit(s.at(i))){ int x = Stack.top(); Stack.pop(); Stack.push(x * ((int)(s.at(i)) - 48)); } else if(isalpha(s.at(i))){ if(s.at(i) == 'H'){ Stack.push(1); } else if(s.at(i) == 'C'){ Stack.push(12); } else { Stack.push(16); } } } int sum = 0; while(!Stack.empty()){ sum += Stack.top(); Stack.pop(); } cout << sum << endl; } return 0; }
true
873a6f757904d933bf388ae7149a20aecd5084e9
C++
mikhaputri/Review-Chapter-2
/4. Restaurant Bill.cpp
UTF-8
672
2.90625
3
[]
no_license
// // 4.cpp // REVIEW BAGUS // // Created by Mikha Yupikha on 11/10/2016. // Copyright © 2016 Mikha Yupikha. All rights reserved. // #include <iostream> using namespace std; int main() { double meal = 88.67; double mealTax = 0.0675; double tipCharge = 0.2; double mealCost = meal + (meal*mealTax); double taxAmount = meal*mealTax; double tipAmount = mealCost*tipCharge; double totalBill = mealCost + tipAmount; cout<< " The meal cost is "<< mealCost<< endl; cout<< " The tax amount is "<< taxAmount<<endl; cout<< " The tip amount is "<<tipAmount<<endl; cout<< " The total bill is "<<totalBill<<endl; return 0; }
true