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
a738ae690bc2c692a80c721fa5ecdede8582ba47
C++
vrcordoba/Klondike
/src/controllers/SaveController.hpp
UTF-8
936
2.65625
3
[]
no_license
#ifndef CONTROLLERS_SAVECONTROLLER_HPP_ #define CONTROLLERS_SAVECONTROLLER_HPP_ #include <string> #include "Controller.hpp" #include "OperationController.hpp" namespace Models { class Game; class Pile; } namespace Utils { class PermanentMediumWriter; } namespace Controllers { class OperationControllerVisitor; class SaveController final : public Controller, public OperationController { public: explicit SaveController(Models::Game& game); ~SaveController(); SaveController(const SaveController&) = delete; SaveController& operator=(const SaveController&) = delete; void accept(OperationControllerVisitor* operationControllerVisitor); bool fileAlreadyExists(const std::string& saveFileName); void saveGame(const std::string& saveFileName); private: void saveCardTable(Utils::PermanentMediumWriter* saveFile); void savePile(Utils::PermanentMediumWriter* saveFile, Models::Pile* pile); }; } #endif
true
f7f0fb94b28dde780749f36428e3dfd86e1b3f71
C++
shindj1219/algorithm
/Longest_Substring/my_answer.cc
UTF-8
785
3.15625
3
[]
no_license
class Solution { public: int lengthOfLongestSubstring(string s) { int max_length{0}; std::string temp; std::vector<char> char_arr; while(!s.empty()) { auto c{s.at(0)}; for(auto iter = char_arr.begin(); iter!=char_arr.end(); iter++) { if(*iter == c) { if(max_length < temp.length()) { max_length = temp.length(); } char_arr.erase(char_arr.begin(), iter); auto find{temp.find(c)}; temp = temp.substr(find+1); break; } } char_arr.emplace_back(c); temp += c; s = s.substr(1); } if(max_length < temp.length()) { max_length = temp.length(); } return max_length; } };
true
604100092c0d6f59b6659dd1d127c16403226ee5
C++
alexandraback/datacollection
/solutions_5695413893988352_1/C++/carlop/B.cpp
UTF-8
2,920
2.734375
3
[]
no_license
#include <vector> #include <iostream> #include <fstream> #include <string> #include <map> #include <cstdlib> #include <algorithm> #include <assert.h> #include <set> using namespace std; int number_of_inversion(const string & S) { int c=0; for (int i=1; i<S.size(); i++) if (S[i] != S[i-1]) c++; return c; } void fill_it_greedily(vector <string> in, vector <string> & best, unsigned long long & best_diff) { vector <string> res(2); int steps = 0; for (string::iterator it0 = in[0].begin(), it1 = in[1].begin(); it0<in[0].end(); it0++, it1++, steps++) { char C[2] = {'0', '0'}; if (isdigit(*it0)) C[0]=*it0; if (isdigit(*it1)) C[1]=*it1; if (res[0] == res[1]) { if (!isdigit(*it0)) C[0] = C[1]; if (!isdigit(*it1)) C[1] = C[0]; //copy-paste!!! if (!isdigit(*it0)) { if (C[0] != '0') { vector <string> recurrence(in); recurrence[0][steps] = (char)((int)C[0]-1); recurrence[1][steps] = C[1]; fill_it_greedily(recurrence, best, best_diff); } if (C[0] != '9') { vector <string> recurrence(in); recurrence[0][steps] = (char)((int)C[0]+1); recurrence[1][steps] = C[1]; fill_it_greedily(recurrence, best, best_diff); } } if (!isdigit(*it1)) { if (C[1] != '0') { vector <string> recurrence(in); recurrence[1][steps] = (char)((int)C[1]-1); recurrence[0][steps] = C[0]; fill_it_greedily(recurrence, best, best_diff); } if (C[1] != '9') { vector <string> recurrence(in); recurrence[1][steps] = (char)((int)C[1]+1); recurrence[0][steps] = C[0]; fill_it_greedily(recurrence, best, best_diff); } } } else if (res[0] < res[1]) { if (!isdigit(*it0)) C[0] = '9'; if (!isdigit(*it1)) C[1] = '0'; } else { if (!isdigit(*it0)) C[0] = '0'; if (!isdigit(*it1)) C[1] = '9'; } *it0 = C[0]; *it1 = C[1]; res[0] += C[0]; res[1] += C[1]; } vector <unsigned long long> V; V.push_back(stoull(res[0])); V.push_back(stoull(res[1])); unsigned long long diff; if (V[0] <= V[1]) diff = V[1]-V[0]; else diff = V[0] - V[1]; if (best.size() == 0) { best = res; best_diff = diff; } // std::cerr<<res[0] <<" "<< res[1] << "\t"; // std::cerr<<best[0] <<" "<< best[1] << "\n"; if (diff < best_diff) { best_diff = diff; best = res; } else if (diff == best_diff){ if (res[0] < best[0]) best = res; else if (res[0] == best[0] && res[1] < best[1]) best = res; } } int main(void) { int num_test; cin>>num_test; for (int test=1; test<=num_test; test++) { vector<string> in(2); cin>>in[0]>>in[1]; vector <string> res; unsigned long long diff = 0; fill_it_greedily(in, res, diff); cout<<"Case #"<<test<<": "<<res[0] << " " << res[1]<<"\n"; // cerr << "-------------\n"; } return 0; }
true
a2c834cc240409330ee870a3058db34169a8d214
C++
ponxosio/EvoCoder
/src/protocolGraph/ConditionEdge.h
UTF-8
2,677
2.59375
3
[ "BSL-1.0" ]
permissive
/* * ConditionEdge.h * * Created on: 15 de mar. de 2016 * Author: angel */ #ifndef SRC_FLUIDCONTROL_PROTOCOLGRAPH_CONDITIONEDGE_H_ #define SRC_FLUIDCONTROL_PROTOCOLGRAPH_CONDITIONEDGE_H_ //boost #include <memory> //local #include "../graph/Edge.h" #include "../util/Utils.h" #include "../operables/comparison/ComparisonOperable.h" //cereal #include <cereal/cereal.hpp> #include <cereal/types/polymorphic.hpp> #include <cereal/types/memory.hpp> /** * Represents an edge in a graph that has a condition, the edge can not be used until the condition is met. */ class ConditionEdge: public Edge { public: //Obligatory constructors if is derived from NODE ConditionEdge(); ConditionEdge(const ConditionEdge & edge); // /** * Makes internal copies of leftVariable and rightVariable * @param comparison comparison operation that must be met in order to use this edge */ ConditionEdge(int idSource, int idTarget, std::shared_ptr<ComparisonOperable> comparison); virtual ~ConditionEdge(); inline void updateReference(const std::string & reference) { comparison->updateReference(reference); } /** * Checks if the condition to use this edge is met * @return true if the condition is met, false otherwise */ bool conditionMet(); /** * Checks if the condition uses physical values * @return true if uses physical variables, false otherwise */ bool isPhyscal(); /** * Checks if this edge has certain condition * @param comparison condition to be checked * @return true if this edge has the same condition, false otherwise */ bool hasCondition(ComparisonOperable* comparison); //OVERRIDEN METHODS /** * Compares two edges * * @param e other edge to compare * @return true if the edges are equal, false otherwise */ virtual bool equals(const Edge& e); virtual std::string toText(); //SERIALIZATIoN template<class Archive> void serialize(Archive & ar, std::uint32_t const version); protected: std::shared_ptr<ComparisonOperable> comparison; }; template<class Archive> inline void ConditionEdge::serialize(Archive& ar, const std::uint32_t version) { if (version <= 1) { Edge::serialize(ar, version); ar(CEREAL_NVP(comparison)); } } // Associate some type with a version number CEREAL_CLASS_VERSION(ConditionEdge, (int)1); // Include any archives you plan on using with your type before you register it // Note that this could be done in any other location so long as it was prior // to this file being included #include <cereal/archives/json.hpp> // Register DerivedClass CEREAL_REGISTER_TYPE_WITH_NAME(ConditionEdge, "ConditionEdge"); #endif /* SRC_FLUIDCONTROL_PROTOCOLGRAPH_CONDITIONEDGE_H_ */
true
0d838762e9801461e04903385f796588e27f9000
C++
fanzcsoft/wxExtension
/extension/src/cmdline.cpp
UTF-8
6,711
2.546875
3
[ "MIT" ]
permissive
//////////////////////////////////////////////////////////////////////////////// // Name: cmdline.cpp // Purpose: Implementation of wxExCmdLine class // Author: Anton van Wezenbeek // Copyright: (c) 2018 Anton van Wezenbeek //////////////////////////////////////////////////////////////////////////////// #include <sstream> // for tclap! #include <variant> #include <tclap/CmdLine.h> #include <wx/app.h> #include <wx/config.h> #include <wx/extension/cmdline.h> #include <wx/extension/log.h> #include <wx/extension/tokenizer.h> #include <wx/extension/version.h> class wxExCmdLineOption { public: wxExCmdLineOption( TCLAP::ValueArg<float>* f, std::function<void(const std::any& any)> fu) : m_val(f), m_f(fu) {;}; wxExCmdLineOption( TCLAP::ValueArg<int>* i, std::function<void(const std::any& any)> fu) : m_val(i), m_f(fu) {;}; wxExCmdLineOption( TCLAP::ValueArg<std::string>* s, std::function<void(const std::any& any)> fu) : m_val(s), m_f(fu) {;}; ~wxExCmdLineOption() { if (std::holds_alternative<TCLAP::ValueArg<float>*>(m_val)) delete std::get<0>(m_val); else if (std::holds_alternative<TCLAP::ValueArg<int>*>(m_val)) delete std::get<1>(m_val); else if (std::holds_alternative<TCLAP::ValueArg<std::string>*>(m_val)) delete std::get<2>(m_val); }; void Run() const { if (auto pval = std::get_if<TCLAP::ValueArg<float>*>(&m_val)) { if ((*pval)->getValue() != -1) { m_f((*pval)->getValue()); } } else if (auto pval = std::get_if<TCLAP::ValueArg<int>*>(&m_val)) { if ((*pval)->getValue() != -1) { m_f((*pval)->getValue()); } } else if (auto pval = std::get_if<TCLAP::ValueArg<std::string>*>(&m_val)) { if (!(*pval)->getValue().empty()) { m_f((*pval)->getValue()); } } } private: std::function<void(const std::any& any)> m_f; const std::variant < TCLAP::ValueArg<float>*, TCLAP::ValueArg<int>*, TCLAP::ValueArg<std::string>*> m_val; }; class wxExCmdLineParam { public: wxExCmdLineParam( TCLAP::UnlabeledMultiArg<std::string>* arg, std::function<bool(std::vector<std::string>)> f) : m_val({arg, f}) {;}; ~wxExCmdLineParam() {delete m_val.first;}; const bool Run() { return m_val.first->getValue().empty() || m_val.second(m_val.first->getValue()); } private: const std::pair< TCLAP::UnlabeledMultiArg<std::string>*, std::function<bool(std::vector<std::string>)>> m_val; }; class wxExCmdLineParser : public TCLAP::CmdLine { public: wxExCmdLineParser( const std::string& message, char delim, const std::string& version, bool help) : TCLAP::CmdLine(message, delim, version, help) {;}; }; class wxExCmdLineSwitch { public: wxExCmdLineSwitch( TCLAP::SwitchArg* arg, std::function<void(bool)> f) : m_val({arg, f}) {;}; ~wxExCmdLineSwitch() {delete m_val.first;}; void Run(bool toggle) { m_val.second(m_val.first->getValue()); if (toggle) { wxConfigBase::Get()->Write(m_val.first->getName(), !m_val.first->getValue()); } } private: const std::pair< TCLAP::SwitchArg*, std::function<void(bool)>> m_val; }; wxExCmdLine::wxExCmdLine( const CmdSwitches & s, const CmdOptions & o, const CmdParams & p, const std::string& message, const std::string &version, bool helpAndVersion) : m_Parser(new wxExCmdLineParser( message, ' ', version.empty() ? wxExGetVersionInfo().GetVersionOnlyString().ToStdString(): version, helpAndVersion)) { m_Parser->setExceptionHandling(false); try { for (auto it = o.rbegin(); it != o.rend(); ++it) { switch (it->second.first) { case CMD_LINE_FLOAT: { auto* arg = new TCLAP::ValueArg<float>( std::get<0>(it->first), std::get<1>(it->first), std::get<2>(it->first), false, -1, "float"); m_Parser->add(arg); m_Options.emplace_back(new wxExCmdLineOption(arg, it->second.second)); } break; case CMD_LINE_INT: { auto* arg = new TCLAP::ValueArg<int>( std::get<0>(it->first), std::get<1>(it->first), std::get<2>(it->first), false, -1, "int"); m_Parser->add(arg); m_Options.emplace_back(new wxExCmdLineOption(arg, it->second.second)); } break; case CMD_LINE_STRING: { auto* arg = new TCLAP::ValueArg<std::string>( std::get<0>(it->first), std::get<1>(it->first), std::get<2>(it->first), false, std::string(), "string"); m_Parser->add(arg); m_Options.emplace_back(new wxExCmdLineOption(arg, it->second.second)); } break; default: wxExLog() << "unknown type"; } } for (auto it = s.rbegin(); it != s.rend(); ++it) { const bool def = !wxConfigBase::Get()->ReadBool(std::get<1>(it->first), true); auto* arg = new TCLAP::SwitchArg( std::get<0>(it->first), std::get<1>(it->first), std::get<2>(it->first), def); m_Switches.emplace_back(new wxExCmdLineSwitch(arg, it->second)); m_Parser->add(arg); } if (!p.first.first.empty()) { auto* arg = new TCLAP::UnlabeledMultiArg<std::string>( p.first.first, p.first.second, false, std::string()); m_Params.emplace_back(new wxExCmdLineParam(arg, p.second)); m_Parser->add(arg); } } catch (TCLAP::ArgException& e) { wxExLog(e) << "tclap"; } catch (TCLAP::ExitException& ) { } } wxExCmdLine::~wxExCmdLine() { for (auto& it : m_Options) delete it; for (auto& it : m_Params) delete it; for (auto& it : m_Switches) delete it; delete m_Parser; } char wxExCmdLine::Delimiter() const { return TCLAP::Arg::delimiter(); } void wxExCmdLine::Delimiter(char c) { TCLAP::Arg::setDelimiter(c); } bool wxExCmdLine::Parse( const std::string& cmdline, bool toggle, const char delimiter) { Delimiter(delimiter); try { if (cmdline.empty()) { m_Parser->parse(wxTheApp->argc, wxTheApp->argv); } else { wxExTokenizer tkz(cmdline); auto v = tkz.Tokenize<std::vector<std::string>>(); m_Parser->parse(v); } for (const auto& it : m_Switches) { it->Run(toggle); } for (const auto& it : m_Options) { it->Run(); } if (!m_Params.empty() && !m_Params[0]->Run()) { wxExLog() << "could not run params"; return false; } return true; } catch (TCLAP::ArgException& e) { wxExLog(e) << "tclap"; return false; } catch (TCLAP::ExitException& ) { return false; } }
true
fbea67df2862ccdb26591fa810fef0c5d4a04864
C++
adamap/code-test2
/28strtstr.cpp
UTF-8
687
3.671875
4
[]
no_license
//Implement strStr(). // //Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. // // class Solution { public: int strStr(string haystack, string needle) { for ( int i = 0; i <= (int)(haystack.size()-needle.size()); i++) { int i_index = i, j_index= 0; while( j_index < needle.size() && (haystack[i_index] == needle[j_index] )) { j_index++; i_index++; } if ( j_index == needle.size()) { return i; } } return -1; } };
true
06edf0e9df0744d51f56d38282c5998c7f1376e8
C++
drzaal/flippy-board
/SourceArt/ArduinoFirmware/flippyBoard/flippyBoard.ino
UTF-8
2,225
3.09375
3
[]
no_license
/* Flippy Board * Global Game Jam 2017 */ // Characters to send over serial to cause different button flash actions const int MODE_ATTRACT = 0; // A const int MODE_OFF = 1; // 0 const int MODE_ON = 2; // 1 const int MODE_DIE = 3; // X const int MODE_WIN = 4; // W int led = 9; int brightness = 0; int fadeAmount = 5; int mode = MODE_ATTRACT; int dieStage = 0; void attractMode() { fadeAmount = 5; brightness = 0; mode = MODE_ATTRACT; } void offMode() { fadeAmount = 0; brightness = 0; mode = MODE_OFF; } void onMode() { fadeAmount = 0; brightness = 255; mode = MODE_ON; } void dieMode() { brightness = 255; fadeAmount = 25; dieStage = 0; mode = MODE_DIE; } void winMode() { mode = MODE_WIN; } void fade() { analogWrite(led, brightness); brightness = brightness + fadeAmount; if(brightness <= 0 || brightness >= 255) { fadeAmount = -fadeAmount; } } void die() { if(dieStage == 0) { analogWrite(led, brightness); brightness -= fadeAmount; if (brightness <= 0) { dieStage = 1; } } else if(dieStage == 1) { analogWrite(led, 255); delay(100); analogWrite(led, 0); delay(100); analogWrite(led, 255); delay(100); analogWrite(led, 0); delay(100); analogWrite(led, 255); delay(100); analogWrite(led, 0); delay(100); onMode(); } } void win() { int i; for(i=0; i < 20; i++) { analogWrite(led, 255); delay(50); analogWrite(led, 0); delay(50); } onMode(); } void handleSerial() { if(Serial.available()) { char inChar = (char)Serial.read(); if(inChar == 'A') { attractMode(); } else if(inChar == '0') { offMode(); } else if(inChar == '1') { onMode(); } else if(inChar == 'X') { dieMode(); } else if(inChar == 'W') { winMode(); } } }; void setup() { pinMode(led, OUTPUT); Serial.begin(9600); } void loop() { if(mode == MODE_DIE) { die(); } else if(mode == MODE_WIN) { win(); } else { fade(); } handleSerial(); delay(30); }
true
ed173114ab7a3612e124698dba7bc830758ca1e5
C++
emrekavak/CSE241-OOP_HomeWorks
/hw5/connectfourplusundo.h
UTF-8
1,817
2.859375
3
[]
no_license
//This file is the file connectfourplusundo.h //This is the interface for the class ConnectFourPlusUndo #ifndef CONNECTFOURPLUSUNDO_H #define CONNECTFOURPLUSUNDO_H #include "connectfourplus.h" #include "connectfourabstract.h" #include<vector> namespace ConnectFour{ class ConnectFourPlusUndo : public ConnectFourPlus // inherit from ConnectFourPlus { public: ConnectFourPlusUndo(); // default constructor ConnectFourPlusUndo(int width, int height); //two parameter constructor ConnectFourPlusUndo& operator=(const ConnectFourPlusUndo & righSide); // assignment operator ConnectFourPlusUndo(const ConnectFourPlusUndo& otherOb); // copy constructor void setVec(); // this function set board size, after user load a file int setBoard(); // if user enter UNDO, this function undo board according to vector saved virtual int play(); // this function only play computer and change board virtual int play(const char columnChoice); // this function is changing board according to parameter only player mode virtual int playGame(); // game is playing in here. game mode, width, height etc. getting in this function. const int loadFile( const string fileName); // load file const int saveFile( const string fileName); // save file ~ConnectFourPlusUndo(); protected: vector<char>saved; // vector is keeping all column choice user's.(a,b,c,d etc.) // after user entered UNDO, vector calling, according to vector the last element, // game board change according to the last move //You can undo game board until beginning of the game. }; } #endif /* CONNECTFOURPLUSUNDO_H */
true
d712deb89b29e8e7ab25f019f89562afc6891bfa
C++
Rosovskyy/HeatConductivity
/headers/matrix.h
UTF-8
1,834
3.484375
3
[]
no_license
#ifndef HEATCONDUCT_MATRIX_H #define HEATCONDUCT_MATRIX_H #include <algorithm> class Matrix { private: double *matr = nullptr; int cols; int rows; public: Matrix(int rows, int cols){ this->rows = rows; this->cols = cols; matr = new double[rows*cols]; } double* getRowCopy(int row_inx){ auto *rowAr = new double[cols]; std::copy(&matr[row_inx * cols], &matr[row_inx * cols + cols], &rowAr[0]); return rowAr; } double* getRowPointer(int row_inx){ return &matr[row_inx * cols]; } void setMatr(double *mtr){ matr = mtr; } void setCopyMatr(double *mtr, size_t size){ std::copy(mtr, mtr + size, matr); } void setRow(const double *new_col, int row_num){ for (int i=0; i < cols; ++i){ matr[row_num * cols + i] = new_col[i]; } } double getEl(int row, int col){ return matr[row * cols + col]; } void setEl(double val, int row, int col){ matr[row * cols + col] = val; } int getAmountOfRows(){ return rows; } int getAmountOfCols(){ return cols; } double *retAr(){ return matr; } void free(){ delete matr; matr = nullptr; } void printContent(){ for (int i = 0; i < rows; ++i){ for (int j =0; j < cols; ++j){ std::cout << getEl(i,j) << " "; } std::cout << "\n"; } } double* rowsToArray(int f_row, int l_row){ auto res_ar = new double[(l_row-f_row)*cols]; for (int i=f_row*cols,j=0;i<l_row*cols; ++i,++j){ //std::cout << matr[i] << " "; res_ar[j] = matr[i]; } //std::cout << "\n"; return res_ar; } }; #endif //HEATCONDUCT_MATRIX_H
true
9fe1dcde50ffa23249258ac40acc18f303a64e13
C++
accountFlp/0223
/test/EventLoopThread_test.cpp
UTF-8
689
2.65625
3
[]
no_license
#include "mEventLoopThread.h" void test(){ std::cout<<"test"<<std::endl; } int main(){ std::cout<<BASE::getCurrentPthreadID()<<std::endl; net::mEventLoopThread t1,t2,t3; net::EventLoop *ev1=t1.startLoop(); net::EventLoop *ev2=t2.startLoop(); net::EventLoop *ev3=t3.startLoop(); ev1->runInThread(test); ev2->runInThread(test); ev3->runInThread(test); std::cout<<"eventloop thread id "<<ev1->currentThreadId()<<std::endl; std::cout<<"eventloop thread id "<<ev2->currentThreadId()<<std::endl; std::cout<<"eventloop thread id "<<ev3->currentThreadId()<<std::endl; sleep(10); ev1->stop(); ev2->stop(); ev3->stop(); return 0; }
true
8dac554ad340bd9a7eca4385bf8807255ac93f31
C++
isthatalex/semestral_work
/src/CWall.cpp
UTF-8
539
2.75
3
[]
no_license
// // Created by alexz on 5/8/18. // #include "CWall.h" #include <iostream> int CWall::cnt = 0; CWall::CWall(const char *textureName, int x, int y, int w, int h) : CGameObject(textureName, x, y, w, h) { } void CWall::collideWith(CHero &x) { x.setxVel() = 0; x.setyVel() = 0; std::cout << "Collision wall!!!" << std::endl; } std::string CWall::save2String() const { return std::to_string(m_xPos) + " " + std::to_string(m_yPos) + " " + std::to_string(destRect.w) + " " + std::to_string(destRect.h) + "\n"; }
true
84fc020903749243496438a8f82d88eeb25ad67a
C++
gpeal/Arduino
/libraries/ChLCD_MCP2300x/examples/HelloWorld/HelloWorld.ino
UTF-8
1,581
2.84375
3
[]
no_license
/* LiquidCrystal Library - Hello World Demonstrates the use a 16x2 LCD display. The LiquidCrystal library works with all LCD displays that are compatible with the Hitachi HD44780 driver. There are many of them out there, and you can usually tell them by the 16-pin interface. This sketch prints "Hello World!" to the LCD and shows the time. The circuit: * LCD RS pin to digital pin 4 * LCD Enable pin to digital pin 5 * LCD D4 pin to digital pin 0 * LCD D5 pin to digital pin 1 * LCD D6 pin to digital pin 2 * LCD D7 pin to digital pin 3 * 10K resistor: * ends to +5V and ground * wiper to LCD VO pin (pin 3) Library originally added 18 Apr 2008 by David A. Mellis library modified 5 Jul 2009 by Limor Fried (http://www.ladyada.net) example added 9 Jul 2009 by Tom Igoe http://www.arduino.cc/en/Tutorial/LiquidCrystal */ // include the library code: #include <Wire.h> #include "IOExpander.h" #include "MCP23009.h" #include "xLCD.h" // initialize the library with the numbers of the interface pins // pin assignments for one of my LCD adapters xLCD lcd(0x07, 6,5,4,3,2,1,0, 7); void setup() { Wire.begin(); // set up the LCD's number of rows and columns: lcd.begin(16, 2); // Print a message to the LCD. lcd.backlightOn(); lcd.print("hello, world!"); delay(1000); } uint8_t c; void loop() { c++; //lcd.command(c); delay(100); // set the cursor to column 0, line 1 // (note: line 1 is the second row, since counting begins with 0): lcd.setCursor(0, 1); // print the number of seconds since reset: lcd.print(millis()/100); }
true
df78cb68d994af1557102a3950f20da34eca09d9
C++
yyyeader/ACM
/HDU/HDU 2993 MAX Average Problem(斜率DP经典+输入输出外挂).cpp
WINDOWS-1252
934
2.53125
3
[]
no_license
#include<iostream> #include<cstring> #include<algorithm> #include<stdio.h> using namespace std; const int N=1e5+5; int q[N],head,tail; long long sum[N]; double Slope(int k,int j){ return double(sum[j]-sum[k])/(j-k); } // const int BUF=25000000; char Buf[BUF],*buf=Buf; template <class T> inline void read(T &a){ for(a=0;*buf<48;buf++); while(*buf>47) a=a*10+*buf++-48; } int main(){ int n,k; int tot=fread(Buf,1,BUF,stdin); while(1){ if(buf-Buf+1>=tot)break; read(n),read(k); for(int i=1;i<=n;i++){ read(sum[i]); sum[i]+=sum[i-1]; } double ans=0; head=tail=0; q[tail++]=0; for(int i=k;i<=n;i++){ while(head+1<tail&&Slope(q[head],i)<=Slope(q[head+1],i)){ head++; } ans=max(ans,Slope(q[head],i)); int j=i-k+1; while(head+1<tail&&Slope(q[tail-2],q[tail-1])>=Slope(q[tail-1],j)){ tail--; } q[tail++]=j; } printf("%.2f\n",ans); } return 0; }
true
6d2217db5acbaf0f4181895cece497e5b37743c3
C++
Seledriac/Aeroport
/src/Implementations/Passager.cpp
UTF-8
5,455
2.875
3
[]
no_license
// Auteurs : Tom BOUMBA et Antoine Zaug, promo L3 info à la FST de l'université de Limoges #ifndef Passager_H_ #include "../Headers/Passager.hpp" #endif #ifndef Reservation_H_ #include "../Headers/Reservation.hpp" #endif #ifndef Vol_H_ #include "../Headers/Vol.hpp" #endif #include <iostream> #include <fstream> list<Passager*> Passager::passagers; Passager::Passager(string nom, string prenom, string titre, string num_passeport, string mot_de_passe, int age) { this->nom = nom; this->prenom = prenom; this->titre = titre; this->num_passeport = num_passeport; this->mot_de_passe = mot_de_passe; this->age = age; } Passager* Passager::getPassager(string num_passeport, string mot_de_passe) { Passager* passager = NULL; for(list<Passager*>::const_iterator it = passagers.begin(); it != passagers.end(); it++) { if((*it)->num_passeport == num_passeport && (*it)->mot_de_passe == mot_de_passe) { passager = *it; break; } } return passager; } void Passager::nouveauPassager(string nom, string prenom, string titre, string num_passeport, string mot_de_passe, int age) { passagers.push_back(new Passager(nom, prenom, titre, num_passeport, mot_de_passe, age)); } bool Passager::ReserverVol(int num_vol) { bool a_pu_reserver = false; if(Vol::getVol(num_vol)->getNb_places() > 0) { reservations.push_back(new Reservation(this, Vol::getVol(num_vol))); a_pu_reserver = true; } return a_pu_reserver; } void Passager::ConfirmerReservation(int num_reservation) { Reservation::getReservation(num_reservation)->Confirmer(); } void Passager::AnnulerReservation(int num_reservation) { Reservation::getReservation(num_reservation)->Annuler(); } void Passager::AfficherListeVols(Destination* dest, Date* date) { cout << endl; list<Vol*> vols = Vol::getVols(); for(list<Vol*>::const_iterator it = vols.begin(); it != vols.end(); it++) { if((dest != NULL && date != NULL && (*it)->getDate() < date && (*it)->getDestination()->getVille_depart() == dest->getVille_depart() && (*it)->getDestination()->getVille_arrivee() == dest->getVille_arrivee()) || (dest != NULL && date == NULL && (*it)->getDestination()->getVille_depart() == dest->getVille_depart() && (*it)->getDestination()->getVille_arrivee() == dest->getVille_arrivee()) || (dest == NULL && date != NULL && (*it)->getDate() < date) || (dest == NULL && date == NULL)){ (*it)->afficherVol(); } } cout << endl; } void Passager::AfficherListeReservations() { cout << endl; for(vector<Reservation*>::const_iterator it = reservations.begin(); it != reservations.end(); it++) { (*it)->afficherReservation(); } cout << endl; } bool Passager::ExistenceVol(int num_vol) { bool vol_existe = false; list<Vol*> vols = Vol::getVols(); for(list<Vol*>::const_iterator it = vols.begin(); it != vols.end(); it++) { if((*it)->getNum_vol() == num_vol) { vol_existe = true; break; } } return vol_existe; } bool Passager::ExistenceReservation(int num_reservation) { bool reservation_existe = false; for(vector<Reservation*>::const_iterator it = reservations.begin(); it != reservations.end(); it++) { if((*it)->getNum_reservation() == num_reservation) { reservation_existe = true; break; } } return reservation_existe; } Passager* Passager::getPassager(string num_passeport) { for(list<Passager*>::const_iterator it = passagers.begin(); it != passagers.end(); it++) { if((*it)->num_passeport == num_passeport) { return (*it); } } return NULL; } list<Passager*> Passager::getPassagers() { list<Passager*> liste; for(list<Passager*>::const_iterator it = passagers.begin(); it != passagers.end(); it++) { liste.push_back(*it); } return liste; } string Passager::getNum_passeport() { return num_passeport; } string Passager::getPrenom() { return prenom; } string Passager::getNom() { return nom; } string Passager::getTitre() { return titre; } int Passager::getAge() { return age; } string Passager::getMot_de_passe() { return mot_de_passe; } void Passager::afficherPassager() { cout << num_passeport << " => " << prenom << " " << nom << " : " << titre << ", " << age << " ans" << endl; } void Passager::chargerPassagers() { fstream fichier_passagers; fichier_passagers.open("./src/donnees/Passagers.txt", ios::in); string line; if(fichier_passagers.is_open()) { while(getline(fichier_passagers, line)) { // Une ligne par administrateur string infos[6]; size_t start; size_t end = 0; int i = 0; while((start = line.find_first_not_of(":", end)) != std::string::npos) { end = line.find(":", start); infos[i] = line.substr(start, end - start); i++; } passagers.push_back(new Passager(infos[0], infos[1], infos[2], infos[3], infos[4], stoi(infos[5]))); } } else { cout << "Erreur lors de l'ouverture du fichier des administrateurs"; } fichier_passagers.close(); }
true
73857734915435e04df57e0c3c5bae3427994b18
C++
johnsonj/SimplyAcademic
/PrimitiveTypes/PrimitiveTypes.cpp
UTF-8
5,530
3.171875
3
[]
no_license
#include "stdafx.h" #include<cmath> #include<functional> #include<iostream> #include "TestSuite.h" #define CHAR_BIT 8 /******************************************* * Parity of a integer value * Even parity: 1011 = 1, 1001 = 0 ******************************************/ // This won't ever finish. sizeof(unsigned int) * CHAR_BIT is pretty big. bool parity_naive(unsigned int value) { bool parity = 0; for (int i = 0; i < pow(2, sizeof(unsigned int) * CHAR_BIT); i++) { if (value & 1) parity = !parity; value = value >> 1; } return parity; } bool parity_optimized(unsigned int value) { bool parity = 0; for (int i = 0; i < pow(2, sizeof(unsigned int) * CHAR_BIT); i++) { // We're out of 1's to analyze here // Note: x & ~(x-1) returns the lowest 1 if (!(value & ~(value - 1))) break; if (value & 1) parity = !parity; value = value >> 1; } return parity; } bool parity_very_optimized(unsigned int value) { bool parity = 0; while (value) { unsigned int lowest_one = (value & ~(value - 1)); while (lowest_one = lowest_one >> 1) value = value >> 1; if (value & 1) parity = !parity; value = value >> 1; } return parity; } // Warm up the cache and keep it internal. // in a real scenario this would live outside this method const int lookup_length = 256; const int lookup_size = 8; const int lookup_mask = 255; bool parity_lookup[lookup_length]; void parity_cached_warmup() { for (int i = 0; i < lookup_length; i++) { parity_lookup[i] = parity_optimized(i); } } bool parity_cached(unsigned int value) { bool parity = 0; for (int i = 0; i < pow(2, sizeof(unsigned int) * CHAR_BIT) / lookup_size; i++) { // We're out of 1's to analyze here // Note: x & ~(x-1) returns the lowest 1 if (!(value & ~(value - 1))) break; if (parity_lookup[value & lookup_mask]) parity = !parity; value = value >> lookup_size; } return parity; } void parity() { TestSuite<bool, unsigned int> runner; runner.AddTestCase(false, 0); runner.AddTestCase(true, 1); runner.AddTestCase(true, 11); runner.AddTestCase(true, 14); runner.AddTestCase(false, 10); runner.AddSolution("Optimized", parity_optimized); parity_cached_warmup(); runner.AddSolution("Cached Results", parity_cached); runner.AddSolution("Very Optimized", parity_very_optimized); runner.Execute(); } template<int R, int C> std::vector<int> spiral_fsm(int (A)[R][C], int width, int height) { using std::cout; using std::vector; int top = 0; int bottom = height - 1; int left = 0; int right = width - 1; int row = 0; int column = 0; enum STATES { LEFT, RIGHT, UP, DOWN }; STATES state = RIGHT; vector<int> result; for (int i = 0; i <= (width*height) + 2*(width-1) + 1; i++) { if (state == RIGHT) { if (column == right) { state = DOWN; top += 1; } else { result.emplace_back(A[row][column]); column += 1; } } else if (state == DOWN) { if (row == bottom) { state = LEFT; right -= 1; } else { result.emplace_back(A[row][column]); row += 1; } } else if (state == LEFT) { if (column == left) { state = UP; bottom -= 1; } else { result.emplace_back(A[row][column]); column -= 1; } } else if (state == UP) { if (row == top) { state = RIGHT; left += 1; } else { result.emplace_back(A[row][column]); row -= 1; } } } return result; }; template<int RC> void spiral_rings(const int (A)[RC][RC]) { for (int i = 0; i < (ceil((RC)/2)); i++) { print_single_ring<RC>(A, i); } // For odd sized matricies we need to print the center element // We can't print a ring of a single element if (RC % 2 == 1) { std::cout << std::to_string(A[(RC-1) / 2][(RC-1) / 2]); } std::cout << "\n"; }; template<int RC> void print_single_ring(const int(A)[RC][RC], int offset) { using std::cout; using std::to_string; if (RC % 2 == 1 && floor(RC / 2) == offset - 1) { cout << to_string(A[offset][offset]) << " "; return; } // Right // A[offset][offset] -> A[offset][ RC-offset - 1 ] for (int j = offset; j < (RC - offset - 1); j++) { cout << to_string(A[offset][j]) << " "; } // Down // A[offset][RC-offset] -> A[ RC-offset-1 ][RC-offset] for (int i = offset; i < (RC - offset - 1); i++) { cout << to_string(A[i][RC - offset - 1]) << " "; } // Left // A[RC-offset][RC-offset] -> A[RC-offset][ offset - 1 ] for (int j = RC - offset - 1; j > offset; j--) { cout << to_string(A[RC - offset - 1][j]) << " "; } // Up // A[RC-offset][offset] -> A[offset -1][offset] for (int i = RC - offset - 1; i > offset; i--) { cout << to_string(A[i][offset]) << " "; } }; void spiral() { using std::vector; using std::cout; int spiral_3x3[3][3] = { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 } }; spiral_rings<3>(spiral_3x3); cout << "\n"; int spiral_4x4[4][4] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; spiral_rings<4>(spiral_4x4); cout << "\n"; int spiral_5x5[5][5] = { { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 }, { 11, 12, 13, 14, 15 }, { 16, 17, 18, 19, 20 }, { 21, 22, 23, 24, 25 } }; spiral_rings<5>(spiral_5x5); cout << "\n"; /* vector<int> spiral_3x3_sln{ 0, 1, 2, 5, 8, 7, 6, 3, 4 }; TestSuite<vector<int>, int[3][3], int, int> test_3x3("3x3"); test_3x3.AddTestCase(spiral_3x3_sln, spiral_3x3, 3, 3); test_3x3.AddSolution("State Macine", spiral_fsm<3,3>); test_3x3.Execute(); */ ///TestSuite< } int _tmain(int argc, _TCHAR* argv[]) { spiral(); char f; std::cin >> f; }
true
1fe01141f7b5a6dadf2cb5cbb202c77361a3b6b3
C++
Xuloh/set09121-project
/src/Tilemap.h
UTF-8
2,738
2.90625
3
[ "MIT" ]
permissive
#pragma once #include <SFML/Graphics.hpp> #include <string> #include <memory> #include <unordered_map> #include <string> #include <vector> #include <Box2D/Box2D.h> namespace tilemap { // the different kinds of tiles enum Tile { EMPTY = ' ', START = 's', END = 'e', WALL = 'w', ENEMY = 'x', FLOOR = 'f' }; // A subclass of sf::Drawable and sf::Transformable that represents a tile map // it can load a map from a text file and render it to a sf::RenderTarget class Tilemap : public sf::Drawable, public sf::Transformable { public: // load a map from the given file path void load(const std::string& filePath); // set the texture to use as a tile set void setTexture(std::shared_ptr<sf::Texture> texture); // set the size of the tiles on screen void setTileSize(const sf::Vector2f& tileSize); // set the size of a single sprite in the tile set void setSpriteSize(const sf::Vector2u& spriteSize); // set the map that will be used to map a Tile to the index of its sprite in the tile set void setTileSpriteIndexMap(const std::unordered_map<Tile, unsigned>& map); // set the index of the sprite in the tile set for the given Tile to the given value void setTileSpriteIndex(Tile tile, unsigned index); // set the default sprite index in the tile set // it will be used for Tiles that don't have a specific sprite index void setDefaultSpriteIndex(unsigned defaultIndex); // get the tile at the given position in the map Tile getTile(sf::Vector2u position) const; // return the position of the given tile in the world sf::Vector2f getTilePosition(sf::Vector2u position) const; size_t getWidth() const; size_t getHeight() const; private: // properties used for rendering sf::VertexArray vertices; std::shared_ptr<sf::Texture> texture; sf::Vector2f tileSize; sf::Vector2u spriteSize; // properties of the actual tile map std::unique_ptr<Tile[]> tiles; size_t width = 0; size_t height = 0; // map to associate a tile and a sprite index std::unordered_map<Tile, unsigned> tileSpriteIndexMap; unsigned defaultSpriteIndex = 0; std::vector<b2Body*> bodies; void draw(sf::RenderTarget& target, sf::RenderStates states) const override; // build the vertex array void buildVertices(); // build the b2Bodies for the wall void buildBodies(); // update the size of the scene view to fit the tilemap void updateViewSize() const; }; }
true
fe44dc8f1975069625559d7eca90d9d927b51684
C++
joemulray/171-172
/171/CS 171 HW 5/CS 171 HW 5/main.cpp
UTF-8
6,335
2.859375
3
[]
no_license
#include <string> #include <iostream> #include <cstdlib> #include <cmath> #include <fstream> using namespace std; void introduction(istream &is, ostream &os, string target, string replacement) { string data,instruct; cout<<"Do you want instructions (y/n): "; os<<"Do you want instructions (y/n): "; cin>>instruct; os<<instruct<<endl; while((instruct.compare("y")==0) || instruct.compare("Y")==0) { string line; ifstream input; input.open("input.txt"); while(!input.eof()) { getline(input,data); cout<<data<<endl; os<<data<<endl; } cout<<"Do you want instructions (y/n): "; os<<"Do you want instructions (y/n): "; cin>>instruct; os<<instruct<<endl; } os<<endl; os<<"LUNAR LANDER"<<endl; os<<"Beginning landing procedure.........."<<endl; os<<"DIGBY wishes you good luck !!!!!!!"<<endl; cout<<endl; cout<<"LUNAR LANDER"<<endl; cout<<"Beginning landing procedure.........."<<endl; cout<<"DIGBY wishes you good luck !!!!!!!"<<endl; string in; while (getline(is, in)) { while (in.find(target) != -1) { in.replace(in.find(target), target.length(), replacement); in.find(target); } os << in; if(!is.eof()) { os<<"\n"; } } } void finalAnalysis(ostream &os, double velocity) { if (velocity <= 0) { cout << "Congratulations! A perfect landing!!" << endl ; cout << "Your license will be renewed.............later." << endl ; os << "Congratulations! A perfect landing!!" << endl ; os << "Your license will be renewed.............later." << endl ; } else if (velocity < 2) { cout << "A little bumpy." << endl ; os << "A little bumpy." << endl ; } else if (velocity < 5) { cout << "You blew it!!!!!!" << endl ; cout << "Your family will be notified..............by post." << endl ; os << "You blew it!!!!!!" << endl ; os << "Your family will be notified..............by post." << endl ; } else if (velocity < 10) { cout << "Your ship is a heap of junk !!!!!" << endl ; cout << "Your family will be notified..............by post." << endl ; os << "Your ship is a heap of junk !!!!!" << endl ; os << "Your family will be notified..............by post." << endl ; } else if (velocity < 30) { cout << "You blasted a huge crater !!!!!" << endl ; cout << "Your family will be notified..............by post." << endl ; os << "You blasted a huge crater !!!!!" << endl ; os << "Your family will be notified..............by post." << endl ; } else if (velocity < 50) { cout << "Your ship is a wreck !!!!!" << endl ; cout << "Your family will be notified..............by post." << endl ; os << "Your ship is a wreck !!!!!" << endl ; os << "Your family will be notified..............by post." << endl ; } else { cout << "You totaled an entire mountain !!!!!" << endl ; cout<< "Your family will be notified..............by post." << endl ; os << "You totaled an entire mountain !!!!!" << endl ; os << "Your family will be notified..............by post." << endl ; } } void touchdown(double &elapsedTime, double &velocity, double &burnAmount, double &height) { double alpha; alpha = (sqrt(pow(velocity,2)+height*(10-2*burnAmount))-velocity)/(5-burnAmount); elapsedTime += alpha; velocity = velocity + (5-burnAmount) * alpha; if(height<0) height=0; } void reportStatus(ostream &os, double elapsedTime, double height, double velocity, double fuel, string name) { cout<<"Status of your " <<name<< " spacecraft: "<<endl; cout<<"Time: "<<elapsedTime <<endl; cout<<"Height: "<<height<<endl; cout<<"Speed : " <<velocity<<endl; cout<<"Fuel Left: "<<fuel<<endl; cout<<endl; os<<"Status of your " <<name << " spacecraft: "<<endl; os<<"Time: "<<elapsedTime <<endl; os<<"Height: "<<height<<endl; os<<"Speed : " <<velocity<<endl; os<<"Fuel Left: "<<fuel<<endl; os<<endl; } void updateStatus(double &velocity, double burnAmount, double &fuelRemaining, double &height) { double v2 = velocity; velocity = velocity+5-burnAmount; height = height - (v2+velocity)/2; fuelRemaining=fuelRemaining-burnAmount; } int main() { double height=1000; double velocity=50; double fuelRemaining=150; double burnAmount=0; double elapsedTime=0; ofstream os; ifstream is; string name,inputfile; cout<<"Enter a file name to log session: "; cin>>inputfile; os.open(inputfile); introduction(is, os,"$SPACECRAFT", "APOLLO"); while (height > 0) { reportStatus(os, elapsedTime, height, velocity, fuelRemaining, "APOLLO"); if (fuelRemaining > 0) { cout << "Enter fuel burn amount: " ; os << "Enter fuel burn amount: " ; cin >> burnAmount ; os<<burnAmount<<endl; if( burnAmount < 0 ) burnAmount = 0; if( burnAmount > fuelRemaining ) burnAmount = fuelRemaining; } else { cout << "**** OUT OF FUEL ****" << endl ; burnAmount = 0; } updateStatus(velocity, burnAmount, fuelRemaining, height); elapsedTime++; } touchdown(elapsedTime, velocity,burnAmount, height); cout<<endl; cout<<"***** CONTACT *****"<<endl; cout<<"Touchdown at "<<elapsedTime<<" seconds."; cout<<"Landing Velocity = " << velocity<<endl; cout<<fuelRemaining<<" units of fuel remaining."<<endl; cout<<endl; os<<endl; os<<"***** CONTACT *****"<<endl; os<<"Touchdown at "<<elapsedTime<<" seconds."; os<<"Landing Velocity = " << velocity<<endl; os<<fuelRemaining<<" units of fuel remaining."<<endl; os<<endl; finalAnalysis(os, velocity); os.close(); return 0; }
true
56e88319f9be8081e6e7fccbfb0847a450e6aa67
C++
7phalange7/CP_Templates
/Sorting and Searching/Heap Sort.cpp
UTF-8
2,033
3.78125
4
[]
no_license
// HEAP SORT // Time Complexity - O (N * logN) // Space Complexity - O(1) // Stability - Unstable ( Only Quick, Selection, Heap are unstable, rest all are stable ) #include <bits/stdc++.h> using namespace std; // To heapify a subtree rooted with node i which is // an index in a[]. n is size of heap void heapify(int a[], int n, int i) { int largest = i; // Initialize largest as root int l = 2 * i + 1; // left = 2*i + 1 ( 0-based indexing ) int r = 2 * i + 2; // right = 2*i + 2 ( 0-based indexing ) // If left child is larger than root if (l < n && a[l] > a[largest]) largest = l; // If right child is larger than 'largest' so far if (r < n && a[r] > a[largest]) largest = r; // If largest is not root, then swap and heapify the affected subtree if (largest != i) { swap(a[i], a[largest]); // Recursively heapify the affected sub-tree heapify(a, n, largest); } } void heapSort(int a[], int n) { // Build heap for all nodes i which has childrens (rearrange array) // ( No use of calling heapify to leaf nodes i.e nodes i which has no child ) for (int i = n / 2 - 1; i >= 0; i--) heapify(a, n, i); // One by one extract an element from heap for (int i = n - 1; i > 0; i--) { // Move current root to end swap(a[0], a[i]); // call heapify on the reduced heap( now size of the heap is i and it is rooted at 0 ) heapify(a, i, 0); } } int main() { int n; cin >> n; int a[n]; for (int i = 0; i < n; i++) cin >> a[i]; // name of an array is a pointer pointing to the first element of the array, So when we pass array in // other function, it is always passed by reference. // Since array is always passed by reference in C++, so changes made in the array in other functions // will also reflect here. heapSort(a, n); // Printing the sorted array for (int i = 0; i < n; i++) cout << a[i] << " "; }
true
73ad4f67245aa1da7bc36dfd70893683cb7e9625
C++
patrick-han/raytracer
/rt/sphere.h
UTF-8
1,674
3.078125
3
[]
no_license
#ifndef SPHERE_H #define SPHERE_H #include "rtweekend.h" #include "hittable.h" /* * Child class for a hittable sphere object */ class sphere : public hittable { public: point3 center; double radius; shared_ptr<material> mat_ptr; sphere() { } sphere(point3 cen, double r, shared_ptr<material> m) : center(cen), radius(r), mat_ptr(m) { }; virtual bool hit(const ray&r, double t_min, double t_max, hit_record& rec) const override; }; /* * Requires: * Incoming ray, bounds for t, rec (hit_record) to be modified * * Effects: * Returns true if an intersection occurs, writes the appropriate information in rec */ bool sphere::hit(const ray&r, double t_min, double t_max, hit_record& rec) const { vec3 oc = r.origin() - center; // A - C auto a = r.direction().length_squared(); auto half_b = dot(oc, r.direction()); auto c = oc.length_squared() - radius * radius; auto discriminant = half_b * half_b - a * c; if (discriminant > 0) { auto root = sqrt(discriminant); auto temp = (-half_b - root) / a; if (temp < t_max && temp > t_min) { // Record the intersection's info + calculate normal rec.t = temp; rec.p = r.at(rec.t); // Point on the sphere vec3 outward_normal = (rec.p - center) / radius; rec.set_face_normal(r, outward_normal); rec.mat_ptr = mat_ptr; return true; } temp = (-half_b + root) / a; // Subtle difference: The other solution to the quadratic if (temp < t_max && temp > t_min) { rec.t = temp; rec.p = r.at(rec.t); vec3 outward_normal = (rec.p - center) / radius; rec.set_face_normal(r, outward_normal); rec.mat_ptr = mat_ptr; return true; } } return false; } #endif
true
384dd38df5b3e099dc8aae3571e332fab0affa6e
C++
lygstate/captive
/arch/common/include/dbt/support.h
UTF-8
1,582
2.625
3
[ "MIT" ]
permissive
/* SPDX-License-Identifier: MIT */ #pragma once #include <dbt/common.h> namespace captive { namespace arch { namespace dbt { namespace terrible { struct arg_match_struct { void *ptr; }; } } } } inline void *operator new(dbt_size_t, captive::arch::dbt::terrible::arg_match_struct *__p){return __p->ptr;} namespace captive { namespace arch { namespace dbt { enum class AllocClass { DATA, TRANSLATED_CODE }; class Support { public: // Object allocation helper template<class T, typename ... Args> T *alloc_obj(Args&& ... x) { // Allocate data storage for the object. terrible::arg_match_struct arg_match; arg_match.ptr = alloc(sizeof(T), AllocClass::DATA); // Invoke the constructor via a specialised form of placement new. return new (&arg_match)T(x...); } // Object release helper template<class T> void free_obj(T *ptr) { // Invoke the object's destructor. ptr->~T(); // Release the data memory. free(ptr, AllocClass::DATA); } virtual void assertion_fail(const char *msg) = 0; virtual void debug_printf(const char *fmt, ...) = 0; virtual dbt_u64 ticks() const { return 0; } virtual void *alloc(dbt_size_t size, AllocClass cls) = 0; virtual void *realloc(void *ptr, dbt_size_t new_size, AllocClass cls) = 0; virtual void free(void *ptr, AllocClass cls) = 0; virtual void debug_dump_mem() { }; virtual void memcpy(void *dest, const void *src, dbt_size_t size) = 0; }; } } }
true
4b7f57f9bf5959db2fb4501e1b23a16f2526438d
C++
theDreamBear/algorithmn
/leetcode/680.验证回文字符串-ⅱ.cpp
UTF-8
2,838
3.453125
3
[]
no_license
/* * @lc app=leetcode.cn id=680 lang=cpp * * [680] 验证回文字符串 Ⅱ */ #include <string.h> #include <algorithm> #include <iostream> #include <map> #include <queue> #include <set> #include <stack> #include <string> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> using namespace std; // @lc code=start class Solution { public: /* 怎么简化逻辑怎么来 1. 本身就是回文串 2. 删除某个字符变成回文串 */ bool checkValid(const char* str, int low, int high, int omit) { for (int i = low, j = high; i < j; ++i, --j) { if (i == omit) { ++i; } else if (j == omit) { --j; } if (i < j && str[i] != str[j]) { return false; } } return true; } /* 超时, 问题 1. 负数和 unsigned int 比较 需要强转 */ bool validPalindrome1(string s) { for (int i = -1; i < (int)s.size(); ++i) { if (checkValid(s.c_str(), 0, s.size() - 1, i)) { return true; } } return false; } /* 上面算法复杂了, 遍历一次 */ int missmatch_count = 0; bool validPalindrome(string s) { if (s.size() <= 1) { return true; } int i = 0, j = s.size() - 1; while (i < j) { if (s[i] == s[j]) { ++i; --j; } else { ++missmatch_count; if (missmatch_count > 1) { return false; } if (i + 1 < j) { // 左右都匹配递归, 左右都有可能 if (s[i] == s[j - 1] && s[i + 1] == s[j]) { // string l1 = s.substr(i, j - i); // string l2 = s.substr(i + 1, j - i); // if (validPalindrome(l1) || validPalindrome(l2)) { // return true; // } // 检查剩下的是否符合要求即可 if (checkValid(s.c_str(), i, j - 1, -1) || checkValid(s.c_str(), i + 1, j, -1)) { return true; } return false; } if (s[i] == s[j - 1]) { --j; } else { // 左右都不匹配 ++i; } } else { return true; } } } return true; } }; // @lc code=end int main() { string s = "aba"; cout << Solution{}.validPalindrome(s); }
true
f8946f47a269cb0b4f71be890df86d4ed192ddaa
C++
shining-yang/DSCPP
/src/05_StackLinkedListCustomized/05_StackLinkedListCustomized.cpp
UTF-8
661
2.953125
3
[]
no_license
// // Test case for stack // #include "StackLinkedListCustomized.h" using namespace DSCPP::Stack; int main(int argc, char* argv[]) { char x; StackLinkedListCustomized<char> s; s.Push('A').Push('B').Push('C').Push('D').Push('E'); cout << s << endl; s.Pop(x); cout << s << endl; s.Push('B'); s.Push('X'); cout << s << endl; s.Pop(x).Pop(x).Pop(x); cout << s << endl; s.Push('Y'); s.Shrink(); cout << s << endl; s.Push('X'); s.Shrink(); cout << s << endl; s.Pop(x).Pop(x).Pop(x); cout << s << endl; s.Shrink(); s.Pop(x).Pop(x); cout << s << endl; s.Shrink(); s.Push('A'); cout << s << endl; return 0; }
true
c729516cc6c0b02ea2776b7d9da67bfeaaf04792
C++
Airbroub2019/C-
/TP2/TP2_5/grille.hh
UTF-8
742
2.828125
3
[]
no_license
#pragma once #include <iostream> #include <vector> #include <array> #include <string> using coordonnee = signed int; enum class etatcellule { vivant, mort }; enum class structure { oscillateurligne, floraison, planeur, oscilateurcroix }; class grille { public: grille (coordonnee largeur, coordonnee longueur); void vider (); bool vivante (coordonnee x, coordonnee y); void generer (coordonnee x, coordonnee y); void afficher(); void ajouterstructure (structure s, coordonnee x, coordonnee y); int vivantes (coordonnee x, coordonnee y); void evolution (grille & g); private: coordonnee _longueur; coordonnee _largeur; std::vector <std::vector<etatcellule>> _grille; };
true
ec71d8f3ee7cc3681a743a296bdd42a2fabd5e5b
C++
matanaliz/ShellExt
/ExperimentalLogger/backtrace.cpp
UTF-8
384
2.625
3
[]
no_license
#include "backtrace.h" #include "backtrace_impl.h" #include <new> backtrace::backtrace() : m_impl(new (std::nothrow) backtrace_impl()) { } // Dtor cannot be defaulted with forward declarated class backtrace::~backtrace() { } std::string backtrace::callstack() { // Handle this in other way return m_impl ? m_impl->callstack() : "Unable to initialize backtrace implementation"; }
true
b5508268659114d0f25077fa3487a4b69a370136
C++
nethojs29/ProgramacionDeComputadoras
/buscaminas mas wapo, ya mero queda.cpp
UTF-8
7,052
2.671875
3
[]
no_license
#include <iostream> #include <stdio.h> #include <windows.h> #include <conio2.h> #include <ctime> #include <cstdlib> using namespace std; #define COLUMNAS 9 #define FILAS 9 #define SIN_BOMBA -2 #define BOMBA -1 #define SIN_JUGAR -3 #define ESTADO_PERDEDOR 0 #define ESTADO_GANADOR 1 #define ESTADO_EN_JUEGO 2 void Print(int,int,int[][FILAS],bool[][FILAS]); int Contar2(int,int,int[][FILAS]); void EstablecerNumeros(int[][FILAS]); void PrintAll(int[][FILAS]); void jugada(int,int,int[][FILAS],bool[][FILAS]); int ContarJugadas(bool[][FILAS]); void JugadaEnGrupo(int,int, int &,int&, int[][FILAS],bool[][FILAS]); bool GetMenu(); void IniciarJuego(int[][FILAS],bool[][FILAS]); void Moverse(unsigned short,unsigned short); int main(int argc, char** argv) { int campo[FILAS][COLUMNAS]; bool jugadas[FILAS][COLUMNAS]; bool cadena_valida = true; bool opt; do{ opt = GetMenu(); if (opt) IniciarJuego(campo, jugadas); }while(opt); } void IniciaArr(int campo[][FILAS], bool jugadas[][FILAS]){ for(int i = 0; i < FILAS; i++){ for(int j = 0; j < COLUMNAS; j++){ campo[i][j] = SIN_BOMBA; jugadas[i][j] = false; } } } void Moverse(unsigned short x,unsigned short y) { HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE); COORD coord = {x-1,y-1}; SetConsoleCursorPosition(handle,coord); } void AgregaBombas(int nbombas,int campo[][FILAS]){ int x,y; for (int i = 0; i < nbombas;++i){ x = rand()%FILAS; y = rand()%COLUMNAS; if (campo[x][y] != BOMBA) campo[x][y] = BOMBA; } } void Print(int x,int y,int campo[][FILAS], bool jugadas[][FILAS]){ int i,j; //system("cls"); Moverse(25,1); cout << "[x] 0 1 2 3 4 5 6 7 8" << endl; Moverse(25,2); cout << "------------------------------" << endl; for( i = 0; i < FILAS; ++i){ Moverse(25,3+i); cout << "[" << i << "]"; for(j = 0; j < COLUMNAS; ++j){ if(i==x && j==y) textcolor(RED); if( jugadas[i][j] ){ if( campo[i][j] == BOMBA){ cout << " * "; }else{ cout << " " << campo[i][j] << " "; } }else{ cout << " - "; } textcolor(WHITE); } cout << endl; } } int Contar2(int x, int y, int campo[][FILAS]){ int nbombas = 0; for(int i = x-1; i < x+2; i++){ for(int j = y-1; j < y+2; j++){ if( i >= 0 && i < FILAS && j >= 0 && j < COLUMNAS ){ if( campo[i][j] == BOMBA){ nbombas++; } } } } return nbombas; } void EstablecerNumeros(int campo[][FILAS]){ int i,j, numero; for( i = 0; i < FILAS; i++){ for(j = 0; j < COLUMNAS; j++){ if( campo[i][j] == SIN_BOMBA){ numero = Contar2(i,j, campo); campo[i][j] = numero; } } } } void PrintAll(int campo[][FILAS]){ for(int i = 0; i < FILAS; i++){ Moverse(26,3+i); for(int j = 0; j < COLUMNAS; j++){ if( campo[i][j] == BOMBA){ textcolor(RED); cout << " * "; textcolor(WHITE); }else{ cout << " " << campo[i][j] << " "; } } cout << endl; } } void jugada(int x, int y, int estado, int campo[][FILAS], bool jugadas[][FILAS]){ if( x >= 0 && x < FILAS && y >= 0 && y < COLUMNAS ){ jugadas[x][y] = true; if( campo[x][y] == BOMBA){ estado = ESTADO_PERDEDOR; } }else{ cout << "Imposible jugada" << endl; system("pause"); } } int ContarJugadas(bool jugadas[][FILAS]){ int numero = 0; for(int i = 0; i < FILAS; i++){ for(int j = 0; j < COLUMNAS; j++){ if ( jugadas[i][j]){ numero++; } } } return numero; } void JugadaEnGrupo(int x, int y, int &estado,int &njugadas, int campo[][FILAS], bool jugadas[][FILAS]){ njugadas++; if(campo[x][y]==0){ for(int i = x-1; i < x+2; i++){ for(int j = y-1; j < y+2; j++){ if(i>=0 && i< FILAS && j>=0 && j<COLUMNAS){ if( campo[i][j] == 0 && !jugadas[i][j]){ jugadas[i][j] = true; JugadaEnGrupo(i,j, estado,njugadas, campo, jugadas); }else{ if (!jugadas[i][j])njugadas++; jugadas[i][j] = true; } } } } } } /////////////////////////////////////////////////////////////////////////////// bool GetMenu(){ cout << "1. Jugar Buscaminas." << endl; cout << "0. Salir." << endl; char opt[30]; bool cadena_valida; do{ cadena_valida = true; cout << "Opci\xa2n: "; cin.getline(opt, 30); if ( (opt[0] == char(48) && opt[1]=='\0') || (opt[0] == char(49) && opt[1]=='\0') ); else cadena_valida = false; }while(!cadena_valida ); int n = opt[0] - 48; if (n == 1) return true; if (n == 0) return false; } void IniciarJuego(int campo[][FILAS], bool jugadas[][FILAS]){ int njugadas=0; int estado; int nbombas = -1; while( nbombas < 0 || nbombas > 70 ){ cout << "Numero de bombas: "; cin >> nbombas; } int opcion,x=0,y=0; estado = ESTADO_EN_JUEGO; IniciaArr(campo, jugadas); srand ( time(NULL) ); AgregaBombas( nbombas, campo ); EstablecerNumeros(campo); system("cls"); while( estado == ESTADO_EN_JUEGO){ Print(x,y,campo, jugadas); if( njugadas == ( FILAS*COLUMNAS - nbombas) ){ estado = ESTADO_GANADOR; } opcion = getch(); if (opcion == 'w' && x - 1 >= 0) --x; if (opcion == 's' && x + 1 <= COLUMNAS-1) ++x; if (opcion == 'a' && y - 1 >= 0) --y; if (opcion == 'd' && y + 1 <= FILAS-1) ++y; if (opcion == 'i'){ jugadas[x][y] = true; if( campo[x][y] == BOMBA){ estado = ESTADO_PERDEDOR; }else{ JugadaEnGrupo(x,y, estado,njugadas, campo,jugadas); } } } system("cls"); if( estado == ESTADO_PERDEDOR){ textcolor(RED); Moverse(35,1); cout << "Perdiste :c" << endl; textcolor(WHITE); cout << "Solucion: " << endl; PrintAll(campo); }else{ Moverse(33,1); textcolor(YELLOW); cout << "\xAD \xAD GANASTE !!" << endl; textcolor(WHITE); PrintAll(campo); } }
true
07a0bfbd3f622db663564bfc60f61617678bae34
C++
rgatkinson/ParticleDmxNeopixel
/src/Lumenizers/MorseCodeLuminance.h
UTF-8
5,553
2.71875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// // MorseCodeLuminance.h // #ifndef __MORSE_CODE_LUMINANCE_H__ #define __MORSE_CODE_LUMINANCE_H__ #include "Lumenizer.h" #include "MorseCode.h" #include "Util/Deadline.h" struct MorseCodeLuminance : Lumenizer { //---------------------------------------------------------------------------------------------- // State //---------------------------------------------------------------------------------------------- protected: enum class Message { None, QueensTrunk, // p34 Parrots, // p34 Pirates, // p34 HardISound, // p34 DontLetMeDown, // p35 IWill, // p36 DavidByrne, First = QueensTrunk, Last = DavidByrne, Default = DavidByrne, }; // https://en.wikipedia.org/wiki/Morse_code#Speed_in_words_per_minute static constexpr int msDotLengthMin = 50; static constexpr int msDotLengthDefault = 200; static constexpr int msDotLengthLast = 500; static constexpr float onLevel = 1.0f; static constexpr float offLevel = 0.0f; int _msDotLength = 0; Message _message = Message::None; LPCSTR _messageString = nullptr; int _encodingIndex = 0; std::vector<bool> _encodedMessage; Deadline _timer; //---------------------------------------------------------------------------------------------- // Construction //---------------------------------------------------------------------------------------------- public: MorseCodeLuminance(Duration duration = Duration::Infinite) : Lumenizer(Flavor::MorseCode, duration) { setMessage(Message::Default); setDotLength(msDotLengthDefault); } //---------------------------------------------------------------------------------------------- // Dmx //---------------------------------------------------------------------------------------------- protected: void setMessage(Message message) { if (_message != message) { _message = message; _messageString = messageString(message); _encodedMessage = MorseCode::encode(_messageString); INFO("MorseCode: message=\"%s\"", _messageString); resetMessage(); } } void setDotLength(int msDotLength) { if (_msDotLength != msDotLength) { INFO("_msDotLength = %d", msDotLength); _msDotLength = msDotLength; _timer = Deadline(_msDotLength); } } #define MESSAGE_LOOP " " static LPCSTR messageString(Message message) { switch (message) { case Message::DavidByrne: return "Hello, David Byrne!" MESSAGE_LOOP; case Message::QueensTrunk: return "Daddy, the Queen's trunk is here, on board the Neverland!" MESSAGE_LOOP; case Message::Parrots: return "Parrots? A flock of parrots?" MESSAGE_LOOP; case Message::Pirates: return "PIRATES! We've been taken over by pirates!" MESSAGE_LOOP; case Message::HardISound: return "Pirates! Oh, that hard i sound is so tricky" MESSAGE_LOOP; case Message::DontLetMeDown: return "MOLLY! The Wasp is bearing down on the Neverland! " "Soon as we catch you, steer clear of Black Stache and BRING THE TRUNK TO ME!" MESSAGE_LOOP; case Message::IWill: return "I will!" MESSAGE_LOOP; default: return "unknown message" MESSAGE_LOOP; } } #undef MESSAGE_LOOP public: void processDmxEffectSpeedControl(const DmxEffectSpeedControl& luminance) override { Lumenizer::processDmxEffectSpeedControl(luminance); if (luminance.speed() == 0) { setDotLength(msDotLengthDefault); } else { float speed = luminance.speedLevel(false); // not directional int msDotLength = scaleRangeDiscrete(1-speed, 0, 1, msDotLengthMin, msDotLengthLast+1); setDotLength(msDotLength); } if (luminance.control() == 0) { setMessage(Message::Default); } else { Message message = scaleRangeDiscrete(luminance.control(), 1, 255, Message::First, Message::Last); setMessage(message); } } //---------------------------------------------------------------------------------------------- // Looping //---------------------------------------------------------------------------------------------- public: void begin() override { Lumenizer::begin(); resetMessage(); } void loop() override { Lumenizer::loop(); if (_timer.hasExpired()) { // Set level accordingly if (_encodingIndex < (int)_encodedMessage.size()) { setCurrentLevel(_encodedMessage[_encodingIndex] ? onLevel : offLevel); } // Advance _encodingIndex++; if (_encodingIndex >= (int)_encodedMessage.size()) { _encodingIndex = 0; } _timer.reset(); } } void report() override { Lumenizer::report(); } protected: void resetMessage() { _encodingIndex = 0; _timer.expire(); } }; #endif
true
345aa4b53a2038795234483db09fc51ce744c707
C++
ArturZieba/CPPLearning
/Operators2/Operators2.cpp
UTF-8
1,092
4.09375
4
[]
no_license
#include <iostream> #include <algorithm> //For std::max bool approximatelyEqualAbsRel(double a, double b, double absEpsilon, double relEpsilon) { //Check if numbers are almost equal (needed when comparing numbers near zero) double diff{ std::abs(a - b) }; if (diff <= absEpsilon) return true; //If the above doesn't work go back to Knuth's algorithm return (diff <= (std::max(std::abs(a), std::abs(b)) * relEpsilon)); } int main() { //Pre-increment int x{ 5 }; int y = ++x; std::cout << x << ' ' << y << "\n\n"; //Post-increment int a{ 5 }; int b = a++; std::cout << a << ' ' << b << "\n\n"; //Conditional operator // c ? x : y -> if c is nonzero(true) then evaluate x, otherwise evaluate y //Example: int larger{}; if (x > y) larger = x; else larger = y; // = larger = (x > y) ? x : y; //Most universal way of comparing 2 really close floating numbers, though it should be reconsidered based on need std::cout << approximatelyEqualAbsRel(a - 1.0, 0.0, 1e-12, 1e-8); //Compate "almost 0.0" to 0.0 return 0; }
true
b170081e30d52e3d1516345795278517bd768a6c
C++
lucasmedeiros/praticasPLP
/pratica1/e3.cpp
UTF-8
1,383
3.015625
3
[]
no_license
#include <iostream> #include <string> using namespace std; int* split(string entrada, int size) { int* array = new int[size]; int j = 0; for (int i = 0; i < entrada.length(); ++i) { char atual = entrada[i]; if (atual != ' ') { array[j] = atual - 48; j++; } } return array; } int contaPontuacao(char pontuacoes[], int valores[], int questoes) { int soma = 0; for (int i = 0; i < questoes; i++) { if (pontuacoes[i] == 'V') { soma += valores[i]; } } return soma; } int main() { int questoes, participantes; string entrada, entrada2; cin >> questoes; int valores[questoes]; for (int i = 0; i < questoes; ++i) { cin >> valores[i]; } cin >> participantes; int vencedor = 1, pontuacao; int maiorPontuacao = 0; char pontuacoes[questoes]; for (int i = 0; i < participantes; ++i) { for (int j = 0; j < questoes; j++) { if (pontuacoes[j] != ' ') cin >> pontuacoes[j]; } pontuacao = contaPontuacao(pontuacoes, valores, questoes); // cout << pontuacao << " " << i + 1 << endl; if (pontuacao > maiorPontuacao) { maiorPontuacao = pontuacao; vencedor = i + 1; } } cout << vencedor << ":" << maiorPontuacao << endl; }
true
16d98fab1647c53cb39d2d48d6b4eba15eb2ef27
C++
RNaveen99/coding-practice
/practice-codes/target_sum.cpp
UTF-8
1,297
3.421875
3
[ "MIT" ]
permissive
/* * Author : Jatin Rohilla * Date : * * Editor : Dev c++ 5.11 * Compiler : g++ 5.1.0 * * Problem : Given an array of integers, return indices of the two numbers such that * they add up to a specific target.You may assume that each input would have * exactly one solution, and you may not use the same element twice. * * Approach : Use hashmap from STL * Pick one element from array, calculate its partner, find its partner in hashmap, * if found, result is found. * if not, add this element to hashmap * * Time complexity - O(n) * */ #include<iostream> #include<map> using namespace std; int main(){ int SIZE=15; int a[SIZE]={1,2,4,5,6,7,8,10,14,11,3,11,65,9,17}; int target=11; int n1,n2; bool flag=false; map<int, int>partner; map<int, int>::iterator it; for(int i=0; i<SIZE; ++i ){ int iPair= target-i; it=partner.find(iPair); if(it!= partner.end()){ n1=i; //n1=it->first; n2=iPair; //n2=it->second; flag=true; break; } else{ partner.insert(std::make_pair<int,int>(i,i)); } } if(flag){ cout<<"Pair is : "<<n1<<" and "<<n2; } else{ cout<<"No pair exists."; } return 0; }
true
c7d419555ca11a7368ca53df6f8d8fa1030b5f03
C++
patiwwb/placementPreparation
/LinkedList/DoublyCLLinsertdelete.cpp
UTF-8
10,303
3.796875
4
[]
no_license
#include<stdio.h> #include<stdlib.h> typedef struct node{ struct node *prev; int data; struct node *next; }cdll; cdll *head; void insert( int item ){ // First check if the item being inserted forms the first node. // if( head == NULL ){ head = ( cdll * )malloc( sizeof( cdll ) ); head -> prev = head; head -> data = item; head -> next = head; } else{ // Initialise a pointer temp to traverse the list. // cdll *temp = head; while( temp -> next != head ){ temp = temp -> next; } // now temp contains last node. // // Now take the element. // cdll *var = ( cdll * )malloc( sizeof( cdll ) ); temp -> next = var; var -> prev = temp; var -> data = item; var -> next = head; head -> prev = var; } printf("Element inserted.\n"); } // End of insert() function. // int deleteNode( int item ){ // Check if the list is empty or not. // if( head == NULL ){ printf("The list is empty.\n"); } else{ // To traverse the list, initialise the temp pointer. // cdll *temp = head; while( temp -> next != head ){ if( temp -> data == item ){ if( temp == head ){ cdll *prev_node = temp -> prev; cdll *next_node = temp -> next; prev_node -> next = next_node; next_node -> prev = prev_node; head = next_node; cdll *temp1 = temp; temp = head; } else{ cdll *prev_node = temp -> prev; cdll *next_node = temp -> next; prev_node -> next = next_node; next_node -> prev = prev_node; cdll *temp1 = temp; temp = head; free( temp1 ); } } else{ temp = temp -> next; } } if( temp -> data == item ){ // Since above while loop will not work for the last node. // if( temp -> prev == temp -> next ){ head = NULL; free( temp ); } else{ cdll *prev_node = temp -> prev; cdll *next_node = temp -> next; prev_node -> next = next_node; next_node -> prev = prev_node; cdll *temp1 = temp; temp = head; free( temp1 ); } } } return 0; } // End of delete() function. // int insertmid( int item, int index ){ // If the list is empty, simply add the element at first position. // if( head == NULL ){ insert( item ); } else{ // Initialise temp pointer and pos variable. // cdll *temp = head; int pos = 0; while( temp -> next != head ){ if( pos == index ){ if( temp -> prev == temp -> next ){ // Take the variable in random node. // cdll *var = ( cdll * )malloc( sizeof( cdll ) ); var -> data = item; head = var; head -> prev = temp; head -> next = temp; temp -> prev = head; temp -> next = head; // Element is inserted at 0th position. // break; } else{ // Now here check if the element is to be inserted at 0th position. // if( index == 0 ){ cdll *prev_node = head -> prev; cdll *next_node = head -> next; cdll *var = ( cdll * )malloc( sizeof( cdll ) ); var -> data = item; var -> next = temp; var -> prev = prev_node; temp -> prev = var; head = var; prev_node -> next = var; break; } else{ // first form the new node. // cdll *var = ( cdll * )malloc( sizeof( cdll ) ); var -> data = item; // Now new node's previous is temp -> prev and new node's next is temp itself. // var -> prev = temp -> prev; var -> next = temp; cdll *previous_node = temp -> prev; previous_node -> next = var; temp -> prev = var; break; } } } else{ pos += 1; temp = temp -> next; } } /* Now if temp == head, that means user wants to enter the element at last node. */ if( temp -> next == head ){ if( pos == index ){ // first form the new node. // cdll *var = ( cdll * )malloc( sizeof( cdll ) ); var -> data = item; // Now new node's previous is temp -> prev and new node's next is temp itself. // var -> prev = temp -> prev; var -> next = temp; cdll *previous_node = temp -> prev; previous_node -> next = var; temp -> prev = var; } } } return 0; } // End of insertmid() function. // void del_at_pos( int index ){ // First check if list is empty or not. // if( head == NULL ){ printf("The list is empty.\n"); } else{ // If there is only one element in the list. // if( head -> prev == head -> next ){ cdll *temp = head; head = NULL; free( temp ); } else{ // Here also if index is zero. // cdll *temp = head; int pos = 0; while( temp -> next != head ){ if( pos == index ){ if( index == 0 ){ head = head -> next; cdll *prev_node = temp -> prev; cdll *next_node = temp -> next; head -> prev = prev_node; prev_node -> next = head; free( temp ); break; } else{ cdll *prev_node = temp -> prev; cdll *next_node = temp -> next; prev_node -> next = temp -> next; next_node -> prev = prev_node; free( temp ); break; } } else{ pos += 1; temp = temp -> next; } } // Now if the element was to be inserted at last position. // if( temp -> next == head ){ if( pos == index ){ cdll *prev_node = temp -> prev; prev_node -> next = head; head -> prev = prev_node; free( temp ); } } } } } // End of del_at_pos() function. // void search( int item ){ // Check if the list is empty or not. // if( head == NULL ){ printf("The list is empty.\n"); } else{ // To traverse the list, initialise the temp pointer. // cdll *temp = head; int index = -1; while( temp -> next != head ){ index += 1; if( temp -> data == item ){ printf("Element found at index %d. \n", index); } temp = temp -> next; } index += 1; if( temp -> data == item ){ printf("Element found at index %d. \n", index); } } } // End of search() function. // void display(){ // Check if the list is empty or not. // if( head == NULL ){ printf("The list is empty.\n"); } else{ // To traverse the list, initialise the temp pointer. // cdll *temp = head; while( temp -> next != head ){ printf("%d\n", temp -> data); temp = temp -> next; } printf("%d\n", temp -> data); } } // End of display() function. // int main(){ head=NULL; int ch = 1; while( ch == 1 ){ printf("1. Insert.\n"); printf("2. Delete.\n"); printf("3. Search.\n"); printf("4. Display.\n"); printf("5. Exit.\n"); printf("6. Insert at a position.\n"); printf("7. Delete at a position.\n"); int x; printf("Enter choice: "); scanf("%d", &x); if( x == 1 ){ int elem; printf("Enter item: "); scanf("%d", &elem); insert( elem ); } else if( x == 2 ){ int elem; printf("Enter item: "); scanf("%d", &elem); deleteNode( elem ); } else if( x == 3 ){ int elem; printf("Enter item: "); scanf("%d", &elem); search( elem ); } else if( x == 4 ){ display(); } else if( x == 5 ){ ch = 0; } else if( x == 6 ){ // Take the position and the element. // int elem, pos; printf("Enter element: "); scanf("%d", &elem); printf("Enter position: "); scanf("%d", &pos); // Make a call to insertmid() function. // insertmid( elem, pos ); } else if( x == 7 ){ // Take the position only. // int pos; printf("Enter the position: "); scanf("%d", &pos); // Make a call to del_at_pos() function. // del_at_pos( pos ); } else{ printf("Invalid choice.\n"); } } return 0; } // End of main() function. //
true
6665179631716115653103d7f60c4c640f7af5d6
C++
fastbuild/fastbuild
/Code/Core/CoreTest/Tests/TestSemaphore.cpp
UTF-8
3,767
3.1875
3
[ "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// TestSempahore.cpp //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include "TestFramework/TestGroup.h" // Core #include <Core/Process/Semaphore.h> #include <Core/Process/Thread.h> // TestSemaphore //------------------------------------------------------------------------------ class TestSemaphore : public TestGroup { private: DECLARE_TESTS void CreateDestroy() const; void WaitForSignal() const; void WaitTimeout() const; #if defined( __WINDOWS__ ) void MaxCount() const; #endif // Internal helpers static uint32_t WaitForSignal_Thread( void * userData ); }; // Register Tests //------------------------------------------------------------------------------ REGISTER_TESTS_BEGIN( TestSemaphore ) REGISTER_TEST( CreateDestroy ) REGISTER_TEST( WaitForSignal ) REGISTER_TEST( WaitTimeout ) #if defined( __WINDOWS__ ) REGISTER_TEST( MaxCount ) #endif REGISTER_TESTS_END // CreateDestroy //------------------------------------------------------------------------------ void TestSemaphore::CreateDestroy() const { Semaphore s; } // WaitForSignal //------------------------------------------------------------------------------ void TestSemaphore::WaitForSignal() const { Semaphore s; // Create a thread which will signal the Semaphore Thread t; t.Start( WaitForSignal_Thread, "Test::WaitForSignal", &s ); // Wait or the expected signal count for ( size_t i = 0; i < 100; ++i ) { s.Wait(); } // Cleanup thread t.Join(); } // WaitForSignal_Thread //------------------------------------------------------------------------------ /*static*/ uint32_t TestSemaphore::WaitForSignal_Thread( void * userData ) { Semaphore * s = static_cast< Semaphore * >( userData ); s->Signal( 100 ); return 0; } // WaitTimeout //------------------------------------------------------------------------------ void TestSemaphore::WaitTimeout() const { const Timer t; Semaphore s; // Check for signalled { s.Signal(); const bool signalled = s.Wait( 1 ); // Wait 1ms TEST_ASSERT( signalled == true ); // Should be signalled (should not time out) } // Check for timeout { const bool signalled = s.Wait( 50 ); // Wait 50ms TEST_ASSERT( signalled == false ); // Should not be signalled (should time out) } // ensure some sensible time has elapsed TEST_ASSERT( t.GetElapsed() > 0.025f ); // 25ms (allow wide margin of error) } // MaxCount //------------------------------------------------------------------------------ #if defined( __WINDOWS__ ) void TestSemaphore::MaxCount() const { // Only Windows supports a signall count limit for Semaphores // Create sempahore with a max count Semaphore s( 1 ); // Signal with individual calls { // Signal more than the max count s.Signal(); // This should signal s.Signal(); // This should gracefully fail TEST_ASSERT( s.Wait( 1 ) == true ); // First wait should see signalled state TEST_ASSERT( s.Wait( 1 ) == false ); // Second wait should time out } // Signal with single call { // Signal more than the max count s.Signal( 2 ); // This should signal once TEST_ASSERT( s.Wait( 1 ) == true ); // First wait should see signalled state TEST_ASSERT( s.Wait( 1 ) == false ); // Second wait should time out } } #endif //------------------------------------------------------------------------------
true
581e0267094c80f2b119d67ebb46375f0e783f8e
C++
aaron-lii/algorithm_and_structure
/c++/算法transform.cpp
UTF-8
1,214
3.96875
4
[]
no_license
#include <iostream> #include <algorithm> #include <vector> /* * transform(iterator begin1, iterator end1, iterator begin2, _func); * 功能:将源容器值搬运到目标容器,并对值做func运算 * 参数:(源容器起始迭代器,源容器结束迭代器,目标容器起始迭代器,函数或函数对象) * 注意:目标容器要初始化大小为源容器大小 * 底层:for循环遍历源容器迭代器,解引用后调用func函数,将函数return的值直接等号赋值给目标容器迭代器 */ using namespace std; // 对于每个搬运的值乘以2 int trans(int val){ return val * 2; } // 打印vector值 void print_val(const vector<int> &v){ for(int i = 0; i < v.size(); i++){ cout << v[i] << " "; } cout << endl; } void test01(){ vector<int> v1; for(int i = 0; i < 10; i++){ v1.emplace_back(i); } vector<int> v2; //此处要用resize,开启空间并置初值为 0 //如果用reserve,只是申请内存,并没有开放赋值,无法往里拷贝 v2.resize(v1.size()); transform(v1.begin(), v1.end(), v2.begin(), trans); print_val(v1); print_val(v2); } int main() { test01(); }
true
10ca87bf68965589e1e9aa18cd5ea1d5cf2c1329
C++
kamalsinghy/CppProg
/Cpp_3.cpp
UTF-8
274
3.140625
3
[]
no_license
#include <iostream> using namespace std; int main() { int i = 100; int *iptr = &i; unique_ptr<int> ptr; ptr.reset(iptr); if (iptr == nullptr) { cout << "iptr is nullptr" << endl; } cout << iptr << endl; cout << *iptr << endl; }
true
cea621abbaf4a6f9bfcb0faab0e56b8105cfeee5
C++
miviwi/Hamil
/Hamil/include/yaml/document.h
UTF-8
1,217
2.890625
3
[]
no_license
#pragma once #include <common.h> #include <yaml/node.h> #include <string> #include <memory> #include <utility> namespace yaml { class Document { public: struct Error { public: Error(size_t line_, size_t column_, std::string&& reason_) : line(line_+1), column(column_+1), reason(std::move(reason_)) /* yaml_mark_t values are 0-based */ { } std::string what() const; const size_t line, column; const std::string reason; }; struct ParseError : public Error { public: using Error::Error; }; struct EmitError : public Error { public: using Error::Error; }; struct AliasError : public Error { public: using Error::Error; }; Document(); Document(const Node::Ptr& root); static Document from_string(const char *doc, size_t len); static Document from_string(const std::string& doc); std::string toString(); // returns the root element Node::Ptr get() const; // 'what' can contain either mapping keys or integer indices // separated by '.' (dots) to signify nested elements Node::Ptr get(const std::string& what) const; Node::Ptr operator()(const std::string& what) const { return get(what); } private: Node::Ptr m_root; }; }
true
f39627f5641b752ca6be80e88f635e841e63cc6f
C++
EmlynLXR/Hust
/C/实验8/源程序替换.cpp
GB18030
444
2.984375
3
[]
no_license
#include<stdio.h> #include<stdlib.h> int main(int argc, char* argv[]) { char ch; if(argc!=2){ printf("Arguments error!\n"); exit(-1); } if(freopen(argv[1],"r",stdin)==NULL){ /*ʹstdinָĿļ*/ printf("Can't open %s file!\n",argv[1]); exit(-1); } while((ch=getchar())!=EOF) /* stdinжַ */ putchar(ch); fclose(stdin); /* رstdin */ return 0; }
true
0874663adf7b7a0ec9166c140a90c12339a96dd8
C++
zinsmatt/Programming
/LeetCode/medium/Single_Number_II.cxx
UTF-8
580
2.625
3
[]
no_license
class Solution { public: int singleNumber(vector<int>& nums) { vector<int> count(32, 0); int res = 0; for (int i = 0; i < 32; ++i) { int count = 0; for (auto x : nums) { count += (x >> i) % 2; } count %= 3; if (i == 31 && count) { res -= 1ll << i; } else if (count) { res += 1ll << i; } } return res; } };
true
60f028ca1cfc4393b7be46c7aa213bea55382571
C++
adamsandwich/PAT_Basic-Level_Practise
/1070. 结绳(25).cpp
UTF-8
438
2.890625
3
[]
no_license
#include<iostream> #include<string> #include<vector> #include<algorithm> using namespace std; int main() { int n, sum; cin >> n; vector<int> len; for (int i = 0; i < n; i++) { int t; cin >> t; len.push_back(t); } sort(len.begin(), len.end()); int i = 0; sum = *len.begin(); for (vector<int>::iterator it = ++len.begin(); it != len.end(); it++) { sum = (sum + *it) / 2; } cout << sum; system("pause"); return 0; }
true
dbb1ba3952ad201a904fa69b75ec723ed319a06e
C++
cbshiles/storm
/sketch.hpp
UTF-8
455
3.015625
3
[]
no_license
#class Parent; #include "base.hpp" class Child { protected: Parent* _parent; }; class Parent : public Child { public: Parent(Parent* parent = NULL); inline void after(Parent* n) { if (_parent != NULL) _parent->swap(this, n); else n->before(this); } inline void before(Child* n) {_children.push_back(n);} protected: Node* _parent; std::vector<Child*> _children; int find(Child* n); void swap(Child* a, Child* b); }
true
df2f60cf5ea7bfadfbae054e84db4b8eaa312c29
C++
colinblack/game_server
/server/app/data/DataComponent.h
UTF-8
1,461
2.515625
3
[]
no_license
#ifndef DATA_COMPONENT_H_ #define DATA_COMPONENT_H_ #include "Kernel.h" struct DataComponent { uint8_t position; //在装备区的位置 uint8_t master; //主属性类型 uint8_t slave1; //副属性1类型 uint8_t slave2; //副属性2类型 uint8_t slave3; //副属性3类型 uint32_t ud; uint32_t uid; uint32_t compid; uint32_t level; uint32_t exp; uint32_t heroid; DataComponent(): position(0), master(0), slave1(0), slave2(0), slave3(0), ud(0), uid(0), compid(0), level(0), exp(0), heroid(0) { } void SetMessage(ProtoComponent::ComponentCPP * msg) { msg->set_compud(ud); msg->set_compid(compid); msg->set_level(level); msg->set_exp(exp); msg->set_heroid(heroid); msg->set_position(position); msg->set_master(master); msg->clear_slave(); //批量数组,添加前要先清除 { vector<uint8_t> vctsubs; AddtoVct(slave1) AddtoVct(slave2) AddtoVct(slave3) for(size_t i = 0; i < vctsubs.size(); ++i) { msg->add_slave(vctsubs[i]); } } } bool operator < (const DataComponent & oth) const { return exp < oth.exp; } }; class CDataComponent :public DBCBase<DataComponent, DB_COMPONET> { public: virtual int Get(DataComponent &data); virtual int Get(vector<DataComponent> &data); virtual int Add(DataComponent &data); virtual int Set(DataComponent &data); virtual int Del(DataComponent &data); }; #endif //DATA_COMPONENT_H_
true
7a77fcf3270f4cedbb99d3a31c78880d118e5ede
C++
rafaelGuasselli/estudo_cpp
/uri/iniciante/e1041.cpp
UTF-8
489
2.765625
3
[]
no_license
#include<iostream> using namespace std; int main(){ float x,y; cin >> x >> y; if(x == 0 && y == 0){ cout<<"Origem\n"; }else if(x == 0){ cout<<"Eixo Y\n"; }else if(y == 0){ cout<<"Eixo X\n"; }else if(x > 0){ if(y > 0){ cout<<"Q1\n"; }else{ cout<<"Q4\n"; } }else if(x < 0){ if(y > 0){ cout<<"Q2\n"; }else{ cout<<"Q3\n"; } } return 0; }
true
c45499cd3f495780f4f12016c840b9a8cbc0a0e7
C++
nikonikolov/c_compiler
/src/DataStructures/ArrayExpression.cpp
UTF-8
1,834
2.65625
3
[]
no_license
#include "ArrayExpression.h" ArrayExpression::ArrayExpression(BaseExpression* first_dim_mem, const int& line_in, const string& src_file_in) : BaseExpression(EXPR_array_expr, line_in, src_file_in) { dimension = new vector<BaseExpression*>; dimension->push_back(first_dim_mem); } ArrayExpression::~ArrayExpression(){ if(dimension!=NULL){ vector<BaseExpression*>::iterator it; for(it=dimension->begin(); it!=dimension->end(); ++it){ delete *it; } delete dimension; } } void ArrayExpression::push_back_mem(BaseExpression* expr_in){ if(dimension==NULL) dimension=new vector<BaseExpression*>; dimension->push_back(expr_in); } void ArrayExpression::pretty_print(const int& indent){ string white_space; white_space.resize(indent, ' '); cout<<white_space<<"{"; if(dimension!=NULL){ vector<BaseExpression*>::iterator it; vector<BaseExpression*>::iterator it_end = --(dimension->end()); for(it=dimension->begin(); it!=dimension->end(); ++it){ (*it)->pretty_print(0); if(it!=it_end) cout<<", "; } } cout<<"}"; } void ArrayExpression::renderasm(ASMhandle& context, ExprResult** dest /*=NULL*/){ for(int i=0; i<dimension->size(); i++){ ExprResult** result = new ExprResult*(NULL); ((*dimension)[i])->renderasm(context, result); (*dest)->load("$t0"); (*result)->load("$t1"); assembler.push_back(ss<<pad<<"sw"<<"$t1, "<<-(i*4)<<"($t0)"<<endl); } } BaseExpression* ArrayExpression::simplify(){ vector<BaseExpression*>::iterator it; for(it=dimension->begin(); it!=dimension->end(); ++it){ BaseExpression* tmp_expr=NULL; try{ tmp_expr = (*it)->simplify(); if(tmp_expr!=NULL){ delete (*it); (*it) = tmp_expr; } } catch(const int& exception_in){ (*it)->generate_error("Variable type expression not allowed for array value initialization"); } } return NULL; }
true
583ca4f386d5925e657ff98fdee8a6ce02a7a990
C++
Mikkareem/Coding-Programs
/geeksforgeeks/checkSortingRecursive.cpp
UTF-8
349
3.3125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; bool checkAsc(const vector<int>& a, int index) { if(index == a.size() - 1) return true; // Check for first 2 numbers, if true, recursively check next 2. return (a[index] < a[index+1]) && checkAsc(a, index + 1); } int main() { vector<int> a = {1, 2, 3, 4, 5, 6, 7, 8}; cout << checkAsc(a, 0); }
true
f5d66e3a7bf583b5cffc42b6696180e80ac74ec5
C++
mathnogueira/mips
/include/mips/instructions/instruction.hpp
UTF-8
1,268
3.21875
3
[ "MIT" ]
permissive
/** * \file instruction.hpp * * Arquivo contendo a estrutura abstrata que representa uma instrução qualquer * em uma arquitetura de 16 bits. * */ #pragma once #include <mips/core.hpp> #include <mips/units/control.hpp> #include <mips/flag.hpp> namespace MIPS { /** * Classe abstrata responsável por representar qualquer instrução em uma * arquitetura de 16 bits. * * \author Matheus Nogueira */ class Instruction { public: /** * Destroi a instrução. */ ~Instruction() {} /** * Método abstrato que deverá ser invocado para que uma instrução seja * executada pelo emulador. * * \return resultado de saída da instrução. */ virtual bit16_t execute() = 0; /** * Método utilizado para atualizar os sinais de controle do processador. * * \param control unidade de controle do processador. */ virtual void updateControl(ControlUnit &control) {} /** * Define a estrutura de flags da ALU. * * \param aluFlags flags da ALU. */ void setALUFlags(struct ALUFlags &aluFlags) { flags = &aluFlags; } protected: /** * Código da operação (opcode) da instrução. */ bit8_t opcode; /** * Flags da ALU. */ struct ALUFlags *flags; }; }; // namespace
true
056dd3f03ba281568d86c5e36e7130211efe46ac
C++
dekorlp/GDV
/spaceGame/erstesProjekt/PolygonGenerator.cpp
ISO-8859-1
17,340
2.5625
3
[]
no_license
#include <GL/freeglut.h> #include <GL/SOIL.h> #include <iostream> #include "PolygonGenerator.h" #define _USE_MATH_DEFINES #include <cmath> // Texturen werden geladen void PolygonGenerator::initPolygonGenerator() { hull = SOIL_load_OGL_texture("textures/hull.jpg", SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_MIPMAPS | SOIL_FLAG_INVERT_Y | SOIL_FLAG_NTSC_SAFE_RGB | SOIL_FLAG_COMPRESS_TO_DXT); if (hull == 0) { std::cout << "Textur Hull konnte nicht geladen werden" << std::endl; printf("SOIL loading error: '%s'\n", SOIL_last_result()); } carbon = SOIL_load_OGL_texture("textures/carbon.png", SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_MIPMAPS | SOIL_FLAG_INVERT_Y | SOIL_FLAG_NTSC_SAFE_RGB | SOIL_FLAG_COMPRESS_TO_DXT); if (carbon == 0) { std::cout << "Textur Carbon konnte nicht geladen werden" << std::endl; } } // Wrfel wird erstellt, raumschiffkrper, Rumpf void PolygonGenerator::createCube(GLfloat fSeitenL) { glBegin(GL_POLYGON); //Vorderseite glNormal3f(0.0f, 0.0f, 1.0f); // Normale wird gesetzt fr Beleuchtung glColor4f(1.0f, 1.0f, 1.0f, 1.0f); //BLAU glTexCoord2f(0, 0); glVertex3f(-fSeitenL / 2.0f, -fSeitenL / 2.0f, +fSeitenL / 2.0f); glTexCoord2f(1, 0); glVertex3f(+fSeitenL / 2.0f, -fSeitenL / 2.0f, +fSeitenL / 2.0f); glTexCoord2f(1, 1); glVertex3f(+fSeitenL / 2.0f, +fSeitenL / 2.0f, +fSeitenL / 2.0f); glTexCoord2f(0, 1); glVertex3f(-fSeitenL / 2.0f, +fSeitenL / 2.0f, +fSeitenL / 2.0f); glEnd(); glBegin(GL_POLYGON); //Rechte Seite glNormal3f(1.0f, 0.0f, 0.0f); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); //BLAU glTexCoord2f(0, 0); glVertex3f(+fSeitenL / 2.0f, -fSeitenL / 2.0f, +fSeitenL / 2.0f); glTexCoord2f(1, 0); glVertex3f(+fSeitenL / 2.0f, -fSeitenL / 2.0f, -fSeitenL / 2.0f); glTexCoord2f(1, 1); glVertex3f(+fSeitenL / 2.0f, +fSeitenL / 2.0f, -fSeitenL / 2.0f); glTexCoord2f(0, 1); glVertex3f(+fSeitenL / 2.0f, +fSeitenL / 2.0f, +fSeitenL / 2.0f); glEnd(); glBegin(GL_POLYGON); //Rueckseite glNormal3f(0.0f, 0.0f, -1.0f); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); //BLAU glTexCoord2f(0, 0); glVertex3f(+fSeitenL / 2.0f, +fSeitenL / 2.0f, -fSeitenL / 2.0f); glTexCoord2f(1, 0); glVertex3f(+fSeitenL / 2.0f, -fSeitenL / 2.0f, -fSeitenL / 2.0f); glTexCoord2f(1, 1); glVertex3f(-fSeitenL / 2.0f, -fSeitenL / 2.0f, -fSeitenL / 2.0f); glTexCoord2f(0, 1); glVertex3f(-fSeitenL / 2.0f, +fSeitenL / 2.0f, -fSeitenL / 2.0f); glEnd(); glBegin(GL_POLYGON); //Linke Seite glNormal3f(-1.0f, 0.0f, 0.0f); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); //BLAU glTexCoord2f(0, 0); glVertex3f(-fSeitenL / 2.0f, +fSeitenL / 2.0f, -fSeitenL / 2.0f); glTexCoord2f(1, 0); glVertex3f(-fSeitenL / 2.0f, -fSeitenL / 2.0f, -fSeitenL / 2.0f); glTexCoord2f(1, 1); glVertex3f(-fSeitenL / 2.0f, -fSeitenL / 2.0f, +fSeitenL / 2.0f); glTexCoord2f(0, 1); glVertex3f(-fSeitenL / 2.0f, +fSeitenL / 2.0f, +fSeitenL / 2.0f); glEnd(); glBegin(GL_POLYGON); //Deckflaeche glNormal3f(0.0f, 1.0f, 0.0f); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); //BLAU glTexCoord2f(0, 0); glVertex3f(-fSeitenL / 2.0f, +fSeitenL / 2.0f, +fSeitenL / 2.0f); glTexCoord2f(1, 0); glVertex3f(+fSeitenL / 2.0f, +fSeitenL / 2.0f, +fSeitenL / 2.0f); glTexCoord2f(1, 1); glVertex3f(+fSeitenL / 2.0f, +fSeitenL / 2.0f, -fSeitenL / 2.0f); glTexCoord2f(0, 1); glVertex3f(-fSeitenL / 2.0f, +fSeitenL / 2.0f, -fSeitenL / 2.0f); glEnd(); glBegin(GL_POLYGON); //Bodenflaeche glNormal3f(0.0f, -1.0f, 0.0f); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); //BLAU glTexCoord2f(0, 0); glVertex3f(-fSeitenL / 2.0f, -fSeitenL / 2.0f, -fSeitenL / 2.0f); glTexCoord2f(1, 0); glVertex3f(+fSeitenL / 2.0f, -fSeitenL / 2.0f, -fSeitenL / 2.0f); glTexCoord2f(1, 1); glVertex3f(+fSeitenL / 2.0f, -fSeitenL / 2.0f, +fSeitenL / 2.0f); glTexCoord2f(0, 1); glVertex3f(-fSeitenL / 2.0f, -fSeitenL / 2.0f, +fSeitenL / 2.0f); glEnd(); } void PolygonGenerator::createCockpit(GLfloat fSeitenL) { glBegin(GL_POLYGON); //Vorderseite glNormal3f(0.0f, 0.0f, 1.0f); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); //BLAU glTexCoord2f(0, 0); glVertex3f(-fSeitenL / 2.0f, -fSeitenL / 2.0f, +fSeitenL / 2.0f); glTexCoord2f(1, 0); glVertex3f(+fSeitenL / 2.0f, -fSeitenL / 2.0f, +fSeitenL / 2.0f); glTexCoord2f(1, 1); glVertex3f(+fSeitenL / 2.0f, +fSeitenL / 2.0f, +fSeitenL / 2.0f); glTexCoord2f(0, 1); glVertex3f(-fSeitenL / 2.0f, +fSeitenL / 2.0f, +fSeitenL / 2.0f); glEnd(); glBegin(GL_POLYGON); //Rechte Seite Unten glNormal3f(1.0f, -1.0f, 0.0f); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); //BLAU glTexCoord2f(0, 0); glVertex3f(+fSeitenL / 2.0f, -fSeitenL / 2.0f, +fSeitenL / 2.0f); glTexCoord2f(1, 0); glVertex3f(+fSeitenL / 2.0f, -fSeitenL / 2.0f, -fSeitenL / 2.0f); glTexCoord2f(1, 1); glVertex3f(+fSeitenL / 2.0f, +fSeitenL / 2.0f / 4, -fSeitenL / 2.0f); glTexCoord2f(0, 1); glVertex3f(+fSeitenL / 2.0f, +fSeitenL / 2.0f / 4, +fSeitenL / 2.0f); glEnd(); glBegin(GL_POLYGON); //Rechte Seite Oben glNormal3f(1.0f, 1.0f, 0.0f); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); //BLAU glTexCoord2f(0, 0); glVertex3f(+fSeitenL / 2.0f, +fSeitenL / 2.0f, -fSeitenL / 2.0f / 4); glTexCoord2f(1, 0); glVertex3f(+fSeitenL / 2.0f, +fSeitenL / 2.0f / 4, -fSeitenL / 2.0f); glTexCoord2f(1, 1); glVertex3f(+fSeitenL / 2.0f, +fSeitenL / 2.0f / 4, +fSeitenL / 2.0f); glTexCoord2f(0, 1); glVertex3f(+fSeitenL / 2.0f, +fSeitenL / 2.0f, +fSeitenL / 2.0f); glEnd(); glBegin(GL_POLYGON); //Rueckseite glNormal3f(0.0f, 0.0f, -1.0f); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); //BLAU glTexCoord2f(0, 0); glVertex3f(+fSeitenL / 2.0f, +fSeitenL / 2.0f / 4, -fSeitenL / 2.0f); glTexCoord2f(1, 0); glVertex3f(+fSeitenL / 2.0f, -fSeitenL / 2.0f, -fSeitenL / 2.0f); glTexCoord2f(1, 1); glVertex3f(-fSeitenL / 2.0f, -fSeitenL / 2.0f, -fSeitenL / 2.0f); glTexCoord2f(0, 1); glVertex3f(-fSeitenL / 2.0f, +fSeitenL / 2.0f / 4, -fSeitenL / 2.0f); glEnd(); glBegin(GL_POLYGON); //Linke Seite Unten glNormal3f(-1.0f, 0.0f, 0.0f); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); //BLAU glTexCoord2f(0, 0); glVertex3f(-fSeitenL / 2.0f, +fSeitenL / 2.0f / 4, -fSeitenL / 2.0f); glTexCoord2f(1, 0); glVertex3f(-fSeitenL / 2.0f, -fSeitenL / 2.0f, -fSeitenL / 2.0f); glTexCoord2f(1, 1); glVertex3f(-fSeitenL / 2.0f, -fSeitenL / 2.0f, +fSeitenL / 2.0f); glTexCoord2f(0, 1); glVertex3f(-fSeitenL / 2.0f, +fSeitenL / 2.0f / 4, +fSeitenL / 2.0f); glEnd(); glBegin(GL_POLYGON); //Linke Seite Oben glNormal3f(-1.0f, 1.0f, 0.0f); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); //BLAU glTexCoord2f(0, 0); glVertex3f(-fSeitenL / 2.0f, +fSeitenL / 2.0f, -fSeitenL / 2.0f / 4); glTexCoord2f(1, 0); glVertex3f(-fSeitenL / 2.0f, +fSeitenL / 2.0f / 4, -fSeitenL / 2.0f); glTexCoord2f(1, 1); glVertex3f(-fSeitenL / 2.0f, +fSeitenL / 2.0f / 4, +fSeitenL / 2.0f); glTexCoord2f(0, 1); glVertex3f(-fSeitenL / 2.0f, +fSeitenL / 2.0f, +fSeitenL / 2.0f); glEnd(); glDisable(GL_TEXTURE); glBegin(GL_POLYGON); // Scheibe glNormal3f(-1.0f, 0.0f, 0.0f); glColor4f(0.8f, 0.8f, 0.8f, 0.6f); //BLAU glTexCoord2f(0, 0); glVertex3f(+fSeitenL / 2.0f, +fSeitenL / 2.0f / 4, -fSeitenL / 2.0f); glTexCoord2f(1, 0); glVertex3f(+fSeitenL / 2.0f, +fSeitenL / 2.0f, -fSeitenL / 2.0f / 4); glTexCoord2f(1, 1); glVertex3f(-fSeitenL / 2.0f, +fSeitenL / 2.0f, -fSeitenL / 2.0f / 4); glTexCoord2f(0, 1); glVertex3f(-fSeitenL / 2.0f, +fSeitenL / 2.0f / 4, -fSeitenL / 2.0f); glEnd(); glEnable(GL_TEXTURE); glBegin(GL_POLYGON); //Deckflaeche glNormal3f(0.0f, 1.0f, 0.0f); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); //BLAU glTexCoord2f(0, 0); glVertex3f(-fSeitenL / 2.0f, +fSeitenL / 2.0f, +fSeitenL / 2.0f); glTexCoord2f(1, 0); glVertex3f(+fSeitenL / 2.0f, +fSeitenL / 2.0f, +fSeitenL / 2.0f); glTexCoord2f(1, 1); glVertex3f(+fSeitenL / 2.0f, +fSeitenL / 2.0f, -fSeitenL / 2.0f / 4); glTexCoord2f(0, 1); glVertex3f(-fSeitenL / 2.0f, +fSeitenL / 2.0f, -fSeitenL / 2.0f / 4); glEnd(); glBegin(GL_POLYGON); //Bodenflaeche glNormal3f(0.0f, -1.0f, 0.0f); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); //BLAU glTexCoord2f(0, 0); glVertex3f(-fSeitenL / 2.0f, -fSeitenL / 2.0f, -fSeitenL / 2.0f); glTexCoord2f(1, 0); glVertex3f(+fSeitenL / 2.0f, -fSeitenL / 2.0f, -fSeitenL / 2.0f); glTexCoord2f(1, 1); glVertex3f(+fSeitenL / 2.0f, -fSeitenL / 2.0f, +fSeitenL / 2.0f); glTexCoord2f(0, 1); glVertex3f(-fSeitenL / 2.0f, -fSeitenL / 2.0f, +fSeitenL / 2.0f); glEnd(); } // Die Flgel void PolygonGenerator::createPropeller(GLfloat fSeitenL) { glBegin(GL_POLYGON); //Vorderseite glNormal3f(0.0f, 0.0f, 1.0f); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); //BLAU glTexCoord2f(0, 0); glVertex3f(-fSeitenL / 2.0f, -fSeitenL / 2.0f, +fSeitenL / 2.0f); glTexCoord2f(1, 0); glVertex3f(+fSeitenL / 2.0f, -fSeitenL / 2.0f, +fSeitenL / 2.0f); glTexCoord2f(1, 1); glVertex3f(+fSeitenL / 2.0f, +fSeitenL / 2.0f, +fSeitenL / 2.0f); glTexCoord2f(0, 1); glVertex3f(-fSeitenL / 2.0f, +fSeitenL / 2.0f, +fSeitenL / 2.0f); glEnd(); glBegin(GL_POLYGON); //Rechte Seite Mitte glNormal3f(0.0f, 0.0f, 0.0f); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); //BLAU glTexCoord2f(0, 0); glVertex3f(+fSeitenL / 2.0f, -fSeitenL / 2.0f / 4, +fSeitenL / 2.0f); glTexCoord2f(1, 0); glVertex3f(+fSeitenL / 2.0f, -fSeitenL / 2.0f / 4, -fSeitenL / 2.0f); glTexCoord2f(1, 1); glVertex3f(+fSeitenL / 2.0f, +fSeitenL / 2.0f / 4, -fSeitenL / 2.0f); glTexCoord2f(0, 1); glVertex3f(+fSeitenL / 2.0f, +fSeitenL / 2.0f / 4, +fSeitenL / 2.0f); glEnd(); glBegin(GL_POLYGON); //Rechte Seite Oben glNormal3f(0.0f, 0.0f, 0.0f); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); //BLAU glTexCoord2f(0, 0); glVertex3f(+fSeitenL / 2.0f, +fSeitenL / 2.0f, -fSeitenL / 2.0f / 4); glTexCoord2f(1, 0); glVertex3f(+fSeitenL / 2.0f, +fSeitenL / 2.0f / 4, -fSeitenL / 2.0f); glTexCoord2f(1, 1); glVertex3f(+fSeitenL / 2.0f, +fSeitenL / 2.0f / 4, +fSeitenL / 2.0f); glTexCoord2f(0, 1); glVertex3f(+fSeitenL / 2.0f, +fSeitenL / 2.0f, +fSeitenL / 2.0f); glEnd(); glBegin(GL_POLYGON); //Rechte Seite Unten glNormal3f(0.0f, 0.0f, 0.0f); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); //BLAU glTexCoord2f(0, 0); glVertex3f(-fSeitenL / 2.0f, -fSeitenL / 2.0f, +fSeitenL / 2.0f); glTexCoord2f(1, 0); glVertex3f(-fSeitenL / 2.0f, -fSeitenL / 2.0f / 4, +fSeitenL / 2.0f); glTexCoord2f(1, 1); glVertex3f(-fSeitenL / 2.0f, -fSeitenL / 2.0f / 4, -fSeitenL / 2.0f); glTexCoord2f(0, 1); glVertex3f(-fSeitenL / 2.0f, -fSeitenL / 2.0f, -fSeitenL / 2.0f / 4); glEnd(); glBegin(GL_POLYGON); //Rueckseite glNormal3f(0.0f, 0.0f, -1.0f); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); //BLAU glTexCoord2f(0, 0); glVertex3f(+fSeitenL / 2.0f, +fSeitenL / 2.0f / 4, -fSeitenL / 2.0f); glTexCoord2f(1, 0); glVertex3f(+fSeitenL / 2.0f, -fSeitenL / 2.0f / 4, -fSeitenL / 2.0f); glTexCoord2f(1, 1); glVertex3f(-fSeitenL / 2.0f, -fSeitenL / 2.0f / 4, -fSeitenL / 2.0f); glTexCoord2f(0, 1); glVertex3f(-fSeitenL / 2.0f, +fSeitenL / 2.0f / 4, -fSeitenL / 2.0f); glEnd(); glBegin(GL_POLYGON); //Linke Seite Mitte glNormal3f(-1.0f, 0.0f, 0.0f); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); //BLAU glTexCoord2f(0, 0); glVertex3f(-fSeitenL / 2.0f, +fSeitenL / 2.0f / 4, -fSeitenL / 2.0f); glTexCoord2f(1, 0); glVertex3f(-fSeitenL / 2.0f, -fSeitenL / 2.0f / 4, -fSeitenL / 2.0f); glTexCoord2f(1, 1); glVertex3f(-fSeitenL / 2.0f, -fSeitenL / 2.0f / 4, +fSeitenL / 2.0f); glTexCoord2f(0, 1); glVertex3f(-fSeitenL / 2.0f, +fSeitenL / 2.0f / 4, +fSeitenL / 2.0f); glEnd(); glBegin(GL_POLYGON); //Linke Seite Unten glNormal3f(0.0f, 0.0f, 0.0f); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); //BLAU glTexCoord2f(0, 0); glVertex3f(+fSeitenL / 2.0f, -fSeitenL / 2.0f, +fSeitenL / 2.0f); glTexCoord2f(1, 0); glVertex3f(+fSeitenL / 2.0f, -fSeitenL / 2.0f / 4, +fSeitenL / 2.0f); glTexCoord2f(1, 1); glVertex3f(+fSeitenL / 2.0f, -fSeitenL / 2.0f / 4, -fSeitenL / 2.0f); glTexCoord2f(0, 1); glVertex3f(+fSeitenL / 2.0f, -fSeitenL / 2.0f, -fSeitenL / 2.0f / 4); glEnd(); glBegin(GL_POLYGON); //Linke Seite Oben glNormal3f(0.0f, 0.0f, 0.0f); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); //BLAU glTexCoord2f(0, 0); glVertex3f(-fSeitenL / 2.0f, +fSeitenL / 2.0f, -fSeitenL / 2.0f / 4); glTexCoord2f(1, 0); glVertex3f(-fSeitenL / 2.0f, +fSeitenL / 2.0f / 4, -fSeitenL / 2.0f); glTexCoord2f(1, 1); glVertex3f(-fSeitenL / 2.0f, +fSeitenL / 2.0f / 4, +fSeitenL / 2.0f); glTexCoord2f(0, 1); glVertex3f(-fSeitenL / 2.0f, +fSeitenL / 2.0f, +fSeitenL / 2.0f); glEnd(); glBegin(GL_POLYGON); // Scheibe Oben glNormal3f(-1.0f, 0.0f, 0.0f); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); //BLAU glTexCoord2f(0, 0); glVertex3f(+fSeitenL / 2.0f, +fSeitenL / 2.0f / 4, -fSeitenL / 2.0f); glTexCoord2f(1, 0); glVertex3f(+fSeitenL / 2.0f, +fSeitenL / 2.0f, -fSeitenL / 2.0f / 4); glTexCoord2f(1, 1); glVertex3f(-fSeitenL / 2.0f, +fSeitenL / 2.0f, -fSeitenL / 2.0f / 4); glTexCoord2f(0, 1); glVertex3f(-fSeitenL / 2.0f, +fSeitenL / 2.0f / 4, -fSeitenL / 2.0f); glEnd(); glBegin(GL_POLYGON); // Scheibe Oben glNormal3f(-1.0f, 0.0f, 0.0f); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); //BLAU glTexCoord2f(0, 0); glVertex3f(+fSeitenL / 2.0f, -fSeitenL / 2.0f / 4, -fSeitenL / 2.0f); glTexCoord2f(1, 0); glVertex3f(+fSeitenL / 2.0f, -fSeitenL / 2.0f, -fSeitenL / 2.0f / 4); glTexCoord2f(1, 1); glVertex3f(-fSeitenL / 2.0f, -fSeitenL / 2.0f, -fSeitenL / 2.0f / 4); glTexCoord2f(0, 1); glVertex3f(-fSeitenL / 2.0f, -fSeitenL / 2.0f / 4, -fSeitenL / 2.0f); glEnd(); glBegin(GL_POLYGON); //Deckflaeche glNormal3f(0.0f, 1.0f, 0.0f); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); //BLAU glTexCoord2f(0, 0); glVertex3f(-fSeitenL / 2.0f, +fSeitenL / 2.0f, +fSeitenL / 2.0f); glTexCoord2f(1, 0); glVertex3f(+fSeitenL / 2.0f, +fSeitenL / 2.0f, +fSeitenL / 2.0f); glTexCoord2f(1, 1); glVertex3f(+fSeitenL / 2.0f, +fSeitenL / 2.0f, -fSeitenL / 2.0f / 4); glTexCoord2f(0, 1); glVertex3f(-fSeitenL / 2.0f, +fSeitenL / 2.0f, -fSeitenL / 2.0f / 4); glEnd(); glBegin(GL_POLYGON); //Bodenflaeche glNormal3f(0.0f, -1.0f, 0.0f); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); //BLAU glTexCoord2f(0, 0); glVertex3f(-fSeitenL / 2.0f, -fSeitenL / 2.0f, -fSeitenL / 2.0f / 4); glTexCoord2f(1, 0); glVertex3f(+fSeitenL / 2.0f, -fSeitenL / 2.0f, -fSeitenL / 2.0f / 4); glTexCoord2f(1, 1); glVertex3f(+fSeitenL / 2.0f, -fSeitenL / 2.0f, +fSeitenL / 2.0f); glTexCoord2f(0, 1); glVertex3f(-fSeitenL / 2.0f, -fSeitenL / 2.0f, +fSeitenL / 2.0f); glEnd(); } void PolygonGenerator::createSphere(GLfloat r, int lats, int longs) { glColor4f(1.0f, 1.0f, 1.0f, 1.0f); //BLAU GLUquadricObj *quadObj; quadObj = gluNewQuadric(); gluQuadricDrawStyle(quadObj, GLU_FILL); gluQuadricNormals(quadObj, GLU_SMOOTH); gluSphere(quadObj, 0.2, 24, 4); } void PolygonGenerator::createCylinder(GLfloat radius, GLfloat height) { glColor4f(1.0f, 1.0f, 1.0f, 1.0f); //BLAU GLUquadricObj *quadObj; quadObj = gluNewQuadric(); gluQuadricDrawStyle(quadObj, GLU_FILL); gluQuadricNormals(quadObj, GLU_SMOOTH); gluCylinder(quadObj, 0.1, 0.1, 0.1, 24, 4); } void PolygonGenerator::createShip(GLfloat rotationSpeed) { glEnable(GL_TEXTURE_2D); glPushMatrix(); // Shuttle Cockpit glPushMatrix(); glTranslatef(-1.46, 0, 0); glRotatef(90, 0, 1, 0); glBindTexture(GL_TEXTURE_2D, hull); createCockpit(0.4); glPopMatrix(); // Shuttlekrper glPushMatrix(); glScalef(3,1,1); glTranslatef(-0.22,0,0); glBindTexture(GL_TEXTURE_2D, hull); createCube(0.4); glPopMatrix(); // Shuttle Hinten Flgel Rechts glPushMatrix(); glRotatef(-35, 0, 1, 0); glScalef(1.5, 0.5, 5); glTranslatef(-0.5, 0, -0.10); glBindTexture(GL_TEXTURE_2D, hull); createPropeller(0.4); glPopMatrix(); // Shuttle Hinten Flgel Links glPushMatrix(); glRotatef(215, 0, 1, 0); glScalef(1.5, 0.5, 5); glTranslatef(0.5, 0, -0.10); glBindTexture(GL_TEXTURE_2D, hull); createPropeller(0.4); glPopMatrix(); glRotatef(propellerRotationSpeed += rotationSpeed, 1, 0, 0); glPushMatrix(); // Halterung der Propeller glPushMatrix(); glTranslatef(-0.1, 0, 0); glRotatef(90, 0,1,0); glBindTexture(GL_TEXTURE_2D, hull); createCylinder(2, 0.4); glPopMatrix(); // Kugelabdeckung von der Halterung glPushMatrix(); glTranslatef(-0.1, 0, 0); glBindTexture(GL_TEXTURE_2D, hull); createSphere(2, 0.4, 10); glPopMatrix(); // Oberer Propeller glPushMatrix(); glScalef(0.1, 1, 0.1); glTranslatef(-0.2, 0.3, 0.0); glBindTexture(GL_TEXTURE_2D, carbon); createCube(0.4); glPopMatrix(); // Unterer Propeller Propeller glPushMatrix(); glScalef(0.1, 1, 0.1); glTranslatef(-0.2, -0.3, 0); glBindTexture(GL_TEXTURE_2D, carbon); createCube(0.4); glPopMatrix(); // Hinten rechter Propeller glPushMatrix(); glRotatef(90, 1,0,0); glScalef(0.1, 1, 0.1); glTranslatef(-0.2, -0.3, 0); glBindTexture(GL_TEXTURE_2D, carbon); createCube(0.4); glPopMatrix(); // Hinten linker Propeller glPushMatrix(); glRotatef(90, 1, 0, 0); glScalef(0.1, 1, 0.1); glTranslatef(-0.2, 0.3, 0); glBindTexture(GL_TEXTURE_2D, carbon); createCube(0.4); glPopMatrix(); glPopMatrix(); glPopMatrix(); glDisable(GL_TEXTURE_2D); }
true
52a7b5fb652690c387d5beea1c7156386a6a0cc3
C++
feel-coding/algorithm-practice
/이진탐색.cpp
UTF-8
341
2.71875
3
[]
no_license
#include <iostream> #include <algorithm> using namespace std; int arr[100005]; int main() { int n, q; cin >> n >> q; for (int i = 0; i < n; i++) { cin >> arr[i]; } int num; for (int i = 0; i < q; i++) { cin >> num; if (binary_search(arr, arr + n, num)) { cout << "YES\n"; } else { cout << "NO\n"; } } return 0; }
true
259b17dda129beae7e8350271a5fb521d94e849d
C++
DJWalker42/laserRacoon
/inc/adv/SparseMat.h
UTF-8
3,914
3.0625
3
[]
no_license
#ifndef SPARSEMAT_HPP #define SPARSEMAT_HPP #include <adv/row.hpp> #include <adv/mesh.hpp> #include <staticMatrix.hpp> #include <iomanip> namespace phys{ template<class T> class sparseMat; // transpose of a sparse matrix template<class T> const sparseMat<T> transpose(const sparseMat<T>&); // return the diagonal elements of a sparse matrix template<class T> const sparseMat<T> diagonal(const sparseMat<T>&); // Gauss-Seidel relaxation; x is overwriten with new iteration template<class T> void Gauss_Seidel(const sparseMat<T>& A, const std::vector<T>& f, std::vector<T>& x); // reverse Gauss-Seidel relaxation; x is overwriten with new iteration template<class T> void reverse_Gauss_Seidel(const sparseMat<T>& A, const std::vector<T>& f, std::vector<T>& x); // symmetric Gauss-Seidel relaxation; x is overwriten with new iteration template<class T> void symmetric_Gauss_Seidel(const sparseMat<T>& A, const std::vector<T>& f, std::vector<T>& x); template<class T> class sparseMat : public list<row<T>>{ public: sparseMat(size_t n = 0); sparseMat(size_t n, const T& a); /** Constructor using a mesh of triangles for the FEM */ sparseMat(mesh<triangle>&); ~sparseMat(){} // destructor const T operator() (size_t i, size_t j) const { return (*item[i])[j]; }// read the (i,j)th element int row_number() const { return number; }// number of rows int column_number() const; int order() const { return std::max(row_number(), column_number()); }// matrix order const sparseMat& operator+=(const sparseMat&); const sparseMat& operator-=(const sparseMat&); const sparseMat& operator*=(const T&); const sparseMat& truncate(double thresh); const sparseMat<T> factorize(double); const std::vector<T> forward_elimination(const std::vector<T>&)const; const std::vector<T> back_substitution(const std::vector<T>&)const; const std::vector<int> coarsen(double threshold = .05) const; const sparseMat<T> create_transfer(); friend const sparseMat operator*<T>(const sparseMat&, const sparseMat&); friend const sparseMat transpose<T>(const sparseMat&); friend const sparseMat diagonal<T>(const sparseMat&); friend void Gauss_Seidel<T>(const sparseMat&, const std::vector<T>&, std::vector<T>&); friend void reverse_Gauss_Seidel<T>(const sparseMat&, const std::vector<T>&, std::vector<T>&); friend void symmetric_Gauss_Seidel<T>(const sparseMat&, const std::vector<T>&, std::vector<T>&); }; // matrix plus matrix template<class T> const sparseMat<T> operator+(const sparseMat<T>&, const sparseMat<T>&); // matrix minus matrix template<class T> const sparseMat<T> operator-(const sparseMat<T>&, const sparseMat<T>&); // scalar times sparse matrix template<class T> const sparseMat<T> operator*(const T&, const sparseMat<T>&); // sparse matrix times scalar template<class T> const sparseMat<T> operator*(const sparseMat<T>&, const T&); // matrix times vector template<class T> const std::vector<T> operator*(const sparseMat<T>&, const std::vector<T>&); // sparse matrix times sparse matrix template<class T> const sparseMat<T> operator*(const sparseMat<T>&, const sparseMat<T>&); // vector, v, divided by main diagonal of a sparse matrix, A template<class T> const std::vector<T> operator/( const std::vector<T>& v, const sparseMat<T>& A ); // Jacobi relaxation; x is overwritten with new iteration. template<class T> void Jacobi( const sparseMat<T>& A, const std::vector<T>& f, std::vector<T>& x ); // ILU iterative lu solver. template<class T> void ILU( const sparseMat<T>& A, const sparseMat<T>& L, const sparseMat<T>& U, const std::vector<T>& f, std::vector<T>& x ); // prints a sparse matrix to screen; includes zero elements. template<class T> std::ostream& operator<<(std::ostream&, const sparseMat<T>&); } #include <adv/SparseMat.inl> #endif
true
daa39a495ce7b93904e6a525a533b11ffb99a740
C++
ahmethelvaci/datastructure
/linkedlist4_delete.cpp
UTF-8
2,058
3.46875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> struct n { int x; n * next; }; typedef n node; node * createNode(int x) { node * n; n = (node *) malloc(sizeof(node)); n->next = NULL; n->x = x; return n; } void bastir (node * r) { int i = 0; while (r != NULL) { printf("%d=>%d ", i, r->x); i++; r = r->next; } printf("\n----------\n"); } node * ekleSirali (node * r, int x) { if (r == NULL) { // linklist boşsa r = createNode(x); return r; } if (r->x > x) { // ilk elemandan küçükse durumu node * temp; temp = createNode(x); temp->next = r; return temp; // root değişiyor } node * iter = r; while (iter->next != NULL && iter->next->x < x) { iter = iter->next; } node * temp = createNode(x); temp->next = iter->next; iter->next = temp; return r; } node * sil(node * r, int x) { node * temp; node * iter = r; if (r->x == x) { // ilk elemansa temp = r->next; free(r); return temp; } while (iter->next != NULL && iter->next->x != x) { iter = iter->next; } if (iter->next == NULL) { // bulunamazsa printf("%d bulunamadı\n--------\n", x); return r; } temp = iter->next; iter->next = temp->next; free(temp); return r; } int main () { node * root; root = NULL; root = ekleSirali(root, 400); root = ekleSirali(root, 40); root = ekleSirali(root, 4); root = ekleSirali(root, 450); root = ekleSirali(root, 50); root = ekleSirali(root, 401); root = ekleSirali(root, 41); root = ekleSirali(root, 5); root = ekleSirali(root, 451); root = ekleSirali(root, 49); bastir(root); root = sil(root, 4); bastir(root); root = sil(root, 999); bastir(root); root = sil(root, 41); bastir(root); root = sil(root, 451); bastir(root); root = sil(root, 450); bastir(root); root = sil(root, 5); bastir(root); }
true
ba4e741c7a5a2e11c4c38fbdb3b24620af15887a
C++
lololalayoho/Algo_share
/20210215/평범한 배낭/lololalayoho.cpp
UTF-8
554
2.609375
3
[]
no_license
/* https://www.acmicpc.net/problem/12865 */ #include <iostream> #include <algorithm> #include <vector> using namespace std; int N, K; int DP[102][100002]; struct package { int w; int v; }; vector<package> v1; int main() { cin >> N >> K; for (int i = 0; i < N; i++) { package p; cin >> p.w >> p.v; v1.push_back(p); } for (int i = 0; i < v1.size(); i++) { for (int j = 0; j <= K; j++) { if (j - v1[i].w >= 0) DP[i + 1][j] = max(DP[i][j], v1[i].v + DP[i][j - v1[i].w]); else DP[i + 1][j] = DP[i][j]; } } cout << DP[N][K]; }
true
01957394ba539129336ab0f9d4153fa8138897de
C++
Exploratory-Studios/Fear-Of-The-Dark
/Code/EntityProjectile.cpp
UTF-8
2,889
2.53125
3
[]
no_license
#include "EntityProjectile.h" #include <XMLDataManager.hpp> #include "Singletons.h" EntityProjectile::EntityProjectile(glm::vec2 pos, unsigned int layer, unsigned int id) : Entity(pos, layer) { m_id = id; init(); } EntityProjectile::EntityProjectile(glm::vec2 pos, unsigned int layer, EntityIDs id) : Entity(pos, layer) { m_id = (unsigned int)id; init(); } void EntityProjectile::init() { m_type = XMLModule::EntityType::PROJECTILE; XMLModule::EntityProjectileData d = getEntityProjectileData(m_id); m_size = d.size; m_updateScript = d.updateScript; m_tickScript = d.tickScript; m_speed = d.speed; m_damage = d.damage; m_collideWithBlocks = d.collides; m_gravity = !d.floating; m_lifeTime = d.lifeTime; m_knockback = d.knockback; m_buffIDs = d.buffIDs; m_anim.init(d.animationID); } void EntityProjectile::init(SaveDataTypes::EntityProjectileData& data) { Entity::init(data); init(); } EntityProjectile::~EntityProjectile() { //dtor } void EntityProjectile::collideWithTiles() { if(m_collideWithBlocks) { std::vector<glm::vec2> positions; checkTilePosition(positions, m_position.x + m_size.x / 2.0f, m_position.y + m_size.y / 2.0f); if(positions.size() > 0) { // We did collide, destroy this Singletons::getEntityManager()->queueEntityToRemove(getUUID()); m_active = false; } } } bool EntityProjectile::collideWithOther(Entity* other) { bool collisionPossible = false; glm::vec2 otherPos = other->getPosition(); glm::vec2 otherSize = other->getSize(); float xDist = (otherPos.x + otherSize.x / 2.0f) - (m_position.x + m_size.x / 2.0f); if(std::abs(xDist) > (otherSize.x + m_size.x) / 2.0f) { return false; // Collision will no longer be possible } if(m_active) { float yDist = (otherPos.y + otherSize.y / 2.0f) - (m_position.y + m_size.y / 2.0f); if(std::abs(yDist) > (otherSize.y + m_size.y) / 2.0f) { return true; // As shown above, collision would be possible on the X axis, so return true. } // Else, we are colliding. if(other->getType() == XMLModule::EntityType::NPC || other->getType() == XMLModule::EntityType::PROJECTILE) { Singletons::getEntityManager()->queueEntityToRemove(this); m_active = false; } } return true; } void EntityProjectile::draw(BARE2D::BumpyRenderer* renderer, float time, int layerDifference, float xOffset) { if(m_draw) { glm::vec4 destRect = glm::vec4(m_position.x + (xOffset * CHUNK_SIZE), m_position.y, m_size.x, m_size.y); float depth = getDepth(); m_anim.draw(renderer, BARE2D::Colour(255, 255, 255, 255), destRect, depth, glm::normalize(m_velocity)); } } void EntityProjectile::onUpdate(float timeStep, unsigned int selfIndex) { if(m_lifeTime > 0.0f) { m_lifeTime -= timeStep; if(m_lifeTime <= 0.0f) Singletons::getEntityManager()->queueEntityToRemove(this); } } void EntityProjectile::onTick() { m_anim.tick(); }
true
055eddfe01e16756302eb021f6e1529db3650582
C++
AlexanderJFranco/DrinkType
/DrinkTypes.h
UTF-8
1,086
3.3125
3
[]
no_license
#include<iostream> using namespace std; class Drink{ //Parent Drink Class friend ostream& operator<<(ostream& os,const Drink& s); //Output overload for printing drinks to screen public: Drink(); virtual void GetDescription() const; const char * GetBeverageName() const; const char * GetCarbonation()const ; protected: //Variables made protected so they remain within scope of children class char * beverage_name; bool carbonated; }; class Juice: public Drink{ //Child Class Declarations public: Juice( char * beverage, bool carb,char * fruit); void GetDescription()const; const char * GetFruit()const; private: char * fruit_base; }; class Beer: public Drink{ public: Beer(char * beverage, bool carb,char * alcohol); void GetDescription()const; const char * GetAlcoholPercentage()const; private: char * alcohol_percentage; }; class Soda: public Drink{ public: Soda( char * beverage, bool carb); void GetDescription()const; };
true
72df84aeb2054edcec6f8ce2a079ac791d0fb308
C++
VukanJ/Chess
/ZobristHash.cpp
UTF-8
1,434
2.90625
3
[ "MIT" ]
permissive
#include "ZobristHash.h" ZobristHash::ZobristHash() { entries.resize(static_cast<size_t>(1e6)); hashSize = static_cast<size_t>(1e6); } ZobristHash::ZobristHash(size_t _hashSize) { entries.resize(_hashSize); hashSize = _hashSize; } ZobristHash::entry& ZobristHash::getEntry(const U64& key) { //cout << hex << key % hashSize << dec << endl; return entries[key % hashSize]; } int ZobristHash::getValue(const U64& key) const { return entries[key % hashSize].value; } bool ZobristHash::isRepetition(const U64& key, int depth) const { // Stored node was found again at greater depth => Repetition auto& entry = entries[key % hashSize]; return entry.search_depth != -1 && entry.search_depth <= depth; } void ZobristHash::clear() { for (auto& entry : entries) { // Invalidate entry: entry = ZobristHash::entry(); } } ZobristHash::entry::entry() : value(-oo), search_depth(-1), flags(0x0), terminal(0), d(0) {} // Class PVTable PVTable::PVTable() { pventries.resize(static_cast<size_t>(3e6)); hashSize = static_cast<size_t>(3e6); } PVTable::PVTable(size_t size) { pventries.resize(size); hashSize = size; } void PVTable::addPVMove(const U64& key, const Move& move) { auto index = key % hashSize; pventries[index].bestmove = move; } PVTable::PVEntry& PVTable::operator[](const U64& key) { return pventries[key % hashSize]; } void PVTable::clear() { for (auto& entry : pventries) entry.bestmove = Move(); }
true
d66c449e57187dda279e67c374476ac9dbbde9e6
C++
Jorgespidy/Labs_Digital2
/Laboratorio5/Lab5/Lab5.ino
UTF-8
4,108
3.09375
3
[]
no_license
//Universidad del Valle de Guatemala //Departamento de Ingenieria Mecatronica y Electronica //Digital 2 - Seccion 20 //Jorge Castillo - 18209 // se incluyen las librerias #include <SPI.h> #include <SD.h> // defino mis variables File archivo; File root; int opcion; void opciones(void); void mostrar(void); void setup() { Serial.begin(115200); SPI.setModule(0); Serial.print("Initializing SD card..."); pinMode(PA_3, OUTPUT); if (!SD.begin(PA_3)) {//PA_3 es el CS Serial.println("initialization failed"); return; } Serial.println("initialization done."); opciones(); } void loop() { if (Serial.available() > 0){ opcion = Serial.read(); delay(250); if (opcion == '1' || opcion == '2' || opcion == '3' || opcion == '4' ){ mostrar(); } else { Serial.println("Por favor ingrese otro numero "); } } } void opciones(void) { Serial.println(); Serial.println("Las figuras disponibles para desplegar son: "); root = SD.open("/"); printDirectory(root, 0); root.close(); Serial.println("Ingrese el numero de imagen que quiere visualizar: \n 1 -> Calabaza \n 2 -> Corazon \n 3 -> Dino \n 4 -> Ghost"); } void printDirectory(File dir, int numTabs) { while(true) { File entry = dir.openNextFile(); if (! entry) { // no more files break; } for (uint8_t i=0; i<numTabs; i++) { Serial.print('\t'); } Serial.print(entry.name()); if (entry.isDirectory()) { Serial.println("/"); printDirectory(entry, numTabs+1); } else { // files have sizes, directories do not Serial.print("\t\t"); Serial.println(entry.size(), DEC); } entry.close(); } } void mostrar(void){ switch (opcion){ case '1': archivo = SD.open("Calabaza.txt"); if (archivo) { // read from the file until there's nothing else in it: while (archivo.available()) { Serial.write(archivo.read()); } // close the file: archivo.close(); } else { // if the file didn't open, print an error: Serial.println("error opening document"); } Serial.println("Ingrese el numero de imagen que quiere visualizar: \n 1 -> Calabaza \n 2 -> Corazon \n 3 -> Dino \n 4 -> Ghost"); break; case '2': archivo = SD.open("Corazon.txt"); if (archivo) { // read from the file until there's nothing else in it: while (archivo.available()) { Serial.write(archivo.read()); } // close the file: archivo.close(); } else { // if the file didn't open, print an error: Serial.println("error opening document"); } Serial.println("Ingrese el numero de imagen que quiere visualizar: \n 1 -> Calabaza \n 2 -> Corazon \n 3 -> Dino \n 4 -> Ghost"); break; case '3': archivo = SD.open("Dino.txt"); if (archivo) { // read from the file until there's nothing else in it: while (archivo.available()) { Serial.write(archivo.read()); } // close the file: archivo.close(); } else { // if the file didn't open, print an error: Serial.println("error opening document"); } Serial.println("Ingrese el numero de imagen que quiere visualizar: \n 1 -> Calabaza \n 2 -> Corazon \n 3 -> Dino \n 4 -> Ghost"); break; case '4': archivo = SD.open("Ghost.txt"); if (archivo) { // read from the file until there's nothing else in it: while (archivo.available()) { Serial.write(archivo.read()); } // close the file: archivo.close(); } else { // if the file didn't open, print an error: Serial.println("error opening document"); } Serial.println("Ingrese el numero de imagen que quiere visualizar: \n 1 -> Calabaza \n 2 -> Corazon \n 3 -> Dino \n 4 -> Ghost"); break; } }
true
fb1f5a50e93d531166f8446cbdefe19f2930ea85
C++
levifussell/Olive_ASCII-Game-Engine-
/Screen/ScreenBuffer.h
UTF-8
941
2.828125
3
[ "MIT" ]
permissive
#ifndef SCREEN_BUFFER #define SCREEN_BUFFER #include<iostream> #include "../Objects/GameObject.h" #include "../DataStructures/LinkedList.h" #include "Colors/colors.hpp" class ScreenBuffer { private: const unsigned int borderSize = 4; int width; int height; ColorType backgroundColor; char** screen; char** screenOld; ColorType** screenColor; ColorType** screenColorOld; LinkedList<GameObject> objectBufferList; bool changeInBuffer; public: ScreenBuffer(int width, int height, ColorType backgroundColor); ~ScreenBuffer(); void drawBorder(); void clear(bool allStates); void addToBuffer(GameObject* obj); void addAllGameObjectsToBuffer(); void clearBuffer(); void drawAtPoint(char pixel, int posX, int posY, char* colorForeground, char* colorBackground); void draw(); int getScreenWidth(); int getScreenHeight(); bool getChangeInBuffer(); }; #endif
true
24ab8aeb9327534a3bf0df19dc9418911280de90
C++
maxtla/Project-Disaster
/Light.h
UTF-8
964
2.765625
3
[]
no_license
#pragma once #ifndef LIGHT_H #define LIGHT_H #include <DirectXMath.h> #include <d3d11.h> using namespace DirectX; enum LightTypes { POINT_LIGHT, DIRECTIONAL_LIGHT }; class Light { private: __declspec(align(16)) struct LightType { DirectX::XMVECTOR lightPosOrDir; DirectX::XMVECTOR lightColor; DirectX::XMVECTOR ambientLight; }; ID3D11Buffer * m_lightBuffer; int type; XMVECTOR focusPoint; XMMATRIX lightView; XMMATRIX lightProjection; void makeMatrices(LightType &light); public: Light(); ~Light(); bool initLightBuffer(ID3D11Device * pDev, int type, XMVECTOR posOrDir, XMVECTOR color, XMVECTOR ambient, XMVECTOR focusPoint); void Release(); ID3D11Buffer * getLightBuffer() { return this->m_lightBuffer; } int getType() const { return this->type; } XMMATRIX getLightView() { return this->lightView; } XMMATRIX getLightProjection() { return this->lightProjection; } }; #endif // !LIGHT_H
true
3cc7713e1ec289611015f95c4fd7f163da9851d4
C++
MrGarrowson/A01018714_Ayms18
/Actividades/A4.2/Observer/observer.cpp
UTF-8
846
3.484375
3
[]
no_license
#include <vector> #include <string> virtual class Observer() { public: std::string name; Observer(std::string n){ name = n; } virtual void update(std::String c){ printf(" %s",c); } } virtual class Subject() { public: std:: vector <Observer> VO; std:: string name; std:: string message; void attach(Observer o){ VO.push_back(o); } void detach(Observer o){ for(Observer i: VO){ if(i.name=o.name) VO.erase (i); } } void notifyAll(std::string c){ for(Observer i : VO){ i.update(c); } } } class ConcreteObvs : public Observer{ public: std::string name; ConcreteObvs(std::string s){ name = s; } void publicar(std::string s) printf(" %s dice: %s\n",name,s); } class ConcreteSubject : public Subject{ public: std::string name; } int main(){ }
true
87d20b06a5887cb01bde4d6500aa57631d1c764a
C++
ajunior/cp
/uri/Cpp/2003.cpp
UTF-8
586
3.515625
4
[]
no_license
#include <iostream> using namespace std; int main() { int h, m, delayed_h, delayedInMinutes; while (scanf("%d:%d", &h, &m) != EOF) { delayed_h = h + 1; // Incrementando uma hora, devido o delay máximo que é de 60 minutos. // 8 é o literal para a hora marcada do encontro dos amigos no terminal if (delayed_h > 8) delayedInMinutes = ((delayed_h - 8) * 60) + m; else if (delayed_h == 8) delayedInMinutes = m; else delayedInMinutes = 0; cout << "Atraso maximo: " << delayedInMinutes << "\n"; } return EXIT_SUCCESS; }
true
49ed290cf605abc86ae03d5d7ec6f5e327075505
C++
ran16/snake-game-Ncurses
/fruit_doublePoints.cpp
UTF-8
496
2.5625
3
[]
no_license
#include "fruit_doublePoints.h" #include <ncurses.h> fruit_doublePoints::fruit_doublePoints(snake* snake): fruit(snake){} void fruit_doublePoints::takeEffect(player* nplayer, snake* nsnake){ nsnake -> grow(); //increase snake length by 1 nplayer -> setScore(2); //increase score by 2 nsnake ->setSpeed(5); //5 is a normal speed. 1-slowest, 10 -fastest } char fruit_doublePoints::drawFruit(){ mvaddch(getPos().y,getPos().x,'*'); return '*'; } fruit_doublePoints:: ~fruit_doublePoints(){}
true
3e0eb15b5b4657bc60ec9409735724807eb5f830
C++
TechnionTDK/cq-random-enum
/CQs/Q2_N/files/Q2_N__N_Parcel.h
UTF-8
2,691
2.625
3
[]
no_license
#ifndef RANDOMORDERENUMERATION_Q2_N__N_PARCEL_H #define RANDOMORDERENUMERATION_Q2_N__N_PARCEL_H #include <iostream> #include <chrono> #include "../../AbstractDatabase/Table.h" #include "../../AbstractDatabase/SplitTable.h" #include <boost/functional/hash.hpp> #include "Q2_N__R_Parcel.h" #ifdef PROJECTION_Q2_N #endif using namespace std; struct Q2_N__N_Key { //data int nationKey; //end-data void print() const { cout << "{" << nationKey << "}"; } }; struct Q2_N__N_Parcel { //data int nationKey; int regionKey; //end-data //construction static Q2_N__N_Parcel from(string line) { size_t pos; pos = line.find("|"); int nationKey = stoi(line.substr(0, pos)); line = line.substr(pos+1, string::npos); for(int _i = 0; _i < 1; _i++) { pos = line.find("|"); line = line.substr(pos + 1, string::npos); } pos = line.find("|"); int regionKey = stoi(line.substr(0, pos)); return {nationKey, regionKey}; } template<typename T> T to() const { throw runtime_error("not implemented"); } void print() const { cout << "{" << nationKey; cout << ", " << regionKey << "}"; } }; //conversion to parent key template<> Q2_N__N_Key Q2_N__N_Parcel::to<Q2_N__N_Key>() const { return {nationKey}; } //conversion to childKeys template<> Q2_N__R_Key Q2_N__N_Parcel::to<Q2_N__R_Key>() const { return {regionKey}; } //hashers & equality operators namespace std { template<> struct hash<Q2_N__N_Key> { size_t operator()(const Q2_N__N_Key& p) const { size_t seed = 0; boost::hash_combine(seed, p.nationKey); return seed; } }; template<> struct hash<Q2_N__N_Parcel> { size_t operator()(const Q2_N__N_Parcel& p) const { size_t seed = 0; boost::hash_combine(seed, p.nationKey); boost::hash_combine(seed, p.regionKey); return seed; } }; template<> struct equal_to<Q2_N__N_Key> { bool operator()(const Q2_N__N_Key& lhs, const Q2_N__N_Key& rhs) const { return lhs.nationKey == rhs.nationKey; } }; template<> struct equal_to<Q2_N__N_Parcel> { bool operator()(const Q2_N__N_Parcel& lhs, const Q2_N__N_Parcel& rhs) const { return lhs.nationKey == rhs.nationKey && lhs.regionKey == rhs.regionKey; } }; } typedef Table<Q2_N__N_Parcel> Q2_N__N_Table; typedef SplitTable<Q2_N__N_Key, Q2_N__N_Parcel> Q2_N__N_SplitTable; #endif //RANDOMORDERENUMERATION_Q2_N__N_PARCEL_H
true
b27ee9d55bfdd6493a6a61ceb1e9326a2b30d596
C++
RC-MODULE/nmOpenGL
/src_proc0/pc/doubleSubC_32f.cpp
UTF-8
209
2.609375
3
[]
no_license
extern "C"{ void doubleSubC_32f(float* src1, float* src2, float C1, float C2, float* dst1, float* dst2, int size){ for(int i = 0; i < size; i++){ dst1[i] = src1[i] - C1; dst2[i] = src2[i] - C2; } } }
true
0b8d7d8fc59e345f4d59e2e04ab3e00f35584060
C++
zmbilx/cxxPrimerPlus6th
/04第四章/4-08-strtype2.cpp
UTF-8
969
3.921875
4
[]
no_license
#include <iostream> #include <string> int main(){ using namespace std; string s1 = "penguin"; string s2,s3; cout<<"You can assign one string object to another:s2 = s1\n"; s2 = s1; cout<<"s1: "<<s1<<",s2: "<<s2<<endl; cout<<"You can assign a C-style string to a string object.\n"; cout<< "s2 = \"buzzard\"\n"; s2 = "buzzard"; cout<<"s2: "<<s2<<endl; cout<<"You can conatenate strings: s3 = s1+ s2\n"; s3 = s1 + s2; cout<<"s3: "<<s3<<endl; cout<<"You can append strings.\n"; s1 += s2; cout<<"s1 += s2 yields s1= "<<s1<<endl; s2 +="for a day"; cout<<"s2 +=\"for a dat\" yields s2= "<<s2<<endl; return 0; } /* output: You can assign one string object to another:s2 = s1 s1: penguin,s2: penguin You can assign a C-style string to a string object. s2 = "buzzard" s2: buzzard You can conatenate strings: s3 = s1+ s2 s3: penguinbuzzard You can append strings. s1 += s2 yields s1= penguinbuzzard s2 +="for a dat" yields s2= buzzardfor a day */
true
158e5aad7a3dcc3cc932557f989657181656b2c8
C++
ayushchopra96/topologize
/modify.cpp
UTF-8
927
2.53125
3
[]
no_license
/*1 4 3 7 4 2 4 6 8 5 9 3*/ #include <bits/stdc++.h> #include "header.h" using namespace std; //3 single bond hai to 109.5 //1 double bond 120 // 1 triple bond 180 void read_pdb(char *argv,struct pdb pdbfile[1000],int &file_length) { //n= read nth pdb file_length=0; fstream fp; fp.open(argv,ios::in); if(fp==NULL) { printf("file %s did not open\n",argv[n]); } int i=0; while(fp) { // || strcmp(f.atom2,"HETATM")==0 char buffer[1000]; string line; getline(fp,line); if(fp==NULL) break; strcpy(buffer,line.c_str()); struct pdb f; sscanf(buffer,"%s%d%s%s%d%f%f%f%f%f%f\n",f.atom2,&f.atomno2,f.t2,f.d2,&f.r2,&f.x2,&f.y2,&f.z2,&f.h2,&f.e2,&f.ep2); strcpy(f.atomName,f.t2); remove_space_num(f.atomName); //printf("|%s|\n",f.atom2); if(strcmp(f.atom2,"ATOM")==0) { pdbfile[i]=f; i++; } } file_length=i; }
true
90725c725201b9354160568677a719220d3b3abb
C++
yzpd/data_structure
/hash.cpp
GB18030
5,531
3.1875
3
[]
no_license
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include "hash.h" #define MAXWORDLEN 80 //ij //λƷַλλ5λ,ڵintֵ int Hash(const char* key, int TableSize) { unsigned int H = 0; while (*key != '\0') H = (H << 5) + *key++; return H % TableSize; } //ȷһСTableSize,ɢбĵַռС int NextPrime(int N) { /*شNҲMAXTABLESIZEС*/ int i, p = (N % 2) ? N + 2 : N + 1; /*ӴNһʼ*/ while (p <= MAXTABLESIZE) { for (i = (int)sqrt(p); i > 2; i++) if (!(p%i)) break; /*p*/ if (i == 2) break; /*forp*/ else p += 2; /*̽һ*/ } return p; } HashTable CreateTable(int TableSize) { HashTable H; int i; H = (HashTable)malloc(sizeof(struct TblNode)); H->TableSize = NextPrime(TableSize); H->Heads = (List)malloc(sizeof(struct LNode) * (H->TableSize + 1)); /*ʼͷ*/ for ( i = 0; i < H->TableSize ; i++ ) { H->Heads[i].data[0] = '\0'; H->Heads[i].next = NULL; H->Heads[i].count = 0; } return H; } void DestroyTable(HashTable H) { int i; Position P, Tmp; for (i = 0;i < H->TableSize;i++) { P = H->Heads[i].next; while (P) { Tmp = P->next; free(P); P = Tmp; } free(H->Heads); free(H); } } Position Find(HashTable H, Type key) { Position P; Index Pos; Pos = Hash(key, H->TableSize); P = H->Heads[Pos].next; while(P && strcmp(P->data, key)) P = P->next; return P; } //ͷ㲻,countʵ void InsertAndCount(HashTable H, Type key) { Position P, NewCell; Index Pos; P = Find(H, key); if (!P) { NewCell = (Position)malloc(sizeof(struct LNode)); strcpy(NewCell->data, key); NewCell->count = 1; Pos = Hash(key, H->TableSize); NewCell->next = H->Heads[Pos].next; H->Heads[Pos].next = NewCell; H->Heads[Pos].count++; } else P->count++; } //жһǷΪϷַ,ϷַΪСдĸ,ֺ» bool IsWordChar(char c) { if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '_') return true; else return false; } //ӸļжȡһʣظõʵijȣKEYLENGTHijȽȥ int GetWord(FILE* fp, Type word) { char tempword[KEYLENGTH + 1], c; int len = 0; //ʳ c = fgetc(fp); while (!feof(fp)) { if (IsWordChar(c)) tempword[len++] = c; c = fgetc(fp); /*ǰķǷַ(Ϊlen=0ɸȥlenС3ַ,Ծһ),ԷǷַһ*/ if (len && !IsWordChar(c)) break; } tempword[len] = '\0'; if (len > KEYLENGTH) { tempword[KEYLENGTH] = '\0'; len = KEYLENGTH; } strcpy(word, tempword); return len; } void Show(HashTable H, double percent) { int diffwordcount = 0; //ͬĵ int maxf = 0; //ĴƵ int* diffwords; //ÿƵӦIJͬ int maxCollision = 0; //ͻ,ʼΪ0 int minCollision = 100; //Сͻ,ʼΪ100 Position L; int i, j, k, lowerbound, count = 0; for (i = 0; i < H->TableSize; i++) { /*ͬĵ*/ diffwordcount += H->Heads[i].count; /*ͳСijͻ*/ if (maxCollision < H->Heads[i].count) maxCollision = H->Heads[i].count; if (minCollision > H->Heads[i].count) minCollision = H->Heads[i].count; /*ĴƵ*/ L = H->Heads[i].next; while (L) { if (maxf < L->count) maxf = L->count; L = L->next; } } printf("%dͬĵʣƵ%d\n", diffwordcount, maxf); printf("ijͻ%d, Сijͻ%d\n", maxCollision, minCollision); /*ÿƵӵеIJͬ*/ /*ĴƵһ*/ diffwords = (int*)malloc((maxf + 1) * sizeof(int)); /*ͳƴƵ1maxfĵ*/ for (i = 0; i <= maxf; i++) diffwords[i] = 0; for (i = 0; i < H->TableSize;i++) { L = H->Heads[i].next; while (L) { diffwords[L->count]++; L = L->next; } } /*ضĴƵʹôڵڸôƵĵܺͳı*/ lowerbound = (int)(diffwordcount * percent); for (i = maxf;i >= 1 && count < lowerbound;i--) count += diffwords[i]; //printf("count = %d\n", count); //printf("i = %d\n", i); /*ƵӴС*/ for (j = maxf;j >= i;j--) { for (k = 0; k < H->TableSize; k++) { L = H->Heads[k].next; while (L) { if (j == L->count) printf(" %-15s %d\n", L->data, L->count); L = L->next; } } } free(diffwords); } int main() { FILE *fp; HashTable H; Type word; int TableSize = 100; int length, wordcount = 0; char document[100] = "C:\\Users\\yzpd\\Desktop\\ѧϰ\\data_structure\\data_structure\\data_structure\\text.txt"; //þԵַ H = CreateTable(TableSize); if ((fp = fopen(document, "r")) == NULL) { printf("޷ļ\n"); getchar(); return -1; } while (!feof(fp)) { length = GetWord(fp, word); if (length > 3) { wordcount++; InsertAndCount(H, word); } } fclose(fp); printf("ĵ%dЧ\n", wordcount); Show(H, 10.0 / 100);/*ʾƵǰ10%е*/ DestroyTable(H); getchar(); return 0; }
true
7cdc68ec13203faf52287714e2fcffaa715b37d3
C++
yeahzdx/Leetcode
/Int To Roman.cpp
UTF-8
828
3.5625
4
[]
no_license
#include"head.h" string intToRoman(int num){ string symbol[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}; int value[]={1000,900,500,400,100,90,50,40,10,9,5,4,1}; int i=0; string res; while(num!=0){ if(num>=value[i]){ num-=value[i]; res+=symbol[i]; } else ++i; } return res; } int c2n(char c) { switch(c){ case 'M':return 1000; case 'D':return 500; case 'C':return 100; case 'L':return 50; case 'X':return 10; case 'V':return 5; case 'I':return 1; default:return 0; } } int romanToInt(string s){ if(s.size()<1) return 0; int res=0; int len=s.length(); int i=1; while((i-1)<len){ if(c2n(s[i-1])>=c2n(s[i])){ res+=c2n(s[i-1]); i++; } else{ res+=c2n(s[i])-c2n(s[i-1]); i+=2; } } return res; }
true
f49cf390dba058dd9b0f79b631140581fb08ae64
C++
lyost/d3d12_framework
/d3d12_framework/src/Time/PerformanceTimer.cpp
UTF-8
730
2.75
3
[]
no_license
#include "private_inc/Time/PerformanceTimer.h" PerformanceTimer* PerformanceTimer::Create() { LARGE_INTEGER freq; if (!QueryPerformanceFrequency(&freq)) { return NULL; } else if (freq.QuadPart == 0) { return NULL; } return new PerformanceTimer(freq.QuadPart / 1000.0f); } PerformanceTimer::PerformanceTimer(float freq) :m_freq(freq) { QueryPerformanceCounter(&m_ref_time); } bool PerformanceTimer::CheckDelta(UINT ms, UINT& actual_ms) { LARGE_INTEGER curr_time; QueryPerformanceCounter(&curr_time); float delta = (curr_time.QuadPart - m_ref_time.QuadPart) / m_freq; if (delta >= ms) { m_ref_time = curr_time; actual_ms = (UINT)delta; return true; } return false; }
true
4d1bfbe7631796eded50fe6567282eaced65350d
C++
fazlerahmanejazi/UVa-Solutions
/Chapter-III/10341 - Solve It(Fast).cpp
UTF-8
647
2.78125
3
[]
no_license
#include <bits/stdc++.h> using namespace std ; #define least 0.000000000001 int p,q,r,s,t,u; double f(double x) { return p*exp(-x) + q*sin(x) + r*cos(x) + s*tan(x) + t*x*x + u; } double fd(double x) { return -p*exp(-x) + q*cos(x) - r*sin(x) + s/(cos(x)*cos(x)) + 2*t*x; } double solve() { if (f(0)==0) return 0; for (double x=0.5; ;) { double x1 = x - f(x)/fd(x); if (fabs(x1-x) < least) return x; x = x1; } } int main() { while(cin>>p>>q>>r>>s>>t>>u) { if (f(0) * f(1) > 0) cout<< "No solution" << endl ; else cout<< fixed << setprecision(4)<< solve() << endl ; } }
true
a4b4c0c51100da63e141b2a8714d3810d5df1f47
C++
alperbek/arduino-kursu
/Kodlar/FUNDAMENTALS/3a - button/8led_3button/8led_3button.ino
UTF-8
2,977
3
3
[]
no_license
/* * Can not be use 3 button with interrupt * because of Arduino Uno support only 2 (d2,d3) input for interrupt. */ const byte leftButton = 12; const byte blinkButton = 11; const byte rightButton = 10; const byte buttonReadCount = 3; // Read multiple times to avoid button bounce byte led = 2; // leds attached 9 from 2 byte ledDelay = 50; unsigned long time; unsigned long buttonResolution = 500; volatile unsigned long lastButtonClick; String signalDirection = "nodirection"; void setup() { pinMode(leftButton, INPUT_PULLUP); pinMode(blinkButton, INPUT_PULLUP); pinMode(rightButton, INPUT_PULLUP); for (byte i= 2; i<=9; i++) pinMode(i, OUTPUT); Serial.begin(9600); Serial.println("Program started."); } String readButtons(String signalDirection) { if (millis() - lastButtonClick < buttonResolution) return signalDirection; String oldDirection = signalDirection; byte leftButtonSum = 0; byte blinkButtonSum = 0; byte rightButtonSum = 0; for (byte i=0; i<buttonReadCount; i++) { leftButtonSum += digitalRead(leftButton); blinkButtonSum += digitalRead(blinkButton); rightButtonSum += digitalRead(rightButton); delayMicroseconds(50); } if (leftButtonSum == 0) { lastButtonClick = millis(); if (oldDirection != "left") signalDirection = "left"; else signalDirection = "noDirection"; } if (blinkButtonSum == 0) { lastButtonClick = millis(); if (oldDirection != "blink") signalDirection ="blink"; else signalDirection = "noDirection"; } if (rightButtonSum == 0) { lastButtonClick = millis(); if (oldDirection != "right") signalDirection = "right"; else signalDirection = "noDirection"; } Serial.println("Direction: " + signalDirection); return signalDirection; } void loop() { signalDirection = readButtons(signalDirection); if (signalDirection == "left" or signalDirection == "blink" or signalDirection == "right") { if (signalDirection == "left" or signalDirection == "right") { Serial.println("Led: " + String(led)); digitalWrite(led, OUTPUT); delay(ledDelay); digitalWrite(led, LOW); if (signalDirection == "left") { led--; if (led < 2) led = 9; } if (signalDirection == "right") { led++; if (led > 9) led = 2; } } if (signalDirection == "blink") { for (byte i=2; i<=9; i++) digitalWrite(i, HIGH); delay(ledDelay); for (byte i=2; i<=9; i++) digitalWrite(i, LOW); delay(ledDelay); } } else { // noDirection for (byte i=2; i<=9; i++) digitalWrite(i, LOW); } }
true
5814b035dd5519c401593e1125b783ecbb2d03e9
C++
CaterTsai/squre_arduino
/LOpen.h
UTF-8
1,802
2.875
3
[]
no_license
#include "baseLight.h" //------------------------------------ //LOpen class LOpen : public baseLight { public: LOpen(eMode mode, int len) : baseLight(mode, len) , _openT(1000) , _timer(0) { _animV = 1.0f / (_openT / 1000.0); } virtual void play(ePlayType t) { _isPlaying = true; _playType = t; open(); } virtual void stop() { _isPlaying = false; } virtual void update(CRGB* ledData, long delta) { if (!_isPlaying) { return; } updateOpen(ledData, delta); _timer -= delta; if (_timer <= 0) { _timer = _openT; if (_playType == ePlayRepeat) { open(); } } } virtual void holdData(unsigned char* source, int len) { if (len != _dataLength) { return; } memcpy(&_openT, source + 2, sizeof(int)); _timer = _openT; _animV = 1.0f / (_openT / 1000.0); } private: void open() { _animP = 0.0; _openP1 = random(0, NUM_LEDS_HALF - 1); } void updateOpen(CRGB* ledData, long delta) { float detlaS = delta / 1000.0; _animP += _animV * detlaS; int len = static_cast<int>(LED_EACH_SIDE * _animP + 0.5); for (int i = 0; i < NUM_LEDS_HALF; i++) { int dist = abs(i - _openP1); dist = min(dist, NUM_LEDS_HALF - dist); if (dist <= len) { ledData[i] = gColor; ledData[i + NUM_LEDS_HALF] = gColor; } } if (_animP >= 1.0) { if (_playType == ePlayOnce) { _isPlaying = false; } } } private: int _timer; int _openT; float _animP, _animV; int _openP1; };
true
1cd8551668c113817985b0fac9d2699e4404b321
C++
arnaudgelas/Examples
/c++/SDL/Events/SDLEvents.cpp
UTF-8
2,510
2.921875
3
[]
no_license
/*This source code copyrighted by Lazy Foo' Productions (2004-2008) and may not be redestributed without written permission.*/ //The headers #include <SDL/SDL.h> #include <SDL/SDL_image.h> #include <string> #include <iostream> #include "SDL_Helper.h" #include <GL/glut.h> #include <assert.h> using namespace std; //The event structure that will be used void apply_surface( int x, int y, SDL_Surface* source, SDL_Surface* destination ); bool HandleEvents(SDL_Event &event); int main( int argc, char* args[] ) { //Initialize bool success; SDL_Surface *screen = InitSDL(640,480,"Test Window"); /* //Load the files SDL_Surface *image = load_image( "x.png" ); //Apply the surface to the screen apply_surface( 0, 0, image, screen ); */ SDL_Event event; //Update the screen if( SDL_Flip( screen ) == -1 ) { return 1; //error } bool QuitSDL = false; /* while( QuitSDL == false ) { while( SDL_PollEvent( &event ) ) */ while(SDL_WaitEvent(&event)) { QuitSDL = HandleEvents(event); if(QuitSDL) { break; } } SDL_FreeSurface(screen); SDL_Quit(); return 0; } /* void apply_surface( int x, int y, SDL_Surface* source, SDL_Surface* destination ) { //Temporary rectangle to hold the offsets SDL_Rect offset; //Get the offsets offset.x = x; offset.y = y; //Blit the surface SDL_BlitSurface( source, NULL, destination, &offset ); } */ bool HandleEvents(SDL_Event &event) { //If the user has clicked the X (to close the window) if( event.type == SDL_QUIT ) { //Quit the program cout << "Clicked the X" << endl; return true; } if(event.type == SDL_MOUSEBUTTONDOWN && SDL_BUTTON(SDL_GetMouseState(NULL,NULL)) == SDL_BUTTON_LEFT) { cout << "mouse left down" << endl; } if(event.type == SDL_MOUSEBUTTONUP) // returns bullet to player { cout << "Mouse up" << endl; } if (event.type == SDL_KEYDOWN) //you must enclose key checks in this KEYDOWN check { if (event.key.keysym.sym == SDLK_ESCAPE) { cout << "pressed esc" << endl; return true; } if (event.key.keysym.sym == SDLK_a) { cout << "pressed a" << endl; } } if (event.type == SDL_KEYUP) { if (event.key.keysym.sym == SDLK_a) { cout << "released a" << endl; } } if(event.type == SDL_MOUSEMOTION) { cout << "x: " << event.motion.x << "y: " << event.motion.y << endl; } return false; }
true
8629a68f7633173e0318015618e43407c5eda3c3
C++
JimNilsson/DV1553H17Lp2
/Lektion7/Square.cpp
UTF-8
453
3.609375
4
[]
no_license
#include "Square.h" #include <iostream> Square::Square(const std::string & color, float side) : Shape(color) { this->sideLength = side; } Square::Square() : Shape() { this->sideLength = 1.0f; } Square::~Square() { } float Square::GetArea() const { return sideLength * sideLength; } void Square::Draw() const { for (int i = 0; i < sideLength; i++) { for (int k = 0; k < sideLength; k++) { std::cout << "*"; } std::cout << "\n"; } }
true
5552b6ca49c0b6e6fdda2d3372e2c9c661a1c491
C++
isVoid/Leet_codebase
/162FindingPeakElement.cpp
UTF-8
1,377
2.828125
3
[]
no_license
#include <iostream> #include <vector> #include <tuple> #include <queue> #include <stack> #include <set> #include <map> #include <unordered_map> #include <algorithm> #include <cmath> #include "dbg.hpp" using namespace std; struct ListNode; struct TreeNode; class Solution { public: // Runtime: 4 ms, faster than 97.53% // Memory Usage: 8.5 MB, less than 82.67% int findPeakElement(vector<int>& nums) { if (nums.size() == 1) return 0; int lo = 0, hi = nums.size()-1; while (lo <= hi) { int mid = (lo + hi) / 2; bool ascending; if (mid < nums.size()-1) { ascending = nums[mid] < nums[mid+1]; } else { ascending = nums[mid-1] < nums[mid]; } if (ascending) { lo = mid + 1; } else { hi = mid - 1; } } return min(lo, (int)nums.size()-1); } }; int main(int argc, char ** argv) { // vector<int> seq = {1, 2, 1, 3, 5, 6, 4}; // vector<int> seq = {1, 2, 1}; // vector<int> seq = {1, 2, 1, 3, 2}; // vector<int> seq = {1, 2, 3, 4, 5}; // vector<int> seq = {5, 4, 3 ,2 ,1}; // vector<int> seq = {1, 2, 3, -1, 0}; vector<int> seq = {1}; cout << Solution().findPeakElement(seq) << endl; return 0; }
true
6e0eef6b6a2cb580a2f16a9295c4f6bf0d1c3516
C++
kunnapatt/Competitive
/Problem/10107/10107.cpp
UTF-8
531
2.53125
3
[]
no_license
#include <bits/stdc++.h> using namespace std ; #define FOR(i, a, b) for(int i = a ; i < b ; i++) #define vi vector<int> #define vii vector<long> #define long long long int main(){ int n ; vi a ; while ( cin >> n){ a.push_back(n) ; sort(a.begin(), a.end()) ; if ( a.size() % 2 != 0 ){ int siz = a.size()/2 ; cout << a[siz] << endl ; }else { int siz = a.size()/2 ; cout << (a[siz-1] + a[siz])/2 << endl ; } } return 0 ; }
true
6b07104dcc2ae66f6fd3d6d96e6727512c301e99
C++
zerohoon96/BOJ_algorithm
/Silver/숨바꼭질 S1.cpp
UTF-8
679
2.6875
3
[]
no_license
#include <stdio.h> #include <string.h> #include <queue> int length[200000]={-1,}; using namespace std; int main(void){ int n,k,cur; queue<int> que; scanf("%d%d",&n,&k); que.push(n); memset(length,-1,sizeof(int)*200000); length[n]=0; while(1){ cur=que.front(); que.pop(); if(cur==k){ printf("%d\n",length[k]); break; } if(cur<k){ if(length[cur*2]<0){ que.push(cur*2); length[cur*2]=length[cur]+1; } if(length[cur+1]<0){ que.push(cur+1); length[cur+1]=length[cur]+1; } } if(cur>0){ if(length[cur-1]<0){ que.push(cur-1); length[cur-1]=length[cur]+1; } } } return 0; }
true
a5eaf26df8bcbafcdfffac12615a5ec66bb5538b
C++
wangluo2028/HearthStoneRobot
/Robot/handWritten-digit-recognition-based-on-OpenCV/handWritten digit recognition based on OpenCV/preprocess.cpp
GB18030
1,061
2.59375
3
[]
no_license
#include "opencv2/imgproc/types_c.h" #include"preprocess.h" void preProcess(const Mat& srcImage, Mat& dstImage) { Mat tmpImage = srcImage.clone(); if (tmpImage.type() != CV_8UC1) { cvtColor(tmpImage, tmpImage, CV_BGR2GRAY); } //ֵ˲Ԥ //GaussianBlur(tmpImage, tmpImage, Size(3, 3), 0, 0, BORDER_DEFAULT); medianBlur(tmpImage, tmpImage, 3); //̬ѧ˲ Ԥ Mat element = getStructuringElement(MORPH_RECT, Size(7,7)); //morphologyEx(tmpImage, tmpImage, MORPH_OPEN, element); //imshow("˹˲ӿ", tmpImage); //waitKey(500); //cannyȡ Canny(tmpImage, dstImage, 75, 100, 3); //imshow("cannyȡ", dstImage); //waitKey(500); //̬ѧ˲մ element = getStructuringElement(MORPH_RECT, Size(3, 3)); morphologyEx(dstImage, dstImage, MORPH_DILATE, element); //imshow("̬ѧ", tmpImage4); //waitKey(500); //ֵ˲ //medianBlur(tmpImage4, dstImage, 3); //imshow("ֵ˲", dstImage); //waitKey(500); }
true
c44ef5656f6fdf7a45af136dc837afd08b06a4d9
C++
heechan3006/CS
/BOJ/BOJ_17472/Project4/소스.cpp
UTF-8
3,170
2.546875
3
[]
no_license
#include <iostream> #include <cstring> #include <queue> #include <vector> #define MAXN 10 #define INF 987654321 using namespace std; int N, M; int map[MAXN][MAXN]; bool visited[MAXN][MAXN]; struct node { int u; int v; int weights; }; int dist[7][7]; int max_v = 0; int dx[] = { 0,0,1,-1 }; int dy[] = { 1,-1,0,0 }; int ans = INF; vector<node> adj; vector<bool> used; bool check() { vector<vector<bool> > selected(max_v + 1, vector<bool>(max_v + 1, false)); vector<bool> num(max_v + 1, false); queue<int> q; for (int i = 0; i < adj.size(); i++) { if (used[i]) { if (q.empty()) { num[adj[i].u] = true; q.push(adj[i].u); } selected[adj[i].u][adj[i].v] = true; selected[adj[i].v][adj[i].u] = true; } } int cnt = max_v - 1; while (!q.empty()) { int cur = q.front(); q.pop(); for (int i = 1; i <= max_v; i++) { if (dist[cur][i] == INF) continue; if (selected[cur][i] && !num[i]) { num[i] = true; cnt--; q.push(i); } } } return cnt == 0; } bool is_range(int x, int y) { return x >= 0 && y >= 0 && x < N && y < M; } void dfs(int x, int y) { visited[x][y] = true; map[x][y] = max_v; for (int k = 0; k < 4; k++) { int nx = x + dx[k]; int ny = y + dy[k]; if (is_range(nx, ny) && !visited[nx][ny] && map[nx][ny]) { dfs(nx, ny); } } } void bfs(int target) { memset(visited, false, sizeof(visited)); queue<pair<int, int> > q; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { if (map[i][j] == target) { q.push({ i,j }); visited[i][j] = true; } } } while (!q.empty()) { int x = q.front().first; int y = q.front().second; q.pop(); for (int k = 0; k < 4; k++) { int nx = x + dx[k]; int ny = y + dy[k]; if (nx < 0 || ny < 0 || nx >= N || ny >= M) continue; if (visited[nx][ny]) continue; if (!map[nx][ny]) { int len = 0; while (nx >= 0 && ny >= 0 && nx < N && ny < M) { if (map[nx][ny]) { if (len >= 2 && dist[target][map[nx][ny]] > len) { dist[target][map[nx][ny]] = len; dist[map[nx][ny]][target] = len; } break; } nx += dx[k]; ny += dy[k]; len++; } } } } } void B_tracking(int now, int cnt, int sum) { if (cnt >= max_v - 1) { if (check()) { if (ans > sum) ans = sum; } } for (int i = now; i < adj.size(); i++) { if (!used[i]) { used[i] = true; B_tracking(now + 1, cnt + 1, sum + adj[i].weights); used[i] = false; } } } int main() { ios::sync_with_stdio(false); cin.tie(0); cin >> N >> M; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { cin >> map[i][j]; } } for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { if (!visited[i][j] && map[i][j]) { max_v++; dfs(i, j); } } } for (int i = 1; i <= max_v; i++) { for (int j = 1; j <= max_v; j++) { dist[i][j] = INF; } } for (int i = 1; i <= max_v; i++) { bfs(i); } for (int i = 1; i <= max_v; i++) { for (int j = i + 1; j <= max_v; j++) { if (dist[i][j] != INF) adj.push_back({ i,j,dist[i][j] }); } } used.resize(adj.size(), false); B_tracking(0, 0,0); if (ans == INF) cout << "-1\n"; else cout << ans << "\n"; return 0; }
true
28763cebfded1ae456091052381ff3ec27a9349b
C++
HelderAntunes/competitive-programming
/uva/dynamicProgramming/Max2D-Sub-range/UVA11951.cpp
UTF-8
1,381
2.625
3
[]
no_license
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <string.h> #include <algorithm> #include <queue> #include <set> #include <climits> using namespace std; typedef pair<int, int> ii; typedef vector<ii> vii; typedef vector<int> vi; typedef long long int ll; int a[105][105]; /* * helder antunes * UVA 11951 - Area * */ int main() { int t; scanf("%d", &t); int test = 1; while(t--){ int n, m, ko; scanf("%d %d %d", &n, &m, &ko); for(int i = 0;i < n;i++){ for(int j = 0;j< m;j++){ scanf("%d", &a[i][j]); if(i > 0) a[i][j] += a[i-1][j]; if(j > 0) a[i][j] += a[i][j-1]; if(i>0 && j>0) a[i][j] -= a[i-1][j-1]; } } long long int ans_area = 0; long long int ans_cost = 0; for(int i = 0;i < n;i++)for(int j = 0;j < m;j++) for(int k = i;k < n;k++)for(int l= j;l < m;l++){ long long int sum = a[k][l]; if(i>0) sum -= (ll)a[i-1][l]; if(j>0) sum -= (ll)a[k][j-1]; if(i > 0 && j>0) sum += (ll)a[i-1][j-1]; if(sum <= (ll)ko){ long long int area = (ll)(k-i+1)*(ll)(l-j+1); if((area > ans_area) || (area == ans_area && sum < ans_cost)){ ans_cost = sum; ans_area = area; } } } printf("Case #%d: %lld %lld\n", test, ans_area, ans_cost); test++; } return 0; }
true
c44685dd2b04c29569f08bf4fe93f959348a7743
C++
igorodinskiy/Laboratory_work_SN-11
/Laboratory_work_6.cpp
UTF-8
909
3.203125
3
[]
no_license
#include <iostream> #include <cstdlib> using namespace std; int main() { cout << "PROGRAM ONE" << endl; int a[20]; int i = 0; for ( i = 0; i < 20; i++ ) a[i] = rand()%100-50; cout << "Massif: "; for ( i = 0; i < 20; i++ ) cout << a[i] << "; "; cout << "\n"; int b=0; cout << "Enter number (from -50 to 50): "; cin >> b; int count = 0; for ( i = 0; i < 20; i++ ) if ( a[i] == b ) count++; cout << "The massif is " << count << " items, equal number " << b << endl; cout << "\nPROGRAM TWO" << endl; if ( a[2] > b * a[1] ) { count = 0; for ( i = 0; i < 20; i++ ) { if ( a[i] < 0 ) count++; } cout << "Number negative items massif: " << count << endl; } else { int d = 0; d = 0; cout << "Number items massif, equal 0: "; for ( i = 0; i < 20; i++ ) { if ( a[i] = 0) d++; } int c = 0; if ( c == d ) cout << "0" << endl; else cout << d << endl; } return 0; }
true
6aaebe1edd4e6504acbb76787412d1e6d5e60471
C++
AlamyLiu/hw2_sort
/main.cpp
UTF-8
6,632
2.828125
3
[]
no_license
/* * main() entry */ #include <cerrno> #include <iostream> #include <string> #include <fstream> // ifstream, ofstream #include <stdlib.h> // atoi #include <getopt.h> // getopt_long() #include <unistd.h> // getopt() //#include <regex> // regex #include <list> // list of SIDLList class #include "SIntFormat.hpp" // validating Signed Integer format #include "sidll.hpp" // Double Linked-List #include "MultiSort.hpp" // Sorting methods #include "DebugW.hpp" // Debug using namespace std; const struct option long_opts[] = { {"input", required_argument, 0, 'i'}, {"digitsPerNode",required_argument, 0, 'n'}, {"algorithm", required_argument, 0, 'a'}, {"output", required_argument, 0, 'o'}, {"debug", no_argument, 0, 'd'}, {"test", no_argument, 0, 't'}, /* internal */ {0,0,0,0}, }; typedef struct _OPT_FLAGS { string iFile; /* Input file */ string oFile; /* Output file */ int digitsPerNode; /* digits per node */ int algorithm; /* <select|insert|merge|heap|quick> */ bool debug; /* Enable debug */ bool test; /* Internal: misc testing function */ } OPT_FLAG; #if 1 OPT_FLAG optFlag; #else OPT_FLAG optFlag = { .iFile = string( "" ), .oFile = string( "" ), .digitsPerNode = 1, .algorithm = SELECT, .debug = false, .test = false }; #endif Debug *dbg; /* Warning: should be created before List */ bool validate_format( string signInteger ) { string str_sign ("+-"); string str_digit("0123456789"); int sign = 1; /* Default to positive '+' */ size_t pSign = signInteger.find_first_of( str_sign ); size_t pValue = signInteger.find_first_not_of( str_sign ); if (pSign == pValue) { /* No sign: default */ } else if (pSign + 1 != pValue) { /* Wrong format */ if (pValue < pSign) { /* [:digit:][+-] */ } else { /* [+-]+[:digit:] */ } cerr << "Wrong Format: " << signInteger << endl; return false; } else { /* pSign < pValue */ if (signInteger.at(pSign) == '-') sign = -1; /* If it's not '-', it must be '+' : find_first_of() */ /* We don't handle '+' case, as it's default case */ } string integer = signInteger.substr(pValue); /* [[:digit:]] */ if (integer.find_first_not_of( str_digit ) != std::string::npos) { /* [+-][[:digit:]]\w */ cerr << "Wrong format: " << signInteger << endl; return false; } return true; } int main(int argc, char* argv[]) { /* Syntax sort "input=<in.txt>;digitsPerNode=<number>;algorithm=<select|insert|merge|heap|quick>;ouput=<out.txt>". */ if (argc < 2) { cerr << "Usage: " << argv[0] << " \"input=<in.txt>;" \ "digitsPerNode=<number>;" \ "algorithm=<select|insert|merge|head|quick>;" \ "output=<out.txt>\"" << endl; return -EINVAL; } // Retrieve options int opt_index = 0; int opt; string algorithm; while ( (opt = getopt_long(argc, argv, "dta:i:n:o:", long_opts, &opt_index)) != -1) { switch (opt) { case 'i': optFlag.iFile = string( optarg ); break; case 'o': optFlag.oFile = string( optarg ); break; case 'n': optFlag.digitsPerNode = atoi(optarg); break; case 'a': /* Algorithm */ algorithm = string( optarg ); if (algorithm.compare("select") == 0) optFlag.algorithm = SELECT; else if (algorithm.compare("insert") == 0) optFlag.algorithm = INSERT; else if (algorithm.compare("merge") == 0) optFlag.algorithm = MERGE; else if (algorithm.compare("heap") == 0) optFlag.algorithm = HEAP; else if (algorithm.compare("quick") == 0) optFlag.algorithm = QUICK; else /* unknown algorithm */ optFlag.algorithm = UNKNOWN; break; case 'd': optFlag.debug = true; break; case 't': optFlag.test = true; break; case '?': /* Unknown option (ignore) */ default : /* Do nothing */ break; } // End of switch(opt) } // End of while(opt) // Options error detection ifstream ifs( optFlag.iFile.c_str() ); ofstream ofs( optFlag.oFile.c_str(), ios::out | ios::app ); if (optFlag.iFile.empty()) { cerr << "Input file ?" << endl; return -EINVAL; } else { if (! ifs.good()) { cerr << "File " << optFlag.iFile \ << " does not exist!" << endl; return -EINVAL; } } if (optFlag.oFile.empty()) { cerr << "Output file ?" << endl; return -EINVAL; } if (optFlag.algorithm == UNKNOWN) { cerr << "Unknown algorithm!" << endl; return -EINVAL; } if (optFlag.digitsPerNode < 1) { cerr << "digitsPerNode could not be " \ << optFlag.digitsPerNode << endl; return -EINVAL; } /* Testing mode: call test() function instead of sorting */ if (optFlag.test) { optFlag.algorithm = UNKNOWN; } // create Debug class (DEFAULT_DEBUG_LEVEL), borrow 'opt' variable opt = (optFlag.debug ? DEBUG_LEVEL_INFO : DEBUG_LEVEL_DEBUG); dbg = new (std::nothrow) Debug(opt); if (!dbg) { cerr << "Unable to create Debug system!" << endl; return -ENOMEM; } *dbg << "Input: " << optFlag.iFile << endl; *dbg << "Digits Per Node: " << optFlag.digitsPerNode << endl; *dbg << "algorithm: " << optFlag.algorithm << endl; *dbg << "Output: " << optFlag.oFile << endl; // Parse input file MultiSort mySort; string line; while (ifs >> line) { /* Trim trailing ... */ line.erase(line.find_last_not_of(" \t\n\r\f\v") + 1); *dbg << "--- line: " << line << endl; /* Validate format /^[+-][[:digit:]]$*/ SIntFormat fmt(line); *dbg << "Format: sign = " << fmt.getSign() \ << ", digits = " << fmt.getDigits() << endl; if (! fmt.isValid()) { cerr << "Invalid format: " << line << " ... skip!" << endl; continue; } /* Create a linked-list containing the number */ SIDLList* num = new(nothrow) SIDLList(fmt.getSign(), fmt.getDigits(), optFlag.digitsPerNode); if (! num) { cerr << "Why allocation failed ?" << std::endl; break; } *dbg << *num; mySort.addItem( num ); // intList.push_back( num ); // intList.addInteger( line ); } ifs.close(); *dbg << mySort.size() << " numbers" << endl; *dbg << mySort; /* Now it's time to SORT */ int rc; switch (optFlag.algorithm) { case SELECT: rc = mySort.SelectSort(); break; case INSERT: rc = mySort.InsertSort(); break; case MERGE: rc = mySort.MergeSort(); break; case HEAP: rc = mySort.HeapSort(); break; case QUICK: rc = mySort.QuickSort(); break; default: if (optFlag.test) { rc = mySort.test(); break; } rc = -EINVAL; cerr << "This should not happen!" << endl; break; } /* End of switch(optFlag.algorithm) */ /* Output the result */ if (! rc) { /* Now the result */ cout << "----- Result -----" << endl; cout << mySort; /* And the statictics */ mySort.statistics( ofs, algorithm ); } ofs.close(); // Free resources mySort.free(); delete dbg; return 0; }
true
7f44fbafe789507dac8767024ff76b850c47df1e
C++
ian-bird/compNetProject
/src/process_binary.cpp
UTF-8
3,070
2.890625
3
[]
no_license
#include "process_binary.h" //function to perform file read in void readFile(SOCKET mySocket, char *type) { char *buffer = (char *)malloc(sizeof(char) * 255); int length; FILE *output = (FILE *)buffer; int i; int outputFileNum = 0; //send request for next line of file send(mySocket,"file next",(int)strlen("file next") + 1, 0); //printf("\"%s\"\n",type); //attempt opening new files until one files to open, meaning the name hasn't been used //printf("output = %p\n",output); while(output != NULL) { sprintf(buffer, "out%d.%s", ++outputFileNum, type); output = fopen(buffer,"r"); fclose(output); } //printf("desired file name = %s",buffer); output = fopen(buffer,"wb");//create file with this name if(output == NULL) { fprintf(stderr, "ERROR: could not create output file\n"); exit(1); } //each file line is 255 long unless it's the last one, in which case it's shorter. do { length = recv(mySocket,buffer, 255, 0); //printf("length = %d\n",length); fwrite(buffer,sizeof(char),length,output); send(mySocket,"file next",(int)strlen("file next") + 1, 0); } while(length == 255); //printf("check for eof\n"); //confirm that end of file is received recv(mySocket, buffer, 255, 0); if(strcmp(buffer, "end of file") != 0) { fprintf(stderr, "expected end of file token, received \"%s\"\n",buffer); exit(1); } fclose(output); free(buffer); printf("file received!\n"); } //sends a binary file void sendBinaryFile(SOCKET socket, FILE *input, const char *file) { char *buffer = (char *)malloc(sizeof(char) * 255); long long oldPosition; long long i; long long fileLength; int messageLength; char firstChar; fclose(input); input = fopen(file,"rb"); firstChar = fgetc(input); //chomp \n if(firstChar == 'f') { while(firstChar != '\n') firstChar = fgetc(input); } //printf("start = %d\n",(int)ftell(input)); send(socket, "file",(int)strlen("file") + 1, 0); //sent to initiate file read mode recv(socket, buffer, 255, 0); //confirm client entered file read mode if(strcmp(buffer, "file") != 0) { fprintf(stderr,"ERROR: unexpected token \"%s\"\n",buffer); exit(1); } fscanf(input, "%s",buffer); //send file extension to client fgetc(input); //chomp \r fgetc(input); //chomp \n oldPosition = ftell(input); //printf("extension = %s\n",buffer); send(socket, buffer, 255, 0); recv(socket, buffer, 255, 0); fseek(input, 0, SEEK_END); //get file length i = ftell(input); //printf("f len = %d\n", i); fileLength = i; fclose(input); //return to old position input = fopen(file,"rb"); fseek(input, (long)oldPosition, SEEK_SET); i = oldPosition; //printf("start position = %d\n", i); while(i < fileLength) //copy file { fread(buffer, sizeof(char), 255, input); i += 255; messageLength = i < fileLength ? 255 : (int)(fileLength - (i - 255)); send(socket, buffer, messageLength, 0); recv(socket, buffer, 255, 0); if (strcmp(buffer, "file next") != 0) { fprintf(stderr, "ERROR: unexpected token \"%s\"\n", buffer); exit(1); } } fclose(input); free(buffer); }
true
9a4d0d81dbe0bf24dd323291cf0c6d370676e9ed
C++
SandeepGarcha1234/NumericalCPPPractice
/FirstOrderODE.cpp
UTF-8
4,066
3.375
3
[]
no_license
#include <cassert> #include "FirstOrderODE" FirstOrderODE::FirstOrderODE(const std::vector<double (*) (double t, Matrix v)>& FF, double t0, const Matrix& y0) : F(FF), initialTime(t0), initialValue(y0){ assert(FF.size() == y0.getRows()); order = y0.getRows(); } Matrix evaluate(const std::vector<double (*) (double t, Matrix u)>& F, double t, const Matrix& v){ //evaluates F(t,v) and returns the result in a matrix of size nx1 (column vector form) int n = v.getRows(); assert(F.size() == n); Matrix result(n,1); for (int i=0; i<n; i++){ double y = (*(F[i]))(t,v); result(i,0) = y; } return result; } Matrix EulerMethod::solve(const FirstOrderODE& A){ //Uses Euler Method to solve the ODE //the value at time step k+1 ie. (v(k+1)) is as follows //v(k+1)=v(k)+h*F(tk,v(k)) int m = A.getorder(); int n = getnumberOfSteps(); Matrix result(m,n); double s = A.getinitialTime(); //this variable represent the current time step double h = (getfinalTime() - s)/n; //this is the size of the time step Matrix currentVector = A.getinitialValue(); for (int j=0; j<n; j++){ currentVector = currentVector + (h* evaluate(A.getRHS(),s,currentVector)); s+=h;//increments to the next time step result.insertColumn(currentVector,j); //insert v(j) into the jth index column } return result; } Matrix ImprovedEulerMethod::solve(const FirstOrderODE& A){ //Uses the Improved Euler Method to solve the ODE //the value at time step k+1 ie. (v(k+1)) is as follows //v(k+1)=v(k)+0.5*h*[F(tk,v(k)) + F(t+h, v(k)+h*F(tk,v(k)))] int m = A.getorder(); int n = getnumberOfSteps(); Matrix result(m,n); double s = A.getinitialTime(); double h = (getfinalTime() - s)/n; //this is the size of the time step Matrix currentVector = A.getinitialValue(); for (int j=0; j<n; j++){ Matrix evaluationVector = evaluate(A.getRHS(),s,currentVector); //h*F(tk,v(k)) Matrix eulerVector = currentVector + (h* evaluationVector); //v(k) + F(tk,v(k)) currentVector = currentVector + 0.5*h * (evaluationVector + evaluate(A.getRHS(),s+h,eulerVector)); //v(k+1) s+=h; result.insertColumn(currentVector,j); } return result; } Matrix MidpointMethod::solve(const FirstOrderODE& A){ //Uses the Midpoint Method to solve the ODE //the value at time step k+1 ie. (v(k+1)) is as follows //v(k+1)=v(k)+h*F(tk+0.5*h, v(k)+0.5*h*F(tk,v(k))) int m = A.getorder(); int n = getnumberOfSteps(); Matrix result(m,n); double s = A.getinitialTime(); double h = (getfinalTime() - s)/n; Matrix currentVector = A.getinitialValue(); for (int j=0; j<n; j++){ Matrix eulerVector = currentVector + 0.5*h*evaluate(A.getRHS(),s,currentVector);//v(k)+0.5*h*F(tk,v(k)) currentVector = currentVector + h*evaluate(A.getRHS(),s+0.5*h,eulerVector); s+=h; result.insertColumn(currentVector,j); } return result; } Matrix RK4::solve(const FirstOrderODE& A){ //Uses the Runge-Kutta Method of order 4 to solve the ODE //the value at time step k+1 ie. (v(k+1)) is as follows //v(k+1)=v(k)+(h/6.0)*[F(tk,v(k))+2F(t2k,v2k)+2F(t3k,v3k)+F(t4k,v4k)] where //t2k = tk+0.5h v2k = u(k) + 0.5h*F(tk,vk) //t3k = t2k v3k = u(k) + 0.5h*F(t2k,v2k) //t4k = tk+h v4k = u(k) + h*F(t3k,v3k) int m = A.getorder(); int n = getnumberOfSteps(); Matrix result(m,n); double s = A.getinitialTime(); double h = (getfinalTime() - s)/n; Matrix currentVector = A.getinitialValue(); for (int j=0;j<n;j++){ double s2 = s+ 0.5*h; //t2k double s4 = s+ h; //t4k Matrix e1 = evaluate(A.getRHS(),s,currentVector); //F(tk,vk) Matrix u2 = currentVector + 0.5*h*e1; //v2k Matrix e2 = evaluate(A.getRHS(),s2,u2); //F(t2k,v2k) Matrix u3 = currentVector + 0.5*h*e2; //v3k Matrix e3 = evaluate(A.getRHS(),s2,u3); //F(t3k,v2k) Matrix u4 = currentVector + h*e3; //v4k currentVector = currentVector + (h/6.0) * (e1+2*e2+2*e3+evaluate(A.getRHS(),s4,u4)); //v(k)+(h/6.0)*[F(tk,v(k))+2F(t2k,v2k)+2F(t3k,v3k)+F(t4k,v4k)] s=s4; //the next time step should be t+h which is t4k result.insertColumn(currentVector,j); } return result; }
true
f263bffeae286a40edbba3998b41db5c7d7780cf
C++
e8yes/eyes-connect
/src/stopwatch.cpp
UTF-8
593
2.765625
3
[]
no_license
#include <ctime> #include "stopwatch.h" StopWatch::StopWatch() { } unsigned StopWatch::begin(unsigned total_amount) { m_total = total_amount; m_begin = clock(); m_last = m_begin; return m_begin; } float StopWatch::dt() const { return m_dt; } float StopWatch::check_point() { clock_t incum = clock(); float elapsed = (incum - m_last)/(float) CLOCKS_PER_SEC*1000; m_dt = elapsed/m_total; m_last = incum; float used = (incum - m_begin)/(float) CLOCKS_PER_SEC*1000; return 1.0f - used/(float) m_total; }
true
f795b5dbf77889c01e584530d59fb4fb0420b409
C++
ImranIsmael/C
/5-Constructors.cpp
UTF-8
768
3.734375
4
[]
no_license
//Constructors #include <iostream> #include <string> using namespace std; //Constructors does not have a return type so we do not need to type in int/void/string etc //Constructors name is always the same as the class name //Main reason to use constructors is to give variable initial value* //You can create multiple object from the same class that does not ovewrite each other. class DirasClass { public: DirasClass(string z) //Constructors { setName(z); } void setName(string x) { name=x; } string getName() { return name; } private: string name; }; int main() { DirasClass do1 ("Dira Nad Iff"); cout << do1.getName() << endl; DirasClass do2 ("Im Imran John"); cout << do2.getName(); return 0; }
true
5596e3ddbf6c870afcb449746b2353de9c96bcec
C++
guihunkun/LeetCode
/307.cpp
UTF-8
1,907
3.9375
4
[]
no_license
/* class NumArray { public: vector<int> cur; NumArray(vector<int>& nums) { for(int i = 0; i < nums.size(); i++) cur.push_back(nums[i]); } void update(int i, int val) { cur[i] = val; } int sumRange(int i, int j) { int sum = 0; for(; i <= j; i++) sum += cur[i]; return sum; } }; */ class NumArray { public: vector<int> tree; int n; NumArray(vector<int>& nums) { if(nums.size() > 0) { n = nums.size(); tree.resize(n*2, 0); buildTree(nums); } } void buildTree(vector<int>& nums) { for(int i = n, j = 0; i < 2*n; i++, j++) tree[i] = nums[j]; for(int i = n - 1; i > 0; --i) tree[i] = tree[i*2] + tree[i*2 + 1]; } void update(int i, int val) { i += n; tree[i] = val; while(i > 0) { int left = i; int right = i; if (i % 2 == 0) { right = i + 1; } else { left = i - 1; } // parent is updated after child is updated tree[i / 2] = tree[left] + tree[right]; i /= 2; } } int sumRange(int i, int j) { i += n; j += n; int sum = 0; while(i <= j) { if ((i % 2) == 1) { sum += tree[i]; i++; } if ((j % 2) == 0) { sum += tree[j]; j--; } i /= 2; j /= 2; } return sum; } }; /** * Your NumArray object will be instantiated and called as such: * NumArray* obj = new NumArray(nums); * obj->update(i,val); * int param_2 = obj->sumRange(i,j); */
true
c152ee298c75838c8bd143048b3a1132c56a04cd
C++
Morpheu5/qtuiotouch
/include/dosc/decoder.hpp
UTF-8
2,752
2.546875
3
[]
no_license
/// UNCLASSIFIED #ifndef DOSC_DECODER_HEAD #define DOSC_DECODER_HEAD #include "bytes.hpp" #include <string> #include <map> #include <boost/function.hpp> #include <boost/cstdint.hpp> namespace dosc { using boost::int32_t; using boost::int64_t; enum osc_type_tags { osc_int32_tag = 'i', // 4 bytes, int32_t osc_float_tag = 'f', // 4 bytes, float osc_string_tag = 's', // variable osc_blob_tag = 'b', // variable osc_int64_tag = 'h', // 8 bytes, int64_t osc_time_tag = 't', // 8 bytes osc_double_tag = 'd', // 8 bytes, double osc_alt_string_tag = 'S',// variable osc_char_tag = 'c', // 4 bytes, char osc_rgba_tag = 'r', // 4 bytes, 32 bit RGBA color osc_midi_tag = 'm', // 4 byte MIDI message osc_true_tag = 'T', // True. No bytes are allocated in the argument data osc_false_tag = 'F', // False. No bytes are allocated in the argument data osc_nil_tag = 'N', // Nil. No bytes are allocated in the argument data osc_infinitum_tag = 'I', // Infinitum. No bytes are allocated in the argument data osc_array_beg_tag = '[', // Indicates the beginning of an array osc_array_end_tag = ']', // Indicates the end of an array }; void chomp_string(const_buffer_range& range, const size_t max_nul); int32_t decode_int32_tag(const_buffer_range& range); int64_t decode_int64_tag(const_buffer_range& range); float decode_float_tag(const_buffer_range& range); double decode_double_tag(const_buffer_range& range); const char* decode_string_tag(const_buffer_range& range); class decoder { public: // callback function accepts: address, type_string, osc_arguments typedef boost::function<void (std::string, std::string, const_buffer_range)> function_type; static const std::string all; void operator()(const bytes_ptr packet); private: typedef std::map<std::string, function_type> map_type; map_type methods_; ///< address methods; invoked when new messages arrive std::string address_; ///< Current address pattern std::string type_; ///< Current type string const_buffer_iterator parse(const_buffer_range); const_buffer_iterator parse_message(const_buffer_range); const_buffer_iterator parse_bundle(const_buffer_range); template <class Handler> friend void add_method(decoder& dcd, const std::string& address_pattern, Handler h); }; // class decoder template <class Handler> void add_method(decoder& dcd, const std::string& address_pattern, Handler h) { dcd.methods_[address_pattern] = h; } } // namespace dosc #endif // DOSC_DECODER_HEAD
true
d522ccd6eee02ff4fd52c4977b43a9e53d272013
C++
mertsalik/kruskal-with-disjointset
/Kruskal_DisjointSet/Kruskal_DisjointSet/Graph.cpp
UTF-8
1,154
3.109375
3
[]
no_license
#include "Graph.h" #include <algorithm> Graph::Graph(void) { } Graph::Graph(string CityFilename,string FlightFilename) { readCityData(CityFilename); readFlightData(FlightFilename); } Graph::~Graph(void) { } void Graph::readFlightData(string Filename) { std::ifstream input( Filename); int counter = 0; for( std::string line; getline( input, line ); ) { vector<string> words = split(line, ","); Edge* edge = new Edge(); edge->left = Node::findNodeByData(nodes,words[0]); edge->right = Node::findNodeByData(nodes,words[1]); edge->cost = atoi(words[2].c_str()); edge->id = counter; edges.push_back(edge); counter++; } } void Graph::readCityData(string Filename) { std::ifstream input( Filename); int counter = 0; for( std::string line; getline( input, line ); ) { string word; istringstream iss(line, istringstream::in); while( iss >> word ) { Node* city = new Node(word,counter); nodes.push_back(city); this->sets.AddElement(city); } //DisjointSets::printElementSets(this->sets); counter++; } }
true
834ad07562c9fbc487cabff778362ac4a6eb9111
C++
protectors/ACM
/UVA/UVA10082-WERTYU.cpp
UTF-8
458
2.515625
3
[]
no_license
//UVA10082 #include <cstdio> #include <iostream> #include <algorithm> #include <string> #include <stack> #include <vector> #include <map> using namespace std; int main() { char s[]={"`1234567890-=QWERTYUIOP[]\\ASDFGHJKL;'ZXCVBNM,./"}; int i,c; while((c=getchar())!=EOF) { for(i=1;s[i]&&s[i]!=c;i++); if(s[i]) putchar(s[i-1]); else putchar(c); } return 0; }
true
c00230293b5f7f6985e9ad4a145b22381ce9596c
C++
Liby99/RaytracerOld
/src/util/Color.cpp
UTF-8
250
2.984375
3
[]
no_license
#include "Color.h" Color::Color() { r = 0; g = 0; b = 0; } Color::Color(vec3 color) { r = color.x; g = color.y; b = color.z; } Color::Color(float r, float, g, float b) { this->r = r; this->g = g; this->b = b; }
true
e990f061f49877bd44a04d7cc5af566e4fab21e6
C++
ggasper/RSSAggregator
/src/ui/favouritestar.cpp
UTF-8
1,405
2.5625
3
[]
no_license
#include "favouritestar.h" FavouriteStar::FavouriteStar() { m_state = false; star = new QPolygonF; test = new QPolygonF; for (int i = 0; i < 5; ++i) { double perCircle = i / 5.0; double perInner = (i+3)%5 / 5.0; qDebug() << 2*QPointF(std::sin(perCircle*2*PI), (-1)*std::cos(perCircle*2*PI)); qDebug() << QPointF((-1)*std::sin(perCircle*2*PI), std::cos(perCircle*2*PI)); star->append(2*QPointF(std::sin(perCircle*2*PI), (-1)*std::cos(perCircle*2*PI))); star->append(QPointF((-1)*std::sin(perInner*2*PI), std::cos(perInner*2*PI))); } } void FavouriteStar::paint(QPainter *painter, const QRect &rect, const QPalette &pallete) const { painter->save(); if(m_state) { painter->setBrush(pallete.dark()); } else{ painter->setBrush(Qt::NoBrush); } painter->setRenderHint(QPainter::Antialiasing, true); painter->setPen(QPen(Qt::black, 0.1)); painter->translate(rect.x() + rect.width()/2, rect.y() + rect.height()/2); painter->scale(5, 5); //painter->drawPolygon(*test, Qt::WindingFill); //painter->setBrush(pallete.light()); painter->drawPolygon(*star, Qt::WindingFill); //painter->drawPolygon(*star); painter->restore(); } QSize FavouriteStar::sizeHint(const QRect &rect) { return QSize(10,10); } void FavouriteStar::setState(bool state) { m_state = state; }
true
83aa1af232e70bcd446841154cf46b34f2dc4b65
C++
KayvanMazaheri/acm
/codeforces/197a.plate-game/197a.cpp
UTF-8
162
2.84375
3
[ "MIT" ]
permissive
#include <iostream> using namespace std; int main() { int a, b, r; cin >> a >> b >> r; cout << (2 * r > min(a, b) ? "Second" : "First") << endl; return 0; }
true
254414f134ebf4f5cc7f0c14fb1172770c22f731
C++
qqdown/LeetCode
/LeetCode/307.h
WINDOWS-1252
1,762
3.203125
3
[]
no_license
#pragma once #include "leetcode.h" namespace _307 { class NumArray { public: NumArray(vector<int> nums) { size = nums.size(); int initsize = nums.size() * 4 + 10; this->segTree = new int[initsize]; memset(segTree, 0, initsize*sizeof(int)); buildTree(1, 0, nums.size() - 1, nums); } void update(int i, int val) { updateTree(1, 0, size - 1, i, val); } int sumRange(int i, int j) { return sumTree(1, 0, size - 1, i, j); } private: int* segTree;//߶ int size; void buildTree(int node, int begin, int end, vector<int>& nums) { if (begin > end) return; if (begin == end) segTree[node] = nums[begin]; else { int m = (begin + end) / 2; buildTree(2 * node, begin, m, nums); buildTree(2 * node + 1, m + 1, end, nums); segTree[node] = segTree[2 * node] + segTree[2 * node + 1]; } } void updateTree(int node, int begin, int end, int target, int newValue) { if (begin > end) return; if (begin == end) { segTree[node] = newValue; return; } int m = (begin + end) / 2; if (target <= m) updateTree(node * 2, begin, m, target, newValue); else updateTree(node * 2 + 1, m + 1, end, target, newValue); segTree[node] = segTree[node * 2] + segTree[node * 2 + 1]; } int sumTree(int node, int begin, int end, int from, int to) { if (begin > end) return 0; if (from == begin && end == to) return segTree[node]; if (begin == end) return segTree[node]; int m = (begin + end) / 2; if (to <= m) return sumTree(node * 2, begin, m, from, to); if (from > m) return sumTree(node * 2 + 1, m + 1, end, from, to); return sumTree(node * 2, begin, m, from, m) + sumTree(node * 2 + 1, m+1, end, m+1, to); } }; }
true
1d2dda8263a5797ef85704dab2aceef73a98f4cb
C++
tinaba96/master
/major_research/others/modified_q3DanQ/src/host/m.cpp
UTF-8
5,601
2.5625
3
[]
no_license
#include <iostream> #include <iomanip> #include <random> #include <string> #include <cstring> #include <fstream> #include <sstream> #include "../kernel/kernel.cpp" //#include "get_data.h" //#include "loss.h" //#include "optimizer.h" //conv -> relu -> maxpooling -> affine -> relu -> affine -> sigmoid using namespace std; class cnn { public: float paramsw1[26*4*320]; float gradsw1[26*4*320]; float paramsb1[975*320]; float gradsb1[975*320]; float paramsw2[75*320*925]; float paramsb2[925]; float gradsb2[925]; float gradsw2[75*925*320]; float paramsw3[925*919]; float paramsb3[919]; float gradsb3[919]; float gradsw3[925*919]; float h1[26*4*320]; float h2[975*320]; //float *h3 = new float[75*320*925]; float h3[75*320*925]; float h4[925]; float h5[925*919]; float h6[919]; conv1d a = conv1d(); relu b = relu(); mpool c = mpool(); fullc d = fullc(); relu2 e = relu2(); fullc2 f = fullc2(); sigmoid g = sigmoid(); //relu3 g = relu3(); cnn() { //weight initialization std::random_device rnd; std::mt19937 mt(rnd()); std::uniform_int_distribution<> rand(-1000, 1000); for(int i = 0; i < 26*4*320; ++i) { paramsw1[i] = rand(mt)/1000.00; gradsw1[i] = 0; } for(int i = 0; i < 975*320; ++i) { paramsb1[i] = rand(mt)/1000.00; gradsb1[i] = 0; } for(int i = 0; i < 925*75*320; ++i) { paramsw2[i] = rand(mt)/1000.00; gradsw2[i] = 0; } for(int i = 0; i < 925; ++i) { paramsb2[i] = rand(mt)/1000.00; gradsb2[i] = 0; } for(int i = 0; i < 925*919; ++i) { paramsw3[i] = rand(mt)/1000.00; gradsw3[i] = 0; } for(int i = 0; i < 919; ++i) { paramsb3[i] = rand(mt)/1000.00; gradsb3[i] = 0; } } void predict(float *x, float *y) { a.forward(x, y, paramsw1, paramsb1); b.forward(y, x); c.forward(x, y); e.forward(x, y); // relu2 f.forward(y, x, paramsw3, paramsb3); //full-connected g.forward(x, y); } void gradient(float *dout, float *y) { g.backward(dout, y); //sigmoid f.backward(dout, paramsw3, gradsw3, gradsb3); //full_connected2 e.backward(dout); //relu2 d.backward(dout, paramsw2, gradsw2, gradsb2); //full_connected c.backward(dout); //maxpooling b.backward(dout); //relu a.backward(dout, paramsw1, gradsw1, gradsb1); //convolution } }; int main() { int epochs = 10; float lossval = 0; cnn *z = new cnn(); bcross_entropy loss = bcross_entropy(); for(int ep = 0; ep < epochs; ++ep) { float x[4000]; //std::cout << sizeof(x) << std::endl; float y[975*320]; float t[919]; //std::cout << sizeof(x) << std::endl; //std::cout << *x << std::endl; float n = 0; float *l; l = &n; //ifstream stream("data/sampledatax.csv"); ifstream stream("data/sampledatax.csv"); string line = ""; //ifstream stream3("data/sampledata.csv"); ifstream stream3("data/sampledata.csv"); string linet = ""; while (getline(stream, line) && getline(stream3, linet)) { int i = 0; string tmp = ""; istringstream stream2(line); while (getline(stream2, tmp, ',')) { try { float tmp2 = std::stoi(tmp); x[i] = (tmp2); //std::cout << x[i]; i++; }catch(...){ //printf("error\n"); break; } } int ti = 0; //while (getline(stream3, line)) //{ string tmpt = ""; istringstream stream4(linet); while (getline(stream4, tmpt, ',')) { try { float tmpt2 = std::stoi(tmpt); t[ti] = (tmpt2); //std::cout << y[ti]; ti++; }catch(...){ printf("error\n"); break; } } float dout[919]; for(int i = 0; i < 919; ++i) { dout[i] = {1}; //std::cout << t[i] << " : "; //std::cout << y[i]; } //cnn z = cnn(); //cnn z; //with this pattern, loss will be -nan z->predict(x, y); //forward for(int i = 0; i < 919; ++i) { //std::cout << x[i]; } //z->loss(x, t, l); *l = 0; loss.forward(y, t, l); //std::cout << "l : " << *l << endl; lossval += *l; loss.backward(dout, t); for(int i = 0; i < 919; ++i) { //std::cout << dout[i] << ":"; } z->gradient(dout, y); //backward for(int i = 0; i < 33280; ++i) { //std::cout << z->a.paramsw1[i]; } for(int i = 0; i < 320; ++i) { //std::cout << z->paramsw1[i]; //std::cout << z->a.gradsw1[i]; } } std::cout << "loss : " << lossval/10 << endl; lossval = 0; rmsprop opt; opt.update(z->paramsw1, z->gradsw1, z->h1, 26*4*320); for(int i = 0; i < 33280; ++i) { z->gradsw1[i] = 0; } opt.update(z->paramsb1, z->gradsb1, z->h2, 975*320); //std::cout << "checkcheck" << endl; for(int i = 0; i < 320; ++i) { //std::cout << z->paramsw1[i]; //std::cout << z->d->gradsw2[i]; } for(int i = 0; i < 975*320; ++i) { z->gradsb1[i] = 0; } opt.update(z->paramsw2, z->gradsw2, z->h3, 75*320*925); opt.update(z->paramsb2, z->gradsb2, z->h4, 925); for(int i = 0; i < 75*925*320; ++i) { z->gradsw2[i] = 0; } for(int i = 0; i < 925; ++i) { z->gradsb2[i] = 0; } //std::cout << "checkcheck" << std::endl; opt.update(z->paramsw3, z->gradsw3, z->h5, 925*919); opt.update(z->paramsb3, z->gradsb3, z->h6, 919); for(int i = 0; i < 919*925; ++i) { //std::cout << z->paramsw3[i]; //std::cout << z->gradsw3[i]; z->gradsw3[i] = 0; } for(int i = 0; i < 919; ++i) { z->gradsb3[i] = 0; } } return 0; } }
true
e058bd3893c2501efe02c70be92fd549789a8ca7
C++
henriquedavid/snaze
/include/ia_astar.h
UTF-8
9,810
3.0625
3
[]
no_license
#include "ai.hpp" /// === ALIASES === using pPair = std::pair<uint, std::pair<uint, uint>>; /// == STRUCTURES == /// A Cell with 'f', 'g', 'h' values. Cell::Cell(Point p): parent(std::make_pair(p.x,p.y)), HasParent(true), f(0u), g(0u), h(0u) { } Cell::Cell(std::pair<int,int> p): parent(p), HasParent(true), f(0u), g(0u), h(0u) { } bool AI::isValid(Point p, Level & niv) { auto atual = niv.get_current_level(); return p.x < atual.return_x() and p.y < atual.return_y(); } bool AI::isUnBlocked(Point p, Level & niv) { auto atual = niv.get_current_level(); if(atual.get_value(p.x, p.y) != '#' and atual.get_value(p.x, p.y) != '-') return true; return false; } bool AI::isDestination(Point p, Apple & apple) { auto applePos = apple.get_coordenadas(); if(p.x == applePos.first and p.y == applePos.second){ return true; } return false; } double AI::calculateHValue(Point p, Apple & apple) { /// Retorna o valor utilizando a formula da distância. auto applePos = apple.get_coordenadas(); return abs(int(p.x - applePos.first)) + abs(int(p.y - applePos.second)); } void AI::tracePath( Apple & apple) { auto applePos = apple.get_coordenadas(); Cell current_cell = Cell(applePos); Cell current_parent = m_cellDetails[current_cell.parent.first][current_cell.parent.second]; Direction dir; while(!(current_cell.parent == current_parent.parent)){ if(current_parent.parent.second == current_cell.parent.second){ if(current_parent.parent.first > current_cell.parent.first) dir = Direction::N; else dir = Direction::S; } else{ if(current_parent.parent.second > current_cell.parent.second) dir = Direction::W; else dir = Direction::E; } m_path.push(dir); current_cell = current_parent; current_parent = m_cellDetails[current_cell.parent.first][current_cell.parent.second]; } } /// Run A* Search Algorithm bool AI::aStarSearch( Level & lvl, Apple & app, Snaze & sna ) { // Obtem as coordenadas da cobra e da maçã. std::pair<int,int> coorde = sna.get_position(); std::pair<int,int> coordeApple = app.get_coordenadas(); // Atribui as coordenadas a uma classe Point. Point appll(coordeApple.first, coordeApple.second); Point src(coorde.first, coorde.second); // Verifica se o ponto da cobra está dentro do mapa. if (!isValid(src, lvl)) throw std::runtime_error("Source is invalid."); // Verifica se o ponto da maçã está no mapa. if (!isValid(appll, lvl)) throw std::runtime_error("Destination is invalid."); // Verifica se a origem e o destino não estão disponiveis. if (!isUnBlocked(src,lvl) or !isUnBlocked(appll, lvl)) throw std::runtime_error("Source or the destination is blocked\n"); // Recebe o mapa do nível atual. Maps map = lvl.get_current_level(); // Cria uma lista fechada e inicializa com falso, de forma que nenhuma célula tenha sido inicializada // ainda. bool closedList[map.return_x()][map.return_y()]; memset(closedList, false, sizeof (closedList)); m_cellDetails.resize(map.return_x()); int i, j; for (i = 0; i < map.return_x(); ++i) { m_cellDetails[i].resize(map.return_y()); for (j = 0; j < map.return_y(); ++j) { m_cellDetails[i][j].f = UINT_MAX; m_cellDetails[i][j].g = UINT_MAX; m_cellDetails[i][j].h = UINT_MAX; m_cellDetails[i][j].HasParent = false; } } // Inicializa os parâmetros da A*. i = src.x, j = src.y; m_cellDetails[i][j].f = 0; m_cellDetails[i][j].g = 0; m_cellDetails[i][j].h = 0; m_cellDetails[i][j].HasParent = true; m_cellDetails[i][j].parent = std::make_pair(i, j); // Cria uma lista aberta para armazenar os valores de f, g e h, de forma que f = g + h. std::set<pPair> openList; // Coloca a primeira posição na lista aberta e configura para o f ser 0. openList.insert(std::make_pair(0.0, std::make_pair (i, j))); while (!openList.empty()) { pPair p = *openList.begin(); // Remove esta posição da lista. openList.erase(openList.begin()); // Adiciona a posição a lista fechada. i = p.second.first; j = p.second.second; closedList[i][j] = true; uint gNew, hNew, fNew; // Para cada uma das 4 posições verifica a partir da posição que se encontra. Point points[4] = {Point(i, j+1), Point(i, j-1), Point(i+1, j), Point(i-1, j)}; uint c; for(c = 0; c < 4; c++) { Point& current_point = points[c]; // Só executa este pocesso se for válida a posição. if (isValid(current_point, lvl)) { // Se o destino for válido é igual ao sucessor atual. if (isDestination(current_point, app)) { // Configura o 'parent' da posição de destino. m_cellDetails[current_point.x][current_point.y].parent = std::make_pair(i,j); m_cellDetails[current_point.x][current_point.y].HasParent = true; tracePath(app); return true; } // Se o sucessor já está na lista fechada ou está bloqueada então ignore. Caso contrário siga. else if (closedList[current_point.x][current_point.y] == false and isUnBlocked(current_point, lvl) == true) { gNew = m_cellDetails[i][j].g + 1; hNew = calculateHValue(current_point, app); fNew = gNew + hNew; // Se não está na lista aberta, adicione-a. Faça a posição atual ser a posição do parent. // Grava os valores de f, g e h da posição. if (m_cellDetails[current_point.x][current_point.y].f == UINT_MAX or m_cellDetails[current_point.x][current_point.y].f > fNew) { openList.insert( std::make_pair(fNew, std::make_pair(current_point.x, current_point.y))); // Atualiza as informações da célula (bloco). m_cellDetails[current_point.x][current_point.y].f = fNew; m_cellDetails[current_point.x][current_point.y].g = gNew; m_cellDetails[current_point.x][current_point.y].h = hNew; m_cellDetails[current_point.x][current_point.y].parent = std::make_pair(i,j); m_cellDetails[current_point.x][current_point.y].HasParent = true; } } } } } return false; } Direction AI::goto_free_way( Level & lvl, Apple & app, Snaze & sna ) { // Retorna as coordenadas da cobra. std::pair<int,int> coorder = sna.get_position(); // Cria um Point com as coordenadas da cobra. Point src(coorder.first, coorder.second); // Recebe o nível atual. Maps & map = lvl.get_current_level(); // Armazena todas as possíveis rotas (cima, baixo, esquerda, direita). Point points[] = {Point(src.x-1, src.y), Point(src.x+1, src.y), Point(src.x, src.y-1), Point(src.x, src.y+1)}; uint min_h = UINT_MAX; auto min_h_dir = ++m_last_move; uint c; for(c = 0; c < 4; ++c) { // Obtem qual a orientação a ser seguida. Point c_ = points[c]; // Obtem as posições. int x_ = c_.x; int y_ = c_.y; // Obtem o que há naquela posição do mapa. auto object = map.get_value(x_, y_); // Verifica se não está bloqueado. if(object != '#' and object != '-') { auto dir = src*points[c]; if(dir == !m_last_move and sna.get_tamanho() == 1) continue; // Calcula o novo valor de H. auto h = calculateHValue(points[c], app); // Verifica se o menor valor de h é h ou min_h, se sim muda. if(h < min_h) { min_h = h; min_h_dir = dir; } } } // Muda o último movimento realizado. m_last_move = min_h_dir; // Retorna o último movimento. return m_last_move; } Direction AI::next_move( Level & lvl, Apple & app, Snaze & sna) { // Recebe a posição da maçã. m_goal = app.get_coordenadas(); // Recebe a posição da cobra. std::pair<int,int> coord = sna.get_position(); // Cria um Point com os dados de origem. Point src(coord.first, coord.second); // Verifica se já não é a origem. if(isDestination(src, app)) { return goto_free_way(lvl, app, sna); } // Verifica se o caminho não está livre. if(!m_path.empty()) { auto dir = m_path.top(); m_path.pop(); return dir; } // Limpa qualquer dado presente nos dados de cada bloco. m_cellDetails.clear(); // Caso não foi encontrado o caminho então busque. if(aStarSearch( lvl, app, sna )) { auto dir = m_path.top(); if(m_path.empty()) throw std::runtime_error("[ERROR]: invalid search return\n"); m_path.pop(); return dir; } // Percorre a direção para ver se é possível percorrer. auto dir = goto_free_way(lvl, app, sna); return dir; }
true
9e3e5ac96978ab8392344ca67ab5b1044fda3a55
C++
tobias-froehlich/beegenerator
/test/test_Generator.cpp
UTF-8
1,337
2.8125
3
[]
no_license
#include "../src/Generator.h" TEST (Generator, create_and_delete ) { Generator* generator_ptr; Parameters* parameters_ptr = new Parameters(); parameters_ptr->read_file( "../test/testfiles/generator_parameters_wrong1.txt"); ASSERT_THROW( generator_ptr = new Generator(parameters_ptr, 0), std::invalid_argument ); delete parameters_ptr; parameters_ptr = new Parameters(); parameters_ptr->read_file( "../test/testfiles/generator_parameters.txt"); generator_ptr = new Generator(parameters_ptr, 0); ASSERT_EQ(generator_ptr->getImageWidth(), 200); ASSERT_EQ(generator_ptr->getImageHeight(), 200); ASSERT_EQ(generator_ptr->getBorderWidth(), 300); delete generator_ptr; } TEST (Generator, write_image) { Parameters* parameters_ptr = new Parameters(); parameters_ptr->read_file("../test/testfiles/generator_parameters.txt"); Generator generator(parameters_ptr, 0); generator.writeImage("/tmp/test_bees.png"); delete parameters_ptr; } TEST (Generator, makeVideo) { std::srand(std::time(nullptr)); Parameters* parameters_ptr = new Parameters(); parameters_ptr->read_file("../test/testfiles/generator_parameters.txt"); Generator generator(parameters_ptr, 0); generator.makeVideo(); delete parameters_ptr; }
true
c48c60745694b260dab6e5cd34949db0803fa1a2
C++
libo8621696/CPP_Course3
/eclipse/main9_2.cpp
UTF-8
663
2.671875
3
[]
no_license
#include<iostream> using namespace std; int main(){ char s1[80], s2[80]; cin.getline(s1, 80); cin.getline(s2, 80); int len1 = 0, len2 = 0; for(len1 =0; s1[len1]!= '\0'; len1++); for(len2 =0; s2[len2]!= '\0'; len2++); for(int j=0; j<len1; j++) { if(s1[j]>=97&&s1[j]<=122) s1[j]-=32; if(s2[j]>=97&&s2[j]<=122) s2[j]-=32; } int i = 0; char result; while (s1[i] != '\0' && (s1[i] == s2[i])){ i++; } if (s1[i] > s2[i]) { result = '>'; } else if (s1[i] < s2[i]) { result = '<'; } else{ result = '='; } cout << result << endl; return 0; }
true
17057e0643a04a9ac1f41aeebb2a4327055f58fc
C++
yiorgosynkl/ntua-ece-progintro
/lowsum/lowsum.cpp
UTF-8
1,067
3.140625
3
[]
no_license
/********************************************************************** * Project : ntua-ece-progintro * Program name : lowsum.cpp * Author : yiorgosynkl (find me in Github: https://github.com/yiorgosynkl) * Date created : 20200115 * Purpose : find a sum of 2 numbers closest to 0 (in a sorted array) **********************************************************************/ #include <iostream> #include <cmath> // abs using namespace std; int main(){ long n_nums; cin >> n_nums; long *nums = new long[n_nums]; for (long i=0; i<n_nums; i++) cin >> nums[i]; long neg_idx = 0, pos_idx = n_nums - 1; long best_sum = nums[neg_idx] + nums[pos_idx]; long sum = 0; while (neg_idx < pos_idx){ sum = nums[neg_idx] + nums[pos_idx]; if (abs(best_sum) > abs(sum)) best_sum = sum; if (sum > 0) pos_idx--; else if (sum < 0) neg_idx++; else break; } cout << best_sum << endl; return 0; }
true
894b1ee95b04bc2b8981f30e7afa33a30dddb58c
C++
AlexLeSang/ranges-example
/range-v3.hpp
UTF-8
478
3.140625
3
[]
no_license
#pragma once #include <range/v3/all.hpp> #include <vector> namespace range_v3 { decltype(auto) number_of_squared_integers_divisible_by_3_5_and_7( const std::vector<int> &numbers) { using namespace ranges; const auto squared = numbers | view::transform([](const auto v) { return v * v; }); const auto result = count_if(squared, [](const auto v) -> bool { return (v % 3 == 0 && v % 5 == 0 && v % 7 == 0); }); return result; } } // namespace range_v3
true
60690a5fd7d54ec92ea0d8090c42f1c8c3469432
C++
bonastos/yadif
/test/provider_test.cpp
UTF-8
1,849
2.5625
3
[ "BSL-1.0" ]
permissive
/* * Copyright 2015 Dirk Bonekamper * * Distributed under the Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include <catch.hpp> #include <yadif.hpp> #include <map> using namespace yadif; namespace { struct DestructionRegistry { void addPtr(void* p) {counters[p] = next++; } unsigned destructionCounter(void* p) const { return counters.at(p); } std::map<void*, unsigned> counters; unsigned next = 1; }; DestructionRegistry registry; struct A { ~A() { registry.addPtr(this); } }; struct B { ~B() { registry.addPtr(this); } }; struct C { ~C() { registry.addPtr(this); } }; struct D { D(A& a, B* bp, std::shared_ptr<C> cp) : a_{a}, bp_{bp}, cp_{cp} {} ~D() { registry.addPtr(this); } A& a_; B* bp_; std::shared_ptr<C> cp_; }; using AProvider = Provider<A>; using BProvider = Provider<B>; using CProvider = Provider<C>; using DProvider = Provider<D, Ref<A>, Ptr<B>, SharedPtr<C>>; struct TestModule : yadif::Module { void configure() const override { bind<A>().toProvider(AProvider{}); bind<B>().toProvider(BProvider{}); bind<C>().toProvider(CProvider{}); bind<D>().toProvider(DProvider{}); } }; } TEST_CASE("Provider template") { Injector injector{TestModule{}}; A* ap = nullptr; B* bp = nullptr; C* cp = nullptr; D* dp = nullptr; { std::shared_ptr<D> spd = injector.get<D>(); dp = spd.get(); ap = &dp->a_; bp = dp->bp_; cp = dp->cp_.get(); } CHECK( registry.destructionCounter(dp) < registry.destructionCounter(ap) ); CHECK( registry.destructionCounter(dp) < registry.destructionCounter(bp) ); CHECK( registry.destructionCounter(dp) < registry.destructionCounter(cp) ); }
true
aa5a43718525b0980194dfaa09e8e07cfffe3b73
C++
dshnightmare/LeetCodeC
/src/MergeInterval.cpp
UTF-8
1,049
3.1875
3
[]
no_license
#include <iostream> #include <vector> using namespace std; struct Interval { int start; int end; Interval() : start(0), end(0) {} Interval(int s, int e) : start(s), end(e) {} }; class Solution{ public: vector<Interval> merge(vector<Interval> &intervals){ vector<Interval> result; if(intervals.size() == 0) return result; sort(intervals.begin(), intervals.end(), customLess); Interval *cur = new Interval(intervals[0].start, intervals[0].end); for(int i = 1; i < intervals.size(); i++){ if(intervals[i].start <= cur->end){ cur->start = min(cur->start, intervals[i].start); cur->end = max(cur->end, intervals[i].end); } else{ result.push_back(*cur); cur = new Interval(intervals[i].start, intervals[i].end); } } result.push_back(*cur); return result; } private: struct COMP{ bool operator()(const Interval &ele1, const Interval &ele2) { if(ele1.start == ele2.start) return ele1.end < ele2.end; return ele1.start < ele2.start; } } customLess; }; int main(){ return 0; }
true
ffb8dba1947a6ee6040ebc39060b2a45c4c7d5ac
C++
Mike2208/Monte_Carlo
/Monte_Carlo/algorithm_voronoi_fields.cpp
UTF-8
7,548
2.78125
3
[]
no_license
#include "algorithm_voronoi_fields.h" bool ALGORITHM_VORONOI_FIELDS::DISTRICT_CHANGE_VECTOR::AreChangedIDs(const ID &DistrictID1, const ID &DistrictID2) const { for(const auto &curChange : *this) { if((curChange.OldID == DistrictID1 && curChange.NewID == DistrictID2) || (curChange.OldID == DistrictID2 && curChange.NewID == DistrictID1)) return true; } return false; } ALGORITHM_VORONOI_FIELDS::SHORTEST_DIST_POS ALGORITHM_VORONOI_FIELDS::SKEL_MAP_SHORTEST_DIST_POS::ConvertToShortestDistPos(const ID_MAP &IDMap, const DIST_MAP &DistMap) const { ID curID = IDMap.GetPixel(this->Position); // The two connected districts ID adjacentID; // Find second position for(const auto navOption : NavigationOptions) { const POS_2D adjacentPos = this->Position+navOption; if(IDMap.GetPixel(adjacentPos, adjacentID) < 0) continue; // Skip if not in map if(adjacentID == curID) continue; // Same district, skip const DIST_MAP::CELL_TYPE adjacentDist = DistMap.GetPixel(adjacentPos); const MOVE_DIST_TYPE moveCost = GetMovementCost(this->Position, adjacentPos); if(adjacentDist <= this->Distance+moveCost && adjacentDist+moveCost >= this->Distance) { // Found adjacent position, create shortestDistPos return ALGORITHM_VORONOI_FIELDS::SHORTEST_DIST_POS(curID, adjacentID, this->Distance, this->Position, adjacentPos); } } // Return error value (shouldn't happen) return ALGORITHM_VORONOI_FIELDS::SHORTEST_DIST_POS(curID, curID, this->Distance, this->Position, this->Position); } ALGORITHM_VORONOI_FIELDS::SKEL_MAP_DATA::SKEL_MAP_DATA(const DIST_MAP::CELL_TYPE &_DistToPrevElement, const SKEL_MAP_SHORTEST_DIST_POS_ID &_PrevElementID) : DistToPrevElement(_DistToPrevElement), PrevElementID(_PrevElementID) { } ALGORITHM_VORONOI_FIELDS::SKEL_MAP_POS_DATA::SKEL_MAP_POS_DATA(const POS_2D &_Pos, const SKEL_MAP_DATA &_SkelMapData) : POS_2D(_Pos), SKEL_MAP_DATA(_SkelMapData) { } ALGORITHM_VORONOI_FIELDS::SKEL_MAP_POS_DATA::SKEL_MAP_POS_DATA(const POS_2D &_Pos, const DIST_MAP::CELL_TYPE &_DistToPrevElement, const SKEL_MAP_SHORTEST_DIST_POS_ID &_PrevElementID) : POS_2D(_Pos), SKEL_MAP_DATA(_DistToPrevElement, _PrevElementID) { } void ALGORITHM_VORONOI_FIELDS::SKEL_MAP_SHORTEST_DIST_POS_VECTOR::push_back(const value_type &element) { // If a previous element is listed, add this to list of next elements if(element.PrevElementID != ALGORITHM_VORONOI_FIELDS::SKEL_MAP_SHORTEST_DIST_POS_INVALID_ID) { const size_type newElementID = this->size(); this->at(element.PrevElementID).NextElementIDs.push_back(newElementID); } // Add element regularly static_cast<std::vector<SKEL_MAP_SHORTEST_DIST_POS>*>(this)->push_back(element); } void ALGORITHM_VORONOI_FIELDS::SKEL_MAP_SHORTEST_DIST_POS_VECTOR::push_back(value_type &&element) { // If a previous element is listed, add this to list of next elements if(element.PrevElementID != ALGORITHM_VORONOI_FIELDS::SKEL_MAP_SHORTEST_DIST_POS_INVALID_ID) { const size_type newElementID = this->size(); this->at(element.PrevElementID).NextElementIDs.push_back(newElementID); } // Add element regularly static_cast<std::vector<SKEL_MAP_SHORTEST_DIST_POS>*>(this)->push_back(std::move(element)); } ALGORITHM_VORONOI_FIELDS::SKEL_MAP_SHORTEST_DIST_POS *ALGORITHM_VORONOI_FIELDS::SKEL_MAP_SHORTEST_DIST_POS_VECTOR::FindClosestDist(const SKEL_MAP_SHORTEST_DIST_POS &CurDist, ALGORITHM_VORONOI_FIELDS::DIST_MAP::CELL_TYPE &Distance) const { ALGORITHM_VORONOI_FIELDS::DIST_MAP::CELL_TYPE backDist = 0; const ALGORITHM_VORONOI_FIELDS::SKEL_MAP_SHORTEST_DIST_POS *pBackDist = nullptr; if(CurDist.PrevElementID != ALGORITHM_VORONOI_FIELDS::SKEL_MAP_SHORTEST_DIST_POS_INVALID_ID) { // Continue backtracking until a valid position is found pBackDist = &CurDist; do { backDist += pBackDist->DistToPrevElement; pBackDist = &(this->at(pBackDist->PrevElementID)); } while(pBackDist->PrevElementID != ALGORITHM_VORONOI_FIELDS::SKEL_MAP_SHORTEST_DIST_POS_INVALID_ID && !pBackDist->ValidElement); if(pBackDist == nullptr) backDist = ALGORITHM_VORONOI_FIELDS::MAX_DIST; } else { backDist = ALGORITHM_VORONOI_FIELDS::MAX_DIST; } ALGORITHM_VORONOI_FIELDS::DIST_MAP::CELL_TYPE frontDist; const ALGORITHM_VORONOI_FIELDS::SKEL_MAP_SHORTEST_DIST_POS *pFrontDist = this->FindClosestDistForward(CurDist, frontDist); if(pFrontDist == nullptr) frontDist = ALGORITHM_VORONOI_FIELDS::MAX_DIST; // Resize to prevent errors if no front distance was found // If no other pos was found, just return nothing if(pBackDist == nullptr && pFrontDist == nullptr) { Distance = ALGORITHM_VORONOI_FIELDS::MAX_DIST; return nullptr; } // Return smaller distance if(backDist <= frontDist) { Distance = backDist; return const_cast<ALGORITHM_VORONOI_FIELDS::SKEL_MAP_SHORTEST_DIST_POS *>(pBackDist); } Distance = frontDist; return const_cast<ALGORITHM_VORONOI_FIELDS::SKEL_MAP_SHORTEST_DIST_POS *>(pFrontDist); } ALGORITHM_VORONOI_FIELDS::SKEL_MAP_SHORTEST_DIST_POS *ALGORITHM_VORONOI_FIELDS::SKEL_MAP_SHORTEST_DIST_POS_VECTOR::FindClosestDistForward(const SKEL_MAP_SHORTEST_DIST_POS &CurDist, ALGORITHM_VORONOI_FIELDS::DIST_MAP::CELL_TYPE &Distance) const { ALGORITHM_VORONOI_FIELDS::DIST_MAP::CELL_TYPE bestDist = ALGORITHM_VORONOI_FIELDS::MAX_DIST; const ALGORITHM_VORONOI_FIELDS::SKEL_MAP_SHORTEST_DIST_POS *pBestDist = nullptr; if(CurDist.NextElementIDs.size() == 0) { Distance = ALGORITHM_VORONOI_FIELDS::MAX_DIST; return nullptr; } // Go through all following distances for(const auto &curForwardDistID : CurDist.NextElementIDs) { const ALGORITHM_VORONOI_FIELDS::SKEL_MAP_SHORTEST_DIST_POS *pCurForwardDist = &(this->at(curForwardDistID)); // If this element was not erased if(pCurForwardDist->ValidElement) { // Check if this is best position if(pCurForwardDist->DistToPrevElement <= bestDist) { bestDist = pCurForwardDist->DistToPrevElement; pBestDist = pCurForwardDist; } } else { // Recursvely calculate shortest distance if this element was erased ALGORITHM_VORONOI_FIELDS::DIST_MAP::CELL_TYPE curDist = 0; const ALGORITHM_VORONOI_FIELDS::SKEL_MAP_SHORTEST_DIST_POS *pClosestDist = this->FindClosestDistForward(*pCurForwardDist, curDist); curDist += pCurForwardDist->DistToPrevElement; // Check if this is best position if(curDist <= bestDist && pClosestDist != nullptr) { bestDist = curDist; pBestDist = pClosestDist; } } } // Return results Distance = bestDist; return const_cast<ALGORITHM_VORONOI_FIELDS::SKEL_MAP_SHORTEST_DIST_POS *>(pBestDist); } DistrictMap *ALGORITHM_VORONOI_FIELDS::DISTRICT_STORAGE::FindDistrictID(const ID &DistrictID) { for(DISTRICT_STORAGE::size_type i=0; i<this->size(); ++i) { if(this->at(i).GetID() == DistrictID) return &(this->at(i)); } return nullptr; } ALGORITHM_VORONOI_FIELDS::DISTRICT_STORAGE::size_type ALGORITHM_VORONOI_FIELDS::DISTRICT_STORAGE::FindDistrictIDIterator(const ID &DistrictID) { for(DISTRICT_STORAGE::size_type i=0; i < this->size(); ++i) { if(this->at(i).GetID() == DistrictID) return i; } return this->size(); } ALGORITHM_VORONOI_FIELDS::SHORTEST_DIST_POS *ALGORITHM_VORONOI_FIELDS::SHORTEST_DIST_POS_VECTOR::FindID(const ID &ID1ToFind, const ID &ID2ToFind) { for(auto &curSDP : this->Poses) { if((ID1ToFind == curSDP.DistrictID1 && ID2ToFind == curSDP.DistrictID2) || (ID1ToFind == curSDP.DistrictID2 && ID2ToFind == curSDP.DistrictID1)) { return &curSDP; } } return nullptr; } template class AlgorithmVoronoiFields<float>;
true
80443626a811a73e5b55027150149e90b1503932
C++
pixled/pixled-lib
/src/pixled/signal/signal.cpp
UTF-8
541
2.828125
3
[]
no_license
#include "signal.h" namespace pixled { namespace signal { float Sine::operator()(led l, time t) const { return std::sin(2*PI * this->call<0>(l, t)); } float Square::operator()(led l, time t) const { return std::sin(2*PI * this->call<0>(l, t)) > 0 ? 1 : -1; } float Triangle::operator()(led l, time t) const { return 2 / PI * std::asin(std::sin( 2*PI * this->call<0>(l, t) )); } float Sawtooth::operator()(led l, time t) const { return 2 / PI * std::atan(std::tan( 2*PI * this->call<0>(l, t) )); } }}
true
c8126fd3f4c74702da90798a2a080e652072759a
C++
rsalinas6721/C-_Fantacy_Combat_Game
/blueMen.hpp
UTF-8
580
2.796875
3
[]
no_license
/* Author: Ricky Salinas Due Date: 5 August 2018 Description: BlueMen Class */ #ifndef BLUEMEN_HPP #define BLUEMEN_HPP #include "character.hpp" // Constructor and function prototypes for class are initialized class BlueMen : public Character { protected: std::string name; int armor; int strength; public: BlueMen(); int attack(); int bdefense(int); int rollAttack(); int brollDefend(int); std::string getCharacter(); int getArmor(); int getStrengthPoints(); void setStrengthPoints(int); }; #endif
true