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
2b75db6326ac321a98e38ebfc91e32afcc991b1e
C++
Vipulk1605/Competitive_Coding
/28.Recursion_IV_Subset_Based/03.0_1_Knapsack_Recursion.cpp
UTF-8
594
3.015625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int profit(int n, int c, int *wt, int *prices){ if(n == 0 || c == 0){ return 0; } //rec case int ans = 0; int inc, exc; inc = exc = INT_MIN; //include if(wt[n-1] <= c) inc = prices[n-1] + profit(n-1, c-wt[n-1], wt, prices); //exclude exc = profit(n-1, c, wt, prices); ans = max(inc, exc); return ans; } int main() { int weights[] = {1, 2, 3, 5}; int prices[] = {40, 20, 30, 100}; int n = 4; int c = 7; cout << profit(n, c, weights, prices); return 0; }
true
ffd731e18fc2a95a7e418fd6192b86790e9a09d9
C++
malaya7/CS150-intro-to-programming-Cpp
/h28/person.h
UTF-8
240
2.796875
3
[]
no_license
#ifndef PERSON_H #define PERSON_H #include <string> class Person { public: Person(); Person(const std::string&name, int age); std::string getName() const; int getAge() const; private: std::string name; int age; }; #endif
true
398003dfdbf6ddf1ba3ff3c36ad7cf1563ecb45f
C++
Danverr/HSE-Course
/module-1/homework/BigInteger/biginteger.h
UTF-8
1,871
2.90625
3
[]
no_license
#include <iostream> #include <vector> #include <string> #include <cmath> class BigInteger { public: const int BASE = 10; const int DIGITS_LEN = log10(BASE); BigInteger(); BigInteger(int); BigInteger(long long int); BigInteger(std::string); std::string toString() const; bool operator==(const BigInteger&) const; bool operator!=(const BigInteger&) const; bool operator>(const BigInteger&) const; bool operator>=(const BigInteger&) const; bool operator<(const BigInteger&) const; bool operator<=(const BigInteger&) const; friend BigInteger abs(const BigInteger&); friend BigInteger max(const BigInteger&, const BigInteger&); friend BigInteger min(const BigInteger&, const BigInteger&); BigInteger& operator=(const BigInteger&); BigInteger operator-() const; BigInteger operator+(const BigInteger&) const; BigInteger operator-(const BigInteger&) const; BigInteger operator*(const BigInteger&) const; BigInteger operator/(const int&) const; BigInteger operator/(const BigInteger&) const; BigInteger operator%(const BigInteger&) const; BigInteger& operator+=(const BigInteger&); BigInteger& operator-=(const BigInteger&); BigInteger& operator*=(const BigInteger&); BigInteger& operator/=(const int&); BigInteger& operator/=(const BigInteger&); BigInteger& operator%=(const BigInteger&); BigInteger& operator--(); BigInteger operator--(int); BigInteger& operator++(); BigInteger operator++(int); operator bool() const; friend std::ostream& operator<<(std::ostream&, const BigInteger&); friend std::istream& operator>>(std::istream&, BigInteger&); private: bool isNeg = false; std::vector<int> digits = { }; int getDigit(const int) const; BigInteger& add(const BigInteger&, const bool); void trim(); }; std::ostream& operator<<(std::ostream&, const BigInteger&); std::istream& operator>>(std::istream&, BigInteger&);
true
601d94dfdf510fa75f7738f9dcfc4ffd6fc4bbba
C++
Inflanty/cpp_course
/Fractal/CFractalCreator.h
UTF-8
1,153
2.640625
3
[]
no_license
// Name : CFractalCreator.h #ifndef _FRACTALCREATOR_H_ #define _FRACTALCREATOR_H_ #include <string> #include <utility> #include <vector> #include "CBitmap.h" #include "CMandelbrot.h" #include "CZoomList.h" #include "CZoom.h" #include "CRGB.h" using namespace bitmap; class CFractalCreator { public: static const int MAX_ITERATIONS{1000}; int const WIDTH{1920}; int const HEIGHT{1080}; private: int m_width; int m_height; int m_total; bool m_bGotFirstRange{false}; CBitmap m_bitmap; CZoomList m_zoomList; CMandelbrot m_mandlebrot; unique_ptr<int[]> fractal; unique_ptr<int[]> histogram; std::vector<int> m_ranges; std::vector<CRGB> m_colors; std::vector<int> m_rangesTotals; static int getIterations(double x, double y); void calculateIterations(); void calculateTotalIterations(); void calculateRangeTotals(); void drawFractal(); bool writeBitmap(std::string name); public: CFractalCreator(const int width, const int height); virtual ~CFractalCreator(); void addRange(double rangeEnd, const CRGB& rgb); void addZoom(const CZoom& zoom); void buildFractal(std::string name); int getRange(int iterations) const; }; #endif // _FRACTALCREATOR_H_
true
d0f6a6a07bcd732b59902eb82cdacb9532d02fdd
C++
AlexisAubineau/StarShooter
/StarShooter/HitBoxComponent.h
UTF-8
1,129
2.515625
3
[]
no_license
#ifndef HITBOXCOMPONENT_H #define HITBOXCOMPONENT_H #include <list> #include <SFML/Graphics.hpp> class Entity; class HitboxComponent { private: sf::Sprite& sprite; sf::RectangleShape hitbox; sf::FloatRect nextPosition; float offsetX; float offsetY; std::string m_tag; bool CanDamage; public: std::list<std::string> CollisionTagList; HitboxComponent(sf::Sprite& sprite, float offset_x, float offset_y, float width, float height, bool isDebug); ~HitboxComponent(); //Accessors const sf::Vector2f& getPosition() const; const sf::FloatRect getGlobalBounds() const; const sf::FloatRect& getNextPosition(const sf::Vector2f& velocity); //Modifiers void setPosition(const sf::Vector2f& position); void setPosition(const float x, const float y); void SetCollisionEnable(bool state, std::list<Entity*> EntityList); void setTag(std::string tag); std::string GetTag(); // Functions bool Intersets(const sf::FloatRect& frect); std::string CheckColliderInfo(HitboxComponent* Collider); void update(); void render(sf::RenderTarget* target); void debugOutline(bool isDebug); }; #endif // HITBOXCOMPONENT_H
true
b2a7d70634625ab9d2a5f9030e6479d40a1eff59
C++
AnkilP/ieeextreme_prep
/google_kick/circlething.cpp
UTF-8
4,111
3.125
3
[ "MIT" ]
permissive
#include <vector> #include <queue> #include <algorithm> #include <iostream> using namespace std; class Solution { public: queue<pair<int,int>> bfs_q; void traverse_graph(vector<vector<int>>& A, vector<vector<int>>& visited, int index1, int index2){ if(index1 + 1 < A.size()){ if(A[index1 + 1][index2] == 1 && visited[index1 + 1][index2] == 0){ visited[index1+1][index2] = 1; traverse_graph(A, visited, index1 + 1, index2); } else if(A[index1 + 1][index2] == 0 && visited[index1 + 1][index2] == 0){ bfs_q.emplace(index1+1, index2); } } if(index1 - 1 >= 0){ if(A[index1 - 1][index2] == 1 && visited[index1 - 1][index2] == 0){ visited[index1-1][index2] = 1; traverse_graph(A, visited, index1 - 1, index2); } else if(A[index1 - 1][index2] == 0 && visited[index1 - 1][index2] == 0){ bfs_q.emplace(index1-1, index2); } } if(index2 + 1 < A[0].size()){ if(A[index1][index2+1] == 1 && visited[index1][index2+1] == 0){ visited[index1][index2+1] = 1; traverse_graph(A, visited, index1, index2+1); } else if(A[index1][index2+1] == 0 && visited[index1][index2+1] == 0){ bfs_q.emplace(index1, index2+1); } } if(index2 - 1 >= 0){ if(A[index1][index2-1] == 1 && visited[index1][index2-1] == 0){ visited[index1][index2-1] = 1; traverse_graph(A, visited, index1, index2-1); } else if(A[index1][index2-1] == 0 && visited[index1][index2-1] == 0){ bfs_q.emplace(index1, index2-1); } } } void printVec(const vector<vector<int>> &A){ for (int i = 0; i < A.size(); i++) { for (int j = 0; j < A[i].size(); j++) { cout << A[i][j]; } cout << endl; } cout << endl; } void find_firstIsland(vector<vector<int>>& A, vector<vector<int>>& visited, int & index1, int & index2){ for(int i = 0; i < A.size(); ++i){ for(int j = 0; j < A[0].size(); ++j){ if(A[i][j] == 1 && visited[i][j] == 0){ visited[i][j] = 1; traverse_graph(A, visited, i, j); index1 = i; index2 = j; return; } } } } int traverse_BFS(vector<vector<int>>& A, vector<vector<int>>& visited){ int bridgeLength = 0; while(!bfs_q.empty()){ auto size = bfs_q.size(); while(size--){ int x = bfs_q.front().first; int y = bfs_q.front().second; bfs_q.pop(); if(A[x][y] == 1 && visited[x][y] == 0){ return bridgeLength; } else{ visited[x][y] = 2; if(x + 1 < A.size() && visited[x+1][y] == 0){ bfs_q.emplace(x+1, y); } if(x - 1 >= 0 && visited[x-1][y] == 0){ bfs_q.emplace(x-1, y); } if(y + 1 < A[0].size() && visited[x][y+1] == 0){ bfs_q.emplace(x, y+1); } if(y -1 >= 0 && visited[x][y-1] == 0){ bfs_q.emplace(x, y-1); } } } bridgeLength++; } return -1; } int shortestBridge(vector<vector<int>>& A) { vector<vector<int> > visited(A.size(), vector<int> (A[0].size(), 0)); int idx1, idx2; find_firstIsland(A, visited, idx1, idx2); return traverse_BFS(A,visited); } }; int main(){ Solution x = Solution(); vector<vector<int> > A = {{0,1},{1,0}}; vector<vector<int> > B = {{0,1,0},{0,0,0},{0,0,1}}; cout << x.shortestBridge(B) << endl; }
true
a54e86425aaff8e60ced2523bf5b936277974d25
C++
liangcevv/StudentManagementSystem
/searchdialog.cpp
UTF-8
2,311
2.59375
3
[ "MIT" ]
permissive
#include "searchdialog.h" #include "ui_searchdialog.h" #include "mainwindow.h"; #include "common.h" SearchDialog::SearchDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SearchDialog) { ui->setupUi(this); } SearchDialog::~SearchDialog() { delete ui; } void SearchDialog::initUi() { // clean window ui->student_tableWidget->clear(); ui->student_tableWidget->setRowCount(0); ui->id_textEdit->clear(); ui->name_textEdit->clear(); ui->gender_comboBox->clear(); ui->major_comboBox->clear(); // fill combo Box QSqlQuery query; query.exec(QString("SELECT name FROM major")); ui->major_comboBox->addItem(QString("")); while(query.next()){ ui->major_comboBox->addItem(QString(query.value(0).toString())); } ui->gender_comboBox->addItem(QString("")); ui->gender_comboBox->addItem(QString("male")); ui->gender_comboBox->addItem(QString("female")); } void SearchDialog::on_search_pushButton_clicked() { QSqlQuery query; QString sql = "SELECT s.id, s.name, s.gender, m.name major, m.course FROM students s, major m WHERE s.major_id = m.id"; QString id = ui->id_textEdit->toPlainText(); if(id != "") { sql += QString(" AND s.id = \"%1\"").arg(id); query.exec(sql); } else { QString name = ui->name_textEdit->toPlainText(), gender = ui->gender_comboBox->currentText(), major = ui->major_comboBox->currentText(); if(name != ""){ sql += QString(" AND s.name = \"%1\"").arg(name); } if(gender != ""){ sql += QString(" AND s.gender = \"%1\"").arg(gender); } if(major != ""){ sql += QString(" AND m.name = \"%1\"").arg(major); } query.exec(sql); } if(query.size() == 0) { QMessageBox::information(this, "Note", "No matching student information"); return; } int row = 0; while(query.next()){ ui->student_tableWidget->setRowCount(row + 1); for (int i = 0; i < 5; i++){ ui->student_tableWidget->setItem(row, i, new QTableWidgetItem(query.value(i).toString())); } row++; } }
true
562a889b7c919991864f52280f736f651a5fb8d6
C++
EasonZhu/rcc
/vxl/vxl-1.13.0/core/vidl_vil1/examples/vidl_vil1_mpegcodec_example.cxx
UTF-8
2,146
2.625
3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
// This is an example of how to use vidl_vil1_mpegcodec, // written by Ming Li(ming@mpi-sb.mpg.de), // Max-Planck-Institut fuer Informatik, Germany, 29 Jan 2003. // may not work for some format mpeg2 files due to the fixed // load_mpegcodec_callback function !! #include <vcl_cassert.h> #include <vcl_cstdlib.h> #include <vil1/vil1_save.h> #include <vidl_vil1/vidl_vil1_io.h> #include <vidl_vil1/vidl_vil1_mpegcodec.h> #include <vidl_vil1/vidl_vil1_movie.h> #include <vidl_vil1/vidl_vil1_frame.h> static void my_load_mpegcodec_callback(vidl_vil1_codec * vc) { bool grey_scale = false; bool demux_video = true; vcl_string pid = "0x00"; int numframes = -1; vidl_vil1_mpegcodec * mpegcodec = vc->castto_vidl_vil1_mpegcodec(); if (!mpegcodec) return; mpegcodec->set_grey_scale(grey_scale); if (demux_video) mpegcodec->set_demux_video(); mpegcodec->set_pid(pid.c_str()); mpegcodec->set_number_frames(numframes); mpegcodec->init(); } int main(int argc, char* argv[]) { if (argc < 2) { vcl_cerr << "Please specify an MPEG movie file as first command line argument.\n" << "The middle frame will then be saved to a file named test.ppm\n"; return 1; } vidl_vil1_io::register_codec(new vidl_vil1_mpegcodec); vidl_vil1_mpegcodec *mpegcodec=new vidl_vil1_mpegcodec; vidl_vil1_io::register_codec(mpegcodec); vidl_vil1_io::load_mpegcodec_callback=&my_load_mpegcodec_callback; vidl_vil1_movie_sptr movie = vidl_vil1_io::load_movie(argv[1]); assert( movie ); assert( movie->length()>0 ); vcl_cout << "Length = " << movie->length() << vcl_endl << "Width = " << movie->width() << vcl_endl << "Height = " << movie->width() << vcl_endl; //traverse the movie sequence int i=0; for (vidl_vil1_movie::frame_iterator pframe = movie->first(); pframe <= movie->last(); ++pframe,i++) { vil1_image im = pframe->get_image(); vcl_cout << "decode frame " << i << vcl_endl; } //random frame access vil1_image im=movie->get_image(movie->length()/2); vil1_save(im,"test.ppm"); mpegcodec->close(); vcl_exit (0); return 0; }
true
74a8eb2cb6cb127cfc27a1281cf591d0ec0b84d2
C++
xxjwxc/oauth2
/oauth2Client/cpp/oauth2Client/Public_linux/src/Tools/MyStream/MyStreamBase.h
GB18030
2,865
2.671875
3
[]
no_license
/******************************************************************** ʱ: 2017/05/25 15:06:23 ļ: MyStreamBase.h : лС emal: 346944475@qq.com : 1.лл 2. ˵: 1. ֧map,vector,stringͣ 2. ָ֧лл *********************************************************************/ #ifndef __MYSTREAM_BASE_H_ #define __MYSTREAM_BASE_H_ #include <string> #include <boost/smart_ptr/scoped_array.hpp> #include <vector> #include <map> #include <set> #include "../DefineBase.h" class CMyStreamBase { //л public: void OnSetBuffer(boost::scoped_array<unsigned char> & src, MY_UINT32 len); void OnSetBuffer(boost::scoped_array<signed char> & src, MY_UINT32 len); bool IsEnd(); //л public: MY_UINT32 Size(); void Clear(); MY_UINT32 OnGetBuffer(boost::scoped_array<unsigned char> & ptr); MY_UINT32 OnGetBuffer(boost::scoped_array<signed char> & ptr); std::vector<unsigned char> OnGetBuffer(); //л public: template <typename T> CMyStreamBase & Push(const T & val); CMyStreamBase & Push(const std::string & val); template <typename T> CMyStreamBase & Push(const std::vector<T> &val); template <typename T, typename P> CMyStreamBase & Push(const std::map<T, P> &val); template <typename T> CMyStreamBase & Push(const std::set<T> &val); template<typename T> CMyStreamBase& operator<<(const T & roData); //л public: template <typename T> CMyStreamBase & Pop(T & val); CMyStreamBase & Pop(std::string & val); template <typename T> CMyStreamBase & Pop(std::vector<T> &val); template <typename T, typename P> CMyStreamBase & Pop(std::map<T, P> &val); template <typename T> CMyStreamBase & Pop(std::set<T> &val); template<typename T> CMyStreamBase& operator>>(T & roData); private://ֹ template <typename T> CMyStreamBase & Push(const T * val) = delete; template <typename T> CMyStreamBase & Push(T * val) = delete; template<typename T> CMyStreamBase& operator<<(const T * roData) = delete; template<typename T> CMyStreamBase& operator<<(T * roData) = delete; template <typename T> CMyStreamBase & Pop(const T * val) = delete;//error template <typename T> CMyStreamBase & Pop(T * val) = delete;//error template <typename T> CMyStreamBase & Pop(const T & val) = delete;//error template<typename T> CMyStreamBase& operator>>(T * roData)=delete; private: void Memcpy(void * _Des, size_t _Size);//л void Memcpy(const void * _Src, size_t _Size);//л std::vector<unsigned char> m_ver; MY_UINT32 m_indexPop = 0; }; #endif // !__MYSTREAM_BASE_H_
true
973e877d1f495a4f109f516378a656e8060b0f11
C++
KobiHawk/BlackJack
/BlackJack/Dealer.h
UTF-8
258
2.578125
3
[]
no_license
#pragma once #include "Player.h" /* Dealer.h Child of Player The dealer only has one revealed card, and can only take very limited actions. */ class Dealer : public Player { public: Dealer(); ~Dealer(); Card* getRevealedCard(); void printHand(); };
true
1df5fb35edff2f7218232030598a751b5121746b
C++
TXKCOME/NeoCrowd
/NeoCrowdLib/NeoCrowdLib.cpp
UTF-8
2,958
2.640625
3
[]
no_license
#include "NeoCrowdLib.h" #include <regex> #include <unistd.h> #include <fcntl.h> #include <stdio.h> <<<<<<< HEAD void RunRecongizeService(const char* _inputPath, const char* _areaString, const char* _outputPath) { string inputPath(_inputPath); string outputPath(_outputPath); string areaString(_areaString); ======= void RunRecongizeService(string inputPath, string areaString, string outputPath) { >>>>>>> 2be7d893eb13448d40f205dacfd9a1ccfe202694 if(access(inputPath.data(), F_OK) != 0) { cout << inputPath + " File Not Exist!" << endl; return; } if(access(outputPath.data(), F_OK) == 0) { std::remove(outputPath.data()); } unique_ptr<NeoCrowdLib> ncl = make_unique<NeoCrowdLib>(); ncl->ParseMedia(inputPath, areaString, outputPath); cout << "finish"<<endl; } NeoCrowdLib::NeoCrowdLib() { detector = CreateDetector(detectorType); tracker = CreateTracker(trackerType); } NeoCrowdLib::~NeoCrowdLib() { } void NeoCrowdLib::ParseMedia(string inputPath, string areaString, string outputPath) { m_inputPath = inputPath; m_outputPath = outputPath; cout << "Input path :" + inputPath << endl; cout << "outputPath :" + outputPath << endl; cap.open(inputPath); if(!cap.isOpened()) { cout << "Open " + inputPath + "failed."; return; } cap.read(src_image); detector->Init(src_image); tracker->SetArea(get_contours(areaString)); tracker->Init(src_image, std::move(detector)); int ex = static_cast<int>(cap.get(CV_CAP_PROP_FOURCC)); char EXT[] = {(char)(ex & 0XFF) , (char)((ex & 0XFF00) >> 8),(char)((ex & 0XFF0000) >> 16),(char)((ex & 0XFF000000) >> 24), 0}; cout << "Input codec type: " << EXT << endl; cv::Size size = cv::Size(384, 288); m_videoWriter = make_unique<cv::VideoWriter>(m_outputPath, ex, cap.get(CV_CAP_PROP_FPS), size, true); DealFrame(); } void NeoCrowdLib::DealFrame() { while(cap.read(src_image)) { Result result = tracker->Update(&src_image); m_videoWriter->write(result.image); } cap.release(); m_videoWriter->release(); } std::vector<std::vector<cv::Point>> NeoCrowdLib::get_contours(std::string str) { if (str == "") return std::vector<std::vector<cv::Point>>(); std::vector<cv::Point> points; std::regex ws_re(","); std::vector<std::string> v(std::sregex_token_iterator(str.begin(), str.end(), ws_re, -1), std::sregex_token_iterator()); if (v.size() % 2 != 0) throw "Not a even number!"; // 非偶数 if (v.size() < 6) throw "Cannot be a polygon!"; // 不构成多边形 for (uint i = 0; i < v.size() / 2; ++i) { std::stringstream ss; ss << v.at(i * 2) << ' ' << v.at(i * 2 + 1); int x, y; ss >> x >> y; points.push_back(cv::Point(x, y)); } std::vector<std::vector<cv::Point>> contours; contours.push_back(points); return contours; }
true
e7bc7de532a510b31b4590b88c8f42d66d132112
C++
2023PHOENIX/11-week-workshop
/week 4/LinkedList/AddTwoNumber.cpp
UTF-8
1,415
3.359375
3
[]
no_license
#include<bits/stdc++.h> using namespace std; class Node { public: int data; Node *next; }; Node* MakeLinkList(int *arr,int n){ Node *head = new Node; head->data = arr[0]; head->next = nullptr; auto last = head; for(int i=1;i<n;i++){ Node *temp = new Node; temp->data = arr[i]; temp->next = nullptr; last->next = temp; last = temp; } return head; } Node *AddTwoNumbers(Node *first,Node *second) { int firstNum = 0; int secondNum = 0; while(first){ firstNum = firstNum*10 + first->data; first = first->next; } while(second) { secondNum = secondNum*10 + second->data; second = second->next; } int finalSum = firstNum + secondNum; int rem = 0; Node *head; head = nullptr; while(finalSum>9){ rem = finalSum%10; finalSum = finalSum/10; Node *temp = new Node; temp->data = rem; temp->next = head; head = temp; } Node *temp = new Node; temp->data = finalSum; temp->next = head; head = temp; return head; } int main() { int n; cin>>n; int *arr = new int[n]; for(int i=0;i<n;i++)cin>>arr[i]; int m; cin>>m; int *brr = new int[m]; for(int i=0;i<m;i++)cin>>brr[i]; auto *P = MakeLinkList(arr,n); auto *Q = MakeLinkList(brr,m); auto head = AddTwoNumbers(P,Q); // not correct answer yet while(head){ cout<<head->data<<" "; head = head->next; } }
true
479dbb128b7aa5103622c2f47bee70089d39be61
C++
lugt/UMAD
/UMAD/UMAD/SourceFiles/util/parallelindex/ft.cpp
UTF-8
752
2.78125
3
[]
no_license
#include <iostream> #include <fstream> #include <cstring> using namespace std; int main(int argc, char **argv) { fstream ifs("../data/ufile.txt", ios::in); if (!ifs) { cout << "failed to open file ufile.txt" << endl; return -1; } long fileloc = 0; char buffer[1024]; for (int i=0; i < 3; i++) { int num = 0; if (i == 2) { num = 20; } else { num = (i + (20 / 3)); } fileloc = ifs.tellg(); cout << "[" << i << "] start location:" << fileloc << endl; for (int j=i; j<num; j++) { bzero(buffer, 1024); ifs.getline(buffer, 1024); cout << "linelen:" << strlen(buffer) << endl; } fileloc = ifs.tellg(); cout << "[" << i << "] start location:" << fileloc << endl; } ifs.clear(); ifs.close(); }
true
0e3d3e83dc767698a4bf6303ade61c56aca6c2c4
C++
ZYChimne/Homework-FTPClient
/include/DownloadFileTask.h
UTF-8
3,591
2.6875
3
[]
no_license
#ifndef DOWNLOADFILETASK_H #define DOWNLOADFILETASK_H #include "../include/FTPSession.h" #include <QObject> #include <fstream> #include <cstring> #include <iostream> namespace ftpclient { /** * @brief 下载任务类 * 调用 start() 开始任务 * 调用 resume() 继续任务 * 调用 stop() 停止任务 */ class DownloadFileTask : public QObject { Q_OBJECT public: /** * @brief DownloadFileTask 构造函数 * @author zyc * @param session FTP会话 * @param localFilepath 本地文件路径,应使用绝对路径 * @param remoteFilepath 服务器文件路径,应使用绝对路径 */ DownloadFileTask(FTPSession &session, const std::string &localFilepath, const std::string &remoteFilepath); ~DownloadFileTask(); DownloadFileTask(const DownloadFileTask &) = delete; DownloadFileTask &operator=(const DownloadFileTask &) = delete; /** * @brief 下载文件内容 * @author zyc */ void downloadFileData(); /** * @brief 开始下载 * @author zyc */ void start(); /** * @brief 下载前的准备工作,进入被动模式 * @author zyc */ void prepare(); /** * @brief 退出下载 * @author zyc */ void quit(); /** * @brief 继续下载 * @author zyc */ void resume(); /** * @brief 停止下载 * @author zyc */ void stop(); /** * @brief 连接信号 * @author zyc */ void connectSignals(); /** * @brief 获取已下载文件的大小 * @author zyc */ void hasDownloaded(); signals: /** * @brief 信号:下载百分比 * @param percent 百分比 */ void percentSync(int percent); /** * @brief 信号:下载开始 */ void downloadStarted(); /** * @brief 信号:下载失败 * @param msg 错误信息 */ void downloadFailedWithMsg(std::string msg); /** * @brief 信号:下载失败 */ void downloadFailed(); /** * @brief 信号:下载失败 */ void readFileError(); /** * @brief 信号:下载成功 */ void downloadSucceed(); private: /** * @brief 发送命令 * @param cmd 发送命令 * @author zyc */ void sendCmd(std::string cmd); /** * @brief 数据套接字连接 * @author zyc */ void dataSocketConnect(); FTPSession session; std::string localFilepath; std::string remoteFilepath; SOCKET dataSocket; SOCKET controlSocket; std::string filename; bool isStop=false; const int SENDTIMEOUT=3000; const int RECVTIMEOUT=3000; const int DATABUFFERLEN=1024; long long downloadOffset=0; long long filesize=0; int dataPort=0; char *dataBuffer=new char [DATABUFFERLEN]; }; } // namespace ftpclient #endif // DOWNLOADFILETASK_H
true
ef6ec039dd36c1f622262e961d9762b646b0c01e
C++
gwtak/My_Leetcode
/leetcode原生/23_合并K个排序链表_hard/暴力法_自己写的.cpp
UTF-8
1,119
3.3125
3
[]
no_license
/*合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。 示例: 输入: [   1->4->5,   1->3->4,   2->6 ] 输出: 1->1->2->3->4->4->5->6 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/merge-k-sorted-lists 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。*/ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* mergeKLists(vector<ListNode*>& lists) { vector<int> tmp; for(int i=0;i<lists.size();i++){ ListNode* root=lists[i]; while(root){ tmp.push_back(root->val); root=root->next; } } sort(tmp.begin(),tmp.end()); ListNode* last=NULL; for(int i=tmp.size()-1;i>=0;i--){ ListNode* now=new ListNode; now->val=tmp[i]; now->next=last; last=now; } return last; } };
true
d58d369cbcb363dff80eb875754657affc770890
C++
mush-musha/University-Management-System-UML-AND-CODE
/Courses.h
UTF-8
1,874
3.671875
4
[]
no_license
#pragma once #include<string> #include<iostream> #include<vector> using namespace std; class Courses { public: Courses()=default; ~Courses()=default; //setters void set_courses_enrolled(string); void set_coursewise_attendance_percentage(float); void set_course_wise_marks(float); void change_course_enrolled(int,string); //getters string get_courses_enrolled(int); float get_coursewise_attendance_percentage(int); float get_course_wise_marks(int); int get_total_no_courses(); private: vector<string> courses_enrolled; vector<float> course_wise_attandance_percentage; vector<float> course_wise_marks; int total_no_courses; }; void Courses::set_courses_enrolled(string ce) { this->courses_enrolled.push_back(ce); this->total_no_courses = courses_enrolled.size(); } void Courses::set_coursewise_attendance_percentage(float cap) { for (size_t i = 0; i < courses_enrolled.size(); i++) { cout << "The " << (i + 1) << " course is " << courses_enrolled[i] << endl; } this->course_wise_attandance_percentage.push_back(cap); } void Courses::set_course_wise_marks(float cm) { for (size_t i = 0; i < courses_enrolled.size(); i++) { cout << "The " << (i + 1) << " course is " << courses_enrolled[i] << endl; } this->course_wise_marks.push_back(cm); } void Courses::change_course_enrolled(int index,string course) { for (size_t i = 0; i < courses_enrolled.size(); i++) { cout << "The " << (i + 1) << " course is " << courses_enrolled[i] << endl; } this->courses_enrolled.at(index) = course; } string Courses::get_courses_enrolled(int index) { return courses_enrolled[index]; } float Courses::get_coursewise_attendance_percentage(int index) { return course_wise_attandance_percentage[index]; } float Courses::get_course_wise_marks(int index) { return course_wise_marks[index]; } int Courses::get_total_no_courses() { return total_no_courses; }
true
fbcc01de40f2387f3ab6b54c986d7f782e33cc8a
C++
shouko/algorithms_iccad2016
/src/answerstack.h
UTF-8
475
2.796875
3
[]
no_license
#ifndef _ANSWERSTACK_H_ #define _ANSWERSTACK_H_ #include <stack> #include <utility> using namespace std; class Gate; class Wire; typedef union AnsEntry { Gate* g; Wire* w; } AnsEntry; enum AnsEntryType { ANS_GATE, ANS_WIRE }; class AnswerStack { public: AnswerStack() {}; ~AnswerStack() {}; void insert(const Gate* g); void insert(const Wire* g); void print(); bool check(); void pop(); private: stack<pair<AnsEntryType, AnsEntry>> s; }; #endif
true
bd88d5426dbc15fefb0659e332b869696e5bf99d
C++
dsupr/230-Final-Project
/Stack.cpp
UTF-8
382
3.015625
3
[]
no_license
#include "Stack.h" void TStack::push(BinaryTreeNode *p) { TStackNode *newNode = new TStackNode(); newNode->data = p; newNode->next = top; top = newNode; } bool TStack::pop(BinaryTreeNode * &p) { if (top == nullptr) { return false; } p = top->data; TStackNode *delNode = top; top = top->next; delete delNode; return true; }
true
8e633a0a7e1039e01adf22a7387eee47dad87470
C++
hanswenzel/lArTest
/include/AuxDetHit.hh
UTF-8
4,906
2.75
3
[]
no_license
/* * File: AuxDetHit.h * Author: wenzel * * Created on October 22, 2018, 2:35 PM */ #ifndef AUXDETHIT_H #define AUXDETHIT_H #include <vector> #include <iostream> class AuxDetHit { private: int ID; ///< Geant4 copy ID int trackID; ///< Geant4 supplied track ID float energyDeposited; ///< total energy deposited for this track ID and time float entryX; ///< Entry position X of particle float entryY; ///< Entry position Y of particle float entryZ; ///< Entry position Z of particle float entryT; ///< Entry time of particle float exitX; ///< Exit position X of particle float exitY; ///< Exit position Y of particle float exitZ; ///< Exit position Z of particle float exitT; ///< Exit time of particle float exitMomentumX; ///< Exit X-Momentum of particle float exitMomentumY; ///< Exit Y-Momentum of particle float exitMomentumZ; ///< Exit Z-Momentum of particle public: // Default constructor AuxDetHit() { } bool operator<(const AuxDetHit& other) const; bool operator==(const AuxDetHit& other) const; // Hide the following from Root #ifndef __GCCXML__ AuxDetHit(int iID, int itrackID, float ienergyDeposited, float ientryX, float ientryY, float ientryZ, float ientryT, float iexitX, float iexitY, float iexitZ, float iexitT, float iexitMomentumX, float iexitMomentumY, float iexitMomentumZ) : ID(iID), trackID(itrackID), energyDeposited(ienergyDeposited), entryX(ientryX), entryY(ientryY), entryZ(ientryZ), entryT(ientryT), exitX(iexitX), exitY(iexitY), exitZ(iexitZ), exitT(iexitT), exitMomentumX(iexitMomentumX), exitMomentumY(iexitMomentumY), exitMomentumZ(iexitMomentumZ) { } void SetExitMomentumZ(float iexitMomentumZ) { this->exitMomentumZ = iexitMomentumZ; } float GetExitMomentumZ() const { return exitMomentumZ; } void SetExitMomentumY(float iexitMomentumY) { this->exitMomentumY = iexitMomentumY; } float GetExitMomentumY() const { return exitMomentumY; } void SetExitMomentumX(float iexitMomentumX) { this->exitMomentumX = iexitMomentumX; } float GetExitMomentumX() const { return exitMomentumX; } void SetExitT(float iexitT) { this->exitT = iexitT; } float GetExitT() const { return exitT; } void SetExitZ(float iexitZ) { this->exitZ = iexitZ; } float GetExitZ() const { return exitZ; } void SetExitY(float iexitY) { this->exitY = iexitY; } float GetExitY() const { return exitY; } void SetExitX(float iexitX) { this->exitX = iexitX; } float GetExitX() const { return exitX; } void SetEntryT(float ientryT) { this->entryT = ientryT; } float GetEntryT() const { return entryT; } void SetEntryZ(float ientryZ) { this->entryZ = ientryZ; } float GetEntryZ() const { return entryZ; } void SetEntryY(float ientryY) { this->entryY = ientryY; } float GetEntryY() const { return entryY; } void SetEntryX(float ientryX) { this->entryX = ientryX; } float GetEntryX() const { return entryX; } void SetEnergyDeposited(float ienergyDeposited) { this->energyDeposited = ienergyDeposited; } float GetEnergyDeposited() const { return energyDeposited; } void SetTrackID( int itrackID) { this->trackID = itrackID; } int GetTrackID() const { return trackID; } void SetID( int iID) { this->ID = iID; } int GetID() const { return ID; } void Print() { std::cout << "AuxDetHit: " << std::endl; std::cout << "copy ID: " << ID << " track ID: " << trackID << " Total energy (MeV) deposited: " << energyDeposited << std::endl; std::cout << "Entry position x,y,z (cm) time (ns) of particle: " << entryX << " " << entryY << " " << entryZ << " " << entryT << std::endl; std::cout << "Exit position x,y,z (cm) time (ns) of particle: " << exitX << " " << exitY << " " << exitZ << " " << exitT << std::endl; std::cout << "Exit momentum px,py,pz (MeV) of particle: " << exitMomentumX << " " << exitMomentumY << " " << exitMomentumZ << std::endl; } #endif }; //typedef std::vector<AuxDetHit*>* AuxDetHitCollection; inline bool AuxDetHit::operator<(const AuxDetHit& other) const { return trackID < other.trackID; } inline bool AuxDetHit::operator==(const AuxDetHit& other) const { return (other.trackID == trackID && other.ID == ID); } #endif /* AUXDETHIT_H */
true
2e2d48052ff4fc39de1c13ddc2bc6e8af176f264
C++
mitchellspryn/ClankRoboticsPlatform
/clank/lib/motor/LiteMotor/LiteMotor.hpp
UTF-8
794
2.546875
3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
#ifndef LITEMOTOR_HPP #define LITEMOTOR_HPP #include "motor/IMotor.hpp" #include "configuration/Configuration.hpp" #include "hardware/GpioPin.hpp" #include "hardware/PwmPin.hpp" #include <string> #include <stdexcept> namespace Clank { namespace Motor { class LiteMotor : IMotor { public: LiteMotor(Clank::Configuration::Configuration *configuration); LiteMotor(double startingRampSpeed, double startingVelocity, std::string dirControlName, std::string pwmPinName); ~LiteMotor(); double GetVelocity(); void SetVelocity(double velocity); double GetRampSpeed(); void SetRampSpeed(double speed); private: Clank::Hardware::GpioPin *DirPin; Clank::Hardware::PwmPin *PulsePin; }; } } #endif
true
b9fd30b87e161f00e22b759ce5b2252e1003379d
C++
uzairjan/Coding-at-LiU
/TND012 - Programming (Autumn 2013)/Lab 2/Lab 2 Ex 1.cpp
UTF-8
2,099
3.671875
4
[]
no_license
#include <iostream> #include <iomanip> #include <cmath> using namespace std; int main () { //declare variables int age, age_1, age_2; int price_1 = 0; int price_2 = 30; int price_3 = 80; const double rabatt = 0.8; int option; double tot_price, price_F, price_S; // user input - option cout << "Welcome to our football arena" << endl; cout << "-----------------------------" << endl; cout << "1. Price of one ticket." << endl; cout << "2. Price of two tickets." << endl; cout << "-----------------------------" << endl; cout << "Enter option: "; cin >> option; //read options if (option==1){ //calculate option 1 cout << "Enter age: "; cin >> age; if (age> 15) cout << "Price: " << price_3 << " SEK." << endl; else if (age<=15 && age>= 8) cout << "Price: " << price_2 << " SEK." << endl; else cout << "Price: " << price_1 << " SEK." << endl; } else if (option==2) //calculate option 2 { cout << "Enter age for 1st ticket: "; cin >> age_1; if (age_1> 15) { price_F = price_3;} else if (age_1<=15 && age_1>= 8) { price_F = price_2; } else{ price_F = price_1;} cout << "Enter age for 2nd ticket: "; cin >> age_2; if (age_2> 15) { price_S = price_3;} else if (age_2<=15 && age_2>= 8){ price_S = price_2;} else{ price_S = price_1; } //display results if (age_1>7 && age_2>7) { tot_price = price_F+ price_S; tot_price = tot_price *rabatt; cout << "Total price: " << tot_price << endl; } else { tot_price = price_F+ price_S; cout << "Total price: " << tot_price << endl; } } else { cout << "Invalid option!" << endl; } return 0; }
true
611e38528526ba7fc161e4bebbd4b3276313a579
C++
manucapo/VectorVisualizer
/Point.hpp
UTF-8
652
3.03125
3
[ "MIT" ]
permissive
// // Point.hpp // SeminarProjectManu // // Created by Manuel Telleria on 09.03.18. #pragma once #include <math.h> class Point{ double x; double y; public: void setX(double value){ x = value; } void setY(double value){ y = value; } double getX(){ return x; } double getY(){ return y; } double calcualteDistance(double xPosition, double yPosition){ double result; result = sqrt(pow((xPosition-x),2)+pow(yPosition-y,2)); return result; } Point(double xCoord, double yCoord); Point(); ~Point(); };
true
abc690d9251e3e3d0588d594176b4ac3e566bf29
C++
nganhkhoa/CTDL-GT
/include/tut6lab.h
UTF-8
2,720
3.21875
3
[]
no_license
#ifndef TUT6LAB_H #define TUT6LAB_H #include <AVL.h> namespace week6 { namespace lab { class SumPathTree : public data::AVL<int> { data::SinglyLinkedList<data::SinglyLinkedList<int>*>* path; int sum; public: SumPathTree() : data::AVL<int>() { path = nullptr; } ~SumPathTree() { if (path) { delete path; path = nullptr; } } bool FindPath(node* n, int s) { if (n == nullptr) return false; s += n->data; if (s == sum) { data::SinglyLinkedList<int>* onePath = new data::SinglyLinkedList<int>(); onePath->insertHead(n->data); path->insertHead(onePath); return true; } bool status = FindPath(n->left, s) || FindPath(n->right, s); if (status) path->front()->insertHead(n->data); return status; } bool FindPath(node* n) { if (n == nullptr) return false; bool pathFromRoot = FindPath(n, 0); bool pathFromLeftRoot = FindPath(n->left); bool pathFromRightRoot = FindPath(n->right); return pathFromRoot || pathFromLeftRoot || pathFromRightRoot; } bool FindPath(int s) { sum = s; return FindPath(root); } int SumPath(int s) { // save one last search if (s == sum) return path->size(); if (path) delete path; path = new data::SinglyLinkedList<data::SinglyLinkedList<int>*>(); if (FindPath(s)) return path->size(); return 0; } void PrintPath() { for (auto eachPath : *path) { for (int pathNode : *eachPath) { std::cout << pathNode << " --> "; } std::cout << "END\n"; } } }; void SumPathTest(); void labTest(); } // namespace lab namespace tut {} // namespace tut namespace onclass {} // namespace onclass } // namespace week6 #endif
true
d10461a5ec6f92ab2023ac7040aeed63e22ce7b0
C++
Y-puyu/Everyday_Coding
/20200223 搜索二维矩阵 数学 二分法 多方法.cpp
GB18030
2,232
3.265625
3
[]
no_license
// ִʱ :12 ms, C++ ύл53.83%û // ڴ :10.1 MB, C++ ύл5.29%û class Solution { public: bool searchMatrix(vector<vector<int>>& matrix, int target) { if (matrix.empty() || matrix[0].empty()) return false; for (int i = 0; i < matrix.size(); ++i) { for (int j = 0; j < matrix[0].size(); ++j) { if (target == matrix[i][j]) return true; } } return false; } }; // ִʱ :12 ms, C++ ύл53.83%û // ڴ :9.8 MB, C++ ύл22.75%û class Solution { public: bool searchMatrix(vector<vector<int>>& matrix, int target) { if (matrix.empty() || matrix[0].empty()) return false; int left = 0, right = matrix.size(); while (left < right) { int mid = (left + right) / 2; if (matrix[mid][0] == target) return true; if (matrix[mid][0] <= target) left = mid + 1; else right = mid; } int tmp = (right > 0) ? (right - 1) : right; left = 0; right = matrix[tmp].size(); while (left < right) { int mid = (left + right) / 2; if (matrix[tmp][mid] == target) return true; if (matrix[tmp][mid] < target) left = mid + 1; else right = mid; } return false; } }; // ִʱ :0 ms, C++ ύл100.00%û // ڴ :10 MB, C++ ύл5.29%û class Solution { public: bool searchMatrix(vector<vector<int>>& matrix, int target) { if (matrix.empty() || matrix[0].empty()) return false; int i = 0, j = (int)matrix[0].size() - 1; while (i < matrix.size() && j >= 0) { if (matrix[i][j] == target) return true; else if (matrix[i][j] > target) --j; else ++i; } return false; } };
true
5835daeae87baf636c7e475d68d2139a073aaa67
C++
meyersh/gimli
/archives/431/project3/project3.cgi.cpp
UTF-8
11,734
2.9375
3
[]
no_license
/* * Handle the webapp junk. * Shaun Meyer, Mar 2012 */ // TODO: Game serialization for saving + loading // TODO: game_id persistance // TODO: game_id timeouts // TODO: ? #include <iostream> #include <sstream> #include <vector> #include "session.hpp" #include "Pente.hpp" using namespace std; #define MAX_GAME_AGE (60*5) void die(string msg) { cout << "ERROR_CAUSED_SHUTDOWN" << endl << msg << endl; exit(1); } int main() { string game_id; string session_id; string instr; // initial POST instruction string param; // a place holder for reading in the parameters vector<string> params; // subsequent POSTS. getline(cin, instr); // all requests are by POST. // Initialize `params`, skipping empty lines. while (getline(cin, param)) if (param != "") params.push_back(param); cout << "Content-Type: text/plain\n\n"; // Filter out blank instructions (initial instruction). if (instr == "") die("msg: Expected parameter."); /* * S E T U P */ if (instr == "SETUP") { // check for four characters, noting all options // have size() == 4, begin with h and end with 1 or 2. // Housekeeping: delete all expired games. vector<string> games = list_games(); for (int i = 0; i < games.size(); i++) if (gameid_age(games[i]) > MAX_GAME_AGE) remove_game(games[i]); bool human_only; bool creator_is_white; string gameid; string sessionkey; string game_type = params[0]; if (game_type.size() != 3 || game_type[0] != 'h') die("Invalid parameter: " + param); if (game_type[1] == 'h') human_only = true; else if (game_type[1] == 'c') human_only = false; else die("2nd character must be h or c."); if (game_type[2] == '1') creator_is_white = true; else if (game_type[2] == '2') creator_is_white = false; else die("3rd character must be 1 or 2."); // Generate a unique game id and session key. for (int i = 0; i < NUM_WORDS; i++) { gameid = get_word(i); sessionkey = get_word(++i); if (!gameid_exists(gameid)) break; } ofstream game_file(gameid_file_path(gameid)); if (!game_file.good()) die("Unable to create new game file at '" + string(gameid_file_path(gameid)) + "'."); Pente new_game; if (human_only) { if (creator_is_white) // hh1 new_game.players[0] = sessionkey; else // hh2 new_game.players[1] = sessionkey; } else { if (creator_is_white) // hc1 { new_game.players[0] = sessionkey; new_game.players[1] = "COMPUTER"; } else // hc2 { new_game.players[0] = "COMPUTER"; new_game.players[1] = sessionkey; } } // Finally, place the white piece on the board new_game.playToken(9,9,WHITE); // return the details to the client cout << "SETUP" << endl << gameid << endl << sessionkey << endl << "9" << endl << "9" << endl; if (game_type == "hh1") cout << "WAITING" << endl; else if (game_type == "hh2") cout << "MOVE" << endl; else if (game_type == "hc1") { // generate a computer move and return it. Weight weights(WEIGHTS_FILE); weights.load(); new_game.make_move(weights); cout << new_game.gametrace.back()->r << endl << new_game.gametrace.back()->c << endl << "MOVE" << endl; } else if (game_type == "hc2") cout << "MOVE"; // Save the file. game_file << new_game.serialize(); game_file.close(); } /* * J O I N */ else if (instr == "JOIN") { // TODO: Assign a valid session ID otherwise. // TODO: Or report that the game is full. /* JOIN\n<gameid> JOIN\n<gameid>\n<sessionid> JOIN\n<gameid> JOIN\n<gameid>\nGAME_UNDERWAY */ string gameid = params[0]; if (params.size() != 1) die("Invalid number of parameters."); if (!gameid_exists(gameid)) die("No game identified by '" + gameid + "'."); Pente game; ifstream game_file( gameid_file_path(gameid) ); game.deserialize(game_file); game_file.close(); cout << "JOIN" << endl << gameid << endl; // Both players have joined (are != WAITING) if (game.players[0] != "WAITING" && game.players[1] != "WAITING") cout << "GAME_UNDERWAY" << endl; // The player has joined as player2 if (game.players[0] == "WAITING") { game.players[0] = generate_sessionid(); cout << game.players[0] << endl << "hh2" << endl << "9" << endl << "9" << endl << "WAITING" << endl; } // The player has joined as player1 else if (game.players[1] == "WAITING") { game.players[1] = generate_sessionid(); cout << game.players[1] << endl << "hh1" << endl << "9" << endl << "9" << endl << "MOVE" << endl; } // Save our game. ofstream ogame_file( gameid_file_path(gameid) ); ogame_file << game.serialize() << endl; ogame_file.close(); } /* * M O V E */ else if (instr == "MOVE") { /* POST: MOVE\n<gameid>\n<sessionid>\n<row>\n<col> RESPONSE: MOVE\n<gameid>\n<sessionid> MOVE\n<gameid>\n<sessionid>\nWIN */ // TODO: Validate gameid, sessionid, and feed the computer a move. if (params.size() != 4) die("Invalid number of parameters."); string gameid = params[0]; string sessionid = params[1]; int row = atoi(params[2].c_str()); int col = atoi(params[3].c_str()); if (!gameid_exists(gameid)) die("No such gameid '" + gameid + "'."); Pente game; ifstream infile(gameid_file_path(gameid)); game.deserialize( infile ); infile.close(); // Die for invalid sessionid if (game.playerNumber(sessionid) == -1) die("'" + sessionid + "' is not a valid sessionid."); // Die for invalid coords if (!game.isValidCoords(row, col)) die("Invalid coordinates."); // this should never happen // Die for piece already layed. if(!game.isEmpty(row, col)) { stringstream ss; ss << "Cell already has a piece at (" << row << ',' << col << ")"; die(ss.str()); } // Die if the game is already completed. if (game.gameOutcome(WHITE) != 0) die("This game has already been decided."); // Validate that it is, in fact, our turn. if (game.turn % 2 != game.playerNumber(sessionid)) die("It's not even your turn to move!"); // go ahead and lay the piece. game.playToken(row, col, game.playerColor(sessionid)); // Save the game ofstream game_file(gameid_file_path(gameid)); game_file << game.serialize(); game_file.close(); cout << "MOVE" << endl << gameid << endl << sessionid << endl; if (game.gameOutcome(game.playerColor(sessionid)) == 1) cout << "WIN" << endl; } /* * C H E C K */ else if (instr == "CHECK") { // TODO: Return computer (or other player) move. /* POST: CHECK\n<gameid>\n<sessionid> RESPONSE: CHECK\n<gameid>\n<sessionid>\nWAITING CHECK\n<gameid>\n<sessionid>\n<row>\n<col> CHECK\n<gameid>\n<sessionid>\n<row>\n<col>\n{WIN|LOSE} CHECK\n<gameid>\n<sessionid>\n<row>\n<col>\nTIMEOUT */ if (params.size() != 2) die("Invalid number of CHECK parameters."); string gameid = params[0]; string sessionid = params[1]; cout << "CHECK" << endl << gameid << endl << sessionid << endl; if (!gameid_exists(gameid) || gameid_age(gameid) > MAX_GAME_AGE) { cout << "9" << endl // bogus row + col because it can't matter. << "9" << endl << "TIMEOUT" << endl; // remove the old game. remove_game(gameid); exit(1); } // Load the game for more checks Pente game; ifstream game_file( gameid_file_path(gameid) ); game.deserialize(game_file); game_file.close(); // Validate sessionid if (game.playerNumber(sessionid) == -1) die("Invalid sessionid: '" + sessionid + "'"); // If the computer is playing and we're waiting on them, // go ahead and initiate a computer move. if (game.players[game.turn % 2] == "COMPUTER") { // Generate a computer move. Weight weights(WEIGHTS_FILE); weights.load(); game.make_move(weights); // Save the computer move to file. ofstream ogame_file( gameid_file_path(gameid) ); ogame_file << game.serialize() << endl; ogame_file.close(); } // Stop here if it is not the requesting players' turn. else if (game.players[game.turn % 2] != sessionid) { cout << "WAITING" << endl; exit(1); } // Maybe something went horribly wrong if (game.gametrace.size() == 0) die("Something went horribly wrong and we're reading an empty gametrace."); // Output row + col of last move: cout << game.gametrace.back()->r << endl << game.gametrace.back()->c << endl; // Report a possible victory. if (game.gameOutcome( game.playerColor(sessionid) ) == 1) cout << "WIN" << endl; else if (game.gameOutcome( game.playerColor(sessionid) ) == -1) cout << "LOSE" << endl; } return 0; }
true
77f2b28cad1c51ed88e6d1d818d40f91c0ccbfcf
C++
FJinn/fjinn.github.io
/Experiences/Programming/C++/DataStructureAndAlgorithm/Week 3/Week 3 Bubble Sort.cpp
UTF-8
1,866
3.671875
4
[ "Unlicense" ]
permissive
#include <iostream> #include "windows.h" #include <vector> #include <ctime> using namespace std; vector <char> Charlist; void RandomOrder() { for (int i=0; i<Charlist.size(); i++) { int randomIndex; do { randomIndex = rand () % Charlist.size(); }while(randomIndex == i); char temp = Charlist[i]; Charlist[i]= Charlist[randomIndex]; Charlist[randomIndex]= temp; } } void BubbleSortAscending() { bool isSorted; do { isSorted = true; for (int i=0; i<Charlist.size()-1; i++) { if(Charlist[i]>Charlist[i+1]) { char temp = Charlist[i]; Charlist[i] = Charlist[i+1]; Charlist[i+1] = temp; isSorted = false; } } }while(!isSorted); } void BubbleSortDescending() { bool isSorted; do { isSorted = true; for (int i=0; i<Charlist.size()-1; i++) { if(Charlist[i]<Charlist[i+1]) { char temp = Charlist[i]; Charlist[i] = Charlist[i+1]; Charlist[i+1] = temp; isSorted = false; } } }while(!isSorted); } void DisplayVector() { for(int i=0; i<Charlist.size(); i++) { cout<<"[" << i << "} : "<< Charlist[i]<< endl; } } int main () { srand(time(NULL)); int size = 10; for (int i=0; i<size; i++) { Charlist.push_back(i+65); } int choice = -1; bool isExit = false; do { DisplayVector(); cout << "===============" << endl; cout << "1. Randomize order"<< endl; cout << "2. Sort in ascending order"<< endl; cout << "3. Sort in descending order"<< endl; cout << "4. Exit!"<< endl; cout <<"==============="<< endl; cout <<"Your Choice : "<< endl; cin >> choice; if (choice == 1 ) { RandomOrder(); } else if (choice == 2) { BubbleSortAscending(); } else if (choice == 3) { BubbleSortDescending(); } else if (choice == 4) { isExit= true; } system("PAUSE"); system("CLS"); }while(!isExit); return 0; }
true
38837ecf686bf43e970d1db26a1eaed0d4aafab0
C++
jsj2008/framework2d
/Log/Log.cpp
UTF-8
1,338
2.53125
3
[]
no_license
#include "Log.h" #include <Log/GameConsole.h> #include <Log/UninitialisedLogger.h> #include <SDL/SDL_timer.h> #include <iostream> Log g_Log; Log::Log() { //ctor logger = new UninitialisedLogger; } Log::~Log() { //dtor } void Log::init() { logger = logger->newLogger(new GameConsole()); } void Log::warning(const std::string& _message) { std::cout << "Warning: " + _message << std::endl; logger->outputText("Warning: " + _message, SDL_GetTicks(), 0xFFFFFF00); } void Log::error(const std::string& _message) { std::cout << "Error: " + _message << std::endl; logger->outputText("Error: " + _message, SDL_GetTicks(), 0xFFFF0000); throw -1; } void Log::message(const std::string& _message) { std::cout << "Message: " + _message << std::endl; logger->outputText("Message: " + _message, SDL_GetTicks(), 0xFFFFFFFF); } std::string Log::getTimeString(unsigned int _timeStamp) { unsigned int milliseconds = _timeStamp % 1000; unsigned int seconds = _timeStamp / 1000; unsigned int minutes = seconds / 60; seconds = seconds % 60; unsigned int hours = minutes / 60; minutes = minutes % 60; char buffer[16]; sprintf(buffer, "%d:%d:%d", hours, minutes, seconds); //sprintf(buffer, "%d:%d:%d:%d", hours, minutes, seconds, milliseconds); return buffer; }
true
ea761d303b2caa1787a4f33f0e6bd4c800b199f1
C++
ozanarkancan/blg-hws
/blg335e-analysis-algorithms/AoA/BigUnsignedInt.h
UTF-8
3,644
2.875
3
[]
no_license
#ifndef BIGUNSIGNEDINT_H #define BIGUNSIGNEDINT_H #include <deque> #include <string> #include <limits.h> #include <math.h> #include <stdint.h> #define base (uint64_t)UINT_MAX + 1 //define base as 2^32 using namespace std; class BigUnsignedInt { private: deque<unsigned int> digits;//Represents digits unsigned int getBinaryLengthOfNumber(unsigned int number);//Finds binary length of an unsigned int number. unsigned long modForUnsignedLong(uint64_t number, uint64_t radix);//There is a problem default / operation on unsigned long type, implements that operation unsigned long divisionForUnsignedLong(uint64_t number1, uint64_t number2);//There is a problem default % on unsigned long type, implements that operation BigUnsignedInt powerOfBase(unsigned int pow); public: BigUnsignedInt(unsigned int number);//Creates object that has one digit as number BigUnsignedInt(const BigUnsignedInt& otherBigInt);//Copy constructor BigUnsignedInt(int numberOfDigits);//Creates object that has specified digits as all of them zero ~BigUnsignedInt();//Deconstructor deque<unsigned int> getDigits() const;//Returns digits //Operator overloadings const BigUnsignedInt& operator+(const BigUnsignedInt& bigIntRightSide) const; BigUnsignedInt& operator+=(const BigUnsignedInt& bigIntRightSide); const BigUnsignedInt& operator-(const BigUnsignedInt& bigIntRightSide) const; BigUnsignedInt& operator-=(const BigUnsignedInt& bigIntRightSide); BigUnsignedInt& operator=(const BigUnsignedInt& bigIntRightSide); bool operator==(const BigUnsignedInt& bigIntRightSide) const; bool operator<(const BigUnsignedInt& bigIntRightSide) const; bool operator<=(const BigUnsignedInt& bigIntRightSide) const; bool operator>(const BigUnsignedInt& bigIntRightSide) const; bool operator>=(const BigUnsignedInt& bigIntRightSide) const; const BigUnsignedInt& operator*(const BigUnsignedInt& bigIntRightSide); const BigUnsignedInt& operator/(const BigUnsignedInt& bigIntRightSide); const BigUnsignedInt& operator+(const unsigned int& intRightSide) const; BigUnsignedInt& operator+=(const unsigned int& intRightSide); const BigUnsignedInt& operator-(const unsigned int& intRightSide) const; BigUnsignedInt& operator-=(const unsigned int& intRightSide); BigUnsignedInt& operator=(const unsigned int& intRightSide); bool operator==(const unsigned int& intRightSide) const; bool operator<(const unsigned int& intRightSide) const; bool operator<=(const unsigned int& intRightSide) const; bool operator>(const unsigned int& bigIntRightSide) const; bool operator>=(const unsigned int& bigIntRightSide) const; const BigUnsignedInt& operator*(const unsigned int& intRightSide); const BigUnsignedInt& operator/(const unsigned int& intRightSide); BigUnsignedInt operator<<=(unsigned int number); unsigned int getBinaryLength();//Returns binary length of number void setDigits(deque<unsigned int>& digits);//Sets digits void setDigit(unsigned int index, unsigned int value);//Set specified digit void printDigits();//Prints digits BigUnsignedInt karatsuba(BigUnsignedInt bigIntRightSide); void addExtraZeroDigitToMostSignificantBit(); BigUnsignedInt fastDivision(BigUnsignedInt bigIntRightSide); }; ostream& operator<< (std::ostream &out, BigUnsignedInt &bigInt); #endif // BIGUNSIGNEDINT_H
true
864440e0c8fa3368457b68f207094060a0112a7a
C++
diypa571/MyCppExercises
/class1/Class1/class1.cpp
UTF-8
1,022
3.71875
4
[]
no_license
#include<iostream> #include<string> using namespace std; class aliens { public: aliens () { cout <<"This will be run automaticly,... \n"; cout <<" When an object of the class is created... \n"; } void display() { cout << "Aliens exist.... \n "; } void xx() { cout << "xxxxx function \n"; } int addition(int a, int b) { int c = a+b; return c; } // When we private varaible, //we need to make public function for them have // access to them... // IN this case,we create two functions, one for setting the varaible // And another function for geting the variable... // For setin, we can create first a void function.. void SetName (string x) { name =x; } string GetName () { return name; } private: string name; }; int main() { aliens alienobject; int par1 =2; int par2 =3; aliens a; alienobject.display(); alienobject.xx(); alienobject.addition(par1,par2); cout << alienobject.addition(par1,par2); cout << endl; alienobject.SetName("Silvia Parwana"); cout << alienobject.GetName(); return 0; }
true
d36621a9421a19a34e5e02ed1699605d480c8f8b
C++
nnovoice/acmuva
/solutions/acm/QuirksomeSquares256/QuirksomeSquares256.cpp
UTF-8
2,246
3.328125
3
[]
no_license
#include <iostream> #include <iomanip> #include <vector> using namespace std; const unsigned int MAXNUMBERS = 100000000; const unsigned int MAXSQUARES = 19999; unsigned int squares[MAXSQUARES]; void GetNumbers (unsigned int num, unsigned int& a, unsigned int& b, int digits) { if (digits == 1) { a = num % 10; b = num / 10; } else if (digits == 2) { a = num % 100; b = num / 100; } else if (digits == 3) { a = num % 1000; b = num / 1000; } else if (digits == 4) { a = num % 10000; b = num / 10000; } } void CheckAndAddQuirk(unsigned int num, unsigned int& a, unsigned int& b, vector<int>& quirkVector) { if (squares[a] > num) return; if (squares[b] > num) return; unsigned int quirkSum = squares[a + b]; if (quirkSum == num) { quirkVector.push_back(num); } } int main() { vector<int> quirkVectorArr[9]; unsigned int a = 0; unsigned int b = 0; unsigned int i = 0; int nQuirkDigits = 0; for (i = 0; i < MAXSQUARES; ++i) { squares[i] = i * i; } for (i = 2; i <= 8; i += 2) { quirkVectorArr[i].push_back(0); quirkVectorArr[i].push_back(1); } for (i = 2; i < MAXNUMBERS; ++i) { if (i < 100) { GetNumbers(i, a, b, 1); CheckAndAddQuirk(i, a, b, quirkVectorArr[2]); } else if (i < 10000) { GetNumbers(i, a, b, 2); CheckAndAddQuirk(i, a, b, quirkVectorArr[4]); GetNumbers(i, a, b, 3); CheckAndAddQuirk(i, a, b, quirkVectorArr[6]); } else if (i < 1000000) { GetNumbers(i, a, b, 3); CheckAndAddQuirk(i, a, b, quirkVectorArr[6]); GetNumbers(i, a, b, 4); CheckAndAddQuirk(i, a, b, quirkVectorArr[8]); } else { GetNumbers(i, a, b, 4); CheckAndAddQuirk(i, a, b, quirkVectorArr[8]); } } while (cin >> nQuirkDigits) { for (unsigned int j = 0; j < quirkVectorArr[nQuirkDigits].size(); ++j){ cout << setw(nQuirkDigits) << setfill('0') << quirkVectorArr[nQuirkDigits][j] << endl; } } return 0; }
true
b30619bcbcc95bb5491b93fdaa03f13b977eb00b
C++
sjnonweb/spoj
/Solutions/CANDY3.cpp
UTF-8
404
2.546875
3
[ "MIT" ]
permissive
#include <iostream> #include <cstdio> using namespace std; int main() { long long int test,n,i,j,sum; cin>>test; while(test--) { getchar(); cin>>n; sum=0; for(i=0;i<n;i++) { cin>>j; sum=(sum+j)%n; } if(sum==0) cout<<"YES"<<endl; else cout<<"NO"<<endl; } return 0; }
true
e36b5a3b92e0c4c9c01c00aa8e67d7cb6062d3a8
C++
lionem2018/Baekjoon_Algorithm
/C++/10818_C.cpp
UTF-8
534
3.1875
3
[]
no_license
/* 2020/02/26 Baekjoon Online Judge Problem 10818: 최소, 최대 N개의 정수가 주어진다. 이때, 최솟값과 최댓값을 구하는 프로그램을 작성하시오. */ #include <iostream> int main(void) { int size, number, min = 1000000, max = -1000000; scanf("%d", &size); for(int i = 0; i < size; i++) { scanf("%d", &number); if(min > number) min = number; if(max < number) max = number; } printf("%d %d\n", min, max); return 0; }
true
bc21bba8eb5493479331117f89902ce65e80b7fa
C++
GregoryVanlaer/c_multi
/topics/classes-overview/destructor-usage.cpp
UTF-8
163
2.59375
3
[]
no_license
class Foo { int* p; public: // Constructor allocates Foo() : p(new int) { } // Destructor deallocates ~Foo() { delete p; } }
true
8efde1149c1356e509cd78b8ca7536769cb35ed3
C++
kruztev/FMI-DSA
/data_structures/tree/trie_tree/trie.cpp
UTF-8
2,359
3.484375
3
[ "MIT" ]
permissive
/******************************************************************************* * This file is part of the "Data structures and algorithms" course. FMI 2018/19 *******************************************************************************/ /** * @file trie.cpp * @author Vasilena Peycheva * @date 03.04.2019 * @brief Example implementation of Trie (Prefix tree). * * @see https://en.wikipedia.org/wiki/Trie * @see https://medium.com/basecs/trying-to-understand-tries-3ec6bede0014 */ #include "trie.h" using dsa::trie; trie::trie(): root(new node) { //... } trie::~trie() { clean_rec(root); } bool trie::insert(const std::string& word) { if (!is_word(word)) return false; if (!root) // if the trie was cleaned root = new node(); // create root node (starting point) node* current = root; // starting point size_t index = 0; for (size_t i = 0; i < word.size(); i++) { // get the current letter index in node alphabet array index = indexation(word[i]); // if the letter is not already created (used with another word) if (!current->alphabet[index]) //create new node from the current node alphabet[letter index] current->alphabet[index] = new node(); current = current->alphabet[index]; } // mark the last node as end of a word current->is_word = true; return true; } bool trie::search(const std::string & word) { if (!is_word(word) || !root) return false; node* current = root; // starting point size_t index = 0; for (size_t i = 0; i < word.size(); i++) { // get the current letter index in node alphabet array index = indexation(word[i]); // if the current letter is not created, then the word is not in the trie if (!current->alphabet[index]) return false; current = current->alphabet[index]; } // check if the last node is marked as word return current->is_word; } void dsa::trie::clean() { clean_rec(root); root = nullptr; } void trie::clean_rec(node* root) { if (!root) return; // standard tree deletion for (size_t i = 0; i < ALPHABET_SIZE; i++) { if (root->alphabet[i]) clean_rec(root->alphabet[i]); } delete root; } int trie::indexation(char c) { if (islower(c)) return c - 'a'; if (isupper(c)) return c - 'A'; return -1; } bool trie::is_word(const std::string& word) { for (char c: word) { if (!isalpha(c)) return false; } return true; }
true
cc3def44c9a0d06a9b7d2e11a8a5e8de3f3f6f13
C++
futuristek/leetcode
/google/347.top-k-frequent-elements.cpp
UTF-8
1,394
3.546875
4
[]
no_license
/* * [347] Top K Frequent Elements * * https://leetcode.com/problems/top-k-frequent-elements/description/ * * algorithms * Medium (51.88%) * Total Accepted: 196.8K * Total Submissions: 361.3K * Testcase Example: '[1,1,1,2,2,3]\n2' * * Given a non-empty array of integers, return the k most frequent elements. * * Example 1: * * * Input: nums = [1,1,1,2,2,3], k = 2 * Output: [1,2] * * * * Example 2: * * * Input: nums = [1], k = 1 * Output: [1] * * * Note: * * * You may assume k is always valid, 1 ≤ k ≤ number of unique elements. * Your algorithm's time complexity must be better than O(n log n), where n is * the array's size. * * */ #include <vector> #include <unordered_map> #include <queue> using namespace std; class Solution { public: vector<int> topKFrequent(vector<int>& nums, int k) { unordered_map<int, int> map; for (auto n: nums) { map[n] += 1; } auto cmp = [](pair<int, int> a, pair<int, int> b) { return a.second > b.second; }; priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(cmp)> pq(cmp); for (auto &p: map) { if (pq.size() < k) { pq.push(p); } else { if (p.second > pq.top().second) { pq.pop(); pq.push(p); } } } vector<int> res; while (!pq.empty()) { auto &next = pq.top(); res.push_back(next.first); pq.pop(); } return res; } };
true
12e712be9d6b9479fc1c78d1ec006d270309576e
C++
fabinhoh13/fabinhoh13
/UFOP/Disciplinas/Terceiro Periodo/Programação Orientada a Objetos/TP1/src/Casa.h
UTF-8
669
2.546875
3
[]
no_license
// Created by Igor Santiago - 19.1.4033 and Fábio Fernandes - 19.1.4128 on 11/2021. #ifndef CASA_H #define CASA_H #include "Imovel.h" using namespace std; class Casa : public Imovel{ int andares; bool sala_jantar; public: Casa(int = 0, float = 0, string = "", string = "", string = "", string = "", int = 0, int = 0, int = 0, int = 0, bool = false); virtual ~Casa(); int getAndares() const; bool getSalaJantar() const; void setAndares(int); void setSalaJantar(bool); virtual void saida (ostream &) const; friend ostream& operator<<(ostream &, const Casa &); }; #endif
true
6ddce204de704559d12208b098326dd94926450a
C++
Wolfenry/PerturBaldosa
/Baldosa.h
UTF-8
1,040
2.796875
3
[]
no_license
#pragma once #include <SFML\Graphics.hpp> using namespace sf; class Baldosa { public: Baldosa(Vector2f size, Texture* textura, float posX, float posY); ~Baldosa(); void SetPosition(Vector2f pos); Vector2f GetPosition(); float GetX(); float GetY(); void recuadropantalla(); void draw(RenderWindow &window); void SetTextureRect(IntRect &rect); private: RectangleShape baldosa; }; Baldosa::Baldosa(Vector2f size, Texture* textura, float posX, float posY) { baldosa.setPosition(posX, posY); baldosa.setSize(size); baldosa.setTexture(textura); } Baldosa::~Baldosa() { } void Baldosa::SetPosition(Vector2f pos) { baldosa.setPosition(pos); } Vector2f Baldosa::GetPosition() { return baldosa.getPosition(); } float Baldosa::GetX() { return baldosa.getPosition().x; } float Baldosa::GetY() { return baldosa.getPosition().y; } void Baldosa::recuadropantalla() { } void Baldosa::draw(RenderWindow &window) { window.draw(baldosa); } void Baldosa::SetTextureRect(IntRect &rect) { baldosa.setTextureRect(rect); }
true
b3b6d7af86a257b55f69881da5c15a966dbfe41c
C++
prickle/GameBloke
/src/teensy-speaker.cpp
UTF-8
922
2.765625
3
[]
no_license
#include <Arduino.h> #include "teensy-speaker.h" #include "globals.h" TeensySpeaker::TeensySpeaker(uint8_t pinNum) : PhysicalSpeaker() { toggleState = false; needsToggle = false; speakerPin = pinNum; pinMode(speakerPin, OUTPUT); // analog speaker output, used as digital volume control mixerValue = numMixed = 0; } TeensySpeaker::~TeensySpeaker() { } void TeensySpeaker::toggle() { needsToggle = true; } void TeensySpeaker::maintainSpeaker(uint32_t c) { if (needsToggle) { toggleState = !toggleState; needsToggle = false; } mixerValue += (toggleState ? 0x1FF : 0x00); mixerValue >>= (16-g_volume); // FIXME: glad it's DAC0 and all, but... how does that relate to the pin passed in the constructor? analogWriteDAC0(mixerValue); } void TeensySpeaker::beginMixing() { mixerValue = 0; numMixed = 0; } void TeensySpeaker::mixOutput(uint8_t v) { mixerValue += v; numMixed++; }
true
6148f6b5a2681aeb7f54075af235b606a4ebfba7
C++
AlgorithmOnline/youngbin
/2020_1005_2217.cpp
UTF-8
430
2.765625
3
[]
no_license
#include<iostream> #include<vector> #include<algorithm> using namespace std; vector<int> v; int N; int ans; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> N; for (int i = 0; i < N; ++i) { int num; cin >> num; v.push_back(num); } sort(v.begin(), v.end()); int temp; for (int i = 0; i < N; ++i) { temp = v[i] * (N - (i)); ans = max(ans, temp); } cout << ans << '\n'; return 0; }
true
aefafe108e9453ec252509cfe4d3e103307d9a34
C++
vijaythyagarajan/Web-based-Code-Repository-Search-Engine
/Display/Display.h
UTF-8
1,905
3.328125
3
[]
no_license
#pragma once ///////////////////////////////////////////////////////////////////// // Display - DisplayFile Package (Source Code Publisher) // // Vijay Thyagarajan, CSE687 - Object Oriented Design, Spring 2019 // ///////////////////////////////////////////////////////////////////// /* * Package Operations: * ------------------- * The Display Package file includes DisplayFile class that stores the * files names that needs to be displayed , the methods setApplicationPath() and * createCommandLineForFileName() are implemented to uses pass required parameters * for the Process package * ------------------- * Required Files: * --------------- * Process.h, Process.cpp * --------------- Maintenance History: =================== ver 1.0 : 17 Jan 2019 - first release - This Class takes in the files to be displayed and uses the process package to - display the file on a browser. */ #include<iostream> #include<algorithm> #include<regex> #include<string> class DisplayFile { public: DisplayFile() {} virtual ~DisplayFile() {} using files = std::vector<std::string>; // Method to create a list of files that needs to be displayed void createDisplayFileList(const DisplayFile::files& fileList); // Method that returns the list of files const DisplayFile::files & getFilesToDisplay(); //Method to display all the files void displayFileWithPath(); // Method to set the application path void setApplicationPath(const std::string& appPath); // Method to create command line for each file to display files on a default browser using cmd. std::string getFilePath(); std::string createCommandLineForFileName(const std::string& filePath); private: //storage for the list of files to display files filesToDisplay_; // parameters used to pass the required fields for the Process Package std::string appPath_; std::string commandLine_; std::string title_; };
true
55514c40b1b21f57a4b28f650a0d871a33150180
C++
lmontigny/Practice_Cpp
/Pointers.cpp
UTF-8
574
3.25
3
[]
no_license
// Pointer.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> using namespace std; int main() { int var = 8; void* ptr = nullptr; ptr = &var; //*ptr = 10; // not working because void int* ptr1 = nullptr; ptr1 = &var; *ptr1 = 10; // On the heap char* buffer = new char[8]; // allocate 8 bytes of memory and return pointer to the beginning of the array memset(buffer, 0, 8); // Double pointer char** sptr = &buffer; int** hptr = &ptr1; **hptr = 2; cout << var << endl; delete[] buffer; return 0; }
true
1a5fa2de08efd6910cdc883144005f650c938417
C++
achallion/intranet-lan-chat-app
/main.cpp
UTF-8
2,892
2.671875
3
[]
no_license
#include "headers.hpp" int main() { cout << GRN << "Welcome To End To End Encrypted Intranet Lan System"; user me; user frnd; cout << GRN << "\n\nWhat is Your Username : " << YEL; cin >> me.name; cout << GRN << me.getname() + " , Do You want to connect to your friend : (y/n) " << YEL; char ans; cin >> ans; bool connected = false; bool server = false; asio::ip::tcp::socket *mysock = NULL; if (ans == 'y' || ans == 'Y') { connected = true; cout << GRN << "Give Your Friend Address : " << YEL; cin >> frnd.address; poweradd ptor; ptor.setpadd(frnd.getaddress()); frnd.address = ptor.getraw(); connector connect(frnd.getaddress(), 6767); mysock = connect.getsock(ioservice); } else { cout << GRN << me.getname() + " , Do you Want a Friend to Connect : (y/n) " << YEL; cin >> ans; if (ans == 'y' || ans == 'Y') { connected = true; server = true; acceptor accept(6767); me.address = accept.getaddress(); poweradd rtop; rtop.setraw(me.address); cout << GRN << "\n\nYour Address is : " << YEL << rtop.getpadd() << flush << YEL; mysock = accept.accept(ioservice); } } // **********Send And Recieve if (connected) { cout <<"\n" << RED << "[+]"; cout << GRN << "Wireless Interface Activated" << flush; if (server) { rw::send(mysock, me.name); frnd.name = remnl(rw::recieve(mysock)); string temp = "HI " + frnd.name; rw::send(mysock, encrypt::base64(encrypt::xor_(temp))); } else { frnd.name = remnl(rw::recieve(mysock)); rw::send(mysock, me.name); } string sendermsg = ""; while (sendermsg != "exit") { string recvddata = remnl(rw::recieve(mysock)); string rdata = remnl(recvddata); cout << GRN << "\n\nRecieved Encrypted Message : " << RED << rdata; cout << "\n" << RST << frnd.name << WHT << " > " << BLU << decrypt::xor_(decrypt::base64(rdata)) << flush; cin.clear(); cin.ignore(INT_MAX, '\n'); cout << "\n" << RST << me.name << " ( YOU )" << WHT << " > " << BLU << flush; getline(cin, sendermsg); string sdata = encrypt::base64(encrypt::xor_(sendermsg)); cout << GRN << "Sending Encrypted Message : " << RED << sdata << flush; rw::send(mysock, sdata); } // ################## if (mysock != NULL) { mysock->close(); delete mysock; } } else cout << "\nExiting Without Any Connection\n"; return 0; }
true
d9d29654597d25648f2a0de06b5882edf749470f
C++
mnrn/Introduction-to-Algorithms
/ComputationalGeometry/Segments/Submission2/submission2.cpp
UTF-8
18,641
3.53125
4
[]
no_license
/** * @brief 線分を扱います * @date 2016/03/20 */ //**************************************** // 必要なヘッダファイルのインクルード //**************************************** #include <vector> #include <algorithm> #include <cmath> #include <iostream> #include <set> //**************************************** // オブジェクト形式マクロの定義 //**************************************** //#define GEOMETRY_BEGIN namespace geom { //#define GEOMETRY_END } //**************************************** // 型シノニム //**************************************** using elem_t = long double; using index_t = std::int32_t; using indices_t = std::vector<index_t>; //**************************************** // 構造体の定義 //**************************************** struct point { elem_t x, y; point() : x(0), y(0) {} point(elem_t x, elem_t y) : x(x), y(y) {} point& operator+=(const point& p) { x += p.x; y += p.y; return *this; } point& operator-=(const point& p) { x -= p.x; y -= p.y; return *this; } point& operator*=(const elem_t d) { x *= d; y *= d; return *this;} point operator+(const point& p) const { return point(*this) += p; } point operator-(const point& p) const { return point(*this) -= p; } point operator*(const elem_t& d) const { return point(*this) *= d; } }; struct segment { point ps; // 線分の始点 point pd; // 線分の終点 }; namespace limits { constexpr auto pi = 3.141592653589793238; constexpr auto eps = 1e-10; constexpr auto inf = 1e12; } /** * @brief 与えられた3点a, b, cをa -> b -> cと進むとき、 * @details a -> bで時計方向に折れてb -> c(cw) * a -> bで反時計方向に折れてb -> c(ccw) * a -> bで逆を向いてaを通り越してb -> c (back) * a -> bでそのままb -> c(front) * a -> bで逆を向いてb -> cまたは、b == c(on) */ enum struct orient { cw = +1, ccw = -1, back = -2, front = +2, on = 0, }; //**************************************** // 型シノニムその2 //**************************************** using vector_t = point; using polygon_t = std::vector<point>; using segments_t = std::vector<segment>; //**************************************** // 関数の定義 //**************************************** /** * @brief 2つのベクトルa, bからなる行列A = (a, b)の行列式(determinant)を返します * @param const vector_t& a ベクトルa * @param const vector_t& b ベクトルb * @return elem_t det(A) 行列式|(a, b)| */ static constexpr elem_t det(const vector_t& a, const vector_t& b) { return a.x * b.y - a.y * b.x; } /** * @brief 2つのベクトルa, bのクロス積(cross product)a x bを返します * @param const vector_t& a ベクトルa * @param const vector_t& b ベクトルb * @return elem_t a x b クロス積a x b */ static constexpr elem_t cross(const vector_t& a, const vector_t& b) { return a.x * b.y - a.y * b.x; //return det(a, b); } /** * @brief 2つのベクトルa, bのドット積(dot product)a・bを返します * @param const vector_t& a ベクトルa * @param const vector_t& b ベクトルb * @return elem_t a・b ドット積a・b */ static constexpr elem_t dot(const vector_t& a, const vector_t& b) { return a.x * b.x + a.y * b.y; } /** * @brief ベクトルvのノルム(norm・大きさの2乗)を返します * @param const vector_t& v * @return elem_t norm(v); */ static constexpr elem_t norm(const vector_t& v) { return v.x * v.x + v.y * v.y; // return dot(v, v); } /** * @brief ベクトルvの大きさ|v|(原点からの距離)を返します * @param const vector_t& v * @return elem_t sqrt(norm(v)) */ static inline elem_t abs(const vector_t& v) { return std::sqrt(norm(v)); } /** * @brief 点pから線分sに下ろした垂線と線分sの交点を返します * @param const segment& s 線分s * @param const point& p 点p * @return 垂線と線分の交点 */ static inline point proj(const segment& s, const point& p) { vector_t base = s.pd - s.ps; vector_t hypo = p - s.ps; elem_t r = dot(hypo, base) / norm(base); return s.ps + base * r; } /** * @brief 点pと線対称の位置に存在する点を返します * @param cosnt segment& s 線分s * @param const point& p 点p * @param pと線対称な点 */ static inline point reflect(const segment& s, const point p) { return p + (proj(s, p) - p) * 2.0; } /** * @brief 絶対許容誤差(absolute tolerance)を比較します * * @note 2つの浮動小数点数値が等しいかどうか比較するためのイプシロン許容誤差の利用は、 * イプシロンの値が固定されているので、絶対許容誤差(absolute tolerance)と呼ばれている * 絶対許容誤差の欠点は適切なイプシロンの値を見つけるのが困難なことである * イプシロンの値は入力データの値の範囲、および使用している浮動小数点の形式に依存する * 浮動小数点数の範囲全体に対するイプシロンの値を1つだけ選ぶことは不可能である * xおよびyの値が非常に小さな(互いに等しくない)値の場合は、その差は常にイプシロンよりも小さくなる可能性があり、 * 逆に大きな値の場合は、その差はイプシロンよりも常に大きくなるかもしれない. 別の見方として、 * 判定している数が大きくなればなるほど、絶対値による判定が成立するために必要な桁数はどんどん大きくなっていく * * @note 固定されているイプシロンよりも数値が十分大きくなったとき、数値が正確に等しくない限り判定は常に失敗する * これは通常、意図したことではない. 絶対許容誤差は数値の桁数の大きさが予めわかっており、 * 許容誤差の値をそれに応じて設定することができる場合にのみ利用するべきである */ static inline bool absolute_tolerance_compare(elem_t x, elem_t y) noexcept { return std::fabs(x - y) <= limits::eps; } /** * @brief 相対許容誤差(relatice tolerance)を比較します * * @note 基本的な考え方はある数を別の数によって除算し、その結果がどのくらい1に近づいているかを見るというものである * * * @note |x| <= |y|を仮定すると、判定は以下のようになる * if (Abs(x/y - 1.0) <= epsilon)... * これは以下のように書き直せる * if (Abs((x - y) / y) <= epsilon)... * コストのかかる除算を避け、ゼロによる除算のエラーから守るために、後者の式の両辺にAbs(y)を乗算して、以下のように単純化する * if (Abs(x - y) <= epsilon * Abs(y))... * 仮定|x| <= |y|を取り除くと、式は最終的に以下のようになる * if (Abs(x - y) <= epsilon * Max(Abs(x), Abs(y)))... // 相対許容誤差の比較 * * * @note 比較において相対的な判定は「より小さいか等しい」であり、「より小さい」ではないことは重要である * もしそうでなければ、両方の数が正確にゼロだった場合、判定は失敗する。相対的な判定も問題がないわけではない * 判定の式はAbs(x)およびAbs(y)が1よりも大きいときには、望み通りの働きをするが、それらの数値が1よりも小さいときは、 * イプシロンはより小さくないと効力がなくなってしまい、それらの数値が小さくなるほど式を成立させるのに必要な桁数はより多く必要になる */ static inline bool relative_tolerance_compare(elem_t x, elem_t y) noexcept { return std::fabs(x - y) <= limits::eps * std::max(std::fabs(x), std::fabs(y)); } /** * @brief 上記2つの判定を1つに結合させる * @note 数値の絶対値が1よりも大きい場合には、相対的な判定を用い、1よりも小さい場合には、絶対的な判定を用いる * @attention この式はMax()が機械語による命令によって利用できない場合には高価な計算になる可能性がある */ static inline bool combined_tolerance_compare(elem_t x, elem_t y) noexcept { return std::fabs(x - y) <= limits::eps * std::max({ std::fabs(x), std::fabs(y), static_cast<elem_t>(1.0) }); } /** * @brief COMBINED-TOLERANCE-COMPAREより少ない労力で行える近似的な判定 */ static inline bool approximate_combined_tolerance_compare(elem_t x, elem_t y) noexcept { return std::fabs(x - y) <= limits::eps * (std::fabs(x) + std::fabs(y) + 1.0); } /** * @brief 手続きAPPROXIMATE-COMBINED-TOLERANCE-COMPAREの短い名前 */ static inline bool eq(elem_t x, elem_t y) { return approximate_combined_tolerance_compare(x, y); } /** * @brinf 2点(p1, p2)のp0に関する偏角(polar angle)から、 * p0から見た2つのベクトルp0p1↑, p0p2↑の方向を返す */ static inline orient orientation(point p0, point p1, point p2) { p1 -= p0; p2 -= p0; if (cross(p1, p2) > limits::eps) { return orient::cw; } // クロス積(p1-p0)x(p2-p0)が正の場合、cw ...(*1) if (cross(p1, p2) < -limits::eps) { return orient::ccw; } // クロス積(p1-p0)x(p2-p0)が負の場合、ccw ...(*2) // (*1), (*2)に当てはまらないとき、p2は直線p0p1|上(線分p0p1↑上とは限らない)に存在する if (dot(p1, p2) < -limits::eps) { return orient::back; } // ドット積(p1-p0)・(p2-p0)が負の場合、p2->p0->p1(back) ...(*3) // (*3)に当てはまらないとき、p2はp0->p1->p2またはp0->p2->p1の位置に存在する if (eq(norm(p1), norm(p2))) { return orient::front; } // p0p2↑の大きさがp0p1↑の大きさより大きい場合、p0->p1->p2(front) ...(*4) // (*4)に当てはまらないとき、p0->p2->p1(on) return orient::on; } /** * @brief 2点(p1, p2)を原点p0に関する偏角に従って、比較を行う */ static inline int polar_angle_cmp(const point& p1, const point& p2) { const point p0(0, 0); switch(orientation(p0, p1, p2)) { case orient::cw : return 1; case orient::ccw : return -1; case orient::back : return 1; case orient::front : return -1; case orient::on : return 1; } return 0; } //**************************************** // 構造体の定義 //**************************************** enum struct event_type { // ソートを行ったとき、leftが先に来るようにする left = 0, right = 1, }; struct event_point { point p; /**< 座標 */ index_t seg; /**< 線分のインデックス */ event_type e; /**< イベント点の種類 */ event_point() = default; event_point(const point& p, index_t seg, event_type type) : p(p), seg(seg), e(type) { } bool operator < (const event_point& ep) const { // 端点を(x, e, y)上の辞書式順序で比較する // p1.x == p2.xのとき...(*1)、 if (eq(p.x, ep.p.x)) { // (*1)かつ、p1.e == p2.eのとき、 if (e == ep.e) { // p1.y < p2.yを返す return p.y < ep.p.y; } // (*1)かつ、p1.e != p2.eのとき、 else { // p1.e < p2.eを返す return static_cast<int>(e) < static_cast<int>(ep.e); } } // p1.x != p2.xのとき、 else { // p1.x < p2.x返す return p.x < ep.p.x; } } }; //**************************************** // 型シノニム //**************************************** using event_points = std::vector<event_point>; //**************************************** // 関数の定義 //**************************************** /** * @brief 3点(pi, pj, pk)を引数に取り、クロス積(pk - pi) x (pj - pi)を返す * @note direction > epsのとき、cw(clockwise)...ただし、定義によってはccw * direction < -epsのとき、ccw(counterclockwise)...ただし、定義によってはcw * それ以外のとき、0であり、境界条件が発生する. このとき、ベクトルは同一直線上(colinear)にあり、 * それらの方向は同じか互いに逆である */ elem_t direction(const point& pi, const point& pj, const point& pk) { return cross(pk - pi, pj - pi); } /** * @brief pkがpipj|の端点の間にあるか否かを判定する * * @note この手続きは、pkが線分pipj|と同一直線上にあると仮定する */ bool on_segment(const point& pi, const point& pj, const point& pk) { elem_t xi = pi.x, xj = pj.x, xk = pk.x; elem_t yi = pi.y, yj = pj.y, yk = pk.y; return std::min(xi, xj) <= xk && xk <= std::max(xi, xj) && std::min(yi, yj) <= yk && yk <= std::max(yi, yj); } /** * @brief 2本の線分の交差判定 * * @note 2本の線分の交差性を判定するために、各線分が他方を含む直線を跨ぐか否か調べる * 線分p1p2|がある直線を跨ぐ(straddle)のは、点p1がこの直線の一方の側にあり、 * 点p2が他方の側にあるときである. 境界となるのは、p1かp2が直線上にある場合である * 2本の線分が交差するための必要十分条件は次の条件の一方(あるいは両方)が成り立つときである * * 1. どちらの線分も他方を含む直線を跨ぐ * 2. 一方の線分の端点が線分上にある(この条件は境界上にある場合から発生する) * * @note このアイデアを次の手続きで実現する. SEGMENT-INTERSECTは、線分p1p2|と線分p3p4|が交差するときに * TRUEを返し、そうでないときはFALSEを返す. この手続きは、サブルーチンDIRECTIONを呼び出して * クロス積法を用いて相対的な方向を求め、ON-SEGMENTを呼び出して、線分を含む直線上にあることが分かっている点が * この線分上にあるかどうかを判定する */ bool segment_intersect(const point& p1, const point& p2, const point& p3, const point& p4) { elem_t d1 = direction(p3, p4, p1); elem_t d2 = direction(p3, p4, p2); elem_t d3 = direction(p1, p2, p3); elem_t d4 = direction(p1, p2, p4); // 線分p1p2↑と線分p3p4↑が互いに他方の直線を跨ぐ場合 if ( ((d1 > limits::eps && d2 < -limits::eps) || (d1 < -limits::eps && d2 > limits::eps)) && ((d3 > limits::eps && d4 < -limits::eps) || (d3 < -limits::eps && d4 > limits::eps))) { // p1p2|がp3p4|を含む直線を跨ぐから、クロス積(p1-p3)x(p2-p1)と(p4-p2)x(p2-p3)の符号は異なる // p3p4|がp1p2|を含む直線を跨ぐから、クロス積(p3-p1)x(p2-p1)と(p4-p1)x(p2-p1)の符号は異なる return true; } // そうではないとき、これらの線分が互いに他方を跨ぐことはないが、端点が他方の線分上にある余地は残る // どの相対的な方向も0でなければこの可能性は消える // ある相対的方向dkが0のときには、pkは他方の線分と同一直線上にある // pkがこの線分上にあるための必要十分条件は、これがこの線分の端点の間にあることである // ON-SEGMENT呼び出しにおいて、この線分は、第一引数を端点とする線分と異なる方の線分である else if (eq(d1, 0) && on_segment(p3, p4, p1)) { return true; } else if (eq(d2, 0) && on_segment(p3, p4, p2)) { return true; } else if (eq(d3, 0) && on_segment(p1, p2, p3)) { return true; } else if (eq(d4, 0) && on_segment(p1, p2, p4)) { return true; } else { return false; // 0判定はすべて失敗し、FALSEを返す } } /** * @brief 線分交差検出を行う * * @note n本の線分の集合をSとし、Sの中に交差する線分対が1つでもあれば * ブール値TRUEを返し、そうでなければFALSEを返す */ int any_segments_intersect(segments_t& S) { // struct cmp { bool operator () (const segment& s1, const segment& s2) { // return (s1.ps.x - s2.ps.x) * (s2.pd.y - s2.ps.y) // < (s1.ps.y - s2.ps.y) * (s2.pd.x - s2.ps.x); // } }; std::set<index_t> T; // 全擬順序Tを空に初期化する int n = S.size(); event_points Q; // イベントキューQを空に初期化する for (index_t i = 0; i < n; i++) { // 端点ps, pdが左下を基準に並ぶように調整する if (eq(S[i].ps.y, S[i].pd.y)) { if (S[i].ps.x> S[i].pd.x) { std::swap(S[i].ps, S[i].pd); } } else if (S[i].ps.y > S[i].pd.y) { std::swap(S[i].ps, S[i].pd); } Q.emplace_back(S[i].ps, i, event_type::left); Q.emplace_back(S[i].pd, i, event_type::right); } // Sの線分の端点を左から右にソートする std::sort(Q.begin(), Q.end()); int count = 0; for (index_t i = 0; i < 2 * n; i++) { // イベント点の個数は2nだからループの繰り返しは2n if (Q[i].e == event_type::left) { // pが線分sの左端点 for (index_t s : T) { if (segment_intersect(S[Q[i].seg].ps, S[Q[i].seg].pd, S[s].ps, S[s].pd)) { count = count + 1; } } T.insert(Q[i].seg); } if (Q[i].e == event_type::right) { // pが線分sの右端点 T.erase(Q[i].seg); } } return count; } //**************************************** // エントリポイント //**************************************** int main() { using namespace std; int s; cin >> s; segments_t S(s); for (int i = 0; i < s; i++) { int x1, y1, x2, y2; cin >> x1 >> y1 >> x2 >> y2; S[i].ps = point(x1, y1); S[i].pd = point(x2, y2); } cout << any_segments_intersect(S) << endl; return 0; }
true
ffee3cbbb180a77aeb55be8f0ff1fa80173ff01f
C++
guithin/BOJ
/2606/Main.cpp
UTF-8
567
2.75
3
[]
no_license
#include<stdio.h> #include<vector> using namespace std; vector<int> vec[101]; bool check[101] = { 0 }; void dfs(int cur) { check[cur] = true; for (int i = 0; i < vec[cur].size(); i++) { int next = vec[cur][i]; if (check[next] == true) continue; dfs(next); } } int main() { int n, m; scanf("%d %d", &n, &m); for (int i = 1; i <= m; i++) { int u,v; scanf("%d %d", &u, &v); vec[u].push_back(v); vec[v].push_back(u); } dfs(1); int cnt = 0; for (int i = 1; i <= n; i++) { if (check[i] == true) cnt++; } printf("%d\n", cnt-1); return 0; }
true
d95757acd14714555999a0439156eb8b8f14ab6a
C++
Datta2901/Algorithmic-Implementations
/Graph/Graph Traversals(BFS & DFS)/BFS/Snake & ladder problem using BFS.cpp
UTF-8
5,219
4
4
[ "MIT" ]
permissive
/* Problem description ----> Vivek takes out his Snakes and Ladders game and stares at the board, and wonders: If he had absolute control on the die (singular), and could get it to generate any number (in the range 1-6 ) he desired, what would be the least number of rolls of the die in which he'd be able to reach the destination square (Square Number 100) after having started at the base square (Square Number 1)? RULES --> 1. Vivek has total control over the die and the face which shows up every time he tosses it. You need to help him figure out the minimum number of moves in which he can reach the target square (100) after starting at the base (Square 1). 2. A die roll which would cause the player to land up at a square greater than 100, goes wasted, and the player remains at his original square. Such as a case when the player is at Square Number 99, rolls the die, and ends up with a 5. 3. If a person reaches a square which is the base of a ladder, (s)he has to climb up that ladder, and he cannot come down on it. If a person reaches a square which has the mouth of the snake, (s)he has to go down the snake and come out through the tail - there is no way to climb down a ladder or to go up through a snake. Input Format ----> The first line contains the number of tests, T. T testcases follow. For each testcase, the first line contain N(Number of ladders) and after that N line follow. Each of the N line contain 2 integer representing the starting point and the ending point of a ladder respectively. The next line contain integer M(Number of snakes) and after that M line follow. Each of the M line contain 2 integer representing the starting point and the ending point of a snake respectively. Constraints-----> The board is always of the size 10 X 10 and Squares are always numbered 1 to 100 . 1 <= T <= 10 1 <= No. of ladder <= 15 1 <= No. of Snakes <= 15 Square number 1 and 100 will not be the starting point of a ladder or a snake. No square will have more than one of the starting or ending point of a snake or ladder (e.g. snake 56 to 44 and ladder 44 to 97 is not possible because 44 has both ending of a snake and a starting of a ladder). Output Format For each of the T test cases, output one integer, each in a new line, which is the least number of moves (or rolls of the die) in which the player can reach the target square (Square Number 100) after starting at the base (Square Number 1). This corresponds to the ideal sequence of faces which show up when the die is rolled. If there is no solution, print -1. Sample Input ----> 2 3 32 62 42 68 12 98 7 95 13 97 25 93 37 79 27 75 19 49 47 67 17 4 8 52 6 80 26 42 2 72 9 51 19 39 11 37 29 81 3 59 5 79 23 53 7 43 33 77 21 Sample Output ---> 3 5 Explanation ----> For the first test: To traverse the board via the shortest route, the player first rolls the die to get a 5, and ends up at square 6. He then rolls the die to get 6. He ends up at square 12, from where he climbs the ladder to square 98. He then rolls the die to get '2', and ends up at square 100, which is the target square. So, the player required 3 rolls of the die for this shortest and best case scenario. So the answer for the first test is 3. */ #include<bits/stdc++.h> using namespace std; #define ll long long #define ull unsigned long long #define pb push_back #define mp make_pair #define F first #define S second #define PI 3.1415926535897932384626 typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef vector<int> vi; typedef vector<ll> vll; typedef vector<ull> vull; typedef vector<pii> vpii; typedef vector<pll> vpll; typedef vector<vi> vvi; typedef vector<vll> vvll; typedef vector<vull> vvull; mt19937_64 rang(chrono::high_resolution_clock::now().time_since_epoch().count()); int rng(int lim) { uniform_int_distribution<int> uid(0,lim-1); return uid(rang); } const int INF = 0x3f3f3f3f; const int mod = 1e9+7; const int N = 101; vvi g; vi dis; vi board; int n, m; void sssp_by_bfs() { dis.clear(); dis.resize(N); dis.assign(N, -1); dis[1] = 0; queue<int> q; q.push(1); while(!q.empty()) { int curr = q.front(); q.pop(); if(curr == 100) break; for(auto x: g[curr]) { if(dis[x] == -1) { dis[x] = dis[curr] + 1; q.push(x); } } } } void solve() { board.clear(); board.resize(N, 0); cin >> n; for(int i = 0; i < n; i++) { int ls, le; cin >> ls >> le; board[ls] = le - ls; } cin >> m; for(int i = 0; i < m; i++) { int ss, se; cin >> ss >> se; board[ss] = -(ss - se); } g.clear(); g.resize(N); for(int v = 1; v < N; v++) { for(int dice = 1; dice <= 6; dice++) { int j = v + dice; j += board[j]; if(j < N) g[v].pb(j); } } sssp_by_bfs(); cout << dis[100] << "\n"; } int main() { ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); srand(chrono::high_resolution_clock::now().time_since_epoch().count()); // #ifndef ONLINE_JUDGE // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); // #endif int t = 1; cin >> t; while(t--) { solve(); } return 0; }
true
a2015dc9874ce6b09c783c626a2503be967a7131
C++
askeySnip/OJ_records
/UVa/10557.cpp
UTF-8
1,681
2.71875
3
[]
no_license
/* ID: leezhen TASK: practice LANG: C++11 */ #include <iostream> #include <fstream> #include <string> #include <vector> #include <algorithm> #include <cstdio> #include <cstring> #include <set> #include <map> #include <stack> #include <queue> #include <cmath> #include <bitset> using namespace std; typedef vector<int> vi; typedef pair<int, int> ii; typedef vector<pair<int, int> > vii; // struct // data int n; int node_value[103]; vi edges[103]; vi dist; int vist[103]; bool flag; bool bfs(int u) { queue<int> q; q.push(u); memset(vist, 0, sizeof vist); while(!q.empty()) { u = q.front(); q.pop(); if(vist[u]) continue; vist[u] = 1; if(u == n) return true; for(int i=0; i<(int)edges[u].size(); i++) { int v = edges[u][i]; if(!vist[v]) q.push(v); } } return false; } void dfs(int s) { if(flag) return; if(s == n && dist[s] > 0) { flag = true; return; } for(int i=0; i<(int)edges[s].size(); i++) { int v = edges[s][i]; if(dist[v] && dist[s] + node_value[v] > dist[v]) { flag |= bfs(v); if(flag) return; } if(!dist[v] && dist[s] + node_value[v] > 0) { dist[v] = dist[s] + node_value[v]; dfs(v); } } } int main() { while(scanf("%d", &n), n != -1) { for(int i=0; i<103; i++) edges[i].clear(); dist.assign(n+1, 0); int v, t, nt; for(int i=1; i<=n; i++) { scanf("%d%d", &v, &t); node_value[i] = v; for(int j=0; j<t; j++) { scanf("%d", &nt); edges[i].push_back(nt); } } dist[1] = 100; flag = false; dfs(1); if(flag) printf("winnable\n"); else printf("hopeless\n"); } return 0; }
true
cc392ea8c0ca04fb6a4b7e6de8f8d2b5444859cb
C++
boates/accelerated_cpp
/6/6_sg/grade.cpp
UTF-8
2,706
3.625
4
[]
no_license
// source file for the grade functions #include <stdexcept> #include <vector> #include <list> #include "grade.h" #include "median.h" #include "Student_info.h" using std::domain_error; using std::vector; // function to compute a sutdent's grade double grade(double midterm, double final, double homework) { return 0.2*midterm + 0.4*final + 0.4*homework; } // function to ask for grades to be computed double grade(double midterm, double final, const vector<double>& hw) { if (hw.size() == 0) throw domain_error("student has done no homework"); return grade(midterm, final, median(hw)); // creating two functions w/ the same name is called // overloading, C++ knows which you mean based on the args } // function to compute grade for a Student_info object double grade(const Student_info& s) { return grade(s.midterm, s.final, s.homework); } // predicate to determine whether a student failed bool fgrade(const Student_info& s) { return grade(s) < 60; } // separate passing and failing student records: first try list<Student_info> extract_fails(vector<Student_info>& students) { list<Student_info> pass, fail; list<Student_info>::iterator iter = students.begin() // iterator vs. const_iterator while (iter != students.end()) { if (fgrade(*iter)) fail.push_back(*iter); // same as appending students[i] iter = students.erase(iter); // not const_iterator b/c we change it else ++iter; } return fail; } // function to check if a student has completed all of their homework bool did_all_hw(const Student_info& s) { return ((find(s.homework.begin(), s.homework.end(), 0)) == s.homeowkr.end()); } // function to implement a catch and allow for proper overloading double grade_aux(const Student_info& s) { try { return grade(s); } catch (domain_error) { return grade(s.midterm, s.final, 0); } } // return the students grade calculated using an average of the homework grades double average_grade(const Student_info& s) { return grade(s.midterm, s.final, average(s.homework)); } // median of the nonzero elements of s.homework, or zero if no such elements exist double optimistic_median(const Student_info& s) { vector<double> nonzero; // remove_copy acts like remove but copies results to indicated destination // this will remove all 0 values (4th arg) from a range (1st & 2nd args) and copy // the remaining to 3rd arg remove_copy(s.homework.begin(), s.homework.end(), back_inserter(nonzero), 0); // Check if there were any nonzero grades at all, if not return 0 as homework grade if (nonzero.empty()) { return grade(s.midterm, s.final, 0); } else { return grade(s.midterm, s.final, median(nonzero)); } }
true
84e143b8fb78750c2de3d48bd3af82ab8ced419d
C++
AaronMooney/Qwixx
/Qwixx_Assignment/player.cpp
UTF-8
3,042
3.171875
3
[]
no_license
/* Assignment: Qwixx Author: Aaron Mooney 20072163 Module: Games Development 1 */ #include "player.h" #include <iostream> #include <algorithm> using namespace std; //Create new player and scoresheet for that player Player::Player(int playerId) : m_playerId(playerId) { p_board = new ScoreSheet(); } //deconstructor Player::~Player() { delete p_board; p_board = 0; } int & Player::getId() { return this->m_playerId; } bool Player::move(int rowId, int value) { vector<string>& row = this->p_board->sheet->at(rowId); //red/yellow/green/blue row if (rowId < 2) { if (row.at(value - 2) == "X" || row.at(value - 2) == "/") { return false; } } //if the value is crossed already or is left of the cross return false else { if (row.at(12 - value) == "X" || row.at(12 - value) == "/") { return false; } } vector<string>::reverse_iterator it; //cycle backwards from the value to block previous values until another cross or if (rowId < 2) it = row.rend() - (value - 2); //the first element is reached else it = row.rend() - (12 - value); for (it; it != row.rend(); it++) { if (*it == "X") break; *it = "/"; } if (rowId < 2) { row.at(value - 2) = "X"; } else row.at(12 - value) = "X"; return true; } int &Player::getMisthrows() { return this->m_misthrows; } void Player::addMisthrow() { this->m_misthrows++; } void Player::setFirstMisthrow(bool& misthrow) { this->firstTurnMisthrow = true; } void Player::setSecondMisthrow(bool& misthrow) { this->secondTurnMisthrow = true; } void Player::isMisthrow() { if (this->secondTurnMisthrow == true && this->firstTurnMisthrow == true) { this->addMisthrow(); } } ScoreSheet& Player::getSheet() { return *this->p_board; } /* This method checks the frequency of 'X' in each row with the count() method and calculates the scores. */ int Player::getScore() { vector<int> chart{ 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78 }; int redXFrequency = count(this->p_board->sheet->at(0).begin(), this->p_board->sheet->at(0).end(), "X"); int yellowXFrequency = count(this->p_board->sheet->at(1).begin(), this->p_board->sheet->at(1).end(), "X"); int greenXFrequency = count(this->p_board->sheet->at(2).begin(), this->p_board->sheet->at(2).end(), "X"); int blueXFrequency = count(this->p_board->sheet->at(3).begin(), this->p_board->sheet->at(3).end(), "X"); int redTotal = 0; int yellowTotal = 0; int greenTotal = 0; int blueTotal = 0; for (vector<int>::const_iterator it = chart.begin(); it != chart.end(); it++) { if (redXFrequency == *it) redTotal = redXFrequency * *it; if (yellowXFrequency == *it) yellowTotal = yellowXFrequency * *it; if (greenXFrequency == *it) greenTotal = greenXFrequency * *it; if (blueXFrequency == *it) blueTotal = blueXFrequency * *it; } int total = (redTotal + yellowTotal + greenTotal + blueTotal) - (getMisthrows() * 5); this->m_score = total; return total; } int Player::getTotalScore() { return this->m_score; } void Player::printBoard() { this->getSheet().printSheet(); }
true
93c0bb363c9a3edee7f464760bbd197b990961d2
C++
TheElderMindseeker/Project_I
/pill/Pill.cpp
UTF-8
610
2.765625
3
[]
no_license
// // Created by Даниил on 21.09.2017. // #include "Pill.hpp" Pill::Pill (float pill_percentage, float death_rate, float problems_rate, float no_reaction_rate) : pill_percentage ( pill_percentage), death_rate (death_rate), problems_rate (problems_rate), no_reaction_rate (no_reaction_rate) {} float Pill::get_death_rate () const { return death_rate; } float Pill::get_problems_rate () const { return problems_rate; } float Pill::get_no_reaction_rate () const { return no_reaction_rate; } float Pill::get_joint_rate (float rate) const { return pill_percentage * rate; }
true
b9f73d0ebd5da3fbbb5bd7f54f2282a45e643bad
C++
yangsha-wan/leetcode
/cpp/103BinaryTreeZigzagLevelOrderTraversal/Solution.cpp
UTF-8
1,740
3.25
3
[]
no_license
// // Created by baidu on 17/10/2016. // #include <vector> #include <queue> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: vector<vector<int>> zigzagLevelOrder(TreeNode *root) { using std::queue; queue<TreeNode *>aQueue,bQueue; TreeNode * pointer = root; TreeNode * flag = NULL; bool zigzag = true; vector<int> currentLevel; vector<vector<int>> result; if (pointer) { aQueue.push(pointer); aQueue.push(flag); } while (!aQueue.empty()) { pointer = aQueue.front(); aQueue.pop(); if (pointer == flag) { if (zigzag) { result.push_back(currentLevel); } else { vector<int> reversedCurrentLevel; for (int i = currentLevel.size() - 1; i >= 0; i--) { reversedCurrentLevel.push_back(currentLevel[i]); } result.push_back(reversedCurrentLevel); } currentLevel.clear(); zigzag = !zigzag; if (aQueue.empty()) { return result; } aQueue.push(flag); } else { currentLevel.push_back(pointer->val); if (pointer->left != NULL) { aQueue.push(pointer->left); } if (pointer->right != NULL) { aQueue.push(pointer->right); } } } return result; } };
true
7b9e2b53ffe837d2f80ae1980e50820be7025f26
C++
whillet/AccountBook
/AccountBook/AccountBook.cpp
UTF-8
415
2.796875
3
[]
no_license
#include <cstdio> #include "Time.h" #include "Data.h" using namespace std; void printTime(Time & time) { char tempString[15]; time.getTIme(tempString, 15); printf(tempString); printf("\n"); } int main() { Time test,test2,test3("20000631000000"); Data a; test2.setTime(test.getTIme()); printf("Hello world!\n"); printTime(a.getApprovedDate()); printTime(a.getRegisteredDate()); getchar(); return 0; }
true
0f1c336513a482f1d403eff91d10164d97a2050f
C++
mpound/carma
/carma/ui/rtd/windows/rtdwho.cc
UTF-8
5,482
2.5625
3
[ "FSFUL" ]
permissive
#include "carma/util/Program.h" #include "carma/ui/rtd/common/CarmaDisplay.h" #include "carma/ui/rtd/common/Connections.h" #include <unistd.h> #include <cstring> using namespace ::std; using namespace log4cpp; using namespace carma::util; using namespace carma::ui::rtd; /** * A slight variant on the normal interger cell. This one generates a * string of blanks when the value is zero. * We use it for display (not displaying) the PID. */ class CellPid: public CellInt { public: CellPid(const char* _fmt, Cnx* _cnx, int& _d): CellInt(_fmt, _d), cnx(_cnx) { setValidity( true ); } virtual void update() { fmtOss_.str( "" ); fmtOss_ << setw(format_.len); if (cnx->valid == 0) fmtOss_ << ""; else fmtOss_ << data ; updateColor(); } virtual void updateColor() { if (cnx->valid ) { if (cnx->hasControl) setColor(PURPLE_CELL_COLOR); else if (cnx->guest) setColor(YELLOW_CELL_COLOR); else setColor(WHITE_CELL_COLOR); } else setColor(WHITE_CELL_COLOR); } private: Cnx* cnx; }; /** * A slight variant on the normal String cell with different colors. */ class CellCnxString:public CellCharString { public: CellCnxString(const char* _fmt, Cnx* _cnx, char* _str): CellCharString(_fmt, _str), cnx(_cnx) { setValidity( true ); } virtual void updateColor() { if (cnx->valid ) { if (cnx->hasControl) setColor(PURPLE_CELL_COLOR); else if (cnx->guest) setColor(YELLOW_CELL_COLOR); else setColor(WHITE_CELL_COLOR); } else setColor(WHITE_CELL_COLOR); } private: Cnx* cnx; }; /** * Include an update of the shared memory that drives the displays. */ class CarmaWho: public CarmaDisplay { public: CarmaWho(): CarmaDisplay("Who (rtd connections)", ut, lst) { string connectionsFilename = "/tmp/connections.shmem"; strcpy(ut, "01:02:03"); strcpy(lst, "12:13:14"); connectionRO = new ConnectionRO(static_cast< int >(getpid()), connectionsFilename); connection = connectionRO->getConnectionData(); } ConnectionRO* getConnection() { return connectionRO; } ConnectionData* getConnectionData() { return connection; } int getMaxConnections() { return connectionRO->getMaxConnections(); } virtual void internalUpdate() { connectionRO->getConnectionData(); // Force an update of the cache //cout<<"*******"<<connection->cnx[1].processId<<endl; } private: ConnectionRO* connectionRO; ConnectionData* connection; char ut[20]; char lst[20]; }; //--------------------------------------------------------------------------- // *** M A I N *** static std::string makeHelp() { ostringstream oss; oss << " WHO (CONNECTION STATUS)\n\n" << "All users connected to the array are listed in this table. " << "Note that there are multiple folders to the display in case " << "the first page is full. " << "Entries listed in purple indicate the person who currently has " << "control of the system (if supported). " << "Guests that cannot control the array are shown in yellow. " << "This window can be made invisible to those who cannot potentially " << "control the array (guests)."; return oss.str(); } int carma::util::Program::main() { const int rowsPerFolder = 20; // Create a display and add help to it CarmaWho display; display.setSpecificHelp("Carma Connections Help", makeHelp()); int totalRows = display.getMaxConnections(); ConnectionData* connection = display.getConnectionData(); vector<string> folderName; const int numFolders = (totalRows + rowsPerFolder - 1)/rowsPerFolder; int r = 0; for (int f = 0; f < numFolders; f++) { const int beg = f*rowsPerFolder + 1; int fin = beg + rowsPerFolder -1; if (fin > totalRows) fin = totalRows; int rowsThisFolder = fin - beg + 1; ostringstream o; o << "Connections " << beg << "-" << fin ; RtFolderPtr folder(new RtFolder(o.str())); display.add(folder); RtTablePtr tbl(new RtTable("Connection")); tbl->setBorder(ONE_PIXEL_BELOW_BORDER); tbl->setReverseOrder(); folder->add(tbl); tbl->addCol(RtColumn::makeColumn("Window Name")); tbl->addCol(RtColumn::makeColumn("User")); tbl->addCol(RtColumn::makeColumn("Location")); tbl->addCol(RtColumn::makeColumn("Start(UT)")); //tbl->addCol(RtColumn::makeColumn("Upd")); tbl->addCol(RtColumn::makeColumn("PID")); for (int i = 0; i<rowsThisFolder; i++) { tbl->addRow(RtRow::makeRow("")); } for (int i = 0; i < rowsThisFolder; i++, r++) { Cnx* c = &(connection->cnx[r]); tbl->add(CellPtr(new CellCnxString("12", c, c->windowName))); tbl->add(CellPtr(new CellCnxString("25", c, c->compactName))); tbl->add(CellPtr(new CellCnxString("30", c, c->fullLocation))); tbl->add(CellPtr(new CellCnxString("11", c, c->connectStartString))); //tbl->add(CellPtr(new CellCharString("6", readPointer[r].wdwUpdateRate))); tbl->add(CellPtr(new CellPid ("5", c, c->processId))); } } // Now serve the data forever while(display.serveData()); return EXIT_SUCCESS; }
true
d4bdde39a0fe6e30f29f3979fdc3834c00059c3c
C++
alexandraback/datacollection
/solutions_2463486_0/C++/natha0x6e/fair.cpp
UTF-8
1,386
3.140625
3
[]
no_license
#include <iostream> //using http://www.shoup.net/ntl/ for handling large numbers #include <NTL/ZZ.h> NTL_CLIENT //mid = true if the ZZ makePal(ZZ x, bool mid) { ZZ result = x; if(mid) { x /= 10; } while(x > 0) { result *= 10; result += x % 10; x /= 10; } return result; } bool isFair(ZZ x) { ZZ logt = to_ZZ(1); ZZ div = to_ZZ(1); while(x / div >= 10) { div *= 10; logt++; } ZZ tmp = x; for(ZZ i = to_ZZ(0);i < logt / 2;i++) { if(tmp % 10 != (x / div) % 10) { return false; } tmp /= 10; div /= 10; } return true; } ZZ test(ZZ a, ZZ b) { ZZ result = to_ZZ(0); ZZ sq = to_ZZ(0); ZZ pal; ZZ start = to_ZZ(1); ZZ j; while(sq < b) { for(j = start;j < start * 10;j++) { pal = makePal(j, true); sq = pal * pal; if(sq >= a && sq <= b && isFair(sq)) { result++; } if(sq >= b){break;} } if(sq >= b){break;} for(j = start;j < start * 10;j++) { pal = makePal(j, false); sq = pal * pal; if(sq >= a && sq <= b && isFair(sq)) { result++; } if(sq >= b){break;} } start *= 10; } return result; } int main(int argc,char *argv[]) { (void) argc; (void) argv; int numTests; cin >> numTests; for(int i = 0;i < numTests;i++) { ZZ a; ZZ b; cin >> a >> b; ZZ result = test(a, b); cout << "Case #" << i+1 << ": " << result << endl; } return 0; }
true
4f0112e628f16429c2703c653bece27e2369ca77
C++
skwee357/sk-graphics-engine
/SkgeCore/include/Render/SkgeResource.hpp
UTF-8
1,185
2.75
3
[ "MIT" ]
permissive
/* * This File is a part of SK-Game Engine. * * Copyright (c) 2009 by Dmitry skwo Kudryavtsev / SK-Software * s.kwee357@gmail.com */ #ifndef SKGE_RESOURCE_H_ #define SKGE_RESOURCE_H_ #include "Skge.hpp" namespace skge{ /** * Resource Information. */ class SKGE_API ResourceInfo{ private: String m_Name; /**< Resource unique name. */ public: /** * Constructor. Sets resource information * @param _name Resource name. */ ResourceInfo(const String& _name):m_Name(_name){} /** * Name getter. * @return Resource name. */ inline const String& getName() const { return m_Name; } }; /** * Resource, basic type of all resources. */ class SKGE_API Resource{ protected: ResourceInfo m_Info; /**< Resource Info. */ bool m_Loaded; /**< Was the resource loaded? */ public: /** * Constructor. * @param _name Resource name. */ Resource(const String& _name): m_Info(_name), m_Loaded(false){} /** * Destructor. */ virtual ~Resource(){} /** * Get Resource Info. * @return Resource info. */ inline const ResourceInfo& getInfo() const { return m_Info; } }; } #endif
true
e2acb49e3d4c561e738c1873a68679a65a948d3a
C++
VirajeeAmarasinghe/MultiCashGame
/NewMultiCashGame.cpp
UTF-8
26,198
3.3125
3
[]
no_license
#include<iostream> #include<string> #include<stdlib.h> #include<windows.h> #include<fstream> #include<time.h> #include<iomanip> using namespace std; void login(); int menu(); void help(); void displayLetterGrid(); int ** randomHiddenGrid(); int insertInitialAmount(); void selection_options(); void calculate_and_display_amount(string &player_name); string getName(); void store_data(string &player_name,int &initial_amount,int &attempts,int &amount1,int &amount2,int &amount3,int &bonus,double &penalty_charge,double &total_amount); void view_player_details(); void create_new_admin_account(); void new_user_registration(); void reset_password(); void main(){ selection_options(); } void selection_options(){ //method for select menu options. int choice=7; //variable for store menu option while(choice!=6 && choice!=1){ choice=menu(); cout<<"\n"; system("pause"); switch(choice){ case 1:{ system("cls"); login(); } break; case 2:{ system("cls"); view_player_details(); } break; case 3:{ system("cls"); create_new_admin_account(); } break; case 4:{ system("cls"); new_user_registration(); } break; case 5:{ system("cls"); reset_password(); } break; case 6:{ system("cls"); cout<<"\n*****************THANK U****************"<<endl; } break; default:{ cout<<"!!!!!!!!!!!!!!!!!!!SORRY...INVALID CHOICE.PLEASE TRY AGAIN!!!!!!!!!!!!!!!!!!!!"<<endl; Sleep(1000); } } } } void login(){ string user,pass,user_name,password,headline; ifstream logintext; int count=0; //variable for control the while loop cout<<"\n LOGIN "<<endl; cout<<"*************************************************************"<<endl; while(count<3){ cout<<"\n* ENTER USER NAME :"; cin.clear(); cin.ignore(10000000,'\n'); cin>>user_name; //get user name from the user cout<<"\n* ENTER PASSWORD :"; cin>>password; //get password from the user logintext.open("Authentication.txt"); getline(logintext,headline); //read headline from the text file logintext>>user>>pass; //read user name and password from the text file while(logintext){ if(strcmpi(user_name.c_str(),user.c_str())==0 && password==pass){ //user name is case insensitive count=3; cout<<"\n\n*************USER NAME AND PASSWORD ARE CORRECT**************"<<endl; cout<<"\n@@@@@@@@@@@@@YOU ARE ALLOWED TO ACCESS NEXT STEP@@@@@@@@@@@@@"<<endl; cout<<"\n"; system("pause"); system("cls"); help(); displayLetterGrid(); calculate_and_display_amount(getName()); return; } logintext>>user>>pass; //read user name and password from the text file } if(count<2){ //check whether attempts exeeds the limit. count+=1; cout<<"\n\n!!!!!!!!!!!!!WARNING:LOGIN DETAILS ARE INCORRECT!!!!!!!!!!!!!"<<endl; cout<<"\n!!!!!!!!!!!!!!!!!!!!!YOU HAVE "<<3-count<<" ATTEMPTS!!!!!!!!!!!!!!!!!!!!!"<<endl; }else if(count==2){ cout<<"\n\n!!!!!WARNING:ATTEMPTS EXCEED THE LIMIT.SYSTEM IS LOCKED!!!!!!"; cout<<"\n"; system("pause"); selection_options(); return; } logintext.close(); } } int menu(){ int choice; //to store menu option system("cls"); cout<<"\n******************************Menu*******************************"<<endl; cout<<"\n* 1.LOGIN *"<<endl; cout<<"\n* 2.VIEW PLAYERS' DETAILS *"<<endl; cout<<"\n* 3.CREATE NEW ADMIN ACCOUNT *"<<endl; cout<<"\n* 4.NEW USER REGISTRATION *"<<endl; cout<<"\n* 5.RESET PASSWORD *"<<endl; cout<<"\n* 6.EXIT *"<<endl; cout<<"\n*****************************************************************"<<endl; cout<<"\nENTER YOUR CHOICE(1,2,3,4,5 or 6):"; cin>>choice; return choice; } void help(){ system("cls"); cout<<"\n************************GUIDLINES FOR THE NEW USER**************************"<<endl; cout<<"\n*1.Player can insert the initial amount to start the game. *"<<endl; cout<<"\n*2.Player can select any letter any of the letter from the Letter Grid. *"<<endl; cout<<"\n*3.Once the player inserts the selected letter,winning amount is displayed *\n on the screen."<<endl; cout<<"****************************************************************************"<<endl; cout<<"\n\n\n*************************RULES AND REGULTAIONS******************************"<<endl; cout<<"\n*1.Initial amount must be between Rs.500-Rs.10000. *"<<endl; cout<<"\n*2.Player can pick only one letter at a time. *"<<endl; cout<<"\n*3.One player can select the lucky letter for 3 attempts. *"<<endl; cout<<"\n*4.Players who get the same value in all 3 attempts(other than zero) will *\n get bonus amount of Rs.500."<<endl; cout<<"\n*5.If the palyer wish to exit the game after first or second attempt *\n 5% penalty will be deducted from the winning amount."<<endl; cout<<"****************************************************************************"<<endl; cout<<"\n"<<endl; system("pause"); } void displayLetterGrid(){ system("cls"); char letters[4][4]={{'A','B','C','D'},{'E','F','G','H'},{'I','J','K','L'},{'M','N','O','P'}}; cout<<"************************LETTER GRID***************************"<<endl; cout<<"\n"; for(int i=0;i<22;i++){ //loop for counting spaces cout<<" "; } for(int j=0;j<9;j++){ cout<<"- "; } cout<<"\n"; for(int k=0;k<4;k++){ for(int l=0;l<22;l++){ cout<<" "; //loop for counting spaces } for(int m=0;m<4;m++){ cout<<"| "<<letters[k][m]<<" "; if(m==3){ cout<<"|"; } } cout<<"\n"; for(int n=0;n<22;n++){ cout<<" "; //loop for counting spaces } for(int p=0;p<9;p++){ cout<<"- "; } cout<<"\n"; } } int ** randomHiddenGrid(){ static int ** random_numbers=new int *[4]; srand(time(NULL)); for(int a=0;a<4;a++){ random_numbers[a]=new int[4]; for(int b=0;b<4;b++){ random_numbers[a][b]=rand()%6; } } return random_numbers; } string getName(){ //function for get player name string player_name; //to store player name cout<<"\n\n* ENTER YOUR NAME :"; cin.clear(); cin.ignore(10000000,'\n'); getline(cin,player_name); return player_name; } int insertInitialAmount(){ int int_amount; //to store intial amount int countloop=1; //variable for control the while loop int count_attempt=0; //variable for counting number of attempts while(countloop!=0 && count_attempt<3){ cout<<"\n\n* ENTER VALID INITIAL AMOUNT BETWEEN Rs.500-Rs.10000\n (WARNING:PLEASE DON'T INSERT CENTS,CENTS PART\n WILL BE IGNORED AUTOMATICALLY) :"; //no decimal values cin>>int_amount; //it takes only integer part of the input,so if the user enters 45j it takes only 45 as the input. countloop=0; count_attempt+=1; if(cin.fail()){ //check whether input is valid or not cin.clear(); cin.ignore(10000000,'\n'); if(count_attempt<3){ //check whether attempts exceed the limit cout<<"\n\n!!!!!!!!!!!!!!!!!!!!!!!!!YOU HAVE "<<3-count_attempt<<" MORE ATTEMPTS!!!!!!!!!!!!!!!!!!!!!!!!!"<<endl; countloop=1; }else{ cout<<"\n\n!!!!!!!!!!!!!!!!!!!!!!!!!WARNING:NO MORE ATTEMPTS!!!!!!!!!!!!!!!!!!!!!!!!!"<<endl; cout<<"\n"; system("pause"); selection_options(); return 0; } }else{ if(int_amount<500 || int_amount>10000){ //check whether value is equal and greater than 500 and equal and less than 10000 if(count_attempt<3){ cout<<"\n\n!!!!!!!!!!!!!!!!!!!!!!!!!YOU HAVE "<<3-count_attempt<<" MORE ATTEMPTS!!!!!!!!!!!!!!!!!!!!!!!!!"<<endl; countloop=1; }else{ cout<<"\n\n!!!!!!!!!!!!!!!!!!!!!!!!!WARNING:NO MORE ATTEMPTS!!!!!!!!!!!!!!!!!!!!!!!!!"<<endl; cout<<"\n"; system("pause"); selection_options(); return 0; } } cin.clear(); cin.ignore(10000000,'\n'); } } return int_amount; } void calculate_and_display_amount(string &player_name){ string player_name1=player_name; //variable to store player name int initial_amount=insertInitialAmount(); //assigning initial_amount int bonus=0; //to store bonus amount double total_amount=initial_amount; //to store total winning amount double penalty_charge=0; //to store penalty charge double current_amount=total_amount; //to store amount,win at one round. int count_loop=0; //to store game round int multiply=0; //to store random hidden value int check_repeat=0; //to check whether valid game round or not. char letter; //to store user input letter char yes_no; //variable to control the exit the game bool want_to_break=false; //to break the outer loop of nested for loop bool matched_the_letter=false; //to check the any letter matches with the input int array_ele1=0; //to increment multiply_per_attempt array index int array_ele2=0; //to increment multiply_per_attempt array index int ** newrandom_numbers; newrandom_numbers=randomHiddenGrid(); //assigning random hidden values to array. char letters[4][4]={{'A','B','C','D'},{'E','F','G','H'},{'I','J','K','L'},{'M','N','O','P'}}; int count_selection[4][4]={{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}}; //to store number of times the letter has selected int multiply_per_attempt[3]={0,0,0}; //to store hidden value in each round int amount_per_attempt[3]={0,0,0}; //to store amount winning in each round while(count_loop<3){ //loop for control the 3 attempts cout<<"\n\n* ENTER YOUR LUCKY LETTER :"; //prompt user to enter the letter cin>>letter; count_loop+=1; for(int i=0;i<4;i++){ for(int j=0;j<4;j++){ if(letter==letters[i][j]){ //check letter is matching with the letter grid if(count_selection[i][j]==0){ //check whether the selected letter is already selected or not. multiply=newrandom_numbers[i][j]; //get hidden random value. count_selection[i][j]+=1; want_to_break=true; matched_the_letter=true; break; }else{ cout<<"\n\n!!WARNING:YOU HAVE SELECTED THIS LETTER ALREADY.PLEASE SELECT ANOTHER ONE!!"<<endl; count_loop-=1; check_repeat+=1; want_to_break=true; matched_the_letter=true; break; } } } if(want_to_break){ break; } } if(matched_the_letter==false){ //check validity of the letter cout<<"\n\n!!!!!!!!!!!!!!!!!!!!!!WARNING:ENTER VALID LETTER!!!!!!!!!!!!!!!!!!!!!!!!!"<<endl; cin.clear(); cin.ignore(1000,'\n'); count_loop-=1; check_repeat+=1; } if(check_repeat==0){ //If user has been entered valid letter,calculation is done total_amount=total_amount*multiply; multiply_per_attempt[array_ele1]=multiply; amount_per_attempt[array_ele2]=total_amount; array_ele1++; array_ele2++; cout<<"\n\n* YOUR WINNING AMOUNT :"; cout<<"Rs."<<current_amount<<"x"<<multiply<<"=Rs."<<total_amount<<endl; current_amount=total_amount; } if(count_loop<3 && check_repeat==0 && matched_the_letter==true){ //user is allowed to exit the game after finishing the round, that he took successfully. cout<<"\n\n* DO YOU WANT TO EXIT THE GAME?\n (ENTER Y/y FOR YES & N/n FOR NO) :"; cin>>yes_no; do{ switch(yes_no){ case 'Y':case 'y':{ if(total_amount>0){ penalty_charge=(total_amount*5)/100; total_amount=(total_amount*95)/100; }else{ penalty_charge=0; total_amount=0; } cout<<"\n\n* PENALTY CHARGE Rs. :"<<penalty_charge<<endl; cout<<"\n\n* YOUR TOTAL WINNING AMOUNT Rs. :"<<total_amount<<endl; store_data(player_name1,initial_amount,count_loop,amount_per_attempt[0],amount_per_attempt[1],amount_per_attempt[2],bonus,penalty_charge,total_amount); //store data cout<<"\n"; system("pause"); selection_options(); return; } break; case 'N':case 'n':; break; default:{cout<<"\n\n* WARNING:ENTER VALID LETTER :"; cin>>yes_no; } } }while(yes_no!='Y' && yes_no!='y' && yes_no!='N' && yes_no!='n'); } check_repeat=0; want_to_break=false; matched_the_letter=false; } if(count_loop==3 && multiply_per_attempt[0]!=0 && multiply_per_attempt[1]!=0 && multiply_per_attempt[2]!=0){ //Player who get the same multiply value in all 3 attempts if(multiply_per_attempt[0]==multiply_per_attempt[1]==multiply_per_attempt[2]){ //(other than zero) will get bonus amount of Rs.500 total_amount+=500; bonus=500; } } system("pause"); system("cls"); cout<<"********************THE FINAL REPORT********************"<<endl; cout<<"* PLAYER NAME :"<<player_name1<<endl; cout<<"* NUMBER OF ATTEMPTS :3"<<endl; cout<<"* WINING AMOUNT OF FIRST ATTEMPT Rs.:"<<amount_per_attempt[0]<<endl; cout<<"* WINING AMOUNT OF SECOND ATTEMPT Rs.:"<<amount_per_attempt[1]<<endl; cout<<"* WINING AMOUNT OF THIRD ATTEMPT Rs.:"<<amount_per_attempt[2]<<endl; cout<<"* BONUS Rs.:"<<bonus<<endl; cout<<"* PENALTY CHARGE Rs.:"<<penalty_charge<<endl; cout<<"* TOTAL WINING AMOUNT Rs.:"<<total_amount<<endl; store_data(player_name1,initial_amount,count_loop,amount_per_attempt[0],amount_per_attempt[1],amount_per_attempt[2],bonus,penalty_charge,total_amount); //store data delete[] newrandom_numbers; //delete the ram space allocated for the array cout<<endl; system("pause"); selection_options(); array_ele1=0; array_ele2=0; return; } void store_data(string &player_name,int &initial_amount,int &attempts,int &amount1,int &amount2,int &amount3,int &bonus,double &penalty_charge,double &total_amount){ ofstream store_file; ifstream get_file; string content; //to store the content of text file bool has_content=false; //check whether the text file already has some content get_file.open("PlayerRecords.txt",ios::in); getline(get_file,content); while(!get_file.eof()){ has_content=true; getline(get_file,content); } get_file.close(); store_file.open("PlayerRecords.txt",ios::app); if(has_content==false){ store_file<<left<<setw(50)<<"PLAYER NAME"<<setw(50)<<"INITIAL AMOUNT"<<setw(50)<<"NUMBER OF ATTEMPTS"<<setw(50)<<"WINING AMOUNT OF FIRST ATTEMPT(Rs.)"<<setw(50)<<"WINING AMOUNT OF SECOND ATTEMPT(Rs.)"<<setw(50)<<"WINING AMOUNT OF THIRD ATTEMPT(Rs.)"<<setw(50)<<"BONUS(Rs.)"<<setw(50)<<"PENALTY CAHRGE(Rs.)"<<setw(50)<<"TOTAL WINNING AMOUNT(Rs.)"<<endl; store_file<<left<<setw(50)<<player_name<<setw(50)<<initial_amount<<setw(50)<<attempts<<setw(50)<<amount1<<setw(50)<<amount2<<setw(50)<<amount3<<setw(50)<<bonus<<setw(50)<<penalty_charge<<setw(50)<<total_amount<<endl; }else{ store_file<<left<<setw(50)<<player_name<<setw(50)<<initial_amount<<setw(50)<<attempts<<setw(50)<<amount1<<setw(50)<<amount2<<setw(50)<<amount3<<setw(50)<<bonus<<setw(50)<<penalty_charge<<setw(50)<<total_amount<<endl; } cout<<"\n SAVED SUCCESSFULLY"<<endl; store_file.close(); } void view_player_details(){ //open PlayerRecord text file string pass; //variable to store admin password entered by the user int i; //variable to control the while loop int count_loop=0; //variable to control the attempts cout<<"*************WELCOME TO VIEW PLAYER DETAILS PAGE***********"<<endl; cout<<"\n TO CONTINUE ENTER ADMIN PASSWORD:"; cin>>pass; do{ i=0; count_loop+=1; ifstream admin_file; string password; //variable to store admin password read from the text file string user_name; //variable to store admin user_name read from the text file admin_file.open("admin_account.txt"); admin_file>>user_name; while(admin_file){ admin_file>>password; } admin_file.close(); if(password!=pass){ //check whether user entered password with the text file password i++; cout<<"\n ENTER VALID PASSWORD:"; cin.clear(); cin.ignore(100000000,'\n'); cin>>pass; }else{ system("cls"); string file = "notepad.exe PlayerRecords.txt"; system(file.c_str()); return; } }while(i!=0 && count_loop<2); cout<<"\n YOU ARE FAILED IN ALL 3 ATTEMPTS.SORRY"<<endl; cout<<"\n"; system("pause"); return; } void create_new_admin_account(){ cout<<"**************WELCOME TO NEW ADMIN REGISTRATION PAGE**************"<<endl; ifstream admin_file; string content; //to store content of the text file bool has_content=false; //to check the text file already has some content admin_file.open("admin_account.txt"); admin_file>>content; while(admin_file){ has_content=true; admin_file>>content; } if(has_content){ char option; //to store yes or no option cout<<"\n* ADMIN HAS ALREADY REGISTERED.DO YOU WANT TO MODIFY THE DETAILS?"<<endl; cout<<"* ENTER Y OR y FOR YES AND N OR n FOR NO :"; do{ cin>>option; switch(option){ case 'Y':case 'y':{ int i=0; string pass; cout<<"\n* TO CONTINUE ENTER THE CURRENT PASSWORD :"; do{ cin>>pass; //to store admin password entered by the user cin.clear(); cin.ignore(10000000,'\n'); i++; if(content==pass){ string user_name,password; int w; do{ w=0; //variable to control the do-while loop cout<<"\n* ENTER NEW USER NAME(USER NAME MUST BE ONE WORD):"; getline(cin,user_name); //get new password from the user for(int i=0;i<user_name.length();i++){ if(user_name.substr(i,1)==" "){ //check whether user name is one word or not w++; cin.clear(); cin.ignore(10000000,'\n'); } } }while(w==1); cout<<"\n* ENTER NEW PASSWORD :"; cin>>password; //get new password from the user ofstream modify_file; modify_file.open("admin_account.txt"); modify_file<<user_name<<"\t"<<password<<endl; modify_file.close(); cout<<"\n MODIFIED SUCCESSFULLY."<<endl; cout<<endl; system("pause"); return; }else{ cout<<"\n* ENTER VALID PASSWORD :"; } }while(i<3); return; } break; case 'N':case 'n':{ return; } break; default:{ cout<<"\n* ENTER VALID LETTER :"; cin.clear(); cin.ignore(10000000,'\n'); } break; } }while(option!='Y' && option!='y' && option!='N' && option!='n'); }else{ string user_name,password; int w; cin.clear(); cin.ignore(1000000,'\n'); do{ w=0; cout<<"\n* ENTER USER NAME(USER NAME MUST BE ONE WORD) :"; getline(cin,user_name); for(int i=0;i<user_name.length();i++){ if(user_name.substr(i,1)==" "){ w++; cin.clear(); cin.ignore(10000000,'\n'); } } }while(w==1); cout<<"\n* ENTER PASSWORD :"; cin>>password; ofstream create_file; create_file.open("admin_account.txt"); create_file<<user_name<<"\t"<<password<<endl; create_file.close(); cout<<"\n CREATED SUCCESSFULLY."<<endl; cout<<"\n"; system("pause"); return; } } void new_user_registration(){ string pass; //variable to store admin password enterd by the user int i; //variable to control the loop int count_loop=0; //variable to count the attempts cout<<"*************WELCOME TO NEW USER REGISTRATION PAGE***********"<<endl; cout<<"\n TO CONTINUE ENTER ADMIN PASSWORD:"; cin>>pass; cin.clear(); cin.ignore(100000000,'\n'); do{ i=0; count_loop+=1; ifstream admin_file; string password; //variable to store password read from text file string user_name; //varable to store user_name read from text file admin_file.open("admin_account.txt"); admin_file>>user_name; while(admin_file){ admin_file>>password; } admin_file.close(); if(password!=pass){ i++; cout<<"\n* ENTER VALID PASSWORD:"; cin>>pass; cin.clear(); cin.ignore(100000000,'\n'); }else{ string user_name2,password2; cout<<"\n* ENTER USER NAME(USER NAME MUST BE ONE WORD) :"; //no validation has done to control user name to one word cin>>user_name2; //get user name from user cout<<"\n* ENTER PASSWORD:"; cin>>password2; //get password from user ifstream get_data; string content; bool hasContent=false; //variable to check whether text file has content or not get_data.open("Authentication.txt"); getline(get_data,content); //read content from the file while(get_data){ hasContent=true; getline(get_data,content); //read content from the file } get_data.close(); ofstream store_file; store_file.open("Authentication.txt",ios::app); if(hasContent==true){ store_file<<left<<setw(50)<<user_name2<<setw(50)<<password2<<endl; cout<<"\n CREATED SUCCESSFULLY"<<endl; store_file.close(); cout<<"\n"; system("pause"); return; }else{ store_file<<left<<setw(50)<<"User Name"<<setw(50)<<"Password"<<endl; store_file<<left<<setw(50)<<user_name2<<setw(50)<<password2<<endl; cout<<"\n CREATED SUCCESSFULLY"<<endl; store_file.close(); cout<<"\n"; system("pause"); return; } } }while(i!=0 && count_loop<2); cout<<"\n YOU ARE FAILED IN ALL 3 ATTEMPTS.SORRY"<<endl; cout<<"\n"; system("pause"); return; } void reset_password(){ //only admin can reset the password or to reset the password user must have admin permission string pass; //variable to store admin password enterd by the user int i; //variable to control the loop int count_loop=0; //variable to count the attempts cout<<"*************WELCOME TO PASSWORD RESETTING PAGE***********"<<endl; cout<<"\n TO CONTINUE ENTER ADMIN PASSWORD:"; cin>>pass; do{ i=0; count_loop+=1; ifstream admin_file; string password; //variable to store password read from text file string user_name; //varable to store user_name read from text file admin_file.open("admin_account.txt"); admin_file>>user_name; while(admin_file){ admin_file>>password; } admin_file.close(); if(password!=pass){ i++; cout<<"\n ENTER VALID PASSWORD:"; cin.clear(); cin.ignore(100000000,'\n'); cin>>pass; }else{ string file = "notepad.exe Authentication.txt"; system(file.c_str()); //open Authentication.txt on the desktop return; } }while(i!=0 && count_loop<2); cout<<"\n YOU ARE FAILED IN ALL 3 ATTEMPTS.SORRY"<<endl; cout<<"\n"; system("pause"); return; }
true
113b590d937c7188ee886762532518475883b7be
C++
kityprincess/ponder10-wordcount
/wc/wc/bst.h
UTF-8
18,287
3.515625
4
[]
no_license
/*********************************************************************** * Component: * Week 09, Binary Search Tree (BST) * Brother Helfrich, CS 235 * Author: * Shayla Nelson, Matthew Burr, Kimberly Stowe, Bryan Lopez * Summary: * The BST class creates a binary search tree and the BSTIterator * class gives a way to iterator or move through it. ************************************************************************/ #ifndef BST_H #define BST_H #include <cassert> #include <stack> #include "bnode.h" template <class T> class BST; // fwd declaration /************************************************************************* * CLASS: BSTITERATOR * Iterator for a BST **************************************************************************/ template <class T> class BSTIterator { public: friend class BST<T>; // The nodes stack should always have a NULL pointer at its head // This helps us easily tell when we've emptied the stack and it helps // in comparing the top() to the NULL (end) iterator BSTIterator() { nodes.push(NULL); } BSTIterator(BinaryNode<T> * in_node) { nodes.push(NULL); nodes.push(in_node); } // We assume that the source has a well-formed stack that has a NULL // at its head BSTIterator(std::stack<BinaryNode<T> * > in_stack) { nodes = in_stack; } BSTIterator(const BSTIterator <T> & in_source); BSTIterator <T> & operator = (const BSTIterator <T> & rhs); BSTIterator <T> & operator -- (); BSTIterator <T> & operator ++ (); bool operator == (const BSTIterator<T> & rhs); bool operator != (const BSTIterator<T> & rhs); T & operator * () const { return nodes.top()->data; } private: std::stack<BinaryNode<T> * > nodes; }; /******************************************* * BSTITERATOR :: COPY CONSTRUCTOR *******************************************/ template <class T> BSTIterator <T> ::BSTIterator(const BSTIterator <T> & in_source) { *this = in_source; } /******************************************* * BSTITERATOR :: ASSIGNMENT OPERATOR *******************************************/ template <class T> BSTIterator <T> & BSTIterator <T> :: operator = (const BSTIterator <T> & rhs) { this->nodes = rhs.nodes; return *this; } /************************************************** * BST ITERATOR :: DECREMENT PREFIX * advance by one. Note that this implementation uses * a stack of nodes to remember where we are. This stack * is called "nodes". * Author: Br. Helfrich * Performance: O(log n) though O(1) in the common case *************************************************/ template <class T> BSTIterator <T> & BSTIterator <T> :: operator -- () { // do nothing if we have nothing if (nodes.top() == NULL) return *this; // if there is a left node, take it if (nodes.top()->pLeft != NULL) { nodes.push(nodes.top()->pLeft); // there might be more right-most children while (nodes.top()->pRight) nodes.push(nodes.top()->pRight); return *this; } // there are no left children, the right are done assert(nodes.top()->pLeft == NULL); BinaryNode <T> * pSave = nodes.top(); nodes.pop(); // if the parent is the NULL, we are done! if (NULL == nodes.top()) return *this; // if we are the right-child, got to the parent. if (pSave == nodes.top()->pRight) return *this; // we are the left-child, go up as long as we are the left child! while (nodes.top() != NULL && pSave == nodes.top()->pLeft) { pSave = nodes.top(); nodes.pop(); } return *this; } /************************************************** * BST ITERATOR :: INCREMENT PREFIX * advance by one. This implementation closely * follows Bro. Helfrich's but also the guidance * from the assignment *************************************************/ template<class T> inline BSTIterator <T> & BSTIterator <T> :: operator ++() { if (NULL == nodes.top()) return *this; if (NULL != nodes.top()->pRight) { nodes.push(nodes.top()->pRight); while (nodes.top()->pLeft) nodes.push(nodes.top()->pLeft); return *this; } BinaryNode<T> * pSave = nodes.top(); nodes.pop(); if (NULL == nodes.top()) return *this; if (pSave == nodes.top()->pLeft) return *this; while (nodes.top() != NULL && nodes.top()->pRight == pSave) { pSave = nodes.top(); nodes.pop(); } return *this; } /************************************************************************ * :: EQUAL (BSTITERATOR) * Indicates whether two BSTIterators point to the same node *************************************************************************/ template <class T> bool BSTIterator<T> :: operator == (const BSTIterator<T> & rhs) { return nodes.top() == rhs.nodes.top(); } /************************************************************************ * :: NOT EQUAL (BSTITERATOR) * Indicates whether two BSTIterators point to the same node *************************************************************************/ template <class T> bool BSTIterator<T> :: operator != (const BSTIterator<T> & rhs) { return nodes.top() != rhs.nodes.top(); } /*************************************************************************** * CLASS: BST * A Binary Search Tree ****************************************************************************/ template <class T> class BST { public: BST() : root(NULL) { } ~BST() { clear(); } BST(const BST <T> & in_source) throw (const char *); BST & operator = (const BST & in_source); int size() const; bool empty() const { return root == NULL; } void clear() { deleteBinaryTree(root); root = NULL; } void insert(const T & in_value); void remove(const BSTIterator<T> & in_pItem); BSTIterator<T> find(const T & in_value) const; BSTIterator<T> begin() const; // end is simply an iterator with a NULL pointer at the top of its stack BSTIterator<T> end() { return BSTIterator <T>(NULL); } BSTIterator<T> rbegin() const; // rend is an iterator with a NULL pointer at the top of its stack BSTIterator<T> rend() { return BSTIterator <T>(NULL); } BinaryNode <T> * getRoot() const { return root; } void redBlack(BinaryNode<T> * & in_node); private: void insertInternal(const T & in_value, BinaryNode<T> * & in_subtree, BinaryNode<T> * parent); BinaryNode <T> * findLeft(BinaryNode <T> * pElement) const; BinaryNode <T> * findRight(BinaryNode <T> * pElement) const; void rotateRight(BinaryNode<T> * in_node); void rotateLeft(BinaryNode<T> * in_node); BinaryNode <T> * copy(BinaryNode <T> * pElement); BinaryNode <T> * root; }; /******************************************* * BST :: COPY CONSTRUCTOR *******************************************/ template <class T> BST <T> :: BST(const BST <T> & in_source) throw (const char *) { this->root = copy(in_source.root); } /******************************************* * BST :: ASSIGNMENT OPERATOR *******************************************/ template <class T> BST<T> & BST<T> :: operator = (const BST & in_source) { this->root = copy(in_source.root); return *this; } /***************************************** * BST:: SIZE * Number of elements in binary search tree. *****************************************/ template <class T> int BST<T> :: size() const { // no elements in tree if (root == NULL) return 0; // add root and any subtrees int size = 1; if (root->pLeft) size += root->pLeft->size(); if (root->pRight) size += root->pRight->size(); return size; } /************************************************** * BST :: INSERT * Adds a new value to the BST in the appropriate * spot. * Note: DOES NOT ATTEMPT TO BALANCE THE TREE *************************************************/ template<class T> void BST<T> :: insert(const T & in_value) { insertInternal(in_value, root, NULL); } /************************************************** * BST :: REMOVE * Remove a value from the BST and adjust tree. *************************************************/ template<class T> void BST<T> :: remove(const BSTIterator<T> & in_pItem) { BinaryNode <T> * node = in_pItem.nodes.top(); // No item to remove if (!node) { return; } //Case where there are 2 children if (node->pLeft != NULL && node->pRight != NULL) { // find the in-order successor BinaryNode <T> * successor = node->pRight; while (successor->pLeft != NULL) { successor = successor->pLeft; } node->data = successor->data; node = successor; } // Case where there are no children or 1 child BinaryNode <T> * subtree = node->pLeft; if (subtree == NULL) subtree = node->pRight; if (node->pParent == NULL) root = subtree; else if (node->pParent->pLeft == node) node->pParent->pLeft = subtree; else node->pParent->pRight = subtree; delete node; } /************************************************** * BST :: FIND * Finds the data by going through the tree *************************************************/ template <class T> BSTIterator<T> BST<T> :: find(const T & in_value) const { BinaryNode<T> * result = root; while (result != NULL && in_value != result->data) { if (in_value < result->data) { result = result->pLeft; } else result = result->pRight; } return BSTIterator<T>(result); } /************************************************** * BST :: BEGIN * Returns an iterator to the leftmost element in the list *************************************************/ template <class T> BSTIterator<T> BST<T> :: begin() const { // Per the guidance in the assignment, it is best // if the iterator already has a stack with the nodes // from the left-most element to the root of the tree std::stack<BinaryNode<T> *> temp; // We push a NULL at the head of the stack so that // we know when we've reached the end temp.push(NULL); // Now, we push all the nodes from the root down // to the left-most node BinaryNode<T> * node = root; while (NULL != node) { temp.push(node); node = node->pLeft; } // We now have a stack where the top() is the left-most // node of our tree and the nodes below it proceed up // to the root. We build an iterator from this stack return BSTIterator<T>(temp); } /************************************************** * BST :: RBEGIN * Returns an iterator to the rightmost element in the list *************************************************/ template <class T> BSTIterator<T> BST<T> :: rbegin() const { // This works the same as the BEGIN function // except that here we want to build the stack // from the root to the rightmost node std::stack<BinaryNode<T> *> temp; temp.push(NULL); BinaryNode<T> * node = root; while (NULL != node) { temp.push(node); node = node->pRight; } return BSTIterator<T>(temp); } /************************************************** * BST :: INSERTINTERNAL * Implements a recursive algorithm to insert a * binary node in the right spot * Note: DOES NOT ATTEMPT TO BALANCE THE TREE *************************************************/ template<class T> void BST<T> :: insertInternal(const T & in_value, BinaryNode<T> * & in_subtree, BinaryNode<T> * parent) { // Quick clean up of 4 node quad-nodes as we walk down the tree if (NULL != in_subtree && in_subtree->pLeft && in_subtree->pRight) { in_subtree->pRight->isRed = in_subtree->pLeft->isRed = false; // And if we're not the root, we should be red (if we're a quad node) if (in_subtree->pParent) in_subtree->isRed = true; } if (NULL == in_subtree) { try { in_subtree = new BinaryNode <T>(in_value); in_subtree->pParent = parent; redBlack(in_subtree); } catch (std::bad_alloc ex) { throw "ERROR: Unable to allocate a node"; } } else if (in_value <= in_subtree->data) insertInternal(in_value, in_subtree->pLeft, in_subtree); else if (in_value > in_subtree->data) insertInternal(in_value, in_subtree->pRight, in_subtree); else return; } /************************************************** * BST :: REDBLACK * Balances the tree. This follows the algorithm * laid out by Bro. Jones, with some small changes * to make it easier to read and understand *************************************************/ template<class T> void BST<T> :: redBlack(BinaryNode<T> * & in_node) { // create pointers to make coding simpler // pointer for new node's parent BinaryNode <T> * parent = in_node->pParent; // pg 219 // case 1 - no parent, in_node is root // set node to black and we're done if (!parent) { in_node->isRed = false; return; } // case 2 - parent is black // do nothing if (!parent->isRed) { return; } // if we get this far, we know the parent is not null // so we don't need to do checks on that // pointer for new node's grandparent BinaryNode <T> * granny = parent->pParent; BinaryNode <T> * greatGrandpa = NULL; if (granny != NULL) greatGrandpa = granny->pParent; // pointer for new node's aunt BinaryNode <T> * aunt = NULL; if (granny != NULL && granny->isLeftChild(parent)) aunt = granny->pRight; else if (granny != NULL && granny->isRightChild(parent)) aunt = granny->pLeft; // pointer for new node's sibling BinaryNode <T> * sibling = NULL; if (parent != NULL && parent->isLeftChild(in_node)) sibling = parent->pRight; else if (parent != NULL && parent->isRightChild(in_node)) sibling = parent->pLeft; assert(granny != NULL); assert(!granny->isRed); // if granny is red, we violate red-red! // case 3 - parent is red, aunt is red or na, gp is black // change gp to red, parent & aunt to black if (aunt != NULL && aunt->isRed) { granny->isRed = true; parent->isRed = false; aunt->isRed = false; redBlack(granny); return; } // Now we move into cases where we need to rotate assert(parent->isRed && !granny->isRed && (aunt == NULL || !aunt->isRed)); // case 4.1: the chain is left-left // for this case, we need to do a right rotation if (parent->isLeftChild(in_node) && granny->isLeftChild(parent)) { assert(granny->isRightChild(aunt)); assert(in_node->isRed); rotateRight(granny); } // case 4.2 else if (parent->isRightChild(in_node) && granny->isRightChild(parent)) { assert(!granny->isRed); assert(granny->isLeftChild(aunt)); rotateLeft(granny); } // case 4.4 else if (parent->isLeftChild(in_node) && granny->isRightChild(parent)) { assert(granny->isLeftChild(aunt)); assert(parent->isRightChild(sibling)); rotateRight(parent); rotateLeft(granny); } // case 4.3 else if (parent->isRightChild(in_node) && granny->isLeftChild(parent)) { assert(granny->isRightChild(aunt)); assert(parent->isLeftChild(sibling)); assert(parent->isRed); rotateLeft(parent); rotateRight(granny); } } /************************************************** * BST :: FINDLEFT * Finds the leftmost data element. *************************************************/ template <class T> BinaryNode <T> * BST <T> ::findLeft(BinaryNode <T> * pElement) const { BinaryNode <T> * tempLeft = NULL; if (pElement != 0) { findLeft(pElement->pLeft); tempLeft = pElement; } return tempLeft; } /************************************************** * BST :: FINDRIGHT * Finds the rightmost data element. *************************************************/ template <class T> BinaryNode <T> * BST<T> :: findRight(BinaryNode <T> * pElement) const { BinaryNode <T> * tempRight = NULL; if (pElement != 0) { findRight(pElement->pRight); tempRight = pElement; } return tempRight; } /******************************************************* * BST:: ROTATERIGHT * Rotates a node right in the tree ********************************************************/ template<class T> inline void BST<T>::rotateRight(BinaryNode<T>* in_node) { assert(in_node); if (!in_node) return; assert(in_node->pLeft); BinaryNode<T> * left = in_node->pLeft; in_node->pLeft = left->pRight; left->pRight = in_node; left->isRed = false; in_node->isRed = true; if (!in_node->pParent) // This WAS the root root = left; else if (in_node->pParent->isLeftChild(in_node)) in_node->pParent->pLeft = left; else in_node->pParent->pRight = left; left->pParent = in_node->pParent; in_node->pParent = left; assert(left->pRight == in_node); } /************************************************************* * BST:: ROTATELEFT * Rotate a node left in the tree **************************************************************/ template<class T> inline void BST<T>::rotateLeft(BinaryNode<T>* in_node) { assert(in_node); if (!in_node) return; assert(in_node->pRight); BinaryNode<T> * right = in_node->pRight; in_node->pRight = right->pLeft; right->pLeft = in_node; right->isRed = false; in_node->isRed = true; if (!in_node->pParent) // This WAS the root root = right; else if (in_node->pParent->isLeftChild(in_node)) in_node->pParent->pLeft = right; else in_node->pParent->pRight = right; right->pParent = in_node->pParent; in_node->pParent = right; assert(right->pLeft == in_node); } /*********************************************************************** * BST :: COPY * Copies over the elements in a tree ***********************************************************************/ template <class T> BinaryNode<T> * BST<T> :: copy(BinaryNode <T> * pElement) { if (pElement == NULL) { return pElement; } BinaryNode <T> * newNode; try { newNode = new BinaryNode <T>(pElement->data); newNode->pLeft = copy(pElement->pLeft); newNode->pRight = copy(pElement->pRight); } catch (std::bad_alloc) { throw "ERROR: Unable to allocate a node"; } return newNode; } #endif // BST_H
true
0e40816bf7304edee39af97e8f2b2e296d38266b
C++
DavidAStevenson/extendible-hashing
/test/ehfbucket_gtest.cc
UTF-8
2,593
2.765625
3
[]
no_license
#include "gtest/gtest.h" #include "ehfconsts.h" #include "ehfbucket.h" #include <fcntl.h> TEST(EHFBucketConstruction, Simple) { // TODO Interesting thing here is I need to pass a file handle // This is bad from perspective of testing this thing // Perhaps better design would be to abstract a file handle into an object, // and construct the EHFBucket with mock instances of the abstract file handler object // This way enable unit testing without bringing the real file system into it... // Maybe GMock is useful for that? int fd = open("ehfbucket.gtest", O_CREAT | O_TRUNC | O_RDWR, 0600); EHFBucket* b = new EHFBucket(fd, 0); ASSERT_EQ(b->NumOfRecs(), 0); ASSERT_EQ(b->Depth(), 1); delete b; b = nullptr; close(fd); } TEST(EHFBucketConstruction, InitialWrite) { int fd = open("ehfbucket.gtest", O_CREAT | O_TRUNC | O_RDWR, 0600); EHFBucket* b = new EHFBucket(fd, 0, 1); ASSERT_EQ(b->Write(), EHF_WROTEOK); b->ChangeAddress(1); ASSERT_EQ(b->Write(), EHF_WROTEOK); delete b; b = nullptr; close(fd); } TEST(EHFBucketConstruction, ExistingBucketRead) { int fd = open("ehfbucket.gtest", O_RDWR); EHFBucket* b = new EHFBucket(fd, 0); ASSERT_EQ(b->Read(), EHF_READOK); delete b; b = nullptr; close(fd); } // TODO gtest teardown? don't want to leave the test files sitting around TEST(EHFBucketUsage, AddToEmptyBucketRetrieveThenDelete) { // TODO Better to create test file in some kind of test setup step int fd = open("ehfbucket.gtest", O_RDWR); EHFBucket* b = new EHFBucket(fd, 0); char key[IDSIZE+1]; strcpy(key, "148000"); char record_in[RECORDSIZE+1]; strcpy(record_in, "148000A primer in data reduction : aEhrenberg, A. SQA276.12 E33"); ASSERT_EQ(b->NumOfRecs(), 0); ASSERT_EQ(b->Add(key, record_in), EHF_INSERTED); ASSERT_EQ(b->NumOfRecs(), 1); ASSERT_EQ(b->RecordPosition(key), 0); { char record_out[RECORDSIZE+1]; ASSERT_EQ(b->Retrieve(key, record_out), EHF_RETRIEVED); ASSERT_EQ(strncmp(record_in, record_out, RECORDSIZE+1), 0); } { char key_out[IDSIZE+1]; char record_out[RECORDSIZE+1]; b->RetrieveRecAtIndex(0, key_out, record_out); ASSERT_EQ(strncmp(key, key_out, IDSIZE+1), 0); ASSERT_EQ(strncmp(record_in, record_out, RECORDSIZE+1), 0); } ASSERT_EQ(b->Add(key, record_in), EHF_ALREADY_PRESENT); ASSERT_EQ(b->Delete(key), EHF_DELETED); { char record_out[RECORDSIZE+1]; ASSERT_EQ(b->Retrieve(key, record_out), EHF_NOT_PRESENT); } } // TODO tests to max out a bucket // TODO test writing / reading a maxed out bucket from disk
true
1bd32fc9c34bbc1d8246482fee4df619eab7d9fd
C++
Lixin-SCUT/cpp-primer
/chapter16/homework16.50.cpp
UTF-8
759
2.6875
3
[]
no_license
#pragma warning(disable:4996) #include <iostream> #include<vector> #include<string> #include<list> #include<algorithm> #include<numeric> #include<functional> #include<iterator> #include<fstream> #include<map> #include<set> #include<unordered_map> #include<sstream> #include<memory> #include<utility> using namespace std; template <typename T> void f(T) { cout << "f(T)" << endl; } template <typename T> void f(const T*) { cout << "f(const T*)" << endl; } template <typename T> void g(T) { cout << "g(T)" << endl; } template <typename T> void g(T*) { cout << "g(T*)" << endl; } int main() { int i = 42, *p = &i; const int ci = 0, *p2 = &ci; g(42); g(p); g(ci); g(p2); f(42); f(p); f(ci); f(p2); }
true
80793df2aa9268d7917cefe2b68d704378310444
C++
spurscoder/forTest
/src/cpp/2016-11-20/__Coding 29 Combinations.cpp
UTF-8
1,092
3.890625
4
[ "MIT" ]
permissive
/** Description: Combinations Given two integers n and k, return all possible Combinations of k numbers out of 1...n For example, if n = 4 and k = 2, a solution is: [[2,4],[2,3],[3,4],[1,2],[1,3],[1,4]] Tags: Backtracking, Array */ class Solution { public: /** * @param n: Given the range of numbers * @param k: Given the numbers of combinations * @return: All the combinations of k numbers out of 1..n */ vector<vector<int> > combine(int n, int k) { // write your code here vector<vector<int> > results; vector<int> temp; if (k == 0 || n == 0) return results; backTracking(results, temp, 1, n, k); return results; } void backTracking(vector<vector<int> > &results, vector<int> &temp, int cur, int n, int left) { if (left == 0) { results.push_back(temp); return; } for (int i = cur; i <= n; i++) { temp.push_back(i); backTracking(results, temp, i+1, n, left-1); temp.pop_back(); } } };
true
355a0165c1fc071138333c1e5c7feae2240f640a
C++
emifervi/POO
/ClassRoom/main.cpp
UTF-8
2,201
4
4
[]
no_license
/** * The program allows the user to give a class room a name, a room number where the class will be taken, a capacity of students and allows the user to sign up students for the class. * Author: Emilio Fernando Alonso Villa A00959385. * Date: January 31st, 2018 */ #include <iostream> #include <string> using namespace std; // Declare header for class to be used. #include "Room.h" int main() { // Declare variables. string name; int roomNum, capacity, students = 0; char cOption; // Receive input for name, room number and capacity and pass it to the object of class Room. cout << "+ What's the name of the class?\n"; getline(cin, name); cout << "\n+ In which room?\n"; cin >> roomNum; cout << "\n+ How many students can sign up for this class ?\n"; cin >> capacity; // Declare object of class room with variable to initialize. Room classRoom(capacity, name, roomNum); do{ // Tell the user the capacity of the room in the class and ask how many students they want to sign up. cout << "\n+ There are " << classRoom.getCapacity() - classRoom.getSignedUp() << " available seats to sign students up in class " << classRoom.getClassName() << endl; do{ cout << "How many students do you want to sign up? "; cin >> students; }while (students <= 0); // If possible sing students to the class, if not, tell user that it is not possible. if (students <= classRoom.getCapacity() - classRoom.getSignedUp()){ classRoom.singStudents(students); } else{ cout << "Not enough seats available. \n"; } // If there are still available seats ask the user if they want to sign up more. // If there are no more seats, end tell the user and end program. if(classRoom.getSignedUp() < classRoom.getCapacity()){ cout << "\n+ Do you want to add more ? (y/n) "; cin >> cOption; } else{ cout << "\n The class is full already.\n"; cOption = 'n'; } } while (tolower(cOption) != 'n'); return 0; }
true
d8876aa96f841f851efbdc9ee0ed63d0c6ccf7d1
C++
PengJiaqiao/CampusRecruitment_Diary
/百度2016实习生真题/乘法表.cpp
UTF-8
1,084
2.984375
3
[]
no_license
/* https://exercise.acmcoder.com/online/online_judge_ques?ques_id=3819&konwledgeId=40 */ #include <iostream> #include <vector> #include <algorithm> #include <math.h> using namespace std; long long int GetCntOfNoGreater(long long int n, long long int m, long long int target) { long long int res = 0; for (int i = 1; i <= n; ++i) res += min(m, target / i); return res; } int main() { long long int n, m, k; cin >> n >> m >> k; long long int low = 1, high = n * m; long long int mid = (low + high) / 2; long long int res = 0; while (1) { long long int tmp = GetCntOfNoGreater(n, m, mid); if (tmp == k) { res = mid; break; } else if (tmp > k) { if (GetCntOfNoGreater(n, m, mid - 1) < k) { res = mid; break; } else high = mid - 1; } else low = mid + 1; mid = low + (high - low) / 2; } cout << res << endl; return 0; }
true
ee8771879c6ce63c61a220878b636134ae69c1a5
C++
euyuil/icpc-training-solutions
/usaco/1-1-ride.cc
UTF-8
560
3.390625
3
[]
no_license
/* ID: 31415926 LANG: C++ TASK: ride */ #include <cstdio> #include <string> #include <cstdlib> #include <iostream> using namespace std; long prodmod47(const string &str) { long prod = 1; for (size_t i = 0; i < str.size(); ++i) prod *= (str[i] - 'A' + 1); return prod % 47; } int main() { freopen("ride.in", "r", stdin); freopen("ride.out", "w", stdout); string a, b; cin >> a >> b; if (prodmod47(a) == prodmod47(b)) cout << "GO" << endl; else cout << "STAY" << endl; return EXIT_SUCCESS; }
true
57abda389444c7279943cb9bd28449e220174fc5
C++
BriskoCube/Teaching-HEIGVD-GEN-Labo5
/src/main/Rental.h
UTF-8
527
2.625
3
[]
no_license
// // Created by julien on 07.06.19. // #ifndef GEN_LABO5_RENTAL_H #define GEN_LABO5_RENTAL_H #include "AbstractRental.h" class Rental : public AbstractRental { public: Rental(std::shared_ptr<AbstractMovie> movie, int daysRented); int getDaysRented() const; AbstractMovie* getMovie() const; static std::shared_ptr<AbstractRental> newRental(std::shared_ptr<AbstractMovie> movie, int daysRented); private: std::shared_ptr<AbstractMovie> _movie; int _daysRented; }; #endif //GEN_LABO5_RENTAL_H
true
039e5c6b4de0821efb81b85f38d78ced815a3628
C++
ryanvolum/CS278-GitHub-Repo
/Desktop/Fall 2013/Programming Languages/sudoku/sudoku/Sudoku.h
UTF-8
1,086
3.0625
3
[]
no_license
Name: Ryan Volum VUnet ID: volumrh e-mail: ryan.h.volum@vanderbilt.edu Class: CS270 Honor Code: I promise that I neither gave nor received help on this assignment #include <iostream> #include <string> #include <set> using namespace std; #ifndef Project1_Sudoku_h #define Project1_Sudoku_h class Sudoku{ private: int puzzle[9][9]; set<int> possibilities[9][9]; set<int> rowPossiblities[9]; set<int> columnPossibilities[9]; set<int> boxPossibilities[9]; bool possible [9][9][9]; void initializeSets(); void loadPossibilities(); public: //Default constructor. Should initialize the object with an empty puzzle (81 zeroes). Sudoku(); //Reinitializes the object with a new puzzle from the specified file. void loadFromFile(string filename); //The entry point for your solver. Returns true if a solution was found, otherwise returns false bool solve(); //Prints the current puzzle contents to the screen in a nicely formatted manner. void print() const; //Determines if two puzzles are equal. bool equals(const Sudoku &other) const; }; #endif
true
de43921c04ed5a3902cbbe4e676d6a5c0787f559
C++
cesarl/Algorithm-Course
/part1/quick_find/UF.cpp
UTF-8
370
2.828125
3
[]
no_license
#include "UF.hh" template <int N> void UF<N>::setUnion(int p, int q) { int pid = this->list_[p]; int qid = this->list_[q]; for (int i = 0; i < this->size_; ++i) { if (this->list_[i] == pid) { this->list_[i] = qid; } } } template <int N> bool UF<N>::isConnected(int p, int q) { return (this->list_[p] == this->list_[q]); }
true
42f0bae7c771a3818736382139101062a8f3a379
C++
wolski-m/Smart-D-LED-API
/Patterns/color.h
UTF-8
526
2.671875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
class colorClass { protected: public: // RGB Color uint8_t red; uint8_t green; uint8_t blue; // HSV Color uint8_t hue = 215; uint8_t saturation = 255; uint8_t value = 255; void setHSV() { for (int i = 0; i <= dled.num_leds; i++) { for (int i = 0; i <= dled.num_leds; i++) { dled.leds[i] = CHSV(hue, saturation, value); } } } void setRGB() { for (int i = 0; i <= dled.num_leds; i++) { dled.leds[i] = CRGB(red, green, blue); } } }; colorClass color;
true
ef13060eba0eac626947670a1081a7280ea1ab7d
C++
iammarajul/competitive_programming
/Codeforecs/1017A.cpp
UTF-8
414
2.6875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int arr[n+1]; int m; for(int i=0;i<n;i++) { int a,b,c,d; cin>>a>>b>>c>>d; if(i==0) m=a+b+c+d; arr[i]=a+b+c+d; } sort(arr,arr+n,greater<int>()); for(int i=0;i<n;i++) { if(arr[i]==m) { cout<<i+1<<endl; break; } } }
true
951ddfb2b5f1d47b33a024360856d414f95fa2e8
C++
JakeEMuller/CS3421-CompOrg
/CPUSIM/CS3421_emul.cpp
UTF-8
4,955
2.765625
3
[]
no_license
#include <iostream> #include <stdio.h> #include <string.h> #include <stdlib.h> #include "Cpu.h" #include "Memory.h" #include "clock.h" using namespace std; int main(int argc, char** argv) { if(argc <= 1){ return 0; //for testing purposes } //get the name of the file from the command line char* fileName = argv[1]; //create the devices //memory Memory memory; //memory should be initalized on memory create command memory.setup(); //IO setup InOut IO; IO.setup(&memory); //instruction memory InstructMem imemory; imemory.setup(); //Cache Cache cache; cache.setup(&memory); //cpu Cpu cpu; cpu.reset(&memory, &imemory, &cache); //clock Clock clock; clock.reset(&memory, &cpu, &imemory, &IO); FILE* inputFile = fopen(fileName, "r"); int junk = 0; //because input files should always be perfect fscanf feedback can be ignored char command[30]; //thirty characters should be enought for the numbers char secondCommand[30]; unsigned int hexValue = 0x00; unsigned char cpuReg = 'X'; while ( fscanf( inputFile, "%s %s" , command, secondCommand ) != EOF ) { strcat(command, " "); // parse the two words strcat(command, secondCommand); //printf("command: %s \n", command); //check clock functions if (!strcmp("clock reset", command)) { clock.reset(); //printf("clock reset \n"); } else if (!strcmp("clock tick", command)) { int ticks = 0; junk = fscanf(inputFile, "%d", &ticks); clock.tick(ticks); //printf("clock tick \n"); } else if (!strcmp("clock dump", command)) { clock.dump(); //printf("clock dump \n"); } else //check memory functions if (!strcmp("memory create", command)) { junk = fscanf(inputFile, "%x", &hexValue); memory.create(hexValue); //printf("memory create \n"); } else if (!strcmp("memory reset", command)) { memory.reset(); //printf("memory reset \n"); } else if (!strcmp("memory dump", command)) { unsigned int count = 0x00; junk = fscanf(inputFile ,"%x", &hexValue); junk = fscanf(inputFile, "%x", &count); memory.dump(hexValue, count); //printf("memory dump \n"); } else if (!strcmp("memory set", command)) { junk = fscanf(inputFile, "%x", &hexValue); unsigned int count = 0x00; junk = fscanf(inputFile, "%x", &count); unsigned char* byteArray = (unsigned char*) malloc(count * sizeof(unsigned char)); unsigned int temp; for(unsigned int i = 0; i < count; i++){ junk = fscanf(inputFile, "%x", &temp); byteArray[i] = (unsigned char)temp; //printf( "%x ", byteArray[i]); } memory.set(hexValue, count, byteArray); //printf("memory set \n"); free(byteArray); } else //check cpu functions if (!strcmp("cpu reset", command)) { cpu.reset(); //printf("cpu reset \n"); } else if (!strcmp("cpu set", command)) { junk = fscanf(inputFile, "%s ", command); junk = fscanf(inputFile, "%c", &cpuReg); //special condition for PC if (cpuReg == 'P') { junk = fscanf(inputFile, "%c", &cpuReg); junk = fscanf(inputFile, "%x", &hexValue); cpu.setReg('P', hexValue); } else { junk = fscanf(inputFile, "%c", &cpuReg); junk = fscanf(inputFile, "%x", &hexValue); cpu.setReg(cpuReg, hexValue); } //printf("cpu set \n"); } else if (!strcmp("cpu dump", command)) { cpu.dump(); //printf("Cpu dump \n"); }else //instruction Memory commands if(!strcmp("imemory create", command)){ junk = fscanf(inputFile, "%x", &hexValue); imemory.create(hexValue); } else if(!strcmp("imemory reset", command)){ imemory.reset(); } else if(!strcmp("imemory dump", command)){ unsigned int count = 0x00; junk = fscanf(inputFile ,"%x", &hexValue); junk = fscanf(inputFile, "%x", &count); imemory.dump(hexValue, count); } else if(!strcmp("imemory set", command)){ junk = fscanf(inputFile ,"%x", &hexValue); junk = fscanf(inputFile , "%s", command); char thing[100]; junk = fscanf(inputFile , "%100s", thing); imemory.set(hexValue, thing); } else //cashe instructions if(!strcmp("cache reset", command)){ cache.reset(); }else if(!strcmp("cache on", command)){ cache.on(); }else if(!strcmp("cache off", command)){ cache.off(); }else if(!strcmp("cache dump", command)){ cache.dump(); } //IO instructions else if(!strcmp("iodev reset", command)){ IO.Reset(); }else if(!strcmp("iodev load", command)){ char IOfile[255] = "null"; //would be surprised if it exceded 255 (aka file lenght of windows) junk = fscanf(inputFile ,"%s", IOfile); IO.Load(IOfile); }else if(!strcmp("iodev dump", command)){ IO.Dump(); } } if(junk == EOF){ exit(1); } memory.kill(); //frees any allocated memory cpu.kill(); imemory.kill(); cache.kill(); }
true
762605079bfd8c8e5637e861b33b72ce486216ec
C++
david-andrew/PRS_robot
/RobotDriver/PressModule.cpp
UTF-8
5,814
2.9375
3
[ "MIT" ]
permissive
/** MIT License Copyright (c) 2019 David-Andrew Samson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PRS Fret Press Robot PressModule.cpp Purpose: Class for managing the press arm and snips on the robot @author David Samson @version 1.0 @date 2019-04-30 */ #include "PressModule.h" /** Constructor for PressModule object */ PressModule::PressModule() { //initialize the StepperModule object for the press motor (read-only public reference). Note moter rotation direction is reversed motor = new StepperModule(PIN_PRESS_PULSE, PIN_PRESS_DIRECTION, PIN_PRESS_MIN_LIMIT, PIN_PRESS_MAX_LIMIT, "press", true); //set motor speeds and acceleration motor->set_speeds(PRESS_MINIMUM_SPEED, PRESS_MEDIUM_SPEED, PRESS_MAXIMUM_SPEED); motor->set_acceleration(PRESS_ACCELERATION); //initilize the pneumatics to control the press and snips press = new PneumaticsModule(PIN_PRESS_OPEN, PIN_PRESS_CLOSE, PRESS_DEFAULT); snips = new PneumaticsModule(PIN_SNIPS_OPEN, PIN_SNIPS_CLOSE, SNIPS_DEFAULT, true, false); //one of the relay's is wired normally closed instead of normally open, so invert in software //intialize the wire feed detector limit switch. Invert button because no wire should be LOW (mechanically reversed, i.e. no wire is HIGH) feed_detect = new ButtonModule(PIN_FEED_DETECT, true); } /** Wrapper to calibrate the press stepper motor step position @return int result is whether or not calibration succeeded. 0 for success, 1 for failure */ int PressModule::calibrate() { num_errors = 0; num_errors += motor->calibrate(); return check_errors(); } /** Check if any errors occured during calibration, and the module needs to be recalibrated */ int PressModule::check_errors() { if (num_errors == -1) { Serial.println("ERROR: PressModule hasn't been calibrated yet. Please calibrate before running robot"); return 1; } //check if there is wire in the feed num_errors += !has_wire(); if (num_errors > 0) { Serial.println("ERROR: PressModule encountered errors. Please ensure press is clear of debris and plugged in correctly"); } return num_errors; } /** Perform steps to press and cut a single fret into the board */ void PressModule::press_slot() { if (!has_wire()) //check if wire is still remaining { delay(500); //pause to stop slide momentum return; //return before attempting to press with no wire } motor->move_absolute(PRESS_PRESS_POSITION, true); //rotate the press arm to the position it will press the frets press->write(LOW); //lower the press arm delay(PNEUMATICS_DELAY); //wait for the press to actuate delay(PRESS_DURATION); //delay for a moment to allow the fret to be completely pressed into the slot press->write(HIGH); //raise the press delay(PNEUMATICS_DELAY); //wait for the press to raise before actuating motor->move_absolute(PRESS_SNIPS_POSITION, true); //rotate the press arm to the position the snips will cut at snips->write(HIGH); //close the snips delay(PNEUMATICS_DELAY); //wait for the pneumatics to close completely snips->write(LOW); //open the snips back up } /** Check if there is still wire in the press feed @return bool has_wire is true if there is more wire, and false if wire needs to be added */ bool PressModule::has_wire() { if (feed_detect->read(true) == HIGH) //satureate the feed limit, and then check if the fret wire is still there { return true; } else { Serial.println("ERROR: out of fret wire. Please reload more"); return false; } } /** Move the press arm to a clear position, ready to begin a new fretboard */ void PressModule::reset() { snips->write(LOW); //open the snips press->write(HIGH); //raise the press motor->move_absolute(PRESS_CLEAR_POSITION, true); //move clear and block till finished check_errors(); //check if there is still wire in the press arm } /** Return a string for the state of the press module */ String PressModule::str() { return "Press Motor Position: " + String(motor->get_current_position()) + "\nPress: " + String(press->read() == HIGH ? "RAISED" : "LOWERED") + "\nSnips: " + String(snips->read() == HIGH ? "CLOSED" : "OPEN") + "\nPress Feed: " + String(has_wire() ? "HAS WIRE" : "OUT OF WIRE"); }
true
4f9c8eb9c1172e5f5bca78ca24e5a1ebad32e4c2
C++
dariahazaparu/FMI
/Year I/Data Structures/TEMA II/exercitiu4/main.cpp
UTF-8
4,669
3.15625
3
[]
no_license
#include <iostream> #include <fstream> using namespace std; ifstream f("exercitiu4matrice.txt"); struct coada{ int info; coada * prev, * next; }*pointer_global_prim_element, *pointer_global_ultim_element; void push_right( int x ) { coada * s = new coada; if (!pointer_global_prim_element) { pointer_global_ultim_element = s; pointer_global_ultim_element->info = x; pointer_global_ultim_element->next = NULL; pointer_global_ultim_element->prev = NULL; pointer_global_prim_element = pointer_global_ultim_element; } else if(pointer_global_prim_element == pointer_global_ultim_element) { pointer_global_prim_element->next = s; s->prev = pointer_global_prim_element; s->info = x; s->next = NULL; pointer_global_ultim_element = s; } else { pointer_global_ultim_element->next = s; s->info = x; s->prev = pointer_global_ultim_element; s-> next = NULL; pointer_global_ultim_element = s; } } void push_left( int x ) { if (!pointer_global_prim_element) { coada * s = new coada; pointer_global_prim_element = s; pointer_global_prim_element->info = x; pointer_global_prim_element->next = NULL; pointer_global_prim_element->prev = NULL; pointer_global_ultim_element = pointer_global_prim_element; } else if(pointer_global_prim_element == pointer_global_ultim_element) { coada * s = new coada; pointer_global_prim_element->prev = s; s->next = pointer_global_prim_element; s->info = x; s->prev = NULL; pointer_global_prim_element = s; } else { coada * s = new coada; pointer_global_prim_element->prev = s; s->next = pointer_global_prim_element; s->info = x; s->prev = NULL; pointer_global_prim_element = s; } } int pop_left() { if (!pointer_global_prim_element) { // cout<<"coada goala."; return -1; } else if(pointer_global_prim_element == pointer_global_ultim_element) { int q = pointer_global_prim_element->info; coada * s = pointer_global_prim_element; pointer_global_prim_element = NULL; pointer_global_prim_element = NULL; delete s; return q; } else { int q = pointer_global_prim_element->info; coada * s = pointer_global_prim_element; pointer_global_prim_element = s->next; delete s; pointer_global_prim_element->prev = NULL; return q; } } int pop_right() { if (!pointer_global_prim_element) { // cout<<"coada goala."; return -1; } else if(pointer_global_prim_element == pointer_global_ultim_element) { int q = pointer_global_prim_element->info; coada * s = pointer_global_prim_element; pointer_global_prim_element = NULL; pointer_global_prim_element = NULL; delete s; return q; } else { int q = pointer_global_ultim_element->info; coada * s = pointer_global_ultim_element; pointer_global_ultim_element = s->prev; delete s; pointer_global_ultim_element->next = NULL; return q; } } void afisare_stanga() { cout<<endl; coada * s = pointer_global_prim_element; while (s){ cout<<s->info<<" "; s = s->next; } } int main() { int m, counter=2; f >> m; int a[m+1][m+1],M[m+1][m+1]; for ( auto i=0; i<m; i++ ) for ( auto j=0; j<m; j++ ) M[i][j] = 0; for ( auto i=0; i<m; i++ ) for ( auto j=0; j<m; j++ ) f >> a[i][j]; for ( auto i=0; i<m; i++ ) for ( auto j=0; j<m; j++ ) { if ( a[i][j] == 1 ) { push_right(i);push_right(j); while ( pointer_global_prim_element ) { int x = pop_left(); int y = pop_left(); M[x][y] = counter; a[x][y] = 0; if ( a[x-1][y] == 1 && x-1 >= 0 ){ push_right(x-1);push_right(y); } if ( a[x][y-1] == 1 && y-1 >= 0 ){ push_right(x);push_right(y-1); } if ( a[x+1][y] == 1 && x+1 < m ){ push_right(x+1);push_right(y); } if ( a[x][y+1] == 1 && y+1 < m ){ push_right(x);push_right(y+1); } } counter++; } } for ( auto i=0; i<m; i++ ){ for ( auto j=0; j<m; j++ ) cout<<M[i][j]<<" "; cout<<endl; } return 0; }
true
e7596646a4ab5636da3c506cb12912d6823867d3
C++
AryanRaj315/CompetitiveProgrammingSolutions
/RandomDFSExperiment.cpp
UTF-8
456
2.796875
3
[]
no_license
#include<iostream> #include<vector> using namespace std; const int N = 1e6+5; vector<int> g[N]; bool vis[N]; void dfs(int u){ for(int v: g[u]){ if(vis[v]) continue; else dfs(v); } } int main(){ int n, m, u, v; cin >> n>> m >> u >> v; while(m--){ cin >> u >> v; g[u].push_back(v); g[v].push_back(u); } dfs(1); if(vis[6]) cout << "Visited"; else cout << "Oops.."; return 0; }
true
0acfb89fd5d02af9fff197de2397203aca568d5d
C++
frazierde12/Sample-C-Code-for-Classes
/CSC1180/Complex.h
UTF-8
374
2.890625
3
[]
no_license
#ifndef COMPLEX_H #define COMPLEX_H class Complex { public: // Constructor(s) Complex(int, int); // Accessors int getReal()const; int getImaginary()const; // Mutators void setReal(int); void setImaginary(int); std::string printComplex(); Complex operator+(Complex); private: // member data int realPart; int imaginaryPart; }; #endif
true
bae522d3c627d13eb217e1e87d23a44d4d5c9f35
C++
kinetickansra/algorithms-in-C-Cplusplus-Java-Python-JavaScript
/Algorithms/searching/C++/binary_search.cpp
UTF-8
1,633
4.5625
5
[ "MIT" ]
permissive
/* Binary Search ----------- A searching algorithm that finds the position of a target value within a sorted array. Time complexity --------------- O(log(N)), where N is the number of elements in the array. Space complexity ---------------- O(1). */ #include <iostream> #include <vector> using namespace std; int binarySearch(const int value, const vector<int>& sortedVect, const int low, const int high) { int mid = (low + high) / 2; if (value == sortedVect[mid]) return mid; else if (low <= high) { if (value < sortedVect[mid]) { // value must be between indices low and mid-1, if exists return binarySearch(value, sortedVect, low, mid-1); } else if (value > sortedVect[mid]) { // value must be between indices mid-1 and high, if exists return binarySearch(value, sortedVect, mid+1, high); } } return -1; } int main() { int value; cout << "Enter the value to search for : "; cin >> value; int size; cout << "Enter the input size : "; cin >> size; vector<int> inputVect(size); // supposedly sorted values cout << "Enter " << size << " integers in ascending order :\n"; for (int& val: inputVect) cin >> val; int index = binarySearch(value, inputVect, 0, size-1); cout << "\n"; if (index != -1) cout << "Found " << value << " at position " << (index + 1) << "\n"; else cout << "Either " << value << " is not present among the input values, or the values aren\'t sorted\n"; return 0; }
true
65088e3caff9cfda85c02a0d6c6c8ef54ed73a71
C++
ppershing/mosaic-from-images
/trunk/src/ThumbnailStack.cpp
UTF-8
2,075
2.546875
3
[]
no_license
// created and maintained by ppershing // please report any bug or suggestion to ppershing<>fks<>sk #include "ThumbnailStack.h" #include <SDL/SDL.h> #include <SDL/SDL_image.h> #include <SDL/SDL_rotozoom.h> #include <string> #include "MyAssert.h" #include "Cache.h" ThumbnailStack::ThumbnailStack(){ stack.resize(SIZE); } void ThumbnailStack::loadFromCache(CacheData& data, int minDivision){ std::string filename = data.getThumbnailFile(); SDL_Surface* tmpSurface = IMG_Load(filename.c_str()); Assert(tmpSurface, "problem with loading thumbnail "+filename); SDL_Surface* surface = shrinkSurface(tmpSurface, 1<<minDivision, 1<<minDivision); Assert(surface, "problem converting surface"); SDL_FreeSurface(tmpSurface); loadFromSurfaceInternal(surface, minDivision); SDL_FreeSurface(surface); } void ThumbnailStack::loadFromSurface(SDL_Surface* surface, int x,int y, int initialDivision) { SDL_Surface* tmpSurface = SDL_CreateRGBSurface(SDL_SWSURFACE, Cache::getTileWidth(initialDivision), Cache::getTileHeight(initialDivision), 32, 0,0,0,0); Assert(tmpSurface, ""); SDL_Rect rect; rect.x=x; rect.y=y; rect.w=Cache::getTileWidth(initialDivision); rect.h=Cache::getTileHeight(initialDivision); SDL_BlitSurface(surface, &rect, tmpSurface, NULL); loadFromSurfaceInternal(tmpSurface, initialDivision); SDL_FreeSurface(tmpSurface); } void ThumbnailStack::loadFromSurfaceInternal(SDL_Surface* surface, int initialDivision) { if (initialDivision >= SIZE) return; int w=Cache::getTileWidth(initialDivision); int h=Cache::getTileHeight(initialDivision); Assert(surface->w == w, ""); Assert(surface->h == h, ""); stack[initialDivision].loadFromSurface(surface, 0, 0, w, h); SDL_Surface* tmpSurface=shrinkSurface(surface, 2, 2); Assert(tmpSurface, ""); loadFromSurfaceInternal(tmpSurface, initialDivision+1); SDL_FreeSurface(tmpSurface); }
true
44e9464e46d428b434687e631b320e09667e7a1c
C++
chrihill/CSC375_Data-Structures
/Queue/main.cpp
UTF-8
535
3.21875
3
[]
no_license
#include <iostream> #include "Queue.h" using namespace std; int main() { Queue<int> q; q.enque(10); q.enque(20); int val; q.dequeue(val); cout << val << endl; Queue<int> q2; q2 = q; q2.enque(30); q2.peek(val); cout << val << endl; q2.dequeue(val); cout << val << endl; q2.dequeue(val); cout << val << endl; q2.dequeue(val); cout << val << endl; return 0; }
true
75e21efb9c12834d77fff422ab331db930b4bce0
C++
deepakantony/competitive_programming
/uva_online_judge/programming_paradigms/dynamic_programming/CoinChange_674.cxx
UTF-8
1,924
3.28125
3
[]
no_license
// Coin Change // Suppose there are 5 types of coins: 50-cent, 25-cent, 10-cent, 5-cent, and // 1-cent. We want to make changes with these coins for a given amount of // money. // // // For example, if we have 11 cents, then we can make changes with one 10-cent // coin and one 1-cent coin, two 5-cent coins and one 1-cent coin, one 5-cent // coin and six 1-cent coins, or eleven 1-cent coins. So there are four ways of // making changes for 11 cents with the above coins. Note that we count that // there is one way of making change for zero cent. // // // Write a program to find the total number of different ways of making changes // for any amount of money in cents. Your program should be able to handle up // to 7489 cents. // // Input // // The input file contains any number of lines, each one consisting of a number // for the amount of money in cents. // Output // // For each input line, output a line containing the number of different ways // of making changes with the above 5 types of coins. // Sample Input // // 11 // 26 // Sample Output // // 4 // 13 // // // Miguel Revilla // 2000-08-14 // #include <cstdio> #include <cstring> typedef unsigned long long ULL; int coins[] = {1, 5, 10, 25, 50}; int memo[5][7490]; int numWaysCC(int curCoinIdx, int money) { if(money == 0) return 1; if(memo[curCoinIdx][money] != -1) return memo[curCoinIdx][money]; if(curCoinIdx == 0) return memo[curCoinIdx][money] = 1; if(money < coins[curCoinIdx]) return memo[curCoinIdx][money] = numWaysCC(curCoinIdx-1, money); else return memo[curCoinIdx][money] = numWaysCC(curCoinIdx-1, money) + numWaysCC(curCoinIdx, money-coins[curCoinIdx]); } int main(int argc, char *argv[]) { int money; memset(memo, -1, sizeof memo); while(scanf(" %d", &money) != EOF) { printf("%d\n", numWaysCC(4, money)); } return 0; }
true
ff36ff4be77dcc6204b468fb72fd50bddffd8235
C++
TECHMATHEMA/Linguagem-C-_-exerc-cios-e-demais
/exercicio_lista2_1_múltiplo de 3.cpp
WINDOWS-1252
493
3.296875
3
[]
no_license
/* 5 - Escreva um algoritmo que receba um nmero e imprima uma das mensagens: mltiplo de 3 ou no mltiplo de 3.*/ #include<stdio.h> #include<conio.h> #include<math.h> #include<stdlib.h> #include<locale.h> main() { setlocale(LC_ALL, "Portuguese"); int b; printf("\n\n Escreva o nmero inteiro \n\n"); scanf("%d",&b); if (b%3==0) { printf(" O nmero mltiplo de 3 "); } else { printf(" O nmero no mltiplo de 3 "); } }
true
bfebeed9e5504a4bad0f3b851ebfab3f47fa7059
C++
lyost/d3d12_framework
/d3d12_framework/private_inc/D3D12/Textures/D3D12_TextureCube.h
UTF-8
2,919
2.8125
3
[]
no_license
#ifndef D3D12_TEXTURE_CUBE_H #define D3D12_TEXTURE_CUBE_H #include <d3d12.h> #include "Graphics/GraphicsCore.h" #include "Graphics/Textures/TextureCube.h" class D3D12_TextureCube : public TextureCube { public: /// <summary> /// Creates a D3D12 texture /// </summary> /// <param name="graphics"> /// core graphics interface /// </param> /// <param name="shader_buffer_heap"> /// shader resources descriptor heap that the texture will be accessed from /// </param> /// <param name="width"> /// width of a texture for each side of the cube in pixels /// </param> /// <param name="height"> /// height of a texture for each side of the cube in pixels /// </param> /// <param name="format"> /// texture format /// </param> /// <param name="mip_levels"> /// number of mipmap levels /// </param> /// <returns> /// D3D12 texture cube /// </returns> /// <exception cref="FrameworkException"> /// Thrown when an error is encountered /// </exception> static TextureCube* Create(const GraphicsCore& graphics, ShaderResourceDescHeap& shader_buffer_heap, UINT width, UINT height, GraphicsDataFormat format, UINT16 mip_levels); ~D3D12_TextureCube(); /// <summary> /// Retrieves the D3D12 resource /// </summary> /// <returns> /// D3D12 resource for the texture /// </returns> ID3D12Resource* GetResource() const; /// <summary> /// Retrieves the GPU address for the texture /// </summary> /// <returns> /// GPU address for the texture /// </returns> D3D12_GPU_DESCRIPTOR_HANDLE GetGPUAddr() const; /// <summary> /// Retrieves the number of mipmap levels the resource was created with /// </summary> /// <returns> /// GPU address for the texture /// </returns> UINT16 GetNumMipmapLevels() const; private: // disabled D3D12_TextureCube(); D3D12_TextureCube(const D3D12_TextureCube& cpy); D3D12_TextureCube& operator=(const D3D12_TextureCube& cpy); D3D12_TextureCube(ID3D12Resource* buffer, D3D12_GPU_DESCRIPTOR_HANDLE gpu_mem, UINT width, UINT height, GraphicsDataFormat format, UINT16 num_mip_levels); /// <summary> /// D3D12 texture resource /// </summary> ID3D12Resource* m_buffer; /// <summary> /// GPU address for the texture /// </summary> D3D12_GPU_DESCRIPTOR_HANDLE m_gpu_mem; /// <summary> /// width of a texture for each side of the cube in pixels /// <summary> UINT m_width; /// <summary> /// height of a texture for each side of the cube in pixels /// <summary> UINT m_height; /// <summary> /// texture format /// <summary> GraphicsDataFormat m_format; /// <summary> /// number of mipmap levels in the resource /// </summary> UINT16 m_num_mipmap_levels; }; #endif /* D3D12_TEXTURE_CUBE_H */
true
9ffe15d73860f6a2fc19d2a761c7f794b4d3af33
C++
nuup20/Craftman-Engine
/dqUtility/src/dqVector2i.cpp
ISO-8859-3
3,888
2.75
3
[]
no_license
#include <assert.h> #include "dqVector2.h" #include "dqVector2i.h" #include "dqPlatformMath.h" #define Math PlatformBaseMath namespace dqEngineSDK { Vector2i::Vector2i() { } Vector2i::Vector2i(DEF_INIT::E) { //TODO: Hago una evaluacin primero, o una igualacin. } Vector2i::Vector2i(const Vector2i & vec) { this->x = vec.x; this->y = vec.y; } Vector2i::Vector2i(const Vector2 & vec) { this->x = static_cast<int32>(vec.x); this->y = static_cast<int32>(vec.y); } Vector2i::Vector2i(int32 x, int32 y) { this->x = x; this->y = y; } Vector2i::~Vector2i() { } Vector2i Vector2i::operator+(const Vector2i & vec) const { return Vector2i(this->x + vec.x, this->y + vec.y); } Vector2i Vector2i::operator-(const Vector2i & vec) const { return Vector2i(this->x - vec.x, this->y - vec.y); } Vector2i Vector2i::operator*(const Vector2i & vec) const { return Vector2i(this->x * vec.x, this->y * vec.y); } Vector2i Vector2i::operator*(const float & escalar) const { int32 _esc = static_cast<int32>(escalar); return Vector2i(this->x * _esc, this->y * _esc); } Vector2i Vector2i::operator*(const int32 & escalar) const { return Vector2i(this->x * escalar, this->y * escalar); } Vector2i Vector2i::operator/(const Vector2i & vec) const { return Vector2i(static_cast<int32>(this->x / vec.x), static_cast<int32>(this->y / vec.y)); } Vector2i Vector2i::operator/(const float & divi) const { return Vector2i(static_cast<int32>(this->x / divi), static_cast<int32>(this->y / divi)); } Vector2i & Vector2i::operator+=(const Vector2i & vec) { this->x += vec.x; this->y += vec.y; return *this; } Vector2i & Vector2i::operator-=(const Vector2i & vec) { this->x -= vec.x; this->y -= vec.y; return *this; } Vector2i & Vector2i::operator*=(const Vector2i & vec) { this->x *= vec.x; this->y *= vec.y; return *this; } Vector2i & Vector2i::operator*=(const float & escalar) { int32 _esc = static_cast<int32>(escalar); this->x *= _esc; this->y *= _esc; return *this; } Vector2i & Vector2i::operator*=(const int32 & escalar) { this->x *= escalar; this->y *= escalar; return *this; } Vector2i & Vector2i::operator/=(const Vector2i & vec) { this->x = static_cast<int32>(this->x / vec.x); this->y = static_cast<int32>(this->y / vec.y); return *this; } Vector2i & Vector2i::operator/=(const float & divi) { this->x /= static_cast<int32>(divi); this->y /= static_cast<int32>(divi); return *this; } Vector2i & Vector2i::Normalize() { return *this /= Magnitude(); } int32 Vector2i::operator[](const int32 & i) const { assert(i < 2 && i > -1); return (&x)[i]; } int32 Vector2i::operator|(const Vector2i & vec) const { return (this->x * vec.x) + (this->y * vec.y); } Vector2i Vector2i::Normalized() const { return *this * Math::InvSqrt(SquareMagnitude()); } Vector2i Vector2i::CrossProduct() const { return Vector2i(this->x, -this->y); } float Vector2i::Magnitude() const { return Math::Sqrt(Math::Pow(this->x, 2) + Math::Pow(this->y, 2)); } float Vector2i::SquareMagnitude() const { return Math::Pow(static_cast<float>(this->x), 2.0f) + Math::Pow(static_cast<float>(this->y), 2.0f); } float Vector2i::RadiansBetween(const Vector2i & vec) const { return Math::Acos(static_cast<float>(*this | vec) / (this->Magnitude() * vec.Magnitude())); } float Vector2i::DegreesBetween(const Vector2i & vec) const { return this->RadiansBetween(vec) * 180.0f / Math::PI; } }
true
12469de0163177d7c5b59ad09705513232c7f821
C++
azharsid96/MovementAlgorithms
/of_v0.11.0_vs2017_release/apps/myApps/Movement Algorithms Project/AIMovementAlgorithms/AIMovementAlgorithms/src/DynamicBlendedBehavior.cpp
UTF-8
2,130
3.328125
3
[ "MIT" ]
permissive
#include "DynamicBlendedBehavior.h" DynamicBlendedBehavior::DynamicBlendedBehavior(float maxAccelerationMagnitude, float maxAngularAccelerationMagnitude) { this->maxAccelerationMagnitude = maxAccelerationMagnitude; this->maxAngularAccelerationMagnitude = maxAngularAccelerationMagnitude; } DynamicBlendedBehavior::~DynamicBlendedBehavior() { // need to destruct the weighted behaviors that are allocated for (auto it = begin(behaviors); it != end(behaviors); ++it) { weightedDynamicBehavior * weightedDynamicBehaviorPtr = *it; delete weightedDynamicBehaviorPtr; } behaviors.clear(); // clear the behaviors out } dynamicOutput DynamicBlendedBehavior::getDynamicSteering() { dynamicOutput blendedOutput = { ofVec2f::zero(), 0.0f }; // define the return variable // for each behavior, for (int i = 0; i < behaviors.size(); i++) { weightedDynamicBehavior * weightedBehavior = behaviors[i]; // get its output dynamicOutput weightedOutput = weightedBehavior->movementBehavior->getDynamicSteering(); // multiply it against its weight weightedOutput.linear *= weightedBehavior->weight; weightedOutput.angular *= weightedBehavior->weight; // add outputs blendedOutput.linear += weightedOutput.linear; blendedOutput.angular += weightedOutput.angular; } // clamp to max acceleration if (blendedOutput.linear.length() > maxAccelerationMagnitude) { blendedOutput.linear.normalize(); blendedOutput.linear *= maxAccelerationMagnitude; } // clamp to max angular acceleration if (fabs(blendedOutput.angular) > maxAngularAccelerationMagnitude) { int accelerationSign = blendedOutput.angular / abs(blendedOutput.angular); blendedOutput.angular = maxAngularAccelerationMagnitude * accelerationSign; } return blendedOutput; } void DynamicBlendedBehavior::addWeightedDynamicBehavior(DynamicBehavior * behavior, float behaviorWeight) { weightedDynamicBehavior * newWeightedDynamicBehavior = new weightedDynamicBehavior(); newWeightedDynamicBehavior->movementBehavior = behavior; newWeightedDynamicBehavior->weight = behaviorWeight; behaviors.push_back(newWeightedDynamicBehavior); }
true
5de28a8da844a29c731c76e9dcfc3981578b48de
C++
ysripath/Practice
/Spring2018/printBalancedParanthesis.cpp
UTF-8
2,952
3.609375
4
[]
no_license
#include <iostream> #include <string> #include <algorithm> #include <vector> #include <stack> using namespace std; bool isValid(string s) { int l = s.length(); if (l < 2) return false; stack<char> bracketStack; for (int i = 0; i < l ; i++) { char c = s[i]; switch (c) { case '(': { bracketStack.push(c); } break; case ')': { if (bracketStack.empty()) return false; if (bracketStack.top() == '(') { bracketStack.pop(); } else return false; } break; case '[': { bracketStack.push(c); } break; case ']': { if (bracketStack.empty()) return false; if (bracketStack.top() == '[') { bracketStack.pop(); } else return false; } break; case '{': { bracketStack.push(c); } break; case '}': { if (bracketStack.empty()) return false; if (bracketStack.top() == '{') { bracketStack.pop(); } else return false; } break; default: return false; } } if (bracketStack.empty()) return true; else return false; } void permute(string str, vector<string> &vec) { sort(str.begin(), str.end()); do { if (isValid(str)) { vec.push_back(str); } } while (next_permutation(str.begin(), str.end())); } vector<string> generateParenthesis(int n) { vector<string> validStrings; if (n == 0) { validStrings.push_back(""); return validStrings; } string mainString = ""; int i; for (i = 0; i < n; i++) mainString += '('; for ( i; i < 2*n; i++) mainString += ')'; //sort(mainString.begin(), mainString.end()); permute(mainString, validStrings); return validStrings; } int main() { cout<<"Enter n value\n"; int N; cin >> N; vector<string> vec = generateParenthesis(N); auto itr = vec.begin(); while (itr != vec.end()) { cout<<*itr<<endl; itr++; } return 0; }
true
247c8fd6f0b78ffb9dd7de152dffc33025f30dc5
C++
JustFlare/ClickHouse
/dbms/src/AggregateFunctions/AggregateFunctionFactory.cpp
UTF-8
10,393
2.9375
3
[ "Apache-2.0" ]
permissive
#include <AggregateFunctions/AggregateFunctionFactory.h> #include <DataTypes/DataTypeAggregateFunction.h> #include <DataTypes/DataTypeArray.h> #include <DataTypes/DataTypeNullable.h> #include <DataTypes/DataTypesNumber.h> #include <IO/WriteBuffer.h> #include <IO/WriteHelpers.h> #include <Interpreters/Context.h> #include <Common/StringUtils.h> #include <Common/typeid_cast.h> #include <Poco/String.h> namespace DB { namespace ErrorCodes { extern const int UNKNOWN_AGGREGATE_FUNCTION; extern const int LOGICAL_ERROR; extern const int ILLEGAL_TYPE_OF_ARGUMENT; extern const int NUMBER_OF_ARGUMENTS_DOESNT_MATCH; } namespace { /// Does not check anything. std::string trimRight(const std::string & in, const char * suffix) { return in.substr(0, in.size() - strlen(suffix)); } } AggregateFunctionPtr createAggregateFunctionArray(AggregateFunctionPtr & nested, const DataTypes & argument_types); AggregateFunctionPtr createAggregateFunctionForEach(AggregateFunctionPtr & nested, const DataTypes & argument_types); AggregateFunctionPtr createAggregateFunctionIf(AggregateFunctionPtr & nested, const DataTypes & argument_types); AggregateFunctionPtr createAggregateFunctionState(AggregateFunctionPtr & nested, const DataTypes & argument_types, const Array & parameters); AggregateFunctionPtr createAggregateFunctionMerge(const String & name, AggregateFunctionPtr & nested, const DataTypes & argument_types); AggregateFunctionPtr createAggregateFunctionNullUnary(AggregateFunctionPtr & nested); AggregateFunctionPtr createAggregateFunctionNullVariadic(AggregateFunctionPtr & nested, const DataTypes & argument_types); AggregateFunctionPtr createAggregateFunctionCountNotNull(const String & name, const DataTypes & argument_types, const Array & parameters); AggregateFunctionPtr createAggregateFunctionNothing(); void AggregateFunctionFactory::registerFunction(const String & name, Creator creator, CaseSensitiveness case_sensitiveness) { if (creator == nullptr) throw Exception("AggregateFunctionFactory: the aggregate function " + name + " has been provided " " a null constructor", ErrorCodes::LOGICAL_ERROR); if (!aggregate_functions.emplace(name, creator).second) throw Exception("AggregateFunctionFactory: the aggregate function name '" + name + "' is not unique", ErrorCodes::LOGICAL_ERROR); if (case_sensitiveness == CaseInsensitive && !case_insensitive_aggregate_functions.emplace(Poco::toLower(name), creator).second) throw Exception("AggregateFunctionFactory: the case insensitive aggregate function name '" + name + "' is not unique", ErrorCodes::LOGICAL_ERROR); } AggregateFunctionPtr AggregateFunctionFactory::get( const String & name, const DataTypes & argument_types, const Array & parameters, int recursion_level) const { bool has_nullable_types = false; bool has_null_types = false; for (const auto & arg_type : argument_types) { if (arg_type->isNullable()) { has_nullable_types = true; if (arg_type->onlyNull()) { has_null_types = true; break; } } } if (has_nullable_types) { /// Special case for 'count' function. It could be called with Nullable arguments /// - that means - count number of calls, when all arguments are not NULL. if (Poco::toLower(name) == "count") return createAggregateFunctionCountNotNull(name, argument_types, parameters); AggregateFunctionPtr nested_function; if (has_null_types) { nested_function = createAggregateFunctionNothing(); } else { DataTypes nested_argument_types; nested_argument_types.reserve(argument_types.size()); for (const auto & arg_type : argument_types) nested_argument_types.push_back(removeNullable(arg_type)); nested_function = getImpl(name, nested_argument_types, parameters, recursion_level); } if (argument_types.size() == 1) return createAggregateFunctionNullUnary(nested_function); else return createAggregateFunctionNullVariadic(nested_function, argument_types); } else return getImpl(name, argument_types, parameters, recursion_level); } AggregateFunctionPtr AggregateFunctionFactory::getImpl( const String & name, const DataTypes & argument_types, const Array & parameters, int recursion_level) const { auto it = aggregate_functions.find(name); if (it != aggregate_functions.end()) { auto it = aggregate_functions.find(name); if (it != aggregate_functions.end()) return it->second(name, argument_types, parameters); } /// Combinators cannot apply for case insensitive (SQL-style) aggregate function names. Only for native names. if (recursion_level == 0) { auto it = case_insensitive_aggregate_functions.find(Poco::toLower(name)); if (it != case_insensitive_aggregate_functions.end()) return it->second(name, argument_types, parameters); } /// Combinators of aggregate functions. /// For every aggregate function 'agg' and combiner '-Comb' there is combined aggregate function with name 'aggComb', /// that can have different number and/or types of arguments, different result type and different behaviour. if (endsWith(name, "State")) { AggregateFunctionPtr nested = get(trimRight(name, "State"), argument_types, parameters, recursion_level + 1); return createAggregateFunctionState(nested, argument_types, parameters); } if (endsWith(name, "Merge")) { if (argument_types.size() != 1) throw Exception("Incorrect number of arguments for aggregate function " + name, ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH); const DataTypeAggregateFunction * function = typeid_cast<const DataTypeAggregateFunction *>(argument_types[0].get()); if (!function) throw Exception("Illegal type " + argument_types[0]->getName() + " of argument for aggregate function " + name + " must be AggregateFunction(...)", ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT); AggregateFunctionPtr nested = get(trimRight(name, "Merge"), function->getArgumentsDataTypes(), parameters, recursion_level + 1); if (nested->getName() != function->getFunctionName()) throw Exception("Illegal type " + argument_types[0]->getName() + " of argument for aggregate function " + name + ", because it corresponds to different aggregate function: " + function->getFunctionName() + " instead of " + nested->getName(), ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT); return createAggregateFunctionMerge(name, nested, argument_types); } if (endsWith(name, "If")) { if (argument_types.empty()) throw Exception("Incorrect number of arguments for aggregate function " + name, ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH); if (!typeid_cast<const DataTypeUInt8 *>(argument_types.back().get())) throw Exception("Illegal type " + argument_types.back()->getName() + " of last argument for aggregate function " + name, ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT); DataTypes nested_dt = argument_types; nested_dt.pop_back(); AggregateFunctionPtr nested = get(trimRight(name, "If"), nested_dt, parameters, recursion_level + 1); return createAggregateFunctionIf(nested, argument_types); } if (endsWith(name, "Array")) { DataTypes nested_arguments; for (const auto & type : argument_types) { if (const DataTypeArray * array = typeid_cast<const DataTypeArray *>(type.get())) nested_arguments.push_back(array->getNestedType()); else throw Exception("Illegal type " + type->getName() + " of argument" " for aggregate function " + name + ". Must be array.", ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT); } AggregateFunctionPtr nested = get(trimRight(name, "Array"), nested_arguments, parameters, recursion_level + 1); return createAggregateFunctionArray(nested, argument_types); } if (endsWith(name, "ForEach")) { DataTypes nested_arguments; for (const auto & type : argument_types) { if (const DataTypeArray * array = typeid_cast<const DataTypeArray *>(type.get())) nested_arguments.push_back(array->getNestedType()); else throw Exception("Illegal type " + type->getName() + " of argument" " for aggregate function " + name + ". Must be array.", ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT); } AggregateFunctionPtr nested = get(trimRight(name, "ForEach"), nested_arguments, parameters, recursion_level + 1); return createAggregateFunctionForEach(nested, argument_types); } throw Exception("Unknown aggregate function " + name, ErrorCodes::UNKNOWN_AGGREGATE_FUNCTION); } AggregateFunctionPtr AggregateFunctionFactory::tryGet(const String & name, const DataTypes & argument_types, const Array & parameters) const { return isAggregateFunctionName(name) ? get(name, argument_types, parameters) : nullptr; } bool AggregateFunctionFactory::isAggregateFunctionName(const String & name, int recursion_level) const { if (aggregate_functions.count(name)) return true; if (recursion_level == 0 && case_insensitive_aggregate_functions.count(Poco::toLower(name))) return true; if (endsWith(name, "State")) return isAggregateFunctionName(trimRight(name, "State"), recursion_level + 1); if (endsWith(name, "Merge")) return isAggregateFunctionName(trimRight(name, "Merge"), recursion_level + 1); if (endsWith(name, "If")) return isAggregateFunctionName(trimRight(name, "If"), recursion_level + 1); if (endsWith(name, "Array")) return isAggregateFunctionName(trimRight(name, "Array"), recursion_level + 1); if (endsWith(name, "ForEach")) return isAggregateFunctionName(trimRight(name, "ForEach"), recursion_level + 1); return false; } }
true
8850ee8818e1b05534b9076e90f6e3efa1d85f78
C++
yular/CC--InterviewProblem
/LintCode/lintcode_wood-cut.cpp
UTF-8
975
3.234375
3
[]
no_license
/* * * Tag: Binary Search * Time: O(lgn) * Space: O(1) */ class Solution { public: /** *@param L: Given n pieces of wood with length L[i] *@param k: An integer *return: The maximum length of the small pieces. */ int woodCut(vector<int> L, int k) { // write your code here int ans = 0; if(L.size() <= 0) return 0; long long r = LLONG_MIN; for(int i = 0; i < L.size(); ++ i){ r = max((long long)L[i], r); } long long l = 1; while(l <= r){ long long mid = (l + r)>>1; int cnt = Cal(mid, L); if(cnt >= k){ ans = mid; l = mid + 1; }else r = mid - 1; } return ans; } int Cal(long long len, vector<int> L){ int cnt = 0; for(int i = 0; i < L.size(); ++ i){ cnt += L[i]/len; } return cnt; } };
true
fdeab7825d3b25e32abc03a327dfeccbc0c31f67
C++
resoliwan/cprimary
/l09/11_usenamesp.cpp
UTF-8
577
3.34375
3
[]
no_license
#include <iostream> #include "11_namesp.h" void other(void); void another(void); int main(void) { using debts::Debt; Debt golf = { {"f_1", "l_1"}, 1}; debts::showDebt(golf); another(); other(); return 0; } void other(void) { using namespace debts; Debt two[2]; for (int i = 0; i < 2; i++) getDebt(two[i]); for (int i = 0; i < 2; i++) showDebt(two[i]); std::cout << "total: " << sumDebts(two, 2) << std::endl; } void another(void) { using pers::Person; Person test = { "L2", "F2" }; pers::showPerson(test); std::cout << std::endl; }
true
05ec3691ab16fec60ac5b51eaa7d81cc1e90047b
C++
Capri2014/math
/test/unit/math/rev/mat/fun/softmax_test.cpp
UTF-8
2,352
2.515625
3
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#include <stan/math/rev/mat.hpp> #include <gtest/gtest.h> #include <test/unit/math/rev/mat/fun/util.hpp> #include <test/unit/math/rev/mat/util.hpp> #include <vector> TEST(AgradRevMatrix, softmax) { using Eigen::Dynamic; using Eigen::Matrix; using stan::math::softmax; using stan::math::vector_v; EXPECT_THROW(softmax(vector_v()), std::invalid_argument); Matrix<AVAR, Dynamic, 1> x(1); x << 0.0; Matrix<AVAR, Dynamic, 1> theta = softmax(x); EXPECT_EQ(1, theta.size()); EXPECT_FLOAT_EQ(1.0, theta[0].val()); Matrix<AVAR, Dynamic, 1> x2(2); x2 << -1.0, 1.0; Matrix<AVAR, Dynamic, 1> theta2 = softmax(x2); EXPECT_EQ(2, theta2.size()); EXPECT_FLOAT_EQ(exp(-1) / (exp(-1) + exp(1)), theta2[0].val()); EXPECT_FLOAT_EQ(exp(1) / (exp(-1) + exp(1)), theta2[1].val()); Matrix<AVAR, Dynamic, 1> x3(3); x3 << -1.0, 1.0, 10.0; Matrix<AVAR, Dynamic, 1> theta3 = softmax(x3); EXPECT_EQ(3, theta3.size()); EXPECT_FLOAT_EQ(exp(-1) / (exp(-1) + exp(1) + exp(10.0)), theta3[0].val()); EXPECT_FLOAT_EQ(exp(1) / (exp(-1) + exp(1) + exp(10.0)), theta3[1].val()); EXPECT_FLOAT_EQ(exp(10) / (exp(-1) + exp(1) + exp(10.0)), theta3[2].val()); } TEST(AgradRevSoftmax, gradient_check) { using Eigen::Dynamic; using Eigen::Matrix; using stan::math::softmax; using stan::math::var; std::vector<std::vector<double> > inputs = {{0.5, -1.0, 3.0}, {4.0, 3.0, -2.0}}; std::vector<double> vals = {0.07459555713221443, 0.729736214118415}; std::vector<std::vector<double> > grads = {{0.06903105998834897, -0.001241607138856182, -0.06778945284949277}, {0.1972212719225377, -0.1959012993504623, -0.001319972572075391}}; for (size_t i = 0; i < inputs.size(); ++i) { for (int j = 0; j < 3; ++j) { stan::math::set_zero_all_adjoints(); Matrix<AVAR, Dynamic, 1> alpha(3); for (int k = 0; k < 3; ++k) alpha((j + k) % 3) = inputs[i][k]; Matrix<AVAR, Dynamic, 1> theta = softmax(alpha); theta(j).grad(); EXPECT_NEAR(vals[i], theta(j).val(), 1e-10); for (size_t k = 0; k < 3; ++k) EXPECT_NEAR(grads[i][k], alpha((j + k) % 3).adj(), 1e-10); } } } TEST(AgradRevMatrix, check_varis_on_stack) { Eigen::Matrix<stan::math::var, Eigen::Dynamic, 1> alpha(3); alpha << 0.0, 3.0, -1.0; test::check_varis_on_stack(stan::math::softmax(alpha)); }
true
614b84c2db7e3f8668bc59b45e1e3635cd828eae
C++
lebinhe/AF
/detail/strings/string_hash.h
UTF-8
859
2.78125
3
[]
no_license
#ifndef AF_DETAIL_STRINGS_STRINGHASH_H #define AF_DETAIL_STRINGS_STRINGHASH_H #include "AF/assert.h" #include "AF/basic_types.h" #include "AF/defines.h" namespace AF { namespace Detail { /* * Simple hash utility for C strings. */ class StringHash { public: enum { RANGE = 256 }; AF_FORCEINLINE static uint32_t Compute(const char *const str) { AF_ASSERT(str); // XOR the first n characters of the string together. const char *const end(str + 64); const char *ch(str); uint8_t hash(0); while (ch != end && *ch != '\0') { hash ^= static_cast<uint8_t>(*ch); ++ch; } return static_cast<uint32_t>(hash); } }; } // namespace Detail } // namespace AF #endif // AF_DETAIL_STRINGS_STRINGHASH_H
true
22eafb45e2f217044756afd30e638d56555d20cd
C++
naningntch/ProFun1
/8.1.cpp
UTF-8
549
2.71875
3
[]
no_license
#include <stdio.h> int main() { int count1, count2; scanf("%d %d", &count1, &count2); int def = count1 - count2; for (int i = 0; i < count1; i++) { for (int j = 0; j < count1; j++) { if (((i < count2) && (j + i < count2)) || ((j >= def) && (j - i >= def)) || ((i >= def) && (i - j >= def)) || ((j >= count1 - 1 - (i - def)) && (i >= def) && (j >= def))) { printf("-"); } else { printf("*"); } } printf("\n"); } }
true
e6202cacc45aa5eccb106d0cda2446e374d2cad8
C++
centhoang/BlasterMasterEngine
/BlasterMasterEngine/Assets/Bullets/Enemy/EnemyBullet.cpp
UTF-8
2,206
2.546875
3
[]
no_license
#include "d3dpch.h" #include "EnemyBullet.h" #include "Core/SceneManager/SceneManager.h" #include "Assets/Particles/NormalExplosion.h" #include "Assets/Characters/Sophia/Sophia.h" #include "Assets/Characters/Jason/Jason.h" EnemyBullet::EnemyBullet(float x, float y, bool pHorizontal, bool pIsFacingRight) : Object2D(x, y) { name = "Normal Fire Bullet"; horizontal = pHorizontal; isFacingRight = pIsFacingRight; tag = Tag::EnemyBullet; rigidbody = GetComponent<Rigidbody>(); boxCollider = GetComponent<BoxCollider2D>(); spriteRenderer = GetComponent<SpriteRenderer>(); layer = Layer::Projectile; } void EnemyBullet::Start() { runSpeed = 60.0f; horizontalRect = { 73, 20, 81, 28 }; verticalRect = { 82, 20, 90, 28 }; boxCollider->size = { 7.0f, 7.0f }; boxCollider->isTrigger = true; rigidbody->bodyType = Rigidbody::BodyType::Dynamic; rigidbody->gravityScale = 0.0f; transform->Scale(isFacingRight ? -WINDOW_CAMERA_SCALE_X : WINDOW_CAMERA_SCALE_X, WINDOW_CAMERA_SCALE_Y, 0.0f); } void EnemyBullet::Update() { if (horizontal) { spriteRenderer->rect = horizontalRect; rigidbody->velocity.x = (isFacingRight ? 1.0f : -1.0f) * runSpeed * Time::GetFixedDeltaTime(); rigidbody->velocity.y = 0.0f; } else { spriteRenderer->rect = verticalRect; rigidbody->velocity.x = 0.0f; rigidbody->velocity.y = runSpeed * Time::GetFixedDeltaTime(); } } void EnemyBullet::CreateResources() { spriteRenderer->sprite = DeviceResources::LoadTexture(SOPHIA_JASON_TEXTURE_PATH, 0); } void EnemyBullet::OnTriggerEnter(std::shared_ptr<Object2D> object) { if (object->tag == Tag::Player && object->rigidbody->bodyType == Rigidbody::BodyType::Dynamic) { std::shared_ptr<Sophia> sophia = std::dynamic_pointer_cast<Sophia>(object); if (sophia != NULL) { sophia->TakeDamage(damage); } std::shared_ptr<Jason> jason = std::dynamic_pointer_cast<Jason>(object); if (jason != NULL) { jason->TakeDamage(damage); } } std::shared_ptr<Object2D> explosion = std::make_shared<NormalExplosion>(transform->position.x, transform->position.y); explosion->CreateResources(); SceneManager::Instantiate(explosion, transform->position); SceneManager::DestroyObject(shared_from_this()); }
true
2e7a224e8a947ded65ceebe320d548f613413789
C++
jaime-varela/RKF45
/rk45/rk45utils.h
UTF-8
1,494
2.953125
3
[ "MIT" ]
permissive
#pragma once #include "rk45Concepts.h" namespace RungeKutta { //error calculation function template<NumT number = double,Index index = int,CoordinateContainer<number> coords> number err_norm(const coords& a) { number result =0; for(index i = 0; i < a.size();i++) { result += (a[i])*(a[i]); } return sqrt(result); } // method returns Nth power of A template<NumT number = double,Index index = int> number integerPower(number A, index N) { number result = A; for(index v = 1;v < N;v++) { result *= A; } return result; } // method returns 1/Nth power of A template<NumT number = double,Index index = int> number integerRootApprox(number A, index N) { // intially based on taylor series approximation number xPre = (A > 1)? A/2.0 : 1- ((1-A)/(1.0*N)) - (((1-A)*(1-A)*(1.0*N -1))/(2.0*N*N)); // smaller eps, denotes more accuracy // tunable but don't need full precision as this only does approximate output number eps = 1e-4; // initializing difference between two number delX; // xK denotes current value of x number xK; // loop untill we reach desired accuracy do { // calculating current value from previous // value by newton's method xK = ((N - 1.0) * xPre + A/integerPower(xPre, N-1)) / (1.0*N); delX = abs(xK - xPre); xPre = xK; } while (delX > eps); return xK; } }
true
470a1d19efbf632ea6f704c60ab0f0cd0c0d74a9
C++
oanaatasie/POO
/P2_TEMA_13/Tema 13/include/Matrice.h
UTF-8
582
2.75
3
[]
no_license
#ifndef MATRICE_H #define MATRICE_H using namespace std; class Matrice{ private: int **a; public: Matrice(); Matrice(int **a); Matrice(const Matrice &matrice); int** getMatrice(); int getdim(int **a) const; void setMatrice(int **a); Matrice& operator=(const Matrice &matrice); void print_mat(ostream& out) const; void read_mat(istream &in); friend ostream &operator<<(ostream &out, Matrice &matrice); friend istream &operator>>(istream &in, Matrice &matrice); virtual ~Matrice(); }; #endif // MATRICE_H
true
ab574a803b95f67bcfe69b6c77f793b70cbd76dd
C++
togashi13/402
/ColorImageClass.cpp
UTF-8
2,889
2.890625
3
[]
no_license
#include <iostream> using namespace std; #include "const_pro2.h" #include "ColorClass.h" #include "RowColumnClass.h" #include "ColorImageClass.h" ColorImageClass::ColorImageClass() { for (int i = 0; i < IMAGE_ROW; ++i) { for (int j = 0; j < IMAGE_COL; ++j) { pixels[i][j].setToBlack(); } } } void ColorImageClass::initializeTo( ColorClass &inColor ) { for (int i = 0; i < IMAGE_ROW; ++i) { for (int j = 0; j < IMAGE_COL; ++j) { pixels[i][j].setTo(inColor); } } } bool ColorImageClass::addImageTo( ColorImageClass &rhsImg ) { int numPixClipped = 0; for (int i = 0; i < IMAGE_ROW; ++i) { for (int j = 0; j < IMAGE_COL; ++j) { if (pixels[i][j].addColor(rhsImg.pixels[i][j])) { numPixClipped++; } } } return (numPixClipped > 0); } bool ColorImageClass::addImages( int numImagesToAdd, ColorImageClass imagesToAdd [] ) { int numClip = 0; for (int i = 0; i < IMAGE_ROW; ++i) { for (int j = 0; j < IMAGE_COL; ++j) { pixels[i][j].setToBlack(); } } for (int i = 0; i < IMAGE_ROW; ++i) { for (int j = 0; j < IMAGE_COL; ++j) { for (int imageIndex = 0; imageIndex < numImagesToAdd; ++imageIndex) { if (pixels[i][j].addColor(imagesToAdd[imageIndex].pixels[i][j])) { numClip ++; } } } } return (numClip > 0); } bool ColorImageClass::setColorAtLocation( RowColumnClass &inRowCol, ColorClass &inColor ) { int setRow = inRowCol.getRow(); int setCol = inRowCol.getCol(); if ((setRow < IMAGE_ROW) && (setRow >= 0) && (setCol < IMAGE_COL) && (setCol >= 0)) { pixels[setRow][setCol].setTo(inColor); return true; }else{ return false; } } bool ColorImageClass::getColorAtLocation( RowColumnClass &inRowCol, ColorClass &outColor ) { int setRow = inRowCol.getRow(); int setCol = inRowCol.getCol(); if ((setRow < IMAGE_ROW) && (setRow >= 0) && (setCol < IMAGE_COL) && (setCol >= 0)) { outColor.setTo(pixels[setRow][setCol]); return true; }else{ return false; } } void ColorImageClass::printImage() { for (int i = 0; i < IMAGE_ROW; ++i) { for (int j = 0; j < IMAGE_COL; ++j) { if (j == 17) { pixels[i][j].printComponentValues(); cout << endl; }else{ pixels[i][j].printComponentValues(); cout << "--"; } } } }
true
4f5721b9c1b00829315f51769ab7d7608075d788
C++
kburgon/salem-candy-dispenser
/salemTrigger/salemTrigger.ino
UTF-8
921
2.765625
3
[ "MIT" ]
permissive
const int buttonPin = 6; bool sendMsg = true; String results = "1"; void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(LED_BUILTIN, OUTPUT); pinMode(buttonPin, INPUT); } void loop() { // If sendMsg == false, then the pi is playing a sound byte. Don't check for a trigger. if (sendMsg) { if (digitalRead(buttonPin) == HIGH) { Serial.println(2); digitalWrite(LED_BUILTIN, HIGH); sendMsg = false; } else { Serial.println(1); } } // Try to read a heartbeat from the pi. if (Serial.available()) { // If the pi sends a "1", then it is not playing a sound byte anymore and is ready to play another. results = Serial.readString(); if (results == "1") { sendMsg = true; } } // The delay is mostly meant for testing purposes. delay(1000); digitalWrite(LED_BUILTIN, LOW); delay(100); }
true
ff5dc5ba681ebe7bdbaa8457dc93412dd663384c
C++
dtruhlar/Sachy
/klavesnice2SP/klavesnice2SP.ino
UTF-8
2,521
3
3
[]
no_license
#include <Keypad.h> int LED_CLOSE = 11; // červená LED int LED_OPEN = 12; // zelená LED const byte ROWS = 4; // 4 řádky const byte COLS = 4; // 4 sloupce // sem se budou ukládat stiskuté znaky char pressedKey[5] = {'0','0','0','0'}; // náš kód pro otevření dveří char code[5] = {'1','9','4','7'}; // zde si napíšete jak Vaše // membránová klávesnice vypadá char hexaKeys[ROWS][COLS] = { {'1','2','3','A'}, {'4','5','6','B'}, {'7','8','9','C'}, {'*','0','#','D'} }; byte rowPins[ROWS] = {9, 8, 7, 6}; //čísla pinů s řadkem 1 2 3 4 byte colPins[COLS] = {5, 4, 3, 2}; //čísla pinu se sloupcem 1 2 3 4 //initializuje objekt klávesnice s názvem customKeypad Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS); void setup(){ Serial.begin(9600); Serial.println("Odesilani stisknutych klaves na seriovou linku"); pinMode(LED_OPEN, OUTPUT); // pin jako výstup pinMode(LED_CLOSE, OUTPUT); // pin jako výstup digitalWrite(LED_CLOSE, HIGH); // rozsvítí červenou } void loop(){ // přečte stiskuté tlačítko a uloží do customKey char customKey = customKeypad.getKey(); if (customKey){ // když je stisknuto potvrzovací tlačítko # Serial.println(customKey); if (customKey == '#') { // když se pole kódu rovná poli stiskutých talčítek if ((pressedKey[0] == code[0]) && (pressedKey[1] == code[1]) && (pressedKey[2] == code[2]) && (pressedKey[3] == code[3])) { digitalWrite(LED_CLOSE, LOW); // zhasni červenou digitalWrite(LED_OPEN, HIGH); // rozsvit zelenou tone(10,2400,4000); // zahraj tón na pinu 10 (2400Hz, 4sec) delay(4000); // čekej 4 sekundy digitalWrite(LED_OPEN, LOW); // zhasni zelenou digitalWrite(LED_CLOSE, HIGH); // zhasni červenou // vynuluj stiskuté tlačítka pressedKey[0] = '0'; pressedKey[1] = '0'; pressedKey[2] = '0'; pressedKey[3] = '0'; } // jinak přo špatném kódu zahraj jiný tón a nic nedělej else tone(10,500,1000); //tón na pinu 10 (500Hz, 1 vteřina) } // když není stisknuto potvrzovací tlačítko # else { //přidej znak do pole a znaky posuň pressedKey[0] = pressedKey[1]; pressedKey[1] = pressedKey[2]; pressedKey[2] = pressedKey[3]; pressedKey[3] = customKey; // zahraje tón při stisku tlačítka tone(10,1200,80); } } }
true
1afbcf9c99e56ef7d73c7c05c220263de7ab464f
C++
rmahidhar/algorithms
/c++/algorithms/segment-tree/segment-tree.cpp
UTF-8
2,740
3.609375
4
[]
no_license
// // Created by Mahidhar Rajala on 8/20/17. // #include <vector> #include <functional> #include <iostream> #include <algorithm> template<class T> const T& max(const T& a, const T& b) { return (a > b) ? a : b; } template<class T> T sum(const T& a, const T& b) { return a + b; } template<class T> const T& min(const T& a, const T& b) { return (a < b) ? a : b; } template <typename T> class SegmentTree { const std::vector<T>& mInput; const std::function<T(T, T)> mFunc; std::vector<T> mSegmentTree; public: SegmentTree(const std::vector<T>& input, const std::function<T(T, T)> func) : mInput(input), mFunc(func), mSegmentTree(input.size() * 4) { build(0, 0, mInput.size()-1); } T query(unsigned long i, unsigned long j) { return query(0, 0, mInput.size()-1, i, j); } void printInput() { std::for_each(mInput.begin(), mInput.end(), [](auto item) { std::cout << item << " ";}); std::cout << std::endl; } void printSegmentTree() { std::cout << "size:" << mSegmentTree.size() << std::endl; std::for_each(mSegmentTree.begin(), mSegmentTree.end(), [](auto item) { std::cout << item << " ";}); std::cout << std::endl; } private: void build(unsigned long treeIndex, unsigned long low, unsigned long high) { if (low == high) { mSegmentTree[treeIndex] = mInput[low]; return; } unsigned long mid = low + (high - low)/2; build(2 * treeIndex + 1, low, mid); build(2 * treeIndex + 2, mid + 1, high); mSegmentTree[treeIndex] = mFunc(mSegmentTree[2 * treeIndex + 1], mSegmentTree[2 * treeIndex + 2]); } T query(unsigned long treeIndex, unsigned long low, unsigned long high, unsigned long i, unsigned long j) { if (low > j || high < i) return 0; if (i <= low && j >= high) return mSegmentTree[treeIndex]; unsigned long mid = low + (high - low)/2; if (i > mid) { return query(2 * treeIndex + 2, mid + 1, high, i, j); } else if (j <= mid) { return query(2 * treeIndex + 1, low, mid, i, j); } else { T lq = query(2 * treeIndex + 1, low, mid, i, mid); T rq = query(2 * treeIndex + 2, mid + 1, high, mid + 1, j); return mFunc(lq, rq); } } }; int main(int argc, char* argv[]) { std::vector<int> items = { 18, 17, 13, 19, 15, 11, 20, 12, 33, 25 }; std::function<int(int, int)> f = sum<int>; SegmentTree<int> st(items, f); st.printInput(); st.printSegmentTree(); unsigned long i = 4; unsigned long j = 6; std::cout << "Max[" << i << ":" << j << "]" << st.query(i, j) << std::endl; }
true
89d98022b81dd39661f28e0ad153abef4f5fad15
C++
Risgrynsgrot/bammi
/src/StreamQuad.cpp
UTF-8
2,786
2.8125
3
[]
no_license
#include "StreamQuad.h" #include <assert.h> #include "ErrorHandler.h" #include "WindowHandler.h" void StreamQuad::Init(SDL_Renderer* aRenderer, Vector2i aSize) { assert(aRenderer != nullptr); myRenderer = aRenderer; myTexture = SDL_CreateTexture(myRenderer, SDL_PIXELFORMAT_RGB888, SDL_TEXTUREACCESS_STREAMING, aSize.x, aSize.y); //Change this if we need transparency if(!myTexture) { PrintLastSDLError(); } assert(myTexture != nullptr); myDestRect.w = aSize.x; myDestRect.h = aSize.y; SetTextureColor(1,1,1); } void StreamQuad::SetTextureColor(float r, float g, float b) { LockTexture(); Uint32* pixels = (Uint32*)GetPixels(); int pixelCount = GetSize().x * GetSize().y; auto format = WindowHandler::GetInstance()->GetPixelFormat(); Uint32 color = SDL_MapRGB(format, r * 255, g * 255, b * 255); for (size_t i = 0; i < pixelCount; i++) { pixels[i] = color; } UnlockTexture(); } void StreamQuad::Render() { SDL_FPoint center; center.x = myCenter.x; center.y = myCenter.y; SDL_RenderCopyExF(myRenderer, myTexture, NULL, &myDestRect, myRotation, &center, SDL_FLIP_NONE); //maybe add flip options if necessary } Vector2f StreamQuad::GetPosition() { return {myDestRect.x, myDestRect.y}; } Vector2f StreamQuad::GetSize() { return {myDestRect.w, myDestRect.h}; } void StreamQuad::SetPosition(Vector2f aPosition) { SetPosition(aPosition.x, aPosition.y); } void StreamQuad::SetPosition(float aX, float aY) { myDestRect.x = aX; myDestRect.y = aY; } void StreamQuad::SetSize(Vector2f aSize) { SetSize(aSize.x, aSize.y); } void StreamQuad::SetSize(float aWidth, float aHeight) { myDestRect.w = aWidth; myDestRect.h = aHeight; } void StreamQuad::SetColorRGB(float r, float g, float b) { int newR = (int)(r * 255.f); int newG = (int)(g * 255.f); int newB = (int)(b * 255.f); SDL_SetTextureColorMod(myTexture, newR, newG, newB); } void StreamQuad::SetRotation(float aRotation) { myRotation = aRotation; } float StreamQuad::GetRotation() { return myRotation; } void StreamQuad::SetCenter(Vector2f aCenter) { myCenter = aCenter; } void StreamQuad::Reset() { myRotation = 0; myCenter = {0,0}; myDestRect = {0,0,0,0}; } bool StreamQuad::LockTexture() { if(myPixels != nullptr) { printf("ERROR: trying to lock already locked texture\n"); return false; } if(SDL_LockTexture(myTexture, nullptr, &myPixels, &myPitch) != 0) { PrintLastSDLError(); return false; } return true; } bool StreamQuad::UnlockTexture() { if(myPixels == nullptr) { printf("ERROR: trying to unlock unlocked texture\n"); return false; } SDL_UnlockTexture(myTexture); myPixels = nullptr; myPitch = 0; return true; } StreamQuad::~StreamQuad() { SDL_DestroyTexture(myTexture); }
true
ec2ec5e1b6808c3184dd0606a3128c42d0259b86
C++
ChenxiTang/ece1373_project_lstm_seizure_detection
/c_code/fir_top/fir_top.cpp
UTF-8
2,317
2.546875
3
[]
no_license
/*Top Level 22-channel 5-band FIR code with optimisation in HLS*/ /*Written by: Chenxi Tang */ /*Last Updated: 25 June 2019 */ /*Developed with Vivdo design suite 2017.2 */ /*Part of the course project for ECE1373 Digital Design for SoC*/ #include <algorithm> #include <cmath> //#include <iostream> #include "sig_band_energy.h" using namespace std; void fir_top(dataType* mem, add_type input_add, add_type output_add) { #pragma HLS INTERFACE m_axi depth=2147483648 port=mem #pragma HLS INTERFACE s_axilite port=input_add bundle=CTRL_BUS #pragma HLS INTERFACE s_axilite port=output_add bundle=CTRL_BUS #pragma HLS INTERFACE s_axilite port=return bundle=CTRL_BUS //read weights from memory dataType weights1[N]; #pragma HLS RESOURCE variable=weights1 core=RAM_S2P_BRAM dataType weights2[N]; #pragma HLS RESOURCE variable=weights2 core=RAM_S2P_BRAM dataType weights3[N]; #pragma HLS RESOURCE variable=weights3 core=RAM_S2P_BRAM dataType weights4[N]; #pragma HLS RESOURCE variable=weights4 core=RAM_S2P_BRAM dataType weights5[N]; #pragma HLS RESOURCE variable=weights5 core=RAM_S2P_BRAM for (int j = 0; j < N; j++) { #pragma HLS PIPELINE weights1[j] = mem[input_add / sizeof(dataType) + j + 0 * N]; weights2[j] = mem[input_add / sizeof(dataType) + j + 1 * N]; weights3[j] = mem[input_add / sizeof(dataType) + j + 2 * N]; weights4[j] = mem[input_add / sizeof(dataType) + j + 3 * N]; weights5[j] = mem[input_add / sizeof(dataType) + j + 4 * N]; } for (int index = 0; index < SIG_LENGTH; index++) { // stream in inputs to BRAM int input_offset = (n_bands * N) * sizeof(dataType) + input_add; dataType channel_in[n_channel]; #pragma HLS RESOURCE variable=channel_in core=RAM_S2P_BRAM for (int i = 0; i < n_channel; i++) { channel_in[i] = mem[input_offset / sizeof(dataType) + index + SIG_LENGTH * i]; } // FIR for 22 channels for (int ch = 0; ch < n_channel; ch++) { int output_offset = (n_bands * N + n_channel * SIG_LENGTH + ch * n_bands) * sizeof(dataType) + output_add; channel_1_band_5(mem, input_offset, output_offset, ch, index, weights1, weights2, weights3, weights4, weights5, channel_in); } } }
true
0a19da155a3754c965dba3e4781995f7c9315cac
C++
wserrantola/SeekurJr
/seekur_12.04/packages/CAMERA_STEREO/mobile_ranger/include/mobile_ranger/libfrdev/FrImageLUTProc.h
UTF-8
2,699
2.53125
3
[]
no_license
/**************************************************************************** * Copyright (c) 2007 by Focus Robotics. * * All rights reserved. No part of this design may be reproduced stored * in a retrieval system, or transmitted, in any form or by any means, * electronic, mechanical, photocopying, recording, or otherwise, without * prior written permission of Focus Robotics, Inc. * * Proprietary and Confidential * * Created By : Andrew Worcester * Creation_Date: Wed May 2 2007 * * Brief Description: * * Functionality: * * Issues: * * Limitations: * * Testing: * ******************************************************************************/ #ifndef FRIMAGELUTPROC_H #define FRIMAGELUTPROC_H #include "FrMsgLog.h" #include "FrImage.h" enum FrImageLUTType { LUT_TYPE_CUSTOM, LUT_TYPE_FULL_RANGE, LUT_TYPE_COLOR_SPECTRUM }; /// This class transforms an image by changing each pixel with an arbitrary LUT. /** * This class transforms a source image into a destination image by converting * every pixel with an arbitrary look-up table. There will be a few standard * LUTs defined that can just be selected and also a way to define a new * arbitrary mapping by specifying the output for every input. * * Initially, the only source image type supported will be single channel * FrImage. The output will be 1 channel or 3 channel FrImage. Other * combinations may be added in the future. * * Standard LUTs will be the full range expansion which maps an image with a * small range (i.e. 0 to 63) to the full range of 0 to 255 for better viewing * and the color spectrum which maps the largest input values to hot colors and * the lowest input values to cool colors. */ class FrImageLUTProc { public: FrImageLUTProc(FrImageLUTType type, FrImage *src, int min, int max); ~FrImageLUTProc(); void setLUTType(FrImageLUTType type); void setSrcMaxVal(int val); // just to make things easier for now void setImg(FrImageType type, FrImage *img); FrImage* getImg(FrImageType type); // Run should allocate the dst image and create the LUT. Additional runs // should only recreate the LUT if params are changed. The user can normally // just construct the LUT obj and then call run() and getImg() for each new // frame. Setting the range or max value after construction is also necessary // for now, but that could be determined automatically in the future, maybe. int run(); protected: void createFullRangeLUT(); void createColorSpectrumLUT(); void remapColor(); void remapGray(); private: uchar *lut0; uchar *lut1; uchar *lut2; FrImage *srcImg; FrImage *dstImg; FrImageLUTType lutType; int srcMax, srcMin; }; #endif
true
6b2186344cb013cde60ec011f4f86ccdb17853f5
C++
Cesaario/TrabalhoPraticoIndustrial
/ExibiçãoDeDefeitos/ExibicaoDeDefeitos.cpp
UTF-8
1,540
2.703125
3
[]
no_license
#include <windows.h> #include <process.h> #include <stdio.h> #include <conio.h> #include <errno.h> #include <string> #include <iostream> #include "DefeitoSuperficieTira.h" #define TAMANHO_MENSAGEM 37 int main() { printf("Processo de exibicao de defeitos iniciando...\n"); HANDLE Handle_Console = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleTextAttribute(Handle_Console, FOREGROUND_BLUE | FOREGROUND_INTENSITY); DWORD resultadoEvento; HANDLE Evento_Nao_Finalizar_Exibicao_De_Defeitos = OpenEvent(SYNCHRONIZE, false, "Evento_Nao_Finalizar_Exibicao_De_Defeitos"); HANDLE Evento_Desbloquear_Exibicao_De_Defeitos = OpenEvent(SYNCHRONIZE, false, "Evento_Desbloquear_Exibicao_De_Defeitos"); WaitNamedPipe("Pipe_Defeitos_Das_Tiras", NMPWAIT_USE_DEFAULT_WAIT); HANDLE Pipe_Defeitos_Das_Tiras = CreateFile( "\\\\.\\pipe\\Pipe_Defeitos_Das_Tiras", GENERIC_READ, 0, NULL, CREATE_ALWAYS, 0, NULL ); do { WaitForSingleObject(Evento_Desbloquear_Exibicao_De_Defeitos, INFINITE); char Mensagem_Lida[TAMANHO_MENSAGEM]; DWORD Bytes_Lidos; ReadFile( Pipe_Defeitos_Das_Tiras, Mensagem_Lida, 37, &Bytes_Lidos, NULL ); std::string Mensagem_Formatada = FormatarDefeitoTira(DesserializarDefeitoTira(Mensagem_Lida)); std::cout << Mensagem_Formatada << std::endl; resultadoEvento = WaitForSingleObject(Evento_Nao_Finalizar_Exibicao_De_Defeitos, 0); } while (resultadoEvento == WAIT_OBJECT_0); CloseHandle(Pipe_Defeitos_Das_Tiras); printf("Finalizando processo de exibicao de defeitos...\n"); }
true
7a43e0a939420e3f08864a10a41b4c4cc1f08a8a
C++
Burakkarakoyun/C-works
/Girilen Metinde Harf Arama.cpp
ISO-8859-9
808
2.796875
3
[]
no_license
//girilen metinde ka tane istenilen harften oldugunu bulan program //Burak KARAKOYUN #include<stdio.h> #include<locale.h> char harf(char cumle[100],char ara){ int sayac=0; for(int i=0;cumle[i]!='\0';i++){ //bu ksmda girilen cmledeki karakterleri tek tek istenilen harfle ayn m diye karlatryoruz.aynysa saya 1 artar. if(cumle[i]==ara){ sayac++; } } if(sayac==0)printf("Aradnz harf metin ierisinde bulunamad."); printf("Aradnz harf metin ierisinde %d defa geti.",sayac); } int main(){ setlocale(LC_ALL,"Turkish"); char cumle[100],ara; printf("Girilen metin ierisinde harf arama program\n\nHOGELDNZ\nLtfen metni giriniz-->");gets(cumle); printf("Ltfen aranan harfi giriniz.--->");scanf("%c",&ara); harf(cumle,ara); }
true
034e598bedce877a6e3a70e6de6e7600308c461a
C++
hikerLi/gameserver
/KCP/connection.cpp
UTF-8
2,058
2.59375
3
[]
no_license
#include "connection.h" #include <iostream> #include <cstring> #include <KCP/connectionmanager.h> #include <Common/logmanager.h> #include <Common/memorypool.h> #include <Common/common.h> Connection::Connection() { } Connection *Connection::Create(const kcp_conv_t &conv, const Endport &ePort, ConnectionManager *connMgr) { if(nullptr == connMgr){ return nullptr; } Connection * conn = MemPoolIns.newElement<Connection>(); if(conn){ conn->connMgr = connMgr; conn->Init(conv); conn->ipPort = ePort; } return conn; } int Connection::UdpSendOutput(const char *buf, int len, IKCPCB *kcp, void *user) { return ((Connection *)user)->SendUdpPackage(buf, len); } void Connection::WriteLog(const char *log, IKCPCB *kcp, void *user) { LOG_DEBUG(" ikcp write log : %s" , log); } void Connection::UpdateIkcp(uint32_t curentTimestamp) { ikcp_update(pKcp, curentTimestamp); } int Connection::PushToSender(const std::string &msg) { return ikcp_send(pKcp, msg.c_str(), msg.length()); } bool Connection::SetToInput(const char *data, size_t len) { if(nullptr == data || len < 0){ LOG_ERR(" recv input null or len < 0."); return false; } if(int ret = ikcp_input(pKcp, data, len) != 0){ LOG_ERR(" kcp input err no : <%d>", ret); return false; } return true; } bool Connection::PopByRecv(std::string &msg) { char buff[MAXPAYLOAD]; memset(buff, 0, MAXPAYLOAD); int ret = ikcp_recv(pKcp,buff,MAXPAYLOAD); if(ret <= 0){ LOG_ERR("kcp recv < 0 len: %d", ret); return false; } msg = buff; return true; } void Connection::Init(const kcp_conv_t &conv) { pKcp = ikcp_create(conv, (void *)this); if(nullptr != pKcp){ pKcp->output = &Connection::UdpSendOutput; pKcp->writelog = &Connection::WriteLog; ikcp_nodelay(pKcp, 1, 5, 1, 1); } } int Connection::SendUdpPackage(const char *buffer, int len) { return connMgr->SendUdpPackage(std::string(buffer,len), ipPort); }
true